LibWebView: Normalize source-code text before highlighting it

The previous code to determine the SourceDocument's lines was too naive:
the source text can contain other newline characters and sequences, and
the HTML/CSS/JS syntax highlighters would take those into account when
determining what line a token is on. This disagreement would cause
incorrect highlighting, or even crashes, if the source didn't solely use
`\n` for its newlines.

In order to have everyone agree on what a line is, this patch first
processes the source to replace all newlines with `\n`. The need to
copy the source like this is unfortunate, but viewing the source is a
rare enough action that this should not cause any noticeable
performance problems.

As the callers have a String, and we want a String, this also changes
the function parameters to keep the source as a String instead of
converting it to StringView and back.

Fixes https://github.com/LadybirdBrowser/ladybird/issues/3169
This commit is contained in:
Sam Atkins 2025-01-08 13:47:24 +00:00
commit 6147557999
Notes: github-actions[bot] 2025-02-04 08:50:24 +00:00
2 changed files with 45 additions and 12 deletions

View file

@ -24,7 +24,7 @@ enum class HighlightOutputMode {
class SourceDocument final : public Syntax::Document {
public:
static NonnullRefPtr<SourceDocument> create(StringView source)
static NonnullRefPtr<SourceDocument> create(String const& source)
{
return adopt_ref(*new (nothrow) SourceDocument(source));
}
@ -38,18 +38,18 @@ public:
virtual Syntax::TextDocumentLine& line(size_t line_index) override;
private:
SourceDocument(StringView source);
SourceDocument(String const& source);
// ^ Syntax::Document
virtual void update_views(Badge<Syntax::TextDocumentLine>) override { }
StringView m_source;
String m_source;
Vector<Syntax::TextDocumentLine> m_lines;
};
class SourceHighlighterClient final : public Syntax::HighlighterClient {
public:
SourceHighlighterClient(StringView source, Syntax::Language);
SourceHighlighterClient(String const& source, Syntax::Language);
virtual ~SourceHighlighterClient() = default;
String to_html_string(URL::URL const& url, URL::URL const& base_url, HighlightOutputMode) const;
@ -75,7 +75,7 @@ private:
OwnPtr<Syntax::Highlighter> m_highlighter;
};
String highlight_source(URL::URL const& url, URL::URL const& base_url, StringView, Syntax::Language, HighlightOutputMode);
String highlight_source(URL::URL const& url, URL::URL const& base_url, String const& source, Syntax::Language, HighlightOutputMode);
constexpr inline StringView HTML_HIGHLIGHTER_STYLE = R"~~~(
@media (prefers-color-scheme: dark) {