1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
//! Implementation of the [`Session`] trait through various implementations
//! automatically choosing the best available interface.
//!
//! ## How to use it
//!
//! ### Initialization
//!
//! To initialize a session just call [`AutoSession::new`].
//! A new session will be opened, if the any available interface is successful and will be closed once the
//! [`AutoSessionNotifier`] is dropped.
//!
//! ### Usage of the session
//!
//! The session may be used to open devices manually through the [`Session`] interface
//! or be passed to other objects that need it to open devices themselves.
//! The [`AutoSession`] is cloneable
//! and may be passed to multiple devices easily.
//!
//! Examples for those are e.g. the [`LibinputInputBackend`](crate::backend::libinput::LibinputInputBackend)
//! (its context might be initialized through a [`Session`] via the [`LibinputSessionInterface`](crate::backend::libinput::LibinputSessionInterface)).
//!
//! ### Usage of the session notifier
//!
//! The notifier might be used to pause device access, when the session gets paused (e.g. by
//! switching the tty via [`AutoSession::change_vt`](crate::backend::session::Session::change_vt))
//! and to automatically enable it again, when the session becomes active again.
//!
//! It is crucial to avoid errors during that state. Examples for object that might be registered
//! for notifications are the [`Libinput`](input::Libinput) context or the [`DrmDevice`](crate::backend::drm::DrmDevice).
//!
//! The [`AutoSessionNotifier`] is to be inserted into
//! a calloop event source to have its events processed.

#[cfg(feature = "backend_session_libseat")]
use super::libseat::{LibSeatSession, LibSeatSessionNotifier};
#[cfg(feature = "backend_session_logind")]
use super::logind::{self, LogindSession, LogindSessionNotifier};
use super::{
    direct::{self, DirectSession, DirectSessionNotifier},
    AsErrno, Session, Signal as SessionSignal,
};
use crate::utils::signaling::Signaler;
use nix::fcntl::OFlag;
use std::{cell::RefCell, io, os::unix::io::RawFd, path::Path, rc::Rc};

use calloop::{EventSource, Poll, PostAction, Readiness, Token, TokenFactory};

use slog::{error, info, o, warn};

/// [`Session`] using the best available interface
#[derive(Debug, Clone)]
pub enum AutoSession {
    /// Logind session
    #[cfg(feature = "backend_session_logind")]
    Logind(LogindSession),
    /// Direct / tty session
    Direct(Rc<RefCell<DirectSession>>),
    /// LibSeat session
    #[cfg(feature = "backend_session_libseat")]
    LibSeat(LibSeatSession),
}

/// Notifier using the best available interface
#[derive(Debug)]
pub enum AutoSessionNotifier {
    /// Logind session notifier
    #[cfg(feature = "backend_session_logind")]
    Logind(LogindSessionNotifier),
    /// Direct / tty session notifier
    Direct(DirectSessionNotifier),
    /// LibSeat session notifier
    #[cfg(feature = "backend_session_libseat")]
    LibSeat(LibSeatSessionNotifier),
}

impl AutoSession {
    /// Tries to create a new session via the best available interface.
    pub fn new<L>(logger: L) -> Option<(AutoSession, AutoSessionNotifier)>
    where
        L: Into<Option<::slog::Logger>>,
    {
        let logger = crate::slog_or_fallback(logger)
            .new(o!("smithay_module" => "backend_session_auto", "session_type" => "auto"));

        #[cfg(feature = "backend_session_libseat")]
        {
            info!(logger, "Trying to create libseat session");
            match LibSeatSession::new(logger.clone()) {
                Ok((sesstion, notifier)) => {
                    return Some((
                        AutoSession::LibSeat(sesstion),
                        AutoSessionNotifier::LibSeat(notifier),
                    ))
                }
                Err(err) => {
                    warn!(logger, "Failed to create libseat session: {}", err);
                }
            }
        }

        #[cfg(feature = "backend_session_logind")]
        {
            info!(logger, "Trying to create logind session");
            match LogindSession::new(logger.clone()) {
                Ok((session, notifier)) => {
                    return Some((
                        AutoSession::Logind(session),
                        AutoSessionNotifier::Logind(notifier),
                    ))
                }
                Err(err) => {
                    warn!(logger, "Failed to create logind session: {}", err);
                }
            }
        }

        info!(logger, "Trying to create tty session");
        match DirectSession::new(None, logger.clone()) {
            Ok((session, notifier)) => {
                return Some((
                    AutoSession::Direct(Rc::new(RefCell::new(session))),
                    AutoSessionNotifier::Direct(notifier),
                ))
            }
            Err(err) => {
                warn!(logger, "Failed to create direct session: {}", err);
            }
        }

        error!(logger, "Could not create any session, possibilities exhausted");
        None
    }
}

impl Session for AutoSession {
    type Error = Error;

    fn open(&mut self, path: &Path, flags: OFlag) -> Result<RawFd, Error> {
        match *self {
            #[cfg(feature = "backend_session_logind")]
            AutoSession::Logind(ref mut logind) => logind.open(path, flags).map_err(|e| e.into()),
            AutoSession::Direct(ref mut direct) => direct.open(path, flags).map_err(|e| e.into()),
            #[cfg(feature = "backend_session_libseat")]
            AutoSession::LibSeat(ref mut logind) => logind.open(path, flags).map_err(|e| e.into()),
        }
    }
    fn close(&mut self, fd: RawFd) -> Result<(), Error> {
        match *self {
            #[cfg(feature = "backend_session_logind")]
            AutoSession::Logind(ref mut logind) => logind.close(fd).map_err(|e| e.into()),
            AutoSession::Direct(ref mut direct) => direct.close(fd).map_err(|e| e.into()),
            #[cfg(feature = "backend_session_libseat")]
            AutoSession::LibSeat(ref mut direct) => direct.close(fd).map_err(|e| e.into()),
        }
    }

