sysutils.pp 31 KB

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