[fractal] toast: Use libadwaita toast



commit d076bd24419ac6172c2c1a7cc023a5dca938ef07
Author: Julian Sparber <julian sparber net>
Date:   Thu Jul 21 21:46:46 2022 +0200

    toast: Use libadwaita toast
    
    Fixes: #857, #967

 data/resources/resources.gresource.xml   |   1 -
 data/resources/ui/in-app-notification.ui |  35 ------
 data/resources/ui/window.ui              |  11 +-
 src/components/in_app_notification.rs    | 182 -------------------------------
 src/components/mod.rs                    |   4 -
 src/components/toast.rs                  | 155 --------------------------
 src/session/content/mod.rs               |  14 +--
 src/utils.rs                             | 117 ++++++++++----------
 src/window.rs                            |   9 +-
 9 files changed, 63 insertions(+), 465 deletions(-)
---
diff --git a/data/resources/resources.gresource.xml b/data/resources/resources.gresource.xml
index 7308ecd5e..2346a57a2 100644
--- a/data/resources/resources.gresource.xml
+++ b/data/resources/resources.gresource.xml
@@ -76,7 +76,6 @@
     <file compressed="true" preprocess="xml-stripblanks" 
alias="event-source-dialog.ui">ui/event-source-dialog.ui</file>
     <file compressed="true" preprocess="xml-stripblanks" alias="greeter.ui">ui/greeter.ui</file>
     <file compressed="true" preprocess="xml-stripblanks" 
alias="identity-verification-widget.ui">ui/identity-verification-widget.ui</file>
-    <file compressed="true" preprocess="xml-stripblanks" 
alias="in-app-notification.ui">ui/in-app-notification.ui</file>
     <file compressed="true" preprocess="xml-stripblanks" 
alias="login-advanced-dialog.ui">ui/login-advanced-dialog.ui</file>
     <file compressed="true" preprocess="xml-stripblanks" 
alias="login-idp-button.ui">ui/login-idp-button.ui</file>
     <file compressed="true" preprocess="xml-stripblanks" alias="login.ui">ui/login.ui</file>
diff --git a/data/resources/ui/window.ui b/data/resources/ui/window.ui
index 851e4364e..b5d8d589d 100644
--- a/data/resources/ui/window.ui
+++ b/data/resources/ui/window.ui
@@ -4,16 +4,7 @@
     <property name="default-width">600</property>
     <property name="default-height">400</property>
     <property name="content">
-      <object class="GtkOverlay">
-        <child type="overlay">
-          <object class="InAppNotification">
-            <property name="error-list">
-              <object class="GListStore" id="error_list">
-                <property name="item-type">ComponentsToast</property>
-              </object>
-            </property>
-          </object>
-        </child>
+      <object class="AdwToastOverlay" id="toast_overlay">
         <child>
           <object class="GtkStack" id="main_stack">
             <property name="visible-child">loading</property>
diff --git a/src/components/mod.rs b/src/components/mod.rs
index ffa03ef06..261c20f8b 100644
--- a/src/components/mod.rs
+++ b/src/components/mod.rs
@@ -9,7 +9,6 @@ mod custom_entry;
 mod drag_overlay;
 mod editable_avatar;
 mod entry_row;
-mod in_app_notification;
 mod label_with_widgets;
 mod loading_listbox_row;
 mod location_viewer;
@@ -19,7 +18,6 @@ mod pill;
 mod reaction_chooser;
 mod room_title;
 mod spinner_button;
-mod toast;
 mod video_player;
 mod video_player_renderer;
 
