sysutils.pp 51 KB

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