File: editorwidget.cpp

package info (click to toggle)
qt6-declarative 6.9.1%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 308,920 kB
  • sloc: cpp: 775,911; javascript: 514,247; xml: 10,855; python: 2,806; ansic: 2,253; java: 810; sh: 262; makefile: 41; php: 27
file content (278 lines) | stat: -rw-r--r-- 7,861 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
// Copyright (C) 2024 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause

#include "editorwidget.h"
#include "codeeditor.h"
#include "patheditwidget.h"
#include "../states/statecontroller.h"
#include "../utility/syntaxhighlighter.h"

#include <QFile>
#include <QMessageBox>
#include <QPushButton>
#include <QVBoxLayout>

namespace {
static inline QByteArray loadFromFile(const QString &filePath)
{
    QFile file{filePath};
    if (!file.open(QFile::ReadOnly | QFile::Text))
        return {};
    return file.readAll();
}

[[nodiscard]] static inline bool saveToFile(const QString &filePath, const QByteArray &data)
{
    QFile file{filePath};
    if (!file.open(QFile::WriteOnly | QFile::Text))
        return false;
    file.write(data);
    return true;
}
}

EditorWidget::EditorWidget(QWidget *parent)
    : QWidget{parent}
    , m_pathEdit{new PathEditWidget}
    , m_editor{new CodeEditor}
    , m_saveButton{new QPushButton}
    , m_reloadButton{new QPushButton}
    , m_closeButton{new QPushButton}
{
    initUI();

    SyntaxHighlighter *syntaxHighlighter = new SyntaxHighlighter{this};
    syntaxHighlighter->setDocument(m_editor->document());

    setupConnections();
}

void EditorWidget::updateEditor()
{
    const QByteArray fileContent = loadFromFile(m_pathEdit->filePath());
    // TODO: show warning if fileContent.isNull()

    m_mutex.lock();
    QTextDocument *doc = m_editor->document();
    doc->setPlainText(fileContent);
    doc->setModified(false);
    m_mutex.unlock();
}

void EditorWidget::openFile()
{
    switch (StateController::instance()->currentState()) {
    case StateController::NewState:
    case StateController::DirtyState: {
        const auto answer = QMessageBox::question(this, tr("About to Open File"),
                                                  tr("You have unsaved changes. "
                                                     "Are you sure you want to discard them?"),
                                                  QMessageBox::Yes | QMessageBox::No,
                                                  QMessageBox::No);
        if (answer != QMessageBox::Yes)
            return;
    } break;
    default:
        break;
    }

    m_pathEdit->openFilePath();
}

void EditorWidget::saveFile()
{
    if (!m_mutex.tryLock())
        return;

    QTextDocument *doc = m_editor->document();
    QString plainText = doc->toPlainText();

    StateController* stateController = StateController::instance();

    auto save = [&](const QString &filePath) -> bool {
        if (saveToFile(filePath, plainText.toUtf8())) {
            doc->setModified(false);
            stateController->changesSaved(m_pathEdit->filePath());
            return true;
        }
        // TODO: show warning
        return false;
    };

    switch (stateController->currentState()) {
    case StateController::DirtyState:
        if (m_pathEdit->filePath() == DEFAULT_SOURCE_PATH)
            save(m_pathEdit->saveFilePath());
        else
            save(m_pathEdit->filePath());
        break;

    case StateController::NewState:
        save(m_pathEdit->saveFilePath());
        break;

    default:
        break;
    }


    m_mutex.unlock();
}

void EditorWidget::closeFile()
{
    if (!m_mutex.tryLock())
        return;
    StateController::instance()->fileClosed();
    m_mutex.unlock();
}

void EditorWidget::reloadFile()
{
    if (!m_mutex.tryLock())
        return;

    const QString filePath = m_pathEdit->filePath();

    const QByteArray fileContent = loadFromFile(filePath);
    // TODO: show warning if fileContent.isNull()

    QTextDocument *doc = m_editor->document();
    doc->setPlainText(fileContent);
    doc->setModified(false);

    StateController::instance()->setDirty(false);

    m_mutex.unlock();
}

