Lomiri
ScreensConfiguration.cpp
1 /*
2  * Copyright (C) 2017 Canonical Ltd.
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; version 3.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11  * GNU General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License
14  * along with this program. If not, see <http://www.gnu.org/licenses/>.
15  */
16 
17 #include "ScreensConfiguration.h"
18 #include "Screen.h"
19 #include "Workspace.h"
20 #include "WorkspaceManager.h"
21 
22 #include <QJsonObject>
23 #include <QJsonDocument>
24 #include <QJsonArray>
25 #include <QFile>
26 #include <QStandardPaths>
27 
28 namespace
29 {
30 QJsonArray jsonScreens;
31 }
32 
33 ScreensConfiguration::ScreensConfiguration()
34 {
35  const QString dbPath = QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation) + QStringLiteral("/lomiri/");
36  QFile f(dbPath + "workspaces");
37 
38  if (f.open(QIODevice::ReadOnly)) {
39  QByteArray saveData = f.readAll();
40  QJsonDocument loadDoc(QJsonDocument::fromJson(saveData));
41  QJsonObject json(loadDoc.object());
42  jsonScreens = json["screens"].toArray();
43  }
44 }
45 
46 ScreensConfiguration::~ScreensConfiguration()
47 {
48  const QString dbPath = QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation) + QStringLiteral("/lomiri/");
49  QFile f(dbPath + "workspaces");
50  if (f.open(QIODevice::WriteOnly)) {
51  QJsonObject json;
52  json["screens"] = jsonScreens;
53  QJsonDocument saveDoc(json);
54  f.write(saveDoc.toJson());
55  }
56 }
57 
58 void ScreensConfiguration::load(Screen *screen)
59 {
60  int workspaces = 2;
61  for (auto iter = jsonScreens.begin(); iter != jsonScreens.end(); ++iter) {
62  QJsonObject jsonScreen = (*iter).toObject();
63  if (jsonScreen["name"] == screen->name()) {
64  QJsonValue jsonWorkspaces = jsonScreen["workspaces"];
65  workspaces = qMax(jsonWorkspaces.toInt(workspaces), 1);
66  break;
67  }
68  }
69 
70  for (int i = 0; i < workspaces; i++) {
71  WorkspaceManager::instance()->createWorkspace()->assign(screen->workspaces());
72  }
73 }
74 
75 void ScreensConfiguration::save(Screen *screen)
76 {
77  QJsonObject newJsonScreen;
78  newJsonScreen["name"] = screen->name();
79  newJsonScreen["workspaces"] = qMax(screen->workspaces()->rowCount(), 1);
80 
81  auto iter = jsonScreens.begin();
82  for (; iter != jsonScreens.end(); ++iter) {
83  QJsonObject jsonScreen = (*iter).toObject();
84  if (jsonScreen["name"] == screen->name()) {
85  break;
86  }
87  }
88 
89  if (iter == jsonScreens.end()) {
90  jsonScreens.push_back(newJsonScreen);
91  } else {
92  *iter = newJsonScreen;
93  }
94 }