Editor.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859
  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 <AK/ByteBuffer.h>
  12. #include <AK/Debug.h>
  13. #include <AK/JsonParser.h>
  14. #include <AK/LexicalPath.h>
  15. #include <LibCMake/CMakeCache/SyntaxHighlighter.h>
  16. #include <LibCMake/SyntaxHighlighter.h>
  17. #include <LibConfig/Client.h>
  18. #include <LibCore/DirIterator.h>
  19. #include <LibCore/Timer.h>
  20. #include <LibCpp/SemanticSyntaxHighlighter.h>
  21. #include <LibCpp/SyntaxHighlighter.h>
  22. #include <LibFileSystem/FileSystem.h>
  23. #include <LibGUI/Action.h>
  24. #include <LibGUI/Application.h>
  25. #include <LibGUI/GML/AutocompleteProvider.h>
  26. #include <LibGUI/GML/SyntaxHighlighter.h>
  27. #include <LibGUI/GitCommitSyntaxHighlighter.h>
  28. #include <LibGUI/INISyntaxHighlighter.h>
  29. #include <LibGUI/Label.h>
  30. #include <LibGUI/MessageBox.h>
  31. #include <LibGUI/Painter.h>
  32. #include <LibGUI/Scrollbar.h>
  33. #include <LibGUI/Window.h>
  34. #include <LibJS/SyntaxHighlighter.h>
  35. #include <LibMarkdown/Document.h>
  36. #include <LibMarkdown/SyntaxHighlighter.h>
  37. #include <LibSQL/AST/SyntaxHighlighter.h>
  38. #include <LibSyntax/Language.h>
  39. #include <LibWeb/CSS/SyntaxHighlighter/SyntaxHighlighter.h>
  40. #include <LibWeb/DOM/Text.h>
  41. #include <LibWeb/HTML/HTMLHeadElement.h>
  42. #include <LibWeb/HTML/SyntaxHighlighter/SyntaxHighlighter.h>
  43. #include <LibWebView/OutOfProcessWebView.h>
  44. #include <Shell/SyntaxHighlighter.h>
  45. #include <fcntl.h>
  46. namespace HackStudio {
  47. enum class TooltipRole {
  48. Documentation,
  49. ParametersHint,
  50. };
  51. static RefPtr<GUI::Window> s_tooltip_window;
  52. static RefPtr<WebView::OutOfProcessWebView> s_tooltip_page_view;
  53. static Optional<TooltipRole> m_tooltip_role;
  54. ErrorOr<NonnullRefPtr<Editor>> Editor::try_create()
  55. {
  56. NonnullRefPtr<Editor> editor = TRY(adopt_nonnull_ref_or_enomem(new (nothrow) Editor()));
  57. TRY(initialize_tooltip_window());
  58. return editor;
  59. }
  60. Editor::Editor()
  61. {
  62. create_tokens_info_timer();
  63. set_document(CodeDocument::create());
  64. m_move_execution_to_line_action = GUI::Action::create("Set execution point to line", [this](auto&) {
  65. VERIFY(is_program_running());
  66. auto success = Debugger::the().set_execution_position(currently_open_file(), cursor().line());
  67. if (success) {
  68. set_execution_position(cursor().line());
  69. } else {
  70. GUI::MessageBox::show(window(), "Failed to set execution position"sv, "Error"sv, GUI::MessageBox::Type::Error);
  71. }
  72. });
  73. set_debug_mode(false);
  74. add_custom_context_menu_action(*m_move_execution_to_line_action);
  75. set_gutter_visible(true);
  76. on_gutter_click = [&](auto line, auto) {
  77. add_breakpoint(line).release_value_but_fixme_should_propagate_errors();
  78. };
  79. m_git_diff_indicator_id = register_gutter_indicator(
  80. [&](auto& painter, Gfx::IntRect rect, size_t line) {
  81. auto diff_type = code_document().line_difference(line);
  82. switch (diff_type) {
  83. case CodeDocument::DiffType::AddedLine:
  84. painter.draw_text(rect, "+"sv, font(), Gfx::TextAlignment::Center);
  85. break;
  86. case CodeDocument::DiffType::ModifiedLine:
  87. painter.draw_text(rect, "!"sv, font(), Gfx::TextAlignment::Center);
  88. break;
  89. case CodeDocument::DiffType::DeletedLinesBefore:
  90. painter.draw_text(rect, "-"sv, font(), Gfx::TextAlignment::Center);
  91. break;
  92. case CodeDocument::DiffType::None:
  93. VERIFY_NOT_REACHED();
  94. }
  95. }).release_value_but_fixme_should_propagate_errors();
  96. m_breakpoint_indicator_id = register_gutter_indicator(
  97. [&](auto& painter, Gfx::IntRect rect, size_t) {
  98. auto const& icon = breakpoint_icon_bitmap();
  99. painter.draw_scaled_bitmap(rect, icon, icon.rect());
  100. },
  101. [&](size_t line_index, auto) {
  102. remove_breakpoint(line_index);
  103. }).release_value_but_fixme_should_propagate_errors();
  104. m_execution_indicator_id = register_gutter_indicator(
  105. [&](auto& painter, Gfx::IntRect rect, size_t) {
  106. auto const& icon = current_position_icon_bitmap();
  107. painter.draw_scaled_bitmap(rect, icon, icon.rect());
  108. }).release_value_but_fixme_should_propagate_errors();
  109. if (Config::read_string("HackStudio"sv, "Global"sv, "DocumentationSearchPaths"sv).is_empty()) {
  110. Config::write_string("HackStudio"sv, "Global"sv, "DocumentationSearchPaths"sv, "[\"/usr/share/man/man2\", \"/usr/share/man/man3\"]"sv);
  111. }
  112. }
  113. ErrorOr<void> Editor::initialize_tooltip_window()
  114. {
  115. if (s_tooltip_window.is_null()) {
  116. s_tooltip_window = GUI::Window::construct();
  117. s_tooltip_window->set_window_type(GUI::WindowType::Tooltip);
  118. }
  119. if (s_tooltip_page_view.is_null()) {
  120. s_tooltip_page_view = TRY(s_tooltip_window->set_main_widget<WebView::OutOfProcessWebView>());
  121. }
  122. return {};
  123. }
  124. EditorWrapper& Editor::wrapper()
  125. {
  126. return static_cast<EditorWrapper&>(*parent());
  127. }
  128. EditorWrapper const& Editor::wrapper() const
  129. {
  130. return static_cast<EditorWrapper const&>(*parent());
  131. }
  132. void Editor::focusin_event(GUI::FocusEvent& event)
  133. {
  134. if (on_focus)
  135. on_focus();
  136. GUI::TextEditor::focusin_event(event);
  137. }
  138. void Editor::focusout_event(GUI::FocusEvent& event)
  139. {
  140. GUI::TextEditor::focusout_event(event);
  141. }
  142. Gfx::IntRect Editor::gutter_icon_rect(size_t line_number) const
  143. {
  144. return gutter_content_rect(line_number).translated(frame_thickness(), 0);
  145. }
  146. void Editor::paint_event(GUI::PaintEvent& event)
  147. {
  148. GUI::TextEditor::paint_event(event);
  149. GUI::Painter painter(*this);
  150. if (is_focused()) {
  151. painter.add_clip_rect(event.rect());
  152. auto rect = frame_inner_rect();
  153. if (vertical_scrollbar().is_visible())
  154. rect.set_width(rect.width() - vertical_scrollbar().width());
  155. if (horizontal_scrollbar().is_visible())
  156. rect.set_height(rect.height() - horizontal_scrollbar().height());
  157. painter.draw_rect(rect, palette().selection());
  158. }
  159. }
  160. static HashMap<DeprecatedString, DeprecatedString>& man_paths()
  161. {
  162. static HashMap<DeprecatedString, DeprecatedString> paths;
  163. if (paths.is_empty()) {
  164. auto json = Config::read_string("HackStudio"sv, "Global"sv, "DocumentationSearchPaths"sv);
  165. AK::JsonParser parser(json);
  166. auto value_or_error = parser.parse();
  167. if (value_or_error.is_error())
  168. return paths;
  169. auto value = value_or_error.release_value();
  170. if (!value.is_array())
  171. return paths;
  172. for (auto& json_value : value.as_array().values()) {
  173. if (!json_value.is_string())
  174. continue;
  175. Core::DirIterator it(json_value.as_string(), Core::DirIterator::Flags::SkipDots);
  176. while (it.has_next()) {
  177. auto path = it.next_full_path();
  178. auto title = LexicalPath::title(path);
  179. paths.set(title, path);
  180. }
  181. }
  182. }
  183. return paths;
  184. }
  185. void Editor::show_documentation_tooltip_if_available(DeprecatedString const& hovered_token, Gfx::IntPoint screen_location)
  186. {
  187. auto it = man_paths().find(hovered_token);
  188. if (it == man_paths().end()) {
  189. dbgln_if(EDITOR_DEBUG, "no man path for {}", hovered_token);
  190. if (m_tooltip_role == TooltipRole::Documentation) {
  191. s_tooltip_window->hide();
  192. m_tooltip_role.clear();
  193. }
  194. return;
  195. }
  196. if (s_tooltip_window->is_visible() && m_tooltip_role == TooltipRole::Documentation && hovered_token == m_last_parsed_token) {
  197. return;
  198. }
  199. dbgln_if(EDITOR_DEBUG, "opening {}", it->value);
  200. auto file_or_error = Core::File::open(it->value, Core::File::OpenMode::Read);
  201. if (file_or_error.is_error()) {
  202. dbgln("Failed to open {}, {}", it->value, file_or_error.error());
  203. return;
  204. }
  205. auto buffer_or_error = file_or_error.release_value()->read_until_eof();
  206. if (buffer_or_error.is_error()) {
  207. dbgln("Couldn't read file: {}", buffer_or_error.error());
  208. return;
  209. }
  210. auto man_document = Markdown::Document::parse(buffer_or_error.release_value());
  211. if (!man_document) {
  212. dbgln("failed to parse markdown");
  213. return;
  214. }
  215. s_tooltip_page_view->load_html(man_document->render_to_html("<style>body { background-color: #dac7b5; }</style>"sv), {});
  216. s_tooltip_window->set_rect(0, 0, 500, 400);
  217. s_tooltip_window->move_to(screen_location.translated(4, 4));
  218. m_tooltip_role = TooltipRole::Documentation;
  219. s_tooltip_window->show();
  220. m_last_parsed_token = hovered_token;
  221. }
  222. void Editor::mousemove_event(GUI::MouseEvent& event)
  223. {
  224. GUI::TextEditor::mousemove_event(event);
  225. if (document().spans().is_empty())
  226. return;
  227. auto text_position = text_position_at(event.position());
  228. if (!text_position.is_valid() && m_tooltip_role == TooltipRole::Documentation) {
  229. s_tooltip_window->hide();
  230. m_tooltip_role.clear();
  231. return;
  232. }
  233. auto highlighter = wrapper().editor().syntax_highlighter();
  234. if (!highlighter)
  235. return;
  236. bool hide_tooltip = (m_tooltip_role == TooltipRole::Documentation);
  237. bool is_over_clickable = false;
  238. auto ruler_line_rect = ruler_content_rect(text_position.line());
  239. auto hovering_lines_ruler = (event.position().x() < ruler_line_rect.width());
  240. if (hovering_lines_ruler && !is_in_drag_select())
  241. set_override_cursor(Gfx::StandardCursor::Arrow);
  242. else if (m_hovering_editor)
  243. set_override_cursor(m_hovering_clickable && event.ctrl() ? Gfx::StandardCursor::Hand : Gfx::StandardCursor::IBeam);
  244. for (auto& span : document().spans()) {
  245. bool is_clickable = (highlighter->is_navigatable(span.data) || highlighter->is_identifier(span.data));
  246. if (span.range.contains(m_previous_text_position) && !span.range.contains(text_position)) {
  247. if (is_clickable && span.attributes.underline_style.has_value()) {
  248. span.attributes.underline_style.clear();
  249. wrapper().editor().update();
  250. }
  251. }
  252. if (span.range.contains(text_position)) {
  253. auto hovered_span_text = document().text_in_range(span.range);
  254. dbgln_if(EDITOR_DEBUG, "Hovering: {} \"{}\"", span.range, hovered_span_text);
  255. if (is_clickable) {
  256. is_over_clickable = true;
  257. bool was_underlined = span.attributes.underline_style.has_value();
  258. bool now_underlined = event.modifiers() & Mod_Ctrl;
  259. span.attributes.underline_style.clear();
  260. if (now_underlined)
  261. span.attributes.underline_style = Gfx::TextAttributes::UnderlineStyle::Solid;
  262. if (now_underlined != 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. if (!(event.modifiers() & Mod_Ctrl)) {
  292. GUI::TextEditor::mousedown_event(event);
  293. return;
  294. }
  295. if (!text_position.is_valid()) {
  296. GUI::TextEditor::mousedown_event(event);
  297. return;
  298. }
  299. if (auto* span = document().span_at(text_position)) {
  300. if (highlighter->is_navigatable(span->data)) {
  301. on_navigatable_link_click(*span);
  302. return;
  303. }
  304. if (highlighter->is_identifier(span->data)) {
  305. on_identifier_click(*span);
  306. return;
  307. }
  308. }
  309. GUI::TextEditor::mousedown_event(event);
  310. }
  311. void Editor::drag_enter_event(GUI::DragEvent& event)
  312. {
  313. auto const& mime_types = event.mime_types();
  314. if (mime_types.contains_slow("text/uri-list"))
  315. event.accept();
  316. }
  317. void Editor::drop_event(GUI::DropEvent& event)
  318. {
  319. event.accept();
  320. if (event.mime_data().has_urls()) {
  321. auto urls = event.mime_data().urls();
  322. if (urls.is_empty())
  323. return;
  324. window()->move_to_front();
  325. if (urls.size() > 1) {
  326. GUI::MessageBox::show(window(), "HackStudio can only open one file at a time!"sv, "One at a time please!"sv, GUI::MessageBox::Type::Error);
  327. return;
  328. }
  329. set_current_editor_wrapper(static_cast<EditorWrapper*>(parent()));
  330. open_file(urls.first().serialize_path());
  331. }
  332. }
  333. void Editor::enter_event(Core::Event& event)
  334. {
  335. m_hovering_editor = true;
  336. GUI::TextEditor::enter_event(event);
  337. }
  338. void Editor::leave_event(Core::Event& event)
  339. {
  340. m_hovering_editor = false;
  341. GUI::TextEditor::leave_event(event);
  342. }
  343. static HashMap<DeprecatedString, DeprecatedString>& include_paths()
  344. {
  345. static HashMap<DeprecatedString, DeprecatedString> paths;
  346. auto add_directory = [](DeprecatedString base, Optional<DeprecatedString> recursive, auto handle_directory) -> void {
  347. Core::DirIterator it(recursive.value_or(base), Core::DirIterator::Flags::SkipDots);
  348. while (it.has_next()) {
  349. auto path = it.next_full_path();
  350. if (!FileSystem::is_directory(path)) {
  351. auto key = path.substring(base.length() + 1, path.length() - base.length() - 1);
  352. dbgln_if(EDITOR_DEBUG, "Adding header \"{}\" in path \"{}\"", key, path);
  353. paths.set(key, path);
  354. } else {
  355. handle_directory(base, path, handle_directory);
  356. }
  357. }
  358. };
  359. if (paths.is_empty()) {
  360. add_directory(".", {}, add_directory);
  361. add_directory("/usr/local/include", {}, add_directory);
  362. add_directory("/usr/local/include/c++/9.2.0", {}, add_directory);
  363. add_directory("/usr/include", {}, add_directory);
  364. }
  365. return paths;
  366. }
  367. void Editor::navigate_to_include_if_available(DeprecatedString path)
  368. {
  369. auto it = include_paths().find(path);
  370. if (it == include_paths().end()) {
  371. dbgln_if(EDITOR_DEBUG, "no header {} found.", path);
  372. return;
  373. }
  374. on_open(it->value);
  375. }
  376. void Editor::set_execution_position(size_t line_number)
  377. {
  378. if (execution_position().has_value())
  379. remove_gutter_indicator(m_execution_indicator_id, execution_position().value());
  380. add_gutter_indicator(m_execution_indicator_id, line_number);
  381. code_document().set_execution_position(line_number);
  382. scroll_position_into_view({ line_number, 0 });
  383. }
  384. void Editor::clear_execution_position()
  385. {
  386. if (!execution_position().has_value()) {
  387. return;
  388. }
  389. size_t previous_position = execution_position().value();
  390. code_document().clear_execution_position();
  391. remove_gutter_indicator(m_execution_indicator_id, previous_position);
  392. update(gutter_icon_rect(previous_position));
  393. }
  394. Gfx::Bitmap const& Editor::breakpoint_icon_bitmap()
  395. {
  396. static auto bitmap = Gfx::Bitmap::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::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::after_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. flush_file_content_to_langauge_server();
  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 = [](DeprecatedString 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. if (!document.language().has_value()) {
  528. set_syntax_highlighter({});
  529. force_rehighlight();
  530. return;
  531. }
  532. switch (document.language().value()) {
  533. case Syntax::Language::Cpp:
  534. if (m_use_semantic_syntax_highlighting) {
  535. set_syntax_highlighter(make<Cpp::SemanticSyntaxHighlighter>());
  536. on_token_info_timer_tick();
  537. m_tokens_info_timer->restart();
  538. } else {
  539. set_syntax_highlighter(make<Cpp::SyntaxHighlighter>());
  540. }
  541. break;
  542. case Syntax::Language::CMake:
  543. set_syntax_highlighter(make<CMake::SyntaxHighlighter>());
  544. break;
  545. case Syntax::Language::CMakeCache:
  546. set_syntax_highlighter(make<CMake::Cache::SyntaxHighlighter>());
  547. break;
  548. case Syntax::Language::CSS:
  549. set_syntax_highlighter(make<Web::CSS::SyntaxHighlighter>());
  550. break;
  551. case Syntax::Language::GitCommit:
  552. set_syntax_highlighter(make<GUI::GitCommitSyntaxHighlighter>());
  553. break;
  554. case Syntax::Language::GML:
  555. set_syntax_highlighter(make<GUI::GML::SyntaxHighlighter>());
  556. break;
  557. case Syntax::Language::HTML:
  558. set_syntax_highlighter(make<Web::HTML::SyntaxHighlighter>());
  559. break;
  560. case Syntax::Language::INI:
  561. set_syntax_highlighter(make<GUI::IniSyntaxHighlighter>());
  562. break;
  563. case Syntax::Language::JavaScript:
  564. set_syntax_highlighter(make<JS::SyntaxHighlighter>());
  565. break;
  566. case Syntax::Language::Markdown:
  567. set_syntax_highlighter(make<Markdown::SyntaxHighlighter>());
  568. break;
  569. case Syntax::Language::Shell:
  570. set_syntax_highlighter(make<Shell::SyntaxHighlighter>());
  571. break;
  572. case Syntax::Language::SQL:
  573. set_syntax_highlighter(make<SQL::AST::SyntaxHighlighter>());
  574. break;
  575. default:
  576. set_syntax_highlighter({});
  577. }
  578. force_rehighlight();
  579. }
  580. void Editor::set_autocomplete_provider_for(CodeDocument const& document)
  581. {
  582. if (document.language() == Syntax::Language::GML) {
  583. set_autocomplete_provider(make<GUI::GML::AutocompleteProvider>());
  584. } else {
  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() == Syntax::Language::Cpp)
  593. m_language_client = get_language_client<LanguageClients::Cpp::ConnectionToServer>(project().root_path());
  594. if (document.language() == Syntax::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. ErrorOr<void> Editor::add_breakpoint(size_t line_number)
  680. {
  681. if (!breakpoint_lines().contains_slow(line_number)) {
  682. add_gutter_indicator(m_breakpoint_indicator_id, line_number);
  683. TRY(breakpoint_lines().try_append(line_number));
  684. Debugger::the().on_breakpoint_change(wrapper().filename_title(), line_number, BreakpointChange::Added);
  685. }
  686. return {};
  687. }
  688. void Editor::remove_breakpoint(size_t line_number)
  689. {
  690. remove_gutter_indicator(m_breakpoint_indicator_id, line_number);
  691. breakpoint_lines().remove_first_matching([&](size_t line) { return line == line_number; });
  692. Debugger::the().on_breakpoint_change(wrapper().filename_title(), line_number, BreakpointChange::Removed);
  693. }
  694. ErrorOr<void> Editor::update_git_diff_indicators()
  695. {
  696. clear_gutter_indicators(m_git_diff_indicator_id);
  697. if (!wrapper().git_repo())
  698. return {};
  699. Vector<CodeDocument::DiffType> line_differences;
  700. TRY(line_differences.try_ensure_capacity(document().line_count()));
  701. for (auto i = 0u; i < document().line_count(); ++i)
  702. line_differences.unchecked_append(CodeDocument::DiffType::None);
  703. for (auto& hunk : wrapper().hunks()) {
  704. auto start_line = hunk.target_start_line;
  705. auto finish_line = start_line + hunk.added_lines.size();
  706. auto additions = hunk.added_lines.size();
  707. auto deletions = hunk.removed_lines.size();
  708. for (size_t line_offset = 0; line_offset < additions; line_offset++) {
  709. auto line = start_line + line_offset;
  710. auto difference = (line_offset < deletions) ? CodeDocument::DiffType::ModifiedLine : CodeDocument::DiffType::AddedLine;
  711. line_differences[line] = difference;
  712. add_gutter_indicator(m_git_diff_indicator_id, line);
  713. }
  714. if (additions < deletions) {
  715. auto deletions_line = min(finish_line, line_count() - 1);
  716. line_differences[deletions_line] = CodeDocument::DiffType::DeletedLinesBefore;
  717. add_gutter_indicator(m_git_diff_indicator_id, deletions_line);
  718. }
  719. }
  720. code_document().set_line_differences({}, move(line_differences));
  721. update();
  722. return {};
  723. }
  724. }