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