Editor.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  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 "Debugger/Debugger.h"
  28. #include "EditorWrapper.h"
  29. #include "HackStudio.h"
  30. #include "Language.h"
  31. #include <AK/ByteBuffer.h>
  32. #include <AK/LexicalPath.h>
  33. #include <LibCore/DirIterator.h>
  34. #include <LibCore/File.h>
  35. #include <LibGUI/Application.h>
  36. #include <LibGUI/CppSyntaxHighlighter.h>
  37. #include <LibGUI/GMLSyntaxHighlighter.h>
  38. #include <LibGUI/INISyntaxHighlighter.h>
  39. #include <LibGUI/JSSyntaxHighlighter.h>
  40. #include <LibGUI/Label.h>
  41. #include <LibGUI/Painter.h>
  42. #include <LibGUI/ScrollBar.h>
  43. #include <LibGUI/ShellSyntaxHighlighter.h>
  44. #include <LibGUI/SyntaxHighlighter.h>
  45. #include <LibGUI/Window.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 <fcntl.h>
  52. // #define EDITOR_DEBUG
  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. #ifdef EDITOR_DEBUG
  142. dbgln("no man path for {}", hovered_token);
  143. #endif
  144. m_documentation_tooltip_window->hide();
  145. return;
  146. }
  147. if (m_documentation_tooltip_window->is_visible() && hovered_token == m_last_parsed_token) {
  148. return;
  149. }
  150. #ifdef EDITOR_DEBUG
  151. dbgln("opening {}", it->value);
  152. #endif
  153. auto file = Core::File::construct(it->value);
  154. if (!file->open(Core::File::ReadOnly)) {
  155. dbgln("failed to open {}, {}", it->value, file->error_string());
  156. return;
  157. }
  158. auto man_document = Markdown::Document::parse(file->read_all());
  159. if (!man_document) {
  160. dbgln("failed to parse markdown");
  161. return;
  162. }
  163. StringBuilder html;
  164. // FIXME: With the InProcessWebView we used to manipulate the document body directly,
  165. // With OutOfProcessWebView this isn't possible (at the moment). The ideal solution
  166. // is probably to tweak Markdown::Document::render_to_html() so we can inject styles
  167. // into the rendered HTML easily.
  168. html.append(man_document->render_to_html());
  169. html.append("<style>body { background-color: #dac7b5; }</style>");
  170. m_documentation_page_view->load_html(html.build(), {});
  171. m_documentation_tooltip_window->move_to(screen_location.translated(4, 4));
  172. m_documentation_tooltip_window->show();
  173. m_last_parsed_token = hovered_token;
  174. }
  175. void Editor::mousemove_event(GUI::MouseEvent& event)
  176. {
  177. GUI::TextEditor::mousemove_event(event);
  178. if (document().spans().is_empty())
  179. return;
  180. auto text_position = text_position_at(event.position());
  181. if (!text_position.is_valid()) {
  182. m_documentation_tooltip_window->hide();
  183. return;
  184. }
  185. auto highlighter = wrapper().editor().syntax_highlighter();
  186. if (!highlighter)
  187. return;
  188. bool hide_tooltip = true;
  189. bool is_over_link = false;
  190. auto ruler_line_rect = ruler_content_rect(text_position.line());
  191. auto hovering_lines_ruler = (event.position().x() < ruler_line_rect.width());
  192. if (hovering_lines_ruler && !is_in_drag_select())
  193. set_override_cursor(Gfx::StandardCursor::Arrow);
  194. else if (m_hovering_editor)
  195. set_override_cursor(m_hovering_link && event.ctrl() ? Gfx::StandardCursor::Hand : Gfx::StandardCursor::IBeam);
  196. for (auto& span : document().spans()) {
  197. if (span.range.contains(m_previous_text_position) && !span.range.contains(text_position)) {
  198. if (highlighter->is_navigatable(span.data) && span.attributes.underline) {
  199. span.attributes.underline = false;
  200. wrapper().editor().update();
  201. }
  202. }
  203. if (span.range.contains(text_position)) {
  204. auto adjusted_range = span.range;
  205. auto end_line_length = document().line(span.range.end().line()).length();
  206. adjusted_range.end().set_column(min(end_line_length, adjusted_range.end().column() + 1));
  207. auto hovered_span_text = document().text_in_range(adjusted_range);
  208. #ifdef EDITOR_DEBUG
  209. dbgln("Hovering: {} \"{}\"", adjusted_range, hovered_span_text);
  210. #endif
  211. if (highlighter->is_navigatable(span.data)) {
  212. is_over_link = 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_link = is_over_link && (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::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::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. GUI::TextEditor::mousedown_event(event);
  259. return;
  260. }
  261. auto adjusted_range = span->range;
  262. adjusted_range.end().set_column(adjusted_range.end().column() + 1);
  263. auto span_text = document().text_in_range(adjusted_range);
  264. auto header_path = span_text.substring(1, span_text.length() - 2);
  265. #ifdef EDITOR_DEBUG
  266. dbgln("Ctrl+click: {} \"{}\"", adjusted_range, header_path);
  267. #endif
  268. navigate_to_include_if_available(header_path);
  269. return;
  270. }
  271. GUI::TextEditor::mousedown_event(event);
  272. }
  273. void Editor::enter_event(Core::Event& event)
  274. {
  275. m_hovering_editor = true;
  276. GUI::TextEditor::enter_event(event);
  277. }
  278. void Editor::leave_event(Core::Event& event)
  279. {
  280. m_hovering_editor = false;
  281. GUI::TextEditor::leave_event(event);
  282. }
  283. static HashMap<String, String>& include_paths()
  284. {
  285. static HashMap<String, String> paths;
  286. auto add_directory = [](String base, Optional<String> recursive, auto handle_directory) -> void {
  287. Core::DirIterator it(recursive.value_or(base), Core::DirIterator::Flags::SkipDots);
  288. while (it.has_next()) {
  289. auto path = it.next_full_path();
  290. if (!Core::File::is_directory(path)) {
  291. auto key = path.substring(base.length() + 1, path.length() - base.length() - 1);
  292. #ifdef EDITOR_DEBUG
  293. dbgln("Adding header \"{}\" in path \"{}\"", key, path);
  294. #endif
  295. paths.set(key, path);
  296. } else {
  297. handle_directory(base, path, handle_directory);
  298. }
  299. }
  300. };
  301. if (paths.is_empty()) {
  302. add_directory(".", {}, add_directory);
  303. add_directory("/usr/local/include", {}, add_directory);
  304. add_directory("/usr/local/include/c++/9.2.0", {}, add_directory);
  305. add_directory("/usr/include", {}, add_directory);
  306. }
  307. return paths;
  308. }
  309. void Editor::navigate_to_include_if_available(String path)
  310. {
  311. auto it = include_paths().find(path);
  312. if (it == include_paths().end()) {
  313. #ifdef EDITOR_DEBUG
  314. dbgln("no header {} found.", path);
  315. #endif
  316. return;
  317. }
  318. on_open(it->value);
  319. }
  320. void Editor::set_execution_position(size_t line_number)
  321. {
  322. code_document().set_execution_position(line_number);
  323. scroll_position_into_view({ line_number, 0 });
  324. update(breakpoint_icon_rect(line_number));
  325. }
  326. void Editor::clear_execution_position()
  327. {
  328. if (!execution_position().has_value()) {
  329. return;
  330. }
  331. size_t previous_position = execution_position().value();
  332. code_document().clear_execution_position();
  333. update(breakpoint_icon_rect(previous_position));
  334. }
  335. const Gfx::Bitmap& Editor::breakpoint_icon_bitmap()
  336. {
  337. static auto bitmap = Gfx::Bitmap::load_from_file("/res/icons/16x16/breakpoint.png");
  338. return *bitmap;
  339. }
  340. const Gfx::Bitmap& Editor::current_position_icon_bitmap()
  341. {
  342. static auto bitmap = Gfx::Bitmap::load_from_file("/res/icons/16x16/go-forward.png");
  343. return *bitmap;
  344. }
  345. const CodeDocument& Editor::code_document() const
  346. {
  347. const auto& doc = document();
  348. ASSERT(doc.is_code_document());
  349. return static_cast<const CodeDocument&>(doc);
  350. }
  351. CodeDocument& Editor::code_document()
  352. {
  353. return const_cast<CodeDocument&>(static_cast<const Editor&>(*this).code_document());
  354. }
  355. void Editor::set_document(GUI::TextDocument& doc)
  356. {
  357. ASSERT(doc.is_code_document());
  358. GUI::TextEditor::set_document(doc);
  359. set_override_cursor(Gfx::StandardCursor::IBeam);
  360. CodeDocument& code_document = static_cast<CodeDocument&>(doc);
  361. switch (code_document.language()) {
  362. case Language::Cpp:
  363. set_syntax_highlighter(make<GUI::CppSyntaxHighlighter>());
  364. m_language_client = get_language_client<LanguageClients::Cpp::ServerConnection>(project().root_path());
  365. break;
  366. case Language::GML:
  367. set_syntax_highlighter(make<GUI::GMLSyntaxHighlighter>());
  368. break;
  369. case Language::JavaScript:
  370. set_syntax_highlighter(make<GUI::JSSyntaxHighlighter>());
  371. break;
  372. case Language::Ini:
  373. set_syntax_highlighter(make<GUI::IniSyntaxHighlighter>());
  374. break;
  375. case Language::Shell:
  376. set_syntax_highlighter(make<GUI::ShellSyntaxHighlighter>());
  377. m_language_client = get_language_client<LanguageClients::Shell::ServerConnection>(project().root_path());
  378. break;
  379. default:
  380. set_syntax_highlighter(nullptr);
  381. }
  382. if (m_language_client) {
  383. set_autocomplete_provider(make<LanguageServerAidedAutocompleteProvider>(*m_language_client));
  384. dbgln("Opening {}", code_document.file_path());
  385. int fd = open(code_document.file_path().characters(), O_RDONLY | O_NOCTTY);
  386. if (fd < 0) {
  387. perror("open");
  388. return;
  389. }
  390. m_language_client->open_file(code_document.file_path(), fd);
  391. close(fd);
  392. }
  393. }
  394. Optional<Editor::AutoCompleteRequestData> Editor::get_autocomplete_request_data()
  395. {
  396. if (!wrapper().editor().m_language_client)
  397. return {};
  398. return Editor::AutoCompleteRequestData { cursor() };
  399. }
  400. void Editor::LanguageServerAidedAutocompleteProvider::provide_completions(Function<void(Vector<Entry>)> callback)
  401. {
  402. auto& editor = static_cast<Editor&>(*m_editor).wrapper().editor();
  403. auto data = editor.get_autocomplete_request_data();
  404. if (!data.has_value())
  405. callback({});
  406. m_language_client.on_autocomplete_suggestions = [callback = move(callback)](auto suggestions) {
  407. callback(suggestions);
  408. };
  409. m_language_client.request_autocomplete(
  410. editor.code_document().file_path(),
  411. data.value().position.line(),
  412. data.value().position.column());
  413. }
  414. void Editor::on_edit_action(const GUI::Command& command)
  415. {
  416. if (!m_language_client)
  417. return;
  418. if (command.is_insert_text()) {
  419. const GUI::InsertTextCommand& insert_command = static_cast<const GUI::InsertTextCommand&>(command);
  420. m_language_client->insert_text(
  421. code_document().file_path(),
  422. insert_command.text(),
  423. insert_command.range().start().line(),
  424. insert_command.range().start().column());
  425. return;
  426. }
  427. if (command.is_remove_text()) {
  428. const GUI::RemoveTextCommand& remove_command = static_cast<const GUI::RemoveTextCommand&>(command);
  429. m_language_client->remove_text(
  430. code_document().file_path(),
  431. remove_command.range().start().line(),
  432. remove_command.range().start().column(),
  433. remove_command.range().end().line(),
  434. remove_command.range().end().column());
  435. return;
  436. }
  437. ASSERT_NOT_REACHED();
  438. }
  439. void Editor::undo()
  440. {
  441. TextEditor::undo();
  442. flush_file_content_to_langauge_server();
  443. }
  444. void Editor::redo()
  445. {
  446. TextEditor::redo();
  447. flush_file_content_to_langauge_server();
  448. }
  449. void Editor::flush_file_content_to_langauge_server()
  450. {
  451. if (!m_language_client)
  452. return;
  453. m_language_client->set_file_content(
  454. code_document().file_path(),
  455. document().text());
  456. }
  457. }