@@ -35,7 +33,6 @@ pub use self::{
     drag_overlay::DragOverlay,
     editable_avatar::EditableAvatar,
     entry_row::EntryRow,
-    in_app_notification::InAppNotification,
     label_with_widgets::{LabelWithWidgets, DEFAULT_PLACEHOLDER},
     loading_listbox_row::LoadingListBoxRow,
     location_viewer::LocationViewer,
@@ -45,7 +42,6 @@ pub use self::{
     reaction_chooser::ReactionChooser,
     room_title::RoomTitle,
     spinner_button::SpinnerButton,
-    toast::Toast,
     video_player::VideoPlayer,
     video_player_renderer::VideoPlayerRenderer,
 };
diff --git a/src/session/content/mod.rs b/src/session/content/mod.rs
index 6f055e9ed..f01464f84 100644
--- a/src/session/content/mod.rs
+++ b/src/session/content/mod.rs
@@ -6,7 +6,7 @@ mod room_history;
 pub mod verification;
 
 use adw::subclass::prelude::*;
-use gtk::{gio, glib, glib::clone, prelude::*, CompositeTemplate};
+use gtk::{glib, glib::clone, prelude::*, CompositeTemplate};
 
 use self::{
     explore::Explore, invite::Invite, markdown_popover::MarkdownPopover, room_details::RoomDetails,
@@ -33,7 +33,6 @@ mod imp {
         pub compact: Cell<bool>,
         pub session: RefCell<Option<WeakRef<Session>>>,
         pub item: RefCell<Option<glib::Object>>,
-        pub error_list: RefCell<Option<gio::ListStore>>,
         pub signal_handler: RefCell<Option<SignalHandlerId>>,
         #[template_child]
         pub stack: TemplateChild<gtk::Stack>,
@@ -99,13 +98,6 @@ mod imp {
                         glib::Object::static_type(),
                         glib::ParamFlags::READWRITE | glib::ParamFlags::EXPLICIT_NOTIFY,
                     ),
-                    glib::ParamSpecObject::new(
-                        "error-list",
-                        "Error List",
-                        "A list of errors shown as in-app-notification",
-                        gio::ListStore::static_type(),
-                        glib::ParamFlags::READWRITE,
-                    ),
                 ]
             });
 
@@ -126,9 +118,6 @@ mod imp {
                 }
                 "session" => obj.set_session(value.get().unwrap()),
                 "item" => obj.set_item(value.get().unwrap()),
-                "error-list" => {
-                    self.error_list.replace(value.get().unwrap());
-                }
                 _ => unimplemented!(),
             }
         }
@@ -138,7 +127,6 @@ mod imp {
                 "compact" => self.compact.get().to_value(),
                 "session" => obj.session().to_value(),
                 "item" => obj.item().to_value(),
-                "error-list" => self.error_list.borrow().to_value(),
                 _ => unimplemented!(),
             }
         }
