sysutils.pp 55 KB

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