sysutils.pp 54 KB

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