diff --git a/src/utils.rs b/src/utils.rs
index 745aa3ad2..8d5002615 100644
--- a/src/utils.rs
+++ b/src/utils.rs
@@ -72,19 +72,7 @@ macro_rules! spawn_tokio {
 macro_rules! toast {
     ($widget:expr, $message:expr) => {
         {
-            let message = $message;
-            if let Some(root) = $widget.root() {
-                if let Some(window) = root.downcast_ref::<$crate::Window>() {
-                    window.add_toast(&$crate::components::Toast::new(message.as_ref()));
-                } else if let Some(window) = root.downcast_ref::<adw::PreferencesWindow>() {
-                    use adw::prelude::PreferencesWindowExt;
-                    window.add_toast(&adw::Toast::new(message.as_ref()));
-                } else {
-                    log::error!("Trying to display a toast when the parent doesn't support it");
-                }
-            } else {
-                log::warn!("Could not display toast with message: {message}");
-            }
+            $crate::_add_toast!($widget, adw::Toast::new($message.as_ref()));
         }
     };
     ($widget:expr, $message:expr, $($tail:tt)+) => {
@@ -96,53 +84,46 @@ macro_rules! toast {
                 .collect();
             let message = $crate::utils::freplace($message.into(), &*string_dict);
 
-            if let Some(root) = $widget.root() {
-                if pill_vars.is_empty() {
-                    if let Some(window) = root.downcast_ref::<$crate::Window>() {
-                        window.add_toast(&$crate::components::Toast::new(&message));
-                    } else if let Some(window) = root.downcast_ref::<adw::PreferencesWindow>() {
-                        use adw::prelude::PreferencesWindowExt;
-                        window.add_toast(&adw::Toast::new(&message));
-                    } else {
-                        log::error!("Trying to display a toast when the parent doesn't support it");
-                    }
-                } else if let Some(window) = root.downcast_ref::<$crate::Window>() {
-                    let pill_vars = std::collections::HashMap::<&str, 
$crate::components::Pill>::from(pill_vars);
-                    let mut swapped_label = String::new();
-                    let mut widgets = Vec::with_capacity(pill_vars.len());
-                    let mut last_end = 0;
-
-                    let mut matches = pill_vars
-                        .keys()
-                        .map(|key: &&str| {
-                            message
-                                .match_indices(&format!("{{{key}}}"))
-                                .map(|(start, _)| (start, key))
-                                .collect::<Vec<_>>()
-                        })
-                        .flatten()
-                        .collect::<Vec<_>>();
-                    matches.sort_unstable();
-
-                    for (start, key) in matches {
-                        swapped_label.push_str(&message[last_end..start]);
-                        swapped_label.push_str($crate::components::DEFAULT_PLACEHOLDER);
-                        last_end = start + key.len() + 2;
-                        widgets.push(pill_vars.get(key).unwrap().clone())
-                    }
-                    swapped_label.push_str(&message[last_end..message.len()]);
-
-                    let toast = $crate::components::Toast::builder()
-                        .title(swapped_label)
-                        .widgets(&widgets)
-                        .build();
-                    window.add_toast(&toast);
-                } else {
-                    log::error!("Trying to display a toast with pills when the parent doesn't support it");
-                }
+            let toast = if pill_vars.is_empty() {
+                adw::Toast::new($message.as_ref())
             } else {
-                log::warn!("Could not display toast with message: {message}");
-            }
+                let pill_vars = std::collections::HashMap::<&str, $crate::components::Pill>::from(pill_vars);
+                let mut swapped_label = String::new();
+                let mut widgets = Vec::with_capacity(pill_vars.len());
+                let mut last_end = 0;
+
+                let mut matches = pill_vars
+                    .keys()
+                    .map(|key: &&str| {
+                        message
+                            .match_indices(&format!("{{{key}}}"))
+                            .map(|(start, _)| (start, key))
+                            .collect::<Vec<_>>()
+                    })
+                    .flatten()
+                    .collect::<Vec<_>>();
+                matches.sort_unstable();
+
+                for (start, key) in matches {
+                    swapped_label.push_str(&message[last_end..start]);
+                    swapped_label.push_str($crate::components::DEFAULT_PLACEHOLDER);
+                    last_end = start + key.len() + 2;
+                    widgets.push(pill_vars.get(key).unwrap().clone())
+                }
+                swapped_label.push_str(&message[last_end..message.len()]);
+
+                let widget = $crate::components::LabelWithWidgets::with_label_and_widgets(
+                    &swapped_label,
+                    widgets,
+                )
+                .upcast::<gtk::Widget>();
+
+                adw::Toast::builder()
+                    .custom_title(&widget)
+                    .build()
+            };
+
+            $crate::_add_toast!($widget, toast);
         }
     };
 }
@@ -170,6 +151,24 @@ macro_rules! _toast_accum {
     ([$($string_vars:tt)*], [$($pill_vars:tt)*],) => { ([$($string_vars)*], [$($pill_vars)*]) };
 }
 
+#[doc(hidden)]
+#[macro_export]
+macro_rules! _add_toast {
+    ($widget:expr, $toast:expr) => {{
+        use gtk::prelude::WidgetExt;
+        if let Some(root) = $widget.root() {
+            if let Some(window) = root.downcast_ref::<$crate::Window>() {
+                window.add_toast($toast.as_ref());
+            } else if let Some(window) = root.downcast_ref::<adw::PreferencesWindow>() {
+                use adw::prelude::PreferencesWindowExt;
+                window.add_toast($toast.as_ref());
+            } else {
+                panic!("Trying to display a toast when the parent doesn't support it");
+            }
+        }
+    }};
+}
+
 use std::{convert::TryInto, path::PathBuf, str::FromStr};
 
 use gettextrs::gettext;
diff --git a/src/window.rs b/src/window.rs
index 68e13cdce..f7cbc36e0 100644
--- a/src/window.rs
+++ b/src/window.rs
@@ -6,7 +6,6 @@ use log::{info, warn};
 
 use crate::{
     account_switcher::AccountSwitcher,
-    components::{InAppNotification, Toast},
     config::{APP_ID, PROFILE},
     secret::{self, SecretError},
     spawn, Application, ErrorPage, Greeter, Login, Session,
@@ -34,7 +33,7 @@ mod imp {
         #[template_child]
         pub sessions: TemplateChild<gtk::Stack>,
         #[template_child]
-        pub error_list: TemplateChild<gio::ListStore>,
+        pub toast_overlay: TemplateChild<adw::ToastOverlay>,
         pub account_switcher: AccountSwitcher,
     }
 
@@ -45,8 +44,6 @@ mod imp {
         type ParentType = adw::ApplicationWindow;
 
         fn class_init(klass: &mut Self::Class) {
-            Toast::static_type();
-            InAppNotification::static_type();
             Self::bind_template(klass);
 
             klass.add_binding_action(
@@ -321,8 +318,8 @@ impl Window {
     }
 
     /// This appends a new toast to the list
-    pub fn add_toast(&self, toast: &Toast) {
-        self.imp().error_list.append(toast);
+    pub fn add_toast(&self, toast: &adw::Toast) {
+        self.imp().toast_overlay.add_toast(toast);
     }
 
     pub fn account_switcher(&self) -> &AccountSwitcher {


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]