sysutils.pp 51 KB

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