sysutils.pp 31 KB

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