forked from pyscripter/python4delphi
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathuCommonFunctions.pas
2377 lines (2120 loc) · 67.1 KB
/
uCommonFunctions.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{-----------------------------------------------------------------------------
Unit Name: uCommonFunctions
Author: Kiriakos Vlahos
Date: 23-Jun-2005
Purpose: Functions common to many units in PyScripter
History:
-----------------------------------------------------------------------------}
unit uCommonFunctions;
interface
Uses
Winapi.Windows,
System.Classes,
System.SysUtils,
System.Diagnostics,
System.RegularExpressionsAPI,
System.RegularExpressionsCore,
System.RegularExpressions,
Vcl.Controls,
Vcl.ComCtrls,
Vcl.Graphics,
Vcl.Forms,
Vcl.Dialogs,
SynEditTypes,
SynUnicode,
SynEdit,
uEditAppIntfs;
const
UTF8BOMString : RawByteString = AnsiChar($EF) + AnsiChar($BB) + AnsiChar($BF);
IdentChars: TSysCharSet = ['_', '0'..'9', 'A'..'Z', 'a'..'z'];
SFileExpr = '(([a-zA-Z]:)?[^\*\?="<>|:,;\+\^]+)'; // fwd slash (/) is allowed
STracebackFilePosExpr = '"\<?' + SFileExpr + '\>?", line (\d+)(, in ([\<\>\?\w]+))?';
SWarningFilePosExpr = '\<?' +SFileExpr + '\>?:(\d+):';
WideLF = WideChar(#10);
WideNull = WideChar(#0);
AnsiLineFeed = AnsiChar(#10);
AnsiCarriageReturn = AnsiChar(#13);
AnsiCrLf = AnsiString(#13#10);
WordBreakString = ',.;:"�`�^!?&$@�%#~[](){}<>-=+*/\| ';
(* returns the System ImageList index of the icon of a given file *)
function GetIconIndexFromFile(const AFileName: string;
const ASmall: boolean): integer;
(* returns long file name even for nonexisting files *)
function GetLongFileName(const APath: string): string;
(* from cStrings *)
(* checks if AText starts with ALeft *)
function StrIsLeft(AText, ALeft: PWideChar): Boolean;
(* checks if AText ends with ARight *)
function StrIsRight(AText, ARight: PChar): Boolean;
(* returns next token - based on Classes.ExtractStrings *)
function StrGetToken(var Content: PChar;
Separators, WhiteSpace, QuoteChars: TSysCharSet): string;
(* removes quotes to AText, if needed *)
function StrUnQuote(const AText: string): string;
(* Lighten a given Color by a certain percentage *)
function LightenColor(Color:TColor; Percentage:integer):TColor;
(* Darken a given Color by a certain percentage *)
function DarkenColor(Color:TColor; Percentage:integer):TColor;
(* Get Exe File Version string *)
function ApplicationVersion : string;
(* Checks whether we are connected to the Internet *)
function ConnectedToInternet : boolean;
(* Extracts the nth line from a string *)
function GetNthLine(const S : string; LineNo : integer) : string;
(* Extracts a range of lines from a string *)
function GetLineRange(const S : string; StartLine, EndLine : integer) : string;
(* Extracts a word from a string *)
function GetWordAtPos(const LineText : string; Start : Integer; WordChars : TSysCharSet;
ScanBackwards : boolean = True; ScanForward : boolean = True;
HandleBrackets : Boolean = False) : string;
(* Format a doc string by removing left space and blank lines at start and bottom *)
function FormatDocString(const DocString : string) : string;
(* Calculate the indentation level of a line *)
function CalcIndent(S : string; TabWidth : integer = 4): integer;
(* check if a directory is a Python Package *)
function DirIsPythonPackage(Dir : string): boolean;
(* check if a directory is a Python Package *)
function FileIsPythonPackage(FileName : string): boolean;
(* Get Python Package Root directory *)
function GetPackageRootDir(Dir : string): string;
(* Python FileName to possibly dotted ModuleName accounting for packages *)
function FileNameToModuleName(const FileName : string): string;
(* Convert < > to < > *)
function HTMLSafe(const S : string): string;
(* Parses command line parameters *)
// From Delphi's system.pas unit! Need to rewrite
function GetParamStr(P: PChar; var Param: string): PChar;
(* Parse a line for a Python encoding spec *)
function ParsePySourceEncoding(Textline : string): string;
(* Version of InputQuery that can be called from threads and executes in the main thread *)
function SyncWideInputQuery(const ACaption, APrompt: string; var Value: string): Boolean;
(* Covert all line breaks to #10 *)
function CleanEOLs(S: AnsiString): AnsiString; overload;
function CleanEOLs(S: string): string; overload;
(* Similar to Delphi's IdentToInt but operating on sorted IdentMapEntries *)
function SortedIdentToInt(const Ident: string; var Int: Longint;
const SortedMap: array of TIdentMapEntry;
CaseSensitive : Boolean = False): Boolean;
(* Used for sorting Python Identifiers *)
function ComparePythonIdents(const S1, S2 : string): Integer; overload;
function ComparePythonIdents(List: TStringList; Index1, Index2: Integer): Integer; overload;
(* Used to get Vista and code fonts *)
function DefaultCodeFontName: string;
procedure SetDefaultUIFont(const AFont: TFont);
procedure SetContentFont(const AFont: TFont);
(* Visual Studio replacement for SynEdits NextWord *)
function VSNextWordPos(SynEdit: TCustomSynEdit; const XY: TBufferCoord): TBufferCoord;
(* Visual Studio replacement for SynEdits PrevWord *)
function VSPrevWordPos(SynEdit: TCustomSynEdit; const XY: TBufferCoord): TBufferCoord;
(* Get the text between two Synedit Block coordinates *)
function GetBlockText(Strings : TStrings; BlockBegin, BlockEnd : TBufferCoord) : string;
(* Extract Error information from a VarPyth variant containing the Python error *)
procedure ExtractPyErrorInfo(E: Variant; var FileName: string; var LineNo: Integer; var Offset: Integer);
(* Get Encoded Ansi string from WideStrings ttaking into account Python file encodings *)
function WideStringsToEncodedText(const AFileName: string;
Lines : TStrings; var EncodedText: AnsiString;
InformationLossWarning: Boolean = False;
IsPython: Boolean = False) : Boolean;
(* Load file into WideStrings taking into account Python file encodings *)
function LoadFileIntoWideStrings(const AFileName: string;
Lines : TStrings): boolean;
(* Save WideStrings to file taking into account Python file encodings *)
function SaveWideStringsToFile(const AFileName: string;
Lines : TStrings; DoBackup : Boolean = True) : boolean;
(* Read File contents. Allows reading of locked files *)
function FileToAnsiStr(const FileName: string): AnsiString;
(* Read File contents into encoded string. Takes into account Python encodings *)
function FileToEncodedStr(const AFileName : string) : AnsiString;
(* Read File contents into Widestring. Takes into account Python encodings *)
function FileToStr(const AFileName : string) : string;
type
TDirectoryWalkProc = reference to function (const Path: string;
const FileInfo: TSearchRec): Boolean;
(*
Directory traversal function. Paths and Masks are semi-colon delimited lists.
*)
procedure WalkThroughDirectories(const Paths, Masks: string;
const PreCallback: TDirectoryWalkProc;
const Recursive: Boolean);
(*
Find files and place them in FileList. Paths and Masks are semi-colon delimited lists.
*)
procedure GetFilesInPaths(Paths, Masks : string; FileList: TStrings; Recursive : Boolean = True);
(*
Find directories and place them in DirList. Paths and Masks are semi-colon delimited lists.
*)
procedure GetDirectoriesInPaths(Paths, Masks : string; DirList: TStrings; Recursive : Boolean = True);
(* Check whether is S is likely to be a number *)
//function WideStrConsistsofNumberChars(const S: WideString): Boolean;
(* Trim certain chars from left of string *)
function StrTrimCharsLeft(const S: string; const Chars: TSysCharSet): string;
(* Trim certain chars from right of string *)
function StrTrimCharsRight(const S: string; const Chars: TSysCharSet): string;
(* Extracts a token and returns the remainder of a string *)
function StrToken(var S: string; Separator: Char): string;
(* Improved CanFocus *)
function CanActuallyFocus(WinControl: TWinControl): Boolean;
(* Create a PCRE Regular Expression and compile it *)
function CompiledRegEx(Expr : string; Options: TRegExOptions = [roNotEmpty];
UCP : Boolean = True): TRegEx;
(* Checks whether S contains digits only *)
function IsDigits(S : string): Boolean;
(* Remove the white space in front of the first line from all lines *)
function Dedent (const S : string) : string;
(* Returns true for dark colors *)
function IsColorDark(AColor : TColor) : boolean;
(* Returns true if the styled clWindows system oolor is dark *)
function IsStyledWindowsColorDark : boolean;
(* Adds formated text to a Richedit control *)
procedure AddFormatText(RE : TRichEdit; const S: string; FontStyle: TFontStyles = [];
const FontColor: TColor = clDefault; FontSize: Integer = 0);
(* Resize Bitmap *)
procedure ResizeBitmap(Bitmap: TBitmap; const NewWidth, NewHeight: integer);
(* Returns string with Desktop size *)
function MonitorProfile: string;
(* Downlads a file from the Interent *)
function DownloadUrlToFile(const URL, Filename: string): Boolean;
(* ExtracFileName that works with both Windows and Unix file names *)
function XtractFileName(const FileName: string): string;
(* ExtractFileDir that works with both Windows and Unix file names *)
function XtractFileDir(const FileName: string): string;
(* Raises a keyword interrupt in another process *)
procedure RaiseKeyboardInterrupt(ProcessId: DWORD);
(* Terminates a process and all child processes *)
function TerminateProcessTree(ProcessID: DWORD): Boolean;
(* Executes a Command using CreateProcess and captures output *)
function ExecuteCmd(Command : string; out CmdOutput: string): cardinal; overload;
function ExecuteCmd(Command : string; out CmdOutput, CmdError: string): cardinal; overload;
(* Checks if a file extension is contained in a file filter *)
function FileExtInFileFilter(FileExt, FileFilter: string): Boolean;
(* Checks if a file name is indicates a Python source file *)
function FileIsPythonSource(FileName: string): Boolean;
(* Simple routine to hook/detour a function *)
procedure RedirectFunction(OrgProc, NewProc: Pointer);
{ Styled MessageDlg (do not use TaskDialog) }
function StyledMessageDlg(const Msg: string; DlgType: TMsgDlgType;
Buttons: TMsgDlgButtons; HelpCtx: Longint): Integer; overload;
function StyledMessageDlg(const Msg: string; DlgType: TMsgDlgType;
Buttons: TMsgDlgButtons; HelpCtx: Longint; DefaultButton: TMsgDlgBtn): Integer; overload;
{Style adjusted svg FixedColor}
function SvgFixedColor(Color: TColor): TColor;
type
(* Extends System.RegularExperssions.TRegEx *)
TRegExHelper = record helper for TRegEx
public
procedure Study;
procedure SetAdditionalPCREOptions(PCREOptions : Integer);
function PerlRegEx : TPerlRegEx;
end;
TMatchHelper = record helper for TMatch
public
function GroupIndex(Index: integer): integer;
function GroupLength(Index: integer): integer;
function GroupValue(Index: integer): string;
end;
(* Helper method for forms *)
TControlHelper = class helper for TControl
public
(* Scale a value according to the FCurrentPPI *)
function PPIScale(ASize: integer): integer;
(* Reverse PPI Scaling *)
function PPIUnScale(ASize: integer): integer;
end;
(*
TSynStringList is a general purpose TStringList descendent that adds
the following features:
- LoadFromFile followed by SaveToFile results in an identical file
- Detects the LineBreak in the read stream and uses it in SaveToStream
- UseBOM is set when reading a stream depending on whether BOM exists
- When reading a file without a BOM it tries to detect whether the e
encoding is UTF8
- Event handler for dealing with information loss in Unicode to ANSI
conversion
*)
TXStringList = class(TStringList)
private
fUTF8CheckLen: Integer;
fFileFormat: TSynEditFileFormat;
fOnInfoLoss: TSynInfoLossEvent;
fDetectUTF8: Boolean;
public
constructor Create; overload;
procedure SetTextAndFileFormat(const Value: string);
procedure LoadFromStream(Stream: TStream; Encoding: TEncoding); override;
procedure SaveToStream(Stream: TStream; Encoding: TEncoding); override;
property FileFormat: TSynEditFileFormat read FFileFormat write fFileFormat;
published
property UTF8CheckLen: Integer read fUTF8CheckLen write fUTF8CheckLen default -1;
property DetectUTF8: Boolean read fDetectUTF8 write fDetectUTF8 default True;
property OnInfoLoss: TSynInfoLossEvent read fOnInfoLoss write fOnInfoLoss;
end;
(*
Multiple Read Exclusive Write lock based on Windows slim reader/writer
(SRW) Locks. Can be also used instead of a critical session.
Limitations: non-reentrant, not "fair"
*)
(*
Interfaced based Timer that can be used with anonymous methods
Developed by : Nuno Picado (https://github.com/nunopicado/Reusable-Objects)
*)
ITimer = interface(IInvokable)
['{1C06BCF6-1C6D-473E-993F-2B231B17D4F5}']
function Start(const Action: TProc): ITimer;
function Stop: ITimer;
function Restart: ITimer;
end;
function NewTimer(Interval: Cardinal): ITimer;
type
(*
Minimalist SmartPointer implementation based on a blog post by Barry Kelly:
http://blog.barrkel.com/2008/11/reference-counted-pointers-revisited.html,
https://stackoverflow.com/questions/30153682/why-does-this-optimization-of-a-smartpointer-not-work
*)
TObjectHandle<T: class> = class(TInterfacedObject, TFunc<T>)
// used by TSmartPointer
private
FValue: T;
public
constructor Create(AValue: T);
destructor Destroy; override;
function Invoke: T;
end;
TSmartPtr = record
class function Make<T: class>(AValue: T): TFunc<T>; static;
end;
Var
StopWatch : TStopWatch;
implementation
Uses
Winapi.UrlMon,
Winapi.CommCtrl,
Winapi.TlHelp32,
Winapi.Wincodec,
System.Types,
System.StrUtils,
System.AnsiStrings,
System.UITypes,
System.IOUtils,
System.Math,
Vcl.ExtCtrls,
Vcl.Themes,
JclFileUtils,
JclBase,
JclStrings,
JclPeImage,
JclSysUtils,
JvJCLUtils,
JvGnugettext,
MPCommonUtilities,
MPCommonObjects,
MPShellUtilities,
SynEditMiscClasses,
SynEditTextBuffer,
VarPyth,
PythonEngine,
cInternalPython,
StringResources,
cPyScripterSettings,
cParameters,
cSSHSupport;
function GetIconIndexFromFile(const AFileName: string;
const ASmall: boolean): integer;
Var
NameSpace : TNameSpace;
IconSize : TIconSize;
begin
Result:= -1;
// swallow any exceptions (bug report by Colin Williams)
try
if FileExists(AFileName) then begin
if ASmall then
IconSize := icSmall
else
IconSize := icLarge;
NameSpace := TNameSpace.CreateFromFileName(AFileName);
try
Result := NameSpace.GetIconIndex(False, IconSize);
finally
NameSpace.Free;
end;
end;
except
end;
end;
function GetLongFileName(const APath: string): string;
(* returns long file name even for nonexisting files *)
begin
if APath = '' then Result:= ''
else begin
Result:= PathGetLongName(APath);
// if different - function is working
if (Result = '') or
((Result = APath) and
not (FileExists(ExcludeTrailingPathDelimiter(APath)) or
System.SysUtils.DirectoryExists(ExcludeTrailingPathDelimiter(APath)))) then
begin
Result:= ExtractFilePath(APath);
// we are up to top level
if (Result = '') or (Result[Length(Result)] = ':') then
Result:= APath
else Result:= Concat(GetLongFileName(ExcludeTrailingPathDelimiter(Result)),
PathDelim, ExtractFileName(APath));
end;
end;
end;
(* from cStrings *)
function StrIsLeft(AText, ALeft: PChar): Boolean;
(* checks if AText starts with ALeft *)
begin
while (ALeft^ <> #0) and (AText^ <> #0) and (ALeft^ = AText^) do begin
Inc(ALeft);
Inc(AText);
end;
Result := ALeft^ = #0;
end;
function StrIsRight(AText, ARight: PChar): Boolean;
(* checks if AText ends with ARight *)
var
LenDiff: Integer;
begin
Result:= ARight = nil;
LenDiff := StrLen(AText) - StrLen(ARight);
if not Result and (LenDiff >= 0) then begin
Inc(AText, LenDiff);
Result := StrIsLeft(AText, ARight);
end;
end;
function StrGetToken(var Content: PChar;
Separators, WhiteSpace, QuoteChars: TSysCharSet): string;
(* returns next token - based on Classes.ExtractStrings *)
var
Head, Tail: PChar;
InQuote: Boolean;
QuoteChar: Char;
begin
Result:= '';
if (Content = nil) or (Content^=#0) then Exit;
Tail := Content;
InQuote := False;
QuoteChar := #0;
while CharInSet(Tail^, WhiteSpace) do Inc(Tail);
Head := Tail;
while True do begin
while (InQuote and not CharInSet(Tail^, QuoteChars + [#0])) or
not CharInSet(Tail^, Separators + WhiteSpace + QuoteChars + [#0]) do Inc(Tail);
if CharInSet(Tail^, QuoteChars) then begin
if (QuoteChar <> #0) and (QuoteChar = Tail^) then
QuoteChar := #0
else QuoteChar := Tail^;
InQuote := QuoteChar <> #0;
Inc(Tail);
end else Break;
end;
if (Head <> Tail) and (Head^ <> #0) then begin
SetString(Result, Head, Tail - Head);
Content:= Tail;
end;
end;
function StrUnQuote(const AText: string): string;
(* removes quotes to AText, if needed *)
var
PText: PChar;
begin
if CharInSet(PChar(AText)^, ['"', '''']) then begin
PText:= PChar(AText);
Result:= AnsiExtractQuotedStr(PText, PText^);
end
else Result:= AText;
end;
(* from cStrings end *)
function LightenColor(Color:TColor; Percentage:integer):TColor;
var
wRGB, wR, wG, wB : longint;
begin
wRGB := ColorToRGB(Color);
wR := Min(round(GetRValue(wRGB) * (1+(percentage / 100))), 255);
wG := Min(round(GetGValue(wRGB) * (1+(percentage / 100))), 255);
wB := Min(round(GetBValue(wRGB) * (1+(percentage / 100))), 255);
result := RGB(wR, wG, wB);
end;
function DarkenColor(Color:TColor; Percentage:integer):TColor;
var
wRGB, wR, wG, wB : longint;
begin
wRGB := ColorToRGB(Color);
wR := round(GetRValue(wRGB) / (1+(percentage / 100)));
wG := round(GetGValue(wRGB) / (1+(percentage / 100)));
wB := round(GetBValue(wRGB) / (1+(percentage / 100)));
result := RGB(wR, wG, wB);
end;
function ApplicationVersion : string;
var
ExeFile : string;
begin
ExeFile := Application.ExeName;
if VersionResourceAvailable(ExeFile) then begin
with TJclFileVersionInfo.Create(ExeFile) do begin
Result := BinFileVersion;
Free;
end;
end else
Result := '1.0.0';
end;
function ConnectedToInternet : boolean;
{
Call SHELL32.DLL for Win < Win98
otherwise call URL.dll
}
{button code:}
const
WininetDLL = 'wininet.dll';
URLDLL = 'url.dll';
INTERNET_CONNECTION_MODEM = 1;
INTERNET_CONNECTION_LAN = 2;
INTERNET_CONNECTION_PROXY = 4;
INTERNET_CONNECTION_MODEM_BUSY = 8;
var
hURLDLL: THandle;
hWininetDLL: THandle;
dwReserved: DWORD;
dwConnectionTypes: DWORD;
fn_InternetGetConnectedState: function(lpdwFlags: LPDWORD; dwReserved: DWORD): BOOL; stdcall;
InetIsOffline : function(dwFlags: DWORD): BOOL; stdcall;
begin
Result := False;
hURLDLL := SafeLoadLibrary(URLDLL);
if hURLDLL > 0 then
begin
@InetIsOffline := GetProcAddress(hURLDLL,'InetIsOffline');
if Assigned(InetIsOffline) then begin
if InetIsOffLine(0) then
Result := False
else
Result := True;
end;
FreeLibrary(hURLDLL);
end;
// Double checking
if Result then begin
hWininetDLL := SafeLoadLibrary(WininetDLL);
if hWininetDLL > 0 then
begin
@fn_InternetGetConnectedState := GetProcAddress(hWininetDLL,'InternetGetConnectedState');
if Assigned(fn_InternetGetConnectedState) then
begin
dwReserved := 0;
dwConnectionTypes := INTERNET_CONNECTION_MODEM or INTERNET_CONNECTION_LAN
or INTERNET_CONNECTION_PROXY or INTERNET_CONNECTION_MODEM_BUSY;
Result := fn_InternetGetConnectedState(@dwConnectionTypes, dwReserved);
end;
FreeLibrary(hWininetDLL);
end;
end;
end;
function GetNthLine(const S : string; LineNo : integer) : string;
var
SL : TStringList;
begin
SL := TStringList.Create;
try
SL.Text := S;
if LineNo <= SL.Count then
Result := SL[LineNo-1]
else
Result := '';
finally
SL.Free;
end;
end;
function GetLineRange(const S : string; StartLine, EndLine : integer) : string;
var
SL : TStringList;
i, LastLine : integer;
begin
Result := '';
SL := TStringList.Create;
try
SL.Text := S;
LastLine := Min(EndLine-1, SL.Count -1);
for i := Max(0, StartLine-1) to LastLine do
if i = LastLine then
Result := Result + SL[i]
else
Result := Result + SL[i] + sLineBreak;
finally
SL.Free;
end;
end;
function GetWordAtPos(const LineText : string; Start : Integer; WordChars : TSysCharSet;
ScanBackwards : boolean = True; ScanForward : boolean = True;
HandleBrackets : Boolean = False) : string;
{ TODO : Replace WordChars with IsLetterOrDigit to properly deal with Unicode }
Var
i : integer;
L, WordStart, WordEnd, ParenCounter, NewStart : integer;
Bracket, MatchingBracket : WideChar;
Const
AllBrackets = '()[]{}';
CloseBrackets = [')', ']', '}'];
OpenBrackets = ['(', '[', '{'];
begin
L := Length(LineText);
WordStart := Start;
WordEnd := Start;
if (Start <= 0) or (Start > L) then
Exit('')
else if not CharInSet(LineText[Start], WordChars) then
Result := ''
else begin
if ScanBackwards then begin
i := Start;
while (i > 1) and CharInSet(LineText[i-1], WordChars) do
Dec(i);
WordStart := i;
end;
if ScanForward then begin
i := Start;
while (i < L) and CharInSet(LineText[i+1], WordChars) do
Inc(i);
WordEnd := i;
end;
Result := Copy(LineText, WordStart, WordEnd - WordStart + 1);
end;
if HandleBrackets and ScanBackwards then begin
if (Result = '') then
NewStart := Start
else
NewStart := WordStart - 1;
if (NewStart > 0) and CharInSet(LineText[NewStart], CloseBrackets) then begin
//We found a close, go till it's opening paren
Bracket := LineText[NewStart];
MatchingBracket := AllBrackets[AllBrackets.IndexOf(Bracket)]; // IndexOf is zero based!
ParenCounter := 1;
i := NewStart - 1;
while (i > 0) and (ParenCounter > 0) do
begin
if Linetext[i] = Bracket then inc(ParenCounter)
else if Linetext[i] = MatchingBracket then dec(ParenCounter);
Dec(i);
end;
WordStart := i+1;
Result := Copy(LineText, WordStart, NewStart - WordStart + 1) + Result;
if WordStart > 1 then
// Recursive call
Result := GetWordAtPos(LineText, WordStart - 1, WordChars,
ScanBackWards, False, True) + Result;
end;
end;
end;
function FormatDocString(const DocString : string) : string;
var
SL : TStringList;
i, Margin : integer;
begin
Result := DocString;
if Result = '' then Exit;
// Expand Tabs
Result := StringReplace(Result, #9, ' ', [rfReplaceAll]);
//Find minimum indentation of any non-blank lines after first line.
Margin := MaxInt;
SL := TStringList.Create;
try
SL.Text := Result;
// Trim First Line
if SL.Count > 0 then
SL[0] := Trim(SL[0]);
// Remove left margin and clear empty lines
for i := 1 to SL.Count - 1 do
if Trim(SL[i]) = '' then
SL[i] := ''
else
Margin := Min(Margin, CalcIndent(SL[i]));
if (Margin > 0) and (Margin < MaxInt) then
for i := 1 to SL.Count - 1 do
if SL[i] <> '' then
SL[i] := Copy(SL[i], Margin+1, Length(SL[i]) - Margin);
Result := SL.Text;
// Remove any trailing or leading blank lines.
Result := StrTrimCharsRight(Result, [#10, #13]);
Result := StrTrimCharsLeft(Result, [#10, #13]);
finally
SL.Free;
end;
end;
function CalcIndent(S : string; TabWidth : integer = 4): integer;
Var
i : integer;
begin
Result := 0;
for i := 1 to Length(S) do
if S[i] = WideChar(#9) then
Inc(Result, TabWidth)
else if S[i] = ' ' then
Inc(Result)
else
break;
end;
function DirIsPythonPackage(Dir : string): boolean;
begin
Result := System.SysUtils.DirectoryExists(Dir) and
FileExists(IncludeTrailingPathDelimiter(Dir) + '__init__.py');
end;
function FileIsPythonPackage(FileName : string): boolean;
begin
Result := (ExtractFileExt(FileName) = '.py') and
(ChangeFileExt(ExtractFileName(FileName), '') = '__init__');
end;
function GetPackageRootDir(Dir : string): string;
Var
S : string;
begin
if not DirIsPythonPackage(Dir) then
raise Exception.CreateFmt('"%s" is not a Python package', [Dir]);
S := Dir;
Repeat
Result := S;
S := ExtractFileDir(S);
Until (Result = S) or (not DirIsPythonPackage(S));
end;
function FileNameToModuleName(const FileName : string): string;
Var
Path, Dir, Server : string;
begin
Result := ChangeFileExt(XtractFileName(FileName), '');
if TSSHFileName.Parse(FileName, Server, Path) then Exit;
Path := ExtractFileDir(FileName);
Dir := ExtractFileName(Path);
if Path <> '' then begin
while DirIsPythonPackage(Path) and (Dir <> '') do begin
Result := Dir + '.' + Result;
Path := ExtractFileDir(Path);
Dir := ExtractFileName(Path);
end;
if StrIsRight(PChar(Result), '.__init__') then
Delete(Result, Length(Result) - 8, 9);
end;
end;
function HTMLSafe(const S : string): string;
begin
Result := StringReplace(S, '<', '<', [rfReplaceAll]);
Result := StringReplace(Result, '>', '>', [rfReplaceAll]);
Result := StringReplace(Result, #13#10, '<br>', [rfReplaceAll]);
Result := StringReplace(Result, #13, '<br>', [rfReplaceAll]);
Result := StringReplace(Result, #10, '<br>', [rfReplaceAll]);
end;
function GetParamStr(P: PChar; var Param: string): PChar;
// From Delphi's system.pas unit!
var
i, Len: Integer;
Start, S, Q: PChar;
begin
while True do
begin
while (P[0] <> #0) and (P[0] <= ' ') do
P := CharNext(P);
{if (P[0] = '"') and (P[1] = '"') then Inc(P, 2) else} Break; // Issue 371
end;
Len := 0;
Start := P;
while P[0] > ' ' do
begin
if P[0] = '"' then
begin
P := CharNext(P);
while (P[0] <> #0) and (P[0] <> '"') do
begin
Q := CharNext(P);
Inc(Len, Q - P);
P := Q;
end;
if P[0] <> #0 then
P := CharNext(P);
end
else
begin
Q := CharNext(P);
Inc(Len, Q - P);
P := Q;
end;
end;
SetLength(Param, Len);
P := Start;
S := Pointer(Param);
i := 0;
while P[0] > ' ' do
begin
if P[0] = '"' then
begin
P := CharNext(P);
while (P[0] <> #0) and (P[0] <> '"') do
begin
Q := CharNext(P);
while P < Q do
begin
S[i] := P^;
Inc(P);
Inc(i);
end;
end;
if P[0] <> #0 then P := CharNext(P);
end
else
begin
Q := CharNext(P);
while P < Q do
begin
S[i] := P^;
Inc(P);
Inc(i);
end;
end;
end;
Result := P;
end;
function ParsePySourceEncoding(Textline : string): string;
begin
Result := '';
with TRegEx.Match(TextLine, 'coding[:=]\s*([-\w.]+)') do
if Success then
Exit(Groups[1].Value);
end;
function GetAveCharSize(Canvas: TCanvas): TPoint;
var
I: Integer;
Buffer: array[0..51] of WideChar;
tm: TTextMetric;
begin
for I := 0 to 25 do Buffer[I] := WideChar(I + Ord('A'));
for I := 0 to 25 do Buffer[I + 26] := WideChar(I + Ord('a'));
GetTextMetrics(Canvas.Handle, tm);
GetTextExtentPointW(Canvas.Handle, Buffer, 52, TSize(Result));
Result.X := (Result.X div 26 + 1) div 2;
Result.Y := tm.tmHeight;
end;
type
TSyncInputQuery = class
public
Caption, Prompt, Value : string;
Res : Boolean;
constructor Create(ACaption, APrompt, AValue : string);
procedure InputQuery;
end;
{ TSyncInputQuery }
constructor TSyncInputQuery.Create(ACaption, APrompt, AValue: string);
begin
Caption := ACaption;
Prompt := APrompt;
Value := AValue;
end;
procedure TSyncInputQuery.InputQuery;
begin
Res := Vcl.Dialogs.InputQuery(Caption, Prompt, Value);
end;
function SyncWideInputQuery(const ACaption, APrompt: string; var Value: string): Boolean;
var
SyncInputQuery : TSyncInputQuery;
SaveThreadState: PPyThreadState;
begin
if GetCurrentThreadId = MainThreadId then
Result := InputQuery(ACaption, APrompt, Value)
else begin
SyncInputQuery := TSyncInputQuery.Create(ACaption, APrompt, Value);
try
with GetPythonEngine do begin
SaveThreadState := PyEval_SaveThread();
try
TThread.Synchronize(nil, SyncInputQuery.InputQuery);
finally
PyEval_RestoreThread(SaveThreadState);
end;
end;
Result := SyncInputQuery.Res;
Value := SyncInputQuery.Value;
finally
SyncInputQuery.Free;
end;
end;
end;
function CleanEOLs(S: AnsiString): AnsiString;
begin
Result := System.AnsiStrings.AdjustLineBreaks(S, System.tlbsLF)
end;
function CleanEOLs(S: string): string;
begin
Result := System.SysUtils.AdjustLineBreaks(S, System.tlbsLF)
end;
function SortedIdentToInt(const Ident: string; var Int: Longint;
const SortedMap: array of TIdentMapEntry;
CaseSensitive : Boolean = False): Boolean;
var
m, n, k, I: Integer;
begin
m := Low(SortedMap); n := High(SortedMap);
while m<=n do
begin
k := m+(n-m) div 2;
if CaseSensitive then
I := CompareStr(Ident, SortedMap[k].Name)
else
I := CompareText(Ident, SortedMap[k].Name);
if I = 0 then begin
Result := true;
Int := SortedMap[k].Value;
exit;
end else if I > 0 then
m := k+1
else
n := k-1;
end;
Result := false
end;
function ComparePythonIdents(const S1, S2 : string): Integer; overload;
Var
L1, L2 : integer;
begin
L1 := Length(S1);