sysutils.pp 30 KB

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