HierarchicalStorage.cpp 65 KB

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