1#include "FileEditor.h"
2
3#include <FileDiffEditor.h>
4#include <GitQlientStyles.h>
5#include <Highlighter.h>
6
7#include <QVBoxLayout>
8#include <QMessageBox>
9
10FileEditor::FileEditor(bool highlighter, QWidget *parent)
11 : QFrame(parent)
12 , mFileEditor(new FileDiffEditor())
13{
14 if (highlighter)
15 mHighlighter = new Highlighter(mFileEditor->document());
16
17 const auto layout = new QVBoxLayout(this);
18 layout->setContentsMargins(QMargins());
19 layout->setSpacing(0);
20 layout->addWidget(mFileEditor);
21}
22
23void FileEditor::editFile(const QString &fileName)
24{
25 mFileName = fileName;
26
27 QFile f(mFileName);
28
29 if (f.open(QIODevice::ReadOnly))
30 {
31 mLoadedContent = QString::fromUtf8(f.readAll());
32 f.close();
33 }
34
35 mFileEditor->loadDiff(mLoadedContent, {});
36
37 isEditing = true;
38}
39
40void FileEditor::finishEdition()
41{
42 if (isEditing)
43 {
44 const auto currentContent = mFileEditor->toPlainText();
45 QFile f(mFileName);
46 QString fileContent;
47
48 if (f.open(QIODevice::ReadOnly))
49 {
50 fileContent = QString::fromUtf8(f.readAll());
51 f.close();
52 }
53
54 if (currentContent != fileContent)
55 {
56 const auto alert = new QMessageBox(QMessageBox::Question, tr("Unsaved changes"),
57 tr("The current text was modified. Do you want to save the changes?"));
58 alert->setStyleSheet(GitQlientStyles::getInstance()->getStyles());
59 alert->addButton(tr("Discard"), QMessageBox::ButtonRole::RejectRole);
60 alert->addButton(tr("Save"), QMessageBox::ButtonRole::AcceptRole);
61
62 if (alert->exec() == QMessageBox::Accepted)
63 saveTextInFile(currentContent);
64 }
65
66 isEditing = false;
67
68 emit signalEditionClosed();
69 }
70}
71
72void FileEditor::saveFile()
73{
74 const auto currentContent = mFileEditor->toPlainText();
75
76 saveTextInFile(currentContent);
77}
78
79void FileEditor::saveTextInFile(const QString &content) const
80{
81 QFile f(mFileName);
82
83 if (f.open(QIODevice::WriteOnly))
84 {
85 f.write(content.toUtf8());
86 f.close();
87 }
88}
89