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
4767751741b2f36f4f51dce7cfcd79dfa05ab819
327
dpr
Pascal
Samples/Delphi/VCL/Sport/TextResource/TextResource.dpr
atkins126/I18N
4176f8991b4c572ac36d8b2667dc345c185ff26f
[ "MIT" ]
43
2019-11-04T09:35:05.000Z
2022-02-28T00:01:46.000Z
Samples/Delphi/VCL/Sport/TextResource/TextResource.dpr
tomajexpress/I18N
2cb4161cb70645e62675925089b15e6ece9bd915
[ "MIT" ]
47
2020-01-16T18:13:31.000Z
2022-02-15T15:06:25.000Z
Samples/Delphi/VCL/Sport/TextResource/TextResource.dpr
tomajexpress/I18N
2cb4161cb70645e62675925089b15e6ece9bd915
[ "MIT" ]
20
2019-10-09T03:44:00.000Z
2022-02-28T00:01:48.000Z
program TextResource; {$R 'Sports.res' 'Sports.rc'} uses Vcl.Forms, Unit1 in 'Unit1.pas' {Form1}, SportFrm in '..\SportFrm.pas' {SportForm}, Sport in '..\Sport.pas'; {$R *.res} begin Application.Initialize; Application.MainFormOnTaskbar := True; Application.CreateForm(TForm1, Form1); Application.Run; end.
17.210526
44
0.688073
47dc9945f876f3ec7d94568eca09ff8091e17065
1,675
pas
Pascal
Libraries/GraphicsLib/dwsJPEGEncoderOptions.pas
synapsea/DW-Script
b36c2e57f0285c217f8f0cae8e4e158d21127163
[ "Condor-1.1" ]
1
2022-02-18T22:14:44.000Z
2022-02-18T22:14:44.000Z
Libraries/GraphicsLib/dwsJPEGEncoderOptions.pas
synapsea/DW-Script
b36c2e57f0285c217f8f0cae8e4e158d21127163
[ "Condor-1.1" ]
null
null
null
Libraries/GraphicsLib/dwsJPEGEncoderOptions.pas
synapsea/DW-Script
b36c2e57f0285c217f8f0cae8e4e158d21127163
[ "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. } { } { Based on WriteJPEG example from OpenGL24.de } { http://www.opengl24.de/header/libjpeg } { } { Further changes Copyright Creative IT. } { Current maintainer: Eric Grange } { } {**********************************************************************} unit dwsJPEGEncoderOptions; interface type TJPEGOption = ( jpgoOptimize, // optimize Huffman tables jpgoNoJFIFHeader, // don't write JFIF header jpgoProgressive // progressive JPEG ); TJPEGOptions = set of TJPEGOption; implementation end.
47.857143
72
0.407164
c348ac128dc52b0fbb3be196c2b266e7e36aba80
13,611
pas
Pascal
demo/generics/uContainers.pas
d-mozulyov/Tiny.Library
d79fb2b2e9a28bc273a509814c3fc9fe970e077c
[ "MIT" ]
54
2020-05-25T09:35:57.000Z
2021-12-29T03:12:06.000Z
demo/generics/uContainers.pas
d-mozulyov/Tiny.Rtti
d79fb2b2e9a28bc273a509814c3fc9fe970e077c
[ "MIT" ]
5
2019-10-07T01:34:58.000Z
2020-05-14T18:04:36.000Z
demo/generics/uContainers.pas
d-mozulyov/Tiny.Library
d79fb2b2e9a28bc273a509814c3fc9fe970e077c
[ "MIT" ]
7
2020-05-25T18:58:37.000Z
2021-10-15T08:39:15.000Z
unit uContainers; {$I TINY.DEFINES.inc} interface uses Winapi.Windows, System.SysUtils, Generics.Defaults, Generics.Collections, Tiny.Types, Tiny.Generics; type T = Integer; const ITEMS_COUNT = 1000000; var ITEMS: array[0..ITEMS_COUNT - 1] of T; type TTest = class public constructor Create; virtual; abstract; procedure FillContainer(const UseCapacity: Boolean); virtual; abstract; procedure Prepare; virtual; abstract; function Execute: T; virtual; abstract; class procedure Run(const IterationsCount: Integer); end; TTestClass = class of TTest; TSystemListTest = class(TTest) public List: Generics.Collections.TList<T>; constructor Create; override; destructor Destroy; override; procedure FillContainer(const UseCapacity: Boolean); override; procedure Prepare; override; end; TTinyListTest = class(TTest) public List: Tiny.Generics.TList<T>; constructor Create; override; destructor Destroy; override; procedure FillContainer(const UseCapacity: Boolean); override; procedure Prepare; override; end; TSystemStackTest = class(TTest) public Stack: Generics.Collections.TStack<T>; constructor Create; override; destructor Destroy; override; procedure FillContainer(const UseCapacity: Boolean); override; procedure Prepare; override; end; TTinyStackTest = class(TTest) public Stack: Tiny.Generics.TStack<T>; constructor Create; override; destructor Destroy; override; procedure FillContainer(const UseCapacity: Boolean); override; procedure Prepare; override; end; TSystemQueueTest = class(TTest) public Queue: Generics.Collections.TQueue<T>; constructor Create; override; destructor Destroy; override; procedure FillContainer(const UseCapacity: Boolean); override; procedure Prepare; override; end; TTinyQueueTest = class(TTest) public Queue: Tiny.Generics.TQueue<T>; constructor Create; override; destructor Destroy; override; procedure FillContainer(const UseCapacity: Boolean); override; procedure Prepare; override; end; SystemListAdd = class(TSystemListTest) procedure Prepare; override; function Execute: T; override; end; TinyListAdd = class(TTinyListTest) procedure Prepare; override; function Execute: T; override; end; SystemListAdd_Capacity = class(TSystemListTest) procedure Prepare; override; function Execute: T; override; end; TinyListAdd_Capacity = class(TTinyListTest) procedure Prepare; override; function Execute: T; override; end; SystemListItems = class(TSystemListTest) function Execute: T; override; end; TinyListItems = class(TTinyListTest) function Execute: T; override; end; SystemListDelete = class(TSystemListTest) function Execute: T; override; end; TinyListDelete = class(TTinyListTest) function Execute: T; override; end; SystemListIndexOf = class(TSystemListTest) function Execute: T; override; end; TinyListIndexOf = class(TTinyListTest) function Execute: T; override; end; SystemListReverse = class(TSystemListTest) constructor Create; override; procedure Prepare; override; function Execute: T; override; end; TinyListReverse = class(TTinyListTest) constructor Create; override; procedure Prepare; override; function Execute: T; override; end; SystemListPack = class(TSystemListTest) function Execute: T; override; end; TinyListPack = class(TTinyListTest) function Execute: T; override; end; SystemStackPush = class(TSystemStackTest) function Execute: T; override; end; TinyStackPush = class(TTinyStackTest) function Execute: T; override; end; SystemStackPush_Capacity = class(TSystemStackTest) function Execute: T; override; end; TinyStackPush_Capacity = class(TTinyStackTest) function Execute: T; override; end; SystemStackPop = class(TSystemStackTest) procedure Prepare; override; function Execute: T; override; end; TinyStackPop = class(TTinyStackTest) procedure Prepare; override; function Execute: T; override; end; SystemQueueEnqueue = class(TSystemQueueTest) function Execute: T; override; end; TinyQueueEnqueue = class(TTinyQueueTest) function Execute: T; override; end; SystemQueueEnqueue_Capacity = class(TSystemQueueTest) function Execute: T; override; end; TinyQueueEnqueue_Capacity = class(TTinyQueueTest) function Execute: T; override; end; SystemQueueDequeue = class(TSystemQueueTest) procedure Prepare; override; function Execute: T; override; end; TinyQueueDequeue = class(TTinyQueueTest) procedure Prepare; override; function Execute: T; override; end; procedure Run; implementation procedure FillItems; var i: Integer; begin RandSeed := 0; for i := Low(ITEMS) to High(ITEMS) do ITEMS[i] := 1 + Random(ITEMS_COUNT - 1); for i := 1 to 20 do ITEMS[Random(ITEMS_COUNT)] := Default(T); end; procedure InternalRun(const SystemTest, TinyTest: TTestClass; const IterationsCount: Integer); begin SystemTest.Run(IterationsCount); TinyTest.Run(IterationsCount); end; procedure Run; begin FillItems; InternalRun(SystemListAdd, TinyListAdd, 300); InternalRun(SystemListAdd_Capacity, TinyListAdd_Capacity, 300); InternalRun(SystemListItems, TinyListItems, 1000); InternalRun(SystemListDelete, TinyListDelete, 500); InternalRun(SystemListIndexOf, TinyListIndexOf, 1000); InternalRun(SystemListReverse, TinyListReverse, 8000); InternalRun(SystemListPack, TinyListPack, 500); InternalRun(SystemStackPush, TinyStackPush, 300); InternalRun(SystemStackPush_Capacity, TinyStackPush_Capacity, 300); InternalRun(SystemStackPop, TinyStackPop, 500); InternalRun(SystemQueueEnqueue, TinyQueueEnqueue, 300); InternalRun(SystemQueueEnqueue_Capacity, TinyQueueEnqueue_Capacity, 300); InternalRun(SystemQueueDequeue, TinyQueueDequeue, 500); end; { TTest } class procedure TTest.Run(const IterationsCount: Integer); var i: Integer; TotalTime, Time: Cardinal; Instance: TTest; begin Write(Self.ClassName, '... '); TotalTime := 0; Instance := Self.Create; try for i := 1 to IterationsCount do begin Instance.Prepare; Time := GetTickCount; Instance.Execute; Time := GetTickCount - Time; Inc(TotalTime, Time); end; finally Instance.Free; end; Writeln(TotalTime, 'ms'); end; { TSystemListTest } constructor TSystemListTest.Create; begin List := Generics.Collections.TList<T>.Create; end; destructor TSystemListTest.Destroy; begin List.Free; inherited; end; procedure TSystemListTest.FillContainer(const UseCapacity: Boolean); var i: Integer; begin List.Clear; if (UseCapacity) then List.Capacity := ITEMS_COUNT; for i := 0 to ITEMS_COUNT - 1 do List.Add(ITEMS[i]); end; procedure TSystemListTest.Prepare; begin FillContainer(True); end; { TTinyListTest } constructor TTinyListTest.Create; begin List := Tiny.Generics.TList<T>.Create; end; destructor TTinyListTest.Destroy; begin List.Free; inherited; end; procedure TTinyListTest.FillContainer(const UseCapacity: Boolean); var i: Integer; begin List.Clear; if (UseCapacity) then List.Capacity := ITEMS_COUNT; for i := 0 to ITEMS_COUNT - 1 do List.Add(ITEMS[i]); end; procedure TTinyListTest.Prepare; begin FillContainer(True); end; { TSystemStackTest } constructor TSystemStackTest.Create; begin Stack := Generics.Collections.TStack<T>.Create; end; destructor TSystemStackTest.Destroy; begin Stack.Free; inherited; end; procedure TSystemStackTest.FillContainer(const UseCapacity: Boolean); var i: Integer; begin Stack.Clear; if (UseCapacity) then Stack.Capacity := ITEMS_COUNT; for i := 0 to ITEMS_COUNT - 1 do Stack.Push(ITEMS[i]); end; procedure TSystemStackTest.Prepare; begin Stack.Clear; end; { TTinyStackTest } constructor TTinyStackTest.Create; begin Stack := Tiny.Generics.TStack<T>.Create; end; destructor TTinyStackTest.Destroy; begin Stack.Free; inherited; end; procedure TTinyStackTest.FillContainer(const UseCapacity: Boolean); var i: Integer; begin Stack.Clear; if (UseCapacity) then Stack.Capacity := ITEMS_COUNT; for i := 0 to ITEMS_COUNT - 1 do Stack.Push(ITEMS[i]); end; procedure TTinyStackTest.Prepare; begin Stack.Clear; end; { TSystemQueueTest } constructor TSystemQueueTest.Create; begin Queue := Generics.Collections.TQueue<T>.Create; end; destructor TSystemQueueTest.Destroy; begin Queue.Free; inherited; end; procedure TSystemQueueTest.FillContainer(const UseCapacity: Boolean); var i: Integer; begin Queue.Clear; if (UseCapacity) then Queue.Capacity := ITEMS_COUNT; for i := 0 to ITEMS_COUNT - 1 do Queue.Enqueue(ITEMS[i]); end; procedure TSystemQueueTest.Prepare; begin Queue.Clear; end; { TTinyQueueTest } constructor TTinyQueueTest.Create; begin Queue := Tiny.Generics.TQueue<T>.Create; end; destructor TTinyQueueTest.Destroy; begin Queue.Free; inherited; end; procedure TTinyQueueTest.FillContainer(const UseCapacity: Boolean); var i: Integer; begin Queue.Clear; if (UseCapacity) then Queue.Capacity := ITEMS_COUNT; for i := 0 to ITEMS_COUNT - 1 do Queue.Enqueue(ITEMS[i]); end; procedure TTinyQueueTest.Prepare; begin Queue.Clear; end; { SystemListAdd } procedure SystemListAdd.Prepare; begin List.Clear; end; function SystemListAdd.Execute: T; begin FillContainer(False); Result := Default(T); end; { TinyListAdd } procedure TinyListAdd.Prepare; begin List.Clear; end; function TinyListAdd.Execute: T; begin FillContainer(False); Result := Default(T); end; { SystemListAdd_Capacity } procedure SystemListAdd_Capacity.Prepare; begin List.Clear; end; function SystemListAdd_Capacity.Execute: T; begin FillContainer(True); Result := Default(T); end; { TinyListAdd_Capacity } procedure TinyListAdd_Capacity.Prepare; begin List.Clear; end; function TinyListAdd_Capacity.Execute: T; begin FillContainer(True); Result := Default(T); end; { SystemListItems } function SystemListItems.Execute: T; var i: Integer; begin for i := 0 to ITEMS_COUNT - 1 do Result := List[i]; end; { TinyListItems } function TinyListItems.Execute: T; var i: Integer; begin for i := 0 to ITEMS_COUNT - 1 do Result := List[i]; end; { SystemListDelete } function SystemListDelete.Execute: T; var i: Integer; begin for i := ITEMS_COUNT - 1 downto 0 do List.Delete(i); Result := Default(T); end; { TinyListDelete } function TinyListDelete.Execute: T; var i: Integer; begin for i := ITEMS_COUNT - 1 downto 0 do List.Delete(i); Result := Default(T); end; { SystemListIndexOf } function SystemListIndexOf.Execute: T; begin Result := List.IndexOf(Low(T)) end; { TinyListIndexOf } function TinyListIndexOf.Execute: T; begin Result := List.IndexOf(Low(T)) end; { SystemListReverse } constructor SystemListReverse.Create; begin inherited; FillContainer(True); end; procedure SystemListReverse.Prepare; begin end; function SystemListReverse.Execute: T; begin List.Reverse; Result := Default(T); end; { TinyListReverse } constructor TinyListReverse.Create; begin inherited; FillContainer(True); end; procedure TinyListReverse.Prepare; begin end; function TinyListReverse.Execute: T; begin List.Reverse; Result := Default(T); end; { SystemListPack } function SystemListPack.Execute: T; begin List.Pack; Result := Default(T); end; { TinyListPack } function TinyListPack.Execute: T; begin List.Pack; Result := Default(T); end; { SystemStackPush } function SystemStackPush.Execute: T; begin FillContainer(False); Result := Default(T); end; { TinyStackPush } function TinyStackPush.Execute: T; begin FillContainer(False); Result := Default(T); end; { SystemStackPush_Capacity } function SystemStackPush_Capacity.Execute: T; begin FillContainer(True); Result := Default(T); end; { TinyStackPush_Capacity } function TinyStackPush_Capacity.Execute: T; begin FillContainer(True); Result := Default(T); end; { SystemStackPop } procedure SystemStackPop.Prepare; begin FillContainer(True); end; function SystemStackPop.Execute: T; var i: Integer; begin for i := ITEMS_COUNT - 1 downto 0 do Result := Stack.Pop; end; { TinyStackPop } procedure TinyStackPop.Prepare; begin FillContainer(True); end; function TinyStackPop.Execute: T; var i: Integer; begin for i := ITEMS_COUNT - 1 downto 0 do Result := Stack.Pop; end; { SystemQueueEnqueue } function SystemQueueEnqueue.Execute: T; begin FillContainer(False); Result := Default(T); end; { TinyQueueEnqueue } function TinyQueueEnqueue.Execute: T; begin FillContainer(False); Result := Default(T); end; { SystemQueueEnqueue_Capacity } function SystemQueueEnqueue_Capacity.Execute: T; begin FillContainer(True); Result := Default(T); end; { TinyQueueEnqueue_Capacity } function TinyQueueEnqueue_Capacity.Execute: T; begin FillContainer(True); Result := Default(T); end; { SystemQueueDequeue } procedure SystemQueueDequeue.Prepare; begin FillContainer(True); end; function SystemQueueDequeue.Execute: T; var i: Integer; begin for i := ITEMS_COUNT - 1 downto 0 do Result := Queue.Dequeue; end; { TinyQueueDequeue } procedure TinyQueueDequeue.Prepare; begin FillContainer(True); end; function TinyQueueDequeue.Execute: T; var i: Integer; begin for i := ITEMS_COUNT - 1 downto 0 do Result := Queue.Dequeue; end; end.
18.318977
94
0.733157
c3052260cc193aa9ec8f44a07a96c90645f17ff7
15,302
pas
Pascal
hpdf_types.pas
r1me/THaruPDF
fa7221ca8593217dcfc3e32032fef47e14a8c509
[ "MIT" ]
21
2017-11-09T22:43:00.000Z
2021-09-17T18:20:44.000Z
hpdf_types.pas
CloudDelphi/THaruPDF
fa7221ca8593217dcfc3e32032fef47e14a8c509
[ "MIT" ]
4
2018-09-28T15:37:08.000Z
2022-03-16T20:58:54.000Z
hpdf_types.pas
r1me/THaruPDF
fa7221ca8593217dcfc3e32032fef47e14a8c509
[ "MIT" ]
6
2017-11-09T23:45:52.000Z
2021-05-09T20:10:42.000Z
{* * << Haru Free PDF Library >> -- hpdf_types.pas * * URL: http://libharu.org * * Copyright (c) 1999-2006 Takeshi Kanno <takeshi_kanno@est.hi-ho.ne.jp> * Copyright (c) 2007-2009 Antony Dovgal <tony@daylessday.org> * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. * It is provided "as is" without express or implied warranty. * *} unit hpdf_types; {$IFDEF FPC}{$MODE DELPHI}{$ENDIF} interface uses SysUtils; type {$Z+} {*----------------------------------------------------------------------------*} {*----- type definition ------------------------------------------------------*} {* native OS integer types *} HPDF_INT = Integer; HPDF_PINT = ^HPDF_INT; HPDF_UINT = Cardinal; HPDF_PUINT = ^Cardinal; {* 32bit integer types *} HPDF_INT32 = Longint; HPDF_UINT32 = Longword; HPDF_PUINT32 = ^Longword; {* 16bit integer types *} HPDF_INT16 = SmallInt; HPDF_UINT16 = Word; HPDF_PUINT16 = ^Word; {* 8bit integer types *} HPDF_INT8 = Shortint; HPDF_PINT8 = ^HPDF_INT8; HPDF_UINT8 = Byte; HPDF_PUINT8 = ^HPDF_UINT8; {* 8bit binary types *} HPDF_BYTE = Byte; HPDF_PBYTE = ^Byte; {* 8bit charactor types *} {$IFDEF FPC} UTF8Char = AnsiChar; {$ENDIF} HPDF_CHAR = UTF8Char; {* null terminated character *} {$IFDEF FPC} PUTF8Char = PAnsiChar; {$ENDIF} HPDF_PCHAR = PUTF8Char; {* float type (32bit IEEE754) *} HPDF_REAL = Single; HPDF_PREAL = ^HPDF_REAL; {* double type (64bit IEEE754) *} HPDF_DOUBLE = Double; {* boolean type (0: False, 1: True) *} HPDF_BOOL = Integer; {* error-no type (32bit unsigned integer) *} HPDF_STATUS = Cardinal; {* charactor-code type (16bit) *} HPDF_CID = HPDF_UINT16; HPDF_UNICODE = HPDF_UINT16; {* charactor-code type (32bit) *} HPDF_UCS4 = HPDF_UINT32; HPDF_CODE = HPDF_UINT32; {* HPDF_Point struct *} THPDF_Point = record x: HPDF_REAL; y: HPDF_REAL; end; PHPDF_Point = ^THPDF_Point; THPDF_Rect = record left: HPDF_REAL; bottom: HPDF_REAL; right: HPDF_REAL; top: HPDF_REAL; end; {* HPDF_Point3D struct *} THPDF_Point3D = record x: HPDF_REAL; y: HPDF_REAL; z: HPDF_REAL; end; THPDF_Box = THPDF_Rect; {* HPDF_Date struct *} THPDF_Date = record year: HPDF_INT; month: HPDF_INT; day: HPDF_INT; hour: HPDF_INT; minutes: HPDF_INT; seconds: HPDF_INT; ind: HPDF_CHAR; off_hour: HPDF_INT; off_minutes: HPDF_INT; end; THPDF_InfoType = ( HPDF_INFO_CREATION_DATE, HPDF_INFO_MOD_DATE, HPDF_INFO_AUTHOR, HPDF_INFO_CREATOR, HPDF_INFO_PRODUCER, HPDF_INFO_TITLE, HPDF_INFO_SUBJECT, HPDF_INFO_KEYWORDS, HPDF_INFO_TRAPPED, HPDF_INFO_GTS_PDFX, HPDF_INFO_EOF ); {* PDF-A Types *} THPDF_PDFA_TYPE = ( HPDF_PDFA_1A = 0, HPDF_PDFA_1B = 1 ); THPDF_PdfVer = ( HPDF_VER_12 = 0, HPDF_VER_13, HPDF_VER_14, HPDF_VER_15, HPDF_VER_16, HPDF_VER_17, HPDF_VER_EOF ); THPDF_EncryptMode = ( HPDF_ENCRYPT_R2 = 2, HPDF_ENCRYPT_R3 = 3 ); THPDF_Error_Handler = procedure (error_no: HPDF_STATUS; detail_no: HPDF_STATUS; user_data: Pointer); {$IFDEF Linux}cdecl{$ELSE}stdcall{$ENDIF}; THPDF_Alloc_Func = procedure (size: HPDF_UINT); {$IFDEF Linux}cdecl{$ELSE}stdcall{$ENDIF}; THPDF_Free_Func = procedure (aptr: Pointer); {$IFDEF Linux}cdecl{$ELSE}stdcall{$ENDIF}; {*---------------------------------------------------------------------------*} {*------ text width struct --------------------------------------------------*} THPDF_TextWidth = record numchars: HPDF_UINT; numwords: HPDF_UINT; {* don't use this value. *} width: HPDF_UINT; numspace: HPDF_UINT; end; THPDF_TextLineWidth = record flags: HPDF_UINT16; linebytes: HPDF_UINT16; numbytes: HPDF_UINT16; numchars: HPDF_UINT16; numspaces: HPDF_UINT16; numtatweels: HPDF_UINT16; charswidth: HPDF_UINT; width: HPDF_REAL; end; {*---------------------------------------------------------------------------*} {*------ dash mode ----------------------------------------------------------*} THPDF_DashMode = record ptn: array[0..7] of HPDF_REAL; num_ptn: HPDF_UINT16; phase: HPDF_REAL; end; {*---------------------------------------------------------------------------*} {*----- HPDF_TransMatrix struct ---------------------------------------------*} THPDF_TransMatrix = record a: HPDF_REAL; b: HPDF_REAL; c: HPDF_REAL; d: HPDF_REAL; x: HPDF_REAL; y: HPDF_REAL; constructor Create(Aa, Ab, Ac, Ad, Ax, Ay: HPDF_REAL); end; {*---------------------------------------------------------------------------*} {*----- HPDF_3DMatrix struct ------------------------------------------------*} THPDF_3DMatrix = record a: HPDF_REAL; b: HPDF_REAL; c: HPDF_REAL; d: HPDF_REAL; e: HPDF_REAL; f: HPDF_REAL; g: HPDF_REAL; h: HPDF_REAL; i: HPDF_REAL; tx: HPDF_REAL; ty: HPDF_REAL; tz: HPDF_REAL; end; {*---------------------------------------------------------------------------*} THPDF_ColorSpace = ( HPDF_CS_DEVICE_GRAY, HPDF_CS_DEVICE_RGB, HPDF_CS_DEVICE_CMYK, HPDF_CS_CAL_GRAY, HPDF_CS_CAL_RGB, HPDF_CS_LAB, HPDF_CS_ICC_BASED, HPDF_CS_SEPARATION, HPDF_CS_DEVICE_N, HPDF_CS_INDEXED, HPDF_CS_PATTERN, HPDF_CS_EOF ); {*---------------------------------------------------------------------------*} {*----- HPDF_RGBColor struct ------------------------------------------------*} THPDF_RGBColor = record r: HPDF_REAL; g: HPDF_REAL; b: HPDF_REAL; constructor Create(Ar, Ag, Ab: HPDF_REAL); end; {*---------------------------------------------------------------------------*} {*----- HPDF_CMYKColor struct -----------------------------------------------*} THPDF_CMYKColor = record c: HPDF_REAL; m: HPDF_REAL; y: HPDF_REAL; k: HPDF_REAL; constructor Create(Ac, Am, Ay, Ak: HPDF_REAL); end; {*---------------------------------------------------------------------------*} {*------ The line cap style -------------------------------------------------*} THPDF_LineCap = ( HPDF_BUTT_END, HPDF_ROUND_END, HPDF_PROJECTING_SQUARE_END, HPDF_LINECAP_EOF ); {*----------------------------------------------------------------------------*} {*------ The line join style -------------------------------------------------*} THPDF_LineJoin = ( HPDF_MITER_JOIN, HPDF_ROUND_JOIN, HPDF_BEVEL_JOIN ); {*----------------------------------------------------------------------------*} {*------ The text rendering mode ---------------------------------------------*} THPDF_TextRenderingMode = ( HPDF_FILL, HPDF_STROKE, HPDF_FILL_THEN_STROKE, HPDF_INVISIBLE, HPDF_FILL_CLIPPING, HPDF_STROKE_CLIPPING, HPDF_FILL_STROKE_CLIPPING, HPDF_CLIPPING, HPDF_RENDERING_MODE_EOF ); THPDF_WritingMode = ( HPDF_WMODE_HORIZONTAL, HPDF_WMODE_VERTICAL, HPDF_WMODE_SIDEWAYS, {* gstate only *} HPDF_WMODE_MIXED, {* gstate only *} HPDF_WMODE_EOF ); THPDF_PageLayout = ( HPDF_PAGE_LAYOUT_SINGLE, HPDF_PAGE_LAYOUT_ONE_COLUMN, HPDF_PAGE_LAYOUT_TWO_COLUMN_LEFT, HPDF_PAGE_LAYOUT_TWO_COLUMN_RIGHT, HPDF_PAGE_LAYOUT_TWO_PAGE_LEFT, HPDF_PAGE_LAYOUT_TWO_PAGE_RIGHT, HPDF_PAGE_LAYOUT_EOF ); THPDF_PageMode = ( HPDF_PAGE_MODE_USE_NONE, HPDF_PAGE_MODE_USE_OUTLINE, HPDF_PAGE_MODE_USE_THUMBS, HPDF_PAGE_MODE_FULL_SCREEN, {* HPDF_PAGE_MODE_USE_OC, HPDF_PAGE_MODE_USE_ATTACHMENTS *} HPDF_PAGE_MODE_EOF ); THPDF_PageNumStyle = ( HPDF_PAGE_NUM_STYLE_DECIMAL, HPDF_PAGE_NUM_STYLE_UPPER_ROMAN, HPDF_PAGE_NUM_STYLE_LOWER_ROMAN, HPDF_PAGE_NUM_STYLE_UPPER_LETTERS, HPDF_PAGE_NUM_STYLE_LOWER_LETTERS, HPDF_PAGE_NUM_STYLE_EOF ); THPDF_DestinationType = ( HPDF_XYZ, HPDF_FIT, HPDF_FIT_H, HPDF_FIT_V, HPDF_FIT_R, HPDF_FIT_B, HPDF_FIT_BH, HPDF_FIT_BV, HPDF_DST_EOF ); THPDF_AnnotType = ( HPDF_ANNOT_TEXT_NOTES, HPDF_ANNOT_LINK, HPDF_ANNOT_SOUND, HPDF_ANNOT_FREE_TEXT, HPDF_ANNOT_STAMP, HPDF_ANNOT_SQUARE, HPDF_ANNOT_CIRCLE, HPDF_ANNOT_STRIKE_OUT, HPDF_ANNOT_HIGHTLIGHT, HPDF_ANNOT_UNDERLINE, HPDF_ANNOT_INK, HPDF_ANNOT_FILE_ATTACHMENT, HPDF_ANNOT_POPUP, HPDF_ANNOT_3D, HPDF_ANNOT_SQUIGGLY, HPDF_ANNOT_LINE, HPDF_ANNOT_PROJECTION, HPDF_ANNOT_WIDGET ); THPDF_AnnotFlgs = ( HPDF_ANNOT_INVISIBLE, HPDF_ANNOT_HIDDEN, HPDF_ANNOT_PRINT, HPDF_ANNOT_NOZOOM, HPDF_ANNOT_NOROTATE, HPDF_ANNOT_NOVIEW, HPDF_ANNOT_READONLY ); THPDF_AnnotHighlightMode = ( HPDF_ANNOT_NO_HIGHLIGHT, HPDF_ANNOT_INVERT_BOX, HPDF_ANNOT_INVERT_BORDER, HPDF_ANNOT_DOWN_APPEARANCE, HPDF_ANNOT_HIGHTLIGHT_MODE_EOF ); THPDF_AnnotIcon = ( HPDF_ANNOT_ICON_COMMENT, HPDF_ANNOT_ICON_KEY, HPDF_ANNOT_ICON_NOTE, HPDF_ANNOT_ICON_HELP, HPDF_ANNOT_ICON_NEW_PARAGRAPH, HPDF_ANNOT_ICON_PARAGRAPH, HPDF_ANNOT_ICON_INSERT, HPDF_ANNOT_ICON_EOF ); THPDF_AnnotIntent = ( HPDF_ANNOT_INTENT_FREETEXTCALLOUT, HPDF_ANNOT_INTENT_FREETEXTTYPEWRITER, HPDF_ANNOT_INTENT_LINEARROW, HPDF_ANNOT_INTENT_LINEDIMENSION, HPDF_ANNOT_INTENT_POLYGONCLOUD, HPDF_ANNOT_INTENT_POLYLINEDIMENSION, HPDF_ANNOT_INTENT_POLYGONDIMENSION ); THPDF_LineAnnotEndingStyle = ( HPDF_LINE_ANNOT_NONE, HPDF_LINE_ANNOT_SQUARE, HPDF_LINE_ANNOT_CIRCLE, HPDF_LINE_ANNOT_DIAMOND, HPDF_LINE_ANNOT_OPENARROW, HPDF_LINE_ANNOT_CLOSEDARROW, HPDF_LINE_ANNOT_BUTT, HPDF_LINE_ANNOT_ROPENARROW, HPDF_LINE_ANNOT_RCLOSEDARROW, HPDF_LINE_ANNOT_SLASH ); THPDF_LineAnnotCapPosition = ( HPDF_LINE_ANNOT_CAP_INLINE, HPDF_LINE_ANNOT_CAP_TOP ); THPDF_StampAnnotName = ( HPDF_STAMP_ANNOT_APPROVED, HPDF_STAMP_ANNOT_EXPERIMENTAL, HPDF_STAMP_ANNOT_NOTAPPROVED, HPDF_STAMP_ANNOT_ASIS, HPDF_STAMP_ANNOT_EXPIRED, HPDF_STAMP_ANNOT_NOTFORPUBLICRELEASE, HPDF_STAMP_ANNOT_CONFIDENTIAL, HPDF_STAMP_ANNOT_FINAL, HPDF_STAMP_ANNOT_SOLD, HPDF_STAMP_ANNOT_DEPARTMENTAL, HPDF_STAMP_ANNOT_FORCOMMENT, HPDF_STAMP_ANNOT_TOPSECRET, HPDF_STAMP_ANNOT_DRAFT, HPDF_STAMP_ANNOT_FORPUBLICRELEASE ); {*----------------------------------------------------------------------------*} {*------ border stype --------------------------------------------------------*} THPDF_BSSubtype = ( HPDF_BS_SOLID, HPDF_BS_DASHED, HPDF_BS_BEVELED, HPDF_BS_INSET, HPDF_BS_UNDERLINED ); {*----- blend modes ----------------------------------------------------------*} THPDF_BlendMode = ( HPDF_BM_NORMAL, HPDF_BM_MULTIPLY, HPDF_BM_SCREEN, HPDF_BM_OVERLAY, HPDF_BM_DARKEN, HPDF_BM_LIGHTEN, HPDF_BM_COLOR_DODGE, HPDF_BM_COLOR_BUM, HPDF_BM_HARD_LIGHT, HPDF_BM_SOFT_LIGHT, HPDF_BM_DIFFERENCE, HPDF_BM_EXCLUSHON, HPDF_BM_EOF ); {*----- slide show -----------------------------------------------------------*} THPDF_TransitionStyle = ( HPDF_TS_WIPE_RIGHT, HPDF_TS_WIPE_UP, HPDF_TS_WIPE_LEFT, HPDF_TS_WIPE_DOWN, HPDF_TS_BARN_DOORS_HORIZONTAL_OUT, HPDF_TS_BARN_DOORS_HORIZONTAL_IN, HPDF_TS_BARN_DOORS_VERTICAL_OUT, HPDF_TS_BARN_DOORS_VERTICAL_IN, HPDF_TS_BOX_OUT, HPDF_TS_BOX_IN, HPDF_TS_BLINDS_HORIZONTAL, HPDF_TS_BLINDS_VERTICAL, HPDF_TS_DISSOLVE, HPDF_TS_GLITTER_RIGHT, HPDF_TS_GLITTER_DOWN, HPDF_TS_GLITTER_TOP_LEFT_TO_BOTTOM_RIGHT, HPDF_TS_REPLACE, HPDF_TS_EOF ); {*----------------------------------------------------------------------------*} THPDF_PageSizes = ( HPDF_PAGE_SIZE_LETTER, HPDF_PAGE_SIZE_LEGAL, HPDF_PAGE_SIZE_A3, HPDF_PAGE_SIZE_A4, HPDF_PAGE_SIZE_A5, HPDF_PAGE_SIZE_B5, HPDF_PAGE_SIZE_EXECUTIVE, HPDF_PAGE_SIZE_US4x6, HPDF_PAGE_SIZE_US4x8, HPDF_PAGE_SIZE_US5x7, HPDF_PAGE_SIZE_COMM10, HPDF_PAGE_SIZE_EOF ); THPDF_PageDirection = ( HPDF_PAGE_PORTRAIT, HPDF_PAGE_LANDSCAPE ); THPDF_PageBoundary = ( HPDF_PAGE_MEDIABOX = 0, HPDF_PAGE_CROPBOX, HPDF_PAGE_BLEEDBOX, HPDF_PAGE_TRIMBOX, HPDF_PAGE_ARTBOX ); THPDF_EncoderType = ( HPDF_ENCODER_TYPE_SINGLE_BYTE, HPDF_ENCODER_TYPE_MULTI_BYTE, {* obsoleted *} HPDF_ENCODER_TYPE_DOUBLE_BYTE = HPDF_ENCODER_TYPE_MULTI_BYTE, HPDF_ENCODER_TYPE_UNINITIALIZED, HPDF_ENCODER_UNKNOWN ); THPDF_ByteType = ( HPDF_BYTE_TYPE_SINGLE, HPDF_BYTE_TYPE_LEAD, HPDF_BYTE_TYPE_TRIAL, HPDF_BYTE_TYPE_UNKNOWN ); {*----------------------------------------------------------------------------*} {* Name Dictionary values -- see PDF reference section 7.7.4 *} THPDF_NameDictKey = ( HPDF_NAME_EMBEDDED_FILES = 0, {* TODO the rest *} HPDF_NAME_EOF ); {*----------------------------------------------------------------------------*} {*----- text converter -------------------------------------------------------*} THPDF_CharEnc = ( HPDF_CHARENC_UNSUPPORTED = 0, HPDF_CHARENC_UTF8, HPDF_CHARENC_UTF16BE, HPDF_CHARENC_UTF32BE, HPDF_CHARENC_UTF16LE, HPDF_CHARENC_UTF32LE, HPDF_CHARENC_UNICODE, {* UTF16 native endian *} HPDF_CHARENC_UCS4, {* UTF32 native endian *} HPDF_CHARENC_WCHAR_T, {* UNICODE or UCS4 *} HPDF_CHARENC_EOF ); HPDF_Converter = ^THPDF_Converter_Rec; THPDF_Converter_New_Func = function (alloc_fn: THPDF_Alloc_Func; free_fn: THPDF_Free_Func; param: Pointer): HPDF_Converter; {$IFDEF Linux}cdecl{$ELSE}stdcall{$ENDIF}; THPDF_Converter_Convert_Func = function (converter: HPDF_Converter; flags: HPDF_UINT32; const src: HPDF_PBYTE; src_bytes: HPDF_UINT; dst: HPDF_PBYTE): HPDF_UINT; {$IFDEF Linux}cdecl{$ELSE}stdcall{$ENDIF}; THPDF_Converter_Delete_Func = function (converter: HPDF_Converter; free_fn: THPDF_Free_Func): HPDF_Converter; {$IFDEF Linux}cdecl{$ELSE}stdcall{$ENDIF}; THPDF_Converter_Rec = record convert_fn: THPDF_Converter_Convert_Func; delete_fn: THPDF_Converter_Delete_Func; src_charenc: THPDF_CharEnc; dst_charenc: THPDF_CharEnc; bytes_factor: HPDF_UINT; chars_factor: HPDF_UINT; end; THPDF_ConverterBiDi_Param_Rec = record max_chars: HPDF_UINT32; base_dir: HPDF_UINT32; bidi_types: HPDF_PUINT32; ar_props: HPDF_PUINT8; embedding_levels: HPDF_PINT8; positions_L_to_V: HPDF_PINT; positions_V_to_L: HPDF_PINT; end; {$Z-} implementation constructor THPDF_TransMatrix.Create(Aa, Ab, Ac, Ad, Ax, Ay: HPDF_REAL); begin a := Aa; b := Ab; c := Ac; d := Ad; x := Ax; y := Ay; end; constructor THPDF_RGBColor.Create(Ar, Ag, Ab: HPDF_REAL); begin r := Ar; g := Ag; b := Ab; end; constructor THPDF_CMYKColor.Create(Ac, Am, Ay, Ak: HPDF_REAL); begin c := Ac; m := Am; y := Ay; k := Ak; end; end.
22.4041
120
0.612338
c35d0e4cb9227c26c37a732427908a2f763b9e7a
27,910
pas
Pascal
source/uidefs.pas
lysee/lysee
2300e9a2d8c190b15bc07e9b2e85f018b016feae
[ "BSD-3-Clause" ]
15
2017-03-03T22:32:51.000Z
2022-02-04T11:11:56.000Z
source/uidefs.pas
lysee/lysee
2300e9a2d8c190b15bc07e9b2e85f018b016feae
[ "BSD-3-Clause" ]
null
null
null
source/uidefs.pas
lysee/lysee
2300e9a2d8c190b15bc07e9b2e85f018b016feae
[ "BSD-3-Clause" ]
6
2017-04-15T14:53:28.000Z
2022-01-03T05:33:53.000Z
unit UIDefs; {$IFDEF FPC} {$MODE objfpc}{$H+} {$ENDIF} interface uses {$IFDEF FPC}LCLType, LCLIntf,{$ELSE}Windows, Messages,{$ENDIF} SysUtils, Classes, Controls, Graphics, StdCtrls, ExtCtrls, Forms; const COLOR_TEXT = clWindowText; COLOR_BACKGROUND = clWindow; COLOR_SELECTEDTEXT = clWindow; COLOR_SELECTEDBACKGROUND = $694D00; // clBlue; { tokens } TK_SPACE = 0; TK_KEYWORD = 1; TK_ID = 2; TK_OPERATOR = 3; TK_DELIMITER = 4; TK_NUMBER = 5; // $... or [0-9]... TK_ENUMBER = 6; TK_CHAR = 7; // #... or #$... or '.' TK_ECHAR = 8; TK_STRING = 9; // "..." or '...' TK_ESTRING = 10; TK_COMMENT = 11; // {...} or (*...*) or /*...*/ or //... TK_ECOMMENT = 12; // {... or /*... TK_ECOMMENTP = 13; // (*... TK_DIRECTIVE = 14; // {$...} TK_EDIRECTIVE = 15; // {$... TK_BOOL = 16; TK_TAG = 17; TK_MARK = 18; TK_HILIGHT = 19; TK_RAWDATA = 20; TK_UNKNOWN = 21; TK_CUSTOM = 100; // start your tokens here { Font Style} FontStyleName: array[TFontStyle] of string = ( 'bold', 'italic', 'underline', 'strikeOut'); type TLyKeyDown = class;{forward} TLyHorzAlign = (haLeft, haCenter, haRight); TLyVertAlign = (vaTop, vaMiddle, vaBottom); TLyTokenID = smallint; { TLyPalette } TLyPalette = class private FTextColor: TColor; FBackground: TColor; FSelectedTextColor: TColor; FSelectedBackground: TColor; FLeftBarBackground: TColor; FChangedBackground: TColor; FActiveBackground: TColor; FCaretColor: TColor; FLine80Color: TColor; FLineMarkBackground: TColor; { token color } FUnknownColor: TColor; FKeywordColor: TColor; FIDColor: TColor; FIDStyle: TFontStyles; FSpaceColor: TColor; FOperatorColor: TColor; FDelimiterColor: TColor; FNumberColor: TColor; FENumberColor: TColor; FCharColor: TColor; FECharColor: TColor; FStringColor: TColor; FEStringColor: TColor; FBoolColor: TColor; FCommentColor: TColor; FECommentColor: TColor; FECommentPColor: TColor; FDirectiveColor: TColor; FEDirectiveColor: TColor; FTagColor: TColor; FMarkColor: TColor; FHilightColor: TColor; FRawDataColor: TColor; { token style } FUnknownStyle: TFontStyles; FKeywordStyle: TFontStyles; FSpaceStyle: TFontStyles; FOperatorStyle: TFontStyles; FDelimiterStyle: TFontStyles; FNumberStyle: TFontStyles; FENumberStyle: TFontStyles; FCharStyle: TFontStyles; FECharStyle: TFontStyles; FStringStyle: TFontStyles; FEStringStyle: TFontStyles; FBoolStyle: TFontStyles; FCommentStyle: TFontStyles; FECommentStyle: TFontStyles; FECommentPStyle: TFontStyles; FDirectiveStyle: TFontStyles; FEDirectiveStyle: TFontStyles; FTagStyle: TFontStyles; FMarkStyle: TFontStyles; FHilightStyle: TFontStyles; FRawDataStyle: TFontStyles; public constructor Create;virtual; function Apply(Font: TFont; Token: TLyTokenID; Selected: boolean): boolean;virtual; function GetStyle(Token: TLyTokenID): TFontStyles;virtual; function GetColor(Token: TLyTokenID): TColor;virtual; property TextColor: TColor read FTextColor write FTextColor; property Background: TColor read FBackground write FBackground; property SelectedTextColor: TColor read FSelectedTextColor write FSelectedTextColor; property SelectedBackground: TColor read FSelectedBackground write FSelectedBackground; { codeedit } property LeftBarBackground: TColor read FLeftBarBackground write FLeftBarBackground; property ChangedBackground: TColor read FChangedBackground write FChangedBackground; property ActiveBackground: TColor read FActiveBackground write FActiveBackground; property CaretColor: TColor read FCaretColor write FCaretColor; property Line80Color: TColor read FLine80Color write FLine80Color; property LineMarkBackground: TColor read FLineMarkBackground write FLineMarkBackground; { token color } property UnknownColor: TColor read FUnknownColor write FUnknownColor; property KeywordColor: TColor read FKeywordColor write FKeywordColor; property IDColor: TColor read FIDColor write FIDColor; property SpaceColor: TColor read FSpaceColor write FSpaceColor; property OperatorColor: TColor read FOperatorColor write FOperatorColor; property DelimiterColor: TColor read FDelimiterColor write FDelimiterColor; property NumberColor: TColor read FNumberColor write FNumberColor; property ENumberColor: TColor read FENumberColor write FENumberColor; property CharColor: TColor read FCharColor write FCharColor; property ECharColor: TColor read FECharColor write FECharColor; property StringColor: TColor read FStringColor write FStringColor; property EStringColor: TColor read FEStringColor write FEStringColor; property BoolColor: TColor read FBoolColor write FBoolColor; property CommentColor: TColor read FCommentColor write FCommentColor; property ECommentColor: TColor read FECommentColor write FECommentColor; property ECommentPColor: TColor read FECommentPColor write FECommentPColor; property DirectiveColor: TColor read FDirectiveColor write FDirectiveColor; property EDirectiveColor: TColor read FEDirectiveColor write FEDirectiveColor; property TagColor: TColor read FTagColor write FTagColor; property MarkColor: TColor read FMarkColor write FMarkColor; property HilightColor: TColor read FHilightColor write FHilightColor; property RawDataColor: TColor read FRawDataColor write FRawDataColor; { token style } property UnknownStyle: TFontStyles read FUnknownStyle write FUnknownStyle; property KeywordStyle: TFontStyles read FKeywordStyle write FKeywordStyle; property IDStyle: TFontStyles read FIDStyle write FIDStyle; property SpaceStyle: TFontStyles read FSpaceStyle write FSpaceStyle; property OperatorStyle: TFontStyles read FOperatorStyle write FOperatorStyle; property DelimiterStyle: TFontStyles read FDelimiterStyle write FDelimiterStyle; property NumberStyle: TFontStyles read FNumberStyle write FNumberStyle; property ENumberStyle: TFontStyles read FENumberStyle write FENumberStyle; property CharStyle: TFontStyles read FCharStyle write FCharStyle; property ECharStyle: TFontStyles read FECharStyle write FECharStyle; property StringStyle: TFontStyles read FStringStyle write FStringStyle; property EStringStyle: TFontStyles read FEStringStyle write FEStringStyle; property BoolStyle: TFontStyles read FBoolStyle write FBoolStyle; property CommentStyle: TFontStyles read FCommentStyle write FCommentStyle; property ECommentStyle: TFontStyles read FECommentStyle write FECommentStyle; property ECommentPStyle: TFontStyles read FECommentPStyle write FECommentPStyle; property DirectiveStyle: TFontStyles read FDirectiveStyle write FDirectiveStyle; property EDirectiveStyle: TFontStyles read FEDirectiveStyle write FEDirectiveStyle; property TagStyle: TFontStyles read FTagStyle write FTagStyle; property MarkStyle: TFontStyles read FMarkStyle write FMarkStyle; property HilightStyle: TFontStyles read FHilightStyle write FHilightStyle; property RawDataStyle: TFontStyles read FRawDataStyle write FRawDataStyle; end; { TLyKeyShift } TLyKeyEvent = procedure(Sender: TObject; Shift: TShiftState) of object; TLyKeyShift = class private FOwner: TLyKeyDown; FKey: Word; FShift: TShiftState; FHandler: TLyKeyEvent; FNext: TLyKeyShift; protected procedure Enter(AOwner: TLyKeyDown); procedure Leave; public constructor Create(AOwner: TLyKeyDown);virtual; destructor Destroy;override; property Owner: TLyKeyDown read FOwner write Enter; property Key: Word read FKey write FKey; property Shift: TShiftState read FShift write FShift; property Handler: TLyKeyEvent read FHandler write FHandler; end; { TLyKeyDown } TLyKeyDown = class private FOwner: TObject; FFirst: TLyKeyShift; public constructor Create(AOwner: TObject);virtual; destructor Destroy;override; function Add(Key: Word; Shift: TShiftState; Handler: TLyKeyEvent): TLyKeyShift; function Find(Key: Word; Shift: TShiftState): TLyKeyShift; function Process(Sender: TObject; Key: Word; Shift: TShiftState): boolean; property Owner: TObject read FOwner write FOwner; end; function Palette: TLyPalette; function TokenSetCanvas(Canvas: TCanvas; Token: TLyTokenID; Selected: boolean): boolean;overload; function TokenSetCanvas(Canvas: TCanvas; Token: TLyTokenID): boolean;overload; function TokenSetFont(Font: TFont; Token: TLyTokenID; Selected: boolean): boolean;overload; function TokenSetFont(Font: TFont; Token: TLyTokenID): boolean;overload; function TokenColor(Token: TLyTokenID): TColor; function TokenSelectedColor(Token: TLyTokenID): TColor; function TokenStyle(Token: TLyTokenID): TFontStyles; { font } function FontStyleToStr(AStyle: TFontStyles): string; function StrToFontStyle(const AStr: string): TFontStyles; { color } function IDToColor(const ID: string; var Color: TColor): boolean; function ColorToID(Color: TColor): string; { screen } function ScreenWidth(MM: currency): integer; function ScreenHeight(MM: currency): integer; { shortcut } function StrToShortCut(const AStr: string): TShortCut; implementation uses UITypes, Menus; var my_palette: TLyPalette; function Palette: TLyPalette; begin if my_palette = nil then my_palette := TLyPalette.Create; Result := my_palette; end; function TokenSetCanvas(Canvas: TCanvas; Token: TLyTokenID; Selected: boolean): boolean; begin Result := Palette.Apply(Canvas.Font, Token, Selected); end; function TokenSetCanvas(Canvas: TCanvas; Token: TLyTokenID): boolean; begin Result := Palette.Apply(Canvas.Font, Token, false); end; function TokenSetFont(Font: TFont; Token: TLyTokenID; Selected: boolean): boolean; begin Result := Palette.Apply(Font, Token, Selected); end; function TokenSetFont(Font: TFont; Token: TLyTokenID): boolean; begin Result := Palette.Apply(Font, Token, false); end; function TokenColor(Token: TLyTokenID): TColor; begin Result := Palette.GetColor(Token); end; function TokenSelectedColor(Token: TLyTokenID): TColor; begin Result := Palette.SelectedTextColor; end; function TokenStyle(Token: TLyTokenID): TFontStyles; begin Result := Palette.GetStyle(Token); end; function FontStyleToStr(AStyle: TFontStyles): string; var I: TFontStyle; begin Result := ''; for I := Low(TFontStyle) to High(TFontStyle) do if I in AStyle then if Result <> '' then Result := Result + ' ' + FontStyleName[I] else Result := FontStyleName[I]; end; function StrToFontStyle(const AStr: string): TFontStyles; var I: TFontStyle; S: string; begin Result := []; S := LowerCase(AStr); for I := Low(TFontStyle) to High(TFontStyle) do if Pos(FontStyleName[I], S) > 0 then Result := Result + [I]; end; const color_map: array [0..146] of TIdentMapEntry = ( //(Value: integer($BBGGRR); Name: 'color'), (Value: integer($FFF8F0); Name: 'Aliceblue'), (Value: integer($D7EBFA); Name: 'Antiquewhite'), (Value: integer(clAqua); Name: 'Aqua'), (Value: integer($D4FF7F); Name: 'Aquamarine'), (Value: integer($FFFFF0); Name: 'Azure'), (Value: integer($DCF5F5); Name: 'Beige'), (Value: integer($C4E4FF); Name: 'Bisque'), (Value: integer(clBlack); Name: 'Black'; ), (Value: integer($CDEBFF); Name: 'Blanchedalmond'), (Value: integer(clBlue); Name: 'Blue'), (Value: integer($E22B8A); Name: 'Blueviolet'), (Value: integer($2A2AA5); Name: 'Brown'), (Value: integer($87B8DE); Name: 'Burlywood'), (Value: integer($A09E5F); Name: 'Cadetblue'), (Value: integer($00FF7F); Name: 'Chartreuse'), (Value: integer($1E69D2); Name: 'Chocolate'), (Value: integer($507FFF); Name: 'Coral'), (Value: integer($ED9564); Name: 'Cornflowerblue'), (Value: integer($DCF8FF); Name: 'Cornsilk'), (Value: integer($3C14DC); Name: 'Crimson'), (Value: integer($FFFF00); Name: 'Cyan'), (Value: integer($8B0000); Name: 'Darkblue'), (Value: integer($8B8B00); Name: 'Darkcyan'), (Value: integer($0B86B8); Name: 'Darkgoldenrod'), (Value: integer(clDkGray); Name: 'Darkgray'), (Value: integer($006400); Name: 'Darkgreen'), (Value: integer($A9A9A9); Name: 'Darkgrey'), (Value: integer($6BB7BD); Name: 'Darkkhaki'), (Value: integer($8B008B); Name: 'Darkmagenta'), (Value: integer($2F6B55); Name: 'Darkolivegreen'), (Value: integer($008CFF); Name: 'Darkorange'), (Value: integer($CC3299); Name: 'Darkorchid'), (Value: integer($00008B); Name: 'Darkred'), (Value: integer($7A96E9); Name: 'Darksalmon'), (Value: integer($8FBC8F); Name: 'Darkseagreen'), (Value: integer($8B3D48); Name: 'Darkslateblue'), (Value: integer($4F4F2F); Name: 'Darkslategray'), (Value: integer($4F4F2F); Name: 'Darkslategrey'), (Value: integer($D1CE00); Name: 'Darkturquoise'), (Value: integer($D30094); Name: 'Darkviolet'), (Value: integer($9314FF); Name: 'Deeppink'), (Value: integer($FFBF00); Name: 'Deepskyblue'), (Value: integer($696969); Name: 'Dimgray'), (Value: integer($696969); Name: 'Dimgrey'), (Value: integer($FF901E); Name: 'Dodgerblue'), (Value: integer($2222B2); Name: 'Firebrick'), (Value: integer($F0FAFF); Name: 'Floralwhite'), (Value: integer($228B22); Name: 'Forestgreen'), (Value: integer(clFuchsia); Name: 'Fuchsia'), (Value: integer($DCDCDC); Name: 'Gainsboro'), (Value: integer($FFF8F8); Name: 'Ghostwhite'), (Value: integer($00D7FF); Name: 'Gold'), (Value: integer($20A5DA); Name: 'Goldenrod'), (Value: integer(clGray); Name: 'Gray'), (Value: integer(clGreen); Name: 'Green'), (Value: integer($2FFFAD); Name: 'Greenyellow'), (Value: integer($808080); Name: 'Grey'), (Value: integer($F0FFF0); Name: 'Honeydew'), (Value: integer($B469FF); Name: 'Hotpink'), (Value: integer($5C5CCD); Name: 'Indianred'), (Value: integer($82004B); Name: 'Indigo'), (Value: integer($F0FFFF); Name: 'Ivory'), (Value: integer($8CE6F0); Name: 'Khaki'), (Value: integer($FAE6E6); Name: 'Lavender'), (Value: integer($F5F0FF); Name: 'Lavenderblush'), (Value: integer($00FC7C); Name: 'Lawngreen'), (Value: integer($CDFAFF); Name: 'Lemonchiffon'), (Value: integer($E6D8AD); Name: 'Lightblue'), (Value: integer($8080F0); Name: 'Lightcoral'), (Value: integer($FFFFE0); Name: 'Lightcyan'), (Value: integer($D2FAFA); Name: 'Lightgoldenrodyellow'), (Value: integer(clLtGray); Name: 'Lightgray'), (Value: integer($90EE90); Name: 'Lightgreen'), (Value: integer($D3D3D3); Name: 'Lightgrey'), (Value: integer($C1B6FF); Name: 'Lightpink'), (Value: integer($7AA0FF); Name: 'Lightsalmon'), (Value: integer($AAB220); Name: 'Lightseagreen'), (Value: integer($FACE87); Name: 'Lightskyblue'), (Value: integer($998877); Name: 'Lightslategray'), (Value: integer($998877); Name: 'Lightslategrey'), (Value: integer($DEC4B0); Name: 'Lightsteelblue'), (Value: integer($E0FFFF); Name: 'Lightyellow'), (Value: integer(clLime); Name: 'Lime'), (Value: integer($32CD32); Name: 'Limegreen'), (Value: integer($E6F0FA); Name: 'Linen'), (Value: integer($FF00FF); Name: 'Magenta'), (Value: integer(clMaroon); Name: 'Maroon'), (Value: integer($AACD66); Name: 'Mediumaquamarine'), (Value: integer($CD0000); Name: 'Mediumblue'), (Value: integer($D355BA); Name: 'Mediumorchid'), (Value: integer($DB7093); Name: 'Mediumpurple'), (Value: integer($71B33C); Name: 'Mediumseagreen'), (Value: integer($EE687B); Name: 'Mediumslateblue'), (Value: integer($9AFA00); Name: 'Mediumspringgreen'), (Value: integer($CCD148); Name: 'Mediumturquoise'), (Value: integer($8515C7); Name: 'Mediumvioletred'), (Value: integer($701919); Name: 'Midnightblue'), (Value: integer($FAFFF5); Name: 'Mintcream'), (Value: integer($E1E4FF); Name: 'Mistyrose'), (Value: integer($B5E4FF); Name: 'Moccasin'), (Value: integer($ADDEFF); Name: 'Navajowhite'), (Value: integer(clNavy); Name: 'Navy'), (Value: integer($E6F5FD); Name: 'Oldlace'), (Value: integer(clOlive); Name: 'Olive'), (Value: integer($238E6B); Name: 'Olivedrab'), (Value: integer($00A5FF); Name: 'Orange'), (Value: integer($0045FF); Name: 'Orangered'), (Value: integer($D670DA); Name: 'Orchid'), (Value: integer($AAE8EE); Name: 'Palegoldenrod'), (Value: integer($98FB98); Name: 'Palegreen'), (Value: integer($EEEEAF); Name: 'Paleturquoise'), (Value: integer($9370DB); Name: 'Palevioletred'), (Value: integer($D5EFFF); Name: 'Papayawhip'), (Value: integer($B9DAFF); Name: 'Peachpuff'), (Value: integer($3F85CD); Name: 'Peru'), (Value: integer($CBC0FF); Name: 'Pink'), (Value: integer($DDA0DD); Name: 'Plum'), (Value: integer($E6E0B0); Name: 'Powderblue'), (Value: integer(clPurple); Name: 'Purple'), (Value: integer(clRed); Name: 'Red'), (Value: integer($8F8FBC); Name: 'Rosybrown'), (Value: integer($E16941); Name: 'Royalblue'), (Value: integer($13458B); Name: 'Saddlebrown'), (Value: integer($7280FA); Name: 'Salmon'), (Value: integer($60A4F4); Name: 'Sandybrown'), (Value: integer($578B2E); Name: 'Seagreen'), (Value: integer($EEF5FF); Name: 'Seashell'), (Value: integer($2D52A0); Name: 'Sienna'), (Value: integer(clSilver); Name: 'Silver'), (Value: integer($EBCE87); Name: 'Skyblue'), (Value: integer($CD5A6A); Name: 'Slateblue'), (Value: integer($908070); Name: 'Slategray'), (Value: integer($908070); Name: 'Slategrey'), (Value: integer($FAFAFF); Name: 'Snow'), (Value: integer($7FFF00); Name: 'Springgreen'), (Value: integer($B48246); Name: 'Steelblue'), (Value: integer($8CB4D2); Name: 'Tan'), (Value: integer(clTeal); Name: 'Teal'), (Value: integer($D8BFD8); Name: 'Thistle'), (Value: integer($4763FF); Name: 'Tomato'), (Value: integer($D0E040); Name: 'Turquoise'), (Value: integer($EE82EE); Name: 'Violet'), (Value: integer($B3DEF5); Name: 'Wheat'), (Value: integer(clWhite); Name: 'White'), (Value: integer($F5F5F5); Name: 'Whitesmoke'), (Value: integer(clYellow); Name: 'Yellow'), (Value: integer($32CD9A); Name: 'Yellowgreen') ); function IDToColor(const ID: string; var Color: TColor): boolean; var X: longint; V: integer; begin Result := (ID <> ''); if Result then if CharInSet(ID[1], ['#', '@']) then begin Result := TryStrToInt('$' + Copy(ID, 2, Length(ID)), V); if Result then Color := TColor(V) else Result := IDToColor(Copy(ID, 2, Length(ID) - 1), Color); end else begin Result := IdentToInt(ID, X, color_map); if Result then Color := TColor(X); end; end; function ColorToID(Color: TColor): string; begin Result := ''; if not IntToIdent(integer(Color), Result, color_map) then Result := Format('#%0.8x', [integer(Color)]); end; function ScreenWidth(MM: currency): integer; begin Result := Round((MM * Screen.PixelsPerInch) / 25.4); end; function ScreenHeight(MM: currency): integer; begin Result := Round((MM * Screen.PixelsPerInch) / 25.4); end; function StrToShortCut(const AStr: string): TShortCut; const ALNUM = ['A'..'Z', 'a'..'z', '0'..'9']; var I, B: integer; T: string; S: TShiftState; K: word; begin S := []; K := 0; B := 1; I := 1; while I <= Length(AStr) do begin if not CharInSet(AStr[I], ALNUM) then begin T := Copy(AStr, B, I - B); if SameText(T, 'Alt') then Include(S, ssAlt) else if SameText(T, 'Alter') then Include(S, ssAlt) else {$IFNDEF FPC} if SameText(T, 'Command') then Include(S, ssCommand) else if SameText(T, 'Cmd') then Include(S, ssCommand) else {$ENDIF} if SameText(T, 'Ctrl') then Include(S, ssCtrl) else if SameText(T, 'Control') then Include(S, ssCtrl) else if SameText(T, 'Shift') then Include(S, ssShift); B := I + 1; end; Inc(I); end; T := Copy(AStr, B, I - B); if T <> '' then if Length(T) = 1 then K := Ord(UpperCase(T)[1]) else if SameText(T, 'F1') then K := VK_F1 else if SameText(T, 'F2') then K := VK_F2 else if SameText(T, 'F3') then K := VK_F3 else if SameText(T, 'F4') then K := VK_F4 else if SameText(T, 'F5') then K := VK_F5 else if SameText(T, 'F6') then K := VK_F6 else if SameText(T, 'F7') then K := VK_F7 else if SameText(T, 'F8') then K := VK_F8 else if SameText(T, 'F9') then K := VK_F9 else if SameText(T, 'F10') then K := VK_F10 else if SameText(T, 'F11') then K := VK_F11 else if SameText(T, 'F12') then K := VK_F12 else if SameText(T, 'Esc') then K := VK_ESCAPE else if SameText(T, 'Escape') then K := VK_ESCAPE else if SameText(T, 'Tab') then K := Ord(#9) else if SameText(T, 'Enter') then K := Ord(#10) else if SameText(T, 'Insert') then K := VK_INSERT else if SameText(T, 'Back') then K := VK_BACK else if SameText(T, 'BackSpace') then K := VK_BACK else if SameText(T, 'Del') then K := VK_DELETE else if SameText(T, 'Delete') then K := VK_DELETE else if SameText(T, 'Home') then K := VK_HOME else if SameText(T, 'End') then K := VK_END else if SameText(T, 'Up') then K := VK_UP else if SameText(T, 'Down') then K := VK_DOWN else if SameText(T, 'Left') then K := VK_LEFT else if SameText(T, 'Right') then K := VK_RIGHT else if SameText(T, 'PageUp') then K := VK_PRIOR else if SameText(T, 'PageDown') then K := VK_NEXT; Result := ShortCut(K, S); end; { TLyKeyShift } procedure TLyKeyShift.Enter(AOwner: TLyKeyDown); begin Leave; FOwner := AOwner; FNext := FOwner.FFirst; FOwner.FFirst := Self; end; procedure TLyKeyShift.Leave; var S: TLyKeyShift; begin if (FOwner <> nil) and (FOwner.FFirst <> nil) then if Self <> FOwner.FFirst then begin S := FOwner.FFirst; while (S <> nil) and (S.FNext <> Self) do S := S.FNext; if S <> nil then S.FNext := FNext; end else FOwner.FFirst := FNext; FNext := nil; FOwner := nil; end; constructor TLyKeyShift.Create(AOwner: TLyKeyDown); begin Enter(AOwner); end; destructor TLyKeyShift.Destroy; begin Leave; inherited; end; { TLyPalette } constructor TLyPalette.Create; begin FTextColor := COLOR_TEXT; FBackground := COLOR_BACKGROUND; FSelectedTextColor := COLOR_SELECTEDTEXT; FSelectedBackground := COLOR_SELECTEDBACKGROUND; FLeftBarBackground := clBtnFace; FChangedBackground := clLime; FActiveBackground := clSkyBlue; FCaretColor := FTextColor; FLine80Color := clGray; FLineMarkBackground := $437E07; { token color } FUnknownColor := clRed; FKeywordColor := clNavy; FIDColor := COLOR_TEXT; FSpaceColor := COLOR_TEXT; FOperatorColor := COLOR_TEXT; FDelimiterColor := COLOR_TEXT; FNumberColor := clBlue; FENumberColor := clRed; FCharColor := clBlue; FECharColor := clRed; FStringColor := clBlue; FEStringColor := clRed; FBoolColor := COLOR_TEXT; FCommentColor := clGreen; FECommentColor := clGreen; FECommentPColor := clGreen; FDirectiveColor := clTeal; FEDirectiveColor := clTeal; FTagColor := clTeal; // clBlue; FMarkColor := clPurple; //clBlue; FHilightColor := clBlue; FRawDataColor := clDkGray; { token style } FKeywordStyle := [fsBold]; end; function TLyPalette.Apply(Font: TFont; Token: TLyTokenID; Selected: boolean): boolean; begin Result := (Font <> nil); if Result then begin Font.Style := Font.Style + GetStyle(Token); if Selected then Font.Color := FSelectedTextColor else Font.Color := GetColor(Token); end; end; function TLyPalette.GetStyle(Token: TLyTokenID): TFontStyles; begin Result := []; case Token of TK_SPACE : Result := FSpaceStyle; TK_KEYWORD : Result := FKeywordStyle; TK_ID : Result := FIDStyle; TK_OPERATOR : Result := FOperatorStyle; TK_DELIMITER : Result := FDelimiterStyle; TK_NUMBER : Result := FNumberStyle; TK_ENUMBER : Result := FENumberStyle; TK_CHAR : Result := FCharStyle; TK_ECHAR : Result := FECharStyle; TK_STRING : Result := FStringStyle; TK_ESTRING : Result := FEStringStyle; TK_BOOL : Result := FBoolStyle; TK_COMMENT : Result := FCommentStyle; TK_ECOMMENT : Result := FECommentStyle; TK_ECOMMENTP : Result := FECommentPStyle; TK_DIRECTIVE : Result := FDirectiveStyle; TK_EDIRECTIVE: Result := FEDirectiveStyle; TK_UNKNOWN : Result := FUnknownStyle; TK_TAG : Result := FTagStyle; TK_MARK : Result := FMarkStyle; TK_HILIGHT : Result := FHilightStyle; TK_RAWDATA : Result := FRawDataStyle; end; end; function TLyPalette.GetColor(Token: TLyTokenID): TColor; begin Result := FSpaceColor; case Token of TK_SPACE : Result := FSpaceColor; TK_KEYWORD : Result := FKeywordColor; TK_ID : Result := FIDColor; TK_OPERATOR : Result := FOperatorColor; TK_DELIMITER : Result := FDelimiterColor; TK_NUMBER : Result := FNumberColor; TK_ENUMBER : Result := FENumberColor; TK_CHAR : Result := FCharColor; TK_ECHAR : Result := FECharColor; TK_STRING : Result := FStringColor; TK_ESTRING : Result := FEStringColor; TK_BOOL : Result := FBoolColor; TK_COMMENT : Result := FCommentColor; TK_ECOMMENT : Result := FECommentColor; TK_ECOMMENTP : Result := FECommentPColor; TK_DIRECTIVE : Result := FDirectiveColor; TK_EDIRECTIVE: Result := FEDirectiveColor; TK_UNKNOWN : Result := FUnknownColor; TK_TAG : Result := FTagColor; TK_MARK : Result := FMarkColor; TK_HILIGHT : Result := FHilightColor; TK_RAWDATA : Result := FRawDataColor; end; end; { TLyKeyDown } constructor TLyKeyDown.Create(AOwner: TObject); begin FOwner := AOwner; end; destructor TLyKeyDown.Destroy; begin while FFirst <> nil do FFirst.Free; inherited; end; function TLyKeyDown.Add(Key: Word; Shift: TShiftState; Handler: TLyKeyEvent): TLyKeyShift; begin Result := nil; if Assigned(Handler) then begin Result := Find(Key, Shift); if Result = nil then begin Result := TLyKeyShift.Create(Self); Result.FKey := Key; Result.FShift := Shift; end; Result.FHandler := Handler; end; end; function TLyKeyDown.Find(Key: Word; Shift: TShiftState): TLyKeyShift; begin Result := FFirst; while Result <> nil do begin if Key = Result.FKey then if Shift = Result.FShift then Exit; Result := Result.FNext; end; end; function TLyKeyDown.Process(Sender: TObject; Key: Word; Shift: TShiftState): boolean; var K: TLyKeyShift; begin K := Find(Key, Shift); Result := (K <> nil); if Result then K.FHandler(Sender, Shift); end; end.
35.644955
97
0.658402
c30cfcfbe562d570d5445b4b30fdb97323ebf395
205
pas
Pascal
Demos/DataSet/DataSet.Resources.Common/DataSet.Resources.Common.pas
Gronfi/DMVVM-ES
f83e781d8d8f235005ed273581ad72868a83a390
[ "Apache-2.0" ]
8
2020-03-03T12:32:32.000Z
2020-11-18T10:54:29.000Z
Prototipo.0/Demos/DataSet/DataSet.Resources.Common/DataSet.Resources.Common.pas
Gronfi/DMVVM-ES
f83e781d8d8f235005ed273581ad72868a83a390
[ "Apache-2.0" ]
null
null
null
Prototipo.0/Demos/DataSet/DataSet.Resources.Common/DataSet.Resources.Common.pas
Gronfi/DMVVM-ES
f83e781d8d8f235005ed273581ad72868a83a390
[ "Apache-2.0" ]
3
2020-03-03T18:09:16.000Z
2020-11-18T11:08:02.000Z
unit DataSet.Resources.Common; interface uses DataSet.Interfaces; var Modelo : IDataSetFile_Model; VistaModelo: IDataSetFile_ViewModel; Vista : IDataSetFile_View; implementation end.
12.8125
38
0.756098
fc7f2ade17b135f0defc6f5c50ba6a521c04c4b2
31,288
pas
Pascal
LUXOPHIA/LUX.Data/LUX.Data.Octree.pas
hartmutdavid/FMX3DViewer
ec6942ce29a3eff811b05553a8e415134e3dcf1f
[ "Apache-2.0" ]
8
2017-12-23T11:26:32.000Z
2020-06-28T10:09:01.000Z
LUXOPHIA/LUX.Data/LUX.Data.Octree.pas
hartmutdavid/FMX3DViewer
ec6942ce29a3eff811b05553a8e415134e3dcf1f
[ "Apache-2.0" ]
null
null
null
LUXOPHIA/LUX.Data/LUX.Data.Octree.pas
hartmutdavid/FMX3DViewer
ec6942ce29a3eff811b05553a8e415134e3dcf1f
[ "Apache-2.0" ]
3
2019-02-08T17:03:25.000Z
2020-06-29T06:41:16.000Z
unit LUX.Data.Octree; interface //#################################################################### ■ uses LUX, LUX.D3; type //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【型】 IOcNode = interface; IOcKnot = interface; IOcLeaf = interface; IOctree = interface; TOcNode = class; TOcKnot = class; TOcLeaf = class; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TOcNode IOcNode = interface ['{2330A1DE-B3EC-4072-8F50-CEAB5A583E02}'] {protected} ///// アクセス function GetRoot :IOctree; function GetLev :Cardinal; function GetInd :TCardinal3D; function GetParen :IOcNode; procedure SetParen( const Paren_:IOcNode ); function GetChilds( const I_:Byte ) :IOcNode; procedure SetChilds( const I_:Byte; const Child_:IOcNode ); {public} ///// プロパティ property Root :IOctree read GetRoot ; property Lev :Cardinal read GetLev ; property Ind :TCardinal3D read GetInd ; property Paren :IOcNode read GetParen write SetParen ; property Childs[ const I_:Byte ] :IOcNode read GetChilds write SetChilds; ///// メソッド procedure Clear; function ForChilds( const Func_:TConstFunc<IOcNode,Boolean> ) :Boolean; procedure ForFamily( const Proc_:TConstProc<IOcNode> ); function ForChildPairs( const Node_:IOcNode; const Func_:TConstFunc<IOcNode,IOcNode,Boolean> ) :Boolean; end; //------------------------------------------------------------------------- TOcNode = class( TInterfacedBase, IOcNode ) private protected ///// アクセス function GetRoot :IOctree; virtual; function GetLev :Cardinal; virtual; function GetInd :TCardinal3D; virtual; abstract; function GetParen :IOcNode; virtual; abstract; procedure SetParen( const Paren_:IOcNode ); virtual; abstract; function GetChilds( const I_:Byte ) :IOcNode; virtual; abstract; procedure SetChilds( const I_:Byte; const Child_:IOcNode ); virtual; abstract; public constructor Create; destructor Destroy; override; ///// プロパティ property Root :IOctree read GetRoot ; property Lev :Cardinal read GetLev ; property Ind :TCardinal3D read GetInd ; property Paren :IOcNode read GetParen write SetParen ; property Childs[ const I_:Byte ] :IOcNode read GetChilds write SetChilds; ///// メソッド procedure Clear; function ForChilds( const Func_:TConstFunc<IOcNode,Boolean> ) :Boolean; virtual; abstract; procedure ForFamily( const Proc_:TConstProc<IOcNode> ); virtual; abstract; function ForChildPairs( const Node_:IOcNode; const Func_:TConstFunc<IOcNode,IOcNode,Boolean> ) :Boolean; virtual; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TOcLeaf IOcLeaf = interface( IOcNode ) ['{D3D3C428-50D3-48B5-B1DD-0FD69EB041AA}'] {protected} {public} end; //------------------------------------------------------------------------- TOcLeaf = class( TOcNode, IOcLeaf, IOcNode ) private protected _Paren :IOcNode; _Id :T1Bit3D; ///// アクセス function GetInd :TCardinal3D; override; function GetParen :IOcNode; override; procedure SetParen( const Paren_:IOcNode ); override; function GetChilds( const I_:Byte ) :IOcNode; override; procedure SetChilds( const I_:Byte; const Child_:IOcNode ); override; public constructor Create; destructor Destroy; override; ///// プロパティ ///// メソッド function ForChilds( const Func_:TConstFunc<IOcNode,Boolean> ) :Boolean; override; procedure ForFamily( const Proc_:TConstProc<IOcNode> ); override; function ForChildPairs( const Node_:IOcNode; const Func_:TConstFunc<IOcNode,IOcNode,Boolean> ) :Boolean; override; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TOcKnot IOcKnot = interface( IOcNode ) ['{977955C9-F3FF-4FF2-BCE2-EA39B19E1216}'] {protected} {public} end; //------------------------------------------------------------------------- TOcKnot = class( TOcNode, IOcKnot, IOcNode ) private protected _Paren :IOcNode; _Id :T1Bit3D; _Childs :array [ 0..7 ] of IOcNode; ///// アクセス function GetInd :TCardinal3D; override; function GetParen :IOcNode; override; procedure SetParen( const Paren_:IOcNode ); override; function GetChilds( const I_:Byte ) :IOcNode; override; procedure SetChilds( const I_:Byte; const Child_:IOcNode ); override; public constructor Create; destructor Destroy; override; ///// プロパティ ///// メソッド function ForChilds( const Func_:TConstFunc<IOcNode,Boolean> ) :Boolean; override; procedure ForFamily( const Proc_:TConstProc<IOcNode> ); override; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TOctree<_TOcKnot_,_TOcLeaf_> IOctree = interface( IOcNode ) ['{C4E87A83-EA71-4145-913A-E856DC00B6B1}'] {protected} ///// アクセス function GetDivL :Integer; procedure SetDivL( const DivL_:Integer ); function GetDivN :Integer; procedure SetDivN( const DivN_:Integer ); {public} ///// プロパティ property DivL :Integer read GetDivL write SetDivL; property DivN :Integer read GetDivN write SetDivN; ///// メソッド function GetNode( const Lev_:cardinal; const Ind_:TCardinal3D ) :IOcNode; end; //------------------------------------------------------------------------- TOctree<_TKnot_:TOcKnot,constructor; _TLeaf_:TOcLeaf,constructor> = class( TOcNode, IOctree, IOcNode ) private protected _Childs :array [ 0..7 ] of IOcNode; _DivL :Integer; ///// アクセス function GetRoot :IOctree; override; function GetLev :Cardinal; override; function GetInd :TCardinal3D; override; function GetParen :IOcNode; override; procedure SetParen( const Paren_:IOcNode ); override; function GetChilds( const I_:Byte ) :IOcNode; override; procedure SetChilds( const I_:Byte; const Child_:IOcNode ); override; function GetDivL :Integer; procedure SetDivL( const DivL_:Integer ); function GetDivN :Integer; procedure SetDivN( const DivN_:Integer ); public constructor Create; destructor Destroy; override; ///// プロパティ property DivL :Integer read GetDivL write SetDivL; property DivN :Integer read GetDivN write SetDivN; ///// メソッド class function DivLtoN( const DivL_:Cardinal ) :Cardinal; class function DivNtoL( const DivN_:Cardinal ) :Cardinal; function ForChilds( const Func_:TConstFunc<IOcNode,Boolean> ) :Boolean; override; procedure ForFamily( const Proc_:TConstProc<IOcNode> ); override; function Add( const Ind_:TCardinal3D ) :_TLeaf_; function GetNode( const Lev_:cardinal; const Ind_:TCardinal3D ) :IOcNode; function GetLeaf( const Ind_:TCardinal3D ) :_TLeaf_; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TOcLeaf<_INode_,_IRoot_> TOcLeaf<_INode_:IOcNode; _IRoot_:IOctree> = class( TOcLeaf, IOcLeaf, IOcNode ) private protected class var {本来不要なキャスト関数} _CastNode :TConstFunc<IOcNode,_INode_>; _CastRoot :TConstFunc<IOctree,_IRoot_>; protected ///// アクセス function GetRoot :_IRoot_; reintroduce; function GetParen :_INode_; reintroduce; procedure SetParen( const Paren_:_INode_ ); reintroduce; function GetChilds( const I_:Byte ) :_INode_; reintroduce; procedure SetChilds( const I_:Byte; const Child_:_INode_ ); reintroduce; public constructor Create; destructor Destroy; override; ///// プロパティ property Root :_IRoot_ read GetRoot ; property Paren :_INode_ read GetParen write SetParen ; property Childs[ const I_:Byte ] :_INode_ read GetChilds write SetChilds; ///// メソッド function ForChilds( const Func_:TConstFunc<_INode_,Boolean> ) :Boolean; reintroduce; procedure ForFamily( const Proc_:TConstProc<_INode_> ); reintroduce; function ForChildPairs( const Node_:_INode_; const Func_:TConstFunc<_INode_,_INode_,Boolean> ) :Boolean; reintroduce; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TOcKnot<_INode_,_IRoot_> TOcKnot<_INode_:IOcNode; _IRoot_:IOctree> = class( TOcKnot, IOcKnot, IOcNode ) private protected class var {本来不要なキャスト関数} _CastNode :TConstFunc<IOcNode,_INode_>; _CastRoot :TConstFunc<IOctree,_IRoot_>; protected ///// アクセス function GetRoot :_IRoot_; reintroduce; function GetParen :_INode_; reintroduce; procedure SetParen( const Paren_:_INode_ ); reintroduce; function GetChilds( const I_:Byte ) :_INode_; reintroduce; procedure SetChilds( const I_:Byte; const Child_:_INode_ ); reintroduce; public constructor Create; destructor Destroy; override; ///// プロパティ property Root :_IRoot_ read GetRoot ; property Paren :_INode_ read GetParen write SetParen ; property Childs[ const I_:Byte ] :_INode_ read GetChilds write SetChilds; ///// メソッド function ForChilds( const Func_:TConstFunc<_INode_,Boolean> ) :Boolean; reintroduce; procedure ForFamily( const Proc_:TConstProc<_INode_> ); reintroduce; function ForChildPairs( const Node_:_INode_; const Func_:TConstFunc<_INode_,_INode_,Boolean> ) :Boolean; reintroduce; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TOctree<_INode_,_IRoot_,_TKnot_,_TLeaf_> TOctree<_INode_:IOcNode; _IRoot_:IOctree; _TKnot_:TOcKnot<_INode_,_IRoot_>,constructor; _TLeaf_:TOcLeaf<_INode_,_IRoot_>,constructor> = class( TOctree<_TKnot_,_TLeaf_>, IOctree, IOcNode ) private protected class var {本来不要なキャスト関数} _CastNode :TConstFunc<IOcNode,_INode_>; _CastRoot :TConstFunc<IOctree,_IRoot_>; protected ///// アクセス function GetRoot :_IRoot_; reintroduce; function GetParen :_INode_; reintroduce; procedure SetParen( const Paren_:_INode_ ); reintroduce; function GetChilds( const I_:Byte ) :_INode_; reintroduce; procedure SetChilds( const I_:Byte; const Child_:_INode_ ); reintroduce; public constructor Create; destructor Destroy; override; ///// プロパティ property Root :_IRoot_ read GetRoot ; property Paren :_INode_ read GetParen write SetParen ; property Childs[ const I_:Byte ] :_INode_ read GetChilds write SetChilds; ///// メソッド function ForChilds( const Func_:TConstFunc<_INode_,Boolean> ) :Boolean; reintroduce; procedure ForFamily( const Proc_:TConstProc<_INode_> ); reintroduce; function ForChildPairs( const Node_:_INode_; const Func_:TConstFunc<_INode_,_INode_,Boolean> ) :Boolean; reintroduce; end; //const //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【定数】 //var //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【変数】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 implementation //############################################################### ■ uses System.SysUtils, System.Math; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TOcNode //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// アクセス function TOcNode.GetRoot :IOctree; begin Result := Paren.Root; end; //------------------------------------------------------------------------------ function TOcNode.GetLev :Cardinal; begin Result := Paren.Lev + 1; end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TOcNode.Create; begin inherited; end; destructor TOcNode.Destroy; begin inherited; end; /////////////////////////////////////////////////////////////////////// メソッド procedure TOcNode.Clear; var I :Byte; begin for I := 0 to 7 do Childs[ I ] := nil; end; //------------------------------------------------------------------------------ function TOcNode.ForChildPairs( const Node_:IOcNode; const Func_:TConstFunc<IOcNode,IOcNode,Boolean> ) :Boolean; begin Result := ForChilds( function( const N0:IOcNode ) :Boolean begin Result := Node_.ForChilds( function( const N1:IOcNode ) :Boolean begin Result := Func_( N0, N1 ); end ); end ); end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TOcLeaf //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// アクセス function TOcLeaf.GetInd :TCardinal3D; begin with Paren.Ind do begin Result.X := ( X shl 1 ) or _Id.X; Result.Y := ( Y shl 1 ) or _Id.Y; Result.Z := ( Z shl 1 ) or _Id.Z; end; end; //------------------------------------------------------------------------------ function TOcLeaf.GetParen :IOcNode; begin Result := _Paren; end; procedure TOcLeaf.SetParen( const Paren_:IOcNode ); begin _Paren := Paren_; end; //------------------------------------------------------------------------------ function TOcLeaf.GetChilds( const I_:Byte ) :IOcNode; begin Result := nil; end; procedure TOcLeaf.SetChilds( const I_:Byte; const Child_:IOcNode ); begin end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TOcLeaf.Create; begin inherited; end; destructor TOcLeaf.Destroy; begin inherited; end; /////////////////////////////////////////////////////////////////////// メソッド function TOcLeaf.ForChilds( const Func_:TConstFunc<IOcNode,Boolean> ) :Boolean; begin Result := Func_( Self ); end; procedure TOcLeaf.ForFamily( const Proc_:TConstProc<IOcNode> ); begin Proc_( Self ); end; function TOcLeaf.ForChildPairs( const Node_:IOcNode; const Func_:TConstFunc<IOcNode,IOcNode,Boolean> ) :Boolean; begin Result := Node_ is TOcLeaf or Node_.ForChilds( function( const N1:IOcNode ) :Boolean begin Result := Func_( Self, N1 ); end ); end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TOcKnot //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// アクセス function TOcKnot.GetInd :TCardinal3D; begin with Paren.Ind do begin Result.X := ( X shl 1 ) or _Id.X; Result.Y := ( Y shl 1 ) or _Id.Y; Result.Z := ( Z shl 1 ) or _Id.Z; end; end; //------------------------------------------------------------------------------ function TOcKnot.GetParen :IOcNode; begin Result := _Paren; end; procedure TOcKnot.SetParen( const Paren_:IOcNode ); begin _Paren := Paren_; end; //------------------------------------------------------------------------------ function TOcKnot.GetChilds( const I_:Byte ) :IOcNode; begin Result := _Childs[ I_ ]; end; procedure TOcKnot.SetChilds( const I_:Byte; const Child_:IOcNode ); begin _Childs[ I_ ] := Child_; end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TOcKnot.Create; var I :Byte; begin inherited; for I := 0 to 7 do _Childs[ I ] := nil; end; destructor TOcKnot.Destroy; begin Clear; inherited; end; /////////////////////////////////////////////////////////////////////// メソッド function TOcKnot.ForChilds( const Func_:TConstFunc<IOcNode,Boolean> ) :Boolean; var I :Byte; C :IOcNode; begin for I := 0 to 7 do begin C := _Childs[ I ]; if Assigned( C ) and Func_( C ) then Exit( True ); end; Result := False; end; procedure TOcKnot.ForFamily( const Proc_:TConstProc<IOcNode> ); var I :Byte; C :IOcNode; begin Proc_( Self ); for I := 0 to 7 do begin C := _Childs[ I ]; if Assigned( C ) then C.ForFamily( Proc_ ); end; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TOctree<_TOcKnot_,_TOcLeaf_> //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// アクセス function TOctree<_TKnot_,_TLeaf_>.GetRoot :IOctree; begin Result := Self; end; //------------------------------------------------------------------------------ function TOctree<_TKnot_,_TLeaf_>.GetLev :Cardinal; begin Result := 0; end; function TOctree<_TKnot_,_TLeaf_>.GetInd :TCardinal3D; begin Result := TCardinal3D.Create( 0, 0, 0 ); end; //------------------------------------------------------------------------------ function TOctree<_TKnot_,_TLeaf_>.GetParen :IOcNode; begin Result := nil; end; procedure TOctree<_TKnot_,_TLeaf_>.SetParen( const Paren_:IOcNode ); begin end; //------------------------------------------------------------------------------ function TOctree<_TKnot_,_TLeaf_>.GetChilds( const I_:Byte ) :IOcNode; begin Result := _Childs[ I_ ]; end; procedure TOctree<_TKnot_,_TLeaf_>.SetChilds( const I_:Byte; const Child_:IOcNode ); begin _Childs[ I_ ] := Child_; end; //------------------------------------------------------------------------------ function TOctree<_TKnot_,_TLeaf_>.GetDivL :Integer; begin Result := _DivL; end; procedure TOctree<_TKnot_,_TLeaf_>.SetDivL( const DivL_:Integer ); begin _DivL := DivL_; Clear; end; function TOctree<_TKnot_,_TLeaf_>.GetDivN :Integer; begin Result := DivLtoN( _DivL ); end; procedure TOctree<_TKnot_,_TLeaf_>.SetDivN( const DivN_:Integer ); begin DivL := DivNtoL( DivN_ ); end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TOctree<_TKnot_,_TLeaf_>.Create; begin inherited; _DivL := 0; end; destructor TOctree<_TKnot_,_TLeaf_>.Destroy; begin inherited; end; /////////////////////////////////////////////////////////////////////// メソッド class function TOctree<_TKnot_,_TLeaf_>.DivLtoN( const DivL_:Cardinal ) :Cardinal; begin Result := 1 shl DivL_; end; class function TOctree<_TKnot_,_TLeaf_>.DivNtoL( const DivN_:Cardinal ) :Cardinal; begin Result := Ceil( Log2( DivN_ ) ); end; //------------------------------------------------------------------------------ function TOctree<_TKnot_,_TLeaf_>.ForChilds( const Func_:TConstFunc<IOcNode,Boolean> ) :Boolean; var I :Byte; C :IOcNode; begin for I := 0 to 7 do begin C := _Childs[ I ]; if Assigned( C ) and Func_( C ) then Exit( True ); end; Result := False; end; procedure TOctree<_TKnot_,_TLeaf_>.ForFamily( const Proc_:TConstProc<IOcNode> ); var I :Byte; C :IOcNode; begin Proc_( Self ); for I := 0 to 7 do begin C := _Childs[ I ]; if Assigned( C ) then C.ForFamily( Proc_ ); end; end; //------------------------------------------------------------------------------ function TOctree<_TKnot_,_TLeaf_>.Add( const Ind_:TCardinal3D ) :_TLeaf_; var P, C :IOcNode; L :Integer; I :TCardinal3D; Id :T1Bit3D; begin P := Self; for L := 1 to _DivL-1 do begin I := Ind_ shr ( _DivL - L ); Id := I.LSB; C := P.Childs[ Id.o ]; if not Assigned( C ) then begin C := _TKnot_.Create; with C as TOcKnot do begin _Paren := P; _Id := Id; end; P.Childs[ Id.o ] := C; end; P := C; end; Id := Ind_.LSB; C := P.Childs[ Id.o ]; if not Assigned( C ) then begin C := _TLeaf_.Create; with C as TOcLeaf do begin _Paren := P; _Id := Id; end; P.Childs[ Id.o ] := C; end; Result := C as _TLeaf_; end; //------------------------------------------------------------------------------ function TOctree<_TKnot_,_TLeaf_>.GetNode( const Lev_:cardinal; const Ind_:TCardinal3D ) :IOcNode; var L :Integer; I :TCardinal3D; Id :T1Bit3D; begin Result := Self; for L := 1 to Lev_ do begin I := Ind_ shr ( _DivL - L ); Id := I.LSB; Result := Result.Childs[ Id.o ]; if not Assigned( Result ) then Exit; end; end; function TOctree<_TKnot_,_TLeaf_>.GetLeaf( const Ind_:TCardinal3D ) :_TLeaf_; begin Result := GetNode( _DivL, Ind_ ) as _TLeaf_; end; //------------------------------------------------------------------------------ { procedure TOctree.Add( const Pos_:TCardinal3D ); var I :TCardinal3D; P, C :TOcKnot; Id :T1Bit3D; L :Integer; F :TOcLeaf; begin if _DivL < 0 then begin _RootN := TOcLeaf.Create; _RootI := Pos_; Inc( _DivL ); end else begin I := Pos_ shr _DivL; while I <> _RootI do begin P := TOcKnot.Create; Id := _RootI.LSB; P.Childs[ Id ] := _RootN; _RootN := P; _RootI := _RootI shr 1; I := I shr 1; Inc( _DivL ); end; P := _RootN as TOcKnot; for L := _DivL-1 downto 1 do begin I := Pos_ shr L; Id := I.LSB; C := P.Childs[ Id ] as TOcKnot; if not Assigned( C ) then begin C := TOcKnot.Create; P.Childs[ Id ] := C; end; P := C; end; Id := Pos_.LSB; F := P.Childs[ Id ] as TOcLeaf; if not Assigned( F ) then P.Childs[ Id ] := TOcLeaf.Create; end; end; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TOcLeaf<_INode_,_IRoot_> //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// アクセス function TOcLeaf<_INode_,_IRoot_>.GetRoot :_IRoot_; begin Result := _CastRoot( inherited GetRoot ); end; //------------------------------------------------------------------------------ function TOcLeaf<_INode_,_IRoot_>.GetParen :_INode_; begin Result := _CastNode( inherited GetParen ); end; procedure TOcLeaf<_INode_,_IRoot_>.SetParen( const Paren_:_INode_ ); begin inherited SetParen( Paren_ ); end; function TOcLeaf<_INode_,_IRoot_>.GetChilds( const I_:Byte ) :_INode_; begin Result := _CastNode( inherited GetChilds( I_ ) ); end; procedure TOcLeaf<_INode_,_IRoot_>.SetChilds( const I_:Byte; const Child_:_INode_ ); begin inherited SetChilds( I_, Child_ ); end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TOcLeaf<_INode_,_IRoot_>.Create; begin inherited; end; destructor TOcLeaf<_INode_,_IRoot_>.Destroy; begin inherited; end; /////////////////////////////////////////////////////////////////////// メソッド function TOcLeaf<_INode_,_IRoot_>.ForChilds( const Func_:TConstFunc<_INode_,Boolean> ) :Boolean; begin Result := inherited ForChilds( function( const Child_:IOcNode ) :Boolean begin Result := Func_( _CastNode( Child_ ) ); end ); end; procedure TOcLeaf<_INode_,_IRoot_>.ForFamily( const Proc_:TConstProc<_INode_> ); begin inherited ForFamily( procedure( const Node_:IOcNode ) begin Proc_( _CastNode( Node_ ) ); end ); end; function TOcLeaf<_INode_,_IRoot_>.ForChildPairs( const Node_:_INode_; const Func_:TConstFunc<_INode_,_INode_,Boolean> ) :Boolean; begin Result := inherited ForChildPairs( Node_, function( const N0,N1:IOcNode ) :Boolean begin Result := Func_( _CastNode( N0 ), _CastNode( N1 ) ); end ); end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TOcKnot<_INode_,_IRoot_> //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// アクセス function TOcKnot<_INode_,_IRoot_>.GetRoot :_IRoot_; begin Result := _CastRoot( inherited GetRoot ); end; //------------------------------------------------------------------------------ function TOcKnot<_INode_,_IRoot_>.GetParen :_INode_; begin Result := _CastNode( inherited GetParen ); end; procedure TOcKnot<_INode_,_IRoot_>.SetParen( const Paren_:_INode_ ); begin inherited SetParen( Paren_ ); end; function TOcKnot<_INode_,_IRoot_>.GetChilds( const I_:Byte ) :_INode_; begin Result := _CastNode( inherited GetChilds( I_ ) ); end; procedure TOcKnot<_INode_,_IRoot_>.SetChilds( const I_:Byte; const Child_:_INode_ ); begin inherited SetChilds( I_, Child_ ); end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TOcKnot<_INode_,_IRoot_>.Create; begin inherited; end; destructor TOcKnot<_INode_,_IRoot_>.Destroy; begin inherited; end; /////////////////////////////////////////////////////////////////////// メソッド function TOcKnot<_INode_,_IRoot_>.ForChilds( const Func_:TConstFunc<_INode_,Boolean> ) :Boolean; begin Result := inherited ForChilds( function( const Child_:IOcNode ) :Boolean begin Result := Func_( _CastNode( Child_ ) ); end ); end; procedure TOcKnot<_INode_,_IRoot_>.ForFamily( const Proc_:TConstProc<_INode_> ); begin inherited ForFamily( procedure( const Node_:IOcNode ) begin Proc_( _CastNode( Node_ ) ); end ); end; function TOcKnot<_INode_,_IRoot_>.ForChildPairs( const Node_:_INode_; const Func_:TConstFunc<_INode_,_INode_,Boolean> ) :Boolean; begin Result := inherited ForChildPairs( Node_, function( const N0,N1:IOcNode ) :Boolean begin Result := Func_( _CastNode( N0 ), _CastNode( N1 ) ); end ); end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TOctree<_INode_,_IRoot_,_TKnot_,_TLeaf_> //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// アクセス function TOctree<_INode_,_IRoot_,_TKnot_,_TLeaf_>.GetRoot :_IRoot_; begin Result := _CastRoot( inherited GetRoot ); end; //------------------------------------------------------------------------------ function TOctree<_INode_,_IRoot_,_TKnot_,_TLeaf_>.GetParen :_INode_; begin Result := _CastNode( inherited GetParen ); end; procedure TOctree<_INode_,_IRoot_,_TKnot_,_TLeaf_>.SetParen( const Paren_:_INode_ ); begin inherited SetParen( Paren_ ); end; function TOctree<_INode_,_IRoot_,_TKnot_,_TLeaf_>.GetChilds( const I_:Byte ) :_INode_; begin Result := _CastNode( inherited GetChilds( I_ ) ); end; procedure TOctree<_INode_,_IRoot_,_TKnot_,_TLeaf_>.SetChilds( const I_:Byte; const Child_:_INode_ ); begin inherited SetChilds( I_, Child_ ); end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TOctree<_INode_,_IRoot_,_TKnot_,_TLeaf_>.Create; begin inherited; end; destructor TOctree<_INode_,_IRoot_,_TKnot_,_TLeaf_>.Destroy; begin inherited; end; /////////////////////////////////////////////////////////////////////// メソッド function TOctree<_INode_,_IRoot_,_TKnot_,_TLeaf_>.ForChilds( const Func_:TConstFunc<_INode_,Boolean> ) :Boolean; begin Result := inherited ForChilds( function( const Child_:IOcNode ) :Boolean begin Result := Func_( _CastNode( Child_ ) ); end ); end; procedure TOctree<_INode_,_IRoot_,_TKnot_,_TLeaf_>.ForFamily( const Proc_:TConstProc<_INode_> ); begin inherited ForFamily( procedure( const Node_:IOcNode ) begin Proc_( _CastNode( Node_ ) ); end ); end; function TOctree<_INode_,_IRoot_,_TKnot_,_TLeaf_>.ForChildPairs( const Node_:_INode_; const Func_:TConstFunc<_INode_,_INode_,Boolean> ) :Boolean; begin Result := inherited ForChildPairs( Node_, function( const N0,N1:IOcNode ) :Boolean begin Result := Func_( _CastNode( N0 ), _CastNode( N1 ) ); end ); end; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 //############################################################################## □ initialization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 初期化 finalization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 最終化 end. //######################################################################### ■
30.347236
145
0.491115
c334753fb8c6cd8675b59465f4e9810929dc3519
212
pas
Pascal
Source/Services/SimpleEmailV2/Base/Model/AWS.SESv2.Model.ConcurrentModificationException.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/Model/AWS.SESv2.Model.ConcurrentModificationException.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/Model/AWS.SESv2.Model.ConcurrentModificationException.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.Model.ConcurrentModificationException; interface uses AWS.SESv2.Exception; type EConcurrentModificationException = class(EAmazonSimpleEmailServiceV2Exception) end; implementation end.
14.133333
80
0.825472
fc7f47333f8f58efad5a6a8fa3545f633c53e9e1
225
pas
Pascal
CAT/tests/00. general/string_literals/str_literal_multi_1.pas
SkliarOleksandr/NextPascal
4dc26abba6613f64c0e6b5864b3348711eb9617a
[ "Apache-2.0" ]
19
2018-10-22T23:45:31.000Z
2021-05-16T00:06:49.000Z
CAT/tests/00. general/string_literals/str_literal_multi_1.pas
SkliarOleksandr/NextPascal
4dc26abba6613f64c0e6b5864b3348711eb9617a
[ "Apache-2.0" ]
1
2019-06-01T06:17:08.000Z
2019-12-28T10:27:42.000Z
CAT/tests/00. general/string_literals/str_literal_multi_1.pas
SkliarOleksandr/NextPascal
4dc26abba6613f64c0e6b5864b3348711eb9617a
[ "Apache-2.0" ]
6
2018-08-30T05:16:21.000Z
2021-05-12T20:25:43.000Z
unit str_literal_multi_1; interface implementation const C = "sql" select id, name from table1 where name = "name1" "sql"; var S: string; uses sys.console; initialization S := C; log(S); finalization end.
10.714286
33
0.68
c331a174b00f8cba604ba22b0a011ebe36fad73f
2,062
pas
Pascal
Source/Services/Translate/Base/Model/AWS.Translate.Model.ParallelDataDataLocation.pas
juliomar/aws-sdk-delphi
995a0af808c7f66122fc6a04763d68203f8502eb
[ "Apache-2.0" ]
67
2021-07-28T23:47:09.000Z
2022-03-15T11:48:35.000Z
Source/Services/Translate/Base/Model/AWS.Translate.Model.ParallelDataDataLocation.pas
juliomar/aws-sdk-delphi
995a0af808c7f66122fc6a04763d68203f8502eb
[ "Apache-2.0" ]
5
2021-09-01T09:31:16.000Z
2022-03-16T18:19:21.000Z
Source/Services/Translate/Base/Model/AWS.Translate.Model.ParallelDataDataLocation.pas
landgraf-dev/aws-sdk-delphi
995a0af808c7f66122fc6a04763d68203f8502eb
[ "Apache-2.0" ]
13
2021-07-29T02:41:16.000Z
2022-03-16T10:22:38.000Z
unit AWS.Translate.Model.ParallelDataDataLocation; interface uses Bcl.Types.Nullable; type TParallelDataDataLocation = class; IParallelDataDataLocation = interface function GetLocation: string; procedure SetLocation(const Value: string); function GetRepositoryType: string; procedure SetRepositoryType(const Value: string); function Obj: TParallelDataDataLocation; function IsSetLocation: Boolean; function IsSetRepositoryType: Boolean; property Location: string read GetLocation write SetLocation; property RepositoryType: string read GetRepositoryType write SetRepositoryType; end; TParallelDataDataLocation = class strict private FLocation: Nullable<string>; FRepositoryType: Nullable<string>; function GetLocation: string; procedure SetLocation(const Value: string); function GetRepositoryType: string; procedure SetRepositoryType(const Value: string); strict protected function Obj: TParallelDataDataLocation; public function IsSetLocation: Boolean; function IsSetRepositoryType: Boolean; property Location: string read GetLocation write SetLocation; property RepositoryType: string read GetRepositoryType write SetRepositoryType; end; implementation { TParallelDataDataLocation } function TParallelDataDataLocation.Obj: TParallelDataDataLocation; begin Result := Self; end; function TParallelDataDataLocation.GetLocation: string; begin Result := FLocation.ValueOrDefault; end; procedure TParallelDataDataLocation.SetLocation(const Value: string); begin FLocation := Value; end; function TParallelDataDataLocation.IsSetLocation: Boolean; begin Result := FLocation.HasValue; end; function TParallelDataDataLocation.GetRepositoryType: string; begin Result := FRepositoryType.ValueOrDefault; end; procedure TParallelDataDataLocation.SetRepositoryType(const Value: string); begin FRepositoryType := Value; end; function TParallelDataDataLocation.IsSetRepositoryType: Boolean; begin Result := FRepositoryType.HasValue; end; end.
25.775
83
0.795829
47049a23b92a91caebc3ae9411a9a49d2a631cad
7,212
pas
Pascal
AdvanceDemo/DocUserDBDemo/_3_User_LoginFrm.pas
PassByYou888/ZNet
8f5439ec275ee4eb5d68e00c33675e6117379fcf
[ "BSD-3-Clause" ]
24
2022-01-20T13:59:38.000Z
2022-03-25T01:11:43.000Z
AdvanceDemo/DocUserDBDemo/_3_User_LoginFrm.pas
PassByYou888/ZNet
8f5439ec275ee4eb5d68e00c33675e6117379fcf
[ "BSD-3-Clause" ]
null
null
null
AdvanceDemo/DocUserDBDemo/_3_User_LoginFrm.pas
PassByYou888/ZNet
8f5439ec275ee4eb5d68e00c33675e6117379fcf
[ "BSD-3-Clause" ]
5
2022-01-20T14:44:24.000Z
2022-02-13T10:07:38.000Z
unit _3_User_LoginFrm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.FileCtrl, System.IOUtils, System.DateUtils, System.TypInfo, Z.Core, Z.PascalStrings, Z.UPascalStrings, Z.UnicodeMixedLib, Z.Status, Z.ListEngine, Z.GHashList, Z.Expression, Z.OpCode, Z.Parsing, Z.DFE, Z.TextDataEngine, Z.Json, Z.Geometry2D, Z.Geometry3D, Z.Number, Z.MemoryStream, Z.Cipher, Z.Notify, Z.IOThread, Z.Net, Z.Net.C4, Z.Net.C4_UserDB, Z.Net.C4_Var, Z.Net.C4_FS, Z.Net.C4_RandSeed, Z.Net.C4_Log_DB, Z.Net.C4_XNAT, Z.Net.C4_PascalRewrite_Client, Z.Net.PhysicsIO, MyCustomService; type Tuser_login_Form = class(TForm, IC40_PhysicsTunnel_Event) TopBarPanel: TPanel; JoinHostEdit: TLabeledEdit; JoinPortEdit: TLabeledEdit; BuildDependNetButton: TButton; resetDependButton: TButton; serviceComboBox: TComboBox; queryButton: TButton; netTimer: TTimer; logMemo: TMemo; _B_Splitter: TSplitter; cliPanel: TPanel; userEdit: TLabeledEdit; passwdEdit: TLabeledEdit; reguserButton: TButton; loginUserButton: TButton; discButton: TButton; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure netTimerTimer(Sender: TObject); procedure queryButtonClick(Sender: TObject); procedure BuildDependNetButtonClick(Sender: TObject); procedure loginUserButtonClick(Sender: TObject); procedure reguserButtonClick(Sender: TObject); procedure resetDependButtonClick(Sender: TObject); private procedure DoStatus_backcall(Text_: SystemString; const ID: Integer); procedure ReadConfig; procedure WriteConfig; procedure Do_QueryResult(Sender: TC40_PhysicsTunnel; L: TC40_InfoList); private procedure C40_PhysicsTunnel_Connected(Sender: TC40_PhysicsTunnel); procedure C40_PhysicsTunnel_Disconnect(Sender: TC40_PhysicsTunnel); procedure C40_PhysicsTunnel_Build_Network(Sender: TC40_PhysicsTunnel; Custom_Client_: TC40_Custom_Client); procedure C40_PhysicsTunnel_Client_Connected(Sender: TC40_PhysicsTunnel; Custom_Client_: TC40_Custom_Client); public ValidService: TC40_InfoList; MyClient: TMyCustom_Client; constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; var user_login_Form: Tuser_login_Form; implementation {$R *.dfm} procedure Tuser_login_Form.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; WriteConfig; end; procedure Tuser_login_Form.netTimerTimer(Sender: TObject); begin Z.Net.C4.C40Progress; end; procedure Tuser_login_Form.queryButtonClick(Sender: TObject); var tunnel_: TC40_PhysicsTunnel; begin tunnel_ := C40_PhysicsTunnelPool.GetOrCreatePhysicsTunnel(JoinHostEdit.Text, EStrToInt(JoinPortEdit.Text, 0)); tunnel_.QueryInfoM(Do_QueryResult); end; procedure Tuser_login_Form.BuildDependNetButtonClick(Sender: TObject); var info: TC40_Info; begin if serviceComboBox.ItemIndex < 0 then exit; info := TC40_Info(serviceComboBox.Items.Objects[serviceComboBox.ItemIndex]); Z.Net.C4.C40_PhysicsTunnelPool.GetOrCreatePhysicsTunnel(info, info.ServiceTyp, self); end; procedure Tuser_login_Form.loginUserButtonClick(Sender: TObject); begin if MyClient = nil then exit; if MyClient.DTVirtualAuth.LinkOk then exit; MyClient.Client.RegisterUserAndLogin := False; MyClient.Client.Connect_P(userEdit.Text, passwdEdit.Text, procedure(const State: Boolean) begin if State then DoStatus('login successed') else DoStatus('login failed.'); end); end; procedure Tuser_login_Form.reguserButtonClick(Sender: TObject); begin if MyClient = nil then exit; if MyClient.DTVirtualAuth.LinkOk then exit; MyClient.Client.RegisterUserAndLogin := True; MyClient.Client.Connect_P(userEdit.Text, passwdEdit.Text, procedure(const State: Boolean) begin if State then DoStatus('reg successed') else DoStatus('reg failed.'); end); end; procedure Tuser_login_Form.resetDependButtonClick(Sender: TObject); begin C40Clean_Client; end; procedure Tuser_login_Form.DoStatus_backcall(Text_: SystemString; const ID: Integer); begin if logMemo.Lines.Count > 2000 then logMemo.Clear; logMemo.Lines.Add(DateTimeToStr(now) + ' ' + Text_); end; procedure Tuser_login_Form.ReadConfig; var fn: U_String; te: THashTextEngine; begin fn := umlChangeFileExt(Application.ExeName, '.conf'); if not umlFileExists(fn) then exit; te := THashTextEngine.Create; te.LoadFromFile(fn); JoinHostEdit.Text := te.GetDefaultValue('Main', JoinHostEdit.Name, JoinHostEdit.Text); JoinPortEdit.Text := te.GetDefaultValue('Main', JoinPortEdit.Name, JoinPortEdit.Text); DisposeObject(te); end; procedure Tuser_login_Form.WriteConfig; var fn: U_String; te: THashTextEngine; begin fn := umlChangeFileExt(Application.ExeName, '.conf'); te := THashTextEngine.Create; te.SetDefaultValue('Main', JoinHostEdit.Name, JoinHostEdit.Text); te.SetDefaultValue('Main', JoinPortEdit.Name, JoinPortEdit.Text); te.SaveToFile(fn); DisposeObject(te); end; procedure Tuser_login_Form.Do_QueryResult(Sender: TC40_PhysicsTunnel; L: TC40_InfoList); var arry: TC40_Info_Array; i: Integer; begin ValidService.Clear; arry := L.SearchService(GetRegisterServiceTypFromClass(TMyCustom_Client)); for i := low(arry) to high(arry) do ValidService.Add(arry[i].Clone); serviceComboBox.Clear; for i := 0 to ValidService.Count - 1 do serviceComboBox.AddItem(Format('"%s" host "%s" port %d', [ValidService[i].ServiceTyp.Text, ValidService[i].PhysicsAddr.Text, ValidService[i].PhysicsPort]), ValidService[i]); if serviceComboBox.Items.Count > 0 then serviceComboBox.ItemIndex := 0; end; procedure Tuser_login_Form.C40_PhysicsTunnel_Connected(Sender: TC40_PhysicsTunnel); begin DoStatus('connect to "%s" port %d ok.', [Sender.PhysicsAddr.Text, Sender.PhysicsPort]); end; procedure Tuser_login_Form.C40_PhysicsTunnel_Disconnect(Sender: TC40_PhysicsTunnel); begin serviceComboBox.Clear; ValidService.Clear; MyClient := nil; cliPanel.Visible := False; end; procedure Tuser_login_Form.C40_PhysicsTunnel_Build_Network(Sender: TC40_PhysicsTunnel; Custom_Client_: TC40_Custom_Client); begin DoStatus('Build network: %s classes: %s', [Custom_Client_.ClientInfo.ServiceTyp.Text, Custom_Client_.ClassName]); if Custom_Client_ is TMyCustom_Client then begin MyClient := Custom_Client_ as TMyCustom_Client; cliPanel.Visible := True; end; end; procedure Tuser_login_Form.C40_PhysicsTunnel_Client_Connected(Sender: TC40_PhysicsTunnel; Custom_Client_: TC40_Custom_Client); begin end; constructor Tuser_login_Form.Create(AOwner: TComponent); begin inherited Create(AOwner); AddDoStatusHook(self, DoStatus_backcall); Z.Net.C4.C40_QuietMode := False; ReadConfig; ValidService := TC40_InfoList.Create(True); C40_PhysicsTunnel_Disconnect(nil); end; destructor Tuser_login_Form.Destroy; begin C40Clean; RemoveDoStatusHook(self); inherited Destroy; end; end.
29.925311
179
0.762618
c33b5bfe4ae0a7bfc42bd9098ce6be8b42b17246
2,375
pas
Pascal
Components/cnvcl/Examples/DHibernate/GroupMgr/PODO/PODO_MEMBERS.pas
98kmir2/98kmir2
46196a161d46cc7a85d168dca683b4aff477a709
[ "BSD-3-Clause" ]
15
2020-02-13T11:59:11.000Z
2021-12-31T14:53:44.000Z
Components/cnvcl/Examples/DHibernate/GroupMgr/PODO/PODO_MEMBERS.pas
bsjzx8/98
46196a161d46cc7a85d168dca683b4aff477a709
[ "BSD-3-Clause" ]
null
null
null
Components/cnvcl/Examples/DHibernate/GroupMgr/PODO/PODO_MEMBERS.pas
bsjzx8/98
46196a161d46cc7a85d168dca683b4aff477a709
[ "BSD-3-Clause" ]
13
2020-02-20T07:22:09.000Z
2021-12-31T14:56:09.000Z
(* This unit is created by PODO generator *) unit PODO_MEMBERS; {$M+} interface uses Classes, SysUtils, CnDHibernateBase; type TMembers = class(TCnDHibernateBase) private FQQCode : WideString; FUserName : WideString; FSex : WideString; FAge : WideString; FArea : WideString; FNameCard : WideString; FEmail : WideString; FWebSite : WideString; FResearch : Variant; FStatus : WideString; FOutReason : Variant; FInTime : TDateTime; FOutTime : TDateTime; FIdentity : WideString; FSex_FORMULA: WideString; FStatus_FORMULA: WideString; FGotResearch: WideString; FGotWarn: WideString; function GetSex_SQL: WideString; function GetStatus_SQL: WideString; published property QQCode : WideString read FQQCode write FQQCode; property UserName : WideString read FUserName write FUserName; property Sex : WideString read FSex write FSex; property Age : WideString read FAge write FAge; property Area : WideString read FArea write FArea; property NameCard : WideString read FNameCard write FNameCard; property Email : WideString read FEmail write FEmail; property WebSite : WideString read FWebSite write FWebSite; property Research : Variant read FResearch write FResearch; property Status : WideString read FStatus write FStatus; property OutReason : Variant read FOutReason write FOutReason; property InTime : TDateTime read FInTime write FInTime; property OutTime : TDateTime read FOutTime write FOutTime; property Identity : WideString read FIdentity write FIdentity; property GotWarn: WideString read FGotWarn write FGotWarn; property GotResearch: WideString read FGotResearch write FGotResearch; property Sex_FORMULA : WideString read FSex_FORMULA write FSex_FORMULA; property Sex_SQL : WideString read GetSex_SQL; property Status_FORMULA: WideString read FStatus_FORMULA write FStatus_FORMULA; property Status_SQL : WideString read GetStatus_SQL; end; implementation { TMembers } function TMembers.GetSex_SQL: WideString; begin Result := Format('select [NAME] from [Constants] where [Code]=''%s''', [Sex]); end; function TMembers.GetStatus_SQL: WideString; begin Result := Format('select [NAME] from [Constants] where [Code]=''%s''', [Status]); end; initialization RegisterClass(TMembers); end.
31.666667
83
0.744
fc6b156e92dbcb11e6255ffa975d0a34fb3bfb8b
470,044
pas
Pascal
SOURCE/Clx/qcomctrls.pas
earthsiege2/borland-cpp-ide
09bcecc811841444338e81b9c9930c0e686f9530
[ "Unlicense", "FSFAP", "Apache-1.1" ]
1
2022-01-13T01:03:55.000Z
2022-01-13T01:03:55.000Z
SOURCE/Clx/qcomctrls.pas
earthsiege2/borland-cpp-ide
09bcecc811841444338e81b9c9930c0e686f9530
[ "Unlicense", "FSFAP", "Apache-1.1" ]
null
null
null
SOURCE/Clx/qcomctrls.pas
earthsiege2/borland-cpp-ide
09bcecc811841444338e81b9c9930c0e686f9530
[ "Unlicense", "FSFAP", "Apache-1.1" ]
null
null
null
{ *************************************************************************** } { } { Delphi and Kylix Cross-Platform Visual Component Library } { } { Copyright (c) 2000, 2001 Borland Software Corporation } { } { *************************************************************************** } unit QComCtrls; {$R-,T-,H+,X+} interface uses Types, SysUtils, Classes, Qt, QTypes, QControls, QStdCtrls, QGraphics, Contnrs, QStdActns, QImgList, QMenus, QDialogs, QExtCtrls, QButtons; type { Exception Classes } EListViewException = class(Exception); EListColumnException = class(Exception); EStatusBarException = class(Exception); EHeaderException = class(Exception); ERangeException = class(Exception); { TTab } TCustomTabControl = class; TTabButtons = (tbLeft, tbRight); TTabStyle = (tsTabs, tsButtons, tsFlatButtons, tsNoTabs); TTabChangedEvent = procedure(Sender: TObject; TabID: Integer) of object; TTabGetImageEvent = procedure(Sender: TObject; TabIndex: Integer; var ImageIndex: Integer) of object; TTabChangingEvent = procedure(Sender: TObject; var AllowChange: Boolean) of object; TDrawTabEvent = procedure(Control: TCustomTabControl; TabIndex: Integer; const Rect: TRect; Active: Boolean; var DefaultDraw: Boolean ) of object; TTabs = class; TTabControl = class; TTab = class(TCollectionItem) private FEnabled: Boolean; FCaption: TCaption; FTabRect: TRect; FRow: Integer; FImageIndex: Integer; FVisible: Boolean; FSelected: Boolean; FHighlighted: Boolean; function GetTabs: TTabs; function CalculateWidth: Integer; function CalculateHeight: Integer; procedure SetCaption(const Value: TCaption); procedure SetEnabled(const Value: Boolean); function GetHeight: Integer; function GetWidth: Integer; procedure SetHeight(const Value: Integer); procedure SetWidth(const Value: Integer); function GetLeft: Integer; function GetTop: Integer; procedure SetLeft(const Value: Integer); procedure SetTop(const Value: Integer); procedure SetVisible(const Value: Boolean); function GetImageIndex: Integer; procedure SetImageIndex(const Value: Integer); procedure SetSelected(const Value: Boolean); procedure SetHighlighted(const Value: Boolean); protected function GetDisplayName: string; override; property Left: Integer read GetLeft write SetLeft; property Top: Integer read GetTop write SetTop; property Height: Integer read GetHeight write SetHeight; property Width: Integer read GetWidth write SetWidth; public constructor Create(Collection: TCollection); override; procedure Assign(Source: TPersistent); override; property Tabs: TTabs read GetTabs; property Row: Integer read FRow; property TabRect: TRect read FTabRect; published property Caption: TCaption read FCaption write SetCaption; property Enabled: Boolean read FEnabled write SetEnabled default True; property Highlighted: Boolean read FHighlighted write SetHighlighted default False; property ImageIndex: Integer read GetImageIndex write SetImageIndex; property Selected: Boolean read FSelected write SetSelected default False; property Visible: Boolean read FVisible write SetVisible default True; end; { TTabs } TTabs = class(TCollection) private FTabControl: TCustomTabControl; FUpdating: Boolean; function GetItem(Index: Integer): TTab; procedure SetItem(Index: Integer; const Value: TTab); function CalculateTabHeight(const S: WideString): Integer; protected function GetOwner: TPersistent; override; procedure Update(Item: TCollectionItem); override; property TabControl: TCustomTabControl read FTabControl; public constructor Create(TabControl: TCustomTabControl); function Add(const ACaption: WideString): TTab; property Items[Index: Integer]: TTab read GetItem write SetItem; default; end; { TCustomTabControl } TTabSide = (tsLeft, tsTop, tsRight, tsBottom); TCustomTabControl = class(TCustomControl) private FBitmap: TBitmap; FButtons: array [TTabButtons] of TSpeedButton; FErase: Boolean; FDblBuffer: TBitmap; FFirstVisibleTab: Integer; FHotImages: TCustomImageList; FHotTrack: Boolean; FHotTrackColor: TColor; FImageBorder: Integer; FImageChangeLink: TChangeLink; FImages: TCustomImageList; FLastVisibleTab: Integer; FLayoutCount: Integer; FMouseOver: Integer; FMultiLine: Boolean; FMultiSelect: Boolean; FOwnerDraw: Boolean; FRaggedRight: Boolean; FRowCount: Integer; FShowFrame: Boolean; FStyle: TTabStyle; FTabIndex: Integer; FTabs: TTabs; FTabSize: TSmallPoint; FTracking: Integer; FOnChange: TNotifyEvent; FOnChanged: TTabChangedEvent; FOnChanging: TTabChangingEvent; FOnDrawTab: TDrawTabEvent; FOnGetImageIndex: TTabGetImageEvent; FUpdating: Boolean; function RightSide: Integer; procedure ButtonClick(Sender: TObject); procedure EraseControlFlag(const Value: Boolean = True); procedure DisplayScrollButtons; procedure DrawFocus; function GetTabHeight: Integer; procedure CalcImageTextOffset(const ARect: TRect; const S: WideString; Image: TCustomImageList; var ImagePos, TextPos: TPoint); procedure CalculateRows(SelectedRow: Integer); procedure CalculateTabPositions; procedure EnableScrollButtons; function FindNextVisibleTab(Index: Integer): Integer; function FindPrevVisibleTab(Index: Integer): Integer; procedure BeginDblBuffer; procedure EndDblBuffer; procedure StretchTabs(ARow: Integer); procedure CreateButtons; function GetDisplayRect: TRect; function GetImageRef: TCustomImageList; function GetTabIndex: Integer; function GetTotalTabHeight: Integer; function HasImages(ATab: TTab): Boolean; procedure InternalDrawTabFrame(ACanvas: TCanvas; const ARect: TRect; Tab: TTab; HotTracking: Boolean = False); procedure InternalDrawTabContents(ACanvas: TCanvas; const ARect: TRect; Tab: TTab; HotTracking: Boolean = False); procedure InternalDrawFrame(ACanvas: TCanvas; ARect: TRect; AShowFrame: Boolean = True; Sunken: Boolean = False; Fill : Boolean = True); function GetTabs: TTabs; procedure PositionButtons; function RightSideAdjustment: Integer; procedure SetTabs(const Value: TTabs); procedure SetHotTrack(const Value: Boolean); procedure SetHotTrackColor(const Value: TColor); procedure SetImages(const Value: TCustomImageList); procedure SetMultiLine(const Value: Boolean); procedure SetMultiSelect(const Value: Boolean); procedure DoHotTrack(const Value: Integer); procedure SetOwnerDraw(const Value: Boolean); procedure SetRaggedRight(const Value: Boolean); procedure SetStyle(Value: TTabStyle); procedure SetTabHeight(const Value: Smallint); procedure SetTabIndex(const Value: Integer); procedure SetTabWidth(const Value: Smallint); procedure TabsChanged; procedure SetShowFrame(const Value: Boolean); procedure DrawHighlight(Canvas: TCanvas; const Rect: TRect; ASelected, AHighlight, AEnabled: Boolean); procedure SetHotImages(const Value: TCustomImageList); procedure UnselectTabs; protected procedure AdjustClientRect(var Rect: TRect); override; procedure AdjustTabClientRect(var Rect: TRect); virtual; procedure AdjustTabRect(var Rect: TRect); virtual; function CanChange: Boolean; dynamic; function CanShowTab(TabIndex: Integer): Boolean; virtual; procedure Change; dynamic; procedure Changed(Value: Integer); dynamic; function DoMouseWheel(Shift: TShiftState; WheelDelta: Integer; const MousePos: TPoint): Boolean; override; function DoMouseWheelDown(Shift: TShiftState; const MousePos: TPoint): Boolean; override; function DoMouseWheelUp(Shift: TShiftState; const MousePos: TPoint): Boolean; override; function DrawTab(TabIndex: Integer; const Rect: TRect; Active: Boolean): Boolean; virtual; procedure EnabledChanged; override; procedure FontChanged; override; function GetImageIndex(ATabIndex: Integer): Integer; virtual; procedure ImageListChange(Sender: TObject); virtual; procedure KeyUp(var Key: Word; Shift: TShiftState); override; procedure Loaded; override; procedure LayoutTabs; virtual; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseLeave(AControl: TControl); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure Paint; override; procedure Resize; override; procedure RequestAlign; override; procedure RequestLayout; dynamic; procedure UpdateTabImages; function WantKey(Key: Integer; Shift: TShiftState; const KeyText: WideString): Boolean; override; function WidgetFlags: Integer; override; property DisplayRect: TRect read GetDisplayRect; property HotImages: TCustomImageList read FHotImages write SetHotImages; property HotTrack: Boolean read FHotTrack write SetHotTrack default False; property HotTrackColor: TColor read FHotTrackColor write SetHotTrackColor default clBlue; property ImageBorder: Integer read FImageBorder write FImageBorder default 4; property Images: TCustomImageList read FImages write SetImages; property MultiLine: Boolean read FMultiLine write SetMultiLine default False; property MultiSelect: Boolean read FMultiSelect write SetMultiSelect default False; procedure Notification(AComponent: TComponent; Operation: TOperation); override; property OwnerDraw: Boolean read FOwnerDraw write SetOwnerDraw default False; property RaggedRight: Boolean read FRaggedRight write SetRaggedRight default False; property ShowFrame: Boolean read FShowFrame write SetShowFrame default False; property Style: TTabStyle read FStyle write SetStyle default tsTabs; property TabHeight: Smallint read FTabSize.Y write SetTabHeight default 0; property TabIndex: Integer read GetTabIndex write SetTabIndex default 0; property Tabs: TTabs read GetTabs write SetTabs; property TabWidth: Smallint read FTabSize.X write SetTabWidth default 0; property OnChange: TNotifyEvent read FOnChange write FOnChange; property OnChanged: TTabChangedEvent read FOnChanged write FOnChanged; property OnChanging: TTabChangingEvent read FOnChanging write FOnChanging; property OnDrawTab: TDrawTabEvent read FOnDrawTab write FOnDrawTab; property OnGetImageIndex: TTabGetImageEvent read FOnGetImageIndex write FOnGetImageIndex; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure BeginUpdate; procedure EndUpdate; function IndexOfTabAt(X, Y: Integer): Integer; procedure ScrollTabs(Delta: Integer); function TabRect(Index: Integer): TRect; //depricated; property Canvas; property RowCount: Integer read FRowCount; property TabStop default True; end; { TTabControl } TTabControl = class(TCustomTabControl) published property Anchors; property Align; property Constraints; property DragMode; property Enabled; property Font; property HotImages; property HotTrack; property HotTrackColor; property Images; property MultiLine; property ParentFont; property ParentShowHint; property PopupMenu; property RaggedRight; property ShowFrame; property ShowHint; property Style; property MultiSelect; { must be after Style due to streaming order } property TabHeight; property TabOrder; property TabStop; property Tabs; property TabIndex; { must be after Tabs due to streaming order } property TabWidth; property Visible; property OnChange; property OnChanged; property OnContextPopup; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnGetImageIndex; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnResize; property OnStartDrag; end; { TTabSheet } TPageControl = class; TTabSheet = class(TCustomControl) private FBorderWidth: TBorderWidth; FImageIndex: TImageIndex; FHighlighted: Boolean; FPageControl: TPageControl; FTabVisible: Boolean; FOnHide: TNotifyEvent; FOnShow: TNotifyEvent; FTab: TTab; function GetPageIndex: Integer; function GetTabIndex: Integer; procedure SetBorderWidth(const Value : TBorderWidth); procedure SetHighlighted(const Value: Boolean); procedure SetImageIndex(const Value: TImageIndex); procedure SetPageControl(const Value: TPageControl); procedure SetPageIndex(const Value: Integer); procedure SetTabVisible(const Value: Boolean); protected procedure AdjustClientRect(var Rect: TRect); override; procedure DoHide; dynamic; procedure DoShow; dynamic; procedure EnabledChanged; override; procedure ReadState(Reader: TReader); override; procedure ShowingChanged; override; procedure TextChanged; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure InitWidget; override; property PageControl: TPageControl read FPageControl write SetPageControl; property TabIndex: Integer read GetTabIndex; published property BorderWidth: TBorderWidth read FBorderWidth write SetBorderWidth default 0; property Caption; property Color; 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 PageIndex: Integer read GetPageIndex write SetPageIndex stored False; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property TabVisible: Boolean read FTabVisible write SetTabVisible default True; 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; property OnMouseMove; property OnMouseUp; property OnResize; property OnShow: TNotifyEvent read FOnShow write FOnShow; property OnStartDrag; end; { TPageControl } TPageChangingEvent = procedure(Sender: TObject; NewPage: TTabSheet; var AllowChange: Boolean) of object; TPageControl = class(TCustomTabControl) private FPages: TList; FActivePage: TTabSheet; FOnPageChange: TNotifyEvent; FOnPageChanging: TPageChangingEvent; procedure DeleteTab(Page: TTabSheet; Index: Integer); function GetActivePageIndex: Integer; function GetPage(Index: Integer): TTabSheet; function GetPageCount: Integer; procedure SetActivePage(aPage: TTabSheet); procedure SetActivePageIndex(const Value: Integer); procedure ChangeActivePage(Page: TTabSheet); procedure MoveTab(CurIndex, NewIndex: Integer); procedure InsertPage(const APage: TTabSheet); procedure InsertTab(Page: TTabSheet); procedure RemovePage(const APage: TTabSheet); procedure UpdateTab(Page: TTabSheet); protected procedure DoContextPopup(const MousePos: TPoint; var Handled: Boolean); override; function CanShowTab(TabIndex: Integer): Boolean; override; procedure Changed(Value: Integer); override; procedure Change; override; function DesignEventQuery(Sender: QObjectH; Event: QEventH): Boolean; override; procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override; procedure PageChange; dynamic; procedure PageChanging(NewPage: TTabSheet; var AllowChange: Boolean); dynamic; procedure SetChildOrder(Child: TComponent; Order: Integer); override; procedure ShowControl(AControl: TControl); override; procedure UpdateActivePage; virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function FindNextPage(CurPage: TTabSheet; GoForward, CheckTabVisible: Boolean): TTabSheet; procedure SelectNextPage(GoForward: Boolean); procedure Update; override; property ActivePageIndex: Integer read GetActivePageIndex write SetActivePageIndex; property PageCount: Integer read GetPageCount; property Pages[Index: Integer]: TTabSheet read GetPage; published property ActivePage: TTabSheet read FActivePage write SetActivePage; property Align; property Anchors; property Constraints; property DragMode; property Enabled; property Font; property HotTrack; property HotTrackColor; property HotImages; property Images; property MultiLine; property ParentFont; property ParentShowHint; property PopupMenu; property RaggedRight; property ShowFrame; property ShowHint; property Style; property TabHeight; property TabOrder; property TabStop; property TabWidth; property Visible; property OnChange: TNotifyEvent read FOnPageChange write FOnPageChange; property OnChanging; property OnContextPopup; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnGetImageIndex; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnPageChanging: TPageChangingEvent read FOnPageChanging write FOnPageChanging; property OnResize; property OnStartDrag; end; { TStatusBar } TStatusBar = class; TStatusPanel = class; TPanelPosition = (ppLeft, ppRight); TStatusPanelStyle = (psText, psOwnerDraw); TStatusPanelBevel = (pbNone, pbLowered, pbRaised); TStatusPanels = class; TStatusPanel = class(TCollectionItem) private FAlignment: TAlignment; FBevel: TStatusPanelBevel; FBounds: TRect; FHidden: Boolean; FPanelPosition: TPanelPosition; FStyle: TStatusPanelStyle; FText: WideString; FVisible: Boolean; FWidth: Integer; procedure SetAlignment(const Value: TAlignment); procedure SetBevel(const Value: TStatusPanelBevel); procedure SetStyle(Value: TStatusPanelStyle); procedure SetText(const Value: WideString); procedure SetWidth(const Value: Integer); procedure SetPanelPosition(const Value: TPanelPosition); procedure SetVisible(const Value: Boolean); function GetStatusPanels: TStatusPanels; protected function GetDisplayName: string; override; property StatusPanels: TStatusPanels read GetStatusPanels; public constructor Create(Collection: TCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; published property Alignment: TAlignment read FAlignment write SetAlignment default taLeftJustify; property Bevel: TStatusPanelBevel read FBevel write SetBevel default pbLowered; property PanelPosition: TPanelPosition read FPanelPosition write SetPanelPosition default ppLeft; property Style: TStatusPanelStyle read FStyle write SetStyle default psText; property Text: WideString read FText write SetText; property Visible: Boolean read FVisible write SetVisible default True; property Width: Integer read FWidth write SetWidth default 50; end; { TStatusPanels } TStatusPanels = class(TCollection) private FFixedPanelCount: Integer; FStatusBar: TStatusBar; function GetItem(Index: Integer): TStatusPanel; procedure SetItem(Index: Integer; const Value: TStatusPanel); protected function GetOwner: TPersistent; override; procedure Update(Item: TCollectionItem); override; property StatusBar: TStatusBar read FStatusBar; public constructor Create(StatusBar: TStatusBar); function Add: TStatusPanel; property Items[Index: Integer]: TStatusPanel read GetItem write SetItem; default; end; { TStatusBar } TPanelClick = procedure(Sender: TObject; Panel: TStatusPanel) of object; TDrawPanelEvent = procedure(StatusBar: TStatusBar; Panel: TStatusPanel; const Rect: TRect) of object; TStatusBar = class(TCustomPanel) private FAutoHint: Boolean; FUpdateCount: Integer; FSimplePanel: Boolean; FSimpleText: WideString; FPanels: TStatusPanels; FOnDrawPanel: TDrawPanelEvent; FOnHint: TNotifyEvent; FSizeGrip: Boolean; FSizeGripHandle: QSizeGripH; FOnPanelClick: TPanelClick; function IsFontStored: Boolean; procedure SetPanels(const Value: TStatusPanels); procedure SetSimplePanel(const Value: Boolean); procedure SetSimpleText(const Value: WideString); procedure UpdatePanels; procedure SetSizeGrip(const Value: Boolean); procedure PositionSizeGrip; procedure ValidateSizeGrip; function GetPanel(PanelPosition: TPanelPosition; Index: Integer): TStatusPanel; function GetBorderWidth: TBorderWidth; procedure SetBorderWidth(const Value: TBorderWidth); procedure CMRecreateWindow(var Message: TMessage); message CM_RECREATEWINDOW; protected procedure ControlsAligned; override; procedure CursorChanged; override; function DoHint: Boolean; virtual; procedure DoPanelClick(Panel: TStatusPanel); dynamic; procedure DrawPanel(Panel: TStatusPanel; const Rect: TRect); dynamic; procedure EnabledChanged; override; procedure InitWidget; override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure Paint; override; procedure PaletteCreated; override; procedure RequestAlign; override; procedure Resize; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure BeginUpdate; procedure EndUpdate; function ExecuteAction(Action: TBasicAction): Boolean; override; function FindPanel(PanelPosition: TPanelPosition; Index: Integer): TStatusPanel; procedure FlipChildren(AllLevels: Boolean); override; procedure Invalidate; override; procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override; procedure Update; override; property Canvas; property Panel[PanelPosition: TPanelPosition; Index: Integer]: TStatusPanel read GetPanel; published property Action; property Align default alBottom; property Anchors; property AutoHint: Boolean read FAutoHint write FAutoHint default False; property BorderWidth: TBorderWidth read GetBorderWidth write SetBorderWidth default 0; property Color default clBackground; property Constraints; property DragMode; property Enabled; property Font stored IsFontStored; property Panels: TStatusPanels read FPanels write SetPanels; property ParentColor default False; property ParentFont default True; property ParentShowHint; property PopupMenu; property ShowHint; property SimplePanel: Boolean read FSimplePanel write SetSimplePanel default False; property SimpleText: WideString read FSimpleText write SetSimpleText; property SizeGrip: Boolean read FSizeGrip write SetSizeGrip default True; property Visible; property OnClick; property OnContextPopup; property OnDblClick; property OnDragDrop; property OnDragOver; property OnDrawPanel: TDrawPanelEvent read FOnDrawPanel write FOnDrawPanel; property OnEndDrag; property OnHint: TNotifyEvent read FOnHint write FOnHint; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnPanelClick: TPanelClick read FOnPanelClick write FOnPanelClick; property OnResize; property OnStartDrag; end; { TTrackBar } TTrackBarOrientation = (trHorizontal, trVertical); TTickMark = (tmBottomRight, tmTopLeft, tmBoth); TTickStyle = (tsNone, tsAuto); QTickSetting = (qtsNoMarks, qtsAbove, qtsLeft, qtsBelow, qtsRight, qtsBoth); TTrackBar = class(TWidgetControl) private FMin: Integer; FMax: Integer; FOnChange: TNotifyEvent; FTickMarks: TTickMark; FTickStyle: TTickStyle; FOrientation: TTrackBarOrientation; procedure ChangeAspectRatio; function GetHandle: QClxSliderH; procedure SetFrequency(const Value: Integer); procedure SetLineSize(const Value: Integer); procedure SetMax(const Value: Integer); procedure SetMin(const Value: Integer); procedure SetOrientation(const Value: TTrackBarOrientation); procedure SetPageSize(const Value: Integer); procedure SetPosition(const Value: Integer); procedure SetRange(const AMin, AMax: Integer); procedure SetTickMarks(const Value: TTickMark); procedure SetTickStyle(const Value: TTickStyle); function GetOrientation: TTrackBarOrientation; function GetFrequency: Integer; function GetRangeControl: QRangeControlH; function GetLineSize: Integer; function GetPageSize: Integer; function GetMax: Integer; function GetMin: Integer; function GetPosition: Integer; function GetTickMarks: TTickMark; function GetTickStyle: TTickStyle; procedure UpdateSettings; procedure ValueChangedHook(Value: Integer); cdecl; protected procedure Changed; dynamic; procedure CreateWidget; override; procedure HookEvents; override; procedure InitWidget; override; procedure Loaded; override; property RangeControl: QRangeControlH read GetRangeControl; public constructor Create(AOwner: TComponent); override; property Handle: QClxSliderH read GetHandle; published property Align; property Anchors; property Bitmap; property Constraints; property DragMode; property Enabled; property Frequency: Integer read GetFrequency write SetFrequency default 1; property Hint; property LineSize: Integer read GetLineSize write SetLineSize default 1; property Masked default False; property Max: Integer read GetMax write SetMax default 10; property Min: Integer read GetMin write SetMin default 0; property Orientation: TTrackBarOrientation read GetOrientation write SetOrientation default trHorizontal; property PageSize: Integer read GetPageSize write SetPageSize default 2; property ParentShowHint; property PopupMenu; property Position: Integer read GetPosition write SetPosition default 0; property ShowHint; property TabOrder; property TabStop default True; property TickMarks: TTickMark read GetTickMarks write SetTickMarks default tmBottomRight; property TickStyle: TTickStyle read GetTickStyle write SetTickStyle default tsAuto; property Visible; property OnChange: TNotifyEvent read FOnChange write FOnChange; property OnContextPopup; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyString; property OnKeyUp; property OnStartDrag; end; { TProgressBar } TProgressBarChangeEvent = procedure(Sender: TObject; var Text: WideString; NewPosition: Integer) of object; TProgressBarOrientation = (pbHorizontal, pbVertical); TProgressBar = class(TGraphicControl) private FBorderWidth: TBorderWidth; FFillColor: TColor; FFillArea: TRect; FSections: Integer; FStep: Integer; FMin: Integer; FMax: Integer; FOrientation: TProgressBarOrientation; FPosition: Integer; FPrevText: WideString; FShowCaption: Boolean; FSmooth: Boolean; FTransparent: Boolean; FText: TCaption; FTextColor: TColor; FTotalSteps: Integer; FWrapRange: Boolean; FOnChanging: TProgressBarChangeEvent; function AdjustToParent(const Rect: TRect): TRect; function CalcTextRect(Rect: TRect; const BoundingRect: TRect; const AText: WideString): TRect; procedure EraseText(const AText: WideString; BackgroundColor : TColor); procedure InternalPaint; procedure InternalDrawFrame; function ScalePosition(Value: Integer): Integer; procedure SetBorderWidth(const Value: TBorderWidth); procedure SetFillColor(const Value: TColor); procedure SetMax(const Value: Integer); procedure SetMin(const Value: Integer); procedure SetOrientation(const Value: TProgressBarOrientation); procedure SetPosition(Value: Integer); procedure SetRange(const AMin, AMax: Integer); procedure SetShowCaption(const Value: Boolean); procedure SetSmooth(const Value: Boolean); procedure SetStep(const Value: Integer); procedure SetTransparent(const Value: Boolean); protected procedure Changing(var Text: WideString; NewPosition: Integer); dynamic; procedure FontChanged; override; function GetText: TCaption; override; procedure Paint; override; procedure SetText(const Value: TCaption); override; property WrapRange: Boolean read FWrapRange write FWrapRange; public constructor Create(AOwner: TComponent); override; procedure StepBy(Delta: Integer); procedure StepIt; virtual; published property Align; property Anchors; property BorderWidth: TBorderWidth read FBorderWidth write SetBorderWidth default 0; property Caption; property Color; property Constraints; property DragMode; property Enabled; property FillColor: TColor read FFillColor write SetFillColor default clHighlight; property Font; property Hint; property Max: Integer read FMax write SetMax default 100; property Min: Integer read FMin write SetMin default 0; property Orientation: TProgressBarOrientation read FOrientation write SetOrientation default pbHorizontal; property ParentColor; property ParentFont; property ParentShowHint; property PopupMenu; property Position: Integer read FPosition write SetPosition default 0; property ShowCaption: Boolean read FShowCaption write SetShowCaption default False; property ShowHint; property Smooth: Boolean read FSmooth write SetSmooth default False; property Step: Integer read FStep write SetStep default 10; property Transparent: Boolean read FTransparent write SetTransparent default False; property Visible; property OnChanging: TProgressBarChangeEvent read FOnChanging write FOnChanging; property OnContextPopup; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; end; TMimeSourceFactory = class(TPersistent) private FFilePath: TStrings; procedure SetFilePath(const Value: TStrings); protected FHandle: QMimeSourceFactoryH; procedure CreateHandle; virtual; procedure DestroyWidget; virtual; function GetHandle: QMimeSourceFactoryH; function HandleAllocated: Boolean; procedure HandleNeeded; procedure DoGetDataHook(AbsoluteName: PWideString; var ResolvedData: QMimeSourceH); cdecl; procedure GetData(const AbsoluteName: string; var ResolvedData: QMimeSourceH); virtual; public constructor Create; destructor Destroy; override; procedure AddDataToFactory(const Name: WideString; Data: QMimeSourceH); procedure AddImageToFactory(const Name: WideString; Data: QImageH); procedure AddPixmapToFactory(const Name: WideString; Data: QPixmapH); procedure AddTextToFactory(const Name: WideString; const Data: string); function GetMimeSource(const MimeType: WideString): QMimeSourceH; procedure RegisterMimeType(const FileExt: WideString; const MimeType: string); property Handle: QMimeSourceFactoryH read GetHandle; published property FilePath: TStrings read FFilePath write SetFilePath; end; { TCustomTextViewer } TTextFormat = (tfPlainText, tfText, tfAutoText); TCustomTextViewer = class(TFrameControl) private FBrush: TBrush; FFactory: TMimeSourceFactory; FUseDefaultFactory: Boolean; FViewportHandle: QWidgetH; FViewportHook: QWidget_hookH; FTextColor: TColor; FFileName: TFileName; FUnderlineLink: Boolean; FLinkColor: TColor; FTextFormat: TTextFormat; FVScrollHandle: QScrollBarH; FHScrollHandle: QScrollBarH; FVScrollHook: QScrollBar_hookH; FHScrollHook: QScrollBar_hookH; procedure SubmitTextColor; procedure SetTextFormat(const Value: TTextFormat); procedure SetUnderlineLink(const Value: Boolean); function GetDocumentTitle: WideString; function GetIsTextSelected: Boolean; function GetSelectedText: WideString; function GetBrush: TBrush; procedure SetBrush(const Value: TBrush); procedure SetTextColor(const Value: TColor); function GetDocumentText: WideString; procedure SetLinkColor(const Value: TColor); procedure SetDocumentText(const Value: WideString); virtual; function GetFactory: TMimeSourceFactory; procedure SetFactory(const Value: TMimeSourceFactory); procedure SetDefaultFactory(const Value: Boolean); procedure SetFileName(const Value: TFileName); procedure UpdateViewableContents; protected procedure CreateWidget; override; function GetChildHandle: QWidgetH; override; function GetHandle: QTextViewH; procedure InitWidget; override; procedure PaperChanged(Sender: TObject); function ViewportHandle: QWidgetH; procedure WidgetDestroyed; override; property DocumentTitle: WideString read GetDocumentTitle; property Handle: QTextViewH read GetHandle; property BorderStyle default bsSunken3d; property Factory: TMimeSourceFactory read GetFactory write SetFactory; property FileName: TFileName read FFileName write SetFileName; property Height default 150; property IsTextSelected: Boolean read GetIsTextSelected; property LinkColor: TColor read FLinkColor write SetLinkColor default clBlue; property Paper: TBrush read GetBrush write SetBrush; property SelectedText: WideString read GetSelectedText; property Text: WideString read GetDocumentText write SetDocumentText; property TextColor: TColor read FTextColor write SetTextColor default clBlack; property TextFormat: TTextFormat read FTextFormat write SetTextFormat default tfAutoText; property UnderlineLink: Boolean read FUnderlineLink write SetUnderlineLink default True; property UseDefaultFactory: Boolean read FUseDefaultFactory write SetDefaultFactory; property Width default 200; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure SelectAll; procedure CopyToClipboard; procedure LoadFromFile(const AFileName: string); virtual; procedure LoadFromStream(Stream: TStream); end; { TTextViewer } TTextViewer = class(TCustomTextViewer) public property DocumentTitle; property Factory; property Handle; property IsTextSelected; property Paper; property SelectedText; property Text; published property Align; property Anchors; property BorderStyle; property Constraints; property DragMode; property Height; property FileName; property LinkColor; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; property TextColor; property TextFormat; property UnderlineLink; property Width; property OnClick; property OnContextPopup; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; end; { TCustomTextBrowser } TRTBHighlightTextEvent = procedure (Sender: TObject; const HighlightedText: WideString) of object; TCustomTextBrowser = class(TCustomTextViewer) private FBackwardAvailable: Boolean; FForwardAvailable: Boolean; FRTBHighlightText: TRTBHighlightTextEvent; FTextChanged: TNotifyEvent; procedure SetDocumentText(const Value: WideString); override; procedure HookBackwardAvailable(p1: Boolean); cdecl; procedure HookForwardAvailable(p1: Boolean); cdecl; procedure HookHighlightText(p1: PWideString); cdecl; procedure HookTextChanged; cdecl; procedure SetHighlightText(const Value: TRTBHighlightTextEvent); procedure SetTextChanged(const Value: TNotifyEvent); protected procedure CreateWidget; override; procedure WidgetDestroyed; override; procedure HookEvents; override; function GetHandle: QTextBrowserH; property Handle: QTextBrowserH read GetHandle; property OnHighlightText: TRTBHighlightTextEvent read FRTBHighlightText write SetHighlightText; property OnTextChanged: TNotifyEvent read FTextChanged write SetTextChanged; public procedure LoadFromFile(const AFileName: string); override; procedure ScrollToAnchor(const AnchorName: WideString); function CanGoBackward: Boolean; procedure Backward; function CanGoForward: Boolean; procedure Forward; procedure Home; end; { TTextBrowser } TTextBrowser = class(TCustomTextBrowser) public property DocumentTitle; property Handle; property IsTextSelected; property Paper; property SelectedText; property Text; published property Align; property Anchors; property BorderStyle; property Constraints; property DragMode; property Factory; property FileName; property Height; property LinkColor; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; property TextColor; property TextFormat; property UnderlineLink; property Width; property OnClick; property OnContextPopup; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnHighlightText; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; property OnTextChanged; end; { TSpinEdit } TSEButtonType = (btNext, btPrev); TSEButtonStyle = (bsArrows, bsPlusMinus); TSEDownDirection = (sedNone, sedUp, sedDown); TSEChangedEvent = procedure (Sender: TObject; NewValue: Integer) of object; TCustomSpinEdit = class(TWidgetControl) private FButtonUpHook: QWidget_HookH; FButtonDownHook: QWidget_HookH; FEditHandle: QWidgetH; FEditHook: QWidget_HookH; FDownButtonHandle: QWidgetH; FMin: Integer; FMax: Integer; FUpButtonHandle: QWidgetH; FOnChanged: TSEChangedEvent; function GetButtonStyle: TSEButtonStyle; function GetCleanText: WideString; function GetIncrement: Integer; function GetMax: Integer; function GetMin: Integer; function GetPrefix: WideString; function GetRangeControl: QRangeControlH; function GetSuffix: WideString; function GetSpecialText: WideString; function GetValue: Integer; function GetWrap: Boolean; procedure ValueChangedHook(AValue: Integer); cdecl; procedure SetButtonStyle(AValue: TSEButtonStyle); procedure SetIncrement(AValue: Integer); procedure SetMax(AValue: Integer); procedure SetMin(AValue: Integer); procedure SetPrefix(const AValue: WideString); procedure SetRange(const AMin, AMax: Integer); procedure SetSuffix(const AValue: WideString); procedure SetSpecialText(const AValue: WideString); procedure SetWrap(AValue: Boolean); function GetHandle: QClxSpinBoxH; procedure SetValue(const AValue: Integer); protected procedure CreateWidget; override; procedure WidgetDestroyed; override; function EventFilter(Sender: QObjectH; Event: QEventH): Boolean; override; procedure HookEvents; override; procedure Change(AValue: Integer); dynamic; function GetText: TCaption; override; procedure InitWidget; override; procedure Loaded; override; procedure PaletteChanged(Sender: TObject); override; property ButtonStyle: TSEButtonStyle read GetButtonStyle write SetButtonStyle default bsArrows; property CleanText: WideString read GetCleanText; property Handle: QClxSpinBoxH read GetHandle; property Max: Integer read GetMax write SetMax default 100; property Min: Integer read GetMin write SetMin default 0; property Increment: Integer read GetIncrement write SetIncrement default 1; property Prefix: WideString read GetPrefix write SetPrefix; property RangeControl: QRangeControlH read GetRangeControl; property SpecialText: WideString read GetSpecialText write SetSpecialText; property Suffix: WideString read GetSuffix write SetSuffix; property TabStop default True; property Text: TCaption read GetText; property Value: Integer read GetValue write SetValue default 0; property Wrap: Boolean read GetWrap write SetWrap default False; property OnChanged: TSEChangedEvent read FOnChanged write FOnChanged; public constructor Create(AOwner: TComponent); override; procedure StepUp; procedure StepDown; end; TSpinEdit = class(TCustomSpinEdit) public property CleanText; property Text; published property Align; property Anchors; property ButtonStyle; property Constraints; property Color; property DragMode; property Enabled; property Hint; property Max; property Min; property Increment; property PopupMenu; property TabOrder; property TabStop; property Value; property Visible; property ParentShowHint; property Prefix; property ShowHint; property SpecialText; property Suffix; property Wrap; property OnChanged; property OnClick; property OnContextPopup; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; end; { forward class declarations } THeaderControl = class; TCustomHeaderControl = class; TCustomViewControl = class; TCustomViewItem = class; TCustomListView = class; TListItem = class; TListView = class; TCustomTreeView = class; TTreeNode = class; { TCustomHeaderSection } TCustomHeaderSection = class(TCollectionItem) private FAllowResize: Boolean; FAllowClick: Boolean; FMaxWidth: Integer; FWidth: Integer; FMinWidth: Integer; FHeader: TCustomHeaderControl; FImageIndex: TImageIndex; FAutoSize: Boolean; FText: WideString; procedure UpdateWidth; function Header: TCustomHeaderControl; procedure SetAllowClick(const Value: Boolean); procedure SetAllowResize(const Value: Boolean); procedure SetMaxWidth(const Value: Integer); procedure SetMinWidth(const Value: Integer); procedure SetWidth(Value: Integer); function GetLeft: Integer; function GetRight: Integer; procedure SetImageIndex(const Value: TImageIndex); procedure UpdateImage; procedure SetAutoSize(const Value: Boolean); function CalcSize: Integer; protected procedure AddSection; virtual; procedure AssignTo(Dest: TPersistent); override; function GetDisplayName: string; override; function GetWidth: Integer; virtual; procedure Resubmit; virtual; procedure SetWidthVal(const Value: Integer); virtual; property AllowClick: Boolean read FAllowClick write SetAllowClick; property AllowResize: Boolean read FAllowResize write SetAllowResize; property AutoSize: Boolean read FAutoSize write SetAutoSize; property ImageIndex: TImageIndex read FImageIndex write SetImageIndex; property Left: Integer read GetLeft; property MaxWidth: Integer read FMaxWidth write SetMaxWidth; property MinWidth: Integer read FMinWidth write SetMinWidth; property Right: Integer read GetRight; property Width: Integer read GetWidth write SetWidth; public constructor Create(Collection: TCollection); override; end; { THeaderSection } THeaderSection = class(TCustomHeaderSection) private procedure SetText(const Value: WideString); protected procedure AssignTo(Dest: TPersistent); override; procedure SetWidthVal(const Value: Integer); override; {$IF not (defined(LINUX) and defined(VER140))} function GetText: WideString; {$IFEND} public destructor Destroy; override; property Index; property Left; property Right; published property AllowClick default True; property AllowResize default True; property AutoSize default False; property ImageIndex default -1; property MaxWidth default 1000; property MinWidth; {$IF defined(LINUX) and defined(VER140)} property Text: WideString read FText write SetText; {$ELSE} property Text: WideString read GetText write SetText; {$IFEND} property Width default 50; end; THeaderSectionClass = class of TCustomHeaderSection; { TCustomHeaderSections } TCustomHeaderSections = class(TCollection) private FHeaderControl: TCustomHeaderControl; procedure UpdateImages; protected function GetOwner: TPersistent; override; procedure Update(Item: TCollectionItem); override; function GetItem(Index: Integer): TCustomHeaderSection; procedure SetItem(Index: Integer; Value: TCustomHeaderSection); public constructor Create(HeaderControl: TCustomHeaderControl; SectionClass: THeaderSectionClass); property Items[Index: Integer]: TCustomHeaderSection read GetItem write SetItem; default; end; { THeaderSections } THeaderSections = class(TCustomHeaderSections) protected function GetItem(Index: Integer): THeaderSection; procedure SetItem(Index: Integer; Value: THeaderSection); public function Add: THeaderSection; property Items[Index: Integer]: THeaderSection read GetItem write SetItem; default; end; { THeaderOrientation } THeaderOrientation = (hoHorizontal, hoVertical); TSectionNotifyEvent = procedure(HeaderControl: TCustomHeaderControl; Section: TCustomHeaderSection) of object; { Resize event is the same as HotTracking if Tracking = True } TCustomHeaderControl = class(TWidgetControl) private FClickable: Boolean; FDragReorder: Boolean; FResizable: Boolean; FTracking: Boolean; FOrientation: THeaderOrientation; FSections: TCustomHeaderSections; FMemStream: TMemoryStream; FOnSectionResize: TSectionNotifyEvent; FOnSectionClick: TSectionNotifyEvent; FOnSectionMoved: TSectionNotifyEvent; FCanvas: TCanvas; FImages: TCustomImageList; FImageChanges: TChangeLink; FDontResubmit: Boolean; procedure OnImageChanges(Sender: TObject); procedure SectionClicked(SectionIndex: Integer); cdecl; procedure SectionSizeChanged(SectionIndex: Integer; OldSize, NewSize: Integer); cdecl; procedure SectionMoved(FromIndex, ToIndex: Integer); cdecl; procedure SetClickable(const Value: Boolean); procedure SetDragReorder(const Value: Boolean); procedure SetOrientation(const Value: THeaderOrientation); procedure SetResizable(const Value: Boolean); procedure SetTracking(const Value: Boolean); procedure SetSections(const Value: TCustomHeaderSections); function GetSections: TCustomHeaderSections; procedure SetImages(const Value: TCustomImageList); protected procedure AssignTo(Dest: TPersistent); override; function GetHandle: QHeaderH; virtual; procedure CreateWidget; override; procedure HookEvents; override; procedure ChangeBounds(ALeft, ATop, AWidth, AHeight: Integer); override; procedure ColumnClicked(Section: TCustomHeaderSection); dynamic; procedure ColumnMoved(Section: TCustomHeaderSection); dynamic; procedure ColumnResized(Section: TCustomHeaderSection); dynamic; procedure ImageListChanged; dynamic; procedure InitWidget; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure RestoreWidgetState; override; procedure SaveWidgetState; override; property Align default alTop; property Canvas: TCanvas read FCanvas; property Clickable: Boolean read FClickable write SetClickable default False; property Handle: QHeaderH read GetHandle; property Height default 19; property DragReorder: Boolean read FDragReorder write SetDragReorder default False; property Images: TCustomImageList read FImages write SetImages; property Resizable: Boolean read FResizable write SetResizable default False; property Sections: TCustomHeaderSections read GetSections write SetSections; property Tracking: Boolean read FTracking write SetTracking default False; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnResize; property OnSectionClick: TSectionNotifyEvent read FOnSectionClick write FOnSectionClick; property OnSectionResize: TSectionNotifyEvent read FOnSectionResize write FOnSectionResize; property OnSectionMoved: TSectionNotifyEvent read FOnSectionMoved write FOnSectionMoved; property Orientation: THeaderOrientation read FOrientation write SetOrientation default hoHorizontal; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; { THeaderControl } THeaderControl = class(TCustomHeaderControl) private procedure SetSections(const Value: THeaderSections); function GetSections: THeaderSections; procedure Init(AHeaderSectionClass: THeaderSectionClass); protected procedure CreateWidget; override; procedure InitWidget; override; public constructor Create(AOwner: TComponent); overload; override; constructor Create(AOwner: TComponent; AHeaderSectionClass: THeaderSectionClass); reintroduce; overload; public destructor Destroy; override; property Canvas; published property Align; property Anchors; property Clickable; property Constraints; property DragMode; property DragReorder; property Height; property Hint; property Images; property Orientation; property ParentShowHint; property PopupMenu; property Resizable; property Sections: THeaderSections read GetSections write SetSections; property ShowHint; property Tracking; property OnConstrainedResize; property OnContextPopup; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnResize; property OnSectionClick; property OnSectionResize; property OnSectionMoved; property OnStartDrag; end; { TListColumn } TListColumn = class(TCustomHeaderSection) private FAlignment: TAlignment; FAutoSize: Boolean; procedure SetCaption(const Value: WideString); procedure SetAutoSize(const Value: Boolean); procedure SetAlignment(const Value: TAlignment); function HeaderIsListHeader: Boolean; {$IF not (defined(LINUX) and defined(VER140))} function GetCaption: WideString; {$IFEND} protected procedure AddSection; override; procedure AssignTo(Dest: TPersistent); override; function GetWidth: Integer; override; procedure Resubmit; override; procedure SetWidthVal(const Value: Integer); override; function ViewControl: TCustomViewControl; public destructor Destroy; override; property Index; published property Alignment: TAlignment read FAlignment write SetAlignment default taLeftJustify; property AllowClick default True; property AllowResize default True; property AutoSize: Boolean read FAutoSize write SetAutoSize default False; {$IF defined(LINUX) and defined(VER140)} property Caption: WideString read FText write SetCaption; {$ELSE} property Caption: WideString read GetCaption write SetCaption; {$IFEND} property MaxWidth default 1000; property MinWidth default 0; property Width; end; { TListColumns } TListColumns = class(TCustomHeaderSections) private function GetItem(Index: Integer): TListColumn; procedure SetItem(Index: Integer; Value: TListColumn); function GetViewControl: TCustomViewControl; protected procedure Added(var Item: TCollectionItem); override; procedure Update(Item: TCollectionItem); override; property ViewControl: TCustomViewControl read GetViewControl; public function Add: TListColumn; property Items[Index: Integer]: TListColumn read GetItem write SetItem; default; end; { TViewItemsList } TListViewItemType = (itDefault, itCheckBox, itRadioButton, itController); TViewItemsList = class(TObjectList) protected function GetItem(Index: Integer): TCustomViewItem; procedure SetItem(Index: Integer; AObject: TCustomViewItem); property Items[Index: Integer]: TCustomViewItem read GetItem write SetItem; default; end; { TCustomViewItems } TCustomViewItems = class(TPersistent) private FUpdateCount: Cardinal; FOwner: TCustomViewControl; FItems: TViewItemsList; function GetItem(Index: Integer): TCustomViewItem; procedure SetItem(Index: Integer; const Value: TCustomViewItem); function GetCount: Integer; protected function GetHandle: QListViewH; function FindViewItem(ItemH: QListViewItemH): TCustomViewItem; procedure SetUpdateState(Updating: Boolean); property Owner: TCustomViewControl read FOwner; property Handle: QListViewH read GetHandle; public constructor Create(AOwner: TCustomViewControl); virtual; destructor Destroy; override; procedure BeginUpdate; procedure Clear; procedure EndUpdate; procedure ChangeItemTypes(NewType: TListViewItemType); function IndexOf(Value: TCustomViewItem): Integer; procedure Delete(Index: Integer); property Count: Integer read GetCount; property Item[Index: Integer]: TCustomViewItem read GetItem write SetItem; default; end; { TListItems } TListItemClass = class of TListItem; TListItems = class(TCustomViewItems) private FListItemClass: TListItemClass; function GetItem(Index: Integer): TListItem; procedure SetItem(Index: Integer; const Value: TListItem); function GetItemsOwner: TCustomListView; protected procedure DefineProperties(Filer: TFiler); override; function FindItem(ItemH: QListViewItemH): TListItem; procedure ReadData(Stream: TStream); procedure WriteData(Stream: TStream); public constructor Create(AOwner: TCustomViewControl); overload; override; constructor Create(AOwner: TCustomViewControl; AItemClass: TListItemClass); reintroduce; overload; function Add: TListItem; function AddItem(Item: TListItem; Index: Integer = -1): TListItem; function Insert(Index: Integer): TListItem; procedure SetItemClass(AListItemClass: TListItemClass); property Item[Index: Integer]: TListItem read GetItem write SetItem; default; property Owner: TCustomListView read GetItemsOwner; end; TItemState = (isNone, isFocused, isSelected, isActivating); TItemStates = set of TItemState; { TCustomViewItem } TCustomViewItem = class(TPersistent) private FSubItems: TStrings; FOwner: TCustomViewItems; FItemType: TListViewItemType; FParent: TCustomViewItem; FNextItem: TCustomViewItem; FPrevItem: TCustomViewItem; FLastChild: TCustomViewItem; FData: Pointer; FChecked: Boolean; FExpandable: Boolean; FSelectable: Boolean; FText: WideString; FStates: TItemStates; FImageIndex: TImageIndex; FDestroying: Boolean; function ViewControlValid: Boolean; procedure DetermineCreationType; procedure SetCaption(const Value: WideString); function GetChildCount: Integer; function GetTotalHeight: Integer; function GetExpanded: Boolean; procedure SetExpanded(const Value: Boolean); function GetHeight: Integer; function GetSelected: Boolean; procedure SetExpandable(const Value: Boolean); procedure SetSelectable(const Value: Boolean); procedure SetSelected(const Value: Boolean); procedure SetChecked(const Value: Boolean); procedure SetItemType(const Value: TListViewItemType); procedure SetParent(const Value: TCustomViewItem); function GetIndex: Integer; procedure SetImageIndex(const Value: TImageIndex); function GetSubItemImages(Column: Integer): Integer; procedure SetSubItemImages(Column: Integer; const Value: Integer); function ItemHook: QClxListViewHooksH; function GetWidth: Integer; procedure SetSubItems(const Value: TStrings); function GetSubItems: TStrings; procedure UpdateImages; function GetFocused: Boolean; procedure SetFocused(const Value: Boolean); protected FHandle: QListViewItemH; procedure Collapse; procedure CreateWidget(AParent, After: TCustomViewItem); procedure DestroyWidget; procedure Expand; function GetHandle: QListViewItemH; function HandleAllocated: Boolean; procedure ImageIndexChange(ColIndex: Integer; NewIndex: Integer); virtual; procedure InsertItem(AItem: TCustomViewItem); function ParentCount: Integer; procedure ReCreateItem; procedure RemoveItem(AItem: TCustomViewItem); procedure Repaint; procedure ResetFields; virtual; function ViewControl: TCustomViewControl; property Caption: WideString read FText write SetCaption; property Checked: Boolean read FChecked write SetChecked; property ChildCount: Integer read GetChildCount; property Data: Pointer read FData write FData; property Expandable: Boolean read FExpandable write SetExpandable; property Expanded: Boolean read GetExpanded write SetExpanded; property Focused: Boolean read GetFocused write SetFocused; property Handle: QListViewItemH read GetHandle; property Height: Integer read GetHeight; property ImageIndex: TImageIndex read FImageIndex write SetImageIndex; property Index: Integer read GetIndex; property ItemType: TListViewItemType read FItemType write SetItemType; property Owner: TCustomViewItems read FOwner; property Parent: TCustomViewItem read FParent write SetParent; property Selectable: Boolean read FSelectable write SetSelectable; property Selected: Boolean read GetSelected write SetSelected; property States: TItemStates read FStates; property SubItemImages[Column: Integer]: Integer read GetSubItemImages write SetSubItemImages; property SubItems: TStrings read GetSubItems write SetSubItems; property TotalHeight: Integer read GetTotalHeight; property Width: Integer read GetWidth; public constructor Create(AOwner: TCustomViewItems; AParent: TCustomViewItem = nil; After: TCustomViewItem = nil); virtual; destructor Destroy; override; procedure AssignTo(Dest: TPersistent); override; procedure Delete; function DisplayRect: TRect; procedure MakeVisible(PartialOK: Boolean); end; { TListItem } TListItem = class(TCustomViewItem) private function GetListView: TCustomListView; function GetOwnerlist: TListItems; function IsEqual(Item: TListItem): Boolean; {$IF not (defined(LINUX) and defined(VER140))} function GetCaption: WideString; procedure SetCaption(Value: WideString); {$IFEND} public destructor Destroy; override; {$IF defined(LINUX) and defined(VER140)} property Caption read FText write SetCaption; {$ELSE} property Caption read GetCaption write SetCaption; {$IFEND} property Checked; property Data; property Focused; property Handle; property ImageIndex; property Index; property ItemType; property ListView: TCustomListView read GetListView; property Owner: TListItems read GetOwnerList; property Selectable; property Selected; property SubItemImages; property SubItems; end; { TItemEditor } TItemEditor = class(TCustomEdit) private FMenuHook: QPopupMenu_hookH; FItem: TCustomViewItem; FEditing: Boolean; FShouldClose: Boolean; FPopup: QPopupMenuH; FFrame: QFrameH; FFrameHooks: QFrame_hookH; FViewControl: TCustomViewControl; procedure FrameDestroyedHook; cdecl; function PopupMenuFilter(Sender: QObjectH; Event: QEventH): Boolean; cdecl; protected procedure ClearMenuHook; procedure CreateWidget; override; procedure Execute; virtual; procedure EditFinished(Accepted: Boolean); virtual; function EventFilter(Sender: QObjectH; Event: QEventH): Boolean; override; procedure HookEvents; override; procedure InitItem; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure KeyUp(var Key: Word; Shift: TShiftState); override; procedure KeyPress(var Key: Char); override; procedure KeyString(var S: WideString; var Handled: Boolean); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; { TCustomViewControl } TItemChange = (ctText, ctImage, ctState); TSortDirection = (sdAscending, sdDescending); TCustomDrawState = set of (cdsSelected, cdsGrayed, cdsDisabled, cdsChecked, cdsFocused, cdsDefault, cdsHot, cdsMarked, cdsIndeterminate); TCustomDrawStage = (cdPrePaint, cdPostPaint); TViewColumnRClickEvent = procedure(Sender: TObject; Column: TListColumn; const Point: TPoint) of object; TViewColumnEvent = procedure(Sender: TObject; Column: TListColumn) of object; TViewColumnClickEvent = TViewColumnEvent; TViewColumnResizeEvent = TViewColumnEvent; TViewColumnMovedEvent = TViewColumnEvent; TCustomDrawViewItemEvent = procedure(Sender: TCustomViewControl; Item: TCustomViewItem; Canvas: TCanvas; const Rect: TRect; State: TCustomDrawState; Stage: TCustomDrawStage; var DefaultDraw: Boolean) of object; TCustomDrawViewSubItemEvent = procedure(Sender: TCustomViewControl; Item: TCustomViewItem; SubItem: Integer; Canvas: TCanvas; const Rect: TRect; State: TCustomDrawState; Stage: TCustomDrawStage; var DefaultDraw: Boolean) of object; TCustomViewControl = class(TFrameControl) private FShowColumnSortIndicators: Boolean; FMultiSelect: Boolean; FRowSelect: Boolean; FShowColumnHeaders: Boolean; FImageList: TCustomImageList; FHeader: TCustomHeaderControl; FMemStream: TMemoryStream; FViewportHandle: QWidgetH; FViewportHooks: QWidget_hookH; FHScrollHooks: QScrollBar_hookH; FVScrollHooks: QScrollBar_hookH; FVScrollHandle: QScrollBarH; FHScrollHandle: QScrollBarH; FItemHooks: QClxListViewHooksH; FOnColumnClick: TViewColumnClickEvent; FColumnDragged: TViewColumnMovedEvent; FColumnResize: TViewColumnResizeEvent; FOnCustomDrawItem: TCustomDrawViewItemEvent; FOnCustomDrawSubItem: TCustomDrawViewSubItemEvent; FOnCustomDrawBranch: TCustomDrawViewItemEvent; FSorted: Boolean; FSortColumn: Integer; FSortDirection: TSortDirection; FOwnerDraw: Boolean; FTimer: TTimer; FAllowEdit: Boolean; FReadOnly: Boolean; FEditor: TItemEditor; FSelCount: Integer; FIndent: Integer; FImageLink: TChangeLink; procedure ImageListChange(Sender: TObject); procedure RepopulateItems; virtual; procedure CheckRemoveEditor; procedure SetIndent(const Value: Integer); function GetHandle: QListViewH; function GetIndent: Integer; procedure SetMultiSelect(const Value: Boolean); function GetMultiSelect: Boolean; function GetRowSelect: Boolean; procedure SetRowSelect(const Value: Boolean); procedure SetImageList(const Value: TCustomImageList); procedure ItemDestroyedHook(AItem: QListViewItemH); cdecl; procedure ItemDestroyed(AItem: QListViewItemH); virtual; procedure ItemPaintHook(p: QPainterH; item: QListViewItemH; column, width, alignment: Integer; var stage: Integer) cdecl; procedure BranchPaintHook(p: QPainterH; item: QListViewItemH; w, y, h: Integer; style: GUIStyle; var stage: Integer) cdecl; procedure ItemChangeHook(item: QListViewItemH; _type: TItemChange); cdecl; procedure ItemChange(item: QListViewItemH; _type: TItemChange); virtual; procedure ItemChangingHook(item: QListViewItemH; _type: TItemChange; var Allow: Boolean); cdecl; procedure ItemChanging(item: QListViewItemH; _type: TItemChange; var Allow: Boolean); virtual; procedure ItemSelectedHook(item: QListViewItemH; wasSelected: Boolean); cdecl; procedure ItemSelected(item: QListViewItemH; wasSelected: Boolean); virtual; procedure ItemExpandingHook(item: QListViewItemH; Expand: Boolean; var Allow: Boolean); cdecl; procedure ItemExpanding(item: QListViewItemH; Expand: Boolean; var Allow: Boolean); virtual; procedure ItemExpandedHook(item: QListViewItemH; Expand: Boolean); cdecl; procedure ItemExpanded(item: QListViewItemH; Expand: Boolean); virtual; procedure ItemCheckedHook(item: QListViewItemH; Checked: Boolean); cdecl; procedure ItemChecked(item: QListViewItemH; Checked: Boolean); virtual; function GetColumnClick: Boolean; procedure SetColumnClick(const Value: Boolean); procedure SetColumns(const Value: TListColumns); function GetColumns: TListColumns; procedure SetShowColumnSortIndicators(const Value: Boolean); function GetColumnResize: Boolean; procedure SetColumnResize(const Value: Boolean); function GetColumnMove: Boolean; procedure SetColumnMove(const Value: Boolean); procedure SetSorted(const Value: Boolean); procedure SetOwnerDraw(const Value: Boolean); procedure TimerIntervalElapsed(Sender: TObject); procedure StartEditTimer; procedure EditItem; procedure ViewportDestroyed; cdecl; protected procedure BeginAutoDrag; override; procedure ColorChanged; override; procedure CreateWidget; override; function CreateEditor: TItemEditor; virtual; function DoCustomDrawViewItem(Item: TCustomViewItem; Canvas: TCanvas; const Rect: TRect; State: TCustomDrawState; Stage: TCustomDrawStage): Boolean; virtual; function DoCustomDrawViewSubItem(Item: TCustomViewItem; SubItem: Integer; Canvas: TCanvas; const Rect: TRect; State: TCustomDrawState; Stage: TCustomDrawStage): Boolean; virtual; function DoCustomDrawViewBranch(Item: TCustomViewItem; Canvas: TCanvas; const Rect: TRect; State: TCustomDrawState; Stage: TCustomDrawStage): Boolean; virtual; procedure DoDrawItem(Item: TCustomViewItem; Canvas: TCanvas; const Rect: TRect; State: TOwnerDrawState); virtual; procedure DoEditing(AItem: TCustomViewItem; var AllowEdit: Boolean); dynamic; procedure DoEdited(AItem: TCustomViewItem; var S: WideString); dynamic; procedure DoGetImageIndex(item: TCustomViewItem); virtual; function EventFilter(Sender: QObjectH; Event: QEventH): Boolean; override; function FindDropTarget: TCustomViewItem; function GetChildHandle: QWidgetH; override; procedure HookEvents; override; procedure InitWidget; override; function IsCustomDrawn: Boolean; virtual; function IsOwnerDrawn: Boolean; virtual; function NeedKey(Key: Integer; Shift: TShiftState; const KeyText: WideString): Boolean; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure ImageListChanged; virtual; procedure SetShowColumnHeaders(const Value: Boolean); procedure UpdateControl; function ViewportHandle: QWidgetH; procedure WidgetDestroyed; override; property ColumnClick: Boolean read GetColumnClick write SetColumnClick default False; property ColumnResize: Boolean read GetColumnResize write SetColumnResize default False; property ColumnMove: Boolean read GetColumnMove write SetColumnMove default True; property Columns: TListColumns read GetColumns write SetColumns; property Images: TCustomImageList read FImageList write SetImageList; property Height default 97; property Indent: Integer read GetIndent write SetIndent default 20; property MultiSelect: Boolean read GetMultiSelect write SetMultiSelect; property OwnerDraw: Boolean read FOwnerDraw write SetOwnerDraw default False; property ParentColor default False; property ReadOnly: Boolean read FReadOnly write FReadOnly default False; property RowSelect: Boolean read GetRowSelect write SetRowSelect default False; property SelCount: Integer read FSelCount default 0; property ShowColumnHeaders: Boolean read FShowColumnHeaders write SetShowColumnHeaders default False; property ShowColumnSortIndicators: Boolean read FShowColumnSortIndicators write SetShowColumnSortIndicators default False; property SortColumn: Integer read FSortColumn write FSortColumn default 0; property SortDirection: TSortDirection read FSortDirection write FSortDirection default sdAscending; property Sorted: Boolean read FSorted write SetSorted default False; property TabStop default True; property Width default 121; property OnColumnClick: TViewColumnClickEvent read FOnColumnClick write FOnColumnClick; property OnColumnDragged: TViewColumnMovedEvent read FColumnDragged write FColumnDragged; property OnColumnResize: TViewColumnResizeEvent read FColumnResize write FColumnResize; property OnCustomDrawBranch: TCustomDrawViewItemEvent read FOnCustomDrawBranch write FOnCustomDrawBranch; property OnCustomDrawItem: TCustomDrawViewItemEvent read FOnCustomDrawItem write FOnCustomDrawItem; property OnCustomDrawSubItem: TCustomDrawViewSubItemEvent read FOnCustomDrawSubItem write FOnCustomDrawSubItem; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure InvertSelection; function IsEditing: Boolean; procedure Sort(Column: Integer; Direction: TSortDirection); property Handle: QListViewH read GetHandle; end; { TCustomListView } TItemFind = (ifData, ifPartialString, ifExactString, ifNearest); TSearchDirection = (sdAbove, sdBelow, sdAll); TViewStyle = (vsList, vsReport); TLVNotifyEvent = procedure (Sender: TObject; Item: TListItem) of object; TLVChangeEvent = procedure (Sender: TObject; Item: TListItem; Change: TItemChange) of object; TLVChangingEvent = procedure (Sender: TObject; Item: TListItem; Change: TItemChange; var AllowChange: Boolean) of object; TLVItemExitViewportEnterEvent = TNotifyEvent; TLVSelectItemEvent = procedure (Sender: TObject; Item: TListItem; Selected: Boolean) of object; TLVItemClickEvent = procedure (Sender: TObject; Button: TMouseButton; Item: TListItem; const Pt: TPoint; ColIndex: Integer) of object; TLVItemDoubleClickEvent = TLVNotifyEvent; TLVEditingEvent = procedure (Sender: TObject; Item: TListItem; var AllowEdit: Boolean) of object; TLVEditedEvent = procedure (Sender: TObject; Item: TListItem; var S: WideString) of object; TLVButtonDownEvent = procedure (Sender: TObject; Button: TMouseButton; Item: TListItem; const Pt: TPoint; ColIndex: Integer) of object; TLVViewportButtonDownEvent = procedure (Sender: TObject; Button: TMouseButton; const Pt: TPoint) of object; TListViewDrawItemEvent = procedure(Sender: TCustomListView; Item: TListItem; Canvas: TCanvas; const Rect: TRect; State: TOwnerDrawState) of object; TCustomListView = class(TCustomViewControl) private FSelected: TListItem; FItems: TListItems; FCheckBoxes: Boolean; FOnInsert: TLVNotifyEvent; FOnChange: TLVChangeEvent; FOnChanging: TLVChangingEvent; FOnDeletion: TLVNotifyEvent; FOnSelectItem: TLVSelectItemEvent; FOnItemClick: TLVItemClickEvent; FOnItemDoubleClick: TLVItemDoubleClickEvent; FOnItemEnter: TLVNotifyEvent; FOnItemExitViewportEnter: TLVItemExitViewportEnterEvent; FOnMouseDown: TLVButtonDownEvent; FOnViewportMouseDown: TLVViewportButtonDownEvent; FOnEditing: TLVEditingEvent; FOnEdited: TLVEditedEvent; FViewStyle: TViewStyle; FDownsHooked: Boolean; FOnGetImageIndex: TLVNotifyEvent; FOnDrawItem: TListViewDrawItemEvent; procedure RepopulateItems; override; procedure SetItems(const Value: TListItems); procedure SetCheckBoxes(const Value: Boolean); procedure UpdateItemTypes; procedure HookMouseDowns; procedure DoItemDoubleClick(ListItem: QListViewItemH); cdecl; procedure DoItemClick(Button: Integer; ListItem: QListViewItemH; Pt: PPoint; ColIndex: Integer); cdecl; procedure DoOnItemEnter(ListItem: QListViewItemH); cdecl; procedure DoOnItemExitViewportEnter; cdecl; procedure DoLVMouseDown(Button: Integer; ListItem: QListViewItemH; Pt: PPoint; ColIndex: Integer); cdecl; procedure SetOnItemDoubleClick(const Value: TLVItemDoubleClickEvent); procedure SetOnItemEnter(const Value: TLVNotifyEvent); procedure SetOnItemExitViewportEnter(const Value: TLVItemExitViewportEnterEvent); procedure SetOnMouseDown(const Value: TLVButtonDownEvent); procedure SetOnViewportButtonDown(const Value: TLVViewportButtonDownEvent); procedure SetViewStyle(const Value: TViewStyle); function GetSelected: TListItem; procedure SetSelected(const Value: TListItem); function GetItemFocused: TListItem; procedure SetItemFocused(const Value: TListItem); procedure SetTopItem(const AItem: TListItem); function GetTopItem: TListItem; protected procedure DoDrawItem(Item: TCustomViewItem; Canvas: TCanvas; const Rect: TRect; State: TOwnerDrawState); override; procedure DoEdited(AItem: TCustomViewItem; var S: WideString); override; procedure DoEditing(AItem: TCustomViewItem; var AllowEdit: Boolean); override; procedure DoGetImageIndex(item: TCustomViewItem); override; function GetDropTarget: TListItem; procedure HookEvents; override; procedure ImageListChanged; override; procedure Init(AListItemClass: TListItemClass); virtual; procedure InitWidget; override; function IsOwnerDrawn: Boolean; override; procedure ItemChange(item: QListViewItemH; _type: TItemChange); override; procedure ItemChanging(item: QListViewItemH; _type: TItemChange; var Allow: Boolean); override; procedure ItemChecked(item: QListViewItemH; Checked: Boolean); override; procedure ItemDestroyed(AItem: QListViewItemH); override; procedure ItemSelected(item: QListViewItemH; wasSelected: Boolean); override; procedure RestoreWidgetState; override; procedure SaveWidgetState; override; property CheckBoxes: Boolean read FCheckBoxes write SetCheckBoxes default False; property Height default 150; property Items: TListItems read FItems write SetItems; property ReadOnly default False; property SortDirection default sdAscending; property ViewStyle: TViewStyle read FViewStyle write SetViewStyle default vsList; property OnChange: TLVChangeEvent read FOnChange write FOnChange; property OnChanging: TLVChangingEvent read FOnChanging write FOnChanging; property OnDeletion: TLVNotifyEvent read FOnDeletion write FOnDeletion; property OnDrawItem: TListViewDrawItemEvent read FOnDrawItem write FOnDrawItem; property OnEdited: TLVEditedEvent read FOnEdited write FOnEdited; property OnEditing: TLVEditingEvent read FOnEditing write FOnEditing; property OnGetImageIndex: TLVNotifyEvent read FOnGetImageIndex write FOnGetImageIndex; property OnInsert: TLVNotifyEvent read FOnInsert write FOnInsert; property OnItemClick: TLVItemClickEvent read FOnItemClick write FOnItemClick; property OnItemDoubleClick: TLVItemDoubleClickEvent read FOnItemDoubleClick write SetOnItemDoubleClick; property OnItemEnter: TLVNotifyEvent read FOnItemEnter write SetOnItemEnter; property OnItemExitViewportEnter: TLVItemExitViewportEnterEvent read FOnItemExitViewportEnter write SetOnItemExitViewportEnter; property OnItemMouseDown: TLVButtonDownEvent read FOnMouseDown write SetOnMouseDown; property OnSelectItem: TLVSelectItemEvent read FOnSelectItem write FOnSelectItem; property OnViewPortMouseDown: TLVViewportButtonDownEvent read FOnViewportMouseDown write SetOnViewportButtonDown; public constructor Create(AOwner: TComponent); overload; override; constructor Create(AOwner: TComponent; AListItemClass: TListItemClass); reintroduce; overload; destructor Destroy; override; function AlphaSort: Boolean; function FindData(StartIndex: Integer; Value: Pointer; Inclusive, Wrap: Boolean): TListItem; function FindCaption(StartIndex: Integer; const Value: WideString; Partial, Inclusive, Wrap: Boolean): TListItem; function GetItemAt(X, Y: Integer): TListItem; function GetNearestItem(const Point: TPoint; Direction: TSearchDirection): TListItem; function GetNextItem(StartItem: TListItem; Direction: TSearchDirection; States: TItemStates): TListItem; procedure Scroll(DX, DY: Integer); procedure UpdateItems(FirstIndex, LastIndex: Integer); property DropTarget: TListItem read GetDropTarget; property ItemFocused: TListItem read GetItemFocused write SetItemFocused; property Selected: TListItem read GetSelected write SetSelected; property TopItem: TListItem read GetTopItem write SetTopItem; end; { TListView } TListView = class(TCustomListView) public property SortColumn; published property Align; property Anchors; property BorderStyle default bsSunken3d; property CheckBoxes default False; property Color; property ColumnClick default True; property ColumnMove default True; property ColumnResize default True; property Columns; property Constraints; property DragMode; property Enabled; property Font; property Height; property Hint; property Images; property Items; property MultiSelect default False; property OwnerDraw; property RowSelect default False; property ParentColor; property ParentFont; property ParentShowHint; property PopupMenu; property ReadOnly; property SelCount; property ShowColumnSortIndicators; property ShowHint; property SortDirection; property Sorted; property TabOrder; property TabStop; property ViewStyle; property Visible; property Width; property OnChange; property OnChanging; property OnClick; property OnColumnClick; property OnColumnDragged; property OnColumnResize; property OnContextPopup; property OnCustomDrawItem; property OnCustomDrawSubItem; property OnDblClick; property OnDeletion; property OnDragDrop; property OnDragOver; property OnDrawItem; property OnEdited; property OnEditing; property OnEndDrag; property OnEnter; property OnExit; property OnGetImageIndex; property OnInsert; property OnItemClick; property OnItemDoubleClick; property OnItemEnter; property OnItemExitViewportEnter; property OnItemMouseDown; property OnKeyDown; property OnKeyPress; property OnKeyString; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnResize; property OnSelectItem; property OnStartDrag; property OnViewPortMouseDown; end; { ETreeViewError } ETreeViewError = class(Exception); { TTreeNodes } TNodeAttachMode = (naAdd, naAddFirst, naAddChild, naAddChildFirst, naInsert); TAddMode = (taAddFirst, taAdd, taInsert); TTreeNodeClass = class of TTreeNode; TTreeNodes = class(TCustomViewItems) private FNodeClass: TTreeNodeClass; function GetItem(Index: Integer): TTreeNode; function GetNodesOwner: TCustomTreeView; procedure ReadData(Stream: TStream); procedure WriteData(Stream: TStream); protected function CreateNode(ParentNode: TTreeNode = nil; AfterNode: TTreeNode = nil): TTreeNode; procedure DefineProperties(Filer: TFiler); override; function InternalAddObject(Node: TTreeNode; const S: WideString; Ptr: Pointer; AddMode: TAddMode): TTreeNode; function FindItem(ItemH: QListViewItemH): TTreeNode; function FindPrevSibling(ANode: TTreeNode): TTreeNode; public function Add(Node: TTreeNode; const S: WideString): TTreeNode; function AddChild(Node: TTreeNode; const S: WideString): TTreeNode; function AddChildFirst(Node: TTreeNode; const S: WideString): TTreeNode; function AddChildObject(Node: TTreeNode; const S: WideString; Ptr: Pointer): TTreeNode; function AddChildObjectFirst(Node: TTreeNode; const S: WideString; Ptr: Pointer): TTreeNode; function AddFirst(Node: TTreeNode; const S: WideString): TTreeNode; function AddObject(Node: TTreeNode; const S: WideString; Ptr: Pointer): TTreeNode; function AddObjectFirst(Node: TTreeNode; const S: WideString; Ptr: Pointer): TTreeNode; procedure Assign(Dest: TPersistent); override; procedure Clear; procedure Delete(Node: TTreeNode); function GetFirstNode: TTreeNode; function GetNode(ItemH: QListViewItemH): TTreeNode; function Insert(Node: TTreeNode; const S: WideString): TTreeNode; function InsertObject(Node: TTreeNode; const S: WideString; Ptr: Pointer): TTreeNode; procedure SetNodeClass(NewNodeClass: TTreeNodeClass); property Item[Index: Integer]: TTreeNode read GetItem; default; property Owner: TCustomTreeView read GetNodesOwner; end; { TTreeNode } PNodeInfo = ^TNodeInfo; TNodeInfo = packed record ImageIndex: Integer; SelectedIndex: Integer; StateIndex: Integer; SubItemCount: Integer; Data: Pointer; Count: Integer; Text: string[255]; end; TTreeNode = class(TCustomViewItem) private FDeleting: Boolean; FSelectedIndex: Integer; function DoCanExpand(Expand: Boolean): Boolean; procedure ExpandItem(Expand: Boolean; Recurse: Boolean); function GetCount: Integer; function GetItem(Index: Integer): TTreeNode; function GetLevel: Integer; function GetParent: TTreeNode; function GetIndex: Integer; function GetTreeView: TCustomTreeView; function IsNodeVisible: Boolean; function IsEqual(Node: TTreeNode): Boolean; procedure SetItem(Index: Integer; const Value: TTreeNode); function GetNodeOwner: TTreeNodes; procedure SetNodeParent(const Value: TTreeNode); procedure SetSelectedIndex(const Value: Integer); function GetDropTarget: Boolean; {$IF not (defined(LINUX) and defined(VER140))} function GetSelected: Boolean; procedure SetSelected(const Value: Boolean); function GetExpandable: Boolean; procedure SetExpandable(const Value: Boolean); function GetCaption: WideString; procedure SetCaption(const Value: WideString); {$IFEND} protected function CompareCount(CompareMe: Integer): Boolean; function GetAbsoluteIndex: Integer; procedure ImageIndexChange(ColIndex: Integer; NewIndex: Integer); override; procedure ReadData(Stream: TStream; Info: PNodeInfo); procedure WriteData(Stream: TStream; Info: PNodeInfo); public constructor Create(AOwner: TCustomViewItems; AParent: TCustomViewItem = nil; After: TCustomViewItem = nil); override; destructor Destroy; override; procedure AssignTo(Dest: TPersistent); override; procedure Collapse(Recurse: Boolean); function AlphaSort(Ascending: Boolean): Boolean; procedure Delete; procedure DeleteChildren; function EditText: Boolean; procedure Expand(Recurse: Boolean); function getFirstChild: TTreeNode; function GetLastChild: TTreeNode; function GetNext: TTreeNode; function GetNextChild(Value: TTreeNode): TTreeNode; function getNextSibling: TTreeNode; function GetNextVisible: TTreeNode; function GetPrev: TTreeNode; function GetPrevChild(Value: TTreeNode): TTreeNode; function getPrevSibling: TTreeNode; function GetPrevVisible: TTreeNode; function HasAsParent(Value: TTreeNode): Boolean; function IndexOf(Value: TTreeNode): Integer; procedure MoveTo(Destination: TTreeNode; Mode: TNodeAttachMode); virtual; property AbsoluteIndex: Integer read GetAbsoluteIndex; property Checked; property Count: Integer read GetCount; property Data; property Deleting: Boolean read FDeleting; property DropTarget: Boolean read GetDropTarget; property Focused: Boolean read GetSelected write SetSelected; property Expanded; property Handle; {$IF defined(LINUX) and defined(VER140)} property HasChildren: Boolean read FExpandable write SetExpandable; {$ELSE} property HasChildren: Boolean read GetExpandable write SetExpandable; {$IFEND} property Height; property ImageIndex; property Index: Integer read GetIndex; property IsVisible: Boolean read IsNodeVisible; property ItemType; property Item[Index: Integer]: TTreeNode read GetItem write SetItem; default; property Level: Integer read GetLevel; property Owner: TTreeNodes read GetNodeOwner; property Parent: TTreeNode read GetParent write SetNodeParent; property Selected; property SelectedIndex: Integer read FSelectedIndex write SetSelectedIndex; {$IF defined(LINUX) and defined(VER140)} property Text: WideString read FText write SetCaption; {$ELSE} property Text: WideString read GetCaption write SetCaption; {$IFEND} property TotalHeight; property TreeView: TCustomTreeView read GetTreeView; property Selectable; property SubItemImages; property SubItems; end; { TCustomTreeView } TSortType = (stNone, stText); TTVItemNotifyEvent = procedure(Sender: TObject; Node: TTreeNode) of object; TTVDeletedEvent = TTVItemNotifyEvent; TTVItemEnterEvent = TTVItemNotifyEvent; TTVItemExitViewportEnterEvent = TNotifyEvent; TTVChangedEvent = TTVItemNotifyEvent; TTVChangingEvent = procedure(Sender: TObject; Node: TTreeNode; var AllowChange: Boolean) of object; TTVExpandingEvent = procedure(Sender: TObject; Node: TTreeNode; var AllowExpansion: Boolean) of object; TTVCollapsingEvent = procedure(Sender: TObject; Node: TTreeNode; var AllowCollapse: Boolean) of object; TTVExpandedEvent = TTVItemNotifyEvent; TTVCollapsedEvent = TTVExpandedEvent; TTVSelectItemEvent = procedure(Sender: TObject; Node: TTreeNode; Selected: Boolean) of object; TTVEditingEvent = procedure (Sender: TObject; Node: TTreeNode; var AllowEdit: Boolean) of object; TTVEditedEvent = procedure (Sender: TObject; Node: TTreeNode; var S: WideString) of object; TTVItemClickEvent = procedure (Sender: TObject; Button: TMouseButton; Node: TTreeNode; const Pt: TPoint) of object; TTVItemDoubleClickEvent = procedure (Sender: TObject; Node: TTreeNode) of object; TTVButtonDownEvent = procedure (Sender: TObject; Button: TMouseButton; Node: TTreeNode; const Pt: TPoint) of object; TTVViewportButtonDownEvent = procedure (Sender: TObject; Button: TMouseButton; const Pt: TPoint) of object; TCustomTreeView = class(TCustomViewControl) private FTreeNodes: TTreeNodes; FSelectedNode: TTreeNode; FLastNode: TTreeNode; FSortType: TSortType; FShowButtons: Boolean; FMemStream: TMemoryStream; FOnChange: TTVChangedEvent; FOnChanging: TTVChangingEvent; FOnCollapsing: TTVCollapsingEvent; FOnDeletion: TTVExpandedEvent; FOnCollapsed: TTVExpandedEvent; FOnExpanded: TTVExpandedEvent; FOnExpanding: TTVExpandingEvent; FAutoExpand: Boolean; FOnMouseDown: TTVButtonDownEvent; FOnInsert: TTVDeletedEvent; FOnItemClick: TTVItemClickEvent; FOnItemDoubleClick: TTVItemDoubleClickEvent; FOnItemEnter: TTVItemEnterEvent; FOnItemExitViewportEnter: TTVItemExitViewportEnterEvent; FOnViewportMouseDown: TTVViewportButtonDownEvent; FOnEdited: TTVEditedEvent; FOnEditing: TTVEditingEvent; FOnGetImageIndex: TTVExpandedEvent; FOnGetSelectedIndex: TTVExpandedEvent; FFullExpansion: Boolean; FItemMargin: Integer; procedure RepopulateItems; override; procedure DoAutoExpand(ExpandedNode: TTreeNode); procedure SetSortType(const Value: TSortType); procedure SetAutoExpand(const Value: Boolean); function GetSelected: TTreeNode; procedure SetSelected(const Value: TTreeNode); procedure SetItemMargin(const Value: Integer); procedure HookMouseDowns; procedure DoItemClick(p1: Integer; p2: QListViewItemH; p3: PPoint; p4: Integer); cdecl; procedure DoItemDoubleClick(p1: QListViewItemH); cdecl; procedure DoOnItemEnter(item: QListViewItemH); cdecl; procedure DoOnItemExitViewportEnter; cdecl; procedure DoOnMouseDown(p1: Integer; p2: QListViewItemH; p3: PPoint; p4: Integer); cdecl; procedure SetOnItemDoubleClick(const Value: TTVItemDoubleClickEvent); procedure SetOnItemEnter(const Value: TTVItemEnterEvent); procedure SetOnItemExitViewportEnter(const Value: TTVItemExitViewportEnterEvent); procedure SetOnMouseDown(const Value: TTVButtonDownEvent); procedure SetOnViewportButtonDown(const Value: TTVViewportButtonDownEvent); procedure SetShowButtons(const Value: Boolean); procedure SetItems(const Value: TTreeNodes); procedure SetTopItem(const AItem: TTreeNode); function GetTopItem: TTreeNode; procedure ItemChanging(item: QListViewItemH; _type: TItemChange; var Allow: Boolean); override; procedure ItemDestroyed(AItem: QListViewItemH); override; procedure ItemExpanding(item: QListViewItemH; Expand: Boolean; var Allow: Boolean); override; procedure ItemExpanded(item: QListViewItemH; Expand: Boolean); override; procedure ItemChecked(item: QListViewItemH; Checked: Boolean); override; procedure ItemSelected(item: QListViewItemH; wasSelected: Boolean); override; protected function CanCollapse(Node: TTreeNode): Boolean; dynamic; function CanExpand(Node: TTreeNode): Boolean; dynamic; procedure Change(Node: TTreeNode); dynamic; procedure Collapse(Node: TTreeNode); dynamic; procedure Delete(Node: TTreeNode); dynamic; procedure DoEdited(AItem: TCustomViewItem; var S: WideString); override; procedure DoEditing(AItem: TCustomViewItem; var AllowEdit: Boolean); override; procedure DoGetImageIndex(item: TCustomViewItem); override; function EventFilter(Sender: QObjectH; Event: QEventH): Boolean; override; function GetDropTarget: TTreeNode; procedure Expand(Node: TTreeNode); dynamic; procedure HookEvents; override; procedure ImageListChanged; override; procedure Init(ANodeClass: TTreeNodeClass); virtual; procedure InitWidget; override; function IsCustomDrawn: Boolean; override; procedure Loaded; override; procedure RestoreWidgetState; override; procedure SaveWidgetState; override; property AutoExpand: Boolean read FAutoExpand write SetAutoExpand default False; property ItemMargin: Integer read FItemMargin write SetItemMargin default 1; property Items: TTreeNodes read FTreeNodes write SetItems; property ShowButtons: Boolean read FShowButtons write SetShowButtons default True; property SortType: TSortType read FSortType write SetSortType default stNone; property OnChange: TTVChangedEvent read FOnChange write FOnChange; property OnChanging: TTVChangingEvent read FOnChanging write FOnChanging; property OnCollapsed: TTVExpandedEvent read FOnCollapsed write FOnCollapsed; property OnCollapsing: TTVCollapsingEvent read FOnCollapsing write FOnCollapsing; property OnDeletion: TTVExpandedEvent read FOnDeletion write FOnDeletion; property OnEdited: TTVEditedEvent read FOnEdited write FOnEdited; property OnEditing: TTVEditingEvent read FOnEditing write FOnEditing; property OnExpanding: TTVExpandingEvent read FOnExpanding write FOnExpanding; property OnExpanded: TTVExpandedEvent read FOnExpanded write FOnExpanded; property OnGetImageIndex: TTVExpandedEvent read FOnGetImageIndex write FOnGetImageIndex; property OnGetSelectedIndex: TTVExpandedEvent read FOnGetSelectedIndex write FOnGetSelectedIndex; property OnInsert: TTVDeletedEvent read FOnInsert write FOnInsert; property OnItemClick: TTVItemClickEvent read FOnItemClick write FOnItemClick; property OnItemDoubleClick: TTVItemDoubleClickEvent read FOnItemDoubleClick write SetOnItemDoubleClick; property OnItemEnter: TTVItemEnterEvent read FOnItemEnter write SetOnItemEnter; property OnItemExitViewportEnter: TTVItemExitViewportEnterEvent read FOnItemExitViewportEnter write SetOnItemExitViewportEnter; property OnItemMouseDown: TTVButtonDownEvent read FOnMouseDown write SetOnMouseDown; property OnViewPortMouseDown: TTVViewportButtonDownEvent read FOnViewportMouseDown write SetOnViewportButtonDown; public constructor Create(AOwner: TComponent); overload; override; constructor Create(AOwner: TComponent; ANodeClass: TTreeNodeClass); reintroduce; overload; destructor Destroy; override; function AlphaSort: Boolean; procedure FullCollapse; procedure FullExpand; function GetNodeAt(X, Y: Integer): TTreeNode; procedure LoadFromFile(const FileName: string); procedure LoadFromStream(Stream: TStream); procedure SaveToFile(const FileName: string); procedure SaveToStream(Stream: TStream); procedure SelectAll(Select: Boolean); property DropTarget: TTreeNode read GetDropTarget; property Selected: TTreeNode read GetSelected write SetSelected; property TopItem: TTreeNode read GetTopItem write SetTopItem; end; { TTreeView } TTreeView = class(TCustomTreeView) {$IF not (defined(LINUX) and defined(VER140))} private function GetSelCount: Integer; {$IFEND} public property SortColumn; published property Align; property Anchors; property AutoExpand default False; property BorderStyle default bsSunken3d; property Color; property ColumnClick default True; property ColumnMove default True; property ColumnResize default True; property Columns; property Constraints; property DragMode; property Enabled; property Font; property Height; property Hint; property Images; property ItemMargin; property Items; property Indent; property MultiSelect default False; property ParentColor; property ParentFont; property ParentShowHint; property PopupMenu; property ReadOnly; property RowSelect; {$IF defined(LINUX) and defined(VER140)} property SelectionCount: Integer read FSelCount default 0; {$ELSE} property SelectionCount: Integer read GetSelCount default 0; {$IFEND} property ShowColumnHeaders; property ShowColumnSortIndicators; property ShowButtons; property ShowHint; property Sorted default False; property SortType; property TabOrder; property TabStop; property Visible; property Width; property OnChange; property OnChanging; property OnClick; property OnCollapsed; property OnCollapsing; property OnColumnClick; property OnColumnDragged; property OnColumnResize; property OnContextPopup; property OnCustomDrawBranch; property OnCustomDrawItem; property OnCustomDrawSubItem; property OnDblClick; property OnDeletion; property OnDragDrop; property OnDragOver; property OnEdited; property OnEditing; property OnEndDrag; property OnEnter; property OnExit; property OnExpanding; property OnExpanded; property OnGetImageIndex; property OnGetSelectedIndex; property OnInsert; property OnItemClick; property OnItemDoubleClick; property OnItemEnter; property OnItemExitViewportEnter; property OnKeyDown; property OnKeyPress; property OnKeyString; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; property OnItemMouseDown; property OnViewPortMouseDown; end; { TIconView } TArrangement = (arLeftToRight, arTopToBottom); TResizeMode = (rmFixed, rmAdjust); TItemTextPos = (itpBottom, itpRight); TCustomIconView = class; TIconViewItems = class; TIconView = class; TIconViewItem = class(TPersistent) private FOwner: TIconViewItems; FDestroying: Boolean; FImageIndex: TImageIndex; FStates: TItemStates; FAllowRename: Boolean; FCaption: WideString; FSelectable: Boolean; procedure SetAllowRename(const Value: Boolean); function GetHandle: QIconViewItemH; procedure SetCaption(const Value: WideString); function GetIndex: Integer; function GetSelected: Boolean; procedure SetSelected(const Value: Boolean); procedure SetSelectable(const Value: Boolean); function IconViewValid: Boolean; procedure UpdateImage; procedure SetImageIndex(const Value: TImageIndex); procedure SetStates(const Value: TItemStates); function GetIconView: TCustomIconView; function GetLeft: Integer; function GetTop: Integer; function GetWidth: Integer; function GetHeight: Integer; protected FHandle: QIconViewItemH; procedure CreateWidget(AfterItem: TIconViewItem); procedure InitWidget; procedure DestroyWidget; function HandleAllocated: Boolean; function IsEqual(AItem: TIconViewItem): Boolean; property IconView: TCustomIconView read GetIconView; public constructor Create(AOwner: TIconViewItems; AfterItem: TIconViewItem = nil); destructor Destroy; override; function BoundingRect: TRect; function IconRect: TRect; procedure MakeVisible; procedure Move(const Pt: TPoint); procedure MoveBy(const Pt: TPoint); procedure Repaint; function TextRect: TRect; property AllowRename: Boolean read FAllowRename write SetAllowRename default True; property Caption: WideString read FCaption write SetCaption; property Handle: QIconViewItemH read GetHandle; property Height: Integer read GetHeight; property ImageIndex: TImageIndex read FImageIndex write SetImageIndex; property Index: Integer read GetIndex; property Left: Integer read GetLeft; property Selectable: Boolean read FSelectable write SetSelectable default True; property Selected: Boolean read GetSelected write SetSelected; property States: TItemStates read FStates write SetStates; property Top: Integer read GetTop; property Width: Integer read GetWidth; end; { TiconViewItems } TIconViewItemClass = class of TIconViewItem; TIconViewItems = class(TPersistent) private FOwner: TCustomIconView; FIconViewItemClass: TIconViewItemClass; FUpdateCount: Integer; FItems: TObjectList; protected procedure DefineProperties(Filer: TFiler); override; function FindItem(ItemH: QIconViewItemH): TIconViewItem; function GetCount: Integer; function GetItem(Index: Integer): TIconViewItem; function IconViewHandle: QIconViewH; procedure ReadData(Stream: TStream); procedure SetItem(Index: Integer; AObject: TIconViewItem); procedure SetUpdateState(Updating: Boolean); virtual; procedure UpdateImages; procedure WriteData(Stream: TStream); public constructor Create(AOwner: TCustomIconView); overload; constructor Create(AOwner: TCustomIconView; AItemClass: TIconViewItemClass); overload; destructor Destroy; override; function Add: TIconViewItem; procedure BeginUpdate; procedure Clear; procedure Delete(Index: Integer); procedure EndUpdate; function IndexOf(Value: TIconViewItem): Integer; function Insert(Index: Integer): TIconViewItem; procedure SetItemClass(AItemClass: TIconViewItemClass); property Count: Integer read GetCount; property Item[Index: Integer]: TIconViewItem read GetItem write SetItem; default; property Owner: TCustomIconView read FOwner; end; { TIconOptions } TIconArrangement = (iaTop, iaLeft); TIconOptions = class(TPersistent) private FAutoArrange: Boolean; FArrangement: TIconArrangement; FWrapText: Boolean; FIconView: TCustomIconView; procedure SetArrangement(Value: TIconArrangement); procedure SetAutoArrange(Value: Boolean); procedure SetWrapText(Value: Boolean); public constructor Create(AOwner: TCustomIconView); published property Arrangement: TIconArrangement read FArrangement write SetArrangement default ialeft; property AutoArrange: Boolean read FAutoArrange write SetAutoArrange default True; property WrapText: Boolean read FWrapText write SetWrapText default True; end; { TCustomIconView } TIVItemMouseEvent = procedure(Sender: TObject; Button: TMouseButton; Item: TIconViewItem; const Pt: TPoint) of object; TIVMouseEvent = procedure(Sender: TObject; Button: TMouseButton; const Pt: TPoint) of object; TIVItemEvent = procedure(Sender: TObject; Item: TIconViewItem) of object; TIVSelectItemEvent = procedure(Sender: TObject; Item: TIconViewItem; Selected: Boolean) of object; TIVItemDoubleClickEvent = TIVItemEvent; TIVItemExitViewportEnterEvent = TNotifyEvent; TIVItemEnterEvent = TIVItemEvent; TIVEditedEvent = procedure(Sender: TObject; Item: TIconViewItem; const NewName: WideString) of object; TIVItemClickEvent = procedure(Sender: TObject; Item: TIconViewItem) of object; TIVViewportClickedEvent = TIVMouseEvent; TIVChangeEvent = procedure (Sender: TObject; Item: TIconViewItem; Change: TItemChange) of object; TIVChangingEvent = procedure (Sender: TObject; Item: TIconViewItem; Change: TItemChange; var AllowChange: Boolean) of object; TCustomIconView = class(TFrameControl) private FItemsMovable: Boolean; FMultiSelect: Boolean; FResizeMode: TResizeMode; FShowToolTips: Boolean; FSort: Boolean; FSpacing: Integer; FSelCount: Integer; FTextPosition: TItemTextPos; FSortDirection: TSortDirection; FItemHooks: QClxIconViewHooksH; FIconViewItems: TIconViewItems; FOnItemClicked: TIVItemClickEvent; FOnItemDoubleClick: TIVItemDoubleClickEvent; FOnItemEnter: TIVItemEnterEvent; FOnItemExitViewportEnter: TIVItemExitViewportEnterEvent; FOnEdited: TIVEditedEvent; FOnItemChange: TIVChangeEvent; FOnItemChanging: TIVChangingEvent; FImages: TCustomImageList; FImageChanges: TChangeLink; FViewportHandle: QWidgetH; FViewportHooks: QWidget_hookH; FOnSelectItem: TIVSelectItemEvent; FIconOptions: TIconOptions; FSelected: TIconViewItem; procedure OnImageChanges(Sender: TObject); function GetHandle: QIconViewH; procedure SetMultiSelect(const Value: Boolean); procedure SetSpacing(const Value: Integer); procedure SetTextPos(const Value: TItemTextPos); procedure SetResizeMode(const Value: TResizeMode); procedure SetShowToolTips(const Value: Boolean); procedure SetIconViewItems(const Value: TIconViewItems); procedure SetSort(const Value: Boolean); procedure SetSortDirection(const Value: TSortDirection); procedure SetItemsMovable(const Value: Boolean); procedure DoItemClicked(item: QIconViewItemH); cdecl; procedure DoItemDoubleClicked(item: QIconViewItemH); cdecl; procedure DoItemEnter(item: QIconViewItemH); cdecl; procedure DoViewportEnter; cdecl; procedure DoEdited(item: QIconViewItemH; p2: PWideString); cdecl; procedure ItemDestroyedHook(item: QIconViewItemH); cdecl; procedure ChangingHook(item: QIconViewItemH; _type: TItemChange; var Allow: Boolean); cdecl; procedure ChangeHook(item: QIconViewItemH; _type: TItemChange); cdecl; procedure SelectedHook(item: QIconViewItemH; Value: Boolean); cdecl; procedure PaintCellHook(p: QPainterH; item: QIconViewItemH; cg: QColorGroupH; var stage: Integer); cdecl; procedure PaintFocusHook(p: QPainterH; item: QIconViewItemH; cg: QColorGroupH; var stage: Integer); cdecl; procedure SetOnItemClicked(const Value: TIVItemClickEvent); procedure SetOnItemDoubleClick(const Value: TIVItemDoubleClickEvent); procedure SetOnItemEnter(const Value: TIVItemEnterEvent); procedure SetOnItemExitViewportEnter(const Value: TIVItemExitViewportEnterEvent); procedure SetOnEdited(const Value: TIVEditedEvent); procedure SetImages(const Value: TCustomImageList); procedure SetSelected(const Value: TIconViewItem); procedure SetIconOptions(const Value: TIconOptions); protected procedure BeginAutoDrag; override; procedure ColorChanged; override; procedure CreateWidget; override; procedure DoChange(Item: TIconViewItem; Change: TItemChange); dynamic; procedure DoChanging(Item: TIconViewItem; Change: TItemChange; var AllowChange: Boolean); dynamic; procedure HookEvents; override; procedure ImageListChanged; dynamic; procedure InitWidget; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; function ViewportHandle: QWidgetH; procedure WidgetDestroyed; override; property BorderStyle default bsSunken3d; property Height default 97; property IconOptions: TIconOptions read FIconOptions write SetIconOptions; property Images: TCustomImageList read FImages write SetImages; property Items: TIconViewItems read FIconViewItems write SetIconViewItems; property ItemsMovable: Boolean read FItemsMovable write SetItemsMovable default True; property MultiSelect: Boolean read FMultiSelect write SetMultiSelect default False; property ParentColor default False; property ResizeMode: TResizeMode read FResizeMode write SetResizeMode default rmAdjust; property SelCount: Integer read FSelCount; property Selected: TIconViewItem read FSelected write SetSelected; property ShowToolTips: Boolean read FShowToolTips write SetShowToolTips default True; property Sort: Boolean read FSort write SetSort default False; property SortDirection: TSortDirection read FSortDirection write SetSortDirection default sdAscending; property Spacing: Integer read FSpacing write SetSpacing default 5; property TabStop default True; property TextPosition: TItemTextPos read FTextPosition write SetTextPos default itpBottom; property Width default 121; property OnChange: TIVChangeEvent read FOnItemChange write FOnItemChange; property OnChanging: TIVChangingEvent read FOnItemChanging write FOnItemChanging; property OnItemDoubleClick: TIVItemDoubleClickEvent read FOnItemDoubleClick write SetOnItemDoubleClick; property OnItemExitViewportEnter: TIVItemExitViewportEnterEvent read FOnItemExitViewportEnter write SetOnItemExitViewportEnter; property OnItemEnter: TIVItemEnterEvent read FOnItemEnter write SetOnItemEnter; property OnEdited: TIVEditedEvent read FOnEdited write SetOnEdited; property OnItemClicked: TIVItemClickEvent read FOnItemClicked write SetOnItemClicked; property OnSelectItem: TIVSelectItemEvent read FOnSelectItem write FOnSelectItem; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Handle: QIconViewH read GetHandle; procedure Clear; procedure SelectAll(Select: Boolean); function FindItemByText(const Str: WideString): TIconViewItem; function FindItemByPoint(const Pt: TPoint): TIconViewItem; function GetNextItem(StartItem: TIconViewItem; Direction: TSearchDirection; States: TItemStates): TIconViewItem; procedure RepaintItem(AItem: TIconViewItem); procedure EnsureItemVisible(AItem: TIconViewItem); function FindVisibleItem(First: Boolean; const ARect: TRect): TIconViewItem; procedure UpdateControl; procedure UpdateItems(FirstIndex, LastIndex: Integer); end; { TIconView } TIconView = class(TCustomIconView) public property SelCount; property Selected; published property Align; property Anchors; property BorderStyle; property Color; property Constraints; property DragMode; property Height; property Hint; property IconOptions; property Images; property Items; property ItemsMovable; property MultiSelect; property ParentColor; property ParentShowHint; property PopupMenu; property ResizeMode; property ShowHint; property ShowToolTips; property Sort; property SortDirection; property Spacing; property TabOrder; property TabStop; property TextPosition; property Width; property Visible; property OnContextPopup; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnItemDoubleClick; property OnItemExitViewportEnter; property OnItemEnter; property OnEdited; property OnItemClicked; property OnKeyDown; property OnKeyPress; property OnKeyString; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnSelectItem; property OnStartDrag; end; { TToolBar } TToolButtonStyle = (tbsButton, tbsCheck, tbsDropDown, tbsSeparator, tbsDivider); TToolButtonState = (tbsChecked, tbsPressed, tbsEnabled, tbsHidden, tbsIndeterminate, tbsWrap, tbsEllipses, tbsMarked); TToolBar = class; TToolButton = class; { TToolButtonActionLink } TToolButtonActionLink = class(TControlActionLink) protected FClient: TToolButton; procedure AssignClient(AClient: TObject); override; function IsCheckedLinked: Boolean; override; function IsImageIndexLinked: Boolean; override; procedure SetChecked(Value: Boolean); override; procedure SetImageIndex(Value: Integer); override; end; TToolButtonActionLinkClass = class of TToolButtonActionLink; TToolButton = class(TCustomControl) private FAllowAllUp: Boolean; FAutoSize: Boolean; FDown: Boolean; FGrouped: Boolean; FMouseIn: Boolean; FImageIndex: TImageIndex; FIndeterminate: Boolean; FMarked: Boolean; FDropDownMenu: TPopupMenu; FMenuDropped: Boolean; FWrap: Boolean; FStyle: TToolButtonStyle; FUpdateCount: Integer; FJustChecked: Boolean; { FShowCaption: Boolean; } FCaption: TCaption; function DropDownRect: TRect; function GetIndex: Integer; function IsCheckedStored: Boolean; function IsImageIndexStored: Boolean; function IsWidthStored: Boolean; { procedure ResizeButton; } procedure SetAutoSize(Value: Boolean); procedure SetDown(Value: Boolean); procedure SetDropDownMenu(Value: TPopupMenu); procedure SetGrouped(Value: Boolean); procedure SetImageIndex(Value: TImageIndex); procedure SetIndeterminate(Value: Boolean); procedure SetMarked(Value: Boolean); procedure SetStyle(Value: TToolButtonStyle); procedure SetWrap(Value: Boolean); procedure SetAllowAllUp(const Value: Boolean); protected FToolBar: TToolBar; procedure ActionChange(Sender: TObject; CheckDefaults: Boolean); override; procedure AssignTo(Dest: TPersistent); override; procedure BeginUpdate; virtual; procedure DoPaint(Canvas: TCanvas); function DropDownWidth: Integer; virtual; procedure EndUpdate; virtual; function EventFilter(Sender: QObjectH; Event: QEventH): Boolean; override; procedure InitWidget; override; function IsEnabled: Boolean; function GetActionLinkClass: TControlActionLinkClass; override; function GetText: TCaption; override; procedure MouseEnter(AControl: TControl); override; procedure MouseLeave(AControl: TControl); override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure Paint; override; procedure SetName(const Value: TComponentName); override; procedure SetParent(const Value: TWidgetControl); override; procedure SetText(const Value: TCaption); override; procedure SetToolBar(AToolBar: TToolBar); procedure ValidateContainer(AComponent: TComponent); override; function WantKey(Key: Integer; Shift: TShiftState; const KeyText: WideString): Boolean; override; public constructor Create(AOwner: TComponent); override; function CheckMenuDropDown: Boolean; dynamic; procedure Click; override; procedure ChangeBounds(ALeft, ATop, AWidth, AHeight: Integer); override; property Index: Integer read GetIndex; property Toolbar: TToolBar read FToolBar write SetToolBar; published property Style: TToolButtonStyle read FStyle write SetStyle default tbsButton; property Action; property AllowAllUp: Boolean read FAllowAllUp write SetAllowAllUp default False; property AutoSize: Boolean read FAutoSize write SetAutoSize default False; property Caption; property Down: Boolean read FDown write SetDown stored IsCheckedStored default False; property DragMode; property DropDownMenu: TPopupMenu read FDropDownMenu write SetDropDownMenu; property Enabled; property Grouped: Boolean read FGrouped write SetGrouped default False; property ImageIndex: TImageIndex read FImageIndex write SetImageIndex stored IsImageIndexStored default -1; property Indeterminate: Boolean read FIndeterminate write SetIndeterminate default False; property Marked: Boolean read FMarked write SetMarked default False; property ParentShowHint; property PopupMenu; { property ShowCaption: Boolean read FShowCaption write SetShowCaption; } property Wrap: Boolean read FWrap write SetWrap default False; property ShowHint; property Visible; property Width stored IsWidthStored; property OnClick; property OnContextPopup; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; end; { TToolBar } TGroupChangeReason = (gcDownState, gcAllowAllUp); TToolBar = class(TCustomControl) private FButtonWidth: Integer; FButtonHeight: Integer; FWrapable: Boolean; FAutoSize: Boolean; FBorderWidth: TBorderWidth; FControls: TList; FEdgeBorders: TEdgeBorders; FEdgeOuter: TEdgeStyle; FEdgeInner: TEdgeStyle; FIndent: Integer; FFlat: Boolean; FList: Boolean; FShowCaptions: Boolean; FHotImages: TCustomImageList; FImages: TCustomImageList; FDisabledImages: TCustomImageList; FImageWidth: Integer; FImageHeight: Integer; FImageChangeLink: TChangeLink; FResizeCount: Integer; FRightEdge: Integer; procedure AdjustSize; reintroduce; procedure DoPaint(ACanvas: TCanvas); function EdgeSpacing(Edge: TEdgeBorder): Integer; function GetControl(Index: Integer): TControl; procedure GroupChange(Requestor: TToolButton; Reason: TGroupChangeReason); function HasImages: Boolean; procedure ImageListChange(Sender: TObject); procedure InternalSetButtonWidth(const Value: Integer; RestrictSize: Boolean); function LastControl: TControl; procedure ResizeButtons(Button: TToolButton); procedure SetWrapable(const Value: Boolean); procedure SetButtonHeight(const Value: Integer); procedure SetButtonWidth(const Value: Integer); procedure SetAutoSize(const Value: Boolean); procedure SetBorderWidth(const Value: TBorderWidth); procedure SetEdgeBorders(const Value: TEdgeBorders); procedure SetEdgeInner(const Value: TEdgeStyle); procedure SetEdgeOuter(const Value: TEdgeStyle); procedure SetIndent(const Value: Integer); procedure SetFlat(const Value: Boolean); procedure SetShowCaptions(const Value: Boolean); procedure SetDisabledImages(const Value: TCustomImageList); procedure SetHotImages(const Value: TCustomImageList); procedure SetImages(const Value: TCustomImageList); procedure SetList(const Value: Boolean); protected procedure ControlsAligned; override; procedure ControlsListChanged(Control: TControl; Inserting: Boolean); override; function CustomAlignInsertBefore(C1, C2: TControl): Boolean; override; procedure CustomAlignPosition(Control: TControl; var NewLeft, NewTop, NewWidth, NewHeight: Integer; var AlignRect: TRect); override; procedure DoResize; function EventFilter(Sender: QObjectH; Event: QEventH): Boolean; override; procedure FontChanged; override; procedure InitWidget; override; procedure AdjustClientRect(var Rect: TRect); override; procedure Loaded; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure Paint; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function ButtonCount: Integer; function ControlCount: Integer; procedure Invalidate; override; property Controls[Index: Integer]: TControl read GetControl; published property Align default alTop; property Anchors; property AutoSize: Boolean read FAutoSize write SetAutoSize default False; property Bitmap; property BorderWidth: TBorderWidth read FBorderWidth write SetBorderWidth default 0; property ButtonHeight: Integer read FButtonHeight write SetButtonHeight default 22; property ButtonWidth: Integer read FButtonWidth write SetButtonWidth default 23; property Caption; property Color; property Constraints; property DisabledImages: TCustomImageList read FDisabledImages write SetDisabledImages; property DragMode; property EdgeBorders: TEdgeBorders read FEdgeBorders write SetEdgeBorders default [ebTop]; property EdgeInner: TEdgeStyle read FEdgeInner write SetEdgeInner default esRaised; property EdgeOuter: TEdgeStyle read FEdgeOuter write SetEdgeOuter default esLowered; property Enabled; property Flat: Boolean read FFlat write SetFlat default False; property Font; property Height default 32; property HotImages: TCustomImageList read FHotImages write SetHotImages; property Images: TCustomImageList read FImages write SetImages; property Indent: Integer read FIndent write SetIndent default 1; property List: Boolean read FList write SetList default False; property Masked default False; property ParentColor; property ParentFont; property ParentShowHint; property PopupMenu; property ShowCaptions: Boolean read FShowCaptions write SetShowCaptions default False; property ShowHint; property TabOrder; property TabStop; property Visible; property Wrapable: Boolean read FWrapable write SetWrapable default True; property OnClick; property OnContextPopup; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnResize; property OnStartDrag; end; { Utility functions } function DefaultMimeFactory: TMimeSourceFactory; procedure SetDefaultMimeFactory(Value: TMimeSourceFactory); procedure CheckRange(AMin, AMax: Integer); implementation uses QConsts, QActnList, Math, QForms; const STATUSBAR_HEIGHT = 19; SIZE_GRIP_SIZE = 15; SCROLL_BUTTON_WIDTH = 17; SELECTED_TAB_SIZE_DELTA = 2; FRAME_BORDER_WIDTH = 2; TAB_FLAT_BORDER = 4; STATUS_PANEL_SPACER = 2; TabDefaultHeightMap: array [TTabStyle] of Integer = (19, 24, 25, 18); TabDefaultWidthMap: array [TTabStyle] of Integer = (45, 45, 53, 40); TabDefaultBorderWidthMap: array [TTabStyle] of Integer = (2, 4, 6, 0); TabDefaultTextOffsetMap: array [TTabStyle] of Integer = (-1, 1, 1, 0); TabButtonsLeftMap: array [TTabStyle] of Integer = (SELECTED_TAB_SIZE_DELTA, 0, -4, 0); FrameMap: array [Boolean] of Integer = (Integer(QFrameShape_NoFrame) or Integer(QFrameShadow_Plain), (Integer(QFrameShape_PopUpPanel) or Integer(QFrameShadow_Raised))); BevelShadowStyle: array [TStatusPanelBevel] of QControls.TBorderStyle = (bsNone, bsSunkenPanel, bsRaisedPanel); { Helper routines } function ButtonToMouseButton(Button: Integer): TMouseButton; begin case Button of Integer(ButtonState_MidButton): Result := mbMiddle; Integer(ButtonState_RightButton): Result := mbRight; else Result := mbLeft; end; end; procedure CheckRange(AMin, AMax: Integer); begin if (AMax < AMin) or (AMin > AMax) then raise ERangeException.Create(Format(SInvalidRangeError,[AMin, AMax])); end; { TProgressBar } constructor TProgressBar.Create(AOwner: TComponent); begin inherited Create(AOwner); Width := 150; Height := 18; Max := 100; FStep := 10; FFillColor := clHighlight; ControlStyle := ControlStyle - [csSetCaption]; end; procedure TProgressBar.FontChanged; begin inherited; FTextColor := Font.Color; end; function TProgressBar.GetText: TCaption; begin Result := FText; end; function TProgressBar.AdjustToParent(const Rect: TRect): TRect; var H, W: Integer; begin H := Rect.Bottom - Rect.Top; W := Rect.Right - Rect.Left; Result.Top := Rect.Top + Top; Result.Left := Rect.Left + Left; Result.Right := Result.Left + W; Result.Bottom := Result.Top + H; end; procedure TProgressBar.EraseText(const AText: WideString; BackgroundColor : TColor); var Rect: TRect; PrevBrush: TBrushRecall; begin PrevBrush := TBrushRecall.Create(Canvas.Brush); try Rect := CalcTextRect(ClientRect, ClientRect, AText); Canvas.Brush.Color := BackgroundColor; Canvas.FillRect(Rect); finally PrevBrush.Free; end; end; function TProgressBar.CalcTextRect(Rect: TRect; const BoundingRect: TRect; const AText: WideString): TRect; const cTextFlags = Integer(AlignmentFlags_AlignHCenter) or Integer(AlignmentFlags_AlignVCenter); begin Canvas.TextExtent(AText, Rect, cTextFlags); IntersectRect(Result, Rect, BoundingRect); end; procedure TProgressBar.InternalPaint; const cTextFlags = Integer(AlignmentFlags_AlignHCenter) or Integer(AlignmentFlags_AlignVCenter); cTextBorder = 4; cSectionSpacer = 2; var Rect: TRect; PrevRect: TRect; TextRect: TRect; PrevPen: TPenRecall; PrevBrush: TBrushRecall; PrevFont: TFontRecall; function CalcSectionSize(const BoundingRect: TRect): Integer; begin if Orientation = pbHorizontal then Result := 2 * (BoundingRect.Bottom - BoundingRect.Top - 1) div 3 else Result := 2 * (BoundingRect.Right - BoundingRect.Left - 1) div 3; end; procedure DrawSpacer(Rect: TRect; SectionSize: Integer); var PrevBrush: TBrushRecall; PrevPen: TPenRecall; begin if not Transparent then begin PrevBrush := nil; PrevPen := TPenRecall.Create(Canvas.Pen); try PrevBrush := TBrushRecall.Create(Canvas.Brush); Canvas.Pen.Color := Color; Canvas.Pen.Width := 1; Canvas.Brush.Style := bsClear; InflateRect(Rect, 1, 1); Canvas.Rectangle(Rect); finally PrevBrush.Free; PrevPen.Free; end; end; end; function SectionCount(const ARect: TRect; FillArea: TRect; SectionSize: Integer): Integer; var TotalPixels: Integer; begin if Orientation = pbHorizontal then TotalPixels := FillArea.Right - ARect.Left else TotalPixels := ARect.Bottom - FillArea.Top; Result := ((TotalPixels - cSectionSpacer) div (CalcSectionSize(ARect) + cSectionSpacer)) + 1; end; procedure DrawSections(BoundingRect: TRect; var FillArea: TRect); var SectionSize: Integer; Sections: Integer; I: Integer; begin InflateRect(FillArea, -1, -1); InflateRect(BoundingRect, -1, -1); SectionSize := CalcSectionSize(BoundingRect); { Draw an empty the progress bar } if Position = Min then begin if not Transparent then begin Canvas.Brush.Color := Color; Canvas.FillRect(BoundingRect); end; InflateRect(FillArea, 1, 1); Exit; end; if SectionSize <> 0 then begin Sections := SectionCount(BoundingRect, FillArea, SectionSize); if FSections <> Sections then begin FSections := Sections; { Draw each section } for I := 0 to Sections - 1 do begin if Orientation = pbHorizontal then begin FillArea.Left := BoundingRect.Left + (I * (SectionSize + cSectionSpacer)); FillArea.Right := FillArea.Left + SectionSize; FillArea.Right := Math.Min(FillArea.Right, BoundingRect.Right - 1); Canvas.FillRect(FillArea); DrawSpacer(FillArea, SectionSize); Inc(FillArea.Right, cSectionSpacer); FillArea.Left := FillArea.Right; end else begin FillArea.Bottom := BoundingRect.Bottom - (I * (SectionSize + cSectionSpacer)); FillArea.Top := FillArea.Bottom - SectionSize; FillArea.Top := Math.Max(FillArea.Top, BoundingRect.Top + 1); Canvas.FillRect(FillArea); DrawSpacer(FillArea, SectionSize); Dec(FillArea.Top, cSectionSpacer); FillArea.Bottom := FillArea.Top; end; end; if Orientation = pbHorizontal then Dec(FillArea.Right, cSectionSpacer) else Inc(FillArea.Top, cSectionSpacer); end else if Orientation = pbHorizontal then FillArea.Right := BoundingRect.Left + (Sections * (SectionSize + cSectionSpacer)) else FillArea.Top := BoundingRect.Bottom - (Sections * (SectionSize + cSectionSpacer)); end; InflateRect(FillArea, 1, 1); end; function PaintProgress(var ARect: TRect): Boolean; var TotalPixels: Integer; Rect: TRect; begin Result := False; PrevRect := ARect; Rect := ARect; Canvas.SetClipRect(AdjustToParent(ARect)); try if (FTotalSteps > 0) then begin { Calculate the size of the fill area in pixels based on the position } case Orientation of pbHorizontal: begin TotalPixels := ARect.Right - ARect.Left; ARect.Right := ARect.Left + ((ScalePosition(Position) * TotalPixels) div FTotalSteps); ARect.Right := Math.Min(ARect.Right, ClientWidth); end; pbVertical: begin TotalPixels := ARect.Bottom - ARect.Top; ARect.Top := ARect.Bottom - ((ScalePosition(Position) * TotalPixels) div FTotalSteps); ARect.Top := Math.Min(ARect.Top, ClientHeight); end; end; if EqualRect(FFillArea, ARect) then Exit; FFillArea := ARect; Result := True; Canvas.Brush.Color := FillColor; { Draw the progress } if Smooth then Canvas.FillRect(ARect) else DrawSections(PrevRect, ARect); { Calculate the rest of the non-progress area if not transparent } if not Transparent then begin Rect := PrevRect; if Orientation = pbHorizontal then begin Rect.Left := ARect.Right; if Rect.Left > Rect.Right then Rect.Left := Rect.Right; end else begin Rect.Bottom := ARect.Top; if Rect.Bottom < Rect.Top then Rect.Bottom := Rect.Top; end; end; end; if not Transparent then begin Canvas.Brush.Color := Color; Canvas.FillRect(Rect); end; finally Canvas.ResetClipRegion; end; end; procedure XORText(const BoundingRect: TRect; FillRect, TextRect: TRect; const Caption: WideString; TextFlags: Integer); procedure DrawText(BackgroundColor, FontColor: TColor); begin EraseText(FPrevText, BackgroundColor); Canvas.Brush.Color := BackgroundColor; Canvas.FillRect(TextRect); Canvas.Font.Color := FontColor; Canvas.TextRect(TextRect, TextRect.Left, TextRect.Top, Caption, cTextFlags); end; begin { Qt doesn't handle XORing text very well in windows. So instead we will paint the text twice with different colors for inside and outside of the fill area. By using SetClipRect we can achieve an XORed look. } try if Transparent then Canvas.Brush.Style := bsClear; if Orientation = pbHorizontal then begin FillRect.Left := BoundingRect.Left; TextRect.Top := BoundingRect.Top; TextRect.Bottom := BoundingRect.Bottom; if (FillRect.Right > TextRect.Left) and (FillRect.Right < TextRect.Right) then Canvas.SetClipRect(AdjustToParent(FillRect)); { Draw the text that is inside of the fill area } if FillRect.Right > TextRect.Left then DrawText(FillColor, clHighlightText); if FillRect.Right < TextRect.Right then begin { Draw the text that is outside of the fill area } if (FillRect.Right > TextRect.Left) then begin Rect := BoundingRect; Rect.Left := FillRect.Right; Canvas.SetClipRect(AdjustToParent(Rect)); end; DrawText(Color, FTextColor); end; end else begin FillRect.Bottom := BoundingRect.Bottom; TextRect.Right := BoundingRect.Right; TextRect.Left := BoundingRect.Left; if (FillRect.Top > TextRect.Top) and (FillRect.Top < TextRect.Bottom) then Canvas.SetClipRect(AdjustToParent(FillRect)); { Draw the text that is inside of the fill area } if FillRect.Top < TextRect.Bottom then DrawText(FillColor, clHighlightText); if FillRect.Top > TextRect.Top then begin { Draw the text that is outside of the fill area } if (FillRect.Top < TextRect.Bottom) then begin Rect := BoundingRect; Rect.Bottom := FillRect.Top; Canvas.SetClipRect(AdjustToParent(Rect)); end; DrawText(Color, FTextColor); end; end; finally Canvas.ResetClipRegion; end; end; begin Canvas.Start; PrevPen := nil; PrevFont := nil; PrevBrush := TBrushRecall.Create(Canvas.Brush); try PrevFont := TFontRecall.Create(Canvas.Font); PrevPen := TPenRecall.Create(Canvas.Pen); Canvas.Brush.Style := bsSolid; Rect := Classes.Rect(0, 0, Width, Height); { Adjust for the frame } InflateRect(Rect, -1, -1); { Adjust for the BorderWidth } InflateRect(Rect, -BorderWidth, -BorderWidth); if IsRectEmpty(Rect) then Exit; TextRect := Rect; { Adjust the fill area depending on where the text will be displayed } if not Smooth then begin if ShowCaption and (Caption <> '') then begin if Orientation = pbHorizontal then begin Rect.Right := Rect.Right - (Canvas.TextWidth(Caption) + (cTextBorder * 2)); if Rect.Right < Rect.Left then Rect.Right := Rect.Left; TextRect.Left := Rect.Right; end else begin Rect.Top := Rect.Top + Canvas.TextHeight(Caption); if Rect.Top > Rect.Bottom then Rect.Top := Rect.Bottom; TextRect.Bottom := Rect.Top; end; end; end; { Paint the progress area } if PaintProgress(Rect) then { Draw the text } if ShowCaption and (Caption <> '')then begin Canvas.Font := Font; Canvas.Font.Color := FTextColor; if Smooth then begin TextRect := CalcTextRect(TextRect, PrevRect, Caption); XORText(PrevRect, Rect, TextRect, Caption, cTextFlags); Exit; end else begin Canvas.SetClipRect(AdjustToParent(TextRect)); if not Transparent then begin Canvas.Brush.Color := Color; Canvas.FillRect(TextRect); end else Canvas.Brush.Style := bsClear; end; Canvas.TextRect(TextRect, TextRect.Left, TextRect.Top, Caption, cTextFlags); end; finally PrevPen.Free; PrevFont.Free; PrevBrush.Free; Canvas.Stop; end; end; procedure TProgressBar.InternalDrawFrame; var R: TRect; procedure DrawBorder(ARect: TRect); const BorderWidthAdj: array[Boolean] of Integer = (0,1); var PrevBrush: TBrushRecall; PrevPen: TPenRecall; i : Integer; begin with Canvas do begin PrevBrush := nil; PrevPen := TPenRecall.Create(Pen); try PrevBrush := TBrushRecall.Create(Brush); Brush.Style := bsClear; if Transparent then Pen.Style := psClear else Pen.Style := psSolid; Pen.Color := Color; for i := 1 to BorderWidth + BorderWidthAdj[Smooth] do if not IsRectEmpty(ARect) then begin Rectangle(ARect); InflateRect(ARect, -1, -1); end; finally PrevPen.Free; PrevBrush.Free; end; end; end; begin R := Rect(0 , 0, Width, Height); { Draw frame } DrawEdge(Canvas, R, esNone, esLowered, [ebLeft, ebTop, ebBottom, ebRight]); InflateRect(R, -1, -1); DrawBorder(R); end; function TProgressBar.ScalePosition(Value: Integer): Integer; begin { Adjust the Position to fit in the scale of 0 to FTotalSteps } Result := Abs(Value - Min); end; procedure TProgressBar.SetBorderWidth(const Value: TBorderWidth); begin if FBorderWidth <> Value then begin FBorderWidth := Value; RequestAlign; Invalidate; end; end; procedure TProgressBar.SetFillColor(const Value: TColor); begin if FFillColor <> Value then begin FFillColor := Value; Invalidate; end; end; procedure TProgressBar.Paint; var PrevBrush: TBrushRecall; PrevPen: TPenRecall; begin PrevBrush := nil; PrevPen := TPenRecall.Create(Canvas.Pen); try PrevBrush := TBrushRecall.Create(Canvas.Brush); FFillArea := Rect(-1, -1, -1, -1); FSections := -1; InternalDrawFrame; InternalPaint; finally PrevPen.Free; PrevBrush.Free; end; end; procedure TProgressBar.SetText(const Value: TCaption); begin if FText <> Value then begin FText := Value; Invalidate; end; end; procedure TProgressBar.Changing(var Text: WideString; NewPosition: Integer); begin if Assigned(FOnChanging) then FOnChanging(Self, Text, NewPosition); end; procedure TProgressBar.SetMax(const Value: Integer); begin if FMax <> Value then begin SetRange(Min, Value); if Value < Position then FPosition := Value; FMax := Value; Invalidate; end; end; procedure TProgressBar.SetMin(const Value: Integer); begin if FMin <> Value then begin SetRange(Value, Max); FPosition := Value; FMin := Value; Invalidate; end; end; procedure TProgressBar.SetOrientation(const Value: TProgressBarOrientation); begin if FOrientation <> Value then begin FOrientation := Value; Invalidate; end; end; procedure TProgressBar.SetPosition(Value: Integer); var Text: WideString; begin if FPosition <> Value then begin FPosition := Value; if (FPosition > Max) or (FPosition < Min) then begin if WrapRange then begin if FTotalSteps > 0 then if Value > Max then FPosition := (ScalePosition(Value) mod (FTotalSteps + 1)) + Min else FPosition := Max - (ScalePosition(Value) mod (FTotalSteps + 1)) + 1 else FPosition := Value; end else if FPosition > Max then FPosition := Max else FPosition := Min; end; Text := Caption; FPrevText := Text; Changing(Text, Position); if Caption <> Text then FText := Text; if (Transparent or ((Position = 0) and (Value <= Max))) then Invalidate else if (Parent <> nil) and Visible then InternalPaint; end; end; procedure TProgressBar.SetRange(const AMin, AMax: Integer); begin if not (csLoading in ComponentState) then CheckRange(AMin, AMax); FTotalSteps := AMax - AMin; end; procedure TProgressBar.SetShowCaption(const Value: Boolean); begin if FShowCaption <> Value then begin FShowCaption := Value; Invalidate; end; end; procedure TProgressBar.SetSmooth(const Value: Boolean); begin if FSmooth <> Value then begin FSmooth := Value; Invalidate; end; end; procedure TProgressBar.SetStep(const Value: Integer); begin if FStep <> Value then FStep := Value; end; procedure TProgressBar.SetTransparent(const Value: Boolean); begin if FTransparent <> Value then begin FTransparent := Value; Invalidate; end; end; procedure TProgressBar.StepBy(Delta: Integer); begin Position := Position + Delta; end; procedure TProgressBar.StepIt; begin WrapRange := True; try Position := Position + FStep; finally WrapRange := False; end; end; { TTrackBar } procedure TTrackBar.Changed; begin if Assigned(FOnChange) then FOnChange(Self); end; constructor TTrackBar.Create(AOwner: TComponent); begin inherited Create(AOwner); { Height and Width set initally for Vertical so that ChangeAspectRatio in SetOrientation can change to the proper aspect ratio for Horizontal when called in InitWidget } Width := 45; Height := 150; FOrientation := trVertical; TabStop := True; FTickMarks := tmBottomRight; ControlStyle := ControlStyle - [csDoubleClicks]; InputKeys := [ikArrows]; end; procedure TTrackBar.CreateWidget; var Method: TMethod; begin FHandle := QClxSlider_create(ParentWidget, PChar(Name), Method); Hooks := QSlider_hook_create(FHandle); end; procedure TTrackBar.InitWidget; begin inherited InitWidget; LineSize := 1; PageSize := 2; Frequency := 1; Min := 0; Max := 10; TickMarks := tmBottomRight; TickStyle := tsAuto; Orientation := trHorizontal; QWidget_setFocusPolicy(FHandle, QWidgetFocusPolicy_ClickFocus); UpdateSettings; // SetRange(Min, Max); end; procedure TTrackBar.HookEvents; var Method: TMethod; begin QSlider_valueChanged_Event(Method) := ValueChangedHook; QSlider_hook_hook_valueChanged(QSlider_hookH(Hooks), Method); QSlider_sliderMoved_Event(Method) := ValueChangedHook; QSlider_hook_hook_valueChanged(QSlider_hookH(Hooks), Method); inherited HookEvents; end; procedure TTrackBar.Loaded; begin inherited Loaded; if Orientation = trVertical then ChangeAspectRatio; SetRange(FMin, FMax); end; procedure TTrackBar.ChangeAspectRatio; begin SetBounds(Left, Top, Height, Width); end; function TTrackBar.GetHandle: QClxSliderH; begin HandleNeeded; Result := QClxSliderH(FHandle); end; function TTrackBar.GetOrientation: TTrackBarOrientation; begin Result := TTrackBarOrientation(QSlider_orientation(Handle)); end; procedure TTrackBar.SetFrequency(const Value: Integer); begin { Note: if Frequency is set to 0 then the QT determines the Tick interval from the LineSize. } QSlider_setTickInterval(Handle, Value); end; procedure TTrackBar.SetLineSize(const Value: Integer); begin QRangeControl_setSteps(RangeControl, Value, PageSize); end; procedure TTrackBar.SetMax(const Value: Integer); begin if (csLoading in ComponentState) then SetRange(FMin, Value) else SetRange(Min, Value); end; procedure TTrackBar.SetMin(const Value: Integer); begin if (csLoading in ComponentState) then SetRange(Value, FMax) else SetRange(Value, Max); end; procedure TTrackBar.SetOrientation(const Value: TTrackBarOrientation); begin if FOrientation <> Value then begin FOrientation := Value; QSlider_setOrientation(Handle, Qt.Orientation(Value)); ChangeAspectRatio; UpdateSettings; end; end; procedure TTrackBar.SetPageSize(const Value: Integer); begin QRangeControl_setSteps(RangeControl, LineSize, Value); end; procedure TTrackBar.SetPosition(const Value: Integer); begin QRangeControl_setValue(RangeControl, Value); end; procedure TTrackBar.SetRange(const AMin, AMax: Integer); begin FMin := AMin; FMax := AMax; if not HandleAllocated or (csLoading in ComponentState) then Exit; try CheckRange(AMin, AMax); except FMin := Min; FMax := Max; raise; end; QRangeControl_setRange(RangeControl, FMin, FMax); Invalidate; end; procedure TTrackBar.SetTickMarks(const Value: TTickMark); begin if FTickMarks <> Value then begin FTickMarks := Value; UpdateSettings; end; end; procedure TTrackBar.SetTickStyle(const Value: TTickStyle); begin if FTickStyle <> Value then begin FTickStyle := Value; case FTickStyle of tsAuto: UpdateSettings; tsNone: QSlider_setTickmarks(Handle, QSliderTickSetting_NoMarks); end; end; end; function TTrackBar.GetFrequency: Integer; begin Result := QSlider_tickInterval(Handle); end; function TTrackBar.GetRangeControl: QRangeControlH; begin Result := QSlider_to_QRangeControl(Handle); end; function TTrackBar.GetLineSize: Integer; begin Result := QRangeControl_lineStep(RangeControl); end; function TTrackBar.GetPageSize: Integer; begin Result := QRangeControl_pageStep(RangeControl); end; function TTrackBar.GetMax: Integer; begin Result := QRangeControl_maxValue(RangeControl); end; function TTrackBar.GetMin: Integer; begin Result := QRangeControl_minValue(RangeControl); end; function TTrackBar.GetPosition: Integer; begin Result := QRangeControl_value(RangeControl); end; function TTrackBar.GetTickMarks: TTickMark; const TickSettingMap: array [Ord(QSliderTickSetting_Above)..Ord(QSliderTickSetting_Both)] of TTickMark = (tmTopLeft, tmBottomRight, tmBoth); var TickSetting: Integer; begin TickSetting := Integer(QSlider_tickMarks(Handle)); if TickSetting = Integer(QSliderTickSetting_NoMarks) then Result := FTickMarks else Result := TickSettingMap[TickSetting]; end; function TTrackBar.GetTickStyle: TTickStyle; begin Result := FTickStyle; end; procedure TTrackBar.UpdateSettings; const TickMarksMap: array [TTickMark, TTrackBarOrientation] of QSliderTickSetting = ((QSliderTickSetting_Below, QSliderTickSetting_Right), (QSliderTickSetting_Above, QSliderTickSetting_Left), (QSliderTickSetting_Both, QSliderTickSetting_Both)); begin if TickStyle <> tsNone then QSlider_setTickMarks(Handle, TickMarksMap[FTickMarks, Orientation]); end; procedure TTrackBar.ValueChangedHook(Value: Integer); begin { The Value parameter from Qt is not used } try Changed; except Application.HandleException(Self); end; end; { TStatusPanel } constructor TStatusPanel.Create(Collection: TCollection); begin inherited Create(Collection); Width := 50; FBevel := pbLowered; FVisible := True; end; destructor TStatusPanel.Destroy; begin if PanelPosition = ppRight then Dec(StatusPanels.FFixedPanelCount); inherited Destroy; end; procedure TStatusPanel.Assign(Source: TPersistent); begin if Source is TStatusPanel then begin Text := TStatusPanel(Source).Text; Width := TStatusPanel(Source).Width; Alignment := TStatusPanel(Source).Alignment; Bevel := TStatusPanel(Source).Bevel; end else inherited Assign(Source); end; function TStatusPanel.GetDisplayName: string; begin Result := Text; if Result = '' then Result := inherited GetDisplayName; end; procedure TStatusPanel.SetAlignment(const Value: TAlignment); begin if FAlignment <> Value then begin FAlignment := Value; Changed(False); end; end; procedure TStatusPanel.SetBevel(const Value: TStatusPanelBevel); begin if FBevel <> Value then begin FBevel := Value; Changed(False); end; end; procedure TStatusPanel.SetStyle(Value: TStatusPanelStyle); begin if FStyle <> Value then begin FStyle := Value; Changed(False); end; end; procedure TStatusPanel.SetText(const Value: WideString); begin if FText <> Value then begin FText := Value; Changed(False); end; end; procedure TStatusPanel.SetWidth(const Value: Integer); begin if FWidth <> Value then begin FWidth := Value; Changed(True); end; end; procedure TStatusPanel.SetPanelPosition(const Value: TPanelPosition); begin if FPanelPosition <> Value then begin if FPanelPosition = ppRight then Dec(StatusPanels.FFixedPanelCount); FPanelPosition := Value; if FPanelPosition = ppRight then Inc(StatusPanels.FFixedPanelCount); Changed(False); end; end; procedure TStatusPanel.SetVisible(const Value: Boolean); begin if FVisible <> Value then begin FVisible := Value; Changed(False); end; end; function TStatusPanel.GetStatusPanels: TStatusPanels; begin Result := TStatusPanels(Collection); end; { TStatusPanels } constructor TStatusPanels.Create(StatusBar: TStatusBar); begin inherited Create(TStatusPanel); FStatusBar := StatusBar; end; function TStatusPanels.Add: TStatusPanel; begin Result := TStatusPanel(inherited Add); end; function TStatusPanels.GetItem(Index: Integer): TStatusPanel; begin Result := TStatusPanel(inherited GetItem(Index)); end; function TStatusPanels.GetOwner: TPersistent; begin Result := FStatusBar; end; procedure TStatusPanels.Update(Item: TCollectionItem); begin StatusBar.UpdatePanels; end; procedure TStatusPanels.SetItem(Index: Integer; const Value: TStatusPanel); begin inherited SetItem(Index, Value); FStatusBar.Update; end; { TStatusBar } function TStatusBar.FindPanel(PanelPosition: TPanelPosition; Index: Integer): TStatusPanel; var I, Count: Integer; begin Result := nil; Count := 0; for I := 0 to Panels.Count-1 do if Panels[I].PanelPosition = PanelPosition then begin if Count = Index then begin Result := Panels[I]; Break; end; Inc(Count); end; end; function TStatusBar.ExecuteAction(Action: TBasicAction): Boolean; begin if AutoHint and (Action is THintAction) and not DoHint then begin if SimplePanel or (Panels.Count = 0) then SimpleText := THintAction(Action).Hint else Panels[0].Text := THintAction(Action).Hint; Result := True; end else Result := inherited ExecuteAction(Action); end; procedure TStatusBar.BeginUpdate; begin Inc(FUpdateCount); end; constructor TStatusBar.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := ControlStyle - [csAcceptsControls, csSetCaption] + [csNoFocus]; Align := alBottom; FPanels := TStatusPanels.Create(Self); FSizeGrip := True; BorderStyle := bsNone; BevelInner := bvNone; BevelOuter := bvNone; ParentColor := False; end; destructor TStatusBar.Destroy; begin FreeAndNil(FPanels); inherited Destroy; end; function TStatusBar.DoHint: Boolean; begin if Assigned(FOnHint) then begin FOnHint(Self); Result := True; end else Result := False; end; procedure TStatusBar.CursorChanged; var I: Integer; begin inherited; for I := 0 to ControlCount-1 do Controls[I].Cursor := Cursor; end; procedure TStatusBar.ControlsAligned; begin inherited ControlsAligned; UpdatePanels; end; procedure TStatusBar.DoPanelClick(Panel: TStatusPanel); begin if Assigned(FOnPanelClick) then FOnPanelClick(Self, Panel); end; procedure TStatusBar.DrawPanel(Panel: TStatusPanel; const Rect: TRect); var PrevBrush: TBrushRecall; begin if Assigned(FOnDrawPanel) then FOnDrawPanel(Self, Panel, Rect) else begin PrevBrush := TBrushRecall.Create(Canvas.Brush); try Canvas.Brush.Color := Color; Canvas.FillRect(Rect); finally PrevBrush.Free; end; end; end; procedure TStatusBar.EnabledChanged; var I: Integer; begin inherited; for I := 0 to ControlCount-1 do Controls[I].Enabled := Enabled; end; procedure TStatusBar.Resize; begin inherited; ValidateSizeGrip; UpdatePanels; end; function TStatusBar.GetPanel(PanelPosition: TPanelPosition; Index: Integer): TStatusPanel; begin Result := FindPanel(PanelPosition, Index); if Result = nil then raise EListError.Create(Format(SListIndexError,[Index])); end; procedure TStatusBar.EndUpdate; begin Dec(FUpdateCount); if FUpdateCount = 0 then Update; end; procedure TStatusBar.FlipChildren(AllLevels: Boolean); var I: Integer; begin if HandleAllocated and (not SimplePanel) and (Panels.Count > 0) then begin BeginUpdate; try { Flip 'em } for I := 0 to Panels.Count - 1 do begin if Panels[I].PanelPosition = ppLeft then Panels[I].PanelPosition := ppRight else Panels[I].PanelPosition := ppLeft; end; finally EndUpdate; end; end; end; procedure TStatusBar.SetBounds(ALeft, ATop, AWidth, AHeight: Integer); begin inherited; ValidateSizeGrip; end; procedure TStatusBar.InitWidget; begin Height := STATUSBAR_HEIGHT; BorderWidth := 0; Color := clBackground; end; procedure TStatusBar.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var I: Integer; Point: TPoint; begin inherited MouseUp(Button, Shift, X, Y); Point.X := X; Point.Y := Y; for I := 0 to Panels.Count - 1 do if PtInRect(Panels[I].FBounds, Point) then begin DoPanelClick(Panels[I]); Break; end; end; procedure TStatusBar.Invalidate; begin inherited Invalidate; ValidateSizeGrip; end; function TStatusBar.IsFontStored: Boolean; begin Result := not ParentFont; end; procedure TStatusBar.PaletteCreated; begin // We don't want a SizeGrip to show up by default when the component is // created off the palette. The default is left True so we can read in old // StatusBar's from VCL SizeGrip := False; end; procedure TStatusBar.RequestAlign; begin inherited RequestAlign; Invalidate; end; procedure TStatusBar.Paint; const cTextFlags: array [TAlignment] of Integer = ( Integer(AlignmentFlags_AlignLeft), Integer(AlignmentFlags_AlignRight), Integer(AlignmentFlags_AlignHCenter)); cEdgeInner: array [TStatusPanelBevel] of TEdgeStyle = (esNone, esNone, esRaised); cEdgeOuter: array [TStatusPanelBevel] of TEdgeStyle = (esNone, esLowered, esNone); var I: Integer; R: TRect; begin Canvas.Font := Font; if (Panels.Count = 0) or SimplePanel then begin R := Rect(BorderWidth, STATUS_PANEL_SPACER - BorderWidth, Width - BorderWidth, Height - BorderWidth); { Find out where the Right border is } for I := 0 to Panels.Count - 1 do if Panels[I].PanelPosition = ppRight then R.Right := Panels[I].FBounds.Left - STATUS_PANEL_SPACER; DrawEdge(Canvas, R, esNone, cEdgeOuter[pbLowered], [ebLeft, ebTop, ebBottom, ebRight]); if SimplePanel then Canvas.TextRect(R, R.Left, R.Top, SimpleText, Integer(AlignmentFlags_AlignVCenter) or cTextFlags[taLeftJustify]); end; if not (Panels.Count = 0) then for I := 0 to Panels.Count - 1 do if Panels[I].Visible and (not Panels[I].FHidden) then begin R := Panels[I].FBounds; DrawEdge(Canvas, R, cEdgeInner[Panels[I].Bevel], cEdgeOuter[Panels[I].Bevel], [ebLeft, ebTop, ebBottom, ebRight]); InflateRect(R, -STATUS_PANEL_SPACER, -STATUS_PANEL_SPACER); if Panels[I].Style = psOwnerDraw then DrawPanel(Panels[I], R) else begin if R.Right - R.Left > STATUS_PANEL_SPACER then Canvas.TextRect(R, R.Left, R.Top, Panels[I].Text, Integer(AlignmentFlags_AlignVCenter) or cTextFlags[Panels[I].Alignment]); end; InflateRect(R, STATUS_PANEL_SPACER, STATUS_PANEL_SPACER); end; end; procedure TStatusBar.SetPanels(const Value: TStatusPanels); begin FPanels.Assign(Value); end; procedure TStatusBar.SetSimplePanel(const Value: Boolean); begin if FSimplePanel <> Value then begin FSimplePanel := Value; UpdatePanels; end; end; procedure TStatusBar.SetSimpleText(const Value: WideString); begin if FSimpleText <> Value then begin FSimpleText := Value; Invalidate; end; end; procedure TStatusBar.Update; begin if FUpdateCount = 0 then begin inherited Update; UpdatePanels; end; end; procedure TStatusBar.UpdatePanels; const cSizeGripMap: array [Boolean] of Integer = (0, SIZE_GRIP_SIZE + STATUS_PANEL_SPACER); var LeftSide: Integer; RightSide: Integer; NewLeft: Integer; NewRight: Integer; LastLeft: Integer; I: Integer; R: TRect; begin if HandleAllocated and (Panels <> nil) then begin LeftSide := BorderWidth; RightSide := Width - BorderWidth; NewLeft := LeftSide; LastLeft := -1; for I := 0 to Panels.Count-1 do begin if (Panels[I].PanelPosition = ppRight) and Panels[I].Visible then begin NewLeft := RightSide - Panels[I].Width; TStatusPanel(Panels[I]).FBounds := Rect(NewLeft, STATUS_PANEL_SPACER + BorderWidth, RightSide, Height - BorderWidth); R := TStatusPanel(Panels[I]).FBounds; RightSide := NewLeft - STATUS_PANEL_SPACER; end; end; for I := 0 to Panels.Count-1 do begin if (Panels[I].PanelPosition = ppLeft) and Panels[I].Visible then begin NewRight := LeftSide + Panels[I].Width; NewRight := Min(NewRight, RightSide); Panels[I].FHidden := (NewRight <= LeftSide - STATUS_PANEL_SPACER) or SimplePanel; if Panels[I].FHidden then Continue; TStatusPanel(Panels[I]).FBounds := Rect(LeftSide, STATUS_PANEL_SPACER + BorderWidth, NewRight, Height - BorderWidth); R := TStatusPanel(Panels[I]).FBounds; LeftSide := NewRight + STATUS_PANEL_SPACER; LastLeft := I; end; end; if LastLeft > -1 then begin NewLeft := Max(NewLeft - STATUS_PANEL_SPACER, RightSide); TStatusPanel(Panels[LastLeft]).FBounds.Right := NewLeft; end; Invalidate; end; end; procedure TStatusBar.SetSizeGrip(const Value: Boolean); begin if FSizeGrip <> Value then begin FSizeGrip := Value; ValidateSizeGrip; end; end; type TOpenCustomForm = class(TCustomForm); procedure TStatusBar.ValidateSizeGrip; var Form: TCustomForm; APoint, P: TPoint; begin Form := GetParentForm(Self); if (Form <> nil) and (TOpenCustomForm(Form).BorderStyle in [fbsSizeable, fbsSizeToolWin]) then begin P := Point(Width, Height); QWidget_mapToParent(Handle, @APoint, @P); if (APoint.X = Form.ClientWidth) {and (APoint.Y = Form.ClientHeight)} then begin if FSizeGripHandle = nil then FSizeGripHandle := QSizeGrip_Create(Handle, nil); PositionSizeGrip; Exit; end; end; if FSizeGripHandle <> nil then QWidget_hide(FSizeGripHandle); end; procedure TStatusBar.PositionSizeGrip; var NewGripSizeHeight: Integer; NewGripSizeLeft: Integer; begin if FSizeGripHandle <> nil then begin NewGripSizeHeight := Height - (BorderWidth * 2) - 6; NewGripSizeLeft := Width - SIZE_GRIP_SIZE - BorderWidth - 2; QWidget_setGeometry(FSizeGripHandle, NewGripSizeLeft, BorderWidth + 4, SIZE_GRIP_SIZE, NewGripSizeHeight); QWidget_raise(FSizeGripHandle); if SizeGrip and (Align in [alBottom, alRight, alClient]) then QWidget_show(FSizeGripHandle) else QWidget_hide(FSizeGripHandle); end; end; function TStatusBar.GetBorderWidth: TBorderWidth; begin Result := inherited BorderWidth; end; procedure TStatusBar.SetBorderWidth(const Value: TBorderWidth); begin inherited BorderWidth := Value; PositionSizeGrip; Update; end; procedure TStatusBar.CMRecreateWindow(var Message: TMessage); begin ValidateSizeGrip; end; { TTab } procedure TTab.Assign(Source: TPersistent); begin if Source is TTab then begin Caption := TTab(Source).Caption; Enabled := TTab(Source).Enabled; FTabRect := TTab(Source).TabRect; Highlighted := TTab(Source).Highlighted; ImageIndex := TTab(Source).ImageIndex; Selected := TTab(Source).Selected; Visible := TTab(Source).Visible; end else inherited Assign(Source); end; constructor TTab.Create(Collection: TCollection); begin inherited Create(Collection); Tabs.BeginUpdate; try Width := TabDefaultWidthMap[Tabs.TabControl.Style]; Height := TabDefaultHeightMap[Tabs.TabControl.Style]; FVisible := True; FEnabled := True; FImageIndex := Index; finally Tabs.EndUpdate; end; end; function TTab.GetTabs: TTabs; begin Result := TTabs(Collection); end; function TTab.CalculateWidth: Integer; var ImageRef: TCustomImageList; begin Result := TabDefaultWidthMap[Tabs.TabControl.Style]; if Caption <> '' then begin { Set the Width based on the width of the caption and Images } Result := Tabs.TabControl.Canvas.TextWidth(Caption) + (TabDefaultBorderWidthMap[Tabs.TabControl.Style] * 4); ImageRef := Tabs.TabControl.GetImageRef; if Tabs.TabControl.HasImages(Self) then Result := Result + ImageRef.Width + (Tabs.TabControl.ImageBorder * 2); if Result < TabDefaultWidthMap[Tabs.TabControl.Style] then Result := TabDefaultWidthMap[Tabs.TabControl.Style]; end; end; function TTab.CalculateHeight: Integer; begin Result := Tabs.CalculateTabHeight(Caption); end; procedure TTab.SetCaption(const Value: TCaption); begin if FCaption <> Value then begin FCaption := Value; Tabs.BeginUpdate; try Width := CalculateWidth; Height := CalculateHeight; finally Tabs.EndUpdate; end; end; end; procedure TTab.SetEnabled(const Value: Boolean); begin if FEnabled <> Value then begin FEnabled := Value; Changed(True); end; end; function TTab.GetDisplayName: string; begin Result := FCaption; if Result = '' then Result := inherited GetDisplayName; end; function TTab.GetHeight: Integer; begin Result := TabRect.Bottom - TabRect.Top; end; function TTab.GetWidth: Integer; begin Result := TabRect.Right - TabRect.Left; end; procedure TTab.SetHeight(const Value: Integer); var NewValue: Integer; begin if Value <> (FTabRect.Bottom - FTabRect.Top) then begin Tabs.FUpdating := True; try if Value = 0 then NewValue := CalculateHeight else NewValue := Value; if FTabRect.Bottom <> FTabRect.Top + NewValue then begin FTabRect.Bottom := FTabRect.Top + NewValue; Changed(True); end; finally Tabs.FUpdating := False; end; end; end; procedure TTab.SetWidth(const Value: Integer); var NewValue: Integer; begin if Value <> (FTabRect.Right - FTabRect.Left) then begin Tabs.FUpdating := True; try if Value = 0 then NewValue := CalculateWidth else NewValue := Value; if FTabRect.Right <> FTabRect.Left + NewValue then begin FTabRect.Right := FTabRect.Left + NewValue; Changed(True); end; finally Tabs.FUpdating := False; end; end; end; function TTab.GetLeft: Integer; begin Result := TabRect.Left; end; function TTab.GetTop: Integer; begin Result := TabRect.Top; end; procedure TTab.SetLeft(const Value: Integer); begin if TabRect.Left <> Value then begin Tabs.FUpdating := True; try FTabRect.Right := Value + Width; FTabRect.Left := Value; Changed(True); finally Tabs.FUpdating := False; end; end; end; procedure TTab.SetTop(const Value: Integer); begin if TabRect.Top <> Value then begin Tabs.FUpdating := True; try FTabRect.Bottom := Value + Height; FTabRect.Top := Value; Changed(True); finally Tabs.FUpdating := False; end; end; end; procedure TTab.SetVisible(const Value: Boolean); begin if FVisible <> Value then begin FVisible := Value; Changed(True); end; end; function TTab.GetImageIndex: Integer; begin Result := FImageIndex; end; procedure TTab.SetImageIndex(const Value: Integer); begin if FImageIndex <> Value then begin FImageIndex := Value; Changed(True); end; end; procedure TTab.SetSelected(const Value: Boolean); begin if FSelected <> Value then begin if Value and (Index <> Tabs.TabControl.TabIndex) then if (Tabs.TabControl.Style = tsTabs) then Exit else if not Tabs.TabControl.MultiSelect then Tabs.TabControl.MultiSelect := True; FSelected := Value; Changed(True); end; end; procedure TTab.SetHighlighted(const Value: Boolean); begin if FHighlighted <> Value then begin FHighlighted := Value; Changed(True); end; end; { TTabs } function TTabs.Add(const ACaption: WideString): TTab; begin Result := TTab(inherited Add); Result.FCaption := ACaption; Result.Changed(True); end; constructor TTabs.Create(TabControl: TCustomTabControl); begin inherited Create(TTab); FTabControl := TabControl; end; function TTabs.GetItem(Index: Integer): TTab; begin Result := TTab(inherited GetItem(Index)); end; function TTabs.GetOwner: TPersistent; begin Result := FTabControl; end; procedure TTabs.Update(Item: TCollectionItem); begin if FUpdating then Exit; FUpdating := True; if Item = nil then begin FTabControl.RequestLayout; end else FTabControl.Invalidate; FUpdating := False; end; procedure TTabs.SetItem(Index: Integer; const Value: TTab); begin inherited SetItem(Index, Value); if Assigned(TabControl) then TabControl.Invalidate; end; function TTabs.CalculateTabHeight(const S: WideString): Integer; var ImageRef: TCustomImageList; begin { Set the Height based on the height of the caption and Images } with TabControl.Canvas do if S = '' then Result := TextHeight('Zy') else Result := TextHeight(S); ImageRef := TabControl.GetImageRef; if Assigned(ImageRef) then if Result < ImageRef.Height then Result := ImageRef.Height + 4; if Result < TabDefaultHeightMap[TabControl.Style] then Result := TabDefaultHeightMap[TabControl.Style]; end; { TTabButton } type TTabButtonDirection = (tbdLeft, tbdRight); TTabScrollButton = class(TSpeedButton) private FTimer: TTimer; FInitialDelay: Word; FDelay: Word; FDirection: TTabButtonDirection; procedure TimerExpired(Sender: TObject); procedure SetDirection(const Value: TTabButtonDirection); protected procedure ChangeScale(MV, DV, MH, DH: Integer); override; procedure EnabledChanged; override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure Paint; override; procedure VisibleChanged; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Delay: Word read FDelay write FDelay default 50; property InitialDelay: Word read FInitialDelay write FInitialDelay default 400; property Direction: TTabButtonDirection read FDirection write SetDirection; end; constructor TTabScrollButton.Create(AOwner: TComponent); begin inherited Create(AOwner); FInitialDelay := 400; FDelay := 50; ControlStyle := ControlStyle + [csNoDesignVisible]; end; destructor TTabScrollButton.Destroy; begin FreeAndNil(FTimer); inherited Destroy; end; procedure TTabScrollButton.TimerExpired(Sender: TObject); begin FTimer.Interval := FDelay; if (FState = bsDown) and MouseCapture then begin try Click; except FTimer.Enabled := False; raise; end; end; end; procedure TTabScrollButton.SetDirection(const Value: TTabButtonDirection); begin if FDirection <> Value then FDirection := Value; end; procedure TTabScrollButton.ChangeScale(MV, DV, MH, DH: Integer); begin { Don't scale } end; procedure TTabScrollButton.EnabledChanged; begin { Don't notify } end; procedure TTabScrollButton.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited MouseDown(Button, Shift, X, Y); if FTimer = nil then begin FTimer := TTimer.Create(Self); FTimer.OnTimer := TimerExpired; end; FTimer.Interval := FInitialDelay; FTimer.Enabled := True; end; procedure TTabScrollButton.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited MouseUp(Button, Shift, X, Y); if FTimer <> nil then FTimer.Enabled := False; end; procedure TTabScrollButton.Paint; const EnabledColors: array [Boolean] of TColor = (clActiveMid, clBlack); var PaintRect: TRect; Offset: TPoint; PrevPen: TPenRecall; PrevBrush: TBrushRecall; begin inherited Paint; with Canvas do begin Offset := Point(0,0); PaintRect := Rect(0, 0, Width - 1, Height - 1); case FState of bsDown: begin Inc(Offset.X); Inc(Offset.Y); end; end; PrevPen := nil; PrevBrush := TBrushRecall.Create(Brush); try PrevPen := TPenRecall.Create(Pen); Pen.Color := EnabledColors[Enabled]; Brush.Color := EnabledColors[Enabled]; Pen.Width := 1; case Direction of tbdLeft: Polygon([ Point(4 + Offset.X, 7 + Offset.Y), Point(7 + Offset.X, 4 + Offset.Y), Point(7 + Offset.X, 10 + Offset.Y), Point(4 + Offset.X, 7 + Offset.Y)]); tbdRight: Polygon([ Point(6 + Offset.X, 4 + Offset.Y), Point(6 + Offset.X, 10 + Offset.Y), Point(9 + Offset.X, 7 + Offset.Y), Point(6 + Offset.X, 4 + Offset.Y)]); end; finally PrevPen.Free; PrevBrush.Free; end; end; end; procedure TTabScrollButton.VisibleChanged; begin inherited; if Visible then Parent.Invalidate; end; { TCustomTabControl } procedure TabControlError(const S: string); begin raise EListError.Create(S); end; constructor TCustomTabControl.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := [csAcceptsControls, csDoubleClicks, csClickEvents, csOpaque]; FTabs := TTabs.Create(Self); Width := 289; Height := 193; FRowCount := 0; FFirstVisibleTab := 0; FLastVisibleTab := 0; FImageBorder := 3; FImageChangeLink := TChangeLink.Create; FImageChangeLink.OnChange := ImageListChange; FMouseOver := -1; FShowFrame := False; FHotTrackColor := clBlue; FTracking := -1; TabStop := True; InputKeys := [ikArrows]; FBitmap := TBitmap.Create; FBitmap.Height := 2; FBitmap.Width := 2; FBitmap.Canvas.Pen.Color := clActiveLight; FBitmap.Canvas.Polyline([Point(0,1),Point(0,1)]); FBitmap.Canvas.Polyline([Point(1,0),Point(1,0)]); FBitmap.Canvas.Pen.Color := clBackground; FBitmap.Canvas.Polyline([Point(0,0),Point(0,0)]); FBitmap.Canvas.Polyline([Point(1,1),Point(1,1)]); FDblBuffer := TBitmap.Create; CreateButtons; end; procedure TCustomTabControl.BeginUpdate; begin Tabs.BeginUpdate; end; destructor TCustomTabControl.Destroy; begin FreeAndNil(FDblBuffer); FreeAndNil(FBitmap); FreeAndNil(FImageChangeLink); FreeAndNil(FTabs); inherited Destroy; end; procedure TCustomTabControl.EndUpdate; begin Tabs.EndUpdate; end; function TCustomTabControl.IndexOfTabAt(X, Y: Integer): Integer; var I: Integer; Rect: TRect; begin Result := -1; if Tabs.Count > 0 then for I := FFirstVisibleTab to FLastVisibleTab do begin Rect := Tabs[I].TabRect; if Rect.Right > RightSide then Rect.Right := RightSide; if PtInRect(Rect, Point(X, Y)) and Tabs[I].Visible then begin Result := I; Break; end; end; end; function TCustomTabControl.TabRect(Index: Integer): TRect; begin Result := Tabs[Index].TabRect; end; procedure TCustomTabControl.ScrollTabs(Delta: Integer); var I: Integer; begin if not FMultiLine then begin for I := 0 to Abs(Delta)-1 do if Delta < 0 then FButtons[tbLeft].Click else FButtons[tbRight].Click; end; end; procedure TCustomTabControl.Changed(Value: Integer); begin if Assigned(FOnChanged) then FOnChanged(Self, Value); end; procedure TCustomTabControl.DrawHighlight(Canvas: TCanvas; const Rect: TRect; ASelected, AHighlight, AEnabled: Boolean); const StyleAdjustment: array [TTabStyle] of Integer = (1, 0, 1, 0); var PrevBrush: TBrushRecall; R: TRect; begin if ASelected and ((Style in [tsButtons, tsFlatButtons]) and not AHighlight) then Canvas.Brush.Bitmap := FBitmap; R := Rect; if (Style = tsTabs) then begin Inc(R.Bottom); if ASelected then InflateRect(R, SELECTED_TAB_SIZE_DELTA, SELECTED_TAB_SIZE_DELTA) else Inc(R.Bottom); end; PrevBrush := TBrushRecall.Create(Canvas.Brush); try if AHighlight then begin if AEnabled then Canvas.Brush.Color := clActiveHighlight else Canvas.Brush.Color := clDisabledHighlight; Canvas.Brush.Bitmap := nil; end; Canvas.Brush.Style := bsSolid; Canvas.FillRect(R); finally PrevBrush.Free; end; Canvas.Brush.Bitmap := nil; end; function TCustomTabControl.DrawTab(TabIndex: Integer; const Rect: TRect; Active: Boolean): Boolean; begin Result := True; if Assigned(FOnDrawTab) then FOnDrawTab(Self, TabIndex, Rect, Active, Result); end; procedure TCustomTabControl.EnabledChanged; begin inherited; EnableScrollButtons; end; procedure TCustomTabControl.FontChanged; begin inherited; Canvas.Font := Font; RequestLayout; end; function TCustomTabControl.GetImageIndex(ATabIndex: Integer): Integer; begin Result := Tabs[ATabIndex].ImageIndex; if Assigned(FOnGetImageIndex) then FOnGetImageIndex(Self, ATabIndex, Result); end; procedure TCustomTabControl.AdjustTabRect(var Rect: TRect); begin case Style of tsTabs: begin Inc(Rect.Top, 1); end; tsButtons: begin Dec(Rect.Right, 3); Inc(Rect.Top, 3); end; tsFlatButtons: begin InflateRect(Rect, -2, -2); Inc(Rect.Left, 2); Dec(Rect.Right, 1); Inc(Rect.Top); Inc(Rect.Bottom); end; end; end; procedure TCustomTabControl.AdjustTabClientRect(var Rect: TRect); begin { Adjust the Tabs rectangle to ignore the Borders } case Style of tsTabs: begin InflateRect(Rect, -TabDefaultBorderWidthMap[Style] - 1, -TabDefaultBorderWidthMap[Style] - 1); Inc(Rect.Bottom, TabDefaultBorderWidthMap[Style] - 1); Dec(Rect.Left, TabDefaultBorderWidthMap[Style] - 1); end; tsButtons: begin InflateRect(Rect, -2, -2); Dec(Rect.Right, 3); Inc(Rect.Top, 3); end; tsFlatButtons: begin InflateRect(Rect, -4, -4); Inc(Rect.Left, 2); Dec(Rect.Right, TAB_FLAT_BORDER + 1); Inc(Rect.Bottom); Inc(Rect.Top); end; end; end; procedure TCustomTabControl.Loaded; begin inherited Loaded; if Images <> nil then UpdateTabImages; RequestLayout; end; procedure TCustomTabControl.UpdateTabImages; var I: Integer; begin for I := 0 to FTabs.Count - 1 do FTabs[I].ImageIndex := GetImageIndex(I); TabsChanged; end; function TCustomTabControl.WantKey(Key: Integer; Shift: TShiftState; const KeyText: WideString): Boolean; var I: Integer; begin Result := False; for I := 0 to Tabs.Count - 1 do if IsAccel(Key, Tabs[I].Caption) and (ssAlt in Shift) then begin TabIndex := Tabs[I].Index; SetFocus; Result := True; Break; end else Result := inherited WantKey(Key, Shift, KeyText); end; function TCustomTabControl.WidgetFlags: Integer; begin Result := inherited WidgetFlags or Integer(WidgetFlags_WRepaintNoErase); end; procedure TCustomTabControl.SetTabIndex(const Value: Integer); function CalculateFirstVisibleTab(Value: Integer): Integer; var vTotalWidth: Integer; begin vTotalWidth := 0; if Value > 0 then repeat { Set Width because we might get here before LayoutTabs} Tabs[Value].Width := TabWidth; if Tabs[Value].Visible then Inc(vTotalWidth, Tabs[Value].Width); if (vTotalWidth + Tabs[Value - 1].Width + (SELECTED_TAB_SIZE_DELTA * 2) <= Rightside) then Dec(Value); until (Value = 0) or (vTotalWidth + (SELECTED_TAB_SIZE_DELTA * 2) >= Rightside); Result := Value; end; begin if FTabIndex <> Value then begin if (Value <> -1) and (Value < 0) or (Value > Tabs.Count-1) then { Don't raise exception to maximize compatibility with VCL } Exit; if CanChange then begin if not MultiLine and (Value <> -1) and ((Value <= FFirstVisibleTab) or (Value >= FLastVisibleTab)) then begin if (Value >= FLastVisibleTab) then begin FLastVisibleTab := Value; FFirstVisibleTab := CalculateFirstVisibleTab(Value); { Sanity Check. The RightSide function bases its result on whether or not the TabScrollButtons are visible and this is determined in part by the variable FFirstVisibleTab. Since this is what we are calculating this becomes a chicken & egg situation. We need to recalculate it again if FFirstVisibleTab is greater than 0 so we can be assured of an accurate result. } if FFirstVisibleTab > 0 then FFirstVisibleTab := CalculateFirstVisibleTab(Value); end else FFirstVisibleTab := Value; end; if Value = -1 then EraseControlFlag; if FTracking <> -1 then Tabs[FTracking].Selected := False; FTracking := -1; FTabIndex := Value; Change; Changed(FTabIndex); if Multiline and (FLastVisibleTab = Tabs.Count - 1) then begin if FTabIndex <> -1 then CalculateRows(Tabs[FTabIndex].Row); { Reset to prevent Layout } FLayoutCount := 0; Invalidate; end else RequestLayout; end; end; end; function TCustomTabControl.GetDisplayRect: TRect; begin Result := ClientRect; Inc(Result.Top, GetTotalTabHeight + 1); end; function TCustomTabControl.GetImageRef: TCustomImageList; begin if Assigned(Images) then Result := Images else if Assigned(HotImages) and HotTrack then Result := HotImages else Result := nil; end; function TCustomTabControl.GetTabIndex: Integer; begin Result := FTabIndex; end; function TCustomTabControl.GetTabHeight: Integer; begin Result := TabHeight; if Result = 0 then Result := Tabs.CalculateTabHeight(''); end; procedure TCustomTabControl.CalcImageTextOffset(const ARect: TRect; const S: WideString; Image: TCustomImageList; var ImagePos, TextPos: TPoint); var TotalWidth: Integer; TotalHeight: Integer; begin if Assigned(Image) then begin TotalWidth := Canvas.TextWidth(S) + (ImageBorder * 2) + Image.Width; TotalHeight := Image.Height; ImagePos.X := ((ARect.Right - ARect.Left) - TotalWidth) div 2; ImagePos.Y := ((ARect.Bottom - ARect.Top) - TotalHeight) div 2; TextPos.X := ImagePos.X + (ImageBorder * 2) + Image.Width; end else begin ImagePos := Point(0,0); TotalWidth := Canvas.TextWidth(S); TextPos.X := ((ARect.Right - ARect.Left) - TotalWidth) div 2; end; TotalHeight := Canvas.TextHeight(S); TextPos.Y := ((ARect.Bottom - ARect.Top) - TotalHeight) div 2; end; procedure TCustomTabControl.CalculateRows(SelectedRow: Integer); var I: Integer; begin if Style = tsTabs then begin for I := FLastVisibleTab downto FFirstVisibleTab do begin if Tabs[I].Row > SelectedRow then Continue; if (Tabs[I].Row = SelectedRow) then Tabs[I].FRow := 1 else if Tabs[I].Row < SelectedRow then Tabs[I].FRow := Tabs[I].Row + 1; end; CalculateTabPositions; end; end; procedure TCustomTabControl.CalculateTabPositions; const TopSpace: array [TTabStyle] of Integer = (2, 0, 0, 0); var LTabHeight: Integer; I: Integer; begin LTabHeight := GetTabHeight; for I := FFirstVisibleTab to FLastVisibleTab do begin if not Tabs[I].Visible then Continue; if not MultiLine then Tabs[I].Top := TopSpace[Style] else case Style of tsTabs: Tabs[I].Top := LTabHeight * (FRowCount - Tabs[I].Row) + SELECTED_TAB_SIZE_DELTA; tsButtons, tsFlatButtons: Tabs[I].Top := LTabHeight * (Tabs[I].Row - 1); tsNoTabs: Tabs[I].Top := 0; end; Tabs[I].Height := LTabHeight; end; end; procedure TCustomTabControl.EnableScrollButtons; begin FUpdating := True; try FButtons[tbLeft].Enabled := Enabled and (FFirstVisibleTab > 0); FButtons[tbRight].Enabled := Enabled and (FLastVisibleTab < Tabs.Count) and (Tabs.Count > 0) and ((FLastVisibleTab <> -1) and (Tabs[FLastVisibleTab].TabRect.Right > RightSide)) and not ((FLastVisibleTab = Tabs.Count - 1) and (Tabs[FLastVisibleTab].Width > RightSide)); finally FUpdating := False; end; end; function TCustomTabControl.FindNextVisibleTab(Index: Integer): Integer; function BackTrack: Integer; var vLeft: Integer; begin Result := Index - 1; vLeft := RightSide; while (Result > 0) and (vLeft > 0) do begin if Tabs[Result].Visible then Dec(vLeft, Tabs[Result].Width); Dec(Result); end; end; begin while (Index < Tabs.Count) and not Tabs[Index].Visible do Inc(Index); Result := Min(Index, Tabs.Count - 1); end; function TCustomTabControl.FindPrevVisibleTab(Index: Integer): Integer; begin Result := 0; while (Index >= 0) and not Tabs[Index].Visible do Dec(Index); if Index > -1 then Result := Index; end; procedure TCustomTabControl.BeginDblBuffer; begin with FDblBuffer do begin Height := GetTotalTabHeight; Width := Self.Width; Canvas.Font := Self.Canvas.Font; Canvas.Brush := Self.Canvas.Brush; Canvas.Pen := Self.Canvas.Pen; Canvas.FillRect(Rect(0, 0, Width, Height)); end; end; procedure TCustomTabControl.EndDblBuffer; begin Canvas.Draw(0, 0, FDblBuffer); end; procedure TCustomTabControl.StretchTabs(ARow: Integer); var Stretch: Integer; I: Integer; FirstTab, LastTab: TTab; TabCount: Integer; procedure CalcRowStats(Row: Integer; var AFirstTab, ALastTab: TTab; var ATabCount: Integer); var I: Integer; begin ATabCount := 0; AFirstTab := nil; ALastTab := nil; for I := FFirstVisibleTab to FLastVisibleTab do begin if Tabs[I].FRow = Row then begin Inc(ATabCount); if AFirstTab = nil then AFirstTab := Tabs[I]; ALastTab := Tabs[I]; end else if (AFirstTab <> nil) and (ALastTab <> nil) then Break; end; end; begin CalcRowStats(ARow, FirstTab, LastTab, TabCount); if TabCount < 1 then Exit; Stretch := RightSide - LastTab.TabRect.Right; Tabs[FirstTab.Index].Width := Tabs[FirstTab.Index].Width + (Stretch div TabCount); for I := FirstTab.Index + 1 to LastTab.Index do begin if not Tabs[I].Visible then Continue; Tabs[I].Width := Tabs[I].Width + (Stretch div TabCount); Tabs[I].Left := Tabs[I - 1].TabRect.Right; end; Tabs[LastTab.Index].Width := Tabs[LastTab.Index].Width + (Stretch mod TabCount); if LastTab.Index > FirstTab.Index then Tabs[LastTab.Index].Left := Tabs[LastTab.Index - 1].TabRect.Right; end; function TCustomTabControl.GetTotalTabHeight: Integer; const SpaceBetweenTabAndFrame: array [TTabStyle] of Integer = (1, 0, -1, 0); var I: Integer; vCurrRow: Integer; vRowCount: Integer; begin Result := 0; if (Tabs.Count > 0) and not (Style = tsNoTabs) then begin if MultiLine then begin vCurrRow := -1; vRowCount := 0; for I := 0 to Tabs.Count - 1 do if Tabs[I].Visible and (vCurrRow <> Tabs[I].Row) then begin Inc(vRowCount); vCurrRow := Tabs[I].Row; end; end else vRowCount := 1; Result := vRowCount * GetTabHeight; Inc(Result, SpaceBetweenTabAndFrame[Style] + SELECTED_TAB_SIZE_DELTA); end; end; function TCustomTabControl.GetTabs: TTabs; begin Result := TTabs(FTabs); end; function TCustomTabControl.HasImages(ATab: TTab): Boolean; var ImageRef: TCustomImageList; begin ImageRef := GetImageRef; Result := Assigned(ImageRef) and (ImageRef.Count > 0); if Result and (ATab <> nil) then Result := (ATab.ImageIndex > -1) and (GetImageIndex(ATab.Index) < ImageRef.Count) and (GetImageIndex(ATab.Index) >= 0); end; function TCustomTabControl.RightSide: Integer; begin DisplayScrollButtons; if FButtons[tbLeft].Visible then Result := FButtons[tbLeft].Left - 1 else Result := Width + RightSideAdjustment; end; procedure TCustomTabControl.ButtonClick(Sender: TObject); begin BeginUpdate; try if Sender = FButtons[tbLeft] then FFirstVisibleTab := FindPrevVisibleTab(FFirstVisibleTab - 1); if Sender = FButtons[tbRight] then if (Tabs[FLastVisibleTab].TabRect.Right > RightSide) or (FindNextVisibleTab(FLastVisibleTab + 1) < Tabs.Count) then FFirstVisibleTab := FindNextVisibleTab(FFirstVisibleTab + 1); finally EndUpdate; end; end; procedure TCustomTabControl.EraseControlFlag(const Value: Boolean = True); begin FErase := Value; end; procedure TCustomTabControl.CreateButtons; var Button: TTabButtons; begin if FButtons[tbLeft] = nil then begin for Button := tbLeft to tbRight do begin FButtons[Button] := TTabScrollButton.Create(Self); with FButtons[Button] do begin Parent := Self; Visible := False; Top := 2; Width := SCROLL_BUTTON_WIDTH; Height := SCROLL_BUTTON_WIDTH; OnClick := ButtonClick; Visible := False; TTabScrollButton(FButtons[Button]).Direction := TTabButtonDirection(Button); end; end; end; end; procedure TCustomTabControl.DisplayScrollButtons; var IsShowing: Boolean; begin PositionButtons; IsShowing := False; if (FLastVisibleTab > -1) and (FLastVisibleTab <= Tabs.Count - 1) and not Multiline then begin IsShowing := (Tabs.Count > 0) and (FFirstVisibleTab > 0) or (FLastVisibleTab < Tabs.Count -1) or (Tabs[FLastVisibleTab].TabRect.Right >= Width + RightSideAdjustment); end; FButtons[tbLeft].Visible := IsShowing; FButtons[tbRight].Visible := IsShowing; end; procedure TCustomTabControl.DrawFocus; const FocusRectAdjust: array[TTabStyle] of Integer = (2, 0, 0, 0); var R, Rect: TRect; begin if Focused and TabStop and not (csDesigning in ComponentState) and (TabIndex > -1) and Tabs[TabIndex].Visible then begin R := Classes.Rect(0, 0, RightSide, GetTotalTabHeight); Rect := Tabs[TabIndex].TabRect; AdjustTabClientRect(Rect); InflateRect(Rect, FocusRectAdjust[Style], FocusRectAdjust[Style]); Canvas.Start; try Canvas.SetClipRect(R); Canvas.DrawFocusRect(Rect); finally InflateRect(Rect, -FocusRectAdjust[Style], -FocusRectAdjust[Style]); Canvas.ResetClipRegion; Canvas.Stop; end; end; end; procedure TCustomTabControl.LayoutTabs; var I, NewLeft, PrevTab, CurrTab, NextTab, MinTabs, NumTabs: Integer; begin if (Style = tsNoTabs) then Exit; FRowCount := 0; MinTabs := 0; NumTabs := 0; FUpdating := True; try if Tabs.Count < 1 then Exit; FLayoutCount := 0; { Tabs start at 2 so that a selected tab will be flush with the left border } NewLeft := TabButtonsLeftMap[Style]; FRowCount := 1; FLastVisibleTab := Tabs.Count - 1; { Find another Tab if the current one has been hidden } if (TabIndex <> -1) and not Tabs[TabIndex].Visible then begin PrevTab := TabIndex; NextTab := FindNextVisibleTab(TabIndex); if not Tabs[NextTab].Visible then NextTab := FindPrevVisibleTab(TabIndex); if not Tabs[NextTab].Visible then NextTab := PrevTab; TabIndex := NextTab; end; for I := FFirstVisibleTab to FLastVisibleTab do begin if not Tabs[I].Visible then Continue; { Set initial Height and Width } Tabs[I].Height := TabHeight; Tabs[I].Width := TabWidth; if MultiLine then begin { Check to see if Tab will fit on current row } if (NewLeft + Tabs[I].Width > RightSide) then begin Inc(FRowCount); NewLeft := TabButtonsLeftMap[Style]; end; Tabs[I].FRow := FRowCount; end else if (NewLeft > RightSide) and (I > 0) then begin FLastVisibleTab := FindPrevVisibleTab(I - 1); Break; end; Tabs[I].Left := NewLeft; NewLeft := Tabs[I].TabRect.Right; if (NewLeft * 2) < RightSide then Inc(MinTabs); Inc(NumTabs); end; { Make sure the last visible tab is properly set. } if not MultiLine and (Tabs[FLastVisibleTab].TabRect.Left + SELECTED_TAB_SIZE_DELTA > RightSide) then FLastVisibleTab := FindPrevVisibleTab(FLastVisibleTab - 1); { Check here to see if the last row has enough tabs to fill it. If not then steal a tab from the prev row until we do or until the prev row is left with the min number of tabs. } if (FRowCount > 1) and (Style = tsTabs) then begin CurrTab := FLastVisibleTab; repeat Dec(CurrTab); until Tabs[CurrTab].Row <> FRowCount; while ((NewLeft * 2) < RightSide) and (NumTabs > MinTabs) and (CurrTab > 0) do begin Tabs[CurrTab].FRow := FRowCount; Inc(NewLeft, Tabs[CurrTab].Width); Dec(NumTabs); Dec(CurrTab); end; NewLeft := TabButtonsLeftMap[Style]; for I := CurrTab + 1 to FLastVisibleTab do begin Tabs[I].Left := NewLeft; Inc(NewLeft, Tabs[I].Width); end end; { Recalculate all the rows of the selected Row and below if the Selected Tab is not on the first row } if MultiLine and (TabIndex <> -1) and (Tabs[TabIndex].Row > 1) and (FRowCount >= Tabs[TabIndex].Row) then CalculateRows(Tabs[TabIndex].Row); { Set the Top for each Tab based on its row } CalculateTabPositions; { Adjust each Tab's width to fit in its row if there is no fixed TabWidth and RaggedRight is not specified } if (not RaggedRight) and MultiLine and (TabWidth = 0) and (FRowCount > 1) then for I := 1 to FRowCount do StretchTabs(I); finally FUpdating := False; end; end; procedure TCustomTabControl.PositionButtons; begin FButtons[tbRight].Top := GetTotalTabHeight - FButtons[tbRight].Height - 2; FButtons[tbLeft].Top := GetTotalTabHeight - FButtons[tbLeft].Height - 2; FButtons[tbRight].Left := Width - SCROLL_BUTTON_WIDTH; FButtons[tbLeft].Left := Width - ((SCROLL_BUTTON_WIDTH) * 2); end; function TCustomTabControl.RightSideAdjustment: Integer; const Adjustment: array [TTabStyle] of Integer = (-2, 3, 6, 0); begin Result := Adjustment[Style]; end; procedure TCustomTabControl.SetTabs(const Value: TTabs); begin FTabs.Assign(Value); RequestLayout; end; procedure TCustomTabControl.SetHotTrack(const Value: Boolean); begin if FHotTrack <> Value then begin FHotTrack := Value; RequestLayout; end; end; procedure TCustomTabControl.SetHotTrackColor(const Value: TColor); begin if FHotTrackColor <> Value then begin FHotTrackColor := Value; end; end; procedure TCustomTabControl.SetImages(const Value: TCustomImageList); begin if Images <> nil then Images.UnRegisterChanges(FImageChangeLink); FImages := Value; if Images <> nil then begin Images.RegisterChanges(FImageChangeLink); Images.FreeNotification(Self); end; ImageListChange(Value); end; procedure TCustomTabControl.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (AComponent = Images) then Images := nil; end; procedure TCustomTabControl.AdjustClientRect(var Rect: TRect); begin { Don't include the tab area } Inc(Rect.Top, GetTotalTabHeight); InflateRect(Rect, -(FRAME_BORDER_WIDTH * 2), -(FRAME_BORDER_WIDTH * 2)); { This can happen if the TabControl is not very tall } if Rect.Bottom < Rect.Top then Rect.Bottom := Rect.Top; end; function TCustomTabControl.CanChange: Boolean; begin Result := True; if Assigned(FOnChanging) then FOnChanging(Self, Result); end; function TCustomTabControl.CanShowTab(TabIndex: Integer): Boolean; begin Result := True; end; procedure TCustomTabControl.Change; begin if Assigned(FOnChange) then FOnChange(Self); end; procedure TCustomTabControl.InternalDrawTabFrame(ACanvas: TCanvas; const ARect: TRect; Tab: TTab; HotTracking: Boolean = False); var R: TRect; PrevPen: TPenRecall; procedure DrawTabFrame(Erase: Boolean); begin with ACanvas do begin if Erase then Pen.Color := clBackground else Pen.Color:= clBtnHighlight; Polyline([Point(R.Left, R.Bottom), Point(R.Left, R.Top + 2), Point(R.Left + 1, R.Top + 1), Point(R.Left + 2, R.Top), Point(R.Right - 3, R.Top)]); if Erase then Pen.Color := clBackground else Pen.Color:= clBtnShadow; Polyline([Point(R.Right - 2, R.Top + 2), Point(R.Right - 2, R.Bottom)]); if Erase then Pen.Color := clBackground else Pen.Color:= clBlack; Polyline([Point(R.Right - 2, R.Top + 1), Point(R.Right - 1, R.Top + 2), Point(R.Right - 1, R.Bottom)]); end; end; begin if not Tab.Visible then Exit; with ACanvas do begin Start; try if not MultiLine then SetClipRect(ARect); R := Tab.TabRect; AdjustTabRect(R); case Style of tsTabs: begin if Tab.Index = TabIndex then begin Dec(R.Top, SELECTED_TAB_SIZE_DELTA); Inc(R.Right, SELECTED_TAB_SIZE_DELTA); Dec(R.Left, SELECTED_TAB_SIZE_DELTA); Inc(R.Bottom, SELECTED_TAB_SIZE_DELTA - 1); end; if DrawTab(Tab.Index, R, Tab.Enabled) then begin { Erase the frame area } PrevPen:= TPenRecall.Create(Pen); try Brush.Style := bsSolid; Pen.Color:= clBackground; Inc(R.Bottom, 1); Rectangle(R); InflateRect(R, -1, -1); Rectangle(R); InflateRect(R, 1, 1); Dec(R.Bottom, 1); if TabIndex = Tab.Index then begin InflateRect(R, -SELECTED_TAB_SIZE_DELTA, -SELECTED_TAB_SIZE_DELTA); Rectangle(R); InflateRect(R, SELECTED_TAB_SIZE_DELTA, SELECTED_TAB_SIZE_DELTA); end; DrawTabFrame(False); finally PrevPen.Free; end; end; end; tsButtons: begin InternalDrawFrame(ACanvas, R, True, (Tab.Index = TabIndex) or (Tab.Selected), True); end; tsFlatButtons: begin PrevPen := TPenRecall.Create(Pen); try Pen.Color:= clBtnShadow; MoveTo(R.Right, R.Top); LineTo(R.Right, R.Bottom - 1); Pen.Color:= clBtnHighlight; MoveTo(R.Right + 1, R.Top); LineTo(R.Right + 1, R.Bottom - 1); finally PrevPen.Free; end; Dec(R.Right, TAB_FLAT_BORDER); if (Tab.Index = TabIndex) or (Tab.Selected) then InternalDrawFrame(ACanvas, R, True, True, True) else begin Brush.Style := bsSolid; FillRect(R); end; end; end; finally if not MultiLine then ResetClipRegion; Stop; end; end; end; procedure TCustomTabControl.InternalDrawTabContents(ACanvas: TCanvas; const ARect: TRect; Tab: TTab; HotTracking: Boolean = False); const TextFlags: array [TTabStyle] of Integer = ( Integer(AlignmentFlags_AlignLeft), Integer(AlignmentFlags_AlignHCenter), Integer(AlignmentFlags_AlignHCenter), 0); var PrevFontColor: TColor; R: TRect; ImageOffset: TPoint; TextOffset: TPoint; ImageRef: TCustomImageList; procedure CalcSelectedOffset(var Point: TPoint); begin if (Tab.Index = TabIndex) or Tab.Selected then begin Inc(Point.X, TabDefaultTextOffsetMap[Style]); Inc(Point.Y, TabDefaultTextOffsetMap[Style]); end; end; begin if not Tab.Visible then Exit; PrevFontColor := Canvas.Font.Color; with ACanvas do begin Start; try if not MultiLine then SetClipRect(ARect); R := Tab.TabRect; AdjustTabClientRect(R); if not HotTracking then DrawHighlight(ACanvas, R, (TabIndex = Tab.Index), Tab.Highlighted, Tab.Enabled); ImageRef := Images; if HotTrack and Assigned(HotImages) then ImageRef := HotImages; if Assigned(ImageRef) and HasImages(Tab) then begin CalcImageTextOffset(R, Tab.Caption, ImageRef, ImageOffset, TextOffset); CalcSelectedOffset(ImageOffset); CalcSelectedOffset(TextOffset); if ((ImageRef = HotImages) and Hottracking) or (ImageRef = Images) then ImageRef.Draw(ACanvas, R.Left + ImageOffset.X, R.Top + ImageOffset.Y, GetImageIndex(Tab.Index), itImage, Tab.Enabled and Enabled); end else begin CalcImageTextOffset(R, Tab.Caption, nil, ImageOffset, TextOffset); CalcSelectedOffset(TextOffset); end; { Draw Text } if not Tab.Enabled or not Enabled then begin { offset the first text slightly to give the recessed disabled look } Font.Color := clDisabledLight; TextRect(R, R.Left + TextOffset.X + 1, R.Top + TextOffset.Y + 1, Tab.Caption, Integer(AlignmentFlags_SingleLine) or Integer(AlignmentFlags_ShowPrefix)); Font.Color := clDisabledText; end else if HotTracking and (Style <> tsFlatButtons) then Font.Color := HotTrackColor else if Tab.Highlighted then Font.Color := clHighlightedText; TextRect(R, R.Left + TextOffset.X, R.Top + TextOffset.Y, Tab.Caption, Integer(AlignmentFlags_SingleLine) or Integer(AlignmentFlags_ShowPrefix)); finally Font.Color := PrevFontColor; if not Multiline then ResetClipRegion; Stop; end; end; end; procedure TCustomTabControl.InternalDrawFrame(ACanvas: TCanvas; ARect: TRect; AShowFrame: Boolean = True; Sunken: Boolean = False; Fill : Boolean = True); const FrameColorOuter: array [Boolean] of TColor = (clActiveLight, clActiveShadow); FrameColorInner: array [Boolean] of TColor = (clBackground, clActiveDark); FrameRectOffset: array [Boolean] of Integer = (3, -1); var PrevPen: TPenRecall; PrevBrush: TBrushRecall; DrawRegion: QRegionH; ControlRegion: QRegionH; VControl: TControl; I: Integer; R: TRect; function DisplayFrame: Boolean; begin Result := AShowFrame or (Style = tsTabs); end; begin with ACanvas do try Start; if (csDesigning in ComponentState) and not AShowFrame and (Style = tsNoTabs) then begin PrevPen := nil; PrevBrush := TBrushRecall.Create(Canvas.Brush); try PrevPen := TPenRecall.Create(Canvas.Pen); Pen.Style := psDot; Brush.Style := bsSolid; if Fill then FillRect(ARect); Rectangle(0, GetTotalTabHeight, Width, Height); Exit; finally PrevBrush.Free; PrevPen.Free; end; end; Dec(ARect.Bottom, 1); Dec(ARect.Right, 1); if DisplayFrame then begin PrevPen := TPenRecall.Create(Canvas.Pen); try Pen.Color := FrameColorOuter[Sunken]; Polyline([Point(ARect.Left, ARect.Bottom), Point(ARect.Left, ARect.Top), Point(ARect.Right - 1, ARect.Top)]); Pen.Color := FrameColorInner[Sunken]; Polyline([Point(ARect.Left + 1, ARect.Bottom - 1), Point(ARect.Left + 1, ARect.Top + 1), Point(ARect.Right - 2, ARect.Top + 1)]); Pen.Color := FrameColorOuter[not Sunken]; Polyline([Point(ARect.Right, ARect.Top), Point(ARect.Right, ARect.Bottom), Point(ARect.Left, ARect.Bottom)]); Pen.Color := FrameColorInner[not Sunken]; Polyline([Point(ARect.Right -1, ARect.Top + 1), Point(ARect.Right - 1, ARect.Bottom - 1), Point(ARect.Left + 1, ARect.Bottom - 1)]); finally PrevPen.Free; end; end; InflateRect(ARect, FrameRectOffset[DisplayFrame], FrameRectOffset[DisplayFrame]); Inc(ARect.Top); Inc(ARect.Left); { Clear the interior of the page } if Fill then begin FillRect(ARect); end else begin DrawRegion := QRegion_create(@ARect, QRegionRegionType_Rectangle); try { Erase the interior excluding any opaque controls } for I := 0 to ControlCount - 1 do begin VControl := TControl(Controls[I]); if (VControl.Visible or ((csDesigning in VControl.ComponentState) and not (csNoDesignVisible in VControl.ControlStyle))) and (csOpaque in VControl.ControlStyle) then begin R := VControl.BoundsRect; ControlRegion := QRegion_create(@R, QRegionRegionType_Rectangle); try QRegion_subtract(DrawRegion, DrawRegion, ControlRegion); finally QRegion_destroy(ControlRegion); end; if QRegion_isEmpty(DrawRegion) then Break; end; end; if not QRegion_isEmpty(DrawRegion) then QWidget_erase(Self.Handle, DrawRegion); finally QRegion_destroy(DrawRegion); end; end; finally Stop; end; end; procedure TCustomTabControl.Paint; const TabFrameAdj: array [Boolean] of Integer = (0, SELECTED_TAB_SIZE_DELTA); var I: Integer; R: TRect; begin inherited Paint; if FLayoutCount > 0 then LayoutTabs; EnableScrollButtons; DisplayScrollButtons; Canvas.Brush.Color := Color; Canvas.Brush.Style := bsSolid; R := Rect(0, GetTotalTabHeight, Width, Height); InternalDrawFrame(Canvas, R, ShowFrame, False, FErase); EraseControlFlag(False); if (Style <> tsNoTabs) and (Tabs.Count > 0) then begin BeginDblBuffer; try R := Rect(0, 0, RightSide, GetTotalTabHeight + 1); for I := FFirstVisibleTab to FLastVisibleTab do if Tabs[I].Visible then if I <> TabIndex then begin InternalDrawTabFrame(FDblBuffer.Canvas, R, Tabs[I], (I = FMouseOver) and HotTrack); InternalDrawTabContents(FDblBuffer.Canvas, R, Tabs[I], (I = FMouseOver) and HotTrack); end; finally EndDblBuffer; end; if (TabIndex >= FFirstVisibleTab) and (TabIndex <= FLastVisibleTab) and (TabIndex > -1) then begin { Draw Selected Tab } InternalDrawTabFrame(Canvas, R, Tabs[TabIndex], (TabIndex = FMouseOver) and HotTrack); InternalDrawTabContents(Canvas, R, Tabs[TabIndex], (TabIndex = FMouseOver) and HotTrack); DrawFocus; end; end; end; procedure TCustomTabControl.RequestAlign; begin inherited RequestAlign; RequestLayout; end; procedure TCustomTabControl.RequestLayout; begin if FUpdating then Exit; Inc(FLayoutCount); Invalidate; end; procedure TCustomTabControl.Resize; begin inherited Resize; PositionButtons; RequestLayout; end; procedure TCustomTabControl.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var vTabIndex: Integer; begin if Button <> mbLeft then Exit; vTabIndex := IndexOfTabAt(X, Y); if vTabIndex = -1 then Exit; if not Tabs[vTabIndex].Enabled then Exit; { Mark tab as selected if CTRL down. If the user clicks on the currently selected tab then unselect the rest } if (ssCtrl in Shift) and MultiSelect and (Style in [tsButtons, tsFlatButtons]) then begin Tabs[vTabIndex].Selected := not Tabs[vTabIndex].Selected; if vTabIndex = TabIndex then begin TabIndex := -1; UnselectTabs; end; Invalidate; end else begin UnselectTabs; if (vTabIndex > -1) and (vTabIndex <> TabIndex) then if (Style <> tsFlatButtons) or (FTracking = vTabIndex) then TabIndex := vTabIndex; end; { Call inherited last. This allows the OnChanging, OnPageChanging and OnChanged events to fire before the Mouse up. } inherited MouseUp(Button, Shift, X, Y); end; procedure TCustomTabControl.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited MouseDown(Button, Shift, X, Y); if (Button = mbLeft) and (Style = tsFlatButtons) then begin FTracking := IndexOfTabAt(X, Y); FMouseOver := -1; DoHotTrack(FTracking); end; end; procedure TCustomTabControl.DoHotTrack(const Value: Integer); procedure DrawHotTrack(Erase: Boolean); var R, Rect: TRect; begin if FMouseOver > -1 then begin R := Classes.Rect(0, 0, RightSide, GetTotalTabHeight + 1); case Style of tsTabs, tsButtons: begin if HotTrack then begin InternalDrawTabContents(Canvas, R, Tabs[FMouseOver], not Erase); if Erase then begin if (FMouseOver <> TabIndex) and (FMouseOver >= FFirstVisibleTab) and (FMouseOver <= FLastVisibleTab) then begin InternalDrawTabFrame(Canvas, R, Tabs[TabIndex], not Erase); InternalDrawTabContents(Canvas, R, Tabs[TabIndex], not Erase); end; DrawFocus; end; end; end; tsFlatButtons: begin if not (HotTrack) and (FTracking > -1) and (FMouseOver <> FTracking) and (FTracking <> TabIndex) then begin InternalDrawTabFrame(Canvas, R, Tabs[FTracking]); InternalDrawTabContents(Canvas, R, Tabs[FTracking]); end; if Erase then begin InternalDrawTabFrame(Canvas, R, Tabs[FMouseOver]); InternalDrawTabContents(Canvas, R, Tabs[FMouseOver]); end else begin Canvas.Start; try Canvas.SetClipRect(R); if (FMouseOver <> TabIndex) then begin Rect := Tabs[FMouseOver].TabRect; AdjustTabRect(Rect); Dec(Rect.Right, TAB_FLAT_BORDER); DrawShadePanel(Canvas, Rect, False, 1, Palette.ColorGroup(cgActive)); end; InternalDrawTabContents(Canvas, R, Tabs[FMouseOver], HotTrack); if (FMouseOver = TabIndex) and ((FTracking = -1) or (FTracking = TabIndex)) then DrawFocus; finally Canvas.ResetClipRegion; Canvas.Stop; end; end; if FMouseOver = TabIndex then DrawFocus; end; end; end; end; begin if (FMouseOver <> Value) then begin if MultiLine or ((FMouseOver >= FFirstVisibleTab) and (FMouseOver <= FLastVisibleTab)) then DrawHotTrack(True); FMouseOver := Value; if HotTrack or (FTracking = Value) then DrawHotTrack(False); end; end; procedure TCustomTabControl.MouseLeave(AControl: TControl); begin inherited MouseLeave(AControl); // When the mouse leaves at high speed it might leave a tab highlighted. Kill it. DoHotTrack(-1); end; procedure TCustomTabControl.MouseMove(Shift: TShiftState; X, Y: Integer); var Index: Integer; begin inherited MouseMove(Shift, X, Y); Index := IndexOfTabAt(X, Y); if (Index = -1) or (Tabs[Index].TabRect.Left <= RightSide) then DoHotTrack(Index); end; function TCustomTabControl.DoMouseWheel(Shift: TShiftState; WheelDelta: Integer; const MousePos: TPoint): Boolean; begin inherited DoMouseWheel(Shift, WheelDelta, MousePos); Result := True; end; function TCustomTabControl.DoMouseWheelDown(Shift: TShiftState; const MousePos: TPoint): Boolean; begin Result := inherited DoMouseWheelDown(Shift, MousePos); if TabIndex > 0 then TabIndex := TabIndex - 1; end; function TCustomTabControl.DoMouseWheelUp(Shift: TShiftState; const MousePos: TPoint): Boolean; begin Result := inherited DoMouseWheelUp(Shift, MousePos); if TabIndex < Tabs.Count-1 then TabIndex := TabIndex + 1; end; procedure TCustomTabControl.ImageListChange(Sender: TObject); begin RequestLayout; end; procedure TCustomTabControl.KeyUp(var Key: Word; Shift: TShiftState); var Delta: Integer; function RangeCheckTracking(const Value: Integer): Integer; begin Result := Value; if (Result > Tabs.Count - 1) or (Result < -1) then Result := FTracking; end; procedure ChangeTracking(const Delta: ShortInt); begin if FTracking = -1 then FTracking := RangeCheckTracking(TabIndex + Delta) else begin Tabs[FTracking].Selected := False; FTracking := RangeCheckTracking(FTracking + Delta); end; if FTracking > -1 then Tabs[FTracking].Selected := True; if not Multiline then ScrollTabs(Delta); end; procedure ChangeTabIndex(const Delta: Integer); begin if (TabIndex + Delta > Tabs.Count - 1) or (TabIndex + Delta < 0) then Exit else TabIndex := TabIndex + Delta; end; begin inherited KeyUp(Key, Shift); Delta := 0; case Key of Key_Tab: if (ssCtrl in Shift) then if ssShift in Shift then Delta := -1 else Delta := 1; Key_Right, Key_Down: if not (Shift = [ssAlt]) then Delta := 1; Key_Left, Key_Up: if not (Shift = [ssAlt]) then Delta := -1; Key_Home: if not (Shift = [ssAlt]) then if FTracking <> -1 then Delta := - FTracking else Delta := -TabIndex; Key_End: if not (Shift = [ssAlt]) then if FTracking <> -1 then Delta := Tabs.Count - FTracking - 1 else Delta := Tabs.Count - TabIndex - 1; Key_Return, Key_Enter, Key_Space: if not (Shift = [ssAlt]) then if FTracking <> -1 then TabIndex := FTracking; end; if Delta <> 0 then if (Style = tsTabs) or (Key = Key_Tab) then ChangeTabIndex(Delta) else ChangeTracking(Delta); end; procedure TCustomTabControl.SetMultiLine(const Value: Boolean); begin if FMultiLine <> Value then begin FMultiLine := Value; FFirstVisibleTab := 0; FLastVisibleTab := Tabs.Count-1; RequestLayout; end; end; procedure TCustomTabControl.SetMultiSelect(const Value: Boolean); begin if FMultiSelect <> Value then begin FMultiSelect := Value; if not FMultiSelect then UnselectTabs; Invalidate; end; end; procedure TCustomTabControl.SetOwnerDraw(const Value: Boolean); begin if FOwnerDraw <> Value then begin FOwnerDraw := Value; end; end; procedure TCustomTabControl.SetRaggedRight(const Value: Boolean); begin if FRaggedRight <> Value then begin FRaggedRight := Value; RequestLayout; end; end; procedure TCustomTabControl.SetStyle(Value: TTabStyle); begin if FStyle <> Value then begin FStyle := Value; if csDesigning in ComponentState then FShowFrame := FShowFrame and (Value = tsTabs); EraseControlFlag; RequestLayout; end; end; procedure TCustomTabControl.SetTabHeight(const Value: Smallint); begin if FTabSize.Y <> Value then begin if Value < 0 then raise EInvalidOperation.CreateFmt(SPropertyOutOfRange, [Self.Classname]); FTabSize.Y := Value; TabsChanged; end; end; procedure TCustomTabControl.SetTabWidth(const Value: Smallint); begin if FTabSize.X <> Value then begin if Value < 0 then raise EInvalidOperation.CreateFmt(SPropertyOutOfRange, [Self.Classname]); FTabSize.X := Value; TabsChanged; end; end; procedure TCustomTabControl.TabsChanged; begin RequestLayout; end; procedure TCustomTabControl.SetShowFrame(const Value: Boolean); begin if FShowFrame <> Value then begin FShowFrame := Value; EraseControlFlag; Invalidate; end; end; procedure TCustomTabControl.SetHotImages(const Value: TCustomImageList); begin if HotImages <> nil then HotImages.UnRegisterChanges(FImageChangeLink); FHotImages := Value; if HotImages <> nil then begin HotImages.RegisterChanges(FImageChangeLink); HotImages.FreeNotification(Self); end; ImageListChange(Value); end; procedure TCustomTabControl.UnselectTabs; var I: Integer; begin for I := 0 to Tabs.Count-1 do if Tabs[I].Selected then Tabs[I].Selected := False; end; { TTabSheet } constructor TTabSheet.Create(AOwner: TComponent); begin inherited Create(AOwner); Align := alClient; ControlStyle := ControlStyle + [csAcceptsControls, csNoDesignVisible]; Visible := False; TabVisible := True; end; destructor TTabSheet.Destroy; begin if (FPageControl <> nil) and not (csDestroying in FPageControl.ComponentState) then FPageControl.RemovePage(Self); inherited Destroy; end; procedure TTabSheet.InitWidget; begin inherited; QWidget_setFocusPolicy(Handle, QWidgetFocusPolicy_NoFocus); end; function TTabSheet.GetTabIndex: Integer; begin if Assigned(FTab) then Result := FTab.Index else Result := -1; end; procedure TTabSheet.AdjustClientRect(var Rect: TRect); begin inherited AdjustClientRect(Rect); InflateRect(Rect, -BorderWidth, -BorderWidth); if Rect.Bottom < Rect.Top then Rect.Bottom := Rect.Top; end; procedure TTabSheet.DoHide; begin if Assigned(FOnHide) then FOnHide(Self); end; procedure TTabSheet.DoShow; begin if Assigned(FOnShow) then FOnShow(Self); end; procedure TTabSheet.EnabledChanged; begin inherited; if Assigned(FPageControl) then FPageControl.UpdateTab(Self); end; procedure TTabSheet.ReadState(Reader: TReader); begin inherited ReadState(Reader); if Reader.Parent is TPageControl then PageControl := TPageControl(Reader.Parent); end; procedure TTabSheet.TextChanged; begin if Assigned(FPageControl) then FPageControl.UpdateTab(Self); end; procedure TTabSheet.ShowingChanged; begin inherited; try if Showing then DoShow else DoHide; except Application.HandleException(Self); end; end; procedure TTabSheet.SetBorderWidth(const Value : TBorderWidth); begin if FBorderWidth <> Value then begin FBorderWidth := Value; Realign; Invalidate; end; end; procedure TTabSheet.SetHighlighted(const Value: Boolean); begin if FHighlighted <> Value then FHighlighted := Value; if Assigned(FPageControl) then FPageControl.UpdateTab(Self); end; procedure TTabSheet.SetImageIndex(const Value: TImageIndex); begin if FImageIndex <> Value then FImageIndex := Value; if Assigned(FPageControl) then FPageControl.UpdateTab(Self); end; procedure TTabSheet.SetPageControl(const Value: TPageControl); begin if PageControl <> Value then begin if PageControl <> nil then PageControl.RemovePage(Self); Parent := Value; if Value <> nil then Value.InsertPage(Self); end; end; function TTabSheet.GetPageIndex: Integer; begin if PageControl <> nil then Result := PageControl.FPages.IndexOf(Self) else Result := -1; end; procedure TTabSheet.SetPageIndex(const Value: Integer); var I, MaxPageIndex: Integer; begin if PageControl <> nil then begin MaxPageIndex := PageControl.PageCount - 1; if Value > MaxPageIndex then raise EListError.CreateResFmt(@SPageIndexError, [Value, MaxPageIndex]); I := TabIndex; PageControl.FPages.Move(PageIndex, Value); PageControl.TabIndex := PageIndex; if I >= 0 then PageControl.MoveTab(I, PageControl.TabIndex); end; end; procedure TTabSheet.SetTabVisible(const Value: Boolean); begin if FTabVisible <> Value then FTabVisible := Value; if Assigned(FPageControl) then FPageControl.UpdateTab(Self); end; { TPageControl } constructor TPageControl.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := ControlStyle - [csAcceptsControls]; FPages := TList.Create; end; procedure TPageControl.DoContextPopup(const MousePos: TPoint; var Handled: Boolean); begin { Since the TTabSheet doesn't cover the entire client area (there is a 4 pixel border) we don't want the popup to display for the PageControl unless it is within the Tab area. } Handled := (MousePos.Y > GetTotalTabHeight) and (ControlAtPos(MousePos, False, True) = nil); if not Handled then inherited DoContextPopup(MousePos, Handled); end; function TPageControl.CanShowTab(TabIndex: Integer): Boolean; begin Result := TTabSheet(FPages[TabIndex]).Enabled; end; procedure TPageControl.Changed(Value: Integer); begin inherited Changed(Value); ActivePageIndex := Value; end; procedure TPageControl.Change; var Form: TCustomForm; begin UpdateActivePage; if csDesigning in ComponentState then begin Form := GetParentForm(Self); if (Form <> nil) and (Form.DesignerHook <> nil) then Form.DesignerHook.Modified; end; inherited Change; end; procedure TPageControl.ChangeActivePage(Page: TTabSheet); var ParentForm: TCustomForm; AllowChange: Boolean; begin AllowChange := True; if FActivePage <> Page then begin if not (csLoading in ComponentState) then PageChanging(Page, AllowChange); if not AllowChange then Exit; ParentForm := GetParentForm(Self); if (ParentForm <> nil) and (FActivePage <> nil) and FActivePage.ContainsControl(ParentForm.ActiveControl) then begin ParentForm.ActiveControl := FActivePage; if ParentForm.ActiveControl <> FActivePage then begin TabIndex := FActivePage.TabIndex; Exit; end; end; if Page <> nil then begin Page.Visible := True; Page.BringToFront; if (ParentForm <> nil) and (FActivePage <> nil) and (ParentForm.ActiveControl = FActivePage) then if Page.CanFocus then ParentForm.ActiveControl := Page else ParentForm.ActiveControl := Self; end; if FActivePage <> nil then FActivePage.Visible := False; FActivePage := Page; if not (csLoading in ComponentState) then PageChange; if (ParentForm <> nil) and (FActivePage <> nil) and (ParentForm.ActiveControl = FActivePage) then FActivePage.SelectFirst; end; end; destructor TPageControl.Destroy; begin FPages.Free; inherited Destroy; end; function TPageControl.FindNextPage(CurPage: TTabSheet; GoForward, CheckTabVisible: Boolean): TTabSheet; var I, StartIndex: Integer; begin if (PageCount > 0) then begin StartIndex := FPages.IndexOf(CurPage); if StartIndex = -1 then if GoForward then StartIndex := PageCount - 1 else StartIndex := 0; I := StartIndex; repeat if GoForward then begin Inc(I); if I = PageCount then I := 0; end else begin if I = 0 then I := PageCount; Dec(I); end; Result := Pages[I]; if not CheckTabVisible or Result.TabVisible then Exit; until I = StartIndex; end; Result := nil; end; procedure TPageControl.DeleteTab(Page: TTabSheet; Index: Integer); var UpdateIndex: Boolean; begin UpdateIndex := Page = ActivePage; Tabs.Delete(Index); if UpdateIndex then begin if Index >= Tabs.Count then Index := Tabs.Count - 1; TabIndex := Index; end; UpdateActivePage; end; function TPageControl.GetActivePageIndex: Integer; begin if ActivePage <> nil then Result := ActivePage.GetPageIndex else Result := -1; end; function TPageControl.DesignEventQuery(Sender: QObjectH; Event: QEventH): Boolean; var Index: Integer; MousePos: TPoint; Control: TControl; begin Result := False; if (Sender = Handle) and (QEvent_type(Event) in [QEventType_MouseButtonPress, QEventType_MouseButtonRelease, QEventType_MouseButtonDblClick]) then begin MousePos := Point(QMouseEvent_x(QMouseEventH(Event)), QMouseEvent_y(QMouseEventH(Event))); Control := ControlAtPos(MousePos, True, True); if (Control is TTabScrollButton) then Result := Control.Enabled else begin Index := IndexOfTabAt(MousePos.X, MousePos.Y); Result := (Index <> -1) and (Index <> TabIndex); end; end; end; procedure TPageControl.GetChildren(Proc: TGetChildProc; Root: TComponent); var I: Integer; begin for I := 0 to FPages.Count - 1 do Proc(TComponent(FPages[I])); end; function TPageControl.GetPage(Index: Integer): TTabSheet; begin Result := TTabSheet(FPages[Index]); end; function TPageControl.GetPageCount: Integer; begin Result := FPages.Count; end; procedure TPageControl.MoveTab(CurIndex, NewIndex: Integer); begin Tabs[CurIndex].Index := NewIndex; end; procedure TPageControl.InsertPage(const APage: TTabSheet); begin BeginUpdate; try FPages.Add(aPage); APage.FPageControl := Self; InsertTab(APage); UpdateActivePage; finally EndUpdate; end; end; procedure TPageControl.InsertTab(Page: TTabSheet); begin Page.FTab := TTab(Tabs.Add(Page.Caption)); UpdateTab(Page); UpdateActivePage; end; procedure TPageControl.RemovePage(const APage: TTabSheet); var NextSheet: TTabSheet; begin NextSheet := FindNextPage(aPage, True, not (csDesigning in ComponentState)); if NextSheet = APage then NextSheet := nil; DeleteTab(APage, APage.PageIndex); APage.FPageControl := nil; FPages.Remove(APage); SetActivePage(NextSheet); end; procedure TPageControl.UpdateTab(Page: TTabSheet); begin if Assigned(FTabs) then begin Tabs[Page.TabIndex].Caption := Page.Caption; Tabs[Page.TabIndex].ImageIndex := Page.ImageIndex; Tabs[Page.TabIndex].Highlighted := Page.Highlighted; Tabs[Page.TabIndex].Visible := Page.TabVisible; end; end; procedure TPageControl.SelectNextPage(GoForward: Boolean); var Page: TTabSheet; begin Page := FindNextPage(ActivePage, GoForward, True); if (Page <> nil) and (Page <> ActivePage) then begin TabIndex := Page.TabIndex; end; end; procedure TPageControl.SetActivePage(aPage: TTabSheet); begin if (aPage <> nil) and (aPage.PageControl <> Self) then Exit; ChangeActivePage(aPage); if aPage = nil then TabIndex := -1 else if aPage = FActivePage then begin TabIndex := aPage.PageIndex; end; end; procedure TPageControl.SetActivePageIndex(const Value: Integer); begin if (Value > -1) and (Value < PageCount) then ActivePage := TTabSheet(Pages[Value]) else ActivePage := nil; end; procedure TPageControl.PageChange; begin if Assigned(FOnPageChange) then FOnPageChange(Self); end; procedure TPageControl.PageChanging(NewPage: TTabSheet; var AllowChange: Boolean); begin if Assigned(FOnPageChanging) then FOnPageChanging(Self, NewPage, AllowChange); end; procedure TPageControl.SetChildOrder(Child: TComponent; Order: Integer); begin TTabSheet(Child).PageIndex := Order; end; procedure TPageControl.ShowControl(AControl: TControl); begin if (AControl is TTabSheet) and (TTabSheet(AControl).PageControl = Self) then SetActivePage(TTabSheet(AControl)); inherited ShowControl(AControl); end; procedure TPageControl.UpdateActivePage; begin if TabIndex >= 0 then SetActivePage(FPages[TabIndex]) else SetActivePage(nil); end; procedure TPageControl.Update; begin if Style = tsNoTabs then Realign; inherited Update; end; { utility routines for TreeView/TreeNode } procedure TreeViewError(const Msg: string); begin raise ETreeViewError.Create(Msg); end; procedure TreeViewErrorFmt(const Msg: string; Format: array of const); begin raise ETreeViewError.CreateFmt(Msg, Format); end; type TListViewHeader = class(TCustomHeaderControl) private FHidden: Boolean; FHiddenChanging: Boolean; procedure SetSections(const Value: TListColumns); function GetSections: TListColumns; procedure SetHidden(const Value: Boolean); function ListViewHandle: QListViewH; function ViewControl: TCustomViewControl; protected function EventFilter(Sender: QObjectH; Event: QEventH): Boolean; override; function GetHandle: QHeaderH; override; procedure ColumnClicked(Section: TCustomHeaderSection); override; procedure ColumnMoved(Section: TCustomHeaderSection); override; procedure ColumnResized(Section: TCustomHeaderSection); override; procedure CreateWidget; override; procedure DestroyWidget; override; procedure HookEvents; override; procedure InitWidget; override; procedure Update; override; procedure UpdateWidgetShowing; override; property Handle: QHeaderH read GetHandle; property Hidden: Boolean read FHidden write SetHidden default True; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Sections: TListColumns read GetSections write SetSections; end; type TSubItems = class(TStringList) private FOwner: TCustomViewItem; protected function GetHandle: QListViewItemH; function HandleAllocated: Boolean; function Add(const S: string): Integer; override; procedure Delete(Index: Integer); override; procedure Put(Index: Integer; const S: string); override; procedure PutObject(Index: Integer; AObject: TObject); override; procedure InsertItem(Index: Integer; const S: string; AObject: TObject); override; public constructor Create(AOwner: TCustomViewItem); procedure Insert(Index: Integer; const S: string); override; procedure AssignTo(Dest: TPersistent); override; property Handle: QListViewItemH read GetHandle; property Owner: TCustomViewItem read FOwner; end; procedure TCustomViewItems.Delete(Index: Integer); begin FItems[Index].Delete; end; function TCustomViewItems.FindViewItem(ItemH: QListViewItemH): TCustomViewItem; var I: Integer; begin Result := nil; if ItemH = nil then Exit; Result := TCustomViewItem(QClxObjectMap_find(ItemH)); if Assigned(Result) then Exit; for I := 0 to Count-1 do begin if FItems[I].Handle = ItemH then begin Result := FItems[I]; Exit; end; end; end; { TSubItems } function TSubItems.Add(const S: string): Integer; var WS: WideString; begin Result := inherited Add(S); Objects[Result] := Pointer(-1); if HandleAllocated and FOwner.ViewControlValid and FOwner.ViewControl.ShowColumnHeaders then begin WS := S; QListViewItem_setText(Handle, Result+1, PWideString(@WS)); end; end; procedure TSubItems.AssignTo(Dest: TPersistent); var I: Integer; begin if Dest is TSubItems then begin BeginUpdate; try TStrings(Dest).Clear; for I := 0 to Count-1 do TStrings(Dest).AddObject(Strings[I], Objects[I]); finally EndUpdate; end; end else inherited AssignTo(Dest); end; constructor TSubItems.Create(AOwner: TCustomViewItem); begin inherited Create; FOwner := AOwner; end; procedure TSubItems.Delete(Index: Integer); begin inherited Delete(Index); if HandleAllocated then QListViewItem_setText(Handle, Index+1, nil); end; function TSubItems.GetHandle: QListViewItemH; begin if FOwner.HandleAllocated then Result := FOwner.Handle else Result := nil; end; function TSubItems.HandleAllocated: Boolean; begin Result := Handle <> nil; end; procedure TSubItems.Insert(Index: Integer; const S: string); begin inherited Insert(Index, S); Objects[Index] := Pointer(-1); end; procedure TSubItems.InsertItem(Index: Integer; const S: string; AObject: TObject); var WS: WideString; begin inherited InsertItem(Index, S, AObject); if HandleAllocated and FOwner.ViewControlValid and FOwner.ViewControl.ShowColumnHeaders then begin Inc(Index); WS := S; QListViewItem_setText(FOwner.Handle, Index, PWideString(@WS)); FOwner.ImageIndexChange(Index, Integer(AObject)); end; end; procedure TSubItems.Put(Index: Integer; const S: string); var WS: WideString; begin inherited Put(Index, S); if HandleAllocated and FOwner.ViewControlValid and FOwner.ViewControl.ShowColumnHeaders then begin WS := S; QListViewItem_setText(Handle, Index+1, PWideString(@WS)); end; end; procedure TSubItems.PutObject(Index: Integer; AObject: TObject); begin if Integer(Objects[Index]) <> Integer(AObject) then begin inherited PutObject(Index, AObject); Inc(Index); FOwner.ImageIndexChange(Index, Integer(AObject)); end; end; { TCustomViewControl } constructor TCustomViewControl.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := [csCaptureMouse, csClickEvents, csDoubleClicks]; FImageLink := TChangeLink.Create; FImageLink.OnChange := ImageListChange; FHeader := TListViewHeader.Create(Self); FIndent := 20; FTimer := TTimer.Create(nil); FTimer.Enabled := False; FTimer.Interval := 500; FTimer.OnTimer := TimerIntervalElapsed; FSortDirection := sdAscending; ParentColor := False; TabStop := True; BorderStyle := bsSunken3d; InputKeys := [ikChars, ikArrows]; Height := 97; Width := 121; end; destructor TCustomViewControl.Destroy; begin CheckRemoveEditor; if Assigned(FMemStream) then FreeAndNil(FMemStream); FTimer.Free; FHeader.Free; FImageLink.Free; inherited Destroy; if Assigned(FItemHooks) then QClxListViewHooks_destroy(FItemHooks); end; procedure TCustomViewControl.ColorChanged; begin inherited ColorChanged; UpdateControl; end; procedure TCustomViewControl.CreateWidget; begin FHandle := QListView_create(ParentWidget, nil); Hooks := QListView_hook_create(FHandle); FItemHooks := QClxListViewHooks_create; FViewportHandle := QScrollView_viewport(Handle); QClxObjectMap_add(FViewportHandle, Integer(Self)); FHScrollHandle := QScrollView_horizontalScrollBar(Handle); QClxObjectMap_add(FHScrollHandle, Integer(Self)); FVScrollHandle := QScrollView_verticalScrollBar(Handle); QClxObjectMap_add(FVScrollHandle, Integer(Self)); end; const cSelMode: array [Boolean] of QListViewSelectionMode = (QListViewSelectionMode_Single, QListViewSelectionMode_Extended); cSortDirection: array [TSortDirection] of Boolean = (True, False); procedure TCustomViewControl.InitWidget; begin inherited InitWidget; QWidget_setMouseTracking(FViewportHandle, True); QWidget_setAcceptDrops(FViewportHandle, True); QListView_setShowSortIndicator(Handle, FShowColumnSortIndicators); QListView_setTreeStepSize(Handle, FIndent); TListViewHeader(FHeader).Hidden := not FShowColumnHeaders; QListView_setSelectionMode(Handle, cSelMode[FMultiSelect]); QListView_setAllColumnsShowFocus(Handle, FRowSelect); if Sorted then QListView_setSorting(Handle, SortColumn, cSortDirection[SortDirection]) else QListView_setSorting(Handle, -1, False); UpdateControl; end; function TCustomViewControl.EventFilter(Sender: QObjectH; Event: QEventH): Boolean; begin if (Sender = QScrollView_verticalScrollBar(Handle)) or (Sender = QScrollView_horizontalScrollBar(Handle)) then begin Result := False; case QEvent_type(Event) of QEventType_MouseButtonPress, QEventType_MouseButtonDblClick, QEventType_FocusIn: CheckRemoveEditor; end; Exit; end; if (QEvent_type(Event) = QEventType_FocusIn) then CheckRemoveEditor; Result := inherited EventFilter(Sender, Event); end; procedure TCustomViewControl.ItemChangeHook(item: QListViewItemH; _type: TItemChange); begin try ItemChange(item, _type); except Application.HandleException(Self); end; end; procedure TCustomViewControl.ItemChangingHook(item: QListViewItemH; _type: TItemChange; var Allow: Boolean); begin try ItemChanging(item, _type, Allow); except Application.HandleException(Self); end; end; procedure TCustomViewControl.ItemCheckedHook(item: QListViewItemH; Checked: Boolean); begin try ItemChecked(item, Checked); except Application.HandleException(Self); end; end; procedure TCustomViewControl.ItemChecked(item: QListViewItemH; Checked: Boolean); begin { stubbed for children } end; procedure TCustomViewControl.ItemDestroyedHook(AItem: QListViewItemH); begin try ItemDestroyed(AItem); except Application.HandleException(Self); end; end; procedure TCustomViewControl.ItemDestroyed(AItem: QListViewItemH); begin { stubbed for children } end; procedure TCustomViewControl.ItemSelectedHook(item: QListViewItemH; wasSelected: Boolean); begin try ItemSelected(item, wasSelected); except Application.HandleException(Self); end; end; procedure TCustomViewControl.ItemChange(item: QListViewItemH; _type: TItemChange); begin { stubbed for children } end; procedure TCustomViewControl.ItemChanging(item: QListViewItemH; _type: TItemChange; var Allow: Boolean); begin { stubbed for children } end; procedure TCustomViewControl.ItemSelected(item: QListViewItemH; wasSelected: Boolean); begin { stubbed for children } end; procedure TCustomViewControl.DoGetImageIndex(item: TCustomViewItem); begin { stubbed for children } end; procedure TCustomViewControl.DoEditing(AItem: TCustomViewItem; var AllowEdit: Boolean); begin { stubbed for children } end; procedure TCustomViewControl.DoEdited(AItem: TCustomViewItem; var S: WideString); begin { stubbed for children } end; procedure TCustomViewControl.ItemExpandingHook(item: QListViewItemH; Expand: Boolean; var Allow: Boolean); begin try ItemExpanding(item, Expand, Allow); except Application.HandleException(Self); end; end; procedure TCustomViewControl.ItemExpanding(item: QListViewItemH; Expand: Boolean; var Allow: Boolean); begin { stubbed for children } end; procedure TCustomViewControl.ItemExpandedHook(item: QListViewItemH; Expand: Boolean); begin try ItemExpanded(item, Expand); except Application.HandleException(Self); end; end; procedure TCustomViewControl.ItemExpanded(item: QListViewItemH; Expand: Boolean); begin { stubbed for children } end; function TCustomViewControl.IsEditing: Boolean; begin Result := Assigned(FEditor) and FEditor.FEditing; end; procedure TCustomViewControl.StartEditTimer; begin if not ReadOnly then FTimer.Enabled := True; FAllowEdit := False; end; procedure TCustomViewControl.TimerIntervalElapsed(Sender: TObject); begin if Visible then begin FTimer.Enabled := False; FAllowEdit := True; end; end; procedure TCustomViewControl.CheckRemoveEditor; begin if not Assigned(FEditor) then Exit; FEditor.EditFinished(True); FEditor := nil; end; procedure TCustomViewControl.EditItem; begin CheckRemoveEditor; if not (csDesigning in ComponentState) and not ReadOnly then begin FEditor := CreateEditor; FEditor.Execute; end; end; function TCustomViewControl.FindDropTarget: TCustomViewItem; var Pt: TPoint; begin if HandleAllocated then begin QCursor_pos(@Pt); QWidget_mapFromGlobal(ViewportHandle, @Pt, @Pt); Result := TCustomViewItem(QClxObjectMap_find(QListView_itemAt(Handle, @Pt))); end else Result := nil; end; function TCustomViewControl.CreateEditor: TItemEditor; begin Result := TItemEditor.Create(Self); end; function TCustomViewControl.GetHandle: QListViewH; begin HandleNeeded; Result := QListViewH(FHandle); end; function TCustomViewControl.GetIndent: Integer; begin Result := FIndent; end; procedure TCustomViewControl.SetIndent(const Value: Integer); begin if FIndent <> Value then begin FIndent := Value; if FIndent < 0 then FIndent := 0; if HandleAllocated then begin QListView_setTreeStepSize(Handle, FIndent); UpdateControl; end; end; end; procedure TCustomViewControl.SetMultiSelect(const Value: Boolean); begin if MultiSelect <> Value then begin FMultiSelect := Value; if HandleAllocated then begin if FMultiSelect then QListView_selectAll(Handle, False); QListView_setSelectionMode(Handle, cSelMode[FMultiSelect]); end; end; end; function TCustomViewControl.GetMultiSelect: Boolean; begin Result := FMultiSelect; end; function TCustomViewControl.GetRowSelect: Boolean; begin Result := FRowSelect; end; procedure TCustomViewControl.SetRowSelect(const Value: Boolean); begin if RowSelect <> Value then begin FRowSelect := Value; if HandleAllocated then QListView_setAllColumnsShowFocus(Handle, FRowSelect); end; end; procedure TCustomViewControl.InvertSelection; begin if HandleAllocated then QListView_invertSelection(Handle); end; procedure TCustomViewControl.SetImageList(const Value: TCustomImageList); begin if FImageList <> Value then begin if Assigned(FImageList) then FImageList.UnRegisterChanges(FImageLink); FImageList := Value; if Assigned(FImageList) then FImageList.RegisterChanges(FImageLink); ImageListChanged; end; end; procedure TCustomViewControl.ImageListChange(Sender: TObject); begin ImageListChanged; end; procedure TCustomViewControl.ImageListChanged; begin { stubbed out for children } end; function TCustomViewControl.NeedKey(Key: Integer; Shift: TShiftState; const KeyText: WideString): Boolean; begin Result := inherited NeedKey(Key, Shift, KeyText) and (Shift * [ssShift, ssAlt, ssCtrl] = []); end; procedure TCustomViewControl.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (AComponent = FImageList) then begin if (Operation = opRemove) then FImageList := nil; ImageListChanged; end; end; procedure TCustomViewControl.SetOwnerDraw(const Value: Boolean); begin if Value <> FOwnerDraw then begin FOwnerDraw := Value; if HandleAllocated then QWidget_update(ViewportHandle); end; end; type TViewControlItemPaint_event = procedure(p: QPainterH; item: QListViewItemH; column, width, alignment: Integer; var stage: Integer) of object cdecl; TViewControlBranchPaint_event = procedure(p: QPainterH; item: QListViewItemH; w, y, h: Integer; style: GUIStyle; var stage: Integer) of object cdecl; TViewControlItemSelected_event = procedure (item: QListViewItemH; wasSelected: Boolean) of object cdecl; TViewControlItemChange_event = procedure (item: QListViewItemH; _type: TItemChange) of object cdecl; TViewControlItemChanging_event = procedure (item: QListViewItemH; _type: TItemChange; var Allow: Boolean) of object cdecl; TViewControlItemExpanding_event = procedure (item: QListViewItemH; Expanding: Boolean; var Allow: Boolean) of object cdecl; TViewControlItemExpanded_event = procedure (item: QListViewItemH; Expanding: Boolean) of object cdecl; TViewControlItemChecked_event = procedure (item: QListViewItemH; Checked: Boolean) of object cdecl; TViewControlItemDestroyed_event = procedure (item: QListViewItemH) of object cdecl; procedure TCustomViewControl.HookEvents; var Method: TMethod; begin inherited HookEvents; TViewControlItemPaint_event(Method) := ItemPaintHook; QClxListViewHooks_hook_PaintCell(FItemHooks, Method); TViewControlBranchPaint_event(Method) := BranchPaintHook; QClxListViewHooks_hook_paintBranches(FItemHooks, Method); TViewControlItemSelected_event(Method) := ItemSelectedHook; QClxListViewHooks_hook_setSelected(FItemHooks, Method); TViewControlItemChange_event(Method) := ItemChangeHook; QClxListViewHooks_hook_change(FItemHooks, Method); TViewControlItemChanging_event(Method) := ItemChangingHook; QClxListViewHooks_hook_changing(FItemHooks, Method); TViewControlItemExpanding_event(Method) := ItemExpandingHook; QClxListViewHooks_hook_expanding(FItemHooks, Method); TViewControlItemExpanded_event(Method) := ItemExpandedHook; QClxListViewHooks_hook_expanded(FItemHooks, Method); TViewControlItemChecked_event(Method) := ItemCheckedHook; QClxListViewHooks_hook_checked(FItemHooks, Method); TViewControlItemDestroyed_event(Method) := ItemDestroyedHook; QClxListViewHooks_hook_destroyed(FItemHooks, Method); TEventFilterMethod(Method) := MainEventFilter; FViewportHooks := QWidget_hook_create(FViewportHandle); Qt_hook_hook_events(FViewportHooks, Method); FHScrollHooks := QScrollBar_hook_create(FHScrollHandle); Qt_hook_hook_events(FHScrollHooks, Method); FVScrollHooks := QScrollBar_hook_create(FVScrollHandle); Qt_hook_hook_events(FVScrollHooks, Method); QObject_destroyed_event(Method) := ViewportDestroyed; QObject_hook_hook_destroyed(FViewportHooks, Method); end; function TCustomViewControl.IsCustomDrawn: Boolean; begin Result := IsOwnerDrawn or Assigned(FOnCustomDrawItem) or Assigned(FOnCustomDrawSubItem) or Assigned(FOnCustomDrawBranch); end; function TCustomViewControl.IsOwnerDrawn: Boolean; begin Result := False; end; function TCustomViewControl.DoCustomDrawViewItem(Item: TCustomViewItem; Canvas: TCanvas; const Rect: TRect; State: TCustomDrawState; Stage: TCustomDrawStage): Boolean; begin Result := True; if Assigned(FOnCustomDrawItem) then FOnCustomDrawItem(Self, Item, Canvas, Rect, State, Stage, Result); end; function TCustomViewControl.DoCustomDrawViewSubItem(Item: TCustomViewItem; SubItem: Integer; Canvas: TCanvas; const Rect: TRect; State: TCustomDrawState; Stage: TCustomDrawStage): Boolean; begin Result := True; if Assigned(FOnCustomDrawSubItem) then FOnCustomDrawSubItem(Self, Item, SubItem, Canvas, Rect, State, Stage, Result); end; procedure TCustomViewControl.DoDrawItem(Item: TCustomViewItem; Canvas: TCanvas; const Rect: TRect; State: TOwnerDrawState); begin { Implemented by descendants } end; procedure TCustomViewControl.BeginAutoDrag; begin BeginDrag(False, Mouse.DragThreshold); end; procedure TCustomViewControl.BranchPaintHook(p: QPainterH; item: QListViewItemH; w, y, h: Integer; style: GUIStyle; var stage: Integer); var Canvas: TCanvas; State: TCustomDrawState; ListItem: TCustomViewItem; R: TRect; begin if not IsCustomDrawn then begin stage := DrawStage_DefaultDraw; Exit; end; try State := []; ListItem := TCustomViewItem(FindObject(QObjectH(item))); if not Assigned(ListItem) then Exit; if ListItem.Selected then Include(State, cdsSelected); if not ListItem.Selectable then Include(State, cdsDisabled); R := Rect(0, 0, w - 1, h - 1); Canvas := TCanvas.Create; Canvas.Handle := p; Canvas.Start(False); if DoCustomDrawViewBranch(ListItem, Canvas, R, State, TCustomDrawStage(stage)) then stage := DrawStage_DefaultDraw; Canvas.Stop; Canvas.ReleaseHandle; Canvas.Free; except Application.HandleException(Self); end; end; procedure TCustomViewControl.ItemPaintHook(p: QPainterH; item: QListViewItemH; column, width, alignment: Integer; var stage: Integer); function CDSStateToODState(cds: TCustomDrawState): TOwnerDrawState; begin Result := []; if cdsSelected in cds then Include(Result, odSelected); if cdsGrayed in cds then Include(Result, odGrayed); if cdsDisabled in cds then Include(Result, odDisabled); if cdsChecked in cds then Include(Result, odChecked); if cdsFocused in cds then Include(Result, odFocused); if cdsDefault in cds then Include(Result, odDefault); end; var Canvas: TCanvas; State: TCustomDrawState; ListItem: TCustomViewItem; R: TRect; I: Integer; begin ListItem := TCustomViewItem(FindObject(QObjectH(item))); if not Assigned(ListItem) then Exit; DoGetImageIndex(ListItem); if not IsCustomDrawn then begin stage := DrawStage_DefaultDraw; Exit; end; try State := []; if ListItem.Selected then Include(State, cdsSelected); if not ListItem.Selectable then Include(State, cdsDisabled); Canvas := TCanvas.Create; Canvas.Handle := p; Canvas.Start(False); if cdsSelected in State then begin Canvas.Brush.Color := clHighlight; Canvas.Font.Color := clHighlightText; end else begin Canvas.Brush.Color := Color; Canvas.Font.Color := Font.Color; end; R := Rect(0, 0, width, ListItem.Height); if IsOwnerDrawn then begin for I := 1 to Columns.Count - 1 do Inc(R.Right, Columns[I].Width); DoDrawItem(ListItem, Canvas, R, CDSStateToODState(State)); end else begin if column = 0 then begin if DoCustomDrawViewItem(ListItem, Canvas, R, State, TCustomDrawStage(stage)) then stage := DrawStage_DefaultDraw; end else if column < Columns.Count then begin I := 0; while I < column do begin R.Left := R.Left + Columns[I].Width; Inc(I); end; R.Right := R.Left + Columns[I].Width; QPainter_translate(p, -R.Left, 0); try if DoCustomDrawViewSubItem(ListItem, column, Canvas, R, State, TCustomDrawStage(stage)) then stage := DrawStage_DefaultDraw; finally QPainter_translate(p, R.Left, 0); end; end; end; Canvas.Stop; Canvas.ReleaseHandle; Canvas.Free; except Application.HandleException(Self); end; end; function TCustomViewControl.GetColumnClick: Boolean; begin Result := FHeader.Clickable; end; function TCustomViewControl.GetColumnMove: Boolean; begin Result := FHeader.DragReorder; end; function TCustomViewControl.GetColumnResize: Boolean; begin Result := FHeader.Resizable; end; function TCustomViewControl.GetColumns: TListColumns; begin Result := TListViewHeader(FHeader).GetSections; end; procedure TCustomViewControl.SetColumnClick(const Value: Boolean); begin if ColumnClick <> Value then FHeader.Clickable := Value; end; procedure TCustomViewControl.SetShowColumnHeaders(const Value: Boolean); begin if FShowColumnHeaders <> Value then begin FShowColumnHeaders := Value; if HandleAllocated then TListViewHeader(FHeader).Hidden := not FShowColumnHeaders; end; end; procedure TCustomViewControl.SetColumnMove(const Value: Boolean); begin if ColumnMove <> Value then FHeader.DragReorder := Value; end; procedure TCustomViewControl.SetColumnResize(const Value: Boolean); begin if ColumnResize <> Value then FHeader.Resizable := Value; end; procedure TCustomViewControl.SetColumns(const Value: TListColumns); begin FHeader.SetSections(Value); end; procedure TCustomViewControl.SetShowColumnSortIndicators(const Value: Boolean); begin if FShowColumnSortIndicators <> Value then begin FShowColumnSortIndicators := Value; Sorted := FShowColumnSortIndicators; if ShowColumnHeaders and HandleAllocated then QListView_setShowSortIndicator(Handle, FShowColumnSortIndicators); end; end; procedure TCustomViewControl.RepopulateItems; begin { stubbed for children } end; procedure TCustomViewControl.UpdateControl; begin if HandleAllocated then begin QWidget_update(FHeader.Handle); QListView_triggerUpdate(Handle); end; end; function TCustomViewControl.DoCustomDrawViewBranch(Item: TCustomViewItem; Canvas: TCanvas; const Rect: TRect; State: TCustomDrawState; Stage: TCustomDrawStage): Boolean; begin Result := True; if Assigned(FOnCustomDrawBranch) then FOnCustomDrawBranch(Self, Item, Canvas, Rect, State, Stage, Result); end; procedure TCustomViewControl.ViewportDestroyed; begin try CheckRemoveEditor; except Application.HandleException(Self); end; end; function TCustomViewControl.ViewportHandle: QWidgetH; begin HandleNeeded; Result := FViewportHandle; end; function TCustomViewControl.GetChildHandle: QWidgetH; begin Result := ViewportHandle; end; procedure TCustomViewControl.WidgetDestroyed; begin CheckRemoveEditor; QClxObjectMap_remove(FViewportHandle); FViewportHandle := nil; if Assigned(FViewportHooks) then begin QWidget_hook_destroy(FViewportHooks); FViewportHooks := nil; end; QClxObjectMap_remove(FVScrollHandle); FVScrollHandle := nil; if Assigned(FVScrollHooks) then begin QScrollBar_hook_destroy(FVScrollHooks); FVScrollHooks := nil; end; QClxObjectMap_remove(FHScrollHandle); FHScrollHandle := nil; if Assigned(FHScrollHandle) then begin QScrollBar_hook_destroy(FHScrollHooks); FHScrollHooks := nil; end; inherited WidgetDestroyed; end; procedure TCustomViewControl.Sort(Column: Integer; Direction: TSortDirection); begin SortColumn := Column; SortDirection := Direction; Sorted := True; end; procedure TCustomViewControl.SetSorted(const Value: Boolean); begin FSorted := Value; if HandleAllocated then begin if FSorted then QListView_setSorting(Handle, SortColumn, cSortDirection[SortDirection]) else QListView_setSorting(Handle, -1, cSortDirection[SortDirection]); end; end; { TItemEditor } constructor TItemEditor.Create(AOwner: TComponent); begin inherited Create(nil); if AOwner is TCustomViewControl then FViewControl := TCustomViewControl(AOwner); InitItem; end; destructor TItemEditor.Destroy; begin if Assigned(FViewControl) then FViewControl.FEditor := nil; inherited Destroy; end; procedure TItemEditor.CreateWidget; begin FFrame := QFrame_create(FViewControl.ViewportHandle, nil, 0, True); FFrameHooks := QFrame_hook_Create(FFrame); QFrame_setFrameStyle(FFrame, Integer(QFrameShape_Box) or Integer(QFrameShadow_Plain)); QWidget_setBackgroundMode(FFrame, QWidgetBackgroundMode_PaletteBase); FHandle := QClxLineEdit_create(FFrame, nil); Hooks := QLineEdit_hook_create(Handle); end; procedure TItemEditor.FrameDestroyedHook; begin try FFrame := nil; QFrame_hook_destroy(FFrameHooks); FFrameHooks := nil; except Application.HandleException(Self); end; end; procedure TItemEditor.HookEvents; var Method: TMethod; begin inherited HookEvents; QObject_destroyed_event(Method) := FrameDestroyedHook; QObject_hook_hook_destroyed(FFrameHooks, Method); end; procedure TItemEditor.InitItem; var Obj: TObject; begin if FViewControl is TCustomViewControl then begin Obj := TObject(QClxObjectMap_find(QListView_currentItem(FViewControl.Handle))); if Obj is TCustomViewItem then FItem := TCustomViewItem(Obj); end; end; procedure TItemEditor.KeyDown(var Key: Word; Shift: TShiftState); begin FViewControl.KeyDown(Key, Shift); end; procedure TItemEditor.KeyUp(var Key: Word; Shift: TShiftState); begin FViewControl.KeyUp(Key, Shift); end; procedure TItemEditor.KeyPress(var Key: Char); begin FViewControl.KeyPress(Key); end; procedure TItemEditor.KeyString(var S: WideString; var Handled: Boolean); begin FViewControl.KeyString(S, Handled); end; function TItemEditor.PopupMenuFilter(Sender: QObjectH; Event: QEventH): Boolean; var FocusedWidget: QWidgetH; begin try case QEvent_type(Event) of QEventType_MouseButtonPress: begin FocusedWidget := QApplication_focusWidget(Application.Handle); if not ((FocusedWidget = Handle) or (FocusedWidget = FPopup)) then FShouldClose := True; end; QEventType_Destroy: ClearMenuHook; end; except Application.HandleException(Self); end; Result := False; end; procedure TItemEditor.ClearMenuHook; begin if Assigned(FMenuHook) then begin QPopupMenu_hook_destroy(FMenuHook); FPopup := nil; FMenuHook := nil; end; end; function TItemEditor.EventFilter(Sender: QObjectH; Event: QEventH): Boolean; var Obj: QObjectH; Method: TMethod; begin if FEditing then begin if FShouldClose then EditFinished(True); case QEvent_type(Event) of QEventType_ChildRemoved: begin Result := False; Obj := QChildEvent_child(QChildEventH(Event)); if FPopup = Obj then ClearMenuHook; Exit; end; QEventType_ChildInserted: begin Result := False; Obj := QChildEvent_child(QChildEventH(Event)); if QObject_isA(Obj, 'QPopupMenu') then begin FPopup := QPopupMenuH(Obj); FMenuHook := QPopupMenu_hook_create(Obj); TEventFilterMethod(Method) := PopupMenuFilter; Qt_hook_hook_events(FMenuHook, Method); end; Exit; end; QEventType_FocusOut: if QFocusEvent_reason <> QFocusEventReason_Popup then EditFinished(True); QEventType_KeyPress: begin case QKeyEvent_key(QKeyEventH(Event)) of Key_Up, Key_Down: begin Result := True; Exit; end; Key_Escape: EditFinished(False); Key_Return, Key_Enter: EditFinished(True); end; end; end; end; Result := inherited EventFilter(Sender, Event); end; procedure TItemEditor.Execute; var Pt: TPoint; Offset: Integer; ListItem: QListViewItemH; ListHandle: QListViewH; Allow: Boolean; Pixmap: QPixmapH; PixmapWidth: Integer; begin if not Assigned(FItem) then EditFinished(False); FEditing := True; Allow := True; FViewControl.DoEditing(FItem, Allow); if not Allow then begin EditFinished(False); Exit; end; HandleNeeded; ListHandle := FViewControl.Handle; ListItem := FItem.Handle; Pt := FItem.DisplayRect.BottomRight; if (Pt.X = -1) and (Pt.Y = -1) then FItem.MakeVisible(False); Offset := 0; PixmapWidth := 0; Pixmap := QListViewItem_pixmap(ListItem, 0); if Assigned(Pixmap) then PixmapWidth := QPixmap_width(Pixmap); while Assigned(ListItem) do begin ListItem := QListViewItem_parent(ListItem); Inc(Offset); end; Pt.X := Offset * QListView_treeStepSize(ListHandle); if not QListView_rootIsDecorated(ListHandle) then Dec(Pt.X, QListView_treeStepSize(ListHandle)); Inc(Pt.X, PixmapWidth); Pt.Y := QListViewItem_itemPos(FItem.Handle); QScrollView_contentsToViewport(ListHandle, @Pt, @Pt); Left := QFrame_frameWidth(FFrame); Top := QFrame_frameWidth(FFrame); Width := QListView_columnWidth(ListHandle, 0); QWidget_setGeometry(FFrame, Pt.X, Pt.Y, (QListView_columnWidth(ListHandle, 0) - Pt.X), QListViewItem_height(FItem.Handle)); Width := (QListView_columnWidth(ListHandle, 0) - Pt.X) - (QFrame_frameWidth(FFrame) * 2); BorderStyle := bsNone; Text := FItem.Caption; SelectAll; QWidget_show(FFrame); QWidget_setFixedHeight(Handle, QListViewItem_height(FItem.Handle) - (QFrame_frameWidth(FFrame) * 2)); QWidget_show(Handle); SetFocus; end; procedure TItemEditor.EditFinished(Accepted: Boolean); var S: WideString; begin if Assigned(FFrame) and Visible then begin if FEditing then begin FEditing := False; ClearMenuHook; if Assigned(FViewControl) and not (csDestroying in FViewControl.ComponentState) then if Accepted and (Text <> FItem.Caption) then begin S := Text; FViewControl.DoEdited(FItem, S); FItem.Caption := S; end; Visible := False; if Assigned(FFrame) then QApplication_postEvent(Application.Handle, QCustomEvent_create(QEventType_CMDestroyWidget, FFrame)); if Assigned(FViewControl) and not (csDestroying in FViewControl.ComponentState) then FViewControl.SetFocus; end; end; end; { TCustomViewItem } constructor TCustomViewItem.Create(AOwner: TCustomViewItems; AParent, After: TCustomViewItem); begin inherited Create; FOwner := AOwner; FParent := AParent; FPrevItem := After; if Assigned(FPrevItem) then FPrevItem.FNextItem := Self; FImageIndex := -1; FSelectable := True; FExpandable := False; if Assigned(Owner) then begin DetermineCreationType; CreateWidget(AParent, After); end; end; destructor TCustomViewItem.Destroy; var Child: TCustomViewItem; begin FDestroying := True; if ViewControlValid and not (csDestroying in Owner.Owner.ComponentState) then begin Owner.BeginUpdate; try if HandleAllocated then while QListViewItem_childCount(Handle) > 0 do begin Child := Owner.FindViewItem(QListViewItem_firstChild(Handle)); if Child is TCustomViewItem then Child.Free; end; if not Assigned(Parent) or (Assigned(Parent) and not Parent.FDestroying) then begin if Selected then begin Selected := False; if Assigned(FNextItem) then FNextItem.Selected := True else if Assigned(FPrevItem) then FPrevItem.Selected := True else if Assigned(Parent) then Parent.Selected := True; end; end; finally Owner.EndUpdate; end; end; Parent := nil; if Assigned(FNextItem) then FNextItem.FPrevItem := FPrevItem; if Assigned(FPrevItem) then FPrevItem.FNextItem := FNextItem; if Assigned(Owner) then Owner.FItems.Extract(Self); if Assigned(FSubItems) then FSubItems.Free; if HandleAllocated then DestroyWidget; inherited Destroy; end; procedure TCustomViewItem.AssignTo(Dest: TPersistent); begin if Dest is TCustomViewItem then begin TCustomViewItem(Dest).Selected := Selected; TCustomViewItem(Dest).Selectable := Selectable; TCustomViewItem(Dest).Expanded := Expanded; TCustomViewItem(Dest).Expandable := Expandable; TCustomViewItem(Dest).Caption := Caption; TCustomViewItem(Dest).Checked := Checked; TCustomViewItem(Dest).Data := Data; TCustomViewItem(Dest).Focused := Focused; TCustomViewItem(Dest).ImageIndex := ImageIndex; TCustomViewItem(Dest).ItemType := ItemType; TCustomViewItem(Dest).SubItems.Assign(SubItems); end else inherited AssignTo(Dest); end; procedure TCustomViewItem.Collapse; begin Expanded := False; end; procedure TCustomViewItem.CreateWidget(AParent, After: TCustomViewItem); const cType: array [TListViewItemType] of QCheckListItemType = (QCheckListItemtype_CheckBox, QCheckListItemtype_CheckBox, QCheckListItemtype_RadioButton, QCheckListItemtype_Controller); var ParentH: QListViewItemH; AfterH: QListViewItemH; ParentListViewH: QListViewH; begin ParentH := nil; AfterH := nil; ParentListViewH := nil; FHandle := nil; if Assigned(AParent) then ParentH := AParent.Handle else if ViewControlValid then ParentListViewH := ViewControl.Handle else ParentListViewH := nil; if Assigned(After) then AfterH := After.Handle; case FItemType of itDefault: begin if Assigned(ParentListViewH) then FHandle := QClxListViewItem_create(ParentListViewH, AfterH, ItemHook) else FHandle := QClxListViewItem_create(ParentH, AfterH, ItemHook); end; else begin if Assigned(ParentListViewH) then FHandle := QClxCheckListItem_create(ParentListViewH, PWideString(@FText), cType[FItemType], ItemHook) else FHandle := QClxCheckListItem_create(ParentH, PWideString(@FText), cType[FItemType], ItemHook); if Assigned(AfterH) then QListViewItem_moveItem(FHandle, AfterH); end; end; QClxObjectMap_add(FHandle, Integer(Self)); end; procedure TCustomViewItem.Delete; begin Free; end; procedure TCustomViewItem.DestroyWidget; begin if HandleAllocated then begin Selected := False; if Assigned(FNextItem) then FNextItem.Selected := True else if Assigned(FPrevItem) then FPrevItem.Selected := True else if Assigned(Parent) then Parent.Selected := True; QClxObjectMap_remove(FHandle); if Assigned(Owner) and ViewControlValid then QListViewItem_destroy(FHandle); end; FHandle := nil; end; procedure TCustomViewItem.DetermineCreationType; begin if Assigned(Owner) and (Owner.Owner is TCustomListView) then if TCustomListView(Owner.Owner).CheckBoxes then FItemType := itCheckBox; end; procedure TCustomViewItem.Expand; begin Expanded := True; end; function TCustomViewItem.GetChildCount: Integer; begin if ViewControlValid and HandleAllocated then Result := QListViewItem_childCount(Handle) else Result := -1; end; function TCustomViewItem.GetFocused: Boolean; begin if ViewControlValid and HandleAllocated then Result := QListView_currentItem(Owner.Owner.Handle) = Handle else Result := False; end; function TCustomViewItem.GetHeight: Integer; begin if ViewControlValid and HandleAllocated then Result := QListViewItem_height(Handle) else Result := -1; end; function TCustomViewItem.GetSubItemImages(Column: Integer): Integer; begin if (Column >= 0) and (Column < SubItems.Count) then Result := Integer(SubItems.Objects[Column]) else Result := -1; end; function TCustomViewItem.GetExpanded: Boolean; begin if HandleAllocated then Result := QListViewItem_isOpen(Handle) else Result := False; end; function TCustomViewItem.GetHandle: QListViewItemH; begin if not HandleAllocated and not FDestroying then CreateWidget(FParent, FPrevItem); Result := FHandle; end; function TCustomViewItem.GetSubItems: TStrings; begin if not Assigned(FSubItems) then FSubItems := TSubItems.Create(Self); Result := FSubItems; end; function TCustomViewItem.GetTotalHeight: Integer; begin if ViewControlValid and HandleAllocated then Result := QListViewItem_totalHeight(Handle) else Result := -1; end; function TCustomViewItem.GetIndex: Integer; begin if Assigned(Owner) then Result := Owner.FItems.IndexOf(Self) else Result := -1; end; function TCustomViewItem.GetSelected: Boolean; begin if HandleAllocated then Result := QListViewItem_isSelected(Handle) else Result := False; end; function TCustomViewItem.HandleAllocated: Boolean; begin Result := FHandle <> nil; end; procedure TCustomViewItem.ImageIndexChange(ColIndex, NewIndex: Integer); var Pixmap: QPixmapH; begin if ViewControlValid and HandleAllocated and Assigned(ViewControl.Images) then begin Pixmap := ViewControl.Images.GetPixmap(NewIndex); if Assigned(Pixmap) then QListViewItem_setPixmap(Handle, ColIndex, Pixmap) else begin Pixmap := QPixmap_create; try QListViewItem_setPixmap(Handle, ColIndex, Pixmap); finally QPixmap_destroy(Pixmap); end; end; end; end; procedure TCustomViewItem.InsertItem(AItem: TCustomViewItem); begin if Assigned(AItem) then begin AItem.FParent := Self; AItem.FPrevItem := FLastChild; AItem.FNextItem := nil; if HandleAllocated and AItem.HandleAllocated then QListViewItem_insertItem(Handle, AItem.Handle); if Assigned(FLastChild) then begin FLastChild.FNextItem := AItem; if HandleAllocated then QListViewItem_moveItem(AItem.Handle, FLastChild.Handle); end; FLastChild := AItem; end; end; function TCustomViewItem.ParentCount: Integer; var Temp: QListViewItemH; begin Result := 0; if ViewControlValid and HandleAllocated then begin Temp := QListViewItem_parent(Handle); while Assigned(Temp) do begin Inc(Result); Temp := QListViewItem_parent(Temp); end; end; end; procedure TCustomViewItem.ReCreateItem; begin FDestroying := True; try DestroyWidget; CreateWidget(FParent, FPrevItem); ResetFields; finally FDestroying := False; end; end; procedure TCustomViewItem.RemoveItem(AItem: TCustomViewItem); begin if Assigned(AItem) then begin if FLastChild = AItem then FLastChild := AItem.FPrevItem; if HandleAllocated then begin if AItem.HandleAllocated then QListViewItem_takeItem(Handle, AItem.Handle); if HandleAllocated and (QListViewItem_childCount(Handle) = 0) then Expandable := False; end; AItem.FParent := nil; end; end; procedure TCustomViewItem.Repaint; begin if HandleAllocated then QListViewItem_repaint(Handle); end; procedure TCustomViewItem.ResetFields; var I: Integer; Temp: WideString; begin if HandleAllocated then begin if ViewControlValid then begin QListViewItem_setText(Handle, 0, PWideString(@FText)); if ItemType <> itDefault then QCheckListItem_setOn(QCheckListItemH(FHandle), FChecked); QListViewItem_setExpandable(Handle, FExpandable); QListViewItem_setSelectable(Handle, FSelectable); end; if Assigned(FSubItems) then for I := 0 to SubItems.Count-1 do begin Temp := SubItems[I]; QListViewItem_setText(Handle, I + 1, PWideString(@Temp)); ImageIndexChange(I + 1, SubItemImages[I]); end; end; end; procedure TCustomViewItem.SetCaption(const Value: WideString); begin if Caption <> Value then begin if HandleAllocated then begin if Assigned(Owner) then QListViewItem_setText(Handle, 0, PWideString(@Value)); QListViewItem_text(Handle, PWideString(@FText), 0); end else FText := Value; end; end; procedure TCustomViewItem.SetChecked(const Value: Boolean); begin if Checked <> Value then begin if ViewControlValid and HandleAllocated and (ItemType <> itDefault) then QCheckListItem_setOn(QCheckListItemH(Handle), Value); FChecked := Value; end; end; procedure TCustomViewItem.SetSubItemImages(Column: Integer; const Value: Integer); begin if (Column >= 0) and (Column < SubItems.Count) then SubItems.Objects[Column] := Pointer(Value); end; procedure TCustomViewItem.SetExpandable(const Value: Boolean); begin if Expandable <> Value then begin FExpandable := Value; if ViewControlValid and HandleAllocated then QListViewItem_setExpandable(Handle, FExpandable); end; end; procedure TCustomViewItem.SetExpanded(const Value: Boolean); var AItem: QListViewItemH; ARect: TRect; begin if (Expanded <> Value) and HandleAllocated then begin QListViewItem_setOpen(Handle, Value); if not Expanded and ViewControlValid then begin AItem := QListView_currentItem(ViewControl.Handle); while Assigned(AItem) do begin if (AItem = Handle) then Break; AItem := QListViewItem_parent(AItem); end; if Assigned(AItem) then begin repeat QListView_itemRect(ViewControl.Handle, @ARect, AItem); if QListViewItem_isOpen(AItem) or ((ARect.Right >= 0) and (ARect.Bottom >= 0)) then begin QListView_setCurrentItem(ViewControl.Handle, AItem); Exit; end; AItem := QListViewItem_parent(AItem); until not Assigned(AItem); end; end; end; end; procedure TCustomViewItem.SetFocused(const Value: Boolean); begin if ViewControlValid and HandleAllocated and (Value <> GetFocused) then QListView_setCurrentItem(ViewControl.Handle, Handle); end; procedure TCustomViewItem.SetImageIndex(const Value: TImageIndex); begin if FImageIndex <> Value then begin FImageIndex := Value; ImageIndexChange(0, FImageIndex); end; end; procedure TCustomViewItem.SetItemType(const Value: TListViewItemType); var ChildrenArray: array of QListViewItemH; Temp: QListViewItemH; I: Integer; begin if FItemType <> Value then begin if (Value = itRadioButton) then if (not Assigned(FParent)) or (FParent.ItemType <> itController) then raise EListViewException.Create(sListRadioItemBadParent); if HandleAllocated then begin if ViewControlValid then begin SetLength(ChildrenArray, QListViewItem_childCount(Handle)); if Length(ChildrenArray) > 0 then begin I := 0; while True do begin Temp := QListViewItem_firstChild(Handle); if not Assigned(Temp) then Break; QListViewItem_takeItem(Handle, Temp); ChildrenArray[I] := Temp; Inc(I); end; end; end; FItemType := Value; ReCreateItem; if ViewControlValid and (Length(ChildrenArray) > 0) then begin I := 0; while (I < Length(ChildrenArray)) and (Assigned(ChildrenArray[I])) do begin QListViewItem_insertItem(Handle, ChildrenArray[I]); Inc(I); end; end; end; end; end; procedure TCustomViewItem.SetParent(const Value: TCustomViewItem); begin if Assigned(FPrevItem) then FPrevItem.FNextItem := FNextItem; if Assigned(FNextItem) then FNextItem.FPrevItem := FPrevItem; if Assigned(FParent) then FParent.RemoveItem(Self); FPrevItem := nil; FNextItem := nil; FParent := Value; if Assigned(FParent) then FParent.InsertItem(Self); end; procedure TCustomViewItem.SetSelectable(const Value: Boolean); begin if Selectable <> Value then begin FSelectable := Value; if ViewControlValid and HandleAllocated then QListViewItem_setSelectable(Handle, FSelectable); end; end; procedure TCustomViewItem.SetSelected(const Value: Boolean); begin if (Selected <> Value) and HandleAllocated then begin if ViewControlValid then QListView_setSelected(ViewControl.Handle, Handle, Value) else QListViewItem_setSelected(Handle, Value); if Value and ViewControlValid and ViewControl.Visible then MakeVisible(False); end; end; function TCustomViewItem.ViewControl: TCustomViewControl; begin Result := nil; if ViewControlValid then Result := Owner.Owner; end; function TCustomViewItem.ViewControlValid: Boolean; begin Result := Assigned(FOwner) and Assigned(FOwner.FOwner) and not (csRecreating in FOwner.FOwner.ControlState); end; function TCustomViewItem.ItemHook: QClxListViewHooksH; begin Result := nil; if ViewControlValid then Result := ViewControl.FItemHooks; end; function TCustomViewItem.DisplayRect: TRect; begin if ViewControlValid and HandleAllocated then QListView_itemRect(ViewControl.Handle, @Result, Handle) else Result := Rect(0, 0, -1, -1); end; function TCustomViewItem.GetWidth: Integer; var R: TRect; begin R := DisplayRect; Result := R.Right - R.Left; end; procedure TCustomViewItem.SetSubItems(const Value: TStrings); begin if SubItems <> Value then SubItems.Assign(Value); end; procedure TCustomViewItem.UpdateImages; var I: Integer; ImgList: TCustomImageList; EmptyPix: QPixmapH; Pixmap: QPixmapH; begin if HandleAllocated then begin ImgList := ViewControl.Images; EmptyPix := QPixmap_create; try if Assigned(ImgList) then begin Pixmap := ImgList.GetPixmap(ImageIndex); if not Assigned(Pixmap) then Pixmap := EmptyPix; QListViewItem_setPixmap(Handle, 0, Pixmap); for I := 0 to SubItems.Count-1 do begin Pixmap := ImgList.GetPixmap(SubItemImages[I]); if not Assigned(Pixmap) then Pixmap := EmptyPix; QListViewItem_setPixmap(Handle, I+1, Pixmap); end; end else begin QListViewItem_setPixmap(Handle, 0, EmptyPix); for I := 0 to SubItems.Count-1 do QListViewItem_setPixmap(Handle, I+1, EmptyPix); end; finally if Assigned(EmptyPix) then QPixmap_destroy(EmptyPix); end; end; end; procedure TCustomViewItem.MakeVisible(PartialOK: Boolean); var ARect: TRect; begin if ViewControlValid and HandleAllocated then begin if PartialOK then begin ARect := DisplayRect; if (ARect.Left <> -1) and (ARect.Top <> -1) and (ARect.Right <> -1) and (ARect.Bottom <> -1) then Exit; end; QListView_ensureItemVisible(ViewControl.Handle, Handle); end; end; { TCustomViewItems } procedure TCustomViewItems.Clear; begin BeginUpdate; try FItems.Clear; if Owner.HandleAllocated then QListView_clear(Owner.Handle); finally EndUpdate; end; end; constructor TCustomViewItems.Create(AOwner: TCustomViewControl); begin inherited Create; FOwner := AOwner; FItems := TViewItemsList.Create; end; destructor TCustomViewItems.Destroy; begin try BeginUpdate; FItems.Free; finally EndUpdate; end; inherited Destroy; end; function TCustomViewItems.GetHandle: QListViewH; begin if Owner <> nil then Result := Owner.Handle else Result := nil; end; function TCustomViewItems.GetItem(Index: Integer): TCustomViewItem; begin Result := FItems[Index]; end; procedure TCustomViewItems.ChangeItemTypes(NewType: TListViewItemType); var I: Integer; begin BeginUpdate; try for I := 0 to Count-1 do Item[I].ItemType := NewType; finally EndUpdate; end; end; function TCustomViewItems.IndexOf(Value: TCustomViewItem): Integer; begin Result := FItems.IndexOf(Value); end; procedure TCustomViewItems.SetItem(Index: Integer; const Value: TCustomViewItem); begin if (Index < Count-1) and (Index >= 0) then if Assigned(FItems[Index]) then FItems[Index].Assign(Value) else FItems[Index] := Value; end; function TCustomViewItems.GetCount: Integer; begin Result := FItems.Count; end; procedure TCustomViewItems.BeginUpdate; begin if FUpdateCount = 0 then SetUpdateState(True); Inc(FUpdateCount); end; procedure TCustomViewItems.EndUpdate; begin Dec(FUpdateCount); if FUpdateCount = 0 then SetUpdateState(False); end; procedure TCustomViewItems.SetUpdateState(Updating: Boolean); begin if not (csDestroying in Owner.ComponentState) and Owner.HandleAllocated then begin if FUpdateCount = 0 then begin QWidget_setUpdatesEnabled(Owner.Handle, not Updating); QWidget_setUpdatesEnabled(QScrollView_viewport(Owner.Handle), not Updating); if not Updating then QListView_triggerUpdate(Owner.Handle); end; end; end; { TCustomListView } function TCustomListView.IsOwnerDrawn: Boolean; begin Result := FOwnerDraw and (ViewStyle = vsReport) and Assigned(FOnDrawItem); end; procedure TCustomListView.ItemChange(item: QListViewItemH; _type: TItemChange); begin if Assigned(FOnChange) then FOnChange(Self, FItems.FindItem(item), _type); end; procedure TCustomListView.ItemChanging(item: QListViewItemH; _type: TItemChange; var Allow: Boolean); var AItem: TListItem; begin AItem := FItems.FindItem(item); if Assigned(AItem) and not AItem.FDestroying then begin if Assigned(FOnChanging) then FOnChanging(Self, AItem, _type, Allow); if (AItem <> FSelected) and (_type = ctState) then StartEditTimer; end; end; procedure TCustomListView.ItemChecked(item: QListViewItemH; Checked: Boolean); var AItem: TListItem; begin AItem := Items.FindItem(item); if Assigned(AItem) then AItem.FChecked := Checked; StartEditTimer; end; procedure TCustomListView.ItemDestroyed(AItem: QListViewItemH); var ListItem: TListItem; begin if QClxObjectMap_find(AItem) <> 0 then ListItem := FItems.FindItem(AItem) else ListItem := nil; if Assigned(ListItem) then begin QClxObjectMap_remove(ListItem.FHandle); ListItem.FHandle := nil; if not (csDestroying in ComponentState) and (FHeader is TListViewHeader) then if (not TListViewHeader(FHeader).FHiddenChanging) and not ListItem.FDestroying then ListItem.Free; end; end; procedure TCustomListView.ItemSelected(item: QListViewItemH; wasSelected: Boolean); const cIncSelCount: array [Boolean] of Integer = (-1, 1); var AItem: TListItem; begin Inc(FSelCount, cIncSelCount[wasSelected]); AItem := FItems.FindItem(item); if FSelCount > 0 then FSelected := AItem else FSelected := nil; if Assigned(FOnSelectItem) then FOnSelectItem(Self, AItem, wasSelected); end; function TCustomListView.AlphaSort: Boolean; begin Result := True; try { The 0th column is the one associated with the TListItem } if HandleAllocated then QListView_setSorting(Handle, 0, SortDirection = sdAscending); except Result := False; end; end; procedure TCustomListView.SetTopItem(const AItem: TListItem); var NewTopH: Integer; begin if Assigned(AItem) and HandleAllocated then begin NewTopH := QListView_itemPos(Handle, AItem.Handle); QListView_setContentsPos(Handle, QScrollView_contentsX(Handle), NewTopH); end; end; function TCustomListView.GetTopItem: TListItem; begin Result := GetItemAt(1, 1); end; function TCustomListView.GetDropTarget: TListItem; var Temp: TCustomViewItem; begin Result := nil; Temp := FindDropTarget; if Temp is TListItem then Result := TListItem(Temp); end; function TCustomListView.FindData(StartIndex: Integer; Value: Pointer; Inclusive, Wrap: Boolean): TListItem; var I: Integer; Item: TListItem; begin Result := nil; if Inclusive then Dec(StartIndex); for I := StartIndex + 1 to Items.Count - 1 do begin Item := Items[I]; if (Item <> nil) and (Item.Data = Value) then begin Result := Item; Exit; end; end; if Wrap then begin if Inclusive then Inc(StartIndex); for I := 0 to StartIndex - 1 do begin Item := Items[I]; if (Item <> nil) and (Item.Data = Value) then begin Result := Item; Exit; end; end; end; end; function TCustomListView.GetItemAt(X, Y: Integer): TListItem; var Temp: QListViewItemH; Pt: TPoint; begin Result := nil; if HandleAllocated then begin Pt := Types.Point(X, Y); Temp := QListView_itemAt(Handle, @Pt); Result := Items.FindItem(Temp); end; end; function TCustomListView.GetSelected: TListItem; begin Result := FSelected; end; procedure TCustomListView.SetSelected(const Value: TListItem); begin if not (csDestroying in ComponentState) then begin if Assigned(FSelected) and not MultiSelect then FSelected.Selected := False; if Assigned(Value) then Value.Selected := True; end; FSelected := Value; end; procedure TCustomListView.HookEvents; var Method: TMethod; begin inherited HookEvents; QListView_mouseButtonClicked_Event(Method) := DoItemClick; QListView_hook_hook_mouseButtonClicked(QListView_hookH(Hooks), Method); end; procedure TCustomListView.ImageListChanged; var I: Integer; begin for I := 0 to Items.Count-1 do Items[I].UpdateImages; end; function TCustomListView.FindCaption(StartIndex: Integer; const Value: WideString; Partial, Inclusive, Wrap: Boolean): TListItem; const cInclusive: array [Boolean] of Integer = (1, 0); var I: Integer; begin Result := nil; if (StartIndex < 0) or (StartIndex >= Items.Count) then Exit; if not Partial then begin for I := StartIndex + cInclusive[Inclusive] to Items.Count-1 do begin Result := Items[I]; if WideCompareText(Value, Result.Caption) = 0 then Exit; end; if Wrap then for I := 0 to StartIndex - cInclusive[not Inclusive] do begin Result := Items[I]; if WideCompareText(Value, Result.Caption) = 0 then Exit; end; Result := nil; end else begin for I := StartIndex + cInclusive[Inclusive] to Items.Count-1 do begin Result := Items[I]; if Pos(Value, Result.Caption) = 1 then Exit; end; if Wrap then for I := 0 to StartIndex - cInclusive[not Inclusive] do begin Result := Items[I]; if Pos(Value, Result.Caption) = 1 then Exit; end; Result := nil; end; end; procedure TCustomListView.Scroll(DX, DY: Integer); begin if HandleAllocated then QScrollView_scrollBy(Handle, DX, DY); end; function TCustomListView.GetItemFocused: TListItem; begin if HandleAllocated then Result := TListItem(QClxObjectMap_find(QListView_currentItem(Handle))) else Result := nil; end; procedure TCustomListView.SetItemFocused(const Value: TListItem); begin if Assigned(Value) and HandleAllocated then QListView_setCurrentItem(Handle, Value.Handle); end; procedure TCustomListView.InitWidget; begin inherited InitWidget; ShowColumnHeaders := FViewStyle = vsReport; QListView_setRootIsDecorated(Handle, False); end; procedure TCustomListView.SetCheckBoxes(const Value: Boolean); begin if FCheckBoxes <> Value then begin FCheckBoxes := Value; UpdateItemTypes; end; end; procedure TCustomListView.UpdateItemTypes; const cNewType: array [Boolean] of TListViewItemType = (itDefault, itCheckBox); begin FItems.ChangeItemTypes(cNewType[FCheckBoxes]); end; procedure TCustomListView.UpdateItems(FirstIndex, LastIndex: Integer); var I: Integer; begin for I := FirstIndex to LastIndex do Items[I].Repaint; end; constructor TCustomListView.Create(AOwner: TComponent); begin inherited Create(AOwner); Init(TListItem); end; constructor TCustomListView.Create(AOwner: TComponent; AListItemClass: TListItemClass); begin inherited Create(AOwner); Init(AListItemClass); end; destructor TCustomListView.Destroy; begin if Assigned(FMemStream) then FreeAndNil(FMemStream); FItems.Free; inherited Destroy; end; procedure TCustomListView.Init(AListItemClass: TListItemClass); begin FItems := TListItems.Create(Self, AListItemClass); FViewStyle := vsList; ColumnClick := True; ColumnMove := True; ColumnResize := True; Palette.ColorRole := crBase; Palette.TextColorRole := crText; end; procedure TCustomListView.DoGetImageIndex(item: TCustomViewItem); begin if Assigned(FOnGetImageIndex) and (item is TListItem) then FonGetImageIndex(Self, TListItem(item)); end; procedure TCustomListView.DoDrawItem(Item: TCustomViewItem; Canvas: TCanvas; const Rect: TRect; State: TOwnerDrawState); begin if Assigned(FOnDrawItem) then FOnDrawItem(Self, TListItem(Item), Canvas, Rect, State); end; procedure TCustomListView.DoEditing(AItem: TCustomViewItem; var AllowEdit: Boolean); begin if Assigned(FOnEditing) and (AItem is TListItem) then FOnEditing(Self, TListItem(AItem), AllowEdit); end; procedure TCustomListView.DoEdited(AItem: TCustomViewItem; var S: WideString); begin if Assigned(FOnEdited) and (AItem is TListItem) then FOnEdited(Self, TListItem(AItem), S); end; procedure TCustomListView.SetItems(const Value: TListItems); begin if FItems <> Value then FItems.Assign(Value); end; function TCustomListView.GetNearestItem(const Point: TPoint; Direction: TSearchDirection): TListItem; var Temp: TListItem; begin Result := nil; Temp := GetItemAt(Point.x, Point.y); if Assigned(Temp) and Temp.HandleAllocated then begin case Direction of sdAbove: Result := Items.FindItem(QListViewItem_itemAbove(Temp.Handle)); sdBelow: Result := Items.FindItem(QListViewItem_itemBelow(Temp.Handle)); end; end; end; function TCustomListView.GetNextItem(StartItem: TListItem; Direction: TSearchDirection; States: TItemStates): TListItem; var AIndex: Integer; begin Result := nil; if Assigned(StartItem) and StartItem.HandleAllocated and HandleAllocated then begin AIndex := StartItem.Index; while True do begin case Direction of sdAbove: Result := Items.FindItem(QListViewItem_itemAbove(StartItem.Handle)); sdBelow: Result := Items.FindItem(QListViewItem_itemBelow(StartItem.Handle)); sdAll: begin Inc(AIndex); if AIndex = StartItem.Index then begin Result := nil; Exit; end; if AIndex >= Items.Count then AIndex := 0; Result := Items[AIndex]; end; end; if Result = nil then Exit; if (Result.States * States <> []) then Exit; StartItem := Result; end; end; end; procedure TCustomListView.DoItemClick(Button: Integer; ListItem: QListViewItemH; Pt: PPoint; ColIndex: Integer); var AItem: TListItem; begin try AItem := FItems.FindItem(ListItem); if Assigned(AItem) then begin if Assigned(FOnItemClick) then FOnItemClick(Self, ButtonToMouseButton(Button), AItem, Pt^, ColIndex); if (ColIndex = 0) and FAllowEdit then EditItem; end; except Application.HandleException(Self); end; end; procedure TCustomListView.SetOnItemDoubleClick(const Value: TLVItemDoubleClickEvent); var Method: TMethod; begin FOnItemDoubleClick := Value; if Assigned(FOnItemDoubleClick) then QListView_doubleClicked_Event(Method) := DoItemDoubleClick else Method := NullHook; QListView_hook_hook_doubleClicked(QListView_hookH(Hooks), Method); end; procedure TCustomListView.DoItemDoubleClick(ListItem: QListViewItemH); var AItem: TListItem; begin if Assigned(FOnItemDoubleClick) then try AItem := FItems.FindItem(ListItem); FOnItemDoubleClick(Self, AItem); except Application.HandleException(Self); end; end; procedure TCustomListView.SetOnItemEnter(const Value: TLVNotifyEvent); var Method: TMethod; begin FOnItemEnter := Value; if Assigned(FOnItemEnter) then QListView_onItem_Event(Method) := DoOnItemEnter else Method := NullHook; QListView_hook_hook_onItem(QListView_hookH(Hooks), Method); end; procedure TCustomListView.SetOnItemExitViewportEnter(const Value: TLVItemExitViewportEnterEvent); var Method: TMethod; begin FOnItemExitViewportEnter := Value; if Assigned(FOnItemExitViewportEnter) then QListView_onViewport_Event(Method) := DoOnItemExitViewportEnter else Method := NullHook; QListView_hook_hook_onViewport(QListView_hookH(Hooks), Method); end; procedure TCustomListView.DoOnItemEnter(ListItem: QListViewItemH); var AItem: TListItem; begin if Assigned(FOnItemEnter) then try AItem := FItems.FindItem(ListItem); FOnItemEnter(Self, AItem); except Application.HandleException(Self); end; end; procedure TCustomListView.DoOnItemExitViewportEnter; begin if Assigned(FOnItemExitViewportEnter) then try FOnItemExitViewportEnter(Self); except Application.HandleException(Self); end; end; procedure TCustomListView.SetOnMouseDown(const Value: TLVButtonDownEvent); begin FOnMouseDown := Value; HookMouseDowns; end; procedure TCustomListView.DoLVMouseDown(Button: Integer; ListItem: QListViewItemH; Pt: PPoint; ColIndex: Integer); var AItem: TListItem; begin try AItem := FItems.FindItem(ListItem); if Assigned(FOnMouseDown) and Assigned(AItem) then FOnMouseDown(Self, ButtonToMouseButton(Button), AItem, Pt^, ColIndex) else if Assigned(FOnViewportMouseDown) and not Assigned(AItem) then FOnViewportMouseDown(Self, ButtonToMouseButton(Button), Pt^); except Application.HandleException(Self); end; end; procedure TCustomListView.SetOnViewportButtonDown(const Value: TLVViewportButtonDownEvent); begin FOnViewportMouseDown := Value; HookMouseDowns; end; procedure TCustomListView.HookMouseDowns; var Method: TMethod; begin if Assigned(FOnMouseDown) or Assigned(FOnViewportMouseDown) then begin if FDownsHooked then Exit; QListView_mouseButtonPressed_Event(Method) := DoLVMouseDown; FDownsHooked := True; end else begin Method := NullHook; FDownsHooked := False; end; QListView_hook_hook_mouseButtonPressed(QListView_hookH(Hooks), Method); end; procedure TCustomListView.SetViewStyle(const Value: TViewStyle); begin if FViewStyle <> Value then begin FViewStyle := Value; ShowColumnHeaders := FViewStyle = vsReport; end; end; procedure TCustomListView.RepopulateItems; var I: Integer; begin if HandleAllocated then begin if (QListView_childCount(Handle) = 0) and (QListView_columns(Handle) > 0) then begin Items.BeginUpdate; try for I := 0 to Items.Count-1 do Items[I].ReCreateItem; finally Items.EndUpdate; end; end else begin Items.BeginUpdate; try for I := 0 to Items.Count-1 do Items[I].ResetFields; finally Items.EndUpdate; end; end; end; end; procedure TCustomListView.RestoreWidgetState; begin inherited RestoreWidgetState; if Assigned(FMemStream) then begin FMemStream.Position := 0; FItems.ReadData(FMemStream); FreeAndNil(FMemStream); end; end; procedure TCustomListView.SaveWidgetState; begin inherited SaveWidgetState; FMemStream := TMemoryStream.Create; FItems.WriteData(FMemStream); FItems.Clear; end; { TTreeStrings } type TTreeStrings = class(TStrings) private FOwner: TTreeNodes; protected function Get(Index: Integer): string; override; function GetBufStart(Buffer: PChar; var Level: Integer): PChar; function GetCount: Integer; override; function GetObject(Index: Integer): TObject; override; procedure PutObject(Index: Integer; AObject: TObject); override; public constructor Create(AOwner: TTreeNodes); function Add(const S: string): Integer; override; procedure Clear; override; procedure Delete(Index: Integer); override; procedure Insert(Index: Integer; const S: string); override; procedure LoadTreeFromStream(Stream: TStream); procedure SaveTreeToStream(Stream: TStream); property Owner: TTreeNodes read FOwner; end; constructor TTreeStrings.Create(AOwner: TTreeNodes); begin inherited Create; FOwner := AOwner; end; function TTreeStrings.Get(Index: Integer): string; const TabChar = #9; var Level, I: Integer; Node: TTreeNode; begin Result := ''; Node := Owner.Item[Index]; if not Assigned(Node) then Exit; Level := Node.Level; for I := 0 to Level - 1 do Result := Result + TabChar; Result := Result + Node.Text; end; function TTreeStrings.GetBufStart(Buffer: PChar; var Level: Integer): PChar; begin Level := 0; while True do begin case Buffer^ of #32: Inc(Buffer); #9: begin Inc(Buffer); Inc(Level); end; else Break; end; end; Result := Buffer; end; function TTreeStrings.GetObject(Index: Integer): TObject; begin Result := Owner.Item[Index]; if Assigned(Result) then Result := TTreeNode(Result).Data; end; procedure TTreeStrings.PutObject(Index: Integer; AObject: TObject); var Node: TTreeNode; begin Node := Owner.Item[Index]; if Assigned(Node) then Node.Data := AObject; end; function TTreeStrings.GetCount: Integer; begin Result := Owner.Count; end; procedure TTreeStrings.Clear; begin Owner.Clear; end; procedure TTreeStrings.Delete(Index: Integer); begin Owner.Item[Index].Delete; end; function TTreeStrings.Add(const S: string): Integer; var Level, OldLevel, I: Integer; NewStr: string; Node: TTreeNode; begin Result := GetCount; if (Length(S) = 1) and (S[1] = Chr($1A)) then Exit; Node := nil; OldLevel := 0; NewStr := GetBufStart(PChar(S), Level); if Result > 0 then begin Node := Owner.Item[Result-1]; OldLevel := Node.Level; end; if (Level > OldLevel) or not Assigned(Node) then begin if Level - OldLevel > 1 then TreeViewError(sInvalidLevel); end else begin for I := OldLevel downto Level do begin Node := Node.Parent; if not Assigned(Node) and (I - Level > 0) then TreeViewError(sInvalidLevel); end; end; Owner.AddChild(Node, NewStr); end; procedure TTreeStrings.Insert(Index: Integer; const S: string); begin Owner.Insert(Owner.Item[Index], S); end; procedure TTreeStrings.LoadTreeFromStream(Stream: TStream); var List: TStringList; ANode, NextNode: TTreeNode; ALevel, I: Integer; CurrStr: string; StartSub, EndSub: PChar; SubItemStart: Integer; begin try List := nil; Owner.BeginUpdate; try List := TStringList.Create; Clear; List.LoadFromStream(Stream); ANode := nil; for I := 0 to List.Count - 1 do begin CurrStr := GetBufStart(PChar(List[I]), ALevel); SubItemStart := Pos(#9, CurrStr); if SubItemStart <> 0 then SetLength(CurrStr, SubItemStart-1); if ANode = nil then ANode := Owner.AddChild(nil, CurrStr) else if ANode.Level = ALevel then ANode := Owner.AddChild(ANode.Parent, CurrStr) else if ANode.Level = (ALevel - 1) then ANode := Owner.AddChild(ANode, CurrStr) else if ANode.Level > ALevel then begin NextNode := ANode.Parent; while NextNode.Level > ALevel do NextNode := NextNode.Parent; ANode := Owner.AddChild(NextNode.Parent, CurrStr); end else TreeViewErrorFmt(sInvalidLevelEx, [ALevel, CurrStr]); if Assigned(ANode) and (SubItemStart <> 0) then begin StartSub := PChar(List[I]) + SubItemStart + ALevel; while True do case StartSub^ of #9, #32: Inc(StartSub); #10, #0: Break; else begin EndSub := StartSub; while True do case EndSub^ of #32, #10, #9, #0: Break; else Inc(EndSub); end; SetString(CurrStr, StartSub, EndSub-StartSub); StartSub := EndSub; ANode.SubItems.Add(CurrStr); end; end; end; end; finally List.Free; Owner.EndUpdate; end; except Owner.Owner.Invalidate; { force repaint on exception } raise; end; end; procedure TTreeStrings.SaveTreeToStream(Stream: TStream); const TabChar = #9; var I: Integer; J: Integer; ANode: TTreeNode; NodeStr: string; begin if Count > 0 then begin ANode := Owner[0]; while Assigned(ANode) do begin NodeStr := ANode.Text; for I := 0 to ANode.Level - 1 do NodeStr := TabChar + NodeStr; for J := 0 to ANode.SubItems.Count-1 do NodeStr := NodeStr + TabChar + ANode.SubItems[J]; NodeStr := NodeStr + sLineBreak; Stream.Write(PChar(NodeStr)^, Length(NodeStr)); ANode := ANode.GetNext; end; end; end; { TCustomTreeView } constructor TCustomTreeView.Create(AOwner: TComponent); begin inherited Create(AOwner); Init(TTreeNode); end; destructor TCustomTreeView.Destroy; begin if Assigned(FMemStream) then FreeAndNil(FMemStream); FTreeNodes.Free; inherited Destroy; end; procedure TCustomTreeView.ItemChanging(item: QListViewItemH; _type: TItemChange; var Allow: Boolean); var AItem: TTreeNode; begin if _type <> ctState then Exit; AItem := FTreeNodes.FindItem(item); if not Assigned(AItem) or (Assigned(AItem) and AItem.FDestroying) then Exit; if Assigned(FOnChanging) then FOnChanging(Self, AItem, Allow); if AItem <> FSelectedNode then StartEditTimer; end; procedure TCustomTreeView.ItemChecked(item: QListViewItemH; Checked: Boolean); var AItem: TTreeNode; begin AItem := FTreeNodes.FindItem(item); if Assigned(AItem) then AItem.FChecked := Checked; StartEditTimer; end; procedure TCustomTreeView.ItemDestroyed(AItem: QListViewItemH); var ANode: TTreeNode; begin if QClxObjectMap_find(AItem) <> 0 then ANode := FTreeNodes.FindItem(AItem) else ANode := nil; if Assigned(ANode) then begin QClxObjectMap_remove(ANode.FHandle); ANode.FHandle := nil; if not (csDestroying in ComponentState) and (FHeader is TListViewHeader) then if (not TListViewHeader(FHeader).FHiddenChanging) and not ANode.FDestroying then ANode.Free; end; end; procedure TCustomTreeView.ItemExpanding(item: QListViewItemH; Expand: Boolean; var Allow: Boolean); var Node: TTreeNode; begin Node := FTreeNodes.FindItem(item); if Assigned(Node) and Node.Expanded <> Expand then Allow := Node.DoCanExpand(Expand); end; procedure TCustomTreeView.ItemExpanded(item: QListViewItemH; Expand: Boolean); var Node: TTreeNode; begin Node := FTreeNodes.FindItem(item); if not Assigned(Node) then Exit; if Expand then begin if AutoExpand and not FFullExpansion then DoAutoExpand(Node); if Assigned(FOnExpanded) then FOnExpanded(Self, Node); end else if Assigned(FOnCollapsed) then FOnCollapsed(Self, Node); end; procedure TCustomTreeView.ItemSelected(item: QListViewItemH; wasSelected: Boolean); const cIncSelCount: array [Boolean] of Integer = (-1, 1); var AItem: TTreeNode; begin Inc(FSelCount, cIncSelCount[wasSelected]); AItem := FTreeNodes.FindItem(item); if wasSelected and Assigned(AItem) and not AItem.FDestroying then FSelectedNode := AItem else FSelectedNode := nil; if Assigned(FSelectedNode) then Change(AItem); end; procedure TCustomTreeView.SetItems(const Value: TTreeNodes); begin FTreeNodes.Assign(Value); end; procedure TCustomTreeView.SetTopItem(const AItem: TTreeNode); var NewTopH: Integer; begin if Assigned(AItem) and HandleAllocated then begin NewTopH := QListView_itemPos(Handle, AItem.Handle); QListView_setContentsPos(Handle, QScrollView_contentsX(Handle), NewTopH); end; end; function TCustomTreeView.GetDropTarget: TTreeNode; var Temp: TCustomViewItem; begin Result := nil; Temp := FindDropTarget; if Temp is TTreeNode then Result := TTreeNode(Temp); end; function TCustomTreeView.GetTopItem: TTreeNode; begin Result := GetNodeAt(1, 1); end; constructor TCustomTreeView.Create(AOwner: TComponent; ANodeClass: TTreeNodeClass); begin inherited Create(AOwner); Init(ANodeClass); end; procedure TCustomTreeView.Init(ANodeClass: TTreeNodeClass); begin FTreeNodes := TTreeNodes.Create(Self); FTreeNodes.SetNodeClass(ANodeClass); FShowButtons := True; FItemMargin := 1; ColumnClick := True; ColumnMove := True; ColumnResize := True; end; function TCustomTreeView.IsCustomDrawn: Boolean; begin Result := Assigned(FOnCustomDrawItem) or Assigned(FOnCustomDrawSubItem) or Assigned(FOnCustomDrawBranch); end; procedure TCustomTreeView.InitWidget; begin inherited InitWidget; QListView_setRootIsDecorated(Handle, FShowButtons); end; procedure TCustomTreeView.DoGetImageIndex(item: TCustomViewItem); var Pixmap: QPixmapH; begin if item is TTreeNode then begin QWidget_setUpdatesEnabled(Handle, False); try if Assigned(FOnGetImageIndex) then FOnGetImageIndex(Self, TTreeNode(item)); if Assigned(Images) then begin Pixmap := Images.GetPixmap(TTreeNode(item).ImageIndex); if Assigned(Pixmap) then QListViewItem_setPixmap(item.Handle, 0, Pixmap); end; if Item.Selected then begin if Assigned(FOnGetSelectedIndex) then FOnGetSelectedIndex(Self, TTreeNode(item)); if Assigned(Images) then begin Pixmap := Images.GetPixmap(TTreeNode(item).SelectedIndex); if Assigned(Pixmap) then QListViewItem_setPixmap(item.Handle, 0, Pixmap); end; end; finally QWidget_setUpdatesEnabled(Handle, True); end; end; end; procedure TCustomTreeView.DoEditing(AItem: TCustomViewItem; var AllowEdit: Boolean); begin if Assigned(FOnEditing) and (AItem is TTreeNode) then FOnEditing(Self, TTreeNode(AItem), AllowEdit); end; procedure TCustomTreeView.DoEdited(AItem: TCustomViewItem; var S: WideString); begin if Assigned(FOnEdited) and (AItem is TTreeNode) then FOnEdited(Self, TTreeNode(AItem), S); end; procedure TCustomTreeView.FullCollapse; var Node: TTreeNode; begin Node := Items.GetFirstNode; while Node <> nil do begin Node.Collapse(True); Node := Node.GetNextSibling; end; end; procedure TCustomTreeView.FullExpand; var Node: TTreeNode; begin Node := Items.GetFirstNode; Items.BeginUpdate; FFullExpansion := True; try while Node <> nil do begin Node.Expand(True); Node := Node.GetNextSibling; end; finally FFullExpansion := False; Items.EndUpdate; end; end; function TCustomTreeView.GetNodeAt(X, Y: Integer): TTreeNode; var Temp: QListViewItemH; Pt: Types.TPoint; begin Result := nil; if HandleAllocated then begin Pt := Types.Point(X, Y); Temp := QListView_itemAt(Handle, @Pt); Result := FTreeNodes.FindItem(Temp); end; end; procedure TCustomTreeView.LoadFromFile(const FileName: string); var Stream: TStream; begin Stream := TFileStream.Create(FileName, fmOpenRead); try LoadFromStream(Stream); finally Stream.Free; end; end; procedure TCustomTreeView.LoadFromStream(Stream: TStream); begin with TTreeStrings.Create(Items) do try LoadTreeFromStream(Stream); finally Free; end; end; procedure TCustomTreeView.SaveToFile(const FileName: string); var Stream: TStream; begin Stream := TFileStream.Create(FileName, fmCreate); try SaveToStream(Stream); finally Stream.Free; end; end; procedure TCustomTreeView.SaveToStream(Stream: TStream); begin with TTreeStrings.Create(Items) do try SaveTreeToStream(Stream); finally Free; end; end; function TCustomTreeView.AlphaSort: Boolean; var Node: TTreeNode; begin Result := True; if HandleAllocated then begin SortColumn := 0; Sorted := True; Node := FTreeNodes.GetFirstNode; while Node <> nil do begin if Node.HasChildren then Node.AlphaSort(SortDirection = sdAscending); Node := Node.GetNext; end; end else Result := False; end; function TCustomTreeView.CanCollapse(Node: TTreeNode): Boolean; begin Result := True; if Assigned(FOnCollapsing) then FOnCollapsing(Self, Node, Result); end; function TCustomTreeView.CanExpand(Node: TTreeNode): Boolean; begin Result := True; if Assigned(FOnExpanding) then FOnExpanding(Self, Node, Result); end; procedure TCustomTreeView.Change(Node: TTreeNode); begin if Assigned(FOnChange) then FOnChange(Self, Node); end; procedure TCustomTreeView.Collapse(Node: TTreeNode); begin if Assigned(Node) then Node.Expanded := False; end; procedure TCustomTreeView.Delete(Node: TTreeNode); begin if Assigned(Node) then Node.Delete; end; function TCustomTreeView.EventFilter(Sender: QObjectH; Event: QEventH): Boolean; begin if QEvent_type(Event) = QEventType_FocusIn then if (Items.Count > 0) and not Assigned(Selected) then QListView_setSelected(Handle, QListView_firstChild(Handle), True); Result := inherited EventFilter(Sender, Event); end; procedure TCustomTreeView.Expand(Node: TTreeNode); begin if Assigned(Node) then Node.Expanded := True; end; procedure TCustomTreeView.Loaded; begin inherited Loaded; if csDesigning in ComponentState then FullExpand; end; procedure TCustomTreeView.SetSortType(const Value: TSortType); begin if SortType <> Value then begin FSortType := Value; if (SortType in [stText]) then AlphaSort; end; end; procedure TCustomTreeView.SetAutoExpand(const Value: Boolean); begin if FAutoExpand <> Value then FAutoExpand := Value; end; function TCustomTreeView.GetSelected: TTreeNode; begin Result := FSelectedNode; end; procedure TCustomTreeView.SetSelected(const Value: TTreeNode); begin if not (csDestroying in ComponentState) then begin if Assigned(FSelectedNode) and not MultiSelect then FSelectedNode.Selected := False; if Assigned(Value) then Value.Selected := True; end; end; procedure TCustomTreeView.SetItemMargin(const Value: Integer); begin if ItemMargin <> Value then begin FItemMargin := Value; if HandleAllocated then QListView_setItemMargin(Handle, FItemMargin); end; end; procedure TCustomTreeView.SelectAll(Select: Boolean); begin MultiSelect := True; if HandleAllocated then QListView_selectAll(Handle, Select); end; procedure TCustomTreeView.SetOnItemDoubleClick(const Value: TTVItemDoubleClickEvent); var Method: TMethod; begin FOnItemDoubleClick := Value; if Assigned(FOnItemDoubleClick) then QListView_doubleClicked_Event(Method) := DoItemDoubleClick else Method := NullHook; QListView_hook_hook_doubleClicked(QListView_hookH(Hooks), Method); end; procedure TCustomTreeView.SetOnItemEnter(const Value: TTVItemEnterEvent); var Method: TMethod; begin FOnItemEnter := Value; if Assigned(FOnItemEnter) then QListView_onItem_Event(Method) := DoOnItemEnter else Method := NullHook; QListView_hook_hook_onItem(QListView_hookH(Hooks), Method); end; procedure TCustomTreeView.SetOnItemExitViewportEnter(const Value: TTVItemExitViewportEnterEvent); var Method: TMethod; begin FOnItemExitViewportEnter := Value; if Assigned(FOnItemExitViewportEnter) then QListView_onViewport_Event(Method) := DoOnItemExitViewportEnter else Method := NullHook; QListView_hook_hook_onViewport(QListView_hookH(Hooks), Method); end; procedure TCustomTreeView.SetOnMouseDown(const Value: TTVButtonDownEvent); begin FOnMouseDown := Value; HookMouseDowns; end; procedure TCustomTreeView.SetOnViewportButtonDown(const Value: TTVViewportButtonDownEvent); begin FOnViewportMouseDown := Value; HookMouseDowns; end; procedure TCustomTreeView.DoItemClick(p1: Integer; p2: QListViewItemH; p3: PPoint; p4: Integer); var AItem: TTreeNode; SelNode: TTreeNode; begin try AItem := FTreeNodes.FindItem(p2); if AutoExpand and Assigned(AItem) then begin SelNode := Selected; try DoAutoExpand(AItem); finally Selected := SelNode; end; end; if Assigned(AItem) then begin if Assigned(FOnItemClick) then FOnItemClick(Self, ButtonToMouseButton(p1), AItem, p3^); if (p4 = 0) and FAllowEdit then EditItem; end; except Application.HandleException(Self); end; end; procedure TCustomTreeView.DoItemDoubleClick(p1: QListViewItemH); var SelectedItem: TTreeNode; begin if Assigned(FOnItemDoubleClick) then try SelectedItem := FTreeNodes.FindItem(p1); FOnItemDoubleClick(Self, SelectedItem); except Application.HandleException(Self); end; end; procedure TCustomTreeView.DoOnItemEnter(item: QListViewItemH); var SelectedItem: TTreeNode; begin if Assigned(FOnItemEnter) then try SelectedItem := FTreeNodes.FindItem(item); FOnItemEnter(Self, SelectedItem); except Application.HandleException(Self); end; end; procedure TCustomTreeView.DoOnItemExitViewportEnter; begin if Assigned(FOnItemExitViewportEnter) then try FOnItemExitViewportEnter(Self); except Application.HandleException(Self); end; end; procedure TCustomTreeView.DoOnMouseDown(p1: Integer; p2: QListViewItemH; p3: PPoint; p4: Integer); var AItem: TTreeNode; begin try AItem := FTreeNodes.FindItem(p2); if Assigned(FOnMouseDown) and (p2 <> nil) then FOnMouseDown(Self, ButtonToMouseButton(p1), AItem, p3^) else if Assigned(FOnViewportMouseDown) and (AItem = nil) then FOnViewportMouseDown(Self, ButtonToMouseButton(p1), p3^); except Application.HandleException(Self); end; end; procedure TCustomTreeView.HookMouseDowns; var Method: TMethod; begin if Assigned(FOnMouseDown) or Assigned(FOnViewportMouseDown) then QListView_mouseButtonPressed_Event(Method) := DoOnMouseDown else Method := NullHook; QListView_hook_hook_mouseButtonPressed(QListView_hookH(Hooks), Method); end; procedure TCustomTreeView.DoAutoExpand(ExpandedNode: TTreeNode); var Node: TTreeNode; ParentNode: TTreeNode; begin if ExpandedNode = nil then Exit; Items.BeginUpdate; try ParentNode := ExpandedNode; if Assigned(ParentNode) then while ParentNode.GetParent <> nil do ParentNode := ParentNode.GetParent; Node := Items.GetFirstNode; if Assigned(Node) then begin while True do begin if Node = nil then Exit; if Node = ParentNode then begin Node := Node.getNextSibling; Continue; end; Node.Collapse(False); Node := Node.getNextSibling; end; end; finally if not ExpandedNode.Expanded then ExpandedNode.Expand(False); Items.EndUpdate; end; end; procedure TCustomTreeView.SetShowButtons(const Value: Boolean); begin if FShowButtons <> Value then begin FShowButtons := Value; if HandleAllocated then QListView_setRootIsDecorated(Handle, FShowButtons); end; end; procedure TCustomTreeView.RepopulateItems; var I: Integer; begin if HandleAllocated then begin if (QListView_childCount(Handle) = 0) and (QListView_columns(Handle) > 0) then begin Items.BeginUpdate; try for I := 0 to Items.Count-1 do Items[I].ReCreateItem; finally Items.EndUpdate; end; end else begin Items.BeginUpdate; try for I := 0 to Items.Count-1 do Items[I].ResetFields; finally Items.EndUpdate; end; end; end; end; procedure TCustomTreeView.RestoreWidgetState; begin inherited RestoreWidgetState; if Assigned(FMemStream) then begin FMemStream.Position := 0; FTreeNodes.ReadData(FMemStream); FreeAndNil(FMemStream); end; end; procedure TCustomTreeView.SaveWidgetState; begin inherited SaveWidgetState; FMemStream := TMemoryStream.Create; FTreeNodes.WriteData(FMemStream); FTreeNodes.Clear; end; procedure TCustomTreeView.HookEvents; var Method: TMethod; begin inherited HookEvents; QListView_mouseButtonClicked_Event(Method) := DoItemClick; QListView_hook_hook_mouseButtonClicked(QListView_hookH(Hooks), Method); end; procedure TCustomTreeView.ImageListChanged; var I: Integer; begin for I := 0 to FTreeNodes.Count-1 do FTreeNodes[i].UpdateImages; end; { TTreeView } {$IF not (defined(LINUX) and defined(VER140))} function TTreeView.GetSelCount: Integer; begin Result := FSelCount; end; {$IFEND} { TViewItemsList } function TViewItemsList.GetItem(Index: Integer): TCustomViewItem; begin Result := TCustomViewItem(inherited GetItem(Index)); end; procedure TViewItemsList.SetItem(Index: Integer; AObject: TCustomViewItem); begin inherited SetItem(Index, AObject); end; { TCustomHeaderControl } constructor TCustomHeaderControl.Create(AOwner: TComponent); begin inherited Create(AOwner); FCanvas := TControlCanvas.Create; TControlCanvas(FCanvas).Control := Self; FImageChanges := TChangeLink.Create; FImageChanges.OnChange := OnImageChanges; FOrientation := hoHorizontal; FTracking := True; FDragReorder := False; Height := 19; Align := alTop; end; destructor TCustomHeaderControl.Destroy; begin if Assigned(FMemStream) then FreeAndNil(FMemStream); FImageChanges.Free; FCanvas.Free; inherited Destroy; end; procedure TCustomHeaderControl.AssignTo(Dest: TPersistent); var I: Integer; begin if Dest is TCustomHeaderControl then begin TCustomHeaderControl(Dest).Sections.Clear; for I := 0 to Sections.Count - 1 do TCustomHeaderControl(Dest).Sections.Add.Assign(Sections[I]); end else inherited Assign(Dest); end; procedure TCustomHeaderControl.ChangeBounds(ALeft, ATop, AWidth, AHeight: Integer); begin inherited ChangeBounds(ALeft, ATop, AWidth, AHeight); Invalidate; end; procedure TCustomHeaderControl.ColumnClicked(Section: TCustomHeaderSection); begin if Assigned(FOnSectionClick) then FOnSectionClick(Self, Section); end; procedure TCustomHeaderControl.ColumnMoved(Section: TCustomHeaderSection); begin if Assigned(FOnSectionMoved) then FOnSectionMoved(Self, Section); end; procedure TCustomHeaderControl.ColumnResized(Section: TCustomHeaderSection); begin if Assigned(FOnSectionResize) then FOnSectionResize(Self, Section); end; procedure TCustomHeaderControl.CreateWidget; begin FHandle := QHeader_create(ParentWidget, nil); Hooks := QHeader_hook_create(FHandle); end; function TCustomHeaderControl.GetHandle: QHeaderH; begin HandleNeeded; Result := QHeaderH(FHandle); end; function TCustomHeaderControl.GetSections: TCustomHeaderSections; begin Result := FSections; end; procedure TCustomHeaderControl.HookEvents; var Method: TMethod; begin inherited HookEvents; QHeader_sectionClicked_Event(Method) := SectionClicked; QHeader_hook_hook_sectionClicked(QHeader_hookH(Hooks), Method); QHeader_sizeChange_Event(Method) := SectionSizeChanged; QHeader_hook_hook_sizeChange(QHeader_hookH(Hooks), Method); QHeader_moved_Event(Method) := SectionMoved; QHeader_hook_hook_moved(QHeader_hookH(Hooks), Method); end; procedure TCustomHeaderControl.ImageListChanged; begin FSections.UpdateImages; end; procedure TCustomHeaderControl.InitWidget; begin inherited InitWidget; if FDragReorder then FClickable := True; QHeader_setClickEnabled(Handle, FClickable, -1); QHeader_setResizeEnabled(Handle, FResizable, -1); QHeader_setTracking(Handle, FTracking); QHeader_setMovingEnabled(Handle, FDragReorder); end; procedure TCustomHeaderControl.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (AComponent = FImages) then begin if (Operation = opRemove) then FImages := nil; ImageListChanged; end; end; procedure TCustomHeaderControl.OnImageChanges(Sender: TObject); begin ImageListChanged; end; procedure TCustomHeaderControl.RestoreWidgetState; begin inherited RestoreWidgetState; if Assigned(FMemStream) then begin FMemStream.Position := 0; FSections.Clear; FMemStream.ReadComponent(Self); FreeAndNil(FMemStream); end; end; procedure TCustomHeaderControl.SaveWidgetState; begin inherited SaveWidgetState; if not Assigned(FMemStream) then FMemStream := TMemoryStream.Create else FMemStream.Clear; FMemStream.WriteComponent(Self); end; procedure TCustomHeaderControl.SectionClicked(SectionIndex: Integer); begin try if (SectionIndex >= 0) and (SectionIndex < FSections.Count) then ColumnClicked(Sections[SectionIndex]); except Application.HandleException(Self); end; end; procedure TCustomHeaderControl.SectionMoved(FromIndex, ToIndex: Integer); var FromSection: TCustomHeaderSection; begin if (FromIndex <> ToIndex) and (FromIndex <> ToIndex-1) then begin try FDontResubmit := True; try if ToIndex > FromIndex then Dec(ToIndex); FromSection := Sections[FromIndex]; FromSection.SetIndex(ToIndex); ColumnMoved(FromSection); except Application.HandleException(Self); end; finally FDontResubmit := False; end; end; end; procedure TCustomHeaderControl.SectionSizeChanged(SectionIndex, OldSize, NewSize: Integer); begin if OldSize <> NewSize then begin try { This by-passes the MaxWidth and MinWidth. Is there a way to make Qt happy with min/max widths on sections? } if (SectionIndex >= 0) and (SectionIndex < FSections.Count) then begin FSections[SectionIndex].FWidth := NewSize; ColumnResized(FSections[SectionIndex]); end; except Application.HandleException(Self); end; end; end; procedure TCustomHeaderControl.SetClickable(const Value: Boolean); var I: Integer; begin if Clickable <> Value then begin FClickable := Value; for I := 0 to Sections.Count-1 do Sections[I].AllowClick := FClickable; if not FClickable then DragReorder := False; if HandleAllocated then QWidget_update(Handle); end; end; procedure TCustomHeaderControl.SetDragReorder(const Value: Boolean); begin if DragReorder <> Value then begin FDragReorder := Value; if HandleAllocated then QHeader_setMovingEnabled(Handle, FDragReorder); if FDragReorder then Clickable := True; end; end; procedure TCustomHeaderControl.SetImages(const Value: TCustomImageList); begin if FImages <> Value then begin if Assigned(FImages) then FImages.UnRegisterChanges(FImageChanges); FImages := Value; if Assigned(FImages) then FImages.RegisterChanges(FImageChanges); ImageListChanged; end; end; procedure TCustomHeaderControl.SetOrientation(const Value: THeaderOrientation); const cOrientation: array [THeaderOrientation] of Qt.Orientation = (Orientation_Horizontal, Orientation_Vertical); begin if FOrientation <> Value then begin FOrientation := Value; if Align <> alNone then if FOrientation = hoHorizontal then Align := alTop else Align := alLeft; if HandleAllocated then QHeader_setOrientation(Handle, cOrientation[FOrientation]); end; end; procedure TCustomHeaderControl.SetResizable(const Value: Boolean); var I: Integer; begin if Resizable <> Value then begin FResizable := Value; for I := 0 to Sections.Count-1 do Sections[I].AllowResize := FResizable; end; end; procedure TCustomHeaderControl.SetSections(const Value: TCustomHeaderSections); begin FSections.Assign(Value); end; procedure TCustomHeaderControl.SetTracking(const Value: Boolean); begin if Tracking <> Value then begin FTracking := Value; if HandleAllocated then QHeader_setTracking(Handle, FTracking); end; end; { THeaderSections } function THeaderSections.Add: THeaderSection; begin Result := THeaderSection(inherited Add); end; function THeaderSections.GetItem(Index: Integer): THeaderSection; begin Result := THeaderSection(inherited GetItem(Index)); end; procedure THeaderSections.SetItem(Index: Integer; Value: THeaderSection); begin inherited SetItem(Index, Value); end; { TCustomHeaderSection } procedure TCustomHeaderSection.AddSection; begin QHeader_addLabel(Header.Handle, nil, FWidth); QHeader_setClickEnabled(Header.Handle, FAllowClick, QHeader_mapToIndex(Header.Handle, Index)); QHeader_setResizeEnabled(Header.Handle, FAllowResize, QHeader_mapToIndex(Header.Handle, Index)); end; procedure TCustomHeaderSection.AssignTo(Dest: TPersistent); begin if Dest is TCustomHeaderSection then begin TCustomHeaderSection(Dest).AllowResize := FAllowResize; TCustomHeaderSection(Dest).AllowClick := FAllowClick; TCustomHeaderSection(Dest).MaxWidth := FMaxWidth; TCustomHeaderSection(Dest).Width := FWidth; TCustomHeaderSection(Dest).MinWidth := FMinWidth; end else inherited AssignTo(Dest); end; constructor TCustomHeaderSection.Create(Collection: TCollection); begin inherited Create(Collection); if (Collection is TCustomHeaderSections) and (TCustomHeaderSections(Collection).GetOwner is TCustomHeaderControl) then FHeader := TCustomHeaderControl(TCustomHeaderSections(Collection).GetOwner) else raise EHeaderException.CreateRes(@sOwnerNotCustomHeaderSections); FAllowClick := True; FAllowResize := True; FWidth := 50; FImageIndex := -1; MaxWidth := 1000; MinWidth := 0; AddSection; end; function TCustomHeaderSection.CalcSize: Integer; const cMargin = 4 shl 1; var fm: QFontMetricsH; Pixmap: QPixmapH; ISet: QIconSetH; begin if not AutoSize then begin Result := FWidth; Exit; end else Result := 0; if FText <> '' then begin fm := QFontMetrics_create(Header.Font.Handle); try Result := QFontMetrics_width(fm, PWideString(@FText), Length(FText)) + cMargin; finally QFontMetrics_destroy(fm); end; end; ISet := QHeader_iconSet(Header.Handle, QHeader_mapToIndex(Header.Handle, Index)); if Assigned(ISet) then begin Pixmap := QPixmap_create; try QIconSet_pixmap(ISet, Pixmap, QIconSetSize_Small, QIconSetMode_Normal); Inc(Result, QPixmap_width(Pixmap) + 2 + cMargin); finally QPixmap_destroy(Pixmap); end; end; end; function TCustomHeaderSection.Header: TCustomHeaderControl; begin Result := FHeader; end; function TCustomHeaderSection.GetDisplayName: string; begin Result := FText; if Result = '' then Result := inherited GetDisplayName; end; function TCustomHeaderSection.GetLeft: Integer; begin if Header.HandleAllocated then Result := QHeader_sectionPos(Header.Handle, QHeader_mapToIndex(Header.Handle, Index)) else Result := -1; end; procedure TCustomHeaderSection.Resubmit; var AHandle: QHeaderH; begin if Header = nil then Exit; if Header.HandleAllocated then begin AHandle := Header.Handle; QWidget_setUpdatesEnabled(AHandle, False); try QHeader_setLabel(AHandle, QHeader_mapToIndex(Header.Handle, Index), @FText, CalcSize); UpdateImage; QHeader_setClickEnabled(AHandle, FAllowClick, QHeader_mapToIndex(Header.Handle, Index)); QHeader_setResizeEnabled(AHandle, FAllowResize, QHeader_mapToIndex(Header.Handle, Index)); finally QWidget_setUpdatesEnabled(AHandle, True); end; end; end; procedure TCustomHeaderSection.SetAutoSize(const Value: Boolean); begin if FAutoSize <> Value then begin FAutoSize := Value; if Header.HandleAllocated then QHeader_setLabel(Header.Handle, QHeader_mapToIndex(Header.Handle, Index), PWideString(@FText), CalcSize); end; end; function TCustomHeaderSection.GetRight: Integer; begin Result := Left + Width; end; function TCustomHeaderSection.GetWidth: Integer; begin if Header.HandleAllocated and not (csRecreating in Header.ControlState) then FWidth := QHeader_sectionSize(Header.Handle, QHeader_mapToIndex(Header.Handle, Index)); Result := FWidth; end; procedure TCustomHeaderSection.SetAllowClick(const Value: Boolean); begin if FAllowClick <> Value then begin FAllowClick := Value; if Header.HandleAllocated then begin QHeader_setClickEnabled(Header.Handle, FAllowClick, QHeader_mapToIndex(Header.Handle, Index)); QWidget_update(Header.Handle); end; end; end; procedure TCustomHeaderSection.SetAllowResize(const Value: Boolean); begin if FAllowResize <> Value then begin FAllowResize := Value; if Header.HandleAllocated then begin QHeader_setResizeEnabled(Header.Handle, FAllowResize, QHeader_mapToIndex(Header.Handle, Index)); QWidget_update(Header.Handle); end; end; end; procedure TCustomHeaderSection.SetImageIndex(const Value: TImageIndex); begin if FImageIndex <> Value then begin FImageIndex := Value; UpdateImage; end; end; procedure TCustomHeaderSection.SetMaxWidth(const Value: Integer); begin if FMaxWidth <> Value then begin FMaxWidth := Value; if FMaxWidth < FMinWidth then FMaxWidth := FMinWidth + 1; UpdateWidth; end; end; procedure TCustomHeaderSection.SetMinWidth(const Value: Integer); begin if FMinWidth <> Value then begin FMinWidth := Value; if FMinWidth > FMaxWidth then FMinWidth := FMaxWidth - 1; UpdateWidth; end; end; procedure TCustomHeaderSection.SetWidth(Value: Integer); begin if FWidth <> Value then begin if ((Value < MinWidth) and (Value >= 0)) then Value := MinWidth else if ((MaxWidth > 0) and (Value > MaxWidth)) then Value := MaxWidth; SetWidthVal(Value); end; end; procedure TCustomHeaderSection.SetWidthVal(const Value: Integer); begin FWidth := Value; end; procedure TCustomHeaderSection.UpdateImage; var Pixmap: QPixmapH; IconSet: QIconSetH; begin if Header.HandleAllocated then begin if Assigned(Header.FImages) then Pixmap := Header.FImages.GetPixmap(FImageIndex) else Pixmap := nil; IconSet := QHeader_iconSet(Header.Handle, QHeader_mapToIndex(Header.Handle, Index)); if not Assigned(IconSet) then begin IconSet := QIconset_create; try QHeader_setLabel(Header.Handle, QHeader_mapToIndex(Header.Handle, Index), IconSet, PWideString(@FText), CalcSize); finally QIconSet_destroy(IconSet); end; end; IconSet := QHeader_iconSet(Header.Handle, QHeader_mapToIndex(Header.Handle, Index)); if not Assigned(Pixmap) then QIconSet_reset(IconSet, QPixmap_create, QIconSetSize_Small) else QIconSet_setPixmap(IconSet, Pixmap, QIconSetSize_Small, QIconSetMode_Normal); QWidget_update(Header.Handle); end; end; procedure TCustomHeaderSection.UpdateWidth; begin if FWidth > FMaxWidth then Width := FMaxWidth else if FWidth < FMinWidth then Width := FMinWidth; end; { TListColumn } procedure TListColumn.AddSection; begin if HeaderIsListHeader and not TListViewHeader(Header).Hidden then begin if Collection.Count <> QListView_columns(ViewControl.Handle) then QListView_addColumn(ViewControl.Handle, nil, FWidth); QHeader_setClickEnabled(Header.Handle, FAllowClick, QHeader_mapToIndex(QListView_header(ViewControl.Handle), Index)); QHeader_setResizeEnabled(Header.Handle, FAllowResize, QHeader_mapToIndex(QListView_header(ViewControl.Handle), Index)); if QHeader_mapToIndex(QListView_header(ViewControl.Handle), Index) = 0 then { repopulate dormant items } ViewControl.RepopulateItems; end; Alignment := taLeftJustify; end; function TListColumn.HeaderIsListHeader: Boolean; begin Result := Assigned(FHeader) and (Header is TListViewHeader); end; {$IF not (defined(LINUX) and defined(VER140))} function TListColumn.GetCaption: WideString; begin Result := FText; end; {$IFEND} procedure TListColumn.AssignTo(Dest: TPersistent); begin inherited AssignTo(Dest); if Dest is TListColumn then begin TListColumn(Dest).Caption := Caption; TListColumn(Dest).Alignment := Alignment; TListColumn(Dest).AutoSize := AutoSize; end; end; destructor TListColumn.Destroy; var Empty: WideString; begin if not (csDestroying in ViewControl.ComponentState) and HeaderIsListHeader then if not TListViewHeader(Header).Hidden then begin if QHeader_mapToIndex(QListView_header(ViewControl.Handle), Index) = 0 then begin if QListView_columns(ViewControl.Handle) > 1 then begin QListView_removeColumn(ViewControl.Handle, QHeader_mapToIndex(QListView_header(ViewControl.Handle), Index)); ViewControl.RepopulateItems; end else begin Empty := ''; QListView_setColumnText(ViewControl.Handle, 0, @Empty); QListView_setColumnWidthMode(ViewControl.Handle, 0, QListViewWidthMode_Maximum); end; end else if QHeader_mapToIndex(QListView_header(ViewControl.Handle), Index) <> 0 then QListView_removeColumn(ViewControl.Handle, QHeader_mapToIndex(QListView_header(ViewControl.Handle), Index)); end; inherited Destroy; end; function TListColumn.GetWidth: Integer; begin if Header.HandleAllocated and not (csRecreating in Header.ControlState) and HeaderIsListHeader and (not TListViewHeader(Header).Hidden) then FWidth := QListView_columnWidth(ViewControl.Handle, QHeader_mapToIndex(QListView_header(ViewControl.Handle), Index)); Result := FWidth; end; const ColAlignmentFlags: array [TAlignment] of Integer = (Integer(AlignmentFlags_AlignLeft), Integer(AlignmentFlags_AlignRight), Integer(AlignmentFlags_AlignCenter)); ColAutoSize: array [Boolean] of QListViewWidthMode = (QListViewWidthMode_Manual, QListViewWidthMode_Maximum); procedure TListColumn.Resubmit; var AHandle: QHeaderH; begin if (Header <> nil) and Header.HandleAllocated then begin AHandle := Header.Handle; if not TListViewHeader(Header).Hidden then QWidget_setUpdatesEnabled(AHandle, False); try QListView_setColumnText(ViewControl.Handle, QHeader_mapToIndex(QListView_header(ViewControl.Handle), Index), PWideString(@FText)); QListView_setColumnAlignment(ViewControl.Handle, QHeader_mapToIndex(QListView_header(ViewControl.Handle), Index), ColAlignmentFlags[FAlignment]); QListView_setColumnWidth(ViewControl.Handle, QHeader_mapToIndex(QListView_header(ViewControl.Handle), Index), Width); QHeader_setClickEnabled(AHandle, FAllowClick, QHeader_mapToIndex(QListView_header(ViewControl.Handle), Index)); QHeader_setResizeEnabled(AHandle, FAllowResize, QHeader_mapToIndex(QListView_header(ViewControl.Handle), Index)); finally if not TListViewHeader(Header).Hidden then QWidget_setUpdatesEnabled(AHandle, True); end; end; end; procedure TListColumn.SetAlignment(const Value: TAlignment); begin if (Value <> Alignment) and (QHeader_mapToIndex(QListView_header(ViewControl.Handle), Index) <> 0) then begin FAlignment := Value; if not TListViewHeader(Header).Hidden and ViewControl.HandleAllocated then QListView_setColumnAlignment(ViewControl.Handle, QHeader_mapToIndex(QListView_header(ViewControl.Handle), Index), ColAlignmentFlags[Value]); end; end; procedure TListColumn.SetAutoSize(const Value: Boolean); begin if AutoSize <> Value then begin FAutoSize := Value; if not TListViewHeader(Header).Hidden and ViewControl.HandleAllocated then QListView_setColumnWidthMode(ViewControl.Handle, QHeader_mapToIndex(QListView_header(ViewControl.Handle), Index), ColAutoSize[Value]); end; end; procedure TListColumn.SetCaption(const Value: WideString); begin if FText <> Value then begin FText := Value; if ViewControl.HandleAllocated and not TListViewHeader(Header).Hidden then QListView_setColumnText(ViewControl.Handle, QHeader_mapToIndex(QListView_header(ViewControl.Handle), Index), PWideString(@FText)); end; end; procedure TListColumn.SetWidthVal(const Value: Integer); begin FWidth := Value; if ViewControl.HandleAllocated and not TListViewHeader(Header).Hidden then QListView_setColumnWidth(ViewControl.Handle, QHeader_mapToIndex(QListView_header(ViewControl.Handle), Index), FWidth); ViewControl.UpdateControl; end; function TListColumn.ViewControl: TCustomViewControl; begin Result := TCustomViewControl(Header.Owner); end; { TListViewHeader } constructor TListViewHeader.Create(AOwner: TComponent); begin inherited Create(AOwner); FSections := TListColumns.Create(Self, TListColumn); end; destructor TListViewHeader.Destroy; begin FSections.Free; inherited Destroy; end; procedure TListViewHeader.ColumnClicked(Section: TCustomHeaderSection); begin if Assigned(ViewControl.FOnColumnClick) then ViewControl.FOnColumnClick(Owner, Section as TListColumn); end; procedure TListViewHeader.ColumnMoved(Section: TCustomHeaderSection); begin if Assigned(ViewControl.FColumnDragged) then ViewControl.FColumnDragged(Owner, Section as TListColumn); end; procedure TListViewHeader.ColumnResized(Section: TCustomHeaderSection); begin if Assigned(ViewControl.FColumnResize) then ViewControl.FColumnResize(Owner, Section as TListColumn); end; procedure TListViewHeader.CreateWidget; begin if Hidden then FHandle := QHeader_create(ParentWidget, nil) else FHandle := QListView_header(ListViewHandle); Hooks := QHeader_hook_create(FHandle); end; procedure TListViewHeader.DestroyWidget; begin if not (csRecreating in ControlState) then FSections.Clear; if Hidden and not FHiddenChanging then inherited DestroyWidget else begin if Assigned(Hooks) then begin QHeader_hook_destroy(QHeader_hookH(Hooks)); Hooks := nil; end; QClxObjectMap_remove(FHandle); FHandle := nil; end; end; function TListViewHeader.EventFilter(Sender: QObjectH; Event: QEventH): Boolean; begin if Hidden then Result := inherited EventFilter(Sender, Event) else Result := False; end; function TListViewHeader.GetHandle: QHeaderH; begin HandleNeeded; if not Hidden and (FHandle <> QListView_header(ListViewHandle)) then RecreateWidget; Result := QHeaderH(FHandle); end; function TListViewHeader.GetSections: TListColumns; begin Result := TListColumns(inherited GetSections); end; procedure TListViewHeader.HookEvents; var Method: TMethod; begin inherited HookEvents; if not Hidden then begin if QClxObjectMap_find(Handle) <> 0 then QClxObjectMap_remove(Handle); QClxObjectMap_add(Handle, Integer(Owner)); if csDesigning in ComponentState then begin TEventFilterMethod(Method) := ViewControl.MainEventFilter; Qt_hook_hook_events(Hooks, Method); end; end; end; procedure TListViewHeader.InitWidget; begin inherited InitWidget; Visible := not Hidden; end; function TListViewHeader.ListViewHandle: QListViewH; begin Result := TCustomViewControl(Owner).Handle; end; procedure TListViewHeader.SetHidden(const Value: Boolean); begin if FHidden <> Value then begin FHidden := Value; FHiddenChanging := True; try while QListView_columns(ListViewHandle) > 1 do QListView_removeColumn(ListViewHandle, 1); RecreateWidget; if Hidden then begin if QListView_columns(ListViewHandle) = 0 then QListView_addColumn(ListViewHandle, nil, 50); QListView_setColumnWidthMode(ListViewHandle, 0, QListViewWidthMode_Maximum); end else begin QListView_setShowSortIndicator(ListViewHandle, ViewControl.ShowColumnSortIndicators); if ViewControl.Columns.Count > 0 then QListView_setColumnWidthMode(ListViewHandle, 0, ColAutoSize[ViewControl.Columns[0].AutoSize]); end; ViewControl.RepopulateItems; finally FHiddenChanging := False; end; end; end; procedure TListViewHeader.SetSections(const Value: TListColumns); begin inherited SetSections(Value); end; procedure TListViewHeader.Update; begin if (not Hidden) and not (csDestroying in ViewControl.ComponentState) and HandleAllocated then QWidget_update(Handle); end; procedure TListViewHeader.UpdateWidgetShowing; begin if HandleAllocated then begin if Hidden then QWidget_hide(QListView_header(ListViewHandle)) else QWidget_show(QListView_header(ListViewHandle)); QListView_triggerUpdate(ListViewHandle); end; end; function TListViewHeader.ViewControl: TCustomViewControl; begin Result := TCustomViewControl(Owner); end; { THeaderControl } function THeaderControl.GetSections: THeaderSections; begin Result := THeaderSections(inherited GetSections); end; procedure THeaderControl.CreateWidget; begin FHandle := QHeader_create(ParentWidget, nil); Hooks := QHeader_hook_create(Handle); end; procedure THeaderControl.SetSections(const Value: THeaderSections); begin inherited SetSections(Value); end; destructor THeaderControl.Destroy; begin FSections.Free; inherited Destroy; end; procedure THeaderControl.InitWidget; begin inherited InitWidget; QHeader_setTracking(Handle, FTracking); end; constructor THeaderControl.Create(AOwner: TComponent); begin inherited Create(AOwner); Init(THeaderSection); end; constructor THeaderControl.Create(AOwner: TComponent; AHeaderSectionClass: THeaderSectionClass); begin inherited Create(AOwner); Init(AHeaderSectionClass); end; procedure THeaderControl.Init(AHeaderSectionClass: THeaderSectionClass); begin FSections := THeaderSections.Create(Self, AHeaderSectionClass); end; { TListColumns } function TListColumns.Add: TListColumn; begin Result := TListColumn(inherited Add); end; procedure TListColumns.Added(var Item: TCollectionItem); begin if not (Item is TListColumn) then Exit; if Assigned(ViewControl) then begin BeginUpdate; try ViewControl.RepopulateItems; finally EndUpdate; end; end; end; function TListColumns.GetItem(Index: Integer): TListColumn; begin Result := TListColumn(inherited GetItem(Index)); end; function TListColumns.GetViewControl: TCustomViewControl; begin if FHeaderControl is TListViewHeader then Result := FHeaderControl.Owner as TCustomViewControl else Result := nil; end; procedure TListColumns.SetItem(Index: Integer; Value: TListColumn); begin inherited SetItem(Index, Value); end; procedure TListColumns.Update(Item: TCollectionItem); var I: Integer; begin if Assigned(ViewControl) then if not ViewControl.FHeader.FDontResubmit then begin if not Assigned(Item) then begin for I := 0 to Count-1 do Items[I].Resubmit; end else if Item is TListColumn then TListColumn(Item).Resubmit; if not Assigned(Item) and not (csDestroying in ViewControl.ComponentState) then ViewControl.UpdateControl; end; end; { TCustomHeaderSections } constructor TCustomHeaderSections.Create(HeaderControl: TCustomHeaderControl; SectionClass: THeaderSectionClass); begin inherited Create(SectionClass); FHeaderControl := HeaderControl; end; function TCustomHeaderSections.GetItem(Index: Integer): TCustomHeaderSection; begin Result := TCustomHeaderSection(inherited GetItem(Index)); end; function TCustomHeaderSections.GetOwner: TPersistent; begin Result := FHeaderControl; end; procedure TCustomHeaderSections.SetItem(Index: Integer; Value: TCustomHeaderSection); begin inherited SetItem(Index, Value); end; procedure TCustomHeaderSections.Update(Item: TCollectionItem); var I: Integer; begin if Owner is TCustomHeaderControl then if not TCustomHeaderControl(Owner).FDontResubmit then begin if not Assigned(Item) then begin for I := 0 to Count-1 do Items[I].Resubmit; end else if Item is TCustomHeaderSection then TCustomHeaderSection(Item).Resubmit; if TCustomHeaderControl(Owner).HandleAllocated then QWidget_repaint(TCustomHeaderControl(Owner).Handle); end; end; procedure TCustomHeaderSections.UpdateImages; var I: Integer; begin for I := 0 to Count-1 do Items[I].UpdateImage; end; { TListItems } function TListItems.Add: TListItem; var After: TListItem; begin if FItems.Count > 0 then After := Item[FItems.Count-1] else After := nil; Result := FListItemClass.Create(Self, nil, After); FItems.Add(Result); if Assigned(Owner) and Assigned(Owner.FOnInsert) then Owner.FOnInsert(Owner, Result); end; function TListItems.AddItem(Item: TListItem; Index: Integer): TListItem; begin if Index < 0 then Index := 0 else if Index >= Count then Index := Count-1; BeginUpdate; try if not Assigned(Item) then Result := FListItemClass.Create(Self, FItems[Index].Parent, nil) else Result := Item; FItems.Insert(Index, Result); if (Result <> Item) and Assigned(Item) then Result.Assign(Item); finally EndUpdate; end; end; constructor TListItems.Create(AOwner: TCustomViewControl); begin inherited Create(AOwner); SetItemClass(TListItem); end; constructor TListItems.Create(AOwner: TCustomViewControl; AItemClass: TListItemClass); begin inherited Create(AOwner); SetItemClass(AItemClass); end; procedure TListItems.DefineProperties(Filer: TFiler); function WriteItems: Boolean; var I: Integer; Items: TListItems; begin Items := TListItems(Filer.Ancestor); if (Items = nil) then Result := Count > 0 else if (Items.Count <> Count) then Result := True else begin Result := False; for I := 0 to Count - 1 do begin Result := not Item[I].IsEqual(Items[I]); if Result then Break; end end; end; begin inherited DefineProperties(Filer); Filer.DefineBinaryProperty('Data', ReadData, WriteData, WriteItems); end; function TListItems.FindItem(ItemH: QListViewItemH): TListItem; var Temp: TCustomViewItem; begin Temp := FindViewItem(ItemH); if Temp is TListItem then Result := TListItem(Temp) else Result := nil; end; function TListItems.GetItem(Index: Integer): TListItem; begin Result := TListItem(inherited GetItem(Index)); end; function TListItems.GetItemsOwner: TCustomListView; begin Result := FOwner as TCustomListView; end; function TListItems.Insert(Index: Integer): TListItem; begin Result := AddItem(nil, Index); end; type PItemHeader = ^TItemHeader; TItemHeader = packed record Size, Count: Integer; Items: record end; end; PItemInfo = ^TItemInfo; TItemInfo = packed record ImageIndex: Integer; StateIndex: Integer; OverlayIndex: Integer; SubItemCount: Integer; Data: Pointer; Caption: string[255]; end; ShortStr = string[255]; PShortStr = ^ShortStr; procedure TListItems.ReadData(Stream: TStream); var I, J, Size, L, Len: Integer; ItemHeader: PItemHeader; ItemInfo: PItemInfo; PStr: PShortStr; PInt: PInteger; begin Clear; Stream.ReadBuffer(Size, SizeOf(Integer)); ItemHeader := AllocMem(Size); try Stream.ReadBuffer(ItemHeader^.Count, Size - SizeOf(Integer)); ItemInfo := @ItemHeader^.Items; PStr := nil; for I := 0 to ItemHeader^.Count - 1 do begin with Add do begin Caption := ItemInfo^.Caption; ImageIndex := ItemInfo^.ImageIndex; Data := ItemInfo^.Data; PStr := @ItemInfo^.Caption; Inc(Integer(PStr), Length(PStr^) + 1); Len := 0; for J := 0 to ItemInfo^.SubItemCount - 1 do begin SubItems.Add(PStr^); L := Length(PStr^); Inc(Len, L + 1); Inc(Integer(PStr), L + 1); end; end; Inc(Integer(ItemInfo), SizeOf(TItemInfo) - 255 + Length(ItemInfo.Caption) + Len); end; //read subitem images, if present. if PChar(PStr) - PChar(ItemHeader) < Size then begin PInt := Pointer(PStr); for I := 0 to Count - 1 do with Item[I] do if Assigned(FSubItems) then for J := 0 to SubItems.Count - 1 do begin SubItemImages[J] := PInt^; Inc(PInt); end; end; finally FreeMem(ItemHeader, Size); end; end; procedure TListItems.SetItem(Index: Integer; const Value: TListItem); begin inherited SetItem(Index, Value); end; procedure TListItems.SetItemClass(AListItemClass: TListItemClass); begin FListItemClass := AListItemClass; end; procedure TListItems.WriteData(Stream: TStream); var I, J, Size, L, Len: Integer; ItemHeader: PItemHeader; ItemInfo: PItemInfo; PStr: PShortStr; PInt: PInteger; function GetLength(const S: string): Integer; begin Result := Length(S); if Result > 255 then Result := 255; end; begin Size := SizeOf(TItemHeader); for I := 0 to Count - 1 do begin L := GetLength(Item[I].Caption) + 1; for J := 0 to Item[I].SubItems.Count - 1 do begin Inc(L, GetLength(Item[I].SubItems[J]) + 1); Inc(L, SizeOf(Integer)); end; Inc(Size, SizeOf(TItemInfo) - 255 + L); end; ItemHeader := AllocMem(Size); try ItemHeader^.Size := Size; ItemHeader^.Count := Count; ItemInfo := @ItemHeader^.Items; PStr := nil; for I := 0 to Count - 1 do begin with Item[I] do begin ItemInfo^.Caption := Caption; ItemInfo^.ImageIndex := ImageIndex; ItemInfo^.OverlayIndex := -1 {OverlayIndex}; ItemInfo^.StateIndex := -1 {StateIndex}; ItemInfo^.Data := Data; ItemInfo^.SubItemCount := SubItems.Count; PStr := @ItemInfo^.Caption; Inc(Integer(PStr), Length(ItemInfo^.Caption) + 1); Len := 0; for J := 0 to SubItems.Count - 1 do begin PStr^ := SubItems[J]; L := Length(PStr^); Inc(Len, L + 1); Inc(Integer(PStr), L + 1); end; end; Inc(Integer(ItemInfo), SizeOf(TItemInfo) - 255 + Length(ItemInfo^.Caption) + Len); end; //write SubItem images. PInt := Pointer(PStr); for I := 0 to Count - 1 do begin with Item[I] do for J := 0 to SubItems.Count - 1 do begin PInt^ := SubItemImages[J]; Inc(PInt); end; end; Stream.WriteBuffer(ItemHeader^, Size); finally FreeMem(ItemHeader, Size); end; end; { THeaderSection } destructor THeaderSection.Destroy; begin if not (csDestroying in Header.ComponentState) and Header.HandleAllocated then QHeader_removeLabel(Header.Handle, QHeader_mapToIndex(Header.Handle, Index)); inherited Destroy; end; procedure THeaderSection.AssignTo(Dest: TPersistent); begin inherited AssignTo(Dest); if Dest is THeaderSection then THeaderSection(Dest).Text := Text; end; {$IF not (defined(LINUX) and defined(VER140))} function THeaderSection.GetText: WideString; begin Result := FText; end; {$IFEND} procedure THeaderSection.SetText(const Value: WideString); begin if Text <> Value then begin FText := Value; if Header.HandleAllocated then QHeader_setLabel(Header.Handle, QHeader_mapToIndex(Header.Handle, Index), PWideString(@FText), CalcSize); end; end; procedure THeaderSection.SetWidthVal(const Value: Integer); begin FWidth := Value; if Header.HandleAllocated then QHeader_setLabel(Header.Handle, QHeader_mapToIndex(Header.Handle, Index), PWideString(@FText), CalcSize); end; { TTreeNode } constructor TTreeNode.Create(AOwner: TCustomViewItems; AParent: TCustomViewItem = nil; After: TCustomViewItem = nil); begin inherited Create(AOwner, AParent, After); FSelectedIndex := -1; end; destructor TTreeNode.Destroy; begin if ViewControlValid then begin if TreeView.FLastNode = Self then TreeView.FLastNode := TTreeNode(FPrevItem); if Assigned(TreeView.FOnDeletion) then TreeView.FOnDeletion(TreeView, Self); end; inherited Destroy; end; function TTreeNode.AlphaSort(Ascending: Boolean): Boolean; procedure UpdateNodes(ANode: TCustomViewItem); var TempNext: TCustomViewItem; TempPrev: TCustomViewItem; TempItem: QListViewItemH; begin if Assigned(Owner) then begin TempItem := QListViewItem_firstChild(ANode.Handle); if Assigned(TempItem) then begin TempPrev := Owner.FindItem(TempItem); if Assigned(TempPrev) then begin TempPrev.FPrevItem := nil; while Assigned(TempItem) do begin UpdateNodes(TempPrev); TempItem := QListViewItem_nextSibling(TempItem); if not Assigned(TempItem) then Break; TempNext := Owner.FindItem(TempItem); TempPrev.FNextItem := TempNext; if Assigned(TempNext) then TempNext.FPrevItem := TempPrev; TempPrev := TempNext; end; ANode.FLastChild := TempPrev; end; end; end; end; begin Result := HandleAllocated; if Result then begin QListViewItem_sortChildItems(Handle, 0, Ascending); UpdateNodes(Self); if ViewControlValid then ViewControl.UpdateControl; end; end; procedure TTreeNode.AssignTo(Dest: TPersistent); var Node: TTreeNode; begin inherited AssignTo(Dest); if Dest is TTreeNode then begin Node := TTreeNode(Dest); Node.Text := Text; Node.HasChildren := HasChildren; Node.SelectedIndex := SelectedIndex; end; end; procedure TTreeNode.Collapse(Recurse: Boolean); begin ExpandItem(False, Recurse); end; function TTreeNode.CompareCount(CompareMe: Integer): Boolean; var Count: integer; Node: TTreeNode; Begin Count := 0; Result := False; Node := GetFirstChild; while Node <> nil do begin Inc(Count); Node := Node.GetNextChild(Node); if Count > CompareMe then Exit; end; if Count = CompareMe then Result := True; end; procedure TTreeNode.Delete; begin if not Deleting then Free; end; procedure TTreeNode.DeleteChildren; var Node: TTreeNode; begin Node := getFirstChild; while Node <> nil do begin Node.Free; Node := getFirstChild; end; end; function TTreeNode.DoCanExpand(Expand: Boolean): Boolean; begin Result := False; if HasChildren then begin if Expand then Result := TreeView.CanExpand(Self) else Result := TreeView.CanCollapse(Self); end; end; function TTreeNode.EditText: Boolean; begin if ViewControlValid then begin Selected := True; ViewControl.EditItem; end; Result := Assigned(ViewControl.FEditor) and ViewControl.FEditor.FEditing; end; procedure TTreeNode.Expand(Recurse: Boolean); begin ExpandItem(True, Recurse); end; procedure TTreeNode.ExpandItem(Expand, Recurse: Boolean); var Node: TTreeNode; begin if Recurse then begin Node := Self; repeat Node.ExpandItem(Expand, False); Node := Node.GetNext; until (Node = nil) or (not Node.HasAsParent(Self)); end else Expanded := Expand; end; function TTreeNode.GetAbsoluteIndex: Integer; var Node: TTreeNode; begin Result := -1; Node := Self; while Node <> nil do begin Inc(Result); Node := Node.GetPrev; end; end; function TTreeNode.GetCount: Integer; var Node: TTreeNode; begin Result := 0; Node := GetFirstChild; while Node <> nil do begin Inc(Result); Node := Node.GetNextChild(Node); end; end; {$IF not (defined(LINUX) and defined(VER140))} function TTreeNode.GetSelected: Boolean; begin Result := inherited GetSelected; end; procedure TTreeNode.SetSelected(const Value: Boolean); begin inherited SetSelected(Value); end; function TTreeNode.GetExpandable: Boolean; begin Result := FExpandable; end; procedure TTreeNode.SetExpandable(const Value: Boolean); begin inherited SetExpandable(Value); end; function TTreeNode.GetCaption: WideString; begin Result := FText; end; procedure TTreeNode.SetCaption(const Value: WideString); begin inherited SetCaption(Value); end; {$IFEND} function TTreeNode.GetDropTarget: Boolean; begin if ViewControlValid then Result := TreeView.DropTarget = Self else Result := False; end; function TTreeNode.getFirstChild: TTreeNode; begin if HandleAllocated then Result := Owner.FindItem(QListViewItem_firstChild(Handle)) else Result := nil; end; function TTreeNode.GetIndex: Integer; var Node: TTreeNode; begin Result := -1; Node := Self; while Node <> nil do begin Inc(Result); Node := Node.GetPrevSibling; end; end; function TTreeNode.GetItem(Index: Integer): TTreeNode; begin Result := GetFirstChild; while Assigned(Result) and (Index > 0) do begin Result := GetNextChild(Result); Dec(Index); end; if Result = nil then TreeViewError(Format(SListIndexError,[Index])); end; function TTreeNode.GetLastChild: TTreeNode; begin if FLastChild is TTreeNode then Result := TTreeNode(FLastChild) else Result := nil; end; function TTreeNode.GetLevel: Integer; begin if HandleAllocated then Result := QListViewItem_Depth(Handle) else Result := -1; end; function TTreeNode.GetNext: TTreeNode; var ChildNodeID, ParentID: QListViewItemH; begin Result := nil; if HandleAllocated then begin ChildNodeID := QListViewItem_firstChild(Handle); if ChildNodeID = nil then ChildNodeID := QListViewItem_nextSibling(Handle); ParentID := Handle; while (ChildNodeID = nil) and (ParentID <> nil) do begin ParentID := QListViewItem_parent(ParentID); if ParentID = nil then Break; ChildNodeID := QListViewItem_nextSibling(ParentID); end; Result := TTreeNodes(FOwner).FindItem(ChildNodeID); end; end; function TTreeNode.GetNextChild(Value: TTreeNode): TTreeNode; begin if Value <> nil then Result := Value.GetNextSibling else Result := nil; end; function TTreeNode.getNextSibling: TTreeNode; begin if HandleAllocated then Result := Owner.FindItem(QListViewItem_nextSibling(Handle)) else Result := nil; end; function TTreeNode.GetNextVisible: TTreeNode; begin Result := GetNext; while Assigned(Result) and not Result.IsNodeVisible do Result := Result.GetNext; end; function TTreeNode.GetNodeOwner: TTreeNodes; begin Result := FOwner as TTreeNodes; end; function TTreeNode.GetParent: TTreeNode; begin Result := FParent as TTreeNode; end; function TTreeNode.GetPrev: TTreeNode; var Node: TTreeNode; begin Result := GetPrevSibling; if Result <> nil then begin Node := Result; repeat Result := Node; Node := Result.GetLastChild; until Node = nil; end else Result := Parent; end; function TTreeNode.GetPrevChild(Value: TTreeNode): TTreeNode; begin if Value <> nil then Result := Value.GetPrevSibling else Result := nil; end; function TTreeNode.getPrevSibling: TTreeNode; begin Result := nil; if Assigned(Owner) then Result := Owner.FindPrevSibling(Self); end; function TTreeNode.GetPrevVisible: TTreeNode; begin Result := GetPrev; while Assigned(Result) and not Result.IsNodeVisible do Result := Result.GetPrev; end; function TTreeNode.GetTreeView: TCustomTreeView; begin Result := FOwner.FOwner as TCustomTreeView; end; function TTreeNode.HasAsParent(Value: TTreeNode): Boolean; begin if Value <> nil then begin if Parent = nil then Result := False else if Parent = Value then Result := True else Result := Parent.HasAsParent(Value); end else Result := True; end; function TTreeNode.IndexOf(Value: TTreeNode): Integer; var Node: TTreeNode; begin Result := -1; Node := GetFirstChild; while Node <> nil do begin Inc(Result); if Node = Value then Break; Node := GetNextChild(Node); end; if Node = nil then Result := -1; end; procedure TTreeNode.ImageIndexChange(ColIndex: Integer; NewIndex: Integer); var Pixmap: QPixmapH; begin if HandleAllocated and ViewControlValid and Assigned(ViewControl.Images) then begin if Selected then begin Pixmap := ViewControl.Images.GetPixmap(SelectedIndex); if Assigned(Pixmap) then begin QListViewItem_setPixmap(Handle, 0, Pixmap); Exit; end; end; inherited ImageIndexChange(ColIndex, NewIndex); end; end; function TTreeNode.IsEqual(Node: TTreeNode): Boolean; begin Result := (Text = Node.Text) and (Data = Node.Data); end; function TTreeNode.IsNodeVisible: Boolean; var R: TRect; begin if HandleAllocated then begin QListView_itemRect(Owner.Owner.Handle, @R, Handle); Result := not ((R.Right = -1) and (R.Bottom = -1)); end else Result := False; end; procedure TTreeNode.MoveTo(Destination: TTreeNode; Mode: TNodeAttachMode); var OldOnChange: TTVChangedEvent; NextSib: TTreeNode; begin OldOnChange := TreeView.OnChange; TreeView.OnChange := nil; Owner.BeginUpdate; try if not Assigned(Destination) or (Assigned(Destination) and Destination.HasAsParent(Self)) and (Destination <> Self) then Exit; case Mode of naAdd: begin Parent := Destination.Parent; if not Assigned(Parent) then begin if ViewControlValid then begin QListView_insertItem(ViewControl.Handle, Handle); if Assigned(TreeView.FLastNode) then begin QListViewItem_moveItem(Handle, TreeView.FLastNode.Handle); if Assigned(FPrevItem) then FPrevItem.FNextItem := FNextItem; if Assigned(FNextItem) then FNextItem.FPrevItem := FPrevItem; FPrevItem := TreeView.FLastNode; TreeView.FLastNode.FNextItem := Self; end; FNextItem := nil; TreeView.FLastNode := Self; end; end; end; naAddFirst: begin Parent := Destination.Parent; if not Assigned(Parent) then begin if ViewControlValid then begin QListView_insertItem(ViewControl.Handle, Handle); NextSib := TreeView.Items.FindItem(QListView_firstChild(ViewControl.Handle)); end else NextSib := nil; end else NextSib := Parent.getFirstChild; if Assigned(NextSib) then begin QListViewItem_moveItem(Handle, NextSib.Handle); QListViewItem_moveItem(NextSib.Handle, Handle); if Assigned(FPrevItem) then FPrevItem.FNextItem := FNextItem; if Assigned(FNextItem) then FNextItem.FPrevItem := FPrevItem; FPrevItem := nil; FNextItem := NextSib; NextSib.FPrevItem := Self; end; end; naAddChild: Parent := Destination; naAddChildFirst: begin Parent := Destination; if Parent.FLastChild = Self then Parent.FLastChild := FPrevItem; if Assigned(FPrevItem) then FPrevItem.FNextItem := FNextItem; if Assigned(FNextItem) then FNextItem.FPrevItem := FPrevItem; FPrevItem := nil; FNextItem := Parent.getFirstChild; if Assigned(FNextItem) then begin FNextItem.FPrevItem := Self; QListViewItem_moveItem(Handle, FNextItem.Handle); QListViewItem_moveItem(FNextItem.Handle, Handle); end else Parent.FLastChild := Self; end; naInsert: begin Parent := Destination.Parent; if Assigned(FPrevItem) then FPrevItem.FNextItem := FNextItem; if Assigned(FNextItem) then FNextItem.FPrevItem := FPrevItem; FPrevItem := Destination.FPrevItem; FNextItem := Destination; FNextItem.FPrevItem := Self; if Assigned(FPrevItem) then FPrevItem.FNextItem := Self; if not Assigned(Parent) and ViewControlValid then QListView_insertItem(ViewControl.Handle, Handle); if Assigned(FNextItem) then begin QListViewItem_moveItem(Handle, FNextItem.Handle); QListViewItem_moveItem(FNextItem.Handle, Handle); end; end; end; if Assigned(Parent) then begin Parent.HasChildren := True; Parent.Expanded := True; end; finally TreeView.OnChange := OldOnChange; Owner.EndUpdate; end; end; procedure TTreeNode.ReadData(Stream: TStream; Info: PNodeInfo); var I, Size, ItemCount: Integer; PStr: PShortStr; PInt: PInteger; begin Stream.ReadBuffer(Size, SizeOf(Size)); Stream.ReadBuffer(Info^, Size); Text := Info^.Text; ImageIndex := Info^.ImageIndex; SelectedIndex := Info^.SelectedIndex; Data := Info^.Data; ItemCount := Info^.Count; PStr := @Info^.Text; Inc(Integer(PStr), Length(PStr^) + 1); for I := 0 to Info^.SubItemCount - 1 do begin SubItems.Add(PStr^); Integer(PStr) := Integer(PStr) + (Length(PStr^) + 1); end; if (Size - (Integer(@PStr^[0]) - Integer(Info))) <> 0 then begin PInt := Pointer(PStr); for I := 0 to SubItems.Count - 1 do begin SubItemImages[I] := PInt^; Inc(PInt); end; end; for I := 0 to ItemCount - 1 do Owner.AddChild(Self, '').ReadData(Stream, Info); end; procedure TTreeNode.SetItem(Index: Integer; const Value: TTreeNode); begin Item[Index].Assign(Value); end; procedure TTreeNode.SetNodeParent(const Value: TTreeNode); begin if Parent <> Value then SetParent(Value); end; procedure TTreeNode.SetSelectedIndex(const Value: Integer); begin if FSelectedIndex <> Value then begin FSelectedIndex := Value; if Selected then ImageIndexChange(0, ImageIndex); end; end; procedure TTreeNode.WriteData(Stream: TStream; Info: PNodeInfo); function GetLength(const S: string): Integer; begin Result := Length(S); if Result > 255 then Result := 255; end; var I, Size, L, ItemCount: Integer; PStr: PShortStr; PInt: PInteger; begin L := GetLength(Text); for I := 0 to SubItems.Count - 1 do begin Inc(L, GetLength(SubItems[I]) + 1); Inc(L, SizeOf(Integer)); end; Size := SizeOf(TNodeInfo) + L - 255; Info^.Text := Text; Info^.ImageIndex := ImageIndex; Info^.SelectedIndex := SelectedIndex; Info^.Data := Data; ItemCount := Count; Info^.Count := ItemCount; Info^.SubItemCount := SubItems.Count; PStr := @Info^.Text; Inc(Integer(PStr), Length(Info^.Text) + 1); for I := 0 to SubItems.Count - 1 do begin PStr^ := SubItems[I]; Integer(PStr) := Integer(PStr) + (Length(PStr^) + 1); end; //write SubItem images. PInt := Pointer(PStr); for I := 0 to SubItems.Count - 1 do begin PInt^ := SubItemImages[I]; Inc(PInt); end; Stream.WriteBuffer(Size, SizeOf(Size)); Stream.WriteBuffer(Info^, Size); for I := 0 to ItemCount - 1 do Item[I].WriteData(Stream, Info); end; { TTreeNodes } function TTreeNodes.Add(Node: TTreeNode; const S: WideString): TTreeNode; begin Result := AddObject(Node, S, nil); end; function TTreeNodes.AddChild(Node: TTreeNode; const S: WideString): TTreeNode; begin Result := AddChildObject(Node, S, nil); end; function TTreeNodes.AddChildFirst(Node: TTreeNode; const S: WideString): TTreeNode; begin Result := AddChildObjectFirst(Node, S, nil); end; function TTreeNodes.AddChildObject(Node: TTreeNode; const S: WideString; Ptr: Pointer): TTreeNode; begin Result := InternalAddObject(Node, S, Ptr, taAdd); end; function TTreeNodes.AddChildObjectFirst(Node: TTreeNode; const S: WideString; Ptr: Pointer): TTreeNode; begin Result := InternalAddObject(Node, S, Ptr, taAddFirst); end; function TTreeNodes.AddFirst(Node: TTreeNode; const S: WideString): TTreeNode; begin Result := AddObjectFirst(Node, S, nil); end; function TTreeNodes.AddObject(Node: TTreeNode; const S: WideString; Ptr: Pointer): TTreeNode; begin if Assigned(Node) then Node := Node.Parent; Result := InternalAddObject(Node, S, Ptr, taAdd); end; function TTreeNodes.AddObjectFirst(Node: TTreeNode; const S: WideString; Ptr: Pointer): TTreeNode; begin if Assigned(Node) then Node := Node.Parent; Result := InternalAddObject(Node, S, Ptr, taAddFirst); end; procedure TTreeNodes.Assign(Dest: TPersistent); var TreeNodes: TTreeNodes; MemStream: TMemoryStream; begin if Dest is TTreeNodes then begin TreeNodes := TTreeNodes(Dest); Clear; MemStream := TMemoryStream.Create; try TreeNodes.WriteData(MemStream); MemStream.Position := 0; ReadData(MemStream); finally MemStream.Free; end; end else inherited Assign(Dest); end; procedure TTreeNodes.Clear; begin BeginUpdate; try FItems.Clear; if Owner.HandleAllocated then QListView_clear(Owner.Handle); finally EndUpdate; end; end; function TTreeNodes.CreateNode(ParentNode, AfterNode: TTreeNode): TTreeNode; begin Result := FNodeClass.Create(Self, ParentNode, AfterNode); end; procedure TTreeNodes.DefineProperties(Filer: TFiler); function WriteNodes: Boolean; var I: Integer; Nodes: TTreeNodes; begin Nodes := TTreeNodes(Filer.Ancestor); if Nodes = nil then Result := Count > 0 else if Nodes.Count <> Count then Result := True else begin Result := False; for I := 0 to Count - 1 do begin Result := not Item[I].IsEqual(Nodes[I]); if Result then Break; end end; end; begin inherited DefineProperties(Filer); Filer.DefineBinaryProperty('Data', ReadData, WriteData, WriteNodes); end; procedure TTreeNodes.Delete(Node: TTreeNode); begin if Assigned(Node) then Node.Delete; end; function TTreeNodes.FindItem(ItemH: QListViewItemH): TTreeNode; var Temp: TCustomViewItem; begin Temp := FindViewItem(ItemH); if Temp is TTreeNode then Result := TTreeNode(Temp) else Result := nil; end; function TTreeNodes.FindPrevSibling(ANode: TTreeNode): TTreeNode; var Node: TTreeNode; Node2: TTreeNode; begin Result := nil; if ANode.FPrevItem is TTreeNode then Result := TTreeNode(ANode.FPrevItem); if not Assigned(Result) then begin if Assigned(ANode.Parent) then Node := ANode.Parent.getFirstChild else Node := GetFirstNode; if Node <> ANode then begin while Assigned(Node) do begin Node2 := Node; Node := Node.getNextSibling; if Node = ANode then begin Result := Node2; Exit; end; end; end; end; end; function TTreeNodes.GetFirstNode: TTreeNode; begin if Owner.HandleAllocated then Result := FindItem(QListView_firstChild(Handle)) else if Count > 0 then Result := Item[0] else Result := nil; end; function TTreeNodes.GetItem(Index: Integer): TTreeNode; begin Result := TTreeNode(inherited GetItem(Index)); end; function TTreeNodes.GetNode(ItemH: QListViewItemH): TTreeNode; begin Result := FindItem(ItemH); end; function TTreeNodes.GetNodesOwner: TCustomTreeView; begin Result := FOwner as TCustomTreeView; end; function TTreeNodes.Insert(Node: TTreeNode; const S: WideString): TTreeNode; begin Result := InternalAddObject(Node, S, nil, taInsert); end; function TTreeNodes.InsertObject(Node: TTreeNode; const S: WideString; Ptr: Pointer): TTreeNode; begin if Node <> nil then Node := Node.Parent; Result := InternalAddObject(Node, S, Ptr, taInsert); end; function TTreeNodes.InternalAddObject(Node: TTreeNode; const S: WideString; Ptr: Pointer; AddMode: TAddMode): TTreeNode; var ParentNode, AfterNode: TTreeNode; begin Result := nil; ParentNode := Node; AfterNode := nil; try case AddMode of taAdd: if Assigned(ParentNode) then AfterNode := ParentNode.GetLastChild else if Assigned(Owner) then AfterNode := Owner.FLastNode; taInsert: begin if Assigned(Node) then ParentNode := Node.Parent else ParentNode := nil; if Assigned(Node) then AfterNode := Node.getPrevSibling; end; end; Result := CreateNode(ParentNode, AfterNode); FItems.Add(Result); if (AddMode = taAdd) then if not Assigned(Result.Parent) and Assigned(Owner) then Owner.FLastNode := Result else if Assigned(Result.Parent) then Result.Parent.FLastChild := Result; if Assigned(Result.Parent) then begin if not Assigned(Result.Parent.FLastChild) then Result.Parent.FLastChild := Result; Result.Parent.HasChildren := True; end; Result.Data := Ptr; Result.Text := S; if Assigned(Owner) and Owner.Visible and (FUpdateCount = 0) then if not Assigned(Result.Parent) or (Assigned(Result.Parent) and Result.Parent.Expanded) then Result.MakeVisible(False); if Assigned(Owner.FOnInsert) then Owner.FOnInsert(Owner, Result); except Result.Free; raise; end; end; procedure TTreeNodes.ReadData(Stream: TStream); var I, Count: Integer; NodeInfo: TNodeInfo; begin if Owner.HandleAllocated then BeginUpdate; try Clear; Stream.ReadBuffer(Count, SizeOf(Count)); for I := 0 to Count - 1 do Add(nil, '').ReadData(Stream, @NodeInfo); finally if Owner.HandleAllocated then EndUpdate; end; end; procedure TTreeNodes.WriteData(Stream: TStream); var I: Integer; Node: TTreeNode; NodeInfo: TNodeInfo; begin I := 0; Node := GetFirstNode; while Node <> nil do begin Inc(I); Node := Node.GetNextSibling; end; Stream.WriteBuffer(I, SizeOf(I)); Node := GetFirstNode; while Node <> nil do begin Node.WriteData(Stream, @NodeInfo); Node := Node.GetNextSibling; end; Stream.Position := 0; end; procedure TTreeNodes.SetNodeClass(NewNodeClass: TTreeNodeClass); begin FNodeClass := NewNodeClass; end; { TListItem } destructor TListItem.Destroy; begin if ViewControlValid and Assigned(ListView.FOnDeletion) then ListView.FOnDeletion(ListView, Self); inherited Destroy; end; function TListItem.IsEqual(Item: TListItem): Boolean; begin Result := (Caption = Item.Caption) and (Data = Item.Data); end; {$IF not (defined(LINUX) and defined(VER140))} function TListItem.GetCaption: WideString; begin Result := FText; end; procedure TListItem.SetCaption(Value: WideString); begin inherited SetCaption(Value); end; {$IFEND} function TListItem.GetListView: TCustomListView; begin Result := Owner.FOwner as TCustomListView; end; function TListItem.GetOwnerlist: TListItems; begin Result := FOwner as TListItems; end; { TCustomSpinEdit } constructor TCustomSpinEdit.Create(AOwner: TComponent); begin inherited Create(AOwner); TabStop := True; Palette.ColorRole := crBase; Palette.TextColorRole := crText; Color := clBase; Height := 23; InputKeys := [ikArrows]; end; procedure TCustomSpinEdit.StepUp; begin QSpinBox_stepUp(Handle); end; procedure TCustomSpinEdit.StepDown; begin QSpinBox_stepDown(Handle); end; function TCustomSpinEdit.GetHandle: QClxSpinBoxH; begin HandleNeeded; Result := QClxSpinBoxH(FHandle); end; function TCustomSpinEdit.EventFilter(Sender: QObjectH; Event: QEventH): Boolean; var R: TRect; P: TPoint; begin { Since Qt is not sending any messages for the up or down button when disabled we decided to only show any popup menu if a right click happens to the left of the buttons. } if (QEvent_type(Event) = QEventType_MouseButtonPress) and (QMouseEvent_button(QMouseEventH(Event)) = ButtonState_RightButton) then begin QWidget_geometry(QWidgetH(FUpButtonHandle), @R); P.X := QMouseEvent_x(QMouseEventH(Event)); P.Y := QMouseEvent_y(QMouseEventH(Event)); if Sender <> Handle then QWidget_mapToParent(QWidgetH(Sender), @P, @P); if P.X >= R.Left then begin Result := False; Exit; end; end; if (Sender = FEditHandle) or (Sender = FUpButtonHandle) or (Sender = FDownButtonHandle) then begin Result := inherited EventFilter(Sender, Event); { Internal Qt aggregated controls should return False (not handled) at this point but there are a few exceptions: 1. The right mouse press: This is handled in EventFilter depending on whether the PopupMenu was activated. 2. Enter and Leave messages should only come from the container. } if ((QEvent_type(Event) = QEventType_MouseButtonPress) and (QMouseEvent_button(QMouseEventH(Event)) = ButtonState_RightButton)) then Exit else if (QEvent_type(Event) = QEventType_Enter) or (QEvent_type(Event) = QEventType_Leave) then begin { When the focus leaves we force the button up. There is the very likely chance that if the OnClick event displays a modal form and the mouse click was on a button then it would keep incrementing the value } if (Sender = FUpButtonHandle) or (Sender = FDownButtonHandle) then QButton_setDown(QButtonH(Sender), False); Result := True; end else Result := False; end else Result := inherited EventFilter(Sender, Event); end; procedure TCustomSpinEdit.CreateWidget; var Method: TMethod; begin FHandle := QClxSpinBox_create(0, 100, 1, ParentWidget, nil); Hooks := QSpinBox_hook_create(FHandle); FEditHandle := QClxSpinBox_editor(Handle); FUpButtonHandle := QClxSpinBox_upButton(Handle); FDownButtonHandle := QClxSpinBox_downButton(Handle); FEditHook := QWidget_hook_create(FEditHandle); FButtonUpHook := QWidget_hook_create(FUpButtonHandle); FButtonDownHook := QWidget_hook_create(FDownButtonHandle); { How to handle Qt aggregated internal controls: 1. Hook each internal control to point to the MainEventFilter. ( You get events first so squash ones you don't want QT to process and let the others through. ) 2. Call QClxObjectMap_add for each control passing in the handle and a reference to the host control cast as an Integer. 3. Call QWidget_setMouseTracking for each control with the handle and True. ( Qt has this off by default. This allows us to get mouse move messages even when the mouse button is not pressed. ) } TEventFilterMethod(Method) := MainEventFilter; Qt_hook_hook_events(FEditHook, Method); Qt_hook_hook_events(FButtonUpHook, Method); Qt_hook_hook_events(FButtonDownHook, Method); QClxObjectMap_add(FEditHandle, Integer(Self)); QClxObjectMap_add(FUpButtonHandle, Integer(Self)); QClxObjectMap_add(FDownButtonHandle, Integer(Self)); QWidget_setMouseTracking(FEditHandle, True); QWidget_setMouseTracking(FUpButtonHandle, True); QWidget_setMouseTracking(FDownButtonHandle, True); end; procedure TCustomSpinEdit.WidgetDestroyed; begin QClxObjectMap_remove(FEditHandle); QClxObjectMap_remove(FUpButtonHandle); QClxObjectMap_remove(FDownButtonHandle); QWidget_hook_destroy(FEditHook); QWidget_hook_destroy(FButtonUpHook); QWidget_hook_destroy(FButtonDownHook); inherited WidgetDestroyed; end; function TCustomSpinEdit.GetButtonStyle: TSEButtonStyle; begin Result := TSEButtonStyle(QSpinBox_buttonSymbols(Handle)); end; function TCustomSpinEdit.GetCleanText: WideString; begin QSpinBox_cleanText(Handle, PWideString(@Result)); end; function TCustomSpinEdit.GetIncrement: Integer; begin Result := QSpinBox_lineStep(Handle); end; function TCustomSpinEdit.GetMax: Integer; begin Result := QSpinBox_maxValue(Handle); end; function TCustomSpinEdit.GetMin: Integer; begin Result := QSpinBox_minValue(Handle); end; function TCustomSpinEdit.GetPrefix: WideString; begin QSpinBox_prefix(Handle, PWideString(@Result)); end; function TCustomSpinEdit.GetRangeControl: QRangeControlH; begin Result := QSpinBox_to_QRangeControl(Handle); end; function TCustomSpinEdit.GetSuffix: WideString; begin QSpinBox_suffix(Handle, PWideString(@Result)); end; function TCustomSpinEdit.GetSpecialText: WideString; begin QSpinBox_specialValueText(Handle, PWideString(@Result)); end; procedure TCustomSpinEdit.Change(AValue: Integer); begin if Assigned(FOnChanged) then FOnChanged(Self, AValue); end; function TCustomSpinEdit.GetText: TCaption; begin QSpinBox_text(Handle, PWideString(@Result)); end; procedure TCustomSpinEdit.InitWidget; begin inherited InitWidget; SetRange(Min, Max); end; procedure TCustomSpinEdit.Loaded; begin inherited Loaded; SetRange(FMin, FMax); end; procedure TCustomSpinEdit.PaletteChanged(Sender: TObject); begin inherited; QWidget_setPalette(FEditHandle, (Sender as TPalette).Handle, True); end; function TCustomSpinEdit.GetWrap: Boolean; begin Result := QSpinBox_wrapping(Handle); end; procedure TCustomSpinEdit.SetMin(AValue: Integer); begin if (csLoading in ComponentState) then SetRange(AValue, FMax) else SetRange(AValue, Max); end; procedure TCustomSpinEdit.SetMax(AValue: Integer); begin if (csLoading in ComponentState) then SetRange(FMin, AValue) else SetRange(Min, AValue); end; procedure TCustomSpinEdit.SetButtonStyle(AValue: TSEButtonStyle); begin QSpinBox_setButtonSymbols(Handle, QSpinBoxButtonSymbols(AValue)); end; procedure TCustomSpinEdit.SetIncrement(AValue: Integer); begin QSpinBox_setLineStep(Handle, AValue); end; procedure TCustomSpinEdit.SetPrefix(const AValue: WideString); begin QSpinBox_setPrefix(Handle, PWideString(@AValue)); end; procedure TCustomSpinEdit.SetRange(const AMin, AMax: Integer); begin FMin := AMin; FMax := AMax; if not HandleAllocated or (csLoading in ComponentState) then Exit; try CheckRange(AMin, AMax); except FMin := Min; FMax := Max; raise; end; QRangeControl_setRange(RangeControl, FMin, FMax); if Value < Min then Value := Min else if Value > Max then Value := Max; end; procedure TCustomSpinEdit.SetSuffix(const AValue: WideString); begin QSpinBox_setSuffix(Handle, PWideString(@AValue)); end; procedure TCustomSpinEdit.SetSpecialText(const AValue: WideString); begin QSpinBox_setSpecialValueText(Handle, PWideString(@AValue)); end; procedure TCustomSpinEdit.SetWrap(AValue: Boolean); begin QSpinBox_setWrapping(Handle, AValue); end; procedure TCustomSpinEdit.HookEvents; var Method: TMethod; begin inherited HookEvents; QSpinBox_valueChanged_Event(Method) := ValueChangedHook; QSpinBox_hook_hook_valueChanged(QSpinBox_hookH(Hooks), Method); end; procedure TCustomSpinEdit.ValueChangedHook(AValue: Integer); begin try Change(AValue); except Application.HandleException(Self); end; end; function TCustomSpinEdit.GetValue: Integer; begin Result := StrToIntDef(CleanText, Min); end; { wrapper for the default Mime Factory } type TDefaultFactory = class(TMimeSourceFactory) protected procedure CreateHandle; override; procedure DestroyWidget; override; end; var PrivateFactory: TMimeSourceFactory; type TMimeFactoryStrings = class(TStringList) private FOwner: TMimeSourceFactory; protected function Add(const S: string): Integer; override; procedure Delete(Index: Integer); override; procedure Put(Index: Integer; const S: string); override; procedure ResetFilePath; public constructor Create(AOwner: TMimeSourceFactory); procedure Insert(Index: Integer; const S: string); override; procedure Assign(Source: TPersistent); override; end; { global routines for the Default Factory } function DefaultMimeFactory: TMimeSourceFactory; begin if PrivateFactory = nil then PrivateFactory := TDefaultFactory.Create; Result := PrivateFactory; end; procedure SetDefaultMimeFactory(Value: TMimeSourceFactory); begin if Assigned(Value) then begin PrivateFactory := Value; QMimeSourceFactory_setDefaultFactory(Value.Handle); end; end; { TBrowserStrings } function TMimeFactoryStrings.Add(const S: string): Integer; var Temp: WideString; begin Result := inherited Add(S); if Assigned(FOwner) then begin Temp := S; QMimeSourceFactory_addFilePath(FOwner.Handle, PWideString(@Temp)); end; end; procedure TMimeFactoryStrings.Assign(Source: TPersistent); begin inherited Assign(Source); ResetFilePath; end; constructor TMimeFactoryStrings.Create(AOwner: TMimeSourceFactory); begin inherited Create; FOwner := AOwner; end; procedure TMimeFactoryStrings.Delete(Index: Integer); begin inherited Delete(Index); ResetFilePath; end; procedure TMimeFactoryStrings.Insert(Index: Integer; const S: string); begin inherited Insert(Index, S); ResetFilePath; end; procedure TMimeFactoryStrings.Put(Index: Integer; const S: string); begin inherited Put(Index, S); ResetFilePath; end; procedure TMimeFactoryStrings.ResetFilePath; var Temp: QStringListH; begin if Assigned(FOwner) then begin Temp := TStringsToQStringList(Self); try QMimeSourceFactory_setFilePath(FOwner.Handle, Temp); finally QStringList_destroy(Temp); end; end; end; procedure TCustomSpinEdit.SetValue(const AValue: Integer); begin QSpinBox_setValue(Handle, AValue); end; { TMimeSourceFactory } constructor TMimeSourceFactory.Create; begin inherited Create; FFilePath := TMimeFactoryStrings.Create(Self); end; destructor TMimeSourceFactory.Destroy; begin DestroyWidget; FFilePath.Free; inherited Destroy; end; type TMimeSourceFactory_datacallback = procedure (AbsoluteName: PWideString; var ResolvedData: QMimeSourceH) of object cdecl; procedure TMimeSourceFactory.CreateHandle; var Method: TMethod; begin FHandle := QClxMimeSourceFactory_create; TMimeSourceFactory_datacallback(Method) := DoGetDataHook; QClxMimeSourceFactory_setDataCallBack(QClxMimeSourceFactoryH(FHandle), Method); end; procedure TMimeSourceFactory.DoGetDataHook(AbsoluteName: PWideString; var ResolvedData: QMimeSourceH); begin try GetData(AbsoluteName^, ResolvedData); except Application.HandleException(Self); end; end; procedure TMimeSourceFactory.GetData(const AbsoluteName: string; var ResolvedData: QMimeSourceH); begin { stubbed for children } end; function TMimeSourceFactory.GetHandle: QMimeSourceFactoryH; begin HandleNeeded; Result := FHandle; end; function TMimeSourceFactory.HandleAllocated: Boolean; begin Result := FHandle <> nil; end; procedure TMimeSourceFactory.HandleNeeded; begin if not HandleAllocated then CreateHandle; end; procedure TMimeSourceFactory.SetFilePath(const Value: TStrings); begin FFilePath.Assign(Value); end; procedure TMimeSourceFactory.RegisterMimeType(const FileExt: WideString; const MimeType: string); begin QMimeSourceFactory_setExtensionType(Handle, PWideString(@FileExt), PChar(MimeType)); end; procedure TMimeSourceFactory.AddTextToFactory(const Name: WideString; const Data: string); begin QMimeSourceFactory_setText(Handle, PWideString(@Name), @Data); end; procedure TMimeSourceFactory.AddImageToFactory(const Name: WideString; Data: QImageH); begin QMimeSourceFactory_setImage(Handle, PWideString(@Name), Data); end; procedure TMimeSourceFactory.AddPixmapToFactory(const Name: WideString; Data: QPixmapH); begin QMimeSourceFactory_setPixmap(Handle, PWideString(@Name), Data); end; procedure TMimeSourceFactory.AddDataToFactory(const Name: WideString; Data: QMimeSourceH); begin QMimeSourceFactory_setData(Handle, PWideString(@Name), Data); end; procedure TMimeSourceFactory.DestroyWidget; begin QMimeSourceFactory_destroy(FHandle); end; function TMimeSourceFactory.GetMimeSource(const MimeType: WideString): QMimeSourceH; begin Result := QMimeSourceFactory_data(Handle, PWideString(@MimeType)); end; { TDefaultFactory } procedure TDefaultFactory.DestroyWidget; begin FHandle := nil; end; procedure TDefaultFactory.CreateHandle; begin FHandle := QMimeSourceFactory_defaultFactory; end; { TCustomTextViewer } procedure TCustomTextViewer.CopyToClipboard; begin QTextView_copy(Handle); end; constructor TCustomTextViewer.Create(AOwner: TComponent); begin inherited Create(AOwner); FBrush := TBrush.Create; FBrush.OnChange := PaperChanged; InputKeys := [ikArrows, ikNav]; Width := 200; Height := 150; FLinkColor := clBlue; FTextColor := clBlack; FTextFormat := tfAutoText; FUnderlineLink := True; Color := clWhite; BorderStyle := bsSunken3d; end; procedure TCustomTextViewer.CreateWidget; begin FHandle := QTextView_create(ParentWidget, PChar(Name)); Hooks := QTextView_hook_create(FHandle); end; destructor TCustomTextViewer.Destroy; begin FBrush.Free; inherited Destroy; end; function TCustomTextViewer.GetBrush: TBrush; var Temp: QBrushH; begin if HandleAllocated then begin Temp := QTextView_paper(Handle); if FBrush.Handle <> Temp then FBrush.Handle := Temp; end; Result := FBrush; end; function TCustomTextViewer.GetDocumentTitle: WideString; begin if HandleAllocated then QTextView_documentTitle(Handle, PWideString(@Result)) else Result := ''; end; function TCustomTextViewer.GetHandle: QTextViewH; begin HandleNeeded; Result := QTextViewH(FHandle); end; function TCustomTextViewer.GetIsTextSelected: Boolean; begin if HandleAllocated then Result := QTextView_hasSelectedText(Handle) else Result := False; end; function TCustomTextViewer.GetSelectedText: WideString; begin if HandleAllocated then QTextView_selectedText(Handle, PWideString(@Result)) else Result := ''; end; function TCustomTextViewer.GetDocumentText: WideString; begin if HandleAllocated then QTextView_text(Handle, PWideString(@Result)) else Result := ''; end; const cQtTextFormat: array [TTextFormat] of Qt.TextFormat = (TextFormat_PlainText, TextFormat_RichText, TextFormat_AutoText); procedure TCustomTextViewer.LoadFromFile(const AFileName: string); var Stream: TStream; begin if AFileName = '' then begin Text := ''; FFileName := ''; Exit; end; Stream := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite); try LoadFromStream(Stream); FFileName := AFileName; finally Stream.Free; end; end; procedure TCustomTextViewer.LoadFromStream(Stream: TStream); var Temp: string; begin if Stream.Size > 0 then begin Stream.Position := 0; SetLength(Temp, Stream.Size); Stream.Read(PChar(Temp)^, Length(Temp)); end else Temp := ''; Text := Temp; end; procedure TCustomTextViewer.SelectAll; begin if HandleAllocated then QTextView_selectAll(Handle); end; procedure TCustomTextViewer.SetBrush(const Value: TBrush); begin if FBrush <> Value then begin FBrush.Handle := Value.Handle; if HandleAllocated then QTextView_setPaper(Handle, FBrush.Handle); end; end; procedure TCustomTextViewer.SetLinkColor(const Value: TColor); begin if LinkColor <> Value then begin FLinkColor := Value; if HandleAllocated then begin QTextView_setLinkColor(Handle, QColor(FLinkColor)); UpdateViewableContents; end; end; end; procedure TCustomTextViewer.SetDocumentText(const Value: WideString); var PaperRecall: TBrushRecall; begin PaperRecall := TBrushRecall.Create(Paper); try if HandleAllocated then QTextView_setText(Handle, @Value); SubmitTextColor; finally PaperRecall.Free; end; end; procedure TCustomTextViewer.SetTextColor(const Value: TColor); begin if FTextColor <> Value then begin FTextColor := Value; SubmitTextColor; end; end; procedure TCustomTextViewer.SetTextFormat(const Value: TTextFormat); begin if TextFormat <> Value then begin FTextFormat := Value; if HandleAllocated then QTextView_setTextFormat(Handle, cQtTextFormat[FTextFormat]); end; end; procedure TCustomTextViewer.SetUnderlineLink(const Value: Boolean); begin if UnderlineLink <> Value then begin FUnderlineLink := Value; if HandleAllocated then begin QTextView_setLinkUnderline(Handle, FUnderlineLink); UpdateViewableContents; end; end; end; function TCustomTextViewer.GetFactory: TMimeSourceFactory; begin if FUseDefaultFactory then begin Result := DefaultMimeFactory; Exit; end; if FFactory = nil then Factory := TMimeSourceFactory.Create; Result := FFactory; end; procedure TCustomTextViewer.SetFactory(const Value: TMimeSourceFactory); begin if Value = nil then UseDefaultFactory := True else begin FFactory := Value; FUseDefaultFactory := False; QTextView_setMimeSourceFactory(Handle, FFactory.Handle); end; end; procedure TCustomTextViewer.SetDefaultFactory(const Value: Boolean); begin if not FUseDefaultFactory and Assigned(FFactory) then FreeAndNil(FFactory); FUseDefaultFactory := Value; QTextView_setMimeSourceFactory(Handle, DefaultMimeFactory.Handle); end; procedure TCustomTextViewer.WidgetDestroyed; begin QClxObjectMap_remove(FViewportHandle); QClxObjectMap_remove(FVScrollHandle); QClxObjectMap_remove(FHScrollHandle); if Assigned(FViewportHook) then begin QWidget_hook_destroy(FViewportHook); FViewportHook := nil; end; if Assigned(FVScrollHook) then begin QScrollbar_hook_destroy(FVScrollHook); FVScrollHook := nil; end; if Assigned(FHScrollHook) then begin QScrollbar_hook_destroy(FHScrollHook); FHScrollHook := nil; end; FViewportHandle := nil; inherited WidgetDestroyed; end; function TCustomTextViewer.ViewportHandle: QWidgetH; begin HandleNeeded; Result := FViewportHandle; end; function TCustomTextViewer.GetChildHandle: QWidgetH; begin Result := ViewportHandle; end; procedure TCustomTextViewer.InitWidget; var Method: TMethod; begin inherited InitWidget; FViewportHandle := QScrollView_viewport(QScrollViewH(FHandle)); FVScrollHandle := QScrollView_verticalScrollBar(Handle); FHScrollHandle := QScrollView_horizontalScrollBar(Handle); QClxObjectMap_add(FViewportHandle, Integer(Self)); QClxObjectMap_add(FVScrollHandle, Integer(Self)); QClxObjectMap_add(FHScrollHandle, Integer(Self)); TEventFilterMethod(Method) := MainEventFilter; FViewportHook := QWidget_hook_create(FViewportHandle); Qt_hook_hook_events(FViewportHook, Method); FVScrollHook := QScrollBar_hook_create(FVScrollHandle); Qt_hook_hook_events(FVScrollHook, Method); FHScrollHook := QScrollBar_hook_create(FHScrollHandle); Qt_hook_hook_events(FHScrollHook, Method); QWidget_setMouseTracking(FViewportHandle, True); QWidget_setAcceptDrops(FViewportHandle, True); SubmitTextColor; QTextView_setLinkColor(Handle, QColor(FLinkColor)); QTextView_setTextFormat(Handle, cQtTextFormat[FTextFormat]); QTextView_setLinkUnderline(Handle, FUnderlineLink); end; procedure TCustomTextViewer.PaperChanged(Sender: TObject); begin if HandleAllocated then begin QWidget_update(ViewportHandle); Repaint; end; end; procedure TCustomTextViewer.SubmitTextColor; var QC: QColorH; begin if HandleAllocated then begin QC := QColor_create(QColor(FTextColor)); try QColorGroup_setColor(QTextView_paperColorGroup(Handle), QColorGroupColorRole(crText), QC); UpdateViewableContents; finally QColor_destroy(QC); end; end; end; procedure TCustomTextViewer.SetFileName(const Value: TFileName); begin LoadFromFile(Value); end; procedure TCustomTextViewer.UpdateViewableContents; begin if HandleAllocated then begin QScrollView_updateContents(Handle, 0,0, QScrollView_visibleWidth(Handle), QScrollView_visibleHeight(Handle)); end; end; { TCustomTextBrowser } procedure TCustomTextBrowser.Backward; begin if HandleAllocated then QTextBrowser_backward(Handle); end; function TCustomTextBrowser.CanGoBackward: Boolean; begin Result := FBackwardAvailable; end; function TCustomTextBrowser.CanGoForward: Boolean; begin Result := FForwardAvailable; end; procedure TCustomTextBrowser.CreateWidget; begin FHandle := QTextBrowser_create(ParentWidget, nil); Hooks := QTextBrowser_hook_create(FHandle); end; procedure TCustomTextBrowser.Forward; begin if HandleAllocated then QTextBrowser_Forward(Handle); end; function TCustomTextBrowser.GetHandle: QTextBrowserH; begin HandleNeeded; Result := QTextBrowserH(FHandle); end; procedure TCustomTextBrowser.Home; begin if HandleAllocated then QTextBrowser_Home(Handle); end; procedure TCustomTextBrowser.HookBackwardAvailable(p1: Boolean); begin try FBackwardAvailable := p1; except Application.HandleException(Self); end; end; procedure TCustomTextBrowser.HookEvents; var Method: TMethod; begin inherited HookEvents; QTextBrowser_backwardAvailable_Event(Method) := HookBackwardAvailable; QTextBrowser_hook_hook_backwardAvailable(QTextBrowser_hookH(Hooks), Method); QTextBrowser_forwardAvailable_Event(Method) := HookForwardAvailable; QTextBrowser_hook_hook_forwardAvailable(QTextBrowser_hookH(Hooks), Method); end; procedure TCustomTextBrowser.HookForwardAvailable(p1: Boolean); begin try FForwardAvailable := p1; except Application.HandleException(Self); end; end; procedure TCustomTextBrowser.HookHighlightText(p1: PWideString); begin if Assigned(FRTBHighlightText) then try FRTBHighlightText(Self, p1^); except Application.HandleException(Self); end; end; procedure TCustomTextBrowser.HookTextChanged; begin if Assigned(FTextChanged) then try FTextChanged(Self); except Application.HandleException(Self); end; end; procedure TCustomTextBrowser.LoadFromFile(const AFileName: string); var WFileName: WideString; begin FFileName := AFileName; if HandleAllocated then begin if FFileName = '' then QTextView_setText(Handle, nil) else begin WFileName := AFileName; QTextBrowser_setSource(Handle, PWideString(@WFileName)); end; end; end; procedure TCustomTextBrowser.ScrollToAnchor(const AnchorName: WideString); begin if HandleAllocated then QTextBrowser_scrollToAnchor(Handle, PWideString(@AnchorName)); end; procedure TCustomTextBrowser.SetDocumentText(const Value: WideString); begin QTextBrowser_setText(Handle, PWideString(@Value), nil); SubmitTextColor; end; procedure TCustomTextBrowser.SetHighlightText(const Value: TRTBHighlightTextEvent); var Method: TMethod; begin FRTBHighlightText := Value; if Assigned(FRTBHighlightText) then QTextBrowser_highlighted_Event(Method) := HookHighlightText else Method := NullHook; QTextBrowser_hook_hook_highlighted(QTextBrowser_hookH(Hooks), Method); end; procedure TCustomTextBrowser.SetTextChanged(const Value: TNotifyEvent); var Method: TMethod; begin FTextChanged := Value; if Assigned(FTextChanged) then QTextBrowser_textChanged_Event(Method) := HookTextChanged else Method := NullHook; QTextBrowser_hook_hook_textChanged(QTextBrowser_hookH(Hooks), Method); end; procedure TCustomTextBrowser.WidgetDestroyed; begin QClxObjectMap_remove(FViewportHandle); FViewportHandle := nil; inherited WidgetDestroyed; end; { TCustomIconView } const cIVQtSelect: array [Boolean] of QIconViewSelectionMode = (QIconViewSelectionMode_Single, QIconViewSelectionMode_Extended); cIVQtResizeMode: array [TResizeMode] of QIconViewResizeMode = (QIconViewResizeMode_Fixed, QIconViewResizeMode_Adjust); cIVResizeMode: array [Boolean] of TResizeMode = (rmAdjust, rmFixed); cIVTextPos: array [Boolean] of TItemTextPos = (itpRight, itpBottom); cIVQtTextPos: array [TItemTextPos] of QIconViewItemTextPos = (QIconViewItemTextPos_Bottom, QIconViewItemTextPos_Right); cIVQtArrangement: array [TIconArrangement] of QIconViewArrangement = (QIconViewArrangement_TopToBottom, QIconViewArrangement_LeftToRight); constructor TCustomIconView.Create(AOwner: TComponent); begin inherited Create(AOwner); FIconViewItems := TIconViewItems.Create(Self); FIconOptions := TIconOptions.Create(Self); FImageChanges := TChangeLink.Create; FImageChanges.OnChange := OnImageChanges; FItemsMovable := True; FResizeMode := rmAdjust; FShowToolTips := True; FSpacing := 5; FSortDirection := sdAscending; ParentColor := False; Width := 121; Height := 97; TabStop := True; InputKeys := [ikArrows, ikReturns, ikNav]; BorderStyle := bsSunken3d; end; procedure TCustomIconView.BeginAutoDrag; begin BeginDrag(False, Mouse.DragThreshold); end; procedure TCustomIconView.ChangeHook(item: QIconViewItemH; _type: TItemChange); var AItem: TIconViewItem; begin try AItem := Items.FindItem(item); if Assigned(AItem) then DoChange(AItem, _type); except Application.HandleException(Self); end; end; procedure TCustomIconView.ChangingHook(item: QIconViewItemH; _type: TItemChange; var Allow: Boolean); var AItem: TIconViewItem; begin try AItem := Items.FindItem(item); if Assigned(AItem) then DoChanging(AItem, _type, Allow); except Application.HandleException(Self); end; end; procedure TCustomIconView.ColorChanged; begin inherited ColorChanged; UpdateControl; end; procedure TCustomIconView.CreateWidget; begin FHandle := QIconView_create(ParentWidget, nil, WidgetFlags); Hooks := QIconView_hook_create(FHandle); FItemHooks := QClxIconViewHooks_create; FViewportHandle := QScrollView_viewport(QScrollViewH(FHandle)); QClxObjectMap_add(FViewportHandle, Integer(Self)); end; destructor TCustomIconView.Destroy; begin FIconViewItems.Free; FIconOptions.Free; FImageChanges.Free; inherited Destroy; end; procedure TCustomIconView.Clear; begin FIconViewItems.Clear; end; procedure TCustomIconView.DoChange(Item: TIconViewItem; Change: TItemChange); begin if Assigned(FOnItemChange) then FOnItemChange(Self, Item, Change); end; procedure TCustomIconView.DoChanging(Item: TIconViewItem; Change: TItemChange; var AllowChange: Boolean); begin if Assigned(FOnItemChanging) then FOnItemChanging(Self, Item, Change, AllowChange); end; procedure TCustomIconView.DoItemDoubleClicked(item: QIconViewItemH); begin if Assigned(FOnItemDoubleClick) then try FOnItemDoubleClick(Self, Items.FindItem(item)); except Application.HandleException(Self); end; end; procedure TCustomIconView.DoItemEnter(item: QIconViewItemH); begin if Assigned(FOnItemEnter) then try FOnItemEnter(Self, Items.FindItem(item)); except Application.HandleException(Self); end; end; procedure TCustomIconView.DoEdited(item: QIconViewItemH; p2: PWideString); var AItem: TIconViewItem; begin if Assigned(FOnEdited) then try AItem := Items.FindItem(item); if Assigned(AItem) then FOnEdited(Self, AItem, p2^); except Application.HandleException(Self); end; end; procedure TCustomIconView.DoItemClicked(item: QIconViewItemH); var AItem: TIconViewItem; begin if Assigned(FOnItemClicked) then try AItem := Items.FindItem(item); if Assigned(AItem) then FOnItemClicked(Self, AItem); except Application.HandleException(Self); end; end; procedure TCustomIconView.DoViewportEnter; begin if Assigned(FOnItemExitViewportEnter) then try FOnItemExitViewportEnter(Self); except Application.HandleException(Self); end; end; procedure TCustomIconView.EnsureItemVisible(AItem: TIconViewItem); begin if Assigned(AItem) and HandleAllocated then QIconView_ensureItemVisible(Handle, AItem.Handle); end; function TCustomIconView.FindItemByPoint(const Pt: TPoint): TIconViewItem; begin if HandleAllocated then Result := Items.FindItem(QIconView_findItem(Handle, PPoint(@Pt))) else Result := nil; end; function TCustomIconView.FindItemByText(const Str: WideString): TIconViewItem; var I: Integer; begin for I := 0 to Items.Count-1 do begin Result := Items[I]; if Result.Caption = Str then Exit; end; Result := nil; end; function TCustomIconView.FindVisibleItem(First: Boolean; const ARect: TRect): TIconViewItem; begin if HandleAllocated then begin if First then { find the first visible item } Result := Items.FindItem(QIconView_findFirstVisibleItem(Handle, @ARect)) else { find the last visible item } Result := Items.FindItem(QIconView_findLastVisibleItem(Handle, @ARect)); end else Result := nil; end; function TCustomIconView.GetHandle: QIconViewH; begin HandleNeeded; Result := QIconViewH(FHandle); end; function TCustomIconView.GetNextItem(StartItem: TIconViewItem; Direction: TSearchDirection; States: TItemStates): TIconViewItem; var AIndex: Integer; begin Result := nil; if HandleAllocated and Assigned(StartItem) then begin if Direction = sdAbove then Result := Items.FindItem(QIconViewItem_prevItem(StartItem.Handle)) else if Direction = sdBelow then Result := Items.FindItem(QIconViewItem_nextItem(StartItem.Handle)) else begin AIndex := StartItem.Index; while True do begin Inc(AIndex); if AIndex < Items.Count then begin Result := Items[AIndex]; if Result = StartItem then Result := nil; if Result = nil then Exit; if (Result.States * States <> []) then Exit; end else begin Result := nil; Exit; end; end; end; end; end; type TIconView_ChangingEvent = procedure(item: QIconViewItemH; _type: TItemChange; var Allow: Boolean) of object cdecl; TIconView_ChangeEvent = procedure(item: QIconViewItemH; _type: TItemChange) of object cdecl; TIconView_DestroyedEvent = procedure(item: QIconViewItemH) of object cdecl; TIconView_SelectedEvent = procedure(item: QIconViewItemH; Value: Boolean) of object cdecl; TIconView_PaintCellEvent = procedure(p: QPainterH; item: QIconViewItemH; cg: QColorGroupH; var stage: Integer) of object cdecl; TIconView_PaintFocusEvent = procedure(p: QPainterH; item: QIconViewItemH; cg: QColorGroupH; var stage: Integer) of object cdecl; procedure TCustomIconView.HookEvents; var Method: TMethod; begin inherited HookEvents; TEventFilterMethod(Method) := MainEventFilter; FViewportHooks := QWidget_hook_create(FViewportHandle); Qt_hook_hook_events(FViewportHooks, Method); TIconView_ChangingEvent(Method) := ChangingHook; QClxIconViewHooks_hook_changing(FItemHooks, Method); TIconView_ChangeEvent(Method) := ChangeHook; QClxIconViewHooks_hook_change(FItemHooks, Method); TIconView_DestroyedEvent(Method) := ItemDestroyedHook; QClxIconViewHooks_hook_destroyed(FItemHooks, Method); TIconView_SelectedEvent(Method) := SelectedHook; QClxIconViewHooks_hook_setSelected(FItemHooks, Method); TIconView_PaintCellEvent(Method) := PaintCellHook; QClxIconViewHooks_hook_PaintItem(FItemHooks, Method); TIconView_PaintFocusEvent(Method) := PaintFocusHook; QClxIconViewHooks_hook_PaintFocus(FItemHooks, Method); end; procedure TCustomIconView.ImageListChanged; begin FIconViewItems.UpdateImages; end; procedure TCustomIconView.ItemDestroyedHook(item: QIconViewItemH); var AItem: TIconViewItem; begin try AItem := Items.FindItem(item); if Assigned(Item) then begin QClxObjectMap_remove(item); AItem.FHandle := nil; if not AItem.FDestroying then AItem.Free; end; except Application.HandleException(Self); end; end; procedure TCustomIconView.InitWidget; begin inherited InitWidget; QIconView_setWordWrapIconText(Handle, IconOptions.WrapText); QIconView_setItemsMovable(Handle, FItemsMovable); QIconView_setSorting(Handle, FSort, FSortDirection = sdAscending); QIconView_setShowToolTips(Handle, FShowToolTips); QIconView_setAutoArrange(Handle, IconOptions.AutoArrange); QIconView_setResizeMode(Handle, cIVQtResizeMode[FResizeMode]); QIconView_setArrangement(Handle, cIVQtArrangement[IconOptions.Arrangement]); QIconView_setItemTextPos(Handle, cIVQtTextPos[FTextPosition]); QIconView_setSpacing(Handle, FSpacing); QIconView_setGridX(Handle, -1); QIconView_setGridY(Handle, -1); QIconView_setSelectionMode(Handle, cIVQtSelect[FMultiSelect]); QWidget_setMouseTracking(Handle, True); QWidget_setAcceptDrops(Handle, True); QWidget_setMouseTracking(FViewportHandle, True); QWidget_setAcceptDrops(FViewportHandle, True); end; procedure TCustomIconView.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (AComponent = FImages) then begin if (Operation = opRemove) then FImages := nil; ImageListChanged; end; end; procedure TCustomIconView.OnImageChanges(Sender: TObject); begin ImageListChanged; end; procedure TCustomIconView.PaintCellHook(p: QPainterH; item: QIconViewItemH; cg: QColorGroupH; var stage: Integer); begin try stage := DrawStage_DefaultDraw; except Application.HandleException(Self); end; end; procedure TCustomIconView.PaintFocusHook(p: QPainterH; item: QIconViewItemH; cg: QColorGroupH; var stage: Integer); begin try stage := DrawStage_DefaultDraw; except Application.HandleException(Self); end; end; procedure TCustomIconView.RepaintItem(AItem: TIconViewItem); begin if Assigned(AItem) and HandleAllocated then QIconView_repaintItem(Handle, AItem.Handle); end; procedure TCustomIconView.SelectAll(Select: Boolean); begin if HandleAllocated then QIconView_selectAll(Handle, Select); end; procedure TCustomIconView.SelectedHook(item: QIconViewItemH; Value: Boolean); const cIncSelCount: array [Boolean] of Integer = (-1, 1); var AItem: TIconViewItem; begin try Inc(FSelCount, cIncSelCount[Value]); if FSelCount < 0 then FSelCount := 0; AItem := Items.FindItem(item); if FSelCount > 0 then begin if (FSelected = AItem) and Value then Dec(FSelCount) else FSelected := AItem; end else FSelected := nil; if Assigned(AItem) then begin if Value then AItem.FStates := [isSelected, isFocused] else AItem.FStates := [isNone]; if Assigned(FOnSelectItem) then FOnSelectItem(Self, AItem, AItem.Selected); end; except Application.HandleException(Self); end; end; procedure TCustomIconView.SetIconOptions(const Value: TIconOptions); begin if (FIconOptions <> Value) and Assigned(Value) then begin FIconOptions.Arrangement := Value.Arrangement; FIconOptions.AutoArrange := Value.AutoArrange; FIconOptions.WrapText := Value.WrapText; end; end; procedure TCustomIconView.SetIconViewItems(const Value: TIconViewItems); begin if FIconViewItems <> Value then FIconViewItems.Assign(Value); end; procedure TCustomIconView.SetImages(const Value: TCustomImageList); begin if Value <> FImages then begin if Assigned(FImages) then FImages.UnRegisterChanges(FImageChanges); FImages := Value; if Assigned(FImages) then FImages.RegisterChanges(FImageChanges); ImageListChanged; end; end; procedure TCustomIconView.SetItemsMovable(const Value: Boolean); begin if FItemsMovable <> Value then begin FItemsMovable := Value; if HandleAllocated then QIconView_setItemsMovable(Handle, FItemsMovable); end; end; procedure TCustomIconView.SetMultiSelect(const Value: Boolean); begin if (FMultiSelect <> Value) then begin FMultiSelect := Value; if HandleAllocated then begin if not Value then QIconView_clearSelection(Handle); QIconView_setSelectionMode(Handle, cIVQtSelect[FMultiSelect]); end; end; end; procedure TCustomIconView.SetOnItemClicked(const Value: TIVItemClickEvent); var Method: TMethod; begin FOnItemClicked := Value; if Assigned(FOnItemClicked) then QIconView_clicked_Event(Method) := DoItemClicked else Method := NullHook; QIconView_hook_hook_clicked(QIconView_hookH(Hooks), Method); end; procedure TCustomIconView.SetOnItemDoubleClick(const Value: TIVItemDoubleClickEvent); var Method: TMethod; begin FOnItemDoubleClick := Value; if Assigned(FOnItemDoubleClick) then QIconView_doubleClicked_Event(Method) := DoItemDoubleClicked else Method := NullHook; QIconView_hook_hook_doubleClicked(QIconView_hookH(Hooks), Method); end; procedure TCustomIconView.SetOnItemEnter(const Value: TIVItemEnterEvent); var Method: TMethod; begin FOnItemEnter := Value; if Assigned(FOnItemEnter) then QIconView_onItem_Event(Method) := DoItemEnter else Method := NullHook; QIconView_hook_hook_onItem(QIconView_hookH(Hooks), Method); end; procedure TCustomIconView.SetOnItemExitViewportEnter(const Value: TIVItemExitViewportEnterEvent); var Method: TMethod; begin FOnItemExitViewportEnter := Value; if Assigned(FOnItemExitViewportEnter) then QIconView_onViewport_Event(Method) := DoViewportEnter else Method := NullHook; QIconView_hook_hook_onItem(QIconView_hookH(Hooks), Method); end; procedure TCustomIconView.SetOnEdited(const Value: TIVEditedEvent); var Method: TMethod; begin FOnEdited := Value; if Assigned(FOnEdited) then QIconView_itemRenamed_Event(Method) := DoEdited else Method := NullHook; QIconView_hook_hook_itemRenamed(QIconView_hookH(Hooks), Method); end; procedure TCustomIconView.SetResizeMode(const Value: TResizeMode); begin if (FResizeMode <> Value) then begin FResizeMode := Value; if HandleAllocated then QIconView_setResizeMode(Handle, cIVQtResizeMode[FResizeMode]); end; end; procedure TCustomIconView.SetSelected(const Value: TIconViewItem); begin if not (csDestroying in ComponentState) then if Assigned(Value) then Value.Selected := True; FSelected := Value; end; procedure TCustomIconView.SetShowToolTips(const Value: Boolean); begin if (FShowToolTips <> Value) then begin FShowToolTips := Value; if HandleAllocated then QIconView_setShowToolTips(Handle, FShowToolTips); end; end; procedure TCustomIconView.SetSort(const Value: Boolean); begin if FSort <> Value then begin FSort := Value; if HandleAllocated then begin QIconView_setSorting(Handle, FSort, FSortDirection = sdAscending); if FSort then QIconView_sort(Handle, FSortDirection = sdAscending); end; end; end; procedure TCustomIconView.SetSortDirection(const Value: TSortDirection); begin if FSortDirection <> Value then begin FSortDirection := Value; if Sort then begin if HandleAllocated then QIconView_sort(Handle, FSortDirection = sdAscending); end else Sort := True; end; end; procedure TCustomIconView.SetSpacing(const Value: Integer); begin if (FSpacing <> Value) then begin FSpacing := Value; if HandleAllocated then QIconView_setSpacing(Handle, FSpacing); end; end; procedure TCustomIconView.SetTextPos(const Value: TItemTextPos); begin if (FTextPosition <> Value) then begin FTextPosition := Value; if HandleAllocated then QIconView_setItemTextPos(Handle, cIVQtTextPos[FTextPosition]); end; end; function TCustomIconView.ViewportHandle: QWidgetH; begin HandleNeeded; Result := FViewportHandle; end; procedure TCustomIconView.WidgetDestroyed; begin QClxIconViewHooks_hook_destroyed(FItemHooks, NullHook); QClxIconViewHooks_destroy(FItemHooks); FItemHooks := nil; QClxObjectMap_remove(FViewportHandle); FViewportHandle := nil; inherited WidgetDestroyed; end; procedure TCustomIconView.UpdateItems(FirstIndex, LastIndex: Integer); var I: Integer; begin if HandleAllocated then begin Items.BeginUpdate; try for I := FirstIndex to LastIndex do QIconViewItem_repaint(Items[I].Handle); finally Items.EndUpdate; end; end; end; procedure TCustomIconView.UpdateControl; begin if HandleAllocated then QIconView_updateContents(Handle); end; { TIconViewItems } constructor TIconViewItems.Create(AOwner: TCustomIconView); begin inherited Create; FOwner := AOwner; FItems := TObjectList.Create; SetItemClass(TIconViewItem); end; constructor TIconViewItems.Create(AOwner: TCustomIconView; AItemClass: TIconViewItemClass); begin inherited Create; FOwner := AOwner; FItems := TObjectList.Create; SetItemClass(AItemClass); end; destructor TIconViewItems.Destroy; begin FItems.Free; inherited Destroy; end; type PIconItemHeader = ^TIconItemHeader; TIconItemHeader = packed record Size: Integer; Count: Integer; Items: record end; end; PIconItemInfo = ^TIconItemInfo; TIconItemInfo = packed record ImageIndex: Integer; Caption: string[255]; end; function TIconViewItems.Add: TIconViewItem; begin BeginUpdate; try Result := TIconViewItem.Create(Self); FItems.Add(Result); finally EndUpdate; end; end; procedure TIconViewItems.BeginUpdate; begin if FUpdateCount = 0 then SetUpdateState(True); Inc(FUpdateCount); end; procedure TIconViewItems.Clear; begin FItems.Clear; end; procedure TIconViewItems.DefineProperties(Filer: TFiler); function WriteItems: Boolean; var I: Integer; Items: TIconViewItems; begin Items := TIconViewItems(Filer.Ancestor); if (Items = nil) then Result := Count > 0 else if (Items.Count <> Count) then Result := True else begin Result := False; for I := 0 to Count - 1 do begin Result := not Item[I].IsEqual(Items[I]); if Result then Break; end end; end; begin inherited DefineProperties(Filer); Filer.DefineBinaryProperty('Data', ReadData, WriteData, WriteItems); end; procedure TIconViewItems.Delete(Index: Integer); begin FItems.Delete(Index); end; procedure TIconViewItems.EndUpdate; begin Dec(FUpdateCount); if FUpdateCount = 0 then SetUpdateState(False); end; procedure TIconViewItems.ReadData(Stream: TStream); var I, Size: Integer; ItemHeader: PIconItemHeader; ItemInfo: PIconItemInfo; begin Clear; Stream.ReadBuffer(Size, SizeOf(Integer)); ItemHeader := AllocMem(Size); try Stream.ReadBuffer(ItemHeader^.Count, Size - SizeOf(Integer)); ItemInfo := @ItemHeader^.Items; for I := 0 to ItemHeader^.Count - 1 do begin with Add do begin Caption := ItemInfo^.Caption; ImageIndex := ItemInfo^.ImageIndex; end; Inc(Integer(ItemInfo), SizeOf(TIconItemInfo) - 255 + Length(ItemInfo.Caption)); end; finally FreeMem(ItemHeader, Size); end; end; procedure TIconViewItems.WriteData(Stream: TStream); var I, Size, L: Integer; ItemHeader: PIconItemHeader; ItemInfo: PIconItemInfo; PStr: PShortStr; function GetLength(const S: string): Integer; begin Result := Length(S); if Result > 255 then Result := 255; end; begin Size := SizeOf(TIconItemHeader); for I := 0 to Count - 1 do begin L := GetLength(Item[I].Caption); Inc(Size, SizeOf(TIconItemInfo) - 255 + L); end; ItemHeader := AllocMem(Size); try ItemHeader^.Size := Size; ItemHeader^.Count := Count; ItemInfo := @ItemHeader^.Items; for I := 0 to Count - 1 do begin with Item[I] do begin ItemInfo^.Caption := Caption; ItemInfo^.ImageIndex := ImageIndex; PStr := @ItemInfo^.Caption; Inc(Integer(PStr), Length(ItemInfo^.Caption) + 1); end; Inc(Integer(ItemInfo), SizeOf(TIconItemInfo) - 255 + Length(ItemInfo^.Caption)); end; Stream.WriteBuffer(ItemHeader^, Size); finally FreeMem(ItemHeader, Size); end; end; function TIconViewItems.FindItem(ItemH: QIconViewItemH): TIconViewItem; var I: Integer; begin Result := nil; if not Assigned(ItemH) then Exit; Result := TIconViewItem(QClxObjectMap_find(ItemH)); if Result is TIconViewItem then Exit; for I := 0 to Count-1 do begin Result := Item[I]; if Result.Handle = ItemH then Exit; end; Result := nil; end; function TIconViewItems.GetCount: Integer; begin Result := FItems.Count; end; function TIconViewItems.GetItem(Index: Integer): TIconViewItem; begin Result := TIconViewItem(FItems[Index]); end; function TIconViewItems.IndexOf(Value: TIconViewItem): Integer; begin Result := FItems.IndexOf(Value); end; function TIconViewItems.Insert(Index: Integer): TIconViewItem; begin Result := Add; FItems.Move(Result.Index, Index); end; function TIconViewItems.IconViewHandle: QIconViewH; begin if Assigned(FOwner) then Result := FOwner.Handle else Result := nil; end; procedure TIconViewItems.SetItem(Index: Integer; AObject: TIconViewItem); begin FItems[Index] := AObject; end; procedure TIconViewItems.SetItemClass(AItemClass: TIconViewItemClass); begin FIconViewItemClass := AItemClass; end; procedure TIconViewItems.SetUpdateState(Updating: Boolean); begin if not (csDestroying in Owner.ComponentState) and Owner.HandleAllocated then begin if (FUpdateCount = 0) then begin QWidget_setUpdatesEnabled(IconViewHandle, not Updating); QWidget_setUpdatesEnabled(QScrollView_viewport(IconViewHandle), not Updating); if not Updating then QIconView_updateContents(IconViewHandle); end; end; end; procedure TIconViewItems.UpdateImages; var I: Integer; begin for I := 0 to Count-1 do Item[I].UpdateImage; end; { TIconViewItem } constructor TIconViewItem.Create(AOwner: TIconViewItems; AfterItem: TIconViewItem = nil); begin inherited Create; FOwner := AOwner; FImageIndex := -1; FAllowRename := True; FSelectable := True; States := [isNone]; CreateWidget(AfterItem); end; procedure TIconViewItem.CreateWidget(AfterItem: TIconViewItem); var AfterH: QIconViewItemH; ParentH: QIconViewH; begin if IconViewValid then begin IconView.HandleNeeded; if Assigned(AfterItem) then AfterH := AfterItem.Handle else AfterH := nil; ParentH := IconView.Handle; FHandle := QClxIconViewItem_create(ParentH, AfterH, IconView.FItemHooks); QClxObjectMap_add(FHandle, Integer(Self)); InitWidget; end; end; destructor TIconViewItem.Destroy; begin FDestroying := True; if Assigned(FOwner) then FOwner.FItems.Extract(Self); if IconViewValid then if IconView.FSelected = Self then IconView.FSelected := nil; DestroyWidget; inherited Destroy; end; procedure TIconViewItem.DestroyWidget; begin if HandleAllocated then QIconViewItem_destroy(FHandle); end; function TIconViewItem.HandleAllocated: Boolean; begin Result := FHandle <> nil; end; procedure TIconViewItem.InitWidget; begin QIconViewItem_setDragEnabled(Handle, False); QIconViewItem_setDropEnabled(Handle, True); QIconViewItem_setRenameEnabled(Handle, FAllowRename); QIconViewItem_setText(Handle, @FCaption); QIconViewItem_setSelectable(Handle, FSelectable); if Assigned(FOwner) and (FOwner.FUpdateCount = 0) then QIconView_ensureItemVisible(IconView.Handle, Handle); end; function TIconViewItem.IsEqual(AItem: TIconViewItem): Boolean; begin if Assigned(AItem) then Result := (Caption = AItem.Caption) and (ImageIndex = AItem.ImageIndex) else Result := False; end; function TIconViewItem.BoundingRect: TRect; begin if HandleAllocated then QIconViewItem_rect(Handle, @Result) else Result := Rect(-1, -1, -1, -1); end; function TIconViewItem.GetHandle: QIconViewItemH; begin Result := FHandle; end; function TIconViewItem.GetHeight: Integer; begin if HandleAllocated then Result := QIconViewItem_height(Handle) else Result := -1; end; function TIconViewItem.GetIconView: TCustomIconView; begin if FOwner.FOwner is TCustomIconView then Result := TCustomIconView(FOwner.FOwner) else Result := nil; end; function TIconViewItem.GetIndex; begin Result := FOwner.IndexOf(Self); end; function TIconViewItem.GetLeft: Integer; begin if HandleAllocated then Result := QIconViewItem_x(Handle) else Result := -1; end; function TIconViewItem.GetSelected: Boolean; begin if HandleAllocated then Result := QIconViewItem_isSelected(Handle) else Result := False; end; function TIconViewItem.GetTop: Integer; begin if HandleAllocated then Result := QIconViewItem_y(Handle) else Result := -1; end; function TIconViewItem.GetWidth: Integer; begin if HandleAllocated then Result := QIconViewItem_width(Handle) else Result := -1; end; function TIconViewItem.IconRect: TRect; begin if HandleAllocated then QIconViewItem_pixmapRect(Handle, @Result, False) else Result := Rect(-1, -1, -1, -1); end; function TIconViewItem.IconViewValid: Boolean; begin Result := Assigned(FOwner) and Assigned(FOwner.FOwner); end; procedure TIconViewItem.MakeVisible; begin if HandleAllocated then QIconView_ensureItemVisible(IconView.Handle, Handle); end; procedure TIconViewItem.Move(const Pt: TPoint); begin if HandleAllocated then begin QIconViewItem_move(Handle, @Pt); if IconViewValid then IconView.UpdateControl; end; end; procedure TIconViewItem.MoveBy(const Pt: TPoint); begin if HandleAllocated then begin QIconViewItem_moveBy(Handle, @Pt); if IconViewValid then IconView.UpdateControl; end; end; procedure TIconViewItem.Repaint; begin if HandleAllocated then QIconViewItem_repaint(Handle); end; procedure TIconViewItem.SetAllowRename(const Value: Boolean); begin if (FAllowRename <> Value) then begin FAllowRename := Value; if HandleAllocated then QIconViewItem_setRenameEnabled(Handle, FAllowRename); end; end; procedure TIconViewItem.SetCaption(const Value: WideString); begin FCaption := Value; if HandleAllocated then QIconViewItem_setText(Handle, @FCaption); end; procedure TIconViewItem.SetImageIndex(const Value: TImageIndex); begin if FImageIndex <> Value then begin FImageIndex := Value; UpdateImage; end; end; procedure TIconViewItem.SetSelectable(const Value: Boolean); begin if (FSelectable <> Value) then begin FSelectable := Value; if HandleAllocated then QIconViewItem_setSelectable(Handle, FSelectable); end; end; procedure TIconViewItem.SetSelected(const Value: Boolean); begin if (Selected <> Value) and HandleAllocated then QIconViewItem_setSelected(Handle, Value, True); end; procedure TIconViewItem.SetStates(const Value: TItemStates); begin if FStates <> Value then begin FStates := Value; if not (isNone in FStates) then begin Selected := True; FStates := FStates - [isNone]; end else begin Selected := False; FStates := [isNone]; end; end; end; function TIconViewItem.TextRect: TRect; begin if HandleAllocated then QIconViewItem_textRect(Handle, @Result, False) else Result := Rect(-1, -1, -1, -1); end; procedure TIconViewItem.UpdateImage; var Imgs: TCustomImageList; EmptyPix: QPixmapH; Pixmap: QPixmapH; begin if IconViewValid and FOwner.FOwner.HandleAllocated then begin EmptyPix := QPixmap_create; try Imgs := FOwner.FOwner.FImages; if Assigned(Imgs) then begin Pixmap := Imgs.GetPixmap(FImageIndex); if Assigned(Pixmap) then QIconViewItem_setPixmap(Handle, Pixmap) else QIconViewItem_setPixmap(Handle, EmptyPix); end else QIconViewItem_setPixmap(Handle, EmptyPix); finally QPixmap_destroy(EmptyPix); end; end; end; { TToolButton } const TBSpacing = 3; constructor TToolButton.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := [csCaptureMouse, csSetCaption, csClickEvents]; FWidth := 23; FHeight := 22; FImageIndex := -1; FDown := False; FGrouped := False; FStyle := tbsButton; FAutoSize := False; FAllowAllUp := False; FIndeterminate := False; FMarked := False; FWrap := False; end; procedure TToolButton.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var PopupPt: TPoint; begin if (Style in [tbsDropDown, tbsButton, tbsCheck]) and (Button = mbLeft) and IsEnabled then begin if Down and Grouped and not AllowAllUp then ControlState := ControlState - [csClicked]; FJustChecked := (Style = tbsCheck) and not Down; Down := True; if (Style = tbsDropDown) then begin if FMenuDropped then begin if Assigned(FDropDownMenu) then QWidget_hide(FDropDownMenu.Handle); FMenuDropped := False; Down := False; end else begin if PtInRect(DropDownRect, Types.Point(X, Y)) then begin PopupPt := ClientToScreen(Types.Point(0, Height)); FMenuDropped := True; try if Assigned(FDropDownMenu) then QPopupMenu_exec(FDropDownMenu.Handle, @PopupPt, 0); finally FMenuDropped := False; Down := False; if GetMouseGrabControl = Self then SetMouseGrabControl(nil); end; Exit; end; end; end; end; inherited MouseDown(Button, Shift, X, Y); end; procedure TToolButton.MouseMove(Shift: TShiftState; X, Y: Integer); begin inherited MouseMove(Shift, X, Y); if (Style = tbsDropDown) and MouseCapture then Down := (X >= 0) and (X < ClientWidth) and (Y >= 0) and (Y <= ClientHeight); end; procedure TToolButton.Click; begin if not (Style in [tbsSeparator, tbsDivider]) then inherited Click; end; procedure TToolButton.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if Operation = opRemove then begin if AComponent = DropDownMenu then DropDownMenu := nil; end; end; procedure TToolButton.ChangeBounds(ALeft, ATop, AWidth, AHeight: Integer); var ResizeWidth, ResizeHeight: Boolean; NeedsUpdate: Boolean; begin if ((AWidth <> Width) or (AHeight <> Height)) and (FToolBar <> nil) and (FToolBar.FResizeCount = 0) and not (csLoading in ComponentState) then begin NeedsUpdate := (Style in [tbsSeparator, tbsDivider]) and (AWidth <> Width) and not FToolBar.ShowCaptions; if Style = tbsDropDown then AWidth := FToolBar.ButtonWidth + AWidth - Width; ResizeWidth := not (Style in [tbsSeparator, tbsDivider]) and (AWidth <> FToolBar.ButtonWidth); ResizeHeight := AHeight <> FToolBar.ButtonHeight; if NeedsUpdate then inherited ChangeBounds(ALeft, ATop, AWidth, AHeight); if csDesigning in ComponentState then begin if ResizeWidth then FToolBar.ButtonWidth := AWidth; if ResizeHeight then FToolBar.ButtonHeight := AHeight; end; end else inherited ChangeBounds(ALeft, ATop, AWidth, AHeight); end; procedure TToolButton.Paint; begin DoPaint(Canvas); end; procedure TToolButton.DoPaint(Canvas: TCanvas); function CaptionRect(var R: TRect): TRect; begin { R -> image rect. Result -> Text rect. } R.Right := R.Right - DropDownWidth; Result := R; if FToolBar.HasImages then begin if FToolBar.List then begin R.Left := R.Left + TBSpacing; R.Right := R.Left + FToolBar.FImageWidth; R.Top := ((R.Bottom - R.Top) div 2) - (FToolBar.FImageHeight div 2); R.Bottom := R.Top + FToolBar.FImageHeight; Result.Left := R.Right; end else begin R.Left := ((R.Right - R.Left) div 2) - (FToolBar.FImageWidth div 2); R.Top := R.Top + TBSpacing; R.Right := R.Left + FToolBar.FImageWidth; R.Bottom := R.Top + FToolBar.FImageHeight; end; end; if FToolBar.List then Result.Top := Result.Top + TBSpacing else if FToolBar.HasImages then Result.Top := R.Bottom + TBSpacing else Result.Top := R.Top + TBSpacing; Result.Left := Result.Left + TBSpacing; Result.Right := Result.Right - TBSpacing; Result.Bottom := Result.Bottom - TBSpacing; end; procedure DrawDropDown; var R: TRect; MidX, MidY: Integer; Pts: array of TPoint; begin R := DropDownRect; if Down and not FMenuDropped then OffsetRect(R, 2, 2); Canvas.Pen.Color := clButtonText; Canvas.Brush.Color := clButtonText; MidX := R.Left + (R.Right - R.Left) div 2; MidY := R.Top + (R.Bottom - R.Top) div 2; if FMenuDropped then begin MidX := MidX + 1; MidY := MidY + 1; end; SetLength(Pts, 4); Pts[0] := Types.Point(MidX - 2, MidY - 1); Pts[1] := Types.Point(MidX + 2, MidY - 1); Pts[2] := Types.Point(MidX, MidY + 1); Pts[3] := Pts[0]; Canvas.Polygon(Pts); if FMenuDropped then begin if FToolBar.Flat then begin Dec(R.Top); Inc(R.Bottom); DrawEdge(Canvas, R, esNone, esLowered, ebRect); end else begin Dec(R.Top, 1); Inc(R.Bottom); DrawEdge(Canvas, R, esLowered, esLowered, ebRect); end end else if not FToolBar.Flat or (FToolBar.Flat and FMouseIn) then DrawEdge(Canvas, R, esRaised, esLowered, [ebLeft]); end; var R: TRect; CR: TRect; DrawFlags: Integer; TBColor: TColor; BrushColor, PenColor, PatternColor: TColor; BrushStyle: TBrushStyle; PenStyle: TPenStyle; Ind: Boolean; begin if FToolBar = nil then Exit; BrushStyle := Canvas.Brush.Style; PenStyle := Canvas.Pen.Style; BrushColor := Canvas.Brush.Color; PenColor := Canvas.Pen.Color; Ind := FIndeterminate and not Down; if Ind then PatternColor := clBtnHighlight else PatternColor := clHighlight; try if FToolBar.Flat then TBColor := FToolBar.Color else TBColor := clBtnFace; if Style in [tbsDropDown, tbsButton, tbsCheck] then begin DrawFlags := Integer(AlignmentFlags_ShowPrefix) or Integer(AlignmentFlags_AlignVCenter); if FToolBar.List then DrawFlags := DrawFlags or Integer(AlignmentFlags_AlignLeft) else DrawFlags := DrawFlags or Integer(AlignmentFlags_AlignHCenter); R := Types.Rect(0, 0, Width, Height); Canvas.Brush.Color := TBColor; if ((Down and (Style = tbsCheck)) or Ind or Marked) and IsEnabled then begin Canvas.TiledDraw(Rect(R.Left, R.Top, R.Right - DropDownWidth, R.Bottom), AllocPatternBitmap(clBtnFace, PatternColor)); Canvas.FillRect(Rect(R.Right - DropDownWidth, R.Top, R.Right, R.Bottom)); end else begin Canvas.Brush.Color := TBColor; Canvas.FillRect(R); end; if not FToolBar.Flat then begin DrawButtonFace(Canvas, R, 1, Down and not FMenuDropped, False, False, clNone); if Style = tbsDropDown then DrawDropDown; end else begin if not Down or FMenuDropped then begin if ((FMouseIn or FMenuDropped) and IsEnabled) or (csDesigning in ComponentState) then DrawEdge(Canvas, R, esNone, esRaised, [ebTop, ebLeft, ebRight, ebBottom]) else if not (Ind or Marked) or not IsEnabled then begin Canvas.Brush.Color := TBColor; Canvas.FillRect(R); end; end else if not FMenuDropped then DrawEdge(Canvas, R, esNone, esLowered, [ebTop, ebLeft, ebRight, ebBottom]); if Style = tbsDropDown then DrawDropDown; end; R := ClientRect; CR := CaptionRect(R); if Down and not FMenuDropped then begin OffsetRect(R, 2, 2); OffsetRect(CR, 2, 2); end; //draw image Canvas.Brush.Style := bsSolid; if (FImageIndex > -1) and FToolBar.HasImages then begin Canvas.Brush.Color := TBColor; if not (Ind or Marked) or not IsEnabled then Canvas.FillRect(R); if Assigned(FToolBar.HotImages) and (FMouseIn or FMenuDropped) and IsEnabled and (FImageIndex < FToolBar.HotImages.Count) then FToolbar.HotImages.Draw(Canvas, R.Left, R.Top, FImageIndex, itImage, not Ind) else if Assigned(FToolBar.DisabledImages) and not IsEnabled and (FImageIndex < FToolBar.DisabledImages.Count) then FToolbar.DisabledImages.Draw(Canvas, R.Left, R.Top, FImageIndex, itImage, not Ind) else if Assigned(FToolBar.Images) and (FImageIndex < FToolBar.Images.Count) then FToolBar.Images.Draw(Canvas, R.Left, R.Top, FImageIndex, itImage, IsEnabled and not Ind); end; { draw caption } if (FCaption <> '') and FToolBar.FShowCaptions then begin Canvas.Font := FToolBar.Font; if not IsEnabled then Canvas.Font.Color := clDisabledText; Canvas.TextRect(CR, CR.Left, CR.Top, FCaption, DrawFlags); end; end; if (Style = tbsSeparator) and FToolBar.Flat then begin R := Types.Rect(Width div 2, 3, Width, Height - 3); DrawEdge(Canvas, R, esRaised, esLowered, [ebLeft]); end; if Style = tbsDivider then begin R := Types.Rect(Width div 2, 1, Width, Height - 2); DrawEdge(Canvas, R, esRaised, esLowered, [ebLeft]); end; if (Style in [tbsSeparator, tbsDivider]) and (csDesigning in ComponentState) then begin Canvas.Pen.Style := psDot; Canvas.Pen.Color := clBlack; Canvas.Brush.Style := bsClear; Canvas.Rectangle(ClientRect); end; finally Canvas.Brush.Style := BrushStyle; Canvas.Pen.Style := PenStyle; Canvas.Brush.Color := BrushColor; Canvas.Pen.Color := PenColor; end; end; procedure TToolButton.SetAutoSize(Value: Boolean); begin if Value <> AutoSize then begin FAutoSize := Value; if not (csLoading in ComponentState) and (FToolBar <> nil) and FToolBar.ShowCaptions then begin FToolBar.ResizeButtons(Self); end; end; end; procedure TToolButton.SetName(const Value: TComponentName); var ChangeText: Boolean; begin ChangeText := Name = Caption; inherited SetName(Value); if ChangeText then Caption := Value; end; procedure TToolButton.SetParent(const Value: TWidgetControl); begin inherited SetParent(Value); if Value is TToolBar then FToolBar := TToolBar(Value); end; procedure TToolButton.SetToolBar(AToolBar: TToolBar); begin if FToolBar <> AToolBar then begin FToolBar := AToolBar; Parent := FToolBar; FToolBar.ResizeButtons(Self); end; end; procedure TToolButton.SetDown(Value: Boolean); begin if Value <> FDown then begin FDown := Value; Invalidate; if FToolBar <> nil then begin if Grouped and (Style = tbsCheck) and (FToolBar <> nil) then FToolBar.GroupChange(Self, gcDownState); end; end; end; procedure TToolButton.SetDropDownMenu(Value: TPopupMenu); begin if Value <> FDropDownMenu then begin FDropDownMenu := Value; if Value <> nil then Value.FreeNotification(Self); end; end; procedure TToolButton.SetGrouped(Value: Boolean); begin if FGrouped <> Value then begin FGrouped := Value; end; end; procedure TToolButton.SetImageIndex(Value: TImageIndex); begin if FImageIndex <> Value then begin FImageIndex := Value; Invalidate; end; end; procedure TToolButton.SetMarked(Value: Boolean); begin if FMarked <> Value then begin FMarked := Value; Invalidate; end; end; procedure TToolButton.SetIndeterminate(Value: Boolean); begin if FIndeterminate <> Value then begin if Value then SetDown(False); FIndeterminate := Value; Invalidate; end; end; procedure TToolButton.SetStyle(Value: TToolButtonStyle); var ResizeNeeded: Boolean; begin if FStyle <> Value then begin ResizeNeeded := (Value = tbsDropDown) or (Style in [tbsDropDown, tbsSeparator, tbsDivider]); FStyle := Value; if not (csLoading in ComponentState) and (FToolBar <> nil) then begin if FToolBar.ShowCaptions then begin // FToolBar.FButtonWidth := 0; // FToolBar.FButtonHeight := 0; FToolBar.ResizeButtons(nil); end; if ResizeNeeded then FToolBar.ResizeButtons(Self); end; // if Style in [tbsSeparator, tbsDivider] then // Wrap := True; if ResizeNeeded then FToolBar.Realign else Invalidate; end; end; procedure TToolButton.SetWrap(Value: Boolean); begin if FWrap <> Value then begin FWrap := Value; if FToolBar <> nil then FToolBar.Realign; end; end; procedure TToolButton.BeginUpdate; begin Inc(FUpdateCount); end; function TToolButton.DropDownWidth: Integer; begin if Style = tbsDropDown then Result := 14 else Result := 0; end; procedure TToolButton.EndUpdate; begin Dec(FUpdateCount); end; function TToolButton.EventFilter(Sender: QObjectH; Event: QEventH): Boolean; {$IFDEF MSWINDOWS} var P: PPoint; {$ENDIF} begin if QEvent_type(Event) = QEventType_MouseButtonRelease then begin if (Style in [tbsDropDown, tbsButton]) and (QMouseEvent_button(QMouseEventH(Event)) = ButtonState_LeftButton) and IsEnabled then begin {$IFDEF MSWINDOWS} if Style = tbsDropDown then begin P := QMouseEvent_pos(QMouseEventH(Event)); Result := PtInRect(DropDownRect, P^); if Result then Exit; end; {$ENDIF} Down := False; end; if (Style = tbsCheck) and not FJustChecked and (not Grouped or AllowAllUp) then Down := False; FJustChecked := False; end; Result := inherited EventFilter(Sender, Event); end; procedure TToolButton.InitWidget; begin QWidget_setFocusPolicy(Handle, QWidgetFocusPolicy_NoFocus); end; function TToolButton.IsEnabled: Boolean; begin Result := Enabled; if FToolBar <> nil then Result := Result and FToolBar.Enabled; end; function TToolButton.GetIndex: Integer; begin Result := -1; if FToolBar <> nil then Result := FToolBar.FControls.IndexOf(Self); end; function TToolButton.IsWidthStored: Boolean; begin Result := Style in [tbsSeparator, tbsDivider]; end; function TToolButton.CheckMenuDropDown: Boolean; begin Result := False; { Result := not (csDesigning in ComponentState) and ((DropdownMenu <> nil) and DropdownMenu.AutoPopup or (MenuItem <> nil)) and (FToolBar <> nil) and FToolBar.CheckMenuDropdown(Self);} end; function TToolButton.IsCheckedStored: Boolean; begin Result := (ActionLink = nil) or not TToolButtonActionLink(ActionLink).IsCheckedLinked; end; function TToolButton.IsImageIndexStored: Boolean; begin Result := (ActionLink = nil) or not TToolButtonActionLink(ActionLink).IsImageIndexLinked; end; procedure TToolButton.ActionChange(Sender: TObject; CheckDefaults: Boolean); begin inherited ActionChange(Sender, CheckDefaults); if Sender is TCustomAction then with TCustomAction(Sender) do begin if not CheckDefaults or (Self.Down = False) then Self.Down := Checked; if not CheckDefaults or (Self.ImageIndex = -1) then Self.ImageIndex := ImageIndex; end; end; function TToolButton.GetActionLinkClass: TControlActionLinkClass; begin Result := TToolButtonActionLink; end; procedure TToolButton.AssignTo(Dest: TPersistent); begin inherited AssignTo(Dest); if Dest is TCustomAction then with TCustomAction(Dest) do begin Checked := Self.Down; ImageIndex := Self.ImageIndex; end; end; procedure TToolButton.ValidateContainer(AComponent: TComponent); var W: Integer; begin inherited ValidateContainer(AComponent); { Update non-stored Width and Height if inserting into TToolBar } if (csLoading in ComponentState) and (AComponent is TToolBar) then begin if Style in [tbsDivider, tbsSeparator] then W := Width else W := TToolBar(AComponent).ButtonWidth; SetBounds(Left, Top, W, TToolBar(AComponent).ButtonHeight); end; end; function TToolButton.GetText: TCaption; begin Result := FCaption; end; procedure TToolButton.SetText(const Value: TCaption); begin if FCaption <> Value then begin FCaption := Value; if Assigned(FToolBar) then FToolBar.ResizeButtons(nil); Invalidate; end; end; procedure TToolButton.SetAllowAllUp(const Value: Boolean); begin if FAllowAllUp <> Value then begin FAllowAllUp := Value; if FToolBar <> nil then FToolBar.GroupChange(Self, gcAllowAllUp); end; end; procedure TToolButton.MouseEnter(AControl: TControl); begin inherited MouseEnter(AControl); FMouseIn := True; Paint; end; procedure TToolButton.MouseLeave(AControl: TControl); begin inherited MouseLeave(AControl); FMouseIn := False; Paint; end; function TToolButton.DropDownRect: TRect; begin Result := Types.Rect(Width - DropDownWidth, 1, Width, Height - 1); end; function TToolButton.WantKey(Key: Integer; Shift: TShiftState; const KeyText: WideString): Boolean; begin if IsAccel(Key, Caption) and (ssAlt in Shift) then begin Click; Result := True; end else Result := inherited WantKey(Key, Shift, KeyText); end; { TToolBar } function TBControlSort(Item1, Item2: Pointer): Integer; var C1, C2: TControl; begin Result := 0; C1 := TControl(Item1); C2 := TControl(Item2); if C1 = C2 then Exit; if C1.Top = C2.Top then begin if C1.Left <= C2.Left then Result := -1 else Result := 1 end else begin if C1.Top < C2.Top then Result := -1 else Result := 1; end; end; function TToolBar.ButtonCount: Integer; var I: Integer; begin Result := 0; for I := 0 to ControlCount - 1 do if (Controls[I] is TToolButton) then Inc(Result); end; procedure TToolBar.ControlsAligned; begin inherited ControlsAligned; FControls.Sort(@TBControlSort); DoResize; end; procedure TToolBar.ControlsListChanged(Control: TControl; Inserting: Boolean); begin inherited ControlsListChanged(Control, Inserting); if Inserting then begin if LastControl <> nil then begin Control.Left := LastControl.Left + LastControl.Width; Control.Top := LastControl.Top; end else begin Control.Left := ClientRect.Left; Control.Top := ClientRect.Top; end; Control.Height := FButtonHeight; if Control is TWidgetControl then TWidgetControl(Control).HandleNeeded; if (Control is TToolButton) and not (TToolButton(Control).Style in [tbsSeparator, tbsDivider]) and not TToolButton(Control).AutoSize then begin Inc(FResizeCount); try Control.Width := FButtonWidth; finally Dec(FResizeCount); end; end; Control.Align := alCustom; FControls.Add(Control); end else FControls.Remove(Control); Realign; if AutoSize then AdjustSize; end; constructor TToolBar.Create(AOwner: TComponent); begin inherited Create(AOwner); FControls := TList.Create; ControlStyle := [csAcceptsControls, csCaptureMouse, csClickEvents, csDoubleClicks, csMenuEvents, csSetCaption, csNoFocus]; FResizeCount := 0; Width := 150; Height := 29; Align := alTop; FButtonWidth := 23; FButtonHeight := 22; FBorderWidth := 0; FIndent := 1; FAutoSize := False; FList := False; FEdgeBorders := [ebTop]; FEdgeInner := esRaised; FEdgeOuter := esLowered; Wrapable := True; FImageChangeLink := TChangeLink.Create; FImageChangeLink.OnChange := ImageListChange; end; procedure TToolBar.AdjustClientRect(var Rect: TRect); begin Rect.Left := FIndent + FBorderWidth + EdgeSpacing(ebLeft); Rect.Right := Width - 2 - FBorderWidth + EdgeSpacing(ebRight); Rect.Top := 2 + FBorderWidth + EdgeSpacing(ebTop); Rect.Bottom := Height - 3 - FBorderWidth + EdgeSpacing(ebBottom); end; function TToolBar.GetControl(Index: Integer): TControl; begin Result := TControl(FControls[Index]); end; procedure TToolBar.Paint; begin inherited Paint; DoPaint(Canvas); end; procedure TToolBar.DoResize; begin if not AutoSize then Exit; AdjustSize; end; procedure TToolBar.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if Operation = opRemove then begin if AComponent = FImages then begin FImages := nil; Repaint; end; if AComponent = FDisabledImages then begin FDisabledImages := nil; Repaint; end; if AComponent = FHotImages then begin FHotImages := nil; Repaint; end; end; end; procedure TToolBar.SetAutoSize(const Value: Boolean); begin if FAutoSize <> Value then begin FAutoSize := Value; DoResize; end; end; procedure TToolBar.SetButtonHeight(const Value: Integer); var I: Integer; begin if FButtonHeight <> Value then begin Inc(FResizeCount); try ControlState := ControlState + [csAlignDisabled]; try FButtonHeight := Value; for I := 0 to ControlCount - 1 do Controls[I].Height := FButtonHeight; finally ControlState := ControlState - [csAlignDisabled]; Realign; end; finally Dec(FResizeCount); end; end; end; procedure TToolBar.InternalSetButtonWidth(const Value: Integer; RestrictSize: Boolean); var I: Integer; begin if RestrictSize and ShowCaptions then Exit; ControlState := ControlState + [csAlignDisabled]; Inc(FResizeCount); try FButtonWidth := Value; for I := 0 to ControlCount - 1 do if Controls[I] is TToolButton then with TToolButton(Controls[I]) do begin if not AutoSize and not (Style in [tbsSeparator, tbsDivider]) then Width := FButtonWidth + DropDownWidth else Width := Width + DropDownWidth; end; finally Dec(FResizeCount); ControlState := ControlState - [csAlignDisabled]; ReAlign; end; end; procedure TToolBar.SetButtonWidth(const Value: Integer); begin InternalSetButtonWidth(Value, True); end; procedure TToolBar.SetWrapable(const Value: Boolean); begin if FWrapable <> Value then begin FWrapable := Value; Realign; end; end; function TToolBar.LastControl: TControl; begin Result := nil; if ControlCount > 0 then Result := Controls[ControlCount - 1]; end; procedure TToolBar.Loaded; begin inherited Loaded; SetButtonWidth(FButtonWidth); end; procedure TToolBar.SetBorderWidth(const Value: TBorderWidth); begin if FBorderWidth <> Value then begin FBorderWidth := Value; Realign; end; end; procedure TToolBar.SetEdgeBorders(const Value: TEdgeBorders); begin FEdgeBorders := Value; DoResize; Invalidate; end; procedure TToolBar.SetEdgeInner(const Value: TEdgeStyle); begin FEdgeInner := Value; DoResize; Invalidate; end; procedure TToolBar.SetEdgeOuter(const Value: TEdgeStyle); begin FEdgeOuter := Value; DoResize; Invalidate; end; function TToolBar.EdgeSpacing(Edge: TEdgeBorder): Integer; begin Result := 0; if (Edge in FEdgeBorders) then begin if FEdgeInner in [esRaised, esLowered] then Inc(Result); if FEdgeOuter in [esRaised, esLowered] then Inc(Result); end; end; procedure TToolBar.AdjustSize; var NewHeight: Integer; begin if FAutoSize and (FControls.Count > 0) then begin NewHeight := 0; case Align of alTop, alBottom: begin if LastControl <> nil then NewHeight := LastControl.Top + LastControl.Height; NewHeight := NewHeight + FBorderWidth + EdgeSpacing(ebBottom); Height := NewHeight; end; alLeft, alRight: Width := FRightEdge + FBorderWidth + EdgeSpacing(ebLeft) + EdgeSpacing(ebRight); end; end; end; procedure TToolBar.SetIndent(const Value: Integer); begin if FIndent <> Value then begin FIndent := Value; DoResize; Realign; end; end; procedure TToolBar.SetFlat(const Value: Boolean); begin FFlat := Value; Invalidate; end; procedure TToolBar.SetShowCaptions(const Value: Boolean); begin if FShowCaptions <> Value then begin FShowCaptions := Value; FButtonHeight := 0; FButtonWidth := 0; ResizeButtons(nil); end; end; procedure TToolBar.SetDisabledImages(const Value: TCustomImageList); begin if FDisabledImages <> nil then FDisabledImages.UnRegisterChanges(FImageChangeLink); FDisabledImages := Value; if FDisabledImages <> nil then begin FDisabledImages.RegisterChanges(FImageChangeLink); FDisabledImages.FreeNotification(Self); end; ImageListChange(Value); end; procedure TToolBar.SetHotImages(const Value: TCustomImageList); begin if FHotImages <> nil then FHotImages.UnRegisterChanges(FImageChangeLink); FHotImages := Value; if FHotImages <> nil then begin FHotImages.RegisterChanges(FImageChangeLink); FHotImages.FreeNotification(Self); end; ImageListChange(Value); end; procedure TToolBar.SetImages(const Value: TCustomImageList); begin if FImages <> nil then FImages.UnRegisterChanges(FImageChangeLink); FImages := Value; if FImages <> nil then begin FImages.RegisterChanges(FImageChangeLink); FImages.FreeNotification(Self); end; ImageListChange(Value); end; procedure TToolBar.ImageListChange(Sender: TObject); begin FImageWidth := 0; FImageHeight := 0; if Assigned(FImages) then begin FImageWidth := FImages.Width; FImageHeight := FImages.Height; end else if Assigned(FHotImages) then begin FImageWidth := FHotImages.Width; FImageHeight := FHotImages.Height; end else if Assigned(FDisabledImages) then begin FImageWidth := FDisabledImages.Width; FImageHeight := FDisabledImages.Height; end; ResizeButtons(nil); Invalidate; end; procedure TToolBar.ResizeButtons(Button: TToolButton); var BtnIndex, I: Integer; NewWidth, NewHeight, AWidth, AHeight: Integer; ABtn: TToolButton; ASize: TSize; AImageList: TCustomImageList; begin Inc(FResizeCount); ControlState := ControlState + [csAlignDisabled]; ABtn := nil; AWidth := 0; try if Button <> nil then BtnIndex := FControls.IndexOf(Button) else BtnIndex := 0; if not ShowCaptions then begin NewWidth := ButtonWidth; //is this necessary?? NewHeight := ButtonHeight; end else begin NewWidth := 0; NewHeight := 0; end; for I := BtnIndex to ControlCount - 1 do begin if Controls[I] is TToolButton then begin ABtn := TToolButton(Controls[I]); if ABtn.Style in [tbsSeparator, tbsDivider] then Continue; AWidth := 23; AHeight := 22; if not FShowCaptions and HasImages then begin if Assigned(Images) then AImageList := Images else if Assigned(DisabledImages) then AImageList := DisabledImages else if Assigned(HotImages) then AImageList := HotImages else AImageList := nil; if AImageList <> nil then begin AWidth := AImageList.Width + (TBSpacing *2) + 1; AHeight := AImageList.Height + (TBSpacing *2) + 1; end; end; if (ABtn.Caption <> '') and (ABtn.Style in [tbsButton, tbsCheck, tbsDropDown]) and FShowCaptions then begin ASize := Canvas.TextExtent(ABtn.Caption, Integer(AlignmentFlags_ShowPrefix) or Integer(AlignmentFlags_AlignCenter)); AWidth := ASize.cx + (TBSpacing * 3); AHeight := ASize.cy + (TBSpacing * 2) + 1; if HasImages then begin if FList then AWidth := AWidth + TBSpacing + FImageWidth else AHeight := AHeight + TBSpacing + FImageHeight; if AHeight < (FImageHeight + (TBSpacing * 2) + 1) then AHeight := FImageHeight + (TBSpacing *2) + 1; end; end; if AHeight > NewHeight then NewHeight := AHeight; if AWidth > NewWidth then NewWidth := AWidth; if ABtn.AutoSize then ABtn.Width := AWidth; end; if ABtn <> nil then if ABtn.AutoSize then ABtn.Width := AWidth + ABtn.DropDownWidth // else if not ShowCaptions then // ABtn.Width := ButtonWidth + ABtn.DropDownWidth; end; finally Dec(FResizeCount); ControlState := ControlState - [csAlignDisabled]; end; if NewHeight = 0 then ButtonHeight := 22 else ButtonHeight := NewHeight; if NewWidth = 0 then InternalSetButtonWidth(23, False) else InternalSetButtonWidth(NewWidth, False); AdjustSize; Invalidate; end; procedure TToolBar.SetList(const Value: Boolean); begin FList := Value; ResizeButtons(nil); end; destructor TToolBar.Destroy; begin FControls.Free; FImageChangeLink.Free; inherited Destroy; end; procedure TToolBar.GroupChange(Requestor: TToolButton; Reason: TGroupChangeReason); procedure ApplyToGroup(Index: Integer; Dir: SmallInt; Reason: TGroupChangeReason); var Control: TControl; begin Inc(Index, Dir); while (Index >= 0) and (Index < ControlCount) do begin Control := Controls[Index]; if (Control is TToolButton) and TToolButton(Control).Grouped then case Reason of gcAllowAllUp: TToolButton(Control).FAllowAllUp := Requestor.AllowAllUp; gcDownState: begin TToolButton(Control).FDown := False; Control.Invalidate; end; end else Break; Inc(Index, Dir); end; end; begin ApplyToGroup(FControls.IndexOf(Requestor), -1, Reason); ApplyToGroup(FControls.IndexOf(Requestor), 1, Reason); end; function TToolBar.CustomAlignInsertBefore(C1, C2: TControl): Boolean; begin Result := False; case Align of alTop, alBottom, alNone, alClient: if C1.Top = C2.Top then Result := C1.Left < C2.Left else Result := C1.Top < C2.Top; alLeft, alRight: if C1.Left = C2.Left then Result := C1.Top < C2.Top else Result := C1.Left < C2.Left; end; FRightEdge := 0; end; procedure TToolBar.CustomAlignPosition(Control: TControl; var NewLeft, NewTop, NewWidth, NewHeight: Integer; var AlignRect: TRect); begin if Wrapable then begin case Align of alTop, alBottom, alNone, alClient: if (((AlignRect.Left + Control.Width) > AlignRect.Right) and (AlignRect.Left > ClientRect.Left)) then begin Inc(AlignRect.Top, NewHeight); NewLeft := ClientRect.Left; AlignRect.Left := NewLeft + Control.Width; NewTop := AlignRect.Top; end else Inc(AlignRect.Left, NewWidth); alLeft, alRight: begin if (((AlignRect.Top + Control.Height) > AlignRect.Bottom) and (AlignRect.Top > ClientRect.Top)) then begin AlignRect.Left := FRightEdge; NewTop := ClientRect.Top; AlignRect.Top := NewTop + Control.Height; NewLeft := AlignRect.Left; end else Inc(AlignRect.Top, NewHeight); if AlignRect.Left + Control.Width > FRightEdge then FRightEdge := AlignRect.Left + Control.Width; end; end end else begin case Align of alTop, alBottom, alNone, alClient: begin NewLeft := AlignRect.Left; NewTop := AlignRect.Top; if (Control is TToolButton) and TToolButton(Control).Wrap then begin Inc(AlignRect.Top, ButtonHeight); AlignRect.Left := ClientRect.Left; end else Inc(AlignRect.Left, NewWidth); end; alLeft, alRight: begin NewLeft := AlignRect.Left; NewTop := AlignRect.Top; if (Control is TToolButton) and TToolButton(Control).Wrap then begin Inc(AlignRect.Left, ButtonWidth); AlignRect.Top := ClientRect.Top; end else Inc(AlignRect.Top, NewHeight); if AlignRect.Left + Control.Width > FRightEdge then FRightEdge := AlignRect.Left + Control.Width; end; end; end; end; function TToolBar.HasImages: Boolean; begin Result := (FImages <> nil) or (FDisabledImages <> nil) or (FHotImages <> nil); end; procedure TToolBar.Invalidate; var I: Integer; begin inherited Invalidate; for I := 0 to ControlCount - 1 do Controls[I].Invalidate; end; function TToolBar.ControlCount: Integer; begin Result := FControls.Count; end; procedure TToolBar.DoPaint(ACanvas: TCanvas); var R: TRect; begin if not Masked and not Assigned(Bitmap) then begin ACanvas.Brush.Color := Color; ACanvas.FillRect(BoundsRect); end; R := Types.Rect(0, 0, Width, Height); DrawEdge(ACanvas, R, FEdgeInner, FEdgeOuter, FEdgeBorders); end; procedure TToolBar.FontChanged; begin inherited FontChanged; Canvas.Font := Font; ResizeButtons(nil); end; procedure TToolBar.InitWidget; begin inherited; TabStop := False; end; function TToolBar.EventFilter(Sender: QObjectH; Event: QEventH): Boolean; begin if (QEvent_type(Event) = QEventType_Resize) then Result := True else Result := inherited EventFilter(Sender, Event); end; { TToolButtonActionLink } procedure TToolButtonActionLink.AssignClient(AClient: TObject); begin inherited AssignClient(AClient); FClient := AClient as TToolButton; end; function TToolButtonActionLink.IsCheckedLinked: Boolean; begin Result := inherited IsCheckedLinked and (FClient.Down = (Action as TCustomAction).Checked); end; function TToolButtonActionLink.IsImageIndexLinked: Boolean; begin Result := inherited IsImageIndexLinked and (FClient.ImageIndex = (Action as TCustomAction).ImageIndex); end; procedure TToolButtonActionLink.SetChecked(Value: Boolean); begin if IsCheckedLinked then FClient.Down := Value; end; procedure TToolButtonActionLink.SetImageIndex(Value: Integer); begin if IsImageIndexLinked then FClient.ImageIndex := Value; end; { TIconOptions } constructor TIconOptions.Create(AOwner: TCustomIconView); begin inherited Create; FIconView := AOwner; FArrangement := iaLeft; FAutoArrange := True; FWrapText := True; end; procedure TIconOptions.SetArrangement(Value: TIconArrangement); begin if (FArrangement <> Value) then begin FArrangement := Value; if FIconView.HandleAllocated then QIconView_setArrangement(FIconView.Handle, cIVQtArrangement[FArrangement]); end; end; procedure TIconOptions.SetAutoArrange(Value: Boolean); begin if (FAutoArrange <> Value) then begin FAutoArrange := Value; if FIconView.HandleAllocated then QIconView_setAutoArrange(FIconView.Handle, FAutoArrange); end; end; procedure TIconOptions.SetWrapText(Value: Boolean); begin if (FWrapText <> Value) then begin FWrapText := Value; if FIconView.HandleAllocated then QIconView_setWordWrapIconText(FIconView.Handle, FWrapText); end; end; end.
28.327849
123
0.689667
fcfb0f914a3dcec7f5db9aaa32f6ac00982ca6ca
17,769
pas
Pascal
src/lua/LAPI_CEF.pas
atkins126/sandcat
3e34ea2b965ae0eff1bebd44ef1fd85fa356f3e2
[ "BSD-3-Clause" ]
1
2021-02-16T13:35:29.000Z
2021-02-16T13:35:29.000Z
src/lua/LAPI_CEF.pas
atkins126/sandcat
3e34ea2b965ae0eff1bebd44ef1fd85fa356f3e2
[ "BSD-3-Clause" ]
null
null
null
src/lua/LAPI_CEF.pas
atkins126/sandcat
3e34ea2b965ae0eff1bebd44ef1fd85fa356f3e2
[ "BSD-3-Clause" ]
null
null
null
unit LAPI_CEF; { Sandcat Chromium OSR (Off-Screen Renderer) LUA Object Copyright (c) 2011-2015, Syhunt Informatica License: 3-clause BSD license See https://github.com/felipedaragon/sandcat/ for details. } interface uses Classes, SysUtils, Lua, pLua, LuaObject, CatChromiumOSRX, Dialogs, CatChromiumLib, uLiveHeaders; type { TSandOSR } TSandOSR = class(TLuaObject) private fGetSourceAsText: boolean; procedure AddressChange(Sender: TObject; const URL: string); procedure BeforeDownload(Sender: TObject; const id: integer; const suggestedName: string); procedure BeforePopup(Sender: TObject; var URL: string; out Result: boolean); procedure BrowserMessage(const msg: integer; const str: string); procedure LoadEnd(Sender: TObject; httpStatusCode: integer); procedure LoadError(Sender: TObject; const errorCode: integer; const errorText, failedUrl: string); procedure LoadingStateChange(Sender: TObject; const isLoading, canGoBack, canGoForward: boolean); procedure ConsoleMessage(Sender: TObject; const message, source: string; line: integer); procedure HandleRequestDetails(const json: string); procedure SendRequest(const method, URL, postdata: string; const load: boolean = false); procedure SendRequestCustom(req: TCatChromiumRequest; load: boolean = false); procedure SourceAvailable(const s, headers: string); public obj: TCatChromiumOSRX; constructor Create(LuaState: PLua_State; AParent: TLuaObject = nil); overload; override; function GetPropValue(propName: String): Variant; override; function SetPropValue(propName: String; const AValue: Variant) : boolean; override; destructor Destroy; override; end; procedure RegisterCEF(L: PLua_State); function BuildJSCallFromLuaTable(L: PLua_State): TCatCustomJSCall; function BuildRequestFromJSON(json: string): TCatChromiumRequest; function BuildRequestFromLuaTable(L: PLua_State): TCatChromiumRequest; function BuildRequestDetailsFromLuaTable(L: PLua_State): TSandcatRequestDetails; function BuildRequestDetailsFromJSON(const json: string; const response: string = ''): TSandcatRequestDetails; procedure lua_pushrequestdetails(L: PLua_State; r: TSandcatRequestDetails); implementation uses uMain, uConst, uUIComponents, uSettings, pLuaTable, CatCEFCache, CatFiles, CatHTTP, CatStrings; const REQUESTKEY_METHOD = 'method'; REQUESTKEY_URL = 'url'; REQUESTKEY_POSTDATA = 'postdata'; REQUESTKEY_HEADERS = 'headers'; REQUESTKEY_DETAILS = 'details'; REQUESTKEY_IGNORECACHE = 'ignorecache'; REQUESTKEY_USECOOKIES = 'usecookies'; REQUESTKEY_USEAUTH = 'useauth'; REQUESTKEY_TAB = 'tab'; REQUESTKEY_FILTER = 'filter'; REQUESTKEY_USERNAME = 'username'; REQUESTKEY_PASSWORD = 'password'; REQUESTKEY_CALLBACK = 'callback'; function BuildJSCallFromLuaTable(L: PLua_State): TCatCustomJSCall; var t: TLuaTable; begin t := TLuaTable.Create(L, true); Result.Code := t.ReadString('code'); Result.URL := t.ReadString('url'); Result.StartLine := t.ReadInteger('startln', 0); Result.Silent := t.ReadBool('silent', false); t.Free; end; function BuildRequestFromLuaTable(L: PLua_State): TCatChromiumRequest; var t: TLuaTable; begin t := TLuaTable.Create(L, true); Result.method := t.ReadString(REQUESTKEY_METHOD); Result.URL := t.ReadString(REQUESTKEY_URL); Result.postdata := t.ReadString(REQUESTKEY_POSTDATA); Result.headers := t.ReadString(REQUESTKEY_HEADERS); Result.ignorecache := t.ReadBool(REQUESTKEY_IGNORECACHE, true); Result.usecookies := t.ReadBool(REQUESTKEY_USECOOKIES, true); Result.usecachedcredentials := t.ReadBool(REQUESTKEY_USEAUTH, true); Result.details := t.ReadString(REQUESTKEY_DETAILS); t.Free; end; function BuildRequestFromJSON(json: string): TCatChromiumRequest; var j: TSandJSON; begin j := TSandJSON.Create; j.text := json; Result.method := j.GetValue(REQUESTKEY_METHOD, 'GET'); Result.URL := j.GetValue(REQUESTKEY_URL, emptystr); Result.postdata := j.GetValue(REQUESTKEY_POSTDATA, emptystr); Result.headers := j.GetValue(REQUESTKEY_HEADERS, emptystr); Result.ignorecache := j.GetValue(REQUESTKEY_IGNORECACHE, true); Result.usecookies := j.GetValue(REQUESTKEY_USECOOKIES, true); Result.usecachedcredentials := j.GetValue(REQUESTKEY_USEAUTH, true); Result.details := j.GetValue(REQUESTKEY_DETAILS, emptystr); j.Free; end; function BuildRequestDetailsFromLuaTable(L: PLua_State): TSandcatRequestDetails; var t: TLuaTable; begin t := TLuaTable.Create(L, true); Result.host := t.ReadString('host', emptystr); Result.port := t.ReadString('port', emptystr); Result.SentHead := t.ReadString(REQUESTKEY_HEADERS, emptystr); Result.RcvdHead := t.ReadString('responseheaders', emptystr); Result.method := t.ReadString(REQUESTKEY_METHOD, emptystr); Result.URL := t.ReadString(REQUESTKEY_URL, emptystr); Result.postdata := t.ReadString(REQUESTKEY_POSTDATA, emptystr); Result.StatusCode := t.ReadInteger('status', 0); Result.Length := t.ReadInteger('length', 0); Result.MimeType := t.ReadString('mimetype', emptystr); Result.details := t.ReadString(REQUESTKEY_DETAILS, emptystr); Result.reqid := t.ReadString('reqid', emptystr); Result.responsefilename := t.ReadString('responsefilename', emptystr); Result.response := t.ReadString('response', emptystr); Result.isredir := t.ReadBool('isredir', false); Result.IsLow := t.ReadBool('islow', false); t.Free; end; function BuildRequestDetailsFromJSON(const json: string; const response: string = ''): TSandcatRequestDetails; var j: TSandJSON; begin j := TSandJSON.Create; j.text := json; Result.host := j.GetValue('host', emptystr); Result.port := j.GetValue('port', emptystr); Result.SentHead := j.GetValue(REQUESTKEY_HEADERS, emptystr); Result.RcvdHead := j.GetValue('responseheaders', emptystr); Result.method := j.GetValue(REQUESTKEY_METHOD, emptystr); Result.URL := j.GetValue(REQUESTKEY_URL, emptystr); Result.postdata := j.GetValue(REQUESTKEY_POSTDATA, emptystr); Result.StatusCode := j.GetValue('status', emptystr); Result.Length := j.GetValue('length', emptystr); Result.MimeType := j.GetValue('mimetype', emptystr); Result.details := j.GetValue(REQUESTKEY_DETAILS, emptystr); Result.reqid := j.GetValue('reqid', emptystr); if response = emptystr then Result.responsefilename := j.GetValue('responsefilename', emptystr) else Result.response := response; Result.isredir := j.GetValue('isredir', false); Result.IsLow := j.GetValue('islow', false); j.Free; end; procedure lua_pushrequestdetails(L: PLua_State; r: TSandcatRequestDetails); begin lua_newtable(L); plua_SetFieldValue(L, 'host', r.host); plua_SetFieldValue(L, 'port', r.port); plua_SetFieldValue(L, 'requestid', r.reqid); plua_SetFieldValue(L, REQUESTKEY_DETAILS, r.details); plua_SetFieldValue(L, REQUESTKEY_METHOD, r.method); plua_SetFieldValue(L, REQUESTKEY_URL, r.URL); plua_SetFieldValue(L, REQUESTKEY_POSTDATA, r.postdata); plua_SetFieldValue(L, 'status', r.StatusCode); plua_SetFieldValue(L, 'mimetype', r.MimeType); plua_SetFieldValue(L, 'length', r.Length); plua_SetFieldValue(L, REQUESTKEY_HEADERS, r.SentHead); plua_SetFieldValue(L, 'responseheaders', r.RcvdHead); plua_SetFieldValue(L, 'response', r.response); plua_SetFieldValue(L, 'responsefilename', r.responsefilename); plua_SetFieldValue(L, 'isredir', r.isredir); plua_SetFieldValue(L, 'islow', r.IsLow); plua_SetFieldValue(L, 'filename', r.Filename); end; function get_temp_preview_filename(URL: string): string; var dir, urlext: string; begin urlext := ExtractUrlFileExt(URL); urlext := CleanFilename(urlext); dir := GetSandcatDir(SCDIR_PREVIEW, true); Result := dir + inttostr(sandbrowser.Handle) + urlext; end; function method_savetofile(L: PLua_State): integer; cdecl; var ht: TSandOSR; outfilename: string; begin outfilename := lua_tostring(L, 2); ht := TSandOSR(LuaToTLuaObject(L, 1)); if outfilename = emptystr then outfilename := get_temp_preview_filename(ht.obj.GetURL); ht.obj.SaveToFile(outfilename); lua_pushstring(L, outfilename); Result := 1; end; function method_loadurl(L: PLua_State): integer; cdecl; var ht: TSandOSR; begin ht := TSandOSR(LuaToTLuaObject(L, 1)); ht.obj.reset; ht.obj.load(lua_tostring(L, 2)); Result := 1; end; function method_loadurlfromcache(L: PLua_State): integer; cdecl; var ht: TSandOSR; begin ht := TSandOSR(LuaToTLuaObject(L, 1)); ht.obj.loadfromcache(lua_tostring(L, 2)); Result := 1; end; function method_loadsource(L: PLua_State): integer; cdecl; var ht: TSandOSR; begin ht := TSandOSR(LuaToTLuaObject(L, 1)); ht.obj.reset; ht.obj.loadfromstring(lua_tostring(L, 2), lua_tostring(L, 3)); Result := 1; end; function method_loadrequest(L: PLua_State): integer; cdecl; var ht: TSandOSR; begin ht := TSandOSR(LuaToTLuaObject(L, 1)); ht.obj.Reset; if lua_istable(L, 2) then // user provided a Lua table ht.SendRequestCustom(BuildRequestFromLuaTable(L), true) else ht.SendRequest(lua_tostring(L, 2), lua_tostring(L, 3), lua_tostring(L, 4), true); Result := 1; end; function method_sendrequest(L: PLua_State): integer; cdecl; var ht: TSandOSR; begin ht := TSandOSR(LuaToTLuaObject(L, 1)); if lua_istable(L, 2) then // user provided a Lua table ht.SendRequestCustom(BuildRequestFromLuaTable(L), false) else ht.SendRequest(lua_tostring(L, 2), lua_tostring(L, 3), lua_tostring(L, 4), false); Result := 1; end; function method_runjavascript(L: PLua_State): integer; cdecl; var ht: TSandOSR; begin ht := TSandOSR(LuaToTLuaObject(L, 1)); if lua_istable(L, 2) then // user provided a Lua table ht.obj.RunJavaScript(BuildJSCallFromLuaTable(L)) else ht.obj.RunJavaScript(lua_tostring(L, 2), lua_tostring(L, 3), lua_tointeger(L, 4)); Result := 1; end; function method_showauthdialog(L: PLua_State): integer; cdecl; var ht: TSandOSR; begin ht := TSandOSR(LuaToTLuaObject(L, 1)); ht.obj.ShowAuthDialog(lua_tostring(L, 2), lua_tostring(L, 3)); Result := 1; end; function method_reload(L: PLua_State): integer; cdecl; var ht: TSandOSR; igncache: boolean; begin ht := TSandOSR(LuaToTLuaObject(L, 1)); igncache := false; if lua_isnone(L, 2) = false then igncache := lua_toboolean(L, 2); ht.obj.Reload(igncache); Result := 1; end; function method_stopload(L: PLua_State): integer; cdecl; var ht: TSandOSR; begin ht := TSandOSR(LuaToTLuaObject(L, 1)); ht.obj.Stop; Result := 1; end; procedure register_methods(L: PLua_State; classTable: integer); begin RegisterMethod(L, 'loadurl', @method_loadurl, classTable); RegisterMethod(L, 'loadcached', @method_loadurlfromcache, classTable); RegisterMethod(L, 'loadsource', @method_loadsource, classTable); RegisterMethod(L, 'loadrequest', @method_loadrequest, classTable); RegisterMethod(L, 'reload', @method_reload, classTable); RegisterMethod(L, 'runjs', @method_runjavascript, classTable); RegisterMethod(L, 'savetofile', @method_savetofile, classTable); RegisterMethod(L, 'sendrequest', @method_sendrequest, classTable); RegisterMethod(L, 'showauthdialog', @method_showauthdialog, classTable); RegisterMethod(L, 'stop', method_stopload, classTable); end; const ObjName = 'osr'; function new_callback(L: PLua_State; AParent: TLuaObject = nil): TLuaObject; begin Result := TSandOSR.Create(L, AParent); end; function Create(L: PLua_State): integer; cdecl; var p: TLuaObjectNewCallback; begin p := @new_callback; Result := new_LuaObject(L, ObjName, p); end; procedure RegisterCEF(L: PLua_State); begin RegisterTLuaObject(L, ObjName, @Create, @register_methods); end; // Called before starting a file download procedure TSandOSR.BeforeDownload(Sender: TObject; const id: integer; const suggestedName: string); begin if LocateEvent('ondownloadstart') then begin lua_newtable(L); plua_SetFieldValue(L, 'id', id); plua_SetFieldValue(L, 'suggestedname', suggestedName); lua_pcall(L, 1, 0, 0); end; downloads.SetDownloadFilename(id, suggestedName); end; procedure TSandOSR.LoadingStateChange(Sender: TObject; const isLoading, canGoBack, canGoForward: boolean); begin if LocateEvent('onloadstatechange') then begin lua_newtable(L); plua_SetFieldValue(L, 'isloading', isLoading); plua_SetFieldValue(L, 'cangoback', canGoBack); plua_SetFieldValue(L, 'cangoforward', canGoForward); lua_pcall(L, 1, 0, 0); end; end; // Calls the object method (if set) and pushes the request details as a Lua table // in the first parameter and a JSON object in the second parameter procedure TSandOSR.HandleRequestDetails(const json: string); var r: TSandcatRequestDetails; begin if LocateEvent('onrequestdone') then begin r := BuildRequestDetailsFromJSON(json); lua_pushrequestdetails(L, r); lua_pushstring(L, json); lua_pcall(L, 2, 0, 0); end; end; // Handling of messages originating from the Chromium component // Can also originate from the V8 engine running in the isolated tab process procedure TSandOSR.BrowserMessage(const msg: integer; const str: string); begin case (msg) of CRM_NEWPAGERESOURCE: CallEvent('onresourcefound', [str]); CRM_LOG_REQUEST_JSON: HandleRequestDetails(str); end; end; // Sends (and optionally loads) a HTTP request procedure TSandOSR.SendRequest(const method, URL, postdata: string; const load: boolean = false); begin obj.SendRequest(buildrequest(method, URL, postdata), load); end; // Sends (and optionally loads) a custom HTTP request procedure TSandOSR.SendRequestCustom(req: TCatChromiumRequest; load: boolean = false); begin // If no URL is provided, uses current tab url as the request URL if req.URL = emptystr then req.URL := obj.GetURL; obj.SendRequest(req, load); end; procedure TSandOSR.SourceAvailable(const s, headers: string); begin CallEvent('onsetsource', [s, headers]); end; procedure TSandOSR.LoadError(Sender: TObject; const errorCode: integer; const errorText, failedUrl: string); begin if LocateEvent('onloaderror') then begin lua_newtable(L); plua_SetFieldValue(L, 'errorcode', errorCode); plua_SetFieldValue(L, 'errortext', errorText); plua_SetFieldValue(L, 'failedurl', failedUrl); lua_pcall(L, 1, 0, 0); end; end; procedure TSandOSR.LoadEnd(Sender: TObject; httpStatusCode: integer); begin if LocateEvent('onloadend') then begin lua_newtable(L); plua_SetFieldValue(L, 'statuscode', httpStatusCode); lua_pcall(L, 1, 0, 0); end; if EventExists('onsetsource') then begin if obj.iscachedurl then fgetsourceastext := true; if fgetsourceastext then obj.GetSourceAsText else obj.GetSource; end; end; // Called before a popup window is opened procedure TSandOSR.BeforePopup(Sender: TObject; var URL: string; out Result: boolean); begin if LocateEvent('onbeforepopup') then begin lua_newtable(L); plua_SetFieldValue(L, 'url', URL); lua_pcall(L, 1, 0, 0); end; end; procedure TSandOSR.ConsoleMessage(Sender: TObject; const message, source: string; line: integer); begin if LocateEvent('onconsolemessage') then begin lua_newtable(L); plua_SetFieldValue(L, 'message', message); plua_SetFieldValue(L, 'source', source); plua_SetFieldValue(L, 'line', line); lua_pcall(L, 1, 0, 0); end; end; procedure TSandOSR.AddressChange(Sender: TObject; const URL: string); begin CallEvent('onaddresschange', [URL]); end; constructor TSandOSR.Create(LuaState: PLua_State; AParent: TLuaObject); begin inherited Create(LuaState, AParent); fGetSourceAsText := false; obj := TCatChromiumOSRX.Create(nil); obj.OnLoadEnd := LoadEnd; obj.OnAfterSetSourceSpecial := SourceAvailable; obj.OnBrowserMessage := BrowserMessage; obj.OnConsoleMessage := ConsoleMessage; obj.OnLoadError := LoadError; obj.OnAddressChange := AddressChange; obj.OnLoadingStateChange := LoadingStateChange; obj.OnBeforePopup := BeforePopup; obj.OnBeforeDownload := BeforeDownload; obj.LoadSettings(settings.preferences.current, settings.preferences.Default); end; function TSandOSR.GetPropValue(propName: String): Variant; begin if CompareText(propName, 'captureurls') = 0 then Result := obj.LogURLs else if CompareText(propName, 'downloadfiles') = 0 then Result := obj.EnableDownloads else if CompareText(propName, 'getsourceastext') = 0 then Result := fgetsourceastext else if CompareText(propName, 'isloading') = 0 then Result := obj.isLoading else if CompareText(propName, 'reslist') = 0 then Result := obj.ResourceList.text else if CompareText(propName, 'url') = 0 then Result := obj.GetURLSpecial else if CompareText(propName, 'urllist') = 0 then Result := obj.URLLog.text else Result := inherited GetPropValue(propName); end; function TSandOSR.SetPropValue(propName: String; const AValue: Variant) : boolean; begin Result := true; if CompareText(propName, 'captureurls') = 0 then obj.LogURLs := AValue else if CompareText(propName, 'downloadfiles') = 0 then obj.EnableDownloads := AValue else if CompareText(propName, 'getsourceastext') = 0 then fgetsourceastext := AValue else if CompareText(propName, 'isloading') = 0 then Result := true // readonly else if CompareText(propName, 'reslist') = 0 then Result := true // readonly else if CompareText(propName, 'url') = 0 then obj.load(string(AValue)) else if CompareText(propName, 'urllist') = 0 then Result := true // readonly else Result := inherited SetPropValue(propName, AValue); end; destructor TSandOSR.Destroy; begin obj.Free; inherited Destroy; end; end.
31.617438
81
0.734481
fca0f483d13edf429f719343741c2fa5a85f2539
6,158
dfm
Pascal
UnitAbout.dfm
sanekgusev/LinX-old
9f393a6f0b669718a7fefd2821112c6b3e2536f7
[ "MIT" ]
40
2015-01-28T06:05:55.000Z
2021-12-24T12:50:04.000Z
UnitAbout.dfm
sanekgusev/LinX-old
9f393a6f0b669718a7fefd2821112c6b3e2536f7
[ "MIT" ]
null
null
null
UnitAbout.dfm
sanekgusev/LinX-old
9f393a6f0b669718a7fefd2821112c6b3e2536f7
[ "MIT" ]
9
2015-02-15T02:27:32.000Z
2022-03-24T05:15:12.000Z
object FormAbout: TFormAbout Left = 0 Top = 0 BorderStyle = bsToolWindow Caption = 'About LinX' ClientHeight = 250 ClientWidth = 350 Color = clBtnFace ParentFont = True GlassFrame.SheetOfGlass = True KeyPreview = True OldCreateOrder = False Position = poMainFormCenter ShowHint = True OnCreate = FormCreate OnKeyDown = FormKeyDown PixelsPerInch = 96 TextHeight = 13 object LabelFacts: TLabel Left = 5 Top = 140 Width = 340 Height = 105 Alignment = taCenter AutoSize = False Transparent = True Visible = False WordWrap = True end object LabelInfo: TLabel Left = 5 Top = 37 Width = 340 Height = 90 Alignment = taCenter AutoSize = False Transparent = True Visible = False WordWrap = True end object LabelDiscl: TLabel Left = 5 Top = 137 Width = 90 Height = 51 Alignment = taCenter AutoSize = False Caption = 'This software is provided '#171'as-is'#187'. Use it at your own risk.' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Tahoma' Font.Style = [] ParentFont = False Transparent = True WordWrap = True end object LabelEMail: TLabel Left = 105 Top = 135 Width = 32 Height = 13 Caption = 'E-Mail:' Transparent = True end object LabelOversLink: TLabel Left = 105 Top = 175 Width = 232 Height = 13 Hint = 'http://forums.overclockers.ru/viewtopic.php?t=272642' Caption = #1056#1091#1089#1089#1082#1072#1103' '#1074#1077#1090#1082#1072' '#1086#1073#1089#1091#1078#1076#1077#1085#1080#1103' '#1085#1072' Overclockers.ru' Font.Charset = DEFAULT_CHARSET Font.Color = 8866336 Font.Height = -11 Font.Name = 'Tahoma' Font.Style = [fsUnderline] ParentFont = False Transparent = True OnClick = LabelOversLinkClick OnMouseEnter = LabelsMouseEnter OnMouseLeave = LabelsMouseLeave end object LabelXSLink: TLabel Left = 105 Top = 155 Width = 229 Height = 13 Hint = 'http://www.xtremesystems.org/forums/showthread.php?t=201670' Caption = 'English discussion thread at XtremeSystems.org' Font.Charset = DEFAULT_CHARSET Font.Color = 8866336 Font.Height = -11 Font.Name = 'Tahoma' Font.Style = [fsUnderline] ParentFont = False Transparent = True OnClick = LabelXSLinkClick OnMouseEnter = LabelsMouseEnter OnMouseLeave = LabelsMouseLeave end object LabelLin: TLabel Left = 5 Top = 41 Width = 60 Height = 90 Hint = 'LinX' Alignment = taCenter AutoSize = False Caption = 'Lin' Font.Charset = DEFAULT_CHARSET Font.Color = 10773812 Font.Height = -45 Font.Name = 'Arial' Font.Style = [] ParentFont = False Layout = tlCenter end object LabelX: TLabel Left = 65 Top = 41 Width = 29 Height = 90 Hint = 'LinX' Alignment = taCenter AutoSize = False Caption = 'X' Font.Charset = DEFAULT_CHARSET Font.Color = 31221 Font.Height = -45 Font.Name = 'Arial' Font.Style = [] ParentFont = False Layout = tlCenter end object LabelThanks1: TLabel Left = 5 Top = 200 Width = 321 Height = 13 Caption = 'Special thanks to Right from Overclockers.ru for AMD compatibili' + 'ty.' Transparent = True end object LabelThanks2: TLabel Left = 5 Top = 215 Width = 340 Height = 30 AutoSize = False Caption = 'Thanks to everybody who helps improve LinX for their suggestions' + ' and bug reports, and especially to my friends, SqeptiQ, Winkle ' + 'and YaK.' Transparent = True WordWrap = True end object LabelIntel1: TLabel Left = 105 Top = 55 Width = 167 Height = 13 Caption = 'Uses Intel'#174' Math Kernel Library '#8212 Transparent = True end object LabelIntel2: TLabel Left = 105 Top = 70 Width = 155 Height = 13 Caption = 'Copyright '#169' Intel'#174' Corporation' Transparent = True end object LabelLinpackLink: TLabel Left = 278 Top = 54 Width = 35 Height = 13 Hint = 'http://www.intel.com/cd/software/products/asmo-na/eng/266857.htm' Caption = 'Linpack' Font.Charset = DEFAULT_CHARSET Font.Color = 8866336 Font.Height = -11 Font.Name = 'Tahoma' Font.Style = [fsUnderline] ParentFont = False Transparent = True OnClick = LabelLinpackLinkClick OnMouseEnter = LabelsMouseEnter OnMouseLeave = LabelsMouseLeave end object LabelMe: TLabel Left = 105 Top = 35 Width = 191 Height = 13 Caption = 'Author: Alexander Gusev a.k.a. Dua|ist' Transparent = True end object LabelPNG: TLabel Left = 105 Top = 90 Width = 222 Height = 13 Caption = 'Uses PNG Delphi Component by Gustavo Daud' Transparent = True end object SpeedButtonInfo: TSpeedButton Left = 5 Top = 5 Width = 75 Height = 25 GroupIndex = 1 Caption = 'Info' OnClick = SpeedButtonInfoClick end object SpeedButtonAbout: TSpeedButton Left = 80 Top = 5 Width = 75 Height = 25 GroupIndex = 1 Caption = 'About' OnClick = SpeedButtonAboutClick end object SpeedButtonReadMe: TSpeedButton Left = 165 Top = 5 Width = 75 Height = 25 Caption = 'ReadMe'#8230 OnClick = SpeedButtonReadMeClick end object LabelVersion: TLabel Left = 245 Top = 12 Width = 100 Height = 13 Alignment = taRightJustify AutoSize = False Font.Charset = DEFAULT_CHARSET Font.Color = clGrayText Font.Height = -11 Font.Name = 'Tahoma' Font.Style = [] ParentFont = False Transparent = True end object EditEMailLink: TEdit Left = 140 Top = 132 Width = 130 Height = 21 Alignment = taCenter Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Tahoma' Font.Style = [] ParentFont = False ReadOnly = True TabOrder = 0 Text = 'sanekgusev@gmail.com' end end
22.977612
161
0.634622
c3355b9f31bec2458fc502d560e914b1c3d651f9
12,484
dfm
Pascal
DepotManagerCenter/untStockStat.dfm
Bill-cc/vegaga-admin
fef700c4d2cf6563c1d5ad9d881f25b6d0370ef1
[ "MIT" ]
1
2020-05-27T07:39:32.000Z
2020-05-27T07:39:32.000Z
DepotManagerCenter/untStockStat.dfm
Bill-cc/vegaga-admin
fef700c4d2cf6563c1d5ad9d881f25b6d0370ef1
[ "MIT" ]
null
null
null
DepotManagerCenter/untStockStat.dfm
Bill-cc/vegaga-admin
fef700c4d2cf6563c1d5ad9d881f25b6d0370ef1
[ "MIT" ]
null
null
null
object frmStockStat: TfrmStockStat Left = 206 Top = 205 Width = 950 Height = 449 Caption = #24211#23384#32479#35745 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] OldCreateOrder = False OnClose = FormClose OnCreate = FormCreate PixelsPerInch = 96 TextHeight = 13 object pnl1: TPanel Left = 0 Top = 0 Width = 942 Height = 41 Align = alTop TabOrder = 0 object RzLabel1: TRzLabel Left = 24 Top = 16 Width = 60 Height = 13 Caption = #21830#21697#24635#25968#65306 end object RzLabel2: TRzLabel Left = 240 Top = 16 Width = 60 Height = 13 Caption = #24211#23384#24635#37327#65306 end object RzEdit1: TRzEdit Left = 88 Top = 12 Width = 145 Height = 21 Color = clInfoBk ReadOnly = True TabOrder = 0 end object RzEdit2: TRzEdit Left = 304 Top = 12 Width = 145 Height = 21 Color = clInfoBk ReadOnly = True TabOrder = 1 end end object pnl2: TPanel Left = 0 Top = 41 Width = 942 Height = 336 Align = alClient TabOrder = 1 object dgeSSList: TDBGridEh Left = 1 Top = 1 Width = 940 Height = 334 Align = alClient DataGrouping.GroupLevels = <> DataSource = dmDepotCenter.dsStockStat Flat = False FooterColor = clWindow FooterFont.Charset = DEFAULT_CHARSET FooterFont.Color = clWindowText FooterFont.Height = -11 FooterFont.Name = 'MS Sans Serif' FooterFont.Style = [] Options = [dgTitles, dgIndicator, dgColumnResize, dgColLines, dgRowLines, dgTabs, dgRowSelect, dgAlwaysShowSelection, dgConfirmDelete, dgCancelOnExit, dgMultiSelect] OptionsEh = [dghFixed3D, dghHighlightFocus, dghClearSelection, dghAutoSortMarking, dghMultiSortMarking, dghIncSearch, dghPreferIncSearch, dghDialogFind, dghShowRecNo, dghColumnResize, dghColumnMove, dghExtendVertLines] RowDetailPanel.Active = True RowDetailPanel.Width = 680 RowDetailPanel.Height = 150 RowDetailPanel.Color = clBtnFace STFilter.InstantApply = True STFilter.Local = True STFilter.Location = stflInTitleFilterEh STFilter.Visible = True TabOrder = 0 TitleFont.Charset = DEFAULT_CHARSET TitleFont.Color = clWindowText TitleFont.Height = -11 TitleFont.Name = 'MS Sans Serif' TitleFont.Style = [] Columns = < item EditButtons = <> FieldName = 'name' Footers = <> Width = 180 end item EditButtons = <> FieldName = 'sn' Footers = <> Width = 100 end item EditButtons = <> FieldName = 'stock' Footers = <> Width = 60 end item EditButtons = <> FieldName = 'can_sale_stock' Footers = <> Width = 60 end item EditButtons = <> FieldName = 'freeze_stock' Footers = <> Width = 60 end item EditButtons = <> FieldName = 'brand_name' Footers = <> Width = 120 end item EditButtons = <> FieldName = 'ean' Footers = <> Width = 80 end item EditButtons = <> FieldName = 'spec' Footers = <> Width = 180 end item EditButtons = <> FieldName = 'color' Footers = <> Width = 60 end item EditButtons = <> FieldName = 'p_size' Footers = <> Width = 100 end> object RowDetailData: TRowDetailPanelControlEh object dgeSkuLogList: TDBGridEh Left = 0 Top = 0 Width = 678 Height = 148 Align = alClient DataGrouping.GroupLevels = <> DataSource = dmDepotCenter.dsSLList Flat = False FooterColor = clWindow FooterFont.Charset = DEFAULT_CHARSET FooterFont.Color = clWindowText FooterFont.Height = -11 FooterFont.Name = 'MS Sans Serif' FooterFont.Style = [] Options = [dgTitles, dgIndicator, dgColumnResize, dgColLines, dgRowLines, dgTabs, dgRowSelect, dgConfirmDelete, dgCancelOnExit] OptionsEh = [dghFixed3D, dghHighlightFocus, dghClearSelection, dghAutoSortMarking, dghMultiSortMarking, dghIncSearch, dghPreferIncSearch, dghDialogFind, dghShowRecNo, dghColumnResize, dghColumnMove, dghExtendVertLines] RowDetailPanel.Color = clBtnFace TabOrder = 0 TitleFont.Charset = DEFAULT_CHARSET TitleFont.Color = clWindowText TitleFont.Height = -11 TitleFont.Name = 'MS Sans Serif' TitleFont.Style = [] Columns = < item EditButtons = <> FieldName = 'ID' Footers = <> Visible = False end item EditButtons = <> FieldName = 'is_sales' Footers = <> KeyList.Strings = ( '301' '302' '303') PickList.Strings = ( #24050#20837#24211 #24050#20986#24211 #24050#39044#35746) Width = 60 end item EditButtons = <> FieldName = 'sto_no' Footers = <> Width = 120 end item EditButtons = <> FieldName = 'so_no' Footers = <> Width = 120 end item EditButtons = <> FieldName = 'lot_id' Footers = <> Visible = False end item EditButtons = <> FieldName = 'p_id' Footers = <> Visible = False end item EditButtons = <> FieldName = 'p_sku' Footers = <> Width = 120 end item EditButtons = <> FieldName = 'sort_n' Footers = <> Width = 60 end item EditButtons = <> FieldName = 'wh_n' Footers = <> Width = 120 end item EditButtons = <> FieldName = 'entrance_date' Footers = <> Width = 100 end item EditButtons = <> FieldName = 'exit_date' Footers = <> Width = 100 end item EditButtons = <> FieldName = 'opt_by' Footers = <> Visible = False end item EditButtons = <> FieldName = 'opt_date' Footers = <> Visible = False end item EditButtons = <> FieldName = 'opt_ip' Footers = <> Visible = False end item EditButtons = <> FieldName = 'remark' Footers = <> Width = 150 end item EditButtons = <> FieldName = 'sys_status' Footers = <> KeyList.Strings = ( '1' '2' '3' '4') PickList.Strings = ( #26377#25928 #26080#25928 #21024#38500 #24402#26723) Width = 60 end> object RowDetailData: TRowDetailPanelControlEh end end end end end object pnl3: TPanel Left = 0 Top = 377 Width = 942 Height = 38 Align = alBottom TabOrder = 2 object pnl4: TPanel Left = 846 Top = 1 Width = 95 Height = 36 Align = alRight TabOrder = 0 object btnCancel: TRzBitBtn Left = 10 Top = 6 Caption = #36864#20986 TabOrder = 0 OnClick = btnCancelClick Glyph.Data = { 36060000424D3606000000000000360400002800000020000000100000000100 08000000000000020000730B0000730B00000001000000000000000000003300 00006600000099000000CC000000FF0000000033000033330000663300009933 0000CC330000FF33000000660000336600006666000099660000CC660000FF66 000000990000339900006699000099990000CC990000FF99000000CC000033CC 000066CC000099CC0000CCCC0000FFCC000000FF000033FF000066FF000099FF 0000CCFF0000FFFF000000003300330033006600330099003300CC003300FF00 330000333300333333006633330099333300CC333300FF333300006633003366 33006666330099663300CC663300FF6633000099330033993300669933009999 3300CC993300FF99330000CC330033CC330066CC330099CC3300CCCC3300FFCC 330000FF330033FF330066FF330099FF3300CCFF3300FFFF3300000066003300 66006600660099006600CC006600FF0066000033660033336600663366009933 6600CC336600FF33660000666600336666006666660099666600CC666600FF66 660000996600339966006699660099996600CC996600FF99660000CC660033CC 660066CC660099CC6600CCCC6600FFCC660000FF660033FF660066FF660099FF 6600CCFF6600FFFF660000009900330099006600990099009900CC009900FF00 990000339900333399006633990099339900CC339900FF339900006699003366 99006666990099669900CC669900FF6699000099990033999900669999009999 9900CC999900FF99990000CC990033CC990066CC990099CC9900CCCC9900FFCC 990000FF990033FF990066FF990099FF9900CCFF9900FFFF99000000CC003300 CC006600CC009900CC00CC00CC00FF00CC000033CC003333CC006633CC009933 CC00CC33CC00FF33CC000066CC003366CC006666CC009966CC00CC66CC00FF66 CC000099CC003399CC006699CC009999CC00CC99CC00FF99CC0000CCCC0033CC CC0066CCCC0099CCCC00CCCCCC00FFCCCC0000FFCC0033FFCC0066FFCC0099FF CC00CCFFCC00FFFFCC000000FF003300FF006600FF009900FF00CC00FF00FF00 FF000033FF003333FF006633FF009933FF00CC33FF00FF33FF000066FF003366 FF006666FF009966FF00CC66FF00FF66FF000099FF003399FF006699FF009999 FF00CC99FF00FF99FF0000CCFF0033CCFF0066CCFF0099CCFF00CCCCFF00FFCC FF0000FFFF0033FFFF0066FFFF0099FFFF00CCFFFF00FFFFFF00000080000080 000000808000800000008000800080800000C0C0C00080808000191919004C4C 4C00B2B2B200E5E5E500C8AC2800E0CC6600F2EABF00B59B2400D8E9EC009933 6600D075A300ECC6D900646F710099A8AC00E2EFF10000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000E8E8E8E8E8E8 EEE8E8E8E8E8E8E8E8E8E8E8E8E8E8E8EEE8E8E8E8E8E8E8E8E8E8E8E8EEE3AC E3EEE8E8E8E8E8E8E8E8E8E8E8EEE8ACE3EEE8E8E8E8E8E8E8E8E8EEE3E28257 57E2ACE3EEE8E8E8E8E8E8EEE8E2818181E2ACE8EEE8E8E8E8E8E382578282D7 578181E2E3E8E8E8E8E8E881818181D7818181E2E8E8E8E8E8E857828989ADD7 57797979EEE8E8E8E8E88181DEDEACD781818181EEE8E8E8E8E857898989ADD7 57AAAAA2D7ADE8E8E8E881DEDEDEACD781DEDE81D7ACE8E8E8E857898989ADD7 57AACEA3AD10E8E8E8E881DEDEDEACD781DEAC81AC81E8E8E8E85789825EADD7 57ABCFE21110E8E8E8E881DE8181ACD781ACACE28181E8E8E8E8578957D7ADD7 57ABDE101010101010E881DE56D7ACD781ACDE818181818181E857898257ADD7 57E810101010101010E881DE8156ACD781E381818181818181E857898989ADD7 57E882101010101010E881DEDEDEACD781E381818181818181E857898989ADD7 57ACEE821110E8E8E8E881DEDEDEACD781ACEE818181E8E8E8E857898989ADD7 57ABE8AB8910E8E8E8E881DEDEDEACD781ACE3ACDE81E8E8E8E857828989ADD7 57ACE8A3E889E8E8E8E88181DEDEACD781ACE381E8DEE8E8E8E8E8DE5E8288D7 57A2A2A2E8E8E8E8E8E8E8DE8181DED781818181E8E8E8E8E8E8E8E8E8AC8257 57E8E8E8E8E8E8E8E8E8E8E8E8AC818181E8E8E8E8E8E8E8E8E8} NumGlyphs = 2 end end object pnl5: TPanel Left = 1 Top = 1 Width = 845 Height = 36 Align = alClient TabOrder = 1 end end end
32.258398
228
0.592438
fc2bc1e6c28b658db1ce0c19eb131f23d36b5338
9,337
pas
Pascal
examples/Delphi/Compound/Bios/Gui/Renderers.pas
LenakeTech/BoldForDelphi
3ef25517d5c92ebccc097c6bc2f2af62fc506c71
[ "MIT" ]
121
2020-09-22T10:46:20.000Z
2021-11-17T12:33:35.000Z
examples/Delphi/Compound/Bios/Gui/Renderers.pas
LenakeTech/BoldForDelphi
3ef25517d5c92ebccc097c6bc2f2af62fc506c71
[ "MIT" ]
8
2020-09-23T12:32:23.000Z
2021-07-28T07:01:26.000Z
examples/Delphi/Compound/Bios/Gui/Renderers.pas
LenakeTech/BoldForDelphi
3ef25517d5c92ebccc097c6bc2f2af62fc506c71
[ "MIT" ]
42
2020-09-22T14:37:20.000Z
2021-10-04T10:24:12.000Z
unit Renderers; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, stdCtrls, BoldCheckboxStateControlPack, BoldSubscription, BoldElements, BoldControlPack, BoldStringControlPack, BuildingsAndOwners; type TDataModule2 = class(TDataModule) NegativeRedRenderer: TBoldAsStringRenderer; FullNameRenderer: TBoldAsStringRenderer; IsRichRenderer: TBoldAsCheckBoxStateRenderer; bsrAddress: TBoldAsStringRenderer; bsrResidentsTotalAssets: TBoldAsStringRenderer; bsrRentPerResident: TBoldAsStringRenderer; function IsRichRendererGetAsCheckBoxState(Element: TBoldElement; Representation: Integer; Expression: String): TCheckBoxState; procedure IsRichRendererSubscribe(Element: TBoldElement; Representation: Integer; Expression: String; Subscriber: TBoldSubscriber); function FullNameRendererGetAsString(Element: TBoldElement; Representation: Integer; Expression: String): String; procedure FullNameRendererSubscribe(Element: TBoldElement; Representation: Integer; Expression: String; Subscriber: TBoldSubscriber); procedure NegativeRedRendererHoldsChangedValue(Element: TBoldElement; Representation: Integer; Expression: String; Subscriber: TBoldSubscriber); procedure NegativeRedRendererSetFont(Element: TBoldElement; AFont: TFont; Representation: Integer; Expression: String); procedure bsrAddressSetColor(Element: TBoldElement; var AColor: TColor; Representation: Integer; Expression: String); procedure bsrAddressSetFont(Element: TBoldElement; AFont: TFont; Representation: Integer; Expression: String); function bsrResidentsTotalAssetsGetAsString(Element: TBoldElement; Representation: Integer; Expression: String): String; procedure bsrResidentsTotalAssetsSubscribe(Element: TBoldElement; Representation: Integer; Expression: String; Subscriber: TBoldSubscriber); function bsrRentPerResidentGetAsString(Element: TBoldElement; Representation: Integer; Expression: String): String; procedure bsrRentPerResidentHoldsChangedValue(Element: TBoldElement; Representation: Integer; Expression: String; Subscriber: TBoldSubscriber); function bsrRentPerResidentMayModify(Element: TBoldElement; Representation: Integer; Expression: String; Subscriber: TBoldSubscriber): Boolean; procedure bsrRentPerResidentReleaseChangedValue(Element: TBoldElement; Representation: Integer; Expression: String; Subscriber: TBoldSubscriber); procedure bsrRentPerResidentSetAsString(Element: TBoldElement; NewValue: String; Representation: Integer; Expression: String); procedure bsrRentPerResidentSubscribe(Element: TBoldElement; Representation: Integer; Expression: String; Subscriber: TBoldSubscriber); function bsrRentPerResidentValidateCharacter(Element: TBoldElement; Value: String; Representation: Integer; Expression: String): Boolean; function bsrRentPerResidentValidateString(Element: TBoldElement; Value: String; Representation: Integer; Expression: String): Boolean; private { Private declarations } public { Public declarations } end; var DataModule2: TDataModule2; implementation {$R *.DFM} function TDataModule2.IsRichRendererGetAsCheckBoxState( Element: TBoldElement; Representation: Integer; Expression: String): TCheckBoxState; begin Result := cbGrayed; if Assigned(Element) then begin with element as TPerson do if Assets > 10000 then Result := cbChecked else Result := cbUnChecked end; end; procedure TDataModule2.IsRichRendererSubscribe(Element: TBoldElement; Representation: Integer; Expression: String; Subscriber: TBoldSubscriber); begin Element.SubscribeToExpression('assets', Subscriber, False); end; function TDataModule2.FullNameRendererGetAsString(Element: TBoldElement; Representation: Integer; Expression: String): String; begin Result := ''; if Assigned(Element) then begin with Element as TPerson do Result := Format('%s, %s', [LastName, FirstName]) end; end; procedure TDataModule2.FullNameRendererSubscribe(Element: TBoldElement; Representation: Integer; Expression: String; Subscriber: TBoldSubscriber); begin Element.SubscribeToExpression('firstName', Subscriber, false); Element.SubscribeToExpression('', Subscriber, False); Element.SubscribeToExpression('lastName', Subscriber, false); end; procedure TDataModule2.NegativeRedRendererHoldsChangedValue( Element: TBoldElement; Representation: Integer; Expression: String; Subscriber: TBoldSubscriber); begin if assigned( element ) then with NegativeRedRenderer do DefaultHoldsChangedValue(element, representation, Expression, nil, subscriber); end; procedure TDataModule2.NegativeRedRendererSetFont(Element: TBoldElement; AFont: TFont; Representation: Integer; Expression: String); begin if assigned( element ) then begin with element as TPerson do if Assets < 0 then aFont.Color := clRed else aFont.Color := clBlue; end; end; procedure TDataModule2.bsrAddressSetColor(Element: TBoldElement; var AColor: TColor; Representation: Integer; Expression: String); begin if Assigned(element) then with element as TBuilding do begin if Pos('Bold', Address) > 0 then aColor := clAqua; end; end; procedure TDataModule2.bsrAddressSetFont(Element: TBoldElement; AFont: TFont; Representation: Integer; Expression: String); begin if Assigned(element) then with element as TBuilding do begin if Pos( 'Bold', Address ) > 0 then aFont.Style := aFont.Style + [fsBold]; if Pos( 'Rose', Address ) > 0 then aFont.Color := clRed; if Pos( 'Select', Address ) > 0 then aFont.Color := clGreen; end; end; function TDataModule2.bsrResidentsTotalAssetsGetAsString( Element: TBoldElement; Representation: Integer; Expression: String): String; var i: integer; sum: Currency; begin Sum := 0; if element is TResidential_Building then with Element as TResidential_Building do for i := 0 to Residents.Count-1 do Sum := Sum + Residents[i].Assets; Result := CurrToStr(Sum); end; procedure TDataModule2.bsrResidentsTotalAssetsSubscribe( Element: TBoldElement; Representation: Integer; Expression: String; Subscriber: TBoldSubscriber); var i: integer; begin if element is TResidential_Building then with Element as TResidential_Building do begin SubscribeToExpression('residents', subscriber, true); for i := 0 to Residents.Count-1 do Residents[i].SubscribeToExpression('assets', subscriber, false); end; end; function TDataModule2.bsrRentPerResidentGetAsString(Element: TBoldElement; Representation: Integer; Expression: String): String; begin result := ''; if element is TResidential_Building then with Element as TResidential_Building do if M_TotalRent.IsNull then Result := '***' else if Residents.Count = 0 then Result := 'No Residents' else Result := CurrToStr(TotalRent/Residents.Count); end; procedure TDataModule2.bsrRentPerResidentHoldsChangedValue( Element: TBoldElement; Representation: Integer; Expression: String; Subscriber: TBoldSubscriber); begin if element is TResidential_Building then with Element as TResidential_Building do M_TotalRent.RegisterModifiedValueHolder(subscriber); end; function TDataModule2.bsrRentPerResidentMayModify(Element: TBoldElement; Representation: Integer; Expression: String; Subscriber: TBoldSubscriber): Boolean; begin Result := False; if element is TResidential_Building then with element as TResidential_Building do Result := Residents.Count > 0; end; procedure TDataModule2.bsrRentPerResidentReleaseChangedValue( Element: TBoldElement; Representation: Integer; Expression: String; Subscriber: TBoldSubscriber); begin if element is TResidential_Building then with Element as TResidential_Building do M_TotalRent.UnRegisterModifiedValueHolder(Subscriber); end; procedure TDataModule2.bsrRentPerResidentSetAsString(Element: TBoldElement; NewValue: String; Representation: Integer; Expression: String); begin if element is TResidential_Building then with Element as TResidential_Building do TotalRent := StrToCurr(NewValue) * Residents.Count; end; procedure TDataModule2.bsrRentPerResidentSubscribe(Element: TBoldElement; Representation: Integer; Expression: String; Subscriber: TBoldSubscriber); begin if element is TResidential_Building then with Element do begin SubscribeToExpression('totalRent', Subscriber, False); SubscribeToExpression('residents', Subscriber, False); end; end; function TDataModule2.bsrRentPerResidentValidateCharacter( Element: TBoldElement; Value: String; Representation: Integer; Expression: String): Boolean; begin Result := value[1] in ['0'..'9', '-', '+', 'e', 'E', DecimalSeparator]; end; function TDataModule2.bsrRentPerResidentValidateString( Element: TBoldElement; Value: String; Representation: Integer; Expression: String): Boolean; begin try StrToCurr(value); Result := True; except Result := False; end; end; end.
32.992933
119
0.757095
fca9bb5eacd8cf0500f629c0645ae34e39d7226e
12,373
pas
Pascal
vcl/SrcXLS/XLSDefaultDataXLSX5.pas
1aq/PBox
67ced599ee36ceaff097c6584f8100cf96006dfe
[ "MIT" ]
null
null
null
vcl/SrcXLS/XLSDefaultDataXLSX5.pas
1aq/PBox
67ced599ee36ceaff097c6584f8100cf96006dfe
[ "MIT" ]
null
null
null
vcl/SrcXLS/XLSDefaultDataXLSX5.pas
1aq/PBox
67ced599ee36ceaff097c6584f8100cf96006dfe
[ "MIT" ]
null
null
null
unit XLSDefaultDataXLSX5; interface const DEFAULT_DOCPROPS_CORE = '<cp:coreProperties ' + 'xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" ' + 'xmlns:dc="http://purl.org/dc/elements/1.1/" ' + 'xmlns:dcterms="http://purl.org/dc/terms/" ' + 'xmlns:dcmitype="http://purl.org/dc/dcmitype/" ' + 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' + #13 + ' <dc:creator>John Doe II</dc:creator>' + #13 + ' <cp:lastModifiedBy>John Doe II</cp:lastModifiedBy>' + #13 + ' <dcterms:created xsi:type="dcterms:W3CDTF">2000-01-01T12:00:00Z</dcterms:created>' + #13 + ' <dcterms:modified xsi:type="dcterms:W3CDTF">2000-01-01T12:00:00Z</dcterms:modified>' + #13 + '</cp:coreProperties>'; const DEFAULT_THEME = '<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="Office Theme">' + #13 + ' <a:themeElements>' + #13 + ' <a:clrScheme name="Office">' + #13 + ' <a:dk1>' + #13 + ' <a:sysClr val="windowText" lastClr="000000"/>' + #13 + ' </a:dk1>' + #13 + ' <a:lt1>' + #13 + ' <a:sysClr val="window" lastClr="FFFFFF"/>' + #13 + ' </a:lt1>' + #13 + ' <a:dk2>' + #13 + ' <a:srgbClr val="1F497D"/>' + #13 + ' </a:dk2>' + #13 + ' <a:lt2>' + #13 + ' <a:srgbClr val="EEECE1"/>' + #13 + ' </a:lt2>' + #13 + ' <a:accent1>' + #13 + ' <a:srgbClr val="4F81BD"/>' + #13 + ' </a:accent1>' + #13 + ' <a:accent2>' + #13 + ' <a:srgbClr val="C0504D"/>' + #13 + ' </a:accent2>' + #13 + ' <a:accent3>' + #13 + ' <a:srgbClr val="9BBB59"/>' + #13 + ' </a:accent3>' + #13 + ' <a:accent4>' + #13 + ' <a:srgbClr val="8064A2"/>' + #13 + ' </a:accent4>' + #13 + ' <a:accent5>' + #13 + ' <a:srgbClr val="4BACC6"/>' + #13 + ' </a:accent5>' + #13 + ' <a:accent6>' + #13 + ' <a:srgbClr val="F79646"/>' + #13 + ' </a:accent6>' + #13 + ' <a:hlink>' + #13 + ' <a:srgbClr val="0000FF"/>' + #13 + ' </a:hlink>' + #13 + ' <a:folHlink>' + #13 + ' <a:srgbClr val="800080"/>' + #13 + ' </a:folHlink>' + #13 + ' </a:clrScheme>' + #13 + ' <a:fontScheme name="Office">' + #13 + ' <a:majorFont>' + #13 + ' <a:latin typeface="Cambria"/>' + #13 + ' <a:ea typeface=""/>' + #13 + ' <a:cs typeface=""/>' + #13 + ' <a:font script="Jpan" typeface="?? ?????"/>' + #13 + ' <a:font script="Hang" typeface="?? ??"/>' + #13 + ' <a:font script="Hans" typeface="??"/>' + #13 + ' <a:font script="Hant" typeface="????"/>' + #13 + ' <a:font script="Arab" typeface="Times New Roman"/>' + #13 + ' <a:font script="Hebr" typeface="Times New Roman"/>' + #13 + ' <a:font script="Thai" typeface="Tahoma"/>' + #13 + ' <a:font script="Ethi" typeface="Nyala"/>' + #13 + ' <a:font script="Beng" typeface="Vrinda"/>' + #13 + ' <a:font script="Gujr" typeface="Shruti"/>' + #13 + ' <a:font script="Khmr" typeface="MoolBoran"/>' + #13 + ' <a:font script="Knda" typeface="Tunga"/>' + #13 + ' <a:font script="Guru" typeface="Raavi"/>' + #13 + ' <a:font script="Cans" typeface="Euphemia"/>' + #13 + ' <a:font script="Cher" typeface="Plantagenet Cherokee"/>' + #13 + ' <a:font script="Yiii" typeface="Microsoft Yi Baiti"/>' + #13 + ' <a:font script="Tibt" typeface="Microsoft Himalaya"/>' + #13 + ' <a:font script="Thaa" typeface="MV Boli"/>' + #13 + ' <a:font script="Deva" typeface="Mangal"/>' + #13 + ' <a:font script="Telu" typeface="Gautami"/>' + #13 + ' <a:font script="Taml" typeface="Latha"/>' + #13 + ' <a:font script="Syrc" typeface="Estrangelo Edessa"/>' + #13 + ' <a:font script="Orya" typeface="Kalinga"/>' + #13 + ' <a:font script="Mlym" typeface="Kartika"/>' + #13 + ' <a:font script="Laoo" typeface="DokChampa"/>' + #13 + ' <a:font script="Sinh" typeface="Iskoola Pota"/>' + #13 + ' <a:font script="Mong" typeface="Mongolian Baiti"/>' + #13 + ' <a:font script="Viet" typeface="Times New Roman"/>' + #13 + ' <a:font script="Uigh" typeface="Microsoft Uighur"/>' + #13 + ' </a:majorFont>' + #13 + ' <a:minorFont>' + #13 + ' <a:latin typeface="Calibri"/>' + #13 + ' <a:ea typeface=""/>' + #13 + ' <a:cs typeface=""/>' + #13 + ' <a:font script="Jpan" typeface="?? ?????"/>' + #13 + ' <a:font script="Hang" typeface="?? ??"/>' + #13 + ' <a:font script="Hans" typeface="??"/>' + #13 + ' <a:font script="Hant" typeface="????"/>' + #13 + ' <a:font script="Arab" typeface="Arial"/>' + #13 + ' <a:font script="Hebr" typeface="Arial"/>' + #13 + ' <a:font script="Thai" typeface="Tahoma"/>' + #13 + ' <a:font script="Ethi" typeface="Nyala"/>' + #13 + ' <a:font script="Beng" typeface="Vrinda"/>' + #13 + ' <a:font script="Gujr" typeface="Shruti"/>' + #13 + ' <a:font script="Khmr" typeface="DaunPenh"/>' + #13 + ' <a:font script="Knda" typeface="Tunga"/>' + #13 + ' <a:font script="Guru" typeface="Raavi"/>' + #13 + ' <a:font script="Cans" typeface="Euphemia"/>' + #13 + ' <a:font script="Cher" typeface="Plantagenet Cherokee"/>' + #13 + ' <a:font script="Yiii" typeface="Microsoft Yi Baiti"/>' + #13 + ' <a:font script="Tibt" typeface="Microsoft Himalaya"/>' + #13 + ' <a:font script="Thaa" typeface="MV Boli"/>' + #13 + ' <a:font script="Deva" typeface="Mangal"/>' + #13 + ' <a:font script="Telu" typeface="Gautami"/>' + #13 + ' <a:font script="Taml" typeface="Latha"/>' + #13 + ' <a:font script="Syrc" typeface="Estrangelo Edessa"/>' + #13 + ' <a:font script="Orya" typeface="Kalinga"/>' + #13 + ' <a:font script="Mlym" typeface="Kartika"/>' + #13 + ' <a:font script="Laoo" typeface="DokChampa"/>' + #13 + ' <a:font script="Sinh" typeface="Iskoola Pota"/>' + #13 + ' <a:font script="Mong" typeface="Mongolian Baiti"/>' + #13 + ' <a:font script="Viet" typeface="Arial"/>' + #13 + ' <a:font script="Uigh" typeface="Microsoft Uighur"/>' + #13 + ' </a:minorFont>' + #13 + ' </a:fontScheme>' + #13 + ' <a:fmtScheme name="Office">' + #13 + ' <a:fillStyleLst>' + #13 + ' <a:solidFill>' + #13 + ' <a:schemeClr val="phClr"/>' + #13 + ' </a:solidFill>' + #13 + ' <a:gradFill rotWithShape="1">' + #13 + ' <a:gsLst>' + #13 + ' <a:gs pos="0">' + #13 + ' <a:schemeClr val="phClr">' + #13 + ' <a:tint val="50000"/>' + #13 + ' <a:satMod val="300000"/>' + #13 + ' </a:schemeClr>' + #13 + ' </a:gs>' + #13 + ' <a:gs pos="35000">' + #13 + ' <a:schemeClr val="phClr">' + #13 + ' <a:tint val="37000"/>' + #13 + ' <a:satMod val="300000"/>' + #13 + ' </a:schemeClr>' + #13 + ' </a:gs>' + #13 + ' <a:gs pos="100000">' + #13 + ' <a:schemeClr val="phClr">' + #13 + ' <a:tint val="15000"/>' + #13 + ' <a:satMod val="350000"/>' + #13 + ' </a:schemeClr>' + #13 + ' </a:gs>' + #13 + ' </a:gsLst>' + #13 + ' <a:lin ang="16200000" scaled="1"/>' + #13 + ' </a:gradFill>' + #13 + ' <a:gradFill rotWithShape="1">' + #13 + ' <a:gsLst>' + #13 + ' <a:gs pos="0">' + #13 + ' <a:schemeClr val="phClr">' + #13 + ' <a:shade val="51000"/>' + #13 + ' <a:satMod val="130000"/>' + #13 + ' </a:schemeClr>' + #13 + ' </a:gs>' + #13 + ' <a:gs pos="80000">' + #13 + ' <a:schemeClr val="phClr">' + #13 + ' <a:shade val="93000"/>' + #13 + ' <a:satMod val="130000"/>' + #13 + ' </a:schemeClr>' + #13 + ' </a:gs>' + #13 + ' <a:gs pos="100000">' + #13 + ' <a:schemeClr val="phClr">' + #13 + ' <a:shade val="94000"/>' + #13 + ' <a:satMod val="135000"/>' + #13 + ' </a:schemeClr>' + #13 + ' </a:gs>' + #13 + ' </a:gsLst>' + #13 + ' <a:lin ang="16200000" scaled="0"/>' + #13 + ' </a:gradFill>' + #13 + ' </a:fillStyleLst>' + #13 + ' <a:lnStyleLst>' + #13 + ' <a:ln w="9525" cap="flat" cmpd="sng" algn="ctr">' + #13 + ' <a:solidFill>' + #13 + ' <a:schemeClr val="phClr">' + #13 + ' <a:shade val="95000"/>' + #13 + ' <a:satMod val="105000"/>' + #13 + ' </a:schemeClr>' + #13 + ' </a:solidFill>' + #13 + ' <a:prstDash val="solid"/>' + #13 + ' </a:ln>' + #13 + ' <a:ln w="25400" cap="flat" cmpd="sng" algn="ctr">' + #13 + ' <a:solidFill>' + #13 + ' <a:schemeClr val="phClr"/>' + #13 + ' </a:solidFill>' + #13 + ' <a:prstDash val="solid"/>' + #13 + ' </a:ln>' + #13 + ' <a:ln w="38100" cap="flat" cmpd="sng" algn="ctr">' + #13 + ' <a:solidFill>' + #13 + ' <a:schemeClr val="phClr"/>' + #13 + ' </a:solidFill>' + #13 + ' <a:prstDash val="solid"/>' + #13 + ' </a:ln>' + #13 + ' </a:lnStyleLst>' + #13 + ' <a:effectStyleLst>' + #13 + ' <a:effectStyle>' + #13 + ' <a:effectLst>' + #13 + ' <a:outerShdw blurRad="40000" dist="20000" dir="5400000" rotWithShape="0">' + #13 + ' <a:srgbClr val="000000">' + #13 + ' <a:alpha val="38000"/>' + #13 + ' </a:srgbClr>' + #13 + ' </a:outerShdw>' + #13 + ' </a:effectLst>' + #13 + ' </a:effectStyle>' + #13 + ' <a:effectStyle>' + #13 + ' <a:effectLst>' + #13 + ' <a:outerShdw blurRad="40000" dist="23000" dir="5400000" rotWithShape="0">' + #13 + ' <a:srgbClr val="000000">' + #13 + ' <a:alpha val="35000"/>' + #13 + ' </a:srgbClr>' + #13 + ' </a:outerShdw>' + #13 + ' </a:effectLst>' + #13 + ' </a:effectStyle>' + #13 + ' <a:effectStyle>' + #13 + ' <a:effectLst>' + #13 + ' <a:outerShdw blurRad="40000" dist="23000" dir="5400000" rotWithShape="0">' + #13 + ' <a:srgbClr val="000000">' + #13 + ' <a:alpha val="35000"/>' + #13 + ' </a:srgbClr>' + #13 + ' </a:outerShdw>' + #13 + ' </a:effectLst>' + #13 + ' <a:scene3d>' + #13 + ' <a:camera prst="orthographicFront">' + #13 + ' <a:rot lat="0" lon="0" rev="0"/>' + #13 + ' </a:camera>' + #13 + ' <a:lightRig rig="threePt" dir="t">' + #13 + ' <a:rot lat="0" lon="0" rev="1200000"/>' + #13 + ' </a:lightRig>' + #13 + ' </a:scene3d>' + #13 + ' <a:sp3d>' + #13 + ' <a:bevelT w="63500" h="25400"/>' + #13 + ' </a:sp3d>' + #13 + ' </a:effectStyle>' + #13 + ' </a:effectStyleLst>' + #13 + ' <a:bgFillStyleLst>' + #13 + ' <a:solidFill>' + #13 + ' <a:schemeClr val="phClr"/>' + #13 + ' </a:solidFill>' + #13 + ' <a:gradFill rotWithShape="1">' + #13 + ' <a:gsLst>' + #13 + ' <a:gs pos="0">' + #13 + ' <a:schemeClr val="phClr">' + #13 + ' <a:tint val="40000"/>' + #13 + ' <a:satMod val="350000"/>' + #13 + ' </a:schemeClr>' + #13 + ' </a:gs>' + #13 + ' <a:gs pos="40000">' + #13 + ' <a:schemeClr val="phClr">' + #13 + ' <a:tint val="45000"/>' + #13 + ' <a:shade val="99000"/>' + #13 + ' <a:satMod val="350000"/>' + #13 + ' </a:schemeClr>' + #13 + ' </a:gs>' + #13 + ' <a:gs pos="100000">' + #13 + ' <a:schemeClr val="phClr">' + #13 + ' <a:shade val="20000"/>' + #13 + ' <a:satMod val="255000"/>' + #13 + ' </a:schemeClr>' + #13 + ' </a:gs>' + #13 + ' </a:gsLst>' + #13 + ' <a:path path="circle">' + #13 + ' <a:fillToRect l="50000" t="-80000" r="50000" b="180000"/>' + #13 + ' </a:path>' + #13 + ' </a:gradFill>' + #13 + ' <a:gradFill rotWithShape="1">' + #13 + ' <a:gsLst>' + #13 + ' <a:gs pos="0">' + #13 + ' <a:schemeClr val="phClr">' + #13 + ' <a:tint val="80000"/>' + #13 + ' <a:satMod val="300000"/>' + #13 + ' </a:schemeClr>' + #13 + ' </a:gs>' + #13 + ' <a:gs pos="100000">' + #13 + ' <a:schemeClr val="phClr">' + #13 + ' <a:shade val="30000"/>' + #13 + ' <a:satMod val="200000"/>' + #13 + ' </a:schemeClr>' + #13 + ' </a:gs>' + #13 + ' </a:gsLst>' + #13 + ' <a:path path="circle">' + #13 + ' <a:fillToRect l="50000" t="50000" r="50000" b="50000"/>' + #13 + ' </a:path>' + #13 + ' </a:gradFill>' + #13 + ' </a:bgFillStyleLst>' + #13 + ' </a:fmtScheme>' + #13 + ' </a:themeElements>' + #13 + ' <a:objectDefaults/>' + #13 + ' <a:extraClrSchemeLst/>' + #13 + '</a:theme>'; implementation end.
40.834983
104
0.471268
47a6448afda86b3060cfbd9f39317108e6f88b04
252
pas
Pascal
misc/0050.pas
nickelsworth/swag
7c21c0da2291fc249b9dc5cfe121a7672a4ffc08
[ "BSD-2-Clause" ]
11
2015-12-12T05:13:15.000Z
2020-10-14T13:32:08.000Z
misc/0050.pas
nickelsworth/swag
7c21c0da2291fc249b9dc5cfe121a7672a4ffc08
[ "BSD-2-Clause" ]
null
null
null
misc/0050.pas
nickelsworth/swag
7c21c0da2291fc249b9dc5cfe121a7672a4ffc08
[ "BSD-2-Clause" ]
8
2017-05-05T05:24:01.000Z
2021-07-03T20:30:09.000Z
{ MARTIN LARSEN There are at least two nice features in BP7: BREAK and CONTINUE: } Repeat Inc(Count); if Odd(Count) then Continue; { Go to start of loop } if Count = 10 then Break; { Go to sentence just after loop } Until False; 
21
66
0.662698
470f2c8db6639df8f98b5e72cd26cc4642302a64
1,359
pas
Pascal
Components/JVCL/devtools/PackagesGenerator/FormTypeDialog.pas
sabatex/Delphi
0efbe6eb38bf8aa2bf269d1866741266e90b9cbf
[ "MIT" ]
null
null
null
Components/JVCL/devtools/PackagesGenerator/FormTypeDialog.pas
sabatex/Delphi
0efbe6eb38bf8aa2bf269d1866741266e90b9cbf
[ "MIT" ]
null
null
null
Components/JVCL/devtools/PackagesGenerator/FormTypeDialog.pas
sabatex/Delphi
0efbe6eb38bf8aa2bf269d1866741266e90b9cbf
[ "MIT" ]
1
2019-12-24T08:39:18.000Z
2019-12-24T08:39:18.000Z
unit FormTypeDialog; {$I jvcl.inc} interface uses Windows, Messages, SysUtils, {$IFDEF COMPILER6_UP}Variants, {$ENDIF}Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons; type TfrmFormType = class(TForm) bbtOk: TBitBtn; lblUnable: TLabel; lblFileName: TLabel; lblDeclarationIs: TLabel; lblDeclaration: TLabel; cmbType: TComboBox; lblPlease: TLabel; private { Private declarations } public { Public declarations } procedure EnsureCorrectType(var TypeName : string; FileName : string; declaration : string); end; var frmFormType: TfrmFormType; implementation {$R *.dfm} { TfrmFormType } procedure TfrmFormType.EnsureCorrectType(var TypeName: string; FileName : string; declaration : string); begin if (TypeName <> 'TForm') and (TypeName <> 'TJvForm') and (TypeName <> 'TFrame') and (TypeName <> 'TDataModule') then begin lblFileName.Caption := FileName; lblDeclaration.Caption := declaration; // try to guess from the filename if Copy(FileName, Length(FileName)-8, 5) = 'Frame' then cmbType.Text := 'TFrame'; if (Copy(FileName, Length(FileName)-7, 4) = 'Form') or (Copy(FileName, Length(FileName)-9, 6) = 'Dialog') then cmbType.Text := 'TForm'; // show dialog ShowModal; TypeName := cmbType.Text; end; end; end.
23.033898
105
0.674025
c355aeb8b1059f652b433b2e224be5d72269ae43
1,365
pas
Pascal
sources/chHash.CRC.CRC11.pas
vampirsoft/CryptoHash
bd8eb1fc2f8c8b63c3cb52b47908b7fbadab4be4
[ "MIT" ]
null
null
null
sources/chHash.CRC.CRC11.pas
vampirsoft/CryptoHash
bd8eb1fc2f8c8b63c3cb52b47908b7fbadab4be4
[ "MIT" ]
null
null
null
sources/chHash.CRC.CRC11.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.CRC11; {$INCLUDE CryptoHash.inc} interface uses {$IF DEFINED(SUPPORTS_INTERFACES)} chHash.CRC; {$ELSE ~ NOT SUPPORTS_INTERFACES} chHash.CRC.CRC11.Impl; {$ENDIF ~ SUPPORTS_INTERFACES} type {$IF DEFINED(SUPPORTS_INTERFACES)} IchCrc11 = interface(IchCrc<Word>) ['{E6ADB11F-1F4C-4321-9EB4-CC9EFE38D058}'] end; {$ELSE ~ NOT SUPPORTS_INTERFACES} TchCrc11 = chHash.CRC.CRC11.Impl.TchCrc11; {$ENDIF ~ SUPPORTS_INTERFACES} const Bits10Mask = Word($7FF); implementation end.
34.125
83
0.403663
fcf77d654fcc542f0a1924a24770a83b8f977832
15,977
pas
Pascal
src/Libs/Protocol/Implementations/Http/Libmicrohttpd/MhdProcessorImpl.pas
atkins126/fano
472679437cb42637b0527dda8255ec52a3e1e953
[ "MIT" ]
null
null
null
src/Libs/Protocol/Implementations/Http/Libmicrohttpd/MhdProcessorImpl.pas
atkins126/fano
472679437cb42637b0527dda8255ec52a3e1e953
[ "MIT" ]
null
null
null
src/Libs/Protocol/Implementations/Http/Libmicrohttpd/MhdProcessorImpl.pas
atkins126/fano
472679437cb42637b0527dda8255ec52a3e1e953
[ "MIT" ]
null
null
null
{*! * Fano Web Framework (https://fanoframework.github.io) * * @link https://github.com/fanoframework/fano * @copyright Copyright (c) 2018 - 2020 Zamrony P. Juhara * @license https://github.com/fanoframework/fano/blob/master/LICENSE (MIT) *} unit MhdProcessorImpl; interface {$MODE OBJFPC} {$H+} uses libmicrohttpd, StreamAdapterIntf, CloseableIntf, RunnableIntf, RunnableWithDataNotifIntf, ProtocolProcessorIntf, StreamIdIntf, ReadyListenerIntf, DataAvailListenerIntf, EnvironmentIntf, MhdConnectionAwareIntf, MhdSvrConfigTypes; type (*!----------------------------------------------- * Class which can process request from libmicrohttpd web server * * @author Zamrony P. Juhara <zamronypj@yahoo.com> *-----------------------------------------------*) TMhdProcessor = class(TInterfacedObject, IProtocolProcessor, IRunnable, IRunnableWithDataNotif) private fSvrConfig : TMhdSvrConfig; fRequestReadyListener : IReadyListener; fDataListener : IDataAvailListener; fStdIn : IStreamAdapter; fConnectionAware : IMhdConnectionAware; procedure resetInternalVars(); procedure waitUntilTerminate(); function buildEnv( aconnection : PMHD_Connection; aurl : pcchar; amethod : pcchar; aversion : pcchar ): ICGIEnvironment; function handleReq( aconnection : PMHD_Connection; aurl : pcchar; amethod : pcchar; aversion : pcchar; aupload_data : pcchar; aupload_data_size : psize_t; aptr : ppointer ): cint; function handleFileNotFoundReq( aconnection : PMHD_Connection; aurl : pcchar; amethod : pcchar; aversion : pcchar; aupload_data : pcchar; aupload_data_size : psize_t; aptr : ppointer ): cint; function handleStaticFileReq( aconnection : PMHD_Connection; aurl : pcchar; amethod : pcchar; aversion : pcchar; aupload_data : pcchar; aupload_data_size : psize_t; aptr : ppointer ): cint; function tryRun() : IRunnable; public constructor create( const aConnectionAware : IMhdConnectionAware; const svrConfig : TMhdSvrConfig ); destructor destroy(); override; (*!------------------------------------------------ * process request stream *-----------------------------------------------*) function process( const stream : IStreamAdapter; const streamCloser : ICloseable; const streamId : IStreamId ) : boolean; (*!------------------------------------------------ * get StdIn stream for complete request *-----------------------------------------------*) function getStdIn() : IStreamAdapter; (*!------------------------------------------------ * set listener to be notified when request is ready *----------------------------------------------- * @return current instance *-----------------------------------------------*) function setReadyListener(const listener : IReadyListener) : IProtocolProcessor; (*!------------------------------------------------ * get number of bytes of complete request based * on information buffer *----------------------------------------------- * @return number of bytes of complete request *-----------------------------------------------*) function expectedSize(const buff : IStreamAdapter) : int64; (*!------------------------------------------------ * run it *------------------------------------------------- * @return current instance *-------------------------------------------------*) function run() : IRunnable; (*!------------------------------------------------ * set instance of class that will be notified when * data is available *----------------------------------------------- * @param dataListener, class that wish to be notified * @return true current instance *-----------------------------------------------*) function setDataAvailListener(const dataListener : IDataAvailListener) : IRunnableWithDataNotif; end; implementation uses Classes, BaseUnix, SysUtils, TermSignalImpl, KeyValueEnvironmentImpl, MhdParamKeyValuePairImpl, StreamAdapterImpl, NullStreamAdapterImpl, FileUtils; constructor TMhdProcessor.create( const aConnectionAware : IMhdConnectionAware; const svrConfig : TMhdSvrConfig ); begin inherited create(); fConnectionAware := aConnectionAware; fSvrConfig := svrConfig; fRequestReadyListener := nil; fDataListener := nil; fStdIn := nil; end; destructor TMhdProcessor.destroy(); begin resetInternalVars(); inherited destroy(); end; procedure TMhdProcessor.resetInternalVars(); begin fRequestReadyListener := nil; fDataListener := nil; fStdIn := nil; fConnectionAware := nil; end; (*!------------------------------------------------ * process request stream *-----------------------------------------------*) function TMhdProcessor.process( const stream : IStreamAdapter; const streamCloser : ICloseable; const streamId : IStreamId ) : boolean; begin //intentationally does nothing, because libmicrohttpd //already does stream parsing so this is not relevant result := true; end; (*!------------------------------------------------ * get StdIn stream for complete request *-----------------------------------------------*) function TMhdProcessor.getStdIn() : IStreamAdapter; begin result := fStdIn; end; (*!------------------------------------------------ * set listener to be notified weh request is ready *----------------------------------------------- * @return current instance *-----------------------------------------------*) function TMhdProcessor.setReadyListener(const listener : IReadyListener) : IProtocolProcessor; begin fRequestReadyListener := listener; result := self; end; (*!------------------------------------------------ * get number of bytes of complete request based * on information buffer *----------------------------------------------- * @return number of bytes of complete request *-----------------------------------------------*) function TMhdProcessor.expectedSize(const buff : IStreamAdapter) : int64; begin result := 0; end; procedure TMhdProcessor.waitUntilTerminate(); var fds : TFDSet; begin fds := default(TFDSet); fpfd_zero(fds); //terminatePipeIn will be ready for IO when application is terminated //see TermSignalImpl unit fpfd_set(terminatePipeIn, FDS); //wait forever until terminatePipeIn changes fpSelect(terminatePipeIn + 1, @fds, nil, nil, nil); end; //BaseUnix and libmicrohttpd both declared pcchar type //here any pcchar use libmicrohttpd.pcchar, //otherwise FPC complains about type mismatch function handleRequestCallback( acontext : pointer; aconnection : PMHD_Connection; aurl : libmicrohttpd.pcchar; amethod : libmicrohttpd.pcchar; aversion : libmicrohttpd.pcchar; aupload_data : libmicrohttpd.pcchar; aupload_data_size : libmicrohttpd.psize_t; aptr : ppointer ): cint; cdecl; begin result := TMhdProcessor(acontext).handleReq( aconnection, aurl, amethod, aversion, aupload_data, aupload_data_size, aptr ); end; function TMhdProcessor.buildEnv( aconnection : PMHD_Connection; aurl : libmicrohttpd.pcchar; amethod : libmicrohttpd.pcchar; aversion : libmicrohttpd.pcchar ): ICGIEnvironment; var mhdData : TMhdData; begin mhdData.connection := aconnection; mhdData.url := aurl; mhdData.method := amethod; mhdData.version := aversion; mhdData.serverConfig := fSvrConfig; result := TKeyValueEnvironment.create( TMhdParamKeyValuePair.create(mhdData) ); end; function TMhdProcessor.handleReq( aconnection : PMHD_Connection; aurl : libmicrohttpd.pcchar; amethod : libmicrohttpd.pcchar; aversion : libmicrohttpd.pcchar; aupload_data : libmicrohttpd.pcchar; aupload_data_size : psize_t; aptr : ppointer ): cint; var bufStat: TStat; isStaticFileRequest : boolean; fname : string; method : string; url : string; begin url := string(pchar(aurl)); method := string(pchar(amethod)); fname := fSvrConfig.documentRoot + url; isStaticFileRequest := ((method = MHD_HTTP_METHOD_GET) or (method = MHD_HTTP_METHOD_HEAD)) and (url <> '/') and (0 = fpStat(pchar(fname), bufStat)); if isStaticFileRequest then begin result := handleStaticFileReq( aconnection, aurl, amethod, aversion, aupload_data, aupload_data_size, aptr ); end else begin result := handleFileNotFoundReq( aconnection, aurl, amethod, aversion, aupload_data, aupload_data_size, aptr ); end; end; function TMhdProcessor.handleFileNotFoundReq( aconnection : PMHD_Connection; aurl : libmicrohttpd.pcchar; amethod : libmicrohttpd.pcchar; aversion : libmicrohttpd.pcchar; aupload_data : libmicrohttpd.pcchar; aupload_data_size : psize_t; aptr : ppointer ): cint; var mhdEnv : ICGIEnvironment; mhdStream : IStreamAdapter; mem : TMemoryStream; begin result := MHD_NO; if (aptr^ = nil) then begin //begin of request mem := TMemoryStream.create(); if (aupload_data_size^ > 0) then begin mem.writeBuffer(aupload_data^, aupload_data_size^); aupload_data_size^ := 0; end; aptr^ := mem; result := MHD_YES; end else begin mem := TMemoryStream(aptr^); if (aupload_data_size^ = 0) then begin //request is complete //set seek position to beginning to avoid EReadError mem.position := 0; fConnectionAware.connection := aconnection; mhdEnv := buildEnv(aconnection, aurl, amethod, aversion); //wrap memory stream as IStreamAdapter and let //them free memory when finished mhdStream := TStreamAdapter.create(mem); fRequestReadyListener.ready( //we will not use socket stream as we will have our own IStdOut //that write output with libmicrohttpd TNullStreamAdapter.create(), mhdEnv, mhdStream ); end else begin mem.writeBuffer(aupload_data^, aupload_data_size^); aupload_data_size^ := 0; end; result := MHD_YES; end; end; function TMhdProcessor.handleStaticFileReq( aconnection : PMHD_Connection; aurl : libmicrohttpd.pcchar; amethod : libmicrohttpd.pcchar; aversion : libmicrohttpd.pcchar; aupload_data : libmicrohttpd.pcchar; aupload_data_size : psize_t; aptr : ppointer ): cint; const beginRequestMarker : cint = 0; var fd : cint; bufStat : TStat; response : PMHD_Response; fname : string; begin result := MHD_NO; if (@beginRequestMarker <> aptr^) then begin //this is begin of request, just skip processing aptr^ := @beginRequestMarker; exit(MHD_YES); end; fname := fSvrConfig.documentRoot + string(pchar(aurl)); fpStat(pchar(fname), bufStat); fd := fpOpen(pchar(fname), O_RdOnly); response := MHD_create_response_from_fd(bufStat.st_size, fd); result := MHD_queue_response (aconnection, MHD_HTTP_OK, response); MHD_destroy_response (response); end; (*!------------------------------------------------ * run it *------------------------------------------------- * @return current instance *-------------------------------------------------*) function TMhdProcessor.tryRun() : IRunnable; var svrDaemon : PMHD_Daemon; tlsKey, tlsCert : string; begin if fSvrConfig.useTLS then begin tlsKey := readFile(fSvrConfig.tlsKey); tlsCert := readFile(fSvrConfig.tlsCert); svrDaemon := MHD_start_daemon( //TODO: MHD_USE_SSL is now deprecated and replaced with MHD_USE_TLS MHD_USE_EPOLL_INTERNALLY_LINUX_ONLY or MHD_USE_SSL, fSvrConfig.port, nil, nil, @handleRequestCallback, self, MHD_OPTION_CONNECTION_TIMEOUT, cuint(fSvrConfig.Timeout), MHD_OPTION_HTTPS_MEM_KEY, libmicrohttpd.pcchar(tlsKey), MHD_OPTION_HTTPS_MEM_CERT, libmicrohttpd.pcchar(tlsCert), MHD_OPTION_END ); end else begin svrDaemon := MHD_start_daemon( MHD_USE_EPOLL_INTERNALLY_LINUX_ONLY, fSvrConfig.port, nil, nil, @handleRequestCallback, self, MHD_OPTION_CONNECTION_TIMEOUT, cuint(fSvrConfig.Timeout), MHD_OPTION_END ); end; if svrDaemon <> nil then begin waitUntilTerminate(); MHD_stop_daemon(svrDaemon); end; result := self; end; (*!------------------------------------------------ * run it *------------------------------------------------- * @return current instance *-------------------------------------------------*) function TMhdProcessor.run() : IRunnable; begin try result := tryRun(); except on e: Exception do begin writeln('Exception: ', e.ClassName); writeln('Message: ', e.Message); end; end; end; (*!------------------------------------------------ * set instance of class that will be notified when * data is available *----------------------------------------------- * @param dataListener, class that wish to be notified * @return true current instance *-----------------------------------------------*) function TMhdProcessor.setDataAvailListener(const dataListener : IDataAvailListener) : IRunnableWithDataNotif; begin fDataListener := dataListener; result := self; end; end.
31.763419
114
0.505539
fc52c1cdd6fb286025ef88ca6552bed1577afcea
18,125
pas
Pascal
Libraries/DDuce/Modules/Editor/DDuce.Editor.Commands.pas
jpluimers/Concepts
78598ab6f1b4206bbc4ed9c7bc15705ad4ade1fe
[ "Apache-2.0" ]
2
2020-01-04T08:19:10.000Z
2020-02-19T22:25:38.000Z
Libraries/DDuce/Modules/Editor/DDuce.Editor.Commands.pas
jpluimers/Concepts
78598ab6f1b4206bbc4ed9c7bc15705ad4ade1fe
[ "Apache-2.0" ]
null
null
null
Libraries/DDuce/Modules/Editor/DDuce.Editor.Commands.pas
jpluimers/Concepts
78598ab6f1b4206bbc4ed9c7bc15705ad4ade1fe
[ "Apache-2.0" ]
1
2020-02-19T22:25:42.000Z
2020-02-19T22:25:42.000Z
{ Copyright (C) 2013-2016 Tim Sinaeve tim.sinaeve@gmail.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. } unit DDuce.Editor.Commands; { Implements IEditorCommands which represents a set of commands that can be executed on the active editor view. Commands are intended to be called by actions and are typically associated with an IEditorView instance. } interface uses Winapi.Windows, System.Classes, System.SysUtils, DDuce.Editor.Interfaces; type TEditorCommands = class(TComponent, IEditorCommands) strict private function GetEvents: IEditorEvents; function GetManager: IEditorManager; function GetSearchEngine: IEditorSearchEngine; function GetSettings: IEditorSettings; function GetView: IEditorView; function StripComments( const AString : string; const AHighlighter : string ): string; function MergeBlankLines(const AString: string): string; function GuessHighlighterType( const AText: string ): string; overload; function IsXML( const AString: string ): Boolean; function IsPAS( const AString: string ): Boolean; strict protected procedure OpenFileAtCursor; procedure ToggleHighlighter; procedure AssignHighlighter(const AName: string); procedure CopyToClipboard; procedure CreateDesktopLink; procedure CompressSpace; procedure CompressWhitespace; procedure UpperCaseSelection; procedure LowerCaseSelection; procedure PascalStringFromSelection; procedure QuoteLinesInSelection(ADelimit : Boolean = False); procedure DequoteLinesInSelection; procedure QuoteSelection; procedure DequoteSelection; procedure Base64FromSelection(ADecode: Boolean = False); procedure URLFromSelection(ADecode: Boolean = False); procedure XMLFromSelection(ADecode: Boolean = False); procedure ConvertTabsToSpacesInSelection; procedure SyncEditSelection; procedure Save; function SaveFile( const AFileName : string = ''; AShowDialog : Boolean = False ): Boolean; procedure SaveAll; procedure AdjustFontSize(AOffset: Integer); procedure AlignSelection( const AToken : string; ACompressWS : Boolean; AInsertSpaceBeforeToken : Boolean; AInsertSpaceAfterToken : Boolean; AAlignInParagraphs : Boolean ); procedure MergeBlankLinesInSelection; procedure StripCommentsFromSelection; procedure StripMarkupFromSelection; procedure StripCharsFromSelection( AFirst : Boolean; ALast : Boolean ); procedure GuessHighlighterType; overload; procedure Indent; procedure UnIndent; procedure ToggleLineComment; procedure ToggleBlockComment; procedure InsertTextAtCaret(const AText: string); procedure FormatCode; procedure SortSelectedLines; procedure SmartSelect; function SelectBlockAroundCursor( const AStartTag : string; const AEndTag : string; AIncludeStartTag : Boolean; AIncludeEndTag : Boolean ): Boolean; procedure FindNext; procedure FindPrevious; property View: IEditorView read GetView; property Events: IEditorEvents read GetEvents; property Settings: IEditorSettings read GetSettings; property SearchEngine: IEditorSearchEngine read GetSearchEngine; property Manager: IEditorManager read GetManager; end; implementation uses Winapi.ShlObj, System.Math, System.StrUtils, Vcl.Forms, BCEditor.Editor.KeyCommands, BCEditor.Types, DDuce.Editor.Highlighters, DDuce.Editor.Resources, DDuce.Editor.Utils, DDuce.Editor.CommentStripper; {$REGION'property access mehods'} function TEditorCommands.GetEvents: IEditorEvents; begin Result := Manager.Events; end; function TEditorCommands.GetManager: IEditorManager; begin Result := Owner as IEditorManager; end; function TEditorCommands.GetSearchEngine: IEditorSearchEngine; begin Result := Manager.SearchEngine; end; function TEditorCommands.GetSettings: IEditorSettings; begin Result := Manager.Settings; end; function TEditorCommands.GetView: IEditorView; begin Result := Manager.ActiveView; end; { TODO: Use interfaces like (cfr. ICodeFormatter) } function TEditorCommands.StripComments(const AString: string; const AHighlighter: string): string; var SSIn : TStringStream; SSOut : TStringStream; CS : TCustomCommentStripper; C : Char; S : string; begin CS := nil; if AnsiMatchStr(AHighlighter, [HL_PAS]) then CS := TPasCommentStripper.Create(nil) else if AnsiMatchStr(AHighlighter, [HL_CPP, HL_JAVA, HL_CS]) then CS := TCPPCommentStripper.Create(nil); if Assigned(CS) then begin try SSIn := TStringStream.Create(''); try SSIn.WriteString(AString); C := #0; SSIn.Write(C, 1); SSIn.Position := 0; SSOut := TStringStream.Create(''); try CS.InStream := SSIn; CS.OutStream := SSOut; CS.Parse; SSOut.Position := 0; S := SSOut.ReadString(SSOut.Size); S := MergeBlankLines(S); Result := S; finally SSOut.Free; end; finally SSIn.Free; end; finally CS.Free; end; end else Result := AString; end; function TEditorCommands.MergeBlankLines(const AString: string): string; var SL : TStrings; begin SL := TStringList.Create; try SL.Text := AString; DDuce.Editor.Utils.MergeBlankLines(SL); // remove first blank line if (SL.Count > 0) and (Trim(SL[0]) = '') then SL.Delete(0); // remove last blank line if (SL.Count > 0) and (Trim(SL[SL.Count - 1]) = '') then SL.Delete(SL.Count - 1); Result := SL.Text; finally SL.Free; end; end; function TEditorCommands.GuessHighlighterType(const AText: string): string; var SL : TStringList; S : string; begin Result := ''; if Length(AText) > 0 then begin SL := TStringList.Create; try SL.Text := Copy(AText, 0, 2000); if SL.Count > 0 then begin S := Trim(SL[0]); if IsXML(S) then Result := HL_XML else begin S := SL.Text; if IsPAS(S) then Result := HL_PAS else if IsLFM(S) then Result := HL_DFM end; if IsLOG(AText) then Result := HL_LOG else if IsHTML(AText) then Result := HL_HTML else if IsXML(AText) then Result := HL_XML else if IsSQL(AText) then Result := HL_SQL; end finally SL.Free; end; end; end; function TEditorCommands.IsXML(const AString: string): Boolean; const MATCH = '^\<\?xml version\=.+\?\>$'; begin Result := MatchRegExpr(AString, MATCH, False); end; function TEditorCommands.IsPAS(const AString: string): Boolean; const MATCH = '^(unit|program|package|library) .+;$'; var SL : TStrings; S : string; B : Boolean; begin Result := False; S := StripComments(AString, HL_PAS); SL := TStringList.Create; try SL.Text := S; B := False; while not B and (SL.Count > 0) do begin if Trim(SL[0]) = '' then begin SL.Delete(0); B := False; end else B := True; end; if SL.Count > 0 then S := Trim(SL[0]); Result := MatchRegExpr(S, MATCH, False); finally SL.Free; end; end; {$ENDREGION} {$REGION'protected methods'} procedure TEditorCommands.OpenFileAtCursor; var FN : string; begin FN := ExtractFilePath(View.FileName) + View.CurrentWord + ExtractFileExt(View.FileName); if FileExists(FN) then Events.DoNew(FN); end; procedure TEditorCommands.ToggleHighlighter; var I : Integer; N : Integer; begin if Assigned(View.HighlighterItem) then begin I := View.HighlighterItem.Index; N := Manager.Highlighters.Count; View.HighlighterItem := Manager.Highlighters[(I + 1) mod N]; Settings.HighlighterType := View.HighlighterItem.Name; end; end; procedure TEditorCommands.AssignHighlighter(const AName: string); var HLI : THighlighterItem; begin if Assigned(Manager.Highlighters) then begin HLI := Manager.Highlighters.ItemsByName[AName]; if Assigned(HLI) then View.HighlighterItem := HLI else raise Exception.CreateFmt('Highlighter %s not found!', [AName]); end; end; procedure TEditorCommands.CopyToClipboard; begin View.Editor.CopyToClipboard; end; procedure TEditorCommands.CreateDesktopLink; //var // PIDL : LPItemIDList; // InFolder : array[0..MAX_PATH] of Char; // SL : TShellLink; begin // PIDL := nil; // SHGetSpecialFolderLocation(0, CSIDL_DESKTOPDIRECTORY, PIDL) ; // SHGetPathFromIDList(PIDL, InFolder) ; // SL.Filename := InFolder + '\' + ExtractFileName(View.FileName) + '.lnk'; // SL.WorkingDir := ExtractFilePath(SL.Filename); // SL.ShortcutTo := Application.ExeName; // SL.Parameters := View.FileName; // CreateShellLink(SL); end; procedure TEditorCommands.CompressSpace; begin View.SelectedText := DDuce.Editor.Utils.CompressSpace(View.SelectedText); end; procedure TEditorCommands.CompressWhitespace; begin View.SelectedText := DDuce.Editor.Utils.CompressWhitespace(View.SelectedText); end; procedure TEditorCommands.UpperCaseSelection; begin View.Editor.CommandProcessor(ecUpperCaseBlock, #0, nil); end; procedure TEditorCommands.LowerCaseSelection; begin View.Editor.CommandProcessor(ecLowerCaseBlock, #0, nil); end; procedure TEditorCommands.PascalStringFromSelection; begin View.SelectedText := PascalStringOf(View.SelectedText); end; procedure TEditorCommands.QuoteLinesInSelection(ADelimit: Boolean); begin if ADelimit then View.SelectedText := QuoteLinesAndDelimit(View.SelectedText) else View.SelectedText := QuoteLines(View.SelectedText); end; procedure TEditorCommands.DequoteLinesInSelection; begin View.SelectedText := DequoteLines(View.SelectedText); end; procedure TEditorCommands.QuoteSelection; begin View.SelectedText := AnsiQuotedStr(View.SelectedText, ''''); end; procedure TEditorCommands.DequoteSelection; begin View.SelectedText := AnsiDequotedStr(View.SelectedText, ''''); end; procedure TEditorCommands.Base64FromSelection(ADecode: Boolean); begin // Selection.Store(True, True); // if ADecode then // Selection.Text := DecodeStringBase64(Selection.Text) // else // Selection.Text := EncodeStringBase64(Selection.Text); // Selection.Restore; // View.Modified := True; end; procedure TEditorCommands.URLFromSelection(ADecode: Boolean); begin // Selection.Store(True, True); // if ADecode then // Selection.Text := URLDecode(Selection.Text) // else // Selection.Text := URLEncode(Selection.Text); // Selection.Restore; // View.Modified := True; end; procedure TEditorCommands.XMLFromSelection(ADecode: Boolean); begin // Selection.Store(True, True); // if ADecode then // Selection.Text := XMLDecode(Selection.Text) // else // Selection.Text := XMLEncode(Selection.Text); // Selection.Restore; // View.Modified := True; end; procedure TEditorCommands.ConvertTabsToSpacesInSelection; begin View.SelectedText := TabsToSpaces(View.SelectedText, Settings.EditorOptions.TabWidth); end; procedure TEditorCommands.SyncEditSelection; begin //View.Editor.CommandProcessor(ecEd ecSynPSyncroEdStart, '', nil); end; procedure TEditorCommands.Save; begin if View.IsFile then SaveFile(View.FileName) else begin View.Save; end; end; function TEditorCommands.SaveFile(const AFileName: string; AShowDialog: Boolean ): Boolean; begin // { TODO -oTS : Migrate implementation to here. }. Result := Manager.SaveFile(AFileName, AShowDialog); end; procedure TEditorCommands.SaveAll; var V : IEditorView; begin for V in Manager.Views do begin if V.Modified then begin if V.IsFile then begin Manager.SaveFile(V.FileName); end else V.Save; end; end; end; procedure TEditorCommands.AdjustFontSize(AOffset: Integer); begin Settings.EditorFont.Size := Settings.EditorFont.Size + AOffset; Settings.Apply; // needed to trigger settings changed event. end; { TODO -oTS : Align in paragraphs does not work! TODO -oTS : Align to leftmost/rightmost token not implemented! } procedure TEditorCommands.AlignSelection(const AToken: string; ACompressWS: Boolean; AInsertSpaceBeforeToken: Boolean; AInsertSpaceAfterToken: Boolean; AAlignInParagraphs: Boolean); begin // if View.SelectionAvailable then // begin // Selection.Store(True, True); // AlignLines( // Selection.Lines, // AToken, // ACompressWS, // AInsertSpaceBeforeToken, // AInsertSpaceAfterToken // ); // Selection.Restore; // end; end; procedure TEditorCommands.MergeBlankLinesInSelection; begin View.SelectedText := MergeBlankLines(View.SelectedText); end; procedure TEditorCommands.StripCommentsFromSelection; begin //View.Editor.KeyCommands //View.SelectedText := StripComments() end; { TODO -oTS : Not working! } procedure TEditorCommands.StripMarkupFromSelection; begin View.SelectedText := StripMarkup(View.SelectedText); end; { REMARK: Whitespace is ignored. This routine strips the first/last non-space char from each line in the selection. } procedure TEditorCommands.StripCharsFromSelection(AFirst: Boolean; ALast: Boolean); begin View.SelectedText := StripChars(View.SelectedText, AFirst, ALast); end; procedure TEditorCommands.GuessHighlighterType; var S : string; begin S := GuessHighlighterType(View.Text); if S <> '' then AssignHighlighter(S); end; procedure TEditorCommands.Indent; begin View.Editor.CommandProcessor(ecBlockIndent, #0, nil); end; procedure TEditorCommands.UnIndent; begin View.Editor.CommandProcessor(ecBlockUnindent, #0, nil); end; { Comments or uncomments selected code lines based on the active highlighter. } procedure TEditorCommands.ToggleLineComment; begin View.Editor.CommandProcessor(ecLineComment, #0, nil); end; { Comments/uncomments the selected block with the block comment tags for the current highlighter. } procedure TEditorCommands.ToggleBlockComment; begin View.Editor.CommandProcessor(ecBlockComment, #0, nil); end; procedure TEditorCommands.InsertTextAtCaret(const AText: string); begin View.Editor.InsertBlock( View.Editor.SelectionBeginPosition, View.Editor.SelectionEndPosition, PWideChar(AText), True ); end; procedure TEditorCommands.FormatCode; //var // HI : THighlighterItem; begin // HI := View.HighlighterItem; // if Assigned(HI) then // if Assigned(HI.CodeFormatter) then // begin // if not View.SelAvail then // begin // View.SelectAll; // end; // Selection.Store; // if Length(Trim(Selection.Text))>0 then // Selection.Text := HI.CodeFormatter.Format(Selection.Text); // Selection.Restore; // end // else // raise Exception.Create('No codeformatter for current highlighter'); end; procedure TEditorCommands.SortSelectedLines; begin View.Editor.BeginUndoBlock; View.Editor.Sort(soToggle); View.Editor.EndUndoBlock; end; { Makes a smart selection of a block around the cursor. } { TODO -oTS : Make this configurable per highlighter (see unit ts.Editor.CodeTags). } procedure TEditorCommands.SmartSelect; //var // HI : THighlighterItem; begin // HI := View.HighlighterItem; // if Assigned(HI) then // begin // if HI.Name = 'XML' then // SelectBlockAroundCursor('>', '<', False, False) // else if HI.Name = 'PAS' then // SelectBlockAroundCursor('begin', 'end', True, True) // else if HI.Name = 'LOG' then // SelectBlockAroundCursor('<XMLRoot>', '</XMLRoot>', True, True); // end; end; { Selects block of code around cursor between AStartTag and AEndTag. Used by the SmartSelect procedure. TODO: - support for nested AStartTag and AEndTag (ignore sublevels) } function TEditorCommands.SelectBlockAroundCursor(const AStartTag: string; const AEndTag: string; AIncludeStartTag: Boolean; AIncludeEndTag: Boolean): Boolean; var Pos : Integer; S : string; B : Boolean; I : Integer; N : Integer; begin N := 0; Result := False; if (AStartTag = '') or (AEndTag = '') then Exit; S := View.Text; Pos := View.SelStart; B := False; while not B and (Pos > 1) do begin N := Length(AStartTag); I := N; B := S[Pos] = AStartTag[I]; while B and (Pos > 1) and (I > 1) do begin Dec(I); Dec(Pos); B := S[Pos] = AStartTag[I]; end; if not B and (Pos > 1) then Dec(Pos); end; if B then begin if AIncludeStartTag then View.SelStart := Pos else View.SelStart := Pos + N; end; if B then begin Pos := View.SelStart; B := False; while not B and (Pos <= Length(S)) do begin N := Length(AEndTag); I := 1; B := S[Pos] = AEndTag[I]; while B and (Pos <= Length(S)) and (I < N) do begin Inc(I); Inc(Pos); B := S[Pos] = AEndTag[I]; end; if not B and (Pos <= Length(S)) then Inc(Pos); end; if B then begin if AIncludeEndTag then View.SelEnd := Pos + 1 else View.SelEnd := Pos - N + 1; end; end; Result := View.SelectionAvailable; end; procedure TEditorCommands.FindNext; begin View.Editor.FindNext; end; procedure TEditorCommands.FindPrevious; begin View.Editor.FindPrevious; end; {$ENDREGION} end.
24.198932
80
0.688828
c3387883818b1b921200e92b1008b3aba14605c2
38,690
pas
Pascal
source/extends/lua/LuaDBGServers.pas
gzwplato/miniedit
2e6f0e5f54e940b279137011a40a21ac61717468
[ "MIT" ]
null
null
null
source/extends/lua/LuaDBGServers.pas
gzwplato/miniedit
2e6f0e5f54e940b279137011a40a21ac61717468
[ "MIT" ]
null
null
null
source/extends/lua/LuaDBGServers.pas
gzwplato/miniedit
2e6f0e5f54e940b279137011a40a21ac61717468
[ "MIT" ]
1
2018-06-28T23:35:38.000Z
2018-06-28T23:35:38.000Z
unit LuaDBGServers; {$mode objfpc}{$H+} {** * Mini Edit * * @license MIT (http://www.gnu.org/licenses/mit.html) * @author Zaher Dirkey <zaher at parmaja dot com> *} { https://bitbucket.org/sylvanaar2/lua-for-idea/src/f554ad3b78e9/src/main/resources/mobdebug/?at=idea16 } {$ifdef WINDOWS} {.$DEFINE SAVELOG} {$endif} interface uses SysUtils, StrUtils, Classes, Contnrs, Dialogs, Variants, mnSockets, mnStreams, mnConnections, mnServers, mnXMLUtils, Base64, mnXMLRttiProfile, mnXMLNodes, SyncObjs, IniFiles, EditorDebugger, mnClasses; type TLuaDBGServer = class; TLuaDBGConnection = class; TLuaDBGConnectionClass = class of TLuaDBGConnection; TDebugCommandRespond = class(TmnXMLNodes) public Source: string; end; { TLuaDBGAction } TLuaDBGAction = class(TDebugCommand) private FConnection: TLuaDBGConnection; protected FTransactionID: integer; property Connection: TLuaDBGConnection read FConnection; procedure CheckError(Respond: TDebugCommandRespond); procedure Execute(Respond: TDebugCommandRespond); virtual; abstract; public end; TLuaDBGActionClass = class of TLuaDBGAction; TLuaDBGSpool = class(specialize GItems<TLuaDBGAction>) private public end; { TLuaDBGConnectionSpool } TLuaDBGConnectionSpool = class(TLuaDBGSpool) private FConnection: TLuaDBGConnection; public procedure Added(Action: TLuaDBGAction); override; end; TLuaDBGInit = class(TLuaDBGAction) protected procedure Created; override; public function GetCommand: string; override; procedure Execute(Respond: TDebugCommandRespond); override; end; { TLuaDBGFeatureSet } TLuaDBGFeatureSet = class(TLuaDBGAction) protected FName: string; FValue: string; procedure Execute(Respond: TDebugCommandRespond); override; public constructor CreateBy(vName, vValue: string); function GetCommand: string; override; end; { TLuaDBGCommandSet } TLuaDBGCommandSet = class(TLuaDBGAction) protected FName: string; FValue: string; procedure Execute(Respond: TDebugCommandRespond); override; public constructor CreateBy(vName, vValue: string); function GetCommand: string; override; end; { TLuaDBGGetCurrent } TLuaDBGGetCurrent = class(TLuaDBGAction) private FCurKey: string; FCurFile: string; FCurLine: integer; FCallStack: TCallStackItems; procedure ShowFile; public procedure Created; override; destructor Destroy; override; function GetCommand: string; override; procedure Execute(Respond: TDebugCommandRespond); override; end; TLuaDBGStep = class(TLuaDBGAction) public function GetCommand: string; override; procedure Execute(Respond: TDebugCommandRespond); override; end; TLuaDBGStepInto = class(TLuaDBGAction) public function GetCommand: string; override; procedure Execute(Respond: TDebugCommandRespond); override; end; TLuaDBGStepOut = class(TLuaDBGAction) public function GetCommand: string; override; procedure Execute(Respond: TDebugCommandRespond); override; end; TLuaDBGRun = class(TLuaDBGAction) public function GetCommand: string; override; procedure Execute(Respond: TDebugCommandRespond); override; end; { TLuaDBGDetach } TLuaDBGDetach = class(TLuaDBGAction) public function GetCommand: string; override; procedure Execute(Respond: TDebugCommandRespond); override; destructor Destroy; override; end; TLuaDBGStop = class(TLuaDBGAction) public function GetCommand: string; override; procedure Execute(Respond: TDebugCommandRespond); override; end; TLuaDBGCustomGet = class(TLuaDBGAction) public Info: TDebugWatchInfo; end; // Watches TLuaDBGCustomGetWatch = class(TLuaDBGCustomGet) protected public function GetCommand: string; override; procedure Execute(Respond: TDebugCommandRespond); override; end; TLuaDBGGetWatch = class(TLuaDBGCustomGetWatch) protected public Index: integer; procedure Execute(Respond: TDebugCommandRespond); override; end; { TLuaDBGEval } TLuaDBGEval = class(TLuaDBGCustomGet) protected public function GetCommand: string; override; function GetData: string; override; procedure Execute(Respond: TDebugCommandRespond); override; end; { TLuaDBGGetWatchInstance } TLuaDBGGetWatchInstance = class(TLuaDBGCustomGetWatch) protected public end; TLuaDBGGetWatches = class(TLuaDBGCustomGetWatch) protected public Current: integer; function Stay: boolean; override; function Enabled: boolean; override; procedure Execute(Respond: TDebugCommandRespond); override; end; // Breakpoints TLuaDBGSetBreakpoint = class(TLuaDBGAction) protected public BreakpointID: cardinal; FileName: string; FileLine: integer; function GetCommand: string; override; procedure Execute(Respond: TDebugCommandRespond); override; end; TLuaDBGSetBreakpoints = class(TLuaDBGSetBreakpoint) protected public Current: integer; function Enabled: boolean; override; function Stay: boolean; override; end; { TLuaDBGRemoveBreakpoint } TLuaDBGRemoveBreakpoint = class(TLuaDBGAction) protected procedure Execute(Respond: TDebugCommandRespond); override; public BreakpointID: integer; function GetCommand: string; override; end; //* Watches TLuaDBGWatch = class(TObject) private FHandle: integer; public Info: TDebugWatchInfo; property Handle: integer read FHandle write FHandle; published end; TLuaDBGWatches = class(specialize GItems<TLuaDBGWatch>) private FServer: TLuaDBGServer; CurrentHandle: integer; function GetValues(Name: string): variant; procedure SetValues(Name: string; const Value: variant); protected property Server: TLuaDBGServer read FServer; public function Find(Name: string): TLuaDBGWatch; function Add(Name: string; Value: variant): integer; overload; procedure AddWatch(Name: string); procedure RemoveWatch(Name: string); procedure Clean; property Values[Name: string]: variant read GetValues write SetValues; end; //* Breakpoints TLuaDBGBreakpoint = class(TObject) private FID: integer; FLine: integer; FHandle: integer; FFileName: string; public property Handle: integer read FHandle write FHandle; property ID: integer read FID write FID; published property FileName: string read FFileName write FFileName; property Line: integer read FLine write FLine; end; TLuaDBGBreakpoints = class(specialize GItems<TLuaDBGBreakpoint>) private CurrentHandle: integer; FServer: TLuaDBGServer; protected property Server: TLuaDBGServer read FServer; public function Remove(Breakpoint: TLuaDBGBreakpoint): integer; overload; procedure Remove(Handle: integer); overload; function Add(FileName: string; Line: integer): integer; overload; function Find(Name: string; Line: integer): TLuaDBGBreakpoint; procedure Toggle(FileName: string; Line: integer); end; TLuaDBGOnServerEvent = procedure(Sender: TObject; Socket: TLuaDBGConnection) of object; { TLuaDBGConnection } TLuaDBGConnection = class(TmnServerConnection) private FLocalSpool: TLuaDBGConnectionSpool; FKey: string; function GetServer: TLuaDBGServer; public FTransactionID: integer; protected function NewTransactionID: integer; {$IFDEF SAVELOG} procedure SaveLog(s: string); {$ENDIF} function ReadRespond: TDebugCommandRespond; function PopAction: TLuaDBGAction; function SendCommand(Command: string; Data: string): integer; procedure Prepare; override; procedure DoExecute; procedure Process; override; public constructor Create(vConnector: TmnConnector; Socket: TmnCustomSocket); override; destructor Destroy; override; procedure Stop; override; property Key: string read FKey; property Server: TLuaDBGServer read GetServer; published end; TmnDBGListener = class(TmnListener) private protected function CreateConnection(vSocket: TmnCustomSocket): TmnServerConnection; override; public constructor Create; destructor Destroy; override; end; { TLuaDBGServer } TLuaDBGServer = class(TmnServer) private FBreakOnFirstLine: Boolean; FSpool: TLuaDBGSpool; FStackDepth: Integer; FWatches: TLuaDBGWatches; FBreakpoints: TLuaDBGBreakpoints; FRunCount: Integer; FKey: string; function GetIsRuning: Boolean; protected function CreateListener: TmnListener; override; procedure DoChanged(vListener: TmnListener); override; procedure DoStart; override; procedure DoStop; override; property Spool: TLuaDBGSpool read FSpool; public constructor Create; destructor Destroy; override; procedure Resume; procedure AddAction(Action: TLuaDBGAction); overload; procedure AddAction(ActionClass: TLuaDBGActionClass); overload; procedure RemoveAction(Action: TLuaDBGAction); procedure ExtractAction(Action: TLuaDBGAction); procedure Clear; property RunCount: Integer read FRunCount; property IsRuning: Boolean read GetIsRuning; property Watches: TLuaDBGWatches read FWatches; property StackDepth: Integer read FStackDepth write FStackDepth; property Breakpoints: TLuaDBGBreakpoints read FBreakpoints; property BreakOnFirstLine: Boolean read FBreakOnFirstLine write FBreakOnFirstLine default False; property Key: string read FKey; published end; TLuaDBGDebug = class; { TLuaDBGDebugBreakPoints } TLuaDBGDebugBreakPoints = class(TEditorBreakPoints) protected FDebug: TLuaDBGDebug; function GetCount: integer; override; function GetItems(Index: integer): TDebugBreakpointInfo; override; public procedure Clear; override; procedure Toggle(FileName: string; LineNo: integer); override; function IsExists(FileName: string; LineNo: integer): boolean; override; procedure Add(FileName: string; LineNo: integer); override; procedure Remove(FileName: string; Line: integer); override; overload; procedure Remove(Handle: integer); override; overload; end; { TLuaDBGDebugWatches } TLuaDBGDebugWatches = class(TEditorWatches) protected FDebug: TLuaDBGDebug; function GetCount: integer; override; function GetItems(Index: integer): TDebugWatchInfo; override; public procedure Clear; override; procedure Add(vName: string); override; procedure Remove(vName: string); override; function GetValue(vName: string; out vValue: Variant; out vType: string; EvalIt: Boolean): boolean; override; end; { TLuaDBGDebug } TLuaDBGDebug = class(TEditorDebugger) private FServer: TLuaDBGServer; protected function CreateBreakPoints: TEditorBreakPoints; override; function CreateWatches: TEditorWatches; override; procedure Reset; procedure Resume; procedure StepOver; procedure StepInto; procedure StepOut; procedure Run; public constructor Create; destructor Destroy; override; procedure Start; override; procedure Stop; override; procedure Action(AAction: TDebugAction); override; function GetState: TDebugStates; override; function GetKey: string; override; end; implementation uses EditorEngine; { TLuaDBGAction } procedure TLuaDBGAction.CheckError(Respond: TDebugCommandRespond); begin if (Respond.Root <> nil) then if StrToIntDef(Respond.GetAttribute('response', 'transaction_id'), -1) <> FTransactionID then raise EDebugException.Create('transaction_id is not same with command.'#13 + Respond.Source); end; { TLuaDBGCommandSet } procedure TLuaDBGCommandSet.Execute(Respond: TDebugCommandRespond); begin end; constructor TLuaDBGCommandSet.CreateBy(vName, vValue: string); begin Create; FName := vName; FValue:= vValue; end; function TLuaDBGCommandSet.GetCommand: string; begin Result := FName + ' ' + FValue; end; { TLuaDBGEval } function TLuaDBGEval.GetCommand: string; begin Result := 'eval'; end; function TLuaDBGEval.GetData: string; begin Result := 'echo ' + Info.Name; end; procedure TLuaDBGEval.Execute(Respond: TDebugCommandRespond); begin end; { TLuaDBGFeatureSet } procedure TLuaDBGFeatureSet.Execute(Respond: TDebugCommandRespond); begin end; constructor TLuaDBGFeatureSet.CreateBy(vName, vValue: string); begin Create; FName := vName; FValue:= vValue; end; function TLuaDBGFeatureSet.GetCommand: string; begin // 'feature_set -n show_hidden -v 1'; Result := 'feature_set -n ' + FName + ' -v '+ FValue; end; constructor TLuaDBGServer.Create; begin inherited; FSpool := TLuaDBGSpool.Create(True); Port := '8172'; // MOBDEBUG_PORT FStackDepth := 10; FWatches := TLuaDBGWatches.Create; FWatches.FServer := Self; FBreakpoints := TLuaDBGBreakpoints.Create; FBreakpoints.FServer := Self; FBreakpoints.FServer := Self; FBreakOnFirstLine := False; end; destructor TLuaDBGServer.Destroy; begin FreeAndNil(FWatches); FreeAndNil(FBreakpoints); FreeAndNil(FSpool); inherited; end; function TLuaDBGServer.GetIsRuning: Boolean; begin Result := RunCount > 0; end; constructor TLuaDBGConnection.Create(vConnector: TmnConnector; Socket: TmnCustomSocket); begin inherited; FLocalSpool := TLuaDBGConnectionSpool.Create; FLocalSpool.FConnection := Self; //KeepAlive := True; Stream.Timeout := 5000; end; destructor TLuaDBGConnection.Destroy; begin FreeAndNil(FLocalSpool); inherited; end; { TLuaDBGConnection } function TLuaDBGConnection.NewTransactionID: integer; begin Inc(FTransactionID); Result := FTransactionID; end; procedure TLuaDBGGetCurrent.ShowFile; //this function must Synchronize begin Engine.DebugLink.SetExecutedLine(FCurKey, FCurFile, FCurLine, FCallStack); end; procedure TLuaDBGConnection.DoExecute; var aAction: TLuaDBGAction; aRespond: TDebugCommandRespond; aCommand: string; aKeep: Boolean; begin aAction := PopAction; if aAction <> nil then begin if not aAction.Enabled then FLocalSpool.Remove(aAction) else try aCommand := aAction.GetCommand; if (dafSend in aAction.Flags) and (aCommand <> '') then aAction.FTransactionID := SendCommand(aCommand, aAction.GetData); if aAction.Accept and Connected then begin aRespond := ReadRespond; try if (aRespond <> nil) and (aRespond.Root <> nil) then begin if (aRespond.GetAttribute('response', 'status') = 'stopping') then Disconnect else if (aRespond.GetAttribute('response', 'status') = 'stoped') then begin //Disconnect; end else begin try if (aRespond <> nil) and Connected and (aRespond.Root <> nil) then aAction.Execute(aRespond); finally end; end; end; finally FreeAndNil(aRespond); end; end; finally if not aAction.Stay then begin aKeep := (aAction.Event <> nil) or aAction.KeepAlive; if aAction.Event <> nil then aAction.Event.SetEvent; if aKeep then FLocalSpool.Extract(aAction) else FLocalSpool.Remove(aAction); end; end; end; end; { TLuaDBGSocketServer } function TLuaDBGServer.CreateListener: TmnListener; begin Result := TmnDBGListener.Create; end; function TLuaDBGConnection.ReadRespond: TDebugCommandRespond; var Reader: TmnXMLNodeReader; s, r: string; aMatched: boolean; begin Result := nil; r := ''; Stream.ReadUntil(#10, true, s, aMatched); if Connected and aMatched and (S <> '') then begin Result := TDebugCommandRespond.Create; repeat //Stream.Connected Stream.ReadUntil(#10, true, s, aMatched); s := Trim(s); r := r + s; until s = ''; {$IFDEF SAVELOG} SaveLog(s); {$ENDIF} Result.Source := s; Reader := TmnXMLNodeReader.Create; try Reader.Start; Reader.Nodes := Result; Reader.Parse(s); finally Reader.Free; end; end; end; {$IFDEF SAVELOG} procedure TLuaDBGConnection.SaveLog(s: string); var aStrings: TStringList; aStream: TFileStream; i: integer; const sFile = 'c:\mobdebug_server.log'; begin aStrings := TStringList.Create; aStrings.Text := s; if FileExists(sFile) then begin aStream := TFileStream.Create(sFile, fmOpenWrite); aStream.Seek(0, soFromEnd); end else aStream := TFileStream.Create(sFile, fmCreate); try for i := 0 to aStrings.Count - 1 do begin s := aStrings[i] + #13; aStream.Write(s[1], Length(s)); end; finally aStream.Free; aStrings.Free; end; end; {$ENDIF} function TLuaDBGConnection.SendCommand(Command: string; Data: string): integer; var s: string; begin Result := NewTransactionID; s := Command ;//+ ' -i ' + IntToStr(Result); if Data <> '' then s := s + ' ' + Data; Stream.WriteLine(s, #13#10); {$IFDEF SAVELOG} SaveLog(s); {$ENDIF} end; function TLuaDBGConnection.GetServer: TLuaDBGServer; begin Result := (Listener.Server as TLuaDBGServer); end; function TLuaDBGConnection.PopAction: TLuaDBGAction; var aAction: TLuaDBGAction; i: integer; begin if FLocalSpool.Count = 0 then begin InterLockedIncrement(Server.FRunCount); DebugManager.Event.WaitFor(INFINITE); //wait the ide to make resume InterLockedDecrement(Server.FRunCount); DebugManager.Lock.Enter; try i := 0; while i < Server.Spool.Count do begin aAction := Server.Spool.Extract(Server.Spool[i]) as TLuaDBGAction; // if aAction.Key = Key then FLocalSpool.Add(aAction); // else // inc(i); end; finally DebugManager.Lock.Leave; end; end; Result := nil; while not Terminated and ((FLocalSpool.Count > 0) and (Result = nil)) do begin Result := FLocalSpool[0]; Result.Prepare; end; end; procedure TLuaDBGConnection.Prepare; begin inherited; //FLocalSpool.Add(TLuaDBGInit.Create); FLocalSpool.Add(TLuaDBGStep.Create); {FLocalSpool.Add(TLuaDBGFeatureSet.CreateBy('show_hidden', '1')); FLocalSpool.Add(TLuaDBGFeatureSet.CreateBy('max_depth', IntToStr(Server.StackDepth))); FLocalSpool.Add(TLuaDBGFeatureSet.CreateBy('max_children', '100'));} FLocalSpool.Add(TLuaDBGSetBreakpoints.Create); FLocalSpool.Add(TLuaDBGCommandSet.CreateBy('breakpoint_set', '-t exception -X Error -s enabled')); FLocalSpool.Add(TLuaDBGCommandSet.CreateBy('breakpoint_set', '-t exception -X Warning -s enabled')); { or breakpoint_set -t exception -X Error breakpoint_set -t exception -X Warning breakpoint_set -t exception -X Notice } if Server.BreakOnFirstLine then begin FLocalSpool.Add(TLuaDBGStepInto.Create); FLocalSpool.Add(TLuaDBGGetCurrent.Create); end else begin FLocalSpool.Add(TLuaDBGRun.Create); FLocalSpool.Add(TLuaDBGGetWatches.Create); FLocalSpool.Add(TLuaDBGGetCurrent.Create); end; end; procedure TLuaDBGConnection.Process; begin inherited; //Allow one connection to Execute //Listener.Enter; try DoExecute; finally //Listener.Leave; end; end; procedure TLuaDBGConnection.Stop; begin inherited; DebugManager.Event.SetEvent; end; { TmnDBGListener } function TmnDBGListener.CreateConnection(vSocket: TmnCustomSocket): TmnServerConnection; begin Result := TLuaDBGConnection.Create(Self, vSocket); end; constructor TmnDBGListener.Create; begin inherited; FOptions := FOptions + [soReuseAddr]; end; destructor TmnDBGListener.Destroy; begin inherited; end; procedure TLuaDBGServer.DoStart; begin Spool.Clear; inherited; end; procedure TLuaDBGServer.DoStop; begin inherited; if FSpool <> nil then //DoStop class when Server free FSpool.Clear; end; procedure TLuaDBGServer.DoChanged(vListener: TmnListener); begin inherited; if vListener.Count = 0 then //TODO: i am not sure in Linux Engine.DebugLink.SetExecutedLine('', '', 0); end; { TLuaDBGStep } function TLuaDBGStep.GetCommand: string; begin Result := 'STEP'; end; procedure TLuaDBGStep.Execute(Respond: TDebugCommandRespond); begin end; { TLuaDBGStepInto } function TLuaDBGStepInto.GetCommand: string; begin Result := 'step_into'; end; procedure TLuaDBGStepInto.Execute(Respond: TDebugCommandRespond); begin end; procedure TLuaDBGServer.Resume; begin DebugManager.Event.SetEvent; end; { TLuaDBGInit } procedure TLuaDBGInit.Created; begin inherited; Flags := Flags + [dafSend]; end; function TLuaDBGInit.GetCommand: string; begin Result := 'init'; end; procedure TLuaDBGInit.Execute(Respond: TDebugCommandRespond); begin DebugManager.Lock.Enter; try Connection.Server.Watches.Clean; Connection.FKey := Respond.Root.Attributes['idekey']; finally DebugManager.Lock.Leave; end; end; { TLuaDBGGetCurrent } function TLuaDBGGetCurrent.GetCommand: string; {var aDepth: Integer;} begin //aDepth := Connection.Server.StackDepth; Result := 'stack_get'; { if aDepth > 0 then Result := Result + ' -d ' + IntToStr(aDepth);} end; procedure TLuaDBGGetCurrent.Execute(Respond: TDebugCommandRespond); var i: Integer; begin if Respond.Root.Items.Count > 0 then begin FCallStack := TCallStackItems.Create; try for i := 0 to Respond.Root.Items.Count -1 do begin if SameText(Respond.Root.Items[i].Name, 'stack') then FCallStack.Add(URIToFileName(Respond.Root.Items[i].Attributes.Values['filename']), StrToIntDef(Respond.Root.Items[i].Attributes.Values['lineno'], 0)); end; finally end; FCurFile := URIToFileName(Respond.GetAttribute('stack', 'filename')); if FCurFile <> '' then begin FCurKey := Connection.Key; FCurLine := StrToIntDef(Respond.GetAttribute('stack', 'lineno'), 0); try //Dont do any lock here Connection.Synchronize(@ShowFile); finally end; end; end; end; procedure TLuaDBGGetCurrent.Created; begin inherited; Flags := Flags + [dafCheckError]; end; destructor TLuaDBGGetCurrent.Destroy; begin FreeAndNil(FCallStack); inherited Destroy; end; { TLuaDBGRun } function TLuaDBGRun.GetCommand: string; begin Result := 'run'; end; procedure TLuaDBGRun.Execute(Respond: TDebugCommandRespond); begin end; { TLuaDBGDetach } function TLuaDBGDetach.GetCommand: string; begin Result := 'detach'; end; procedure TLuaDBGDetach.Execute(Respond: TDebugCommandRespond); begin Connection.Disconnect; end; destructor TLuaDBGDetach.Destroy; begin inherited Destroy; end; { TLuaDBGStop } function TLuaDBGStop.GetCommand: string; begin Result := 'stop'; end; procedure TLuaDBGStop.Execute(Respond: TDebugCommandRespond); begin Connection.Disconnect; end; { TLuaDBGStepOut } function TLuaDBGStepOut.GetCommand: string; begin Result := 'step_out'; end; procedure TLuaDBGStepOut.Execute(Respond: TDebugCommandRespond); begin end; { TLuaDBGWatches } function TLuaDBGWatches.Add(Name: string; Value: variant): integer; var aWatch: TLuaDBGWatch; begin Inc(CurrentHandle); aWatch := TLuaDBGWatch.Create; aWatch.Handle := CurrentHandle; aWatch.Info.Name := Name; aWatch.Info.VarType := ''; aWatch.Info.Value := Value; Result := Add(aWatch); end; procedure TLuaDBGWatches.AddWatch(Name: string); begin DebugManager.Lock.Enter; try Add(Name, ''); finally DebugManager.Lock.Leave; end; if Server.IsRuning then begin DebugManager.Lock.Enter; try Server.Spool.Add(TLuaDBGGetWatches.Create); Server.Spool.Add(TLuaDBGGetCurrent.Create); finally DebugManager.Lock.Leave; end; Server.Resume; end; end; procedure TLuaDBGWatches.Clean; var i: integer; begin for i := 0 to Count - 1 do begin VarClear(Items[i].Info.Value); end; end; function TLuaDBGWatches.Find(Name: string): TLuaDBGWatch; var i: integer; begin Result := nil; for i := 0 to Count - 1 do begin if Items[i].Info.Name = Name then begin Result := Items[i]; break; end; end; end; function TLuaDBGWatches.GetValues(Name: string): variant; var aWatch: TLuaDBGWatch; begin aWatch := Find(Name); if aWatch <> nil then Result := aWatch.Info.Value else VarClear(Result); end; procedure TLuaDBGWatches.RemoveWatch(Name: string); var i: integer; begin for i := 0 to Count - 1 do begin if Items[i].Info.Name = Name then begin Delete(i); break; end; end; if Server.IsRuning then begin DebugManager.Lock.Enter; try Server.Spool.Add(TLuaDBGGetWatches.Create); Server.Spool.Add(TLuaDBGGetCurrent.Create); finally DebugManager.Lock.Leave; end; Server.Resume; end; end; procedure TLuaDBGWatches.SetValues(Name: string; const Value: variant); begin end; { TLuaDBGGetWatch } procedure TLuaDBGGetWatch.Execute(Respond: TDebugCommandRespond); begin inherited; DebugManager.Lock.Enter; try Connection.Server.Watches[Index].Info.Value := Info.Value; Connection.Server.Watches[Index].Info.VarType := Info.VarType; finally DebugManager.Lock.Leave; end; end; { TLuaDBGBreakpoints } function TLuaDBGBreakpoints.Add(FileName: string; Line: integer): integer; var aBreakpoint: TLuaDBGBreakpoint; begin Inc(CurrentHandle); aBreakpoint := TLuaDBGBreakpoint.Create; aBreakpoint.Handle := CurrentHandle; aBreakpoint.FileName := FileName; aBreakpoint.Line := Line; Result := Add(aBreakpoint); end; function TLuaDBGBreakpoints.Find(Name: string; Line: integer): TLuaDBGBreakpoint; var i: integer; begin Result := nil; for i := 0 to Count - 1 do begin if (Items[i].line = Line) and SameText(Items[i].FileName, Name) then begin Result := Items[i]; break; end; end; end; function TLuaDBGBreakpoints.Remove(Breakpoint: TLuaDBGBreakpoint): integer; begin Result := inherited Remove(Breakpoint); end; procedure TLuaDBGBreakpoints.Remove(Handle: integer); var i: integer; begin for i := 0 to Count - 1 do begin if Items[i].Handle = Handle then begin Delete(i); break; end; end; end; procedure TLuaDBGBreakpoints.Toggle(FileName: string; Line: integer); var aBreakpoint: TLuaDBGBreakpoint; aSetBreakpoint: TLuaDBGSetBreakpoint; aRemoveBreakpoint: TLuaDBGRemoveBreakpoint; begin aBreakpoint := Find(FileName, Line); if aBreakpoint <> nil then begin Remove(aBreakpoint); if Server.IsRuning then begin if aBreakpoint.ID <> 0 then begin aRemoveBreakpoint := TLuaDBGRemoveBreakpoint.Create; aRemoveBreakpoint.BreakpointID := aBreakpoint.ID; Server.Spool.Add(aRemoveBreakpoint); end; end; end else begin Add(FileName, Line); if Server.IsRuning then begin aSetBreakpoint := TLuaDBGSetBreakpoint.Create; aSetBreakpoint.FileName := FileName; aSetBreakpoint.FileLine := Line; Server.Spool.Add(aSetBreakpoint); end; end; end; { TLuaDBGGetWatches } function TLuaDBGGetWatches.Stay: boolean; begin DebugManager.Lock.Enter; try Inc(Current); Result := Current < Connection.Server.Watches.Count; finally DebugManager.Lock.Leave; end; end; procedure TLuaDBGGetWatches.Execute(Respond: TDebugCommandRespond); begin inherited; DebugManager.Lock.Enter; try Connection.Server.Watches[Current].Info.Value := Info.Value; Connection.Server.Watches[Current].Info.VarType := Info.VarType; finally DebugManager.Lock.Leave; end; end; function TLuaDBGGetWatches.Enabled: boolean; begin DebugManager.Lock.Enter; try Result := Current < Connection.Server.Watches.Count; if Result then Info.Name := Connection.Server.Watches[Current].Info.Name; finally DebugManager.Lock.Leave; end; end; { TLuaDBGSetBreakpoints } function TLuaDBGSetBreakpoints.Enabled: boolean; begin DebugManager.Lock.Enter; try Result := Current < Connection.Server.Breakpoints.Count; if Result then begin FileName := Connection.Server.Breakpoints[Current].FileName; FileLine := Connection.Server.Breakpoints[Current].Line; end; finally DebugManager.Lock.Leave; end; end; function TLuaDBGSetBreakpoints.Stay: boolean; begin DebugManager.Lock.Enter; try Connection.Server.Breakpoints[Current].ID := BreakpointID; Inc(Current); Result := Current < Connection.Server.Breakpoints.Count; finally DebugManager.Lock.Leave; end; end; { TLuaDBGSetBreakpoint } function TLuaDBGSetBreakpoint.GetCommand: string; begin Result := 'breakpoint_set -t line -n ' + IntToStr(FileLine) + ' -f ' + FileNameToURI(FileName) + ''; end; procedure TLuaDBGSetBreakpoint.Execute(Respond: TDebugCommandRespond); begin CheckError(Respond); BreakpointID := StrToInt(Respond.Root.Attributes['id']); end; { TLuaDBGRemoveBreakpoint } procedure TLuaDBGRemoveBreakpoint.Execute(Respond: TDebugCommandRespond); begin end; function TLuaDBGRemoveBreakpoint.GetCommand: string; begin Result := 'breakpoint_remove -d ' + IntToStr(BreakpointID); end; { TLuaDBGConnectionSpool } procedure TLuaDBGConnectionSpool.Added(Action: TLuaDBGAction); begin inherited Added(Action); Action.FConnection := FConnection; end; {$IFDEF SAVELOG} procedure SaveLog(s: string); var aStrings: TStringList; aStream: TFileStream; i: integer; const sFile = 'c:\lock_server.log'; begin aStrings := TStringList.Create; aStrings.Text := s; if FileExists(sFile) then begin aStream := TFileStream.Create(sFile, fmOpenWrite); aStream.Seek(0, soFromEnd); end else aStream := TFileStream.Create(sFile, fmCreate); try for i := 0 to aStrings.Count - 1 do begin s := aStrings[i] + #13; aStream.Write(s[1], Length(s)); end; finally aStream.Free; aStrings.Free; end; end; {$ENDIF} procedure TLuaDBGServer.AddAction(Action: TLuaDBGAction); begin DebugManager.Lock.Enter; try Spool.Add(Action); finally DebugManager.Lock.Leave; end; end; procedure TLuaDBGServer.AddAction(ActionClass: TLuaDBGActionClass); begin AddAction(ActionClass.Create); end; procedure TLuaDBGServer.RemoveAction(Action: TLuaDBGAction); begin DebugManager.Lock.Enter; try Spool.Remove(Action); finally DebugManager.Lock.Leave; end; end; procedure TLuaDBGServer.ExtractAction(Action: TLuaDBGAction); begin DebugManager.Lock.Enter; try Spool.Extract(Action); finally DebugManager.Lock.Leave; end; end; procedure TLuaDBGServer.Clear; begin DebugManager.Lock.Enter; try Spool.Clear; finally DebugManager.Lock.Leave; end; end; { TLuaDBGCustomGetWatch } function TLuaDBGCustomGetWatch.GetCommand: string; begin Result := 'property_value -n "' + Info.Name + '" -m 1024'; //Result := 'property_get -n "' + Name + '" -m 1024'; end; procedure TLuaDBGCustomGetWatch.Execute(Respond: TDebugCommandRespond); const //sCmd = 'property'; sCmd = 'response'; var S: string; begin if Respond[sCmd] <> nil then begin S := Respond[sCmd].Value; if (S <> '') and (Respond[sCmd].Attributes['encoding'] = 'base64') then //bug DecodeStringBase64 when S = '' Info.Value := DecodeStringBase64(S) else Info.Value := S; Info.VarType := Respond[sCmd].Attributes['type']; end else begin Info.VarType := '[ERROR]'; Info.Value := ''; end; end; { TLuaDBGDebugWatches } function TLuaDBGDebugWatches.GetCount: integer; begin with FDebug.FServer do Result := Watches.Count; end; function TLuaDBGDebugWatches.GetItems(Index: integer): TDebugWatchInfo; var aWt: TLuaDBGWatch; begin with FDebug.FServer do aWt := Watches[Index]; Result:= aWt.Info; end; procedure TLuaDBGDebugWatches.Clear; begin with FDebug.FServer do Watches.Clear; end; procedure TLuaDBGDebugWatches.Add(vName: string); begin with FDebug.FServer do Watches.AddWatch(vName); end; procedure TLuaDBGDebugWatches.Remove(vName: string); begin with FDebug.FServer do Watches.RemoveWatch(vName); end; function TLuaDBGDebugWatches.GetValue(vName: string; out vValue: Variant; out vType: string; EvalIt: Boolean): boolean; var aAction: TLuaDBGCustomGet; begin Result := False; if dbsRunning in FDebug.GetState then //there is a connection from mobdebug begin if EvalIt then aAction := TLuaDBGEval.Create else aAction := TLuaDBGGetWatchInstance.Create; aAction.CreateEvent; aAction.Info.Name := vName; with FDebug.FServer do begin AddAction(aAction); Resume; aAction.Event.WaitFor(30000); vValue := aAction.Info.Value; vType := aAction.Info.VarType; ExtractAction(aAction); aAction.Free; Result := True; end; end; end; { TLuaDBGDebugBreakPoints } function TLuaDBGDebugBreakPoints.GetCount: integer; begin with FDebug.FServer do Result := Breakpoints.Count; end; function TLuaDBGDebugBreakPoints.GetItems(Index: integer): TDebugBreakpointInfo; var aBP: TLuaDBGBreakpoint; begin with FDebug.FServer do aBP := Breakpoints[Index]; Result.FileName := aBP.FileName; Result.Handle := aBP.Handle; Result.Line := aBP.Line; end; procedure TLuaDBGDebugBreakPoints.Clear; begin with FDebug.FServer do Breakpoints.Clear; end; procedure TLuaDBGDebugBreakPoints.Toggle(FileName: string; LineNo: integer); begin with FDebug.FServer do Breakpoints.Toggle(FileName, LineNo); end; function TLuaDBGDebugBreakPoints.IsExists(FileName: string; LineNo: integer): boolean; begin with FDebug.FServer do Result := Breakpoints.Find(FileName, LineNo) <> nil; end; procedure TLuaDBGDebugBreakPoints.Add(FileName: string; LineNo: integer); begin with FDebug.FServer do Breakpoints.Add(FileName, LineNo); end; procedure TLuaDBGDebugBreakPoints.Remove(FileName: string; Line: integer); var aBP: TLuaDBGBreakpoint; begin with FDebug.FServer do aBP := Breakpoints.Find(FileName, Line); if aBP <> nil then with FDebug.FServer do Breakpoints.Remove(aBP); end; procedure TLuaDBGDebugBreakPoints.Remove(Handle: integer); begin with FDebug.FServer do Breakpoints.Remove(Handle); end; { TLuaDBGDebug } function TLuaDBGDebug.CreateBreakPoints: TEditorBreakPoints; begin Result := TLuaDBGDebugBreakPoints.Create; (Result as TLuaDBGDebugBreakPoints).FDebug := Self; end; function TLuaDBGDebug.CreateWatches: TEditorWatches; begin Result := TLuaDBGDebugWatches.Create; (Result as TLuaDBGDebugWatches).FDebug := Self; end; constructor TLuaDBGDebug.Create; begin inherited Create; FServer := TLuaDBGServer.Create; //FServer.FDebug := Self; end; destructor TLuaDBGDebug.Destroy; begin FreeAndNil(FServer); inherited; end; procedure TLuaDBGDebug.Action(AAction: TDebugAction); begin case AAction of dbaStartServer: Start; dbaStopServer: Stop; dbaReset: Reset; dbaResume: Resume; dbaStepInto: StepInto; dbaStepOver: StepOver; dbaStepOut: StepOut; dbaRun: Run; end; end; function TLuaDBGDebug.GetState: TDebugStates; begin Result := []; if FServer.Active then Result := Result + [dbsActive]; if FServer.IsRuning then Result := Result + [dbsRunning]; end; procedure TLuaDBGDebug.Start; begin inherited; FServer.Start; end; procedure TLuaDBGDebug.Stop; var aAction: TLuaDBGDetach; begin inherited; if FServer.IsRuning then begin FServer.Clear; aAction := TLuaDBGDetach.Create; aAction.CreateEvent; FServer.AddAction(aAction); FServer.Resume; aAction.Event.WaitFor(30000); FServer.ExtractAction(aAction); aAction.Free; end; FServer.Stop; end; procedure TLuaDBGDebug.Reset; begin FServer.Clear; //no need to any exists actions FServer.AddAction(TLuaDBGStop.Create); FServer.AddAction(TLuaDBGGetCurrent.Create); FServer.Resume; end; procedure TLuaDBGDebug.Resume; begin FServer.AddAction(TLuaDBGDetach.Create); FServer.AddAction(TLuaDBGGetCurrent.Create); FServer.Resume; end; procedure TLuaDBGDebug.StepInto; begin FServer.AddAction(TLuaDBGStepInto.Create); FServer.AddAction(TLuaDBGGetWatches.Create); FServer.AddAction(TLuaDBGGetCurrent.Create); FServer.Resume; end; procedure TLuaDBGDebug.StepOver; begin FServer.AddAction(TLuaDBGStep.Create); FServer.AddAction(TLuaDBGGetWatches.Create); FServer.AddAction(TLuaDBGGetCurrent.Create); FServer.Resume; end; procedure TLuaDBGDebug.StepOut; begin FServer.AddAction(TLuaDBGStepOut.Create); FServer.AddAction(TLuaDBGGetWatches.Create); FServer.AddAction(TLuaDBGGetCurrent.Create); FServer.Resume; end; procedure TLuaDBGDebug.Run; begin FServer.AddAction(TLuaDBGRun.Create); FServer.AddAction(TLuaDBGGetWatches.Create); FServer.AddAction(TLuaDBGGetCurrent.Create); FServer.Resume; end; function TLuaDBGDebug.GetKey: string; begin Result := FServer.Key; end; end.
23.794588
161
0.6893
4728149e2075ba2eec0718c9a89c1b80ef3f6478
848
dfm
Pascal
DocumentGroupUnit.dfm
naumovda/d-client
4fa4be0d97962ad6166243fdd9b92b2269909151
[ "Apache-2.0" ]
null
null
null
DocumentGroupUnit.dfm
naumovda/d-client
4fa4be0d97962ad6166243fdd9b92b2269909151
[ "Apache-2.0" ]
null
null
null
DocumentGroupUnit.dfm
naumovda/d-client
4fa4be0d97962ad6166243fdd9b92b2269909151
[ "Apache-2.0" ]
null
null
null
inherited DocumentGroup: TDocumentGroup Caption = #1043#1088#1091#1087#1087#1099' '#1076#1086#1075#1086#1074#1086#1088#1086#1074 OldCreateOrder = True PixelsPerInch = 96 TextHeight = 13 inherited Grid: TcxGrid inherited tvMain: TcxGridDBTableView object tvMainGroupName: TcxGridDBColumn Caption = #1053#1072#1080#1084#1077#1085#1086#1074#1072#1085#1080#1077 DataBinding.FieldName = 'GroupName' end end end inherited dxLeft: TdxLayoutControl Visible = False end inherited cxSplitterMain: TcxSplitter Visible = False end inherited DS: TDataSource DataSet = dmPublic.tDocumentGroup end inherited dxBarManager: TdxBarManager Categories.ItemsVisibles = ( 2) Categories.Visibles = ( True) DockControlHeights = ( 0 0 26 0) end end
24.228571
90
0.693396
c36a6de0191cabf7018d0481189f4348420bb104
13,071
pas
Pascal
mainunit.pas
nhwood/SqlSmusher
76592faa2b3a2d5e8f6c75fc9cd1ef36dc0996d6
[ "MIT" ]
null
null
null
mainunit.pas
nhwood/SqlSmusher
76592faa2b3a2d5e8f6c75fc9cd1ef36dc0996d6
[ "MIT" ]
null
null
null
mainunit.pas
nhwood/SqlSmusher
76592faa2b3a2d5e8f6c75fc9cd1ef36dc0996d6
[ "MIT" ]
null
null
null
unit MainUnit; {$mode objfpc}{$H+} {$MACRO ON} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, Menus, ActnList, StdActns, ComCtrls, ExtCtrls, Buttons, StdCtrls, Clipbrd, OptionsUnit, IniFiles, Utilities, fileinfo, About, Editor; {$IF defined(Windows)} {$Define NotPosix} {$ENDIF} type { TFormMain } TFormMain = class(TForm) MenuItem1: TMenuItem; MenuItem2: TMenuItem; MenuItemView: TMenuItem; SaveDialog: TSaveDialog; ScrollBox1: TScrollBox; ViewFileOnly: TAction; ViewFullPath: TAction; FileSmush: TAction; FileRemoveAll: TAction; FileMoveDown: TAction; FileMoveUp: TAction; BtnExit: TBitBtn; BtnAddFiles: TBitBtn; BtnAddFolder: TBitBtn; BitBtn3: TBitBtn; BitBtn4: TBitBtn; BtnRemoveFile: TBitBtn; BtnRemoveAll: TBitBtn; BtnSmush: TBitBtn; FileRemove: TAction; HelpChangelog: TAction; HelpAbout: TAction; ListBoxFiles: TListBox; MenuItemSep7: TMenuItem; MenuItemSmush: TMenuItem; MenuItemSep6: TMenuItem; MenuItemRemoveAllFiles: TMenuItem; MenuItemSep5: TMenuItem; MenuItemMoveDown: TMenuItem; MenuItemMoveUp: TMenuItem; MenuItemMoveFile: TMenuItem; MenuItemContextDel: TMenuItem; MenuItemContextPaste: TMenuItem; MenuItemContextCopy: TMenuItem; MenuItemContextCut: TMenuItem; MenuItemRemoveFile: TMenuItem; MenuItemAbout: TMenuItem; MenuItemSep4: TMenuItem; MenuItemChangelog: TMenuItem; MenuItemHelp: TMenuItem; MenuItemToolsOptions: TMenuItem; MenuItemTools: TMenuItem; MenuItemDel: TMenuItem; MenuItemPaste: TMenuItem; MenuItemCopy: TMenuItem; MenuItemCut: TMenuItem; MenuItemEdit: TMenuItem; MenuItemExit: TMenuItem; MenuItemSep1: TMenuItem; MenuItemAddFolder: TMenuItem; MenuItemAddFiles: TMenuItem; OpenFileDlg: TOpenDialog; PanelUpDown: TPanel; PanelLeft: TPanel; PanelRight: TPanel; PopupMenuMain: TPopupMenu; OpenDirDlg: TSelectDirectoryDialog; StatusBar: TStatusBar; ToolsOptions: TAction; EditCopy: TEditCopy; EditCut: TEditCut; EditDelete: TEditDelete; EditPaste: TEditPaste; EditSelectAll: TEditSelectAll; FileExit: TAction; FileAddFolders: TAction; FileAddFiles: TAction; FileNew: TAction; ActionList: TActionList; MainMenu: TMainMenu; MenuItemNew: TMenuItem; MenuItemFile: TMenuItem; procedure EditCutExecute(Sender: TObject); procedure EditCopyExecute(Sender: TObject); procedure EditDeleteExecute(Sender: TObject); procedure EditUpdate(Sender: TObject); procedure EditDelUpdate(Sender: TObject); procedure FileAddFilesExecute(Sender: TObject); procedure FileAddFoldersExecute(Sender: TObject); procedure FileExitExecute(Sender: TObject); procedure FileMoveDownExecute(Sender: TObject); procedure FileMoveUpExecute(Sender: TObject); procedure FileNewExecute(Sender: TObject); procedure FileRemoveAllExecute(Sender: TObject); procedure FileRemoveExecute(Sender: TObject); procedure FileSmushExecute(Sender: TObject); procedure FileSmushUpdate(Sender: TObject); procedure FileUpdate(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure HelpAboutExecute(Sender: TObject); procedure ToolsOptionsExecute(Sender: TObject); procedure ViewPathExecute(Sender: TObject); private procedure ClearAllFiles; procedure MoveAndSelect(NewIndex: integer); procedure WriteFile(FileName: string; FileText: string); function CombineFiles(ListBox: TListBox): string; public AppSettings: TAppSettings; end; const NO_FILES = 'No Files Added...'; SEP_CHAR = {$IFDEF NotPosix} '\' {$ELSE} '/'{$ENDIF}; INI_FILE = 'settings.ini'; INI_SECT = 'Settings'; INI_GOTEXT = 'StatementEndText'; INI_LINE_BREAK = 'StatementEndLineBreak'; INI_EXECUTE = 'ExecuteOption'; INI_EXTERNAL_APP = 'ExternalApplication'; INI_FILTER = 'FilterAddFolderByType'; INI_FILTER_EXT = 'FilterAddFolderExtension'; DEF_GOTEXT = 'GO'; DEF_FILTER = '*.sql'; var FormMain: TFormMain; implementation {$R *.lfm} { TFormMain } procedure TFormMain.FileNewExecute(Sender: TObject); begin ShowMessage('Hello!'); end; procedure TFormMain.FileExitExecute(Sender: TObject); begin Self.Close; end; procedure TFormMain.FileMoveDownExecute(Sender: TObject); var NewIndex: integer; begin NewIndex:=ListBoxFiles.ItemIndex + 1; if NewIndex >= ListBoxFiles.Items.Count then exit; MoveAndSelect(NewIndex); end; procedure TFormMain.FileMoveUpExecute(Sender: TObject); var NewIndex: integer; begin NewIndex:=ListBoxFiles.ItemIndex - 1; if NewIndex = -1 then exit; MoveAndSelect(NewIndex); end; procedure TFormMain.FileAddFilesExecute(Sender: TObject); var i: integer; FileInfo: TFileInfo; begin if OpenFileDlg.Execute then begin if ListBoxFiles.Items.IndexOf(NO_FILES) > -1 then begin ListBoxFiles.Items.Delete(0); end; for i:=0 to OpenFileDlg.Files.Count - 1 do begin FileInfo:=TFileInfo.Create(OpenFileDlg.Files[i]); ListBoxFiles.AddItem(FileInfo.FilePath, FileInfo); end; end; end; procedure TFormMain.EditCutExecute(Sender: TObject); begin EditCopyExecute(Sender); ListBoxFiles.Items.Delete(ListBoxFiles.ItemIndex); end; procedure TFormMain.EditUpdate(Sender: TObject); begin TAction(Sender).Enabled:=false; if ListBoxFiles.ItemIndex > -1 then begin TAction(Sender).Enabled:=true; end; end; procedure TFormMain.EditCopyExecute(Sender: TObject); begin Clipboard.AsText:=ListBoxFiles.GetSelectedText; end; procedure TFormMain.EditDeleteExecute(Sender: TObject); begin if (Self.ActiveControl is TListBox) then begin FileRemoveExecute(Sender); end; end; procedure TFormMain.EditDelUpdate(Sender: TObject); begin TAction(Sender).Enabled:=false; if (ListBoxFiles.ItemIndex > -1) and (ListBoxFiles.GetSelectedText <> NO_FILES) then begin TAction(Sender).Enabled:=true; end; end; procedure TFormMain.FileAddFoldersExecute(Sender: TObject); var Sr: TSearchRec; Mask, DirPath: string; AddedOne: boolean; FileInfo: TFileInfo; begin if OpenDirDlg.Execute then begin Mask:='*.*'; if AppSettings.FilterFolder then begin Mask:=AppSettings.FilterExt; end; DirPath:=OpenDirDlg.FileName.TrimEnd(SEP_CHAR) + SEP_CHAR; if FindFirst(DirPath + Mask, faAnyFile, Sr) = 0 then begin repeat begin if (Sr.Name <> '.') and (Sr.Name <> '..') then begin FileInfo:=TFileInfo.Create(DirPath + Sr.Name); ListBoxFiles.AddItem(FileInfo.FilePath, FileInfo); AddedOne:=true; end; end; until FindNext(sr) <> 0; if AddedOne and (ListBoxFiles.Items.IndexOf(NO_FILES) > -1) then begin ListBoxFiles.Items.Delete(ListBoxFiles.Items.IndexOf(NO_FILES)); end; end; end; end; procedure TFormMain.FileRemoveAllExecute(Sender: TObject); begin ClearAllFiles; end; procedure TFormMain.FileRemoveExecute(Sender: TObject); var NewIndex: integer; begin NewIndex:=ListBoxFiles.ItemIndex; ListBoxFiles.Items.Objects[NewIndex].Free; ListBoxFiles.Items.Delete(NewIndex); if NewIndex >= ListBoxFiles.Items.Count then Dec(NewIndex); ListBoxFiles.ItemIndex:=NewIndex; if ListBoxFiles.Items.Count < 1 then ListBoxFiles.AddItem(NO_FILES, nil); end; procedure TFormMain.FileSmushExecute(Sender: TObject); var ResultStr, FilePath: string; FormEditor: TFormEditor; begin ResultStr:=CombineFiles(ListBoxFiles); case AppSettings.ExecuteOption of 0: // Save File begin if SaveDialog.Execute then WriteFile(SaveDialog.FileName, ResultStr); end; 1: // Show Editor begin FormEditor:=TFormEditor.Create(Self, ResultStr); FormEditor.Show; end; 2: // Open External begin FilePath:=GetTempFileName; WriteFile(FilePath, ResultStr); ExecuteProcess(AppSettings.ExternalApp, FilePath, []); end; end; end; procedure TFormMain.FileSmushUpdate(Sender: TObject); begin TAction(Sender).Enabled:=(ListBoxFiles.Items.Count > 1); end; procedure TFormMain.FileUpdate(Sender: TObject); begin if (ListBoxFiles.GetSelectedText <> '') and (ListBoxFiles.GetSelectedText <> NO_FILES) then begin TAction(Sender).Enabled:=true; end else begin TAction(Sender).Enabled:=false; end; end; procedure TFormMain.FormCreate(Sender: TObject); var Ini: TIniFile; begin Ini:=TIniFile.Create(INI_FILE); try with AppSettings do begin GoText:=Ini.ReadString(INI_SECT, INI_GOTEXT, DEF_GOTEXT); ExecuteOption:=Ini.ReadInteger(INI_SECT, INI_EXECUTE, 0); IncludeLineBreak:=Ini.ReadBool(INI_SECT, INI_LINE_BREAK, true); ExternalApp:=Ini.ReadString(INI_SECT, INI_EXTERNAL_APP, ''); FilterFolder:=Ini.ReadBool(INI_SECT, INI_FILTER, false); FilterExt:=Ini.ReadString(INI_SECT, INI_FILTER_EXT, DEF_FILTER); end; finally Ini.Free; end; ClearAllFiles; end; procedure TFormMain.FormDestroy(Sender: TObject); var Ini: TIniFile; begin Ini:=TIniFile.Create(INI_FILE); try with AppSettings do begin Ini.WriteString(INI_SECT, INI_GOTEXT, GoText); Ini.WriteInteger(INI_SECT, INI_EXECUTE, ExecuteOption); Ini.WriteBool(INI_SECT, INI_LINE_BREAK, IncludeLineBreak); Ini.WriteString(INI_SECT, INI_EXTERNAL_APP, ExternalApp); Ini.WriteBool(INI_SECT, INI_FILTER, FilterFolder); Ini.WriteString(INI_SECT, INI_FILTER_EXT, FilterExt); end; finally Ini.Free; end; ClearAllFiles; end; procedure TFormMain.HelpAboutExecute(Sender: TObject); var FormAbout: TFormAbout; begin FormAbout:=TFormAbout.Create(Self); FormAbout.ShowModal; end; procedure TFormMain.ToolsOptionsExecute(Sender: TObject); var OptionsDlg: TFormOptions; begin OptionsDlg:=TFormOptions.Create(Self, AppSettings); OptionsDlg.ShowModal; AppSettings:=OptionsDlg.AppSettings; FreeAndNil(OptionsDlg); end; procedure TFormMain.ViewPathExecute(Sender: TObject); var i: integer; NewStr: string; begin if Sender = ViewFullPath then begin ViewFullPath.Checked:=(not ViewFullPath.Checked); ViewFileOnly.Checked:=(not ViewFullPath.Checked); end else if Sender = ViewFileOnly then begin ViewFileOnly.Checked:=(not ViewFileOnly.Checked); ViewFullPath.Checked:=(not ViewFileOnly.Checked); end; for i:=0 to ListBoxFiles.Items.Count - 1 do begin if ListBoxFiles.Items.Strings[i] = NO_FILES then continue; NewStr:=''; if ViewFullPath.Checked then begin NewStr:=TFileInfo(ListBoxFiles.Items.Objects[i]).FilePath; end else if ViewFileOnly.Checked then begin NewStr:=TFileInfo(ListBoxFiles.Items.Objects[i]).FileName; end; ListBoxFiles.Items.Strings[i]:=NewStr; end; end; procedure TFormMain.ClearAllFiles; var i: integer; begin for i:=0 to ListBoxFiles.Items.Count - 1 do begin ListBoxFiles.Items.Objects[i].Free; end; ListBoxFiles.Clear; ListBoxFiles.AddItem(NO_FILES, nil); end; procedure TFormMain.MoveAndSelect(NewIndex: integer); begin ListBoxFiles.Items.Move(ListBoxFiles.ItemIndex, NewIndex); ListBoxFiles.ItemIndex:=NewIndex; end; function TFormMain.CombineFiles(ListBox: TListBox): string; var ErrorFiles: TStringList; FileStr, TotalStr, OneLine: string; TheFile: TextFile; i: integer; begin ErrorFiles:=TStringList.Create; TotalStr:=''; for i:=0 to ListBox.Count - 1 do begin AssignFile(TheFile, TFileInfo(ListBox.Items.Objects[i]).FilePath); Reset(TheFile); FileStr:=''; while not Eof(TheFile) do begin ReadLn(TheFile, OneLine); OneLine:=OneLine.Trim; if OneLine.EndsWith(AppSettings.GoText, true) then begin OneLine:=OneLine.Substring(0, OneLine.Length - AppSettings.GoText.Length); end; FileStr+=OneLine+LineEnding; end; CloseFile(TheFile); FileStr:=FileStr.Trim; TotalStr+=FileStr; if AppSettings.IncludeLineBreak then begin TotalStr+=LineEnding+LineEnding; end; TotalStr+=AppSettings.GoText; if AppSettings.IncludeLineBreak then begin TotalStr+=LineEnding+LineEnding; end; end; FreeAndNil(ErrorFiles); Result:=TotalStr.Trim; end; procedure TFormMain.WriteFile(FileName: string; FileText: string); var FileOut: TextFile; begin AssignFile(FileOut, FileName); ReWrite(FileOut); Write(FileOut, FileText); CloseFile(FileOut); end; end.
26.513185
76
0.696427
fc506459671fcad6bcbbb158e33e651866fce5f9
35,643
pas
Pascal
library/client/FHIR.Client.HTTP.pas
17-years-old/fhirserver
9575a7358868619311a5d1169edde3ffe261e558
[ "BSD-3-Clause" ]
null
null
null
library/client/FHIR.Client.HTTP.pas
17-years-old/fhirserver
9575a7358868619311a5d1169edde3ffe261e558
[ "BSD-3-Clause" ]
null
null
null
library/client/FHIR.Client.HTTP.pas
17-years-old/fhirserver
9575a7358868619311a5d1169edde3ffe261e558
[ "BSD-3-Clause" ]
null
null
null
unit FHIR.Client.HTTP; { Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } interface uses SysUtils, Classes, FHIR.Support.Utilities, FHIR.Support.Stream, FHIR.Support.Json, IdHTTP, IdSSLOpenSSL, IdComponent, {$IFDEF MSWINDOWS}FHIR.Web.WinInet, {$ENDIF} FHIR.Base.Objects, FHIR.Base.Parser, FHIR.Base.Common, FHIR.Client.Base, FHIR.Base.Lang, FHIR.Smart.Utilities; type TFhirHTTPClientHTTPVerb = (httpGet, httpPost, httpPut, httpDelete, httpOptions, httpPatch); // use only in one thread at a time TFHIRHTTPCommunicator = class (TFHIRClientCommunicator) private FUrl : String; FProxy: String; FUseIndy: boolean; FCertFile: String; FPassword: String; FUsername: String; FCertKey: String; FCertPWord: String; FTerminated : boolean; FTimeout: cardinal; FBytesToTransfer: Int64; indy : TIdHTTP; ssl : TIdSSLIOHandlerSocketOpenSSL; {$IFDEF MSWINDOWS} http : TFslWinInetClient; {$ENDIF} procedure createClient; function exchangeIndy(url: String; verb: TFhirHTTPClientHTTPVerb; source: TStream; headers : THTTPHeaders; mtStated : String = ''): TStream; {$IFDEF MSWINDOWS} function exchangeHTTP(url: String; verb: TFhirHTTPClientHTTPVerb; source: TStream; headers : THTTPHeaders; mtStated : String = ''): TStream; {$ENDIF} function makeMultipart(stream: TStream; streamName: string; params: TStringList; var mp : TStream) : String; function exchange(url : String; verb : TFhirHTTPClientHTTPVerb; source : TStream; headers : THTTPHeaders; mtStated : String = '') : TStream; function GetHeader(name : String) : String; procedure setHeader(name, value : String); function makeUrl(tail : String) : String; function makeUrlPath(tail : String) : String; function serialise(resource : TFhirResourceV):TStream; overload; function fetchResource(url : String; verb : TFhirHTTPClientHTTPVerb; source : TStream; headers : THTTPHeaders; mtStated : String = '') : TFhirResourceV; procedure SetTimeout(const Value: cardinal); procedure SetUseIndy(const Value: boolean); procedure SetCertFile(const Value: String); procedure SetCertPWord(const Value: String); procedure SetCertKey(const Value: String); procedure getSSLpassword(var Password: String); function authoriseByOWinIndy(server, username, password : String): TJsonObject; function authoriseByOWinHttp(server, username, password : String): TJsonObject; procedure HTTPWorkBegin(ASender: TObject; AWorkMode: TWorkMode; AWorkCountMax: Int64); procedure HTTPWork(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64); procedure HTTPWorkEnd(Sender: TObject; AWorkMode: TWorkMode); public constructor Create(url : String); overload; destructor Destroy; override; function link: TFHIRHTTPCommunicator; overload; property UseIndy : boolean read FUseIndy write SetUseIndy; // set this to true for a service, but you may have problems with SSL property proxy : String read FProxy write FProxy; property certFile : String read FCertFile write SetCertFile; property certKey : String read FCertKey write SetCertKey; property certPWord : String read FCertPWord write SetCertPWord; property username : String read FUsername write FUsername; property password : String read FPassword write FPassword; property timeout : cardinal read FTimeout write SetTimeout; function address : String; override; function conformanceV(summary : boolean) : TFHIRResourceV; override; function transactionV(bundle : TFHIRResourceV) : TFHIRResourceV; override; function createResourceV(resource : TFHIRResourceV; var id : String) : TFHIRResourceV; override; function readResourceV(atype : TFhirResourceTypeV; id : String) : TFHIRResourceV; override; function vreadResourceV(atype : TFhirResourceTypeV; id, vid : String) : TFHIRResourceV; override; function updateResourceV(resource : TFHIRResourceV) : TFHIRResourceV; overload; override; function updateResourceV(resource : TFHIRResourceV; search: String) : TFHIRResourceV; overload; override; function patchResourceV(atype : TFhirResourceTypeV; id : String; params : TFHIRResourceV) : TFHIRResourceV; overload; override; function patchResourceV(atype : TFhirResourceTypeV; id : String; patch : TJsonArray) : TFHIRResourceV; overload; override; procedure deleteResourceV(atype : TFHIRResourceTypeV; id : String); override; function searchV(atype : TFHIRResourceTypeV; allRecords : boolean; params : string) : TFHIRResourceV; overload; override; function searchPostV(atype : TFHIRResourceTypeV; allRecords : boolean; params : TStringList; resource : TFHIRResourceV) : TFHIRResourceV; override; function searchAgainV(link : String) : TFHIRResourceV; overload; override; function operationV(atype : TFHIRResourceTypeV; opName : String; params : TFHIRResourceV) : TFHIRResourceV; overload; override; function operationV(atype : TFHIRResourceTypeV; id, opName : String; params : TFHIRResourceV) : TFHIRResourceV; overload; override; function historyTypeV(atype : TFHIRResourceTypeV; allRecords : boolean; params : string) : TFHIRResourceV; override; function historyInstanceV(atype : TFHIRResourceTypeV; id : String; allRecords : boolean; params : string) : TFHIRResourceV; override; // special case that gives direct access to the communicator... function customGet(path : String; headers : THTTPHeaders) : TFslBuffer; override; function customPost(path : String; headers : THTTPHeaders; body : TFslBuffer) : TFslBuffer; override; procedure terminate; override; // special functions procedure authoriseByOWin(server, username, password : String); end; const CODES_TFhirHTTPClientHTTPVerb : array [TFhirHTTPClientHTTPVerb] of String = ('GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'); implementation function readIdFromLocation(resType, location : String) : String; var a : TArray<String>; begin a := location.split(['/']); if length(a) < 2 then raise EFHIRException.create('Unable to process location header (too short)'); if a[length(a)-2] = '_history' then begin if length(a) < 4 then raise EFHIRException.create('Unable to process location header (too short for a version specific location). Location: '+location); if a[length(a)-4] <> resType then raise EFHIRException.create('Unable to process location header (version specific, but resource doesn''t match). Location: '+location); result := a[length(a)-3]; // 1 for offset, 2 for _history and vers end else begin if a[length(a)-2] <> resType then raise EFHIRException.create('Unable to process location header (resource doesn''t match). Location: '+location); result := a[length(a)-1]; end; end; { TFHIRHTTPCommunicator } constructor TFHIRHTTPCommunicator.Create(url: String); begin inherited create; FUrl := url; {$IFNDEF WINDOWS} FUseIndy := true; {$ENDIF} end; destructor TFHIRHTTPCommunicator.destroy; begin ssl.Free; indy.free; {$IFDEF MSWINDOWS} http.Free; {$ENDIF} inherited; end; function TFHIRHTTPCommunicator.link: TFHIRHTTPCommunicator; begin result := TFHIRHTTPCommunicator(inherited Link); end; function TFHIRHTTPCommunicator.address: String; begin result := FUrl; end; procedure TFHIRHTTPCommunicator.SetUseIndy(const Value: boolean); begin {$IFDEF MSWINDOWS} FUseIndy := Value; {$ELSE} // ignore...? {$ENDIF} end; procedure TFHIRHTTPCommunicator.SetTimeout(const Value: cardinal); begin FTimeout := Value; createClient; if FUseIndy then begin indy.IOHandler.ReadTimeout := Value; indy.ReadTimeout := Value; end; end; procedure TFHIRHTTPCommunicator.SetCertFile(const Value: String); begin FCertFile := Value; indy.free; indy := nil; {$IFDEF MSWINDOWS} http.Free; http := nil; {$ENDIF} end; procedure TFHIRHTTPCommunicator.SetCertKey(const Value: String); begin FCertKey := Value; indy.free; indy := nil; {$IFDEF MSWINDOWS} http.Free; http := nil; {$ENDIF} end; procedure TFHIRHTTPCommunicator.SetCertPWord(const Value: String); begin FCertPWord := Value; indy.free; indy := nil; {$IFDEF MSWINDOWS} http.Free; http := nil; {$ENDIF} end; procedure TFHIRHTTPCommunicator.getSSLpassword(var Password: String); begin Password := FCertPWord; end; function TFHIRHTTPCommunicator.makeMultipart(stream: TStream; streamName: string; params: TStringList; var mp : TStream) : String; var m : TMimeMessage; p : TMimePart; s : String; i : integer; begin m := TMimeMessage.create; try p := m.AddPart(NewGuidURN); p.ContentDisposition := 'form-data; name="'+streamName+'"'; p.Content.LoadFromStream(stream); for i := 0 to params.Count -1 do begin s := params.Names[i]; p := m.AddPart(NewGuidURN); p.ContentDisposition := 'form-data; name="'+s+'"'; p.Content.AsBytes := TEncoding.UTF8.GetBytes(params.ValueFromIndex[i]); end; m.Boundary := '---'+AnsiString(copy(GUIDToString(CreateGUID), 2, 36)); m.start := m.parts[0].Id; result := 'multipart/form-data; boundary='+String(m.Boundary); mp := TMemoryStream.Create; m.WriteToStream(mp, false); finally m.free; end; end; function TFHIRHTTPCommunicator.makeUrl(tail: String): String; begin result := FURL; if not result.EndsWith('/') and (tail <> '') then result := result + '/'; result := result + tail; end; function TFHIRHTTPCommunicator.makeUrlPath(tail: String): String; var s : String; begin StringSplit(FURL, '://', s, result); StringSplit(result, '://', s, result); if not result.EndsWith('/') then result := result + '/'; result := result + tail; end; function TFHIRHTTPCommunicator.exchange(url : String; verb : TFhirHTTPClientHTTPVerb; source : TStream; headers : THTTPHeaders; mtStated : String = '') : TStream; begin if Assigned(FClient.OnProgress) then FClient.OnProgress(FClient, 'Requesting', 0, false); FHeaders.accept := ''; FHeaders.prefer := ''; createClient; FClient.LastURL := url; try if FUseIndy then result := exchangeIndy(url, verb, source, headers, mtStated) {$IFDEF MSWINDOWS} else result := exchangeHTTP(url, verb, source, headers, mtStated) {$ENDIF} finally if Assigned(FClient.OnProgress) then FClient.OnProgress(FClient, 'Done', 100, true); // just make sure this fires with a done. end; end; procedure TFHIRHTTPCommunicator.createClient; begin if FUseIndy then begin if (indy = nil) then begin indy := TIdHTTP.create(nil); indy.request.userAgent := 'FHIR Client'; indy.OnWork := HTTPWork; indy.OnWorkBegin := HTTPWorkBegin; indy.OnWorkEnd := HTTPWorkEnd; indy.ReadTimeout := 30000; indy.HandleRedirects := true; if (proxy <> '') then begin try indy.ProxyParams.ProxyServer := proxy.Split([':'])[0]; indy.ProxyParams.ProxyPort := StrToInt(proxy.Split([':'])[1]); except raise EFHIRException.create('Unable to process proxy "'+proxy+'" - use address:port'); end; end; ssl := TIdSSLIOHandlerSocketOpenSSL.Create(nil); indy.IOHandler := ssl; ssl.SSLOptions.Mode := sslmClient; ssl.SSLOptions.SSLVersions := [sslvTLSv1_2]; ssl.SSLOptions.Method := sslvTLSv1_2; if certFile <> '' then begin ssl.SSLOptions.CertFile := certFile; if certKey <> '' then ssl.SSLOptions.KeyFile := certKey else ssl.SSLOptions.KeyFile := ChangeFileExt(certFile,'.key'); ssl.OnGetPassword := getSSLpassword; end; end; end {$IFDEF MSWINDOWS} else if http = nil then begin if certFile <> '' then raise EFHIRException.create('Certificates are not supported with winInet yet'); // have to figure out how to do that ... http := TFslWinInetClient.Create; http.UseWindowsProxySettings := true; http.UserAgent := 'FHIR Client'; end; {$ENDIF} end; function TFHIRHTTPCommunicator.serialise(resource: TFhirResourceV): TStream; var ok : boolean; comp : TFHIRComposer; begin ok := false; result := TBytesStream.create; try comp := FClient.makeComposer(FClient.format, OutputStyleNormal); try comp.Compose(result, resource); finally comp.free; end; result.position := 0; ok := true; finally if not ok then result.free; end; end; function TFHIRHTTPCommunicator.exchangeIndy(url : String; verb : TFhirHTTPClientHTTPVerb; source : TStream; headers : THTTPHeaders; mtStated : String = '') : TStream; var comp : TFHIRParser; ok : boolean; cnt : String; op : TFHIROperationOutcomeW; iss : TFhirOperationOutcomeIssueW; begin if mtStated <> '' then indy.Request.ContentType := mtStated else indy.Request.ContentType := MIMETYPES_TFHIRFormat_Version[FClient.format, FCLient.version]+'; charset=utf-8'; indy.Request.Accept := indy.Request.ContentType; if headers.contentType <> '' then indy.Request.ContentType := headers.contentType; if headers.accept <> '' then indy.Request.Accept := headers.accept; if headers.prefer <> '' then indy.Request.CustomHeaders.values['Prefer'] := headers.prefer; if FClient.smartToken <> nil then indy.Request.CustomHeaders.values['Authorization'] := 'Bearer '+FClient.smartToken.accessToken; if password <> '' then begin indy.Request.BasicAuthentication:= true; indy.Request.UserName := UserName; indy.Request.Password := Password; end; if FCLient.provenance <> nil then indy.Request.CustomHeaders.values['X-Provenance'] := ProvenanceString else if indy.Request.CustomHeaders.IndexOfName('X-Provenance') > -1 then indy.Request.CustomHeaders.Delete(indy.Request.CustomHeaders.IndexOfName('X-Provenance')); ok := false; result := TMemoryStream.create; Try Try case verb of httpGet : indy.Get(url, result); httpPost : indy.Post(url, source, result); httpPut : indy.Put(url, source, result); httpDelete : indy.delete(url); httpOptions: indy.Options(url); {$IFNDEF VER260} httpPatch : indy.Patch(url, source, result); {$ENDIF} else raise EFHIRException.create('Unknown HTTP method '+inttostr(ord(verb))); end; FClient.Logger.logExchange(CODES_TFhirHTTPClientHTTPVerb[verb], url, indy.ResponseText, indy.Request.RawHeaders.Text, indy.Response.RawHeaders.Text, source, result); if (indy.ResponseCode < 200) or (indy.ResponseCode >= 300) Then raise EFHIRException.create('unexpected condition'); ok := true; if (result <> nil) then result.Position := 0; FHeaders.contentType := indy.Response.ContentType; FHeaders.location := indy.Response.Location; FHeaders.LastOperationId := indy.Response.RawHeaders.Values['X-Request-Id']; FHeaders.Progress := indy.Response.RawHeaders.Values['X-Progress']; FHeaders.contentLocation := indy.Response.RawHeaders.Values['Content-Location']; FClient.LastStatus := indy.ResponseCode; FClient.LastStatusMsg := indy.ResponseText; except on E:EIdHTTPProtocolException do begin FClient.Logger.logExchange(CODES_TFhirHTTPClientHTTPVerb[verb], url, indy.ResponseText, indy.Request.RawHeaders.Text, indy.Response.RawHeaders.Text, source, result); cnt := e.ErrorMessage; if cnt = '' then cnt := e.message; FHeaders.contentType := indy.Response.ContentType; FHeaders.location := indy.Response.Location; FHeaders.contentLocation := indy.Response.RawHeaders.Values['Content-Location']; FHeaders.LastOperationId := indy.Response.RawHeaders.Values['X-Request-Id']; FHeaders.Progress := indy.Response.RawHeaders.Values['X-Request-Id']; FClient.LastStatus := indy.ResponseCode; FClient.LastStatusMsg := indy.ResponseText; if StringFind(cnt, 'OperationOutcome') > 0 then begin removeBom(cnt); comp := FClient.makeParser(FClient.format); try comp.source := TStringStream.create(cnt); comp.Parse; if (comp.resource <> nil) and (comp.resource.fhirType = 'OperationOutcome') then begin op := opWrapper.create(comp.resource.Link); try if (op.hasText) then Raise EFHIRClientException.create(op.text, op.link) else if (op.issueCount > 0) then for iss in op.issues.forEnum do Raise EFHIRClientException.create(iss.display, op.link) else raise EFHIRException.create(cnt) finally op.Free; end; end else raise EFHIRException.create(cnt) finally comp.source.free; comp.Free; end; end else raise EFHIRException.create(cnt) end; on e : exception do raise; end; finally if not ok then result.free; end; end; {$IFDEF MSWINDOWS} function TFHIRHTTPCommunicator.exchangeHTTP(url: String; verb: TFhirHTTPClientHTTPVerb; source: TStream; headers : THTTPHeaders; mtStated : String = ''): TStream; var op : TFhirOperationOutcomeW; code : integer; procedure processException; var cnt : string; p : TFHIRParser; begin cnt := http.Response.AsText; if StringFind(cnt, 'OperationOutcome') > 0 then begin removeBom(cnt); p := FClient.makeParser(FClient.format); try p.source := TBytesStream.create(http.response.AsBytes); p.Parse; if (p.resource <> nil) and (p.resource.fhirType = 'OperationOutcome') then begin op := opWrapper.create(p.resource.link); try if (op.hasText) then Raise EFHIRClientException.create(op.text, op.link) else raise EFHIRException.create(cnt) finally op.Free; end; end else raise EFHIRException.create(cnt) finally p.source.free; p.Free; end; end else if cnt = '' then raise EFHIRException.create(http.ResponseCode+' ' +http.ResponseText) else raise EFHIRException.create(cnt) end; begin if mtStated <> '' then http.RequestType := mtStated else http.RequestType := MIMETYPES_TFHIRFormat_Version[FClient.format, FCLient.version]+'; charset=utf-8'; http.ResponseType := http.RequestType; if headers.contentType <> '' then http.RequestType := headers.contentType; if FClient.provenance <> nil then http.Headers['X-Provenance'] := ProvenanceString else http.Headers.Remove('X-Provenance'); if password <> '' then begin http.Username := username; http.Password := Password; end; // todo: if smartToken <> nil then // todo: indy.Request.CustomHeaders.values['Authorization'] := 'Bearer '+smartToken.accessToken; ? how to set this on wininet repeat http.SetAddress(url); case verb of httpGet : begin http.RequestMethod := 'GET'; end; httpPost : begin http.RequestMethod := 'POST'; http.Request := TFslBuffer.create; http.Request.LoadFromStream(source); end; httpPut : begin http.RequestMethod := 'PUT'; http.Request.LoadFromStream(source); end; httpDelete : http.RequestMethod := 'DELETE'; httpPatch : begin http.RequestMethod := 'PATCH'; http.RequestType := 'application/json-patch+json; charset=utf-8'; end; httpOptions : begin http.RequestMethod := 'OPTIONS'; end; end; http.Response := TFslBuffer.create; http.Execute; code := StrToInt(http.ResponseCode); FClient.LastStatus := code; FClient.LastStatusMsg := http.ResponseText; if (code < 200) or (code >= 600) Then raise EFHIRException.create('unexpected condition'); if (code >= 300) and (code < 400) then url := http.getResponseHeader('Location'); until (code < 300) or (code >= 400); FHeaders.contentType := http.Headers['Content-Type']; FHeaders.location := http.Headers['Location']; FHeaders.contentLocation := http.Headers['Content-Location']; FHeaders.LastOperationId := http.Headers['X-Request-Id']; FHeaders.progress := http.Headers['X-Progress']; if code >= 300 then processException; result := TMemoryStream.Create; // if this breaks, the stream leaks http.Response.SaveToStream(result); result.Position := 0; end; {$ENDIF} function TFHIRHTTPCommunicator.fetchResource(url: String; verb: TFhirHTTPClientHTTPVerb; source: TStream; headers : THTTPHeaders; mtStated : String = ''): TFhirResourceV; var ret : TStream; p : TFHIRParser; begin FTerminated := false; ret := exchange(url, verb, source, headers, mtStated); if FTerminated then abort; try if ret.Size = 0 then result := nil else begin p := FClient.makeParser(FClient.format); try p.source := ret; p.parse; if (p.resource = nil) then raise EFHIRException.create('No response bundle'); result := p.resource.link; finally p.free; end; end; finally ret.free; end; end; procedure TFHIRHTTPCommunicator.setHeader(name, value: String); begin createClient; if FUseIndy then indy.Request.RawHeaders.Values[name] := value {$IFDEF MSWINDOWS} else http.Headers.AddOrSetValue(name, value); {$ENDIF} end; function TFHIRHTTPCommunicator.GetHeader(name: String): String; begin createClient; if FUseIndy then result := indy.Response.RawHeaders.Values[name] {$IFDEF MSWINDOWS} else result := http.getResponseHeader(name); {$ENDIF} end; procedure TFHIRHTTPCommunicator.terminate; begin if not FUseIndy then raise EFHIRException.create('Cancel not supported') else begin FTerminated := true; if FUseIndy and (indy <> nil) then indy.Disconnect; end; end; function TFHIRHTTPCommunicator.conformanceV(summary : boolean): TFHIRResourceV; var headers : THTTPHeaders; begin if summary then result := FetchResource(MakeUrl('metadata')+'?_summary=true', httpGet, nil, headers) else result := FetchResource(MakeUrl('metadata'), httpGet, nil, headers); end; function TFHIRHTTPCommunicator.transactionV(bundle : TFHIRResourceV) : TFHIRResourceV; Var src : TStream; headers : THTTPHeaders; begin src := serialise(bundle); try result := fetchResource(makeUrl(''), httpPost, src, headers); finally src.free; end; end; function TFHIRHTTPCommunicator.updateResourceV(resource: TFHIRResourceV; search: String): TFHIRResourceV; Var src : TStream; headers : THTTPHeaders; vId : String; begin vId := getResourceVersionId(resource); if vId <> '' then SetHeader('Content-Location', MakeUrlPath(resource.fhirType+'/'+resource.id+'/history/'+vId)); src := serialise(resource); try if search <> '' then result := fetchResource(MakeUrl(resource.fhirType+'?'+search), httpPut, src, headers) else result := fetchResource(MakeUrl(resource.fhirType+'/'+resource.id), httpPut, src, headers); finally src.free; end; end; function TFHIRHTTPCommunicator.createResourceV(resource: TFhirResourceV; var id : String): TFHIRResourceV; Var src : TStream; headers : THTTPHeaders; begin src := serialise(resource); try result := nil; try result := fetchResource(MakeUrl(resource.fhirType), httpPost, src, headers); id := readIdFromLocation(resource.fhirType, getHeader('Location')); result.link; finally result.free; end; finally src.free; end; end; function TFHIRHTTPCommunicator.readResourceV(atype: TFhirResourceTypeV; id: String): TFHIRResourceV; var headers : THTTPHeaders; begin result := nil; try result := fetchResource(MakeUrl(AType+'/'+id), httpGet, nil, headers); result.link; finally result.free; end; end; function TFHIRHTTPCommunicator.vreadResourceV(atype: TFhirResourceTypeV; id, vid: String): TFHIRResourceV; var headers : THTTPHeaders; begin result := nil; try result := fetchResource(MakeUrl(AType+'/'+id+'/_history/'+vid), httpGet, nil, headers); result.link; finally result.free; end; end; function TFHIRHTTPCommunicator.updateResourceV(resource : TFhirResourceV) : TFHIRResourceV; begin Result := updateResourceV(resource, '') end; procedure TFHIRHTTPCommunicator.deleteResourceV(atype : TFhirResourceTypeV; id : String); var headers : THTTPHeaders; begin exchange(MakeUrl(aType+'/'+id), httpDelete, nil, headers).free; end; function TFHIRHTTPCommunicator.searchV(atype: TFhirResourceTypeV; allRecords: boolean; params: string): TFHIRResourceV; var s : String; bnd : TFHIRResourceV; bh : TFHIRBundleW; headers : THTTPHeaders; res : TFHIRResourceV; begin res := fetchResource(makeUrl(aType)+'?'+params, httpGet, nil, headers); if res = nil then raise Exception.Create('Network error: nothing returned from server?'); bh := FClient.BundleFactory.Create(res); try if bh.resource.fhirType <> 'Bundle' then raise EFHIRException.create('Found a resource of type '+bh.resource.fhirType+' expecting a Bundle'); s := bh.next; while AllRecords and (s <> '') do begin bnd := fetchResource(s, httpGet, nil, headers); try bh.addEntries(bnd); s := bh.next(bnd); finally bnd.free; end; end; if allRecords then bh.clearLinks; result := bh.resource.Link; finally bh.Free; end; end; function TFHIRHTTPCommunicator.searchAgainV(link: String): TFHIRResourceV; var headers : THTTPHeaders; begin result := fetchResource(link, httpGet, nil, headers) as TFHIRResourceV; end; function TFHIRHTTPCommunicator.searchPostV(atype: TFhirResourceTypeV; allRecords: boolean; params: TStringList; resource: TFhirResourceV): TFHIRResourceV; var src, frm : TStream; ct : String; headers : THTTPHeaders; begin src := serialise(resource); try src.Position := 0; ct := makeMultipart(src, 'src', params, frm); try result := fetchResource(makeUrl(aType)+'/_search', httpPost, frm, headers) as TFHIRResourceV; finally frm.Free; end; finally src.free; end; end; function TFHIRHTTPCommunicator.operationV(atype : TFhirResourceTypeV; opName : String; params : TFHIRResourceV) : TFHIRResourceV; Var src : TStream; headers : THTTPHeaders; begin src := serialise(params); try src.Position := 0; if aType = '' then result := fetchResource(makeUrl('$'+opName), httpPost, src, headers) else result := fetchResource(makeUrl(aType)+'/$'+opName, httpPost, src, headers); finally src.free; end; end; function TFHIRHTTPCommunicator.operationV(atype : TFhirResourceTypeV; id, opName : String; params : TFHIRResourceV) : TFHIRResourceV; Var src : TStream; headers : THTTPHeaders; begin if params = nil then begin result := fetchResource(makeUrl(aType)+'/'+id+'/$'+opName, httpGet, nil, headers); end else begin src := serialise(params); try src.Position := 0; result := fetchResource(makeUrl(aType)+'/'+id+'/$'+opName, httpPost, src, headers); finally src.free; end; end; end; function TFHIRHTTPCommunicator.patchResourceV(atype: TFhirResourceTypeV; id: String; patch: TJsonArray): TFHIRResourceV; Var src : TStream; headers : THTTPHeaders; begin src := TMemoryStream.Create; try TJSONWriter.writeArray(src, patch, false); src.Position := 0; result := fetchResource(MakeUrl(atype+'/'+id), httpPatch, src, headers, 'application/json-patch+json'); finally src.free; end; end; function TFHIRHTTPCommunicator.patchResourceV(atype: TFhirResourceTypeV; id: String; params: TFHIRResourceV): TFHIRResourceV; Var src : TStream; headers : THTTPHeaders; begin src := serialise(params); try result := fetchResource(MakeUrl(atype+'/'+id), httpPatch, src, headers); finally src.free; end; end; function TFHIRHTTPCommunicator.historyTypeV(atype: TFhirResourceTypeV; allRecords: boolean; params: string): TFHIRResourceV; var s : String; feed : TFHIRResourceV; i : integer; headers : THTTPHeaders; bh : TFHIRBundleW; begin // client.Request.RawHeaders.Values['Content-Location'] := MakeUrlPath(CODES_TFhirResourceType[resource.resourceType]+'/'+id+'/history/'+ver); notify('Fetch History for '+aType); bh := FClient.BundleFactory.Create(fetchResource(makeUrl(aType)+'/_history?'+params, httpGet, nil, headers) as TFHIRResourceV); try s := bh.next; i := 1; while AllRecords and (s <> '') do begin inc(i); notify('Fetch History for '+aType+' page '+inttostr(i)); feed := fetchResource(s, httpGet, nil, headers) as TFHIRResourceV; try bh.addEntries(feed); s := bh.next(feed); finally feed.free; end; end; if allRecords then bh.clearLinks;; result := bh.resource.Link; finally bh.Free; end; end; function TFHIRHTTPCommunicator.historyInstanceV(atype: TFhirResourceTypeV; id : String; allRecords: boolean; params: string): TFHIRResourceV; var s : String; feed : TFHIRResourceV; i : integer; headers : THTTPHeaders; bh : TFHIRBundleW; begin // client.Request.RawHeaders.Values['Content-Location'] := MakeUrlPath(CODES_TFhirResourceType[resource.resourceType]+'/'+id+'/history/'+ver); notify('Fetch History for '+aType+'/'+id); bh := FClient.BundleFactory.Create(fetchResource(makeUrl(aType)+'/'+id+'/_history?'+params, httpGet, nil, headers) as TFHIRResourceV); try s := bh.next; i := 1; while AllRecords and (s <> '') do begin inc(i); notify('Fetch History for '+aType+'/'+id+' page '+inttostr(i)); feed := fetchResource(s, httpGet, nil, headers) as TFHIRResourceV; try bh.addEntries(feed); s := bh.next(feed); finally feed.free; end; end; if allRecords then bh.clearLinks;; result := bh.resource.Link; finally bh.Free; end; end; procedure TFHIRHTTPCommunicator.HTTPWork(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64); begin if FBytesToTransfer = 0 then // No Update File Exit; if Assigned(FClient.OnProgress) then FClient.OnProgress(FClient, 'Downloading', Round((AWorkCount / FBytesToTransfer) * 100), false); end; procedure TFHIRHTTPCommunicator.HTTPWorkBegin(ASender: TObject; AWorkMode: TWorkMode; AWorkCountMax: Int64); begin FBytesToTransfer := AWorkCountMax; if Assigned(FClient.OnProgress) then FClient.OnProgress(FClient, 'Download Starting', 0, false); end; procedure TFHIRHTTPCommunicator.HTTPWorkEnd(Sender: TObject; AWorkMode: TWorkMode); begin FBytesToTransfer := 0; if Assigned(FClient.OnProgress) then FClient.OnProgress(FClient, 'Downloaded', 100, true); end; function TFHIRHTTPCommunicator.customGet(path: String; headers: THTTPHeaders): TFslBuffer; var ret : TStream; begin if isAbsoluteUrl(path) then ret := exchange(path, httpGet, nil, headers) else ret := exchange(URLPath([Furl, path]), httpGet, nil, headers); try result := TFslBuffer.Create; try result.LoadFromStream(ret); result.link; finally result.Free; end; finally ret.Free; end; end; function TFHIRHTTPCommunicator.customPost(path: String; headers: THTTPHeaders; body : TFslBuffer): TFslBuffer; var req : TMemoryStream; ret : TStream; begin req := TMemoryStream.Create; try body.SaveToStream(req); req.Position := 0; ret := exchange(Furl+'/'+path, httpPost, req, headers); try result := TFslBuffer.Create; try result.LoadFromStream(ret); result.link; finally result.Free; end; finally ret.Free; end; finally req.Free; end; end; procedure TFHIRHTTPCommunicator.authoriseByOWin(server, username, password: String); var token : TJsonObject; begin if FUseIndy then token := authoriseByOWinIndy(server, username, password) else token := authoriseByOWinHttp(server, username, password); try FClient.smartToken := TClientAccessToken.Create; FClient.smartToken.accessToken := token.str['access_token']; FClient.smartToken.expires := now + (StrToInt(token.num['expires_in']) * DATETIME_SECOND_ONE); finally token.Free; end; end; function TFHIRHTTPCommunicator.authoriseByOWinHttp(server, username, password: String): TJsonObject; begin raise EFHIRTodo.create('TFHIRHTTPCommunicator.authoriseByOWinHttp'); end; function TFHIRHTTPCommunicator.authoriseByOWinIndy(server, username, password: String): TJsonObject; var ss : TStringStream; resp : TMemoryStream; begin createClient; indy.Request.ContentType := 'application/x-www-form-urlencoded'; ss := TStringStream.Create('grant_type=password&username='+username+'&password='+(password)); try resp := TMemoryStream.create; Try indy.Post(server, ss, resp); if (indy.ResponseCode < 200) or (indy.ResponseCode >= 300) Then raise EFHIRException.create('unexpected condition'); resp.Position := 0; result := TJSONParser.Parse(resp); finally resp.Free; end; finally ss.Free; end; end; (* function TFHIRHTTPCommunicator.Convert(stream: TStream): TStream; var s : String; begin if FALlowR2 then begin s := StreamToString(stream, TEncoding.UTF8); if s.Contains('<Conformance') then begin s := s.Replace('<Conformance', '<CapabilityStatement'); s := s.Replace('</Conformance', '</CapabilityStatement'); s := s.Replace('"Conformance"', '"CapabilityStatement"'); s := s.Replace('"DiagnosticOrder"', '"DiagnosticRequest"'); end; result := TStringStream.Create(s, TEncoding.UTF8) end else result := stream; end; *) end.
31.102094
173
0.688691
8349b1e10d0d8b4c15632976ad92fd3bd95232fb
306
dpr
Pascal
Projects/Lazarus_Bible/D24/WinesEntry.dpr
joecare99/Public
9eee060fbdd32bab33cf65044602976ac83f4b83
[ "MIT" ]
11
2017-06-17T05:13:45.000Z
2021-07-11T13:18:48.000Z
Projects/Lazarus_Bible/2009/WinesEntry.dpr
joecare99/Public
9eee060fbdd32bab33cf65044602976ac83f4b83
[ "MIT" ]
2
2019-03-05T12:52:40.000Z
2021-12-03T12:34:26.000Z
Projects/Lazarus_Bible/DXE2/WinesEntry.dpr
joecare99/Public
9eee060fbdd32bab33cf65044602976ac83f4b83
[ "MIT" ]
6
2017-09-07T09:10:09.000Z
2022-02-19T20:19:58.000Z
program WinesEntry; uses Forms, Frm_WinesEntryMain in '..\Source\WinesEntry\Frm_WinesEntryMain.pas' {MainForm}; {$R *.RES} {$E EXE} begin Application.Initialize; Application.Title := 'Demo: WinesEntry'; Application.CreateForm(TMainForm, MainForm); Application.Run; end.
23.538462
83
0.686275
475d1e35a8b10272b43b06950de7aae18574faca
25,249
dfm
Pascal
DataModule/udmRelatorios.dfm
ViniMilagres/Sistema
c597e8065ea02cd4666b4b09d0794c3ad37d9830
[ "MIT" ]
1
2021-04-08T00:53:33.000Z
2021-04-08T00:53:33.000Z
DataModule/udmRelatorios.dfm
ViniMilagres/Sistema
c597e8065ea02cd4666b4b09d0794c3ad37d9830
[ "MIT" ]
null
null
null
DataModule/udmRelatorios.dfm
ViniMilagres/Sistema
c597e8065ea02cd4666b4b09d0794c3ad37d9830
[ "MIT" ]
null
null
null
object DataModule2: TDataModule2 OldCreateOrder = False Height = 341 Width = 505 object frxDBDataset1: TfrxDBDataset UserName = 'frxDBDataset1' CloseDataSource = False FieldAliases.Strings = ( 'id=id' 'nome=nome' 'login=login' 'senha=senha' 'status=status' 'dt_cadastro=dt_cadastro') DataSet = DataModule1.cdsUsuarios BCDToCurrency = False Left = 184 Top = 72 end object frxReport: TfrxReport Version = '6.8.11' DotMatrixReport = False IniFile = '\Software\Fast Reports' PreviewOptions.Buttons = [pbPrint, pbLoad, pbSave, pbExport, pbZoom, pbFind, pbOutline, pbPageSetup, pbTools, pbEdit, pbNavigator, pbExportQuick, pbCopy, pbSelection] PreviewOptions.Zoom = 1.000000000000000000 PrintOptions.Printer = 'Default' PrintOptions.PrintOnSheet = 0 ReportOptions.CreateDate = 44171.836043969900000000 ReportOptions.LastChange = 44171.964352002320000000 ScriptLanguage = 'PascalScript' ScriptText.Strings = ( 'begin' '' 'end.') Left = 88 Top = 72 Datasets = < item DataSet = frxDBDataset1 DataSetName = 'frxDBDataset1' end> Variables = <> Style = <> object Data: TfrxDataPage Height = 1000.000000000000000000 Width = 1000.000000000000000000 end object Page1: TfrxReportPage Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -7 Font.Name = 'Arial' Font.Style = [] PaperWidth = 210.000000000000000000 PaperHeight = 297.000000000000000000 PaperSize = 9 LeftMargin = 10.000000000000000000 RightMargin = 10.000000000000000000 TopMargin = 10.000000000000000000 BottomMargin = 10.000000000000000000 Frame.Typ = [] MirrorMode = [] object ReportTitle1: TfrxReportTitle FillType = ftBrush Frame.Typ = [] Height = 37.795300000000000000 Top = 18.897650000000000000 Width = 718.110700000000000000 object Shape6: TfrxShapeView AllowVectorExport = True Width = 721.890230000000000000 Height = 30.236240000000000000 Frame.Typ = [] end object Memo1: TfrxMemoView AllowVectorExport = True Left = 204.094620000000000000 Top = 7.559060000000000000 Width = 230.551330000000000000 Height = 18.897650000000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -19 Font.Name = 'Arial' Font.Style = [fsBold] Frame.Typ = [] HAlign = haCenter Memo.UTF8W = ( 'Relat'#243'rio de Usu'#225'rios') ParentFont = False VAlign = vaCenter end object Date: TfrxMemoView IndexTag = 1 AllowVectorExport = True Left = 514.236550000000000000 Top = 14.897650000000000000 Width = 196.535560000000000000 Height = 11.338590000000000000 DisplayFormat.FormatStr = 'dd mmm yyyy' DisplayFormat.Kind = fkDateTime Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -11 Font.Name = 'Arial' Font.Style = [] Frame.Typ = [] HAlign = haRight Memo.UTF8W = ( '[Date]') ParentFont = False VAlign = vaCenter end object Page: TfrxMemoView IndexTag = 1 AllowVectorExport = True Left = 664.417750000000000000 Top = 2.000000000000000000 Width = 45.354360000000000000 Height = 11.338590000000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -11 Font.Name = 'Arial' Font.Style = [] Frame.Typ = [] HAlign = haRight Memo.UTF8W = ( '[Page]') ParentFont = False VAlign = vaBottom end object Memo6: TfrxMemoView AllowVectorExport = True Left = 649.488560000000000000 Top = 1.000000000000000000 Width = 49.133890000000000000 Height = 11.338590000000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -8 Font.Name = 'Arial' Font.Style = [fsBold] Frame.Typ = [] HAlign = haCenter Memo.UTF8W = ( 'P'#225'g') ParentFont = False VAlign = vaCenter end end object MasterData1: TfrxMasterData FillType = ftBrush Frame.Typ = [] Height = 26.456710000000000000 Top = 170.078850000000000000 Width = 718.110700000000000000 DataSet = frxDBDataset1 DataSetName = 'frxDBDataset1' RowCount = 0 object Shape3: TfrxShapeView AllowVectorExport = True Left = 98.267780000000000000 Width = 238.110390000000000000 Height = 26.456710000000000000 Frame.Typ = [] end object Shape1: TfrxShapeView AllowVectorExport = True Width = 714.331170000000000000 Height = 26.456710000000000000 Frame.Typ = [] end object frxDBDataset1id: TfrxMemoView IndexTag = 1 AllowVectorExport = True Left = 11.338590000000000000 Top = 2.559060000000000000 Width = 79.370130000000000000 Height = 18.897650000000000000 DataField = 'id' DataSet = frxDBDataset1 DataSetName = 'frxDBDataset1' Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -13 Font.Name = 'Arial' Font.Style = [] Frame.Typ = [] Memo.UTF8W = ( '[frxDBDataset1."id"]') ParentFont = False end object frxDBDataset1login: TfrxMemoView IndexTag = 1 AllowVectorExport = True Left = 105.826840000000000000 Top = 2.559060000000000000 Width = 222.992270000000000000 Height = 18.897650000000000000 DataField = 'login' DataSet = frxDBDataset1 DataSetName = 'frxDBDataset1' Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -13 Font.Name = 'Arial' Font.Style = [] Frame.Typ = [] Memo.UTF8W = ( '[frxDBDataset1."login"]') ParentFont = False end object frxDBDataset1login1: TfrxMemoView IndexTag = 1 AllowVectorExport = True Left = 340.157700000000000000 Top = 2.559060000000000000 Width = 200.315090000000000000 Height = 18.897650000000000000 DataField = 'login' DataSet = frxDBDataset1 DataSetName = 'frxDBDataset1' Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -13 Font.Name = 'Arial' Font.Style = [] Frame.Typ = [] Memo.UTF8W = ( '[frxDBDataset1."login"]') ParentFont = False end object frxDBDataset1dt_cadastro: TfrxMemoView IndexTag = 1 AllowVectorExport = True Left = 582.047620000000000000 Top = 2.559060000000000000 Width = 79.370130000000000000 Height = 18.897650000000000000 DataField = 'dt_cadastro' DataSet = frxDBDataset1 DataSetName = 'frxDBDataset1' Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -13 Font.Name = 'Arial' Font.Style = [] Frame.Typ = [] Memo.UTF8W = ( '[frxDBDataset1."dt_cadastro"]') ParentFont = False end object Shape2: TfrxShapeView AllowVectorExport = True Width = 98.267780000000000000 Height = 26.456710000000000000 Frame.Typ = [] end object Shape4: TfrxShapeView AllowVectorExport = True Left = 336.378170000000000000 Width = 211.653680000000000000 Height = 26.456710000000000000 Frame.Typ = [] end end object PageHeader1: TfrxPageHeader FillType = ftBrush Frame.Typ = [] Height = 30.236240000000000000 Top = 79.370130000000000000 Width = 718.110700000000000000 object Shape8: TfrxShapeView AllowVectorExport = True Left = 98.267780000000000000 Width = 238.110390000000000000 Height = 30.236240000000000000 Frame.Typ = [] end object Shape9: TfrxShapeView AllowVectorExport = True Left = 336.464750000000000000 Width = 211.653680000000000000 Height = 30.236240000000000000 Frame.Typ = [] end object Shape10: TfrxShapeView AllowVectorExport = True Left = 548.118430000000000000 Width = 166.299320000000000000 Height = 30.236240000000000000 Frame.Typ = [] end object Memo2: TfrxMemoView AllowVectorExport = True Left = 3.779530000000000000 Top = 7.559060000000000000 Width = 56.692950000000000000 Height = 18.897650000000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -13 Font.Name = 'Arial' Font.Style = [fsBold] Frame.Typ = [] HAlign = haCenter Memo.UTF8W = ( 'ID') ParentFont = False VAlign = vaCenter end object Memo3: TfrxMemoView AllowVectorExport = True Left = 105.826840000000000000 Top = 7.559060000000000000 Width = 222.992270000000000000 Height = 18.897650000000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -13 Font.Name = 'Arial' Font.Style = [fsBold] Frame.Typ = [] HAlign = haCenter Memo.UTF8W = ( 'NOME') ParentFont = False VAlign = vaCenter end object Memo4: TfrxMemoView AllowVectorExport = True Left = 347.023810000000000000 Top = 7.559060000000000000 Width = 192.756030000000000000 Height = 18.897650000000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -13 Font.Name = 'Arial' Font.Style = [fsBold] Frame.Typ = [] HAlign = haCenter Memo.UTF8W = ( 'LOGIN') ParentFont = False VAlign = vaCenter end object Memo5: TfrxMemoView AllowVectorExport = True Left = 581.677490000000000000 Top = 7.559060000000000000 Width = 120.944960000000000000 Height = 18.897650000000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -13 Font.Name = 'Arial' Font.Style = [fsBold] Frame.Typ = [] HAlign = haCenter Memo.UTF8W = ( 'CADASTRO') ParentFont = False VAlign = vaCenter end object Shape7: TfrxShapeView AllowVectorExport = True Width = 98.267780000000000000 Height = 30.236240000000000000 Frame.Typ = [] end end object Footer1: TfrxFooter FillType = ftBrush Frame.Typ = [] Height = 34.015770000000000000 Top = 219.212740000000000000 Width = 718.110700000000000000 object Memo7: TfrxMemoView AllowVectorExport = True Left = 597.165740000000000000 Top = 3.779530000000000000 Width = 109.606370000000000000 Height = 26.456710000000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -11 Font.Name = 'Arial' Font.Style = [fsItalic] Frame.Typ = [] Memo.UTF8W = ( 'Sistema desenvolvido por Marcus Vinicius da Silva Milagres') ParentFont = False end object SysMemo1: TfrxSysMemoView AllowVectorExport = True Left = 111.929190000000000000 Top = 7.779530000000000000 Width = 94.488250000000000000 Height = 15.118120000000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -11 Font.Name = 'Arial' Font.Style = [] Frame.Typ = [] Memo.UTF8W = ( '[COUNT(MasterData1)]') ParentFont = False end object Memo8: TfrxMemoView AllowVectorExport = True Left = -9.440940000000000000 Top = 7.779530000000000000 Width = 113.385900000000000000 Height = 15.118120000000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -11 Font.Name = 'Arial' Font.Style = [fsBold] Frame.Typ = [] HAlign = haRight Memo.UTF8W = ( 'Total de Usu'#225'rios') ParentFont = False VAlign = vaCenter end end end end object frxPDFExport1: TfrxPDFExport UseFileCache = True ShowProgress = True OverwritePrompt = False DataOnly = False InteractiveFormsFontSubset = 'A-Z,a-z,0-9,#43-#47 ' OpenAfterExport = False PrintOptimized = False Outline = False Background = False HTMLTags = True Quality = 95 Transparency = False Author = 'FastReport' Subject = 'FastReport PDF export' ProtectionFlags = [ePrint, eModify, eCopy, eAnnot] HideToolbar = False HideMenubar = False HideWindowUI = False FitWindow = False CenterWindow = False PrintScaling = False PdfA = False PDFStandard = psNone PDFVersion = pv17 Left = 376 Top = 16 end object frxXLSExport1: TfrxXLSExport UseFileCache = True ShowProgress = True OverwritePrompt = False DataOnly = False ExportEMF = True AsText = False Background = True FastExport = True PageBreaks = True EmptyLines = True SuppressPageHeadersFooters = False Left = 376 Top = 88 end object frxDBDatasetCaixa: TfrxDBDataset UserName = 'frxDBDataset2' CloseDataSource = False FieldAliases.Strings = ( 'id=id' 'numero_doc=numero_doc' 'descricao=descricao' 'valor=valor' 'tipo=tipo' 'dt_cadastro=dt_cadastro') DataSet = DataModule1.cdsCaixa BCDToCurrency = False Left = 184 Top = 152 end object frxReportCaixa: TfrxReport Version = '6.8.11' DotMatrixReport = False IniFile = '\Software\Fast Reports' PreviewOptions.Buttons = [pbPrint, pbLoad, pbSave, pbExport, pbZoom, pbFind, pbOutline, pbPageSetup, pbTools, pbEdit, pbNavigator, pbExportQuick, pbCopy, pbSelection] PreviewOptions.Zoom = 1.000000000000000000 PrintOptions.Printer = 'Default' PrintOptions.PrintOnSheet = 0 ReportOptions.CreateDate = 44293.875271527800000000 ReportOptions.LastChange = 44293.906968472220000000 ScriptLanguage = 'PascalScript' ScriptText.Strings = ( 'begin' '' 'end.') Left = 88 Top = 152 Datasets = < item DataSet = frxDBDatasetCaixa DataSetName = 'frxDBDataset2' end> Variables = <> Style = <> object Data: TfrxDataPage Height = 1000.000000000000000000 Width = 1000.000000000000000000 end object Page1: TfrxReportPage PaperWidth = 210.000000000000000000 PaperHeight = 297.000000000000000000 PaperSize = 9 LeftMargin = 10.000000000000000000 RightMargin = 10.000000000000000000 TopMargin = 10.000000000000000000 BottomMargin = 10.000000000000000000 Frame.Typ = [] MirrorMode = [] object ReportTitle1: TfrxReportTitle FillType = ftBrush Frame.Typ = [] Height = 37.795300000000000000 Top = 18.897650000000000000 Width = 718.110700000000000000 object Date: TfrxMemoView IndexTag = 1 AllowVectorExport = True Left = 597.165740000000000000 Top = 3.779530000000000000 Width = 56.692950000000000000 Height = 11.338590000000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -9 Font.Name = 'Arial' Font.Style = [] Frame.Typ = [] HAlign = haCenter Memo.UTF8W = ( '[Date]') ParentFont = False VAlign = vaCenter end object Time: TfrxMemoView IndexTag = 1 AllowVectorExport = True Left = 597.165740000000000000 Top = 19.677180000000000000 Width = 56.692950000000000000 Height = 11.338590000000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -9 Font.Name = 'Arial' Font.Style = [] Frame.Typ = [] HAlign = haCenter Memo.UTF8W = ( '[Time]') ParentFont = False VAlign = vaCenter end object Page: TfrxMemoView IndexTag = 1 AllowVectorExport = True Left = 668.976810000000000000 Top = 3.779530000000000000 Width = 41.574830000000000000 Height = 18.897650000000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -9 Font.Name = 'Arial' Font.Style = [] Frame.Typ = [] Memo.UTF8W = ( '[Page#]') ParentFont = False end object Memo1: TfrxMemoView AllowVectorExport = True Left = 11.338590000000000000 Top = 3.779530000000000000 Width = 555.590910000000000000 Height = 30.236240000000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -19 Font.Name = 'Arial' Font.Style = [fsBold] Frame.Typ = [] HAlign = haCenter Memo.UTF8W = ( 'Relat'#243'rio de Lan'#231'amentos no Caixa') ParentFont = False VAlign = vaCenter end object Line1: TfrxLineView AllowVectorExport = True Left = 4.779530000000000000 Top = 34.795300000000000000 Width = 706.772110000000000000 Color = clBlack Frame.Typ = [ftTop] end end object PageHeader1: TfrxPageHeader FillType = ftBrush Frame.Typ = [] Height = 30.236240000000000000 Top = 79.370130000000000000 Width = 718.110700000000000000 object Memo2: TfrxMemoView AllowVectorExport = True Left = 3.779530000000000000 Top = 3.779530000000000000 Width = 105.826840000000000000 Height = 18.897650000000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -13 Font.Name = 'Arial' Font.Style = [fsBold] Frame.Typ = [] Memo.UTF8W = ( 'Nr. Documento') ParentFont = False VAlign = vaCenter end object Memo3: TfrxMemoView AllowVectorExport = True Left = 130.063080000000000000 Top = 3.779530000000000000 Width = 222.992270000000000000 Height = 18.897650000000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -13 Font.Name = 'Arial' Font.Style = [fsBold] Frame.Typ = [] Memo.UTF8W = ( 'Descri'#231#227'o') ParentFont = False VAlign = vaCenter end object Memo5: TfrxMemoView AllowVectorExport = True Left = 498.897960000000000000 Top = 3.779530000000000000 Width = 56.692950000000000000 Height = 18.897650000000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -13 Font.Name = 'Arial' Font.Style = [fsBold] Frame.Typ = [] Memo.UTF8W = ( 'Tipo') ParentFont = False VAlign = vaCenter end object Memo4: TfrxMemoView AllowVectorExport = True Left = 374.055350000000000000 Top = 3.779530000000000000 Width = 94.488250000000000000 Height = 18.897650000000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -13 Font.Name = 'Arial' Font.Style = [fsBold] Frame.Typ = [] Memo.UTF8W = ( 'Valor') ParentFont = False VAlign = vaCenter end object Memo6: TfrxMemoView AllowVectorExport = True Left = 577.606680000000000000 Top = 3.779530000000000000 Width = 113.385900000000000000 Height = 18.897650000000000000 Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -13 Font.Name = 'Arial' Font.Style = [fsBold] Frame.Typ = [] Memo.UTF8W = ( 'Data do Cadastro') ParentFont = False VAlign = vaCenter end object Line2: TfrxLineView AllowVectorExport = True Left = 2.779530000000000000 Top = 28.236240000000000000 Width = 706.772110000000000000 Color = clBlack Frame.Typ = [ftTop] Frame.Width = 0.100000000000000000 end end object MasterData1: TfrxMasterData FillType = ftBrush Frame.Typ = [] Height = 41.574830000000000000 Top = 170.078850000000000000 Width = 718.110700000000000000 DataSet = frxDBDatasetCaixa DataSetName = 'frxDBDataset2' RowCount = 0 object frxDBDataset2numero_doc: TfrxMemoView IndexTag = 1 AllowVectorExport = True Left = 7.559060000000000000 Top = 7.559060000000000000 Width = 102.047310000000000000 Height = 18.897650000000000000 DataField = 'numero_doc' DataSet = frxDBDatasetCaixa DataSetName = 'frxDBDataset2' Frame.Typ = [] Memo.UTF8W = ( '[frxDBDataset2."numero_doc"]') end object frxDBDataset2descricao: TfrxMemoView IndexTag = 1 AllowVectorExport = True Left = 128.504020000000000000 Top = 7.559060000000000000 Width = 222.992270000000000000 Height = 18.897650000000000000 DataField = 'descricao' DataSet = frxDBDatasetCaixa DataSetName = 'frxDBDataset2' Frame.Typ = [] Memo.UTF8W = ( '[frxDBDataset2."descricao"]') end object frxDBDataset2valor: TfrxMemoView IndexTag = 1 AllowVectorExport = True Left = 374.173470000000000000 Top = 7.559060000000000000 Width = 98.267780000000000000 Height = 18.897650000000000000 DataField = 'valor' DataSet = frxDBDatasetCaixa DataSetName = 'frxDBDataset2' Frame.Typ = [] Memo.UTF8W = ( '[frxDBDataset2."valor"]') end object frxDBDataset2tipo: TfrxMemoView IndexTag = 1 AllowVectorExport = True Left = 506.457020000000000000 Top = 7.559060000000000000 Width = 26.456710000000000000 Height = 18.897650000000000000 DataField = 'tipo' DataSet = frxDBDatasetCaixa DataSetName = 'frxDBDataset2' Frame.Typ = [] Memo.UTF8W = ( '[frxDBDataset2."tipo"]') end object frxDBDataset2dt_cadastro: TfrxMemoView IndexTag = 1 AllowVectorExport = True Left = 585.827150000000000000 Top = 7.559060000000000000 Width = 79.370130000000000000 Height = 18.897650000000000000 DataField = 'dt_cadastro' DataSet = frxDBDatasetCaixa DataSetName = 'frxDBDataset2' Frame.Typ = [] Memo.UTF8W = ( '[frxDBDataset2."dt_cadastro"]') end object Line3: TfrxLineView AllowVectorExport = True Left = 7.559060000000000000 Top = 30.236240000000000000 Width = 706.772110000000000000 Color = clBlack Frame.Typ = [ftTop] Frame.Width = 0.100000000000000000 end end end end end
31.171605
170
0.566478
fc579ee3ace33bc8ebd859c3d1e594609d624f1a
7,041
pas
Pascal
Production7/CashDesks/EditCashDesk.pas
kadavris/ok-sklad
f9cd84be7bf984104d9af93d83c0719f2d5668c5
[ "MIT" ]
1
2016-04-04T18:11:56.000Z
2016-04-04T18:11:56.000Z
Production7/CashDesks/EditCashDesk.pas
kadavris/ok-sklad
f9cd84be7bf984104d9af93d83c0719f2d5668c5
[ "MIT" ]
null
null
null
Production7/CashDesks/EditCashDesk.pas
kadavris/ok-sklad
f9cd84be7bf984104d9af93d83c0719f2d5668c5
[ "MIT" ]
5
2016-02-15T02:08:05.000Z
2021-04-05T08:57:58.000Z
{$I ok_sklad.inc} unit EditCashDesk; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, dxCntner, dxEditor, StdCtrls, ActnList, ssBaseTypes, ssFormStorage, cxCheckBox, cxControls, cxContainer, cxEdit, cxTextEdit, cxLookAndFeelPainters, cxButtons, ssBaseDlg, ssBevel, ImgList, ssSpeedButton, ssPanel, ssGradientPanel, xButton; type TfrmEditCashDesk = class(TBaseDlg) bvlMain: TssBevel; edName: TcxTextEdit; lName: TLabel; bvlSep: TssBevel; chbDefault: TcxCheckBox; procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure ActionListUpdate(Action: TBasicAction; var Handled: Boolean); procedure DataModified(Sender: TObject); protected procedure setid(const Value: integer); override; procedure SetParentName(const Value: string); override; public ParentHandle: HWND; procedure SetCaptions; override; { Public declarations } end; var frmEditCashDesk: TfrmEditCashDesk; implementation uses ssBaseConst, prConst, DbClient, DB, ClientData, prFun, ssCallbackConst, ssClientDataSet, xLngManager, prTypes, Udebug; var DEBUG_unit_ID: Integer; Debugging: Boolean; DEBUG_group_ID: String = ''; {$R *.dfm} //============================================================================================== procedure TfrmEditCashDesk.setid(const Value: integer); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelLow, DEBUG_unit_ID, 'TfrmEditCashDesk.setid') else _udebug := nil;{$ENDIF} if not IsPattern then FID := Value; with newDataSet do try if Value <> 0 then begin if not IsPattern then Self.Caption := dmData.Lng.GetRS(ParentNameEx, 'TitleEdit') else Self.Caption := dmData.Lng.GetRS(ParentNameEx, 'TitleAdd'); ProviderName := 'pCashDesks_Get'; FetchParams; Params.ParamByName('CashID').AsInteger := Value; Open; if not IsEmpty then begin edName.Text := FieldByName('Name').asstring; chbDefault.Checked := FieldByName('def').AsInteger=1; end; Close; if not IsPattern then begin chbDefault.Enabled := not chbDefault.Checked; btnApply.Enabled := False; end; end else Self.Caption := dmData.Lng.GetRS(ParentNameEx, 'TitleAdd'); finally Free; end; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmEditCashDesk.FormCloseQuery(Sender: TObject; var CanClose: Boolean); var NewRecord: boolean; {$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmEditCashDesk.FormCloseQuery') else _udebug := nil;{$ENDIF} if ModalResult in [mrOK, mrYes] then begin CanClose := False; with newDataSet do try TrStart; try NewRecord := (ID = 0); if NewRecord then FID := GetMaxID(dmData.SConnection, 'cashdesks', 'cashid'); if chbDefault.Checked then begin ProviderName := 'pCashDesks_SetDef'; Execute; chbDefault.Enabled := False; end; if NewRecord then ProviderName := 'pCashDesks_Ins' else ProviderName := 'pCashDesks_Upd'; FetchParams; Params.ParamByName('cashid').AsInteger := FID; Params.ParamByName('name').AsString := edName.Text; Params.ParamByName('def').AsInteger := Integer(chbDefault.Checked); Execute; TrCommit; SendMessage(MainHandle, WM_REFRESH, ID, 0); frmMainForm.ExecRefresh('TfmFinance', FID, Integer(rtCashDesks)); //if RefreshAllClients // then dmData.SConnection.AppServer.q_Add(CA_REFRESH, CA_ACCOUNTTYPE); if ModalResult = mrYes then begin if NewRecord then begin if not IsPattern then edName.Text := EmptyStr; chbDefault.Enabled := True; chbDefault.Checked := False; edName.SetFocus; FID := 0; end end else CanClose := True; FModified := False; finally Free; end; except on e:exception do begin TrRollback; MessageDlg(e.Message, mtError, [mbOk], 0); end; end; end; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmEditCashDesk.ActionListUpdate(Action: TBasicAction; var Handled: Boolean); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmEditCashDesk.ActionListUpdate') else _udebug := nil;{$ENDIF} aOk.Enabled := (Trim(edName.Text) <> EmptyStr); aApply.Enabled := aOk.Enabled and FModified; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmEditCashDesk.DataModified(Sender: TObject); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmEditCashDesk.DataModified') else _udebug := nil;{$ENDIF} FModified := True; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmEditCashDesk.SetCaptions; {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmEditCashDesk.SetCaptions') else _udebug := nil;{$ENDIF} inherited; with dmData.Lng do begin lName.Caption := GetRS(ParentNameEx, 'Name') + ':'; chbDefault.Properties.Caption := GetRS('Common', 'Default'); end; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmEditCashDesk.SetParentName(const Value: string); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmEditCashDesk.SetParentName') else _udebug := nil;{$ENDIF} FParentName := Value; SetCaptions; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; initialization {$IFDEF UDEBUG}Debugging := False; DEBUG_unit_ID := debugRegisterUnit('EditCashDesk', @Debugging, DEBUG_group_ID);{$ENDIF} finalization //{$IFDEF UDEBUG}debugUnregisterUnit(DEBUG_unit_ID);{$ENDIF} end.
32.004545
157
0.612271
47e5457ef2a6ac0930796d8cc8adc2c4a1764e75
2,666
pas
Pascal
streams/0005.pas
nickelsworth/swag
7c21c0da2291fc249b9dc5cfe121a7672a4ffc08
[ "BSD-2-Clause" ]
11
2015-12-12T05:13:15.000Z
2020-10-14T13:32:08.000Z
streams/0005.pas
nickelsworth/swag
7c21c0da2291fc249b9dc5cfe121a7672a4ffc08
[ "BSD-2-Clause" ]
null
null
null
streams/0005.pas
nickelsworth/swag
7c21c0da2291fc249b9dc5cfe121a7672a4ffc08
[ "BSD-2-Clause" ]
8
2017-05-05T05:24:01.000Z
2021-07-03T20:30:09.000Z
{ I conceived and made something I find highly useful, hope you do to.. If you use this in combination with DJ's Streams unit, you can store text files and that kind of things in your EXE.. On its own, it's great for the usual Config record. } Unit ExeS; INTERFACE Uses Objects; Type PExeStream = ^TExeStream; TExeStream = Object(TBufStream) Constructor Init(FileName: FNameStr; Mode, Size: Word); Procedure Seek(Pos: Longint); Virtual; Function GetPos: Longint; Virtual; Function GetSize: Longint; Virtual; Private AddOffset: LongInt; End; Implementation Constructor TExeStream.Init(FileName: FNameStr; Mode, Size: Word); Type ExeHdrType = Record Signature: Word; Rest, Blocks: Word; End; Var ExeFil: File Of ExeHdrType; ExeHdr: ExeHdrType; ExeLen: LongInt; fm: Integer; Begin fm := FileMode; FileMode := 64; System.Assign(ExeFil, FileName); System.Reset(ExeFil); System.Read(ExeFil, ExeHdr); System.Close(ExeFil); FileMode := fm; Inherited Init(FileName, Mode, Size); AddOffset := (ExeHdr.Blocks - 1) * LongInt(512) + ExeHdr.Rest; Seek(0); End; Procedure TExeStream.Seek(Pos: Longint); Begin Inherited Seek(Pos + AddOffset); End; Function TExeStream.GetPos: Longint; Var p: LongInt; Begin p := Inherited GetPos; GetPos := p - AddOffset; End; Function TExeStream.GetSize: Longint; Var s: LongInt; Begin s := Inherited GetSize; GetSize := s - AddOffset; End; End. { ------------------- DEMO PROGRAM -----------------------} Below is a simple example program to show its potential use: Program TestExeS; Uses ExeS; Type TConfig = Record Value1: String; Value2: Word; End; Var InS: PStream; Config: TConfig; Begin InS := New(PExeStream, Init(ParamStr(0), stOpen, 2048)); If InS = nil Then Begin Writeln('Something is really wrong!'); Halt; End Else If InS^.Status <> stOk Then Begin Writeln('Something is really wrong!'); Halt; End; If InS^.GetSize > 0 Then Begin InS^.Read(Config, SizeOf(TConfig)); InS^.Seek(0); Writeln('Old config:'); Writeln('Value 1: ', Config.Value1); Writeln('Value 2: ', Config.Value2); End Else Writeln('No config info found.'); Writeln; Write('Enter new value 1: '); Readln(Config.Value1); Write('Enter new value 2: '); Readln(Config.Value2); InS^.Write(Config, SizeOf(TConfig)); Dispose(InS, Done); End. 
20.351145
86
0.607652
475b6bd9fa6daa18fa77b164083a0d4f2a755a0a
1,522
pas
Pascal
Model/Empresa/Metodos/Buscar/MFichas.Model.Empresa.Metodos.Buscar.Model.pas
JoseLSB/rodeo-sales-project
28699e98d52b83cc8d97dcbe8a66f7358113b17f
[ "MIT" ]
null
null
null
Model/Empresa/Metodos/Buscar/MFichas.Model.Empresa.Metodos.Buscar.Model.pas
JoseLSB/rodeo-sales-project
28699e98d52b83cc8d97dcbe8a66f7358113b17f
[ "MIT" ]
null
null
null
Model/Empresa/Metodos/Buscar/MFichas.Model.Empresa.Metodos.Buscar.Model.pas
JoseLSB/rodeo-sales-project
28699e98d52b83cc8d97dcbe8a66f7358113b17f
[ "MIT" ]
null
null
null
unit MFichas.Model.Empresa.Metodos.Buscar.Model; interface uses System.SysUtils, System.Generics.Collections, MFichas.Model.Entidade.EMPRESA, MFichas.Model.Empresa.Interfaces; type TModelEmpresaMetodosBuscarModel = class(TInterfacedObject, iModelEmpresaMetodosBuscarModel) private [weak] FParent: iModelEmpresa; FListaEmpresa: TObjectList<TEMPRESA>; constructor Create(AParent: iModelEmpresa); public destructor Destroy; override; class function New(AParent: iModelEmpresa): iModelEmpresaMetodosBuscarModel; function NomeDaEmpresa: String; function &End : iModelEmpresaMetodos; end; implementation { TModelEmpresaMetodosBuscarModel } function TModelEmpresaMetodosBuscarModel.&End: iModelEmpresaMetodos; begin Result := FParent.Metodos; end; constructor TModelEmpresaMetodosBuscarModel.Create(AParent: iModelEmpresa); begin FParent := AParent; end; destructor TModelEmpresaMetodosBuscarModel.Destroy; begin {$IFDEF MSWINDOWS} if Assigned(FListaEmpresa) then FreeAndNil(FListaEmpresa); {$ELSE} if Assigned(FListaEmpresa) then begin FListaEmpresa.Free; FListaEmpresa.DisposeOf; end; {$ENDIF} inherited; end; class function TModelEmpresaMetodosBuscarModel.New(AParent: iModelEmpresa): iModelEmpresaMetodosBuscarModel; begin Result := Self.Create(AParent); end; function TModelEmpresaMetodosBuscarModel.NomeDaEmpresa: String; begin FListaEmpresa := FParent.DAO.Find; Result := FListaEmpresa.Items[0].DESCRICAO; end; end.
22.716418
108
0.78318
fc5f773ec25e2eff02c13565fd3919d38d1b151d
222
pas
Pascal
CAT/tests/08. types/strings/unicode/strings_1.pas
SkliarOleksandr/NextPascal
4dc26abba6613f64c0e6b5864b3348711eb9617a
[ "Apache-2.0" ]
19
2018-10-22T23:45:31.000Z
2021-05-16T00:06:49.000Z
CAT/tests/08. types/strings/unicode/strings_1.pas
SkliarOleksandr/NextPascal
4dc26abba6613f64c0e6b5864b3348711eb9617a
[ "Apache-2.0" ]
1
2019-06-01T06:17:08.000Z
2019-12-28T10:27:42.000Z
CAT/tests/08. types/strings/unicode/strings_1.pas
SkliarOleksandr/NextPascal
4dc26abba6613f64c0e6b5864b3348711eb9617a
[ "Apache-2.0" ]
6
2018-08-30T05:16:21.000Z
2021-05-12T20:25:43.000Z
unit strings_1; interface implementation var S1, S2, S3: string; procedure Test; begin S1 := 'abcd'; S2 := S1; S3 := 'X'; end; initialization Test(); finalization Assert(S1 = S2); Assert(S3 = 'X'); end.
9.652174
21
0.617117
c361794139b0af69ecf7391a638adc877f8721b6
1,377
dpr
Pascal
branch_portal/branch_portal.dpr
kim-g/Player-universal
e96daa5f6f1dc7b7cd694a47c5907eaf2994cb89
[ "BSD-2-Clause" ]
null
null
null
branch_portal/branch_portal.dpr
kim-g/Player-universal
e96daa5f6f1dc7b7cd694a47c5907eaf2994cb89
[ "BSD-2-Clause" ]
null
null
null
branch_portal/branch_portal.dpr
kim-g/Player-universal
e96daa5f6f1dc7b7cd694a47c5907eaf2994cb89
[ "BSD-2-Clause" ]
null
null
null
library branch_portal; uses System.SysUtils, System.Classes, VCL.Forms, VCL.Dialogs, WinAPI.Windows, INIFiles; const DEBUG = false; var ApplicationExeName:string=''; {$R *.res} procedure ShutDownPlayer(Width, Height: Integer); stdcall; var dm : TDEVMODE; begin ZeroMemory(@dm, sizeof(TDEVMODE)); dm.dmSize := sizeof(TDEVMODE); dm.dmPelsWidth := Width; dm.dmPelsHeight := Height; dm.dmFields := DM_PELSWIDTH or DM_PELSHEIGHT; ChangeDisplaySettings(dm, 0); Application.Terminate; end; function ConfigAddress:string; stdcall; begin if Debug then ShowMessage('Called ConfigAddress()'); if ApplicationExeName = '' then ApplicationExeName := ExtractFilePath(Application.ExeName); Result := ApplicationExeName+'config.ini'; end; function MusicAddress(FP:string):string; stdcall; begin if Debug then ShowMessage('Called MusicAddress(FP:string)'); if ApplicationExeName = '' then ApplicationExeName := ExtractFilePath(Application.ExeName); Result := ApplicationExeName + FP + '\'; end; function ListAddress(INI:TINIFile):string; stdcall; begin if Debug then ShowMessage('Called ListAddress(INI:TINIFile)'); if ApplicationExeName = '' then ApplicationExeName := ExtractFilePath(Application.ExeName); Result := ApplicationExeName + 'ListDir\'; end; exports ShutDownPlayer, ConfigAddress, MusicAddress, ListAddress; begin end.
22.95
93
0.750182
f1e599b9937a4889c16c14441f4c5854aab9ca12
2,187
pas
Pascal
set_ports.pas
DarkPatrick/rs_to_arinc_new
e1f8723e4df23517e492d77029a40e5b05b615f4
[ "MIT" ]
null
null
null
set_ports.pas
DarkPatrick/rs_to_arinc_new
e1f8723e4df23517e492d77029a40e5b05b615f4
[ "MIT" ]
null
null
null
set_ports.pas
DarkPatrick/rs_to_arinc_new
e1f8723e4df23517e492d77029a40e5b05b615f4
[ "MIT" ]
null
null
null
unit set_ports; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TForm4 = class(TForm) port_num1: TComboBox; port_num2: TComboBox; set_control: TCheckBox; Button1: TButton; Button2: TButton; procedure set_controlClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button1Click(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure port_num1Click(Sender: TObject); procedure port_num2Change(Sender: TObject); private { Private declarations } public { Public declarations } end; var form4: TForm4; setup_this: boolean; ready_to_launch: boolean; cancel_main, cancel_extra, cancel_extra2: boolean; implementation {$R *.dfm} procedure closeAll(); begin if (form4.port_num1.itemIndex > -1) then begin cancel_main := FALSE; end else begin cancel_main := TRUE; end; setup_this := FALSE; end; procedure TForm4.Button1Click(Sender: TObject); begin ready_to_launch := TRUE; form4.close(); end; procedure TForm4.Button2Click(Sender: TObject); begin form4.close(); end; procedure TForm4.FormClose(Sender: TObject; var Action: TCloseAction); begin closeAll(); end; procedure TForm4.FormCreate(Sender: TObject); begin setup_this := FALSE; ready_to_launch := FALSE; cancel_main := TRUE; cancel_extra := TRUE; cancel_extra2 := TRUE; end; procedure TForm4.port_num1Click(Sender: TObject); begin cancel_main := FALSE; end; procedure TForm4.port_num2Change(Sender: TObject); begin cancel_extra2 := FALSE; end; procedure TForm4.set_controlClick(Sender: TObject); begin if (set_control.checked = TRUE) then begin port_num2.visible := TRUE; cancel_extra := FALSE; end else begin port_num2.visible := FALSE; cancel_extra := TRUE; cancel_extra2 := TRUE; end; end; end.
21.028846
71
0.670782
fcf1384e5b7572913747e69e326e022a3a2ea075
5,534
pas
Pascal
MicroGest/MicroGest8/Persistence.FireDAC.SQLite.pas
mauriziodm/DelphiDay_Padova_2018
f200f06d9ec1eb5f0a28c7eb83358031c3576b5a
[ "MIT" ]
2
2019-04-19T12:17:01.000Z
2019-11-15T23:43:46.000Z
MicroGest/MicroGest8/Persistence.FireDAC.SQLite.pas
mauriziodm/DelphiDay_Padova_2018
f200f06d9ec1eb5f0a28c7eb83358031c3576b5a
[ "MIT" ]
null
null
null
MicroGest/MicroGest8/Persistence.FireDAC.SQLite.pas
mauriziodm/DelphiDay_Padova_2018
f200f06d9ec1eb5f0a28c7eb83358031c3576b5a
[ "MIT" ]
2
2019-04-19T12:19:42.000Z
2019-11-15T23:43:47.000Z
unit Persistence.FireDAC.SQLite; interface uses Persistence.Interfaces, FireDAC.Comp.Client, FireDAC.Stan.Param, Data.DB, FireDAC.Stan.Def, FireDAC.Phys.SQLite, FireDAC.Stan.ExprFuncs, FireDAC.Stan.Intf, FireDAC.Phys, FireDAC.DApt, FireDAC.UI.Intf, FireDAC.Comp.UI, FireDAC.Stan.Async, Demo.Core.Rtti, Demo.Core.ServiceLocator, {$IFDEF mgFMX} FireDAC.FMXUI.Wait; {$ELSE} FireDAC.VCLUI.Wait; {$ENDIF} type [Alias('sqlite')] TPersistanceFireDacSQLiteFactory = class(TInterfacedObject, IPersistanceLayerFactory) private class var FInstance: IPersistanceLayerFactory; FConnection: TFDConnection; protected function GetQuery: TFDQuery; function GetNextDocID: Integer; virtual; public class function GetInstance: IPersistanceLayerFactory; constructor Create; Destructor Destroy; override; function GetListaDocumentiDS: TDataSet; function GetListaArticoliDS: TDataSet; function GetDocumentoDS(const ATipoDoc: String; const AID:Integer=0): TDataSet; function GetRigheDocumentoDS(const AID:Integer=0): TDataSet; procedure ApplyUpdates(const ADataSet:TDataSet); procedure CancelUpdates(const ADataSet:TDataSet); procedure CommitUpdates(const ADataSet:TDataSet); function CanSave(const ADataSet:TDataSet): Boolean; procedure StartTransaction; procedure CommitTransaction; procedure RollbackTransaction; end; implementation uses System.IOUtils, System.SysUtils; { TPersistanceFireDacSQLiteFactory } procedure TPersistanceFireDacSQLiteFactory.ApplyUpdates(const ADataSet: TDataSet); begin if CanSave(ADataSet) then (ADataSet as TFDQuery).ApplyUpdates; end; procedure TPersistanceFireDacSQLiteFactory.CancelUpdates(const ADataSet: TDataSet); begin if CanSave(ADataSet) then (ADataSet as TFDQuery).CancelUpdates; end; function TPersistanceFireDacSQLiteFactory.CanSave(const ADataSet: TDataSet): Boolean; begin Result := (ADataSet as TFDQuery).UpdatesPending or (ADataSet.State in [dsEdit, dsInsert]); end; procedure TPersistanceFireDacSQLiteFactory.CommitTransaction; begin FConnection.Commit; end; procedure TPersistanceFireDacSQLiteFactory.CommitUpdates(const ADataSet: TDataSet); begin if CanSave(ADataSet) then (ADataSet as TFDQuery).CommitUpdates; end; constructor TPersistanceFireDacSQLiteFactory.Create; begin FConnection := TFDConnection.Create(nil); FConnection.Params.DriverID := 'SQLite'; FConnection.Params.Database := TPath.Combine(TPath.GetDocumentsPath, 'MICROGEST.db'); FConnection.Open; end; destructor TPersistanceFireDacSQLiteFactory.Destroy; begin FConnection.Free; inherited; end; function TPersistanceFireDacSQLiteFactory.GetDocumentoDS(const ATipoDoc: String; const AID: Integer): TDataSet; var LQuery: TFDQuery; begin LQuery := GetQuery; LQuery.SQL.Text := 'SELECT * FROM DOCUMENTI WHERE ID = :P_ID'; LQuery.ParamByName('P_ID').AsInteger := AID; LQuery.Open; (LQuery.FieldByName('TOTALEIMPONIBILE') as TFloatField).Currency := True; (LQuery.FieldByName('TOTALEIVA') as TFloatField).Currency := True; (LQuery.FieldByName('TOTALEDOCUMENTO') as TFloatField).Currency := True; if LQuery.Eof and (AID = 0) then begin LQuery.Append; LQuery.FieldByName('ID').Value := GetNextDocID; LQuery.FieldByName('TIPO').Value := ATipoDoc; LQuery.FieldByName('DATA').Value := Date; end; Result := LQuery; end; class function TPersistanceFireDacSQLiteFactory.GetInstance: IPersistanceLayerFactory; begin // Singleton if not Assigned(FInstance) then FInstance := Self.Create; Result := FInstance; end; function TPersistanceFireDacSQLiteFactory.GetListaArticoliDS: TDataSet; var LQuery: TFDQuery; begin LQuery := GetQuery; LQuery.SQL.Text := 'SELECT * FROM ARTICOLI'; LQuery.Open; Result := LQuery; end; function TPersistanceFireDacSQLiteFactory.GetListaDocumentiDS: TDataSet; var LQuery: TFDQuery; begin LQuery := GetQuery; LQuery.SQL.Text := 'SELECT TIPO, ID, DATA, CLIENTE, TOTALEDOCUMENTO FROM DOCUMENTI'; LQuery.Open; (LQuery.FieldByName('TOTALEDOCUMENTO') as TFloatField).Currency := True; Result := LQuery; end; function TPersistanceFireDacSQLiteFactory.GetNextDocID: Integer; var LQuery: TFDQuery; begin LQuery := TFDQuery.Create(nil); try LQuery := GetQuery; LQuery.SQL.Text := 'SELECT MAX(ID) FROM DOCUMENTI'; LQuery.Open; Result := LQuery.Fields[0].AsInteger + 1; finally LQuery.Free; end; end; function TPersistanceFireDacSQLiteFactory.GetQuery: TFDQuery; begin Result := TFDQuery.Create(nil); Result.CachedUpdates := True; Result.Connection := FConnection; end; function TPersistanceFireDacSQLiteFactory.GetRigheDocumentoDS(const AID: Integer): TDataSet; var LQuery: TFDQuery; begin LQuery := GetQuery; LQuery.SQL.Text := 'SELECT * FROM RIGHEDOCUMENTI WHERE ID_DOC = :P_ID_DOC'; LQuery.ParamByName('P_ID_DOC').AsInteger := AID; LQuery.Open; (LQuery.FieldByName('PREZZO') as TFloatField).Currency := True; (LQuery.FieldByName('IMPORTO') as TFloatField).Currency := True; Result := LQuery; end; procedure TPersistanceFireDacSQLiteFactory.RollbackTransaction; begin FConnection.Rollback; end; procedure TPersistanceFireDacSQLiteFactory.StartTransaction; begin FConnection.StartTransaction; end; initialization ServiceLocator.RegisterClass(TPersistanceFireDacSQLiteFactory, function ():TObject begin Result := TPersistanceFireDacSQLiteFactory.GetInstance as TPersistanceFireDacSQLiteFactory; end ); end.
25.739535
111
0.765992
fc72f9b7631973bb682e9dd2ce597c94f71305b3
5,495
pas
Pascal
Chapter12/04_ParksLinuxDaemon/udmTCPParksServer.pas
atkins126/Fearless-Cross-Platform-Development-with-Delphi
1fc47e085c82bfa51f0bf2792f22bedc18a72756
[ "MIT" ]
25
2020-06-19T10:50:25.000Z
2022-03-16T12:46:25.000Z
Chapter12/04_ParksLinuxDaemon/udmTCPParksServer.pas
atkins126/Fearless-Cross-Platform-Development-with-Delphi
1fc47e085c82bfa51f0bf2792f22bedc18a72756
[ "MIT" ]
null
null
null
Chapter12/04_ParksLinuxDaemon/udmTCPParksServer.pas
atkins126/Fearless-Cross-Platform-Development-with-Delphi
1fc47e085c82bfa51f0bf2792f22bedc18a72756
[ "MIT" ]
7
2020-08-27T02:55:57.000Z
2022-03-02T21:25:21.000Z
unit udmTCPParksServer; interface uses System.SysUtils, System.Classes, IdContext, IdBaseComponent, IdComponent, IdCustomTCPServer, IdTCPServer; type TdmTCPParksServer = class(TDataModule) IdTCPMyParksServer: TIdTCPServer; procedure IdTCPMyParksServerConnect(AContext: TIdContext); procedure IdTCPMyParksServerExecute(AContext: TIdContext); procedure IdTCPMyParksServerException(AContext: TIdContext; AException: Exception); procedure IdTCPMyParksServerDisconnect(AContext: TIdContext); private FOnConnect: TNotifyEvent; FOnDisconnect: TNotifyEvent; FOnException: TGetStrProc; FOnExecute: TGetStrProc; function IsRunning: Boolean; protected procedure DoOnConnect; procedure DoOnDisconnect; procedure DoOnException(const ExceptionMsg: string); procedure DoOnExecute(const AMessage: string); public procedure Start; procedure Stop; property Running: Boolean read IsRunning; property OnConnect: TNotifyEvent read FOnConnect write FOnConnect; property OnDisconnect: TNotifyEvent read FOnDisconnect write FOnDisconnect; property OnException: TGetStrProc read FOnException write FOnException; property OnExecute: TGetStrProc read FOnExecute write FOnExecute; end; var dmTCPParksServer: TdmTCPParksServer; implementation {%CLASSGROUP 'System.Classes.TPersistent'} {$R *.dfm} uses System.StrUtils, IdIOHandlerSocket, {$IFDEF LINUX} Posix.Syslog, {$ELSE} uMyParksLogging, {$ENDIF} udmParksDB; {$IFNDEF LINUX} const LOG_TAG = 'tcp'; {$ENDIF} procedure TdmTCPParksServer.DoOnConnect; begin {$IFDEF LINUX} syslog(LOG_DEBUG, 'OnConnect'); {$ELSE} Log.Debug('OnConnect', LOG_TAG); {$ENDIF} if Assigned(FOnConnect) then FOnConnect(self); end; procedure TdmTCPParksServer.DoOnDisconnect; begin {$IFDEF LINUX} syslog(LOG_DEBUG, 'OnDisconnect'); {$ELSE} Log.Debug('OnDisconnect', LOG_TAG); {$ENDIF} if Assigned(FOnDisconnect) then FOnDisconnect(self); end; procedure TdmTCPParksServer.DoOnException(const ExceptionMsg: string); begin {$IFDEF LINUX} syslog(LOG_ERR, 'OnException: ' + ExceptionMsg); {$ELSE} Log.Error('OnException: ' + ExceptionMsg, LOG_TAG); {$ENDIF} if Assigned(FOnException) then FOnExecute(ExceptionMsg); end; procedure TdmTCPParksServer.DoOnExecute(const AMessage: string); begin {$IFDEF LINUX} syslog(LOG_DEBUG, 'OnExecute'); {$ELSE} Log.Debug('OnExecute', LOG_TAG); {$ENDIF} if Assigned(FOnExecute) then FOnExecute('Response: ' + AMessage); end; procedure TdmTCPParksServer.IdTCPMyParksServerConnect(AContext: TIdContext); begin DoOnConnect; end; procedure TdmTCPParksServer.IdTCPMyParksServerDisconnect(AContext: TIdContext); begin DoOnDisconnect; end; procedure TdmTCPParksServer.IdTCPMyParksServerException(AContext: TIdContext; AException: Exception); begin DoOnException(AException.Message); end; procedure TdmTCPParksServer.IdTCPMyParksServerExecute(AContext: TIdContext); var ValidRequest: Boolean; Requests: TStringList; ReqLong, ReqLat: Double; ResponseStr: string; begin {$IFDEF LINUX} syslog(LOG_INFO, 'Request received'); {$ELSE} Log.Info('Received Request', LOG_TAG); {$ENDIF} ValidRequest := False; ResponseStr := EmptyStr; Requests := TStringList.Create; try Requests.CommaText := Trim(AContext.Connection.Socket.ReadLn); if Requests.Count = 2 then begin if TryStrToFloat(Requests.Values['longitude'], ReqLong) and TryStrToFloat(Requests.Values['latitude'], ReqLat) then begin {$IFDEF LINUX} syslog(LOG_DEBUG, Format(' Request parameters: longitude=%f, latitude=%f', [ReqLong, ReqLat])); {$ELSE} Log.Debug(Format(' Request parameters: longitude=%f, latitude=%f', [ReqLong, ReqLat]), LOG_TAG); {$ENDIF} var ParkInfo := dmParksDB.LookupParkByLocation(ReqLong, ReqLat); if ParkInfo.ParkName.Length > 0 then begin ResponseStr := ParkInfo.ParkName; {$IFDEF LINUX} syslog(LOG_INFO, ' Returning park name: ' + ResponseStr); {$ELSE} Log.Debug(' Returning park name: ' + ResponseStr, LOG_TAG); {$ENDIF} ValidRequest := True; end else begin ResponseStr := '<Unknown Park>'; {$IFDEF LINUX} syslog(LOG_WARNING, ' Returning: ' + ResponseStr); {$ELSE} Log.Warn(' Returning: ' + ResponseStr, LOG_TAG); {$ENDIF} end; end; end; finally Requests.Free; end; if (not ValidRequest) and (ResponseStr.Length = 0) then begin ResponseStr := 'ERROR: Invalid request'; {$IFDEF LINUX} syslog(LOG_ERR, ' Returning: ' + ResponseStr); {$ELSE} Log.Error(' Returning: ' + ResponseStr, LOG_TAG); {$ENDIF} end; AContext.Connection.Socket.WriteLn(ResponseStr); DoOnExecute(ResponseStr); end; function TdmTCPParksServer.IsRunning: Boolean; begin Result := IdTCPMyParksServer.Active; end; procedure TdmTCPParksServer.Start; begin {$IFDEF LINUX} syslog(LOG_NOTICE, 'TCP Server Starting'); {$ELSE} Log.Info('START', LOG_TAG); {$ENDIF} IdTCPMyParksServer.Active := True; end; procedure TdmTCPParksServer.Stop; begin {$IFDEF LINUX} syslog(LOG_NOTICE, 'TCP Server Stopping'); {$ELSE} Log.Info('STOP', LOG_TAG); {$ENDIF} IdTCPMyParksServer.Active := False; end; initialization dmTCPParksServer := TdmTCPParksServer.Create(nil); finalization dmTCPParksServer.Free; end.
25.67757
105
0.712648
85bcd16c2374dcacb807778256af40247bfe0924
3,216
pas
Pascal
mp/ParseErrors.pas
shaoziyang/LittleInterpretors
f0eb011dd3a0e9b82886465033fd1757bfa96f81
[ "CC0-1.0" ]
1
2022-03-18T19:18:37.000Z
2022-03-18T19:18:37.000Z
mp/ParseErrors.pas
shaoziyang/LittleInterpreters
f0eb011dd3a0e9b82886465033fd1757bfa96f81
[ "CC0-1.0" ]
null
null
null
mp/ParseErrors.pas
shaoziyang/LittleInterpreters
f0eb011dd3a0e9b82886465033fd1757bfa96f81
[ "CC0-1.0" ]
null
null
null
{ *********************************************************************** } { } { ParseErrors } { } { Copyright (c) 2006 Pisarev Yuriy (post@pisarev.net) } { } { *********************************************************************** } unit ParseErrors; {$B-} interface uses SysUtils; type EParserError = class(Exception); const ErrorMessage = '%s: "%s"'; AMutualExcessError = 'Function "%s" requires expression after itself, function "%s" requires expression before itself'; BMutualExcessError = 'Function "%s" does not require expression after itself, function "%s" does not require expression before itself'; BracketError = 'Bracket character expected'; EmptyTextError = 'Empty text'; FunctionHandleError = 'Function handle error: "%s"'; FunctionExpectError = 'Function expected: "%s"'; ElementError = 'Unknown element: "%s"'; RExcessError = '"%s" does not require expression after itself'; LTextExcessError = 'Function "%s" does not require expression before itself'; LTextExpectError = 'Function "%s" requires expression before itself'; DefinitionError = '"%s" cannot start with a number'; AParameterExcessError = 'Function "%s" does not require parameters'; BParameterExcessError = 'Too much parameters for function "%s"'; AParameterExpectError = 'Function "%s" requires parameters'; BParameterExpectError = 'Not enough parameters for function "%s"'; ReserveError = 'Text "%s" contains reserved character: "%s"'; RTextExcessError = 'Function "%s" does not require expression after itself'; RTextExpectError = 'Function "%s" requires expression after itself'; ScriptError = 'Script error'; StringError = '"%s" cannot be the part of math expression'; StringTypeError = '"%s" cannot have type of string'; NumberTypeError = 'Cannot apply "%s" type to "%s" number in "%s" expression'; FunctionTypeError = 'Cannot apply "%s" type to "%s" function in "%s" expression'; ScriptTypeError = 'Cannot apply "%s" type to "%s" script in "%s" expression'; TextError = 'Expression expected: "%s"'; function Error(const Message: string): Exception; overload; function Error(const Message: string; const Arguments: array of const): Exception; overload; function Error(const Text, Message: string): Exception; overload; function Error(const Text, Message: string; const Arguments: array of const): Exception; overload; implementation function Error(const Message: string): Exception; begin Result := Error(Message, []); end; function Error(const Message: string; const Arguments: array of const): Exception; begin Result := EParserError.CreateFmt(Message, Arguments); end; function Error(const Text, Message: string): Exception; begin Result := Error(Text, Message, []); end; function Error(const Text, Message: string; const Arguments: array of const): Exception; begin Result := Error(Format(ErrorMessage, [Format(Message, Arguments), Text])); end; end.
41.230769
137
0.626866
47f32286b56f9a107d1caf0bcc433f6542790fd4
17,805
dfm
Pascal
DemosWithoutInstall/ShellContextMenuHandlerSimple/ContextMenuHandlerMain.dfm
magnussandberg/The-Drag-and-Drop-Component-Suite-for-Delphi
31ce9e0b89a093b140f64ded119b8ea75b9f5eed
[ "MIT" ]
98
2015-08-24T13:11:14.000Z
2020-08-19T14:25:40.000Z
DemosWithoutInstall/ShellContextMenuHandlerSimple/ContextMenuHandlerMain.dfm
magnussandberg/The-Drag-and-Drop-Component-Suite-for-Delphi
31ce9e0b89a093b140f64ded119b8ea75b9f5eed
[ "MIT" ]
40
2015-11-26T22:14:18.000Z
2020-03-30T12:11:07.000Z
DemosWithoutInstall/ShellContextMenuHandlerSimple/ContextMenuHandlerMain.dfm
magnussandberg/The-Drag-and-Drop-Component-Suite-for-Delphi
31ce9e0b89a093b140f64ded119b8ea75b9f5eed
[ "MIT" ]
34
2015-12-14T12:39:45.000Z
2020-08-10T21:12:05.000Z
object DataModuleContextMenuHandler: TDataModuleContextMenuHandler OldCreateOrder = False OnCreate = DataModuleCreate Height = 279 Width = 409 object PopupMenu1: TPopupMenu Images = ImageList1 OwnerDraw = True Left = 48 Top = 72 object N1: TMenuItem Caption = '-' end object test1: TMenuItem Bitmap.Data = { 36030000424D3603000000000000360000002800000010000000100000000100 18000000000000030000F00A0000F00A00000000000000000000C0C0C0C0C0C0 C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0 C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C06699662D7E2B16 740F17720E2C7A29639463C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0 C0C0C08BAE8B117F110888000F8D001388001F7E00327200266D00156F0E86AA 86C0C0C0C0C0C0C0C0C0C0C0C0C0C0C08BB18B06860804A008009D0000A30D00 9A000097000094001E7E00396B00126B0386A886C0C0C0C0C0C0C0C0C0C0C0C0 188B180BA81701A10D38BF54DCF3E97ADD9B009D030099000098001285003A6C 0013700EC0C0C0C0C0C0C0C0C069A16924A82F08A91B2BB43EF6F0F5FCF6FAFF FFFF7DDE9C009E07009B02009900217D00266E00639463C0C0C0C0C0C031932F 39BF4F20AA2AECE6EAF5EEF4FFF7FFFFFBFFFFFFFF7DDD9C009F09009B020294 00367100297C29C0C0C0C0C0C02197263BBE50AAC9A7FAEAF9D1E1D11EAF33DA EFDDFFFFFFFFFFFF7BDD9B009E07009A00297C0014740DC0C0C0C0C0C0249A27 5DD27C17A3258EBF8811AB241BB9400BAD27DBEFDFFFFFFFFFFFFF7BDB99009E 021B860014760DC0C0C0C0C0C031983177DC952CC55A1FBB4529C45626C04F22 BB450BAC26DAEEDDFFFCFFFFFDFF78DB96138C002B822AC0C0C0C0C0C06CA66C 53C66C61D8892ECA622FC9612CC55927C04D20B94209AA22DAEDDDFFF9FFCAEC D70E8E08659A65C0C0C0C0C0C0C0C0C0219D2683E5A74CD3792ECB632FC96029 C35422BB461CB53A0BA81F7ACC8511AD24117F11C0C0C0C0C0C0C0C0C0C0C0C0 90B89026A72F81E3A65ED88831CA6327C35321BC471DB63B16B02E0FA920068B 098BB28BC0C0C0C0C0C0C0C0C0C0C0C0C0C0C090B890229E2656CA7377E09C59 D37E43C86636C1541EAA2F168E168BB28BC0C0C0C0C0C0C0C0C0C0C0C0C0C0C0 C0C0C0C0C0C0C0C0C06CA76C329B32259D2B21992731973069A369C0C0C0C0C0 C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0 C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0} Caption = 'Item with bitmap' OnClick = MenuTest1Click end object Itemwithaccelerator1: TMenuItem Caption = 'Item with &accelerator' OnClick = MenuTest1Click end object Anotheritemwithanaccelerator1: TMenuItem Caption = '&Another item with an accelerator' OnClick = MenuTest1Click end object Yetanotheritemwithyouknowwhat1: TMenuItem Caption = '&Yet another item with you know what' OnClick = MenuTest1Click end object submenu1: TMenuItem Caption = '&Sub menu' object Item1: TMenuItem Caption = 'Item with shortcut (doesn'#39't work)' ShortCut = 122 OnClick = MenuTest1Click end object Item21: TMenuItem Caption = 'Item with &accelerator' OnClick = MenuTest1Click end object N3: TMenuItem Caption = '-' end object Itemwithglyphfrombitmap1: TMenuItem Bitmap.Data = { 36050000424D3605000000000000360400002800000010000000100000000100 08000000000000010000C21E0000C21E0000000100000000000001B0EE0071E6 FE0049E3FF002FDDFF002DA3E2000293D20016BAF00018B9EE0038C7F60068D6 FB0050CEF5001BD9FF0000AAEC0001C8FA0000B8F3000ED5FF0000000000FFFF FF00000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000002000068781200426658001C02 0000747812007C781200080000000E000000287A120011FFFF00010000000000 0000000000000000000098781200C0E4DD008A2CFB0000008300B8E4DD00C0E4 DD0074781200880683002C791200647EFB005831F800FFFFFF003C791200C2B7 FC0018078300C0E4DD00C892DB00C0E4DD00ECB6140011FFFF0001000000FFB0 FC0000001300BEB4FC0018B6FC000A0200001A02000000000000474946003961 12001200C40000EEB00000E67100030000002FE2A300D2930200BA16EE0018F6 C700FBD66800000083000300000000E4DD00180000000E00000000E0FD0001E0 FD0060791200A8781200D092DB0074791200647EFB007816F800FFFFFF008479 1200001E00000000830000000000C0E4DD00C892DB004092DB00ECB614002244 9E00208812006ABD000050220300FFFFFF000C000000208812006ABD0000A022 03002FCAFE001002130010021300A193F800B801000000000000000000000000 0000C07912002800090000000000000000000000000000000000000000002400 020000000000000000000000000000ECFD004A004C007567F80060FCFC00376F F800306FF800080200001A02000080A01700F0BC5800080000000E0000000B00 0000017A12002500000002000000FFFFFF00000400000000000000040000B814 0000000400000000000043000000147B12004A00000001000000030000000000 00004A000800000000004A004C0000ECFD000000000043000000167B12000000 0000000000004A00000038A317003804130078A0170000E0FD0000E0FD00307D 1200647EFB006811F800FFFFFF00407D12001A02000008000000407D12007567 F80060FCFC005467F800426658001C020000E47A1200EC7A1200080000000E00 0000C882120018E2DA000900000063003A005C004C0069006200720061007200 79005C0067000000000000000000EF00000000000000C8821200B7C8FE001C02 0000000000000000000001000000653BFC001C0200000000000001000000CE3B FC00C88212000000000001000000966F9700C8821200C882120018E2DA00EF00 000009000000D0CF1100A1B11A000067610054C1CE008553000000A1F9000000 00000000000000000000EF00000000000000000000000000000000000000B07B 1200030000000C2CFB00000083001807830003000000C0E4DD00585810585858 585858585858105858585810091010585858585810100C105858581001000410 105810100C0E0E1058585858100B0E05041007000E0E10585858585810010B0E 05000E0D060E1058585858585810020B0E0D0D0D00105858585858585810020B 0F0F0D000C10585858585858100E030F0F0F0D0C0E0C1058585858100D0E0D0F 0F0F0F0D0E0E0C105858100A0D0F0B0B0B0F0B0F0D0C040C1058101010101002 030F0302101010101010585858585810010F0110585858585858585858585810 0F0D0F1058585858585858585858585810081058585858585858585858585858 100F105858585858585858585858585858105858585858585858} Caption = 'Item with glyph from bitmap' OnClick = MenuTest1Click end object Itemwithglyphfromimagelist1: TMenuItem Caption = 'Item with glyph from image list' ImageIndex = 2 OnClick = MenuTest1Click end object Disableditem1: TMenuItem Caption = 'Hidden item' Visible = False OnClick = MenuTest1Click end object Disableditem2: TMenuItem Caption = 'Disabled item' Enabled = False OnClick = MenuTest1Click end object N4: TMenuItem Caption = '-' end object Checkeditem1: TMenuItem Caption = 'Checked item' Checked = True OnClick = MenuTest1Click end object Radioitem1: TMenuItem Caption = 'Radio item' Checked = True RadioItem = True OnClick = MenuTest1Click end object Barbreakitem1: TMenuItem Break = mbBarBreak Caption = 'Bar break item' OnClick = MenuTest1Click end object Followedbyaregularitem1: TMenuItem Caption = 'Followed by a regular item' OnClick = MenuTest1Click end object Breakitem1: TMenuItem Break = mbBreak Caption = 'Break item' OnClick = MenuTest1Click end object Anthelastitem1: TMenuItem Caption = 'And finally the last item' OnClick = MenuTest1Click end end object Glyphfromimagelist1: TMenuItem Caption = 'Glyph from image list' ImageIndex = 0 OnClick = MenuTest1Click end object N2: TMenuItem Caption = '-' end end object ImageList1: TImageList Left = 48 Top = 140 Bitmap = { 494C010103000500040010001000FFFFFFFFFF10FFFFFFFFFFFFFFFF424D3600 0000000000003600000028000000400000001000000001002000000000000010 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000004891E1000365 D5000962D500055FD6000859D2000858CF000554CD000653CE000556CF000A56 D4000356CF00538DDF0000000000000000000000000000000000494AE200060A D500080AD4000509D4000808D6000509D3000708D4000608D2000608D2000408 D2000509D3005455E100000000000000000000000000000000005FB782002397 52002197500020914E001F8F49001D8F49001D8C48001A8C4600198B45001B8A 46001D8B430066B0860000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000003288E2001A75DE002979 DE002575DA00216FD4001F6AD100175FCA00165AC300175AC7001A63CF001D64 D3001864D4000C5ED5004584DC0000000000000000003636E2001A30D6002F4A DA002944DA002540D700253BD7002138D4001F34D3001A33D1001F30D3001D30 D5001F2FD6000F1ED2004346DE00000000000000000053AF7A0035AC680040B2 73003BAE6B0038AE670036A7630031A5600032A35F002EA35A002EA25C002FA2 59002DA35C002699500058AB7700000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000016DDC003686DD003081 DC00287DD9002774D5003D7DD500F7F8FC00E1E7F4001B5DC4001964D0001C67 D3001D69D3001E66D6000356D00000000000000000000105D6003B5BDC003255 DA002F4ED900324ADA002C44D900273FD5002238CD002035CD002234D5001E35 D7002134D7002233D6000002D200000000000000000023A159004BBD7E0047B9 79004AB5760040B16D003EAB660038A4620034A5610036A7630032A6610035A5 5F0032A45E0031A66100188B4100000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000172E0003D8DE0003A8A DD003486DF002F7ED9005C91DA00FFFEFF00F4F9FC002265C800226BD300226E D800206CD600236ED5000055CF0000000000000000000105D9004263DE003D5D DE003858DF003654DB00334EDA00FBFFFF00FFFEFF00283CD100283DD400253B D6002639D600253BD7000002D200000000000000000026A35E0056C2870055BF 840049BB7B0046B27700FDFFFF003AA2630037A361003DA7650037AA670039AA 670036A8620036A76400178C4300000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000477E0004799E1004294 E500418FE2003E85E000357CD3005D8ED2004279CA00266AC9002C73D4002975 D9002571DB002771D7000258D40000000000000000000309D8004C71DF00496E DE004564DD004561DE003F5CDD00FFFFFF00FFFFFF003249D4002D48D9002C46 DA002B40D8002B40D8000103D30000000000000000002EA862005FC88F005BC8 8A0058BF8500FFFEFF00FEFFFD00FFFFFE0040A66C003EA8660044AE69003DAE 6B003FAD6B003DAC6800188C4600000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000127FE10057A1E900509E E5004C9AE6004793DF003F87D500E9EDF800C8D4EC002F6CC9003279D400327D D9002D7ADA002F79D9000059D20000000000000000001618DB005B7CE3005777 E0005175E0004A6FDF004869DE004563DA003D56D4003A53D3003A53D900394C DD003448DB003049DB000103D300000000000000000037AC6D0070D199006ACC 9600FEFEFE00FDFEFF00FDFFFF00FFFFFF00FFFFFF0048A9710043AB6C0045AD 700045B0710043B17100198F4800000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000002388E40069ADE80061A7 EA005EA5E800529DE2004990DA00F7F8FC00F6F7FB003872C4003979CE003481 D8003582DE00367FDB00035DD40000000000000000002228DF00708BE5006687 E4006284E2005D7BE4005577E200FFFFFF00FFFFFF00415CCF00435DD9003D58 DE003E54DC003A50DE000003D400000000000000000046B375007ED3A60078D3 A200FFFFFF00FDFFFF0069C99300FFFFFF00FFFFFF00FFFFFF004CAD740049AD 73004AB2750049B476001D914B00000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000003191E50079B5EB0075B2 EA006FAEEA0068A9E6005B9CE100A9C4E600FBFFFF00C9D6EC003A79CA004082 D5003D87DF003E89DF00005FD70000000000000000002E35DE007C96EA007894 E8007491E6006E8CE5006588E200FFFFFF00FFFFFF004D67D3004B66DE004A65 DD00435CE000435BDD000203D50000000000000000004EB77E008DD9AF0087D6 AB0083D5AA0080D2A70079D1A30072CF9C00FFFFFE00FFFFFF00FEFDFF0050AF 760051B0770053B77D001E944D00000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000004097E70083BDEE0081BA ED007DB6ED0079B1E8006FA7E2006096D700C2D2E900FFFFFF0090B0DB004683 D300488DDC004B90E0000061D90000000000000000003F42E4008BA2ED0087A0 EA00849CE8008099E9007795E800FFFFFF00FFFEFF005575D4005775DE005571 E0004E6BDE004F66E0000004D50000000000000000005FBC890097DCB70097DD B5008FDAB4008FD9AF0088D9AC007FD8A7007DD3A300FDFFFF00FFFFFF00FDFF FF005AB780005EBC85001D975100000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000004A9CEA0094C2F1008EBE EE008CBDEB0081B0E40073A1DB006995D2006991CC00FFFFFE00E2E5F3004E88 D3005298DE005399E6000268D80000000000000000004A4DE50093AAEE0094AA EB0092AAEC008DA7EA008CA2EA00FFFFFF00FFFFFF00687ED6006881E1006180 E3005D77E3005872E4000003D700000000000000000066BE9000A1E0C0009EDE BB00A0E0BC0099DCBC0098DBB40093D9B40089D7AE0082D4A900FFFFFF00FFFF FE0065C4910069C68F001F9B5500000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000052A2E9009DC7F10098C3 EE0090BBE600D3E1F300AFC2E500A6B8DD00C1CFE600FFFFFF00E4E8F3005C96 D8005EA2E3005FA2E700006CDB0000000000000000005057E2009FB3ED009EB4 EE00A0B3F00097B2EB0095AEEC00FFFEFF00FFFFFE007990DE007593E200708E E7006786E300627EE3000004D90000000000000000006FC39300A8E2C500ABE4 C300A6E0C300A8E1C000A5E2BE009FDFBC009ADDB80094DAB10089D8AD007ED4 A40077D2A10072CD9C00259C5800000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000057A5E800A1CCF300A2C9 F000A4C5EC00F9FCFF00FFFFFF00FFFFFF00FFFFFF00FBFAFE009DBAE10074A8 E4006DABE70066ABEA000370DC000000000000000000595AE600A8B9F100A5B9 F000ABBAF200A5BAED00A5B6EF00FFFEFF00FFFFFF008CA2E900869FE7007F9A EA007392E7006D89E7000405D900000000000000000074C59600ADE5C800B1E4 C800B2E5CA00B2E5C900AEE3C800AAE3C200A5E0C1009FDFBC0095DCB40091D8 B00084D3AA007FD2A50028A25C00000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000074B6EB0087BCEE00A7CD F000A5C9EF009FC1E500B5CBE700B2C5E600BACCE9008AB0E00088B3E40087B8 EA007DB6ED003792E3003792E70000000000000000007778EA008695EB00AFBD F100B2C0F100AFC0F100ADBEEF00A8BAEF00A3B7F0009FB3ED0096ABEF0093A4 ED007F9CE6003D51DE00393BDF0000000000000000008CCFA80098DAB700B5E6 CA00BAE9CF00B9E8CE00B6E8CA00B1E6CB00AFE5C700A7E1C400A1E0C0009BDE B90091DBB10054C0850054BA8000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000085BCEF0067AD E90068AAEB0069A8E50060A4E500599EE300559BE1004D9AE3004196E400348F E4002587E5004FA0EB00000000000000000000000000000000008486EC00676C E700686DE800696EE900696AEA006464E600585BE5005151E5004146E3003437 E000232ADF005052E6000000000000000000000000000000000098D5B10081CA A20083CBA10082CBA5007CCAA1007BC79E0075C596006CC292005FBD860055B7 810044B277006CC2920000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000424D3E000000000000003E000000 2800000040000000100000000100010000000000800000000000000000000000 000000000000000000000000FFFFFF00FFFFFFFFFFFF0000C003C003C0030000 8001800180010000800180018001000080018001800100008001800180010000 8001800180010000800180018001000080018001800100008001800180010000 8001800180010000800180018001000080018001800100008001800180010000 C003C003C0030000FFFFFFFFFFFF000000000000000000000000000000000000 000000000000} end end
55.815047
74
0.842572
479dddec6e1e4ba80e5f1ccec7ae36e81ebb5d03
1,072
pas
Pascal
Visitor/src/model/Visitor.model.Varejo.pas
rafael-figueiredo-alves/Design_Patterns_em_Delphi
e840c540e6d0b35a5e0acc286ffab91ab2be2d45
[ "MIT" ]
1
2022-01-20T01:07:59.000Z
2022-01-20T01:07:59.000Z
Visitor/src/model/Visitor.model.Varejo.pas
rafael-figueiredo-alves/Design_Patterns_em_Delphi
e840c540e6d0b35a5e0acc286ffab91ab2be2d45
[ "MIT" ]
null
null
null
Visitor/src/model/Visitor.model.Varejo.pas
rafael-figueiredo-alves/Design_Patterns_em_Delphi
e840c540e6d0b35a5e0acc286ffab91ab2be2d45
[ "MIT" ]
null
null
null
unit Visitor.model.Varejo; interface uses Visitor.model.interfaces; Type TModelVarejo = Class(TInterfacedObject, iItemRegras, iVisitor) Private FItem : iItem; Public Constructor Create; Destructor Destroy; Override; Class function New: iItemRegras; Function PrecoVenda: Currency; Function PrecoPromocao: Currency; Function Visitor: iVisitor; Function Visit(Value: iItem): iItemRegras; End; implementation { TModelVarejo } constructor TModelVarejo.Create; begin end; destructor TModelVarejo.Destroy; begin inherited; end; class function TModelVarejo.New: iItemRegras; begin Result := Self.Create; end; function TModelVarejo.PrecoPromocao: Currency; begin Result := (FItem.PrecoUnitario * 0.75); //com 25% de desconto end; function TModelVarejo.PrecoVenda: Currency; begin Result := (FItem.PrecoUnitario * 1); //sem desconto end; function TModelVarejo.Visit(Value: iItem): iItemRegras; begin FItem := Value; Result := self; end; function TModelVarejo.Visitor: iVisitor; begin Result := Self; end; end.
16.75
64
0.742537
85b2231654dceecf980ddf98b4357c913893a8eb
5,126
pas
Pascal
DelphiLanguageSession/03_AnonymousCalculatedFields/AnonymousCalculatedFields_MainForm.pas
xchinjo/DelphiSessions
0679d97a78ff232c6bbec1217c4f8c2104d58210
[ "MIT" ]
44
2017-05-30T20:54:06.000Z
2022-02-25T16:44:23.000Z
DelphiLanguageSession/03_AnonymousCalculatedFields/AnonymousCalculatedFields_MainForm.pas
jpluimers/DelphiSessions
0679d97a78ff232c6bbec1217c4f8c2104d58210
[ "MIT" ]
null
null
null
DelphiLanguageSession/03_AnonymousCalculatedFields/AnonymousCalculatedFields_MainForm.pas
jpluimers/DelphiSessions
0679d97a78ff232c6bbec1217c4f8c2104d58210
[ "MIT" ]
19
2017-07-25T10:03:13.000Z
2021-10-17T11:40:38.000Z
unit AnonymousCalculatedFields_MainForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DBXFirebird, Data.FMTBcd, Vcl.Grids, Vcl.DBGrids, Data.DB, Datasnap.Provider, Data.SqlExpr, Datasnap.DBClient, Generics.Collections, Vcl.StdCtrls; type TClientDataSet = class (DataSnap.DBClient.TClientDataSet) private fTrueCalc: Boolean; FDerivedDataset: TClientDataSet; FFieldCalculations: TDictionary<string,TFunc<string>>; public // snapshot version procedure AddExtraField (const fieldName: string; fieldType: TFieldType; nSize: Integer; calcField: TFunc<string>); overload; procedure CommitExtraFields; function GetDerivedDataset: TClientDataSet; protected procedure CreateFields; override; public // truly calculated version procedure AddExtraFieldCalc(const fieldName: string; fieldType: TFieldType; nSize: Integer; calcField: TFunc<string>); procedure DoCalc (DataSet: TDataSet); end; TForm1 = class(TForm) FBCONNECTION: TSQLConnection; ClientDataSet1: TClientDataSet; SQLDataSet1: TSQLDataSet; DataSetProvider1: TDataSetProvider; DataSource1: TDataSource; DBGrid1: TDBGrid; btnPlain: TButton; btnCalc: TButton; btnTrueCalc: TButton; procedure btnPlainClick(Sender: TObject); procedure btnCalcClick(Sender: TObject); procedure btnTrueCalcClick(Sender: TObject); public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} uses DateUtils; { TClientDataSet } procedure TClientDataSet.AddExtraField(const fieldName: string; fieldType: TFieldType; nSize: Integer; calcField: TFunc<string>); begin if not Assigned (FDerivedDataset) then begin FDerivedDataset := TClientDataSet.Create(nil); FDerivedDataset.FieldDefs.Assign(self.FieldDefs); FFieldCalculations := TDictionary<string,TFunc<string>>.Create; end; if FDerivedDataset.Active = False then begin FDerivedDataset.FieldDefs.Add(fieldName, fieldType, nSize, FDerivedDataset.FieldDefs.Count = 0); // first is key field if Assigned (calcField) then FFieldCalculations.Add (fieldname, calcField); end; end; procedure TClientDataSet.AddExtraFieldCalc(const fieldName: string; fieldType: TFieldType; nSize: Integer; calcField: TFunc<string>); begin fTrueCalc := True; if not Assigned (FFieldCalculations) then begin OnCalcFields := DoCalc; FFieldCalculations := TDictionary<string,TFunc<string>>.Create; end; FFieldCalculations.Add (fieldname, calcField); end; procedure TClientDataSet.CommitExtraFields; var i: Integer; fieldname: string; aFunct: TFunc<string>; begin FDerivedDataset.CreateDataSet; FDerivedDataset.Open; self.First; while not self.Eof do begin FDerivedDataset.Append; for i := 0 to self.FieldCount - 1 do begin FDerivedDataset.Fields[i].Value := self.Fields[i].Value; end; for fieldname in FFieldCalculations.Keys do begin aFunct := FFieldCalculations[fieldname]; FDerivedDataset.FieldByName (fieldname).AsString := aFunct; end; FDerivedDataset.UpdateRecord; self.Next; end; end; procedure TClientDataSet.CreateFields; var calcField: TStringField; fieldname: string; begin inherited; if FTrueCalc then for fieldname in FFieldCalculations.Keys do begin calcField := TStringField.Create(self); calcField.FieldKind := fkCalculated; calcField.FieldName := fieldname; calcField.Index := -1; calcField.Size := 20; calcField.DataSet := self; end; end; procedure TClientDataSet.DoCalc(DataSet: TDataSet); var fieldname: string; aFunct: TFunc<string>; begin for fieldname in FFieldCalculations.Keys do begin aFunct := FFieldCalculations[fieldname]; Dataset.FieldByName (fieldname).AsString := aFunct; end; end; function TClientDataSet.GetDerivedDataset: TClientDataSet; begin Result := FDerivedDataset; end; procedure TForm1.btnCalcClick(Sender: TObject); begin ClientDataSet1.Close; DataSource1.DataSet := nil; ClientDataSet1.Open; ClientDataSet1.AddExtraField('WorkYears', ftString, 10, function () : string begin Result := IntToStr (YearsBetween (Now, ClientDataSet1.FieldByName('HIRE_DATE').AsDateTime)); end); ClientDataSet1.CommitExtraFields; DataSource1.DataSet := ClientDataSet1.GetDerivedDataset; end; procedure TForm1.btnPlainClick(Sender: TObject); begin ClientDataSet1.Close; ClientDataSet1.Open; end; procedure TForm1.btnTrueCalcClick(Sender: TObject); begin ClientDataSet1.Close; ClientDataSet1.AddExtraFieldCalc('WorkYears', ftString, 10, function () : string begin Result := IntToStr (YearsBetween (Now, ClientDataSet1.FieldByName('HIRE_DATE').AsDateTime)); end); ClientDataSet1.Open; end; end.
27.121693
99
0.710886
fc5b3479b44d422192f63f3ae9160e14943de800
101
lpr
Pascal
Examples/FPC/prj_CountSurround.lpr
joecare99/Public
9eee060fbdd32bab33cf65044602976ac83f4b83
[ "MIT" ]
11
2017-06-17T05:13:45.000Z
2021-07-11T13:18:48.000Z
Examples/FPC/prj_CountSurround.lpr
joecare99/Public
9eee060fbdd32bab33cf65044602976ac83f4b83
[ "MIT" ]
2
2019-03-05T12:52:40.000Z
2021-12-03T12:34:26.000Z
Examples/FPC/prj_CountSurround.lpr
joecare99/Public
9eee060fbdd32bab33cf65044602976ac83f4b83
[ "MIT" ]
6
2017-09-07T09:10:09.000Z
2022-02-19T20:19:58.000Z
program prj_CountSurround; uses unt_CountSurrond; {$AppType console} begin Execute; end.
11.222222
27
0.722772
83dc871d02550341dfc4ac4e5a0a3deba464510f
297
pas
Pascal
DPAInformatics/01.pas
erodot/UniversityLabs
9d11825b62f64a78e13a132815bfb888c4093aed
[ "MIT" ]
null
null
null
DPAInformatics/01.pas
erodot/UniversityLabs
9d11825b62f64a78e13a132815bfb888c4093aed
[ "MIT" ]
null
null
null
DPAInformatics/01.pas
erodot/UniversityLabs
9d11825b62f64a78e13a132815bfb888c4093aed
[ "MIT" ]
null
null
null
Program v1; Var n,k,num:integer; function simple(n:integer):boolean; Var i:integer; begin simple:=true; for i:=2 to n-1 do if (n mod i = 0) then simple:=false; end; begin readln(n); num:=2; k:=0; while(k<n) do begin if(simple(num)) then begin write(num,' '); k:=k+1; end; num:=num+1; end; end.
11.423077
35
0.656566
f18617d773a05b7e5d3264720add4d2531228863
603
dpr
Pascal
test/resources/testproject-android/TestProject.dpr
ashumkin/rake-delphi
0cb95d0664885e90c2d0561edb3fba91071261f2
[ "MIT" ]
3
2015-01-26T12:13:59.000Z
2016-09-01T11:03:02.000Z
test/resources/testproject-android/TestProject.dpr
ashumkin/rake-delphi
0cb95d0664885e90c2d0561edb3fba91071261f2
[ "MIT" ]
null
null
null
test/resources/testproject-android/TestProject.dpr
ashumkin/rake-delphi
0cb95d0664885e90c2d0561edb3fba91071261f2
[ "MIT" ]
null
null
null
program TestProject; uses System.StartUpCopy, FMX.MobilePreview, Forms, SysUtils, {$IFDEF LIBS} LibUnit, {$ENDIF LIBS} {$IFDEF EXPLICIT_LIBS} ExplicitLibUnit, {$ENDIF} fmTest in 'fmTest.pas' {TestForm}; {$R *.res} var s: string; begin s := EmptyStr; {$IFDEF LIBS} s := s + LibUnit.LibUnitFunction; {$ENDIF LIBS} {$IFDEF EXPLICIT_LIBS} s := s + ExplicitLibUnit.ExplicitLibUnitFunction; {$ENDIF EXPLICIT_LIBS} Application.Initialize; Application.CreateForm(TTestForm, TestForm); TestForm.Caption := s; Application.Run; end.
18.272727
52
0.6534
83cca0a2a04b6601ea228f692df8b33116b603d9
4,554
pas
Pascal
FundamentalSyntacticElements.pas
MatthewMcAndrews/delphi-tokenizer
fea5b623125b8c471680c4a39a113fe1deee50ea
[ "MIT" ]
1
2022-03-10T09:37:06.000Z
2022-03-10T09:37:06.000Z
FundamentalSyntacticElements.pas
MatthewMcAndrews/delphi-tokenizer
fea5b623125b8c471680c4a39a113fe1deee50ea
[ "MIT" ]
null
null
null
FundamentalSyntacticElements.pas
MatthewMcAndrews/delphi-tokenizer
fea5b623125b8c471680c4a39a113fe1deee50ea
[ "MIT" ]
null
null
null
unit FundamentalSyntacticElements; interface { a program is a sequence of tokens delimited by separators } { case insensitive } type {$SCOPEDENUMS ON} { Tokens and Separators combine to make these } TThing = ( tExpression, { syntactic units that occur within statements and denote values } tDeclaration, { definitions of identifiers that can be used in expressions and statements } tStatement { algorithmic actions that can be executed within a program } ); { ends with a semicolon } TDeclaration = ( dHintDirecticve, { e.g. deprecated; experimental; } dVariable, dConstant, dType, dField, dProperty, dProcedure, dFunction, dProgram, dUnit, dLibrary, dPackage ); TStatement = ( sAssignment, { variable := expression } sProcedureCall, { name; name(arg); name(arg1,...); } sFunctionCall, sGotoJump { goto label, label: statement, label label1, label2; } ); TVariable = ( vVariableTypecast, vDereferencedPointer, vStructuredVariableComponent ); TState = ( sToken, sSeparator ); TToken = ( tSpecialSymbol, tIdentifier, tReservedWord, tDirective, tNumeral, { integers, reals, +/-, exp, $hex } tLabel, { identifier or uint32 } tString { can contain separators } ); TString = ( sQuoted, { '', can contain separators, '' = ' } sControl { #utf-16 } ); TSeparator = ( sBlank, sComment {} (**) // alike comments cannot be nested ); { only the first 255 characters of an identifier are significant } { must begin with an alphanumeric or underscore may not contain spaces after the first character, may include digits may not be reserved words } { reserved words can be used if calls are prefixed by &- } { may be qualified by a namespace } TIdentifier = ( iConstant, iVariable, iField, iType, iProperty, iProcedure, iFunction, iProgram, iUnit, iLibrary, iPackage ); TDirective = ( dContextSensitive, { can be used as identifiers } dCompilerDirective { surrounded by braces and starts with $ } ); const TokensRequiringSeparatorsBetweenThem = [ TToken.tIdentifier, TToken.tReservedWord, TToken.tNumeral, TToken.tLabel]; const OneCharacterSpecialSymbols: array[0..22] of string = ( '#', '$', '&', '''', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '@', '[', ']', '^', '{', '}'); const TwoCharacterSpecialSymbols: array[0..9] of string = ( '(*', '(.', '*)', '.)', '..', '//', ':=', '<=', '>=', '<>'); function IsOneCharacterSpecialSymbol(const c: Char): Boolean; function IsTwoCharacterSpecialSymbol(const s : string): Boolean; const ReservedWords: array[0..63] of string = ( 'and', 'end', 'interface', 'record', 'var', 'array', 'except', 'is', 'repeat', 'while', 'as', 'exports', 'label', 'resourcestring', 'with', 'asm', 'file', 'library', 'set', 'xor', 'begin', 'finalization', 'mod', 'shl', 'case', 'finally', 'nil', 'shr', 'class', 'for', 'not', 'string', 'const', 'function', 'object', 'then', 'constructor', 'goto', 'of', 'threadvar', 'destructor', 'if', 'or', 'to', 'dispinterface', 'implementation', 'packed', 'try', 'div', 'in', 'procedure', 'type', 'do', 'inherited', 'program', 'unit', 'downto', 'initialization', 'property', 'until', 'else', 'inline', 'raise', 'uses'); const Directives: array[0..56] of string = ( 'absolute', 'export', 'name', 'public', 'stdcall', 'abstract', 'external', 'near', 'published', 'strict', 'assembler', 'far', 'nodefault', 'read', 'stored', 'automated', 'final', 'operator', 'readonly', 'unsafe', 'cdecl', 'forward', 'out', 'reference', 'varargs', 'contains', 'helper', 'overload', 'register', 'virtual', 'default', 'implements', 'override', 'reintroduce', 'winapi', 'delayed', 'index', 'package', 'requires', 'write', 'deprecated', 'inline', 'pascal', 'resident', 'writeonly', 'dispid', 'library', 'platform', 'safecall', 'dynamic', 'local', 'private', 'sealed', 'experimental', 'message', 'protected', 'static'); implementation function IsOneCharacterSpecialSymbol(const c: Char): Boolean; begin for var SpecialSymbol in OneCharacterSpecialSymbols do begin if c = SpecialSymbol then begin Exit(True); end; end; Result := False; end; function IsTwoCharacterSpecialSymbol(const s : string): Boolean; begin for var SpecialSymbol in TwoCharacterSpecialSymbols do begin if s = SpecialSymbol then begin Exit(True); end; end; Result := False; end; end.
30.979592
95
0.631752
c37058be668a3332d6c00a22b51b41179e3e02ad
7,996
pas
Pascal
Operacion/AnularVenta/Form/AnularVtaF.pas
Civeloo/GeN-XE7
638b59def20424955972a568817d012df4cf2cde
[ "Apache-2.0" ]
null
null
null
Operacion/AnularVenta/Form/AnularVtaF.pas
Civeloo/GeN-XE7
638b59def20424955972a568817d012df4cf2cde
[ "Apache-2.0" ]
null
null
null
Operacion/AnularVenta/Form/AnularVtaF.pas
Civeloo/GeN-XE7
638b59def20424955972a568817d012df4cf2cde
[ "Apache-2.0" ]
null
null
null
unit AnularVtaF; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, DB, ExtCtrls, DataModule, OperacionDM, IBX.IBCustomDataSet, IBX.IBQuery; type TFAnulaReimp = class(TForm) Label1: TLabel; BitBtn1: TBitBtn; NoBitBtn: TBitBtn; buscarBitBtn: TBitBtn; BitBtn2: TBitBtn; nroEdit: TEdit; LetraLabel: TLabel; Label2: TLabel; procedure BitBtn1Click(Sender: TObject); procedure buscarBitBtnClick(Sender: TObject); procedure BitBtn2Click(Sender: TObject); procedure NoBitBtnClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } salir : Boolean; public { Public declarations } end; var FAnulaReimp: TFAnulaReimp; Tipo: Char; TipoNom: String; implementation uses BuscarOperacion; {$R *.dfm} procedure TFAnulaReimp.BitBtn1Click(Sender: TObject); begin OperacionDataModule := TOperacionDataModule.Create(self); try if nroEdit.Text<>'' then OperacionDataModule.AnularVTA(nroEdit.Text); finally nroEdit.Text:=''; OperacionDataModule.Free; end; Close; end; procedure TFAnulaReimp.buscarBitBtnClick(Sender: TObject); begin BuscarOperacionForm := TBuscarOperacionForm.Create(self); BuscarOperacionForm.anular := true; try BuscarOperacionForm.ShowModal; salir := BuscarOperacionForm.salir; if salir then Exit; finally if BuscarOperacionForm.TipoRadioGroup.ItemIndex=0 then begin nroEdit.Text := BuscarOperacionForm.Codigo; BitBtn1.Click; end else ShowMessage('Solo se pueden anular Facturas!!!'); BuscarOperacionForm.Free; end; Close; end; procedure TFAnulaReimp.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_Escape then Close; end; procedure TFAnulaReimp.FormShow(Sender: TObject); begin buscarBitBtn.Click; if salir then PostMessage(Self.Handle, WM_CLOSE, 0, 0); end; procedure TFAnulaReimp.BitBtn2Click(Sender: TObject); { var Balance, PagosRec, BalanceTotal, BalanceAnterior, MontoSinAplicar, MontoAplicado, Total: double; NombCliente, fecha, Cliente, SinAplicar :string; Numtrans, OrdTrans : Integer; } begin { If cbTipo.ItemIndex = 0 then begin Tipo:= 'F'; TipoNom := 'Factura'; end else begin Tipo := 'C'; TipoNom := 'Consignacin'; end; // Verificar que la factura Exista y que no est anulada Q.SQL.Text := 'Select CODIGO, ANULADA, FECHA From FACTURA Where CODIGO = '+IntEdit1.Text+' and LETRA = '+QuotedStr(LetraLabel.Caption); Q.Open; IF Q.RecordCount = 0 then begin MessageDlg(TipoNom+' no existe.',mtError,[mbOK],0); Q.Close; Exit; end; if Q.Fields[1].AsString ='S' then begin MessageDlg(TipoNom+' ya est anulada.',mtError,[mbOK],0); Q.Close; Exit; end; ShortDateFormat := 'mm'; If (DateToStr(Now) <> DateToStr(Q.Fields[2].AsDateTime)) AND (Tipo = 'F') then begin MessageDlg(TipoNom+' no se puede anular por ser de un periodo anterior',mtError,[mbOK],0); ShortDateFormat := 'dd/mm/yyyy'; Q.Close; Exit; end; ShortDateFormat := 'dd/mm/yyyy'; Q.Close; If Tipo = 'F' then begin Q.SQL.Text := 'SELECT CxCobrar.PagosRec '+ 'FROM CxCobrar '+ 'WHERE (((CxCobrar.CodTransac)= '+IntEdit1.Text+') AND ((CxCobrar.Secuencia)=0) AND ((CxCobrar.TipoTransac)="FA")) '; Q.Open; If Q.Fields[0].AsInteger <> 0 then begin MessageDlg(TipoNom+' no se puede anular debido a que ya hay pagos realizados.',mtError,[mbOK],0); Q.Close; Exit; end; end; if MessageDlg('Est seguro que desea eliminar la '+TipoNom+' '+IntEdit1.Text+'?',mtConfirmation,[mbYes,mbNo],0) = mrYes then begin Q.Close; // Marcar la Factura como anulada y poner los saldos en cero Q.SQL.Text := 'Update VENTA set ANULADA = S, MntEnvio = 0, MntSubTotal = 0, MntImpuesto = 0, MntTotal = 0, MntDescuento = 0, '+ 'MntContado = 0, MntCheque = 0, MntTarjeta = 0, MntOtros = 0, Saldo = 0, Pagado = 0 where CodFactura = '+IntEdit1.Text; Q.ExecSQL; // Poner las series en estado "bodega" If Tipo = 'F' then begin Q.SQL.Text := 'Update Series Set Estado = ''Bodega'' Where '+ 'NumFactura = '+IntEdit1.Text+' and estado = ''Facturado''' end else begin Q.SQL.Text := 'Update Series Set Estado = ''Bodega'' Where '+ 'NumFactura = '+IntEdit1.Text+' and estado = ''Consignac''' end; Q.ExecSQL; // Actualizar la cantidad disponible en la tabla de Articulos Q.SQL.Text := 'SELECT ARTICULO, CANTIDAD FROM "VentaItem" WHERE OPERACION = '+IntEdit1.Text; Q.Open; While not Q.Eof do begin Q.SQL.Text := 'Update Articulo Set Disponible = Disponible + '+Q.Fields[1].AsString+' Where '+ 'ARTICULO = '+Q.Fields[0].AsString; Q.ExecSQL; Q.Next; end; Q.Close; // Borrar los Items de la factura de la tabla "VentaItem" Q.SQL.Text := 'DELETE FROM "VentaItem" WHERE "VentaItem".OPERACION='+IntEdit1.Text; Q.ExecSQL; // Borrar la factura Q.SQL.Text := 'DELETE FROM Factura '+ 'WHERE CodFactura='+IntEdit1.Text; Q.ExecSQL; //Calcula el siguiente numero de transaccin Q.SQL.Text := 'SELECT Max(CxCobrar.CodTransac) AS MaxOfCodTransac '+ 'FROM CxCobrar '+ 'GROUP BY CxCobrar.Secuencia, CxCobrar.TipoTransac '+ 'HAVING ((CxCobrar.Secuencia=0) AND (CxCobrar.TipoTransac="NC"))'; Q.Active := True; If Q.RecordCount = 0 then NumTrans:=1 else NumTrans := Q.Fields[0].AsInteger+1; Q.Close; //Calcula el siguiente numero de OrdTrans Q.SQL.Text := 'SELECT Max([OrdTrans]) AS Expr1 '+ 'FROM CxCobrar;'; Q.Active := True; If Q.RecordCount = 0 then OrdTrans:=1 else OrdTrans := Q.Fields[0].AsInteger+1; Q.Close; //Calcula la fecha de Transaccion ShortDateFormat := 'yyyy-mm-dd'; Fecha := DateToStr(Now); ShortDateFormat := 'dd/mm/yyyy'; //Calcula el saldo anterior Q.SQL.Text := 'Select BalanceTotal From CxCobrar where CodCliente = '+Cliente+ ' Order By OrdTrans;'; Q.Open; IF Q.RecordCount = 0 then BalanceAnterior := 0 else begin Q.Last; BalanceAnterior := Q.Fields[0].AsFloat; end; Q.Close; BalanceTotal := BalanceAnterior - Total; MontoSinAplicar := Total + PagosRec - Balance; MontoAplicado := Total - MontoSinAplicar; If MontoSinAplicar = 0 then SinAplicar := 'False' else SinAplicar := 'True'; //Insertar la nota de credito Q.SQL.Text := 'INSERT INTO CxCobrar ( CodTransac, Secuencia, TipoTransac, OrdTrans, FechaTransac, CodCliente, Balance, BalanceTotal, BalanceAnterior, SinAplicar, MontoSinAplicar, Motivo ) '+ 'VALUES ( '+IntToStr(NumTrans)+', 0, ''NC'', '+IntToStr(OrdTrans)+', '+QuotedStr(Fecha)+', '+Cliente+', '+QuotedStr(FloatToStr(-Total))+', '+QuotedStr(FloatToStr(BalanceTotal))+', '+QuotedStr(FloatToStr(BalanceAnterior))+', '+SinAplicar+', '+QuotedStr(FloatToStr(MontoSinAplicar))+', '+QuotedStr('Anulacin de factura '+IntEdit1.Text)+' )'; Q.ExecSQL; //Inserta el detalle de la nota de crdito Q.SQL.Text := 'INSERT INTO CxCDetalle ( CodTransac, Secuencia, TipoTransac, Documento, Monto ) '+ 'VALUES ( '+IntToStr(NumTrans)+', 0, ''NC'', '+IntEdit1.Text+', '+QuotedStr(FloatToStr(MontoAplicado))+' )'; Q.ExecSQL; //Genera e imprime Nota de Credito Q.SQL.Text := 'Select NombreCliente from Clientes Where CodCliente = '+cliente; Q.Open; NombCliente:= Q.Fields[0].AsString; Q.Close; end; //Completa la Transaccion Q.Transaction.Commit; MessageDlg('La '+TipoNom+' '+IntEdit1.Text+' ha sido eliminada.'#13'Las partes retornaron al inventario',mtConfirmation,[mbOK],0) end; Close; } end; procedure TFAnulaReimp.NoBitBtnClick(Sender: TObject); begin FAnulaReimp.Close; end; end.
30.992248
343
0.66921
fcc0c48008181428667730c247b44f8d08605187
1,721
pas
Pascal
library/base/FHIR.Base.Validator.pas
niaz819/fhirserver
fee45e1e57053a776b893dba543f700dd9cb9075
[ "BSD-3-Clause" ]
null
null
null
library/base/FHIR.Base.Validator.pas
niaz819/fhirserver
fee45e1e57053a776b893dba543f700dd9cb9075
[ "BSD-3-Clause" ]
null
null
null
library/base/FHIR.Base.Validator.pas
niaz819/fhirserver
fee45e1e57053a776b893dba543f700dd9cb9075
[ "BSD-3-Clause" ]
null
null
null
unit FHIR.Base.Validator; { Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } interface uses FHIR.Support.Base, FHIR.Support.Stream, FHIR.Base.Objects, FHIR.Base.Common; implementation end.
40.97619
97
0.788495
fcfe163db815bf35ae2634fac22064a4d150c768
318
pas
Pascal
Server/USMPai.pas
gabrielthinassi/VENDAS_DS
6ca57ed2cee6439b9bbe926bdaa7d1cfaade8fca
[ "MIT" ]
null
null
null
Server/USMPai.pas
gabrielthinassi/VENDAS_DS
6ca57ed2cee6439b9bbe926bdaa7d1cfaade8fca
[ "MIT" ]
null
null
null
Server/USMPai.pas
gabrielthinassi/VENDAS_DS
6ca57ed2cee6439b9bbe926bdaa7d1cfaade8fca
[ "MIT" ]
null
null
null
unit USMPai; interface uses System.SysUtils, System.Classes, System.Json, DataSnap.DSProviderDataModuleAdapter, Datasnap.DSServer, Datasnap.DSAuth; type TSMPai = class(TDSServerModule) private { Private declarations } public { Public declarations } end; implementation {$R *.dfm} end.
12.72
50
0.720126
c31f0debb2c57acf89c99f7165d44b24f814eecd
1,044
pas
Pascal
windows/src/ext/jedi/jcl/jcl/examples/windows/clr/ClrDemoGuidForm.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
219
2017-06-21T03:37:03.000Z
2022-03-27T12:09:28.000Z
windows/src/ext/jedi/jcl/jcl/examples/windows/clr/ClrDemoGuidForm.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
4,451
2017-05-29T02:52:06.000Z
2022-03-31T23:53:23.000Z
windows/src/ext/jedi/jcl/jcl/examples/windows/clr/ClrDemoGuidForm.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
72
2017-05-26T04:08:37.000Z
2022-03-03T10:26:20.000Z
unit ClrDemoGuidForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, Buttons, JclCLR; type TfrmGuid = class(TForm) btnOK: TBitBtn; lstGuids: TListView; procedure lstGuidsData(Sender: TObject; Item: TListItem); private FStream: TJclCLRGuidStream; procedure ShowGuids(const AStream: TJclCLRGuidStream); public class procedure Execute(const AStream: TJclCLRGuidStream); end; implementation {$R *.DFM} uses ComObj; { TfrmGuid } class procedure TfrmGuid.Execute(const AStream: TJclCLRGuidStream); begin with TfrmGuid.Create(nil) do try ShowGuids(AStream); ShowModal; finally Free; end; end; procedure TfrmGuid.ShowGuids(const AStream: TJclCLRGuidStream); begin FStream := AStream; lstGuids.Items.Count := FStream.GuidCount; end; procedure TfrmGuid.lstGuidsData(Sender: TObject; Item: TListItem); begin Item.Caption := IntToStr(Item.Index); Item.SubItems.Add(GUIDToString(FStream.Guids[Item.Index])); end; end.
19.333333
75
0.741379
471e0a3c8933de55a73e11b74fe485adddb7877e
2,118
dfm
Pascal
Chapter04/Flyweight/FlyweightMain.dfm
PacktPublishing/Hands-On-Design-Patterns-with-Delphi
30f6ab51e61d583f822be4918f4b088e2255cd82
[ "MIT" ]
38
2019-02-28T06:22:52.000Z
2022-03-16T12:30:43.000Z
Chapter04/Flyweight/FlyweightMain.dfm
alefragnani/Hands-On-Design-Patterns-with-Delphi
3d29e5b2ce9e99e809a6a9a178c3f5e549a8a03d
[ "MIT" ]
null
null
null
Chapter04/Flyweight/FlyweightMain.dfm
alefragnani/Hands-On-Design-Patterns-with-Delphi
3d29e5b2ce9e99e809a6a9a178c3f5e549a8a03d
[ "MIT" ]
18
2019-03-29T08:36:14.000Z
2022-03-30T00:31:28.000Z
object frmFlyweight: TfrmFlyweight Left = 0 Top = 0 Caption = 'Flyweight pattern' ClientHeight = 316 ClientWidth = 752 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Tahoma' Font.Style = [] OldCreateOrder = False OnCreate = FormCreate OnDestroy = FormDestroy DesignSize = ( 752 316) PixelsPerInch = 96 TextHeight = 13 object lblCustomers: TLabel Left = 264 Top = 8 Width = 51 Height = 13 Caption = 'Customers' end object lblSelected: TLabel Left = 464 Top = 8 Width = 88 Height = 13 Caption = 'Selected customer' end object lbCustomers: TListBox Left = 264 Top = 27 Width = 185 Height = 270 Anchors = [akLeft, akTop, akBottom] ItemHeight = 13 TabOrder = 3 OnClick = lbCustomersClick end object grpPersonal: TGroupBox Left = 16 Top = 21 Width = 233 Height = 105 Caption = 'Personal data ' TabOrder = 0 object inpPersName: TEdit Left = 16 Top = 32 Width = 201 Height = 21 TabOrder = 0 TextHint = 'name' end object inpPersAddr: TEdit Left = 16 Top = 64 Width = 201 Height = 21 TabOrder = 1 TextHint = 'address' end end object grpCompanyData: TGroupBox Left = 16 Top = 132 Width = 233 Height = 105 Caption = 'Company data' TabOrder = 1 object inpCompAddr: TEdit Left = 16 Top = 64 Width = 201 Height = 21 TabOrder = 1 TextHint = 'address' end object inpCompName: TEdit Left = 16 Top = 32 Width = 201 Height = 21 TabOrder = 0 TextHint = 'name' end end object bnAddCustomer: TButton Left = 16 Top = 243 Width = 233 Height = 54 Caption = 'Add customer' TabOrder = 2 OnClick = bnAddCustomerClick end object lbSelected: TListBox Left = 464 Top = 27 Width = 268 Height = 270 Anchors = [akLeft, akTop, akRight] ItemHeight = 13 TabOrder = 4 end end
18.910714
39
0.587347
47ddfcee915c68fdb7e5f07f8198a08e8d69ddd5
4,588
pas
Pascal
printing/0038.pas
nickelsworth/swag
7c21c0da2291fc249b9dc5cfe121a7672a4ffc08
[ "BSD-2-Clause" ]
11
2015-12-12T05:13:15.000Z
2020-10-14T13:32:08.000Z
printing/0038.pas
nickelsworth/swag
7c21c0da2291fc249b9dc5cfe121a7672a4ffc08
[ "BSD-2-Clause" ]
null
null
null
printing/0038.pas
nickelsworth/swag
7c21c0da2291fc249b9dc5cfe121a7672a4ffc08
[ "BSD-2-Clause" ]
8
2017-05-05T05:24:01.000Z
2021-07-03T20:30:09.000Z
{ From: randyd@alpha2.csd.uwm.edu (Randall Elton Ding) >How do you get an Epson-compatible 24-pin printer to print graphics? >Printing text is simple... just open the appropriate LPT port and >redirect text into it. > >I suppose if I had a manual for the printer I could find out what any of >the escape codes are. Here is a routine I wrote years ago for my old Epson MX-100 (made in early 80's) You should get some ideas from this program, it may even be capable of being modified to work with your printer. I don't know if the escape codes are the same, you'll have to look them up. BTW, this printer is a 9 pin and only 8 are used. Thats convenient because each print head pass generates 8 pixils high per character sent. I don't know how your 24 pin works. } program develop; { developed for Epson MX-100 and EGA screen } uses graph; const rotate90= true; widepaper= false; bgipath: string = 'e:\bp\bgi'; procedure initbgi; var errcode,grdriver,grmode: integer; begin grdriver := Detect; initgraph(grdriver,grmode,bgipath); errcode:= graphresult; if errcode <> grok then begin writeln('Graphics error: ',grapherrormsg (errcode)); halt(1); end; end; procedure developgraph(rotate: boolean); { if passed parameter is true, the graphics image will be rotated 90 degrees to fit on a narrow sheet of printer paper, if false the image will completely fill the wide paper erect and double height } const maxprinter = 816; { maximum width of printer } var graphwidth,graphheight,printerwidth,printerheight: integer; n1,n2,sx,sy,x,y,y2,pixcolr: integer; widthratio,heightratio: real; blank: boolean; bitloc,bits: byte; bytes: array [1..maxprinter] of byte; lst: text; begin assign(lst,'lpt1'); rewrite(lst); case rotate of widepaper: begin { develop erect on wide paper } graphwidth:= getmaxx+1; graphheight:= getmaxy+1; printerwidth:= maxprinter; { scale 1.275 x 2 } printerheight:= graphheight*2; end; rotate90: begin { if rotate then reverse x and y } graphwidth:= getmaxy+1; graphheight:= getmaxx+1; printerwidth:= graphwidth; { scale 1 x 1 } printerheight:= graphheight; end; end; n2:= printerwidth div 256; n1:= printerwidth mod 256; write(lst,chr(27),'A',chr(8)); { set line spacing to 8 } widthratio:= printerwidth/graphwidth; heightratio:= printerheight/graphheight; y:= 0; while y < printerheight do begin blank:= true; { remains true if entire printer pass is blank } for x:= 1 to printerwidth do begin sx:= trunc((x-1)/widthratio); { screen x coorid } bits:= 0; bitloc:= $80; for y2:= y to y+7 do begin sy:= trunc(y2/heightratio); { screen y coorid } if sy < graphheight then begin { last printer pass is incomplete } case rotate of widepaper: pixcolr:= getpixel(sx,sy); rotate90: pixcolr:= getpixel(sy,sx); { x and y swaped } end; if pixcolr > 0 then bits:= bits or bitloc; end; bitloc:= bitloc shr 1; end; case rotate of widepaper: bytes[x]:= bits; rotate90: bytes[printerwidth-x+1]:= bits; { reverse image } end; if bits > 0 then blank:= false; { have something to print this pass } end; if not blank then begin { line feed if nothing to print this pass } write (lst,chr(27),'K',chr(n1),chr(n2)); { set printer graph mode } for x:= 1 to printerwidth do write (lst,chr(bytes[x])); end; writeln(lst); { output 8 printer pixels high per pass } y:= y+8; end; write(lst,chr(12)); { top of form } write(lst,chr(27),'@'); { re-initalize printer } close(lst); end; begin initbgi; { your graphics code here } Line(100,100,200,100); Line(200,100,200,100); Line(100,200,200,100); Line(100,100,200,200); SetColor(Blue); Circle(300,200,50); developgraph(rotate90); { or use (widepaper) } end. 
33.246377
78
0.575196
c312b83644876c3c45aaaf1f15af024cfa800093
6,523
pas
Pascal
Components/FileUtils.pas
ricardojr01/mathparser
549e897aad33517bcf1d9fdfbfbcb2720304fb63
[ "Apache-2.0" ]
8
2019-09-26T02:28:30.000Z
2022-01-02T17:36:50.000Z
Components/FileUtils.pas
ricardojr01/mathparser
549e897aad33517bcf1d9fdfbfbcb2720304fb63
[ "Apache-2.0" ]
2
2020-10-28T15:29:22.000Z
2021-01-31T13:28:36.000Z
Components/FileUtils.pas
ricardojr01/mathparser
549e897aad33517bcf1d9fdfbfbcb2720304fb63
[ "Apache-2.0" ]
3
2020-10-25T09:46:58.000Z
2021-02-02T03:02:07.000Z
{ *********************************************************************** } { } { FileUtils } { } { Copyright (c) 2006 Pisarev Yuriy (post@pisarev.net) } { } { *********************************************************************** } unit FileUtils; {$B-} {$I Directives.inc} interface uses {$IFDEF DELPHI_XE7}WinApi.Windows, {$ELSE}Windows, {$ENDIF}SysUtils, Classes, Types; type TOpenType = (otCreate, otOpen, otRewrite); TFiles = array of ^TextFile; function CheckIndex(const Index: Integer): Boolean; function CreateFile: Integer; function DisposeFile(const Index: Integer): Boolean; function RemoveFile(const Index: Integer): Boolean; procedure RemoveAll; function ForceFile(const FileName: string): Boolean; function ForceDirectories(const FileName: string): Boolean; function DeleteFile(const FileName: string): Boolean; procedure DeleteDirectory(const Path: string); function OpenFile(const FileName: string; OpenType: TOpenType): Boolean; function SaveFile: Boolean; function CloseFile: Boolean; function EmptyFile: Boolean; function FileSize: Integer; function ExactFileSize(const FileName: string): Integer; function Write(const S: string): Boolean; overload; function Write(const StringArray: TStringDynArray): Boolean; overload; function WriteFile(const FileName: string): Boolean; var Files: TFiles; threadvar FileIndex: Integer; implementation uses MemoryUtils, SearchUtils; function CheckIndex(const Index: Integer): Boolean; begin Result := (Index >= 0) and (Index < Length(Files)); end; function CreateFile: Integer; var I: Integer; begin Result := -1; for I := Low(Files) to High(Files) do if not Assigned(Files[I]) then begin Result := I; Break; end; if Result < 0 then begin Result := Length(Files); SetLength(Files, Result + 1); end; New(Files[Result]); end; function DisposeFile(const Index: Integer): Boolean; begin Result := CheckIndex(Index) and Assigned(Files[Index]); if Result then begin {$I-} System.CloseFile(Files[Index]^); {$I+} Result := IOResult = 0; if Result then begin Dispose(Files[Index]); Files[Index] := nil; end; end; end; function RemoveFile(const Index: Integer): Boolean; var I: Integer; begin Result := CheckIndex(Index); if Result then begin DisposeFile(Index); I := Length(Files); Result := Delete(Files, Index * SizeOf(Pointer), SizeOf(Pointer), I * SizeOf(Pointer)); if Result then SetLength(Files, I - 1); end; end; procedure RemoveAll; var I: Integer; begin for I := Low(Files) to High(Files) do DisposeFile(I); Files := nil; end; function ForceFile(const FileName: string): Boolean; var F: TextFile; begin Result := Trim(FileName) <> ''; if Result then begin AssignFile(F, FileName); {$I-} Append(F); if IOResult <> 0 then begin ForceDirectories(FileName); Rewrite(F); end; {$I+} Result := IOResult = 0; if Result then System.CloseFile(F); end; end; function ForceDirectories(const FileName: string): Boolean; var FilePath: string; begin FilePath := ExtractFilePath(FileName); Result := (FilePath <> '') and SysUtils.ForceDirectories(FilePath); end; function DeleteFile(const FileName: string): Boolean; begin SetFileAttributes(PChar(FileName), 0); Result := {$IFDEF DELPHI_XE7}WinApi.Windows{$ELSE}Windows{$ENDIF}.DeleteFile(PChar(FileName)); end; procedure DeleteDirectory(const Path: string); var FileList, PathList: TStringList; I: Integer; begin FileList := TStringList.Create; try PathList := TStringList.Create; try Search(Path, FileList, PathList, True); for I := 0 to FileList.Count - 1 do DeleteFile(FileList[I]); for I := 0 to PathList.Count - 1 do begin SetFileAttributes(PChar(PathList[I]), 0); RemoveDirectory(PChar(PathList[I])); end; finally PathList.Free; end; finally FileList.Free; end; end; function OpenFile(const FileName: string; OpenType: TOpenType): Boolean; begin AssignFile(Files[FileIndex]^, FileName); {$I-} case OpenType of otCreate: begin Append(Files[FileIndex]^); if IOResult <> 0 then begin ForceDirectories(FileName); Rewrite(Files[FileIndex]^); end; end; otOpen: Append(Files[FileIndex]^); otRewrite: begin ForceDirectories(FileName); Rewrite(Files[FileIndex]^); end; end; {$I+} Result := IOResult = 0; end; function SaveFile: Boolean; begin {$I-} Flush(Files[FileIndex]^); {$I+} Result := IOResult = 0; end; function CloseFile: Boolean; begin {$I-} System.CloseFile(Files[FileIndex]^); {$I+} Result := IOResult = 0; end; function EmptyFile: Boolean; begin {$I-} Rewrite(Files[FileIndex]^); {$I+} Result := IOResult = 0; end; function FileSize: Integer; begin {$I-} Result := System.FileSize(Files[FileIndex]^); {$I+} if IOResult <> 0 then Result := -1; end; function ExactFileSize(const FileName: string): Integer; var Handle: THandle; begin Handle := {$IFDEF DELPHI_XE7}WinApi.Windows{$ELSE}Windows{$ENDIF}.CreateFile(PChar(FileName), GENERIC_READ, FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if Handle = INVALID_HANDLE_VALUE then Result := -1 else try Result := GetFileSize(Handle, nil); finally CloseHandle(Handle); end; end; function Write(const S: string): Boolean; begin {$I-} WriteLn(Files[FileIndex]^, S); {$I+} Result := IOResult = 0; end; function Write(const StringArray: TStringDynArray): Boolean; var I: Integer; begin for I := Low(StringArray) to High(StringArray) do begin Result := Write(StringArray[I]); if not Result then Exit; end; Result := True; end; function WriteFile(const FileName: string): Boolean; var F: TextFile; S: string; begin AssignFile(F, FileName); {$I-} Reset(F); {$I+} Result := IOResult = 0; if Result then try while not Eof(F) do begin ReadLn(F, S); WriteLn(Files[FileIndex]^, S); end; finally System.CloseFile(F); end; end; initialization finalization RemoveAll; end.
22.037162
109
0.626859
47cfe7f13b06a07e19b9d1f38f2d149f1db77862
19,094
pas
Pascal
exereader.pas
reddor/emr
b623a0f95bc8aafc16e5f046d67a6ab1086b9540
[ "Unlicense" ]
13
2017-07-09T21:26:26.000Z
2021-08-07T17:40:56.000Z
exereader.pas
reddor/emr
b623a0f95bc8aafc16e5f046d67a6ab1086b9540
[ "Unlicense" ]
1
2019-03-18T11:37:32.000Z
2019-03-29T08:40:18.000Z
exereader.pas
reddor/emr
b623a0f95bc8aafc16e5f046d67a6ab1086b9540
[ "Unlicense" ]
1
2017-08-29T01:17:49.000Z
2017-08-29T01:17:49.000Z
unit exereader; {$mode objfpc}{$H+} interface uses SysUtils, Math, dosheader; type TExeFileKind = ( fkUnknown, fkDOS, fkExe16, fkExe32, fkExe64, fkExeArm, fkDll16, fkDll32, fkDll64, fkDllArm, fkVXD ); PLongword = ^Longword; TExeFile = class; TImportFuncEntry = record case IsOrdinal: Boolean of true: ( Ordinal: Word; ); false: ( Hint: Word; Name: PAnsiChar; ); end; { TExeImportDLL } TExeImportDLL = class private FHandle: THandle; FParent: TExeFile; FDLLName: PChar; FDescriptor: PIMAGE_IMPORT_DESCRIPTOR; FEntries: array of TImportFuncEntry; function GetCount: Integer; function GetDLLName: string; function GetEntry(Index: Integer): TImportFuncEntry; public constructor Create(AParent: TExeFile; DLL: PIMAGE_IMPORT_DESCRIPTOR); function Read: Boolean; function Read64: Boolean; property Descriptor: PIMAGE_IMPORT_DESCRIPTOR read FDescriptor; property DLLName: string read GetDLLName; property Count: Integer read GetCount; property Entries[Index: Integer]: TImportFuncEntry read GetEntry; property Handle: THandle read FHandle write FHandle; end; TExeExportFunc = record Name: PChar; Ordinal: Word; EntryPoint: longword; end; TDWordArray = array[0..0] of DWord; PDWordArray = ^TDWordArray; TExeRelocTable = record VirtualAddress: UInt64; Count: Integer; Items: PWordarray; end; { TExeFile } TExeFile = class private FDataSize: longword; FData: PByteArray; FDOSHeader: PIMAGE_DOS_HEADER; FNTHeaders64: PIMAGE_NT_HEADERS64; FNTHeaders: PIMAGE_NT_HEADERS; FSections: array of PIMAGE_SECTION_HEADER; FImports: array of TExeImportDLL; FExports: array of TExeExportFunc; FRelocations: array of TExeRelocTable; FDOSFileSize: longword; FStatus: string; FExportName: PChar; FFileType: TExeFileKind; function GetExport(Index: Integer): TExeExportFunc; function GetExportCount: Integer; function GetImport(Index: Integer): TExeImportDLL; function GetImportCount: Integer; function GetRelocation(Index: Integer): TExeRelocTable; function GetRelocationCount: Integer; function GetSection(Index: Integer): PIMAGE_SECTION_HEADER; function GetSectionCount: Integer; protected function ResolveVirtualAddress32(VirtualAddress: UInt64): UInt64; procedure ReadImports(VirtualAddress: UInt64; is64Bit: Boolean); procedure ReadExports(VirtualAddress: UInt64); procedure ReadRelocations(VirtualAddress: UInt64); function ReadDOSHeader: Boolean; function ReadWin32Header: Boolean; function ReadWin64Header: Boolean; public constructor Create; destructor Destroy; override; procedure Clear; function LoadFile(aFilename: string; ReadFull: Boolean = True): Boolean; function GetRawAddress(Address: UInt64): Pointer; function GetVirtualAddress(VirtualAddress: UInt64): Pointer; function IsValidVirtualAddress(VirtualAddress: UInt64): Boolean; property Status: string read FStatus; property FileType: TExeFileKind read FFileType; property DOSHeader: PIMAGE_DOS_HEADER read FDOSHeader; property NTHeader: PIMAGE_NT_HEADERS read FNTHeaders; property NTHeader64: PIMAGE_NT_HEADERS64 read FNTHeaders64; property SectionCount: Integer read GetSectionCount; property Sections[Index: Integer]: PIMAGE_SECTION_HEADER read GetSection; property ImportCount: Integer read GetImportCount; property Imports[Index: Integer]: TExeImportDLL read GetImport; property ExportName: PChar read FExportName; property ExportCount: Integer read GetExportCount; property ExportFuncs[Index: Integer]: TExeExportFunc read GetExport; property RelocationCount: Integer read GetRelocationCount; property Relocations[Index: Integer]: TExeRelocTable read GetRelocation; end; implementation { TExeImportDLL } function TExeImportDLL.GetDLLName: string; begin result:=FDLLName; end; function TExeImportDLL.GetCount: Integer; begin result:=Length(FEntries); end; function TExeImportDLL.GetEntry(Index: Integer): TImportFuncEntry; begin if(Index>=0)and(Index<Length(FEntries)) then result:=FEntries[Index] else begin result.IsOrdinal:=False; result.Hint:=0; result.Name:=nil; end; end; constructor TExeImportDLL.Create(AParent: TExeFile; DLL: PIMAGE_IMPORT_DESCRIPTOR); begin FParent:=AParent; FDescriptor:=DLL; end; function TExeImportDLL.Read: Boolean; var p: Pointer; ThunkData: PIMAGE_IMPORT_BY_NAME; ThunkRef: PDWord; ACount: Integer; begin result:=False; if FDescriptor^.Name = 0 then raise Exception.Create('Invalid Image Import Descriptor!'); try FDLLName:=PChar(FParent.GetVirtualAddress(FDescriptor^.Name)); except result:=False; Exit; end; if FDescriptor^.OriginalFirstThunk <> 0 then p := FParent.GetVirtualAddress(FDescriptor^.OriginalFirstThunk) else p := FParent.GetVirtualAddress(FDescriptor^.FirstThunk); ACount:=0; ThunkRef:=p; while ThunkRef^ <> 0 do begin Inc(ACount); Inc(ThunkRef); end; Setlength(FEntries, ACount); ThunkRef:=p; ACount:=0; while ThunkRef^ <> 0 do begin if (ThunkRef^ and IMAGE_ORDINAL_FLAG32 = IMAGE_ORDINAL_FLAG32) then begin FEntries[ACount].IsOrdinal:=True; FEntries[ACount].Ordinal:=ThunkRef^ and $FFFF; end else begin FEntries[ACount].IsOrdinal:=False; ThunkData:=FParent.GetVirtualAddress(ThunkRef^); FEntries[ACount].Name:=PChar(@ThunkData^.Name[0]); FEntries[ACount].Hint:=ThunkData^.Hint; end; Inc(ACount); Inc(ThunkRef); end; result:=True; end; function TExeImportDLL.Read64: Boolean; var p: Pointer; ThunkData: PIMAGE_IMPORT_BY_NAME; ThunkRef: PQWord; ACount: Integer; begin result:=False; if FDescriptor^.Name = 0 then //raise Exception.Create('Invalid Image Import Descriptor!'); Exit; FDLLName:=PChar(FParent.GetVirtualAddress(FDescriptor^.Name)); if FDescriptor^.OriginalFirstThunk <> 0 then p := FParent.GetVirtualAddress(FDescriptor^.OriginalFirstThunk) else p := FParent.GetVirtualAddress(FDescriptor^.FirstThunk); ACount:=0; ThunkRef:=p; while ThunkRef^ <> 0 do begin Inc(ACount); Inc(ThunkRef); end; Setlength(FEntries, ACount); ThunkRef:=p; ACount:=0; while ThunkRef^ <> 0 do begin if (ThunkRef^ and IMAGE_ORDINAL_FLAG64 = IMAGE_ORDINAL_FLAG64) then begin FEntries[ACount].IsOrdinal:=True; FEntries[ACount].Ordinal:=ThunkRef^ and $FFFFFFFF; end else begin FEntries[ACount].IsOrdinal:=False; ThunkData:=FParent.GetVirtualAddress(ThunkRef^); FEntries[ACount].Name:=PChar(@ThunkData^.Name[0]); FEntries[ACount].Hint:=ThunkData^.Hint; end; Inc(ACount); Inc(ThunkRef); end; result:=True; end; { TExeFile } function TExeFile.GetSection(Index: Integer): PIMAGE_SECTION_HEADER; begin if (Index>=0)and(Index<Length(FSections)) then result:=FSections[Index] else result:=nil; end; function TExeFile.GetImport(Index: Integer): TExeImportDLL; begin if (Index>=0)and(Index<Length(FImports)) then result:=FImports[Index] else result:=nil; end; function TExeFile.GetExport(Index: Integer): TExeExportFunc; begin if(Index>=0)and(Index<Length(FExports)) then result:=FExports[Index] else begin result.EntryPoint:=0; result.Name:=nil; result.Ordinal:=0; end; end; function TExeFile.GetExportCount: Integer; begin result:=Length(FExports); end; function TExeFile.GetImportCount: Integer; begin result:=Length(FImports); end; function TExeFile.GetRelocation(Index: Integer): TExeRelocTable; begin if (Index>=0)and(Index<Length(FRelocations)) then result:=FRelocations[Index] else begin result.Count:=0; result.Items:=nil; result.VirtualAddress:=0; end; end; function TExeFile.GetRelocationCount: Integer; begin result:=Length(FRelocations); end; function TExeFile.GetSectionCount: Integer; begin result:=Length(FSections); end; function TExeFile.IsValidVirtualAddress(VirtualAddress: UInt64): Boolean; var i: Integer; begin result:=False; if VirtualAddress = 0 then Exit; for i:=0 to Length(FSections)-1 do if (VirtualAddress >= FSections[i]^.VirtualAddress) and (VirtualAddress < FSections[i]^.VirtualAddress + UInt64(FSections[i]^.PhysicalAddress)) // PhysicalAddress == VirtualSize! then begin result:= ((VirtualAddress - FSections[i]^.VirtualAddress) + FSections[i]^.PointerToRawData) < FDataSize; Exit; end; if VirtualAddress<FDataSize then result:=True; end; function TExeFile.ResolveVirtualAddress32(VirtualAddress: UInt64): UInt64; var i: Integer; begin result:=0; if VirtualAddress = 0 then Exit; for i:=0 to Length(FSections)-1 do if (VirtualAddress >= FSections[i]^.VirtualAddress) and (VirtualAddress < UInt64(FSections[i]^.VirtualAddress) + UInt64(FSections[i]^.PhysicalAddress)) // PhysicalAddress == VirtualSize! then begin result:= ((VirtualAddress - FSections[i]^.VirtualAddress) + FSections[i]^.PointerToRawData); if result>=FDataSize then raise Exception.Create('Virtual address out of bounds'); Exit; end; // not sure if this is right behaviour, but it'srequired for some versions // of kkrunchy result:=VirtualAddress; if result>=FDataSize then raise Exception.Create('Virtual address out of bounds'); end; procedure TExeFile.ReadImports(VirtualAddress: UInt64; is64Bit: Boolean); var ImportDesc: PIMAGE_IMPORT_DESCRIPTOR_ARRAY; i: Integer; begin if not IsValidVirtualAddress(VirtualAddress) then Exit; ImportDesc:=GetVirtualAddress(VirtualAddress); i:=0; while (ImportDesc^[i].Name<>0) do begin Setlength(FImports, i + 1); FImports[i]:=TExeImportDLL.Create(Self, @ImportDesc^[i]); if is64Bit then FImports[i].Read64 else FImports[i].Read; Inc(i); end; end; procedure TExeFile.ReadExports(VirtualAddress: UInt64); var ExportDesc: PIMAGE_EXPORT_DIRECTORY; expInfo: PDWord; ordInfo: PWord; addrInfo: PDWord; j: Integer; begin if not IsValidVirtualAddress(VirtualAddress) then Exit; ExportDesc:=GetVirtualAddress(VirtualAddress); if ExportDesc^.Name <> 0 then begin FExportName:=GetVirtualAddress(ExportDesc^.Name); expInfo:=GEtVirtualAddress(ExportDesc^.AddressOfNames); ordInfo:=GEtVirtualAddress(ExportDesc^.AddressOfNameOrdinals); addrInfo:=GetVirtualAddress(ExportDesc^.AddressOfFunctions); Setlength(FExports, ExportDesc^.NumberOfNames); for j:=0 to ExportDesc^.NumberOfNames -1 do begin FExports[j].Name:=GetVirtualAddress(expInfo^); FExports[j].Ordinal:=OrdInfo^; FExports[j].EntryPoint:=AddrInfo^; inc(expInfo); inc(ordInfo); inc(addrInfo); end; end; end; procedure TExeFile.ReadRelocations(VirtualAddress: UInt64); var Reloc:PIMAGE_BASE_RELOCATION; i: Integer; begin if not IsValidVirtualAddress(VirtualAddress) then Exit; reloc:=GetVirtualAddress(VirtualAddress); while reloc^.VirtualAddress>0 do begin if reloc^.SizeOfBlock>0 then begin i:=Length(FRelocations); Setlength(FRelocations, i+1); FRelocations[i].VirtualAddress:=reloc^.VirtualAddress; FRelocations[i].Count:=(reloc^.SizeOfBlock - IMAGE_SIZEOF_BASE_RELOCATION) div 2; FRelocations[i].Items:=Pointer((Reloc)+ IMAGE_SIZEOF_BASE_RELOCATION); end; reloc:=Pointer(UInt64(reloc)+reloc^.SizeOfBlock); end; end; function TExeFile.ReadDOSHeader: Boolean; var HeaderOFfset: longword; NEFlags: Byte; begin FStatus:='Invalid file'; FFileType:=fkUnknown; result:=False; if not Assigned(FData) then Exit; if FDataSize<SizeOf(IMAGE_DOS_HEADER) then Exit; FDOSHeader:=@FData[0]; if FDOSHeader^.e_magic <> cDOSMagic then begin FStatus:='Not an executable file'; Exit; end; // DOS files have length >= size indicated at offset $02 and $04 // (offset $02 indicates length of file mod 512 and offset $04 // indicates no. of 512 pages in file) if FDOSHeader^.e_cblp = 0 then FDOSFileSize:=512 * FDOSHeader^.e_cp else FDOSFileSize:=512 * (FDOSHeader^.e_cp - 1) + FDOSHeader^.e_cblp; // DOS file relocation offset must be within DOS file size. if FDOSHeader^.e_lfarlc > FDOSFileSize then Exit; FFileType:=fkDOS; FSTatus:=''; result:=True; if FDataSize <= cWinHeaderOffset + SizeOf(LongInt) then Exit; HeaderOffset:=FDOSHeader^.e_lfanew; if FDataSize< HeaderOffset + SizeOf(IMAGE_NT_HEADERS) then Exit; FNTHeaders:=@FData^[HeaderOffset]; case FNTHeaders^.Signature of cPEMagic: begin // 32 bit/64 bit if FDataSize>=HeaderOffset + SizeOf(FNTHeaders^) then begin case FNTHeaders^.FileHeader.Machine of $01c4: begin // arm 32 bit if (FNTHeaders^.FileHeader.Characteristics and IMAGE_FILE_DLL) = IMAGE_FILE_DLL then FFileType:=fkDllArm else FFileType:=fkExeArm; end; $014c: begin // 32 bit if (FNTHeaders^.FileHeader.Characteristics and IMAGE_FILE_DLL) = IMAGE_FILE_DLL then FFileType:=fkDll32 else FFileType:=fkExe32; end; $8664: begin // 64 bit FNTHeaders64:=PIMAGE_NT_HEADERS64(FNTHeaders); FNTHeaders:=nil; if (FNTHeaders64^.FileHeader.Characteristics and IMAGE_FILE_DLL) = IMAGE_FILE_DLL then FFileType:=fkDll64 else FFileType:=fkExe64; end; else begin result:=False; FFileType:=fkUnknown; FStatus:='Unknown Machine Type '+IntToHex(FNTHeaders^.FileHeader.Machine, 4); FNTHeaders:=nil; end; end; end; end; cNEMagic: begin // 16 bit FNTHeaders:=nil; if FDataSize>=HeaderOffset + cNEAppTypeOffset + SizeOf(NEFlags) then begin NEFlags:=FData^[HeaderOffset + cNEAppTypeOffset]; if (NEFlags and cNEDLLFlag) = cNEDLLFlag then FFileType:=fkDll16 else FFileType:=fkExe16; end; Exit; end; cLEMagic: begin FNTHeaders:=nil; FFileType:=fkVXD; end; else begin FStatus:='Unknown NT Header Signature'; Exit; end; end; end; function TExeFile.ReadWin32Header: Boolean; var i: Integer; p: longword; begin result:=False; if FNTHeaders^.OptionalHeader.Magic <> $10b then begin FStatus:='OptionalHeader Magic is not Win32'; Exit; end; // read sections if FNTHeaders^.FileHeader.NumberOfSections<=96 then begin Setlength(FSections, FNTHeaders^.FileHeader.NumberOfSections); p:=FDOSHeader^.e_lfanew + SizeOf(FNTHeaders^); for i:=0 to FNTHeaders^.FileHeader.NumberOfSections-1 do begin FSections[i]:=@FData^[p]; p:=p+SizeOf(FSections[i]^); end; end else begin FStatus:='Number of sections exceeds maximum'; Exit; end; if FNTHeaders^.OptionalHeader.DataDirectory[0].VirtualAddress <> 0 then ReadExports(FNTHeaders^.OptionalHeader.DataDirectory[0].VirtualAddress); if FNTHeaders^.OptionalHeader.DataDirectory[1].VirtualAddress <> 0 then ReadImports(FNTHeaders^.OptionalHeader.DataDirectory[1].VirtualAddress, false); if FNTHeaders^.OptionalHeader.DataDirectory[5].Size >= SizeOf(IMAGE_BASE_RELOCATION) then ReadRelocations(FNTHeaders^.OptionalHeader.DataDirectory[5].VirtualAddress); result:=True; end; function TExeFile.ReadWin64Header: Boolean; var i: Integer; p: longword; begin result:=False; if FNTHeaders64^.OptionalHeader.Magic <> $20b then begin FStatus:='Not Win32/x86'; Exit; end; // read sections if FNTHeaders64^.FileHeader.NumberOfSections<=96 then begin Setlength(FSections, FNTHeaders64^.FileHeader.NumberOfSections); p:=FDOSHeader^.e_lfanew + SizeOf(FNTHeaders64^); for i:=0 to FNTHeaders64^.FileHeader.NumberOfSections-1 do begin FSections[i]:=@FData^[p]; p:=p+SizeOf(FSections[i]^); end; end else begin FStatus:='Number of sections exceeds maximum'; Exit; end; if FNTHeaders64^.OptionalHeader.DataDirectory[0].Size <> 0 then ReadExports(FNTHeaders64^.OptionalHeader.DataDirectory[0].VirtualAddress); if FNTHeaders64^.OptionalHeader.DataDirectory[1].Size <> 0 then ReadImports(FNTHeaders64^.OptionalHeader.DataDirectory[1].VirtualAddress, true); if FNTHeaders64^.OptionalHeader.DataDirectory[5].Size >= SizeOf(IMAGE_BASE_RELOCATION) then ReadRelocations(FNTHeaders64^.OptionalHeader.DataDirectory[5].VirtualAddress); result:=True; end; constructor TExeFile.Create; begin FData:=nil; end; destructor TExeFile.Destroy; begin Clear; inherited Destroy; end; function TExeFile.GetVirtualAddress(VirtualAddress: UInt64): Pointer; begin result:=@FData^[ResolveVirtualAddress32(VirtualAddress)]; end; function TExeFile.LoadFile(aFilename: string; ReadFull: Boolean): Boolean; var f: File; begin result:=False; Clear; Assignfile(f, aFilename); Filemode:=0; {$i-}reset(f,1);{$i+} if ioresult=0 then begin FDataSize := Filesize(f); if not ReadFull then FDataSize := Min(4 * 1024, FdataSize); Getmem(FData, FDataSize); Blockread(f, FData^, FDataSize); CloseFile(f); end else begin FStatus:='Could not open file'; Exit; end; result:=ReadDOSHeader; case FFileType of fkExe32, fkExeArm, fkDll32, fkDllArm: ReadWin32Header; fkExe64, fkDLL64: ReadWin64Header; end; end; function TExeFile.GetRawAddress(Address: UInt64): Pointer; begin result:=@FData^[Address]; end; procedure TExeFile.Clear; var i: Integer; begin for i:=0 to Length(FImports)-1 do FImports[i].Free; Setlength(FImports, 0); Setlength(FExports, 0); Setlength(FSections, 0); FDOSHeader:=nil; FNTHeaders:=nil; FNTHeaders64:=nil; FExportName:=nil; if Assigned(FData) then Freemem(FData); FDataSize:=0; FData:=nil; end; end.
25.123684
138
0.670944
c3384fc3e07d221391876c2add74ff4ff29094d9
9,051
pas
Pascal
2006 - Task3 {18 of 26} [k]/src/Filters.pas
retgone/cmc-cg
7e5a76992e524958353ee799092f810681a13107
[ "MIT" ]
null
null
null
2006 - Task3 {18 of 26} [k]/src/Filters.pas
retgone/cmc-cg
7e5a76992e524958353ee799092f810681a13107
[ "MIT" ]
null
null
null
2006 - Task3 {18 of 26} [k]/src/Filters.pas
retgone/cmc-cg
7e5a76992e524958353ee799092f810681a13107
[ "MIT" ]
null
null
null
// NAME: TUMAKOV KIRILL ALEKSANDROVICH, 203 // ASGN: N3 unit Filters; interface uses Graphics, Gauges, Recognition; var Gauge: TGauge; procedure MedianFilter(var Bmp:TBitmap; const R:Integer); procedure ConvertToBinary(var Bmp:TBitmap); procedure BExpand(var Bmp:TBitmap; R:Integer); procedure BShrink(var Bmp:TBitmap; R:Integer); procedure BClose(var Bmp:TBitmap; R:Integer); procedure BOpen(var Bmp:TBitmap; R:Integer); procedure AddContrast(var Bmp:TBitmap; IgnorePercent:Single); implementation uses SysUtils, Math, Forms; const MaxKernelSize=127; type TConvolution2D=record Size: Integer; Weights: array[-MaxKernelSize..MaxKernelSize, -MaxKernelSize..MaxKernelSize] of Single; end; type TConvolution1D=record Size: Integer; Weights: array[-MaxKernelSize..MaxKernelSize] of Single; end; procedure PrepareBmp(var Bmp:TBitmap; var w,h: Integer; var P:PByteArray); begin; Bmp.PixelFormat:=pf24bit; w:=Bmp.Width*3; w:=w+(4-w mod 4)mod 4; h:=Bmp.Height-1; P:=Bmp.ScanLine[Bmp.Height-1]; end; procedure GrayScale(var Bmp:TBitmap; var GrayScale:PByteArray); overload var x,y:Integer; w,h:Integer; P:PByteArray; begin; PrepareBmp(Bmp,w,h,P); GetMem(GrayScale, Bmp.Width*Bmp.Height); FillChar(GrayScale^, Bmp.Width*Bmp.Height, 0); for x:=0 to Bmp.Width-1 do for y:=0 to Bmp.Height-1 do GrayScale[Bmp.Width*y+x]:=Round(0.114*P^[(h-y)*w+x*3+0]+0.587*P^[(h-y)*w+x*3+1]+0.299*P^[(h-y)*w+x*3+2]); end; function Trim(const Min, Max, Number: Integer):Integer; overload; begin; if Number>Max then Result:=Max else if Number<Min then Result:=Min else Result:=Number; end; procedure MedianFilter(var Bmp:TBitmap; const R:Integer); var Bmp2:TBitmap; P,P2,YC:PByteArray; w,h,x,y,dx,dy,yy,xx:Integer; c:array[0..255,0..2] of Byte; Counts:array[0..255] of Integer; i, n:Integer; begin; if (Bmp=nil) or (Bmp.Width=0) or (Bmp.Height=0) or (R=0) then exit; Bmp2:=TBitmap.Create; Bmp2.Width:=Bmp.Width; Bmp2.Height:=Bmp.Height; PrepareBmp(Bmp,w,h,P); PrepareBmp(Bmp2,w,h,P2); GrayScale(Bmp, YC); Gauge.MaxValue:=Bmp.Width-1; Gauge.Progress:=0; for x:=0 to Bmp.Width-1 do begin; Gauge.Progress:=Gauge.Progress+1; Application.ProcessMessages; for y:=0 to Bmp.Height-1 do begin; FillChar(Counts,sizeof(Counts),0); for dx:=-R to R do for dy:=-R to R do begin; xx:=Trim(0,Bmp.Width-1, x+dx); yy:=Trim(0,Bmp.Height-1,y+dy); if Counts[YC[Bmp.Width*yy+xx]]=0 then begin; c[YC[Bmp.Width*yy+xx],0]:=P^[(h-yy)*w+xx*3+0]; c[YC[Bmp.Width*yy+xx],1]:=P^[(h-yy)*w+xx*3+1]; c[YC[Bmp.Width*yy+xx],2]:=P^[(h-yy)*w+xx*3+2]; Counts[YC[Bmp.Width*yy+xx]]:=1; end else Inc(Counts[YC[Bmp.Width*yy+xx]]); end; n:=0; for i:=0 to 255 do if Counts[i]<>0 then begin; n:=n+Counts[i]; if n>sqr(2*R+1) div 2 then break; end; P2^[(h-y)*w+x*3+0]:=c[i,0]; P2^[(h-y)*w+x*3+1]:=c[i,1]; P2^[(h-y)*w+x*3+2]:=c[i,2]; end; end; FreeMem(YC); Bmp.Free; Bmp:=Bmp2; Gauge.Progress:=0; end; procedure ConvertToBinary(var Bmp:TBitmap); var w,h,n1,n2,r1,r2:Integer; P:PByteArray; C1,S1,C2,S2:array[0..2] of Integer; procedure KStep; var x,y,i:Integer; begin; C1:=S1;C2:=S2; fillchar(S1,sizeof(S1),0);fillchar(S2,sizeof(S2),0);n1:=0;n2:=0; for x:=0 to Bmp.Width-1 do for y:=0 to Bmp.Height-1 do begin; if abs(P^[(h-y)*w+x*3+0]-C1[0])+abs(P^[(h-y)*w+x*3+1]-C1[1])+abs(P^[(h-y)*w+x*3+2]-C1[2])< abs(P^[(h-y)*w+x*3+0]-C2[0])+abs(P^[(h-y)*w+x*3+1]-C2[1])+abs(P^[(h-y)*w+x*3+2]-C2[2]) then begin; S1[0]:=S1[0]+P^[(h-y)*w+x*3+0]; S1[1]:=S1[1]+P^[(h-y)*w+x*3+1]; S1[2]:=S1[2]+P^[(h-y)*w+x*3+2]; Inc(n1); end else begin; S2[0]:=S2[0]+P^[(h-y)*w+x*3+0]; S2[1]:=S2[1]+P^[(h-y)*w+x*3+1]; S2[2]:=S2[2]+P^[(h-y)*w+x*3+2]; Inc(n2); end; end; for i:=0 to 2 do begin; S1[i]:=S1[i] div n1; S2[i]:=S2[i] div n2; end; end; var x,y:Integer; begin; if (Bmp=nil) or (Bmp.Width=0) or (Bmp.Height=0) then exit; PrepareBmp(Bmp,w,h,P); Gauge.MaxValue:=9; Gauge.Progress:=1; C1[0]:=255;C1[1]:=255;C1[2]:=255;C2[0]:=0;C2[1]:=0;C2[2]:=0; for x:=0 to Bmp.Width-1 do for y:=0 to Bmp.Height-1 do begin; if P^[(h-y)*w+x*3+0]<C1[0] then C1[0]:=P^[(h-y)*w+x*3+0]; if P^[(h-y)*w+x*3+1]<C1[1] then C1[1]:=P^[(h-y)*w+x*3+1]; if P^[(h-y)*w+x*3+2]<C1[2] then C1[2]:=P^[(h-y)*w+x*3+2]; if P^[(h-y)*w+x*3+0]>C2[0] then C2[0]:=P^[(h-y)*w+x*3+0]; if P^[(h-y)*w+x*3+1]>C2[1] then C2[1]:=P^[(h-y)*w+x*3+1]; if P^[(h-y)*w+x*3+2]>C2[2] then C2[2]:=P^[(h-y)*w+x*3+2]; end; S1:=C1;S2:=C2; repeat Gauge.Progress:=Gauge.Progress+1; if Gauge.Progress=8 then Gauge.MaxValue:=Gauge.MaxValue+2; Application.ProcessMessages; KStep; until (abs(C1[0]-S1[0])+abs(C1[1]-S1[1])+abs(C1[2]-S1[2])+abs(C2[0]-S2[0])+abs(C2[1]-S2[1])+abs(C2[2]-S2[2])<10); Gauge.Progress:=Gauge.MaxValue; if(n1>n2) then begin; r1:=0; r2:=255; end else begin; r1:=255; r2:=0; end; C1:=S1;C2:=S2; for x:=0 to Bmp.Width-1 do for y:=0 to Bmp.Height-1 do begin; if abs(P^[(h-y)*w+x*3+0]-C1[0])+abs(P^[(h-y)*w+x*3+1]-C1[1])+abs(P^[(h-y)*w+x*3+2]-C1[2])< abs(P^[(h-y)*w+x*3+0]-C2[0])+abs(P^[(h-y)*w+x*3+1]-C2[1])+abs(P^[(h-y)*w+x*3+2]-C2[2]) then begin; P^[(h-y)*w+x*3+0]:=r1; P^[(h-y)*w+x*3+1]:=r1; P^[(h-y)*w+x*3+2]:=r1; end else begin; P^[(h-y)*w+x*3+0]:=r2; P^[(h-y)*w+x*3+1]:=r2; P^[(h-y)*w+x*3+2]:=r2; end; end; Gauge.Progress:=0; end; procedure BinaryExSh(var Bmp:TBitmap; R:Integer; C:Byte); var Bmp2:TBitmap; P,P2:PByteArray; w,h,x,y,dx,dy,yy,xx:Integer; Convolution: TConvolution2D; begin; if (Bmp=nil) or (Bmp.Width=0) or (Bmp.Height=0) or (R=0) then exit; if (R>MaxKernelSize) then R:=MaxKernelSize; Convolution.Size:=R; for x:=-R to R do for y:=-R to R do begin; if (sqr(x)+sqr(y)>sqr(R)) then Convolution.Weights[x,y]:=0 else Convolution.Weights[x,y]:=1; end; Bmp2:=TBitmap.Create; Bmp2.Assign(Bmp); PrepareBmp(Bmp,w,h,P); PrepareBmp(Bmp2,w,h,P2); Gauge.MaxValue:=Bmp.Width-1; Gauge.Progress:=0; for x:=0 to Bmp.Width-1 do begin; Gauge.Progress:=Gauge.Progress+1; Application.ProcessMessages; for y:=0 to Bmp.Height-1 do begin; if (P^[(h-y)*w+x*3+0]=C) then begin; for dx:=-R to R do for dy:=-R to R do if Convolution.Weights[dx,dy]=1 then begin; xx:=Trim(0,Bmp.Width-1, x+dx); yy:=Trim(0,Bmp.Height-1,y+dy); P2^[(h-yy)*w+xx*3+0]:=C; P2^[(h-yy)*w+xx*3+1]:=C; P2^[(h-yy)*w+xx*3+2]:=C; end; end; end; end; Bmp.Free; Bmp:=Bmp2; Gauge.Progress:=0; end; procedure BExpand(var Bmp:TBitmap; R:Integer); begin; BinaryExSh(Bmp,R,255); end; procedure BShrink(var Bmp:TBitmap; R:Integer); begin; BinaryExSh(Bmp,R,0); end; procedure BClose(var Bmp:TBitmap; R:Integer); begin; BExpand(Bmp,R); BShrink(Bmp,R); end; procedure BOpen(var Bmp:TBitmap; R:Integer); begin; BShrink(Bmp,R); BExpand(Bmp,R); end; procedure AddContrast(var Bmp:TBitmap; IgnorePercent:Single); var P:PByteArray; w,h,x,y,n,maxn,ming,maxg:Integer; Counts:array[0..255] of Integer; begin; if IgnorePercent>0.49 then IgnorePercent:=0.49; if (Bmp=nil) or (Bmp.Width=0) or (Bmp.Height=0) then exit; PrepareBmp(Bmp,w,h,P); Gauge.MaxValue:=Bmp.Width*2-1; Gauge.Progress:=0; FillChar(Counts,sizeof(Counts),0); for x:=0 to Bmp.Width-1 do begin; Gauge.Progress:=Gauge.Progress+1; Application.ProcessMessages; for y:=0 to Bmp.Height-1 do Inc(Counts[Round(0.114*P^[(h-y)*w+x*3+0]+0.587*P^[(h-y)*w+x*3+1]+0.299*P^[(h-y)*w+x*3+2])]); end; maxn:=Round(Bmp.Width*Bmp.Height*IgnorePercent); n:=0; for ming:=0 to 255 do begin; n:=n+Counts[ming]; if n>=maxn then break; end; n:=0; for maxg:=255 downto 0 do begin; n:=n+Counts[maxg]; if n>=maxn then break; end; if ming>maxg then ming:=maxg; for x:=0 to Bmp.Width-1 do begin; Gauge.Progress:=Gauge.Progress+1; Application.ProcessMessages; for y:=0 to Bmp.Height-1 do begin; P^[(h-y)*w+x*3+0]:=Trim(0,255,((P^[(h-y)*w+x*3+0]-ming)*255) div (maxg-ming+1)); P^[(h-y)*w+x*3+1]:=Trim(0,255,((P^[(h-y)*w+x*3+1]-ming)*255) div (maxg-ming+1)); P^[(h-y)*w+x*3+2]:=Trim(0,255,((P^[(h-y)*w+x*3+2]-ming)*255) div (maxg-ming+1)); end; end; Gauge.Progress:=0; end; end.
27.18018
126
0.560049
fc39da00f4d05a5e8edb9b87a515fed7a887999d
599
dpr
Pascal
src/tests/PascalCoinUnitTests.dpr
rabarbers/PascalCoin
7a87031bc10a3e1d9461dfed3c61036047ce4fb0
[ "MIT" ]
384
2016-07-16T10:07:28.000Z
2021-12-29T11:22:56.000Z
src/tests/PascalCoinUnitTests.dpr
rabarbers/PascalCoin
7a87031bc10a3e1d9461dfed3c61036047ce4fb0
[ "MIT" ]
165
2016-09-11T11:06:04.000Z
2021-12-05T23:31:55.000Z
src/tests/PascalCoinUnitTests.dpr
rabarbers/PascalCoin
7a87031bc10a3e1d9461dfed3c61036047ce4fb0
[ "MIT" ]
210
2016-08-26T14:49:47.000Z
2022-02-22T18:06:33.000Z
program RandomHash.Tests; {$WARN DUPLICATE_CTOR_DTOR OFF} {$IFDEF CONSOLE_TESTRUNNER} {$APPTYPE CONSOLE} {$ENDIF} uses Forms, TestFramework, GUITestRunner, TextTestRunner, UPCSafeBoxRootHashTests in 'UPCSafeBoxRootHashTests.pas', URandomHash.Tests.Delphi in 'URandomHash.Tests.Delphi.pas', URandomHash2.Tests.Delphi in 'URandomHash2.Tests.Delphi.pas', URandomHash in '..\core\URandomHash.pas', URandomHash2 in '..\core\URandomHash2.pas'; begin Application.Initialize; if IsConsole then TextTestRunner.RunRegisteredTests else GUITestRunner.RunRegisteredTests; end.
23.038462
63
0.776294
c34176320b726dcef98d41a4a4c36c7c3f426891
204
dpr
Pascal
14-JSONStorage/JSONStorage.dpr
FMXExpress/Cross-Platform-Samples
d6b761b81a6521652db814b0c1e65263dff4f694
[ "BSD-3-Clause" ]
140
2019-08-07T23:22:44.000Z
2022-02-23T18:27:51.000Z
14-JSONStorage/JSONStorage.dpr
azrael11/Cross-Platform-Samples
f2c16ae3ae23d1ecca00110af1571313eb4e4c51
[ "BSD-3-Clause" ]
1
2020-06-08T11:23:04.000Z
2020-06-08T11:23:04.000Z
14-JSONStorage/JSONStorage.dpr
azrael11/Cross-Platform-Samples
f2c16ae3ae23d1ecca00110af1571313eb4e4c51
[ "BSD-3-Clause" ]
54
2019-08-09T21:37:51.000Z
2022-03-13T12:13:16.000Z
program JSONStorage; uses System.StartUpCopy, FMX.Forms, Unit1 in 'Unit1.pas' {Form1}; {$R *.res} begin Application.Initialize; Application.CreateForm(TForm1, Form1); Application.Run; end.
13.6
40
0.715686
c3607b2b209a80ba857d38d8f3e7772c1480a489
123
pas
Pascal
tests/semantics/12-div-02.pas
ZeroICQ/pascal-compiler
be7fce3ea610bae8a7b7917c9f568f5552d7b08d
[ "MIT" ]
null
null
null
tests/semantics/12-div-02.pas
ZeroICQ/pascal-compiler
be7fce3ea610bae8a7b7917c9f568f5552d7b08d
[ "MIT" ]
null
null
null
tests/semantics/12-div-02.pas
ZeroICQ/pascal-compiler
be7fce3ea610bae8a7b7917c9f568f5552d7b08d
[ "MIT" ]
null
null
null
var i1, i2, i3 : integer; f: double; // c1, c2: char; // b1, b2: boolean; begin i1 := i2 div f; end.
13.666667
25
0.471545
f152c4cc6f76f475aeb6fc8a80433fdad64fdb55
1,506
pas
Pascal
SDQC/source/SDQC.Util.WayneFusionConstantes.pas
rafarocha28/Delphi-miscellanea
bb0583673054dcdda3249426abebe65b8ea65e02
[ "MIT" ]
null
null
null
SDQC/source/SDQC.Util.WayneFusionConstantes.pas
rafarocha28/Delphi-miscellanea
bb0583673054dcdda3249426abebe65b8ea65e02
[ "MIT" ]
null
null
null
SDQC/source/SDQC.Util.WayneFusionConstantes.pas
rafarocha28/Delphi-miscellanea
bb0583673054dcdda3249426abebe65b8ea65e02
[ "MIT" ]
null
null
null
unit SDQC.Util.WayneFusionConstantes; interface const WAYNE_PARAM = '-wayne'; FUSION_PARAM = '-fusion'; WAYNE_FUSION_PARAM = '-wayne_fusion'; WAYNE_FILE = 'wayne.bin'; MESSAGE_TERMINATOR = '^'; WAYNE_DEFAULT_PORT = 3011; OK_REPLY = 1; COMMAND_PUMP_GET_PRICE_LEVEL = 'REQ_PUMP_GET_PRICE_LEVEL_ID_'; COMMAND_PUMP_STATUS = 'REQ_PUMP_STATUS_ID_'; COMMAND_PUMP_GET_TOTALS = 'REQ_PUMP_GET_TOTALS_ID_'; COMMAND_GET_SALE_DETAIL = 'REQ_GET_SALE_DETAIL'; resourcestring sSaleDetailReplyTag = '00344|5|2||POST|RES_GET_SALE_DETAIL|192.168.10.5:49808|'+ '127.0.0.1:48116|VO=11.15700|TY=1|TSID=|TI=141553|STI=141432|SDA=20160112|'+ 'SA=931925|RC=OK|PU=2.68900|PR=0.00000|PM=1|PAY_TY=Attendant Tagging|'+ 'PAY_IN=#$PREPAY=ATT-TAG~$TAG=17000015EA67E201~$USER=ADMIN~$TAGROLE=0|'+ 'LV=1|IV=427342.06000|HO=9|GR=96|FV=427353.22000|DA=20161027|CT=|CD=|'+ 'AUTH=OK|AM=30.00|^'; sSaleDetailReplyNoTag = '00344|5|2||POST|RES_GET_SALE_DETAIL|192.168.10.5:49808|'+ '127.0.0.1:48116|VO=11.15700|TY=1|TSID=|TI=141553|STI=141432|SDA=20160112|'+ 'SA=931925|RC=OK|PU=2.68900|PR=0.00000|PM=1|PAY_TY=Attendant Tagging|'+ 'PAY_IN=|'+ // no tag 'LV=1|IV=427342.06000|HO=9|GR=96|FV=427353.22000|DA=20161027|CT=|CD=|'+ 'AUTH=OK|AM=30.00|^'; sStatusReply = '00088|5|2|GUEST|POST|EVT_PUMP_STATUS_CHANGE_ID_%.3d|'+ '10.10.1.24:4335|127.0.0.1:55102|SU=|ST=IDLE|^'; // sGetTotalsReply = '00344|5|2||POST|RES_PUMP_GET_TOTALS_ID_%.3d|HOSES=1||^'; implementation end.
35.857143
84
0.708499
fc3b422c9901641d645725cef428e150effa70ee
3,855
pas
Pascal
Server/xTBudgetOrderRegularityType.pas
Sembium/Sembium3
0179c38c6a217f71016f18f8a419edd147294b73
[ "Apache-2.0" ]
null
null
null
Server/xTBudgetOrderRegularityType.pas
Sembium/Sembium3
0179c38c6a217f71016f18f8a419edd147294b73
[ "Apache-2.0" ]
null
null
null
Server/xTBudgetOrderRegularityType.pas
Sembium/Sembium3
0179c38c6a217f71016f18f8a419edd147294b73
[ "Apache-2.0" ]
3
2021-06-30T10:11:17.000Z
2021-07-01T09:13:29.000Z
 {****************************************************************************************} { } { XML Data Binding } { } { Generated on: 11.1.2006 16:04:28 } { Generated from: XMLSchemas\Public\TBudgetOrderRegularityType.xsd } { } {****************************************************************************************} unit xTBudgetOrderRegularityType; interface uses xmldom, XMLDoc, XMLIntf; type { Forward Decls } IXMLTBudgetOrderRegularityType = interface; { IXMLTBudgetOrderRegularityType } IXMLTBudgetOrderRegularityType = interface(IXMLNode) ['{40E455EB-607B-4521-95ED-74E2E44A88C0}'] { Property Accessors } function Get_BudgetOrderRegularityTypeName: Variant; function Get_BudgetOrderRegularityTypeAbbrev: Variant; procedure Set_BudgetOrderRegularityTypeName(Value: Variant); procedure Set_BudgetOrderRegularityTypeAbbrev(Value: Variant); { Methods & Properties } property BudgetOrderRegularityTypeName: Variant read Get_BudgetOrderRegularityTypeName write Set_BudgetOrderRegularityTypeName; property BudgetOrderRegularityTypeAbbrev: Variant read Get_BudgetOrderRegularityTypeAbbrev write Set_BudgetOrderRegularityTypeAbbrev; end; { Forward Decls } TXMLTBudgetOrderRegularityType = class; { TXMLTBudgetOrderRegularityType } TXMLTBudgetOrderRegularityType = class(TXMLNode, IXMLTBudgetOrderRegularityType) protected { IXMLTBudgetOrderRegularityType } function Get_BudgetOrderRegularityTypeName: Variant; function Get_BudgetOrderRegularityTypeAbbrev: Variant; procedure Set_BudgetOrderRegularityTypeName(Value: Variant); procedure Set_BudgetOrderRegularityTypeAbbrev(Value: Variant); end; { Global Functions } function GetUnknown(Doc: IXMLDocument): IXMLTBudgetOrderRegularityType; function LoadUnknown(const FileName: WideString): IXMLTBudgetOrderRegularityType; function NewUnknown: IXMLTBudgetOrderRegularityType; const TargetNamespace = ''; implementation { Global Functions } function GetUnknown(Doc: IXMLDocument): IXMLTBudgetOrderRegularityType; begin Result := Doc.GetDocBinding('Unknown', TXMLTBudgetOrderRegularityType, TargetNamespace) as IXMLTBudgetOrderRegularityType; end; function LoadUnknown(const FileName: WideString): IXMLTBudgetOrderRegularityType; begin Result := LoadXMLDocument(FileName).GetDocBinding('Unknown', TXMLTBudgetOrderRegularityType, TargetNamespace) as IXMLTBudgetOrderRegularityType; end; function NewUnknown: IXMLTBudgetOrderRegularityType; begin Result := NewXMLDocument.GetDocBinding('Unknown', TXMLTBudgetOrderRegularityType, TargetNamespace) as IXMLTBudgetOrderRegularityType; end; { TXMLTBudgetOrderRegularityType } function TXMLTBudgetOrderRegularityType.Get_BudgetOrderRegularityTypeName: Variant; begin Result := ChildNodes['BudgetOrderRegularityTypeName'].NodeValue; end; procedure TXMLTBudgetOrderRegularityType.Set_BudgetOrderRegularityTypeName(Value: Variant); begin ChildNodes['BudgetOrderRegularityTypeName'].NodeValue := Value; end; function TXMLTBudgetOrderRegularityType.Get_BudgetOrderRegularityTypeAbbrev: Variant; begin Result := ChildNodes['BudgetOrderRegularityTypeAbbrev'].NodeValue; end; procedure TXMLTBudgetOrderRegularityType.Set_BudgetOrderRegularityTypeAbbrev(Value: Variant); begin ChildNodes['BudgetOrderRegularityTypeAbbrev'].NodeValue := Value; end; end.
37.427184
147
0.681193
f1aa15a057cd3dce1885804f2d6a9c4184ee55c1
3,696
pas
Pascal
Source/dlgOptionsEditor.pas
nioniochang/pyscripter
e5ad6138fe3c6de9fd96c58e6fed98aa4c82fd5a
[ "MIT" ]
1
2020-10-14T10:51:42.000Z
2020-10-14T10:51:42.000Z
Source/dlgOptionsEditor.pas
RogerioMatos78/pyscripter
0c3928b8c984ebcbd51824b120b6fc97c17317be
[ "MIT" ]
null
null
null
Source/dlgOptionsEditor.pas
RogerioMatos78/pyscripter
0c3928b8c984ebcbd51824b120b6fc97c17317be
[ "MIT" ]
null
null
null
{----------------------------------------------------------------------------- Unit Name: dlgOptionsEditor Author: Kiriakos Vlahos Date: 10-Mar-2005 Purpose: Generic Options Editor based on JvInspector History: -----------------------------------------------------------------------------} unit dlgOptionsEditor; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Buttons, dlgPyIDEBase, zBase, zObjInspector, Vcl.ExtCtrls, System.Generics.Collections, cPyScripterSettings, Vcl.StdCtrls; type TOption = record PropertyName : string; DisplayName : string; end; TOptionCategory = record DisplayName : string; Options : array of TOption; end; TOptionsInspector = class(TPyIDEDlgBase) Panel1: TPanel; Panel2: TPanel; Inspector: TzObjectInspector; OKButton: TButton; BitBtn2: TButton; HelpButton: TButton; procedure OKButtonClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure HelpButtonClick(Sender: TObject); procedure FormCreate(Sender: TObject); function InspectorGetItemFriendlyName(Sender: TControl; PItem: PPropItem): string; private { Private declarations } fOptionsObject, fTempOptionsObject : TPersistent; FriendlyNames : TDictionary<string, string>; public { Public declarations } procedure Setup(OptionsObject : TBaseOptions; Categories : array of TOptionCategory); end; function InspectOptions(OptionsObject : TBaseOptions; Categories : array of TOptionCategory; FormCaption : string; HelpCntxt : integer = 0): boolean; implementation {$R *.dfm} { TIDEOptionsWindow } procedure TOptionsInspector.Setup(OptionsObject: TBaseOptions; Categories: array of TOptionCategory); var i, j : integer; begin fOptionsObject := OptionsObject; fTempOptionsObject := TBaseOptionsClass(OptionsObject.ClassType).Create; fTempOptionsObject.Assign(fOptionsObject); Inspector.Component := fTempOptionsObject; for i := Low(Categories) to High(Categories) do with Categories[i] do begin for j := Low(Options) to High(Options) do begin Inspector.RegisterPropertyInCategory(Categories[i].DisplayName, Options[j].PropertyName); FriendlyNames.Add(Options[j].PropertyName, Options[j].DisplayName); end; end; Inspector.UpdateProperties; end; procedure TOptionsInspector.OKButtonClick(Sender: TObject); begin fOptionsObject.Assign(fTempOptionsObject); end; procedure TOptionsInspector.FormCreate(Sender: TObject); begin inherited; FriendlyNames := TDictionary<string,string>.Create; end; procedure TOptionsInspector.FormDestroy(Sender: TObject); begin if Assigned(fTempOptionsObject) then FreeAndNil(fTempOptionsObject); FriendlyNames.Free; end; function InspectOptions(OptionsObject : TBaseOptions; Categories : array of TOptionCategory; FormCaption : string; HelpCntxt : integer = 0): boolean; begin with TOptionsInspector.Create(Application) do begin Caption := FormCaption; HelpContext := HelpCntxt; Setup(OptionsObject, Categories); Result := ShowModal = mrOK; Release; end; end; procedure TOptionsInspector.HelpButtonClick(Sender: TObject); begin if HelpContext <> 0 then Application.HelpContext(HelpContext); end; function TOptionsInspector.InspectorGetItemFriendlyName(Sender: TControl; PItem: PPropItem): string; begin if FriendlyNames.ContainsKey(PItem.Name) then Result := FriendlyNames[PItem.Name] else Result := PItem.Name; end; end.
27.58209
98
0.691558
fc1b26993f6c6eb245fcf6ab72bf9f9085284b20
4,599
pas
Pascal
20210527-Delphi-App-Tethering/ChatOnTheFly/ChatOnTheFly.Forms.Main.pas
marcobreveglieri/compilaquindiva
fca8c384b2556526a9575524808f4517993cc2e7
[ "CC0-1.0" ]
1
2021-09-24T21:15:55.000Z
2021-09-24T21:15:55.000Z
20210527-Delphi-App-Tethering/ChatOnTheFly/ChatOnTheFly.Forms.Main.pas
marcobreveglieri/compilaquindiva
fca8c384b2556526a9575524808f4517993cc2e7
[ "CC0-1.0" ]
null
null
null
20210527-Delphi-App-Tethering/ChatOnTheFly/ChatOnTheFly.Forms.Main.pas
marcobreveglieri/compilaquindiva
fca8c384b2556526a9575524808f4517993cc2e7
[ "CC0-1.0" ]
1
2021-09-24T21:16:04.000Z
2021-09-24T21:16:04.000Z
unit ChatOnTheFly.Forms.Main; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Controls.Presentation, FMX.Edit, FMX.Layouts, FMX.Memo, System.Actions, FMX.ActnList, IPPeerClient, IPPeerServer, System.Tether.Manager, System.Tether.AppProfile, FMX.Memo.Types, FMX.ScrollBox; type TMainForm = class(TForm) HeaderToolBar: TToolBar; FooterToolBar: TToolBar; HeaderLabel: TLabel; MessageEdit: TEdit; SendMessageButton: TButton; ChatMemo: TMemo; MainActionList: TActionList; SendMessageAction: TAction; ChatManager: TTetheringManager; ChatAppProfile: TTetheringAppProfile; NameToolBar: TToolBar; NameEdit: TEdit; NameLabel: TLabel; ConnectButton: TButton; ConnectAction: TAction; procedure SendMessageActionExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ChatManagerRequestManagerPassword(const Sender: TObject; const ARemoteIdentifier: string; var Password: string); procedure ChatAppProfileResourceReceived(const Sender: TObject; const AResource: TRemoteResource); procedure MessageEditKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); procedure MainActionListUpdate(Action: TBasicAction; var Handled: Boolean); procedure ConnectActionExecute(Sender: TObject); procedure ChatManagerEndAutoConnect(Sender: TObject); private { Private declarations } FPassword: string; procedure AppendToChatLog(const AText: string); public { Public declarations } end; var MainForm: TMainForm; implementation {$R *.fmx} procedure TMainForm.AppendToChatLog(const AText: string); begin // Append text to the chat log memo control, adding a separator. if ChatMemo.Lines.Count > 0 then ChatMemo.Lines.Add(StringOfChar('-', 10)); ChatMemo.Lines.Add(AText); end; procedure TMainForm.ChatAppProfileResourceReceived(const Sender: TObject; const AResource: TRemoteResource); begin // Add any new message received as a string resource // from a connected app to the chat log control. AppendToChatLog(AResource.Value.AsString); end; procedure TMainForm.ChatManagerEndAutoConnect(Sender: TObject); begin // Display information about found and paired managers. ConnectAction.Caption := Format('Connected! (%d)', [ChatManager.PairedManagers.Count]); end; procedure TMainForm.ChatManagerRequestManagerPassword(const Sender: TObject; const ARemoteIdentifier: string; var Password: string); begin // Set the password required by the manager this app is trying to connect to. Password := FPassword; end; procedure TMainForm.ConnectActionExecute(Sender: TObject); begin // Auto discover and connect to available tethering managers and profiles. ConnectAction.Caption := 'Connecting...'; ChatManager.AutoConnect(); end; procedure TMainForm.FormCreate(Sender: TObject); begin // Set the password required by other instances (with tethering managers) // to create a connection to hosted app profiles. You can also ask the user // to manually enter this password through an Input Box or similar. FPassword := 'toc'; end; procedure TMainForm.MainActionListUpdate(Action: TBasicAction; var Handled: Boolean); begin // Enable the message sending action only if nickname and text are specified. SendMessageAction.Enabled := (Length(Trim(NameEdit.Text)) > 0) and (Length(Trim(MessageEdit.Text)) > 0); Handled := True; end; procedure TMainForm.MessageEditKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin // Send the message by hitting return key. if KeyChar = #13 then SendMessageAction.Execute; end; procedure TMainForm.SendMessageActionExecute(Sender: TObject); var RemoteProfile: TTetheringProfileInfo; MessageText: string; begin // Create a formatted log for the message to send to connected apps. MessageText := Format('%s says: "%s"', [Trim(NameEdit.Text), Trim(MessageEdit.Text)]); // Append the message to the chat log. AppendToChatLog(MessageText); // Scan remote connected profiles and send the message log as a resource. for RemoteProfile in ChatManager.RemoteProfiles do ChatAppProfile.SendString(RemoteProfile, 'New message', MessageText); // Empty the message input box for new text. MessageEdit.Text := EmptyStr; end; end.
33.816176
80
0.733855
f1c4f2d87796c8d90d926517de1dbc0c3eeddca1
8,993
pas
Pascal
3rdParty/JWAPI/jwapi2.2a/Win32API/JwaLmStats.pas
bero/CodeCoverage
927a3059962296c4d9f9bac861b1446259214471
[ "Apache-2.0" ]
1
2020-10-06T01:19:34.000Z
2020-10-06T01:19:34.000Z
3rdParty/JWAPI/jwapi2.2a/Win32API/JwaLmStats.pas
bero/CodeCoverage
927a3059962296c4d9f9bac861b1446259214471
[ "Apache-2.0" ]
null
null
null
3rdParty/JWAPI/jwapi2.2a/Win32API/JwaLmStats.pas
bero/CodeCoverage
927a3059962296c4d9f9bac861b1446259214471
[ "Apache-2.0" ]
null
null
null
{******************************************************************************} { } { Lan Manager Statistics API interface Unit for Object Pascal } { } { Portions created by Microsoft are Copyright (C) 1995-2001 Microsoft } { Corporation. All Rights Reserved. } { } { The original file is: lmstats.h, released November 2001. The original Pascal } { code is: LmStats.pas, released Februari 2002. The initial developer of the } { Pascal code is Marcel van Brakel (brakelm att chello dott nl). } { } { Portions created by Marcel van Brakel are Copyright (C) 1999-2001 } { Marcel van Brakel. All Rights Reserved. } { } { Obtained through: Joint Endeavour of Delphi Innovators (Project JEDI) } { } { You may retrieve the latest version of this file at the Project JEDI } { APILIB home page, located at http://jedi-apilib.sourceforge.net } { } { 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.1.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. } { } { Alternatively, the contents of this file may be used under the terms of the } { GNU Lesser General Public License (the "LGPL License"), in which case the } { provisions of the LGPL License are applicable instead of those above. } { If you wish to allow use of your version of this file only under the terms } { of the LGPL License and not to allow others to use your version of this file } { under the MPL, indicate your decision by deleting the provisions above and } { replace them with the notice and other provisions required by the LGPL } { License. If you do not delete the provisions above, a recipient may use } { your version of this file under either the MPL or the LGPL License. } { } { For more information about the LGPL: http://www.gnu.org/copyleft/lesser.html } { } {******************************************************************************} // $Id: JwaLmStats.pas,v 1.12 2007/09/05 11:58:51 dezipaitor Exp $ {$IFNDEF JWA_OMIT_SECTIONS_LM} unit JwaLmStats; {$WEAKPACKAGEUNIT} {$ENDIF JWA_OMIT_SECTIONS_LM} {$HPPEMIT ''} {$HPPEMIT '#include "lmstats.h"'} {$HPPEMIT ''} {$IFNDEF JWA_OMIT_SECTIONS_LM} {$I ..\Includes\JediAPILib.inc} interface uses JwaLmCons, JwaWinType; {$ENDIF JWA_OMIT_SECTIONS_LM} {$IFNDEF JWA_IMPLEMENTATIONSECTION} // // Function Prototypes - Statistics // function NetStatisticsGet(server: LMSTR; service: LMSTR; level: DWORD; options: DWORD; var bufptr: LPBYTE): NET_API_STATUS; stdcall; {$EXTERNALSYM NetStatisticsGet} // // Data Structures - Statistics // {$IFDEF LM20_WORKSTATION_STATISTICS} type _STAT_WORKSTATION_0 = record stw0_start: DWORD; stw0_numNCB_r: DWORD; stw0_numNCB_s: DWORD; stw0_numNCB_a: DWORD; stw0_fiNCB_r: DWORD; stw0_fiNCB_s: DWORD; stw0_fiNCB_a: DWORD; stw0_fcNCB_r: DWORD; stw0_fcNCB_s: DWORD; stw0_fcNCB_a: DWORD; stw0_sesstart: DWORD; stw0_sessfailcon: DWORD; stw0_sessbroke: DWORD; stw0_uses: DWORD; stw0_usefail: DWORD; stw0_autorec: DWORD; stw0_bytessent_r_lo: DWORD; stw0_bytessent_r_hi: DWORD; stw0_bytesrcvd_r_lo: DWORD; stw0_bytesrcvd_r_hi: DWORD; stw0_bytessent_s_lo: DWORD; stw0_bytessent_s_hi: DWORD; stw0_bytesrcvd_s_lo: DWORD; stw0_bytesrcvd_s_hi: DWORD; stw0_bytessent_a_lo: DWORD; stw0_bytessent_a_hi: DWORD; stw0_bytesrcvd_a_lo: DWORD; stw0_bytesrcvd_a_hi: DWORD; stw0_reqbufneed: DWORD; stw0_bigbufneed: DWORD; end; {$EXTERNALSYM _STAT_WORKSTATION_0} STAT_WORKSTATION_0 = _STAT_WORKSTATION_0; {$EXTERNALSYM STAT_WORKSTATION_0} PSTAT_WORKSTATION_0 = ^STAT_WORKSTATION_0; {$EXTERNALSYM PSTAT_WORKSTATION_0} LPSTAT_WORKSTATION_0 = ^STAT_WORKSTATION_0; {$EXTERNALSYM LPSTAT_WORKSTATION_0} TStatWorkstation0 = STAT_WORKSTATION_0; PStatWorkstation0 = PSTAT_WORKSTATION_0; {$ELSE} // // NB: The following structure is REDIR_STATISTICS in sdk\inc\ntddnfs.h. If you // change the structure, change it in both places // type _STAT_WORKSTATION_0 = record StatisticsStartTime: LARGE_INTEGER; BytesReceived: LARGE_INTEGER; SmbsReceived: LARGE_INTEGER; PagingReadBytesRequested: LARGE_INTEGER; NonPagingReadBytesRequested: LARGE_INTEGER; CacheReadBytesRequested: LARGE_INTEGER; NetworkReadBytesRequested: LARGE_INTEGER; BytesTransmitted: LARGE_INTEGER; SmbsTransmitted: LARGE_INTEGER; PagingWriteBytesRequested: LARGE_INTEGER; NonPagingWriteBytesRequested: LARGE_INTEGER; CacheWriteBytesRequested: LARGE_INTEGER; NetworkWriteBytesRequested: LARGE_INTEGER; InitiallyFailedOperations: DWORD; FailedCompletionOperations: DWORD; ReadOperations: DWORD; RandomReadOperations: DWORD; ReadSmbs: DWORD; LargeReadSmbs: DWORD; SmallReadSmbs: DWORD; WriteOperations: DWORD; RandomWriteOperations: DWORD; WriteSmbs: DWORD; LargeWriteSmbs: DWORD; SmallWriteSmbs: DWORD; RawReadsDenied: DWORD; RawWritesDenied: DWORD; NetworkErrors: DWORD; // Connection/Session counts Sessions: DWORD; FailedSessions: DWORD; Reconnects: DWORD; CoreConnects: DWORD; Lanman20Connects: DWORD; Lanman21Connects: DWORD; LanmanNtConnects: DWORD; ServerDisconnects: DWORD; HungSessions: DWORD; UseCount: DWORD; FailedUseCount: DWORD; // // Queue Lengths (updates protected by RdrMpxTableSpinLock NOT // RdrStatisticsSpinlock) // CurrentCommands: DWORD; end; {$EXTERNALSYM _STAT_WORKSTATION_0} STAT_WORKSTATION_0 = _STAT_WORKSTATION_0; {$EXTERNALSYM STAT_WORKSTATION_0} PSTAT_WORKSTATION_0 = ^STAT_WORKSTATION_0; {$EXTERNALSYM PSTAT_WORKSTATION_0} LPSTAT_WORKSTATION_0 = ^STAT_WORKSTATION_0; {$EXTERNALSYM LPSTAT_WORKSTATION_0} TStatWorkstation0 = STAT_WORKSTATION_0; PStatWorkstation0 = PSTAT_WORKSTATION_0; {$ENDIF LM20_WORKSTATION_STATISTICS} type _STAT_SERVER_0 = record sts0_start: DWORD; sts0_fopens: DWORD; sts0_devopens: DWORD; sts0_jobsqueued: DWORD; sts0_sopens: DWORD; sts0_stimedout: DWORD; sts0_serrorout: DWORD; sts0_pwerrors: DWORD; sts0_permerrors: DWORD; sts0_syserrors: DWORD; sts0_bytessent_low: DWORD; sts0_bytessent_high: DWORD; sts0_bytesrcvd_low: DWORD; sts0_bytesrcvd_high: DWORD; sts0_avresponse: DWORD; sts0_reqbufneed: DWORD; sts0_bigbufneed: DWORD; end; {$EXTERNALSYM _STAT_SERVER_0} STAT_SERVER_0 = _STAT_SERVER_0; {$EXTERNALSYM STAT_SERVER_0} PSTAT_SERVER_0 = ^STAT_SERVER_0; {$EXTERNALSYM PSTAT_SERVER_0} LPSTAT_SERVER_0 = ^STAT_SERVER_0; {$EXTERNALSYM LPSTAT_SERVER_0} TStatServer0 = STAT_SERVER_0; PStatServer0 = PSTAT_SERVER_0; // // Special Values and Constants // const STATSOPT_CLR = 1; {$EXTERNALSYM STATSOPT_CLR} STATS_NO_VALUE = ULONG(-1); {$EXTERNALSYM STATS_NO_VALUE} STATS_OVERFLOW = ULONG(-2); {$EXTERNALSYM STATS_OVERFLOW} {$ENDIF JWA_IMPLEMENTATIONSECTION} {$IFNDEF JWA_OMIT_SECTIONS_LM} implementation //uses ... {$ENDIF JWA_OMIT_SECTIONS_LM} {$IFNDEF JWA_INTERFACESECTION} {$IFDEF DYNAMIC_LINK} var _NetStatisticsGet: Pointer; function NetStatisticsGet; begin GetProcedureAddress(_NetStatisticsGet, netapi32, 'NetStatisticsGet'); asm MOV ESP, EBP POP EBP JMP [_NetStatisticsGet] end; end; {$ELSE} function NetStatisticsGet; external netapi32 {$IFDEF DELAYED_LOADING}delayed{$ENDIF} name 'NetStatisticsGet'; {$ENDIF DYNAMIC_LINK} {$ENDIF JWA_INTERFACESECTION} {$IFNDEF JWA_OMIT_SECTIONS_LM} end. {$ENDIF JWA_OMIT_SECTIONS_LM}
34.193916
132
0.641944
c305f04c414062710c99e5905f887a89c22b65a8
5,562
pas
Pascal
Components/TNT/Design/TntDesignEditors_Design.pas
jaksco/cubicexplorer
7bf2513700477d753fd8ea1c6226ddab0175df91
[ "Condor-1.1" ]
1
2021-09-23T17:32:49.000Z
2021-09-23T17:32:49.000Z
Components/TNT/Design/TntDesignEditors_Design.pas
jaksco/cubicexplorer
7bf2513700477d753fd8ea1c6226ddab0175df91
[ "Condor-1.1" ]
null
null
null
Components/TNT/Design/TntDesignEditors_Design.pas
jaksco/cubicexplorer
7bf2513700477d753fd8ea1c6226ddab0175df91
[ "Condor-1.1" ]
null
null
null
{*****************************************************************************} { } { Tnt Delphi Unicode Controls } { http://www.tntware.com/delphicontrols/unicode/ } { Version: 2.3.0 } { } { Copyright (c) 2002-2007, Troy Wolbrink (troy.wolbrink@tntware.com) } { } {*****************************************************************************} unit TntDesignEditors_Design; {$INCLUDE ..\Source\TntCompilers.inc} interface uses Classes, Forms, TypInfo, DesignIntf, DesignEditors; type ITntDesigner = IDesigner; TTntDesignerSelections = class(TInterfacedObject, IDesignerSelections) private FList: TList; {$IFDEF COMPILER_9_UP} function GetDesignObject(Index: Integer): IDesignObject; {$ENDIF} protected function Add(const Item: TPersistent): Integer; function Equals(const List: IDesignerSelections): Boolean; function Get(Index: Integer): TPersistent; function GetCount: Integer; property Count: Integer read GetCount; property Items[Index: Integer]: TPersistent read Get; default; public constructor Create; virtual; destructor Destroy; override; procedure ReplaceSelection(const OldInst, NewInst: TPersistent); end; function GetObjectInspectorForm: TCustomForm; procedure EditPropertyWithDialog(Component: TPersistent; const PropName: AnsiString; const Designer: ITntDesigner); implementation uses SysUtils; { TTntDesignerSelections } function TTntDesignerSelections.Add(const Item: TPersistent): Integer; begin Result := FList.Add(Item); end; constructor TTntDesignerSelections.Create; begin inherited; FList := TList.Create; end; destructor TTntDesignerSelections.Destroy; begin FList.Free; inherited; end; function TTntDesignerSelections.Equals(const List: IDesignerSelections): Boolean; var I: Integer; begin Result := False; if List.Count <> Count then Exit; for I := 0 to Count - 1 do begin if Items[I] <> List[I] then Exit; end; Result := True; end; function TTntDesignerSelections.Get(Index: Integer): TPersistent; begin Result := TPersistent(FList[Index]); end; function TTntDesignerSelections.GetCount: Integer; begin Result := FList.Count; end; {$IFDEF COMPILER_9_UP} function TTntDesignerSelections.GetDesignObject(Index: Integer): IDesignObject; begin Result := nil; {TODO: Figure out what IDesignerSelections.GetDesignObject is all about. Must wait for more documentation!} end; {$ENDIF} procedure TTntDesignerSelections.ReplaceSelection(const OldInst, NewInst: TPersistent); var Idx: Integer; begin Idx := FList.IndexOf(OldInst); if Idx <> -1 then FList[Idx] := NewInst; end; {//------------------------------ // Helpful discovery routines to explore the components and classes inside the IDE... // procedure EnumerateComponents(Comp: TComponent); var i: integer; begin for i := Comp.ComponentCount - 1 downto 0 do MessageBoxW(0, PWideChar(WideString(Comp.Components[i].Name + ': ' + Comp.Components[i].ClassName)), PWideChar(WideString(Comp.Name)), 0); end; procedure EnumerateClasses(Comp: TComponent); var AClass: TClass; begin AClass := Comp.ClassType; repeat MessageBoxW(0, PWideChar(WideString(AClass.ClassName)), PWideChar(WideString(Comp.Name)), 0); AClass := Aclass.ClassParent; until AClass = nil; end; //------------------------------} //------------------------------ function GetIdeMainForm: TCustomForm; var Comp: TComponent; begin Result := nil; if Application <> nil then begin Comp := Application.FindComponent('AppBuilder'); if Comp is TCustomForm then Result := TCustomForm(Comp); end; end; function GetObjectInspectorForm: TCustomForm; var Comp: TComponent; IdeMainForm: TCustomForm; begin Result := nil; IdeMainForm := GetIdeMainForm; if IdeMainForm <> nil then begin Comp := IdeMainForm.FindComponent('PropertyInspector'); if Comp is TCustomForm then Result := TCustomForm(Comp); end; end; { TPropertyEditorWithDialog } type TPropertyEditorWithDialog = class private FPropName: AnsiString; procedure CheckEditProperty(const Prop: IProperty); procedure EditProperty(Component: TPersistent; const PropName: AnsiString; const Designer: ITntDesigner); end; procedure TPropertyEditorWithDialog.CheckEditProperty(const Prop: IProperty); begin if Prop.GetName = FPropName then Prop.Edit; end; procedure TPropertyEditorWithDialog.EditProperty(Component: TPersistent; const PropName: AnsiString; const Designer: ITntDesigner); var Components: IDesignerSelections; begin FPropName := PropName; Components := TDesignerSelections.Create; Components.Add(Component); GetComponentProperties(Components, [tkClass], Designer, CheckEditProperty); end; procedure EditPropertyWithDialog(Component: TPersistent; const PropName: AnsiString; const Designer: ITntDesigner); begin with TPropertyEditorWithDialog.Create do try EditProperty(Component, PropName, Designer); finally Free; end; end; end.
28.233503
132
0.638979
473461d47ce2c9efa03e9710bb8ffa09ef78beea
48,440
pas
Pascal
references/embarcadero/rio/10_3_3/patched/fmx/FMX.Filter.pas
marlonnardi/alcinoe
5e14b2fca7adcc38e483771055b5623501433334
[ "Apache-2.0" ]
1
2019-01-27T14:00:28.000Z
2019-01-27T14:00:28.000Z
references/embarcadero/rio/10_3_3/patched/fmx/FMX.Filter.pas
marlonnardi/alcinoe
5e14b2fca7adcc38e483771055b5623501433334
[ "Apache-2.0" ]
2
2019-06-23T00:02:43.000Z
2019-10-12T22:39:28.000Z
references/embarcadero/rio/10_3_3/patched/fmx/FMX.Filter.pas
marlonnardi/alcinoe
5e14b2fca7adcc38e483771055b5623501433334
[ "Apache-2.0" ]
null
null
null
{*******************************************************} { } { Delphi FireMonkey Platform } { } { Copyright(c) 2011-2019 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit FMX.Filter; interface {$HINTS OFF} {$SCOPEDENUMS ON} uses System.Classes, System.Types, System.Rtti, System.UITypes, System.Generics.Collections, FMX.Types3D, FMX.Graphics; type { TFilter } TFilterValueType = (Float, Point, Color, Bitmap); TFilterValueTypeHelper = record helper for TFilterValueType const vtFloat = TFilterValueType.Float deprecated 'Use TFilterValueType.Float'; vtPoint = TFilterValueType.Point deprecated 'Use TFilterValueType.Point'; vtColor = TFilterValueType.Color deprecated 'Use TFilterValueType.Color'; vtBitmap = TFilterValueType.Bitmap deprecated 'Use TFilterValueType.Bitmap'; end; TFilterValueRec = record Name: string; Desc: string; ValueType: TFilterValueType; Value: TValue; Min, Max, Default: TValue; Bitmap: TBitmap; constructor Create(const AName, ADesc: string; AType: TFilterValueType; ADefault, AMin, AMax: TValue); overload; constructor Create(const AName, ADesc: string; AType: TFilterValueType); overload; constructor Create(const AName, ADesc: string; ADefault: TAlphaColor); overload; constructor Create(const AName, ADesc: string; ADefault, AMin, AMax: Single); overload; constructor Create(const AName, ADesc: string; ADefault, AMin, AMax: TPointF); overload; end; TFilterValueRecArray = array of TFilterValueRec; TFilterRec = record Name: string; Desc: string; Values: TFilterValueRecArray; constructor Create(const AName, ADesc: string; AValues: array of TFilterValueRec); overload; end; TFilterClass = class of TFilter; TFilter = class(TPersistent) private function GetFilterValues(const Index: string): TValue; procedure SetFilterValues(const Index: string; Value: TValue); function GetFilterValuesAsBitmap(const Index: string): TBitmap; procedure SetFilterValuesAsBitmap(const Index: string; const Value: TBitmap); function GetFilterValuesAsPoint(const Index: string): TPointF; procedure SetFilterValuesAsPoint(const Index: string; const Value: TPointF); procedure SetInputFilter(const Value: TFilter); function GetFilterValuesAsFloat(const Index: string): Single; procedure SetFilterValuesAsFloat(const Index: string; const Value: Single); function GetFilterValuesAsColor(const Index: string): TAlphaColor; procedure SetFilterValuesAsColor(const Index: string; const Value: TAlphaColor); function GetFilterValuesAsTexture(const Index: string): TTexture; procedure SetFilterValuesAsTexture(const Index: string; const Value: TTexture); property Values[const Index: string]: TValue read GetFilterValues write SetFilterValues; default; private class var FNoise: TTexture; procedure CreateNoise; procedure RenderTextureToContext(const Context: TContext3D; const Texture: TTexture; const ARect: TRect; const DstPos: TPoint); protected class var FVertexShader: TContextShader; protected FValues: TFilterValueRecArray; FInputRT: TTexture; FInputRTContext: TContext3D; FTargetRT: TTexture; FTargetRTContext: TContext3D; FPassInputRT: TTexture; FPassInputRTContext: TContext3D; FInput: TTexture; [Weak] FInputBitmap: TBitmap; FTarget: TTexture; [Weak] FTargetBitmap: TBitmap; FOutputSize: TSize; FOutputBitmap: TBitmap; FProcessing: Boolean; FModified: Boolean; FInputFilter: TFilter; FNeedInternalSecondTex: string; // need internal texture as second FNoCopyForOutput: Boolean; // not copy result to targer FAntiAlise: Boolean; // add transparent border for antialising FShaders: array of TContextShader; // shaders FPass, FPassCount: Integer; // for multipass - default shader have 1 pass function CreateFilterMaterial: TMaterial; virtual; procedure CalcSize(var W, H: Integer); virtual; procedure LoadShaders; virtual; procedure LoadTextures; virtual; procedure Render(W, H: Integer); virtual; function InputSize: TSize; function InputTexture: TTexture; function TargetTexture: TTexture; public constructor Create; virtual; destructor Destroy; override; class procedure UnInitialize; class function FilterAttr: TFilterRec; virtual; { Class static method for C++ access } class function FilterAttrForClass(C: TFilterClass): TFilterRec; static; procedure Apply; virtual; procedure ApplyWithoutCopyToOutput; property ValuesAsBitmap[const Index: string]: TBitmap read GetFilterValuesAsBitmap write SetFilterValuesAsBitmap; property ValuesAsTexture[const Index: string]: TTexture read GetFilterValuesAsTexture write SetFilterValuesAsTexture; property ValuesAsPoint[const Index: string]: TPointF read GetFilterValuesAsPoint write SetFilterValuesAsPoint; property ValuesAsFloat[const Index: string]: Single read GetFilterValuesAsFloat write SetFilterValuesAsFloat; property ValuesAsColor[const Index: string]: TAlphaColor read GetFilterValuesAsColor write SetFilterValuesAsColor; property InputFilter: TFilter read FInputFilter write SetInputFilter; end; TFilterClassDict = TDictionary<TFilterClass, string>; TFilterManager = class sealed strict private type TContextRec = record Texture: TTexture; Context: TContext3D; end; strict private class var FFilterList: TFilterClassDict; class var FContextList: TList<TContextRec>; class var FCurrentContext: Integer; class function GetFilterContext: TContext3D; static; class function GetFilterTexture: TTexture; static; class procedure SetCurrentContext(const Value: Integer); static; class function GetContextCount: Integer; static; class procedure SetContextCount(const Value: Integer); static; public // Reserved for internal use only - do not call directly! class procedure UnInitialize; // Register a filter in category class procedure RegisterFilter(const Category: string; Filter: TFilterClass); // Return filter class function FilterByName(const AName: string): TFilter; class function FilterClassByName(const AName: string): TFilterClass; // Categoties class procedure FillCategory(AList: TStrings); class procedure FillFiltersInCategory(const Category: string; AList: TStrings); // Context class procedure ResizeContext(Width, Height: Integer); class function GetTexture(const Index: Integer): TTexture; class property CurrentContext: Integer read FCurrentContext write SetCurrentContext; class property ContextCount: Integer read GetContextCount write SetContextCount; class property FilterContext: TContext3D read GetFilterContext; class property FilterTexture: TTexture read GetFilterTexture; end; implementation uses System.Math.Vectors, System.TypInfo, System.SysUtils, FMX.Materials, FMX.Surfaces; {$R *.res} { TFilterValueRec } constructor TFilterValueRec.Create(const AName, ADesc: string; AType: TFilterValueType; ADefault, AMin, AMax: TValue); begin Self.Name := AName; Self.Desc := ADesc; Self.ValueType := AType; Self.Value := ADefault; Self.Default := ADefault; Self.Min := AMin; Self.Max := AMax; end; constructor TFilterValueRec.Create(const AName, ADesc: string; ADefault: TAlphaColor); begin Self.Name := AName; Self.Desc := ADesc; Self.ValueType := TFilterValueType.Color; Self.Value := TValue.From<TAlphaColor>(ADefault); Self.Default := TValue.From<TAlphaColor>(ADefault); end; constructor TFilterValueRec.Create(const AName, ADesc: string; ADefault, AMin, AMax: Single); begin Self.Name := AName; Self.Desc := ADesc; Self.ValueType := TFilterValueType.Float; Self.Value := ADefault; Self.Default := ADefault; Self.Min := AMin; Self.Max := AMax; end; constructor TFilterValueRec.Create(const AName, ADesc: string; ADefault, AMin, AMax: TPointF); begin Self.Name := AName; Self.Desc := ADesc; Self.ValueType := TFilterValueType.Point; Self.Value := TValue.From<TPointF>(ADefault); Self.Default := TValue.From<TPointF>(ADefault); Self.Min := TValue.From<TPointF>(AMin); Self.Max := TValue.From<TPointF>(AMax); end; constructor TFilterValueRec.Create(const AName, ADesc: string; AType: TFilterValueType); begin Self.Name := AName; Self.Desc := ADesc; Self.ValueType := AType; end; { TFilterRec } constructor TFilterRec.Create(const AName, ADesc: string; AValues: array of TFilterValueRec); var i: Integer; begin Self.Name := AName; Self.Desc := ADesc; SetLength(Self.Values, Length(AValues)); for i := 0 to High(AValues) do Self.Values[i] := AValues[i]; end; { TFilterManager } class function TFilterManager.FilterByName(const AName: string): TFilter; var f: TFilterClass; begin Result := nil; if FFilterList = nil then Exit; for f in FFilterList.Keys do if CompareText(f.FilterAttr.Name, AName) = 0 then begin Result := f.Create; Exit; end; end; class function TFilterManager.FilterClassByName(const AName: string): TFilterClass; var f: TFilterClass; begin Result := nil; if FFilterList = nil then Exit; for f in FFilterList.Keys do if CompareText(f.FilterAttr.Name, AName) = 0 then begin Result := f; Exit; end; end; class function TFilterManager.GetContextCount: Integer; begin if Assigned(FContextList) then Result := FContextList.Count else Result := 0; end; class function TFilterManager.GetFilterContext: TContext3D; begin if Assigned(FContextList) then Result := FContextList[FCurrentContext].Context else Result := nil; end; class function TFilterManager.GetFilterTexture: TTexture; begin if Assigned(FContextList) then Result := FContextList[FCurrentContext].Texture else Result := nil; end; class function TFilterManager.GetTexture(const Index: Integer): TTexture; begin if Assigned(FContextList) and (Index < FContextList.Count) then Result := FContextList[Index].Texture else Result := nil; end; class procedure TFilterManager.RegisterFilter(const Category: string; Filter: TFilterClass); begin if FFilterList = nil then begin FFilterList := TFilterClassDict.Create; end; FFilterList.Add(Filter, Category); end; class procedure TFilterManager.ResizeContext(Width, Height: Integer); var I: Integer; Rec: TContextRec; CurWidth, CurHeight: Integer; begin if not Assigned(FContextList) then FContextList := TList<TContextRec>.Create; CurWidth := 0; CurHeight := 0; for I := 0 to FContextList.Count - 1 do begin Rec := FContextList[I]; if Assigned(Rec.Context) then Rec.Context.DisposeOf; if Assigned(Rec.Texture) then begin if Rec.Texture.Width > CurWidth then CurWidth := Rec.Texture.Width; if Rec.Texture.Height > CurHeight then CurHeight := Rec.Texture.Height; Rec.Texture.DisposeOf; end; Rec.Texture := nil; Rec.Context := nil; FContextList[I] := Rec; end; if Width > CurWidth then CurWidth := Width; if Height > CurHeight then CurHeight := Height; for I := 0 to FContextList.Count - 1 do begin Rec.Texture := TTexture.Create; Rec.Texture.SetSize(CurWidth, CurHeight); Rec.Texture.Style := [TTextureStyle.RenderTarget]; Rec.Context := TContextManager.CreateFromTexture(Rec.Texture, TMultisample.None, False); FContextList[I] := Rec; end; end; class procedure TFilterManager.SetContextCount(const Value: Integer); begin if not Assigned(FContextList) then FContextList := TList<TContextRec>.Create; FContextList.Count := Value; end; class procedure TFilterManager.SetCurrentContext(const Value: Integer); begin FCurrentContext := Value; if not Assigned(FContextList) then FContextList := TList<TContextRec>.Create; if (FCurrentContext > FContextList.Count) then FContextList.Count := FCurrentContext; end; class procedure TFilterManager.FillCategory(AList: TStrings); var s: string; begin AList.Clear; if FFilterList = nil then Exit; for s in FFilterList.Values do if AList.IndexOf(s) < 0 then AList.Add(s); end; class procedure TFilterManager.FillFiltersInCategory(const Category: string; AList: TStrings); var pair: TPair<TFilterClass, string>; begin AList.Clear; if FFilterList = nil then Exit; for pair in FFilterList do if pair.Value = Category then AList.Add(pair.Key.FilterAttr.Name); end; class procedure TFilterManager.UnInitialize; var I: Integer; Rec: TContextRec; begin TFilter.UnInitialize; if Assigned(FContextList) then for I := 0 to FContextList.Count - 1 do begin Rec := FContextList[I]; FreeAndNil(Rec.Context); FreeAndNil(Rec.Texture); end; FreeAndNil(FContextList); FreeAndNil(FFilterList); end; { TFilterMaterial } type TFilterMaterial = class(TMaterial) private FFilter: TFilter; procedure SetFilter(const Value: TFilter); protected procedure DoApply(const Context: TContext3D); override; procedure DoInitialize; override; class function DoGetMaterialProperty(const Prop: TMaterial.TProperty): string; override; public property Filter: TFilter write SetFilter; end; { TFilterMaterial } class function TFilterMaterial.DoGetMaterialProperty(const Prop: TMaterial.TProperty): string; begin case Prop of TProperty.ModelViewProjection: Result := 'MVPMatrix'; else Result := ''; end; end; procedure TFilterMaterial.DoInitialize; begin end; procedure TFilterMaterial.DoApply(const Context: TContext3D); begin // Shaders FFilter.LoadShaders; // Textures FFilter.LoadTextures; end; procedure TFilterMaterial.SetFilter(const Value: TFilter); begin FFilter := Value; end; { TFilter } constructor TFilter.Create; begin inherited Create; FVertexShader := TShaderManager.RegisterShaderFromData('filter.fvs', TContextShaderKind.VertexShader, '', [ TContextShaderSource.Create(TContextShaderArch.DX9, [ $00, $02, $FE, $FF, $FE, $FF, $1F, $00, $43, $54, $41, $42, $1C, $00, $00, $00, $53, $00, $00, $00, $00, $02, $FE, $FF, $01, $00, $00, $00, $1C, $00, $00, $00, $00, $01, $00, $20, $4C, $00, $00, $00, $30, $00, $00, $00, $02, $00, $00, $00, $04, $00, $00, $00, $3C, $00, $00, $00, $00, $00, $00, $00, $4D, $56, $50, $4D, $61, $74, $72, $69, $78, $00, $AB, $AB, $03, $00, $03, $00, $04, $00, $04, $00, $01, $00, $00, $00, $00, $00, $00, $00, $76, $73, $5F, $32, $5F, $30, $00, $4D, $69, $63, $72, $6F, $73, $6F, $66, $74, $20, $28, $52, $29, $20, $44, $33, $44, $58, $39, $20, $53, $68, $61, $64, $65, $72, $20, $43, $6F, $6D, $70, $69, $6C, $65, $72, $20, $00, $1F, $00, $00, $02, $00, $00, $00, $80, $00, $00, $0F, $90, $1F, $00, $00, $02, $05, $00, $00, $80, $01, $00, $0F, $90, $05, $00, $00, $03, $00, $00, $0F, $80, $00, $00, $55, $90, $01, $00, $E4, $A0, $04, $00, $00, $04, $00, $00, $0F, $80, $00, $00, $E4, $A0, $00, $00, $00, $90, $00, $00, $E4, $80, $04, $00, $00, $04, $00, $00, $0F, $80, $02, $00, $E4, $A0, $00, $00, $AA, $90, $00, $00, $E4, $80, $02, $00, $00, $03, $00, $00, $0F, $C0, $00, $00, $E4, $80, $03, $00, $E4, $A0, $01, $00, $00, $02, $00, $00, $03, $E0, $01, $00, $E4, $90, $FF, $FF, $00, $00], [ TContextShaderVariable.Create('MVPMatrix', TContextShaderVariableKind.Matrix, 0, 4)] ), TContextShaderSource.Create(TContextShaderArch.DX11_level_9, [ $44, $58, $42, $43, $F8, $1F, $8F, $3D, $4B, $A9, $C9, $45, $B4, $6C, $29, $4E, $9F, $CF, $27, $39, $01, $00, $00, $00, $04, $04, $00, $00, $06, $00, $00, $00, $38, $00, $00, $00, $08, $01, $00, $00, $0C, $02, $00, $00, $88, $02, $00, $00, $58, $03, $00, $00, $AC, $03, $00, $00, $41, $6F, $6E, $39, $C8, $00, $00, $00, $C8, $00, $00, $00, $00, $02, $FE, $FF, $94, $00, $00, $00, $34, $00, $00, $00, $01, $00, $24, $00, $00, $00, $30, $00, $00, $00, $30, $00, $00, $00, $24, $00, $01, $00, $30, $00, $00, $00, $00, $00, $04, $00, $01, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $02, $FE, $FF, $1F, $00, $00, $02, $05, $00, $00, $80, $00, $00, $0F, $90, $1F, $00, $00, $02, $05, $00, $01, $80, $01, $00, $0F, $90, $05, $00, $00, $03, $00, $00, $0F, $80, $00, $00, $55, $90, $02, $00, $E4, $A0, $04, $00, $00, $04, $00, $00, $0F, $80, $01, $00, $E4, $A0, $00, $00, $00, $90, $00, $00, $E4, $80, $04, $00, $00, $04, $00, $00, $0F, $80, $03, $00, $E4, $A0, $00, $00, $AA, $90, $00, $00, $E4, $80, $02, $00, $00, $03, $00, $00, $0F, $80, $00, $00, $E4, $80, $04, $00, $E4, $A0, $04, $00, $00, $04, $00, $00, $03, $C0, $00, $00, $FF, $80, $00, $00, $E4, $A0, $00, $00, $E4, $80, $01, $00, $00, $02, $00, $00, $0C, $C0, $00, $00, $E4, $80, $01, $00, $00, $02, $00, $00, $03, $E0, $01, $00, $E4, $90, $FF, $FF, $00, $00, $53, $48, $44, $52, $FC, $00, $00, $00, $40, $00, $01, $00, $3F, $00, $00, $00, $59, $00, $00, $04, $46, $8E, $20, $00, $00, $00, $00, $00, $04, $00, $00, $00, $5F, $00, $00, $03, $72, $10, $10, $00, $00, $00, $00, $00, $5F, $00, $00, $03, $32, $10, $10, $00, $01, $00, $00, $00, $65, $00, $00, $03, $32, $20, $10, $00, $00, $00, $00, $00, $67, $00, $00, $04, $F2, $20, $10, $00, $01, $00, $00, $00, $01, $00, $00, $00, $68, $00, $00, $02, $01, $00, $00, $00, $36, $00, $00, $05, $32, $20, $10, $00, $00, $00, $00, $00, $46, $10, $10, $00, $01, $00, $00, $00, $38, $00, $00, $08, $F2, $00, $10, $00, $00, $00, $00, $00, $56, $15, $10, $00, $00, $00, $00, $00, $46, $8E, $20, $00, $00, $00, $00, $00, $01, $00, $00, $00, $32, $00, $00, $0A, $F2, $00, $10, $00, $00, $00, $00, $00, $46, $8E, $20, $00, $00, $00, $00, $00, $00, $00, $00, $00, $06, $10, $10, $00, $00, $00, $00, $00, $46, $0E, $10, $00, $00, $00, $00, $00, $32, $00, $00, $0A, $F2, $00, $10, $00, $00, $00, $00, $00, $46, $8E, $20, $00, $00, $00, $00, $00, $02, $00, $00, $00, $A6, $1A, $10, $00, $00, $00, $00, $00, $46, $0E, $10, $00, $00, $00, $00, $00, $00, $00, $00, $08, $F2, $20, $10, $00, $01, $00, $00, $00, $46, $0E, $10, $00, $00, $00, $00, $00, $46, $8E, $20, $00, $00, $00, $00, $00, $03, $00, $00, $00, $3E, $00, $00, $01, $53, $54, $41, $54, $74, $00, $00, $00, $06, $00, $00, $00, $01, $00, $00, $00, $00, $00, $00, $00, $04, $00, $00, $00, $02, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $01, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $01, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $52, $44, $45, $46, $C8, $00, $00, $00, $01, $00, $00, $00, $48, $00, $00, $00, $01, $00, $00, $00, $1C, $00, $00, $00, $00, $04, $FE, $FF, $00, $11, $00, $00, $94, $00, $00, $00, $3C, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $01, $00, $00, $00, $00, $00, $00, $00, $24, $47, $6C, $6F, $62, $61, $6C, $73, $00, $AB, $AB, $AB, $3C, $00, $00, $00, $01, $00, $00, $00, $60, $00, $00, $00, $40, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $78, $00, $00, $00, $00, $00, $00, $00, $40, $00, $00, $00, $02, $00, $00, $00, $84, $00, $00, $00, $00, $00, $00, $00, $4D, $56, $50, $4D, $61, $74, $72, $69, $78, $00, $AB, $AB, $03, $00, $03, $00, $04, $00, $04, $00, $00, $00, $00, $00, $00, $00, $00, $00, $4D, $69, $63, $72, $6F, $73, $6F, $66, $74, $20, $28, $52, $29, $20, $48, $4C, $53, $4C, $20, $53, $68, $61, $64, $65, $72, $20, $43, $6F, $6D, $70, $69, $6C, $65, $72, $20, $39, $2E, $32, $36, $2E, $39, $35, $32, $2E, $32, $38, $34, $34, $00, $AB, $AB, $AB, $49, $53, $47, $4E, $4C, $00, $00, $00, $02, $00, $00, $00, $08, $00, $00, $00, $38, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $03, $00, $00, $00, $00, $00, $00, $00, $07, $07, $00, $00, $41, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $03, $00, $00, $00, $01, $00, $00, $00, $03, $03, $00, $00, $50, $4F, $53, $49, $54, $49, $4F, $4E, $00, $54, $45, $58, $43, $4F, $4F, $52, $44, $00, $AB, $AB, $4F, $53, $47, $4E, $50, $00, $00, $00, $02, $00, $00, $00, $08, $00, $00, $00, $38, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $03, $00, $00, $00, $00, $00, $00, $00, $03, $0C, $00, $00, $41, $00, $00, $00, $00, $00, $00, $00, $01, $00, $00, $00, $03, $00, $00, $00, $01, $00, $00, $00, $0F, $00, $00, $00, $54, $45, $58, $43, $4F, $4F, $52, $44, $00, $53, $56, $5F, $50, $6F, $73, $69, $74, $69, $6F, $6E, $00, $AB, $AB, $AB], [ TContextShaderVariable.Create('MVPMatrix', TContextShaderVariableKind.Matrix, 0, 64)] ), TContextShaderSource.Create(TContextShaderArch.GLSL, [ $61, $74, $74, $72, $69, $62, $75, $74, $65, $20, $76, $65, $63, $32, $20, $61, $5F, $54, $65, $78, $43, $6F, $6F, $72, $64, $30, $3B, $0D, $0A, $61, $74, $74, $72, $69, $62, $75, $74, $65, $20, $76, $65, $63, $33, $20, $61, $5F, $50, $6F, $73, $69, $74, $69, $6F, $6E, $3B, $0D, $0A, $76, $61, $72, $79, $69, $6E, $67, $20, $76, $65, $63, $34, $20, $54, $45, $58, $30, $3B, $0D, $0A, $76, $65, $63, $34, $20, $5F, $6F, $5F, $70, $6F, $73, $31, $3B, $0D, $0A, $76, $65, $63, $32, $20, $5F, $6F, $5F, $74, $65, $78, $63, $6F, $6F, $72, $64, $30, $31, $3B, $0D, $0A, $76, $65, $63, $34, $20, $5F, $72, $30, $30, $30, $33, $3B, $0D, $0A, $76, $65, $63, $34, $20, $5F, $76, $30, $30, $30, $33, $3B, $0D, $0A, $75, $6E, $69, $66, $6F, $72, $6D, $20, $76, $65, $63, $34, $20, $5F, $4D, $56, $50, $4D, $61, $74, $72, $69, $78, $5B, $34, $5D, $3B, $0D, $0A, $76, $6F, $69, $64, $20, $6D, $61, $69, $6E, $28, $29, $0D, $0A, $7B, $0D, $0A, $20, $20, $20, $20, $5F, $76, $30, $30, $30, $33, $20, $3D, $20, $76, $65, $63, $34, $28, $61, $5F, $50, $6F, $73, $69, $74, $69, $6F, $6E, $2E, $78, $2C, $20, $61, $5F, $50, $6F, $73, $69, $74, $69, $6F, $6E, $2E, $79, $2C, $20, $61, $5F, $50, $6F, $73, $69, $74, $69, $6F, $6E, $2E, $7A, $2C, $20, $31, $2E, $30, $29, $3B, $0D, $0A, $20, $20, $20, $20, $5F, $72, $30, $30, $30, $33, $2E, $78, $20, $3D, $20, $64, $6F, $74, $28, $5F, $4D, $56, $50, $4D, $61, $74, $72, $69, $78, $5B, $30, $5D, $2C, $20, $5F, $76, $30, $30, $30, $33, $29, $3B, $0D, $0A, $20, $20, $20, $20, $5F, $72, $30, $30, $30, $33, $2E, $79, $20, $3D, $20, $64, $6F, $74, $28, $5F, $4D, $56, $50, $4D, $61, $74, $72, $69, $78, $5B, $31, $5D, $2C, $20, $5F, $76, $30, $30, $30, $33, $29, $3B, $0D, $0A, $20, $20, $20, $20, $5F, $72, $30, $30, $30, $33, $2E, $7A, $20, $3D, $20, $64, $6F, $74, $28, $5F, $4D, $56, $50, $4D, $61, $74, $72, $69, $78, $5B, $32, $5D, $2C, $20, $5F, $76, $30, $30, $30, $33, $29, $3B, $0D, $0A, $20, $20, $20, $20, $5F, $72, $30, $30, $30, $33, $2E, $77, $20, $3D, $20, $64, $6F, $74, $28, $5F, $4D, $56, $50, $4D, $61, $74, $72, $69, $78, $5B, $33, $5D, $2C, $20, $5F, $76, $30, $30, $30, $33, $29, $3B, $0D, $0A, $20, $20, $20, $20, $5F, $6F, $5F, $70, $6F, $73, $31, $20, $3D, $20, $5F, $72, $30, $30, $30, $33, $3B, $0D, $0A, $20, $20, $20, $20, $5F, $6F, $5F, $74, $65, $78, $63, $6F, $6F, $72, $64, $30, $31, $20, $3D, $20, $61, $5F, $54, $65, $78, $43, $6F, $6F, $72, $64, $30, $2E, $78, $79, $3B, $0D, $0A, $20, $20, $20, $20, $54, $45, $58, $30, $2E, $78, $79, $20, $3D, $20, $61, $5F, $54, $65, $78, $43, $6F, $6F, $72, $64, $30, $2E, $78, $79, $3B, $0D, $0A, $20, $20, $20, $20, $67, $6C, $5F, $50, $6F, $73, $69, $74, $69, $6F, $6E, $20, $3D, $20, $5F, $72, $30, $30, $30, $33, $3B, $0D, $0A, $7D, $20, $0D, $0A], [ TContextShaderVariable.Create('MVPMatrix', TContextShaderVariableKind.Matrix, 0, 4)] ) ]); SetLength(FShaders, 10); FPassCount := 1; FValues := FilterAttr.Values; SetLength(FValues, Length(FValues) + 2); FValues[High(FValues) - 1] := TFilterValueRec.Create('Input', '', TFilterValueType.Bitmap, '', '', ''); FValues[High(FValues)] := TFilterValueRec.Create('Output', '', TFilterValueType.Bitmap, '', '', ''); FModified := True; end; destructor TFilter.Destroy; begin if (FInputBitmap <> nil) and not (TCanvasStyle.NeedGPUSurface in TCanvasManager.DefaultCanvas.GetCanvasStyle) then FInput.Free; if (FTargetBitmap <> nil) and not (TCanvasStyle.NeedGPUSurface in TCanvasManager.DefaultCanvas.GetCanvasStyle) then FTarget.Free; FreeAndNil(FPassInputRTContext); FreeAndNil(FPassInputRT); FreeAndNil(FInputRTContext); FreeAndNil(FInputRT); FreeAndNil(FTargetRTContext); FreeAndNil(FTargetRT); FreeAndNil(FOutputBitmap); inherited; end; class procedure TFilter.UnInitialize; begin FreeAndNil(FNoise); end; class function TFilter.FilterAttr: TFilterRec; begin FillChar(Result, SizeOf(Result), 0); end; class function TFilter.FilterAttrForClass(C: TFilterClass): TFilterRec; begin Result := C.FilterAttr; end; function TFilter.GetFilterValues(const Index: string): TValue; var I: Integer; begin for I := 0 to High(FValues) do if CompareText(FValues[I].Name, Index) = 0 then begin if CompareText(FValues[I].Name, 'Output') = 0 then begin if not FProcessing and FModified then Apply; Result := TFilterManager.GetTexture(FPass); FValues[I].Value := Result; Exit; end; Result := FValues[I].Value; Exit; end; Result := TValue.Empty; end; procedure TFilter.SetFilterValues(const Index: string; Value: TValue); var I: Integer; begin for I := 0 to High(FValues) do if CompareText(FValues[I].Name, Index) = 0 then begin case FValues[I].ValueType of TFilterValueType.Float: begin if Value.AsExtended < FValues[I].Min.AsExtended then Value := FValues[I].Min.AsExtended; if Value.AsExtended > FValues[I].Max.AsExtended then Value := FValues[I].Max.AsExtended; FValues[I].Value := Value end; TFilterValueType.Point: begin FValues[I].Value := Value end; TFilterValueType.Color: begin FValues[I].Value := Value; end; TFilterValueType.Bitmap: begin if Value.IsObject and ((Value.AsObject is TBitmap) or (Value.AsObject is TTexture)) then begin if CompareText(Index, 'Output') = 0 then Exit; FValues[I].Value := Value; if CompareText(Index, 'Input') = 0 then begin if Value.AsObject is TBitmap then begin FInputBitmap := TBitmap(Value.AsObject); if not (TCanvasStyle.NeedGPUSurface in TCanvasManager.DefaultCanvas.GetCanvasStyle) then FreeAndNil(FInput); FInput := TContextManager.DefaultContextClass.BitmapToTexture(FInputBitmap); end; if Value.AsObject is TTexture then FInput := TTexture(Value.AsObject); end else if CompareText(Index, 'Target') = 0 then begin if Value.AsObject is TBitmap then begin FTargetBitmap := TBitmap(Value.AsObject); if not (TCanvasStyle.NeedGPUSurface in TCanvasManager.DefaultCanvas.GetCanvasStyle) then FreeAndNil(FTarget); FTarget := TContextManager.DefaultContextClass.BitmapToTexture(FTargetBitmap); end; if Value.AsObject is TTexture then FTarget := TTexture(Value.AsObject); end else if Value.AsObject is TBitmap then begin FValues[I].Bitmap := TBitmap(Value.AsObject); FValues[I].Value := TContextManager.DefaultContextClass.BitmapToTexture(TBitmap(Value.AsObject)); end; end; end; end; FModified := True; Exit; end; end; function TFilter.GetFilterValuesAsColor(const Index: string): TAlphaColor; begin Result := Values[Index].AsType<TAlphaColor>; end; procedure TFilter.SetFilterValuesAsBitmap(const Index: string; const Value: TBitmap); begin Values[Index] := Value; end; procedure TFilter.SetFilterValuesAsColor(const Index: string; const Value: TAlphaColor); begin Values[Index] := TValue.From<TAlphaColor>(Value); end; function TFilter.GetFilterValuesAsPoint(const Index: string): TPointF; begin Result := Values[Index].AsType<TPointF>; end; function TFilter.GetFilterValuesAsBitmap(const Index: string): TBitmap; begin if SameText(Index, 'Output') then begin // real copy to output bitmap if FOutputBitmap = nil then FOutputBitmap := TBitmap.Create(0, 0); Values[Index]; // apply Result := FOutputBitmap; end else Result := nil; end; function TFilter.GetFilterValuesAsTexture(const Index: string): TTexture; begin if not Values[Index].IsEmpty then Result := TTexture(Values[Index].AsObject) else Result := nil; end; function TFilter.GetFilterValuesAsFloat(const Index: string): Single; begin Result := Values[Index].AsType<Single>; end; procedure TFilter.SetFilterValuesAsPoint(const Index: string; const Value: TPointF); begin Values[Index] := TValue.From<TPointF>(Value); end; procedure TFilter.SetFilterValuesAsTexture(const Index: string; const Value: TTexture); begin Values[Index] := Value; end; procedure TFilter.SetFilterValuesAsFloat(const Index: string; const Value: Single); begin Values[Index] := TValue.From<Single>(Value); end; procedure TFilter.SetInputFilter(const Value: TFilter); begin FInputFilter := Value; FModified := True; end; procedure TFilter.LoadShaders; var i: Integer; C: TAlphaColorRec; begin if FShaders[FPass] <> nil then begin // Shaders TFilterManager.FilterContext.SetShaders(FVertexShader, FShaders[FPass]); // Params for i := 0 to High(FValues) do begin case FValues[I].ValueType of TFilterValueType.Bitmap: ; TFilterValueType.Float: TFilterManager.FilterContext.SetShaderVariable(FValues[I].Name, [Vector3D(FValues[I].Value.AsExtended, FValues[I].Value.AsExtended, FValues[I].Value.AsExtended, FValues[I].Value.AsExtended)]); TFilterValueType.Point: if (InputSize.Width > 0) and (InputSize.Height > 0) then begin if TContextStyle.RenderTargetFlipped in TFilterManager.FilterContext.Style then TFilterManager.FilterContext.SetShaderVariable(FValues[I].Name, [Vector3D(FValues[I].Value.AsType<TPointF>.x / InputSize.Width, (InputSize.Height - FValues[I].Value.AsType<TPointF>.y) / InputSize.Height, 0, 0)]) else TFilterManager.FilterContext.SetShaderVariable(FValues[I].Name, [Vector3D(FValues[I].Value.AsType<TPointF>.x / InputSize.Width, FValues[I].Value.AsType<TPointF>.y / InputSize.Height, 0, 0)]); end; TFilterValueType.Color: begin C := TAlphaColorRec(FValues[I].Value.AsType<TAlphaColor>()); TFilterManager.FilterContext.SetShaderVariable(FValues[I].Name, [Vector3D(C.R / $FF, C.G / $FF, C.B / $FF, C.A / $FF)]); end; end; end; end; end; procedure TFilter.RenderTextureToContext(const Context: TContext3D; const Texture: TTexture; const ARect: TRect; const DstPos: TPoint); var Ver: TVertexBuffer; Ind: TIndexBuffer; Mat: TTextureMaterial; begin if Context.BeginScene then try Ver := TVertexBuffer.Create([TVertexFormat.Vertex, TVertexFormat.TexCoord0], 4); Ver.Vertices[0] := Point3D(ARect.Left, ARect.Top, 0); Ver.Vertices[1] := Point3D(ARect.Right, ARect.Top, 0); Ver.Vertices[2] := Point3D(ARect.Right, ARect.Bottom, 0); Ver.Vertices[3] := Point3D(ARect.Left, ARect.Bottom, 0); Ver.TexCoord0[0] := PointF((DstPos.X + ARect.Left) / Texture.Width, (DstPos.Y + ARect.Top) / Texture.Height); Ver.TexCoord0[1] := PointF((DstPos.X + ARect.Right) / Texture.Width, (DstPos.Y + ARect.Top) / Texture.Height); Ver.TexCoord0[2] := PointF((DstPos.X + ARect.Right) / Texture.Width, (DstPos.Y + ARect.Bottom) / Texture.Height); Ver.TexCoord0[3] := PointF((DstPos.X + ARect.Left) / Texture.Width, (DstPos.Y + ARect.Bottom) / Texture.Height); Ind := TIndexBuffer.Create(6); Ind[0] := 0; Ind[1] := 1; Ind[2] := 3; Ind[3] := 3; Ind[4] := 1; Ind[5] := 2; Mat := TTextureMaterial.Create; Mat.Texture := Texture; Context.SetMatrix(TMatrix3D.Identity); Context.SetContextState(TContextState.cs2DScene); Context.SetContextState(TContextState.csZWriteOff); Context.SetContextState(TContextState.csZTestOff); Context.SetContextState(TContextState.csAllFace); Context.SetContextState(TContextState.csAlphaBlendOff); Context.SetContextState(TContextState.csScissorOff); Context.Clear(0); Context.DrawTriangles(Ver, Ind, Mat, 1); Mat.Free; Ind.Free; Ver.Free; finally Context.EndScene; end; end; function TFilter.InputTexture: TTexture; begin //https://quality.embarcadero.com/browse/RSP-20825 //if TCanvasStyle.NeedGPUSurface in TCanvasManager.DefaultCanvas.GetCanvasStyle then // Result := TContextManager.DefaultContextClass.BitmapToTexture(FInputBitmap) //else Result := FInput; end; function TFilter.TargetTexture: TTexture; begin //https://quality.embarcadero.com/browse/RSP-20825 //if TCanvasStyle.NeedGPUSurface in TCanvasManager.DefaultCanvas.GetCanvasStyle then // Result := TContextManager.DefaultContextClass.BitmapToTexture(FTargetBitmap) //else Result := FTarget; end; procedure TFilter.LoadTextures; var I: Integer; begin if FPass = 0 then begin if (FInputFilter = nil) then begin if Assigned(FInputRT) then TFilterManager.FilterContext.SetShaderVariable('Input', FInputRT) else TFilterManager.FilterContext.SetShaderVariable('Input', InputTexture); end else TFilterManager.FilterContext.SetShaderVariable('Input', FInputRT); end else TFilterManager.FilterContext.SetShaderVariable('Input', FPassInputRT); if (FTarget <> nil) and not FTarget.IsEmpty then begin if Assigned(FTargetRT) then TFilterManager.FilterContext.SetShaderVariable('Target', FTargetRT) else TFilterManager.FilterContext.SetShaderVariable('Target', TargetTexture); end; if FNeedInternalSecondTex <> '' then TFilterManager.FilterContext.SetShaderVariable('Second', FNoise); { load another } for I := 0 to High(FValues) do begin if (FValues[I].ValueType = TFilterValueType.Bitmap) then begin if SameText(FValues[I].Name, 'input') then Continue; if SameText(FValues[I].Name, 'output') then Continue; if SameText(FValues[I].Name, 'second') then Continue; if SameText(FValues[I].Name, 'target') then Continue; end; if (FValues[I].ValueType = TFilterValueType.Bitmap) and not FValues[I].Value.IsEmpty and (FValues[I].Value.IsObject) and (FValues[I].Value.AsObject is TTexture) then begin if TCanvasStyle.NeedGPUSurface in TCanvasManager.DefaultCanvas.GetCanvasStyle then TFilterManager.FilterContext.SetShaderVariable(FValues[I].Name, TContextManager.DefaultContextClass.BitmapToTexture(FValues[I].Bitmap)) else TFilterManager.FilterContext.SetShaderVariable(FValues[I].Name, TTexture(FValues[I].Value.AsObject)); end; end; end; function TFilter.InputSize: TSize; begin if Assigned(FInputFilter) then Result := FInputFilter.FOutputSize else if Assigned(FInput) then Result := TSize.Create(FInput.Width, FInput.Height) else Result := TSize.Create(0, 0); end; procedure TFilter.CalcSize(var W, H: Integer); begin W := InputSize.Width; H := InputSize.Height; end; procedure TFilter.ApplyWithoutCopyToOutput; begin FNoCopyForOutput := True; try Apply; finally FNoCopyForOutput := False; end; end; procedure TFilter.Apply; var I, W, H: Integer; begin if not FModified then Exit; FProcessing := True; try // Prepare if (FInputFilter <> nil) then begin TFilter(FInputFilter).FNoCopyForOutput := True; FInputFilter.Apply; CalcSize(W, H); end else begin if (FInput = nil) then Exit; CalcSize(W, H); end; if W * H = 0 then Exit; FOutputSize := TSize.Create(W, H); // Correct size if TFilterManager.ContextCount < FPassCount then begin TFilterManager.ContextCount := FPassCount; TFilterManager.ResizeContext(W, H); end; if (TFilterManager.FilterContext = nil) or ((W > TFilterManager.FilterTexture.Width) or (H > TFilterManager.FilterTexture.Height)) then TFilterManager.ResizeContext(W, H); // Prepare textures if (FInputFilter = nil) then begin if FAntiAlise then begin if FInputBitmap <> nil then begin if FInputRT = nil then begin FInputRT := TTexture.Create; FInputRT.Style := [TTextureStyle.RenderTarget]; FInputRT.SetSize(FInput.Width + 2, FInput.Height + 2); FInputRTContext := TContextManager.CreateFromTexture(FInputRT, TMultisample.None, False); end; if (FInputRT.Width <> FInputBitmap.Width + 2) or (FInputRT.Height <> FInputBitmap.Height + 2) then begin FreeAndNil(FInputRTContext); FInputRT.SetSize(FInputBitmap.Width + 2, FInputBitmap.Height + 2); FInputRTContext := TContextManager.CreateFromTexture(FInputRT, TMultisample.None, False); end; RenderTextureToContext(FInputRTContext, InputTexture, TRect.Create(0, 0, FInput.Width, FInput.Height), TPoint.Create(1, 1)); end else begin if FInputRT = nil then begin FInputRT := TTexture.Create; FInputRT.Style := [TTextureStyle.RenderTarget]; FInputRT.SetSize(FInput.Width + 2, FInput.Height + 2); FInputRTContext := TContextManager.CreateFromTexture(FInputRT, TMultisample.None, False); end; if (FInputRT.Width <> FInput.Width + 2) or (FInputRT.Height <> FInput.Height + 2) then begin FreeAndNil(FInputRTContext); FInputRT.SetSize(FInput.Width + 2, FInput.Height + 2); FInputRTContext := TContextManager.CreateFromTexture(FInputRT, TMultisample.None, False); end; RenderTextureToContext(FInputRTContext, InputTexture, TRect.Create(0, 0, FInput.Width, FInput.Height), TPoint.Create(1, 1)); end; end else begin if not (TTextureStyle.RenderTarget in FInput.Style) and (TContextStyle.RenderTargetFlipped in TFilterManager.FilterContext.Style) then begin if FInputRT = nil then begin FInputRT := TTexture.Create; FInputRT.Style := [TTextureStyle.RenderTarget]; FInputRT.SetSize(FInput.Width, FInput.Height); FInputRTContext := TContextManager.CreateFromTexture(FInputRT, TMultisample.None, False); end; if (FInputRT.Width <> FInput.Width) or (FInputRT.Height <> FInput.Height) then begin FreeAndNil(FInputRTContext); FInputRT.SetSize(FInput.Width, FInput.Height); FInputRTContext := TContextManager.CreateFromTexture(FInputRT, TMultisample.None, False); end; RenderTextureToContext(FInputRTContext, InputTexture, TRect.Create(0, 0, FInput.Width, FInput.Height), TPoint.Zero); end; end; end else if Assigned(TFilterManager.FilterTexture) then begin if FInputRT = nil then begin FInputRT := TTexture.Create; FInputRT.Style := [TTextureStyle.RenderTarget]; FInputRT.SetSize(InputSize.Width, InputSize.Height); FInputRTContext := TContextManager.CreateFromTexture(FInputRT, TMultisample.None, False); end; if (FInputRT.Width <> InputSize.Width) or (FInputRT.Height <> InputSize.Height) then begin FreeAndNil(FInputRTContext); FInputRT.SetSize(InputSize.Width, InputSize.Height); FInputRTContext := TContextManager.CreateFromTexture(FInputRT, TMultisample.None, False); end; RenderTextureToContext(FInputRTContext, TFilterManager.FilterTexture, TRect.Create(0, 0, InputSize.Width, InputSize.Height), TPoint.Zero); end; if (FTarget <> nil) and not FTarget.IsEmpty then begin if not (TTextureStyle.RenderTarget in FTarget.Style) and (TContextStyle.RenderTargetFlipped in TFilterManager.FilterContext.Style) then begin if FTargetRT = nil then begin FTargetRT := TTexture.Create; FTargetRT.Style := [TTextureStyle.RenderTarget]; FTargetRT.SetSize(FTarget.Width, FTarget.Height); FTargetRTContext := TContextManager.CreateFromTexture(FTargetRT, TMultisample.None, False); end; if (FTargetRT.Width <> FTarget.Width) or (FTargetRT.Height <> FTarget.Height) then begin FreeAndNil(FTargetRTContext); FTargetRT.SetSize(FTarget.Width, FTarget.Height); FTargetRTContext := TContextManager.CreateFromTexture(FTargetRT, TMultisample.None, False); end; RenderTextureToContext(FTargetRTContext, TargetTexture, TRect.Create(0, 0, FTarget.Width, FTarget.Height), TPoint.Zero); end; end; if FNeedInternalSecondTex <> '' then CreateNoise; // Process passes for i := 0 to FPassCount - 1 do begin FPass := i; if FPass > 0 then begin if FPassInputRT = nil then begin FPassInputRT := TTexture.Create; FPassInputRT.Style := [TTextureStyle.RenderTarget]; FPassInputRT.SetSize(W, H); FPassInputRTContext := TContextManager.CreateFromTexture(FPassInputRT, TMultisample.None, False); end; if (FPassInputRT.Width <> W) or (FPassInputRT.Height <> H) then begin FreeAndNil(FPassInputRTContext); FPassInputRT.SetSize(W, H); FPassInputRTContext := TContextManager.CreateFromTexture(FPassInputRT, TMultisample.None, False); end; RenderTextureToContext(FPassInputRTContext, TFilterManager.GetTexture(FPass - 1), TRect.Create(0, 0, FPassInputRT.Width, FPassInputRT.Height), TPoint.Zero); end; TFilterManager.CurrentContext := FPass; if TFilterManager.FilterContext.BeginScene then try TFilterManager.FilterContext.SetMatrix(TMatrix3D.Identity); TFilterManager.FilterContext.SetContextState(TContextState.cs2DScene); TFilterManager.FilterContext.SetContextState(TContextState.csZWriteOff); TFilterManager.FilterContext.SetContextState(TContextState.csZTestOff); TFilterManager.FilterContext.SetContextState(TContextState.csAllFace); TFilterManager.FilterContext.SetContextState(TContextState.csAlphaBlendOff); TFilterManager.FilterContext.SetContextState(TContextState.csScissorOff); TFilterManager.FilterContext.Clear(0); Render(W, H); finally TFilterManager.FilterContext.EndScene; end; // Copy result to output texture if not FNoCopyForOutput then begin if (FOutputBitmap <> nil) then begin FOutputBitmap.SetSize(FOutputSize.Width, FOutputSize.Height); TFilterManager.FilterContext.CopyToBitmap(FOutputBitmap, TRect.Create(0, 0, FOutputBitmap.Width, FOutputBitmap.Height)); end; end; end; finally if (FInputFilter <> nil) then begin TFilter(FInputFilter).FNoCopyForOutput := False; FInput := nil; end; FProcessing := False; FModified := False; end; end; function CreateTextureFromData(const Data: array of Byte): TTexture; var S: TStream; Surf: TBitmapSurface; begin Result := TTexture.Create; Result.Style := [TTextureStyle.Dynamic]; S := TMemoryStream.Create; try S.Write(Data[0], Length(Data)); S.Position := 0; Surf := TBitmapSurface.Create; try if TBitmapCodecManager.LoadFromStream(S, Surf) then Result.Assign(Surf) finally Surf.Free; end; finally S.Free; end; end; procedure TFilter.CreateNoise; var S: TStream; begin if FNeedInternalSecondTex = '' then Exit; if FNoise = nil then begin S := TResourceStream.Create(HInstance, FNeedInternalSecondTex, RT_RCDATA); try FNoise := TTexture.Create; FNoise.Style := [TTextureStyle.Dynamic]; FNoise.LoadFromStream(S); finally S.Free; end; end; end; function TFilter.CreateFilterMaterial: TMaterial; begin Result := TFilterMaterial.Create; TFilterMaterial(Result).Filter := Self; end; procedure TFilter.Render(W, H: Integer); var Ver: TVertexBuffer; Ind: TIndexBuffer; Mat: TMaterial; P: TPointF; begin // Fill Ver := TVertexBuffer.Create([TVertexFormat.Vertex, TVertexFormat.TexCoord0], 4); P := TFilterManager.FilterContext.PixelToPixelPolygonOffset; if FAntiAlise then begin Ver.Vertices[0] := Point3D(-1 + P.X, -1 + P.Y, 0); Ver.Vertices[1] := Point3D(W + 1 + P.X, -1 + P.Y, 0); Ver.Vertices[2] := Point3D(W + 1 + P.X, H + 1 + P.Y, 0); Ver.Vertices[3] := Point3D(-1 + P.X, H + 1 + P.Y, 0); end else begin Ver.Vertices[0] := Point3D(0 + P.X, 0 + P.Y, 0); Ver.Vertices[1] := Point3D(W + P.X, 0 + P.Y, 0); Ver.Vertices[2] := Point3D(W + P.X, H + P.Y, 0); Ver.Vertices[3] := Point3D(0 + P.X, H + P.Y, 0); end; if TContextStyle.RenderTargetFlipped in TFilterManager.FilterContext.Style then begin Ver.TexCoord0[0] := PointF(0.0, 1.0); Ver.TexCoord0[1] := PointF(1.0, 1.0); Ver.TexCoord0[2] := PointF(1.0, 0.0); Ver.TexCoord0[3] := PointF(0.0, 0.0); end else begin Ver.TexCoord0[0] := PointF(0.0, 0.0); Ver.TexCoord0[1] := PointF(1.0, 0.0); Ver.TexCoord0[2] := PointF(1.0, 1.0); Ver.TexCoord0[3] := PointF(0.0, 1.0); end; Ind := TIndexBuffer.Create(6); Ind[0] := 0; Ind[1] := 1; Ind[2] := 3; Ind[3] := 3; Ind[4] := 1; Ind[5] := 2; Mat := CreateFilterMaterial; TFilterManager.FilterContext.DrawTriangles(Ver, Ind, Mat, 1); Mat.Free; Ind.Free; Ver.Free; end; procedure RegisterAliases; begin AddEnumElementAliases(TypeInfo(TFilterValueType), ['vtFloat', 'vtPoint', 'vtColor', 'vtBitmap']); end; procedure UnregisterAliases; begin RemoveEnumElementAliases(TypeInfo(TFilterValueType)); end; initialization RegisterAliases; finalization UnregisterAliases; end.
40.333056
206
0.612139
47db58f7d59e4e2f45438a4d6f399b1147e9f959
2,697
pas
Pascal
windows/src/ext/jedi/jvcl/jvcl/archive/JvgStepLabel.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
219
2017-06-21T03:37:03.000Z
2022-03-27T12:09:28.000Z
windows/src/ext/jedi/jvcl/jvcl/archive/JvgStepLabel.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/archive/JvgStepLabel.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: JvgStepLabel.PAS, released on 2003-01-15. The Initial Developer of the Original Code is Andrey V. Chudin, [chudin@yandex.ru] Portions created by Andrey V. Chudin are Copyright (C) 2003 Andrey V. Chudin. All Rights Reserved. Contributor(s): Michael Beck [mbeck att bigfoot dott com]. 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: -----------------------------------------------------------------------------} // $Id$ {$I jvcl.inc} unit JvgStepLabel; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, JvComponent; type TJvgStepLabel = class(TJvGraphicControl) private FStepCount: Integer; FPassiveColor: TColor; FActiveColor: TColor; procedure SetStepCount(const Value: Integer); procedure WMPaint(var Msg: TWMPaint); message WM_PAINT; procedure SetActiveColor(const Value: TColor); procedure SetPassiveColor(const Value: TColor); public constructor Create(AOwner: TComponent); override; published property StepCount: Integer read FStepCount write SetStepCount default 4; property ActiveColor: TColor read FActiveColor write SetActiveColor default clWindowText; property PassiveColor: TColor read FPassiveColor write SetPassiveColor default clSilver; property Font; end; implementation constructor TJvgStepLabel.Create(AOwner: TComponent); begin inherited Create(AOwner); FStepCount := 4; FActiveColor := clWindowText; FPassiveColor := clSilver; end; procedure TJvgStepLabel.SetActiveColor(const Value: TColor); begin if FActiveColor <> Value then begin FActiveColor := Value; Invalidate; end; end; procedure TJvgStepLabel.SetPassiveColor(const Value: TColor); begin if FPassiveColor <> Value then begin FPassiveColor := Value; Invalidate; end; end; procedure TJvgStepLabel.SetStepCount(const Value: Integer); begin if Value >= 1 then FStepCount := Value; end; procedure TJvgStepLabel.WMPaint(var Msg: TWMPaint); var Caption: string; I: Integer; begin // StepCount; end; end.
27.242424
93
0.716722
fc3ea71456ed54a11da6774205b1e51b7c4f2276
14,584
pas
Pascal
Src/Graphics32/GR32_Dsgn_Bitmap.pas
ryujt/ryulib4delphi
1269afeb5d55d5d6710cfb1d744d5a1596583a96
[ "MIT" ]
18
2015-05-18T01:55:45.000Z
2019-05-03T03:23:52.000Z
Src/Graphics32/GR32_Dsgn_Bitmap.pas
ryujt/ryulib4delphi
1269afeb5d55d5d6710cfb1d744d5a1596583a96
[ "MIT" ]
null
null
null
Src/Graphics32/GR32_Dsgn_Bitmap.pas
ryujt/ryulib4delphi
1269afeb5d55d5d6710cfb1d744d5a1596583a96
[ "MIT" ]
19
2015-05-14T01:06:35.000Z
2019-06-02T05:19:00.000Z
unit GR32_Dsgn_Bitmap; (* ***** 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): * * ***** END LICENSE BLOCK ***** *) interface {$I GR32.inc} uses {$IFDEF FPC} LCLIntf, LCLType, RtlConsts, Buttons, LazIDEIntf, PropEdits, ComponentEditors, {$ELSE} Windows, ExtDlgs, ToolWin, Registry, ImgList, Consts, DesignIntf, DesignEditors, VCLEditors, {$ENDIF} Forms, Controls, ComCtrls, ExtCtrls, StdCtrls, Graphics, Dialogs, Menus, SysUtils, Classes, Clipbrd, GR32, GR32_Image, GR32_Layers, GR32_Filters; type TPictureEditorForm = class(TForm) AlphaSheet: TTabSheet; Bevel1: TBevel; Cancel: TButton; Clear: TToolButton; Copy: TToolButton; ImageList: TImageList; ImageSheet: TTabSheet; Label1: TLabel; Load: TToolButton; MagnCombo: TComboBox; mnClear: TMenuItem; mnCopy: TMenuItem; mnInvert: TMenuItem; mnLoad: TMenuItem; mnPaste: TMenuItem; mnSave: TMenuItem; mnSeparator: TMenuItem; mnSeparator2: TMenuItem; OKButton: TButton; PageControl: TPageControl; Panel1: TPanel; Panel2: TPanel; Paste: TToolButton; PopupMenu: TPopupMenu; Save: TToolButton; Timer: TTimer; ToolBar: TToolBar; ToolButton2: TToolButton; procedure LoadClick(Sender: TObject); procedure SaveClick(Sender: TObject); procedure ClearClick(Sender: TObject); procedure CopyClick(Sender: TObject); procedure PasteClick(Sender: TObject); procedure TimerTimer(Sender: TObject); procedure PopupMenuPopup(Sender: TObject); procedure mnInvertClick(Sender: TObject); procedure MagnComboChange(Sender: TObject); protected {$IFDEF PLATFORM_INDEPENDENT} OpenDialog: TOpenDialog; SaveDialog: TSaveDialog; {$ELSE} OpenDialog: TOpenPictureDialog; SaveDialog: TSavePictureDialog; {$ENDIF} AlphaChannel: TImage32; RGBChannels: TImage32; procedure AlphaChannelMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); procedure RGBChannelsMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); function CurrentImage: TImage32; public constructor Create(AOwner: TComponent); override; end; TBitmap32Editor = class(TComponent) private FBitmap32: TBitmap32; FPicDlg: TPictureEditorForm; procedure SetBitmap32(Value: TBitmap32); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function Execute: Boolean; property Bitmap32: TBitmap32 read FBitmap32 write SetBitmap32; end; TBitmap32Property = class(TClassProperty {$IFDEF EXT_PROP_EDIT} , ICustomPropertyDrawing {$IFDEF COMPILER2005_UP}, ICustomPropertyDrawing80{$ENDIF} {$ENDIF} ) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; function GetValue: string; override; procedure SetValue(const Value: string); override; {$IFDEF EXT_PROP_EDIT} { ICustomPropertyDrawing } procedure PropDrawName(ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); procedure PropDrawValue(Canvas: TCanvas; const ARect: TRect; ASelected: Boolean); {$IFDEF COMPILER2005_UP} { ICustomPropertyDrawing80 } function PropDrawNameRect(const ARect: TRect): TRect; function PropDrawValueRect(const ARect: TRect): TRect; {$ENDIF} {$ENDIF} end; TImage32Editor = class(TComponentEditor) public procedure ExecuteVerb(Index: Integer); override; function GetVerb(Index: Integer): string; override; function GetVerbCount: Integer; override; end; implementation uses GR32_Resamplers; {$IFDEF FPC} {$R *.lfm} {$ELSE} {$R *.dfm} {$ENDIF} { TPictureEditorForm } procedure TPictureEditorForm.LoadClick(Sender: TObject); var Picture: TPicture; DoAlpha: Boolean; S: string; begin if OpenDialog.Execute then begin Picture := TPicture.Create; try Picture.LoadFromFile(OpenDialog.Filename); DoAlpha := False; if (Picture.Graphic is TBitmap) and (Picture.Bitmap.PixelFormat = pf32Bit) then begin S := ExtractFileName(OpenDialog.FileName); S := '''' + S + ''' file contains RGB and Alpha channels.'#13#10 + 'Do you want to load all channels?'; case MessageDlg(S, mtConfirmation, mbYesNoCancel, 0) of mrYes: DoAlpha := True; mrCancel: Exit; end; end; if DoAlpha then begin RGBChannels.Bitmap.Assign(Picture.Bitmap); AlphaToGrayscale(AlphaChannel.Bitmap, RGBChannels.Bitmap); RGBChannels.Bitmap.ResetAlpha; end else with CurrentImage do begin Bitmap.Assign(Picture); if CurrentImage = AlphaChannel then ColorToGrayscale(Bitmap, Bitmap); end; finally Picture.Free; end; end; end; procedure TPictureEditorForm.SaveClick(Sender: TObject); var Picture: TPicture; begin Picture := TPicture.Create; try Picture.Bitmap.Assign(CurrentImage.Bitmap); Picture.Bitmap.PixelFormat := pf24Bit; if Picture.Graphic <> nil then begin with SaveDialog do begin DefaultExt := GraphicExtension(TGraphicClass(Picture.Graphic.ClassType)); Filter := GraphicFilter(TGraphicClass(Picture.Graphic.ClassType)); if Execute then Picture.SaveToFile(Filename); end; end; finally Picture.Free; end; end; procedure TPictureEditorForm.ClearClick(Sender: TObject); begin CurrentImage.Bitmap.Delete; end; procedure TPictureEditorForm.CopyClick(Sender: TObject); begin Clipboard.Assign(CurrentImage.Bitmap); end; procedure TPictureEditorForm.PasteClick(Sender: TObject); begin if Clipboard.HasFormat(CF_BITMAP) or Clipboard.HasFormat(CF_PICTURE) then CurrentImage.Bitmap.Assign(Clipboard); if CurrentImage = AlphaChannel then ColorToGrayscale(CurrentImage.Bitmap, CurrentImage.Bitmap); end; procedure TPictureEditorForm.TimerTimer(Sender: TObject); begin Save.Enabled := not CurrentImage.Bitmap.Empty; Clear.Enabled := Save.Enabled; Copy.Enabled := Save.Enabled; Paste.Enabled := Clipboard.HasFormat(CF_BITMAP) or Clipboard.HasFormat(CF_PICTURE); end; function TPictureEditorForm.CurrentImage: TImage32; begin if PageControl.ActivePage = ImageSheet then Result := RGBChannels else Result := AlphaChannel; end; procedure TPictureEditorForm.PopupMenuPopup(Sender: TObject); begin mnSave.Enabled := not CurrentImage.Bitmap.Empty; mnClear.Enabled := Save.Enabled; mnCopy.Enabled := Save.Enabled; mnInvert.Enabled := Save.Enabled; mnPaste.Enabled := Clipboard.HasFormat(CF_BITMAP) or Clipboard.HasFormat(CF_PICTURE); end; procedure TPictureEditorForm.mnInvertClick(Sender: TObject); begin InvertRGB(CurrentImage.Bitmap, CurrentImage.Bitmap); end; procedure TPictureEditorForm.MagnComboChange(Sender: TObject); const MAGN: array[0..6] of Integer = (25, 50, 100, 200, 400, 800, -1); var S: Integer; begin S := MAGN[MagnCombo.ItemIndex]; if S = -1 then begin RGBChannels.ScaleMode := smResize; AlphaChannel.ScaleMode := smResize; end else begin RGBChannels.ScaleMode := smScale; RGBChannels.Scale := S / 100; AlphaChannel.ScaleMode := smScale; AlphaChannel.Scale := S / 100; end; end; constructor TPictureEditorForm.Create(AOwner: TComponent); begin inherited; RGBChannels := TImage32.Create(Self); RGBChannels.Parent := ImageSheet; RGBChannels.Align := alClient; RGBChannels.OnMouseMove := RGBChannelsMouseMove; AlphaChannel := TImage32.Create(Self); AlphaChannel.Parent := AlphaSheet; AlphaChannel.Align := alClient; AlphaChannel.OnMouseMove := AlphaChannelMouseMove; {$IFDEF PLATFORM_INDEPENDENT} OpenDialog := TOpenDialog.Create(Self); SaveDialog := TSaveDialog.Create(Self); {$ELSE} OpenDialog := TOpenPictureDialog.Create(Self); SaveDialog := TSavePictureDialog.Create(Self); {$ENDIF} MagnCombo.ItemIndex := 2; OpenDialog.Filter := GraphicFilter(TGraphic); SaveDialog.Filter := GraphicFilter(TGraphic); end; { TBitmap32Editor } constructor TBitmap32Editor.Create(AOwner: TComponent); begin inherited; FBitmap32 := TBitmap32.Create; FPicDlg := TPictureEditorForm.Create(Self); end; destructor TBitmap32Editor.Destroy; begin FBitmap32.Free; FPicDlg.Free; inherited; end; function TBitmap32Editor.Execute: Boolean; var B: TBitmap32; begin FPicDlg.RGBChannels.Bitmap := FBitmap32; AlphaToGrayscale(FPicDlg.AlphaChannel.Bitmap, FBitmap32); Result := (FPicDlg.ShowModal = mrOK); if Result then begin FBitmap32.Assign(FPicDlg.RGBChannels.Bitmap); FBitmap32.ResetAlpha; if not FBitmap32.Empty and not FPicDlg.AlphaChannel.Bitmap.Empty then begin B := TBitmap32.Create; try B.SetSize(FBitmap32.Width, FBitmap32.Height); FPicDlg.AlphaChannel.Bitmap.DrawTo(B, Rect(0, 0, B.Width, B.Height)); IntensityToAlpha(FBitmap32, B); finally B.Free; end; end; end; end; procedure TBitmap32Editor.SetBitmap32(Value: TBitmap32); begin try FBitmap32.Assign(Value); except on E: Exception do ShowMessage(E.Message); end; end; { TBitmap32Property } procedure TBitmap32Property.Edit; var BitmapEditor: TBitmap32Editor; begin try BitmapEditor := TBitmap32Editor.Create(nil); try BitmapEditor.Bitmap32 := TBitmap32(Pointer(GetOrdValue)); if BitmapEditor.Execute then begin SetOrdValue(Longint(BitmapEditor.Bitmap32)); {$IFNDEF FPC} Designer.Modified; {$ENDIF} end; finally BitmapEditor.Free; end; except on E: Exception do ShowMessage(E.Message); end; end; function TBitmap32Property.GetAttributes: TPropertyAttributes; begin Result := [paDialog, paSubProperties]; end; function TBitmap32Property.GetValue: string; var Bitmap: TBitmap32; begin try Bitmap := TBitmap32(GetOrdValue); if (Bitmap = nil) or Bitmap.Empty then Result := srNone else Result := Format('%s [%d,%d]', [Bitmap.ClassName, Bitmap.Width, Bitmap.Height]); except on E: Exception do ShowMessage(E.Message); end; end; {$IFDEF EXT_PROP_EDIT} procedure TBitmap32Property.PropDrawValue(Canvas: TCanvas; const ARect: TRect; ASelected: Boolean); var Bitmap32: TBitmap32; TmpBitmap: TBitmap32; R: TRect; begin Bitmap32 := TBitmap32(GetOrdValue); if Bitmap32.Empty then DefaultPropertyDrawValue(Self, Canvas, ARect) else begin R := ARect; R.Right := R.Left + R.Bottom - R.Top; TmpBitmap := TBitmap32.Create; TmpBitmap.Width := R.Right - R.Left; TmpBitmap.Height := R.Bottom - R.Top; TDraftResampler.Create(TmpBitmap); TmpBitmap.Draw(TmpBitmap.BoundsRect, Bitmap32.BoundsRect, Bitmap32); TmpBitmap.DrawTo(Canvas.Handle, R, TmpBitmap.BoundsRect); TmpBitmap.Free; R.Left := R.Right; R.Right := ARect.Right; DefaultPropertyDrawValue(Self, Canvas, R); end; end; procedure TBitmap32Property.PropDrawName(ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); begin DefaultPropertyDrawName(Self, ACanvas, ARect); end; {$IFDEF COMPILER2005_UP} function TBitmap32Property.PropDrawNameRect(const ARect: TRect): TRect; begin Result := ARect; end; function TBitmap32Property.PropDrawValueRect(const ARect: TRect): TRect; begin if TBitmap32(GetOrdValue).Empty then Result := ARect else Result := Rect(ARect.Left, ARect.Top, (ARect.Bottom - ARect.Top) + ARect.Left, ARect.Bottom); end; {$ENDIF} {$ENDIF} procedure TBitmap32Property.SetValue(const Value: string); begin if Value = '' then SetOrdValue(0); end; { TImage32Editor } procedure TImage32Editor.ExecuteVerb(Index: Integer); var Img: TCustomImage32; BitmapEditor: TBitmap32Editor; begin Img := Component as TCustomImage32; if Index = 0 then begin BitmapEditor := TBitmap32Editor.Create(nil); try BitmapEditor.Bitmap32 := Img.Bitmap; if BitmapEditor.Execute then begin Img.Bitmap := BitmapEditor.Bitmap32; Designer.Modified; end; finally BitmapEditor.Free; end; end; end; function TImage32Editor.GetVerb(Index: Integer): string; begin if Index = 0 then Result := 'Bitmap32 Editor...'; end; function TImage32Editor.GetVerbCount: Integer; begin Result := 1; end; procedure TPictureEditorForm.AlphaChannelMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); var P: TPoint; begin if AlphaChannel.Bitmap <> nil then begin P := AlphaChannel.ControlToBitmap(Point(X, Y)); X := P.X; Y := P.Y; if (X >= 0) and (Y >= 0) and (X < AlphaChannel.Bitmap.Width) and (Y < AlphaChannel.Bitmap.Height) then Panel2.Caption := 'Alpha: $' + IntToHex(AlphaChannel.Bitmap[X, Y] and $FF, 2) + Format(' '#9'X: %d'#9'Y: %d', [X, Y]) else Panel2.Caption := ''; end else Panel2.Caption := ''; end; procedure TPictureEditorForm.RGBChannelsMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); var P: TPoint; begin if RGBChannels.Bitmap <> nil then begin P := RGBChannels.ControlToBitmap(Point(X, Y)); X := P.X; Y := P.Y; if (X >= 0) and (Y >= 0) and (X < RGBChannels.Bitmap.Width) and (Y < RGBChannels.Bitmap.Height) then Panel2.Caption := 'RGB: $' + IntToHex(RGBChannels.Bitmap[X, Y] and $00FFFFFF, 6) + Format(#9'X: %d'#9'Y: %d', [X, Y]) else Panel2.Caption := ''; end else Panel2.Caption := ''; end; end.
26.957486
109
0.711465
c324244702fdd0a162a9ec12b19668eab0b3274e
21,073
pas
Pascal
Source/rmkThemes/rmkThemes.pas
sharov-artem/TBX
4982cf02765672376ae887711b8820d63a0d71af
[ "MIT" ]
42
2015-02-02T22:39:21.000Z
2022-01-19T15:28:20.000Z
Source/rmkThemes/rmkThemes.pas
sharov-artem/TBX
4982cf02765672376ae887711b8820d63a0d71af
[ "MIT" ]
16
2019-02-02T19:54:54.000Z
2019-02-28T05:22:36.000Z
Source/rmkThemes/rmkThemes.pas
sharov-artem/TBX
4982cf02765672376ae887711b8820d63a0d71af
[ "MIT" ]
14
2015-06-17T07:40:11.000Z
2020-12-17T06:34:49.000Z
{* * rmkThemes common functions * Copyright 2003-2013 Roy Magne Klever. All rights reserved. * * The MIT License (MIT) * * 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 rmkThemes; interface uses Windows, Messages, Graphics, Types, TBXUtils; type TGradDir = (tgLeftRight, tgTopBottom); procedure ButtonFrame(Canvas: TCanvas; R: TRect; RL, RR: Integer; c1, c2, c3: TColor); procedure SmartFrame(Canvas: TCanvas; R: TRect; RL, RR: Integer; c1, c2: TColor); procedure GradientGlass(const Canvas: TCanvas; const ARect: TRect; const Aqua:Boolean; const Direction: TGradDir); Overload; procedure GradientGlass(const Canvas: TCanvas; const ARect: TRect; const Aqua, Dark: Boolean; const Direction: TGradDir); Overload; procedure GradientFillOld(const Canvas: TCanvas; const ARect: TRect; const StartColor, EndColor: TColor; const Direction: TGradDir); // --- { LOW LEVEL } function GradientFillWinEnabled: Boolean; function GradientFillWin(DC: HDC; PVertex: Pointer; NumVertex: Cardinal; PMesh: Pointer; NumMesh, Mode: Cardinal): BOOL; { HIGH LEVEL } procedure GradientFill(DC: HDC; const ARect: TRect; StartColor, EndColor: TColor; Direction: TGradDir); overload; procedure GradientFill(Canvas: TCanvas; const ARect: TRect; StartColor, EndColor: TColor; Direction: TGradDir); overload; { Redeclare TRIVERTEX } type {$EXTERNALSYM COLOR16} COLOR16 = Word; { in Delphi Windows.pas wrong declared as Shortint } PTriVertex = ^TTriVertex; {$EXTERNALSYM _TRIVERTEX} _TRIVERTEX = packed record x : Longint; y : Longint; Red : COLOR16; Green : COLOR16; Blue : COLOR16; Alpha : COLOR16; end; TTriVertex = _TRIVERTEX; {$EXTERNALSYM TRIVERTEX} TRIVERTEX = _TRIVERTEX; // --- implementation // --- type TGradientFillWin = function(DC: HDC; PVertex: Pointer; NumVertex: ULONG; Mesh: Pointer; NumMesh, Mode: ULONG): BOOL; stdcall; TGradientFill = procedure(DC: HDC; const ARect: TRect; StartColor, EndColor: TColor; Direction: TGradDir); var InitDone : Boolean = False; MSImg32Module : THandle; GradFillWinProc : TGradientFillWin; GradFillProc : TGradientFill; // ---- procedure ButtonFrame(Canvas: TCanvas; R: TRect; RL, RR: Integer; c1, c2, c3: TColor); var Color: TColor; begin with Canvas, R do begin Color := Pen.Color; Pen.Color := c1; Dec(Right); Dec(Bottom); PolyLine([ Point(Left + RL, Top), Point(Right - RR, Top), Point(Right, Top + RR), Point(Right, Bottom - RR), Point(Right - RR, Bottom), Point(Left + RL, Bottom), Point(Left, Bottom - RL), Point(Left, Top + RL), Point(Left + RL, Top) ]); if c2 <> clNone then begin Pen.Color := c2; PolyLine([ Point(Right, Top + RR), Point(Right, Bottom - RR), Point(Right - RR, Bottom), Point(Left + RL - 1, Bottom) ]); end; Pen.Color := c3; if RR > 0 then begin Inc(Right); MoveTo(Right - RR, Top); LineTo(Right, Top + RR); MoveTo(Right - RR, Bottom); LineTo(Right, Bottom - RR); Dec(Right); end; if RL > 0 then begin Dec(Left); MoveTo(Left + RL, Top); LineTo(Left, Top + RL); MoveTo(Left + RL, Bottom); LineTo(Left, Bottom - RL); Inc(Left); end; Inc(Right); Inc(Bottom); Pen.Color := Color; end; end; // From Alex aluminum theme procedure RoundFrame(DC: HDC; R: TRect; TL, TR, BL, BR: Integer; Color: TColor); overload; var Radius: Integer; CornerID: Integer; procedure PutPixel(X, Y: Integer; Alpha: Integer); begin with R do case CornerID of 0: SetPixelEx(DC, Left + X, Top + Y, Color, Alpha); 1: SetPixelEx(DC, Right - X, Top + Y, Color, Alpha); 2: SetPixelEx(DC, Left + X, Bottom - Y, Color, Alpha); 3: SetPixelEx(DC, Right - X, Bottom - Y, Color, Alpha); end; end; begin if Color = clNone then Exit; with R do begin Dec(Right); Dec(Bottom); if Color < 0 then Color := GetSysColor(Color and $FF); { Edges } DrawLineEx(DC, Left, Bottom - BL, Left, Top + TL - 1, Color); DrawLineEx(DC, Left + TL, Top, Right - TR + 1, Top, Color); DrawLineEx(DC, Left + BL, Bottom, Right - BR + 1, Bottom, Color); DrawLineEx(DC, Right, Top + TR, Right, Bottom - BR + 1, Color); { Corners } for CornerID := 0 to 3 do begin case CornerID of 0: Radius := TL; 1: Radius := TR; 2: Radius := BL; else Radius := BR; end; case Radius of 1: begin PutPixel(0, 0, $3F); PutPixel(1, 1, $3F); end; 2: begin PutPixel(0, 0, $1F); PutPixel(1, 0, $4F); PutPixel(0, 1, $4F); PutPixel(1, 1, $FF); end; end; end; end; end; procedure SmartFrame(Canvas: TCanvas; R: TRect; RL, RR: Integer; c1, c2: TColor); var Color: TColor; begin RoundFrame(Canvas.Handle, R, RL, RR, RL, RR, c1); { with Canvas, R do begin Color := Pen.Color; Pen.Color := c1; Dec(Right); Dec(Bottom); Pen.Color := c1; PolyLine([ Point(Left + RL, Top), Point(Right - RR, Top), Point(Right, Top + RR), Point(Right, Bottom - RR), Point(Right - RR, Bottom), Point(Left + RL, Bottom), Point(Left, Bottom - RL), Point(Left, Top + RL), Point(Left + RL, Top) ]); if c2 <> clNone then begin Pen.Color := c2; PolyLine([ Point(Right, Top + RR), Point(Right, Bottom - RR), Point(Right - RR, Bottom), Point(Left + RL - 1, Bottom) ]); end; Pen.Color := Blend(Pixels[Left, Top], c1, 60); if RL > 0 then begin Dec(Left); MoveTo(Left + RL, Top); LineTo(Left, Top + RL); MoveTo(Left + RL, Bottom); LineTo(Left, Bottom - RL); Inc(Left); end; if c2 <> clNone then Pen.Color := Blend(Pixels[Right, Bottom], c2, 60); if RR > 0 then begin Inc(Right); MoveTo(Right - RR, Top); LineTo(Right, Top + RR); MoveTo(Right - RR, Bottom); LineTo(Right, Bottom - RR); Dec(Right); end; Inc(Right); Inc(Bottom); Pen.Color := Color; end; } end; procedure GradientGlass(const Canvas: TCanvas; const ARect: TRect; const Aqua, Dark: Boolean; const Direction: TGradDir); var GSize: Integer; rc1, rc2, gc1, gc2, bc1, bc2, rc3, gc3, bc3, rc4, gc4, bc4, r, g, b, y1, Counter, i, d1, d2, d3: Integer; Brush: HBrush; begin if Aqua then begin if Dark then begin rc1 := $e0; rc2 := $70; rc3 := $60; rc4 := $A0; gc1 := $e8; gc2 := $A0; gc3 := $D0; gc4 := $EF; bc1 := $EF; bc2 := $D0; bc3 := $E0; bc4 := $EF; end else begin //rc1 := $ff; rc2 := $b0; rc3 := $4; rc4 := $30; //gc1 := $ff; gc2 := $B0; gc3 := $4; gc4 := $40; //bc1 := $Ff; bc2 := $b0; bc3 := $4; bc4 := $b0; rc1 := $f0; rc2 := $80; rc3 := $70; rc4 := $B0; gc1 := $f8; gc2 := $B0; gc3 := $E8; gc4 := $FF; bc1 := $FF; bc2 := $E0; bc3 := $F0; bc4 := $FF; end; end else begin //rc1 := $ff; rc2 := $10; rc3 := $4; rc4 := $60; //gc1 := $ff; gc2 := $10; gc3 := $4; gc4 := $80; //bc1 := $Ff; bc2 := $20; bc3 := $4; bc4 := $c0; rc1 := $F8; rc2 := $d8; rc3 := $f0; rc4 := $F8; gc1 := $F8; gc2 := $d8; gc3 := $f0; gc4 := $F8; bc1 := $F8; bc2 := $d8; bc3 := $f0; bc4 := $F8; end; if Direction = tGTopBottom then begin GSize := (ARect.Bottom - ARect.Top) - 1; y1 := GSize div 3; if y1 = 0 then y1:= 1; d1 := y1; d2 := y1 + y1; for i := 0 to y1 do begin r := rc1 + (((rc2 - rc1) * (i)) div y1); g := gc1 + (((gc2 - gc1) * (i)) div y1); b := bc1 + (((bc2 - bc1) * (i)) div y1); if r < 0 then r := 0 else if r > 255 then r := 255; if g < 0 then g := 0 else if g > 255 then g := 255; if b < 0 then b := 0 else if b > 255 then b := 255; Brush := CreateSolidBrush( RGB(r, g, b)); Windows.FillRect(Canvas.Handle, Rect(ARect.Left, ARect.Top + i, ARect.Right, ARect.Top + i + 1), Brush); DeleteObject(Brush); end; for i := y1 to d2 do begin r := rc2 + (((rc3 - rc2) * (i - d1)) div y1); g := gc2 + (((gc3 - gc2) * (i - d1)) div y1); b := bc2 + (((bc3 - bc2) * (i - d1)) div y1); if r < 0 then r := 0 else if r > 255 then r := 255; if g < 0 then g := 0 else if g > 255 then g := 255; if b < 0 then b := 0 else if b > 255 then b := 255; Brush := CreateSolidBrush( RGB(r, g, b)); Windows.FillRect(Canvas.Handle, Rect(ARect.Left, ARect.Top + i, ARect.Right, ARect.Top + i + 1), Brush); DeleteObject(Brush); end; for i := d2 to GSize do begin r := rc3 + (((rc4 - rc3) * (i - d2)) div y1); g := gc3 + (((gc4 - gc3) * (i - d2)) div y1); b := bc3 + (((bc4 - bc3) * (i - d2)) div y1); if r < 0 then r := 0 else if r > 255 then r := 255; if g < 0 then g := 0 else if g > 255 then g := 255; if b < 0 then b := 0 else if b > 255 then b := 255; Brush := CreateSolidBrush( RGB(r, g, b)); Windows.FillRect(Canvas.Handle, Rect(ARect.Left, ARect.Top + i, ARect.Right, ARect.Top + i + 1), Brush); DeleteObject(Brush); end; end else begin GSize := (ARect.Right - ARect.Left) - 1; y1 := GSize div 3; if y1 = 0 then y1:= 1; d1 := y1; d2 := y1 + y1; for i := 0 to y1 do begin r := rc1 + (((rc2 - rc1) * (i)) div y1); g := gc1 + (((gc2 - gc1) * (i)) div y1); b := bc1 + (((bc2 - bc1) * (i)) div y1); if r < 0 then r := 0 else if r > 255 then r := 255; if g < 0 then g := 0 else if g > 255 then g := 255; if b < 0 then b := 0 else if b > 255 then b := 255; Brush := CreateSolidBrush( RGB(r, g, b)); Windows.FillRect(Canvas.Handle, Rect(ARect.Left + i, ARect.Top, ARect.Left + i + 1, ARect.Bottom), Brush); DeleteObject(Brush); end; for i := y1 to d2 do begin r := rc2 + (((rc3 - rc2) * (i - d1)) div y1); g := gc2 + (((gc3 - gc2) * (i - d1)) div y1); b := bc2 + (((bc3 - bc2) * (i - d1)) div y1); if r < 0 then r := 0 else if r > 255 then r := 255; if g < 0 then g := 0 else if g > 255 then g := 255; if b < 0 then b := 0 else if b > 255 then b := 255; Brush := CreateSolidBrush( RGB(r, g, b)); Windows.FillRect(Canvas.Handle, Rect(ARect.Left + i, ARect.Top, ARect.Left + i + 1, ARect.Bottom), Brush); DeleteObject(Brush); end; for i := d2 to GSize do begin r := rc3 + (((rc4 - rc3) * (i - d2)) div y1); g := gc3 + (((gc4 - gc3) * (i - d2)) div y1); b := bc3 + (((bc4 - bc3) * (i - d2)) div y1); if r < 0 then r := 0 else if r > 255 then r := 255; if g < 0 then g := 0 else if g > 255 then g := 255; if b < 0 then b := 0 else if b > 255 then b := 255; Brush := CreateSolidBrush( RGB(r, g, b)); Windows.FillRect(Canvas.Handle, Rect(ARect.Left + i, ARect.Top, ARect.Left + i + 1, ARect.Bottom), Brush); DeleteObject(Brush); end; end; end; procedure GradientGlass(const Canvas: TCanvas; const ARect: TRect; const Aqua: Boolean; const Direction: TGradDir); begin GradientGlass(Canvas, Arect, Aqua, False, Direction); end; procedure GradientFillOld(const Canvas: TCanvas; const ARect: TRect; const StartColor, EndColor: TColor; const Direction: TGradDir); var rc1, rc2, gc1, gc2, bc1, bc2, Counter, GSize: Integer; Brush: HBrush; begin rc1 := GetRValue(ColorToRGB(StartColor)); gc1 := GetGValue(ColorToRGB(StartColor)); bc1 := GetBValue(ColorToRGB(StartColor)); rc2 := GetRValue(ColorToRGB(EndColor)); gc2 := GetGValue(ColorToRGB(EndColor)); bc2 := GetBValue(ColorToRGB(EndColor)); if Direction = tGTopBottom then begin GSize := (ARect.Bottom - ARect.Top) - 1; if GSize = 0 then GSize:= 1; for Counter := 0 to GSize do begin Brush := CreateSolidBrush( RGB( Byte(rc1 + (((rc2 - rc1) * (Counter)) div GSize)), Byte(gc1 + (((gc2 - gc1) * (Counter)) div GSize)), Byte(bc1 + (((bc2 - bc1) * (Counter)) div GSize))) ); Windows.FillRect(Canvas.Handle, Rect(ARect.Left, ARect.Top, ARect.Right, ARect.Bottom - Counter), Brush); DeleteObject(Brush); end; end else begin GSize := (ARect.Right - ARect.Left) - 1; if GSize = 0 then GSize:= 1; for Counter := 0 to GSize do begin Brush := CreateSolidBrush( RGB(Byte(rc1 + (((rc2 - rc1) * (Counter)) div GSize)), Byte(gc1 + (((gc2 - gc1) * (Counter)) div GSize)), Byte(bc1 + (((bc2 - bc1) * (Counter)) div GSize)))); Windows.FillRect(Canvas.Handle, Rect(ARect.Left, ARect.Top, ARect.Right - Counter, ARect.Bottom), Brush); DeleteObject(Brush); end; end; end; // Code belowe is from Vladimir Bochkarev (******************************************************************************) procedure InitializeGradientFill; forward; (******************************************************************************) { GradientFillWin } (******************************************************************************) function GradFillWinInitProc(DC: HDC; PVertex: Pointer; NumVertex: ULONG; Mesh: Pointer; NumMesh, Mode: ULONG): BOOL; stdcall; begin InitializeGradientFill; Result := GradFillWinProc(DC, PVertex, NumVertex, Mesh, NumMesh, Mode); end; (******************************************************************************) function GradFillWinNone(DC: HDC; PVertex: Pointer; NumVertex: ULONG; Mesh: Pointer; NumMesh, Mode: ULONG): BOOL; stdcall; begin Result := False; end; (******************************************************************************) function GradientFillWin(DC: HDC; PVertex: Pointer; NumVertex: Cardinal; PMesh: Pointer; NumMesh, Mode: Cardinal): BOOL; begin Result := GradFillWinProc(DC, PVertex, NumVertex, PMesh, NumMesh, Mode); end; (******************************************************************************) function GradientFillWinEnabled: Boolean; begin if not InitDone then InitializeGradientFill; Result := @GradFillWinProc <> @GradFillWinNone; end; (******************************************************************************) { GradientFill } (******************************************************************************) procedure GradFillInitProc(DC: HDC; const ARect: TRect; StartColor, EndColor: TColor; Direction: TGradDir); begin InitializeGradientFill; GradFillProc(DC, ARect, StartColor, EndColor, Direction); end; (*****************************************************************************) procedure GradFillInt(DC: HDC; const ARect: TRect; StartColor, EndColor: TColor; Direction: TGradDir); var FillRect : TRect; RS, GS, BS : TColor; RE, GE, BE : TColor; LineCount : Integer; CurLine : Integer; //---------------------------------------------------------------------------- procedure InternalFillRect; var Brush: HBRUSH; begin Brush := CreateSolidBrush( RGB((RS+ (((RE- RS)* CurLine) div LineCount)), (GS+ (((GE- GS)* CurLine) div LineCount)), (BS+ (((BE- BS)* CurLine) div LineCount)))); Windows.FillRect(DC, FillRect, Brush); DeleteObject(Brush); end; //---------------------------------------------------------------------------- begin FillRect := ARect; if StartColor < 0 then StartColor := Integer(GetSysColor(StartColor and $000000FF)); if EndColor < 0 then EndColor := Integer(GetSysColor(EndColor and $000000FF)); RS := GetRValue(Cardinal(StartColor)); GS := GetGValue(Cardinal(StartColor)); BS := GetBValue(Cardinal(StartColor)); RE := GetRValue(Cardinal(EndColor)); GE := GetGValue(Cardinal(EndColor)); BE := GetBValue(Cardinal(EndColor)); if Direction = tgLeftRight then begin FillRect.Right := FillRect.Left+ 1; LineCount := ARect.Right- ARect.Left; for CurLine := 1 to LineCount do begin InternalFillRect; Inc(FillRect.Left); Inc(FillRect.Right); end; end else begin FillRect.Bottom := FillRect.Top+ 1; LineCount := ARect.Bottom- ARect.Top; for CurLine := 1 to LineCount do begin InternalFillRect; Inc(FillRect.Top); Inc(FillRect.Bottom); end; end; end; (******************************************************************************) procedure GradFillWin(DC: HDC; const ARect: TRect; StartColor, EndColor: TColor; Direction: TGradDir); var Vertexs: array[0..1] of TTriVertex; //---------------------------------------------------------------------------- procedure SetVertex(Index, AX, AY, AColor: TColor); begin with Vertexs[Index] do begin X := AX; Y := AY; Red := (AColor and $000000FF) shl 8; Green := (AColor and $0000FF00); Blue := (AColor and $00FF0000) shr 8; Alpha := 0; end; end; //---------------------------------------------------------------------------- var GRect : TGradientRect; Mode : Cardinal; begin if StartColor < 0 then StartColor := Integer(GetSysColor(StartColor and $000000FF)); if EndColor < 0 then EndColor := Integer(GetSysColor(EndColor and $000000FF)); SetVertex(0, ARect.Left, ARect.Top, StartColor); SetVertex(1, ARect.Right, ARect.Bottom, EndColor); with GRect do begin UpperLeft := 0; LowerRight := 1; end; if Direction = tgLeftRight then Mode := GRADIENT_FILL_RECT_H else Mode := GRADIENT_FILL_RECT_V; GradientFillWin(DC, @Vertexs, 2, @GRect, 1, Mode); end; (******************************************************************************) procedure GradientFill(DC: HDC; const ARect: TRect; StartColor, EndColor: TColor; Direction: TGradDir); begin GradFillProc(DC, ARect, StartColor, EndColor, Direction); end; (******************************************************************************) procedure GradientFill(Canvas: TCanvas; const ARect: TRect; StartColor, EndColor: TColor; Direction: TGradDir); begin GradientFill(Canvas.Handle, ARect, EndColor, StartColor, Direction); end; { Initializations } (******************************************************************************) procedure InitializeGradientFill; begin if InitDone then Exit; MSImg32Module := LoadLibrary('msimg32.dll'); if MSImg32Module <> 0 then GradFillWinProc := GetProcAddress(MSImg32Module, 'GradientFill') else GradFillWinProc := nil; if @GradFillWinProc = nil then begin GradFillWinProc := GradFillWinNone; GradFillProc := GradFillInt; end else GradFillProc := GradFillWin; InitDone := True; end; (******************************************************************************) procedure UninitializeGradientFill; begin if MSImg32Module <> 0 then FreeLibrary(MSImg32Module); end; (******************************************************************************) initialization GradFillWinProc := GradFillWinInitProc; GradFillProc := GradFillInitProc; finalization UninitializeGradientFill; (******************************************************************************) end.
33.081633
113
0.53476
fcc4ba32674ba355a8bf865618018503a9cc5481
20,646
pas
Pascal
windows/src/ext/jedi/jcl/jcl/experts/stacktraceviewer/JclStackTraceViewerClasses.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
219
2017-06-21T03:37:03.000Z
2022-03-27T12:09:28.000Z
windows/src/ext/jedi/jcl/jcl/experts/stacktraceviewer/JclStackTraceViewerClasses.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
4,451
2017-05-29T02:52:06.000Z
2022-03-31T23:53:23.000Z
windows/src/ext/jedi/jcl/jcl/experts/stacktraceviewer/JclStackTraceViewerClasses.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
72
2017-05-26T04:08:37.000Z
2022-03-03T10:26:20.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 JclStackTraceViewerClasses.pas. } { } { The Initial Developer of the Original Code is Uwe Schuster. } { Portions created by Uwe Schuster are Copyright (C) 2009 Uwe Schuster. All rights reserved. } { } { Contributor(s): } { Uwe Schuster (uschuster) } { } {**************************************************************************************************} { } { Last modified: $Date:: $ } { Revision: $Rev:: $ } { Author: $Author:: $ } { } {**************************************************************************************************} unit JclStackTraceViewerClasses; {$I jcl.inc} interface uses Windows, Classes, Contnrs, {$IFDEF UNITVERSIONING} JclUnitVersioning, {$ENDIF UNITVERSIONING} JclDebug, JclDebugSerialization, JclStackTraceViewerAPI; type TJclStackTraceViewerLocationInfo = class(TJclLocationInfoEx, IJclLocationInfo, IJclPreparedLocationInfo) private FFoundFile: Boolean; FFileName: string; FProjectName: string; FRevision: string; FTranslatedLineNumber: Integer; protected procedure AssignTo(Dest: TPersistent); override; public { IInterface } function QueryInterface(const IID: TGUID; out Obj): HRESULT; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; { IJclLocationInfo } function GetAddress: Pointer; function GetBinaryFileName: string; function GetLineNumber: Integer; function GetLineNumberOffsetFromProcedureStart: Integer; function GetModuleName: string; function GetOffsetFromLineNumber: Integer; function GetOffsetFromProcName: Integer; function GetProcedureName: string; function GetSourceName: string; function GetSourceUnitName: string; function GetUnitVersionDateTime: TDateTime; function GetUnitVersionExtra: string; function GetUnitVersionLogPath: string; function GetUnitVersionRCSfile: string; function GetUnitVersionRevision: string; function GetVAddress: Pointer; function GetValues: Integer; property Address: Pointer read GetAddress; property BinaryFileName: string read GetBinaryFileName; property LineNumber: Integer read GetLineNumber; property LineNumberOffsetFromProcedureStart: Integer read GetLineNumberOffsetFromProcedureStart; property ModuleName: string read GetModuleName; property OffsetFromLineNumber: Integer read GetOffsetFromLineNumber; property OffsetFromProcName: Integer read GetOffsetFromProcName; property ProcedureName: string read GetProcedureName; property SourceName: string read GetSourceName; property SourceUnitName: string read GetSourceUnitName; property UnitVersionDateTime: TDateTime read GetUnitVersionDateTime; property UnitVersionExtra: string read GetUnitVersionExtra; property UnitVersionLogPath: string read GetUnitVersionLogPath; property UnitVersionRCSfile: string read GetUnitVersionRCSfile; property UnitVersionRevision: string read GetUnitVersionRevision; property VAddress: Pointer read GetVAddress; property Values: Integer read GetValues; { IJclPreparedLocationInfo } function GetFileName: string; function GetFoundFile: Boolean; function GetProjectName: string; function GetRevision: string; function GetTranslatedLineNumber: Integer; procedure SetFileName(AValue: string); procedure SetFoundFile(AValue: Boolean); procedure SetProjectName(AValue: string); procedure SetRevision(AValue: string); procedure SetTranslatedLineNumber(AValue: Integer); property FileName: string read FFileName write FFileName; property FoundFile: Boolean read FFoundFile write FFoundFile; property ProjectName: string read FProjectName write FProjectName; property Revision: string read FRevision write FRevision; property TranslatedLineNumber: Integer read FTranslatedLineNumber write FTranslatedLineNumber; end; TJclStackTraceViewerLocationInfoList = class(TJclCustomLocationInfoList, IJclLocationInfoList, IJclPreparedLocationInfoList) private FPrepared: Boolean; FModuleInfoList: IJclModuleInfoList; function GetItems(AIndex: Integer): TJclStackTraceViewerLocationInfo; public constructor Create; override; function Add(Addr: Pointer): TJclStackTraceViewerLocationInfo; property Items[AIndex: Integer]: TJclStackTraceViewerLocationInfo read GetItems; { IInterface } function QueryInterface(const IID: TGUID; out Obj): HRESULT; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; { IJclLocationInfoList } function GetCount: Integer; function GetLocationItems(AIndex: Integer): IJclLocationInfo; property Count: Integer read GetCount; property LocationItems[AIndex: Integer]: IJclLocationInfo read GetLocationItems; default; { IJclPreparedLocationInfoList } function GetPrepared: Boolean; procedure SetPrepared(AValue: Boolean); function GetModuleInfoList: IJclModuleInfoList; property ModuleInfoList: IJclModuleInfoList read FModuleInfoList write FModuleInfoList; property Prepared: Boolean read FPrepared write FPrepared; end; TJclStackTraceViewerThreadInfo = class(TJclCustomThreadInfo) private function GetStack(const AIndex: Integer): TJclStackTraceViewerLocationInfoList; protected function GetStackClass: TJclCustomLocationInfoListClass; override; public property CreationStack: TJclStackTraceViewerLocationInfoList index 1 read GetStack; property Stack: TJclStackTraceViewerLocationInfoList index 2 read GetStack; end; TJclStackTraceViewerThreadInfoList = class(TObject) private FItems: TObjectList; function GetItems(AIndex: Integer): TJclStackTraceViewerThreadInfo; function GetCount: Integer; public constructor Create; destructor Destroy; override; function Add: TJclStackTraceViewerThreadInfo; procedure Clear; property Count: Integer read GetCount; property Items[AIndex: Integer]: TJclStackTraceViewerThreadInfo read GetItems; default; end; TJclStackTraceViewerModuleModuleInfo = class(TJclSerializableModuleInfo, IJclModuleInfo) { IInterface } function QueryInterface(const IID: TGUID; out Obj): HRESULT; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; { IJclModuleInfo } function GetBinFileVersion: string; function GetModuleName: string; property BinFileVersion: string read GetBinFileVersion; property ModuleName: string read GetModuleName; end; TJclStackTraceViewerModuleInfoList = class(TInterfacedObject, IInterface, IJclModuleInfoList) private FItems: TObjectList; public constructor Create; destructor Destroy; override; function Add: TJclStackTraceViewerModuleModuleInfo; procedure Clear; { IInterface } // function QueryInterface(const IID: TGUID; out Obj): HRESULT; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; { IJclModuleInfoList } function GetModuleCount: Integer; function GetModuleInfo(AIndex: Integer): IJclModuleInfo; property Count: Integer read GetModuleCount; property Items[AIndex: Integer]: IJclModuleInfo read GetModuleInfo; default; end; TJclStackTraceViewerExceptionInfo = class(TObject) private FException: TJclSerializableException; FThreadInfoList: TJclStackTraceViewerThreadInfoList; FModules: TJclStackTraceViewerModuleInfoList; procedure AddModuleListToStacks; public constructor Create; destructor Destroy; override; procedure AssignExceptionInfo(AExceptionInfo: TJclSerializableExceptionInfo); property ThreadInfoList: TJclStackTraceViewerThreadInfoList read FThreadInfoList; property Exception: TJclSerializableException read FException; property Modules: TJclStackTraceViewerModuleInfoList read FModules; end; {$IFDEF UNITVERSIONING} const UnitVersioning: TUnitVersionInfo = ( RCSfile: '$URL$'; Revision: '$Revision$'; Date: '$Date$'; LogPath: 'JCL\experts\stacktraceviewer'; Extra: ''; Data: nil ); {$ENDIF UNITVERSIONING} implementation //=== { TJclStackTraceViewerLocationInfoList } =============================== function TJclStackTraceViewerLocationInfoList.Add(Addr: Pointer): TJclStackTraceViewerLocationInfo; begin Result := TJclStackTraceViewerLocationInfo(InternalAdd(Addr)); end; constructor TJclStackTraceViewerLocationInfoList.Create; begin inherited Create; FItemClass := TJclStackTraceViewerLocationInfo; FOptions := []; FPrepared := False; end; function TJclStackTraceViewerLocationInfoList.GetCount: Integer; begin Result := FItems.Count; end; function TJclStackTraceViewerLocationInfoList.GetItems(AIndex: Integer): TJclStackTraceViewerLocationInfo; begin Result := TJclStackTraceViewerLocationInfo(FItems[AIndex]); end; function TJclStackTraceViewerLocationInfoList.GetLocationItems(AIndex: Integer): IJclLocationInfo; begin FItems[AIndex].GetInterface(IJclLocationInfo, Result); end; function TJclStackTraceViewerLocationInfoList.GetModuleInfoList: IJclModuleInfoList; begin Result := FModuleInfoList; end; function TJclStackTraceViewerLocationInfoList.GetPrepared: Boolean; begin Result := FPrepared; end; function TJclStackTraceViewerLocationInfoList.QueryInterface(const IID: TGUID; out Obj): HRESULT; begin if GetInterface(IID, Obj) then Result := S_OK else Result := E_NOINTERFACE; end; procedure TJclStackTraceViewerLocationInfoList.SetPrepared(AValue: Boolean); begin FPrepared := AValue; end; function TJclStackTraceViewerLocationInfoList._AddRef: Integer; begin Result := -1; end; function TJclStackTraceViewerLocationInfoList._Release: Integer; begin Result := -1; end; //=== { TJclStackTraceViewerThreadInfo } ===================================== function TJclStackTraceViewerThreadInfo.GetStack(const AIndex: Integer): TJclStackTraceViewerLocationInfoList; begin case AIndex of 1: Result := TJclStackTraceViewerLocationInfoList(FCreationStack); 2: Result := TJclStackTraceViewerLocationInfoList(FStack); else Result := nil; end; end; function TJclStackTraceViewerThreadInfo.GetStackClass: TJclCustomLocationInfoListClass; begin Result := TJclStackTraceViewerLocationInfoList; end; //=== { TJclStackTraceViewerThreadInfoList } ================================= constructor TJclStackTraceViewerThreadInfoList.Create; begin inherited Create; FItems := TObjectList.Create; end; destructor TJclStackTraceViewerThreadInfoList.Destroy; begin FItems.Free; inherited Destroy; end; function TJclStackTraceViewerThreadInfoList.Add: TJclStackTraceViewerThreadInfo; begin FItems.Add(TJclStackTraceViewerThreadInfo.Create); Result := TJclStackTraceViewerThreadInfo(FItems.Last); end; procedure TJclStackTraceViewerThreadInfoList.Clear; begin FItems.Clear; end; function TJclStackTraceViewerThreadInfoList.GetCount: Integer; begin Result := FItems.Count; end; function TJclStackTraceViewerThreadInfoList.GetItems(AIndex: Integer): TJclStackTraceViewerThreadInfo; begin Result := TJclStackTraceViewerThreadInfo(FItems[AIndex]); end; //=== { TJclStackTraceViewerExceptionInfo } ================================== constructor TJclStackTraceViewerExceptionInfo.Create; begin inherited Create; FException := TJclSerializableException.Create; FThreadInfoList := TJclStackTraceViewerThreadInfoList.Create; FModules := TJclStackTraceViewerModuleInfoList.Create; end; destructor TJclStackTraceViewerExceptionInfo.Destroy; begin FModules.Free; FException.Free; FThreadInfoList.Free; inherited Destroy; end; procedure TJclStackTraceViewerExceptionInfo.AddModuleListToStacks; var I: Integer; begin for I := 0 to FThreadInfoList.Count - 1 do FThreadInfoList[I].CreationStack.ModuleInfoList := FModules; for I := 0 to FThreadInfoList.Count - 1 do FThreadInfoList[I].Stack.ModuleInfoList := FModules; end; procedure TJclStackTraceViewerExceptionInfo.AssignExceptionInfo(AExceptionInfo: TJclSerializableExceptionInfo); var I: Integer; begin FException.Assign(AExceptionInfo.Exception); FThreadInfoList.Clear; for I := 0 to AExceptionInfo.ThreadInfoList.Count - 1 do FThreadInfoList.Add.Assign(AExceptionInfo.ThreadInfoList[I]); FModules.Clear; for I := 0 to AExceptionInfo.Modules.Count - 1 do FModules.Add.Assign(AExceptionInfo.Modules[I]); AddModuleListToStacks; end; { TJclStackTraceViewerLocationInfo } function TJclStackTraceViewerLocationInfo.QueryInterface(const IID: TGUID; out Obj): HRESULT; begin if GetInterface(IID, Obj) then Result := S_OK else Result := E_NOINTERFACE; end; function TJclStackTraceViewerLocationInfo._AddRef: Integer; begin Result := -1; end; function TJclStackTraceViewerLocationInfo._Release: Integer; begin Result := -1; end; procedure TJclStackTraceViewerLocationInfo.AssignTo(Dest: TPersistent); begin inherited AssignTo(Dest); if Dest is TJclStackTraceViewerLocationInfo then begin TJclStackTraceViewerLocationInfo(Dest).FFoundFile := FFoundFile; TJclStackTraceViewerLocationInfo(Dest).FFileName := FFileName; TJclStackTraceViewerLocationInfo(Dest).FProjectName := FProjectName; TJclStackTraceViewerLocationInfo(Dest).FRevision := FRevision; TJclStackTraceViewerLocationInfo(Dest).FTranslatedLineNumber := FTranslatedLineNumber; end; end; function TJclStackTraceViewerLocationInfo.GetAddress: Pointer; begin Result := Address; end; function TJclStackTraceViewerLocationInfo.GetBinaryFileName: string; begin Result := BinaryFileName; end; function TJclStackTraceViewerLocationInfo.GetFileName: string; begin Result := FFileName; end; function TJclStackTraceViewerLocationInfo.GetFoundFile: Boolean; begin Result := FFoundFile; end; function TJclStackTraceViewerLocationInfo.GetLineNumber: Integer; begin Result := LineNumber; end; function TJclStackTraceViewerLocationInfo.GetLineNumberOffsetFromProcedureStart: Integer; begin Result := LineNumberOffsetFromProcedureStart; end; function TJclStackTraceViewerLocationInfo.GetModuleName: string; begin Result := ModuleName; end; function TJclStackTraceViewerLocationInfo.GetOffsetFromLineNumber: Integer; begin Result := OffsetFromLineNumber; end; function TJclStackTraceViewerLocationInfo.GetOffsetFromProcName: Integer; begin Result := OffsetFromProcName; end; function TJclStackTraceViewerLocationInfo.GetProcedureName: string; begin Result := ProcedureName; end; function TJclStackTraceViewerLocationInfo.GetProjectName: string; begin Result := FProjectName; end; function TJclStackTraceViewerLocationInfo.GetRevision: string; begin Result := FRevision; end; function TJclStackTraceViewerLocationInfo.GetSourceName: string; begin Result := SourceName; end; function TJclStackTraceViewerLocationInfo.GetSourceUnitName: string; begin Result := SourceUnitName; end; function TJclStackTraceViewerLocationInfo.GetTranslatedLineNumber: Integer; begin Result := FTranslatedLineNumber; end; function TJclStackTraceViewerLocationInfo.GetUnitVersionDateTime: TDateTime; begin Result := UnitVersionDateTime; end; function TJclStackTraceViewerLocationInfo.GetUnitVersionExtra: string; begin Result := UnitVersionExtra; end; function TJclStackTraceViewerLocationInfo.GetUnitVersionLogPath: string; begin Result := UnitVersionLogPath; end; function TJclStackTraceViewerLocationInfo.GetUnitVersionRCSfile: string; begin Result := UnitVersionRCSfile; end; function TJclStackTraceViewerLocationInfo.GetUnitVersionRevision: string; begin Result := UnitVersionRevision; end; function TJclStackTraceViewerLocationInfo.GetVAddress: Pointer; begin Result := VAddress; end; function TJclStackTraceViewerLocationInfo.GetValues: Integer; begin Result := 0; if lievLocationInfo in (inherited Values) then Inc(Result, livLocationInfo); if lievProcedureStartLocationInfo in (inherited Values) then Inc(Result, livProcedureStartLocationInfo); if lievUnitVersionInfo in (inherited Values) then Inc(Result, livUnitVersionInfo); end; procedure TJclStackTraceViewerLocationInfo.SetFileName(AValue: string); begin FFileName := AValue; end; procedure TJclStackTraceViewerLocationInfo.SetFoundFile(AValue: Boolean); begin FFoundFile := AValue; end; procedure TJclStackTraceViewerLocationInfo.SetProjectName(AValue: string); begin FProjectName := AValue; end; procedure TJclStackTraceViewerLocationInfo.SetRevision(AValue: string); begin FRevision := AValue; end; procedure TJclStackTraceViewerLocationInfo.SetTranslatedLineNumber(AValue: Integer); begin FTranslatedLineNumber := AValue; end; { TJclStackTraceViewerModuleModuleInfo } function TJclStackTraceViewerModuleModuleInfo.GetBinFileVersion: string; begin Result := BinFileVersion; end; function TJclStackTraceViewerModuleModuleInfo.GetModuleName: string; begin Result := ModuleName; end; function TJclStackTraceViewerModuleModuleInfo.QueryInterface(const IID: TGUID; out Obj): HRESULT; begin if GetInterface(IID, Obj) then Result := S_OK else Result := E_NOINTERFACE; end; function TJclStackTraceViewerModuleModuleInfo._AddRef: Integer; begin Result := -1; end; function TJclStackTraceViewerModuleModuleInfo._Release: Integer; begin Result := -1; end; { TJclStackTraceViewerModuleInfoList } function TJclStackTraceViewerModuleInfoList.Add: TJclStackTraceViewerModuleModuleInfo; begin FItems.Add(TJclStackTraceViewerModuleModuleInfo.Create); Result := TJclStackTraceViewerModuleModuleInfo(FItems.Last); end; procedure TJclStackTraceViewerModuleInfoList.Clear; begin FItems.Clear; end; constructor TJclStackTraceViewerModuleInfoList.Create; begin inherited Create; FItems := TObjectList.Create; end; destructor TJclStackTraceViewerModuleInfoList.Destroy; begin FItems.Free; inherited Destroy; end; function TJclStackTraceViewerModuleInfoList.GetModuleCount: Integer; begin Result := FItems.Count; end; function TJclStackTraceViewerModuleInfoList.GetModuleInfo(AIndex: Integer): IJclModuleInfo; begin FItems[AIndex].GetInterface(IJclModuleInfo, Result); end; function TJclStackTraceViewerModuleInfoList._AddRef: Integer; begin Result := -1; end; function TJclStackTraceViewerModuleInfoList._Release: Integer; begin Result := -1; end; {$IFDEF UNITVERSIONING} initialization RegisterUnitVersion(HInstance, UnitVersioning); finalization UnregisterUnitVersion(HInstance); {$ENDIF UNITVERSIONING} end.
32.309859
111
0.721835
f1199178e9bec494706fca11aac163fec91f215d
4,057
pas
Pascal
Projects/CompStartup.pas
tony8077616/issrc
3b0cd1eff411bc3f3b85a89190f02e47a5d78991
[ "FSFAP" ]
1
2020-02-23T18:27:35.000Z
2020-02-23T18:27:35.000Z
Projects/CompStartup.pas
tony8077616/issrc
3b0cd1eff411bc3f3b85a89190f02e47a5d78991
[ "FSFAP" ]
null
null
null
Projects/CompStartup.pas
tony8077616/issrc
3b0cd1eff411bc3f3b85a89190f02e47a5d78991
[ "FSFAP" ]
1
2020-04-07T23:20:56.000Z
2020-04-07T23:20:56.000Z
unit CompStartup; { Inno Setup Copyright (C) 1997-2004 Jordan Russell Portions by Martijn Laan For conditions of distribution and use, see LICENSE.TXT. Compiler Startup form $jrsoftware: issrc/Projects/CompStartup.pas,v 1.11 2004/07/22 19:49:39 jr Exp $ } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, UIStateForm, StdCtrls, ExtCtrls; type TStartupFormResult = (srNone, srEmpty, srWizard, srOpenFile, srOpenDialog, srOpenDialogExamples); TStartupForm = class(TUIStateForm) OKButton: TButton; CancelButton: TButton; GroupBox1: TGroupBox; GroupBox2: TGroupBox; EmptyRadioButton: TRadioButton; WizardRadioButton: TRadioButton; OpenRadioButton: TRadioButton; OpenListBox: TListBox; StartupCheck: TCheckBox; NewImage: TImage; OpenImage: TImage; procedure RadioButtonClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure DblClick_(Sender: TObject); procedure OpenListBoxClick(Sender: TObject); procedure OKButtonClick(Sender: TObject); procedure FormAfterMonitorDpiChanged(Sender: TObject; OldDPI, NewDPI: Integer); private FResult: TStartupFormResult; FResultFileName: TFileName; procedure SetMRUList(const MRUList: TStringList); procedure UpdateImages; public property MRUList: TStringList write SetMRUList; property Result: TStartupFormResult read FResult; property ResultFileName: TFileName read FResultFileName; end; implementation uses CompMsgs, CmnFunc, CmnFunc2, CompForm, ComCtrls; {$R *.DFM} procedure TStartupForm.SetMRUList(const MRUList: TStringList); var I: Integer; begin for I := 0 to MRUList.Count-1 do OpenListBox.Items.Add(MRUList[I]); UpdateHorizontalExtent(OpenListBox); end; procedure TStartupForm.UpdateImages; function GetBitmap(const Button: TToolButton; const WH: Integer): TBitmap; begin Result := CompileForm.ToolBarImageCollection.GetBitmap(Button.ImageIndex, WH, WH) end; var WH: Integer; begin { After a DPI change the button's Width and Height isn't yet updated, so calculate it ourselves } WH := MulDiv(16, CurrentPPI, 96); NewImage.Picture.Bitmap := GetBitmap(CompileForm.NewButton, WH); OpenImage.Picture.Bitmap := GetBitmap(CompileForm.OpenButton, WH); end; procedure TStartupForm.FormAfterMonitorDpiChanged(Sender: TObject; OldDPI, NewDPI: Integer); begin UpdateImages; end; procedure TStartupForm.FormCreate(Sender: TObject); begin FResult := srNone; InitFormFont(Self); UpdateImages; OpenListBox.Items.Add(SCompilerExampleScripts); OpenListBox.Items.Add(SCompilerMoreFiles); OpenListBox.ItemIndex := 0; UpdateHorizontalExtent(OpenListBox); ActiveControl := OpenRadioButton; end; procedure TStartupForm.RadioButtonClick(Sender: TObject); begin EmptyRadioButton.Checked := Sender = EmptyRadioButton; WizardRadioButton.Checked := Sender = WizardRadioButton; OpenRadioButton.Checked := Sender = OpenRadioButton; if Sender = OpenRadioButton then begin if OpenListBox.ItemIndex = -1 then OpenListBox.ItemIndex := 0; end else OpenListBox.ItemIndex := -1; end; procedure TStartupForm.DblClick_(Sender: TObject); begin if OkButton.Enabled then OkButton.Click; end; procedure TStartupForm.OpenListBoxClick(Sender: TObject); begin OpenRadioButton.Checked := True; end; procedure TStartupForm.OKButtonClick(Sender: TObject); begin if EmptyRadioButton.Checked then FResult := srEmpty else if WizardRadioButton.Checked then FResult := srWizard else { if OpenRadioButton.Checked then } begin if OpenListBox.ItemIndex = 0 then FResult := srOpenDialogExamples else if OpenListBox.ItemIndex > 1 then begin FResult := srOpenFile; FResultFileName := OpenListBox.Items[OpenListBox.ItemIndex]; end else FResult := srOpenDialog; end; end; end.
27.228188
99
0.725659
fca7852de7e9474d4efaa649ebdd477bfa2521d9
107,380
pas
Pascal
library/wp/FHIR.WP.Toolbar.pas
rhausam/fhirserver
d7e2fc59f9c55b1989367b4d3e2ad8a811e71af3
[ "BSD-3-Clause" ]
132
2015-02-02T00:22:40.000Z
2021-08-11T12:08:08.000Z
library/wp/FHIR.WP.Toolbar.pas
rhausam/fhirserver
d7e2fc59f9c55b1989367b4d3e2ad8a811e71af3
[ "BSD-3-Clause" ]
113
2015-03-20T01:55:20.000Z
2021-10-08T16:15:28.000Z
library/wp/FHIR.WP.Toolbar.pas
rhausam/fhirserver
d7e2fc59f9c55b1989367b4d3e2ad8a811e71af3
[ "BSD-3-Clause" ]
49
2015-04-11T14:59:43.000Z
2021-03-30T10:29:18.000Z
Unit FHIR.WP.Toolbar; { Copyright (c) 2001+, Kestral Computing Pty Ltd (http://www.kestral.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, Classes, Graphics, Controls, StdCtrls, ExtCtrls, Dialogs, Buttons, fsl_utilities, fui_vclx_Base, fui_vclx_Images, fui_vclx_Controls, fui_vclx_Advanced, wp_types, FHIR.WP.Widgets, wp_definers, wp_clipboard, FHIR.WP.Icons, FHIR.WP.Control; Type TWordProcessorToolbar = Class(TUixAdvancedToolBar) Private FWordProcessor : TWordProcessor; FVisibleWidgetSet : TWPToolbarWidgets; FNewComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FOpenComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FSaveComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FSaveAsComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FPrintComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FPageDesignComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FCutComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FCopyComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FCopyAllComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FPasteComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FPasteSpecialComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FUndoComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FRedoComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FSearchComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FPlaybackComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FSpellingComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FStyleComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FStyleComboBox : TUixAdvancedComboBox; FFontNameComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FFontNameComboBox : TUixAdvancedFontComboBox; FFontSizeComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FFontSizeComboBox : TUixAdvancedComboBox; FFontColourComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FFontColourComboBox : TUixAdvancedColourComboBox; FBackColourComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FBackColourComboBox : TUixAdvancedColourComboBox; FBoldComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FItalicComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FUnderlineComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FSuperscriptComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FSubscriptComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FChangeCaseComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FLeftComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FRightComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FCentreComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FJustifyComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FBulletsComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FNumbersComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FIndentComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FOutdentComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FInsertTableComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FInsertImageComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FInsertLineComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FInsertPageBreakComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FEditHintsComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FMacroComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FInsertFieldComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FInsertTemplateComponentEntity : TUixAdvancedToolbarPresentationComponentEntity; FInsertFieldPopupMenu : TUixPopupMenu; FOnPageDesign: TNotifyEvent; FOnSave: TNotifyEvent; FOnSaveAs: TNotifyEvent; FOnNew: TNotifyEvent; FOnOpen: TNotifyEvent; FOnPrint: TNotifyEvent; Procedure NewButtonClickHandler(oSender : TObject); Procedure OpenButtonClickHandler(oSender : TObject); Procedure SaveButtonClickHandler(oSender : TObject); Procedure SaveAsButtonClickHandler(oSender : TObject); Procedure PrintButtonClickHandler(oSender : TObject); Procedure PageDesignButtonClickHandler(oSender : TObject); Procedure HintsButtonClickHandler(oSender : TObject); Procedure BoldButtonClickHandler(oSender : TObject); Procedure CutButtonClickHandler(oSender : TObject); Procedure CopyButtonClickHandler(oSender : TObject); Procedure CopyAllButtonClickHandler(oSender : TObject); Procedure PasteButtonClickHandler(oSender : TObject); Procedure PasteSpecialButtonClickHandler(oSender : TObject); Procedure ItalicsButtonClickHandler(oSender : TObject); Procedure UnderlineButtonClickHandler(oSender : TObject); Procedure SuperscriptButtonClickHandler(oSender : TObject); Procedure SubscriptButtonClickHandler(oSender : TObject); Procedure CaseButtonClickHandler(oSender : TObject); Procedure UndoButtonClickHandler(oSender : TObject); Procedure RedoButtonClickHandler(oSender : TObject); Procedure AlignLeftButtonClickHandler(oSender : TObject); Procedure AlignCentreButtonClickHandler(oSender : TObject); Procedure AlignRightButtonClickHandler(oSender : TObject); Procedure AlignJustifyButtonClickHandler(oSender : TObject); Procedure BulletsButtonClickHandler(oSender : TObject); Procedure NumbersButtonClickHandler(oSender : TObject); Procedure IndentButtonClickHandler(oSender : TObject); Procedure OutdentButtonClickHandler(oSender : TObject); Procedure InsertImageButtonClickHandler(oSender : TObject); Procedure InsertFieldDefaultButtonClickHandler(oSender : TObject); Procedure InsertTemplateButtonClickHandler(oSender : TObject); Procedure InsertLineButtonClickHandler(oSender : TObject); Procedure InsertPageBreakButtonClickHandler(oSender : TObject); Procedure InsertTableButtonClickHandler(oSender : TObject); Procedure VoicePlaybackButtonClickHandler(oSender : TObject); Procedure SpellingButtonClickHandler(oSender : TObject); Procedure SearchButtonClickHandler(oSender : TObject); Procedure MacroButtonClickHandler(oSender : TObject); Procedure StyleChangeHandler(oSender : TObject); Procedure FontNameChangeHandler(oSender : TObject); Procedure FontSizeChangeHandler(oSender : TObject); Procedure FontColourChangeHandler(oSender : TObject); Procedure BackColourChangeHandler(oSender : TObject); Procedure InsertFieldMenuItemClickHandler(oSender : TObject); Procedure WordProcessorObserverNotificationHandler(oSender : TObject); Procedure UpdateStatus; Procedure Build; Procedure LoadWordProcessorData; Procedure SetWordProcessor(Const Value: TWordProcessor); Public constructor Create(oOwner : TComponent); Override; destructor Destroy; Override; Procedure Refresh; Property VisibleWidgetSet : TWPToolbarWidgets Read FVisibleWidgetSet Write FVisibleWidgetSet; Property WordProcessor : TWordProcessor Read FWordProcessor Write SetWordProcessor; Property NewComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FNewComponentEntity; Property OpenComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FOpenComponentEntity; Property SaveComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FSaveComponentEntity; Property SaveAsComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FSaveAsComponentEntity; Property PrintComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FPrintComponentEntity; Property PageDesignComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FPageDesignComponentEntity; Property BackColourComboBox : TUixAdvancedColourComboBox Read FBackColourComboBox; Property BackColourComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FBackColourComponentEntity; Property BoldComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FBoldComponentEntity; Property BulletsComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FBulletsComponentEntity; Property CentreComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FCentreComponentEntity; Property ChangeCaseComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FChangeCaseComponentEntity; Property CopyAllComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FCopyAllComponentEntity; Property CopyComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FCopyComponentEntity; Property CutComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FCutComponentEntity; Property EditHintsComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FEditHintsComponentEntity; Property FontColourComboBox : TUixAdvancedColourComboBox Read FFontColourComboBox; Property FontColourComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FFontColourComponentEntity; Property FontNameComboBox : TUixAdvancedFontComboBox Read FFontNameComboBox; Property FontNameComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FFontNameComponentEntity; Property FontSizeComboBox : TUixAdvancedComboBox Read FFontSizeComboBox; Property FontSizeComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FFontSizeComponentEntity; Property IndentComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FIndentComponentEntity; Property InsertFieldComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FInsertFieldComponentEntity; Property InsertImageComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FInsertImageComponentEntity; Property InsertLineComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FInsertLineComponentEntity; Property InsertPageBreakComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FInsertPageBreakComponentEntity; Property InsertTableComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FInsertTableComponentEntity; Property InsertTemplateComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FInsertTemplateComponentEntity; Property ItalicComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FItalicComponentEntity; Property JustifyComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FJustifyComponentEntity; Property LeftComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FLeftComponentEntity; Property MacroComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FMacroComponentEntity; Property NumbersComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FNumbersComponentEntity; Property OutdentComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FOutdentComponentEntity; Property PasteComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FPasteComponentEntity; Property PasteSpecialComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FPasteSpecialComponentEntity; Property PlaybackComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FPlaybackComponentEntity; Property RedoComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FRedoComponentEntity; Property RightComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FRightComponentEntity; Property SearchComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FSearchComponentEntity; Property SpellingComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FSpellingComponentEntity; Property StyleComboBox : TUixAdvancedComboBox Read FStyleComboBox; Property StyleComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FStyleComponentEntity; Property SubscriptComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FSubscriptComponentEntity; Property SuperscriptComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FSuperscriptComponentEntity; Property UnderlineComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FUnderlineComponentEntity; Property UndoComponentEntity : TUixAdvancedToolbarPresentationComponentEntity Read FUndoComponentEntity; Property onNew : TNotifyEvent read FOnNew write FOnNew; Property onOpen : TNotifyEvent read FOnOpen write FOnOpen; Property onSave : TNotifyEvent read FOnSave write FOnSave; Property onSaveAs : TNotifyEvent read FOnSaveAs write FOnSaveAs; Property onPrint : TNotifyEvent read FOnPrint write FOnPrint; Property onPageDesign : TNotifyEvent read FOnPageDesign write FOnPageDesign; End; Const WordProcessorToolbarWidgetDefaultSet = [tbwCut, tbwCopy, tbwPaste, tbwUndo, tbwRedo, tbwSearch, tbwPlayback, tbwSpelling, tbwStyle, tbwFontName, tbwFontSize, tbwFontColour, tbwBold, tbwItalic, tbwUnderline, tbwLeft, tbwCentre, tbwRight, tbwJustify, tbwBullet, tbwNumber, tbwIndent, tbwOutdent, tbwInsertImage, tbwInsertTable, tbwInsertPageBreak, tbwInsertField, tbwMacro]; WordProcessorToolbarWidgetUniversalSet = [Low(TWPToolbarWidget)..High(TWPToolbarWidget)]; WordProcessorToolbarWidgetCaptionArray : Array [TWPToolbarWidget] Of String = ( 'Cut', 'Copy', 'Copy All', 'Paste', 'Paste Special', 'Undo', 'Redo', 'Search', 'Replay Dictation', 'Spelling', 'Style', 'Font Name', 'Font Size', 'Font Colour', 'Background Color', 'Bold', 'Italic', 'Underline', 'Superscript', 'Subscript', 'ChangeCase', 'Left Justify', 'Centre Justify', 'Right Justify', 'Block Justify', 'Bulleted', 'Numbered', 'Indent Paragraph', 'Unindent Paragraph', 'Insert Table', 'Insert Image', 'Insert Horizontal Line', 'Insert Page Break', 'Show Paragraph markers', 'Expand as a Macro', 'Insert Field', 'Insert Template', 'Insert Symbol', 'New', 'Open', 'Save', 'Save As', 'Print', 'Import', 'Export', 'Page Design' ); Const LEFT_INC_V = 60; LEFT_INC_H = 70; Btn_Offs_Cat_Operations = 0; Btn_Offs_New = Btn_Offs_Cat_Operations + 1; Btn_Offs_Open = Btn_Offs_New + 1; Btn_Offs_Save = Btn_Offs_Open + 1; Btn_Offs_SaveAs = Btn_Offs_Save + 1; Btn_Offs_Print_Preview = Btn_Offs_SaveAs + 1; Btn_Offs_Print = Btn_Offs_Print_Preview + 1; Btn_Offs_Email = Btn_Offs_Print + 1; Btn_Offs_Fax = Btn_Offs_Email + 1; Btn_Offs_Exit = Btn_Offs_Fax + 1; Btn_Offs_Cat_Edit = Btn_Offs_Exit + 1; Btn_Offs_Undo = Btn_Offs_Cat_Edit + 1; Btn_Offs_Redo = Btn_Offs_Undo + 1; Btn_Offs_Cut = Btn_Offs_Redo + 1; Btn_Offs_Copy = Btn_Offs_Cut + 1; Btn_Offs_Paste = Btn_Offs_Copy + 1; Btn_Offs_PasteSpecial = Btn_Offs_Paste + 1; Btn_Offs_SelectAll = Btn_Offs_PasteSpecial + 1; Btn_Offs_CopyFilename = Btn_Offs_SelectAll + 1; Btn_Offs_Search = Btn_Offs_CopyFilename + 1; Btn_Offs_Replace = Btn_Offs_Search + 1; Btn_Offs_ChangeCase = Btn_Offs_Replace + 1; Btn_Offs_Cat_Font = Btn_Offs_ChangeCase + 1; Btn_Offs_Bold = Btn_Offs_Cat_Font + 1; Btn_Offs_Italic = Btn_Offs_Bold + 1; Btn_Offs_Underline = Btn_Offs_Italic + 1; Btn_Offs_Colour = Btn_Offs_Underline + 1; Btn_Offs_Background = Btn_Offs_Colour + 1; Btn_Offs_Superscript = Btn_Offs_Background + 1; Btn_Offs_Subscript = Btn_Offs_Superscript + 1; Btn_Offs_FontProps = Btn_Offs_Subscript + 1; Btn_Offs_Cat_Paragraph = Btn_Offs_FontProps + 1; Btn_Offs_Left = Btn_Offs_Cat_Paragraph + 1; Btn_Offs_Center = Btn_Offs_Left + 1; Btn_Offs_Right = Btn_Offs_Center + 1; Btn_Offs_Justify = Btn_Offs_Right + 1; Btn_Offs_Normal = Btn_Offs_Justify + 1; Btn_Offs_Bullets = Btn_Offs_Normal + 1; Btn_Offs_Numbers = Btn_Offs_Bullets + 1; Btn_Offs_Indent = Btn_Offs_Numbers + 1; Btn_Offs_Outdent = Btn_Offs_Indent + 1; Btn_Offs_ParaProps = Btn_Offs_Outdent + 1; Btn_Offs_Cat_Insert = Btn_Offs_ParaProps + 1; Btn_Offs_Symbol = Btn_Offs_Cat_Insert + 1; Btn_Offs_Field = Btn_Offs_Symbol + 1; Btn_Offs_Template = Btn_Offs_Field + 1; Btn_Offs_Break = Btn_Offs_Template + 1; Btn_Offs_Picture = Btn_Offs_Break + 1; Btn_Offs_InsTable = Btn_Offs_Picture + 1; Btn_Offs_InsLine = Btn_Offs_InsTable + 1; Btn_Offs_Comment = Btn_Offs_InsLine + 1; Btn_Offs_Cat_Image = Btn_Offs_Comment + 1; Btn_Offs_Image = Btn_Offs_Cat_Image + 1; Btn_Offs_ImageMap = Btn_Offs_Image + 1; Btn_Offs_Select = Btn_Offs_ImageMap + 1; Btn_Offs_Line = Btn_Offs_Select + 1; Btn_Offs_Rect = Btn_Offs_Line + 1; Btn_Offs_Circle = Btn_Offs_Rect + 1; Btn_Offs_Mark = Btn_Offs_Circle + 1; Btn_Offs_Zoom = Btn_Offs_Mark + 1; Btn_Offs_ImageEdit = Btn_Offs_Zoom + 1; Btn_Offs_Cat_Field = Btn_Offs_ImageEdit + 1; Btn_Offs_Ins_Field = Btn_Offs_Cat_Field + 1; Btn_Offs_Previous = Btn_Offs_Ins_Field + 1; Btn_Offs_Next = Btn_Offs_Previous + 1; Btn_Offs_EditField = Btn_Offs_Next + 1; Btn_Offs_RemoveField = Btn_Offs_EditField + 1; Btn_Offs_cat_table = Btn_Offs_RemoveField + 1; Btn_Offs_TableToText = Btn_Offs_cat_table + 1; Btn_Offs_TextToTable = Btn_Offs_TableToText + 1; Btn_Offs_InsColLeft = Btn_Offs_TextToTable + 1; Btn_Offs_InsColRight = Btn_Offs_InsColLeft + 1; Btn_Offs_InsRowAbove = Btn_Offs_InsColRight + 1; Btn_Offs_InsRowBelow = Btn_Offs_InsRowAbove + 1; Btn_Offs_SelRow = Btn_Offs_InsRowBelow + 1; Btn_Offs_SelTable = Btn_Offs_SelRow + 1; Btn_Offs_DelCol = Btn_Offs_SelTable + 1; Btn_Offs_DelRow = Btn_Offs_DelCol + 1; Btn_Offs_DelTable = Btn_Offs_DelRow + 1; Btn_Offs_Sort = Btn_Offs_DelTable + 1; Btn_Offs_TableProps = Btn_Offs_Sort + 1; Btn_Offs_cat_Tools = Btn_Offs_TableProps + 1; Btn_Offs_Spell = Btn_Offs_cat_Tools + 1; Btn_Offs_Styles = Btn_Offs_Spell + 1; Btn_Offs_Options = Btn_Offs_Styles + 1; Btn_Offs_cat_Help = Btn_Offs_Options + 1; Btn_Offs_HelpIndex = Btn_Offs_cat_Help + 1; Btn_Offs_HelpHome = Btn_Offs_HelpIndex + 1; Btn_Offs_HelpVersion = Btn_Offs_HelpHome + 1; Btn_Offs_HelpSupportCase = Btn_Offs_HelpVersion + 1; Type TWordProcessorTouchToolbar = Class(TUixPanel) Private FWordProcessor : TWordProcessor; FColourDialog : TColorDialog; FOperationsButton : TSpeedButton; FEditButton : TSpeedButton; FFontButton : TSpeedButton; FParagraphButton : TSpeedButton; FInsertButton : TSpeedButton; FImageButton : TSpeedButton; FFieldButton : TSpeedButton; FTableButton : TSpeedButton; FToolsButton : TSpeedButton; FHelpButton : TSpeedButton; FVisibleWidgetSet : TWPToolbarWidgets; FImages : TUixImages; FCurrentMenu : TUixPanel; FOnNew: TNotifyEvent; FOnSave: TNotifyEvent; FOnSaveAs: TNotifyEvent; FOnOpen: TNotifyEvent; FOnEmail: TNotifyEvent; FOnExit: TNotifyEvent; FOnFax: TNotifyEvent; FOnPrint: TNotifyEvent; FOnCopyFilename: TNotifyEvent; FOnOptions : TNotifyEvent; FOnHelpIndex : TNotifyEvent; FOnHelpHome : TNotifyEvent; FOnHelpVersion : TNotifyEvent; FOnHelpSupportCase : TNotifyEvent; Function button(owner : TWinControl; top, left : integer; image : integer; hint : string; enabled : Boolean; captioned : boolean = false) : TSpeedButton; Procedure caption(owner : TWinControl; top, width : integer; title : string); Procedure WordProcessorObserverNotificationHandler(oSender : TObject); Procedure UpdateStatus; Procedure Build; Procedure LoadWordProcessorData; Procedure SetWordProcessor(Const Value: TWordProcessor); Procedure DoOperationsMenu(sender : TObject); Procedure DoNewOperation(sender : TObject); Procedure DoOpenOperation(sender : TObject); Procedure DoSaveOperation(sender : TObject); Procedure DoSaveAsOperation(sender : TObject); Procedure DoPrintOperation(sender : TObject); Procedure DoFaxOperation(sender : TObject); Procedure DoEmailOperation(sender : TObject); Procedure DoExitOperation(sender : TObject); Procedure DoEditMenu(sender : TObject); Procedure DoCutOperation(sender : TObject); Procedure DoCopyOperation(sender : TObject); Procedure DoPasteOperation(sender : TObject); Procedure DoPasteSpecialOperation(sender : TObject); Procedure DoCopyFilenameOperation(sender : TObject); Procedure DoUndoOperation(sender : TObject); Procedure DoRedoOperation(sender : TObject); Procedure DoSearchOperation(sender : TObject); Procedure DoReplaceOperation(sender : TObject); Procedure DoChangeCaseOperation(sender : TObject); Procedure DoFontMenu(sender : TObject); Procedure DoBoldButton(sender : TObject); Procedure DoItalicButton(sender : TObject); Procedure DoUnderlineButton(sender : TObject); Procedure DoColourButton(sender : TObject); Procedure DoBackgroundButton(sender : TObject); Procedure DoSuperscriptButton(sender : TObject); Procedure DoSubscriptButton(sender : TObject); Procedure DoFontPropertiesButton(sender : TObject); Procedure DoParagraphMenu(sender : TObject); Procedure DoLeftButton(sender : TObject); Procedure DoCenterButton(sender : TObject); Procedure DoRightButton(sender : TObject); Procedure DoJustifyButton(sender : TObject); Procedure DoNormalButton(sender : TObject); Procedure DoBulletsButton(sender : TObject); Procedure DoNumbersButton(sender : TObject); Procedure DoIndentButton(sender : TObject); Procedure DoOutdentButton(sender : TObject); Procedure DoParaPropsButton(sender : TObject); Procedure DoInsertMenu(sender : TObject); Procedure DoSymbolButton(sender : TObject); Procedure DoTemplateButton(sender : TObject); Procedure DoBreakButton(sender : TObject); Procedure DoPictureButton(sender : TObject); Procedure DoInsLineButton(sender : TObject); Procedure DoInsTableButton(sender : TObject); Procedure DoInsFieldButton(sender : TObject); Procedure DoImageMenu(sender : TObject); Procedure DoImageMapButton(sender : TObject); Procedure DoImageEditButton(sender : TObject); Procedure DoSelectButton(sender : TObject); Procedure DoLineButton(sender : TObject); Procedure DoRectButton(sender : TObject); Procedure DoCircleButton(sender : TObject); Procedure DoMarkButton(sender : TObject); Procedure DoZoomButton(sender : TObject); Procedure DoFieldMenu(sender : TObject); Procedure DoNextField(sender : TObject); Procedure DoPreviousField(sender : TObject); Procedure DoEditField(sender : TObject); Procedure DoRemoveField(sender : TObject); Procedure DoTableMenu(sender : TObject); Procedure DoTableToTextButton(sender : TObject); Procedure DoTextToTableButton(sender : TObject); Procedure DoTablePropsButton(sender : TObject); Procedure DoSelRowButton(sender : TObject); Procedure DoSelTableButton(sender : TObject); Procedure DoSortTableButton(sender : TObject); Procedure DoInsertLeftButton(sender : TObject); Procedure DoInsertRightButton(sender : TObject); Procedure DoInsertAboveButton(sender : TObject); Procedure DoInsertBelowButton(sender : TObject); Procedure DoDelColButton(sender : TObject); Procedure DoDelRowButton(sender : TObject); Procedure DoDelTableButton(sender : TObject); Procedure DoToolsMenu(sender : TObject); Procedure DoSpellButton(sender : TObject); Procedure DoStylesButton(sender : TObject); Procedure DoOptionsButton(sender : TObject); Procedure DoHelpMenu(sender : TObject); Procedure DoHelpIndexButton(sender : TObject); Procedure DoHelpHomeButton(sender : TObject); Procedure DoHelpVersionButton(sender : TObject); Procedure DoHelpSupportCaseButton(sender : TObject); Public constructor Create(oOwner : TComponent); Override; destructor Destroy; Override; Procedure Refresh; Property VisibleWidgetSet : TWPToolbarWidgets Read FVisibleWidgetSet Write FVisibleWidgetSet; Property WordProcessor : TWordProcessor Read FWordProcessor Write SetWordProcessor; Property OnNew : TNotifyEvent read FOnNew write FOnNew; Property OnOpen : TNotifyEvent read FOnOpen write FOnOpen; Property OnSave : TNotifyEvent read FOnSave write FOnSave; Property OnSaveAs : TNotifyEvent read FOnSaveAs write FOnSaveAs; Property OnPrint : TNotifyEvent read FOnPrint write FOnPrint; Property OnFax : TNotifyEvent read FOnFax write FOnFax; Property OnEmail : TNotifyEvent read FOnEmail write FOnEmail; Property OnExit : TNotifyEvent read FOnExit write FOnExit; Property OnOptions : TNotifyEvent read FOnOptions write FOnOptions; Property OnCopyFilename : TNotifyEvent read FOnCopyFilename write FOnCopyFilename; Property OnHelpIndex : TNotifyEvent read FOnHelpIndex write FOnHelpIndex; Property OnHelpHome : TNotifyEvent read FOnHelpHome write FOnHelpHome; Property OnHelpVersion : TNotifyEvent read FOnHelpVersion write FOnHelpVersion; Property OnHelpSupportCase : TNotifyEvent read FOnHelpSupportCase write FOnHelpSupportCase; End; Const WordProcessorTouchToolbarWidgetDefaultSet = [ tbwCut, tbwCopy, tbwPaste, tbwUndo, tbwRedo, tbwSearch, tbwPlayback, tbwSpelling, tbwStyle, tbwFontName, tbwFontSize, tbwFontColour, tbwBold, tbwItalic, tbwUnderline, tbwLeft, tbwCentre, tbwRight, tbwJustify, tbwBullet, tbwNumber, tbwIndent, tbwOutdent, tbwInsertImage, tbwInsertTable, tbwInsertPageBreak, tbwInsertField, tbwMacro]; WordProcessorTouchToolbarWidgetUniversalSet = [Low(TWPToolbarWidget)..High(TWPToolbarWidget)]; WordProcessorTouchToolbarWidgetCaptionArray : Array [TWPToolbarWidget] Of String = ( 'Cut', 'Copy', 'Copy All', 'Paste', 'Paste Special', 'Undo', 'Redo', 'Search', 'Replay Dictation', 'Spelling', 'Style', 'Font Name', 'Font Size', 'Font Colour', 'Background Color', 'Bold', 'Italic', 'Underline', 'Superscript', 'Subscript', 'ChangeCase', 'Left Justify', 'Centre Justify', 'Right Justify', 'Block Justify', 'Bulleted', 'Numbered', 'Indent Paragraph', 'Unindent Paragraph', 'Insert Table', 'Insert Image', 'Insert Horizontal Line', 'Insert Page Break', 'Show Paragraph markers', 'Expand as a Macro', 'Insert Field', 'Insert Template', 'Insert Symbol', 'New', 'Open', 'Save', 'Save As', 'Print', 'Import', 'Export', 'Page Design' ); Implementation Uses FHIR.WP.Engine; {$R resources\FHIR.WP.Toolbar.ImageSet.Res} {$R resources\FHIR.WP.Toolbar.Touch.ImageSet.Res} { TWordProcessorToolbar } Constructor TWordProcessorToolbar.Create(oOwner: TComponent); Begin Inherited; FWordProcessor := Nil; VisibleWidgetSet := WordProcessorToolbarWidgetDefaultSet; PresentationEntity.SpecificationEntity.IconSize := 16; PresentationEntity.SpecificationEntity.AllowWrapping := True; PresentationEntity.MarginLeft := 3; PresentationEntity.MarginRight := 3; PresentationEntity.MarginTop := 3; PresentationEntity.MarginBottom := 3; End; Destructor TWordProcessorToolbar.Destroy; Begin FWordProcessor := Nil; Inherited; End; Procedure TWordProcessorToolbar.Build; Var oAdvancedToolbarGroupEntity : TUixAdvancedToolbarPresentationGroupEntity; oAdvancedToolbarSectionEntity : TUixAdvancedToolbarPresentationSectionEntity; Begin PresentationEntity.GroupEntityList.Clear; oAdvancedToolbarGroupEntity := PresentationEntity.AddNewGroupEntity; oAdvancedToolbarGroupEntity.Caption := 'Clipboard'; oAdvancedToolbarSectionEntity := oAdvancedToolbarGroupEntity.AddNewSectionEntity; FNewComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FNewComponentEntity.Caption := WordProcessorToolbarWidgetCaptionArray[tbwNew]; FNewComponentEntity.HasButtonEntity := True; FNewComponentEntity.ButtonEntity.HasBitmapImage := True; FNewComponentEntity.ButtonEntity.BitmapImage.LoadPNGFromResource('New'); FNewComponentEntity.ButtonEntity.ClickHandler := NewButtonClickHandler; FOpenComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FOpenComponentEntity.Caption := WordProcessorToolbarWidgetCaptionArray[tbwOpen]; FOpenComponentEntity.HasButtonEntity := True; FOpenComponentEntity.ButtonEntity.HasBitmapImage := True; FOpenComponentEntity.ButtonEntity.BitmapImage.LoadPNGFromResource('Open'); FOpenComponentEntity.ButtonEntity.ClickHandler := OpenButtonClickHandler; FSaveComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FSaveComponentEntity.Caption := WordProcessorToolbarWidgetCaptionArray[tbwSave]; FSaveComponentEntity.HasButtonEntity := True; FSaveComponentEntity.ButtonEntity.HasBitmapImage := True; FSaveComponentEntity.ButtonEntity.BitmapImage.LoadPNGFromResource('Save'); FSaveComponentEntity.ButtonEntity.ClickHandler := SaveButtonClickHandler; FSaveAsComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FSaveAsComponentEntity.Caption := WordProcessorToolbarWidgetCaptionArray[tbwSaveAs]; FSaveAsComponentEntity.HasButtonEntity := True; FSaveAsComponentEntity.ButtonEntity.HasBitmapImage := True; FSaveAsComponentEntity.ButtonEntity.BitmapImage.LoadPNGFromResource('SaveAs'); FSaveAsComponentEntity.ButtonEntity.ClickHandler := SaveAsButtonClickHandler; FPrintComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FPrintComponentEntity.Caption := WordProcessorToolbarWidgetCaptionArray[tbwPrint]; FPrintComponentEntity.HasButtonEntity := True; FPrintComponentEntity.ButtonEntity.HasBitmapImage := True; FPrintComponentEntity.ButtonEntity.BitmapImage.LoadPNGFromResource('Print'); FPrintComponentEntity.ButtonEntity.ClickHandler := PrintButtonClickHandler; FPageDesignComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FPageDesignComponentEntity.Caption := WordProcessorToolbarWidgetCaptionArray[tbwPageDesign]; FPageDesignComponentEntity.HasButtonEntity := True; FPageDesignComponentEntity.ButtonEntity.HasBitmapImage := True; FPageDesignComponentEntity.ButtonEntity.BitmapImage.LoadPNGFromResource('PageDesign'); FPageDesignComponentEntity.ButtonEntity.ClickHandler := PageDesignButtonClickHandler; oAdvancedToolbarSectionEntity := oAdvancedToolbarGroupEntity.AddNewSectionEntity; FCutComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FCutComponentEntity.Caption := WordProcessorToolbarWidgetCaptionArray[tbwCut]; FCutComponentEntity.HasButtonEntity := True; FCutComponentEntity.ButtonEntity.HasBitmapImage := True; FCutComponentEntity.ButtonEntity.BitmapImage.LoadPNGFromResource('Cut'); FCutComponentEntity.ButtonEntity.ClickHandler := CutButtonClickHandler; FCopyComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FCopyComponentEntity.Caption := WordProcessorToolbarWidgetCaptionArray[tbwCopy]; FCopyComponentEntity.HasButtonEntity := True; FCopyComponentEntity.ButtonEntity.HasBitmapImage := True; FCopyComponentEntity.ButtonEntity.BitmapImage.LoadPNGFromResource('Copy'); FCopyComponentEntity.ButtonEntity.ClickHandler := CopyButtonClickHandler; FCopyAllComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FCopyAllComponentEntity.Caption := WordProcessorToolbarWidgetCaptionArray[tbwCopyAll]; FCopyAllComponentEntity.HasButtonEntity := True; FCopyAllComponentEntity.ButtonEntity.HasBitmapImage := True; FCopyAllComponentEntity.ButtonEntity.BitmapImage.LoadPNGFromResource('Copy'); FCopyAllComponentEntity.ButtonEntity.ClickHandler := CopyAllButtonClickHandler; FPasteComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FPasteComponentEntity.Caption := WordProcessorToolbarWidgetCaptionArray[tbwPaste]; FPasteComponentEntity.HasButtonEntity := True; FPasteComponentEntity.ButtonEntity.HasBitmapImage := True; FPasteComponentEntity.ButtonEntity.BitmapImage.LoadPNGFromResource('Paste'); FPasteComponentEntity.ButtonEntity.ClickHandler := PasteButtonClickHandler; FPasteSpecialComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FPasteSpecialComponentEntity.Caption := WordProcessorToolbarWidgetCaptionArray[tbwPasteSpecial]; FPasteSpecialComponentEntity.HasButtonEntity := True; FPasteSpecialComponentEntity.ButtonEntity.HasBitmapImage := True; FPasteSpecialComponentEntity.ButtonEntity.BitmapImage.LoadPNGFromResource('Paste'); FPasteSpecialComponentEntity.ButtonEntity.ClickHandler := PasteSpecialButtonClickHandler; oAdvancedToolbarSectionEntity := oAdvancedToolbarGroupEntity.AddNewSectionEntity; FUndoComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FUndoComponentEntity.Caption := WordProcessorToolbarWidgetCaptionArray[tbwUndo]; FUndoComponentEntity.HasButtonEntity := True; FUndoComponentEntity.ButtonEntity.HasBitmapImage := True; FUndoComponentEntity.ButtonEntity.BitmapImage.LoadPNGFromResource('Undo'); FUndoComponentEntity.ButtonEntity.ClickHandler := UndoButtonClickHandler; FRedoComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FRedoComponentEntity.Caption := WordProcessorToolbarWidgetCaptionArray[tbwRedo]; FRedoComponentEntity.HasButtonEntity := True; FRedoComponentEntity.ButtonEntity.HasBitmapImage := True; FRedoComponentEntity.ButtonEntity.BitmapImage.LoadPNGFromResource('Redo'); FRedoComponentEntity.ButtonEntity.ClickHandler := RedoButtonClickHandler; oAdvancedToolbarGroupEntity := PresentationEntity.AddNewGroupEntity; oAdvancedToolbarGroupEntity.Caption := 'Font'; oAdvancedToolbarSectionEntity := oAdvancedToolbarGroupEntity.AddNewSectionEntity; FStyleComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FStyleComponentEntity.Caption := WordProcessorToolbarWidgetCaptionArray[tbwStyle]; FStyleComponentEntity.HasControlEntity := True; FStyleComboBox := TUixAdvancedComboBox.Create(Self); FStyleComboBox.Parent := Self; FStyleComboBox.Font.Color := clBlack; FStyleComponentEntity.ControlEntity.Control := FStyleComboBox; FStyleComponentEntity.ControlEntity.MinimumWidth := 50; FStyleComponentEntity.ControlEntity.MaximumWidth := 80; FStyleComboBox.OnChange := StyleChangeHandler; oAdvancedToolbarSectionEntity := oAdvancedToolbarGroupEntity.AddNewSectionEntity; FFontNameComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FFontNameComponentEntity.Caption := WordProcessorToolbarWidgetCaptionArray[tbwFontName]; FFontNameComponentEntity.HasControlEntity := True; FFontNameComboBox := TUixAdvancedFontComboBox.Create(Self); FFontNameComboBox.Parent := Self; FFontNameComboBox.Align := alNone; FFontNameComboBox.Height := 15; FFontNameComboBox.DropDownWidth := 280; FFontNameComboBox.OnChange := FontNameChangeHandler; FFontNameComboBox.Font.Color := clBlack; FFontNameComponentEntity.ControlEntity.Control := FFontNameComboBox; FFontNameComponentEntity.ControlEntity.MinimumWidth := 50; FFontNameComponentEntity.ControlEntity.MaximumWidth := 140; oAdvancedToolbarSectionEntity := oAdvancedToolbarGroupEntity.AddNewSectionEntity; FFontSizeComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FFontSizeComponentEntity.Caption := WordProcessorToolbarWidgetCaptionArray[tbwFontSize]; FFontSizeComponentEntity.HasControlEntity := True; FFontSizeComboBox := TUixAdvancedComboBox.Create(Self); FFontSizeComboBox.Parent := Self; FFontSizeComboBox.Align := alNone; FFontSizeComboBox.Style := csDropDown; FFontSizeComboBox.Font.Color := clBlack; FFontSizeComboBox.OnChange := FontSizeChangeHandler; FFontSizeComponentEntity.ControlEntity.Control := FFontSizeComboBox; FFontSizeComponentEntity.ControlEntity.MinimumWidth := 50; FFontSizeComponentEntity.ControlEntity.MaximumWidth := 50; FFontSizeComboBox.Items.Clear; FFontSizeComboBox.Items.Add('4'); FFontSizeComboBox.Items.Add('5'); FFontSizeComboBox.Items.Add('6'); FFontSizeComboBox.Items.Add('7'); FFontSizeComboBox.Items.Add('8'); FFontSizeComboBox.Items.Add('9'); FFontSizeComboBox.Items.Add('10'); FFontSizeComboBox.Items.Add('11'); FFontSizeComboBox.Items.Add('12'); FFontSizeComboBox.Items.Add('13'); FFontSizeComboBox.Items.Add('14'); FFontSizeComboBox.Items.Add('15'); FFontSizeComboBox.Items.Add('16'); FFontSizeComboBox.Items.Add('17'); FFontSizeComboBox.Items.Add('18'); FFontSizeComboBox.Items.Add('19'); FFontSizeComboBox.Items.Add('20'); FFontSizeComboBox.Items.Add('21'); FFontSizeComboBox.Items.Add('22'); FFontSizeComboBox.Items.Add('24'); FFontSizeComboBox.Items.Add('26'); FFontSizeComboBox.Items.Add('28'); FFontSizeComboBox.Items.Add('30'); FFontSizeComboBox.Items.Add('32'); FFontSizeComboBox.Items.Add('34'); FFontSizeComboBox.Items.Add('36'); FFontSizeComboBox.Items.Add('38'); FFontSizeComboBox.Items.Add('40'); FFontSizeComboBox.Items.Add('44'); FFontSizeComboBox.Items.Add('48'); FFontSizeComboBox.Items.Add('52'); FFontSizeComboBox.Items.Add('56'); FFontSizeComboBox.Items.Add('60'); FFontSizeComboBox.Items.Add('64'); FFontSizeComboBox.Items.Add('72'); FFontSizeComboBox.Items.Add('80'); FFontSizeComboBox.Items.Add('96'); FFontSizeComboBox.Items.Add('128'); FFontSizeComboBox.Items.Add('172'); oAdvancedToolbarSectionEntity := oAdvancedToolbarGroupEntity.AddNewSectionEntity; FBackColourComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FBackColourComponentEntity.Caption := WordProcessorToolbarWidgetCaptionArray[tbwBackColor]; FBackColourComponentEntity.HasControlEntity := True; FBackColourComboBox := TUixAdvancedColourComboBox.Create(Self); FBackColourComboBox.Parent := Self; FBackColourComboBox.OnChange := BackColourChangeHandler; FBackColourComboBox.Height := 15; FBackColourComponentEntity.ControlEntity.Control := FBackColourComboBox; FBackColourComponentEntity.ControlEntity.MinimumWidth := 50; FBackColourComponentEntity.ControlEntity.MaximumWidth := 50; oAdvancedToolbarSectionEntity := oAdvancedToolbarGroupEntity.AddNewSectionEntity; FFontColourComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FFontColourComponentEntity.Caption := WordProcessorToolbarWidgetCaptionArray[tbwFontColour]; FFontColourComponentEntity.HasControlEntity := True; FFontColourComboBox := TUixAdvancedColourComboBox.Create(Self); FFontColourComboBox.Parent := Self; FFontColourComboBox.Height := 15; FFontColourComboBox.OnChange := FontColourChangeHandler; FFontColourComponentEntity.ControlEntity.Control := FFontColourComboBox; FFontColourComponentEntity.ControlEntity.MinimumWidth := 45; FFontColourComponentEntity.ControlEntity.MaximumWidth := 45; oAdvancedToolbarSectionEntity := oAdvancedToolbarGroupEntity.AddNewSectionEntity; FBoldComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FBoldComponentEntity.Caption := WordProcessorToolbarWidgetCaptionArray[tbwBold]; FBoldComponentEntity.HasButtonEntity := True; FBoldComponentEntity.ButtonEntity.HasBitmapImage := True; FBoldComponentEntity.ButtonEntity.BitmapImage.LoadPNGFromResource('Font_Bold'); FBoldComponentEntity.ButtonEntity.ClickHandler := BoldButtonClickHandler; FItalicComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FItalicComponentEntity.Caption := WordProcessorToolbarWidgetCaptionArray[tbwItalic]; FItalicComponentEntity.HasButtonEntity := True; FItalicComponentEntity.ButtonEntity.HasBitmapImage := True; FItalicComponentEntity.ButtonEntity.BitmapImage.LoadPNGFromResource('Font_Italics'); FItalicComponentEntity.ButtonEntity.ClickHandler := ItalicsButtonClickHandler; FUnderlineComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FUnderlineComponentEntity.Caption := WordProcessorToolbarWidgetCaptionArray[tbwUnderline]; FUnderlineComponentEntity.HasButtonEntity := True; FUnderlineComponentEntity.ButtonEntity.HasBitmapImage := True; FUnderlineComponentEntity.ButtonEntity.BitmapImage.LoadPNGFromResource('Font_Underline'); FUnderlineComponentEntity.ButtonEntity.ClickHandler := UnderlineButtonClickHandler; oAdvancedToolbarSectionEntity := oAdvancedToolbarGroupEntity.AddNewSectionEntity; FChangeCaseComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FChangeCaseComponentEntity.Caption := WordProcessorToolbarWidgetCaptionArray[tbwChangeCase]; FChangeCaseComponentEntity.HasButtonEntity := True; FChangeCaseComponentEntity.ButtonEntity.HasBitmapImage := True; FChangeCaseComponentEntity.ButtonEntity.BitmapImage.LoadPNGFromResource('Font_Change_Case'); FChangeCaseComponentEntity.ButtonEntity.ClickHandler := CaseButtonClickHandler; FSubScriptComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FSubScriptComponentEntity.Caption := WordProcessorToolbarWidgetCaptionArray[tbwSubscript]; FSubScriptComponentEntity.HasButtonEntity := True; FSubScriptComponentEntity.ButtonEntity.HasBitmapImage := True; FSubScriptComponentEntity.ButtonEntity.BitmapImage.LoadPNGFromResource('Copy'); FSubScriptComponentEntity.ButtonEntity.ClickHandler := SubscriptButtonClickHandler; FSuperScriptComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FSuperScriptComponentEntity.Caption := WordProcessorToolbarWidgetCaptionArray[tbwSuperscript]; FSuperScriptComponentEntity.HasButtonEntity := True; FSuperScriptComponentEntity.ButtonEntity.HasBitmapImage := True; FSuperScriptComponentEntity.ButtonEntity.BitmapImage.LoadPNGFromResource('Copy'); FSuperScriptComponentEntity.ButtonEntity.ClickHandler := SuperscriptButtonClickHandler; oAdvancedToolbarGroupEntity := PresentationEntity.AddNewGroupEntity; oAdvancedToolbarGroupEntity.Caption := 'Paragraph'; oAdvancedToolbarSectionEntity := oAdvancedToolbarGroupEntity.AddNewSectionEntity; FLeftComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FLeftComponentEntity.Caption := CAPTIONS_TOOLBARWIDGET[tbwLeft]; FLeftComponentEntity.HasButtonEntity := True; FLeftComponentEntity.ButtonEntity.HasBitmapImage := True; FLeftComponentEntity.ButtonEntity.BitmapImage.LoadPNGFromResource('Align_Text_Left'); FLeftComponentEntity.ButtonEntity.ClickHandler := AlignLeftButtonClickHandler; FCentreComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FCentreComponentEntity.Caption := CAPTIONS_TOOLBARWIDGET[tbwCentre]; FCentreComponentEntity.HasButtonEntity := True; FCentreComponentEntity.ButtonEntity.HasBitmapImage := True; FCentreComponentEntity.ButtonEntity.BitmapImage.LoadPNGFromResource('Align_Text_Center'); FCentreComponentEntity.ButtonEntity.ClickHandler := AlignCentreButtonClickHandler; FRightComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FRightComponentEntity.Caption := CAPTIONS_TOOLBARWIDGET[tbwRight]; FRightComponentEntity.HasButtonEntity := True; FRightComponentEntity.ButtonEntity.HasBitmapImage := True; FRightComponentEntity.ButtonEntity.BitmapImage.LoadPNGFromResource('Align_Text_Right'); FRightComponentEntity.ButtonEntity.ClickHandler := AlignRightButtonClickHandler; FJustifyComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FJustifyComponentEntity.Caption := CAPTIONS_TOOLBARWIDGET[tbwJustify]; FJustifyComponentEntity.HasButtonEntity := True; FJustifyComponentEntity.ButtonEntity.HasBitmapImage := True; FJustifyComponentEntity.ButtonEntity.BitmapImage.LoadPNGFromResource('Align_Text_Justify'); FJustifyComponentEntity.ButtonEntity.ClickHandler := AlignJustifyButtonClickHandler; oAdvancedToolbarSectionEntity := oAdvancedToolbarGroupEntity.AddNewSectionEntity; FOutdentComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FOutdentComponentEntity.Caption := CAPTIONS_TOOLBARWIDGET[tbwOutdent]; FOutdentComponentEntity.HasButtonEntity := True; FOutdentComponentEntity.ButtonEntity.HasBitmapImage := True; FOutdentComponentEntity.ButtonEntity.BitmapImage.LoadPNGFromResource('Indent_Decrease'); FOutdentComponentEntity.ButtonEntity.ClickHandler := OutdentButtonClickHandler; FIndentComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FIndentComponentEntity.Caption := CAPTIONS_TOOLBARWIDGET[tbwIndent]; FIndentComponentEntity.HasButtonEntity := True; FIndentComponentEntity.ButtonEntity.HasBitmapImage := True; FIndentComponentEntity.ButtonEntity.BitmapImage.LoadPNGFromResource('Indent_Increase'); FIndentComponentEntity.ButtonEntity.ClickHandler := IndentButtonClickHandler; oAdvancedToolbarSectionEntity := oAdvancedToolbarGroupEntity.AddNewSectionEntity; FNumbersComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FNumbersComponentEntity.Caption := CAPTIONS_TOOLBARWIDGET[tbwNumber]; FNumbersComponentEntity.HasButtonEntity := True; FNumbersComponentEntity.ButtonEntity.HasBitmapImage := True; FNumbersComponentEntity.ButtonEntity.BitmapImage.LoadPNGFromResource('Numbering'); FNumbersComponentEntity.ButtonEntity.ClickHandler := NumbersButtonClickHandler; FBulletsComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FBulletsComponentEntity.Caption := CAPTIONS_TOOLBARWIDGET[tbwBullet]; FBulletsComponentEntity.HasButtonEntity := True; FBulletsComponentEntity.ButtonEntity.HasBitmapImage := True; FBulletsComponentEntity.ButtonEntity.BitmapImage.LoadPNGFromResource('Bullets_Left'); FBulletsComponentEntity.ButtonEntity.ClickHandler := BulletsButtonClickHandler; oAdvancedToolbarGroupEntity := PresentationEntity.AddNewGroupEntity; oAdvancedToolbarGroupEntity.Caption := 'Editing'; oAdvancedToolbarSectionEntity := oAdvancedToolbarGroupEntity.AddNewSectionEntity; FSpellingComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FSpellingComponentEntity.Caption := CAPTIONS_TOOLBARWIDGET[tbwSpelling]; FSpellingComponentEntity.HasButtonEntity := True; FSpellingComponentEntity.ButtonEntity.HasBitmapImage := True; FSpellingComponentEntity.ButtonEntity.BitmapImage.LoadPNGFromResource('SpellCheck'); FSpellingComponentEntity.ButtonEntity.ClickHandler := SpellingButtonClickHandler; FSearchComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FSearchComponentEntity.Caption := CAPTIONS_TOOLBARWIDGET[tbwSearch]; FSearchComponentEntity.HasButtonEntity := True; FSearchComponentEntity.ButtonEntity.HasBitmapImage := True; FSearchComponentEntity.ButtonEntity.BitmapImage.LoadPNGFromResource('Search'); FSearchComponentEntity.ButtonEntity.ClickHandler := SearchButtonClickHandler; oAdvancedToolbarGroupEntity := PresentationEntity.AddNewGroupEntity; oAdvancedToolbarGroupEntity.Caption := 'Insert'; oAdvancedToolbarSectionEntity := oAdvancedToolbarGroupEntity.AddNewSectionEntity; FInsertFieldPopupMenu := TUixPopupMenu.Create(Self); FInsertFieldComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FInsertFieldComponentEntity.Caption := CAPTIONS_TOOLBARWIDGET[tbwInsertField]; FInsertFieldComponentEntity.HasButtonEntity := True; FInsertFieldComponentEntity.ButtonEntity.DropDownPopup := FInsertFieldPopupMenu; FInsertFieldComponentEntity.ButtonEntity.HasBitmapImage := True; FInsertFieldComponentEntity.ButtonEntity.BitmapImage.LoadPNGFromResource('Insert_Field'); FInsertFieldComponentEntity.ButtonEntity.ClickHandler := InsertFieldDefaultButtonClickHandler; FInsertTemplateComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FInsertTemplateComponentEntity.Caption := CAPTIONS_TOOLBARWIDGET[tbwInsertTemplate]; FInsertTemplateComponentEntity.HasButtonEntity := True; FInsertTemplateComponentEntity.ButtonEntity.HasBitmapImage := True; FInsertTemplateComponentEntity.ButtonEntity.BitmapImage.LoadPNGFromResource('Insert_Template'); FInsertTemplateComponentEntity.ButtonEntity.ClickHandler := InsertTemplateButtonClickHandler; FInsertPageBreakComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FInsertPageBreakComponentEntity.Caption := CAPTIONS_TOOLBARWIDGET[tbwInsertPageBreak]; FInsertPageBreakComponentEntity.HasButtonEntity := True; FInsertPageBreakComponentEntity.ButtonEntity.HasBitmapImage := True; FInsertPageBreakComponentEntity.ButtonEntity.BitmapImage.LoadPNGFromResource('Insert_Page_Break'); FInsertPageBreakComponentEntity.ButtonEntity.ClickHandler := InsertPageBreakButtonClickHandler; FInsertImageComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FInsertImageComponentEntity.Caption := CAPTIONS_TOOLBARWIDGET[tbwInsertImage]; FInsertImageComponentEntity.HasButtonEntity := True; FInsertImageComponentEntity.ButtonEntity.HasBitmapImage := True; FInsertImageComponentEntity.ButtonEntity.BitmapImage.LoadPNGFromResource('Insert_Image'); FInsertImageComponentEntity.ButtonEntity.ClickHandler := InsertImageButtonClickHandler; FInsertTableComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FInsertTableComponentEntity.Caption := CAPTIONS_TOOLBARWIDGET[tbwInsertTable]; FInsertTableComponentEntity.HasButtonEntity := True; FInsertTableComponentEntity.ButtonEntity.HasBitmapImage := True; FInsertTableComponentEntity.ButtonEntity.BitmapImage.LoadPNGFromResource('Insert_Table'); FInsertTableComponentEntity.ButtonEntity.ClickHandler := InsertTableButtonClickHandler; FInsertLineComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FInsertLineComponentEntity.Caption := CAPTIONS_TOOLBARWIDGET[tbwInsertLine]; FInsertLineComponentEntity.HasButtonEntity := True; FInsertLineComponentEntity.ButtonEntity.HasBitmapImage := True; FInsertLineComponentEntity.ButtonEntity.BitmapImage.LoadPNGFromResource('Horizontal_Line'); FInsertLineComponentEntity.ButtonEntity.ClickHandler := InsertLineButtonClickHandler; FEditHintsComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FEditHintsComponentEntity.Caption := CAPTIONS_TOOLBARWIDGET[tbwEditHints]; FEditHintsComponentEntity.HasButtonEntity := True; FEditHintsComponentEntity.ButtonEntity.HasBitmapImage := True; FEditHintsComponentEntity.ButtonEntity.BitmapImage.LoadPNGFromResource('Copy'); FEditHintsComponentEntity.ButtonEntity.ClickHandler := HintsButtonClickHandler; oAdvancedToolbarGroupEntity := PresentationEntity.AddNewGroupEntity; oAdvancedToolbarGroupEntity.Caption := 'Voice'; oAdvancedToolbarSectionEntity := oAdvancedToolbarGroupEntity.AddNewSectionEntity; FMacroComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FMacroComponentEntity.Caption := CAPTIONS_TOOLBARWIDGET[tbwMacro]; FMacroComponentEntity.HasButtonEntity := True; FMacroComponentEntity.ButtonEntity.HasBitmapImage := True; FMacroComponentEntity.ButtonEntity.BitmapImage.LoadPNGFromResource('Voice_Macro'); FMacroComponentEntity.ButtonEntity.ClickHandler := MacroButtonClickHandler; FPlaybackComponentEntity := oAdvancedToolbarSectionEntity.AddNewComponentEntity; FPlaybackComponentEntity.Caption := CAPTIONS_TOOLBARWIDGET[tbwPlayback]; FPlaybackComponentEntity.HasButtonEntity := True; FPlaybackComponentEntity.ButtonEntity.HasBitmapImage := True; FPlaybackComponentEntity.ButtonEntity.BitmapImage.LoadPNGFromResource('Voice_Speaker'); FPlaybackComponentEntity.ButtonEntity.ClickHandler := VoicePlaybackButtonClickHandler; Execute; End; Procedure TWordProcessorToolbar.LoadWordProcessorData; Var oFontNameList : TStringList; iFontNameIndex : Integer; iStyleIndex : Integer; Begin Assert(Invariants('LoadWordProcessorData', FWordProcessor, TWordProcessor, 'FWordProcessor')); FFontNameComboBox.Items.BeginUpdate; Try FFontNameComboBox.Items.Clear; oFontNameList := FWordProcessor.ListAllFonts; Try For iFontNameIndex := 0 To oFontNameList.Count - 1 Do FFontNameComboBox.Items.Add(oFontNameList[iFontNameIndex]); Finally oFontNameList.Free; End; FFontNameComboBox.Cache; Finally FFontNameComboBox.Items.EndUpdate; End; FStyleComboBox.Items.BeginUpdate; Try FStyleComboBox.Items.Clear; If FWordProcessor.HasWorkingStyles Then Begin For iStyleIndex := 0 To FWordProcessor.WorkingStyles.Count - 1 Do FStyleComboBox.Items.Add(FWordProcessor.WorkingStyles[iStyleIndex].Name); End; Finally FStyleComboBox.Items.EndUpdate; End; End; Procedure TWordProcessorToolbar.WordProcessorObserverNotificationHandler(oSender : TObject); Begin UpdateStatus; End; Procedure TWordProcessorToolbar.UpdateStatus; Var oWPStyle : TWPStyle; oWPFont : TWPSFontDetails; oWPParagraph : TWPSParagraphDetails; aRangeCapabilities : TWPCapabilities; iFieldDefinitionIndex : Integer; oDefinition : TWPFieldDefinitionProvider; iIconIndex : Integer; oMenu : TUixMenuItem; iStyleIndex : Integer; Begin NewComponentEntity.IsVisible := (tbwNew in VisibleWidgetSet) and assigned(FOnNew); OpenComponentEntity.IsVisible := (tbwOpen in VisibleWidgetSet) and assigned(FOnOpen); SaveComponentEntity.IsVisible := (tbwSave in VisibleWidgetSet) and assigned(FOnSave); SaveAsComponentEntity.IsVisible := (tbwSaveAs in VisibleWidgetSet) and assigned(FOnSaveAs); PrintComponentEntity.IsVisible := (tbwPrint in VisibleWidgetSet) and assigned(FOnPrint); PageDesignComponentEntity.IsVisible := (tbwPageDesign in VisibleWidgetSet) and assigned(FOnPageDesign); FPasteSpecialComponentEntity.IsVisible := tbwPasteSpecial In VisibleWidgetSet; FPasteComponentEntity.IsVisible := tbwPaste In VisibleWidgetSet; FCopyAllComponentEntity.IsVisible := tbwCopyAll In VisibleWidgetSet; FCopyComponentEntity.IsVisible := tbwCopy In VisibleWidgetSet; FCutComponentEntity.IsVisible := tbwCut In VisibleWidgetSet; FUndoComponentEntity.IsVisible := tbwUndo In VisibleWidgetSet; FRedoComponentEntity.IsVisible := tbwRedo In VisibleWidgetSet; FStyleComponentEntity.IsVisible := tbwStyle In VisibleWidgetSet; FFontNameComponentEntity.IsVisible := tbwFontName In VisibleWidgetSet; FFontSizeComponentEntity.IsVisible := tbwFontSize In VisibleWidgetSet; FBackColourComponentEntity.IsVisible := tbwBackColor In VisibleWidgetSet; FFontColourComponentEntity.IsVisible := tbwFontColour In VisibleWidgetSet; FBoldComponentEntity.IsVisible := tbwBold In VisibleWidgetSet; FItalicComponentEntity.IsVisible := tbwItalic In VisibleWidgetSet; FUnderlineComponentEntity.IsVisible := tbwUnderline In VisibleWidgetSet; FChangeCaseComponentEntity.IsVisible := tbwChangeCase In VisibleWidgetSet; FSubScriptComponentEntity.IsVisible := tbwSubscript In VisibleWidgetSet; FSuperScriptComponentEntity.IsVisible := tbwSuperscript In VisibleWidgetSet; FLeftComponentEntity.IsVisible := tbwLeft In VisibleWidgetSet; FCentreComponentEntity.IsVisible := tbwCentre In VisibleWidgetSet; FRightComponentEntity.IsVisible := tbwRight In VisibleWidgetSet; FJustifyComponentEntity.IsVisible := tbwJustify In VisibleWidgetSet; FOutdentComponentEntity.IsVisible := tbwOutdent In VisibleWidgetSet; FIndentComponentEntity.IsVisible := tbwIndent In VisibleWidgetSet; FNumbersComponentEntity.IsVisible := tbwNumber In VisibleWidgetSet; FBulletsComponentEntity.IsVisible := tbwBullet In VisibleWidgetSet; FSpellingComponentEntity.IsVisible := tbwSpelling In VisibleWidgetSet; FSearchComponentEntity.IsVisible := tbwSearch In VisibleWidgetSet; FMacroComponentEntity.IsVisible := tbwMacro In VisibleWidgetSet; FInsertFieldComponentEntity.IsVisible := tbwInsertField In VisibleWidgetSet; FInsertTemplateComponentEntity.IsVisible := tbwInsertTemplate In VisibleWidgetSet; FInsertPageBreakComponentEntity.IsVisible := tbwInsertPageBreak In VisibleWidgetSet; FInsertImageComponentEntity.IsVisible := tbwInsertImage In VisibleWidgetSet; FInsertTableComponentEntity.IsVisible := tbwInsertTable In VisibleWidgetSet; FInsertLineComponentEntity.IsVisible := tbwInsertTable In VisibleWidgetSet; FEditHintsComponentEntity.IsVisible := tbwEditHints In VisibleWidgetSet; FPlaybackComponentEntity.IsVisible := tbwPlayback In VisibleWidgetSet; FStyleComponentEntity.IsVisible := Not WordProcessor.Settings.ConsoleMode; FFontNameComponentEntity.IsVisible := Not WordProcessor.Settings.ConsoleMode; FFontSizeComponentEntity.IsVisible := Not WordProcessor.Settings.ConsoleMode; FBackColourComponentEntity.IsVisible := Not WordProcessor.Settings.ConsoleMode; FFontColourComponentEntity.IsVisible := Not WordProcessor.Settings.ConsoleMode; FChangeCaseComponentEntity.IsVisible := Not WordProcessor.Settings.ConsoleMode; FSubScriptComponentEntity.IsVisible := Not WordProcessor.Settings.ConsoleMode; FSuperScriptComponentEntity.IsVisible := Not WordProcessor.Settings.ConsoleMode; FLeftComponentEntity.IsVisible := Not WordProcessor.Settings.ConsoleMode; FCentreComponentEntity.IsVisible := Not WordProcessor.Settings.ConsoleMode; FRightComponentEntity.IsVisible := Not WordProcessor.Settings.ConsoleMode; FJustifyComponentEntity.IsVisible := Not WordProcessor.Settings.ConsoleMode; FOutdentComponentEntity.IsVisible := Not WordProcessor.Settings.ConsoleMode; FIndentComponentEntity.IsVisible := Not WordProcessor.Settings.ConsoleMode; FNumbersComponentEntity.IsVisible := Not WordProcessor.Settings.ConsoleMode; FBulletsComponentEntity.IsVisible := Not WordProcessor.Settings.ConsoleMode; FInsertFieldComponentEntity.IsVisible := Not WordProcessor.Settings.ConsoleMode; FInsertTemplateComponentEntity.IsVisible := Not WordProcessor.Settings.ConsoleMode; FInsertPageBreakComponentEntity.IsVisible := Not WordProcessor.Settings.ConsoleMode; FInsertImageComponentEntity.IsVisible := Not WordProcessor.Settings.ConsoleMode; FInsertTableComponentEntity.IsVisible := Not WordProcessor.Settings.ConsoleMode; FInsertLineComponentEntity.IsVisible := Not WordProcessor.Settings.ConsoleMode; If Assigned(FWordProcessor) Then Begin FStyleComboBox.Items.BeginUpdate; Try FStyleComboBox.Items.Clear; If FWordProcessor.HasWorkingStyles Then Begin For iStyleIndex := 0 To FWordProcessor.WorkingStyles.Count - 1 Do If FWordProcessor.WorkingStyles[iStyleIndex].HasParagraphAspect Then FStyleComboBox.Items.Add(FWordProcessor.WorkingStyles[iStyleIndex].Name + ' 6') Else FStyleComboBox.Items.Add(FWordProcessor.WorkingStyles[iStyleIndex].Name); End; Finally FStyleComboBox.Items.EndUpdate; End; oWPStyle := FWordProcessor.WorkingStyles.GetByName(FWordProcessor.PrimaryRange.Style); If Not Assigned(oWPStyle) Then oWPStyle := FWordProcessor.WorkingStyles.DefaultStyle; Assert(Invariants('LoadWordProcessorData', oWPStyle, TWPStyle, 'oWPStyle')); If Assigned(oWPStyle) Then Begin FStyleComboBox.ItemIndex := FWordProcessor.WorkingStyles.IndexByName(oWPStyle.Name); FFontNameComboBox.Text := oWPStyle.Font.Name; oWPFont := FWordProcessor.PrimaryRange.Font; FFontNameComboBox.Text := oWPStyle.WorkingFontName(oWPFont); FFontSizeComboBox.Text := IntToStr(oWPStyle.WorkingFontSize(oWPFont)); FFontColourComboBox.Value := oWPStyle.WorkingFontForeground(oWPFont); FBackColourComboBox.Value := oWPStyle.WorkingFontBackground(oWPFont, FWordProcessor.Color); FBoldComponentEntity.ButtonEntity.IsToggled := oWPStyle.WorkingFontBold(oWPFont) = tsTrue; FItalicComponentEntity.ButtonEntity.IsToggled := oWPStyle.WorkingFontItalic(oWPFont) = tsTrue; FUnderlineComponentEntity.ButtonEntity.IsToggled := oWPStyle.WorkingFontUnderline(oWPFont) = tsTrue; FSuperscriptComponentEntity.ButtonEntity.IsToggled := oWPStyle.WorkingFontState(oWPFont) = fsSuperscript; FSubscriptComponentEntity.ButtonEntity.IsToggled := oWPStyle.WorkingFontState(oWPFont) = fsSubscript; End; oWPParagraph := FWordProcessor.PrimaryRange.Paragraph; Assert(Invariants('LoadWordProcessorData', oWPParagraph, TWPSParagraphDetails, 'oWPParagraph')); FLeftComponentEntity.ButtonEntity.IsToggled := oWPParagraph.Align = WordProcessorParagraphAlignmentLeft; FRightComponentEntity.ButtonEntity.IsToggled := oWPParagraph.Align = WordProcessorParagraphAlignmentRight; FCentreComponentEntity.ButtonEntity.IsToggled := oWPParagraph.Align = WordProcessorParagraphAlignmentCentre; FJustifyComponentEntity.ButtonEntity.IsToggled := oWPParagraph.Align = WordProcessorParagraphAlignmentJustify; FBulletsComponentEntity.ButtonEntity.IsToggled := oWPParagraph.ListType = WPSParagraphListTypeBullets; FNumbersComponentEntity.ButtonEntity.IsToggled := oWPParagraph.ListType = WPSParagraphListTypeNumbers; FOutdentComponentEntity.IsEnabled := (oWPParagraph.LeftIndent > 0); aRangeCapabilities := FWordProcessor.PrimaryRange.Capabilities; FEditHintsComponentEntity.ButtonEntity.IsToggled := FWordProcessor.Settings.EditHints; FCutComponentEntity.IsEnabled := canCut In aRangeCapabilities; FCopyComponentEntity.IsEnabled := canWrite In aRangeCapabilities; FPasteComponentEntity.IsEnabled := (canInsert In aRangeCapabilities) And Clipboard.CanPaste; FPasteSpecialComponentEntity.IsEnabled := (canInsert In aRangeCapabilities) And Clipboard.CanPaste; FUndoComponentEntity.IsEnabled := canUndo In aRangeCapabilities; FRedoComponentEntity.IsEnabled := canRedo In aRangeCapabilities; FSearchComponentEntity.IsEnabled := FWordProcessor.Settings.Search; FMacroComponentEntity.IsEnabled := (canInsert In aRangeCapabilities) And Assigned(FWordProcessor.OnCodeCompletion); FPlaybackComponentEntity.IsEnabled := FWordProcessor.HasVoicePlayback; FSpellingComponentEntity.IsEnabled := Not FWordProcessor.Settings.ReadOnly; FStyleComboBox.Enabled := canFormat In aRangeCapabilities; FFontNameComboBox.Enabled := canFormat In aRangeCapabilities; FFontSizeComboBox.Enabled := canFormat In aRangeCapabilities; FFontColourComboBox.Enabled := canFormat In aRangeCapabilities; FBackColourComboBox.Enabled := canFormat In aRangeCapabilities; FBoldComponentEntity.IsEnabled := canFormat In aRangeCapabilities; FItalicComponentEntity.IsEnabled := canFormat In aRangeCapabilities; FUnderlineComponentEntity.IsEnabled := canFormat In aRangeCapabilities; FSuperscriptComponentEntity.IsEnabled := canFormat In aRangeCapabilities; FSubscriptComponentEntity.IsEnabled := canFormat In aRangeCapabilities; FChangeCaseComponentEntity.IsEnabled := (canFormat In aRangeCapabilities) And FWordProcessor.PrimaryRange.Selection.HasSelection; FLeftComponentEntity.IsEnabled := canFormat In aRangeCapabilities; FRightComponentEntity.IsEnabled := canFormat In aRangeCapabilities; FCentreComponentEntity.IsEnabled := canFormat In aRangeCapabilities; FJustifyComponentEntity.IsEnabled := canFormat In aRangeCapabilities; FBulletsComponentEntity.IsEnabled := canFormat In aRangeCapabilities; FNumbersComponentEntity.IsEnabled := canFormat In aRangeCapabilities; FIndentComponentEntity.IsEnabled := canFormat In aRangeCapabilities; FOutdentComponentEntity.IsEnabled := canFormat In aRangeCapabilities; FInsertTableComponentEntity.IsEnabled := canInsertTable In aRangeCapabilities; FInsertImageComponentEntity.IsEnabled := canInsertImage In aRangeCapabilities; FInsertLineComponentEntity.IsEnabled := canInsertLine In aRangeCapabilities; FInsertPageBreakComponentEntity.IsEnabled := canInsertPageBreak In aRangeCapabilities; If FInsertFieldComponentEntity.IsVisible Then Begin FInsertFieldPopupMenu.Items.Clear; For iFieldDefinitionIndex := 0 To FWordProcessor.Settings.FieldDefinitions.Count - 1 Do Begin oDefinition := FWordProcessor.Settings.FieldDefinitions[iFieldDefinitionIndex]; iIconIndex := oDefinition.GetStdIconIndex; If iIconIndex = -1 Then iIconIndex := WPIconModule.NONE; oMenu := TUixMenuItem.Create(Self); oMenu.Caption := oDefinition.GetTitle; oMenu.OnClick := InsertFieldMenuItemClickHandler; oMenu.ImageIndex := iIconIndex; oMenu.Tag := iFieldDefinitionIndex; oMenu.Enabled := oDefinition.CanInsertField; FInsertFieldPopupMenu.Items.Add(oMenu); End; End; End; Invalidate; End; Procedure TWordProcessorToolbar.FontNameChangeHandler(oSender : TObject); Begin If FFontNameComboBox.Items.IndexOf(FFontNameComboBox.Text) > -1 Then Begin FWordProcessor.PrimaryRange.ApplyFontName(FFontNameComboBox.Text); FWordProcessor.SetFocus; End; End; Procedure TWordProcessorToolbar.FontSizeChangeHandler(oSender: TObject); Begin If StringIsInteger32(FFontSizeComboBox.Text) Then FWordProcessor.PrimaryRange.ApplyFontSize(StringToInteger32(FFontSizeComboBox.Text)); FWordProcessor.SetFocus; End; Procedure TWordProcessorToolbar.AlignCentreButtonClickHandler(oSender: TObject); Begin FWordProcessor.PrimaryRange.AlignCentre; End; Procedure TWordProcessorToolbar.AlignJustifyButtonClickHandler(oSender: TObject); Begin FWordProcessor.PrimaryRange.AlignJustify; End; Procedure TWordProcessorToolbar.AlignLeftButtonClickHandler(oSender: TObject); Begin FWordProcessor.PrimaryRange.AlignLeft; End; Procedure TWordProcessorToolbar.AlignRightButtonClickHandler(oSender: TObject); Begin FWordProcessor.PrimaryRange.AlignRight; End; Procedure TWordProcessorToolbar.BoldButtonClickHandler(oSender: TObject); Begin FBoldComponentEntity.ButtonEntity.IsToggled := Not FBoldComponentEntity.ButtonEntity.IsToggled; FWordProcessor.PrimaryRange.ApplyBold(FBoldComponentEntity.ButtonEntity.IsToggled); Refresh; End; Procedure TWordProcessorToolbar.BulletsButtonClickHandler(oSender: TObject); Begin FWordProcessor.PrimaryRange.ApplyBullets(FWordProcessor.PrimaryRange.Paragraph.ListType <> WPSParagraphListTypeBullets); End; Procedure TWordProcessorToolbar.CaseButtonClickHandler(oSender: TObject); Begin FWordProcessor.ChangeCaseDialog; End; Procedure TWordProcessorToolbar.CopyAllButtonClickHandler(oSender: TObject); Begin FWordProcessor.CopyAllToClipboard;; End; Procedure TWordProcessorToolbar.CopyButtonClickHandler(oSender: TObject); Begin FWordProcessor.PrimaryRange.Copy; End; Procedure TWordProcessorToolbar.CutButtonClickHandler(oSender: TObject); Begin FWordProcessor.PrimaryRange.Cut; End; Procedure TWordProcessorToolbar.IndentButtonClickHandler(oSender: TObject); Begin FWordProcessor.PrimaryRange.ApplyLeftIndent(+1); End; Procedure TWordProcessorToolbar.InsertFieldDefaultButtonClickHandler(oSender: TObject); Begin FWordProcessor.InsertField(Nil); End; Procedure TWordProcessorToolbar.InsertImageButtonClickHandler(oSender: TObject); Begin FWordProcessor.InsertImageDialog; End; Procedure TWordProcessorToolbar.InsertLineButtonClickHandler(oSender: TObject); Begin FWordProcessor.PrimaryRange.InsertLine; End; Procedure TWordProcessorToolbar.InsertPageBreakButtonClickHandler(oSender: TObject); Begin FWordProcessor.PrimaryRange.InsertPageBreak; End; Procedure TWordProcessorToolbar.InsertTableButtonClickHandler(oSender: TObject); Begin FWordProcessor.InsertTableDialog; End; Procedure TWordProcessorToolbar.InsertTemplateButtonClickHandler; Begin FWordProcessor.InsertTemplate; End; Procedure TWordProcessorToolbar.ItalicsButtonClickHandler; Begin FItalicComponentEntity.ButtonEntity.IsToggled := Not FItalicComponentEntity.ButtonEntity.IsToggled; FWordProcessor.PrimaryRange.ApplyItalic(FItalicComponentEntity.ButtonEntity.IsToggled); Refresh; End; Procedure TWordProcessorToolbar.MacroButtonClickHandler; Begin FWordProcessor.CodeCompletePrompt; End; Procedure TWordProcessorToolbar.NumbersButtonClickHandler; Begin FWordProcessor.PrimaryRange.ApplyNumbers(FWordProcessor.PrimaryRange.Paragraph.ListType <> WPSParagraphListTypeNumbers); End; Procedure TWordProcessorToolbar.OutdentButtonClickHandler; Begin FWordProcessor.PrimaryRange.ApplyLeftIndent(-1); End; Procedure TWordProcessorToolbar.PasteButtonClickHandler; Var sError : String; Begin If Not FWordProcessor.PrimaryRange.Paste(sError) Then DialogError(sError); End; Procedure TWordProcessorToolbar.PasteSpecialButtonClickHandler; Begin FWordProcessor.PasteSpecialDialog; End; Procedure TWordProcessorToolbar.RedoButtonClickHandler(oSender: TObject); Begin FWordProcessor.PrimaryRange.Redo; End; Procedure TWordProcessorToolbar.SearchButtonClickHandler(oSender: TObject); Begin FWordProcessor.SearchDialog; End; Procedure TWordProcessorToolbar.SpellingButtonClickHandler(oSender: TObject); Begin FWordProcessor.CheckSpelling; End; Procedure TWordProcessorToolbar.SubscriptButtonClickHandler(oSender: TObject); Begin FSubscriptComponentEntity.ButtonEntity.IsToggled := Not FSubscriptComponentEntity.ButtonEntity.IsToggled; FWordProcessor.PrimaryRange.ApplySubscript(FSubscriptComponentEntity.ButtonEntity.IsToggled); Refresh; End; Procedure TWordProcessorToolbar.SuperscriptButtonClickHandler(oSender: TObject); Begin FSuperscriptComponentEntity.ButtonEntity.IsToggled := Not FSuperscriptComponentEntity.ButtonEntity.IsToggled; FWordProcessor.PrimaryRange.ApplySuperscript(FSuperscriptComponentEntity.ButtonEntity.IsToggled); Refresh; End; Procedure TWordProcessorToolbar.UnderlineButtonClickHandler(oSender: TObject); Begin FUnderlineComponentEntity.ButtonEntity.IsToggled := Not FUnderlineComponentEntity.ButtonEntity.IsToggled; FWordProcessor.PrimaryRange.ApplyUnderline(FUnderlineComponentEntity.ButtonEntity.IsToggled); Refresh; End; Procedure TWordProcessorToolbar.UndoButtonClickHandler(oSender: TObject); Begin FWordProcessor.PrimaryRange.Undo; End; Procedure TWordProcessorToolbar.VoicePlaybackButtonClickHandler(oSender: TObject); Begin FWordProcessor.VoicePlayback; End; Procedure TWordProcessorToolbar.HintsButtonClickHandler(oSender: TObject); Begin FWordProcessor.Settings.EditHints := Not FWordProcessor.Settings.EditHints; End; Procedure TWordProcessorToolbar.FontColourChangeHandler(oSender: TObject); Begin FWordProcessor.PrimaryRange.ApplyForeground(FFontColourComboBox.Value); FWordProcessor.SetFocus; End; Procedure TWordProcessorToolbar.BackColourChangeHandler(oSender: TObject); Begin FWordProcessor.PrimaryRange.ApplyBackground(FBackColourComboBox.Value); FWordProcessor.SetFocus; End; Procedure TWordProcessorToolbar.Refresh; Begin UpdateStatus; End; Procedure TWordProcessorToolbar.InsertFieldMenuItemClickHandler(oSender: TObject); Var oDefinition : TWPFieldDefinitionProvider; Begin oDefinition := FWordProcessor.Settings.FieldDefinitions[TUixMenuItem(oSender).Tag]; FWordProcessor.InsertField(oDefinition); End; Procedure TWordProcessorToolbar.SetWordProcessor(Const Value: TWordProcessor); Begin FWordProcessor := Value; If Assigned(FWordProcessor) Then Begin Build; LoadWordProcessorData; FWordProcessor.RegisterObserver(Self, WordProcessorObserverNotificationHandler); End; End; Procedure TWordProcessorToolbar.StyleChangeHandler(oSender : TObject); var sStyle : String; Begin If FStyleComboBox.Items.IndexOf(FStyleComboBox.Text) > -1 Then Begin sStyle := FStyleComboBox.Text; if StringEndsWith(sStyle, ' 6') Then SetLength(sStyle, length(sStyle)-2); FWordProcessor.PrimaryRange.Style := sStyle; FWordProcessor.SetFocus; End; End; Procedure TWordProcessorToolbar.NewButtonClickHandler(oSender : TObject); begin if assigned(onNew) then onNew(self); end; Procedure TWordProcessorToolbar.OpenButtonClickHandler(oSender : TObject); begin if assigned(onOpen) then onOpen(self); end; Procedure TWordProcessorToolbar.SaveButtonClickHandler(oSender : TObject); begin if assigned(onSave) then onSave(Self); end; Procedure TWordProcessorToolbar.SaveAsButtonClickHandler(oSender : TObject); begin if assigned(onSaveAs) then onSaveAs(Self); end; procedure TWordProcessorToolbar.PrintButtonClickHandler(oSender : TObject); begin if assigned(onPrint) then onPrint(Self); end; Procedure TWordProcessorToolbar.PageDesignButtonClickHandler(oSender : TObject); begin if assigned(onPageDesign) then onPageDesign(Self); end; { TWordProcessorTouchToolbar } Constructor TWordProcessorTouchToolbar.Create(oOwner: TComponent); Begin Inherited; FColourDialog := TColorDialog.Create(Owner); FColourDialog.Options := [cdFullOpen, cdSolidColor, cdAnyColor]; FImages := TUixImages.Create(Nil); FImages.Height := 32; FImages.Width := 32; FImages.LoadBitmapFromResource('WordProcessorTouchToolbarImageSet', clFuchsia); FWordProcessor := Nil; VisibleWidgetSet := WordProcessorTouchToolbarWidgetDefaultSet; End; Destructor TWordProcessorTouchToolbar.Destroy; Begin FColourDialog.Free; FWordProcessor := Nil; FImages.free; Inherited; End; Function TWordProcessorTouchToolbar.button(owner : TWinControl; top, left : integer; image : integer; hint : string; enabled : boolean; captioned : boolean) : TSpeedButton; var bmp : TBitmap; begin result := TSpeedButton.create(owner); result.Parent := owner; result.Left := 4 + left * LEFT_INC_H; result.Top := 4 + top * LEFT_INC_V; if captioned then result.Top := result.Top + 20; result.Height := 58; result.Width := 68; result.Caption := hint; result.Layout := blGlyphTop; result.Hint := hint; result.Enabled := enabled; result.Flat := true; bmp := TBitmap.Create; try FImages.GetBitmap(image, bmp); result.Glyph.Assign(bmp); result.NumGlyphs := 1; finally bmp.Free; end; end; procedure TWordProcessorTouchToolbar.caption(owner: TWinControl; top, width: integer; title: string); var bev : TUixBevel; lbl : TUixLabel; begin bev := TUixBevel.Create(owner); bev.Parent := owner; bev.Top := top * LEFT_INC_V + 14; bev.Height := 10; bev.Shape := bsTopLine; bev.Left := 10; bev.Width := width * LEFT_INC_H - 10; lbl := TUixLabel.Create(owner); lbl.Parent := owner; lbl.Top := top * LEFT_INC_V + 7; lbl.Height := 20; lbl.Left := 2+15; lbl.Caption := ' '+title+' '; lbl.Transparent := false; end; procedure TWordProcessorTouchToolbar.DoChangeCaseOperation(sender: TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.ChangeCaseDialog; end; procedure TWordProcessorTouchToolbar.DoCopyFilenameOperation(sender: TObject); begin FWordProcessor.WantCloseTouchMenu; OnCopyFilename(self); end; procedure TWordProcessorTouchToolbar.DoCopyOperation(sender: TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.Copy; end; procedure TWordProcessorTouchToolbar.DoCutOperation(sender: TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.Cut; end; procedure TWordProcessorTouchToolbar.DoEditField(sender: TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.FieldPropertiesDialog; end; procedure TWordProcessorTouchToolbar.DoEditMenu(sender: TObject); begin FCurrentMenu := FWordProcessor.CreateTouchMenu; FCurrentMenu.Left := 4 + LEFT_INC_H; FCurrentMenu.Width := LEFT_INC_H * 2 + 6; FCurrentMenu.Height := LEFT_INC_V * 5 + 4; button(FCurrentMenu, 0, 0, Btn_Offs_Cut, 'Cut', canCut in FWordProcessor.PrimaryRange.Capabilities).OnClick := DoCutOperation; button(FCurrentMenu, 1, 0, Btn_Offs_Copy, 'Copy', canWrite in FWordProcessor.PrimaryRange.Capabilities).OnClick := DoCopyOperation; button(FCurrentMenu, 2, 0, Btn_Offs_Paste, 'Paste', canInsert in FWordProcessor.PrimaryRange.Capabilities).OnClick := DoPasteOperation; button(FCurrentMenu, 3, 0, Btn_Offs_PasteSpecial, 'Import', canInsert in FWordProcessor.PrimaryRange.Capabilities).OnClick := DoPasteSpecialOperation; button(FCurrentMenu, 4, 0, Btn_Offs_CopyFilename, 'Copy name', true).OnClick := DoCopyFilenameOperation; button(FCurrentMenu, 0, 1, Btn_Offs_Undo, 'Undo', FWordProcessor.PrimaryRange.CanUndo_).OnClick := DoUndoOperation; button(FCurrentMenu, 1, 1, Btn_Offs_Redo, 'Redo', FWordProcessor.PrimaryRange.CanRedo_).OnClick := DoRedoOperation; button(FCurrentMenu, 2, 1, Btn_Offs_Search, 'Search', true).OnClick := DoSearchOperation; button(FCurrentMenu, 3, 1, Btn_Offs_Replace, 'Replace', true).OnClick := DoReplaceOperation; button(FCurrentMenu, 4, 1, Btn_Offs_ChangeCase, 'Case', FWordProcessor.PrimaryRange.Selection.HasSelection).OnClick := DoChangeCaseOperation; end; procedure TWordProcessorTouchToolbar.DoEmailOperation(sender: TObject); begin FWordProcessor.WantCloseTouchMenu; OnEmail(self); end; procedure TWordProcessorTouchToolbar.DoExitOperation(sender: TObject); begin FWordProcessor.WantCloseTouchMenu; OnExit(self); end; procedure TWordProcessorTouchToolbar.DoFaxOperation(sender: TObject); begin FWordProcessor.WantCloseTouchMenu; OnFax(self); end; procedure TWordProcessorTouchToolbar.DoFieldMenu(sender: TObject); begin FCurrentMenu := FWordProcessor.CreateTouchMenu; FCurrentMenu.Left := 4 + LEFT_INC_H * 6; FCurrentMenu.Width := LEFT_INC_H * 2 + 6; FCurrentMenu.Height := LEFT_INC_V * 2 + 4; button(FCurrentMenu, 0, 0, Btn_Offs_Previous, 'Previous', canGotoField In FWordProcessor.PrimaryRange.Capabilities).OnClick := DoPreviousField; button(FCurrentMenu, 0, 1, Btn_Offs_Next, 'Next', canGotoField In FWordProcessor.PrimaryRange.Capabilities).OnClick := DoNextField; button(FCurrentMenu, 1, 0, Btn_Offs_EditField, 'Edit', FWordProcessor.PrimaryRange.HasCurrentFieldStart).OnClick := DoEditField; button(FCurrentMenu, 1, 1, Btn_Offs_RemoveField, 'Remove', FWordProcessor.PrimaryRange.HasCurrentFieldStart).OnClick := DoRemoveField; end; procedure TWordProcessorTouchToolbar.DoFontMenu(sender: TObject); begin FCurrentMenu := FWordProcessor.CreateTouchMenu; FCurrentMenu.Left := 4 + LEFT_INC_H * 2; FCurrentMenu.Width := LEFT_INC_H * 2 + 6; FCurrentMenu.Height := LEFT_INC_V * 4 + 4; button(FCurrentMenu, 0, 0, Btn_Offs_Bold, 'Bold', canFormat in FWordProcessor.PrimaryRange.Capabilities).OnClick := DoBoldButton; button(FCurrentMenu, 1, 0, Btn_Offs_Italic, 'Italic', canFormat in FWordProcessor.PrimaryRange.Capabilities).OnClick := DoItalicButton; button(FCurrentMenu, 2, 0, Btn_Offs_Underline, 'Underline', canFormat in FWordProcessor.PrimaryRange.Capabilities).OnClick := DoUnderlineButton; button(FCurrentMenu, 3, 0, Btn_Offs_FontProps, 'Properties', canFormat in FWordProcessor.PrimaryRange.Capabilities).OnClick := DoFontPropertiesButton; button(FCurrentMenu, 0, 1, Btn_Offs_Colour, 'Colour', canFormat in FWordProcessor.PrimaryRange.Capabilities).OnClick := DoColourButton; button(FCurrentMenu, 1, 1, Btn_Offs_Background, 'Background', canFormat in FWordProcessor.PrimaryRange.Capabilities).OnClick := DoBackgroundButton; button(FCurrentMenu, 2, 1, Btn_Offs_Superscript, 'Superscript', canFormat in FWordProcessor.PrimaryRange.Capabilities).OnClick := DoSuperscriptButton; button(FCurrentMenu, 3, 1, Btn_Offs_Subscript, 'Subscript', canFormat in FWordProcessor.PrimaryRange.Capabilities).OnClick := DoSubscriptButton; end; procedure TWordProcessorTouchToolbar.DoImageEditButton(sender: TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.ImagePropertiesDialog; end; procedure TWordProcessorTouchToolbar.DoImageMapButton(sender: TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.ImageMapsDialog; end; procedure TWordProcessorTouchToolbar.DoImageMenu(sender: TObject); begin FCurrentMenu := FWordProcessor.CreateTouchMenu; FCurrentMenu.Left := 4 + LEFT_INC_H * 5; FCurrentMenu.Width := LEFT_INC_H * 3 + 8; FCurrentMenu.Height := LEFT_INC_V * 3 + 5; button(FCurrentMenu, 0, 0, Btn_Offs_Picture, 'Insert', canInsertImage in FWordProcessor.PrimaryRange.Capabilities).OnClick := DoPictureButton; button(FCurrentMenu, 1, 0, Btn_Offs_ImageMap, 'Map Editor', FWordProcessor.PrimaryRange.HasCurrentImage).OnClick := DoImageMapButton; button(FCurrentMenu, 2, 0, Btn_Offs_ImageEdit, 'Properties', FWordProcessor.PrimaryRange.HasCurrentImage).OnClick := DoImageEditButton; button(FCurrentMenu, 0, 1, Btn_Offs_Select, 'Select', FWordProcessor.PrimaryRange.HasCurrentImage).OnClick := DoSelectButton; button(FCurrentMenu, 1, 1, Btn_Offs_Line, 'Draw Line', FWordProcessor.PrimaryRange.HasCurrentImage).OnClick := DoLineButton; button(FCurrentMenu, 2, 1, Btn_Offs_Rect, 'Draw Rect', FWordProcessor.PrimaryRange.HasCurrentImage).OnClick := DoRectButton; button(FCurrentMenu, 0, 2, Btn_Offs_Circle, 'Draw Circle', FWordProcessor.PrimaryRange.HasCurrentImage).OnClick := DoCircleButton; button(FCurrentMenu, 1, 2, Btn_Offs_Mark, 'Draw Mark', FWordProcessor.PrimaryRange.HasCurrentImage).OnClick := DoMarkButton; button(FCurrentMenu, 2, 2, Btn_Offs_Zoom, 'Zoom', FWordProcessor.PrimaryRange.HasCurrentImage).OnClick := DoZoomButton; { Image Insert Tool (select | line | rectangle | circle | mark | zoom) Properties } end; procedure TWordProcessorTouchToolbar.DoInsertMenu(sender: TObject); var i : integer; definition : TWPFieldDefinitionProvider; btn : TSpeedButton; begin i := IntegerMin(3, FWordProcessor.Settings.FieldDefinitions.Count); FCurrentMenu := FWordProcessor.CreateTouchMenu; FCurrentMenu.Left := 4 + LEFT_INC_H * 4; FCurrentMenu.Width := LEFT_INC_H * 3 + 6; if i mod 3 = 0 then FCurrentMenu.Height := LEFT_INC_V * (2 + i div 3) + 4 + 20 else FCurrentMenu.Height := LEFT_INC_V * (3 + i div 3) + 4 + 20; button(FCurrentMenu, 0, 0, Btn_Offs_Symbol, 'Symbol', canInsert in FWordProcessor.PrimaryRange.Capabilities).OnClick := DoSymbolButton; button(FCurrentMenu, 0, 1, Btn_Offs_Picture, 'Picture', canInsertImage in FWordProcessor.PrimaryRange.Capabilities).OnClick := DoPictureButton; button(FCurrentMenu, 0, 2, Btn_Offs_Break, 'Break', canInsertPageBreak in FWordProcessor.PrimaryRange.Capabilities).OnClick := DoBreakButton; button(FCurrentMenu, 1, 0, Btn_Offs_Template, 'Template', canInsert in FWordProcessor.PrimaryRange.Capabilities).OnClick := DoTemplateButton; button(FCurrentMenu, 1, 1, Btn_Offs_InsLine, 'Line', canInsertLine in FWordProcessor.PrimaryRange.Capabilities).OnClick := DoInsLineButton; button(FCurrentMenu, 1, 2, Btn_Offs_InsTable, 'Table', canInsertTable in FWordProcessor.PrimaryRange.Capabilities).OnClick := DoInsTableButton; caption(FCurrentMenu, 2, 3, 'Fields'); for i := 0 To FWordProcessor.Settings.FieldDefinitions.Count - 1 Do begin definition := FWordProcessor.Settings.FieldDefinitions[i]; btn := button(FCurrentMenu, 2 + i div 3, i mod 3, definition.GetTouchIconIndex, definition.GetTitle, true, true); btn.OnClick := DoInsFieldButton; btn.Tag := Integer(definition); end; // todo : comment; end; procedure TWordProcessorTouchToolbar.DoInsFieldButton(sender: TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.InsertField(TWPFieldDefinitionProvider((sender as TComponent).tag)); end; procedure TWordProcessorTouchToolbar.DoNewOperation(sender: TObject); begin FWordProcessor.WantCloseTouchMenu; OnNew(self); end; procedure TWordProcessorTouchToolbar.DoNextField(sender: TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.PrimaryRange.NextField; end; procedure TWordProcessorTouchToolbar.DoOpenOperation(sender: TObject); begin FWordProcessor.WantCloseTouchMenu; OnOpen(self); end; procedure TWordProcessorTouchToolbar.DoOperationsMenu(sender: TObject); begin FCurrentMenu := FWordProcessor.CreateTouchMenu; FCurrentMenu.Left := 4; FCurrentMenu.Width := LEFT_INC_H * 2 + 6; FCurrentMenu.Height := LEFT_INC_V * 4 + 4; button(FCurrentMenu, 0, 0, Btn_Offs_New, 'New', true).OnClick := DoNewOperation; button(FCurrentMenu, 1, 0, Btn_Offs_Open, 'Open', true).OnClick := DoOpenOperation; button(FCurrentMenu, 2, 0, Btn_Offs_Save, 'Save', true).OnClick := DoSaveOperation; button(FCurrentMenu, 3, 0, Btn_Offs_SaveAs, 'Save As', true).OnClick := DoSaveAsOperation; button(FCurrentMenu, 0, 1, Btn_Offs_Print, 'Print', true).OnClick := DoPrintOperation; button(FCurrentMenu, 1, 1, Btn_Offs_Fax, 'Fax', true).OnClick := DoFaxOperation; button(FCurrentMenu, 2, 1, Btn_Offs_Email, 'Email', true).OnClick := DoEmailOperation; button(FCurrentMenu, 3, 1, Btn_Offs_Exit, 'Exit', true).OnClick := DoExitOperation; end; procedure TWordProcessorTouchToolbar.DoOptionsButton(sender: TObject); begin FWordProcessor.WantCloseTouchMenu; OnOptions(self); end; procedure TWordProcessorTouchToolbar.DoParagraphMenu(sender: TObject); begin FCurrentMenu := FWordProcessor.CreateTouchMenu; FCurrentMenu.Left := 4 + LEFT_INC_H * 3; FCurrentMenu.Width := LEFT_INC_H * 4 + 6; FCurrentMenu.Height := LEFT_INC_V * 3 + 4; button(FCurrentMenu, 0, 0, Btn_Offs_Left, 'Left', true).OnClick := DoLeftButton; button(FCurrentMenu, 0, 1, Btn_Offs_Center, 'Center', true).OnClick := DoCenterButton; button(FCurrentMenu, 0, 2, Btn_Offs_Right, 'Right', true).OnClick := DoRightButton; button(FCurrentMenu, 0, 3, Btn_Offs_Justify, 'Justify', true).OnClick := DoJustifyButton; button(FCurrentMenu, 1, 0, Btn_Offs_Normal, 'Normal', true).OnClick := DoNormalButton; button(FCurrentMenu, 1, 1, Btn_Offs_Bullets, 'Bullets', true).OnClick := DoBulletsButton; button(FCurrentMenu, 1, 2, Btn_Offs_Numbers, 'Numbers', true).OnClick := DoNumbersButton; button(FCurrentMenu, 2, 0, Btn_Offs_Indent, 'Indent', true).OnClick := DoIndentButton; button(FCurrentMenu, 2, 1, Btn_Offs_Outdent, 'Outdent', true).OnClick := DoOutdentButton; button(FCurrentMenu, 2, 3, Btn_Offs_ParaProps, 'Properties', true).OnClick := DoParaPropsButton; end; procedure TWordProcessorTouchToolbar.DoPasteOperation(sender: TObject); var sErr : String; begin FWordProcessor.WantCloseTouchMenu; if not FWordProcessor.Paste(sErr) then ShowMessage(sErr); end; procedure TWordProcessorTouchToolbar.DoPasteSpecialOperation(sender: TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.PasteSpecialDialog; end; procedure TWordProcessorTouchToolbar.DoPreviousField(sender: TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.PrimaryRange.PreviousField; end; procedure TWordProcessorTouchToolbar.DoPrintOperation(sender: TObject); begin FWordProcessor.WantCloseTouchMenu; OnPrint(self); end; procedure TWordProcessorTouchToolbar.DoRedoOperation(sender: TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.Redo; end; procedure TWordProcessorTouchToolbar.DoRemoveField(sender: TObject); begin FWordProcessor.WantCloseTouchMenu; Case MessageDlg('Remove Field. Keep Field Contents?', mtConfirmation, mbYesNoCancel, 0) Of mrYes : FWordProcessor.PrimaryRange.RemoveField(True); mrNo : FWordProcessor.PrimaryRange.RemoveField(False); End; end; procedure TWordProcessorTouchToolbar.DoReplaceOperation(sender: TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.ReplaceDialog; end; procedure TWordProcessorTouchToolbar.DoSaveAsOperation(sender: TObject); begin FWordProcessor.WantCloseTouchMenu; OnSaveAs(self); end; procedure TWordProcessorTouchToolbar.DoSaveOperation(sender: TObject); begin FWordProcessor.WantCloseTouchMenu; OnSave(self); end; procedure TWordProcessorTouchToolbar.DoSearchOperation(sender: TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.SearchDialog; end; procedure TWordProcessorTouchToolbar.DoSpellButton(sender: TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.CheckSpelling; end; procedure TWordProcessorTouchToolbar.DoStylesButton(sender: TObject); begin FWordProcessor.WantCloseTouchMenu; ShowMessage('todo'); end; procedure TWordProcessorTouchToolbar.DoTableMenu(sender: TObject); begin FCurrentMenu := FWordProcessor.CreateTouchMenu; FCurrentMenu.Left := 4 + LEFT_INC_H * 7; FCurrentMenu.Width := LEFT_INC_H * 4 + 6; FCurrentMenu.Height := LEFT_INC_V * 5 + 4; button(FCurrentMenu, 0, 0, Btn_Offs_InsTable, 'Insert', canInsertTable in FWordProcessor.PrimaryRange.Capabilities).OnClick := DoInsTableButton; if FWordProcessor.PrimaryRange.HasCurrentTableStart then button(FCurrentMenu, 0, 1, Btn_Offs_TableToText, 'Convert', true).OnClick := DoTableToTextButton else button(FCurrentMenu, 0, 1, Btn_Offs_TextToTable, 'Convert', FWordProcessor.PrimaryRange.SelectedText <> '').OnClick := DoTextToTableButton; button(FCurrentMenu, 0, 3, Btn_Offs_TableProps, 'Properties', canTableProps in FWordProcessor.PrimaryRange.Capabilities).OnClick := DoTablePropsButton; button(FCurrentMenu, 1, 0, Btn_Offs_SelRow, 'Select Row', canSelectRow in FWordProcessor.PrimaryRange.Capabilities).OnClick := DoSelRowButton; button(FCurrentMenu, 1, 1, Btn_Offs_SelTable, 'Select Table', canSelectTable in FWordProcessor.PrimaryRange.Capabilities).OnClick := DoSelTableButton; button(FCurrentMenu, 1, 2, Btn_Offs_Sort, 'Sort Table', canSortTable in FWordProcessor.PrimaryRange.Capabilities).OnClick := DoSortTableButton; button(FCurrentMenu, 2, 0, Btn_Offs_InsColLeft, 'Insert Left', canInsertColumn in FWordProcessor.PrimaryRange.Capabilities).OnClick := DoInsertLeftButton; button(FCurrentMenu, 2, 1, Btn_Offs_InsColRight, 'Insert Right', canInsertColumn in FWordProcessor.PrimaryRange.Capabilities).OnClick := DoInsertRightButton; button(FCurrentMenu, 2, 2, Btn_Offs_InsRowAbove, 'Insert Above', canInsertRowAbove in FWordProcessor.PrimaryRange.Capabilities).OnClick := DoInsertAboveButton; button(FCurrentMenu, 2, 3, Btn_Offs_InsRowBelow, 'Insert Below', canInsertRowBelow in FWordProcessor.PrimaryRange.Capabilities).OnClick := DoInsertBelowButton; button(FCurrentMenu, 3, 0, Btn_Offs_DelCol, 'Delete Column', canRemoveColumn in FWordProcessor.PrimaryRange.Capabilities).OnClick := DoDelColButton; button(FCurrentMenu, 3, 1, Btn_Offs_DelRow, 'Delete Row', canRemoveRow in FWordProcessor.PrimaryRange.Capabilities).OnClick := DoDelRowButton; button(FCurrentMenu, 3, 2, Btn_Offs_DelTable, 'Delete Table', canRemoveTable in FWordProcessor.PrimaryRange.Capabilities).OnClick := DoDelTableButton; end; procedure TWordProcessorTouchToolbar.DoToolsMenu(sender: TObject); begin FCurrentMenu := FWordProcessor.CreateTouchMenu; FCurrentMenu.Left := 4 + LEFT_INC_H * 8; FCurrentMenu.Width := LEFT_INC_H * 1 + 6; FCurrentMenu.Height := LEFT_INC_V * 3 + 4; button(FCurrentMenu, 0, 0, Btn_Offs_Spell, 'Spell Check', true).OnClick := DoSpellButton; button(FCurrentMenu, 1, 0, Btn_Offs_Styles, 'Style Editor', true).OnClick := DoStylesButton; button(FCurrentMenu, 2, 0, Btn_Offs_Options, 'Options', true).OnClick := DoOptionsButton; end; procedure TWordProcessorTouchToolbar.DoUndoOperation(sender: TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.Undo; end; Procedure TWordProcessorTouchToolbar.Build; var left : integer; bev : TUixBevel; Begin Height := 60; Left := 0; Color := clWhite; ParentColor := false; ParentBackground := false; bev := TUixBevel.Create(self); bev.ShapeBottomLine; bev.AlignBottom; FOperationsButton := Button(self, 0, 0, Btn_Offs_Cat_Operations, 'File', true); FOperationsButton.OnClick := DoOperationsMenu; FEditButton := Button(self, 0, 1, Btn_Offs_Cat_Edit, 'Edit', true); FEditButton.OnClick := DoEditMenu; FFontButton := button(self, 0, 2, Btn_Offs_Cat_Font, 'Font', true); FFontButton.OnClick := DoFontMenu; FParagraphButton := button(self, 0, 3, Btn_Offs_Cat_Paragraph, 'Paragraph', true); FParagraphButton.OnClick := DoParagraphMenu; FInsertButton := button(self, 0, 4, Btn_Offs_Cat_Insert, 'Insert', true); FInsertButton.OnClick := DoInsertMenu; FImageButton := button(self, 0, 5, Btn_Offs_Cat_Image, 'Image', true); FImageButton.OnClick := DoImageMenu; FFieldButton := button(self, 0, 6, Btn_Offs_Cat_Field, 'Field', true); FFieldButton.OnClick := DoFieldMenu; FTableButton := button(self, 0, 7, Btn_Offs_Cat_Table, 'Table', true); FTableButton.OnClick := DoTableMenu; FToolsButton := button(self, 0, 8, Btn_Offs_Cat_Tools, 'Tools', true); FToolsButton.OnClick := DoToolsMenu; FHelpButton := button(self, 0, 9, Btn_Offs_cat_Help, 'Help', true); FHelpButton.OnClick := DoHelpMenu; End; Procedure TWordProcessorTouchToolbar.LoadWordProcessorData; Begin End; Procedure TWordProcessorTouchToolbar.WordProcessorObserverNotificationHandler(oSender : TObject); Begin updateStatus; End; Procedure TWordProcessorTouchToolbar.UpdateStatus; Begin End; Procedure TWordProcessorTouchToolbar.Refresh; Begin UpdateStatus; End; Procedure TWordProcessorTouchToolbar.SetWordProcessor(Const Value: TWordProcessor); Begin FWordProcessor := Value; If Assigned(FWordProcessor) Then Begin Build; LoadWordProcessorData; FWordProcessor.RegisterObserver(Self, WordProcessorObserverNotificationHandler); End; End; Procedure TWordProcessorTouchToolbar.DoBoldButton(sender : TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.PrimaryRange.ApplyBold(FWordProcessor.PrimaryRange.Font.HasBold); end; Procedure TWordProcessorTouchToolbar.DoItalicButton(sender : TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.PrimaryRange.ApplyItalic(FWordProcessor.PrimaryRange.Font.HasItalic); end; Procedure TWordProcessorTouchToolbar.DoUnderlineButton(sender : TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.PrimaryRange.ApplyUnderline(FWordProcessor.PrimaryRange.Font.HasUnderline); end; Procedure TWordProcessorTouchToolbar.DoColourButton(sender : TObject); begin FWordProcessor.WantCloseTouchMenu; FColourDialog.Color := FWordProcessor.PrimaryRange.Font.Foreground; if FColourDialog.Execute then FWordProcessor.PrimaryRange.ApplyForeground(FColourDialog.Color); end; Procedure TWordProcessorTouchToolbar.DoBackgroundButton(sender : TObject); begin FWordProcessor.WantCloseTouchMenu; FColourDialog.Color := FWordProcessor.PrimaryRange.Font.Background; if FColourDialog.Execute then FWordProcessor.PrimaryRange.ApplyBackground(FColourDialog.Color); end; Procedure TWordProcessorTouchToolbar.DoSuperscriptButton(sender : TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.PrimaryRange.ApplySuperscript(not (FWordProcessor.PrimaryRange.Font.State = fsSuperscript)); end; Procedure TWordProcessorTouchToolbar.DoSubscriptButton(sender : TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.PrimaryRange.ApplySubscript(not (FWordProcessor.PrimaryRange.Font.State = fsSubscript)); end; Procedure TWordProcessorTouchToolbar.DoFontPropertiesButton(sender : TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.FontDialog; end; procedure TWordProcessorTouchToolbar.DoHelpHomeButton(sender: TObject); begin FWordProcessor.WantCloseTouchMenu; OnHelpHome(self); end; procedure TWordProcessorTouchToolbar.DoHelpIndexButton(sender: TObject); begin FWordProcessor.WantCloseTouchMenu; OnHelpIndex(self); end; procedure TWordProcessorTouchToolbar.DoHelpMenu(sender: TObject); begin FCurrentMenu := FWordProcessor.CreateTouchMenu; FCurrentMenu.Left := 4 + LEFT_INC_H * 9; FCurrentMenu.Width := LEFT_INC_H * 2 + 6; FCurrentMenu.Height := LEFT_INC_V * 2 + 4; button(FCurrentMenu, 0, 0, Btn_Offs_HelpIndex, 'Index', true).OnClick := DoHelpIndexButton; button(FCurrentMenu, 1, 0, Btn_Offs_HelpHome, 'Web Page', true).OnClick := DoHelpHomeButton; button(FCurrentMenu, 0, 1, Btn_Offs_HelpVersion, 'Upgrade? ', true).OnClick := DoHelpVersionButton; button(FCurrentMenu, 1, 1, Btn_Offs_HelpSupportCase, 'Bug Case', true).OnClick := DoHelpSupportCaseButton; end; procedure TWordProcessorTouchToolbar.DoHelpSupportCaseButton(sender: TObject); begin FWordProcessor.WantCloseTouchMenu; OnHelpSupportCase(self); end; procedure TWordProcessorTouchToolbar.DoHelpVersionButton(sender: TObject); begin FWordProcessor.WantCloseTouchMenu; OnHelpVersion(self); end; Procedure TWordProcessorTouchToolbar.DoLeftButton(sender : TObject); var para : TWPSParagraphDetails; begin FWordProcessor.WantCloseTouchMenu; para := TWPSParagraphDetails.Create; try para.AlignLeft; FWordProcessor.PrimaryRange.ApplyParagraph(para); finally para.Free; end; end; Procedure TWordProcessorTouchToolbar.DoCenterButton(sender : TObject); var para : TWPSParagraphDetails; begin FWordProcessor.WantCloseTouchMenu; para := TWPSParagraphDetails.Create; try para.AlignCentre; FWordProcessor.PrimaryRange.ApplyParagraph(para); finally para.Free; end; end; Procedure TWordProcessorTouchToolbar.DoRightButton(sender : TObject); var para : TWPSParagraphDetails; begin FWordProcessor.WantCloseTouchMenu; para := TWPSParagraphDetails.Create; try para.AlignRight; FWordProcessor.PrimaryRange.ApplyParagraph(para); finally para.Free; end; end; Procedure TWordProcessorTouchToolbar.DoJustifyButton(sender : TObject); var para : TWPSParagraphDetails; begin FWordProcessor.WantCloseTouchMenu; para := TWPSParagraphDetails.Create; try para.AlignJustify; FWordProcessor.PrimaryRange.ApplyParagraph(para); finally para.Free; end; end; Procedure TWordProcessorTouchToolbar.DoNormalButton(sender : TObject); var para : TWPSParagraphDetails; begin FWordProcessor.WantCloseTouchMenu; para := TWPSParagraphDetails.Create; try para.ListType := WPSParagraphListTypeNone; FWordProcessor.PrimaryRange.ApplyParagraph(para); finally para.Free; end; end; Procedure TWordProcessorTouchToolbar.DoBulletsButton(sender : TObject); var para : TWPSParagraphDetails; begin FWordProcessor.WantCloseTouchMenu; para := TWPSParagraphDetails.Create; try para.ListType := WPSParagraphListTypeBullets; FWordProcessor.PrimaryRange.ApplyParagraph(para); finally para.Free; end; end; Procedure TWordProcessorTouchToolbar.DoNumbersButton(sender : TObject); var para : TWPSParagraphDetails; begin FWordProcessor.WantCloseTouchMenu; para := TWPSParagraphDetails.Create; try para.ListType := WPSParagraphListTypeNumbers; FWordProcessor.PrimaryRange.ApplyParagraph(para); finally para.Free; end; end; Procedure TWordProcessorTouchToolbar.DoIndentButton(sender : TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.PrimaryRange.ApplyLeftIndent(1); end; Procedure TWordProcessorTouchToolbar.DoOutdentButton(sender : TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.PrimaryRange.ApplyLeftIndent(-1); end; Procedure TWordProcessorTouchToolbar.DoParaPropsButton(sender : TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.ParaDialog; end; Procedure TWordProcessorTouchToolbar.DoSymbolButton(sender : TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.InsertSymbol; end; Procedure TWordProcessorTouchToolbar.DoTemplateButton(sender : TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.InsertTemplate; end; Procedure TWordProcessorTouchToolbar.DoBreakButton(sender : TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.PrimaryRange.InsertPageBreak; end; Procedure TWordProcessorTouchToolbar.DoPictureButton(sender : TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.InsertImageDialog; end; Procedure TWordProcessorTouchToolbar.DoInsTableButton(sender : TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.InsertTableDialog; end; Procedure TWordProcessorTouchToolbar.DoInsLineButton(sender : TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.PrimaryRange.InsertLine; end; Procedure TWordProcessorTouchToolbar.DoSelectButton(sender : TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.ImageTool := itSelect; end; Procedure TWordProcessorTouchToolbar.DoLineButton(sender : TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.ImageTool := itLine; end; Procedure TWordProcessorTouchToolbar.DoRectButton(sender : TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.ImageTool := itRectangle; end; Procedure TWordProcessorTouchToolbar.DoCircleButton(sender : TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.ImageTool := itCircle; end; Procedure TWordProcessorTouchToolbar.DoMarkButton(sender : TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.ImageTool := itMark; end; Procedure TWordProcessorTouchToolbar.DoZoomButton(sender : TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.ImageTool := itZoom; end; Procedure TWordProcessorTouchToolbar.DoTableToTextButton(sender : TObject); begin FWordProcessor.WantCloseTouchMenu; ShowMessage('todo'); end; Procedure TWordProcessorTouchToolbar.DoTextToTableButton(sender : TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.PrimaryRange.ConvertTextToTable; end; Procedure TWordProcessorTouchToolbar.DoTablePropsButton(sender : TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.TablePropertiesDialog; end; Procedure TWordProcessorTouchToolbar.DoSelRowButton(sender : TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.PrimaryRange.SelectRow; end; Procedure TWordProcessorTouchToolbar.DoSelTableButton(sender : TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.PrimaryRange.SelectTable; end; Procedure TWordProcessorTouchToolbar.DoSortTableButton(sender : TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.SortTableDialog; end; Procedure TWordProcessorTouchToolbar.DoInsertLeftButton(sender : TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.PrimaryRange.InsertColumnLeft; end; Procedure TWordProcessorTouchToolbar.DoInsertRightButton(sender : TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.PrimaryRange.InsertColumnRight; end; Procedure TWordProcessorTouchToolbar.DoInsertAboveButton(sender : TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.PrimaryRange.InsertRowAbove; end; Procedure TWordProcessorTouchToolbar.DoInsertBelowButton(sender : TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.PrimaryRange.InsertRowBelow; end; Procedure TWordProcessorTouchToolbar.DoDelColButton(sender : TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.PrimaryRange.DeleteColumn; end; Procedure TWordProcessorTouchToolbar.DoDelRowButton(sender : TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.PrimaryRange.DeleteRow; end; Procedure TWordProcessorTouchToolbar.DoDelTableButton(sender : TObject); begin FWordProcessor.WantCloseTouchMenu; FWordProcessor.PrimaryRange.DeleteTable; end; End.
43.650407
174
0.793546
fcbd8a793e45d45fcb73321d71f1201d4eff99de
6,236
dfm
Pascal
Client/fStoreQuantitiesFilter.dfm
Sembium/Sembium3
0179c38c6a217f71016f18f8a419edd147294b73
[ "Apache-2.0" ]
null
null
null
Client/fStoreQuantitiesFilter.dfm
Sembium/Sembium3
0179c38c6a217f71016f18f8a419edd147294b73
[ "Apache-2.0" ]
null
null
null
Client/fStoreQuantitiesFilter.dfm
Sembium/Sembium3
0179c38c6a217f71016f18f8a419edd147294b73
[ "Apache-2.0" ]
3
2021-06-30T10:11:17.000Z
2021-07-01T09:13:29.000Z
inherited fmStoreQuantitiesFilter: TfmStoreQuantitiesFilter Left = 350 Top = 283 Caption = '%s '#1085#1072' '#1053#1072#1083#1080#1095#1085#1086#1089#1090#1080' '#1086#1090' %ProductClassAbbrev% '#1082#1098#1084' '#1076#1072#1090#1072 ClientHeight = 500 ClientWidth = 465 ExplicitWidth = 471 ExplicitHeight = 525 DesignSize = ( 465 500) PixelsPerInch = 96 TextHeight = 13 inherited bvlMain: TBevel Width = 450 Height = 450 ExplicitWidth = 450 ExplicitHeight = 401 end object lblStoreDealDate: TLabel [1] Left = 24 Top = 16 Width = 48 Height = 13 Caption = #1050#1098#1084' '#1076#1072#1090#1072 end object rgIsGroupedByStore: TDBRadioGroup [2] Left = 136 Top = 16 Width = 305 Height = 41 Caption = ' '#1043#1088#1091#1087#1080#1088#1072#1085#1077' '#1087#1086' ' Columns = 2 DataField = 'IS_GROUPED_BY_STORE' DataSource = dsData Items.Strings = ( '%ProductClassName%' '%ProductClassAbbrev% '#1080' '#1058#1055' '#1047#1072#1076#1098#1088#1078#1072#1097#1086) ParentBackground = True TabOrder = 1 Values.Strings = ( 'False' 'True') end inherited pnlBottomButtons: TPanel Top = 465 Width = 465 TabOrder = 4 ExplicitTop = 465 ExplicitWidth = 465 inherited pnlOKCancel: TPanel Left = 197 ExplicitLeft = 197 end inherited pnlClose: TPanel Left = 108 ExplicitLeft = 108 end inherited pnlApply: TPanel Left = 376 ExplicitLeft = 376 end end inline frStoreDealDate: TfrDateFieldEditFrame [4] Left = 24 Top = 32 Width = 105 Height = 21 Constraints.MaxHeight = 21 Constraints.MaxWidth = 105 Constraints.MinHeight = 21 Constraints.MinWidth = 105 TabOrder = 0 TabStop = True ExplicitLeft = 24 ExplicitTop = 32 end inline frParamProductFilter: TfrParamProductFilter [5] Left = 24 Top = 64 Width = 417 Height = 233 ParentShowHint = False ShowHint = True TabOrder = 2 TabStop = True ExplicitLeft = 24 ExplicitTop = 64 ExplicitWidth = 417 inherited grpTreeNodeFilter: TGroupBox Width = 417 ExplicitWidth = 417 inherited lblUsedBy: TLabel Width = 61 ExplicitWidth = 61 end inherited lblProductOrigin: TLabel Width = 23 ExplicitWidth = 23 end inherited lblCommonStatus: TLabel Width = 45 ExplicitWidth = 45 end inherited lblIsActive: TLabel Width = 53 ExplicitWidth = 53 end inherited pnlNodes: TPanel Width = 401 ExplicitWidth = 401 inherited grdChosenNodes: TAbmesDBGrid Width = 376 FooterFont.Name = 'Microsoft Sans Serif' TitleFont.Name = 'Microsoft Sans Serif' Columns = < item EditButtons = <> FieldName = 'NODE_NAME' Footers = <> Width = 279 end item EditButtons = <> FieldName = 'NODE_NO' Footers = <> Width = 63 end> end inherited pnlNodesButtons: TPanel Left = 376 ExplicitLeft = 376 end end inherited pnlParams: TPanel Width = 401 ExplicitWidth = 401 inherited grdChosenNodeParams: TAbmesDBGrid Width = 376 FooterFont.Name = 'Microsoft Sans Serif' TitleFont.Name = 'Microsoft Sans Serif' Columns = < item EditButtons = <> FieldName = 'NODE_PARAM_NAME' Footers = <> Width = 247 end item EditButtons = <> FieldName = 'DISPLAY_VALUE' Footers = <> Width = 95 end> end inherited pnlParamsButtons: TPanel Left = 376 ExplicitLeft = 376 end end end end inline frDeptFilter: TfrDeptFilter [6] Left = 24 Top = 304 Width = 417 Height = 145 ParentShowHint = False ShowHint = True TabOrder = 3 TabStop = True ExplicitLeft = 24 ExplicitTop = 304 ExplicitWidth = 417 inherited grpTreeNodeFilter: TGroupBox Width = 417 ExplicitWidth = 417 inherited lblsExternal: TLabel Width = 52 ExplicitWidth = 52 end inherited lblIsActive: TLabel Width = 53 ExplicitWidth = 53 end inherited pnlNodes: TPanel Width = 401 ExplicitWidth = 401 inherited grdChosenNodes: TAbmesDBGrid Width = 376 FooterFont.Name = 'Microsoft Sans Serif' TitleFont.Name = 'Microsoft Sans Serif' Columns = < item EditButtons = <> FieldName = 'NODE_NAME' Footers = <> Width = 279 end item EditButtons = <> FieldName = 'NODE_IDENTIFIER' Footers = <> Width = 63 end> end inherited pnlNodesButtons: TPanel Left = 376 ExplicitLeft = 376 end end end end inherited alActions: TActionList [7] Left = 336 Top = 400 inherited actForm: TAction Caption = '%s '#1085#1072' '#1053#1072#1083#1080#1095#1085#1086#1089#1090#1080' '#1086#1090' %ProductClassAbbrev% '#1082#1098#1084' '#1076#1072#1090#1072 end end inherited dsData: TDataSource [8] Left = 288 Top = 400 end inherited cdsData: TAbmesClientDataSet [10] Left = 256 Top = 400 end inherited cdsFilterVariants: TAbmesClientDataSet Left = 24 Top = 464 end inherited dsFilterVariants: TDataSource Left = 56 Top = 464 end inherited cdsFilterVariantFields: TAbmesClientDataSet Left = 80 Top = 480 end end
25.768595
160
0.54923
47da0ef133ef4695ae5a746a0d55b55188e4ba03
509
dpr
Pascal
macros/src/macros.dpr
regyssilveira/firedac-demos
ebbdb512d45d64a63b7e3c34203a10e14e03113b
[ "Apache-2.0" ]
8
2019-06-21T20:02:27.000Z
2021-07-19T15:11:58.000Z
macros/src/macros.dpr
regyssilveira/firedac-demos
ebbdb512d45d64a63b7e3c34203a10e14e03113b
[ "Apache-2.0" ]
null
null
null
macros/src/macros.dpr
regyssilveira/firedac-demos
ebbdb512d45d64a63b7e3c34203a10e14e03113b
[ "Apache-2.0" ]
4
2020-04-29T22:25:05.000Z
2022-01-28T02:12:46.000Z
program macros; uses Vcl.Forms, UBasePrincipal in '..\..\comuns\UBasePrincipal.pas' {FrmBasePrincipal}, UConfig in '..\..\comuns\UConfig.pas', UPrincipal in 'UPrincipal.pas' {FrmPrincipal}, UFBConnection in '..\..\comuns\UFBConnection.pas' {DtmFBConnection: TDataModule}; {$R *.res} begin Application.Initialize; Application.MainFormOnTaskbar := True; Application.CreateForm(TDtmFBConnection, DtmFBConnection); Application.CreateForm(TFrmPrincipal, FrmPrincipal); Application.Run; end.
26.789474
83
0.750491
fc9ee3c589bf3dc6680332be091f6a4484f0247b
2,610
pas
Pascal
dependencies/Indy10/Protocols/IdSystatServer.pas
17-years-old/fhirserver
9575a7358868619311a5d1169edde3ffe261e558
[ "BSD-3-Clause" ]
132
2015-02-02T00:22:40.000Z
2021-08-11T12:08:08.000Z
dependencies/Indy10/Protocols/IdSystatServer.pas
17-years-old/fhirserver
9575a7358868619311a5d1169edde3ffe261e558
[ "BSD-3-Clause" ]
113
2015-03-20T01:55:20.000Z
2021-10-08T16:15:28.000Z
dependencies/Indy10/Protocols/IdSystatServer.pas
17-years-old/fhirserver
9575a7358868619311a5d1169edde3ffe261e558
[ "BSD-3-Clause" ]
49
2015-04-11T14:59:43.000Z
2021-03-30T10:29:18.000Z
{ $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.7 12/2/2004 4:23:58 PM JPMugaas Adjusted for changes in Core. Rev 1.6 10/26/2004 10:49:20 PM JPMugaas Updated ref. Rev 1.5 2004.02.03 5:44:30 PM czhower Name changes Rev 1.4 1/21/2004 4:04:04 PM JPMugaas InitComponent Rev 1.3 2/24/2003 10:29:50 PM JPMugaas Rev 1.2 1/17/2003 07:10:58 PM JPMugaas Now compiles under new framework. Rev 1.1 1/8/2003 05:53:54 PM JPMugaas Switched stuff to IdContext. Rev 1.0 11/13/2002 08:02:28 AM JPMugaas } unit IdSystatServer; { Indy Systat Client TIdSystatServer Copyright (C) 2002 Winshoes Working Group Original author J. Peter Mugaas 2002-August-13 Based on RFC 866 Note that this protocol is officially called Active User } interface {$i IdCompilerDefines.inc} uses Classes, IdAssignedNumbers, IdContext, IdCustomTCPServer; type TIdSystatEvent = procedure (AThread: TIdContext; AResults : TStrings) of object; Type TIdSystatServer = class(TIdCustomTCPServer) protected FOnSystat : TIdSystatEvent; // function DoExecute(AThread: TIdContext): boolean; override; procedure InitComponent; override; published property OnSystat : TIdSystatEvent read FOnSystat write FOnSystat; property DefaultPort default IdPORT_SYSTAT; end; { Note that no result parsing is done because RFC 866 does not specify a syntax for a user list. Quoted from RFC 866: There is no specific syntax for the user list. It is recommended that it be limited to the ASCII printing characters, space, carriage return, and line feed. Each user should be listed on a separate line. } implementation uses IdGlobal, SysUtils; { TIdSystatServer } procedure TIdSystatServer.InitComponent; begin inherited; DefaultPort := IdPORT_SYSTAT; end; function TIdSystatServer.DoExecute(AThread: TIdContext): boolean; var s : TStrings; begin Result := True; if Assigned(FOnSystat) then begin s := TStringList.Create; try FOnSystat(AThread,s); AThread.Connection.IOHandler.Write(s); finally FreeAndNil(s); end; end; AThread.Connection.Disconnect; end; end.
21.393443
83
0.679693
473e3b85a5e0c208a1d1a585454d8b34fe809e51
2,059
pas
Pascal
src/Libs/Protocol/Implementations/FastCGI/Records/FcgiUnknownType.pas
zamronypj/fano-framework
559e385be5e1d26beada94c46eb8e760c4d855da
[ "MIT" ]
78
2019-01-31T13:40:48.000Z
2022-03-22T17:26:54.000Z
src/Libs/Protocol/Implementations/FastCGI/Records/FcgiUnknownType.pas
zamronypj/fano-framework
559e385be5e1d26beada94c46eb8e760c4d855da
[ "MIT" ]
24
2020-01-04T11:50:53.000Z
2022-02-17T09:55:23.000Z
src/Libs/Protocol/Implementations/FastCGI/Records/FcgiUnknownType.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 FcgiUnknownType; interface {$MODE OBJFPC} {$H+} uses StreamAdapterIntf, FcgiRecord; type (*!----------------------------------------------- * Unknown type record (FCGI_UNKNOWN_TYPE) * * @author Zamrony P. Juhara <zamronypj@yahoo.com> *-----------------------------------------------*) TFcgiUnknownType = class(TFcgiRecord) public constructor create( const aVersion : byte; const aType : byte; const aRequestId : word; const dataStream : IStreamAdapter; const unknownType : byte ); constructor create( const dataStream : IStreamAdapter; const requestId : word; const unknownType : byte ); end; implementation uses fastcgi; constructor TFcgiUnknownType.create( const aVersion : byte; const aType : byte; const aRequestId : word; const dataStream : IStreamAdapter; const unknownType : byte ); var reqBody : FCGI_UnknownTypeBody; begin inherited create(aVersion, aType, aRequestId, dataStream); reqBody._type := unknownType; reqBody.reserved[0] := 0; reqBody.reserved[1] := 0; reqBody.reserved[2] := 0; reqBody.reserved[3] := 0; reqBody.reserved[4] := 0; reqBody.reserved[5] := 0; reqBody.reserved[6] := 0; fContentData.writeBuffer(reqBody, sizeof(FCGI_UnknownTypeBody)); fContentData.seek(0); end; constructor TFcgiUnknownType.create( const dataStream : IStreamAdapter; const requestId : word; const unknownType : byte ); begin create(FCGI_VERSION_1, FCGI_UNKNOWN_TYPE, requestId, dataStream, unknownType); end; end.
25.109756
86
0.581836
f1a5453141e0185cf9d3e5d7faa33b8012c9b410
7,688
pas
Pascal
Packages/IconFontsImageListEditor.pas
atkins126/IconFontsImageList
b5737f3924b26fdf977e4325af5348991fc63e5c
[ "Apache-2.0" ]
179
2019-11-22T23:31:22.000Z
2022-03-21T00:27:54.000Z
Packages/IconFontsImageListEditor.pas
andrea-magni/IconFontsImageList
8006265c83c98728949ae6822df1321c92d780ec
[ "Apache-2.0" ]
45
2019-12-14T16:47:02.000Z
2021-11-24T09:43:40.000Z
Packages/IconFontsImageListEditor.pas
andrea-magni/IconFontsImageList
8006265c83c98728949ae6822df1321c92d780ec
[ "Apache-2.0" ]
40
2019-11-25T19:22:51.000Z
2021-12-16T19:14:10.000Z
{******************************************************************************} { } { Icon Fonts ImageList: An extended ImageList for Delphi } { to simplify use of Icons (resize, colors and more...) } { } { Copyright (c) 2019-2021 (Ethea S.r.l.) } { Contributors: } { Carlo Barazzetta } { } { https://github.com/EtheaDev/IconFontsImageList } { } {******************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {******************************************************************************} unit IconFontsImageListEditor; {$INCLUDE ..\Source\IconFontsImageList.inc} interface uses SysUtils , Classes , Graphics , DesignIntf , DesignEditors; type TIconFontsImageListCompEditor = class (TComponentEditor) private public function GetVerbCount: Integer; override; function GetVerb(Index: Integer): string; override; procedure ExecuteVerb(Index: Integer); override; end; TIconFontsVirtualImageListCompEditor = class(TComponentEditor) public function GetVerbCount: Integer; override; function GetVerb(Index: Integer): string; override; procedure ExecuteVerb(Index: Integer); override; end; TIconFontsImageCollectionCompEditor = class(TComponentEditor) public function GetVerbCount: Integer; override; function GetVerb(Index: Integer): string; override; procedure ExecuteVerb(Index: Integer); override; end; TIconFontsImageListProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; function GetValue: string; override; end; TIconFontsCollectionListProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; function GetValue: string; override; end; implementation uses ShellApi , Windows , IconFontsImageList , IconFontsImageListBase , IconFontsVirtualImageList , IconFontsImageCollection , IconFontsImageListEditorUnit {$IFDEF D2010+} , MaterialFontConvert {$ENDIF} , Dialogs; { TIconFontsImageListCompEditor } procedure TIconFontsImageListCompEditor.ExecuteVerb(Index: Integer); {$IFDEF D2010+} var LConvertCount : integer; LMissingCount : integer; {$ENDIF} begin inherited; if Index = 0 then begin if (Component is TIconFontsImageListBase) and EditIconFontsImageList(TIconFontsImageListBase(Component)) then Designer.Modified; end else if Index = 1 then begin ShellExecute(0, 'open', PChar('https://github.com/EtheaDev/IconFontsImageList/wiki/Home'), nil, nil, SW_SHOWNORMAL) {$IFDEF D2010+} end else //Index = 2 begin ConvertFont((Component as TIconFontsImageList), LConvertCount, LMissingCount); MessageDlg(Format(MSG_ICONFONTS_CONVERTED, [LConvertCount,LMissingCount]), mtInformation, [mbOK], 0); if LConvertCount > 0 then Designer.Modified; {$ENDIF} end; end; function TIconFontsImageListCompEditor.GetVerb(Index: Integer): string; begin Result := ''; case Index of 0: Result := 'I&conFonts ImageList Editor...'; 1: Result := Format('Ver. %s - (c) Ethea S.r.l. - show help...',[IconFontsImageListVersion]); {$IFDEF D2010+} 2: Result := Format('Convert from "%s" to "%s"...',[OLD_FONT_NAME, NEW_FONT_NAME]); {$ENDIF} end; end; function TIconFontsImageListCompEditor.GetVerbCount: Integer; begin Result := 3; end; { TIconFontsImageListProperty } procedure TIconFontsImageListProperty.Edit; var SVGImageList: TIconFontsImageList; begin SVGImageList := TIconFontsImageList(GetComponent(0)); if EdiTIconFontsImageList(SVGImageList) then Modified; end; function TIconFontsImageListProperty.GetAttributes: TPropertyAttributes; begin Result := inherited GetAttributes + [paDialog]; end; function TIconFontsImageListProperty.GetValue: string; begin Result := 'IconFonts'; end; { TIconFontsCollectionListProperty } procedure TIconFontsCollectionListProperty.Edit; var SVGImageCollection: TIconFontsImageCollection; begin SVGImageCollection := TIconFontsImageCollection(GetComponent(0)); if EditIconFontsImageCollection(SVGImageCollection) then Modified; end; function TIconFontsCollectionListProperty.GetAttributes: TPropertyAttributes; begin Result := inherited GetAttributes + [paDialog]; end; function TIconFontsCollectionListProperty.GetValue: string; begin Result := 'IconFontsImageCollection'; end; { TIconFontsImageCollectionCompEditor } procedure TIconFontsImageCollectionCompEditor.ExecuteVerb(Index: Integer); begin inherited; if Index = 0 then begin if EdiTIconFontsImageCollection(Component as TIconFontsImageCollection) then Designer.Modified; end else if Index = 1 then begin ShellExecute(0, 'open', PChar('https://github.com/EtheaDev/SVGIconImageList/wiki/Home'), nil, nil, SW_SHOWNORMAL) end; end; function TIconFontsImageCollectionCompEditor.GetVerb(Index: Integer): string; begin Result := ''; case Index of 0: Result := 'I&conFonts ImageCollection Editor...'; 1: Result := Format('Ver. %s - (c) Ethea S.r.l. - show help...',[IconFontsImageListVersion]); end; end; function TIconFontsImageCollectionCompEditor.GetVerbCount: Integer; begin Result := 2; end; { TIconFontsVirtualImageListCompEditor } procedure TIconFontsVirtualImageListCompEditor.ExecuteVerb(Index: Integer); begin inherited; if Index = 0 then begin if EdiTIconFontsVirtualImageList(Component as TIconFontsVirtualImageList) then Designer.Modified; end else if Index = 1 then begin ShellExecute(0, 'open', PChar('https://github.com/EtheaDev/SVGIconImageList/wiki/Home'), nil, nil, SW_SHOWNORMAL) end; end; function TIconFontsVirtualImageListCompEditor.GetVerb(Index: Integer): string; begin Result := ''; case Index of 0: Result := 'I&conFonts VirtualImageList Editor...'; 1: Result := Format('Ver. %s - (c) Ethea S.r.l. - show help...',[IconFontsImageListVersion]); end; end; function TIconFontsVirtualImageListCompEditor.GetVerbCount: Integer; begin result := 2; end; end.
30.387352
97
0.621358
f198d43c94464905c448bd2bd01b36e0213cd89e
109,830
pas
Pascal
Matrix.pas
williamdale/mrmath
3caa5d2b160ee8e2955fdbefefd9709cdf72f0f4
[ "Apache-2.0" ]
null
null
null
Matrix.pas
williamdale/mrmath
3caa5d2b160ee8e2955fdbefefd9709cdf72f0f4
[ "Apache-2.0" ]
null
null
null
Matrix.pas
williamdale/mrmath
3caa5d2b160ee8e2955fdbefefd9709cdf72f0f4
[ "Apache-2.0" ]
1
2019-07-09T09:40:32.000Z
2019-07-09T09:40:32.000Z
// ################################################################### // #### This file is part of the mathematics library project, and is // #### offered under the licence agreement described on // #### http://www.mrsoft.org/ // #### // #### Copyright:(c) 2011, Michael R. . All rights reserved. // #### // #### Unless required by applicable law or agreed to in writing, software // #### distributed under the License is distributed on an "AS IS" BASIS, // #### WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // #### See the License for the specific language governing permissions and // #### limitations under the License. // ################################################################### unit Matrix; // ############################################ // #### Base matrix operations // ############################################ interface uses SysUtils, Classes, Types, MatrixConst, BaseMathPersistence, RandomEng; {$IFDEF CPUX64} {$DEFINE x64} {$ENDIF} {$IFDEF cpux86_64} {$DEFINE x64} {$ENDIF} {$IFDEF FPC} {.$DEFINE ANONMETHODS} {$ELSE} {$IF CompilerVersion >= 20.0} {$DEFINE ANONMETHODS} {$IFEND} {$ENDIF} type EBaseMatrixException = class(Exception); ELinEQSingularException = class(EBaseMatrixException); type TDoubleMatrix = class; IMatrix = interface(IMathPersistence) ['{8B76CD12-4314-41EB-BD98-302A024AA0EC}'] function StartElement : PDouble; function LineWidth : integer; procedure SetLinEQProgress(value : TLinEquProgress); function GetLinEQProgress : TLinEquProgress; function GetItems(x, y: integer): double; register; procedure SetItems(x, y: integer; const Value: double); register; function GetVecItem(idx: integer): double; register; procedure SetVecItem(idx: integer; const Value: double); register; function GetSubWidth : integer; function GetSubHeight : integer; procedure SetWidth(const Value : integer); procedure SetHeight(const Value : integer); procedure SetWidthHeight(const Width, Height : integer); procedure Resize(aNewWidth, aNewHeight : Integer); // setwidthheight with data preserve function GetVecLen : integer; property Width : integer read GetSubWidth write SetWidth; property Height : integer read GetSubHeight write SetHeight; property LinEQProgress : TLinEquProgress read GetLinEQProgress write SetLinEQProgress; // general access property Items[x, y : integer] : double read GetItems write SetItems; default; property Vec[idx : integer] : double read GetVecItem write SetVecItem; // matrix as vector property VecLen : integer read GetVecLen; procedure Clear; function GetObjRef : TDoubleMatrix; function SubMatrix : TDoubleDynArray; procedure SetSubMatrix(x, y, Subwidth, Subheight : integer); procedure UseFullMatrix; procedure SetRow(row : integer; const Values : Array of Double); overload; procedure SetRow(row : integer; Values : TDoubleMatrix; ValRow : integer = 0); overload; procedure SetRow(row : integer; Values : IMatrix; ValRow : integer = 0); overload; procedure SetColumn(col : integer; const Values : Array of Double); overload; procedure SetColumn(col : integer; Values : TDoubleMatrix; ValCols : integer = 0); overload; procedure SetColumn(col : integer; Values : IMatrix; ValCols : integer = 0); overload; procedure SetValue(const initVal : double); function Reshape(newWidth, newHeight : integer; RowMajor : boolean = False) : TDoubleMatrix; procedure ReshapeInPlace(newWidth, newHeight : integer; RowMajor : boolean = False); function AsVector( RowMajor : boolean = False ) : TDoubleMatrix; // ################################################### // #### Simple matrix utility functions function Max : double; function Min : double; function Abs : TDoubleMatrix; procedure AbsInPlace; procedure DiagInPlace(createDiagMtx : boolean); function Diag(createDiagMtx : boolean) : TDoubleMatrix; function Trace : double; procedure Normalize(RowWise : boolean); procedure NormZeroMeanVarOne(RowWise : boolean); function ElementwiseNorm2(doSqrt : boolean = True) : double; // ################################################### // #### Base Matrix operations procedure TransposeInPlace; function Transpose : TDoubleMatrix; procedure AddInplace(Value : TDoubleMatrix); overload; function Add(Value : TDoubleMatrix) : TDoubleMatrix; overload; procedure AddVecInPlace(Value : TDoubleMatrix; rowWise : Boolean); overload; function AddVec(aVec : TDoubleMatrix; rowWise : Boolean) : TDoubleMatrix; overload; procedure AddVecInPlace(Value : IMatrix; rowWise : Boolean); overload; function AddVec(iVec : IMatrix; rowWise : Boolean) : TDoubleMatrix; overload; procedure SubInPlace(Value : TDoubleMatrix); overload; function Sub(Value : TDoubleMatrix) : TDoubleMatrix; overload; procedure SubVecInPlace(Value : TDoubleMatrix; rowWise : Boolean); overload; function SubVec(aVec : TDoubleMatrix; rowWise : Boolean) : TDoubleMatrix; overload; procedure SubVecInPlace(Value : IMatrix; rowWise : Boolean); overload; function SubVec(iVec : IMatrix; rowWise : Boolean) : TDoubleMatrix; overload; procedure MultInPlace(Value : TDoubleMatrix); overload; function Mult(Value : TDoubleMatrix) : TDoubleMatrix; overload; // multT1: dest = mt1' * mt2 mt1' = mt1.transpose procedure MultInPlaceT1(Value : TDoubleMatrix); overload; function MultT1(Value : TDoubleMatrix) : TDoubleMatrix; overload; // multT2: dest = mt1 * mt2' mt2 = mt2.transpose procedure MultInPlaceT2(Value : TDoubleMatrix); overload; function MultT2(Value : TDoubleMatrix) : TDoubleMatrix; overload; procedure AddInplace(Value : IMatrix); overload; function Add(Value : IMatrix) : TDoubleMatrix; overload; procedure SubInPlace(Value : IMatrix); overload; function Sub(Value : IMatrix) : TDoubleMatrix; overload; procedure MultInPlace(Value : IMatrix); overload; function Mult(Value : IMatrix) : TDoubleMatrix; overload; procedure MultInPlaceT1(Value : IMatrix); overload; function MultT1(Value : IMatrix) : TDoubleMatrix; overload; procedure MultInPlaceT2(Value : IMatrix); overload; function MultT2(Value : IMatrix) : TDoubleMatrix; overload; procedure ElementWiseMultInPlace(Value : TDoubleMatrix); overload; function ElementWiseMult(Value : TDoubleMatrix) : TDoubleMatrix; overload; procedure ElementWiseMultInPlace(Value : IMatrix); overload; function ElementWiseMult(Value : IMatrix) : TDoubleMatrix; overload; procedure ElementWiseDivInPlace(Value : TDoubleMatrix); overload; function ElementWiseDiv(Value : TDoubleMatrix) : TDoubleMatrix; overload; procedure ElementWiseDivInPlace(Value : IMatrix); overload; function ElementWiseDiv(Value : IMatrix) : TDoubleMatrix; overload; procedure AddAndScaleInPlace(const Offset, Scale : double); function AddAndScale(const Offset, Scale : double) : TDoubleMatrix; function Mean(RowWise : boolean) : TDoubleMatrix; procedure MeanInPlace(RowWise : boolean); function Variance(RowWise : boolean; unbiased : boolean = True) : TDoubleMatrix; procedure VarianceInPlace(RowWise : boolean; unbiased : boolean = True); function Std(RowWise : boolean; unbiased : boolean = True) : TDoubleMatrix; procedure StdInPlace(RowWise : boolean; unbiased : boolean = True); // calculates mean and variance in one step and stores the mean in the first row, the variance in the second // if RowWise is selected. If rowwise is false it's vice versa function MeanVariance(RowWise : boolean; unbiased : boolean = True) : TDoubleMatrix; procedure MeanVarianceInPlace(RowWise : boolean; unbiased : boolean = True); function Median(RowWise : boolean) : TDoubleMatrix; procedure MedianInPlace(RowWise : boolean); procedure SortInPlace(RowWise : boolean); function Sort(RowWise : boolean) : TDoubleMatrix; function Diff(RowWise : boolean) : TDoubleMatrix; procedure DiffInPlace(RowWise : boolean); function Sum(RowWise : boolean) : TDoubleMatrix; procedure SumInPlace(RowWise : boolean); overload; procedure SumInPlace(RowWide : boolean; keepMemory : boolean); overload; function CumulativeSum(RowWise : boolean) : TDoubleMatrix; procedure CumulativeSumInPlace(RowWise : boolean); function Add(const Value : double) : TDoubleMatrix; overload; procedure AddInPlace(const Value : double); overload; function Scale(const Value : double) : TDoubleMatrix; procedure ScaleInPlace(const Value : Double); function ScaleAndAdd(const aOffset, aScale : double) : TDoubleMatrix; procedure ScaleAndAddInPlace(const aOffset, aScale : double); function SQRT : TDoubleMatrix; procedure SQRTInPlace; procedure ElementwiseFuncInPlace(func : TMatrixFunc); overload; function ElementwiseFunc(func : TMatrixFunc) : TDoubleMatrix; overload; procedure ElementwiseFuncInPlace(func : TMatrixObjFunc); overload; function ElementwiseFunc(func : TMatrixObjFunc) : TDoubleMatrix; overload; procedure ElementwiseFuncInPlace(func : TMatrixMtxRefFunc); overload; function ElementwiseFunc(func : TMatrixMtxRefFunc) : TDoubleMatrix; overload; procedure ElementwiseFuncInPlace(func : TMatrixMtxRefObjFunc); overload; function ElementwiseFunc(func : TMatrixMtxRefObjFunc) : TDoubleMatrix; overload; {$IFDEF ANONMETHODS} procedure ElementwiseFuncInPlace(func : TMatrixFuncRef); overload; function ElementwiseFunc(func : TMatrixFuncRef) : TDoubleMatrix; overload; procedure ElementwiseFuncInPlace(func : TMatrixMtxRefFuncRef); overload; function ElementwiseFunc(func : TMatrixMtxRefFuncRef) : TDoubleMatrix; overload; {$ENDIF} // ################################################### // #### Linear System solver A*x = B -> use A.SolveLinEQ(B) -> x function SolveLinEQ(Value : TDoubleMatrix; numRefinements : integer = 0) : TDoubleMatrix; overload; function SolveLinEQ(Value : IMatrix; numRefinements : integer = 0) : TDoubleMatrix; overload; procedure SolveLinEQInPlace(Value : TDoubleMatrix; numRefinements : integer = 0); overload; procedure SolveLinEQInPlace(Value : IMatrix; numRefinements : integer = 0); overload; // solves least sqaures A*x = b using the QR decomposition function SolveLeastSquaresInPlace(out x : TDoubleMatrix; b : TDoubleMatrix) : TQRResult; overload; function SolveLeastSquaresInPlace(out x : IMatrix; b : IMatrix) : TQRResult; overload; function SolveLeastSquares(out x : TDoubleMatrix; b : TDoubleMatrix) : TQRResult; overload; function SolveLeastSquares(out x : IMatrix; b : IMatrix) : TQRResult; overload; // matrix inversion (based on LU decomposition) function InvertInPlace : TLinEquResult; function Invert : TDoubleMatrix; overload; function Invert( out InvMtx : TDoubleMatrix ) : TLinEquResult; overload; function Invert( out InvMtx : IMatrix ) : TLinEquResult; overload; function PseudoInversionInPlace : TSVDResult; function PseudoInversion(out Mtx : TDoubleMatrix) : TSVDResult; overload; function PseudoInversion(out Mtx : IMatrix) : TSVDResult; overload; function Determinant : double; // ################################################### // #### Special functions procedure MaskedSetValue(const Mask : Array of boolean; const newVal : double); procedure RepeatMatrixInPlace(numX, numY : integer); function RepeatMatrix(numX, numY : integer) : TDoubleMatrix; // ################################################### // #### Matrix transformations function SVD(out U, V, W : TDoubleMatrix; onlyDiagElements : boolean = False) : TSVDResult; overload; function SVD(out U, V, W : IMatrix; onlyDiagElements : boolean = False) : TSVDResult; overload; function SymEig(out EigVals : TDoubleMatrix; out EigVect : TDoubleMatrix) : TEigenvalueConvergence; overload; function SymEig(out EigVals : TDoubleMatrix) : TEigenvalueConvergence; overload; function SymEig(out EigVals : IMatrix; out EigVect : IMatrix) : TEigenvalueConvergence; overload; function SymEig(out EigVals : IMatrix) : TEigenvalueConvergence; overload; function Eig(out EigVals : TDoublematrix; out EigVect : TDoubleMatrix; normEigVecs : boolean = False) : TEigenvalueConvergence; overload; function Eig(out EigVals : TDoublematrix) : TEigenvalueConvergence; overload; function Eig(out EigVals : IMatrix; out EigVect : IMatrix; normEigVecs : boolean = False) : TEigenvalueConvergence; overload; function Eig(out EigVals : IMatrix) : TEigenvalueConvergence; overload; function Cholesky(out Chol : TDoubleMatrix) : TCholeskyResult; overload; function Cholesky(out Chol : IMatrix) : TCholeskyResult; overload; // only internaly used -> use the other QR or QRFull methods instead //function QR(out R : TDoubleMatrix; out tau : TDoubleMatrix) : TQRResult; overload; //function QR(out R : IMatrix; out tau : IMatrix) : TQRResult; overload; function QR(out R : TDoubleMatrix) : TQRResult; overload; function QR(out R : IMatrix) : TQRResult; overload; function QRFull(out Q, R : TDoubleMatrix) : TQRResult; overload; function QRFull(out Q, R : IMatrix) : TQRResult; overload; // ################################################### // #### Matrix assignment operations procedure Assign(Value : TDoubleMatrix); overload; procedure Assign(Value : IMatrix); overload; procedure Assign(Value : TDoubleMatrix; OnlySubElements : boolean); overload; procedure Assign(Value : IMatrix; OnlySubElements : boolean); overload; procedure Assign(const Mtx : Array of double; W, H : integer); overload; procedure AssignSubMatrix(Value : TDoubleMatrix; X : integer = 0; Y : integer = 0); overload; procedure AssignSubMatrix(Value : IMatrix; X : integer = 0; Y : integer = 0); overload; procedure Append(Value : IMatrix; appendColumns : boolean); overload; procedure Append(Value : TDoubleMatrix; appendColumns : boolean); overload; // moves data from Value to self and clears original object procedure TakeOver(Value : TDoubleMatrix); overload; procedure TakeOver(Value : IMatrix); overload; function Clone : TDoubleMatrix; end; // ################################################# // #### Builds base matrix operations TDoubleMatrixClass = class of TDoubleMatrix; TDoubleMatrix = class(TBaseMathPersistence, IMatrix) private type TLocConstDoubleArr = Array[0..MaxInt div sizeof(double) - 1] of double; PLocConstDoubleArr = ^TLocConstDoubleArr; {$IFDEF x64} TLocASMNativeInt = NativeInt; {$ELSE} TLocASMNativeInt = integer; {$ENDIF} protected // used to determine which class type to use as a result // e.g. the threaded class does not override all standard functions but // the resulting class type shall always be the threaded class! class function ResultClass : TDoubleMatrixClass; virtual; function GetItems(x, y: integer): double; register; inline; procedure SetItems(x, y: integer; const Value: double); register; inline; // Access as vector -> same as GetItem(idx mod width, idx div width) function GetVecItem(idx: integer): double; register; procedure SetVecItem(idx: integer; const Value: double); register; // matrix persistence functions procedure DefineProps; override; function PropTypeOfName(const Name : string) : TPropType; override; class function ClassIdentifier : String; override; procedure OnLoadStringProperty(const Name : String; const Value : String); overload; override; procedure OnLoadIntProperty(const Name : String; Value : integer); overload; override; procedure OnLoadDoubleArr(const Name : String; const Value : TDoubleDynArray); override; procedure SetLinEQProgress(value : TLinEquProgress); function GetLinEQProgress : TLinEquProgress; procedure InternalSetWidthHeight(const aWidth, aHeight : integer; AssignMem : boolean = True); procedure ReserveMem(width, height: integer); private fMemory : Pointer; fData : PLocConstDoubleArr; // 16 byte aligned pointer: fLineWidth : TLocASMNativeInt; fObj : TObject; // arbitrary object procedure MtxRandWithEng(var value : double); procedure MtxRand(var value : double); protected fHeight : integer; fWidth : integer; fName : String; fSubWidth : integer; fSubHeight : integer; fOffsetX : integer; fOffsetY : integer; fLinEQProgress : TLinEquProgress; procedure CheckAndRaiseError(assertionVal : boolean; const msg : string); inline; procedure SetData(data : PDouble; srcLineWidth, width, height : integer); procedure Clear; procedure SetWidth(const Value : integer); procedure SetHeight(const Value : integer); function GetSubWidth : integer; function GetSubHeight : integer; function GetVecLen : integer; function GetObjRef : TDoubleMatrix; // qr decomposition without clearing the lower triangular matrix and factors tau function QR(out ecosizeR : TDoubleMatrix; out tau : TDoubleMatrix) : TQRResult; overload; virtual; function QR(out ecosizeR : IMatrix; out tau : IMatrix) : TQRResult; overload; public property Width : integer read GetSubWidth write SetWidth; property Height : integer read GetSubHeight write SetHeight; procedure SetWidthHeight(const aWidth, aHeight : integer); procedure Resize(aNewWidth, aNewHeight : Integer); // setwidthheight with data preserve property Name : string read fName write fName; property LineEQProgress : TLinEquProgress read GetLinEQProgress write SetLinEQProgress; // general access // direct access functionality (use only when you know what you are doing!) function StartElement : PDouble; {$IFNDEF FPC} {$IF CompilerVersion >= 17.0} inline; {$IFEND} {$ENDIF} function LineWidth : integer; {$IFNDEF FPC} {$IF CompilerVersion >= 17.0} inline; {$IFEND} {$ENDIF} property Items[x, y : integer] : double read GetItems write SetItems; default; property Vec[idx : integer] : double read GetVecItem write SetVecItem; // matrix as vector property VecLen : integer read GetVecLen; // width*height function SubMatrix : TDoubleDynArray; procedure SetSubMatrix(x, y, Subwidth, Subheight : integer); procedure UseFullMatrix; procedure SetRow(row : integer; const Values : Array of Double); overload; procedure SetRow(row : integer; Values : TDoubleMatrix; ValRow : integer = 0); overload; procedure SetRow(row : integer; Values : IMatrix; ValRow : integer = 0); overload; procedure SetColumn(col : integer; const Values : Array of Double); overload; procedure SetColumn(col : integer; Values : TDoubleMatrix; ValCols : integer = 0); overload; procedure SetColumn(col : integer; Values : IMatrix; ValCols : integer = 0); overload; procedure SetValue(const initVal : double); function Reshape(newWidth, newHeight : integer; RowMajor : boolean = False) : TDoubleMatrix; procedure ReshapeInPlace(newWidth, newHeight : integer; RowMajor : boolean = False); function AsVector( RowMajor : boolean = False ) : TDoubleMatrix; // ################################################### // #### Simple matrix utility functions function Max : double; function Min : double; function Abs : TDoubleMatrix; procedure AbsInPlace; procedure DiagInPlace(createDiagMtx : boolean); function Diag(createDiagMtx : boolean) : TDoubleMatrix; function Trace : double; procedure Normalize(RowWise : boolean); procedure NormZeroMeanVarOne(RowWise : boolean); function ElementwiseNorm2(doSqrt : boolean = True) : double; // ################################################### // #### Base Matrix operations procedure TransposeInPlace; function Transpose : TDoubleMatrix; procedure AddInplace(Value : TDoubleMatrix); overload; virtual; function Add(Value : TDoubleMatrix) : TDoubleMatrix; overload; virtual; procedure AddVecInPlace(Value : TDoubleMatrix; rowWise : Boolean); overload; function AddVec(aVec : TDoubleMatrix; rowWise : Boolean) : TDoubleMatrix; overload; procedure AddVecInPlace(Value : IMatrix; rowWise : Boolean); overload; function AddVec(iVec : IMatrix; rowWise : Boolean) : TDoubleMatrix; overload; procedure SubInPlace(Value : TDoubleMatrix); overload; virtual; function Sub(Value : TDoubleMatrix) : TDoubleMatrix; overload; virtual; procedure SubVecInPlace(Value : TDoubleMatrix; rowWise : Boolean); overload; function SubVec(aVec : TDoubleMatrix; rowWise : Boolean) : TDoubleMatrix; overload; procedure SubVecInPlace(Value : IMatrix; rowWise : Boolean); overload; function SubVec(iVec : IMatrix; rowWise : Boolean) : TDoubleMatrix; overload; procedure MultInPlace(Value : TDoubleMatrix); overload; virtual; function Mult(Value : TDoubleMatrix) : TDoubleMatrix; overload; virtual; procedure MultInPlaceT1(Value : TDoubleMatrix); overload; virtual; function MultT1(Value : TDoubleMatrix) : TDoubleMatrix; overload; virtual; procedure MultInPlaceT2(Value : TDoubleMatrix); overload; virtual; function MultT2(Value : TDoubleMatrix) : TDoubleMatrix; overload; virtual; procedure AddInplace(Value : IMatrix); overload; function Add(Value : IMatrix) : TDoubleMatrix; overload; procedure SubInPlace(Value : IMatrix); overload; function Sub(Value : IMatrix) : TDoubleMatrix; overload; procedure MultInPlace(Value : IMatrix); overload; function Mult(Value : IMatrix) : TDoubleMatrix; overload; procedure MultInPlaceT1(Value : IMatrix); overload; function MultT1(Value : IMatrix) : TDoubleMatrix; overload; procedure MultInPlaceT2(Value : IMatrix); overload; function MultT2(Value : IMatrix) : TDoubleMatrix; overload; procedure ElementWiseMultInPlace(Value : IMatrix); overload; function ElementWiseMult(Value : IMatrix) : TDoubleMatrix; overload; procedure ElementWiseMultInPlace(Value : TDoubleMatrix); overload; virtual; function ElementWiseMult(Value : TDoubleMatrix) : TDoubleMatrix; overload; virtual; procedure ElementWiseDivInPlace(Value : TDoubleMatrix); overload; virtual; function ElementWiseDiv(Value : TDoubleMatrix) : TDoubleMatrix; overload; virtual; procedure ElementWiseDivInPlace(Value : IMatrix); overload; virtual; function ElementWiseDiv(Value : IMatrix) : TDoubleMatrix; overload; virtual; procedure AddAndScaleInPlace(const Offset, Scale : double); virtual; function AddAndScale(const Offset, Scale : double) : TDoubleMatrix; virtual; function Mean(RowWise : boolean) : TDoubleMatrix; procedure MeanInPlace(RowWise : boolean); function Variance(RowWise : boolean; unbiased : boolean = True) : TDoubleMatrix; procedure VarianceInPlace(RowWise : boolean; unbiased : boolean = True); function Std(RowWise : boolean; unbiased : boolean = True) : TDoubleMatrix; procedure StdInPlace(RowWise : boolean; unbiased : boolean = True); // calculates mean and variance in one step and stores the mean in the first row, the variance in the second // if RowWise is selected. If rowwise is false it's vice versa function MeanVariance(RowWise : boolean; unbiased : boolean = True) : TDoubleMatrix; procedure MeanVarianceInPlace(RowWise : boolean; unbiased : boolean = True); function Median(RowWise : boolean) : TDoubleMatrix; virtual; procedure MedianInPlace(RowWise : boolean); procedure SortInPlace(RowWise : boolean); virtual; function Sort(RowWise : boolean) : TDoubleMatrix; function Diff(RowWise : boolean) : TDoubleMatrix; procedure DiffInPlace(RowWise : boolean); function Sum(RowWise : boolean) : TDoubleMatrix; procedure SumInPlace(RowWise : boolean); overload; procedure SumInPlace(RowWise : boolean; keepMemory : boolean); overload; function CumulativeSum(RowWise : boolean) : TDoubleMatrix; procedure CumulativeSumInPlace(RowWise : boolean); function Add(const Value : double) : TDoubleMatrix; overload; procedure AddInPlace(const Value : double); overload; function Scale(const Value : double) : TDoubleMatrix; procedure ScaleInPlace(const Value : Double); function ScaleAndAdd(const aOffset, aScale : double) : TDoubleMatrix; procedure ScaleAndAddInPlace(const aOffset, aScale : double); function SQRT : TDoubleMatrix; procedure SQRTInPlace; procedure ElementwiseFuncInPlace(func : TMatrixFunc); overload; virtual; function ElementwiseFunc(func : TMatrixFunc) : TDoubleMatrix; overload; virtual; procedure ElementwiseFuncInPlace(func : TMatrixObjFunc); overload; virtual; function ElementwiseFunc(func : TMatrixObjFunc) : TDoubleMatrix; overload; virtual; procedure ElementwiseFuncInPlace(func : TMatrixMtxRefFunc); overload; virtual; function ElementwiseFunc(func : TMatrixMtxRefFunc) : TDoubleMatrix; overload; virtual; procedure ElementwiseFuncInPlace(func : TMatrixMtxRefObjFunc); overload; virtual; function ElementwiseFunc(func : TMatrixMtxRefObjFunc) : TDoubleMatrix; overload; virtual; {$IFDEF ANONMETHODS} procedure ElementwiseFuncInPlace(func : TMatrixFuncRef); overload; virtual; function ElementwiseFunc(func : TMatrixFuncRef) : TDoubleMatrix; overload; virtual; procedure ElementwiseFuncInPlace(func : TMatrixMtxRefFuncRef); overload; virtual; function ElementwiseFunc(func : TMatrixMtxRefFuncRef) : TDoubleMatrix; overload; virtual; {$ENDIF} // ################################################### // #### Linear System solver A*x = B -> use A.SolveLinEQ(B) -> x function SolveLinEQ(Value : TDoubleMatrix; numRefinements : integer = 0) : TDoubleMatrix; overload; virtual; function SolveLinEQ(Value : IMatrix; numRefinements : integer = 0) : TDoubleMatrix; overload; procedure SolveLinEQInPlace(Value : TDoubleMatrix; numRefinements : integer = 0); overload; virtual; procedure SolveLinEQInPlace(Value : IMatrix; numRefinements : integer = 0); overload; // solves least sqaures A*x = b using the QR decomposition function SolveLeastSquaresInPlace(out x : TDoubleMatrix; b : TDoubleMatrix) : TQRResult; overload; virtual; function SolveLeastSquaresInPlace(out x : IMatrix; b : IMatrix) : TQRResult; overload; function SolveLeastSquares(out x : TDoubleMatrix; b : TDoubleMatrix) : TQRResult; overload; virtual; function SolveLeastSquares(out x : IMatrix; b : IMatrix) : TQRResult; overload; // Matrix inversion (via LU decomposition) function InvertInPlace : TLinEquResult; virtual; function Invert : TDoubleMatrix; overload; virtual; function Invert( out InvMtx : TDoubleMatrix ) : TLinEquResult; overload; virtual; function Invert( out InvMtx : IMatrix ) : TLinEquResult; overload; virtual; function Determinant : double; virtual; // pseudoinversion via svd function PseudoInversionInPlace : TSVDResult; function PseudoInversion(out Mtx : TDoubleMatrix) : TSVDResult; overload; function PseudoInversion(out Mtx : IMatrix) : TSVDResult; overload; // ################################################### // #### Special functions procedure MaskedSetValue(const Mask : Array of boolean; const newVal : double); procedure RepeatMatrixInPlace(numX, numY : integer); function RepeatMatrix(numX, numY : integer) : TDoubleMatrix; // ################################################### // #### Matrix transformations function SVD(out U, V, W : TDoubleMatrix; onlyDiagElements : boolean = False) : TSVDResult; overload; virtual; function SVD(out U, V, W : IMatrix; onlyDiagElements : boolean = False) : TSVDResult; overload; function SymEig(out EigVals : TDoubleMatrix; out EigVect : TDoubleMatrix) : TEigenvalueConvergence; overload; function SymEig(out EigVals : TDoubleMatrix) : TEigenvalueConvergence; overload; function SymEig(out EigVals : IMatrix; out EigVect : IMatrix) : TEigenvalueConvergence; overload; function SymEig(out EigVals : IMatrix) : TEigenvalueConvergence; overload; function Eig(out EigVals : TDoublematrix; out EigVect : TDoubleMatrix; normEigVecs : boolean = False) : TEigenvalueConvergence; overload; function Eig(out EigVals : TDoublematrix) : TEigenvalueConvergence; overload; function Eig(out EigVals : IMatrix; out EigVect : IMatrix; normEigVecs : boolean = False) : TEigenvalueConvergence; overload; function Eig(out EigVals : IMatrix) : TEigenvalueConvergence; overload; function Cholesky(out Chol : TDoubleMatrix) : TCholeskyResult; overload; virtual; function Cholesky(out Chol : IMatrix) : TCholeskyResult; overload; // cleared lower triangle qr decomposition -> R only function QR(out R : TDoubleMatrix) : TQRResult; overload; function QR(out R : IMatrix) : TQRResult; overload; function QRFull(out Q, R : TDoubleMatrix) : TQRResult; overload; virtual; function QRFull(out Q, R : IMatrix) : TQRResult; overload; // ################################################### // #### Matrix assignment operations procedure Assign(Value : TDoubleMatrix); overload; procedure Assign(Value : IMatrix); overload; procedure Assign(Value : TDoubleMatrix; OnlySubElements : boolean); overload; procedure Assign(Value : IMatrix; OnlySubElements : boolean); overload; procedure Assign(const Mtx : Array of double; W, H : integer); overload; procedure AssignSubMatrix(Value : TDoubleMatrix; X : integer = 0; Y : integer = 0); overload; procedure AssignSubMatrix(Value : IMatrix; X : integer = 0; Y : integer = 0); overload; procedure Append(Value : IMatrix; appendColumns : boolean); overload; procedure Append(Value : TDoubleMatrix; appendColumns : boolean); overload; // actually the same as assign but it takes over the data and leaves an empty matrix object behind. procedure TakeOver(Value : TDoubleMatrix); overload; procedure TakeOver(Value : IMatrix); overload; function Clone : TDoubleMatrix; constructor Create; overload; constructor Create(aWidth, aHeight : integer; const initVal : double = 0); overload; constructor CreateEye(aWidth : integer); constructor Create(data : PDouble; aLineWidth : integer; aWidth, aHeight : integer); overload; constructor CreateDyn(const Data : TDoubleDynArray; aWidth, aHeight : integer); overload; constructor CreateDyn(const Data : TDoubleDynArray; fromDataIdx : integer; aWidth, aHeight : integer); overload; constructor Create(const Mtx : Array of double; W, H : integer); overload; constructor CreateRand(aWidth, aHeight : integer; method : TRandomAlgorithm; seed : LongInt); overload; // uses random engine constructor CreateRand(aWidth, aHeight : integer); overload; // uses system default random constructor CreateLinSpace(aVecLen : integer; const StartVal : double; const EndVal : double); destructor Destroy; override; end; type TDoubleMatrixDynArr = Array of TDoubleMatrix; IMatrixDynArr = Array of IMatrix; // default class used in derrived methods like in the global subspace methdos: // override the class value to use different matrix class implementations // e.g. the threaded version type TMatrixClass = class(TBaseMathPersistence) private fMatrixClass : TDoubleMatrixClass; function GetMtxClass: TDoubleMatrixClass; procedure SetMtxClass(const Value: TDoubleMatrixClass); protected procedure DefineProps; override; public property MatrixClass : TDoubleMatrixClass read GetMtxClass write SetMtxClass; class var DefMatrixClass : TDoubleMatrixClass; end; function MatrixFromTxtFile( fileName : string; mtxClass : TDoubleMatrixClass ) : TDoubleMatrix; overload; function MatrixFromTxtFile( fileName : string ) : TDoubleMatrix; overload; procedure MatrixToTxtFile(const fileName : string; const mtx : TDoubleMatrix; prec : integer = 8); implementation uses Math, MatrixASMStubSwitch, Eigensystems, LinAlgSVD, LinAlgQR, BlockSizeSetup, LinAlgCholesky, LinAlgLU, MathUtilFunc; {$IFNDEF CPUX64} type NativeUInt = Cardinal; {$ENDIF} // ########################################### // #### Inline functions (need to be first) // ########################################### procedure TDoubleMatrix.CheckAndRaiseError(assertionVal: boolean; const msg: string); begin if not assertionVal then raise EBaseMatrixException.Create(msg); end; procedure TDoubleMatrix.SetItems(x, y: integer; const Value: double); var pData : PLocConstDoubleArr; begin CheckAndRaiseError((x >= 0) and (x < fSubWidth), 'Dimension error'); CheckAndRaiseError((y >= 0) and (y < fSubHeight), 'Dimension error'); pData := fData; inc(PByte(pData), (fOffsetY + y)*fLineWidth); pData^[fOffsetX + x] := Value; end; function TDoubleMatrix.GetItems(x, y: integer): double; var pData : PLocConstDoubleArr; begin CheckAndRaiseError((x >= 0) and (x < fSubWidth) and (y >= 0) and (y < fSubHeight), 'Dimension error'); pData := fData; inc(PByte(pData), (fOffsetY + y)*fLineWidth); Result := pData^[fOffsetX + x]; end; procedure TDoubleMatrix.SetVecItem(idx: integer; const Value: double); begin if idx < fSubWidth then SetItems(idx, 0, Value) else SetItems(idx mod fSubWidth, idx div fSubWidth, Value); end; function TDoubleMatrix.GetVecItem(idx: integer): double; begin if idx < fSubWidth then Result := GetItems(idx, 0) else Result := GetItems(idx mod fSubWidth, idx div fSubWidth); end; // ########################################### // #### TDoubleMatrix // ########################################### function TDoubleMatrix.Abs: TDoubleMatrix; begin CheckAndRaiseError((fSubWidth > 0) and (fSubHeight > 0), 'Dimension Error'); Result := ResultClass.Create; Result.Assign(Self, True); MatrixAbs(Result.StartElement, Result.LineWidth, Result.Width, Result.Height); end; procedure TDoubleMatrix.AbsInPlace; begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); MatrixAbs(StartElement, LineWidth, fSubWidth, fSubHeight); end; function TDoubleMatrix.Add(Value: IMatrix): TDoubleMatrix; begin Result := Add(Value.GetObjRef); end; function TDoubleMatrix.Add(const Value: double): TDoubleMatrix; begin CheckAndRaiseError((fSubWidth > 0) and (fSubHeight > 0), 'Dimension Error'); Result := ResultClass.Create; Result.Assign(Self, True); MatrixAddAndScale(Result.StartElement, Result.LineWidth, Result.Width, Result.Height, Value, 1); end; function TDoubleMatrix.AddAndScale(const Offset, Scale: double): TDoubleMatrix; begin CheckAndRaiseError((width > 0) and (Height > 0), 'No data assigned'); Result := ResultClass.Create; Result.Assign(self, True); Result.AddAndScaleInPlace(Offset, Scale); end; procedure TDoubleMatrix.AddAndScaleInPlace(const Offset, Scale: double); begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); MatrixAddAndScale(StartElement, LineWidth, fSubWidth, fSubHeight, Offset, Scale); end; procedure TDoubleMatrix.AddInplace(const Value: double); begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); MatrixAddAndScale(StartElement, LineWidth, fSubWidth, fSubHeight, Value, 1); end; procedure TDoubleMatrix.AddInplace(Value: IMatrix); begin AddInplace(Value.GetObjRef); end; procedure TDoubleMatrix.AddInplace(Value: TDoubleMatrix); begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); // inplace matrix addition CheckAndRaiseError((fSubWidth = Value.fSubWidth) and (fSubHeight = Value.fSubHeight), 'Matrix dimensions do not match'); MatrixAdd(StartElement, LineWidth, StartElement, Value.StartElement, fSubWidth, fSubHeight, LineWidth, Value.LineWidth); end; procedure TDoubleMatrix.Assign(const Mtx: array of double; W, H : integer); begin CheckAndRaiseError((W*H > 0) and (Length(Mtx) = W*H), 'Dimension error'); SetWidthHeight(W, H); MatrixCopy(StartElement, LineWidth, @Mtx[0], W*sizeof(double), W, H); end; procedure TDoubleMatrix.AssignSubMatrix(Value: IMatrix; X, Y: integer); begin AssignSubMatrix(Value.GetObjRef, X, Y); end; procedure TDoubleMatrix.Assign(Value: IMatrix; OnlySubElements: boolean); begin Assign(Value.GetObjRef, OnlySubElements); end; procedure TDoubleMatrix.Assign(Value: IMatrix); begin Assign(Value.GetObjRef); end; procedure TDoubleMatrix.Append(Value: TDoubleMatrix; appendColumns: boolean); var pStart : PDouble; begin if AppendColumns then begin CheckAndRaiseError(Value.Height = fSubHeight, 'Dimension error, number of rows are not equal'); Resize(fSubWidth + Value.Width, fSubHeight); pStart := StartElement; inc(pStart, fSubWidth - Value.Width); MatrixCopy(pStart, LineWidth, Value.StartElement, Value.LineWidth, Value.Width, Value.Height ); end else begin CheckAndRaiseError(Value.Width = fSubWidth, 'Dimension error, number of columns are not equal'); Resize(fSubWidth, Value.Height + fSubHeight); pStart := GenPtr(StartElement, 0, fSubHeight - Value.Height, LineWidth); MatrixCopy(pStart, LineWidth, Value.StartElement, Value.LineWidth, Value.Width, Value.Height ); end; end; procedure TDoubleMatrix.Append(Value: IMatrix; appendColumns: boolean); begin Append(Value.GetObjRef, appendColumns); end; procedure TDoubleMatrix.AssignSubMatrix(Value: TDoubleMatrix; X, Y: integer); var pSelf, pValue : PDouble; begin CheckAndRaiseError((Value.Width <= Width + x) and (Value.Height <= Height + y), 'Dimension error'); if (Value.Width = 0) or (Value.Height = 0) then exit; pSelf := GenPtr(StartElement, x, y, LineWidth); pValue := Value.StartElement; MatrixCopy(pSelf, LineWidth, pValue, Value.LineWidth, Value.Width, Value.Height); end; procedure TDoubleMatrix.Assign(Value: TDoubleMatrix; OnlySubElements: boolean); begin fName := Value.Name; if OnlySubElements then begin SetWidthHeight(Value.Width, Value.Height); MatrixCopy(StartElement, LineWidth, Value.StartElement, Value.LineWidth, Value.Width, Value.Height); end else begin SetWidthHeight(Value.fWidth, Value.fHeight); MatrixCopy(StartElement, LineWidth, PDouble(Value.fData), Value.LineWidth, Value.fWidth, Value.fHeight); fSubWidth := Value.fSubWidth; fSubHeight := Value.fSubHeight; end; end; function TDoubleMatrix.Add(Value : TDoubleMatrix) : TDoubleMatrix; begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); CheckAndRaiseError((Value.fSubWidth = fSubWidth) and (Value.fSubHeight = fSubHeight), 'Dimension error'); Result := ResultClass.Create(fSubWidth, fSubHeight); MatrixAdd(Result.StartElement, Result.LineWidth, StartElement, Value.StartElement, fSubWidth, fSubHeight, LineWidth, Value.LineWidth); end; procedure TDoubleMatrix.AddVecInPlace(Value: TDoubleMatrix; rowWise: Boolean); var incX : TASMNativeInt; begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); if rowWise then CheckAndRaiseError((Value.VecLen = Width), 'Arguments dimension error') else CheckAndRaiseError((Value.VecLen = Height), 'Arguments dimension error'); incX := sizeof(double); if value.Width = 1 then incX := value.LineWidth; MatrixAddVec(StartElement, LineWidth, Value.StartElement, incX, Width, Height, RowWise); end; function TDoubleMatrix.AddVec(aVec: TDoubleMatrix; rowWise: Boolean): TDoubleMatrix; begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); if rowWise then CheckAndRaiseError((aVec.VecLen = Width), 'Arguments dimension error') else CheckAndRaiseError((aVec.VecLen = Height), 'Arguments dimension error'); Result := Clone; Result.AddVecInPlace(aVec, rowWise); end; procedure TDoubleMatrix.AddVecInPlace(Value: IMatrix; rowWise: Boolean); begin AddVecInPlace(Value.getObjRef, RowWise); end; function TDoubleMatrix.AddVec(iVec: IMatrix; rowWise: Boolean): TDoubleMatrix; begin Result := AddVec(iVec.GetObjRef, RowWise); end; procedure TDoubleMatrix.Assign(Value: TDoubleMatrix); begin Assign(Value, False); end; function TDoubleMatrix.Cholesky(out Chol: TDoubleMatrix): TCholeskyResult; var x, y : integer; begin CheckAndRaiseError((fSubWidth > 0) and (fSubWidth = fSubHeight), 'Cholesky decomposition is only allowed on square matrices'); chol := ResultClass.Create; try chol.Assign(Self); // block wise cholesky decomposition Result := MatrixCholeskyInPlace4(chol.StartElement, chol.LineWidth, chol.Width, 0, fLinEQProgress); if Result = crOk then begin // zero out the upper elements for y := 0 to fSubWidth - 1 do begin for x := y + 1 to fSubWidth - 1 do Chol[x, y] := 0; end; end else FreeAndNil(chol); except FreeAndNil(chol); Result := crNoPositiveDefinite; end; end; constructor TDoubleMatrix.Create; begin inherited Create; SetWidthHeight(1, 1); end; constructor TDoubleMatrix.Create(data: PDouble; aLineWidth, aWidth, aHeight: integer); begin inherited Create; fWidth := aWidth; fHeight := aHeight; fMemory := data; fData := PLocConstDoubleArr(data); fLineWidth := aLineWidth; fOffsetX := 0; fOffsetY := 0; fSubWidth := fWidth; fSubHeight := fHeight; CheckAndRaiseError(width*sizeof(double) <= LineWidth, 'Dimension error'); end; constructor TDoubleMatrix.Create(aWidth, aHeight: integer; const initVal : double); var pData : PConstDoubleArr; x, y : integer; begin inherited Create; SetWidthHeight(aWidth, aHeight); if initVal <> 0 then begin for y := 0 to height - 1 do begin pData := PConstDoubleArr( StartElement ); inc(PByte(pData), y*LineWidth); for x := 0 to Width - 1 do pData^[x] := initVal; end; end; end; constructor TDoubleMatrix.CreateDyn(const Data : TDoubleDynArray; aWidth, aHeight : integer); begin CheckAndRaiseError((aWidth*aHeight > 0) and (Length(Data) >= aWidth*aHeight), 'Dimension error'); inherited Create; SetWidthHeight(aWidth, aHeight); MatrixCopy(StartElement, LineWidth, @Data[0], aWidth*sizeof(double), aWidth, aHeight); end; constructor TDoubleMatrix.CreateEye(aWidth: integer); var i : integer; begin inherited Create; SetWidthHeight(aWidth, aWidth); for i := 0 to width - 1 do Items[i, i] := 1; end; constructor TDoubleMatrix.CreateRand(aWidth, aHeight: integer; method: TRandomAlgorithm; seed: LongInt); begin inherited Create; SetWidthHeight(aWidth, aHeight); fObj := TRandomGenerator.Create; TRandomGenerator(fObj).RandMethod := method; TRandomGenerator(fObj).Init(seed); ElementwiseFuncInPlace({$IFDEF FPC}@{$ENDIF}MtxRandWithEng); FreeAndNil(fObj); end; constructor TDoubleMatrix.CreateLinSpace(aVecLen: integer; const StartVal, EndVal: double); var value : double; pVec : PDouble; counter: Integer; dx : double; begin assert(vecLen >= 0, 'Error: initialized by negative len'); inherited Create; SetWidthHeight(1, aVecLen); if aVecLen = 0 then exit; dx := (EndVal - StartVal)/Math.Max(1, aVecLen - 1); pVec := StartElement; value := startVal; for counter := 0 to aVecLen - 1 do begin pVec^ := value; value := value + dx; inc(PByte(pVec), LineWidth); end; // account for small accumulated errors - so at least the last // value is as expected if aVecLen > 1 then Vec[vecLen - 1] := EndVal; end; constructor TDoubleMatrix.Create(const Mtx: array of double; W, H: integer); begin CheckAndRaiseError((W*H > 0) and (Length(Mtx) = W*H), 'Dimension error'); inherited Create; SetWidthHeight(W, H); MatrixCopy(StartElement, LineWidth, @Mtx[0], W*sizeof(double), W, H); end; constructor TDoubleMatrix.CreateDyn(const Data: TDoubleDynArray; fromDataIdx, aWidth, aHeight: integer); begin CheckAndRaiseError((aWidth*aHeight > 0) and (Length(Data) - fromDataIdx >= aWidth*aHeight), 'Dimension error'); inherited Create; SetWidthHeight(aWidth, aHeight); MatrixCopy(StartElement, LineWidth, @Data[fromDataIdx], aWidth*sizeof(double), aWidth, aHeight); end; procedure TDoubleMatrix.MtxRand(var value: double); begin value := Random; end; procedure TDoubleMatrix.MtxRandWithEng(var value: double); begin value := TRandomGenerator(fObj).Random; end; constructor TDoubleMatrix.CreateRand(aWidth, aHeight: integer); begin inherited Create; SetWidthHeight(aWidth, aHeight); ElementwiseFuncInPlace({$IFDEF FPC}@{$ENDIF}MtxRand); end; function TDoubleMatrix.CumulativeSum(RowWise: boolean): TDoubleMatrix; begin Result := TDoubleMatrix.Create(Width, Height); MatrixCumulativeSum(Result.StartElement, Result.LineWidth, StartElement, LineWidth, width, height, RowWise); end; procedure TDoubleMatrix.CumulativeSumInPlace(RowWise: boolean); begin MatrixCumulativeSum(StartElement, LineWidth, StartElement, LineWidth, Width, Height, RowWise); end; function TDoubleMatrix.Determinant: double; begin CheckAndRaiseError((Width > 0) and (Height = Width), 'Determinant only allowed on square matrices'); Result := MatrixDeterminant(StartElement, LineWidth, fSubWidth); end; function TDoubleMatrix.Diag(createDiagMtx : boolean): TDoubleMatrix; var x : integer; begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); if createDiagMtx then begin if (width = 1) then begin Result := TDoubleMatrix.Create(height, height); for x := 0 to Height - 1 do Result[x, x] := Vec[x]; end else if height = 1 then begin Result := TDoubleMatrix.Create(width, width); for x := 0 to width - 1 do Result[x, x] := Vec[x]; end else begin Result := TDoubleMatrix.Create(Math.Min(Width, Height), Math.Min(Width, Height)); for x := 0 to Math.Min(Width, Height) - 1 do Result[x, x] := Items[x, x]; end; end else begin Result := TDoubleMatrix.Create(1, Math.Min(Width, Height)); for x := 0 to Result.Height - 1 do Result[Math.Min(x, Result.width - 1), x] := Items[x, x]; end; end; procedure TDoubleMatrix.DiagInPlace(createDiagMtx : boolean); var dl : IMatrix; begin dl := Diag(createDiagMtx); TakeOver(dl); end; function TDoubleMatrix.Diff(RowWise: boolean): TDoubleMatrix; var newWidth : integer; newHeight : integer; begin Result := nil; if (width = 0) or (height = 0) then exit; newWidth := Width; newHeight := Height; if RowWise then dec(newWidth) else dec(newHeight); Result := ResultClass.Create(newWidth, newHeight); MatrixDiff(Result.StartElement, Result.LineWidth, StartElement, LineWidth, Width, Height, RowWise); end; procedure TDoubleMatrix.DiffInPlace(RowWise: boolean); begin if (width = 0) or (height = 0) then exit; MatrixDiff(StartElement, LineWidth, StartElement, LineWidth, Width, height, RowWise); if RowWise then begin dec(fSubWidth); fWidth := fSubWidth; end else begin dec(fSubHeight); fHeight := fHeight; end; end; function TDoubleMatrix.SolveLinEQ(Value: TDoubleMatrix; numRefinements : integer) : TDoubleMatrix; begin // solves the System: A * x = b // whereas A is the matrix stored in self, and be is the matrix in Value // The result is a matrix having the size of Value. CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); CheckAndRaiseError((fSubWidth = fSubHeight) and (Value.fSubHeight = fSubHeight), 'Dimension error'); Result := ResultClass.Create(Value.fSubWidth, fSubHeight); try if MatrixLinEQSolve(StartElement, LineWidth, fSubWidth, Value.StartElement, Value.LineWidth, Result.StartElement, Result.LineWidth, Value.fSubWidth, numRefinements, fLinEQProgress) = leSingular then raise ELinEQSingularException.Create('Matrix is singular'); except FreeAndNil(Result); raise; end; end; function TDoubleMatrix.SolveLeastSquares(out x : TDoubleMatrix; b : TDoubleMatrix): TQRResult; var tmpA : TDoubleMatrix; begin CheckAndRaiseError( width <= Height, 'Height must be at least width'); tmpA := Clone; try x := ResultClass.Create( 1, Width ); Result := MatrixQRSolve( x.StartElement, x.LineWidth, tmpA.StartElement, tmpA.LineWidth, b.StartElement, b.LineWidth, width, height); if Result <> qrOK then FreeAndNil(x); finally tmpA.Free; end; end; function TDoubleMatrix.SolveLeastSquares(out x : IMatrix; b: IMatrix): TQRResult; var tmp : TDoubleMatrix; begin Result := SolveLeastSquares(tmp, b.GetObjRef); x := tmp; end; function TDoubleMatrix.SolveLeastSquaresInPlace(out x: TDoubleMatrix; b: TDoubleMatrix): TQRResult; begin CheckAndRaiseError( width <= Height, 'Height must be at least width'); x := ResultClass.Create( 1, Width ); Result := MatrixQRSolve( x.StartElement, x.LineWidth, StartElement, LineWidth, b.StartElement, b.LineWidth, width, height); if Result <> qrOK then FreeAndNil(x); end; function TDoubleMatrix.SolveLeastSquaresInPlace(out x: IMatrix; b: IMatrix): TQRResult; var tmp : TDoubleMatrix; begin Result := SolveLeastSquaresInPlace(tmp, b.GetObjRef); x := tmp; end; function TDoubleMatrix.SolveLinEQ(Value: IMatrix; numRefinements: integer): TDoubleMatrix; begin Result := SolveLinEQ(Value.GetObjRef, numRefinements); end; procedure TDoubleMatrix.SolveLinEQInPlace(Value: IMatrix; numRefinements: integer); begin SolveLinEQInPlace(Value.GetObjRef, numRefinements); end; procedure TDoubleMatrix.SolveLinEQInPlace(Value: TDoubleMatrix; numRefinements : integer); var dt : TDoubleMatrix; begin // solves the System: A * x = b // whereas A is the matrix stored in self, and be is the matrix in Value // The result is a matrix having the size of Value. CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); CheckAndRaiseError((fSubWidth = fSubHeight) and (Value.fSubHeight = fSubHeight), 'Dimension error'); dt := ResultClass.Create(Value.fSubWidth, fSubHeight); try if MatrixLinEQSolve(StartElement, LineWidth, fSubWidth, Value.StartElement, Value.LineWidth, dt.StartElement, dt.LineWidth, Value.fSubWidth, numRefinements, fLinEQProgress) = leSingular then raise ELinEQSingularException.Create('Matrix is singular'); TakeOver(dt); finally dt.Free; end; end; function TDoubleMatrix.SQRT: TDoubleMatrix; begin CheckAndRaiseError((fSubWidth > 0) and (fSubHeight > 0), 'No data assigned'); Result := ResultClass.Create; Result.Assign(Self, True); MatrixSQRT(Result.StartElement, Result.LineWidth, Result.Width, Result.Height); end; procedure TDoubleMatrix.SQRTInPlace; begin CheckAndRaiseError((fSubWidth > 0) and (fSubHeight > 0), 'No data assigned'); MatrixSQRT(StartElement, LineWidth, fSubWidth, fSubHeight); end; function TDoubleMatrix.Eig(out EigVals, EigVect: IMatrix; normEigVecs : boolean = False): TEigenvalueConvergence; var outEigVals, outEigVect : TDoubleMatrix; begin Result := Eig(outEigVals, outEigVect, normEigVecs); EigVals := outEigVals; EigVect := outEigVect; end; function TDoubleMatrix.Eig(out EigVals: IMatrix): TEigenvalueConvergence; var outEigVals : TDoubleMatrix; begin Result := Eig(outEigVals); EigVals := outEigVals; end; function TDoubleMatrix.Eig(out EigVals: TDoublematrix): TEigenvalueConvergence; var dt : TDoubleMatrix; pReal, pImag : PDouble; dummy : TDoubleMatrix; perm : TIntegerDynArray; begin CheckAndRaiseError((fSubWidth > 0) and (fSubHeight = fSubWidth), 'Eigenvalues are only defined for square matrices'); EigVals := nil; dt := ResultClass.Create(2, fSubHeight); pReal := dt.StartElement; pImag := pReal; inc(pImag); dummy := TDoubleMatrix.Create; dummy.Assign(self); SetLength(perm, fSubWidth); MatrixHessenbergPerm(dummy.StartElement, dummy.LineWidth, StartElement, LineWidth, fSubWidth, @perm[0], sizeof(integer)); Result := MatrixEigHessenbergInPlace(dummy.StartElement, dummy.LineWidth, fSubWidth, pReal, dt.LineWidth, pImag, dt.LineWidth); dummy.Free; if Result = qlOk then EigVals := dt else dt.Free; end; function TDoubleMatrix.Eig(out EigVals, EigVect: TDoubleMatrix; normEigVecs : boolean = False): TEigenvalueConvergence; var dt : TDoubleMatrix; vecs : TDoubleMatrix; pReal, pImag : PDouble; dummy : TDoubleMatrix; begin CheckAndRaiseError((fSubWidth > 0) and (fSubHeight = fSubWidth), 'Eigenvalues are only defined for square matrices'); EigVals := nil; EigVect := nil; dt := nil; vecs := nil; try dt := ResultClass.Create(2, fSubHeight); pReal := dt.StartElement; pImag := pReal; inc(pImag); vecs := ResultClass.Create(fSubWidth, fSubHeight); // create a copy since the original content is destroyed! dummy := TDoubleMatrix.Create; try dummy.Assign(self); Result := MatrixUnsymEigVecInPlace(dummy.StartElement, dummy.LineWidth, fSubWidth, pReal, dt.LineWidth, pImag, dt.LineWidth, vecs.StartElement, vecs.LineWidth, True); finally dummy.Free; end; if Result = qlOk then begin if normEigVecs then MatrixNormEivecInPlace(vecs.StartElement, vecs.LineWidth, fSubWidth, pImag, dt.LineWidth); EigVals := dt; EigVect := vecs; end else begin dt.Free; vecs.Free; end; except dt.Free; vecs.Free; raise; end; end; function TDoubleMatrix.ElementwiseFunc(func: TMatrixFunc): TDoubleMatrix; begin CheckAndRaiseError((fSubWidth > 0) and (fSubHeight > 0), 'No data assigned'); Result := ResultClass.Create; Result.Assign(self); MatrixFunc(Result.StartElement, Result.LineWidth, Result.Width, Result.Height, func); end; procedure TDoubleMatrix.ElementwiseFuncInPlace(func: TMatrixFunc); begin CheckAndRaiseError((fSubWidth > 0) and (fSubHeight > 0), 'No data assigned'); MatrixFunc(StartElement, LineWidth, fSubWidth, fSubHeight, func); end; function TDoubleMatrix.ElementwiseFunc(func: TMatrixObjFunc): TDoubleMatrix; begin CheckAndRaiseError((fSubWidth > 0) and (fSubHeight > 0), 'No data assigned'); Result := ResultClass.Create; Result.Assign(self); MatrixFunc(Result.StartElement, Result.LineWidth, Result.Width, Result.Height, func); end; procedure TDoubleMatrix.ElementwiseFuncInPlace(func: TMatrixObjFunc); begin CheckAndRaiseError((fSubWidth > 0) and (fSubHeight > 0), 'No data assigned'); MatrixFunc(StartElement, LineWidth, fSubWidth, fSubHeight, func); end; function TDoubleMatrix.ElementwiseFunc(func: TMatrixMtxRefFunc): TDoubleMatrix; begin CheckAndRaiseError((fSubWidth > 0) and (fSubHeight > 0), 'No data assigned'); Result := ResultClass.Create; Result.Assign(self); MatrixFunc(Result.StartElement, Result.LineWidth, Result.Width, Result.Height, func); end; function TDoubleMatrix.ElementwiseFunc(func: TMatrixMtxRefObjFunc): TDoubleMatrix; begin CheckAndRaiseError((fSubWidth > 0) and (fSubHeight > 0), 'No data assigned'); Result := ResultClass.Create; Result.Assign(self); MatrixFunc(Result.StartElement, Result.LineWidth, Result.Width, Result.Height, func); end; procedure TDoubleMatrix.ElementwiseFuncInPlace(func: TMatrixMtxRefFunc); begin CheckAndRaiseError((fSubWidth > 0) and (fSubHeight > 0), 'No data assigned'); MatrixFunc(StartElement, LineWidth, fSubWidth, fSubHeight, func); end; procedure TDoubleMatrix.ElementwiseFuncInPlace(func: TMatrixMtxRefObjFunc); begin CheckAndRaiseError((fSubWidth > 0) and (fSubHeight > 0), 'No data assigned'); MatrixFunc(StartElement, LineWidth, fSubWidth, fSubHeight, func); end; {$IFDEF ANONMETHODS} procedure TDoubleMatrix.ElementwiseFuncInPlace(func : TMatrixFuncRef); begin CheckAndRaiseError((fSubWidth > 0) and (fSubHeight > 0), 'No data assigned'); MatrixFunc(StartElement, LineWidth, fSubWidth, fSubHeight, func); end; function TDoubleMatrix.ElementwiseFunc(func : TMatrixFuncRef) : TDoubleMatrix; begin CheckAndRaiseError((fSubWidth > 0) and (fSubHeight > 0), 'No data assigned'); Result := ResultClass.Create; Result.Assign(self); MatrixFunc(Result.StartElement, Result.LineWidth, Result.Width, Result.Height, func); end; procedure TDoubleMatrix.ElementwiseFuncInPlace(func : TMatrixMtxRefFuncRef); begin CheckAndRaiseError((fSubWidth > 0) and (fSubHeight > 0), 'No data assigned'); MatrixFunc(StartElement, LineWidth, fSubWidth, fSubHeight, func); end; function TDoubleMatrix.ElementwiseFunc(func : TMatrixMtxRefFuncRef) : TDoubleMatrix; begin CheckAndRaiseError((fSubWidth > 0) and (fSubHeight > 0), 'No data assigned'); Result := ResultClass.Create; Result.Assign(self); MatrixFunc(Result.StartElement, Result.LineWidth, Result.Width, Result.Height, func); end; {$ENDIF} function TDoubleMatrix.ElementWiseMult(Value: TDoubleMatrix) : TDoubleMatrix; begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); CheckAndRaiseError((fSubWidth = Value.fSubWidth) and (fSubHeight = Value.fSubHeight), 'Dimension error'); Result := ResultClass.Create; Result.Assign(self); MatrixElemMult(Result.StartElement, Result.LineWidth, StartElement, Value.StartElement, fSubWidth, fSubHeight, LineWidth, Value.LineWidth); end; procedure TDoubleMatrix.ElementWiseMultInPlace(Value: TDoubleMatrix); begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); CheckAndRaiseError((fSubWidth = Value.fSubWidth) and (fSubHeight = Value.fSubHeight), 'Dimension error'); MatrixElemMult(StartElement, LineWidth, StartElement, Value.StartElement, fSubWidth, fSubHeight, LineWidth, Value.LineWidth); end; function TDoubleMatrix.ElementWiseDiv(Value: TDoubleMatrix): TDoubleMatrix; begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); CheckAndRaiseError((fSubWidth = Value.fSubWidth) and (fSubHeight = Value.fSubHeight), 'Dimension error'); Result := ResultClass.Create; Result.Assign(self); MatrixElemDiv(Result.StartElement, Result.LineWidth, StartElement, Value.StartElement, fSubWidth, fSubHeight, LineWidth, Value.LineWidth); end; procedure TDoubleMatrix.ElementWiseDivInPlace(Value: TDoubleMatrix); begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); CheckAndRaiseError((fSubWidth = Value.fSubWidth) and (fSubHeight = Value.fSubHeight), 'Dimension error'); MatrixElemDiv(StartElement, LineWidth, StartElement, Value.StartElement, fSubWidth, fSubHeight, LineWidth, Value.LineWidth); end; procedure TDoubleMatrix.ElementWiseDivInPlace(Value : IMatrix); begin ElementWiseDivInPlace(Value.GetObjRef); end; function TDoubleMatrix.ElementWiseDiv(Value : IMatrix) : TDoubleMatrix; begin Result := ElementWiseDiv(Value.GetObjRef); end; function TDoubleMatrix.ElementwiseNorm2(doSqrt : boolean = True): double; begin Result := 0; if (Width > 0) and (Height > 0) then Result := MatrixElementwiseNorm2(StartElement, LineWidth, Width, Height, doSqrt); end; function TDoubleMatrix.GetLinEQProgress: TLinEquProgress; begin Result := fLinEQProgress; end; function TDoubleMatrix.GetObjRef: TDoubleMatrix; begin Result := self; end; function TDoubleMatrix.GetSubHeight: integer; begin Result := fSubHeight; end; function TDoubleMatrix.GetSubWidth: integer; begin Result := fSubWidth; end; function TDoubleMatrix.GetVecLen: integer; begin // treat matrix as vector Result := fSubWidth*fSubHeight; end; function TDoubleMatrix.Invert: TDoubleMatrix; begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); CheckAndRaiseError(fSubWidth = fSubHeight, 'Operation only allowed on square matrices'); Result := ResultClass.Create; try Result.Assign(Self, True); if MatrixInverseInPlace(Result.StartElement, Result.LineWidth, fSubWidth, fLinEQProgress) = leSingular then raise ELinEQSingularException.Create('Singular matrix'); except Result.Free; raise; end; end; function TDoubleMatrix.Invert(out InvMtx : TDoubleMatrix): TLinEquResult; begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); CheckAndRaiseError(fSubWidth = fSubHeight, 'Operation only allowed on square matrices'); InvMtx := ResultClass.Create; InvMtx.Assign(Self, True); Result := MatrixInverseInPlace(InvMtx.StartElement, InvMtx.LineWidth, fSubWidth, fLinEQProgress); if Result <> leOk then FreeAndNil(invMtx); end; function TDoubleMatrix.Invert(out InvMtx: IMatrix): TLinEquResult; var tmp : TDoubleMatrix; begin Result := Invert(tmp); InvMtx := tmp; end; function TDoubleMatrix.InvertInPlace: TLinEquResult; var dt : TDoubleMatrix; begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); CheckAndRaiseError(fSubWidth = fSubHeight, 'Operation only allowed on square matrices'); dt := ResultClass.Create(Width, Height); try dt.Assign(self, True); Result := MatrixInverseInPlace(dt.StartElement, dt.LineWidth, fSubWidth, fLinEQProgress); if Result = leOk then TakeOver(dt); FreeAndNil(dt); except dt.Free; raise; end; end; function TDoubleMatrix.LineWidth: integer; begin Result := fLineWidth; end; // set all values where mask = true to the new value procedure TDoubleMatrix.MaskedSetValue(const Mask: array of boolean; const newVal: double); var y : integer; x : integer; maskIdx : integer; pValue2 : PConstDoubleArr; pValue1 : PByte; begin CheckAndRaiseError(fSubWidth*fSubHeight = Length(Mask), 'Error number of mask elements must be the same as the matrix dimension'); pValue1 := PByte(StartElement); maskIdx := 0; for y := 0 to fsubHeight - 1 do begin pValue2 := PConstDoubleArr(pValue1); for x := 0 to fSubWidth - 1 do begin if not mask[maskidx] then pValue2^[x] := newVal; inc(maskidx); end; inc(pValue1, LineWidth); end; end; function TDoubleMatrix.Max: double; begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); Result := MatrixMax(StartElement, fSubWidth, fSubHeight, LineWidth); end; function TDoubleMatrix.Mean(RowWise: boolean): TDoubleMatrix; begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); if RowWise then begin Result := ResultClass.Create(1, fSubHeight); MatrixMean(Result.StartElement, Result.LineWidth, StartElement, LineWidth, fSubWidth, fSubHeight, RowWise); end else begin Result := ResultClass.Create(fSubWidth, 1); MatrixMean(Result.StartElement, Result.LineWidth, StartElement, LineWidth, fSubWidth, fSubHeight, RowWise); end; end; procedure TDoubleMatrix.MeanInPlace(RowWise: boolean); var dl : TDoubleMatrix; begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); dl := Mean(RowWise); try TakeOver(dl); finally dl.Free; end; end; function TDoubleMatrix.MeanVariance(RowWise, unbiased: boolean): TDoubleMatrix; begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); if RowWise then begin Result := ResultClass.Create(2, fSubHeight); MatrixMeanVar(Result.StartElement, Result.LineWidth, StartElement, LineWidth, fSubWidth, fSubHeight, RowWise, unbiased); end else begin Result := ResultClass.Create(fSubWidth, 2); MatrixMeanVar(Result.StartElement, Result.LineWidth, StartElement, LineWidth, fSubWidth, fSubHeight, RowWise, unbiased); end; end; procedure TDoubleMatrix.MeanVarianceInPlace(RowWise, unbiased: boolean); var dt : TDoubleMatrix; begin dt := MeanVariance(RowWise, unbiased); try TakeOver(dt); finally dt.Free; end; end; function TDoubleMatrix.Median(RowWise: boolean): TDoubleMatrix; begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); if RowWise then begin Result := ResultClass.Create(1, fSubHeight); MatrixMedian(Result.StartElement, Result.LineWidth, StartElement, LineWidth, fSubWidth, fSubHeight, RowWise, nil); end else begin Result := ResultClass.Create(fSubWidth, 1); MatrixMedian(Result.StartElement, Result.LineWidth, StartElement, LineWidth, fSubWidth, fSubHeight, RowWise, nil); end; end; procedure TDoubleMatrix.MedianInPlace(RowWise: boolean); var dl : TDoubleMatrix; begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); dl := Median(RowWise); try TakeOver(dl); finally dl.Free; end; end; function TDoubleMatrix.Sort(RowWise: boolean): TDoubleMatrix; begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); Result := ResultClass.Create; Result.Assign(self); Result.SortInPlace(RowWise); end; procedure TDoubleMatrix.SortInPlace(RowWise: boolean); begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); MatrixSort(StartElement, LineWidth, width, Height, RowWise, nil); end; function TDoubleMatrix.Std(RowWise: boolean; unbiased : boolean = True): TDoubleMatrix; begin Result := Variance(RowWise, unbiased); Result.SQRTInPlace; end; procedure TDoubleMatrix.StdInPlace(RowWise: boolean; unbiased : boolean = True); var dl : TDoubleMatrix; begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); dl := Std(RowWise, unbiased); try TakeOver(dl); finally dl.Free; end; end; function TDoubleMatrix.Variance(RowWise: boolean; unbiased : boolean = True): TDoubleMatrix; begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); if RowWise then begin Result := ResultClass.Create(1, fSubHeight); MatrixVar(Result.StartElement, Result.LineWidth, StartElement, LineWidth, fSubWidth, fSubHeight, RowWise, unbiased); end else begin Result := ResultClass.Create(fSubWidth, 1); MatrixVar(Result.StartElement, Result.LineWidth, StartElement, LineWidth, fSubWidth, fSubHeight, RowWise, unbiased); end; end; procedure TDoubleMatrix.VarianceInPlace(RowWise: boolean; unbiased : boolean = True); var dl : TDoubleMatrix; begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); dl := Variance(RowWise, unbiased); try TakeOver(dl); finally dl.Free; end; end; function TDoubleMatrix.Min: double; begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); Result := MatrixMin(StartElement, fSubWidth, fSubHeight, LineWidth); end; function TDoubleMatrix.Mult(Value: TDoubleMatrix): TDoubleMatrix; begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); Result := ResultClass.Create(Value.fSubWidth, fSubHeight); MatrixMult(Result.StartElement, Result.LineWidth, StartElement, Value.StartElement, fSubWidth, fSubHeight, Value.fSubWidth, Value.fSubHeight, LineWidth, Value.LineWidth); end; procedure TDoubleMatrix.MultInPlace(Value: TDoubleMatrix); var dl : TDoubleMatrix; begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); CheckAndRaiseError((fOffsetX = 0) and (fOffsetY = 0) and (fWidth = fSubWidth) and (fHeight = fSubHeight), 'Operation only allowed on full matrices'); CheckAndRaiseError((fSubWidth = Value.fSubHeight), 'Dimension error'); dl := Mult(Value); try TakeOver(dl); finally dl.Free; end; end; procedure TDoubleMatrix.MultInPlaceT1(Value: TDoubleMatrix); var dl : TDoubleMatrix; begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); CheckAndRaiseError((fOffsetX = 0) and (fOffsetY = 0) and (fWidth = fSubWidth) and (fHeight = fSubHeight), 'Operation only allowed on full matrices'); dl := MultT1(Value); try TakeOver(dl); finally dl.Free; end; end; procedure TDoubleMatrix.MultInPlaceT2(Value: TDoubleMatrix); var dl : TDoubleMatrix; begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); CheckAndRaiseError((fOffsetX = 0) and (fOffsetY = 0) and (fWidth = fSubWidth) and (fHeight = fSubHeight), 'Operation only allowed on full matrices'); dl := MultT2(Value); try TakeOver(dl); finally dl.Free; end; end; function TDoubleMatrix.MultT1(Value: TDoubleMatrix): TDoubleMatrix; begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); Result := ResultClass.Create(Value.fSubWidth, fSubWidth); MatrixMultT1Ex(Result.StartElement, Result.LineWidth, StartElement, Value.StartElement, fSubWidth, fSubHeight, Value.fSubWidth, Value.fSubHeight, LineWidth, Value.LineWidth, BlockMatrixCacheSize, doNone, nil); end; function TDoubleMatrix.MultT2(Value: TDoubleMatrix): TDoubleMatrix; begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); Result := ResultClass.Create(Value.fSubHeight, fSubHeight); MatrixMultT2Ex(Result.StartElement, Result.LineWidth, StartElement, Value.StartElement, fSubWidth, fSubHeight, Value.fSubWidth, Value.fSubHeight, LineWidth, Value.LineWidth, BlockMatrixCacheSize, doNone, nil); end; function TDoubleMatrix.Scale(const Value: double): TDoubleMatrix; begin CheckAndRaiseError((fSubWidth > 0) and (fSubHeight > 0), 'Dimension Error'); Result := ResultClass.Create; Result.Assign(Self, True); MatrixAddAndScale(Result.StartElement, Result.LineWidth, Result.Width, Result.Height, 0, Value); end; function TDoubleMatrix.ScaleAndAdd(const aOffset, aScale: double): TDoubleMatrix; begin CheckAndRaiseError((width > 0) and (Height > 0), 'No data assigned'); Result := ResultClass.Create; Result.Assign(self, True); Result.ScaleAndAddInPlace(aOffset, aScale); end; procedure TDoubleMatrix.ScaleAndAddInPlace(const aOffset, aScale: double); begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); MatrixScaleAndAdd(StartElement, LineWidth, fSubWidth, fSubHeight, aOffset, aScale); end; procedure TDoubleMatrix.ScaleInPlace(const Value: Double); begin MatrixAddAndScale(StartElement, LineWidth, fSubWidth, fSubHeight, 0, Value); end; procedure TDoubleMatrix.Normalize(RowWise: boolean); var dt : TDoubleMatrix; begin CheckAndRaiseError((width > 0) and (height > 0), 'Dimension error'); dt := ResultClass.Create(Width, Height); try MatrixNormalize(dt.StartElement, dt.LineWidth, StartElement, LineWidth, Width, Height, RowWise); TakeOver(dt); finally dt.Free; end; end; procedure TDoubleMatrix.NormZeroMeanVarOne(RowWise : boolean); begin CheckAndRaiseError((width > 0) and (height > 0), 'Dimension error'); MatrixNormalizeMeanVar(StartElement, LineWidth, width, height, RowWise); end; function TDoubleMatrix.PseudoInversion(out mtx : TDoubleMatrix) : TSVDResult; var tmp : TDoubleMatrix; begin CheckAndRaiseError((width > 0) and (height > 0), 'Dimension error'); mtx := ResultClass.Create( height, width ); tmp := ResultClass.Create; try tmp.Assign(self); Result := MatrixPseudoinverse2Ex( mtx.StartElement, mtx.LineWidth, tmp.StartElement, tmp.LineWidth, Width, Height, StartElement, LineWidth, fLinEQProgress ); if Result <> srOk then FreeAndNil(mtx); FreeAndNil(tmp); mtx.fLinEQProgress := nil; except FreeAndNil(mtx); FreeAndNil(tmp); raise; end; end; function TDoubleMatrix.PseudoInversion(out Mtx: IMatrix): TSVDResult; var outMtx : TDoubleMatrix; begin Result := PseudoInversion(outMtx); Mtx := outMtx; end; function TDoubleMatrix.PseudoInversionInPlace: TSVDResult; var mtx : TDoubleMatrix; begin CheckAndRaiseError((width > 0) and (height > 0), 'Dimension error'); mtx := ResultClass.Create(height, width); try Result := MatrixPseudoinverse2(mtx.StartElement, mtx.LineWidth, StartElement, LineWidth, Width, Height, fLinEQProgress); if Result = srOk then TakeOver(mtx); finally mtx.Free; end; end; function TDoubleMatrix.QR(out R: IMatrix): TQRResult; var outR : TDoubleMatrix; begin Result := QR(outR); R := outR; end; function TDoubleMatrix.QR(out R: TDoubleMatrix): TQRResult; var tmp : TDoubleMatrix; i, j : integer; begin Result := QR(R, tmp); tmp.Free; if Result = qrOK then begin R.Resize( Width, Math.Min(Width, Height) ); // clear lower triangular matrix of R for i := 1 to R.Height - 1 do for j := 0 to i - 1 do R[j, i] := 0; end; end; function TDoubleMatrix.QR(out ecosizeR: IMatrix; out tau : IMatrix): TQRResult; var outR : TDoubleMatrix; outTau : TDoubleMatrix; begin Result := QR(outR, outTau); ecosizeR := outR; tau := outTau; end; function TDoubleMatrix.QRFull(out Q, R: TDoubleMatrix): TQRResult; var tau : TDoubleMatrix; tmp : TDoubleMatrix; x, y : integer; pdata : PConstDoubleArr; begin Q := nil; R := nil; // ########################################### // #### First create a compact QR decomposition Result := QR(R, Tau); if Result <> qrOK then begin FreeAndNil(R); exit; end; // ########################################### // #### Calculation Q from the previous operation tmp := ResultClass.Create; try tmp.Assign(R); MatrixQFromQRDecomp(tmp.StartElement, tmp.LineWidth, Width, Height, tau.StartElement, fLinEQProgress); // now assign only the relevant parts of Q (or just copy it if we have a square matrix) if Width = height then Q := tmp else begin // economy size Q: tmp.SetSubMatrix(0, 0, Math.min(tmp.Width, tmp.Height), tmp.Height); Q := ResultClass.Create; Q.Assign(tmp, True); tmp.Free; tmp := R; tmp.SetSubMatrix(0, 0, tmp.Width, Math.Min(tmp.Width, tmp.Height)); R := ResultClass.Create; R.Assign(tmp, True); tmp.Free; end; // clear R so we only have un upper triangle matrix // zero out the parts occupied by Q for y := 1 to R.Height - 1 do begin pData := PConstDoubleArr( R.StartElement ); inc(PByte(pData), y*R.LineWidth); for x := 0 to Math.Min(r.Width, y) - 1 do pData^[x] := 0; end; finally Tau.Free; end; end; function TDoubleMatrix.QRFull(out Q, R: IMatrix): TQRResult; var outR, outQ : TDoubleMatrix; begin Result := QRFull(outQ, outR); Q := outQ; R := outR; end; function TDoubleMatrix.QR(out ecosizeR: TDoubleMatrix; out tau : TDoubleMatrix): TQRResult; begin // note: the QR decomposition here does not update the resulting matrix size -> it is further used in the Q decomposition and that memory // is needed there. So in any subsequent call one needs to adjust the size self. Also the lower triangular data is not destroyed and set to 0! ecosizeR := Clone; tau := ResultClass.Create(width, 1); try Result := MatrixQRDecompInPlace2(ecosizeR.StartElement, ecosizeR.LineWidth, width, height, tau.StartElement, fLinEQProgress); except FreeAndNil(ecosizeR); FreeAndNil(tau); raise; end; end; function TDoubleMatrix.RepeatMatrix(numX, numy : integer): TDoubleMatrix; begin Result := Clone; Result.RepeatMatrixInPlace(numX, numY); end; procedure TDoubleMatrix.RepeatMatrixInPlace(numX, numY: integer); var origW, origH : integer; subMtx : IMatrix; x, y : Integer; begin origW := Width; origH := Height; subMtx := Clone; SetWidthHeight( Width*numX, Height*numY ); for y := 0 to numY - 1 do for x := 0 to numX - 1 do AssignSubMatrix(subMtx, x*origW, y*origH); end; procedure TDoubleMatrix.ReserveMem(width, height : integer); begin // check if we need to reserve memory or if we already have a matrix with this size if (fWidth = width) and (fHeight = height) and (width > 0) and (height > 0) and Assigned(fMemory) then exit; if Assigned(fMemory) then FreeMem(fMemory); fData := nil; fMemory := nil; fLineWidth := 0; // create an always aligned matrix if (width > 0) and (height > 0) then begin // take special care for vectores - there are optimized functions // for those types (e.g. vector matrix multiplication) if width > 1 then begin // get an AVX friendly linewidth fData := MtxAllocAlign(width, height, fLineWidth, fMemory); end else begin fMemory := MtxAlloc($20 + height*width*sizeof(double)); fData := AlignPtr32( fMemory ); fLineWidth := sizeof(double); end; end; end; function TDoubleMatrix.Reshape(newWidth, newHeight: integer; RowMajor : boolean = False) : TDoubleMatrix; var xOld, yOld : integer; x, y : Integer; begin CheckAndRaiseError((fSubWidth > 0) and (fSubHeight > 0), 'Error operation not allowed on empty matrices'); CheckAndRaiseError((newWidth*newHeight) = (fSubWidth*fSubHeight), 'Error new dimension does not fit into the old one'); Result := ResultClass.Create(newWidth, newHeight); try if RowMajor then begin // reshape along rows not columns... xOld := 0; yOld := 0; for x := 0 to newWidth - 1 do begin for y := 0 to newHeight - 1 do begin Result[x, y] := Items[xOld, yOld]; inc(yOld); if yOld = Height then begin inc(xOld); yOld := 0; end; end; end; end else begin // reshape along rows not columns... xOld := 0; yOld := 0; for y := 0 to newheight - 1 do begin for x := 0 to newWidth - 1 do begin Result[x, y] := Items[xOld, yOld]; inc(xOld); if xOld = Width then begin inc(yOld); xOld := 0; end; end; end; end; except FreeAndNil(Result); raise; end; end; procedure TDoubleMatrix.ReshapeInPlace(newWidth, newHeight: integer; RowMajor : boolean = False); var res : TDoubleMatrix; begin CheckAndRaiseError((fWidth > 0) and (fHeight > 0), 'Error operation not allowed on empty matrices'); CheckAndRaiseError((fWidth = fSubWidth) and (fHeight = fSubHeight), 'Operation only allowed on full matrices'); CheckAndRaiseError((newWidth*newHeight) = (fWidth*fHeight), 'Error new dimension does not fit into the old one'); // check if the line width fits the old width -> then we only have to adjust the // line width parameter, otherwise copy. if (fWidth = fSubWidth) and (fHeight = fSubHeight) and (fLineWidth = fWidth*sizeof(double)) and not RowMajor then fLineWidth := newWidth*sizeof(double) else begin res := Reshape(newWidth, newHeight, RowMajor); TakeOver(res); res.Free; end; fWidth := newWidth; fHeight := newHeight; fSubWidth := newWidth; fSubHeight := newHeight; fOffsetX := 0; fOffsetY := 0; end; class function TDoubleMatrix.ResultClass: TDoubleMatrixClass; begin Result := TDoubleMatrix; end; procedure TDoubleMatrix.SetColumn(col : integer; Values: TDoubleMatrix; ValCols : integer); var pVal1 : PDouble; pVal2 : PDouble; y : integer; begin CheckAndRaiseError(Values.fSubHeight = fSubHeight, 'Dimension error'); CheckAndRaiseError((col >= 0) and (col < fSubWidth), 'Error index out of bounds'); pVal1 := StartElement; inc(pVal1, col); pVal2 := Values.StartElement; inc(pVal2, ValCols); for y := 0 to fSubHeight - 1 do begin pVal1^ := pVal2^; inc(PByte(pVal1), LineWidth); inc(PByte(pVal2), Values.LineWidth); end; end; procedure TDoubleMatrix.SetColumn(col: integer; Values: IMatrix; ValCols: integer); begin SetColumn(col, values.GetObjRef, ValCols); end; procedure TDoubleMatrix.SetData(data: PDouble; srcLineWidth, width, height: integer); begin ReserveMem(width, height); MatrixCopy(StartElement, LineWidth, data, srcLineWidth, width, height); end; procedure TDoubleMatrix.SetColumn(col : integer; const Values: array of Double); var pVal1 : PDouble; y : integer; begin CheckAndRaiseError(fSubHeight = Length(Values), 'Dimension error'); CheckAndRaiseError((col >= 0) and (col < fSubWidth), 'Error index out of bounds'); pVal1 := StartElement; inc(pVal1, col); for y := 0 to fSubHeight - 1 do begin pVal1^ := Values[y]; inc(PByte(pVal1), LineWidth); end; end; procedure TDoubleMatrix.SetHeight(const Value: integer); begin SetWidthHeight(fWidth, Value); end; procedure TDoubleMatrix.SetLinEQProgress(value: TLinEquProgress); begin fLinEQProgress := value; end; procedure TDoubleMatrix.SetRow(row : integer; Values: TDoubleMatrix; ValRow : integer); var pVal1 : PDouble; pVal2 : PDouble; begin CheckAndRaiseError(Values.Width = fSubWidth, 'Dimension Error'); CheckAndRaiseError((row >= 0) and (row < fSubHeight), 'Error index out of bounds'); pVal1 := StartElement; inc(PByte(pVal1), row*LineWidth); pVal2 := Values.StartElement; inc(PByte(pVal2), Values.LineWidth*ValRow); Move(pVal2^, pVal1^, fSubWidth*sizeof(double)); end; procedure TDoubleMatrix.SetRow(row : integer; const Values: array of Double); var pVal1 : PDouble; begin CheckAndRaiseError(Length(Values) = fSubWidth, 'Dimension Error'); CheckAndRaiseError((row >= 0) and (row < fSubHeight), 'Error index out of bounds'); pVal1 := StartElement; inc(PByte(pVal1), row*LineWidth); Move(Values[0], pVal1^, fSubWidth*sizeof(double)); end; procedure TDoubleMatrix.SetSubMatrix(x, y, Subwidth, Subheight: integer); begin CheckAndRaiseError((x >= 0) and (x + SubWidth <= fWidth), 'Dimension x error'); CheckAndRaiseError((y >= 0) and (y + SubHeight <= fHeight), 'Dimension y error'); fOffsetX := x; fOffsetY := y; fSubWidth := Subwidth; fSubHeight := Subheight; end; procedure TDoubleMatrix.SetValue(const initVal: double); var x, y : integer; pData : PConstDoubleArr; begin // ########################################### // #### Initialize the matrix with the given value for y := 0 to height - 1 do begin pData := PConstDoubleArr( StartElement ); inc(PByte(pData), y*LineWidth); for x := 0 to Width - 1 do pData^[x] := initVal; end; end; procedure TDoubleMatrix.SetWidth(const Value: integer); begin SetWidthHeight(Value, fHeight); end; procedure TDoubleMatrix.SetWidthHeight(const aWidth, aHeight: integer); begin InternalSetWidthHeight(aWidth, aHeight, True); end; procedure TDoubleMatrix.Resize(aNewWidth, aNewHeight: Integer); var origSubWidth, origSubHeight : integer; origMemory : Pointer; origLineWidth : TASMNativeInt; origStart : PDouble; begin CheckAndRaiseError( (aNewWidth > 0) and (aNewHeight > 0), 'Width and height need to be greater than 0'); origSubWidth := fSubWidth; origSubHeight := fSubHeight; origMemory := fMemory; origLineWidth := fLineWidth; origStart := StartElement; fMemory := nil; fData := nil; InternalSetWidthHeight(aNewWidth, aNewHeight, True); // ####################################### // #### copy old memory and free // note only the submatrix stuff is copied MatrixCopy( StartElement, LineWidth, origStart, origLineWidth, Math.Min(fWidth, origSubWidth), Math.Min( fHeight, origSubHeight ) ); FreeMem(origMemory); end; procedure TDoubleMatrix.InternalSetWidthHeight(const aWidth, aHeight: integer; AssignMem : boolean); begin CheckAndRaiseError((aWidth > 0) and (aHeight > 0), 'Dimension error'); if AssignMem then ReserveMem(aWidth, aHeight) else ReserveMem(0, 0); fWidth := aWidth; fHeight := aHeight; fSubWidth := aWidth; fSubHeight := aHeight; end; function TDoubleMatrix.StartElement: PDouble; begin if (fWidth <> 0) and (fHeight <> 0) then Result := PDouble(NativeUInt(@ (fData^[fOffsetX])) + NativeUInt(fOffsetY*fLineWidth)) else Result := nil; end; function TDoubleMatrix.Sub(Value: TDoubleMatrix): TDoubleMatrix; begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); CheckAndRaiseError((Value.fSubWidth = fSubWidth) and (Value.fSubHeight = fSubHeight), 'Dimension error'); Result := ResultClass.Create(fSubWidth, fSubHeight); MatrixSub(Result.StartElement, Result.LineWidth, StartElement, Value.StartElement, fSubWidth, fSubHeight, LineWidth, Value.LineWidth); end; procedure TDoubleMatrix.SubInPlace(Value: TDoubleMatrix); begin CheckAndRaiseError((Value.fSubWidth = fSubWidth) and (Value.fSubHeight = fSubHeight), 'Dimension error'); MatrixSub(StartElement, LineWidth, StartElement, Value.StartElement, fSubWidth, fSubHeight, LineWidth, Value.LineWidth); end; procedure TDoubleMatrix.SubVecInPlace(Value: TDoubleMatrix; rowWise : Boolean); var incX : TASMNativeInt; begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); if rowWise then CheckAndRaiseError((Value.VecLen = Width), 'Arguments dimension error') else CheckAndRaiseError((Value.VecLen = Height), 'Arguments dimension error'); incX := sizeof(double); if value.Width = 1 then incX := value.LineWidth; MatrixSubVec(StartElement, LineWidth, Value.StartElement, incX, Width, Height, RowWise); end; function TDoubleMatrix.SubVec(aVec: TDoubleMatrix; rowWise : Boolean): TDoubleMatrix; begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); if rowWise then CheckAndRaiseError((aVec.VecLen = Width), 'Arguments dimension error') else CheckAndRaiseError((aVec.VecLen = Height), 'Arguments dimension error'); Result := Clone; Result.SubVecInPlace(aVec, rowWise); end; procedure TDoubleMatrix.SubVecInPlace(Value: IMatrix; rowWise: Boolean); begin SubVecInPlace(Value.GetObjRef, RowWise); end; function TDoubleMatrix.SubVec(iVec: IMatrix; rowWise: Boolean): TDoubleMatrix; begin Result := SubVec(iVec.GetObjRef, RowWise); end; function TDoubleMatrix.SubMatrix: TDoubleDynArray; var pRes : PDouble; pVal : PDouble; i : integer; begin Result := nil; if fSubWidth*fSubHeight = 0 then exit; SetLength(Result, fSubWidth*fSubHeight); pVal := StartElement; pRes := @Result[0]; for i := 0 to fSubHeight - 1 do begin Move(pVal^, pRes^, sizeof(double)*fSubWidth); inc(PByte(pVal), LineWidth); inc(pRes, fSubWidth); end; end; function TDoubleMatrix.Sum(RowWise: boolean): TDoubleMatrix; begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); if RowWise then begin Result := ResultClass.Create(1, fSubHeight); MatrixSum(Result.StartElement, Result.LineWidth, StartElement, LineWidth, fSubWidth, fSubHeight, RowWise); end else begin Result := ResultClass.Create(fSubWidth, 1); MatrixSum(Result.StartElement, Result.LineWidth, StartElement, LineWidth, fSubWidth, fSubHeight, RowWise); end; end; procedure TDoubleMatrix.SumInPlace(RowWise, keepMemory: boolean); begin if not keepMemory then SumInPlace(RowWise) else begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); // inplace sum + do not change the if RowWise then begin MatrixSum(PDouble(fData), LineWidth, StartElement, LineWidth, fSubWidth, fSubHeight, RowWise); fOffsetX := 0; fSubWidth := 1; end else begin MatrixSum(PDouble(fData), LineWidth, StartElement, LineWidth, fSubWidth, fSubHeight, RowWise); fOffsetY := 0; fSubHeight := 1; end; end; end; procedure TDoubleMatrix.SumInPlace(RowWise: boolean); var dl : TDoubleMatrix; begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); dl := Sum(RowWise); try TakeOver(dl); finally dl.Free; end; end; function TDoubleMatrix.SVD(out U, V, W: IMatrix; onlyDiagElements: boolean): TSVDResult; var uObj, vObj, wObj : TDoubleMatrix; begin Result := SVD(uObj, vObj, wObj, onlyDiagElements); U := uObj; V := vObj; W := wObj; end; function TDoubleMatrix.SVD(out U, V, W: TDoubleMatrix; onlyDiagElements : boolean): TSVDResult; var pW : PConstDoubleArr; wArr : PByte; minWH : TASMNativeInt; i : Integer; begin CheckAndRaiseError((Width > 0) and (Height > 0), 'Dimension error'); U := nil; V := nil; W := nil; wArr := nil; try minWH := Math.Min(fSubWidth, fSubHeight); W := ResultClass.Create(ifthen(onlyDiagElements, 1, minWH), minWH); pW := PConstDoubleArr( W.StartElement ); if not onlyDiagElements then begin wArr := MtxAlloc( minWH*sizeof(double)); pW := PConstDoubleArr( wArr ); end; if width > height then begin V := Transpose; U := ResultClass.Create( fSubHeight, fSubHeight ); Result := MatrixSVDInPlace2(V.StartElement, V.LineWidth, Height, Width, pW, U.StartElement, U.LineWidth, SVDBlockSize, fLinEQProgress ); // we need a final transposition on the matrix U and V U.TransposeInPlace; V.TransposeInPlace; end else begin U := Clone; V := ResultClass.Create(fSubWidth, fSubWidth); Result := MatrixSVDInPlace2Ex(U.StartElement, U.LineWidth, Width, Height, pW, V.StartElement, V.LineWidth, StartElement, LineWidth, SVDBlockSize, fLinEQProgress); end; if Result <> srOk then begin FreeAndNil(u); FreeAndNil(V); FreeAndNil(W); end else if not onlyDiagElements then begin for i := 0 to minWH - 1 do W[i, i] := pW^[i]; end; if Assigned(wArr) then FreeMem(wArr); except FreeAndNil(u); FreeAndNil(V); FreeAndNil(W); if Assigned(wArr) then FreeMem(wArr); raise; end; end; function TDoubleMatrix.SymEig(out EigVals: TDoubleMatrix): TEigenvalueConvergence; var dt : TDoubleMatrix; vecs : TDoubleMatrix; begin CheckAndRaiseError((fSubWidth > 0) and (fSubWidth = fSubHeight), 'Eigenvalue calculation only allowed on square matrices'); EigVals := nil; dt := ResultClass.Create(1, fSubHeight); vecs := ResultClass.Create(fSubWidth, fSubWidth); try Result := MatrixEigTridiagonalMatrix(vecs.StartElement, vecs.LineWidth, StartElement, LineWidth, fSubWidth, dt.StartElement, dt.LineWidth); if Result = qlOk then begin EigVals := dt; vecs.Free; end else begin dt.Free; vecs.Free; end; except FreeAndNil(dt); FreeAndNil(vecs); raise; end; end; function TDoubleMatrix.SymEig(out EigVals, EigVect: TDoubleMatrix): TEigenvalueConvergence; var dt : TDoubleMatrix; vecs : TDoubleMatrix; begin CheckAndRaiseError((fSubWidth > 0) and (fSubWidth = fSubHeight), 'Eigenvalue calculation only allowed on square matrices'); EigVals := nil; EigVect := nil; dt := ResultClass.Create(1, fSubHeight); vecs := ResultClass.Create(fSubWidth, fSubWidth); try Result := MatrixEigTridiagonalMatrix(vecs.StartElement, vecs.LineWidth, StartElement, LineWidth, fSubWidth, dt.StartElement, dt.LineWidth); if Result = qlOk then begin EigVals := dt; EigVect := vecs; end else begin dt.Free; vecs.Free; end; except FreeAndNil(dt); FreeAndNil(vecs); raise; end; end; procedure TDoubleMatrix.TakeOver(Value: TDoubleMatrix); begin // free memory from self Clear; // move properties to self fSubWidth := Value.fSubWidth; fSubHeight := Value.fSubHeight; fMemory := Value.fMemory; fData := Value.fData; fLineWidth := Value.fLineWidth; fWidth := Value.fWidth; fHeight := Value.fHeight; fOffsetX := Value.fOffsetX; fOffsetY := Value.fOffsetY; // since this is a hostile takeover we need to clear the other object value.fSubWidth := 0; value.fSubHeight := 0; Value.fMemory := nil; value.fData := nil; value.fLineWidth := 0; value.fWidth := 0; value.fHeight := 0; value.fOffsetX := 0; value.fOffsetY := 0; end; procedure TDoubleMatrix.TakeOver(Value: IMatrix); begin TakeOver(Value.GetObjRef); end; function TDoubleMatrix.Trace: double; var i : Integer; begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); CheckAndRaiseError((Width = Height), 'Trace only defined on square matrices'); Result := 0; for i := 0 to Width - 1 do Result := Result + Items[i, i]; end; function TDoubleMatrix.Transpose : TDoubleMatrix; begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); Result := ResultClass.Create(fSubHeight, fSubWidth); MatrixTranspose(Result.StartElement, Result.LineWidth, StartElement, LineWidth, fSubWidth, fSubHeight); end; procedure TDoubleMatrix.TransposeInPlace; var dt : TDoubleMatrix; begin CheckAndRaiseError((Width > 0) and (Height > 0), 'No data assigned'); // transpose is only allowed on full matrix CheckAndRaiseError((fOffsetX = 0) and (fOffsetY = 0) and (fSubWidth = fWidth) and (fSubHeight = fHeight), 'Operation only allowed on full matrices'); // in case of vectors we can fasten things up a bit if (fwidth = 1) and (LineWidth = sizeof(double)) then begin fWidth := fHeight; fSubWidth := fSubHeight; fHeight := 1; fSubHeight := 1; fLineWidth := fWidth*sizeof(double); exit; end; if fHeight = 1 then begin fHeight := fWidth; fSubHeight := fSubWidth; fWidth := 1; fSubWidth := 1; fLineWidth := sizeof(double); exit; end; // ########################################### // #### Standard transpose dt := Transpose; try TakeOver(dt); finally dt.Free; end; end; procedure TDoubleMatrix.UseFullMatrix; begin fOffsetX := 0; fOffsetY := 0; fSubWidth := fWidth; fSubHeight := fHeight; end; // ########################################################### // #### Persistence functions procedure TDoubleMatrix.DefineProps; var origSubWidth, origSubHeight, origOffsetX, origOffsetY : integer; begin AddStringProperty('Name', fName); AddIntProperty('Width', fWidth); AddIntProperty('Height', fHeight); origSubWidth := fSubWidth; origSubHeight := fSubHeight; origOffsetX := fOffsetX; origOffsetY := fOffsetY; UseFullMatrix; AddDoubleArr('data', SubMatrix); SetSubMatrix(origOffsetX, origOffsetY, origSubWidth, origSubHeight); // note: add the offsets after we data -> this ensures that variables are not ovewritten AddIntProperty('SubWidth', fSubWidth); AddIntProperty('SubHeight', fSubHeight); AddIntProperty('OffsetX', fOffsetX); AddIntProperty('OffsetY', fOffsetY); end; function TDoubleMatrix.PropTypeOfName(const Name: string): TPropType; begin if CompareText(Name, 'Name') = 0 then Result := ptString else if CompareText(Name, 'Width') = 0 then Result := ptInteger else if CompareText(Name, 'Height') = 0 then Result := ptInteger else if CompareText(Name, 'data') = 0 then Result := ptDouble else if CompareText(Name, 'SubWidth') = 0 then Result := ptInteger else if CompareText(Name, 'SubHeight') = 0 then Result := ptInteger else if CompareText(Name, 'OffsetX') = 0 then Result := ptInteger else if CompareText(Name, 'OffsetY') = 0 then Result := ptInteger else Result := inherited PropTypeOfName(Name); end; destructor TDoubleMatrix.Destroy; begin Clear; inherited; end; procedure TDoubleMatrix.OnLoadDoubleArr(const Name: String; const Value: TDoubleDynArray); begin if (CompareText(Name, 'data') = 0) and (Length(Value) > 0) then begin CheckAndRaiseError(Length(value) = fWidth*fHeight, 'The loaded array does not fit the expected size.'); Assign(Value, fWidth, fHeight); end; end; procedure TDoubleMatrix.OnLoadStringProperty(const Name, Value: String); begin if CompareText(Name, 'Name') = 0 then fName := Value else inherited; end; procedure TDoubleMatrix.OnLoadIntProperty(const Name: String; Value: integer); begin if CompareText(Name, 'Width') = 0 then fWidth := Value else if CompareText(Name, 'Height') = 0 then fHeight := Value else if CompareText(Name, 'SubWidth') = 0 then fSubWidth := Value else if CompareText(Name, 'SubHeight') = 0 then fSubHeight := Value else if CompareText(Name, 'OffsetX') = 0 then fOffsetX := Value else if CompareText(Name, 'OffsetY') = 0 then fOffsetY := Value else end; function TDoubleMatrix.Cholesky(out Chol: IMatrix): TCholeskyResult; var outChol : TDoubleMatrix; begin Result := Cholesky(outChol); Chol := outChol; end; class function TDoubleMatrix.ClassIdentifier: String; begin Result := 'MTX'; end; procedure TDoubleMatrix.Clear; begin ReserveMem(0, 0); fWidth := 0; fHeight := 0; fSubWidth := 0; fSubHeight := 0; end; function TDoubleMatrix.Clone: TDoubleMatrix; begin Result := ResultClass.Create(Width, Height); Result.Assign(Self, True); end; procedure TDoubleMatrix.SetRow(row: integer; Values: IMatrix; ValRow: integer); begin SetRow(row, Values.GetObjRef, ValRow); end; function TDoubleMatrix.ElementWiseMult(Value: IMatrix): TDoubleMatrix; begin Result := ElementWiseMult(Value.GetObjRef); end; procedure TDoubleMatrix.ElementWiseMultInPlace(Value: IMatrix); begin ElementWiseMultInPlace(Value.GetObjRef); end; function TDoubleMatrix.Mult(Value: IMatrix): TDoubleMatrix; begin Result := Mult(Value.GetObjRef); end; procedure TDoubleMatrix.MultInPlace(Value: IMatrix); begin MultInPlace(Value.GetObjRef); end; procedure TDoubleMatrix.MultInPlaceT1(Value: IMatrix); begin MultInPlaceT1(Value.GetObjRef); end; procedure TDoubleMatrix.MultInPlaceT2(Value: IMatrix); begin MultInPlaceT2(Value.GetObjRef); end; function TDoubleMatrix.MultT1(Value: IMatrix): TDoubleMatrix; begin Result := MultT1(Value.GetObjRef); end; function TDoubleMatrix.MultT2(Value: IMatrix): TDoubleMatrix; begin Result := MultT2(VAlue.GetObjRef); end; function TDoubleMatrix.Sub(Value: IMatrix): TDoubleMatrix; begin Result := Sub(Value.GetObjRef); end; procedure TDoubleMatrix.SubInPlace(Value: IMatrix); begin SubInPlace(Value.GetObjRef); end; function TDoubleMatrix.SymEig(out EigVals, EigVect: IMatrix): TEigenvalueConvergence; var outEigVals, outEigVect : TDoubleMatrix; begin Result := SymEig(outEigVals, outEigVect); EigVals := outEigVals; EigVect := outEigVect; end; function TDoubleMatrix.SymEig(out EigVals: IMatrix): TEigenvalueConvergence; var outEigVals : TDoubleMatrix; begin Result := SymEig(outEigVals); EigVals := outEigVals; end; function TMatrixClass.GetMtxClass: TDoubleMatrixClass; begin Result := fMatrixClass; if Result = nil then Result := DefMatrixClass; end; procedure TMatrixClass.SetMtxClass(const Value: TDoubleMatrixClass); begin fMatrixClass := Value; end; procedure TMatrixClass.DefineProps; begin // do nothing here end; // ########################################### // #### Utility Functions to read and write simple textual based matrices // ########################################### procedure MatrixToTxtFile(const fileName : string; const mtx : TDoubleMatrix; prec : integer = 8); var s : UTF8String; x, y : integer; ft : TFormatSettings; begin ft := GetLocalFMTSet; ft.DecimalSeparator := '.'; with TFileStream.Create(fileName, fmCreate or fmOpenWrite) do try for y := 0 to mtx.Height - 1 do begin s := ''; for x := 0 to mtx.width - 1 do s := s + UTF8String(Format('%.*f,', [prec, mtx[x, y]], ft)); s[length(s)] := #13; s := s + #10; WriteBuffer(s[1], Length(s)); end; finally Free; end; end; function MatrixFromTxtFile( fileName : string ) : TDoubleMatrix; overload; begin Result := MatrixFromTxtFile( fileName, TDoubleMatrix ); end; function MatrixFromTxtFile( fileName : string; mtxClass : TDoubleMatrixClass ) : TDoubleMatrix; var fmt : TFormatSettings; w, h : integer; arr : TDoubleDynArray; numElem : integer; i : integer; slLine : TStringList; aFile : TStringList; cnt: Integer; begin fmt := GetLocalFMTSet; fmt.DecimalSeparator := '.'; Result := nil; numElem := 0; aFile := TStringList.Create; try aFile.LoadFromFile(filename); w := 0; h := aFile.Count; slLine := TStringList.Create; slLine.Delimiter := ' '; try for cnt := 0 to h - 1 do begin slLine.DelimitedText := aFile[cnt]; if w = 0 then begin w := slLine.Count; SetLength(arr, w*h); end; if w <> slLine.Count then raise Exception.Create('Number of columns do not match'); for i := 0 to slLine.Count - 1 do begin arr[numElem] := StrToFloat( slLine[i], fmt ); inc(numElem); end; end; finally slLine.Free; end; // ########################################### // #### Build resulting matrix SetLength(arr, numElem); Result := mtxClass.Create(arr, w, h ); finally aFile.Free; end; end; function TDoubleMatrix.AsVector( RowMajor : boolean = False ): TDoubleMatrix; begin if Height = 1 then Result := Clone else Result := Reshape(width*height, 1, RowMajor); end; initialization TMatrixClass.DefMatrixClass := TDoubleMatrix; RegisterMathIO(TDoubleMatrix); end.
35
155
0.648766
f1f62e81d34f872ac869bdcd3d708819a37fa125
3,398
dfm
Pascal
src/sbbs3/ctrl/MailFormUnit.dfm
jonny290/synchronet
012a39d00a3160a593ef5923fdc1ee95e0497083
[ "Artistic-2.0" ]
1
2017-07-18T03:56:48.000Z
2017-07-18T03:56:48.000Z
src/sbbs3/ctrl/MailFormUnit.dfm
jonny290/synchronet
012a39d00a3160a593ef5923fdc1ee95e0497083
[ "Artistic-2.0" ]
null
null
null
src/sbbs3/ctrl/MailFormUnit.dfm
jonny290/synchronet
012a39d00a3160a593ef5923fdc1ee95e0497083
[ "Artistic-2.0" ]
null
null
null
object MailForm: TMailForm Left = 735 Top = 317 Width = 480 Height = 150 Caption = 'Mail Server' Color = clBtnFace UseDockManager = True DefaultMonitor = dmPrimary DragKind = dkDock DragMode = dmAutomatic Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] OldCreateOrder = False Position = poDefault OnHide = FormHide PixelsPerInch = 96 TextHeight = 13 object ToolBar: TToolBar Left = 0 Top = 0 Width = 464 Height = 25 Caption = 'ToolBar' EdgeBorders = [] Flat = True Images = MainForm.ImageList ParentShowHint = False ShowHint = True TabOrder = 0 object StartButton: TToolButton Left = 0 Top = 0 Action = MainForm.MailStart ParentShowHint = False ShowHint = True end object LogPauseButton: TToolButton Left = 23 Top = 0 Action = MainForm.MailPause Style = tbsCheck end object StopButton: TToolButton Left = 46 Top = 0 Action = MainForm.MailStop ParentShowHint = False ShowHint = True end object RecycleButton: TToolButton Left = 69 Top = 0 Action = MainForm.MailRecycle end object ToolButton4: TToolButton Left = 92 Top = 0 Width = 8 Caption = 'ToolButton4' ImageIndex = 3 Style = tbsSeparator end object ConfigureButton: TToolButton Left = 100 Top = 0 Action = MainForm.MailConfigure end object ToolButton6: TToolButton Left = 123 Top = 0 Width = 8 Caption = 'ToolButton6' ImageIndex = 5 Style = tbsSeparator end object Status: TStaticText Left = 131 Top = 0 Width = 150 Height = 22 Hint = 'Mail Server Status' AutoSize = False BorderStyle = sbsSunken Caption = 'Down' TabOrder = 0 end object ToolButton1: TToolButton Left = 281 Top = 0 Width = 8 Caption = 'ToolButton1' ImageIndex = 6 Style = tbsSeparator end object ProgressBar: TProgressBar Left = 289 Top = 0 Width = 75 Height = 22 Hint = 'Mail Server Utilization' Min = 0 Max = 100 Smooth = True Step = 1 TabOrder = 1 end object ToolButton2: TToolButton Left = 364 Top = 0 Width = 8 Caption = 'ToolButton2' ImageIndex = 7 Style = tbsSeparator end object LogLevelText: TStaticText Left = 372 Top = 0 Width = 75 Height = 22 Hint = 'Log Level' AutoSize = False BorderStyle = sbsSunken TabOrder = 2 end object LogLevelUpDown: TUpDown Left = 447 Top = 0 Width = 16 Height = 22 Hint = 'Log Level Adjustment' Min = 0 Max = 7 Position = 0 TabOrder = 3 Wrap = False OnChangingEx = LogLevelUpDownChangingEx end end object Log: TRichEdit Left = 0 Top = 25 Width = 464 Height = 87 Align = alClient Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -12 Font.Name = 'MS Sans Serif' Font.Style = [] HideScrollBars = False ParentFont = False ReadOnly = True ScrollBars = ssBoth TabOrder = 1 WordWrap = False end end
20.975309
45
0.58505
f1f0a2865d4fbc132c4128783a27630d3782225b
35,816
pas
Pascal
Projects/LZMA.pas
winter-wh/issrc-is-5_4
bebd906f45bcaa3e3a22944e2511c583ae3dfb13
[ "FSFAP" ]
5
2018-01-03T06:43:07.000Z
2020-07-30T13:15:29.000Z
Projects/LZMA.pas
winter-wh/issrc-is-5_4
bebd906f45bcaa3e3a22944e2511c583ae3dfb13
[ "FSFAP" ]
null
null
null
Projects/LZMA.pas
winter-wh/issrc-is-5_4
bebd906f45bcaa3e3a22944e2511c583ae3dfb13
[ "FSFAP" ]
2
2019-11-04T02:54:49.000Z
2020-04-24T17:50:46.000Z
unit LZMA; { Inno Setup Copyright (C) 1997-2010 Jordan Russell Portions by Martijn Laan For conditions of distribution and use, see LICENSE.TXT. Interface to the LZMA/LZMA2 compression DLL Source code for the compression DLL can found in the lzma2/Encoder subdirectory. $jrsoftware: issrc/Projects/LZMA.pas,v 1.55 2010/09/07 03:09:36 jr Exp $ } interface {$I VERSION.INC} uses Windows, SysUtils, {$IFNDEF Delphi3orHigher} Ole2, {$ENDIF} Compress, Int64Em; { Note: Ole2 must be included in the 'uses' clause on D2, and after Windows, because it redefines E_* constants in Windows that are incorrect. E_OUTOFMEMORY, for example, is defined as $80000002 in Windows, instead of $8007000E. } function LZMAInitCompressFunctions(Module: HMODULE): Boolean; function LZMAGetLevel(const Value: String; var Level: Integer): Boolean; const clLZMAFast = 1; clLZMANormal = 2; clLZMAMax = 3; clLZMAUltra = 4; clLZMAUltra64 = 5; type { Internally-used types } TLZMASRes = type Integer; TLZMACompressorCustomWorker = class; TLZMACompressorProps = class(TCompressorProps) public Algorithm: Integer; BlockSize: Integer; BTMode: Integer; DictionarySize: Integer; NumBlockThreads: Integer; NumFastBytes: Integer; NumThreads: Integer; WorkerProcessFilename: String; constructor Create; end; { Internally-used records } TLZMAEncoderProps = record Algorithm: Integer; BlockSize: Integer; BTMode: Integer; DictionarySize: Integer; NumBlockThreads: Integer; NumFastBytes: Integer; NumThreads: Integer; end; TLZMACompressorRingBuffer = record Count: Longint; { updated by reader and writer using InterlockedExchangeAdd only } WriterOffset: Longint; { accessed only by writer thread } ReaderOffset: Longint; { accessed only by reader thread } Buf: array[0..$FFFFF] of Byte; end; PLZMACompressorSharedEvents = ^TLZMACompressorSharedEvents; TLZMACompressorSharedEvents = record TerminateWorkerEvent: THandle; StartEncodeEvent: THandle; EndWaitOnInputEvent: THandle; EndWaitOnOutputEvent: THandle; EndWaitOnProgressEvent: THandle; WorkerWaitingOnInputEvent: THandle; WorkerWaitingOnOutputEvent: THandle; WorkerHasProgressEvent: THandle; WorkerEncodeFinishedEvent: THandle; end; PLZMACompressorSharedData = ^TLZMACompressorSharedData; TLZMACompressorSharedData = record NoMoreInput: BOOL; ProgressKB: LongWord; EncodeResult: TLZMASRes; InputBuffer: TLZMACompressorRingBuffer; OutputBuffer: TLZMACompressorRingBuffer; end; PLZMACompressorProcessData = ^TLZMACompressorProcessData; TLZMACompressorProcessData = record StructSize: LongWord; ParentProcess: THandle; LZMA2: BOOL; EncoderProps: TLZMAEncoderProps; Events: TLZMACompressorSharedEvents; SharedDataStructSize: LongWord; SharedDataMapping: THandle; end; TLZMACompressor = class(TCustomCompressor) private FUseLZMA2: Boolean; FEvents: TLZMACompressorSharedEvents; FShared: PLZMACompressorSharedData; FWorker: TLZMACompressorCustomWorker; FEncodeStarted: Boolean; FEncodeFinished: Boolean; FLastInputWriteCount: LongWord; FLastProgressKB: LongWord; procedure FlushOutputBuffer(const OnlyOptimalSize: Boolean); procedure InitializeProps(const CompressionLevel: Integer; const ACompressorProps: TCompressorProps); class function IsEventSet(const AEvent: THandle): Boolean; class procedure SatisfyWorkerWait(const AWorkerEvent, AMainEvent: THandle); procedure SatisfyWorkerWaitOnInput; procedure SatisfyWorkerWaitOnOutput; procedure StartEncode; procedure UpdateProgress; procedure WaitForWorkerEvent; protected procedure DoCompress(const Buffer; Count: Longint); override; procedure DoFinish; override; public constructor Create(AWriteProc: TCompressorWriteProc; AProgressProc: TCompressorProgressProc; CompressionLevel: Integer; ACompressorProps: TCompressorProps); override; destructor Destroy; override; end; TLZMA2Compressor = class(TLZMACompressor) public constructor Create(AWriteProc: TCompressorWriteProc; AProgressProc: TCompressorProgressProc; CompressionLevel: Integer; ACompressorProps: TCompressorProps); override; end; { Internally-used classes } TLZMACompressorCustomWorker = class protected FEvents: PLZMACompressorSharedEvents; FShared: PLZMACompressorSharedData; public constructor Create(const AEvents: PLZMACompressorSharedEvents); virtual; function GetExitHandle: THandle; virtual; abstract; procedure SetProps(const LZMA2: Boolean; const EncProps: TLZMAEncoderProps); virtual; abstract; procedure UnexpectedTerminationError; virtual; abstract; end; implementation const ISLZMA_EXE_VERSION = 101; type TLZMACompressorHandle = type Pointer; TLZMAWorkerThread = class(TLZMACompressorCustomWorker) private FThread: THandle; FLZMAHandle: TLZMACompressorHandle; FReadLock, FWriteLock, FProgressLock: Integer; FLastProgressTick: DWORD; function FillBuffer(const AWrite: Boolean; const Data: Pointer; Size: Cardinal; var ProcessedSize: Cardinal): HRESULT; function ProgressMade(const TotalBytesProcessed: Integer64): HRESULT; function Read(var Data; Size: Cardinal; var ProcessedSize: Cardinal): HRESULT; function WakeMainAndWaitUntil(const AWakeEvent, AWaitEvent: THandle): HRESULT; procedure WorkerThreadProc; function Write(const Data; Size: Cardinal; var ProcessedSize: Cardinal): HRESULT; public constructor Create(const AEvents: PLZMACompressorSharedEvents); override; destructor Destroy; override; function GetExitHandle: THandle; override; procedure SetProps(const LZMA2: Boolean; const EncProps: TLZMAEncoderProps); override; procedure UnexpectedTerminationError; override; end; TLZMAWorkerProcess = class(TLZMACompressorCustomWorker) private FProcess: THandle; FSharedMapping: THandle; FExeFilename: String; public constructor Create(const AEvents: PLZMACompressorSharedEvents); override; destructor Destroy; override; function GetExitHandle: THandle; override; procedure SetProps(const LZMA2: Boolean; const EncProps: TLZMAEncoderProps); override; procedure UnexpectedTerminationError; override; property ExeFilename: String read FExeFilename write FExeFilename; end; PLZMASeqInStream = ^TLZMASeqInStream; TLZMASeqInStream = record Read: function(p: PLZMASeqInStream; var buf; var size: Cardinal): TLZMASRes; stdcall; Instance: TLZMAWorkerThread; end; PLZMASeqOutStream = ^TLZMASeqOutStream; TLZMASeqOutStream = record Write: function(p: PLZMASeqOutStream; const buf; size: Cardinal): Cardinal; stdcall; Instance: TLZMAWorkerThread; end; PLZMACompressProgress = ^TLZMACompressProgress; TLZMACompressProgress = record Progress: function(p: PLZMACompressProgress; inSize, outSize: Integer64): TLZMASRes; stdcall; Instance: TLZMAWorkerThread; end; var LZMADLLInitialized: Boolean; LZMA_Init: function(LZMA2: BOOL; var handle: TLZMACompressorHandle): TLZMASRes; stdcall; LZMA_SetProps: function(handle: TLZMACompressorHandle; const encProps: TLZMAEncoderProps; encPropsSize: Cardinal): TLZMASRes; stdcall; LZMA_Encode: function(handle: TLZMACompressorHandle; const inStream: TLZMASeqInStream; const outStream: TLZMASeqOutStream; const progress: TLZMACompressProgress): TLZMASRes; stdcall; LZMA_End: function(handle: TLZMACompressorHandle): TLZMASRes; stdcall; const { SRes (TLZMASRes) } SZ_OK = 0; SZ_ERROR_MEM = 2; SZ_ERROR_READ = 8; SZ_ERROR_PROGRESS = 10; SZ_ERROR_FAIL = 11; function InterlockedExchangeAdd(var Addend: Longint; Value: Longint): Longint; stdcall; external kernel32; function GetNumberOfProcessors: Cardinal; var SysInfo: TSystemInfo; begin GetSystemInfo(SysInfo); Result := SysInfo.dwNumberOfProcessors; end; function LZMAInitCompressFunctions(Module: HMODULE): Boolean; begin LZMADLLInitialized := False; LZMA_Init := GetProcAddress(Module, 'LZMA_Init3'); LZMA_SetProps := GetProcAddress(Module, 'LZMA_SetProps3'); LZMA_Encode := GetProcAddress(Module, 'LZMA_Encode3'); LZMA_End := GetProcAddress(Module, 'LZMA_End3'); Result := Assigned(LZMA_Init) and Assigned(LZMA_SetProps) and Assigned(LZMA_Encode) and Assigned(LZMA_End); if Result then LZMADLLInitialized := True else begin LZMA_Init := nil; LZMA_SetProps := nil; LZMA_Encode := nil; LZMA_End := nil; end; end; procedure LZMAInternalError(const Msg: String); begin raise ECompressInternalError.Create('lzma: ' + Msg); end; procedure LZMAInternalErrorFmt(const Msg: String; const Args: array of const); begin LZMAInternalError(Format(Msg, Args)); end; procedure LZMAWin32Error(const FunctionName: String); var LastError: DWORD; begin LastError := GetLastError; LZMAInternalErrorFmt('%s failed (%u)', [FunctionName, LastError]); end; function LZMAGetLevel(const Value: String; var Level: Integer): Boolean; begin Result := True; if CompareText(Value, 'fast') = 0 then Level := clLZMAFast else if CompareText(Value, 'normal') = 0 then Level := clLZMANormal else if CompareText(Value, 'max') = 0 then Level := clLZMAMax else if CompareText(Value, 'ultra') = 0 then Level := clLZMAUltra else if CompareText(Value, 'ultra64') = 0 then Level := clLZMAUltra64 else Result := False; end; function LZMACreateEvent(const ManualReset: BOOL): THandle; begin Result := CreateEvent(nil, ManualReset, False, nil); if Result = 0 then LZMAWin32Error('CreateEvent'); end; function LZMASeqInStreamReadWrapper(p: PLZMASeqInStream; var buf; var size: Cardinal): TLZMASRes; stdcall; begin if p.Instance.Read(buf, size, size) = S_OK then Result := SZ_OK else Result := SZ_ERROR_READ; end; function LZMASeqOutStreamWriteWrapper(p: PLZMASeqOutStream; const buf; size: Cardinal): Cardinal; stdcall; begin if p.Instance.Write(buf, size, Result) <> S_OK then Result := 0; end; function LZMACompressProgressProgressWrapper(p: PLZMACompressProgress; inSize, outSize: Integer64): TLZMASRes; stdcall; begin if p.Instance.ProgressMade(inSize) = S_OK then Result := SZ_OK else Result := SZ_ERROR_PROGRESS; end; { TLZMACompressorRingBuffer: Designed to support concurrent, lock-free access by two threads in a pipe-like fashion: one thread may read from the buffer (FIFO) at the same time another thread is writing to it. Two threads, however, may NOT both read, or both write simultaneously. } procedure RingBufferReset(var Ring: TLZMACompressorRingBuffer); begin Ring.Count := 0; Ring.WriterOffset := 0; Ring.ReaderOffset := 0; end; function RingBufferInternalWriteOrRead(var Ring: TLZMACompressorRingBuffer; const AWrite: Boolean; var Offset: Longint; const Data: Pointer; Size: Longint): Longint; var P: ^Byte; Bytes: Longint; begin Result := 0; P := Data; while Size > 0 do begin if AWrite then Bytes := SizeOf(Ring.Buf) - Ring.Count else Bytes := Ring.Count; if Bytes = 0 then { Buffer is full (write) or empty (read) } Break; if Bytes > Size then Bytes := Size; if Bytes > SizeOf(Ring.Buf) - Offset then Bytes := SizeOf(Ring.Buf) - Offset; if AWrite then begin Move(P^, Ring.Buf[Offset], Bytes); InterlockedExchangeAdd(Ring.Count, Bytes); end else begin Move(Ring.Buf[Offset], P^, Bytes); InterlockedExchangeAdd(Ring.Count, -Bytes); end; if Offset + Bytes = SizeOf(Ring.Buf) then Offset := 0 else Inc(Offset, Bytes); Dec(Size, Bytes); Inc(Result, Bytes); Inc(P, Bytes); end; end; function RingBufferRead(var Ring: TLZMACompressorRingBuffer; var Buf; const Size: Longint): Longint; begin Result := RingBufferInternalWriteOrRead(Ring, False, Ring.ReaderOffset, @Buf, Size); end; function RingBufferWrite(var Ring: TLZMACompressorRingBuffer; const Buf; const Size: Longint): Longint; begin Result := RingBufferInternalWriteOrRead(Ring, True, Ring.WriterOffset, @Buf, Size); end; function RingBufferReadToCallback(var Ring: TLZMACompressorRingBuffer; const AWriteProc: TCompressorWriteProc; Size: Longint): Longint; var Bytes: Longint; begin Result := 0; while Size > 0 do begin Bytes := Ring.Count; if Bytes = 0 then Break; if Bytes > Size then Bytes := Size; if Bytes > SizeOf(Ring.Buf) - Ring.ReaderOffset then Bytes := SizeOf(Ring.Buf) - Ring.ReaderOffset; AWriteProc(Ring.Buf[Ring.ReaderOffset], Bytes); InterlockedExchangeAdd(Ring.Count, -Bytes); if Ring.ReaderOffset + Bytes = SizeOf(Ring.Buf) then Ring.ReaderOffset := 0 else Inc(Ring.ReaderOffset, Bytes); Dec(Size, Bytes); Inc(Result, Bytes); end; end; { TLZMACompressorProps } constructor TLZMACompressorProps.Create; begin inherited; Algorithm := -1; BTMode := -1; end; { TLZMACompressorCustomWorker } constructor TLZMACompressorCustomWorker.Create(const AEvents: PLZMACompressorSharedEvents); begin inherited Create; FEvents := AEvents; end; { TLZMAWorkerThread } function WorkerThreadFunc(Parameter: Pointer): Integer; begin try TLZMAWorkerThread(Parameter).WorkerThreadProc; except end; Result := 0; end; constructor TLZMAWorkerThread.Create(const AEvents: PLZMACompressorSharedEvents); begin inherited; FShared := VirtualAlloc(nil, SizeOf(FShared^), MEM_COMMIT, PAGE_READWRITE); if FShared = nil then OutOfMemoryError; end; destructor TLZMAWorkerThread.Destroy; begin if FThread <> 0 then begin SetEvent(FEvents.TerminateWorkerEvent); WaitForSingleObject(FThread, INFINITE); CloseHandle(FThread); FThread := 0; end; if Assigned(FLZMAHandle) then LZMA_End(FLZMAHandle); if Assigned(FShared) then VirtualFree(FShared, 0, MEM_RELEASE); inherited; end; function TLZMAWorkerThread.GetExitHandle: THandle; begin Result := FThread; end; procedure TLZMAWorkerThread.SetProps(const LZMA2: Boolean; const EncProps: TLZMAEncoderProps); var Res: TLZMASRes; ThreadID: DWORD; begin Res := LZMA_Init(LZMA2, FLZMAHandle); if Res = SZ_ERROR_MEM then OutOfMemoryError; if Res <> SZ_OK then LZMAInternalErrorFmt('LZMA_Init failed with code %d', [Res]); if LZMA_SetProps(FLZMAHandle, EncProps, SizeOf(EncProps)) <> SZ_OK then LZMAInternalError('LZMA_SetProps failed'); FThread := BeginThread(nil, 0, WorkerThreadFunc, Self, 0, ThreadID); if FThread = 0 then LZMAWin32Error('BeginThread'); end; procedure TLZMAWorkerThread.UnexpectedTerminationError; begin LZMAInternalError('Worker thread terminated unexpectedly'); end; procedure TLZMAWorkerThread.WorkerThreadProc; { Worker thread main procedure } var InStream: TLZMASeqInStream; OutStream: TLZMASeqOutStream; CompressProgress: TLZMACompressProgress; H: array[0..1] of THandle; begin InStream.Read := LZMASeqInStreamReadWrapper; InStream.Instance := Self; OutStream.Write := LZMASeqOutStreamWriteWrapper; OutStream.Instance := Self; CompressProgress.Progress := LZMACompressProgressProgressWrapper; CompressProgress.Instance := Self; H[0] := FEvents.TerminateWorkerEvent; H[1] := FEvents.StartEncodeEvent; while WaitForMultipleObjects(2, @H, False, INFINITE) = WAIT_OBJECT_0 + 1 do begin FShared.EncodeResult := LZMA_Encode(FLZMAHandle, InStream, OutStream, CompressProgress); if not SetEvent(FEvents.WorkerEncodeFinishedEvent) then Break; end; end; function TLZMAWorkerThread.WakeMainAndWaitUntil(const AWakeEvent, AWaitEvent: THandle): HRESULT; var H: array[0..1] of THandle; begin if not SetEvent(AWakeEvent) then begin SetEvent(FEvents.TerminateWorkerEvent); Result := E_FAIL; Exit; end; H[0] := FEvents.TerminateWorkerEvent; H[1] := AWaitEvent; case WaitForMultipleObjects(2, @H, False, INFINITE) of WAIT_OBJECT_0 + 0: Result := E_ABORT; WAIT_OBJECT_0 + 1: Result := S_OK; else SetEvent(FEvents.TerminateWorkerEvent); Result := E_FAIL; end; end; function TLZMAWorkerThread.FillBuffer(const AWrite: Boolean; const Data: Pointer; Size: Cardinal; var ProcessedSize: Cardinal): HRESULT; { Called from worker thread (or a thread spawned by the worker thread) } var P: ^Byte; Bytes: Longint; begin ProcessedSize := 0; if Size > Cardinal(High(Longint)) then begin Result := E_INVALIDARG; Exit; end; P := Data; while Size <> 0 do begin if AWrite then Bytes := RingBufferWrite(FShared.OutputBuffer, P^, Size) else Bytes := RingBufferRead(FShared.InputBuffer, P^, Size); if Bytes = 0 then begin if AWrite then begin { Output buffer full; wait for the main thread to flush it } Result := WakeMainAndWaitUntil(FEvents.WorkerWaitingOnOutputEvent, FEvents.EndWaitOnOutputEvent); if Result <> S_OK then Exit; end else begin { Input buffer empty; wait for the main thread to fill it } if FShared.NoMoreInput then Break; Result := WakeMainAndWaitUntil(FEvents.WorkerWaitingOnInputEvent, FEvents.EndWaitOnInputEvent); if Result <> S_OK then Exit; end; end else begin Inc(ProcessedSize, Bytes); Dec(Size, Bytes); Inc(P, Bytes); end; end; Result := S_OK; end; function TLZMAWorkerThread.Read(var Data; Size: Cardinal; var ProcessedSize: Cardinal): HRESULT; { Called from worker thread (or a thread spawned by the worker thread) } begin { Sanity check: Make sure we're the only thread inside Read } if InterlockedExchange(FReadLock, 1) <> 0 then begin Result := E_FAIL; Exit; end; Result := FillBuffer(False, @Data, Size, ProcessedSize); FReadLock := 0; end; function TLZMAWorkerThread.Write(const Data; Size: Cardinal; var ProcessedSize: Cardinal): HRESULT; { Called from worker thread (or a thread spawned by the worker thread) } begin { Sanity check: Make sure we're the only thread inside Write } if InterlockedExchange(FWriteLock, 1) <> 0 then begin Result := E_FAIL; Exit; end; Result := FillBuffer(True, @Data, Size, ProcessedSize); FWriteLock := 0; end; function TLZMAWorkerThread.ProgressMade(const TotalBytesProcessed: Integer64): HRESULT; { Called from worker thread (or a thread spawned by the worker thread) } var T: DWORD; KBProcessed: Integer64; begin T := GetTickCount; if Cardinal(T - FLastProgressTick) >= Cardinal(100) then begin { Sanity check: Make sure we're the only thread inside Progress } if InterlockedExchange(FProgressLock, 1) <> 0 then begin Result := E_FAIL; Exit; end; FLastProgressTick := T; { Make sure TotalBytesProcessed isn't negative. LZMA's Types.h says "-1 for size means unknown value", though I don't see any place where LzmaEnc actually does call Progress with inSize = -1. } if Longint(TotalBytesProcessed.Hi) >= 0 then begin KBProcessed := TotalBytesProcessed; Div64(KBProcessed, 1024); FShared.ProgressKB := KBProcessed.Lo; end; Result := WakeMainAndWaitUntil(FEvents.WorkerHasProgressEvent, FEvents.EndWaitOnProgressEvent); FProgressLock := 0; end else Result := S_OK; end; { TLZMAWorkerProcess } constructor TLZMAWorkerProcess.Create(const AEvents: PLZMACompressorSharedEvents); begin inherited; FSharedMapping := CreateFileMapping(INVALID_HANDLE_VALUE, nil, PAGE_READWRITE, 0, SizeOf(FShared^), nil); if FSharedMapping = 0 then LZMAWin32Error('CreateFileMapping'); FShared := MapViewOfFile(FSharedMapping, FILE_MAP_WRITE, 0, 0, SizeOf(FShared^)); if FShared = nil then LZMAWin32Error('MapViewOfFile'); end; destructor TLZMAWorkerProcess.Destroy; begin if FProcess <> 0 then begin SetEvent(FEvents.TerminateWorkerEvent); WaitForSingleObject(FProcess, INFINITE); CloseHandle(FProcess); FProcess := 0; end; if Assigned(FShared) then UnmapViewOfFile(FShared); if FSharedMapping <> 0 then CloseHandle(FSharedMapping); inherited; end; function TLZMAWorkerProcess.GetExitHandle: THandle; begin Result := FProcess; end; procedure TLZMAWorkerProcess.SetProps(const LZMA2: Boolean; const EncProps: TLZMAEncoderProps); function GetSystemDir: String; var Buf: array[0..MAX_PATH-1] of Char; begin GetSystemDirectory(Buf, SizeOf(Buf) div SizeOf(Buf[0])); Result := Buf; end; procedure DupeHandle(const SourceHandle: THandle; const DestProcess: THandle; var DestHandle: THandle; const DesiredAccess: DWORD); begin if not DuplicateHandle(GetCurrentProcess, SourceHandle, DestProcess, @DestHandle, DesiredAccess, False, 0) then LZMAWin32Error('DuplicateHandle'); end; procedure DupeEventHandles(const Src: TLZMACompressorSharedEvents; const Process: THandle; var Dest: TLZMACompressorSharedEvents); procedure DupeEvent(const SourceHandle: THandle; var DestHandle: THandle); begin DupeHandle(SourceHandle, Process, DestHandle, SYNCHRONIZE or EVENT_MODIFY_STATE); end; begin DupeEvent(Src.TerminateWorkerEvent, Dest.TerminateWorkerEvent); DupeEvent(Src.StartEncodeEvent, Dest.StartEncodeEvent); DupeEvent(Src.EndWaitOnInputEvent, Dest.EndWaitOnInputEvent); DupeEvent(Src.EndWaitOnOutputEvent, Dest.EndWaitOnOutputEvent); DupeEvent(Src.EndWaitOnProgressEvent, Dest.EndWaitOnProgressEvent); DupeEvent(Src.WorkerWaitingOnInputEvent, Dest.WorkerWaitingOnInputEvent); DupeEvent(Src.WorkerWaitingOnOutputEvent, Dest.WorkerWaitingOnOutputEvent); DupeEvent(Src.WorkerHasProgressEvent, Dest.WorkerHasProgressEvent); DupeEvent(Src.WorkerEncodeFinishedEvent, Dest.WorkerEncodeFinishedEvent); end; const InheritableSecurity: TSecurityAttributes = ( nLength: SizeOf(InheritableSecurity); lpSecurityDescriptor: nil; bInheritHandle: True); var ProcessDataMapping: THandle; ProcessData: PLZMACompressorProcessData; StartupInfo: TStartupInfo; ProcessInfo: TProcessInformation; begin ProcessData := nil; ProcessDataMapping := CreateFileMapping(INVALID_HANDLE_VALUE, @InheritableSecurity, PAGE_READWRITE, 0, SizeOf(ProcessData^), nil); if ProcessDataMapping = 0 then LZMAWin32Error('CreateFileMapping'); try ProcessData := MapViewOfFile(ProcessDataMapping, FILE_MAP_WRITE, 0, 0, SizeOf(ProcessData^)); if ProcessData = nil then LZMAWin32Error('MapViewOfFile'); ProcessData.StructSize := SizeOf(ProcessData^); ProcessData.LZMA2 := LZMA2; ProcessData.EncoderProps := EncProps; ProcessData.SharedDataStructSize := SizeOf(FShared^); FillChar(StartupInfo, SizeOf(StartupInfo), 0); StartupInfo.cb := SizeOf(StartupInfo); StartupInfo.dwFlags := STARTF_FORCEOFFFEEDBACK; if not CreateProcess(PChar(FExeFilename), PChar(Format('islzma_exe %d 0x%x', [ISLZMA_EXE_VERSION, ProcessDataMapping])), nil, nil, True, CREATE_DEFAULT_ERROR_MODE or CREATE_SUSPENDED, nil, PChar(GetSystemDir), StartupInfo, ProcessInfo) then LZMAWin32Error('CreateProcess'); try { We duplicate the handles instead of using inheritable handles so that if something outside this unit calls CreateProcess() while compression is in progress, our handles won't be inadvertently passed on to that other process. } DupeHandle(GetCurrentProcess, ProcessInfo.hProcess, ProcessData.ParentProcess, SYNCHRONIZE); DupeHandle(FSharedMapping, ProcessInfo.hProcess, ProcessData.SharedDataMapping, FILE_MAP_WRITE); DupeEventHandles(FEvents^, ProcessInfo.hProcess, ProcessData.Events); if ResumeThread(ProcessInfo.hThread) = DWORD(-1) then LZMAWin32Error('ResumeThread'); except CloseHandle(ProcessInfo.hThread); TerminateProcess(ProcessInfo.hProcess, 1); WaitForSingleObject(ProcessInfo.hProcess, INFINITE); CloseHandle(ProcessInfo.hProcess); raise; end; FProcess := ProcessInfo.hProcess; CloseHandle(ProcessInfo.hThread); finally if Assigned(ProcessData) then UnmapViewOfFile(ProcessData); CloseHandle(ProcessDataMapping); end; end; procedure TLZMAWorkerProcess.UnexpectedTerminationError; var ProcessExitCode: DWORD; begin if GetExitCodeProcess(FProcess, ProcessExitCode) then LZMAInternalErrorFmt('Worker process terminated unexpectedly (0x%x)', [ProcessExitCode]) else LZMAInternalError('Worker process terminated unexpectedly ' + '(failed to get exit code)'); end; { TLZMACompressor } constructor TLZMACompressor.Create(AWriteProc: TCompressorWriteProc; AProgressProc: TCompressorProgressProc; CompressionLevel: Integer; ACompressorProps: TCompressorProps); begin inherited; FEvents.TerminateWorkerEvent := LZMACreateEvent(True); { manual reset } FEvents.StartEncodeEvent := LZMACreateEvent(False); { auto reset } FEvents.EndWaitOnInputEvent := LZMACreateEvent(False); { auto reset } FEvents.EndWaitOnOutputEvent := LZMACreateEvent(False); { auto reset } FEvents.EndWaitOnProgressEvent := LZMACreateEvent(False); { auto reset } FEvents.WorkerWaitingOnInputEvent := LZMACreateEvent(True); { manual reset } FEvents.WorkerWaitingOnOutputEvent := LZMACreateEvent(True); { manual reset } FEvents.WorkerHasProgressEvent := LZMACreateEvent(True); { manual reset } FEvents.WorkerEncodeFinishedEvent := LZMACreateEvent(True); { manual reset } InitializeProps(CompressionLevel, ACompressorProps); end; destructor TLZMACompressor.Destroy; procedure DestroyEvent(const AEvent: THandle); begin if AEvent <> 0 then CloseHandle(AEvent); end; begin FWorker.Free; DestroyEvent(FEvents.WorkerEncodeFinishedEvent); DestroyEvent(FEvents.WorkerHasProgressEvent); DestroyEvent(FEvents.WorkerWaitingOnOutputEvent); DestroyEvent(FEvents.WorkerWaitingOnInputEvent); DestroyEvent(FEvents.EndWaitOnProgressEvent); DestroyEvent(FEvents.EndWaitOnOutputEvent); DestroyEvent(FEvents.EndWaitOnInputEvent); DestroyEvent(FEvents.StartEncodeEvent); DestroyEvent(FEvents.TerminateWorkerEvent); inherited; end; procedure TLZMACompressor.InitializeProps(const CompressionLevel: Integer; const ACompressorProps: TCompressorProps); const algorithm: array [clLZMAFast..clLZMAUltra64] of Cardinal = (0, 1, 1, 1, 1); dicSize: array [clLZMAFast..clLZMAUltra64] of Cardinal = (32 shl 10, 2 shl 20, 8 shl 20, 32 shl 20, 64 shl 20); numFastBytes: array [clLZMAFast..clLZMAUltra64] of Cardinal = (32, 32, 64, 64, 64); btMode: array [clLZMAFast..clLZMAUltra64] of Cardinal = (0, 1, 1, 1, 1); var EncProps: TLZMAEncoderProps; Props: TLZMACompressorProps; WorkerProcessFilename: String; begin if (CompressionLevel < Low(algorithm)) or (CompressionLevel > High(algorithm)) then LZMAInternalError('TLZMACompressor.Create got invalid CompressionLevel ' + IntToStr(CompressionLevel)); FillChar(EncProps, SizeOf(EncProps), 0); EncProps.Algorithm := algorithm[CompressionLevel]; EncProps.BTMode := btMode[CompressionLevel]; EncProps.DictionarySize := dicSize[CompressionLevel]; EncProps.NumBlockThreads := -1; EncProps.NumFastBytes := numFastBytes[CompressionLevel]; EncProps.NumThreads := -1; if ACompressorProps is TLZMACompressorProps then begin Props := (ACompressorProps as TLZMACompressorProps); if Props.Algorithm <> -1 then EncProps.Algorithm := Props.Algorithm; EncProps.BlockSize := Props.BlockSize; if Props.BTMode <> -1 then EncProps.BTMode := Props.BTMode; if Props.DictionarySize <> 0 then EncProps.DictionarySize := Props.DictionarySize; if Props.NumBlockThreads <> 0 then EncProps.NumBlockThreads := Props.NumBlockThreads; if Props.NumFastBytes <> 0 then EncProps.NumFastBytes := Props.NumFastBytes; if Props.NumThreads <> 0 then EncProps.NumThreads := Props.NumThreads; WorkerProcessFilename := Props.WorkerProcessFilename; end; if WorkerProcessFilename <> '' then begin FWorker := TLZMAWorkerProcess.Create(@FEvents); (FWorker as TLZMAWorkerProcess).ExeFilename := WorkerProcessFilename; end else begin if not LZMADLLInitialized then LZMAInternalError('LZMA DLL functions not initialized'); FWorker := TLZMAWorkerThread.Create(@FEvents); end; FShared := FWorker.FShared; FWorker.SetProps(FUseLZMA2, EncProps); end; class function TLZMACompressor.IsEventSet(const AEvent: THandle): Boolean; begin Result := False; case WaitForSingleObject(AEvent, 0) of WAIT_OBJECT_0: Result := True; WAIT_TIMEOUT: ; else LZMAInternalError('IsEventSet: WaitForSingleObject failed'); end; end; class procedure TLZMACompressor.SatisfyWorkerWait(const AWorkerEvent, AMainEvent: THandle); begin if IsEventSet(AWorkerEvent) then begin if not ResetEvent(AWorkerEvent) then LZMAWin32Error('SatisfyWorkerWait: ResetEvent'); if not SetEvent(AMainEvent) then LZMAWin32Error('SatisfyWorkerWait: SetEvent'); end; end; procedure TLZMACompressor.SatisfyWorkerWaitOnInput; begin SatisfyWorkerWait(FEvents.WorkerWaitingOnInputEvent, FEvents.EndWaitOnInputEvent); end; procedure TLZMACompressor.SatisfyWorkerWaitOnOutput; begin SatisfyWorkerWait(FEvents.WorkerWaitingOnOutputEvent, FEvents.EndWaitOnOutputEvent); end; procedure TLZMACompressor.UpdateProgress; var NewProgressKB: LongWord; Bytes: Integer64; begin if IsEventSet(FEvents.WorkerHasProgressEvent) then begin if Assigned(ProgressProc) then begin NewProgressKB := FShared.ProgressKB; Bytes.Hi := 0; Bytes.Lo := NewProgressKB - FLastProgressKB; { wraparound is OK } Mul64(Bytes, 1024); FLastProgressKB := NewProgressKB; while Bytes.Hi <> 0 do begin ProgressProc(Cardinal($80000000)); ProgressProc(Cardinal($80000000)); Dec(Bytes.Hi); end; ProgressProc(Bytes.Lo); end; if not ResetEvent(FEvents.WorkerHasProgressEvent) then LZMAWin32Error('UpdateProgress: ResetEvent'); if not SetEvent(FEvents.EndWaitOnProgressEvent) then LZMAWin32Error('UpdateProgress: SetEvent'); end; end; procedure TLZMACompressor.FlushOutputBuffer(const OnlyOptimalSize: Boolean); const { Calling WriteProc may be an expensive operation, so we prefer to wait until we've accumulated a reasonable number of bytes before flushing } OptimalFlushSize = $10000; { can't exceed size of OutputBuffer.Buf } var Bytes: Longint; begin while True do begin Bytes := FShared.OutputBuffer.Count; if Bytes = 0 then Break; if Bytes > OptimalFlushSize then Bytes := OptimalFlushSize; if OnlyOptimalSize and (Bytes < OptimalFlushSize) then Break; RingBufferReadToCallback(FShared.OutputBuffer, WriteProc, Bytes); { Output buffer (partially?) flushed; unblock worker Write } SatisfyWorkerWaitOnOutput; end; { Must satisfy a waiting worker even if there was nothing to flush. (Needed to avoid deadlock in the event the main thread empties the output buffer after the worker's FillBuffer(AWrite=True) gets Bytes=0 but *before* it sets WorkerWaitingOnOutputEvent and waits on EndWaitOnOutputEvent.) } SatisfyWorkerWaitOnOutput; end; procedure TLZMACompressor.StartEncode; begin if not FEncodeStarted then begin FShared.NoMoreInput := False; FShared.ProgressKB := 0; FShared.EncodeResult := -1; RingBufferReset(FShared.InputBuffer); RingBufferReset(FShared.OutputBuffer); FLastInputWriteCount := 0; FLastProgressKB := 0; FEncodeFinished := False; FEncodeStarted := True; if not ResetEvent(FEvents.WorkerEncodeFinishedEvent) then LZMAWin32Error('StartEncode: ResetEvent'); if not SetEvent(FEvents.StartEncodeEvent) then LZMAWin32Error('StartEncode: SetEvent'); end; end; procedure TLZMACompressor.WaitForWorkerEvent; var H: array[0..4] of THandle; begin { Wait until the worker needs our attention. Separate, manual-reset events are used for progress/input/output because it allows us to see specifically what the worker is waiting for, which eases debugging and helps to avoid unnecessary wakeups. Note that the order of the handles in the array is significant: when more than one object is signaled, WaitForMultipleObjects returns the index of the array's first signaled object. The "worker unexpectedly terminated" object must be at the front to ensure it takes precedence over the Worker* events. } H[0] := FWorker.GetExitHandle; H[1] := FEvents.WorkerEncodeFinishedEvent; H[2] := FEvents.WorkerHasProgressEvent; H[3] := FEvents.WorkerWaitingOnInputEvent; H[4] := FEvents.WorkerWaitingOnOutputEvent; case WaitForMultipleObjects(5, @H, False, INFINITE) of WAIT_OBJECT_0 + 0: FWorker.UnexpectedTerminationError; WAIT_OBJECT_0 + 1: FEncodeFinished := True; WAIT_OBJECT_0 + 2, WAIT_OBJECT_0 + 3, WAIT_OBJECT_0 + 4: ; else LZMAInternalError('WaitForWorkerEvent: WaitForMultipleObjects failed'); end; end; procedure TLZMACompressor.DoCompress(const Buffer; Count: Longint); var P: ^Byte; BytesWritten: Longint; InputWriteCount: LongWord; begin StartEncode; P := @Buffer; while Count > 0 do begin if FEncodeFinished then begin if FShared.EncodeResult = SZ_ERROR_MEM then OutOfMemoryError; LZMAInternalErrorFmt('Compress: LZMA_Encode failed with code %d', [FShared.EncodeResult]); end; UpdateProgress; { Note that the progress updates that come in every ~100 ms also serve to keep the output buffer flushed well before it fills up. } FlushOutputBuffer(True); BytesWritten := RingBufferWrite(FShared.InputBuffer, P^, Count); if BytesWritten = 0 then begin { Input buffer full; unblock worker Read } SatisfyWorkerWaitOnInput; { Wait until the worker wants more input, needs output to be flushed, and/or has progress to report. All combinations are possible, so we need to handle all three before waiting again. } WaitForWorkerEvent; end else begin Dec(Count, BytesWritten); Inc(P, BytesWritten); { Unblock the worker every 64 KB so it doesn't have to wait until the entire input buffer is filled to begin/continue compressing. } InputWriteCount := FLastInputWriteCount + LongWord(BytesWritten); if InputWriteCount shr 16 <> FLastInputWriteCount shr 16 then SatisfyWorkerWaitOnInput; FLastInputWriteCount := InputWriteCount; end; end; end; procedure TLZMACompressor.DoFinish; begin StartEncode; FShared.NoMoreInput := True; while not FEncodeFinished do begin SatisfyWorkerWaitOnInput; UpdateProgress; FlushOutputBuffer(True); { Wait until the worker wants more input, needs output to be flushed, and/or has progress to report. All combinations are possible, so we need to handle all three before waiting again. } WaitForWorkerEvent; end; { Flush any remaining output in optimally-sized blocks, then flush whatever is left } FlushOutputBuffer(True); FlushOutputBuffer(False); case FShared.EncodeResult of SZ_OK: ; SZ_ERROR_MEM: OutOfMemoryError; else LZMAInternalErrorFmt('Finish: LZMA_Encode failed with code %d', [FShared.EncodeResult]); end; FEncodeStarted := False; end; { TLZMA2Compressor } constructor TLZMA2Compressor.Create(AWriteProc: TCompressorWriteProc; AProgressProc: TCompressorProgressProc; CompressionLevel: Integer; ACompressorProps: TCompressorProps); begin FUseLZMA2 := True; inherited; end; end.
32.09319
113
0.739167
c30ac54173ba84dca9f4fc10cff01e9d13a9036d
5,595
pas
Pascal
Source/Z.GBKBig.pas
PassByYou888/ZNet
8f5439ec275ee4eb5d68e00c33675e6117379fcf
[ "BSD-3-Clause" ]
24
2022-01-20T13:59:38.000Z
2022-03-25T01:11:43.000Z
Source/Z.GBKBig.pas
PassByYou888/ZNet
8f5439ec275ee4eb5d68e00c33675e6117379fcf
[ "BSD-3-Clause" ]
null
null
null
Source/Z.GBKBig.pas
PassByYou888/ZNet
8f5439ec275ee4eb5d68e00c33675e6117379fcf
[ "BSD-3-Clause" ]
5
2022-01-20T14:44:24.000Z
2022-02-13T10:07:38.000Z
{ ****************************************************************************** } { * GBK Big data * } { ****************************************************************************** } unit Z.GBKBig; {$I Z.Define.inc} interface uses Z.Status, Z.Core, Z.PascalStrings, Z.UPascalStrings, Z.MemoryStream, Z.ListEngine, Z.UnicodeMixedLib; procedure BigKeyAnalysis(const Analysis: THashVariantList); function BigKey(const s: TUPascalString; const MatchSingleWord: Boolean; const Unidentified, Completed: TListPascalString): Integer; function BigKeyValue(const s: TUPascalString; const MatchSingleWord: Boolean; const Analysis: THashVariantList): Integer; function BigKeyWord(const s: TUPascalString; const MatchSingleWord: Boolean): TPascalString; function BigWord(const s: TUPascalString; const MatchSingleWord: Boolean; const Unidentified, Completed: TListPascalString): Integer; overload; function BigWord(const s: TUPascalString; const MatchSingleWord: Boolean): TPascalString; overload; implementation uses Z.GBKMediaCenter, Z.GBK, Z.GBKVec; type TBigKeyAnalysis = class output: THashVariantList; procedure doProgress(Sender: THashStringList; Name: PSystemString; const v: SystemString); end; procedure TBigKeyAnalysis.doProgress(Sender: THashStringList; Name: PSystemString; const v: SystemString); begin umlSeparatorText(v, output, ',;'#9); end; procedure BigKeyAnalysis(const Analysis: THashVariantList); var tmp: TBigKeyAnalysis; begin tmp := TBigKeyAnalysis.Create; tmp.output := Analysis; bigKeyDict.ProgressM({$IFDEF FPC}@{$ENDIF FPC}tmp.doProgress); DisposeObject(tmp); end; function BigKey(const s: TUPascalString; const MatchSingleWord: Boolean; const Unidentified, Completed: TListPascalString): Integer; var n, tmp: TUPascalString; i, j: Integer; Successed: Boolean; begin n := GBKString(s); Result := 0; i := 1; while i <= n.L do begin Successed := False; j := umlMin(bigKeyDict.HashList.MaxNameSize, n.L - i + 1); while j > 1 do begin tmp := n.Copy(i, j); Successed := bigKeyDict.Exists(tmp); if Successed then begin Completed.Add(tmp.Text); inc(Result); inc(i, j); Break; end; dec(j); end; if not Successed then begin Successed := MatchSingleWord and bigKeyDict.Exists(n[i]); if Successed then begin Completed.Add(n[i]); inc(Result); end else begin Unidentified.Add(n[i]); end; inc(i); end; end; end; function BigKeyValue(const s: TUPascalString; const MatchSingleWord: Boolean; const Analysis: THashVariantList): Integer; var Unidentified: TListPascalString; Completed: TListPascalString; i: Integer; begin Analysis.Clear; Unidentified := TListPascalString.Create; Completed := TListPascalString.Create; Result := BigKey(s, MatchSingleWord, Unidentified, Completed); if Result > 0 then for i := 0 to Completed.Count - 1 do umlSeparatorText(bigKeyDict.GetDefaultValue(Completed[i], ''), Analysis, ',;'#9); DisposeObject([Unidentified, Completed]); end; function BigKeyWord(const s: TUPascalString; const MatchSingleWord: Boolean): TPascalString; var Unidentified: TListPascalString; Completed: TListPascalString; i: Integer; begin Result := ''; Unidentified := TListPascalString.Create; Completed := TListPascalString.Create; if BigKey(s, MatchSingleWord, Unidentified, Completed) > 0 then begin for i := 0 to Completed.Count - 1 do begin if Result.L > 0 then Result.Append(','); Result.Append(Completed[i]); end; end; DisposeObject([Unidentified, Completed]); end; function BigWord(const s: TUPascalString; const MatchSingleWord: Boolean; const Unidentified, Completed: TListPascalString): Integer; var n, tmp: TUPascalString; i, j: Integer; Successed: Boolean; begin n := GBKString(s); Result := 0; i := 1; while i <= n.L do begin Successed := False; j := umlMin(bigWordDict.MaxNameSize, n.L - i + 1); while j > 1 do begin tmp := n.Copy(i, j); Successed := bigWordDict.Exists(tmp); if Successed then begin Completed.Add(tmp.Text); inc(Result); inc(i, j); Break; end; dec(j); end; if not Successed then begin Successed := MatchSingleWord and bigWordDict.Exists(n[i]); if Successed then begin Completed.Add(n[i]); inc(Result); end else begin Unidentified.Add(n[i]); end; inc(i); end; end; end; function BigWord(const s: TUPascalString; const MatchSingleWord: Boolean): TPascalString; var Unidentified: TListPascalString; Completed: TListPascalString; i: Integer; begin Result := ''; Unidentified := TListPascalString.Create; Completed := TListPascalString.Create; if BigWord(s, MatchSingleWord, Unidentified, Completed) > 0 then begin for i := 0 to Completed.Count - 1 do begin if Result.L > 0 then Result.Append(','); Result.Append(Completed[i]); end; end; DisposeObject([Unidentified, Completed]); end; initialization end.
28.545918
143
0.615371
fc9b428c06ba458aaf50bec45de1f806dcfda11b
1,639
pas
Pascal
PosTest/Unit1.pas
edwinyzh/Delphi-64-bit-compiler-RTL-speed-up_2
1f377aed2408398d591bfef3fb3431e4534650b3
[ "Zlib" ]
null
null
null
PosTest/Unit1.pas
edwinyzh/Delphi-64-bit-compiler-RTL-speed-up_2
1f377aed2408398d591bfef3fb3431e4534650b3
[ "Zlib" ]
null
null
null
PosTest/Unit1.pas
edwinyzh/Delphi-64-bit-compiler-RTL-speed-up_2
1f377aed2408398d591bfef3fb3431e4534650b3
[ "Zlib" ]
1
2021-12-31T08:28:22.000Z
2021-12-31T08:28:22.000Z
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TForm1 = class(TForm) Memo1: TMemo; Button1: TButton; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} var SA: string = 'abcdefghilmnopqrstuvz'; SB: string = 'abcd'; SC: string = 'ghi'; SD: string = 'uvz'; WA: widestring = 'abcdefghilmnopqrstuvz'; WB: widestring = 'abcd'; WC: widestring = 'ghi'; WD: widestring = 'uvz'; RA: rawbytestring = 'abcdefghilmnopqrstuvz'; RB: rawbytestring = 'abcd'; RC: rawbytestring = 'ghi'; RD: rawbytestring = 'uvz'; procedure TForm1.Button1Click(Sender: TObject); var SZ : string; WZ : widestring; RZ : rawbytestring; begin Memo1.Lines.Add(IntToStr(Pos(SB, SA))); Memo1.Lines.Add(IntToStr(Pos(SC, SA))); Memo1.Lines.Add(IntToStr(Pos(SD, SA))); SZ:= SA + 'uvz'; Memo1.Lines.Add(IntToStr(Pos(SD, SZ, 20))); Memo1.Lines.Add(''); Memo1.Lines.Add(IntToStr(Pos(WB, WA))); Memo1.Lines.Add(IntToStr(Pos(WC, WA))); Memo1.Lines.Add(IntToStr(Pos(WD, WA))); WZ:= WA + 'uvz'; Memo1.Lines.Add(IntToStr(Pos(WD, WZ, 20))); Memo1.Lines.Add(''); Memo1.Lines.Add(IntToStr(Pos(RB, RA))); Memo1.Lines.Add(IntToStr(Pos(RC, RA))); Memo1.Lines.Add(IntToStr(Pos(RD, RA))); RZ:= RA + 'uvz'; Memo1.Lines.Add(IntToStr(Pos(RD, RZ, 20))); Memo1.Lines.Add(''); end; end.
22.452055
99
0.629042
83715c645f76d4fe1ac81ec40954817bfed0bf40
63
pas
Pascal
Test/FailureScripts/ifthenelse_expression1.pas
skolkman/dwscript
b9f99d4b8187defac3f3713e2ae0f7b83b63d516
[ "Condor-1.1" ]
79
2015-03-18T10:46:13.000Z
2022-03-17T18:05:11.000Z
Test/FailureScripts/ifthenelse_expression1.pas
skolkman/dwscript
b9f99d4b8187defac3f3713e2ae0f7b83b63d516
[ "Condor-1.1" ]
6
2016-03-29T14:39:00.000Z
2020-09-14T10:04:14.000Z
Test/FailureScripts/ifthenelse_expression1.pas
skolkman/dwscript
b9f99d4b8187defac3f3713e2ae0f7b83b63d516
[ "Condor-1.1" ]
25
2016-05-04T13:11:38.000Z
2021-09-29T13:34:31.000Z
var t1 := if 'bug' then 1 else 2; var t2 := if 2=2 1 else 2;
21
34
0.555556
fcf45e8d8cb0995fc44fa9f675260e9d08dc36ba
4,223
pas
Pascal
windows/src/ext/jedi/jcl/jcl/experts/stacktraceviewer/JclStackTraceViewerOptions.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
219
2017-06-21T03:37:03.000Z
2022-03-27T12:09:28.000Z
windows/src/ext/jedi/jcl/jcl/experts/stacktraceviewer/JclStackTraceViewerOptions.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
4,451
2017-05-29T02:52:06.000Z
2022-03-31T23:53:23.000Z
windows/src/ext/jedi/jcl/jcl/experts/stacktraceviewer/JclStackTraceViewerOptions.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
72
2017-05-26T04:08:37.000Z
2022-03-03T10:26:20.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 JclStackTraceViewerOptions.pas. } { } { The Initial Developer of the Original Code is Uwe Schuster. } { Portions created by Uwe Schuster are Copyright (C) 2009 Uwe Schuster. All rights reserved. } { } { Contributor(s): } { Uwe Schuster (uschuster) } { } {**************************************************************************************************} { } { Last modified: $Date:: $ } { Revision: $Rev:: $ } { Author: $Author:: $ } { } {**************************************************************************************************} unit JclStackTraceViewerOptions; {$I jcl.inc} interface uses Classes {$IFDEF UNITVERSIONING} , JclUnitVersioning {$ENDIF UNITVERSIONING} ; type TExceptionViewerOption = class(TPersistent) private FExpandTreeView: Boolean; FModuleVersionAsRevision: Boolean; protected procedure AssignTo(Dest: TPersistent); override; public constructor Create; property ExpandTreeView: Boolean read FExpandTreeView write FExpandTreeView; property ModuleVersionAsRevision: Boolean read FModuleVersionAsRevision write FModuleVersionAsRevision; end; {$IFDEF UNITVERSIONING} const UnitVersioning: TUnitVersionInfo = ( RCSfile: '$URL$'; Revision: '$Revision$'; Date: '$Date$'; LogPath: 'JCL\experts\stacktraceviewer'; Extra: ''; Data: nil ); {$ENDIF UNITVERSIONING} implementation { TExceptionViewerOption } constructor TExceptionViewerOption.Create; begin inherited Create; FExpandTreeView := False; FModuleVersionAsRevision := False; end; procedure TExceptionViewerOption.AssignTo(Dest: TPersistent); begin if Dest is TExceptionViewerOption then begin TExceptionViewerOption(Dest).FExpandTreeView := ExpandTreeView; TExceptionViewerOption(Dest).FModuleVersionAsRevision := ModuleVersionAsRevision; end else inherited AssignTo(Dest); end; {$IFDEF UNITVERSIONING} initialization RegisterUnitVersion(HInstance, UnitVersioning); finalization UnregisterUnitVersion(HInstance); {$ENDIF UNITVERSIONING} end.
43.536082
107
0.420081
fced64c46c4b1aad2403a64096f70f143547eaff
16,057
pas
Pascal
Components/JVCL/qrun/JvQNTEventLog.pas
sabatex/Delphi
0efbe6eb38bf8aa2bf269d1866741266e90b9cbf
[ "MIT" ]
null
null
null
Components/JVCL/qrun/JvQNTEventLog.pas
sabatex/Delphi
0efbe6eb38bf8aa2bf269d1866741266e90b9cbf
[ "MIT" ]
null
null
null
Components/JVCL/qrun/JvQNTEventLog.pas
sabatex/Delphi
0efbe6eb38bf8aa2bf269d1866741266e90b9cbf
[ "MIT" ]
1
2019-12-24T08:39:18.000Z
2019-12-24T08:39:18.000Z
{******************************************************************************} {* WARNING: JEDI VCL To CLX Converter generated unit. *} {* Manual modifications will be lost on next release. *} {******************************************************************************} {----------------------------------------------------------------------------- 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: JvEventLog.PAS, released on 2002-09-02. The Initial Developer of the Original Code is Fernando Silva [fernando dott silva att myrealbox dott com] Portions created by Fernando Silva are Copyright (C) 2002 Fernando Silva. All Rights Reserved. Contributor(s): 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: -----------------------------------------------------------------------------} // $Id: JvQNTEventLog.pas,v 1.17 2005/04/16 19:33:33 asnepvangers Exp $ unit JvQNTEventLog; {$I jvcl.inc} {$I windowsonly.inc} interface uses {$IFDEF UNITVERSIONING} JclUnitVersioning, {$ENDIF UNITVERSIONING} {$IFDEF MSWINDOWS} Windows, {$ENDIF MSWINDOWS} Classes, SysUtils, JvQComponent; type TNotifyChangeEventLog = class; TJvNTEventLogRecord = class; TJvNTEventLog = class(TJvComponent) private FLogHandle: THandle; FLog: string; FServer: string; FSource: string; FActive: Boolean; FLastError: Cardinal; FOnChange: TNotifyEvent; FNotifyThread: TNotifyChangeEventLog; FEventRecord: TJvNTEventLogRecord; procedure SetActive(Value: Boolean); procedure SetServer(const Value: string); procedure SetSource(const Value: string); procedure SetLog(const Value: string); function GetEventCount: Cardinal; procedure SeekRecord(N: Cardinal); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Open; procedure Close; procedure First; procedure Last; function Eof: Boolean; procedure Next; procedure Seek(N: Cardinal); procedure ReadEventLogs(AStrings: TStrings); property EventCount: Cardinal read GetEventCount; property EventRecord: TJvNTEventLogRecord read FEventRecord; published property Server: string read FServer write SetServer; property Source: string read FSource write SetSource; property Log: string read FLog write SetLog; property Active: Boolean read FActive write SetActive; property OnChange: TNotifyEvent read FOnChange write FOnChange; end; TNotifyChangeEventLog = class(TThread) private FEventLog: TJvNTEventLog; FEventHandle: THandle; procedure DoChange; protected procedure Execute; override; public constructor Create(AOwner: TComponent); end; TJvNTEventLogRecord = class(TObject) private FEventLog: TJvNTEventLog; FCurrentRecord: Pointer; FOwner: TComponent; function GetRecordNumber: Cardinal; function GetDateTime: TDateTime; function GetID: DWORD; function GetType: string; function GetStringCount: DWORD; function GetCategory: Cardinal; function GetSource: string; function GetComputer: string; function GetSID: PSID; function GetString(Index: Cardinal): string; function GetMessageText: string; function GetUsername: string; public constructor Create(AOwner: TComponent); property RecordNumber: Cardinal read GetRecordNumber; property DateTime: TDateTime read GetDateTime; property EventType: string read GetType; property Category: Cardinal read GetCategory; property Source: string read GetSource; property Computer: string read GetComputer; property ID: DWORD read GetID; property StringCount: DWORD read GetStringCount; property SID: PSID read GetSID; property EventString[Index: Cardinal]: string read GetString; property MessageText: string read GetMessageText; property UserName: string read GetUsername; property Owner: TComponent read FOwner; end; {$IFDEF UNITVERSIONING} const UnitVersioning: TUnitVersionInfo = ( RCSfile: '$RCSfile: JvQNTEventLog.pas,v $'; Revision: '$Revision: 1.17 $'; Date: '$Date: 2005/04/16 19:33:33 $'; LogPath: 'JVCL\run' ); {$ENDIF UNITVERSIONING} implementation uses Registry, JvQResources; const EVENTLOG_SEQUENTIAL_READ = $0001; EVENTLOG_SEEK_READ = $0002; EVENTLOG_FORWARDS_READ = $0004; EVENTLOG_BACKWARDS_READ = $0008; cEventLogBaseKey = 'SYSTEM\CurrentControlSet\Services\EventLog'; type PEventLogRecord = ^TEventLogRecord; TEventLogRecord = packed record Length: DWORD; // Length of full record Reserved: DWORD; // Used by the service RecordNumber: DWORD; // Absolute record number TimeGenerated: DWORD; // Seconds since 1-1-1970 TimeWritten: DWORD; // Seconds since 1-1-1970 EventID: DWORD; EventType: WORD; NumStrings: WORD; EventCategory: WORD; ReservedFlags: WORD; // For Use with paired events (auditing) ClosingRecordNumber: DWORD; // For Use with paired events (auditing) StringOffset: DWORD; // Offset from beginning of record UserSidLength: DWORD; UserSidOffset: DWORD; DataLength: DWORD; DataOffset: DWORD; // Offset from beginning of record end; //=== { TJvNTEventLog } ====================================================== constructor TJvNTEventLog.Create(AOwner: TComponent); begin inherited Create(AOwner); FLog := ''; FSource := ''; FOnChange := nil; FNotifyThread := nil; FEventRecord := TJvNTEventLogRecord.Create(Self); end; destructor TJvNTEventLog.Destroy; begin Close; FEventRecord.Free; inherited Destroy; end; procedure TJvNTEventLog.SetActive(Value: Boolean); begin if Value <> FActive then if csDesigning in ComponentState then FActive := Value else if Value then Open else Close; end; procedure TJvNTEventLog.SetServer(const Value: string); var OldActive: Boolean; begin if FServer <> Value then begin OldActive := Active; Active := False; FServer := Value; Active := OldActive; end end; procedure TJvNTEventLog.SetSource(const Value: string); var OldActive: Boolean; begin if FSource <> Value then begin OldActive := Active; Active := False; FSource := Value; Active := OldActive; end end; procedure TJvNTEventLog.SetLog(const Value: string); var OldActive: Boolean; begin if FLog <> Value then begin OldActive := Active; Active := False; FLog := Value; Active := OldActive; end end; function TJvNTEventLog.GetEventCount: Cardinal; begin if Active then GetNumberOfEventLogRecords(FLogHandle, Result) else Result := 0; end; procedure TJvNTEventLog.Open; begin if Source <> '' then begin FLogHandle := OpenEventLog(PChar(Server), PChar(Source)); if FLogHandle = 0 then RaiseLastOSError; FNotifyThread := TNotifyChangeEventLog.Create(Self); FActive := True; end; end; procedure TJvNTEventLog.Close; begin if FLogHandle <> 0 then begin FNotifyThread.Terminate; CloseEventLog(FLogHandle); FLogHandle := 0 end; ReallocMem(FEventRecord.FCurrentRecord, 0); FActive := False; end; procedure TJvNTEventLog.First; begin SeekRecord(0); end; procedure TJvNTEventLog.Last; begin SeekRecord(GetEventCount - 1); end; function TJvNTEventLog.Eof: Boolean; begin Result := (EventRecord.FCurrentRecord = nil) or (EventRecord.RecordNumber = GetEventCount) or (FLastError = ERROR_HANDLE_EOF); end; procedure TJvNTEventLog.Next; var BytesRead, BytesNeeded, Flags: DWORD; Dummy: Char; begin Flags := EVENTLOG_SEQUENTIAL_READ; Flags := Flags or EVENTLOG_FORWARDS_READ; ReadEventLog(FLogHandle, Flags, 0, @Dummy, 0, BytesRead, BytesNeeded); FLastError := GetLastError; if FLastError = ERROR_INSUFFICIENT_BUFFER then begin ReallocMem(FEventRecord.FCurrentRecord, BytesNeeded); if not ReadEventLog(FLogHandle, Flags, 0, FEventRecord.FCurrentRecord, BytesNeeded, BytesRead, BytesNeeded) then RaiseLastOSError; end else if FLastError <> ERROR_HANDLE_EOF then RaiseLastOSError; end; procedure TJvNTEventLog.SeekRecord(N: Cardinal); var Offset, Flags: DWORD; BytesRead, BytesNeeded: Cardinal; Dummy: Char; RecNo: Integer; begin GetOldestEventLogRecord(FLogHandle, Offset); RecNo := N + Offset; Flags := EVENTLOG_SEEK_READ; Flags := Flags or EVENTLOG_FORWARDS_READ; ReadEventLog(FLogHandle, Flags, RecNo, @Dummy, 0, BytesRead, BytesNeeded); FLastError := GetLastError; if FLastError = ERROR_INSUFFICIENT_BUFFER then begin ReallocMem(FEventRecord.FCurrentRecord, BytesNeeded); if not ReadEventLog(FLogHandle, Flags, RecNo, FEventRecord.FCurrentRecord, BytesNeeded, BytesRead, BytesNeeded) then RaiseLastOSError; end else if FLastError <> ERROR_HANDLE_EOF then RaiseLastOSError; end; procedure TJvNTEventLog.Seek(N: Cardinal); begin if N <> FEventRecord.RecordNumber then SeekRecord(N); end; procedure TJvNTEventLog.ReadEventLogs(AStrings: TStrings); begin with TRegistry.Create do begin AStrings.BeginUpdate; try RootKey := HKEY_LOCAL_MACHINE; OpenKey(cEventLogBaseKey, False); GetKeyNames(AStrings); finally Free; AStrings.EndUpdate; end; end; end; //=== { TNotifyChangeEventLog } ============================================== constructor TNotifyChangeEventLog.Create(AOwner: TComponent); begin inherited Create(True); // Create thread suspended FreeOnTerminate := True; // Thread Free Itself when terminated // initialize system events FEventLog := TJvNTEventLog(AOwner); FEventHandle := CreateEvent(nil, True, False, nil); NotifyChangeEventLog(FEventLog.FLogHandle, FEventHandle); Suspended := False; // Continue the thread end; procedure TNotifyChangeEventLog.DoChange; begin if Assigned(FEventLog.FOnChange) then FEventLog.FOnChange(FEventLog); end; procedure TNotifyChangeEventLog.Execute; var LResult: DWORD; begin // (rom) secure thread against exceptions try while not Terminated do begin // reset event signal, so we can get it again ResetEvent(FEventHandle); // wait for event to happen LResult := WaitForSingleObject(FEventHandle, INFINITE); // check event Result case LResult of WAIT_OBJECT_0: Synchronize(DoChange); else Synchronize(DoChange); end; end; except end; end; //=== { TJvNTEventLogRecord } ================================================ constructor TJvNTEventLogRecord.Create(AOwner: TComponent); begin // (rom) added inherited Create inherited Create; FEventLog := TJvNTEventLog(AOwner); FCurrentRecord := nil; FOwner := AOwner; end; function TJvNTEventLogRecord.GetRecordNumber: Cardinal; begin Result := PEventLogRecord(FCurrentRecord)^.RecordNumber; end; function TJvNTEventLogRecord.GetMessageText: string; var MessagePath: string; Count, I: Integer; P: PChar; Args, PArgs: ^PChar; St: string; function FormatMessageFrom(const DllName: string): Boolean; var DllModule: THandle; Buffer: array [0..2047] of Char; FullDLLName: array [0..MAX_PATH] of Char; begin Result := False; ExpandEnvironmentStrings(PChar(DllName), FullDLLName, MAX_PATH); DllModule := LoadLibraryEx(FullDLLName, 0, LOAD_LIBRARY_AS_DATAFILE); if DllModule <> 0 then try // (rom) memory leak fixed if FormatMessage( FORMAT_MESSAGE_FROM_HMODULE or FORMAT_MESSAGE_ARGUMENT_ARRAY, Pointer(DllModule), ID, 0, Buffer, SizeOf(Buffer), Args) > 0 then begin Buffer[StrLen(Buffer) - 2] := #0; St := Buffer; Result := True; end finally FreeLibrary(DllModule); end end; begin St := ''; Count := StringCount; GetMem(Args, Count * SizeOf(PChar)); try PArgs := Args; P := PEventLogRecord(FCurrentRecord)^.StringOffset + PChar(FCurrentRecord); for I := 0 to Count - 1 do begin PArgs^ := P; Inc(P, lstrlen(P) + 1); Inc(PArgs); end; with TRegistry.Create do begin RootKey := HKEY_LOCAL_MACHINE; OpenKey(Format('%s\%s\%s', [cEventLogBaseKey, FEventLog.Log, Source]), False); {rw} // OpenKey(Format('SYSTEM\CurrentControlSet\Services\EventLog\%s\%s', [FEventLog.Log, FEventLog.Source]), False); MessagePath := ReadString('EventMessageFile'); repeat I := Pos(';', MessagePath); if I <> 0 then begin if FormatMessageFrom(Copy(MessagePath, 1, I - 1 )) then {rw} // if FormatMessageFrom(Copy(MessagePath, 1, I)) then Break; MessagePath := Copy(MessagePath, I + 1, MaxInt); {rw} // MessagePath := Copy(MessagePath, I, MaxInt); end else FormatMessageFrom(MessagePath); until I = 0; end finally FreeMem(Args) end; Result := St; end; function TJvNTEventLogRecord.GetUsername: string; var UserName: array [0..256] of Char; UserNameLen: Cardinal; DomainName: array [0..256] of Char; DomainNameLen: Cardinal; Use: SID_NAME_USE; begin Result := ''; UserNameLen := SizeOf(UserName); DomainNameLen := SizeOf(DomainName); if LookupAccountSID(nil, SID, UserName, UserNameLen, DomainName, DomainNameLen, Use) then Result := string(DomainName) + '\' + string(UserName); end; function TJvNTEventLogRecord.GetType: string; begin case PEventLogRecord(FCurrentRecord)^.EventType of EVENTLOG_ERROR_TYPE: Result := RsLogError; EVENTLOG_WARNING_TYPE: Result := RsLogWarning; EVENTLOG_INFORMATION_TYPE: Result := RsLogInformation; EVENTLOG_AUDIT_SUCCESS: Result := RsLogSuccessAudit; EVENTLOG_AUDIT_FAILURE: Result := RsLogFailureAudit; else Result := ''; end; end; function TJvNTEventLogRecord.GetSource: string; begin Result := PChar(FCurrentRecord) + SizeOf(TEventLogRecord); end; function TJvNTEventLogRecord.GetComputer: string; var P: PChar; begin P := PChar(FCurrentRecord) + SizeOf(TEventLogRecord); Result := P + StrLen(P) + 1; end; function TJvNTEventLogRecord.GetID: DWORD; begin Result := PEventLogRecord(FCurrentRecord)^.EventID; end; function TJvNTEventLogRecord.GetStringCount: DWORD; begin Result := PEventLogRecord(FCurrentRecord)^.NumStrings; end; function TJvNTEventLogRecord.GetCategory: Cardinal; begin Result := PEventLogRecord(FCurrentRecord)^.EventCategory; end; function TJvNTEventLogRecord.GetSID: PSID; begin Result := PSID(PChar(FCurrentRecord) + PEventLogRecord(FCurrentRecord)^.UserSidOffset); end; function TJvNTEventLogRecord.GetString(Index: Cardinal): string; var P: PChar; begin Result := ''; if Index < StringCount then begin P := PChar(FCurrentRecord) + PEventLogRecord(FCurrentRecord)^.StringOffset; while Index > 0 do begin Inc(P, StrLen(P) + 1); Dec(Index); end; Result := StrPas(P); end; end; function TJvNTEventLogRecord.GetDateTime: TDateTime; const StartPoint: TDateTime = 25569.0; // January 1, 1970 00:00:00 begin // Result := IncSecond(StartPoint, PEventLogRecord(FCurrentRecord)^.TimeGenerated); // Result := IncSecond(StartPoint, PEventLogRecord(FCurrentRecord)^.TimeWritten); Result := ((StartPoint * 86400.0) + PEventLogRecord(FCurrentRecord)^.TimeWritten) / 86400.0; end; {$IFDEF UNITVERSIONING} initialization RegisterUnitVersion(HInstance, UnitVersioning); finalization UnregisterUnitVersion(HInstance); {$ENDIF UNITVERSIONING} end.
26.628524
120
0.693716
fcb069f6664ddb8b19287689482a0399eb90dd85
3,466
pas
Pascal
windows/src/ext/jedi/jvcl/tests/Globus/design/JvgReportParamEditorForm.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
219
2017-06-21T03:37:03.000Z
2022-03-27T12:09:28.000Z
windows/src/ext/jedi/jvcl/tests/Globus/design/JvgReportParamEditorForm.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/Globus/design/JvgReportParamEditorForm.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: JvgReportParamEditorForm.PAS, released on 2003-01-15. The Initial Developer of the Original Code is Andrey V. Chudin, [chudin@yandex.ru] Portions created by Andrey V. Chudin are Copyright (C) 2003 Andrey V. Chudin. All Rights Reserved. Contributor(s): Michael Beck [mbeck@bigfoot.com]. Last Modified: 2003-01-15 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 JvgReportParamEditorForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, Mask; type TJvgReportParamEditor = class(TForm) Panel1: TPanel; Panel2: TPanel; BitBtn2: TBitBtn; BitBtn1: TBitBtn; rgParameterType: TRadioGroup; Notebook: TNotebook; gbTextMask: TGroupBox; Label1: TLabel; Label2: TLabel; meTestMask: TMaskEdit; eTextMask: TEdit; gbRadioItems: TGroupBox; Label5: TLabel; lbRadioItems: TListBox; pbAddItem: TButton; pbDeleteItem: TButton; eItemToAdd: TEdit; pbInsertItem: TButton; gbCheckbox: TGroupBox; Label7: TLabel; eCheckBox: TEdit; gbDataSource: TGroupBox; Label3: TLabel; Label4: TLabel; eTableName: TEdit; eFieldName: TEdit; procedure rgParameterTypeClick(Sender: TObject); procedure pbAddItemClick(Sender: TObject); procedure lbRadioItemsClick(Sender: TObject); procedure eTextMaskChange(Sender: TObject); procedure pbDeleteItemClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var ReportParamEditor: TJvgReportParamEditor; implementation {$R *.DFM} {procedure SetEnabledState( WC: TWinControl; State: boolean ); var i: integer; begin for i:=0 to WC.ControlCount-1 do WC.Controls[i].Enabled := State; end;} procedure TJvgReportParamEditor.rgParameterTypeClick(Sender: TObject); begin Notebook.PageIndex := rgParameterType.ItemIndex; end; procedure TJvgReportParamEditor.pbAddItemClick(Sender: TObject); begin eItemToAdd.Text := Trim(eItemToAdd.Text); if length(eItemToAdd.Text) > 0 then if TButton(Sender).Tag = 0 then lbRadioItems.Items.Append(eItemToAdd.Text) else if lbRadioItems.ItemIndex <> -1 then lbRadioItems.Items.Insert(lbRadioItems.ItemIndex, eItemToAdd.Text); end; procedure TJvgReportParamEditor.lbRadioItemsClick(Sender: TObject); begin pbDeleteItem.Enabled := lbRadioItems.ItemIndex <> -1; pbInsertItem.Enabled := pbDeleteItem.Enabled; end; procedure TJvgReportParamEditor.eTextMaskChange(Sender: TObject); begin meTestMask.EditMask := eTextMask.Text; end; procedure TJvgReportParamEditor.pbDeleteItemClick(Sender: TObject); begin lbRadioItems.Items.Delete(lbRadioItems.ItemIndex); end; end.
28.178862
86
0.719561
fc621741f80bd442dca857a355d3dabe2936976e
438
pas
Pascal
CAT/tests/08. types/pointers/pointers_proc_explicit_2.pas
SkliarOleksandr/NextPascal
4dc26abba6613f64c0e6b5864b3348711eb9617a
[ "Apache-2.0" ]
19
2018-10-22T23:45:31.000Z
2021-05-16T00:06:49.000Z
CAT/tests/08. types/pointers/pointers_proc_explicit_2.pas
SkliarOleksandr/NextPascal
4dc26abba6613f64c0e6b5864b3348711eb9617a
[ "Apache-2.0" ]
1
2019-06-01T06:17:08.000Z
2019-12-28T10:27:42.000Z
CAT/tests/08. types/pointers/pointers_proc_explicit_2.pas
SkliarOleksandr/NextPascal
4dc26abba6613f64c0e6b5864b3348711eb9617a
[ "Apache-2.0" ]
6
2018-08-30T05:16:21.000Z
2021-05-12T20:25:43.000Z
unit pointers_proc_explicit_2; interface implementation type TProc = procedure(a, b: Int32; const s: string); var P: Pointer; GA, GB: Int32; GS: string; procedure SetG(a, b: Int32; const s: string); begin GA := a; GB := b; GS := s; end; procedure Test; begin P := @SetG; TProc(P)(44, 33, 'str'); end; initialization Test(); finalization Assert(GA = 44); Assert(GB = 33); Assert(GS = 'str'); end.
12.166667
50
0.611872
4789fa714a6c04045dd1962966e7d96af14085cd
29,675
pas
Pascal
Components/TNT/Source/TntExtCtrls.pas
jaksco/cubicexplorer
7bf2513700477d753fd8ea1c6226ddab0175df91
[ "Condor-1.1" ]
1
2021-09-23T17:32:49.000Z
2021-09-23T17:32:49.000Z
Components/TNT/Source/TntExtCtrls.pas
jaksco/cubicexplorer
7bf2513700477d753fd8ea1c6226ddab0175df91
[ "Condor-1.1" ]
null
null
null
Components/TNT/Source/TntExtCtrls.pas
jaksco/cubicexplorer
7bf2513700477d753fd8ea1c6226ddab0175df91
[ "Condor-1.1" ]
null
null
null
{*****************************************************************************} { } { Tnt Delphi Unicode Controls } { http://www.tntware.com/delphicontrols/unicode/ } { Version: 2.3.0 } { } { Copyright (c) 2002-2007, Troy Wolbrink (troy.wolbrink@tntware.com) } { } {*****************************************************************************} unit TntExtCtrls; {$INCLUDE TntCompilers.inc} interface uses Classes, Messages, Controls, ExtCtrls, TntClasses, TntControls, TntStdCtrls, TntGraphics; type {TNT-WARN TShape} TTntShape = class(TShape{TNT-ALLOW TShape}) private function GetHint: WideString; procedure SetHint(const Value: WideString); function IsHintStored: Boolean; procedure CMHintShow(var Message: TMessage); message CM_HINTSHOW; protected procedure DefineProperties(Filer: TFiler); override; function GetActionLinkClass: TControlActionLinkClass; override; procedure ActionChange(Sender: TObject; CheckDefaults: Boolean); override; published property Hint: WideString read GetHint write SetHint stored IsHintStored; end; {TNT-WARN TPaintBox} TTntPaintBox = class(TPaintBox{TNT-ALLOW TPaintBox}) private function GetHint: WideString; procedure SetHint(const Value: WideString); function IsHintStored: Boolean; procedure CMHintShow(var Message: TMessage); message CM_HINTSHOW; protected procedure DefineProperties(Filer: TFiler); override; function GetActionLinkClass: TControlActionLinkClass; override; procedure ActionChange(Sender: TObject; CheckDefaults: Boolean); override; published property Hint: WideString read GetHint write SetHint stored IsHintStored; end; {TNT-WARN TImage} TTntImage = class(TImage{TNT-ALLOW TImage}) private function GetHint: WideString; procedure SetHint(const Value: WideString); function IsHintStored: Boolean; procedure CMHintShow(var Message: TMessage); message CM_HINTSHOW; function GetPicture: TTntPicture; procedure SetPicture(const Value: TTntPicture); protected procedure DefineProperties(Filer: TFiler); override; function GetActionLinkClass: TControlActionLinkClass; override; procedure ActionChange(Sender: TObject; CheckDefaults: Boolean); override; public constructor Create(AOwner: TComponent); override; published property Hint: WideString read GetHint write SetHint stored IsHintStored; property Picture: TTntPicture read GetPicture write SetPicture; end; {TNT-WARN TBevel} TTntBevel = class(TBevel{TNT-ALLOW TBevel}) private function GetHint: WideString; procedure SetHint(const Value: WideString); function IsHintStored: Boolean; procedure CMHintShow(var Message: TMessage); message CM_HINTSHOW; protected procedure DefineProperties(Filer: TFiler); override; function GetActionLinkClass: TControlActionLinkClass; override; procedure ActionChange(Sender: TObject; CheckDefaults: Boolean); override; published property Hint: WideString read GetHint write SetHint stored IsHintStored; end; {TNT-WARN TCustomPanel} TTntCustomPanel = class(TCustomPanel{TNT-ALLOW TCustomPanel}) private function GetCaption: TWideCaption; procedure SetCaption(const Value: TWideCaption); function GetHint: WideString; procedure SetHint(const Value: WideString); function IsCaptionStored: Boolean; function IsHintStored: Boolean; protected procedure Paint; override; procedure CreateWindowHandle(const Params: TCreateParams); override; procedure DefineProperties(Filer: TFiler); override; function GetActionLinkClass: TControlActionLinkClass; override; procedure ActionChange(Sender: TObject; CheckDefaults: Boolean); override; property Caption: TWideCaption read GetCaption write SetCaption stored IsCaptionStored; published property Hint: WideString read GetHint write SetHint stored IsHintStored; end; {TNT-WARN TPanel} TTntPanel = class(TTntCustomPanel) public property DockManager; published property Align; property Alignment; property Anchors; property AutoSize; property BevelEdges; property BevelInner; property BevelKind; property BevelOuter; property BevelWidth; property BiDiMode; property BorderWidth; property BorderStyle; property Caption; property Color; property Constraints; property Ctl3D; property UseDockManager default True; property DockSite; property DragCursor; property DragKind; property DragMode; property Enabled; property FullRepaint; property Font; property Locked; {$IFDEF COMPILER_10_UP} property Padding; {$ENDIF} property ParentBiDiMode; {$IFDEF COMPILER_7_UP} property ParentBackground; {$ENDIF} property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; {$IFDEF COMPILER_9_UP} property VerticalAlignment; {$ENDIF} property Visible; {$IFDEF COMPILER_9_UP} property OnAlignInsertBefore; property OnAlignPosition; {$ENDIF} property OnCanResize; property OnClick; property OnConstrainedResize; property OnContextPopup; property OnDockDrop; property OnDockOver; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnGetSiteInfo; {$IFDEF COMPILER_9_UP} property OnMouseActivate; {$ENDIF} property OnMouseDown; {$IFDEF COMPILER_10_UP} property OnMouseEnter; property OnMouseLeave; {$ENDIF} property OnMouseMove; property OnMouseUp; property OnResize; property OnStartDock; property OnStartDrag; property OnUnDock; end; {TNT-WARN TCustomControlBar} TTntCustomControlBar = class(TCustomControlBar{TNT-ALLOW TCustomControlBar}) private function IsHintStored: Boolean; function GetHint: WideString; procedure SetHint(const Value: WideString); protected procedure CreateWindowHandle(const Params: TCreateParams); override; procedure DefineProperties(Filer: TFiler); override; function GetActionLinkClass: TControlActionLinkClass; override; procedure ActionChange(Sender: TObject; CheckDefaults: Boolean); override; published property Hint: WideString read GetHint write SetHint stored IsHintStored; end; {TNT-WARN TControlBar} TTntControlBar = class(TTntCustomControlBar) public property Canvas; published property Align; property Anchors; property AutoDock; property AutoDrag; property AutoSize; property BevelEdges; property BevelInner; property BevelOuter; property BevelKind; property BevelWidth; property BorderWidth; property Color {$IFDEF COMPILER_7_UP} nodefault {$ENDIF}; property Constraints; {$IFDEF COMPILER_10_UP} property CornerEdge; {$ENDIF} property DockSite; property DragCursor; property DragKind; property DragMode; {$IFDEF COMPILER_10_UP} property DrawingStyle; {$ENDIF} property Enabled; {$IFDEF COMPILER_10_UP} property GradientDirection; property GradientEndColor; property GradientStartColor; {$ENDIF} {$IFDEF COMPILER_7_UP} property ParentBackground default True; {$ENDIF} property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property Picture; property PopupMenu; property RowSize; property RowSnap; property ShowHint; property TabOrder; property TabStop; property Visible; {$IFDEF COMPILER_9_UP} property OnAlignInsertBefore; property OnAlignPosition; {$ENDIF} property OnBandDrag; property OnBandInfo; property OnBandMove; property OnBandPaint; {$IFDEF COMPILER_9_UP} property OnBeginBandMove; property OnEndBandMove; {$ENDIF} property OnCanResize; property OnClick; property OnConstrainedResize; property OnContextPopup; property OnDockDrop; property OnDockOver; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnGetSiteInfo; {$IFDEF COMPILER_9_UP} property OnMouseActivate; {$ENDIF} property OnMouseDown; {$IFDEF COMPILER_10_UP} property OnMouseEnter; property OnMouseLeave; {$ENDIF} property OnMouseMove; property OnMouseUp; property OnPaint; property OnResize; property OnStartDock; property OnStartDrag; property OnUnDock; end; {TNT-WARN TCustomRadioGroup} TTntCustomRadioGroup = class(TTntCustomGroupBox) private FButtons: TList; FItems: TTntStrings; FItemIndex: Integer; FColumns: Integer; FReading: Boolean; FUpdating: Boolean; function GetButtons(Index: Integer): TTntRadioButton; procedure ArrangeButtons; procedure ButtonClick(Sender: TObject); procedure ItemsChange(Sender: TObject); procedure SetButtonCount(Value: Integer); procedure SetColumns(Value: Integer); procedure SetItemIndex(Value: Integer); procedure SetItems(Value: TTntStrings); procedure UpdateButtons; procedure CMEnabledChanged(var Message: TMessage); message CM_ENABLEDCHANGED; procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED; procedure WMSize(var Message: TWMSize); message WM_SIZE; protected procedure Loaded; override; procedure ReadState(Reader: TReader); override; function CanModify: Boolean; virtual; procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override; property Columns: Integer read FColumns write SetColumns default 1; property ItemIndex: Integer read FItemIndex write SetItemIndex default -1; property Items: TTntStrings read FItems write SetItems; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure FlipChildren(AllLevels: Boolean); override; property Buttons[Index: Integer]: TTntRadioButton read GetButtons; end; {TNT-WARN TRadioGroup} TTntRadioGroup = class(TTntCustomRadioGroup) published property Align; property Anchors; property BiDiMode; property Caption; property Color; property Columns; property Ctl3D; property DragCursor; property DragKind; property DragMode; property Enabled; property Font; property ItemIndex; property Items; property Constraints; property ParentBiDiMode; {$IFDEF COMPILER_7_UP} property ParentBackground default True; {$ENDIF} property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; property Visible; property OnClick; property OnContextPopup; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnStartDock; property OnStartDrag; end; {TNT-WARN TSplitter} TTntSplitter = class(TSplitter{TNT-ALLOW TSplitter}) private function GetHint: WideString; procedure SetHint(const Value: WideString); function IsHintStored: Boolean; procedure CMHintShow(var Message: TMessage); message CM_HINTSHOW; protected procedure DefineProperties(Filer: TFiler); override; function GetActionLinkClass: TControlActionLinkClass; override; procedure ActionChange(Sender: TObject; CheckDefaults: Boolean); override; published property Hint: WideString read GetHint write SetHint stored IsHintStored; end; implementation uses Windows, Graphics, Forms, {$IFDEF THEME_7_UP} Themes, {$ENDIF} TntSysUtils, TntWindows, TntActnList; { TTntShape } procedure TTntShape.DefineProperties(Filer: TFiler); begin inherited; TntPersistent_AfterInherited_DefineProperties(Filer, Self); end; function TTntShape.IsHintStored: Boolean; begin Result := TntControl_IsHintStored(Self) end; function TTntShape.GetHint: WideString; begin Result := TntControl_GetHint(Self) end; procedure TTntShape.SetHint(const Value: WideString); begin TntControl_SetHint(Self, Value); end; procedure TTntShape.CMHintShow(var Message: TMessage); begin ProcessCMHintShowMsg(Message); inherited; end; procedure TTntShape.ActionChange(Sender: TObject; CheckDefaults: Boolean); begin TntControl_BeforeInherited_ActionChange(Self, Sender, CheckDefaults); inherited; end; function TTntShape.GetActionLinkClass: TControlActionLinkClass; begin Result := TntControl_GetActionLinkClass(Self, inherited GetActionLinkClass); end; { TTntPaintBox } procedure TTntPaintBox.DefineProperties(Filer: TFiler); begin inherited; TntPersistent_AfterInherited_DefineProperties(Filer, Self); end; function TTntPaintBox.IsHintStored: Boolean; begin Result := TntControl_IsHintStored(Self) end; function TTntPaintBox.GetHint: WideString; begin Result := TntControl_GetHint(Self) end; procedure TTntPaintBox.SetHint(const Value: WideString); begin TntControl_SetHint(Self, Value); end; procedure TTntPaintBox.CMHintShow(var Message: TMessage); begin ProcessCMHintShowMsg(Message); inherited; end; procedure TTntPaintBox.ActionChange(Sender: TObject; CheckDefaults: Boolean); begin TntControl_BeforeInherited_ActionChange(Self, Sender, CheckDefaults); inherited; end; function TTntPaintBox.GetActionLinkClass: TControlActionLinkClass; begin Result := TntControl_GetActionLinkClass(Self, inherited GetActionLinkClass); end; type {$IFDEF COMPILER_6} // verified against VCL source in Delphi 6 and BCB 6 THackImage = class(TGraphicControl) protected FPicture: TPicture{TNT-ALLOW TPicture}; end; {$ENDIF} {$IFDEF DELPHI_7} // verified against VCL source in Delphi 7 THackImage = class(TGraphicControl) protected FPicture: TPicture{TNT-ALLOW TPicture}; end; {$ENDIF} {$IFDEF DELPHI_9} // verified against VCL source in Delphi 9 THackImage = class(TGraphicControl) private FPicture: TPicture{TNT-ALLOW TPicture}; end; {$ENDIF} {$IFDEF DELPHI_10} // verified against VCL source in Delphi 10 THackImage = class(TGraphicControl) private FPicture: TPicture{TNT-ALLOW TPicture}; end; {$ENDIF} { TTntImage } constructor TTntImage.Create(AOwner: TComponent); var OldPicture: TPicture{TNT-ALLOW TPicture}; begin inherited; OldPicture := THackImage(Self).FPicture; THackImage(Self).FPicture := TTntPicture.Create; Picture.OnChange := OldPicture.OnChange; Picture.OnProgress := OldPicture.OnProgress; OldPicture.Free; end; function TTntImage.GetPicture: TTntPicture; begin Result := inherited Picture as TTntPicture; end; procedure TTntImage.SetPicture(const Value: TTntPicture); begin inherited Picture := Value; end; procedure TTntImage.DefineProperties(Filer: TFiler); begin inherited; TntPersistent_AfterInherited_DefineProperties(Filer, Self); end; function TTntImage.IsHintStored: Boolean; begin Result := TntControl_IsHintStored(Self) end; function TTntImage.GetHint: WideString; begin Result := TntControl_GetHint(Self) end; procedure TTntImage.SetHint(const Value: WideString); begin TntControl_SetHint(Self, Value); end; procedure TTntImage.CMHintShow(var Message: TMessage); begin ProcessCMHintShowMsg(Message); inherited; end; procedure TTntImage.ActionChange(Sender: TObject; CheckDefaults: Boolean); begin TntControl_BeforeInherited_ActionChange(Self, Sender, CheckDefaults); inherited; end; function TTntImage.GetActionLinkClass: TControlActionLinkClass; begin Result := TntControl_GetActionLinkClass(Self, inherited GetActionLinkClass); end; { TTntBevel } procedure TTntBevel.DefineProperties(Filer: TFiler); begin inherited; TntPersistent_AfterInherited_DefineProperties(Filer, Self); end; function TTntBevel.IsHintStored: Boolean; begin Result := TntControl_IsHintStored(Self) end; function TTntBevel.GetHint: WideString; begin Result := TntControl_GetHint(Self) end; procedure TTntBevel.SetHint(const Value: WideString); begin TntControl_SetHint(Self, Value); end; procedure TTntBevel.CMHintShow(var Message: TMessage); begin ProcessCMHintShowMsg(Message); inherited; end; procedure TTntBevel.ActionChange(Sender: TObject; CheckDefaults: Boolean); begin TntControl_BeforeInherited_ActionChange(Self, Sender, CheckDefaults); inherited; end; function TTntBevel.GetActionLinkClass: TControlActionLinkClass; begin Result := TntControl_GetActionLinkClass(Self, inherited GetActionLinkClass); end; { TTntCustomPanel } procedure TTntCustomPanel.CreateWindowHandle(const Params: TCreateParams); begin CreateUnicodeHandle(Self, Params, ''); end; procedure TTntCustomPanel.DefineProperties(Filer: TFiler); begin inherited; TntPersistent_AfterInherited_DefineProperties(Filer, Self); end; function TTntCustomPanel.IsCaptionStored: Boolean; begin Result := TntControl_IsCaptionStored(Self); end; function TTntCustomPanel.GetCaption: TWideCaption; begin Result := TntControl_GetText(Self) end; procedure TTntCustomPanel.SetCaption(const Value: TWideCaption); begin TntControl_SetText(Self, Value); end; procedure TTntCustomPanel.Paint; const Alignments: array[TAlignment] of Longint = (DT_LEFT, DT_RIGHT, DT_CENTER); var Rect: TRect; TopColor, BottomColor: TColor; FontHeight: Integer; Flags: Longint; procedure AdjustColors(Bevel: TPanelBevel); begin TopColor := clBtnHighlight; if Bevel = bvLowered then TopColor := clBtnShadow; BottomColor := clBtnShadow; if Bevel = bvLowered then BottomColor := clBtnHighlight; end; begin if (not Win32PlatformIsUnicode) then inherited else begin Rect := GetClientRect; if BevelOuter <> bvNone then begin AdjustColors(BevelOuter); Frame3D(Canvas, Rect, TopColor, BottomColor, BevelWidth); end; {$IFDEF THEME_7_UP} if ThemeServices.ThemesEnabled {$IFDEF COMPILER_7_UP} and ParentBackground {$ENDIF} then InflateRect(Rect, -BorderWidth, -BorderWidth) else {$ENDIF} begin Frame3D(Canvas, Rect, Color, Color, BorderWidth); end; if BevelInner <> bvNone then begin AdjustColors(BevelInner); Frame3D(Canvas, Rect, TopColor, BottomColor, BevelWidth); end; with Canvas do begin {$IFDEF THEME_7_UP} if not ThemeServices.ThemesEnabled {$IFDEF COMPILER_7_UP} or not ParentBackground {$ENDIF} then {$ENDIF} begin Brush.Color := Color; FillRect(Rect); end; Brush.Style := bsClear; Font := Self.Font; FontHeight := WideCanvasTextHeight(Canvas, 'W'); with Rect do begin Top := ((Bottom + Top) - FontHeight) div 2; Bottom := Top + FontHeight; end; Flags := DT_EXPANDTABS or DT_VCENTER or Alignments[Alignment]; Flags := DrawTextBiDiModeFlags(Flags); Tnt_DrawTextW(Handle, PWideChar(Caption), -1, Rect, Flags); end; end; end; function TTntCustomPanel.IsHintStored: Boolean; begin Result := TntControl_IsHintStored(Self) end; function TTntCustomPanel.GetHint: WideString; begin Result := TntControl_GetHint(Self); end; procedure TTntCustomPanel.SetHint(const Value: WideString); begin TntControl_SetHint(Self, Value); end; procedure TTntCustomPanel.ActionChange(Sender: TObject; CheckDefaults: Boolean); begin TntControl_BeforeInherited_ActionChange(Self, Sender, CheckDefaults); inherited; end; function TTntCustomPanel.GetActionLinkClass: TControlActionLinkClass; begin Result := TntControl_GetActionLinkClass(Self, inherited GetActionLinkClass); end; { TTntCustomControlBar } procedure TTntCustomControlBar.CreateWindowHandle(const Params: TCreateParams); begin CreateUnicodeHandle(Self, Params, ''); end; procedure TTntCustomControlBar.DefineProperties(Filer: TFiler); begin inherited; TntPersistent_AfterInherited_DefineProperties(Filer, Self); end; function TTntCustomControlBar.IsHintStored: Boolean; begin Result := TntControl_IsHintStored(Self); end; function TTntCustomControlBar.GetHint: WideString; begin Result := TntControl_GetHint(Self); end; procedure TTntCustomControlBar.SetHint(const Value: WideString); begin TntControl_SetHint(Self, Value); end; procedure TTntCustomControlBar.ActionChange(Sender: TObject; CheckDefaults: Boolean); begin TntControl_BeforeInherited_ActionChange(Self, Sender, CheckDefaults); inherited; end; function TTntCustomControlBar.GetActionLinkClass: TControlActionLinkClass; begin Result := TntControl_GetActionLinkClass(Self, inherited GetActionLinkClass); end; { TTntGroupButton } type TTntGroupButton = class(TTntRadioButton) private FInClick: Boolean; procedure CNCommand(var Message: TWMCommand); message CN_COMMAND; protected procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure KeyPress(var Key: Char{TNT-ALLOW Char}); override; public constructor InternalCreate(RadioGroup: TTntCustomRadioGroup); destructor Destroy; override; end; constructor TTntGroupButton.InternalCreate(RadioGroup: TTntCustomRadioGroup); begin inherited Create(RadioGroup); RadioGroup.FButtons.Add(Self); Visible := False; Enabled := RadioGroup.Enabled; ParentShowHint := False; OnClick := RadioGroup.ButtonClick; Parent := RadioGroup; end; destructor TTntGroupButton.Destroy; begin TTntCustomRadioGroup(Owner).FButtons.Remove(Self); inherited Destroy; end; procedure TTntGroupButton.CNCommand(var Message: TWMCommand); begin if not FInClick then begin FInClick := True; try if ((Message.NotifyCode = BN_CLICKED) or (Message.NotifyCode = BN_DOUBLECLICKED)) and TTntCustomRadioGroup(Parent).CanModify then inherited; except Application.HandleException(Self); end; FInClick := False; end; end; procedure TTntGroupButton.KeyPress(var Key: Char{TNT-ALLOW Char}); begin inherited KeyPress(Key); TTntCustomRadioGroup(Parent).KeyPress(Key); if (Key = #8) or (Key = ' ') then begin if not TTntCustomRadioGroup(Parent).CanModify then Key := #0; end; end; procedure TTntGroupButton.KeyDown(var Key: Word; Shift: TShiftState); begin inherited KeyDown(Key, Shift); TTntCustomRadioGroup(Parent).KeyDown(Key, Shift); end; { TTntCustomRadioGroup } constructor TTntCustomRadioGroup.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := [csSetCaption, csDoubleClicks {$IFDEF COMPILER_7_UP}, csParentBackground {$ENDIF}]; FButtons := TList.Create; FItems := TTntStringList.Create; TTntStringList(FItems).OnChange := ItemsChange; FItemIndex := -1; FColumns := 1; end; destructor TTntCustomRadioGroup.Destroy; begin SetButtonCount(0); TTntStringList(FItems).OnChange := nil; FItems.Free; FButtons.Free; inherited Destroy; end; procedure TTntCustomRadioGroup.FlipChildren(AllLevels: Boolean); begin { The radio buttons are flipped using BiDiMode } end; procedure TTntCustomRadioGroup.ArrangeButtons; var ButtonsPerCol, ButtonWidth, ButtonHeight, TopMargin, I: Integer; DC: HDC; SaveFont: HFont; Metrics: TTextMetric; DeferHandle: THandle; ALeft: Integer; begin if (FButtons.Count <> 0) and not FReading then begin DC := GetDC(0); SaveFont := SelectObject(DC, Font.Handle); GetTextMetrics(DC, Metrics); SelectObject(DC, SaveFont); ReleaseDC(0, DC); ButtonsPerCol := (FButtons.Count + FColumns - 1) div FColumns; ButtonWidth := (Width - 10) div FColumns; I := Height - Metrics.tmHeight - 5; ButtonHeight := I div ButtonsPerCol; TopMargin := Metrics.tmHeight + 1 + (I mod ButtonsPerCol) div 2; DeferHandle := BeginDeferWindowPos(FButtons.Count); try for I := 0 to FButtons.Count - 1 do with TTntGroupButton(FButtons[I]) do begin BiDiMode := Self.BiDiMode; ALeft := (I div ButtonsPerCol) * ButtonWidth + 8; if UseRightToLeftAlignment then ALeft := Self.ClientWidth - ALeft - ButtonWidth; DeferHandle := DeferWindowPos(DeferHandle, Handle, 0, ALeft, (I mod ButtonsPerCol) * ButtonHeight + TopMargin, ButtonWidth, ButtonHeight, SWP_NOZORDER or SWP_NOACTIVATE); Visible := True; end; finally EndDeferWindowPos(DeferHandle); end; end; end; procedure TTntCustomRadioGroup.ButtonClick(Sender: TObject); begin if not FUpdating then begin FItemIndex := FButtons.IndexOf(Sender); Changed; Click; end; end; procedure TTntCustomRadioGroup.ItemsChange(Sender: TObject); begin if not FReading then begin if FItemIndex >= FItems.Count then FItemIndex := FItems.Count - 1; UpdateButtons; end; end; procedure TTntCustomRadioGroup.Loaded; begin inherited Loaded; ArrangeButtons; end; procedure TTntCustomRadioGroup.ReadState(Reader: TReader); begin FReading := True; inherited ReadState(Reader); FReading := False; UpdateButtons; end; procedure TTntCustomRadioGroup.SetButtonCount(Value: Integer); begin while FButtons.Count < Value do TTntGroupButton.InternalCreate(Self); while FButtons.Count > Value do TTntGroupButton(FButtons.Last).Free; end; procedure TTntCustomRadioGroup.SetColumns(Value: Integer); begin if Value < 1 then Value := 1; if Value > 16 then Value := 16; if FColumns <> Value then begin FColumns := Value; ArrangeButtons; Invalidate; end; end; procedure TTntCustomRadioGroup.SetItemIndex(Value: Integer); begin if FReading then FItemIndex := Value else begin if Value < -1 then Value := -1; if Value >= FButtons.Count then Value := FButtons.Count - 1; if FItemIndex <> Value then begin if FItemIndex >= 0 then TTntGroupButton(FButtons[FItemIndex]).Checked := False; FItemIndex := Value; if FItemIndex >= 0 then TTntGroupButton(FButtons[FItemIndex]).Checked := True; end; end; end; procedure TTntCustomRadioGroup.SetItems(Value: TTntStrings); begin FItems.Assign(Value); end; procedure TTntCustomRadioGroup.UpdateButtons; var I: Integer; begin SetButtonCount(FItems.Count); for I := 0 to FButtons.Count - 1 do TTntGroupButton(FButtons[I]).Caption := FItems[I]; if FItemIndex >= 0 then begin FUpdating := True; TTntGroupButton(FButtons[FItemIndex]).Checked := True; FUpdating := False; end; ArrangeButtons; Invalidate; end; procedure TTntCustomRadioGroup.CMEnabledChanged(var Message: TMessage); var I: Integer; begin inherited; for I := 0 to FButtons.Count - 1 do TTntGroupButton(FButtons[I]).Enabled := Enabled; end; procedure TTntCustomRadioGroup.CMFontChanged(var Message: TMessage); begin inherited; ArrangeButtons; end; procedure TTntCustomRadioGroup.WMSize(var Message: TWMSize); begin inherited; ArrangeButtons; end; function TTntCustomRadioGroup.CanModify: Boolean; begin Result := True; end; procedure TTntCustomRadioGroup.GetChildren(Proc: TGetChildProc; Root: TComponent); begin end; function TTntCustomRadioGroup.GetButtons(Index: Integer): TTntRadioButton; begin Result := TTntRadioButton(FButtons[Index]); end; { TTntSplitter } procedure TTntSplitter.DefineProperties(Filer: TFiler); begin inherited; TntPersistent_AfterInherited_DefineProperties(Filer, Self); end; function TTntSplitter.IsHintStored: Boolean; begin Result := TntControl_IsHintStored(Self) end; function TTntSplitter.GetHint: WideString; begin Result := TntControl_GetHint(Self) end; procedure TTntSplitter.SetHint(const Value: WideString); begin TntControl_SetHint(Self, Value); end; procedure TTntSplitter.CMHintShow(var Message: TMessage); begin ProcessCMHintShowMsg(Message); inherited; end; procedure TTntSplitter.ActionChange(Sender: TObject; CheckDefaults: Boolean); begin TntControl_BeforeInherited_ActionChange(Self, Sender, CheckDefaults); inherited; end; function TTntSplitter.GetActionLinkClass: TControlActionLinkClass; begin Result := TntControl_GetActionLinkClass(Self, inherited GetActionLinkClass); end; end.
27.916275
102
0.708711
fce2a9ab01160de593dc37b9c8840e09e3fa06b4
8,272
pas
Pascal
Sources/Pascal/VCL/NV.VCL.DBCtrls.pas
DelcioSbeghen/NetVCL
7467db6f3b979b38d6dda4a93e0f708d1c3142d2
[ "MIT" ]
5
2019-05-08T20:13:31.000Z
2021-07-30T10:58:53.000Z
Sources/Pascal/VCL/NV.VCL.DBCtrls.pas
DelcioSbeghen/NetVCL
7467db6f3b979b38d6dda4a93e0f708d1c3142d2
[ "MIT" ]
null
null
null
Sources/Pascal/VCL/NV.VCL.DBCtrls.pas
DelcioSbeghen/NetVCL
7467db6f3b979b38d6dda4a93e0f708d1c3142d2
[ "MIT" ]
4
2019-03-30T16:37:05.000Z
2021-07-31T18:56:34.000Z
unit NV.VCL.DBCtrls; interface uses NV.Interfaces, DB, SysUtils; type EInvalidGridOperation = class(Exception); TpGridDatalink = class(TDataLink) private FModified : Boolean; FInUpdateData: Boolean; FGrid : INvDbGrid; protected // DataLink overrides procedure ActiveChanged; override; procedure DataSetChanged; override; procedure DataSetScrolled(Distance: Integer); override; procedure EditingChanged; override; procedure LayoutChanged; override; procedure RecordChanged(Field: TField); override; procedure UpdateData; override; public constructor Create(AGrid: INvDbGrid); destructor Destroy; override; // function AddMapping(const FieldName: string): Boolean; // procedure ClearMapping; procedure Modified; procedure Reset; // property DefaultFields: Boolean read GetDefaultFields; // property FieldCount: Integer read FFieldCount; // property Fields[I: Integer]: TField read GetFields; // property SparseMap: Boolean read FSparseMap write FSparseMap; property Grid: INvDbGrid read FGrid; end; TpBookmarkList = class private FList : array of TBookmark; FGrid : INvDbGrid; FCache : TBookmark; FCacheIndex: Integer; FCacheFind : Boolean; FLinkActive: Boolean; function GetCount: Integer; function GetCurrentRowSelected: Boolean; function GetItem(Index: Integer): TBookmark; procedure InsertItem(Index: Integer; Item: TBookmark); procedure DeleteItem(Index: Integer); procedure SetCurrentRowSelected(Value: Boolean); procedure DataChanged(Sender: TObject); protected function CurrentRow: TBookmark; function Compare(const Item1, Item2: TBookmark): Integer; public constructor Create(AGrid: INvDbGrid); destructor Destroy; override; procedure Clear; // free all bookmarks procedure Delete; // delete all selected rows from dataset function Find(const Item: TBookmark; var Index: Integer): Boolean; function IndexOf(const Item: TBookmark): Integer; function Refresh: Boolean; // drop orphaned bookmarks; True = orphans found property Count: Integer read GetCount; procedure LinkActive(Value: Boolean); property CurrentRowSelected: Boolean read GetCurrentRowSelected write SetCurrentRowSelected; property Items[Index: Integer]: TBookmark read GetItem; default; end; procedure RaiseGridError(const S: string); implementation uses DBConsts, RTLConsts; procedure RaiseGridError(const S: string); begin raise EInvalidGridOperation.Create(S); end; { TpGridDatalink } procedure TpGridDatalink.ActiveChanged; begin FGrid.LinkActive(Active); FModified := False; end; constructor TpGridDatalink.Create(AGrid: INvDbGrid); begin inherited Create; FGrid := AGrid; VisualControl := True; end; procedure TpGridDatalink.DataSetChanged; begin inherited; FGrid.DataChanged; FModified := False; end; procedure TpGridDatalink.DataSetScrolled(Distance: Integer); begin FGrid.Scroll(Distance); end; destructor TpGridDatalink.Destroy; begin inherited; end; procedure TpGridDatalink.EditingChanged; begin FGrid.EditingChanged; end; procedure TpGridDatalink.LayoutChanged; begin FGrid.LayoutChanged; inherited LayoutChanged; end; procedure TpGridDatalink.Modified; begin FModified := True; end; procedure TpGridDatalink.RecordChanged(Field: TField); begin // If we get called with a field that is not the selected field // and the selected field is modified we need force it to be updated first. if FModified and Assigned(Field) and (Field.FieldKind = fkData) and (FGrid.SelectedField <> Field) and not FInUpdateData then UpdateData; FGrid.RecordChanged(Field); FModified := False; end; procedure TpGridDatalink.Reset; begin if FModified then RecordChanged(nil) else Dataset.Cancel; end; procedure TpGridDatalink.UpdateData; begin FInUpdateData := True; try if FModified then FGrid.UpdateData; FModified := False; finally FInUpdateData := False; end; end; { TpBookmarkList } procedure TpBookmarkList.Clear; begin if Length(FList) = 0 then Exit; SetLength(FList, 0); FGrid.Invalidate; end; function TpBookmarkList.Compare(const Item1, Item2: TBookmark): Integer; begin with FGrid.Datalink.Datasource.Dataset do Result := CompareBookmarks(TBookmark(Item1), TBookmark(Item2)); end; constructor TpBookmarkList.Create(AGrid: INvDbGrid); begin inherited Create; SetLength(FList, 0); FGrid := AGrid; end; function TpBookmarkList.CurrentRow: TBookmark; begin if not FLinkActive then RaiseGridError(sDataSetClosed); Result := FGrid.Datalink.Datasource.Dataset.Bookmark; end; procedure TpBookmarkList.DataChanged(Sender: TObject); begin FCache := nil; FCacheIndex := -1; end; procedure TpBookmarkList.Delete; var I: Integer; begin with FGrid.Datalink.Datasource.Dataset do begin DisableControls; try for I := Length(FList)-1 downto 0 do begin Bookmark := FList[I]; Delete; DeleteItem(I); end; finally EnableControls; end; end; end; procedure TpBookmarkList.DeleteItem(Index: Integer); var Temp: Pointer; begin if (Index < 0) or (Index >= Count) then raise EListError.Create(SListIndexError); Temp := FList[Index]; // The Move below will overwrite this slot, so we need to finalize it first FList[Index] := nil; if Index < Count-1 then begin System.Move(FList[Index + 1], FList[Index], (Count - Index - 1) * SizeOf(Pointer)); // Make sure we don't finalize the item that was in the last position. PPointer(@FList[Count-1])^ := nil; end; SetLength(FList, Count-1); DataChanged(Temp); end; destructor TpBookmarkList.Destroy; begin Clear; inherited Destroy; end; function TpBookmarkList.Find(const Item: TBookmark; var Index: Integer): Boolean; var L, H, I, C: Integer; begin if (Item = FCache) and (FCacheIndex >= 0) then begin Index := FCacheIndex; Result := FCacheFind; Exit; end; Result := False; L := 0; H := Length(FList) - 1; while L <= H do begin I := (L + H) shr 1; C := Compare(FList[I], Item); if C < 0 then L := I + 1 else begin H := I - 1; if C = 0 then begin Result := True; L := I; end; end; end; Index := L; FCache := Item; FCacheIndex := Index; FCacheFind := Result; end; function TpBookmarkList.GetCount: Integer; begin Result := Length(FList); end; function TpBookmarkList.GetCurrentRowSelected: Boolean; var Index: Integer; begin Result := Find(CurrentRow, Index); end; function TpBookmarkList.GetItem(Index: Integer): TBookmark; begin Result := FList[Index]; end; function TpBookmarkList.IndexOf(const Item: TBookmark): Integer; begin if not Find(Item, Result) then Result := -1; end; procedure TpBookmarkList.InsertItem(Index: Integer; Item: TBookmark); begin if (Index < 0) or (Index > Count) then raise EListError.Create(SListIndexError); SetLength(FList, Count + 1); if Index < Count - 1 then begin Move(FList[Index], FList[Index + 1], (Count - Index - 1) * SizeOf(Pointer)); // The slot we opened up with the Move above has a dangling pointer we don't want finalized PPointer(@FList[Index])^ := nil; end; FList[Index] := Item; DataChanged(TObject(Item)); end; procedure TpBookmarkList.LinkActive(Value: Boolean); begin Clear; FLinkActive := Value; end; function TpBookmarkList.Refresh: Boolean; var I: Integer; begin Result := False; with FGrid.DataLink.Datasource.Dataset do try CheckBrowseMode; for I := Length(FList) - 1 downto 0 do if not BookmarkValid(TBookmark(FList[I])) then begin Result := True; DeleteItem(I); end; finally UpdateCursorPos; if Result then FGrid.Invalidate; end; end; procedure TpBookmarkList.SetCurrentRowSelected(Value: Boolean); var Index: Integer; Current: TBookmark; begin Current := CurrentRow; if (Length(Current) = 0) or (Find(Current, Index) = Value) then Exit; if Value then InsertItem(Index, Current) else DeleteItem(Index); FGrid.InvalidateRow(FGrid.GetRow); end; end.
22.914127
100
0.706359
c38fc0579d9292d8ad4c8f6acbc7fc39973db82b
405
pas
Pascal
FloatingTools.pas
atkins126/NxDbTools
d5874ab52653307c18d72a24efaa8deecab05aa0
[ "BSD-2-Clause" ]
null
null
null
FloatingTools.pas
atkins126/NxDbTools
d5874ab52653307c18d72a24efaa8deecab05aa0
[ "BSD-2-Clause" ]
null
null
null
FloatingTools.pas
atkins126/NxDbTools
d5874ab52653307c18d72a24efaa8deecab05aa0
[ "BSD-2-Clause" ]
null
null
null
unit FloatingTools; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs; type Tfrm_FloatingTools = class(TForm) private { Private declarations } public { Public declarations } end; var frm_FloatingTools: Tfrm_FloatingTools; implementation {$R *.dfm} end.
16.2
99
0.696296
fcc127f0403883f2c19df9fb9c38c2039bc984f7
2,397
pas
Pascal
FGX-master/Library/FGX.Graphics.pas
PauloRamalho7/ISLib
83df9ed568496a264cace3db24ad18489a186602
[ "MIT" ]
null
null
null
FGX-master/Library/FGX.Graphics.pas
PauloRamalho7/ISLib
83df9ed568496a264cace3db24ad18489a186602
[ "MIT" ]
null
null
null
FGX-master/Library/FGX.Graphics.pas
PauloRamalho7/ISLib
83df9ed568496a264cace3db24ad18489a186602
[ "MIT" ]
null
null
null
{********************************************************************* * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Autor: Brovin Y.D. * E-mail: y.brovin@gmail.com * ********************************************************************} unit FGX.Graphics; interface uses System.Types, System.UITypes, System.Classes, FMX.Graphics; function RoundLogicPointsToMatchPixel(const LogicPoints: Single; const AtLeastOnePixel: Boolean = False): Single; function RoundToPixel(const Source: TRectF; const AThickness: Single = 1): TRectF; overload; function RoundToPixel(const Source: TPointF; const AThickness: Single = 1): TPointF; overload; function RoundToPixel(const Source: Single; const AThickness: Single = 1): Single; overload; function MakeColor(const ASource: TAlphaColor; AOpacity: Single): TAlphaColor; implementation uses System.Math, System.SysUtils, FMX.Forms, FMX.Platform, FGX.Helpers, FGX.Consts, FGX.Asserts, FMX.Types, FMX.Filter.Custom, FMX.Filter, System.UIConsts, FMX.Effects; function RoundLogicPointsToMatchPixel(const LogicPoints: Single; const AtLeastOnePixel: Boolean = False): Single; var Pixels: Single; begin Pixels := Round(LogicPoints * Screen.Scale); if (Pixels < 1) and AtLeastOnePixel then Pixels := 1.0; Result := Pixels / Screen.Scale; end; function RoundToPixel(const Source: Single; const AThickness: Single = 1): Single; overload; begin Result := Source; if SameValue(Round(Source * Screen.Scale), Source * Screen.Scale, Single.Epsilon) then Result := Source - AThickness / 2; end; function RoundToPixel(const Source: TPointF; const AThickness: Single = 1): TPointF; overload; begin Result.X := RoundToPixel(Source.X); Result.Y := RoundToPixel(Source.Y); end; function RoundToPixel(const Source: TRectF; const AThickness: Single = 1): TRectF; overload; begin Result.Left := RoundToPixel(Source.Left); Result.Top := RoundToPixel(Source.Top); Result.Right := RoundToPixel(Source.Right); Result.Bottom := RoundToPixel(Source.Bottom); end; function MakeColor(const ASource: TAlphaColor; AOpacity: Single): TAlphaColor; begin TfgAssert.InRange(AOpacity, 0, 1); Result := ASource; TAlphaColorRec(Result).A := Round(255 * AOpacity); end; end.
31.96
113
0.700459
47bf4a951e5ed93f417197a6bc98aec46556e36a
970
pas
Pascal
Source/BCEditor.Editor.CodeFolding.Hint.Colors.pas
EricGrange/TBCEditor
ef037fc3638b9bcf4ecacafcfc30fac745712460
[ "MIT" ]
2
2018-01-03T03:48:19.000Z
2021-12-08T14:54:20.000Z
Source/BCEditor.Editor.CodeFolding.Hint.Colors.pas
EricGrange/TBCEditor
ef037fc3638b9bcf4ecacafcfc30fac745712460
[ "MIT" ]
null
null
null
Source/BCEditor.Editor.CodeFolding.Hint.Colors.pas
EricGrange/TBCEditor
ef037fc3638b9bcf4ecacafcfc30fac745712460
[ "MIT" ]
1
2021-04-29T08:09:41.000Z
2021-04-29T08:09:41.000Z
unit BCEditor.Editor.CodeFolding.Hint.Colors; interface uses Classes, Graphics; type TBCEditorCodeFoldingHintColors = class(TPersistent) strict private FBackground: TColor; FBorder: TColor; public constructor Create; procedure Assign(ASource: TPersistent); override; published property Background: TColor read FBackground write FBackground default clWindow; property Border: TColor read FBorder write FBorder default clBtnFace; end; implementation constructor TBCEditorCodeFoldingHintColors.Create; begin inherited; FBackground := clWindow; FBorder := clBtnFace; end; procedure TBCEditorCodeFoldingHintColors.Assign(ASource: TPersistent); begin if ASource is TBCEditorCodeFoldingHintColors then with ASource as TBCEditorCodeFoldingHintColors do begin Self.FBackground := FBackground; Self.FBorder := FBorder; end else inherited Assign(ASource); end; end.
22.045455
85
0.742268
47b7cb8eb4b12d18260821e7576bf0ebcb2cae6e
7,281
pas
Pascal
Tools/FilePackage/ObjectDataTreeFrameUnit.pas
lovong/ZNet
ad67382654ea1979c316c2dc9716fd6d8509f028
[ "BSD-3-Clause" ]
1
2022-01-30T11:33:39.000Z
2022-01-30T11:33:39.000Z
Tools/FilePackage/ObjectDataTreeFrameUnit.pas
lovong/ZNet
ad67382654ea1979c316c2dc9716fd6d8509f028
[ "BSD-3-Clause" ]
null
null
null
Tools/FilePackage/ObjectDataTreeFrameUnit.pas
lovong/ZNet
ad67382654ea1979c316c2dc9716fd6d8509f028
[ "BSD-3-Clause" ]
null
null
null
unit ObjectDataTreeFrameUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ImgList, ComCtrls, Z.UnicodeMixedLib, Z.ZDB; type TOpenObjectDataPath = procedure(_Path: string) of object; TObjectDataTreeFrame = class(TFrame) TreeView: TTreeView; procedure TreeViewExpanding(Sender: TObject; Node: TTreeNode; var AllowExpansion: Boolean); procedure TreeViewChange(Sender: TObject; Node: TTreeNode); procedure TreeViewKeyUp(Sender: TObject; var key: Word; Shift: TShiftState); private DefaultFolderImageIndex: Integer; FCurrentObjectDataPath : string; FObjectDataEngine : TObjectDataManager; FOnOpenObjectDataPath : TOpenObjectDataPath; function GetObjectDataEngine: TObjectDataManager; procedure SetObjectDataEngine(const Value: TObjectDataManager); procedure SetCurrentObjectDataPath(const Value: string); function GetPathTreeNode(_Value, _Split: string; _TreeView: TTreeView; _RN: TTreeNode): TTreeNode; function GetNodeObjDataPath(_DestNode: TTreeNode; _Split: string): string; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure UpdateFieldList(_OwnerNode: TTreeNode; _Path: string); procedure RefreshList; property CurrentObjectDataPath: string read FCurrentObjectDataPath write SetCurrentObjectDataPath; property ObjectDataEngine: TObjectDataManager read GetObjectDataEngine write SetObjectDataEngine; property OnOpenObjectDataPath: TOpenObjectDataPath read FOnOpenObjectDataPath write FOnOpenObjectDataPath; end; implementation {$R *.dfm} procedure TObjectDataTreeFrame.TreeViewExpanding(Sender: TObject; Node: TTreeNode; var AllowExpansion: Boolean); begin AllowExpansion := True; if Node.Count = 0 then UpdateFieldList(Node, GetNodeObjDataPath(Node, '/')); end; procedure TObjectDataTreeFrame.TreeViewChange(Sender: TObject; Node: TTreeNode); begin if (Node.selected) and (not(Sender as TTreeView).IsEditing) then begin FCurrentObjectDataPath := GetNodeObjDataPath(Node, '/'); if FCurrentObjectDataPath = '' then FCurrentObjectDataPath := '/'; if Assigned(FOnOpenObjectDataPath) then FOnOpenObjectDataPath(FCurrentObjectDataPath); end; end; function TObjectDataTreeFrame.GetObjectDataEngine: TObjectDataManager; begin Result := FObjectDataEngine; end; procedure TObjectDataTreeFrame.SetObjectDataEngine(const Value: TObjectDataManager); var _RootNode: TTreeNode; begin if FObjectDataEngine <> Value then begin FObjectDataEngine := Value; end; TreeView.Items.BeginUpdate; TreeView.Items.Clear; if FObjectDataEngine <> nil then begin _RootNode := TreeView.Items.AddFirst(nil, 'Root'); with _RootNode do begin ImageIndex := DefaultFolderImageIndex; selectedIndex := DefaultFolderImageIndex; StateIndex := DefaultFolderImageIndex; selected := True; Data := nil; end; UpdateFieldList(_RootNode, '/'); end; TreeView.Items.EndUpdate; end; procedure TObjectDataTreeFrame.SetCurrentObjectDataPath(const Value: string); begin FCurrentObjectDataPath := Value; if ObjectDataEngine <> nil then begin if ObjectDataEngine.DirectoryExists(FCurrentObjectDataPath) then with GetPathTreeNode('/Root/' + Value, '/', TreeView, nil) do selected := True; end; end; function TObjectDataTreeFrame.GetPathTreeNode(_Value, _Split: string; _TreeView: TTreeView; _RN: TTreeNode): TTreeNode; var Rep_Int : Integer; _Postfix: string; begin _Postfix := umlGetFirstStr(_Value, _Split); if _Value = '' then Result := _RN else if _RN = nil then begin if _TreeView.Items.Count > 0 then begin for Rep_Int := 0 to _TreeView.Items.Count - 1 do begin if (_TreeView.Items[Rep_Int].Parent = _RN) and (umlMultipleMatch(True, _Postfix, _TreeView.Items[Rep_Int].Text)) then begin Result := GetPathTreeNode(umlDeleteFirstStr(_Value, _Split), _Split, _TreeView, _TreeView.Items[Rep_Int]); Result.Expand(False); Exit; end; end; end; Result := _TreeView.Items.AddChild(_RN, _Postfix); with Result do begin ImageIndex := DefaultFolderImageIndex; StateIndex := -1; selectedIndex := DefaultFolderImageIndex; Data := nil; end; Result := GetPathTreeNode(umlDeleteFirstStr(_Value, _Split), _Split, _TreeView, Result); end else begin if (_RN.Count > 0) then begin for Rep_Int := 0 to _RN.Count - 1 do begin if (_RN.Item[Rep_Int].Parent = _RN) and (umlMultipleMatch(True, _Postfix, _RN.Item[Rep_Int].Text)) then begin Result := GetPathTreeNode(umlDeleteFirstStr(_Value, _Split), _Split, _TreeView, _RN.Item[Rep_Int]); Result.Expand(False); Exit; end; end; end; Result := _TreeView.Items.AddChild(_RN, _Postfix); with Result do begin ImageIndex := DefaultFolderImageIndex; StateIndex := -1; selectedIndex := DefaultFolderImageIndex; Data := nil; end; Result := GetPathTreeNode(umlDeleteFirstStr(_Value, _Split), _Split, _TreeView, Result); end; end; function TObjectDataTreeFrame.GetNodeObjDataPath(_DestNode: TTreeNode; _Split: string): string; begin if _DestNode.level > 0 then Result := GetNodeObjDataPath(_DestNode.Parent, _Split) + _Split + _DestNode.Text else Result := ''; end; constructor TObjectDataTreeFrame.Create(AOwner: TComponent); begin inherited Create(AOwner); DefaultFolderImageIndex := -1; FObjectDataEngine := nil; end; destructor TObjectDataTreeFrame.Destroy; begin inherited Destroy; end; procedure TObjectDataTreeFrame.UpdateFieldList(_OwnerNode: TTreeNode; _Path: string); var _FieldSR: TFieldSearch; nd : TTreeNode; begin if ObjectDataEngine <> nil then begin if ObjectDataEngine.FieldFindFirst(_Path, '*', _FieldSR) then begin repeat nd := TreeView.Items.AddChild(_OwnerNode, _FieldSR.Name); with nd do begin HasChildren := ObjectDataEngine.FastFieldExists(_FieldSR.HeaderPOS, '*'); ImageIndex := DefaultFolderImageIndex; selectedIndex := DefaultFolderImageIndex; StateIndex := DefaultFolderImageIndex; Data := nil; end; if nd.HasChildren then UpdateFieldList(nd, ObjectDataEngine.GetFieldPath(_FieldSR.HeaderPOS)); until not ObjectDataEngine.FieldFindNext(_FieldSR); end; end; end; procedure TObjectDataTreeFrame.RefreshList; var _N: string; begin _N := CurrentObjectDataPath; SetObjectDataEngine(ObjectDataEngine); SetCurrentObjectDataPath(_N); end; procedure TObjectDataTreeFrame.TreeViewKeyUp(Sender: TObject; var key: Word; Shift: TShiftState); begin case key of VK_F5: RefreshList; end; end; end.
31.383621
131
0.685345
c36107abda06097607148a3f920f4230f3d82cbd
248
dpr
Pascal
FastPHPBrowser.dpr
danielmarschall/fastphp
e790d80b4fc21811b28323fb40c09f544af64eea
[ "Apache-2.0" ]
null
null
null
FastPHPBrowser.dpr
danielmarschall/fastphp
e790d80b4fc21811b28323fb40c09f544af64eea
[ "Apache-2.0" ]
null
null
null
FastPHPBrowser.dpr
danielmarschall/fastphp
e790d80b4fc21811b28323fb40c09f544af64eea
[ "Apache-2.0" ]
1
2021-01-28T02:18:50.000Z
2021-01-28T02:18:50.000Z
program FastPHPBrowser; uses Forms, BrowserMain in 'BrowserMain.pas' {Form2}; {$R *.res} begin Application.Initialize; Application.MainFormOnTaskbar := True; Application.CreateForm(TForm2, Form2); Application.Run; end.
16.533333
44
0.697581
fcbf3e28cdc161ab372722a3d18b5674280de402
4,113
pas
Pascal
ThirdParty/Spring4D/Source/Persistence/Core/Spring.Persistence.Core.ListSession.pas
Gronfi/DPN
a21706737f6eca7378e31511d15768a36f93a72a
[ "Apache-2.0" ]
3
2020-11-06T15:46:18.000Z
2021-06-24T09:23:29.000Z
ThirdParty/Spring4D/Source/Persistence/Core/Spring.Persistence.Core.ListSession.pas
Gronfi/DPN
a21706737f6eca7378e31511d15768a36f93a72a
[ "Apache-2.0" ]
null
null
null
ThirdParty/Spring4D/Source/Persistence/Core/Spring.Persistence.Core.ListSession.pas
Gronfi/DPN
a21706737f6eca7378e31511d15768a36f93a72a
[ "Apache-2.0" ]
3
2020-10-31T00:46:34.000Z
2021-06-23T15:23:27.000Z
{***************************************************************************} { } { Spring Framework for Delphi } { } { Copyright (c) 2009-2020 Spring4D Team } { } { http://www.spring4d.org } { } {***************************************************************************} { } { 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. } { } {***************************************************************************} {$I Spring.inc} unit Spring.Persistence.Core.ListSession; interface uses Spring, Spring.Collections, Spring.Persistence.Core.Interfaces, Spring.Persistence.Core.Session; type TListSession<T: class, constructor> = class(TInterfacedObject, IListSession<T>) private {$IFDEF AUTOREFCOUNT}[Unsafe]{$ENDIF} fSession: TSession; fList: IList<T>; fPrimaryKeys: ISet<TValue>; protected procedure DoOnListChanged(Sender: TObject; const item: T; action: TCollectionChangedAction); procedure CommitListSession; virtual; procedure RollbackListSession; virtual; procedure DeleteEntities; public constructor Create(const session: TSession; const list: IList<T>); virtual; destructor Destroy; override; end; implementation uses Spring.Persistence.Core.Exceptions, Spring.Persistence.Core.EntityCache, Spring.Persistence.SQL.Commands.Delete; {$REGION 'TListSession'} constructor TListSession<T>.Create(const session: TSession; const list: IList<T>); begin inherited Create; fPrimaryKeys := TCollections.CreateSet<TValue>; fSession := session; fList := list; fList.OnChanged.Add(DoOnListChanged); end; destructor TListSession<T>.Destroy; begin fList.OnChanged.Remove(DoOnListChanged); inherited Destroy; end; procedure TListSession<T>.CommitListSession; begin //delete first DeleteEntities; fSession.SaveList<T>(fList); end; procedure TListSession<T>.DeleteEntities; var deleter: IDeleteCommand; primaryKey: TValue; begin deleter := TDeleteExecutor.Create(fSession.Connection); deleter.Build(T); for primaryKey in fPrimaryKeys do deleter.ExecuteById(primaryKey); end; procedure TListSession<T>.DoOnListChanged(Sender: TObject; const Item: T; Action: TCollectionChangedAction); var value: TValue; entityDetails: TEntityData; begin case Action of caAdded: ; caRemoved: begin if not fSession.IsNew(Item) then begin entityDetails := TEntityCache.Get(T); value := entityDetails.PrimaryKeyColumn.GetValue(Item); if fPrimaryKeys.Add(value) then fSession.OldStateEntities.Remove(Item); end; end; caReplaced: ; caMoved: ; caReset: ; end; end; procedure TListSession<T>.RollbackListSession; begin fPrimaryKeys.Clear; end; {$ENDREGION} end.
31.396947
108
0.533917
f1d81282105b941afe3b773b42bb281e46f99a3b
2,322
pas
Pascal
service/ureserveservicelistener.pas
itfx3035/lazarus-freepascal-ims
b411f18490dbee0a7b37fe6bb74cb96ba523bae0
[ "MIT" ]
null
null
null
service/ureserveservicelistener.pas
itfx3035/lazarus-freepascal-ims
b411f18490dbee0a7b37fe6bb74cb96ba523bae0
[ "MIT" ]
null
null
null
service/ureserveservicelistener.pas
itfx3035/lazarus-freepascal-ims
b411f18490dbee0a7b37fe6bb74cb96ba523bae0
[ "MIT" ]
null
null
null
unit uReserveServiceListener; {$mode objfpc}{$H+} interface uses Classes, SysUtils, synsock, uLog, uNetwork, blcksock, uReserveServiceConnection; type TReserveServiceListener = class(TThread) private { Private declarations } trLocalIp:string; trPort:integer; trLogMsg:string; S:TTCPBlockSocket; procedure ReadParams; //procedure toLog; procedure trWriteLog(msg_str:string); //procedure UpdateCurrSocketID; protected { Protected declarations } procedure Execute; override; public constructor Create(local_ip: string); end; implementation uses uMain; constructor TReserveServiceListener.Create(local_ip: string); begin inherited create(false); FreeOnTerminate := true; trLocalIp := local_ip; end; procedure TReserveServiceListener.Execute; var S_res:TSocketResult; ss:tSocket; le:integer; begin FreeOnTerminate:=true; //Synchronize(@ReadParams); ReadParams; S_res:=PrepereSocketToListen(trLocalIp,trPort); While S_res.res<>1 do begin if Terminated then begin exit; end; trWriteLog('Error: cannot bind socket to local ip '+trLocalIp+' port '+inttostr(trPort)+'; err '+inttostr(-1*S_res.res)); trWriteLog('Waiting 5 seconds and try again..'); Sleep(5000); S_res:=PrepereSocketToListen(trLocalIp,trPort); end; S:=S_res.S; while not Terminated do begin if s.CanRead(500) then begin S.ResetLastError; ss:=S.Accept; le:=s.LastError; if le<>0 Then begin trWriteLog('Error while accepting connection. Err '+inttostr(-1*le)); Continue; end; // start new thread to proceed connection uReserveServiceConnection.TThreadReserveServiceConnection.Create(ss); end; end; s.CloseSocket; end; procedure TReserveServiceListener.ReadParams; begin cs1.Enter; trPort:=uMain.sReservServiceListeningPort; cs1.Leave; end; //procedure TReserveServiceListener.toLog; //begin // uLog.WriteLogMsg(trLogMsg); //end; procedure TReserveServiceListener.trWriteLog(msg_str:string); begin //trLogMsg:=msg_str; //Synchronize(@toLog); uLog.WriteLogMsg(msg_str); end; end.
21.90566
127
0.664944
c351cedb1efe7aa243c1590fcf954ae1e790ea6b
8,668
pas
Pascal
HODLER_Multiplatform_Win_And_iOS_Linux/additionalUnits/bi/Velthuis.BigIntegers.Primes.pas
M3Supreme45/HODLER-Open-Source-Multi-Asset-Wallet
259ea75f7aba999ffd184997a884c1c22d34fa40
[ "Unlicense" ]
null
null
null
HODLER_Multiplatform_Win_And_iOS_Linux/additionalUnits/bi/Velthuis.BigIntegers.Primes.pas
M3Supreme45/HODLER-Open-Source-Multi-Asset-Wallet
259ea75f7aba999ffd184997a884c1c22d34fa40
[ "Unlicense" ]
null
null
null
HODLER_Multiplatform_Win_And_iOS_Linux/additionalUnits/bi/Velthuis.BigIntegers.Primes.pas
M3Supreme45/HODLER-Open-Source-Multi-Asset-Wallet
259ea75f7aba999ffd184997a884c1c22d34fa40
[ "Unlicense" ]
1
2020-05-15T11:43:18.000Z
2020-05-15T11:43:18.000Z
{ --------------------------------------------------------------------------- } { } { File: Velthuis.BigIntegers.Primes.pas } { Function: Prime functions for BigIntegers } { Language: Delphi version XE2 or later } { Author: Rudy Velthuis } { Copyright: (c) 2017 Rudy Velthuis } { Notes: See http://rvelthuis.de/programs/bigintegers.html } { See https://github.com/rvelthuis/BigNumbers } { } { License: 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. } { } { Disclaimer: THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "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 OWNER 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. } { } { --------------------------------------------------------------------------- } unit Velthuis.BigIntegers.Primes; interface uses Velthuis.BigIntegers; type /// <summary>Type indicating primality of a number.</summary> TPrimality = ( /// <summary>Number is definitely composite.</summary> primComposite, /// <summary>Number is probably prime.</summary> primProbablyPrime, /// <summary>Number is definitely prime.</summary> primPrime); /// <summary>Detects if N is probably prime according to a Miller-Rabin test.</summary> /// <param name="N">The number to be tested</param> /// <param name="Precision">Determines the probability of the test, which is 1.0 - 0.25^Precision</param> /// <returns>True if N is prime with the given precision, False if N is definitely composite.</returns> function IsProbablePrime(const N: BigInteger; Precision: Integer): Boolean; /// <summary>Detects if N is prime, probably prime or composite. Deterministically correct for N &lt; 341,550,071,728,321, otherwise /// with a probability determined by the Precision parameter</summary> /// <param name="N">The number to be tested</param> /// <param name="Precision">For values >= 341,550,071,728,321, IsProbablyPrime(N, Precision) is called</param> /// <returns>Returns primComposite if N is definitely composite, primProbablyPrime if N is probably prime and /// primPrime if N is definitely prime.</returns> function IsPrime(const N: BigInteger; Precision: Integer): TPrimality; /// <summary>Returns a random probably prime number.</summary> /// <param name="NumBits">Maximum number of bits of th random number</param> /// <param name="Precision">Precision to be used for IsProbablyPrime</param> /// <returns> a random prime number that is probably prime with the given precision.</returns> function RandomProbablePrime(NumBits: Integer; Precision: Integer): BigInteger; /// <summary>Returns a probable prime >= N.</summary> /// <param name="N">Number to start with</param> /// <param name="Precision">Precision for primality test</param> /// <returns>A number >= N that is probably prime with the given precision.</returns> function NextProbablePrime(const N: BigInteger; Precision: Integer): BigInteger; /// <summary>Checks if the (usually randomly chosen) number A witnesses N's compositeness.</summary> /// <param name="A">Value to test with</param> /// <param name="N">Number to be tested as composite</param> /// /// <remarks>See https://en.wikipedia.org/wiki/Miller-Rabin_primality_test#Algorithm_and_running_time</remarks> function IsWitness(const A, N: BigInteger): Boolean; function IsComposite(const A, D, N: BigInteger; S: Integer): Boolean; implementation // See https://en.wikipedia.org/wiki/Miller-Rabin_primality_test. uses Velthuis.RandomNumbers, System.SysUtils; var Two: BigInteger; Random: IRandom; // Rabin-Miller test, deterministically correct for N < 341,550,071,728,321. // http://rosettacode.org/wiki/Miller-Rabin_primality_test#Python:_Proved_correct_up_to_large_N // If you want to improve upon this: // https://en.wikipedia.org/wiki/Miller-Rabin_primality_test#Deterministic_variants_of_the_test function IsPrime(const N: BigInteger; Precision: Integer): TPrimality; var R: Integer; I: Integer; PrimesToTest: Integer; D: BigInteger; const CPrimesToTest: array [0 .. 6] of Integer = (2, 3, 5, 7, 11, 13, 17); CProbabilityResults: array [Boolean] of TPrimality = (primComposite, primProbablyPrime); function GetNumberOfPrimesToTest(const N64: Int64): Integer; begin if N64 > Int64(3474749660383) then Result := 7 else if N64 > Int64(2152302898747) then Result := 6 else if N64 > Int64(118670087467) then Result := 5 else if N64 > Int64(25326001) then Result := 4 else if N64 > Int64(1373653) then Result := 3 else Result := 2; end; begin if N > BigInteger('341 550 071 728 321') then Exit(CProbabilityResults[IsProbablePrime(N, Precision)]); PrimesToTest := GetNumberOfPrimesToTest(Int64(N)); if N = 3215031751 then Exit(primComposite); D := N; Dec(D); R := 0; while D.IsEven do begin D := D shr 1; Inc(R); end; for I := 0 to PrimesToTest - 1 do if IsComposite(CPrimesToTest[I], D, N, R) then Exit(primComposite); Result := primPrime; end; // Check if N is probably prime with a probability of at least 1.0 - 0.25^Precision function IsProbablePrime(const N: BigInteger; Precision: Integer): Boolean; var I: Integer; A, NLessOne: BigInteger; begin if (N = 2) or (N = 3) then Exit(True) else if (N = BigInteger.Zero) or (N = BigInteger.One) or (N.IsEven) then Exit(False); NLessOne := N; Dec(NLessOne); for I := 1 to Precision do begin repeat A := BigInteger.Create(N.BitLength, Random); until (A > BigInteger.One) and (A < NLessOne); if IsWitness(A, N) then Exit(False); end; Result := True; end; function RandomProbablePrime(NumBits: Integer; Precision: Integer): BigInteger; begin repeat Result := BigInteger.Create(NumBits, Random); until IsProbablePrime(Result, Precision); end; // Next probable prime >= N. function NextProbablePrime(const N: BigInteger; Precision: Integer): BigInteger; var Two: BigInteger; begin Two := 2; Result := N; if Result = Two then Exit; if Result.IsEven then Result := Result.FlipBit(0); while not IsProbablePrime(Result, Precision) do begin Result := Result + Two; end; Result := N; end; function IsWitness(const A, N: BigInteger): Boolean; var R: Integer; D: BigInteger; // Estimate: BigInteger; // NewEstimate: BigInteger; // I: Integer; begin // Write N - 1 as (2 ^ Power) * Factor, where Factor is odd. // Repeatedly try to divide N - 1 by 2 R := 1; D := (N - BigInteger.One) shr 1; while D.IsEven do begin D := D shr 1; Inc(R); end; // Now check if A is a witness to N's compositeness Result := IsComposite(A, D, N, R); // Estimate := BigInteger.ModPow(A, D, N); // for I := 0 to R - 1 do // begin // NewEstimate := (Estimate * Estimate) mod N; // if (NewEstimate = BigInteger.One) and (Estimate <> BigInteger.One) and (Estimate <> N - BigInteger.One) then // Exit(True); // Estimate := NewEstimate; // end; // Result := Estimate <> BigInteger.One; end; function IsComposite(const A, D, N: BigInteger; S: Integer): Boolean; var I: Integer; NLessOne: BigInteger; begin NLessOne := N - BigInteger.One; // if A^(2^0 * D) ≡ 1 (mod N) then prime. if BigInteger.ModPow(A, D, N) = BigInteger.One then Exit(False); for I := 0 to S - 1 do // if A^(2^I * D) ≡ N - 1 (mod N) then prime. if BigInteger.ModPow(A, (BigInteger.One shl I) * D, N) = NLessOne then Exit(False); Result := True; end; initialization Two := 2; Random := TRandom.Create(Round(Now * SecsPerDay * MSecsPerSec)); end.
32.586466
132
0.68551
c34447e56f9f8fa4224b2b4363d52d98a8aace84
2,550
pas
Pascal
Tests/ValueHolder.pas
ritalin/promise-for-delphi
aa54cee8e16cc626713d9a95af081fb5609970ee
[ "MIT" ]
9
2017-09-07T07:52:17.000Z
2021-01-09T15:46:37.000Z
Tests/ValueHolder.pas
ritalin/promise-for-delphi
aa54cee8e16cc626713d9a95af081fb5609970ee
[ "MIT" ]
null
null
null
Tests/ValueHolder.pas
ritalin/promise-for-delphi
aa54cee8e16cc626713d9a95af081fb5609970ee
[ "MIT" ]
3
2019-08-09T00:05:49.000Z
2021-02-22T23:09:01.000Z
unit ValueHolder; interface uses System.SysUtils, System.SyncObjs, Promise.Proto ; type IHolder<TResult> = interface function GetValue: TResult; procedure SetValue(const value: TResult); function GetReason: IFailureReason<Exception>; procedure SetReason(const value: IFailureReason<Exception>); function GetSuccessCount: integer; function GetFailureCount: integer; function GetAlwaysCount: integer; procedure Success; procedure Failed; procedure Increment; property Value: TResult read GetValue write SetValue; property Error: IFailureReason<Exception> read GetReason write SetReason; property SuccessCount: integer read GetSuccessCount; property FailureCount: integer read GetFailureCount; property AlwaysCount: integer read GetAlwaysCount; end; TValueHolder<TResult> = class (TInterfacedObject, IHolder<TResult>) private var FValue: TResult; FReason: IFailureReason<Exception>; FSuccessCount: integer; FFailureCount: integer; FAlwaysCount: integer; private function GetValue: TResult; procedure SetValue(const value: TResult); function GetReason: IFailureReason<Exception>; procedure SetReason(const value: IFailureReason<Exception>); function GetSuccessCount: integer; function GetFailureCount: integer; function GetAlwaysCount: integer; protected procedure Success; procedure Failed; procedure Increment; end; implementation { TValueHolder<TResult> } procedure TValueHolder<TResult>.Failed; begin TInterlocked.Increment(FFailureCount); end; function TValueHolder<TResult>.GetAlwaysCount: integer; begin Exit(FAlwaysCount); end; function TValueHolder<TResult>.GetFailureCount: integer; begin Exit(FFailureCount); end; function TValueHolder<TResult>.GetReason: IFailureReason<Exception>; begin Exit(FReason); end; function TValueHolder<TResult>.GetSuccessCount: integer; begin Exit(FSuccessCount); end; function TValueHolder<TResult>.GetValue: TResult; begin Exit(FValue); end; procedure TValueHolder<TResult>.Increment; begin TInterlocked.Increment(FAlwaysCount); end; procedure TValueHolder<TResult>.Success; begin TInterlocked.Increment(FSuccessCount); end; procedure TValueHolder<TResult>.SetReason(const value: IFailureReason<Exception>); begin FReason := value; end; procedure TValueHolder<TResult>.SetValue(const value: TResult); begin FValue := value; end; end.
24.285714
83
0.74
c34721a0db903d372ae263bfc9e1f251989c5212
67,810
dfm
Pascal
NoNaMe_Post_Editor/frmuSplash.dfm
delphi-pascal-archive/noname_pe
57b2f869af0d98c66f5edecb3c14acb57ecbf098
[ "Unlicense" ]
null
null
null
NoNaMe_Post_Editor/frmuSplash.dfm
delphi-pascal-archive/noname_pe
57b2f869af0d98c66f5edecb3c14acb57ecbf098
[ "Unlicense" ]
null
null
null
NoNaMe_Post_Editor/frmuSplash.dfm
delphi-pascal-archive/noname_pe
57b2f869af0d98c66f5edecb3c14acb57ecbf098
[ "Unlicense" ]
null
null
null
object frmSplash: TfrmSplash Left = 295 Top = 222 AlphaBlend = True AlphaBlendValue = 0 BorderStyle = bsNone Caption = 'frmSplash' ClientHeight = 270 ClientWidth = 378 Color = clWhite Font.Charset = RUSSIAN_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] FormStyle = fsStayOnTop OldCreateOrder = False Position = poScreenCenter OnClose = FormClose OnCreate = FormCreate OnDeactivate = FormDeactivate OnPaint = FormPaint PixelsPerInch = 96 TextHeight = 13 object Image1: TImage Left = 144 Top = 8 Width = 225 Height = 225 Center = True Picture.Data = { 0954474946496D6167654D190000474946383961E600E600C40000FEFEFE6965 7DCFCBE4BDBACDC8C5D7D8D4EDF1F1F2E0DCF5EBEBEDD6D6D9E5E5E9837F94DD DCE1AEACB99B97A9E2E4E3F7F7FA46426E262150E7E3FC000000FFFFFF000000 0000000000000000000000000000000000000000000000000000002C00000000 E600E6000005FF20258E64699E68AAAE6CEBBE702CCF740DDC78AEEF7CEFFFC0 A070482C1A8FC8E45104A8389FD0A8744AAD5AAFD8AC76CBED7ABF602E80192E 9BCFE8B47ACDAE8C29CDB67C4EAFDBDBEFF87DCFEFFBEB797F82838485578186 898A8B76888C8F90915E8E929596976E64989B9C8A949DA0A1779FA27D13A7A8 A9AAABACADAEAFB0B1B2B3A856A4A57BB4AE07040E011111010B0E05BAC6C7C8 A9B69AB87EC9A7030112D3D41211D6C5CFDADBABCB70CD7FC90DD7D5D4C0D303 DCEADCDE7AE0B9C6E3E5F3D4E9EBF7C8EDEFA6B402E4F4D58005B087AFE02C7D FBE0C97200909E40070623C642980802844BB2FC3504082C8200892059514C58 2756838D0D1FFF865C59ABCA2D926C5E15908632A530962C47C294E38AC0B99A 0E0308C5B952E7CE98AC1CFC033A4FE84DA2208D1E55C36A8135A60E810D831A D525B3A948511DF88575633088AB0EA85DCB359FD76F60DBA412B02018CDB2F3 048A555BA0AFDF026ADBEA921AD70C2ABA110810B88BB71CB0B57F0B08984C19 B0E0836FDD154673CA670001070638A8DBD87184BF9453A7B67C1916E1CD6026 8C8BB0A08183010D1AD4FDD9189800C9AA834FCED6DAD56BD85E94FE13E62077 83010594E2154840B8F0BE078A1BCF8C1CCD6CC7C3404F28306001E39A76AB57 B79E3ABBF656C7BB67514EEF9783DBB86D93651A4C3DFBD5EFC1C79D7C60D087 126DCDE1461AFF7AC0A8B7DE7FAC05A8CC80047661DE521B0933C064D160C851 041B2AF6DF70EE49D812152F5558C56E6545E080620458055483028838E26F25 9A189F8A501858D630B9F9E2A163423978238E13AC95636B3BF258818F8D0510 E47E1C0953A38DAAC15899925C16D7A48A5096B60090427EE8C0950FA2096375 D871A92493143A3945035496664E6D0A9A7925656BF6C9266080B9B924515FCA 47679D7652B30001F26475A69F908A1859646CB5552827081800463442250AD0 30A379084C036A46AAE5A49406C6D5A59840D000035F30C0A2A79FDE276A62A6 423A1CAA7E554A689CFB2440C0455D20409B8CB4D67A1E75B9EACA6BAFAAFE8A E257FB286611FF170628F50B3943D21A0C862E36ABD800E4AEF76C9B9602FB8E 020324A7D498B3264B24B821FA390001E4E67BEFAECF462BED14299602C1B05C 28050131499AB76DB7A505639A8330EA2BF1BEBF9DEB2F4EAC623200AC5A3010 4C030738911BB9B65D28AF35E04ED6E7C4FAFE69F1C545A9FB8EB05A20508104 01845C01B97E4163F2C9F3AC372ECB2D57FCF2A021657CC90304646140D30BB4 BB73C51340D09982E7C94B239A4497EB32AF6F42A5B4250A348D0501210BE0C4 BD805994E4D0FA7574727F7C0ECDB2A44723DDD5B470C1A4400367FFB2400503 13D076926A8A274099C902F32296764B6C6EDEABCA0CCE03805BF18002828FF3 627668527600FFB1BCE8C630568E7BAD72E4F94EFE72BA7C6B166CE65418B040 D90EE30C6AB9944DE084D52AEB96F574113CA7BA9A921BDD2FCC31C77ED47355 1CBC1BA22E92F804047DD558236E61A25E7CCB90167D6E9B7AEF0D30B5FB34F0 4015BE703AA49404F8EEC40192655F8002F4F7126F8BF8B51EFEBD5F031BF392 66B945404F0BAE2296141480B36F5569010520DC78B083800328E08292E9C5B6 4A633CF0ADCC46E3235FE59C6789E6682A0B09A05D140C7012A15CA35B02094F 6020A3800C2A68412D229AA9F875B4119EAF6F9250C030B4702F2AD8A623BCF9 50F17655B7A109E974791948D700A8251E2EAF7C11191B1F0C208C2C34E08451 20800414A01CFFB9992320FF289E9F84E5C4FD1DA87F5D5B93158133A9B061AC 808F180D18A7F0B72920C02A480CE452CC480DF85D2901884CA46284C71F104D 117CC3614FAA7C4540126E42340A98C245C83505850952902803C84004900006 5C500108C8940110C02EC665488A8F545DF6AC33494A4A448B7F785A02A46091 0664320AE3B0DD2791B8418E2CCA94174CE503949900D1202A8A518B65EB2A06 A1BFB8A9793F94DD252030805D4201022C54A0131020B8850D73612959D40537 A78007B89301C20A151425104D69E2AD9AE4B3E32DF158895246E16FE2AC405D 9C324CB921514F167C0003148A487CE906871CE9602CF1069CEB58F39AE69342 C0B0004E0330FFAD5C0940C0B5E440009B3D810103308002E93400DA9853902E 0C24471EA71836462C546681A53D5D26496861749F96E402029E388F055C641C CCE9A648CB7091A741A19B0650690584E894311594903519080112C9557832AA 987991E8441F5451D5D4529F06611504205AD4A38AD20126ED82022EB2D0270C E022E05CAB307EE114BEFEC4A01D792639E087C885BA93A1A2F91978A409C911 9DD59605B994029208100754E0246671C003026A055656C000DE4480D408C729 9C6D2BA6D3B82AB842491B021C96015E25D99406190CC636B6A717FD6916F909 8507C8B4211BC32C4A008748A95A01B49F2580A69AF9042EBAF0B9FB512D2807 1980DBD43491FF866D6702888A323832164BB4CCAD6ED3CADBDF81B2210E40E9 3C55F81CE34AE169A0C5CDCEE28AD460781265D235A769ECEBDA544635AAA954 004A899A1EDB1E0F9FF9EC5246A3B0D127CCE6BC4D89C687AE1280B826C03E09 70EFEFB62A2CF33880585C0C2C410522DD12F74795AB54A6421965BAC0B26EAC 8E15AF82170C85063BE1A5076D0A43CC428D0688D4A37771D15C15B855C598E7 769755584CEDD2D76F89D8C4485C40024E898077C2937BE6DCD0F66C9BA6F0FA 74BCE40DAA15AE4A8F5749E7406673C28EAB3110953E8D51E581972FFACA5773 8ED8C9818572D40A0BCF86E6ABC5C5CBDE8BE3782319CF18A8D9D4028E293B8D CF4060B25749FF499A2B20C6D49A23000BE5DE68E8CCE9262F1ACA82AC0D87B9 0AB723436796F8DA698CBF7C68446B147D5468E94B1B72BB04CC5302698680AD F7EBA2E68C89D34EB6068E970CEA503F87ABC866546D50B33A5523385082CA49 799DB0183C3724000F4800B23234AC54FE312B12881B93F3CC2DD5E2B7D8B479 CEA8BDDACCDC18CE7E4D9C68A10D0DD930277A0B87CA715819D0A8944800AE0B FDDB81AE1A5D7443B9BA1C7667333FACE5CA6469D0B7F532ABD1BA5B3163814E FAA6AE5ACEBC91DBAD92DFB7C2AFB087995A8377FA9378C2D768EE032BD17439 35119B22782D3AF17ADBFBD540CC020470EC90940AD4216CCE14225BCA9B17FE 15CF19572D74FF3B7D7226CBB901A316E2EE8413F3BBBD3C388FB57964A70D05 9F14B4902F226356CBA5A9930096BA64317AA4CFDD649832BDAF4FB7EE092180 D2928D69CE510B4ED53DB8EA04B7DAD50C86F5150C4066D6E20B280D905F058C E5182281352FC42428B199CCE931417D7DD7EBA801049C5860231CE62F9EB959 EB28282CE2436944FFE455AE013FC48FF4B28D47A30BCD12C83B539EE977BF17 229709E0141760914A0E64DEEBC6F767FB5DEB5BB7B8162E7CDE833607280BF0 DDB51808741153095C4A7F3BDC139426537A5B008955B29D6BB3BA71C9B1EF35 1FE0CD039FF32E3C18C203616B8447EA2A7F7F0BB5908769EDB57FF7E7ACA662 6AA100DB157CFFA1F622A55245E8777CA6777A5C4705BB0161202200C3630EC1 50000AE40F21875F04951591376CB8675DA0011991F11B31327B25A71506E827 473247A5B780F7804B9F55780B2000FD264A114438107000DBC62D14086167B4 7F4FA67D2F421CA7603549226835C25DA9C51C7CB282A3A780EA5771F7560621 A67AC0702FDBD673BF034EFD762BFAC66B0B7367DA270CCF510C166184559324 07A03D9B062EE48775B3D4772DE8822FD88055404E5F270C31821268910A5908 798F874646F7641D486796472EBF5184AC2019E5814EA9350CEFA63C71885B50 4887EB00834F808757351A2821251F51841AF1211BE81017426EFB6788F0A26E 20940A22481EFF8FE73843C82BCF3687B0338567508505658241411055235C41 318A45558AE3E67655052450A777F9F47BE0E746D7701F68832AC6D782B58873 DA14066B957D30E422AA621159637474865567E149B7677D42918A1B32823067 340EA58B27981B92E81712078582818952C07CD295178D163F5573116BD683B7 376C08428092878AA0E27F5C826A54641BF2144A1AE889EF4873F466890CA87C 68C042E8E483967685567386182888FF687B67B16995077777771FDC871DAA40 3FDA037C058744BE605DAE3389EF086D6076471499062C547801F10B0461353A 186985D8742E350CE24792E558901D843795921DC0A172FB7385A3414520841A 57F477FF428DFF77F0004FF45B82B828FB083A6984329EE7692E449445290CF0 D27F14533724423FD0C688C2435BDCE72C21248D97418F3AA76D18E992162816 80748A23066CAC771FBF769469B93B86231616B5860E976F1832323B343EB478 9776780665445981F42262D121803990851958A0726468599240728E45E8362A 5951A826224AD81190499702547A5E529967E075BF556EDAE896F48371E4D869 9FC957848996A36992DC8724D7E293F5A39A5B264F69545BAA787E5559936243 9BB58974FB1500F1C31ADC1486637896CDE10B69499CCE718E285935389883D6 A172607550B8A182D1299D57C97ED57807D9C295E7460C25823D18578E63399A 70971BA48994FFAD43938171864618492A9358451765A22647A83287C8276D37 B90797D99CD4E11EC8A91CB5719624A964B56177DFD91C23C33B3912182A7586 885337A6237BE37077EE49A010FA1E7819066112483D992413B0380110527356 7969D957B7A190223AA2548424A8C04A08B08F6E331E91842F75521B2B27950E 0AA376399B13CA075D780E0271A36A1823A4C5A18759985113240942A4D5514A 0C5022FFC54A0AA088A8F07BC0C71B1F2AA5A906400008A1516893B658086677 501D7126EE911DD9911B84936D8DB87D77579852921F09E23FEB1170A8F45F00 86A406B017BFA72047D7A02BE33F773A99DA31A366C0009FE68995C2009A4538 22E52AFE99A8FF84F96BD1142412C346A5944CFE25A9017641A7E09649584C8E 931BC8F6AB09B039AA64A0C4CA599060637D50A1815586EE41A85B3855A37198 C4D9AA90981F50772FBAB77BA8E46D280660A7843F7C017E18D7832303ACD815 70C35AACAF5709C8DA070FB041C4440C05005A1F462C0AC4340AE91CB6E11CD1 0A89FB0A40C29248EC9429DE26A951D54EB0C5004DC93872731F0D60AE09CB4E 91AAAEC67AAC829708D2517B41DA3451F53B4F803F0FC03BD6AAAF2EFAAF35B5 55F0C40048CAADDDBA4A02065BC2027E04E622E5711BC06A58125BABC5CA09ED 9A4BE51179A2415C71D55C1360000CF01BD8332EC65332F761ADA32600088B4A 91CAAD93EA6DFF7D862FBFF60F4D7B6C7D866C124BAB99B2B39BD0B383902D7B 256A80E300DEA4407955A955B379C2E235CEF4A1E55A4A04A0B2EE4465481AA9 2EAB4CF05432FA751B090BB3BF0AA9B41A55C4DA09643B08E02460CD3480B591 AA99A7AE08906CCA36A65C9B6D2155657ACBAD7CCBA602E84CA136000A95B010 9BB3E97A868A7BB190601108802F90BB28E2447F78E5BA0A85B088349EEE3665 29CB4AC29A4CDFBA3929B64EA6CAAB42212CA56BAE85F5ADA95BB192B0B88460 11F752BCE5B859F69A791EDBB8DBBA622659AE8EEB7D861BBC87C5A6A5DB21E6 901B9BD74DCA2BB05486B8EB3AB6AC1B09A0C54A9C22140D40BBB5EBB138D8AD 8CB2B5CFA170FFB0A54CC9E44EE47B589B736538256C05202C9A8200C7D6555D 05B61AB6BAEDB74D16F1340455AF4D457F9A74A2AFEB722CB6310AF54E1E25AC 79BB3906BC5057F633DFA3B6BF534AE472AE232CAC05FBBEF05BC116AC6B7E85 9DE749BB9A6411D9A66E24732F55F64ECB94B7ED64C0467CB45F6550B7911D0A 94B250574A5F4BB5272A0AD06B08405C7B1698B83E3CB9CD542ED68AB7A61452 2F7B4A4ACC5029248C1F63190165B7774BC3052BA9CECBAEF12B09AEFB52F7DB 5162BBAEC412C6D8EAAB9B674A0A850009BB4E29DC501A2462D0313AFB08052A AB18DE37C7FFA5BAA090C55AAC57C4A46EA96AC938F84D525536D8DA9E105065 65AC5DB0A5C4FF30CB928165800D60819A5436C1CAB2EE6BC39880C95A6C8FF1 AA524A6AAFEB7AC5032331FF45C82A9BB286A5C20D15977FAA2DB451239C5565 1BB3AD3A6BCBB77CC79550CA6C6C1709B08F45B885D7FB59205653E462BDDE37 650218B1C89CBBC64B940BB3C751B039FD35C7D45CCD38CC09DC340C82440C6E A3BA069ABD60C4342BB64B8F56CCC5CC678A442E04661F6524250FCB598EBBAD 748C0BB89C08A205680271BFBDDCC3F99B574EB07BCC55CAEC045BDF1BB0717B 1F763688C50399BFF404EE3400105DC9126DCD9760003F5B7B0390A4A709CEC7 7986885B01009D6DB032C8071CACB20A40CA5C2748E41C61CC006054B988F4D2 578CC5326D09FFE0B4952E960A174CAC27CAD1BA4600EDD434E094CAECF2B7D8 EA6BFAB55F0EAB4888344E4307D5F36C0913AD08DB597BADA50C1B295595DCD3 0CE0D50296498F361902E85ACDB455739667AB1753CC0175B00523016BA82FDD CFA110D78AE05C9F9433A8B0A4EE8BB895ECD41704D6A0E55AA58B58562D371E 36501FD31CA64B45D8FAD89E4CC1F3290A74D240810432978DA345CBC7E09429 15202C0126D0868CC2AB6CBE6B8782007A217727D628D53A0BE55F891BD9538D 096FD60B1A2B1EB98AA17C9C628BE7D5A9C4D484A300505BBA75175DD520A207 7C444012BEE02DD261FBD670FDDC9810C616ED389FF87BC491DB2A75412A555C AB6436DCE45AFF302B1A83843223734A7B2DA271FCAD683CC20AB0D5315DCFB8 40BFCA5A5DCFE16E6A58B4B56A4AA5AC5C00E6D26B955E7D56D3FE887049BC62 282BD6089EE092DBE0AFDD0C7FB468A339837D91247C2B60519552FFD54ED3E4 508A9599C43CB83E6EB8BF7B4A512DD50E0E0E47240C6E471B14B34CED64C80B EED5923A2E86DABFFA4567E985B0A66BBAD885BA0196E244BEE2CDB05DD8892F B9688C5336C2DEA7E1FFA52FD5558AA9F5504706DA846BCC5D5B58034BCB75DC DE45DE0CAA4A32CA9A67CCE1D583AB6B0B1EE58BB181E71024CFD11C5656E7CA 8BAE2816B62A5E18D9D24DA27B82FB276AA41BAC7B6DB0AAFA78438AC88DEEE8 850BE906BB47FF97ECDEA1B0A6B17D1B82F380C4647988F4BA2D7B308E585DF7 92E03FBEBEC1CABCA79EE7CFABEAA0C0D3980338E42425B211E1F67B2FAFE2E9 2CF480F4F4B0B79ADE5AAEBC41CEB730FDE59B61A0F43A60B4710A97E56BE4B6 B5DD7AC1A2253877EB6D49FCE37D56EDD825CDD8EEBEDA5E185AFDB8D6629E3B D3A3DCF90B6ABED51B5E529E9BBC85C567385BE7934CCBF2EEDC7B0E0E5ABDEE 1BF35462B9680B80623CEDAD9E8BBBA54EC36A4CC5915EEBF34EEFDCBE4E1916 057591CD48C47BB53CBCF02EF0C806A9EADEEEC27AEAD99EEA0BCFF0DCAEEE93 669147A415C574D3CDABEE528BE5E62AC70166E2E5DEDC340FE6EFA0AE009666 B2664E52D657FF3833CDE60EBA584EEACB7BF1ED74B8B58CF43C2BECA1C0F41E 6533CE05EBE1422752761F10DDF023AEE5836BE7F07EE2B5BAD53B0DEC8C20D9 395CAC4E8583A9365063B2C6BDE0D2546FBBD41EB18D2EC727EED6149BF4C841 B1408C794E10D88782DA5246BAD24CF78DFBF668FAB55B2FCD56CFF579D5CFAD 7D09789FF7C55A524F951FD5D51C2944C5C984F999DFEE900EF42C0BF4ACEDF8 AEDD1D8E3FD050202CB9D16B6A3BB8E30BFB83BCF99ECFB2C77FAB35BCFBB9DF F8BB3F69AF0B5B26A9BE687AC8B09FDB8775F929A6FC946CC5752FB6F4ACF4FB B0FBA51C057B6DC8B6D1F283DBC95ABDFDB67AF1945CB5097F9EF47FC3E23FFE BBEF4DE374B7FF8E0B028938268CA91890BA42868BB83132CF8A42C7699E4295 5FAD7EC221B1683C2293000A05907C42A3D2E98F65ED1986898189541A991E3C EB2E47ABE1622C5750A8A2C2E3C765536EBFDFAFAC0A42C82094309074053220 E8B5949D2DC2B021F6E045DED139495A5E123DBE25FC1888283C088A30280886 A1E8BD30C2303AEEED61C63E51CAD64A6AAA70422024D0948E3C943204A3A6B6 2AE65855D93213D136434FE1B6F4F15223FC966007CF8C5D192C96955D459757 3C9BA71B4D27180826CE8496DC60777B93D98B27B741AADBA2FB0BE803978107 EDE0810B45AA95267D3AF6BD11C80CA04475D35AAC00F7E20137558D1AEA7B54 F11F934A23FDFF4D1BF3E2C50D191A5DA5DAA1E9642D8A34CB1154D908DCCE71 2031CEBC89C9A650683955ACE4E9F022D3A296883A6506F2A119473E99068D3A A9A4D6740D7B5275A506EBB4AE76A09A95F548A9D8B164DFA68583366EAC983B C9BC253BB01FDD595CFB1AFD26332FE17E7C01CFF98B58AA60B77B0B975D1C65 AEE4483161EEAD02D730ACCA4A147BAE7BD95BA6BC433A87364239B59CD1A835 632D1291B56AD0B46F5D7E0DFBE26D2AAB7B4BCBDDA6B4B2DDC0A5FC3E0E652D E975C595C7490E3D49D323BAA74FB68D3D0EEFED35B57BA7A28C5CF858D2CBA3 1F793E3D7B7FEBDBC38FF63E3EFDEF75EAE397383F3FFFADF7FB0308CD7E0112 08C580052258D2DB7F0932E89F490D42281778115288C4811516782186016AB8 617F1D7A981F8821D6372289F19978627B29AA981E8B2D96F7228CDEC9382376 35DA081D8E391EB7238FBDF9F8236D410A991A91457A7624929229B924624D3A D9179451C6352595665979A556596AE914975D0AF52598348939A67A139AC95E 99690AB4269BEEA1F966786ECA690E9D75CA17279ED3DDB9E7447AFAD923A081 0259120087229AA8A28B32DAA8A38F421AA9A493525AA9A597629AA9A54C70DA A9A79F821AAAA8A3925AAAA9A7A29AAAAAABB2DAAAAB148400003B} end object Image2: TImage Left = 8 Top = 8 Width = 217 Height = 41 Picture.Data = { 0A544A504547496D616765CF560000FFD8FFE000104A46494600010201004800 480000FFE10BD84578696600004D4D002A000000080007011200030000000100 010000011A00050000000100000062011B0005000000010000006A0128000300 00000100020000013100020000001B0000007201320002000000140000008D87 69000400000001000000A4000000D00000004800000001000000480000000141 646F62652050686F746F73686F702043532057696E646F777300323030363A30 353A31382030323A30323A3339000000000003A001000300000001FFFF0000A0 02000400000001000000D6A00300040000000100000028000000000000000601 0300030000000100060000011A0005000000010000011E011B00050000000100 00012601280003000000010002000002010004000000010000012E0202000400 00000100000AA20000000000000048000000010000004800000001FFD8FFE000 104A46494600010201004800480000FFED000C41646F62655F434D0002FFEE00 0E41646F626500648000000001FFDB0084000C08080809080C09090C110B0A0B 11150F0C0C0F1518131315131318110C0C0C0C0C0C110C0C0C0C0C0C0C0C0C0C 0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C010D0B0B0D0E0D100E0E10140E0E 0E14140E0E0E0E14110C0C0C0C0C11110C0C0C0C0C0C110C0C0C0C0C0C0C0C0C 0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0CFFC0001108001E00A003012200 021101031101FFDD0004000AFFC4013F00000105010101010101000000000000 00030001020405060708090A0B01000105010101010101000000000000000100 02030405060708090A0B1000010401030204020507060805030C330100021103 04211231054151611322718132061491A1B14223241552C16233347282D14307 259253F0E1F163733516A2B283264493546445C2A3743617D255E265F2B384C3 D375E3F3462794A485B495C4D4E4F4A5B5C5D5E5F55666768696A6B6C6D6E6F6 37475767778797A7B7C7D7E7F711000202010204040304050607070605350100 021103213112044151617122130532819114A1B14223C152D1F0332462E17282 92435315637334F1250616A2B283072635C2D2449354A317644555367465E2F2 B384C3D375E3F34694A485B495C4D4E4F4A5B5C5D5E5F55666768696A6B6C6D6 E6F62737475767778797A7B7C7FFDA000C03010002110311003F00AFF56FEB9E 5F46EB97B7A85F6E474CC8B9F5DFEABDD61A61EF6D79157A8E7B9B5B3FC3D6DF F07FA4FF0006BD6D8F63D8D7B1C1CC7005AE0641078734AF1CE8FF0056DFD7D9 D7998D1F6FC3B9B6E2CE81F2FC8F571DDFF1CD67B3FE17F90B73FC5C7D6C3458 DFAB9D489634B8B305F66858F07DFD3EDDDF476BBFA3EEFF00C2FF00E8D1284D D7733319FE343A7633322D663BC505F436C78AC9232BE9D21DE93BF9B67E62EB FAE7D65E8BD01B4BBAADE71C64970AA18F7C9600E7FF0032CB36FD25C5F5FF00 FF002AFD2FFAB8FF009331747F5DBEB074EE898F8AECBC06F51BB21EE6E3D4F0 D0D6ED01D63DD658CB7D3FCCFA15A4947FF8E6FD4AFF00B9E7FED9BBFF0048A4 7FC677D4A027EDE7FED8BBBFFD65617FCEDCAFFE721DFE63FF00F91CA0FF00AE F898CFACF54FAA630F1EC76D363DA279F77A75E461E336DD9F4B6FA89521DDFF 001977E463FD5AF531EDB28B3ED150DF53DD5BA097070DF596B957FF0017BF5B CF54C7FD91D46CDDD4719BFA2B1DCDF5374DD3F9D914FF0087FF00B7917FC696 BF554C7FDC8A75F995C4F56E8799D270BA4FD67E985D553753458F7B35F43276 35BB8FFDD6CCFF00CF8FB29FF0F5A5D14FB0E4FF0047B7B7B1DA8F82E13FC51E 66665E067BF2F22DC8735F486BAEB1F6100D7BBDA6D73F6FB8AE87EADFD65C7F AC5D19F90D02BCBA9A59998E3F31F07DCD9F77A177D3A5FF00FA32BB1733FE26 FF00E4EEA1FF001947FE7A6A497A3CDFAFBF5570732EC2CACC2CC8C777A76B05 373A1C35DBBABA9CC77283FF008E4FD4DFFB9CEFFB62FF00FD20B5B2BA27D5FB 1D6E5E660E239C65F75F6D55CE9CBECB1EDFFA4E5C7754FAD5FE2E709E6AC4E9 74751B78FD063D419A48D2EB5AC6BFFEB5EA24A7A4E9BF5E3EACF54CEABA7E0E 59B72AEDDE9D66AB593B1A6C7FBEDA98CFA0DFDE5CE7F8D7CBCDC67F4AFB264D D8C5DF6893558F60247A0585EDADCDDFB3F96A3F567EB1E265FD67C5C1ABEAEE 374A7BD963BD5DA05ED6FA66C6167E831F67AADFFC0D4FFC68061EA3F575B637 731D90F6BDA7BB5CFC463DBFDA6392EA87AAFAAFD719D77A2E3E7886DC47A792 C1F9B733DB737FABFE12BFF827B11BAF757A3A2F49C9EA576A2864B19C17BCFB 6AA87FC65876AE0BEA9E55BF55BEB8E5FD5DCB318B9960652E3C6F20BF06EFFD 09A3F56B3FEEC32AAD5AFAED9377D60FACDD3FEA96238FA7558DB735C3B123D4 74FF00E16C4DF67FC75F4A55AA507F8B0EA1D4737ADF50766E55B905D436C22C B1CE607BAC76FF004AB7B9CDADBFBBB3F31761D5BEB8FD5CE8D9670FA9659A32 0305859E95AFF6BA76BB7D3558CFCDFDE5C7FF008B30C6FD67EB4DAC6DADA1CC 637C1ADC8B995B7FB2C6A375AAAABBFC6AF4EAAE636CADD4B7731E039A7F4798 756BBF941243BBFF008E5FD49FFCB1FF00C0323FF482BFD2FEB7FD5BEAF78C7C 0CE6597BA76D2E0EA9EE8E7D3AF21953ECFEC2B9FB1BA3FF00DC1C6FFB699FF9 15E73F59FA774DFF009F9D2B07A154CA6F16D2ECA6638DAD658DB1B76FD95FB6 BB2BC3AADB6ED9F99E9FA9FCE2497FFFD0D3FF0015FF00F2A75FFF008D67FE7C CA51FF0018FF00547E9FD61E9CC20B46EEA15D720C378CFAF6FD1B2AFF000FFC 8FD3FF00837A37F8B5A5B5F53EBA45D5DDBAC648AFD496FBF27E9FAD4D0DFF00 B6FD45DEBB6ED3BA36C6B3C479A3D54F8F74AEAD7F58FAE3D072F275C967A58F 7D9DAC756DC92DBE3F37D4AED6FA9FF08BA0FF001B7C746FF8EB7F254B230713 A0B3EBD605BD0B36AB701D93BEBA36DAD731DB6D6D94D0EF43D0B28FF0943FD6 FE6FF47FE8D6FF00F8D2C6C7BE8E98E7E5D58D7D773FD1AEE6D85B64866EFD26 3D591E9BAB77A7FCE3363D243DD2F3EFF1BFFD03A6FF00C759FF00508BF64FF1 B9FF007370FEEAFF00F79961FD6AC1FAD5633119F5B7A8E2538A6D3E9581AE73 818FD36CAF131773DDE97FA4F4D8904BD4FF008D0FFC4A9FFC314FE55A7F5771 31B33EA7F4FC4CAAC5D8F7E154CB6B7EA1CD731B2150FF001975B6CFAB05AEB1 948FB453EFB77EDE7FE06BBECFFC0D6B7D56686FD5AE96D0E0F0316901CD9DA7 D8DF7377B6B7FF009CC494F9AE4E3750FA85F599AE66FBB0AE0E159260646313 1663D8EFFB978DB99EFF00DFF4EEFE6EFB2B5BBFE2819B30BA9B2676DD5367E1 505D1FD76A7A15DD0DF575BBC62D4F7B463640697BD97EBE93E9AEB0FB1EEFA7 EA31BFE03D5DFF00A3587FE2AA96D58DD500BEAC826FAE5D4FA9B44571FF006A 2AC777BBE925D14D3EB56E77D73FADB67D5BAAE763749E9E49CADBCBCD65ADB6 C70FA2F77AD67A18CC7FE8D9FA4C9D8F5DAF48FABBD1BA35619D3F1595380F75 C46EB5DE765EF9B5DFE72F3F1D3F207D6ECCBBEA6754A5D98F7DCEBF1ADAED66 CF7FEB753ED38F7635D47DA7F9BFE6FDFF0041EBA3167F8D38FE6BA4FDF6FF00 E492439AEFFF002C0DFF0088FF00DD752FF1A1FF00287D5DFF00C347FF003E62 2ABD26BEA87FC64D37759B711BD47D170B31F1BD5236FA2E1596FA957A5F43E9 FEB1BD5DFF001975B5FD47EAF136B2BDB92480FDF2EFD26268CF4EBB1BBBFE33 D3494BFF008D1E8AEB7131FAF6388BB00865EE1A1F49CE0EAADFFD06C8FF00CF D6A9FF008B5E936BEBCAFACB9D3665F527B854F7000FA7BB75D6ED6FD1FB4DED FF00B6E8A7D35D8751FB17ECFCAFDA1B7EC5E8D9F6ADFF0047D2DAEF5F7C7E6F A5B92E9DF62FD9F8BFB3F6FD8BD1AFECBB3E8FA5B5BE86C9FCDF4F6A5D12F9EF F8B3FF00C53F5CFEDFFEDCDEA3F5B73ECE9DFE3171B3EAC6B335F8B8EC7FD9E9 04BDDB9B934FE632DDBFCE6EFA08FF00E2EA9657F59BACB9B7556EFF005096D7 EA4B7F58B74B3D5A6967F98FB1743D79BF5F0F50FF00203B09B83E9B7FA44EFF 00525DBFE8B5DEDFA0921C37F51FF197F5801A70F099D1315FA1BEC25B641FE5 D9BAE6FF00D6713D5FF85AD6EFD55FA9783F5783B21D61CCEA57022ECB78D7DC 773DB4B497EC6BDDFCE39CF7DB6FF84B16706FF8D80E04BBA5B8784BE3FEA02B 9D3C7F8C619D47ED13D30E16F1F68F44DBEA6CFCEF4F7B1ADDC925FFD9FFED10 9E50686F746F73686F7020332E30003842494D04250000000000100000000000 00000000000000000000003842494D03ED000000000010004800000001000200 480000000100023842494D042600000000000E000000000000000000003F8000 003842494D040D000000000004000000783842494D0419000000000004000000 1E3842494D03F3000000000009000000000000000001003842494D040A000000 00000100003842494D271000000000000A000100000000000000023842494D03 F5000000000048002F66660001006C66660006000000000001002F6666000100 A1999A0006000000000001003200000001005A00000006000000000001003500 000001002D000000060000000000013842494D03F80000000000700000FFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF03E800000000FFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFF03E800000000FFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFF03E800000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFF03E800003842494D040000000000000200003842494D040200 000000000200003842494D040800000000001000000001000002400000024000 0000003842494D041E000000000004000000003842494D041A00000000034900 000006000000000000000000000028000000D60000000A0055006E0074006900 74006C00650064002D0031000000010000000000000000000000000000000000 0000010000000000000000000000D60000002800000000000000000000000000 0000000100000000000000000000000000000000000000100000000100000000 00006E756C6C0000000200000006626F756E64734F626A630000000100000000 0000526374310000000400000000546F70206C6F6E6700000000000000004C65 66746C6F6E67000000000000000042746F6D6C6F6E6700000028000000005267 68746C6F6E67000000D600000006736C69636573566C4C73000000014F626A63 00000001000000000005736C6963650000001200000007736C69636549446C6F 6E67000000000000000767726F757049446C6F6E6700000000000000066F7269 67696E656E756D0000000C45536C6963654F726967696E0000000D6175746F47 656E6572617465640000000054797065656E756D0000000A45536C6963655479 706500000000496D672000000006626F756E64734F626A630000000100000000 0000526374310000000400000000546F70206C6F6E6700000000000000004C65 66746C6F6E67000000000000000042746F6D6C6F6E6700000028000000005267 68746C6F6E67000000D60000000375726C54455854000000010000000000006E 756C6C54455854000000010000000000004D7367655445585400000001000000 000006616C74546167544558540000000100000000000E63656C6C5465787449 7348544D4C626F6F6C010000000863656C6C5465787454455854000000010000 00000009686F727A416C69676E656E756D0000000F45536C696365486F727A41 6C69676E0000000764656661756C740000000976657274416C69676E656E756D 0000000F45536C69636556657274416C69676E0000000764656661756C740000 000B6267436F6C6F7254797065656E756D0000001145536C6963654247436F6C 6F7254797065000000004E6F6E6500000009746F704F75747365746C6F6E6700 0000000000000A6C6566744F75747365746C6F6E67000000000000000C626F74 746F6D4F75747365746C6F6E67000000000000000B72696768744F7574736574 6C6F6E6700000000003842494D042800000000000C000000013FF00000000000 003842494D041100000000000101003842494D04140000000000040000000338 42494D040C000000000ABE00000001000000A00000001E000001E00000384000 000AA200180001FFD8FFE000104A46494600010201004800480000FFED000C41 646F62655F434D0002FFEE000E41646F626500648000000001FFDB0084000C08 080809080C09090C110B0A0B11150F0C0C0F1518131315131318110C0C0C0C0C 0C110C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C010D 0B0B0D0E0D100E0E10140E0E0E14140E0E0E0E14110C0C0C0C0C11110C0C0C0C 0C0C110C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0CFF C0001108001E00A003012200021101031101FFDD0004000AFFC4013F00000105 01010101010100000000000000030001020405060708090A0B01000105010101 01010100000000000000010002030405060708090A0B10000104010302040205 07060805030C33010002110304211231054151611322718132061491A1B14223 241552C16233347282D14307259253F0E1F163733516A2B283264493546445C2 A3743617D255E265F2B384C3D375E3F3462794A485B495C4D4E4F4A5B5C5D5E5 F55666768696A6B6C6D6E6F637475767778797A7B7C7D7E7F711000202010204 040304050607070605350100021103213112044151617122130532819114A1B1 4223C152D1F0332462E1728292435315637334F1250616A2B283072635C2D244 9354A317644555367465E2F2B384C3D375E3F34694A485B495C4D4E4F4A5B5C5 D5E5F55666768696A6B6C6D6E6F62737475767778797A7B7C7FFDA000C030100 02110311003F00AFF56FEB9E5F46EB97B7A85F6E474CC8B9F5DFEABDD61A61EF 6D79157A8E7B9B5B3FC3D6DFF07FA4FF0006BD6D8F63D8D7B1C1CC7005AE0641 078734AF1CE8FF0056DFD7D9D7998D1F6FC3B9B6E2CE81F2FC8F571DDFF1CD67 B3FE17F90B73FC5C7D6C3458DFAB9D489634B8B305F66858F07DFD3EDDDF476B BFA3EEFF00C2FF00E8D1284DD7733319FE343A7633322D663BC505F436C78AC9 232BE9D21DE93BF9B67E62EBFAE7D65E8BD01B4BBAADE71C64970AA18F7C9600 E7FF0032CB36FD25C5F5FF00FF002AFD2FFAB8FF009331747F5DBEB074EE898F 8AECBC06F51BB21EE6E3D4F0D0D6ED01D63DD658CB7D3FCCFA15A4947FF8E6FD 4AFF00B9E7FED9BBFF0048A47FC677D4A027EDE7FED8BBBFFD65617FCEDCAFFE 721DFE63FF00F91CA0FF00AEF898CFACF54FAA630F1EC76D363DA279F77A75E4 61E336DD9F4B6FA89521DDFF001977E463FD5AF531EDB28B3ED150DF53DD5BA0 97070DF596B957FF0017BF5BCF54C7FD91D46CDDD4719BFA2B1DCDF5374DD3F9 D914FF0087FF00B7917FC696BF554C7FDC8A75F995C4F56E8799D270BA4FD67E 985D553753458F7B35F4327635BB8FFDD6CCFF00CF8FB29FF0F5A5D14FB0E4FF 0047B7B7B1DA8F82E13FC51E66665E067BF2F22DC8735F486BAEB1F6100D7BBD A6D73F6FB8AE87EADFD65C7FAC5D19F90D02BCBA9A59998E3F31F07DCD9F77A1 77D3A5FF00FA32BB1733FE26FF00E4EEA1FF001947FE7A6A497A3CDFAFBF5570 732EC2CACC2CC8C777A76B05373A1C35DBBABA9CC77283FF008E4FD4DFFB9CEF FB62FF00FD20B5B2BA27D5FB1D6E5E660E239C65F75F6D55CE9CBECB1EDFFA4E 5C7754FAD5FE2E709E6AC4E974751B78FD063D419A48D2EB5AC6BFFEB5EA24A7 A4E9BF5E3EACF54CEABA7E0E59B72AEDDE9D66AB593B1A6C7FBEDA98CFA0DFDE 5CE7F8D7CBCDC67F4AFB264DD8C5DF6893558F60247A0585EDADCDDFB3F96A3F 567EB1E265FD67C5C1ABEAEE374A7BD963BD5DA05ED6FA66C6167E831F67AADF FC0D4FFC68061EA3F575B637731D90F6BDA7BB5CFC463DBFDA6392EA87AAFAAF D719D77A2E3E7886DC47A792C1F9B733DB737FABFE12BFF827B11BAF757A3A2F 49C9EA576A2864B19C17BCFB6AA87FC65876AE0BEA9E55BF55BEB8E5FD5DCB31 8B9960652E3C6F20BF06EFFD09A3F56B3FEEC32AAD5AFAED9377D60FACDD3FEA 96238FA7558DB735C3B123D474FF00E16C4DF67FC75F4A55AA507F8B0EA1D473 7ADF50766E55B905D436C22CB1CE607BAC76FF004AB7B9CDADBFBBB3F31761D5 BEB8FD5CE8D9670FA9659A320305859E95AFF6BA76BB7D3558CFCDFDE5C7FF00 8B30C6FD67EB4DAC6DADA1CC637C1ADC8B995B7FB2C6A375AAAABBFC6AF4EAAE 636CADD4B7731E039A7F4798756BBF941243BBFF008E5FD49FFCB1FF00C0323F F482BFD2FEB7FD5BEAF78C7C0CE6597BA76D2E0EA9EE8E7D3AF21953ECFEC2B9 FB1BA3FF00DC1C6FFB699FF915E73F59FA774DFF009F9D2B07A154CA6F16D2EC A6638DAD658DB1B76FD95FB6BB2BC3AADB6ED9F99E9FA9FCE2497FFFD0D3FF00 15FF00F2A75FFF008D67FE7CCA51FF0018FF00547E9FD61E9CC20B46EEA15D72 0C378CFAF6FD1B2AFF000FFC8FD3FF00837A37F8B5A5B5F53EBA45D5DDBAC648 AFD496FBF27E9FAD4D0DFF00B6FD45DEBB6ED3BA36C6B3C479A3D54F8F74AEAD 7F58FAE3D072F275C967A58F7D9DAC756DC92DBE3F37D4AED6FA9FF08BA0FF00 1B7C746FF8EB7F254B230713A0B3EBD605BD0B36AB701D93BEBA36DAD731DB6D 6D94D0EF43D0B28FF0943FD6FE6FF47FE8D6FF00F8D2C6C7BE8E98E7E5D58D7D 773FD1AEE6D85B64866EFD263D591E9BAB77A7FCE3363D243DD2F3EFF1BFFD03 A6FF00C759FF00508BF64FF1B9FF007370FEEAFF00F79961FD6AC1FAD5633119 F5B7A8E2538A6D3E9581AE73818FD36CAF131773DDE97FA4F4D8904BD4FF008D 0FFC4A9FFC314FE55A7F577131B33EA7F4FC4CAAC5D8F7E154CB6B7EA1CD731B 2150FF001975B6CFAB05AEB1948FB453EFB77EDE7FE06BBECFFC0D6B7D56686F D5AE96D0E0F0316901CD9DA7D8DF7377B6B7FF009CC494F9AE4E3750FA85F599 AE66FBB0AE0E1592606463131663D8EFFB978DB99EFF00DFF4EEFE6EFB2B5BBF E2819B30BA9B2676DD5367E1505D1FD76A7A15DD0DF575BBC62D4F7B46364069 7BD97EBE93E9AEB0FB1EEFA7EA31BFE03D5DFF00A3587FE2AA96D58DD500BEAC 826FAE5D4FA9B44571FF006A2AC777BBE925D14D3EB56E77D73FADB67D5BAAE7 63749E9E49CADBCBCD65ADB6C70FA2F77AD67A18CC7FE8D9FA4C9D8F5DAF48FA BBD1BA35619D3F1595380F75C46EB5DE765EF9B5DFE72F3F1D3F207D6ECCBBEA 6754A5D98F7DCEBF1ADAED66CF7FEB753ED38F7635D47DA7F9BFE6FDFF0041EB A3167F8D38FE6BA4FDF6FF00E492439AEFFF002C0DFF0088FF00DD752FF1A1FF 00287D5DFF00C347FF003E622ABD26BEA87FC64D37759B711BD47D170B31F1BD 5236FA2E1596FA957A5F43E9FEB1BD5DFF001975B5FD47EAF136B2BDB92480FD F2EFD26268CF4EBB1BBBFE33D3494BFF008D1E8AEB7131FAF6388BB00865EE1A 1F49CE0EAADFFD06C8FF00CFD6A9FF008B5E936BEBCAFACB9D3665F527B854F7 000FA7BB75D6ED6FD1FB4DEDFF00B6E8A7D35D8751FB17ECFCAFDA1B7EC5E8D9 F6ADFF0047D2DAEF5F7C7E6FA5B92E9DF62FD9F8BFB3F6FD8BD1AFECBB3E8FA5 B5BE86C9FCDF4F6A5D12F9EFF8B3FF00C53F5CFEDFFEDCDEA3F5B73ECE9DFE31 71B3EAC6B335F8B8EC7FD9E904BDDB9B934FE632DDBFCE6EFA08FF00E2EA9657 F59BACB9B7556EFF005096D7EA4B7F58B74B3D5A6967F98FB1743D79BF5F0F50 FF00203B09B83E9B7FA44EFF00525DBFE8B5DEDFA0921C37F51FF197F5801A70 F099D1315FA1BEC25B641FE5D9BAE6FF00D6713D5FF85AD6EFD55FA9783F5783 B21D61CCEA57022ECB78D7DC773DB4B497EC6BDDFCE39CF7DB6FF84B16706FF8 D80E04BBA5B8784BE3FEA02B9D3C7F8C619D47ED13D30E16F1F68F44DBEA6CFC EF4F7B1ADDC925FFD93842494D042100000000005300000001010000000F0041 0064006F00620065002000500068006F0074006F00730068006F007000000012 00410064006F00620065002000500068006F0074006F00730068006F00700020 0043005300000001003842494D04060000000000070008000000010100FFE118 02687474703A2F2F6E732E61646F62652E636F6D2F7861702F312E302F003C3F 787061636B657420626567696E3D27EFBBBF272069643D2757354D304D704365 6869487A7265537A4E54637A6B633964273F3E0A3C783A786D706D6574612078 6D6C6E733A783D2761646F62653A6E733A6D6574612F2720783A786D70746B3D 27584D5020746F6F6C6B697420332E302D32382C206672616D65776F726B2031 2E36273E0A3C7264663A52444620786D6C6E733A7264663D27687474703A2F2F 7777772E77332E6F72672F313939392F30322F32322D7264662D73796E746178 2D6E73232720786D6C6E733A69583D27687474703A2F2F6E732E61646F62652E 636F6D2F69582F312E302F273E0A0A203C7264663A4465736372697074696F6E 207264663A61626F75743D27757569643A63363631323761332D653566302D31 3164612D393934332D653134306430313434383238270A2020786D6C6E733A65 7869663D27687474703A2F2F6E732E61646F62652E636F6D2F657869662F312E 302F273E0A20203C657869663A436F6C6F7253706163653E3432393439363732 39353C2F657869663A436F6C6F7253706163653E0A20203C657869663A506978 656C5844696D656E73696F6E3E3231343C2F657869663A506978656C5844696D 656E73696F6E3E0A20203C657869663A506978656C5944696D656E73696F6E3E 34303C2F657869663A506978656C5944696D656E73696F6E3E0A203C2F726466 3A4465736372697074696F6E3E0A0A203C7264663A4465736372697074696F6E 207264663A61626F75743D27757569643A63363631323761332D653566302D31 3164612D393934332D653134306430313434383238270A2020786D6C6E733A70 64663D27687474703A2F2F6E732E61646F62652E636F6D2F7064662F312E332F 273E0A203C2F7264663A4465736372697074696F6E3E0A0A203C7264663A4465 736372697074696F6E207264663A61626F75743D27757569643A633636313237 61332D653566302D313164612D393934332D653134306430313434383238270A 2020786D6C6E733A70686F746F73686F703D27687474703A2F2F6E732E61646F 62652E636F6D2F70686F746F73686F702F312E302F273E0A20203C70686F746F 73686F703A486973746F72793E3C2F70686F746F73686F703A486973746F7279 3E0A203C2F7264663A4465736372697074696F6E3E0A0A203C7264663A446573 6372697074696F6E207264663A61626F75743D27757569643A63363631323761 332D653566302D313164612D393934332D653134306430313434383238270A20 20786D6C6E733A746966663D27687474703A2F2F6E732E61646F62652E636F6D 2F746966662F312E302F273E0A20203C746966663A4F7269656E746174696F6E 3E313C2F746966663A4F7269656E746174696F6E3E0A20203C746966663A5852 65736F6C7574696F6E3E37322F313C2F746966663A585265736F6C7574696F6E 3E0A20203C746966663A595265736F6C7574696F6E3E37322F313C2F74696666 3A595265736F6C7574696F6E3E0A20203C746966663A5265736F6C7574696F6E 556E69743E323C2F746966663A5265736F6C7574696F6E556E69743E0A203C2F 7264663A4465736372697074696F6E3E0A0A203C7264663A4465736372697074 696F6E207264663A61626F75743D27757569643A63363631323761332D653566 302D313164612D393934332D653134306430313434383238270A2020786D6C6E 733A7861703D27687474703A2F2F6E732E61646F62652E636F6D2F7861702F31 2E302F273E0A20203C7861703A437265617465446174653E323030362D30352D 31385430323A30323A33392B30333A30303C2F7861703A437265617465446174 653E0A20203C7861703A4D6F64696679446174653E323030362D30352D313854 30323A30323A33392B30333A30303C2F7861703A4D6F64696679446174653E0A 20203C7861703A4D65746164617461446174653E323030362D30352D31385430 323A30323A33392B30333A30303C2F7861703A4D65746164617461446174653E 0A20203C7861703A43726561746F72546F6F6C3E41646F62652050686F746F73 686F702043532057696E646F77733C2F7861703A43726561746F72546F6F6C3E 0A203C2F7264663A4465736372697074696F6E3E0A0A203C7264663A44657363 72697074696F6E207264663A61626F75743D27757569643A6336363132376133 2D653566302D313164612D393934332D653134306430313434383238270A2020 786D6C6E733A7861704D4D3D27687474703A2F2F6E732E61646F62652E636F6D 2F7861702F312E302F6D6D2F273E0A20203C7861704D4D3A446F63756D656E74 49443E61646F62653A646F6369643A70686F746F73686F703A63363631323761 322D653566302D313164612D393934332D6531343064303134343832383C2F78 61704D4D3A446F63756D656E7449443E0A203C2F7264663A4465736372697074 696F6E3E0A0A203C7264663A4465736372697074696F6E207264663A61626F75 743D27757569643A63363631323761332D653566302D313164612D393934332D 653134306430313434383238270A2020786D6C6E733A64633D27687474703A2F 2F7075726C2E6F72672F64632F656C656D656E74732F312E312F273E0A20203C 64633A666F726D61743E696D6167652F6A7065673C2F64633A666F726D61743E 0A203C2F7264663A4465736372697074696F6E3E0A0A3C2F7264663A5244463E 0A3C2F783A786D706D6574613E0A202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020200A20202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 20202020202020202020202020202020202020202020200A2020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 202020202020202020202020202020202020202020202020202020200A202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 200A202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020200A20202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 20202020202020202020200A2020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 202020202020202020202020202020200A202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020200A20202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 20202020202020202020202020202020202020202020202020200A2020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 202020202020202020202020202020202020202020202020202020202020200A 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 202020200A202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020200A20202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 20202020202020202020202020200A2020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 202020202020202020202020202020202020200A202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020200A20202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 20202020202020202020202020202020202020202020202020202020200A2020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 20200A2020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 202020202020200A202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020200A20202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 20202020202020202020202020202020200A2020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 202020202020202020202020202020202020202020200A202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020200A20202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 0A20202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 20202020200A2020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 202020202020202020200A202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020200A20202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 20202020202020202020202020202020202020200A2020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 202020202020202020202020202020202020202020202020200A202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020200A20 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020200A20202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 20202020202020200A2020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 202020202020202020202020200A202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020200A20202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 20202020202020202020202020202020202020202020200A2020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 202020202020202020202020202020202020202020202020202020200A202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 200A202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020200A20202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 20202020202020202020200A2020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 202020202020202020202020202020200A202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 2020202020202020202020202020202020202020200A20202020202020202020 2020202020202020202020202020202020202020202020202020202020202020 202020202020202020202020200A3C3F787061636B657420656E643D2777273F 3EFFEE000E41646F626500644000000001FFDB00840001010101010101010101 0101010101010101010101010101010101010101010101010101010101010101 0102020202020202020202020303030303030303030301010101010101010101 0102020102020303030303030303030303030303030303030303030303030303 0303030303030303030303030303030303030303030303FFC0001108002800D6 03011100021101031101FFDD0004001BFFC401A2000000060203010000000000 0000000000070806050409030A0201000B010000060301010100000000000000 0000060504030702080109000A0B100002010304010303020303030206097501 0203041105120621071322000831144132231509514216612433175271811862 912543A1B1F02634720A19C1D13527E1533682F192A244547345463747632855 56571AB2C2D2E2F2648374938465A3B3C3D3E3293866F3752A393A48494A5859 5A6768696A767778797A85868788898A9495969798999AA4A5A6A7A8A9AAB4B5 B6B7B8B9BAC4C5C6C7C8C9CAD4D5D6D7D8D9DAE4E5E6E7E8E9EAF4F5F6F7F8F9 FA110002010302040403050404040606056D0102031104211205310600221341 51073261147108428123911552A162163309B124C1D14372F017E18234259253 186344F1A2B226351954364564270A7383934674C2D2E2F255657556378485A3 B3C3D3E3F3291A94A4B4C4D4E4F495A5B5C5D5E5F52847576638768696A6B6C6 D6E6F667778797A7B7C7D7E7F7485868788898A8B8C8D8E8F839495969798999 A9B9C9D9E9F92A3A4A5A6A7A8A9AAABACADAEAFAFFDA000C0301000211031100 3F002CBF1A3F9BA7C94F873F3B7766F5DF9DADDB1DC7D371F62EFBD93BD3AEB7 BEFF00DD5BA68E9B64D4EF0AA072BB1B0F9DC8CD8AA4CDEDD871D14B0C6A6186 454FB60D07DC9A9A734731C86484A806B8E8B51DD14495A81D7D133A93B5F627 78F5BECFED7EB3DC58EDD3B277C60B1DB830399C5D40A8A6A8A3C8D2C5551A96 D28F1CF12CA15D1D55D4FD40F65AE8C8C5586474608EB228753507A11BDD7AB7 5A14FC24F913F2233FFCFF008F50677BF3B9F35D5B47F2E3E59E121EB8CE76CE FACC6C08F13B593BA67DBD8C8B69D467DF010D3E3171313D2C5F6E634900B0B0 001AB9510CC348AE91E43E5D20AB78B08A9A57FCFD6F8F92CAE2F0D48F5F98C9 5062A86364592B725594F43491B4874A2BD45549142ACEDC004F27D958049A01 53D2E240C9341D264F64F5D0254EFED94187041DD383041B03620D7DC707DDBC 393F80FEC3D6B5A7F10FDBD7BFD2575CFF00CF7FB2BFF42AC17FF57FBF78727F BEDBF61EBDAD7F8875EFF495D73745FEFF00ECAD52B88A31FDEAC15E495880B1 A0FBFBBBB13C01C9F7EF0E4FE03FB0F5ED69FC63F6F487F92992ABC57C71EFEC BE32AEAA8EBB1BD25DA992C7D763AAA5A3ADA5ABA3D899DAAA4ABA1ADA69619E 96AA09A3578A58DD5D1C06560403EF70FF006B15786A1FE1EB521FD3723D0FF8 3AD093F943FF003A3EE4F8D3F22E976E7CA5EE1EC3ED8E86EDAAAC6EDEDCF9BE CADE79DDDF90EB6C9C330A4C36EAC3D7EEACA642A697134C6A4435D4A93C34EB 4E5EA3830B890CA748E6AA2A80E38701F91E912CA6321D8D5282BD7D0D70B9AC 4EE3C46333F82C852E570D99A1A6C962F25452ACD4B5D435912CF4D53048BC34 72C4E08FC8FA1B1F654415241191D2F0430041C1E9BB78876DA1BA96390C3236 DBCE08E6124B0989CE32A82C82585E39A228DCEA46565B5C1079F7B4C3A9F98E B4DF0B7D9D68E9FF0009B8F919F217B8BF9816ECDB9DB1DF1DCFD9BB6F17F1AB B2F3941B7FB07B577B6EFC150E4E9F7E75463682BE8B01B8F3992A2A5A8871D9 59E247450CB1FD2DCFB31BBD25642AA064797CCF492D89212A49E3FE01D6F3B9 4CCE1F074E9579BCAE370F4924A204AACA5752E3E9DE731CB308526AB9618DA5 30C0EFA41BE9463F407D96AAB31A2A927E5D2C242E58803A64FEFF00EC4FF9ED 7697FE84787FFEACF76F0A4FF7DB7EC3D57C48FF008C7ED1D7BFBFDB13FE7B5D A5FF00A11E1FFF00AB3DFBC293FDF6DFB0F5EF123FE31FB475D1EC0D8601277B 6D1000B92772618003FA9BD6F03DFBC297FDF6DFB0F5EF123FE31FB474A98278 2AA086A69A68AA29AA228E7A7A882449A09E09904914D0CB1968E58A58D832B2 92181B8F74208343C7ABF1C8E1D7CDDFE1FF00F348EFEF8CFF00CC6317BB7B5F BE3B877F748D3F6FEF1D85BEF6BEFAEC7DD9BAF6BE2B636E4DC75F836CFD1613 3F5B90C6619B6BB2D3550A8A6803AD3C332A581209C9549BC7882806B8FE54E8 B519942C858D01EBE8FB89CAE3B3B8BC766B11590E431596A1A5C9636BA9DB54 159435B0A5452D4C2C402639A191585C0363CFB2720A9208C8E8C4104023874E 1EF5D6FAD127FE1429FCCE3B3F2FF2C70FF1EFE36F7276175A6DFF008F98BAEC 6EFACD759EFBDD9B2EBB74765E7A7C6D6D762AA65DB396A34C9516CFA0A3A3F1 B906D3544EB7E3D99246208119C0D4F9FCBCBA4458CD3B2AB7628A7E7D6D71FC ABB726E0DDFF00CBA3E1CEE8DD79DCBEE7DC99DE8BD9D93CDEE1CFD7E432999C C64AA695E4AAAFC96472B3D4E42B6AEA2424B492C8C5BEA38B0F692E68677205 063FC03A7EDC110A03C73FE1E8F44B9FC1432490CD9AC4C5342ED1CB14B92A38 E48A443678E48DA60C8EA78208041F6D6963F84F4EEA51F88758FF00BC7B7BFE 77D85FFCFA50FF00D7FF007ED0FF00C27F675AD4BFC43AF7F7936EDC2FF1FC2E A62005FE29437249B00079EE493EFDA1FF0084FECEBDA97F8874F5EEBD5BAFFF D0A5FC9744EFAEF4F915F2636DF5D508CCEE2DA792EF2EC71B7923AB9721B8B0 FB37785455E7F1D86829A3715F988B0D34D53141C332C0FA6EC5549C39019C9F E2E9001E9D5C77F20EFE6C755F133B0E87E2C779E7A47F8F7DA7B8160DAF99C9 4D51241D43D8393ACF0685926D4713B3F73E4AA7FCAE023C34D5F2C954DE38DA A650C4C8B2D1147EAF1FB47A7F2EAC92146C9EC3D7D01E391254496274922911 648E48D83A488E0323A3A92AC8CA6E08E08F65DD2DEBE79DF02E9F4FFC2906A4 DBE9F333E691E7EBC63BBF8F3CFE2DECC9BFB297FD2F490FF690FF00ABD7ADD9 FE7DFC35DBBF3DFE336EEF8D1BAB7AE67AFF0009BBB35B3F3155B97038CA3CBE 4A99B686E4C76E4A7A78A8ABEA2969DD6AE7C72A33170501B806D628E197C172 DA6B823F6F4FCB1F88BA75533D6BCA9FF0960F8C69A84DF363B11A4B82C576BE C08FEA8A46A57CD4AD7239BDFE847FAE542CBA6B4B63935E27FCDD3623D22825 EB9FFD02C5F17BFEF35BB1BFF41AEBDFFEBAFBB7D41FF9463FB4FF009BADE8FF 00868FE5D6487FE12ABF1BEBE65871DF33BB22AE536614F1ECED8F58EFE36D6F 78E973913B218C1B8FC7D6F6E3DD7C70AE2536E411F3FF0063AA343AF1E2E7FD 5F3EB668F9254E297E3177E5286D629FA1FB4E9C3950BA845D7D9D8C3695F4AE AD37B0E07B4B16668FFD30FF000F4FC988DFFD29FF00075F290D81D05BF7B43A BFB9BB6366E3D33588E86FEE6657B0B114BFBB99A5D97BBEB370E36B378C741F AEBF6D6D6AEC5C10E5592E6953270C8C3C7AD90CD500FD43EA47ECCF48545457 ADAD7FE13BBFCDB27846DCF803F23F73B78E1A7FB4F8E7BE371E40BCA501D7FE 88AAEAA6D45E2C606230EE58471D3E9A6F4058C162E1566ACA83F50711EBF3FB 7D7A7A2974B046F84F0EB712DD8356D6DCABF5D5B7F322DFEBE3AA47B40BF12F DBD2A6F85BECEB40EFF84B9C1A7F98D6F87FE9F14FB30FFB7EC6E9A1CFFB7F6B EE7E17FB7A4F07C2BF6FF9075B6BFF00352FE5D3FF000E53D15B63A7D7B51FAA 2A3696FCA2DF74597FEECFF79A9F23574B43578B143594C331896A68529B212C 81D7CA5A4555B2825BDB36D7020326A4AAB0A7579A36902E96A107AD7F5BFE12 6D9A26E3E65630702F7EA69CDDAC35117DD67482DF8F6E2CF6CB5A46D93EA3AA 78737F18EBCBFF000936CC8FAFCCAC5DFF00F11255FD3FD65DE51A7FC9B7FF00 1F7BFA9B7FF7DB7ED1D6FC39BF88741F6E6FF84CCF57EC06A6ABEC9FE645D5BB 130FF754E6BABF71EDDDBBB77C74D0CAD34B253AE73B1B174B35440B0B32ABCD 186B105940BFB7A394070F1DAC848FF57A74CC91923BE651D6E9FD7F82A7DAFB 0F64ED9A4CAA676976EED1DB782A6CDC491C71E629F1186A2C7C3958D229EAA2 44C8474E26016591407E198724B646D4EEC452A49A74B14515456B8EBE4FDBAF A933DD8BD8FF002F337B762FBB97A7723BD7B3F398F485EA27ACDA63BAB03D7F 959A18D11C138EC96FBA09989D2AB186627D3626AD18F19A63FC54FF002F45AC 3F90EB788FF84E4FCE55F921F118FC7EDE99C5AEED5F8BE31DB529D2A66D75D9 CEA3A98746C0CDC6A94F0C11C1888217C498C33C8AB471BB9BCBED2DE26A6F1D 568AC687ED1FE7E955B4A1AB113DC057F2EAD1FF0098AFCBCDBFF087E2376E77 DE5A685F3581DBD3E3362621E511CD9DDF79DB62B6B63A3D2EB3470BE5AAE233 4EAAE29A2065752AA47B62DE2F1650BF8464FD9D3D2BE8527CFCBAF97CF616D5 DFF9AD9986F925BF6BAAF2557DE7DABDC18D872B9052959B8F736C9A7D81B8B7 F67CC5E348E3A7ADC9F6A42AA1490B2C724761A3DAE95C32800703D308852424 F9AFF9FAFA6A7F2920A3F9687C260BF8F8FBB135FF00CB6FB03E7FFACDABDA0B 8FED5FF2FF00074F43FD98FCFF00C27AD273E46FC64C57CC0FE7E5DCBF1AF35B A321B3715DB5F25B7CE1B21B8F17474791AFC5D3E3F6BD56E27A8A7A2AA9A9D2 A24D38B65552EAA49FAFD7DAE8E5D105295A2D7F90E98D1572C0E7511D5D027F C24E7A400B3FCBEED466D4E75275C6D58EEA5895D43F8FBEA7552013C5EDF41E D37D4A7FBEBF9FFB1D38D0331A993F97FB3D023DE7FF000962DC1B1F67E73797 C6EF95F92CE6F2DB786972B8BDB5BDB6547B6E6CDE4291A57A9A7A5DDFB7B734 AD85718D2C6989A390FDC7D5D55815723B888B00D1907EDAFF009075A3148AA4 2BD4754F5D13FCCBFE60BFC28F9B1F1CB39DCBD95B836FFF00A27EB8DF3B2776 D66F7DC93761EC0C9E37E4AF406D0CE6330FBDE5C8B67E976EEE4DB1B9A6A19A 9A3A814FE391804B3C9A95158982CBA7BC3D3ED14E9AFD40DA2BD856BF61AF5F FFD16FFE46F089BF9DB6F48E48A39A0917E5425446EA2552925466534CB135D4 452AEA5B90435CAFB31970971EB51FE11D238F8C5FE98FF83A79FE7F3FCA6A7F 8BDBF723F2DFA276ED47FB2FBD9F9D7FEFF6070F0C9F6FD4DBE72D346A186863 F63B5B79D64C0D24AEA60A0AC8E44670F35227BDC1278C7539FD551FB475A954 C43420EC63FB3AB43FF84F87F36793B9B6E623E107C86DCF0D576DED3C6CE3A5 B78E52A264AEEC7DA18AA533CFB5B20F5566A8DD5B4E9217F1BB5AA2B2863124 BAEA04CECD5C4624D73463871FF3F5789BC2D1139E3C3FCDD541FC105BFF00C2 91ABED62A7E66FCD99631F911B63BE40C89AAFCDF49BFF00B1F6EBB6A864F928 1FE0EA8174C91FCCD7FC3D6D33FCFABB53B13A7FF966775EE9EB0DCF94D9DB9A B739D6FB5DF70E16AA7A1CB5161B71EF8C363B329415F4F514D350CD57452342 6556BAAC840B120862CD55A6EE15A29E9CBA244583C48EB541FE5E3FC8B7B2BF 98F7C7E9BE4A51FC92DBDD7F16437E6E3D9B2E1F746C8CDEF2CB57D46D88F1C2 B33159968B7263E391AA8D6C68A2CE49898961C0F6EB4B1A3156524FCBAF0591 8028C00A747A3FE8139ED6B06FF6733AECBB8FDD0DD399E31DC2923C63FBE97E 2403EBF8FF006DEEBF510FF0375EF0E6FE35EAA4FE7B7C21EE9FE4DBDF9D394F B5FE4549B8378EE8DB6BD9384DE3B0F1B9ED893618E1F3D3E15B195F4D2E5725 4F5F4F535114A0A1775962934BA006C5F8192571A57B7E7D37307489B53777CB AFA1BF6E656B3707C35ECECDE47FE07E6FE32EF4CAD7E9057FCB325D5792ABAA B2B2A95FDE99B8205BFA7B40A00B8503807FF2F4A6B58AA7895FF275A74FFC25 AB0580DDDDEDF2F767EE9C56333DB7772FC7DC662F3781CA431D5506631551BE A8E92B293214132BC35B4AF0D615F50FDAF235BFCE7B5772E554053460F5FF00 0F4CA519846C2A0A7F9BA229FCE0FF009656EDFE5B3F21F19BCBAACEE34F8FDD 879F3B8BA8B79E3A4962ABEB7DD54F5553915D875999A690D5419FC44B4CB578 6A97F1D4D542ACB19714F54FEFD03296328F8BCC75492321043E5E5D6D45FC98 FF009AAD17CF3F8EF9DEAEEDACA6360F937D3FB267A5DDAA523A03D93B428F18 B8EA1EC9A7A0454A486BAAE6061CAC14DFB29568F34491D3CB1286A5886A1344 3F48BD3EC3C7F67A74E46E42F8521FD40B5FB475AF7FFC25CE33FF000E2FBF58 8375F8A7D98031FD2CBFE92BA602347FF36C23051FE23DDEE7FD1FFD3F4E27C1 07D9D7D01DDD6356776544452EEEE42AA2A82599989015540B927803DA0E9DEB 5BFF00E64FFF000A19E9DF8ABB8372F49FC66DBF41DFDDE7839EAB0B9CCD4B59 347D59B13704426864C7575563D9727BD335435213C9458E78E23AB4FDCEAE3D AB4B7552A2E1B4B1150BE64797D9C3A61A52C18454241A57AA90A1EBDFF850FF 00F34568F70E5F71EF8E8BEACCC3D755629737989FE376CD8293214D46F3E3E9 311B6E867ED7CD636A297C6D09AEA6A9A3987D252FABDBBA921AE141FDA7A602 4CD512549FD83ECEAA4FF9967F2E8ED6FE5DDBF3ABB6B770F65E03B3F78F6DEC 7C8EFECBD5EDEFE312D3632B68F7056E26A6965C867025766241252F945598E0 32ACA03448CAD7704BE32863E469FE0E9E8E311EB0052A3AFA7F6D4509B5B6D2 0370980C32823E842E3A985FFDE3D96BFC4DF6F4F8E03AD0D3F9156C1DB1DA5F CD27E64F5B6F7C650E6F686F8E82F945B6772617208D25365B0D99EE6EB5C6E4 682489593CD0CD4F55FB8A480C9C1F6BA5AA7892AF10E3A471D18F8478107A2A 5D5D9BDF5FC913F9B84988DC15D936D83B2F7A55ED2DDD9026B255DF3F1DF7FC F4F3D1672A529228A3CAD4E0B1D352E467A688012663092A06FDBBFBB12B2EA5 03E2CFE7D568D1B231FC38E8F4FF003EFF00953B9BE76FCC2E94F819F1D72326 E6DBFB532FB529FC18E992A31BB87BA3B3696993135B34704B534F5143B2B68E 721792A011E186B6BA375531B7BF220821A38EF735FB00AFF9BADDC032F72F05 34FCF07A49FF00C2833E326CBF87BD2BFCAFBE3E6C4874E1FAEFAEBE4163AB2B 1C059F35B92AAAFA6EBF73EE0AB5477896AB399DAA9EA240842067F4F1EF51B9 91656F2A8EAC574490AF9E93FE4EB6CEFE534BA7F96A7C251FF80F3D7CDFF256 251BFE27DA5BAFEDE4FCBFC03A510FF66BF9FF0087AD4F362476FF008544D728 FCFCABEC797FDBF576E4723F3F81ED57FC473FE93FCDD32BF19FF4FD6F9C4850 59880A0124936000E4924F0001ECBBA55D5097F374FE73BD2DF0EFACB7CF51F4 F6F0C1F61FCAADCB87ADDB786C06DCC95065283AB27CBD2D451CBBBF7E56C495 F478D93031C8B3458F756AAA896486F1AC2D24D1AA8603AD4C828BC73E7FEC74 9E597B1BC3353C3ECEB5A9F8FF00FCB5BB4769FF00277F9E7F30778EC0DD91EE 3ED3EBAE99C1F4DEDA8F19552EED6EA0DBFF0021BA7BB2BB0BB3EAB0314AEF4F 85C9E336CC7908BCA11461F16F562730CAB5656348BAE3B707F1127F6500E938 562AD31190B41FB78F5FFFD2E3FC8D0FFD8EEF7E0FE9FECD2FFBCE4329ED74DC 2E3F2FF08E995E29FEAF2EB7C0ECDEB5D95DC5D7DBC3ABBB1B0549B9B63EFBDB F94DB1B9F075A09832188CBD24B455B016521E2768663A5D48646B11ED12B152 181CF4E9018107875F351FE647F04BB6FF00953FCB2C236D5CD6669B665667A2 EC1F8E5DA9404D2D51A4C16529AAA3C3CD516289BA36554490435CA2EAF4D241 300AB28406511474AAF9F11F3E911564343F97431FF282ECFCAF75FF003BAE8C EDECF63F1B8ACFF6776A77B6FDCFE3F111C898C833BBB3A8BB6B3998968FCB2C D234790C956CB524963EB988FA0F7E90522900E1A7FCA3A710E54FF4BADACFFE 146CBABF95776E736D3BFF00A68FFAFF00F19130A3FE27DA4B6F8DBFD2FF009B A50DF87EDE91BFF09A45D3FCB371A39E7BDBB688BFFC1F6E8FF7B1EF773F1A7F A51FE13D370FFA27FA6FF20EB604F69BA7BAD1ABFE156C97F92FF1709BDBFD05 EE017FC71D855B7FC7E2FED75BFF0065FEDBFC83A60FF6C7FD27F9FADBA37EA7 FCE0EEF44278FF00654B71A1238FF9A43582FF009B7B4FFF00123FDBFF0097AB 9FEC8FFA5FF275A8FF00FC25205FE477CAA6E6E3A536BA0FE96FEFF464FE3EB7 1EDFB8FECFFDB7F90F4D47FDA0FF0049FE5EB703F957F183AABE61F46EF9E84E E1C28CB6D3DE989A8A48EAE014F1E5F6E665627388DCFB7AB2A696B62A0CE60E BB45453CAD148AB220D48C2E0A68A4689C329E9F650E083D7CDA3B53AD3E48FF 00278F9DB434734869B7BF52EE1A6DD9B1B734749554B83ED5EB8CC5557502B8 A586797C781DDD837AAA1C8C2B2BB53CF04D0ACD218C4CC623448951F09E91D5 95B3C475649FF097AF137F319EC4786248223F14BB27C5047E4D14E9FE933A5C 0A74F28D4129BFCDA7E3428F6C5CF03F60FF0009E9C8BE25FCFF00C9D6C35FF0 A0EF9A5BCFE25FC2FA6DB7D6394ABC17617C85DD67ACA8F7262AB168B33B536A A636A331BC33B8AA930CAF49949B194BF634B3A3433534F562A237BC054B3020 62CC470EAF3BE9014713D136FF0084F47F2B6EA1C1F456CBF9D1DC1B628F7C76 D7664D94C9F56D1EE4C7413E27AEB6862B295982C7E73198DA88DE297736E297 1F3D42D539614D412C10C6A8EB23B3D73218A904668282BF98EBD14608563D6D 5488A8AA88AA888A11110055455165555160AAA05801F4F687A7FAD1BBFE1566 85BE4DFC5836E3FD06E7C73F4B8EC2AEFF006F6BFB5D6FFD97FB6FF20E983FDB 1FF49FE7EB776DAC2DB636E03F5182C403FEC31F4FED1B7C4DF6F4F0E03AD1AF FE13DBEAFE70BF28406B14EAAF913230FF00540779F5A46BFEF329F6AAE38CDF 6F4C2FC51FD87AB05FF8537FC196EC7E9FDA1F3576362609B76F4BAD2ECDED15 8A93EE2A72FD639BC915C2E4AAA250CF594BB3773644B4ABC08A86BEA6426C87 DDAD1B556227E63FCBD56E415D328FB0F44E7FE1319F078EF3EC7DF1F39B7D62 E69F0DD732D7F5E74DCD925FDEA8DE794C7A0DF1BA61378E495A8B0B5D151453 A978FCB555B0B2DD4116B8611446207B98E7ECC75B88F88C1FC80E96DFF0ACF5 D5B8BE0BFF00DA93E45FFEE5F4CFFBD7B620F81BED1D7A4FEDE2FF004A7FC9D6 C65FCA7174FF002D6F84C0DBFEC9E3AF4F1F4E711191FEF07DD2E3FB67FCBFC1 D3B17F66BF9FF87AD293E566F1F921D39FCEF3E46F7AFC6CEA8CCF6BF67757F7 F6EFCBED7C2526C3DE9BFF0010D5595DA6704C72387D92EB94AA782933019234 75218A96F49D3ED5A895A35553FA45457A4D58559D9BFB50C69D1DCACD85FF00 0A48FE62694D41BAB2BBFF00A07AB7724F5B918E0C9D761BE37EDDA382459E9A 7C665315B66920EEBAEC63432BC6947944A989C006C5B9F7ED514181A35538F1 3FE5EB60BCB5146D35FB3AB2DF815FF09BBE82F8FB9BC2F68FCA3DD31FC8DECA C6CB0E4E83692E365C5753EDDCADA86ABCD363EAE7A8C9EF5C8526462988AAAB FB58654740D4B78C33276B86A929F17AF9F4E2DBA2F1E1E9D6CA3F6143F63FC3 3ECA93F86FDA7D87F0EFB787EC7EC7C3F6FF0065F69A3EDFED3EDFD1E3D3A347 A6D6E3DA7A9AD6B9E947CBCBAFFFD3167F92F743F78EC9FE71DBBB7AEF3E9EED 8DA7B42A7FD995F1EEEDD1D7FB9F05B56B7F8AD5E524C7FD967B238DA7C7CFF7 6C57C5695BC971A6F7F6613B29898023CBFC3D23881D698FF553ADE7FD97F4B3 A267F3C3E13F55FCF5F8F5BB3A2BB3A8A08E4AE88E5B63EED5A68A5CB6C3DF34 10CDFC0774E1E778DE6A79A92790C73AA11F71492CB03868A5911DD8A5689AA3 81E3D52440EB4F3EB4B8FE557F083E4F7C59FE71FD13B73B4BA7B7ED0E1FAE77 DF6C61B27D8F4FB3F72C9D715D0CDD2DD9F8EC5E670DBC8D19C39C7EE14C9C72 470CB32CF0B4DE2951650CBED43E9F0DF49E22BD311EAC06E21A9FCBADAEBF9D 5FC78ED1F93FFCBB3BABABBA6F05FDE8EC0FBED87BC713B6E3644ADCDD3EC7DE B85DCB94A0C5BB95FF00728F8DC7CAD0283AA575F18FD7EDBB4758E6AB1A0208 E9D994B25071AF5A99FC32F9DBFCDD7F97CF4CC7F1CFA93E1566AA36A63774EE 0DDADFE93BE30FC80CAEE7872BB967A596AE9E49F0BB8F6FD12534DE388C6AB0 1E3D618EBE2F22ABB134AFE7D368E11406343F6746BBFE1F2FF9E40F537C1FDA AAAE27FF00B94FF93178052C8209DCFF00BFFF00D5A25617FE87DD3C35FE1FE7 D5BC55FE2FE5D57D7CA8A9FE695FCDDBBB7A8A4ED2F885BA36EEE7DB7469D6D8 7C9ED4E8DED9EBFD9589C4E7F3B257D4E4F75E637CE4F3B434B0C6ED33B4AF3A 0541609702EA6DCA44D52683EDE9B909929A73D6FF007DB3B76B71FF0015BB33 69C54F5193C8517C7EDE7B763A5A3A79ABAAB215B4DD7392C6A53D2D252C734F 5951573A0548E346791982A82481ED0835983796AFF2F4A08A211F2EB546FF00 84C3749F717557C80F9355DD9FD4BDA1D754995E9BDAB4D8AAEDF5B03766D0C6 E4A74DF06AA5A7A0ABDC58DC6455B56B4CE8FA6247BC62E1B861ED4DC1062143 F8FF00C9D3518224C8FC1FE5EB73AF68BA51D55A7F360FE5BBB2FF0098A7C77C 8ED754C760BBBB604191DC7D2BBF67A795A5C5E7C536AAADAF949E8D1EBDF6A6 F18E04A6AD8A30FA5D61A8543353C2C8A2DE73112A7FB33C7FCFD37226A151F1 0EB5B7FF0084E77C6BEFFE8BFE633D9EBDC3D2DD8FD6F4F8CF8E5DA5B4A6CB6E 9D999EC3EDCABDC54BD9BD45FE4785CFD4C5FC0F2E24A6C6D4490CF4D23A55D3 5A688989D0FB7660A236D26B9E998C96941229DBD5D57F3E7FE5B9D9DF3DFA47 ADF3FD17458FCE76DF47E6F70E4A836864726316BBCF6BEE7A3C7A663118DABA A9531D4D9BA7ACC2D34B4E65318941752F7D3EDBB79150B2B9A29EAF32B1D2C8 323AA2EF867F3E3F9BE7F2DBEBFC5FC6DDCBF03BB1FB4BAC761E5770D3E071FB 8FA77B471F97C4B56D61C8E430983ECAD9F8ECC6DFCC6260CAD4544F119A8AA6 6D550D697C3E24575A18DC921B3F23D35E2CC08A2F6FCC747AC7FC2813F98059 4BFF0028DED040ECC1435377482B78818D2E3A7595D8BB0248B5C7161F5F75F0 221F139AFE5D6FC797F80754A9FCD07BCBE69FF332EC5EB2DFFBA3E05F72F51C DD6BB3329B420C4E1F6076B6E14C85354E42B7706472194C865F636161869E93 D44208C08D10B1637E37A6340A11AA2BD51D9E41565A1CF5F45FDB57FEEE6DFD 41837F04C56A0C862607EC20B868C8063607EAB616FA7B46DF137DBD2D1C075A 52FF0020CEACECCD91FCD9BE48EE0DE5D71BEB6A6072BD5DF2031B8CDC1B8F69 E7B0B83CB6464EEAEB7AE8A9B1395C9525350D74A2869277D3096F40B8E01B2E B920A1A1F4E92C3F1FE5D6E8BD85B0B6AF69EC5DE1D6DBE715167366EFCDB798 DA7BA30D3965872781CF50CF8DCA50CA508611D4D2543A9FF03F91ED123B232B A9EE06BD2A650CA55B81E83FF8E3F1DFAB3E2974CEC9E85E97C1C9B7BAEB60D0 4D4182C7D4553575637DD55CF5F5B5B5F5AEB19ABAFAFADA99259A4D2BADD89B 0F76965799CC8E7B8F558E358D422F01D6B05FF0A8EE9FED9ED6CDFC293D57D5 7D89D9B3E0315F201F32BB0B636E1DE7FC1132359D3471ED955C0636BA4A44C9 49412A445CA8262240F6F4247812E7CC74D483F5A334FC27FC9D5F97F2B1C465 36FF00F2EBF87581CE62B3383CCE13A2F666232B87DC341578BCD637218CA36A 2ABA3C863ABE0A5ACA49A09E065D1222B0503EBF52D4FF00DABFFABCBA722FEC D7F3FF000F54C9F2E3F9C9FF00311F8FFF0028FBBFA7FA73F97055763EC3D91B E6B703B73B0A9FADBBA6BE5DF18CA38A178F38D90DA94B2623222A669E4292C2 4A693F4BDFDB9E1A9543A89C7A8E9B2F22B3008295F43D008FFCFC3F9B3468AD 2FF29FDCB4EAD70B3CDD55F24FC0CC8159C0FF00708BFD96BFD78BFBF2C2878B 7F31D6BC597F83F91E9698EFE7BDFCD2B2547055527F28BEC6AC5640B2CF47D7 9F2226A769872DE32BB15B42E9653A4B3117BDF9F76F013F8BF98EB62571F121 AFD9D1B4EA3FE6CDFCC0B7DFC6AF973DBBBABF96D6FED9FD95D0F45D1957D55D 6353B33B969F21DBEFD99D98766EF2831B8AC86D38371D7B6C6DBA8D9491B1F0 4C123566974C6ACC34D0C63451F893E63C875B12B1D7D86800F2F9F5FFD9} Transparent = True end object SpeedButton1: TSpeedButton Left = 280 Top = 232 Width = 89 Height = 33 Caption = #1047#1072#1082#1088#1099#1090#1100 Flat = True OnClick = SpeedButton1Click end object Label1: TLabel Left = 8 Top = 88 Width = 144 Height = 13 Cursor = crHandPoint Caption = #1056#1077#1076#1072#1082#1090#1086#1088' '#1085#1086#1074#1086#1089#1090#1077#1081' NoNaMe' Font.Charset = DEFAULT_CHARSET Font.Color = clBlue Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [fsUnderline] ParentFont = False OnClick = Label1Click end object Label4: TLabel Left = 8 Top = 144 Width = 118 Height = 13 Cursor = crHandPoint Caption = #1057#1087#1088#1072#1074#1082#1072' '#1087#1086' '#1087#1088#1086#1075#1088#1072#1084#1084#1077 Enabled = False Font.Charset = DEFAULT_CHARSET Font.Color = clBlue Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [fsUnderline] ParentFont = False end object Label2: TLabel Left = 113 Top = 104 Width = 40 Height = 13 Alignment = taRightJustify Caption = #1042#1077#1088#1089#1080#1103':' Font.Charset = DEFAULT_CHARSET Font.Color = clGrayText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] ParentFont = False end object CheckBox1: TCheckBox Left = 8 Top = 244 Width = 249 Height = 17 Caption = #1055#1086#1082#1072#1079#1099#1074#1072#1090#1100' '#1087#1088#1080' '#1079#1072#1087#1091#1089#1082#1077' '#1087#1088#1086#1075#1088#1072#1084#1084#1099 Checked = True State = cbChecked TabOrder = 0 OnClick = CheckBox1Click end object ProgressBar: TProgressBar Left = 8 Top = 266 Width = 361 Height = 3 Min = 100 Max = 3000 Position = 100 Smooth = True Step = 100 TabOrder = 1 end object TimerBlend: TTimer Interval = 30 OnTimer = TimerBlendTimer Left = 328 Top = 8 end object Timer1: TTimer Interval = 3000 OnTimer = Timer1Timer Left = 328 Top = 40 end object Timer2: TTimer Interval = 100 OnTimer = Timer2Timer Left = 328 Top = 72 end end
65.580271
169
0.875815
fc7655363cd84292ccf803700d0928c93010a61b
4,175
dfm
Pascal
Editors/ActorEditor_old/KeyBar.dfm
ixray-team/xray-vss-archive
b245c8601dcefb505b4b51f58142da6769d4dc92
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:19.000Z
2022-03-26T17:00:19.000Z
net.ssa/Editors/ActorEditor/KeyBar.dfm
ixray-team/xray-vss-archive
b245c8601dcefb505b4b51f58142da6769d4dc92
[ "Linux-OpenIB" ]
null
null
null
net.ssa/Editors/ActorEditor/KeyBar.dfm
ixray-team/xray-vss-archive
b245c8601dcefb505b4b51f58142da6769d4dc92
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:21.000Z
2022-03-26T17:00:21.000Z
object frmKeyBar: TfrmKeyBar Left = 253 Top = 400 Align = alTop BorderIcons = [] BorderStyle = bsNone ClientHeight = 21 ClientWidth = 747 Color = 10528425 Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] KeyPreview = True OldCreateOrder = False Position = poScreenCenter Scaled = False PixelsPerInch = 96 TextHeight = 13 object Panel1: TPanel Left = 640 Top = 0 Width = 107 Height = 21 Align = alRight BevelOuter = bvNone Color = 10528425 TabOrder = 0 object Label1: TLabel Left = 5 Top = 4 Width = 25 Height = 13 Caption = 'LOD:' end object Bevel1: TBevel Left = 33 Top = 3 Width = 70 Height = 16 end object seLOD: TMultiObjSpinEdit Left = 35 Top = 4 Width = 67 Height = 14 LWSensitivity = 0.1 ButtonKind = bkLightWave Increment = 0.01 MaxValue = 1 ValueType = vtFloat Value = 1 BorderStyle = bsNone Color = 10526880 TabOrder = 0 OnLWChange = seLODLWChange OnExit = seLODExit OnKeyPress = seLODKeyPress end end object Panel2: TPanel Left = 0 Top = 0 Width = 640 Height = 21 Align = alClient BevelOuter = bvNone Color = 10528425 TabOrder = 1 object Panel3: TPanel Left = 0 Top = 0 Width = 59 Height = 21 Align = alLeft BevelOuter = bvNone Color = 10528425 TabOrder = 0 object stStartTime: TStaticText Left = 3 Top = 4 Width = 55 Height = 16 AutoSize = False BorderStyle = sbsSunken Color = 10526880 Font.Charset = DEFAULT_CHARSET Font.Color = 12582911 Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] ParentColor = False ParentFont = False TabOrder = 0 end end object Panel4: TPanel Left = 59 Top = 0 Width = 522 Height = 21 Align = alClient BevelOuter = bvNone Color = 10528425 TabOrder = 1 object Gradient1: TGradient Left = 0 Top = 0 Width = 522 Height = 21 BeginColor = 6118749 EndColor = 11777977 FillDirection = fdUpToBottom NumberOfColors = 32 Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [fsBold] Caption = ' ' TextTop = 5 TextLeft = 12 Border = True BorderWidth = 1 BorderColor = 8226442 Align = alClient object lbCurrentTime: TMxLabel Left = 1 Top = 6 Width = 520 Height = 14 Align = alBottom Alignment = taCenter AutoSize = False Caption = '...' Color = 10528425 Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] ParentColor = False ParentFont = False ShadowColor = 13158600 ShadowPos = spRightBottom Transparent = True end end end object Panel5: TPanel Left = 581 Top = 0 Width = 59 Height = 21 Align = alRight BevelOuter = bvNone Color = 10528425 TabOrder = 2 object stEndTime: TStaticText Left = 3 Top = 4 Width = 55 Height = 16 AutoSize = False BorderStyle = sbsSunken Color = 10526880 Font.Charset = DEFAULT_CHARSET Font.Color = 12582911 Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] ParentColor = False ParentFont = False TabOrder = 0 end end end end
23.194444
41
0.51497
47c6c659bb54da30a60e3d02973165c152a3f97b
1,747
pas
Pascal
references/jcl/jcl/examples/windows/peimage/ApiHookDemoMain.pas
zekiguven/alcinoe
e55c5368ee8bfe7cd6d92424c29ab07d8a3e844c
[ "Apache-2.0" ]
851
2018-02-05T09:54:56.000Z
2022-03-24T23:13:10.000Z
references/jcl/jcl/examples/windows/peimage/ApiHookDemoMain.pas
zekiguven/alcinoe
e55c5368ee8bfe7cd6d92424c29ab07d8a3e844c
[ "Apache-2.0" ]
200
2018-02-06T18:52:39.000Z
2022-03-24T19:59:14.000Z
references/jcl/jcl/examples/windows/peimage/ApiHookDemoMain.pas
zekiguven/alcinoe
e55c5368ee8bfe7cd6d92424c29ab07d8a3e844c
[ "Apache-2.0" ]
197
2018-03-20T20:49:55.000Z
2022-03-21T17:38:14.000Z
unit ApiHookDemoMain; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) HookBtn: TButton; UnhookBtn: TButton; BeepBtn: TButton; Memo1: TMemo; procedure HookBtnClick(Sender: TObject); procedure UnhookBtnClick(Sender: TObject); procedure BeepBtnClick(Sender: TObject); private { Private declarations } public procedure AddMsg(const S: string); end; var Form1: TForm1; implementation {$R *.DFM} uses JclPeImage, JclSysUtils; var PeImportHooks: TJclPeMapImgHooks; OldMessageBeep: function(uType: UINT): BOOL; stdcall = nil; function NewMessageBeep(uType: UINT): BOOL; stdcall; begin Form1.AddMsg(Format('MessageBeep called, uType = %d', [uType])); Result := OldMessageBeep(uType); end; { TForm1 } procedure TForm1.AddMsg(const S: string); begin Memo1.Lines.Add(S); end; procedure TForm1.HookBtnClick(Sender: TObject); begin if PeImportHooks.HookImport(Pointer(HInstance), user32, 'MessageBeep', @NewMessageBeep, @OldMessageBeep) then AddMsg('MessageBeep hooked ...') else AddMsg(Format('MessageBeep hooking error - %s', [SysErrorMessage(GetLastError)])); end; procedure TForm1.UnhookBtnClick(Sender: TObject); begin if PeImportHooks.UnhookByNewAddress(@NewMessageBeep) then begin @OldMessageBeep := nil; AddMsg('MessageBeep unhooked ...'); end else AddMsg('MessageBeep wasn''t hooked') end; procedure TForm1.BeepBtnClick(Sender: TObject); begin MessageBeep(MB_OK); end; initialization PeImportHooks := TJclPeMapImgHooks.Create; finalization FreeAndNil(PeImportHooks); end.
21.048193
87
0.696623
6a85b2cdb439fe94cf7844aed642736a24b8d3d2
18,687
pas
Pascal
XMLReader.pas
joaogl/LeGame
bddb2778a3baf9226206fa09259b712d85450a34
[ "Apache-2.0" ]
null
null
null
XMLReader.pas
joaogl/LeGame
bddb2778a3baf9226206fa09259b712d85450a34
[ "Apache-2.0" ]
null
null
null
XMLReader.pas
joaogl/LeGame
bddb2778a3baf9226206fa09259b712d85450a34
[ "Apache-2.0" ]
null
null
null
unit XMLReader; interface uses crt, GlobalVariables, FileManager, SysUtils; var statage, s1 : integer; const ALPHA = ['A'..'Z', 'a'..'z']; Function getBlockCode(name : String) : boolean; Function ReadXMLFile(FileFrom : String) : codeFile; Function FilterXMLFile(localCode : codeFile) : codeFile; Function PreInterpretXMLFile(ccode : codeFile) : boolean; Procedure printCode(thecode : codeFile); Procedure printTags(); Function confirmClosingTag(localCode, name : String[250]; ii : integer) : boolean; Function TagReader : boolean; Function analyzer(fromLine, fromChar, toLine, toChar : integer; inSub : boolean; tagID, subTagID : integer) : boolean; implementation // Function to put everything rolling. Function getBlockCode(name : String) : boolean; var f : String; fromFile, t1, t2 : codeFile; i : integer; Begin // Setting the file to read. f := resDirectory + name + '.xml'; // Checking if the file exists if (ExistFile(f)) then writeln(name , ' file found') Else Begin writeln(name , ' file missing.'); writeln('Insufficient data to open game. Closing...'); getBlockCode := false; exit; End; for i := 0 to 10000 do Begin fromFile.code[i] := ' '; t1.code[i] := ' '; t2.code[i] := ' '; End; // Reading the Code from the file fromFile := ReadXMLFile(f); // Filtering the Code (removing comments spaces etc.) t1 := FilterXMLFile(fromFile); t2 := FilterXMLFile(t1); processedCode := t2; // Printing the code without being interpreted. // printCode(t1); // Debug stuff. if (s1 > 0) then writeln(name , ' file successfully loaded to the memory.') else Begin writeln('Failed to load ' , name , ' file.'); getBlockCode := false; exit; End; // Starting to PreInterpret file. writeln('Starting to interpret ' , name , ' file'); if (PreInterpretXMLFile(t2)) then writeln(name , ' file successfully preinterpreted.') else Begin writeln(name , ' file failed to be preinterpreted.'); writeln('Closing...'); getBlockCode := false; exit; End; // Printing the code tags. // printTags; getBlockCode := true; End; // Function to Group and organize the TAGS. Function PreInterpretXMLFile(ccode : codeFile) : boolean; var i, ii, iii, subtagamount, pointer : integer; inTag, inSubTag, done, isFound : boolean; tempName : String; Begin // Setting everything up to run the code. tagamount := 0; subtagamount := -1; inTag := false; inSubTag := false; // Go through all the code lines for i := 0 to s1 do Begin // Reseting the tag name. tempName := ''; // Go through all the characters of the line for ii := 0 to length(ccode.code[i]) do Begin // if it starts by <[char] it means its a XML Tag. if ((ccode.code[i][ii] = '<') AND (ccode.code[i][ii + 1] <> ' ') AND (ccode.code[i][ii + 1] <> '/') AND (not (inTag))) then Begin // Inform the program that this is a tag. inTag := true; // Inform also that we havent got the name of the tag. done := false; // Going again through all the lines this time searching for the name. for iii := (ii + 1) to length(ccode.code[i]) do Begin // If its not done and the next char its a space it means the name is over. if (not(done) AND (ccode.code[i][iii] = ' ')) then Begin // Because the name is over set this to true. done := true; // If we are inside a subTag if (inSubTag) then Begin // Go to the next subTag. subtagamount := subtagamount + 1; // Report now many subtags there are on this tag. tags[tagamount].subAmount := subtagamount; // And register it. tags[tagamount].subTag[subtagamount].name := tempName; isFound := false; pointer := ii + length(tempName) + 2; Repeat if ((ccode.code[i][pointer] in ALPHA) AND (ord(ccode.code[i][pointer]) <> 21) AND (ord(ccode.code[i][pointer]) <> 26) AND (ord(ccode.code[i][pointer]) <> 27)) then isFound := true else pointer := pointer + 1; Until (isFound); tags[tagamount].subTag[subtagamount].fromChar := pointer; tags[tagamount].subTag[subtagamount].fromLine := i; End Else Begin // If its not a subTag register it has a tag. tags[tagamount].name := tempName; isFound := false; pointer := ii + length(tempName) + 2; Repeat if (ccode.code[i][pointer] in ALPHA) then isFound := true else pointer := pointer + 1; Until (isFound); tags[tagamount].fromChar := pointer; tags[tagamount].fromLine := i; End; End Else Begin // if its not done and the next char isn't a space it means we are still inside the name so keep writing it. if not (ccode.code[i][iii] = '<') then tempName := tempName + ccode.code[i][iii]; End; End; End; // If we have reached a /> it means that its the end of a tag. if ((ccode.code[i][ii] = '/') AND (ccode.code[i][ii + 1] = '>') AND (inTag)) then Begin // If we are inside a subTag if (inSubTag) then Begin // Register the end of it. tags[tagamount].subTag[subtagamount].toChar := ii - 1; tags[tagamount].subTag[subtagamount].toLine := i; End Else Begin // If its not a subTag register the end of the tag. tags[tagamount].toChar := ii - 1; tags[tagamount].toLine := i; tagamount := tagamount + 1; End; // After the end of the tag set this to false to inform the program that we left. inTag := false; End // Check if this is the closing tag of our current tag. ex. </Level> else if ((inSubTag) AND (length(ccode.code[i]) > 3) AND (confirmClosingTag(ccode.code[i], tags[tagamount].name, ii))) then Begin // Move to the next tag. tagamount := tagamount + 1; subtagamount := -1; inTag := false; inSubTag := false; End // If the line ends with > it means this tag will have subTags. else if ((ccode.code[i][ii] = '>') AND (inTag) AND not (inSubTag)) then Begin // Register the end of the tag tags[tagamount].toChar := ii - 1; tags[tagamount].toLine := i; // Inform the program that we will join the subTags of this tag. tags[tagamount].hasSub := true; inTag := false; inSubTag := true; End; End; End; // At the end, this program adds a nil array entry so just ignore it. if (tagamount > 0) then tagamount := tagamount - 1; PreInterpretXMLFile := true; End; // Function to confirm that we have a closing Tag of a certain tag. Function confirmClosingTag(localCode, name : String[250]; ii : integer) : boolean; var i, char, startpoint : integer; good : boolean; Begin // if the name of the tag is not empty. if (length(name) > 0) then Begin // Char will act has stages for our code to be interpreted. char := 0; // Is this closing tag still usable? start it with yes until something tells u the opposit. good := true; // Go through all the charaters again. for i := ii to length(localCode) do Begin // if we are still in the first stage and we find the < char move to the next stage. if ((localCode[i] = '<') AND (char = 0)) then char := 1 // if we are still in the second stage and we find the / char move to the next stage. else if ((localCode[i] = '/') AND (char = 1)) then Begin // The next stage will be confirming if the closing tag name is the same as the opening tag name. // For this reason we'll need our current position. startpoint := i; char := 2; End // If the name is the same keep going. else if ((char = 2) AND ((i - startpoint) <= length(name)) AND (localCode[i] = name[i - startpoint]) AND good) then good := true // If not, discard it. else if ((char = 2) AND ((i - startpoint) <= length(name)) AND (localCode[i] <> name[i - startpoint]) AND good) then good := false; // if after the name is checked there is a > its the end of our closing tag. if (good AND (char = 2) AND ((i - startpoint) > length(name)) AND (localCode[i] = '>')) then Begin confirmClosingTag := true; exit; End // If there is anything besides a space it will prevent the function from working. else if (good AND (char = 2) AND ((i - startpoint) > length(name)) AND (localCode[i] <> ' ')) then Begin confirmClosingTag := false; exit; End; End; end; confirmClosingTag := false; End; // Function to Read the XML and remove all the unnecessary code. Function FilterXMLFile(localCode : codeFile) : codeFile; var hasSomething, comment : boolean; line, pline, chari, i, ii, ignoreUntil : integer; fCode : codeFile; Begin for i := 0 to 10000 do Begin fCode.code[i] := ' '; End; // Setting the comments to false comment := false; // To read from the first line line := s1; // Reading line by line and removing useless characters. (comments, spaces and empty lines) pline := 0; // From 0 (begining of the file) to line (end of the file) for i := 0 to line do Begin // Does this line contain anything? hasSomething := false; // chari is our character position on the final code array chari := 0; ignoreUntil := 0; // Form 0 to the end of the localCode line. for ii := 0 to length(localCode.code[i]) do Begin // If there is an ENTER it will be ignored if ((localCode.code[i][ii] <> #0)) then Begin // If the first character is a space, ignore it. if not ((chari = 1) AND (localCode.code[i][ii] = #32)) then Begin // If there are two spaces together, ignore them. if not ((localCode.code[i][ii] = #32) AND (localCode.code[i][ii + 1] = #32)) then Begin // If there is a tab if (localCode.code[i][ii] = #9) then Begin // And if its not on the first character. if not (chari = 1) then Begin // Change it to a space fcode.code[pline][chari] := ' '; hasSomething := true; chari := chari + 1; End; End Else Begin // If a comment tag is found set the comment boolean to true if ((localCode.code[i][ii] = '<') AND (localCode.code[i][ii + 1] = '!') AND (localCode.code[i][ii + 2] = '-') AND (localCode.code[i][ii + 3] = '-')) then comment := true; // If a closing comment tag is found set the comment boolean to false if ((localCode.code[i][ii] = '-') AND (localCode.code[i][ii + 1] = '-') AND (localCode.code[i][ii + 2] = '>')) then Begin // Set the ignoreUntil to the end of the comment tag. comment := false; ignoreUntil := ii + 2; End; // If its not a comment if not (comment) then Begin // If the ignoreUntil is = 0 (not set) or if the current character is after the last character of the comment closing tag if ((ignoreUntil = 0) OR (ii > ignoreUntil)) then Begin // If there isnt a tab just write the localCode content to the Final Code array. fcode.code[pline][chari] := localCode.code[i][ii]; hasSomething := true; chari := chari + 1; End Else hasSomething := false; End; End; End; End; End; End; // If there is something on the line move to the next one. if (hasSomething) then Begin pline := pline + 1; End; End; s1 := pline; FilterXMLFile := fcode; End; // Function to Read the XML file. Function ReadXMLFile(FileFrom : String) : codeFile; var F : TextFile; temp : String; line, i : integer; localCode : codeFile; Begin // To read from the first line line := 0; for i := 0 to 10000 do Begin localCode.code[i] := ''; End; // Assigning the file AssignFile(F, FileFrom); // Reading the file try Reset(F); Repeat temp := ''; // Reading line by line Readln(F, temp); // Storing the line inside an array localCode.code[line] := temp; // Going to next line line := line + 1; Until Eof(F); CloseFile(F); except on E: EInOutError do Begin // If it does throw an error, write it writeln('Could not read ', FileFrom); End; End; s1 := line; ReadXMLFile := localCode; End; // Writing the pure Code Procedure printCode(thecode : codeFile); var i : integer; Begin writeln; writeln('== CODE =='); writeln; // Going through all the lines and writing them. for i := 0 to s1 do Begin writeln(thecode.code[i]); End; writeln; writeln('== END OF CODE =='); writeln; End; // Writing the tags Procedure printTags(); var i, ii : integer; Begin writeln; writeln('== TAGS =='); writeln; // Going through all the tags and writing them. for i := 0 to tagamount do Begin writeln(tags[i].name , ' FL: ' , tags[i].fromLine , ' FC: ' , tags[i].fromChar , ' TL: ' , tags[i].toLine , ' TC: ' , tags[i].toChar); // If this tag has subtags, go through them all and write them too. if (tags[i].hasSub) then Begin for ii := 0 to tags[i].subAmount do writeln(' - ' , tags[i].subTag[ii].name , ' FL: ' , tags[i].subTag[ii].fromLine , ' FC: ' , tags[i].subTag[ii].fromChar , ' TL: ' , tags[i].subTag[ii].toLine , ' TC: ' , tags[i].subTag[ii].toChar); End; End; writeln; writeln('== END OF TAGS =='); writeln; End; Function TagReader : boolean; var rti, rtii, si : integer; Begin for rti := 0 to tagamount do Begin if not (analyzer(tags[rti].fromLine, tags[rti].fromChar, tags[rti].toLine, tags[rti].toChar, false, rti, 0)) then Begin TagReader := false; exit; End; if (tags[rti].hasSub) then Begin for rtii := 0 to tags[rti].subAmount do Begin if not (analyzer(tags[rti].subTag[rtii].fromLine, tags[rti].subTag[rtii].fromChar, tags[rti].subTag[rtii].toLine, tags[rti].subTag[rtii].toChar, true, rti, rtii)) then Begin TagReader := false; exit; End; End; End; End; tagReader := true; End; Function analyzer(fromLine, fromChar, toLine, toChar : integer; inSub : boolean; tagID, subTagID : integer) : boolean; var ai, aii, ifrom, ito, currentData, stage : integer; tempname : String; Begin currentData := 0; stage := 0; tempname := ''; for ai := fromLine to toLine do Begin ifrom := 0; ito := length(processedCode.code[ai]); if (ai = fromLine) then ifrom := fromChar; if (ai = toLine) then ito := toChar; for aii := ifrom to ito do Begin if ((ord(processedCode.code[ai][aii]) <> 21) AND (ord(processedCode.code[ai][aii]) <> 26) AND (ord(processedCode.code[ai][aii]) <> 27)) then Begin if ((stage = -1) AND (not (processedCode.code[ai][aii] = ' '))) then stage := 0; if (stage = 0) then Begin if ((processedCode.code[ai][aii] = '=') OR (processedCode.code[ai][aii] = ' ')) then Begin if (inSub) then tags[tagID].subTag[subTagID].data[currentData].name := tempname else tags[tagID].data[currentData].name := tempname; tempname := ''; if (processedCode.code[ai][aii] = '=') then stage := 1; End Else Begin if (processedCode.code[ai][aii] in ALPHA) then tempname := tempname + processedCode.code[ai][aii]; End; End Else if ((stage = 1) AND (processedCode.code[ai][aii] = '"')) then stage := 2 Else if (stage = 2) then Begin if (processedCode.code[ai][aii] = '"') then Begin if (inSub) then Begin tags[tagID].subTag[subTagID].data[currentData].value := tempname; tags[tagID].subTag[subTagID].dataAm := currentData; End Else Begin tags[tagID].data[currentData].value := tempname; tags[tagID].dataAm := currentData; End; currentData := currentData + 1; tempname := ''; stage := -1; End Else tempname := tempname + processedCode.code[ai][aii]; End; End; End; End; analyzer := true; End; end.
36.426901
209
0.524482