MainWidget.cpp 20 KB

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