ScriptEditor.cpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /*
  2. * Copyright (c) 2022, Dylan Katz <dykatz@uw.edu>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibCore/Stream.h>
  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(String 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::Stream::File::open(file_path.string(), Core::Stream::OpenMode::Read));
  26. auto buffer = TRY(file->read_all());
  27. set_text({ buffer.bytes() });
  28. m_path = file_path.string();
  29. set_name(file_path.title());
  30. return {};
  31. }
  32. ErrorOr<bool> ScriptEditor::save()
  33. {
  34. if (m_path.is_empty())
  35. return save_as();
  36. auto file = TRY(Core::Stream::File::open(m_path, Core::Stream::OpenMode::Write));
  37. auto editor_text = text();
  38. if (editor_text.length() && !file->write_or_error(editor_text.bytes()))
  39. return Error::from_string_literal("Failed to write to file");
  40. document().set_unmodified();
  41. return true;
  42. }
  43. ErrorOr<bool> ScriptEditor::save_as()
  44. {
  45. auto maybe_save_path = GUI::FilePicker::get_save_filepath(window(), name(), "sql");
  46. if (!maybe_save_path.has_value())
  47. return false;
  48. auto save_path = maybe_save_path.release_value();
  49. auto file = TRY(Core::Stream::File::open(save_path, Core::Stream::OpenMode::Write));
  50. auto editor_text = text();
  51. if (editor_text.length() && !file->write_or_error(editor_text.bytes()))
  52. return Error::from_string_literal("Failed to write to file");
  53. m_path = save_path;
  54. auto lexical_path = LexicalPath(save_path);
  55. set_name(lexical_path.title());
  56. auto parent = static_cast<GUI::TabWidget*>(parent_widget());
  57. if (parent)
  58. parent->set_tab_title(*this, lexical_path.title());
  59. document().set_unmodified();
  60. return true;
  61. }
  62. ErrorOr<bool> ScriptEditor::attempt_to_close()
  63. {
  64. if (!document().is_modified())
  65. return true;
  66. auto result = GUI::MessageBox::ask_about_unsaved_changes(window(), m_path.is_empty() ? name() : m_path, document().undo_stack().last_unmodified_timestamp());
  67. switch (result) {
  68. case GUI::Dialog::ExecResult::Yes:
  69. return save();
  70. case GUI::Dialog::ExecResult::No:
  71. return true;
  72. default:
  73. return false;
  74. }
  75. }
  76. }