Skip to content

Commit b12e995

Browse files
committed
[Refactor] Improve memory management by using smart pointers for editor and tree in MainWindow
1 parent 113d206 commit b12e995

File tree

1 file changed

+20
-27
lines changed

1 file changed

+20
-27
lines changed

src/MainWindow.cpp

Lines changed: 20 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
#include "MainWindow.h"
22
#include "Syntax.h"
33
#include "Tree.h"
4+
#include "CodeEditor.h"
45

56
#include <QMenuBar>
67
#include <QFileDialog>
@@ -14,8 +15,8 @@
1415

1516
MainWindow::MainWindow(QWidget *parent)
1617
: QMainWindow(parent),
17-
editor(new CodeEditor(this)),
18-
syntax(new Syntax(editor->document())),
18+
editor(std::make_unique<CodeEditor>(this)),
19+
syntax(std::make_unique<Syntax>(editor->document())),
1920
tree(nullptr)
2021
{
2122
setWindowTitle("CodeAstra ~ Code Editor");
@@ -38,10 +39,9 @@ void MainWindow::initTree()
3839
QSplitter *splitter = new QSplitter(Qt::Horizontal, this);
3940
setCentralWidget(splitter);
4041

41-
tree = new Tree(splitter, this);
42-
43-
splitter->addWidget(editor);
42+
tree = std::make_unique<Tree>(splitter, this);
4443

44+
splitter->addWidget(editor.get());
4545
splitter->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
4646
splitter->setHandleWidth(5);
4747
splitter->setSizes(QList<int>() << 150 << 800);
@@ -158,27 +158,7 @@ void MainWindow::openFile()
158158
"C++ Files (*.cpp *.h);;Text Files (*.txt);;All Files (*)");
159159
if (!fileName.isEmpty())
160160
{
161-
QFile file(fileName);
162-
if (!file.open(QFile::ReadOnly | QFile::Text))
163-
{
164-
QMessageBox::warning(this, "Error", "Cannot open file: " + file.errorString());
165-
return;
166-
}
167-
168-
QTextStream in(&file);
169-
if (editor)
170-
{
171-
editor->setPlainText(in.readAll());
172-
}
173-
else
174-
{
175-
QMessageBox::critical(this, "Error", "Editor is not initialized.");
176-
}
177-
file.close();
178-
179-
currentFileName = fileName;
180-
181-
setWindowTitle("CodeAstra ~ " + QFileInfo(fileName).fileName());
161+
loadFileInEditor(fileName);
182162
}
183163
}
184164

@@ -202,6 +182,11 @@ void MainWindow::saveFile()
202182
{
203183
out << editor->toPlainText();
204184
}
185+
else
186+
{
187+
QMessageBox::critical(this, "Error", "Editor is not initialized.");
188+
return;
189+
}
205190
file.close();
206191

207192
statusBar()->showMessage("File saved successfully.", 2000);
@@ -229,7 +214,15 @@ void MainWindow::loadFileInEditor(const QString &filePath)
229214
}
230215

231216
QTextStream in(&file);
232-
editor->setPlainText(in.readAll());
217+
if (editor)
218+
{
219+
editor->setPlainText(in.readAll());
220+
}
221+
else
222+
{
223+
QMessageBox::critical(this, "Error", "Editor is not initialized.");
224+
return;
225+
}
233226
file.close();
234227

235228
currentFileName = filePath;

0 commit comments

Comments
 (0)