HierarchicalStorage.cpp 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include "Common.h"
  5. #include "Exceptions.h"
  6. #include "PuttyIntf.h"
  7. #include "HierarchicalStorage.h"
  8. #include <Interface.h>
  9. #include <TextsCore.h>
  10. #include <StrUtils.hpp>
  11. #include <vector>
  12. //---------------------------------------------------------------------------
  13. #pragma package(smart_init)
  14. //---------------------------------------------------------------------------
  15. // ValueExists test was probably added to avoid registry exceptions when debugging
  16. #define READ_REGISTRY(Method) \
  17. if (FRegistry->ValueExists(Name)) \
  18. try { return FRegistry->Method(Name); } catch(...) { return Default; } \
  19. else return Default;
  20. #define WRITE_REGISTRY(Method) \
  21. try { FRegistry->Method(Name, Value); } catch(...) { }
  22. //---------------------------------------------------------------------------
  23. UnicodeString __fastcall MungeStr(const UnicodeString & Str, bool ForceAnsi, bool Value)
  24. {
  25. RawByteString Source;
  26. if (ForceAnsi)
  27. {
  28. Source = RawByteString(AnsiString(Str));
  29. }
  30. else
  31. {
  32. Source = RawByteString(UTF8String(Str));
  33. if (Source.Length() > Str.Length())
  34. {
  35. Source.Insert(Bom, 1);
  36. }
  37. }
  38. strbuf * sb = strbuf_new();
  39. escape_registry_key(Source.c_str(), sb);
  40. RawByteString Dest(sb->s);
  41. strbuf_free(sb);
  42. if (Value)
  43. {
  44. // We do not want to munge * in PasswordMask
  45. Dest = ReplaceStr(Dest, L"%2A", L"*");
  46. }
  47. return UnicodeString(Dest.c_str(), Dest.Length());
  48. }
  49. //---------------------------------------------------------------------------
  50. UnicodeString __fastcall UnMungeStr(const UnicodeString & Str)
  51. {
  52. // Str should contain ASCII characters only
  53. RawByteString Source = AnsiString(Str);
  54. strbuf * sb = strbuf_new();
  55. unescape_registry_key(Source.c_str(), sb);
  56. RawByteString Dest(sb->s);
  57. strbuf_free(sb);
  58. UnicodeString Result;
  59. if (Dest.SubString(1, LENOF(Bom)) == Bom)
  60. {
  61. Dest.Delete(1, LENOF(Bom));
  62. Result = UTF8ToString(Dest);
  63. }
  64. else
  65. {
  66. Result = AnsiToString(Dest);
  67. }
  68. return Result;
  69. }
  70. //---------------------------------------------------------------------------
  71. UnicodeString __fastcall PuttyMungeStr(const UnicodeString Str)
  72. {
  73. return MungeStr(Str, false, false);
  74. }
  75. //---------------------------------------------------------------------------
  76. UnicodeString __fastcall MungeIniName(const UnicodeString & Str)
  77. {
  78. int P = Str.Pos(L"=");
  79. // make this fast for now
  80. if (P > 0)
  81. {
  82. return ReplaceStr(Str, L"=", L"%3D");
  83. }
  84. else
  85. {
  86. return Str;
  87. }
  88. }
  89. //---------------------------------------------------------------------------
  90. UnicodeString __fastcall UnMungeIniName(const UnicodeString & Str)
  91. {
  92. int P = Str.Pos(L"%3D");
  93. // make this fast for now
  94. if (P > 0)
  95. {
  96. return ReplaceStr(Str, L"%3D", L"=");
  97. }
  98. else
  99. {
  100. return Str;
  101. }
  102. }
  103. //===========================================================================
  104. __fastcall THierarchicalStorage::THierarchicalStorage(const UnicodeString AStorage)
  105. {
  106. FStorage = AStorage;
  107. FKeyHistory = new TStringList();
  108. AccessMode = smRead;
  109. Explicit = false;
  110. ForceSave = false;
  111. // While this was implemented in 5.0 already, for some reason
  112. // it was disabled (by mistake?). So although enabled for 5.6.1 only,
  113. // data written in Unicode/UTF8 can be read by all versions back to 5.0.
  114. ForceAnsi = false;
  115. MungeStringValues = true;
  116. }
  117. //---------------------------------------------------------------------------
  118. __fastcall THierarchicalStorage::~THierarchicalStorage()
  119. {
  120. delete FKeyHistory;
  121. }
  122. //---------------------------------------------------------------------------
  123. void __fastcall THierarchicalStorage::Flush()
  124. {
  125. }
  126. //---------------------------------------------------------------------------
  127. void __fastcall THierarchicalStorage::SetAccessMode(TStorageAccessMode value)
  128. {
  129. FAccessMode = value;
  130. }
  131. //---------------------------------------------------------------------------
  132. UnicodeString __fastcall THierarchicalStorage::GetCurrentSubKeyMunged()
  133. {
  134. if (FKeyHistory->Count) return FKeyHistory->Strings[FKeyHistory->Count-1];
  135. else return L"";
  136. }
  137. //---------------------------------------------------------------------------
  138. UnicodeString __fastcall THierarchicalStorage::GetCurrentSubKey()
  139. {
  140. return UnMungeStr(GetCurrentSubKeyMunged());
  141. }
  142. //---------------------------------------------------------------------------
  143. bool __fastcall THierarchicalStorage::OpenRootKey(bool CanCreate)
  144. {
  145. return OpenSubKey(L"", CanCreate);
  146. }
  147. //---------------------------------------------------------------------------
  148. UnicodeString __fastcall THierarchicalStorage::MungeKeyName(UnicodeString Key)
  149. {
  150. UnicodeString Result = MungeStr(Key, ForceAnsi, false);
  151. // if there's already ANSI-munged subkey, keep ANSI munging
  152. if ((Result != Key) && !ForceAnsi && DoKeyExists(Key, true))
  153. {
  154. Result = MungeStr(Key, true, false);
  155. }
  156. return Result;
  157. }
  158. //---------------------------------------------------------------------------
  159. bool __fastcall THierarchicalStorage::OpenSubKey(UnicodeString Key, bool CanCreate, bool Path)
  160. {
  161. UnicodeString MungedKey;
  162. if (Path)
  163. {
  164. DebugAssert(Key.IsEmpty() || (Key[Key.Length()] != L'\\'));
  165. while (!Key.IsEmpty())
  166. {
  167. if (!MungedKey.IsEmpty())
  168. {
  169. MungedKey += L'\\';
  170. }
  171. MungedKey += MungeKeyName(CutToChar(Key, L'\\', false));
  172. }
  173. }
  174. else
  175. {
  176. MungedKey = MungeKeyName(Key);
  177. }
  178. bool Result = DoOpenSubKey(MungedKey, CanCreate);
  179. if (Result)
  180. {
  181. FKeyHistory->Add(IncludeTrailingBackslash(CurrentSubKey+MungedKey));
  182. }
  183. return Result;
  184. }
  185. //---------------------------------------------------------------------------
  186. void __fastcall THierarchicalStorage::CloseSubKey()
  187. {
  188. if (FKeyHistory->Count == 0) throw Exception(L"");
  189. else FKeyHistory->Delete(FKeyHistory->Count-1);
  190. }
  191. //---------------------------------------------------------------------------
  192. void __fastcall THierarchicalStorage::CloseAll()
  193. {
  194. while (!CurrentSubKey.IsEmpty())
  195. {
  196. CloseSubKey();
  197. }
  198. }
  199. //---------------------------------------------------------------------------
  200. void __fastcall THierarchicalStorage::ClearSubKeys()
  201. {
  202. TStringList *SubKeys = new TStringList();
  203. try
  204. {
  205. GetSubKeyNames(SubKeys);
  206. for (int Index = 0; Index < SubKeys->Count; Index++)
  207. {
  208. RecursiveDeleteSubKey(SubKeys->Strings[Index]);
  209. }
  210. }
  211. __finally
  212. {
  213. delete SubKeys;
  214. }
  215. }
  216. //---------------------------------------------------------------------------
  217. void __fastcall THierarchicalStorage::RecursiveDeleteSubKey(const UnicodeString Key)
  218. {
  219. if (OpenSubKey(Key, false))
  220. {
  221. ClearSubKeys();
  222. CloseSubKey();
  223. }
  224. DeleteSubKey(Key);
  225. }
  226. //---------------------------------------------------------------------------
  227. bool __fastcall THierarchicalStorage::HasSubKeys()
  228. {
  229. bool Result;
  230. TStrings * SubKeys = new TStringList();
  231. try
  232. {
  233. GetSubKeyNames(SubKeys);
  234. Result = (SubKeys->Count > 0);
  235. }
  236. __finally
  237. {
  238. delete SubKeys;
  239. }
  240. return Result;
  241. }
  242. //---------------------------------------------------------------------------
  243. bool __fastcall THierarchicalStorage::HasSubKey(const UnicodeString SubKey)
  244. {
  245. bool Result = OpenSubKey(SubKey, false);
  246. if (Result)
  247. {
  248. CloseSubKey();
  249. }
  250. return Result;
  251. }
  252. //---------------------------------------------------------------------------
  253. bool __fastcall THierarchicalStorage::KeyExists(const UnicodeString SubKey)
  254. {
  255. return DoKeyExists(SubKey, ForceAnsi);
  256. }
  257. //---------------------------------------------------------------------------
  258. void __fastcall THierarchicalStorage::ReadValues(Classes::TStrings* Strings,
  259. bool MaintainKeys)
  260. {
  261. TStrings * Names = new TStringList();
  262. try
  263. {
  264. GetValueNames(Names);
  265. for (int Index = 0; Index < Names->Count; Index++)
  266. {
  267. if (MaintainKeys)
  268. {
  269. Strings->Add(FORMAT(L"%s=%s", (Names->Strings[Index],
  270. ReadString(Names->Strings[Index], L""))));
  271. }
  272. else
  273. {
  274. Strings->Add(ReadString(Names->Strings[Index], L""));
  275. }
  276. }
  277. }
  278. __finally
  279. {
  280. delete Names;
  281. }
  282. }
  283. //---------------------------------------------------------------------------
  284. void __fastcall THierarchicalStorage::ClearValues()
  285. {
  286. TStrings * Names = new TStringList();
  287. try
  288. {
  289. GetValueNames(Names);
  290. for (int Index = 0; Index < Names->Count; Index++)
  291. {
  292. DeleteValue(Names->Strings[Index]);
  293. }
  294. }
  295. __finally
  296. {
  297. delete Names;
  298. }
  299. }
  300. //---------------------------------------------------------------------------
  301. void __fastcall THierarchicalStorage::WriteValues(Classes::TStrings * Strings,
  302. bool MaintainKeys)
  303. {
  304. ClearValues();
  305. if (Strings)
  306. {
  307. for (int Index = 0; Index < Strings->Count; Index++)
  308. {
  309. if (MaintainKeys)
  310. {
  311. DebugAssert(Strings->Strings[Index].Pos(L"=") > 1);
  312. WriteString(Strings->Names[Index], Strings->Values[Strings->Names[Index]]);
  313. }
  314. else
  315. {
  316. WriteString(IntToStr(Index), Strings->Strings[Index]);
  317. }
  318. }
  319. }
  320. }
  321. //---------------------------------------------------------------------------
  322. UnicodeString __fastcall THierarchicalStorage::ReadString(const UnicodeString Name, const UnicodeString Default)
  323. {
  324. UnicodeString Result;
  325. if (MungeStringValues)
  326. {
  327. Result = UnMungeStr(ReadStringRaw(Name, MungeStr(Default, ForceAnsi, true)));
  328. }
  329. else
  330. {
  331. Result = ReadStringRaw(Name, Default);
  332. }
  333. return Result;
  334. }
  335. //---------------------------------------------------------------------------
  336. RawByteString __fastcall THierarchicalStorage::ReadBinaryData(const UnicodeString Name)
  337. {
  338. size_t Size = BinaryDataSize(Name);
  339. RawByteString Value;
  340. Value.SetLength(Size);
  341. ReadBinaryData(Name, Value.c_str(), Size);
  342. return Value;
  343. }
  344. //---------------------------------------------------------------------------
  345. RawByteString __fastcall THierarchicalStorage::ReadStringAsBinaryData(const UnicodeString Name, const RawByteString Default)
  346. {
  347. UnicodeString UnicodeDefault = AnsiToString(Default);
  348. // This should be exactly the same operation as calling ReadString in
  349. // C++Builder 6 (non-Unicode) on Unicode-based OS
  350. // (conversion is done by Ansi layer of the OS)
  351. UnicodeString String = ReadString(Name, UnicodeDefault);
  352. AnsiString Ansi = AnsiString(String);
  353. RawByteString Result = RawByteString(Ansi.c_str(), Ansi.Length());
  354. return Result;
  355. }
  356. //---------------------------------------------------------------------------
  357. void __fastcall THierarchicalStorage::WriteString(const UnicodeString Name, const UnicodeString Value)
  358. {
  359. if (MungeStringValues)
  360. {
  361. WriteStringRaw(Name, MungeStr(Value, ForceAnsi, true));
  362. }
  363. else
  364. {
  365. WriteStringRaw(Name, Value);
  366. }
  367. }
  368. //---------------------------------------------------------------------------
  369. void __fastcall THierarchicalStorage::WriteBinaryData(const UnicodeString Name,
  370. const RawByteString Value)
  371. {
  372. WriteBinaryData(Name, Value.c_str(), Value.Length());
  373. }
  374. //---------------------------------------------------------------------------
  375. void __fastcall THierarchicalStorage::WriteBinaryDataAsString(const UnicodeString Name, const RawByteString Value)
  376. {
  377. // This should be exactly the same operation as calling WriteString in
  378. // C++Builder 6 (non-Unicode) on Unicode-based OS
  379. // (conversion is done by Ansi layer of the OS)
  380. WriteString(Name, AnsiToString(Value));
  381. }
  382. //---------------------------------------------------------------------------
  383. UnicodeString __fastcall THierarchicalStorage::IncludeTrailingBackslash(const UnicodeString & S)
  384. {
  385. // expanded from ?: as it caused memory leaks
  386. if (S.IsEmpty())
  387. {
  388. return S;
  389. }
  390. else
  391. {
  392. return ::IncludeTrailingBackslash(S);
  393. }
  394. }
  395. //---------------------------------------------------------------------------
  396. UnicodeString __fastcall THierarchicalStorage::ExcludeTrailingBackslash(const UnicodeString & S)
  397. {
  398. // expanded from ?: as it caused memory leaks
  399. if (S.IsEmpty())
  400. {
  401. return S;
  402. }
  403. else
  404. {
  405. return ::ExcludeTrailingBackslash(S);
  406. }
  407. }
  408. //---------------------------------------------------------------------------
  409. bool __fastcall THierarchicalStorage::GetTemporary()
  410. {
  411. return false;
  412. }
  413. //===========================================================================
  414. __fastcall TRegistryStorage::TRegistryStorage(const UnicodeString AStorage):
  415. THierarchicalStorage(IncludeTrailingBackslash(AStorage))
  416. {
  417. FWowMode = 0;
  418. Init();
  419. };
  420. //---------------------------------------------------------------------------
  421. __fastcall TRegistryStorage::TRegistryStorage(const UnicodeString AStorage, HKEY ARootKey, REGSAM WowMode):
  422. THierarchicalStorage(IncludeTrailingBackslash(AStorage))
  423. {
  424. FWowMode = WowMode;
  425. Init();
  426. FRegistry->RootKey = ARootKey;
  427. }
  428. //---------------------------------------------------------------------------
  429. void __fastcall TRegistryStorage::Init()
  430. {
  431. FRegistry = new TRegistry();
  432. FRegistry->Access = KEY_READ | FWowMode;
  433. }
  434. //---------------------------------------------------------------------------
  435. __fastcall TRegistryStorage::~TRegistryStorage()
  436. {
  437. delete FRegistry;
  438. };
  439. //---------------------------------------------------------------------------
  440. bool __fastcall TRegistryStorage::Copy(TRegistryStorage * Storage)
  441. {
  442. TRegistry * Registry = Storage->FRegistry;
  443. bool Result = true;
  444. TStrings * Names = new TStringList();
  445. try
  446. {
  447. Registry->GetValueNames(Names);
  448. std::vector<unsigned char> Buffer(1024, 0);
  449. int Index = 0;
  450. while ((Index < Names->Count) && Result)
  451. {
  452. UnicodeString Name = MungeStr(Names->Strings[Index], ForceAnsi, false);
  453. unsigned long Size = Buffer.size();
  454. unsigned long Type;
  455. int RegResult;
  456. do
  457. {
  458. RegResult = RegQueryValueEx(Registry->CurrentKey, Name.c_str(), NULL,
  459. &Type, &Buffer[0], &Size);
  460. if (RegResult == ERROR_MORE_DATA)
  461. {
  462. Buffer.resize(Size);
  463. }
  464. } while (RegResult == ERROR_MORE_DATA);
  465. Result = (RegResult == ERROR_SUCCESS);
  466. if (Result)
  467. {
  468. RegResult = RegSetValueEx(FRegistry->CurrentKey, Name.c_str(), NULL, Type,
  469. &Buffer[0], Size);
  470. Result = (RegResult == ERROR_SUCCESS);
  471. }
  472. ++Index;
  473. }
  474. }
  475. __finally
  476. {
  477. delete Names;
  478. }
  479. return Result;
  480. }
  481. //---------------------------------------------------------------------------
  482. UnicodeString __fastcall TRegistryStorage::GetSource()
  483. {
  484. return RootKeyToStr(FRegistry->RootKey) + L"\\" + Storage;
  485. }
  486. //---------------------------------------------------------------------------
  487. void __fastcall TRegistryStorage::SetAccessMode(TStorageAccessMode value)
  488. {
  489. THierarchicalStorage::SetAccessMode(value);
  490. if (FRegistry)
  491. {
  492. switch (AccessMode) {
  493. case smRead:
  494. FRegistry->Access = KEY_READ | FWowMode;
  495. break;
  496. case smReadWrite:
  497. default:
  498. FRegistry->Access = KEY_READ | KEY_WRITE | FWowMode;
  499. break;
  500. }
  501. }
  502. }
  503. //---------------------------------------------------------------------------
  504. bool __fastcall TRegistryStorage::DoOpenSubKey(const UnicodeString SubKey, bool CanCreate)
  505. {
  506. UnicodeString PrevPath;
  507. bool WasOpened = (FRegistry->CurrentKey != NULL);
  508. if (WasOpened)
  509. {
  510. PrevPath = FRegistry->CurrentPath;
  511. DebugAssert(SamePaths(PrevPath, Storage + GetCurrentSubKeyMunged()));
  512. FRegistry->CloseKey();
  513. }
  514. UnicodeString K = ExcludeTrailingBackslash(Storage + CurrentSubKey + SubKey);
  515. bool Result = FRegistry->OpenKey(K, CanCreate);
  516. if (!Result && WasOpened)
  517. {
  518. FRegistry->OpenKey(PrevPath, false);
  519. }
  520. return Result;
  521. }
  522. //---------------------------------------------------------------------------
  523. void __fastcall TRegistryStorage::CloseSubKey()
  524. {
  525. FRegistry->CloseKey();
  526. THierarchicalStorage::CloseSubKey();
  527. if (FKeyHistory->Count)
  528. {
  529. FRegistry->OpenKey(Storage + GetCurrentSubKeyMunged(), True);
  530. }
  531. }
  532. //---------------------------------------------------------------------------
  533. bool __fastcall TRegistryStorage::DeleteSubKey(const UnicodeString SubKey)
  534. {
  535. UnicodeString K;
  536. if (FKeyHistory->Count == 0) K = Storage + CurrentSubKey;
  537. K += MungeKeyName(SubKey);
  538. return FRegistry->DeleteKey(K);
  539. }
  540. //---------------------------------------------------------------------------
  541. void __fastcall TRegistryStorage::GetSubKeyNames(Classes::TStrings* Strings)
  542. {
  543. FRegistry->GetKeyNames(Strings);
  544. for (int Index = 0; Index < Strings->Count; Index++)
  545. {
  546. Strings->Strings[Index] = UnMungeStr(Strings->Strings[Index]);
  547. }
  548. }
  549. //---------------------------------------------------------------------------
  550. void __fastcall TRegistryStorage::GetValueNames(Classes::TStrings* Strings)
  551. {
  552. FRegistry->GetValueNames(Strings);
  553. }
  554. //---------------------------------------------------------------------------
  555. bool __fastcall TRegistryStorage::DeleteValue(const UnicodeString Name)
  556. {
  557. return FRegistry->DeleteValue(Name);
  558. }
  559. //---------------------------------------------------------------------------
  560. bool __fastcall TRegistryStorage::DoKeyExists(const UnicodeString SubKey, bool AForceAnsi)
  561. {
  562. UnicodeString K = MungeStr(SubKey, AForceAnsi, false);
  563. bool Result = FRegistry->KeyExists(K);
  564. return Result;
  565. }
  566. //---------------------------------------------------------------------------
  567. bool __fastcall TRegistryStorage::ValueExists(const UnicodeString Value)
  568. {
  569. bool Result = FRegistry->ValueExists(Value);
  570. return Result;
  571. }
  572. //---------------------------------------------------------------------------
  573. size_t __fastcall TRegistryStorage::BinaryDataSize(const UnicodeString Name)
  574. {
  575. size_t Result = FRegistry->GetDataSize(Name);
  576. return Result;
  577. }
  578. //---------------------------------------------------------------------------
  579. bool __fastcall TRegistryStorage::ReadBool(const UnicodeString Name, bool Default)
  580. {
  581. READ_REGISTRY(ReadBool);
  582. }
  583. //---------------------------------------------------------------------------
  584. TDateTime __fastcall TRegistryStorage::ReadDateTime(const UnicodeString Name, TDateTime Default)
  585. {
  586. READ_REGISTRY(ReadDateTime);
  587. }
  588. //---------------------------------------------------------------------------
  589. double __fastcall TRegistryStorage::ReadFloat(const UnicodeString Name, double Default)
  590. {
  591. READ_REGISTRY(ReadFloat);
  592. }
  593. //---------------------------------------------------------------------------
  594. int __fastcall TRegistryStorage::ReadInteger(const UnicodeString Name, int Default)
  595. {
  596. READ_REGISTRY(ReadInteger);
  597. }
  598. //---------------------------------------------------------------------------
  599. __int64 __fastcall TRegistryStorage::ReadInt64(const UnicodeString Name, __int64 Default)
  600. {
  601. __int64 Result = Default;
  602. if (FRegistry->ValueExists(Name))
  603. {
  604. try
  605. {
  606. FRegistry->ReadBinaryData(Name, &Result, sizeof(Result));
  607. }
  608. catch(...)
  609. {
  610. }
  611. }
  612. return Result;
  613. }
  614. //---------------------------------------------------------------------------
  615. UnicodeString __fastcall TRegistryStorage::ReadStringRaw(const UnicodeString Name, const UnicodeString Default)
  616. {
  617. READ_REGISTRY(ReadString);
  618. }
  619. //---------------------------------------------------------------------------
  620. size_t __fastcall TRegistryStorage::ReadBinaryData(const UnicodeString Name,
  621. void * Buffer, size_t Size)
  622. {
  623. size_t Result;
  624. if (FRegistry->ValueExists(Name))
  625. {
  626. try
  627. {
  628. Result = FRegistry->ReadBinaryData(Name, Buffer, Size);
  629. }
  630. catch(...)
  631. {
  632. Result = 0;
  633. }
  634. }
  635. else
  636. {
  637. Result = 0;
  638. }
  639. return Result;
  640. }
  641. //---------------------------------------------------------------------------
  642. void __fastcall TRegistryStorage::WriteBool(const UnicodeString Name, bool Value)
  643. {
  644. WRITE_REGISTRY(WriteBool);
  645. }
  646. //---------------------------------------------------------------------------
  647. void __fastcall TRegistryStorage::WriteDateTime(const UnicodeString Name, TDateTime Value)
  648. {
  649. WRITE_REGISTRY(WriteDateTime);
  650. }
  651. //---------------------------------------------------------------------------
  652. void __fastcall TRegistryStorage::WriteFloat(const UnicodeString Name, double Value)
  653. {
  654. WRITE_REGISTRY(WriteFloat);
  655. }
  656. //---------------------------------------------------------------------------
  657. void __fastcall TRegistryStorage::WriteStringRaw(const UnicodeString Name, const UnicodeString Value)
  658. {
  659. WRITE_REGISTRY(WriteString);
  660. }
  661. //---------------------------------------------------------------------------
  662. void __fastcall TRegistryStorage::WriteInteger(const UnicodeString Name, int Value)
  663. {
  664. WRITE_REGISTRY(WriteInteger);
  665. }
  666. //---------------------------------------------------------------------------
  667. void __fastcall TRegistryStorage::WriteInt64(const UnicodeString Name, __int64 Value)
  668. {
  669. try
  670. {
  671. FRegistry->WriteBinaryData(Name, &Value, sizeof(Value));
  672. }
  673. catch(...)
  674. {
  675. }
  676. }
  677. //---------------------------------------------------------------------------
  678. void __fastcall TRegistryStorage::WriteBinaryData(const UnicodeString Name,
  679. const void * Buffer, int Size)
  680. {
  681. try
  682. {
  683. FRegistry->WriteBinaryData(Name, const_cast<void *>(Buffer), Size);
  684. }
  685. catch(...)
  686. {
  687. }
  688. }
  689. //===========================================================================
  690. __fastcall TCustomIniFileStorage::TCustomIniFileStorage(const UnicodeString Storage, TCustomIniFile * IniFile) :
  691. THierarchicalStorage(Storage),
  692. FIniFile(IniFile),
  693. FMasterStorageOpenFailures(0),
  694. FOpeningSubKey(false)
  695. {
  696. }
  697. //---------------------------------------------------------------------------
  698. __fastcall TCustomIniFileStorage::~TCustomIniFileStorage()
  699. {
  700. delete FIniFile;
  701. }
  702. //---------------------------------------------------------------------------
  703. UnicodeString __fastcall TCustomIniFileStorage::GetSource()
  704. {
  705. return Storage;
  706. }
  707. //---------------------------------------------------------------------------
  708. UnicodeString __fastcall TCustomIniFileStorage::GetCurrentSection()
  709. {
  710. return ExcludeTrailingBackslash(GetCurrentSubKeyMunged());
  711. }
  712. //---------------------------------------------------------------------------
  713. void __fastcall TCustomIniFileStorage::CacheSections()
  714. {
  715. if (FSections.get() == NULL)
  716. {
  717. FSections.reset(new TStringList());
  718. FIniFile->ReadSections(FSections.get());
  719. FSections->Sorted = true; // has to set only after reading as ReadSections reset it to false
  720. }
  721. }
  722. //---------------------------------------------------------------------------
  723. void __fastcall TCustomIniFileStorage::ResetCache()
  724. {
  725. FSections.reset(NULL);
  726. }
  727. //---------------------------------------------------------------------------
  728. void __fastcall TCustomIniFileStorage::SetAccessMode(TStorageAccessMode value)
  729. {
  730. if (FMasterStorage.get() != NULL)
  731. {
  732. FMasterStorage->AccessMode = value;
  733. }
  734. THierarchicalStorage::SetAccessMode(value);
  735. }
  736. //---------------------------------------------------------------------------
  737. bool __fastcall TCustomIniFileStorage::DoOpenSubKey(const UnicodeString SubKey, bool CanCreate)
  738. {
  739. bool Result = CanCreate;
  740. if (!Result)
  741. {
  742. CacheSections();
  743. UnicodeString NewKey = ExcludeTrailingBackslash(CurrentSubKey+SubKey);
  744. if (FSections->Count > 0)
  745. {
  746. int Index = -1;
  747. Result = FSections->Find(NewKey, Index);
  748. if (!Result &&
  749. (Index < FSections->Count) &&
  750. (FSections->Strings[Index].SubString(1, NewKey.Length()+1) == NewKey + L"\\"))
  751. {
  752. Result = true;
  753. }
  754. }
  755. }
  756. return Result;
  757. }
  758. //---------------------------------------------------------------------------
  759. bool __fastcall TCustomIniFileStorage::OpenRootKey(bool CanCreate)
  760. {
  761. // Not supported with master storage.
  762. // Actually currently, we use OpenRootKey with TRegistryStorage only.
  763. DebugAssert(FMasterStorage.get() == NULL);
  764. return THierarchicalStorage::OpenRootKey(CanCreate);
  765. }
  766. //---------------------------------------------------------------------------
  767. bool __fastcall TCustomIniFileStorage::OpenSubKey(UnicodeString Key, bool CanCreate, bool Path)
  768. {
  769. bool Result;
  770. {
  771. TAutoFlag Flag(FOpeningSubKey);
  772. Result = THierarchicalStorage::OpenSubKey(Key, CanCreate, Path);
  773. }
  774. if (FMasterStorage.get() != NULL)
  775. {
  776. if (FMasterStorageOpenFailures > 0)
  777. {
  778. FMasterStorageOpenFailures++;
  779. }
  780. else
  781. {
  782. bool MasterResult = FMasterStorage->OpenSubKey(Key, CanCreate, Path);
  783. if (!Result && MasterResult)
  784. {
  785. Result = THierarchicalStorage::OpenSubKey(Key, true, Path);
  786. DebugAssert(Result);
  787. }
  788. else if (Result && !MasterResult)
  789. {
  790. FMasterStorageOpenFailures++;
  791. }
  792. }
  793. }
  794. return Result;
  795. }
  796. //---------------------------------------------------------------------------
  797. void __fastcall TCustomIniFileStorage::CloseSubKey()
  798. {
  799. THierarchicalStorage::CloseSubKey();
  800. // What we are called to restore previous key from OpenSubKey,
  801. // when opening path component fails, the master storage was not involved yet
  802. if (!FOpeningSubKey && (FMasterStorage.get() != NULL))
  803. {
  804. if (FMasterStorageOpenFailures > 0)
  805. {
  806. FMasterStorageOpenFailures--;
  807. }
  808. else
  809. {
  810. FMasterStorage->CloseSubKey();
  811. }
  812. }
  813. }
  814. //---------------------------------------------------------------------------
  815. bool __fastcall TCustomIniFileStorage::DeleteSubKey(const UnicodeString SubKey)
  816. {
  817. bool Result;
  818. try
  819. {
  820. ResetCache();
  821. FIniFile->EraseSection(CurrentSubKey + MungeKeyName(SubKey));
  822. Result = true;
  823. }
  824. catch (...)
  825. {
  826. Result = false;
  827. }
  828. if (HandleByMasterStorage())
  829. {
  830. Result = FMasterStorage->DeleteSubKey(SubKey);
  831. }
  832. return Result;
  833. }
  834. //---------------------------------------------------------------------------
  835. void __fastcall TCustomIniFileStorage::GetSubKeyNames(Classes::TStrings* Strings)
  836. {
  837. Strings->Clear();
  838. if (HandleByMasterStorage())
  839. {
  840. FMasterStorage->GetSubKeyNames(Strings);
  841. }
  842. CacheSections();
  843. for (int i = 0; i < FSections->Count; i++)
  844. {
  845. UnicodeString Section = FSections->Strings[i];
  846. if (AnsiCompareText(CurrentSubKey,
  847. Section.SubString(1, CurrentSubKey.Length())) == 0)
  848. {
  849. UnicodeString SubSection = Section.SubString(CurrentSubKey.Length() + 1,
  850. Section.Length() - CurrentSubKey.Length());
  851. int P = SubSection.Pos(L"\\");
  852. if (P)
  853. {
  854. SubSection.SetLength(P - 1);
  855. }
  856. if (Strings->IndexOf(SubSection) < 0)
  857. {
  858. Strings->Add(UnMungeStr(SubSection));
  859. }
  860. }
  861. }
  862. }
  863. //---------------------------------------------------------------------------
  864. void __fastcall TCustomIniFileStorage::GetValueNames(Classes::TStrings* Strings)
  865. {
  866. if (HandleByMasterStorage())
  867. {
  868. FMasterStorage->GetValueNames(Strings);
  869. }
  870. FIniFile->ReadSection(CurrentSection, Strings);
  871. for (int Index = 0; Index < Strings->Count; Index++)
  872. {
  873. Strings->Strings[Index] = UnMungeIniName(Strings->Strings[Index]);
  874. }
  875. }
  876. //---------------------------------------------------------------------------
  877. bool __fastcall TCustomIniFileStorage::DoKeyExists(const UnicodeString SubKey, bool AForceAnsi)
  878. {
  879. return
  880. (HandleByMasterStorage() && FMasterStorage->DoKeyExists(SubKey, AForceAnsi)) ||
  881. FIniFile->SectionExists(CurrentSubKey + MungeStr(SubKey, AForceAnsi, false));
  882. }
  883. //---------------------------------------------------------------------------
  884. bool __fastcall TCustomIniFileStorage::DoValueExists(const UnicodeString & Value)
  885. {
  886. return FIniFile->ValueExists(CurrentSection, MungeIniName(Value));
  887. }
  888. //---------------------------------------------------------------------------
  889. bool __fastcall TCustomIniFileStorage::ValueExists(const UnicodeString Value)
  890. {
  891. return
  892. (HandleByMasterStorage() && FMasterStorage->ValueExists(Value)) ||
  893. DoValueExists(Value);
  894. }
  895. //---------------------------------------------------------------------------
  896. bool __fastcall TCustomIniFileStorage::DeleteValue(const UnicodeString Name)
  897. {
  898. bool Result = true;
  899. if (HandleByMasterStorage())
  900. {
  901. Result = FMasterStorage->DeleteValue(Name);
  902. }
  903. ResetCache();
  904. FIniFile->DeleteKey(CurrentSection, MungeIniName(Name));
  905. return Result;
  906. }
  907. //---------------------------------------------------------------------------
  908. bool __fastcall TCustomIniFileStorage::HandleByMasterStorage()
  909. {
  910. return
  911. (FMasterStorage.get() != NULL) &&
  912. (FMasterStorageOpenFailures == 0);
  913. }
  914. //---------------------------------------------------------------------------
  915. bool __fastcall TCustomIniFileStorage::HandleReadByMasterStorage(const UnicodeString & Name)
  916. {
  917. return HandleByMasterStorage() && !DoValueExists(Name);
  918. }
  919. //---------------------------------------------------------------------------
  920. size_t __fastcall TCustomIniFileStorage::BinaryDataSize(const UnicodeString Name)
  921. {
  922. if (HandleReadByMasterStorage(Name))
  923. {
  924. return FMasterStorage->BinaryDataSize(Name);
  925. }
  926. else
  927. {
  928. return ReadStringRaw(Name, L"").Length() / 2;
  929. }
  930. }
  931. //---------------------------------------------------------------------------
  932. bool __fastcall TCustomIniFileStorage::ReadBool(const UnicodeString Name, bool Default)
  933. {
  934. if (HandleReadByMasterStorage(Name))
  935. {
  936. return FMasterStorage->ReadBool(Name, Default);
  937. }
  938. else
  939. {
  940. return FIniFile->ReadBool(CurrentSection, MungeIniName(Name), Default);
  941. }
  942. }
  943. //---------------------------------------------------------------------------
  944. int __fastcall TCustomIniFileStorage::ReadInteger(const UnicodeString Name, int Default)
  945. {
  946. int Result;
  947. if (HandleReadByMasterStorage(Name))
  948. {
  949. Result = FMasterStorage->ReadInteger(Name, Default);
  950. }
  951. else
  952. {
  953. Result = FIniFile->ReadInteger(CurrentSection, MungeIniName(Name), Default);
  954. }
  955. return Result;
  956. }
  957. //---------------------------------------------------------------------------
  958. __int64 __fastcall TCustomIniFileStorage::ReadInt64(const UnicodeString Name, __int64 Default)
  959. {
  960. __int64 Result;
  961. if (HandleReadByMasterStorage(Name))
  962. {
  963. Result = FMasterStorage->ReadInt64(Name, Default);
  964. }
  965. else
  966. {
  967. Result = Default;
  968. UnicodeString Str;
  969. Str = ReadStringRaw(Name, L"");
  970. if (!Str.IsEmpty())
  971. {
  972. Result = StrToInt64Def(Str, Default);
  973. }
  974. }
  975. return Result;
  976. }
  977. //---------------------------------------------------------------------------
  978. TDateTime __fastcall TCustomIniFileStorage::ReadDateTime(const UnicodeString Name, TDateTime Default)
  979. {
  980. TDateTime Result;
  981. if (HandleReadByMasterStorage(Name))
  982. {
  983. Result = FMasterStorage->ReadDateTime(Name, Default);
  984. }
  985. else
  986. {
  987. UnicodeString Value = FIniFile->ReadString(CurrentSection, MungeIniName(Name), L"");
  988. if (Value.IsEmpty())
  989. {
  990. Result = Default;
  991. }
  992. else
  993. {
  994. try
  995. {
  996. RawByteString Raw = HexToBytes(Value);
  997. if (static_cast<size_t>(Raw.Length()) == sizeof(Result))
  998. {
  999. memcpy(&Result, Raw.c_str(), sizeof(Result));
  1000. }
  1001. else
  1002. {
  1003. Result = StrToDateTime(Value);
  1004. }
  1005. }
  1006. catch(...)
  1007. {
  1008. Result = Default;
  1009. }
  1010. }
  1011. }
  1012. return Result;
  1013. }
  1014. //---------------------------------------------------------------------------
  1015. double __fastcall TCustomIniFileStorage::ReadFloat(const UnicodeString Name, double Default)
  1016. {
  1017. double Result;
  1018. if (HandleReadByMasterStorage(Name))
  1019. {
  1020. Result = FMasterStorage->ReadFloat(Name, Default);
  1021. }
  1022. else
  1023. {
  1024. UnicodeString Value = FIniFile->ReadString(CurrentSection, MungeIniName(Name), L"");
  1025. if (Value.IsEmpty())
  1026. {
  1027. Result = Default;
  1028. }
  1029. else
  1030. {
  1031. try
  1032. {
  1033. RawByteString Raw = HexToBytes(Value);
  1034. if (static_cast<size_t>(Raw.Length()) == sizeof(Result))
  1035. {
  1036. memcpy(&Result, Raw.c_str(), sizeof(Result));
  1037. }
  1038. else
  1039. {
  1040. Result = static_cast<double>(StrToFloat(Value));
  1041. }
  1042. }
  1043. catch(...)
  1044. {
  1045. Result = Default;
  1046. }
  1047. }
  1048. }
  1049. return Result;
  1050. }
  1051. //---------------------------------------------------------------------------
  1052. UnicodeString __fastcall TCustomIniFileStorage::ReadStringRaw(const UnicodeString Name, UnicodeString Default)
  1053. {
  1054. UnicodeString Result;
  1055. if (HandleReadByMasterStorage(Name))
  1056. {
  1057. Result = FMasterStorage->ReadStringRaw(Name, Default);
  1058. }
  1059. else
  1060. {
  1061. Result = FIniFile->ReadString(CurrentSection, MungeIniName(Name), Default);
  1062. }
  1063. return Result;
  1064. }
  1065. //---------------------------------------------------------------------------
  1066. size_t __fastcall TCustomIniFileStorage::ReadBinaryData(const UnicodeString Name,
  1067. void * Buffer, size_t Size)
  1068. {
  1069. size_t Len;
  1070. if (HandleReadByMasterStorage(Name))
  1071. {
  1072. FMasterStorage->ReadBinaryData(Name, Buffer, Size);
  1073. }
  1074. else
  1075. {
  1076. RawByteString Value = HexToBytes(ReadStringRaw(Name, L""));
  1077. Len = Value.Length();
  1078. if (Size > Len)
  1079. {
  1080. Size = Len;
  1081. }
  1082. DebugAssert(Buffer);
  1083. memcpy(Buffer, Value.c_str(), Size);
  1084. }
  1085. return Size;
  1086. }
  1087. //---------------------------------------------------------------------------
  1088. void __fastcall TCustomIniFileStorage::WriteBool(const UnicodeString Name, bool Value)
  1089. {
  1090. if (HandleByMasterStorage())
  1091. {
  1092. FMasterStorage->WriteBool(Name, Value);
  1093. }
  1094. ResetCache();
  1095. FIniFile->WriteBool(CurrentSection, MungeIniName(Name), Value);
  1096. }
  1097. //---------------------------------------------------------------------------
  1098. void __fastcall TCustomIniFileStorage::WriteInteger(const UnicodeString Name, int Value)
  1099. {
  1100. if (HandleByMasterStorage())
  1101. {
  1102. FMasterStorage->WriteInteger(Name, Value);
  1103. }
  1104. ResetCache();
  1105. FIniFile->WriteInteger(CurrentSection, MungeIniName(Name), Value);
  1106. }
  1107. //---------------------------------------------------------------------------
  1108. void __fastcall TCustomIniFileStorage::WriteInt64(const UnicodeString Name, __int64 Value)
  1109. {
  1110. if (HandleByMasterStorage())
  1111. {
  1112. FMasterStorage->WriteInt64(Name, Value);
  1113. }
  1114. DoWriteStringRaw(Name, IntToStr(Value));
  1115. }
  1116. //---------------------------------------------------------------------------
  1117. void __fastcall TCustomIniFileStorage::WriteDateTime(const UnicodeString Name, TDateTime Value)
  1118. {
  1119. if (HandleByMasterStorage())
  1120. {
  1121. FMasterStorage->WriteDateTime(Name, Value);
  1122. }
  1123. DoWriteBinaryData(Name, &Value, sizeof(Value));
  1124. }
  1125. //---------------------------------------------------------------------------
  1126. void __fastcall TCustomIniFileStorage::WriteFloat(const UnicodeString Name, double Value)
  1127. {
  1128. if (HandleByMasterStorage())
  1129. {
  1130. FMasterStorage->WriteFloat(Name, Value);
  1131. }
  1132. DoWriteBinaryData(Name, &Value, sizeof(Value));
  1133. }
  1134. //---------------------------------------------------------------------------
  1135. void __fastcall TCustomIniFileStorage::DoWriteStringRaw(const UnicodeString & Name, const UnicodeString & Value)
  1136. {
  1137. ResetCache();
  1138. FIniFile->WriteString(CurrentSection, MungeIniName(Name), Value);
  1139. }
  1140. //---------------------------------------------------------------------------
  1141. void __fastcall TCustomIniFileStorage::WriteStringRaw(const UnicodeString Name, const UnicodeString Value)
  1142. {
  1143. if (HandleByMasterStorage())
  1144. {
  1145. FMasterStorage->WriteStringRaw(Name, Value);
  1146. }
  1147. DoWriteStringRaw(Name, Value);
  1148. }
  1149. //---------------------------------------------------------------------------
  1150. void __fastcall TCustomIniFileStorage::DoWriteBinaryData(const UnicodeString & Name,
  1151. const void * Buffer, int Size)
  1152. {
  1153. DoWriteStringRaw(Name, BytesToHex(RawByteString(static_cast<const char*>(Buffer), Size)));
  1154. }
  1155. //---------------------------------------------------------------------------
  1156. void __fastcall TCustomIniFileStorage::WriteBinaryData(const UnicodeString Name,
  1157. const void * Buffer, int Size)
  1158. {
  1159. if (HandleByMasterStorage())
  1160. {
  1161. FMasterStorage->WriteBinaryData(Name, Buffer, Size);
  1162. }
  1163. DoWriteBinaryData(Name, Buffer, Size);
  1164. }
  1165. //===========================================================================
  1166. TIniFileStorage * __fastcall TIniFileStorage::CreateFromPath(const UnicodeString AStorage)
  1167. {
  1168. // The code was originally inline in the parent contructor call in the TIniFileStorage::TIniFileStorage [public originally].
  1169. // But if the TMemIniFile constructor throws (e.g. because the INI file is locked), the exception causes access violation.
  1170. // Moving the code to a factory solves this.
  1171. TMemIniFile * IniFile = new TMemIniFile(AStorage);
  1172. return new TIniFileStorage(AStorage, IniFile);
  1173. }
  1174. //---------------------------------------------------------------------------
  1175. __fastcall TIniFileStorage::TIniFileStorage(const UnicodeString AStorage, TCustomIniFile * IniFile):
  1176. TCustomIniFileStorage(AStorage, IniFile)
  1177. {
  1178. FOriginal = new TStringList();
  1179. dynamic_cast<TMemIniFile *>(FIniFile)->GetStrings(FOriginal);
  1180. ApplyOverrides();
  1181. }
  1182. //---------------------------------------------------------------------------
  1183. void __fastcall TIniFileStorage::Flush()
  1184. {
  1185. if (FMasterStorage.get() != NULL)
  1186. {
  1187. FMasterStorage->Flush();
  1188. }
  1189. if (FOriginal != NULL)
  1190. {
  1191. TStrings * Strings = new TStringList;
  1192. try
  1193. {
  1194. dynamic_cast<TMemIniFile *>(FIniFile)->GetStrings(Strings);
  1195. if (!Strings->Equals(FOriginal))
  1196. {
  1197. int Attr;
  1198. // preserve attributes (especially hidden)
  1199. bool Exists = FileExists(ApiPath(Storage));
  1200. if (Exists)
  1201. {
  1202. Attr = GetFileAttributes(ApiPath(Storage).c_str());
  1203. }
  1204. else
  1205. {
  1206. Attr = FILE_ATTRIBUTE_NORMAL;
  1207. }
  1208. if (FLAGSET(Attr, FILE_ATTRIBUTE_READONLY) && ForceSave)
  1209. {
  1210. SetFileAttributes(ApiPath(Storage).c_str(), Attr & ~FILE_ATTRIBUTE_READONLY);
  1211. }
  1212. HANDLE Handle = CreateFile(ApiPath(Storage).c_str(), GENERIC_READ | GENERIC_WRITE,
  1213. 0, NULL, CREATE_ALWAYS, Attr, 0);
  1214. if (Handle == INVALID_HANDLE_VALUE)
  1215. {
  1216. // "access denied" errors upon implicit saves to existing file are ignored
  1217. if (Explicit || !Exists || (GetLastError() != ERROR_ACCESS_DENIED))
  1218. {
  1219. throw EOSExtException(FMTLOAD((Exists ? WRITE_ERROR : CREATE_FILE_ERROR), (Storage)));
  1220. }
  1221. }
  1222. else
  1223. {
  1224. TStream * Stream = new THandleStream(int(Handle));
  1225. try
  1226. {
  1227. Strings->SaveToStream(Stream);
  1228. }
  1229. __finally
  1230. {
  1231. CloseHandle(Handle);
  1232. delete Stream;
  1233. }
  1234. }
  1235. }
  1236. }
  1237. __finally
  1238. {
  1239. delete FOriginal;
  1240. FOriginal = NULL;
  1241. delete Strings;
  1242. }
  1243. }
  1244. }
  1245. //---------------------------------------------------------------------------
  1246. __fastcall TIniFileStorage::~TIniFileStorage()
  1247. {
  1248. Flush();
  1249. }
  1250. //---------------------------------------------------------------------------
  1251. void __fastcall TIniFileStorage::ApplyOverrides()
  1252. {
  1253. UnicodeString OverridesKey = IncludeTrailingBackslash(L"Override");
  1254. CacheSections();
  1255. for (int i = 0; i < FSections->Count; i++)
  1256. {
  1257. UnicodeString Section = FSections->Strings[i];
  1258. if (SameText(OverridesKey,
  1259. Section.SubString(1, OverridesKey.Length())))
  1260. {
  1261. UnicodeString SubKey = Section.SubString(OverridesKey.Length() + 1,
  1262. Section.Length() - OverridesKey.Length());
  1263. // this all uses raw names (munged)
  1264. TStrings * Names = new TStringList;
  1265. try
  1266. {
  1267. FIniFile->ReadSection(Section, Names);
  1268. for (int ii = 0; ii < Names->Count; ii++)
  1269. {
  1270. UnicodeString Name = Names->Strings[ii];
  1271. UnicodeString Value = FIniFile->ReadString(Section, Name, L"");
  1272. FIniFile->WriteString(SubKey, Name, Value);
  1273. }
  1274. }
  1275. __finally
  1276. {
  1277. delete Names;
  1278. }
  1279. FIniFile->EraseSection(Section);
  1280. ResetCache();
  1281. }
  1282. }
  1283. }
  1284. //===========================================================================
  1285. enum TWriteMode { wmAllow, wmFail, wmIgnore };
  1286. //---------------------------------------------------------------------------
  1287. class TOptionsIniFile : public TCustomIniFile
  1288. {
  1289. public:
  1290. __fastcall TOptionsIniFile(TStrings * Options, TWriteMode WriteMode, const UnicodeString & RootKey);
  1291. virtual UnicodeString __fastcall ReadString(const UnicodeString Section, const UnicodeString Ident, const UnicodeString Default);
  1292. virtual void __fastcall WriteString(const UnicodeString Section, const UnicodeString Ident, const UnicodeString Value);
  1293. virtual void __fastcall ReadSection(const UnicodeString Section, TStrings * Strings);
  1294. virtual void __fastcall ReadSections(TStrings* Strings);
  1295. virtual void __fastcall ReadSectionValues(const UnicodeString Section, TStrings* Strings);
  1296. virtual void __fastcall EraseSection(const UnicodeString Section);
  1297. virtual void __fastcall DeleteKey(const UnicodeString Section, const UnicodeString Ident);
  1298. virtual void __fastcall UpdateFile();
  1299. // Hoisted overload
  1300. void __fastcall ReadSections(const UnicodeString Section, TStrings* Strings);
  1301. // Ntb, we can implement ValueExists more efficiently than the TCustomIniFile.ValueExists
  1302. private:
  1303. TStrings * FOptions;
  1304. TWriteMode FWriteMode;
  1305. UnicodeString FRootKey;
  1306. bool __fastcall AllowWrite();
  1307. void __fastcall NotImplemented();
  1308. bool __fastcall AllowSection(const UnicodeString & Section);
  1309. UnicodeString __fastcall FormatKey(const UnicodeString & Section, const UnicodeString & Ident);
  1310. };
  1311. //---------------------------------------------------------------------------
  1312. __fastcall TOptionsIniFile::TOptionsIniFile(TStrings * Options, TWriteMode WriteMode, const UnicodeString & RootKey) :
  1313. TCustomIniFile(UnicodeString())
  1314. {
  1315. FOptions = Options;
  1316. FWriteMode = WriteMode;
  1317. FRootKey = RootKey;
  1318. if (!FRootKey.IsEmpty())
  1319. {
  1320. FRootKey += PathDelim;
  1321. }
  1322. }
  1323. //---------------------------------------------------------------------------
  1324. void __fastcall TOptionsIniFile::NotImplemented()
  1325. {
  1326. throw Exception(L"Not implemented");
  1327. }
  1328. //---------------------------------------------------------------------------
  1329. bool __fastcall TOptionsIniFile::AllowWrite()
  1330. {
  1331. switch (FWriteMode)
  1332. {
  1333. case wmAllow:
  1334. return true;
  1335. case wmFail:
  1336. NotImplemented();
  1337. return false; // never gets here
  1338. case wmIgnore:
  1339. return false;
  1340. default:
  1341. DebugFail();
  1342. return false;
  1343. }
  1344. }
  1345. //---------------------------------------------------------------------------
  1346. bool __fastcall TOptionsIniFile::AllowSection(const UnicodeString & Section)
  1347. {
  1348. UnicodeString Name = Section;
  1349. if (!Name.IsEmpty())
  1350. {
  1351. Name += PathDelim;
  1352. }
  1353. bool Result = SameText(Name.SubString(1, FRootKey.Length()), FRootKey);
  1354. return Result;
  1355. }
  1356. //---------------------------------------------------------------------------
  1357. UnicodeString __fastcall TOptionsIniFile::FormatKey(const UnicodeString & Section, const UnicodeString & Ident)
  1358. {
  1359. UnicodeString Result = Section;
  1360. if (!Result.IsEmpty())
  1361. {
  1362. Result += PathDelim;
  1363. }
  1364. Result += Ident; // Can be empty, when called from a contructor, AllowSection or ReadSection
  1365. if (DebugAlwaysTrue(AllowSection(Section)))
  1366. {
  1367. Result.Delete(1, FRootKey.Length());
  1368. }
  1369. return Result;
  1370. }
  1371. //---------------------------------------------------------------------------
  1372. UnicodeString __fastcall TOptionsIniFile::ReadString(const UnicodeString Section, const UnicodeString Ident, const UnicodeString Default)
  1373. {
  1374. UnicodeString Value;
  1375. if (!AllowSection(Section))
  1376. {
  1377. Value = Default;
  1378. }
  1379. else
  1380. {
  1381. UnicodeString Name = FormatKey(Section, Ident);
  1382. int Index = FOptions->IndexOfName(Name);
  1383. if (Index >= 0)
  1384. {
  1385. Value = FOptions->ValueFromIndex[Index];
  1386. }
  1387. else
  1388. {
  1389. Value = Default;
  1390. }
  1391. }
  1392. return Value;
  1393. }
  1394. //---------------------------------------------------------------------------
  1395. void __fastcall TOptionsIniFile::WriteString(const UnicodeString Section, const UnicodeString Ident, const UnicodeString Value)
  1396. {
  1397. if (AllowWrite() &&
  1398. DebugAlwaysTrue(AllowSection(Section)))
  1399. {
  1400. UnicodeString Name = FormatKey(Section, Ident);
  1401. FOptions->Values[Name] = Value;
  1402. }
  1403. }
  1404. //---------------------------------------------------------------------------
  1405. void __fastcall TOptionsIniFile::ReadSection(const UnicodeString Section, TStrings * Strings)
  1406. {
  1407. if (AllowSection(Section))
  1408. {
  1409. UnicodeString SectionPrefix = FormatKey(Section, UnicodeString());
  1410. Strings->BeginUpdate();
  1411. try
  1412. {
  1413. for (int Index = 0; Index < FOptions->Count; Index++)
  1414. {
  1415. UnicodeString Name = FOptions->Names[Index];
  1416. if (SameText(Name.SubString(1, SectionPrefix.Length()), SectionPrefix) &&
  1417. (LastDelimiter(PathDelim, Name) <= SectionPrefix.Length()))
  1418. {
  1419. Strings->Add(Name.SubString(SectionPrefix.Length() + 1, Name.Length() - SectionPrefix.Length()));
  1420. }
  1421. }
  1422. }
  1423. __finally
  1424. {
  1425. Strings->EndUpdate();
  1426. }
  1427. }
  1428. }
  1429. //---------------------------------------------------------------------------
  1430. void __fastcall TOptionsIniFile::ReadSections(TStrings * Strings)
  1431. {
  1432. std::unique_ptr<TStringList> Sections(CreateSortedStringList());
  1433. for (int Index = 0; Index < FOptions->Count; Index++)
  1434. {
  1435. UnicodeString Name = FOptions->Names[Index];
  1436. int P = LastDelimiter(PathDelim, Name);
  1437. if (P > 0)
  1438. {
  1439. UnicodeString Section = Name.SubString(1, P - 1);
  1440. if (Sections->IndexOf(Section) < 0)
  1441. {
  1442. Sections->Add(Section);
  1443. }
  1444. }
  1445. }
  1446. for (int Index = 0; Index < Sections->Count; Index++)
  1447. {
  1448. Strings->Add(FRootKey + Sections->Strings[Index]);
  1449. }
  1450. }
  1451. //---------------------------------------------------------------------------
  1452. void __fastcall TOptionsIniFile::ReadSectionValues(const UnicodeString Section, TStrings * /*Strings*/)
  1453. {
  1454. NotImplemented();
  1455. }
  1456. //---------------------------------------------------------------------------
  1457. void __fastcall TOptionsIniFile::EraseSection(const UnicodeString Section)
  1458. {
  1459. if (AllowWrite())
  1460. {
  1461. NotImplemented();
  1462. }
  1463. }
  1464. //---------------------------------------------------------------------------
  1465. void __fastcall TOptionsIniFile::DeleteKey(const UnicodeString Section, const UnicodeString Ident)
  1466. {
  1467. if (AllowWrite() &&
  1468. DebugAlwaysTrue(AllowSection(Section)))
  1469. {
  1470. UnicodeString Name = FormatKey(Section, Ident);
  1471. int Index = FOptions->IndexOfName(Name);
  1472. if (Index >= 0)
  1473. {
  1474. FOptions->Delete(Index);
  1475. }
  1476. }
  1477. }
  1478. //---------------------------------------------------------------------------
  1479. void __fastcall TOptionsIniFile::UpdateFile()
  1480. {
  1481. if (AllowWrite())
  1482. {
  1483. // noop
  1484. }
  1485. }
  1486. //---------------------------------------------------------------------------
  1487. void __fastcall TOptionsIniFile::ReadSections(const UnicodeString /*Section*/, TStrings * /*Strings*/)
  1488. {
  1489. NotImplemented();
  1490. }
  1491. //===========================================================================
  1492. __fastcall TOptionsStorage::TOptionsStorage(TStrings * Options, bool AllowWrite):
  1493. TCustomIniFileStorage(
  1494. UnicodeString(L"Command-line options"),
  1495. new TOptionsIniFile(Options, (AllowWrite ? wmAllow : wmFail), UnicodeString()))
  1496. {
  1497. }
  1498. //---------------------------------------------------------------------------
  1499. __fastcall TOptionsStorage::TOptionsStorage(TStrings * Options, const UnicodeString & RootKey, THierarchicalStorage * MasterStorage) :
  1500. TCustomIniFileStorage(
  1501. UnicodeString(L"Command-line options overriding " + MasterStorage->Source),
  1502. new TOptionsIniFile(Options, wmIgnore, RootKey))
  1503. {
  1504. FMasterStorage.reset(MasterStorage);
  1505. }
  1506. //---------------------------------------------------------------------------
  1507. bool __fastcall TOptionsStorage::GetTemporary()
  1508. {
  1509. return true;
  1510. }