MainWidget.cpp 20 KB

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