GMLSyntaxHighlighter.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. * Copyright (c) 2020-2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibGUI/GMLLexer.h>
  7. #include <LibGUI/GMLSyntaxHighlighter.h>
  8. #include <LibGfx/Palette.h>
  9. namespace GUI {
  10. static Syntax::TextStyle style_for_token_type(const Gfx::Palette& palette, GMLToken::Type type)
  11. {
  12. switch (type) {
  13. case GMLToken::Type::LeftCurly:
  14. case GMLToken::Type::RightCurly:
  15. return { palette.syntax_punctuation() };
  16. case GMLToken::Type::ClassMarker:
  17. return { palette.syntax_keyword() };
  18. case GMLToken::Type::ClassName:
  19. return { palette.syntax_identifier(), true };
  20. case GMLToken::Type::Identifier:
  21. return { palette.syntax_identifier() };
  22. case GMLToken::Type::JsonValue:
  23. return { palette.syntax_string() };
  24. case GMLToken::Type::Comment:
  25. return { palette.syntax_comment() };
  26. default:
  27. return { palette.base_text() };
  28. }
  29. }
  30. bool GMLSyntaxHighlighter::is_identifier(u64 token) const
  31. {
  32. auto ini_token = static_cast<GUI::GMLToken::Type>(token);
  33. return ini_token == GUI::GMLToken::Type::Identifier;
  34. }
  35. void GMLSyntaxHighlighter::rehighlight(const Palette& palette)
  36. {
  37. auto text = m_client->get_text();
  38. GMLLexer lexer(text);
  39. auto tokens = lexer.lex();
  40. Vector<GUI::TextDocumentSpan> spans;
  41. for (auto& token : tokens) {
  42. GUI::TextDocumentSpan span;
  43. span.range.set_start({ token.m_start.line, token.m_start.column });
  44. span.range.set_end({ token.m_end.line, token.m_end.column });
  45. auto style = style_for_token_type(palette, token.m_type);
  46. span.attributes.color = style.color;
  47. span.attributes.bold = style.bold;
  48. span.is_skippable = false;
  49. span.data = static_cast<u64>(token.m_type);
  50. spans.append(span);
  51. }
  52. m_client->do_set_spans(move(spans));
  53. m_has_brace_buddies = false;
  54. highlight_matching_token_pair();
  55. m_client->do_update();
  56. }
  57. Vector<GMLSyntaxHighlighter::MatchingTokenPair> GMLSyntaxHighlighter::matching_token_pairs_impl() const
  58. {
  59. static Vector<MatchingTokenPair> pairs;
  60. if (pairs.is_empty()) {
  61. pairs.append({ static_cast<u64>(GMLToken::Type::LeftCurly), static_cast<u64>(GMLToken::Type::RightCurly) });
  62. }
  63. return pairs;
  64. }
  65. bool GMLSyntaxHighlighter::token_types_equal(u64 token1, u64 token2) const
  66. {
  67. return static_cast<GUI::GMLToken::Type>(token1) == static_cast<GUI::GMLToken::Type>(token2);
  68. }
  69. GMLSyntaxHighlighter::~GMLSyntaxHighlighter()
  70. {
  71. }
  72. }