Editor.cpp 19 KB

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