Editor.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. * 2018-2021, the SerenityOS developers
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include "Editor.h"
  8. #include "Debugger/Debugger.h"
  9. #include "Debugger/EvaluateExpressionDialog.h"
  10. #include "EditorWrapper.h"
  11. #include "HackStudio.h"
  12. #include "Language.h"
  13. #include <AK/ByteBuffer.h>
  14. #include <AK/Debug.h>
  15. #include <AK/LexicalPath.h>
  16. #include <LibCore/DirIterator.h>
  17. #include <LibCore/File.h>
  18. #include <LibCpp/SyntaxHighlighter.h>
  19. #include <LibGUI/Action.h>
  20. #include <LibGUI/Application.h>
  21. #include <LibGUI/GMLSyntaxHighlighter.h>
  22. #include <LibGUI/INISyntaxHighlighter.h>
  23. #include <LibGUI/Label.h>
  24. #include <LibGUI/MessageBox.h>
  25. #include <LibGUI/Painter.h>
  26. #include <LibGUI/Scrollbar.h>
  27. #include <LibGUI/Window.h>
  28. #include <LibJS/SyntaxHighlighter.h>
  29. #include <LibMarkdown/Document.h>
  30. #include <LibWeb/DOM/ElementFactory.h>
  31. #include <LibWeb/DOM/Text.h>
  32. #include <LibWeb/HTML/HTMLHeadElement.h>
  33. #include <LibWeb/OutOfProcessWebView.h>
  34. #include <Shell/SyntaxHighlighter.h>
  35. #include <fcntl.h>
  36. namespace HackStudio {
  37. Editor::Editor()
  38. {
  39. set_document(CodeDocument::create());
  40. m_documentation_tooltip_window = GUI::Window::construct();
  41. m_documentation_tooltip_window->set_rect(0, 0, 500, 400);
  42. m_documentation_tooltip_window->set_window_type(GUI::WindowType::Tooltip);
  43. m_documentation_page_view = m_documentation_tooltip_window->set_main_widget<Web::OutOfProcessWebView>();
  44. m_evaluate_expression_action = GUI::Action::create("Evaluate expression", { Mod_Ctrl, Key_E }, [this](auto&) {
  45. if (!execution_position().has_value()) {
  46. GUI::MessageBox::show(window(), "Program is not running", "Error", GUI::MessageBox::Type::Error);
  47. return;
  48. }
  49. auto dialog = EvaluateExpressionDialog::construct(window());
  50. dialog->exec();
  51. });
  52. m_move_execution_to_line_action = GUI::Action::create("Set execution point to line", [this](auto&) {
  53. if (!execution_position().has_value()) {
  54. GUI::MessageBox::show(window(), "Program must be paused", "Error", GUI::MessageBox::Type::Error);
  55. return;
  56. }
  57. auto success = Debugger::the().set_execution_position(currently_open_file(), cursor().line());
  58. if (success) {
  59. set_execution_position(cursor().line());
  60. } else {
  61. GUI::MessageBox::show(window(), "Failed to set execution position", "Error", GUI::MessageBox::Type::Error);
  62. }
  63. });
  64. add_custom_context_menu_action(*m_evaluate_expression_action);
  65. add_custom_context_menu_action(*m_move_execution_to_line_action);
  66. set_gutter_visible(true);
  67. }
  68. Editor::~Editor()
  69. {
  70. }
  71. EditorWrapper& Editor::wrapper()
  72. {
  73. return static_cast<EditorWrapper&>(*parent());
  74. }
  75. const EditorWrapper& Editor::wrapper() const
  76. {
  77. return static_cast<const EditorWrapper&>(*parent());
  78. }
  79. void Editor::focusin_event(GUI::FocusEvent& event)
  80. {
  81. wrapper().set_editor_has_focus({}, true);
  82. if (on_focus)
  83. on_focus();
  84. GUI::TextEditor::focusin_event(event);
  85. }
  86. void Editor::focusout_event(GUI::FocusEvent& event)
  87. {
  88. wrapper().set_editor_has_focus({}, false);
  89. GUI::TextEditor::focusout_event(event);
  90. }
  91. Gfx::IntRect Editor::gutter_icon_rect(size_t line_number) const
  92. {
  93. return gutter_content_rect(line_number).translated(ruler_width() + gutter_width() + frame_thickness(), -vertical_scrollbar().value());
  94. }
  95. void Editor::paint_event(GUI::PaintEvent& event)
  96. {
  97. GUI::TextEditor::paint_event(event);
  98. GUI::Painter painter(*this);
  99. if (is_focused()) {
  100. painter.add_clip_rect(event.rect());
  101. auto rect = frame_inner_rect();
  102. if (vertical_scrollbar().is_visible())
  103. rect.set_width(rect.width() - vertical_scrollbar().width());
  104. if (horizontal_scrollbar().is_visible())
  105. rect.set_height(rect.height() - horizontal_scrollbar().height());
  106. painter.draw_rect(rect, palette().selection());
  107. }
  108. if (gutter_visible()) {
  109. size_t first_visible_line = text_position_at(event.rect().top_left()).line();
  110. size_t last_visible_line = text_position_at(event.rect().bottom_right()).line();
  111. for (size_t line : breakpoint_lines()) {
  112. if (line < first_visible_line || line > last_visible_line) {
  113. continue;
  114. }
  115. const auto& icon = breakpoint_icon_bitmap();
  116. painter.blit(gutter_icon_rect(line).top_left(), icon, icon.rect());
  117. }
  118. if (execution_position().has_value()) {
  119. const auto& icon = current_position_icon_bitmap();
  120. painter.blit(gutter_icon_rect(execution_position().value()).top_left(), icon, icon.rect());
  121. }
  122. if (wrapper().git_repo()) {
  123. for (auto& hunk : wrapper().hunks()) {
  124. auto start_line = hunk.target_start_line;
  125. auto finish_line = start_line + hunk.added_lines.size();
  126. auto additions = hunk.added_lines.size();
  127. auto deletions = hunk.removed_lines.size();
  128. for (size_t line_offset = 0; line_offset < additions; line_offset++) {
  129. auto line = start_line + line_offset;
  130. if (line < first_visible_line || line > last_visible_line) {
  131. continue;
  132. }
  133. char const* sign = (line_offset < deletions) ? "!" : "+";
  134. painter.draw_text(gutter_icon_rect(line), sign, font(), Gfx::TextAlignment::Center);
  135. }
  136. if (additions < deletions) {
  137. auto deletions_line = min(finish_line, line_count() - 1);
  138. if (deletions_line <= last_visible_line) {
  139. painter.draw_text(gutter_icon_rect(deletions_line), "-", font(), Gfx::TextAlignment::Center);
  140. }
  141. }
  142. }
  143. }
  144. }
  145. }
  146. static HashMap<String, String>& man_paths()
  147. {
  148. static HashMap<String, String> paths;
  149. if (paths.is_empty()) {
  150. // FIXME: This should also search man3, possibly other places..
  151. Core::DirIterator it("/usr/share/man/man2", Core::DirIterator::Flags::SkipDots);
  152. while (it.has_next()) {
  153. auto path = it.next_full_path();
  154. auto title = LexicalPath(path).title();
  155. paths.set(title, path);
  156. }
  157. }
  158. return paths;
  159. }
  160. void Editor::show_documentation_tooltip_if_available(const String& hovered_token, const Gfx::IntPoint& screen_location)
  161. {
  162. auto it = man_paths().find(hovered_token);
  163. if (it == man_paths().end()) {
  164. dbgln_if(EDITOR_DEBUG, "no man path for {}", hovered_token);
  165. m_documentation_tooltip_window->hide();
  166. return;
  167. }
  168. if (m_documentation_tooltip_window->is_visible() && hovered_token == m_last_parsed_token) {
  169. return;
  170. }
  171. dbgln_if(EDITOR_DEBUG, "opening {}", it->value);
  172. auto file = Core::File::construct(it->value);
  173. if (!file->open(Core::OpenMode::ReadOnly)) {
  174. dbgln("failed to open {}, {}", it->value, file->error_string());
  175. return;
  176. }
  177. auto man_document = Markdown::Document::parse(file->read_all());
  178. if (!man_document) {
  179. dbgln("failed to parse markdown");
  180. return;
  181. }
  182. StringBuilder html;
  183. // FIXME: With the InProcessWebView we used to manipulate the document body directly,
  184. // With OutOfProcessWebView this isn't possible (at the moment). The ideal solution
  185. // is probably to tweak Markdown::Document::render_to_html() so we can inject styles
  186. // into the rendered HTML easily.
  187. html.append(man_document->render_to_html());
  188. html.append("<style>body { background-color: #dac7b5; }</style>");
  189. m_documentation_page_view->load_html(html.build(), {});
  190. m_documentation_tooltip_window->move_to(screen_location.translated(4, 4));
  191. m_documentation_tooltip_window->show();
  192. m_last_parsed_token = hovered_token;
  193. }
  194. void Editor::mousemove_event(GUI::MouseEvent& event)
  195. {
  196. GUI::TextEditor::mousemove_event(event);
  197. if (document().spans().is_empty())
  198. return;
  199. auto text_position = text_position_at(event.position());
  200. if (!text_position.is_valid()) {
  201. m_documentation_tooltip_window->hide();
  202. return;
  203. }
  204. auto highlighter = wrapper().editor().syntax_highlighter();
  205. if (!highlighter)
  206. return;
  207. bool hide_tooltip = true;
  208. bool is_over_clickable = false;
  209. auto ruler_line_rect = ruler_content_rect(text_position.line());
  210. auto hovering_lines_ruler = (event.position().x() < ruler_line_rect.width());
  211. if (hovering_lines_ruler && !is_in_drag_select())
  212. set_override_cursor(Gfx::StandardCursor::Arrow);
  213. else if (m_hovering_editor)
  214. set_override_cursor(m_hovering_clickable && event.ctrl() ? Gfx::StandardCursor::Hand : Gfx::StandardCursor::IBeam);
  215. for (auto& span : document().spans()) {
  216. bool is_clickable = (highlighter->is_navigatable(span.data) || highlighter->is_identifier(span.data));
  217. if (span.range.contains(m_previous_text_position) && !span.range.contains(text_position)) {
  218. if (is_clickable && span.attributes.underline) {
  219. span.attributes.underline = false;
  220. wrapper().editor().update();
  221. }
  222. }
  223. if (span.range.contains(text_position)) {
  224. auto adjusted_range = span.range;
  225. auto end_line_length = document().line(span.range.end().line()).length();
  226. adjusted_range.end().set_column(min(end_line_length, adjusted_range.end().column() + 1));
  227. auto hovered_span_text = document().text_in_range(adjusted_range);
  228. dbgln_if(EDITOR_DEBUG, "Hovering: {} \"{}\"", adjusted_range, hovered_span_text);
  229. if (is_clickable) {
  230. is_over_clickable = true;
  231. bool was_underlined = span.attributes.underline;
  232. span.attributes.underline = event.modifiers() & Mod_Ctrl;
  233. if (span.attributes.underline != was_underlined) {
  234. wrapper().editor().update();
  235. }
  236. }
  237. if (highlighter->is_identifier(span.data)) {
  238. show_documentation_tooltip_if_available(hovered_span_text, event.position().translated(screen_relative_rect().location()));
  239. hide_tooltip = false;
  240. }
  241. }
  242. }
  243. m_previous_text_position = text_position;
  244. if (hide_tooltip)
  245. m_documentation_tooltip_window->hide();
  246. m_hovering_clickable = (is_over_clickable) && (event.modifiers() & Mod_Ctrl);
  247. }
  248. void Editor::mousedown_event(GUI::MouseEvent& event)
  249. {
  250. auto highlighter = wrapper().editor().syntax_highlighter();
  251. if (!highlighter) {
  252. GUI::TextEditor::mousedown_event(event);
  253. return;
  254. }
  255. auto text_position = text_position_at(event.position());
  256. auto ruler_line_rect = ruler_content_rect(text_position.line());
  257. if (event.button() == GUI::MouseButton::Left && event.position().x() < ruler_line_rect.width()) {
  258. if (!breakpoint_lines().contains_slow(text_position.line())) {
  259. breakpoint_lines().append(text_position.line());
  260. Debugger::the().on_breakpoint_change(wrapper().filename_label().text(), text_position.line(), BreakpointChange::Added);
  261. } else {
  262. breakpoint_lines().remove_first_matching([&](size_t line) { return line == text_position.line(); });
  263. Debugger::the().on_breakpoint_change(wrapper().filename_label().text(), text_position.line(), BreakpointChange::Removed);
  264. }
  265. }
  266. if (!(event.modifiers() & Mod_Ctrl)) {
  267. GUI::TextEditor::mousedown_event(event);
  268. return;
  269. }
  270. if (!text_position.is_valid()) {
  271. GUI::TextEditor::mousedown_event(event);
  272. return;
  273. }
  274. if (auto* span = document().span_at(text_position)) {
  275. if (highlighter->is_navigatable(span->data)) {
  276. on_navigatable_link_click(*span);
  277. return;
  278. }
  279. if (highlighter->is_identifier(span->data)) {
  280. on_identifier_click(*span);
  281. return;
  282. }
  283. }
  284. GUI::TextEditor::mousedown_event(event);
  285. }
  286. void Editor::drop_event(GUI::DropEvent& event)
  287. {
  288. event.accept();
  289. window()->move_to_front();
  290. if (event.mime_data().has_urls()) {
  291. auto urls = event.mime_data().urls();
  292. if (urls.is_empty())
  293. return;
  294. if (urls.size() > 1) {
  295. GUI::MessageBox::show(window(), "HackStudio can only open one file at a time!", "One at a time please!", GUI::MessageBox::Type::Error);
  296. return;
  297. }
  298. open_file(urls.first().path());
  299. }
  300. }
  301. void Editor::enter_event(Core::Event& event)
  302. {
  303. m_hovering_editor = true;
  304. GUI::TextEditor::enter_event(event);
  305. }
  306. void Editor::leave_event(Core::Event& event)
  307. {
  308. m_hovering_editor = false;
  309. GUI::TextEditor::leave_event(event);
  310. }
  311. static HashMap<String, String>& include_paths()
  312. {
  313. static HashMap<String, String> paths;
  314. auto add_directory = [](String base, Optional<String> recursive, auto handle_directory) -> void {
  315. Core::DirIterator it(recursive.value_or(base), Core::DirIterator::Flags::SkipDots);
  316. while (it.has_next()) {
  317. auto path = it.next_full_path();
  318. if (!Core::File::is_directory(path)) {
  319. auto key = path.substring(base.length() + 1, path.length() - base.length() - 1);
  320. dbgln_if(EDITOR_DEBUG, "Adding header \"{}\" in path \"{}\"", key, path);
  321. paths.set(key, path);
  322. } else {
  323. handle_directory(base, path, handle_directory);
  324. }
  325. }
  326. };
  327. if (paths.is_empty()) {
  328. add_directory(".", {}, add_directory);
  329. add_directory("/usr/local/include", {}, add_directory);
  330. add_directory("/usr/local/include/c++/9.2.0", {}, add_directory);
  331. add_directory("/usr/include", {}, add_directory);
  332. }
  333. return paths;
  334. }
  335. void Editor::navigate_to_include_if_available(String path)
  336. {
  337. auto it = include_paths().find(path);
  338. if (it == include_paths().end()) {
  339. dbgln_if(EDITOR_DEBUG, "no header {} found.", path);
  340. return;
  341. }
  342. on_open(it->value);
  343. }
  344. void Editor::set_execution_position(size_t line_number)
  345. {
  346. code_document().set_execution_position(line_number);
  347. scroll_position_into_view({ line_number, 0 });
  348. update(gutter_icon_rect(line_number));
  349. }
  350. void Editor::clear_execution_position()
  351. {
  352. if (!execution_position().has_value()) {
  353. return;
  354. }
  355. size_t previous_position = execution_position().value();
  356. code_document().clear_execution_position();
  357. update(gutter_icon_rect(previous_position));
  358. }
  359. const Gfx::Bitmap& Editor::breakpoint_icon_bitmap()
  360. {
  361. static auto bitmap = Gfx::Bitmap::load_from_file("/res/icons/16x16/breakpoint.png");
  362. return *bitmap;
  363. }
  364. const Gfx::Bitmap& Editor::current_position_icon_bitmap()
  365. {
  366. static auto bitmap = Gfx::Bitmap::load_from_file("/res/icons/16x16/go-forward.png");
  367. return *bitmap;
  368. }
  369. const CodeDocument& Editor::code_document() const
  370. {
  371. const auto& doc = document();
  372. VERIFY(doc.is_code_document());
  373. return static_cast<const CodeDocument&>(doc);
  374. }
  375. CodeDocument& Editor::code_document()
  376. {
  377. return const_cast<CodeDocument&>(static_cast<const Editor&>(*this).code_document());
  378. }
  379. void Editor::set_document(GUI::TextDocument& doc)
  380. {
  381. if (has_document() && &document() == &doc)
  382. return;
  383. VERIFY(doc.is_code_document());
  384. GUI::TextEditor::set_document(doc);
  385. set_override_cursor(Gfx::StandardCursor::IBeam);
  386. auto& code_document = static_cast<CodeDocument&>(doc);
  387. set_syntax_highlighter_for(code_document);
  388. set_language_client_for(code_document);
  389. if (m_language_client) {
  390. set_autocomplete_provider(make<LanguageServerAidedAutocompleteProvider>(*m_language_client));
  391. // NOTE:
  392. // When a file is opened for the first time in HackStudio, its content is already synced with the filesystem.
  393. // Otherwise, if the file has already been opened before in some Editor instance, it should exist in the LanguageServer's
  394. // FileDB, and the LanguageServer should already have its up-to-date content.
  395. // So it's OK to just pass an fd here (rather than the TextDocument's content).
  396. int fd = open(code_document.file_path().characters(), O_RDONLY | O_NOCTTY);
  397. if (fd < 0) {
  398. perror("open");
  399. return;
  400. }
  401. m_language_client->open_file(code_document.file_path(), fd);
  402. close(fd);
  403. }
  404. }
  405. Optional<Editor::AutoCompleteRequestData> Editor::get_autocomplete_request_data()
  406. {
  407. if (!wrapper().editor().m_language_client)
  408. return {};
  409. return Editor::AutoCompleteRequestData { cursor() };
  410. }
  411. void Editor::LanguageServerAidedAutocompleteProvider::provide_completions(Function<void(Vector<Entry>)> callback)
  412. {
  413. auto& editor = static_cast<Editor&>(*m_editor).wrapper().editor();
  414. auto data = editor.get_autocomplete_request_data();
  415. if (!data.has_value())
  416. callback({});
  417. m_language_client.on_autocomplete_suggestions = [callback = move(callback)](auto suggestions) {
  418. callback(suggestions);
  419. };
  420. m_language_client.request_autocomplete(
  421. editor.code_document().file_path(),
  422. data.value().position.line(),
  423. data.value().position.column());
  424. }
  425. void Editor::will_execute(GUI::TextDocumentUndoCommand const& command)
  426. {
  427. if (!m_language_client)
  428. return;
  429. if (is<GUI::InsertTextCommand>(command)) {
  430. auto const& insert_command = static_cast<GUI::InsertTextCommand const&>(command);
  431. m_language_client->insert_text(
  432. code_document().file_path(),
  433. insert_command.text(),
  434. insert_command.range().start().line(),
  435. insert_command.range().start().column());
  436. return;
  437. }
  438. if (is<GUI::RemoveTextCommand>(command)) {
  439. auto const& remove_command = static_cast<GUI::RemoveTextCommand const&>(command);
  440. m_language_client->remove_text(
  441. code_document().file_path(),
  442. remove_command.range().start().line(),
  443. remove_command.range().start().column(),
  444. remove_command.range().end().line(),
  445. remove_command.range().end().column());
  446. return;
  447. }
  448. VERIFY_NOT_REACHED();
  449. }
  450. void Editor::undo()
  451. {
  452. TextEditor::undo();
  453. flush_file_content_to_langauge_server();
  454. }
  455. void Editor::redo()
  456. {
  457. TextEditor::redo();
  458. flush_file_content_to_langauge_server();
  459. }
  460. void Editor::flush_file_content_to_langauge_server()
  461. {
  462. if (!m_language_client)
  463. return;
  464. m_language_client->set_file_content(
  465. code_document().file_path(),
  466. document().text());
  467. }
  468. void Editor::on_navigatable_link_click(const GUI::TextDocumentSpan& span)
  469. {
  470. auto adjusted_range = span.range;
  471. adjusted_range.end().set_column(adjusted_range.end().column() + 1);
  472. auto span_text = document().text_in_range(adjusted_range);
  473. auto header_path = span_text.substring(1, span_text.length() - 2);
  474. dbgln_if(EDITOR_DEBUG, "Ctrl+click: {} \"{}\"", adjusted_range, header_path);
  475. navigate_to_include_if_available(header_path);
  476. }
  477. void Editor::on_identifier_click(const GUI::TextDocumentSpan& span)
  478. {
  479. if (!m_language_client)
  480. return;
  481. m_language_client->on_declaration_found = [this](const String& file, size_t line, size_t column) {
  482. HackStudio::open_file(file, line, column);
  483. };
  484. m_language_client->search_declaration(code_document().file_path(), span.range.start().line(), span.range.start().column());
  485. }
  486. void Editor::set_cursor(const GUI::TextPosition& a_position)
  487. {
  488. TextEditor::set_cursor(a_position);
  489. }
  490. void Editor::set_syntax_highlighter_for(const CodeDocument& document)
  491. {
  492. switch (document.language()) {
  493. case Language::Cpp:
  494. set_syntax_highlighter(make<Cpp::SyntaxHighlighter>());
  495. break;
  496. case Language::GML:
  497. set_syntax_highlighter(make<GUI::GMLSyntaxHighlighter>());
  498. break;
  499. case Language::JavaScript:
  500. set_syntax_highlighter(make<JS::SyntaxHighlighter>());
  501. break;
  502. case Language::Ini:
  503. set_syntax_highlighter(make<GUI::IniSyntaxHighlighter>());
  504. break;
  505. case Language::Shell:
  506. set_syntax_highlighter(make<Shell::SyntaxHighlighter>());
  507. break;
  508. default:
  509. set_syntax_highlighter({});
  510. }
  511. }
  512. void Editor::set_language_client_for(const CodeDocument& document)
  513. {
  514. if (m_language_client && m_language_client->language() == document.language())
  515. return;
  516. if (document.language() == Language::Cpp)
  517. m_language_client = get_language_client<LanguageClients::Cpp::ServerConnection>(project().root_path());
  518. if (document.language() == Language::Shell)
  519. m_language_client = get_language_client<LanguageClients::Shell::ServerConnection>(project().root_path());
  520. }
  521. }