Site: the editor and the installer as an app that works without internet (Android too): sw.js, manifest, Install the app; firmware unchanged (2.6)

This commit is contained in:
isod89 committed 2026-10-11 14:58:33 -04:00
1 parent 4365a1d007
commit cb6dedcec2
22 files changed
+480 -24

No files matched your search

+1 -1
View File
@@ -20,7 +20,7 @@ Le guide complet, chaque bouton, combinaison et page, avec un aide-mémoire d'un
2. Dans **Chrome ou Edge**, branche le FM-1 en USB (câble de données, directement, sans hub).
3. **INSTALL**, autorise le MIDI, attends *Done*. Garde la fenêtre noire ouverte jusque-là.
L'éditeur web : `http://localhost:8766/webapp/editor/` (ou **`OPEN-EDITOR.bat`**). Hors ligne (2.6) : le lien *Download the editor* (sous Connect, ou sur la page de l'installateur) enregistre l'éditeur en un seul fichier ; double-clique-le, il s'ouvre dans Chrome ou Edge sans internet (Chrome demande une fois d'autoriser le MIDI).
L'éditeur web : `http://localhost:8766/webapp/editor/` (ou **`OPEN-EDITOR.bat`**). Hors ligne (2.6) : le lien *Download the editor* (sous Connect, ou sur la page de l'installateur) enregistre l'éditeur en un seul fichier ; double-clique-le, il s'ouvre dans Chrome ou Edge sans internet (Chrome demande une fois d'autoriser le MIDI). Sur Android (ou pour l'avoir comme une application) : ouvre une fois l'éditeur en ligne avec internet, puis *Install the app* ; l'app SLOOP marche ensuite sans internet, l'installateur aussi.
## Un beat en soixante secondes
+3 -1
View File
@@ -1040,7 +1040,9 @@ SLOOP 2.5: the editor's **Drum synth** page changes every value of a synthesised
Open it from the [installer page](https://isod89.github.io/sloop-fm1/), the [editor link](https://isod89.github.io/sloop-fm1/webapp/editor/), or **`OPEN-EDITOR.bat`**, in **Chrome or Edge** with the FM-1 on USB, and press **Connect** (allow MIDI). It follows the device live: turn a knob on the FM-1, the editor moves. It looks like the FM-1: the black screen, the four track colours, the FM-1's own pixel font. The language button switches English / Japanese.
**Offline (2.6).** *Download the editor* (under Connect, or on the installer page) saves the whole editor as one file, `sloop-editor-2.6.html`, also attached to each [release](https://github.com/isod89/sloop-fm1/releases). Double-click it: it opens in Chrome or Edge without internet (Chrome asks once to allow MIDI) and works as the online one. Its sound library (kept in the browser) is its own, apart from the online editor's: move sounds between them with Export / Import, or a backup.
**Offline (2.6).** *Download the editor* (under Connect, or on the installer page) saves the whole editor as one file for a computer, `sloop-editor-2.6.html`, also attached to each [release](https://github.com/isod89/sloop-fm1/releases). Double-click it: it opens in Chrome or Edge without internet (Chrome asks once to allow MIDI) and works as the online one. Its sound library (kept in the browser) is its own, apart from the online editor's: move sounds between them with Export / Import, or a backup.
**As an app, also on Android (2.6).** Open the [online editor](https://isod89.github.io/sloop-fm1/webapp/editor/) or the installer once with internet, then *Install the app* (under Connect, or on the installer page; or Chrome's menu → *Install app* / *Add to Home screen*). From then on the SLOOP app opens the editor without internet, and its link to the installer works offline too (with the firmware it installs). It stays the online site kept by the browser, so it uses the same sound library as the online editor, and it takes each new SLOOP version by itself the next time it opens online. On Android, use the app rather than the downloaded file: Chrome on Android does not allow MIDI in a downloaded file.
**Layout:** the side bar has the pages in three groups — **Track** (Sound, Sequencer, Tracks, Song), **Sounds** (Library, Samples, Drum kit, Drum synth), **Device** (Projects, Settings) — and the connection. On top: the page title, the messages, and on the Track pages the **four tracks** (number, sound, engine): click one to select it. With the side bar focused, the arrow keys move between pages.
+11 -2
View File
@@ -52,7 +52,7 @@ SLOOP turns the FM-1 into a four-track groovebox you play live: **three synths a
- **Step entry from a MIDI keyboard:** on the STEP page, the notes your keyboard plays write the step, as the FM-1's keys do.
- **Program Change, 1/4D delay, REV / ECHO THROW** (FX + OCT− / OCT+), after Felucca 1.5.1.
- **Erase a saved loop:** SAVE → PROJECT → ERASE (KNOB 2) empties a project slot, song section A–D. Thanks to the viewer who asked!
- **The web editor offline:** *Download the editor* saves it as one file that runs in Chrome or Edge without internet.
- **The web editor offline:** *Download the editor* saves it as one file that runs in Chrome or Edge without internet, or *Install the app* (Android too): the editor and the installer then open without internet.
- **MIDI IN on one channel** (GLO → MIDI 2 → IN = CH 1 … 16), for a sequencer driving other gear on the same cable.
- **A bolder screen:** Terminus Bold, all in capitals.
- **No more clicks** when loading a sound over held notes, or when a filter (track, drums, master FILT) starts to close.
@@ -151,6 +151,13 @@ The full list, and what came in 2.0, 2.1 and 2.2: [SLOOP.md](SLOOP.md#new-in-23)
<p align="center"><sub>The piano roll: draw, delete and stretch notes and chords with the mouse; Export MIDI / Import MIDI next to it.</sub></p>
<p align="center"><img src="assets/screens/editor-drums.png" alt="SLOOP web editor: the drum track" width="760"></p>
<p align="center"><sub>The web editor: the drum track as a 16-lane grid, with levels and ratchets.</sub></p>
<p align="center"><img src="assets/screens/editor-chop.png" alt="SLOOP web editor: CHOP" width="760"></p>
<p align="center"><sub>CHOP: a 20 s recording cut into 16 chops, 8 kept, fitted to the slot.</sub></p>
## Features
@@ -370,7 +377,9 @@ On USB the FM-1 is also an **audio input named "Felucca"**: 44.1 or 48 kHz (2.5:
Open it from the [installer page](https://isod89.github.io/sloop-fm1/) (or the [editor link](https://isod89.github.io/sloop-fm1/webapp/editor/)) in Chrome or Edge, with the FM-1 on USB, and press **Connect**. It follows the device live: turn a knob on the FM-1 and the editor moves.
**Offline (2.6).** *Download the editor* (under Connect, or on the installer page) saves the whole editor as one file, `sloop-editor-2.6.html`, also attached to each [release](https://github.com/isod89/sloop-fm1/releases). Double-click it: it opens in Chrome or Edge without internet (Chrome asks once to allow MIDI) and works as the online one. Its sound library (kept in the browser) is its own, apart from the online editor's: move sounds between them with Export / Import, or a backup.
**Offline (2.6).** *Download the editor* (under Connect, or on the installer page) saves the whole editor as one file for a computer, `sloop-editor-2.6.html`, also attached to each [release](https://github.com/isod89/sloop-fm1/releases). Double-click it: it opens in Chrome or Edge without internet (Chrome asks once to allow MIDI) and works as the online one. Its sound library (kept in the browser) is its own, apart from the online editor's: move sounds between them with Export / Import, or a backup.
**As an app, also on Android (2.6).** Open the [online editor](https://isod89.github.io/sloop-fm1/webapp/editor/) or the installer once with internet, then *Install the app* (under Connect, or on the installer page; or Chrome's menu → *Install app* / *Add to Home screen*). From then on the SLOOP app opens the editor without internet, and its link to the installer works offline too (with the firmware it installs). It stays the online site kept by the browser, so it uses the same sound library as the online editor, and it takes each new SLOOP version by itself the next time it opens online. On Android, use the app rather than the downloaded file: Chrome on Android does not allow MIDI in a downloaded file.
- **Sound** — every parameter of the selected track, the engines and the presets; on an FM6 track the **FM6** panel: every operator, the bank, **Import / Export SysEx** (DX7 voices and banks).
- **Sequencer** — the steps, as tiles or as a **piano roll**, and the track's length (1–64 steps); on the drum track a grid of 16 sounds × the steps, with levels and ratchets, and the kit. Click a step for its nudge, parameter locks and fill condition. **Export MIDI / Import MIDI**: the selected track as a MIDI file, and back.
+4 -2
View File
@@ -29,7 +29,7 @@ SLOOP is free and open source (GPL-3.0), based on [Felucca](https://github.com/h
- **Step entry from a MIDI keyboard.** On the STEP page (SEQ tapped), the notes your keyboard plays on the selected track now write the cursor's step, as the FM-1's keys do (a chord: the notes held together; let go: the next step). Its channel must be the selected track's (GLO → MIDI); if it plays another track, the screen says *MIDI PLAYS TRACK n*. SEQ + an empty step also takes the last note or chord played on the keyboard. And when you record (REC armed or recording) with a keyboard that plays another track than the one recording, the screen says *MIDI PLAYS TRACK n* once, so a take that stays empty is explained. Thanks to the viewers who reported it!
- **From Felucca 1.5.1:** **Program Change** loads a track's sound from a keyboard or a sequencer (the n-th sound of the PRESETS list; kit n on the drum channel; after @renebohne's PR #179), the delay's TIME gets **1/4D**, and **REV THROW / ECHO THROW**: hold FX + OCT− (reverb) or OCT+ (echo) and every send goes full while held, the song's settings untouched.
- **Erase a saved loop.** SAVE → PROJECT, KNOB 2 **ERASE** (GO, the song stopped) empties the project slot KNOB 1 picks, that is song section A–D: its section key goes dark, and the song's steps that played it are taken out. Your working loop is not touched. Thanks to the viewer who asked!
- **The web editor offline.** *Download the editor* (under Connect, or on the installer page) saves it as one file: double-click it, it runs in Chrome or Edge without internet.
- **The web editor offline.** *Download the editor* (under Connect, or on the installer page) saves it as one file: double-click it, it runs in Chrome or Edge without internet. Or *Install the app* (Android too): opened once online, the editor and the installer then work without internet.
- **MIDI IN on one channel.** GLO → MIDI 2 (or SYSTEM) → IN = CH 1 … CH 16: SLOOP answers that channel only, on the selected track (for a sequencer whose other channels drive other gear).
- **No more clicks** when you load a sound (factory or user preset) over notes that are still sounding: they now fade out with their own sound. And none when the track FILTER, the drum track's filter (FX + KNOB 4) or the master FILT start to close (their low-pass used to start from silence under the sound: a crack). Thanks to the users who reported crackles!
- **A cleaner output, in headphones too.** The master limiter now looks 0.7 ms ahead: a hot kick or bass is already turned down when it arrives, instead of its first samples going through the output's soft clipper (a crackle on the beats with MASTER turned up, clearest in headphones). Below the limiter nothing changes; the output is 0.7 ms later. A held loud bass keeps one gain (the limiter waits 35 ms before letting go), so it does not buzz or whistle. And the kicks of the synthesised kits (808, 909…) no longer whistle under their tail: their level glided in steps that jumped a little at every audio block (0.7 ms), a faint high tone (in 2.5 too). Thanks to the user who heard it! Punch-in **FREEZE** now holds the sound at the level the mix had (a big reverb jumped up to +11 dB and could distort), and a sound loaded over held notes fades over 5.8 ms (2.9 before: no thump on a bass).
@@ -470,7 +470,9 @@ The **SONG screen** (SAVE tapped on TRACKS, or SAVE + key 16) shows the chain an
Open it from the installer page, or with **`OPEN-EDITOR.bat`** (`http://localhost:8766/webapp/editor/`), in Chrome or Edge with the FM-1 on USB, and press **Connect**. It follows the device live (turn a knob on the FM-1, the editor moves).
**Offline (2.6).** *Download the editor* (under Connect, or on the installer page) saves the whole editor as one file, `sloop-editor-2.6.html`, also attached to each [release](https://github.com/isod89/sloop-fm1/releases). Double-click it: it opens in Chrome or Edge without internet (Chrome asks once to allow MIDI) and works as the online one. Its sound library (kept in the browser) is its own, apart from the online editor's: move sounds between them with Export / Import, or a backup.
**Offline (2.6).** *Download the editor* (under Connect, or on the installer page) saves the whole editor as one file for a computer, `sloop-editor-2.6.html`, also attached to each [release](https://github.com/isod89/sloop-fm1/releases). Double-click it: it opens in Chrome or Edge without internet (Chrome asks once to allow MIDI) and works as the online one. Its sound library (kept in the browser) is its own, apart from the online editor's: move sounds between them with Export / Import, or a backup.
**As an app, also on Android (2.6).** Open the [online editor](https://isod89.github.io/sloop-fm1/webapp/editor/) or the installer once with internet, then *Install the app* (under Connect, or on the installer page; or Chrome's menu → *Install app* / *Add to Home screen*). From then on the SLOOP app opens the editor without internet, and its link to the installer works offline too (with the firmware it installs). It stays the online site kept by the browser, so it uses the same sound library as the online editor, and it takes each new SLOOP version by itself the next time it opens online. On Android, use the app rather than the downloaded file: Chrome on Android does not allow MIDI in a downloaded file.
It looks like the FM-1 (its black screen, the four track colours, its own Terminus font). The side bar has the pages — **Track**: Sound, Sequencer, Tracks; **Sounds**: Library, Samples, Drum kit; **Device**: Projects, Settings — and the FM-1's connection. On top: the page, the messages and the **four tracks** (number, sound, engine): click one to edit it; the selected track's colour is the editor's.
+22 -2
View File
@@ -8,6 +8,7 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SLOOP Editor</title>
<!--PWA--><link rel="manifest" href="../sloop.webmanifest"><meta name="theme-color" content="#000000"><link rel="icon" href="../icon-192.png"><!--/PWA-->
<style>
/* SLOOP 2.4 editor: the FM-1's screen on a big display. Black, the four track colours, the device's own
Terminus pixel font (tools/gen_webfont.py, inlined: the editor also runs from file://), 16 px and 32 px only
@@ -470,6 +471,7 @@
<span id="mock" hidden data-t="mock"></span>
<button id="connect" class="pri" data-t="connect" data-ic="port_usb_c"></button>
<div class="links"><a class="dim" href="../installer/" data-t="installer"></a><button class="lang" id="lang"></button></div>
<button id="install" class="pri" data-t="install" hidden></button>
<!--DL--><a class="dim" id="offline" href="sloop-editor.html" download="sloop-editor-2.6.html" data-t="offline"></a><!--/DL-->
</div>
</aside>
@@ -3567,7 +3569,8 @@ const TEXT = {
loadedUser: "読み込みました: ", reloaded: "本体で音色が変わったので読み直しました", readingBank: "スロットを読み込み中",
badEngine: "このファームウェアにないエンジンです: ", flashFail: "書き込みに失敗しました(rc {rc})",
installer: "SLOOP インストーラー",
offline: "エディタをダウンロード(オフライン用:Chrome / Edge で開く)",
offline: "エディタをダウンロード(パソコンでオフライン用:Chrome / Edge で開く)",
install: "アプリとしてインストール(オフラインで使える・Android も)",
tabSeq: "シーケンサー", tabTracks: "トラック", tabSettings: "設定",
navTrack: "トラック", navSounds: "サウンド", navDevice: "本体", tabKits: "ドラムキット", fm1: "FM-1",
stepList: "ステップ一覧(音名を入力)", stepsOf: "{n} ステップ", fontCredit: "フォント: Terminus(SIL OFL 1.1)",
@@ -3767,7 +3770,8 @@ const TEXT = {
loadedUser: "Loaded ", reloaded: "The sound changed on the device: read again", readingBank: "Reading the slots",
badEngine: "This firmware has no such engine: ", flashFail: "Write failed (rc {rc})",
installer: "SLOOP installer",
offline: "Download the editor (offline: open it in Chrome or Edge)",
offline: "Download the editor (offline on a computer: open it in Chrome or Edge)",
install: "Install the app (works offline, Android too)",
tabSeq: "Sequencer", tabTracks: "Tracks", tabSettings: "Settings",
navTrack: "Track", navSounds: "Sounds", navDevice: "Device", tabKits: "Drum kit", fm1: "FM-1",
stepList: "Step list (type note names)", stepsOf: "{n} steps", fontCredit: "Font: Terminus (SIL OFL 1.1)",
@@ -7602,6 +7606,22 @@ showTab(tab);
libInit();
if (!MOCK && !navigator.requestMIDIAccess) sayK("nomidi");
})();
/* the site without internet (SLOOP 2.6, webapp/sw.js): opened once online, the editor and the installer work
* offline too, still on https (Android: a downloaded file opens as content://, where Chrome refuses MIDI) */
/*PWA*/if ("serviceWorker" in navigator && /^https?:$/.test(location.protocol))
navigator.serviceWorker.register("../sw.js").catch(() => {});
{
let ask = null;
window.addEventListener("beforeinstallprompt", (e) => { e.preventDefault(); ask = e; $("install").hidden = false; });
window.addEventListener("appinstalled", () => { ask = null; $("install").hidden = true; });
$("install").addEventListener("click", async () => {
if (!ask) return;
ask.prompt();
await ask.userChoice.catch(() => {});
ask = null;
$("install").hidden = true;
});
}/*/PWA*/
</script>
</body>
</html>
+9 -4
View File
@@ -8,6 +8,7 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SLOOP Editor</title>
<style>
/* SLOOP 2.4 editor: the FM-1's screen on a big display. Black, the four track colours, the device's own
Terminus pixel font (tools/gen_webfont.py, inlined: the editor also runs from file://), 16 px and 32 px only
@@ -470,8 +471,7 @@
<span id="mock" hidden data-t="mock"></span>
<button id="connect" class="pri" data-t="connect" data-ic="port_usb_c"></button>
<div class="links"><a class="dim" href="https://isod89.github.io/sloop-fm1/webapp/installer/" target="_blank" rel="noopener" data-t="installer"></a><button class="lang" id="lang"></button></div>
</div>
</div>
</aside>
<main class="main">
@@ -3567,7 +3567,8 @@ const TEXT = {
loadedUser: "読み込みました: ", reloaded: "本体で音色が変わったので読み直しました", readingBank: "スロットを読み込み中",
badEngine: "このファームウェアにないエンジンです: ", flashFail: "書き込みに失敗しました(rc {rc})",
installer: "SLOOP インストーラー",
offline: "エディタをダウンロード(オフライン用:Chrome / Edge で開く)",
offline: "エディタをダウンロード(パソコンでオフライン用:Chrome / Edge で開く)",
install: "アプリとしてインストール(オフラインで使える・Android も)",
tabSeq: "シーケンサー", tabTracks: "トラック", tabSettings: "設定",
navTrack: "トラック", navSounds: "サウンド", navDevice: "本体", tabKits: "ドラムキット", fm1: "FM-1",
stepList: "ステップ一覧(音名を入力)", stepsOf: "{n} ステップ", fontCredit: "フォント: Terminus(SIL OFL 1.1)",
@@ -3767,7 +3768,8 @@ const TEXT = {
loadedUser: "Loaded ", reloaded: "The sound changed on the device: read again", readingBank: "Reading the slots",
badEngine: "This firmware has no such engine: ", flashFail: "Write failed (rc {rc})",
installer: "SLOOP installer",
offline: "Download the editor (offline: open it in Chrome or Edge)",
offline: "Download the editor (offline on a computer: open it in Chrome or Edge)",
install: "Install the app (works offline, Android too)",
tabSeq: "Sequencer", tabTracks: "Tracks", tabSettings: "Settings",
navTrack: "Track", navSounds: "Sounds", navDevice: "Device", tabKits: "Drum kit", fm1: "FM-1",
stepList: "Step list (type note names)", stepsOf: "{n} steps", fontCredit: "Font: Terminus (SIL OFL 1.1)",
@@ -7602,6 +7604,9 @@ showTab(tab);
libInit();
if (!MOCK && !navigator.requestMIDIAccess) sayK("nomidi");
})();
/* the site without internet (SLOOP 2.6, webapp/sw.js): opened once online, the editor and the installer work
* offline too, still on https (Android: a downloaded file opens as content://, where Chrome refuses MIDI) */
</script>
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

+24 -2
View File
@@ -6,6 +6,7 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SLOOP installer</title>
<!--PWA--><link rel="manifest" href="../sloop.webmanifest"><meta name="theme-color" content="#000000"><link rel="icon" href="../icon-192.png"><!--/PWA-->
<style>
:root { --bg: #000; --fg: #f2f2f2; --dim: #8a8a92; --tile: #16161a; --line: #2a2a30;
--blue: #287cff; --green: #1ecc70; --yellow: #ffc618; --orange: #ff621a; --red: #ff2c34; }
@@ -41,6 +42,8 @@
progress::-moz-progress-bar { background: var(--orange); }
pre { color: var(--dim); font-size: 11px; white-space: pre-wrap; margin-top: 12px; max-height: 160px; overflow: auto; }
hr { border: 0; border-top: 1px solid var(--line); margin: 28px 0 18px; }
[hidden] { display: none !important; }
button.ed { font: inherit; color: var(--fg); border: 0; cursor: pointer; }
.ed { display: inline-block; margin: 8px 0 0; padding: 10px 14px; background: var(--tile); text-decoration: none; }
details { margin: 22px 0 0; } summary { cursor: pointer; font-weight: 600; }
button#stock-go { font: 600 14px/1 inherit; font-family: inherit; background: var(--tile); color: var(--fg); border: 1px solid var(--line);
@@ -88,6 +91,7 @@
<pre id="log"></pre>
<a class="ed" href="../editor/" data-t="editor"></a>
<p class="small"><a href="../editor/sloop-editor.html" download="sloop-editor-2.6.html" data-t="edOffline"></a></p>
<p><button id="app" class="ed" hidden data-t="appInstall"></button></p>
<hr>
<p class="small" data-t="direct"></p>
<p class="small" data-t="beta"></p>
@@ -411,7 +415,8 @@ const TEXT = {
warn: "書き込み中は USB を抜かないでください。",
install: "インストール", other: "English",
editor: "エディタ(インストール後、パソコンから音色やシーケンスを編集)",
edOffline: "エディタをダウンロード(インターネットなしで使う:ファイルを Chrome / Edge で開く)",
edOffline: "エディタをダウンロード(パソコンでインターネットなしで使う:ファイルを Chrome / Edge で開く)",
appInstall: "アプリとしてインストール(エディタとインストーラーがオフラインで使える・Android も)",
direct: "USB ケーブルはパソコンに直接つないでください。Probe や Transporter などの機材は不要です。",
brick: "万一インストールに失敗して起動しなくなった場合は、復旧に Transporter が必要です:",
beta: "これはベータ版で、不安定な場合があります。このカスタムファームウェアを使ったことで FM-1 が壊れたり不具合が起きたりしても、作者は一切の責任を負いません。自己責任でお使いください。",
@@ -446,7 +451,8 @@ const TEXT = {
warn: "Do not unplug the USB cable while writing.",
install: "Install", other: "日本語",
editor: "Editor (after installing: edit sounds and sequences from the computer)",
edOffline: "Download the editor to use it without internet (open the file in Chrome or Edge)",
edOffline: "Download the editor to use it without internet on a computer (open the file in Chrome or Edge)",
appInstall: "Install the app (the editor and the installer offline, Android too)",
direct: "Connect the USB cable directly to the computer. No probe or Transporter is needed.",
brick: "If an install fails and the FM-1 no longer starts, recovering it needs a Transporter:",
beta: "This is a beta and may be unstable. The author accepts no responsibility if your FM-1 is damaged or misbehaves because of this custom firmware. Use it at your own risk.",
@@ -488,6 +494,22 @@ function applyLang() {
}
$("lang").addEventListener("click", () => { lang = lang === "ja" ? "en" : "ja"; applyLang(); });
applyLang();
/* the site without internet (SLOOP 2.6, webapp/sw.js): opened once online, the installer, the firmware and the
* editor work offline too, still on https (Android: a downloaded file opens as content://, where Chrome refuses MIDI) */
if ("serviceWorker" in navigator && /^https?:$/.test(location.protocol))
navigator.serviceWorker.register("../sw.js").catch(() => {});
{
let ask = null;
window.addEventListener("beforeinstallprompt", (e) => { e.preventDefault(); ask = e; $("app").hidden = false; });
window.addEventListener("appinstalled", () => { ask = null; $("app").hidden = true; });
$("app").addEventListener("click", async () => {
if (!ask) return;
ask.prompt();
await ask.userChoice.catch(() => {});
ask = null;
$("app").hidden = true;
});
}
const sayK = (k, arg = "") => { lastKey = k; lastArg = arg; $("status").textContent = t(k) + arg; };
const say = (txt) => { lastKey = null; $("status").textContent = txt; };
const log = (t) => { $("log").textContent += t + "\n"; };
+31
View File
@@ -0,0 +1,31 @@
{
"name": "SLOOP",
"short_name": "SLOOP",
"id": "editor/",
"start_url": "editor/",
"scope": "./",
"display": "standalone",
"background_color": "#000000",
"theme_color": "#000000",
"description": "SLOOP for the M-VAVE FM-1: the editor and the installer, also without internet",
"icons": [
{
"src": "icon-192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "any"
},
{
"src": "icon-512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "any"
},
{
"src": "icon-maskable-512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable"
}
]
}
+56
View File
@@ -0,0 +1,56 @@
// SPDX-License-Identifier: GPL-3.0-only
// SLOOP 2.6: the site without internet (webapp/sw.js, made by web/make_site.py). Opened once online, the
// installer, the editor and the firmware they install are kept here; offline they come from this copy, still on
// https, so Web MIDI asks as usual (a downloaded file on Android opens as content://, where Chrome refuses MIDI).
// Online the network always wins (the page as published, never an old one); the copy is only the fallback.
// A new site (any file changed) is a new sw.js: the new copy replaces the old one.
const STAMP = "2.6-4979302c6d05"; // version + a hash of the files
const CACHE = "sloop-site-" + STAMP;
const FILES = ["../firmware/sloop-2.6.fwsc", "editor/", "editor/FUKIAI-LICENSE.txt", "editor/fukiai.ttf", "icon-192.png", "icon-512.png", "icon-maskable-512.png", "installer/", "sloop.webmanifest"]; // relative to this file
const KEEP = new Set(FILES.map((f) => new URL(f, self.location).href));
const key = (url) => { // the copy's name of a request: no query, index.html = the folder
const u = new URL(url);
u.search = "";
u.hash = "";
if (u.pathname.endsWith("/index.html")) u.pathname = u.pathname.slice(0, -10);
return u.href;
};
self.addEventListener("install", (e) => {
e.waitUntil((async () => {
const c = await caches.open(CACHE);
await c.addAll(FILES.map((f) => new Request(f, { cache: "reload" }))); // all or nothing: never half a site
await self.skipWaiting();
})());
});
self.addEventListener("activate", (e) => {
e.waitUntil((async () => {
for (const k of await caches.keys())
if (k.startsWith("sloop-site-") && k !== CACHE) await caches.delete(k);
await self.clients.claim();
})());
});
self.addEventListener("fetch", (e) => {
const req = e.request;
if (req.method !== "GET") return;
const k = key(req.url);
if (!KEEP.has(k)) return; // not ours: the browser as usual
e.respondWith((async () => {
try {
const r = await fetch(req.url, { cache: "no-cache" }); // online: what is published now (by its URL: a
// page's own request, mode navigate, takes no options)
if (r.ok) {
const copy = r.clone();
e.waitUntil(caches.open(CACHE).then((c) => c.put(k, copy)).catch(() => {}));
}
return r;
} catch (err) { // offline: the copy
const hit = await caches.match(k, { cacheName: CACHE });
if (hit) return hit;
throw err;
}
})());
});
+116
View File
@@ -0,0 +1,116 @@
// SPDX-License-Identifier: GPL-3.0-only
// SLOOP 2.6: the site without internet (web/sw.js, made by web/make_site.py), in a real Chromium (Playwright):
// opened once with the server up, the installer (and its firmware, checked against its SHA-256) and the editor
// load again with the server stopped; online again, a changed page is served as published, never the old copy;
// the manifest is one Chrome can install. Run from the repo root after a site is made:
// node tests/pwa_test.mjs SITE_DIR (skipped, exit 0, without Playwright)
import { spawn } from "node:child_process";
import { readFileSync, writeFileSync } from "node:fs";
import { createRequire } from "node:module";
import { join } from "node:path";
let chromium;
try { ({ chromium } = await import("playwright")); }
catch {
try { // (a global install: NODE_PATH, as require finds it)
const req = createRequire(join(process.cwd(), "x.js"));
({ chromium } = req(req.resolve("playwright", { paths: (process.env.NODE_PATH || "").split(":").filter(Boolean) })));
} catch { console.log("pwa: Playwright not installed: skipped"); process.exit(0); }
}
const site = process.argv[2];
if (!site) { console.log("usage: node tests/pwa_test.mjs SITE_DIR"); process.exit(2); }
const PORT = 8790 + Math.floor(Math.random() * 100);
const base = `http://127.0.0.1:${PORT}/webapp/`;
let failed = 0;
const ok = (c, what) => { console.log(`pwa: ${what.padEnd(70)} ${c ? "ok" : "FAIL"}`); if (!c) failed++; };
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
let server = null;
async function serve() {
server = spawn("python3", ["-m", "http.server", String(PORT), "--bind", "127.0.0.1", "--directory", site],
{ stdio: "ignore" });
for (let i = 0; i < 50; i++) {
try { await fetch(base + "sw.js"); return; } catch { await sleep(100); }
}
throw new Error("server did not start");
}
async function stop() { if (server) { server.kill(); await new Promise((r) => server.on("exit", r)); server = null; } }
const launch = { headless: true };
if (process.env.PLAYWRIGHT_BROWSERS_PATH === undefined) launch.executablePath = "/opt/pw-browsers/chromium";
const browser = await chromium.launch(launch).catch(() => chromium.launch({ headless: true }));
try {
await serve();
const ctx = await browser.newContext();
const page = await ctx.newPage();
await page.goto(base + "installer/");
const ready = await page.evaluate(async () => {
const reg = await navigator.serviceWorker.ready;
return !!reg.active;
});
ok(ready, "online: the installer registers sw.js, it is active");
await page.reload(); // (now controlled)
ok(await page.evaluate(() => !!navigator.serviceWorker.controller), "the installer page is controlled by it");
const cached = await page.evaluate(async () => {
const ks = await caches.keys();
const c = await caches.open(ks.find((k) => k.startsWith("sloop-site-")));
return (await c.keys()).map((r) => new URL(r.url).pathname);
});
ok(cached.includes("/webapp/editor/") && cached.includes("/webapp/installer/") &&
cached.some((p) => /^\/firmware\/sloop-.*\.fwsc$/.test(p)) && cached.includes("/webapp/editor/fukiai.ttf"),
"kept: the installer, the editor, its font, the firmware");
const cdp = await ctx.newCDPSession(page);
const errs = (await cdp.send("Page.getInstallabilityErrors")).installabilityErrors || [];
ok(errs.length === 0, "Chrome can install it (no installability error)" + (errs.length ? ": " + errs.map((e) => e.errorId).join(", ") : ""));
await stop(); // ---- no network at all
await page.goto(base + "installer/");
await page.waitForFunction(() => /SLOOP \d/.test(document.getElementById("status").textContent), null, { timeout: 8000 })
.catch(() => {});
const st = await page.textContent("#status");
ok(/^SLOOP \d/.test(st), `offline: the installer loads its firmware from the copy (${st.trim().slice(0, 40)})`);
await page.goto(base + "editor/");
const ed = await page.evaluate(async () => {
await document.fonts.ready;
return { title: document.title, connect: !!document.getElementById("connect"), font: document.fonts.check('16px "Fukiai"', "") };
});
ok(ed.title === "SLOOP Editor" && ed.connect, "offline: the editor loads");
ok(ed.font, "offline: with its icon font");
await page.goto(base + "editor/index.html?x=1");
ok((await page.title()) === "SLOOP Editor", "offline: index.html and a query find the same copy");
const miss = await page.goto(base + "nothing.html").then(() => "page").catch(() => "error");
ok(miss === "error", "offline: what is not kept is not invented");
await serve(); // ---- online again, the site changed
const f = join(site, "webapp", "editor", "index.html");
const orig = readFileSync(f, "utf8");
writeFileSync(f, orig.replace("<title>SLOOP Editor</title>", "<title>SLOOP Editor NEW</title>"));
await page.goto(base + "editor/");
ok((await page.title()) === "SLOOP Editor NEW", "online: the page as published now, not the old copy");
await stop();
await page.goto(base + "editor/");
ok((await page.title()) === "SLOOP Editor NEW", "offline after that: the copy is the newest one seen");
writeFileSync(f, orig);
await serve(); // ---- a new site: a new sw.js takes over, the old copy goes
const swf = join(site, "webapp", "sw.js");
const sw0 = readFileSync(swf, "utf8");
writeFileSync(swf, sw0.replace(/const STAMP = "([^"]*)"/, 'const STAMP = "$1-next"'));
const keys = await page.evaluate(async () => {
const reg = await navigator.serviceWorker.getRegistration();
await reg.update();
for (let i = 0; i < 80 && !(await caches.keys()).some((k) => k.endsWith("-next")); i++)
await new Promise((r) => setTimeout(r, 100));
for (let i = 0; i < 40 && (await caches.keys()).length > 1; i++) await new Promise((r) => setTimeout(r, 100));
return caches.keys();
});
ok(keys.length === 1 && keys[0].endsWith("-next"), "a new site: its sw.js replaces the copy (" + keys.join(", ") + ")");
writeFileSync(swf, sw0);
} finally {
await stop();
await browser.close();
}
console.log("pwa:", failed ? `FAILED (${failed})` : "the site without internet: test passed");
process.exit(failed ? 1 : 0);
+3 -1
View File
@@ -143,10 +143,12 @@ run "regression: target cost of the render loops" python3 tests/target_budget.py
build/felucca.dis tests/target_budget.txt
run "installer CLI (fm1_install.py) against a simulated FM-1" python3 tests/install_test.py
run "the offline editor (one file, nothing next to it)" python3 tests/site_test.py
run "the offline editor (one file, nothing next to it); the offline site (sw.js, manifest)" python3 tests/site_test.py
if command -v node >/dev/null 2>&1; then
run "web pages: editor protocol, samples, packages, update protocol" node web/test_web.mjs
rm -rf "$OUT/pwa-site" && python3 web/make_site.py build/felucca.fwsc 2.6 "$OUT/pwa-site" >/dev/null &&
run "the site without internet in Chromium (skipped without Playwright)" node tests/pwa_test.mjs "$OUT/pwa-site"
else
echo "== skip web tests (no node)"
fi
+49 -2
View File
@@ -1,8 +1,12 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-only
"""SLOOP 2.6: the offline editor (web/make_site.py offline_editor): one file that needs nothing next to it."""
"""SLOOP 2.6: the offline editor (web/make_site.py offline_editor): one file that needs nothing next to it; and the
site without internet (webapp/sw.js, the manifest): what sw.js keeps is all there and all it needs."""
import json
import re
import shutil
import sys
import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
@@ -31,5 +35,48 @@ check("offline: the installer and the font licence online",
rel = [m for m in re.findall(r'(?:src|href)="([^"#]+)"', off) if not re.match(r"(https?:|data:|mailto:)", m)]
check("offline: no other file next to it (no relative src / href)", not rel)
check("offline: no url() to a file", not re.search(r'url\((?!data:)["\']?[A-Za-z]', off))
print("site:", "FAILED" if bad else "offline editor test passed")
check("offline: no app, no service worker (a file has no site)",
"serviceWorker" not in off and "webmanifest" not in off and 'id="install"' not in off)
# the site without internet: a site made from any package (a fake one with the identity make_site checks)
tmp = Path(tempfile.mkdtemp())
try:
pkg = bytearray(4096)
for i, ch in enumerate("FM-1_900"):
pkg[i * make_site.BLK + make_site.KEEP] = (ord(ch) + i + 1) & 0xFF
for i in range(8, make_site.BLOCKS):
pkg[i * make_site.BLK + make_site.KEEP] = 0x7D
pkg[2000:2016] = b"FELUCCA-LOADER-1"
(tmp / "p.fwsc").write_bytes(bytes(pkg))
make_site.main(tmp / "p.fwsc", "9.9", tmp / "site")
app = tmp / "site" / "webapp"
sw = (app / "sw.js").read_text(encoding="utf-8")
files = json.loads(re.search(r"const FILES = (\[.*?\]);", sw).group(1))
path = lambda f: (app / f / "index.html") if f.endswith("/") else (app / f) # noqa: E731
check("sw.js: stamped with the version", 'const STAMP = "9.9-' in sw and "/*" + "FILES*/" not in sw)
check("sw.js keeps the installer, the editor, its font, the firmware",
{"installer/", "editor/", "editor/fukiai.ttf", "../firmware/sloop-9.9.fwsc"} <= set(files))
check("sw.js: every file it keeps is in the site", all(path(f).is_file() for f in files))
m = json.loads((app / "sloop.webmanifest").read_text(encoding="utf-8"))
check("manifest: standalone, starts at the editor, icons 192 and 512 (+ maskable)",
m["display"] == "standalone" and m["start_url"] == "editor/" and
{i["sizes"] for i in m["icons"]} == {"192x192", "512x512"} and
any(i.get("purpose") == "maskable" for i in m["icons"]) and
all((app / i["src"]).is_file() for i in m["icons"]))
for page in ("editor", "installer"):
h = (app / page / "index.html").read_text(encoding="utf-8")
check(f"{page}: links the manifest, registers ../sw.js, an install button",
'href="../sloop.webmanifest"' in h and 'register("../sw.js")' in h and "beforeinstallprompt" in h)
stamp = sw.split('const STAMP = "')[1].split('"')[0]
(tmp / "site2").mkdir()
make_site.main(tmp / "p.fwsc", "9.9", tmp / "site2")
same = (tmp / "site2" / "webapp" / "sw.js").read_text(encoding="utf-8").split('const STAMP = "')[1].split('"')[0]
pkg[3000] ^= 1
(tmp / "p.fwsc").write_bytes(bytes(pkg))
make_site.main(tmp / "p.fwsc", "9.9", tmp / "site2")
other = (tmp / "site2" / "webapp" / "sw.js").read_text(encoding="utf-8").split('const STAMP = "')[1].split('"')[0]
check("sw.js: the same site, the same stamp; a file changed, a new one", stamp == same and stamp != other)
finally:
shutil.rmtree(tmp, ignore_errors=True)
print("site:", "FAILED" if bad else "offline editor and offline site test passed")
sys.exit(1 if bad else 0)
+22 -2
View File
@@ -8,6 +8,7 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SLOOP Editor</title>
<!--PWA--><link rel="manifest" href="../sloop.webmanifest"><meta name="theme-color" content="#000000"><link rel="icon" href="../icon-192.png"><!--/PWA-->
<style>
/* SLOOP 2.4 editor: the FM-1's screen on a big display. Black, the four track colours, the device's own
Terminus pixel font (tools/gen_webfont.py, inlined: the editor also runs from file://), 16 px and 32 px only
@@ -470,6 +471,7 @@
<span id="mock" hidden data-t="mock"></span>
<button id="connect" class="pri" data-t="connect" data-ic="port_usb_c"></button>
<div class="links"><a class="dim" href="../installer/" data-t="installer"></a><button class="lang" id="lang"></button></div>
<button id="install" class="pri" data-t="install" hidden></button>
<!--DL--><a class="dim" id="offline" href="sloop-editor.html" download="sloop-editor.html" data-t="offline"></a><!--/DL-->
</div>
</aside>
@@ -3567,7 +3569,8 @@ const TEXT = {
loadedUser: "読み込みました: ", reloaded: "本体で音色が変わったので読み直しました", readingBank: "スロットを読み込み中",
badEngine: "このファームウェアにないエンジンです: ", flashFail: "書き込みに失敗しました(rc {rc})",
installer: "SLOOP インストーラー",
offline: "エディタをダウンロード(オフライン用:Chrome / Edge で開く)",
offline: "エディタをダウンロード(パソコンでオフライン用:Chrome / Edge で開く)",
install: "アプリとしてインストール(オフラインで使える・Android も)",
tabSeq: "シーケンサー", tabTracks: "トラック", tabSettings: "設定",
navTrack: "トラック", navSounds: "サウンド", navDevice: "本体", tabKits: "ドラムキット", fm1: "FM-1",
stepList: "ステップ一覧(音名を入力)", stepsOf: "{n} ステップ", fontCredit: "フォント: Terminus(SIL OFL 1.1)",
@@ -3767,7 +3770,8 @@ const TEXT = {
loadedUser: "Loaded ", reloaded: "The sound changed on the device: read again", readingBank: "Reading the slots",
badEngine: "This firmware has no such engine: ", flashFail: "Write failed (rc {rc})",
installer: "SLOOP installer",
offline: "Download the editor (offline: open it in Chrome or Edge)",
offline: "Download the editor (offline on a computer: open it in Chrome or Edge)",
install: "Install the app (works offline, Android too)",
tabSeq: "Sequencer", tabTracks: "Tracks", tabSettings: "Settings",
navTrack: "Track", navSounds: "Sounds", navDevice: "Device", tabKits: "Drum kit", fm1: "FM-1",
stepList: "Step list (type note names)", stepsOf: "{n} steps", fontCredit: "Font: Terminus (SIL OFL 1.1)",
@@ -7602,6 +7606,22 @@ showTab(tab);
libInit();
if (!MOCK && !navigator.requestMIDIAccess) sayK("nomidi");
})();
/* the site without internet (SLOOP 2.6, webapp/sw.js): opened once online, the editor and the installer work
* offline too, still on https (Android: a downloaded file opens as content://, where Chrome refuses MIDI) */
/*PWA*/if ("serviceWorker" in navigator && /^https?:$/.test(location.protocol))
navigator.serviceWorker.register("../sw.js").catch(() => {});
{
let ask = null;
window.addEventListener("beforeinstallprompt", (e) => { e.preventDefault(); ask = e; $("install").hidden = false; });
window.addEventListener("appinstalled", () => { ask = null; $("install").hidden = true; });
$("install").addEventListener("click", async () => {
if (!ask) return;
ask.prompt();
await ask.userChoice.catch(() => {});
ask = null;
$("install").hidden = true;
});
}/*/PWA*/
</script>
</body>
</html>
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

+24 -2
View File
@@ -6,6 +6,7 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SLOOP installer</title>
<!--PWA--><link rel="manifest" href="../sloop.webmanifest"><meta name="theme-color" content="#000000"><link rel="icon" href="../icon-192.png"><!--/PWA-->
<style>
:root { --bg: #000; --fg: #f2f2f2; --dim: #8a8a92; --tile: #16161a; --line: #2a2a30;
--blue: #287cff; --green: #1ecc70; --yellow: #ffc618; --orange: #ff621a; --red: #ff2c34; }
@@ -41,6 +42,8 @@
progress::-moz-progress-bar { background: var(--orange); }
pre { color: var(--dim); font-size: 11px; white-space: pre-wrap; margin-top: 12px; max-height: 160px; overflow: auto; }
hr { border: 0; border-top: 1px solid var(--line); margin: 28px 0 18px; }
[hidden] { display: none !important; }
button.ed { font: inherit; color: var(--fg); border: 0; cursor: pointer; }
.ed { display: inline-block; margin: 8px 0 0; padding: 10px 14px; background: var(--tile); text-decoration: none; }
details { margin: 22px 0 0; } summary { cursor: pointer; font-weight: 600; }
button#stock-go { font: 600 14px/1 inherit; font-family: inherit; background: var(--tile); color: var(--fg); border: 1px solid var(--line);
@@ -71,6 +74,7 @@
<pre id="log"></pre>
<a class="ed" href="../editor/" data-t="editor"></a>
<p class="small"><a href="../editor/sloop-editor.html" download="sloop-editor.html" data-t="edOffline"></a></p>
<p><button id="app" class="ed" hidden data-t="appInstall"></button></p>
<hr>
<p class="small" data-t="direct"></p>
<p class="small" data-t="beta"></p>
@@ -102,7 +106,8 @@ const TEXT = {
warn: "書き込み中は USB を抜かないでください。",
install: "インストール", other: "English",
editor: "エディタ(インストール後、パソコンから音色やシーケンスを編集)",
edOffline: "エディタをダウンロード(インターネットなしで使う:ファイルを Chrome / Edge で開く)",
edOffline: "エディタをダウンロード(パソコンでインターネットなしで使う:ファイルを Chrome / Edge で開く)",
appInstall: "アプリとしてインストール(エディタとインストーラーがオフラインで使える・Android も)",
direct: "USB ケーブルはパソコンに直接つないでください。Probe や Transporter などの機材は不要です。",
brick: "万一インストールに失敗して起動しなくなった場合は、復旧に Transporter が必要です:",
beta: "これはベータ版で、不安定な場合があります。このカスタムファームウェアを使ったことで FM-1 が壊れたり不具合が起きたりしても、作者は一切の責任を負いません。自己責任でお使いください。",
@@ -137,7 +142,8 @@ const TEXT = {
warn: "Do not unplug the USB cable while writing.",
install: "Install", other: "日本語",
editor: "Editor (after installing: edit sounds and sequences from the computer)",
edOffline: "Download the editor to use it without internet (open the file in Chrome or Edge)",
edOffline: "Download the editor to use it without internet on a computer (open the file in Chrome or Edge)",
appInstall: "Install the app (the editor and the installer offline, Android too)",
direct: "Connect the USB cable directly to the computer. No probe or Transporter is needed.",
brick: "If an install fails and the FM-1 no longer starts, recovering it needs a Transporter:",
beta: "This is a beta and may be unstable. The author accepts no responsibility if your FM-1 is damaged or misbehaves because of this custom firmware. Use it at your own risk.",
@@ -179,6 +185,22 @@ function applyLang() {
}
$("lang").addEventListener("click", () => { lang = lang === "ja" ? "en" : "ja"; applyLang(); });
applyLang();
/* the site without internet (SLOOP 2.6, webapp/sw.js): opened once online, the installer, the firmware and the
* editor work offline too, still on https (Android: a downloaded file opens as content://, where Chrome refuses MIDI) */
if ("serviceWorker" in navigator && /^https?:$/.test(location.protocol))
navigator.serviceWorker.register("../sw.js").catch(() => {});
{
let ask = null;
window.addEventListener("beforeinstallprompt", (e) => { e.preventDefault(); ask = e; $("app").hidden = false; });
window.addEventListener("appinstalled", () => { ask = null; $("app").hidden = true; });
$("app").addEventListener("click", async () => {
if (!ask) return;
ask.prompt();
await ask.userChoice.catch(() => {});
ask = null;
$("app").hidden = true;
});
}
const sayK = (k, arg = "") => { lastKey = k; lastArg = arg; $("status").textContent = t(k) + arg; };
const say = (txt) => { lastKey = null; $("status").textContent = txt; };
const log = (t) => { $("log").textContent += t + "\n"; };
+49 -3
View File
@@ -10,6 +10,10 @@
webapp/editor/sloop-editor.html the editor in one file, for offline use (SLOOP 2.6): its icon font inlined,
its links to the installer and the font licence online; opened from the disk in
Chrome / Edge (file:// is a secure context: Web MIDI asks for permission)
webapp/sw.js, webapp/sloop.webmanifest, webapp/icon-*.png the site without internet (SLOOP 2.6): an app to
install; opened once online, the installer, the editor and the firmware are kept
by the browser and work offline, still on https (on Android a downloaded file opens
as content://, where Chrome refuses Web MIDI)
src/ not touched
web/make_site.py build/felucca-X.Y.fwsc X.Y OUT_DIR [--beta]
@@ -39,10 +43,51 @@ def offline_editor(html):
if html.count(a) != 1:
raise SystemExit(f"editor.html must contain {a} once; update make_site.py")
html = html.replace(a, b)
html, n = re.subn(r"<!--DL-->.*?<!--/DL-->", "", html, flags=re.S)
if n != 1:
raise SystemExit("editor.html must contain <!--DL-->...<!--/DL--> once; update make_site.py")
for pat, what in ((r"<!--DL-->.*?<!--/DL-->", "<!--DL-->...<!--/DL-->"), # (the file has no site
(r"<!--PWA-->.*?<!--/PWA-->", "<!--PWA-->...<!--/PWA-->"), # around it: no app to
(r"/\*PWA\*/.*?/\*/PWA\*/", "/*PWA*/.../*/PWA*/"), # install, no copy kept)
(r'<button id="install"[^>]*></button>\s*', '<button id="install">')):
html, n = re.subn(pat, "", html, flags=re.S)
if n != 1:
raise SystemExit(f"editor.html must contain {what} once; update make_site.py")
return html
ICONS = ("icon-192.png", "icon-512.png", "icon-maskable-512.png")
def app_files(out, version, fw_name):
"""webapp/: the manifest, the icons and sw.js with the list of what it keeps (relative to webapp/) and a
stamp of their contents, so any change makes a new sw.js and the browser takes the new site"""
app = out / "webapp"
for f in ICONS:
shutil.copy(HERE / f, app / f)
manifest = {
"name": "SLOOP", "short_name": "SLOOP", "id": "editor/", "start_url": "editor/", "scope": "./",
"display": "standalone", "background_color": "#000000", "theme_color": "#000000",
"description": "SLOOP for the M-VAVE FM-1: the editor and the installer, also without internet",
"icons": [{"src": "icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any"},
{"src": "icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any"},
{"src": "icon-maskable-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable"}],
}
(app / "sloop.webmanifest").write_text(json.dumps(manifest, indent=1) + "\n", encoding="utf-8")
keep = {"installer/": app / "installer" / "index.html", "editor/": app / "editor" / "index.html",
"../firmware/" + fw_name: out / "firmware" / fw_name, "sloop.webmanifest": app / "sloop.webmanifest"}
for f in ("fukiai.ttf", "FUKIAI-LICENSE.txt"):
if (app / "editor" / f).exists():
keep["editor/" + f] = app / "editor" / f
for f in ICONS:
keep[f] = app / f
h = hashlib.sha256()
for k in sorted(keep):
h.update(k.encode() + b"\0" + keep[k].read_bytes())
sw = (HERE / "sw.js").read_text(encoding="utf-8")
for mark in ("/*STAMP*/", "/*FILES*/[]"):
if sw.count(mark) != 1:
raise SystemExit(f"sw.js must contain {mark} once; update make_site.py")
sw = sw.replace("/*STAMP*/", f"{version}-{h.hexdigest()[:12]}").replace("/*FILES*/[]", json.dumps(sorted(keep)))
(app / "sw.js").write_text(sw, encoding="utf-8")
return sorted(keep)
BLOCKS, BLK, KEEP = 20, 0x30, 0x2F
@@ -103,6 +148,7 @@ def main(pkg, version, out):
for f in ("fukiai.ttf", "FUKIAI-LICENSE.txt"):
if (HERE / f).exists():
shutil.copy(HERE / f, ed / f)
app_files(out, version, name)
(out / "index.html").write_text(
'<!doctype html><meta charset="utf-8"><title>SLOOP</title>'
'<meta http-equiv="refresh" content="0; url=webapp/installer/">'
+56
View File
@@ -0,0 +1,56 @@
// SPDX-License-Identifier: GPL-3.0-only
// SLOOP 2.6: the site without internet (webapp/sw.js, made by web/make_site.py). Opened once online, the
// installer, the editor and the firmware they install are kept here; offline they come from this copy, still on
// https, so Web MIDI asks as usual (a downloaded file on Android opens as content://, where Chrome refuses MIDI).
// Online the network always wins (the page as published, never an old one); the copy is only the fallback.
// A new site (any file changed) is a new sw.js: the new copy replaces the old one.
const STAMP = "/*STAMP*/"; // version + a hash of the files
const CACHE = "sloop-site-" + STAMP;
const FILES = /*FILES*/[]; // relative to this file
const KEEP = new Set(FILES.map((f) => new URL(f, self.location).href));
const key = (url) => { // the copy's name of a request: no query, index.html = the folder
const u = new URL(url);
u.search = "";
u.hash = "";
if (u.pathname.endsWith("/index.html")) u.pathname = u.pathname.slice(0, -10);
return u.href;
};
self.addEventListener("install", (e) => {
e.waitUntil((async () => {
const c = await caches.open(CACHE);
await c.addAll(FILES.map((f) => new Request(f, { cache: "reload" }))); // all or nothing: never half a site
await self.skipWaiting();
})());
});
self.addEventListener("activate", (e) => {
e.waitUntil((async () => {
for (const k of await caches.keys())
if (k.startsWith("sloop-site-") && k !== CACHE) await caches.delete(k);
await self.clients.claim();
})());
});
self.addEventListener("fetch", (e) => {
const req = e.request;
if (req.method !== "GET") return;
const k = key(req.url);
if (!KEEP.has(k)) return; // not ours: the browser as usual
e.respondWith((async () => {
try {
const r = await fetch(req.url, { cache: "no-cache" }); // online: what is published now (by its URL: a
// page's own request, mode navigate, takes no options)
if (r.ok) {
const copy = r.clone();
e.waitUntil(caches.open(CACHE).then((c) => c.put(k, copy)).catch(() => {}));
}
return r;
} catch (err) { // offline: the copy
const hit = await caches.match(k, { cacheName: CACHE });
if (hit) return hit;
throw err;
}
})());
});