sysutils.pp 32 KB

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