Editor.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  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/INISyntaxHighlighter.h>
  38. #include <LibGUI/JSSyntaxHighlighter.h>
  39. #include <LibGUI/Label.h>
  40. #include <LibGUI/Painter.h>
  41. #include <LibGUI/ScrollBar.h>
  42. #include <LibGUI/ShellSyntaxHighlighter.h>
  43. #include <LibGUI/SyntaxHighlighter.h>
  44. #include <LibGUI/Window.h>
  45. #include <LibMarkdown/Document.h>
  46. #include <LibWeb/DOM/ElementFactory.h>
  47. #include <LibWeb/DOM/Text.h>
  48. #include <LibWeb/HTML/HTMLHeadElement.h>
  49. #include <LibWeb/InProcessWebView.h>
  50. // #define EDITOR_DEBUG
  51. namespace HackStudio {
  52. Editor::Editor()
  53. {
  54. set_document(CodeDocument::create());
  55. m_documentation_tooltip_window = GUI::Window::construct();
  56. m_documentation_tooltip_window->set_rect(0, 0, 500, 400);
  57. m_documentation_tooltip_window->set_window_type(GUI::WindowType::Tooltip);
  58. m_documentation_page_view = m_documentation_tooltip_window->set_main_widget<Web::InProcessWebView>();
  59. m_autocomplete_box = make<AutoCompleteBox>(make_weak_ptr());
  60. }
  61. Editor::~Editor()
  62. {
  63. }
  64. EditorWrapper& Editor::wrapper()
  65. {
  66. return static_cast<EditorWrapper&>(*parent());
  67. }
  68. const EditorWrapper& Editor::wrapper() const
  69. {
  70. return static_cast<const EditorWrapper&>(*parent());
  71. }
  72. void Editor::focusin_event(GUI::FocusEvent& event)
  73. {
  74. wrapper().set_editor_has_focus({}, true);
  75. if (on_focus)
  76. on_focus();
  77. GUI::TextEditor::focusin_event(event);
  78. }
  79. void Editor::focusout_event(GUI::FocusEvent& event)
  80. {
  81. wrapper().set_editor_has_focus({}, false);
  82. GUI::TextEditor::focusout_event(event);
  83. }
  84. Gfx::IntRect Editor::breakpoint_icon_rect(size_t line_number) const
  85. {
  86. auto ruler_line_rect = ruler_content_rect(line_number);
  87. auto scroll_value = vertical_scrollbar().value();
  88. ruler_line_rect = ruler_line_rect.translated({ 0, -scroll_value });
  89. auto center = ruler_line_rect.center().translated({ ruler_line_rect.width() - 10, -line_spacing() - 3 });
  90. constexpr int size = 32;
  91. return { center.x() - size / 2, center.y() - size / 2, size, size };
  92. }
  93. void Editor::paint_event(GUI::PaintEvent& event)
  94. {
  95. GUI::TextEditor::paint_event(event);
  96. GUI::Painter painter(*this);
  97. if (is_focused()) {
  98. painter.add_clip_rect(event.rect());
  99. auto rect = frame_inner_rect();
  100. if (vertical_scrollbar().is_visible())
  101. rect.set_width(rect.width() - vertical_scrollbar().width());
  102. if (horizontal_scrollbar().is_visible())
  103. rect.set_height(rect.height() - horizontal_scrollbar().height());
  104. painter.draw_rect(rect, palette().selection());
  105. }
  106. if (ruler_visible()) {
  107. size_t first_visible_line = text_position_at(event.rect().top_left()).line();
  108. size_t last_visible_line = text_position_at(event.rect().bottom_right()).line();
  109. for (size_t line : breakpoint_lines()) {
  110. if (line < first_visible_line || line > last_visible_line) {
  111. continue;
  112. }
  113. const auto& icon = breakpoint_icon_bitmap();
  114. painter.blit(breakpoint_icon_rect(line).center(), icon, icon.rect());
  115. }
  116. if (execution_position().has_value()) {
  117. const auto& icon = current_position_icon_bitmap();
  118. painter.blit(breakpoint_icon_rect(execution_position().value()).center(), icon, icon.rect());
  119. }
  120. }
  121. }
  122. static HashMap<String, String>& man_paths()
  123. {
  124. static HashMap<String, String> paths;
  125. if (paths.is_empty()) {
  126. // FIXME: This should also search man3, possibly other places..
  127. Core::DirIterator it("/usr/share/man/man2", Core::DirIterator::Flags::SkipDots);
  128. while (it.has_next()) {
  129. auto path = String::format("/usr/share/man/man2/%s", it.next_path().characters());
  130. auto title = LexicalPath(path).title();
  131. paths.set(title, path);
  132. }
  133. }
  134. return paths;
  135. }
  136. void Editor::show_documentation_tooltip_if_available(const String& hovered_token, const Gfx::IntPoint& screen_location)
  137. {
  138. auto it = man_paths().find(hovered_token);
  139. if (it == man_paths().end()) {
  140. #ifdef EDITOR_DEBUG
  141. dbg() << "no man path for " << hovered_token;
  142. #endif
  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. #ifdef EDITOR_DEBUG
  150. dbg() << "opening " << it->value;
  151. #endif
  152. auto file = Core::File::construct(it->value);
  153. if (!file->open(Core::File::ReadOnly)) {
  154. dbg() << "failed to open " << it->value << " " << file->error_string();
  155. return;
  156. }
  157. auto man_document = Markdown::Document::parse(file->read_all());
  158. if (!man_document) {
  159. dbg() << "failed to parse markdown";
  160. return;
  161. }
  162. auto html_text = man_document->render_to_html();
  163. m_documentation_page_view->load_html(html_text, {});
  164. if (auto* document = m_documentation_page_view->document()) {
  165. const_cast<Web::HTML::HTMLElement*>(document->body())->set_attribute(Web::HTML::AttributeNames::style, "background-color: #dac7b5;");
  166. }
  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_link = 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_link && m_holding_ctrl ? Gfx::StandardCursor::Hand : Gfx::StandardCursor::IBeam);
  192. for (auto& span : document().spans()) {
  193. if (span.range.contains(m_previous_text_position) && !span.range.contains(text_position)) {
  194. if (highlighter->is_navigatable(span.data) && span.is_underlined) {
  195. span.is_underlined = false;
  196. wrapper().editor().update();
  197. }
  198. }
  199. if (span.range.contains(text_position)) {
  200. auto adjusted_range = span.range;
  201. auto end_line_length = document().line(span.range.end().line()).length();
  202. adjusted_range.end().set_column(min(end_line_length, adjusted_range.end().column() + 1));
  203. auto hovered_span_text = document().text_in_range(adjusted_range);
  204. #ifdef EDITOR_DEBUG
  205. dbg() << "Hovering: " << adjusted_range << " \"" << hovered_span_text << "\"";
  206. #endif
  207. if (highlighter->is_navigatable(span.data)) {
  208. is_over_link = true;
  209. bool was_underlined = span.is_underlined;
  210. span.is_underlined = event.modifiers() & Mod_Ctrl;
  211. if (span.is_underlined != 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_link = is_over_link && (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::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::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. for (auto& span : document().spans()) {
  253. if (span.range.contains(text_position)) {
  254. if (!highlighter->is_navigatable(span.data)) {
  255. GUI::TextEditor::mousedown_event(event);
  256. return;
  257. }
  258. auto adjusted_range = span.range;
  259. adjusted_range.end().set_column(adjusted_range.end().column() + 1);
  260. auto span_text = document().text_in_range(adjusted_range);
  261. auto header_path = span_text.substring(1, span_text.length() - 2);
  262. #ifdef EDITOR_DEBUG
  263. dbg() << "Ctrl+click: " << adjusted_range << " \"" << header_path << "\"";
  264. #endif
  265. navigate_to_include_if_available(header_path);
  266. return;
  267. }
  268. }
  269. GUI::TextEditor::mousedown_event(event);
  270. }
  271. void Editor::keydown_event(GUI::KeyEvent& event)
  272. {
  273. if (m_autocomplete_in_focus) {
  274. if (event.key() == Key_Escape) {
  275. m_autocomplete_in_focus = false;
  276. m_autocomplete_box->close();
  277. return;
  278. }
  279. if (event.key() == Key_Down) {
  280. m_autocomplete_box->next_suggestion();
  281. return;
  282. }
  283. if (event.key() == Key_Up) {
  284. m_autocomplete_box->previous_suggestion();
  285. return;
  286. }
  287. if (event.key() == Key_Return || event.key() == Key_Tab) {
  288. m_autocomplete_box->apply_suggestion();
  289. close_autocomplete();
  290. return;
  291. }
  292. }
  293. auto autocomplete_action = [this]() {
  294. auto data = get_autocomplete_request_data();
  295. if (data.has_value()) {
  296. update_autocomplete(data.value());
  297. if (m_autocomplete_in_focus)
  298. show_autocomplete(data.value());
  299. } else {
  300. close_autocomplete();
  301. }
  302. };
  303. if (event.key() == Key_Control)
  304. m_holding_ctrl = true;
  305. if (m_holding_ctrl && event.key() == Key_Space) {
  306. autocomplete_action();
  307. }
  308. GUI::TextEditor::keydown_event(event);
  309. if (m_autocomplete_in_focus) {
  310. autocomplete_action();
  311. }
  312. }
  313. void Editor::keyup_event(GUI::KeyEvent& event)
  314. {
  315. if (event.key() == Key_Control)
  316. m_holding_ctrl = false;
  317. GUI::TextEditor::keyup_event(event);
  318. }
  319. void Editor::enter_event(Core::Event& event)
  320. {
  321. m_hovering_editor = true;
  322. GUI::TextEditor::enter_event(event);
  323. }
  324. void Editor::leave_event(Core::Event& event)
  325. {
  326. m_hovering_editor = false;
  327. GUI::TextEditor::leave_event(event);
  328. }
  329. static HashMap<String, String>& include_paths()
  330. {
  331. static HashMap<String, String> paths;
  332. auto add_directory = [](String base, Optional<String> recursive, auto handle_directory) -> void {
  333. Core::DirIterator it(recursive.value_or(base), Core::DirIterator::Flags::SkipDots);
  334. while (it.has_next()) {
  335. auto path = it.next_full_path();
  336. if (!Core::File::is_directory(path)) {
  337. auto key = path.substring(base.length() + 1, path.length() - base.length() - 1);
  338. #ifdef EDITOR_DEBUG
  339. dbg() << "Adding header \"" << key << "\" in path \"" << path << "\"";
  340. #endif
  341. paths.set(key, path);
  342. } else {
  343. handle_directory(base, path, handle_directory);
  344. }
  345. }
  346. };
  347. if (paths.is_empty()) {
  348. add_directory(".", {}, add_directory);
  349. add_directory("/usr/local/include", {}, add_directory);
  350. add_directory("/usr/local/include/c++/9.2.0", {}, add_directory);
  351. add_directory("/usr/include", {}, add_directory);
  352. }
  353. return paths;
  354. }
  355. void Editor::navigate_to_include_if_available(String path)
  356. {
  357. auto it = include_paths().find(path);
  358. if (it == include_paths().end()) {
  359. #ifdef EDITOR_DEBUG
  360. dbg() << "no header " << path << " found.";
  361. #endif
  362. return;
  363. }
  364. on_open(it->value);
  365. }
  366. void Editor::set_execution_position(size_t line_number)
  367. {
  368. code_document().set_execution_position(line_number);
  369. scroll_position_into_view({ line_number, 0 });
  370. update(breakpoint_icon_rect(line_number));
  371. }
  372. void Editor::clear_execution_position()
  373. {
  374. if (!execution_position().has_value()) {
  375. return;
  376. }
  377. size_t previous_position = execution_position().value();
  378. code_document().clear_execution_position();
  379. update(breakpoint_icon_rect(previous_position));
  380. }
  381. const Gfx::Bitmap& Editor::breakpoint_icon_bitmap()
  382. {
  383. static auto bitmap = Gfx::Bitmap::load_from_file("/res/icons/16x16/breakpoint.png");
  384. return *bitmap;
  385. }
  386. const Gfx::Bitmap& Editor::current_position_icon_bitmap()
  387. {
  388. static auto bitmap = Gfx::Bitmap::load_from_file("/res/icons/16x16/go-forward.png");
  389. return *bitmap;
  390. }
  391. const CodeDocument& Editor::code_document() const
  392. {
  393. const auto& doc = document();
  394. ASSERT(doc.is_code_document());
  395. return static_cast<const CodeDocument&>(doc);
  396. }
  397. CodeDocument& Editor::code_document()
  398. {
  399. return const_cast<CodeDocument&>(static_cast<const Editor&>(*this).code_document());
  400. }
  401. void Editor::set_document(GUI::TextDocument& doc)
  402. {
  403. ASSERT(doc.is_code_document());
  404. GUI::TextEditor::set_document(doc);
  405. CodeDocument& code_document = static_cast<CodeDocument&>(doc);
  406. switch (code_document.language()) {
  407. case Language::Cpp:
  408. set_syntax_highlighter(make<GUI::CppSyntaxHighlighter>());
  409. cpp_Language_server_connection().post_message(Messages::CppLanguageServer::FileOpened(code_document.file_path().string()));
  410. break;
  411. case Language::JavaScript:
  412. set_syntax_highlighter(make<GUI::JSSyntaxHighlighter>());
  413. break;
  414. case Language::Ini:
  415. set_syntax_highlighter(make<GUI::IniSyntaxHighlighter>());
  416. break;
  417. case Language::Shell:
  418. set_syntax_highlighter(make<GUI::ShellSyntaxHighlighter>());
  419. break;
  420. default:
  421. set_syntax_highlighter(nullptr);
  422. }
  423. }
  424. Optional<Editor::AutoCompleteRequestData> Editor::get_autocomplete_request_data()
  425. {
  426. auto highlighter = wrapper().editor().syntax_highlighter();
  427. if (!highlighter)
  428. return {};
  429. auto& spans = document().spans();
  430. for (size_t span_index = 2; span_index < spans.size(); ++span_index) {
  431. auto& span = spans[span_index];
  432. if (!span.range.contains(cursor())) {
  433. continue;
  434. }
  435. if (highlighter->is_identifier(spans[span_index - 1].data)) {
  436. auto completion_span = spans[span_index - 1];
  437. auto adjusted_range = completion_span.range;
  438. auto end_line_length = document().line(completion_span.range.end().line()).length();
  439. adjusted_range.end().set_column(min(end_line_length, adjusted_range.end().column() + 1));
  440. auto text_in_span = document().text_in_range(adjusted_range);
  441. return AutoCompleteRequestData { completion_span.range.end(), text_in_span };
  442. }
  443. }
  444. return {};
  445. }
  446. void Editor::update_autocomplete(const AutoCompleteRequestData& data)
  447. {
  448. if (code_document().language() != Language::Cpp)
  449. return;
  450. auto autocomplete_response = cpp_Language_server_connection().send_sync<Messages::CppLanguageServer::AutoCompleteSuggestions>(
  451. code_document().file_path().string(),
  452. data.position.line(),
  453. data.position.column());
  454. ASSERT(autocomplete_response);
  455. auto suggestions = autocomplete_response->suggestions();
  456. if (suggestions.is_empty()) {
  457. close_autocomplete();
  458. return;
  459. }
  460. m_autocomplete_box->update_suggestions(data.partial_input, move(suggestions));
  461. m_autocomplete_in_focus = true;
  462. }
  463. void Editor::show_autocomplete(const AutoCompleteRequestData& data)
  464. {
  465. 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));
  466. m_autocomplete_box->show(suggestion_box_location);
  467. }
  468. void Editor::close_autocomplete()
  469. {
  470. m_autocomplete_box->close();
  471. m_autocomplete_in_focus = false;
  472. }
  473. void Editor::on_edit_action(const GUI::Command& command)
  474. {
  475. if (code_document().language() != Language::Cpp)
  476. return;
  477. if (command.is_insert_text()) {
  478. const GUI::InsertTextCommand& insert_command = static_cast<const GUI::InsertTextCommand&>(command);
  479. cpp_Language_server_connection().post_message(
  480. Messages::CppLanguageServer::FileEditInsertText(
  481. code_document().file_path().string(),
  482. insert_command.text(),
  483. insert_command.range().start().line(),
  484. insert_command.range().start().column()));
  485. return;
  486. }
  487. if (command.is_remove_text()) {
  488. const GUI::RemoveTextCommand& remove_command = static_cast<const GUI::RemoveTextCommand&>(command);
  489. cpp_Language_server_connection().post_message(
  490. Messages::CppLanguageServer::FileEditRemoveText(
  491. code_document().file_path().string(),
  492. remove_command.range().start().line(),
  493. remove_command.range().start().column(),
  494. remove_command.range().end().line(),
  495. remove_command.range().end().column()));
  496. return;
  497. }
  498. ASSERT_NOT_REACHED();
  499. }
  500. void Editor::undo()
  501. {
  502. TextEditor::undo();
  503. flush_file_content_to_langauge_server();
  504. }
  505. void Editor::redo()
  506. {
  507. TextEditor::redo();
  508. flush_file_content_to_langauge_server();
  509. }
  510. void Editor::flush_file_content_to_langauge_server()
  511. {
  512. if (code_document().language() != Language::Cpp)
  513. return;
  514. cpp_Language_server_connection().post_message(
  515. Messages::CppLanguageServer::SetFileContent(
  516. code_document().file_path().string(),
  517. document().text()));
  518. }
  519. }