sysutils.pp 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180
  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. { force ansistrings }
  16. {$H+}
  17. uses
  18. windows;
  19. {$DEFINE HAS_SLEEP}
  20. {$DEFINE HAS_OSERROR}
  21. {$DEFINE HAS_OSCONFIG}
  22. {$DEFINE HAS_CREATEGUID}
  23. { Include platform independent interface part }
  24. {$i sysutilh.inc}
  25. type
  26. TSystemTime = Windows.TSystemTime;
  27. EWin32Error = class(Exception)
  28. public
  29. ErrorCode : DWORD;
  30. end;
  31. Var
  32. Win32Platform : Longint;
  33. Win32MajorVersion,
  34. Win32MinorVersion,
  35. Win32BuildNumber : dword;
  36. Win32CSDVersion : ShortString; // CSD record is 128 bytes only?
  37. { Compatibility with Delphi }
  38. function Win32Check(res:boolean):boolean;
  39. implementation
  40. uses
  41. sysconst;
  42. function Win32Check(res:boolean):boolean;
  43. begin
  44. if not res then
  45. RaiseLastOSError;
  46. result:=res;
  47. end;
  48. {$define HASCREATEGUID}
  49. {$define HASEXPANDUNCFILENAME}
  50. {$DEFINE FPC_NOGENERICANSIROUTINES}
  51. {$DEFINE FPC_FEXPAND_UNC} (* UNC paths are supported *)
  52. {$DEFINE FPC_FEXPAND_DRIVES} (* Full paths begin with drive specification *)
  53. { Include platform independent implementation part }
  54. {$i sysutils.inc}
  55. Function SysGetTempFileName(lpPathName:LPCSTR; lpPrefixString:LPCSTR; uUnique:UINT; lpTempFileName:LPSTR):UINT; external 'kernel32' name 'GetTempFileNameA';
  56. function GetTempFileName(Dir,Prefix: PChar; uUnique: DWORD; TempFileName: PChar):DWORD;
  57. begin
  58. Result:=SysGetTempFileName(Dir,Prefix,uUnique,TempFileName);
  59. end;
  60. { UUID generation. }
  61. function CoCreateGuid(out guid: TGUID): HResult; stdcall; external 'ole32.dll' name 'CoCreateGuid';
  62. function SysCreateGUID(out Guid: TGUID): Integer;
  63. begin
  64. Result := Integer(CoCreateGuid(Guid));
  65. end;
  66. function ExpandUNCFileName (const filename:string) : string;
  67. { returns empty string on errors }
  68. var
  69. s : ansistring;
  70. size : dword;
  71. rc : dword;
  72. p,buf : pchar;
  73. begin
  74. s := ExpandFileName (filename);
  75. s := s + #0;
  76. size := max_path;
  77. getmem(buf,size);
  78. try
  79. rc := WNetGetUniversalName (pchar(s), UNIVERSAL_NAME_INFO_LEVEL, buf, @size);
  80. if rc=ERROR_MORE_DATA then
  81. begin
  82. buf:=reallocmem(buf,size);
  83. rc := WNetGetUniversalName (pchar(s), UNIVERSAL_NAME_INFO_LEVEL, buf, @size);
  84. end;
  85. if rc = NO_ERROR then
  86. Result := PRemoteNameInfo(buf)^.lpUniversalName
  87. else if rc = ERROR_NOT_CONNECTED then
  88. Result := filename
  89. else
  90. Result := '';
  91. finally
  92. freemem(buf);
  93. end;
  94. end;
  95. {****************************************************************************
  96. File Functions
  97. ****************************************************************************}
  98. var
  99. SetFilePointerEx : function(hFile : THandle;
  100. liDistanceToMove : int64;lpNewFilePointer : pint64;
  101. dwMoveMethod : DWord) : ByteBool;stdcall;
  102. Function FileOpen (Const FileName : string; Mode : Integer) : THandle;
  103. const
  104. AccessMode: array[0..2] of Cardinal = (
  105. GENERIC_READ,
  106. GENERIC_WRITE,
  107. GENERIC_READ or GENERIC_WRITE);
  108. ShareMode: array[0..4] of Integer = (
  109. 0,
  110. 0,
  111. FILE_SHARE_READ,
  112. FILE_SHARE_WRITE,
  113. FILE_SHARE_READ or FILE_SHARE_WRITE);
  114. Var
  115. FN : string;
  116. begin
  117. FN:=FileName+#0;
  118. result := CreateFile(@FN[1], dword(AccessMode[Mode and 3]),
  119. dword(ShareMode[(Mode and $F0) shr 4]), nil, OPEN_EXISTING,
  120. FILE_ATTRIBUTE_NORMAL, 0);
  121. end;
  122. Function FileCreate (Const FileName : String) : THandle;
  123. Var
  124. FN : string;
  125. begin
  126. FN:=FileName+#0;
  127. Result := CreateFile(@FN[1], GENERIC_READ or GENERIC_WRITE,
  128. 0, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  129. end;
  130. Function FileCreate (Const FileName : String; Mode:longint) : THandle;
  131. begin
  132. FileCreate:=FileCreate(FileName);
  133. end;
  134. Function FileRead (Handle : THandle; Var Buffer; Count : longint) : Longint;
  135. Var
  136. res : dword;
  137. begin
  138. if ReadFile(Handle, Buffer, Count, res, nil) then
  139. FileRead:=Res
  140. else
  141. FileRead:=-1;
  142. end;
  143. Function FileWrite (Handle : THandle; const Buffer; Count : Longint) : Longint;
  144. Var
  145. Res : dword;
  146. begin
  147. if WriteFile(Handle, Buffer, Count, Res, nil) then
  148. FileWrite:=Res
  149. else
  150. FileWrite:=-1;
  151. end;
  152. Function FileSeek (Handle : THandle;FOffset,Origin : Longint) : Longint;
  153. begin
  154. Result := longint(SetFilePointer(Handle, FOffset, nil, Origin));
  155. end;
  156. Function FileSeek (Handle : THandle; FOffset,Origin : Int64) : Int64;
  157. begin
  158. if assigned(SetFilePointerEx) then
  159. begin
  160. if not(SetFilePointerEx(Handle, FOffset, @result, Origin)) then
  161. Result:=-1;
  162. end
  163. else
  164. Result:=longint(SetFilePointer(Handle, FOffset, nil, Origin));
  165. end;
  166. Procedure FileClose (Handle : THandle);
  167. begin
  168. if Handle<=4 then
  169. exit;
  170. CloseHandle(Handle);
  171. end;
  172. Function FileTruncate (Handle : THandle;Size: Longint) : boolean;
  173. begin
  174. Result:=longint(SetFilePointer(handle,Size,nil,FILE_BEGIN))<>-1;
  175. If Result then
  176. Result:=SetEndOfFile(handle);
  177. end;
  178. Function DosToWinTime (DTime:longint;Var Wtime : TFileTime):longbool;
  179. var
  180. lft : TFileTime;
  181. begin
  182. DosToWinTime:=DosDateTimeToFileTime(longrec(dtime).hi,longrec(dtime).lo,@lft) and
  183. LocalFileTimeToFileTime(lft,Wtime);
  184. end;
  185. Function WinToDosTime (Var Wtime : TFileTime;var DTime:longint):longbool;
  186. var
  187. lft : TFileTime;
  188. begin
  189. WinToDosTime:=FileTimeToLocalFileTime(WTime,lft) and
  190. FileTimeToDosDateTime(lft,Longrec(Dtime).Hi,LongRec(DTIME).lo);
  191. end;
  192. Function FileAge (Const FileName : String): Longint;
  193. var
  194. Handle: THandle;
  195. FindData: TWin32FindData;
  196. begin
  197. Handle := FindFirstFile(Pchar(FileName), FindData);
  198. if Handle <> INVALID_HANDLE_VALUE then
  199. begin
  200. Windows.FindClose(Handle);
  201. if (FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) = 0 then
  202. If WinToDosTime(FindData.ftLastWriteTime,Result) then
  203. exit;
  204. end;
  205. Result := -1;
  206. end;
  207. Function FileExists (Const FileName : String) : Boolean;
  208. var
  209. Attr:Dword;
  210. begin
  211. Attr:=GetFileAttributes(PChar(FileName));
  212. if Attr <> $ffffffff then
  213. Result:= (Attr and FILE_ATTRIBUTE_DIRECTORY) = 0
  214. else
  215. Result:=False;
  216. end;
  217. Function DirectoryExists (Const Directory : String) : Boolean;
  218. var
  219. Attr:Dword;
  220. begin
  221. Attr:=GetFileAttributes(PChar(Directory));
  222. if Attr <> $ffffffff then
  223. Result:= (Attr and FILE_ATTRIBUTE_DIRECTORY) > 0
  224. else
  225. Result:=False;
  226. end;
  227. Function FindMatch(var f: TSearchRec) : Longint;
  228. begin
  229. { Find file with correct attribute }
  230. While (F.FindData.dwFileAttributes and cardinal(F.ExcludeAttr))<>0 do
  231. begin
  232. if not FindNextFile (F.FindHandle,F.FindData) then
  233. begin
  234. Result:=GetLastError;
  235. exit;
  236. end;
  237. end;
  238. { Convert some attributes back }
  239. WinToDosTime(F.FindData.ftLastWriteTime,F.Time);
  240. f.size:=F.FindData.NFileSizeLow;
  241. f.attr:=F.FindData.dwFileAttributes;
  242. f.Name:=StrPas(@F.FindData.cFileName);
  243. Result:=0;
  244. end;
  245. Function FindFirst (Const Path : String; Attr : Longint; out Rslt : TSearchRec) : Longint;
  246. begin
  247. Rslt.Name:=Path;
  248. Rslt.Attr:=attr;
  249. Rslt.ExcludeAttr:=(not Attr) and ($1e);
  250. { $1e = faHidden or faSysFile or faVolumeID or faDirectory }
  251. { FindFirstFile is a Win32 Call }
  252. Rslt.FindHandle:=FindFirstFile (PChar(Path),Rslt.FindData);
  253. If Rslt.FindHandle=Invalid_Handle_value then
  254. begin
  255. Result:=GetLastError;
  256. exit;
  257. end;
  258. { Find file with correct attribute }
  259. Result:=FindMatch(Rslt);
  260. end;
  261. Function FindNext (Var Rslt : TSearchRec) : Longint;
  262. begin
  263. if FindNextFile(Rslt.FindHandle, Rslt.FindData) then
  264. Result := FindMatch(Rslt)
  265. else
  266. Result := GetLastError;
  267. end;
  268. Procedure FindClose (Var F : TSearchrec);
  269. begin
  270. if F.FindHandle <> INVALID_HANDLE_VALUE then
  271. Windows.FindClose(F.FindHandle);
  272. end;
  273. Function FileGetDate (Handle : THandle) : Longint;
  274. Var
  275. FT : TFileTime;
  276. begin
  277. If GetFileTime(Handle,nil,nil,@ft) and
  278. WinToDosTime(FT,Result) then
  279. exit;
  280. Result:=-1;
  281. end;
  282. Function FileSetDate (Handle : THandle;Age : Longint) : Longint;
  283. Var
  284. FT: TFileTime;
  285. begin
  286. Result := 0;
  287. if DosToWinTime(Age,FT) and
  288. SetFileTime(Handle, ft, ft, FT) then
  289. Exit;
  290. Result := GetLastError;
  291. end;
  292. Function FileGetAttr (Const FileName : String) : Longint;
  293. begin
  294. Result:=GetFileAttributes(PChar(FileName));
  295. end;
  296. Function FileSetAttr (Const Filename : String; Attr: longint) : Longint;
  297. begin
  298. if SetFileAttributes(PChar(FileName), Attr) then
  299. Result:=0
  300. else
  301. Result := GetLastError;
  302. end;
  303. Function DeleteFile (Const FileName : String) : Boolean;
  304. begin
  305. Result:=Windows.DeleteFile(Pchar(FileName));
  306. end;
  307. Function RenameFile (Const OldName, NewName : String) : Boolean;
  308. begin
  309. Result := MoveFile(PChar(OldName), PChar(NewName));
  310. end;
  311. {****************************************************************************
  312. Disk Functions
  313. ****************************************************************************}
  314. function GetDiskFreeSpace(drive:pchar;var sector_cluster,bytes_sector,
  315. freeclusters,totalclusters:longint):longbool;
  316. stdcall;external 'kernel32' name 'GetDiskFreeSpaceA';
  317. type
  318. TGetDiskFreeSpaceEx = function(drive:pchar;var availableforcaller,total,free):longbool;stdcall;
  319. var
  320. GetDiskFreeSpaceEx : TGetDiskFreeSpaceEx;
  321. function diskfree(drive : byte) : int64;
  322. var
  323. disk : array[1..4] of char;
  324. secs,bytes,
  325. free,total : longint;
  326. qwtotal,qwfree,qwcaller : int64;
  327. begin
  328. if drive=0 then
  329. begin
  330. disk[1]:='\';
  331. disk[2]:=#0;
  332. end
  333. else
  334. begin
  335. disk[1]:=chr(drive+64);
  336. disk[2]:=':';
  337. disk[3]:='\';
  338. disk[4]:=#0;
  339. end;
  340. if assigned(GetDiskFreeSpaceEx) then
  341. begin
  342. if GetDiskFreeSpaceEx(@disk,qwcaller,qwtotal,qwfree) then
  343. diskfree:=qwfree
  344. else
  345. diskfree:=-1;
  346. end
  347. else
  348. begin
  349. if GetDiskFreeSpace(@disk,secs,bytes,free,total) then
  350. diskfree:=int64(free)*secs*bytes
  351. else
  352. diskfree:=-1;
  353. end;
  354. end;
  355. function disksize(drive : byte) : int64;
  356. var
  357. disk : array[1..4] of char;
  358. secs,bytes,
  359. free,total : longint;
  360. qwtotal,qwfree,qwcaller : int64;
  361. begin
  362. if drive=0 then
  363. begin
  364. disk[1]:='\';
  365. disk[2]:=#0;
  366. end
  367. else
  368. begin
  369. disk[1]:=chr(drive+64);
  370. disk[2]:=':';
  371. disk[3]:='\';
  372. disk[4]:=#0;
  373. end;
  374. if assigned(GetDiskFreeSpaceEx) then
  375. begin
  376. if GetDiskFreeSpaceEx(@disk,qwcaller,qwtotal,qwfree) then
  377. disksize:=qwtotal
  378. else
  379. disksize:=-1;
  380. end
  381. else
  382. begin
  383. if GetDiskFreeSpace(@disk,secs,bytes,free,total) then
  384. disksize:=int64(total)*secs*bytes
  385. else
  386. disksize:=-1;
  387. end;
  388. end;
  389. Function GetCurrentDir : String;
  390. begin
  391. GetDir(0, result);
  392. end;
  393. Function SetCurrentDir (Const NewDir : String) : Boolean;
  394. begin
  395. Result:=SetCurrentDirectory(PChar(NewDir));
  396. end;
  397. Function CreateDir (Const NewDir : String) : Boolean;
  398. begin
  399. Result:=CreateDirectory(PChar(NewDir),nil);
  400. end;
  401. Function RemoveDir (Const Dir : String) : Boolean;
  402. begin
  403. Result:=RemoveDirectory(PChar(Dir));
  404. end;
  405. {****************************************************************************
  406. Time Functions
  407. ****************************************************************************}
  408. Procedure GetLocalTime(var SystemTime: TSystemTime);
  409. Var
  410. Syst : Windows.TSystemtime;
  411. begin
  412. windows.Getlocaltime(@syst);
  413. SystemTime.year:=syst.wYear;
  414. SystemTime.month:=syst.wMonth;
  415. SystemTime.day:=syst.wDay;
  416. SystemTime.hour:=syst.wHour;
  417. SystemTime.minute:=syst.wMinute;
  418. SystemTime.second:=syst.wSecond;
  419. SystemTime.millisecond:=syst.wMilliSeconds;
  420. end;
  421. {****************************************************************************
  422. Misc Functions
  423. ****************************************************************************}
  424. procedure Beep;
  425. begin
  426. MessageBeep(0);
  427. end;
  428. {****************************************************************************
  429. Locale Functions
  430. ****************************************************************************}
  431. Procedure InitAnsi;
  432. Var
  433. i : longint;
  434. begin
  435. { Fill table entries 0 to 127 }
  436. for i := 0 to 96 do
  437. UpperCaseTable[i] := chr(i);
  438. for i := 97 to 122 do
  439. UpperCaseTable[i] := chr(i - 32);
  440. for i := 123 to 191 do
  441. UpperCaseTable[i] := chr(i);
  442. Move (CPISO88591UCT,UpperCaseTable[192],SizeOf(CPISO88591UCT));
  443. for i := 0 to 64 do
  444. LowerCaseTable[i] := chr(i);
  445. for i := 65 to 90 do
  446. LowerCaseTable[i] := chr(i + 32);
  447. for i := 91 to 191 do
  448. LowerCaseTable[i] := chr(i);
  449. Move (CPISO88591LCT,UpperCaseTable[192],SizeOf(CPISO88591UCT));
  450. end;
  451. function GetLocaleStr(LID, LT: Longint; const Def: string): ShortString;
  452. var
  453. L: Integer;
  454. Buf: array[0..255] of Char;
  455. begin
  456. L := GetLocaleInfo(LID, LT, Buf, SizeOf(Buf));
  457. if L > 0 then
  458. SetString(Result, @Buf[0], L - 1)
  459. else
  460. Result := Def;
  461. end;
  462. function GetLocaleChar(LID, LT: Longint; Def: Char): Char;
  463. var
  464. Buf: array[0..1] of Char;
  465. begin
  466. if GetLocaleInfo(LID, LT, Buf, 2) > 0 then
  467. Result := Buf[0]
  468. else
  469. Result := Def;
  470. end;
  471. Function GetLocaleInt(LID,TP,Def: LongInt): LongInt;
  472. Var
  473. S: String;
  474. C: Integer;
  475. Begin
  476. S:=GetLocaleStr(LID,TP,'0');
  477. Val(S,Result,C);
  478. If C<>0 Then
  479. Result:=Def;
  480. End;
  481. procedure GetFormatSettings;
  482. var
  483. HF : Shortstring;
  484. LID : LCID;
  485. I,Day : longint;
  486. begin
  487. LID := GetThreadLocale;
  488. { Date stuff }
  489. for I := 1 to 12 do
  490. begin
  491. ShortMonthNames[I]:=GetLocaleStr(LID,LOCALE_SABBREVMONTHNAME1+I-1,ShortMonthNames[i]);
  492. LongMonthNames[I]:=GetLocaleStr(LID,LOCALE_SMONTHNAME1+I-1,LongMonthNames[i]);
  493. end;
  494. for I := 1 to 7 do
  495. begin
  496. Day := (I + 5) mod 7;
  497. ShortDayNames[I]:=GetLocaleStr(LID,LOCALE_SABBREVDAYNAME1+Day,ShortDayNames[i]);
  498. LongDayNames[I]:=GetLocaleStr(LID,LOCALE_SDAYNAME1+Day,LongDayNames[i]);
  499. end;
  500. DateSeparator := GetLocaleChar(LID, LOCALE_SDATE, '/');
  501. ShortDateFormat := GetLocaleStr(LID, LOCALE_SSHORTDATE, 'm/d/yy');
  502. LongDateFormat := GetLocaleStr(LID, LOCALE_SLONGDATE, 'mmmm d, yyyy');
  503. { Time stuff }
  504. TimeSeparator := GetLocaleChar(LID, LOCALE_STIME, ':');
  505. TimeAMString := GetLocaleStr(LID, LOCALE_S1159, 'AM');
  506. TimePMString := GetLocaleStr(LID, LOCALE_S2359, 'PM');
  507. if StrToIntDef(GetLocaleStr(LID, LOCALE_ITLZERO, '0'), 0) = 0 then
  508. HF:='h'
  509. else
  510. HF:='hh';
  511. // No support for 12 hour stuff at the moment...
  512. ShortTimeFormat := HF+':nn';
  513. LongTimeFormat := HF + ':nn:ss';
  514. { Currency stuff }
  515. CurrencyString:=GetLocaleStr(LID, LOCALE_SCURRENCY, '');
  516. CurrencyFormat:=StrToIntDef(GetLocaleStr(LID, LOCALE_ICURRENCY, '0'), 0);
  517. NegCurrFormat:=StrToIntDef(GetLocaleStr(LID, LOCALE_INEGCURR, '0'), 0);
  518. { Number stuff }
  519. ThousandSeparator:=GetLocaleChar(LID, LOCALE_STHOUSAND, ',');
  520. DecimalSeparator:=GetLocaleChar(LID, LOCALE_SDECIMAL, '.');
  521. CurrencyDecimals:=StrToIntDef(GetLocaleStr(LID, LOCALE_ICURRDIGITS, '0'), 0);
  522. end;
  523. Procedure InitInternational;
  524. var
  525. { A call to GetSystemMetrics changes the value of the 8087 Control Word on
  526. Pentium4 with WinXP SP2 }
  527. old8087CW: word;
  528. begin
  529. InitInternationalGeneric;
  530. old8087CW:=Get8087CW;
  531. SysLocale.MBCS:=GetSystemMetrics(SM_DBCSENABLED)<>0;
  532. SysLocale.RightToLeft:=GetSystemMetrics(SM_MIDEASTENABLED)<>0;
  533. SysLocale.DefaultLCID := $0409;
  534. SysLocale.PriLangID := LANG_ENGLISH;
  535. SysLocale.SubLangID := SUBLANG_ENGLISH_US;
  536. // probably needs update with getthreadlocale. post 2.0.2
  537. Set8087CW(old8087CW);
  538. InitAnsi;
  539. GetFormatSettings;
  540. end;
  541. {****************************************************************************
  542. Target Dependent
  543. ****************************************************************************}
  544. function FormatMessageA(dwFlags : DWORD;
  545. lpSource : Pointer;
  546. dwMessageId : DWORD;
  547. dwLanguageId: DWORD;
  548. lpBuffer : PCHAR;
  549. nSize : DWORD;
  550. Arguments : Pointer): DWORD; stdcall;external 'kernel32' name 'FormatMessageA';
  551. function SysErrorMessage(ErrorCode: Integer): String;
  552. const
  553. MaxMsgSize = Format_Message_Max_Width_Mask;
  554. var
  555. MsgBuffer: pChar;
  556. begin
  557. GetMem(MsgBuffer, MaxMsgSize);
  558. FillChar(MsgBuffer^, MaxMsgSize, #0);
  559. FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM,
  560. nil,
  561. ErrorCode,
  562. MakeLangId(LANG_NEUTRAL, SUBLANG_DEFAULT),
  563. MsgBuffer, { This function allocs the memory }
  564. MaxMsgSize, { Maximum message size }
  565. nil);
  566. SysErrorMessage := StrPas(MsgBuffer);
  567. FreeMem(MsgBuffer, MaxMsgSize);
  568. end;
  569. {****************************************************************************
  570. Initialization code
  571. ****************************************************************************}
  572. Function GetEnvironmentVariable(Const EnvVar : String) : String;
  573. var
  574. s : string;
  575. i : longint;
  576. hp,p : pchar;
  577. begin
  578. Result:='';
  579. p:=GetEnvironmentStrings;
  580. hp:=p;
  581. while hp^<>#0 do
  582. begin
  583. s:=strpas(hp);
  584. i:=pos('=',s);
  585. if uppercase(copy(s,1,i-1))=upcase(envvar) then
  586. begin
  587. Result:=copy(s,i+1,length(s)-i);
  588. break;
  589. end;
  590. { next string entry}
  591. hp:=hp+strlen(hp)+1;
  592. end;
  593. FreeEnvironmentStrings(p);
  594. end;
  595. Function GetEnvironmentVariableCount : Integer;
  596. var
  597. hp,p : pchar;
  598. begin
  599. Result:=0;
  600. p:=GetEnvironmentStrings;
  601. hp:=p;
  602. If (Hp<>Nil) then
  603. while hp^<>#0 do
  604. begin
  605. Inc(Result);
  606. hp:=hp+strlen(hp)+1;
  607. end;
  608. FreeEnvironmentStrings(p);
  609. end;
  610. Function GetEnvironmentString(Index : Integer) : String;
  611. var
  612. hp,p : pchar;
  613. begin
  614. Result:='';
  615. p:=GetEnvironmentStrings;
  616. hp:=p;
  617. If (Hp<>Nil) then
  618. begin
  619. while (hp^<>#0) and (Index>1) do
  620. begin
  621. Dec(Index);
  622. hp:=hp+strlen(hp)+1;
  623. end;
  624. If (hp^<>#0) then
  625. Result:=StrPas(HP);
  626. end;
  627. FreeEnvironmentStrings(p);
  628. end;
  629. function ExecuteProcess(Const Path: AnsiString; Const ComLine: AnsiString):integer;
  630. var
  631. SI: TStartupInfo;
  632. PI: TProcessInformation;
  633. Proc : THandle;
  634. l : DWord;
  635. CommandLine : ansistring;
  636. e : EOSError;
  637. begin
  638. FillChar(SI, SizeOf(SI), 0);
  639. SI.cb:=SizeOf(SI);
  640. SI.wShowWindow:=1;
  641. { always surround the name of the application by quotes
  642. so that long filenames will always be accepted. But don't
  643. do it if there are already double quotes, since Win32 does not
  644. like double quotes which are duplicated!
  645. }
  646. if pos('"',path)=0 then
  647. CommandLine:='"'+path+'"'
  648. else
  649. CommandLine:=path;
  650. if ComLine <> '' then
  651. CommandLine:=Commandline+' '+ComLine+#0
  652. else
  653. CommandLine := CommandLine + #0;
  654. if not CreateProcess(nil, pchar(CommandLine),
  655. Nil, Nil, False,$20, Nil, Nil, SI, PI) then
  656. begin
  657. e:=EOSError.CreateFmt(SExecuteProcessFailed,[CommandLine,GetLastError]);
  658. e.ErrorCode:=GetLastError;
  659. raise e;
  660. end;
  661. Proc:=PI.hProcess;
  662. if WaitForSingleObject(Proc, dword($ffffffff)) <> $ffffffff then
  663. begin
  664. GetExitCodeProcess(Proc,l);
  665. CloseHandle(Proc);
  666. CloseHandle(PI.hThread);
  667. result:=l;
  668. end
  669. else
  670. begin
  671. e:=EOSError.CreateFmt(SExecuteProcessFailed,[CommandLine,GetLastError]);
  672. e.ErrorCode:=GetLastError;
  673. CloseHandle(Proc);
  674. CloseHandle(PI.hThread);
  675. raise e;
  676. end;
  677. end;
  678. function ExecuteProcess(Const Path: AnsiString; Const ComLine: Array of AnsiString):integer;
  679. Var
  680. CommandLine : AnsiString;
  681. i : Integer;
  682. Begin
  683. Commandline:='';
  684. For i:=0 to high(ComLine) Do
  685. Commandline:=CommandLine+' '+Comline[i];
  686. ExecuteProcess:=ExecuteProcess(Path,CommandLine);
  687. End;
  688. Procedure Sleep(Milliseconds : Cardinal);
  689. begin
  690. Windows.Sleep(MilliSeconds)
  691. end;
  692. Function GetLastOSError : Integer;
  693. begin
  694. Result:=GetLastError;
  695. end;
  696. {****************************************************************************
  697. Initialization code
  698. ****************************************************************************}
  699. var
  700. kernel32dll : THandle;
  701. Procedure LoadVersionInfo;
  702. // and getfreespaceex
  703. Var
  704. versioninfo : TOSVERSIONINFO;
  705. i : Integer;
  706. begin
  707. kernel32dll:=0;
  708. GetDiskFreeSpaceEx:=nil;
  709. versioninfo.dwOSVersionInfoSize:=sizeof(versioninfo);
  710. GetVersionEx(versioninfo);
  711. Win32Platform:=versionInfo.dwPlatformId;
  712. Win32MajorVersion:=versionInfo.dwMajorVersion;
  713. Win32MinorVersion:=versionInfo.dwMinorVersion;
  714. Win32BuildNumber:=versionInfo.dwBuildNumber;
  715. Move (versioninfo.szCSDVersion ,Win32CSDVersion[1],128);
  716. win32CSDVersion[0]:=chr(strlen(pchar(@versioninfo.szCSDVersion)));
  717. if ((versioninfo.dwPlatformId=VER_PLATFORM_WIN32_WINDOWS) and
  718. (versioninfo.dwBuildNUmber>=1000)) or
  719. (versioninfo.dwPlatformId=VER_PLATFORM_WIN32_NT) then
  720. begin
  721. kernel32dll:=LoadLibrary('kernel32');
  722. if kernel32dll<>0 then
  723. GetDiskFreeSpaceEx:=TGetDiskFreeSpaceEx(GetProcAddress(kernel32dll,'GetDiskFreeSpaceExA'));
  724. end;
  725. end;
  726. function FreeLibrary(hLibModule : THANDLE) : longbool;
  727. stdcall;external 'kernel32' name 'FreeLibrary';
  728. function GetVersionEx(var VersionInformation:TOSVERSIONINFO) : longbool;
  729. stdcall;external 'kernel32' name 'GetVersionExA';
  730. function LoadLibrary(lpLibFileName : pchar):THandle;
  731. stdcall;external 'kernel32' name 'LoadLibraryA';
  732. function GetProcAddress(hModule : THandle;lpProcName : pchar) : pointer;
  733. stdcall;external 'kernel32' name 'GetProcAddress';
  734. Const
  735. CSIDL_PROGRAMS = $0002; { %SYSTEMDRIVE%\Program Files }
  736. CSIDL_PERSONAL = $0005; { %USERPROFILE%\My Documents }
  737. CSIDL_FAVORITES = $0006; { %USERPROFILE%\Favorites }
  738. CSIDL_STARTUP = $0007; { %USERPROFILE%\Start menu\Programs\Startup }
  739. CSIDL_RECENT = $0008; { %USERPROFILE%\Recent }
  740. CSIDL_SENDTO = $0009; { %USERPROFILE%\Sendto }
  741. CSIDL_STARTMENU = $000B; { %USERPROFILE%\Start menu }
  742. CSIDL_MYMUSIC = $000D; { %USERPROFILE%\Documents\My Music }
  743. CSIDL_MYVIDEO = $000E; { %USERPROFILE%\Documents\My Videos }
  744. CSIDL_DESKTOPDIRECTORY = $0010; { %USERPROFILE%\Desktop }
  745. CSIDL_NETHOOD = $0013; { %USERPROFILE%\NetHood }
  746. CSIDL_TEMPLATES = $0015; { %USERPROFILE%\Templates }
  747. CSIDL_COMMON_STARTMENU = $0016; { %PROFILEPATH%\All users\Start menu }
  748. CSIDL_COMMON_PROGRAMS = $0017; { %PROFILEPATH%\All users\Start menu\Programs }
  749. CSIDL_COMMON_STARTUP = $0018; { %PROFILEPATH%\All users\Start menu\Programs\Startup }
  750. CSIDL_COMMON_DESKTOPDIRECTORY = $0019; { %PROFILEPATH%\All users\Desktop }
  751. CSIDL_APPDATA = $001A; { %USERPROFILE%\Application Data (roaming) }
  752. CSIDL_PRINTHOOD = $001B; { %USERPROFILE%\Printhood }
  753. CSIDL_LOCAL_APPDATA = $001C; { %USERPROFILE%\Local Settings\Application Data (non roaming) }
  754. CSIDL_COMMON_FAVORITES = $001F; { %PROFILEPATH%\All users\Favorites }
  755. CSIDL_INTERNET_CACHE = $0020; { %USERPROFILE%\Local Settings\Temporary Internet Files }
  756. CSIDL_COOKIES = $0021; { %USERPROFILE%\Cookies }
  757. CSIDL_HISTORY = $0022; { %USERPROFILE%\Local settings\History }
  758. CSIDL_COMMON_APPDATA = $0023; { %PROFILESPATH%\All Users\Application Data }
  759. CSIDL_WINDOWS = $0024; { %SYSTEMROOT% }
  760. CSIDL_SYSTEM = $0025; { %SYSTEMROOT%\SYSTEM32 (may be system on 95/98/ME) }
  761. CSIDL_PROGRAM_FILES = $0026; { %SYSTEMDRIVE%\Program Files }
  762. CSIDL_MYPICTURES = $0027; { %USERPROFILE%\My Documents\My Pictures }
  763. CSIDL_PROFILE = $0028; { %USERPROFILE% }
  764. CSIDL_PROGRAM_FILES_COMMON = $002B; { %SYSTEMDRIVE%\Program Files\Common }
  765. CSIDL_COMMON_TEMPLATES = $002D; { %PROFILEPATH%\All Users\Templates }
  766. CSIDL_COMMON_DOCUMENTS = $002E; { %PROFILEPATH%\All Users\Documents }
  767. CSIDL_COMMON_ADMINTOOLS = $002F; { %PROFILEPATH%\All Users\Start Menu\Programs\Administrative Tools }
  768. CSIDL_ADMINTOOLS = $0030; { %USERPROFILE%\Start Menu\Programs\Administrative Tools }
  769. CSIDL_COMMON_MUSIC = $0035; { %PROFILEPATH%\All Users\Documents\my music }
  770. CSIDL_COMMON_PICTURES = $0036; { %PROFILEPATH%\All Users\Documents\my pictures }
  771. CSIDL_COMMON_VIDEO = $0037; { %PROFILEPATH%\All Users\Documents\my videos }
  772. CSIDL_CDBURN_AREA = $003B; { %USERPROFILE%\Local Settings\Application Data\Microsoft\CD Burning }
  773. CSIDL_PROFILES = $003E; { %PROFILEPATH% }
  774. CSIDL_FLAG_CREATE = $8000; { (force creation of requested folder if it doesn't exist yet) }
  775. Type
  776. PFNSHGetFolderPath = Function(Ahwnd: HWND; Csidl: Integer; Token: THandle; Flags: DWord; Path: PChar): HRESULT; stdcall;
  777. var
  778. SHGetFolderPath : PFNSHGetFolderPath = Nil;
  779. CFGDLLHandle : THandle = 0;
  780. Procedure InitDLL;
  781. Var
  782. P : Pointer;
  783. begin
  784. CFGDLLHandle:=LoadLibrary('shell32.dll');
  785. if (CFGDLLHandle<>0) then
  786. begin
  787. P:=GetProcAddress(CFGDLLHandle,'SHGetFolderPathA');
  788. If (P=Nil) then
  789. begin
  790. FreeLibrary(CFGDLLHandle);
  791. CFGDllHandle:=0;
  792. end
  793. else
  794. SHGetFolderPath:=PFNSHGetFolderPath(P);
  795. end;
  796. If (P=Nil) then
  797. begin
  798. CFGDLLHandle:=LoadLibrary('shfolder.dll');
  799. if (CFGDLLHandle<>0) then
  800. begin
  801. P:=GetProcAddress(CFGDLLHandle,'SHGetFolderPathA');
  802. If (P=Nil) then
  803. begin
  804. FreeLibrary(CFGDLLHandle);
  805. CFGDllHandle:=0;
  806. end
  807. else
  808. ShGetFolderPath:=PFNSHGetFolderPath(P);
  809. end;
  810. end;
  811. If (@ShGetFolderPath=Nil) then
  812. Raise Exception.Create('Could not determine SHGetFolderPath Function');
  813. end;
  814. Function GetSpecialDir(ID : Integer) : String;
  815. Var
  816. APath : Array[0..MAX_PATH] of char;
  817. begin
  818. Result:='';
  819. if (CFGDLLHandle=0) then
  820. InitDLL;
  821. If (SHGetFolderPath<>Nil) then
  822. begin
  823. if SHGetFolderPath(0,ID or CSIDL_FLAG_CREATE,0,0,@APATH[0])=S_OK then
  824. Result:=IncludeTrailingPathDelimiter(StrPas(@APath[0]));
  825. end;
  826. end;
  827. Function GetAppConfigDir(Global : Boolean) : String;
  828. begin
  829. If Global then
  830. Result:=DGetAppConfigDir(Global) // or use windows dir ??
  831. else
  832. begin
  833. Result:=GetSpecialDir(CSIDL_LOCAL_APPDATA)+ApplicationName;
  834. If (Result='') then
  835. Result:=DGetAppConfigDir(Global);
  836. end;
  837. end;
  838. Function GetAppConfigFile(Global : Boolean; SubDir : Boolean) : String;
  839. begin
  840. if Global then
  841. begin
  842. Result:=IncludeTrailingPathDelimiter(DGetAppConfigDir(Global));
  843. if SubDir then
  844. Result:=IncludeTrailingPathDelimiter(Result+'Config');
  845. Result:=Result+ApplicationName+ConfigExtension;
  846. end
  847. else
  848. begin
  849. Result:=IncludeTrailingPathDelimiter(GetAppConfigDir(False));
  850. if SubDir then
  851. Result:=Result+'Config\';
  852. Result:=Result+ApplicationName+ConfigExtension;
  853. end;
  854. end;
  855. Procedure InitSysConfigDir;
  856. begin
  857. SetLength(SysConfigDir, MAX_PATH);
  858. SetLength(SysConfigDir, GetWindowsDirectory(PChar(SysConfigDir), MAX_PATH));
  859. end;
  860. {****************************************************************************
  861. Target Dependent WideString stuff
  862. ****************************************************************************}
  863. function Win32CompareWideString(const s1, s2 : WideString) : PtrInt;
  864. begin
  865. SetLastError(0);
  866. Result:=CompareStringW(LOCALE_USER_DEFAULT,0,pwidechar(s1),
  867. length(s1),pwidechar(s2),length(s2))-2;
  868. if GetLastError<>0 then
  869. RaiseLastOSError;
  870. end;
  871. function Win32CompareTextWideString(const s1, s2 : WideString) : PtrInt;
  872. begin
  873. SetLastError(0);
  874. Result:=CompareStringW(LOCALE_USER_DEFAULT,NORM_IGNORECASE,pwidechar(s1),
  875. length(s1),pwidechar(s2),length(s2))-2;
  876. if GetLastError<>0 then
  877. RaiseLastOSError;
  878. end;
  879. function Win32AnsiUpperCase(const s: string): string;
  880. begin
  881. if length(s)>0 then
  882. begin
  883. result:=s;
  884. UniqueString(result);
  885. CharUpperBuff(pchar(result),length(result));
  886. end
  887. else
  888. result:='';
  889. end;
  890. function Win32AnsiLowerCase(const s: string): string;
  891. begin
  892. if length(s)>0 then
  893. begin
  894. result:=s;
  895. UniqueString(result);
  896. CharLowerBuff(pchar(result),length(result));
  897. end
  898. else
  899. result:='';
  900. end;
  901. function Win32AnsiCompareStr(const S1, S2: string): PtrInt;
  902. begin
  903. result:=CompareString(LOCALE_USER_DEFAULT,0,pchar(s1),length(s1),
  904. pchar(s2),length(s2))-2;
  905. end;
  906. function Win32AnsiCompareText(const S1, S2: string): PtrInt;
  907. begin
  908. result:=CompareString(LOCALE_USER_DEFAULT,NORM_IGNORECASE,pchar(s1),length(s1),
  909. pchar(s2),length(s2))-2;
  910. end;
  911. function Win32AnsiStrComp(S1, S2: PChar): PtrInt;
  912. begin
  913. result:=CompareString(LOCALE_USER_DEFAULT,0,s1,-1,s2,-1)-2;
  914. end;
  915. function Win32AnsiStrIComp(S1, S2: PChar): PtrInt;
  916. begin
  917. result:=CompareString(LOCALE_USER_DEFAULT,NORM_IGNORECASE,s1,-1,s2,-1)-2;
  918. end;
  919. function Win32AnsiStrLComp(S1, S2: PChar; MaxLen: PtrUInt): PtrInt;
  920. begin
  921. result:=CompareString(LOCALE_USER_DEFAULT,0,s1,maxlen,s2,maxlen)-2;
  922. end;
  923. function Win32AnsiStrLIComp(S1, S2: PChar; MaxLen: PtrUInt): PtrInt;
  924. begin
  925. result:=CompareString(LOCALE_USER_DEFAULT,NORM_IGNORECASE,s1,maxlen,s2,maxlen)-2;
  926. end;
  927. function Win32AnsiStrLower(Str: PChar): PChar;
  928. begin
  929. CharLower(str);
  930. result:=str;
  931. end;
  932. function Win32AnsiStrUpper(Str: PChar): PChar;
  933. begin
  934. CharUpper(str);
  935. result:=str;
  936. end;
  937. { there is a similiar procedure in the system unit which inits the fields which
  938. are relevant already for the system unit }
  939. procedure InitWin32Widestrings;
  940. begin
  941. widestringmanager.CompareWideStringProc:=@Win32CompareWideString;
  942. widestringmanager.CompareTextWideStringProc:=@Win32CompareTextWideString;
  943. widestringmanager.UpperAnsiStringProc:=@Win32AnsiUpperCase;
  944. widestringmanager.LowerAnsiStringProc:=@Win32AnsiLowerCase;
  945. widestringmanager.CompareStrAnsiStringProc:=@Win32AnsiCompareStr;
  946. widestringmanager.CompareTextAnsiStringProc:=@Win32AnsiCompareText;
  947. widestringmanager.StrCompAnsiStringProc:=@Win32AnsiStrComp;
  948. widestringmanager.StrICompAnsiStringProc:=@Win32AnsiStrIComp;
  949. widestringmanager.StrLCompAnsiStringProc:=@Win32AnsiStrLComp;
  950. widestringmanager.StrLICompAnsiStringProc:=@Win32AnsiStrLIComp;
  951. widestringmanager.StrLowerAnsiStringProc:=@Win32AnsiStrLower;
  952. widestringmanager.StrUpperAnsiStringProc:=@Win32AnsiStrUpper;
  953. end;
  954. procedure SetupProcVars;
  955. var
  956. hinstLib : THandle;
  957. begin
  958. SetFilePointerEx:=nil;
  959. hinstLib:=LoadLibrary(KernelDLL);
  960. if hinstLib<>0 then
  961. begin
  962. pointer(SetFilePointerEx):=GetProcAddress(hinstLib,'SetFilePointerEx');
  963. FreeLibrary(hinstLib);
  964. end;
  965. end;
  966. Initialization
  967. InitWin32Widestrings;
  968. InitExceptions; { Initialize exceptions. OS independent }
  969. InitInternational; { Initialize internationalization settings }
  970. LoadVersionInfo;
  971. InitSysConfigDir;
  972. SetupProcVars;
  973. Finalization
  974. DoneExceptions;
  975. if kernel32dll<>0 then
  976. FreeLibrary(kernel32dll);
  977. if CFGDLLHandle<>0 then
  978. FreeLibrary(CFGDllHandle);
  979. end.