sysutils.pp 34 KB

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