Editor.cpp 26 KB

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