From 2dcf0529d17ba7b611efdb0350fb4d9906a1f2bc Mon Sep 17 00:00:00 2001 From: Shaun Reed Date: Sat, 12 Apr 2025 13:33:39 -0400 Subject: [PATCH] Custom highlighting to fix UI bugs. + Selecting text caused blurry editor view. + Now prefers syntect theme background color over QML background color. --- src/filesystem.rs | 52 +++++++++++++++++++++++++++++++++-------------- 1 file changed, 37 insertions(+), 15 deletions(-) diff --git a/src/filesystem.rs b/src/filesystem.rs index 7306b2c..2c39d7f 100644 --- a/src/filesystem.rs +++ b/src/filesystem.rs @@ -43,10 +43,13 @@ use cxx_qt_lib::{QModelIndex, QString}; use dirs; use log::warn; use std::fs; -use std::fs::FileType; -use syntect::highlighting::{Style, ThemeSet}; +use std::io::BufRead; +use syntect::easy::HighlightFile; +use syntect::highlighting::ThemeSet; +use syntect::html::{ + IncludeBackground, append_highlighted_html_for_styled_line, start_highlighted_html_snippet, +}; use syntect::parsing::SyntaxSet; -use syntect::html::highlighted_html_for_file; // TODO: Impleent a provider for QFileSystemModel::setIconProvider for icons. pub struct FileSystemImpl { @@ -69,23 +72,42 @@ impl qobject::FileSystem { if path.is_empty() { return QString::default(); } - if fs::metadata(path.to_string()) + if !fs::metadata(path.to_string()) .expect(format!("Failed to get file metadata {}", path).as_str()) .is_file() { - let ps = SyntaxSet::load_defaults_nonewlines(); - let ts = ThemeSet::load_defaults(); - - if let Ok(result) = highlighted_html_for_file(std::path::Path::new(&path.to_string()), &ps, &ts.themes["base16-ocean.dark"]) { - QString::from(result) - } else { - warn!("Failed to read file {}", path); - QString::default() - } - } else { warn!("Attempted to open file {} that is not a valid file", path); - QString::default() + return QString::default(); } + let ss = SyntaxSet::load_defaults_nonewlines(); + let ts = ThemeSet::load_defaults(); + let theme = &ts.themes["base16-ocean.dark"]; + + let mut highlighter = + HighlightFile::new(path.to_string(), &ss, theme).expect("Failed to create highlighter"); + let (mut output, _bg) = start_highlighted_html_snippet(theme); + let mut line = String::new(); + while highlighter + .reader + .read_line(&mut line) + .expect("Failed to read file.") + > 0 + { + let regions = highlighter + .highlight_lines + .highlight_line(&line, &ss) + .expect("Failed to highlight"); + + append_highlighted_html_for_styled_line( + ®ions[..], + IncludeBackground::Yes, + &mut output, + ) + .expect("Failed to insert highlighted html"); + line.clear(); + } + output.push_str("\n"); + QString::from(output) } // There will never be more than one column.