MainWidget.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  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. warnln("\033[33;1mCould not connect to:\033[0m {}", 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_next_result = [this](auto, auto, auto row) {
  212. m_results.append({});
  213. m_results.last().ensure_capacity(row.size());
  214. for (auto const& value : row)
  215. m_results.last().unchecked_append(value.to_deprecated_string());
  216. };
  217. m_sql_client->on_results_exhausted = [this](auto, auto, auto) {
  218. if (m_results.size() == 0)
  219. return;
  220. if (m_results[0].size() == 0)
  221. return;
  222. Vector<GUI::JsonArrayModel::FieldSpec> query_result_fields;
  223. for (size_t i = 0; i < m_results[0].size(); i++)
  224. query_result_fields.empend(DeprecatedString::formatted("column_{}", i + 1), DeprecatedString::formatted("Column {}", i + 1), Gfx::TextAlignment::CenterLeft);
  225. auto query_results_model = GUI::JsonArrayModel::create("{}", move(query_result_fields));
  226. m_query_results_table_view->set_model(MUST(GUI::SortingProxyModel::create(*query_results_model)));
  227. for (auto& result_row : m_results) {
  228. Vector<JsonValue> individual_result_as_json;
  229. for (auto& result_row_column : result_row)
  230. individual_result_as_json.append(result_row_column);
  231. query_results_model->add(move(individual_result_as_json));
  232. }
  233. m_action_tab_widget->set_fixed_height(200);
  234. };
  235. }
  236. void MainWidget::initialize_menu(GUI::Window* window)
  237. {
  238. auto& file_menu = window->add_menu("&File");
  239. file_menu.add_action(*m_new_action);
  240. file_menu.add_action(*m_open_action);
  241. file_menu.add_action(*m_save_action);
  242. file_menu.add_action(*m_save_as_action);
  243. file_menu.add_action(*m_save_all_action);
  244. file_menu.add_separator();
  245. file_menu.add_action(GUI::CommonActions::make_quit_action([](auto&) {
  246. GUI::Application::the()->quit();
  247. }));
  248. auto& edit_menu = window->add_menu("&Edit");
  249. edit_menu.add_action(*m_copy_action);
  250. edit_menu.add_action(*m_cut_action);
  251. edit_menu.add_action(*m_paste_action);
  252. edit_menu.add_separator();
  253. edit_menu.add_action(*m_undo_action);
  254. edit_menu.add_action(*m_redo_action);
  255. edit_menu.add_separator();
  256. edit_menu.add_action(*m_run_script_action);
  257. auto& help_menu = window->add_menu("&Help");
  258. help_menu.add_action(GUI::CommonActions::make_command_palette_action(window));
  259. help_menu.add_action(GUI::CommonActions::make_help_action([](auto&) {
  260. Desktop::Launcher::open(URL::create_with_file_scheme("/usr/share/man/man1/SQLStudio.md"), "/bin/Help");
  261. }));
  262. help_menu.add_action(GUI::CommonActions::make_about_action("SQL Studio", GUI::Icon::default_icon("app-sql-studio"sv), window));
  263. }
  264. void MainWidget::open_new_script()
  265. {
  266. auto new_script_name = DeprecatedString::formatted("New Script - {}", m_new_script_counter);
  267. ++m_new_script_counter;
  268. auto& editor = m_tab_widget->add_tab<ScriptEditor>(new_script_name);
  269. editor.new_script_with_temp_name(new_script_name);
  270. editor.on_cursor_change = [this] { on_editor_change(); };
  271. editor.on_selection_change = [this] { on_editor_change(); };
  272. editor.on_highlighter_change = [this] { on_editor_change(); };
  273. m_tab_widget->set_active_widget(&editor);
  274. }
  275. void MainWidget::open_script_from_file(LexicalPath const& file_path)
  276. {
  277. auto& editor = m_tab_widget->add_tab<ScriptEditor>(file_path.title());
  278. if (auto result = editor.open_script_from_file(file_path); result.is_error()) {
  279. GUI::MessageBox::show_error(window(), DeprecatedString::formatted("Failed to open {}\n{}", file_path, result.error()));
  280. return;
  281. }
  282. editor.on_cursor_change = [this] { on_editor_change(); };
  283. editor.on_selection_change = [this] { on_editor_change(); };
  284. editor.on_highlighter_change = [this] { on_editor_change(); };
  285. m_tab_widget->set_active_widget(&editor);
  286. }
  287. void MainWidget::open_database_from_file(LexicalPath const&)
  288. {
  289. TODO();
  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. if (lexical_path.extension().equals_ignoring_case("sql"sv))
  398. open_script_from_file(lexical_path);
  399. if (lexical_path.extension().equals_ignoring_case("db"sv))
  400. open_database_from_file(lexical_path);
  401. }
  402. }
  403. }
  404. void MainWidget::read_next_sql_statement_of_editor()
  405. {
  406. if (!m_connection_id.has_value())
  407. return;
  408. StringBuilder piece;
  409. do {
  410. if (!piece.is_empty())
  411. piece.append('\n');
  412. auto line_maybe = read_next_line_of_editor();
  413. if (!line_maybe.has_value())
  414. return;
  415. auto& line = line_maybe.value();
  416. auto lexer = SQL::AST::Lexer(line);
  417. piece.append(line);
  418. bool is_first_token = true;
  419. bool is_command = false;
  420. bool last_token_ended_statement = false;
  421. bool tokens_found = false;
  422. for (SQL::AST::Token token = lexer.next(); token.type() != SQL::AST::TokenType::Eof; token = lexer.next()) {
  423. tokens_found = true;
  424. switch (token.type()) {
  425. case SQL::AST::TokenType::ParenOpen:
  426. ++m_editor_line_level;
  427. break;
  428. case SQL::AST::TokenType::ParenClose:
  429. --m_editor_line_level;
  430. break;
  431. case SQL::AST::TokenType::SemiColon:
  432. last_token_ended_statement = true;
  433. break;
  434. case SQL::AST::TokenType::Period:
  435. if (is_first_token)
  436. is_command = true;
  437. break;
  438. default:
  439. last_token_ended_statement = is_command;
  440. break;
  441. }
  442. is_first_token = false;
  443. }
  444. if (tokens_found)
  445. m_editor_line_level = last_token_ended_statement ? 0 : (m_editor_line_level > 0 ? m_editor_line_level : 1);
  446. } while ((m_editor_line_level > 0) || piece.is_empty());
  447. auto sql_statement = piece.to_deprecated_string();
  448. if (auto statement_id = m_sql_client->prepare_statement(*m_connection_id, sql_statement); statement_id.has_value()) {
  449. m_sql_client->async_execute_statement(*statement_id, {});
  450. } else {
  451. auto* editor = active_editor();
  452. VERIFY(editor);
  453. GUI::MessageBox::show_error(window(), DeprecatedString::formatted("Could not parse {}\n{}", editor->path(), sql_statement));
  454. }
  455. }
  456. Optional<DeprecatedString> MainWidget::read_next_line_of_editor()
  457. {
  458. auto* editor = active_editor();
  459. if (!editor)
  460. return {};
  461. if (m_current_line_for_parsing >= editor->document().line_count())
  462. return {};
  463. auto result = editor->document().line(m_current_line_for_parsing).to_utf8();
  464. ++m_current_line_for_parsing;
  465. return result;
  466. }
  467. }