sysutils.pp 39 KB

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