-
Notifications
You must be signed in to change notification settings - Fork 1
/
DataManager.cpp
96 lines (76 loc) · 2.16 KB
/
DataManager.cpp
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
//
// Created by Raymond_Lx on 2019/11/10.
//
#include "DataManager.h"
#include <QFile>
#include <QDebug>
DataManager::DataManager():dirty(false){
//默认文件名
currentJsonFileUrl = QUrl::fromLocalFile("Untitled.json");
}
DataManager *DataManager::Instance() {
static DataManager ins;
return &ins;
}
void DataManager::setDirty(bool _d) {
dirty = _d;
}
bool DataManager::isDirty() {
return dirty;
}
bool DataManager::currentFileExists() {
return QFile::exists(currentJsonFileUrl.toLocalFile());
}
QString DataManager::getFileName() {
return currentJsonFileUrl.fileName();
}
bool DataManager::loadFromFile(const QString &path) {
if(!QFile::exists(path)){
qDebug()<<"File not found: "<<path<<endl;
return false;
}
currentJsonFileUrl = QUrl::fromLocalFile(path);
QFile theFile(currentJsonFileUrl.toLocalFile());
if(!theFile.open(QIODevice::ReadOnly | QIODevice::Text))
{
qDebug()<<"Can't open file: "<<path<<endl;
return false;
}
QString jsonText(theFile.readAll());
theFile.close();
Rix::Json::Parser p(jsonText.toStdString());
try {
Rix::Json::Object j(p.Parse());
currentJsonObject = j;
}catch (Rix::Json::ParserException e)
{
currentJsonFileUrl.clear();
qDebug()<<"Parsing json text fail!"<<endl;
qDebug()<<e.what()<<endl;
throw e;
return false;
}
dirty = false;
return true;
}
bool DataManager::saveToFile(const QString &path) {
currentJsonFileUrl = QUrl::fromLocalFile(path);
return saveToFile();
}
bool DataManager::saveToFile() {
if(currentJsonFileUrl.isEmpty())
return false;
QFile theFile(currentJsonFileUrl.toLocalFile());
if(!theFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
qDebug()<<"Can't open file "<<currentJsonFileUrl.toLocalFile()<<endl;
return false;
}
QString jsonText = QString::fromStdString(currentJsonObject.ToStr(true));
theFile.write(jsonText.toStdString().c_str());
theFile.close();
dirty = false;
return true;
}
Rix::Json::Object &DataManager::getCurrentJsonObject() {
return currentJsonObject;
}