MainWidget.cpp 19 KB

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