File: Controller.cpp

package info (click to toggle)
charmtimetracker 1.12.0-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 3,340 kB
  • sloc: cpp: 19,176; xml: 284; python: 120; makefile: 14
file content (458 lines) | stat: -rw-r--r-- 14,909 bytes parent folder | download | duplicates (2)
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
/*
  Controller.cpp

  This file is part of Charm, a task-based time tracking application.

  Copyright (C) 2007-2018 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com

  Author: Mirko Boehm <mirko.boehm@kdab.com>
  Author: Frank Osterfeld <frank.osterfeld@kdab.com>
  Author: Olivier JG <olivier.de.gaalon@kdab.com>
  Author: Guillermo A. Amaral <gamaral@kdab.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 2 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, see <http://www.gnu.org/licenses/>.
*/

#include "Controller.h"
#include "CharmCommand.h"
#include "CharmConstants.h"
#include "CharmExceptions.h"
#include "Configuration.h"
#include "Event.h"
#include "SqLiteStorage.h"
#include "SqlRaiiTransactor.h"
#include "SqlStorage.h"
#include "Task.h"

#include <QtDebug>

Controller::Controller(QObject *parent_)
    : QObject(parent_)
{
}

Controller::~Controller()
{
}

Event Controller::makeEvent(const Task &task)
{
    Event event = m_storage->makeEvent();
    Q_ASSERT(event.isValid());

    event.setTaskId(task.id());
    if (m_storage->modifyEvent(event)) {
        emit eventAdded(event);
    } else {
        event = Event();
    }
    return event;
}

Event Controller::cloneEvent(const Event &e)
{
    Event event = m_storage->makeEvent();
    Q_ASSERT(event.isValid());

    int id = event.id();
    event = e;
    event.setId(id);
    if (m_storage->modifyEvent(event)) {
        emit eventAdded(event);
    } else {
        event = Event();
    }
    return event;
}

bool Controller::modifyEvent(const Event &e)
{
    if (m_storage->modifyEvent(e)) {
        emit eventModified(e);
        return true;
    } else {
        return false;
    }
}

bool Controller::deleteEvent(const Event &e)
{
    if (m_storage->deleteEvent(e)) {
        emit eventDeleted(e);
        return true;
    } else {
        return false;
    }
}

bool Controller::addTask(const Task &task)
{
    if (m_storage->addTask(task)) {
        updateSubscriptionForTask(task);
        emit taskAdded(task);

        return true;
    } else {
        Q_ASSERT(false);   // impossible
        return false;
    }
}

bool Controller::modifyTask(const Task &task)
{
    // modify the task itself:
    bool result = m_storage->modifyTask(task);
    Q_ASSERT(result);
    if (!result) {
        qCritical() << Q_FUNC_INFO << "modifyTask failed!";
        return result;
    }

    updateSubscriptionForTask(task);
    emit(taskUpdated(task));

    return true;
}

bool Controller::deleteTask(const Task &task)
{
    if (m_storage->deleteTask(task)) {
        m_storage->deleteSubscription(CONFIGURATION.user, task);
        emit taskDeleted(task);
        return true;
    } else {
        Q_ASSERT(false);   // impossible
        return false;
    }
}

bool Controller::setAllTasks(const TaskList &tasks)
{
    if (m_storage->setAllTasks(CONFIGURATION.user, tasks)) {
        const TaskList newTasks = m_storage->getAllTasks();
        // tell the view about the existing tasks;
        emit definedTasks(newTasks);
        return true;
    } else {
        return false;
    }
}

void Controller::updateSubscriptionForTask(const Task &task)
{
    if (task.subscribed()) {
        bool result = m_storage->addSubscription(CONFIGURATION.user, task);
        Q_ASSERT(result);
        Q_UNUSED(result);
    } else {
        bool result = m_storage->deleteSubscription(CONFIGURATION.user, task);
        Q_ASSERT(result);
        Q_UNUSED(result);
    }
}

void Controller::stateChanged(State previous, State next)
{
    Q_UNUSED(previous);

    switch (next) {
    case Connected:
    {   // yes, it is that simple:
        TaskList tasks = m_storage->getAllTasks();
        // tell the view about the existing tasks;
        if (!Task::checkForUniqueTaskIds(tasks)) {
            throw CharmException(tr(
                                     "The Charm database is corrupted, it contains duplicate task ids. "
                                     "Please have it looked after by a professional."));
        }
        if (!Task::checkForTreeness(tasks)) {
            throw CharmException(tr(
                                     "The Charm database is corrupted, the tasks do not form a tree. "
                                     "Please have it looked after by a professional."));
        }
        emit definedTasks(tasks);
        EventList events = m_storage->getAllEvents();
        emit allEvents(events);
        break;
    }
    case Disconnecting:
    {
        emit readyToQuit();
        if (m_storage) {
// this will still leave Qt complaining about a repeated connection
            m_storage->disconnect();
            delete m_storage;
            m_storage = nullptr;
        }
        break;
    }
    default:
        break;
    }

    if (m_storage) {
        emit currentBackendStatus(m_storage->description());
        m_storage->stateChanged(previous);
    }
}

