crabshell-services 0.8.1

Crabshell's services: workspaces, tray, audio, clock, power, Bluetooth, network, media players, notifications, apps, programs, files, PAM, greetd and polkit
Documentation
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
//! The server's answers to calls on `/org/freedesktop/Notifications`,
//! and how a `Notify` call's arguments become a [`Notification`].

use std::collections::HashMap;
use std::fmt;
use std::os::unix::ffi::OsStringExt;
use std::path::PathBuf;
use std::rc::Rc;
use std::time::{Duration, SystemTime};

use crabshell_ui::{IconPixels, IconSource};
use serde::de::{Deserialize, Deserializer, IgnoredAny, SeqAccess, Visitor};
use zbus::message::Flags;
use zbus::{Connection, Message, Signature, Type};

use super::{CloseReason, HANDOFF, NOTIFICATIONS_PATH, Notification, Service, Timeout, Urgency};

/// The most bytes kept of a summary and of a body. With every other
/// cap, 256 notifications stay within a few MiB however apps fill them.
pub(super) const MAX_SUMMARY: usize = 1024;
pub(super) const MAX_BODY: usize = 4 * 1024;
/// The most bytes kept of every other string: names, icons and actions.
pub(super) const MAX_TEXT: usize = 256;
pub(super) const MAX_ACTIONS: usize = 16;
/// The largest picture side kept, the same as tray pixmaps'.
const MAX_IMAGE_SIDE: i32 = 512;
/// The most bytes a picture may send: one 512 px picture with alpha.
const MAX_IMAGE_BYTES: usize = 1024 * 1024;

/// What the server offers: action buttons, a body, a still image, and a
/// history that outlasts the popups.
const CAPABILITIES: [&str; 4] = ["actions", "body", "icon-static", "persistence"];
/// The same with markup in the body: `b`, `i`, `u` and links. Not
/// `body-images`, since an `img` shows its alt text.
const MARKUP_CAPABILITIES: [&str; 6] = [
  "actions",
  "body",
  "body-hyperlinks",
  "body-markup",
  "icon-static",
  "persistence",
];

/// What the server offers, for callers that look before calling.
const INTROSPECTION: &str = r#"<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN"
 "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
<node>
  <interface name="org.freedesktop.Notifications">
    <method name="Notify">
      <arg name="app_name" type="s" direction="in"/>
      <arg name="replaces_id" type="u" direction="in"/>
      <arg name="app_icon" type="s" direction="in"/>
      <arg name="summary" type="s" direction="in"/>
      <arg name="body" type="s" direction="in"/>
      <arg name="actions" type="as" direction="in"/>
      <arg name="hints" type="a{sv}" direction="in"/>
      <arg name="expire_timeout" type="i" direction="in"/>
      <arg name="id" type="u" direction="out"/>
    </method>
    <method name="CloseNotification"><arg name="id" type="u" direction="in"/></method>
    <method name="GetCapabilities"><arg name="capabilities" type="as" direction="out"/></method>
    <method name="GetServerInformation">
      <arg name="name" type="s" direction="out"/>
      <arg name="vendor" type="s" direction="out"/>
      <arg name="version" type="s" direction="out"/>
      <arg name="spec_version" type="s" direction="out"/>
    </method>
    <signal name="NotificationClosed"><arg name="id" type="u"/><arg name="reason" type="u"/></signal>
    <signal name="ActionInvoked"><arg name="id" type="u"/><arg name="action_key" type="s"/></signal>
  </interface>
  <interface name="org.freedesktop.DBus.Introspectable">
    <method name="Introspect"><arg name="xml" type="s" direction="out"/></method>
  </interface>
</node>
"#;

const INVALID_ARGS: &str = "org.freedesktop.DBus.Error.InvalidArgs";
const ACCESS_DENIED: &str = "org.freedesktop.DBus.Error.AccessDenied";
const UNKNOWN_METHOD: &str = "org.freedesktop.DBus.Error.UnknownMethod";

