sysutils.pp 48 KB

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