    fn change_vt(&mut self, vt: i32) -> Result<(), Error> {
        match *self {
            #[cfg(feature = "backend_session_logind")]
            AutoSession::Logind(ref mut logind) => logind.change_vt(vt).map_err(|e| e.into()),
            AutoSession::Direct(ref mut direct) => direct.change_vt(vt).map_err(|e| e.into()),
            #[cfg(feature = "backend_session_libseat")]
            AutoSession::LibSeat(ref mut direct) => direct.change_vt(vt).map_err(|e| e.into()),
        }
    }

    fn is_active(&self) -> bool {
        match *self {
            #[cfg(feature = "backend_session_logind")]
            AutoSession::Logind(ref logind) => logind.is_active(),
            AutoSession::Direct(ref direct) => direct.is_active(),
            #[cfg(feature = "backend_session_libseat")]
            AutoSession::LibSeat(ref direct) => direct.is_active(),
        }
    }
    fn seat(&self) -> String {
        match *self {
            #[cfg(feature = "backend_session_logind")]
            AutoSession::Logind(ref logind) => logind.seat(),
            AutoSession::Direct(ref direct) => direct.seat(),
            #[cfg(feature = "backend_session_libseat")]
            AutoSession::LibSeat(ref direct) => direct.seat(),
        }
    }
}

impl AutoSessionNotifier {
    /// Get a handle to the Signaler of this session.
    ///
    /// You can use it to listen for signals generated by the session.
    pub fn signaler(&self) -> Signaler<SessionSignal> {
        match *self {
            #[cfg(feature = "backend_session_logind")]
            AutoSessionNotifier::Logind(ref logind) => logind.signaler(),
            AutoSessionNotifier::Direct(ref direct) => direct.signaler(),
            #[cfg(feature = "backend_session_libseat")]
            AutoSessionNotifier::LibSeat(ref direct) => direct.signaler(),
        }
    }
}

impl EventSource for AutoSessionNotifier {
    type Event = ();
    type Metadata = ();
    type Ret = ();

    fn process_events<F>(&mut self, readiness: Readiness, token: Token, callback: F) -> io::Result<PostAction>
    where
        F: FnMut((), &mut ()),
    {
        match self {
            #[cfg(feature = "backend_session_logind")]
            AutoSessionNotifier::Logind(s) => s.process_events(readiness, token, callback),
            AutoSessionNotifier::Direct(s) => s.process_events(readiness, token, callback),
            #[cfg(feature = "backend_session_libseat")]
            AutoSessionNotifier::LibSeat(s) => s.process_events(readiness, token, callback),
        }
    }

    fn register(&mut self, poll: &mut Poll, factory: &mut TokenFactory) -> io::Result<()> {
        match self {
            #[cfg(feature = "backend_session_logind")]
            AutoSessionNotifier::Logind(s) => EventSource::register(s, poll, factory),
            AutoSessionNotifier::Direct(s) => EventSource::register(s, poll, factory),
            #[cfg(feature = "backend_session_libseat")]
            AutoSessionNotifier::LibSeat(s) => EventSource::register(s, poll, factory),
        }
    }

    fn reregister(&mut self, poll: &mut Poll, factory: &mut TokenFactory) -> io::Result<()> {
        match self {
            #[cfg(feature = "backend_session_logind")]
            AutoSessionNotifier::Logind(s) => EventSource::reregister(s, poll, factory),
            AutoSessionNotifier::Direct(s) => EventSource::reregister(s, poll, factory),
            #[cfg(feature = "backend_session_libseat")]
            AutoSessionNotifier::LibSeat(s) => EventSource::reregister(s, poll, factory),
        }
    }

    fn unregister(&mut self, poll: &mut Poll) -> io::Result<()> {
        match self {
            #[cfg(feature = "backend_session_logind")]
            AutoSessionNotifier::Logind(s) => EventSource::unregister(s, poll),
            AutoSessionNotifier::Direct(s) => EventSource::unregister(s, poll),
            #[cfg(feature = "backend_session_libseat")]
            AutoSessionNotifier::LibSeat(s) => EventSource::unregister(s, poll),
        }
    }
}

/// Errors related to auto sessions
#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[cfg(feature = "backend_session_logind")]
    /// Logind session error
    #[error("Logind session error: {0}")]
    Logind(#[from] logind::Error),
    /// Direct session error
    #[error("Direct session error: {0}")]
    Direct(#[from] direct::Error),
    /// LibSeat session error
    #[cfg(feature = "backend_session_libseat")]
    #[error("LibSeat session error: {0}")]
    LibSeat(#[from] super::libseat::Error),

    /// Nix error
    #[error("Nix error: {0}")]
    Nix(#[from] nix::Error),
}

impl AsErrno for Error {
    fn as_errno(&self) -> Option<i32> {
        //TODO figure this out, I don't see a way..
        None
    }
}