sysutils.pp 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099
  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. begin
  511. InitAnsi;
  512. GetFormatSettings;
  513. end;
  514. {****************************************************************************
  515. Target Dependent
  516. ****************************************************************************}
  517. function FormatMessageA(dwFlags : DWORD;
  518. lpSource : Pointer;
  519. dwMessageId : DWORD;
  520. dwLanguageId: DWORD;
  521. lpBuffer : PCHAR;
  522. nSize : DWORD;
  523. Arguments : Pointer): DWORD; stdcall;external 'kernel32' name 'FormatMessageA';
  524. function SysErrorMessage(ErrorCode: Integer): String;
  525. const
  526. MaxMsgSize = Format_Message_Max_Width_Mask;
  527. var
  528. MsgBuffer: pChar;
  529. begin
  530. GetMem(MsgBuffer, MaxMsgSize);
  531. FillChar(MsgBuffer^, MaxMsgSize, #0);
  532. FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM,
  533. nil,
  534. ErrorCode,
  535. MakeLangId(LANG_NEUTRAL, SUBLANG_DEFAULT),
  536. MsgBuffer, { This function allocs the memory }
  537. MaxMsgSize, { Maximum message size }
  538. nil);
  539. SysErrorMessage := StrPas(MsgBuffer);
  540. FreeMem(MsgBuffer, MaxMsgSize);
  541. end;
  542. {****************************************************************************
  543. Initialization code
  544. ****************************************************************************}
  545. Function GetEnvironmentVariable(Const EnvVar : String) : String;
  546. var
  547. s : string;
  548. i : longint;
  549. hp,p : pchar;
  550. begin
  551. Result:='';
  552. p:=GetEnvironmentStrings;
  553. hp:=p;
  554. while hp^<>#0 do
  555. begin
  556. s:=strpas(hp);
  557. i:=pos('=',s);
  558. if uppercase(copy(s,1,i-1))=upcase(envvar) then
  559. begin
  560. Result:=copy(s,i+1,length(s)-i);
  561. break;
  562. end;
  563. { next string entry}
  564. hp:=hp+strlen(hp)+1;
  565. end;
  566. FreeEnvironmentStrings(p);
  567. end;
  568. Function GetEnvironmentVariableCount : Integer;
  569. var
  570. hp,p : pchar;
  571. begin
  572. Result:=0;
  573. p:=GetEnvironmentStrings;
  574. hp:=p;
  575. If (Hp<>Nil) then
  576. while hp^<>#0 do
  577. begin
  578. Inc(Result);
  579. hp:=hp+strlen(hp)+1;
  580. end;
  581. FreeEnvironmentStrings(p);
  582. end;
  583. Function GetEnvironmentString(Index : Integer) : String;
  584. var
  585. hp,p : pchar;
  586. begin
  587. Result:='';
  588. p:=GetEnvironmentStrings;
  589. hp:=p;
  590. If (Hp<>Nil) then
  591. begin
  592. while (hp^<>#0) and (Index>1) do
  593. begin
  594. Dec(Index);
  595. hp:=hp+strlen(hp)+1;
  596. end;
  597. If (hp^<>#0) then
  598. Result:=StrPas(HP);
  599. end;
  600. FreeEnvironmentStrings(p);
  601. end;
  602. function ExecuteProcess(Const Path: AnsiString; Const ComLine: AnsiString):integer;
  603. var
  604. SI: TStartupInfo;
  605. PI: TProcessInformation;
  606. Proc : TWin32Handle;
  607. l : DWord;
  608. CommandLine : ansistring;
  609. e : EOSError;
  610. begin
  611. DosError := 0;
  612. FillChar(SI, SizeOf(SI), 0);
  613. SI.cb:=SizeOf(SI);
  614. SI.wShowWindow:=1;
  615. { always surround the name of the application by quotes
  616. so that long filenames will always be accepted. But don't
  617. do it if there are already double quotes, since Win32 does not
  618. like double quotes which are duplicated!
  619. }
  620. if pos('"',path)=0 then
  621. CommandLine:='"'+path+'"'
  622. else
  623. CommandLine:=path;
  624. if ComLine <> '' then
  625. CommandLine:=Commandline+' '+ComLine+#0
  626. else
  627. CommandLine := CommandLine + #0;
  628. if not CreateProcess(nil, pchar(CommandLine),
  629. Nil, Nil, ExecInheritsHandles,$20, Nil, Nil, SI, PI) then
  630. begin
  631. e:=EOSError.CreateFmt(SExecuteProcessFailed,[CommandLine,GetLastError]);
  632. e.ErrorCode:=GetLastError;
  633. raise e;
  634. end;
  635. Proc:=PI.hProcess;
  636. CloseHandle(PI.hThread);
  637. if WaitForSingleObject(Proc, dword($ffffffff)) <> $ffffffff then
  638. begin
  639. GetExitCodeProcess(Proc,l);
  640. CloseHandle(Proc);
  641. result:=l;
  642. end
  643. else
  644. begin
  645. e:=EOSError.CreateFmt(SExecuteProcessFailed,[CommandLine,GetLastError]);
  646. e.ErrorCode:=GetLastError;
  647. CloseHandle(Proc);
  648. raise e;
  649. end;
  650. end;
  651. function ExecuteProcess(Const Path: AnsiString; Const ComLine: Array of AnsiString):integer;
  652. Var
  653. CommandLine : AnsiString;
  654. i : Integer;
  655. Begin
  656. Commandline:='';
  657. For i:=0 to high(ComLine) Do
  658. Commandline:=CommandLine+' '+Comline[i];
  659. ExecuteProcess:=ExecuteProcess(Path,CommandLine);
  660. End;
  661. Procedure Sleep(Milliseconds : Cardinal);
  662. begin
  663. Windows.Sleep(MilliSeconds)
  664. end;
  665. Function GetLastOSError : Integer;
  666. begin
  667. Result:=GetLastError;
  668. end;
  669. {****************************************************************************
  670. Initialization code
  671. ****************************************************************************}
  672. var
  673. kernel32dll : THandle;
  674. Procedure LoadVersionInfo;
  675. // and getfreespaceex
  676. Var
  677. versioninfo : TOSVERSIONINFO;
  678. i : Integer;
  679. begin
  680. kernel32dll:=0;
  681. GetDiskFreeSpaceEx:=nil;
  682. versioninfo.dwOSVersionInfoSize:=sizeof(versioninfo);
  683. GetVersionEx(versioninfo);
  684. Win32Platform:=versionInfo.dwPlatformId;
  685. Win32MajorVersion:=versionInfo.dwMajorVersion;
  686. Win32MinorVersion:=versionInfo.dwMinorVersion;
  687. Win32BuildNumber:=versionInfo.dwBuildNumber;
  688. Move (versioninfo.szCSDVersion ,Win32CSDVersion[1],128);
  689. win32CSDVersion[0]:=chr(strlen(pchar(@versioninfo.szCSDVersion)));
  690. if ((versioninfo.dwPlatformId=VER_PLATFORM_WIN32_WINDOWS) and
  691. (versioninfo.dwBuildNUmber>=1000)) or
  692. (versioninfo.dwPlatformId=VER_PLATFORM_WIN32_NT) then
  693. begin
  694. kernel32dll:=LoadLibrary('kernel32');
  695. if kernel32dll<>0 then
  696. {$IFDEF VIRTUALPASCAL}
  697. @GetDiskFreeSpaceEx:=GetProcAddress(0,'GetDiskFreeSpaceExA');
  698. {$ELSE}
  699. GetDiskFreeSpaceEx:=TGetDiskFreeSpaceEx(GetProcAddress(kernel32dll,'GetDiskFreeSpaceExA'));
  700. {$ENDIF}
  701. end;
  702. end;
  703. function FreeLibrary(hLibModule : THANDLE) : longbool;
  704. stdcall;external 'kernel32' name 'FreeLibrary';
  705. function GetVersionEx(var VersionInformation:TOSVERSIONINFO) : longbool;
  706. stdcall;external 'kernel32' name 'GetVersionExA';
  707. function LoadLibrary(lpLibFileName : pchar):THandle;
  708. stdcall;external 'kernel32' name 'LoadLibraryA';
  709. function GetProcAddress(hModule : THandle;lpProcName : pchar) : pointer;
  710. stdcall;external 'kernel32' name 'GetProcAddress';
  711. Const
  712. CSIDL_PROGRAMS = $0002; { %SYSTEMDRIVE%\Program Files }
  713. CSIDL_PERSONAL = $0005; { %USERPROFILE%\My Documents }
  714. CSIDL_FAVORITES = $0006; { %USERPROFILE%\Favorites }
  715. CSIDL_STARTUP = $0007; { %USERPROFILE%\Start menu\Programs\Startup }
  716. CSIDL_RECENT = $0008; { %USERPROFILE%\Recent }
  717. CSIDL_SENDTO = $0009; { %USERPROFILE%\Sendto }
  718. CSIDL_STARTMENU = $000B; { %USERPROFILE%\Start menu }
  719. CSIDL_MYMUSIC = $000D; { %USERPROFILE%\Documents\My Music }
  720. CSIDL_MYVIDEO = $000E; { %USERPROFILE%\Documents\My Videos }
  721. CSIDL_DESKTOPDIRECTORY = $0010; { %USERPROFILE%\Desktop }
  722. CSIDL_NETHOOD = $0013; { %USERPROFILE%\NetHood }
  723. CSIDL_TEMPLATES = $0015; { %USERPROFILE%\Templates }
  724. CSIDL_COMMON_STARTMENU = $0016; { %PROFILEPATH%\All users\Start menu }
  725. CSIDL_COMMON_PROGRAMS = $0017; { %PROFILEPATH%\All users\Start menu\Programs }
  726. CSIDL_COMMON_STARTUP = $0018; { %PROFILEPATH%\All users\Start menu\Programs\Startup }
  727. CSIDL_COMMON_DESKTOPDIRECTORY = $0019; { %PROFILEPATH%\All users\Desktop }
  728. CSIDL_APPDATA = $001A; { %USERPROFILE%\Application Data (roaming) }
  729. CSIDL_PRINTHOOD = $001B; { %USERPROFILE%\Printhood }
  730. CSIDL_LOCAL_APPDATA = $001C; { %USERPROFILE%\Local Settings\Application Data (non roaming) }
  731. CSIDL_COMMON_FAVORITES = $001F; { %PROFILEPATH%\All users\Favorites }
  732. CSIDL_INTERNET_CACHE = $0020; { %USERPROFILE%\Local Settings\Temporary Internet Files }
  733. CSIDL_COOKIES = $0021; { %USERPROFILE%\Cookies }
  734. CSIDL_HISTORY = $0022; { %USERPROFILE%\Local settings\History }
  735. CSIDL_COMMON_APPDATA = $0023; { %PROFILESPATH%\All Users\Application Data }
  736. CSIDL_WINDOWS = $0024; { %SYSTEMROOT% }
  737. CSIDL_SYSTEM = $0025; { %SYSTEMROOT%\SYSTEM32 (may be system on 95/98/ME) }
  738. CSIDL_PROGRAM_FILES = $0026; { %SYSTEMDRIVE%\Program Files }
  739. CSIDL_MYPICTURES = $0027; { %USERPROFILE%\My Documents\My Pictures }
  740. CSIDL_PROFILE = $0028; { %USERPROFILE% }
  741. CSIDL_PROGRAM_FILES_COMMON = $002B; { %SYSTEMDRIVE%\Program Files\Common }
  742. CSIDL_COMMON_TEMPLATES = $002D; { %PROFILEPATH%\All Users\Templates }
  743. CSIDL_COMMON_DOCUMENTS = $002E; { %PROFILEPATH%\All Users\Documents }
  744. CSIDL_COMMON_ADMINTOOLS = $002F; { %PROFILEPATH%\All Users\Start Menu\Programs\Administrative Tools }
  745. CSIDL_ADMINTOOLS = $0030; { %USERPROFILE%\Start Menu\Programs\Administrative Tools }
  746. CSIDL_COMMON_MUSIC = $0035; { %PROFILEPATH%\All Users\Documents\my music }
  747. CSIDL_COMMON_PICTURES = $0036; { %PROFILEPATH%\All Users\Documents\my pictures }
  748. CSIDL_COMMON_VIDEO = $0037; { %PROFILEPATH%\All Users\Documents\my videos }
  749. CSIDL_CDBURN_AREA = $003B; { %USERPROFILE%\Local Settings\Application Data\Microsoft\CD Burning }
  750. CSIDL_PROFILES = $003E; { %PROFILEPATH% }
  751. CSIDL_FLAG_CREATE = $8000; { (force creation of requested folder if it doesn't exist yet) }
  752. Type
  753. PFNSHGetFolderPath = Function(Ahwnd: HWND; Csidl: Integer; Token: THandle; Flags: DWord; Path: PChar): HRESULT; stdcall;
  754. {$ifdef VER1_0}
  755. Const
  756. {$else}
  757. var
  758. {$endif}
  759. SHGetFolderPath : PFNSHGetFolderPath = Nil;
  760. CFGDLLHandle : THandle = 0;
  761. Procedure InitDLL;
  762. Var
  763. P : Pointer;
  764. begin
  765. CFGDLLHandle:=LoadLibrary('shell32.dll');
  766. if (CFGDLLHandle<>0) then
  767. begin
  768. P:=GetProcAddress(CFGDLLHandle,'SHGetFolderPathA');
  769. If (P=Nil) then
  770. begin
  771. FreeLibrary(CFGDLLHandle);
  772. CFGDllHandle:=0;
  773. end
  774. else
  775. SHGetFolderPath:=PFNSHGetFolderPath(P);
  776. end;
  777. If (P=Nil) then
  778. begin
  779. CFGDLLHandle:=LoadLibrary('shfolder.dll');
  780. if (CFGDLLHandle<>0) then
  781. begin
  782. P:=GetProcAddress(CFGDLLHandle,'SHGetFolderPathA');
  783. If (P=Nil) then
  784. begin
  785. FreeLibrary(CFGDLLHandle);
  786. CFGDllHandle:=0;
  787. end
  788. else
  789. ShGetFolderPath:=PFNSHGetFolderPath(P);
  790. end;
  791. end;
  792. If (@ShGetFolderPath=Nil) then
  793. Raise Exception.Create('Could not determine SHGetFolderPath Function');
  794. end;
  795. Function GetSpecialDir(ID : Integer) : String;
  796. Var
  797. APath : Array[0..MAX_PATH] of char;
  798. begin
  799. Result:='';
  800. if (CFGDLLHandle=0) then
  801. InitDLL;
  802. If (SHGetFolderPath<>Nil) then
  803. begin
  804. if SHGetFolderPath(0,ID or CSIDL_FLAG_CREATE,0,0,@APATH[0])=S_OK then
  805. Result:=IncludeTrailingPathDelimiter(StrPas(@APath[0]));
  806. end;
  807. end;
  808. Function GetAppConfigDir(Global : Boolean) : String;
  809. begin
  810. If Global then
  811. Result:=DGetAppConfigDir(Global) // or use windows dir ??
  812. else
  813. begin
  814. Result:=GetSpecialDir(CSIDL_LOCAL_APPDATA)+ApplicationName;
  815. If (Result='') then
  816. Result:=DGetAppConfigDir(Global);
  817. end;
  818. end;
  819. Function GetAppConfigFile(Global : Boolean; SubDir : Boolean) : String;
  820. begin
  821. if Global then
  822. begin
  823. Result:=IncludeTrailingPathDelimiter(DGetAppConfigDir(Global));
  824. if SubDir then
  825. Result:=IncludeTrailingPathDelimiter(Result+'Config');
  826. Result:=Result+ApplicationName+ConfigExtension;
  827. end
  828. else
  829. begin
  830. Result:=IncludeTrailingPathDelimiter(GetAppConfigDir(False));
  831. if SubDir then
  832. Result:=Result+'Config\';
  833. Result:=Result+ApplicationName+ConfigExtension;
  834. end;
  835. end;
  836. Procedure InitSysConfigDir;
  837. begin
  838. SetLength(SysConfigDir, MAX_PATH);
  839. SetLength(SysConfigDir, GetWindowsDirectory(PChar(SysConfigDir), MAX_PATH));
  840. end;
  841. Initialization
  842. InitExceptions; { Initialize exceptions. OS independent }
  843. InitInternational; { Initialize internationalization settings }
  844. LoadVersionInfo;
  845. InitSysConfigDir;
  846. Finalization
  847. DoneExceptions;
  848. if kernel32dll<>0 then
  849. FreeLibrary(kernel32dll);
  850. if CFGDLLHandle<>0 then
  851. FreeLibrary(CFGDllHandle);
  852. end.
  853. {
  854. $Log$
  855. Revision 1.39 2004-12-11 11:48:38 michael
  856. + Some fixes in new envvar function
  857. Revision 1.38 2004/12/11 11:32:44 michael
  858. + Added GetEnvironmentVariableCount and GetEnvironmentString calls
  859. Revision 1.37 2004/08/06 13:23:21 michael
  860. + Ver 1.0 does not handle initialized variables well
  861. Revision 1.36 2004/08/05 12:55:29 michael
  862. + initialized SysConfigDir
  863. Revision 1.35 2004/08/05 07:28:37 michael
  864. Added getappconfig calls
  865. Revision 1.34 2004/06/13 10:49:50 florian
  866. * fixed some bootstrapping problems as well as some 64 bit stuff
  867. Revision 1.33 2004/02/13 10:50:23 marco
  868. * Hopefully last large changes to fpexec and friends.
  869. - naming conventions changes from Michael.
  870. - shell functions get alternative under ifdef.
  871. - arraystring function moves to unixutil
  872. - unixutil now regards quotes in stringtoppchar.
  873. - sysutils/unix get executeprocess(ansi,array of ansi), and
  874. both executeprocess functions are fixed
  875. - Sysutils/win32 get executeprocess(ansi,array of ansi)
  876. Revision 1.32 2004/02/08 11:00:18 michael
  877. + Implemented winsysut unit
  878. Revision 1.31 2004/01/20 23:12:49 hajny
  879. * ExecuteProcess fixes, ProcessID and ThreadID added
  880. Revision 1.30 2004/01/16 20:53:33 michael
  881. + DirectoryExists now closes findfirst handle
  882. Revision 1.29 2004/01/10 17:40:25 michael
  883. + Added Sleep() function
  884. Revision 1.28 2004/01/05 22:56:08 florian
  885. * changed sysutils.exec to ExecuteProcess
  886. Revision 1.27 2003/11/26 20:00:19 florian
  887. * error handling for Variants improved
  888. Revision 1.26 2003/11/06 22:25:10 marco
  889. * added some more of win32* delphi pseudo constants
  890. Revision 1.25 2003/10/25 23:44:33 hajny
  891. * THandle in sysutils common using System.THandle
  892. Revision 1.24 2003/09/17 15:06:36 peter
  893. * stdcall patch
  894. Revision 1.23 2003/09/06 22:23:35 marco
  895. * VP fixes.
  896. Revision 1.22 2003/04/01 15:57:41 peter
  897. * made THandle platform dependent and unique type
  898. Revision 1.21 2003/03/29 18:21:42 hajny
  899. * DirectoryExists declaration changed to that one from fixes branch
  900. Revision 1.20 2003/03/28 19:06:59 peter
  901. * directoryexists added
  902. Revision 1.19 2003/01/03 20:41:04 peter
  903. * FileCreate(string,mode) overload added
  904. Revision 1.18 2003/01/01 20:56:57 florian
  905. + added invalid instruction exception
  906. Revision 1.17 2002/12/15 20:24:17 peter
  907. * some more C style functions
  908. Revision 1.16 2002/10/02 21:17:03 florian
  909. * we've to reimport TSystemTime time from the windows unit
  910. Revision 1.15 2002/09/07 16:01:29 peter
  911. * old logs removed and tabs fixed
  912. Revision 1.14 2002/05/09 08:28:23 carl
  913. * Merges from Fixes branch
  914. Revision 1.13 2002/03/24 19:26:49 marco
  915. * Added win32platform
  916. Revision 1.12 2002/01/25 16:23:04 peter
  917. * merged filesearch() fix
  918. }