focus windows using launcher IPC
This commit is contained in:
parent
19f003f942
commit
54b762dbab
18 changed files with 350 additions and 276 deletions
|
|
@ -1,7 +1,4 @@
|
|||
use glib::{
|
||||
types::Type, FromVariant, ParamFlags, ParamSpec, ParamSpecObject, ToVariant, Value, Variant,
|
||||
VariantTy,
|
||||
};
|
||||
use glib::{FromVariant, ParamFlags, ParamSpec, ToVariant, Value, Variant, VariantTy};
|
||||
use gtk4::glib;
|
||||
use gtk4::prelude::*;
|
||||
use gtk4::subclass::prelude::*;
|
||||
|
|
@ -21,7 +18,7 @@ pub struct ApplicationObject {
|
|||
// The central trait for subclassing a GObject
|
||||
#[glib::object_subclass]
|
||||
impl ObjectSubclass for ApplicationObject {
|
||||
const NAME: &'static str = "LibCosmicLauncherApplicationObject";
|
||||
const NAME: &'static str = "ApplicationObject";
|
||||
type Type = super::ApplicationObject;
|
||||
type ParentType = glib::Object;
|
||||
}
|
||||
|
|
@ -31,6 +28,20 @@ impl ObjectImpl for ApplicationObject {
|
|||
fn properties() -> &'static [ParamSpec] {
|
||||
static PROPERTIES: Lazy<Vec<ParamSpec>> = Lazy::new(|| {
|
||||
vec![
|
||||
ParamSpec::new_uint(
|
||||
// Name
|
||||
"id",
|
||||
// Nickname
|
||||
"id",
|
||||
// Short description
|
||||
"ID of application in launcher search result",
|
||||
0,
|
||||
u32::MAX,
|
||||
// Default value
|
||||
0,
|
||||
// The property can be read and written to
|
||||
ParamFlags::READWRITE,
|
||||
),
|
||||
ParamSpec::new_string(
|
||||
// Name
|
||||
"name",
|
||||
|
|
@ -102,6 +113,10 @@ impl ObjectImpl for ApplicationObject {
|
|||
|
||||
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().0.id = id;
|
||||
}
|
||||
"name" => {
|
||||
let name = value
|
||||
.get()
|
||||
|
|
@ -115,46 +130,44 @@ impl ObjectImpl for ApplicationObject {
|
|||
self.data.borrow_mut().0.description = description;
|
||||
}
|
||||
"icon" => {
|
||||
let icon = <Option<(i32, String)>>::from_variant(
|
||||
let icon = <(i32, String)>::from_variant(
|
||||
&value
|
||||
.get::<Variant>()
|
||||
.expect("The icon needs to be a Variant"),
|
||||
)
|
||||
.expect("The icon variant needs to be an Option<(i32, String)>");
|
||||
if let Some(icon) = icon {
|
||||
self.data.borrow_mut().0.icon = match icon {
|
||||
(i_type, name) if i_type == pop_launcher::IconSource::Name as i32 => {
|
||||
Some(pop_launcher::IconSource::Name(name.into()))
|
||||
}
|
||||
(i_type, name) if i_type == pop_launcher::IconSource::Mime as i32 => {
|
||||
Some(pop_launcher::IconSource::Mime(name.into()))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
} else {
|
||||
self.data.borrow_mut().0.icon = None;
|
||||
}
|
||||
.expect("The icon variant needs to be an (i32, String)");
|
||||
self.data.borrow_mut().0.icon = match icon {
|
||||
(i_type, name) if i_type == pop_launcher::IconSource::Name as i32 => {
|
||||
Some(pop_launcher::IconSource::Name(name.into()))
|
||||
}
|
||||
(i_type, name) if i_type == pop_launcher::IconSource::Mime as i32 => {
|
||||
Some(pop_launcher::IconSource::Mime(name.into()))
|
||||
}
|
||||
(i_type, name) => {
|
||||
println!("Failed to set icon. {} {}", i_type, name);
|
||||
None
|
||||
}
|
||||
};
|
||||
}
|
||||
"categoryicon" => {
|
||||
let icon = <Option<(i32, String)>>::from_variant(
|
||||
let icon = <(i32, String)>::from_variant(
|
||||
&value
|
||||
.get::<Variant>()
|
||||
.expect("The icon needs to be a Variant"),
|
||||
)
|
||||
.expect("The icon variant needs to be an Option<(i32, String)>");
|
||||
if let Some(icon) = icon {
|
||||
self.data.borrow_mut().0.icon = match icon {
|
||||
(i_type, name) if i_type == pop_launcher::IconSource::Name as i32 => {
|
||||
Some(pop_launcher::IconSource::Name(name.into()))
|
||||
}
|
||||
(i_type, name) if i_type == pop_launcher::IconSource::Mime as i32 => {
|
||||
Some(pop_launcher::IconSource::Mime(name.into()))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
} else {
|
||||
self.data.borrow_mut().0.icon = None;
|
||||
}
|
||||
self.data.borrow_mut().0.category_icon = match icon {
|
||||
(i_type, name) if i_type == pop_launcher::IconSource::Name as i32 => {
|
||||
Some(pop_launcher::IconSource::Name(name.into()))
|
||||
}
|
||||
(i_type, name) if i_type == pop_launcher::IconSource::Mime as i32 => {
|
||||
Some(pop_launcher::IconSource::Mime(name.into()))
|
||||
}
|
||||
(i_type, name) => {
|
||||
println!("Failed to set icon. {} {}", i_type, name);
|
||||
None
|
||||
}
|
||||
};
|
||||
}
|
||||
"window" => {
|
||||
unimplemented!()
|
||||
|
|
@ -165,8 +178,9 @@ impl ObjectImpl for ApplicationObject {
|
|||
|
||||
fn property(&self, _obj: &Self::Type, _id: usize, pspec: &ParamSpec) -> Value {
|
||||
match pspec.name() {
|
||||
"id" => self.data.borrow().0.id.to_value(),
|
||||
"name" => self.data.borrow().0.name.to_value(),
|
||||
"description" => self.data.borrow().0.name.to_value(),
|
||||
"description" => self.data.borrow().0.description.to_value(),
|
||||
"icon" => match &self.data.borrow().0.icon {
|
||||
Some(pop_launcher::IconSource::Name(icon_name)) => {
|
||||
(pop_launcher::IconSource::Name as i32, icon_name.to_string())
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
mod imp;
|
||||
|
||||
use gdk4::glib::Object;
|
||||
use glib::ObjectExt;
|
||||
use glib::ToVariant;
|
||||
use gtk4::glib;
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
glib::wrapper! {
|
||||
pub struct ApplicationObject(ObjectSubclass<imp::ApplicationObject>);
|
||||
|
|
@ -11,8 +11,46 @@ glib::wrapper! {
|
|||
|
||||
impl ApplicationObject {
|
||||
pub fn new(application_search_result: &pop_launcher::SearchResult) -> Self {
|
||||
Object::new(&[("name", &application_search_result.name)])
|
||||
.expect("Failed to create `ApplicationObject`.")
|
||||
let self_: Self = Object::new(&[
|
||||
("id", &application_search_result.id),
|
||||
("name", &application_search_result.name),
|
||||
("description", &application_search_result.description),
|
||||
])
|
||||
.expect("Failed to create `ApplicationObject`.");
|
||||
if let Some(icon) = &application_search_result.icon {
|
||||
if let Err(e) = self_.set_property(
|
||||
"icon",
|
||||
match icon {
|
||||
pop_launcher::IconSource::Name(name) => {
|
||||
(pop_launcher::IconSource::Name as i32, name.to_string()).to_variant()
|
||||
}
|
||||
pop_launcher::IconSource::Mime(name) => {
|
||||
(pop_launcher::IconSource::Mime as i32, name.to_string()).to_variant()
|
||||
}
|
||||
},
|
||||
) {
|
||||
println!("failed to set icon property");
|
||||
dbg!(e);
|
||||
};
|
||||
}
|
||||
if let Some(icon) = &application_search_result.category_icon {
|
||||
if let Err(e) = self_.set_property(
|
||||
"categoryicon",
|
||||
match icon {
|
||||
pop_launcher::IconSource::Name(name) => {
|
||||
(pop_launcher::IconSource::Name as i32, name.to_string()).to_variant()
|
||||
}
|
||||
pop_launcher::IconSource::Mime(name) => {
|
||||
(pop_launcher::IconSource::Mime as i32, name.to_string()).to_variant()
|
||||
}
|
||||
},
|
||||
) {
|
||||
println!("failed to set category icon property");
|
||||
dbg!(e);
|
||||
};
|
||||
}
|
||||
|
||||
self_
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
58
examples/launcher/application_row/application_row.ui
Normal file
58
examples/launcher/application_row/application_row.ui
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<interface>
|
||||
<template class="ApplicationRow" parent="GtkBox">
|
||||
<property name="orientation">horizontal</property>
|
||||
<property name="spacing">12</property>
|
||||
<property name="margin-start">4</property>
|
||||
<property name="margin-end">4</property>
|
||||
<property name="hexpand">true</property>
|
||||
<child>
|
||||
<object class="GtkImage" id="categoryimage">
|
||||
<property name="pixel-size">20</property>
|
||||
</object>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkImage" id="image">
|
||||
<property name="margin-top">4</property>
|
||||
<property name="margin-bottom">4</property>
|
||||
<property name="pixel-size">36</property>
|
||||
</object>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkBox">
|
||||
<property name="orientation">vertical</property>
|
||||
<property name="halign">fill</property>
|
||||
<property name="hexpand">true</property>
|
||||
<property name="margin-top">4</property>
|
||||
<property name="margin-end">4</property>
|
||||
<property name="margin-bottom">4</property>
|
||||
<child>
|
||||
<object class="GtkLabel" id="name">
|
||||
<property name="halign">start</property>
|
||||
<style>
|
||||
<class name="title-4" />
|
||||
</style>
|
||||
</object>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkLabel" id="description">
|
||||
<property name="halign">start</property>
|
||||
<property name="wrap">True</property>
|
||||
<style>
|
||||
<class name="body" />
|
||||
</style>
|
||||
</object>
|
||||
</child>
|
||||
</object>
|
||||
</child>
|
||||
<child type="end">
|
||||
<object class="GtkLabel" id="shortcut">
|
||||
<property name="halign">end</property>
|
||||
<property name="wrap">false</property>
|
||||
<style>
|
||||
<class name="body" />
|
||||
</style>
|
||||
</object>
|
||||
</child>
|
||||
</template>
|
||||
</interface>
|
||||
40
examples/launcher/application_row/imp.rs
Normal file
40
examples/launcher/application_row/imp.rs
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
use gtk::glib;
|
||||
use gtk::prelude::*;
|
||||
use gtk::subclass::prelude::*;
|
||||
use gtk4 as gtk;
|
||||
|
||||
use gtk::CompositeTemplate;
|
||||
|
||||
#[derive(Debug, Default, CompositeTemplate)]
|
||||
#[template(file = "application_row.ui")]
|
||||
pub struct ApplicationRow {
|
||||
#[template_child]
|
||||
pub name: TemplateChild<gtk::Label>,
|
||||
#[template_child]
|
||||
pub description: TemplateChild<gtk::Label>,
|
||||
#[template_child]
|
||||
pub shortcut: TemplateChild<gtk::Label>,
|
||||
#[template_child]
|
||||
pub image: TemplateChild<gtk::Image>,
|
||||
#[template_child]
|
||||
pub categoryimage: TemplateChild<gtk::Image>,
|
||||
}
|
||||
|
||||
#[glib::object_subclass]
|
||||
impl ObjectSubclass for ApplicationRow {
|
||||
const NAME: &'static str = "ApplicationRow";
|
||||
type Type = super::ApplicationRow;
|
||||
type ParentType = gtk::Box;
|
||||
|
||||
fn class_init(klass: &mut Self::Class) {
|
||||
Self::bind_template(klass);
|
||||
}
|
||||
|
||||
fn instance_init(obj: &glib::subclass::InitializingObject<Self>) {
|
||||
obj.init_template();
|
||||
}
|
||||
}
|
||||
|
||||
impl ObjectImpl for ApplicationRow {}
|
||||
impl WidgetImpl for ApplicationRow {}
|
||||
impl BoxImpl for ApplicationRow {}
|
||||
79
examples/launcher/application_row/mod.rs
Normal file
79
examples/launcher/application_row/mod.rs
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
use crate::icon_source;
|
||||
use glib::FromVariant;
|
||||
use glib::Variant;
|
||||
use gtk4 as gtk;
|
||||
mod imp;
|
||||
|
||||
use crate::ApplicationObject;
|
||||
use gtk::glib;
|
||||
use gtk::prelude::*;
|
||||
use gtk::subclass::prelude::*;
|
||||
|
||||
glib::wrapper! {
|
||||
pub struct ApplicationRow(ObjectSubclass<imp::ApplicationRow>)
|
||||
@extends gtk::Widget, gtk::Box;
|
||||
}
|
||||
|
||||
impl Default for ApplicationRow {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl ApplicationRow {
|
||||
pub fn new() -> Self {
|
||||
glib::Object::new(&[]).expect("Failed to create ApplicationRow")
|
||||
}
|
||||
|
||||
pub fn set_app_info(&self, app_obj: ApplicationObject) {
|
||||
let self_ = imp::ApplicationRow::from_instance(self);
|
||||
|
||||
if let Ok(name) = app_obj.property("name") {
|
||||
self_.name.set_text(
|
||||
&name
|
||||
.get::<String>()
|
||||
.expect("Property name needs to be a String."),
|
||||
);
|
||||
}
|
||||
if let Ok(desc) = app_obj.property("description") {
|
||||
self_.description.set_text(
|
||||
&desc
|
||||
.get::<String>()
|
||||
.expect("Property description needs to be a String."),
|
||||
);
|
||||
}
|
||||
if let Ok(icon) = app_obj.property("icon") {
|
||||
if let Ok(icon) = icon.get::<Variant>() {
|
||||
let icon = match <(i32, String)>::from_variant(&icon) {
|
||||
Some((i_type, name)) if i_type == pop_launcher::IconSource::Name as i32 => {
|
||||
Some(pop_launcher::IconSource::Name(name.into()))
|
||||
}
|
||||
Some((i_type, name)) if i_type == pop_launcher::IconSource::Mime as i32 => {
|
||||
Some(pop_launcher::IconSource::Mime(name.into()))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
icon_source(&self_.image, &icon);
|
||||
}
|
||||
}
|
||||
if let Ok(icon) = app_obj.property("categoryicon") {
|
||||
if let Ok(icon) = icon.get::<Variant>() {
|
||||
let icon = match <(i32, String)>::from_variant(&icon) {
|
||||
Some((i_type, name)) if i_type == pop_launcher::IconSource::Name as i32 => {
|
||||
Some(pop_launcher::IconSource::Name(name.into()))
|
||||
}
|
||||
Some((i_type, name)) if i_type == pop_launcher::IconSource::Mime as i32 => {
|
||||
Some(pop_launcher::IconSource::Mime(name.into()))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
icon_source(&self_.categoryimage, &icon);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_shortcut(&self, indx: u32) {
|
||||
let self_ = imp::ApplicationRow::from_instance(self);
|
||||
self_.shortcut.set_text(&format!("Ctrl + {}", indx));
|
||||
}
|
||||
}
|
||||
|
|
@ -1,40 +0,0 @@
|
|||
?xml version="1.0" encoding="UTF-8"?>
|
||||
<interface>
|
||||
<template class="ApplicationRow" parent="GtkBox">
|
||||
<property name="orientation">horizontal</property>
|
||||
<property name="spacing">12</property>
|
||||
<child>
|
||||
<object class="GtkImage" id="image">
|
||||
<property name="margin-top">6</property>
|
||||
<property name="margin-bottom">6</property>
|
||||
<property name="margin-start">6</property>
|
||||
<property name="margin-end">6</property>
|
||||
<property name="pixel-size">48</property>
|
||||
</object>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkBox">
|
||||
<property name="orientation">vertical</property>
|
||||
<property name="margin-top">6</property>
|
||||
<property name="margin-bottom">6</property>
|
||||
<child>
|
||||
<object class="GtkLabel" id="name">
|
||||
<property name="halign">start</property>
|
||||
<style>
|
||||
<class name="title-4" />
|
||||
</style>
|
||||
</object>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkLabel" id="description">
|
||||
<property name="halign">start</property>
|
||||
<property name="wrap">True</property>
|
||||
<style>
|
||||
<class name="body" />
|
||||
</style>
|
||||
</object>
|
||||
</child>
|
||||
</object>
|
||||
</child>
|
||||
</template>
|
||||
</interface>
|
||||
|
|
@ -1,18 +1,22 @@
|
|||
mod application_object;
|
||||
mod application_row;
|
||||
use gio::DesktopAppInfo;
|
||||
use gtk4 as gtk;
|
||||
use gtk4::SliceListModel;
|
||||
|
||||
use cascade::cascade;
|
||||
use gtk::gio;
|
||||
use gtk::prelude::*;
|
||||
use gtk::{
|
||||
glib, Application, ApplicationWindow, Label, ListView, PolicyType, ScrolledWindow,
|
||||
SignalListItemFactory, SingleSelection,
|
||||
};
|
||||
use gtk::{glib, ListView, SignalListItemFactory, SingleSelection};
|
||||
use libcosmic::x;
|
||||
use std::{cell::RefCell, rc::Rc};
|
||||
use pop_launcher_service::IpcClient;
|
||||
use postage::mpsc::Sender;
|
||||
use postage::prelude::*;
|
||||
|
||||
use self::application_object::ApplicationObject;
|
||||
use self::ipc::LauncherIpc;
|
||||
mod ipc;
|
||||
use self::application_row::ApplicationRow;
|
||||
|
||||
const NUM_LAUNCHER_ITEMS: u8 = 10;
|
||||
|
||||
fn icon_source(icon: >k::Image, source: &Option<pop_launcher::IconSource>) {
|
||||
match source {
|
||||
|
|
@ -28,22 +32,50 @@ fn icon_source(icon: >k::Image, source: &Option<pop_launcher::IconSource>) {
|
|||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let launcher = Rc::new(RefCell::new(
|
||||
LauncherIpc::new().expect("failed to connect to launcher service"),
|
||||
));
|
||||
enum Event {
|
||||
Response(pop_launcher::Response),
|
||||
Search(String),
|
||||
Activate(u32),
|
||||
}
|
||||
|
||||
fn spawn_launcher(mut tx: Sender<Event>) -> IpcClient {
|
||||
let (launcher, responses) =
|
||||
pop_launcher_service::IpcClient::new().expect("failed to connect to launcher service");
|
||||
|
||||
glib::MainContext::default().spawn_local(async move {
|
||||
use futures::StreamExt;
|
||||
futures::pin_mut!(responses);
|
||||
while let Some(event) = responses.next().await {
|
||||
let _ = tx.send(Event::Response(event)).await;
|
||||
}
|
||||
});
|
||||
|
||||
launcher
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let app = gtk::Application::builder()
|
||||
.application_id("com.system76.Launcher")
|
||||
.build();
|
||||
|
||||
app.connect_activate(move |app| {
|
||||
let (tx, mut rx) = postage::mpsc::channel(1);
|
||||
let mut launcher = spawn_launcher(tx.clone());
|
||||
|
||||
//quit shortcut
|
||||
app.set_accels_for_action("win.quit", &["<primary>W", "Escape"]);
|
||||
//launch shortcuts
|
||||
for i in 1..10 {
|
||||
app.set_accels_for_action(&format!("win.launch{}", i), &[&format!("<primary>{}", i)]);
|
||||
}
|
||||
|
||||
let window = gtk::ApplicationWindow::builder()
|
||||
.application(app)
|
||||
.decorated(false)
|
||||
.default_width(480)
|
||||
.default_width(600)
|
||||
.default_height(440)
|
||||
.title("Launcher")
|
||||
.resizable(false)
|
||||
.build();
|
||||
|
||||
let vbox = gtk::Box::new(gtk::Orientation::Vertical, 16);
|
||||
|
|
@ -57,14 +89,11 @@ fn main() {
|
|||
search.set_placeholder_text(Some(" Type to search apps, or type '?' for more options."));
|
||||
vbox.append(&search);
|
||||
|
||||
let listbox = gtk::ListBox::new();
|
||||
//vbox.append(&listbox);
|
||||
|
||||
let model = gio::ListStore::new(ApplicationObject::static_type());
|
||||
let factory = SignalListItemFactory::new();
|
||||
factory.connect_setup(move |_, list_item| {
|
||||
let label = Label::new(None);
|
||||
list_item.set_child(Some(&label))
|
||||
let row = ApplicationRow::new();
|
||||
list_item.set_child(Some(&row))
|
||||
});
|
||||
factory.connect_bind(move |_, list_item| {
|
||||
let application_object = list_item
|
||||
|
|
@ -72,98 +101,85 @@ fn main() {
|
|||
.expect("The item has to exist.")
|
||||
.downcast::<ApplicationObject>()
|
||||
.expect("The item has to be an `ApplicationObject`");
|
||||
let name = application_object
|
||||
.property("name")
|
||||
.expect("Property name of the wrong type or does not exist!")
|
||||
.get::<String>()
|
||||
.expect("Property name needs to be a String.");
|
||||
let label = list_item
|
||||
let row = list_item
|
||||
.child()
|
||||
.expect("The child has to exist.")
|
||||
.downcast::<Label>()
|
||||
.expect("The child has to be a `label`");
|
||||
label.set_label(&name);
|
||||
.expect("The list item child needs to exist.")
|
||||
.downcast::<ApplicationRow>()
|
||||
.expect("The list item type needs to be `ApplicationRow`");
|
||||
if list_item.position() < 9 {
|
||||
row.set_shortcut(list_item.position() + 1);
|
||||
}
|
||||
|
||||
row.set_app_info(application_object);
|
||||
});
|
||||
let selection_model = SingleSelection::new(Some(&model));
|
||||
let slice_model = SliceListModel::new(Some(&model), 0, NUM_LAUNCHER_ITEMS.into());
|
||||
let selection_model = SingleSelection::new(Some(&slice_model));
|
||||
let list_view = ListView::new(Some(&selection_model), Some(&factory));
|
||||
vbox.append(&list_view);
|
||||
let scroll = cascade! {
|
||||
gtk::ScrolledWindow::new();
|
||||
..set_min_content_height(400);
|
||||
..set_max_content_height(700);
|
||||
..set_propagate_natural_height(true);
|
||||
..set_vexpand(true);
|
||||
..set_policy(gtk::PolicyType::Never, gtk::PolicyType::Automatic);
|
||||
};
|
||||
scroll.set_child(Some(&list_view));
|
||||
vbox.append(&scroll);
|
||||
|
||||
for i in 1..10 {
|
||||
let action_launchi = gio::SimpleAction::new(&format!("launch{}", i), None);
|
||||
window.add_action(&action_launchi);
|
||||
action_launchi.connect_activate(
|
||||
glib::clone!(@weak list_view, @strong tx => move |_action, _parameter| {
|
||||
println!("acitvating... {}", i);
|
||||
let model = list_view.model().unwrap();
|
||||
let app_info = model.item(i - 1);
|
||||
if app_info.is_none() {
|
||||
println!("oops no app for this row...");
|
||||
return;
|
||||
}
|
||||
if let Ok(id)= app_info.unwrap().property("id") {
|
||||
let id = id.get::<u32>().expect("App ID must be u32");
|
||||
let mut tx = tx.clone();
|
||||
|
||||
glib::MainContext::default().spawn_local(async move {
|
||||
let _ = tx.send(Event::Activate(id)).await;
|
||||
});
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
list_view.connect_activate(glib::clone!(@strong tx => move |list_view, i| {
|
||||
println!("acitvating... {}", i + 1);
|
||||
let model = list_view.model().unwrap();
|
||||
let app_info = model.item(i);
|
||||
if app_info.is_none() {
|
||||
println!("oops no app for this row...");
|
||||
return;
|
||||
}
|
||||
if let Ok(id)= app_info.unwrap().property("id") {
|
||||
let id = id.get::<u32>().expect("App ID must be u32");
|
||||
let mut tx = tx.clone();
|
||||
|
||||
glib::MainContext::default().spawn_local(async move {
|
||||
let _ = tx.send(Event::Activate(id)).await;
|
||||
});
|
||||
}
|
||||
}));
|
||||
|
||||
{
|
||||
let launcher = launcher.clone();
|
||||
let search_changed = move |search: >k::Entry| {
|
||||
let model_len = model.n_items();
|
||||
//TODO: is this the best way to clear a listbox?
|
||||
//while let Some(child) = listbox.last_child() {
|
||||
// listbox.remove(&child);
|
||||
//}
|
||||
let search_changed = glib::clone!(@strong tx => move |search: >k::Entry| {
|
||||
let search = search.text().to_string();
|
||||
|
||||
let response_res = launcher
|
||||
.borrow_mut()
|
||||
.request(pop_launcher::Request::Search(search.text().to_string()));
|
||||
|
||||
println!("{:#?}", response_res);
|
||||
|
||||
let num_items = 9;
|
||||
|
||||
if let Ok(pop_launcher::Response::Update(results)) = response_res {
|
||||
let new_results: Vec<glib::Object> = results
|
||||
[0..std::cmp::min(results.len(), num_items)]
|
||||
.iter()
|
||||
.map(|result| ApplicationObject::new(result).upcast())
|
||||
.collect();
|
||||
model.splice(0, model_len, &new_results[..]);
|
||||
// for (i, result) in results[0..std::cmp::min(results.len(), num_items)]
|
||||
// .iter()
|
||||
// .enumerate()
|
||||
// {
|
||||
// dbg!(result);
|
||||
// // Limit to 9 results
|
||||
// // if i >= 9 {
|
||||
// // break 'result_loop;
|
||||
// // }
|
||||
|
||||
// let row = gtk::ListBoxRow::new();
|
||||
// listbox.append(&row);
|
||||
|
||||
// // Select first row
|
||||
// if i == 0 {
|
||||
// listbox.select_row(Some(&row));
|
||||
// }
|
||||
|
||||
// let hbox = gtk::Box::new(gtk::Orientation::Horizontal, 8);
|
||||
// hbox.set_margin_start(8);
|
||||
// hbox.set_margin_end(8);
|
||||
// hbox.set_margin_top(8);
|
||||
// hbox.set_margin_bottom(8);
|
||||
// row.set_child(Some(&hbox));
|
||||
|
||||
// let category_icon = gtk::Image::new();
|
||||
// category_icon.set_pixel_size(16);
|
||||
// icon_source(&category_icon, &result.category_icon);
|
||||
// hbox.append(&category_icon);
|
||||
|
||||
// let icon = gtk::Image::new();
|
||||
// icon.set_pixel_size(32);
|
||||
// icon_source(&icon, &result.icon);
|
||||
// hbox.append(&icon);
|
||||
|
||||
// let labels = gtk::Box::new(gtk::Orientation::Vertical, 4);
|
||||
// hbox.append(&labels);
|
||||
|
||||
// let name = gtk::Label::new(Some(&result.name));
|
||||
// name.set_halign(gtk::Align::Start);
|
||||
// labels.append(&name);
|
||||
|
||||
// let description = gtk::Label::new(Some(&result.description));
|
||||
// description.set_halign(gtk::Align::Start);
|
||||
// labels.append(&description);
|
||||
// }
|
||||
}
|
||||
};
|
||||
|
||||
search.connect_changed(search_changed.clone());
|
||||
let mut tx = tx.clone();
|
||||
glib::MainContext::default().spawn_local(async move {
|
||||
let _ = tx.send(Event::Search(search)).await;
|
||||
});
|
||||
});
|
||||
|
||||
search_changed(&search);
|
||||
search.connect_changed(search_changed);
|
||||
}
|
||||
|
||||
// Setting the window to dialog type must happen between realize and show. Dialog windows
|
||||
|
|
@ -183,8 +199,54 @@ fn main() {
|
|||
println!("failed to get X11 window");
|
||||
}
|
||||
});
|
||||
let action_quit = gio::SimpleAction::new("quit", None);
|
||||
action_quit.connect_activate(glib::clone!(@weak window => move |_, _| {
|
||||
window.close();
|
||||
}));
|
||||
window.add_action(&action_quit);
|
||||
|
||||
window.connect_is_active_notify(|win| {
|
||||
if !win.is_active() {
|
||||
win.close();
|
||||
}
|
||||
});
|
||||
|
||||
window.show();
|
||||
glib::MainContext::default().spawn_local(async move {
|
||||
while let Some(event) = rx.recv().await {
|
||||
match event {
|
||||
Event::Search(search) => {
|
||||
let _ = launcher.send(pop_launcher::Request::Search(search)).await;
|
||||
}
|
||||
Event::Activate(index) => {
|
||||
let _ = launcher.send(pop_launcher::Request::Activate(index)).await;
|
||||
}
|
||||
|
||||
Event::Response(event) => {
|
||||
if let pop_launcher::Response::Update(results) = event {
|
||||
let model_len = model.n_items();
|
||||
dbg!(&results);
|
||||
let new_results: Vec<glib::Object> = results
|
||||
[0..std::cmp::min(results.len(), NUM_LAUNCHER_ITEMS.into())]
|
||||
.iter()
|
||||
.map(|result| ApplicationObject::new(result).upcast())
|
||||
.collect();
|
||||
model.splice(0, model_len, &new_results[..]);
|
||||
} else if let pop_launcher::Response::DesktopEntry {
|
||||
path,
|
||||
gpu_preference: _gpu_preference, // TODO use GPU preference when launching app
|
||||
} = event
|
||||
{
|
||||
let app_info =
|
||||
DesktopAppInfo::new(&path.file_name().expect("desktop entry path needs to be a valid filename").to_string_lossy())
|
||||
.expect("failed to create a Desktop App info for launching the application.");
|
||||
app_info
|
||||
.launch(&[], Some(&window.display().app_launch_context().clone())).expect("failed to launch the application.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
app.run();
|
||||
|
|
|
|||
56
examples/launcher/window/imp.rs
Normal file
56
examples/launcher/window/imp.rs
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
use gtk4 as gtk;
|
||||
|
||||
use glib::subclass::InitializingObject;
|
||||
use gtk::prelude::*;
|
||||
use gtk::subclass::prelude::*;
|
||||
use gtk::{gio, glib};
|
||||
use gtk::{CompositeTemplate, Entry, ListView};
|
||||
use once_cell::sync::OnceCell;
|
||||
|
||||
// Object holding the state
|
||||
#[derive(CompositeTemplate, Default)]
|
||||
#[template(file = "window.ui")]
|
||||
pub struct Window {
|
||||
#[template_child]
|
||||
pub entry: TemplateChild<Entry>,
|
||||
#[template_child]
|
||||
pub list_view: TemplateChild<ListView>,
|
||||
pub model: OnceCell<gio::ListStore>,
|
||||
}
|
||||
|
||||
// The central trait for subclassing a GObject
|
||||
#[glib::object_subclass]
|
||||
impl ObjectSubclass for Window {
|
||||
// `NAME` needs to match `class` attribute of template
|
||||
const NAME: &'static str = "LauncherWindow";
|
||||
type Type = super::Window;
|
||||
type ParentType = gtk::ApplicationWindow;
|
||||
|
||||
fn class_init(klass: &mut Self::Class) {
|
||||
Self::bind_template(klass);
|
||||
}
|
||||
|
||||
fn instance_init(obj: &InitializingObject<Self>) {
|
||||
obj.init_template();
|
||||
}
|
||||
}
|
||||
// Trait shared by all GObjects
|
||||
impl ObjectImpl for Window {
|
||||
fn constructed(&self, obj: &Self::Type) {
|
||||
// Call "constructed" on parent
|
||||
self.parent_constructed(obj);
|
||||
|
||||
// Setup
|
||||
obj.setup_model();
|
||||
obj.setup_callbacks();
|
||||
obj.setup_factory();
|
||||
}
|
||||
}
|
||||
// Trait shared by all widgets
|
||||
impl WidgetImpl for Window {}
|
||||
|
||||
// Trait shared by all windows
|
||||
impl WindowImpl for Window {}
|
||||
|
||||
// Trait shared by all application
|
||||
impl ApplicationWindowImpl for Window {}
|
||||
245
examples/launcher/window/mod.rs
Normal file
245
examples/launcher/window/mod.rs
Normal file
|
|
@ -0,0 +1,245 @@
|
|||
mod imp;
|
||||
use gtk4 as gtk;
|
||||
|
||||
use crate::application_row::ApplicationRow;
|
||||
use glib::Object;
|
||||
use gtk::prelude::*;
|
||||
use gtk::subclass::prelude::*;
|
||||
use gtk::{gio, glib};
|
||||
use gtk::{Application, SignalListItemFactory};
|
||||
|
||||
use libcosmic::x;
|
||||
|
||||
glib::wrapper! {
|
||||
pub struct Window(ObjectSubclass<imp::Window>)
|
||||
@extends gtk::ApplicationWindow, gtk::Window, gtk::Widget,
|
||||
@implements gio::ActionGroup, gio::ActionMap, gtk::Accessible, gtk::Buildable,
|
||||
gtk::ConstraintTarget, gtk::Native, gtk::Root, gtk::ShortcutManager;
|
||||
}
|
||||
|
||||
impl Window {
|
||||
pub fn new(app: &Application) -> Self {
|
||||
//quit shortcut
|
||||
app.set_accels_for_action("win.quit", &["<primary>W", "Escape"]);
|
||||
//launch shortcuts
|
||||
for i in 1..10 {
|
||||
app.set_accels_for_action(&format!("win.launch{}", i), &[&format!("<primary>{}", i)]);
|
||||
}
|
||||
Object::new(&[("application", app)]).expect("Failed to create `Window`.")
|
||||
}
|
||||
|
||||
fn model(&self) -> &gio::ListStore {
|
||||
// Get state
|
||||
let imp = imp::Window::from_instance(self);
|
||||
imp.model.get().expect("Could not get model")
|
||||
}
|
||||
|
||||
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);
|
||||
});
|
||||
|
||||
// Get state and set model
|
||||
let imp = imp::Window::from_instance(self);
|
||||
imp.model.set(model.clone()).expect("Could not set model");
|
||||
|
||||
// A sorter used to sort AppInfo in the model by their name
|
||||
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();
|
||||
|
||||
app_info1
|
||||
.name()
|
||||
.to_lowercase()
|
||||
.cmp(&app_info2.name().to_lowercase())
|
||||
.into()
|
||||
});
|
||||
let filter = gtk::CustomFilter::new(|_obj| true);
|
||||
let filter_model = gtk::FilterListModel::new(Some(&model), Some(filter).as_ref());
|
||||
let sorted_model = gtk::SortListModel::new(Some(&filter_model), Some(&sorter));
|
||||
let slice_model = gtk::SliceListModel::new(Some(&sorted_model), 0, 9);
|
||||
let selection_model = gtk::SingleSelection::new(Some(&slice_model));
|
||||
|
||||
// Wrap model with selection and pass it to the list view
|
||||
imp.list_view.set_model(Some(&selection_model));
|
||||
}
|
||||
|
||||
fn setup_callbacks(&self) {
|
||||
// Get state
|
||||
let imp = imp::Window::from_instance(self);
|
||||
let window = self.clone().upcast::<gtk::Window>();
|
||||
let list_view = &imp.list_view;
|
||||
let sorted_model = list_view
|
||||
.model()
|
||||
.expect("List view missing selection model")
|
||||
.downcast::<gtk::SingleSelection>()
|
||||
.expect("could not downcast listview model to single selection model")
|
||||
.model()
|
||||
.downcast::<gtk::SliceListModel>()
|
||||
.expect("could not downcast single selection model to slice list model.")
|
||||
.model()
|
||||
.expect("sorted list model is missing from slice list model")
|
||||
.downcast::<gtk::SortListModel>()
|
||||
.expect("sorted list model could not be downcast");
|
||||
let filter_model = sorted_model
|
||||
.model()
|
||||
.expect("missing model for sort list model.")
|
||||
.downcast::<gtk::FilterListModel>()
|
||||
.expect("could not downcast sort list model to filter list model");
|
||||
|
||||
let entry = &imp.entry;
|
||||
let lv = list_view.get();
|
||||
for i in 1..10 {
|
||||
let action_launchi = gio::SimpleAction::new(&format!("launch{}", i), None);
|
||||
self.add_action(&action_launchi);
|
||||
let context = list_view.display().app_launch_context().clone();
|
||||
let parent_window = list_view.root().unwrap().downcast::<gtk::Window>().unwrap();
|
||||
action_launchi.connect_activate(glib::clone!(@weak lv => move |_action, _parameter| {
|
||||
let model = lv.model().unwrap();
|
||||
let app_info = model.item(i - 1);
|
||||
if app_info.is_none() {
|
||||
println!("oops no app for this row...");
|
||||
return;
|
||||
}
|
||||
let app_info = app_info.unwrap().downcast::<gio::AppInfo>().unwrap();
|
||||
if let Err(err) = app_info.launch(&[], Some(&context)) {
|
||||
|
||||
gtk::MessageDialog::builder()
|
||||
.text(&format!("Failed to start {}", app_info.name()))
|
||||
.secondary_text(&err.to_string())
|
||||
.message_type(gtk::MessageType::Error)
|
||||
.modal(true)
|
||||
.transient_for(&parent_window)
|
||||
.build()
|
||||
.show();
|
||||
|
||||
println!("oops launch failed")
|
||||
}
|
||||
println!("{}", i-1);
|
||||
}));
|
||||
}
|
||||
|
||||
// Launch the application when an item of the list is activated
|
||||
list_view.connect_activate(move |list_view, position| {
|
||||
let model = list_view.model().unwrap();
|
||||
let app_info = model
|
||||
.item(position)
|
||||
.unwrap()
|
||||
.downcast::<gio::AppInfo>()
|
||||
.unwrap();
|
||||
|
||||
let context = list_view.display().app_launch_context();
|
||||
if let Err(err) = app_info.launch(&[], Some(&context)) {
|
||||
let parent_window = list_view.root().unwrap().downcast::<gtk::Window>().unwrap();
|
||||
|
||||
gtk::MessageDialog::builder()
|
||||
.text(&format!("Failed to start {}", app_info.name()))
|
||||
.secondary_text(&err.to_string())
|
||||
.message_type(gtk::MessageType::Error)
|
||||
.modal(true)
|
||||
.transient_for(&parent_window)
|
||||
.build()
|
||||
.show();
|
||||
}
|
||||
});
|
||||
|
||||
entry.connect_changed(
|
||||
glib::clone!(@weak filter_model, @weak sorted_model => move |search: >k::Entry| {
|
||||
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>()
|
||||
.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();
|
||||
if search_text == "" {
|
||||
return app_info1
|
||||
.name()
|
||||
.to_lowercase()
|
||||
.cmp(&app_info2.name().to_lowercase())
|
||||
.into();
|
||||
}
|
||||
|
||||
let i_1 = app_info1.name().to_lowercase().find(&search_text);
|
||||
let i_2 = app_info2.name().to_lowercase().find(&search_text);
|
||||
match (i_1, i_2) {
|
||||
(Some(i_1), Some(i_2)) => i_1.cmp(&i_2).into(),
|
||||
(Some(_), None) => std::cmp::Ordering::Less.into(),
|
||||
(None, Some(_)) => std::cmp::Ordering::Greater.into(),
|
||||
_ => app_info1
|
||||
.name()
|
||||
.to_lowercase()
|
||||
.cmp(&app_info2.name().to_lowercase())
|
||||
.into()
|
||||
}
|
||||
});
|
||||
|
||||
filter_model.set_filter(Some(new_filter).as_ref());
|
||||
sorted_model.set_sorter(Some(new_sorter).as_ref());
|
||||
}),
|
||||
);
|
||||
|
||||
window.connect_realize(move |window| {
|
||||
if let Some((display, surface)) = x::get_window_x11(window) {
|
||||
unsafe {
|
||||
x::change_property(
|
||||
&display,
|
||||
&surface,
|
||||
"_NET_WM_WINDOW_TYPE",
|
||||
x::PropMode::Replace,
|
||||
&[x::Atom::new(&display, "_NET_WM_WINDOW_TYPE_DIALOG").unwrap()],
|
||||
);
|
||||
}
|
||||
} else {
|
||||
println!("failed to get X11 window");
|
||||
}
|
||||
});
|
||||
|
||||
let action_quit = gio::SimpleAction::new("quit", None);
|
||||
action_quit.connect_activate(glib::clone!(@weak window => move |_, _| {
|
||||
window.close();
|
||||
}));
|
||||
self.add_action(&action_quit);
|
||||
|
||||
window.connect_is_active_notify(|win| {
|
||||
if !win.is_active() {
|
||||
win.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn setup_factory(&self) {
|
||||
let factory = SignalListItemFactory::new();
|
||||
factory.connect_setup(move |_factory, item| {
|
||||
let row = ApplicationRow::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, list_item| {
|
||||
let app_info = list_item
|
||||
.item()
|
||||
.unwrap()
|
||||
.downcast::<gio::AppInfo>()
|
||||
.unwrap();
|
||||
|
||||
let child = list_item
|
||||
.child()
|
||||
.unwrap()
|
||||
.downcast::<ApplicationRow>()
|
||||
.unwrap();
|
||||
child.set_app_info(&app_info);
|
||||
if list_item.position() < 9 {
|
||||
child.set_shortcut(list_item.position() + 1);
|
||||
}
|
||||
});
|
||||
// Set the factory of the list view
|
||||
let imp = imp::Window::from_instance(self);
|
||||
imp.list_view.set_factory(Some(&factory));
|
||||
}
|
||||
}
|
||||
32
examples/launcher/window/window.ui
Normal file
32
examples/launcher/window/window.ui
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<interface>
|
||||
<template class="LauncherWindow" parent="GtkApplicationWindow">
|
||||
<property name="width-request">600</property>
|
||||
<property name="title">Gtk Pop Launcher</property>
|
||||
<property name="decorated">false</property>
|
||||
<child>
|
||||
<object class="GtkBox">
|
||||
<property name="orientation">vertical</property>
|
||||
<property name="margin-top">12</property>
|
||||
<property name="margin-bottom">12</property>
|
||||
<property name="margin-start">12</property>
|
||||
<property name="margin-end">12</property>
|
||||
<child>
|
||||
<object class="GtkEntry" id="entry">
|
||||
<property name="margin-bottom">12</property>
|
||||
</object>
|
||||
</child>
|
||||
<child>
|
||||
<object class="GtkScrolledWindow">
|
||||
<property name="hscrollbar-policy">never</property>
|
||||
<property name="min-content-height">500</property>
|
||||
<property name="vexpand">true</property>
|
||||
<child>
|
||||
<object class="GtkListView" id="list_view"/>
|
||||
</child>
|
||||
</object>
|
||||
</child>
|
||||
</object>
|
||||
</child>
|
||||
</template>
|
||||
</interface>
|
||||
Loading…
Add table
Add a link
Reference in a new issue