1#[cfg(feature = "applet-token")]
2pub mod token;
3
4use crate::app::{BootData, BootDataInner, cosmic, iced_settings};
5use crate::cctk::sctk;
6use crate::theme::{self, Button, THEME, system_dark, system_light};
7use crate::widget::autosize::{self, Autosize, autosize};
8use crate::widget::{self, layer_container};
9use crate::{Application, Element, Renderer};
10
11pub use cosmic_panel_config;
12use cosmic_panel_config::{CosmicPanelBackground, PanelAnchor, PanelSize};
13use iced::alignment::{Alignment, Horizontal, Vertical};
14use iced::widget::Container;
15use iced::{self, Color, Length, Limits, Rectangle, window};
16use iced_core::{Padding, Shadow};
17use iced_runtime::platform_specific::wayland::popup::{SctkPopupSettings, SctkPositioner};
18use iced_widget::Text;
19use sctk::reexports::protocols::xdg::shell::client::xdg_positioner::{Anchor, Gravity};
20use std::borrow::Cow;
21use std::cell::RefCell;
22use std::fmt;
23use std::num::NonZeroU32;
24use std::rc::Rc;
25use std::sync::LazyLock;
26use std::time::Duration;
27use tracing::info;
28
29pub mod column;
30pub mod row;
31
32static AUTOSIZE_ID: LazyLock<iced::id::Id> =
33 LazyLock::new(|| iced::id::Id::new("cosmic-applet-autosize"));
34static AUTOSIZE_MAIN_ID: LazyLock<iced::id::Id> =
35 LazyLock::new(|| iced::id::Id::new("cosmic-applet-autosize-main"));
36static TOOLTIP_ID: LazyLock<crate::widget::Id> = LazyLock::new(|| iced::id::Id::new("subsurface"));
37pub(crate) static TOOLTIP_WINDOW_ID: LazyLock<window::Id> = LazyLock::new(window::Id::unique);
38
39#[derive(Debug, Clone)]
40pub struct Context {
41 pub size: Size,
42 pub anchor: PanelAnchor,
43 pub spacing: u32,
44 pub background: CosmicPanelBackground,
45 pub output_name: String,
46 pub panel_type: PanelType,
47 pub suggested_bounds: Option<iced::Size>,
50 pub padding_overlap: f32,
52}
53
54#[derive(Clone, Debug, PartialEq, Eq)]
55pub enum Size {
56 Hardcoded((u16, u16)),
58 PanelSize(PanelSize),
59}
60#[derive(Clone, Debug, PartialEq)]
61pub enum PanelType {
62 Panel,
63 Dock,
64 Other(String),
65}
66
67impl fmt::Display for PanelType {
68 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69 match self {
70 Self::Panel => write!(f, "Panel"),
71 Self::Dock => write!(f, "Dock"),
72 Self::Other(other) => write!(f, "{}", other),
73 }
74 }
75}
76
77impl From<String> for PanelType {
78 fn from(value: String) -> Self {
79 match value.as_str() {
80 "Panel" => PanelType::Panel,
81 "Dock" => PanelType::Dock,
82 _ => PanelType::Other(value),
83 }
84 }
85}
86
87impl Default for Context {
88 fn default() -> Self {
89 Self {
90 size: Size::PanelSize(
91 std::env::var("COSMIC_PANEL_SIZE")
92 .ok()
93 .and_then(|size| ron::from_str(size.as_str()).ok())
94 .unwrap_or(PanelSize::S),
95 ),
96 anchor: std::env::var("COSMIC_PANEL_ANCHOR")
97 .ok()
98 .and_then(|size| ron::from_str(size.as_str()).ok())
99 .unwrap_or(PanelAnchor::Top),
100 spacing: std::env::var("COSMIC_PANEL_SPACING")
101 .ok()
102 .and_then(|size| ron::from_str(size.as_str()).ok())
103 .unwrap_or(4),
104 background: std::env::var("COSMIC_PANEL_BACKGROUND")
105 .ok()
106 .and_then(|size| ron::from_str(size.as_str()).ok())
107 .unwrap_or(CosmicPanelBackground::ThemeDefault),
108 output_name: std::env::var("COSMIC_PANEL_OUTPUT").unwrap_or_default(),
109 panel_type: PanelType::from(std::env::var("COSMIC_PANEL_NAME").unwrap_or_default()),
110 padding_overlap: str::parse(
111 &std::env::var("COSMIC_PANEL_PADDING_OVERLAP").unwrap_or_default(),
112 )
113 .unwrap_or(0.0),
114 suggested_bounds: None,
115 }
116 }
117}
118
119impl Context {
120 #[must_use]
121 pub fn suggested_size(&self, is_symbolic: bool) -> (u16, u16) {
122 match &self.size {
123 Size::PanelSize(size) => {
124 let s = size.get_applet_icon_size(is_symbolic) as u16;
125 (s, s)
126 }
127 Size::Hardcoded((width, height)) => (*width, *height),
128 }
129 }
130
131 #[must_use]
132 pub fn suggested_window_size(&self) -> (NonZeroU32, NonZeroU32) {
133 let suggested = self.suggested_size(true);
134 let (applet_padding_major_axis, applet_padding_minor_axis) = self.suggested_padding(true);
135 let (horizontal_padding, vertical_padding) = if self.is_horizontal() {
136 (applet_padding_major_axis, applet_padding_minor_axis)
137 } else {
138 (applet_padding_minor_axis, applet_padding_major_axis)
139 };
140
141 let configured_width = self
142 .suggested_bounds
143 .as_ref()
144 .and_then(|c| NonZeroU32::new(c.width as u32)) .unwrap_or_else(|| {
146 NonZeroU32::new(suggested.0 as u32 + horizontal_padding as u32 * 2).unwrap()
147 });
148
149 let configured_height = self
150 .suggested_bounds
151 .as_ref()
152 .and_then(|c| NonZeroU32::new(c.height as u32))
153 .unwrap_or_else(|| {
154 NonZeroU32::new(suggested.1 as u32 + vertical_padding as u32 * 2).unwrap()
155 });
156 info!("{configured_height:?}");
157 (configured_width, configured_height)
158 }
159
160 #[must_use]
161 pub fn suggested_padding(&self, is_symbolic: bool) -> (u16, u16) {
162 match &self.size {
163 Size::PanelSize(size) => (
164 size.get_applet_shrinkable_padding(is_symbolic),
165 size.get_applet_padding(is_symbolic),
166 ),
167 Size::Hardcoded(_) => (12, 8),
168 }
169 }
170
171 pub fn window_size(&mut self, width: u16, height: u16) {
173 self.size = Size::Hardcoded((width, height));
174 }
175
176 #[allow(clippy::cast_precision_loss)]
177 pub fn window_settings(&self) -> crate::app::Settings {
178 let (width, height) = self.suggested_size(true);
179 let (applet_padding_major_axis, applet_padding_minor_axis) = self.suggested_padding(true);
180 let (horizontal_padding, vertical_padding) = if self.is_horizontal() {
181 (applet_padding_major_axis, applet_padding_minor_axis)
182 } else {
183 (applet_padding_minor_axis, applet_padding_major_axis)
184 };
185
186 let width = f32::from(width) + horizontal_padding as f32 * 2.;
187 let height = f32::from(height) + vertical_padding as f32 * 2.;
188 let mut settings = crate::app::Settings::default()
189 .size(iced_core::Size::new(width, height))
190 .size_limits(Limits::NONE.min_height(height).min_width(width))
191 .resizable(None)
192 .default_text_size(14.0)
193 .transparent(true);
194 if let Some(theme) = self.theme() {
195 settings = settings.theme(theme);
196 }
197 settings.exit_on_close = true;
198 settings
199 }
200
201 #[must_use]
202 pub fn is_horizontal(&self) -> bool {
203 matches!(self.anchor, PanelAnchor::Top | PanelAnchor::Bottom)
204 }
205
206 pub fn icon_button_from_handle<'a, Message: Clone + 'static>(
207 &self,
208 icon: widget::icon::Handle,
209 ) -> crate::widget::Button<'a, Message> {
210 let suggested = self.suggested_size(icon.symbolic);
211 let (applet_padding_major_axis, applet_padding_minor_axis) = self.suggested_padding(true);
212 let (_horizontal_padding, _vertical_padding) = if self.is_horizontal() {
213 (applet_padding_major_axis, applet_padding_minor_axis)
214 } else {
215 (applet_padding_minor_axis, applet_padding_major_axis)
216 };
217 let symbolic = icon.symbolic;
218 let icon = widget::icon(icon)
219 .class(if symbolic {
220 theme::Svg::Custom(Rc::new(|theme| iced_widget::svg::Style {
221 color: Some(theme.cosmic().background(theme.transparent).on.into()),
222 }))
223 } else {
224 theme::Svg::default()
225 })
226 .width(Length::Fixed(suggested.0 as f32))
227 .height(Length::Fixed(suggested.1 as f32));
228 self.button_from_element(icon, symbolic)
229 }
230
231 pub fn button_from_element<'a, Message: Clone + 'static>(
232 &self,
233 content: impl Into<Element<'a, Message>>,
234 use_symbolic_size: bool,
235 ) -> crate::widget::Button<'a, Message> {
236 let suggested = self.suggested_size(use_symbolic_size);
237 let (applet_padding_major_axis, applet_padding_minor_axis) = self.suggested_padding(true);
238 let (horizontal_padding, vertical_padding) = if self.is_horizontal() {
239 (applet_padding_major_axis, applet_padding_minor_axis)
240 } else {
241 (applet_padding_minor_axis, applet_padding_major_axis)
242 };
243
244 crate::widget::button::custom(layer_container(content).center(Length::Fill))
245 .width(Length::Fixed((suggested.0 + 2 * horizontal_padding) as f32))
246 .height(Length::Fixed((suggested.1 + 2 * vertical_padding) as f32))
247 .class(Button::AppletIcon)
248 }
249
250 pub fn text_button<'a, Message: Clone + 'static>(
251 &self,
252 text: impl Into<Text<'a, crate::Theme, crate::Renderer>>,
253 message: Message,
254 ) -> crate::widget::Button<'a, Message> {
255 let text = text.into();
256 let suggested = self.suggested_size(true);
257
258 let (applet_padding_major_axis, applet_padding_minor_axis) = self.suggested_padding(true);
259 let (horizontal_padding, vertical_padding) = if self.is_horizontal() {
260 (applet_padding_major_axis, applet_padding_minor_axis)
261 } else {
262 (applet_padding_minor_axis, applet_padding_major_axis)
263 };
264 crate::widget::button::custom(
265 layer_container(
266 Text::from(text)
267 .height(Length::Fill)
268 .align_y(Alignment::Center),
269 )
270 .center_y(Length::Fixed(f32::from(suggested.1 + 2 * vertical_padding))),
271 )
272 .on_press(message)
273 .padding([0, horizontal_padding])
274 .class(crate::theme::Button::AppletIcon)
275 }
276
277 pub fn icon_button<'a, Message: Clone + 'static>(
278 &self,
279 icon_name: &'a str,
280 ) -> crate::widget::Button<'a, Message> {
281 let suggested_size = self.suggested_size(true);
282 self.icon_button_from_handle(
283 widget::icon::from_name(icon_name)
284 .symbolic(true)
285 .size(suggested_size.0)
286 .into(),
287 )
288 }
289
290 pub fn applet_tooltip<'a, Message: 'static>(
291 &self,
292 content: impl Into<Element<'a, Message>>,
293 tooltip: impl Into<Cow<'static, str>>,
294 has_popup: bool,
295 on_surface_action: impl Fn(crate::surface::Action<Message>) -> Message + 'static,
296 parent_id: Option<window::Id>,
297 ) -> crate::widget::wayland::tooltip::widget::Tooltip<'a, Message, Message> {
298 let window_id = *TOOLTIP_WINDOW_ID;
299 let subsurface_id = TOOLTIP_ID.clone();
300 let anchor = self.anchor;
301 let tooltip = tooltip.into();
302
303 crate::widget::wayland::tooltip::widget::Tooltip::<'a, Message, Message>::new(
304 content,
305 (!has_popup).then_some(move |bounds: Rectangle| {
306 let window_id = window_id;
307 let (popup_anchor, gravity) = match anchor {
308 PanelAnchor::Left => (Anchor::Right, Gravity::Right),
309 PanelAnchor::Right => (Anchor::Left, Gravity::Left),
310 PanelAnchor::Top => (Anchor::Bottom, Gravity::Bottom),
311 PanelAnchor::Bottom => (Anchor::Top, Gravity::Top),
312 };
313
314 SctkPopupSettings {
315 parent: parent_id.unwrap_or(window::Id::RESERVED),
316 id: window_id,
317 grab: false,
318 input_zone: Some(vec![Rectangle::new(
319 iced::Point::new(-1000., -1000.),
320 iced::Size::default(),
321 )]),
322 positioner: SctkPositioner {
323 size: None,
324 size_limits: Limits::NONE.min_width(1.).min_height(1.),
325 anchor_rect: Rectangle {
326 x: bounds.x.round() as i32,
327 y: bounds.y.round() as i32,
328 width: bounds.width.round() as i32,
329 height: bounds.height.round() as i32,
330 },
331 anchor: popup_anchor,
332 gravity,
333 constraint_adjustment: 15,
334 offset: (0, 0),
335 reactive: true,
336 },
337 parent_size: None,
338 close_with_children: true,
339 }
340 }),
341 move || {
342 Element::from(autosize::autosize(
343 layer_container(crate::widget::text(tooltip.clone()))
344 .layer(crate::cosmic_theme::Layer::Background)
345 .padding(4.),
346 subsurface_id.clone(),
347 ))
348 },
349 on_surface_action(crate::surface::Action::DestroyPopup(window_id)),
350 on_surface_action,
351 )
352 .delay(Duration::from_millis(100))
353 }
354
355 pub fn popup_container<'a, Message: 'static>(
357 &self,
358 content: impl Into<Element<'a, Message>>,
359 ) -> Autosize<'a, Message, crate::Theme, Renderer> {
360 let (vertical_align, horizontal_align) = match self.anchor {
361 PanelAnchor::Left => (Vertical::Center, Horizontal::Left),
362 PanelAnchor::Right => (Vertical::Center, Horizontal::Right),
363 PanelAnchor::Top => (Vertical::Top, Horizontal::Center),
364 PanelAnchor::Bottom => (Vertical::Bottom, Horizontal::Center),
365 };
366
367 autosize(
368 Container::<Message, _, Renderer>::new(
369 Container::<Message, _, Renderer>::new(content).style(|theme| {
370 let cosmic = theme.cosmic();
371 let corners = cosmic.corner_radii;
372 let bg = cosmic.background(theme.transparent).base;
373 iced_widget::container::Style {
374 text_color: Some(cosmic.background(theme.transparent).on.into()),
375 background: Some(Color::from(bg).into()),
376 border: iced::Border {
377 radius: corners.radius_m.into(),
378 width: 1.0,
379 color: cosmic.background(theme.transparent).divider.into(),
380 },
381 shadow: Shadow::default(),
382 icon_color: Some(cosmic.background(theme.transparent).on.into()),
383 snap: true,
384 }
385 }),
386 )
387 .height(Length::Shrink)
388 .align_x(horizontal_align)
389 .align_y(vertical_align),
390 AUTOSIZE_ID.clone(),
391 )
392 .limits(
393 Limits::NONE
394 .min_height(1.)
395 .min_width(360.0)
396 .max_width(360.0)
397 .max_height(1000.0),
398 )
399 }
400
401 #[must_use]
402 #[allow(clippy::cast_possible_wrap)]
403 pub fn get_popup_settings(
404 &self,
405 parent: window::Id,
406 id: window::Id,
407 size: Option<(u32, u32)>,
408 width_padding: Option<i32>,
409 height_padding: Option<i32>,
410 ) -> SctkPopupSettings {
411 let (width, height) = self.suggested_size(true);
412 let (applet_padding_major_axis, applet_padding_minor_axis) = self.suggested_padding(true);
413 let (horizontal_padding, vertical_padding) = if self.is_horizontal() {
414 (applet_padding_major_axis, applet_padding_minor_axis)
415 } else {
416 (applet_padding_minor_axis, applet_padding_major_axis)
417 };
418 let pixel_offset = 4;
419 let (offset, anchor, gravity) = match self.anchor {
420 PanelAnchor::Left => ((pixel_offset, 0), Anchor::Right, Gravity::Right),
421 PanelAnchor::Right => ((-pixel_offset, 0), Anchor::Left, Gravity::Left),
422 PanelAnchor::Top => ((0, pixel_offset), Anchor::Bottom, Gravity::Bottom),
423 PanelAnchor::Bottom => ((0, -pixel_offset), Anchor::Top, Gravity::Top),
424 };
425 SctkPopupSettings {
426 parent,
427 id,
428 positioner: SctkPositioner {
429 anchor,
430 gravity,
431 offset,
432 size,
433 anchor_rect: Rectangle {
434 x: 0,
435 y: 0,
436 width: width_padding.unwrap_or(horizontal_padding as i32) * 2
437 + i32::from(width),
438 height: height_padding.unwrap_or(vertical_padding as i32) * 2
439 + i32::from(height),
440 },
441 reactive: true,
442 constraint_adjustment: 15, size_limits: Limits::NONE
444 .min_height(1.0)
445 .min_width(360.0)
446 .max_width(360.0)
447 .max_height(1080.0),
448 },
449 parent_size: None,
450 grab: true,
451 close_with_children: false,
452 input_zone: None,
453 }
454 }
455
456 pub fn autosize_window<'a, Message: 'static>(
457 &self,
458 content: impl Into<Element<'a, Message>>,
459 ) -> Autosize<'a, Message, crate::Theme, crate::Renderer> {
460 let _force_configured = matches!(&self.panel_type, PanelType::Other(n) if n.is_empty());
461 let w = autosize(content, AUTOSIZE_MAIN_ID.clone());
462 let mut limits = Limits::NONE;
463 let _suggested_window_size = self.suggested_window_size();
464
465 if let Some(width) = self
466 .suggested_bounds
467 .as_ref()
468 .filter(|c| c.width as i32 > 0)
469 .map(|c| c.width)
470 {
471 limits = limits.width(width);
472 }
473 if let Some(height) = self
474 .suggested_bounds
475 .as_ref()
476 .filter(|c| c.height as i32 > 0)
477 .map(|c| c.height)
478 {
479 limits = limits.height(height);
480 }
481
482 w.limits(limits)
483 }
484
485 #[must_use]
486 pub fn theme(&self) -> Option<theme::Theme> {
487 match self.background {
488 CosmicPanelBackground::Dark => {
489 let mut theme = system_dark();
490 theme.theme_type.prefer_dark(Some(true));
491 Some(theme)
492 }
493 CosmicPanelBackground::Light => {
494 let mut theme = system_light();
495 theme.theme_type.prefer_dark(Some(false));
496 Some(theme)
497 }
498 _ => Some(theme::system_preference()),
499 }
500 }
501
502 pub fn text<'a>(&self, msg: impl Into<Cow<'a, str>>) -> crate::widget::Text<'a, crate::Theme> {
503 let msg = msg.into();
504 let t = match self.size {
505 Size::Hardcoded(_) => crate::widget::text,
506 Size::PanelSize(ref s) => {
507 let size = s.get_applet_icon_size_with_padding(false);
508
509 let size_threshold_small = PanelSize::S.get_applet_icon_size_with_padding(false);
510 let size_threshold_medium = PanelSize::M.get_applet_icon_size_with_padding(false);
511 let size_threshold_large = PanelSize::L.get_applet_icon_size_with_padding(false);
512
513 if size <= size_threshold_small {
514 crate::widget::text::body
515 } else if size <= size_threshold_medium {
516 crate::widget::text::title4
517 } else if size <= size_threshold_large {
518 crate::widget::text::title3
519 } else {
520 crate::widget::text::title2
521 }
522 }
523 };
524 t(msg).font(crate::font::default())
525 }
526}
527
528pub fn run<App: Application>(flags: App::Flags) -> iced::Result {
534 if let Some(fd) = std::env::var("X_PRIVILEGED_WAYLAND_SOCKET")
535 .ok()
536 .and_then(|fd| fd.parse::<std::os::fd::RawFd>().ok())
537 {
538 let fd = unsafe { std::os::fd::BorrowedFd::borrow_raw(fd) };
539 if let Ok(flags) = rustix::io::fcntl_getfd(fd) {
540 let _ = rustix::io::fcntl_setfd(fd, flags | rustix::io::FdFlags::CLOEXEC);
541 }
542 }
543 let helper = Context::default();
544
545 let mut settings = helper.window_settings();
546 settings.resizable = None;
547
548 #[cfg(all(target_env = "gnu", not(target_os = "windows")))]
549 if let Some(threshold) = settings.default_mmap_threshold {
550 crate::malloc::limit_mmap_threshold(threshold);
551 }
552
553 let (iced_settings, (mut core, flags), mut window_settings) =
554 iced_settings::<App>(settings, flags);
555 core.window.show_headerbar = false;
556 core.window.sharp_corners = true;
557 core.window.show_maximize = false;
558 core.window.show_minimize = false;
559 core.window.use_template = false;
560 core.app_type = crate::core::AppType::Applet;
561
562 window_settings.decorations = false;
563 window_settings.exit_on_close_request = true;
564 window_settings.resizable = false;
565 window_settings.resize_border = 0;
566
567 let no_main_window = core.main_window.is_none();
570 if no_main_window {
571 core.main_window = Some(iced_core::window::Id::RESERVED);
574 }
575 let app = iced::daemon(
576 BootData(Rc::new(RefCell::new(Some(BootDataInner::<App> {
577 flags,
578 core,
579 settings: window_settings,
580 })))),
581 cosmic::Cosmic::update,
582 cosmic::Cosmic::view,
583 );
584
585 app.subscription(cosmic::Cosmic::subscription)
586 .style(cosmic::Cosmic::style)
587 .theme(cosmic::Cosmic::theme)
588 .settings(iced_settings)
589 .run()
590}
591
592#[must_use]
593pub fn style() -> iced::theme::Style {
594 let theme = crate::theme::THEME.lock().unwrap();
595 iced::theme::Style {
596 background_color: Color::from_rgba(0.0, 0.0, 0.0, 0.0),
597 text_color: theme.cosmic().on_bg_color().into(),
598 icon_color: theme.cosmic().on_bg_color().into(),
599 }
600}
601
602pub fn menu_button<'a, Message: Clone + 'a>(
603 content: impl Into<Element<'a, Message>>,
604) -> crate::widget::Button<'a, Message> {
605 crate::widget::button::custom(content)
606 .class(Button::AppletMenu)
607 .padding(menu_control_padding())
608 .width(Length::Fill)
609}
610
611pub fn padded_control<'a, Message>(
612 content: impl Into<Element<'a, Message>>,
613) -> crate::widget::container::Container<'a, Message, crate::Theme, crate::Renderer> {
614 crate::widget::container(content)
615 .padding(menu_control_padding())
616 .width(Length::Fill)
617}
618
619pub fn menu_control_padding() -> Padding {
620 let guard = THEME.lock().unwrap();
621 let cosmic = guard.cosmic();
622 [cosmic.space_xxs(), cosmic.space_m()].into()
623}