struct Setting {
    QString key;
    QString value;
};

void Controller::persistMetaData(Configuration &configuration)
{
    Q_ASSERT_X(m_storage != nullptr, Q_FUNC_INFO, "No storage interface available");
    Setting settings[] = {
        { MetaKey_Key_UserName,
          configuration.user.name() },
        { MetaKey_Key_SubscribedTasksOnly,
          QString().setNum(configuration.taskPrefilteringMode) },
        { MetaKey_Key_TimeTrackerFontSize,
          QString().setNum(configuration.timeTrackerFontSize) },
        { MetaKey_Key_DurationFormat,
          QString::number(configuration.durationFormat) },
        { MetaKey_Key_IdleDetection,
          stringForBool(configuration.detectIdling) },
        { MetaKey_Key_WarnUnuploadedTimesheets,
          stringForBool(configuration.warnUnuploadedTimesheets) },
        { MetaKey_Key_RequestEventComment,
          stringForBool(configuration.requestEventComment) },
        { MetaKey_Key_ToolButtonStyle,
          QString().setNum(configuration.toolButtonStyle) },
        { MetaKey_Key_ShowStatusBar,
          stringForBool(configuration.showStatusBar) },
        { MetaKey_Key_EnableCommandInterface,
          stringForBool(configuration.enableCommandInterface) },
        { MetaKey_Key_NumberOfTaskSelectorEntries,
          QString::number(configuration.numberOfTaskSelectorEntries) }
    };
    int NumberOfSettings = sizeof settings / sizeof settings[0];

    bool good = true;
    for (int i = 0; i < NumberOfSettings; ++i)
        good = good && m_storage->setMetaData(settings[i].key, settings[i].value);
    Q_ASSERT_X(good, Q_FUNC_INFO, "Controller assumes write "
                                  "permissions in meta data table if persistMetaData is called");
    CONFIGURATION.dump();
}

template<class T>
void Controller::loadConfigValue(const QString &key, T &configValue) const
{
    const QString storedValue = m_storage->getMetaData(key);
    if (storedValue.isNull())
        return;
    configValue = strToT<T>(storedValue);
}

void Controller::provideMetaData(Configuration &configuration)
{
    Q_ASSERT_X(m_storage != nullptr, Q_FUNC_INFO, "No storage interface available");
    configuration.user.setName(m_storage->getMetaData(MetaKey_Key_UserName));

    loadConfigValue(MetaKey_Key_TimeTrackerFontSize, configuration.timeTrackerFontSize);
    loadConfigValue(MetaKey_Key_DurationFormat, configuration.durationFormat);
    loadConfigValue(MetaKey_Key_SubscribedTasksOnly, configuration.taskPrefilteringMode);
    loadConfigValue(MetaKey_Key_IdleDetection, configuration.detectIdling);
    loadConfigValue(MetaKey_Key_WarnUnuploadedTimesheets, configuration.warnUnuploadedTimesheets);
    loadConfigValue(MetaKey_Key_RequestEventComment, configuration.requestEventComment);
    loadConfigValue(MetaKey_Key_ToolButtonStyle, configuration.toolButtonStyle);
    loadConfigValue(MetaKey_Key_ShowStatusBar, configuration.showStatusBar);
    loadConfigValue(MetaKey_Key_EnableCommandInterface, configuration.enableCommandInterface);
    loadConfigValue(MetaKey_Key_NumberOfTaskSelectorEntries, configuration.numberOfTaskSelectorEntries);
    configuration.numberOfTaskSelectorEntries = qMax(0, configuration.numberOfTaskSelectorEntries);

    CONFIGURATION.dump();
}

bool Controller::initializeBackEnd(const QString &name)
{
    // make storage interface according to configuration
    // this is our local storage backend factory and may have to be
    // factored out into a factory method (now that is some serious
    // refucktoring):
    if (name == CHARM_SQLITE_BACKEND_DESCRIPTOR) {
        m_storage = new SqLiteStorage;
        return true;
    } else {
        Q_ASSERT_X(false, Q_FUNC_INFO, "Unknown local storage backend type");
        return false;
    }
}

bool Controller::connectToBackend()
{
    bool result = m_storage->connect(CONFIGURATION);

    // the user id in the database, and the installation id, do not
    // have to be 1 and 1, as we have guessed --> persist configuration
    if (result && !CONFIGURATION.newDatabase)
        provideMetaData(CONFIGURATION);

    return result;
}

bool Controller::disconnectFromBackend()
{
    return m_storage->disconnect();
}

