MainWidget.cpp 18 KB

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