sysutils.pp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155
  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) : Longint;
  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) : Longint;
  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) : SizeInt;
  126. begin
  127. FileCreate:=FileCreate(FileName);
  128. end;
  129. Function FileRead (Handle : Longint; 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 : Longint; 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,FOffset,Origin : Longint) : Longint;
  148. begin
  149. Result := longint(SetFilePointer(Handle, FOffset, nil, Origin));
  150. end;
  151. Function FileSeek (Handle : Longint; 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 : Longint);
  157. begin
  158. if Handle<=4 then
  159. exit;
  160. CloseHandle(Handle);
  161. end;
  162. Function FileTruncate (Handle,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 : Longint) : 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,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 : TWin32Handle;
  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. CloseHandle(PI.hThread);
  654. if WaitForSingleObject(Proc, dword($ffffffff)) <> $ffffffff then
  655. begin
  656. GetExitCodeProcess(Proc,l);
  657. CloseHandle(Proc);
  658. result:=l;
  659. end
  660. else
  661. begin
  662. e:=EOSError.CreateFmt(SExecuteProcessFailed,[CommandLine,GetLastError]);
  663. e.ErrorCode:=GetLastError;
  664. CloseHandle(Proc);
  665. raise e;
  666. end;
  667. end;
  668. function ExecuteProcess(Const Path: AnsiString; Const ComLine: Array of AnsiString):integer;
  669. Var
  670. CommandLine : AnsiString;
  671. i : Integer;
  672. Begin
  673. Commandline:='';
  674. For i:=0 to high(ComLine) Do
  675. Commandline:=CommandLine+' '+Comline[i];
  676. ExecuteProcess:=ExecuteProcess(Path,CommandLine);
  677. End;
  678. Procedure Sleep(Milliseconds : Cardinal);
  679. begin
  680. Windows.Sleep(MilliSeconds)
  681. end;
  682. Function GetLastOSError : Integer;
  683. begin
  684. Result:=GetLastError;
  685. end;
  686. {****************************************************************************
  687. Initialization code
  688. ****************************************************************************}
  689. var
  690. kernel32dll : THandle;
  691. Procedure LoadVersionInfo;
  692. // and getfreespaceex
  693. Var
  694. versioninfo : TOSVERSIONINFO;
  695. i : Integer;
  696. begin
  697. kernel32dll:=0;
  698. GetDiskFreeSpaceEx:=nil;
  699. versioninfo.dwOSVersionInfoSize:=sizeof(versioninfo);
  700. GetVersionEx(versioninfo);
  701. Win32Platform:=versionInfo.dwPlatformId;
  702. Win32MajorVersion:=versionInfo.dwMajorVersion;
  703. Win32MinorVersion:=versionInfo.dwMinorVersion;
  704. Win32BuildNumber:=versionInfo.dwBuildNumber;
  705. Move (versioninfo.szCSDVersion ,Win32CSDVersion[1],128);
  706. win32CSDVersion[0]:=chr(strlen(pchar(@versioninfo.szCSDVersion)));
  707. if ((versioninfo.dwPlatformId=VER_PLATFORM_WIN32_WINDOWS) and
  708. (versioninfo.dwBuildNUmber>=1000)) or
  709. (versioninfo.dwPlatformId=VER_PLATFORM_WIN32_NT) then
  710. begin
  711. kernel32dll:=LoadLibrary('kernel32');
  712. if kernel32dll<>0 then
  713. GetDiskFreeSpaceEx:=TGetDiskFreeSpaceEx(GetProcAddress(kernel32dll,'GetDiskFreeSpaceExA'));
  714. end;
  715. end;
  716. function FreeLibrary(hLibModule : THANDLE) : longbool;
  717. stdcall;external 'kernel32' name 'FreeLibrary';
  718. function GetVersionEx(var VersionInformation:TOSVERSIONINFO) : longbool;
  719. stdcall;external 'kernel32' name 'GetVersionExA';
  720. function LoadLibrary(lpLibFileName : pchar):THandle;
  721. stdcall;external 'kernel32' name 'LoadLibraryA';
  722. function GetProcAddress(hModule : THandle;lpProcName : pchar) : pointer;
  723. stdcall;external 'kernel32' name 'GetProcAddress';
  724. Const
  725. CSIDL_PROGRAMS = $0002; { %SYSTEMDRIVE%\Program Files }
  726. CSIDL_PERSONAL = $0005; { %USERPROFILE%\My Documents }
  727. CSIDL_FAVORITES = $0006; { %USERPROFILE%\Favorites }
  728. CSIDL_STARTUP = $0007; { %USERPROFILE%\Start menu\Programs\Startup }
  729. CSIDL_RECENT = $0008; { %USERPROFILE%\Recent }
  730. CSIDL_SENDTO = $0009; { %USERPROFILE%\Sendto }
  731. CSIDL_STARTMENU = $000B; { %USERPROFILE%\Start menu }
  732. CSIDL_MYMUSIC = $000D; { %USERPROFILE%\Documents\My Music }
  733. CSIDL_MYVIDEO = $000E; { %USERPROFILE%\Documents\My Videos }
  734. CSIDL_DESKTOPDIRECTORY = $0010; { %USERPROFILE%\Desktop }
  735. CSIDL_NETHOOD = $0013; { %USERPROFILE%\NetHood }
  736. CSIDL_TEMPLATES = $0015; { %USERPROFILE%\Templates }
  737. CSIDL_COMMON_STARTMENU = $0016; { %PROFILEPATH%\All users\Start menu }
  738. CSIDL_COMMON_PROGRAMS = $0017; { %PROFILEPATH%\All users\Start menu\Programs }
  739. CSIDL_COMMON_STARTUP = $0018; { %PROFILEPATH%\All users\Start menu\Programs\Startup }
  740. CSIDL_COMMON_DESKTOPDIRECTORY = $0019; { %PROFILEPATH%\All users\Desktop }
  741. CSIDL_APPDATA = $001A; { %USERPROFILE%\Application Data (roaming) }
  742. CSIDL_PRINTHOOD = $001B; { %USERPROFILE%\Printhood }
  743. CSIDL_LOCAL_APPDATA = $001C; { %USERPROFILE%\Local Settings\Application Data (non roaming) }
  744. CSIDL_COMMON_FAVORITES = $001F; { %PROFILEPATH%\All users\Favorites }
  745. CSIDL_INTERNET_CACHE = $0020; { %USERPROFILE%\Local Settings\Temporary Internet Files }
  746. CSIDL_COOKIES = $0021; { %USERPROFILE%\Cookies }
  747. CSIDL_HISTORY = $0022; { %USERPROFILE%\Local settings\History }
  748. CSIDL_COMMON_APPDATA = $0023; { %PROFILESPATH%\All Users\Application Data }
  749. CSIDL_WINDOWS = $0024; { %SYSTEMROOT% }
  750. CSIDL_SYSTEM = $0025; { %SYSTEMROOT%\SYSTEM32 (may be system on 95/98/ME) }
  751. CSIDL_PROGRAM_FILES = $0026; { %SYSTEMDRIVE%\Program Files }
  752. CSIDL_MYPICTURES = $0027; { %USERPROFILE%\My Documents\My Pictures }
  753. CSIDL_PROFILE = $0028; { %USERPROFILE% }
  754. CSIDL_PROGRAM_FILES_COMMON = $002B; { %SYSTEMDRIVE%\Program Files\Common }
  755. CSIDL_COMMON_TEMPLATES = $002D; { %PROFILEPATH%\All Users\Templates }
  756. CSIDL_COMMON_DOCUMENTS = $002E; { %PROFILEPATH%\All Users\Documents }
  757. CSIDL_COMMON_ADMINTOOLS = $002F; { %PROFILEPATH%\All Users\Start Menu\Programs\Administrative Tools }
  758. CSIDL_ADMINTOOLS = $0030; { %USERPROFILE%\Start Menu\Programs\Administrative Tools }
  759. CSIDL_COMMON_MUSIC = $0035; { %PROFILEPATH%\All Users\Documents\my music }
  760. CSIDL_COMMON_PICTURES = $0036; { %PROFILEPATH%\All Users\Documents\my pictures }
  761. CSIDL_COMMON_VIDEO = $0037; { %PROFILEPATH%\All Users\Documents\my videos }
  762. CSIDL_CDBURN_AREA = $003B; { %USERPROFILE%\Local Settings\Application Data\Microsoft\CD Burning }
  763. CSIDL_PROFILES = $003E; { %PROFILEPATH% }
  764. CSIDL_FLAG_CREATE = $8000; { (force creation of requested folder if it doesn't exist yet) }
  765. Type
  766. PFNSHGetFolderPath = Function(Ahwnd: HWND; Csidl: Integer; Token: THandle; Flags: DWord; Path: PChar): HRESULT; stdcall;
  767. var
  768. SHGetFolderPath : PFNSHGetFolderPath = Nil;
  769. CFGDLLHandle : THandle = 0;
  770. Procedure InitDLL;
  771. Var
  772. P : Pointer;
  773. begin
  774. CFGDLLHandle:=LoadLibrary('shell32.dll');
  775. if (CFGDLLHandle<>0) then
  776. begin
  777. P:=GetProcAddress(CFGDLLHandle,'SHGetFolderPathA');
  778. If (P=Nil) then
  779. begin
  780. FreeLibrary(CFGDLLHandle);
  781. CFGDllHandle:=0;
  782. end
  783. else
  784. SHGetFolderPath:=PFNSHGetFolderPath(P);
  785. end;
  786. If (P=Nil) then
  787. begin
  788. CFGDLLHandle:=LoadLibrary('shfolder.dll');
  789. if (CFGDLLHandle<>0) then
  790. begin
  791. P:=GetProcAddress(CFGDLLHandle,'SHGetFolderPathA');
  792. If (P=Nil) then
  793. begin
  794. FreeLibrary(CFGDLLHandle);
  795. CFGDllHandle:=0;
  796. end
  797. else
  798. ShGetFolderPath:=PFNSHGetFolderPath(P);
  799. end;
  800. end;
  801. If (@ShGetFolderPath=Nil) then
  802. Raise Exception.Create('Could not determine SHGetFolderPath Function');
  803. end;
  804. Function GetSpecialDir(ID : Integer) : String;
  805. Var
  806. APath : Array[0..MAX_PATH] of char;
  807. begin
  808. Result:='';
  809. if (CFGDLLHandle=0) then
  810. InitDLL;
  811. If (SHGetFolderPath<>Nil) then
  812. begin
  813. if SHGetFolderPath(0,ID or CSIDL_FLAG_CREATE,0,0,@APATH[0])=S_OK then
  814. Result:=IncludeTrailingPathDelimiter(StrPas(@APath[0]));
  815. end;
  816. end;
  817. Function GetAppConfigDir(Global : Boolean) : String;
  818. begin
  819. If Global then
  820. Result:=DGetAppConfigDir(Global) // or use windows dir ??
  821. else
  822. begin
  823. Result:=GetSpecialDir(CSIDL_LOCAL_APPDATA)+ApplicationName;
  824. If (Result='') then
  825. Result:=DGetAppConfigDir(Global);
  826. end;
  827. end;
  828. Function GetAppConfigFile(Global : Boolean; SubDir : Boolean) : String;
  829. begin
  830. if Global then
  831. begin
  832. Result:=IncludeTrailingPathDelimiter(DGetAppConfigDir(Global));
  833. if SubDir then
  834. Result:=IncludeTrailingPathDelimiter(Result+'Config');
  835. Result:=Result+ApplicationName+ConfigExtension;
  836. end
  837. else
  838. begin
  839. Result:=IncludeTrailingPathDelimiter(GetAppConfigDir(False));
  840. if SubDir then
  841. Result:=Result+'Config\';
  842. Result:=Result+ApplicationName+ConfigExtension;
  843. end;
  844. end;
  845. Procedure InitSysConfigDir;
  846. begin
  847. SetLength(SysConfigDir, MAX_PATH);
  848. SetLength(SysConfigDir, GetWindowsDirectory(PChar(SysConfigDir), MAX_PATH));
  849. end;
  850. {****************************************************************************
  851. Target Dependent WideString stuff
  852. ****************************************************************************}
  853. function Win32CompareWideString(const s1, s2 : WideString) : PtrInt;
  854. begin
  855. SetLastError(0);
  856. Result:=CompareStringW(LOCALE_USER_DEFAULT,0,pwidechar(s1),
  857. length(s1),pwidechar(s2),length(s2))-2;
  858. if GetLastError<>0 then
  859. RaiseLastOSError;
  860. end;
  861. function Win32CompareTextWideString(const s1, s2 : WideString) : PtrInt;
  862. begin
  863. SetLastError(0);
  864. Result:=CompareStringW(LOCALE_USER_DEFAULT,NORM_IGNORECASE,pwidechar(s1),
  865. length(s1),pwidechar(s2),length(s2))-2;
  866. if GetLastError<>0 then
  867. RaiseLastOSError;
  868. end;
  869. function Win32AnsiUpperCase(const s: string): string;
  870. begin
  871. if length(s)>0 then
  872. begin
  873. result:=s;
  874. UniqueString(result);
  875. CharUpperBuff(pchar(result),length(result));
  876. end
  877. else
  878. result:='';
  879. end;
  880. function Win32AnsiLowerCase(const s: string): string;
  881. begin
  882. if length(s)>0 then
  883. begin
  884. result:=s;
  885. UniqueString(result);
  886. CharLowerBuff(pchar(result),length(result));
  887. end
  888. else
  889. result:='';
  890. end;
  891. function Win32AnsiCompareStr(const S1, S2: string): PtrInt;
  892. begin
  893. result:=CompareString(LOCALE_USER_DEFAULT,0,pchar(s1),length(s1),
  894. pchar(s2),length(s2))-2;
  895. end;
  896. function Win32AnsiCompareText(const S1, S2: string): PtrInt;
  897. begin
  898. result:=CompareString(LOCALE_USER_DEFAULT,NORM_IGNORECASE,pchar(s1),length(s1),
  899. pchar(s2),length(s2))-2;
  900. end;
  901. function Win32AnsiStrComp(S1, S2: PChar): PtrInt;
  902. begin
  903. result:=CompareString(LOCALE_USER_DEFAULT,0,s1,-1,s2,-1)-2;
  904. end;
  905. function Win32AnsiStrIComp(S1, S2: PChar): PtrInt;
  906. begin
  907. result:=CompareString(LOCALE_USER_DEFAULT,NORM_IGNORECASE,s1,-1,s2,-1)-2;
  908. end;
  909. function Win32AnsiStrLComp(S1, S2: PChar; MaxLen: PtrUInt): PtrInt;
  910. begin
  911. result:=CompareString(LOCALE_USER_DEFAULT,0,s1,maxlen,s2,maxlen)-2;
  912. end;
  913. function Win32AnsiStrLIComp(S1, S2: PChar; MaxLen: PtrUInt): PtrInt;
  914. begin
  915. result:=CompareString(LOCALE_USER_DEFAULT,NORM_IGNORECASE,s1,maxlen,s2,maxlen)-2;
  916. end;
  917. function Win32AnsiStrLower(Str: PChar): PChar;
  918. begin
  919. CharLower(str);
  920. result:=str;
  921. end;
  922. function Win32AnsiStrUpper(Str: PChar): PChar;
  923. begin
  924. CharUpper(str);
  925. result:=str;
  926. end;
  927. { there is a similiar procedure in the system unit which inits the fields which
  928. are relevant already for the system unit }
  929. procedure InitWin32Widestrings;
  930. begin
  931. widestringmanager.CompareWideStringProc:=@Win32CompareWideString;
  932. widestringmanager.CompareTextWideStringProc:=@Win32CompareTextWideString;
  933. widestringmanager.UpperAnsiStringProc:=@Win32AnsiUpperCase;
  934. widestringmanager.LowerAnsiStringProc:=@Win32AnsiLowerCase;
  935. widestringmanager.CompareStrAnsiStringProc:=@Win32AnsiCompareStr;
  936. widestringmanager.CompareTextAnsiStringProc:=@Win32AnsiCompareText;
  937. widestringmanager.StrCompAnsiStringProc:=@Win32AnsiStrComp;
  938. widestringmanager.StrICompAnsiStringProc:=@Win32AnsiStrIComp;
  939. widestringmanager.StrLCompAnsiStringProc:=@Win32AnsiStrLComp;
  940. widestringmanager.StrLICompAnsiStringProc:=@Win32AnsiStrLIComp;
  941. widestringmanager.StrLowerAnsiStringProc:=@Win32AnsiStrLower;
  942. widestringmanager.StrUpperAnsiStringProc:=@Win32AnsiStrUpper;
  943. end;
  944. Initialization
  945. InitWin32Widestrings;
  946. InitExceptions; { Initialize exceptions. OS independent }
  947. InitInternational; { Initialize internationalization settings }
  948. LoadVersionInfo;
  949. InitSysConfigDir;
  950. Finalization
  951. DoneExceptions;
  952. if kernel32dll<>0 then
  953. FreeLibrary(kernel32dll);
  954. if CFGDLLHandle<>0 then
  955. FreeLibrary(CFGDllHandle);
  956. end.