ScriptEditor.cpp 2.4 KB

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