HierarchicalStorage.cpp 47 KB

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