feat(client): redesign native UI, themes, settings and avatars
Separate conversation drafts and voice view state, add native settings and restricted CSS themes, implement validated avatar cropping, and refresh dependencies with documented desktop compatibility backports.
This commit is contained in:
parent
44d284a568
commit
8e5ab56611
276 changed files with 53546 additions and 3399 deletions
382
patches/sctk-adwaita/src/buttons.rs
vendored
Normal file
382
patches/sctk-adwaita/src/buttons.rs
vendored
Normal file
|
|
@ -0,0 +1,382 @@
|
|||
use log::{debug, warn};
|
||||
use smithay_client_toolkit::reexports::csd_frame::{WindowManagerCapabilities, WindowState};
|
||||
use tiny_skia::{FillRule, PathBuilder, PixmapMut, Rect, Stroke, Transform};
|
||||
|
||||
use crate::{theme::ColorMap, Location, SkiaResult};
|
||||
|
||||
/// The size of the button on the header bar in logical points.
|
||||
const BUTTON_SIZE: f32 = 24.;
|
||||
const BUTTON_MARGIN: f32 = 5.;
|
||||
const BUTTON_SPACING: f32 = 13.;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Buttons {
|
||||
// Sorted by order vec of buttons for the left and right sides
|
||||
buttons_left: Vec<Button>,
|
||||
buttons_right: Vec<Button>,
|
||||
layout_config: Option<(String, String)>,
|
||||
}
|
||||
|
||||
type ButtonLayout = (Vec<Button>, Vec<Button>);
|
||||
|
||||
impl Default for Buttons {
|
||||
fn default() -> Self {
|
||||
let (buttons_left, buttons_right) = Buttons::get_default_buttons_layout();
|
||||
|
||||
Self {
|
||||
buttons_left,
|
||||
buttons_right,
|
||||
layout_config: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Buttons {
|
||||
pub fn new(layout_config: Option<(String, String)>) -> Self {
|
||||
match Buttons::parse_button_layout(layout_config.clone()) {
|
||||
Some((buttons_left, buttons_right)) => Self {
|
||||
buttons_left,
|
||||
buttons_right,
|
||||
layout_config,
|
||||
},
|
||||
_ => Self::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Rearrange the buttons with the new width.
|
||||
pub fn arrange(&mut self, width: u32, margin_h: f32) {
|
||||
let mut left_x = BUTTON_MARGIN + margin_h;
|
||||
let mut right_x = width as f32 - BUTTON_MARGIN;
|
||||
|
||||
for button in &mut self.buttons_left {
|
||||
button.offset = left_x;
|
||||
|
||||
// Add the button size plus spacing
|
||||
left_x += BUTTON_SIZE + BUTTON_SPACING;
|
||||
}
|
||||
|
||||
for button in &mut self.buttons_right {
|
||||
// Subtract the button size.
|
||||
right_x -= BUTTON_SIZE;
|
||||
|
||||
// Update it
|
||||
button.offset = right_x;
|
||||
|
||||
// Subtract spacing for the next button.
|
||||
right_x -= BUTTON_SPACING;
|
||||
}
|
||||
}
|
||||
|
||||
/// Find the coordinate of the button.
|
||||
pub fn find_button(&self, x: f64, y: f64) -> Location {
|
||||
let x = x as f32;
|
||||
let y = y as f32;
|
||||
let buttons = self.buttons_left.iter().chain(self.buttons_right.iter());
|
||||
|
||||
for button in buttons {
|
||||
if button.contains(x, y) {
|
||||
return Location::Button(button.kind);
|
||||
}
|
||||
}
|
||||
|
||||
Location::Head
|
||||
}
|
||||
|
||||
pub fn update_wm_capabilities(&mut self, wm_capabilites: WindowManagerCapabilities) {
|
||||
let supports_maximize = wm_capabilites.contains(WindowManagerCapabilities::MAXIMIZE);
|
||||
let supports_minimize = wm_capabilites.contains(WindowManagerCapabilities::MINIMIZE);
|
||||
|
||||
self.update_buttons(supports_maximize, supports_minimize);
|
||||
}
|
||||
|
||||
pub fn update_buttons(&mut self, supports_maximize: bool, supports_minimize: bool) {
|
||||
let is_supported = |button: &Button| match button.kind {
|
||||
ButtonKind::Close => true,
|
||||
ButtonKind::Maximize => supports_maximize,
|
||||
ButtonKind::Minimize => supports_minimize,
|
||||
};
|
||||
|
||||
let (buttons_left, buttons_right) =
|
||||
Buttons::parse_button_layout(self.layout_config.clone())
|
||||
.unwrap_or_else(Buttons::get_default_buttons_layout);
|
||||
|
||||
self.buttons_left = buttons_left.into_iter().filter(is_supported).collect();
|
||||
self.buttons_right = buttons_right.into_iter().filter(is_supported).collect();
|
||||
}
|
||||
|
||||
pub fn right_buttons_start_x(&self) -> Option<f32> {
|
||||
self.buttons_right.last().map(|button| button.x())
|
||||
}
|
||||
|
||||
pub fn left_buttons_end_x(&self) -> Option<f32> {
|
||||
self.buttons_left.last().map(|button| button.end_x())
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn draw(
|
||||
&self,
|
||||
start_x: f32,
|
||||
end_x: f32,
|
||||
scale: f32,
|
||||
colors: &ColorMap,
|
||||
mouse_location: Location,
|
||||
pixmap: &mut PixmapMut,
|
||||
resizable: bool,
|
||||
state: &WindowState,
|
||||
) {
|
||||
let left_buttons_right_limit =
|
||||
self.right_buttons_start_x().unwrap_or(end_x).min(end_x) - BUTTON_SPACING;
|
||||
let buttons_left = self.buttons_left.iter().map(|x| (x, Side::Left));
|
||||
let buttons_right = self.buttons_right.iter().map(|x| (x, Side::Right));
|
||||
|
||||
for (button, side) in buttons_left.chain(buttons_right) {
|
||||
let is_visible = button.x() > start_x && button.end_x() < end_x
|
||||
// If we have buttons from both sides and they overlap, prefer the right side
|
||||
&& (side == Side::Right || button.end_x() < left_buttons_right_limit);
|
||||
|
||||
if is_visible {
|
||||
button.draw(scale, colors, mouse_location, pixmap, resizable, state);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_button_layout(sides: Option<(String, String)>) -> Option<ButtonLayout> {
|
||||
let Some((left_side, right_side)) = sides else {
|
||||
return None;
|
||||
};
|
||||
|
||||
let buttons_left = Buttons::parse_button_layout_side(left_side, Side::Left);
|
||||
let buttons_right = Buttons::parse_button_layout_side(right_side, Side::Right);
|
||||
|
||||
if buttons_left.is_empty() && buttons_right.is_empty() {
|
||||
warn!("No valid buttons found in configuration");
|
||||
return None;
|
||||
}
|
||||
|
||||
Some((buttons_left, buttons_right))
|
||||
}
|
||||
|
||||
fn parse_button_layout_side(config: String, side: Side) -> Vec<Button> {
|
||||
let mut buttons: Vec<Button> = vec![];
|
||||
|
||||
for button in config.split(',').take(3) {
|
||||
let button_kind = match button {
|
||||
"close" => ButtonKind::Close,
|
||||
"maximize" => ButtonKind::Maximize,
|
||||
"minimize" => ButtonKind::Minimize,
|
||||
"appmenu" => {
|
||||
debug!("Ignoring \"appmenu\" button");
|
||||
continue;
|
||||
}
|
||||
_ => {
|
||||
warn!("Ignoring unknown button type: {button}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
buttons.push(Button::new(button_kind));
|
||||
}
|
||||
|
||||
// For the right side, we need to revert the order
|
||||
if side == Side::Right {
|
||||
buttons.into_iter().rev().collect()
|
||||
} else {
|
||||
buttons
|
||||
}
|
||||
}
|
||||
|
||||
fn get_default_buttons_layout() -> ButtonLayout {
|
||||
(
|
||||
vec![],
|
||||
vec![
|
||||
Button::new(ButtonKind::Close),
|
||||
Button::new(ButtonKind::Maximize),
|
||||
Button::new(ButtonKind::Minimize),
|
||||
],
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct Button {
|
||||
/// The button offset into the header bar canvas.
|
||||
offset: f32,
|
||||
/// The kind of the button.
|
||||
kind: ButtonKind,
|
||||
}
|
||||
|
||||
impl Button {
|
||||
pub fn new(kind: ButtonKind) -> Self {
|
||||
Self { offset: 0., kind }
|
||||
}
|
||||
|
||||
pub fn radius(&self) -> f32 {
|
||||
BUTTON_SIZE / 2.0
|
||||
}
|
||||
|
||||
pub fn x(&self) -> f32 {
|
||||
self.offset
|
||||
}
|
||||
|
||||
pub fn center_x(&self) -> f32 {
|
||||
self.offset + self.radius()
|
||||
}
|
||||
|
||||
pub fn center_y(&self) -> f32 {
|
||||
BUTTON_MARGIN + self.radius()
|
||||
}
|
||||
|
||||
pub fn end_x(&self) -> f32 {
|
||||
self.offset + BUTTON_SIZE
|
||||
}
|
||||
|
||||
fn contains(&self, x: f32, y: f32) -> bool {
|
||||
x > self.offset
|
||||
&& x < self.offset + BUTTON_SIZE
|
||||
&& y > BUTTON_MARGIN
|
||||
&& y < BUTTON_MARGIN + BUTTON_SIZE
|
||||
}
|
||||
|
||||
pub fn draw(
|
||||
&self,
|
||||
scale: f32,
|
||||
colors: &ColorMap,
|
||||
mouse_location: Location,
|
||||
pixmap: &mut PixmapMut,
|
||||
resizable: bool,
|
||||
state: &WindowState,
|
||||
) -> SkiaResult {
|
||||
let button_bg = if mouse_location == Location::Button(self.kind)
|
||||
&& (resizable || self.kind != ButtonKind::Maximize)
|
||||
{
|
||||
colors.button_hover_paint()
|
||||
} else {
|
||||
colors.button_idle_paint()
|
||||
};
|
||||
|
||||
// Convert to pixels.
|
||||
let x = self.center_x() * scale;
|
||||
let y = self.center_y() * scale;
|
||||
let radius = self.radius() * scale;
|
||||
|
||||
// Draw the button background.
|
||||
let circle = PathBuilder::from_circle(x, y, radius)?;
|
||||
pixmap.fill_path(
|
||||
&circle,
|
||||
&button_bg,
|
||||
FillRule::Winding,
|
||||
Transform::identity(),
|
||||
None,
|
||||
);
|
||||
|
||||
let mut button_icon_paint = colors.button_icon_paint();
|
||||
// Do AA only for diagonal lines.
|
||||
button_icon_paint.anti_alias = self.kind == ButtonKind::Close;
|
||||
|
||||
// Draw the icon.
|
||||
match self.kind {
|
||||
ButtonKind::Close => {
|
||||
let x_icon = {
|
||||
let size = 3.5 * scale;
|
||||
let mut pb = PathBuilder::new();
|
||||
|
||||
{
|
||||
let sx = x - size;
|
||||
let sy = y - size;
|
||||
let ex = x + size;
|
||||
let ey = y + size;
|
||||
|
||||
pb.move_to(sx, sy);
|
||||
pb.line_to(ex, ey);
|
||||
pb.close();
|
||||
}
|
||||
|
||||
{
|
||||
let sx = x - size;
|
||||
let sy = y + size;
|
||||
let ex = x + size;
|
||||
let ey = y - size;
|
||||
|
||||
pb.move_to(sx, sy);
|
||||
pb.line_to(ex, ey);
|
||||
pb.close();
|
||||
}
|
||||
|
||||
pb.finish()?
|
||||
};
|
||||
|
||||
pixmap.stroke_path(
|
||||
&x_icon,
|
||||
&button_icon_paint,
|
||||
&Stroke {
|
||||
width: 1.1 * scale,
|
||||
..Default::default()
|
||||
},
|
||||
Transform::identity(),
|
||||
None,
|
||||
);
|
||||
}
|
||||
ButtonKind::Maximize => {
|
||||
let path2 = {
|
||||
let size = 8.0 * scale;
|
||||
let hsize = size / 2.0;
|
||||
let mut pb = PathBuilder::new();
|
||||
|
||||
let x = x - hsize;
|
||||
let y = y - hsize;
|
||||
if state.contains(WindowState::MAXIMIZED) {
|
||||
let offset = 2.0 * scale;
|
||||
if let Some(rect) =
|
||||
Rect::from_xywh(x, y + offset, size - offset, size - offset)
|
||||
{
|
||||
pb.push_rect(rect);
|
||||
pb.move_to(rect.left() + offset, rect.top() - offset);
|
||||
pb.line_to(rect.right() + offset, rect.top() - offset);
|
||||
pb.line_to(rect.right() + offset, rect.bottom() - offset + 0.5);
|
||||
}
|
||||
} else if let Some(rect) = Rect::from_xywh(x, y, size, size) {
|
||||
pb.push_rect(rect);
|
||||
}
|
||||
|
||||
pb.finish()?
|
||||
};
|
||||
|
||||
pixmap.stroke_path(
|
||||
&path2,
|
||||
&button_icon_paint,
|
||||
&Stroke {
|
||||
width: 1.0 * scale,
|
||||
..Default::default()
|
||||
},
|
||||
Transform::identity(),
|
||||
None,
|
||||
);
|
||||
}
|
||||
ButtonKind::Minimize => {
|
||||
let len = 8.0 * scale;
|
||||
let hlen = len / 2.0;
|
||||
pixmap.fill_rect(
|
||||
Rect::from_xywh(x - hlen, y + hlen, len, scale)?,
|
||||
&button_icon_paint,
|
||||
Transform::identity(),
|
||||
None,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Some(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||
pub enum ButtonKind {
|
||||
Close,
|
||||
Maximize,
|
||||
Minimize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||
pub enum Side {
|
||||
Left,
|
||||
Right,
|
||||
}
|
||||
56
patches/sctk-adwaita/src/config.rs
vendored
Normal file
56
patches/sctk-adwaita/src/config.rs
vendored
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
//! System configuration.
|
||||
use std::process::Command;
|
||||
|
||||
/// Query system to see if dark theming should be preferred.
|
||||
pub(crate) fn prefer_dark() -> bool {
|
||||
// outputs something like: `variant variant uint32 1`
|
||||
let stdout = Command::new("dbus-send")
|
||||
.arg("--reply-timeout=100")
|
||||
.arg("--print-reply=literal")
|
||||
.arg("--dest=org.freedesktop.portal.Desktop")
|
||||
.arg("/org/freedesktop/portal/desktop")
|
||||
.arg("org.freedesktop.portal.Settings.Read")
|
||||
.arg("string:org.freedesktop.appearance")
|
||||
.arg("string:color-scheme")
|
||||
.output()
|
||||
.ok()
|
||||
.and_then(|out| String::from_utf8(out.stdout).ok());
|
||||
|
||||
if matches!(stdout, Some(ref s) if s.is_empty()) {
|
||||
log::error!("XDG Settings Portal did not return response in time: timeout: 100ms, key: color-scheme");
|
||||
}
|
||||
|
||||
matches!(stdout, Some(s) if s.trim().ends_with("uint32 1"))
|
||||
}
|
||||
|
||||
/// Query system configuration for buttons layout.
|
||||
/// Should be updated to use standard xdg-desktop-portal specs once available
|
||||
/// https://github.com/flatpak/xdg-desktop-portal/pull/996
|
||||
pub(crate) fn get_button_layout_config() -> Option<(String, String)> {
|
||||
let config_string = Command::new("dbus-send")
|
||||
.arg("--reply-timeout=100")
|
||||
.arg("--print-reply=literal")
|
||||
.arg("--dest=org.freedesktop.portal.Desktop")
|
||||
.arg("/org/freedesktop/portal/desktop")
|
||||
.arg("org.freedesktop.portal.Settings.Read")
|
||||
.arg("string:org.gnome.desktop.wm.preferences")
|
||||
.arg("string:button-layout")
|
||||
.output()
|
||||
.ok()
|
||||
.and_then(|out| String::from_utf8(out.stdout).ok())?;
|
||||
|
||||
let sides_split: Vec<_> = config_string
|
||||
// Taking last word
|
||||
.rsplit(' ')
|
||||
.next()?
|
||||
// Split by left/right side
|
||||
.split(':')
|
||||
// Only two sides
|
||||
.take(2)
|
||||
.collect();
|
||||
|
||||
match sides_split.as_slice() {
|
||||
[left, right] => Some((left.to_string(), right.to_string())),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
780
patches/sctk-adwaita/src/lib.rs
vendored
Normal file
780
patches/sctk-adwaita/src/lib.rs
vendored
Normal file
|
|
@ -0,0 +1,780 @@
|
|||
use std::error::Error;
|
||||
use std::mem;
|
||||
use std::num::NonZeroU32;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use tiny_skia::{
|
||||
Color, FillRule, Mask, Path, PathBuilder, Pixmap, PixmapMut, PixmapPaint, Point, Rect,
|
||||
Transform,
|
||||
};
|
||||
|
||||
use smithay_client_toolkit::reexports::client::backend::ObjectId;
|
||||
use smithay_client_toolkit::reexports::client::protocol::wl_shm;
|
||||
use smithay_client_toolkit::reexports::client::protocol::wl_subsurface::WlSubsurface;
|
||||
use smithay_client_toolkit::reexports::client::protocol::wl_surface::WlSurface;
|
||||
use smithay_client_toolkit::reexports::client::{Dispatch, Proxy, QueueHandle};
|
||||
use smithay_client_toolkit::reexports::csd_frame::{
|
||||
CursorIcon, DecorationsFrame, FrameAction, FrameClick, WindowManagerCapabilities, WindowState,
|
||||
};
|
||||
|
||||
use smithay_client_toolkit::compositor::{CompositorState, Region, SurfaceData};
|
||||
use smithay_client_toolkit::shell::WaylandSurface;
|
||||
use smithay_client_toolkit::shm::{slot::SlotPool, Shm};
|
||||
use smithay_client_toolkit::subcompositor::SubcompositorState;
|
||||
use smithay_client_toolkit::subcompositor::SubsurfaceData;
|
||||
|
||||
mod buttons;
|
||||
mod config;
|
||||
mod parts;
|
||||
mod pointer;
|
||||
mod shadow;
|
||||
pub mod theme;
|
||||
mod title;
|
||||
mod wl_typed;
|
||||
|
||||
use crate::theme::{
|
||||
ColorMap, ColorTheme, BORDER_SIZE, CORNER_RADIUS, HEADER_SIZE, RESIZE_HANDLE_CORNER_SIZE,
|
||||
VISIBLE_BORDER_SIZE,
|
||||
};
|
||||
|
||||
use buttons::Buttons;
|
||||
use config::get_button_layout_config;
|
||||
use parts::DecorationParts;
|
||||
use pointer::{Location, MouseState};
|
||||
use shadow::Shadow;
|
||||
use title::TitleText;
|
||||
use wl_typed::WlTyped;
|
||||
|
||||
/// XXX this is not result, so `must_use` when needed.
|
||||
type SkiaResult = Option<()>;
|
||||
|
||||
/// A simple set of decorations
|
||||
#[derive(Debug)]
|
||||
pub struct AdwaitaFrame<State> {
|
||||
/// The base surface used to create the window.
|
||||
base_surface: WlTyped<WlSurface, SurfaceData>,
|
||||
|
||||
compositor: Arc<CompositorState>,
|
||||
|
||||
/// Subcompositor to create/drop subsurfaces ondemand.
|
||||
subcompositor: Arc<SubcompositorState>,
|
||||
|
||||
/// Queue handle to perform object creation.
|
||||
queue_handle: QueueHandle<State>,
|
||||
|
||||
/// The drawable decorations, `None` when hidden.
|
||||
decorations: Option<DecorationParts>,
|
||||
|
||||
/// Memory pool to allocate the buffers for the decorations.
|
||||
pool: SlotPool,
|
||||
|
||||
/// Whether the frame should be redrawn.
|
||||
dirty: bool,
|
||||
|
||||
/// Whether the drawing should be synced with the main surface.
|
||||
should_sync: bool,
|
||||
|
||||
/// Scale factor used for the surface.
|
||||
scale_factor: u32,
|
||||
|
||||
/// Wether the frame is resizable.
|
||||
resizable: bool,
|
||||
|
||||
buttons: Buttons,
|
||||
state: WindowState,
|
||||
wm_capabilities: WindowManagerCapabilities,
|
||||
mouse: MouseState,
|
||||
theme: ColorTheme,
|
||||
title: Option<String>,
|
||||
title_text: Option<TitleText>,
|
||||
shadow: Shadow,
|
||||
}
|
||||
|
||||
impl<State> AdwaitaFrame<State>
|
||||
where
|
||||
State: Dispatch<WlSurface, SurfaceData> + Dispatch<WlSubsurface, SubsurfaceData> + 'static,
|
||||
{
|
||||
pub fn new(
|
||||
base_surface: &impl WaylandSurface,
|
||||
shm: &Shm,
|
||||
compositor: Arc<CompositorState>,
|
||||
subcompositor: Arc<SubcompositorState>,
|
||||
queue_handle: QueueHandle<State>,
|
||||
frame_config: FrameConfig,
|
||||
) -> Result<Self, Box<dyn Error>> {
|
||||
let base_surface = WlTyped::wrap::<State>(base_surface.wl_surface().clone());
|
||||
|
||||
let pool = SlotPool::new(1, shm)?;
|
||||
|
||||
let decorations = Some(DecorationParts::new(
|
||||
&base_surface,
|
||||
&subcompositor,
|
||||
&queue_handle,
|
||||
));
|
||||
|
||||
let theme = frame_config.theme;
|
||||
|
||||
Ok(AdwaitaFrame {
|
||||
base_surface,
|
||||
decorations,
|
||||
pool,
|
||||
compositor,
|
||||
subcompositor,
|
||||
queue_handle,
|
||||
dirty: true,
|
||||
scale_factor: 1,
|
||||
should_sync: true,
|
||||
title: None,
|
||||
title_text: TitleText::new(theme.active.font_color),
|
||||
theme,
|
||||
buttons: Buttons::new(get_button_layout_config()),
|
||||
mouse: Default::default(),
|
||||
state: WindowState::empty(),
|
||||
wm_capabilities: WindowManagerCapabilities::all(),
|
||||
resizable: true,
|
||||
shadow: Shadow::default(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Update the current frame config.
|
||||
pub fn set_config(&mut self, config: FrameConfig) {
|
||||
self.theme = config.theme;
|
||||
self.dirty = true;
|
||||
}
|
||||
|
||||
fn precise_location(
|
||||
&self,
|
||||
location: Location,
|
||||
decoration: &DecorationParts,
|
||||
x: f64,
|
||||
y: f64,
|
||||
) -> Location {
|
||||
let header_width = decoration.header().surface_rect.width;
|
||||
let side_height = decoration.side_height();
|
||||
|
||||
let left_corner_x = BORDER_SIZE + RESIZE_HANDLE_CORNER_SIZE;
|
||||
let right_corner_x = (header_width + BORDER_SIZE).saturating_sub(RESIZE_HANDLE_CORNER_SIZE);
|
||||
let top_corner_y = RESIZE_HANDLE_CORNER_SIZE;
|
||||
let bottom_corner_y = side_height.saturating_sub(RESIZE_HANDLE_CORNER_SIZE);
|
||||
match location {
|
||||
Location::Head | Location::Button(_) => self.buttons.find_button(x, y),
|
||||
Location::Top | Location::TopLeft | Location::TopRight => {
|
||||
if x <= f64::from(left_corner_x) {
|
||||
Location::TopLeft
|
||||
} else if x >= f64::from(right_corner_x) {
|
||||
Location::TopRight
|
||||
} else {
|
||||
Location::Top
|
||||
}
|
||||
}
|
||||
Location::Bottom | Location::BottomLeft | Location::BottomRight => {
|
||||
if x <= f64::from(left_corner_x) {
|
||||
Location::BottomLeft
|
||||
} else if x >= f64::from(right_corner_x) {
|
||||
Location::BottomRight
|
||||
} else {
|
||||
Location::Bottom
|
||||
}
|
||||
}
|
||||
Location::Left => {
|
||||
if y <= f64::from(top_corner_y) {
|
||||
Location::TopLeft
|
||||
} else if y >= f64::from(bottom_corner_y) {
|
||||
Location::BottomLeft
|
||||
} else {
|
||||
Location::Left
|
||||
}
|
||||
}
|
||||
Location::Right => {
|
||||
if y <= f64::from(top_corner_y) {
|
||||
Location::TopRight
|
||||
} else if y >= f64::from(bottom_corner_y) {
|
||||
Location::BottomRight
|
||||
} else {
|
||||
Location::Right
|
||||
}
|
||||
}
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
fn redraw_inner(&mut self) -> Option<bool> {
|
||||
let decorations = self.decorations.as_mut()?;
|
||||
|
||||
// Reset the dirty bit.
|
||||
self.dirty = false;
|
||||
let should_sync = mem::take(&mut self.should_sync);
|
||||
|
||||
// Don't draw borders if the frame explicitly hidden or fullscreened.
|
||||
if self.state.contains(WindowState::FULLSCREEN) {
|
||||
decorations.hide();
|
||||
return Some(true);
|
||||
}
|
||||
|
||||
let colors = if self.state.contains(WindowState::ACTIVATED) {
|
||||
&self.theme.active
|
||||
} else {
|
||||
&self.theme.inactive
|
||||
};
|
||||
|
||||
let draw_borders = if self.state.contains(WindowState::MAXIMIZED) {
|
||||
// Don't draw the borders.
|
||||
decorations.hide_borders();
|
||||
false
|
||||
} else {
|
||||
true
|
||||
};
|
||||
let border_paint = colors.border_paint();
|
||||
|
||||
// Draw the borders.
|
||||
for (idx, part) in decorations
|
||||
.parts()
|
||||
.filter(|(idx, _)| *idx == DecorationParts::HEADER || draw_borders)
|
||||
{
|
||||
let scale = self.scale_factor;
|
||||
|
||||
let mut rect = part.surface_rect;
|
||||
// XXX to perfectly align the visible borders we draw them with
|
||||
// the header, otherwise rounded corners won't look 'smooth' at the
|
||||
// start. To achieve that, we enlargen the width of the header by
|
||||
// 2 * `VISIBLE_BORDER_SIZE`, and move `x` by `VISIBLE_BORDER_SIZE`
|
||||
// to the left.
|
||||
if idx == DecorationParts::HEADER && draw_borders {
|
||||
rect.width += 2 * VISIBLE_BORDER_SIZE;
|
||||
rect.x -= VISIBLE_BORDER_SIZE as i32;
|
||||
}
|
||||
|
||||
rect.width *= scale;
|
||||
rect.height *= scale;
|
||||
|
||||
let (buffer, canvas) = match self.pool.create_buffer(
|
||||
rect.width as i32,
|
||||
rect.height as i32,
|
||||
rect.width as i32 * 4,
|
||||
wl_shm::Format::Argb8888,
|
||||
) {
|
||||
Ok((buffer, canvas)) => (buffer, canvas),
|
||||
Err(_) => continue,
|
||||
};
|
||||
|
||||
// Create the pixmap and fill with transparent color.
|
||||
let mut pixmap = PixmapMut::from_bytes(canvas, rect.width, rect.height)?;
|
||||
|
||||
// Fill everything with transparent background, since we draw rounded corners and
|
||||
// do invisible borders to enlarge the input zone.
|
||||
pixmap.fill(Color::TRANSPARENT);
|
||||
|
||||
if !self.state.intersects(WindowState::TILED) {
|
||||
self.shadow.draw(
|
||||
&mut pixmap,
|
||||
scale,
|
||||
self.state.contains(WindowState::ACTIVATED),
|
||||
idx,
|
||||
);
|
||||
}
|
||||
|
||||
match idx {
|
||||
DecorationParts::HEADER => {
|
||||
if let Some(title_text) = self.title_text.as_mut() {
|
||||
title_text.update_scale(scale);
|
||||
title_text.update_color(colors.font_color);
|
||||
}
|
||||
|
||||
draw_headerbar(
|
||||
&mut pixmap,
|
||||
self.title_text.as_ref().map(|t| t.pixmap()).unwrap_or(None),
|
||||
scale as f32,
|
||||
self.resizable,
|
||||
&self.state,
|
||||
&self.theme,
|
||||
&self.buttons,
|
||||
self.mouse.location,
|
||||
);
|
||||
}
|
||||
border => {
|
||||
// The visible border is one pt.
|
||||
let visible_border_size = VISIBLE_BORDER_SIZE * scale;
|
||||
|
||||
// XXX we do all the match using integral types and then convert to f32 in the
|
||||
// end to ensure that result is finite.
|
||||
let border_rect = match border {
|
||||
DecorationParts::LEFT => {
|
||||
let x = (rect.x.unsigned_abs() * scale) - visible_border_size;
|
||||
let y = rect.y.unsigned_abs() * scale;
|
||||
Rect::from_xywh(
|
||||
x as f32,
|
||||
y as f32,
|
||||
visible_border_size as f32,
|
||||
(rect.height - y) as f32,
|
||||
)
|
||||
}
|
||||
DecorationParts::RIGHT => {
|
||||
let y = rect.y.unsigned_abs() * scale;
|
||||
Rect::from_xywh(
|
||||
0.,
|
||||
y as f32,
|
||||
visible_border_size as f32,
|
||||
(rect.height - y) as f32,
|
||||
)
|
||||
}
|
||||
// We draw small visible border only bellow the window surface, no need to
|
||||
// handle `TOP`.
|
||||
DecorationParts::BOTTOM => {
|
||||
let x = (rect.x.unsigned_abs() * scale) - visible_border_size;
|
||||
Rect::from_xywh(
|
||||
x as f32,
|
||||
0.,
|
||||
(rect.width - 2 * x) as f32,
|
||||
visible_border_size as f32,
|
||||
)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
|
||||
// Fill the visible border, if present.
|
||||
if let Some(border_rect) = border_rect {
|
||||
pixmap.fill_rect(border_rect, &border_paint, Transform::identity(), None);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if should_sync {
|
||||
part.subsurface.set_sync();
|
||||
} else {
|
||||
part.subsurface.set_desync();
|
||||
}
|
||||
|
||||
part.surface.set_buffer_scale(scale as i32);
|
||||
|
||||
part.subsurface.set_position(rect.x, rect.y);
|
||||
buffer.attach_to(&part.surface).ok()?;
|
||||
|
||||
if part.surface.version() >= 4 {
|
||||
part.surface.damage_buffer(0, 0, i32::MAX, i32::MAX);
|
||||
} else {
|
||||
part.surface.damage(0, 0, i32::MAX, i32::MAX);
|
||||
}
|
||||
|
||||
if let Some(input_rect) = part.input_rect {
|
||||
let input_region = Region::new(&*self.compositor).ok()?;
|
||||
input_region.add(
|
||||
input_rect.x,
|
||||
input_rect.y,
|
||||
input_rect.width as i32,
|
||||
input_rect.height as i32,
|
||||
);
|
||||
|
||||
part.surface
|
||||
.set_input_region(Some(input_region.wl_region()));
|
||||
}
|
||||
|
||||
part.surface.commit();
|
||||
}
|
||||
|
||||
Some(should_sync)
|
||||
}
|
||||
}
|
||||
|
||||
impl<State> DecorationsFrame for AdwaitaFrame<State>
|
||||
where
|
||||
State: Dispatch<WlSurface, SurfaceData> + Dispatch<WlSubsurface, SubsurfaceData> + 'static,
|
||||
{
|
||||
fn update_state(&mut self, state: WindowState) {
|
||||
let difference = self.state.symmetric_difference(state);
|
||||
self.state = state;
|
||||
self.dirty |= difference.intersects(
|
||||
WindowState::ACTIVATED
|
||||
| WindowState::FULLSCREEN
|
||||
| WindowState::MAXIMIZED
|
||||
| WindowState::TILED,
|
||||
);
|
||||
}
|
||||
|
||||
fn update_wm_capabilities(&mut self, wm_capabilities: WindowManagerCapabilities) {
|
||||
self.dirty |= self.wm_capabilities != wm_capabilities;
|
||||
self.wm_capabilities = wm_capabilities;
|
||||
self.buttons.update_wm_capabilities(wm_capabilities);
|
||||
}
|
||||
|
||||
fn set_hidden(&mut self, hidden: bool) {
|
||||
if hidden {
|
||||
self.dirty = false;
|
||||
let _ = self.pool.resize(1);
|
||||
self.decorations = None;
|
||||
} else if self.decorations.is_none() {
|
||||
self.decorations = Some(DecorationParts::new(
|
||||
&self.base_surface,
|
||||
&self.subcompositor,
|
||||
&self.queue_handle,
|
||||
));
|
||||
self.dirty = true;
|
||||
self.should_sync = true;
|
||||
}
|
||||
}
|
||||
|
||||
fn set_resizable(&mut self, resizable: bool) {
|
||||
self.dirty |= self.resizable != resizable;
|
||||
self.resizable = resizable;
|
||||
}
|
||||
|
||||
fn resize(&mut self, width: NonZeroU32, height: NonZeroU32) {
|
||||
let Some(decorations) = self.decorations.as_mut() else {
|
||||
log::error!("trying to resize the hidden frame.");
|
||||
return;
|
||||
};
|
||||
|
||||
decorations.resize(width.get(), height.get());
|
||||
self.buttons
|
||||
.arrange(width.get(), get_margin_h_lp(&self.state));
|
||||
self.dirty = true;
|
||||
self.should_sync = true;
|
||||
}
|
||||
|
||||
fn draw(&mut self) -> bool {
|
||||
self.redraw_inner().unwrap_or(true)
|
||||
}
|
||||
|
||||
fn subtract_borders(
|
||||
&self,
|
||||
width: NonZeroU32,
|
||||
height: NonZeroU32,
|
||||
) -> (Option<NonZeroU32>, Option<NonZeroU32>) {
|
||||
if self.decorations.is_none() || self.state.contains(WindowState::FULLSCREEN) {
|
||||
(Some(width), Some(height))
|
||||
} else {
|
||||
(
|
||||
Some(width),
|
||||
NonZeroU32::new(height.get().saturating_sub(HEADER_SIZE)),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn add_borders(&self, width: u32, height: u32) -> (u32, u32) {
|
||||
if self.decorations.is_none() || self.state.contains(WindowState::FULLSCREEN) {
|
||||
(width, height)
|
||||
} else {
|
||||
(width, height + HEADER_SIZE)
|
||||
}
|
||||
}
|
||||
|
||||
fn location(&self) -> (i32, i32) {
|
||||
if self.decorations.is_none() || self.state.contains(WindowState::FULLSCREEN) {
|
||||
(0, 0)
|
||||
} else {
|
||||
(0, -(HEADER_SIZE as i32))
|
||||
}
|
||||
}
|
||||
|
||||
fn set_title(&mut self, title: impl Into<String>) {
|
||||
let new_title = title.into();
|
||||
if let Some(title_text) = self.title_text.as_mut() {
|
||||
title_text.update_title(new_title.clone());
|
||||
}
|
||||
|
||||
self.title = Some(new_title);
|
||||
self.dirty = true;
|
||||
}
|
||||
|
||||
fn on_click(
|
||||
&mut self,
|
||||
timestamp: Duration,
|
||||
click: FrameClick,
|
||||
pressed: bool,
|
||||
) -> Option<FrameAction> {
|
||||
match click {
|
||||
FrameClick::Normal => self.mouse.click(
|
||||
timestamp,
|
||||
pressed,
|
||||
self.resizable,
|
||||
&self.state,
|
||||
&self.wm_capabilities,
|
||||
),
|
||||
FrameClick::Alternate => self.mouse.alternate_click(pressed, &self.wm_capabilities),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn set_scaling_factor(&mut self, scale_factor: f64) {
|
||||
// NOTE: Clamp it just in case to some ok-ish range.
|
||||
self.scale_factor = scale_factor.clamp(0.1, 64.).ceil() as u32;
|
||||
self.dirty = true;
|
||||
self.should_sync = true;
|
||||
}
|
||||
|
||||
fn click_point_moved(
|
||||
&mut self,
|
||||
_timestamp: Duration,
|
||||
surface: &ObjectId,
|
||||
x: f64,
|
||||
y: f64,
|
||||
) -> Option<CursorIcon> {
|
||||
let decorations = self.decorations.as_ref()?;
|
||||
let location = decorations.find_surface(surface);
|
||||
if location == Location::None {
|
||||
return None;
|
||||
}
|
||||
|
||||
let old_location = self.mouse.location;
|
||||
|
||||
let location = self.precise_location(location, decorations, x, y);
|
||||
let new_cursor = self.mouse.moved(location, x, y, self.resizable);
|
||||
|
||||
// Set dirty if we moved the cursor between the buttons.
|
||||
self.dirty |= (matches!(old_location, Location::Button(_))
|
||||
|| matches!(self.mouse.location, Location::Button(_)))
|
||||
&& old_location != self.mouse.location;
|
||||
|
||||
Some(new_cursor)
|
||||
}
|
||||
|
||||
fn click_point_left(&mut self) {
|
||||
self.mouse.left()
|
||||
}
|
||||
|
||||
fn is_dirty(&self) -> bool {
|
||||
self.dirty
|
||||
}
|
||||
|
||||
fn is_hidden(&self) -> bool {
|
||||
self.decorations.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
/// The configuration for the [`AdwaitaFrame`] frame.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct FrameConfig {
|
||||
pub theme: ColorTheme,
|
||||
}
|
||||
|
||||
impl FrameConfig {
|
||||
/// Create the new configuration with the given `theme`.
|
||||
pub fn new(theme: ColorTheme) -> Self {
|
||||
Self { theme }
|
||||
}
|
||||
|
||||
/// This is equivalent of calling `FrameConfig::new(ColorTheme::auto())`.
|
||||
///
|
||||
/// For details see [`ColorTheme::auto`].
|
||||
pub fn auto() -> Self {
|
||||
Self {
|
||||
theme: ColorTheme::auto(),
|
||||
}
|
||||
}
|
||||
|
||||
/// This is equivalent of calling `FrameConfig::new(ColorTheme::light())`.
|
||||
///
|
||||
/// For details see [`ColorTheme::light`].
|
||||
pub fn light() -> Self {
|
||||
Self {
|
||||
theme: ColorTheme::light(),
|
||||
}
|
||||
}
|
||||
|
||||
/// This is equivalent of calling `FrameConfig::new(ColorTheme::dark())`.
|
||||
///
|
||||
/// For details see [`ColorTheme::dark`].
|
||||
pub fn dark() -> Self {
|
||||
Self {
|
||||
theme: ColorTheme::dark(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn draw_headerbar(
|
||||
pixmap: &mut PixmapMut,
|
||||
text_pixmap: Option<&Pixmap>,
|
||||
scale: f32,
|
||||
resizable: bool,
|
||||
state: &WindowState,
|
||||
theme: &ColorTheme,
|
||||
buttons: &Buttons,
|
||||
mouse: Location,
|
||||
) {
|
||||
let colors = theme.for_state(state.contains(WindowState::ACTIVATED));
|
||||
|
||||
let _ = draw_headerbar_bg(pixmap, scale, colors, state);
|
||||
|
||||
// Horizontal margin.
|
||||
let margin_h = get_margin_h_lp(state) * 2.0;
|
||||
|
||||
let canvas_w = pixmap.width() as f32;
|
||||
let canvas_h = pixmap.height() as f32;
|
||||
|
||||
let header_w = canvas_w - margin_h * 2.0;
|
||||
let header_h = canvas_h;
|
||||
|
||||
if let Some(text_pixmap) = text_pixmap {
|
||||
const TEXT_OFFSET: f32 = 10.;
|
||||
let offset_x = TEXT_OFFSET * scale;
|
||||
|
||||
let text_w = text_pixmap.width() as f32;
|
||||
let text_h = text_pixmap.height() as f32;
|
||||
|
||||
let x = margin_h + header_w / 2. - text_w / 2.;
|
||||
let y = header_h / 2. - text_h / 2.;
|
||||
|
||||
let left_buttons_end_x = buttons.left_buttons_end_x().unwrap_or(0.0) * scale;
|
||||
let right_buttons_start_x =
|
||||
buttons.right_buttons_start_x().unwrap_or(header_w / scale) * scale;
|
||||
|
||||
{
|
||||
// We have enough space to center text
|
||||
let (x, y, text_canvas_start_x) = if (x + text_w < right_buttons_start_x - offset_x)
|
||||
&& (x > left_buttons_end_x + offset_x)
|
||||
{
|
||||
let text_canvas_start_x = x;
|
||||
|
||||
(x, y, text_canvas_start_x)
|
||||
} else {
|
||||
let x = left_buttons_end_x + offset_x;
|
||||
let text_canvas_start_x = left_buttons_end_x + offset_x;
|
||||
|
||||
(x, y, text_canvas_start_x)
|
||||
};
|
||||
|
||||
let text_canvas_end_x = right_buttons_start_x - x - offset_x;
|
||||
// Ensure that text start within the bounds.
|
||||
let x = x.max(margin_h + offset_x);
|
||||
|
||||
if let Some(clip) =
|
||||
Rect::from_xywh(text_canvas_start_x, 0., text_canvas_end_x, canvas_h)
|
||||
{
|
||||
if let Some(mut mask) = Mask::new(canvas_w as u32, canvas_h as u32) {
|
||||
mask.fill_path(
|
||||
&PathBuilder::from_rect(clip),
|
||||
FillRule::Winding,
|
||||
false,
|
||||
Transform::identity(),
|
||||
);
|
||||
pixmap.draw_pixmap(
|
||||
x.round() as i32,
|
||||
y as i32,
|
||||
text_pixmap.as_ref(),
|
||||
&PixmapPaint::default(),
|
||||
Transform::identity(),
|
||||
Some(&mask),
|
||||
);
|
||||
} else {
|
||||
log::error!(
|
||||
"Invalid mask width and height: w: {}, h: {}",
|
||||
canvas_w as u32,
|
||||
canvas_h as u32
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Draw the buttons.
|
||||
buttons.draw(
|
||||
margin_h, header_w, scale, colors, mouse, pixmap, resizable, state,
|
||||
);
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
fn draw_headerbar_bg(
|
||||
pixmap: &mut PixmapMut,
|
||||
scale: f32,
|
||||
colors: &ColorMap,
|
||||
state: &WindowState,
|
||||
) -> SkiaResult {
|
||||
let w = pixmap.width() as f32;
|
||||
let h = pixmap.height() as f32;
|
||||
|
||||
let radius = if state.intersects(WindowState::MAXIMIZED | WindowState::TILED) {
|
||||
0.
|
||||
} else {
|
||||
CORNER_RADIUS as f32 * scale
|
||||
};
|
||||
|
||||
let bg = rounded_headerbar_shape(0., 0., w, h, radius)?;
|
||||
|
||||
pixmap.fill_path(
|
||||
&bg,
|
||||
&colors.headerbar_paint(),
|
||||
FillRule::Winding,
|
||||
Transform::identity(),
|
||||
None,
|
||||
);
|
||||
|
||||
pixmap.fill_rect(
|
||||
Rect::from_xywh(0., h - 1., w, h)?,
|
||||
&colors.border_paint(),
|
||||
Transform::identity(),
|
||||
None,
|
||||
);
|
||||
|
||||
Some(())
|
||||
}
|
||||
|
||||
fn rounded_headerbar_shape(x: f32, y: f32, width: f32, height: f32, radius: f32) -> Option<Path> {
|
||||
// https://stackoverflow.com/a/27863181
|
||||
let cubic_bezier_circle = 0.552_284_8 * radius;
|
||||
|
||||
let mut pb = PathBuilder::new();
|
||||
let mut cursor = Point::from_xy(x, y);
|
||||
|
||||
// !!!
|
||||
// This code is heavily "inspired" by https://gitlab.com/snakedye/snui/
|
||||
// So technically it should be licensed under MPL-2.0, sorry about that 🥺 👉👈
|
||||
// !!!
|
||||
|
||||
// Positioning the cursor
|
||||
cursor.y += radius;
|
||||
pb.move_to(cursor.x, cursor.y);
|
||||
|
||||
// Drawing the outline
|
||||
let next = Point::from_xy(cursor.x + radius, cursor.y - radius);
|
||||
pb.cubic_to(
|
||||
cursor.x,
|
||||
cursor.y - cubic_bezier_circle,
|
||||
next.x - cubic_bezier_circle,
|
||||
next.y,
|
||||
next.x,
|
||||
next.y,
|
||||
);
|
||||
cursor = next;
|
||||
pb.line_to(
|
||||
{
|
||||
cursor.x = x + width - radius;
|
||||
cursor.x
|
||||
},
|
||||
cursor.y,
|
||||
);
|
||||
let next = Point::from_xy(cursor.x + radius, cursor.y + radius);
|
||||
pb.cubic_to(
|
||||
cursor.x + cubic_bezier_circle,
|
||||
cursor.y,
|
||||
next.x,
|
||||
next.y - cubic_bezier_circle,
|
||||
next.x,
|
||||
next.y,
|
||||
);
|
||||
cursor = next;
|
||||
pb.line_to(cursor.x, {
|
||||
cursor.y = y + height;
|
||||
cursor.y
|
||||
});
|
||||
pb.line_to(
|
||||
{
|
||||
cursor.x = x;
|
||||
cursor.x
|
||||
},
|
||||
cursor.y,
|
||||
);
|
||||
|
||||
pb.close();
|
||||
|
||||
pb.finish()
|
||||
}
|
||||
|
||||
// returns horizontal margin, logical points
|
||||
fn get_margin_h_lp(state: &WindowState) -> f32 {
|
||||
if state.intersects(WindowState::MAXIMIZED | WindowState::TILED) {
|
||||
0.
|
||||
} else {
|
||||
VISIBLE_BORDER_SIZE as f32
|
||||
}
|
||||
}
|
||||
260
patches/sctk-adwaita/src/parts.rs
vendored
Normal file
260
patches/sctk-adwaita/src/parts.rs
vendored
Normal file
|
|
@ -0,0 +1,260 @@
|
|||
use smithay_client_toolkit::reexports::client::{
|
||||
backend::ObjectId,
|
||||
protocol::{wl_subsurface::WlSubsurface, wl_surface::WlSurface},
|
||||
Dispatch, Proxy, QueueHandle,
|
||||
};
|
||||
|
||||
use smithay_client_toolkit::{
|
||||
compositor::SurfaceData,
|
||||
subcompositor::{SubcompositorState, SubsurfaceData},
|
||||
};
|
||||
|
||||
use crate::theme::{BORDER_SIZE, HEADER_SIZE, RESIZE_HANDLE_SIZE};
|
||||
use crate::{pointer::Location, wl_typed::WlTyped};
|
||||
|
||||
/// The decoration's 'parts'.
|
||||
#[derive(Debug)]
|
||||
pub struct DecorationParts {
|
||||
parts: [Part; 5],
|
||||
}
|
||||
|
||||
impl DecorationParts {
|
||||
// XXX keep in sync with `Self;:new`.
|
||||
// Order is important. The lower the number, the earlier the part gets drawn.
|
||||
// Because the header can overlap other parts, we draw it last.
|
||||
pub const TOP: usize = 0;
|
||||
pub const LEFT: usize = 1;
|
||||
pub const RIGHT: usize = 2;
|
||||
pub const BOTTOM: usize = 3;
|
||||
pub const HEADER: usize = 4;
|
||||
|
||||
pub fn new<State>(
|
||||
base_surface: &WlTyped<WlSurface, SurfaceData>,
|
||||
subcompositor: &SubcompositorState,
|
||||
queue_handle: &QueueHandle<State>,
|
||||
) -> Self
|
||||
where
|
||||
State: Dispatch<WlSurface, SurfaceData> + Dispatch<WlSubsurface, SubsurfaceData> + 'static,
|
||||
{
|
||||
// XXX the order must be in sync with associated constants.
|
||||
let parts = [
|
||||
// Top.
|
||||
Part::new(
|
||||
base_surface,
|
||||
subcompositor,
|
||||
queue_handle,
|
||||
Rect {
|
||||
x: -(BORDER_SIZE as i32),
|
||||
y: -(HEADER_SIZE as i32 + BORDER_SIZE as i32),
|
||||
width: 0, // Defined by `Self::resize`.
|
||||
height: BORDER_SIZE,
|
||||
},
|
||||
Some(Rect {
|
||||
x: BORDER_SIZE as i32 - RESIZE_HANDLE_SIZE as i32,
|
||||
y: BORDER_SIZE as i32 - RESIZE_HANDLE_SIZE as i32,
|
||||
width: 0, // Defined by `Self::resize`.
|
||||
height: RESIZE_HANDLE_SIZE,
|
||||
}),
|
||||
),
|
||||
// Left.
|
||||
Part::new(
|
||||
base_surface,
|
||||
subcompositor,
|
||||
queue_handle,
|
||||
Rect {
|
||||
x: -(BORDER_SIZE as i32),
|
||||
y: -(HEADER_SIZE as i32),
|
||||
width: BORDER_SIZE,
|
||||
height: 0, // Defined by `Self::resize`.
|
||||
},
|
||||
Some(Rect {
|
||||
x: BORDER_SIZE as i32 - RESIZE_HANDLE_SIZE as i32,
|
||||
y: 0,
|
||||
width: RESIZE_HANDLE_SIZE,
|
||||
height: 0, // Defined by `Self::resize`.
|
||||
}),
|
||||
),
|
||||
// Right.
|
||||
Part::new(
|
||||
base_surface,
|
||||
subcompositor,
|
||||
queue_handle,
|
||||
Rect {
|
||||
x: 0, // Defined by `Self::resize`.
|
||||
y: -(HEADER_SIZE as i32),
|
||||
width: BORDER_SIZE,
|
||||
height: 0, // Defined by `Self::resize`.
|
||||
},
|
||||
Some(Rect {
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: RESIZE_HANDLE_SIZE,
|
||||
height: 0, // Defined by `Self::resize`.
|
||||
}),
|
||||
),
|
||||
// Bottom.
|
||||
Part::new(
|
||||
base_surface,
|
||||
subcompositor,
|
||||
queue_handle,
|
||||
Rect {
|
||||
x: -(BORDER_SIZE as i32),
|
||||
y: 0, // Defined by `Self::resize`.
|
||||
width: 0, // Defined by `Self::resize`.
|
||||
height: BORDER_SIZE,
|
||||
},
|
||||
Some(Rect {
|
||||
x: BORDER_SIZE as i32 - RESIZE_HANDLE_SIZE as i32,
|
||||
y: 0,
|
||||
width: 0, // Defined by `Self::resize`,
|
||||
height: RESIZE_HANDLE_SIZE,
|
||||
}),
|
||||
),
|
||||
// Header.
|
||||
Part::new(
|
||||
base_surface,
|
||||
subcompositor,
|
||||
queue_handle,
|
||||
Rect {
|
||||
x: 0,
|
||||
y: -(HEADER_SIZE as i32),
|
||||
width: 0, // Defined by `Self::resize`.
|
||||
height: HEADER_SIZE,
|
||||
},
|
||||
None,
|
||||
),
|
||||
];
|
||||
|
||||
Self { parts }
|
||||
}
|
||||
|
||||
pub fn parts(&self) -> std::iter::Enumerate<std::slice::Iter<'_, Part>> {
|
||||
self.parts.iter().enumerate()
|
||||
}
|
||||
|
||||
pub fn hide(&self) {
|
||||
for part in self.parts.iter() {
|
||||
part.subsurface.set_sync();
|
||||
part.surface.attach(None, 0, 0);
|
||||
part.surface.commit();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn hide_borders(&self) {
|
||||
for (_, part) in self.parts().filter(|(idx, _)| *idx != Self::HEADER) {
|
||||
part.surface.attach(None, 0, 0);
|
||||
part.surface.commit();
|
||||
}
|
||||
}
|
||||
|
||||
// These unwraps are guaranteed to succeed because the affected options are filled above
|
||||
// and then never emptied afterwards.
|
||||
#[allow(clippy::unwrap_used)]
|
||||
pub fn resize(&mut self, width: u32, height: u32) {
|
||||
self.parts[Self::HEADER].surface_rect.width = width;
|
||||
|
||||
self.parts[Self::BOTTOM].surface_rect.width = width + 2 * BORDER_SIZE;
|
||||
self.parts[Self::BOTTOM].surface_rect.y = height as i32;
|
||||
self.parts[Self::BOTTOM].input_rect.as_mut().unwrap().width =
|
||||
self.parts[Self::BOTTOM].surface_rect.width - (BORDER_SIZE * 2)
|
||||
+ (RESIZE_HANDLE_SIZE * 2);
|
||||
|
||||
self.parts[Self::TOP].surface_rect.width = self.parts[Self::BOTTOM].surface_rect.width;
|
||||
self.parts[Self::TOP].input_rect.as_mut().unwrap().width =
|
||||
self.parts[Self::TOP].surface_rect.width - (BORDER_SIZE * 2) + (RESIZE_HANDLE_SIZE * 2);
|
||||
|
||||
self.parts[Self::LEFT].surface_rect.height = height + HEADER_SIZE;
|
||||
self.parts[Self::LEFT].input_rect.as_mut().unwrap().height =
|
||||
self.parts[Self::LEFT].surface_rect.height;
|
||||
|
||||
self.parts[Self::RIGHT].surface_rect.height = self.parts[Self::LEFT].surface_rect.height;
|
||||
self.parts[Self::RIGHT].surface_rect.x = width as i32;
|
||||
self.parts[Self::RIGHT].input_rect.as_mut().unwrap().height =
|
||||
self.parts[Self::RIGHT].surface_rect.height;
|
||||
}
|
||||
|
||||
pub fn header(&self) -> &Part {
|
||||
&self.parts[Self::HEADER]
|
||||
}
|
||||
|
||||
pub fn side_height(&self) -> u32 {
|
||||
self.parts[Self::LEFT].surface_rect.height
|
||||
}
|
||||
|
||||
pub fn find_surface(&self, surface: &ObjectId) -> Location {
|
||||
let pos = match self
|
||||
.parts
|
||||
.iter()
|
||||
.position(|part| &part.surface.id() == surface)
|
||||
{
|
||||
Some(pos) => pos,
|
||||
None => return Location::None,
|
||||
};
|
||||
|
||||
match pos {
|
||||
Self::HEADER => Location::Head,
|
||||
Self::TOP => Location::Top,
|
||||
Self::BOTTOM => Location::Bottom,
|
||||
Self::LEFT => Location::Left,
|
||||
Self::RIGHT => Location::Right,
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Rect {
|
||||
pub x: i32,
|
||||
pub y: i32,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Part {
|
||||
pub surface: WlTyped<WlSurface, SurfaceData>,
|
||||
pub subsurface: WlTyped<WlSubsurface, SubsurfaceData>,
|
||||
|
||||
/// Positioned relative to the main surface.
|
||||
pub surface_rect: Rect,
|
||||
/// Positioned relative to the local surface, aka. `surface_rect`.
|
||||
///
|
||||
/// `None` if it fully covers `surface_rect`.
|
||||
pub input_rect: Option<Rect>,
|
||||
}
|
||||
|
||||
impl Part {
|
||||
fn new<State>(
|
||||
parent: &WlTyped<WlSurface, SurfaceData>,
|
||||
subcompositor: &SubcompositorState,
|
||||
queue_handle: &QueueHandle<State>,
|
||||
surface_rect: Rect,
|
||||
input_rect: Option<Rect>,
|
||||
) -> Part
|
||||
where
|
||||
State: Dispatch<WlSurface, SurfaceData> + Dispatch<WlSubsurface, SubsurfaceData> + 'static,
|
||||
{
|
||||
let (subsurface, surface) =
|
||||
subcompositor.create_subsurface(parent.inner().clone(), queue_handle);
|
||||
|
||||
let subsurface = WlTyped::wrap::<State>(subsurface);
|
||||
let surface = WlTyped::wrap::<State>(surface);
|
||||
|
||||
// Sync with the parent surface.
|
||||
subsurface.set_sync();
|
||||
|
||||
Part {
|
||||
surface,
|
||||
subsurface,
|
||||
surface_rect,
|
||||
input_rect,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Part {
|
||||
fn drop(&mut self) {
|
||||
self.subsurface.destroy();
|
||||
self.surface.destroy();
|
||||
}
|
||||
}
|
||||
142
patches/sctk-adwaita/src/pointer.rs
vendored
Normal file
142
patches/sctk-adwaita/src/pointer.rs
vendored
Normal file
|
|
@ -0,0 +1,142 @@
|
|||
use std::time::Duration;
|
||||
|
||||
use smithay_client_toolkit::reexports::csd_frame::{
|
||||
CursorIcon, FrameAction, ResizeEdge, WindowManagerCapabilities, WindowState,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
buttons::ButtonKind,
|
||||
theme::{BORDER_SIZE, HEADER_SIZE},
|
||||
};
|
||||
|
||||
/// Time to register the next click as a double click.
|
||||
///
|
||||
/// The value is the same as the default in gtk4.
|
||||
const DOUBLE_CLICK_DURATION: Duration = Duration::from_millis(400);
|
||||
|
||||
/// The state of the mouse input inside the decorations frame.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct MouseState {
|
||||
pub location: Location,
|
||||
|
||||
/// The surface local location inside the surface.
|
||||
position: (f64, f64),
|
||||
|
||||
/// The instant of the last click.
|
||||
last_normal_click: Option<Duration>,
|
||||
}
|
||||
|
||||
impl MouseState {
|
||||
/// The normal click on decorations frame was made.
|
||||
pub fn click(
|
||||
&mut self,
|
||||
timestamp: Duration,
|
||||
pressed: bool,
|
||||
resizable: bool,
|
||||
state: &WindowState,
|
||||
wm_capabilities: &WindowManagerCapabilities,
|
||||
) -> Option<FrameAction> {
|
||||
let maximized = state.contains(WindowState::MAXIMIZED);
|
||||
let action = match self.location {
|
||||
Location::Top if resizable => FrameAction::Resize(ResizeEdge::Top),
|
||||
Location::TopLeft if resizable => FrameAction::Resize(ResizeEdge::TopLeft),
|
||||
Location::Left if resizable => FrameAction::Resize(ResizeEdge::Left),
|
||||
Location::BottomLeft if resizable => FrameAction::Resize(ResizeEdge::BottomLeft),
|
||||
Location::Bottom if resizable => FrameAction::Resize(ResizeEdge::Bottom),
|
||||
Location::BottomRight if resizable => FrameAction::Resize(ResizeEdge::BottomRight),
|
||||
Location::Right if resizable => FrameAction::Resize(ResizeEdge::Right),
|
||||
Location::TopRight if resizable => FrameAction::Resize(ResizeEdge::TopRight),
|
||||
Location::Button(ButtonKind::Close) if !pressed => FrameAction::Close,
|
||||
Location::Button(ButtonKind::Maximize) if !pressed && !maximized => {
|
||||
FrameAction::Maximize
|
||||
}
|
||||
Location::Button(ButtonKind::Maximize) if !pressed && maximized => {
|
||||
FrameAction::UnMaximize
|
||||
}
|
||||
Location::Button(ButtonKind::Minimize) if !pressed => FrameAction::Minimize,
|
||||
Location::Head
|
||||
if pressed && wm_capabilities.contains(WindowManagerCapabilities::MAXIMIZE) =>
|
||||
{
|
||||
match self.last_normal_click.replace(timestamp) {
|
||||
Some(last) if timestamp.saturating_sub(last) < DOUBLE_CLICK_DURATION => {
|
||||
if maximized {
|
||||
FrameAction::UnMaximize
|
||||
} else {
|
||||
FrameAction::Maximize
|
||||
}
|
||||
}
|
||||
_ => FrameAction::Move,
|
||||
}
|
||||
}
|
||||
Location::Head if pressed => FrameAction::Move,
|
||||
_ => return None,
|
||||
};
|
||||
|
||||
Some(action)
|
||||
}
|
||||
|
||||
/// Alternative click on decorations frame was made.
|
||||
pub fn alternate_click(
|
||||
&mut self,
|
||||
pressed: bool,
|
||||
wm_capabilities: &WindowManagerCapabilities,
|
||||
) -> Option<FrameAction> {
|
||||
// Invalidate the normal click.
|
||||
self.last_normal_click = None;
|
||||
|
||||
match self.location {
|
||||
Location::Head | Location::Button(_)
|
||||
if pressed && wm_capabilities.contains(WindowManagerCapabilities::WINDOW_MENU) =>
|
||||
{
|
||||
Some(FrameAction::ShowMenu(
|
||||
// XXX this could be one 1pt off when the frame is not maximized, but it's not
|
||||
// like it really matters in the end.
|
||||
self.position.0 as i32 - BORDER_SIZE as i32,
|
||||
// We must offset it by header size for precise position.
|
||||
self.position.1 as i32 - HEADER_SIZE as i32,
|
||||
))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The mouse moved inside the decorations frame.
|
||||
pub fn moved(&mut self, location: Location, x: f64, y: f64, resizable: bool) -> CursorIcon {
|
||||
self.location = location;
|
||||
self.position = (x, y);
|
||||
match self.location {
|
||||
_ if !resizable => CursorIcon::Default,
|
||||
Location::Top => CursorIcon::NResize,
|
||||
Location::TopRight => CursorIcon::NeResize,
|
||||
Location::Right => CursorIcon::EResize,
|
||||
Location::BottomRight => CursorIcon::SeResize,
|
||||
Location::Bottom => CursorIcon::SResize,
|
||||
Location::BottomLeft => CursorIcon::SwResize,
|
||||
Location::Left => CursorIcon::WResize,
|
||||
Location::TopLeft => CursorIcon::NwResize,
|
||||
_ => CursorIcon::Default,
|
||||
}
|
||||
}
|
||||
|
||||
/// The mouse left the decorations frame.
|
||||
pub fn left(&mut self) {
|
||||
// Reset only the location.
|
||||
self.location = Location::None;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
|
||||
pub enum Location {
|
||||
#[default]
|
||||
None,
|
||||
Head,
|
||||
Top,
|
||||
TopRight,
|
||||
Right,
|
||||
BottomRight,
|
||||
Bottom,
|
||||
BottomLeft,
|
||||
Left,
|
||||
TopLeft,
|
||||
Button(ButtonKind),
|
||||
}
|
||||
397
patches/sctk-adwaita/src/shadow.rs
vendored
Normal file
397
patches/sctk-adwaita/src/shadow.rs
vendored
Normal file
|
|
@ -0,0 +1,397 @@
|
|||
use crate::{parts::DecorationParts, theme};
|
||||
use std::collections::BTreeMap;
|
||||
use tiny_skia::{Pixmap, PixmapMut, PixmapRef, Point, PremultipliedColorU8};
|
||||
|
||||
// These values were generated from a screenshot of an libadwaita window using a script.
|
||||
// For more details see: https://github.com/PolyMeilex/sctk-adwaita/pull/43
|
||||
pub const SHADOW_SIZE: u32 = 43;
|
||||
const SHADOW_PARAMS_ACTIVE: (f32, f32, f32) = (0.206_505_5, 0.104_617_53, -0.000_542_446_2);
|
||||
const SHADOW_PARAMS_INACTIVE: (f32, f32, f32) = (0.168_297_29, 0.204_299_8, 0.001_769_798_6);
|
||||
|
||||
fn shadow(pixel_dist: f32, scale: u32, active: bool) -> f32 {
|
||||
let (a, b, c) = if active {
|
||||
SHADOW_PARAMS_ACTIVE
|
||||
} else {
|
||||
SHADOW_PARAMS_INACTIVE
|
||||
};
|
||||
|
||||
a * (-b * (pixel_dist / scale as f32)).exp() + c
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct RenderedShadow {
|
||||
side: Pixmap,
|
||||
edges: Pixmap,
|
||||
}
|
||||
|
||||
impl RenderedShadow {
|
||||
fn new(scale: u32, active: bool) -> RenderedShadow {
|
||||
let shadow_size = SHADOW_SIZE * scale;
|
||||
let corner_radius = theme::CORNER_RADIUS * scale;
|
||||
|
||||
#[allow(clippy::unwrap_used)]
|
||||
let mut side = Pixmap::new(shadow_size, 1).unwrap();
|
||||
for x in 0..side.width() as usize {
|
||||
let alpha = (shadow(x as f32 + 0.5, scale, active) * u8::MAX as f32).round() as u8;
|
||||
|
||||
#[allow(clippy::unwrap_used)]
|
||||
let color = PremultipliedColorU8::from_rgba(0, 0, 0, alpha).unwrap();
|
||||
side.pixels_mut()[x] = color;
|
||||
}
|
||||
|
||||
let edges_size = (corner_radius + shadow_size) * 2;
|
||||
#[allow(clippy::unwrap_used)]
|
||||
let mut edges = Pixmap::new(edges_size, edges_size).unwrap();
|
||||
let edges_middle = Point::from_xy(edges_size as f32 / 2.0, edges_size as f32 / 2.0);
|
||||
for y in 0..edges_size as usize {
|
||||
let y_pos = y as f32 + 0.5;
|
||||
for x in 0..edges_size as usize {
|
||||
let dist = edges_middle.distance(Point::from_xy(x as f32 + 0.5, y_pos))
|
||||
- corner_radius as f32;
|
||||
let alpha = (shadow(dist, scale, active) * u8::MAX as f32).round() as u8;
|
||||
|
||||
#[allow(clippy::unwrap_used)]
|
||||
let color = PremultipliedColorU8::from_rgba(0, 0, 0, alpha).unwrap();
|
||||
edges.pixels_mut()[y * edges_size as usize + x] = color;
|
||||
}
|
||||
}
|
||||
|
||||
RenderedShadow { side, edges }
|
||||
}
|
||||
|
||||
fn side_draw(
|
||||
&self,
|
||||
flipped: bool,
|
||||
rotated: bool,
|
||||
stack: usize,
|
||||
dst_pixmap: &mut PixmapMut,
|
||||
dst_left: usize,
|
||||
dst_top: usize,
|
||||
) {
|
||||
fn iter_copy<'a>(
|
||||
src: impl Iterator<Item = &'a PremultipliedColorU8>,
|
||||
dst: impl Iterator<Item = &'a mut PremultipliedColorU8>,
|
||||
) {
|
||||
src.zip(dst).for_each(|(src, dst)| *dst = *src)
|
||||
}
|
||||
|
||||
let dst_width = dst_pixmap.width() as usize;
|
||||
let dst_pixels = dst_pixmap.pixels_mut();
|
||||
match (flipped, rotated) {
|
||||
(false, false) => (0..stack).for_each(|i| {
|
||||
let dst = dst_pixels
|
||||
.iter_mut()
|
||||
.skip((dst_top + i) * dst_width + dst_left);
|
||||
iter_copy(self.side.pixels().iter(), dst);
|
||||
}),
|
||||
(false, true) => (0..stack).for_each(|i| {
|
||||
let dst = dst_pixels
|
||||
.iter_mut()
|
||||
.skip(dst_top * dst_width + dst_left + i)
|
||||
.step_by(dst_width);
|
||||
iter_copy(self.side.pixels().iter(), dst);
|
||||
}),
|
||||
(true, false) => (0..stack).for_each(|i| {
|
||||
let dst = dst_pixels
|
||||
.iter_mut()
|
||||
.skip((dst_top + i) * dst_width + dst_left);
|
||||
iter_copy(self.side.pixels().iter().rev(), dst);
|
||||
}),
|
||||
(true, true) => (0..stack).for_each(|i| {
|
||||
let dst = dst_pixels
|
||||
.iter_mut()
|
||||
.skip(dst_top * dst_width + dst_left + i)
|
||||
.step_by(dst_width);
|
||||
iter_copy(self.side.pixels().iter().rev(), dst);
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn edges_draw(
|
||||
&self,
|
||||
src_x_offset: isize,
|
||||
src_y_offset: isize,
|
||||
dst_pixmap: &mut PixmapMut,
|
||||
dst_rect_left: usize,
|
||||
dst_rect_top: usize,
|
||||
dst_rect_width: usize,
|
||||
dst_rect_height: usize,
|
||||
) {
|
||||
let src_width = self.edges.width() as usize;
|
||||
let src_pixels = self.edges.pixels();
|
||||
let dst_width = dst_pixmap.width() as usize;
|
||||
let dst_pixels = dst_pixmap.pixels_mut();
|
||||
for y in 0..dst_rect_height {
|
||||
let dst_y = dst_rect_top + y;
|
||||
let src_y = y as isize + src_y_offset;
|
||||
if src_y < 0 {
|
||||
continue;
|
||||
}
|
||||
|
||||
let src_y = src_y as usize;
|
||||
for x in 0..dst_rect_width {
|
||||
let dst_x = dst_rect_left + x;
|
||||
let src_x = x as isize + src_x_offset;
|
||||
if src_x < 0 {
|
||||
continue;
|
||||
}
|
||||
|
||||
let src = src_pixels.get(src_y * src_width + src_x as usize);
|
||||
let dst = dst_pixels.get_mut(dst_y * dst_width + dst_x);
|
||||
if let (Some(src), Some(dst)) = (src, dst) {
|
||||
*dst = *src;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn draw(&self, dst_pixmap: &mut PixmapMut, scale: u32, part_idx: usize) {
|
||||
let shadow_size = (SHADOW_SIZE * scale) as usize;
|
||||
let visible_border_size = (theme::VISIBLE_BORDER_SIZE * scale) as usize;
|
||||
let corner_radius = (theme::CORNER_RADIUS * scale) as usize;
|
||||
assert!(corner_radius > visible_border_size);
|
||||
|
||||
let dst_width = dst_pixmap.width() as usize;
|
||||
let dst_height = dst_pixmap.height() as usize;
|
||||
let edges_half = self.edges.width() as usize / 2;
|
||||
match part_idx {
|
||||
DecorationParts::TOP => {
|
||||
let left_edge_width = edges_half;
|
||||
let right_edge_width = edges_half;
|
||||
let side_width = dst_width
|
||||
.saturating_sub(left_edge_width)
|
||||
.saturating_sub(right_edge_width);
|
||||
|
||||
self.edges_draw(
|
||||
0,
|
||||
-(visible_border_size as isize),
|
||||
dst_pixmap,
|
||||
0,
|
||||
0,
|
||||
left_edge_width,
|
||||
dst_height,
|
||||
);
|
||||
|
||||
self.side_draw(
|
||||
true,
|
||||
true,
|
||||
side_width,
|
||||
dst_pixmap,
|
||||
left_edge_width,
|
||||
visible_border_size,
|
||||
);
|
||||
|
||||
self.edges_draw(
|
||||
edges_half as isize,
|
||||
-(visible_border_size as isize),
|
||||
dst_pixmap,
|
||||
left_edge_width + side_width,
|
||||
0,
|
||||
right_edge_width,
|
||||
dst_height,
|
||||
);
|
||||
}
|
||||
DecorationParts::LEFT => {
|
||||
let top_edge_height = corner_radius;
|
||||
let bottom_edge_height = corner_radius - visible_border_size;
|
||||
let side_height = dst_height
|
||||
.saturating_sub(top_edge_height)
|
||||
.saturating_sub(bottom_edge_height);
|
||||
|
||||
self.edges_draw(
|
||||
0,
|
||||
shadow_size as isize,
|
||||
dst_pixmap,
|
||||
0,
|
||||
0,
|
||||
dst_width.saturating_sub(visible_border_size),
|
||||
top_edge_height,
|
||||
);
|
||||
|
||||
self.side_draw(true, false, side_height, dst_pixmap, 0, top_edge_height);
|
||||
|
||||
self.edges_draw(
|
||||
0,
|
||||
edges_half as isize,
|
||||
dst_pixmap,
|
||||
0,
|
||||
top_edge_height + side_height,
|
||||
dst_width.saturating_sub(visible_border_size),
|
||||
bottom_edge_height,
|
||||
);
|
||||
}
|
||||
DecorationParts::RIGHT => {
|
||||
let top_edge_height = corner_radius;
|
||||
let bottom_edge_height = corner_radius - visible_border_size;
|
||||
let side_height = dst_height
|
||||
.saturating_sub(top_edge_height)
|
||||
.saturating_sub(bottom_edge_height);
|
||||
|
||||
self.edges_draw(
|
||||
edges_half as isize + corner_radius as isize,
|
||||
shadow_size as isize,
|
||||
dst_pixmap,
|
||||
visible_border_size,
|
||||
0,
|
||||
dst_width.saturating_sub(visible_border_size),
|
||||
top_edge_height,
|
||||
);
|
||||
|
||||
self.side_draw(
|
||||
false,
|
||||
false,
|
||||
side_height,
|
||||
dst_pixmap,
|
||||
visible_border_size,
|
||||
top_edge_height,
|
||||
);
|
||||
|
||||
self.edges_draw(
|
||||
edges_half as isize + corner_radius as isize,
|
||||
edges_half as isize,
|
||||
dst_pixmap,
|
||||
visible_border_size,
|
||||
top_edge_height + side_height,
|
||||
dst_width.saturating_sub(visible_border_size),
|
||||
bottom_edge_height,
|
||||
);
|
||||
}
|
||||
DecorationParts::BOTTOM => {
|
||||
let left_edge_width = edges_half;
|
||||
let right_edge_width = edges_half;
|
||||
let side_width = dst_width
|
||||
.saturating_sub(left_edge_width)
|
||||
.saturating_sub(right_edge_width);
|
||||
|
||||
self.edges_draw(
|
||||
0,
|
||||
edges_half as isize + (corner_radius - visible_border_size) as isize,
|
||||
dst_pixmap,
|
||||
0,
|
||||
0,
|
||||
left_edge_width,
|
||||
dst_height,
|
||||
);
|
||||
|
||||
self.side_draw(
|
||||
false,
|
||||
true,
|
||||
side_width,
|
||||
dst_pixmap,
|
||||
left_edge_width,
|
||||
visible_border_size,
|
||||
);
|
||||
|
||||
self.edges_draw(
|
||||
edges_half as isize,
|
||||
edges_half as isize + (corner_radius - visible_border_size) as isize,
|
||||
dst_pixmap,
|
||||
left_edge_width + side_width,
|
||||
0,
|
||||
right_edge_width,
|
||||
dst_height,
|
||||
);
|
||||
}
|
||||
DecorationParts::HEADER => {
|
||||
self.edges_draw(
|
||||
shadow_size as isize,
|
||||
shadow_size as isize,
|
||||
dst_pixmap,
|
||||
0,
|
||||
0,
|
||||
corner_radius,
|
||||
corner_radius,
|
||||
);
|
||||
|
||||
self.edges_draw(
|
||||
edges_half as isize,
|
||||
shadow_size as isize,
|
||||
dst_pixmap,
|
||||
dst_width.saturating_sub(corner_radius),
|
||||
0,
|
||||
corner_radius,
|
||||
corner_radius,
|
||||
);
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct CachedPart {
|
||||
pixmap: Pixmap,
|
||||
scale: u32,
|
||||
active: bool,
|
||||
}
|
||||
|
||||
impl CachedPart {
|
||||
fn new(
|
||||
dst_pixmap: &PixmapRef,
|
||||
rendered: &RenderedShadow,
|
||||
scale: u32,
|
||||
active: bool,
|
||||
part_idx: usize,
|
||||
) -> CachedPart {
|
||||
#[allow(clippy::unwrap_used)]
|
||||
let mut pixmap = Pixmap::new(dst_pixmap.width(), dst_pixmap.height()).unwrap();
|
||||
rendered.draw(&mut pixmap.as_mut(), scale, part_idx);
|
||||
|
||||
CachedPart {
|
||||
pixmap,
|
||||
scale,
|
||||
active,
|
||||
}
|
||||
}
|
||||
|
||||
fn matches(&self, dst_pixmap: &PixmapRef, dst_scale: u32, dst_active: bool) -> bool {
|
||||
self.pixmap.width() == dst_pixmap.width()
|
||||
&& self.pixmap.height() == dst_pixmap.height()
|
||||
&& self.scale == dst_scale
|
||||
&& self.active == dst_active
|
||||
}
|
||||
|
||||
fn draw(&self, dst_pixmap: &mut PixmapMut) {
|
||||
let src_data = self.pixmap.data();
|
||||
dst_pixmap.data_mut()[..src_data.len()].copy_from_slice(src_data);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Debug)]
|
||||
pub struct Shadow {
|
||||
part_cache: [Option<CachedPart>; 5],
|
||||
// (scale, active) -> RenderedShadow
|
||||
rendered: BTreeMap<(u32, bool), RenderedShadow>,
|
||||
}
|
||||
|
||||
impl Shadow {
|
||||
pub fn draw(&mut self, pixmap: &mut PixmapMut, scale: u32, active: bool, part_idx: usize) {
|
||||
let cache = &mut self.part_cache[part_idx];
|
||||
|
||||
if let Some(cache_value) = cache {
|
||||
if !cache_value.matches(&pixmap.as_ref(), scale, active) {
|
||||
*cache = None;
|
||||
}
|
||||
}
|
||||
|
||||
if cache.is_none() {
|
||||
let rendered = self
|
||||
.rendered
|
||||
.entry((scale, active))
|
||||
.or_insert_with(|| RenderedShadow::new(scale, active));
|
||||
|
||||
*cache = Some(CachedPart::new(
|
||||
&pixmap.as_ref(),
|
||||
rendered,
|
||||
scale,
|
||||
active,
|
||||
part_idx,
|
||||
));
|
||||
}
|
||||
|
||||
// We filled the cache above.
|
||||
#[allow(clippy::unwrap_used)]
|
||||
cache.as_ref().unwrap().draw(pixmap);
|
||||
}
|
||||
}
|
||||
139
patches/sctk-adwaita/src/theme.rs
vendored
Normal file
139
patches/sctk-adwaita/src/theme.rs
vendored
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
pub use tiny_skia::Color;
|
||||
use tiny_skia::{Paint, Shader};
|
||||
|
||||
// https://gitlab.gnome.org/GNOME/gtk/-/blob/1bf88f1d81043fd99740e2f91e56ade7ede7303b/gtk/gtkwindow.c#L165
|
||||
pub(crate) const RESIZE_HANDLE_SIZE: u32 = 12;
|
||||
// https://gitlab.gnome.org/GNOME/gtk/-/blob/1bf88f1d81043fd99740e2f91e56ade7ede7303b/gtk/gtkwindow.c#L166
|
||||
pub(crate) const RESIZE_HANDLE_CORNER_SIZE: u32 = 24;
|
||||
pub(crate) const BORDER_SIZE: u32 = crate::shadow::SHADOW_SIZE + VISIBLE_BORDER_SIZE;
|
||||
pub(crate) const HEADER_SIZE: u32 = 35;
|
||||
pub(crate) const CORNER_RADIUS: u32 = 10;
|
||||
pub(crate) const VISIBLE_BORDER_SIZE: u32 = 1;
|
||||
|
||||
/// The color theme to use with the decorations frame.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ColorTheme {
|
||||
pub active: ColorMap,
|
||||
pub inactive: ColorMap,
|
||||
}
|
||||
|
||||
impl ColorTheme {
|
||||
/// Automatically choose between light & dark themes based on:
|
||||
/// * dbus org.freedesktop.portal.Settings
|
||||
/// <https://flatpak.github.io/xdg-desktop-portal/#gdbus-interface-org-freedesktop-portal-Settings>
|
||||
pub fn auto() -> Self {
|
||||
match crate::config::prefer_dark() {
|
||||
true => Self::dark(),
|
||||
false => Self::light(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Predefined light variant, which aims to replecate Adwaita theme.
|
||||
pub fn light() -> Self {
|
||||
Self {
|
||||
active: ColorMap {
|
||||
headerbar: Color::from_rgba8(235, 235, 235, 255),
|
||||
button_idle: Color::from_rgba8(216, 216, 216, 255),
|
||||
button_hover: Color::from_rgba8(207, 207, 207, 255),
|
||||
button_icon: Color::from_rgba8(42, 42, 42, 255),
|
||||
border_color: Color::from_rgba8(220, 220, 220, 255),
|
||||
font_color: Color::from_rgba8(47, 47, 47, 255),
|
||||
},
|
||||
inactive: ColorMap {
|
||||
headerbar: Color::from_rgba8(250, 250, 250, 255),
|
||||
button_idle: Color::from_rgba8(240, 240, 240, 255),
|
||||
button_hover: Color::from_rgba8(216, 216, 216, 255),
|
||||
button_icon: Color::from_rgba8(148, 148, 148, 255),
|
||||
border_color: Color::from_rgba8(220, 220, 220, 255),
|
||||
font_color: Color::from_rgba8(150, 150, 150, 255),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Predefined dark variant, which aims to replecate Adwaita-dark theme.
|
||||
pub fn dark() -> Self {
|
||||
Self {
|
||||
active: ColorMap {
|
||||
headerbar: Color::from_rgba8(48, 48, 48, 255),
|
||||
button_idle: Color::from_rgba8(69, 69, 69, 255),
|
||||
button_hover: Color::from_rgba8(79, 79, 79, 255),
|
||||
button_icon: Color::from_rgba8(255, 255, 255, 255),
|
||||
border_color: Color::from_rgba8(58, 58, 58, 255),
|
||||
font_color: Color::from_rgba8(255, 255, 255, 255),
|
||||
},
|
||||
inactive: ColorMap {
|
||||
headerbar: Color::from_rgba8(36, 36, 36, 255),
|
||||
button_idle: Color::from_rgba8(47, 47, 47, 255),
|
||||
button_hover: Color::from_rgba8(57, 57, 57, 255),
|
||||
button_icon: Color::from_rgba8(144, 144, 144, 255),
|
||||
border_color: Color::from_rgba8(58, 58, 58, 255),
|
||||
font_color: Color::from_rgba8(144, 144, 144, 255),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn for_state(&self, active: bool) -> &ColorMap {
|
||||
if active {
|
||||
&self.active
|
||||
} else {
|
||||
&self.inactive
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for ColorTheme {
|
||||
fn default() -> Self {
|
||||
Self::auto()
|
||||
}
|
||||
}
|
||||
|
||||
/// The color map for various decorcation parts.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ColorMap {
|
||||
pub headerbar: Color,
|
||||
pub button_idle: Color,
|
||||
pub button_hover: Color,
|
||||
pub button_icon: Color,
|
||||
pub border_color: Color,
|
||||
pub font_color: Color,
|
||||
}
|
||||
|
||||
impl ColorMap {
|
||||
pub(crate) fn headerbar_paint(&self) -> Paint<'_> {
|
||||
Paint {
|
||||
shader: Shader::SolidColor(self.headerbar),
|
||||
anti_alias: true,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn button_idle_paint(&self) -> Paint<'_> {
|
||||
Paint {
|
||||
shader: Shader::SolidColor(self.button_idle),
|
||||
anti_alias: true,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn button_hover_paint(&self) -> Paint<'_> {
|
||||
Paint {
|
||||
shader: Shader::SolidColor(self.button_hover),
|
||||
anti_alias: true,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn button_icon_paint(&self) -> Paint<'_> {
|
||||
Paint {
|
||||
shader: Shader::SolidColor(self.button_icon),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn border_paint(&self) -> Paint<'_> {
|
||||
Paint {
|
||||
shader: Shader::SolidColor(self.border_color),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
61
patches/sctk-adwaita/src/title.rs
vendored
Normal file
61
patches/sctk-adwaita/src/title.rs
vendored
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
use tiny_skia::{Color, Pixmap};
|
||||
|
||||
#[cfg(any(feature = "crossfont", feature = "ab_glyph"))]
|
||||
mod config;
|
||||
#[cfg(any(feature = "crossfont", feature = "ab_glyph"))]
|
||||
mod font_preference;
|
||||
|
||||
#[cfg(feature = "crossfont")]
|
||||
mod crossfont_renderer;
|
||||
|
||||
#[cfg(all(not(feature = "crossfont"), feature = "ab_glyph"))]
|
||||
mod ab_glyph_renderer;
|
||||
|
||||
#[cfg(all(not(feature = "crossfont"), not(feature = "ab_glyph")))]
|
||||
mod dumb;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct TitleText {
|
||||
#[cfg(feature = "crossfont")]
|
||||
imp: crossfont_renderer::CrossfontTitleText,
|
||||
#[cfg(all(not(feature = "crossfont"), feature = "ab_glyph"))]
|
||||
imp: ab_glyph_renderer::AbGlyphTitleText,
|
||||
#[cfg(all(not(feature = "crossfont"), not(feature = "ab_glyph")))]
|
||||
imp: dumb::DumbTitleText,
|
||||
}
|
||||
|
||||
impl TitleText {
|
||||
pub fn new(color: Color) -> Option<Self> {
|
||||
#[cfg(feature = "crossfont")]
|
||||
return crossfont_renderer::CrossfontTitleText::new(color)
|
||||
.ok()
|
||||
.map(|imp| Self { imp });
|
||||
|
||||
#[cfg(all(not(feature = "crossfont"), feature = "ab_glyph"))]
|
||||
return Some(Self {
|
||||
imp: ab_glyph_renderer::AbGlyphTitleText::new(color),
|
||||
});
|
||||
|
||||
#[cfg(all(not(feature = "crossfont"), not(feature = "ab_glyph")))]
|
||||
{
|
||||
let _ = color;
|
||||
return None;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_scale(&mut self, scale: u32) {
|
||||
self.imp.update_scale(scale)
|
||||
}
|
||||
|
||||
pub fn update_title(&mut self, title: impl Into<String>) {
|
||||
self.imp.update_title(title)
|
||||
}
|
||||
|
||||
pub fn update_color(&mut self, color: Color) {
|
||||
self.imp.update_color(color)
|
||||
}
|
||||
|
||||
pub fn pixmap(&self) -> Option<&Pixmap> {
|
||||
self.imp.pixmap()
|
||||
}
|
||||
}
|
||||
BIN
patches/sctk-adwaita/src/title/Cantarell-Regular.ttf
vendored
Normal file
BIN
patches/sctk-adwaita/src/title/Cantarell-Regular.ttf
vendored
Normal file
Binary file not shown.
199
patches/sctk-adwaita/src/title/ab_glyph_renderer.rs
vendored
Normal file
199
patches/sctk-adwaita/src/title/ab_glyph_renderer.rs
vendored
Normal file
|
|
@ -0,0 +1,199 @@
|
|||
//! Title renderer using ab_glyph.
|
||||
//!
|
||||
//! Requires no dynamically linked dependencies.
|
||||
//!
|
||||
//! Can fallback to a embedded Cantarell-Regular.ttf font (SIL Open Font Licence v1.1)
|
||||
//! if the system font doesn't work.
|
||||
use crate::title::{config, font_preference::FontPreference};
|
||||
use ab_glyph::{point, Font, FontRef, Glyph, PxScale, PxScaleFont, ScaleFont, VariableFont};
|
||||
use std::{fs::File, process::Command};
|
||||
use tiny_skia::{Color, Pixmap, PremultipliedColorU8};
|
||||
|
||||
const CANTARELL: &[u8] = include_bytes!("Cantarell-Regular.ttf");
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct AbGlyphTitleText {
|
||||
title: String,
|
||||
font: Option<(memmap2::Mmap, FontPreference)>,
|
||||
original_px_size: f32,
|
||||
size: PxScale,
|
||||
color: Color,
|
||||
pixmap: Option<Pixmap>,
|
||||
}
|
||||
|
||||
impl AbGlyphTitleText {
|
||||
pub fn new(color: Color) -> Self {
|
||||
let font_pref = config::titlebar_font().unwrap_or_default();
|
||||
let font_pref_pt_size = font_pref.pt_size;
|
||||
let font = font_file_matching(&font_pref)
|
||||
.and_then(|f| mmap(&f))
|
||||
.map(|mmap| (mmap, font_pref));
|
||||
|
||||
let size = parse_font(&font)
|
||||
.pt_to_px_scale(font_pref_pt_size)
|
||||
.unwrap_or_else(|| {
|
||||
log::error!("invalid font units_per_em");
|
||||
PxScale { x: 17.6, y: 17.6 }
|
||||
});
|
||||
|
||||
Self {
|
||||
title: <_>::default(),
|
||||
font,
|
||||
original_px_size: size.x,
|
||||
size,
|
||||
color,
|
||||
pixmap: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_scale(&mut self, scale: u32) {
|
||||
let new_scale = PxScale::from(self.original_px_size * scale as f32);
|
||||
if (self.size.x - new_scale.x).abs() > f32::EPSILON {
|
||||
self.size = new_scale;
|
||||
self.pixmap = self.render();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_title(&mut self, title: impl Into<String>) {
|
||||
let new_title = title.into();
|
||||
if new_title != self.title {
|
||||
self.title = new_title;
|
||||
self.pixmap = self.render();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_color(&mut self, color: Color) {
|
||||
if color != self.color {
|
||||
self.color = color;
|
||||
self.pixmap = self.render();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn pixmap(&self) -> Option<&Pixmap> {
|
||||
self.pixmap.as_ref()
|
||||
}
|
||||
|
||||
/// Render returning the new `Pixmap`.
|
||||
fn render(&self) -> Option<Pixmap> {
|
||||
let font = parse_font(&self.font);
|
||||
let font = font.as_scaled(self.size);
|
||||
|
||||
let glyphs = self.layout(&font);
|
||||
let last_glyph = glyphs.last()?;
|
||||
// + 2 because ab_glyph likes to draw outside of its area,
|
||||
// so we add 1px border around the pixmap
|
||||
let width = (last_glyph.position.x + font.h_advance(last_glyph.id)).ceil() as u32 + 2;
|
||||
let height = font.height().ceil() as u32 + 2;
|
||||
|
||||
let mut pixmap = Pixmap::new(width, height)?;
|
||||
|
||||
let pixels = pixmap.pixels_mut();
|
||||
|
||||
for glyph in glyphs {
|
||||
if let Some(outline) = font.outline_glyph(glyph) {
|
||||
let bounds = outline.px_bounds();
|
||||
let left = bounds.min.x as u32;
|
||||
let top = bounds.min.y as u32;
|
||||
outline.draw(|x, y, c| {
|
||||
// `ab_glyph` may return values greater than 1.0, but they are defined to be
|
||||
// same as 1.0. For our purposes, we need to constrain this value.
|
||||
let c = c.min(1.0);
|
||||
|
||||
// offset the index by 1, so it is in the center of the pixmap
|
||||
let p_idx = (top + y + 1) * width + (left + x + 1);
|
||||
let Some(pixel) = pixels.get_mut(p_idx as usize) else {
|
||||
log::warn!("Ignoring out of range pixel (pixel id: {p_idx}");
|
||||
return;
|
||||
};
|
||||
|
||||
let old_alpha_u8 = pixel.alpha();
|
||||
|
||||
let new_alpha = c + (old_alpha_u8 as f32 / 255.0);
|
||||
if let Some(px) = PremultipliedColorU8::from_rgba(
|
||||
(self.color.red() * new_alpha * 255.0) as _,
|
||||
(self.color.green() * new_alpha * 255.0) as _,
|
||||
(self.color.blue() * new_alpha * 255.0) as _,
|
||||
(new_alpha * 255.0) as _,
|
||||
) {
|
||||
*pixel = px;
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Some(pixmap)
|
||||
}
|
||||
|
||||
/// Simple single-line glyph layout.
|
||||
fn layout(&self, font: &PxScaleFont<impl Font>) -> Vec<Glyph> {
|
||||
let mut caret = point(0.0, font.ascent());
|
||||
let mut last_glyph: Option<Glyph> = None;
|
||||
let mut target = Vec::new();
|
||||
for c in self.title.chars() {
|
||||
if c.is_control() {
|
||||
continue;
|
||||
}
|
||||
let mut glyph = font.scaled_glyph(c);
|
||||
if let Some(previous) = last_glyph.take() {
|
||||
caret.x += font.kern(previous.id, glyph.id);
|
||||
}
|
||||
glyph.position = caret;
|
||||
|
||||
last_glyph = Some(glyph.clone());
|
||||
caret.x += font.h_advance(glyph.id);
|
||||
|
||||
target.push(glyph);
|
||||
}
|
||||
target
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse the memmapped system font or fallback to built-in cantarell.
|
||||
fn parse_font(sys_font: &Option<(memmap2::Mmap, FontPreference)>) -> FontRef<'_> {
|
||||
match sys_font {
|
||||
Some((mmap, font_pref)) => {
|
||||
FontRef::try_from_slice(mmap)
|
||||
.map(|mut f| {
|
||||
// basic "bold" handling for variable fonts
|
||||
if font_pref
|
||||
.style
|
||||
.as_deref()
|
||||
.map_or(false, |s| s.eq_ignore_ascii_case("bold"))
|
||||
{
|
||||
f.set_variation(b"wght", 700.0);
|
||||
}
|
||||
f
|
||||
})
|
||||
.unwrap_or_else(|_| {
|
||||
// We control the default font, so I guess it's fine to unwrap it
|
||||
#[allow(clippy::unwrap_used)]
|
||||
FontRef::try_from_slice(CANTARELL).unwrap()
|
||||
})
|
||||
}
|
||||
// We control the default font, so I guess it's fine to unwrap it
|
||||
#[allow(clippy::unwrap_used)]
|
||||
_ => FontRef::try_from_slice(CANTARELL).unwrap(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Font-config without dynamically linked dependencies
|
||||
fn font_file_matching(pref: &FontPreference) -> Option<File> {
|
||||
let mut pattern = pref.name.clone();
|
||||
if let Some(style) = &pref.style {
|
||||
pattern.push(':');
|
||||
pattern.push_str(style);
|
||||
}
|
||||
Command::new("fc-match")
|
||||
.arg("-f")
|
||||
.arg("%{file}")
|
||||
.arg(&pattern)
|
||||
.output()
|
||||
.ok()
|
||||
.and_then(|out| String::from_utf8(out.stdout).ok())
|
||||
.and_then(|path| File::open(path.trim()).ok())
|
||||
}
|
||||
|
||||
fn mmap(file: &File) -> Option<memmap2::Mmap> {
|
||||
// Safety: System font files are not expected to be mutated during use
|
||||
unsafe { memmap2::Mmap::map(file).ok() }
|
||||
}
|
||||
20
patches/sctk-adwaita/src/title/config.rs
vendored
Normal file
20
patches/sctk-adwaita/src/title/config.rs
vendored
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
//! System font configuration.
|
||||
use crate::title::font_preference::FontPreference;
|
||||
use std::process::Command;
|
||||
|
||||
/// Query system for which font to use for window titles.
|
||||
pub(crate) fn titlebar_font() -> Option<FontPreference> {
|
||||
// outputs something like: `'Cantarell Bold 12'`
|
||||
let stdout = Command::new("gsettings")
|
||||
.args(["get", "org.gnome.desktop.wm.preferences", "titlebar-font"])
|
||||
.output()
|
||||
.ok()
|
||||
.and_then(|out| String::from_utf8(out.stdout).ok())?;
|
||||
|
||||
FontPreference::from_name_style_size(
|
||||
stdout
|
||||
.trim()
|
||||
.trim_end_matches('\'')
|
||||
.trim_start_matches('\''),
|
||||
)
|
||||
}
|
||||
227
patches/sctk-adwaita/src/title/crossfont_renderer.rs
vendored
Normal file
227
patches/sctk-adwaita/src/title/crossfont_renderer.rs
vendored
Normal file
|
|
@ -0,0 +1,227 @@
|
|||
use std::mem;
|
||||
|
||||
use crossfont::{GlyphKey, Rasterize, RasterizedGlyph};
|
||||
use tiny_skia::{Color, Pixmap, PixmapPaint, PixmapRef, Transform};
|
||||
|
||||
use crate::title::config;
|
||||
|
||||
pub struct CrossfontTitleText {
|
||||
title: String,
|
||||
|
||||
font_desc: crossfont::FontDesc,
|
||||
font_key: crossfont::FontKey,
|
||||
size: crossfont::Size,
|
||||
scale: u32,
|
||||
metrics: crossfont::Metrics,
|
||||
rasterizer: crossfont::Rasterizer,
|
||||
color: Color,
|
||||
|
||||
pixmap: Option<Pixmap>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for CrossfontTitleText {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("TitleText")
|
||||
.field("title", &self.title)
|
||||
.field("font_desc", &self.font_desc)
|
||||
.field("font_key", &self.font_key)
|
||||
.field("size", &self.size)
|
||||
.field("scale", &self.scale)
|
||||
.field("pixmap", &self.pixmap)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl CrossfontTitleText {
|
||||
pub fn new(color: Color) -> Result<Self, crossfont::Error> {
|
||||
let title = "".into();
|
||||
|
||||
let font_pref = config::titlebar_font().unwrap_or_default();
|
||||
let font_style = font_pref
|
||||
.style
|
||||
.map(crossfont::Style::Specific)
|
||||
.unwrap_or_else(|| crossfont::Style::Description {
|
||||
slant: crossfont::Slant::Normal,
|
||||
weight: crossfont::Weight::Normal,
|
||||
});
|
||||
let font_desc = crossfont::FontDesc::new(&font_pref.name, font_style);
|
||||
|
||||
let mut rasterizer = crossfont::Rasterizer::new()?;
|
||||
let size = crossfont::Size::new(font_pref.pt_size);
|
||||
let font_key = rasterizer.load_font(&font_desc, size)?;
|
||||
|
||||
// Need to load at least one glyph for the face before calling metrics.
|
||||
// The glyph requested here ('m' at the time of writing) has no special
|
||||
// meaning.
|
||||
rasterizer.get_glyph(GlyphKey {
|
||||
font_key,
|
||||
character: 'm',
|
||||
size,
|
||||
})?;
|
||||
|
||||
let metrics = rasterizer.metrics(font_key, size)?;
|
||||
|
||||
let mut this = Self {
|
||||
pixmap: None,
|
||||
rasterizer,
|
||||
font_desc,
|
||||
font_key,
|
||||
scale: 1,
|
||||
metrics,
|
||||
title,
|
||||
color,
|
||||
size,
|
||||
};
|
||||
|
||||
this.rerender();
|
||||
|
||||
Ok(this)
|
||||
}
|
||||
|
||||
fn update_metrics(&mut self) -> Result<(), crossfont::Error> {
|
||||
self.rasterizer.get_glyph(GlyphKey {
|
||||
font_key: self.font_key,
|
||||
character: 'm',
|
||||
size: self.size,
|
||||
})?;
|
||||
self.metrics = self.rasterizer.metrics(self.font_key, self.size)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn update_scale(&mut self, scale: u32) {
|
||||
let old_scale = mem::replace(&mut self.scale, scale);
|
||||
if old_scale != self.scale {
|
||||
self.size = self.size.scale(self.scale as f32 / old_scale as f32);
|
||||
self.update_metrics().ok();
|
||||
self.rerender();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_title<S: Into<String>>(&mut self, title: S) {
|
||||
let title = title.into();
|
||||
if self.title != title {
|
||||
self.title = title;
|
||||
self.rerender();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_color(&mut self, color: Color) {
|
||||
if self.color != color {
|
||||
self.color = color;
|
||||
self.rerender();
|
||||
}
|
||||
}
|
||||
|
||||
fn rerender(&mut self) {
|
||||
let glyphs: Vec<_> = self
|
||||
.title
|
||||
.chars()
|
||||
.filter_map(|character| {
|
||||
let key = GlyphKey {
|
||||
character,
|
||||
font_key: self.font_key,
|
||||
size: self.size,
|
||||
};
|
||||
|
||||
self.rasterizer
|
||||
.get_glyph(key)
|
||||
.map(|glyph| (key, glyph))
|
||||
.ok()
|
||||
})
|
||||
.collect();
|
||||
|
||||
if glyphs.is_empty() {
|
||||
self.pixmap = None;
|
||||
return;
|
||||
}
|
||||
|
||||
let width = self.calc_width(&glyphs);
|
||||
let height = self.metrics.line_height.round() as i32;
|
||||
|
||||
let mut pixmap = if let Some(p) = Pixmap::new(width as u32, height as u32) {
|
||||
p
|
||||
} else {
|
||||
self.pixmap = None;
|
||||
return;
|
||||
};
|
||||
// pixmap.fill(Color::from_rgba8(255, 0, 0, 55));
|
||||
|
||||
let mut caret = 0;
|
||||
let mut last_glyph = None;
|
||||
|
||||
for (key, glyph) in glyphs {
|
||||
let mut buffer = Vec::with_capacity(glyph.width as usize * 4);
|
||||
|
||||
let glyph_buffer = match &glyph.buffer {
|
||||
crossfont::BitmapBuffer::Rgb(v) => v.chunks(3),
|
||||
crossfont::BitmapBuffer::Rgba(v) => v.chunks(4),
|
||||
};
|
||||
|
||||
for px in glyph_buffer {
|
||||
let alpha = if let Some(alpha) = px.get(3) {
|
||||
*alpha as f32 / 255.0
|
||||
} else {
|
||||
let r = px[0] as f32 / 255.0;
|
||||
let g = px[1] as f32 / 255.0;
|
||||
let b = px[2] as f32 / 255.0;
|
||||
(r + g + b) / 3.0
|
||||
};
|
||||
|
||||
let mut color = self.color;
|
||||
color.set_alpha(alpha);
|
||||
let color = color.premultiply().to_color_u8();
|
||||
|
||||
buffer.push(color.red());
|
||||
buffer.push(color.green());
|
||||
buffer.push(color.blue());
|
||||
buffer.push(color.alpha());
|
||||
}
|
||||
|
||||
if let Some(last) = last_glyph {
|
||||
let (x, _) = self.rasterizer.kerning(last, key);
|
||||
caret += x as i32;
|
||||
}
|
||||
|
||||
if let Some(pixmap_glyph) =
|
||||
PixmapRef::from_bytes(&buffer, glyph.width as _, glyph.height as _)
|
||||
{
|
||||
pixmap.draw_pixmap(
|
||||
glyph.left + caret,
|
||||
height - glyph.top + self.metrics.descent.round() as i32,
|
||||
pixmap_glyph,
|
||||
&PixmapPaint::default(),
|
||||
Transform::identity(),
|
||||
None,
|
||||
);
|
||||
}
|
||||
|
||||
caret += glyph.advance.0;
|
||||
|
||||
last_glyph = Some(key);
|
||||
}
|
||||
|
||||
self.pixmap = Some(pixmap);
|
||||
}
|
||||
|
||||
pub fn pixmap(&self) -> Option<&Pixmap> {
|
||||
self.pixmap.as_ref()
|
||||
}
|
||||
|
||||
fn calc_width(&mut self, glyphs: &[(GlyphKey, RasterizedGlyph)]) -> i32 {
|
||||
let mut caret = 0;
|
||||
let mut last_glyph: Option<&GlyphKey> = None;
|
||||
|
||||
for (key, glyph) in glyphs.iter() {
|
||||
if let Some(last) = last_glyph {
|
||||
let (x, _) = self.rasterizer.kerning(*last, *key);
|
||||
caret += x as i32;
|
||||
}
|
||||
|
||||
caret += glyph.advance.0;
|
||||
|
||||
last_glyph = Some(key);
|
||||
}
|
||||
|
||||
caret
|
||||
}
|
||||
}
|
||||
16
patches/sctk-adwaita/src/title/dumb.rs
vendored
Normal file
16
patches/sctk-adwaita/src/title/dumb.rs
vendored
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
use tiny_skia::{Color, Pixmap};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct DumbTitleText {}
|
||||
|
||||
impl DumbTitleText {
|
||||
pub fn update_scale(&mut self, _scale: u32) {}
|
||||
|
||||
pub fn update_title<S: Into<String>>(&mut self, _title: S) {}
|
||||
|
||||
pub fn update_color(&mut self, _color: Color) {}
|
||||
|
||||
pub fn pixmap(&self) -> Option<&Pixmap> {
|
||||
None
|
||||
}
|
||||
}
|
||||
91
patches/sctk-adwaita/src/title/font_preference.rs
vendored
Normal file
91
patches/sctk-adwaita/src/title/font_preference.rs
vendored
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
#[derive(Debug)]
|
||||
pub(crate) struct FontPreference {
|
||||
pub name: String,
|
||||
pub style: Option<String>,
|
||||
pub pt_size: f32,
|
||||
}
|
||||
|
||||
impl Default for FontPreference {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
name: "sans-serif".into(),
|
||||
style: None,
|
||||
pt_size: 10.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FontPreference {
|
||||
/// Parse config string like `Cantarell 12`, `Cantarell Bold 11`, `Noto Serif CJK HK Bold 12`.
|
||||
pub fn from_name_style_size(conf: &str) -> Option<Self> {
|
||||
// assume last is size, 2nd last is style and the rest is name.
|
||||
match conf.rsplit_once(' ') {
|
||||
Some((head, tail)) if tail.chars().all(|c| c.is_numeric()) => {
|
||||
let pt_size: f32 = tail.parse().unwrap_or(10.0);
|
||||
match head.rsplit_once(' ') {
|
||||
Some((name, style)) if !name.is_empty() => Some(Self {
|
||||
name: name.into(),
|
||||
style: Some(style.into()),
|
||||
pt_size,
|
||||
}),
|
||||
None if !head.is_empty() => Some(Self {
|
||||
name: head.into(),
|
||||
style: None,
|
||||
pt_size,
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
Some((head, tail)) if !head.is_empty() => Some(Self {
|
||||
name: head.into(),
|
||||
style: Some(tail.into()),
|
||||
pt_size: 10.0,
|
||||
}),
|
||||
None if !conf.is_empty() => Some(Self {
|
||||
name: conf.into(),
|
||||
style: None,
|
||||
pt_size: 10.0,
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pref_from_multi_name_variant_size() {
|
||||
let pref = FontPreference::from_name_style_size("Noto Serif CJK HK Bold 12").unwrap();
|
||||
assert_eq!(pref.name, "Noto Serif CJK HK");
|
||||
assert_eq!(pref.style, Some("Bold".into()));
|
||||
assert!((pref.pt_size - 12.0).abs() < f32::EPSILON);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pref_from_name_variant_size() {
|
||||
let pref = FontPreference::from_name_style_size("Cantarell Bold 12").unwrap();
|
||||
assert_eq!(pref.name, "Cantarell");
|
||||
assert_eq!(pref.style, Some("Bold".into()));
|
||||
assert!((pref.pt_size - 12.0).abs() < f32::EPSILON);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pref_from_name_size() {
|
||||
let pref = FontPreference::from_name_style_size("Cantarell 12").unwrap();
|
||||
assert_eq!(pref.name, "Cantarell");
|
||||
assert_eq!(pref.style, None);
|
||||
assert!((pref.pt_size - 12.0).abs() < f32::EPSILON);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pref_from_name() {
|
||||
let pref = FontPreference::from_name_style_size("Cantarell").unwrap();
|
||||
assert_eq!(pref.name, "Cantarell");
|
||||
assert_eq!(pref.style, None);
|
||||
assert!((pref.pt_size - 10.0).abs() < f32::EPSILON);
|
||||
}
|
||||
#[test]
|
||||
fn pref_from_multi_name_style() {
|
||||
let pref = FontPreference::from_name_style_size("Foo Bar Baz Bold").unwrap();
|
||||
assert_eq!(pref.name, "Foo Bar Baz");
|
||||
assert_eq!(pref.style, Some("Bold".into()));
|
||||
assert!((pref.pt_size - 10.0).abs() < f32::EPSILON);
|
||||
}
|
||||
52
patches/sctk-adwaita/src/wl_typed.rs
vendored
Normal file
52
patches/sctk-adwaita/src/wl_typed.rs
vendored
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
use std::{marker::PhantomData, ops::Deref};
|
||||
|
||||
use smithay_client_toolkit::reexports::client::{Dispatch, Proxy};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct WlTyped<I, DATA>(I, PhantomData<DATA>);
|
||||
|
||||
impl<I, DATA> WlTyped<I, DATA>
|
||||
where
|
||||
I: Proxy,
|
||||
DATA: Send + Sync + 'static,
|
||||
{
|
||||
#[allow(clippy::extra_unused_type_parameters)]
|
||||
pub fn wrap<STATE>(i: I) -> Self
|
||||
where
|
||||
STATE: Dispatch<I, DATA>,
|
||||
{
|
||||
Self(i, PhantomData)
|
||||
}
|
||||
|
||||
pub fn inner(&self) -> &I {
|
||||
&self.0
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn data(&self) -> &DATA {
|
||||
// Generic on Self::wrap makes sure that this will never panic
|
||||
#[allow(clippy::unwrap_used)]
|
||||
self.0.data().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl<I: Clone, D> Clone for WlTyped<I, D> {
|
||||
fn clone(&self) -> Self {
|
||||
Self(self.0.clone(), PhantomData)
|
||||
}
|
||||
}
|
||||
|
||||
impl<I, D> Deref for WlTyped<I, D> {
|
||||
type Target = I;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<I: PartialEq, D> PartialEq for WlTyped<I, D> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.0 == other.0
|
||||
}
|
||||
}
|
||||
impl<I: Eq, D> Eq for WlTyped<I, D> {}
|
||||
Loading…
Add table
Add a link
Reference in a new issue