MainWidget.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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(), 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"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(), 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. 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](int, bool, int, int, int) {
  191. read_next_sql_statement_of_editor();
  192. };
  193. m_sql_client->on_next_result = [this](int, Vector<String> const& row) {
  194. m_results.append(row);
  195. };
  196. m_sql_client->on_results_exhausted = [this](int, int) {
  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(String::formatted("column_{}", i + 1), String::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_help_action([](auto&) {
  238. Desktop::Launcher::open(URL::create_with_file_protocol("/usr/share/man/man1/SQLStudio.md"), "/bin/Help");
  239. }));
  240. help_menu.add_action(GUI::CommonActions::make_about_action("SQL Studio", GUI::Icon::default_icon("app-sql-studio"sv), window));
  241. }
  242. void MainWidget::open_new_script()
  243. {
  244. auto new_script_name = String::formatted("New Script - {}", m_new_script_counter);
  245. ++m_new_script_counter;
  246. auto& editor = m_tab_widget->add_tab<ScriptEditor>(new_script_name);
  247. editor.new_script_with_temp_name(new_script_name);
  248. editor.on_cursor_change = [this] { on_editor_change(); };
  249. editor.on_selection_change = [this] { on_editor_change(); };
  250. editor.on_highlighter_change = [this] { on_editor_change(); };
  251. m_tab_widget->set_active_widget(&editor);
  252. }
  253. void MainWidget::open_script_from_file(LexicalPath const& file_path)
  254. {
  255. auto& editor = m_tab_widget->add_tab<ScriptEditor>(file_path.title());
  256. auto maybe_error = editor.open_script_from_file(file_path);
  257. if (maybe_error.is_error()) {
  258. GUI::MessageBox::show_error(window(), String::formatted("Failed to open {}\n{}", file_path, maybe_error.release_error()));
  259. return;
  260. }
  261. editor.on_cursor_change = [this] { on_editor_change(); };
  262. editor.on_selection_change = [this] { on_editor_change(); };
  263. editor.on_highlighter_change = [this] { on_editor_change(); };
  264. m_tab_widget->set_active_widget(&editor);
  265. }
  266. void MainWidget::open_database_from_file(LexicalPath const&)
  267. {
  268. TODO();
  269. }
  270. bool MainWidget::request_close()
  271. {
  272. auto any_scripts_modified { false };
  273. auto is_script_modified = [&](auto& child) {
  274. auto editor = dynamic_cast<ScriptEditor*>(&child);
  275. if (!editor)
  276. return IterationDecision::Continue;
  277. if (editor->document().is_modified()) {
  278. any_scripts_modified = true;
  279. return IterationDecision::Break;
  280. }
  281. return IterationDecision::Continue;
  282. };
  283. m_tab_widget->for_each_child_widget(is_script_modified);
  284. if (!any_scripts_modified)
  285. return true;
  286. auto result = GUI::MessageBox::ask_about_unsaved_changes(window(), {});
  287. switch (result) {
  288. case GUI::Dialog::ExecResult::Yes:
  289. break;
  290. case GUI::Dialog::ExecResult::No:
  291. return true;
  292. default:
  293. return false;
  294. }
  295. m_save_all_action->activate();
  296. any_scripts_modified = false;
  297. m_tab_widget->for_each_child_widget(is_script_modified);
  298. return !any_scripts_modified;
  299. }
  300. void MainWidget::update_title()
  301. {
  302. auto editor = dynamic_cast<ScriptEditor*>(m_tab_widget->active_widget());
  303. if (editor) {
  304. window()->set_title(String::formatted("{} - SQL Studio", editor->name()));
  305. } else {
  306. window()->set_title("SQL Studio");
  307. }
  308. }
  309. void MainWidget::on_editor_change()
  310. {
  311. auto editor = dynamic_cast<ScriptEditor*>(m_tab_widget->active_widget());
  312. update_statusbar(editor);
  313. update_editor_actions(editor);
  314. }
  315. void MainWidget::update_statusbar(ScriptEditor* editor)
  316. {
  317. if (!editor) {
  318. m_statusbar->set_text(1, "");
  319. m_statusbar->set_text(2, "");
  320. return;
  321. }
  322. if (editor->has_selection()) {
  323. auto character_count = editor->selected_text().length();
  324. auto word_count = editor->number_of_selected_words();
  325. m_statusbar->set_text(1, String::formatted("{} {} ({} {}) selected", character_count, character_count == 1 ? "character" : "characters", word_count, word_count == 1 ? "word" : "words"));
  326. } else {
  327. auto character_count = editor->text().length();
  328. auto word_count = editor->number_of_words();
  329. m_statusbar->set_text(1, String::formatted("{} {} ({} {})", character_count, character_count == 1 ? "character" : "characters", word_count, word_count == 1 ? "word" : "words"));
  330. }
  331. m_statusbar->set_text(2, String::formatted("Ln {}, Col {}", editor->cursor().line() + 1, editor->cursor().column()));
  332. }
  333. void MainWidget::update_editor_actions(ScriptEditor* editor)
  334. {
  335. if (!editor) {
  336. m_copy_action->set_enabled(false);
  337. m_cut_action->set_enabled(false);
  338. m_paste_action->set_enabled(false);
  339. m_undo_action->set_enabled(false);
  340. m_redo_action->set_enabled(false);
  341. return;
  342. }
  343. m_copy_action->set_enabled(editor->copy_action().is_enabled());
  344. m_cut_action->set_enabled(editor->cut_action().is_enabled());
  345. m_paste_action->set_enabled(editor->paste_action().is_enabled());
  346. m_undo_action->set_enabled(editor->undo_action().is_enabled());
  347. m_redo_action->set_enabled(editor->redo_action().is_enabled());
  348. }
  349. void MainWidget::drop_event(GUI::DropEvent& drop_event)
  350. {
  351. drop_event.accept();
  352. window()->move_to_front();
  353. if (drop_event.mime_data().has_urls()) {
  354. auto urls = drop_event.mime_data().urls();
  355. if (urls.is_empty())
  356. return;
  357. for (auto& url : urls) {
  358. auto& scheme = url.scheme();
  359. if (!scheme.equals_ignoring_case("file"sv))
  360. continue;
  361. auto lexical_path = LexicalPath(url.path());
  362. if (lexical_path.extension().equals_ignoring_case("sql"sv))
  363. open_script_from_file(lexical_path);
  364. if (lexical_path.extension().equals_ignoring_case("db"sv))
  365. open_database_from_file(lexical_path);
  366. }
  367. }
  368. }
  369. String MainWidget::read_next_sql_statement_of_editor()
  370. {
  371. StringBuilder piece;
  372. do {
  373. if (!piece.is_empty())
  374. piece.append('\n');
  375. auto line_maybe = read_next_line_of_editor();
  376. if (!line_maybe.has_value())
  377. return {};
  378. auto& line = line_maybe.value();
  379. auto lexer = SQL::AST::Lexer(line);
  380. piece.append(line);
  381. bool is_first_token = true;
  382. bool is_command = false;
  383. bool last_token_ended_statement = false;
  384. bool tokens_found = false;
  385. for (SQL::AST::Token token = lexer.next(); token.type() != SQL::AST::TokenType::Eof; token = lexer.next()) {
  386. tokens_found = true;
  387. switch (token.type()) {
  388. case SQL::AST::TokenType::ParenOpen:
  389. ++m_editor_line_level;
  390. break;
  391. case SQL::AST::TokenType::ParenClose:
  392. --m_editor_line_level;
  393. break;
  394. case SQL::AST::TokenType::SemiColon:
  395. last_token_ended_statement = true;
  396. break;
  397. case SQL::AST::TokenType::Period:
  398. if (is_first_token)
  399. is_command = true;
  400. break;
  401. default:
  402. last_token_ended_statement = is_command;
  403. break;
  404. }
  405. is_first_token = false;
  406. }
  407. if (tokens_found)
  408. m_editor_line_level = last_token_ended_statement ? 0 : (m_editor_line_level > 0 ? m_editor_line_level : 1);
  409. } while ((m_editor_line_level > 0) || piece.is_empty());
  410. auto statement_id = m_sql_client->sql_statement(m_connection_id, piece.to_string());
  411. m_sql_client->async_statement_execute(statement_id);
  412. return piece.to_string();
  413. }
  414. Optional<String> MainWidget::read_next_line_of_editor()
  415. {
  416. auto editor = dynamic_cast<ScriptEditor*>(m_tab_widget->active_widget());
  417. if (!editor)
  418. return {};
  419. if (m_current_line_for_parsing < editor->document().line_count()) {
  420. String result = editor->document().line(m_current_line_for_parsing).to_utf8();
  421. m_current_line_for_parsing++;
  422. return result;
  423. } else {
  424. return {};
  425. }
  426. }
  427. }