Editor.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  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. m_autocomplete_box = make<AutoCompleteBox>(*this);
  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. #ifdef EDITOR_DEBUG
  143. dbgln("no man path for {}", hovered_token);
  144. #endif
  145. m_documentation_tooltip_window->hide();
  146. return;
  147. }
  148. if (m_documentation_tooltip_window->is_visible() && hovered_token == m_last_parsed_token) {
  149. return;
  150. }
  151. #ifdef EDITOR_DEBUG
  152. dbgln("opening {}", it->value);
  153. #endif
  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_link = 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_link && event.ctrl() ? Gfx::StandardCursor::Hand : Gfx::StandardCursor::IBeam);
  197. for (auto& span : document().spans()) {
  198. if (span.range.contains(m_previous_text_position) && !span.range.contains(text_position)) {
  199. if (highlighter->is_navigatable(span.data) && span.is_underlined) {
  200. span.is_underlined = false;
  201. wrapper().editor().update();
  202. }
  203. }
  204. if (span.range.contains(text_position)) {
  205. auto adjusted_range = span.range;
  206. auto end_line_length = document().line(span.range.end().line()).length();
  207. adjusted_range.end().set_column(min(end_line_length, adjusted_range.end().column() + 1));
  208. auto hovered_span_text = document().text_in_range(adjusted_range);
  209. #ifdef EDITOR_DEBUG
  210. dbgln("Hovering: {} \"{}\"", adjusted_range, hovered_span_text);
  211. #endif
  212. if (highlighter->is_navigatable(span.data)) {
  213. is_over_link = true;
  214. bool was_underlined = span.is_underlined;
  215. span.is_underlined = event.modifiers() & Mod_Ctrl;
  216. if (span.is_underlined != was_underlined) {
  217. wrapper().editor().update();
  218. }
  219. }
  220. if (highlighter->is_identifier(span.data)) {
  221. show_documentation_tooltip_if_available(hovered_span_text, event.position().translated(screen_relative_rect().location()));
  222. hide_tooltip = false;
  223. }
  224. }
  225. }
  226. m_previous_text_position = text_position;
  227. if (hide_tooltip)
  228. m_documentation_tooltip_window->hide();
  229. m_hovering_link = is_over_link && (event.modifiers() & Mod_Ctrl);
  230. }
  231. void Editor::mousedown_event(GUI::MouseEvent& event)
  232. {
  233. auto highlighter = wrapper().editor().syntax_highlighter();
  234. if (!highlighter) {
  235. GUI::TextEditor::mousedown_event(event);
  236. return;
  237. }
  238. auto text_position = text_position_at(event.position());
  239. auto ruler_line_rect = ruler_content_rect(text_position.line());
  240. if (event.button() == GUI::MouseButton::Left && event.position().x() < ruler_line_rect.width()) {
  241. if (!breakpoint_lines().contains_slow(text_position.line())) {
  242. breakpoint_lines().append(text_position.line());
  243. Debugger::on_breakpoint_change(wrapper().filename_label().text(), text_position.line(), BreakpointChange::Added);
  244. } else {
  245. breakpoint_lines().remove_first_matching([&](size_t line) { return line == text_position.line(); });
  246. Debugger::on_breakpoint_change(wrapper().filename_label().text(), text_position.line(), BreakpointChange::Removed);
  247. }
  248. }
  249. if (!(event.modifiers() & Mod_Ctrl)) {
  250. GUI::TextEditor::mousedown_event(event);
  251. return;
  252. }
  253. if (!text_position.is_valid()) {
  254. GUI::TextEditor::mousedown_event(event);
  255. return;
  256. }
  257. if (auto* span = document().span_at(text_position)) {
  258. if (!highlighter->is_navigatable(span->data)) {
  259. GUI::TextEditor::mousedown_event(event);
  260. return;
  261. }
  262. auto adjusted_range = span->range;
  263. adjusted_range.end().set_column(adjusted_range.end().column() + 1);
  264. auto span_text = document().text_in_range(adjusted_range);
  265. auto header_path = span_text.substring(1, span_text.length() - 2);
  266. #ifdef EDITOR_DEBUG
  267. dbgln("Ctrl+click: {} \"{}\"", adjusted_range, header_path);
  268. #endif
  269. navigate_to_include_if_available(header_path);
  270. return;
  271. }
  272. GUI::TextEditor::mousedown_event(event);
  273. }
  274. void Editor::keydown_event(GUI::KeyEvent& event)
  275. {
  276. if (m_autocomplete_in_focus) {
  277. if (event.key() == Key_Escape) {
  278. m_autocomplete_in_focus = false;
  279. m_autocomplete_box->close();
  280. return;
  281. }
  282. if (event.key() == Key_Down) {
  283. m_autocomplete_box->next_suggestion();
  284. return;
  285. }
  286. if (event.key() == Key_Up) {
  287. m_autocomplete_box->previous_suggestion();
  288. return;
  289. }
  290. if (event.key() == Key_Return || event.key() == Key_Tab) {
  291. m_autocomplete_box->apply_suggestion();
  292. close_autocomplete();
  293. return;
  294. }
  295. }
  296. auto autocomplete_action = [this]() {
  297. auto data = get_autocomplete_request_data();
  298. if (data.has_value()) {
  299. update_autocomplete(data.value());
  300. if (m_autocomplete_in_focus)
  301. show_autocomplete(data.value());
  302. } else {
  303. close_autocomplete();
  304. }
  305. };
  306. if (event.ctrl() && event.key() == Key_Space) {
  307. autocomplete_action();
  308. }
  309. GUI::TextEditor::keydown_event(event);
  310. if (m_autocomplete_in_focus) {
  311. autocomplete_action();
  312. }
  313. }
  314. void Editor::enter_event(Core::Event& event)
  315. {
  316. m_hovering_editor = true;
  317. GUI::TextEditor::enter_event(event);
  318. }
  319. void Editor::leave_event(Core::Event& event)
  320. {
  321. m_hovering_editor = false;
  322. GUI::TextEditor::leave_event(event);
  323. }
  324. static HashMap<String, String>& include_paths()
  325. {
  326. static HashMap<String, String> paths;
  327. auto add_directory = [](String base, Optional<String> recursive, auto handle_directory) -> void {
  328. Core::DirIterator it(recursive.value_or(base), Core::DirIterator::Flags::SkipDots);
  329. while (it.has_next()) {
  330. auto path = it.next_full_path();
  331. if (!Core::File::is_directory(path)) {
  332. auto key = path.substring(base.length() + 1, path.length() - base.length() - 1);
  333. #ifdef EDITOR_DEBUG
  334. dbgln("Adding header \"{}\" in path \"{}\"", key, path);
  335. #endif
  336. paths.set(key, path);
  337. } else {
  338. handle_directory(base, path, handle_directory);
  339. }
  340. }
  341. };
  342. if (paths.is_empty()) {
  343. add_directory(".", {}, add_directory);
  344. add_directory("/usr/local/include", {}, add_directory);
  345. add_directory("/usr/local/include/c++/9.2.0", {}, add_directory);
  346. add_directory("/usr/include", {}, add_directory);
  347. }
  348. return paths;
  349. }
  350. void Editor::navigate_to_include_if_available(String path)
  351. {
  352. auto it = include_paths().find(path);
  353. if (it == include_paths().end()) {
  354. #ifdef EDITOR_DEBUG
  355. dbgln("no header {} found.", path);
  356. #endif
  357. return;
  358. }
  359. on_open(it->value);
  360. }
  361. void Editor::set_execution_position(size_t line_number)
  362. {
  363. code_document().set_execution_position(line_number);
  364. scroll_position_into_view({ line_number, 0 });
  365. update(breakpoint_icon_rect(line_number));
  366. }
  367. void Editor::clear_execution_position()
  368. {
  369. if (!execution_position().has_value()) {
  370. return;
  371. }
  372. size_t previous_position = execution_position().value();
  373. code_document().clear_execution_position();
  374. update(breakpoint_icon_rect(previous_position));
  375. }
  376. const Gfx::Bitmap& Editor::breakpoint_icon_bitmap()
  377. {
  378. static auto bitmap = Gfx::Bitmap::load_from_file("/res/icons/16x16/breakpoint.png");
  379. return *bitmap;
  380. }
  381. const Gfx::Bitmap& Editor::current_position_icon_bitmap()
  382. {
  383. static auto bitmap = Gfx::Bitmap::load_from_file("/res/icons/16x16/go-forward.png");
  384. return *bitmap;
  385. }
  386. const CodeDocument& Editor::code_document() const
  387. {
  388. const auto& doc = document();
  389. ASSERT(doc.is_code_document());
  390. return static_cast<const CodeDocument&>(doc);
  391. }
  392. CodeDocument& Editor::code_document()
  393. {
  394. return const_cast<CodeDocument&>(static_cast<const Editor&>(*this).code_document());
  395. }
  396. void Editor::set_document(GUI::TextDocument& doc)
  397. {
  398. ASSERT(doc.is_code_document());
  399. GUI::TextEditor::set_document(doc);
  400. set_override_cursor(Gfx::StandardCursor::IBeam);
  401. CodeDocument& code_document = static_cast<CodeDocument&>(doc);
  402. switch (code_document.language()) {
  403. case Language::Cpp:
  404. set_syntax_highlighter(make<GUI::CppSyntaxHighlighter>());
  405. m_language_client = get_language_client<LanguageClients::Cpp::ServerConnection>(project().root_path());
  406. break;
  407. case Language::GML:
  408. set_syntax_highlighter(make<GUI::GMLSyntaxHighlighter>());
  409. break;
  410. case Language::JavaScript:
  411. set_syntax_highlighter(make<GUI::JSSyntaxHighlighter>());
  412. break;
  413. case Language::Ini:
  414. set_syntax_highlighter(make<GUI::IniSyntaxHighlighter>());
  415. break;
  416. case Language::Shell:
  417. set_syntax_highlighter(make<GUI::ShellSyntaxHighlighter>());
  418. m_language_client = get_language_client<LanguageClients::Shell::ServerConnection>(project().root_path());
  419. break;
  420. default:
  421. set_syntax_highlighter(nullptr);
  422. }
  423. if (m_language_client) {
  424. dbgln("Opening {}", code_document.file_path());
  425. int fd = open(code_document.file_path().characters(), O_RDONLY | O_NOCTTY);
  426. if (fd < 0) {
  427. perror("open");
  428. return;
  429. }
  430. m_language_client->open_file(code_document.file_path(), fd);
  431. close(fd);
  432. }
  433. }
  434. Optional<Editor::AutoCompleteRequestData> Editor::get_autocomplete_request_data()
  435. {
  436. if (!wrapper().editor().m_language_client)
  437. return {};
  438. return Editor::AutoCompleteRequestData { cursor() };
  439. }
  440. void Editor::update_autocomplete(const AutoCompleteRequestData& data)
  441. {
  442. if (!m_language_client)
  443. return;
  444. m_language_client->on_autocomplete_suggestions = [=, this](auto suggestions) {
  445. if (suggestions.is_empty()) {
  446. close_autocomplete();
  447. return;
  448. }
  449. show_autocomplete(data);
  450. m_autocomplete_box->update_suggestions(move(suggestions));
  451. m_autocomplete_in_focus = true;
  452. };
  453. m_language_client->request_autocomplete(
  454. code_document().file_path(),
  455. data.position.line(),
  456. data.position.column());
  457. }
  458. void Editor::show_autocomplete(const AutoCompleteRequestData& data)
  459. {
  460. auto suggestion_box_location = content_rect_for_position(data.position).bottom_right().translated(screen_relative_rect().top_left().translated(ruler_width(), 0).translated(10, 5));
  461. m_autocomplete_box->show(suggestion_box_location);
  462. }
  463. void Editor::close_autocomplete()
  464. {
  465. m_autocomplete_box->close();
  466. m_autocomplete_in_focus = false;
  467. }
  468. void Editor::on_edit_action(const GUI::Command& command)
  469. {
  470. if (!m_language_client)
  471. return;
  472. if (command.is_insert_text()) {
  473. const GUI::InsertTextCommand& insert_command = static_cast<const GUI::InsertTextCommand&>(command);
  474. m_language_client->insert_text(
  475. code_document().file_path(),
  476. insert_command.text(),
  477. insert_command.range().start().line(),
  478. insert_command.range().start().column());
  479. return;
  480. }
  481. if (command.is_remove_text()) {
  482. const GUI::RemoveTextCommand& remove_command = static_cast<const GUI::RemoveTextCommand&>(command);
  483. m_language_client->remove_text(
  484. code_document().file_path(),
  485. remove_command.range().start().line(),
  486. remove_command.range().start().column(),
  487. remove_command.range().end().line(),
  488. remove_command.range().end().column());
  489. return;
  490. }
  491. ASSERT_NOT_REACHED();
  492. }
  493. void Editor::undo()
  494. {
  495. TextEditor::undo();
  496. flush_file_content_to_langauge_server();
  497. }
  498. void Editor::redo()
  499. {
  500. TextEditor::redo();
  501. flush_file_content_to_langauge_server();
  502. }
  503. void Editor::flush_file_content_to_langauge_server()
  504. {
  505. if (!m_language_client)
  506. return;
  507. m_language_client->set_file_content(
  508. code_document().file_path(),
  509. document().text());
  510. }
  511. }