sysutils.pp 31 KB

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