void EditorWidget::moveCursorTo(int line, int column)
{
    if (line < 1 || column < 1)
        return;

    QTextCursor cursor = m_editor->textCursor();
    cursor.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor);
    cursor.movePosition(QTextCursor::Down, QTextCursor::MoveAnchor, line - 1);
    cursor.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, column - 1);
    m_editor->setTextCursor(cursor);
    m_editor->setFocus();
}

void EditorWidget::initUI()
{
    QHBoxLayout *actionsLayout = new QHBoxLayout;
    actionsLayout->addWidget(m_saveButton);
    actionsLayout->addWidget(m_reloadButton);
    actionsLayout->addWidget(m_closeButton);

    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(m_pathEdit);
    layout->addWidget(m_editor);
    layout->addLayout(actionsLayout);
    layout->setContentsMargins(0,0,0,0);
    setLayout(layout);

    m_editor->setCursorWidth(2);
    m_editor->setPlaceholderText(tr("Write code or open a file"));
    m_saveButton->setText(tr("Save"));
    m_saveButton->setEnabled(false);
    m_reloadButton->setText(tr("Reload"));
    m_reloadButton->setEnabled(false);
    m_closeButton->setText(tr("Close"));
    m_closeButton->setEnabled(false);
}

void EditorWidget::setupConnections()
{
    connect(StateController::instance(), &StateController::stateChanged, this,
            &EditorWidget::onAppStateChanged);

    connect(m_pathEdit, &PathEditWidget::fileSelected, this, &EditorWidget::onFileSelected);
    connect(m_pathEdit, &PathEditWidget::openFileRequested, this, &EditorWidget::openFile);
    connect(m_editor, &QPlainTextEdit::modificationChanged, this, &EditorWidget::onEditorModified);
    connect(m_editor, &QPlainTextEdit::textChanged, this, &EditorWidget::onEditorTextChanged);
    connect(m_saveButton, &QPushButton::clicked, this, &EditorWidget::saveFile);
    connect(m_reloadButton, &QPushButton::clicked, this, &EditorWidget::reloadFile);
    connect(m_closeButton, &QPushButton::clicked, this, &EditorWidget::closeFile);
}

void EditorWidget::onAppStateChanged(int oldState, int newState)
{
    Q_UNUSED(oldState);

    m_saveButton->setEnabled((newState == StateController::NewState) ||
                             (newState == StateController::DirtyState));
    m_reloadButton->setEnabled(newState == StateController::DirtyState);
    m_closeButton->setEnabled(newState == StateController::OpenState);

    switch (newState) {
    case StateController::InitState:
        m_editor->clear();
        break;

    default:
        break;
    }
}

void EditorWidget::onFileSelected(const QString &filePath)
{
    StateController *stateController = StateController::instance();

    switch (stateController->currentState()) {
    case StateController::NewState:
        stateController->changesSaved(filePath);
        break;
    case StateController::DirtyState:
        stateController->changesSaved(filePath);
        closeFile();
        break;
    default:
        break;
    }

    const QByteArray fileContent = loadFromFile(filePath);
    // TODO: show warning if fileContent.isNull()

    if (m_mutex.tryLock()) {
        QTextDocument *doc = m_editor->document();
        doc->setPlainText(fileContent);
        doc->setModified(false);
        StateController::instance()->fileLoaded(filePath);
        m_mutex.unlock();
    }
}

void EditorWidget::onEditorModified(bool dirty)
{
    if (!m_mutex.tryLock())
        return;
    StateController::instance()->setDirty(dirty);
    m_mutex.unlock();
}

void EditorWidget::onEditorTextChanged()
{
    if (!m_mutex.tryLock())
        return;

    StateController* stateController = StateController::instance();

    switch (stateController->currentState()) {
    case StateController::InitState:
        if (!m_editor->document()->isEmpty())
            stateController->setDirty(true);
        break;

    case StateController::NewState:
        if (m_editor->document()->isEmpty())
            stateController->setDirty(false);
        break;

    default:
        break;
    }

    m_mutex.unlock();
}