Editor.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2018-2022, the SerenityOS developers.
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include "Editor.h"
  8. #include "Debugger/Debugger.h"
  9. #include "EditorWrapper.h"
  10. #include "HackStudio.h"
  11. #include "Language.h"
  12. #include <AK/ByteBuffer.h>
  13. #include <AK/Debug.h>
  14. #include <AK/JsonParser.h>
  15. #include <AK/LexicalPath.h>
  16. #include <LibConfig/Client.h>
  17. #include <LibCore/DirIterator.h>
  18. #include <LibCore/File.h>
  19. #include <LibCore/Timer.h>
  20. #include <LibCpp/SemanticSyntaxHighlighter.h>
  21. #include <LibCpp/SyntaxHighlighter.h>
  22. #include <LibGUI/Action.h>
  23. #include <LibGUI/Application.h>
  24. #include <LibGUI/GML/AutocompleteProvider.h>
  25. #include <LibGUI/GML/SyntaxHighlighter.h>
  26. #include <LibGUI/GitCommitSyntaxHighlighter.h>
  27. #include <LibGUI/INISyntaxHighlighter.h>
  28. #include <LibGUI/Label.h>
  29. #include <LibGUI/MessageBox.h>
  30. #include <LibGUI/Painter.h>
  31. #include <LibGUI/Scrollbar.h>
  32. #include <LibGUI/Window.h>
  33. #include <LibJS/SyntaxHighlighter.h>
  34. #include <LibMarkdown/Document.h>
  35. #include <LibSQL/AST/SyntaxHighlighter.h>
  36. #include <LibWeb/CSS/SyntaxHighlighter/SyntaxHighlighter.h>
  37. #include <LibWeb/DOM/Text.h>
  38. #include <LibWeb/HTML/HTMLHeadElement.h>
  39. #include <LibWeb/HTML/SyntaxHighlighter/SyntaxHighlighter.h>
  40. #include <LibWebView/OutOfProcessWebView.h>
  41. #include <Shell/SyntaxHighlighter.h>
  42. #include <fcntl.h>
  43. namespace HackStudio {
  44. enum class TooltipRole {
  45. Documentation,
  46. ParametersHint,
  47. };
  48. static RefPtr<GUI::Window> s_tooltip_window;
  49. static RefPtr<WebView::OutOfProcessWebView> s_tooltip_page_view;
  50. static Optional<TooltipRole> m_tooltip_role;
  51. ErrorOr<NonnullRefPtr<Editor>> Editor::try_create()
  52. {
  53. NonnullRefPtr<Editor> editor = TRY(adopt_nonnull_ref_or_enomem(new (nothrow) Editor()));
  54. TRY(initialize_tooltip_window());
  55. return editor;
  56. }
  57. Editor::Editor()
  58. {
  59. create_tokens_info_timer();
  60. set_document(CodeDocument::create());
  61. m_move_execution_to_line_action = GUI::Action::create("Set execution point to line", [this](auto&) {
  62. VERIFY(is_program_running());
  63. auto success = Debugger::the().set_execution_position(currently_open_file(), cursor().line());
  64. if (success) {
  65. set_execution_position(cursor().line());
  66. } else {
  67. GUI::MessageBox::show(window(), "Failed to set execution position"sv, "Error"sv, GUI::MessageBox::Type::Error);
  68. }
  69. });
  70. set_debug_mode(false);
  71. add_custom_context_menu_action(*m_move_execution_to_line_action);
  72. set_gutter_visible(true);
  73. if (Config::read_string("HackStudio"sv, "Global"sv, "DocumentationSearchPaths"sv).is_empty()) {
  74. Config::write_string("HackStudio"sv, "Global"sv, "DocumentationSearchPaths"sv, "[\"/usr/share/man/man2\", \"/usr/share/man/man3\"]"sv);
  75. }
  76. }
  77. ErrorOr<void> Editor::initialize_tooltip_window()
  78. {
  79. if (s_tooltip_window.is_null()) {
  80. s_tooltip_window = GUI::Window::construct();
  81. s_tooltip_window->set_window_type(GUI::WindowType::Tooltip);
  82. }
  83. if (s_tooltip_page_view.is_null()) {
  84. s_tooltip_page_view = TRY(s_tooltip_window->try_set_main_widget<WebView::OutOfProcessWebView>());
  85. }
  86. return {};
  87. }
  88. EditorWrapper& Editor::wrapper()
  89. {
  90. return static_cast<EditorWrapper&>(*parent());
  91. }
  92. EditorWrapper const& Editor::wrapper() const
  93. {
  94. return static_cast<EditorWrapper const&>(*parent());
  95. }
  96. void Editor::focusin_event(GUI::FocusEvent& event)
  97. {
  98. if (on_focus)
  99. on_focus();
  100. GUI::TextEditor::focusin_event(event);
  101. }
  102. void Editor::focusout_event(GUI::FocusEvent& event)
  103. {
  104. GUI::TextEditor::focusout_event(event);
  105. }
  106. Gfx::IntRect Editor::gutter_icon_rect(size_t line_number) const
  107. {
  108. return gutter_content_rect(line_number).translated(ruler_width() + gutter_width() + frame_thickness(), -vertical_scrollbar().value());
  109. }
  110. void Editor::paint_event(GUI::PaintEvent& event)
  111. {
  112. GUI::TextEditor::paint_event(event);
  113. GUI::Painter painter(*this);
  114. if (is_focused()) {
  115. painter.add_clip_rect(event.rect());
  116. auto rect = frame_inner_rect();
  117. if (vertical_scrollbar().is_visible())
  118. rect.set_width(rect.width() - vertical_scrollbar().width());
  119. if (horizontal_scrollbar().is_visible())
  120. rect.set_height(rect.height() - horizontal_scrollbar().height());
  121. painter.draw_rect(rect, palette().selection());
  122. }
  123. if (gutter_visible()) {
  124. size_t first_visible_line = text_position_at(event.rect().top_left()).line();
  125. size_t last_visible_line = text_position_at(event.rect().bottom_right()).line();
  126. for (size_t line : breakpoint_lines()) {
  127. if (line < first_visible_line || line > last_visible_line) {
  128. continue;
  129. }
  130. auto const& icon = breakpoint_icon_bitmap();
  131. painter.blit(gutter_icon_rect(line).top_left(), icon, icon.rect());
  132. }
  133. if (execution_position().has_value()) {
  134. auto const& icon = current_position_icon_bitmap();
  135. painter.blit(gutter_icon_rect(execution_position().value()).top_left(), icon, icon.rect());
  136. }
  137. if (wrapper().git_repo()) {
  138. for (auto& hunk : wrapper().hunks()) {
  139. auto start_line = hunk.target_start_line;
  140. auto finish_line = start_line + hunk.added_lines.size();
  141. auto additions = hunk.added_lines.size();
  142. auto deletions = hunk.removed_lines.size();
  143. for (size_t line_offset = 0; line_offset < additions; line_offset++) {
  144. auto line = start_line + line_offset;
  145. if (line < first_visible_line || line > last_visible_line) {
  146. continue;
  147. }
  148. auto sign = (line_offset < deletions) ? "!"sv : "+"sv;
  149. painter.draw_text(gutter_icon_rect(line), sign, font(), Gfx::TextAlignment::Center);
  150. }
  151. if (additions < deletions) {
  152. auto deletions_line = min(finish_line, line_count() - 1);
  153. if (deletions_line <= last_visible_line) {
  154. painter.draw_text(gutter_icon_rect(deletions_line), "-"sv, font(), Gfx::TextAlignment::Center);
  155. }
  156. }
  157. }
  158. }
  159. }
  160. }
  161. static HashMap<String, String>& man_paths()
  162. {
  163. static HashMap<String, String> paths;
  164. if (paths.is_empty()) {
  165. auto json = Config::read_string("HackStudio"sv, "Global"sv, "DocumentationSearchPaths"sv);
  166. AK::JsonParser parser(json);
  167. auto value_or_error = parser.parse();
  168. if (value_or_error.is_error())
  169. return paths;
  170. auto value = value_or_error.release_value();
  171. if (!value.is_array())
  172. return paths;
  173. for (auto& json_value : value.as_array().values()) {
  174. if (!json_value.is_string())
  175. continue;
  176. Core::DirIterator it(json_value.as_string(), Core::DirIterator::Flags::SkipDots);
  177. while (it.has_next()) {
  178. auto path = it.next_full_path();
  179. auto title = LexicalPath::title(path);
  180. paths.set(title, path);
  181. }
  182. }
  183. }
  184. return paths;
  185. }
  186. void Editor::show_documentation_tooltip_if_available(String const& hovered_token, Gfx::IntPoint const& screen_location)
  187. {
  188. auto it = man_paths().find(hovered_token);
  189. if (it == man_paths().end()) {
  190. dbgln_if(EDITOR_DEBUG, "no man path for {}", hovered_token);
  191. if (m_tooltip_role == TooltipRole::Documentation) {
  192. s_tooltip_window->hide();
  193. m_tooltip_role.clear();
  194. }
  195. return;
  196. }
  197. if (s_tooltip_window->is_visible() && m_tooltip_role == TooltipRole::Documentation && hovered_token == m_last_parsed_token) {
  198. return;
  199. }
  200. dbgln_if(EDITOR_DEBUG, "opening {}", it->value);
  201. auto file = Core::File::construct(it->value);
  202. if (!file->open(Core::OpenMode::ReadOnly)) {
  203. dbgln("failed to open {}, {}", it->value, file->error_string());
  204. return;
  205. }
  206. auto man_document = Markdown::Document::parse(file->read_all());
  207. if (!man_document) {
  208. dbgln("failed to parse markdown");
  209. return;
  210. }
  211. s_tooltip_page_view->load_html(man_document->render_to_html("<style>body { background-color: #dac7b5; }</style>"sv), {});
  212. s_tooltip_window->set_rect(0, 0, 500, 400);
  213. s_tooltip_window->move_to(screen_location.translated(4, 4));
  214. m_tooltip_role = TooltipRole::Documentation;
  215. s_tooltip_window->show();
  216. m_last_parsed_token = hovered_token;
  217. }
  218. void Editor::mousemove_event(GUI::MouseEvent& event)
  219. {
  220. GUI::TextEditor::mousemove_event(event);
  221. if (document().spans().is_empty())
  222. return;
  223. auto text_position = text_position_at(event.position());
  224. if (!text_position.is_valid() && m_tooltip_role == TooltipRole::Documentation) {
  225. s_tooltip_window->hide();
  226. m_tooltip_role.clear();
  227. return;
  228. }
  229. auto highlighter = wrapper().editor().syntax_highlighter();
  230. if (!highlighter)
  231. return;
  232. bool hide_tooltip = (m_tooltip_role == TooltipRole::Documentation);
  233. bool is_over_clickable = false;
  234. auto ruler_line_rect = ruler_content_rect(text_position.line());
  235. auto hovering_lines_ruler = (event.position().x() < ruler_line_rect.width());
  236. if (hovering_lines_ruler && !is_in_drag_select())
  237. set_override_cursor(Gfx::StandardCursor::Arrow);
  238. else if (m_hovering_editor)
  239. set_override_cursor(m_hovering_clickable && event.ctrl() ? Gfx::StandardCursor::Hand : Gfx::StandardCursor::IBeam);
  240. for (auto& span : document().spans()) {
  241. bool is_clickable = (highlighter->is_navigatable(span.data) || highlighter->is_identifier(span.data));
  242. if (span.range.contains(m_previous_text_position) && !span.range.contains(text_position)) {
  243. if (is_clickable && span.attributes.underline) {
  244. span.attributes.underline = false;
  245. wrapper().editor().update();
  246. }
  247. }
  248. if (span.range.contains(text_position)) {
  249. auto hovered_span_text = document().text_in_range(span.range);
  250. dbgln_if(EDITOR_DEBUG, "Hovering: {} \"{}\"", span.range, hovered_span_text);
  251. if (is_clickable) {
  252. is_over_clickable = true;
  253. bool was_underlined = span.attributes.underline;
  254. span.attributes.underline = event.modifiers() & Mod_Ctrl;
  255. if (span.attributes.underline != was_underlined) {
  256. wrapper().editor().update();
  257. }
  258. }
  259. if (highlighter->is_identifier(span.data)) {
  260. show_documentation_tooltip_if_available(hovered_span_text, event.position().translated(screen_relative_rect().location()));
  261. hide_tooltip = false;
  262. }
  263. }
  264. }
  265. m_previous_text_position = text_position;
  266. if (hide_tooltip) {
  267. s_tooltip_window->hide();
  268. m_tooltip_role.clear();
  269. }
  270. m_hovering_clickable = (is_over_clickable) && (event.modifiers() & Mod_Ctrl);
  271. }
  272. void Editor::mousedown_event(GUI::MouseEvent& event)
  273. {
  274. if (m_tooltip_role == TooltipRole::ParametersHint) {
  275. s_tooltip_window->hide();
  276. m_tooltip_role.clear();
  277. }
  278. auto highlighter = wrapper().editor().syntax_highlighter();
  279. if (!highlighter) {
  280. GUI::TextEditor::mousedown_event(event);
  281. return;
  282. }
  283. auto text_position = text_position_at(event.position());
  284. auto ruler_line_rect = ruler_content_rect(text_position.line());
  285. if (event.button() == GUI::MouseButton::Primary && event.position().x() < ruler_line_rect.width()) {
  286. if (!breakpoint_lines().contains_slow(text_position.line())) {
  287. breakpoint_lines().append(text_position.line());
  288. Debugger::the().on_breakpoint_change(wrapper().filename_title(), text_position.line(), BreakpointChange::Added);
  289. } else {
  290. breakpoint_lines().remove_first_matching([&](size_t line) { return line == text_position.line(); });
  291. Debugger::the().on_breakpoint_change(wrapper().filename_title(), text_position.line(), BreakpointChange::Removed);
  292. }
  293. }
  294. if (!(event.modifiers() & Mod_Ctrl)) {
  295. GUI::TextEditor::mousedown_event(event);
  296. return;
  297. }
  298. if (!text_position.is_valid()) {
  299. GUI::TextEditor::mousedown_event(event);
  300. return;
  301. }
  302. if (auto* span = document().span_at(text_position)) {
  303. if (highlighter->is_navigatable(span->data)) {
  304. on_navigatable_link_click(*span);
  305. return;
  306. }
  307. if (highlighter->is_identifier(span->data)) {
  308. on_identifier_click(*span);
  309. return;
  310. }
  311. }
  312. GUI::TextEditor::mousedown_event(event);
  313. }
  314. void Editor::drag_enter_event(GUI::DragEvent& event)
  315. {
  316. auto const& mime_types = event.mime_types();
  317. if (mime_types.contains_slow("text/uri-list"))
  318. event.accept();
  319. }
  320. void Editor::drop_event(GUI::DropEvent& event)
  321. {
  322. event.accept();
  323. if (event.mime_data().has_urls()) {
  324. auto urls = event.mime_data().urls();
  325. if (urls.is_empty())
  326. return;
  327. window()->move_to_front();
  328. if (urls.size() > 1) {
  329. GUI::MessageBox::show(window(), "HackStudio can only open one file at a time!"sv, "One at a time please!"sv, GUI::MessageBox::Type::Error);
  330. return;
  331. }
  332. set_current_editor_wrapper(static_cast<EditorWrapper*>(parent()));
  333. open_file(urls.first().path());
  334. }
  335. }
  336. void Editor::enter_event(Core::Event& event)
  337. {
  338. m_hovering_editor = true;
  339. GUI::TextEditor::enter_event(event);
  340. }
  341. void Editor::leave_event(Core::Event& event)
  342. {
  343. m_hovering_editor = false;
  344. GUI::TextEditor::leave_event(event);
  345. }
  346. static HashMap<String, String>& include_paths()
  347. {
  348. static HashMap<String, String> paths;
  349. auto add_directory = [](String base, Optional<String> recursive, auto handle_directory) -> void {
  350. Core::DirIterator it(recursive.value_or(base), Core::DirIterator::Flags::SkipDots);
  351. while (it.has_next()) {
  352. auto path = it.next_full_path();
  353. if (!Core::File::is_directory(path)) {
  354. auto key = path.substring(base.length() + 1, path.length() - base.length() - 1);
  355. dbgln_if(EDITOR_DEBUG, "Adding header \"{}\" in path \"{}\"", key, path);
  356. paths.set(key, path);
  357. } else {
  358. handle_directory(base, path, handle_directory);
  359. }
  360. }
  361. };
  362. if (paths.is_empty()) {
  363. add_directory(".", {}, add_directory);
  364. add_directory("/usr/local/include", {}, add_directory);
  365. add_directory("/usr/local/include/c++/9.2.0", {}, add_directory);
  366. add_directory("/usr/include", {}, add_directory);
  367. }
  368. return paths;
  369. }
  370. void Editor::navigate_to_include_if_available(String path)
  371. {
  372. auto it = include_paths().find(path);
  373. if (it == include_paths().end()) {
  374. dbgln_if(EDITOR_DEBUG, "no header {} found.", path);
  375. return;
  376. }
  377. on_open(it->value);
  378. }
  379. void Editor::set_execution_position(size_t line_number)
  380. {
  381. code_document().set_execution_position(line_number);
  382. scroll_position_into_view({ line_number, 0 });
  383. update(gutter_icon_rect(line_number));
  384. }
  385. void Editor::clear_execution_position()
  386. {
  387. if (!execution_position().has_value()) {
  388. return;
  389. }
  390. size_t previous_position = execution_position().value();
  391. code_document().clear_execution_position();
  392. update(gutter_icon_rect(previous_position));
  393. }
  394. Gfx::Bitmap const& Editor::breakpoint_icon_bitmap()
  395. {
  396. static auto bitmap = Gfx::Bitmap::try_load_from_file("/res/icons/16x16/breakpoint.png"sv).release_value_but_fixme_should_propagate_errors();
  397. return *bitmap;
  398. }
  399. Gfx::Bitmap const& Editor::current_position_icon_bitmap()
  400. {
  401. static auto bitmap = Gfx::Bitmap::try_load_from_file("/res/icons/16x16/go-forward.png"sv).release_value_but_fixme_should_propagate_errors();
  402. return *bitmap;
  403. }
  404. CodeDocument const& Editor::code_document() const
  405. {
  406. auto const& doc = document();
  407. VERIFY(doc.is_code_document());
  408. return static_cast<CodeDocument const&>(doc);
  409. }
  410. CodeDocument& Editor::code_document()
  411. {
  412. return const_cast<CodeDocument&>(static_cast<Editor const&>(*this).code_document());
  413. }
  414. void Editor::set_document(GUI::TextDocument& doc)
  415. {
  416. if (has_document() && &document() == &doc)
  417. return;
  418. VERIFY(doc.is_code_document());
  419. GUI::TextEditor::set_document(doc);
  420. set_override_cursor(Gfx::StandardCursor::IBeam);
  421. auto& code_document = static_cast<CodeDocument&>(doc);
  422. set_language_client_for(code_document);
  423. set_syntax_highlighter_for(code_document);
  424. if (m_language_client) {
  425. set_autocomplete_provider(make<LanguageServerAidedAutocompleteProvider>(*m_language_client));
  426. // NOTE:
  427. // When a file is opened for the first time in HackStudio, its content is already synced with the filesystem.
  428. // Otherwise, if the file has already been opened before in some Editor instance, it should exist in the LanguageServer's
  429. // FileDB, and the LanguageServer should already have its up-to-date content.
  430. // So it's OK to just pass an fd here (rather than the TextDocument's content).
  431. int fd = open(code_document.file_path().characters(), O_RDONLY | O_NOCTTY);
  432. if (fd < 0) {
  433. perror("open");
  434. return;
  435. }
  436. m_language_client->open_file(code_document.file_path(), fd);
  437. close(fd);
  438. } else {
  439. set_autocomplete_provider_for(code_document);
  440. }
  441. }
  442. Optional<Editor::AutoCompleteRequestData> Editor::get_autocomplete_request_data()
  443. {
  444. if (!wrapper().editor().m_language_client)
  445. return {};
  446. return Editor::AutoCompleteRequestData { cursor() };
  447. }
  448. void Editor::LanguageServerAidedAutocompleteProvider::provide_completions(Function<void(Vector<CodeComprehension::AutocompleteResultEntry>)> callback)
  449. {
  450. auto& editor = static_cast<Editor&>(*m_editor).wrapper().editor();
  451. auto data = editor.get_autocomplete_request_data();
  452. if (!data.has_value())
  453. callback({});
  454. m_language_client.on_autocomplete_suggestions = [callback = move(callback)](auto suggestions) {
  455. callback(suggestions);
  456. };
  457. m_language_client.request_autocomplete(
  458. editor.code_document().file_path(),
  459. data.value().position.line(),
  460. data.value().position.column());
  461. }
  462. void Editor::will_execute(GUI::TextDocumentUndoCommand const& command)
  463. {
  464. if (!m_language_client)
  465. return;
  466. if (is<GUI::InsertTextCommand>(command)) {
  467. auto const& insert_command = static_cast<GUI::InsertTextCommand const&>(command);
  468. m_language_client->insert_text(
  469. code_document().file_path(),
  470. insert_command.text(),
  471. insert_command.range().start().line(),
  472. insert_command.range().start().column());
  473. return;
  474. }
  475. if (is<GUI::RemoveTextCommand>(command)) {
  476. auto const& remove_command = static_cast<GUI::RemoveTextCommand const&>(command);
  477. m_language_client->remove_text(
  478. code_document().file_path(),
  479. remove_command.range().start().line(),
  480. remove_command.range().start().column(),
  481. remove_command.range().end().line(),
  482. remove_command.range().end().column());
  483. return;
  484. }
  485. VERIFY_NOT_REACHED();
  486. }
  487. void Editor::undo()
  488. {
  489. TextEditor::undo();
  490. flush_file_content_to_langauge_server();
  491. }
  492. void Editor::redo()
  493. {
  494. TextEditor::redo();
  495. flush_file_content_to_langauge_server();
  496. }
  497. void Editor::flush_file_content_to_langauge_server()
  498. {
  499. if (!m_language_client)
  500. return;
  501. m_language_client->set_file_content(
  502. code_document().file_path(),
  503. document().text());
  504. }
  505. void Editor::on_navigatable_link_click(const GUI::TextDocumentSpan& span)
  506. {
  507. auto span_text = document().text_in_range(span.range);
  508. auto header_path = span_text.substring(1, span_text.length() - 2);
  509. dbgln_if(EDITOR_DEBUG, "Ctrl+click: {} \"{}\"", span.range, header_path);
  510. navigate_to_include_if_available(header_path);
  511. }
  512. void Editor::on_identifier_click(const GUI::TextDocumentSpan& span)
  513. {
  514. if (!m_language_client)
  515. return;
  516. m_language_client->on_declaration_found = [](String const& file, size_t line, size_t column) {
  517. HackStudio::open_file(file, line, column);
  518. };
  519. m_language_client->search_declaration(code_document().file_path(), span.range.start().line(), span.range.start().column());
  520. }
  521. void Editor::set_cursor(const GUI::TextPosition& a_position)
  522. {
  523. TextEditor::set_cursor(a_position);
  524. }
  525. void Editor::set_syntax_highlighter_for(CodeDocument const& document)
  526. {
  527. switch (document.language()) {
  528. case Language::Cpp:
  529. if (m_use_semantic_syntax_highlighting) {
  530. set_syntax_highlighter(make<Cpp::SemanticSyntaxHighlighter>());
  531. on_token_info_timer_tick();
  532. m_tokens_info_timer->restart();
  533. } else
  534. set_syntax_highlighter(make<Cpp::SyntaxHighlighter>());
  535. break;
  536. case Language::CSS:
  537. set_syntax_highlighter(make<Web::CSS::SyntaxHighlighter>());
  538. break;
  539. case Language::GitCommit:
  540. set_syntax_highlighter(make<GUI::GitCommitSyntaxHighlighter>());
  541. break;
  542. case Language::GML:
  543. set_syntax_highlighter(make<GUI::GML::SyntaxHighlighter>());
  544. break;
  545. case Language::HTML:
  546. set_syntax_highlighter(make<Web::HTML::SyntaxHighlighter>());
  547. break;
  548. case Language::JavaScript:
  549. set_syntax_highlighter(make<JS::SyntaxHighlighter>());
  550. break;
  551. case Language::Ini:
  552. set_syntax_highlighter(make<GUI::IniSyntaxHighlighter>());
  553. break;
  554. case Language::Shell:
  555. set_syntax_highlighter(make<Shell::SyntaxHighlighter>());
  556. break;
  557. case Language::SQL:
  558. set_syntax_highlighter(make<SQL::AST::SyntaxHighlighter>());
  559. break;
  560. default:
  561. set_syntax_highlighter({});
  562. }
  563. force_rehighlight();
  564. }
  565. void Editor::set_autocomplete_provider_for(CodeDocument const& document)
  566. {
  567. switch (document.language()) {
  568. case Language::GML:
  569. set_autocomplete_provider(make<GUI::GML::AutocompleteProvider>());
  570. break;
  571. default:
  572. set_autocomplete_provider({});
  573. }
  574. }
  575. void Editor::set_language_client_for(CodeDocument const& document)
  576. {
  577. if (m_language_client && m_language_client->language() == document.language())
  578. return;
  579. if (document.language() == Language::Cpp)
  580. m_language_client = get_language_client<LanguageClients::Cpp::ConnectionToServer>(project().root_path());
  581. if (document.language() == Language::Shell)
  582. m_language_client = get_language_client<LanguageClients::Shell::ConnectionToServer>(project().root_path());
  583. if (m_language_client) {
  584. m_language_client->on_tokens_info_result = [this](Vector<CodeComprehension::TokenInfo> const& tokens_info) {
  585. on_tokens_info_result(tokens_info);
  586. };
  587. }
  588. }
  589. void Editor::keydown_event(GUI::KeyEvent& event)
  590. {
  591. TextEditor::keydown_event(event);
  592. if (m_tooltip_role == TooltipRole::ParametersHint) {
  593. s_tooltip_window->hide();
  594. m_tooltip_role.clear();
  595. }
  596. if (!event.shift() && !event.alt() && event.ctrl() && event.key() == KeyCode::Key_P) {
  597. handle_function_parameters_hint_request();
  598. }
  599. m_tokens_info_timer->restart();
  600. }
  601. void Editor::handle_function_parameters_hint_request()
  602. {
  603. if (!m_language_client)
  604. return;
  605. m_language_client->on_function_parameters_hint_result = [this](Vector<String> const& params, size_t argument_index) {
  606. dbgln("on_function_parameters_hint_result");
  607. StringBuilder html;
  608. for (size_t i = 0; i < params.size(); ++i) {
  609. if (i == argument_index)
  610. html.append("<b>"sv);
  611. html.appendff("{}", params[i]);
  612. if (i == argument_index)
  613. html.append("</b>"sv);
  614. if (i < params.size() - 1)
  615. html.append(", "sv);
  616. }
  617. html.append("<style>body { background-color: #dac7b5; }</style>"sv);
  618. s_tooltip_page_view->load_html(html.build(), {});
  619. auto cursor_rect = current_editor().cursor_content_rect().location().translated(screen_relative_rect().location());
  620. Gfx::Rect content(cursor_rect.x(), cursor_rect.y(), s_tooltip_page_view->children_clip_rect().width(), s_tooltip_page_view->children_clip_rect().height());
  621. m_tooltip_role = TooltipRole::ParametersHint;
  622. s_tooltip_window->set_rect(0, 0, 280, 35);
  623. s_tooltip_window->move_to(cursor_rect.x(), cursor_rect.y() - s_tooltip_window->height() - vertical_scrollbar().value());
  624. s_tooltip_window->show();
  625. };
  626. m_language_client->get_parameters_hint(
  627. code_document().file_path(),
  628. cursor().line(),
  629. cursor().column());
  630. }
  631. void Editor::set_debug_mode(bool enabled)
  632. {
  633. m_move_execution_to_line_action->set_enabled(enabled);
  634. }
  635. void Editor::on_token_info_timer_tick()
  636. {
  637. if (!semantic_syntax_highlighting_is_enabled())
  638. return;
  639. if (!m_language_client || !m_language_client->is_active_client())
  640. return;
  641. m_language_client->get_tokens_info(code_document().file_path());
  642. }
  643. void Editor::on_tokens_info_result(Vector<CodeComprehension::TokenInfo> const& tokens_info)
  644. {
  645. auto highlighter = syntax_highlighter();
  646. if (highlighter && highlighter->is_cpp_semantic_highlighter()) {
  647. auto& semantic_cpp_highlighter = verify_cast<Cpp::SemanticSyntaxHighlighter>(*highlighter);
  648. semantic_cpp_highlighter.update_tokens_info(tokens_info);
  649. force_rehighlight();
  650. }
  651. }
  652. void Editor::create_tokens_info_timer()
  653. {
  654. static constexpr size_t token_info_timer_interval_ms = 1000;
  655. m_tokens_info_timer = Core::Timer::create_repeating((int)token_info_timer_interval_ms, [this] {
  656. on_token_info_timer_tick();
  657. m_tokens_info_timer->stop();
  658. });
  659. m_tokens_info_timer->start();
  660. }
  661. void Editor::set_semantic_syntax_highlighting(bool value)
  662. {
  663. m_use_semantic_syntax_highlighting = value;
  664. set_syntax_highlighter_for(code_document());
  665. }
  666. }