Editor.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. * 2018-2021, the SerenityOS developers
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are met:
  8. *
  9. * 1. Redistributions of source code must retain the above copyright notice, this
  10. * list of conditions and the following disclaimer.
  11. *
  12. * 2. Redistributions in binary form must reproduce the above copyright notice,
  13. * this list of conditions and the following disclaimer in the documentation
  14. * and/or other materials provided with the distribution.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  17. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  18. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  20. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  21. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  22. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  23. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  24. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  25. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. #include "Editor.h"
  28. #include "Debugger/Debugger.h"
  29. #include "EditorWrapper.h"
  30. #include "HackStudio.h"
  31. #include "Language.h"
  32. #include <AK/ByteBuffer.h>
  33. #include <AK/Debug.h>
  34. #include <AK/LexicalPath.h>
  35. #include <LibCore/DirIterator.h>
  36. #include <LibCore/File.h>
  37. #include <LibCpp/SyntaxHighlighter.h>
  38. #include <LibGUI/Application.h>
  39. #include <LibGUI/GMLSyntaxHighlighter.h>
  40. #include <LibGUI/INISyntaxHighlighter.h>
  41. #include <LibGUI/Label.h>
  42. #include <LibGUI/Painter.h>
  43. #include <LibGUI/ScrollBar.h>
  44. #include <LibGUI/Window.h>
  45. #include <LibJS/SyntaxHighlighter.h>
  46. #include <LibMarkdown/Document.h>
  47. #include <LibWeb/DOM/ElementFactory.h>
  48. #include <LibWeb/DOM/Text.h>
  49. #include <LibWeb/HTML/HTMLHeadElement.h>
  50. #include <LibWeb/OutOfProcessWebView.h>
  51. #include <Shell/SyntaxHighlighter.h>
  52. #include <fcntl.h>
  53. namespace HackStudio {
  54. Editor::Editor()
  55. {
  56. set_document(CodeDocument::create());
  57. m_documentation_tooltip_window = GUI::Window::construct();
  58. m_documentation_tooltip_window->set_rect(0, 0, 500, 400);
  59. m_documentation_tooltip_window->set_window_type(GUI::WindowType::Tooltip);
  60. m_documentation_page_view = m_documentation_tooltip_window->set_main_widget<Web::OutOfProcessWebView>();
  61. }
  62. Editor::~Editor()
  63. {
  64. }
  65. EditorWrapper& Editor::wrapper()
  66. {
  67. return static_cast<EditorWrapper&>(*parent());
  68. }
  69. const EditorWrapper& Editor::wrapper() const
  70. {
  71. return static_cast<const EditorWrapper&>(*parent());
  72. }
  73. void Editor::focusin_event(GUI::FocusEvent& event)
  74. {
  75. wrapper().set_editor_has_focus({}, true);
  76. if (on_focus)
  77. on_focus();
  78. GUI::TextEditor::focusin_event(event);
  79. }
  80. void Editor::focusout_event(GUI::FocusEvent& event)
  81. {
  82. wrapper().set_editor_has_focus({}, false);
  83. GUI::TextEditor::focusout_event(event);
  84. }
  85. Gfx::IntRect Editor::breakpoint_icon_rect(size_t line_number) const
  86. {
  87. auto ruler_line_rect = ruler_content_rect(line_number);
  88. auto scroll_value = vertical_scrollbar().value();
  89. ruler_line_rect = ruler_line_rect.translated({ 0, -scroll_value });
  90. auto center = ruler_line_rect.center().translated({ ruler_line_rect.width() - 10, -line_spacing() - 3 });
  91. constexpr int size = 32;
  92. return { center.x() - size / 2, center.y() - size / 2, size, size };
  93. }
  94. void Editor::paint_event(GUI::PaintEvent& event)
  95. {
  96. GUI::TextEditor::paint_event(event);
  97. GUI::Painter painter(*this);
  98. if (is_focused()) {
  99. painter.add_clip_rect(event.rect());
  100. auto rect = frame_inner_rect();
  101. if (vertical_scrollbar().is_visible())
  102. rect.set_width(rect.width() - vertical_scrollbar().width());
  103. if (horizontal_scrollbar().is_visible())
  104. rect.set_height(rect.height() - horizontal_scrollbar().height());
  105. painter.draw_rect(rect, palette().selection());
  106. }
  107. if (ruler_visible()) {
  108. size_t first_visible_line = text_position_at(event.rect().top_left()).line();
  109. size_t last_visible_line = text_position_at(event.rect().bottom_right()).line();
  110. for (size_t line : breakpoint_lines()) {
  111. if (line < first_visible_line || line > last_visible_line) {
  112. continue;
  113. }
  114. const auto& icon = breakpoint_icon_bitmap();
  115. painter.blit(breakpoint_icon_rect(line).center(), icon, icon.rect());
  116. }
  117. if (execution_position().has_value()) {
  118. const auto& icon = current_position_icon_bitmap();
  119. painter.blit(breakpoint_icon_rect(execution_position().value()).center(), icon, icon.rect());
  120. }
  121. }
  122. }
  123. static HashMap<String, String>& man_paths()
  124. {
  125. static HashMap<String, String> paths;
  126. if (paths.is_empty()) {
  127. // FIXME: This should also search man3, possibly other places..
  128. Core::DirIterator it("/usr/share/man/man2", Core::DirIterator::Flags::SkipDots);
  129. while (it.has_next()) {
  130. auto path = String::formatted("/usr/share/man/man2/{}", it.next_path());
  131. auto title = LexicalPath(path).title();
  132. paths.set(title, path);
  133. }
  134. }
  135. return paths;
  136. }
  137. void Editor::show_documentation_tooltip_if_available(const String& hovered_token, const Gfx::IntPoint& screen_location)
  138. {
  139. auto it = man_paths().find(hovered_token);
  140. if (it == man_paths().end()) {
  141. dbgln_if(EDITOR_DEBUG, "no man path for {}", hovered_token);
  142. m_documentation_tooltip_window->hide();
  143. return;
  144. }
  145. if (m_documentation_tooltip_window->is_visible() && hovered_token == m_last_parsed_token) {
  146. return;
  147. }
  148. dbgln_if(EDITOR_DEBUG, "opening {}", it->value);
  149. auto file = Core::File::construct(it->value);
  150. if (!file->open(Core::File::ReadOnly)) {
  151. dbgln("failed to open {}, {}", it->value, file->error_string());
  152. return;
  153. }
  154. auto man_document = Markdown::Document::parse(file->read_all());
  155. if (!man_document) {
  156. dbgln("failed to parse markdown");
  157. return;
  158. }
  159. StringBuilder html;
  160. // FIXME: With the InProcessWebView we used to manipulate the document body directly,
  161. // With OutOfProcessWebView this isn't possible (at the moment). The ideal solution
  162. // is probably to tweak Markdown::Document::render_to_html() so we can inject styles
  163. // into the rendered HTML easily.
  164. html.append(man_document->render_to_html());
  165. html.append("<style>body { background-color: #dac7b5; }</style>");
  166. m_documentation_page_view->load_html(html.build(), {});
  167. m_documentation_tooltip_window->move_to(screen_location.translated(4, 4));
  168. m_documentation_tooltip_window->show();
  169. m_last_parsed_token = hovered_token;
  170. }
  171. void Editor::mousemove_event(GUI::MouseEvent& event)
  172. {
  173. GUI::TextEditor::mousemove_event(event);
  174. if (document().spans().is_empty())
  175. return;
  176. auto text_position = text_position_at(event.position());
  177. if (!text_position.is_valid()) {
  178. m_documentation_tooltip_window->hide();
  179. return;
  180. }
  181. auto highlighter = wrapper().editor().syntax_highlighter();
  182. if (!highlighter)
  183. return;
  184. bool hide_tooltip = true;
  185. bool is_over_clickable = false;
  186. auto ruler_line_rect = ruler_content_rect(text_position.line());
  187. auto hovering_lines_ruler = (event.position().x() < ruler_line_rect.width());
  188. if (hovering_lines_ruler && !is_in_drag_select())
  189. set_override_cursor(Gfx::StandardCursor::Arrow);
  190. else if (m_hovering_editor)
  191. set_override_cursor(m_hovering_clickable && event.ctrl() ? Gfx::StandardCursor::Hand : Gfx::StandardCursor::IBeam);
  192. for (auto& span : document().spans()) {
  193. bool is_clickable = (highlighter->is_navigatable(span.data) || highlighter->is_identifier(span.data));
  194. if (span.range.contains(m_previous_text_position) && !span.range.contains(text_position)) {
  195. if (is_clickable && span.attributes.underline) {
  196. span.attributes.underline = false;
  197. wrapper().editor().update();
  198. }
  199. }
  200. if (span.range.contains(text_position)) {
  201. auto adjusted_range = span.range;
  202. auto end_line_length = document().line(span.range.end().line()).length();
  203. adjusted_range.end().set_column(min(end_line_length, adjusted_range.end().column() + 1));
  204. auto hovered_span_text = document().text_in_range(adjusted_range);
  205. dbgln_if(EDITOR_DEBUG, "Hovering: {} \"{}\"", adjusted_range, hovered_span_text);
  206. if (is_clickable) {
  207. is_over_clickable = true;
  208. bool was_underlined = span.attributes.underline;
  209. span.attributes.underline = event.modifiers() & Mod_Ctrl;
  210. if (span.attributes.underline != was_underlined) {
  211. wrapper().editor().update();
  212. }
  213. }
  214. if (highlighter->is_identifier(span.data)) {
  215. show_documentation_tooltip_if_available(hovered_span_text, event.position().translated(screen_relative_rect().location()));
  216. hide_tooltip = false;
  217. }
  218. }
  219. }
  220. m_previous_text_position = text_position;
  221. if (hide_tooltip)
  222. m_documentation_tooltip_window->hide();
  223. m_hovering_clickable = (is_over_clickable) && (event.modifiers() & Mod_Ctrl);
  224. }
  225. void Editor::mousedown_event(GUI::MouseEvent& event)
  226. {
  227. auto highlighter = wrapper().editor().syntax_highlighter();
  228. if (!highlighter) {
  229. GUI::TextEditor::mousedown_event(event);
  230. return;
  231. }
  232. auto text_position = text_position_at(event.position());
  233. auto ruler_line_rect = ruler_content_rect(text_position.line());
  234. if (event.button() == GUI::MouseButton::Left && event.position().x() < ruler_line_rect.width()) {
  235. if (!breakpoint_lines().contains_slow(text_position.line())) {
  236. breakpoint_lines().append(text_position.line());
  237. Debugger::on_breakpoint_change(wrapper().filename_label().text(), text_position.line(), BreakpointChange::Added);
  238. } else {
  239. breakpoint_lines().remove_first_matching([&](size_t line) { return line == text_position.line(); });
  240. Debugger::on_breakpoint_change(wrapper().filename_label().text(), text_position.line(), BreakpointChange::Removed);
  241. }
  242. }
  243. if (!(event.modifiers() & Mod_Ctrl)) {
  244. GUI::TextEditor::mousedown_event(event);
  245. return;
  246. }
  247. if (!text_position.is_valid()) {
  248. GUI::TextEditor::mousedown_event(event);
  249. return;
  250. }
  251. if (auto* span = document().span_at(text_position)) {
  252. if (highlighter->is_navigatable(span->data)) {
  253. on_navigatable_link_click(*span);
  254. return;
  255. }
  256. if (highlighter->is_identifier(span->data)) {
  257. on_identifier_click(*span);
  258. return;
  259. }
  260. }
  261. GUI::TextEditor::mousedown_event(event);
  262. }
  263. void Editor::enter_event(Core::Event& event)
  264. {
  265. m_hovering_editor = true;
  266. GUI::TextEditor::enter_event(event);
  267. }
  268. void Editor::leave_event(Core::Event& event)
  269. {
  270. m_hovering_editor = false;
  271. GUI::TextEditor::leave_event(event);
  272. }
  273. static HashMap<String, String>& include_paths()
  274. {
  275. static HashMap<String, String> paths;
  276. auto add_directory = [](String base, Optional<String> recursive, auto handle_directory) -> void {
  277. Core::DirIterator it(recursive.value_or(base), Core::DirIterator::Flags::SkipDots);
  278. while (it.has_next()) {
  279. auto path = it.next_full_path();
  280. if (!Core::File::is_directory(path)) {
  281. auto key = path.substring(base.length() + 1, path.length() - base.length() - 1);
  282. dbgln_if(EDITOR_DEBUG, "Adding header \"{}\" in path \"{}\"", key, path);
  283. paths.set(key, path);
  284. } else {
  285. handle_directory(base, path, handle_directory);
  286. }
  287. }
  288. };
  289. if (paths.is_empty()) {
  290. add_directory(".", {}, add_directory);
  291. add_directory("/usr/local/include", {}, add_directory);
  292. add_directory("/usr/local/include/c++/9.2.0", {}, add_directory);
  293. add_directory("/usr/include", {}, add_directory);
  294. }
  295. return paths;
  296. }
  297. void Editor::navigate_to_include_if_available(String path)
  298. {
  299. auto it = include_paths().find(path);
  300. if (it == include_paths().end()) {
  301. dbgln_if(EDITOR_DEBUG, "no header {} found.", path);
  302. return;
  303. }
  304. on_open(it->value);
  305. }
  306. void Editor::set_execution_position(size_t line_number)
  307. {
  308. code_document().set_execution_position(line_number);
  309. scroll_position_into_view({ line_number, 0 });
  310. update(breakpoint_icon_rect(line_number));
  311. }
  312. void Editor::clear_execution_position()
  313. {
  314. if (!execution_position().has_value()) {
  315. return;
  316. }
  317. size_t previous_position = execution_position().value();
  318. code_document().clear_execution_position();
  319. update(breakpoint_icon_rect(previous_position));
  320. }
  321. const Gfx::Bitmap& Editor::breakpoint_icon_bitmap()
  322. {
  323. static auto bitmap = Gfx::Bitmap::load_from_file("/res/icons/16x16/breakpoint.png");
  324. return *bitmap;
  325. }
  326. const Gfx::Bitmap& Editor::current_position_icon_bitmap()
  327. {
  328. static auto bitmap = Gfx::Bitmap::load_from_file("/res/icons/16x16/go-forward.png");
  329. return *bitmap;
  330. }
  331. const CodeDocument& Editor::code_document() const
  332. {
  333. const auto& doc = document();
  334. ASSERT(doc.is_code_document());
  335. return static_cast<const CodeDocument&>(doc);
  336. }
  337. CodeDocument& Editor::code_document()
  338. {
  339. return const_cast<CodeDocument&>(static_cast<const Editor&>(*this).code_document());
  340. }
  341. void Editor::set_document(GUI::TextDocument& doc)
  342. {
  343. ASSERT(doc.is_code_document());
  344. GUI::TextEditor::set_document(doc);
  345. set_override_cursor(Gfx::StandardCursor::IBeam);
  346. CodeDocument& code_document = static_cast<CodeDocument&>(doc);
  347. switch (code_document.language()) {
  348. case Language::Cpp:
  349. set_syntax_highlighter(make<Cpp::SyntaxHighlighter>());
  350. m_language_client = get_language_client<LanguageClients::Cpp::ServerConnection>(project().root_path());
  351. break;
  352. case Language::GML:
  353. set_syntax_highlighter(make<GUI::GMLSyntaxHighlighter>());
  354. break;
  355. case Language::JavaScript:
  356. set_syntax_highlighter(make<JS::SyntaxHighlighter>());
  357. break;
  358. case Language::Ini:
  359. set_syntax_highlighter(make<GUI::IniSyntaxHighlighter>());
  360. break;
  361. case Language::Shell:
  362. set_syntax_highlighter(make<Shell::SyntaxHighlighter>());
  363. m_language_client = get_language_client<LanguageClients::Shell::ServerConnection>(project().root_path());
  364. break;
  365. default:
  366. set_syntax_highlighter({});
  367. }
  368. if (m_language_client) {
  369. set_autocomplete_provider(make<LanguageServerAidedAutocompleteProvider>(*m_language_client));
  370. int fd = open(code_document.file_path().characters(), O_RDONLY | O_NOCTTY);
  371. if (fd < 0) {
  372. perror("open");
  373. return;
  374. }
  375. m_language_client->open_file(code_document.file_path(), fd);
  376. close(fd);
  377. }
  378. }
  379. Optional<Editor::AutoCompleteRequestData> Editor::get_autocomplete_request_data()
  380. {
  381. if (!wrapper().editor().m_language_client)
  382. return {};
  383. return Editor::AutoCompleteRequestData { cursor() };
  384. }
  385. void Editor::LanguageServerAidedAutocompleteProvider::provide_completions(Function<void(Vector<Entry>)> callback)
  386. {
  387. auto& editor = static_cast<Editor&>(*m_editor).wrapper().editor();
  388. auto data = editor.get_autocomplete_request_data();
  389. if (!data.has_value())
  390. callback({});
  391. m_language_client.on_autocomplete_suggestions = [callback = move(callback)](auto suggestions) {
  392. callback(suggestions);
  393. };
  394. m_language_client.request_autocomplete(
  395. editor.code_document().file_path(),
  396. data.value().position.line(),
  397. data.value().position.column());
  398. }
  399. void Editor::on_edit_action(const GUI::Command& command)
  400. {
  401. if (!m_language_client)
  402. return;
  403. if (command.is_insert_text()) {
  404. const GUI::InsertTextCommand& insert_command = static_cast<const GUI::InsertTextCommand&>(command);
  405. m_language_client->insert_text(
  406. code_document().file_path(),
  407. insert_command.text(),
  408. insert_command.range().start().line(),
  409. insert_command.range().start().column());
  410. return;
  411. }
  412. if (command.is_remove_text()) {
  413. const GUI::RemoveTextCommand& remove_command = static_cast<const GUI::RemoveTextCommand&>(command);
  414. m_language_client->remove_text(
  415. code_document().file_path(),
  416. remove_command.range().start().line(),
  417. remove_command.range().start().column(),
  418. remove_command.range().end().line(),
  419. remove_command.range().end().column());
  420. return;
  421. }
  422. ASSERT_NOT_REACHED();
  423. }
  424. void Editor::undo()
  425. {
  426. TextEditor::undo();
  427. flush_file_content_to_langauge_server();
  428. }
  429. void Editor::redo()
  430. {
  431. TextEditor::redo();
  432. flush_file_content_to_langauge_server();
  433. }
  434. void Editor::flush_file_content_to_langauge_server()
  435. {
  436. if (!m_language_client)
  437. return;
  438. m_language_client->set_file_content(
  439. code_document().file_path(),
  440. document().text());
  441. }
  442. void Editor::on_navigatable_link_click(const GUI::TextDocumentSpan& span)
  443. {
  444. auto adjusted_range = span.range;
  445. adjusted_range.end().set_column(adjusted_range.end().column() + 1);
  446. auto span_text = document().text_in_range(adjusted_range);
  447. auto header_path = span_text.substring(1, span_text.length() - 2);
  448. dbgln_if(EDITOR_DEBUG, "Ctrl+click: {} \"{}\"", adjusted_range, header_path);
  449. navigate_to_include_if_available(header_path);
  450. }
  451. void Editor::open_and_set_cursor(const String& file, size_t line, size_t column)
  452. {
  453. if (code_document().file_path() != file)
  454. on_open(file);
  455. set_cursor(GUI::TextPosition { line, column });
  456. }
  457. void Editor::on_identifier_click(const GUI::TextDocumentSpan& span)
  458. {
  459. m_language_client->on_declaration_found = [this](const String& file, size_t line, size_t column) {
  460. open_and_set_cursor(file, line, column);
  461. };
  462. m_language_client->search_declaration(code_document().file_path(), span.range.start().line(), span.range.start().column());
  463. }
  464. }