sysutils.pp 34 KB

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