sysutils.pp 40 KB

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