sysutils.pp 32 KB

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