sysutils.pp 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892
  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. CVolumePrefix = 'Volume';
  376. CGlobalPrefix = '\\?\';
  377. var
  378. HFile, Handle: THandle;
  379. PBuffer: ^TReparseDataBuffer;
  380. BytesReturned: DWORD;
  381. guid: TGUID;
  382. begin
  383. Result := slrError;
  384. SymLinkRec := Default(TUnicodeSymLinkRec);
  385. HFile := CreateFileW(PUnicodeChar(FileName), FILE_READ_EA, CShareAny, Nil, OPEN_EXISTING, COpenReparse, 0);
  386. if HFile <> INVALID_HANDLE_VALUE then
  387. try
  388. GetMem(PBuffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
  389. try
  390. if DeviceIoControl(HFile, FSCTL_GET_REPARSE_POINT, Nil, 0,
  391. PBuffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE, @BytesReturned, Nil) then begin
  392. case PBuffer^.ReparseTag of
  393. IO_REPARSE_TAG_MOUNT_POINT: begin
  394. SymLinkRec.TargetName := WideCharLenToString(
  395. @PBuffer^.PathBufferMount[4 { skip start '\??\' } +
  396. PBuffer^.SubstituteNameOffset div SizeOf(WCHAR)],
  397. PBuffer^.SubstituteNameLength div SizeOf(WCHAR) - 4);
  398. if (Length(SymLinkRec.TargetName) = Length(CVolumePrefix) + 2 { brackets } + 32 { guid } + 4 { - } + 1 { \ }) and
  399. (Copy(SymLinkRec.TargetName, 1, Length(CVolumePrefix)) = CVolumePrefix) and
  400. TryStringToGUID(String(Copy(SymLinkRec.TargetName, Length(CVolumePrefix) + 1, Length(SymLinkRec.TargetName) - Length(CVolumePrefix) - 1)), guid) then
  401. SymLinkRec.TargetName := CGlobalPrefix + SymLinkRec.TargetName;
  402. end;
  403. IO_REPARSE_TAG_SYMLINK: begin
  404. SymLinkRec.TargetName := WideCharLenToString(
  405. @PBuffer^.PathBufferSym[PBuffer^.PrintNameOffset div SizeOf(WCHAR)],
  406. PBuffer^.PrintNameLength div SizeOf(WCHAR));
  407. if (PBuffer^.Flags and SYMLINK_FLAG_RELATIVE) <> 0 then
  408. SymLinkRec.TargetName := ExpandFileName(ExtractFilePath(FileName) + SymLinkRec.TargetName);
  409. end;
  410. end;
  411. if SymLinkRec.TargetName <> '' then begin
  412. { the fields of WIN32_FILE_ATTRIBUTE_DATA match with the first fields of WIN32_FIND_DATA }
  413. if GetFileAttributesExW(PUnicodeChar(SymLinkRec.TargetName), GetFileExInfoStandard, @SymLinkRec.FindData) then begin
  414. SymLinkRec.Attr := SymLinkRec.FindData.dwFileAttributes;
  415. SymLinkRec.Size := QWord(SymLinkRec.FindData.nFileSizeHigh) shl 32 + QWord(SymLinkRec.FindData.nFileSizeLow);
  416. end else if RaiseErrorOnMissing then
  417. raise EDirectoryNotFoundException.Create(SysErrorMessage(GetLastOSError))
  418. else
  419. SymLinkRec.TargetName := '';
  420. end else begin
  421. SetLastError(ERROR_REPARSE_TAG_INVALID);
  422. Result := slrNoSymLink;
  423. end;
  424. end else
  425. SetLastError(ERROR_REPARSE_TAG_INVALID);
  426. finally
  427. FreeMem(PBuffer);
  428. end;
  429. finally
  430. CloseHandle(HFile);
  431. end;
  432. if SymLinkRec.TargetName <> '' then
  433. Result := slrOk
  434. end;
  435. function FileGetSymLinkTarget(const FileName: UnicodeString; out SymLinkRec: TUnicodeSymLinkRec): Boolean;
  436. begin
  437. Result := FileGetSymLinkTargetInt(FileName, SymLinkRec, True) = slrOk;
  438. end;
  439. function FileOrDirExists(const FileOrDirName: UnicodeString; CheckDir: Boolean; FollowLink: Boolean): Boolean;
  440. const
  441. CDirAttributes: array[Boolean] of DWORD = (0, FILE_ATTRIBUTE_DIRECTORY);
  442. function FoundByEnum: Boolean;
  443. var
  444. FindData: TWin32FindDataW;
  445. Handle: THandle;
  446. begin
  447. { FindFirstFileEx is faster than FindFirstFile }
  448. Handle := FindFirstFileExW(PUnicodeChar(FileOrDirName), FindExInfoDefaults , @FindData,
  449. FindExSearchNameMatch, Nil, 0);
  450. Result := Handle <> INVALID_HANDLE_VALUE;
  451. if Result then begin
  452. Windows.FindClose(Handle);
  453. Result := (FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) = CDirAttributes[CheckDir];
  454. end;
  455. end;
  456. const
  457. CNotExistsErrors = [
  458. ERROR_FILE_NOT_FOUND,
  459. ERROR_PATH_NOT_FOUND,
  460. ERROR_INVALID_NAME, // protects from names in the form of masks like '*'
  461. ERROR_INVALID_DRIVE,
  462. ERROR_NOT_READY,
  463. ERROR_INVALID_PARAMETER,
  464. ERROR_BAD_PATHNAME,
  465. ERROR_BAD_NETPATH,
  466. ERROR_BAD_NET_NAME
  467. ];
  468. var
  469. Attr : DWord;
  470. slr : TUnicodeSymLinkRec;
  471. res : TSymLinkResult;
  472. begin
  473. Attr := GetFileAttributesW(PUnicodeChar(FileOrDirName));
  474. if Attr = INVALID_FILE_ATTRIBUTES then
  475. Result := not (GetLastError in CNotExistsErrors) and FoundByEnum
  476. else begin
  477. Result := (Attr and FILE_ATTRIBUTE_DIRECTORY) = CDirAttributes[CheckDir];
  478. if Result and FollowLink and ((Attr and FILE_ATTRIBUTE_REPARSE_POINT) <> 0) then begin
  479. res := FileGetSymLinkTargetInt(FileOrDirName, slr, False);
  480. case res of
  481. slrOk:
  482. Result := FileOrDirExists(slr.TargetName, CheckDir, False);
  483. slrNoSymLink:
  484. Result := True;
  485. else
  486. Result := False;
  487. end;
  488. end;
  489. end;
  490. end;
  491. Function FileExists (Const FileName : UnicodeString; FollowLink : Boolean) : Boolean;
  492. begin
  493. Result := FileOrDirExists(FileName, False, FollowLink);
  494. end;
  495. Function DirectoryExists (Const Directory : UnicodeString; FollowLink : Boolean) : Boolean;
  496. begin
  497. Result := FileOrDirExists(Directory, True, FollowLink);
  498. end;
  499. Function FindMatch(var f: TAbstractSearchRec; var Name: UnicodeString) : Longint;
  500. var
  501. tmpdtime : longint;
  502. begin
  503. { Find file with correct attribute }
  504. While (F.FindData.dwFileAttributes and cardinal(F.ExcludeAttr))<>0 do
  505. begin
  506. if not FindNextFileW (F.FindHandle,F.FindData) then
  507. begin
  508. Result:=GetLastError;
  509. exit;
  510. end;
  511. end;
  512. { Convert some attributes back }
  513. WinToDosTime(F.FindData.ftLastWriteTime,tmpdtime);
  514. F.Time:=tmpdtime;
  515. f.size:=F.FindData.NFileSizeLow+(qword(maxdword)+1)*F.FindData.NFileSizeHigh;
  516. f.attr:=F.FindData.dwFileAttributes;
  517. Name:=F.FindData.cFileName;
  518. Result:=0;
  519. end;
  520. Procedure InternalFindClose (var Handle: THandle; var FindData: TFindData);
  521. begin
  522. if Handle <> INVALID_HANDLE_VALUE then
  523. begin
  524. Windows.FindClose(Handle);
  525. Handle:=INVALID_HANDLE_VALUE;
  526. end;
  527. end;
  528. Function InternalFindFirst (Const Path : UnicodeString; Attr : Longint; out Rslt : TAbstractSearchRec; var Name : UnicodeString) : Longint;
  529. begin
  530. Name:=Path;
  531. Rslt.Attr:=attr;
  532. Rslt.ExcludeAttr:=(not Attr) and ($1e);
  533. { $1e = faHidden or faSysFile or faVolumeID or faDirectory }
  534. { FindFirstFile is a Win32 Call }
  535. Rslt.FindHandle:=FindFirstFileExW(PUnicodeChar(Path), FindExInfoDefaults , @Rslt.FindData,
  536. FindExSearchNameMatch, Nil, FindFirstAdditionalFlags);
  537. If Rslt.FindHandle=Invalid_Handle_value then
  538. begin
  539. Result:=GetLastError;
  540. exit;
  541. end;
  542. { Find file with correct attribute }
  543. Result:=FindMatch(Rslt,Name);
  544. if (Result<>0) then
  545. InternalFindClose(Rslt.FindHandle,Rslt.FindData);
  546. end;
  547. Function InternalFindNext (Var Rslt : TAbstractSearchRec; var Name: UnicodeString) : Longint;
  548. begin
  549. if FindNextFileW(Rslt.FindHandle, Rslt.FindData) then
  550. Result := FindMatch(Rslt, Name)
  551. else
  552. Result := GetLastError;
  553. end;
  554. Function FileGetDate (Handle : THandle) : Int64;
  555. Var
  556. FT : TFileTime;
  557. tmpdtime : longint;
  558. begin
  559. If GetFileTime(Handle,nil,nil,@ft) and
  560. WinToDosTime(FT,tmpdtime) then
  561. begin
  562. result:=tmpdtime;
  563. exit;
  564. end;
  565. Result:=-1;
  566. end;
  567. Function FileGetDate (Handle : THandle; out FileDateTime: TDateTime) : Boolean;
  568. Var
  569. FT : TFileTime;
  570. begin
  571. Result :=
  572. GetFileTime(Handle,nil,nil,@ft) and
  573. FindDataTimeToDateTime(FT, FileDateTime);
  574. end;
  575. Function FileGetDateUTC (Handle : THandle; out FileDateTimeUTC: TDateTime) : Boolean;
  576. Var
  577. FT : TFileTime;
  578. begin
  579. Result :=
  580. GetFileTime(Handle,nil,nil,@ft) and
  581. FindDataTimeToUTC(FT, FileDateTimeUTC);
  582. end;
  583. Function FileSetDate (Handle : THandle;Age : Int64) : Longint;
  584. Var
  585. FT: TFileTime;
  586. begin
  587. Result := 0;
  588. if DosToWinTime(Age,FT) and
  589. SetFileTime(Handle, nil, nil, @FT) then
  590. Exit;
  591. Result := GetLastError;
  592. end;
  593. Function FileSetDate (Handle : THandle; const FileDateTime: TDateTime) : Longint;
  594. var
  595. FT: TFiletime;
  596. LT: TFiletime;
  597. ST: TSystemTime;
  598. begin
  599. DateTimeToSystemTime(FileDateTime,ST);
  600. if SystemTimeToFileTime(ST,LT) and LocalFileTimeToFileTime(LT,FT)
  601. and SetFileTime(Handle,nil,nil,@FT) then
  602. Result:=0
  603. else
  604. Result:=GetLastError;
  605. end;
  606. Function FileSetDateUTC (Handle : THandle; const FileDateTimeUTC: TDateTime) : Longint;
  607. var
  608. FT: TFiletime;
  609. ST: TSystemTime;
  610. begin
  611. DateTimeToSystemTime(FileDateTimeUTC,ST);
  612. if SystemTimeToFileTime(ST,FT) and SetFileTime(Handle,nil,nil,@FT) then
  613. Result:=0
  614. else
  615. Result:=GetLastError;
  616. end;
  617. {$IFDEF OS_FILESETDATEBYNAME}
  618. Function FileSetDate (Const FileName : UnicodeString;Age : Int64) : Longint;
  619. Var
  620. fd : THandle;
  621. begin
  622. FD := CreateFileW (PWideChar (FileName), GENERIC_READ or GENERIC_WRITE,
  623. FILE_SHARE_WRITE, nil, OPEN_EXISTING,
  624. FILE_FLAG_BACKUP_SEMANTICS, 0);
  625. If (Fd<>feInvalidHandle) then
  626. try
  627. Result:=FileSetDate(fd,Age);
  628. finally
  629. FileClose(fd);
  630. end
  631. else
  632. Result:=GetLastOSError;
  633. end;
  634. Function FileSetDate (Const FileName : UnicodeString;const FileDateTime : TDateTime) : Longint;
  635. Var
  636. fd : THandle;
  637. begin
  638. FD := CreateFileW (PWideChar (FileName), GENERIC_READ or GENERIC_WRITE,
  639. FILE_SHARE_WRITE, nil, OPEN_EXISTING,
  640. FILE_FLAG_BACKUP_SEMANTICS, 0);
  641. If (Fd<>feInvalidHandle) then
  642. try
  643. Result:=FileSetDate(fd,FileDateTime);
  644. finally
  645. FileClose(fd);
  646. end
  647. else
  648. Result:=GetLastOSError;
  649. end;
  650. Function FileSetDateUTC (Const FileName : UnicodeString;const FileDateTimeUTC : TDateTime) : Longint;
  651. Var
  652. fd : THandle;
  653. begin
  654. FD := CreateFileW (PWideChar (FileName), GENERIC_READ or GENERIC_WRITE,
  655. FILE_SHARE_WRITE, nil, OPEN_EXISTING,
  656. FILE_FLAG_BACKUP_SEMANTICS, 0);
  657. If (Fd<>feInvalidHandle) then
  658. try
  659. Result:=FileSetDateUTC(fd,FileDateTimeUTC);
  660. finally
  661. FileClose(fd);
  662. end
  663. else
  664. Result:=GetLastOSError;
  665. end;
  666. {$ENDIF}
  667. Function FileGetAttr (Const FileName : UnicodeString) : Longint;
  668. begin
  669. Result:=Longint(GetFileAttributesW(PWideChar(FileName)));
  670. end;
  671. Function FileSetAttr (Const Filename : UnicodeString; Attr: longint) : Longint;
  672. begin
  673. if SetFileAttributesW(PWideChar(FileName), Attr) then
  674. Result:=0
  675. else
  676. Result := GetLastError;
  677. end;
  678. Function DeleteFile (Const FileName : UnicodeString) : Boolean;
  679. begin
  680. Result:=Windows.DeleteFileW(PWidechar(FileName));
  681. end;
  682. Function RenameFile (Const OldName, NewName : UnicodeString) : Boolean;
  683. begin
  684. Result := MoveFileW(PWideChar(OldName), PWideChar(NewName));
  685. end;
  686. {****************************************************************************
  687. Disk Functions
  688. ****************************************************************************}
  689. type
  690. TGetDiskFreeSpaceEx = function(drive:pchar;var availableforcaller,total,free):longbool;stdcall;
  691. var
  692. GetDiskFreeSpaceEx : TGetDiskFreeSpaceEx;
  693. function diskfree(drive : byte) : int64;
  694. var
  695. disk : array[1..4] of char;
  696. secs,bytes,
  697. free,total : dword;
  698. qwtotal,qwfree,qwcaller : int64;
  699. begin
  700. if drive=0 then
  701. begin
  702. disk[1]:='\';
  703. disk[2]:=#0;
  704. end
  705. else
  706. begin
  707. disk[1]:=chr(drive+64);
  708. disk[2]:=':';
  709. disk[3]:='\';
  710. disk[4]:=#0;
  711. end;
  712. if assigned(GetDiskFreeSpaceEx) then
  713. begin
  714. if GetDiskFreeSpaceEx(@disk[1],qwcaller,qwtotal,qwfree) then
  715. diskfree:=qwfree
  716. else
  717. diskfree:=-1;
  718. end
  719. else
  720. begin
  721. if GetDiskFreeSpace(@disk[1],secs,bytes,free,total) then
  722. diskfree:=int64(free)*secs*bytes
  723. else
  724. diskfree:=-1;
  725. end;
  726. end;
  727. function disksize(drive : byte) : int64;
  728. var
  729. disk : array[1..4] of char;
  730. secs,bytes,
  731. free,total : dword;
  732. qwtotal,qwfree,qwcaller : int64;
  733. begin
  734. if drive=0 then
  735. begin
  736. disk[1]:='\';
  737. disk[2]:=#0;
  738. end
  739. else
  740. begin
  741. disk[1]:=chr(drive+64);
  742. disk[2]:=':';
  743. disk[3]:='\';
  744. disk[4]:=#0;
  745. end;
  746. if assigned(GetDiskFreeSpaceEx) then
  747. begin
  748. if GetDiskFreeSpaceEx(@disk[1],qwcaller,qwtotal,qwfree) then
  749. disksize:=qwtotal
  750. else
  751. disksize:=-1;
  752. end
  753. else
  754. begin
  755. if GetDiskFreeSpace(@disk[1],secs,bytes,free,total) then
  756. disksize:=int64(total)*secs*bytes
  757. else
  758. disksize:=-1;
  759. end;
  760. end;
  761. {****************************************************************************
  762. Time Functions
  763. ****************************************************************************}
  764. Procedure GetLocalTime(var SystemTime: TSystemTime);
  765. begin
  766. windows.Getlocaltime(SystemTime);
  767. end;
  768. function GetUniversalTime(var SystemTime: TSystemTime): Boolean;
  769. begin
  770. windows.GetSystemTime(SystemTime);
  771. Result:=True;
  772. end;
  773. function GetLocalTimeOffset: Integer;
  774. var
  775. TZInfo: TTimeZoneInformation;
  776. begin
  777. case GetTimeZoneInformation(TZInfo) of
  778. TIME_ZONE_ID_UNKNOWN:
  779. Result := TZInfo.Bias;
  780. TIME_ZONE_ID_STANDARD:
  781. Result := TZInfo.Bias + TZInfo.StandardBias;
  782. TIME_ZONE_ID_DAYLIGHT:
  783. Result := TZInfo.Bias + TZInfo.DaylightBias;
  784. else
  785. Result := 0;
  786. end;
  787. end;
  788. type
  789. TGetTimeZoneInformationForYear = function(wYear: USHORT; lpDynamicTimeZoneInformation: PDynamicTimeZoneInformation;
  790. var lpTimeZoneInformation: TTimeZoneInformation): BOOL;stdcall;
  791. var
  792. GetTimeZoneInformationForYear:TGetTimeZoneInformationForYear=nil;
  793. function GetLocalTimeOffset(const DateTime: TDateTime; const InputIsUTC: Boolean; out Offset: Integer): Boolean;
  794. var
  795. Year: Integer;
  796. const
  797. DaysPerWeek = 7;
  798. // MonthOf and YearOf are not available in SysUtils
  799. function MonthOf(const AValue: TDateTime): Word;
  800. var
  801. Y,D : Word;
  802. begin
  803. DecodeDate(AValue,Y,Result,D);
  804. end;
  805. function YearOf(const AValue: TDateTime): Word;
  806. var
  807. D,M : Word;
  808. begin
  809. DecodeDate(AValue,Result,D,M);
  810. end;
  811. function RelWeekDayToDateTime(const SysTime: TSystemTime): TDateTime;
  812. var
  813. WeekDay, IncDays: Integer;
  814. begin
  815. // get first day in month
  816. Result := EncodeDate(Year, SysTime.Month, 1);
  817. WeekDay := DayOfWeek(Result)-1;
  818. // get the correct first weekday in month
  819. IncDays := SysTime.wDayOfWeek-WeekDay;
  820. if IncDays<0 then
  821. Inc(IncDays, DaysPerWeek);
  822. // inc weeks
  823. Result := Result+IncDays+DaysPerWeek*(SysTime.Day-1);
  824. // SysTime.DayOfWeek=5 means the last one - check if we are not in the next month
  825. while (MonthOf(Result)>SysTime.Month) do
  826. Result := Result-DaysPerWeek;
  827. Result := Result+EncodeTime(SysTime.Hour, SysTime.Minute, SysTime.Second, SysTime.Millisecond);
  828. end;
  829. var
  830. TZInfo: TTimeZoneInformation;
  831. DSTStart, DSTEnd: TDateTime;
  832. begin
  833. if not Assigned(GetTimeZoneInformationForYear) then
  834. Exit(False);
  835. Year := YearOf(DateTime);
  836. TZInfo := Default(TTimeZoneInformation);
  837. if not GetTimeZoneInformationForYear(Year, nil, TZInfo) then
  838. Exit(False);
  839. if (TZInfo.StandardDate.Month>0) and (TZInfo.DaylightDate.Month>0) then
  840. begin // there is DST
  841. // DaylightDate and StandardDate are local times
  842. DSTStart := RelWeekDayToDateTime(TZInfo.DaylightDate);
  843. DSTEnd := RelWeekDayToDateTime(TZInfo.StandardDate);
  844. if InputIsUTC then
  845. begin
  846. DSTStart := DSTStart + (TZInfo.Bias+TZInfo.StandardBias)/MinsPerDay;
  847. DSTEnd := DSTEnd + (TZInfo.Bias+TZInfo.DaylightBias)/MinsPerDay;
  848. end;
  849. if (DSTStart<=DateTime) and (DateTime<DSTEnd) then
  850. Offset := TZInfo.Bias+TZInfo.DaylightBias
  851. else
  852. Offset := TZInfo.Bias+TZInfo.StandardBias;
  853. end else // no DST
  854. Offset := TZInfo.Bias;
  855. Result := True;
  856. end;
  857. function GetTickCount: LongWord;
  858. begin
  859. Result := Windows.GetTickCount;
  860. end;
  861. {$IFNDEF WINCE}
  862. type
  863. TGetTickCount64 = function : QWord; stdcall;
  864. var
  865. WinGetTickCount64: TGetTickCount64 = Nil;
  866. {$ENDIF}
  867. function GetTickCount64: QWord;
  868. begin
  869. {$IFNDEF WINCE}
  870. if Assigned(WinGetTickCount64) then
  871. Exit(WinGetTickCount64());
  872. { on Vista and newer there is a GetTickCount64 implementation }
  873. if Win32MajorVersion >= 6 then begin
  874. WinGetTickCount64 := TGetTickCount64(GetProcAddress(GetModuleHandle('kernel32.dll'), 'GetTickCount64'));
  875. Result := WinGetTickCount64();
  876. end else
  877. {$ENDIF}
  878. Result := Windows.GetTickCount;
  879. end;
  880. {****************************************************************************
  881. Misc Functions
  882. ****************************************************************************}
  883. procedure sysbeep;
  884. begin
  885. MessageBeep(0);
  886. end;
  887. {****************************************************************************
  888. Locale Functions
  889. ****************************************************************************}
  890. function GetLocaleStr(LID, LT: Longint; const Def: string): AnsiString;
  891. var
  892. L: Integer;
  893. Buf: unicodestring;
  894. begin
  895. L := GetLocaleInfoW(LID, LT, nil, 0);
  896. if L > 0 then
  897. begin
  898. SetLength(Buf,L-1); // L includes terminating NULL
  899. if l>1 Then
  900. L := GetLocaleInfoW(LID, LT, @Buf[1], L);
  901. result:=buf;
  902. end
  903. else
  904. Result := Def;
  905. end;
  906. function GetLocaleChar(LID, LT: Longint; Def: Char): Char;
  907. var
  908. Buf: array[0..3] of Char; // sdate allows 4 chars.
  909. begin
  910. if GetLocaleInfoA(LID, LT, Buf, sizeof(buf)) > 0 then
  911. Result := Buf[0]
  912. else
  913. Result := Def;
  914. end;
  915. function ConvertEraString(Count ,Year,Month,Day : integer) : string;
  916. var
  917. ASystemTime: TSystemTime;
  918. wbuf: array[0..100] of WideChar;
  919. ALCID : LCID;
  920. begin
  921. Result := ''; if (Count<=0) then exit;
  922. DateTimeToSystemTime(EncodeDate(Year,Month,Day),ASystemTime);
  923. ALCID := GetThreadLocale;
  924. // ALCID := SysLocale.DefaultLCID;
  925. if GetDateFormatW(ALCID , DATE_USE_ALT_CALENDAR
  926. , @ASystemTime, PWChar('gg')
  927. , @wbuf, SizeOf(wbuf)) > 0 then
  928. begin
  929. if Count = 1 then
  930. wbuf[1] := #0;
  931. Result := string(WideString(wbuf));
  932. end;
  933. end;
  934. function ConvertEraYearString(Count ,Year,Month,Day : integer) : string;
  935. var
  936. ALCID : LCID;
  937. ASystemTime : TSystemTime;
  938. AFormatText : string;
  939. buf : array[0..100] of Char;
  940. begin
  941. Result := '';
  942. DateTimeToSystemTime(EncodeDate(Year,Month,Day),ASystemTime);
  943. if Count <= 2 then
  944. AFormatText := 'yy'
  945. else
  946. AFormatText := 'yyyy';
  947. ALCID := GetThreadLocale;
  948. // ALCID := SysLocale.DefaultLCID;
  949. if GetDateFormatA(ALCID, DATE_USE_ALT_CALENDAR
  950. , @ASystemTime, PChar(AFormatText)
  951. , @buf, SizeOf(buf)) > 0 then
  952. begin
  953. Result := buf;
  954. if (Count = 1) and (Result[1] = '0') then
  955. Result := Copy(Result, 2, Length(Result)-1);
  956. end;
  957. end;
  958. Function GetLocaleInt(LID,TP,Def: LongInt): LongInt;
  959. Var
  960. S: String;
  961. C: Integer;
  962. Begin
  963. S:=GetLocaleStr(LID,TP,'0');
  964. Val(S,Result,C);
  965. If C<>0 Then
  966. Result:=Def;
  967. End;
  968. function EnumEraNames(Names: PChar): WINBOOL; stdcall;
  969. var
  970. i : integer;
  971. begin
  972. Result := False;
  973. for i := Low(EraNames) to High(EraNames) do
  974. if (EraNames[i] = '') then
  975. begin
  976. EraNames[i] := Names;
  977. Result := True;
  978. break;
  979. end;
  980. end;
  981. function EnumEraYearOffsets(YearOffsets: PChar): WINBOOL; stdcall;
  982. var
  983. i : integer;
  984. begin
  985. Result := False;
  986. for i := Low(EraYearOffsets) to High(EraYearOffsets) do
  987. if (EraYearOffsets[i] = -1) then
  988. begin
  989. EraYearOffsets[i] := StrToIntDef(YearOffsets, 0);
  990. Result := True;
  991. break;
  992. end;
  993. end;
  994. procedure GetEraNamesAndYearOffsets;
  995. var
  996. ACALID : CALID;
  997. ALCID : LCID;
  998. buf : array[0..10] of char;
  999. i : integer;
  1000. begin
  1001. for i:= 1 to MaxEraCount do
  1002. begin
  1003. EraNames[i] := ''; EraYearOffsets[i] := -1;
  1004. end;
  1005. ALCID := GetThreadLocale;
  1006. if GetLocaleInfoA(ALCID , LOCALE_IOPTIONALCALENDAR, buf, sizeof(buf)) <= 0 then exit;
  1007. ACALID := StrToIntDef(buf,1);
  1008. if ACALID in [3..5] then
  1009. begin
  1010. EnumCalendarInfoA(@EnumEraNames, ALCID, ACALID , CAL_SERASTRING);
  1011. EnumCalendarInfoA(@EnumEraYearOffsets, ALCID, ACALID, CAL_IYEAROFFSETRANGE);
  1012. end;
  1013. (*
  1014. 1 CAL_GREGORIAN Gregorian (localized)
  1015. 2 CAL_GREGORIAN_US Gregorian (English strings always)
  1016. 3 CAL_JAPAN Japanese Emperor Era
  1017. 4 CAL_TAIWAN Taiwan Calendar
  1018. 5 CAL_KOREA Korean Tangun Era
  1019. 6 CAL_HIJRI Hijri (Arabic Lunar)
  1020. 7 CAL_THAI Thai
  1021. 8 CAL_HEBREW Hebrew (Lunar)
  1022. 9 CAL_GREGORIAN_ME_FRENCH Gregorian Middle East French
  1023. 10 CAL_GREGORIAN_ARABIC Gregorian Arabic
  1024. 11 CAL_GREGORIAN_XLIT_ENGLISH Gregorian transliterated English
  1025. 12 CAL_GREGORIAN_XLIT_FRENCH Gregorian transliterated French
  1026. 23 CAL_UMALQURA Windows Vista or later: Um Al Qura (Arabic lunar) calendar
  1027. *)
  1028. end;
  1029. procedure GetLocaleFormatSettings(LCID: Integer; var FormatSettings: TFormatSettings);
  1030. function FixSeparator(const Format: string; const FromSeparator, ToSeparator: Char): string;
  1031. var
  1032. R: PChar;
  1033. begin
  1034. if (Format='') or (FromSeparator=ToSeparator) then
  1035. Exit(Format);
  1036. Result := Copy(Format, 1);
  1037. R := PChar(Result);
  1038. while R^<>#0 do
  1039. begin
  1040. if R^=FromSeparator then
  1041. R^:=ToSeparator;
  1042. Inc(R);
  1043. end;
  1044. end;
  1045. var
  1046. HF : Shortstring;
  1047. LID : Windows.LCID;
  1048. I,Day : longint;
  1049. begin
  1050. LID := LCID;
  1051. with FormatSettings do
  1052. begin
  1053. { Date stuff }
  1054. for I := 1 to 12 do
  1055. begin
  1056. ShortMonthNames[I]:=GetLocaleStr(LID,LOCALE_SABBREVMONTHNAME1+I-1,ShortMonthNames[i]);
  1057. LongMonthNames[I]:=GetLocaleStr(LID,LOCALE_SMONTHNAME1+I-1,LongMonthNames[i]);
  1058. end;
  1059. for I := 1 to 7 do
  1060. begin
  1061. Day := (I + 5) mod 7;
  1062. ShortDayNames[I]:=GetLocaleStr(LID,LOCALE_SABBREVDAYNAME1+Day,ShortDayNames[i]);
  1063. LongDayNames[I]:=GetLocaleStr(LID,LOCALE_SDAYNAME1+Day,LongDayNames[i]);
  1064. end;
  1065. DateSeparator := GetLocaleChar(LID, LOCALE_SDATE, '/');
  1066. ShortDateFormat := FixSeparator(GetLocaleStr(LID, LOCALE_SSHORTDATE, 'm/d/yy'), DateSeparator, '/');
  1067. LongDateFormat := FixSeparator(GetLocaleStr(LID, LOCALE_SLONGDATE, 'mmmm d, yyyy'), DateSeparator, '/');
  1068. { Time stuff }
  1069. TimeSeparator := GetLocaleChar(LID, LOCALE_STIME, ':');
  1070. TimeAMString := GetLocaleStr(LID, LOCALE_S1159, 'AM');
  1071. TimePMString := GetLocaleStr(LID, LOCALE_S2359, 'PM');
  1072. if StrToIntDef(GetLocaleStr(LID, LOCALE_ITLZERO, '0'), 0) = 0 then
  1073. HF:='h'
  1074. else
  1075. HF:='hh';
  1076. // No support for 12 hour stuff at the moment...
  1077. ShortTimeFormat := HF+':nn';
  1078. LongTimeFormat := HF + ':nn:ss';
  1079. { Currency stuff }
  1080. CurrencyString:=GetLocaleStr(LID, LOCALE_SCURRENCY, '');
  1081. CurrencyFormat:=StrToIntDef(GetLocaleStr(LID, LOCALE_ICURRENCY, '0'), 0);
  1082. NegCurrFormat:=StrToIntDef(GetLocaleStr(LID, LOCALE_INEGCURR, '0'), 0);
  1083. { Number stuff }
  1084. ThousandSeparator:=GetLocaleChar(LID, LOCALE_STHOUSAND, ',');
  1085. DecimalSeparator:=GetLocaleChar(LID, LOCALE_SDECIMAL, '.');
  1086. CurrencyDecimals:=StrToIntDef(GetLocaleStr(LID, LOCALE_ICURRDIGITS, '0'), 0);
  1087. ListSeparator := GetLocaleChar(LID, LOCALE_SLIST, ',');
  1088. end;
  1089. end;
  1090. procedure GetFormatSettings;
  1091. begin
  1092. GetlocaleFormatSettings(GetThreadLocale, DefaultFormatSettings);
  1093. end;
  1094. Procedure InitLeadBytes;
  1095. var
  1096. I,B,C,E: Byte;
  1097. Info: TCPInfo;
  1098. begin
  1099. GetCPInfo(CP_ACP,Info);
  1100. I:=0;
  1101. With Info do
  1102. begin
  1103. B:=LeadByte[i];
  1104. E:=LeadByte[i+1];
  1105. while (I<MAX_LEADBYTES) and (B<>0) and (E<>0) do
  1106. begin
  1107. for C:=B to E do
  1108. Include(LeadBytes,AnsiChar(C));
  1109. Inc(I,2);
  1110. if (I<MAX_LEADBYTES) then
  1111. begin
  1112. B:=LeadByte[i];
  1113. E:=LeadByte[i+1];
  1114. end;
  1115. end;
  1116. end;
  1117. end;
  1118. Procedure InitInternational;
  1119. var
  1120. {$if defined(CPU386) or defined(CPUX86_64)}
  1121. { A call to GetSystemMetrics changes the value of the 8087 Control Word on
  1122. Pentium4 with WinXP SP2 }
  1123. old8087CW: word;
  1124. {$endif}
  1125. DefaultCustomLocaleID : LCID; // typedef DWORD LCID;
  1126. DefaultCustomLanguageID : Word; // typedef WORD LANGID;
  1127. begin
  1128. /// workaround for Windows 7 bug, see bug report #18574
  1129. SetThreadLocale(GetUserDefaultLCID);
  1130. InitInternationalGeneric;
  1131. {$if defined(CPU386) or defined(CPUX86_64)}
  1132. old8087CW:=Get8087CW;
  1133. {$endif}
  1134. SysLocale.MBCS:=GetSystemMetrics(SM_DBCSENABLED)<>0;
  1135. SysLocale.RightToLeft:=GetSystemMetrics(SM_MIDEASTENABLED)<>0;
  1136. SysLocale.DefaultLCID := $0409;
  1137. SysLocale.PriLangID := LANG_ENGLISH;
  1138. SysLocale.SubLangID := SUBLANG_ENGLISH_US;
  1139. // probably needs update with getthreadlocale. post 2.0.2
  1140. DefaultCustomLocaleID := GetThreadLocale;
  1141. if DefaultCustomLocaleID <> 0 then
  1142. begin
  1143. { Locale Identifiers
  1144. +-------------+---------+-------------------------+
  1145. | Reserved | Sort ID | Language ID |
  1146. +-------------+---------+-------------------------+
  1147. 31 20 19 16 15 0 bit }
  1148. DefaultCustomLanguageID := DefaultCustomLocaleID and $FFFF; // 2^16
  1149. if DefaultCustomLanguageID <> 0 then
  1150. begin
  1151. SysLocale.DefaultLCID := DefaultCustomLocaleID;
  1152. { Language Identifiers
  1153. +-------------------------+-------------------------+
  1154. | SubLanguage ID | Primary Language ID |
  1155. +-------------------------+-------------------------+
  1156. 15 10 9 0 bit }
  1157. SysLocale.PriLangID := DefaultCustomLanguageID and $3ff; // 2^10
  1158. SysLocale.SubLangID := DefaultCustomLanguageID shr 10;
  1159. end;
  1160. end;
  1161. {$if defined(CPU386) or defined(CPUX86_64)}
  1162. Set8087CW(old8087CW);
  1163. {$endif}
  1164. GetFormatSettings;
  1165. if SysLocale.FarEast then GetEraNamesAndYearOffsets;
  1166. end;
  1167. {****************************************************************************
  1168. Target Dependent
  1169. ****************************************************************************}
  1170. function SysErrorMessage(ErrorCode: Integer): String;
  1171. var
  1172. MsgBuffer: PWideChar;
  1173. Msg: UnicodeString;
  1174. len: longint;
  1175. begin
  1176. len := FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM or
  1177. FORMAT_MESSAGE_IGNORE_INSERTS or
  1178. FORMAT_MESSAGE_ALLOCATE_BUFFER,
  1179. nil,
  1180. ErrorCode,
  1181. MakeLangId(LANG_NEUTRAL, SUBLANG_DEFAULT),
  1182. PWideChar(@MsgBuffer),
  1183. 0,
  1184. nil);
  1185. // Remove trailing #13#10
  1186. if (len > 1) and (MsgBuffer[len - 2] = #13) and (MsgBuffer[len - 1] = #10) then
  1187. Dec(len, 2);
  1188. SetString(Msg, PUnicodeChar(MsgBuffer), len);
  1189. LocalFree(HLOCAL(MsgBuffer));
  1190. Result := Msg;
  1191. end;
  1192. {****************************************************************************
  1193. Initialization code
  1194. ****************************************************************************}
  1195. {$push}
  1196. { GetEnvironmentStrings cannot be checked by CheckPointer function }
  1197. {$checkpointer off}
  1198. Function GetEnvironmentVariable(Const EnvVar : String) : String;
  1199. var
  1200. oemenvvar, oemstr : RawByteString;
  1201. i, hplen : longint;
  1202. hp,p : pchar;
  1203. begin
  1204. oemenvvar:=uppercase(envvar);
  1205. SetCodePage(oemenvvar,CP_OEMCP);
  1206. Result:='';
  1207. p:=GetEnvironmentStringsA;
  1208. hp:=p;
  1209. while hp^<>#0 do
  1210. begin
  1211. oemstr:=hp;
  1212. { cache length, may change after uppercasing depending on code page }
  1213. hplen:=length(oemstr);
  1214. { all environment variables are encoded in the oem code page }
  1215. SetCodePage(oemstr,CP_OEMCP,false);
  1216. i:=pos('=',oemstr);
  1217. if uppercase(copy(oemstr,1,i-1))=oemenvvar then
  1218. begin
  1219. Result:=copy(oemstr,i+1,length(oemstr)-i);
  1220. break;
  1221. end;
  1222. { next string entry}
  1223. hp:=hp+hplen+1;
  1224. end;
  1225. FreeEnvironmentStringsA(p);
  1226. end;
  1227. Function GetEnvironmentVariable(Const EnvVar : UnicodeString) : UnicodeString;
  1228. var
  1229. s, upperenv : Unicodestring;
  1230. i : longint;
  1231. hp,p : pwidechar;
  1232. begin
  1233. Result:='';
  1234. p:=GetEnvironmentStringsW;
  1235. hp:=p;
  1236. upperenv:=uppercase(envvar);
  1237. while hp^<>#0 do
  1238. begin
  1239. s:=hp;
  1240. i:=pos('=',s);
  1241. if uppercase(copy(s,1,i-1))=upperenv then
  1242. begin
  1243. Result:=copy(s,i+1,length(s)-i);
  1244. break;
  1245. end;
  1246. { next string entry}
  1247. hp:=hp+strlen(hp)+1;
  1248. end;
  1249. FreeEnvironmentStringsW(p);
  1250. end;
  1251. Function GetEnvironmentVariableCount : Integer;
  1252. var
  1253. hp,p : pchar;
  1254. begin
  1255. Result:=0;
  1256. p:=GetEnvironmentStringsA;
  1257. hp:=p;
  1258. If (Hp<>Nil) then
  1259. while hp^<>#0 do
  1260. begin
  1261. Inc(Result);
  1262. hp:=hp+strlen(hp)+1;
  1263. end;
  1264. FreeEnvironmentStringsA(p);
  1265. end;
  1266. Function GetEnvironmentString(Index : Integer) : {$ifdef FPC_RTL_UNICODE}UnicodeString{$else}AnsiString{$endif};
  1267. var
  1268. hp,p : pchar;
  1269. {$ifdef FPC_RTL_UNICODE}
  1270. tmpstr : RawByteString;
  1271. {$endif}
  1272. begin
  1273. Result:='';
  1274. p:=GetEnvironmentStringsA;
  1275. hp:=p;
  1276. If (Hp<>Nil) then
  1277. begin
  1278. while (hp^<>#0) and (Index>1) do
  1279. begin
  1280. Dec(Index);
  1281. hp:=hp+strlen(hp)+1;
  1282. end;
  1283. If (hp^<>#0) then
  1284. begin
  1285. {$ifdef FPC_RTL_UNICODE}
  1286. tmpstr:=hp;
  1287. SetCodePage(tmpstr,CP_OEMCP,false);
  1288. Result:=tmpstr;
  1289. {$else}
  1290. Result:=hp;
  1291. SetCodePage(RawByteString(Result),CP_OEMCP,false);
  1292. {$endif}
  1293. end;
  1294. end;
  1295. FreeEnvironmentStringsA(p);
  1296. end;
  1297. {$pop}
  1298. function ExecuteProcess(Const Path: RawByteString; Const ComLine: RawByteString;Flags:TExecuteFlags=[]):integer;
  1299. begin
  1300. result:=ExecuteProcess(Unicodestring(Path),UnicodeString(ComLine),Flags);
  1301. end;
  1302. function ExecuteProcess(Const Path: UnicodeString; Const ComLine: UnicodeString;Flags:TExecuteFlags=[]):integer;
  1303. // win specific function
  1304. var
  1305. SI: TStartupInfoW;
  1306. PI: TProcessInformation;
  1307. Proc : THandle;
  1308. l : DWord;
  1309. CommandLine : unicodestring;
  1310. e : EOSError;
  1311. ExecInherits : longbool;
  1312. begin
  1313. FillChar(SI, SizeOf(SI), 0);
  1314. SI.cb:=SizeOf(SI);
  1315. SI.wShowWindow:=1;
  1316. { always surround the name of the application by quotes
  1317. so that long filenames will always be accepted. But don't
  1318. do it if there are already double quotes, since Win32 does not
  1319. like double quotes which are duplicated!
  1320. }
  1321. if pos('"',path)=0 then
  1322. CommandLine:='"'+path+'"'
  1323. else
  1324. CommandLine:=path;
  1325. if ComLine <> '' then
  1326. CommandLine:=Commandline+' '+ComLine+#0
  1327. else
  1328. CommandLine := CommandLine + #0;
  1329. ExecInherits:=ExecInheritsHandles in Flags;
  1330. if not CreateProcessW(nil, pwidechar(CommandLine),
  1331. Nil, Nil, ExecInherits,$20, Nil, Nil, SI, PI) then
  1332. begin
  1333. e:=EOSError.CreateFmt(SExecuteProcessFailed,[CommandLine,GetLastError]);
  1334. e.ErrorCode:=GetLastError;
  1335. raise e;
  1336. end;
  1337. Proc:=PI.hProcess;
  1338. if WaitForSingleObject(Proc, dword($ffffffff)) <> $ffffffff then
  1339. begin
  1340. GetExitCodeProcess(Proc,l);
  1341. CloseHandle(Proc);
  1342. CloseHandle(PI.hThread);
  1343. result:=l;
  1344. end
  1345. else
  1346. begin
  1347. e:=EOSError.CreateFmt(SExecuteProcessFailed,[CommandLine,GetLastError]);
  1348. e.ErrorCode:=GetLastError;
  1349. CloseHandle(Proc);
  1350. CloseHandle(PI.hThread);
  1351. raise e;
  1352. end;
  1353. end;
  1354. function ExecuteProcess(Const Path: RawByteString; Const ComLine: Array of RawByteString;Flags:TExecuteFlags=[]):integer;
  1355. var
  1356. CommandLine: UnicodeString;
  1357. I: integer;
  1358. begin
  1359. Commandline := '';
  1360. for I := 0 to High (ComLine) do
  1361. if Pos (' ', ComLine [I]) <> 0 then
  1362. CommandLine := CommandLine + ' ' + '"' + ComLine [I] + '"'
  1363. else
  1364. CommandLine := CommandLine + ' ' + Comline [I];
  1365. ExecuteProcess := ExecuteProcess (UnicodeString(Path), CommandLine,Flags);
  1366. end;
  1367. function ExecuteProcess(Const Path: UnicodeString; Const ComLine: Array of UnicodeString;Flags:TExecuteFlags=[]):integer;
  1368. var
  1369. CommandLine: UnicodeString;
  1370. I: integer;
  1371. begin
  1372. Commandline := '';
  1373. for I := 0 to High (ComLine) do
  1374. if Pos (' ', ComLine [I]) <> 0 then
  1375. CommandLine := CommandLine + ' ' + '"' + ComLine [I] + '"'
  1376. else
  1377. CommandLine := CommandLine + ' ' + Comline [I];
  1378. ExecuteProcess := ExecuteProcess (Path,CommandLine,Flags);
  1379. end;
  1380. Procedure Sleep(Milliseconds : Cardinal);
  1381. begin
  1382. Windows.Sleep(MilliSeconds)
  1383. end;
  1384. Function GetLastOSError : Integer;
  1385. begin
  1386. Result:=GetLastError;
  1387. end;
  1388. {****************************************************************************
  1389. Initialization code
  1390. ****************************************************************************}
  1391. var
  1392. kernel32dll : THandle;
  1393. Procedure LoadVersionInfo;
  1394. // and getfreespaceex
  1395. Var
  1396. versioninfo : TOSVERSIONINFO;
  1397. begin
  1398. GetDiskFreeSpaceEx:=nil;
  1399. versioninfo.dwOSVersionInfoSize:=sizeof(versioninfo);
  1400. GetVersionEx(versioninfo);
  1401. Win32Platform:=versionInfo.dwPlatformId;
  1402. Win32MajorVersion:=versionInfo.dwMajorVersion;
  1403. Win32MinorVersion:=versionInfo.dwMinorVersion;
  1404. Win32BuildNumber:=versionInfo.dwBuildNumber;
  1405. Move (versioninfo.szCSDVersion ,Win32CSDVersion[1],128);
  1406. win32CSDVersion[0]:=chr(strlen(pchar(@versioninfo.szCSDVersion)));
  1407. kernel32dll:=GetModuleHandle('kernel32');
  1408. if kernel32dll<>0 then
  1409. GetDiskFreeSpaceEx:=TGetDiskFreeSpaceEx(GetProcAddress(kernel32dll,'GetDiskFreeSpaceExA'));
  1410. if Win32MajorVersion<6 then
  1411. FindExInfoDefaults := FindExInfoStandard; // also searches SFNs. XP only.
  1412. if (Win32MajorVersion>=6) and (Win32MinorVersion>=1) then
  1413. FindFirstAdditionalFlags := FIND_FIRST_EX_LARGE_FETCH; // win7 and 2008R2+
  1414. // GetTimeZoneInformationForYear is supported only on Vista and newer
  1415. if (kernel32dll<>0) and (Win32MajorVersion>=6) then
  1416. GetTimeZoneInformationForYear:=TGetTimeZoneInformationForYear(GetProcAddress(kernel32dll,'GetTimeZoneInformationForYear'));
  1417. end;
  1418. Function GetAppConfigDir(Global : Boolean) : String;
  1419. begin
  1420. If Global then
  1421. Result:=GetWindowsSpecialDir(CSIDL_COMMON_APPDATA)
  1422. else
  1423. Result:=GetWindowsSpecialDir(CSIDL_LOCAL_APPDATA);
  1424. If (Result<>'') then
  1425. begin
  1426. if VendorName<>'' then
  1427. Result:=IncludeTrailingPathDelimiter(Result+VendorName);
  1428. Result:=IncludeTrailingPathDelimiter(Result+ApplicationName);
  1429. end
  1430. else
  1431. Result:=IncludeTrailingPathDelimiter(DGetAppConfigDir(Global));
  1432. end;
  1433. Function GetAppConfigFile(Global : Boolean; SubDir : Boolean) : String;
  1434. begin
  1435. result:=DGetAppConfigFile(Global,SubDir);
  1436. end;
  1437. Function GetUserDir : String;
  1438. begin
  1439. Result:=GetWindowsSpecialDir(CSIDL_PROFILE);
  1440. end;
  1441. Procedure InitSysConfigDir;
  1442. begin
  1443. SetLength(SysConfigDir, MAX_PATH);
  1444. SetLength(SysConfigDir, GetWindowsDirectoryA(PChar(SysConfigDir), MAX_PATH));
  1445. end;
  1446. {****************************************************************************
  1447. Target Dependent WideString stuff
  1448. ****************************************************************************}
  1449. { This is the case of Win9x. Limited to current locale of course, but it's better
  1450. than not working at all. }
  1451. function DoCompareStringA(P1, P2: PWideChar; L1, L2: PtrUInt; Flags: DWORD): PtrInt;
  1452. var
  1453. a1, a2: AnsiString;
  1454. begin
  1455. if L1>0 then
  1456. widestringmanager.Wide2AnsiMoveProc(P1,a1,DefaultSystemCodePage,L1);
  1457. if L2>0 then
  1458. widestringmanager.Wide2AnsiMoveProc(P2,a2,DefaultSystemCodePage,L2);
  1459. SetLastError(0);
  1460. Result:=CompareStringA(LOCALE_USER_DEFAULT,Flags,pchar(a1),
  1461. length(a1),pchar(a2),length(a2))-2;
  1462. end;
  1463. function DoCompareStringW(P1, P2: PWideChar; L1, L2: PtrUInt; Flags: DWORD): PtrInt;
  1464. begin
  1465. SetLastError(0);
  1466. Result:=CompareStringW(LOCALE_USER_DEFAULT,Flags,P1,L1,P2,L2)-2;
  1467. if GetLastError=0 then
  1468. Exit;
  1469. if GetLastError=ERROR_CALL_NOT_IMPLEMENTED then // Win9x case
  1470. Result:=DoCompareStringA(P1, P2, L1, L2, Flags);
  1471. if GetLastError<>0 then
  1472. RaiseLastOSError;
  1473. end;
  1474. const
  1475. WinAPICompareFlags : array [TCompareOption] of LongWord
  1476. = ({LINGUISTIC_IGNORECASE, LINGUISTIC_IGNOREDIACRITIC, }NORM_IGNORECASE{,
  1477. NORM_IGNOREKANATYPE, NORM_IGNORENONSPACE, NORM_IGNORESYMBOLS, NORM_IGNOREWIDTH,
  1478. NORM_LINGUISTIC_CASING, SORT_DIGITSASNUMBERS, SORT_STRINGSORT});
  1479. function Win32CompareWideString(const s1, s2 : WideString; Options : TCompareOptions) : PtrInt;
  1480. Var
  1481. O : LongWord;
  1482. CO : TCompareOption;
  1483. begin
  1484. O:=0;
  1485. for CO in TCompareOption do
  1486. if CO in Options then
  1487. O:=O or WinAPICompareFlags[CO];
  1488. Result:=DoCompareStringW(PWideChar(s1), PWideChar(s2), Length(s1), Length(s2), O);
  1489. end;
  1490. function Win32CompareTextWideString(const s1, s2 : WideString) : PtrInt;
  1491. begin
  1492. Result:=DoCompareStringW(PWideChar(s1), PWideChar(s2), Length(s1), Length(s2), NORM_IGNORECASE);
  1493. end;
  1494. function Win32AnsiUpperCase(const s: string): string;
  1495. begin
  1496. if length(s)>0 then
  1497. begin
  1498. result:=s;
  1499. UniqueString(result);
  1500. CharUpperBuffA(pchar(result),length(result));
  1501. end
  1502. else
  1503. result:='';
  1504. end;
  1505. function Win32AnsiLowerCase(const s: string): string;
  1506. begin
  1507. if length(s)>0 then
  1508. begin
  1509. result:=s;
  1510. UniqueString(result);
  1511. CharLowerBuffA(pchar(result),length(result));
  1512. end
  1513. else
  1514. result:='';
  1515. end;
  1516. function Win32AnsiCompareStr(const S1, S2: string): PtrInt;
  1517. begin
  1518. result:=CompareStringA(LOCALE_USER_DEFAULT,0,pchar(s1),length(s1),
  1519. pchar(s2),length(s2))-2;
  1520. end;
  1521. function Win32AnsiCompareText(const S1, S2: string): PtrInt;
  1522. begin
  1523. result:=CompareStringA(LOCALE_USER_DEFAULT,NORM_IGNORECASE,pchar(s1),length(s1),
  1524. pchar(s2),length(s2))-2;
  1525. end;
  1526. function Win32AnsiStrComp(S1, S2: PChar): PtrInt;
  1527. begin
  1528. result:=CompareStringA(LOCALE_USER_DEFAULT,0,s1,-1,s2,-1)-2;
  1529. end;
  1530. function Win32AnsiStrIComp(S1, S2: PChar): PtrInt;
  1531. begin
  1532. result:=CompareStringA(LOCALE_USER_DEFAULT,NORM_IGNORECASE,s1,-1,s2,-1)-2;
  1533. end;
  1534. function Win32AnsiStrLComp(S1, S2: PChar; MaxLen: PtrUInt): PtrInt;
  1535. begin
  1536. result:=CompareStringA(LOCALE_USER_DEFAULT,0,s1,maxlen,s2,maxlen)-2;
  1537. end;
  1538. function Win32AnsiStrLIComp(S1, S2: PChar; MaxLen: PtrUInt): PtrInt;
  1539. begin
  1540. result:=CompareStringA(LOCALE_USER_DEFAULT,NORM_IGNORECASE,s1,maxlen,s2,maxlen)-2;
  1541. end;
  1542. function Win32AnsiStrLower(Str: PChar): PChar;
  1543. begin
  1544. CharLowerA(str);
  1545. result:=str;
  1546. end;
  1547. function Win32AnsiStrUpper(Str: PChar): PChar;
  1548. begin
  1549. CharUpperA(str);
  1550. result:=str;
  1551. end;
  1552. function Win32CompareUnicodeString(const s1, s2 : UnicodeString; Options : TCompareOptions) : PtrInt;
  1553. Var
  1554. O : LongWord;
  1555. CO : TCompareOption;
  1556. begin
  1557. O:=0;
  1558. for CO in TCompareOption do
  1559. if CO in Options then
  1560. O:=O or WinAPICompareFlags[CO];
  1561. Result:=DoCompareStringW(PWideChar(s1), PWideChar(s2), Length(s1), Length(s2), O);
  1562. end;
  1563. function Win32CompareTextUnicodeString(const s1, s2 : UnicodeString) : PtrInt;
  1564. begin
  1565. Result:=DoCompareStringW(PWideChar(s1), PWideChar(s2), Length(s1), Length(s2), NORM_IGNORECASE);
  1566. end;
  1567. { there is a similiar procedure in the system unit which inits the fields which
  1568. are relevant already for the system unit }
  1569. procedure InitWin32Widestrings;
  1570. begin
  1571. { return value: number of code points in the string. Whenever an invalid
  1572. code point is encountered, all characters part of this invalid code point
  1573. are considered to form one "character" and the next character is
  1574. considered to be the start of a new (possibly also invalid) code point }
  1575. //!!! CharLengthPCharProc : function(const Str: PChar): PtrInt;
  1576. { return value:
  1577. -1 if incomplete or invalid code point
  1578. 0 if NULL character,
  1579. > 0 if that's the length in bytes of the code point }
  1580. //!!!! CodePointLengthProc : function(const Str: PChar; MaxLookAead: PtrInt): Ptrint;
  1581. widestringmanager.CompareWideStringProc:=@Win32CompareWideString;
  1582. widestringmanager.UpperAnsiStringProc:=@Win32AnsiUpperCase;
  1583. widestringmanager.LowerAnsiStringProc:=@Win32AnsiLowerCase;
  1584. widestringmanager.CompareStrAnsiStringProc:=@Win32AnsiCompareStr;
  1585. widestringmanager.CompareTextAnsiStringProc:=@Win32AnsiCompareText;
  1586. widestringmanager.StrCompAnsiStringProc:=@Win32AnsiStrComp;
  1587. widestringmanager.StrICompAnsiStringProc:=@Win32AnsiStrIComp;
  1588. widestringmanager.StrLCompAnsiStringProc:=@Win32AnsiStrLComp;
  1589. widestringmanager.StrLICompAnsiStringProc:=@Win32AnsiStrLIComp;
  1590. widestringmanager.StrLowerAnsiStringProc:=@Win32AnsiStrLower;
  1591. widestringmanager.StrUpperAnsiStringProc:=@Win32AnsiStrUpper;
  1592. widestringmanager.CompareUnicodeStringProc:=@Win32CompareUnicodeString;
  1593. end;
  1594. { Platform-specific exception support }
  1595. function WinExceptionObject(code: Longint; const rec: TExceptionRecord): Exception;
  1596. var
  1597. entry: PExceptMapEntry;
  1598. begin
  1599. entry := FindExceptMapEntry(code);
  1600. if assigned(entry) then
  1601. result:=entry^.cls.CreateRes(entry^.msg)
  1602. else
  1603. result:=EExternalException.CreateResFmt(@SExternalException,[rec.ExceptionCode]);
  1604. if result is EExternal then
  1605. EExternal(result).FExceptionRecord:=rec;
  1606. end;
  1607. function WinExceptionClass(code: longint): ExceptClass;
  1608. var
  1609. entry: PExceptMapEntry;
  1610. begin
  1611. entry := FindExceptMapEntry(code);
  1612. if assigned(entry) then
  1613. result:=entry^.cls
  1614. else
  1615. result:=EExternalException;
  1616. end;
  1617. Initialization
  1618. InitWin32Widestrings;
  1619. InitExceptions; { Initialize exceptions. OS independent }
  1620. {$ifdef mswindows} { Keeps exe size down for systems that do not use SEH }
  1621. ExceptObjProc:=@WinExceptionObject;
  1622. ExceptClsProc:=@WinExceptionClass;
  1623. {$endif mswindows}
  1624. InitLeadBytes;
  1625. InitInternational; { Initialize internationalization settings }
  1626. LoadVersionInfo;
  1627. InitSysConfigDir;
  1628. OnBeep:=@SysBeep;
  1629. Finalization
  1630. FreeTerminateProcs;
  1631. DoneExceptions;
  1632. end.