| 1 |
use std::{ |
| 2 |
collections::HashMap, |
| 3 |
sync::{Arc, Mutex}, |
| 4 |
}; |
| 5 |
|
| 6 |
use async_trait::async_trait; |
| 7 |
use serde::Serialize; |
| 8 |
use zbus::{ |
| 9 |
object_server::SignalEmitter, |
| 10 |
zvariant::{OwnedObjectPath, Type, as_value}, |
| 11 |
}; |
| 12 |
|
| 13 |
use crate::{PortalError, desktop::HandleToken}; |
| 14 |
|
| 15 |
pub(crate) struct Session { |
| 16 |
path: OwnedObjectPath, |
| 17 |
manager: Arc<Mutex<SessionManager>>, |
| 18 |
monitor: Option<Arc<dyn SessionImpl>>, |
| 19 |
} |
| 20 |
|
| 21 |
impl Session { |
| 22 |
pub(crate) fn new( |
| 23 |
path: OwnedObjectPath, |
| 24 |
manager: Arc<Mutex<SessionManager>>, |
| 25 |
monitor: Option<Arc<dyn SessionImpl>>, |
| 26 |
) -> Self { |
| 27 |
Self { |
| 28 |
path, |
| 29 |
manager, |
| 30 |
monitor, |
| 31 |
} |
| 32 |
} |
| 33 |
|
| 34 |
pub fn token(&self) -> HandleToken { |
| 35 |
HandleToken::try_from(&self.path).unwrap() |
| 36 |
} |
| 37 |
|
| 38 |
pub async fn serve(&self, cnx: zbus::Connection) -> zbus::Result<bool> { |
| 39 |
let interface = SessionInterface::new( |
| 40 |
self.path.clone(), |
| 41 |
Arc::clone(&self.manager), |
| 42 |
self.monitor.clone(), |
| 43 |
); |
| 44 |
cnx.object_server().at(&self.path, interface).await |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
impl PartialEq for Session { |
| 49 |
fn eq(&self, other: &Self) -> bool { |
| 50 |
self.path == other.path |
| 51 |
} |
| 52 |
} |
| 53 |
|
| 54 |
impl std::fmt::Debug for Session { |
| 55 |
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 56 |
f.debug_struct("Session").field("path", &self.path).finish() |
| 57 |
} |
| 58 |
} |
| 59 |
|
| 60 |
struct SessionInterface { |
| 61 |
path: OwnedObjectPath, |
| 62 |
manager: Arc<Mutex<SessionManager>>, |
| 63 |
monitor: Option<Arc<dyn SessionImpl>>, |
| 64 |
} |
| 65 |
|
| 66 |
impl SessionInterface { |
| 67 |
fn new( |
| 68 |
path: OwnedObjectPath, |
| 69 |
manager: Arc<Mutex<SessionManager>>, |
| 70 |
monitor: Option<Arc<dyn SessionImpl>>, |
| 71 |
) -> Self { |
| 72 |
Self { |
| 73 |
path, |
| 74 |
manager, |
| 75 |
monitor, |
| 76 |
} |
| 77 |
} |
| 78 |
} |
| 79 |
|
| 80 |
#[zbus::interface(name = "org.freedesktop.impl.portal.Session")] |
| 81 |
impl SessionInterface { |
| 82 |
#[zbus(property(emits_changed_signal = "const"), name = "version")] |
| 83 |
fn version(&self) -> u32 { |
| 84 |
1 |
| 85 |
} |
| 86 |
|
| 87 |
#[doc(alias = "Close")] |
| 88 |
async fn close( |
| 89 |
&self, |
| 90 |
#[zbus(object_server)] server: &zbus::ObjectServer, |
| 91 |
) -> zbus::fdo::Result<()> { |
| 92 |
#[cfg(feature = "tracing")] |
| 93 |
tracing::debug!("SessionInterface::Close {}", self.path.as_str()); |
| 94 |
let token = HandleToken::try_from(&self.path).unwrap(); |
| 95 |
{ |
| 96 |
// Let the session manager know so it can update |
| 97 |
// its internal map of tracked sessions. |
| 98 |
let mut manager = self.manager.lock().unwrap(); |
| 99 |
let _ = manager.remove(&token); |
| 100 |
} |
| 101 |
if let Some(monitor) = &self.monitor { |
| 102 |
// The backend implements the `SessionImpl` trait, |
| 103 |
// it wants to be notified that the session was closed. |
| 104 |
let _ = monitor.session_closed(token).await; |
| 105 |
} |
| 106 |
// This method intentionally does *not* emit the `Closed` signal. |
| 107 |
server.remove::<Self, _>(&self.path).await?; |
| 108 |
Ok(()) |
| 109 |
} |
| 110 |
|
| 111 |
#[zbus(signal)] |
| 112 |
async fn closed(signal_emitter: &SignalEmitter<'_>) -> zbus::Result<()>; |
| 113 |
} |
| 114 |
|
| 115 |
#[async_trait] |
| 116 |
/// A trait that backends that create long-lived sessions should implement |
| 117 |
/// to be notified when a session has been closed. |
| 118 |
pub trait SessionImpl: Send + Sync { |
| 119 |
#[doc(alias = "Closed")] |
| 120 |
async fn session_closed(&self, session_token: HandleToken) -> crate::backend::Result<()>; |
| 121 |
} |
| 122 |
|
| 123 |
#[derive(Serialize, Type, Debug)] |
| 124 |
#[zvariant(signature = "dict")] |
| 125 |
pub struct CreateSessionResponse { |
| 126 |
#[serde(with = "as_value")] |
| 127 |
session_id: HandleToken, |
| 128 |
} |
| 129 |
|
| 130 |
impl CreateSessionResponse { |
| 131 |
pub fn new(token: HandleToken) -> Self { |
| 132 |
Self { session_id: token } |
| 133 |
} |
| 134 |
} |
| 135 |
|
| 136 |
#[derive(Default)] |
| 137 |
// Not thread-safe! If it needs to be accessed from several threads, |
| 138 |
// consider wrapping it in a Mutex. |
| 139 |
pub(crate) struct SessionManager { |
| 140 |
sessions: HashMap<HandleToken, Session>, |
| 141 |
} |
| 142 |
|
| 143 |
impl SessionManager { |
| 144 |
/// Expects to find a tracked session with the given handle. |
| 145 |
/// Returns a suitable portal error if not. |
| 146 |
pub fn try_contains(&self, token: &HandleToken) -> crate::backend::Result<&Session> { |
| 147 |
self.sessions |
| 148 |
.get(token) |
| 149 |
.ok_or(PortalError::NotFound(format!("Unknown session: `{token}`"))) |
| 150 |
} |
| 151 |
|
| 152 |
/// Tests whether a session with the given handle token already exists. |
| 153 |
pub fn contains(&self, token: &HandleToken) -> bool { |
| 154 |
#[cfg(feature = "tracing")] |
| 155 |
tracing::debug!("SessionManager::contains: tracked sessions: {:?}", &self); |
| 156 |
self.try_contains(token).is_ok() |
| 157 |
} |
| 158 |
|
| 159 |
/// Adds a session to the list of tracked sessions. |
| 160 |
/// Assumes that no session with the same handle token is already tracked |
| 161 |
/// (if there was one, it is silently discarded and backends are not |
| 162 |
/// notified). To avoid such a situation, it is recommended to call |
| 163 |
/// `contains()` prior to instantiating and adding a session. |
| 164 |
pub fn add(&mut self, session: Session) { |
| 165 |
let token = session.token(); |
| 166 |
let _ = self.sessions.insert(token.clone(), session); |
| 167 |
} |
| 168 |
|
| 169 |
/// Removes a session from the list of tracked sessions. |
| 170 |
/// Returns an error if no session with the given handle token was tracked. |
| 171 |
pub fn remove(&mut self, token: &HandleToken) -> crate::backend::Result<()> { |
| 172 |
if self.sessions.remove(token).is_some() { |
| 173 |
Ok(()) |
| 174 |
} else { |
| 175 |
let message = format!("Unknown session: `{token}`"); |
| 176 |
#[cfg(feature = "tracing")] |
| 177 |
tracing::error!("{}", message.as_str()); |
| 178 |
Err(PortalError::NotFound(message)) |
| 179 |
} |
| 180 |
} |
| 181 |
} |
| 182 |
|
| 183 |
impl std::fmt::Debug for SessionManager { |
| 184 |
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 185 |
f.debug_list().entries(self.sessions.keys()).finish() |
| 186 |
} |
| 187 |
} |