MainWidget.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. /*
  2. * Copyright (c) 2022, Dylan Katz <dykatz@uw.edu>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibDesktop/Launcher.h>
  7. #include <LibGUI/Action.h>
  8. #include <LibGUI/Application.h>
  9. #include <LibGUI/BoxLayout.h>
  10. #include <LibGUI/FilePicker.h>
  11. #include <LibGUI/GroupBox.h>
  12. #include <LibGUI/JsonArrayModel.h>
  13. #include <LibGUI/Menu.h>
  14. #include <LibGUI/MessageBox.h>
  15. #include <LibGUI/SortingProxyModel.h>
  16. #include <LibGUI/Statusbar.h>
  17. #include <LibGUI/TabWidget.h>
  18. #include <LibGUI/TableView.h>
  19. #include <LibGUI/TextDocument.h>
  20. #include <LibGUI/TextEditor.h>
  21. #include <LibGUI/Toolbar.h>
  22. #include <LibGUI/ToolbarContainer.h>
  23. #include <LibSQL/AST/Lexer.h>
  24. #include <LibSQL/AST/Token.h>
  25. #include <LibSQL/SQLClient.h>
  26. #include "MainWidget.h"
  27. #include "ScriptEditor.h"
  28. namespace SQLStudio {
  29. MainWidget::MainWidget()
  30. {
  31. set_fill_with_background_color(true);
  32. set_layout<GUI::VerticalBoxLayout>();
  33. m_new_action = GUI::Action::create("&New", { Mod_Ctrl, Key_N }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/new.png").release_value_but_fixme_should_propagate_errors(), [this](auto&) {
  34. open_new_script();
  35. });
  36. m_open_action = GUI::CommonActions::make_open_action([&](auto&) {
  37. auto maybe_load_path = GUI::FilePicker::get_open_filepath(window());
  38. if (!maybe_load_path.has_value())
  39. return;
  40. auto lexical_path = LexicalPath(maybe_load_path.release_value());
  41. open_script_from_file(lexical_path);
  42. });
  43. m_save_action = GUI::CommonActions::make_save_action([&](auto&) {
  44. if (!m_tab_widget)
  45. return;
  46. auto editor = dynamic_cast<ScriptEditor*>(m_tab_widget->active_widget());
  47. if (!editor)
  48. return;
  49. auto save_attempt = editor->save();
  50. if (save_attempt.is_error())
  51. GUI::MessageBox::show_error(window(), String::formatted("Failed to save\n{}", save_attempt.release_error()));
  52. });
  53. m_save_as_action = GUI::CommonActions::make_save_as_action([&](auto&) {
  54. if (!m_tab_widget)
  55. return;
  56. auto editor = dynamic_cast<ScriptEditor*>(m_tab_widget->active_widget());
  57. if (!editor)
  58. return;
  59. auto save_attempt = editor->save_as();
  60. if (save_attempt.is_error())
  61. GUI::MessageBox::show_error(window(), String::formatted("Failed to save\n{}", save_attempt.release_error()));
  62. });
  63. m_save_all_action = GUI::Action::create("Save All", { Mod_Ctrl | Mod_Alt, Key_S }, [this](auto&) {
  64. auto current_active_widget = m_tab_widget->active_widget();
  65. ErrorOr<void> error {};
  66. m_tab_widget->for_each_child_widget([&](auto& child) {
  67. auto editor = dynamic_cast<ScriptEditor*>(&child);
  68. if (!editor)
  69. return IterationDecision::Continue;
  70. m_tab_widget->set_active_widget(editor);
  71. auto save_attempt = editor->save();
  72. if (save_attempt.is_error()) {
  73. error = save_attempt.release_error();
  74. return IterationDecision::Break;
  75. }
  76. auto save_result = save_attempt.release_value();
  77. if (save_result)
  78. return IterationDecision::Continue;
  79. return IterationDecision::Break;
  80. });
  81. if (error.is_error())
  82. GUI::MessageBox::show_error(window(), String::formatted("Failed to save all files\n{}", error.release_error()));
  83. m_tab_widget->set_active_widget(current_active_widget);
  84. });
  85. m_copy_action = GUI::CommonActions::make_copy_action([&](auto&) {
  86. if (!m_tab_widget)
  87. return;
  88. auto editor = dynamic_cast<ScriptEditor*>(m_tab_widget->active_widget());
  89. if (!editor)
  90. return;
  91. editor->copy_action().activate();
  92. update_editor_actions(editor);
  93. });
  94. m_cut_action = GUI::CommonActions::make_cut_action([&](auto&) {
  95. if (!m_tab_widget)
  96. return;
  97. auto editor = dynamic_cast<ScriptEditor*>(m_tab_widget->active_widget());
  98. if (!editor)
  99. return;
  100. editor->cut_action().activate();
  101. update_editor_actions(editor);
  102. });
  103. m_paste_action = GUI::CommonActions::make_paste_action([&](auto&) {
  104. if (!m_tab_widget)
  105. return;
  106. auto editor = dynamic_cast<ScriptEditor*>(m_tab_widget->active_widget());
  107. if (!editor)
  108. return;
  109. editor->paste_action().activate();
  110. update_editor_actions(editor);
  111. });
  112. m_undo_action = GUI::CommonActions::make_undo_action([&](auto&) {
  113. if (!m_tab_widget)
  114. return;
  115. auto editor = dynamic_cast<ScriptEditor*>(m_tab_widget->active_widget());
  116. if (!editor)
  117. return;
  118. editor->document().undo();
  119. update_editor_actions(editor);
  120. });
  121. m_redo_action = GUI::CommonActions::make_redo_action([&](auto&) {
  122. if (!m_tab_widget)
  123. return;
  124. auto editor = dynamic_cast<ScriptEditor*>(m_tab_widget->active_widget());
  125. if (!editor)
  126. return;
  127. editor->document().redo();
  128. update_editor_actions(editor);
  129. });
  130. m_run_script_action = GUI::Action::create("Run script", { Mod_Alt, Key_F9 }, Gfx::Bitmap::try_load_from_file("/res/icons/16x16/play.png").release_value_but_fixme_should_propagate_errors(), [&](auto&) {
  131. m_results.clear();
  132. m_current_line_for_parsing = 0;
  133. // TODO select the database to use in UI.
  134. m_connection_id = m_sql_client->connect("test");
  135. read_next_sql_statement_of_editor();
  136. });
  137. auto& toolbar_container = add<GUI::ToolbarContainer>();
  138. auto& toolbar = toolbar_container.add<GUI::Toolbar>();
  139. toolbar.add_action(*m_new_action);
  140. toolbar.add_action(*m_open_action);
  141. toolbar.add_action(*m_save_action);
  142. toolbar.add_action(*m_save_as_action);
  143. toolbar.add_separator();
  144. toolbar.add_action(*m_copy_action);
  145. toolbar.add_action(*m_cut_action);
  146. toolbar.add_action(*m_paste_action);
  147. toolbar.add_separator();
  148. toolbar.add_action(*m_undo_action);
  149. toolbar.add_action(*m_redo_action);
  150. toolbar.add_separator();
  151. toolbar.add_action(*m_run_script_action);
  152. m_tab_widget = add<GUI::TabWidget>();
  153. m_tab_widget->set_close_button_enabled(true);
  154. m_tab_widget->set_reorder_allowed(true);
  155. m_tab_widget->on_tab_close_click = [&](auto& widget) {
  156. auto editor = dynamic_cast<ScriptEditor*>(&widget);
  157. if (!editor)
  158. return;
  159. auto close_attempt = editor->attempt_to_close();
  160. if (close_attempt.is_error()) {
  161. GUI::MessageBox::show_error(window(), String::formatted("Failed to save before closing\n{}", close_attempt.release_error()));
  162. return;
  163. }
  164. if (close_attempt.release_value()) {
  165. m_tab_widget->remove_tab(widget);
  166. update_title();
  167. }
  168. };
  169. m_tab_widget->on_change = [&](auto&) {
  170. update_title();
  171. on_editor_change();
  172. };
  173. m_statusbar = add<GUI::Statusbar>(3);
  174. m_statusbar->segment(1).set_mode(GUI::Statusbar::Segment::Mode::Fixed);
  175. m_statusbar->segment(1).set_fixed_width(font().width("000000 characters (00000 words) selected") + font().max_glyph_width());
  176. m_statusbar->segment(2).set_mode(GUI::Statusbar::Segment::Mode::Fixed);
  177. m_statusbar->segment(2).set_fixed_width(font().width("Ln 0000, Col 000") + font().max_glyph_width());
  178. m_query_results_widget = add<GUI::GroupBox>("Results");
  179. m_query_results_widget->set_layout<GUI::VerticalBoxLayout>();
  180. m_query_results_widget->layout()->set_margins(6);
  181. m_query_results_table_view = m_query_results_widget->add<GUI::TableView>();
  182. m_sql_client = SQL::SQLClient::try_create().release_value_but_fixme_should_propagate_errors();
  183. m_sql_client->on_execution_success = [this](int, bool, int, int, int) {
  184. read_next_sql_statement_of_editor();
  185. };
  186. m_sql_client->on_next_result = [this](int, Vector<String> const& row) {
  187. m_results.append(row);
  188. };
  189. m_sql_client->on_results_exhausted = [this](int, int) {
  190. if (m_results.size() == 0)
  191. return;
  192. if (m_results[0].size() == 0)
  193. return;
  194. Vector<GUI::JsonArrayModel::FieldSpec> query_result_fields;
  195. for (size_t i = 0; i < m_results[0].size(); i++)
  196. query_result_fields.empend(String::formatted("column_{}", i + 1), String::formatted("Column {}", i + 1), Gfx::TextAlignment::CenterLeft);
  197. auto query_results_model = GUI::JsonArrayModel::create("{}", move(query_result_fields));
  198. m_query_results_table_view->set_model(MUST(GUI::SortingProxyModel::create(*query_results_model)));
  199. for (auto& result_row : m_results) {
  200. Vector<JsonValue> individual_result_as_json;
  201. for (auto& result_row_column : result_row)
  202. individual_result_as_json.append(result_row_column);
  203. query_results_model->add(move(individual_result_as_json));
  204. }
  205. };
  206. }
  207. void MainWidget::initialize_menu(GUI::Window* window)
  208. {
  209. auto& file_menu = window->add_menu("&File");
  210. file_menu.add_action(*m_new_action);
  211. file_menu.add_action(*m_open_action);
  212. file_menu.add_action(*m_save_action);
  213. file_menu.add_action(*m_save_as_action);
  214. file_menu.add_action(*m_save_all_action);
  215. file_menu.add_separator();
  216. file_menu.add_action(GUI::CommonActions::make_quit_action([](auto&) {
  217. GUI::Application::the()->quit();
  218. }));
  219. auto& edit_menu = window->add_menu("&Edit");
  220. edit_menu.add_action(*m_copy_action);
  221. edit_menu.add_action(*m_cut_action);
  222. edit_menu.add_action(*m_paste_action);
  223. edit_menu.add_separator();
  224. edit_menu.add_action(*m_undo_action);
  225. edit_menu.add_action(*m_redo_action);
  226. edit_menu.add_separator();
  227. edit_menu.add_action(*m_run_script_action);
  228. auto& help_menu = window->add_menu("&Help");
  229. help_menu.add_action(GUI::CommonActions::make_help_action([](auto&) {
  230. Desktop::Launcher::open(URL::create_with_file_protocol("/usr/share/man/man1/SQLStudio.md"), "/bin/Help");
  231. }));
  232. help_menu.add_action(GUI::CommonActions::make_about_action("SQL Studio", GUI::Icon::default_icon("app-sql-studio"), window));
  233. }
  234. void MainWidget::open_new_script()
  235. {
  236. auto new_script_name = String::formatted("New Script - {}", m_new_script_counter);
  237. ++m_new_script_counter;
  238. auto& editor = m_tab_widget->add_tab<ScriptEditor>(new_script_name);
  239. editor.new_script_with_temp_name(new_script_name);
  240. editor.on_cursor_change = [this] { on_editor_change(); };
  241. editor.on_selection_change = [this] { on_editor_change(); };
  242. editor.on_highlighter_change = [this] { on_editor_change(); };
  243. m_tab_widget->set_active_widget(&editor);
  244. }
  245. void MainWidget::open_script_from_file(LexicalPath const& file_path)
  246. {
  247. auto& editor = m_tab_widget->add_tab<ScriptEditor>(file_path.title());
  248. auto maybe_error = editor.open_script_from_file(file_path);
  249. if (maybe_error.is_error()) {
  250. GUI::MessageBox::show_error(window(), String::formatted("Failed to open {}\n{}", file_path, maybe_error.release_error()));
  251. return;
  252. }
  253. editor.on_cursor_change = [this] { on_editor_change(); };
  254. editor.on_selection_change = [this] { on_editor_change(); };
  255. editor.on_highlighter_change = [this] { on_editor_change(); };
  256. m_tab_widget->set_active_widget(&editor);
  257. }
  258. void MainWidget::open_database_from_file(LexicalPath const&)
  259. {
  260. TODO();
  261. }
  262. bool MainWidget::request_close()
  263. {
  264. auto any_scripts_modified { false };
  265. auto is_script_modified = [&](auto& child) {
  266. auto editor = dynamic_cast<ScriptEditor*>(&child);
  267. if (!editor)
  268. return IterationDecision::Continue;
  269. if (editor->document().is_modified()) {
  270. any_scripts_modified = true;
  271. return IterationDecision::Break;
  272. }
  273. return IterationDecision::Continue;
  274. };
  275. m_tab_widget->for_each_child_widget(is_script_modified);
  276. if (!any_scripts_modified)
  277. return true;
  278. auto result = GUI::MessageBox::ask_about_unsaved_changes(window(), {});
  279. switch (result) {
  280. case GUI::Dialog::ExecResult::Yes:
  281. break;
  282. case GUI::Dialog::ExecResult::No:
  283. return true;
  284. default:
  285. return false;
  286. }
  287. m_save_all_action->activate();
  288. any_scripts_modified = false;
  289. m_tab_widget->for_each_child_widget(is_script_modified);
  290. return !any_scripts_modified;
  291. }
  292. void MainWidget::update_title()
  293. {
  294. auto editor = dynamic_cast<ScriptEditor*>(m_tab_widget->active_widget());
  295. if (editor) {
  296. window()->set_title(String::formatted("{} - SQL Studio", editor->name()));
  297. } else {
  298. window()->set_title("SQL Studio");
  299. }
  300. }
  301. void MainWidget::on_editor_change()
  302. {
  303. auto editor = dynamic_cast<ScriptEditor*>(m_tab_widget->active_widget());
  304. if (editor) {
  305. update_statusbar(editor);
  306. update_editor_actions(editor);
  307. }
  308. }
  309. void MainWidget::update_statusbar(ScriptEditor* editor)
  310. {
  311. if (editor->has_selection()) {
  312. auto character_count = editor->selected_text().length();
  313. auto word_count = editor->number_of_selected_words();
  314. m_statusbar->set_text(1, String::formatted("{} {} ({} {}) selected", character_count, character_count == 1 ? "character" : "characters", word_count, word_count == 1 ? "word" : "words"));
  315. } else {
  316. auto character_count = editor->text().length();
  317. auto word_count = editor->number_of_words();
  318. m_statusbar->set_text(1, String::formatted("{} {} ({} {})", character_count, character_count == 1 ? "character" : "characters", word_count, word_count == 1 ? "word" : "words"));
  319. }
  320. m_statusbar->set_text(2, String::formatted("Ln {}, Col {}", editor->cursor().line() + 1, editor->cursor().column()));
  321. }
  322. void MainWidget::update_editor_actions(ScriptEditor* editor)
  323. {
  324. m_copy_action->set_enabled(editor->copy_action().is_enabled());
  325. m_cut_action->set_enabled(editor->cut_action().is_enabled());
  326. m_paste_action->set_enabled(editor->paste_action().is_enabled());
  327. m_undo_action->set_enabled(editor->undo_action().is_enabled());
  328. m_redo_action->set_enabled(editor->redo_action().is_enabled());
  329. }
  330. void MainWidget::drop_event(GUI::DropEvent& drop_event)
  331. {
  332. drop_event.accept();
  333. window()->move_to_front();
  334. if (drop_event.mime_data().has_urls()) {
  335. auto urls = drop_event.mime_data().urls();
  336. if (urls.is_empty())
  337. return;
  338. for (auto& url : urls) {
  339. auto& scheme = url.scheme();
  340. if (!scheme.equals_ignoring_case("file"))
  341. continue;
  342. auto lexical_path = LexicalPath(url.path());
  343. if (lexical_path.extension().equals_ignoring_case("sql"sv))
  344. open_script_from_file(lexical_path);
  345. if (lexical_path.extension().equals_ignoring_case("db"sv))
  346. open_database_from_file(lexical_path);
  347. }
  348. }
  349. }
  350. String MainWidget::read_next_sql_statement_of_editor()
  351. {
  352. StringBuilder piece;
  353. do {
  354. if (!piece.is_empty())
  355. piece.append('\n');
  356. auto line_maybe = read_next_line_of_editor();
  357. if (!line_maybe.has_value())
  358. return {};
  359. auto& line = line_maybe.value();
  360. auto lexer = SQL::AST::Lexer(line);
  361. piece.append(line);
  362. bool is_first_token = true;
  363. bool is_command = false;
  364. bool last_token_ended_statement = false;
  365. bool tokens_found = false;
  366. for (SQL::AST::Token token = lexer.next(); token.type() != SQL::AST::TokenType::Eof; token = lexer.next()) {
  367. tokens_found = true;
  368. switch (token.type()) {
  369. case SQL::AST::TokenType::ParenOpen:
  370. ++m_editor_line_level;
  371. break;
  372. case SQL::AST::TokenType::ParenClose:
  373. --m_editor_line_level;
  374. break;
  375. case SQL::AST::TokenType::SemiColon:
  376. last_token_ended_statement = true;
  377. break;
  378. case SQL::AST::TokenType::Period:
  379. if (is_first_token)
  380. is_command = true;
  381. break;
  382. default:
  383. last_token_ended_statement = is_command;
  384. break;
  385. }
  386. is_first_token = false;
  387. }
  388. if (tokens_found)
  389. m_editor_line_level = last_token_ended_statement ? 0 : (m_editor_line_level > 0 ? m_editor_line_level : 1);
  390. } while ((m_editor_line_level > 0) || piece.is_empty());
  391. auto statement_id = m_sql_client->sql_statement(m_connection_id, piece.to_string());
  392. m_sql_client->async_statement_execute(statement_id);
  393. return piece.to_string();
  394. }
  395. Optional<String> MainWidget::read_next_line_of_editor()
  396. {
  397. auto editor = dynamic_cast<ScriptEditor*>(m_tab_widget->active_widget());
  398. if (!editor)
  399. return {};
  400. if (m_current_line_for_parsing < editor->document().line_count()) {
  401. String result = editor->document().line(m_current_line_for_parsing).to_utf8();
  402. m_current_line_for_parsing++;
  403. return result;
  404. } else {
  405. return {};
  406. }
  407. }
  408. }