sysutils.pp 33 KB

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