summaryrefslogtreecommitdiff
path: root/Userland/DevTools/SQLStudio/ScriptEditor.cpp
blob: 0ad98073016fe2d81eaca71b49eaf37664a52ec4 (plain)
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
/*
 * Copyright (c) 2022, Dylan Katz <dykatz@uw.edu>
 * Copyright (c) 2022, Tim Flynn <trflynn89@serenityos.org>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <LibCore/Stream.h>
#include <LibGUI/Dialog.h>
#include <LibGUI/FilePicker.h>
#include <LibGUI/MessageBox.h>
#include <LibGUI/TabWidget.h>
#include <LibSQL/AST/SyntaxHighlighter.h>

#include "ScriptEditor.h"

namespace SQLStudio {

ScriptEditor::ScriptEditor()
{
    set_syntax_highlighter(make<SQL::AST::SyntaxHighlighter>());
    set_ruler_visible(true);
}

void ScriptEditor::new_script_with_temp_name(DeprecatedString name)
{
    set_name(name);
}

ErrorOr<void> ScriptEditor::open_script_from_file(LexicalPath const& file_path)
{
    auto file = TRY(Core::Stream::File::open(file_path.string(), Core::Stream::OpenMode::Read));
    auto buffer = TRY(file->read_until_eof());

    set_text({ buffer.bytes() });
    m_path = file_path.string();
    set_name(file_path.title());
    return {};
}

static ErrorOr<void> save_text_to_file(StringView filename, DeprecatedString text)
{
    auto file = TRY(Core::Stream::File::open(filename, Core::Stream::OpenMode::Write));

    if (!text.is_empty())
        TRY(file->write_entire_buffer(text.bytes()));

    return {};
}

ErrorOr<bool> ScriptEditor::save()
{
    if (m_path.is_empty())
        return save_as();

    TRY(save_text_to_file(m_path, text()));
    document().set_unmodified();
    return true;
}

ErrorOr<bool> ScriptEditor::save_as()
{
    auto maybe_save_path = GUI::FilePicker::get_save_filepath(window(), name(), "sql");
    if (!maybe_save_path.has_value())
        return false;

    auto save_path = maybe_save_path.release_value();
    TRY(save_text_to_file(save_path, text()));
    m_path = save_path;

    auto lexical_path = LexicalPath(save_path);
    set_name(lexical_path.title());

    auto parent = static_cast<GUI::TabWidget*>(parent_widget());
    if (parent)
        parent->set_tab_title(*this, lexical_path.title());

    document().set_unmodified();
    return true;
}

ErrorOr<bool> ScriptEditor::attempt_to_close()
{
    if (!document().is_modified())
        return true;

    auto result = GUI::MessageBox::ask_about_unsaved_changes(window(), m_path.is_empty() ? name() : m_path, document().undo_stack().last_unmodified_timestamp());
    switch (result) {
    case GUI::Dialog::ExecResult::Yes:
        return save();
    case GUI::Dialog::ExecResult::No:
        return true;
    default:
        return false;
    }
}

}