Editor.cpp 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include "Editor.h"
  27. #include "CppLexer.h"
  28. #include "EditorWrapper.h"
  29. #include <AK/FileSystemPath.h>
  30. #include <LibCore/DirIterator.h>
  31. #include <LibCore/File.h>
  32. #include <LibGUI/GApplication.h>
  33. #include <LibGUI/GPainter.h>
  34. #include <LibGUI/GScrollBar.h>
  35. #include <LibGUI/GWindow.h>
  36. #include <LibHTML/DOM/ElementFactory.h>
  37. #include <LibHTML/DOM/HTMLHeadElement.h>
  38. #include <LibHTML/DOM/Text.h>
  39. #include <LibHTML/HtmlView.h>
  40. #include <LibHTML/Parser/HTMLParser.h>
  41. #include <LibMarkdown/MDDocument.h>
  42. //#define EDITOR_DEBUG
  43. Editor::Editor(GUI::Widget* parent)
  44. : TextEditor(GUI::TextEditor::MultiLine, parent)
  45. {
  46. m_documentation_tooltip_window = GUI::Window::construct();
  47. m_documentation_tooltip_window->set_rect(0, 0, 500, 400);
  48. m_documentation_tooltip_window->set_window_type(GUI::WindowType::Tooltip);
  49. m_documentation_html_view = HtmlView::construct(nullptr);
  50. m_documentation_tooltip_window->set_main_widget(m_documentation_html_view);
  51. }
  52. Editor::~Editor()
  53. {
  54. }
  55. EditorWrapper& Editor::wrapper()
  56. {
  57. return static_cast<EditorWrapper&>(*parent());
  58. }
  59. const EditorWrapper& Editor::wrapper() const
  60. {
  61. return static_cast<const EditorWrapper&>(*parent());
  62. }
  63. void Editor::focusin_event(Core::Event& event)
  64. {
  65. wrapper().set_editor_has_focus({}, true);
  66. if (on_focus)
  67. on_focus();
  68. GUI::TextEditor::focusin_event(event);
  69. }
  70. void Editor::focusout_event(Core::Event& event)
  71. {
  72. wrapper().set_editor_has_focus({}, false);
  73. GUI::TextEditor::focusout_event(event);
  74. }
  75. void Editor::paint_event(GUI::PaintEvent& event)
  76. {
  77. GUI::TextEditor::paint_event(event);
  78. if (is_focused()) {
  79. GUI::Painter painter(*this);
  80. painter.add_clip_rect(event.rect());
  81. auto rect = frame_inner_rect();
  82. if (vertical_scrollbar().is_visible())
  83. rect.set_width(rect.width() - vertical_scrollbar().width());
  84. if (horizontal_scrollbar().is_visible())
  85. rect.set_height(rect.height() - horizontal_scrollbar().height());
  86. painter.draw_rect(rect, palette().selection());
  87. }
  88. }
  89. static HashMap<String, String>& man_paths()
  90. {
  91. static HashMap<String, String> paths;
  92. if (paths.is_empty()) {
  93. // FIXME: This should also search man3, possibly other places..
  94. Core::DirIterator it("/usr/share/man/man2", Core::DirIterator::Flags::SkipDots);
  95. while (it.has_next()) {
  96. auto path = String::format("/usr/share/man/man2/%s", it.next_path().characters());
  97. auto title = FileSystemPath(path).title();
  98. paths.set(title, path);
  99. }
  100. }
  101. return paths;
  102. }
  103. void Editor::show_documentation_tooltip_if_available(const String& hovered_token, const Gfx::Point& screen_location)
  104. {
  105. auto it = man_paths().find(hovered_token);
  106. if (it == man_paths().end()) {
  107. #ifdef EDITOR_DEBUG
  108. dbg() << "no man path for " << hovered_token;
  109. #endif
  110. m_documentation_tooltip_window->hide();
  111. return;
  112. }
  113. if (m_documentation_tooltip_window->is_visible() && hovered_token == m_last_parsed_token) {
  114. return;
  115. }
  116. #ifdef EDITOR_DEBUG
  117. dbg() << "opening " << it->value;
  118. #endif
  119. auto file = Core::File::construct(it->value);
  120. if (!file->open(Core::File::ReadOnly)) {
  121. dbg() << "failed to open " << it->value << " " << file->error_string();
  122. return;
  123. }
  124. MDDocument man_document;
  125. bool success = man_document.parse(file->read_all());
  126. if (!success) {
  127. dbg() << "failed to parse markdown";
  128. return;
  129. }
  130. auto html_text = man_document.render_to_html();
  131. auto html_document = parse_html_document(html_text);
  132. if (!html_document) {
  133. dbg() << "failed to parse HTML";
  134. return;
  135. }
  136. // FIXME: LibHTML needs a friendlier DOM manipulation API. Something like innerHTML :^)
  137. auto style_element = create_element(*html_document, "style");
  138. style_element->append_child(adopt(*new Text(*html_document, "body { background-color: #dac7b5; }")));
  139. // FIXME: This const_cast should not be necessary.
  140. auto* head_element = const_cast<HTMLHeadElement*>(html_document->head());
  141. ASSERT(head_element);
  142. head_element->append_child(style_element);
  143. m_documentation_html_view->set_document(html_document);
  144. m_documentation_tooltip_window->move_to(screen_location.translated(4, 4));
  145. m_documentation_tooltip_window->show();
  146. m_last_parsed_token = hovered_token;
  147. }
  148. void Editor::mousemove_event(GUI::MouseEvent& event)
  149. {
  150. GUI::TextEditor::mousemove_event(event);
  151. if (document().spans().is_empty())
  152. return;
  153. auto text_position = text_position_at(event.position());
  154. if (!text_position.is_valid()) {
  155. GUI::Application::the().hide_tooltip();
  156. return;
  157. }
  158. for (auto& span : document().spans()) {
  159. if (span.range.contains(text_position)) {
  160. auto adjusted_range = span.range;
  161. adjusted_range.end().set_column(adjusted_range.end().column() + 1);
  162. auto hovered_span_text = document().text_in_range(adjusted_range);
  163. #ifdef EDITOR_DEBUG
  164. dbg() << "Hovering: " << adjusted_range << " \"" << hovered_span_text << "\"";
  165. #endif
  166. show_documentation_tooltip_if_available(hovered_span_text, event.position().translated(screen_relative_rect().location()));
  167. return;
  168. }
  169. }
  170. GUI::Application::the().hide_tooltip();
  171. }
  172. void Editor::highlight_matching_token_pair()
  173. {
  174. enum class Direction {
  175. Forward,
  176. Backward,
  177. };
  178. auto find_span_of_type = [&](int i, CppToken::Type type, CppToken::Type not_type, Direction direction) {
  179. int nesting_level = 0;
  180. bool forward = direction == Direction::Forward;
  181. for (forward ? ++i : --i; forward ? (i < document().spans().size()) : (i >= 0); forward ? ++i : --i) {
  182. auto& span = document().spans().at(i);
  183. auto span_token_type = (CppToken::Type)((uintptr_t)span.data);
  184. if (span_token_type == not_type) {
  185. ++nesting_level;
  186. } else if (span_token_type == type) {
  187. if (nesting_level-- <= 0)
  188. return i;
  189. }
  190. }
  191. return -1;
  192. };
  193. auto make_buddies = [&](int index0, int index1) {
  194. auto& buddy0 = const_cast<GUI::TextDocumentSpan&>(document().spans()[index0]);
  195. auto& buddy1 = const_cast<GUI::TextDocumentSpan&>(document().spans()[index1]);
  196. m_has_brace_buddies = true;
  197. m_brace_buddies[0].index = index0;
  198. m_brace_buddies[1].index = index1;
  199. m_brace_buddies[0].span_backup = buddy0;
  200. m_brace_buddies[1].span_backup = buddy1;
  201. buddy0.background_color = Color::DarkCyan;
  202. buddy1.background_color = Color::DarkCyan;
  203. buddy0.color = Color::White;
  204. buddy1.color = Color::White;
  205. update();
  206. };
  207. struct MatchingTokenPair {
  208. CppToken::Type open;
  209. CppToken::Type close;
  210. };
  211. MatchingTokenPair pairs[] = {
  212. { CppToken::Type::LeftCurly, CppToken::Type::RightCurly },
  213. { CppToken::Type::LeftParen, CppToken::Type::RightParen },
  214. { CppToken::Type::LeftBracket, CppToken::Type::RightBracket },
  215. };
  216. for (int i = 0; i < document().spans().size(); ++i) {
  217. auto& span = const_cast<GUI::TextDocumentSpan&>(document().spans().at(i));
  218. auto token_type = (CppToken::Type)((uintptr_t)span.data);
  219. for (auto& pair : pairs) {
  220. if (token_type == pair.open && span.range.start() == cursor()) {
  221. auto buddy = find_span_of_type(i, pair.close, pair.open, Direction::Forward);
  222. if (buddy != -1)
  223. make_buddies(i, buddy);
  224. return;
  225. }
  226. }
  227. auto right_of_end = span.range.end();
  228. right_of_end.set_column(right_of_end.column() + 1);
  229. for (auto& pair : pairs) {
  230. if (token_type == pair.close && right_of_end == cursor()) {
  231. auto buddy = find_span_of_type(i, pair.open, pair.close, Direction::Backward);
  232. if (buddy != -1)
  233. make_buddies(i, buddy);
  234. return;
  235. }
  236. }
  237. }
  238. }
  239. void Editor::cursor_did_change()
  240. {
  241. if (m_has_brace_buddies) {
  242. if (m_brace_buddies[0].index >= 0 && m_brace_buddies[0].index < document().spans().size())
  243. document().set_span_at_index(m_brace_buddies[0].index, m_brace_buddies[0].span_backup);
  244. if (m_brace_buddies[1].index >= 0 && m_brace_buddies[1].index < document().spans().size())
  245. document().set_span_at_index(m_brace_buddies[1].index, m_brace_buddies[1].span_backup);
  246. m_has_brace_buddies = false;
  247. update();
  248. }
  249. highlight_matching_token_pair();
  250. }
  251. void Editor::notify_did_rehighlight()
  252. {
  253. m_has_brace_buddies = false;
  254. highlight_matching_token_pair();
  255. }