sysutils.pp 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508
  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 FileGetSymLinkTarget(const FileName: UnicodeString; out SymLinkRec: TUnicodeSymLinkRec): Boolean;
  332. begin
  333. Result := False;
  334. end;
  335. Function FileExists (Const FileName : UnicodeString; FollowLink : Boolean) : Boolean;
  336. var
  337. Attr:Dword;
  338. begin
  339. Attr:=GetFileAttributesW(PWideChar(FileName));
  340. if Attr <> $ffffffff then
  341. Result:= (Attr and FILE_ATTRIBUTE_DIRECTORY) = 0
  342. else
  343. Result:=False;
  344. end;
  345. Function DirectoryExists (Const Directory : UnicodeString; FollowLink : Boolean) : Boolean;
  346. var
  347. Attr:Dword;
  348. begin
  349. Attr:=GetFileAttributesW(PWideChar(Directory));
  350. if Attr <> $ffffffff then
  351. Result:= (Attr and FILE_ATTRIBUTE_DIRECTORY) > 0
  352. else
  353. Result:=False;
  354. end;
  355. Function FindMatch(var f: TAbstractSearchRec; var Name: UnicodeString) : Longint;
  356. begin
  357. { Find file with correct attribute }
  358. While (F.FindData.dwFileAttributes and cardinal(F.ExcludeAttr))<>0 do
  359. begin
  360. if not FindNextFileW (F.FindHandle,F.FindData) then
  361. begin
  362. Result:=GetLastError;
  363. exit;
  364. end;
  365. end;
  366. { Convert some attributes back }
  367. WinToDosTime(F.FindData.ftLastWriteTime,F.Time);
  368. f.size:=F.FindData.NFileSizeLow+(qword(maxdword)+1)*F.FindData.NFileSizeHigh;
  369. f.attr:=F.FindData.dwFileAttributes;
  370. Name:=F.FindData.cFileName;
  371. Result:=0;
  372. end;
  373. Procedure InternalFindClose (var Handle: THandle; var FindData: TFindData);
  374. begin
  375. if Handle <> INVALID_HANDLE_VALUE then
  376. begin
  377. Windows.FindClose(Handle);
  378. Handle:=INVALID_HANDLE_VALUE;
  379. end;
  380. end;
  381. Function InternalFindFirst (Const Path : UnicodeString; Attr : Longint; out Rslt : TAbstractSearchRec; var Name : UnicodeString) : Longint;
  382. begin
  383. Name:=Path;
  384. Rslt.Attr:=attr;
  385. Rslt.ExcludeAttr:=(not Attr) and ($1e);
  386. { $1e = faHidden or faSysFile or faVolumeID or faDirectory }
  387. { FindFirstFile is a Win32 Call }
  388. Rslt.FindHandle:=FindFirstFileW (PWideChar(Path),Rslt.FindData);
  389. If Rslt.FindHandle=Invalid_Handle_value then
  390. begin
  391. Result:=GetLastError;
  392. exit;
  393. end;
  394. { Find file with correct attribute }
  395. Result:=FindMatch(Rslt,Name);
  396. if (Result<>0) then
  397. InternalFindClose(Rslt.FindHandle,Rslt.FindData);
  398. end;
  399. Function InternalFindNext (Var Rslt : TAbstractSearchRec; var Name: UnicodeString) : Longint;
  400. begin
  401. if FindNextFileW(Rslt.FindHandle, Rslt.FindData) then
  402. Result := FindMatch(Rslt, Name)
  403. else
  404. Result := GetLastError;
  405. end;
  406. Function FileGetDate (Handle : THandle) : Longint;
  407. Var
  408. FT : TFileTime;
  409. begin
  410. If GetFileTime(Handle,nil,nil,@ft) and
  411. WinToDosTime(FT,Result) then
  412. exit;
  413. Result:=-1;
  414. end;
  415. Function FileSetDate (Handle : THandle;Age : Longint) : Longint;
  416. Var
  417. FT: TFileTime;
  418. begin
  419. Result := 0;
  420. if DosToWinTime(Age,FT) and
  421. SetFileTime(Handle, nil, nil, @FT) then
  422. Exit;
  423. Result := GetLastError;
  424. end;
  425. {$IFDEF OS_FILESETDATEBYNAME}
  426. Function FileSetDate (Const FileName : UnicodeString;Age : Longint) : Longint;
  427. Var
  428. fd : THandle;
  429. begin
  430. FD := CreateFileW (PWideChar (FileName), GENERIC_READ or GENERIC_WRITE,
  431. FILE_SHARE_WRITE, nil, OPEN_EXISTING,
  432. FILE_FLAG_BACKUP_SEMANTICS, 0);
  433. If (Fd<>feInvalidHandle) then
  434. try
  435. Result:=FileSetDate(fd,Age);
  436. finally
  437. FileClose(fd);
  438. end
  439. else
  440. Result:=GetLastOSError;
  441. end;
  442. {$ENDIF}
  443. Function FileGetAttr (Const FileName : UnicodeString) : Longint;
  444. begin
  445. Result:=Longint(GetFileAttributesW(PWideChar(FileName)));
  446. end;
  447. Function FileSetAttr (Const Filename : UnicodeString; Attr: longint) : Longint;
  448. begin
  449. if SetFileAttributesW(PWideChar(FileName), Attr) then
  450. Result:=0
  451. else
  452. Result := GetLastError;
  453. end;
  454. Function DeleteFile (Const FileName : UnicodeString) : Boolean;
  455. begin
  456. Result:=Windows.DeleteFileW(PWidechar(FileName));
  457. end;
  458. Function RenameFile (Const OldName, NewName : UnicodeString) : Boolean;
  459. begin
  460. Result := MoveFileW(PWideChar(OldName), PWideChar(NewName));
  461. end;
  462. {****************************************************************************
  463. Disk Functions
  464. ****************************************************************************}
  465. type
  466. TGetDiskFreeSpaceEx = function(drive:pchar;var availableforcaller,total,free):longbool;stdcall;
  467. var
  468. GetDiskFreeSpaceEx : TGetDiskFreeSpaceEx;
  469. function diskfree(drive : byte) : int64;
  470. var
  471. disk : array[1..4] of char;
  472. secs,bytes,
  473. free,total : dword;
  474. qwtotal,qwfree,qwcaller : int64;
  475. begin
  476. if drive=0 then
  477. begin
  478. disk[1]:='\';
  479. disk[2]:=#0;
  480. end
  481. else
  482. begin
  483. disk[1]:=chr(drive+64);
  484. disk[2]:=':';
  485. disk[3]:='\';
  486. disk[4]:=#0;
  487. end;
  488. if assigned(GetDiskFreeSpaceEx) then
  489. begin
  490. if GetDiskFreeSpaceEx(@disk[1],qwcaller,qwtotal,qwfree) then
  491. diskfree:=qwfree
  492. else
  493. diskfree:=-1;
  494. end
  495. else
  496. begin
  497. if GetDiskFreeSpace(@disk[1],secs,bytes,free,total) then
  498. diskfree:=int64(free)*secs*bytes
  499. else
  500. diskfree:=-1;
  501. end;
  502. end;
  503. function disksize(drive : byte) : int64;
  504. var
  505. disk : array[1..4] of char;
  506. secs,bytes,
  507. free,total : dword;
  508. qwtotal,qwfree,qwcaller : int64;
  509. begin
  510. if drive=0 then
  511. begin
  512. disk[1]:='\';
  513. disk[2]:=#0;
  514. end
  515. else
  516. begin
  517. disk[1]:=chr(drive+64);
  518. disk[2]:=':';
  519. disk[3]:='\';
  520. disk[4]:=#0;
  521. end;
  522. if assigned(GetDiskFreeSpaceEx) then
  523. begin
  524. if GetDiskFreeSpaceEx(@disk[1],qwcaller,qwtotal,qwfree) then
  525. disksize:=qwtotal
  526. else
  527. disksize:=-1;
  528. end
  529. else
  530. begin
  531. if GetDiskFreeSpace(@disk[1],secs,bytes,free,total) then
  532. disksize:=int64(total)*secs*bytes
  533. else
  534. disksize:=-1;
  535. end;
  536. end;
  537. {****************************************************************************
  538. Time Functions
  539. ****************************************************************************}
  540. Procedure GetLocalTime(var SystemTime: TSystemTime);
  541. begin
  542. windows.Getlocaltime(SystemTime);
  543. end;
  544. function GetLocalTimeOffset: Integer;
  545. var
  546. TZInfo: TTimeZoneInformation;
  547. begin
  548. case GetTimeZoneInformation(TZInfo) of
  549. TIME_ZONE_ID_UNKNOWN:
  550. Result := TZInfo.Bias;
  551. TIME_ZONE_ID_STANDARD:
  552. Result := TZInfo.Bias + TZInfo.StandardBias;
  553. TIME_ZONE_ID_DAYLIGHT:
  554. Result := TZInfo.Bias + TZInfo.DaylightBias;
  555. else
  556. Result := 0;
  557. end;
  558. end;
  559. function GetTickCount: LongWord;
  560. begin
  561. Result := Windows.GetTickCount;
  562. end;
  563. {$IFNDEF WINCE}
  564. type
  565. TGetTickCount64 = function : QWord; stdcall;
  566. var
  567. WinGetTickCount64: TGetTickCount64 = Nil;
  568. {$ENDIF}
  569. function GetTickCount64: QWord;
  570. {$IFNDEF WINCE}
  571. var
  572. lib: THandle;
  573. {$ENDIF}
  574. begin
  575. {$IFNDEF WINCE}
  576. { on Vista and newer there is a GetTickCount64 implementation }
  577. if Win32MajorVersion >= 6 then begin
  578. if not Assigned(WinGetTickCount64) then begin
  579. lib := LoadLibrary('kernel32.dll');
  580. WinGetTickCount64 := TGetTickCount64(
  581. GetProcAddress(lib, 'GetTickCount64'));
  582. end;
  583. Result := WinGetTickCount64();
  584. end else
  585. {$ENDIF}
  586. Result := Windows.GetTickCount;
  587. end;
  588. {****************************************************************************
  589. Misc Functions
  590. ****************************************************************************}
  591. procedure sysbeep;
  592. begin
  593. MessageBeep(0);
  594. end;
  595. {****************************************************************************
  596. Locale Functions
  597. ****************************************************************************}
  598. function GetLocaleStr(LID, LT: Longint; const Def: string): ShortString;
  599. var
  600. L: Integer;
  601. Buf: array[0..255] of Char;
  602. begin
  603. L := GetLocaleInfoA(LID, LT, Buf, SizeOf(Buf));
  604. if L > 0 then
  605. SetString(Result, @Buf[0], L - 1)
  606. else
  607. Result := Def;
  608. end;
  609. function GetLocaleChar(LID, LT: Longint; Def: Char): Char;
  610. var
  611. Buf: array[0..3] of Char; // sdate allows 4 chars.
  612. begin
  613. if GetLocaleInfoA(LID, LT, Buf, sizeof(buf)) > 0 then
  614. Result := Buf[0]
  615. else
  616. Result := Def;
  617. end;
  618. function ConvertEraString(Count ,Year,Month,Day : integer) : string;
  619. var
  620. ASystemTime: TSystemTime;
  621. wbuf: array[0..100] of WideChar;
  622. ALCID : LCID;
  623. begin
  624. Result := ''; if (Count<=0) then exit;
  625. DateTimeToSystemTime(EncodeDate(Year,Month,Day),ASystemTime);
  626. ALCID := GetThreadLocale;
  627. // ALCID := SysLocale.DefaultLCID;
  628. if GetDateFormatW(ALCID , DATE_USE_ALT_CALENDAR
  629. , @ASystemTime, PWChar('gg')
  630. , @wbuf, SizeOf(wbuf)) > 0 then
  631. begin
  632. if Count = 1 then
  633. wbuf[1] := #0;
  634. Result := string(WideString(wbuf));
  635. end;
  636. end;
  637. function ConvertEraYearString(Count ,Year,Month,Day : integer) : string;
  638. var
  639. ALCID : LCID;
  640. ASystemTime : TSystemTime;
  641. AFormatText : string;
  642. buf : array[0..100] of Char;
  643. begin
  644. Result := '';
  645. DateTimeToSystemTime(EncodeDate(Year,Month,Day),ASystemTime);
  646. if Count <= 2 then
  647. AFormatText := 'yy'
  648. else
  649. AFormatText := 'yyyy';
  650. ALCID := GetThreadLocale;
  651. // ALCID := SysLocale.DefaultLCID;
  652. if GetDateFormatA(ALCID, DATE_USE_ALT_CALENDAR
  653. , @ASystemTime, PChar(AFormatText)
  654. , @buf, SizeOf(buf)) > 0 then
  655. begin
  656. Result := buf;
  657. if (Count = 1) and (Result[1] = '0') then
  658. Result := Copy(Result, 2, Length(Result)-1);
  659. end;
  660. end;
  661. Function GetLocaleInt(LID,TP,Def: LongInt): LongInt;
  662. Var
  663. S: String;
  664. C: Integer;
  665. Begin
  666. S:=GetLocaleStr(LID,TP,'0');
  667. Val(S,Result,C);
  668. If C<>0 Then
  669. Result:=Def;
  670. End;
  671. function EnumEraNames(Names: PChar): WINBOOL; stdcall;
  672. var
  673. i : integer;
  674. begin
  675. Result := False;
  676. for i := Low(EraNames) to High(EraNames) do
  677. if (EraNames[i] = '') then
  678. begin
  679. EraNames[i] := Names;
  680. Result := True;
  681. break;
  682. end;
  683. end;
  684. function EnumEraYearOffsets(YearOffsets: PChar): WINBOOL; stdcall;
  685. var
  686. i : integer;
  687. begin
  688. Result := False;
  689. for i := Low(EraYearOffsets) to High(EraYearOffsets) do
  690. if (EraYearOffsets[i] = -1) then
  691. begin
  692. EraYearOffsets[i] := StrToIntDef(YearOffsets, 0);
  693. Result := True;
  694. break;
  695. end;
  696. end;
  697. procedure GetEraNamesAndYearOffsets;
  698. var
  699. ACALID : CALID;
  700. ALCID : LCID;
  701. buf : array[0..10] of char;
  702. i : integer;
  703. begin
  704. for i:= 1 to MaxEraCount do
  705. begin
  706. EraNames[i] := ''; EraYearOffsets[i] := -1;
  707. end;
  708. ALCID := GetThreadLocale;
  709. if GetLocaleInfoA(ALCID , LOCALE_IOPTIONALCALENDAR, buf, sizeof(buf)) <= 0 then exit;
  710. ACALID := StrToIntDef(buf,1);
  711. if ACALID in [3..5] then
  712. begin
  713. EnumCalendarInfoA(@EnumEraNames, ALCID, ACALID , CAL_SERASTRING);
  714. EnumCalendarInfoA(@EnumEraYearOffsets, ALCID, ACALID, CAL_IYEAROFFSETRANGE);
  715. end;
  716. (*
  717. 1 CAL_GREGORIAN Gregorian (localized)
  718. 2 CAL_GREGORIAN_US Gregorian (English strings always)
  719. 3 CAL_JAPAN Japanese Emperor Era
  720. 4 CAL_TAIWAN Taiwan Calendar
  721. 5 CAL_KOREA Korean Tangun Era
  722. 6 CAL_HIJRI Hijri (Arabic Lunar)
  723. 7 CAL_THAI Thai
  724. 8 CAL_HEBREW Hebrew (Lunar)
  725. 9 CAL_GREGORIAN_ME_FRENCH Gregorian Middle East French
  726. 10 CAL_GREGORIAN_ARABIC Gregorian Arabic
  727. 11 CAL_GREGORIAN_XLIT_ENGLISH Gregorian transliterated English
  728. 12 CAL_GREGORIAN_XLIT_FRENCH Gregorian transliterated French
  729. 23 CAL_UMALQURA Windows Vista or later: Um Al Qura (Arabic lunar) calendar
  730. *)
  731. end;
  732. procedure GetLocaleFormatSettings(LCID: Integer; var FormatSettings: TFormatSettings);
  733. var
  734. HF : Shortstring;
  735. LID : Windows.LCID;
  736. I,Day : longint;
  737. begin
  738. LID := LCID;
  739. with FormatSettings do
  740. begin
  741. { Date stuff }
  742. for I := 1 to 12 do
  743. begin
  744. ShortMonthNames[I]:=GetLocaleStr(LID,LOCALE_SABBREVMONTHNAME1+I-1,ShortMonthNames[i]);
  745. LongMonthNames[I]:=GetLocaleStr(LID,LOCALE_SMONTHNAME1+I-1,LongMonthNames[i]);
  746. end;
  747. for I := 1 to 7 do
  748. begin
  749. Day := (I + 5) mod 7;
  750. ShortDayNames[I]:=GetLocaleStr(LID,LOCALE_SABBREVDAYNAME1+Day,ShortDayNames[i]);
  751. LongDayNames[I]:=GetLocaleStr(LID,LOCALE_SDAYNAME1+Day,LongDayNames[i]);
  752. end;
  753. DateSeparator := GetLocaleChar(LID, LOCALE_SDATE, '/');
  754. ShortDateFormat := GetLocaleStr(LID, LOCALE_SSHORTDATE, 'm/d/yy');
  755. LongDateFormat := GetLocaleStr(LID, LOCALE_SLONGDATE, 'mmmm d, yyyy');
  756. { Time stuff }
  757. TimeSeparator := GetLocaleChar(LID, LOCALE_STIME, ':');
  758. TimeAMString := GetLocaleStr(LID, LOCALE_S1159, 'AM');
  759. TimePMString := GetLocaleStr(LID, LOCALE_S2359, 'PM');
  760. if StrToIntDef(GetLocaleStr(LID, LOCALE_ITLZERO, '0'), 0) = 0 then
  761. HF:='h'
  762. else
  763. HF:='hh';
  764. // No support for 12 hour stuff at the moment...
  765. ShortTimeFormat := HF+':nn';
  766. LongTimeFormat := HF + ':nn:ss';
  767. { Currency stuff }
  768. CurrencyString:=GetLocaleStr(LID, LOCALE_SCURRENCY, '');
  769. CurrencyFormat:=StrToIntDef(GetLocaleStr(LID, LOCALE_ICURRENCY, '0'), 0);
  770. NegCurrFormat:=StrToIntDef(GetLocaleStr(LID, LOCALE_INEGCURR, '0'), 0);
  771. { Number stuff }
  772. ThousandSeparator:=GetLocaleChar(LID, LOCALE_STHOUSAND, ',');
  773. DecimalSeparator:=GetLocaleChar(LID, LOCALE_SDECIMAL, '.');
  774. CurrencyDecimals:=StrToIntDef(GetLocaleStr(LID, LOCALE_ICURRDIGITS, '0'), 0);
  775. ListSeparator := GetLocaleChar(LID, LOCALE_SLIST, ',');
  776. end;
  777. end;
  778. procedure GetFormatSettings;
  779. begin
  780. GetlocaleFormatSettings(GetThreadLocale, DefaultFormatSettings);
  781. end;
  782. Procedure InitInternational;
  783. var
  784. { A call to GetSystemMetrics changes the value of the 8087 Control Word on
  785. Pentium4 with WinXP SP2 }
  786. old8087CW: word;
  787. DefaultCustomLocaleID : LCID; // typedef DWORD LCID;
  788. DefaultCustomLanguageID : Word; // typedef WORD LANGID;
  789. begin
  790. /// workaround for Windows 7 bug, see bug report #18574
  791. SetThreadLocale(GetUserDefaultLCID);
  792. InitInternationalGeneric;
  793. old8087CW:=Get8087CW;
  794. SysLocale.MBCS:=GetSystemMetrics(SM_DBCSENABLED)<>0;
  795. SysLocale.RightToLeft:=GetSystemMetrics(SM_MIDEASTENABLED)<>0;
  796. SysLocale.DefaultLCID := $0409;
  797. SysLocale.PriLangID := LANG_ENGLISH;
  798. SysLocale.SubLangID := SUBLANG_ENGLISH_US;
  799. // probably needs update with getthreadlocale. post 2.0.2
  800. DefaultCustomLocaleID := GetThreadLocale;
  801. if DefaultCustomLocaleID <> 0 then
  802. begin
  803. { Locale Identifiers
  804. +-------------+---------+-------------------------+
  805. | Reserved | Sort ID | Language ID |
  806. +-------------+---------+-------------------------+
  807. 31 20 19 16 15 0 bit }
  808. DefaultCustomLanguageID := DefaultCustomLocaleID and $FFFF; // 2^16
  809. if DefaultCustomLanguageID <> 0 then
  810. begin
  811. SysLocale.DefaultLCID := DefaultCustomLocaleID;
  812. { Language Identifiers
  813. +-------------------------+-------------------------+
  814. | SubLanguage ID | Primary Language ID |
  815. +-------------------------+-------------------------+
  816. 15 10 9 0 bit }
  817. SysLocale.PriLangID := DefaultCustomLanguageID and $3ff; // 2^10
  818. SysLocale.SubLangID := DefaultCustomLanguageID shr 10;
  819. end;
  820. end;
  821. Set8087CW(old8087CW);
  822. GetFormatSettings;
  823. if SysLocale.FarEast then GetEraNamesAndYearOffsets;
  824. end;
  825. {****************************************************************************
  826. Target Dependent
  827. ****************************************************************************}
  828. function SysErrorMessage(ErrorCode: Integer): String;
  829. const
  830. MaxMsgSize = Format_Message_Max_Width_Mask;
  831. var
  832. MsgBuffer: unicodestring;
  833. len: longint;
  834. begin
  835. SetLength(MsgBuffer, MaxMsgSize);
  836. len := FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM,
  837. nil,
  838. ErrorCode,
  839. MakeLangId(LANG_NEUTRAL, SUBLANG_DEFAULT),
  840. PUnicodeChar(MsgBuffer),
  841. MaxMsgSize,
  842. nil);
  843. // Remove trailing #13#10
  844. if (len > 1) and (MsgBuffer[len - 1] = #13) and (MsgBuffer[len] = #10) then
  845. Dec(len, 2);
  846. SetLength(MsgBuffer, len);
  847. Result := MsgBuffer;
  848. end;
  849. {****************************************************************************
  850. Initialization code
  851. ****************************************************************************}
  852. {$push}
  853. { GetEnvironmentStrings cannot be checked by CheckPointer function }
  854. {$checkpointer off}
  855. Function GetEnvironmentVariable(Const EnvVar : String) : String;
  856. var
  857. oemenvvar, oemstr : RawByteString;
  858. i, hplen : longint;
  859. hp,p : pchar;
  860. begin
  861. oemenvvar:=uppercase(envvar);
  862. SetCodePage(oemenvvar,CP_OEMCP);
  863. Result:='';
  864. p:=GetEnvironmentStringsA;
  865. hp:=p;
  866. while hp^<>#0 do
  867. begin
  868. oemstr:=hp;
  869. { cache length, may change after uppercasing depending on code page }
  870. hplen:=length(oemstr);
  871. { all environment variables are encoded in the oem code page }
  872. SetCodePage(oemstr,CP_OEMCP,false);
  873. i:=pos('=',oemstr);
  874. if uppercase(copy(oemstr,1,i-1))=oemenvvar then
  875. begin
  876. Result:=copy(oemstr,i+1,length(oemstr)-i);
  877. break;
  878. end;
  879. { next string entry}
  880. hp:=hp+hplen+1;
  881. end;
  882. FreeEnvironmentStringsA(p);
  883. end;
  884. Function GetEnvironmentVariable(Const EnvVar : UnicodeString) : UnicodeString;
  885. var
  886. s, upperenv : Unicodestring;
  887. i : longint;
  888. hp,p : pwidechar;
  889. begin
  890. Result:='';
  891. p:=GetEnvironmentStringsW;
  892. hp:=p;
  893. upperenv:=uppercase(envvar);
  894. while hp^<>#0 do
  895. begin
  896. s:=hp;
  897. i:=pos('=',s);
  898. if uppercase(copy(s,1,i-1))=upperenv then
  899. begin
  900. Result:=copy(s,i+1,length(s)-i);
  901. break;
  902. end;
  903. { next string entry}
  904. hp:=hp+strlen(hp)+1;
  905. end;
  906. FreeEnvironmentStringsW(p);
  907. end;
  908. Function GetEnvironmentVariableCount : Integer;
  909. var
  910. hp,p : pchar;
  911. begin
  912. Result:=0;
  913. p:=GetEnvironmentStringsA;
  914. hp:=p;
  915. If (Hp<>Nil) then
  916. while hp^<>#0 do
  917. begin
  918. Inc(Result);
  919. hp:=hp+strlen(hp)+1;
  920. end;
  921. FreeEnvironmentStringsA(p);
  922. end;
  923. Function GetEnvironmentString(Index : Integer) : {$ifdef FPC_RTL_UNICODE}UnicodeString{$else}AnsiString{$endif};
  924. var
  925. hp,p : pchar;
  926. {$ifdef FPC_RTL_UNICODE}
  927. tmpstr : RawByteString;
  928. {$endif}
  929. begin
  930. Result:='';
  931. p:=GetEnvironmentStringsA;
  932. hp:=p;
  933. If (Hp<>Nil) then
  934. begin
  935. while (hp^<>#0) and (Index>1) do
  936. begin
  937. Dec(Index);
  938. hp:=hp+strlen(hp)+1;
  939. end;
  940. If (hp^<>#0) then
  941. begin
  942. {$ifdef FPC_RTL_UNICODE}
  943. tmpstr:=hp;
  944. SetCodePage(tmpstr,CP_OEMCP,false);
  945. Result:=tmpstr;
  946. {$else}
  947. Result:=hp;
  948. SetCodePage(RawByteString(Result),CP_OEMCP,false);
  949. {$endif}
  950. end;
  951. end;
  952. FreeEnvironmentStringsA(p);
  953. end;
  954. {$pop}
  955. function ExecuteProcess(Const Path: RawByteString; Const ComLine: RawByteString;Flags:TExecuteFlags=[]):integer;
  956. begin
  957. result:=ExecuteProcess(Unicodestring(Path),UnicodeString(ComLine),Flags);
  958. end;
  959. function ExecuteProcess(Const Path: UnicodeString; Const ComLine: UnicodeString;Flags:TExecuteFlags=[]):integer;
  960. // win specific function
  961. var
  962. SI: TStartupInfoW;
  963. PI: TProcessInformation;
  964. Proc : THandle;
  965. l : DWord;
  966. CommandLine : unicodestring;
  967. e : EOSError;
  968. ExecInherits : longbool;
  969. begin
  970. FillChar(SI, SizeOf(SI), 0);
  971. SI.cb:=SizeOf(SI);
  972. SI.wShowWindow:=1;
  973. { always surround the name of the application by quotes
  974. so that long filenames will always be accepted. But don't
  975. do it if there are already double quotes, since Win32 does not
  976. like double quotes which are duplicated!
  977. }
  978. if pos('"',path)=0 then
  979. CommandLine:='"'+path+'"'
  980. else
  981. CommandLine:=path;
  982. if ComLine <> '' then
  983. CommandLine:=Commandline+' '+ComLine+#0
  984. else
  985. CommandLine := CommandLine + #0;
  986. ExecInherits:=ExecInheritsHandles in Flags;
  987. if not CreateProcessW(nil, pwidechar(CommandLine),
  988. Nil, Nil, ExecInherits,$20, Nil, Nil, SI, PI) then
  989. begin
  990. e:=EOSError.CreateFmt(SExecuteProcessFailed,[CommandLine,GetLastError]);
  991. e.ErrorCode:=GetLastError;
  992. raise e;
  993. end;
  994. Proc:=PI.hProcess;
  995. if WaitForSingleObject(Proc, dword($ffffffff)) <> $ffffffff then
  996. begin
  997. GetExitCodeProcess(Proc,l);
  998. CloseHandle(Proc);
  999. CloseHandle(PI.hThread);
  1000. result:=l;
  1001. end
  1002. else
  1003. begin
  1004. e:=EOSError.CreateFmt(SExecuteProcessFailed,[CommandLine,GetLastError]);
  1005. e.ErrorCode:=GetLastError;
  1006. CloseHandle(Proc);
  1007. CloseHandle(PI.hThread);
  1008. raise e;
  1009. end;
  1010. end;
  1011. function ExecuteProcess(Const Path: RawByteString; Const ComLine: Array of RawByteString;Flags:TExecuteFlags=[]):integer;
  1012. var
  1013. CommandLine: UnicodeString;
  1014. I: integer;
  1015. begin
  1016. Commandline := '';
  1017. for I := 0 to High (ComLine) do
  1018. if Pos (' ', ComLine [I]) <> 0 then
  1019. CommandLine := CommandLine + ' ' + '"' + ComLine [I] + '"'
  1020. else
  1021. CommandLine := CommandLine + ' ' + Comline [I];
  1022. ExecuteProcess := ExecuteProcess (UnicodeString(Path), CommandLine,Flags);
  1023. end;
  1024. function ExecuteProcess(Const Path: UnicodeString; Const ComLine: Array of UnicodeString;Flags:TExecuteFlags=[]):integer;
  1025. var
  1026. CommandLine: UnicodeString;
  1027. I: integer;
  1028. begin
  1029. Commandline := '';
  1030. for I := 0 to High (ComLine) do
  1031. if Pos (' ', ComLine [I]) <> 0 then
  1032. CommandLine := CommandLine + ' ' + '"' + ComLine [I] + '"'
  1033. else
  1034. CommandLine := CommandLine + ' ' + Comline [I];
  1035. ExecuteProcess := ExecuteProcess (Path,CommandLine,Flags);
  1036. end;
  1037. Procedure Sleep(Milliseconds : Cardinal);
  1038. begin
  1039. Windows.Sleep(MilliSeconds)
  1040. end;
  1041. Function GetLastOSError : Integer;
  1042. begin
  1043. Result:=GetLastError;
  1044. end;
  1045. {****************************************************************************
  1046. Initialization code
  1047. ****************************************************************************}
  1048. var
  1049. kernel32dll : THandle;
  1050. Procedure LoadVersionInfo;
  1051. // and getfreespaceex
  1052. Var
  1053. versioninfo : TOSVERSIONINFO;
  1054. begin
  1055. GetDiskFreeSpaceEx:=nil;
  1056. versioninfo.dwOSVersionInfoSize:=sizeof(versioninfo);
  1057. GetVersionEx(versioninfo);
  1058. Win32Platform:=versionInfo.dwPlatformId;
  1059. Win32MajorVersion:=versionInfo.dwMajorVersion;
  1060. Win32MinorVersion:=versionInfo.dwMinorVersion;
  1061. Win32BuildNumber:=versionInfo.dwBuildNumber;
  1062. Move (versioninfo.szCSDVersion ,Win32CSDVersion[1],128);
  1063. win32CSDVersion[0]:=chr(strlen(pchar(@versioninfo.szCSDVersion)));
  1064. kernel32dll:=GetModuleHandle('kernel32');
  1065. if kernel32dll<>0 then
  1066. GetDiskFreeSpaceEx:=TGetDiskFreeSpaceEx(GetProcAddress(kernel32dll,'GetDiskFreeSpaceExA'));
  1067. end;
  1068. Function GetAppConfigDir(Global : Boolean) : String;
  1069. begin
  1070. If Global then
  1071. Result:=GetWindowsSpecialDir(CSIDL_COMMON_APPDATA)
  1072. else
  1073. Result:=GetWindowsSpecialDir(CSIDL_LOCAL_APPDATA);
  1074. If (Result<>'') then
  1075. begin
  1076. if VendorName<>'' then
  1077. Result:=IncludeTrailingPathDelimiter(Result+VendorName);
  1078. Result:=IncludeTrailingPathDelimiter(Result+ApplicationName);
  1079. end
  1080. else
  1081. Result:=IncludeTrailingPathDelimiter(DGetAppConfigDir(Global));
  1082. end;
  1083. Function GetAppConfigFile(Global : Boolean; SubDir : Boolean) : String;
  1084. begin
  1085. result:=DGetAppConfigFile(Global,SubDir);
  1086. end;
  1087. Function GetUserDir : String;
  1088. begin
  1089. Result:=GetWindowsSpecialDir(CSIDL_PROFILE);
  1090. end;
  1091. Procedure InitSysConfigDir;
  1092. begin
  1093. SetLength(SysConfigDir, MAX_PATH);
  1094. SetLength(SysConfigDir, GetWindowsDirectoryA(PChar(SysConfigDir), MAX_PATH));
  1095. end;
  1096. {****************************************************************************
  1097. Target Dependent WideString stuff
  1098. ****************************************************************************}
  1099. { This is the case of Win9x. Limited to current locale of course, but it's better
  1100. than not working at all. }
  1101. function DoCompareStringA(P1, P2: PWideChar; L1, L2: PtrUInt; Flags: DWORD): PtrInt;
  1102. var
  1103. a1, a2: AnsiString;
  1104. begin
  1105. if L1>0 then
  1106. widestringmanager.Wide2AnsiMoveProc(P1,a1,DefaultSystemCodePage,L1);
  1107. if L2>0 then
  1108. widestringmanager.Wide2AnsiMoveProc(P2,a2,DefaultSystemCodePage,L2);
  1109. SetLastError(0);
  1110. Result:=CompareStringA(LOCALE_USER_DEFAULT,Flags,pchar(a1),
  1111. length(a1),pchar(a2),length(a2))-2;
  1112. end;
  1113. function DoCompareStringW(P1, P2: PWideChar; L1, L2: PtrUInt; Flags: DWORD): PtrInt;
  1114. begin
  1115. SetLastError(0);
  1116. Result:=CompareStringW(LOCALE_USER_DEFAULT,Flags,P1,L1,P2,L2)-2;
  1117. if GetLastError=0 then
  1118. Exit;
  1119. if GetLastError=ERROR_CALL_NOT_IMPLEMENTED then // Win9x case
  1120. Result:=DoCompareStringA(P1, P2, L1, L2, Flags);
  1121. if GetLastError<>0 then
  1122. RaiseLastOSError;
  1123. end;
  1124. const
  1125. WinAPICompareFlags : array [TCompareOption] of LongWord
  1126. = ({LINGUISTIC_IGNORECASE, LINGUISTIC_IGNOREDIACRITIC, }NORM_IGNORECASE{,
  1127. NORM_IGNOREKANATYPE, NORM_IGNORENONSPACE, NORM_IGNORESYMBOLS, NORM_IGNOREWIDTH,
  1128. NORM_LINGUISTIC_CASING, SORT_DIGITSASNUMBERS, SORT_STRINGSORT});
  1129. function Win32CompareWideString(const s1, s2 : WideString; Options : TCompareOptions) : PtrInt;
  1130. Var
  1131. O : LongWord;
  1132. CO : TCompareOption;
  1133. begin
  1134. O:=0;
  1135. for CO in TCompareOption do
  1136. if CO in Options then
  1137. O:=O or WinAPICompareFlags[CO];
  1138. Result:=DoCompareStringW(PWideChar(s1), PWideChar(s2), Length(s1), Length(s2), O);
  1139. end;
  1140. function Win32CompareTextWideString(const s1, s2 : WideString) : PtrInt;
  1141. begin
  1142. Result:=DoCompareStringW(PWideChar(s1), PWideChar(s2), Length(s1), Length(s2), NORM_IGNORECASE);
  1143. end;
  1144. function Win32AnsiUpperCase(const s: string): string;
  1145. begin
  1146. if length(s)>0 then
  1147. begin
  1148. result:=s;
  1149. UniqueString(result);
  1150. CharUpperBuffA(pchar(result),length(result));
  1151. end
  1152. else
  1153. result:='';
  1154. end;
  1155. function Win32AnsiLowerCase(const s: string): string;
  1156. begin
  1157. if length(s)>0 then
  1158. begin
  1159. result:=s;
  1160. UniqueString(result);
  1161. CharLowerBuffA(pchar(result),length(result));
  1162. end
  1163. else
  1164. result:='';
  1165. end;
  1166. function Win32AnsiCompareStr(const S1, S2: string): PtrInt;
  1167. begin
  1168. result:=CompareStringA(LOCALE_USER_DEFAULT,0,pchar(s1),length(s1),
  1169. pchar(s2),length(s2))-2;
  1170. end;
  1171. function Win32AnsiCompareText(const S1, S2: string): PtrInt;
  1172. begin
  1173. result:=CompareStringA(LOCALE_USER_DEFAULT,NORM_IGNORECASE,pchar(s1),length(s1),
  1174. pchar(s2),length(s2))-2;
  1175. end;
  1176. function Win32AnsiStrComp(S1, S2: PChar): PtrInt;
  1177. begin
  1178. result:=CompareStringA(LOCALE_USER_DEFAULT,0,s1,-1,s2,-1)-2;
  1179. end;
  1180. function Win32AnsiStrIComp(S1, S2: PChar): PtrInt;
  1181. begin
  1182. result:=CompareStringA(LOCALE_USER_DEFAULT,NORM_IGNORECASE,s1,-1,s2,-1)-2;
  1183. end;
  1184. function Win32AnsiStrLComp(S1, S2: PChar; MaxLen: PtrUInt): PtrInt;
  1185. begin
  1186. result:=CompareStringA(LOCALE_USER_DEFAULT,0,s1,maxlen,s2,maxlen)-2;
  1187. end;
  1188. function Win32AnsiStrLIComp(S1, S2: PChar; MaxLen: PtrUInt): PtrInt;
  1189. begin
  1190. result:=CompareStringA(LOCALE_USER_DEFAULT,NORM_IGNORECASE,s1,maxlen,s2,maxlen)-2;
  1191. end;
  1192. function Win32AnsiStrLower(Str: PChar): PChar;
  1193. begin
  1194. CharLowerA(str);
  1195. result:=str;
  1196. end;
  1197. function Win32AnsiStrUpper(Str: PChar): PChar;
  1198. begin
  1199. CharUpperA(str);
  1200. result:=str;
  1201. end;
  1202. function Win32CompareUnicodeString(const s1, s2 : UnicodeString; Options : TCompareOptions) : PtrInt;
  1203. Var
  1204. O : LongWord;
  1205. CO : TCompareOption;
  1206. begin
  1207. O:=0;
  1208. for CO in TCompareOption do
  1209. if CO in Options then
  1210. O:=O or WinAPICompareFlags[CO];
  1211. Result:=DoCompareStringW(PWideChar(s1), PWideChar(s2), Length(s1), Length(s2), O);
  1212. end;
  1213. function Win32CompareTextUnicodeString(const s1, s2 : UnicodeString) : PtrInt;
  1214. begin
  1215. Result:=DoCompareStringW(PWideChar(s1), PWideChar(s2), Length(s1), Length(s2), NORM_IGNORECASE);
  1216. end;
  1217. { there is a similiar procedure in the system unit which inits the fields which
  1218. are relevant already for the system unit }
  1219. procedure InitWin32Widestrings;
  1220. begin
  1221. { return value: number of code points in the string. Whenever an invalid
  1222. code point is encountered, all characters part of this invalid code point
  1223. are considered to form one "character" and the next character is
  1224. considered to be the start of a new (possibly also invalid) code point }
  1225. //!!! CharLengthPCharProc : function(const Str: PChar): PtrInt;
  1226. { return value:
  1227. -1 if incomplete or invalid code point
  1228. 0 if NULL character,
  1229. > 0 if that's the length in bytes of the code point }
  1230. //!!!! CodePointLengthProc : function(const Str: PChar; MaxLookAead: PtrInt): Ptrint;
  1231. widestringmanager.CompareWideStringProc:=@Win32CompareWideString;
  1232. widestringmanager.UpperAnsiStringProc:=@Win32AnsiUpperCase;
  1233. widestringmanager.LowerAnsiStringProc:=@Win32AnsiLowerCase;
  1234. widestringmanager.CompareStrAnsiStringProc:=@Win32AnsiCompareStr;
  1235. widestringmanager.CompareTextAnsiStringProc:=@Win32AnsiCompareText;
  1236. widestringmanager.StrCompAnsiStringProc:=@Win32AnsiStrComp;
  1237. widestringmanager.StrICompAnsiStringProc:=@Win32AnsiStrIComp;
  1238. widestringmanager.StrLCompAnsiStringProc:=@Win32AnsiStrLComp;
  1239. widestringmanager.StrLICompAnsiStringProc:=@Win32AnsiStrLIComp;
  1240. widestringmanager.StrLowerAnsiStringProc:=@Win32AnsiStrLower;
  1241. widestringmanager.StrUpperAnsiStringProc:=@Win32AnsiStrUpper;
  1242. widestringmanager.CompareUnicodeStringProc:=@Win32CompareUnicodeString;
  1243. end;
  1244. { Platform-specific exception support }
  1245. function WinExceptionObject(code: Longint; const rec: TExceptionRecord): Exception;
  1246. var
  1247. entry: PExceptMapEntry;
  1248. begin
  1249. entry := FindExceptMapEntry(code);
  1250. if assigned(entry) then
  1251. result:=entry^.cls.CreateRes(entry^.msg)
  1252. else
  1253. result:=EExternalException.CreateResFmt(@SExternalException,[rec.ExceptionCode]);
  1254. if result is EExternal then
  1255. EExternal(result).FExceptionRecord:=rec;
  1256. end;
  1257. function WinExceptionClass(code: longint): ExceptClass;
  1258. var
  1259. entry: PExceptMapEntry;
  1260. begin
  1261. entry := FindExceptMapEntry(code);
  1262. if assigned(entry) then
  1263. result:=entry^.cls
  1264. else
  1265. result:=EExternalException;
  1266. end;
  1267. Initialization
  1268. InitWin32Widestrings;
  1269. InitExceptions; { Initialize exceptions. OS independent }
  1270. {$ifdef mswindows} { Keeps exe size down for systems that do not use SEH }
  1271. ExceptObjProc:=@WinExceptionObject;
  1272. ExceptClsProc:=@WinExceptionClass;
  1273. {$endif mswindows}
  1274. InitInternational; { Initialize internationalization settings }
  1275. LoadVersionInfo;
  1276. InitSysConfigDir;
  1277. OnBeep:=@SysBeep;
  1278. Finalization
  1279. DoneExceptions;
  1280. end.