ScriptEditor.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. #include <LibGUI/Dialog.h>
  8. #include <LibGUI/FilePicker.h>
  9. #include <LibGUI/MessageBox.h>
  10. #include <LibGUI/TabWidget.h>
  11. #include <LibSQL/AST/SyntaxHighlighter.h>
  12. #include "ScriptEditor.h"
  13. namespace SQLStudio {
  14. ScriptEditor::ScriptEditor()
  15. {
  16. set_syntax_highlighter(make<SQL::AST::SyntaxHighlighter>());
  17. set_ruler_visible(true);
  18. }
  19. void ScriptEditor::new_script_with_temp_name(DeprecatedString name)
  20. {
  21. set_name(name);
  22. }
  23. ErrorOr<void> ScriptEditor::open_script_from_file(LexicalPath const& file_path)
  24. {
  25. auto file = TRY(Core::File::open(file_path.string(), Core::File::OpenMode::Read));
  26. auto buffer = TRY(file->read_until_eof());
  27. set_text({ buffer.bytes() });
  28. m_path = file_path.string();
  29. set_name(file_path.title());
  30. return {};
  31. }
  32. static ErrorOr<void> save_text_to_file(StringView filename, DeprecatedString text)
  33. {
  34. auto file = TRY(Core::File::open(filename, Core::File::OpenMode::Write));
  35. if (!text.is_empty())
  36. TRY(file->write_until_depleted(text.bytes()));
  37. return {};
  38. }
  39. ErrorOr<bool> ScriptEditor::save()
  40. {
  41. if (m_path.is_empty())
  42. return save_as();
  43. TRY(save_text_to_file(m_path, text()));
  44. document().set_unmodified();
  45. return true;
  46. }
  47. ErrorOr<bool> ScriptEditor::save_as()
  48. {
  49. auto maybe_save_path = GUI::FilePicker::get_save_filepath(window(), name(), "sql");
  50. if (!maybe_save_path.has_value())
  51. return false;
  52. auto save_path = maybe_save_path.release_value();
  53. TRY(save_text_to_file(save_path, text()));
  54. m_path = save_path;
  55. auto lexical_path = LexicalPath(save_path);
  56. set_name(lexical_path.title());
  57. auto parent = static_cast<GUI::TabWidget*>(parent_widget());
  58. if (parent)
  59. parent->set_tab_title(*this, String::from_utf8(lexical_path.title()).release_value_but_fixme_should_propagate_errors());
  60. document().set_unmodified();
  61. return true;
  62. }
  63. ErrorOr<bool> ScriptEditor::attempt_to_close()
  64. {
  65. if (!document().is_modified())
  66. return true;
  67. auto result = GUI::MessageBox::ask_about_unsaved_changes(window(), m_path.is_empty() ? name() : m_path, document().undo_stack().last_unmodified_timestamp());
  68. switch (result) {
  69. case GUI::Dialog::ExecResult::Yes:
  70. return save();
  71. case GUI::Dialog::ExecResult::No:
  72. return true;
  73. default:
  74. return false;
  75. }
  76. }
  77. }