sysutils.pp 32 KB

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