MainWidget.cpp 18 KB

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