sysutils.pp 31 KB

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