[fractal] window: Use the toast macro
- From: Julian Sparber <jsparber src gnome org>
- To: commits-list gnome org
- Cc:
- Subject: [fractal] window: Use the toast macro
- Date: Tue, 31 May 2022 13:59:57 +0000 (UTC)
commit 613a182a9e04921f45158f1278373bec2d85e1b6
Author: Kévin Commaille <zecakeh tedomum fr>
Date: Tue May 31 14:47:14 2022 +0200
window: Use the toast macro
src/error_page.rs | 17 +--
src/login/mod.rs | 10 +-
.../user_page/deactivate_account_subpage.rs | 9 +-
src/session/content/room_history/mod.rs | 56 ++------
.../content/verification/session_verification.rs | 8 +-
src/session/mod.rs | 15 +-
src/session/room/event_actions.rs | 12 +-
src/session/room/mod.rs | 151 +++++++++------------
src/session/room_list.rs | 13 +-
src/session/verification/identity_verification.rs | 7 +-
10 files changed, 114 insertions(+), 184 deletions(-)
---
diff --git a/src/error_page.rs b/src/error_page.rs
index 5ed7a188e..86766db38 100644
--- a/src/error_page.rs
+++ b/src/error_page.rs
@@ -3,7 +3,7 @@ use gettextrs::gettext;
use gtk::{self, glib, glib::clone, prelude::*, subclass::prelude::*, CompositeTemplate};
use log::error;
-use crate::{components::Toast, secret, secret::SecretError, spawn, window::Window};
+use crate::{secret, secret::SecretError, spawn, toast, window::Window};
pub enum ErrorSubpage {
SecretErrorSession,
@@ -105,21 +105,16 @@ impl ErrorPage {
.as_ref()
.and_then(|root| root.downcast_ref::<Window>())
{
- window.add_toast(&Toast::new(&gettext("Session removed successfully.")));
+ toast!(self, gettext("Session removed successfully."));
window.restore_sessions().await;
}
}
Err(err) => {
error!("Could not remove session from secret storage: {:?}", err);
- if let Some(window) = self
- .root()
- .as_ref()
- .and_then(|root| root.downcast_ref::<Window>())
- {
- window.add_toast(&Toast::new(&gettext(
- "Could not remove session from secret storage",
- )));
- }
+ toast!(
+ self,
+ gettext("Could not remove session from secret storage")
+ );
}
}
}
diff --git a/src/login/mod.rs b/src/login/mod.rs
index 5ec3a5c04..d093e26ee 100644
--- a/src/login/mod.rs
+++ b/src/login/mod.rs
@@ -22,8 +22,8 @@ use idp_button::IdpButton;
use login_advanced_dialog::LoginAdvancedDialog;
use crate::{
- components::{EntryRow, PasswordEntryRow, SpinnerButton, Toast},
- gettext_f, spawn, spawn_tokio,
+ components::{EntryRow, PasswordEntryRow, SpinnerButton},
+ gettext_f, spawn, spawn_tokio, toast,
user_facing_error::UserFacingError,
Session,
};
@@ -380,7 +380,7 @@ impl Login {
}
Err(error) => {
warn!("Failed to discover homeserver: {}", error);
- obj.parent_window().add_toast(&Toast::new(&error.to_user_facing()));
+ toast!(obj, error.to_user_facing());
}
};
obj.unfreeze();
@@ -448,7 +448,7 @@ impl Login {
}
Err(error) => {
warn!("Failed to check homeserver: {}", error);
- obj.parent_window().add_toast(&Toast::new(&error.to_user_facing()));
+ toast!(obj, error.to_user_facing());
}
};
obj.unfreeze();
@@ -600,7 +600,7 @@ impl Login {
clone!(@weak self as login => move |session, error| {
match error {
Some(e) => {
- login.parent_window().add_toast(&e);
+ toast!(login, e);
login.unfreeze();
},
None => {
diff --git a/src/session/account_settings/user_page/deactivate_account_subpage.rs
b/src/session/account_settings/user_page/deactivate_account_subpage.rs
index 6d8751c89..0f64908a1 100644
--- a/src/session/account_settings/user_page/deactivate_account_subpage.rs
+++ b/src/session/account_settings/user_page/deactivate_account_subpage.rs
@@ -9,9 +9,9 @@ use log::error;
use matrix_sdk::ruma::{api::client::account::deactivate, assign};
use crate::{
- components::{AuthDialog, EntryRow, SpinnerButton, Toast},
+ components::{AuthDialog, EntryRow, SpinnerButton},
session::{Session, UserExt},
- spawn,
+ spawn, toast,
};
mod imp {
@@ -194,10 +194,7 @@ impl DeactivateAccountSubpage {
match result {
Ok(_) => {
if let Some(session) = self.session() {
- session
- .parent_window()
- .unwrap()
- .add_toast(&Toast::new(&gettext("Account successfully deactivated")));
+ toast!(session, gettext("Account successfully deactivated"));
session.handle_logged_out();
}
self.activate_action("account-settings.close", None)
diff --git a/src/session/content/room_history/mod.rs b/src/session/content/room_history/mod.rs
index 304a2fd94..15bf3ae8f 100644
--- a/src/session/content/room_history/mod.rs
+++ b/src/session/content/room_history/mod.rs
@@ -34,16 +34,15 @@ use self::{
state_row::StateRow, verification_info_bar::VerificationInfoBar,
};
use crate::{
- components::{CustomEntry, DragOverlay, Pill, ReactionChooser, RoomTitle, Toast},
+ components::{CustomEntry, DragOverlay, Pill, ReactionChooser, RoomTitle},
i18n::gettext_f,
session::{
content::{MarkdownPopover, RoomDetails},
room::{Event, Room, RoomType, Timeline, TimelineItem, TimelineState},
user::UserExt,
},
- spawn,
+ spawn, toast,
utils::filename_for_mime,
- window::Window,
};
mod imp {
@@ -53,7 +52,7 @@ mod imp {
use once_cell::unsync::OnceCell;
use super::*;
- use crate::{components::Toast, window::Window, Application};
+ use crate::Application;
#[derive(Debug, Default, CompositeTemplate)]
#[template(resource = "/org/gnome/Fractal/content-room-history.ui")]
@@ -162,14 +161,8 @@ mod imp {
_ => None,
};
- if let Some(window) = widget
- .root()
- .as_ref()
- .and_then(|root| root.downcast_ref::<Window>())
- {
- if let Some(message) = toast_error {
- window.add_toast(&Toast::new(&message));
- }
+ if let Some(message) = toast_error {
+ toast!(widget, message);
}
}));
});
@@ -843,14 +836,7 @@ impl RoomHistory {
}
Err(err) => {
warn!("Could not read file: {}", err);
-
- if let Some(window) = self
- .root()
- .as_ref()
- .and_then(|root| root.downcast_ref::<Window>())
- {
- window.add_toast(&Toast::new(&gettext("Error reading file")));
- }
+ toast!(self, gettext("Error reading file"));
}
}
}
@@ -874,16 +860,10 @@ impl RoomHistory {
}
Err(error) => {
warn!("Could not get file from drop: {error:?}");
-
- if let Some(window) = obj
- .root()
- .as_ref()
- .and_then(|root| root.downcast_ref::<Window>())
- {
- window.add_toast(
- &Toast::new(&gettext("Error getting file from drop"))
- );
- }
+ toast!(
+ obj,
+ gettext("Error getting file from drop")
+ );
false
}
@@ -914,13 +894,7 @@ impl RoomHistory {
Err(error) => warn!("Could not get GdkTexture from the clipboard: {error:?}"),
}
- if let Some(window) = self
- .root()
- .as_ref()
- .and_then(|root| root.downcast_ref::<Window>())
- {
- window.add_toast(&Toast::new(&gettext("Error getting image from clipboard")));
- }
+ toast!(self, gettext("Error getting image from clipboard"));
} else if formats.contains_type(gio::File::static_type()) {
// There is a file in the clipboard.
match clipboard
@@ -937,13 +911,7 @@ impl RoomHistory {
Err(error) => warn!("Could not get file from the clipboard: {error:?}"),
}
- if let Some(window) = self
- .root()
- .as_ref()
- .and_then(|root| root.downcast_ref::<Window>())
- {
- window.add_toast(&Toast::new(&gettext("Error getting file from clipboard")));
- }
+ toast!(self, gettext("Error getting file from clipboard"));
}
}
diff --git a/src/session/content/verification/session_verification.rs
b/src/session/content/verification/session_verification.rs
index 335f7833e..dcc970e93 100644
--- a/src/session/content/verification/session_verification.rs
+++ b/src/session/content/verification/session_verification.rs
@@ -5,9 +5,9 @@ use log::{debug, error};
use super::IdentityVerificationWidget;
use crate::{
- components::{AuthDialog, AuthError, SpinnerButton, Toast},
+ components::{AuthDialog, AuthError, SpinnerButton},
session::verification::{IdentityVerification, VerificationState},
- spawn, Session, Window,
+ spawn, toast, Session, Window,
};
mod imp {
@@ -326,9 +326,7 @@ impl SessionVerification {
};
if let Some(error_message) = error_message {
- if let Some(window) = obj.parent_window() {
- window.add_toast(&Toast::new(&error_message));
- }
+ toast!(obj, error_message);
} else {
// TODO tell user that the a crypto identity was created
obj.activate_action("session.show-content", None).unwrap();
diff --git a/src/session/mod.rs b/src/session/mod.rs
index 0f748fe69..5c4e244bf 100644
--- a/src/session/mod.rs
+++ b/src/session/mod.rs
@@ -66,11 +66,10 @@ pub use self::{
user::{User, UserActions, UserExt},
};
use crate::{
- components::Toast,
secret,
secret::{Secret, StoredSession},
session::sidebar::ItemList,
- spawn, spawn_tokio, UserFacingError, Window,
+ spawn, spawn_tokio, toast, UserFacingError, Window,
};
#[derive(Error, Debug)]
@@ -235,7 +234,7 @@ mod imp {
vec![
Signal::builder(
"prepared",
- &[Option::<Toast>::static_type().into()],
+ &[Option::<String>::static_type().into()],
<()>::static_type().into(),
)
.build(),
@@ -491,7 +490,7 @@ impl Session {
priv_.logout_on_dispose.set(false);
- Some(Toast::new(&error.to_user_facing()))
+ Some(error.to_user_facing())
}
};
@@ -658,13 +657,13 @@ impl Session {
}
/// Connects the prepared signals to the function f given in input
- pub fn connect_prepared<F: Fn(&Self, Option<Toast>) + 'static>(
+ pub fn connect_prepared<F: Fn(&Self, Option<String>) + 'static>(
&self,
f: F,
) -> glib::SignalHandlerId {
self.connect_local("prepared", true, move |values| {
let obj = values[0].get::<Self>().unwrap();
- let err = values[1].get::<Option<Toast>>().unwrap();
+ let err = values[1].get::<Option<String>>().unwrap();
f(&obj, err);
@@ -758,9 +757,7 @@ impl Session {
}
Err(error) => {
error!("Couldn’t logout the session {}", error);
- if let Some(window) = self.parent_window() {
- window.add_toast(&Toast::new(&gettext("Failed to logout the session.")));
- }
+ toast!(self, gettext("Failed to logout the session."));
}
}
}
diff --git a/src/session/room/event_actions.rs b/src/session/room/event_actions.rs
index ac38d9ff2..a8c894e08 100644
--- a/src/session/room/event_actions.rs
+++ b/src/session/room/event_actions.rs
@@ -5,13 +5,12 @@ use matrix_sdk::ruma::events::{room::message::MessageType, AnyMessageLikeEventCo
use once_cell::sync::Lazy;
use crate::{
- components::Toast,
session::{
event_source_dialog::EventSourceDialog,
room::{Event, RoomAction},
user::UserExt,
},
- spawn,
+ spawn, toast,
utils::cache_dir,
UserFacingError, Window,
};
@@ -190,12 +189,12 @@ where
let window: Window = self.root().unwrap().downcast().unwrap();
spawn!(
glib::PRIORITY_LOW,
- clone!(@weak window => async move {
+ clone!(@weak self as obj, @weak window => async move {
let (_, filename, data) = match event.get_media_content().await {
Ok(res) => res,
Err(err) => {
error!("Could not get file: {}", err);
- window.add_toast(&Toast::new(&err.to_user_facing()));
+ toast!(obj, err.to_user_facing());
return;
}
@@ -236,15 +235,14 @@ where
/// See `Event::get_media_content` for compatible events. Panics on an
/// incompatible event.
fn open_event_file(&self, event: Event) {
- let window: Window = self.root().unwrap().downcast().unwrap();
spawn!(
glib::PRIORITY_LOW,
- clone!(@weak window => async move {
+ clone!(@weak self as obj => async move {
let (uid, filename, data) = match event.get_media_content().await {
Ok(res) => res,
Err(err) => {
error!("Could not get file: {}", err);
- window.add_toast(&Toast::new(&err.to_user_facing()));
+ toast!(obj, err.to_user_facing());
return;
}
diff --git a/src/session/room/mod.rs b/src/session/room/mod.rs
index 0b1b507eb..fc2065fde 100644
--- a/src/session/room/mod.rs
+++ b/src/session/room/mod.rs
@@ -12,7 +12,7 @@ mod timeline;
use std::{cell::RefCell, convert::TryInto, path::PathBuf};
-use gettextrs::gettext;
+use gettextrs::{gettext, ngettext};
use gtk::{glib, glib::clone, prelude::*, subclass::prelude::*};
use log::{debug, error, info, warn};
use matrix_sdk::{
@@ -42,7 +42,7 @@ use matrix_sdk::{
serde::Raw,
EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomId, OwnedUserId, RoomId,
},
- DisplayName,
+ DisplayName, Result as MatrixResult,
};
use ruma::events::SyncEphemeralRoomEvent;
@@ -63,8 +63,8 @@ pub use self::{
};
use super::verification::IdentityVerification;
use crate::{
- components::{Pill, Toast},
- gettext_f, ngettext_f,
+ components::Pill,
+ gettext_f,
prelude::*,
session::{
avatar::update_room_avatar_from_file,
@@ -72,7 +72,7 @@ use crate::{
sidebar::{SidebarItem, SidebarItemImpl},
Avatar, Session, User,
},
- spawn, spawn_tokio,
+ spawn, spawn_tokio, toast,
utils::pending_event_ids,
};
@@ -458,21 +458,17 @@ impl Room {
obj.emit_by_name::<()>("room-forgotten", &[]);
}
Err(error) => {
- error!("Couldn’t forget the room: {}", error);
+ error!("Couldn’t forget the room: {}", error);
- let room_pill = Pill::for_room(&obj);
- let error = Toast::builder()
- // Translators: Do NOT translate the content between '{' and '}', this is a
variable name.
- .title(gettext_f("Failed to forget {room}.", &[("room", "<widget>")]))
- .widgets(&[room_pill])
- .build();
-
- if let Some(window) = obj.session().parent_window() {
- window.add_toast(&error);
- }
+ toast!(
+ obj.session(),
+ // Translators: Do NOT translate the content between '{' and '}', this is a
variable name.
+ gettext("Failed to forget {room}."),
+ @room = &obj,
+ );
- // Load the previous category
- obj.load_category();
+ // Load the previous category
+ obj.load_category();
},
};
})
@@ -699,24 +695,21 @@ impl Room {
match handle.await.unwrap() {
Ok(_) => {},
Err(error) => {
- error!("Couldn’t set the room category: {}", error);
-
- let room_pill = Pill::for_room(&obj);
- let error = Toast::builder()
- .title(gettext_f(
- // Translators: Do NOT translate the content between '{' and '}',
this is a variable name.
- "Failed to move {room} from {previous_category} to {new_category}.",
- &[("room", "<widget>"),("previous_category",
&previous_category.to_string()), ("new_category", &category.to_string())],
- ))
- .widgets(&[room_pill])
- .build();
-
- if let Some(window) = obj.session().parent_window() {
- window.add_toast(&error);
- }
+ error!("Couldn’t set the room category: {}", error);
+
+ toast!(
+ obj.session(),
+ gettext(
+ // Translators: Do NOT translate the content between '{' and '}', this
is a variable name.
+ "Failed to move {room} from {previous_category} to {new_category}.",
+ ),
+ @room = obj,
+ previous_category = previous_category.to_string(),
+ new_category = category.to_string(),
+ );
- // Load the previous category
- obj.load_category();
+ // Load the previous category
+ obj.load_category();
},
};
})
@@ -1426,7 +1419,7 @@ impl Room {
);
}
- pub async fn accept_invite(&self) -> Result<(), Toast> {
+ pub async fn accept_invite(&self) -> MatrixResult<()> {
let matrix_room = self.matrix_room();
if let MatrixRoom::Invited(matrix_room) = matrix_room {
@@ -1436,20 +1429,15 @@ impl Room {
Err(error) => {
error!("Accepting invitation failed: {}", error);
- let room_pill = Pill::for_room(self);
- let error = Toast::builder()
- .title(gettext_f(
+ toast!(
+ self.session(),
+ gettext(
// Translators: Do NOT translate the content between '{' and '}', this
// is a variable name.
"Failed to accept invitation for {room}. Try again later.",
- &[("room", "<widget>")],
- ))
- .widgets(&[room_pill])
- .build();
-
- if let Some(window) = self.session().parent_window() {
- window.add_toast(&error);
- }
+ ),
+ @room = self,
+ );
Err(error)
}
@@ -1460,7 +1448,7 @@ impl Room {
}
}
- pub async fn reject_invite(&self) -> Result<(), Toast> {
+ pub async fn reject_invite(&self) -> MatrixResult<()> {
let matrix_room = self.matrix_room();
if let MatrixRoom::Invited(matrix_room) = matrix_room {
@@ -1470,20 +1458,15 @@ impl Room {
Err(error) => {
error!("Rejecting invitation failed: {}", error);
- let room_pill = Pill::for_room(self);
- let error = Toast::builder()
- .title(gettext_f(
+ toast!(
+ self.session(),
+ gettext(
// Translators: Do NOT translate the content between '{' and '}', this
// is a variable name.
"Failed to reject invitation for {room}. Try again later.",
- &[("room", "<widget>")],
- ))
- .widgets(&[room_pill])
- .build();
-
- if let Some(window) = self.session().parent_window() {
- window.add_toast(&error);
- }
+ ),
+ @room = self,
+ );
Err(error)
}
@@ -1640,35 +1623,33 @@ impl Room {
let first_failed = failed_invites.first().unwrap();
// TODO: should we show all the failed users?
- let error_message =
- if no_failed == 1 {
- gettext_f(
+ if no_failed == 1 {
+ toast!(
+ self.session(),
+ gettext(
// Translators: Do NOT translate the content between '{' and '}', this
// is a variable name.
"Failed to invite {user} to {room}. Try again later.",
- &[("user", "<widget>"), ("room", "<widget>")],
- )
- } else {
- let n = (no_failed - 1) as u32;
- ngettext_f(
- // Translators: Do NOT translate the content between '{' and '}', this
- // is a variable name.
- "Failed to invite {user} and 1 other user to {room}. Try again later.",
- "Failed to invite {user} and {n} other users to {room}. Try again later.",
- n,
- &[("user", "<widget>"), ("room", "<widget>"), ("n", &n.to_string())],
- )
- };
- let user_pill = Pill::for_user(first_failed);
- let room_pill = Pill::for_room(self);
- let error = Toast::builder()
- .title(error_message)
- .widgets(&[user_pill, room_pill])
- .build();
-
- if let Some(window) = self.session().parent_window() {
- window.add_toast(&error);
- }
+ ),
+ @user = first_failed,
+ @room = self,
+ );
+ } else {
+ let n = (no_failed - 1) as u32;
+ toast!(
+ self.session(),
+ ngettext(
+ // Translators: Do NOT translate the content between '{' and '}', this
+ // is a variable name.
+ "Failed to invite {user} and 1 other user to {room}. Try again later.",
+ "Failed to invite {user} and {n} other users to {room}. Try again later.",
+ n,
+ ),
+ @user = first_failed,
+ @room = self,
+ n = n.to_string(),
+ );
+ };
}
} else {
error!("Can’t invite users, because this room isn’t a joined room");
diff --git a/src/session/room_list.rs b/src/session/room_list.rs
index 48f2b9878..8bb57d918 100644
--- a/src/session/room_list.rs
+++ b/src/session/room_list.rs
@@ -9,10 +9,9 @@ use matrix_sdk::{
};
use crate::{
- components::Toast,
gettext_f,
session::{room::Room, Session},
- spawn, spawn_tokio,
+ spawn, spawn_tokio, toast,
};
mod imp {
@@ -321,14 +320,14 @@ impl RoomList {
Err(error) => {
obj.pending_rooms_remove(&identifier);
error!("Joining room {} failed: {}", identifier, error);
- let error = Toast::new(
+
+ let error = gettext_f(
// Translators: Do NOT translate the content between '{' and '}', this is a
variable name.
- &gettext_f("Failed to join room {room_name}. Try again later.", &[("room_name",
identifier.as_str())])
+ "Failed to join room {room_name}. Try again later.",
+ &[("room_name", identifier.as_str())]
);
- if let Some(window) = obj.session().parent_window() {
- window.add_toast(&error);
- }
+ toast!(obj.session(), error);
}
}
})
diff --git a/src/session/verification/identity_verification.rs
b/src/session/verification/identity_verification.rs
index b0281efc5..8ca9ec275 100644
--- a/src/session/verification/identity_verification.rs
+++ b/src/session/verification/identity_verification.rs
@@ -22,14 +22,13 @@ use tokio::sync::mpsc;
use super::{VERIFICATION_CREATION_TIMEOUT, VERIFICATION_RECEIVE_TIMEOUT};
use crate::{
- components::Toast,
contrib::Camera,
session::{
sidebar::{SidebarItem, SidebarItemImpl},
user::UserExt,
Session, User,
},
- spawn, spawn_tokio,
+ spawn, spawn_tokio, toast,
};
#[derive(Debug, Eq, PartialEq, Clone, Copy, glib::Enum)]
@@ -697,9 +696,7 @@ impl IdentityVerification {
gettext("An unknown error occurred during the verification process.")
});
- if let Some(window) = self.session().parent_window() {
- window.add_toast(&Toast::new(&error_message));
- }
+ toast!(self.session(), error_message);
}
pub fn display_name(&self) -> String {
[
Date Prev][
Date Next] [
Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]