Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions linux/changelog.d/4109.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Picked editor schemes could differ from their previews and make code blocks and value placeholders hard to read.
128 changes: 111 additions & 17 deletions linux/crates/app/src/ui/assistant/code_block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,31 +8,28 @@ use sourceview5::prelude::*;

use crate::ui::handler_guard::HandlerGuard;

/// What a code block's buttons reach beyond it.
#[derive(Clone)]
pub(crate) struct BlockHooks {
pub settings: Rc<tablepro_linux_platform::AppSettings>,
/// Put the code in the editor.
pub insert: Rc<dyn Fn(String)>,
pub toast: Rc<dyn Fn(String)>,
}

/// One code block of a reply: highlighted as the editor is, with Copy
/// and Insert. A label rather than a text view: a text view lays its
/// text out in an idle that a running spinner can hold off, and until
/// then asks for the height of no text.
// A label measures streaming text synchronously; a text view waits for an idle
// that the running spinner can hold off.
pub(crate) struct CodeBlock {
root: gtk::Box,
shown: Rc<Shown>,
settings: Rc<tablepro_linux_platform::AppSettings>,
_theme: [HandlerGuard; 2],
}

/// The code and the label that shows it, with the buffer that colours it.
struct Shown {
code: RefCell<String>,
label: gtk::Label,
buffer: sourceview5::Buffer,
colors: gtk::CssProvider,
color_class: String,
}

