File: settings.cpp

package info (click to toggle)
cutecom 0.30.3-1
  • links: PTS
  • area: main
  • in suites: bullseye, buster, stretch
  • size: 808 kB
  • sloc: cpp: 2,177; makefile: 54; sh: 8
file content (351 lines) | stat: -rw-r--r-- 12,416 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
/*
 * Copyright (c) 2015 Meinhard Ritscher <cyc1ingsir@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 * For more information on the GPL, please go to:
 * http://www.gnu.org/copyleft/gpl.html
 */
#include "settings.h"

#include <QSettings>
#include <QHash>
#include <QVariant>
#include <QSerialPort>

#include <qdebug.h>

const QString Settings::DEFAULT_SESSION_NAME = QStringLiteral("Default");

Settings::Settings(QObject *parent)
    : QObject(parent)
{
}

void Settings::settingChanged(Settings::Options option, QVariant setting)
{
    bool sessionSettings = true;
    Session session;
    if (m_sessions.contains(m_current_session))
        session = m_sessions.value(m_current_session);

    switch (option) {
    case BaudRate:
        session.baudRate = setting.toInt();
        break;
    case StopBits:
        session.stopBits = static_cast<QSerialPort::StopBits>(setting.toInt());
        break;
    case DataBits:
        session.dataBits = static_cast<QSerialPort::DataBits>(setting.toInt());
        break;
    case Parity:
        session.parity = static_cast<QSerialPort::Parity>(setting.toInt());
        break;
    case FlowControl:
        session.flowControl = static_cast<QSerialPort::FlowControl>(setting.toInt());
        break;
    case OpenMode:
        session.openMode = static_cast<QIODevice::OpenModeFlag>(setting.toInt());
        break;
    case Device:
        session.device = setting.toString();
        break;
    case ShowCtrlCharacters:
        session.showCtrlCharacters = setting.toBool();
        break;
    case ShowTimestamp:
        session.showTimestamp = setting.toBool();
        break;
    case CommandHistory:
        session.command_history = setting.toStringList();
        break;
    case WindowGeometry:
        m_windowGeometry = setting.toRect();
        sessionSettings = false;
        break;
    case LogFileLocation:
        m_logFileLocation = setting.toString();
        sessionSettings = false;
        break;
    case LineTermination:
        m_lineterm = setting.value<LineTerminator>();
        sessionSettings = false;
        break;
    case CharacterDelay:
        m_character_delay = setting.toUInt();
        sessionSettings = false;
        break;
    case ProtocolOption:
        m_protocol = setting.value<Protocol>();
        sessionSettings = false;
        break;
    case SendStartDir:
        m_sendingStartDir = setting.toString();
        sessionSettings = false;
        break;
    case CurrentSession:
        m_current_session = setting.toString();
        emit sessionChanged(getCurrentSession());
        sessionSettings = false;
    default:
        break;
    }
    m_sessions.insert(m_current_session, session);
    if (sessionSettings) {
        saveSessionSettings();
        emit sessionChanged(getCurrentSession());
    } else {
        saveGenericSettings();
    }
}

/**
 * @brief Settings::readSessionSettings
 * Reads the settings of all stored sessions.
 * These settings contain settings relevant to connect to a specific device
 * especially the baud rate but also the command history which may be device
 * specific as well.
 * If the value for a setting can't be successfully been read, a default value
 * will be used.
 * If that value isn't beeing changed by the user, the setting will not be
 * rewritten to the config file. But this doesn't effect the user since the
 * default values for this setting seem to be suit him/her.
 *
 * @param settings a reference to the QSetting instance of this process
 */
void Settings::readSessionSettings(QSettings &settings)
{
    int size = settings.beginReadArray("sessions");

    if (size < 1) {
        qDebug() << "no session information found in conf file";
        return;
    }
    m_sessions.clear();
    quint32 value;

    for (int i = 0; i < size; i++) {
        settings.setArrayIndex(i);
        Session session;
        QString name = settings.value("name").toString();
        if (name.isEmpty())
            continue;

        /*
         * the static casts are prone to errors since a valid int in the config
         * file might not be able to be mapped to a QSerialPort enum
         * e.g. flowControl=35600 has no equivalent
         * the static cast can't throw an error but this error will be
         * handled the time this value is appied to the combo boxes within
         * the control panel. It's a workaround though.
         */
        session.baudRate = settings.value("BaudRate", 115200).toInt();
        session.dataBits = (readUIntSetting(settings, QStringLiteral("DataBits"), &value))
                               ? static_cast<QSerialPort::DataBits>(value)
                               : QSerialPort::Data8;
        session.parity = (readUIntSetting(settings, QStringLiteral("Parity"), &value))
                             ? static_cast<QSerialPort::Parity>(value)
                             : QSerialPort::NoParity;
        session.stopBits = (readUIntSetting(settings, QStringLiteral("StopBits"), &value))
                               ? static_cast<QSerialPort::StopBits>(value)
                               : QSerialPort::OneStop;
        session.flowControl = (readUIntSetting(settings, QStringLiteral("FlowControl"), &value))
                                  ? static_cast<QSerialPort::FlowControl>(value)
                                  : QSerialPort::NoFlowControl;
        session.openMode = (readUIntSetting(settings, QStringLiteral("OpenMode"), &value))
                               ? static_cast<QIODevice::OpenModeFlag>(value)
                               : QIODevice::ReadWrite;
        // the recovering default for the device its Linux specific but I can live with that
        session.device = settings.value("Device", QStringLiteral("/dev/ttyUSB0")).toString();
        session.showCtrlCharacters = settings.value("showCtrlCharacters", false).toBool();
        session.showTimestamp = settings.value("showTimestamp", false).toBool();
        session.command_history = settings.value("History").toStringList();

        m_sessions.insert(name, session);
    }
    settings.endArray();
}

