sysutils.pp 29 KB

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