impl CodeBlock {
Expand All @@ -50,16 +47,22 @@ impl CodeBlock {
.wrap(true)
.wrap_mode(gtk::pango::WrapMode::WordChar)
.selectable(true)
.margin_top(8)
.margin_bottom(8)
.margin_start(10)
.margin_end(10)
.build();
label.add_css_class("monospace");
let color_class = format!("code-{}", gtk::glib::uuid_string_random());
label.add_css_class(&color_class);
let colors = gtk::CssProvider::new();
gtk::style_context_add_provider_for_display(
&label.display(),
&colors,
gtk::STYLE_PROVIDER_PRIORITY_APPLICATION,
);
let shown = Rc::new(Shown {
code: RefCell::new(code.to_owned()),
label,
buffer,
colors,
color_class,
});
shown.paint(&hooks.settings.style_scheme());

Expand Down Expand Up @@ -116,7 +119,6 @@ impl CodeBlock {
&self.root
}

/// Show `code` in place of what the block shows, as a reply streams.
pub(crate) fn set_code(&self, code: &str) {
if *self.shown.code.borrow() == code {
return;
Expand All @@ -127,12 +129,23 @@ impl CodeBlock {
}

impl Shown {
/// Lay the code out in the label, coloured by the `scheme` the user
/// picked for the editor.
fn paint(&self, scheme: &str) {
let code = self.code.borrow();
self.buffer
.set_style_scheme(crate::ui::style_scheme_resolver::scheme(scheme).as_ref());
let scheme = crate::ui::style_scheme_resolver::scheme(scheme);
self.buffer.set_style_scheme(scheme.as_ref());
let text = gtk::TextTag::new(None);
if let Some(style) = scheme.as_ref().and_then(|scheme| scheme.style("text")) {
style.apply(&text);
}
// Only parsed colors enter CSS; a scheme file cannot supply declarations.
let foreground = text.foreground_rgba().filter(|_| text.is_foreground_set());
let background = text.background_rgba().filter(|_| text.is_background_set());
self.colors.load_from_string(&format!(
".{} {{ padding: 8px 10px; color: {}; background-color: {}; }}",
self.color_class,
foreground.map_or_else(|| "inherit".to_owned(), |color| color.to_string()),
background.map_or_else(|| "transparent".to_owned(), |color| color.to_string()),
));
self.buffer.set_text(&code);
let (start, end) = self.buffer.bounds();
self.buffer.ensure_highlight(&start, &end);
Expand Down Expand Up @@ -162,7 +175,12 @@ impl Shown {
}
}

/// What a highlighting tag sets, as text attributes.
impl Drop for Shown {
fn drop(&mut self) {
gtk::style_context_remove_provider_for_display(&self.label.display(), &self.colors);
}
}

fn tag_attributes(tag: &gtk::TextTag) -> Vec<gtk::pango::Attribute> {
let mut attributes = Vec::new();
let channels = |rgba: gtk::gdk::RGBA| {
Expand Down Expand Up @@ -219,6 +237,82 @@ mod tests {

use super::*;

fn background_pixel(label: &gtk::Label) -> [u8; 4] {
use gtk::gsk::prelude::*;

crate::test_support::after_next_frame(label);
let snapshot = gtk::Snapshot::new();
gtk::WidgetPaintable::new(Some(label)).snapshot(&snapshot, f64::from(label.width()), f64::from(label.height()));
let node = snapshot.to_node().expect("painted label");
let renderer = gtk::gsk::CairoRenderer::new();
renderer.realize(None::<&gtk::gdk::Surface>).expect("Cairo renderer");
let texture = renderer.render_texture(&node, None);
let mut download = gtk::gdk::TextureDownloader::new(&texture);
download.set_format(gtk::gdk::MemoryFormat::R8g8b8a8);
let (bytes, _) = download.download_bytes();
let pixel = bytes[..4].try_into().expect("one pixel");
renderer.unrealize();
pixel
}

#[gtk4::test]
fn style_scheme_colors_paint_the_code_foreground_and_background_together() {
adw::init().expect("libadwaita");
let settings = crate::test_support::MemorySettings::new();
let block = CodeBlock::new("SELECT name FROM users;", Some("sql"), &hooks(&settings));
let window = crate::test_support::OwnedWindow::presented(
gtk::Window::builder().child(block.widget()).default_width(400).build(),
);
let style = adw::StyleManager::default();
let previous = style.color_scheme();
for id in ["Adwaita-dark", "Adwaita"] {
settings.get().set_style_scheme(id).expect("a scheme");
for desktop in [adw::ColorScheme::ForceLight, adw::ColorScheme::ForceDark] {
style.set_color_scheme(desktop);
let scheme = block.shown.buffer.style_scheme().expect("a scheme");
assert_eq!(scheme.id(), id);
let text = gtk::TextTag::new(None);
scheme.style("text").expect("text style").apply(&text);
let foreground = text.foreground_rgba().expect("foreground");
let background = text.background_rgba().expect("background");
let pixel = background_pixel(&block.shown.label);
assert_eq!(block.shown.label.color(), foreground);
let byte = |value: f32| (value * 255.0).round() as u8;
assert_eq!(
pixel,
[
byte(background.red()),
byte(background.green()),
byte(background.blue()),
255
]
);
block.set_code("SELECT name FROM users WHERE id = 1;");
assert_eq!(block.shown.label.text(), "SELECT name FROM users WHERE id = 1;");
}
}
settings.get().set_style_scheme("").expect("automatic");
style.set_color_scheme(adw::ColorScheme::ForceLight);
assert_eq!(block.shown.buffer.style_scheme().expect("scheme").id(), "Adwaita");
style.set_color_scheme(adw::ColorScheme::ForceDark);
assert_eq!(block.shown.buffer.style_scheme().expect("scheme").id(), "Adwaita-dark");
drop(window);
style.set_color_scheme(previous);
}

#[gtk4::test]
fn dropping_a_code_block_releases_its_paint_and_theme_handlers() {
let settings = crate::test_support::MemorySettings::new();
let references = Rc::weak_count(settings.get());
let block = CodeBlock::new("plain code", Some("text"), &hooks(&settings));
let shown = Rc::downgrade(&block.shown);
let provider = block.shown.colors.downgrade();
drop(block);
assert!(shown.upgrade().is_none());
assert!(provider.upgrade().is_none());
assert_eq!(Rc::weak_count(settings.get()), references);
}

#[gtk4::test]
fn insert_hands_over_the_code_as_it_now_reads() {
let settings = crate::test_support::MemorySettings::new();
Expand Down
117 changes: 117 additions & 0 deletions linux/crates/app/src/ui/data_grid/row_detail/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use chrono::{NaiveDate, NaiveTime};
use gtk4::prelude::*;
use gtk4::subclass::prelude::*;
use gtk4::{self as gtk, gdk};
use sourceview5::prelude::*;
use tablepro_core::column::{TemporalZone, TimeRange};
use tablepro_core::edit::CellInput;
use tablepro_core::value::{JsonText, SqlTime, Temporal};
Expand Down Expand Up @@ -144,6 +145,122 @@ fn column_of(info: ColumnInfo) -> GridColumn {
grid_columns(&[info.result_column()], std::slice::from_ref(&info), |_| true)[0].clone()
}

fn assert_value_scheme(pane: &RowDetailPane, id: &str) {
let scheme = pane.imp().value_buffer.style_scheme().expect("the value's scheme");
assert_eq!(scheme.id(), id);
let expected = scheme.style("text").expect("the scheme text style");
let expected = gdk::RGBA::parse(expected.foreground().expect("the scheme foreground")).expect("a scheme color");
let attributes = pane
.imp()
.placeholder_label
.attributes()
.expect("placeholder attributes");
let attributes = attributes.attributes();
let color = attributes
.iter()
.find(|attribute| attribute.type_() == gtk::pango::AttrType::Foreground)
.and_then(|attribute| attribute.downcast_ref::<gtk::pango::AttrColor>())
.expect("the placeholder uses the scheme foreground")
.color();
let channel = |value: f32| (value * 65535.0).round() as u16;
assert_eq!(
(color.red(), color.green(), color.blue()),
(
channel(expected.red()),
channel(expected.green()),
channel(expected.blue())
)
);
assert!(
attributes
.iter()
.any(|attribute| { attribute == gtk::pango::AttrInt::new_style(gtk::pango::Style::Italic).upcast_ref() })
);
assert!(pane.imp().placeholder_label.has_css_class("dimmed"));
}

#[gtk4::test]
fn value_scheme_and_placeholders_keep_the_exact_pick_across_desktop_changes() {
let (grid, pane) = opened(
vec![named("id", "integer", true), named("quantity", "integer", false)],
vec![vec![Value::Int(1), Value::Null], vec![Value::Int(2), Value::Int(7)]],
);
let settings = &grid.grid.config().expect("grid settings").settings;
let style = libadwaita::StyleManager::default();
let previous = style.color_scheme();
for id in ["Adwaita-dark", "Adwaita"] {
settings.set_style_scheme(id).expect("a writable preference");
for desktop in [libadwaita::ColorScheme::ForceLight, libadwaita::ColorScheme::ForceDark] {
style.set_color_scheme(desktop);
grid.focus(0, 1);
assert!(pane.imp().placeholder_label.is_visible());
assert_eq!(pane.imp().placeholder_label.text(), "NULL");
assert_value_scheme(&pane, id);
grid.focus(1, 1);
assert_eq!(pane.typed_text(), "7");
assert!(!pane.imp().placeholder_label.is_visible());
assert_value_scheme(&pane, id);
type_value(&pane, "");
assert!(pane.imp().placeholder_label.is_visible());
assert_value_scheme(&pane, id);
type_value(&pane, "7");
}
}
style.set_color_scheme(previous);
}

#[gtk4::test]
fn automatic_value_scheme_recolors_the_placeholder_with_the_desktop() {
let (grid, pane) = opened(two_text_columns(), vec![vec![Value::Int(1), Value::Null]]);
grid.grid
.config()
.expect("grid settings")
.settings
.set_style_scheme("")
.expect("the automatic preference");
grid.focus(0, 1);
let style = libadwaita::StyleManager::default();
let previous = style.color_scheme();
for (desktop, expected) in [
(libadwaita::ColorScheme::ForceLight, "Adwaita"),
(libadwaita::ColorScheme::ForceDark, "Adwaita-dark"),
] {
style.set_color_scheme(desktop);
assert!(pane.imp().placeholder_label.is_visible());
assert_value_scheme(&pane, expected);
}
style.set_color_scheme(previous);
}

#[gtk4::test]
fn closed_value_editor_disconnects_scheme_and_placeholder_updates() {
let (grid, pane) = opened(two_text_columns(), vec![vec![Value::Int(1), Value::Null]]);
let settings = grid.grid.config().expect("grid settings").settings.clone();
settings
.set_style_scheme("Adwaita-dark")
.expect("a writable preference");
let buffer = pane.imp().value_buffer.get();
let placeholder = pane.imp().placeholder_label.get();
let attributes = placeholder.attributes().expect("placeholder attributes");
let weak_pane = pane.downgrade();
drop(pane);
drop(grid);
drain_main_context();
assert!(weak_pane.upgrade().is_none(), "the value editor outlived its grid");

settings.set_style_scheme("Adwaita").expect("a writable preference");
let style = libadwaita::StyleManager::default();
let previous = style.color_scheme();
style.set_color_scheme(libadwaita::ColorScheme::ForceLight);
style.set_color_scheme(libadwaita::ColorScheme::ForceDark);
assert_eq!(
buffer.style_scheme().expect("the retained buffer's scheme").id(),
"Adwaita-dark"
);
assert_eq!(placeholder.attributes().expect("retained attributes"), attributes);
style.set_color_scheme(previous);
}

#[gtk4::test]
fn the_pane_follows_the_focused_cell() {
let (grid, pane) = opened(two_text_columns(), two_text_values());
Expand Down
33 changes: 27 additions & 6 deletions linux/crates/app/src/ui/data_grid/row_detail/value_editor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,7 @@ use crate::ui::data_grid::{DataGrid, GridRow, PinnedRow};
use crate::ui::error_text::edit_parse_message;
use crate::ui::handler_guard::HandlerGuard;

/// The scheme a grid without settings paints with, as the multi-line
/// editor did. The resolver follows it to its dark variant.
const FALLBACK_SCHEME: &str = "Adwaita";
const FALLBACK_SCHEME: &str = "";

/// The value editor's own key handler, named so it can be told from the
/// view's.
Expand Down Expand Up @@ -501,12 +499,12 @@ impl RowDetailPane {
grid.refresh_actions();
}

/// The SQL editor's scheme where the grid has the settings, in the
/// variant for the current style, following a switch of either.
fn follow_style_scheme(&self, grid: &DataGrid) {
let settings = grid.config().map(|config| config.settings.clone());
let paint = {
let buffer = self.imp().value_buffer.get().downgrade();
let placeholder = self.imp().placeholder_label.get().downgrade();
let placeholder_attributes = self.imp().placeholder_label.attributes();
let settings = settings.as_ref().map(Rc::downgrade);
Rc::new(move || {
let Some(buffer) = buffer.upgrade() else {
Expand All @@ -516,7 +514,30 @@ impl RowDetailPane {
.as_ref()
.and_then(Weak::upgrade)
.map_or_else(|| FALLBACK_SCHEME.to_owned(), |settings| settings.style_scheme());
buffer.set_style_scheme(crate::ui::style_scheme_resolver::scheme(&preferred).as_ref());
let scheme = crate::ui::style_scheme_resolver::scheme(&preferred);
buffer.set_style_scheme(scheme.as_ref());
if let Some(placeholder) = placeholder.upgrade() {
// The placeholder sits over the source view's background, so
// its text must use that scheme too, even without a value.
let attributes = placeholder_attributes
.as_ref()
.and_then(gtk::pango::AttrList::copy)
.unwrap_or_default();
let tag = gtk::TextTag::new(None);
if let Some(text) = scheme.and_then(|scheme| scheme.style("text")) {
text.apply(&tag);
}
if let Some(rgba) = tag.foreground_rgba().filter(|_| tag.is_foreground_set()) {
let channel = |value: f32| (value.clamp(0.0, 1.0) * 65535.0).round() as u16;
attributes.insert(gtk::pango::AttrColor::new_foreground(
channel(rgba.red()),
channel(rgba.green()),
channel(rgba.blue()),
));
attributes.insert(gtk::pango::AttrInt::new_foreground_alpha(channel(rgba.alpha())));
}
placeholder.set_attributes(Some(&attributes));
}
})
};
paint();
Expand Down
Loading
Loading