add app groups

This commit is contained in:
Ashley Wulber 2021-12-02 17:25:33 -05:00 committed by Jeremy Soller
parent 0bca6c94b6
commit b1cff2ab59
11 changed files with 373 additions and 76 deletions

View file

@ -20,4 +20,6 @@ postage = "0.4.1"
futures = "0.3.18"
glib = "0.14.8"
# examples/gtklauncher
once_cell = "1.8.0"
once_cell = "1.8.0"
xdg = "2.4.0"
serde = "1.0.130"

View file

@ -0,0 +1,163 @@
use glib::{FromVariant, ParamFlags, ParamSpec, ToVariant, Value, Variant, VariantTy};
use gtk4::glib;
use gtk4::prelude::*;
use gtk4::subclass::prelude::*;
use once_cell::sync::Lazy;
use std::cell::RefCell;
use std::rc::Rc;
use super::AppGroupData;
// Object holding the state
#[derive(Default)]
pub struct AppGroup {
data: Rc<RefCell<AppGroupData>>,
}
// The central trait for subclassing a GObject
#[glib::object_subclass]
impl ObjectSubclass for AppGroup {
const NAME: &'static str = "AppGroup";
type Type = super::AppGroup;
type ParentType = glib::Object;
}
// Trait shared by all GObjects
impl ObjectImpl for AppGroup {
fn properties() -> &'static [ParamSpec] {
static PROPERTIES: Lazy<Vec<ParamSpec>> = Lazy::new(|| {
vec![
ParamSpec::new_uint(
// Name
"id",
// Nickname
"id",
// Short description
"Name of the application group",
0,
u32::MAX,
// Default value
0,
// The property can be read and written to
ParamFlags::READWRITE,
),
ParamSpec::new_string(
// Name
"name",
// Nickname
"name",
// Short description
"Name of the application group",
// Default value
Some(""),
// The property can be read and written to
ParamFlags::READWRITE,
),
ParamSpec::new_boolean(
// Name
"mutable",
// Nickname
"mutable",
// Short description
"Mutability of the application group",
// Default value
false,
// The property can be read and written to
ParamFlags::READWRITE,
),
ParamSpec::new_string(
// Name
"icon",
// Nickname
"icon",
// Short description
"Icon of application Group",
// Default value
Some("folder"),
// The property can be read and written to
ParamFlags::READWRITE,
),
ParamSpec::new_string(
// Name
"category",
// Nickname
"category",
// Short description
"Category of application Group",
// Default value
None,
// The property can be read and written to
ParamFlags::READWRITE,
),
ParamSpec::new_variant(
// Name
"appnames",
// Nickname
"appnames",
// Short description
"Names of applications in the App Group",
VariantTy::new("as").expect("Oops invalid string for VariantTy tuple."),
// Default value
None,
// The property can be read and written to
ParamFlags::READWRITE,
),
]
});
PROPERTIES.as_ref()
}
fn set_property(&self, _obj: &Self::Type, _id: usize, value: &Value, pspec: &ParamSpec) {
match pspec.name() {
"id" => {
let id = value.get().expect("The value needs to be of type `u32`.");
self.data.borrow_mut().id = id;
}
"name" => {
let name = value
.get()
.expect("The value needs to be of type `String`.");
self.data.borrow_mut().name = name;
}
"icon" => {
let icon = value.get().expect("The icon needs to be of type `String`");
self.data.borrow_mut().icon = icon;
}
"category" => {
let category = value
.get()
.expect("The category needs to be of type `String`");
self.data.borrow_mut().category = category;
}
"mutable" => {
let mutable = value
.get()
.expect("The mutable property needs to be of type `bool`");
self.data.borrow_mut().mutable = mutable;
}
"appnames" => {
let appnames = <Vec<String>>::from_variant(
&value
.get::<Variant>()
.expect("The icon needs to be a Variant"),
)
.expect("The icon variant needs to be a Vec<String>");
self.data.borrow_mut().app_names = appnames;
}
_ => unimplemented!(),
}
}
fn property(&self, _obj: &Self::Type, _id: usize, pspec: &ParamSpec) -> Value {
match pspec.name() {
"id" => self.data.borrow().id.to_value(),
"name" => self.data.borrow().name.to_value(),
"icon" => self.data.borrow().icon.to_value(),
"mutable" => self.data.borrow().mutable.to_value(),
"category" => self.data.borrow().category.to_value(),
"appnames" => self.data.borrow().app_names.to_variant().to_value(),
_ => unimplemented!(),
}
}
}

