sysutils.pp 52 KB

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