/// Answers one method call to this connection, while it serves. Anything
/// else gets the bus's usual error, so no caller waits for a timeout. A
/// call that asks for no reply is still acted on.
pub(super) async fn answer(service: &Rc<Service>, connection: &Connection, call: &Message) {
  let header = call.header();
  let path = header.path().map(|path| path.as_str());
  let member = header.member().map_or("", |member| member.as_str());
  let body = call.body();
  let reply = Message::method_return(&header);
  let refuse = |error: &str, why: &str| Message::error(&header, error).build(&why);
  let interface = header.interface().map(|interface| interface.as_str());
  let taken = match (interface, path, member) {
    (Some(HANDOFF), Some(NOTIFICATIONS_PATH), "Take") => {
      let caller = header.sender().map(|sender| sender.as_str());
      Some(service.hand_over(connection, caller).await)
    }
    _ => None,
  };
  let answer = match (path, member) {
    _ if taken.is_some() => match taken.flatten() {
      Some(kept) => reply.build(&kept),
      None => refuse(ACCESS_DENIED, "nothing to hand over"),
    },
    _ if !service.serving() => refuse(UNKNOWN_METHOD, "not serving notifications"),
    (Some(NOTIFICATIONS_PATH), "Notify") => match body.deserialize::<NotifyArgs<'_>>() {
      Ok(args) => {
        let (replaces, notification) = notification(args, service.body_markup.get());
        reply.build(&service.notify(replaces, notification))
      }
      Err(_) => refuse(INVALID_ARGS, "not a notification"),
    },
    (Some(NOTIFICATIONS_PATH), "CloseNotification") => match body.deserialize::<u32>() {
      Ok(id) if service.close(&[id], CloseReason::CloseRequested) => reply.build(&()),
      _ => refuse(INVALID_ARGS, "no such notification"),
    },
    (Some(NOTIFICATIONS_PATH), "GetCapabilities") => match service.body_markup.get() {
      true => reply.build(&MARKUP_CAPABILITIES.as_slice()),
      false => reply.build(&CAPABILITIES.as_slice()),
    },
    (Some(NOTIFICATIONS_PATH), "GetServerInformation") => {
      let version = env!("CARGO_PKG_VERSION");
      reply.build(&("crabshell", "crabshell", version, "1.2"))
    }
    (Some(NOTIFICATIONS_PATH), "Introspect") => reply.build(&INTROSPECTION),
    _ => refuse(UNKNOWN_METHOD, "no such method"),
  };
  if header.primary().flags().contains(Flags::NO_REPLY_EXPECTED) {
    return;
  }
  let sent = match answer {
    Ok(answer) => connection.send(&answer).await,
    Err(error) => Err(error),
  };
  if let Err(error) = sent {
    tracing::debug!(member, %error, "the notification server's answer wasn't sent");
  }
}

/// `Notify`'s arguments: the app's name, the id to replace, the app's
/// icon, the summary, the body, the actions, the hints and the timeout.
type NotifyArgs<'a> = (
  &'a str,
  u32,
  &'a str,
  &'a str,
  &'a str,
  Vec<&'a str>,
  HashMap<&'a str, Hint<'a>>,
  i32,
);

/// The id a `Notify` call replaces, and its notification, with id 0. Its
/// body keeps its markup if `markup`, or else is shown as plain text.
fn notification(args: NotifyArgs<'_>, markup: bool) -> (u32, Notification) {
  let (app_name, replaces, app_icon, summary, body, actions, hints, timeout) = args;
  let text = |key: &str| match hints.get(key) {
    Some(Hint::Text(text)) => cut(text, MAX_TEXT),
    _ => String::new(),
  };
  let flag = |key: &str| matches!(hints.get(key), Some(Hint::Number(n)) if *n != 0);
  let pixels = |key: &str| match hints.get(key) {
    Some(Hint::Image(raw)) => image_pixels(raw).map(IconSource::Pixels),
    _ => None,
  };
  let file = |key: &str| match hints.get(key) {
    Some(Hint::Text(path)) => icon(path),
    _ => None,
  };
  let app_icon = cut(app_icon, MAX_TEXT);
  // The spec's order, with the names of its earlier versions.
  let image = pixels("image-data")
    .or_else(|| pixels("image_data"))
    .or_else(|| file("image-path"))
    .or_else(|| file("image_path"))
    .or_else(|| icon(&app_icon))
    .or_else(|| pixels("icon_data"));
  let notification = Notification {
    id: 0,
    app_name: cut(app_name, MAX_TEXT),
    summary: cut(summary, MAX_SUMMARY),
    body: match markup {
      true => cut_markup(body, MAX_BODY),
      // Read past the cap only so far, since tags and entities shrink.
      false => cut(
        &plain(&body[..body.floor_char_boundary(MAX_BODY * 4)]),
        MAX_BODY,
      ),
    },
    actions: actions
      .as_chunks::<2>()
      .0
      .iter()
      .take(MAX_ACTIONS)
      .map(|[key, label]| (cut(key, MAX_TEXT), cut(label, MAX_TEXT)))
      .collect(),
    urgency: match hints.get("urgency") {
      Some(Hint::Number(0)) => Urgency::Low,
      Some(Hint::Number(2)) => Urgency::Critical,
      _ => Urgency::Normal,
    },
    timeout: match u64::try_from(timeout) {
      Ok(0) => Timeout::Never,
      Ok(ms) => Timeout::After(Duration::from_millis(ms)),
      Err(_) => Timeout::Default,
    },
    image,
    desktop_entry: text("desktop-entry"),
    category: text("category"),
    resident: flag("resident"),
    transient: flag("transient"),
    received: SystemTime::now(),
    app_icon,
  };
  (replaces, notification)
}