View file

@ -0,0 +1,40 @@
mod imp;
use gdk4::glib::Object;
use glib::ObjectExt;
use glib::ToVariant;
use gtk4::glib;
use serde::{Deserialize, Serialize};
glib::wrapper! {
pub struct AppGroup(ObjectSubclass<imp::AppGroup>);
}
impl AppGroup {
pub fn new(data: AppGroupData) -> Self {
let self_: Self = Object::new(&[
("id", &data.id),
("name", &data.name),
("mutable", &data.mutable),
("icon", &data.icon),
("category", &data.category),
])
.expect("Failed to create `ApplicationObject`.");
if let Err(e) = self_.set_property("appnames", data.app_names.to_variant()) {
println!("failed to set category icon property");
dbg!(e);
};
self_
}
}
// Object holding the state
#[derive(Default, Serialize, Deserialize, Clone)]
pub struct AppGroupData {
pub id: u32,
pub name: String,
pub icon: String,
pub mutable: bool,
pub app_names: Vec<String>,
pub category: String,
}

View file

@ -1,31 +0,0 @@
use gtk4 as gtk;
mod imp;
use gtk::prelude::*;
use gtk::subclass::prelude::*;
use gtk::{gio, glib};
glib::wrapper! {
pub struct AppItem(ObjectSubclass<imp::AppItem>)
@extends gtk::Widget, gtk::Box;
}
impl Default for AppItem {
fn default() -> Self {
Self::new()
}
}
impl AppItem {
pub fn new() -> Self {
glib::Object::new(&[]).expect("Failed to create AppItem")
}
pub fn set_app_info(&self, app_info: &gio::AppInfo) {
let self_ = imp::AppItem::from_instance(self);
self_.name.set_text(&app_info.name());
if let Some(icon) = app_info.icon() {
self_.image.set_from_gicon(&icon);
}
}
}

View file

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<interface>
<template class="AppItem" parent="GtkBox">
<template class="GridItem" parent="GtkBox">
<property name="orientation">vertical</property>
<property name="halign">center</property>
<property name="hexpand">true</property>

View file

