sysutils.pp 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502
  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. {$MODESWITCH OUT}
  16. { force ansistrings }
  17. {$H+}
  18. {$modeswitch typehelpers}
  19. {$modeswitch advancedrecords}
  20. uses
  21. windows;
  22. {$DEFINE HAS_SLEEP}
  23. {$DEFINE HAS_OSERROR}
  24. {$DEFINE HAS_OSCONFIG}
  25. {$DEFINE HAS_OSUSERDIR}
  26. {$DEFINE HAS_CREATEGUID}
  27. {$DEFINE HAS_LOCALTIMEZONEOFFSET}
  28. {$DEFINE HAS_GETTICKCOUNT}
  29. {$DEFINE HAS_GETTICKCOUNT64}
  30. {$DEFINE OS_FILESETDATEBYNAME}
  31. // this target has an fileflush implementation, don't include dummy
  32. {$DEFINE SYSUTILS_HAS_FILEFLUSH_IMPL}
  33. { used OS file system APIs use unicodestring }
  34. {$define SYSUTILS_HAS_UNICODESTR_FILEUTIL_IMPL}
  35. { OS has an ansistring/single byte environment variable API }
  36. {$define SYSUTILS_HAS_ANSISTR_ENVVAR_IMPL}
  37. { OS has a unicodestring/two byte environment variable API }
  38. {$define SYSUTILS_HAS_UNICODESTR_ENVVAR_IMPL}
  39. { Include platform independent interface part }
  40. {$i sysutilh.inc}
  41. type
  42. TSystemTime = Windows.TSystemTime;
  43. EWin32Error = class(Exception)
  44. public
  45. ErrorCode : DWORD;
  46. end;
  47. Var
  48. Win32Platform : Longint;
  49. Win32MajorVersion,
  50. Win32MinorVersion,
  51. Win32BuildNumber : dword;
  52. Win32CSDVersion : ShortString; // CSD record is 128 bytes only?
  53. const
  54. MaxEraCount = 7;
  55. var
  56. EraNames: array [1..MaxEraCount] of String;
  57. EraYearOffsets: array [1..MaxEraCount] of Integer;
  58. { Compatibility with Delphi }
  59. function Win32Check(res:boolean):boolean;inline;
  60. function WinCheck(res:boolean):boolean;
  61. function CheckWin32Version(Major,Minor : Integer ): Boolean;
  62. function CheckWin32Version(Major : Integer): Boolean;
  63. Procedure RaiseLastWin32Error;
  64. function GetFileVersion(const AFileName: string): Cardinal;
  65. function GetFileVersion(const AFileName: UnicodeString): Cardinal;
  66. procedure GetFormatSettings;
  67. procedure GetLocaleFormatSettings(LCID: Integer; var FormatSettings: TFormatSettings); platform;
  68. implementation
  69. uses
  70. sysconst,
  71. windirs;
  72. function WinCheck(res:boolean):boolean;
  73. begin
  74. if not res then
  75. RaiseLastOSError;
  76. result:=res;
  77. end;
  78. function Win32Check(res:boolean):boolean;inline;
  79. begin
  80. result:=WinCheck(res);
  81. end;
  82. procedure RaiseLastWin32Error;
  83. begin
  84. RaiseLastOSError;
  85. end;
  86. function CheckWin32Version(Major : Integer): Boolean;
  87. begin
  88. Result:=CheckWin32Version(Major,0)
  89. end;
  90. function CheckWin32Version(Major,Minor: Integer): Boolean;
  91. begin
  92. Result:=(Win32MajorVersion>dword(Major)) or
  93. ((Win32MajorVersion=dword(Major)) and (Win32MinorVersion>=dword(Minor)));
  94. end;
  95. function GetFileVersion(const AFileName:string):Cardinal;
  96. var
  97. { useful only as long as we don't need to touch different stack pages }
  98. buf : array[0..3071] of byte;
  99. bufp : pointer;
  100. fn : string;
  101. valsize,
  102. size : DWORD;
  103. h : DWORD;
  104. valrec : PVSFixedFileInfo;
  105. begin
  106. result:=$fffffff;
  107. fn:=AFileName;
  108. UniqueString(fn);
  109. size:=GetFileVersionInfoSizeA(pchar(fn),@h);
  110. if size>sizeof(buf) then
  111. begin
  112. getmem(bufp,size);
  113. try
  114. if GetFileVersionInfoA(pchar(fn),h,size,bufp) then
  115. if VerQueryValue(bufp,'\',valrec,valsize) then
  116. result:=valrec^.dwFileVersionMS;
  117. finally
  118. freemem(bufp);
  119. end;
  120. end
  121. else
  122. begin
  123. if GetFileVersionInfoA(pchar(fn),h,size,@buf) then
  124. if VerQueryValue(@buf,'\',valrec,valsize) then
  125. result:=valrec^.dwFileVersionMS;
  126. end;
  127. end;
  128. function GetFileVersion(const AFileName:UnicodeString):Cardinal;
  129. var
  130. { useful only as long as we don't need to touch different stack pages }
  131. buf : array[0..3071] of byte;
  132. bufp : pointer;
  133. fn : unicodestring;
  134. valsize,
  135. size : DWORD;
  136. h : DWORD;
  137. valrec : PVSFixedFileInfo;
  138. begin
  139. result:=$fffffff;
  140. fn:=AFileName;
  141. UniqueString(fn);
  142. size:=GetFileVersionInfoSizeW(pwidechar(fn),@h);
  143. if size>sizeof(buf) then
  144. begin
  145. getmem(bufp,size);
  146. try
  147. if GetFileVersionInfoW(pwidechar(fn),h,size,bufp) then
  148. if VerQueryValue(bufp,'\',valrec,valsize) then
  149. result:=valrec^.dwFileVersionMS;
  150. finally
  151. freemem(bufp);
  152. end;
  153. end
  154. else
  155. begin
  156. if GetFileVersionInfoW(pwidechar(fn),h,size,@buf) then
  157. if VerQueryValueW(@buf,'\',valrec,valsize) then
  158. result:=valrec^.dwFileVersionMS;
  159. end;
  160. end;
  161. {$define HASCREATEGUID}
  162. {$define HASEXPANDUNCFILENAME}
  163. {$DEFINE FPC_NOGENERICANSIROUTINES}
  164. {$DEFINE FPC_FEXPAND_UNC} (* UNC paths are supported *)
  165. {$DEFINE FPC_FEXPAND_DRIVES} (* Full paths begin with drive specification *)
  166. function ConvertEraYearString(Count ,Year,Month,Day : integer) : string; forward;
  167. function ConvertEraString(Count ,Year,Month,Day : integer) : string; forward;
  168. { Include platform independent implementation part }
  169. {$i sysutils.inc}
  170. function GetTempFileName(Dir,Prefix: PChar; uUnique: DWORD; TempFileName: PChar):DWORD;
  171. begin
  172. Result:= Windows.GetTempFileNameA(Dir,Prefix,uUnique,TempFileName);
  173. end;
  174. { UUID generation. }
  175. function CoCreateGuid(out guid: TGUID): HResult; stdcall; external 'ole32.dll' name 'CoCreateGuid';
  176. function SysCreateGUID(out Guid: TGUID): Integer;
  177. begin
  178. Result := Integer(CoCreateGuid(Guid));
  179. end;
  180. function ExpandUNCFileName (const filename:rawbytestring) : rawbytestring;
  181. { returns empty string on errors }
  182. var
  183. u: unicodestring;
  184. begin
  185. { prevent data loss due to unsupported characters in ansi code page }
  186. u:=ExpandUNCFileName(unicodestring(filename));
  187. widestringmanager.Unicode2AnsiMoveProc(punicodechar(u),result,DefaultRTLFileSystemCodePage,length(u));
  188. end;
  189. function ExpandUNCFileName (const filename:unicodestring) : unicodestring;
  190. { returns empty string on errors }
  191. var
  192. s : unicodestring;
  193. size : dword;
  194. rc : dword;
  195. buf : pwidechar;
  196. begin
  197. s := ExpandFileName (filename);
  198. s := s + #0;
  199. size := max_path;
  200. getmem(buf,size);
  201. try
  202. rc := WNetGetUniversalNameW (pwidechar(s), UNIVERSAL_NAME_INFO_LEVEL, buf, @size);
  203. if rc=ERROR_MORE_DATA then
  204. begin
  205. buf:=reallocmem(buf,size);
  206. rc := WNetGetUniversalNameW (pwidechar(s), UNIVERSAL_NAME_INFO_LEVEL, buf, @size);
  207. end;
  208. if rc = NO_ERROR then
  209. Result := PRemoteNameInfoW(buf)^.lpUniversalName
  210. else if rc = ERROR_NOT_CONNECTED then
  211. Result := filename
  212. else
  213. Result := '';
  214. finally
  215. freemem(buf);
  216. end;
  217. end;
  218. {****************************************************************************
  219. File Functions
  220. ****************************************************************************}
  221. const
  222. AccessMode: array[0..2] of Cardinal = (
  223. GENERIC_READ,
  224. GENERIC_WRITE,
  225. GENERIC_READ or GENERIC_WRITE or FILE_WRITE_ATTRIBUTES);
  226. ShareModes: array[0..4] of Integer = (
  227. 0,
  228. 0,
  229. FILE_SHARE_READ,
  230. FILE_SHARE_WRITE,
  231. FILE_SHARE_READ or FILE_SHARE_WRITE);
  232. function FileFlush(Handle: THandle): Boolean;
  233. begin
  234. Result:= FlushFileBuffers(Handle);
  235. end;
  236. Function FileOpen (Const FileName : unicodestring; Mode : Integer) : THandle;
  237. begin
  238. result := CreateFileW(PWideChar(FileName), dword(AccessMode[Mode and 3]),
  239. dword(ShareModes[(Mode and $F0) shr 4]), nil, OPEN_EXISTING,
  240. FILE_ATTRIBUTE_NORMAL, 0);
  241. //if fail api return feInvalidHandle (INVALIDE_HANDLE=feInvalidHandle=-1)
  242. end;
  243. Function FileCreate (Const FileName : UnicodeString) : THandle;
  244. begin
  245. FileCreate:=FileCreate(FileName, fmShareExclusive, 0);
  246. end;
  247. Function FileCreate (Const FileName : UnicodeString; Rights:longint) : THandle;
  248. begin
  249. FileCreate:=FileCreate(FileName, fmShareExclusive, Rights);
  250. end;
  251. Function FileCreate (Const FileName : UnicodeString; ShareMode : Integer; Rights : Integer) : THandle;
  252. begin
  253. Result := CreateFileW(PwideChar(FileName), GENERIC_READ or GENERIC_WRITE,
  254. dword(ShareModes[(ShareMode and $F0) shr 4]), nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  255. end;
  256. Function FileRead (Handle : THandle; out Buffer; Count : longint) : Longint;
  257. Var
  258. res : dword;
  259. begin
  260. if ReadFile(Handle, Buffer, Count, res, nil) then
  261. FileRead:=Res
  262. else
  263. FileRead:=-1;
  264. end;
  265. Function FileWrite (Handle : THandle; const Buffer; Count : Longint) : Longint;
  266. Var
  267. Res : dword;
  268. begin
  269. if WriteFile(Handle, Buffer, Count, Res, nil) then
  270. FileWrite:=Res
  271. else
  272. FileWrite:=-1;
  273. end;
  274. Function FileSeek (Handle : THandle;FOffset,Origin : Longint) : Longint;
  275. begin
  276. Result := longint(SetFilePointer(Handle, FOffset, nil, Origin));
  277. end;
  278. Function FileSeek (Handle : THandle; FOffset: Int64; Origin: Longint) : Int64;
  279. var
  280. rslt: Int64Rec;
  281. begin
  282. rslt := Int64Rec(FOffset);
  283. rslt.lo := SetFilePointer(Handle, rslt.lo, @rslt.hi, Origin);
  284. if (rslt.lo = $FFFFFFFF) and (GetLastError <> 0) then
  285. rslt.hi := $FFFFFFFF;
  286. Result := Int64(rslt);
  287. end;
  288. Procedure FileClose (Handle : THandle);
  289. begin
  290. CloseHandle(Handle);
  291. end;
  292. Function FileTruncate (Handle : THandle;Size: Int64) : boolean;
  293. begin
  294. {
  295. Result:=longint(SetFilePointer(handle,Size,nil,FILE_BEGIN))<>-1;
  296. }
  297. if FileSeek (Handle, Size, FILE_BEGIN) = Size then
  298. Result:=SetEndOfFile(handle)
  299. else
  300. Result := false;
  301. end;
  302. Function DosToWinTime (DTime:longint;Var Wtime : TFileTime):longbool;
  303. var
  304. lft : TFileTime;
  305. begin
  306. DosToWinTime:=DosDateTimeToFileTime(longrec(dtime).hi,longrec(dtime).lo,@lft) and
  307. LocalFileTimeToFileTime(lft,Wtime);
  308. end;
  309. Function WinToDosTime (Var Wtime : TFileTime;var DTime:longint):longbool;
  310. var
  311. lft : TFileTime;
  312. begin
  313. WinToDosTime:=FileTimeToLocalFileTime(WTime,lft) and
  314. FileTimeToDosDateTime(lft,Longrec(Dtime).Hi,LongRec(DTIME).lo);
  315. end;
  316. Function FileAge (Const FileName : UnicodeString): Longint;
  317. var
  318. Handle: THandle;
  319. FindData: TWin32FindDataW;
  320. begin
  321. Handle := FindFirstFileW(Pwidechar(FileName), FindData);
  322. if Handle <> INVALID_HANDLE_VALUE then
  323. begin
  324. Windows.FindClose(Handle);
  325. if (FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) = 0 then
  326. If WinToDosTime(FindData.ftLastWriteTime,Result) then
  327. exit;
  328. end;
  329. Result := -1;
  330. end;
  331. Function FileExists (Const FileName : UnicodeString) : Boolean;
  332. var
  333. Attr:Dword;
  334. begin
  335. Attr:=GetFileAttributesW(PWideChar(FileName));
  336. if Attr <> $ffffffff then
  337. Result:= (Attr and FILE_ATTRIBUTE_DIRECTORY) = 0
  338. else
  339. Result:=False;
  340. end;
  341. Function DirectoryExists (Const Directory : UnicodeString) : Boolean;
  342. var
  343. Attr:Dword;
  344. begin
  345. Attr:=GetFileAttributesW(PWideChar(Directory));
  346. if Attr <> $ffffffff then
  347. Result:= (Attr and FILE_ATTRIBUTE_DIRECTORY) > 0
  348. else
  349. Result:=False;
  350. end;
  351. Function FindMatch(var f: TAbstractSearchRec; var Name: UnicodeString) : Longint;
  352. begin
  353. { Find file with correct attribute }
  354. While (F.FindData.dwFileAttributes and cardinal(F.ExcludeAttr))<>0 do
  355. begin
  356. if not FindNextFileW (F.FindHandle,F.FindData) then
  357. begin
  358. Result:=GetLastError;
  359. exit;
  360. end;
  361. end;
  362. { Convert some attributes back }
  363. WinToDosTime(F.FindData.ftLastWriteTime,F.Time);
  364. f.size:=F.FindData.NFileSizeLow+(qword(maxdword)+1)*F.FindData.NFileSizeHigh;
  365. f.attr:=F.FindData.dwFileAttributes;
  366. Name:=F.FindData.cFileName;
  367. Result:=0;
  368. end;
  369. Procedure InternalFindClose (var Handle: THandle; var FindData: TFindData);
  370. begin
  371. if Handle <> INVALID_HANDLE_VALUE then
  372. begin
  373. Windows.FindClose(Handle);
  374. Handle:=INVALID_HANDLE_VALUE;
  375. end;
  376. end;
  377. Function InternalFindFirst (Const Path : UnicodeString; Attr : Longint; out Rslt : TAbstractSearchRec; var Name : UnicodeString) : Longint;
  378. begin
  379. Name:=Path;
  380. Rslt.Attr:=attr;
  381. Rslt.ExcludeAttr:=(not Attr) and ($1e);
  382. { $1e = faHidden or faSysFile or faVolumeID or faDirectory }
  383. { FindFirstFile is a Win32 Call }
  384. Rslt.FindHandle:=FindFirstFileW (PWideChar(Path),Rslt.FindData);
  385. If Rslt.FindHandle=Invalid_Handle_value then
  386. begin
  387. Result:=GetLastError;
  388. exit;
  389. end;
  390. { Find file with correct attribute }
  391. Result:=FindMatch(Rslt,Name);
  392. if (Result<>0) then
  393. InternalFindClose(Rslt.FindHandle,Rslt.FindData);
  394. end;
  395. Function InternalFindNext (Var Rslt : TAbstractSearchRec; var Name: UnicodeString) : Longint;
  396. begin
  397. if FindNextFileW(Rslt.FindHandle, Rslt.FindData) then
  398. Result := FindMatch(Rslt, Name)
  399. else
  400. Result := GetLastError;
  401. end;
  402. Function FileGetDate (Handle : THandle) : Longint;
  403. Var
  404. FT : TFileTime;
  405. begin
  406. If GetFileTime(Handle,nil,nil,@ft) and
  407. WinToDosTime(FT,Result) then
  408. exit;
  409. Result:=-1;
  410. end;
  411. Function FileSetDate (Handle : THandle;Age : Longint) : Longint;
  412. Var
  413. FT: TFileTime;
  414. begin
  415. Result := 0;
  416. if DosToWinTime(Age,FT) and
  417. SetFileTime(Handle, nil, nil, @FT) then
  418. Exit;
  419. Result := GetLastError;
  420. end;
  421. {$IFDEF OS_FILESETDATEBYNAME}
  422. Function FileSetDate (Const FileName : UnicodeString;Age : Longint) : Longint;
  423. Var
  424. fd : THandle;
  425. begin
  426. FD := CreateFileW (PWideChar (FileName), GENERIC_READ or GENERIC_WRITE,
  427. FILE_SHARE_WRITE, nil, OPEN_EXISTING,
  428. FILE_FLAG_BACKUP_SEMANTICS, 0);
  429. If (Fd<>feInvalidHandle) then
  430. try
  431. Result:=FileSetDate(fd,Age);
  432. finally
  433. FileClose(fd);
  434. end
  435. else
  436. Result:=GetLastOSError;
  437. end;
  438. {$ENDIF}
  439. Function FileGetAttr (Const FileName : UnicodeString) : Longint;
  440. begin
  441. Result:=Longint(GetFileAttributesW(PWideChar(FileName)));
  442. end;
  443. Function FileSetAttr (Const Filename : UnicodeString; Attr: longint) : Longint;
  444. begin
  445. if SetFileAttributesW(PWideChar(FileName), Attr) then
  446. Result:=0
  447. else
  448. Result := GetLastError;
  449. end;
  450. Function DeleteFile (Const FileName : UnicodeString) : Boolean;
  451. begin
  452. Result:=Windows.DeleteFileW(PWidechar(FileName));
  453. end;
  454. Function RenameFile (Const OldName, NewName : UnicodeString) : Boolean;
  455. begin
  456. Result := MoveFileW(PWideChar(OldName), PWideChar(NewName));
  457. end;
  458. {****************************************************************************
  459. Disk Functions
  460. ****************************************************************************}
  461. type
  462. TGetDiskFreeSpaceEx = function(drive:pchar;var availableforcaller,total,free):longbool;stdcall;
  463. var
  464. GetDiskFreeSpaceEx : TGetDiskFreeSpaceEx;
  465. function diskfree(drive : byte) : int64;
  466. var
  467. disk : array[1..4] of char;
  468. secs,bytes,
  469. free,total : dword;
  470. qwtotal,qwfree,qwcaller : int64;
  471. begin
  472. if drive=0 then
  473. begin
  474. disk[1]:='\';
  475. disk[2]:=#0;
  476. end
  477. else
  478. begin
  479. disk[1]:=chr(drive+64);
  480. disk[2]:=':';
  481. disk[3]:='\';
  482. disk[4]:=#0;
  483. end;
  484. if assigned(GetDiskFreeSpaceEx) then
  485. begin
  486. if GetDiskFreeSpaceEx(@disk[1],qwcaller,qwtotal,qwfree) then
  487. diskfree:=qwfree
  488. else
  489. diskfree:=-1;
  490. end
  491. else
  492. begin
  493. if GetDiskFreeSpace(@disk[1],secs,bytes,free,total) then
  494. diskfree:=int64(free)*secs*bytes
  495. else
  496. diskfree:=-1;
  497. end;
  498. end;
  499. function disksize(drive : byte) : int64;
  500. var
  501. disk : array[1..4] of char;
  502. secs,bytes,
  503. free,total : dword;
  504. qwtotal,qwfree,qwcaller : int64;
  505. begin
  506. if drive=0 then
  507. begin
  508. disk[1]:='\';
  509. disk[2]:=#0;
  510. end
  511. else
  512. begin
  513. disk[1]:=chr(drive+64);
  514. disk[2]:=':';
  515. disk[3]:='\';
  516. disk[4]:=#0;
  517. end;
  518. if assigned(GetDiskFreeSpaceEx) then
  519. begin
  520. if GetDiskFreeSpaceEx(@disk[1],qwcaller,qwtotal,qwfree) then
  521. disksize:=qwtotal
  522. else
  523. disksize:=-1;
  524. end
  525. else
  526. begin
  527. if GetDiskFreeSpace(@disk[1],secs,bytes,free,total) then
  528. disksize:=int64(total)*secs*bytes
  529. else
  530. disksize:=-1;
  531. end;
  532. end;
  533. {****************************************************************************
  534. Time Functions
  535. ****************************************************************************}
  536. Procedure GetLocalTime(var SystemTime: TSystemTime);
  537. begin
  538. windows.Getlocaltime(SystemTime);
  539. end;
  540. function GetLocalTimeOffset: Integer;
  541. var
  542. TZInfo: TTimeZoneInformation;
  543. begin
  544. case GetTimeZoneInformation(TZInfo) of
  545. TIME_ZONE_ID_UNKNOWN:
  546. Result := TZInfo.Bias;
  547. TIME_ZONE_ID_STANDARD:
  548. Result := TZInfo.Bias + TZInfo.StandardBias;
  549. TIME_ZONE_ID_DAYLIGHT:
  550. Result := TZInfo.Bias + TZInfo.DaylightBias;
  551. else
  552. Result := 0;
  553. end;
  554. end;
  555. function GetTickCount: LongWord;
  556. begin
  557. Result := Windows.GetTickCount;
  558. end;
  559. {$IFNDEF WINCE}
  560. type
  561. TGetTickCount64 = function : QWord; stdcall;
  562. var
  563. WinGetTickCount64: TGetTickCount64 = Nil;
  564. {$ENDIF}
  565. function GetTickCount64: QWord;
  566. {$IFNDEF WINCE}
  567. var
  568. lib: THandle;
  569. {$ENDIF}
  570. begin
  571. {$IFNDEF WINCE}
  572. { on Vista and newer there is a GetTickCount64 implementation }
  573. if Win32MajorVersion >= 6 then begin
  574. if not Assigned(WinGetTickCount64) then begin
  575. lib := LoadLibrary('kernel32.dll');
  576. WinGetTickCount64 := TGetTickCount64(
  577. GetProcAddress(lib, 'GetTickCount64'));
  578. end;
  579. Result := WinGetTickCount64();
  580. end else
  581. {$ENDIF}
  582. Result := Windows.GetTickCount;
  583. end;
  584. {****************************************************************************
  585. Misc Functions
  586. ****************************************************************************}
  587. procedure sysbeep;
  588. begin
  589. MessageBeep(0);
  590. end;
  591. {****************************************************************************
  592. Locale Functions
  593. ****************************************************************************}
  594. function GetLocaleStr(LID, LT: Longint; const Def: string): ShortString;
  595. var
  596. L: Integer;
  597. Buf: array[0..255] of Char;
  598. begin
  599. L := GetLocaleInfoA(LID, LT, Buf, SizeOf(Buf));
  600. if L > 0 then
  601. SetString(Result, @Buf[0], L - 1)
  602. else
  603. Result := Def;
  604. end;
  605. function GetLocaleChar(LID, LT: Longint; Def: Char): Char;
  606. var
  607. Buf: array[0..3] of Char; // sdate allows 4 chars.
  608. begin
  609. if GetLocaleInfoA(LID, LT, Buf, sizeof(buf)) > 0 then
  610. Result := Buf[0]
  611. else
  612. Result := Def;
  613. end;
  614. function ConvertEraString(Count ,Year,Month,Day : integer) : string;
  615. var
  616. ASystemTime: TSystemTime;
  617. wbuf: array[0..100] of WideChar;
  618. ALCID : LCID;
  619. begin
  620. Result := ''; if (Count<=0) then exit;
  621. DateTimeToSystemTime(EncodeDate(Year,Month,Day),ASystemTime);
  622. ALCID := GetThreadLocale;
  623. // ALCID := SysLocale.DefaultLCID;
  624. if GetDateFormatW(ALCID , DATE_USE_ALT_CALENDAR
  625. , @ASystemTime, PWChar('gg')
  626. , @wbuf, SizeOf(wbuf)) > 0 then
  627. begin
  628. if Count = 1 then
  629. wbuf[1] := #0;
  630. Result := string(WideString(wbuf));
  631. end;
  632. end;
  633. function ConvertEraYearString(Count ,Year,Month,Day : integer) : string;
  634. var
  635. ALCID : LCID;
  636. ASystemTime : TSystemTime;
  637. AFormatText : string;
  638. buf : array[0..100] of Char;
  639. begin
  640. Result := '';
  641. DateTimeToSystemTime(EncodeDate(Year,Month,Day),ASystemTime);
  642. if Count <= 2 then
  643. AFormatText := 'yy'
  644. else
  645. AFormatText := 'yyyy';
  646. ALCID := GetThreadLocale;
  647. // ALCID := SysLocale.DefaultLCID;
  648. if GetDateFormatA(ALCID, DATE_USE_ALT_CALENDAR
  649. , @ASystemTime, PChar(AFormatText)
  650. , @buf, SizeOf(buf)) > 0 then
  651. begin
  652. Result := buf;
  653. if (Count = 1) and (Result[1] = '0') then
  654. Result := Copy(Result, 2, Length(Result)-1);
  655. end;
  656. end;
  657. Function GetLocaleInt(LID,TP,Def: LongInt): LongInt;
  658. Var
  659. S: String;
  660. C: Integer;
  661. Begin
  662. S:=GetLocaleStr(LID,TP,'0');
  663. Val(S,Result,C);
  664. If C<>0 Then
  665. Result:=Def;
  666. End;
  667. function EnumEraNames(Names: PChar): WINBOOL; stdcall;
  668. var
  669. i : integer;
  670. begin
  671. Result := False;
  672. for i := Low(EraNames) to High(EraNames) do
  673. if (EraNames[i] = '') then
  674. begin
  675. EraNames[i] := Names;
  676. Result := True;
  677. break;
  678. end;
  679. end;
  680. function EnumEraYearOffsets(YearOffsets: PChar): WINBOOL; stdcall;
  681. var
  682. i : integer;
  683. begin
  684. Result := False;
  685. for i := Low(EraYearOffsets) to High(EraYearOffsets) do
  686. if (EraYearOffsets[i] = -1) then
  687. begin
  688. EraYearOffsets[i] := StrToIntDef(YearOffsets, 0);
  689. Result := True;
  690. break;
  691. end;
  692. end;
  693. procedure GetEraNamesAndYearOffsets;
  694. var
  695. ACALID : CALID;
  696. ALCID : LCID;
  697. buf : array[0..10] of char;
  698. i : integer;
  699. begin
  700. for i:= 1 to MaxEraCount do
  701. begin
  702. EraNames[i] := ''; EraYearOffsets[i] := -1;
  703. end;
  704. ALCID := GetThreadLocale;
  705. if GetLocaleInfoA(ALCID , LOCALE_IOPTIONALCALENDAR, buf, sizeof(buf)) <= 0 then exit;
  706. ACALID := StrToIntDef(buf,1);
  707. if ACALID in [3..5] then
  708. begin
  709. EnumCalendarInfoA(@EnumEraNames, ALCID, ACALID , CAL_SERASTRING);
  710. EnumCalendarInfoA(@EnumEraYearOffsets, ALCID, ACALID, CAL_IYEAROFFSETRANGE);
  711. end;
  712. (*
  713. 1 CAL_GREGORIAN Gregorian (localized)
  714. 2 CAL_GREGORIAN_US Gregorian (English strings always)
  715. 3 CAL_JAPAN Japanese Emperor Era
  716. 4 CAL_TAIWAN Taiwan Calendar
  717. 5 CAL_KOREA Korean Tangun Era
  718. 6 CAL_HIJRI Hijri (Arabic Lunar)
  719. 7 CAL_THAI Thai
  720. 8 CAL_HEBREW Hebrew (Lunar)
  721. 9 CAL_GREGORIAN_ME_FRENCH Gregorian Middle East French
  722. 10 CAL_GREGORIAN_ARABIC Gregorian Arabic
  723. 11 CAL_GREGORIAN_XLIT_ENGLISH Gregorian transliterated English
  724. 12 CAL_GREGORIAN_XLIT_FRENCH Gregorian transliterated French
  725. 23 CAL_UMALQURA Windows Vista or later: Um Al Qura (Arabic lunar) calendar
  726. *)
  727. end;
  728. procedure GetLocaleFormatSettings(LCID: Integer; var FormatSettings: TFormatSettings);
  729. var
  730. HF : Shortstring;
  731. LID : Windows.LCID;
  732. I,Day : longint;
  733. begin
  734. LID := LCID;
  735. with FormatSettings do
  736. begin
  737. { Date stuff }
  738. for I := 1 to 12 do
  739. begin
  740. ShortMonthNames[I]:=GetLocaleStr(LID,LOCALE_SABBREVMONTHNAME1+I-1,ShortMonthNames[i]);
  741. LongMonthNames[I]:=GetLocaleStr(LID,LOCALE_SMONTHNAME1+I-1,LongMonthNames[i]);
  742. end;
  743. for I := 1 to 7 do
  744. begin
  745. Day := (I + 5) mod 7;
  746. ShortDayNames[I]:=GetLocaleStr(LID,LOCALE_SABBREVDAYNAME1+Day,ShortDayNames[i]);
  747. LongDayNames[I]:=GetLocaleStr(LID,LOCALE_SDAYNAME1+Day,LongDayNames[i]);
  748. end;
  749. DateSeparator := GetLocaleChar(LID, LOCALE_SDATE, '/');
  750. ShortDateFormat := GetLocaleStr(LID, LOCALE_SSHORTDATE, 'm/d/yy');
  751. LongDateFormat := GetLocaleStr(LID, LOCALE_SLONGDATE, 'mmmm d, yyyy');
  752. { Time stuff }
  753. TimeSeparator := GetLocaleChar(LID, LOCALE_STIME, ':');
  754. TimeAMString := GetLocaleStr(LID, LOCALE_S1159, 'AM');
  755. TimePMString := GetLocaleStr(LID, LOCALE_S2359, 'PM');
  756. if StrToIntDef(GetLocaleStr(LID, LOCALE_ITLZERO, '0'), 0) = 0 then
  757. HF:='h'
  758. else
  759. HF:='hh';
  760. // No support for 12 hour stuff at the moment...
  761. ShortTimeFormat := HF+':nn';
  762. LongTimeFormat := HF + ':nn:ss';
  763. { Currency stuff }
  764. CurrencyString:=GetLocaleStr(LID, LOCALE_SCURRENCY, '');
  765. CurrencyFormat:=StrToIntDef(GetLocaleStr(LID, LOCALE_ICURRENCY, '0'), 0);
  766. NegCurrFormat:=StrToIntDef(GetLocaleStr(LID, LOCALE_INEGCURR, '0'), 0);
  767. { Number stuff }
  768. ThousandSeparator:=GetLocaleChar(LID, LOCALE_STHOUSAND, ',');
  769. DecimalSeparator:=GetLocaleChar(LID, LOCALE_SDECIMAL, '.');
  770. CurrencyDecimals:=StrToIntDef(GetLocaleStr(LID, LOCALE_ICURRDIGITS, '0'), 0);
  771. ListSeparator := GetLocaleChar(LID, LOCALE_SLIST, ',');
  772. end;
  773. end;
  774. procedure GetFormatSettings;
  775. begin
  776. GetlocaleFormatSettings(GetThreadLocale, DefaultFormatSettings);
  777. end;
  778. Procedure InitInternational;
  779. var
  780. { A call to GetSystemMetrics changes the value of the 8087 Control Word on
  781. Pentium4 with WinXP SP2 }
  782. old8087CW: word;
  783. DefaultCustomLocaleID : LCID; // typedef DWORD LCID;
  784. DefaultCustomLanguageID : Word; // typedef WORD LANGID;
  785. begin
  786. /// workaround for Windows 7 bug, see bug report #18574
  787. SetThreadLocale(GetUserDefaultLCID);
  788. InitInternationalGeneric;
  789. old8087CW:=Get8087CW;
  790. SysLocale.MBCS:=GetSystemMetrics(SM_DBCSENABLED)<>0;
  791. SysLocale.RightToLeft:=GetSystemMetrics(SM_MIDEASTENABLED)<>0;
  792. SysLocale.DefaultLCID := $0409;
  793. SysLocale.PriLangID := LANG_ENGLISH;
  794. SysLocale.SubLangID := SUBLANG_ENGLISH_US;
  795. // probably needs update with getthreadlocale. post 2.0.2
  796. DefaultCustomLocaleID := GetThreadLocale;
  797. if DefaultCustomLocaleID <> 0 then
  798. begin
  799. { Locale Identifiers
  800. +-------------+---------+-------------------------+
  801. | Reserved | Sort ID | Language ID |
  802. +-------------+---------+-------------------------+
  803. 31 20 19 16 15 0 bit }
  804. DefaultCustomLanguageID := DefaultCustomLocaleID and $FFFF; // 2^16
  805. if DefaultCustomLanguageID <> 0 then
  806. begin
  807. SysLocale.DefaultLCID := DefaultCustomLocaleID;
  808. { Language Identifiers
  809. +-------------------------+-------------------------+
  810. | SubLanguage ID | Primary Language ID |
  811. +-------------------------+-------------------------+
  812. 15 10 9 0 bit }
  813. SysLocale.PriLangID := DefaultCustomLanguageID and $3ff; // 2^10
  814. SysLocale.SubLangID := DefaultCustomLanguageID shr 10;
  815. end;
  816. end;
  817. Set8087CW(old8087CW);
  818. GetFormatSettings;
  819. if SysLocale.FarEast then GetEraNamesAndYearOffsets;
  820. end;
  821. {****************************************************************************
  822. Target Dependent
  823. ****************************************************************************}
  824. function SysErrorMessage(ErrorCode: Integer): String;
  825. const
  826. MaxMsgSize = Format_Message_Max_Width_Mask;
  827. var
  828. MsgBuffer: unicodestring;
  829. len: longint;
  830. begin
  831. SetLength(MsgBuffer, MaxMsgSize);
  832. len := FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM,
  833. nil,
  834. ErrorCode,
  835. MakeLangId(LANG_NEUTRAL, SUBLANG_DEFAULT),
  836. PUnicodeChar(MsgBuffer),
  837. MaxMsgSize,
  838. nil);
  839. // Remove trailing #13#10
  840. if (len > 1) and (MsgBuffer[len - 1] = #13) and (MsgBuffer[len] = #10) then
  841. Dec(len, 2);
  842. SetLength(MsgBuffer, len);
  843. Result := MsgBuffer;
  844. end;
  845. {****************************************************************************
  846. Initialization code
  847. ****************************************************************************}
  848. {$push}
  849. { GetEnvironmentStrings cannot be checked by CheckPointer function }
  850. {$checkpointer off}
  851. Function GetEnvironmentVariable(Const EnvVar : String) : String;
  852. var
  853. oemenvvar, oemstr : RawByteString;
  854. i, hplen : longint;
  855. hp,p : pchar;
  856. begin
  857. oemenvvar:=uppercase(envvar);
  858. SetCodePage(oemenvvar,CP_OEMCP);
  859. Result:='';
  860. p:=GetEnvironmentStringsA;
  861. hp:=p;
  862. while hp^<>#0 do
  863. begin
  864. oemstr:=hp;
  865. { cache length, may change after uppercasing depending on code page }
  866. hplen:=length(oemstr);
  867. { all environment variables are encoded in the oem code page }
  868. SetCodePage(oemstr,CP_OEMCP,false);
  869. i:=pos('=',oemstr);
  870. if uppercase(copy(oemstr,1,i-1))=oemenvvar then
  871. begin
  872. Result:=copy(oemstr,i+1,length(oemstr)-i);
  873. break;
  874. end;
  875. { next string entry}
  876. hp:=hp+hplen+1;
  877. end;
  878. FreeEnvironmentStringsA(p);
  879. end;
  880. Function GetEnvironmentVariable(Const EnvVar : UnicodeString) : UnicodeString;
  881. var
  882. s, upperenv : Unicodestring;
  883. i : longint;
  884. hp,p : pwidechar;
  885. begin
  886. Result:='';
  887. p:=GetEnvironmentStringsW;
  888. hp:=p;
  889. upperenv:=uppercase(envvar);
  890. while hp^<>#0 do
  891. begin
  892. s:=hp;
  893. i:=pos('=',s);
  894. if uppercase(copy(s,1,i-1))=upperenv then
  895. begin
  896. Result:=copy(s,i+1,length(s)-i);
  897. break;
  898. end;
  899. { next string entry}
  900. hp:=hp+strlen(hp)+1;
  901. end;
  902. FreeEnvironmentStringsW(p);
  903. end;
  904. Function GetEnvironmentVariableCount : Integer;
  905. var
  906. hp,p : pchar;
  907. begin
  908. Result:=0;
  909. p:=GetEnvironmentStringsA;
  910. hp:=p;
  911. If (Hp<>Nil) then
  912. while hp^<>#0 do
  913. begin
  914. Inc(Result);
  915. hp:=hp+strlen(hp)+1;
  916. end;
  917. FreeEnvironmentStringsA(p);
  918. end;
  919. Function GetEnvironmentString(Index : Integer) : {$ifdef FPC_RTL_UNICODE}UnicodeString{$else}AnsiString{$endif};
  920. var
  921. hp,p : pchar;
  922. {$ifdef FPC_RTL_UNICODE}
  923. tmpstr : RawByteString;
  924. {$endif}
  925. begin
  926. Result:='';
  927. p:=GetEnvironmentStringsA;
  928. hp:=p;
  929. If (Hp<>Nil) then
  930. begin
  931. while (hp^<>#0) and (Index>1) do
  932. begin
  933. Dec(Index);
  934. hp:=hp+strlen(hp)+1;
  935. end;
  936. If (hp^<>#0) then
  937. begin
  938. {$ifdef FPC_RTL_UNICODE}
  939. tmpstr:=hp;
  940. SetCodePage(tmpstr,CP_OEMCP,false);
  941. Result:=tmpstr;
  942. {$else}
  943. Result:=hp;
  944. SetCodePage(RawByteString(Result),CP_OEMCP,false);
  945. {$endif}
  946. end;
  947. end;
  948. FreeEnvironmentStringsA(p);
  949. end;
  950. {$pop}
  951. function ExecuteProcess(Const Path: RawByteString; Const ComLine: RawByteString;Flags:TExecuteFlags=[]):integer;
  952. begin
  953. result:=ExecuteProcess(Unicodestring(Path),UnicodeString(ComLine),Flags);
  954. end;
  955. function ExecuteProcess(Const Path: UnicodeString; Const ComLine: UnicodeString;Flags:TExecuteFlags=[]):integer;
  956. // win specific function
  957. var
  958. SI: TStartupInfoW;
  959. PI: TProcessInformation;
  960. Proc : THandle;
  961. l : DWord;
  962. CommandLine : unicodestring;
  963. e : EOSError;
  964. ExecInherits : longbool;
  965. begin
  966. FillChar(SI, SizeOf(SI), 0);
  967. SI.cb:=SizeOf(SI);
  968. SI.wShowWindow:=1;
  969. { always surround the name of the application by quotes
  970. so that long filenames will always be accepted. But don't
  971. do it if there are already double quotes, since Win32 does not
  972. like double quotes which are duplicated!
  973. }
  974. if pos('"',path)=0 then
  975. CommandLine:='"'+path+'"'
  976. else
  977. CommandLine:=path;
  978. if ComLine <> '' then
  979. CommandLine:=Commandline+' '+ComLine+#0
  980. else
  981. CommandLine := CommandLine + #0;
  982. ExecInherits:=ExecInheritsHandles in Flags;
  983. if not CreateProcessW(nil, pwidechar(CommandLine),
  984. Nil, Nil, ExecInherits,$20, Nil, Nil, SI, PI) then
  985. begin
  986. e:=EOSError.CreateFmt(SExecuteProcessFailed,[CommandLine,GetLastError]);
  987. e.ErrorCode:=GetLastError;
  988. raise e;
  989. end;
  990. Proc:=PI.hProcess;
  991. if WaitForSingleObject(Proc, dword($ffffffff)) <> $ffffffff then
  992. begin
  993. GetExitCodeProcess(Proc,l);
  994. CloseHandle(Proc);
  995. CloseHandle(PI.hThread);
  996. result:=l;
  997. end
  998. else
  999. begin
  1000. e:=EOSError.CreateFmt(SExecuteProcessFailed,[CommandLine,GetLastError]);
  1001. e.ErrorCode:=GetLastError;
  1002. CloseHandle(Proc);
  1003. CloseHandle(PI.hThread);
  1004. raise e;
  1005. end;
  1006. end;
  1007. function ExecuteProcess(Const Path: RawByteString; Const ComLine: Array of RawByteString;Flags:TExecuteFlags=[]):integer;
  1008. var
  1009. CommandLine: UnicodeString;
  1010. I: integer;
  1011. begin
  1012. Commandline := '';
  1013. for I := 0 to High (ComLine) do
  1014. if Pos (' ', ComLine [I]) <> 0 then
  1015. CommandLine := CommandLine + ' ' + '"' + ComLine [I] + '"'
  1016. else
  1017. CommandLine := CommandLine + ' ' + Comline [I];
  1018. ExecuteProcess := ExecuteProcess (UnicodeString(Path), CommandLine,Flags);
  1019. end;
  1020. function ExecuteProcess(Const Path: UnicodeString; Const ComLine: Array of UnicodeString;Flags:TExecuteFlags=[]):integer;
  1021. var
  1022. CommandLine: UnicodeString;
  1023. I: integer;
  1024. begin
  1025. Commandline := '';
  1026. for I := 0 to High (ComLine) do
  1027. if Pos (' ', ComLine [I]) <> 0 then
  1028. CommandLine := CommandLine + ' ' + '"' + ComLine [I] + '"'
  1029. else
  1030. CommandLine := CommandLine + ' ' + Comline [I];
  1031. ExecuteProcess := ExecuteProcess (Path,CommandLine,Flags);
  1032. end;
  1033. Procedure Sleep(Milliseconds : Cardinal);
  1034. begin
  1035. Windows.Sleep(MilliSeconds)
  1036. end;
  1037. Function GetLastOSError : Integer;
  1038. begin
  1039. Result:=GetLastError;
  1040. end;
  1041. {****************************************************************************
  1042. Initialization code
  1043. ****************************************************************************}
  1044. var
  1045. kernel32dll : THandle;
  1046. Procedure LoadVersionInfo;
  1047. // and getfreespaceex
  1048. Var
  1049. versioninfo : TOSVERSIONINFO;
  1050. begin
  1051. GetDiskFreeSpaceEx:=nil;
  1052. versioninfo.dwOSVersionInfoSize:=sizeof(versioninfo);
  1053. GetVersionEx(versioninfo);
  1054. Win32Platform:=versionInfo.dwPlatformId;
  1055. Win32MajorVersion:=versionInfo.dwMajorVersion;
  1056. Win32MinorVersion:=versionInfo.dwMinorVersion;
  1057. Win32BuildNumber:=versionInfo.dwBuildNumber;
  1058. Move (versioninfo.szCSDVersion ,Win32CSDVersion[1],128);
  1059. win32CSDVersion[0]:=chr(strlen(pchar(@versioninfo.szCSDVersion)));
  1060. kernel32dll:=GetModuleHandle('kernel32');
  1061. if kernel32dll<>0 then
  1062. GetDiskFreeSpaceEx:=TGetDiskFreeSpaceEx(GetProcAddress(kernel32dll,'GetDiskFreeSpaceExA'));
  1063. end;
  1064. Function GetAppConfigDir(Global : Boolean) : String;
  1065. begin
  1066. If Global then
  1067. Result:=GetWindowsSpecialDir(CSIDL_COMMON_APPDATA)
  1068. else
  1069. Result:=GetWindowsSpecialDir(CSIDL_LOCAL_APPDATA);
  1070. If (Result<>'') then
  1071. begin
  1072. if VendorName<>'' then
  1073. Result:=IncludeTrailingPathDelimiter(Result+VendorName);
  1074. Result:=IncludeTrailingPathDelimiter(Result+ApplicationName);
  1075. end
  1076. else
  1077. Result:=IncludeTrailingPathDelimiter(DGetAppConfigDir(Global));
  1078. end;
  1079. Function GetAppConfigFile(Global : Boolean; SubDir : Boolean) : String;
  1080. begin
  1081. result:=DGetAppConfigFile(Global,SubDir);
  1082. end;
  1083. Function GetUserDir : String;
  1084. begin
  1085. Result:=GetWindowsSpecialDir(CSIDL_PROFILE);
  1086. end;
  1087. Procedure InitSysConfigDir;
  1088. begin
  1089. SetLength(SysConfigDir, MAX_PATH);
  1090. SetLength(SysConfigDir, GetWindowsDirectoryA(PChar(SysConfigDir), MAX_PATH));
  1091. end;
  1092. {****************************************************************************
  1093. Target Dependent WideString stuff
  1094. ****************************************************************************}
  1095. { This is the case of Win9x. Limited to current locale of course, but it's better
  1096. than not working at all. }
  1097. function DoCompareStringA(P1, P2: PWideChar; L1, L2: PtrUInt; Flags: DWORD): PtrInt;
  1098. var
  1099. a1, a2: AnsiString;
  1100. begin
  1101. if L1>0 then
  1102. widestringmanager.Wide2AnsiMoveProc(P1,a1,DefaultSystemCodePage,L1);
  1103. if L2>0 then
  1104. widestringmanager.Wide2AnsiMoveProc(P2,a2,DefaultSystemCodePage,L2);
  1105. SetLastError(0);
  1106. Result:=CompareStringA(LOCALE_USER_DEFAULT,Flags,pchar(a1),
  1107. length(a1),pchar(a2),length(a2))-2;
  1108. end;
  1109. function DoCompareStringW(P1, P2: PWideChar; L1, L2: PtrUInt; Flags: DWORD): PtrInt;
  1110. begin
  1111. SetLastError(0);
  1112. Result:=CompareStringW(LOCALE_USER_DEFAULT,Flags,P1,L1,P2,L2)-2;
  1113. if GetLastError=0 then
  1114. Exit;
  1115. if GetLastError=ERROR_CALL_NOT_IMPLEMENTED then // Win9x case
  1116. Result:=DoCompareStringA(P1, P2, L1, L2, Flags);
  1117. if GetLastError<>0 then
  1118. RaiseLastOSError;
  1119. end;
  1120. const
  1121. WinAPICompareFlags : array [TCompareOption] of LongWord
  1122. = ({LINGUISTIC_IGNORECASE, LINGUISTIC_IGNOREDIACRITIC, }NORM_IGNORECASE{,
  1123. NORM_IGNOREKANATYPE, NORM_IGNORENONSPACE, NORM_IGNORESYMBOLS, NORM_IGNOREWIDTH,
  1124. NORM_LINGUISTIC_CASING, SORT_DIGITSASNUMBERS, SORT_STRINGSORT});
  1125. function Win32CompareWideString(const s1, s2 : WideString; Options : TCompareOptions) : PtrInt;
  1126. Var
  1127. O : LongWord;
  1128. CO : TCompareOption;
  1129. begin
  1130. O:=0;
  1131. for CO in TCompareOption do
  1132. if CO in Options then
  1133. O:=O or WinAPICompareFlags[CO];
  1134. Result:=DoCompareStringW(PWideChar(s1), PWideChar(s2), Length(s1), Length(s2), O);
  1135. end;
  1136. function Win32CompareTextWideString(const s1, s2 : WideString) : PtrInt;
  1137. begin
  1138. Result:=DoCompareStringW(PWideChar(s1), PWideChar(s2), Length(s1), Length(s2), NORM_IGNORECASE);
  1139. end;
  1140. function Win32AnsiUpperCase(const s: string): string;
  1141. begin
  1142. if length(s)>0 then
  1143. begin
  1144. result:=s;
  1145. UniqueString(result);
  1146. CharUpperBuffA(pchar(result),length(result));
  1147. end
  1148. else
  1149. result:='';
  1150. end;
  1151. function Win32AnsiLowerCase(const s: string): string;
  1152. begin
  1153. if length(s)>0 then
  1154. begin
  1155. result:=s;
  1156. UniqueString(result);
  1157. CharLowerBuffA(pchar(result),length(result));
  1158. end
  1159. else
  1160. result:='';
  1161. end;
  1162. function Win32AnsiCompareStr(const S1, S2: string): PtrInt;
  1163. begin
  1164. result:=CompareStringA(LOCALE_USER_DEFAULT,0,pchar(s1),length(s1),
  1165. pchar(s2),length(s2))-2;
  1166. end;
  1167. function Win32AnsiCompareText(const S1, S2: string): PtrInt;
  1168. begin
  1169. result:=CompareStringA(LOCALE_USER_DEFAULT,NORM_IGNORECASE,pchar(s1),length(s1),
  1170. pchar(s2),length(s2))-2;
  1171. end;
  1172. function Win32AnsiStrComp(S1, S2: PChar): PtrInt;
  1173. begin
  1174. result:=CompareStringA(LOCALE_USER_DEFAULT,0,s1,-1,s2,-1)-2;
  1175. end;
  1176. function Win32AnsiStrIComp(S1, S2: PChar): PtrInt;
  1177. begin
  1178. result:=CompareStringA(LOCALE_USER_DEFAULT,NORM_IGNORECASE,s1,-1,s2,-1)-2;
  1179. end;
  1180. function Win32AnsiStrLComp(S1, S2: PChar; MaxLen: PtrUInt): PtrInt;
  1181. begin
  1182. result:=CompareStringA(LOCALE_USER_DEFAULT,0,s1,maxlen,s2,maxlen)-2;
  1183. end;
  1184. function Win32AnsiStrLIComp(S1, S2: PChar; MaxLen: PtrUInt): PtrInt;
  1185. begin
  1186. result:=CompareStringA(LOCALE_USER_DEFAULT,NORM_IGNORECASE,s1,maxlen,s2,maxlen)-2;
  1187. end;
  1188. function Win32AnsiStrLower(Str: PChar): PChar;
  1189. begin
  1190. CharLowerA(str);
  1191. result:=str;
  1192. end;
  1193. function Win32AnsiStrUpper(Str: PChar): PChar;
  1194. begin
  1195. CharUpperA(str);
  1196. result:=str;
  1197. end;
  1198. function Win32CompareUnicodeString(const s1, s2 : UnicodeString; Options : TCompareOptions) : PtrInt;
  1199. Var
  1200. O : LongWord;
  1201. CO : TCompareOption;
  1202. begin
  1203. O:=0;
  1204. for CO in TCompareOption do
  1205. if CO in Options then
  1206. O:=O or WinAPICompareFlags[CO];
  1207. Result:=DoCompareStringW(PWideChar(s1), PWideChar(s2), Length(s1), Length(s2), O);
  1208. end;
  1209. function Win32CompareTextUnicodeString(const s1, s2 : UnicodeString) : PtrInt;
  1210. begin
  1211. Result:=DoCompareStringW(PWideChar(s1), PWideChar(s2), Length(s1), Length(s2), NORM_IGNORECASE);
  1212. end;
  1213. { there is a similiar procedure in the system unit which inits the fields which
  1214. are relevant already for the system unit }
  1215. procedure InitWin32Widestrings;
  1216. begin
  1217. { return value: number of code points in the string. Whenever an invalid
  1218. code point is encountered, all characters part of this invalid code point
  1219. are considered to form one "character" and the next character is
  1220. considered to be the start of a new (possibly also invalid) code point }
  1221. //!!! CharLengthPCharProc : function(const Str: PChar): PtrInt;
  1222. { return value:
  1223. -1 if incomplete or invalid code point
  1224. 0 if NULL character,
  1225. > 0 if that's the length in bytes of the code point }
  1226. //!!!! CodePointLengthProc : function(const Str: PChar; MaxLookAead: PtrInt): Ptrint;
  1227. widestringmanager.CompareWideStringProc:=@Win32CompareWideString;
  1228. widestringmanager.UpperAnsiStringProc:=@Win32AnsiUpperCase;
  1229. widestringmanager.LowerAnsiStringProc:=@Win32AnsiLowerCase;
  1230. widestringmanager.CompareStrAnsiStringProc:=@Win32AnsiCompareStr;
  1231. widestringmanager.CompareTextAnsiStringProc:=@Win32AnsiCompareText;
  1232. widestringmanager.StrCompAnsiStringProc:=@Win32AnsiStrComp;
  1233. widestringmanager.StrICompAnsiStringProc:=@Win32AnsiStrIComp;
  1234. widestringmanager.StrLCompAnsiStringProc:=@Win32AnsiStrLComp;
  1235. widestringmanager.StrLICompAnsiStringProc:=@Win32AnsiStrLIComp;
  1236. widestringmanager.StrLowerAnsiStringProc:=@Win32AnsiStrLower;
  1237. widestringmanager.StrUpperAnsiStringProc:=@Win32AnsiStrUpper;
  1238. widestringmanager.CompareUnicodeStringProc:=@Win32CompareUnicodeString;
  1239. end;
  1240. { Platform-specific exception support }
  1241. function WinExceptionObject(code: Longint; const rec: TExceptionRecord): Exception;
  1242. var
  1243. entry: PExceptMapEntry;
  1244. begin
  1245. entry := FindExceptMapEntry(code);
  1246. if assigned(entry) then
  1247. result:=entry^.cls.CreateRes(entry^.msg)
  1248. else
  1249. result:=EExternalException.CreateResFmt(@SExternalException,[rec.ExceptionCode]);
  1250. if result is EExternal then
  1251. EExternal(result).FExceptionRecord:=rec;
  1252. end;
  1253. function WinExceptionClass(code: longint): ExceptClass;
  1254. var
  1255. entry: PExceptMapEntry;
  1256. begin
  1257. entry := FindExceptMapEntry(code);
  1258. if assigned(entry) then
  1259. result:=entry^.cls
  1260. else
  1261. result:=EExternalException;
  1262. end;
  1263. Initialization
  1264. InitWin32Widestrings;
  1265. InitExceptions; { Initialize exceptions. OS independent }
  1266. {$ifdef mswindows} { Keeps exe size down for systems that do not use SEH }
  1267. ExceptObjProc:=@WinExceptionObject;
  1268. ExceptClsProc:=@WinExceptionClass;
  1269. {$endif mswindows}
  1270. InitInternational; { Initialize internationalization settings }
  1271. LoadVersionInfo;
  1272. InitSysConfigDir;
  1273. OnBeep:=@SysBeep;
  1274. Finalization
  1275. DoneExceptions;
  1276. end.