sysutils.pp 32 KB

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