OpenCPN Partial API docs
observable_confvar.cpp
1 /*************************************************************************
2  *
3  * Project: OpenCPN
4  * Purpose: Implement observable.h
5  *
6  * Copyright (C) 2022 Alec Leamas
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the
20  * Free Software Foundation, Inc.,
21  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22  **************************************************************************/
23 
24 #include <sstream>
25 #include <string>
26 
27 #include <wx/log.h>
28 #include <wx/string.h>
29 #include <wx/config.h>
30 
31 #include "observable_confvar.h"
32 
37 std::istream& operator>>(std::istream& input, wxString& ws) {
38  std::string s;
39  input >> s;
40  ws.Append(s);
41  return input;
42 }
43 
44 /* ConfigVar implementation. */
45 
46 template <typename T>
47 ConfigVar<T>::ConfigVar(const std::string& section_, const std::string& key_,
48  wxConfigBase* cb)
49  : Observable(section_ + "/" + key_),
50  section(section_),
51  key(key_),
52  config(cb) {}
53 
54 template <typename T>
55 const T ConfigVar<T>::Get(const T& default_val) {
56  std::istringstream iss;
57  config->SetPath(section);
58  auto value = config->Read(key, "").ToStdString();
59  iss.str(value);
60  T r;
61  iss >> r;
62  return iss.fail() ? default_val : r;
63 }
64 
65 template <typename T>
66 void ConfigVar<T>::Set(const T& arg) {
67  std::ostringstream oss;
68  oss << arg;
69  if (oss.fail()) {
70  wxLogWarning("Cannot dump failed buffer for key %s:%s", section.c_str(),
71  key.c_str());
72  return;
73  }
74  config->SetPath(section);
75  if (!config->Write(key.c_str(), oss.str().c_str())) {
76  wxLogWarning("Error writing buffer to key %s:%s", section.c_str(),
77  key.c_str());
78  }
80 }
81 
82 /* Explicitly instantiate the ConfigVar types supported. */
83 template class ConfigVar<bool>;
84 template class ConfigVar<double>;
85 template class ConfigVar<int>;
86 template class ConfigVar<std::string>;
87 template class ConfigVar<wxString>;
Wrapper for configuration variables which lives in a wxBaseConfig object.
The observable notify/listen basic nuts and bolts.
Definition: observable.h:82
virtual const void Notify()
Notify all listeners about variable change.
Definition: observable.cpp:94