sysutils.pp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251
  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>Major) or
  69. ((Win32MajorVersion=Major) and (Win32MinorVersion>=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. Procedure InitAnsi;
  496. Var
  497. i : longint;
  498. begin
  499. { Fill table entries 0 to 127 }
  500. for i := 0 to 96 do
  501. UpperCaseTable[i] := chr(i);
  502. for i := 97 to 122 do
  503. UpperCaseTable[i] := chr(i - 32);
  504. for i := 123 to 191 do
  505. UpperCaseTable[i] := chr(i);
  506. Move (CPISO88591UCT,UpperCaseTable[192],SizeOf(CPISO88591UCT));
  507. for i := 0 to 64 do
  508. LowerCaseTable[i] := chr(i);
  509. for i := 65 to 90 do
  510. LowerCaseTable[i] := chr(i + 32);
  511. for i := 91 to 191 do
  512. LowerCaseTable[i] := chr(i);
  513. Move (CPISO88591LCT,UpperCaseTable[192],SizeOf(CPISO88591UCT));
  514. end;
  515. function GetLocaleStr(LID, LT: Longint; const Def: string): ShortString;
  516. var
  517. L: Integer;
  518. Buf: array[0..255] of Char;
  519. begin
  520. L := GetLocaleInfo(LID, LT, Buf, SizeOf(Buf));
  521. if L > 0 then
  522. SetString(Result, @Buf[0], L - 1)
  523. else
  524. Result := Def;
  525. end;
  526. function GetLocaleChar(LID, LT: Longint; Def: Char): Char;
  527. var
  528. Buf: array[0..1] of Char;
  529. begin
  530. if GetLocaleInfo(LID, LT, Buf, 2) > 0 then
  531. Result := Buf[0]
  532. else
  533. Result := Def;
  534. end;
  535. Function GetLocaleInt(LID,TP,Def: LongInt): LongInt;
  536. Var
  537. S: String;
  538. C: Integer;
  539. Begin
  540. S:=GetLocaleStr(LID,TP,'0');
  541. Val(S,Result,C);
  542. If C<>0 Then
  543. Result:=Def;
  544. End;
  545. procedure GetFormatSettings;
  546. var
  547. HF : Shortstring;
  548. LID : LCID;
  549. I,Day : longint;
  550. begin
  551. LID := GetThreadLocale;
  552. { Date stuff }
  553. for I := 1 to 12 do
  554. begin
  555. ShortMonthNames[I]:=GetLocaleStr(LID,LOCALE_SABBREVMONTHNAME1+I-1,ShortMonthNames[i]);
  556. LongMonthNames[I]:=GetLocaleStr(LID,LOCALE_SMONTHNAME1+I-1,LongMonthNames[i]);
  557. end;
  558. for I := 1 to 7 do
  559. begin
  560. Day := (I + 5) mod 7;
  561. ShortDayNames[I]:=GetLocaleStr(LID,LOCALE_SABBREVDAYNAME1+Day,ShortDayNames[i]);
  562. LongDayNames[I]:=GetLocaleStr(LID,LOCALE_SDAYNAME1+Day,LongDayNames[i]);
  563. end;
  564. DateSeparator := GetLocaleChar(LID, LOCALE_SDATE, '/');
  565. ShortDateFormat := GetLocaleStr(LID, LOCALE_SSHORTDATE, 'm/d/yy');
  566. LongDateFormat := GetLocaleStr(LID, LOCALE_SLONGDATE, 'mmmm d, yyyy');
  567. { Time stuff }
  568. TimeSeparator := GetLocaleChar(LID, LOCALE_STIME, ':');
  569. TimeAMString := GetLocaleStr(LID, LOCALE_S1159, 'AM');
  570. TimePMString := GetLocaleStr(LID, LOCALE_S2359, 'PM');
  571. if StrToIntDef(GetLocaleStr(LID, LOCALE_ITLZERO, '0'), 0) = 0 then
  572. HF:='h'
  573. else
  574. HF:='hh';
  575. // No support for 12 hour stuff at the moment...
  576. ShortTimeFormat := HF+':nn';
  577. LongTimeFormat := HF + ':nn:ss';
  578. { Currency stuff }
  579. CurrencyString:=GetLocaleStr(LID, LOCALE_SCURRENCY, '');
  580. CurrencyFormat:=StrToIntDef(GetLocaleStr(LID, LOCALE_ICURRENCY, '0'), 0);
  581. NegCurrFormat:=StrToIntDef(GetLocaleStr(LID, LOCALE_INEGCURR, '0'), 0);
  582. { Number stuff }
  583. ThousandSeparator:=GetLocaleChar(LID, LOCALE_STHOUSAND, ',');
  584. DecimalSeparator:=GetLocaleChar(LID, LOCALE_SDECIMAL, '.');
  585. CurrencyDecimals:=StrToIntDef(GetLocaleStr(LID, LOCALE_ICURRDIGITS, '0'), 0);
  586. end;
  587. Procedure InitInternational;
  588. var
  589. { A call to GetSystemMetrics changes the value of the 8087 Control Word on
  590. Pentium4 with WinXP SP2 }
  591. old8087CW: word;
  592. begin
  593. InitInternationalGeneric;
  594. old8087CW:=Get8087CW;
  595. SysLocale.MBCS:=GetSystemMetrics(SM_DBCSENABLED)<>0;
  596. SysLocale.RightToLeft:=GetSystemMetrics(SM_MIDEASTENABLED)<>0;
  597. SysLocale.DefaultLCID := $0409;
  598. SysLocale.PriLangID := LANG_ENGLISH;
  599. SysLocale.SubLangID := SUBLANG_ENGLISH_US;
  600. // probably needs update with getthreadlocale. post 2.0.2
  601. Set8087CW(old8087CW);
  602. InitAnsi;
  603. GetFormatSettings;
  604. end;
  605. {****************************************************************************
  606. Target Dependent
  607. ****************************************************************************}
  608. function FormatMessageA(dwFlags : DWORD;
  609. lpSource : Pointer;
  610. dwMessageId : DWORD;
  611. dwLanguageId: DWORD;
  612. lpBuffer : PCHAR;
  613. nSize : DWORD;
  614. Arguments : Pointer): DWORD; stdcall;external 'kernel32' name 'FormatMessageA';
  615. function SysErrorMessage(ErrorCode: Integer): String;
  616. const
  617. MaxMsgSize = Format_Message_Max_Width_Mask;
  618. var
  619. MsgBuffer: pChar;
  620. begin
  621. GetMem(MsgBuffer, MaxMsgSize);
  622. FillChar(MsgBuffer^, MaxMsgSize, #0);
  623. FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM,
  624. nil,
  625. ErrorCode,
  626. MakeLangId(LANG_NEUTRAL, SUBLANG_DEFAULT),
  627. MsgBuffer, { This function allocs the memory }
  628. MaxMsgSize, { Maximum message size }
  629. nil);
  630. SysErrorMessage := StrPas(MsgBuffer);
  631. FreeMem(MsgBuffer, MaxMsgSize);
  632. end;
  633. {****************************************************************************
  634. Initialization code
  635. ****************************************************************************}
  636. Function GetEnvironmentVariable(Const EnvVar : String) : String;
  637. var
  638. s : string;
  639. i : longint;
  640. hp,p : pchar;
  641. begin
  642. Result:='';
  643. p:=GetEnvironmentStrings;
  644. hp:=p;
  645. while hp^<>#0 do
  646. begin
  647. s:=strpas(hp);
  648. i:=pos('=',s);
  649. if uppercase(copy(s,1,i-1))=upcase(envvar) then
  650. begin
  651. Result:=copy(s,i+1,length(s)-i);
  652. break;
  653. end;
  654. { next string entry}
  655. hp:=hp+strlen(hp)+1;
  656. end;
  657. FreeEnvironmentStrings(p);
  658. end;
  659. Function GetEnvironmentVariableCount : Integer;
  660. var
  661. hp,p : pchar;
  662. begin
  663. Result:=0;
  664. p:=GetEnvironmentStrings;
  665. hp:=p;
  666. If (Hp<>Nil) then
  667. while hp^<>#0 do
  668. begin
  669. Inc(Result);
  670. hp:=hp+strlen(hp)+1;
  671. end;
  672. FreeEnvironmentStrings(p);
  673. end;
  674. Function GetEnvironmentString(Index : Integer) : String;
  675. var
  676. hp,p : pchar;
  677. begin
  678. Result:='';
  679. p:=GetEnvironmentStrings;
  680. hp:=p;
  681. If (Hp<>Nil) then
  682. begin
  683. while (hp^<>#0) and (Index>1) do
  684. begin
  685. Dec(Index);
  686. hp:=hp+strlen(hp)+1;
  687. end;
  688. If (hp^<>#0) then
  689. Result:=StrPas(HP);
  690. end;
  691. FreeEnvironmentStrings(p);
  692. end;
  693. function ExecuteProcess(Const Path: AnsiString; Const ComLine: AnsiString):integer;
  694. var
  695. SI: TStartupInfo;
  696. PI: TProcessInformation;
  697. Proc : THandle;
  698. l : DWord;
  699. CommandLine : ansistring;
  700. e : EOSError;
  701. begin
  702. FillChar(SI, SizeOf(SI), 0);
  703. SI.cb:=SizeOf(SI);
  704. SI.wShowWindow:=1;
  705. { always surround the name of the application by quotes
  706. so that long filenames will always be accepted. But don't
  707. do it if there are already double quotes, since Win32 does not
  708. like double quotes which are duplicated!
  709. }
  710. if pos('"',path)=0 then
  711. CommandLine:='"'+path+'"'
  712. else
  713. CommandLine:=path;
  714. if ComLine <> '' then
  715. CommandLine:=Commandline+' '+ComLine+#0
  716. else
  717. CommandLine := CommandLine + #0;
  718. if not CreateProcess(nil, pchar(CommandLine),
  719. Nil, Nil, False,$20, Nil, Nil, SI, PI) then
  720. begin
  721. e:=EOSError.CreateFmt(SExecuteProcessFailed,[CommandLine,GetLastError]);
  722. e.ErrorCode:=GetLastError;
  723. raise e;
  724. end;
  725. Proc:=PI.hProcess;
  726. if WaitForSingleObject(Proc, dword($ffffffff)) <> $ffffffff then
  727. begin
  728. GetExitCodeProcess(Proc,l);
  729. CloseHandle(Proc);
  730. CloseHandle(PI.hThread);
  731. result:=l;
  732. end
  733. else
  734. begin
  735. e:=EOSError.CreateFmt(SExecuteProcessFailed,[CommandLine,GetLastError]);
  736. e.ErrorCode:=GetLastError;
  737. CloseHandle(Proc);
  738. CloseHandle(PI.hThread);
  739. raise e;
  740. end;
  741. end;
  742. function ExecuteProcess(Const Path: AnsiString; Const ComLine: Array of AnsiString):integer;
  743. Var
  744. CommandLine : AnsiString;
  745. i : Integer;
  746. Begin
  747. Commandline:='';
  748. For i:=0 to high(ComLine) Do
  749. Commandline:=CommandLine+' '+Comline[i];
  750. ExecuteProcess:=ExecuteProcess(Path,CommandLine);
  751. End;
  752. Procedure Sleep(Milliseconds : Cardinal);
  753. begin
  754. Windows.Sleep(MilliSeconds)
  755. end;
  756. Function GetLastOSError : Integer;
  757. begin
  758. Result:=GetLastError;
  759. end;
  760. {****************************************************************************
  761. Initialization code
  762. ****************************************************************************}
  763. var
  764. kernel32dll : THandle;
  765. Procedure LoadVersionInfo;
  766. // and getfreespaceex
  767. Var
  768. versioninfo : TOSVERSIONINFO;
  769. begin
  770. kernel32dll:=0;
  771. GetDiskFreeSpaceEx:=nil;
  772. versioninfo.dwOSVersionInfoSize:=sizeof(versioninfo);
  773. GetVersionEx(versioninfo);
  774. Win32Platform:=versionInfo.dwPlatformId;
  775. Win32MajorVersion:=versionInfo.dwMajorVersion;
  776. Win32MinorVersion:=versionInfo.dwMinorVersion;
  777. Win32BuildNumber:=versionInfo.dwBuildNumber;
  778. Move (versioninfo.szCSDVersion ,Win32CSDVersion[1],128);
  779. win32CSDVersion[0]:=chr(strlen(pchar(@versioninfo.szCSDVersion)));
  780. if ((versioninfo.dwPlatformId=VER_PLATFORM_WIN32_WINDOWS) and
  781. (versioninfo.dwBuildNUmber>=1000)) or
  782. (versioninfo.dwPlatformId=VER_PLATFORM_WIN32_NT) then
  783. begin
  784. kernel32dll:=LoadLibrary('kernel32');
  785. if kernel32dll<>0 then
  786. GetDiskFreeSpaceEx:=TGetDiskFreeSpaceEx(GetProcAddress(kernel32dll,'GetDiskFreeSpaceExA'));
  787. end;
  788. end;
  789. function FreeLibrary(hLibModule : THANDLE) : longbool;
  790. stdcall;external 'kernel32' name 'FreeLibrary';
  791. function GetVersionEx(var VersionInformation:TOSVERSIONINFO) : longbool;
  792. stdcall;external 'kernel32' name 'GetVersionExA';
  793. function LoadLibrary(lpLibFileName : pchar):THandle;
  794. stdcall;external 'kernel32' name 'LoadLibraryA';
  795. function GetProcAddress(hModule : THandle;lpProcName : pchar) : pointer;
  796. stdcall;external 'kernel32' name 'GetProcAddress';
  797. Const
  798. CSIDL_PROGRAMS = $0002; { %SYSTEMDRIVE%\Program Files }
  799. CSIDL_PERSONAL = $0005; { %USERPROFILE%\My Documents }
  800. CSIDL_FAVORITES = $0006; { %USERPROFILE%\Favorites }
  801. CSIDL_STARTUP = $0007; { %USERPROFILE%\Start menu\Programs\Startup }
  802. CSIDL_RECENT = $0008; { %USERPROFILE%\Recent }
  803. CSIDL_SENDTO = $0009; { %USERPROFILE%\Sendto }
  804. CSIDL_STARTMENU = $000B; { %USERPROFILE%\Start menu }
  805. CSIDL_MYMUSIC = $000D; { %USERPROFILE%\Documents\My Music }
  806. CSIDL_MYVIDEO = $000E; { %USERPROFILE%\Documents\My Videos }
  807. CSIDL_DESKTOPDIRECTORY = $0010; { %USERPROFILE%\Desktop }
  808. CSIDL_NETHOOD = $0013; { %USERPROFILE%\NetHood }
  809. CSIDL_TEMPLATES = $0015; { %USERPROFILE%\Templates }
  810. CSIDL_COMMON_STARTMENU = $0016; { %PROFILEPATH%\All users\Start menu }
  811. CSIDL_COMMON_PROGRAMS = $0017; { %PROFILEPATH%\All users\Start menu\Programs }
  812. CSIDL_COMMON_STARTUP = $0018; { %PROFILEPATH%\All users\Start menu\Programs\Startup }
  813. CSIDL_COMMON_DESKTOPDIRECTORY = $0019; { %PROFILEPATH%\All users\Desktop }
  814. CSIDL_APPDATA = $001A; { %USERPROFILE%\Application Data (roaming) }
  815. CSIDL_PRINTHOOD = $001B; { %USERPROFILE%\Printhood }
  816. CSIDL_LOCAL_APPDATA = $001C; { %USERPROFILE%\Local Settings\Application Data (non roaming) }
  817. CSIDL_COMMON_FAVORITES = $001F; { %PROFILEPATH%\All users\Favorites }
  818. CSIDL_INTERNET_CACHE = $0020; { %USERPROFILE%\Local Settings\Temporary Internet Files }
  819. CSIDL_COOKIES = $0021; { %USERPROFILE%\Cookies }
  820. CSIDL_HISTORY = $0022; { %USERPROFILE%\Local settings\History }
  821. CSIDL_COMMON_APPDATA = $0023; { %PROFILESPATH%\All Users\Application Data }
  822. CSIDL_WINDOWS = $0024; { %SYSTEMROOT% }
  823. CSIDL_SYSTEM = $0025; { %SYSTEMROOT%\SYSTEM32 (may be system on 95/98/ME) }
  824. CSIDL_PROGRAM_FILES = $0026; { %SYSTEMDRIVE%\Program Files }
  825. CSIDL_MYPICTURES = $0027; { %USERPROFILE%\My Documents\My Pictures }
  826. CSIDL_PROFILE = $0028; { %USERPROFILE% }
  827. CSIDL_PROGRAM_FILES_COMMON = $002B; { %SYSTEMDRIVE%\Program Files\Common }
  828. CSIDL_COMMON_TEMPLATES = $002D; { %PROFILEPATH%\All Users\Templates }
  829. CSIDL_COMMON_DOCUMENTS = $002E; { %PROFILEPATH%\All Users\Documents }
  830. CSIDL_COMMON_ADMINTOOLS = $002F; { %PROFILEPATH%\All Users\Start Menu\Programs\Administrative Tools }
  831. CSIDL_ADMINTOOLS = $0030; { %USERPROFILE%\Start Menu\Programs\Administrative Tools }
  832. CSIDL_COMMON_MUSIC = $0035; { %PROFILEPATH%\All Users\Documents\my music }
  833. CSIDL_COMMON_PICTURES = $0036; { %PROFILEPATH%\All Users\Documents\my pictures }
  834. CSIDL_COMMON_VIDEO = $0037; { %PROFILEPATH%\All Users\Documents\my videos }
  835. CSIDL_CDBURN_AREA = $003B; { %USERPROFILE%\Local Settings\Application Data\Microsoft\CD Burning }
  836. CSIDL_PROFILES = $003E; { %PROFILEPATH% }
  837. CSIDL_FLAG_CREATE = $8000; { (force creation of requested folder if it doesn't exist yet) }
  838. Type
  839. PFNSHGetFolderPath = Function(Ahwnd: HWND; Csidl: Integer; Token: THandle; Flags: DWord; Path: PChar): HRESULT; stdcall;
  840. var
  841. SHGetFolderPath : PFNSHGetFolderPath = Nil;
  842. CFGDLLHandle : THandle = 0;
  843. Procedure InitDLL;
  844. Var
  845. P : Pointer;
  846. begin
  847. CFGDLLHandle:=LoadLibrary('shell32.dll');
  848. if (CFGDLLHandle<>0) then
  849. begin
  850. P:=GetProcAddress(CFGDLLHandle,'SHGetFolderPathA');
  851. If (P=Nil) then
  852. begin
  853. FreeLibrary(CFGDLLHandle);
  854. CFGDllHandle:=0;
  855. end
  856. else
  857. SHGetFolderPath:=PFNSHGetFolderPath(P);
  858. end;
  859. If (P=Nil) then
  860. begin
  861. CFGDLLHandle:=LoadLibrary('shfolder.dll');
  862. if (CFGDLLHandle<>0) then
  863. begin
  864. P:=GetProcAddress(CFGDLLHandle,'SHGetFolderPathA');
  865. If (P=Nil) then
  866. begin
  867. FreeLibrary(CFGDLLHandle);
  868. CFGDllHandle:=0;
  869. end
  870. else
  871. ShGetFolderPath:=PFNSHGetFolderPath(P);
  872. end;
  873. end;
  874. If (@ShGetFolderPath=Nil) then
  875. Raise Exception.Create('Could not determine SHGetFolderPath Function');
  876. end;
  877. Function GetSpecialDir(ID : Integer) : String;
  878. Var
  879. APath : Array[0..MAX_PATH] of char;
  880. begin
  881. Result:='';
  882. if (CFGDLLHandle=0) then
  883. InitDLL;
  884. If (SHGetFolderPath<>Nil) then
  885. begin
  886. if SHGetFolderPath(0,ID or CSIDL_FLAG_CREATE,0,0,@APATH[0])=S_OK then
  887. Result:=IncludeTrailingPathDelimiter(StrPas(@APath[0]));
  888. end;
  889. end;
  890. Function GetAppConfigDir(Global : Boolean) : String;
  891. begin
  892. If Global then
  893. Result:=DGetAppConfigDir(Global) // or use windows dir ??
  894. else
  895. begin
  896. Result:=GetSpecialDir(CSIDL_LOCAL_APPDATA)+ApplicationName;
  897. If (Result='') then
  898. Result:=DGetAppConfigDir(Global);
  899. end;
  900. end;
  901. Function GetAppConfigFile(Global : Boolean; SubDir : Boolean) : String;
  902. begin
  903. if Global then
  904. begin
  905. Result:=IncludeTrailingPathDelimiter(DGetAppConfigDir(Global));
  906. if SubDir then
  907. Result:=IncludeTrailingPathDelimiter(Result+'Config');
  908. Result:=Result+ApplicationName+ConfigExtension;
  909. end
  910. else
  911. begin
  912. Result:=IncludeTrailingPathDelimiter(GetAppConfigDir(False));
  913. if SubDir then
  914. Result:=Result+'Config\';
  915. Result:=Result+ApplicationName+ConfigExtension;
  916. end;
  917. end;
  918. Procedure InitSysConfigDir;
  919. begin
  920. SetLength(SysConfigDir, MAX_PATH);
  921. SetLength(SysConfigDir, GetWindowsDirectory(PChar(SysConfigDir), MAX_PATH));
  922. end;
  923. {****************************************************************************
  924. Target Dependent WideString stuff
  925. ****************************************************************************}
  926. function Win32CompareWideString(const s1, s2 : WideString) : PtrInt;
  927. begin
  928. SetLastError(0);
  929. Result:=CompareStringW(LOCALE_USER_DEFAULT,0,pwidechar(s1),
  930. length(s1),pwidechar(s2),length(s2))-2;
  931. if GetLastError<>0 then
  932. RaiseLastOSError;
  933. end;
  934. function Win32CompareTextWideString(const s1, s2 : WideString) : PtrInt;
  935. begin
  936. SetLastError(0);
  937. Result:=CompareStringW(LOCALE_USER_DEFAULT,NORM_IGNORECASE,pwidechar(s1),
  938. length(s1),pwidechar(s2),length(s2))-2;
  939. if GetLastError<>0 then
  940. RaiseLastOSError;
  941. end;
  942. function Win32AnsiUpperCase(const s: string): string;
  943. begin
  944. if length(s)>0 then
  945. begin
  946. result:=s;
  947. UniqueString(result);
  948. CharUpperBuff(pchar(result),length(result));
  949. end
  950. else
  951. result:='';
  952. end;
  953. function Win32AnsiLowerCase(const s: string): string;
  954. begin
  955. if length(s)>0 then
  956. begin
  957. result:=s;
  958. UniqueString(result);
  959. CharLowerBuff(pchar(result),length(result));
  960. end
  961. else
  962. result:='';
  963. end;
  964. function Win32AnsiCompareStr(const S1, S2: string): PtrInt;
  965. begin
  966. result:=CompareString(LOCALE_USER_DEFAULT,0,pchar(s1),length(s1),
  967. pchar(s2),length(s2))-2;
  968. end;
  969. function Win32AnsiCompareText(const S1, S2: string): PtrInt;
  970. begin
  971. result:=CompareString(LOCALE_USER_DEFAULT,NORM_IGNORECASE,pchar(s1),length(s1),
  972. pchar(s2),length(s2))-2;
  973. end;
  974. function Win32AnsiStrComp(S1, S2: PChar): PtrInt;
  975. begin
  976. result:=CompareString(LOCALE_USER_DEFAULT,0,s1,-1,s2,-1)-2;
  977. end;
  978. function Win32AnsiStrIComp(S1, S2: PChar): PtrInt;
  979. begin
  980. result:=CompareString(LOCALE_USER_DEFAULT,NORM_IGNORECASE,s1,-1,s2,-1)-2;
  981. end;
  982. function Win32AnsiStrLComp(S1, S2: PChar; MaxLen: PtrUInt): PtrInt;
  983. begin
  984. result:=CompareString(LOCALE_USER_DEFAULT,0,s1,maxlen,s2,maxlen)-2;
  985. end;
  986. function Win32AnsiStrLIComp(S1, S2: PChar; MaxLen: PtrUInt): PtrInt;
  987. begin
  988. result:=CompareString(LOCALE_USER_DEFAULT,NORM_IGNORECASE,s1,maxlen,s2,maxlen)-2;
  989. end;
  990. function Win32AnsiStrLower(Str: PChar): PChar;
  991. begin
  992. CharLower(str);
  993. result:=str;
  994. end;
  995. function Win32AnsiStrUpper(Str: PChar): PChar;
  996. begin
  997. CharUpper(str);
  998. result:=str;
  999. end;
  1000. { there is a similiar procedure in the system unit which inits the fields which
  1001. are relevant already for the system unit }
  1002. procedure InitWin32Widestrings;
  1003. begin
  1004. widestringmanager.CompareWideStringProc:=@Win32CompareWideString;
  1005. widestringmanager.CompareTextWideStringProc:=@Win32CompareTextWideString;
  1006. widestringmanager.UpperAnsiStringProc:=@Win32AnsiUpperCase;
  1007. widestringmanager.LowerAnsiStringProc:=@Win32AnsiLowerCase;
  1008. widestringmanager.CompareStrAnsiStringProc:=@Win32AnsiCompareStr;
  1009. widestringmanager.CompareTextAnsiStringProc:=@Win32AnsiCompareText;
  1010. widestringmanager.StrCompAnsiStringProc:=@Win32AnsiStrComp;
  1011. widestringmanager.StrICompAnsiStringProc:=@Win32AnsiStrIComp;
  1012. widestringmanager.StrLCompAnsiStringProc:=@Win32AnsiStrLComp;
  1013. widestringmanager.StrLICompAnsiStringProc:=@Win32AnsiStrLIComp;
  1014. widestringmanager.StrLowerAnsiStringProc:=@Win32AnsiStrLower;
  1015. widestringmanager.StrUpperAnsiStringProc:=@Win32AnsiStrUpper;
  1016. end;
  1017. procedure SetupProcVars;
  1018. var
  1019. hinstLib : THandle;
  1020. begin
  1021. SetFilePointerEx:=nil;
  1022. hinstLib:=LoadLibrary(KernelDLL);
  1023. if hinstLib<>0 then
  1024. begin
  1025. pointer(SetFilePointerEx):=GetProcAddress(hinstLib,'SetFilePointerEx');
  1026. FreeLibrary(hinstLib);
  1027. end;
  1028. end;
  1029. Initialization
  1030. InitWin32Widestrings;
  1031. InitExceptions; { Initialize exceptions. OS independent }
  1032. InitInternational; { Initialize internationalization settings }
  1033. LoadVersionInfo;
  1034. InitSysConfigDir;
  1035. SetupProcVars;
  1036. Finalization
  1037. DoneExceptions;
  1038. if kernel32dll<>0 then
  1039. FreeLibrary(kernel32dll);
  1040. if CFGDLLHandle<>0 then
  1041. FreeLibrary(CFGDllHandle);
  1042. end.