sysutils.pp 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051
  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. InitInternationalGeneric;
  512. SysLocale.MBCS:=GetSystemMetrics(SM_DBCSENABLED)<>0;
  513. SysLocale.RightToLeft:=GetSystemMetrics(SM_MIDEASTENABLED)<>0;
  514. InitAnsi;
  515. GetFormatSettings;
  516. end;
  517. {****************************************************************************
  518. Target Dependent
  519. ****************************************************************************}
  520. function FormatMessageA(dwFlags : DWORD;
  521. lpSource : Pointer;
  522. dwMessageId : DWORD;
  523. dwLanguageId: DWORD;
  524. lpBuffer : PCHAR;
  525. nSize : DWORD;
  526. Arguments : Pointer): DWORD; stdcall;external 'kernel32' name 'FormatMessageA';
  527. function SysErrorMessage(ErrorCode: Integer): String;
  528. const
  529. MaxMsgSize = Format_Message_Max_Width_Mask;
  530. var
  531. MsgBuffer: pChar;
  532. begin
  533. GetMem(MsgBuffer, MaxMsgSize);
  534. FillChar(MsgBuffer^, MaxMsgSize, #0);
  535. FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM,
  536. nil,
  537. ErrorCode,
  538. MakeLangId(LANG_NEUTRAL, SUBLANG_DEFAULT),
  539. MsgBuffer, { This function allocs the memory }
  540. MaxMsgSize, { Maximum message size }
  541. nil);
  542. SysErrorMessage := StrPas(MsgBuffer);
  543. FreeMem(MsgBuffer, MaxMsgSize);
  544. end;
  545. {****************************************************************************
  546. Initialization code
  547. ****************************************************************************}
  548. Function GetEnvironmentVariable(Const EnvVar : String) : String;
  549. var
  550. s : string;
  551. i : longint;
  552. hp,p : pchar;
  553. begin
  554. Result:='';
  555. p:=GetEnvironmentStrings;
  556. hp:=p;
  557. while hp^<>#0 do
  558. begin
  559. s:=strpas(hp);
  560. i:=pos('=',s);
  561. if uppercase(copy(s,1,i-1))=upcase(envvar) then
  562. begin
  563. Result:=copy(s,i+1,length(s)-i);
  564. break;
  565. end;
  566. { next string entry}
  567. hp:=hp+strlen(hp)+1;
  568. end;
  569. FreeEnvironmentStrings(p);
  570. end;
  571. Function GetEnvironmentVariableCount : Integer;
  572. var
  573. hp,p : pchar;
  574. begin
  575. Result:=0;
  576. p:=GetEnvironmentStrings;
  577. hp:=p;
  578. If (Hp<>Nil) then
  579. while hp^<>#0 do
  580. begin
  581. Inc(Result);
  582. hp:=hp+strlen(hp)+1;
  583. end;
  584. FreeEnvironmentStrings(p);
  585. end;
  586. Function GetEnvironmentString(Index : Integer) : String;
  587. var
  588. hp,p : pchar;
  589. begin
  590. Result:='';
  591. p:=GetEnvironmentStrings;
  592. hp:=p;
  593. If (Hp<>Nil) then
  594. begin
  595. while (hp^<>#0) and (Index>1) do
  596. begin
  597. Dec(Index);
  598. hp:=hp+strlen(hp)+1;
  599. end;
  600. If (hp^<>#0) then
  601. Result:=StrPas(HP);
  602. end;
  603. FreeEnvironmentStrings(p);
  604. end;
  605. function ExecuteProcess(Const Path: AnsiString; Const ComLine: AnsiString):integer;
  606. var
  607. SI: TStartupInfo;
  608. PI: TProcessInformation;
  609. Proc : TWin32Handle;
  610. l : DWord;
  611. CommandLine : ansistring;
  612. e : EOSError;
  613. begin
  614. DosError := 0;
  615. FillChar(SI, SizeOf(SI), 0);
  616. SI.cb:=SizeOf(SI);
  617. SI.wShowWindow:=1;
  618. { always surround the name of the application by quotes
  619. so that long filenames will always be accepted. But don't
  620. do it if there are already double quotes, since Win32 does not
  621. like double quotes which are duplicated!
  622. }
  623. if pos('"',path)=0 then
  624. CommandLine:='"'+path+'"'
  625. else
  626. CommandLine:=path;
  627. if ComLine <> '' then
  628. CommandLine:=Commandline+' '+ComLine+#0
  629. else
  630. CommandLine := CommandLine + #0;
  631. if not CreateProcess(nil, pchar(CommandLine),
  632. Nil, Nil, ExecInheritsHandles,$20, Nil, Nil, SI, PI) then
  633. begin
  634. e:=EOSError.CreateFmt(SExecuteProcessFailed,[CommandLine,GetLastError]);
  635. e.ErrorCode:=GetLastError;
  636. raise e;
  637. end;
  638. Proc:=PI.hProcess;
  639. CloseHandle(PI.hThread);
  640. if WaitForSingleObject(Proc, dword($ffffffff)) <> $ffffffff then
  641. begin
  642. GetExitCodeProcess(Proc,l);
  643. CloseHandle(Proc);
  644. result:=l;
  645. end
  646. else
  647. begin
  648. e:=EOSError.CreateFmt(SExecuteProcessFailed,[CommandLine,GetLastError]);
  649. e.ErrorCode:=GetLastError;
  650. CloseHandle(Proc);
  651. raise e;
  652. end;
  653. end;
  654. function ExecuteProcess(Const Path: AnsiString; Const ComLine: Array of AnsiString):integer;
  655. Var
  656. CommandLine : AnsiString;
  657. i : Integer;
  658. Begin
  659. Commandline:='';
  660. For i:=0 to high(ComLine) Do
  661. Commandline:=CommandLine+' '+Comline[i];
  662. ExecuteProcess:=ExecuteProcess(Path,CommandLine);
  663. End;
  664. Procedure Sleep(Milliseconds : Cardinal);
  665. begin
  666. Windows.Sleep(MilliSeconds)
  667. end;
  668. Function GetLastOSError : Integer;
  669. begin
  670. Result:=GetLastError;
  671. end;
  672. {****************************************************************************
  673. Initialization code
  674. ****************************************************************************}
  675. var
  676. kernel32dll : THandle;
  677. Procedure LoadVersionInfo;
  678. // and getfreespaceex
  679. Var
  680. versioninfo : TOSVERSIONINFO;
  681. i : Integer;
  682. begin
  683. kernel32dll:=0;
  684. GetDiskFreeSpaceEx:=nil;
  685. versioninfo.dwOSVersionInfoSize:=sizeof(versioninfo);
  686. GetVersionEx(versioninfo);
  687. Win32Platform:=versionInfo.dwPlatformId;
  688. Win32MajorVersion:=versionInfo.dwMajorVersion;
  689. Win32MinorVersion:=versionInfo.dwMinorVersion;
  690. Win32BuildNumber:=versionInfo.dwBuildNumber;
  691. Move (versioninfo.szCSDVersion ,Win32CSDVersion[1],128);
  692. win32CSDVersion[0]:=chr(strlen(pchar(@versioninfo.szCSDVersion)));
  693. if ((versioninfo.dwPlatformId=VER_PLATFORM_WIN32_WINDOWS) and
  694. (versioninfo.dwBuildNUmber>=1000)) or
  695. (versioninfo.dwPlatformId=VER_PLATFORM_WIN32_NT) then
  696. begin
  697. kernel32dll:=LoadLibrary('kernel32');
  698. if kernel32dll<>0 then
  699. {$IFDEF VIRTUALPASCAL}
  700. @GetDiskFreeSpaceEx:=GetProcAddress(0,'GetDiskFreeSpaceExA');
  701. {$ELSE}
  702. GetDiskFreeSpaceEx:=TGetDiskFreeSpaceEx(GetProcAddress(kernel32dll,'GetDiskFreeSpaceExA'));
  703. {$ENDIF}
  704. end;
  705. end;
  706. function FreeLibrary(hLibModule : THANDLE) : longbool;
  707. stdcall;external 'kernel32' name 'FreeLibrary';
  708. function GetVersionEx(var VersionInformation:TOSVERSIONINFO) : longbool;
  709. stdcall;external 'kernel32' name 'GetVersionExA';
  710. function LoadLibrary(lpLibFileName : pchar):THandle;
  711. stdcall;external 'kernel32' name 'LoadLibraryA';
  712. function GetProcAddress(hModule : THandle;lpProcName : pchar) : pointer;
  713. stdcall;external 'kernel32' name 'GetProcAddress';
  714. Const
  715. CSIDL_PROGRAMS = $0002; { %SYSTEMDRIVE%\Program Files }
  716. CSIDL_PERSONAL = $0005; { %USERPROFILE%\My Documents }
  717. CSIDL_FAVORITES = $0006; { %USERPROFILE%\Favorites }
  718. CSIDL_STARTUP = $0007; { %USERPROFILE%\Start menu\Programs\Startup }
  719. CSIDL_RECENT = $0008; { %USERPROFILE%\Recent }
  720. CSIDL_SENDTO = $0009; { %USERPROFILE%\Sendto }
  721. CSIDL_STARTMENU = $000B; { %USERPROFILE%\Start menu }
  722. CSIDL_MYMUSIC = $000D; { %USERPROFILE%\Documents\My Music }
  723. CSIDL_MYVIDEO = $000E; { %USERPROFILE%\Documents\My Videos }
  724. CSIDL_DESKTOPDIRECTORY = $0010; { %USERPROFILE%\Desktop }
  725. CSIDL_NETHOOD = $0013; { %USERPROFILE%\NetHood }
  726. CSIDL_TEMPLATES = $0015; { %USERPROFILE%\Templates }
  727. CSIDL_COMMON_STARTMENU = $0016; { %PROFILEPATH%\All users\Start menu }
  728. CSIDL_COMMON_PROGRAMS = $0017; { %PROFILEPATH%\All users\Start menu\Programs }
  729. CSIDL_COMMON_STARTUP = $0018; { %PROFILEPATH%\All users\Start menu\Programs\Startup }
  730. CSIDL_COMMON_DESKTOPDIRECTORY = $0019; { %PROFILEPATH%\All users\Desktop }
  731. CSIDL_APPDATA = $001A; { %USERPROFILE%\Application Data (roaming) }
  732. CSIDL_PRINTHOOD = $001B; { %USERPROFILE%\Printhood }
  733. CSIDL_LOCAL_APPDATA = $001C; { %USERPROFILE%\Local Settings\Application Data (non roaming) }
  734. CSIDL_COMMON_FAVORITES = $001F; { %PROFILEPATH%\All users\Favorites }
  735. CSIDL_INTERNET_CACHE = $0020; { %USERPROFILE%\Local Settings\Temporary Internet Files }
  736. CSIDL_COOKIES = $0021; { %USERPROFILE%\Cookies }
  737. CSIDL_HISTORY = $0022; { %USERPROFILE%\Local settings\History }
  738. CSIDL_COMMON_APPDATA = $0023; { %PROFILESPATH%\All Users\Application Data }
  739. CSIDL_WINDOWS = $0024; { %SYSTEMROOT% }
  740. CSIDL_SYSTEM = $0025; { %SYSTEMROOT%\SYSTEM32 (may be system on 95/98/ME) }
  741. CSIDL_PROGRAM_FILES = $0026; { %SYSTEMDRIVE%\Program Files }
  742. CSIDL_MYPICTURES = $0027; { %USERPROFILE%\My Documents\My Pictures }
  743. CSIDL_PROFILE = $0028; { %USERPROFILE% }
  744. CSIDL_PROGRAM_FILES_COMMON = $002B; { %SYSTEMDRIVE%\Program Files\Common }
  745. CSIDL_COMMON_TEMPLATES = $002D; { %PROFILEPATH%\All Users\Templates }
  746. CSIDL_COMMON_DOCUMENTS = $002E; { %PROFILEPATH%\All Users\Documents }
  747. CSIDL_COMMON_ADMINTOOLS = $002F; { %PROFILEPATH%\All Users\Start Menu\Programs\Administrative Tools }
  748. CSIDL_ADMINTOOLS = $0030; { %USERPROFILE%\Start Menu\Programs\Administrative Tools }
  749. CSIDL_COMMON_MUSIC = $0035; { %PROFILEPATH%\All Users\Documents\my music }
  750. CSIDL_COMMON_PICTURES = $0036; { %PROFILEPATH%\All Users\Documents\my pictures }
  751. CSIDL_COMMON_VIDEO = $0037; { %PROFILEPATH%\All Users\Documents\my videos }
  752. CSIDL_CDBURN_AREA = $003B; { %USERPROFILE%\Local Settings\Application Data\Microsoft\CD Burning }
  753. CSIDL_PROFILES = $003E; { %PROFILEPATH% }
  754. CSIDL_FLAG_CREATE = $8000; { (force creation of requested folder if it doesn't exist yet) }
  755. Type
  756. PFNSHGetFolderPath = Function(Ahwnd: HWND; Csidl: Integer; Token: THandle; Flags: DWord; Path: PChar): HRESULT; stdcall;
  757. {$ifdef VER1_0}
  758. Const
  759. {$else}
  760. var
  761. {$endif}
  762. SHGetFolderPath : PFNSHGetFolderPath = Nil;
  763. CFGDLLHandle : THandle = 0;
  764. Procedure InitDLL;
  765. Var
  766. P : Pointer;
  767. begin
  768. CFGDLLHandle:=LoadLibrary('shell32.dll');
  769. if (CFGDLLHandle<>0) then
  770. begin
  771. P:=GetProcAddress(CFGDLLHandle,'SHGetFolderPathA');
  772. If (P=Nil) then
  773. begin
  774. FreeLibrary(CFGDLLHandle);
  775. CFGDllHandle:=0;
  776. end
  777. else
  778. SHGetFolderPath:=PFNSHGetFolderPath(P);
  779. end;
  780. If (P=Nil) then
  781. begin
  782. CFGDLLHandle:=LoadLibrary('shfolder.dll');
  783. if (CFGDLLHandle<>0) then
  784. begin
  785. P:=GetProcAddress(CFGDLLHandle,'SHGetFolderPathA');
  786. If (P=Nil) then
  787. begin
  788. FreeLibrary(CFGDLLHandle);
  789. CFGDllHandle:=0;
  790. end
  791. else
  792. ShGetFolderPath:=PFNSHGetFolderPath(P);
  793. end;
  794. end;
  795. If (@ShGetFolderPath=Nil) then
  796. Raise Exception.Create('Could not determine SHGetFolderPath Function');
  797. end;
  798. Function GetSpecialDir(ID : Integer) : String;
  799. Var
  800. APath : Array[0..MAX_PATH] of char;
  801. begin
  802. Result:='';
  803. if (CFGDLLHandle=0) then
  804. InitDLL;
  805. If (SHGetFolderPath<>Nil) then
  806. begin
  807. if SHGetFolderPath(0,ID or CSIDL_FLAG_CREATE,0,0,@APATH[0])=S_OK then
  808. Result:=IncludeTrailingPathDelimiter(StrPas(@APath[0]));
  809. end;
  810. end;
  811. Function GetAppConfigDir(Global : Boolean) : String;
  812. begin
  813. If Global then
  814. Result:=DGetAppConfigDir(Global) // or use windows dir ??
  815. else
  816. begin
  817. Result:=GetSpecialDir(CSIDL_LOCAL_APPDATA)+ApplicationName;
  818. If (Result='') then
  819. Result:=DGetAppConfigDir(Global);
  820. end;
  821. end;
  822. Function GetAppConfigFile(Global : Boolean; SubDir : Boolean) : String;
  823. begin
  824. if Global then
  825. begin
  826. Result:=IncludeTrailingPathDelimiter(DGetAppConfigDir(Global));
  827. if SubDir then
  828. Result:=IncludeTrailingPathDelimiter(Result+'Config');
  829. Result:=Result+ApplicationName+ConfigExtension;
  830. end
  831. else
  832. begin
  833. Result:=IncludeTrailingPathDelimiter(GetAppConfigDir(False));
  834. if SubDir then
  835. Result:=Result+'Config\';
  836. Result:=Result+ApplicationName+ConfigExtension;
  837. end;
  838. end;
  839. Procedure InitSysConfigDir;
  840. begin
  841. SetLength(SysConfigDir, MAX_PATH);
  842. SetLength(SysConfigDir, GetWindowsDirectory(PChar(SysConfigDir), MAX_PATH));
  843. end;
  844. {****************************************************************************
  845. Target Dependent WideString stuff
  846. ****************************************************************************}
  847. function Win32CompareWideString(const s1, s2 : WideString) : PtrInt;
  848. begin
  849. SetLastError(0);
  850. Result:=CompareStringW(LOCALE_USER_DEFAULT,0,pwidechar(s1),
  851. length(s1),pwidechar(s2),length(s2))-2;
  852. if GetLastError<>0 then
  853. RaiseLastOSError;
  854. end;
  855. function Win32CompareTextWideString(const s1, s2 : WideString) : PtrInt;
  856. begin
  857. SetLastError(0);
  858. Result:=CompareStringW(LOCALE_USER_DEFAULT,NORM_IGNORECASE,pwidechar(s1),
  859. length(s1),pwidechar(s2),length(s2))-2;
  860. if GetLastError<>0 then
  861. RaiseLastOSError;
  862. end;
  863. { there is a similiar procedure in the system unit which inits the fields which
  864. are relevant already for the system unit }
  865. procedure InitWin32Widestrings;
  866. begin
  867. widestringmanager.CompareWideStringProc:=@Win32CompareWideString;
  868. widestringmanager.CompareTextWideStringProc:=@Win32CompareTextWideString;
  869. end;
  870. Initialization
  871. InitWin32Widestrings;
  872. InitExceptions; { Initialize exceptions. OS independent }
  873. InitInternational; { Initialize internationalization settings }
  874. LoadVersionInfo;
  875. InitSysConfigDir;
  876. Finalization
  877. DoneExceptions;
  878. if kernel32dll<>0 then
  879. FreeLibrary(kernel32dll);
  880. if CFGDLLHandle<>0 then
  881. FreeLibrary(CFGDllHandle);
  882. end.
  883. {
  884. $Log$
  885. Revision 1.42 2005-02-26 20:43:52 florian
  886. + WideCompareString and WideCompareText for win32 implemented
  887. Revision 1.41 2005/02/26 14:38:14 florian
  888. + SysLocale
  889. Revision 1.40 2005/02/14 17:13:32 peter
  890. * truncate log
  891. }