sysutils.pp 33 KB

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