MainWidget.cpp 20 KB

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