MainWidget.cpp 20 KB

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