HierarchicalStorage.cpp 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114
  1. //---------------------------------------------------------------------------
  2. #include <CorePCH.h>
  3. #pragma hdrstop
  4. #include "Exceptions.h"
  5. #include "PuttyIntf.h"
  6. #include "HierarchicalStorage.h"
  7. //---------------------------------------------------------------------------
  8. // ValueExists test was probably added to avoid registry exceptions when debugging
  9. #define READ_REGISTRY(Method) \
  10. if (FRegistry->ValueExists(Name)) \
  11. try { return FRegistry->Method(Name); } catch(...) { return Default; } \
  12. else return Default;
  13. #define WRITE_REGISTRY(Method) \
  14. try { FRegistry->Method(Name, Value); } catch(...) { }
  15. //---------------------------------------------------------------------------
  16. UnicodeString PuttyEscape(const RawByteString & Source, bool Value)
  17. {
  18. strbuf * sb = strbuf_new();
  19. escape_registry_key(Source.c_str(), sb);
  20. RawByteString Dest(sb->s);
  21. strbuf_free(sb);
  22. if (Value)
  23. {
  24. // We do not want to munge * in PasswordMask
  25. Dest = ReplaceStr(Dest, L"%2A", L"*");
  26. }
  27. return UnicodeString(Dest.c_str(), Dest.Length());
  28. }
  29. //---------------------------------------------------------------------------
  30. bool ToUnicode(const UnicodeString & Str, RawByteString & Utf)
  31. {
  32. Utf = RawByteString(UTF8String(Str));
  33. bool Result = (Utf.Length() > Str.Length());
  34. if (Result)
  35. {
  36. Utf.Insert(Bom, 1);
  37. }
  38. return Result;
  39. }
  40. //---------------------------------------------------------------------------
  41. UnicodeString __fastcall MungeStr(const UnicodeString & Str, bool ForceAnsi, bool Value)
  42. {
  43. RawByteString Source;
  44. if (ForceAnsi)
  45. {
  46. Source = RawByteString(PuttyStr(Str));
  47. }
  48. else
  49. {
  50. ToUnicode(Str, Source);
  51. }
  52. return PuttyEscape(Source, Value);
  53. }
  54. //---------------------------------------------------------------------------
  55. UnicodeString __fastcall UnMungeStr(const UnicodeString & Str)
  56. {
  57. // Str should contain ASCII characters only
  58. RawByteString Source = AnsiString(Str);
  59. strbuf * sb = strbuf_new();
  60. unescape_registry_key(Source.c_str(), sb);
  61. RawByteString Dest(sb->s);
  62. strbuf_free(sb);
  63. UnicodeString Result;
  64. if (Dest.SubString(1, strlen(Bom)) == Bom)
  65. {
  66. Dest.Delete(1, strlen(Bom));
  67. Result = UTF8ToString(Dest);
  68. }
  69. else
  70. {
  71. Result = AnsiToString(Dest);
  72. }
  73. return Result;
  74. }
  75. //---------------------------------------------------------------------------
  76. AnsiString PuttyStr(const UnicodeString & Str)
  77. {
  78. return AnsiString(Str);
  79. }
  80. //---------------------------------------------------------------------------
  81. UnicodeString __fastcall PuttyMungeStr(const UnicodeString & Str)
  82. {
  83. return MungeStr(Str, true, false);
  84. }
  85. //---------------------------------------------------------------------------
  86. UnicodeString __fastcall MungeIniName(const UnicodeString & Str, bool ForceAnsi)
  87. {
  88. bool NeedEscaping = false;
  89. for (int Index = 1; !NeedEscaping && (Index <= Str.Length()); Index++)
  90. {
  91. wchar_t Ch = Str[Index];
  92. NeedEscaping = IsWideChar(Ch) || (Ch == L'=');
  93. }
  94. UnicodeString Result;
  95. if (!ForceAnsi && NeedEscaping)
  96. {
  97. RawByteString Utf;
  98. ToUnicode(Str, Utf);
  99. Result = PuttyEscape(Utf, false);
  100. }
  101. else
  102. {
  103. Result = Str;
  104. }
  105. Result = ReplaceStr(Result, L"=", L"%3D");
  106. return Result;
  107. }
  108. //---------------------------------------------------------------------------
  109. static UnicodeString EscapedBom(TraceInitStr(PuttyEscape(Bom, false)));
  110. //---------------------------------------------------------------------------
  111. UnicodeString __fastcall UnMungeIniName(const UnicodeString & Str)
  112. {
  113. UnicodeString Result;
  114. if (StartsStr(EscapedBom, Str))
  115. {
  116. Result = UnMungeStr(Str);
  117. }
  118. else
  119. {
  120. // Backward compatibility only, with versions that did not Unicode-encoded strings with =.
  121. // Can be dropped eventually.
  122. int P = Str.Pos(L"%3D");
  123. if (P > 0)
  124. {
  125. Result = ReplaceStr(Str, L"%3D", L"=");
  126. }
  127. else
  128. {
  129. Result = Str;
  130. }
  131. }
  132. return Result;
  133. }
  134. //---------------------------------------------------------------------------
  135. template<typename T>
  136. void AddIntMapping(TIntMapping & Mapping, const wchar_t * Name, const T & Value)
  137. {
  138. if (Name != NULL)
  139. {
  140. Mapping.insert(std::make_pair(UnicodeString(Name), Value));
  141. }
  142. }
  143. //---------------------------------------------------------------------------
  144. template<typename T>
  145. TIntMapping CreateIntMapping(
  146. const wchar_t * Name1, const T & Value1,
  147. const wchar_t * Name2 = NULL, const T & Value2 = T(0),
  148. const wchar_t * Name3 = NULL, const T & Value3 = T(0))
  149. {
  150. TIntMapping Result;
  151. AddIntMapping(Result, Name1, Value1);
  152. AddIntMapping(Result, Name2, Value2);
  153. AddIntMapping(Result, Name3, Value3);
  154. return Result;
  155. }
  156. //---------------------------------------------------------------------------
  157. TIntMapping CreateIntMappingFromEnumNames(const UnicodeString & ANames)
  158. {
  159. UnicodeString Names(ANames);
  160. TIntMapping Result;
  161. int Index = 0;
  162. while (!Names.IsEmpty())
  163. {
  164. UnicodeString Name = CutToChar(Names, L';', true);
  165. Result.insert(std::make_pair(Name, Index));
  166. Index++;
  167. }
  168. return Result;
  169. }
  170. //---------------------------------------------------------------------------
  171. TIntMapping AutoSwitchMapping = CreateIntMapping(L"on", asOn, L"off", asOff, L"auto", asAuto);
  172. TIntMapping AutoSwitchReversedMapping = CreateIntMapping(L"on", asOff, L"off", asOn, L"auto", asAuto);
  173. static TIntMapping BoolMapping = CreateIntMapping(L"on", true, L"off", false);
  174. //===========================================================================
  175. static UnicodeString AccessValueName(L"Access");
  176. static UnicodeString DefaultAccessString(L"inherit");
  177. //---------------------------------------------------------------------------
  178. __fastcall THierarchicalStorage::THierarchicalStorage(const UnicodeString & AStorage)
  179. {
  180. FStorage = AStorage;
  181. AccessMode = smRead;
  182. Explicit = false;
  183. ForceSave = false;
  184. // While this was implemented in 5.0 already, for some reason
  185. // it was disabled (by mistake?). So although enabled for 5.6.1 only,
  186. // data written in Unicode/UTF8 can be read by all versions back to 5.0.
  187. ForceAnsi = false;
  188. MungeStringValues = true;
  189. FFakeReadOnlyOpens = 0;
  190. FRootAccess = -1;
  191. }
  192. //---------------------------------------------------------------------------
  193. __fastcall THierarchicalStorage::~THierarchicalStorage()
  194. {
  195. }
  196. //---------------------------------------------------------------------------
  197. void __fastcall THierarchicalStorage::Flush()
  198. {
  199. }
  200. //---------------------------------------------------------------------------
  201. void __fastcall THierarchicalStorage::SetAccessMode(TStorageAccessMode value)
  202. {
  203. FAccessMode = value;
  204. }
  205. //---------------------------------------------------------------------------
  206. UnicodeString __fastcall THierarchicalStorage::GetCurrentSubKeyMunged()
  207. {
  208. if (!FKeyHistory.empty())
  209. {
  210. return FKeyHistory.back().Key;
  211. }
  212. else
  213. {
  214. return UnicodeString();
  215. }
  216. }
  217. //---------------------------------------------------------------------------
  218. UnicodeString __fastcall THierarchicalStorage::GetCurrentSubKey()
  219. {
  220. return UnMungeStr(GetCurrentSubKeyMunged());
  221. }
  222. //---------------------------------------------------------------------------
  223. void __fastcall THierarchicalStorage::ConfigureForPutty()
  224. {
  225. MungeStringValues = false;
  226. ForceAnsi = true;
  227. }
  228. //---------------------------------------------------------------------------
  229. bool __fastcall THierarchicalStorage::OpenRootKey(bool CanCreate)
  230. {
  231. // This do not seem to be doing what it advertises.
  232. // It probably "works" only when used as a first "Open". So let's verify that by this assertion.
  233. DebugAssert(CurrentSubKey.IsEmpty());
  234. return OpenSubKey(UnicodeString(), CanCreate);
  235. }
  236. //---------------------------------------------------------------------------
  237. bool THierarchicalStorage::MungingKeyName(const UnicodeString & Key)
  238. {
  239. UnicodeString K = CurrentSubKey + Key + L"\\";
  240. return UnmungedRoot.IsEmpty() || !SameText(LeftStr(UnmungedRoot + L"\\", K.Length()), K);
  241. }
  242. //---------------------------------------------------------------------------
  243. UnicodeString __fastcall THierarchicalStorage::MungeKeyName(const UnicodeString & Key)
  244. {
  245. UnicodeString Result;
  246. if (!MungingKeyName(Key))
  247. {
  248. Result = Key;
  249. }
  250. else
  251. {
  252. Result = MungeStr(Key, ForceAnsi, false);
  253. // if there's already ANSI-munged subkey, keep ANSI munging
  254. if ((Result != Key) && !ForceAnsi && CanRead() && DoKeyExists(Key, true))
  255. {
  256. Result = MungeStr(Key, true, false);
  257. }
  258. }
  259. return Result;
  260. }
  261. //---------------------------------------------------------------------------
  262. UnicodeString THierarchicalStorage::MungeIniName(const UnicodeString & Str)
  263. {
  264. UnicodeString Result = ::MungeIniName(Str, ForceAnsi);
  265. // This does not handle Ansi-encoded value with equal sign, but that's an edge case
  266. if ((Result != Str) && !ForceAnsi && CanRead() && DoValueExists(Str, true))
  267. {
  268. Result = ::MungeIniName(Str, true);
  269. }
  270. return Result;
  271. }
  272. //---------------------------------------------------------------------------
  273. UnicodeString __fastcall THierarchicalStorage::DoReadRootAccessString()
  274. {
  275. UnicodeString Result;
  276. if (OpenRootKey(false))
  277. {
  278. Result = ReadAccessString();
  279. CloseSubKey();
  280. }
  281. else
  282. {
  283. Result = DefaultAccessString;
  284. }
  285. return Result;
  286. }
  287. //---------------------------------------------------------------------------
  288. UnicodeString __fastcall THierarchicalStorage::ReadAccessString()
  289. {
  290. UnicodeString Result;
  291. if (!FKeyHistory.empty())
  292. {
  293. Result = ReadString(AccessValueName, DefaultAccessString);
  294. }
  295. else
  296. {
  297. Result = DoReadRootAccessString();
  298. }
  299. return Result;
  300. }
  301. //---------------------------------------------------------------------------
  302. unsigned int __fastcall THierarchicalStorage::ReadAccess(unsigned int CurrentAccess)
  303. {
  304. UnicodeString Access = ReadAccessString();
  305. unsigned int Result = 0;
  306. while (!Access.IsEmpty())
  307. {
  308. UnicodeString Token = CutToChar(Access, L',', true);
  309. if (SameText(Token, L"inherit"))
  310. {
  311. Result |= CurrentAccess;
  312. }
  313. else if (SameText(Token, "read"))
  314. {
  315. Result |= hsaRead;
  316. }
  317. else if (SameText(Token, "full"))
  318. {
  319. Result |= hsaRead | hsaWrite;
  320. }
  321. }
  322. return Result;
  323. }
  324. //---------------------------------------------------------------------------
  325. unsigned int __fastcall THierarchicalStorage::GetCurrentAccess()
  326. {
  327. unsigned int Result;
  328. if (!FKeyHistory.empty())
  329. {
  330. // We must have resolved root access when opening the sub key the latest.
  331. DebugAssert(FRootAccess >= 0);
  332. Result = FKeyHistory.back().Access;
  333. }
  334. else
  335. {
  336. if (FRootAccess < 0)
  337. {
  338. FRootAccess = hsaRead; // Prevent recursion to allow reading the access
  339. FRootAccess = ReadAccess(hsaRead | hsaWrite);
  340. }
  341. Result = FRootAccess;
  342. }
  343. return Result;
  344. }
  345. //---------------------------------------------------------------------------
  346. bool __fastcall THierarchicalStorage::OpenSubKeyPath(const UnicodeString & KeyPath, bool CanCreate)
  347. {
  348. DebugAssert(!KeyPath.IsEmpty() && (KeyPath[KeyPath.Length()] != L'\\'));
  349. bool Result = false; // shut up
  350. UnicodeString Buf(KeyPath);
  351. int Opens = 0;
  352. while (!Buf.IsEmpty())
  353. {
  354. UnicodeString SubKey = CutToChar(Buf, L'\\', false);
  355. Result = OpenSubKey(SubKey, CanCreate);
  356. if (Result)
  357. {
  358. Opens++;
  359. }
  360. }
  361. if (Result)
  362. {
  363. FKeyHistory.back().Levels = Opens;
  364. }
  365. else
  366. {
  367. while (Opens > 0)
  368. {
  369. CloseSubKey();
  370. Opens--;
  371. }
  372. }
  373. return Result;
  374. }
  375. //---------------------------------------------------------------------------
  376. bool __fastcall THierarchicalStorage::OpenSubKey(const UnicodeString & Key, bool CanCreate)
  377. {
  378. UnicodeString MungedKey = MungeKeyName(Key);
  379. bool Result;
  380. unsigned int InheritAccess;
  381. unsigned int Access;
  382. // For the first open, CanWrite > GetCurrentAccess > ReadAccess has a (needed) side effect of caching root access.
  383. if (!CanWrite() && CanCreate && !KeyExists(MungedKey))
  384. {
  385. InheritAccess = Access = 0; // do not even try to read the access, as the key is actually not opened
  386. FFakeReadOnlyOpens++;
  387. Result = true;
  388. }
  389. else
  390. {
  391. Access = hsaRead; // allow reading the access
  392. InheritAccess = GetCurrentAccess();
  393. Result = DoOpenSubKey(MungedKey, CanCreate);
  394. }
  395. if (Result)
  396. {
  397. TKeyEntry Entry;
  398. Entry.Key = IncludeTrailingBackslash(CurrentSubKey + MungedKey);
  399. Entry.Levels = 1;
  400. Entry.Access = Access;
  401. FKeyHistory.push_back(Entry);
  402. // Read the real access only now, that the key is finally opened (it's in FKeyHistory)
  403. FKeyHistory.back().Access = ReadAccess(InheritAccess);
  404. }
  405. return Result;
  406. }
  407. //---------------------------------------------------------------------------
  408. void __fastcall THierarchicalStorage::CloseSubKeyPath()
  409. {
  410. if (FKeyHistory.empty())
  411. {
  412. throw Exception(UnicodeString());
  413. }
  414. int Levels = FKeyHistory.back().Levels;
  415. FKeyHistory.back().Levels = 1; // to satisfy the assertion in CloseSubKey()
  416. while (Levels > 0)
  417. {
  418. CloseSubKey();
  419. Levels--;
  420. DebugAssert((Levels == 0) || (FKeyHistory.back().Levels == 1));
  421. }
  422. }
  423. //---------------------------------------------------------------------------
  424. void __fastcall THierarchicalStorage::CloseSubKey()
  425. {
  426. if (FKeyHistory.empty())
  427. {
  428. throw Exception(UnicodeString());
  429. }
  430. DebugAssert(FKeyHistory.back().Levels == 1);
  431. FKeyHistory.pop_back();
  432. if (FFakeReadOnlyOpens > 0)
  433. {
  434. FFakeReadOnlyOpens--;
  435. }
  436. else
  437. {
  438. DoCloseSubKey();
  439. }
  440. }
  441. //---------------------------------------------------------------------------
  442. void __fastcall THierarchicalStorage::CloseAll()
  443. {
  444. while (!CurrentSubKey.IsEmpty())
  445. {
  446. CloseSubKeyPath();
  447. }
  448. }
  449. //---------------------------------------------------------------------------
  450. void __fastcall THierarchicalStorage::ClearSubKeys()
  451. {
  452. std::unique_ptr<TStringList> SubKeys(new TStringList());
  453. GetSubKeyNames(SubKeys.get());
  454. for (int Index = 0; Index < SubKeys->Count; Index++)
  455. {
  456. RecursiveDeleteSubKey(SubKeys->Strings[Index]);
  457. }
  458. }
  459. //---------------------------------------------------------------------------
  460. bool THierarchicalStorage::RecursiveDeleteSubKey(const UnicodeString & Key)
  461. {
  462. return DeleteSubKey(Key, true);
  463. }
  464. //---------------------------------------------------------------------------
  465. bool THierarchicalStorage::DeleteSubKey(const UnicodeString & Key, bool Recursive)
  466. {
  467. bool CanWriteParent = CanWrite();
  468. bool Result = OpenSubKey(Key, false);
  469. if (Result)
  470. {
  471. if (Recursive)
  472. {
  473. ClearSubKeys();
  474. // Cannot delete the key itself, but can delete its contents, so at least delete the values
  475. // (which would otherwise be deleted implicitly by DoDeleteSubKey)
  476. if (!CanWriteParent && CanWrite())
  477. {
  478. ClearValues();
  479. }
  480. }
  481. std::unique_ptr<TStrings> ValueNames(new TStringList());
  482. if (!Recursive)
  483. {
  484. GetValueNames(ValueNames.get());
  485. }
  486. // Only if all subkeys were successfully deleted in ClearSubKeys
  487. Result = CanWriteParent && !HasSubKeys() && (ValueNames->Count == 0);
  488. CloseSubKey();
  489. if (Result)
  490. {
  491. Result = DoDeleteSubKey(Key);
  492. }
  493. }
  494. return Result;
  495. }
  496. //---------------------------------------------------------------------------
  497. bool __fastcall THierarchicalStorage::HasSubKeys()
  498. {
  499. std::unique_ptr<TStrings> SubKeys(new TStringList());
  500. GetSubKeyNames(SubKeys.get());
  501. bool Result = (SubKeys->Count > 0);
  502. return Result;
  503. }
  504. //---------------------------------------------------------------------------
  505. bool __fastcall THierarchicalStorage::DeleteValue(const UnicodeString & Name)
  506. {
  507. if (CanWrite())
  508. {
  509. return DoDeleteValue(Name);
  510. }
  511. else
  512. {
  513. return false;
  514. }
  515. }
  516. //---------------------------------------------------------------------------
  517. bool __fastcall THierarchicalStorage::KeyExists(const UnicodeString & SubKey)
  518. {
  519. if (CanRead())
  520. {
  521. return DoKeyExists(SubKey, ForceAnsi);
  522. }
  523. else
  524. {
  525. return false;
  526. }
  527. }
  528. //---------------------------------------------------------------------------
  529. bool __fastcall THierarchicalStorage::ValueExists(const UnicodeString & Value)
  530. {
  531. if (CanRead())
  532. {
  533. return DoValueExists(Value, ForceAnsi);
  534. }
  535. else
  536. {
  537. return false;
  538. }
  539. }
  540. //---------------------------------------------------------------------------
  541. void __fastcall THierarchicalStorage::ReadValues(TStrings * Strings, bool MaintainKeys)
  542. {
  543. std::unique_ptr<TStrings> Names(new TStringList());
  544. GetValueNames(Names.get());
  545. for (int Index = 0; Index < Names->Count; Index++)
  546. {
  547. if (MaintainKeys)
  548. {
  549. Strings->Add(FORMAT(L"%s=%s", (Names->Strings[Index], ReadString(Names->Strings[Index], UnicodeString()))));
  550. }
  551. else
  552. {
  553. Strings->Add(ReadString(Names->Strings[Index], UnicodeString()));
  554. }
  555. }
  556. }
  557. //---------------------------------------------------------------------------
  558. void __fastcall THierarchicalStorage::ClearValues()
  559. {
  560. std::unique_ptr<TStrings> Names(new TStringList());
  561. GetValueNames(Names.get());
  562. for (int Index = 0; Index < Names->Count; Index++)
  563. {
  564. DeleteValue(Names->Strings[Index]);
  565. }
  566. }
  567. //---------------------------------------------------------------------------
  568. void __fastcall THierarchicalStorage::WriteValues(TStrings * Strings, bool MaintainKeys)
  569. {
  570. ClearValues();
  571. if (Strings != NULL)
  572. {
  573. for (int Index = 0; Index < Strings->Count; Index++)
  574. {
  575. if (MaintainKeys)
  576. {
  577. DebugAssert(Strings->Strings[Index].Pos(L"=") > 1);
  578. WriteString(Strings->Names[Index], Strings->Values[Strings->Names[Index]]);
  579. }
  580. else
  581. {
  582. WriteString(IntToStr(Index), Strings->Strings[Index]);
  583. }
  584. }
  585. }
  586. }
  587. //---------------------------------------------------------------------------
  588. bool __fastcall THierarchicalStorage::HasAccess(unsigned int Access)
  589. {
  590. return
  591. FLAGSET(GetCurrentAccess(), Access) &&
  592. // There should never be any kind of access to a non-existent key
  593. DebugAlwaysTrue(FFakeReadOnlyOpens == 0);
  594. }
  595. //---------------------------------------------------------------------------
  596. bool __fastcall THierarchicalStorage::CanRead()
  597. {
  598. return HasAccess(hsaRead);
  599. }
  600. //---------------------------------------------------------------------------
  601. void __fastcall THierarchicalStorage::GetSubKeyNames(TStrings * Strings)
  602. {
  603. if (CanRead())
  604. {
  605. DoGetSubKeyNames(Strings);
  606. }
  607. else
  608. {
  609. Strings->Clear();
  610. }
  611. }
  612. //---------------------------------------------------------------------------
  613. void __fastcall THierarchicalStorage::GetValueNames(TStrings * Strings)
  614. {
  615. if (CanRead())
  616. {
  617. DoGetValueNames(Strings);
  618. int Index = 0;
  619. while (Index < Strings->Count)
  620. {
  621. if (SameText(Strings->Strings[Index], AccessValueName))
  622. {
  623. Strings->Delete(Index);
  624. }
  625. else
  626. {
  627. Index++;
  628. }
  629. }
  630. }
  631. else
  632. {
  633. Strings->Clear();
  634. }
  635. }
  636. //---------------------------------------------------------------------------
  637. bool __fastcall THierarchicalStorage::ReadBool(const UnicodeString & Name, bool Default)
  638. {
  639. if (CanRead())
  640. {
  641. return DoReadBool(Name, Default);
  642. }
  643. else
  644. {
  645. return Default;
  646. }
  647. }
  648. //---------------------------------------------------------------------------
  649. int __fastcall THierarchicalStorage::ReadInteger(const UnicodeString & Name, int Default)
  650. {
  651. return ReadIntegerWithMapping(Name, Default, NULL);
  652. }
  653. //---------------------------------------------------------------------------
  654. int THierarchicalStorage::ReadIntegerWithMapping(const UnicodeString & Name, int Default, const TIntMapping * Mapping)
  655. {
  656. if (CanRead())
  657. {
  658. return DoReadInteger(Name, Default, Mapping);
  659. }
  660. else
  661. {
  662. return Default;
  663. }
  664. }
  665. //---------------------------------------------------------------------------
  666. __int64 __fastcall THierarchicalStorage::ReadInt64(const UnicodeString & Name, __int64 Default)
  667. {
  668. if (CanRead())
  669. {
  670. return DoReadInt64(Name, Default);
  671. }
  672. else
  673. {
  674. return Default;
  675. }
  676. }
  677. //---------------------------------------------------------------------------
  678. TDateTime __fastcall THierarchicalStorage::ReadDateTime(const UnicodeString & Name, TDateTime Default)
  679. {
  680. if (CanRead())
  681. {
  682. return DoReadDateTime(Name, Default);
  683. }
  684. else
  685. {
  686. return Default;
  687. }
  688. }
  689. //---------------------------------------------------------------------------
  690. double __fastcall THierarchicalStorage::ReadFloat(const UnicodeString & Name, double Default)
  691. {
  692. if (CanRead())
  693. {
  694. return DoReadFloat(Name, Default);
  695. }
  696. else
  697. {
  698. return Default;
  699. }
  700. }
  701. //---------------------------------------------------------------------------
  702. UnicodeString __fastcall THierarchicalStorage::ReadStringRaw(const UnicodeString & Name, const UnicodeString & Default)
  703. {
  704. if (CanRead())
  705. {
  706. return DoReadStringRaw(Name, Default);
  707. }
  708. else
  709. {
  710. return Default;
  711. }
  712. }
  713. //---------------------------------------------------------------------------
  714. size_t __fastcall THierarchicalStorage::ReadBinaryData(const UnicodeString & Name, void * Buffer, size_t Size)
  715. {
  716. if (CanRead())
  717. {
  718. return DoReadBinaryData(Name, Buffer, Size);
  719. }
  720. else
  721. {
  722. return 0;
  723. }
  724. }
  725. //---------------------------------------------------------------------------
  726. UnicodeString __fastcall THierarchicalStorage::ReadString(const UnicodeString & Name, const UnicodeString & Default)
  727. {
  728. UnicodeString Result;
  729. if (CanRead())
  730. {
  731. if (MungeStringValues)
  732. {
  733. Result = UnMungeStr(ReadStringRaw(Name, MungeStr(Default, ForceAnsi, true)));
  734. }
  735. else
  736. {
  737. Result = ReadStringRaw(Name, Default);
  738. }
  739. }
  740. else
  741. {
  742. Result = Default;
  743. }
  744. return Result;
  745. }
  746. //---------------------------------------------------------------------------
  747. size_t __fastcall THierarchicalStorage::BinaryDataSize(const UnicodeString & Name)
  748. {
  749. if (CanRead())
  750. {
  751. return DoBinaryDataSize(Name);
  752. }
  753. else
  754. {
  755. return 0;
  756. }
  757. }
  758. //---------------------------------------------------------------------------
  759. RawByteString __fastcall THierarchicalStorage::ReadBinaryData(const UnicodeString & Name)
  760. {
  761. size_t Size = BinaryDataSize(Name);
  762. RawByteString Value;
  763. Value.SetLength(Size);
  764. ReadBinaryData(Name, Value.c_str(), Size);
  765. return Value;
  766. }
  767. //---------------------------------------------------------------------------
  768. RawByteString __fastcall THierarchicalStorage::ReadStringAsBinaryData(const UnicodeString & Name, const RawByteString & Default)
  769. {
  770. UnicodeString UnicodeDefault = AnsiToString(Default);
  771. // This should be exactly the same operation as calling ReadString in
  772. // C++Builder 6 (non-Unicode) on Unicode-based OS
  773. // (conversion is done by Ansi layer of the OS)
  774. UnicodeString String = ReadString(Name, UnicodeDefault);
  775. AnsiString Ansi = AnsiString(String);
  776. RawByteString Result = RawByteString(Ansi.c_str(), Ansi.Length());
  777. return Result;
  778. }
  779. //---------------------------------------------------------------------------
  780. bool __fastcall THierarchicalStorage::CanWrite()
  781. {
  782. return HasAccess(hsaWrite);
  783. }
  784. //---------------------------------------------------------------------------
  785. void __fastcall THierarchicalStorage::WriteBool(const UnicodeString & Name, bool Value)
  786. {
  787. if (CanWrite())
  788. {
  789. DoWriteBool(Name, Value);
  790. }
  791. }
  792. //---------------------------------------------------------------------------
  793. void __fastcall THierarchicalStorage::WriteStringRaw(const UnicodeString & Name, const UnicodeString & Value)
  794. {
  795. if (CanWrite())
  796. {
  797. DoWriteStringRaw(Name, Value);
  798. }
  799. }
  800. //---------------------------------------------------------------------------
  801. void __fastcall THierarchicalStorage::WriteInteger(const UnicodeString & Name, int Value)
  802. {
  803. if (CanWrite())
  804. {
  805. DoWriteInteger(Name, Value);
  806. }
  807. }
  808. //---------------------------------------------------------------------------
  809. // Simple alias to WriteInteger
  810. void __fastcall THierarchicalStorage::WriteEnum(const UnicodeString & Name, int Value)
  811. {
  812. WriteInteger(Name, Value);
  813. }
  814. //---------------------------------------------------------------------------
  815. void __fastcall THierarchicalStorage::WriteInt64(const UnicodeString & Name, __int64 Value)
  816. {
  817. if (CanWrite())
  818. {
  819. DoWriteInt64(Name, Value);
  820. }
  821. }
  822. //---------------------------------------------------------------------------
  823. void __fastcall THierarchicalStorage::WriteDateTime(const UnicodeString & Name, TDateTime Value)
  824. {
  825. if (CanWrite())
  826. {
  827. // TRegistry.WriteDateTime does this internally
  828. DoWriteBinaryData(Name, &Value, sizeof(Value));
  829. }
  830. }
  831. //---------------------------------------------------------------------------
  832. void __fastcall THierarchicalStorage::WriteFloat(const UnicodeString & Name, double Value)
  833. {
  834. if (CanWrite())
  835. {
  836. // TRegistry.WriteFloat does this internally
  837. DoWriteBinaryData(Name, &Value, sizeof(Value));
  838. }
  839. }
  840. //---------------------------------------------------------------------------
  841. void __fastcall THierarchicalStorage::WriteString(const UnicodeString & Name, const UnicodeString & Value)
  842. {
  843. if (MungeStringValues)
  844. {
  845. WriteStringRaw(Name, MungeStr(Value, ForceAnsi, true));
  846. }
  847. else
  848. {
  849. WriteStringRaw(Name, Value);
  850. }
  851. }
  852. //---------------------------------------------------------------------------
  853. void __fastcall THierarchicalStorage::WriteBinaryData(const UnicodeString & Name, const void * Buffer, int Size)
  854. {
  855. if (CanWrite())
  856. {
  857. DoWriteBinaryData(Name, Buffer, Size);
  858. }
  859. }
  860. //---------------------------------------------------------------------------
  861. void __fastcall THierarchicalStorage::WriteBinaryData(const UnicodeString & Name, const RawByteString & Value)
  862. {
  863. WriteBinaryData(Name, Value.c_str(), Value.Length());
  864. }
  865. //---------------------------------------------------------------------------
  866. void __fastcall THierarchicalStorage::WriteBinaryDataAsString(const UnicodeString & Name, const RawByteString & Value)
  867. {
  868. // This should be exactly the same operation as calling WriteString in
  869. // C++Builder 6 (non-Unicode) on Unicode-based OS
  870. // (conversion is done by Ansi layer of the OS)
  871. WriteString(Name, AnsiToString(Value));
  872. }
  873. //---------------------------------------------------------------------------
  874. UnicodeString __fastcall THierarchicalStorage::IncludeTrailingBackslash(const UnicodeString & S)
  875. {
  876. // expanded from ?: as it caused memory leaks
  877. if (S.IsEmpty())
  878. {
  879. return S;
  880. }
  881. else
  882. {
  883. return ::IncludeTrailingBackslash(S);
  884. }
  885. }
  886. //---------------------------------------------------------------------------
  887. UnicodeString __fastcall THierarchicalStorage::ExcludeTrailingBackslash(const UnicodeString & S)
  888. {
  889. // expanded from ?: as it caused memory leaks
  890. if (S.IsEmpty())
  891. {
  892. return S;
  893. }
  894. else
  895. {
  896. return ::ExcludeTrailingBackslash(S);
  897. }
  898. }
  899. //---------------------------------------------------------------------------
  900. bool __fastcall THierarchicalStorage::GetTemporary()
  901. {
  902. return false;
  903. }
  904. //===========================================================================
  905. __fastcall TRegistryStorage::TRegistryStorage(const UnicodeString & AStorage) :
  906. THierarchicalStorage(IncludeTrailingBackslash(AStorage))
  907. {
  908. FWowMode = 0;
  909. Init();
  910. };
  911. //---------------------------------------------------------------------------
  912. __fastcall TRegistryStorage::TRegistryStorage(const UnicodeString & AStorage, HKEY ARootKey, REGSAM WowMode):
  913. THierarchicalStorage(IncludeTrailingBackslash(AStorage))
  914. {
  915. FWowMode = WowMode;
  916. Init();
  917. FRegistry->RootKey = ARootKey;
  918. }
  919. //---------------------------------------------------------------------------
  920. void __fastcall TRegistryStorage::Init()
  921. {
  922. FRegistry = new TRegistry();
  923. FRegistry->Access = KEY_READ | FWowMode;
  924. }
  925. //---------------------------------------------------------------------------
  926. __fastcall TRegistryStorage::~TRegistryStorage()
  927. {
  928. delete FRegistry;
  929. };
  930. //---------------------------------------------------------------------------
  931. // Used only in OpenSessionInPutty
  932. bool __fastcall TRegistryStorage::Copy(TRegistryStorage * Storage)
  933. {
  934. TRegistry * Registry = Storage->FRegistry;
  935. bool Result = true;
  936. std::unique_ptr<TStrings> Names(new TStringList());
  937. Registry->GetValueNames(Names.get());
  938. std::vector<unsigned char> Buffer(1024, 0);
  939. int Index = 0;
  940. while ((Index < Names->Count) && Result)
  941. {
  942. UnicodeString Name = MungeStr(Names->Strings[Index], ForceAnsi, false);
  943. unsigned long Size = Buffer.size();
  944. unsigned long Type;
  945. int RegResult;
  946. do
  947. {
  948. RegResult = RegQueryValueEx(Registry->CurrentKey, Name.c_str(), NULL, &Type, &Buffer[0], &Size);
  949. if (RegResult == ERROR_MORE_DATA)
  950. {
  951. Buffer.resize(Size);
  952. }
  953. } while (RegResult == ERROR_MORE_DATA);
  954. Result = (RegResult == ERROR_SUCCESS);
  955. if (Result)
  956. {
  957. RegResult = RegSetValueEx(FRegistry->CurrentKey, Name.c_str(), NULL, Type, &Buffer[0], Size);
  958. Result = (RegResult == ERROR_SUCCESS);
  959. }
  960. ++Index;
  961. }
  962. return Result;
  963. }
  964. //---------------------------------------------------------------------------
  965. UnicodeString __fastcall TRegistryStorage::GetSource()
  966. {
  967. return RootKeyToStr(FRegistry->RootKey) + L"\\" + Storage;
  968. }
  969. //---------------------------------------------------------------------------
  970. void __fastcall TRegistryStorage::SetAccessMode(TStorageAccessMode value)
  971. {
  972. THierarchicalStorage::SetAccessMode(value);
  973. if (FRegistry)
  974. {
  975. switch (AccessMode) {
  976. case smRead:
  977. FRegistry->Access = KEY_READ | FWowMode;
  978. break;
  979. case smReadWrite:
  980. default:
  981. FRegistry->Access = KEY_READ | KEY_WRITE | FWowMode;
  982. break;
  983. }
  984. }
  985. }
  986. //---------------------------------------------------------------------------
  987. bool __fastcall TRegistryStorage::DoOpenSubKey(const UnicodeString & SubKey, bool CanCreate)
  988. {
  989. UnicodeString PrevPath;
  990. bool WasOpened = (FRegistry->CurrentKey != NULL);
  991. if (WasOpened)
  992. {
  993. PrevPath = FRegistry->CurrentPath;
  994. DebugAssert(SamePaths(PrevPath, Storage + GetCurrentSubKeyMunged()));
  995. FRegistry->CloseKey();
  996. }
  997. UnicodeString K = ExcludeTrailingBackslash(Storage + CurrentSubKey + SubKey);
  998. bool Result = FRegistry->OpenKey(K, CanCreate);
  999. if (!Result && WasOpened)
  1000. {
  1001. FRegistry->OpenKey(PrevPath, false);
  1002. }
  1003. return Result;
  1004. }
  1005. //---------------------------------------------------------------------------
  1006. void __fastcall TRegistryStorage::DoCloseSubKey()
  1007. {
  1008. FRegistry->CloseKey();
  1009. if (!FKeyHistory.empty())
  1010. {
  1011. FRegistry->OpenKey(Storage + GetCurrentSubKeyMunged(), True);
  1012. }
  1013. }
  1014. //---------------------------------------------------------------------------
  1015. bool __fastcall TRegistryStorage::DoDeleteSubKey(const UnicodeString & SubKey)
  1016. {
  1017. UnicodeString K;
  1018. if (FKeyHistory.empty())
  1019. {
  1020. K = Storage + CurrentSubKey;
  1021. }
  1022. K += MungeKeyName(SubKey);
  1023. return FRegistry->DeleteKey(K);
  1024. }
  1025. //---------------------------------------------------------------------------
  1026. void __fastcall TRegistryStorage::DoGetSubKeyNames(TStrings * Strings)
  1027. {
  1028. FRegistry->GetKeyNames(Strings);
  1029. for (int Index = 0; Index < Strings->Count; Index++)
  1030. {
  1031. Strings->Strings[Index] = UnMungeStr(Strings->Strings[Index]);
  1032. }
  1033. }
  1034. //---------------------------------------------------------------------------
  1035. void __fastcall TRegistryStorage::DoGetValueNames(TStrings * Strings)
  1036. {
  1037. FRegistry->GetValueNames(Strings);
  1038. }
  1039. //---------------------------------------------------------------------------
  1040. bool __fastcall TRegistryStorage::DoDeleteValue(const UnicodeString & Name)
  1041. {
  1042. return FRegistry->DeleteValue(Name);
  1043. }
  1044. //---------------------------------------------------------------------------
  1045. bool __fastcall TRegistryStorage::DoKeyExists(const UnicodeString & SubKey, bool AForceAnsi)
  1046. {
  1047. UnicodeString K = SubKey;
  1048. if (MungingKeyName(K))
  1049. {
  1050. K = MungeStr(K, AForceAnsi, false);
  1051. }
  1052. bool Result = FRegistry->KeyExists(K);
  1053. return Result;
  1054. }
  1055. //---------------------------------------------------------------------------
  1056. bool __fastcall TRegistryStorage::DoValueExists(const UnicodeString & Value, bool DebugUsedArg(AForceAnsi))
  1057. {
  1058. // TODO: use AForceAnsi
  1059. bool Result = FRegistry->ValueExists(Value);
  1060. return Result;
  1061. }
  1062. //---------------------------------------------------------------------------
  1063. size_t __fastcall TRegistryStorage::DoBinaryDataSize(const UnicodeString & Name)
  1064. {
  1065. size_t Result = FRegistry->GetDataSize(Name);
  1066. return Result;
  1067. }
  1068. //---------------------------------------------------------------------------
  1069. bool __fastcall TRegistryStorage::DoReadBool(const UnicodeString & Name, bool Default)
  1070. {
  1071. READ_REGISTRY(ReadBool);
  1072. }
  1073. //---------------------------------------------------------------------------
  1074. TDateTime __fastcall TRegistryStorage::DoReadDateTime(const UnicodeString & Name, TDateTime Default)
  1075. {
  1076. // Internally does what would DoReadBinaryData do (like in DoReadInt64)
  1077. READ_REGISTRY(ReadDateTime);
  1078. }
  1079. //---------------------------------------------------------------------------
  1080. double __fastcall TRegistryStorage::DoReadFloat(const UnicodeString & Name, double Default)
  1081. {
  1082. // Internally does what would DoReadBinaryData do (like in DoReadInt64)
  1083. READ_REGISTRY(ReadFloat);
  1084. }
  1085. //---------------------------------------------------------------------------
  1086. int __fastcall TRegistryStorage::DoReadInteger(const UnicodeString & Name, int Default, const TIntMapping *)
  1087. {
  1088. READ_REGISTRY(ReadInteger);
  1089. }
  1090. //---------------------------------------------------------------------------
  1091. __int64 __fastcall TRegistryStorage::DoReadInt64(const UnicodeString & Name, __int64 Default)
  1092. {
  1093. __int64 Result;
  1094. if (DoReadBinaryData(Name, &Result, sizeof(Result)) == 0)
  1095. {
  1096. Result = Default;
  1097. }
  1098. return Result;
  1099. }
  1100. //---------------------------------------------------------------------------
  1101. UnicodeString __fastcall TRegistryStorage::DoReadStringRaw(const UnicodeString & Name, const UnicodeString & Default)
  1102. {
  1103. READ_REGISTRY(ReadString);
  1104. }
  1105. //---------------------------------------------------------------------------
  1106. size_t __fastcall TRegistryStorage::DoReadBinaryData(const UnicodeString & Name, void * Buffer, size_t Size)
  1107. {
  1108. size_t Result;
  1109. if (FRegistry->ValueExists(Name))
  1110. {
  1111. try
  1112. {
  1113. Result = FRegistry->ReadBinaryData(Name, Buffer, Size);
  1114. }
  1115. catch(...)
  1116. {
  1117. Result = 0;
  1118. }
  1119. }
  1120. else
  1121. {
  1122. Result = 0;
  1123. }
  1124. return Result;
  1125. }
  1126. //---------------------------------------------------------------------------
  1127. void __fastcall TRegistryStorage::DoWriteBool(const UnicodeString & Name, bool Value)
  1128. {
  1129. WRITE_REGISTRY(WriteBool);
  1130. }
  1131. //---------------------------------------------------------------------------
  1132. void __fastcall TRegistryStorage::DoWriteStringRaw(const UnicodeString & Name, const UnicodeString & Value)
  1133. {
  1134. WRITE_REGISTRY(WriteString);
  1135. }
  1136. //---------------------------------------------------------------------------
  1137. void __fastcall TRegistryStorage::DoWriteInteger(const UnicodeString & Name, int Value)
  1138. {
  1139. WRITE_REGISTRY(WriteInteger);
  1140. }
  1141. //---------------------------------------------------------------------------
  1142. void __fastcall TRegistryStorage::DoWriteInt64(const UnicodeString & Name, __int64 Value)
  1143. {
  1144. WriteBinaryData(Name, &Value, sizeof(Value));
  1145. }
  1146. //---------------------------------------------------------------------------
  1147. void __fastcall TRegistryStorage::DoWriteBinaryData(const UnicodeString & Name, const void * Buffer, int Size)
  1148. {
  1149. try
  1150. {
  1151. FRegistry->WriteBinaryData(Name, const_cast<void *>(Buffer), Size);
  1152. }
  1153. catch(...)
  1154. {
  1155. }
  1156. }
  1157. //===========================================================================
  1158. __fastcall TCustomIniFileStorage::TCustomIniFileStorage(const UnicodeString & Storage, TCustomIniFile * IniFile) :
  1159. THierarchicalStorage(Storage),
  1160. FIniFile(IniFile),
  1161. FMasterStorageOpenFailures(0),
  1162. FOpeningSubKey(false)
  1163. {
  1164. }
  1165. //---------------------------------------------------------------------------
  1166. __fastcall TCustomIniFileStorage::~TCustomIniFileStorage()
  1167. {
  1168. delete FIniFile;
  1169. }
  1170. //---------------------------------------------------------------------------
  1171. UnicodeString __fastcall TCustomIniFileStorage::GetSource()
  1172. {
  1173. return Storage;
  1174. }
  1175. //---------------------------------------------------------------------------
  1176. UnicodeString __fastcall TCustomIniFileStorage::GetCurrentSection()
  1177. {
  1178. return ExcludeTrailingBackslash(GetCurrentSubKeyMunged());
  1179. }
  1180. //---------------------------------------------------------------------------
  1181. void __fastcall TCustomIniFileStorage::CacheSections()
  1182. {
  1183. if (FSections.get() == NULL)
  1184. {
  1185. FSections.reset(new TStringList());
  1186. FIniFile->ReadSections(FSections.get());
  1187. FSections->Sorted = true; // has to set only after reading as ReadSections reset it to false
  1188. }
  1189. }
  1190. //---------------------------------------------------------------------------
  1191. void __fastcall TCustomIniFileStorage::ResetCache()
  1192. {
  1193. FSections.reset(NULL);
  1194. }
  1195. //---------------------------------------------------------------------------
  1196. void __fastcall TCustomIniFileStorage::SetAccessMode(TStorageAccessMode value)
  1197. {
  1198. if (FMasterStorage.get() != NULL)
  1199. {
  1200. FMasterStorage->AccessMode = value;
  1201. }
  1202. THierarchicalStorage::SetAccessMode(value);
  1203. }
  1204. //---------------------------------------------------------------------------
  1205. bool __fastcall TCustomIniFileStorage::DoKeyExistsInternal(const UnicodeString & SubKey)
  1206. {
  1207. CacheSections();
  1208. bool Result = false;
  1209. UnicodeString NewKey = ExcludeTrailingBackslash(CurrentSubKey + SubKey);
  1210. if (FSections->Count > 0)
  1211. {
  1212. int Index = -1;
  1213. Result = FSections->Find(NewKey, Index);
  1214. if (!Result &&
  1215. (Index < FSections->Count) &&
  1216. (FSections->Strings[Index].SubString(1, NewKey.Length()+1) == NewKey + L"\\"))
  1217. {
  1218. Result = true;
  1219. }
  1220. }
  1221. return Result;
  1222. }
  1223. //---------------------------------------------------------------------------
  1224. bool __fastcall TCustomIniFileStorage::DoOpenSubKey(const UnicodeString & SubKey, bool CanCreate)
  1225. {
  1226. bool Result =
  1227. CanCreate ||
  1228. DoKeyExistsInternal(SubKey);
  1229. return Result;
  1230. }
  1231. //---------------------------------------------------------------------------
  1232. bool __fastcall TCustomIniFileStorage::OpenSubKey(const UnicodeString & Key, bool CanCreate)
  1233. {
  1234. bool Result;
  1235. // To cache root access in advance, otherwise we end up calling ourselves, what TAutoFlag does not like
  1236. GetCurrentAccess();
  1237. {
  1238. TAutoFlag Flag(FOpeningSubKey);
  1239. Result = THierarchicalStorage::OpenSubKey(Key, CanCreate);
  1240. }
  1241. if (FMasterStorage.get() != NULL)
  1242. {
  1243. if (FMasterStorageOpenFailures > 0)
  1244. {
  1245. if (Result)
  1246. {
  1247. FMasterStorageOpenFailures++;
  1248. }
  1249. }
  1250. else
  1251. {
  1252. bool MasterResult = FMasterStorage->OpenSubKey(Key, CanCreate);
  1253. if (!Result && MasterResult)
  1254. {
  1255. Result = THierarchicalStorage::OpenSubKey(Key, true);
  1256. DebugAssert(Result);
  1257. }
  1258. else if (Result && !MasterResult)
  1259. {
  1260. FMasterStorageOpenFailures++;
  1261. }
  1262. }
  1263. }
  1264. return Result;
  1265. }
  1266. //---------------------------------------------------------------------------
  1267. void __fastcall TCustomIniFileStorage::DoCloseSubKey()
  1268. {
  1269. // noop
  1270. }
  1271. //---------------------------------------------------------------------------
  1272. void __fastcall TCustomIniFileStorage::CloseSubKey()
  1273. {
  1274. // What we are called to restore previous key from OpenSubKey,
  1275. // when opening path component fails, the master storage was not involved yet
  1276. if (!FOpeningSubKey && (FMasterStorage.get() != NULL))
  1277. {
  1278. if (FMasterStorageOpenFailures > 0)
  1279. {
  1280. FMasterStorageOpenFailures--;
  1281. }
  1282. else
  1283. {
  1284. FMasterStorage->CloseSubKey();
  1285. }
  1286. }
  1287. THierarchicalStorage::CloseSubKey();
  1288. }
  1289. //---------------------------------------------------------------------------
  1290. bool __fastcall TCustomIniFileStorage::DoDeleteSubKey(const UnicodeString & SubKey)
  1291. {
  1292. bool Result = true;
  1293. try
  1294. {
  1295. ResetCache();
  1296. FIniFile->EraseSection(CurrentSubKey + MungeKeyName(SubKey));
  1297. }
  1298. catch (...)
  1299. {
  1300. }
  1301. if (HandleByMasterStorage())
  1302. {
  1303. Result =
  1304. FMasterStorage->CanWrite() &&
  1305. FMasterStorage->DoDeleteSubKey(SubKey);
  1306. }
  1307. return Result;
  1308. }
  1309. //---------------------------------------------------------------------------
  1310. void __fastcall TCustomIniFileStorage::DoGetSubKeyNames(TStrings * Strings)
  1311. {
  1312. Strings->Clear();
  1313. if (HandleByMasterStorage())
  1314. {
  1315. FMasterStorage->GetSubKeyNames(Strings);
  1316. }
  1317. CacheSections();
  1318. for (int i = 0; i < FSections->Count; i++)
  1319. {
  1320. UnicodeString Section = FSections->Strings[i];
  1321. if (AnsiCompareText(CurrentSubKey,
  1322. Section.SubString(1, CurrentSubKey.Length())) == 0)
  1323. {
  1324. UnicodeString SubSection = Section.SubString(CurrentSubKey.Length() + 1,
  1325. Section.Length() - CurrentSubKey.Length());
  1326. int P = SubSection.Pos(L"\\");
  1327. if (P)
  1328. {
  1329. SubSection.SetLength(P - 1);
  1330. }
  1331. if (Strings->IndexOf(SubSection) < 0)
  1332. {
  1333. Strings->Add(UnMungeStr(SubSection));
  1334. }
  1335. }
  1336. }
  1337. }
  1338. //---------------------------------------------------------------------------
  1339. void __fastcall TCustomIniFileStorage::DoGetValueNames(TStrings * Strings)
  1340. {
  1341. if (HandleByMasterStorage())
  1342. {
  1343. FMasterStorage->GetValueNames(Strings);
  1344. }
  1345. FIniFile->ReadSection(CurrentSection, Strings);
  1346. for (int Index = 0; Index < Strings->Count; Index++)
  1347. {
  1348. UnicodeString S = Strings->Strings[Index];
  1349. S = UnMungeIniName(S);
  1350. Strings->Strings[Index] = S;
  1351. }
  1352. }
  1353. //---------------------------------------------------------------------------
  1354. bool __fastcall TCustomIniFileStorage::DoKeyExists(const UnicodeString & SubKey, bool AForceAnsi)
  1355. {
  1356. return
  1357. (HandleByMasterStorage() && FMasterStorage->DoKeyExists(SubKey, AForceAnsi)) ||
  1358. DoKeyExistsInternal(MungeStr(SubKey, AForceAnsi, false));
  1359. }
  1360. //---------------------------------------------------------------------------
  1361. bool __fastcall TCustomIniFileStorage::DoValueExistsInternal(const UnicodeString & Value, bool AForceAnsi)
  1362. {
  1363. return FIniFile->ValueExists(CurrentSection, ::MungeIniName(Value, AForceAnsi));
  1364. }
  1365. //---------------------------------------------------------------------------
  1366. bool __fastcall TCustomIniFileStorage::DoValueExists(const UnicodeString & Value, bool AForceAnsi)
  1367. {
  1368. return
  1369. (HandleByMasterStorage() && FMasterStorage->DoValueExists(Value, AForceAnsi)) ||
  1370. DoValueExistsInternal(Value, AForceAnsi);
  1371. }
  1372. //---------------------------------------------------------------------------
  1373. bool __fastcall TCustomIniFileStorage::DoDeleteValue(const UnicodeString & Name)
  1374. {
  1375. bool Result = true;
  1376. if (HandleByMasterStorage())
  1377. {
  1378. Result = FMasterStorage->DeleteValue(Name);
  1379. }
  1380. ResetCache();
  1381. FIniFile->DeleteKey(CurrentSection, MungeIniName(Name));
  1382. return Result;
  1383. }
  1384. //---------------------------------------------------------------------------
  1385. bool __fastcall TCustomIniFileStorage::HandleByMasterStorage()
  1386. {
  1387. return
  1388. (FMasterStorage.get() != NULL) &&
  1389. (FMasterStorageOpenFailures == 0);
  1390. }
  1391. //---------------------------------------------------------------------------
  1392. bool __fastcall TCustomIniFileStorage::HandleReadByMasterStorage(const UnicodeString & Name)
  1393. {
  1394. return HandleByMasterStorage() && !DoValueExistsInternal(Name, ForceAnsi);
  1395. }
  1396. //---------------------------------------------------------------------------
  1397. size_t __fastcall TCustomIniFileStorage::DoBinaryDataSize(const UnicodeString & Name)
  1398. {
  1399. if (HandleReadByMasterStorage(Name))
  1400. {
  1401. return FMasterStorage->BinaryDataSize(Name);
  1402. }
  1403. else
  1404. {
  1405. return ReadStringRaw(Name, L"").Length() / 2;
  1406. }
  1407. }
  1408. //---------------------------------------------------------------------------
  1409. bool __fastcall TCustomIniFileStorage::DoReadBool(const UnicodeString & Name, bool Default)
  1410. {
  1411. if (HandleReadByMasterStorage(Name))
  1412. {
  1413. return FMasterStorage->ReadBool(Name, Default);
  1414. }
  1415. else
  1416. {
  1417. int IntDefault = int(Default);
  1418. int Int = DoReadIntegerWithMapping(Name, IntDefault, &BoolMapping);
  1419. return (Int != 0);
  1420. }
  1421. }
  1422. //---------------------------------------------------------------------------
  1423. int __fastcall TCustomIniFileStorage::DoReadIntegerWithMapping(const UnicodeString & Name, int Default, const TIntMapping * Mapping)
  1424. {
  1425. int Result = 0; // shut up
  1426. bool ReadAsInteger = true;
  1427. UnicodeString MungedName = MungeIniName(Name);
  1428. if (Mapping != NULL) // optimization
  1429. {
  1430. UnicodeString S = FIniFile->ReadString(CurrentSection, MungedName, EmptyStr);
  1431. if (!S.IsEmpty())
  1432. {
  1433. S = S.LowerCase();
  1434. TIntMapping::const_iterator I = Mapping->find(S);
  1435. if (I != Mapping->end())
  1436. {
  1437. Result = I->second;
  1438. ReadAsInteger = false;
  1439. }
  1440. }
  1441. }
  1442. if (ReadAsInteger)
  1443. {
  1444. Result = FIniFile->ReadInteger(CurrentSection, MungedName, Default);
  1445. }
  1446. return Result;
  1447. }
  1448. //---------------------------------------------------------------------------
  1449. int __fastcall TCustomIniFileStorage::DoReadInteger(const UnicodeString & Name, int Default, const TIntMapping * Mapping)
  1450. {
  1451. int Result;
  1452. if (HandleReadByMasterStorage(Name))
  1453. {
  1454. Result = FMasterStorage->ReadIntegerWithMapping(Name, Default, Mapping);
  1455. }
  1456. else
  1457. {
  1458. Result = DoReadIntegerWithMapping(Name, Default, Mapping);
  1459. }
  1460. return Result;
  1461. }
  1462. //---------------------------------------------------------------------------
  1463. __int64 __fastcall TCustomIniFileStorage::DoReadInt64(const UnicodeString & Name, __int64 Default)
  1464. {
  1465. __int64 Result;
  1466. if (HandleReadByMasterStorage(Name))
  1467. {
  1468. Result = FMasterStorage->ReadInt64(Name, Default);
  1469. }
  1470. else
  1471. {
  1472. Result = Default;
  1473. UnicodeString Str;
  1474. Str = ReadStringRaw(Name, L"");
  1475. if (!Str.IsEmpty())
  1476. {
  1477. Result = StrToInt64Def(Str, Default);
  1478. }
  1479. }
  1480. return Result;
  1481. }
  1482. //---------------------------------------------------------------------------
  1483. TDateTime __fastcall TCustomIniFileStorage::DoReadDateTime(const UnicodeString & Name, TDateTime Default)
  1484. {
  1485. TDateTime Result;
  1486. if (HandleReadByMasterStorage(Name))
  1487. {
  1488. Result = FMasterStorage->ReadDateTime(Name, Default);
  1489. }
  1490. else
  1491. {
  1492. UnicodeString Value = FIniFile->ReadString(CurrentSection, MungeIniName(Name), L"");
  1493. if (Value.IsEmpty())
  1494. {
  1495. Result = Default;
  1496. }
  1497. else
  1498. {
  1499. try
  1500. {
  1501. RawByteString Raw = HexToBytes(Value);
  1502. if (static_cast<size_t>(Raw.Length()) == sizeof(Result))
  1503. {
  1504. memcpy(&Result, Raw.c_str(), sizeof(Result));
  1505. }
  1506. else
  1507. {
  1508. Result = StrToDateTime(Value);
  1509. }
  1510. }
  1511. catch(...)
  1512. {
  1513. Result = Default;
  1514. }
  1515. }
  1516. }
  1517. return Result;
  1518. }
  1519. //---------------------------------------------------------------------------
  1520. double __fastcall TCustomIniFileStorage::DoReadFloat(const UnicodeString & Name, double Default)
  1521. {
  1522. double Result;
  1523. if (HandleReadByMasterStorage(Name))
  1524. {
  1525. Result = FMasterStorage->ReadFloat(Name, Default);
  1526. }
  1527. else
  1528. {
  1529. UnicodeString Value = FIniFile->ReadString(CurrentSection, MungeIniName(Name), L"");
  1530. if (Value.IsEmpty())
  1531. {
  1532. Result = Default;
  1533. }
  1534. else
  1535. {
  1536. try
  1537. {
  1538. RawByteString Raw = HexToBytes(Value);
  1539. if (static_cast<size_t>(Raw.Length()) == sizeof(Result))
  1540. {
  1541. memcpy(&Result, Raw.c_str(), sizeof(Result));
  1542. }
  1543. else
  1544. {
  1545. Result = static_cast<double>(StrToFloat(Value));
  1546. }
  1547. }
  1548. catch(...)
  1549. {
  1550. Result = Default;
  1551. }
  1552. }
  1553. }
  1554. return Result;
  1555. }
  1556. //---------------------------------------------------------------------------
  1557. UnicodeString __fastcall TCustomIniFileStorage::DoReadStringRaw(const UnicodeString & Name, const UnicodeString & Default)
  1558. {
  1559. UnicodeString Result;
  1560. if (HandleReadByMasterStorage(Name))
  1561. {
  1562. Result = FMasterStorage->ReadStringRaw(Name, Default);
  1563. }
  1564. else
  1565. {
  1566. Result = FIniFile->ReadString(CurrentSection, MungeIniName(Name), Default);
  1567. }
  1568. return Result;
  1569. }
  1570. //---------------------------------------------------------------------------
  1571. size_t __fastcall TCustomIniFileStorage::DoReadBinaryData(const UnicodeString & Name, void * Buffer, size_t Size)
  1572. {
  1573. size_t Len;
  1574. if (HandleReadByMasterStorage(Name))
  1575. {
  1576. Size = FMasterStorage->ReadBinaryData(Name, Buffer, Size);
  1577. }
  1578. else
  1579. {
  1580. RawByteString Value = HexToBytes(ReadStringRaw(Name, L""));
  1581. Len = Value.Length();
  1582. if (Size > Len)
  1583. {
  1584. Size = Len;
  1585. }
  1586. DebugAssert(Buffer);
  1587. memcpy(Buffer, Value.c_str(), Size);
  1588. }
  1589. return Size;
  1590. }
  1591. //---------------------------------------------------------------------------
  1592. void __fastcall TCustomIniFileStorage::DoWriteBool(const UnicodeString & Name, bool Value)
  1593. {
  1594. if (HandleByMasterStorage())
  1595. {
  1596. FMasterStorage->WriteBool(Name, Value);
  1597. }
  1598. ResetCache();
  1599. FIniFile->WriteBool(CurrentSection, MungeIniName(Name), Value);
  1600. }
  1601. //---------------------------------------------------------------------------
  1602. void __fastcall TCustomIniFileStorage::DoWriteInteger(const UnicodeString & Name, int Value)
  1603. {
  1604. if (HandleByMasterStorage())
  1605. {
  1606. FMasterStorage->WriteInteger(Name, Value);
  1607. }
  1608. ResetCache();
  1609. FIniFile->WriteInteger(CurrentSection, MungeIniName(Name), Value);
  1610. }
  1611. //---------------------------------------------------------------------------
  1612. void __fastcall TCustomIniFileStorage::DoWriteInt64(const UnicodeString & Name, __int64 Value)
  1613. {
  1614. if (HandleByMasterStorage())
  1615. {
  1616. FMasterStorage->WriteInt64(Name, Value);
  1617. }
  1618. DoWriteStringRawInternal(Name, IntToStr(Value));
  1619. }
  1620. //---------------------------------------------------------------------------
  1621. void __fastcall TCustomIniFileStorage::DoWriteStringRawInternal(const UnicodeString & Name, const UnicodeString & Value)
  1622. {
  1623. ResetCache();
  1624. FIniFile->WriteString(CurrentSection, MungeIniName(Name), Value);
  1625. }
  1626. //---------------------------------------------------------------------------
  1627. void __fastcall TCustomIniFileStorage::DoWriteStringRaw(const UnicodeString & Name, const UnicodeString & Value)
  1628. {
  1629. if (HandleByMasterStorage())
  1630. {
  1631. FMasterStorage->WriteStringRaw(Name, Value);
  1632. }
  1633. DoWriteStringRawInternal(Name, Value);
  1634. }
  1635. //---------------------------------------------------------------------------
  1636. void __fastcall TCustomIniFileStorage::DoWriteBinaryData(const UnicodeString & Name, const void * Buffer, int Size)
  1637. {
  1638. if (HandleByMasterStorage())
  1639. {
  1640. FMasterStorage->WriteBinaryData(Name, Buffer, Size);
  1641. }
  1642. DoWriteStringRawInternal(Name, BytesToHex(RawByteString(static_cast<const char*>(Buffer), Size)));
  1643. }
  1644. //---------------------------------------------------------------------------
  1645. UnicodeString __fastcall TCustomIniFileStorage::DoReadRootAccessString()
  1646. {
  1647. UnicodeString Result;
  1648. if (OpenSubKey(L"_", false))
  1649. {
  1650. Result = ReadAccessString();
  1651. CloseSubKey();
  1652. }
  1653. else
  1654. {
  1655. Result = DefaultAccessString;
  1656. }
  1657. return Result;
  1658. }
  1659. //---------------------------------------------------------------------------
  1660. unsigned int __fastcall TCustomIniFileStorage::GetCurrentAccess()
  1661. {
  1662. unsigned int Result;
  1663. // The way THierarchicalStorage::OpenSubKey is implemented, the access will be zero for non-existing keys in
  1664. // configuration overrides => delegating access handling to the master storage (which still should read overriden access keys)
  1665. if (FMasterStorage.get() != NULL)
  1666. {
  1667. Result = FMasterStorage->GetCurrentAccess();
  1668. }
  1669. else
  1670. {
  1671. Result = THierarchicalStorage::GetCurrentAccess();
  1672. }
  1673. return Result;
  1674. }
  1675. //---------------------------------------------------------------------------
  1676. bool __fastcall TCustomIniFileStorage::HasAccess(unsigned int Access)
  1677. {
  1678. bool Result;
  1679. // Avoid the FFakeReadOnlyOpens assertion in THierarchicalStorage::HasAccess, which is not valid for overriden configuration
  1680. if (HandleByMasterStorage())
  1681. {
  1682. Result = FMasterStorage->HasAccess(Access);
  1683. }
  1684. else
  1685. {
  1686. Result = THierarchicalStorage::HasAccess(Access);
  1687. }
  1688. return Result;
  1689. }
  1690. //===========================================================================
  1691. TIniFileStorage * __fastcall TIniFileStorage::CreateFromPath(const UnicodeString & AStorage)
  1692. {
  1693. // The code was originally inline in the parent constructor call in the TIniFileStorage::TIniFileStorage [public originally].
  1694. // But if the TMemIniFile constructor throws (e.g. because the INI file is locked), the exception causes access violation.
  1695. // Moving the code to a factory solves this.
  1696. TMemIniFile * IniFile = new TMemIniFile(AStorage);
  1697. return new TIniFileStorage(AStorage, IniFile);
  1698. }
  1699. //---------------------------------------------------------------------------
  1700. TIniFileStorage * __fastcall TIniFileStorage::CreateNul()
  1701. {
  1702. // Before we passed "nul", but we have report of a system, where opening "nul" file fails.
  1703. // Passing an empty string is even more efficient, as it does not even try to read the file.
  1704. TMemIniFile * IniFile = new TMemIniFile(EmptyStr);
  1705. return new TIniFileStorage(INI_NUL, IniFile);
  1706. }
  1707. //---------------------------------------------------------------------------
  1708. __fastcall TIniFileStorage::TIniFileStorage(const UnicodeString & AStorage, TCustomIniFile * IniFile):
  1709. TCustomIniFileStorage(AStorage, IniFile)
  1710. {
  1711. if (!FIniFile->FileName.IsEmpty())
  1712. {
  1713. FOriginal = new TStringList();
  1714. dynamic_cast<TMemIniFile *>(FIniFile)->GetStrings(FOriginal);
  1715. }
  1716. else
  1717. {
  1718. FOriginal = NULL;
  1719. }
  1720. ApplyOverrides();
  1721. }
  1722. //---------------------------------------------------------------------------
  1723. void __fastcall TIniFileStorage::Flush()
  1724. {
  1725. if (FMasterStorage.get() != NULL)
  1726. {
  1727. FMasterStorage->Flush();
  1728. }
  1729. // This does not seem correct, if storage is written after it is flushed (though we probably never do that currently)
  1730. if ((FOriginal != NULL) && !FIniFile->FileName.IsEmpty())
  1731. {
  1732. std::unique_ptr<TStrings> Strings(new TStringList);
  1733. std::unique_ptr<TStrings> Original(FOriginal);
  1734. FOriginal = NULL;
  1735. dynamic_cast<TMemIniFile *>(FIniFile)->GetStrings(Strings.get());
  1736. if (!Strings->Equals(Original.get()))
  1737. {
  1738. int Attr;
  1739. // preserve attributes (especially hidden)
  1740. bool Exists = FileExists(ApiPath(Storage));
  1741. if (Exists)
  1742. {
  1743. Attr = GetFileAttributes(ApiPath(Storage).c_str());
  1744. }
  1745. else
  1746. {
  1747. Attr = FILE_ATTRIBUTE_NORMAL;
  1748. }
  1749. if (FLAGSET(Attr, FILE_ATTRIBUTE_READONLY) && ForceSave)
  1750. {
  1751. SetFileAttributes(ApiPath(Storage).c_str(), Attr & ~FILE_ATTRIBUTE_READONLY);
  1752. }
  1753. HANDLE Handle;
  1754. int Error;
  1755. bool Retry;
  1756. int Trying = 0;
  1757. do
  1758. {
  1759. Error = 0;
  1760. Handle =
  1761. CreateFile(ApiPath(Storage).c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, Attr, 0);
  1762. if (Handle == INVALID_HANDLE_VALUE)
  1763. {
  1764. Error = GetLastError();
  1765. }
  1766. Retry = (Error == ERROR_SHARING_VIOLATION) && (Trying < 2000);
  1767. if (Retry)
  1768. {
  1769. const int Step = 100;
  1770. Sleep(Step);
  1771. Trying += Step;
  1772. }
  1773. }
  1774. while (Retry);
  1775. if (Handle == INVALID_HANDLE_VALUE)
  1776. {
  1777. // "access denied" errors upon implicit saves to existing file are ignored
  1778. if (Explicit || !Exists || (Error != ERROR_ACCESS_DENIED))
  1779. {
  1780. throw EOSExtException(FMTLOAD((Exists ? WRITE_ERROR : CREATE_FILE_ERROR), (Storage)));
  1781. }
  1782. }
  1783. else
  1784. {
  1785. try
  1786. {
  1787. std::unique_ptr<TStream> Stream(new TSafeHandleStream(int(Handle)));
  1788. try
  1789. {
  1790. Strings->SaveToStream(Stream.get());
  1791. }
  1792. __finally
  1793. {
  1794. CloseHandle(Handle);
  1795. }
  1796. }
  1797. catch (Exception & E)
  1798. {
  1799. throw ExtException(&E, FMTLOAD(WRITE_ERROR, (Storage)));
  1800. }
  1801. }
  1802. }
  1803. }
  1804. }
  1805. //---------------------------------------------------------------------------
  1806. __fastcall TIniFileStorage::~TIniFileStorage()
  1807. {
  1808. Flush();
  1809. }
  1810. //---------------------------------------------------------------------------
  1811. void __fastcall TIniFileStorage::ApplyOverrides()
  1812. {
  1813. UnicodeString OverridesKey = IncludeTrailingBackslash(L"Override");
  1814. CacheSections();
  1815. for (int i = 0; i < FSections->Count; i++)
  1816. {
  1817. UnicodeString Section = FSections->Strings[i];
  1818. if (SameText(OverridesKey,
  1819. Section.SubString(1, OverridesKey.Length())))
  1820. {
  1821. UnicodeString SubKey = Section.SubString(OverridesKey.Length() + 1,
  1822. Section.Length() - OverridesKey.Length());
  1823. // this all uses raw names (munged)
  1824. TStrings * Names = new TStringList;
  1825. try
  1826. {
  1827. FIniFile->ReadSection(Section, Names);
  1828. for (int ii = 0; ii < Names->Count; ii++)
  1829. {
  1830. UnicodeString Name = Names->Strings[ii];
  1831. UnicodeString Value = FIniFile->ReadString(Section, Name, L"");
  1832. FIniFile->WriteString(SubKey, Name, Value);
  1833. }
  1834. }
  1835. __finally
  1836. {
  1837. delete Names;
  1838. }
  1839. FIniFile->EraseSection(Section);
  1840. ResetCache();
  1841. }
  1842. }
  1843. }
  1844. //===========================================================================
  1845. enum TWriteMode { wmAllow, wmFail, wmIgnore };
  1846. //---------------------------------------------------------------------------
  1847. class TOptionsIniFile : public TCustomIniFile
  1848. {
  1849. public:
  1850. __fastcall TOptionsIniFile(TStrings * Options, TWriteMode WriteMode, const UnicodeString & RootKey);
  1851. virtual UnicodeString __fastcall ReadString(const UnicodeString Section, const UnicodeString Ident, const UnicodeString Default);
  1852. virtual void __fastcall WriteString(const UnicodeString Section, const UnicodeString Ident, const UnicodeString Value);
  1853. virtual void __fastcall ReadSection(const UnicodeString Section, TStrings * Strings);
  1854. virtual void __fastcall ReadSections(TStrings* Strings);
  1855. virtual void __fastcall ReadSectionValues(const UnicodeString Section, TStrings* Strings);
  1856. virtual void __fastcall EraseSection(const UnicodeString Section);
  1857. virtual void __fastcall DeleteKey(const UnicodeString Section, const UnicodeString Ident);
  1858. virtual void __fastcall UpdateFile();
  1859. // Hoisted overload
  1860. void __fastcall ReadSections(const UnicodeString Section, TStrings* Strings);
  1861. // Ntb, we can implement ValueExists more efficiently than the TCustomIniFile.ValueExists
  1862. private:
  1863. TStrings * FOptions;
  1864. TWriteMode FWriteMode;
  1865. UnicodeString FRootKey;
  1866. bool __fastcall AllowWrite();
  1867. bool __fastcall AllowSection(const UnicodeString & Section);
  1868. UnicodeString __fastcall FormatKey(const UnicodeString & Section, const UnicodeString & Ident);
  1869. };
  1870. //---------------------------------------------------------------------------
  1871. __fastcall TOptionsIniFile::TOptionsIniFile(TStrings * Options, TWriteMode WriteMode, const UnicodeString & RootKey) :
  1872. TCustomIniFile(UnicodeString())
  1873. {
  1874. FOptions = Options;
  1875. FWriteMode = WriteMode;
  1876. FRootKey = RootKey;
  1877. if (!FRootKey.IsEmpty())
  1878. {
  1879. FRootKey += PathDelim;
  1880. }
  1881. }
  1882. //---------------------------------------------------------------------------
  1883. bool __fastcall TOptionsIniFile::AllowWrite()
  1884. {
  1885. switch (FWriteMode)
  1886. {
  1887. case wmAllow:
  1888. return true;
  1889. case wmFail:
  1890. NotImplemented();
  1891. UNREACHABLE_AFTER_NORETURN(return false);
  1892. case wmIgnore:
  1893. return false;
  1894. default:
  1895. DebugFail();
  1896. return false;
  1897. }
  1898. }
  1899. //---------------------------------------------------------------------------
  1900. bool __fastcall TOptionsIniFile::AllowSection(const UnicodeString & Section)
  1901. {
  1902. UnicodeString Name = Section;
  1903. if (!Name.IsEmpty())
  1904. {
  1905. Name += PathDelim;
  1906. }
  1907. bool Result = SameText(Name.SubString(1, FRootKey.Length()), FRootKey);
  1908. return Result;
  1909. }
  1910. //---------------------------------------------------------------------------
  1911. UnicodeString __fastcall TOptionsIniFile::FormatKey(const UnicodeString & Section, const UnicodeString & Ident)
  1912. {
  1913. UnicodeString Result = Section;
  1914. if (!Result.IsEmpty())
  1915. {
  1916. Result += PathDelim;
  1917. }
  1918. Result += Ident; // Can be empty, when called from a constructor, AllowSection or ReadSection
  1919. if (DebugAlwaysTrue(AllowSection(Section)))
  1920. {
  1921. Result.Delete(1, FRootKey.Length());
  1922. }
  1923. return Result;
  1924. }
  1925. //---------------------------------------------------------------------------
  1926. UnicodeString __fastcall TOptionsIniFile::ReadString(const UnicodeString Section, const UnicodeString Ident, const UnicodeString Default)
  1927. {
  1928. UnicodeString Value;
  1929. if (!AllowSection(Section))
  1930. {
  1931. Value = Default;
  1932. }
  1933. else
  1934. {
  1935. UnicodeString Name = FormatKey(Section, Ident);
  1936. int Index = FOptions->IndexOfName(Name);
  1937. if (Index >= 0)
  1938. {
  1939. Value = FOptions->ValueFromIndex[Index];
  1940. }
  1941. else
  1942. {
  1943. Value = Default;
  1944. }
  1945. }
  1946. return Value;
  1947. }
  1948. //---------------------------------------------------------------------------
  1949. void __fastcall TOptionsIniFile::WriteString(const UnicodeString Section, const UnicodeString Ident, const UnicodeString Value)
  1950. {
  1951. if (AllowWrite() &&
  1952. DebugAlwaysTrue(AllowSection(Section)))
  1953. {
  1954. UnicodeString Name = FormatKey(Section, Ident);
  1955. SetStringValueEvenIfEmpty(FOptions, Name, Value);
  1956. }
  1957. }
  1958. //---------------------------------------------------------------------------
  1959. void __fastcall TOptionsIniFile::ReadSection(const UnicodeString Section, TStrings * Strings)
  1960. {
  1961. if (AllowSection(Section))
  1962. {
  1963. UnicodeString SectionPrefix = FormatKey(Section, UnicodeString());
  1964. Strings->BeginUpdate();
  1965. try
  1966. {
  1967. for (int Index = 0; Index < FOptions->Count; Index++)
  1968. {
  1969. UnicodeString Name = FOptions->Names[Index];
  1970. if (SameText(Name.SubString(1, SectionPrefix.Length()), SectionPrefix) &&
  1971. (LastDelimiter(PathDelim, Name) <= SectionPrefix.Length()))
  1972. {
  1973. Strings->Add(Name.SubString(SectionPrefix.Length() + 1, Name.Length() - SectionPrefix.Length()));
  1974. }
  1975. }
  1976. }
  1977. __finally
  1978. {
  1979. Strings->EndUpdate();
  1980. }
  1981. }
  1982. }
  1983. //---------------------------------------------------------------------------
  1984. void __fastcall TOptionsIniFile::ReadSections(TStrings * Strings)
  1985. {
  1986. std::unique_ptr<TStringList> Sections(CreateSortedStringList());
  1987. for (int Index = 0; Index < FOptions->Count; Index++)
  1988. {
  1989. UnicodeString Name = FOptions->Names[Index];
  1990. int P = LastDelimiter(PathDelim, Name);
  1991. if (P > 0)
  1992. {
  1993. UnicodeString Section = Name.SubString(1, P - 1);
  1994. if (Sections->IndexOf(Section) < 0)
  1995. {
  1996. Sections->Add(Section);
  1997. }
  1998. }
  1999. }
  2000. for (int Index = 0; Index < Sections->Count; Index++)
  2001. {
  2002. Strings->Add(FRootKey + Sections->Strings[Index]);
  2003. }
  2004. }
  2005. //---------------------------------------------------------------------------
  2006. void __fastcall TOptionsIniFile::ReadSectionValues(const UnicodeString Section, TStrings * /*Strings*/)
  2007. {
  2008. DebugUsedParam(Section);
  2009. NotImplemented();
  2010. }
  2011. //---------------------------------------------------------------------------
  2012. void __fastcall TOptionsIniFile::EraseSection(const UnicodeString Section)
  2013. {
  2014. DebugUsedParam(Section);
  2015. if (AllowWrite())
  2016. {
  2017. NotImplemented();
  2018. }
  2019. }
  2020. //---------------------------------------------------------------------------
  2021. void __fastcall TOptionsIniFile::DeleteKey(const UnicodeString Section, const UnicodeString Ident)
  2022. {
  2023. if (AllowWrite() &&
  2024. DebugAlwaysTrue(AllowSection(Section)))
  2025. {
  2026. UnicodeString Name = FormatKey(Section, Ident);
  2027. int Index = FOptions->IndexOfName(Name);
  2028. if (Index >= 0)
  2029. {
  2030. FOptions->Delete(Index);
  2031. }
  2032. }
  2033. }
  2034. //---------------------------------------------------------------------------
  2035. void __fastcall TOptionsIniFile::UpdateFile()
  2036. {
  2037. if (AllowWrite())
  2038. {
  2039. // noop
  2040. }
  2041. }
  2042. //---------------------------------------------------------------------------
  2043. void __fastcall TOptionsIniFile::ReadSections(const UnicodeString /*Section*/, TStrings * /*Strings*/)
  2044. {
  2045. NotImplemented();
  2046. }
  2047. //===========================================================================
  2048. __fastcall TOptionsStorage::TOptionsStorage(TStrings * Options, bool AllowWrite):
  2049. TCustomIniFileStorage(
  2050. UnicodeString(L"Command-line options"),
  2051. new TOptionsIniFile(Options, (AllowWrite ? wmAllow : wmFail), UnicodeString()))
  2052. {
  2053. }
  2054. //---------------------------------------------------------------------------
  2055. __fastcall TOptionsStorage::TOptionsStorage(TStrings * Options, const UnicodeString & RootKey, THierarchicalStorage * MasterStorage) :
  2056. TCustomIniFileStorage(
  2057. UnicodeString(L"Command-line options overriding " + MasterStorage->Source),
  2058. new TOptionsIniFile(Options, wmIgnore, RootKey))
  2059. {
  2060. FMasterStorage.reset(MasterStorage);
  2061. }
  2062. //---------------------------------------------------------------------------
  2063. bool __fastcall TOptionsStorage::GetTemporary()
  2064. {
  2065. return true;
  2066. }