sysutils.pp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407
  1. {
  2. This file is part of the Free Pascal run time library.
  3. Copyright (c) 1999-2000 by Florian Klaempfl
  4. member of the Free Pascal development team
  5. Sysutils unit for win32
  6. See the file COPYING.FPC, included in this distribution,
  7. for details about the copyright.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  11. **********************************************************************}
  12. unit sysutils;
  13. interface
  14. {$MODE objfpc}
  15. {$MODESWITCH OUT}
  16. { force ansistrings }
  17. {$H+}
  18. uses
  19. windows;
  20. {$DEFINE HAS_SLEEP}
  21. {$DEFINE HAS_OSERROR}
  22. {$DEFINE HAS_OSCONFIG}
  23. {$DEFINE HAS_OSUSERDIR}
  24. {$DEFINE HAS_CREATEGUID}
  25. {$DEFINE HAS_LOCALTIMEZONEOFFSET}
  26. {$DEFINE HAS_GETTICKCOUNT}
  27. {$DEFINE HAS_GETTICKCOUNT64}
  28. { used OS file system APIs use unicodestring }
  29. {$define SYSUTILS_HAS_UNICODESTR_FILEUTIL_IMPL}
  30. { OS has an ansistring/single byte environment variable API }
  31. {$define SYSUTILS_HAS_ANSISTR_ENVVAR_IMPL}
  32. { OS has a unicodestring/two byte environment variable API }
  33. {$define SYSUTILS_HAS_UNICODESTR_ENVVAR_IMPL}
  34. { Include platform independent interface part }
  35. {$i sysutilh.inc}
  36. type
  37. TSystemTime = Windows.TSystemTime;
  38. EWin32Error = class(Exception)
  39. public
  40. ErrorCode : DWORD;
  41. end;
  42. Var
  43. Win32Platform : Longint;
  44. Win32MajorVersion,
  45. Win32MinorVersion,
  46. Win32BuildNumber : dword;
  47. Win32CSDVersion : ShortString; // CSD record is 128 bytes only?
  48. const
  49. MaxEraCount = 7;
  50. var
  51. EraNames: array [1..MaxEraCount] of String;
  52. EraYearOffsets: array [1..MaxEraCount] of Integer;
  53. { Compatibility with Delphi }
  54. function Win32Check(res:boolean):boolean;inline;
  55. function WinCheck(res:boolean):boolean;
  56. function CheckWin32Version(Major,Minor : Integer ): Boolean;
  57. function CheckWin32Version(Major : Integer): Boolean;
  58. Procedure RaiseLastWin32Error;
  59. function GetFileVersion(const AFileName: string): Cardinal;
  60. procedure GetFormatSettings;
  61. procedure GetLocaleFormatSettings(LCID: Integer; var FormatSettings: TFormatSettings); platform;
  62. implementation
  63. uses
  64. sysconst,
  65. windirs;
  66. function WinCheck(res:boolean):boolean;
  67. begin
  68. if not res then
  69. RaiseLastOSError;
  70. result:=res;
  71. end;
  72. function Win32Check(res:boolean):boolean;inline;
  73. begin
  74. result:=WinCheck(res);
  75. end;
  76. procedure RaiseLastWin32Error;
  77. begin
  78. RaiseLastOSError;
  79. end;
  80. function CheckWin32Version(Major : Integer): Boolean;
  81. begin
  82. Result:=CheckWin32Version(Major,0)
  83. end;
  84. function CheckWin32Version(Major,Minor: Integer): Boolean;
  85. begin
  86. Result:=(Win32MajorVersion>dword(Major)) or
  87. ((Win32MajorVersion=dword(Major)) and (Win32MinorVersion>=dword(Minor)));
  88. end;
  89. function GetFileVersion(const AFileName:string):Cardinal;
  90. var
  91. { useful only as long as we don't need to touch different stack pages }
  92. buf : array[0..3071] of byte;
  93. bufp : pointer;
  94. fn : string;
  95. valsize,
  96. size : DWORD;
  97. h : DWORD;
  98. valrec : PVSFixedFileInfo;
  99. begin
  100. result:=$fffffff;
  101. fn:=AFileName;
  102. UniqueString(fn);
  103. size:=GetFileVersionInfoSizeA(pchar(fn),@h);
  104. if size>sizeof(buf) then
  105. begin
  106. getmem(bufp,size);
  107. try
  108. if GetFileVersionInfoA(pchar(fn),h,size,bufp) then
  109. if VerQueryValue(bufp,'\',valrec,valsize) then
  110. result:=valrec^.dwFileVersionMS;
  111. finally
  112. freemem(bufp);
  113. end;
  114. end
  115. else
  116. begin
  117. if GetFileVersionInfo(pchar(fn),h,size,@buf) then
  118. if VerQueryValue(@buf,'\',valrec,valsize) then
  119. result:=valrec^.dwFileVersionMS;
  120. end;
  121. end;
  122. {$define HASCREATEGUID}
  123. {$define HASEXPANDUNCFILENAME}
  124. {$DEFINE FPC_NOGENERICANSIROUTINES}
  125. {$DEFINE FPC_FEXPAND_UNC} (* UNC paths are supported *)
  126. {$DEFINE FPC_FEXPAND_DRIVES} (* Full paths begin with drive specification *)
  127. function ConvertEraYearString(Count ,Year,Month,Day : integer) : string; forward;
  128. function ConvertEraString(Count ,Year,Month,Day : integer) : string; forward;
  129. { Include platform independent implementation part }
  130. {$i sysutils.inc}
  131. function GetTempFileName(Dir,Prefix: PChar; uUnique: DWORD; TempFileName: PChar):DWORD;
  132. begin
  133. Result:= Windows.GetTempFileNameA(Dir,Prefix,uUnique,TempFileName);
  134. end;
  135. { UUID generation. }
  136. function CoCreateGuid(out guid: TGUID): HResult; stdcall; external 'ole32.dll' name 'CoCreateGuid';
  137. function SysCreateGUID(out Guid: TGUID): Integer;
  138. begin
  139. Result := Integer(CoCreateGuid(Guid));
  140. end;
  141. function ExpandUNCFileName (const filename:string) : string;
  142. { returns empty string on errors }
  143. var
  144. u: unicodestring;
  145. begin
  146. { prevent data loss due to unsupported characters in ansi code page }
  147. u:=ExpandUNCFileName(unicodestring(filename));
  148. widestringmanager.Unicode2AnsiMoveProc(punicodechar(u),result,DefaultRTLFileSystemCodePage,length(u));
  149. end;
  150. function ExpandUNCFileName (const filename:unicodestring) : unicodestring;
  151. { returns empty string on errors }
  152. var
  153. s : unicodestring;
  154. size : dword;
  155. rc : dword;
  156. buf : pwidechar;
  157. begin
  158. s := ExpandFileName (filename);
  159. s := s + #0;
  160. size := max_path;
  161. getmem(buf,size);
  162. try
  163. rc := WNetGetUniversalNameW (pwidechar(s), UNIVERSAL_NAME_INFO_LEVEL, buf, @size);
  164. if rc=ERROR_MORE_DATA then
  165. begin
  166. buf:=reallocmem(buf,size);
  167. rc := WNetGetUniversalNameW (pwidechar(s), UNIVERSAL_NAME_INFO_LEVEL, buf, @size);
  168. end;
  169. if rc = NO_ERROR then
  170. Result := PRemoteNameInfo(buf)^.lpUniversalName
  171. else if rc = ERROR_NOT_CONNECTED then
  172. Result := filename
  173. else
  174. Result := '';
  175. finally
  176. freemem(buf);
  177. end;
  178. end;
  179. {****************************************************************************
  180. File Functions
  181. ****************************************************************************}
  182. const
  183. AccessMode: array[0..2] of Cardinal = (
  184. GENERIC_READ,
  185. GENERIC_WRITE,
  186. GENERIC_READ or GENERIC_WRITE or FILE_WRITE_ATTRIBUTES);
  187. ShareModes: array[0..4] of Integer = (
  188. 0,
  189. 0,
  190. FILE_SHARE_READ,
  191. FILE_SHARE_WRITE,
  192. FILE_SHARE_READ or FILE_SHARE_WRITE);
  193. Function FileOpen (Const FileName : unicodestring; Mode : Integer) : THandle;
  194. begin
  195. result := CreateFileW(PWideChar(FileName), dword(AccessMode[Mode and 3]),
  196. dword(ShareModes[(Mode and $F0) shr 4]), nil, OPEN_EXISTING,
  197. FILE_ATTRIBUTE_NORMAL, 0);
  198. //if fail api return feInvalidHandle (INVALIDE_HANDLE=feInvalidHandle=-1)
  199. end;
  200. Function FileCreate (Const FileName : UnicodeString) : THandle;
  201. begin
  202. FileCreate:=FileCreate(FileName, fmShareExclusive, 0);
  203. end;
  204. Function FileCreate (Const FileName : UnicodeString; Rights:longint) : THandle;
  205. begin
  206. FileCreate:=FileCreate(FileName, fmShareExclusive, Rights);
  207. end;
  208. Function FileCreate (Const FileName : UnicodeString; ShareMode : Integer; Rights : Integer) : THandle;
  209. begin
  210. Result := CreateFileW(PwideChar(FileName), GENERIC_READ or GENERIC_WRITE,
  211. dword(ShareModes[(ShareMode and $F0) shr 4]), nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  212. end;
  213. Function FileRead (Handle : THandle; out Buffer; Count : longint) : Longint;
  214. Var
  215. res : dword;
  216. begin
  217. if ReadFile(Handle, Buffer, Count, res, nil) then
  218. FileRead:=Res
  219. else
  220. FileRead:=-1;
  221. end;
  222. Function FileWrite (Handle : THandle; const Buffer; Count : Longint) : Longint;
  223. Var
  224. Res : dword;
  225. begin
  226. if WriteFile(Handle, Buffer, Count, Res, nil) then
  227. FileWrite:=Res
  228. else
  229. FileWrite:=-1;
  230. end;
  231. Function FileSeek (Handle : THandle;FOffset,Origin : Longint) : Longint;
  232. begin
  233. Result := longint(SetFilePointer(Handle, FOffset, nil, Origin));
  234. end;
  235. Function FileSeek (Handle : THandle; FOffset: Int64; Origin: Longint) : Int64;
  236. var
  237. rslt: Int64Rec;
  238. begin
  239. rslt := Int64Rec(FOffset);
  240. rslt.lo := SetFilePointer(Handle, rslt.lo, @rslt.hi, Origin);
  241. if (rslt.lo = $FFFFFFFF) and (GetLastError <> 0) then
  242. rslt.hi := $FFFFFFFF;
  243. Result := Int64(rslt);
  244. end;
  245. Procedure FileClose (Handle : THandle);
  246. begin
  247. if Handle<=4 then
  248. exit;
  249. CloseHandle(Handle);
  250. end;
  251. Function FileTruncate (Handle : THandle;Size: Int64) : boolean;
  252. begin
  253. {
  254. Result:=longint(SetFilePointer(handle,Size,nil,FILE_BEGIN))<>-1;
  255. }
  256. if FileSeek (Handle, Size, FILE_BEGIN) = Size then
  257. Result:=SetEndOfFile(handle)
  258. else
  259. Result := false;
  260. end;
  261. Function DosToWinTime (DTime:longint;Var Wtime : TFileTime):longbool;
  262. var
  263. lft : TFileTime;
  264. begin
  265. DosToWinTime:=DosDateTimeToFileTime(longrec(dtime).hi,longrec(dtime).lo,@lft) and
  266. LocalFileTimeToFileTime(lft,Wtime);
  267. end;
  268. Function WinToDosTime (Var Wtime : TFileTime;var DTime:longint):longbool;
  269. var
  270. lft : TFileTime;
  271. begin
  272. WinToDosTime:=FileTimeToLocalFileTime(WTime,lft) and
  273. FileTimeToDosDateTime(lft,Longrec(Dtime).Hi,LongRec(DTIME).lo);
  274. end;
  275. Function FileAge (Const FileName : UnicodeString): Longint;
  276. var
  277. Handle: THandle;
  278. FindData: TWin32FindDataW;
  279. begin
  280. Handle := FindFirstFileW(Pwidechar(FileName), FindData);
  281. if Handle <> INVALID_HANDLE_VALUE then
  282. begin
  283. Windows.FindClose(Handle);
  284. if (FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) = 0 then
  285. If WinToDosTime(FindData.ftLastWriteTime,Result) then
  286. exit;
  287. end;
  288. Result := -1;
  289. end;
  290. Function FileExists (Const FileName : UnicodeString) : Boolean;
  291. var
  292. Attr:Dword;
  293. begin
  294. Attr:=GetFileAttributesW(PWideChar(FileName));
  295. if Attr <> $ffffffff then
  296. Result:= (Attr and FILE_ATTRIBUTE_DIRECTORY) = 0
  297. else
  298. Result:=False;
  299. end;
  300. Function DirectoryExists (Const Directory : UnicodeString) : Boolean;
  301. var
  302. Attr:Dword;
  303. begin
  304. Attr:=GetFileAttributesW(PWideChar(Directory));
  305. if Attr <> $ffffffff then
  306. Result:= (Attr and FILE_ATTRIBUTE_DIRECTORY) > 0
  307. else
  308. Result:=False;
  309. end;
  310. Function FindMatch(var f: TAbstractSearchRec; var Name: UnicodeString) : Longint;
  311. begin
  312. { Find file with correct attribute }
  313. While (F.FindData.dwFileAttributes and cardinal(F.ExcludeAttr))<>0 do
  314. begin
  315. if not FindNextFileW (F.FindHandle,F.FindData) then
  316. begin
  317. Result:=GetLastError;
  318. exit;
  319. end;
  320. end;
  321. { Convert some attributes back }
  322. WinToDosTime(F.FindData.ftLastWriteTime,F.Time);
  323. f.size:=F.FindData.NFileSizeLow+(qword(maxdword)+1)*F.FindData.NFileSizeHigh;
  324. f.attr:=F.FindData.dwFileAttributes;
  325. Name:=F.FindData.cFileName;
  326. Result:=0;
  327. end;
  328. Function InternalFindFirst (Const Path : UnicodeString; Attr : Longint; out Rslt : TAbstractSearchRec; var Name : UnicodeString) : Longint;
  329. begin
  330. Name:=Path;
  331. Rslt.Attr:=attr;
  332. Rslt.ExcludeAttr:=(not Attr) and ($1e);
  333. { $1e = faHidden or faSysFile or faVolumeID or faDirectory }
  334. { FindFirstFile is a Win32 Call }
  335. Rslt.FindHandle:=FindFirstFileW (PWideChar(Path),Rslt.FindData);
  336. If Rslt.FindHandle=Invalid_Handle_value then
  337. begin
  338. Result:=GetLastError;
  339. exit;
  340. end;
  341. { Find file with correct attribute }
  342. Result:=FindMatch(Rslt,Name);
  343. end;
  344. Function InternalFindNext (Var Rslt : TAbstractSearchRec; var Name: UnicodeString) : Longint;
  345. begin
  346. if FindNextFileW(Rslt.FindHandle, Rslt.FindData) then
  347. Result := FindMatch(Rslt, Name)
  348. else
  349. Result := GetLastError;
  350. end;
  351. Procedure InternalFindClose (var Handle: THandle; var FindData: TFindData);
  352. begin
  353. if Handle <> INVALID_HANDLE_VALUE then
  354. Windows.FindClose(Handle);
  355. end;
  356. Function FileGetDate (Handle : THandle) : Longint;
  357. Var
  358. FT : TFileTime;
  359. begin
  360. If GetFileTime(Handle,nil,nil,@ft) and
  361. WinToDosTime(FT,Result) then
  362. exit;
  363. Result:=-1;
  364. end;
  365. Function FileSetDate (Handle : THandle;Age : Longint) : Longint;
  366. Var
  367. FT: TFileTime;
  368. begin
  369. Result := 0;
  370. if DosToWinTime(Age,FT) and
  371. SetFileTime(Handle, nil, nil, @FT) then
  372. Exit;
  373. Result := GetLastError;
  374. end;
  375. Function FileGetAttr (Const FileName : UnicodeString) : Longint;
  376. begin
  377. Result:=Longint(GetFileAttributesW(PWideChar(FileName)));
  378. end;
  379. Function FileSetAttr (Const Filename : UnicodeString; Attr: longint) : Longint;
  380. begin
  381. if SetFileAttributesW(PWideChar(FileName), Attr) then
  382. Result:=0
  383. else
  384. Result := GetLastError;
  385. end;
  386. Function DeleteFile (Const FileName : UnicodeString) : Boolean;
  387. begin
  388. Result:=Windows.DeleteFileW(PWidechar(FileName));
  389. end;
  390. Function RenameFile (Const OldName, NewName : UnicodeString) : Boolean;
  391. begin
  392. Result := MoveFileW(PWideChar(OldName), PWideChar(NewName));
  393. end;
  394. {****************************************************************************
  395. Disk Functions
  396. ****************************************************************************}
  397. type
  398. TGetDiskFreeSpaceEx = function(drive:pchar;var availableforcaller,total,free):longbool;stdcall;
  399. var
  400. GetDiskFreeSpaceEx : TGetDiskFreeSpaceEx;
  401. function diskfree(drive : byte) : int64;
  402. var
  403. disk : array[1..4] of char;
  404. secs,bytes,
  405. free,total : dword;
  406. qwtotal,qwfree,qwcaller : int64;
  407. begin
  408. if drive=0 then
  409. begin
  410. disk[1]:='\';
  411. disk[2]:=#0;
  412. end
  413. else
  414. begin
  415. disk[1]:=chr(drive+64);
  416. disk[2]:=':';
  417. disk[3]:='\';
  418. disk[4]:=#0;
  419. end;
  420. if assigned(GetDiskFreeSpaceEx) then
  421. begin
  422. if GetDiskFreeSpaceEx(@disk[1],qwcaller,qwtotal,qwfree) then
  423. diskfree:=qwfree
  424. else
  425. diskfree:=-1;
  426. end
  427. else
  428. begin
  429. if GetDiskFreeSpace(@disk[1],secs,bytes,free,total) then
  430. diskfree:=int64(free)*secs*bytes
  431. else
  432. diskfree:=-1;
  433. end;
  434. end;
  435. function disksize(drive : byte) : int64;
  436. var
  437. disk : array[1..4] of char;
  438. secs,bytes,
  439. free,total : dword;
  440. qwtotal,qwfree,qwcaller : int64;
  441. begin
  442. if drive=0 then
  443. begin
  444. disk[1]:='\';
  445. disk[2]:=#0;
  446. end
  447. else
  448. begin
  449. disk[1]:=chr(drive+64);
  450. disk[2]:=':';
  451. disk[3]:='\';
  452. disk[4]:=#0;
  453. end;
  454. if assigned(GetDiskFreeSpaceEx) then
  455. begin
  456. if GetDiskFreeSpaceEx(@disk[1],qwcaller,qwtotal,qwfree) then
  457. disksize:=qwtotal
  458. else
  459. disksize:=-1;
  460. end
  461. else
  462. begin
  463. if GetDiskFreeSpace(@disk[1],secs,bytes,free,total) then
  464. disksize:=int64(total)*secs*bytes
  465. else
  466. disksize:=-1;
  467. end;
  468. end;
  469. {****************************************************************************
  470. Time Functions
  471. ****************************************************************************}
  472. Procedure GetLocalTime(var SystemTime: TSystemTime);
  473. begin
  474. windows.Getlocaltime(SystemTime);
  475. end;
  476. function GetLocalTimeOffset: Integer;
  477. var
  478. TZInfo: TTimeZoneInformation;
  479. begin
  480. case GetTimeZoneInformation(TZInfo) of
  481. TIME_ZONE_ID_UNKNOWN:
  482. Result := TZInfo.Bias;
  483. TIME_ZONE_ID_STANDARD:
  484. Result := TZInfo.Bias + TZInfo.StandardBias;
  485. TIME_ZONE_ID_DAYLIGHT:
  486. Result := TZInfo.Bias + TZInfo.DaylightBias;
  487. else
  488. Result := 0;
  489. end;
  490. end;
  491. function GetTickCount: LongWord;
  492. begin
  493. Result := Windows.GetTickCount;
  494. end;
  495. {$IFNDEF WINCE}
  496. type
  497. TGetTickCount64 = function : QWord; stdcall;
  498. var
  499. WinGetTickCount64: TGetTickCount64 = Nil;
  500. {$ENDIF}
  501. function GetTickCount64: QWord;
  502. {$IFNDEF WINCE}
  503. var
  504. lib: THandle;
  505. {$ENDIF}
  506. begin
  507. {$IFNDEF WINCE}
  508. { on Vista and newer there is a GetTickCount64 implementation }
  509. if Win32MajorVersion >= 6 then begin
  510. if not Assigned(WinGetTickCount64) then begin
  511. lib := LoadLibrary('kernel32.dll');
  512. WinGetTickCount64 := TGetTickCount64(
  513. GetProcAddress(lib, 'GetTickCount64'));
  514. end;
  515. Result := WinGetTickCount64();
  516. end else
  517. {$ENDIF}
  518. Result := Windows.GetTickCount;
  519. end;
  520. {****************************************************************************
  521. Misc Functions
  522. ****************************************************************************}
  523. procedure sysbeep;
  524. begin
  525. MessageBeep(0);
  526. end;
  527. {****************************************************************************
  528. Locale Functions
  529. ****************************************************************************}
  530. function GetLocaleStr(LID, LT: Longint; const Def: string): ShortString;
  531. var
  532. L: Integer;
  533. Buf: array[0..255] of Char;
  534. begin
  535. L := GetLocaleInfo(LID, LT, Buf, SizeOf(Buf));
  536. if L > 0 then
  537. SetString(Result, @Buf[0], L - 1)
  538. else
  539. Result := Def;
  540. end;
  541. function GetLocaleChar(LID, LT: Longint; Def: Char): Char;
  542. var
  543. Buf: array[0..3] of Char; // sdate allows 4 chars.
  544. begin
  545. if GetLocaleInfo(LID, LT, Buf, sizeof(buf)) > 0 then
  546. Result := Buf[0]
  547. else
  548. Result := Def;
  549. end;
  550. function ConvertEraString(Count ,Year,Month,Day : integer) : string;
  551. var
  552. ASystemTime: TSystemTime;
  553. buf: array[0..100] of char;
  554. ALCID : LCID;
  555. PriLangID : Word;
  556. SubLangID : Word;
  557. begin
  558. Result := ''; if (Count<=0) then exit;
  559. DateTimeToSystemTime(EncodeDate(Year,Month,Day),ASystemTime);
  560. ALCID := GetThreadLocale;
  561. // ALCID := SysLocale.DefaultLCID;
  562. if GetDateFormat(ALCID , DATE_USE_ALT_CALENDAR
  563. , @ASystemTime, PChar('gg')
  564. , @buf, SizeOf(buf)) > 0 then
  565. begin
  566. Result := buf;
  567. if Count = 1 then
  568. begin
  569. PriLangID := ALCID and $3FF;
  570. SubLangID := (ALCID and $FFFF) shr 10;
  571. case PriLangID of
  572. LANG_JAPANESE:
  573. begin
  574. Result := Copy(WideString(Result),1,1);
  575. end;
  576. LANG_CHINESE:
  577. if (SubLangID = SUBLANG_CHINESE_TRADITIONAL) then
  578. begin
  579. Result := Copy(WideString(Result),1,1);
  580. end;
  581. end;
  582. end;
  583. end;
  584. // if Result = '' then Result := StringOfChar('G',Count);
  585. end;
  586. function ConvertEraYearString(Count ,Year,Month,Day : integer) : string;
  587. var
  588. ALCID : LCID;
  589. ASystemTime : TSystemTime;
  590. AFormatText : string;
  591. buf : array[0..100] of Char;
  592. begin
  593. Result := '';
  594. DateTimeToSystemTime(EncodeDate(Year,Month,Day),ASystemTime);
  595. if Count <= 2 then
  596. AFormatText := 'yy'
  597. else
  598. AFormatText := 'yyyy';
  599. ALCID := GetThreadLocale;
  600. // ALCID := SysLocale.DefaultLCID;
  601. if GetDateFormat(ALCID, DATE_USE_ALT_CALENDAR
  602. , @ASystemTime, PChar(AFormatText)
  603. , @buf, SizeOf(buf)) > 0 then
  604. begin
  605. Result := buf;
  606. if (Count = 1) and (Result[1] = '0') then
  607. Result := Copy(Result, 2, Length(Result)-1);
  608. end;
  609. end;
  610. Function GetLocaleInt(LID,TP,Def: LongInt): LongInt;
  611. Var
  612. S: String;
  613. C: Integer;
  614. Begin
  615. S:=GetLocaleStr(LID,TP,'0');
  616. Val(S,Result,C);
  617. If C<>0 Then
  618. Result:=Def;
  619. End;
  620. function EnumEraNames(Names: PChar): WINBOOL; stdcall;
  621. var
  622. i : integer;
  623. begin
  624. Result := False;
  625. for i := Low(EraNames) to High(EraNames) do
  626. if (EraNames[i] = '') then
  627. begin
  628. EraNames[i] := Names;
  629. Result := True;
  630. break;
  631. end;
  632. end;
  633. function EnumEraYearOffsets(YearOffsets: PChar): WINBOOL; stdcall;
  634. var
  635. i : integer;
  636. begin
  637. Result := False;
  638. for i := Low(EraYearOffsets) to High(EraYearOffsets) do
  639. if (EraYearOffsets[i] = -1) then
  640. begin
  641. EraYearOffsets[i] := StrToIntDef(YearOffsets, 0);
  642. Result := True;
  643. break;
  644. end;
  645. end;
  646. procedure GetEraNamesAndYearOffsets;
  647. var
  648. ACALID : CALID;
  649. ALCID : LCID;
  650. buf : array[0..10] of char;
  651. i : integer;
  652. begin
  653. for i:= 1 to MaxEraCount do
  654. begin
  655. EraNames[i] := ''; EraYearOffsets[i] := -1;
  656. end;
  657. ALCID := GetThreadLocale;
  658. if GetLocaleInfo(ALCID , LOCALE_IOPTIONALCALENDAR, buf, sizeof(buf)) <= 0 then exit;
  659. ACALID := StrToIntDef(buf,1);
  660. if ACALID in [3..5] then
  661. begin
  662. EnumCalendarInfoA(@EnumEraNames, ALCID, ACALID , CAL_SERASTRING);
  663. EnumCalendarInfoA(@EnumEraYearOffsets, ALCID, ACALID, CAL_IYEAROFFSETRANGE);
  664. end;
  665. (*
  666. 1 CAL_GREGORIAN Gregorian (localized)
  667. 2 CAL_GREGORIAN_US Gregorian (English strings always)
  668. 3 CAL_JAPAN Japanese Emperor Era
  669. 4 CAL_TAIWAN Taiwan Calendar
  670. 5 CAL_KOREA Korean Tangun Era
  671. 6 CAL_HIJRI Hijri (Arabic Lunar)
  672. 7 CAL_THAI Thai
  673. 8 CAL_HEBREW Hebrew (Lunar)
  674. 9 CAL_GREGORIAN_ME_FRENCH Gregorian Middle East French
  675. 10 CAL_GREGORIAN_ARABIC Gregorian Arabic
  676. 11 CAL_GREGORIAN_XLIT_ENGLISH Gregorian transliterated English
  677. 12 CAL_GREGORIAN_XLIT_FRENCH Gregorian transliterated French
  678. 23 CAL_UMALQURA Windows Vista or later: Um Al Qura (Arabic lunar) calendar
  679. *)
  680. end;
  681. procedure GetLocaleFormatSettings(LCID: Integer; var FormatSettings: TFormatSettings);
  682. var
  683. HF : Shortstring;
  684. LID : Windows.LCID;
  685. I,Day : longint;
  686. begin
  687. LID := LCID;
  688. with FormatSettings do
  689. begin
  690. { Date stuff }
  691. for I := 1 to 12 do
  692. begin
  693. ShortMonthNames[I]:=GetLocaleStr(LID,LOCALE_SABBREVMONTHNAME1+I-1,ShortMonthNames[i]);
  694. LongMonthNames[I]:=GetLocaleStr(LID,LOCALE_SMONTHNAME1+I-1,LongMonthNames[i]);
  695. end;
  696. for I := 1 to 7 do
  697. begin
  698. Day := (I + 5) mod 7;
  699. ShortDayNames[I]:=GetLocaleStr(LID,LOCALE_SABBREVDAYNAME1+Day,ShortDayNames[i]);
  700. LongDayNames[I]:=GetLocaleStr(LID,LOCALE_SDAYNAME1+Day,LongDayNames[i]);
  701. end;
  702. DateSeparator := GetLocaleChar(LID, LOCALE_SDATE, '/');
  703. ShortDateFormat := GetLocaleStr(LID, LOCALE_SSHORTDATE, 'm/d/yy');
  704. LongDateFormat := GetLocaleStr(LID, LOCALE_SLONGDATE, 'mmmm d, yyyy');
  705. { Time stuff }
  706. TimeSeparator := GetLocaleChar(LID, LOCALE_STIME, ':');
  707. TimeAMString := GetLocaleStr(LID, LOCALE_S1159, 'AM');
  708. TimePMString := GetLocaleStr(LID, LOCALE_S2359, 'PM');
  709. if StrToIntDef(GetLocaleStr(LID, LOCALE_ITLZERO, '0'), 0) = 0 then
  710. HF:='h'
  711. else
  712. HF:='hh';
  713. // No support for 12 hour stuff at the moment...
  714. ShortTimeFormat := HF+':nn';
  715. LongTimeFormat := HF + ':nn:ss';
  716. { Currency stuff }
  717. CurrencyString:=GetLocaleStr(LID, LOCALE_SCURRENCY, '');
  718. CurrencyFormat:=StrToIntDef(GetLocaleStr(LID, LOCALE_ICURRENCY, '0'), 0);
  719. NegCurrFormat:=StrToIntDef(GetLocaleStr(LID, LOCALE_INEGCURR, '0'), 0);
  720. { Number stuff }
  721. ThousandSeparator:=GetLocaleChar(LID, LOCALE_STHOUSAND, ',');
  722. DecimalSeparator:=GetLocaleChar(LID, LOCALE_SDECIMAL, '.');
  723. CurrencyDecimals:=StrToIntDef(GetLocaleStr(LID, LOCALE_ICURRDIGITS, '0'), 0);
  724. ListSeparator := GetLocaleChar(LID, LOCALE_SLIST, ',');
  725. end;
  726. end;
  727. procedure GetFormatSettings;
  728. begin
  729. GetlocaleFormatSettings(GetThreadLocale, DefaultFormatSettings);
  730. end;
  731. Procedure InitInternational;
  732. var
  733. { A call to GetSystemMetrics changes the value of the 8087 Control Word on
  734. Pentium4 with WinXP SP2 }
  735. old8087CW: word;
  736. DefaultCustomLocaleID : LCID; // typedef DWORD LCID;
  737. DefaultCustomLanguageID : Word; // typedef WORD LANGID;
  738. begin
  739. /// workaround for Windows 7 bug, see bug report #18574
  740. SetThreadLocale(GetUserDefaultLCID);
  741. InitInternationalGeneric;
  742. old8087CW:=Get8087CW;
  743. SysLocale.MBCS:=GetSystemMetrics(SM_DBCSENABLED)<>0;
  744. SysLocale.RightToLeft:=GetSystemMetrics(SM_MIDEASTENABLED)<>0;
  745. SysLocale.DefaultLCID := $0409;
  746. SysLocale.PriLangID := LANG_ENGLISH;
  747. SysLocale.SubLangID := SUBLANG_ENGLISH_US;
  748. // probably needs update with getthreadlocale. post 2.0.2
  749. DefaultCustomLocaleID := GetThreadLocale;
  750. if DefaultCustomLocaleID <> 0 then
  751. begin
  752. { Locale Identifiers
  753. +-------------+---------+-------------------------+
  754. | Reserved | Sort ID | Language ID |
  755. +-------------+---------+-------------------------+
  756. 31 20 19 16 15 0 bit }
  757. DefaultCustomLanguageID := DefaultCustomLocaleID and $FFFF; // 2^16
  758. if DefaultCustomLanguageID <> 0 then
  759. begin
  760. SysLocale.DefaultLCID := DefaultCustomLocaleID;
  761. { Language Identifiers
  762. +-------------------------+-------------------------+
  763. | SubLanguage ID | Primary Language ID |
  764. +-------------------------+-------------------------+
  765. 15 10 9 0 bit }
  766. SysLocale.PriLangID := DefaultCustomLanguageID and $3ff; // 2^10
  767. SysLocale.SubLangID := DefaultCustomLanguageID shr 10;
  768. end;
  769. end;
  770. Set8087CW(old8087CW);
  771. GetFormatSettings;
  772. if SysLocale.FarEast then GetEraNamesAndYearOffsets;
  773. end;
  774. {****************************************************************************
  775. Target Dependent
  776. ****************************************************************************}
  777. function SysErrorMessage(ErrorCode: Integer): String;
  778. const
  779. MaxMsgSize = Format_Message_Max_Width_Mask;
  780. var
  781. MsgBuffer: pChar;
  782. begin
  783. GetMem(MsgBuffer, MaxMsgSize);
  784. FillChar(MsgBuffer^, MaxMsgSize, #0);
  785. FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM,
  786. nil,
  787. ErrorCode,
  788. MakeLangId(LANG_NEUTRAL, SUBLANG_DEFAULT),
  789. MsgBuffer, { This function allocs the memory }
  790. MaxMsgSize, { Maximum message size }
  791. nil);
  792. SysErrorMessage := StrPas(MsgBuffer);
  793. FreeMem(MsgBuffer, MaxMsgSize);
  794. end;
  795. {****************************************************************************
  796. Initialization code
  797. ****************************************************************************}
  798. {$push}
  799. { GetEnvironmentStrings cannot be checked by CheckPointer function }
  800. {$checkpointer off}
  801. Function GetEnvironmentVariable(Const EnvVar : String) : String;
  802. var
  803. oemenvvar, oemstr : RawByteString;
  804. i, hplen : longint;
  805. hp,p : pchar;
  806. begin
  807. oemenvvar:=uppercase(envvar);
  808. SetCodePage(oemenvvar,CP_OEMCP);
  809. Result:='';
  810. p:=GetEnvironmentStringsA;
  811. hp:=p;
  812. while hp^<>#0 do
  813. begin
  814. oemstr:=hp;
  815. { cache length, may change after uppercasing depending on code page }
  816. hplen:=length(oemstr);
  817. { all environment variables are encoded in the oem code page }
  818. SetCodePage(oemstr,CP_OEMCP,false);
  819. i:=pos('=',oemstr);
  820. if uppercase(copy(oemstr,1,i-1))=oemenvvar then
  821. begin
  822. Result:=copy(oemstr,i+1,length(oemstr)-i);
  823. break;
  824. end;
  825. { next string entry}
  826. hp:=hp+hplen+1;
  827. end;
  828. FreeEnvironmentStringsA(p);
  829. end;
  830. Function GetEnvironmentVariable(Const EnvVar : UnicodeString) : UnicodeString;
  831. var
  832. s, upperenv : Unicodestring;
  833. i : longint;
  834. hp,p : pwidechar;
  835. begin
  836. Result:='';
  837. p:=GetEnvironmentStringsW;
  838. hp:=p;
  839. upperenv:=uppercase(envvar);
  840. while hp^<>#0 do
  841. begin
  842. s:=hp;
  843. i:=pos('=',s);
  844. if uppercase(copy(s,1,i-1))=upperenv then
  845. begin
  846. Result:=copy(s,i+1,length(s)-i);
  847. break;
  848. end;
  849. { next string entry}
  850. hp:=hp+strlen(hp)+1;
  851. end;
  852. FreeEnvironmentStringsW(p);
  853. end;
  854. Function GetEnvironmentVariableCount : Integer;
  855. var
  856. hp,p : pchar;
  857. begin
  858. Result:=0;
  859. p:=GetEnvironmentStringsA;
  860. hp:=p;
  861. If (Hp<>Nil) then
  862. while hp^<>#0 do
  863. begin
  864. Inc(Result);
  865. hp:=hp+strlen(hp)+1;
  866. end;
  867. FreeEnvironmentStringsA(p);
  868. end;
  869. Function GetEnvironmentString(Index : Integer) : {$ifdef FPC_RTL_UNICODE}UnicodeString{$else}AnsiString{$endif};
  870. var
  871. hp,p : pchar;
  872. {$ifdef FPC_RTL_UNICODE}
  873. tmpstr : RawByteString;
  874. {$endif}
  875. begin
  876. Result:='';
  877. p:=GetEnvironmentStringsA;
  878. hp:=p;
  879. If (Hp<>Nil) then
  880. begin
  881. while (hp^<>#0) and (Index>1) do
  882. begin
  883. Dec(Index);
  884. hp:=hp+strlen(hp)+1;
  885. end;
  886. If (hp^<>#0) then
  887. begin
  888. {$ifdef FPC_RTL_UNICODE}
  889. tmpstr:=hp;
  890. SetCodePage(tmpstr,CP_OEMCP,false);
  891. Result:=tmpstr;
  892. {$else}
  893. Result:=hp;
  894. SetCodePage(RawByteString(Result),CP_OEMCP,false);
  895. {$endif}
  896. end;
  897. end;
  898. FreeEnvironmentStringsA(p);
  899. end;
  900. {$pop}
  901. function ExecuteProcess(Const Path: AnsiString; Const ComLine: AnsiString;Flags:TExecuteFlags=[]):integer;
  902. // win specific function
  903. var
  904. SI: TStartupInfo;
  905. PI: TProcessInformation;
  906. Proc : THandle;
  907. l : DWord;
  908. CommandLine : ansistring;
  909. e : EOSError;
  910. ExecInherits : longbool;
  911. begin
  912. FillChar(SI, SizeOf(SI), 0);
  913. SI.cb:=SizeOf(SI);
  914. SI.wShowWindow:=1;
  915. { always surround the name of the application by quotes
  916. so that long filenames will always be accepted. But don't
  917. do it if there are already double quotes, since Win32 does not
  918. like double quotes which are duplicated!
  919. }
  920. if pos('"',path)=0 then
  921. CommandLine:='"'+path+'"'
  922. else
  923. CommandLine:=path;
  924. if ComLine <> '' then
  925. CommandLine:=Commandline+' '+ComLine+#0
  926. else
  927. CommandLine := CommandLine + #0;
  928. ExecInherits:=ExecInheritsHandles in Flags;
  929. if not CreateProcess(nil, pchar(CommandLine),
  930. Nil, Nil, ExecInherits,$20, Nil, Nil, SI, PI) then
  931. begin
  932. e:=EOSError.CreateFmt(SExecuteProcessFailed,[CommandLine,GetLastError]);
  933. e.ErrorCode:=GetLastError;
  934. raise e;
  935. end;
  936. Proc:=PI.hProcess;
  937. if WaitForSingleObject(Proc, dword($ffffffff)) <> $ffffffff then
  938. begin
  939. GetExitCodeProcess(Proc,l);
  940. CloseHandle(Proc);
  941. CloseHandle(PI.hThread);
  942. result:=l;
  943. end
  944. else
  945. begin
  946. e:=EOSError.CreateFmt(SExecuteProcessFailed,[CommandLine,GetLastError]);
  947. e.ErrorCode:=GetLastError;
  948. CloseHandle(Proc);
  949. CloseHandle(PI.hThread);
  950. raise e;
  951. end;
  952. end;
  953. function ExecuteProcess(Const Path: AnsiString; Const ComLine: Array of AnsiString;Flags:TExecuteFlags=[]):integer;
  954. var
  955. CommandLine: AnsiString;
  956. I: integer;
  957. begin
  958. Commandline := '';
  959. for I := 0 to High (ComLine) do
  960. if Pos (' ', ComLine [I]) <> 0 then
  961. CommandLine := CommandLine + ' ' + '"' + ComLine [I] + '"'
  962. else
  963. CommandLine := CommandLine + ' ' + Comline [I];
  964. ExecuteProcess := ExecuteProcess (Path, CommandLine,Flags);
  965. end;
  966. Procedure Sleep(Milliseconds : Cardinal);
  967. begin
  968. Windows.Sleep(MilliSeconds)
  969. end;
  970. Function GetLastOSError : Integer;
  971. begin
  972. Result:=GetLastError;
  973. end;
  974. {****************************************************************************
  975. Initialization code
  976. ****************************************************************************}
  977. var
  978. kernel32dll : THandle;
  979. Procedure LoadVersionInfo;
  980. // and getfreespaceex
  981. Var
  982. versioninfo : TOSVERSIONINFO;
  983. begin
  984. GetDiskFreeSpaceEx:=nil;
  985. versioninfo.dwOSVersionInfoSize:=sizeof(versioninfo);
  986. GetVersionEx(versioninfo);
  987. Win32Platform:=versionInfo.dwPlatformId;
  988. Win32MajorVersion:=versionInfo.dwMajorVersion;
  989. Win32MinorVersion:=versionInfo.dwMinorVersion;
  990. Win32BuildNumber:=versionInfo.dwBuildNumber;
  991. Move (versioninfo.szCSDVersion ,Win32CSDVersion[1],128);
  992. win32CSDVersion[0]:=chr(strlen(pchar(@versioninfo.szCSDVersion)));
  993. kernel32dll:=GetModuleHandle('kernel32');
  994. if kernel32dll<>0 then
  995. GetDiskFreeSpaceEx:=TGetDiskFreeSpaceEx(GetProcAddress(kernel32dll,'GetDiskFreeSpaceExA'));
  996. end;
  997. Function GetAppConfigDir(Global : Boolean) : String;
  998. begin
  999. If Global then
  1000. Result:=GetWindowsSpecialDir(CSIDL_COMMON_APPDATA)
  1001. else
  1002. Result:=GetWindowsSpecialDir(CSIDL_LOCAL_APPDATA);
  1003. If (Result<>'') then
  1004. begin
  1005. if VendorName<>'' then
  1006. Result:=IncludeTrailingPathDelimiter(Result+VendorName);
  1007. Result:=IncludeTrailingPathDelimiter(Result+ApplicationName);
  1008. end
  1009. else
  1010. Result:=IncludeTrailingPathDelimiter(DGetAppConfigDir(Global));
  1011. end;
  1012. Function GetAppConfigFile(Global : Boolean; SubDir : Boolean) : String;
  1013. begin
  1014. result:=DGetAppConfigFile(Global,SubDir);
  1015. end;
  1016. Function GetUserDir : String;
  1017. begin
  1018. Result:=GetWindowsSpecialDir(CSIDL_PROFILE);
  1019. end;
  1020. Procedure InitSysConfigDir;
  1021. begin
  1022. SetLength(SysConfigDir, MAX_PATH);
  1023. SetLength(SysConfigDir, GetWindowsDirectory(PChar(SysConfigDir), MAX_PATH));
  1024. end;
  1025. {****************************************************************************
  1026. Target Dependent WideString stuff
  1027. ****************************************************************************}
  1028. { This is the case of Win9x. Limited to current locale of course, but it's better
  1029. than not working at all. }
  1030. function DoCompareStringA(P1, P2: PWideChar; L1, L2: PtrUInt; Flags: DWORD): PtrInt;
  1031. var
  1032. a1, a2: AnsiString;
  1033. begin
  1034. if L1>0 then
  1035. widestringmanager.Wide2AnsiMoveProc(P1,a1,DefaultSystemCodePage,L1);
  1036. if L2>0 then
  1037. widestringmanager.Wide2AnsiMoveProc(P2,a2,DefaultSystemCodePage,L2);
  1038. SetLastError(0);
  1039. Result:=CompareStringA(LOCALE_USER_DEFAULT,Flags,pchar(a1),
  1040. length(a1),pchar(a2),length(a2))-2;
  1041. end;
  1042. function DoCompareStringW(P1, P2: PWideChar; L1, L2: PtrUInt; Flags: DWORD): PtrInt;
  1043. begin
  1044. SetLastError(0);
  1045. Result:=CompareStringW(LOCALE_USER_DEFAULT,Flags,P1,L1,P2,L2)-2;
  1046. if GetLastError=0 then
  1047. Exit;
  1048. if GetLastError=ERROR_CALL_NOT_IMPLEMENTED then // Win9x case
  1049. Result:=DoCompareStringA(P1, P2, L1, L2, Flags);
  1050. if GetLastError<>0 then
  1051. RaiseLastOSError;
  1052. end;
  1053. function Win32CompareWideString(const s1, s2 : WideString) : PtrInt;
  1054. begin
  1055. Result:=DoCompareStringW(PWideChar(s1), PWideChar(s2), Length(s1), Length(s2), 0);
  1056. end;
  1057. function Win32CompareTextWideString(const s1, s2 : WideString) : PtrInt;
  1058. begin
  1059. Result:=DoCompareStringW(PWideChar(s1), PWideChar(s2), Length(s1), Length(s2), NORM_IGNORECASE);
  1060. end;
  1061. function Win32AnsiUpperCase(const s: string): string;
  1062. begin
  1063. if length(s)>0 then
  1064. begin
  1065. result:=s;
  1066. UniqueString(result);
  1067. CharUpperBuff(pchar(result),length(result));
  1068. end
  1069. else
  1070. result:='';
  1071. end;
  1072. function Win32AnsiLowerCase(const s: string): string;
  1073. begin
  1074. if length(s)>0 then
  1075. begin
  1076. result:=s;
  1077. UniqueString(result);
  1078. CharLowerBuff(pchar(result),length(result));
  1079. end
  1080. else
  1081. result:='';
  1082. end;
  1083. function Win32AnsiCompareStr(const S1, S2: string): PtrInt;
  1084. begin
  1085. result:=CompareString(LOCALE_USER_DEFAULT,0,pchar(s1),length(s1),
  1086. pchar(s2),length(s2))-2;
  1087. end;
  1088. function Win32AnsiCompareText(const S1, S2: string): PtrInt;
  1089. begin
  1090. result:=CompareString(LOCALE_USER_DEFAULT,NORM_IGNORECASE,pchar(s1),length(s1),
  1091. pchar(s2),length(s2))-2;
  1092. end;
  1093. function Win32AnsiStrComp(S1, S2: PChar): PtrInt;
  1094. begin
  1095. result:=CompareString(LOCALE_USER_DEFAULT,0,s1,-1,s2,-1)-2;
  1096. end;
  1097. function Win32AnsiStrIComp(S1, S2: PChar): PtrInt;
  1098. begin
  1099. result:=CompareString(LOCALE_USER_DEFAULT,NORM_IGNORECASE,s1,-1,s2,-1)-2;
  1100. end;
  1101. function Win32AnsiStrLComp(S1, S2: PChar; MaxLen: PtrUInt): PtrInt;
  1102. begin
  1103. result:=CompareString(LOCALE_USER_DEFAULT,0,s1,maxlen,s2,maxlen)-2;
  1104. end;
  1105. function Win32AnsiStrLIComp(S1, S2: PChar; MaxLen: PtrUInt): PtrInt;
  1106. begin
  1107. result:=CompareString(LOCALE_USER_DEFAULT,NORM_IGNORECASE,s1,maxlen,s2,maxlen)-2;
  1108. end;
  1109. function Win32AnsiStrLower(Str: PChar): PChar;
  1110. begin
  1111. CharLower(str);
  1112. result:=str;
  1113. end;
  1114. function Win32AnsiStrUpper(Str: PChar): PChar;
  1115. begin
  1116. CharUpper(str);
  1117. result:=str;
  1118. end;
  1119. function Win32CompareUnicodeString(const s1, s2 : UnicodeString) : PtrInt;
  1120. begin
  1121. Result:=DoCompareStringW(PWideChar(s1), PWideChar(s2), Length(s1), Length(s2), 0);
  1122. end;
  1123. function Win32CompareTextUnicodeString(const s1, s2 : UnicodeString) : PtrInt;
  1124. begin
  1125. Result:=DoCompareStringW(PWideChar(s1), PWideChar(s2), Length(s1), Length(s2), NORM_IGNORECASE);
  1126. end;
  1127. { there is a similiar procedure in the system unit which inits the fields which
  1128. are relevant already for the system unit }
  1129. procedure InitWin32Widestrings;
  1130. begin
  1131. { return value: number of code points in the string. Whenever an invalid
  1132. code point is encountered, all characters part of this invalid code point
  1133. are considered to form one "character" and the next character is
  1134. considered to be the start of a new (possibly also invalid) code point }
  1135. //!!! CharLengthPCharProc : function(const Str: PChar): PtrInt;
  1136. { return value:
  1137. -1 if incomplete or invalid code point
  1138. 0 if NULL character,
  1139. > 0 if that's the length in bytes of the code point }
  1140. //!!!! CodePointLengthProc : function(const Str: PChar; MaxLookAead: PtrInt): Ptrint;
  1141. widestringmanager.CompareWideStringProc:=@Win32CompareWideString;
  1142. widestringmanager.CompareTextWideStringProc:=@Win32CompareTextWideString;
  1143. widestringmanager.UpperAnsiStringProc:=@Win32AnsiUpperCase;
  1144. widestringmanager.LowerAnsiStringProc:=@Win32AnsiLowerCase;
  1145. widestringmanager.CompareStrAnsiStringProc:=@Win32AnsiCompareStr;
  1146. widestringmanager.CompareTextAnsiStringProc:=@Win32AnsiCompareText;
  1147. widestringmanager.StrCompAnsiStringProc:=@Win32AnsiStrComp;
  1148. widestringmanager.StrICompAnsiStringProc:=@Win32AnsiStrIComp;
  1149. widestringmanager.StrLCompAnsiStringProc:=@Win32AnsiStrLComp;
  1150. widestringmanager.StrLICompAnsiStringProc:=@Win32AnsiStrLIComp;
  1151. widestringmanager.StrLowerAnsiStringProc:=@Win32AnsiStrLower;
  1152. widestringmanager.StrUpperAnsiStringProc:=@Win32AnsiStrUpper;
  1153. widestringmanager.CompareUnicodeStringProc:=@Win32CompareUnicodeString;
  1154. widestringmanager.CompareTextUnicodeStringProc:=@Win32CompareTextUnicodeString;
  1155. end;
  1156. { Platform-specific exception support }
  1157. function WinExceptionObject(code: Longint; const rec: TExceptionRecord): Exception;
  1158. var
  1159. entry: PExceptMapEntry;
  1160. begin
  1161. entry := FindExceptMapEntry(code);
  1162. if assigned(entry) then
  1163. result:=entry^.cls.CreateRes(entry^.msg)
  1164. else
  1165. result:=EExternalException.CreateResFmt(@SExternalException,[rec.ExceptionCode]);
  1166. if result is EExternal then
  1167. EExternal(result).FExceptionRecord:=rec;
  1168. end;
  1169. function WinExceptionClass(code: longint): ExceptClass;
  1170. var
  1171. entry: PExceptMapEntry;
  1172. begin
  1173. entry := FindExceptMapEntry(code);
  1174. if assigned(entry) then
  1175. result:=entry^.cls
  1176. else
  1177. result:=EExternalException;
  1178. end;
  1179. Initialization
  1180. InitWin32Widestrings;
  1181. InitExceptions; { Initialize exceptions. OS independent }
  1182. {$ifdef win64} { Nothing win64-specific here, just keeping exe size down
  1183. as these procedures aren't used in generic exception handling }
  1184. ExceptObjProc:=@WinExceptionObject;
  1185. ExceptClsProc:=@WinExceptionClass;
  1186. {$endif win64}
  1187. InitInternational; { Initialize internationalization settings }
  1188. LoadVersionInfo;
  1189. InitSysConfigDir;
  1190. OnBeep:=@SysBeep;
  1191. Finalization
  1192. DoneExceptions;
  1193. end.