AparokshaUI/adwaita-swift

Custom CSS loader and Window style

lambdaclan opened this issue · 2 comments

Is your feature request related to a problem? Please describe.

I am considering having beta releases along the stable releases for my app and would like to use the devel style class but it seems like the Window object does not expose a style method like other widgets.

Describe the solution you'd like

It would be nice to be able to add some custom styling through CSS to the various widgets. Maybe the style method could accept a CSS file/string? (per widget direct styling) or any other way of loading custom CSS through a provider (global styling - declare classes and attach them to widgets via a different call). Convention normally uses a file called style.css.

gtk-rs sample:

fn load_css() {
    // Load the CSS file and add it to the provider
    let provider = CssProvider::new();
    provider.load_from_string(include_str!("style.css"));

    // Add the provider to the default screen
    gtk::style_context_add_provider_for_display(
        &Display::default().expect("Could not connect to a display."),
        &provider,
        gtk::STYLE_PROVIDER_PRIORITY_APPLICATION,
    );
}

....

let button = gtk::Button::with_label("hover me!");
 button.add_css_class("button1"); // declared in style.css

let entry = gtk::Entry::new();
entry.add_css_class("entry1"); // declared in style.css

Specifically for my use case, I would like to style the Buttons in order to specify a custom icon size via -gtk-icon-size CSS property. Something like:

.custom-button {
  min-height: 48px;
  min-width: 48px;
  -gtk-icon-size: 32px;
}

Describe alternatives you've considered

For now as a workaround I am using a different widget (not a button) that allows custom sizing, but ideally we would be able to use custom CSS.

Additional context

References:

Thanks for this request! I implemented both:

  • Devel window: You can use the new devel(_:) modifier.
  • Custom CSS: Apply bits of CSS to a view that will be loaded once the view appears for the first time with the css(_:) modifier (it's then globally available and can be used with style(_:active:)). It's your choice whether to write the CSS directly as a string, read from a CSS file or use some kind of Swift CSS DSL. An example:
Button(label) {
    number = .random(in: 1...6)
}
.pill()
.suggested()
.style("custom-button")
.css {
    """
    .custom-button {
        background-color: @green_5;
    }
    """
}

Amazing work! I will test it right away and be back with more feedback if needed, thank you!