sysutils.pp 32 KB

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