sysutils.pp 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471
  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: RawByteString; Const ComLine: RawByteString;Flags:TExecuteFlags=[]):integer;
  923. begin
  924. result:=ExecuteProcess(Unicodestring(Path),UnicodeString(ComLine),Flags);
  925. end;
  926. function ExecuteProcess(Const Path: UnicodeString; Const ComLine: UnicodeString;Flags:TExecuteFlags=[]):integer;
  927. // win specific function
  928. var
  929. SI: TStartupInfoW;
  930. PI: TProcessInformation;
  931. Proc : THandle;
  932. l : DWord;
  933. CommandLine : unicodestring;
  934. e : EOSError;
  935. ExecInherits : longbool;
  936. begin
  937. FillChar(SI, SizeOf(SI), 0);
  938. SI.cb:=SizeOf(SI);
  939. SI.wShowWindow:=1;
  940. { always surround the name of the application by quotes
  941. so that long filenames will always be accepted. But don't
  942. do it if there are already double quotes, since Win32 does not
  943. like double quotes which are duplicated!
  944. }
  945. if pos('"',path)=0 then
  946. CommandLine:='"'+path+'"'
  947. else
  948. CommandLine:=path;
  949. if ComLine <> '' then
  950. CommandLine:=Commandline+' '+ComLine+#0
  951. else
  952. CommandLine := CommandLine + #0;
  953. ExecInherits:=ExecInheritsHandles in Flags;
  954. if not CreateProcessW(nil, pwidechar(CommandLine),
  955. Nil, Nil, ExecInherits,$20, Nil, Nil, SI, PI) then
  956. begin
  957. e:=EOSError.CreateFmt(SExecuteProcessFailed,[CommandLine,GetLastError]);
  958. e.ErrorCode:=GetLastError;
  959. raise e;
  960. end;
  961. Proc:=PI.hProcess;
  962. if WaitForSingleObject(Proc, dword($ffffffff)) <> $ffffffff then
  963. begin
  964. GetExitCodeProcess(Proc,l);
  965. CloseHandle(Proc);
  966. CloseHandle(PI.hThread);
  967. result:=l;
  968. end
  969. else
  970. begin
  971. e:=EOSError.CreateFmt(SExecuteProcessFailed,[CommandLine,GetLastError]);
  972. e.ErrorCode:=GetLastError;
  973. CloseHandle(Proc);
  974. CloseHandle(PI.hThread);
  975. raise e;
  976. end;
  977. end;
  978. function ExecuteProcess(Const Path: RawByteString; Const ComLine: Array of RawByteString;Flags:TExecuteFlags=[]):integer;
  979. var
  980. CommandLine: UnicodeString;
  981. I: integer;
  982. begin
  983. Commandline := '';
  984. for I := 0 to High (ComLine) do
  985. if Pos (' ', ComLine [I]) <> 0 then
  986. CommandLine := CommandLine + ' ' + '"' + ComLine [I] + '"'
  987. else
  988. CommandLine := CommandLine + ' ' + Comline [I];
  989. ExecuteProcess := ExecuteProcess (UnicodeString(Path), CommandLine,Flags);
  990. end;
  991. function ExecuteProcess(Const Path: UnicodeString; Const ComLine: Array of UnicodeString;Flags:TExecuteFlags=[]):integer;
  992. var
  993. CommandLine: UnicodeString;
  994. I: integer;
  995. begin
  996. Commandline := '';
  997. for I := 0 to High (ComLine) do
  998. if Pos (' ', ComLine [I]) <> 0 then
  999. CommandLine := CommandLine + ' ' + '"' + ComLine [I] + '"'
  1000. else
  1001. CommandLine := CommandLine + ' ' + Comline [I];
  1002. ExecuteProcess := ExecuteProcess (Path,CommandLine,Flags);
  1003. end;
  1004. Procedure Sleep(Milliseconds : Cardinal);
  1005. begin
  1006. Windows.Sleep(MilliSeconds)
  1007. end;
  1008. Function GetLastOSError : Integer;
  1009. begin
  1010. Result:=GetLastError;
  1011. end;
  1012. {****************************************************************************
  1013. Initialization code
  1014. ****************************************************************************}
  1015. var
  1016. kernel32dll : THandle;
  1017. Procedure LoadVersionInfo;
  1018. // and getfreespaceex
  1019. Var
  1020. versioninfo : TOSVERSIONINFO;
  1021. begin
  1022. GetDiskFreeSpaceEx:=nil;
  1023. versioninfo.dwOSVersionInfoSize:=sizeof(versioninfo);
  1024. GetVersionEx(versioninfo);
  1025. Win32Platform:=versionInfo.dwPlatformId;
  1026. Win32MajorVersion:=versionInfo.dwMajorVersion;
  1027. Win32MinorVersion:=versionInfo.dwMinorVersion;
  1028. Win32BuildNumber:=versionInfo.dwBuildNumber;
  1029. Move (versioninfo.szCSDVersion ,Win32CSDVersion[1],128);
  1030. win32CSDVersion[0]:=chr(strlen(pchar(@versioninfo.szCSDVersion)));
  1031. kernel32dll:=GetModuleHandle('kernel32');
  1032. if kernel32dll<>0 then
  1033. GetDiskFreeSpaceEx:=TGetDiskFreeSpaceEx(GetProcAddress(kernel32dll,'GetDiskFreeSpaceExA'));
  1034. end;
  1035. Function GetAppConfigDir(Global : Boolean) : String;
  1036. begin
  1037. If Global then
  1038. Result:=GetWindowsSpecialDir(CSIDL_COMMON_APPDATA)
  1039. else
  1040. Result:=GetWindowsSpecialDir(CSIDL_LOCAL_APPDATA);
  1041. If (Result<>'') then
  1042. begin
  1043. if VendorName<>'' then
  1044. Result:=IncludeTrailingPathDelimiter(Result+VendorName);
  1045. Result:=IncludeTrailingPathDelimiter(Result+ApplicationName);
  1046. end
  1047. else
  1048. Result:=IncludeTrailingPathDelimiter(DGetAppConfigDir(Global));
  1049. end;
  1050. Function GetAppConfigFile(Global : Boolean; SubDir : Boolean) : String;
  1051. begin
  1052. result:=DGetAppConfigFile(Global,SubDir);
  1053. end;
  1054. Function GetUserDir : String;
  1055. begin
  1056. Result:=GetWindowsSpecialDir(CSIDL_PROFILE);
  1057. end;
  1058. Procedure InitSysConfigDir;
  1059. begin
  1060. SetLength(SysConfigDir, MAX_PATH);
  1061. SetLength(SysConfigDir, GetWindowsDirectoryA(PChar(SysConfigDir), MAX_PATH));
  1062. end;
  1063. {****************************************************************************
  1064. Target Dependent WideString stuff
  1065. ****************************************************************************}
  1066. { This is the case of Win9x. Limited to current locale of course, but it's better
  1067. than not working at all. }
  1068. function DoCompareStringA(P1, P2: PWideChar; L1, L2: PtrUInt; Flags: DWORD): PtrInt;
  1069. var
  1070. a1, a2: AnsiString;
  1071. begin
  1072. if L1>0 then
  1073. widestringmanager.Wide2AnsiMoveProc(P1,a1,DefaultSystemCodePage,L1);
  1074. if L2>0 then
  1075. widestringmanager.Wide2AnsiMoveProc(P2,a2,DefaultSystemCodePage,L2);
  1076. SetLastError(0);
  1077. Result:=CompareStringA(LOCALE_USER_DEFAULT,Flags,pchar(a1),
  1078. length(a1),pchar(a2),length(a2))-2;
  1079. end;
  1080. function DoCompareStringW(P1, P2: PWideChar; L1, L2: PtrUInt; Flags: DWORD): PtrInt;
  1081. begin
  1082. SetLastError(0);
  1083. Result:=CompareStringW(LOCALE_USER_DEFAULT,Flags,P1,L1,P2,L2)-2;
  1084. if GetLastError=0 then
  1085. Exit;
  1086. if GetLastError=ERROR_CALL_NOT_IMPLEMENTED then // Win9x case
  1087. Result:=DoCompareStringA(P1, P2, L1, L2, Flags);
  1088. if GetLastError<>0 then
  1089. RaiseLastOSError;
  1090. end;
  1091. const
  1092. WinAPICompareFlags : array [TCompareOption] of LongWord
  1093. = ({LINGUISTIC_IGNORECASE, LINGUISTIC_IGNOREDIACRITIC, }NORM_IGNORECASE{,
  1094. NORM_IGNOREKANATYPE, NORM_IGNORENONSPACE, NORM_IGNORESYMBOLS, NORM_IGNOREWIDTH,
  1095. NORM_LINGUISTIC_CASING, SORT_DIGITSASNUMBERS, SORT_STRINGSORT});
  1096. function Win32CompareWideString(const s1, s2 : WideString; Options : TCompareOptions) : PtrInt;
  1097. Var
  1098. O : LongWord;
  1099. CO : TCompareOption;
  1100. begin
  1101. O:=0;
  1102. for CO in TCompareOption do
  1103. if CO in Options then
  1104. O:=O or WinAPICompareFlags[CO];
  1105. Result:=DoCompareStringW(PWideChar(s1), PWideChar(s2), Length(s1), Length(s2), O);
  1106. end;
  1107. function Win32CompareTextWideString(const s1, s2 : WideString) : PtrInt;
  1108. begin
  1109. Result:=DoCompareStringW(PWideChar(s1), PWideChar(s2), Length(s1), Length(s2), NORM_IGNORECASE);
  1110. end;
  1111. function Win32AnsiUpperCase(const s: string): string;
  1112. begin
  1113. if length(s)>0 then
  1114. begin
  1115. result:=s;
  1116. UniqueString(result);
  1117. CharUpperBuffA(pchar(result),length(result));
  1118. end
  1119. else
  1120. result:='';
  1121. end;
  1122. function Win32AnsiLowerCase(const s: string): string;
  1123. begin
  1124. if length(s)>0 then
  1125. begin
  1126. result:=s;
  1127. UniqueString(result);
  1128. CharLowerBuffA(pchar(result),length(result));
  1129. end
  1130. else
  1131. result:='';
  1132. end;
  1133. function Win32AnsiCompareStr(const S1, S2: string): PtrInt;
  1134. begin
  1135. result:=CompareStringA(LOCALE_USER_DEFAULT,0,pchar(s1),length(s1),
  1136. pchar(s2),length(s2))-2;
  1137. end;
  1138. function Win32AnsiCompareText(const S1, S2: string): PtrInt;
  1139. begin
  1140. result:=CompareStringA(LOCALE_USER_DEFAULT,NORM_IGNORECASE,pchar(s1),length(s1),
  1141. pchar(s2),length(s2))-2;
  1142. end;
  1143. function Win32AnsiStrComp(S1, S2: PChar): PtrInt;
  1144. begin
  1145. result:=CompareStringA(LOCALE_USER_DEFAULT,0,s1,-1,s2,-1)-2;
  1146. end;
  1147. function Win32AnsiStrIComp(S1, S2: PChar): PtrInt;
  1148. begin
  1149. result:=CompareStringA(LOCALE_USER_DEFAULT,NORM_IGNORECASE,s1,-1,s2,-1)-2;
  1150. end;
  1151. function Win32AnsiStrLComp(S1, S2: PChar; MaxLen: PtrUInt): PtrInt;
  1152. begin
  1153. result:=CompareStringA(LOCALE_USER_DEFAULT,0,s1,maxlen,s2,maxlen)-2;
  1154. end;
  1155. function Win32AnsiStrLIComp(S1, S2: PChar; MaxLen: PtrUInt): PtrInt;
  1156. begin
  1157. result:=CompareStringA(LOCALE_USER_DEFAULT,NORM_IGNORECASE,s1,maxlen,s2,maxlen)-2;
  1158. end;
  1159. function Win32AnsiStrLower(Str: PChar): PChar;
  1160. begin
  1161. CharLowerA(str);
  1162. result:=str;
  1163. end;
  1164. function Win32AnsiStrUpper(Str: PChar): PChar;
  1165. begin
  1166. CharUpperA(str);
  1167. result:=str;
  1168. end;
  1169. function Win32CompareUnicodeString(const s1, s2 : UnicodeString; Options : TCompareOptions) : PtrInt;
  1170. Var
  1171. O : LongWord;
  1172. CO : TCompareOption;
  1173. begin
  1174. O:=0;
  1175. for CO in TCompareOption do
  1176. if CO in Options then
  1177. O:=O or WinAPICompareFlags[CO];
  1178. Result:=DoCompareStringW(PWideChar(s1), PWideChar(s2), Length(s1), Length(s2), O);
  1179. end;
  1180. function Win32CompareTextUnicodeString(const s1, s2 : UnicodeString) : PtrInt;
  1181. begin
  1182. Result:=DoCompareStringW(PWideChar(s1), PWideChar(s2), Length(s1), Length(s2), NORM_IGNORECASE);
  1183. end;
  1184. { there is a similiar procedure in the system unit which inits the fields which
  1185. are relevant already for the system unit }
  1186. procedure InitWin32Widestrings;
  1187. begin
  1188. { return value: number of code points in the string. Whenever an invalid
  1189. code point is encountered, all characters part of this invalid code point
  1190. are considered to form one "character" and the next character is
  1191. considered to be the start of a new (possibly also invalid) code point }
  1192. //!!! CharLengthPCharProc : function(const Str: PChar): PtrInt;
  1193. { return value:
  1194. -1 if incomplete or invalid code point
  1195. 0 if NULL character,
  1196. > 0 if that's the length in bytes of the code point }
  1197. //!!!! CodePointLengthProc : function(const Str: PChar; MaxLookAead: PtrInt): Ptrint;
  1198. widestringmanager.CompareWideStringProc:=@Win32CompareWideString;
  1199. widestringmanager.UpperAnsiStringProc:=@Win32AnsiUpperCase;
  1200. widestringmanager.LowerAnsiStringProc:=@Win32AnsiLowerCase;
  1201. widestringmanager.CompareStrAnsiStringProc:=@Win32AnsiCompareStr;
  1202. widestringmanager.CompareTextAnsiStringProc:=@Win32AnsiCompareText;
  1203. widestringmanager.StrCompAnsiStringProc:=@Win32AnsiStrComp;
  1204. widestringmanager.StrICompAnsiStringProc:=@Win32AnsiStrIComp;
  1205. widestringmanager.StrLCompAnsiStringProc:=@Win32AnsiStrLComp;
  1206. widestringmanager.StrLICompAnsiStringProc:=@Win32AnsiStrLIComp;
  1207. widestringmanager.StrLowerAnsiStringProc:=@Win32AnsiStrLower;
  1208. widestringmanager.StrUpperAnsiStringProc:=@Win32AnsiStrUpper;
  1209. widestringmanager.CompareUnicodeStringProc:=@Win32CompareUnicodeString;
  1210. end;
  1211. { Platform-specific exception support }
  1212. function WinExceptionObject(code: Longint; const rec: TExceptionRecord): Exception;
  1213. var
  1214. entry: PExceptMapEntry;
  1215. begin
  1216. entry := FindExceptMapEntry(code);
  1217. if assigned(entry) then
  1218. result:=entry^.cls.CreateRes(entry^.msg)
  1219. else
  1220. result:=EExternalException.CreateResFmt(@SExternalException,[rec.ExceptionCode]);
  1221. if result is EExternal then
  1222. EExternal(result).FExceptionRecord:=rec;
  1223. end;
  1224. function WinExceptionClass(code: longint): ExceptClass;
  1225. var
  1226. entry: PExceptMapEntry;
  1227. begin
  1228. entry := FindExceptMapEntry(code);
  1229. if assigned(entry) then
  1230. result:=entry^.cls
  1231. else
  1232. result:=EExternalException;
  1233. end;
  1234. Initialization
  1235. InitWin32Widestrings;
  1236. InitExceptions; { Initialize exceptions. OS independent }
  1237. {$ifdef mswindows} { Keeps exe size down for systems that do not use SEH }
  1238. ExceptObjProc:=@WinExceptionObject;
  1239. ExceptClsProc:=@WinExceptionClass;
  1240. {$endif mswindows}
  1241. InitInternational; { Initialize internationalization settings }
  1242. LoadVersionInfo;
  1243. InitSysConfigDir;
  1244. OnBeep:=@SysBeep;
  1245. Finalization
  1246. DoneExceptions;
  1247. end.