sysutils.pp 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820
  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. {$modeswitch typehelpers}
  19. {$modeswitch advancedrecords}
  20. uses
  21. windows;
  22. {$DEFINE HAS_SLEEP}
  23. {$DEFINE HAS_OSERROR}
  24. {$DEFINE HAS_OSCONFIG}
  25. {$DEFINE HAS_OSUSERDIR}
  26. {$DEFINE HAS_CREATEGUID}
  27. {$DEFINE HAS_LOCALTIMEZONEOFFSET}
  28. {$DEFINE HAS_GETTICKCOUNT}
  29. {$DEFINE HAS_GETTICKCOUNT64}
  30. {$DEFINE HAS_FILEDATETIME}
  31. {$DEFINE OS_FILESETDATEBYNAME}
  32. // this target has an fileflush implementation, don't include dummy
  33. {$DEFINE SYSUTILS_HAS_FILEFLUSH_IMPL}
  34. { used OS file system APIs use unicodestring }
  35. {$define SYSUTILS_HAS_UNICODESTR_FILEUTIL_IMPL}
  36. { OS has an ansistring/single byte environment variable API }
  37. {$define SYSUTILS_HAS_ANSISTR_ENVVAR_IMPL}
  38. { OS has a unicodestring/two byte environment variable API }
  39. {$define SYSUTILS_HAS_UNICODESTR_ENVVAR_IMPL}
  40. { Include platform independent interface part }
  41. {$i sysutilh.inc}
  42. type
  43. TSystemTime = Windows.TSystemTime;
  44. EWin32Error = class(Exception)
  45. public
  46. ErrorCode : DWORD;
  47. end;
  48. Var
  49. Win32Platform : Longint;
  50. Win32MajorVersion,
  51. Win32MinorVersion,
  52. Win32BuildNumber : dword;
  53. Win32CSDVersion : ShortString; // CSD record is 128 bytes only?
  54. const
  55. MaxEraCount = 7;
  56. var
  57. EraNames: array [1..MaxEraCount] of String;
  58. EraYearOffsets: array [1..MaxEraCount] of Integer;
  59. { Compatibility with Delphi }
  60. function Win32Check(res:boolean):boolean;inline;
  61. function WinCheck(res:boolean):boolean;
  62. function CheckWin32Version(Major,Minor : Integer ): Boolean;
  63. function CheckWin32Version(Major : Integer): Boolean;
  64. Procedure RaiseLastWin32Error;
  65. function GetFileVersion(const AFileName: string): Cardinal;
  66. function GetFileVersion(const AFileName: UnicodeString): Cardinal;
  67. procedure GetFormatSettings;
  68. procedure GetLocaleFormatSettings(LCID: Integer; var FormatSettings: TFormatSettings); platform;
  69. implementation
  70. uses
  71. sysconst,
  72. windirs;
  73. var
  74. FindExInfoDefaults : TFINDEX_INFO_LEVELS = FindExInfoStandard;
  75. FindFirstAdditionalFlags : DWord = 0;
  76. function WinCheck(res:boolean):boolean;
  77. begin
  78. if not res then
  79. RaiseLastOSError;
  80. result:=res;
  81. end;
  82. function Win32Check(res:boolean):boolean;inline;
  83. begin
  84. result:=WinCheck(res);
  85. end;
  86. procedure RaiseLastWin32Error;
  87. begin
  88. RaiseLastOSError;
  89. end;
  90. function CheckWin32Version(Major : Integer): Boolean;
  91. begin
  92. Result:=CheckWin32Version(Major,0)
  93. end;
  94. function CheckWin32Version(Major,Minor: Integer): Boolean;
  95. begin
  96. Result:=(Win32MajorVersion>dword(Major)) or
  97. ((Win32MajorVersion=dword(Major)) and (Win32MinorVersion>=dword(Minor)));
  98. end;
  99. function GetFileVersion(const AFileName:string):Cardinal;
  100. var
  101. { useful only as long as we don't need to touch different stack pages }
  102. buf : array[0..3071] of byte;
  103. bufp : pointer;
  104. fn : string;
  105. valsize,
  106. size : DWORD;
  107. h : DWORD;
  108. valrec : PVSFixedFileInfo;
  109. begin
  110. result:=$fffffff;
  111. fn:=AFileName;
  112. UniqueString(fn);
  113. size:=GetFileVersionInfoSizeA(pchar(fn),@h);
  114. if size>sizeof(buf) then
  115. begin
  116. getmem(bufp,size);
  117. try
  118. if GetFileVersionInfoA(pchar(fn),h,size,bufp) then
  119. if VerQueryValue(bufp,'\',valrec,valsize) then
  120. result:=valrec^.dwFileVersionMS;
  121. finally
  122. freemem(bufp);
  123. end;
  124. end
  125. else
  126. begin
  127. if GetFileVersionInfoA(pchar(fn),h,size,@buf) then
  128. if VerQueryValue(@buf,'\',valrec,valsize) then
  129. result:=valrec^.dwFileVersionMS;
  130. end;
  131. end;
  132. function GetFileVersion(const AFileName:UnicodeString):Cardinal;
  133. var
  134. { useful only as long as we don't need to touch different stack pages }
  135. buf : array[0..3071] of byte;
  136. bufp : pointer;
  137. fn : unicodestring;
  138. valsize,
  139. size : DWORD;
  140. h : DWORD;
  141. valrec : PVSFixedFileInfo;
  142. begin
  143. result:=$fffffff;
  144. fn:=AFileName;
  145. UniqueString(fn);
  146. size:=GetFileVersionInfoSizeW(pwidechar(fn),@h);
  147. if size>sizeof(buf) then
  148. begin
  149. getmem(bufp,size);
  150. try
  151. if GetFileVersionInfoW(pwidechar(fn),h,size,bufp) then
  152. if VerQueryValue(bufp,'\',valrec,valsize) then
  153. result:=valrec^.dwFileVersionMS;
  154. finally
  155. freemem(bufp);
  156. end;
  157. end
  158. else
  159. begin
  160. if GetFileVersionInfoW(pwidechar(fn),h,size,@buf) then
  161. if VerQueryValueW(@buf,'\',valrec,valsize) then
  162. result:=valrec^.dwFileVersionMS;
  163. end;
  164. end;
  165. {$define HASCREATEGUID}
  166. {$define HASEXPANDUNCFILENAME}
  167. {$DEFINE FPC_NOGENERICANSIROUTINES}
  168. {$DEFINE FPC_FEXPAND_UNC} (* UNC paths are supported *)
  169. {$DEFINE FPC_FEXPAND_DRIVES} (* Full paths begin with drive specification *)
  170. function ConvertEraYearString(Count ,Year,Month,Day : integer) : string; forward;
  171. function ConvertEraString(Count ,Year,Month,Day : integer) : string; forward;
  172. { Include platform independent implementation part }
  173. {$i sysutils.inc}
  174. function GetTempFileName(Dir,Prefix: PChar; uUnique: DWORD; TempFileName: PChar):DWORD;
  175. begin
  176. Result:= Windows.GetTempFileNameA(Dir,Prefix,uUnique,TempFileName);
  177. end;
  178. { UUID generation. }
  179. function CoCreateGuid(out guid: TGUID): HResult; stdcall; external 'ole32.dll' name 'CoCreateGuid';
  180. function SysCreateGUID(out Guid: TGUID): Integer;
  181. begin
  182. Result := Integer(CoCreateGuid(Guid));
  183. end;
  184. function ExpandUNCFileName (const filename:rawbytestring) : rawbytestring;
  185. { returns empty string on errors }
  186. var
  187. u: unicodestring;
  188. begin
  189. { prevent data loss due to unsupported characters in ansi code page }
  190. u:=ExpandUNCFileName(unicodestring(filename));
  191. widestringmanager.Unicode2AnsiMoveProc(punicodechar(u),result,DefaultRTLFileSystemCodePage,length(u));
  192. end;
  193. function ExpandUNCFileName (const filename:unicodestring) : unicodestring;
  194. { returns empty string on errors }
  195. var
  196. s : unicodestring;
  197. size : dword;
  198. rc : dword;
  199. buf : pwidechar;
  200. begin
  201. s := ExpandFileName (filename);
  202. s := s + #0;
  203. size := max_path;
  204. getmem(buf,size);
  205. try
  206. rc := WNetGetUniversalNameW (pwidechar(s), UNIVERSAL_NAME_INFO_LEVEL, buf, @size);
  207. if rc=ERROR_MORE_DATA then
  208. begin
  209. buf:=reallocmem(buf,size);
  210. rc := WNetGetUniversalNameW (pwidechar(s), UNIVERSAL_NAME_INFO_LEVEL, buf, @size);
  211. end;
  212. if rc = NO_ERROR then
  213. Result := PRemoteNameInfoW(buf)^.lpUniversalName
  214. else if rc = ERROR_NOT_CONNECTED then
  215. Result := filename
  216. else
  217. Result := '';
  218. finally
  219. freemem(buf);
  220. end;
  221. end;
  222. {****************************************************************************
  223. File Functions
  224. ****************************************************************************}
  225. const
  226. AccessMode: array[0..2] of Cardinal = (
  227. GENERIC_READ,
  228. GENERIC_WRITE,
  229. GENERIC_READ or GENERIC_WRITE or FILE_WRITE_ATTRIBUTES);
  230. ShareModes: array[0..4] of Integer = (
  231. 0,
  232. 0,
  233. FILE_SHARE_READ,
  234. FILE_SHARE_WRITE,
  235. FILE_SHARE_READ or FILE_SHARE_WRITE);
  236. function FileFlush(Handle: THandle): Boolean;
  237. begin
  238. Result:= FlushFileBuffers(Handle);
  239. end;
  240. Function FileOpen (Const FileName : unicodestring; Mode : Integer) : THandle;
  241. begin
  242. result := CreateFileW(PWideChar(FileName), dword(AccessMode[Mode and 3]),
  243. dword(ShareModes[(Mode and $F0) shr 4]), nil, OPEN_EXISTING,
  244. FILE_ATTRIBUTE_NORMAL, 0);
  245. //if fail api return feInvalidHandle (INVALIDE_HANDLE=feInvalidHandle=-1)
  246. end;
  247. Function FileCreate (Const FileName : UnicodeString) : THandle;
  248. begin
  249. FileCreate:=FileCreate(FileName, fmShareExclusive, 0);
  250. end;
  251. Function FileCreate (Const FileName : UnicodeString; Rights:longint) : THandle;
  252. begin
  253. FileCreate:=FileCreate(FileName, fmShareExclusive, Rights);
  254. end;
  255. Function FileCreate (Const FileName : UnicodeString; ShareMode : Integer; Rights : Integer) : THandle;
  256. begin
  257. Result := CreateFileW(PwideChar(FileName), GENERIC_READ or GENERIC_WRITE,
  258. dword(ShareModes[(ShareMode and $F0) shr 4]), nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  259. end;
  260. Function FileRead (Handle : THandle; out Buffer; Count : longint) : Longint;
  261. Var
  262. res : dword;
  263. begin
  264. if ReadFile(Handle, Buffer, Count, res, nil) then
  265. FileRead:=Res
  266. else
  267. FileRead:=-1;
  268. end;
  269. Function FileWrite (Handle : THandle; const Buffer; Count : Longint) : Longint;
  270. Var
  271. Res : dword;
  272. begin
  273. if WriteFile(Handle, Buffer, Count, Res, nil) then
  274. FileWrite:=Res
  275. else
  276. FileWrite:=-1;
  277. end;
  278. Function FileSeek (Handle : THandle;FOffset,Origin : Longint) : Longint;
  279. begin
  280. Result := longint(SetFilePointer(Handle, FOffset, nil, Origin));
  281. end;
  282. Function FileSeek (Handle : THandle; FOffset: Int64; Origin: Longint) : Int64;
  283. var
  284. rslt: Int64Rec;
  285. begin
  286. rslt := Int64Rec(FOffset);
  287. rslt.lo := SetFilePointer(Handle, rslt.lo, @rslt.hi, Origin);
  288. if (rslt.lo = $FFFFFFFF) and (GetLastError <> 0) then
  289. rslt.hi := $FFFFFFFF;
  290. Result := Int64(rslt);
  291. end;
  292. Procedure FileClose (Handle : THandle);
  293. begin
  294. CloseHandle(Handle);
  295. end;
  296. Function FileTruncate (Handle : THandle;Size: Int64) : boolean;
  297. begin
  298. {
  299. Result:=longint(SetFilePointer(handle,Size,nil,FILE_BEGIN))<>-1;
  300. }
  301. if FileSeek (Handle, Size, FILE_BEGIN) = Size then
  302. Result:=SetEndOfFile(handle)
  303. else
  304. Result := false;
  305. end;
  306. Function DosToWinTime (DTime:longint;Var Wtime : TFileTime):longbool;
  307. var
  308. lft : TFileTime;
  309. begin
  310. DosToWinTime:=DosDateTimeToFileTime(longrec(dtime).hi,longrec(dtime).lo,@lft) and
  311. LocalFileTimeToFileTime(lft,Wtime);
  312. end;
  313. Function WinToDosTime (Var Wtime : TFileTime;var DTime:longint):longbool;
  314. var
  315. lft : TFileTime;
  316. begin
  317. WinToDosTime:=FileTimeToLocalFileTime(WTime,lft) and
  318. FileTimeToDosDateTime(lft,Longrec(Dtime).Hi,LongRec(DTIME).lo);
  319. end;
  320. Function FileAge (Const FileName : UnicodeString): Int64;
  321. var
  322. Handle: THandle;
  323. FindData: TWin32FindDataW;
  324. tmpdtime : longint;
  325. begin
  326. Handle := FindFirstFileW(Pwidechar(FileName), FindData);
  327. if Handle <> INVALID_HANDLE_VALUE then
  328. begin
  329. Windows.FindClose(Handle);
  330. if (FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) = 0 then
  331. If WinToDosTime(FindData.ftLastWriteTime,tmpdtime) then
  332. begin
  333. result:=tmpdtime;
  334. exit;
  335. end;
  336. end;
  337. Result := -1;
  338. end;
  339. type
  340. TSymLinkResult = (
  341. slrOk,
  342. slrNoSymLink,
  343. slrError
  344. );
  345. function FileGetSymLinkTargetInt(const FileName: UnicodeString; out SymLinkRec: TUnicodeSymLinkRec; RaiseErrorOnMissing: Boolean): TSymLinkResult;
  346. { reparse point specific declarations from Windows headers }
  347. const
  348. IO_REPARSE_TAG_MOUNT_POINT = $A0000003;
  349. IO_REPARSE_TAG_SYMLINK = $A000000C;
  350. ERROR_REPARSE_TAG_INVALID = 4393;
  351. FSCTL_GET_REPARSE_POINT = $900A8;
  352. MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 16 * 1024;
  353. SYMLINK_FLAG_RELATIVE = 1;
  354. FILE_FLAG_OPEN_REPARSE_POINT = $200000;
  355. FILE_READ_EA = $8;
  356. type
  357. TReparseDataBuffer = record
  358. ReparseTag: ULONG;
  359. ReparseDataLength: Word;
  360. Reserved: Word;
  361. SubstituteNameOffset: Word;
  362. SubstituteNameLength: Word;
  363. PrintNameOffset: Word;
  364. PrintNameLength: Word;
  365. case ULONG of
  366. IO_REPARSE_TAG_MOUNT_POINT: (
  367. PathBufferMount: array[0..4095] of WCHAR);
  368. IO_REPARSE_TAG_SYMLINK: (
  369. Flags: ULONG;
  370. PathBufferSym: array[0..4095] of WCHAR);
  371. end;
  372. const
  373. CShareAny = FILE_SHARE_READ or FILE_SHARE_WRITE or FILE_SHARE_DELETE;
  374. COpenReparse = FILE_FLAG_OPEN_REPARSE_POINT or FILE_FLAG_BACKUP_SEMANTICS;
  375. var
  376. HFile, Handle: THandle;
  377. PBuffer: ^TReparseDataBuffer;
  378. BytesReturned: DWORD;
  379. begin
  380. Result := slrError;
  381. SymLinkRec := Default(TUnicodeSymLinkRec);
  382. HFile := CreateFileW(PUnicodeChar(FileName), FILE_READ_EA, CShareAny, Nil, OPEN_EXISTING, COpenReparse, 0);
  383. if HFile <> INVALID_HANDLE_VALUE then
  384. try
  385. GetMem(PBuffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
  386. try
  387. if DeviceIoControl(HFile, FSCTL_GET_REPARSE_POINT, Nil, 0,
  388. PBuffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE, @BytesReturned, Nil) then begin
  389. case PBuffer^.ReparseTag of
  390. IO_REPARSE_TAG_MOUNT_POINT: begin
  391. SymLinkRec.TargetName := WideCharLenToString(
  392. @PBuffer^.PathBufferMount[4 { skip start '\??\' } +
  393. PBuffer^.SubstituteNameOffset div SizeOf(WCHAR)],
  394. PBuffer^.SubstituteNameLength div SizeOf(WCHAR) - 4);
  395. end;
  396. IO_REPARSE_TAG_SYMLINK: begin
  397. SymLinkRec.TargetName := WideCharLenToString(
  398. @PBuffer^.PathBufferSym[PBuffer^.PrintNameOffset div SizeOf(WCHAR)],
  399. PBuffer^.PrintNameLength div SizeOf(WCHAR));
  400. if (PBuffer^.Flags and SYMLINK_FLAG_RELATIVE) <> 0 then
  401. SymLinkRec.TargetName := ExpandFileName(ExtractFilePath(FileName) + SymLinkRec.TargetName);
  402. end;
  403. end;
  404. if SymLinkRec.TargetName <> '' then begin
  405. Handle := FindFirstFileExW(PUnicodeChar(SymLinkRec.TargetName), FindExInfoDefaults , @SymLinkRec.FindData,
  406. FindExSearchNameMatch, Nil, 0);
  407. if Handle <> INVALID_HANDLE_VALUE then begin
  408. Windows.FindClose(Handle);
  409. SymLinkRec.Attr := SymLinkRec.FindData.dwFileAttributes;
  410. SymLinkRec.Size := QWord(SymLinkRec.FindData.nFileSizeHigh) shl 32 + QWord(SymLinkRec.FindData.nFileSizeLow);
  411. end else if RaiseErrorOnMissing then
  412. raise EDirectoryNotFoundException.Create(SysErrorMessage(GetLastOSError))
  413. else
  414. SymLinkRec.TargetName := '';
  415. end else begin
  416. SetLastError(ERROR_REPARSE_TAG_INVALID);
  417. Result := slrNoSymLink;
  418. end;
  419. end else
  420. SetLastError(ERROR_REPARSE_TAG_INVALID);
  421. finally
  422. FreeMem(PBuffer);
  423. end;
  424. finally
  425. CloseHandle(HFile);
  426. end;
  427. if SymLinkRec.TargetName <> '' then
  428. Result := slrOk
  429. end;
  430. function FileGetSymLinkTarget(const FileName: UnicodeString; out SymLinkRec: TUnicodeSymLinkRec): Boolean;
  431. begin
  432. Result := FileGetSymLinkTargetInt(FileName, SymLinkRec, True) = slrOk;
  433. end;
  434. function FileOrDirExists(const FileOrDirName: UnicodeString; CheckDir: Boolean; FollowLink: Boolean): Boolean;
  435. const
  436. CDirAttributes: array[Boolean] of DWORD = (0, FILE_ATTRIBUTE_DIRECTORY);
  437. function FoundByEnum: Boolean;
  438. var
  439. FindData: TWin32FindDataW;
  440. Handle: THandle;
  441. begin
  442. { FindFirstFileEx is faster than FindFirstFile }
  443. Handle := FindFirstFileExW(PUnicodeChar(FileOrDirName), FindExInfoDefaults , @FindData,
  444. FindExSearchNameMatch, Nil, 0);
  445. Result := Handle <> INVALID_HANDLE_VALUE;
  446. if Result then begin
  447. Windows.FindClose(Handle);
  448. Result := (FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) = CDirAttributes[CheckDir];
  449. end;
  450. end;
  451. const
  452. CNotExistsErrors = [
  453. ERROR_FILE_NOT_FOUND,
  454. ERROR_PATH_NOT_FOUND,
  455. ERROR_INVALID_NAME, // protects from names in the form of masks like '*'
  456. ERROR_INVALID_DRIVE,
  457. ERROR_NOT_READY,
  458. ERROR_INVALID_PARAMETER,
  459. ERROR_BAD_PATHNAME,
  460. ERROR_BAD_NETPATH,
  461. ERROR_BAD_NET_NAME
  462. ];
  463. var
  464. Attr : DWord;
  465. slr : TUnicodeSymLinkRec;
  466. res : TSymLinkResult;
  467. begin
  468. Attr := GetFileAttributesW(PUnicodeChar(FileOrDirName));
  469. if Attr = INVALID_FILE_ATTRIBUTES then
  470. Result := not (GetLastError in CNotExistsErrors) and FoundByEnum
  471. else begin
  472. Result := (Attr and FILE_ATTRIBUTE_DIRECTORY) = CDirAttributes[CheckDir];
  473. if Result and FollowLink and ((Attr and FILE_ATTRIBUTE_REPARSE_POINT) <> 0) then begin
  474. res := FileGetSymLinkTargetInt(FileOrDirName, slr, False);
  475. case res of
  476. slrOk:
  477. Result := FileOrDirExists(slr.TargetName, CheckDir, False);
  478. slrNoSymLink:
  479. Result := True;
  480. else
  481. Result := False;
  482. end;
  483. end;
  484. end;
  485. end;
  486. Function FileExists (Const FileName : UnicodeString; FollowLink : Boolean) : Boolean;
  487. begin
  488. Result := FileOrDirExists(FileName, False, FollowLink);
  489. end;
  490. Function DirectoryExists (Const Directory : UnicodeString; FollowLink : Boolean) : Boolean;
  491. begin
  492. Result := FileOrDirExists(Directory, True, FollowLink);
  493. end;
  494. Function FindMatch(var f: TAbstractSearchRec; var Name: UnicodeString) : Longint;
  495. var
  496. tmpdtime : longint;
  497. begin
  498. { Find file with correct attribute }
  499. While (F.FindData.dwFileAttributes and cardinal(F.ExcludeAttr))<>0 do
  500. begin
  501. if not FindNextFileW (F.FindHandle,F.FindData) then
  502. begin
  503. Result:=GetLastError;
  504. exit;
  505. end;
  506. end;
  507. { Convert some attributes back }
  508. WinToDosTime(F.FindData.ftLastWriteTime,tmpdtime);
  509. F.Time:=tmpdtime;
  510. f.size:=F.FindData.NFileSizeLow+(qword(maxdword)+1)*F.FindData.NFileSizeHigh;
  511. f.attr:=F.FindData.dwFileAttributes;
  512. Name:=F.FindData.cFileName;
  513. Result:=0;
  514. end;
  515. Procedure InternalFindClose (var Handle: THandle; var FindData: TFindData);
  516. begin
  517. if Handle <> INVALID_HANDLE_VALUE then
  518. begin
  519. Windows.FindClose(Handle);
  520. Handle:=INVALID_HANDLE_VALUE;
  521. end;
  522. end;
  523. Function InternalFindFirst (Const Path : UnicodeString; Attr : Longint; out Rslt : TAbstractSearchRec; var Name : UnicodeString) : Longint;
  524. begin
  525. Name:=Path;
  526. Rslt.Attr:=attr;
  527. Rslt.ExcludeAttr:=(not Attr) and ($1e);
  528. { $1e = faHidden or faSysFile or faVolumeID or faDirectory }
  529. { FindFirstFile is a Win32 Call }
  530. Rslt.FindHandle:=FindFirstFileExW(PUnicodeChar(Path), FindExInfoDefaults , @Rslt.FindData,
  531. FindExSearchNameMatch, Nil, FindFirstAdditionalFlags);
  532. If Rslt.FindHandle=Invalid_Handle_value then
  533. begin
  534. Result:=GetLastError;
  535. exit;
  536. end;
  537. { Find file with correct attribute }
  538. Result:=FindMatch(Rslt,Name);
  539. if (Result<>0) then
  540. InternalFindClose(Rslt.FindHandle,Rslt.FindData);
  541. end;
  542. Function InternalFindNext (Var Rslt : TAbstractSearchRec; var Name: UnicodeString) : Longint;
  543. begin
  544. if FindNextFileW(Rslt.FindHandle, Rslt.FindData) then
  545. Result := FindMatch(Rslt, Name)
  546. else
  547. Result := GetLastError;
  548. end;
  549. Function FileGetDate (Handle : THandle) : Int64;
  550. Var
  551. FT : TFileTime;
  552. tmpdtime : longint;
  553. begin
  554. If GetFileTime(Handle,nil,nil,@ft) and
  555. WinToDosTime(FT,tmpdtime) then
  556. begin
  557. result:=tmpdtime;
  558. exit;
  559. end;
  560. Result:=-1;
  561. end;
  562. Function FileGetDate (Handle : THandle; out FileDateTime: TDateTime) : Boolean;
  563. Var
  564. FT : TFileTime;
  565. begin
  566. Result :=
  567. GetFileTime(Handle,nil,nil,@ft) and
  568. FindDataTimeToDateTime(FT, FileDateTime);
  569. end;
  570. Function FileGetDateUTC (Handle : THandle; out FileDateTimeUTC: TDateTime) : Boolean;
  571. Var
  572. FT : TFileTime;
  573. begin
  574. Result :=
  575. GetFileTime(Handle,nil,nil,@ft) and
  576. FindDataTimeToUTC(FT, FileDateTimeUTC);
  577. end;
  578. Function FileSetDate (Handle : THandle;Age : Int64) : Longint;
  579. Var
  580. FT: TFileTime;
  581. begin
  582. Result := 0;
  583. if DosToWinTime(Age,FT) and
  584. SetFileTime(Handle, nil, nil, @FT) then
  585. Exit;
  586. Result := GetLastError;
  587. end;
  588. Function FileSetDate (Handle : THandle; const Age: TDateTime) : Boolean;
  589. var
  590. FT: TFiletime;
  591. LT: TFiletime;
  592. ST: TSystemTime;
  593. begin
  594. DateTimeToSystemTime(Age,ST);
  595. Result :=
  596. SystemTimeToFileTime(ST,LT)
  597. and LocalFileTimeToFileTime(LT,FT)
  598. and SetFileTime(Handle,nil,nil,@FT);
  599. end;
  600. Function FileSetDateUTC (Handle : THandle; const AgeUTC: TDateTime) : Boolean;
  601. var
  602. FT: TFiletime;
  603. ST: TSystemTime;
  604. begin
  605. DateTimeToSystemTime(AgeUTC,ST);
  606. Result :=
  607. SystemTimeToFileTime(ST,FT) and
  608. SetFileTime(Handle,nil,nil,@FT);
  609. end;
  610. {$IFDEF OS_FILESETDATEBYNAME}
  611. Function FileSetDate (Const FileName : UnicodeString;Age : Int64) : Longint;
  612. Var
  613. fd : THandle;
  614. begin
  615. FD := CreateFileW (PWideChar (FileName), GENERIC_READ or GENERIC_WRITE,
  616. FILE_SHARE_WRITE, nil, OPEN_EXISTING,
  617. FILE_FLAG_BACKUP_SEMANTICS, 0);
  618. If (Fd<>feInvalidHandle) then
  619. try
  620. Result:=FileSetDate(fd,Age);
  621. finally
  622. FileClose(fd);
  623. end
  624. else
  625. Result:=GetLastOSError;
  626. end;
  627. {$ENDIF}
  628. Function FileGetAttr (Const FileName : UnicodeString) : Longint;
  629. begin
  630. Result:=Longint(GetFileAttributesW(PWideChar(FileName)));
  631. end;
  632. Function FileSetAttr (Const Filename : UnicodeString; Attr: longint) : Longint;
  633. begin
  634. if SetFileAttributesW(PWideChar(FileName), Attr) then
  635. Result:=0
  636. else
  637. Result := GetLastError;
  638. end;
  639. Function DeleteFile (Const FileName : UnicodeString) : Boolean;
  640. begin
  641. Result:=Windows.DeleteFileW(PWidechar(FileName));
  642. end;
  643. Function RenameFile (Const OldName, NewName : UnicodeString) : Boolean;
  644. begin
  645. Result := MoveFileW(PWideChar(OldName), PWideChar(NewName));
  646. end;
  647. {****************************************************************************
  648. Disk Functions
  649. ****************************************************************************}
  650. type
  651. TGetDiskFreeSpaceEx = function(drive:pchar;var availableforcaller,total,free):longbool;stdcall;
  652. var
  653. GetDiskFreeSpaceEx : TGetDiskFreeSpaceEx;
  654. function diskfree(drive : byte) : int64;
  655. var
  656. disk : array[1..4] of char;
  657. secs,bytes,
  658. free,total : dword;
  659. qwtotal,qwfree,qwcaller : int64;
  660. begin
  661. if drive=0 then
  662. begin
  663. disk[1]:='\';
  664. disk[2]:=#0;
  665. end
  666. else
  667. begin
  668. disk[1]:=chr(drive+64);
  669. disk[2]:=':';
  670. disk[3]:='\';
  671. disk[4]:=#0;
  672. end;
  673. if assigned(GetDiskFreeSpaceEx) then
  674. begin
  675. if GetDiskFreeSpaceEx(@disk[1],qwcaller,qwtotal,qwfree) then
  676. diskfree:=qwfree
  677. else
  678. diskfree:=-1;
  679. end
  680. else
  681. begin
  682. if GetDiskFreeSpace(@disk[1],secs,bytes,free,total) then
  683. diskfree:=int64(free)*secs*bytes
  684. else
  685. diskfree:=-1;
  686. end;
  687. end;
  688. function disksize(drive : byte) : int64;
  689. var
  690. disk : array[1..4] of char;
  691. secs,bytes,
  692. free,total : dword;
  693. qwtotal,qwfree,qwcaller : int64;
  694. begin
  695. if drive=0 then
  696. begin
  697. disk[1]:='\';
  698. disk[2]:=#0;
  699. end
  700. else
  701. begin
  702. disk[1]:=chr(drive+64);
  703. disk[2]:=':';
  704. disk[3]:='\';
  705. disk[4]:=#0;
  706. end;
  707. if assigned(GetDiskFreeSpaceEx) then
  708. begin
  709. if GetDiskFreeSpaceEx(@disk[1],qwcaller,qwtotal,qwfree) then
  710. disksize:=qwtotal
  711. else
  712. disksize:=-1;
  713. end
  714. else
  715. begin
  716. if GetDiskFreeSpace(@disk[1],secs,bytes,free,total) then
  717. disksize:=int64(total)*secs*bytes
  718. else
  719. disksize:=-1;
  720. end;
  721. end;
  722. {****************************************************************************
  723. Time Functions
  724. ****************************************************************************}
  725. Procedure GetLocalTime(var SystemTime: TSystemTime);
  726. begin
  727. windows.Getlocaltime(SystemTime);
  728. end;
  729. function GetUniversalTime(var SystemTime: TSystemTime): Boolean;
  730. begin
  731. windows.GetSystemTime(SystemTime);
  732. Result:=True;
  733. end;
  734. function GetLocalTimeOffset: Integer;
  735. var
  736. TZInfo: TTimeZoneInformation;
  737. begin
  738. case GetTimeZoneInformation(TZInfo) of
  739. TIME_ZONE_ID_UNKNOWN:
  740. Result := TZInfo.Bias;
  741. TIME_ZONE_ID_STANDARD:
  742. Result := TZInfo.Bias + TZInfo.StandardBias;
  743. TIME_ZONE_ID_DAYLIGHT:
  744. Result := TZInfo.Bias + TZInfo.DaylightBias;
  745. else
  746. Result := 0;
  747. end;
  748. end;
  749. function GetLocalTimeOffset(const DateTime: TDateTime; const InputIsUTC: Boolean; out Offset: Integer): Boolean;
  750. var
  751. Year: Integer;
  752. const
  753. DaysPerWeek = 7;
  754. // MonthOf and YearOf are not available in SysUtils
  755. function MonthOf(const AValue: TDateTime): Word;
  756. var
  757. Y,D : Word;
  758. begin
  759. DecodeDate(AValue,Y,Result,D);
  760. end;
  761. function YearOf(const AValue: TDateTime): Word;
  762. var
  763. D,M : Word;
  764. begin
  765. DecodeDate(AValue,Result,D,M);
  766. end;
  767. function RelWeekDayToDateTime(const SysTime: TSystemTime): TDateTime;
  768. var
  769. WeekDay, IncDays: Integer;
  770. begin
  771. // get first day in month
  772. Result := EncodeDate(Year, SysTime.Month, 1);
  773. WeekDay := DayOfWeek(Result)-1;
  774. // get the correct first weekday in month
  775. IncDays := SysTime.wDayOfWeek-WeekDay;
  776. if IncDays<0 then
  777. Inc(IncDays, DaysPerWeek);
  778. // inc weeks
  779. Result := Result+IncDays+DaysPerWeek*(SysTime.Day-1);
  780. // SysTime.DayOfWeek=5 means the last one - check if we are not in the next month
  781. while (MonthOf(Result)>SysTime.Month) do
  782. Result := Result-DaysPerWeek;
  783. Result := Result+EncodeTime(SysTime.Hour, SysTime.Minute, SysTime.Second, SysTime.Millisecond);
  784. end;
  785. var
  786. TZInfo: TTimeZoneInformation;
  787. DSTStart, DSTEnd: TDateTime;
  788. begin
  789. Year := YearOf(DateTime);
  790. TZInfo := Default(TTimeZoneInformation);
  791. // GetTimeZoneInformationForYear is supported only on Vista and newer
  792. if not ((Win32MajorVersion>=6) and GetTimeZoneInformationForYear(Year, nil, TZInfo)) then
  793. Exit(False);
  794. if (TZInfo.StandardDate.Month>0) and (TZInfo.DaylightDate.Month>0) then
  795. begin // there is DST
  796. // DaylightDate and StandardDate are local times
  797. DSTStart := RelWeekDayToDateTime(TZInfo.DaylightDate);
  798. DSTEnd := RelWeekDayToDateTime(TZInfo.StandardDate);
  799. if InputIsUTC then
  800. begin
  801. DSTStart := DSTStart + (TZInfo.Bias+TZInfo.StandardBias)/MinsPerDay;
  802. DSTEnd := DSTEnd + (TZInfo.Bias+TZInfo.DaylightBias)/MinsPerDay;
  803. end;
  804. if (DSTStart<=DateTime) and (DateTime<DSTEnd) then
  805. Offset := TZInfo.Bias+TZInfo.DaylightBias
  806. else
  807. Offset := TZInfo.Bias+TZInfo.StandardBias;
  808. end else // no DST
  809. Offset := TZInfo.Bias;
  810. Result := True;
  811. end;
  812. function GetTickCount: LongWord;
  813. begin
  814. Result := Windows.GetTickCount;
  815. end;
  816. {$IFNDEF WINCE}
  817. type
  818. TGetTickCount64 = function : QWord; stdcall;
  819. var
  820. WinGetTickCount64: TGetTickCount64 = Nil;
  821. {$ENDIF}
  822. function GetTickCount64: QWord;
  823. begin
  824. {$IFNDEF WINCE}
  825. if Assigned(WinGetTickCount64) then
  826. Exit(WinGetTickCount64());
  827. { on Vista and newer there is a GetTickCount64 implementation }
  828. if Win32MajorVersion >= 6 then begin
  829. WinGetTickCount64 := TGetTickCount64(GetProcAddress(GetModuleHandle('kernel32.dll'), 'GetTickCount64'));
  830. Result := WinGetTickCount64();
  831. end else
  832. {$ENDIF}
  833. Result := Windows.GetTickCount;
  834. end;
  835. {****************************************************************************
  836. Misc Functions
  837. ****************************************************************************}
  838. procedure sysbeep;
  839. begin
  840. MessageBeep(0);
  841. end;
  842. {****************************************************************************
  843. Locale Functions
  844. ****************************************************************************}
  845. function GetLocaleStr(LID, LT: Longint; const Def: string): ShortString;
  846. var
  847. L: Integer;
  848. Buf: array[0..255] of Char;
  849. begin
  850. L := GetLocaleInfoA(LID, LT, Buf, SizeOf(Buf));
  851. if L > 0 then
  852. SetString(Result, @Buf[0], L - 1)
  853. else
  854. Result := Def;
  855. end;
  856. function GetLocaleChar(LID, LT: Longint; Def: Char): Char;
  857. var
  858. Buf: array[0..3] of Char; // sdate allows 4 chars.
  859. begin
  860. if GetLocaleInfoA(LID, LT, Buf, sizeof(buf)) > 0 then
  861. Result := Buf[0]
  862. else
  863. Result := Def;
  864. end;
  865. function ConvertEraString(Count ,Year,Month,Day : integer) : string;
  866. var
  867. ASystemTime: TSystemTime;
  868. wbuf: array[0..100] of WideChar;
  869. ALCID : LCID;
  870. begin
  871. Result := ''; if (Count<=0) then exit;
  872. DateTimeToSystemTime(EncodeDate(Year,Month,Day),ASystemTime);
  873. ALCID := GetThreadLocale;
  874. // ALCID := SysLocale.DefaultLCID;
  875. if GetDateFormatW(ALCID , DATE_USE_ALT_CALENDAR
  876. , @ASystemTime, PWChar('gg')
  877. , @wbuf, SizeOf(wbuf)) > 0 then
  878. begin
  879. if Count = 1 then
  880. wbuf[1] := #0;
  881. Result := string(WideString(wbuf));
  882. end;
  883. end;
  884. function ConvertEraYearString(Count ,Year,Month,Day : integer) : string;
  885. var
  886. ALCID : LCID;
  887. ASystemTime : TSystemTime;
  888. AFormatText : string;
  889. buf : array[0..100] of Char;
  890. begin
  891. Result := '';
  892. DateTimeToSystemTime(EncodeDate(Year,Month,Day),ASystemTime);
  893. if Count <= 2 then
  894. AFormatText := 'yy'
  895. else
  896. AFormatText := 'yyyy';
  897. ALCID := GetThreadLocale;
  898. // ALCID := SysLocale.DefaultLCID;
  899. if GetDateFormatA(ALCID, DATE_USE_ALT_CALENDAR
  900. , @ASystemTime, PChar(AFormatText)
  901. , @buf, SizeOf(buf)) > 0 then
  902. begin
  903. Result := buf;
  904. if (Count = 1) and (Result[1] = '0') then
  905. Result := Copy(Result, 2, Length(Result)-1);
  906. end;
  907. end;
  908. Function GetLocaleInt(LID,TP,Def: LongInt): LongInt;
  909. Var
  910. S: String;
  911. C: Integer;
  912. Begin
  913. S:=GetLocaleStr(LID,TP,'0');
  914. Val(S,Result,C);
  915. If C<>0 Then
  916. Result:=Def;
  917. End;
  918. function EnumEraNames(Names: PChar): WINBOOL; stdcall;
  919. var
  920. i : integer;
  921. begin
  922. Result := False;
  923. for i := Low(EraNames) to High(EraNames) do
  924. if (EraNames[i] = '') then
  925. begin
  926. EraNames[i] := Names;
  927. Result := True;
  928. break;
  929. end;
  930. end;
  931. function EnumEraYearOffsets(YearOffsets: PChar): WINBOOL; stdcall;
  932. var
  933. i : integer;
  934. begin
  935. Result := False;
  936. for i := Low(EraYearOffsets) to High(EraYearOffsets) do
  937. if (EraYearOffsets[i] = -1) then
  938. begin
  939. EraYearOffsets[i] := StrToIntDef(YearOffsets, 0);
  940. Result := True;
  941. break;
  942. end;
  943. end;
  944. procedure GetEraNamesAndYearOffsets;
  945. var
  946. ACALID : CALID;
  947. ALCID : LCID;
  948. buf : array[0..10] of char;
  949. i : integer;
  950. begin
  951. for i:= 1 to MaxEraCount do
  952. begin
  953. EraNames[i] := ''; EraYearOffsets[i] := -1;
  954. end;
  955. ALCID := GetThreadLocale;
  956. if GetLocaleInfoA(ALCID , LOCALE_IOPTIONALCALENDAR, buf, sizeof(buf)) <= 0 then exit;
  957. ACALID := StrToIntDef(buf,1);
  958. if ACALID in [3..5] then
  959. begin
  960. EnumCalendarInfoA(@EnumEraNames, ALCID, ACALID , CAL_SERASTRING);
  961. EnumCalendarInfoA(@EnumEraYearOffsets, ALCID, ACALID, CAL_IYEAROFFSETRANGE);
  962. end;
  963. (*
  964. 1 CAL_GREGORIAN Gregorian (localized)
  965. 2 CAL_GREGORIAN_US Gregorian (English strings always)
  966. 3 CAL_JAPAN Japanese Emperor Era
  967. 4 CAL_TAIWAN Taiwan Calendar
  968. 5 CAL_KOREA Korean Tangun Era
  969. 6 CAL_HIJRI Hijri (Arabic Lunar)
  970. 7 CAL_THAI Thai
  971. 8 CAL_HEBREW Hebrew (Lunar)
  972. 9 CAL_GREGORIAN_ME_FRENCH Gregorian Middle East French
  973. 10 CAL_GREGORIAN_ARABIC Gregorian Arabic
  974. 11 CAL_GREGORIAN_XLIT_ENGLISH Gregorian transliterated English
  975. 12 CAL_GREGORIAN_XLIT_FRENCH Gregorian transliterated French
  976. 23 CAL_UMALQURA Windows Vista or later: Um Al Qura (Arabic lunar) calendar
  977. *)
  978. end;
  979. procedure GetLocaleFormatSettings(LCID: Integer; var FormatSettings: TFormatSettings);
  980. var
  981. HF : Shortstring;
  982. LID : Windows.LCID;
  983. I,Day : longint;
  984. begin
  985. LID := LCID;
  986. with FormatSettings do
  987. begin
  988. { Date stuff }
  989. for I := 1 to 12 do
  990. begin
  991. ShortMonthNames[I]:=GetLocaleStr(LID,LOCALE_SABBREVMONTHNAME1+I-1,ShortMonthNames[i]);
  992. LongMonthNames[I]:=GetLocaleStr(LID,LOCALE_SMONTHNAME1+I-1,LongMonthNames[i]);
  993. end;
  994. for I := 1 to 7 do
  995. begin
  996. Day := (I + 5) mod 7;
  997. ShortDayNames[I]:=GetLocaleStr(LID,LOCALE_SABBREVDAYNAME1+Day,ShortDayNames[i]);
  998. LongDayNames[I]:=GetLocaleStr(LID,LOCALE_SDAYNAME1+Day,LongDayNames[i]);
  999. end;
  1000. DateSeparator := GetLocaleChar(LID, LOCALE_SDATE, '/');
  1001. ShortDateFormat := GetLocaleStr(LID, LOCALE_SSHORTDATE, 'm/d/yy');
  1002. LongDateFormat := GetLocaleStr(LID, LOCALE_SLONGDATE, 'mmmm d, yyyy');
  1003. { Time stuff }
  1004. TimeSeparator := GetLocaleChar(LID, LOCALE_STIME, ':');
  1005. TimeAMString := GetLocaleStr(LID, LOCALE_S1159, 'AM');
  1006. TimePMString := GetLocaleStr(LID, LOCALE_S2359, 'PM');
  1007. if StrToIntDef(GetLocaleStr(LID, LOCALE_ITLZERO, '0'), 0) = 0 then
  1008. HF:='h'
  1009. else
  1010. HF:='hh';
  1011. // No support for 12 hour stuff at the moment...
  1012. ShortTimeFormat := HF+':nn';
  1013. LongTimeFormat := HF + ':nn:ss';
  1014. { Currency stuff }
  1015. CurrencyString:=GetLocaleStr(LID, LOCALE_SCURRENCY, '');
  1016. CurrencyFormat:=StrToIntDef(GetLocaleStr(LID, LOCALE_ICURRENCY, '0'), 0);
  1017. NegCurrFormat:=StrToIntDef(GetLocaleStr(LID, LOCALE_INEGCURR, '0'), 0);
  1018. { Number stuff }
  1019. ThousandSeparator:=GetLocaleChar(LID, LOCALE_STHOUSAND, ',');
  1020. DecimalSeparator:=GetLocaleChar(LID, LOCALE_SDECIMAL, '.');
  1021. CurrencyDecimals:=StrToIntDef(GetLocaleStr(LID, LOCALE_ICURRDIGITS, '0'), 0);
  1022. ListSeparator := GetLocaleChar(LID, LOCALE_SLIST, ',');
  1023. end;
  1024. end;
  1025. procedure GetFormatSettings;
  1026. begin
  1027. GetlocaleFormatSettings(GetThreadLocale, DefaultFormatSettings);
  1028. end;
  1029. Procedure InitLeadBytes;
  1030. var
  1031. I,B,C,E: Byte;
  1032. Info: TCPInfo;
  1033. begin
  1034. GetCPInfo(CP_ACP,Info);
  1035. I:=0;
  1036. With Info do
  1037. begin
  1038. B:=LeadByte[i];
  1039. E:=LeadByte[i+1];
  1040. while (I<MAX_LEADBYTES) and (B<>0) and (E<>0) do
  1041. begin
  1042. for C:=B to E do
  1043. Include(LeadBytes,AnsiChar(C));
  1044. Inc(I,2);
  1045. if (I<MAX_LEADBYTES) then
  1046. begin
  1047. B:=LeadByte[i];
  1048. E:=LeadByte[i+1];
  1049. end;
  1050. end;
  1051. end;
  1052. end;
  1053. Procedure InitInternational;
  1054. var
  1055. {$if defined(CPU386) or defined(CPUX86_64)}
  1056. { A call to GetSystemMetrics changes the value of the 8087 Control Word on
  1057. Pentium4 with WinXP SP2 }
  1058. old8087CW: word;
  1059. {$endif}
  1060. DefaultCustomLocaleID : LCID; // typedef DWORD LCID;
  1061. DefaultCustomLanguageID : Word; // typedef WORD LANGID;
  1062. begin
  1063. /// workaround for Windows 7 bug, see bug report #18574
  1064. SetThreadLocale(GetUserDefaultLCID);
  1065. InitInternationalGeneric;
  1066. {$if defined(CPU386) or defined(CPUX86_64)}
  1067. old8087CW:=Get8087CW;
  1068. {$endif}
  1069. SysLocale.MBCS:=GetSystemMetrics(SM_DBCSENABLED)<>0;
  1070. SysLocale.RightToLeft:=GetSystemMetrics(SM_MIDEASTENABLED)<>0;
  1071. SysLocale.DefaultLCID := $0409;
  1072. SysLocale.PriLangID := LANG_ENGLISH;
  1073. SysLocale.SubLangID := SUBLANG_ENGLISH_US;
  1074. // probably needs update with getthreadlocale. post 2.0.2
  1075. DefaultCustomLocaleID := GetThreadLocale;
  1076. if DefaultCustomLocaleID <> 0 then
  1077. begin
  1078. { Locale Identifiers
  1079. +-------------+---------+-------------------------+
  1080. | Reserved | Sort ID | Language ID |
  1081. +-------------+---------+-------------------------+
  1082. 31 20 19 16 15 0 bit }
  1083. DefaultCustomLanguageID := DefaultCustomLocaleID and $FFFF; // 2^16
  1084. if DefaultCustomLanguageID <> 0 then
  1085. begin
  1086. SysLocale.DefaultLCID := DefaultCustomLocaleID;
  1087. { Language Identifiers
  1088. +-------------------------+-------------------------+
  1089. | SubLanguage ID | Primary Language ID |
  1090. +-------------------------+-------------------------+
  1091. 15 10 9 0 bit }
  1092. SysLocale.PriLangID := DefaultCustomLanguageID and $3ff; // 2^10
  1093. SysLocale.SubLangID := DefaultCustomLanguageID shr 10;
  1094. end;
  1095. end;
  1096. {$if defined(CPU386) or defined(CPUX86_64)}
  1097. Set8087CW(old8087CW);
  1098. {$endif}
  1099. GetFormatSettings;
  1100. if SysLocale.FarEast then GetEraNamesAndYearOffsets;
  1101. end;
  1102. {****************************************************************************
  1103. Target Dependent
  1104. ****************************************************************************}
  1105. function SysErrorMessage(ErrorCode: Integer): String;
  1106. const
  1107. MaxMsgSize = Format_Message_Max_Width_Mask;
  1108. var
  1109. MsgBuffer: unicodestring;
  1110. len: longint;
  1111. begin
  1112. SetLength(MsgBuffer, MaxMsgSize);
  1113. len := FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM,
  1114. nil,
  1115. ErrorCode,
  1116. MakeLangId(LANG_NEUTRAL, SUBLANG_DEFAULT),
  1117. PUnicodeChar(MsgBuffer),
  1118. MaxMsgSize,
  1119. nil);
  1120. // Remove trailing #13#10
  1121. if (len > 1) and (MsgBuffer[len - 1] = #13) and (MsgBuffer[len] = #10) then
  1122. Dec(len, 2);
  1123. SetLength(MsgBuffer, len);
  1124. Result := MsgBuffer;
  1125. end;
  1126. {****************************************************************************
  1127. Initialization code
  1128. ****************************************************************************}
  1129. {$push}
  1130. { GetEnvironmentStrings cannot be checked by CheckPointer function }
  1131. {$checkpointer off}
  1132. Function GetEnvironmentVariable(Const EnvVar : String) : String;
  1133. var
  1134. oemenvvar, oemstr : RawByteString;
  1135. i, hplen : longint;
  1136. hp,p : pchar;
  1137. begin
  1138. oemenvvar:=uppercase(envvar);
  1139. SetCodePage(oemenvvar,CP_OEMCP);
  1140. Result:='';
  1141. p:=GetEnvironmentStringsA;
  1142. hp:=p;
  1143. while hp^<>#0 do
  1144. begin
  1145. oemstr:=hp;
  1146. { cache length, may change after uppercasing depending on code page }
  1147. hplen:=length(oemstr);
  1148. { all environment variables are encoded in the oem code page }
  1149. SetCodePage(oemstr,CP_OEMCP,false);
  1150. i:=pos('=',oemstr);
  1151. if uppercase(copy(oemstr,1,i-1))=oemenvvar then
  1152. begin
  1153. Result:=copy(oemstr,i+1,length(oemstr)-i);
  1154. break;
  1155. end;
  1156. { next string entry}
  1157. hp:=hp+hplen+1;
  1158. end;
  1159. FreeEnvironmentStringsA(p);
  1160. end;
  1161. Function GetEnvironmentVariable(Const EnvVar : UnicodeString) : UnicodeString;
  1162. var
  1163. s, upperenv : Unicodestring;
  1164. i : longint;
  1165. hp,p : pwidechar;
  1166. begin
  1167. Result:='';
  1168. p:=GetEnvironmentStringsW;
  1169. hp:=p;
  1170. upperenv:=uppercase(envvar);
  1171. while hp^<>#0 do
  1172. begin
  1173. s:=hp;
  1174. i:=pos('=',s);
  1175. if uppercase(copy(s,1,i-1))=upperenv then
  1176. begin
  1177. Result:=copy(s,i+1,length(s)-i);
  1178. break;
  1179. end;
  1180. { next string entry}
  1181. hp:=hp+strlen(hp)+1;
  1182. end;
  1183. FreeEnvironmentStringsW(p);
  1184. end;
  1185. Function GetEnvironmentVariableCount : Integer;
  1186. var
  1187. hp,p : pchar;
  1188. begin
  1189. Result:=0;
  1190. p:=GetEnvironmentStringsA;
  1191. hp:=p;
  1192. If (Hp<>Nil) then
  1193. while hp^<>#0 do
  1194. begin
  1195. Inc(Result);
  1196. hp:=hp+strlen(hp)+1;
  1197. end;
  1198. FreeEnvironmentStringsA(p);
  1199. end;
  1200. Function GetEnvironmentString(Index : Integer) : {$ifdef FPC_RTL_UNICODE}UnicodeString{$else}AnsiString{$endif};
  1201. var
  1202. hp,p : pchar;
  1203. {$ifdef FPC_RTL_UNICODE}
  1204. tmpstr : RawByteString;
  1205. {$endif}
  1206. begin
  1207. Result:='';
  1208. p:=GetEnvironmentStringsA;
  1209. hp:=p;
  1210. If (Hp<>Nil) then
  1211. begin
  1212. while (hp^<>#0) and (Index>1) do
  1213. begin
  1214. Dec(Index);
  1215. hp:=hp+strlen(hp)+1;
  1216. end;
  1217. If (hp^<>#0) then
  1218. begin
  1219. {$ifdef FPC_RTL_UNICODE}
  1220. tmpstr:=hp;
  1221. SetCodePage(tmpstr,CP_OEMCP,false);
  1222. Result:=tmpstr;
  1223. {$else}
  1224. Result:=hp;
  1225. SetCodePage(RawByteString(Result),CP_OEMCP,false);
  1226. {$endif}
  1227. end;
  1228. end;
  1229. FreeEnvironmentStringsA(p);
  1230. end;
  1231. {$pop}
  1232. function ExecuteProcess(Const Path: RawByteString; Const ComLine: RawByteString;Flags:TExecuteFlags=[]):integer;
  1233. begin
  1234. result:=ExecuteProcess(Unicodestring(Path),UnicodeString(ComLine),Flags);
  1235. end;
  1236. function ExecuteProcess(Const Path: UnicodeString; Const ComLine: UnicodeString;Flags:TExecuteFlags=[]):integer;
  1237. // win specific function
  1238. var
  1239. SI: TStartupInfoW;
  1240. PI: TProcessInformation;
  1241. Proc : THandle;
  1242. l : DWord;
  1243. CommandLine : unicodestring;
  1244. e : EOSError;
  1245. ExecInherits : longbool;
  1246. begin
  1247. FillChar(SI, SizeOf(SI), 0);
  1248. SI.cb:=SizeOf(SI);
  1249. SI.wShowWindow:=1;
  1250. { always surround the name of the application by quotes
  1251. so that long filenames will always be accepted. But don't
  1252. do it if there are already double quotes, since Win32 does not
  1253. like double quotes which are duplicated!
  1254. }
  1255. if pos('"',path)=0 then
  1256. CommandLine:='"'+path+'"'
  1257. else
  1258. CommandLine:=path;
  1259. if ComLine <> '' then
  1260. CommandLine:=Commandline+' '+ComLine+#0
  1261. else
  1262. CommandLine := CommandLine + #0;
  1263. ExecInherits:=ExecInheritsHandles in Flags;
  1264. if not CreateProcessW(nil, pwidechar(CommandLine),
  1265. Nil, Nil, ExecInherits,$20, Nil, Nil, SI, PI) then
  1266. begin
  1267. e:=EOSError.CreateFmt(SExecuteProcessFailed,[CommandLine,GetLastError]);
  1268. e.ErrorCode:=GetLastError;
  1269. raise e;
  1270. end;
  1271. Proc:=PI.hProcess;
  1272. if WaitForSingleObject(Proc, dword($ffffffff)) <> $ffffffff then
  1273. begin
  1274. GetExitCodeProcess(Proc,l);
  1275. CloseHandle(Proc);
  1276. CloseHandle(PI.hThread);
  1277. result:=l;
  1278. end
  1279. else
  1280. begin
  1281. e:=EOSError.CreateFmt(SExecuteProcessFailed,[CommandLine,GetLastError]);
  1282. e.ErrorCode:=GetLastError;
  1283. CloseHandle(Proc);
  1284. CloseHandle(PI.hThread);
  1285. raise e;
  1286. end;
  1287. end;
  1288. function ExecuteProcess(Const Path: RawByteString; Const ComLine: Array of RawByteString;Flags:TExecuteFlags=[]):integer;
  1289. var
  1290. CommandLine: UnicodeString;
  1291. I: integer;
  1292. begin
  1293. Commandline := '';
  1294. for I := 0 to High (ComLine) do
  1295. if Pos (' ', ComLine [I]) <> 0 then
  1296. CommandLine := CommandLine + ' ' + '"' + ComLine [I] + '"'
  1297. else
  1298. CommandLine := CommandLine + ' ' + Comline [I];
  1299. ExecuteProcess := ExecuteProcess (UnicodeString(Path), CommandLine,Flags);
  1300. end;
  1301. function ExecuteProcess(Const Path: UnicodeString; Const ComLine: Array of UnicodeString;Flags:TExecuteFlags=[]):integer;
  1302. var
  1303. CommandLine: UnicodeString;
  1304. I: integer;
  1305. begin
  1306. Commandline := '';
  1307. for I := 0 to High (ComLine) do
  1308. if Pos (' ', ComLine [I]) <> 0 then
  1309. CommandLine := CommandLine + ' ' + '"' + ComLine [I] + '"'
  1310. else
  1311. CommandLine := CommandLine + ' ' + Comline [I];
  1312. ExecuteProcess := ExecuteProcess (Path,CommandLine,Flags);
  1313. end;
  1314. Procedure Sleep(Milliseconds : Cardinal);
  1315. begin
  1316. Windows.Sleep(MilliSeconds)
  1317. end;
  1318. Function GetLastOSError : Integer;
  1319. begin
  1320. Result:=GetLastError;
  1321. end;
  1322. {****************************************************************************
  1323. Initialization code
  1324. ****************************************************************************}
  1325. var
  1326. kernel32dll : THandle;
  1327. Procedure LoadVersionInfo;
  1328. // and getfreespaceex
  1329. Var
  1330. versioninfo : TOSVERSIONINFO;
  1331. begin
  1332. GetDiskFreeSpaceEx:=nil;
  1333. versioninfo.dwOSVersionInfoSize:=sizeof(versioninfo);
  1334. GetVersionEx(versioninfo);
  1335. Win32Platform:=versionInfo.dwPlatformId;
  1336. Win32MajorVersion:=versionInfo.dwMajorVersion;
  1337. Win32MinorVersion:=versionInfo.dwMinorVersion;
  1338. Win32BuildNumber:=versionInfo.dwBuildNumber;
  1339. Move (versioninfo.szCSDVersion ,Win32CSDVersion[1],128);
  1340. win32CSDVersion[0]:=chr(strlen(pchar(@versioninfo.szCSDVersion)));
  1341. kernel32dll:=GetModuleHandle('kernel32');
  1342. if kernel32dll<>0 then
  1343. GetDiskFreeSpaceEx:=TGetDiskFreeSpaceEx(GetProcAddress(kernel32dll,'GetDiskFreeSpaceExA'));
  1344. if Win32MajorVersion<6 then
  1345. FindExInfoDefaults := FindExInfoStandard; // also searches SFNs. XP only.
  1346. if (Win32MajorVersion>=6) and (Win32MinorVersion>=1) then
  1347. FindFirstAdditionalFlags := FIND_FIRST_EX_LARGE_FETCH; // win7 and 2008R2+
  1348. end;
  1349. Function GetAppConfigDir(Global : Boolean) : String;
  1350. begin
  1351. If Global then
  1352. Result:=GetWindowsSpecialDir(CSIDL_COMMON_APPDATA)
  1353. else
  1354. Result:=GetWindowsSpecialDir(CSIDL_LOCAL_APPDATA);
  1355. If (Result<>'') then
  1356. begin
  1357. if VendorName<>'' then
  1358. Result:=IncludeTrailingPathDelimiter(Result+VendorName);
  1359. Result:=IncludeTrailingPathDelimiter(Result+ApplicationName);
  1360. end
  1361. else
  1362. Result:=IncludeTrailingPathDelimiter(DGetAppConfigDir(Global));
  1363. end;
  1364. Function GetAppConfigFile(Global : Boolean; SubDir : Boolean) : String;
  1365. begin
  1366. result:=DGetAppConfigFile(Global,SubDir);
  1367. end;
  1368. Function GetUserDir : String;
  1369. begin
  1370. Result:=GetWindowsSpecialDir(CSIDL_PROFILE);
  1371. end;
  1372. Procedure InitSysConfigDir;
  1373. begin
  1374. SetLength(SysConfigDir, MAX_PATH);
  1375. SetLength(SysConfigDir, GetWindowsDirectoryA(PChar(SysConfigDir), MAX_PATH));
  1376. end;
  1377. {****************************************************************************
  1378. Target Dependent WideString stuff
  1379. ****************************************************************************}
  1380. { This is the case of Win9x. Limited to current locale of course, but it's better
  1381. than not working at all. }
  1382. function DoCompareStringA(P1, P2: PWideChar; L1, L2: PtrUInt; Flags: DWORD): PtrInt;
  1383. var
  1384. a1, a2: AnsiString;
  1385. begin
  1386. if L1>0 then
  1387. widestringmanager.Wide2AnsiMoveProc(P1,a1,DefaultSystemCodePage,L1);
  1388. if L2>0 then
  1389. widestringmanager.Wide2AnsiMoveProc(P2,a2,DefaultSystemCodePage,L2);
  1390. SetLastError(0);
  1391. Result:=CompareStringA(LOCALE_USER_DEFAULT,Flags,pchar(a1),
  1392. length(a1),pchar(a2),length(a2))-2;
  1393. end;
  1394. function DoCompareStringW(P1, P2: PWideChar; L1, L2: PtrUInt; Flags: DWORD): PtrInt;
  1395. begin
  1396. SetLastError(0);
  1397. Result:=CompareStringW(LOCALE_USER_DEFAULT,Flags,P1,L1,P2,L2)-2;
  1398. if GetLastError=0 then
  1399. Exit;
  1400. if GetLastError=ERROR_CALL_NOT_IMPLEMENTED then // Win9x case
  1401. Result:=DoCompareStringA(P1, P2, L1, L2, Flags);
  1402. if GetLastError<>0 then
  1403. RaiseLastOSError;
  1404. end;
  1405. const
  1406. WinAPICompareFlags : array [TCompareOption] of LongWord
  1407. = ({LINGUISTIC_IGNORECASE, LINGUISTIC_IGNOREDIACRITIC, }NORM_IGNORECASE{,
  1408. NORM_IGNOREKANATYPE, NORM_IGNORENONSPACE, NORM_IGNORESYMBOLS, NORM_IGNOREWIDTH,
  1409. NORM_LINGUISTIC_CASING, SORT_DIGITSASNUMBERS, SORT_STRINGSORT});
  1410. function Win32CompareWideString(const s1, s2 : WideString; Options : TCompareOptions) : PtrInt;
  1411. Var
  1412. O : LongWord;
  1413. CO : TCompareOption;
  1414. begin
  1415. O:=0;
  1416. for CO in TCompareOption do
  1417. if CO in Options then
  1418. O:=O or WinAPICompareFlags[CO];
  1419. Result:=DoCompareStringW(PWideChar(s1), PWideChar(s2), Length(s1), Length(s2), O);
  1420. end;
  1421. function Win32CompareTextWideString(const s1, s2 : WideString) : PtrInt;
  1422. begin
  1423. Result:=DoCompareStringW(PWideChar(s1), PWideChar(s2), Length(s1), Length(s2), NORM_IGNORECASE);
  1424. end;
  1425. function Win32AnsiUpperCase(const s: string): string;
  1426. begin
  1427. if length(s)>0 then
  1428. begin
  1429. result:=s;
  1430. UniqueString(result);
  1431. CharUpperBuffA(pchar(result),length(result));
  1432. end
  1433. else
  1434. result:='';
  1435. end;
  1436. function Win32AnsiLowerCase(const s: string): string;
  1437. begin
  1438. if length(s)>0 then
  1439. begin
  1440. result:=s;
  1441. UniqueString(result);
  1442. CharLowerBuffA(pchar(result),length(result));
  1443. end
  1444. else
  1445. result:='';
  1446. end;
  1447. function Win32AnsiCompareStr(const S1, S2: string): PtrInt;
  1448. begin
  1449. result:=CompareStringA(LOCALE_USER_DEFAULT,0,pchar(s1),length(s1),
  1450. pchar(s2),length(s2))-2;
  1451. end;
  1452. function Win32AnsiCompareText(const S1, S2: string): PtrInt;
  1453. begin
  1454. result:=CompareStringA(LOCALE_USER_DEFAULT,NORM_IGNORECASE,pchar(s1),length(s1),
  1455. pchar(s2),length(s2))-2;
  1456. end;
  1457. function Win32AnsiStrComp(S1, S2: PChar): PtrInt;
  1458. begin
  1459. result:=CompareStringA(LOCALE_USER_DEFAULT,0,s1,-1,s2,-1)-2;
  1460. end;
  1461. function Win32AnsiStrIComp(S1, S2: PChar): PtrInt;
  1462. begin
  1463. result:=CompareStringA(LOCALE_USER_DEFAULT,NORM_IGNORECASE,s1,-1,s2,-1)-2;
  1464. end;
  1465. function Win32AnsiStrLComp(S1, S2: PChar; MaxLen: PtrUInt): PtrInt;
  1466. begin
  1467. result:=CompareStringA(LOCALE_USER_DEFAULT,0,s1,maxlen,s2,maxlen)-2;
  1468. end;
  1469. function Win32AnsiStrLIComp(S1, S2: PChar; MaxLen: PtrUInt): PtrInt;
  1470. begin
  1471. result:=CompareStringA(LOCALE_USER_DEFAULT,NORM_IGNORECASE,s1,maxlen,s2,maxlen)-2;
  1472. end;
  1473. function Win32AnsiStrLower(Str: PChar): PChar;
  1474. begin
  1475. CharLowerA(str);
  1476. result:=str;
  1477. end;
  1478. function Win32AnsiStrUpper(Str: PChar): PChar;
  1479. begin
  1480. CharUpperA(str);
  1481. result:=str;
  1482. end;
  1483. function Win32CompareUnicodeString(const s1, s2 : UnicodeString; Options : TCompareOptions) : PtrInt;
  1484. Var
  1485. O : LongWord;
  1486. CO : TCompareOption;
  1487. begin
  1488. O:=0;
  1489. for CO in TCompareOption do
  1490. if CO in Options then
  1491. O:=O or WinAPICompareFlags[CO];
  1492. Result:=DoCompareStringW(PWideChar(s1), PWideChar(s2), Length(s1), Length(s2), O);
  1493. end;
  1494. function Win32CompareTextUnicodeString(const s1, s2 : UnicodeString) : PtrInt;
  1495. begin
  1496. Result:=DoCompareStringW(PWideChar(s1), PWideChar(s2), Length(s1), Length(s2), NORM_IGNORECASE);
  1497. end;
  1498. { there is a similiar procedure in the system unit which inits the fields which
  1499. are relevant already for the system unit }
  1500. procedure InitWin32Widestrings;
  1501. begin
  1502. { return value: number of code points in the string. Whenever an invalid
  1503. code point is encountered, all characters part of this invalid code point
  1504. are considered to form one "character" and the next character is
  1505. considered to be the start of a new (possibly also invalid) code point }
  1506. //!!! CharLengthPCharProc : function(const Str: PChar): PtrInt;
  1507. { return value:
  1508. -1 if incomplete or invalid code point
  1509. 0 if NULL character,
  1510. > 0 if that's the length in bytes of the code point }
  1511. //!!!! CodePointLengthProc : function(const Str: PChar; MaxLookAead: PtrInt): Ptrint;
  1512. widestringmanager.CompareWideStringProc:=@Win32CompareWideString;
  1513. widestringmanager.UpperAnsiStringProc:=@Win32AnsiUpperCase;
  1514. widestringmanager.LowerAnsiStringProc:=@Win32AnsiLowerCase;
  1515. widestringmanager.CompareStrAnsiStringProc:=@Win32AnsiCompareStr;
  1516. widestringmanager.CompareTextAnsiStringProc:=@Win32AnsiCompareText;
  1517. widestringmanager.StrCompAnsiStringProc:=@Win32AnsiStrComp;
  1518. widestringmanager.StrICompAnsiStringProc:=@Win32AnsiStrIComp;
  1519. widestringmanager.StrLCompAnsiStringProc:=@Win32AnsiStrLComp;
  1520. widestringmanager.StrLICompAnsiStringProc:=@Win32AnsiStrLIComp;
  1521. widestringmanager.StrLowerAnsiStringProc:=@Win32AnsiStrLower;
  1522. widestringmanager.StrUpperAnsiStringProc:=@Win32AnsiStrUpper;
  1523. widestringmanager.CompareUnicodeStringProc:=@Win32CompareUnicodeString;
  1524. end;
  1525. { Platform-specific exception support }
  1526. function WinExceptionObject(code: Longint; const rec: TExceptionRecord): Exception;
  1527. var
  1528. entry: PExceptMapEntry;
  1529. begin
  1530. entry := FindExceptMapEntry(code);
  1531. if assigned(entry) then
  1532. result:=entry^.cls.CreateRes(entry^.msg)
  1533. else
  1534. result:=EExternalException.CreateResFmt(@SExternalException,[rec.ExceptionCode]);
  1535. if result is EExternal then
  1536. EExternal(result).FExceptionRecord:=rec;
  1537. end;
  1538. function WinExceptionClass(code: longint): ExceptClass;
  1539. var
  1540. entry: PExceptMapEntry;
  1541. begin
  1542. entry := FindExceptMapEntry(code);
  1543. if assigned(entry) then
  1544. result:=entry^.cls
  1545. else
  1546. result:=EExternalException;
  1547. end;
  1548. Initialization
  1549. InitWin32Widestrings;
  1550. InitExceptions; { Initialize exceptions. OS independent }
  1551. {$ifdef mswindows} { Keeps exe size down for systems that do not use SEH }
  1552. ExceptObjProc:=@WinExceptionObject;
  1553. ExceptClsProc:=@WinExceptionClass;
  1554. {$endif mswindows}
  1555. InitLeadBytes;
  1556. InitInternational; { Initialize internationalization settings }
  1557. LoadVersionInfo;
  1558. InitSysConfigDir;
  1559. OnBeep:=@SysBeep;
  1560. Finalization
  1561. FreeTerminateProcs;
  1562. DoneExceptions;
  1563. end.