MainWidget.cpp 18 KB

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