/// A markup body's first `max` bytes at most, cut at a char boundary,
/// without the tag or entity the cut split, which would show as raw text.
pub(super) fn cut_markup(body: &str, max: usize) -> String {
  let mut kept = &body[..body.floor_char_boundary(max)];
  // `open` was split if the cut left out the `close` that ends it within
  // `within` bytes; a bare `<` or `&` the body never closes stays.
  let split = |kept: &str, open: char, close: char, within: usize| {
    let at = kept.rfind(open)?;
    let closed = body[at..].find(close).is_some_and(|end| end <= within);
    (!kept[at..].contains(close) && closed).then_some(at)
  };
  if let Some(at) = split(kept, '<', '>', usize::MAX) {
    kept = &kept[..at];
  }
  // An entity is at most 10 bytes, `&#x10FFFF;`, as `plain` reads them.
  if let Some(at) = split(kept, '&', ';', 10) {
    kept = &kept[..at];
  }
  kept.to_owned()
}

/// `body` as the text it shows. When `body-markup` is off, many apps send
/// markup anyway, so tags are taken out and XML's five entities and
/// numeric ones decoded. An unknown entity and a `<` with no `>` stay as
/// they are.
fn plain(body: &str) -> String {
  let mut shown = String::with_capacity(body.len());
  let mut rest = body;
  while let Some(at) = rest.find(['<', '&']) {
    shown.push_str(&rest[..at]);
    rest = &rest[at..];
    if rest.starts_with('<') {
      match rest.find('>') {
        Some(end) => rest = &rest[end + 1..],
        None => {
          shown.push_str(rest);
          rest = "";
        }
      }
      continue;
    }
    let decoded = rest
      .find(';')
      .filter(|end| *end <= 10)
      .and_then(|end| Some((entity(&rest[1..end])?, end)));
    match decoded {
      Some((character, end)) => {
        shown.push(character);
        rest = &rest[end + 1..];
      }
      None => {
        shown.push('&');
        rest = &rest[1..];
      }
    }
  }
  shown.push_str(rest);
  shown
}

/// The character an entity's name between `&` and `;` stands for.
fn entity(name: &str) -> Option<char> {
  match name {
    "amp" => Some('&'),
    "lt" => Some('<'),
    "gt" => Some('>'),
    "quot" => Some('"'),
    "apos" => Some('\''),
    _ => {
      let number = name.strip_prefix('#')?;
      let code = match number.strip_prefix(['x', 'X']) {
        Some(hex) => u32::from_str_radix(hex, 16).ok()?,
        None => number.parse().ok()?,
      };
      char::from_u32(code)
    }
  }
}

/// `text`'s first `max` bytes at most, cut at a char boundary.
pub(super) fn cut(text: &str, max: usize) -> String {
  text[..text.floor_char_boundary(max)].to_owned()
}

/// What an icon name or image path names: a file for an absolute path or
/// a `file://` URI, a themed icon for a plain name, and `None` for
/// nothing, another URI, or a relative path.
pub(super) fn icon(name: &str) -> Option<IconSource> {
  if name.starts_with('/') {
    return Some(IconSource::File(name.into()));
  }
  if name.starts_with("file://") {
    return file_path(name).map(IconSource::File);
  }
  let named = !name.is_empty() && !name.contains('/');
  named.then(|| IconSource::Name(name.to_owned()))
}

/// The path a local `file://` URI names, with its `%xx` escapes undone.
fn file_path(uri: &str) -> Option<PathBuf> {
  let path = uri.strip_prefix("file://")?;
  if !path.starts_with('/') {
    return None;
  }
  let mut bytes = Vec::with_capacity(path.len());
  let mut rest = path.bytes();
  while let Some(byte) = rest.next() {
    if byte != b'%' {
      bytes.push(byte);
      continue;
    }
    let mut digit = || char::from(rest.next()?).to_digit(16);
    let (high, low) = (digit()?, digit()?);
    // Two hex digits, so at most 255.
    bytes.push((high * 16 + low) as u8);
  }
  Some(PathBuf::from(std::ffi::OsString::from_vec(bytes)))
}

