Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions crates/app/android/res/mipmap-anydpi-v26/ic_launcher.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_bg" />
<foreground android:drawable="@mipmap/ic_launcher_foreground" />
</adaptive-icon>
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 4 additions & 0 deletions crates/app/android/res/values/ic_launcher_background.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_bg">#F7F7F5</color>
</resources>
4 changes: 2 additions & 2 deletions crates/app/assets/layout.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@

async function load(first) {
try {
const r = await fetch(baseUrl(hostIp) + '/screens', { cache: 'no-store', headers: mullion.authHeaders(hostIp, 'GET', '/screens') });
const r = await mullionFetch(baseUrl(hostIp) + '/screens', { cache: 'no-store', headers: mullion.authHeaders(hostIp, 'GET', '/screens') });
if (r.status === 401) { needPairing(); return; }
if (!r.ok) throw new Error((await r.text()).trim() || r.status);
const v = await r.json();
Expand Down Expand Up @@ -375,7 +375,7 @@
board.setAttribute('aria-busy', 'true');
try {
const body = JSON.stringify({ cells });
const r = await fetch(baseUrl(hostIp) + '/screens/layout', {
const r = await mullionFetch(baseUrl(hostIp) + '/screens/layout', {
method: 'POST', headers: Object.assign({ 'Content-Type': 'application/json' }, mullion.authHeaders(hostIp, 'POST', '/screens/layout', body)), body,
});
const text = await r.text();
Expand Down
21 changes: 20 additions & 1 deletion crates/app/assets/pair.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,27 @@
function store(cred) { try { localStorage.setItem(KEY + cred.host_id, JSON.stringify(cred)); } catch (e) { /* */ } }
function forget(hostId) { try { localStorage.removeItem(KEY + hostId); } catch (e) { /* */ } }

// A request to a Mullion host. In the apps it goes through native code
// (window.mullionNative.http, app main.rs): the Android page is https and its
// WebView blocks http:// requests as mixed content. In a browser, fetch.
// Resolves to a Response either way; network failures reject with TypeError
// and an aborted signal with AbortError, as fetch does.
async function hostFetch(url, init) {
init = init || {};
const http = window.mullionNative && window.mullionNative.http;

Check warning on line 87 in crates/app/assets/pair.js

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Prefer using an optional chain expression instead, as it's more concise and easier to read.

See more on https://sonarcloud.io/project/issues?id=th3r-dev_mullion&issues=AaHLzezQaSYgc5kovGZa&open=AaHLzezQaSYgc5kovGZa&pullRequest=22
if (!http) return fetch(url, Object.assign({ cache: 'no-store', credentials: 'omit' }, init));

Check warning on line 88 in crates/app/assets/pair.js

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Use an object spread instead of `Object.assign` eg: `{ ...foo }`.

See more on https://sonarcloud.io/project/issues?id=th3r-dev_mullion&issues=AaHLzezQaSYgc5kovGZb&open=AaHLzezQaSYgc5kovGZb&pullRequest=22
const abortErr = () => new DOMException('The request was aborted.', 'AbortError');
const call = http(init.method || 'GET', url, init.headers || {}, init.body || '');
const s = init.signal;
const r = await (s ? Promise.race([call, new Promise((_, no) => { if (s.aborted) no(abortErr()); s.addEventListener('abort', () => no(abortErr())); })]) : call);

Check warning on line 92 in crates/app/assets/pair.js

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

This statement will not be executed conditionally; only the first statement will be. The rest will execute unconditionally.

See more on https://sonarcloud.io/project/issues?id=th3r-dev_mullion&issues=AaHLzezQaSYgc5kovGZc&open=AaHLzezQaSYgc5kovGZc&pullRequest=22
if (r.error) throw new TypeError(r.error);
const empty = [101, 103, 204, 205, 304].includes(r.status);
return new Response(empty ? null : r.body, { status: r.status });
}
window.mullionFetch = hostFetch;

async function post(url, body) {
const r = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), cache: 'no-store', credentials: 'omit' });
const r = await hostFetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
let data = null;
try { data = await r.json(); } catch (e) { /* plain text error */ }
return { status: r.status, data };
Expand Down
6 changes: 3 additions & 3 deletions crates/app/assets/receiver.js
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@
}

async function postJSON(url, body) {
const r = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), cache: 'no-store', credentials: 'omit' });
const r = await mullionFetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
let data = null;
try { data = await r.json(); } catch (e) { /* plain text */ }
return { status: r.status, data };
Expand Down Expand Up @@ -289,7 +289,7 @@
const body = auth
? { device: auth.cred.device, sealed: mullionPair.sealOffer(auth.cred, auth.nonce, plain) }
: Object.assign({ device_id: deviceId() }, plain);
const resp = await fetch(`http://${hostIp}:${port}/offer`, {
const resp = await mullionFetch(`http://${hostIp}:${port}/offer`, {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body), signal: ctrl.signal,
});
Expand Down Expand Up @@ -395,7 +395,7 @@
if (outer) outer.addEventListener('abort', stop);
const t0 = performance.now();
try {
const r = await fetch(`http://${ip}:${port}/hello`, { signal: ctrl.signal, cache: 'no-store', credentials: 'omit' });
const r = await mullionFetch(`http://${ip}:${port}/hello`, { signal: ctrl.signal });
if (!r.ok) return null;
const h = await r.json();
if (!h || h.app !== 'mullion') return null;
Expand Down
5 changes: 5 additions & 0 deletions crates/app/assets/ui.css
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,11 @@ button:has(> .i), .links a { display: inline-flex; align-items: center; justify-
margin: 0; padding: 6px 10px; color: var(--ink); opacity: .55; font-size: 13px; font-weight: 600;
letter-spacing: .01em; font-variant-numeric: tabular-nums; user-select: text; }
.version:empty { display: none; }
/* The apps' update check (ui.js): a link just above the version. */
.update { position: fixed; left: max(16px, env(safe-area-inset-left)); bottom: calc(max(14px, env(safe-area-inset-bottom)) + 22px);
font-size: 13px; font-weight: 600; color: var(--accent); text-decoration: none; padding: 4px 10px; }
.update:hover, .update:focus-visible { text-decoration: underline; }
.update[hidden] { display: none; }
/* GitHub's sponsor heart colour; a non-text mark (4.7:1 light, 5.9:1 dark on --paper). */
.links .heart { color: #BF3989; }
@media (prefers-color-scheme: dark) { .links .heart { color: #E85AAD; } }
Expand Down
1 change: 1 addition & 0 deletions crates/app/assets/ui.html
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@
<div class="hint" id="hint"></div>
</div>
<p class="version" id="version"></p>
<a class="update" id="update" target="_blank" rel="noopener noreferrer" hidden></a>

Check warning on line 72 in crates/app/assets/ui.html

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Anchors must have content and the content must be accessible by a screen reader.

See more on https://sonarcloud.io/project/issues?id=th3r-dev_mullion&issues=AaHLzezVaSYgc5kovGZd&open=AaHLzezVaSYgc5kovGZd&pullRequest=22
<nav class="links" aria-label="Project">
<a href="https://github.com/th3r-dev/mullion" target="_blank" rel="noopener noreferrer"><svg class="i" aria-hidden="true"><use href="#i-github"/></svg><span>GitHub</span></a>
<a href="https://github.com/sponsors/th3r-dev" target="_blank" rel="noopener noreferrer"><svg class="i heart" aria-hidden="true"><use href="#i-heart"/></svg><span>Sponsor</span></a>
Expand Down
50 changes: 50 additions & 0 deletions crates/app/assets/ui.js
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,56 @@
// Version, bottom left: the host's when it served this page, the app's in the tablet app.
if (window.MULLION_VERSION) $('version').textContent = 'Mullion ' + window.MULLION_VERSION;

// The Windows and Android apps look for a newer beta on GitHub at start and
// every 6 hours, and offer this platform's file (Mullion.app has its own
// updater in the menu bar). The page can call GitHub itself: it is HTTPS.
const UPDATE_FILE = { windows: '-windows-x64.exe', android: '-android-arm64.apk' }[window.MULLION_APP];
// Same order as mullion_proto::version::is_newer: numbers, then a release
// beats its pre-releases, then pre-release parts (numeric ones as numbers).
function newer(a, b) {

Check failure on line 368 in crates/app/assets/ui.js

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this function to reduce its Cognitive Complexity from 19 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=th3r-dev_mullion&issues=AaHLzexyaSYgc5kovGZZ&open=AaHLzexyaSYgc5kovGZZ&pullRequest=22
const parse = (v) => {
const m = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.*)?$/.exec(String(v).trim());
return m && { core: [+m[1], +m[2], +m[3]], pre: m[4] ? m[4].split('.') : null };
};
const x = parse(a), y = parse(b);
if (!x || !y) return false;
for (let i = 0; i < 3; i++) if (x.core[i] !== y.core[i]) return x.core[i] > y.core[i];
if (!x.pre || !y.pre) return !x.pre && !!y.pre;
for (let i = 0; i < Math.max(x.pre.length, y.pre.length); i++) {
const p = x.pre[i], q = y.pre[i];
if (p === undefined) return false;
if (q === undefined) return true;
const pn = /^\d+$/.test(p), qn = /^\d+$/.test(q);
if (pn && qn && +p !== +q) return +p > +q;
if (pn !== qn) return qn;
if (!pn && p !== q) return p > q;
}
return false;
}
async function checkUpdate() {
if (!UPDATE_FILE || !window.MULLION_VERSION) return;
try {
const r = await fetch('https://api.github.com/repos/th3r-dev/mullion/releases?per_page=20', { cache: 'no-store', headers: { Accept: 'application/vnd.github+json' } });
if (!r.ok) return;
let best = null;
for (const rel of await r.json()) {
const file = !rel.draft && (rel.assets || []).find((a) => a.name.endsWith(UPDATE_FILE));
const v = String(rel.tag_name || '').replace(/^v/, '');
if (file && (!best || newer(v, best.version))) best = { version: v, url: file.browser_download_url };
}
if (!best || !newer(best.version, window.MULLION_VERSION)) return;
const link = $('update');
link.href = best.url;
link.textContent = `Get Mullion ${best.version}`;
// Beta APKs are signed with a different key each build, so Android
// will not install one over the other.
link.title = window.MULLION_APP === 'android' ? 'Remove this app first, then install the new one.' : 'Download the new version';
link.hidden = false;
} catch (e) { /* offline or rate-limited: try again later */ }
}
if (UPDATE_FILE) { setTimeout(checkUpdate, 3000); setInterval(checkUpdate, 6 * 3600 * 1000); }
window.mullionUpdate = { newer, check: checkUpdate };

// Shared with layout.js so every surface moves on the same spring.
window.mullionUI = { spring, toast };
})();
70 changes: 60 additions & 10 deletions crates/app/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,25 @@ const LAYOUT_JS: &str = include_str!("../assets/layout.js");
const UI_CSS: &str = include_str!("../assets/ui.css");
const UI_HTML: &str = include_str!("../assets/ui.html");

/// Which app this is, for the page's update check (ui.js): it offers this
/// platform's file from the newest GitHub release.
const APP_PLATFORM: &str = if cfg!(target_os = "android") {
"android"
} else if cfg!(windows) {
"windows"
} else {
"desktop"
};

/// Run `f` on its own thread and wait for it without blocking the UI.
async fn blocking<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> T {
let (tx, rx) = futures_channel::oneshot::channel();
std::thread::spawn(move || {
let _ = tx.send(f());
});
rx.await.expect("the worker thread sends before it ends")
}

fn main() {
// Desktop (the Windows viewer): our title, not "Dioxus App". The window
// icon comes from the .exe's icon resource (build.rs). Closing the window
Expand Down Expand Up @@ -54,7 +73,7 @@ fn windows_data_dir() -> Option<std::path::PathBuf> {
fn App() -> Element {
// Boot the shared scripts once the shared markup is in the document.
use_future(move || async move {
let _ = eval(&format!("window.MULLION_VERSION = {:?};", mullion_proto::version::VERSION)).await;
let _ = eval(&format!("window.MULLION_VERSION = {:?}; window.MULLION_APP = {:?};", mullion_proto::version::VERSION, APP_PLATFORM)).await;
let _ = eval(NOBLE_JS).await;
let _ = eval(PAIR_JS).await;
let _ = eval(RECEIVER_JS).await;
Expand All @@ -65,23 +84,54 @@ fn App() -> Element {
// window.mullionNative, the page's way to native code:
// - nearby(): the Nearby sweep (mullion_proto::nearby), which a page
// cannot do itself without starving its own Connect.
// - http(method, url, headers, body): a request to a Mullion host
// (mullion_proto::lanhttp). The Android page is https://dioxus.index.html
// and its WebView blocks every http:// request as mixed content, so the
// page cannot reach a host with fetch.
// - fullscreen(on), desktop only: the page's Full screen button fills only
// the web view (WebView2 does not resize the window), so this makes the
// window itself borderless full screen.
// Replies are tagged, and slow work runs on its own thread, so one sweep
// never holds up a request or the full screen toggle.
use_future(move || async move {
let fullscreen = if cfg!(feature = "desktop") { "fullscreen: (on) => dioxus.send({ fullscreen: !!on })," } else { "" };
let mut bridge = eval(&format!(
"const waiting = [];
window.mullionNative = {{ {fullscreen} nearby: () => new Promise((r) => {{ waiting.push(r); dioxus.send({{ nearby: true }}); }}) }};
for (;;) {{ const found = await dioxus.recv(); waiting.splice(0).forEach((r) => r(found)); }}"
let bridge = eval(&format!(
"const nearby = [], pending = new Map(); let next = 1;
window.mullionNative = {{ {fullscreen}
nearby: () => new Promise((r) => {{ if (nearby.push(r) === 1) dioxus.send({{ nearby: true }}); }}),
http: (method, url, headers, body) => new Promise((r) => {{ const id = next++; pending.set(id, r); dioxus.send({{ http: {{ id, method, url, headers: headers || {{}}, body: body || '' }} }}); }}),
}};
for (;;) {{
const m = await dioxus.recv();
if (m.kind === 'nearby') nearby.splice(0).forEach((r) => r(m.found));
else if (m.kind === 'http') {{ const r = pending.get(m.id); pending.delete(m.id); if (r) r(m); }}
}}"
));
while let Ok(msg) = bridge.recv::<serde_json::Value>().await {
let mut rx = bridge;
while let Ok(msg) = rx.recv::<serde_json::Value>().await {
if msg["nearby"] == true {
let (tx, rx) = futures_channel::oneshot::channel();
std::thread::spawn(move || {
let _ = tx.send(mullion_proto::nearby::sweep(47100));
spawn(async move {
let found = blocking(|| mullion_proto::nearby::sweep(47100)).await;
let _ = bridge.send(serde_json::json!({ "kind": "nearby", "found": found }));
});
}
if let Some(req) = msg.get("http").cloned() {
spawn(async move {
let id = req["id"].clone();
let reply = blocking(move || {
let s = |k: &str| req[k].as_str().unwrap_or("").to_string();
let headers: Vec<(String, String)> = req["headers"]
.as_object()
.map(|m| m.iter().filter_map(|(k, v)| v.as_str().map(|v| (k.clone(), v.to_string()))).collect())
.unwrap_or_default();
mullion_proto::lanhttp::request(&s("method"), &s("url"), &headers, s("body").as_bytes(), std::time::Duration::from_secs(8))
})
.await;
let _ = bridge.send(match reply {
Ok(r) => serde_json::json!({ "kind": "http", "id": id, "status": r.status, "body": r.body }),
Err(e) => serde_json::json!({ "kind": "http", "id": id, "error": e }),
});
});
let _ = bridge.send(rx.await.unwrap_or_default());
}
#[cfg(feature = "desktop")]
if let Some(on) = msg["fullscreen"].as_bool() {
Expand Down
Loading
Loading