@ -6,8 +6,8 @@ use gtk4 as gtk;
use gtk::CompositeTemplate;
#[derive(Debug, Default, CompositeTemplate)]
#[template(file = "app_item.ui")]
pub struct AppItem {
#[template(file = "grid_item.ui")]
pub struct GridItem {
#[template_child]
pub name: TemplateChild<gtk::Label>,
#[template_child]
@ -15,9 +15,9 @@ pub struct AppItem {
}
#[glib::object_subclass]
impl ObjectSubclass for AppItem {
const NAME: &'static str = "AppItem";
type Type = super::AppItem;
impl ObjectSubclass for GridItem {
const NAME: &'static str = "GridItem";
type Type = super::GridItem;
type ParentType = gtk::Box;
fn class_init(klass: &mut Self::Class) {
@ -29,6 +29,6 @@ impl ObjectSubclass for AppItem {
}
}
impl ObjectImpl for AppItem {}
impl WidgetImpl for AppItem {}
impl BoxImpl for AppItem {}
impl ObjectImpl for GridItem {}
impl WidgetImpl for GridItem {}
impl BoxImpl for GridItem {}

View file

@ -0,0 +1,50 @@
use crate::app_group::AppGroup;
use gtk4 as gtk;
mod imp;
use gtk::prelude::*;
use gtk::subclass::prelude::*;
use gtk::{gio, glib};
glib::wrapper! {
pub struct GridItem(ObjectSubclass<imp::GridItem>)
@extends gtk::Widget, gtk::Box;
}
impl Default for GridItem {
fn default() -> Self {
Self::new()
}
}
impl GridItem {
pub fn new() -> Self {
glib::Object::new(&[]).expect("Failed to create GridItem")
}
pub fn set_app_info(&self, app_info: &gio::DesktopAppInfo) {
let self_ = imp::GridItem::from_instance(self);
self_.name.set_text(&app_info.name());
if let Some(icon) = app_info.icon() {
self_.image.set_from_gicon(&icon);
}
}
pub fn set_group_info(&self, app_group: AppGroup) {
let self_ = imp::GridItem::from_instance(self);
if let Ok(name) = app_group.property("name") {
self_.name.set_text(
&name
.get::<String>()
.expect("property name needs to be a string."),
);
}
if let Ok(icon) = app_group.property("icon") {
&self_.image.set_from_icon_name(Some(
&icon
.get::<String>()
.expect("Property name needs to be a String."),
));
}
}
}

View file

@ -1,4 +1,5 @@
mod app_item;
mod app_group;
mod grid_item;
mod window;
use gtk::gdk::Display;

View file

@ -1,4 +1,6 @@
use gtk4 as gtk;
use std::cell::RefCell;
use std::rc::Rc;
use glib::subclass::InitializingObject;
use gtk::prelude::*;
@ -16,6 +18,9 @@ pub struct Window {
#[template_child]
pub app_grid_view: TemplateChild<GridView>,
pub app_model: OnceCell<gio::ListStore>,
#[template_child]
pub group_grid_view: TemplateChild<GridView>,
pub group_model: OnceCell<gio::ListStore>,
}
// The central trait for subclassing a GObject

View file

@ -1,7 +1,10 @@
mod imp;
use crate::app_group::AppGroup;
use crate::app_group::AppGroupData;
use gtk4 as gtk;
use std::path::Path;
use crate::app_item::AppItem;
use crate::grid_item::GridItem;
use glib::Object;
use gtk::prelude::*;
use gtk::subclass::prelude::*;
@ -36,21 +39,40 @@ impl Window {
fn setup_model(&self) {
// Create new model
let model = gio::ListStore::new(gio::AppInfo::static_type());
gio::AppInfo::all().iter().for_each(|app_info| {
model.append(app_info);
});
let app_model = gio::ListStore::new(gio::DesktopAppInfo::static_type());
// Get state and set model
let imp = imp::Window::from_instance(self);
imp.app_model
.set(model.clone())
.set(app_model.clone())
.expect("Could not set model");
// A sorter used to sort AppInfo in the model by their name
xdg::BaseDirectories::new()
.expect("could not access XDG Base directory")
.get_data_dirs()
.iter_mut()
.for_each(|xdg_data_path| {
xdg_data_path.push("applications");
if let Ok(dir_iter) = std::fs::read_dir(xdg_data_path) {
dir_iter.for_each(|dir_entry| {
if let Ok(dir_entry) = dir_entry {
if let Some(path) = dir_entry.path().file_name() {
if let Some(path) = path.to_str() {
if let Some(app_info) = gio::DesktopAppInfo::new(path) {
if !app_info.should_show() {
app_model.append(&app_info)
};
}
}
}
}
})
}
});
let sorter = gtk::CustomSorter::new(move |obj1, obj2| {
let app_info1 = obj1.downcast_ref::<gio::AppInfo>().unwrap();
let app_info2 = obj2.downcast_ref::<gio::AppInfo>().unwrap();
let app_info1 = obj1.downcast_ref::<gio::DesktopAppInfo>().unwrap();
let app_info2 = obj2.downcast_ref::<gio::DesktopAppInfo>().unwrap();
app_info1
.name()
@ -59,12 +81,49 @@ impl Window {
.into()
});
let filter = gtk::CustomFilter::new(|_obj| true);
let filter_model = gtk::FilterListModel::new(Some(&model), Some(filter).as_ref());
let filter_model = gtk::FilterListModel::new(Some(&app_model), Some(filter).as_ref());
let sorted_model = gtk::SortListModel::new(Some(&filter_model), Some(&sorter));
let selection_model = gtk::SingleSelection::new(Some(&sorted_model));
// Wrap model with selection and pass it to the list view
imp.app_grid_view.set_model(Some(&selection_model));
let group_model = gio::ListStore::new(AppGroup::static_type());
imp.group_model
.set(group_model.clone())
.expect("Could not set group model");
vec![
AppGroup::new(AppGroupData {
id: 0,
name: "Library Home".to_string(),
icon: "user-home".to_string(),
mutable: false,
app_names: Vec::new(),
category: "".to_string(),
}),
AppGroup::new(AppGroupData {
id: 0,
name: "System".to_string(),
icon: "folder".to_string(),
mutable: false,
app_names: Vec::new(),
category: "System".to_string(),
}),
AppGroup::new(AppGroupData {
id: 0,
name: "Utilities".to_string(),
icon: "folder".to_string(),
mutable: false,
app_names: Vec::new(),
category: "Utility".to_string(),
}),
]
.iter()
.for_each(|group| {
group_model.append(group);
});
imp.group_grid_view
.set_model(Some(&gtk4::SingleSelection::new(Some(&group_model))));
}
fn setup_callbacks(&self) {
@ -94,7 +153,7 @@ impl Window {
let app_info = model
.item(position)
.unwrap()
.downcast::<gio::AppInfo>()
.downcast::<gio::DesktopAppInfo>()
.unwrap();
let context = grid_view.display().app_launch_context();
@ -116,14 +175,14 @@ impl Window {
glib::clone!(@weak filter_model, @weak sorted_model => move |search: &gtk::SearchEntry| {
let search_text = search.text().to_string().to_lowercase();
let new_filter: gtk::CustomFilter = gtk::CustomFilter::new(move |obj| {
let search_res = obj.downcast_ref::<gio::AppInfo>()
let search_res = obj.downcast_ref::<gio::DesktopAppInfo>()
.expect("The Object needs to be of type AppInfo");
search_res.name().to_string().to_lowercase().contains(&search_text)
});
let search_text = search.text().to_string().to_lowercase();
let new_sorter: gtk::CustomSorter = gtk::CustomSorter::new(move |obj1, obj2| {
let app_info1 = obj1.downcast_ref::<gio::AppInfo>().unwrap();
let app_info2 = obj2.downcast_ref::<gio::AppInfo>().unwrap();
let app_info1 = obj1.downcast_ref::<gio::DesktopAppInfo>().unwrap();
let app_info2 = obj2.downcast_ref::<gio::DesktopAppInfo>().unwrap();
if search_text == "" {
return app_info1
.name()
@ -181,25 +240,41 @@ impl Window {
}
fn setup_factory(&self) {
let factory = SignalListItemFactory::new();
factory.connect_setup(move |_factory, item| {
let row = AppItem::new();
let app_factory = SignalListItemFactory::new();
app_factory.connect_setup(move |_factory, item| {
let row = GridItem::new();
item.set_child(Some(&row));
});
// the bind stage is used for "binding" the data to the created widgets on the "setup" stage
factory.connect_bind(move |_factory, grid_item| {
app_factory.connect_bind(move |_factory, grid_item| {
let app_info = grid_item
.item()
.unwrap()
.downcast::<gio::AppInfo>()
.downcast::<gio::DesktopAppInfo>()
.unwrap();
let child = grid_item.child().unwrap().downcast::<AppItem>().unwrap();
let child = grid_item.child().unwrap().downcast::<GridItem>().unwrap();
child.set_app_info(&app_info);
});
// Set the factory of the list view
let imp = imp::Window::from_instance(self);
imp.app_grid_view.set_factory(Some(&factory));
imp.app_grid_view.set_factory(Some(&app_factory));
let group_factory = SignalListItemFactory::new();
group_factory.connect_setup(move |_factory, item| {
let row = GridItem::new();
item.set_child(Some(&row));
});
// the bind stage is used for "binding" the data to the created widgets on the "setup" stage
group_factory.connect_bind(move |_factory, grid_item| {
let group_info = grid_item.item().unwrap().downcast::<AppGroup>().unwrap();
let child = grid_item.child().unwrap().downcast::<GridItem>().unwrap();
child.set_group_info(group_info);
});
// Set the factory of the list view
imp.group_grid_view.set_factory(Some(&group_factory));
}
}

View file

@ -44,19 +44,11 @@
</object>
</child>
<child>
<object class="GtkScrolledWindow">
<property name="hscrollbar-policy">never</property>
<property name="min-content-height">100</property>
<property name="max-content-height">200</property>
<property name="vexpand">true</property>
<child>
<object class="GtkGridView" id="group_grid_view">
<property name="min-columns">8</property>
<property name="max-columns">8</property>
<property name="single-click-activate">true</property>
<property name="enable-rubberband">true</property>
</object>
</child>
<object class="GtkGridView" id="group_grid_view">
<property name="min-columns">8</property>
<property name="max-columns">8</property>
<property name="single-click-activate">true</property>
<property name="enable-rubberband">true</property>
</object>
</child>
</object>