sysutils.pp 54 KB

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