MainWidget.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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"sv).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(), DeprecatedString::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(), DeprecatedString::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(), DeprecatedString::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"sv).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(), DeprecatedString::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. on_editor_change();
  168. }
  169. };
  170. m_tab_widget->on_change = [&](auto&) {
  171. update_title();
  172. on_editor_change();
  173. };
  174. m_action_tab_widget = add<GUI::TabWidget>();
  175. m_action_tab_widget->set_fixed_height(0);
  176. m_action_tab_widget->set_close_button_enabled(true);
  177. m_query_results_widget = m_action_tab_widget->add_tab<GUI::Widget>("Results");
  178. m_query_results_widget->set_layout<GUI::VerticalBoxLayout>();
  179. m_query_results_widget->layout()->set_margins(6);
  180. m_query_results_table_view = m_query_results_widget->add<GUI::TableView>();
  181. m_action_tab_widget->on_tab_close_click = [this](auto&) {
  182. m_action_tab_widget->set_fixed_height(0);
  183. };
  184. m_statusbar = add<GUI::Statusbar>(3);
  185. m_statusbar->segment(1).set_mode(GUI::Statusbar::Segment::Mode::Fixed);
  186. m_statusbar->segment(1).set_fixed_width(font().width("000000 characters (00000 words) selected"sv) + font().max_glyph_width());
  187. m_statusbar->segment(2).set_mode(GUI::Statusbar::Segment::Mode::Fixed);
  188. m_statusbar->segment(2).set_fixed_width(font().width("Ln 0000, Col 000"sv) + font().max_glyph_width());
  189. m_sql_client = SQL::SQLClient::try_create().release_value_but_fixme_should_propagate_errors();
  190. m_sql_client->on_execution_success = [this](auto, auto, auto, auto, auto, auto) {
  191. read_next_sql_statement_of_editor();
  192. };
  193. m_sql_client->on_next_result = [this](auto, auto, auto const& row) {
  194. m_results.append(row);
  195. };
  196. m_sql_client->on_results_exhausted = [this](auto, auto, auto) {
  197. if (m_results.size() == 0)
  198. return;
  199. if (m_results[0].size() == 0)
  200. return;
  201. Vector<GUI::JsonArrayModel::FieldSpec> query_result_fields;
  202. for (size_t i = 0; i < m_results[0].size(); i++)
  203. query_result_fields.empend(DeprecatedString::formatted("column_{}", i + 1), DeprecatedString::formatted("Column {}", i + 1), Gfx::TextAlignment::CenterLeft);
  204. auto query_results_model = GUI::JsonArrayModel::create("{}", move(query_result_fields));
  205. m_query_results_table_view->set_model(MUST(GUI::SortingProxyModel::create(*query_results_model)));
  206. for (auto& result_row : m_results) {
  207. Vector<JsonValue> individual_result_as_json;
  208. for (auto& result_row_column : result_row)
  209. individual_result_as_json.append(result_row_column);
  210. query_results_model->add(move(individual_result_as_json));
  211. }
  212. m_action_tab_widget->set_fixed_height(200);
  213. };
  214. }
  215. void MainWidget::initialize_menu(GUI::Window* window)
  216. {
  217. auto& file_menu = window->add_menu("&File");
  218. file_menu.add_action(*m_new_action);
  219. file_menu.add_action(*m_open_action);
  220. file_menu.add_action(*m_save_action);
  221. file_menu.add_action(*m_save_as_action);
  222. file_menu.add_action(*m_save_all_action);
  223. file_menu.add_separator();
  224. file_menu.add_action(GUI::CommonActions::make_quit_action([](auto&) {
  225. GUI::Application::the()->quit();
  226. }));
  227. auto& edit_menu = window->add_menu("&Edit");
  228. edit_menu.add_action(*m_copy_action);
  229. edit_menu.add_action(*m_cut_action);
  230. edit_menu.add_action(*m_paste_action);
  231. edit_menu.add_separator();
  232. edit_menu.add_action(*m_undo_action);
  233. edit_menu.add_action(*m_redo_action);
  234. edit_menu.add_separator();
  235. edit_menu.add_action(*m_run_script_action);
  236. auto& help_menu = window->add_menu("&Help");
  237. help_menu.add_action(GUI::CommonActions::make_command_palette_action(window));
  238. help_menu.add_action(GUI::CommonActions::make_help_action([](auto&) {
  239. Desktop::Launcher::open(URL::create_with_file_scheme("/usr/share/man/man1/SQLStudio.md"), "/bin/Help");
  240. }));
  241. help_menu.add_action(GUI::CommonActions::make_about_action("SQL Studio", GUI::Icon::default_icon("app-sql-studio"sv), window));
  242. }
  243. void MainWidget::open_new_script()
  244. {
  245. auto new_script_name = DeprecatedString::formatted("New Script - {}", m_new_script_counter);
  246. ++m_new_script_counter;
  247. auto& editor = m_tab_widget->add_tab<ScriptEditor>(new_script_name);
  248. editor.new_script_with_temp_name(new_script_name);
  249. editor.on_cursor_change = [this] { on_editor_change(); };
  250. editor.on_selection_change = [this] { on_editor_change(); };
  251. editor.on_highlighter_change = [this] { on_editor_change(); };
  252. m_tab_widget->set_active_widget(&editor);
  253. }
  254. void MainWidget::open_script_from_file(LexicalPath const& file_path)
  255. {
  256. auto& editor = m_tab_widget->add_tab<ScriptEditor>(file_path.title());
  257. auto maybe_error = editor.open_script_from_file(file_path);
  258. if (maybe_error.is_error()) {
  259. GUI::MessageBox::show_error(window(), DeprecatedString::formatted("Failed to open {}\n{}", file_path, maybe_error.release_error()));
  260. return;
  261. }
  262. editor.on_cursor_change = [this] { on_editor_change(); };
  263. editor.on_selection_change = [this] { on_editor_change(); };
  264. editor.on_highlighter_change = [this] { on_editor_change(); };
  265. m_tab_widget->set_active_widget(&editor);
  266. }
  267. void MainWidget::open_database_from_file(LexicalPath const&)
  268. {
  269. TODO();
  270. }
  271. bool MainWidget::request_close()
  272. {
  273. auto any_scripts_modified { false };
  274. auto is_script_modified = [&](auto& child) {
  275. auto editor = dynamic_cast<ScriptEditor*>(&child);
  276. if (!editor)
  277. return IterationDecision::Continue;
  278. if (editor->document().is_modified()) {
  279. any_scripts_modified = true;
  280. return IterationDecision::Break;
  281. }
  282. return IterationDecision::Continue;
  283. };
  284. m_tab_widget->for_each_child_widget(is_script_modified);
  285. if (!any_scripts_modified)
  286. return true;
  287. auto result = GUI::MessageBox::ask_about_unsaved_changes(window(), {});
  288. switch (result) {
  289. case GUI::Dialog::ExecResult::Yes:
  290. break;
  291. case GUI::Dialog::ExecResult::No:
  292. return true;
  293. default:
  294. return false;
  295. }
  296. m_save_all_action->activate();
  297. any_scripts_modified = false;
  298. m_tab_widget->for_each_child_widget(is_script_modified);
  299. return !any_scripts_modified;
  300. }
  301. void MainWidget::update_title()
  302. {
  303. auto editor = dynamic_cast<ScriptEditor*>(m_tab_widget->active_widget());
  304. if (editor) {
  305. window()->set_title(DeprecatedString::formatted("{} - SQL Studio", editor->name()));
  306. } else {
  307. window()->set_title("SQL Studio");
  308. }
  309. }
  310. void MainWidget::on_editor_change()
  311. {
  312. auto editor = dynamic_cast<ScriptEditor*>(m_tab_widget->active_widget());
  313. update_statusbar(editor);
  314. update_editor_actions(editor);
  315. }
  316. void MainWidget::update_statusbar(ScriptEditor* editor)
  317. {
  318. if (!editor) {
  319. m_statusbar->set_text(1, "");
  320. m_statusbar->set_text(2, "");
  321. return;
  322. }
  323. if (editor->has_selection()) {
  324. auto character_count = editor->selected_text().length();
  325. auto word_count = editor->number_of_selected_words();
  326. m_statusbar->set_text(1, DeprecatedString::formatted("{} {} ({} {}) selected", character_count, character_count == 1 ? "character" : "characters", word_count, word_count == 1 ? "word" : "words"));
  327. } else {
  328. auto character_count = editor->text().length();
  329. auto word_count = editor->number_of_words();
  330. m_statusbar->set_text(1, DeprecatedString::formatted("{} {} ({} {})", character_count, character_count == 1 ? "character" : "characters", word_count, word_count == 1 ? "word" : "words"));
  331. }
  332. m_statusbar->set_text(2, DeprecatedString::formatted("Ln {}, Col {}", editor->cursor().line() + 1, editor->cursor().column()));
  333. }
  334. void MainWidget::update_editor_actions(ScriptEditor* editor)
  335. {
  336. if (!editor) {
  337. m_copy_action->set_enabled(false);
  338. m_cut_action->set_enabled(false);
  339. m_paste_action->set_enabled(false);
  340. m_undo_action->set_enabled(false);
  341. m_redo_action->set_enabled(false);
  342. return;
  343. }
  344. m_copy_action->set_enabled(editor->copy_action().is_enabled());
  345. m_cut_action->set_enabled(editor->cut_action().is_enabled());
  346. m_paste_action->set_enabled(editor->paste_action().is_enabled());
  347. m_undo_action->set_enabled(editor->undo_action().is_enabled());
  348. m_redo_action->set_enabled(editor->redo_action().is_enabled());
  349. }
  350. void MainWidget::drag_enter_event(GUI::DragEvent& event)
  351. {
  352. auto const& mime_types = event.mime_types();
  353. if (mime_types.contains_slow("text/uri-list"))
  354. event.accept();
  355. }
  356. void MainWidget::drop_event(GUI::DropEvent& drop_event)
  357. {
  358. drop_event.accept();
  359. window()->move_to_front();
  360. if (drop_event.mime_data().has_urls()) {
  361. auto urls = drop_event.mime_data().urls();
  362. if (urls.is_empty())
  363. return;
  364. for (auto& url : urls) {
  365. auto& scheme = url.scheme();
  366. if (!scheme.equals_ignoring_case("file"sv))
  367. continue;
  368. auto lexical_path = LexicalPath(url.path());
  369. if (lexical_path.extension().equals_ignoring_case("sql"sv))
  370. open_script_from_file(lexical_path);
  371. if (lexical_path.extension().equals_ignoring_case("db"sv))
  372. open_database_from_file(lexical_path);
  373. }
  374. }
  375. }
  376. DeprecatedString MainWidget::read_next_sql_statement_of_editor()
  377. {
  378. StringBuilder piece;
  379. do {
  380. if (!piece.is_empty())
  381. piece.append('\n');
  382. auto line_maybe = read_next_line_of_editor();
  383. if (!line_maybe.has_value())
  384. return {};
  385. auto& line = line_maybe.value();
  386. auto lexer = SQL::AST::Lexer(line);
  387. piece.append(line);
  388. bool is_first_token = true;
  389. bool is_command = false;
  390. bool last_token_ended_statement = false;
  391. bool tokens_found = false;
  392. for (SQL::AST::Token token = lexer.next(); token.type() != SQL::AST::TokenType::Eof; token = lexer.next()) {
  393. tokens_found = true;
  394. switch (token.type()) {
  395. case SQL::AST::TokenType::ParenOpen:
  396. ++m_editor_line_level;
  397. break;
  398. case SQL::AST::TokenType::ParenClose:
  399. --m_editor_line_level;
  400. break;
  401. case SQL::AST::TokenType::SemiColon:
  402. last_token_ended_statement = true;
  403. break;
  404. case SQL::AST::TokenType::Period:
  405. if (is_first_token)
  406. is_command = true;
  407. break;
  408. default:
  409. last_token_ended_statement = is_command;
  410. break;
  411. }
  412. is_first_token = false;
  413. }
  414. if (tokens_found)
  415. m_editor_line_level = last_token_ended_statement ? 0 : (m_editor_line_level > 0 ? m_editor_line_level : 1);
  416. } while ((m_editor_line_level > 0) || piece.is_empty());
  417. if (auto statement_id = m_sql_client->prepare_statement(m_connection_id, piece.to_deprecated_string()); statement_id.has_value())
  418. m_sql_client->async_execute_statement(*statement_id, {});
  419. return piece.to_deprecated_string();
  420. }
  421. Optional<DeprecatedString> MainWidget::read_next_line_of_editor()
  422. {
  423. auto editor = dynamic_cast<ScriptEditor*>(m_tab_widget->active_widget());
  424. if (!editor)
  425. return {};
  426. if (m_current_line_for_parsing < editor->document().line_count()) {
  427. DeprecatedString result = editor->document().line(m_current_line_for_parsing).to_utf8();
  428. m_current_line_for_parsing++;
  429. return result;
  430. } else {
  431. return {};
  432. }
  433. }
  434. }