sysutils.pp 38 KB

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