1// File dialogs on Linux through the desktop portal (PLAN.md,2// F6c): org.freedesktop.portal.FileChooser over the session bus, which3// every desktop answers with its own dialog, inside a Flatpak too. A call4// gives a request object at once; its Response signal, later, gives the5// chosen files as URIs. With no session bus or no portal, a dialog is6// answered at once with no files. The desktop's wish for less motion is7// read from org.freedesktop.portal.Settings (F11e), its SettingChanged8// signal telling a change. Reached once a program installs files or9// screen readers (window.alloy's `install_files`, `install_access`).1011import std::string;12import std::vector;13import std::option;14import std::dispose;15import std::fs;16import pkg::alloy::dbus;1718import window;1920pub type Portal : Disposable = struct {21 pub bus: Option<Connection>,22 pub tried: bool,23 // the requests waiting for their Response, by object path24 pub waiting: Vector<Waiting>,25 pub tokens: u32,26 // whether the desktop asks for less motion, once a signal said27 pub motion: Option<bool> = ::None,28};2930pub type Waiting = struct {31 pub path: String,32 pub request: u64,33};3435pub fn Portal::empty() -> Portal => Portal {36 .bus = ::None,37 .tried = false,38 .waiting = Vector<Waiting>::empty(),39 .tokens = 040};4142pub fn dispose(self p: &var Portal) {43 p.bus.dispose();44}4546// The session bus's socket while connected, for the loop to poll.47pub fn fd(self p: &Portal) -> Option<i32> {48 if (p.bus is ::Some |&bus|) {49 return ::Some(bus.fd());50 }51 return ::None;52}5354// Joins the session bus, the first time, for the portal's answers and55// its settings' changes.56fn connect(self p: &var Portal) {57 if (p.tried) {58 return;59 }60 p.tried = true;61 if (Connection::session() is ::Some |move bus|) {62 var b = move bus;63 b.add_match(&"type='signal',interface='org.freedesktop.portal.Request',member='Response'");64 b.add_match(65 &"type='signal',interface='org.freedesktop.portal.Settings',member='SettingChanged'"66 );67 p.bus = ::Some(move b);68 }69}7071// Whether the desktop asks for less motion: GNOME's animations turned72// off, or KDE's made to take no time; false with no portal.73pub fn reduced_motion(self p: &var Portal) -> bool {74 p.connect();75 if (p.setting(&GNOME, &ANIMATIONS) is ::Some |&v|) {76 return v.as_integer() == 0;77 }78 if (p.setting(&KDE, &DURATION) is ::Some |&v|) {79 return no_time(&v);80 }81 return false;82}8384const GNOME: [u8 : 27] = "org.gnome.desktop.interface";85const ANIMATIONS: [u8 : 17] = "enable-animations";86const KDE: [u8 : 22] = "org.kde.kdeglobals.KDE";87const DURATION: [u8 : 23] = "AnimationDurationFactor";8889// Whether KDE's animation factor, a number or its text, is 0.90fn no_time(v: &Value) -> bool => match (v) {91 ::Double |d| d == 0.0;92 ::Text |&t| t.view() == "0" || t.view() == "0.0";93 ::Variant |&inner| no_time(&inner);94 else false;95};9697// A setting the portal reads, its variants opened.98fn setting(self p: &var Portal, namespace: &[u8], key: &[u8]) -> Option<Value> {99 const bus = if (p.bus is ::Some |&var b|) &var b else {100 return ::None;101 };102 var body = Vector<Value>::empty();103 body.push(Value::text(&namespace));104 body.push(Value::text(&key));105 const reply = bus.call_message(106 Message::call(107 &"org.freedesktop.portal.Desktop",108 &"/org/freedesktop/portal/desktop",109 &"org.freedesktop.portal.Settings",110 &"Read",111 &"ss",112 move body113 ),114 1000115 );116 if (reply is ::Some |&r| && !r.is_error() && r.body.length() > 0) {117 var v = &r.body.get(0);118 while (v is ::Variant |&inner|) {119 v = &inner;120 }121 return ::Some(copy v);122 }123 return ::None;124}125126// What a SettingChanged signal says of less motion, if it is about it.127fn motion_of(m: &Message) -> Option<bool> {128 if (m.body.length() < 3) {129 return ::None;130 }131 const namespace = &m.body.get(0).as_text();132 const key = &m.body.get(1).as_text();133 if (namespace == GNOME && key == ANIMATIONS) {134 return ::Some(m.body.get(2).as_integer() == 0);135 }136 if (namespace == KDE && key == DURATION) {137 return ::Some(no_time(&m.body.get(2)));138 }139 return ::None;140}141142// Shows the dialog through the portal; false when there is none, the143// window then answering with no files.144pub fn ask(self p: &var Portal, asked: &DialogRequest) -> bool {145 p.connect();146 const bus = if (p.bus is ::Some |&var b|) &var b else {147 return false;148 };149 p.tokens += 1;150 const d = &asked.dialog;151 var options = Vector<Value>::empty();152 options.push(Value::entry(153 Value::text(&"handle_token"),154 Value::variant(Value::Text(f"alloy{p.tokens}"))155 ));156 options.push(Value::entry(Value::text(&"modal"), Value::variant(Value::Boolean(true))));157 if (!asked.save) {158 options.push(Value::entry(159 Value::text(&"multiple"),160 Value::variant(Value::Boolean(d.multiple))161 ));162 } else if (d.name.length() > 0) {163 options.push(Value::entry(164 Value::text(&"current_name"),165 Value::variant(Value::Text(copy d.name))166 ));167 }168 if (d.filters.length() > 0) {169 // a(sa(us)): each filter's name and its glob patterns (0)170 var filters = Vector<Value>::empty();171 for (d.filters.view()) |&filter| {172 var patterns = Vector<Value>::empty();173 for (filter.patterns.view()) |&pattern| {174 var pair = Vector<Value>::empty();175 pair.push(Value::Uint32(0));176 pair.push(Value::Text(copy pattern));177 patterns.push(Value::Struct(move pair));178 }179 var f = Vector<Value>::empty();180 f.push(Value::Text(copy filter.name));181 f.push(Value::Array(move patterns));182 filters.push(Value::Struct(move f));183 }184 options.push(Value::entry(185 Value::text(&"filters"),186 Value::variant(Value::Array(move filters))187 ));188 }189 var body = Vector<Value>::empty();190 body.push(Value::text(&"")); // no parent window191 const title: &[u8] = if (192 d.title.length() > 0193 ) &d.title.view() else if (asked.save) &"Save" else &"Open";194 body.push(Value::text(&title));195 body.push(Value::Array(move options));196 const reply = bus.call(197 &"org.freedesktop.portal.Desktop",198 &"/org/freedesktop/portal/desktop",199 &"org.freedesktop.portal.FileChooser",200 if (asked.save) &"SaveFile" else &"OpenFile",201 &"ssa{sv}",202 move body203 );204 if (reply is ::Some |&r|) {205 if (!r.is_error() && r.body.length() > 0) {206 p.waiting.push(Waiting {207 .path = String::from(&r.body.get(0).as_text()),208 .request = asked.id209 });210 return true;211 }212 }213 return false;214}215216// Whether answers wait, read while calling.217pub fn has_waiting(self p: &Portal) -> bool {218 if (p.bus is ::Some |&bus|) {219 return bus.has_received();220 }221 return false;222}223224// Notes what the bus sent of the settings' changes, the rest let go,225// for a window showing no dialogs.226pub fn read_settings(self p: &var Portal) {227 const bus = if (p.bus is ::Some |&var b|) &var b else {228 return;229 };230 while (bus.receive() is ::Some |&m|) {231 if (m.kind is ::Signal && m.member.view() == "SettingChanged") {232 if (motion_of(&m) is ::Some |reduced|) {233 p.motion = ::Some(reduced);234 }235 }236 }237}238239// The dialogs answered since last asked, from what the bus sent.240pub fn answers(self p: &var Portal) -> Vector<Chosen> {241 var out = Vector<Chosen>::empty();242 const bus = if (p.bus is ::Some |&var b|) &var b else {243 return move out;244 };245 while (bus.receive() is ::Some |&m|) {246 if (m.kind is ::Signal && m.member.view() == "SettingChanged") {247 if (motion_of(&m) is ::Some |reduced|) {248 p.motion = ::Some(reduced);249 }250 continue;251 }252 if (!(m.kind is ::Signal) || m.member.view() != "Response" || m.body.length() < 2) {253 continue;254 }255 for ([..p.waiting.length()]) |k| {256 if (p.waiting.get(k).path.view() == m.path.view()) {257 const request = p.waiting.remove(k).request;258 var chosen = Chosen { .request = request, .files = Vector<ChosenFile>::empty() };259 // 0: chosen; 1: cancelled; 2: failed260 if (m.body.get(0).as_integer() == 0) {261 if (m.body.get(1).lookup(&"uris") is ::Some |&uris|) {262 for (uris.items()) |&uri| {263 if (file_of_uri(&uri.as_text()) is ::Some |move file|) {264 chosen.files.push(move file);265 }266 }267 }268 }269 out.push(move chosen);270 break;271 }272 }273 }274 return move out;275}276277// A `file://` URI's file, its path's %xx escapes undone.278pub fn file_of_uri(uri: &[u8]) -> Option<ChosenFile> {279 if (uri.length() < 8 || uri[..7] != "file://") {280 return ::None;281 }282 // after the host, empty or `localhost`283 var at: u64 = 7;284 while (at < uri.length() && uri[at] != '/') {285 at += 1;286 }287 var path = String::empty();288 var k = at;289 while (k < uri.length()) {290 if (uri[k] == '%' && k + 2 < uri.length()) {291 path.push((hex(uri[k + 1]) << 4) | hex(uri[k + 2]));292 k += 3;293 } else {294 path.push(uri[k]);295 k += 1;296 }297 }298 if (path.length() == 0) {299 return ::None;300 }301 return ::Some(ChosenFile::at(PathStyle::Unix, &path.view()));302}303304fn hex(c: u8) -> u8 {305 if (c >= '0' && c <= '9') {306 return c - '0';307 }308 if (c >= 'a' && c <= 'f') {309 return c - 'a' + 10;310 }311 if (c >= 'A' && c <= 'F') {312 return c - 'A' + 10;313 }314 return 0;315}316317// The files a `text/uri-list` names, one URI a line, `#` lines comments.318pub fn files_of_uri_list(text: &[u8]) -> Vector<ChosenFile> {319 var out = Vector<ChosenFile>::empty();320 var start: u64 = 0;321 while (start < text.length()) {322 var end = start;323 while (end < text.length() && text[end] != '\n') {324 end += 1;325 }326 var line = &text[start..end];327 if (line.length() > 0 && line[line.length() - 1] == '\r') {328 line = &line[..line.length() - 1];329 }330 if (line.length() > 0 && line[0] != '#') {331 if (file_of_uri(&line) is ::Some |move file|) {332 out.push(move file);333 }334 }335 start = end + 1;336 }337 return move out;338}