sysutils.pp 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822
  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) : Longint;
  589. var
  590. FT: TFiletime;
  591. LT: TFiletime;
  592. ST: TSystemTime;
  593. begin
  594. DateTimeToSystemTime(Age,ST);
  595. if SystemTimeToFileTime(ST,LT) and LocalFileTimeToFileTime(LT,FT)
  596. and SetFileTime(Handle,nil,nil,@FT) then
  597. Result:=0
  598. else
  599. Result:=GetLastError;
  600. end;
  601. Function FileSetDateUTC (Handle : THandle; const AgeUTC: TDateTime) : Longint;
  602. var
  603. FT: TFiletime;
  604. ST: TSystemTime;
  605. begin
  606. DateTimeToSystemTime(AgeUTC,ST);
  607. if SystemTimeToFileTime(ST,FT) and SetFileTime(Handle,nil,nil,@FT) then
  608. Result:=0
  609. else
  610. Result:=GetLastError;
  611. end;
  612. {$IFDEF OS_FILESETDATEBYNAME}
  613. Function FileSetDate (Const FileName : UnicodeString;Age : Int64) : Longint;
  614. Var
  615. fd : THandle;
  616. begin
  617. FD := CreateFileW (PWideChar (FileName), GENERIC_READ or GENERIC_WRITE,
  618. FILE_SHARE_WRITE, nil, OPEN_EXISTING,
  619. FILE_FLAG_BACKUP_SEMANTICS, 0);
  620. If (Fd<>feInvalidHandle) then
  621. try
  622. Result:=FileSetDate(fd,Age);
  623. finally
  624. FileClose(fd);
  625. end
  626. else
  627. Result:=GetLastOSError;
  628. end;
  629. {$ENDIF}
  630. Function FileGetAttr (Const FileName : UnicodeString) : Longint;
  631. begin
  632. Result:=Longint(GetFileAttributesW(PWideChar(FileName)));
  633. end;
  634. Function FileSetAttr (Const Filename : UnicodeString; Attr: longint) : Longint;
  635. begin
  636. if SetFileAttributesW(PWideChar(FileName), Attr) then
  637. Result:=0
  638. else
  639. Result := GetLastError;
  640. end;
  641. Function DeleteFile (Const FileName : UnicodeString) : Boolean;
  642. begin
  643. Result:=Windows.DeleteFileW(PWidechar(FileName));
  644. end;
  645. Function RenameFile (Const OldName, NewName : UnicodeString) : Boolean;
  646. begin
  647. Result := MoveFileW(PWideChar(OldName), PWideChar(NewName));
  648. end;
  649. {****************************************************************************
  650. Disk Functions
  651. ****************************************************************************}
  652. type
  653. TGetDiskFreeSpaceEx = function(drive:pchar;var availableforcaller,total,free):longbool;stdcall;
  654. var
  655. GetDiskFreeSpaceEx : TGetDiskFreeSpaceEx;
  656. function diskfree(drive : byte) : int64;
  657. var
  658. disk : array[1..4] of char;
  659. secs,bytes,
  660. free,total : dword;
  661. qwtotal,qwfree,qwcaller : int64;
  662. begin
  663. if drive=0 then
  664. begin
  665. disk[1]:='\';
  666. disk[2]:=#0;
  667. end
  668. else
  669. begin
  670. disk[1]:=chr(drive+64);
  671. disk[2]:=':';
  672. disk[3]:='\';
  673. disk[4]:=#0;
  674. end;
  675. if assigned(GetDiskFreeSpaceEx) then
  676. begin
  677. if GetDiskFreeSpaceEx(@disk[1],qwcaller,qwtotal,qwfree) then
  678. diskfree:=qwfree
  679. else
  680. diskfree:=-1;
  681. end
  682. else
  683. begin
  684. if GetDiskFreeSpace(@disk[1],secs,bytes,free,total) then
  685. diskfree:=int64(free)*secs*bytes
  686. else
  687. diskfree:=-1;
  688. end;
  689. end;
  690. function disksize(drive : byte) : int64;
  691. var
  692. disk : array[1..4] of char;
  693. secs,bytes,
  694. free,total : dword;
  695. qwtotal,qwfree,qwcaller : int64;
  696. begin
  697. if drive=0 then
  698. begin
  699. disk[1]:='\';
  700. disk[2]:=#0;
  701. end
  702. else
  703. begin
  704. disk[1]:=chr(drive+64);
  705. disk[2]:=':';
  706. disk[3]:='\';
  707. disk[4]:=#0;
  708. end;
  709. if assigned(GetDiskFreeSpaceEx) then
  710. begin
  711. if GetDiskFreeSpaceEx(@disk[1],qwcaller,qwtotal,qwfree) then
  712. disksize:=qwtotal
  713. else
  714. disksize:=-1;
  715. end
  716. else
  717. begin
  718. if GetDiskFreeSpace(@disk[1],secs,bytes,free,total) then
  719. disksize:=int64(total)*secs*bytes
  720. else
  721. disksize:=-1;
  722. end;
  723. end;
  724. {****************************************************************************
  725. Time Functions
  726. ****************************************************************************}
  727. Procedure GetLocalTime(var SystemTime: TSystemTime);
  728. begin
  729. windows.Getlocaltime(SystemTime);
  730. end;
  731. function GetUniversalTime(var SystemTime: TSystemTime): Boolean;
  732. begin
  733. windows.GetSystemTime(SystemTime);
  734. Result:=True;
  735. end;
  736. function GetLocalTimeOffset: Integer;
  737. var
  738. TZInfo: TTimeZoneInformation;
  739. begin
  740. case GetTimeZoneInformation(TZInfo) of
  741. TIME_ZONE_ID_UNKNOWN:
  742. Result := TZInfo.Bias;
  743. TIME_ZONE_ID_STANDARD:
  744. Result := TZInfo.Bias + TZInfo.StandardBias;
  745. TIME_ZONE_ID_DAYLIGHT:
  746. Result := TZInfo.Bias + TZInfo.DaylightBias;
  747. else
  748. Result := 0;
  749. end;
  750. end;
  751. function GetLocalTimeOffset(const DateTime: TDateTime; const InputIsUTC: Boolean; out Offset: Integer): Boolean;
  752. var
  753. Year: Integer;
  754. const
  755. DaysPerWeek = 7;
  756. // MonthOf and YearOf are not available in SysUtils
  757. function MonthOf(const AValue: TDateTime): Word;
  758. var
  759. Y,D : Word;
  760. begin
  761. DecodeDate(AValue,Y,Result,D);
  762. end;
  763. function YearOf(const AValue: TDateTime): Word;
  764. var
  765. D,M : Word;
  766. begin
  767. DecodeDate(AValue,Result,D,M);
  768. end;
  769. function RelWeekDayToDateTime(const SysTime: TSystemTime): TDateTime;
  770. var
  771. WeekDay, IncDays: Integer;
  772. begin
  773. // get first day in month
  774. Result := EncodeDate(Year, SysTime.Month, 1);
  775. WeekDay := DayOfWeek(Result)-1;
  776. // get the correct first weekday in month
  777. IncDays := SysTime.wDayOfWeek-WeekDay;
  778. if IncDays<0 then
  779. Inc(IncDays, DaysPerWeek);
  780. // inc weeks
  781. Result := Result+IncDays+DaysPerWeek*(SysTime.Day-1);
  782. // SysTime.DayOfWeek=5 means the last one - check if we are not in the next month
  783. while (MonthOf(Result)>SysTime.Month) do
  784. Result := Result-DaysPerWeek;
  785. Result := Result+EncodeTime(SysTime.Hour, SysTime.Minute, SysTime.Second, SysTime.Millisecond);
  786. end;
  787. var
  788. TZInfo: TTimeZoneInformation;
  789. DSTStart, DSTEnd: TDateTime;
  790. begin
  791. Year := YearOf(DateTime);
  792. TZInfo := Default(TTimeZoneInformation);
  793. // GetTimeZoneInformationForYear is supported only on Vista and newer
  794. if not ((Win32MajorVersion>=6) and GetTimeZoneInformationForYear(Year, nil, TZInfo)) then
  795. Exit(False);
  796. if (TZInfo.StandardDate.Month>0) and (TZInfo.DaylightDate.Month>0) then
  797. begin // there is DST
  798. // DaylightDate and StandardDate are local times
  799. DSTStart := RelWeekDayToDateTime(TZInfo.DaylightDate);
  800. DSTEnd := RelWeekDayToDateTime(TZInfo.StandardDate);
  801. if InputIsUTC then
  802. begin
  803. DSTStart := DSTStart + (TZInfo.Bias+TZInfo.StandardBias)/MinsPerDay;
  804. DSTEnd := DSTEnd + (TZInfo.Bias+TZInfo.DaylightBias)/MinsPerDay;
  805. end;
  806. if (DSTStart<=DateTime) and (DateTime<DSTEnd) then
  807. Offset := TZInfo.Bias+TZInfo.DaylightBias
  808. else
  809. Offset := TZInfo.Bias+TZInfo.StandardBias;
  810. end else // no DST
  811. Offset := TZInfo.Bias;
  812. Result := True;
  813. end;
  814. function GetTickCount: LongWord;
  815. begin
  816. Result := Windows.GetTickCount;
  817. end;
  818. {$IFNDEF WINCE}
  819. type
  820. TGetTickCount64 = function : QWord; stdcall;
  821. var
  822. WinGetTickCount64: TGetTickCount64 = Nil;
  823. {$ENDIF}
  824. function GetTickCount64: QWord;
  825. begin
  826. {$IFNDEF WINCE}
  827. if Assigned(WinGetTickCount64) then
  828. Exit(WinGetTickCount64());
  829. { on Vista and newer there is a GetTickCount64 implementation }
  830. if Win32MajorVersion >= 6 then begin
  831. WinGetTickCount64 := TGetTickCount64(GetProcAddress(GetModuleHandle('kernel32.dll'), 'GetTickCount64'));
  832. Result := WinGetTickCount64();
  833. end else
  834. {$ENDIF}
  835. Result := Windows.GetTickCount;
  836. end;
  837. {****************************************************************************
  838. Misc Functions
  839. ****************************************************************************}
  840. procedure sysbeep;
  841. begin
  842. MessageBeep(0);
  843. end;
  844. {****************************************************************************
  845. Locale Functions
  846. ****************************************************************************}
  847. function GetLocaleStr(LID, LT: Longint; const Def: string): ShortString;
  848. var
  849. L: Integer;
  850. Buf: array[0..255] of Char;
  851. begin
  852. L := GetLocaleInfoA(LID, LT, Buf, SizeOf(Buf));
  853. if L > 0 then
  854. SetString(Result, @Buf[0], L - 1)
  855. else
  856. Result := Def;
  857. end;
  858. function GetLocaleChar(LID, LT: Longint; Def: Char): Char;
  859. var
  860. Buf: array[0..3] of Char; // sdate allows 4 chars.
  861. begin
  862. if GetLocaleInfoA(LID, LT, Buf, sizeof(buf)) > 0 then
  863. Result := Buf[0]
  864. else
  865. Result := Def;
  866. end;
  867. function ConvertEraString(Count ,Year,Month,Day : integer) : string;
  868. var
  869. ASystemTime: TSystemTime;
  870. wbuf: array[0..100] of WideChar;
  871. ALCID : LCID;
  872. begin
  873. Result := ''; if (Count<=0) then exit;
  874. DateTimeToSystemTime(EncodeDate(Year,Month,Day),ASystemTime);
  875. ALCID := GetThreadLocale;
  876. // ALCID := SysLocale.DefaultLCID;
  877. if GetDateFormatW(ALCID , DATE_USE_ALT_CALENDAR
  878. , @ASystemTime, PWChar('gg')
  879. , @wbuf, SizeOf(wbuf)) > 0 then
  880. begin
  881. if Count = 1 then
  882. wbuf[1] := #0;
  883. Result := string(WideString(wbuf));
  884. end;
  885. end;
  886. function ConvertEraYearString(Count ,Year,Month,Day : integer) : string;
  887. var
  888. ALCID : LCID;
  889. ASystemTime : TSystemTime;
  890. AFormatText : string;
  891. buf : array[0..100] of Char;
  892. begin
  893. Result := '';
  894. DateTimeToSystemTime(EncodeDate(Year,Month,Day),ASystemTime);
  895. if Count <= 2 then
  896. AFormatText := 'yy'
  897. else
  898. AFormatText := 'yyyy';
  899. ALCID := GetThreadLocale;
  900. // ALCID := SysLocale.DefaultLCID;
  901. if GetDateFormatA(ALCID, DATE_USE_ALT_CALENDAR
  902. , @ASystemTime, PChar(AFormatText)
  903. , @buf, SizeOf(buf)) > 0 then
  904. begin
  905. Result := buf;
  906. if (Count = 1) and (Result[1] = '0') then
  907. Result := Copy(Result, 2, Length(Result)-1);
  908. end;
  909. end;
  910. Function GetLocaleInt(LID,TP,Def: LongInt): LongInt;
  911. Var
  912. S: String;
  913. C: Integer;
  914. Begin
  915. S:=GetLocaleStr(LID,TP,'0');
  916. Val(S,Result,C);
  917. If C<>0 Then
  918. Result:=Def;
  919. End;
  920. function EnumEraNames(Names: PChar): WINBOOL; stdcall;
  921. var
  922. i : integer;
  923. begin
  924. Result := False;
  925. for i := Low(EraNames) to High(EraNames) do
  926. if (EraNames[i] = '') then
  927. begin
  928. EraNames[i] := Names;
  929. Result := True;
  930. break;
  931. end;
  932. end;
  933. function EnumEraYearOffsets(YearOffsets: PChar): WINBOOL; stdcall;
  934. var
  935. i : integer;
  936. begin
  937. Result := False;
  938. for i := Low(EraYearOffsets) to High(EraYearOffsets) do
  939. if (EraYearOffsets[i] = -1) then
  940. begin
  941. EraYearOffsets[i] := StrToIntDef(YearOffsets, 0);
  942. Result := True;
  943. break;
  944. end;
  945. end;
  946. procedure GetEraNamesAndYearOffsets;
  947. var
  948. ACALID : CALID;
  949. ALCID : LCID;
  950. buf : array[0..10] of char;
  951. i : integer;
  952. begin
  953. for i:= 1 to MaxEraCount do
  954. begin
  955. EraNames[i] := ''; EraYearOffsets[i] := -1;
  956. end;
  957. ALCID := GetThreadLocale;
  958. if GetLocaleInfoA(ALCID , LOCALE_IOPTIONALCALENDAR, buf, sizeof(buf)) <= 0 then exit;
  959. ACALID := StrToIntDef(buf,1);
  960. if ACALID in [3..5] then
  961. begin
  962. EnumCalendarInfoA(@EnumEraNames, ALCID, ACALID , CAL_SERASTRING);
  963. EnumCalendarInfoA(@EnumEraYearOffsets, ALCID, ACALID, CAL_IYEAROFFSETRANGE);
  964. end;
  965. (*
  966. 1 CAL_GREGORIAN Gregorian (localized)
  967. 2 CAL_GREGORIAN_US Gregorian (English strings always)
  968. 3 CAL_JAPAN Japanese Emperor Era
  969. 4 CAL_TAIWAN Taiwan Calendar
  970. 5 CAL_KOREA Korean Tangun Era
  971. 6 CAL_HIJRI Hijri (Arabic Lunar)
  972. 7 CAL_THAI Thai
  973. 8 CAL_HEBREW Hebrew (Lunar)
  974. 9 CAL_GREGORIAN_ME_FRENCH Gregorian Middle East French
  975. 10 CAL_GREGORIAN_ARABIC Gregorian Arabic
  976. 11 CAL_GREGORIAN_XLIT_ENGLISH Gregorian transliterated English
  977. 12 CAL_GREGORIAN_XLIT_FRENCH Gregorian transliterated French
  978. 23 CAL_UMALQURA Windows Vista or later: Um Al Qura (Arabic lunar) calendar
  979. *)
  980. end;
  981. procedure GetLocaleFormatSettings(LCID: Integer; var FormatSettings: TFormatSettings);
  982. var
  983. HF : Shortstring;
  984. LID : Windows.LCID;
  985. I,Day : longint;
  986. begin
  987. LID := LCID;
  988. with FormatSettings do
  989. begin
  990. { Date stuff }
  991. for I := 1 to 12 do
  992. begin
  993. ShortMonthNames[I]:=GetLocaleStr(LID,LOCALE_SABBREVMONTHNAME1+I-1,ShortMonthNames[i]);
  994. LongMonthNames[I]:=GetLocaleStr(LID,LOCALE_SMONTHNAME1+I-1,LongMonthNames[i]);
  995. end;
  996. for I := 1 to 7 do
  997. begin
  998. Day := (I + 5) mod 7;
  999. ShortDayNames[I]:=GetLocaleStr(LID,LOCALE_SABBREVDAYNAME1+Day,ShortDayNames[i]);
  1000. LongDayNames[I]:=GetLocaleStr(LID,LOCALE_SDAYNAME1+Day,LongDayNames[i]);
  1001. end;
  1002. DateSeparator := GetLocaleChar(LID, LOCALE_SDATE, '/');
  1003. ShortDateFormat := GetLocaleStr(LID, LOCALE_SSHORTDATE, 'm/d/yy');
  1004. LongDateFormat := GetLocaleStr(LID, LOCALE_SLONGDATE, 'mmmm d, yyyy');
  1005. { Time stuff }
  1006. TimeSeparator := GetLocaleChar(LID, LOCALE_STIME, ':');
  1007. TimeAMString := GetLocaleStr(LID, LOCALE_S1159, 'AM');
  1008. TimePMString := GetLocaleStr(LID, LOCALE_S2359, 'PM');
  1009. if StrToIntDef(GetLocaleStr(LID, LOCALE_ITLZERO, '0'), 0) = 0 then
  1010. HF:='h'
  1011. else
  1012. HF:='hh';
  1013. // No support for 12 hour stuff at the moment...
  1014. ShortTimeFormat := HF+':nn';
  1015. LongTimeFormat := HF + ':nn:ss';
  1016. { Currency stuff }
  1017. CurrencyString:=GetLocaleStr(LID, LOCALE_SCURRENCY, '');
  1018. CurrencyFormat:=StrToIntDef(GetLocaleStr(LID, LOCALE_ICURRENCY, '0'), 0);
  1019. NegCurrFormat:=StrToIntDef(GetLocaleStr(LID, LOCALE_INEGCURR, '0'), 0);
  1020. { Number stuff }
  1021. ThousandSeparator:=GetLocaleChar(LID, LOCALE_STHOUSAND, ',');
  1022. DecimalSeparator:=GetLocaleChar(LID, LOCALE_SDECIMAL, '.');
  1023. CurrencyDecimals:=StrToIntDef(GetLocaleStr(LID, LOCALE_ICURRDIGITS, '0'), 0);
  1024. ListSeparator := GetLocaleChar(LID, LOCALE_SLIST, ',');
  1025. end;
  1026. end;
  1027. procedure GetFormatSettings;
  1028. begin
  1029. GetlocaleFormatSettings(GetThreadLocale, DefaultFormatSettings);
  1030. end;
  1031. Procedure InitLeadBytes;
  1032. var
  1033. I,B,C,E: Byte;
  1034. Info: TCPInfo;
  1035. begin
  1036. GetCPInfo(CP_ACP,Info);
  1037. I:=0;
  1038. With Info do
  1039. begin
  1040. B:=LeadByte[i];
  1041. E:=LeadByte[i+1];
  1042. while (I<MAX_LEADBYTES) and (B<>0) and (E<>0) do
  1043. begin
  1044. for C:=B to E do
  1045. Include(LeadBytes,AnsiChar(C));
  1046. Inc(I,2);
  1047. if (I<MAX_LEADBYTES) then
  1048. begin
  1049. B:=LeadByte[i];
  1050. E:=LeadByte[i+1];
  1051. end;
  1052. end;
  1053. end;
  1054. end;
  1055. Procedure InitInternational;
  1056. var
  1057. {$if defined(CPU386) or defined(CPUX86_64)}
  1058. { A call to GetSystemMetrics changes the value of the 8087 Control Word on
  1059. Pentium4 with WinXP SP2 }
  1060. old8087CW: word;
  1061. {$endif}
  1062. DefaultCustomLocaleID : LCID; // typedef DWORD LCID;
  1063. DefaultCustomLanguageID : Word; // typedef WORD LANGID;
  1064. begin
  1065. /// workaround for Windows 7 bug, see bug report #18574
  1066. SetThreadLocale(GetUserDefaultLCID);
  1067. InitInternationalGeneric;
  1068. {$if defined(CPU386) or defined(CPUX86_64)}
  1069. old8087CW:=Get8087CW;
  1070. {$endif}
  1071. SysLocale.MBCS:=GetSystemMetrics(SM_DBCSENABLED)<>0;
  1072. SysLocale.RightToLeft:=GetSystemMetrics(SM_MIDEASTENABLED)<>0;
  1073. SysLocale.DefaultLCID := $0409;
  1074. SysLocale.PriLangID := LANG_ENGLISH;
  1075. SysLocale.SubLangID := SUBLANG_ENGLISH_US;
  1076. // probably needs update with getthreadlocale. post 2.0.2
  1077. DefaultCustomLocaleID := GetThreadLocale;
  1078. if DefaultCustomLocaleID <> 0 then
  1079. begin
  1080. { Locale Identifiers
  1081. +-------------+---------+-------------------------+
  1082. | Reserved | Sort ID | Language ID |
  1083. +-------------+---------+-------------------------+
  1084. 31 20 19 16 15 0 bit }
  1085. DefaultCustomLanguageID := DefaultCustomLocaleID and $FFFF; // 2^16
  1086. if DefaultCustomLanguageID <> 0 then
  1087. begin
  1088. SysLocale.DefaultLCID := DefaultCustomLocaleID;
  1089. { Language Identifiers
  1090. +-------------------------+-------------------------+
  1091. | SubLanguage ID | Primary Language ID |
  1092. +-------------------------+-------------------------+
  1093. 15 10 9 0 bit }
  1094. SysLocale.PriLangID := DefaultCustomLanguageID and $3ff; // 2^10
  1095. SysLocale.SubLangID := DefaultCustomLanguageID shr 10;
  1096. end;
  1097. end;
  1098. {$if defined(CPU386) or defined(CPUX86_64)}
  1099. Set8087CW(old8087CW);
  1100. {$endif}
  1101. GetFormatSettings;
  1102. if SysLocale.FarEast then GetEraNamesAndYearOffsets;
  1103. end;
  1104. {****************************************************************************
  1105. Target Dependent
  1106. ****************************************************************************}
  1107. function SysErrorMessage(ErrorCode: Integer): String;
  1108. const
  1109. MaxMsgSize = Format_Message_Max_Width_Mask;
  1110. var
  1111. MsgBuffer: unicodestring;
  1112. len: longint;
  1113. begin
  1114. SetLength(MsgBuffer, MaxMsgSize);
  1115. len := FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM,
  1116. nil,
  1117. ErrorCode,
  1118. MakeLangId(LANG_NEUTRAL, SUBLANG_DEFAULT),
  1119. PUnicodeChar(MsgBuffer),
  1120. MaxMsgSize,
  1121. nil);
  1122. // Remove trailing #13#10
  1123. if (len > 1) and (MsgBuffer[len - 1] = #13) and (MsgBuffer[len] = #10) then
  1124. Dec(len, 2);
  1125. SetLength(MsgBuffer, len);
  1126. Result := MsgBuffer;
  1127. end;
  1128. {****************************************************************************
  1129. Initialization code
  1130. ****************************************************************************}
  1131. {$push}
  1132. { GetEnvironmentStrings cannot be checked by CheckPointer function }
  1133. {$checkpointer off}
  1134. Function GetEnvironmentVariable(Const EnvVar : String) : String;
  1135. var
  1136. oemenvvar, oemstr : RawByteString;
  1137. i, hplen : longint;
  1138. hp,p : pchar;
  1139. begin
  1140. oemenvvar:=uppercase(envvar);
  1141. SetCodePage(oemenvvar,CP_OEMCP);
  1142. Result:='';
  1143. p:=GetEnvironmentStringsA;
  1144. hp:=p;
  1145. while hp^<>#0 do
  1146. begin
  1147. oemstr:=hp;
  1148. { cache length, may change after uppercasing depending on code page }
  1149. hplen:=length(oemstr);
  1150. { all environment variables are encoded in the oem code page }
  1151. SetCodePage(oemstr,CP_OEMCP,false);
  1152. i:=pos('=',oemstr);
  1153. if uppercase(copy(oemstr,1,i-1))=oemenvvar then
  1154. begin
  1155. Result:=copy(oemstr,i+1,length(oemstr)-i);
  1156. break;
  1157. end;
  1158. { next string entry}
  1159. hp:=hp+hplen+1;
  1160. end;
  1161. FreeEnvironmentStringsA(p);
  1162. end;
  1163. Function GetEnvironmentVariable(Const EnvVar : UnicodeString) : UnicodeString;
  1164. var
  1165. s, upperenv : Unicodestring;
  1166. i : longint;
  1167. hp,p : pwidechar;
  1168. begin
  1169. Result:='';
  1170. p:=GetEnvironmentStringsW;
  1171. hp:=p;
  1172. upperenv:=uppercase(envvar);
  1173. while hp^<>#0 do
  1174. begin
  1175. s:=hp;
  1176. i:=pos('=',s);
  1177. if uppercase(copy(s,1,i-1))=upperenv then
  1178. begin
  1179. Result:=copy(s,i+1,length(s)-i);
  1180. break;
  1181. end;
  1182. { next string entry}
  1183. hp:=hp+strlen(hp)+1;
  1184. end;
  1185. FreeEnvironmentStringsW(p);
  1186. end;
  1187. Function GetEnvironmentVariableCount : Integer;
  1188. var
  1189. hp,p : pchar;
  1190. begin
  1191. Result:=0;
  1192. p:=GetEnvironmentStringsA;
  1193. hp:=p;
  1194. If (Hp<>Nil) then
  1195. while hp^<>#0 do
  1196. begin
  1197. Inc(Result);
  1198. hp:=hp+strlen(hp)+1;
  1199. end;
  1200. FreeEnvironmentStringsA(p);
  1201. end;
  1202. Function GetEnvironmentString(Index : Integer) : {$ifdef FPC_RTL_UNICODE}UnicodeString{$else}AnsiString{$endif};
  1203. var
  1204. hp,p : pchar;
  1205. {$ifdef FPC_RTL_UNICODE}
  1206. tmpstr : RawByteString;
  1207. {$endif}
  1208. begin
  1209. Result:='';
  1210. p:=GetEnvironmentStringsA;
  1211. hp:=p;
  1212. If (Hp<>Nil) then
  1213. begin
  1214. while (hp^<>#0) and (Index>1) do
  1215. begin
  1216. Dec(Index);
  1217. hp:=hp+strlen(hp)+1;
  1218. end;
  1219. If (hp^<>#0) then
  1220. begin
  1221. {$ifdef FPC_RTL_UNICODE}
  1222. tmpstr:=hp;
  1223. SetCodePage(tmpstr,CP_OEMCP,false);
  1224. Result:=tmpstr;
  1225. {$else}
  1226. Result:=hp;
  1227. SetCodePage(RawByteString(Result),CP_OEMCP,false);
  1228. {$endif}
  1229. end;
  1230. end;
  1231. FreeEnvironmentStringsA(p);
  1232. end;
  1233. {$pop}
  1234. function ExecuteProcess(Const Path: RawByteString; Const ComLine: RawByteString;Flags:TExecuteFlags=[]):integer;
  1235. begin
  1236. result:=ExecuteProcess(Unicodestring(Path),UnicodeString(ComLine),Flags);
  1237. end;
  1238. function ExecuteProcess(Const Path: UnicodeString; Const ComLine: UnicodeString;Flags:TExecuteFlags=[]):integer;
  1239. // win specific function
  1240. var
  1241. SI: TStartupInfoW;
  1242. PI: TProcessInformation;
  1243. Proc : THandle;
  1244. l : DWord;
  1245. CommandLine : unicodestring;
  1246. e : EOSError;
  1247. ExecInherits : longbool;
  1248. begin
  1249. FillChar(SI, SizeOf(SI), 0);
  1250. SI.cb:=SizeOf(SI);
  1251. SI.wShowWindow:=1;
  1252. { always surround the name of the application by quotes
  1253. so that long filenames will always be accepted. But don't
  1254. do it if there are already double quotes, since Win32 does not
  1255. like double quotes which are duplicated!
  1256. }
  1257. if pos('"',path)=0 then
  1258. CommandLine:='"'+path+'"'
  1259. else
  1260. CommandLine:=path;
  1261. if ComLine <> '' then
  1262. CommandLine:=Commandline+' '+ComLine+#0
  1263. else
  1264. CommandLine := CommandLine + #0;
  1265. ExecInherits:=ExecInheritsHandles in Flags;
  1266. if not CreateProcessW(nil, pwidechar(CommandLine),
  1267. Nil, Nil, ExecInherits,$20, Nil, Nil, SI, PI) then
  1268. begin
  1269. e:=EOSError.CreateFmt(SExecuteProcessFailed,[CommandLine,GetLastError]);
  1270. e.ErrorCode:=GetLastError;
  1271. raise e;
  1272. end;
  1273. Proc:=PI.hProcess;
  1274. if WaitForSingleObject(Proc, dword($ffffffff)) <> $ffffffff then
  1275. begin
  1276. GetExitCodeProcess(Proc,l);
  1277. CloseHandle(Proc);
  1278. CloseHandle(PI.hThread);
  1279. result:=l;
  1280. end
  1281. else
  1282. begin
  1283. e:=EOSError.CreateFmt(SExecuteProcessFailed,[CommandLine,GetLastError]);
  1284. e.ErrorCode:=GetLastError;
  1285. CloseHandle(Proc);
  1286. CloseHandle(PI.hThread);
  1287. raise e;
  1288. end;
  1289. end;
  1290. function ExecuteProcess(Const Path: RawByteString; Const ComLine: Array of RawByteString;Flags:TExecuteFlags=[]):integer;
  1291. var
  1292. CommandLine: UnicodeString;
  1293. I: integer;
  1294. begin
  1295. Commandline := '';
  1296. for I := 0 to High (ComLine) do
  1297. if Pos (' ', ComLine [I]) <> 0 then
  1298. CommandLine := CommandLine + ' ' + '"' + ComLine [I] + '"'
  1299. else
  1300. CommandLine := CommandLine + ' ' + Comline [I];
  1301. ExecuteProcess := ExecuteProcess (UnicodeString(Path), CommandLine,Flags);
  1302. end;
  1303. function ExecuteProcess(Const Path: UnicodeString; Const ComLine: Array of UnicodeString;Flags:TExecuteFlags=[]):integer;
  1304. var
  1305. CommandLine: UnicodeString;
  1306. I: integer;
  1307. begin
  1308. Commandline := '';
  1309. for I := 0 to High (ComLine) do
  1310. if Pos (' ', ComLine [I]) <> 0 then
  1311. CommandLine := CommandLine + ' ' + '"' + ComLine [I] + '"'
  1312. else
  1313. CommandLine := CommandLine + ' ' + Comline [I];
  1314. ExecuteProcess := ExecuteProcess (Path,CommandLine,Flags);
  1315. end;
  1316. Procedure Sleep(Milliseconds : Cardinal);
  1317. begin
  1318. Windows.Sleep(MilliSeconds)
  1319. end;
  1320. Function GetLastOSError : Integer;
  1321. begin
  1322. Result:=GetLastError;
  1323. end;
  1324. {****************************************************************************
  1325. Initialization code
  1326. ****************************************************************************}
  1327. var
  1328. kernel32dll : THandle;
  1329. Procedure LoadVersionInfo;
  1330. // and getfreespaceex
  1331. Var
  1332. versioninfo : TOSVERSIONINFO;
  1333. begin
  1334. GetDiskFreeSpaceEx:=nil;
  1335. versioninfo.dwOSVersionInfoSize:=sizeof(versioninfo);
  1336. GetVersionEx(versioninfo);
  1337. Win32Platform:=versionInfo.dwPlatformId;
  1338. Win32MajorVersion:=versionInfo.dwMajorVersion;
  1339. Win32MinorVersion:=versionInfo.dwMinorVersion;
  1340. Win32BuildNumber:=versionInfo.dwBuildNumber;
  1341. Move (versioninfo.szCSDVersion ,Win32CSDVersion[1],128);
  1342. win32CSDVersion[0]:=chr(strlen(pchar(@versioninfo.szCSDVersion)));
  1343. kernel32dll:=GetModuleHandle('kernel32');
  1344. if kernel32dll<>0 then
  1345. GetDiskFreeSpaceEx:=TGetDiskFreeSpaceEx(GetProcAddress(kernel32dll,'GetDiskFreeSpaceExA'));
  1346. if Win32MajorVersion<6 then
  1347. FindExInfoDefaults := FindExInfoStandard; // also searches SFNs. XP only.
  1348. if (Win32MajorVersion>=6) and (Win32MinorVersion>=1) then
  1349. FindFirstAdditionalFlags := FIND_FIRST_EX_LARGE_FETCH; // win7 and 2008R2+
  1350. end;
  1351. Function GetAppConfigDir(Global : Boolean) : String;
  1352. begin
  1353. If Global then
  1354. Result:=GetWindowsSpecialDir(CSIDL_COMMON_APPDATA)
  1355. else
  1356. Result:=GetWindowsSpecialDir(CSIDL_LOCAL_APPDATA);
  1357. If (Result<>'') then
  1358. begin
  1359. if VendorName<>'' then
  1360. Result:=IncludeTrailingPathDelimiter(Result+VendorName);
  1361. Result:=IncludeTrailingPathDelimiter(Result+ApplicationName);
  1362. end
  1363. else
  1364. Result:=IncludeTrailingPathDelimiter(DGetAppConfigDir(Global));
  1365. end;
  1366. Function GetAppConfigFile(Global : Boolean; SubDir : Boolean) : String;
  1367. begin
  1368. result:=DGetAppConfigFile(Global,SubDir);
  1369. end;
  1370. Function GetUserDir : String;
  1371. begin
  1372. Result:=GetWindowsSpecialDir(CSIDL_PROFILE);
  1373. end;
  1374. Procedure InitSysConfigDir;
  1375. begin
  1376. SetLength(SysConfigDir, MAX_PATH);
  1377. SetLength(SysConfigDir, GetWindowsDirectoryA(PChar(SysConfigDir), MAX_PATH));
  1378. end;
  1379. {****************************************************************************
  1380. Target Dependent WideString stuff
  1381. ****************************************************************************}
  1382. { This is the case of Win9x. Limited to current locale of course, but it's better
  1383. than not working at all. }
  1384. function DoCompareStringA(P1, P2: PWideChar; L1, L2: PtrUInt; Flags: DWORD): PtrInt;
  1385. var
  1386. a1, a2: AnsiString;
  1387. begin
  1388. if L1>0 then
  1389. widestringmanager.Wide2AnsiMoveProc(P1,a1,DefaultSystemCodePage,L1);
  1390. if L2>0 then
  1391. widestringmanager.Wide2AnsiMoveProc(P2,a2,DefaultSystemCodePage,L2);
  1392. SetLastError(0);
  1393. Result:=CompareStringA(LOCALE_USER_DEFAULT,Flags,pchar(a1),
  1394. length(a1),pchar(a2),length(a2))-2;
  1395. end;
  1396. function DoCompareStringW(P1, P2: PWideChar; L1, L2: PtrUInt; Flags: DWORD): PtrInt;
  1397. begin
  1398. SetLastError(0);
  1399. Result:=CompareStringW(LOCALE_USER_DEFAULT,Flags,P1,L1,P2,L2)-2;
  1400. if GetLastError=0 then
  1401. Exit;
  1402. if GetLastError=ERROR_CALL_NOT_IMPLEMENTED then // Win9x case
  1403. Result:=DoCompareStringA(P1, P2, L1, L2, Flags);
  1404. if GetLastError<>0 then
  1405. RaiseLastOSError;
  1406. end;
  1407. const
  1408. WinAPICompareFlags : array [TCompareOption] of LongWord
  1409. = ({LINGUISTIC_IGNORECASE, LINGUISTIC_IGNOREDIACRITIC, }NORM_IGNORECASE{,
  1410. NORM_IGNOREKANATYPE, NORM_IGNORENONSPACE, NORM_IGNORESYMBOLS, NORM_IGNOREWIDTH,
  1411. NORM_LINGUISTIC_CASING, SORT_DIGITSASNUMBERS, SORT_STRINGSORT});
  1412. function Win32CompareWideString(const s1, s2 : WideString; Options : TCompareOptions) : PtrInt;
  1413. Var
  1414. O : LongWord;
  1415. CO : TCompareOption;
  1416. begin
  1417. O:=0;
  1418. for CO in TCompareOption do
  1419. if CO in Options then
  1420. O:=O or WinAPICompareFlags[CO];
  1421. Result:=DoCompareStringW(PWideChar(s1), PWideChar(s2), Length(s1), Length(s2), O);
  1422. end;
  1423. function Win32CompareTextWideString(const s1, s2 : WideString) : PtrInt;
  1424. begin
  1425. Result:=DoCompareStringW(PWideChar(s1), PWideChar(s2), Length(s1), Length(s2), NORM_IGNORECASE);
  1426. end;
  1427. function Win32AnsiUpperCase(const s: string): string;
  1428. begin
  1429. if length(s)>0 then
  1430. begin
  1431. result:=s;
  1432. UniqueString(result);
  1433. CharUpperBuffA(pchar(result),length(result));
  1434. end
  1435. else
  1436. result:='';
  1437. end;
  1438. function Win32AnsiLowerCase(const s: string): string;
  1439. begin
  1440. if length(s)>0 then
  1441. begin
  1442. result:=s;
  1443. UniqueString(result);
  1444. CharLowerBuffA(pchar(result),length(result));
  1445. end
  1446. else
  1447. result:='';
  1448. end;
  1449. function Win32AnsiCompareStr(const S1, S2: string): PtrInt;
  1450. begin
  1451. result:=CompareStringA(LOCALE_USER_DEFAULT,0,pchar(s1),length(s1),
  1452. pchar(s2),length(s2))-2;
  1453. end;
  1454. function Win32AnsiCompareText(const S1, S2: string): PtrInt;
  1455. begin
  1456. result:=CompareStringA(LOCALE_USER_DEFAULT,NORM_IGNORECASE,pchar(s1),length(s1),
  1457. pchar(s2),length(s2))-2;
  1458. end;
  1459. function Win32AnsiStrComp(S1, S2: PChar): PtrInt;
  1460. begin
  1461. result:=CompareStringA(LOCALE_USER_DEFAULT,0,s1,-1,s2,-1)-2;
  1462. end;
  1463. function Win32AnsiStrIComp(S1, S2: PChar): PtrInt;
  1464. begin
  1465. result:=CompareStringA(LOCALE_USER_DEFAULT,NORM_IGNORECASE,s1,-1,s2,-1)-2;
  1466. end;
  1467. function Win32AnsiStrLComp(S1, S2: PChar; MaxLen: PtrUInt): PtrInt;
  1468. begin
  1469. result:=CompareStringA(LOCALE_USER_DEFAULT,0,s1,maxlen,s2,maxlen)-2;
  1470. end;
  1471. function Win32AnsiStrLIComp(S1, S2: PChar; MaxLen: PtrUInt): PtrInt;
  1472. begin
  1473. result:=CompareStringA(LOCALE_USER_DEFAULT,NORM_IGNORECASE,s1,maxlen,s2,maxlen)-2;
  1474. end;
  1475. function Win32AnsiStrLower(Str: PChar): PChar;
  1476. begin
  1477. CharLowerA(str);
  1478. result:=str;
  1479. end;
  1480. function Win32AnsiStrUpper(Str: PChar): PChar;
  1481. begin
  1482. CharUpperA(str);
  1483. result:=str;
  1484. end;
  1485. function Win32CompareUnicodeString(const s1, s2 : UnicodeString; Options : TCompareOptions) : PtrInt;
  1486. Var
  1487. O : LongWord;
  1488. CO : TCompareOption;
  1489. begin
  1490. O:=0;
  1491. for CO in TCompareOption do
  1492. if CO in Options then
  1493. O:=O or WinAPICompareFlags[CO];
  1494. Result:=DoCompareStringW(PWideChar(s1), PWideChar(s2), Length(s1), Length(s2), O);
  1495. end;
  1496. function Win32CompareTextUnicodeString(const s1, s2 : UnicodeString) : PtrInt;
  1497. begin
  1498. Result:=DoCompareStringW(PWideChar(s1), PWideChar(s2), Length(s1), Length(s2), NORM_IGNORECASE);
  1499. end;
  1500. { there is a similiar procedure in the system unit which inits the fields which
  1501. are relevant already for the system unit }
  1502. procedure InitWin32Widestrings;
  1503. begin
  1504. { return value: number of code points in the string. Whenever an invalid
  1505. code point is encountered, all characters part of this invalid code point
  1506. are considered to form one "character" and the next character is
  1507. considered to be the start of a new (possibly also invalid) code point }
  1508. //!!! CharLengthPCharProc : function(const Str: PChar): PtrInt;
  1509. { return value:
  1510. -1 if incomplete or invalid code point
  1511. 0 if NULL character,
  1512. > 0 if that's the length in bytes of the code point }
  1513. //!!!! CodePointLengthProc : function(const Str: PChar; MaxLookAead: PtrInt): Ptrint;
  1514. widestringmanager.CompareWideStringProc:=@Win32CompareWideString;
  1515. widestringmanager.UpperAnsiStringProc:=@Win32AnsiUpperCase;
  1516. widestringmanager.LowerAnsiStringProc:=@Win32AnsiLowerCase;
  1517. widestringmanager.CompareStrAnsiStringProc:=@Win32AnsiCompareStr;
  1518. widestringmanager.CompareTextAnsiStringProc:=@Win32AnsiCompareText;
  1519. widestringmanager.StrCompAnsiStringProc:=@Win32AnsiStrComp;
  1520. widestringmanager.StrICompAnsiStringProc:=@Win32AnsiStrIComp;
  1521. widestringmanager.StrLCompAnsiStringProc:=@Win32AnsiStrLComp;
  1522. widestringmanager.StrLICompAnsiStringProc:=@Win32AnsiStrLIComp;
  1523. widestringmanager.StrLowerAnsiStringProc:=@Win32AnsiStrLower;
  1524. widestringmanager.StrUpperAnsiStringProc:=@Win32AnsiStrUpper;
  1525. widestringmanager.CompareUnicodeStringProc:=@Win32CompareUnicodeString;
  1526. end;
  1527. { Platform-specific exception support }
  1528. function WinExceptionObject(code: Longint; const rec: TExceptionRecord): Exception;
  1529. var
  1530. entry: PExceptMapEntry;
  1531. begin
  1532. entry := FindExceptMapEntry(code);
  1533. if assigned(entry) then
  1534. result:=entry^.cls.CreateRes(entry^.msg)
  1535. else
  1536. result:=EExternalException.CreateResFmt(@SExternalException,[rec.ExceptionCode]);
  1537. if result is EExternal then
  1538. EExternal(result).FExceptionRecord:=rec;
  1539. end;
  1540. function WinExceptionClass(code: longint): ExceptClass;
  1541. var
  1542. entry: PExceptMapEntry;
  1543. begin
  1544. entry := FindExceptMapEntry(code);
  1545. if assigned(entry) then
  1546. result:=entry^.cls
  1547. else
  1548. result:=EExternalException;
  1549. end;
  1550. Initialization
  1551. InitWin32Widestrings;
  1552. InitExceptions; { Initialize exceptions. OS independent }
  1553. {$ifdef mswindows} { Keeps exe size down for systems that do not use SEH }
  1554. ExceptObjProc:=@WinExceptionObject;
  1555. ExceptClsProc:=@WinExceptionClass;
  1556. {$endif mswindows}
  1557. InitLeadBytes;
  1558. InitInternational; { Initialize internationalization settings }
  1559. LoadVersionInfo;
  1560. InitSysConfigDir;
  1561. OnBeep:=@SysBeep;
  1562. Finalization
  1563. FreeTerminateProcs;
  1564. DoneExceptions;
  1565. end.