[fractal/multi-account: 17/19] Add account switcher




commit 5f31880b35c42300927897559747fef308cd225c
Author: Alejandro Domínguez <adomu net-c com>
Date:   Tue Jul 13 15:34:37 2021 +0200

    Add account switcher

 data/resources/style.css                     |  22 ++++
 data/resources/ui/sidebar.ui                 |  15 +++
 src/components/avatar.rs                     |   5 +
 src/meson.build                              |   3 +
 src/session/mod.rs                           |   7 +-
 src/session/sidebar/account_switcher/item.rs | 147 +++++++++++++++++++++++++++
 src/session/sidebar/account_switcher/mod.rs  |   2 +
 src/session/sidebar/account_switcher/rows.rs |  77 ++++++++++++++
 src/session/sidebar/mod.rs                   |   1 +
 src/session/sidebar/sidebar.rs               |  72 ++++++++++++-
 src/window.rs                                |   1 +
 11 files changed, 350 insertions(+), 2 deletions(-)
---
diff --git a/data/resources/style.css b/data/resources/style.css
index e5728086..355cf490 100644
--- a/data/resources/style.css
+++ b/data/resources/style.css
@@ -41,6 +41,28 @@ headerbar.flat {
   border: none;
 }
 
+/* Account switcher */
+#account-switcher row {
+  border-radius: 10px;
+  margin-top: 2px;
+  margin-bottom: 2px;
+  padding-top: 7px;
+  padding-bottom: 7px;
+}
+
+#account-switcher .user-id {
+  font-size: 12px;
+}
+
+#new-login-icon {
+  /*
+   *  2 * padding + pixel-size = size (of avatar)
+   */
+  padding: 10px;
+  background-color: lightgrey;
+  border-radius: 9999px;
+}
+
 /* Sidebar */
 .sidebar row {
   padding-left: 10px;
diff --git a/data/resources/ui/sidebar.ui b/data/resources/ui/sidebar.ui
index 5de728b5..eb9f13d3 100644
--- a/data/resources/ui/sidebar.ui
+++ b/data/resources/ui/sidebar.ui
@@ -29,6 +29,21 @@
               <object class="AdwWindowTitle"></object>
             </property>
             <property name="show-end-title-buttons" bind-source="Sidebar" bind-property="compact" 
bind-flags="sync-create"/>
+            <child type="start">
+              <object class="GtkMenuButton" id="accounts_button">
+                <property name="icon-name">system-users-symbolic</property>
+                <property name="popover">
+                  <object class="GtkPopover">
+                    <child>
+                      <object class="GtkListView" id="account_switcher">
+                        <property name="name">account-switcher</property>
+                        <property name="single-click-activate">true</property>
+                      </object>
+                    </child>
+                  </object>
+                </property>
+              </object>
+            </child>
             <child type="end">
               <object class="GtkMenuButton" id="appmenu_button">
                 <property name="icon-name">open-menu-symbolic</property>
diff --git a/src/components/avatar.rs b/src/components/avatar.rs
index 49e3e90b..1f0497ad 100644
--- a/src/components/avatar.rs
+++ b/src/components/avatar.rs
@@ -105,6 +105,11 @@ impl Avatar {
         glib::Object::new(&[]).expect("Failed to create Avatar")
     }
 
+    pub fn set_size(&self, size: i32) {
+        let priv_ = imp::Avatar::from_instance(self);
+        priv_.avatar.set_size(size);
+    }
+
     pub fn set_item(&self, item: Option<AvatarItem>) {
         let priv_ = imp::Avatar::from_instance(self);
 
diff --git a/src/meson.build b/src/meson.build
index ee7f4d2a..63fa861e 100644
--- a/src/meson.build
+++ b/src/meson.build
@@ -71,6 +71,9 @@ sources = files(
   'session/sidebar/room_row.rs',
   'session/sidebar/selection.rs',
   'session/sidebar/sidebar.rs',
+  'session/sidebar/account_switcher/item.rs',
+  'session/sidebar/account_switcher/mod.rs',
+  'session/sidebar/account_switcher/rows.rs',
 )
 
 custom_target(
diff --git a/src/session/mod.rs b/src/session/mod.rs
index 3084f7cd..436fa2f6 100644
--- a/src/session/mod.rs
+++ b/src/session/mod.rs
@@ -25,7 +25,7 @@ use crate::session::content::ContentType;
 use adw::subclass::prelude::BinImpl;
 use gtk::subclass::prelude::*;
 use gtk::{self, prelude::*};
-use gtk::{gio, glib, glib::clone, glib::SyncSender, CompositeTemplate};
+use gtk::{gio, glib, glib::clone, glib::SyncSender, CompositeTemplate, SelectionModel};
 use gtk_macros::send;
 use log::error;
 use matrix_sdk::ruma::{
@@ -449,6 +449,11 @@ impl Session {
     fn handle_sync_response(&self, response: SyncResponse) {
         self.room_list().handle_response_rooms(response.rooms);
     }
+
+    pub fn set_logged_in_users(&self, sessions_stack_pages: &SelectionModel) {
+        let priv_ = &imp::Session::from_instance(self);
+        priv_.sidebar.set_logged_in_users(sessions_stack_pages);
+    }
 }
 
 impl Default for Session {
diff --git a/src/session/sidebar/account_switcher/item.rs b/src/session/sidebar/account_switcher/item.rs
new file mode 100644
index 00000000..2e4ebe72
--- /dev/null
+++ b/src/session/sidebar/account_switcher/item.rs
@@ -0,0 +1,147 @@
+use super::rows;
+use gtk::{gio::ListStore, glib, prelude::*, subclass::prelude::*};
+use std::convert::TryFrom;
+
+mod imp {
+    use super::*;
+    use once_cell::sync::Lazy;
+    use std::cell::Cell;
+
+    #[derive(Debug, Default)]
+    pub struct ExtraItemObj(pub Cell<super::ExtraItem>);
+
+    #[glib::object_subclass]
+    impl ObjectSubclass for ExtraItemObj {
+        const NAME: &'static str = "ExtraItemObj";
+        type Type = super::ExtraItemObj;
+        type ParentType = glib::Object;
+    }
+
+    impl ObjectImpl for ExtraItemObj {
+        fn properties() -> &'static [glib::ParamSpec] {
+            static PROPERTIES: Lazy<Vec<glib::ParamSpec>> = Lazy::new(|| {
+                vec![glib::ParamSpec::new_enum(
+                    "inner",
+                    "Inner",
+                    "Inner value of ExtraItem",
+                    super::ExtraItem::static_type(),
+                    0,
+                    glib::ParamFlags::READWRITE | glib::ParamFlags::CONSTRUCT_ONLY,
+                )]
+            });
+
+            PROPERTIES.as_ref()
+        }
+
+        fn property(&self, obj: &Self::Type, _id: usize, pspec: &glib::ParamSpec) -> glib::Value {
+            match pspec.name() {
+                "inner" => obj.get().to_value(),
+                _ => unimplemented!(),
+            }
+        }
+
+        fn set_property(
+            &self,
+            _obj: &Self::Type,
+            _id: usize,
+            value: &glib::Value,
+            pspec: &glib::ParamSpec,
+        ) {
+            match pspec.name() {
+                "inner" => self.0.set(value.get().unwrap()),
+                _ => unimplemented!(),
+            }
+        }
+    }
+}
+
+#[derive(Debug, Hash, Eq, PartialEq, Clone, Copy, glib::GEnum)]
+#[repr(u32)]
+#[genum(type_name = "ExtraItem")]
+pub enum ExtraItem {
+    Separator = 0,
+    AddAccount = 1,
+}
+
+impl ExtraItem {
+    const VALUES: [Self; 2] = [Self::Separator, Self::AddAccount];
+}
+
+impl Default for ExtraItem {
+    fn default() -> Self {
+        Self::Separator
+    }
+}
+
+glib::wrapper! {
+    pub struct ExtraItemObj(ObjectSubclass<imp::ExtraItemObj>);
+}
+
+impl From<&ExtraItem> for ExtraItemObj {
+    fn from(item: &ExtraItem) -> Self {
+        glib::Object::new(&[("inner", item)]).expect("Failed to create ExtraItem")
+    }
+}
+
+impl ExtraItemObj {
+    pub fn list_store() -> ListStore {
+        ExtraItem::VALUES.iter().map(ExtraItemObj::from).fold(
+            ListStore::new(ExtraItemObj::static_type()),
+            |list_items, item| {
+                list_items.append(&item);
+                list_items
+            },
+        )
+    }
+
+    pub fn get(&self) -> ExtraItem {
+        let priv_ = imp::ExtraItemObj::from_instance(self);
+
+        priv_.0.get()
+    }
+
+    pub fn is_separator(&self) -> bool {
+        self.get() == ExtraItem::Separator
+    }
+
+    pub fn is_add_account(&self) -> bool {
+        self.get() == ExtraItem::AddAccount
+    }
+}
+
+#[derive(Debug, Clone)]
+pub enum Item {
+    User(gtk::StackPage),
+    Separator,
+    AddAccount,
+}
+
+impl From<ExtraItem> for Item {
+    fn from(extra_item: ExtraItem) -> Self {
+        match extra_item {
+            ExtraItem::Separator => Self::Separator,
+            ExtraItem::AddAccount => Self::AddAccount,
+        }
+    }
+}
+
+impl TryFrom<glib::Object> for Item {
+    type Error = glib::Object;
+
+    fn try_from(object: glib::Object) -> Result<Self, Self::Error> {
+        object
+            .downcast::<gtk::StackPage>()
+            .map(Self::User)
+            .or_else(|object| object.downcast::<ExtraItemObj>().map(|it| it.get().into()))
+    }
+}
+
+impl Item {
+    pub fn build_widget(&self) -> gtk::Widget {
+        match self {
+            Self::User(ref session_page) => rows::user_entry(session_page).upcast(),
+            Self::Separator => gtk::Separator::new(gtk::Orientation::Vertical).upcast(),
+            Self::AddAccount => rows::add_account().upcast(),
+        }
+    }
+}
diff --git a/src/session/sidebar/account_switcher/mod.rs b/src/session/sidebar/account_switcher/mod.rs
new file mode 100644
index 00000000..e10218a8
--- /dev/null
+++ b/src/session/sidebar/account_switcher/mod.rs
@@ -0,0 +1,2 @@
+pub mod item;
+pub mod rows;
diff --git a/src/session/sidebar/account_switcher/rows.rs b/src/session/sidebar/account_switcher/rows.rs
new file mode 100644
index 00000000..5e3a32b1
--- /dev/null
+++ b/src/session/sidebar/account_switcher/rows.rs
@@ -0,0 +1,77 @@
+use crate::{
+    components::Avatar as ComponentsAvatar,
+    session::{Session, User},
+};
+use gtk::{glib, prelude::*};
+
+pub fn user_entry(session_page: &gtk::StackPage) -> gtk::Box {
+    let session = session_page.child().downcast::<Session>().unwrap();
+    let user = session.user();
+
+    let container = gtk::Box::new(gtk::Orientation::Horizontal, 10);
+
+    let ref avatar = ComponentsAvatar::new();
+    avatar.set_size(40);
+    let avatar_exp = gtk::PropertyExpression::new::<gtk::PropertyExpression>(
+        User::static_type(),
+        None,
+        "avatar",
+    );
+    avatar_exp.bind::<glib::Object>(avatar.upcast_ref(), "item", Some(user.upcast_ref()));
+
+    let ref identifiers = gtk::Box::new(gtk::Orientation::Vertical, 5);
+
+    let ref display_name = gtk::Label::builder()
+        .xalign(0.0)
+        .css_classes(vec!["bold".into()])
+        .build();
+    let display_name_exp = gtk::PropertyExpression::new::<gtk::PropertyExpression>(
+        User::static_type(),
+        None,
+        "display-name",
+    );
+    display_name_exp.bind::<glib::Object>(
+        display_name.upcast_ref(),
+        "label",
+        Some(user.upcast_ref()),
+    );
+
+    let ref user_id = gtk::Label::builder()
+        .xalign(0.0)
+        .css_classes(vec!["dim-label".into(), "user-id".into()])
+        .build();
+    let user_id_exp = gtk::PropertyExpression::new::<gtk::PropertyExpression>(
+        User::static_type(),
+        None,
+        "user-id",
+    );
+    user_id_exp.bind::<glib::Object>(user_id.upcast_ref(), "label", Some(user.upcast_ref()));
+
+    identifiers.append(display_name);
+    identifiers.append(user_id);
+
+    container.append(avatar);
+    container.append(identifiers);
+
+    container
+}
+
+pub fn add_account() -> gtk::Box {
+    let container = gtk::Box::new(gtk::Orientation::Horizontal, 10);
+
+    let ref icon = gtk::Image::builder()
+        .icon_name("list-add-symbolic")
+        .pixel_size(20)
+        .build();
+    icon.set_widget_name("new-login-icon");
+
+    let ref label = gtk::Label::builder()
+        .label("_Add account")
+        .use_underline(true)
+        .build();
+
+    container.append(icon);
+    container.append(label);
+
+    container
+}
diff --git a/src/session/sidebar/mod.rs b/src/session/sidebar/mod.rs
index e9cc2def..ac8dc48d 100644
--- a/src/session/sidebar/mod.rs
+++ b/src/session/sidebar/mod.rs
@@ -1,3 +1,4 @@
+mod account_switcher;
 mod category;
 mod category_row;
 mod entry;
diff --git a/src/session/sidebar/sidebar.rs b/src/session/sidebar/sidebar.rs
index 50ff61ce..1e54619a 100644
--- a/src/session/sidebar/sidebar.rs
+++ b/src/session/sidebar/sidebar.rs
@@ -1,6 +1,14 @@
 use adw::subclass::prelude::BinImpl;
-use gtk::{gio, glib, prelude::*, subclass::prelude::*, CompositeTemplate};
+use gtk::{
+    gio::{self, ListModel, ListStore},
+    glib,
+    prelude::*,
+    subclass::prelude::*,
+    CompositeTemplate, SelectionModel,
+};
+use std::convert::TryFrom;
 
+use super::account_switcher::item::{ExtraItemObj, Item as AccountSwitcherItem};
 use crate::session::{
     content::ContentType,
     room::Room,
@@ -23,6 +31,8 @@ mod imp {
         #[template_child]
         pub headerbar: TemplateChild<adw::HeaderBar>,
         #[template_child]
+        pub account_switcher: TemplateChild<gtk::ListView>,
+        #[template_child]
         pub listview: TemplateChild<gtk::ListView>,
         #[template_child]
         pub room_search_entry: TemplateChild<gtk::SearchEntry>,
@@ -142,6 +152,53 @@ mod imp {
                     _ => {}
                 }
             });
+
+            // Account switcher setup
+
+            self.account_switcher.connect_activate(|list_view, index| {
+                list_view
+                    .model()
+                    .and_then(|model| model.item(index))
+                    .map(AccountSwitcherItem::try_from)
+                    .and_then(Result::ok)
+                    .map(|item| match item {
+                        AccountSwitcherItem::User(session_page) => {
+                            session_page.set_visible(true);
+                        }
+                        _ => {}
+                    });
+            });
+
+            // There is no permanent stuff to take care of,
+            // so only bind and unbind are connected.
+            let ref factory = gtk::SignalListItemFactory::new();
+            factory.connect_bind(|_, list_item| {
+                list_item.set_selectable(false);
+                let child = list_item
+                    .item()
+                    .map(AccountSwitcherItem::try_from)
+                    .and_then(Result::ok)
+                    .as_ref()
+                    .map(|item| {
+                        match item {
+                            AccountSwitcherItem::Separator => {
+                                list_item.set_activatable(false);
+                            }
+                            _ => {}
+                        }
+
+                        item
+                    })
+                    .map(AccountSwitcherItem::build_widget);
+
+                list_item.set_child(child.as_ref());
+            });
+
+            factory.connect_unbind(|_, list_item| {
+                list_item.set_child::<gtk::Widget>(None);
+            });
+
+            self.account_switcher.set_factory(Some(factory));
         }
     }
 
@@ -249,6 +306,19 @@ impl Sidebar {
         priv_.selected_room.replace(selected_room);
         self.notify("selected-room");
     }
+
+    pub fn set_logged_in_users(&self, sessions_stack_pages: &SelectionModel) {
+        let account_switcher = imp::Sidebar::from_instance(self).account_switcher.get();
+
+        let ref end_items = ExtraItemObj::list_store();
+        let ref items_split = ListStore::new(ListModel::static_type());
+        items_split.append(sessions_stack_pages);
+        items_split.append(end_items);
+        let ref items = gtk::FlattenListModel::new(Some(items_split));
+        let ref selectable_items = gtk::NoSelection::new(Some(items));
+
+        account_switcher.set_model(Some(selectable_items));
+    }
 }
 
 impl Default for Sidebar {
diff --git a/src/window.rs b/src/window.rs
index 7485a1d9..ca973c6c 100644
--- a/src/window.rs
+++ b/src/window.rs
@@ -107,6 +107,7 @@ impl Window {
 
     fn add_session(&self, session: &Session) {
         let priv_ = &imp::Window::from_instance(self);
+        session.set_logged_in_users(&priv_.sessions.pages());
         priv_.sessions.add_child(session);
         priv_.sessions.set_visible_child(session);
         self.install_session_actions(session);


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