sysutils.pp 33 KB

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