Editor.cpp 19 KB

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