MainWidget.cpp 18 KB

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