sysutils.pp 51 KB

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