Editor.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  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 Cursor 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 = 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::paint_event(GUI::PaintEvent& event)
  133. {
  134. GUI::TextEditor::paint_event(event);
  135. GUI::Painter painter(*this);
  136. if (is_focused()) {
  137. painter.add_clip_rect(event.rect());
  138. auto rect = frame_inner_rect();
  139. if (vertical_scrollbar().is_visible())
  140. rect.set_width(rect.width() - vertical_scrollbar().width());
  141. if (horizontal_scrollbar().is_visible())
  142. rect.set_height(rect.height() - horizontal_scrollbar().height());
  143. painter.draw_rect(rect, palette().selection());
  144. }
  145. }
  146. static HashMap<DeprecatedString, DeprecatedString>& man_paths()
  147. {
  148. static HashMap<DeprecatedString, DeprecatedString> paths;
  149. if (paths.is_empty()) {
  150. auto json = Config::read_string("HackStudio"sv, "Global"sv, "DocumentationSearchPaths"sv);
  151. AK::JsonParser parser(json);
  152. auto value_or_error = parser.parse();
  153. if (value_or_error.is_error())
  154. return paths;
  155. auto value = value_or_error.release_value();
  156. if (!value.is_array())
  157. return paths;
  158. for (auto& json_value : value.as_array().values()) {
  159. if (!json_value.is_string())
  160. continue;
  161. Core::DirIterator it(json_value.as_string(), Core::DirIterator::Flags::SkipDots);
  162. while (it.has_next()) {
  163. auto path = it.next_full_path();
  164. auto title = LexicalPath::title(path);
  165. paths.set(title, path);
  166. }
  167. }
  168. }
  169. return paths;
  170. }
  171. void Editor::show_documentation_tooltip_if_available(DeprecatedString const& hovered_token, Gfx::IntPoint screen_location)
  172. {
  173. auto it = man_paths().find(hovered_token);
  174. if (it == man_paths().end()) {
  175. dbgln_if(EDITOR_DEBUG, "no man path for {}", hovered_token);
  176. if (m_tooltip_role == TooltipRole::Documentation) {
  177. s_tooltip_window->hide();
  178. m_tooltip_role.clear();
  179. }
  180. return;
  181. }
  182. if (s_tooltip_window->is_visible() && m_tooltip_role == TooltipRole::Documentation && hovered_token == m_last_parsed_token) {
  183. return;
  184. }
  185. dbgln_if(EDITOR_DEBUG, "opening {}", it->value);
  186. auto file_or_error = Core::File::open(it->value, Core::File::OpenMode::Read);
  187. if (file_or_error.is_error()) {
  188. dbgln("Failed to open {}, {}", it->value, file_or_error.error());
  189. return;
  190. }
  191. auto buffer_or_error = file_or_error.release_value()->read_until_eof();
  192. if (buffer_or_error.is_error()) {
  193. dbgln("Couldn't read file: {}", buffer_or_error.error());
  194. return;
  195. }
  196. auto man_document = Markdown::Document::parse(buffer_or_error.release_value());
  197. if (!man_document) {
  198. dbgln("failed to parse markdown");
  199. return;
  200. }
  201. s_tooltip_page_view->load_html(man_document->render_to_html("<style>body { background-color: #dac7b5; }</style>"sv));
  202. s_tooltip_window->set_rect(0, 0, 500, 400);
  203. s_tooltip_window->move_to(screen_location.translated(4, 4));
  204. m_tooltip_role = TooltipRole::Documentation;
  205. s_tooltip_window->show();
  206. m_last_parsed_token = hovered_token;
  207. }
  208. void Editor::mousemove_event(GUI::MouseEvent& event)
  209. {
  210. GUI::TextEditor::mousemove_event(event);
  211. if (document().spans().is_empty())
  212. return;
  213. auto text_position = text_position_at(event.position());
  214. if (!text_position.is_valid() && m_tooltip_role == TooltipRole::Documentation) {
  215. s_tooltip_window->hide();
  216. m_tooltip_role.clear();
  217. return;
  218. }
  219. auto highlighter = wrapper().editor().syntax_highlighter();
  220. if (!highlighter)
  221. return;
  222. bool hide_tooltip = (m_tooltip_role == TooltipRole::Documentation);
  223. bool is_over_clickable = false;
  224. auto ruler_line_rect = ruler_content_rect(text_position.line());
  225. auto hovering_lines_ruler = (event.position().x() < ruler_line_rect.width());
  226. if (hovering_lines_ruler && !is_in_drag_select())
  227. set_override_cursor(Gfx::StandardCursor::Arrow);
  228. else if (m_hovering_editor)
  229. set_override_cursor(m_hovering_clickable && event.ctrl() ? Gfx::StandardCursor::Hand : Gfx::StandardCursor::IBeam);
  230. for (auto& span : document().spans()) {
  231. bool is_clickable = (highlighter->is_navigatable(span.data) || highlighter->is_identifier(span.data));
  232. if (span.range.contains(m_previous_text_position) && !span.range.contains(text_position)) {
  233. if (is_clickable && span.attributes.underline_style.has_value()) {
  234. span.attributes.underline_style.clear();
  235. wrapper().editor().update();
  236. }
  237. }
  238. if (span.range.contains(text_position)) {
  239. auto hovered_span_text = document().text_in_range(span.range);
  240. dbgln_if(EDITOR_DEBUG, "Hovering: {} \"{}\"", span.range, hovered_span_text);
  241. if (is_clickable) {
  242. is_over_clickable = true;
  243. bool was_underlined = span.attributes.underline_style.has_value();
  244. bool now_underlined = event.modifiers() & Mod_Ctrl;
  245. span.attributes.underline_style.clear();
  246. if (now_underlined)
  247. span.attributes.underline_style = Gfx::TextAttributes::UnderlineStyle::Solid;
  248. if (now_underlined != was_underlined) {
  249. wrapper().editor().update();
  250. }
  251. }
  252. if (highlighter->is_identifier(span.data)) {
  253. show_documentation_tooltip_if_available(hovered_span_text, event.position().translated(screen_relative_rect().location()));
  254. hide_tooltip = false;
  255. }
  256. }
  257. }
  258. m_previous_text_position = text_position;
  259. if (hide_tooltip) {
  260. s_tooltip_window->hide();
  261. m_tooltip_role.clear();
  262. }
  263. m_hovering_clickable = (is_over_clickable) && (event.modifiers() & Mod_Ctrl);
  264. }
  265. void Editor::mousedown_event(GUI::MouseEvent& event)
  266. {
  267. if (m_tooltip_role == TooltipRole::ParametersHint) {
  268. s_tooltip_window->hide();
  269. m_tooltip_role.clear();
  270. }
  271. auto highlighter = wrapper().editor().syntax_highlighter();
  272. if (!highlighter) {
  273. GUI::TextEditor::mousedown_event(event);
  274. return;
  275. }
  276. auto text_position = text_position_at(event.position());
  277. if (!(event.modifiers() & Mod_Ctrl)) {
  278. GUI::TextEditor::mousedown_event(event);
  279. return;
  280. }
  281. if (!text_position.is_valid()) {
  282. GUI::TextEditor::mousedown_event(event);
  283. return;
  284. }
  285. if (auto* span = document().span_at(text_position)) {
  286. if (highlighter->is_navigatable(span->data)) {
  287. on_navigatable_link_click(*span);
  288. return;
  289. }
  290. if (highlighter->is_identifier(span->data)) {
  291. on_identifier_click(*span);
  292. return;
  293. }
  294. }
  295. GUI::TextEditor::mousedown_event(event);
  296. }
  297. void Editor::drag_enter_event(GUI::DragEvent& event)
  298. {
  299. auto const& mime_types = event.mime_types();
  300. if (mime_types.contains_slow("text/uri-list"sv))
  301. event.accept();
  302. }
  303. void Editor::drop_event(GUI::DropEvent& event)
  304. {
  305. event.accept();
  306. if (event.mime_data().has_urls()) {
  307. auto urls = event.mime_data().urls();
  308. if (urls.is_empty())
  309. return;
  310. window()->move_to_front();
  311. if (urls.size() > 1) {
  312. GUI::MessageBox::show(window(), "HackStudio can only open one file at a time!"sv, "One at a time please!"sv, GUI::MessageBox::Type::Error);
  313. return;
  314. }
  315. set_current_editor_wrapper(static_cast<EditorWrapper*>(parent()));
  316. open_file(urls.first().serialize_path());
  317. }
  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<DeprecatedString, DeprecatedString>& include_paths()
  330. {
  331. static HashMap<DeprecatedString, DeprecatedString> paths;
  332. auto add_directory = [](DeprecatedString base, Optional<DeprecatedString> 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 (!FileSystem::is_directory(path)) {
  337. auto key = path.substring(base.length() + 1, path.length() - base.length() - 1);
  338. dbgln_if(EDITOR_DEBUG, "Adding header \"{}\" in path \"{}\"", key, path);
  339. paths.set(key, path);
  340. } else {
  341. handle_directory(base, path, handle_directory);
  342. }
  343. }
  344. };
  345. if (paths.is_empty()) {
  346. add_directory(".", {}, add_directory);
  347. add_directory("/usr/local/include", {}, add_directory);
  348. add_directory("/usr/local/include/c++/9.2.0", {}, add_directory);
  349. add_directory("/usr/include", {}, add_directory);
  350. }
  351. return paths;
  352. }
  353. void Editor::navigate_to_include_if_available(DeprecatedString path)
  354. {
  355. auto it = include_paths().find(path);
  356. if (it == include_paths().end()) {
  357. dbgln_if(EDITOR_DEBUG, "no header {} found.", path);
  358. return;
  359. }
  360. on_open(it->value);
  361. }
  362. void Editor::set_execution_position(size_t line_number)
  363. {
  364. if (execution_position().has_value())
  365. remove_gutter_indicator(m_execution_indicator_id, execution_position().value());
  366. add_gutter_indicator(m_execution_indicator_id, line_number);
  367. code_document().set_execution_position(line_number);
  368. scroll_position_into_view({ line_number, 0 });
  369. }
  370. void Editor::clear_execution_position()
  371. {
  372. if (!execution_position().has_value()) {
  373. return;
  374. }
  375. size_t previous_position = execution_position().value();
  376. code_document().clear_execution_position();
  377. remove_gutter_indicator(m_execution_indicator_id, previous_position);
  378. }
  379. Gfx::Bitmap const& Editor::breakpoint_icon_bitmap()
  380. {
  381. static auto bitmap = Gfx::Bitmap::load_from_file("/res/icons/16x16/breakpoint.png"sv).release_value_but_fixme_should_propagate_errors();
  382. return *bitmap;
  383. }
  384. Gfx::Bitmap const& Editor::current_position_icon_bitmap()
  385. {
  386. static auto bitmap = Gfx::Bitmap::load_from_file("/res/icons/16x16/go-forward.png"sv).release_value_but_fixme_should_propagate_errors();
  387. return *bitmap;
  388. }
  389. CodeDocument const& Editor::code_document() const
  390. {
  391. return verify_cast<CodeDocument const>(document());
  392. }
  393. CodeDocument& Editor::code_document()
  394. {
  395. return const_cast<CodeDocument&>(static_cast<Editor const&>(*this).code_document());
  396. }
  397. void Editor::set_document(GUI::TextDocument& doc)
  398. {
  399. if (has_document() && &document() == &doc)
  400. return;
  401. VERIFY(is<CodeDocument>(doc));
  402. GUI::TextEditor::set_document(doc);
  403. set_override_cursor(Gfx::StandardCursor::IBeam);
  404. auto& code_document = static_cast<CodeDocument&>(doc);
  405. set_language_client_for(code_document);
  406. set_syntax_highlighter_for(code_document);
  407. if (m_language_client) {
  408. set_autocomplete_provider(make<LanguageServerAidedAutocompleteProvider>(*m_language_client));
  409. // NOTE:
  410. // When a file is opened for the first time in HackStudio, its content is already synced with the filesystem.
  411. // Otherwise, if the file has already been opened before in some Editor instance, it should exist in the LanguageServer's
  412. // FileDB, and the LanguageServer should already have its up-to-date content.
  413. // So it's OK to just pass an fd here (rather than the TextDocument's content).
  414. int fd = open(code_document.file_path().characters(), O_RDONLY | O_NOCTTY);
  415. if (fd < 0) {
  416. perror("open");
  417. return;
  418. }
  419. m_language_client->open_file(code_document.file_path(), fd);
  420. close(fd);
  421. } else {
  422. set_autocomplete_provider_for(code_document);
  423. }
  424. }
  425. Optional<Editor::AutoCompleteRequestData> Editor::get_autocomplete_request_data()
  426. {
  427. if (!wrapper().editor().m_language_client)
  428. return {};
  429. return Editor::AutoCompleteRequestData { cursor() };
  430. }
  431. void Editor::LanguageServerAidedAutocompleteProvider::provide_completions(Function<void(Vector<CodeComprehension::AutocompleteResultEntry>)> callback)
  432. {
  433. auto& editor = static_cast<Editor&>(*m_editor).wrapper().editor();
  434. auto data = editor.get_autocomplete_request_data();
  435. if (!data.has_value())
  436. callback({});
  437. m_language_client.on_autocomplete_suggestions = [callback = move(callback)](auto suggestions) {
  438. callback(suggestions);
  439. };
  440. m_language_client.request_autocomplete(
  441. editor.code_document().file_path(),
  442. data.value().position.line(),
  443. data.value().position.column());
  444. }
  445. void Editor::after_execute(GUI::TextDocumentUndoCommand const& command)
  446. {
  447. if (!m_language_client)
  448. return;
  449. if (is<GUI::InsertTextCommand>(command)) {
  450. auto const& insert_command = static_cast<GUI::InsertTextCommand const&>(command);
  451. m_language_client->insert_text(
  452. code_document().file_path(),
  453. insert_command.text(),
  454. insert_command.range().start().line(),
  455. insert_command.range().start().column());
  456. return;
  457. }
  458. if (is<GUI::RemoveTextCommand>(command)) {
  459. auto const& remove_command = static_cast<GUI::RemoveTextCommand const&>(command);
  460. m_language_client->remove_text(
  461. code_document().file_path(),
  462. remove_command.range().start().line(),
  463. remove_command.range().start().column(),
  464. remove_command.range().end().line(),
  465. remove_command.range().end().column());
  466. return;
  467. }
  468. flush_file_content_to_langauge_server();
  469. }
  470. void Editor::undo()
  471. {
  472. TextEditor::undo();
  473. flush_file_content_to_langauge_server();
  474. }
  475. void Editor::redo()
  476. {
  477. TextEditor::redo();
  478. flush_file_content_to_langauge_server();
  479. }
  480. void Editor::flush_file_content_to_langauge_server()
  481. {
  482. if (!m_language_client)
  483. return;
  484. m_language_client->set_file_content(
  485. code_document().file_path(),
  486. document().text());
  487. }
  488. void Editor::on_navigatable_link_click(const GUI::TextDocumentSpan& span)
  489. {
  490. auto span_text = document().text_in_range(span.range);
  491. auto header_path = span_text.substring(1, span_text.length() - 2);
  492. dbgln_if(EDITOR_DEBUG, "Ctrl+click: {} \"{}\"", span.range, header_path);
  493. navigate_to_include_if_available(header_path);
  494. }
  495. void Editor::on_identifier_click(const GUI::TextDocumentSpan& span)
  496. {
  497. if (!m_language_client)
  498. return;
  499. m_language_client->on_declaration_found = [](DeprecatedString const& file, size_t line, size_t column) {
  500. HackStudio::open_file(file, line, column);
  501. };
  502. m_language_client->search_declaration(code_document().file_path(), span.range.start().line(), span.range.start().column());
  503. }
  504. void Editor::set_cursor(const GUI::TextPosition& a_position)
  505. {
  506. TextEditor::set_cursor(a_position);
  507. }
  508. void Editor::set_syntax_highlighter_for(CodeDocument const& document)
  509. {
  510. if (!document.language().has_value()) {
  511. set_syntax_highlighter({});
  512. force_rehighlight();
  513. return;
  514. }
  515. switch (document.language().value()) {
  516. case Syntax::Language::Cpp:
  517. if (m_use_semantic_syntax_highlighting) {
  518. set_syntax_highlighter(make<Cpp::SemanticSyntaxHighlighter>());
  519. on_token_info_timer_tick();
  520. m_tokens_info_timer->restart();
  521. } else {
  522. set_syntax_highlighter(make<Cpp::SyntaxHighlighter>());
  523. }
  524. break;
  525. case Syntax::Language::CMake:
  526. set_syntax_highlighter(make<CMake::SyntaxHighlighter>());
  527. break;
  528. case Syntax::Language::CMakeCache:
  529. set_syntax_highlighter(make<CMake::Cache::SyntaxHighlighter>());
  530. break;
  531. case Syntax::Language::CSS:
  532. set_syntax_highlighter(make<Web::CSS::SyntaxHighlighter>());
  533. break;
  534. case Syntax::Language::GitCommit:
  535. set_syntax_highlighter(make<GUI::GitCommitSyntaxHighlighter>());
  536. break;
  537. case Syntax::Language::GML:
  538. set_syntax_highlighter(make<GUI::GML::SyntaxHighlighter>());
  539. break;
  540. case Syntax::Language::HTML:
  541. set_syntax_highlighter(make<Web::HTML::SyntaxHighlighter>());
  542. break;
  543. case Syntax::Language::INI:
  544. set_syntax_highlighter(make<GUI::IniSyntaxHighlighter>());
  545. break;
  546. case Syntax::Language::JavaScript:
  547. set_syntax_highlighter(make<JS::SyntaxHighlighter>());
  548. break;
  549. case Syntax::Language::Markdown:
  550. set_syntax_highlighter(make<Markdown::SyntaxHighlighter>());
  551. break;
  552. case Syntax::Language::Shell:
  553. set_syntax_highlighter(make<Shell::SyntaxHighlighter>());
  554. break;
  555. case Syntax::Language::SQL:
  556. set_syntax_highlighter(make<SQL::AST::SyntaxHighlighter>());
  557. break;
  558. default:
  559. set_syntax_highlighter({});
  560. }
  561. force_rehighlight();
  562. }
  563. void Editor::set_autocomplete_provider_for(CodeDocument const& document)
  564. {
  565. if (document.language() == Syntax::Language::GML) {
  566. set_autocomplete_provider(make<GUI::GML::AutocompleteProvider>());
  567. } else {
  568. set_autocomplete_provider({});
  569. }
  570. }
  571. void Editor::set_language_client_for(CodeDocument const& document)
  572. {
  573. if (m_language_client && m_language_client->language() == document.language())
  574. return;
  575. if (document.language() == Syntax::Language::Cpp)
  576. m_language_client = get_language_client<LanguageClients::Cpp::ConnectionToServer>(project().root_path());
  577. if (document.language() == Syntax::Language::Shell)
  578. m_language_client = get_language_client<LanguageClients::Shell::ConnectionToServer>(project().root_path());
  579. if (m_language_client) {
  580. m_language_client->on_tokens_info_result = [this](Vector<CodeComprehension::TokenInfo> const& tokens_info) {
  581. on_tokens_info_result(tokens_info);
  582. };
  583. }
  584. }
  585. void Editor::keydown_event(GUI::KeyEvent& event)
  586. {
  587. TextEditor::keydown_event(event);
  588. if (m_tooltip_role == TooltipRole::ParametersHint) {
  589. s_tooltip_window->hide();
  590. m_tooltip_role.clear();
  591. }
  592. if (!event.shift() && !event.alt() && event.ctrl() && event.key() == KeyCode::Key_P) {
  593. handle_function_parameters_hint_request();
  594. }
  595. m_tokens_info_timer->restart();
  596. }
  597. void Editor::handle_function_parameters_hint_request()
  598. {
  599. if (!m_language_client)
  600. return;
  601. m_language_client->on_function_parameters_hint_result = [this](Vector<DeprecatedString> const& params, size_t argument_index) {
  602. dbgln("on_function_parameters_hint_result");
  603. StringBuilder html;
  604. for (size_t i = 0; i < params.size(); ++i) {
  605. if (i == argument_index)
  606. html.append("<b>"sv);
  607. html.appendff("{}", params[i]);
  608. if (i == argument_index)
  609. html.append("</b>"sv);
  610. if (i < params.size() - 1)
  611. html.append(", "sv);
  612. }
  613. html.append("<style>body { background-color: #dac7b5; }</style>"sv);
  614. s_tooltip_page_view->load_html(html.to_deprecated_string());
  615. auto cursor_rect = current_editor().cursor_content_rect().location().translated(screen_relative_rect().location());
  616. 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());
  617. m_tooltip_role = TooltipRole::ParametersHint;
  618. s_tooltip_window->set_rect(0, 0, 280, 35);
  619. s_tooltip_window->move_to(cursor_rect.x(), cursor_rect.y() - s_tooltip_window->height() - vertical_scrollbar().value());
  620. s_tooltip_window->show();
  621. };
  622. m_language_client->get_parameters_hint(
  623. code_document().file_path(),
  624. cursor().line(),
  625. cursor().column());
  626. }
  627. void Editor::set_debug_mode(bool enabled)
  628. {
  629. m_move_execution_to_line_action->set_enabled(enabled);
  630. }
  631. void Editor::on_token_info_timer_tick()
  632. {
  633. if (!semantic_syntax_highlighting_is_enabled())
  634. return;
  635. if (!m_language_client || !m_language_client->is_active_client())
  636. return;
  637. m_language_client->get_tokens_info(code_document().file_path());
  638. }
  639. void Editor::on_tokens_info_result(Vector<CodeComprehension::TokenInfo> const& tokens_info)
  640. {
  641. auto highlighter = syntax_highlighter();
  642. if (highlighter && highlighter->is_cpp_semantic_highlighter()) {
  643. auto& semantic_cpp_highlighter = verify_cast<Cpp::SemanticSyntaxHighlighter>(*highlighter);
  644. semantic_cpp_highlighter.update_tokens_info(tokens_info);
  645. force_rehighlight();
  646. }
  647. }
  648. void Editor::create_tokens_info_timer()
  649. {
  650. static constexpr size_t token_info_timer_interval_ms = 1000;
  651. m_tokens_info_timer = Core::Timer::create_repeating((int)token_info_timer_interval_ms, [this] {
  652. on_token_info_timer_tick();
  653. m_tokens_info_timer->stop();
  654. }).release_value_but_fixme_should_propagate_errors();
  655. m_tokens_info_timer->start();
  656. }
  657. void Editor::set_semantic_syntax_highlighting(bool value)
  658. {
  659. m_use_semantic_syntax_highlighting = value;
  660. set_syntax_highlighter_for(code_document());
  661. }
  662. ErrorOr<void> Editor::add_breakpoint(size_t line_number)
  663. {
  664. if (!breakpoint_lines().contains_slow(line_number)) {
  665. add_gutter_indicator(m_breakpoint_indicator_id, line_number);
  666. TRY(breakpoint_lines().try_append(line_number));
  667. Debugger::the().on_breakpoint_change(wrapper().filename_title(), line_number, BreakpointChange::Added);
  668. }
  669. return {};
  670. }
  671. void Editor::remove_breakpoint(size_t line_number)
  672. {
  673. remove_gutter_indicator(m_breakpoint_indicator_id, line_number);
  674. breakpoint_lines().remove_first_matching([&](size_t line) { return line == line_number; });
  675. Debugger::the().on_breakpoint_change(wrapper().filename_title(), line_number, BreakpointChange::Removed);
  676. }
  677. ErrorOr<void> Editor::update_git_diff_indicators()
  678. {
  679. clear_gutter_indicators(m_git_diff_indicator_id);
  680. if (!wrapper().git_repo())
  681. return {};
  682. Vector<CodeDocument::DiffType> line_differences;
  683. TRY(line_differences.try_ensure_capacity(document().line_count()));
  684. for (auto i = 0u; i < document().line_count(); ++i)
  685. line_differences.unchecked_append(CodeDocument::DiffType::None);
  686. for (auto const& hunk : wrapper().hunks()) {
  687. auto start_line = hunk.location.new_range.start_line;
  688. // Account for 1 indexed hunk location
  689. if (start_line != 0)
  690. start_line--;
  691. auto finish_line = start_line + hunk.location.new_range.number_of_lines;
  692. auto additions = hunk.location.new_range.number_of_lines;
  693. auto deletions = hunk.location.old_range.number_of_lines;
  694. for (size_t line_offset = 0; line_offset < additions; line_offset++) {
  695. auto line = start_line + line_offset;
  696. auto difference = (line_offset < deletions) ? CodeDocument::DiffType::ModifiedLine : CodeDocument::DiffType::AddedLine;
  697. line_differences[line] = difference;
  698. add_gutter_indicator(m_git_diff_indicator_id, line);
  699. }
  700. if (additions < deletions) {
  701. auto deletions_line = min(finish_line, line_count() - 1);
  702. line_differences[deletions_line] = CodeDocument::DiffType::DeletedLinesBefore;
  703. add_gutter_indicator(m_git_diff_indicator_id, deletions_line);
  704. }
  705. }
  706. code_document().set_line_differences({}, move(line_differences));
  707. update();
  708. return {};
  709. }
  710. }