use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use gtk::prelude::*;
use gtk::{gio, glib};
use prism_core::menu::{ActionRole, AlertSpec, MenuItemSpec, MenuSpec};
use prism_core::surfaces::PlatformRequest;
use prism_core::{
Accuracy, Capabilities, DeviceCall, DeviceError, DeviceEvent, DeviceValue, Permission,
PermissionState, PickedFile, PlatformServices, UiEvent,
};
use crate::imp;
use crate::security::SecretOp;
const GATED: &str = "\u{1}prism-gated\u{1}";
const GEOCLUE: &str = "org.freedesktop.GeoClue2";
pub(crate) struct LinuxServices {
pub app: gtk::Application,
pub window: gtk::ApplicationWindow,
caps: Capabilities,
location_streams: Rc<RefCell<HashMap<u64, String>>>,
pending: HashMap<String, glib::SourceId>,
pub background: Vec<(String, std::time::Instant, std::time::Duration)>,
loopback: crate::security::Loopback,
data_dir: std::path::PathBuf,
}
fn reply(id: u64, result: Result<DeviceValue, DeviceError>) {
glib::idle_add_local_once(move || imp::device_reply(id, result));
}
fn event(id: u64, e: DeviceEvent) {
glib::idle_add_local_once(move || imp::device_event(id, e));
}
fn reveal(path: &std::path::Path) {
let uri = gio::File::for_path(path).uri().to_string();
let folder = path
.parent()
.map(|p| gio::File::for_path(p).uri().to_string());
let open_folder = move || {
if let Some(folder) = &folder {
let _ = gio::AppInfo::launch_default_for_uri(folder, None::<&gio::AppLaunchContext>);
}
};
let Ok(bus) = gio::bus_get_sync(gio::BusType::Session, None::<&gio::Cancellable>) else {
return open_folder();
};
bus.call(
Some("org.freedesktop.FileManager1"),
"/org/freedesktop/FileManager1",
"org.freedesktop.FileManager1",
"ShowItems",
Some(&(vec![uri], "").to_variant()),
None,
gio::DBusCallFlags::NONE,
5000,
None::<&gio::Cancellable>,
move |r| {
if r.is_err() {
open_folder();
}
},
);
}
fn system_bus() -> Option<gio::DBusConnection> {
gio::bus_get_sync(gio::BusType::System, None::<&gio::Cancellable>).ok()
}
impl LinuxServices {
pub fn new(
app: gtk::Application,
window: gtk::ApplicationWindow,
data_dir: std::path::PathBuf,
) -> Self {
let session = gio::bus_get_sync(gio::BusType::Session, None::<&gio::Cancellable>).is_ok();
let geoclue = system_bus().is_some_and(|bus| {
bus.call_sync(
Some("org.freedesktop.DBus"),
"/org/freedesktop/DBus",
"org.freedesktop.DBus",
"ListActivatableNames",
None,
Some(glib::VariantTy::new("(as)").expect("type")),
gio::DBusCallFlags::NONE,
-1,
None::<&gio::Cancellable>,
)
.ok()
.and_then(|v| v.child_value(0).get::<Vec<String>>())
.is_some_and(|names| names.iter().any(|n| n == GEOCLUE))
});
let (secrets, biometry) = crate::security::capabilities();
LinuxServices {
caps: Capabilities {
car: false,
notifications: session,
app_menu: true,
tray: session,
location: geoclue,
photos: true,
clipboard: true,
secure_storage: secrets,
biometry,
device_auth: biometry.is_biometric(),
web_auth: true,
push: crate::push::distributor().map(|_| prism_core::PushService::UnifiedPush),
drop_files: true,
drag_and_drop: true,
..Default::default()
},
data_dir,
app,
window,
location_streams: Rc::new(RefCell::new(HashMap::new())),
pending: HashMap::new(),
background: Vec::new(),
loopback: Default::default(),
}
}
fn device(&mut self, id: u64, call: DeviceCall) {
match call {
DeviceCall::RequestPermission(Permission::Location | Permission::LocationAlways)
if self.caps.location =>
{
let desktop_id = self.desktop_id();
glib::MainContext::default().spawn_local(async move {
let state = match geoclue::start_client(&desktop_id, 4).await {
Ok((bus, path)) => {
geoclue::stop(&bus, &path).await;
PermissionState::Granted
}
Err("denied") => PermissionState::Denied,
Err(_) => PermissionState::Unavailable,
};
reply(id, Ok(DeviceValue::Permission(state)));
});
}
DeviceCall::PermissionStatus(p) | DeviceCall::RequestPermission(p) => {
let state = match p {
Permission::Location | Permission::LocationAlways if self.caps.location => {
PermissionState::NotDetermined
}
Permission::Notifications if self.caps.notifications => {
PermissionState::Granted
}
Permission::Photos => PermissionState::Granted,
_ => PermissionState::Unavailable,
};
reply(id, Ok(DeviceValue::Permission(state)));
}
DeviceCall::CurrentLocation(a) => self.locate(id, a, false),
DeviceCall::WatchLocation(a) => self.locate(id, a, true),
DeviceCall::StopWatch => {
if let Some(path) = self.location_streams.borrow_mut().remove(&id)
&& let Some(bus) = system_bus()
{
glib::MainContext::default()
.spawn_local(async move { geoclue::stop(&bus, &path).await });
}
}
DeviceCall::PickImages(o) => {
if o.camera {
return reply(id, Err(DeviceError::from_message("unavailable")));
}
self.pick_images(id, o.limit);
}
DeviceCall::PickFiles(o) => self.pick_files(id, o),
DeviceCall::PickFolder(o) => self.pick_folder(id, o),
DeviceCall::SaveFile(f) => self.save_file(id, f),
DeviceCall::RevealPath(p) => reveal(&p),
DeviceCall::ReadClipboard => {
let clipboard = self.window.clipboard();
clipboard.read_text_async(None::<&gio::Cancellable>, move |r| {
let text = r.ok().flatten().map(|t| t.to_string());
reply(id, Ok(DeviceValue::Text(text)));
});
}
DeviceCall::CopyText(t) => {
self.window.clipboard().set_text(&t);
reply(id, Ok(DeviceValue::Done));
}
DeviceCall::ReadClipboardItem => {
let clipboard = self.window.clipboard();
glib::MainContext::default().spawn_local(async move {
let item = read_clipboard_item(&clipboard).await;
reply(id, Ok(DeviceValue::Clipboard(item)));
});
}
DeviceCall::WriteClipboard(item) => {
write_clipboard_item(&self.window.clipboard(), &item);
reply(id, Ok(DeviceValue::Done));
}
DeviceCall::OpenUrl(url) | DeviceCall::OpenUrlIn(url, _) => {
let ok = gio::AppInfo::launch_default_for_uri(&url, None::<&gio::AppLaunchContext>);
reply(
id,
ok.map(|_| DeviceValue::Done)
.map_err(|e| DeviceError::from_message(&e.to_string())),
);
}
DeviceCall::WatchMotion(_) => event(
id,
DeviceEvent::Error(DeviceError::from_message("unavailable")),
),
DeviceCall::Haptic(_)
| DeviceCall::Share(_)
| DeviceCall::SignInWithApple(_)
| DeviceCall::WebAuthn(_) => reply(id, Err(DeviceError::from_message("unavailable"))),
DeviceCall::SecureGet { key, prompt, .. } => {
self.secret(id, key, SecretOp::Get, prompt)
}
DeviceCall::SecureSet {
key,
value,
options,
} => {
let gated = match options.app_gate(self.caps.device_auth) {
Ok(gated) => gated,
Err(e) => return reply(id, Err(e)),
};
let label = self
.window
.title()
.map(|t| t.to_string())
.unwrap_or_default();
let value = format!("{}{value}", if gated { GATED } else { "" });
self.secret(id, key, SecretOp::Set { label, value }, None)
}
DeviceCall::SecureDelete { key, .. } => self.secret(id, key, SecretOp::Delete, None),
DeviceCall::BiometryStatus => {
crate::security::biometry(move |r| imp::device_reply(id, r))
}
DeviceCall::Authenticate(r) => {
crate::security::authenticate(&self.window, r.reason, move |r| {
imp::device_reply(id, r)
})
}
DeviceCall::AuthRedirect(_) => reply(id, self.loopback.redirect()),
DeviceCall::WebAuth(r) => self
.loopback
.start(&r.url, &r.redirect, move |r| imp::device_reply(id, r)),
DeviceCall::SetCookie(_) => reply(id, Err(DeviceError::Unavailable)),
DeviceCall::Reconnect => {}
DeviceCall::RenewBrowserId => reply(id, Ok(DeviceValue::Done)),
}
}
fn secret(&mut self, id: u64, key: String, op: SecretOp, prompt: Option<String>) {
if !self.caps.secure_storage {
return reply(id, Err(DeviceError::Unavailable));
}
let window = self.window.clone();
let get = matches!(op, SecretOp::Get);
crate::security::secret(self.desktop_id(), key, op, move |r| match r {
Ok(DeviceValue::Text(Some(v))) if get && v.starts_with(GATED) => {
let value = v[GATED.len()..].to_string();
let reason = prompt
.or_else(|| window.title().map(|t| t.to_string()))
.unwrap_or_default();
crate::security::authenticate(&window, reason, move |r| {
imp::device_reply(id, r.map(|_| DeviceValue::Text(Some(value))))
});
}
r => imp::device_reply(id, r),
});
}
fn desktop_id(&self) -> String {
self.app
.application_id()
.map(|s| s.to_string())
.unwrap_or_default()
}
fn locate(&mut self, id: u64, accuracy: Accuracy, stream: bool) {
let fail = move |m: &str| {
if stream {
event(id, DeviceEvent::Error(DeviceError::from_message(m)));
} else {
reply(id, Err(DeviceError::from_message(m)));
}
};
if !self.caps.location {
return fail("unavailable");
}
let level: u32 = match accuracy {
Accuracy::Coarse => 4,
Accuracy::Balanced => 6,
Accuracy::Best => 8,
};
let desktop_id = self.desktop_id();
let streams = self.location_streams.clone();
glib::MainContext::default().spawn_local(async move {
let (bus, path) = match geoclue::create_client(&desktop_id, level).await {
Ok(c) => c,
Err(e) => return fail(e),
};
geoclue::on_location(&bus, &path, move |bus, client, location| {
if stream {
event(id, DeviceEvent::Location(location));
true
} else {
reply(id, Ok(DeviceValue::Location(location)));
let (bus, client) = (bus.clone(), client.to_string());
glib::MainContext::default()
.spawn_local(async move { geoclue::stop(&bus, &client).await });
false
}
});
if stream {
streams.borrow_mut().insert(id, path.clone());
}
if let Err(e) = geoclue::start(&bus, &path).await {
streams.borrow_mut().remove(&id);
fail(e);
}
});
}
fn pick_images(&mut self, id: u64, limit: u32) {
let chooser = gtk::FileChooserNative::new(
None,
Some(&self.window),
gtk::FileChooserAction::Open,
None,
None,
);
chooser.set_select_multiple(limit != 1);
let filter = gtk::FileFilter::new();
filter.add_mime_type("image/*");
chooser.add_filter(&filter);
let keep = chooser.clone();
chooser.connect_response(move |c, response| {
let _ = &keep;
if response != gtk::ResponseType::Accept {
return reply(id, Err(DeviceError::from_message("cancelled")));
}
let files = c.files();
let mut picked = Vec::new();
for i in 0..files.n_items() {
if limit > 0 && picked.len() as u32 >= limit {
break;
}
let Some(file) = files.item(i).and_downcast::<gio::File>() else {
continue;
};
if let Some(p) = copy_picked(&file) {
picked.push(p);
}
}
reply(id, Ok(DeviceValue::Files(picked)));
});
chooser.show();
}
fn pick_files(&mut self, id: u64, o: prism_core::PickFiles) {
let chooser = gtk::FileChooserNative::new(
None,
Some(&self.window),
gtk::FileChooserAction::Open,
None,
None,
);
chooser.set_select_multiple(o.multiple);
if !o.types.is_empty() {
let filter = gtk::FileFilter::new();
for t in &o.types {
match t.trim().strip_prefix('.') {
Some(ext) => filter.add_suffix(ext),
None => filter.add_mime_type(t.trim()),
}
}
chooser.add_filter(&filter);
}
let keep = chooser.clone();
chooser.connect_response(move |c, response| {
let _ = &keep;
if response != gtk::ResponseType::Accept {
return reply(id, Err(DeviceError::from_message("cancelled")));
}
let files = c.files();
let mut picked = Vec::new();
for i in 0..files.n_items() {
if !o.multiple && !picked.is_empty() {
break;
}
let Some(file) = files.item(i).and_downcast::<gio::File>() else {
continue;
};
if let Some(p) = copy_picked(&file) {
picked.push(p);
}
}
reply(id, Ok(DeviceValue::Files(picked)));
});
chooser.show();
}
fn pick_folder(&mut self, id: u64, o: prism_core::PickFolder) {
let chooser = gtk::FileChooserNative::new(
o.title.as_deref(),
Some(&self.window),
gtk::FileChooserAction::SelectFolder,
o.title.as_deref(),
None,
);
let keep = chooser.clone();
chooser.connect_response(move |c, response| {
let _ = &keep;
if response != gtk::ResponseType::Accept {
return reply(id, Err(DeviceError::from_message("cancelled")));
}
let Some(root) = c.file().and_then(|f| f.path()) else {
return reply(id, Err(DeviceError::Failed("not a local folder".into())));
};
glib::MainContext::default().spawn_local(async move {
match gio::spawn_blocking(move || folder_files(&root)).await {
Ok(files) => reply(id, Ok(DeviceValue::Files(files))),
Err(_) => reply(
id,
Err(DeviceError::Failed("could not read the folder".into())),
),
}
});
});
chooser.show();
}
fn save_file(&mut self, id: u64, f: prism_core::SaveFile) {
let chooser = gtk::FileChooserNative::new(
None,
Some(&self.window),
gtk::FileChooserAction::Save,
None,
None,
);
chooser.set_current_name(&f.file_name());
let keep = chooser.clone();
let file = RefCell::new(Some(f));
chooser.connect_response(move |c, response| {
let _ = &keep;
let Some(f) = file.borrow_mut().take() else {
return;
};
if response != gtk::ResponseType::Accept {
return reply(id, Err(DeviceError::from_message("cancelled")));
}
let Some(path) = c.file().and_then(|file| file.path()) else {
return reply(id, Err(DeviceError::Failed("not a local file".into())));
};
glib::MainContext::default().spawn_local(async move {
let dest = path.clone();
let mime = f.mime_type();
let written = gio::spawn_blocking(move || f.write_to(&dest)).await;
reply(
id,
match written {
Ok(Ok(size)) => Ok(DeviceValue::Files(vec![PickedFile {
name: path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default(),
path: path.to_string_lossy().into_owned(),
mime,
size,
}])),
Ok(Err(e)) => Err(DeviceError::Failed(e.to_string())),
Err(_) => Err(DeviceError::Failed("could not save the file".into())),
},
);
});
});
chooser.show();
}
fn notify(&mut self, n: prism_core::surfaces::Notification) {
if let Some(timer) = self.pending.remove(&n.id) {
timer.remove();
}
let notification = gio::Notification::new(&n.title);
let body = [n.subtitle.clone(), Some(n.body.clone())]
.into_iter()
.flatten()
.filter(|s| !s.is_empty())
.collect::<Vec<_>>()
.join("\n");
if !body.is_empty() {
notification.set_body(Some(&body));
}
let target = |action: &str, link: Option<&String>| {
(n.id.as_str(), action, link.map_or("", String::as_str)).to_variant()
};
notification.set_default_action_and_target_value(
"app.prism-notification",
Some(&target("", n.link.as_ref())),
);
for a in &n.actions {
notification.add_button_with_target_value(
&a.title,
"app.prism-notification",
Some(&target(&a.id, a.link.as_ref())),
);
}
let app = self.app.clone();
let id = n.id.clone();
match n.delay {
Some(delay) if !delay.is_zero() => {
let pending_id = id.clone();
let timer = glib::timeout_add_local_once(delay, move || {
app.send_notification(Some(&pending_id), ¬ification)
});
self.pending.insert(id, timer);
}
_ => app.send_notification(Some(&id), ¬ification),
}
}
}
async fn read_clipboard_item(clipboard: >k::gdk::Clipboard) -> prism_core::ClipboardItem {
let mut item = prism_core::ClipboardItem::new();
let formats = clipboard.formats();
let mimes: Vec<String> = formats.mime_types().iter().map(|m| m.to_string()).collect();
let base = |m: &str| {
m.split(';')
.next()
.unwrap_or("")
.trim()
.to_ascii_lowercase()
};
if mimes.iter().any(|m| base(m) == "text/plain")
&& let Ok(Some(text)) = clipboard.read_text_future().await
{
item = item.text(text.as_str());
}
if (formats.contains_type(gtk::gdk::Texture::static_type())
|| mimes.iter().any(|m| m.starts_with("image/")))
&& let Ok(Some(texture)) = clipboard.read_texture_future().await
{
item = item.image(texture.save_to_png_bytes().to_vec(), "image/png");
}
let mut seen = Vec::new();
for mime in &mimes {
let ty = base(mime);
if !ty.contains('/') || ty == "text/plain" || ty.starts_with("image/") || seen.contains(&ty)
{
continue;
}
seen.push(ty.clone());
let Ok((stream, _)) = clipboard
.read_future(&[mime.as_str()], glib::Priority::DEFAULT)
.await
else {
continue;
};
let out = gio::MemoryOutputStream::new_resizable();
let flags =
gio::OutputStreamSpliceFlags::CLOSE_SOURCE | gio::OutputStreamSpliceFlags::CLOSE_TARGET;
if out
.splice_future(&stream, flags, glib::Priority::DEFAULT)
.await
.is_ok()
{
item = item.custom(ty, out.steal_as_bytes().to_vec());
}
}
item
}
fn write_clipboard_item(clipboard: >k::gdk::Clipboard, item: &prism_core::ClipboardItem) {
use gtk::gdk::ContentProvider;
let mut providers = Vec::new();
for (ty, data) in item.entries() {
if ty == prism_core::ClipboardItem::TEXT {
providers.push(ContentProvider::for_value(
&String::from_utf8_lossy(data).to_value(),
));
} else {
providers.push(ContentProvider::for_bytes(ty, &glib::Bytes::from(data)));
}
}
if let Some(image) = item.as_image()
&& let Ok(texture) = gtk::gdk::Texture::from_bytes(&glib::Bytes::from_owned(image.bytes))
{
providers.push(ContentProvider::for_value(&texture.to_value()));
}
let _ = clipboard.set_content(Some(&ContentProvider::new_union(&providers)));
}
pub(crate) fn menu_model(app: >k::Application, spec: &MenuSpec) -> gio::Menu {
let menu = gio::Menu::new();
let mut section = gio::Menu::new();
for item in &spec.items {
match item {
MenuItemSpec::Action {
id,
title,
shortcut,
shortcut_hint,
role,
checked,
enabled,
..
} => {
let name = format!("m{id}");
action(app, &name, *id, *enabled);
let label = match (checked, role) {
(Some(true), _) => format!("✓ {title}"),
_ => title.clone(),
};
let entry = gio::MenuItem::new(Some(&label), Some(&format!("app.{name}")));
match shortcut {
Some(keys) if *shortcut_hint => {
entry.set_attribute_value("accel", Some(&accelerator(keys).to_variant()));
}
Some(keys) => {
app.set_accels_for_action(&format!("app.{name}"), &[&accelerator(keys)]);
}
None => {}
}
section.append_item(&entry);
}
MenuItemSpec::Separator => {
menu.append_section(None, §ion);
section = gio::Menu::new();
}
MenuItemSpec::System { .. } => {}
MenuItemSpec::Submenu {
title, menu: sub, ..
} => {
let model = menu_model(app, sub);
section.append_submenu(Some(title), &model);
}
}
}
menu.append_section(None, §ion);
menu
}
fn action(app: >k::Application, name: &str, id: u64, enabled: bool) {
if let Some(existing) = app.lookup_action(name).and_downcast::<gio::SimpleAction>() {
existing.set_enabled(enabled);
return;
}
let action = gio::SimpleAction::new(name, None);
action.set_enabled(enabled);
action.connect_activate(move |_, _| imp::dispatch(UiEvent::MenuSelect(id)));
app.add_action(&action);
}
impl LinuxServices {
fn alert(&self, spec: AlertSpec) {
let dialog = gtk::Window::builder()
.transient_for(&self.window)
.modal(true)
.resizable(false)
.default_width(360)
.build();
let body = gtk::Box::new(gtk::Orientation::Vertical, 12);
body.set_margin_top(20);
body.set_margin_bottom(20);
body.set_margin_start(20);
body.set_margin_end(20);
let title = gtk::Label::new(Some(&spec.title));
title.add_css_class("title-3");
title.set_wrap(true);
body.append(&title);
if let Some(m) = &spec.message {
let message = gtk::Label::new(Some(m));
message.set_wrap(true);
body.append(&message);
}
let buttons = gtk::Box::new(gtk::Orientation::Horizontal, 8);
buttons.set_halign(gtk::Align::End);
for (index, (label, role)) in spec.actions.iter().enumerate() {
let b = gtk::Button::with_label(label);
match role {
ActionRole::Destructive => b.add_css_class("destructive-action"),
ActionRole::Cancel => {}
_ => b.add_css_class("suggested-action"),
}
let (dialog, id) = (dialog.clone(), spec.id);
b.connect_clicked(move |_| {
dialog.close();
imp::dispatch(UiEvent::AlertAction(id, index));
});
buttons.append(&b);
}
body.append(&buttons);
dialog.set_child(Some(&body));
dialog.present();
}
pub fn due_background(&mut self) -> Vec<String> {
let now = std::time::Instant::now();
let (due, later): (Vec<_>, Vec<_>) =
self.background.drain(..).partition(|(_, at, _)| *at <= now);
self.background = later;
due.into_iter().map(|(id, _, _)| id).collect()
}
}
impl PlatformServices for LinuxServices {
fn capabilities(&self) -> Capabilities {
self.caps
}
fn handle(&mut self, request: PlatformRequest) {
match request {
PlatformRequest::Device { id, call } => self.device(id, call),
PlatformRequest::Notify(n) => {
if self.caps.notifications {
self.notify(n)
}
}
PlatformRequest::CancelNotification(id) => {
if let Some(timer) = self.pending.remove(&id) {
timer.remove();
}
self.app.withdraw_notification(&id);
}
PlatformRequest::RequestNotificationPermission => {}
PlatformRequest::SetBadge(_) => {}
PlatformRequest::RegisterPush => crate::push::register(
self.data_dir.clone(),
|r| {
glib::idle_add_local_once(move || imp::push_registered(r));
},
|m| {
glib::idle_add_local_once(move || imp::push_received(m));
},
),
PlatformRequest::UnregisterPush => crate::push::unregister(&self.data_dir),
PlatformRequest::WatchActivityPushToStart => {}
PlatformRequest::ShowAlert(spec) => self.alert(spec),
PlatformRequest::SetAppMenu(menus) | PlatformRequest::SetMenuBar(menus) => {
let bar = gio::Menu::new();
for m in &menus {
let model = menu_model(&self.app, m);
bar.append_submenu(Some(&m.title), &model);
}
self.app.set_menubar(Some(&bar));
self.window.set_show_menubar(true);
}
PlatformRequest::ScheduleBackgroundTask(task) => {
let every = imp::background_interval(task.every);
self.background.retain(|(id, _, _)| *id != task.id);
self.background
.push((task.id, std::time::Instant::now() + every, every));
}
PlatformRequest::SetTray(spec) => crate::tray::set(self, spec),
PlatformRequest::RemoveTray(id) => crate::tray::remove(&id),
PlatformRequest::SetCar(_) => {}
PlatformRequest::LoadFont(_)
| PlatformRequest::AddStylesheet(_)
| PlatformRequest::RemoveStylesheet(_)
| PlatformRequest::SetTitle(_)
| PlatformRequest::SetUnsavedChanges(_) => {}
PlatformRequest::ReloadWidgets(_)
| PlatformRequest::StartActivity { .. }
| PlatformRequest::UpdateActivity { .. }
| PlatformRequest::EndActivity { .. } => {}
}
}
}
fn accelerator(keys: &str) -> String {
let mut out = String::new();
let mut key = String::new();
for part in keys.split('+') {
match part.trim().to_ascii_lowercase().as_str() {
"cmd" | "command" | "ctrl" | "control" | "meta" => out += "<Control>",
"shift" => out += "<Shift>",
"alt" | "option" | "opt" => out += "<Alt>",
"super" => out += "<Super>",
other => key = other.to_string(),
}
}
let mut chars = key.chars();
if let (Some(c), None) = (chars.next(), chars.next()) {
use gtk::glib::translate::FromGlib;
let keyval =
unsafe { gtk::gdk::Key::from_glib(gtk::gdk::ffi::gdk_unicode_to_keyval(c as u32)) };
if let Some(name) = keyval.name() {
key = name.to_string();
}
}
out + &key
}
mod geoclue {
use std::cell::RefCell;
use std::rc::Rc;
use gtk::prelude::*;
use gtk::{gio, glib};
use prism_core::Location;
use super::GEOCLUE;
const TIMEOUT_MS: i32 = 10_000;
type Handler = Rc<dyn Fn(&gio::DBusConnection, &str, Location) -> bool>;
async fn call(
bus: &gio::DBusConnection,
path: &str,
interface: &str,
method: &str,
args: Option<glib::Variant>,
reply: Option<&str>,
) -> Result<glib::Variant, glib::Error> {
bus.call_future(
Some(GEOCLUE),
path,
interface,
method,
args.as_ref(),
reply.map(|r| glib::VariantTy::new(r).expect("type")),
gio::DBusCallFlags::NONE,
TIMEOUT_MS,
)
.await
}
fn error(e: glib::Error) -> &'static str {
eprintln!("prism-linux: GeoClue: {e}");
if e.to_string().contains("AccessDenied") {
"denied"
} else {
"unavailable"
}
}
pub async fn create_client(
desktop_id: &str,
level: u32,
) -> Result<(gio::DBusConnection, String), &'static str> {
let bus = gio::bus_get_future(gio::BusType::System)
.await
.map_err(|_| "unavailable")?;
let created = call(
&bus,
"/org/freedesktop/GeoClue2/Manager",
"org.freedesktop.GeoClue2.Manager",
"CreateClient",
None,
Some("(o)"),
)
.await
.map_err(error)?;
let path = created
.child_value(0)
.str()
.map(str::to_string)
.ok_or("unavailable")?;
for (name, value) in [
("DesktopId", desktop_id.to_variant()),
("RequestedAccuracyLevel", level.to_variant()),
] {
call(
&bus,
&path,
"org.freedesktop.DBus.Properties",
"Set",
Some(("org.freedesktop.GeoClue2.Client", name, value).to_variant()),
None,
)
.await
.map_err(error)?;
}
Ok((bus, path))
}
pub async fn start_client(
desktop_id: &str,
level: u32,
) -> Result<(gio::DBusConnection, String), &'static str> {
let (bus, path) = create_client(desktop_id, level).await?;
start(&bus, &path).await?;
Ok((bus, path))
}
pub async fn start(bus: &gio::DBusConnection, path: &str) -> Result<(), &'static str> {
call(
bus,
path,
"org.freedesktop.GeoClue2.Client",
"Start",
None,
None,
)
.await
.map(|_| ())
.map_err(error)
}
pub async fn stop(bus: &gio::DBusConnection, path: &str) {
let _ = call(
bus,
path,
"org.freedesktop.GeoClue2.Client",
"Stop",
None,
None,
)
.await;
}
#[allow(deprecated)]
pub fn on_location(
bus: &gio::DBusConnection,
path: &str,
f: impl Fn(&gio::DBusConnection, &str, Location) -> bool + 'static,
) {
let f: Handler = Rc::new(f);
let subscription: Rc<RefCell<Option<gio::SignalSubscriptionId>>> =
Rc::new(RefCell::new(None));
let sub = subscription.clone();
let client = path.to_string();
let handle = bus.signal_subscribe(
Some(GEOCLUE),
Some("org.freedesktop.GeoClue2.Client"),
Some("LocationUpdated"),
Some(path),
None,
gio::DBusSignalFlags::NONE,
move |bus, _, _, _, _, params| {
let Some(location_path) = params.child_value(1).str().map(str::to_string) else {
return;
};
let (bus, client, sub, f) = (bus.clone(), client.clone(), sub.clone(), f.clone());
glib::MainContext::default().spawn_local(async move {
let Some(location) = read_location(&bus, &location_path).await else {
return;
};
if !f(&bus, &client, location)
&& let Some(id) = sub.borrow_mut().take()
{
bus.signal_unsubscribe(id);
}
});
},
);
*subscription.borrow_mut() = Some(handle);
}
pub async fn read_location(bus: &gio::DBusConnection, path: &str) -> Option<Location> {
let all = call(
bus,
path,
"org.freedesktop.DBus.Properties",
"GetAll",
Some(("org.freedesktop.GeoClue2.Location",).to_variant()),
None,
)
.await
.ok()?;
let props = all.child_value(0);
let dict = glib::VariantDict::new(Some(&props));
let num = |k: &str| dict.lookup::<f64>(k).ok().flatten();
let timestamp = dict
.lookup_value("Timestamp", None)
.and_then(|v| v.get::<(u64, u64)>())
.map_or(0., |(s, us)| s as f64 + us as f64 / 1e6);
Some(Location {
latitude: num("Latitude")?,
longitude: num("Longitude")?,
altitude: num("Altitude").filter(|a| *a > f64::MIN),
accuracy: num("Accuracy").unwrap_or(0.),
speed: num("Speed").filter(|s| *s >= 0.),
heading: num("Heading").filter(|h| *h >= 0.),
timestamp,
})
}
}
fn copy_picked(file: &gio::File) -> Option<PickedFile> {
copy_picked_path(file.path()?)
}
fn folder_files(root: &std::path::Path) -> Vec<PickedFile> {
let mut out = vec![PickedFile {
path: root.to_string_lossy().to_string(),
name: root
.file_name()
.map_or_else(|| "folder".into(), |n| n.to_string_lossy().to_string()),
mime: prism_core::FOLDER_MIME.into(),
size: 0,
}];
let mut todo = vec![(root.to_path_buf(), String::new())];
while let Some((dir, prefix)) = todo.pop() {
let Ok(read) = std::fs::read_dir(&dir) else {
continue;
};
let mut entries: Vec<_> = read.flatten().collect();
entries.sort_by_key(|e| e.file_name());
for e in entries {
let name = e.file_name().to_string_lossy().to_string();
if name.starts_with('.') {
continue;
}
let rel = if prefix.is_empty() {
name
} else {
format!("{prefix}/{name}")
};
let Ok(kind) = e.file_type() else {
continue;
};
if kind.is_dir() {
todo.push((e.path(), rel));
} else if kind.is_file() {
let path = e.path();
let mime = gio::content_type_guess(Some(&path), None::<&[u8]>).0;
let mime = gio::content_type_get_mime_type(&mime)
.map_or("application/octet-stream".into(), |m| m.to_string());
out.push(PickedFile {
size: e.metadata().map_or(0, |m| m.len()),
path: path.to_string_lossy().to_string(),
name: rel,
mime,
});
}
}
}
out
}
pub(crate) fn copy_picked_path(src: std::path::PathBuf) -> Option<PickedFile> {
let dir = glib::user_cache_dir().join("prism-picked");
std::fs::create_dir_all(&dir).ok()?;
let name = src.file_name()?.to_string_lossy().to_string();
let ext = src
.extension()
.map(|e| e.to_string_lossy().to_string())
.unwrap_or_default();
let unique = format!(
"{}.{ext}",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_nanos())
);
let dest = dir.join(unique);
let size = std::fs::copy(&src, &dest).ok()?;
let mime = gio::content_type_guess(Some(&src), None::<&[u8]>).0;
let mime = gio::content_type_get_mime_type(&mime)
.map_or("application/octet-stream".into(), |m| m.to_string());
Some(PickedFile {
path: dest.to_string_lossy().to_string(),
name,
mime,
size,
})
}