bool Settings::readUIntSetting(QSettings &settings, QString const &name, quint32 *i)
{
    bool ok = false;
    int r = settings.value(name, -1).toInt(&ok);
    if (r < 0 || !ok) {
        *i = 0;
        return false;
    } else {
        *i = r;
    }
    return true;
}

/**
 * @brief Settings::readSettings
 * @param session A specific session to be used as the current session.
 */
void Settings::readSettings(const QString &session)
{
    QSettings settings(this->parent());
    settings.beginGroup("CuteCom");
    QString stored_session = settings.value("session", DEFAULT_SESSION_NAME).toString();
    if (session.isEmpty()) {
        m_current_session = stored_session;
    } else {
        m_current_session = session;
        if (session != stored_session)
            settings.setValue("session", session);
    }
    qDebug() << "setting current session to: " << m_current_session;

    m_windowGeometry = settings.value("WindowGeometry", QRect(0, 0, 0, 0)).toRect();
    m_logFileLocation = settings.value("LogFileLocation").toString();
    if (m_logFileLocation.isEmpty()) {
        m_logFileLocation = QDir::homePath() + QDir::separator() + QStringLiteral("cutecom.log");
    }

    m_lineterm = static_cast<Settings::LineTerminator>(
        settings.value("LineTerminator", QVariant::fromValue(Settings::LF)).toUInt());

    m_protocol
        = static_cast<Settings::Protocol>(settings.value("Protocol", QVariant::fromValue(Settings::PLAIN)).toUInt());

    m_sendingStartDir = settings.value("SendingStartDir", QDir::homePath()).toString();

    m_character_delay = settings.value("CharacterDelay", 0).toUInt();

    settings.endGroup();
    readSessionSettings(settings);
}

const Settings::Session Settings::getCurrentSession()
{
    if (!m_sessions.contains(m_current_session)) {
        // Since this is probably the first time CuteCom is
        // started (with this session specified as parameter)
        // we set sensible default values for at least
        // the connection parameter

        Settings::Session session;
        session.baudRate = 115200;
        session.dataBits = QSerialPort::Data8;
        session.parity = QSerialPort::NoParity;
        session.stopBits = QSerialPort::OneStop;
        session.openMode = QIODevice::ReadWrite;
        session.flowControl = QSerialPort::NoFlowControl;
        m_sessions.insert(m_current_session, session);
    }

    return m_sessions.value(m_current_session);
}

void Settings::saveGenericSettings()
{
    QSettings settings(this->parent());
    settings.beginGroup("CuteCom");
    // store generic fluff
    settings.setValue("WindowGeometry", m_windowGeometry);
    settings.setValue("LogFileLocation", m_logFileLocation);

    // save session releated settings
    if (!m_current_session.isEmpty())
        settings.setValue("session", m_current_session);
    else
        settings.setValue("session", DEFAULT_SESSION_NAME);

    settings.setValue("LineTerminator", m_lineterm);

    settings.setValue("CharacterDelay", m_character_delay);

    settings.setValue("Protocol", m_protocol);

    settings.setValue("SendingStartDir", m_sendingStartDir);

    settings.endGroup();
}

void Settings::saveSessionSettings()
{
    QSettings settings(this->parent());

    if (m_sessions.size() > 0) {
        settings.beginWriteArray("sessions");
        int index = 0;
        QHashIterator<QString, Session> iter(m_sessions);
        while (iter.hasNext()) {
            iter.next();
            settings.setArrayIndex(index++);
            settings.setValue("name", iter.key());
            Session session = iter.value();
            settings.setValue("BaudRate", session.baudRate);
            settings.setValue("DataBits", session.dataBits);
            settings.setValue("Parity", session.parity);
            settings.setValue("StopBits", session.stopBits);
            settings.setValue("FlowControl", session.flowControl);
            settings.setValue("OpenMode", session.openMode);
            settings.setValue("Device", session.device);
            settings.setValue("showCtrlCharacters", session.showCtrlCharacters);
            settings.setValue("showTimestamp", session.showTimestamp);
            settings.setValue("History", session.command_history);
        }
        settings.endArray();
    }
}

void Settings::removeSession(const QString &session)
{
    m_sessions.remove(session);
    QSettings settings;
    settings.beginGroup("sessions");
    settings.remove("");
    settings.endGroup();
    saveSessionSettings();
    m_current_session = QStringLiteral("Default");
    saveGenericSettings();
    emit this->sessionChanged(getCurrentSession());
}

void Settings::cloneSession(const QString &source, const QString &destination)
{
    Session session = m_sessions.value(source);
    m_sessions.insert(destination, session);
    saveSessionSettings();
}

void Settings::renameSession(const QString &source, const QString &destination)
{
    Session session = m_sessions.value(source);
    m_sessions.remove(source);
    QSettings settings;
    settings.beginGroup("sessions");
    settings.remove("");
    settings.endGroup();
    m_sessions.insert(destination, session);
    saveSessionSettings();
}

QString Settings::getLogFileLocation() const { return m_logFileLocation; }

Settings::LineTerminator Settings::getLineTerminator() const { return m_lineterm; }

QList<QString> Settings::getSessionNames() const
{
    QList<QString> sessions = m_sessions.keys();
    if (sessions.isEmpty())
        sessions.append(QStringLiteral("Default"));
    return sessions;
}

QRect Settings::getWindowGeometry() const { return m_windowGeometry; }