/// A picture in the spec's `(iiibiiay)`: width, height, row stride,
/// alpha, bits per sample, channels, and the RGB or RGBA bytes.
pub(super) type RawImage<'a> = (i32, i32, i32, bool, i32, i32, &'a [u8]);

/// A picture as the renderer takes it. One over 512 px a side or 1 MiB,
/// in a format other than 8-bit RGB or RGBA, or with too few bytes for
/// its size, is logged and refused.
pub(super) fn image_pixels(raw: &RawImage<'_>) -> Option<IconPixels> {
  let &(width, height, rowstride, alpha, bits, channels, data) = raw;
  let refuse = || {
    let bytes = data.len();
    tracing::debug!(
      width,
      height,
      rowstride,
      bits,
      channels,
      bytes,
      "a bad notification picture; skipped"
    );
    None
  };
  let side = 1..=MAX_IMAGE_SIDE;
  let format = bits == 8 && channels == if alpha { 4 } else { 3 };
  let sized = side.contains(&width) && side.contains(&height) && data.len() <= MAX_IMAGE_BYTES;
  if !format || !sized {
    return refuse();
  }
  // The sides are from 1 to 512 and there are 3 or 4 channels, so the
  // casts are exact.
  let (width, height, channels) = (width as usize, height as usize, channels as usize);
  let row = width * channels;
  // The last row may end at its pixels, as GdkPixbuf's does.
  let stride = usize::try_from(rowstride).ok().filter(|&stride| {
    let needed = stride
      .checked_mul(height - 1)
      .and_then(|n| n.checked_add(row));
    stride >= row && needed.is_some_and(|needed| needed <= data.len())
  });
  let Some(stride) = stride else {
    return refuse();
  };
  let mut argb = Vec::with_capacity(width * height * 4);
  for y in 0..height {
    for pixel in data[y * stride..][..row].chunks_exact(channels) {
      let opacity = pixel.get(3).copied().unwrap_or(255);
      argb.extend_from_slice(&[opacity, pixel[0], pixel[1], pixel[2]]);
    }
  }
  Some(IconPixels {
    width: width as u32,
    height: height as u32,
    data: argb.into(),
  })
}

/// A hint's value, as far as the server reads one. Any other type is
/// skipped unread, so a large value of the wrong type costs nothing, and
/// a picture's bytes stay borrowed from the message.
enum Hint<'a> {
  /// A boolean or an integer of any width.
  Number(i64),
  Text(&'a str),
  Image(RawImage<'a>),
  Other,
}

impl Type for Hint<'_> {
  const SIGNATURE: &'static Signature = &Signature::Variant;
}

impl<'de: 'a, 'a> Deserialize<'de> for Hint<'a> {
  fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
    deserializer.deserialize_any(HintVisitor)
  }
}

struct HintVisitor;

impl<'de> Visitor<'de> for HintVisitor {
  type Value = Hint<'de>;

  fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
    formatter.write_str("a variant")
  }

  /// zbus hands a variant over as its signature, then its value.
  fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Hint<'de>, A::Error> {
    let Some(signature) = seq.next_element::<Signature>()? else {
      return Ok(Hint::Other);
    };
    let number = |n: Option<i64>| n.map(Hint::Number);
    let hint = match signature {
      Signature::Bool => number(seq.next_element::<bool>()?.map(i64::from)),
      Signature::U8 => number(seq.next_element::<u8>()?.map(i64::from)),
      Signature::I16 => number(seq.next_element::<i16>()?.map(i64::from)),
      Signature::U16 => number(seq.next_element::<u16>()?.map(i64::from)),
      Signature::I32 => number(seq.next_element::<i32>()?.map(i64::from)),
      Signature::U32 => number(seq.next_element::<u32>()?.map(i64::from)),
      Signature::I64 => number(seq.next_element::<i64>()?),
      Signature::U64 => number(
        seq
          .next_element::<u64>()?
          .map(|n| i64::try_from(n).unwrap_or(i64::MAX)),
      ),
      Signature::Str => seq.next_element::<&str>()?.map(Hint::Text),
      _ if signature == "(iiibiiay)" => seq.next_element::<RawImage<'de>>()?.map(Hint::Image),
      _ => seq.next_element::<IgnoredAny>()?.map(|_| Hint::Other),
    };
    Ok(hint.unwrap_or(Hint::Other))
  }
}