Serenity Operating System
1/*
2 * Copyright (c) 2022, Dylan Katz <dykatz@uw.edu>
3 * Copyright (c) 2022, Tim Flynn <trflynn89@serenityos.org>
4 *
5 * SPDX-License-Identifier: BSD-2-Clause
6 */
7
8#include <LibGUI/Dialog.h>
9#include <LibGUI/FilePicker.h>
10#include <LibGUI/MessageBox.h>
11#include <LibGUI/TabWidget.h>
12#include <LibSQL/AST/SyntaxHighlighter.h>
13
14#include "ScriptEditor.h"
15
16namespace SQLStudio {
17
18ScriptEditor::ScriptEditor()
19{
20 set_syntax_highlighter(make<SQL::AST::SyntaxHighlighter>());
21 set_ruler_visible(true);
22}
23
24void ScriptEditor::new_script_with_temp_name(DeprecatedString name)
25{
26 set_name(name);
27}
28
29ErrorOr<void> ScriptEditor::open_script_from_file(LexicalPath const& file_path)
30{
31 auto file = TRY(Core::File::open(file_path.string(), Core::File::OpenMode::Read));
32 auto buffer = TRY(file->read_until_eof());
33
34 set_text({ buffer.bytes() });
35 m_path = file_path.string();
36 set_name(file_path.title());
37 return {};
38}
39
40static ErrorOr<void> save_text_to_file(StringView filename, DeprecatedString text)
41{
42 auto file = TRY(Core::File::open(filename, Core::File::OpenMode::Write));
43
44 if (!text.is_empty())
45 TRY(file->write_until_depleted(text.bytes()));
46
47 return {};
48}
49
50ErrorOr<bool> ScriptEditor::save()
51{
52 if (m_path.is_empty())
53 return save_as();
54
55 TRY(save_text_to_file(m_path, text()));
56 document().set_unmodified();
57 return true;
58}
59
60ErrorOr<bool> ScriptEditor::save_as()
61{
62 auto maybe_save_path = GUI::FilePicker::get_save_filepath(window(), name(), "sql");
63 if (!maybe_save_path.has_value())
64 return false;
65
66 auto save_path = maybe_save_path.release_value();
67 TRY(save_text_to_file(save_path, text()));
68 m_path = save_path;
69
70 auto lexical_path = LexicalPath(save_path);
71 set_name(lexical_path.title());
72
73 auto parent = static_cast<GUI::TabWidget*>(parent_widget());
74 if (parent)
75 parent->set_tab_title(*this, lexical_path.title());
76
77 document().set_unmodified();
78 return true;
79}
80
81ErrorOr<bool> ScriptEditor::attempt_to_close()
82{
83 if (!document().is_modified())
84 return true;
85
86 auto result = GUI::MessageBox::ask_about_unsaved_changes(window(), m_path.is_empty() ? name() : m_path, document().undo_stack().last_unmodified_timestamp());
87 switch (result) {
88 case GUI::Dialog::ExecResult::Yes:
89 return save();
90 case GUI::Dialog::ExecResult::No:
91 return true;
92 default:
93 return false;
94 }
95}
96
97}