void Controller::executeCommand(CharmCommand *command)
{
    command->execute(this);
    // send it back to the view:
    emit commandCompleted(command);
}

void Controller::rollbackCommand(CharmCommand *command)
{
    command->rollback(this);
    // send it back to the view:
    emit commandCompleted(command);
}

SqlStorage *Controller::storage()
{
    return m_storage;
}

const QString MetaDataElement(QStringLiteral("metadata"));
const QString ExportRootElement(QStringLiteral("charmdatabase"));
const QString VersionElement(QStringLiteral("version"));
const QString TasksElement(QStringLiteral("tasks"));
const QString EventsElement(QStringLiteral("events"));

QDomDocument Controller::exportDatabasetoXml() const
{
    QDomDocument document(QStringLiteral("charmdatabase"));
    // root element:
    QDomElement root = document.createElement(ExportRootElement);
    root.setAttribute(VersionElement, CHARM_DATABASE_VERSION);
    document.appendChild(root);
    // metadata:
    QDomElement metadata = document.createElement(MetaDataElement);
    // I am not so sure what kind of metadata needs to be stored
    root.appendChild(metadata);
    // tasks element:
    QDomElement tasksElement = document.createElement(TasksElement);
    // FIXME there are generic methods for that now, in Task.h
    TaskList tasks = m_storage->getAllTasks();
    Q_FOREACH (const Task &task, tasks) {
        QDomElement element = task.toXml(document);
        tasksElement.appendChild(element);
    }
    root.appendChild(tasksElement);
    // events element:
    QDomElement eventsElement = document.createElement(EventsElement);
    EventList events = m_storage->getAllEvents();
    Q_FOREACH (const Event &event, events) {
        QDomElement element = event.toXml(document);
        eventsElement.appendChild(element);
    }
    root.appendChild(eventsElement);
    return document;
}

class MakeSureTheModelIsUpdated
{
public:
    explicit MakeSureTheModelIsUpdated(Controller *controller)
        : m_controller(controller)
    {
    }

    ~MakeSureTheModelIsUpdated()
    {
        // now tell the data model that things have changed:
        m_controller->updateModelEventsAndTasks();
    }

private:
    Controller *m_controller;
};

QString Controller::importDatabaseFromXml(const QDomDocument &document)
{
    MakeSureTheModelIsUpdated m(this);

    // first, parse the XML document, and break if there is an error
    // (not touching the DB contents):
    TaskList importedTasks;
    EventList importedEvents;
    int databaseSchemaVersion;

    // FIXME test for the file to be a database export, not (for example) a task definitions export
    try {
        QDomElement rootElement = document.documentElement();
        bool ok;
        databaseSchemaVersion = rootElement.attribute(QStringLiteral("version")).toInt(&ok);
        if (!ok) throw XmlSerializationException(QObject::tr(
                                                     "Syntax error, no version attribute found."));

        QDomElement tasksElement = rootElement.firstChildElement(TasksElement);
        for (QDomElement element = tasksElement.firstChildElement(Task::tagName());
             !element.isNull(); element = element.nextSiblingElement(Task::tagName())) {
            Task task = Task::fromXml(element, databaseSchemaVersion);
            if (!task.isValid()) {
                qDebug() << "The following task is invalid and will not be added:";
                task.dump();
                // return tr( "The Export file contains at least one invalid task." );
            } else {
                importedTasks.append(task);
            }
        }
        QDomElement eventsElement = rootElement.firstChildElement(EventsElement);
        for (QDomElement element = eventsElement.firstChildElement(Event::tagName());
             !element.isNull(); element = element.nextSiblingElement(Event::tagName())) {
            Event event = Event::fromXml(element, databaseSchemaVersion);
            if (!event.isValid()) {
                qDebug() << "The following event is invalid and will not be added:";
                event.dump();
                // return tr( "The Export file contains at least one invalid event." );
            } else {
                importedEvents.append(event);
            }
        }
    } catch (const XmlSerializationException &e) {
        qDebug() << "Controller::importDatabaseFromXml: things fucked up:" << e.what();
        return tr("The export file is invalid: %1").arg(e.what());
    }

    const QString error = m_storage->setAllTasksAndEvents(CONFIGURATION.user, importedTasks,
                                                          importedEvents);
    if (!error.isEmpty()) {
        // the database should be unchanged, and the model will update on return
        return tr("Error importing tasks and events from the file:<br />%1")
               .arg(error);
    }

    // FIXME needed?

    // tell the model that the tasks and events have vanished:
    emit allEvents(EventList());
    emit definedTasks(TaskList());

    return QString();
}

void Controller::updateModelEventsAndTasks()
{
    TaskList tasks = m_storage->getAllTasks();
    // tell the view about the existing tasks;
    emit definedTasks(tasks);
    EventList events = m_storage->getAllEvents();
    emit allEvents(events);
}