forked from upstream-mirrors/OrcaSlicer
Compare commits
18 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| be0188dfad | |||
| 3fd9c26805 | |||
| d74b2e4f10 | |||
| b2ffb7f10e | |||
| c82388cec4 | |||
| f9896430c3 | |||
| e552ff65b1 | |||
| bcda8ef4fa | |||
| 9d585c6c2d | |||
| f66ed2d6e4 | |||
| 0518ffeb09 | |||
| 6d7d598a9d | |||
| e33657fa45 | |||
| fc9fcdd0d4 | |||
| a63458c94e | |||
| 27cbe5a04b | |||
| 145ec0f43a | |||
| 8b18bd58ac |
@@ -70,3 +70,8 @@ web/frontend/dist-demo
|
||||
|
||||
# Persistent application data beside compose.yaml.
|
||||
/data/
|
||||
|
||||
# Package the desktop helper from committed sources in the web image.
|
||||
desktop/bambu-login/node_modules
|
||||
desktop/bambu-login/dist
|
||||
web/frontend/public/bambu-login/*.zip
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
# Copy to .env. Runtime state belongs in ./data beside compose.yaml, not Git.
|
||||
# The maintainer publishes app + web with the same immutable version tag.
|
||||
ORCA_IMAGE_PREFIX=gitea.labus.uk/karol/web-slicer
|
||||
ORCA_IMAGE_TAG=0.2.2-alpha
|
||||
ORCA_IMAGE_TAG=0.3.1-alpha
|
||||
|
||||
WEB_PORT=8080
|
||||
LAN_BIND=0.0.0.0
|
||||
|
||||
@@ -149,7 +149,7 @@ models can exceed these defaults. Build requirements are separate; see
|
||||
|
||||
## Getting started
|
||||
|
||||
The current image version is `0.2.2-alpha`, an alpha for evaluation. Images
|
||||
The current image version is `0.3.2-alpha`. Images
|
||||
are public and can be pulled without registry authentication.
|
||||
|
||||
Install Docker Engine and Compose v2. Put [compose.yaml](compose.yaml) and
|
||||
@@ -211,14 +211,12 @@ save G-code with no server, account or network. It can also drive printers on
|
||||
your LAN — Bambu Lab in Developer Mode, Anycubic Kobra, Moonraker and the other
|
||||
hosts the web client supports.
|
||||
|
||||
The current app version is `0.3.0-alpha`, an alpha for evaluation. Install it by
|
||||
side-loading the APK from the [latest release](https://gitea.labus.uk/karol/web-slicer/releases)
|
||||
(enable "install unknown apps" for your browser or file manager); it is not on
|
||||
any app store. Two builds are published:
|
||||
The current Android version is `0.3.2-alpha`. Enable "install unknown apps"
|
||||
for your browser or file manager to sideload one of the two APKs:
|
||||
|
||||
- `web-slicer-<version>-arm64.apk` — the standard app (offline slicing and LAN
|
||||
- [Standard APK](https://gitea.labus.uk/api/packages/karol/generic/web-slicer-android/0.3.2-alpha/web-slicer-0.3.2-alpha-arm64.apk) — the standard app (offline slicing and LAN
|
||||
printing). Most users want this one.
|
||||
- `web-slicer-<version>-cloud-arm64.apk` — additionally bundles the third-party
|
||||
- [Bambu Cloud APK](https://gitea.labus.uk/api/packages/karol/generic/web-slicer-android/0.3.2-alpha/web-slicer-0.3.2-alpha-cloud-arm64.apk) — additionally bundles the third-party
|
||||
[open-bamboo-networking](https://gitea.labus.uk/karol/open-bamboo-networking)
|
||||
plugin (AGPL-3.0) for Bambu Lab account sign-in, cloud printer status and
|
||||
control, and cloud printing. It ships no Bambu keys: printers with command
|
||||
@@ -236,7 +234,7 @@ Copy [.env.example](.env.example) to `.env`. Do not commit the edited file.
|
||||
| Variable | Default | Purpose |
|
||||
| --- | --- | --- |
|
||||
| `ORCA_IMAGE_PREFIX` | `gitea.labus.uk/karol/web-slicer` | Shared image prefix; services append `-app`, `-web` and optional `-demo`. |
|
||||
| `ORCA_IMAGE_TAG` | `0.2.2-alpha` | Matching release version for all images; alpha prerelease. |
|
||||
| `ORCA_IMAGE_TAG` | `0.3.2-alpha` | Matching release version for all images. |
|
||||
| `WEB_PORT` | `8080` | Published HTTP port. |
|
||||
| `LAN_BIND` | `0.0.0.0` | Host bind address; use `127.0.0.1` for a proxy on the same host. |
|
||||
| `DEMO_PORT` / `DEMO_BIND` | `8082` / `127.0.0.1` | Separate static demo, enabled with the `demo` Compose profile. |
|
||||
@@ -366,7 +364,12 @@ git merge --no-commit upstream/main
|
||||
For an existing `upstream`, skip `remote add`. Resolve conflicts and refresh
|
||||
`README.upstream.md` from the reviewed upstream revision while retaining this
|
||||
fork README. Before merging, check headless/desktop builds, 3MF compatibility,
|
||||
profiles, generated settings/locales, API contracts and browser preview. See
|
||||
profiles, generated settings/locales, API contracts and browser preview.
|
||||
|
||||
This fork's GUI is a separate web client, not OrcaSlicer's desktop GUI, so a
|
||||
merge that only builds is not finished: new upstream options must be surfaced in
|
||||
the web client (regenerate the settings layout and confirm they render), never
|
||||
left behind because the C++ merged cleanly. See
|
||||
[upstream maintenance](docs/upstream-maintenance.md).
|
||||
|
||||
## Documentation
|
||||
|
||||
+29
-1
@@ -13,10 +13,38 @@ the same pieces as the server deployment:
|
||||
- the web client in a WebView, served by the same local origin
|
||||
(`python/android_main.py`), with the slicer resources and profiles.
|
||||
|
||||
One local user, no accounts. Everything the backend reads is packed into
|
||||
The offline workspace has one local user. Everything the embedded backend reads is packed into
|
||||
`assets/payload.zip` and unpacked into the app's private storage once per
|
||||
payload version.
|
||||
|
||||
## Connecting to a server
|
||||
|
||||
Open **Preferences and help → Connection settings** in the application menu.
|
||||
**Offline on this device** is the default. To use a server, enter its HTTPS origin, such as
|
||||
`https://slicer.example.com`, and sign in with your Web Slicer account. The app
|
||||
remembers the selected mode and server. If the server is unavailable, you can
|
||||
retry or return to the offline workspace. The theme selected in the app applies
|
||||
to both workspaces. The system theme is the default.
|
||||
|
||||
Each mode has its own projects, presets and account session. In server mode the
|
||||
web client uses the selected server for slicing and storage. Server attachments
|
||||
are saved to Android Downloads. The native Bambu sign-in and native blob
|
||||
download bridge run in the offline WebView.
|
||||
|
||||
## Syncing filament libraries
|
||||
|
||||
After signing in to the server in the app, choose **Sync filament library** in
|
||||
**Preferences and help → Connection settings**. Select a library on each side
|
||||
and compare them before confirming. You can sync libraries you manage. The server needs an authenticated
|
||||
Web Slicer installation with library sync support.
|
||||
|
||||
The preview lists the number of products that will be created or updated in
|
||||
each workspace. Sync carries a product's name, material, colour and other
|
||||
metadata. A shared product can follow edits made on one side since the last
|
||||
match. Products edited on both sides stay as they are, with their names shown
|
||||
for review. Deletions, machine availability, slicing profiles and AMS slot
|
||||
assignments stay with their own workspace.
|
||||
|
||||
## Building
|
||||
|
||||
Tools live outside the repository in `~/android`: JDK 21, the Android SDK with
|
||||
|
||||
@@ -14,8 +14,8 @@ android {
|
||||
applicationId = "uk.labus.webslicer"
|
||||
minSdk = 29
|
||||
targetSdk = 35
|
||||
versionCode = 2
|
||||
versionName = "0.3.0-alpha"
|
||||
versionCode = 4
|
||||
versionName = "0.3.2-alpha"
|
||||
ndk { abiFilters += "arm64-v8a" }
|
||||
}
|
||||
sourceSets["main"].assets.srcDir(stage.resolve("assets"))
|
||||
|
||||
@@ -17,17 +17,17 @@
|
||||
android:networkSecurityConfig="@xml/network_security_config"
|
||||
android:allowBackup="false"
|
||||
android:theme="@android:style/Theme.DeviceDefault.NoActionBar">
|
||||
<activity android:name=".MainActivity" android:exported="true"
|
||||
<activity android:name=".MainActivity" android:exported="true" android:enableOnBackInvokedCallback="true"
|
||||
android:configChanges="orientation|screenSize|screenLayout|keyboardHidden|uiMode">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
<activity android:name=".BambuLoginActivity" android:exported="false"
|
||||
<activity android:name=".BambuLoginActivity" android:exported="false" android:process=":bambu_login"
|
||||
android:configChanges="orientation|screenSize|screenLayout|keyboardHidden|uiMode" />
|
||||
<service android:name=".ServerService" android:process=":server"
|
||||
android:exported="false" android:foregroundServiceType="specialUse">
|
||||
android:exported="false" android:stopWithTask="true" android:foregroundServiceType="specialUse">
|
||||
<property android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
|
||||
android:value="Local slicing server for the app's own user interface" />
|
||||
</service>
|
||||
|
||||
@@ -34,8 +34,12 @@ class BambuLoginActivity : Activity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
val version = intent.getStringExtra(EXTRA_VERSION)?.takeIf { VERSION.matches(it) } ?: DEFAULT_VERSION
|
||||
// A fresh sign-in: cookies of an earlier account must not carry over.
|
||||
CookieManager.getInstance().removeAllCookies(null)
|
||||
// This activity runs in its own process and cookie store. Signing in to
|
||||
// Bambu must not clear the user's Web Slicer server session.
|
||||
if (!webDataInitialized) {
|
||||
WebView.setDataDirectorySuffix("bambu-login")
|
||||
webDataInitialized = true
|
||||
}
|
||||
web = WebView(this)
|
||||
web.settings.javaScriptEnabled = true
|
||||
web.settings.domStorageEnabled = true
|
||||
@@ -52,7 +56,9 @@ class BambuLoginActivity : Activity() {
|
||||
}
|
||||
web.addJavascriptInterface(Bridge(), "wx")
|
||||
setContentView(web)
|
||||
web.loadUrl(SIGN_IN)
|
||||
CookieManager.getInstance().removeAllCookies {
|
||||
if (!isFinishing && !isDestroyed) web.loadUrl(SIGN_IN)
|
||||
}
|
||||
}
|
||||
|
||||
/** Receives `window.wx.postMessage(json)` from the page; runs on a WebView thread. */
|
||||
@@ -109,6 +115,7 @@ class BambuLoginActivity : Activity() {
|
||||
}
|
||||
|
||||
companion object {
|
||||
private var webDataInitialized = false
|
||||
const val EXTRA_VERSION = "plugin_version"
|
||||
private const val DEFAULT_VERSION = "02.09.01.99"
|
||||
private const val SIGN_IN = "https://bambulab.com/sign-in"
|
||||
|
||||
@@ -18,27 +18,31 @@ import kotlin.concurrent.thread
|
||||
|
||||
/**
|
||||
* Saves files the web client downloads into the shared Downloads collection.
|
||||
* Server artifacts (G-code, archives) arrive as links to the local backend;
|
||||
* Server artifacts (G-code, archives) arrive as links to the active backend;
|
||||
* files the client builds itself arrive as blob: links, which only the page
|
||||
* can read, so a small page script hands their bytes over [BRIDGE].
|
||||
*/
|
||||
class Downloads(private val context: Context) {
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
|
||||
/** A link to the local backend, from the WebView's download listener. */
|
||||
fun fromUrl(url: String, contentDisposition: String?, mimeType: String?) {
|
||||
if (!url.startsWith(ORIGIN + "/")) { notify(context.getString(R.string.download_failed)); return }
|
||||
/** An attachment from the active origin, already checked by the caller. */
|
||||
fun fromUrl(url: String, contentDisposition: String?, mimeType: String?, origin: String, cookie: String?) {
|
||||
thread(name = "download") {
|
||||
try {
|
||||
val connection = URL(url).openConnection() as HttpURLConnection
|
||||
connection.connectTimeout = 5000
|
||||
if (connection.responseCode != 200) throw IllegalStateException("HTTP ${connection.responseCode}")
|
||||
val disposition = connection.getHeaderField("Content-Disposition") ?: contentDisposition
|
||||
val type = connection.contentType ?: mimeType
|
||||
val name = fileName(url, disposition, type)
|
||||
connection.inputStream.use { save(name, type, it) }
|
||||
try {
|
||||
connection.connectTimeout = 5000
|
||||
connection.readTimeout = 30000
|
||||
connection.instanceFollowRedirects = false
|
||||
if (cookie != null) connection.setRequestProperty("Cookie", cookie)
|
||||
if (connection.responseCode != 200) throw IllegalStateException("HTTP ${connection.responseCode}")
|
||||
val disposition = connection.getHeaderField("Content-Disposition") ?: contentDisposition
|
||||
val type = connection.contentType ?: mimeType
|
||||
val name = fileName(url, disposition, type)
|
||||
connection.inputStream.use { save(name, type, it) }
|
||||
} finally { connection.disconnect() }
|
||||
} catch (error: Exception) {
|
||||
Log.w(TAG, "download failed: $url", error)
|
||||
Log.w(TAG, "download failed for $origin", error)
|
||||
notify(context.getString(R.string.download_failed))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
package uk.labus.webslicer
|
||||
|
||||
import android.content.SharedPreferences
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.IOException
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
|
||||
/** Reconciles portable product data. Printer assignments and tuning stay with their workspace. */
|
||||
internal class LibrarySync(
|
||||
private val server: String,
|
||||
private val cookie: String?,
|
||||
private val history: SharedPreferences
|
||||
) {
|
||||
class RequestFailed(val status: Int) : IOException("HTTP $status")
|
||||
|
||||
data class Product(val id: String, val revision: Int, val data: JSONObject?, val fingerprint: String?)
|
||||
data class Library(val origin: String, val id: String, val name: String, val csrf: String,
|
||||
val products: Map<String, Product> = emptyMap())
|
||||
data class Plan(
|
||||
val local: Library, val remote: Library, val key: String,
|
||||
val toLocal: JSONArray, val toRemote: JSONArray, val conflicts: List<String>
|
||||
)
|
||||
|
||||
fun choices(): Pair<List<Library>, List<Library>> {
|
||||
val remote = libraries(server)
|
||||
awaitLocalBackend()
|
||||
return libraries(Downloads.ORIGIN) to remote
|
||||
}
|
||||
|
||||
fun prepare(localChoice: Library, remoteChoice: Library): Plan {
|
||||
val remote = snapshot(remoteChoice)
|
||||
val local = snapshot(localChoice)
|
||||
val key = "$server/${remote.id}/${local.id}"
|
||||
val base = JSONObject(history.getString(key, "{}") ?: "{}")
|
||||
val toLocal = JSONArray()
|
||||
val toRemote = JSONArray()
|
||||
val conflicts = mutableListOf<String>()
|
||||
|
||||
for (id in local.products.keys + remote.products.keys) {
|
||||
val left = local.products[id]
|
||||
val right = remote.products[id]
|
||||
if (left?.fingerprint == right?.fingerprint) continue
|
||||
val known = base.optString(id)
|
||||
when {
|
||||
left != null && left.data == null || right != null && right.data == null ->
|
||||
conflicts.add(label(left, right))
|
||||
left == null -> toLocal.put(change(checkNotNull(right), 0))
|
||||
right == null -> toRemote.put(change(left, 0))
|
||||
known == left.fingerprint -> toLocal.put(change(right, left.revision))
|
||||
known == right.fingerprint -> toRemote.put(change(left, right.revision))
|
||||
else -> conflicts.add(label(left, right))
|
||||
}
|
||||
}
|
||||
remember(key, local, remote)
|
||||
return Plan(local, remote, key, toLocal, toRemote, conflicts)
|
||||
}
|
||||
|
||||
fun apply(plan: Plan): Pair<Int, Int> {
|
||||
val currentLocal = snapshot(plan.local)
|
||||
val currentRemote = snapshot(plan.remote)
|
||||
if (!unchangedSources(plan.toRemote, plan.local, currentLocal) ||
|
||||
!unchangedSources(plan.toLocal, plan.remote, currentRemote)) {
|
||||
throw IOException("Source library changed after preview")
|
||||
}
|
||||
var updated = 0
|
||||
var conflicts = plan.conflicts.size
|
||||
// A successful first write remains valid if the second connection drops.
|
||||
// The next preview calculates a fresh plan from both current snapshots.
|
||||
for ((target, changes) in listOf(plan.remote to plan.toRemote, plan.local to plan.toLocal)) {
|
||||
if (changes.length() == 0) continue
|
||||
val result = request(target.origin, path(target.id), JSONObject().put("products", changes), target.csrf)
|
||||
updated += result.getJSONArray("updated").length()
|
||||
conflicts += result.getJSONArray("conflicts").length()
|
||||
}
|
||||
val remote = snapshot(plan.remote)
|
||||
val local = snapshot(plan.local)
|
||||
remember(plan.key, local, remote)
|
||||
return updated to conflicts
|
||||
}
|
||||
|
||||
private fun unchangedSources(changes: JSONArray, before: Library, after: Library): Boolean =
|
||||
(0 until changes.length()).all { index ->
|
||||
val id = changes.getJSONObject(index).getString("id")
|
||||
before.products[id]?.fingerprint == after.products[id]?.fingerprint
|
||||
}
|
||||
|
||||
private fun remember(key: String, local: Library, remote: Library) {
|
||||
val previous = JSONObject(history.getString(key, "{}") ?: "{}")
|
||||
val base = JSONObject()
|
||||
for ((id, product) in local.products) {
|
||||
val fingerprint = product.fingerprint ?: continue
|
||||
val other = remote.products[id]?.fingerprint ?: continue
|
||||
if (fingerprint == other) base.put(id, fingerprint)
|
||||
else if (previous.has(id)) base.put(id, previous.getString(id))
|
||||
}
|
||||
history.edit().putString(key, base.toString()).apply()
|
||||
}
|
||||
|
||||
private fun awaitLocalBackend() {
|
||||
val deadline = android.os.SystemClock.elapsedRealtime() + 120000
|
||||
do {
|
||||
try {
|
||||
request(Downloads.ORIGIN, "/auth/me")
|
||||
return
|
||||
} catch (_: java.net.ConnectException) {
|
||||
Thread.sleep(500)
|
||||
}
|
||||
} while (android.os.SystemClock.elapsedRealtime() < deadline)
|
||||
throw IOException("Local slicer did not start")
|
||||
}
|
||||
|
||||
private fun libraries(origin: String): List<Library> {
|
||||
val session = request(origin, "/auth/me")
|
||||
if (origin == server && (session.optJSONObject("user") == null || !session.optBoolean("required"))) {
|
||||
throw RequestFailed(401)
|
||||
}
|
||||
val csrf = session.optString("csrf_token").takeUnless { it.isBlank() || it == "null" } ?: "login"
|
||||
val default = request(origin, "/filament-libraries/default", JSONObject(), csrf)
|
||||
fun option(row: JSONObject) = Library(origin, row.getString("id"), row.getString("name"), csrf)
|
||||
val primary = option(default)
|
||||
val available = exchange(origin, "/filament-libraries") { JSONArray(it) }
|
||||
val others = (0 until available.length()).map { available.getJSONObject(it) }
|
||||
.filter { it.optBoolean("can_manage") && it.getString("id") != primary.id }.map(::option)
|
||||
return listOf(primary) + others
|
||||
}
|
||||
|
||||
private fun snapshot(library: Library): Library {
|
||||
val rows = request(library.origin, path(library.id)).getJSONArray("products")
|
||||
val products = (0 until rows.length()).associate { index ->
|
||||
val row = rows.getJSONObject(index)
|
||||
val id = row.getString("id")
|
||||
id to Product(id, row.getInt("revision"), row.optJSONObject("data"),
|
||||
if (row.isNull("fingerprint")) null else row.getString("fingerprint"))
|
||||
}
|
||||
return library.copy(products = products)
|
||||
}
|
||||
|
||||
private fun request(origin: String, path: String, body: JSONObject? = null, csrf: String? = null) =
|
||||
exchange(origin, path, body, csrf) { JSONObject(it) }
|
||||
|
||||
private fun <T> exchange(origin: String, path: String, body: JSONObject? = null,
|
||||
csrf: String? = null, decode: (String) -> T): T {
|
||||
val connection = URL("$origin/api/v1$path").openConnection() as HttpURLConnection
|
||||
try {
|
||||
connection.connectTimeout = 5000
|
||||
connection.readTimeout = 15000
|
||||
connection.instanceFollowRedirects = false
|
||||
connection.setRequestProperty("Accept", "application/json")
|
||||
if (origin == server && cookie != null) connection.setRequestProperty("Cookie", cookie)
|
||||
if (body != null) {
|
||||
val bytes = body.toString().toByteArray(Charsets.UTF_8)
|
||||
connection.requestMethod = "POST"
|
||||
connection.doOutput = true
|
||||
connection.setFixedLengthStreamingMode(bytes.size)
|
||||
connection.setRequestProperty("Content-Type", "application/json")
|
||||
connection.setRequestProperty("X-Orca-CSRF", csrf)
|
||||
connection.outputStream.use { it.write(bytes) }
|
||||
}
|
||||
val status = connection.responseCode
|
||||
if (status !in 200..299) throw RequestFailed(status)
|
||||
val data = ByteArrayOutputStream()
|
||||
connection.inputStream.use { input ->
|
||||
val buffer = ByteArray(8192)
|
||||
while (true) {
|
||||
val length = input.read(buffer)
|
||||
if (length < 0) break
|
||||
if (data.size() + length > 8 * 1024 * 1024) throw IOException("Response too large")
|
||||
data.write(buffer, 0, length)
|
||||
}
|
||||
}
|
||||
return decode(data.toString("UTF-8"))
|
||||
} finally {
|
||||
connection.disconnect()
|
||||
}
|
||||
}
|
||||
|
||||
private fun path(id: String) = "/filament-libraries/${java.util.UUID.fromString(id)}/sync"
|
||||
private fun change(source: Product, revision: Int) = JSONObject()
|
||||
.put("id", source.id).put("revision", revision).put("data", source.data)
|
||||
private fun label(left: Product?, right: Product?) =
|
||||
(left?.data ?: right?.data)?.optString("name").orEmpty()
|
||||
}
|
||||
@@ -2,24 +2,47 @@ package uk.labus.webslicer
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.app.Activity
|
||||
import android.app.AlertDialog
|
||||
import android.content.Intent
|
||||
import android.content.pm.ApplicationInfo
|
||||
import android.content.res.Configuration
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.view.WindowInsets
|
||||
import android.view.WindowInsetsController
|
||||
import android.widget.ArrayAdapter
|
||||
import android.widget.EditText
|
||||
import android.widget.FrameLayout
|
||||
import android.widget.LinearLayout
|
||||
import android.widget.Spinner
|
||||
import android.widget.TextView
|
||||
import android.window.OnBackInvokedDispatcher
|
||||
import android.webkit.ValueCallback
|
||||
import android.webkit.WebChromeClient
|
||||
import android.webkit.WebView
|
||||
import android.webkit.WebViewClient
|
||||
import android.webkit.WebResourceResponse
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URI
|
||||
import java.net.URL
|
||||
import org.json.JSONObject
|
||||
import kotlin.concurrent.thread
|
||||
|
||||
/** Shows the web client served by the local backend in a WebView. */
|
||||
/** Hosts either the embedded slicer or the selected Web Slicer server. */
|
||||
class MainActivity : Activity() {
|
||||
private lateinit var web: WebView
|
||||
private lateinit var content: FrameLayout
|
||||
private var server: String? = null
|
||||
private var localStarted = false
|
||||
private var backendWait: Thread? = null
|
||||
private val preferences by lazy { getSharedPreferences("connection", MODE_PRIVATE) }
|
||||
private val downloads by lazy { Downloads(this) }
|
||||
private val theme by lazy {
|
||||
WebTheme(preferences, {
|
||||
resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES
|
||||
}, ::updateAppearance)
|
||||
}
|
||||
private var chooser: ValueCallback<Array<Uri>>? = null
|
||||
|
||||
@SuppressLint("SetJavaScriptEnabled")
|
||||
@@ -27,69 +50,8 @@ class MainActivity : Activity() {
|
||||
super.onCreate(savedInstanceState)
|
||||
// Debug builds expose the page to DevTools for on-device browser tests.
|
||||
if (applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0) WebView.setWebContentsDebuggingEnabled(true)
|
||||
web = WebView(this)
|
||||
web.settings.javaScriptEnabled = true
|
||||
web.settings.domStorageEnabled = true
|
||||
val downloads = Downloads(this)
|
||||
web.webViewClient = object : WebViewClient() {
|
||||
// Keep the app on its own origin; anything else opens outside.
|
||||
override fun shouldOverrideUrlLoading(view: WebView, request: android.webkit.WebResourceRequest): Boolean {
|
||||
if (request.url.host == "127.0.0.1") {
|
||||
// The backend serves files as attachment links. Some WebView builds navigate
|
||||
// to them instead of firing setDownloadListener, so route the known download
|
||||
// endpoints to the handler here; the handler reads the server's filename.
|
||||
val path = request.url.path ?: ""
|
||||
// The web client asks for the native Bambu sign-in (cloud build only).
|
||||
if (path == "/native/bambu-cloud-login") {
|
||||
@Suppress("DEPRECATION")
|
||||
startActivityForResult(Intent(this@MainActivity, BambuLoginActivity::class.java)
|
||||
.putExtra(BambuLoginActivity.EXTRA_VERSION, request.url.getQueryParameter("plugin_version")),
|
||||
BAMBU_LOGIN)
|
||||
return true
|
||||
}
|
||||
if (path.contains("/artifacts/") || path.endsWith("/download")) {
|
||||
downloads.fromUrl(request.url.toString(), null, null)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
startActivity(Intent(Intent.ACTION_VIEW, request.url))
|
||||
return true
|
||||
}
|
||||
override fun onPageStarted(view: WebView, url: String, favicon: android.graphics.Bitmap?) {
|
||||
if (url.startsWith(Downloads.ORIGIN)) view.evaluateJavascript(Downloads.BLOB_HOOK, null)
|
||||
}
|
||||
override fun onPageFinished(view: WebView, url: String) {
|
||||
if (url.startsWith(Downloads.ORIGIN)) view.evaluateJavascript(Downloads.BLOB_HOOK, null)
|
||||
}
|
||||
}
|
||||
web.addJavascriptInterface(downloads, Downloads.BRIDGE)
|
||||
// Kept as a fallback for WebView builds that do route attachment links here.
|
||||
web.setDownloadListener { url, _, disposition, mimeType, _ -> downloads.fromUrl(url, disposition, mimeType) }
|
||||
web.webChromeClient = object : WebChromeClient() {
|
||||
override fun onShowFileChooser(view: WebView, callback: ValueCallback<Array<Uri>>,
|
||||
params: FileChooserParams): Boolean {
|
||||
chooser?.onReceiveValue(null)
|
||||
chooser = callback
|
||||
startActivityForResult(params.createIntent(), CHOOSE_FILE)
|
||||
return true
|
||||
}
|
||||
}
|
||||
web.loadDataWithBaseURL(null, STARTING_HTML, "text/html", "UTF-8", null)
|
||||
// Android 15 (targetSdk 35) draws the app edge to edge, so the WebView would
|
||||
// sit under the status and navigation bars and the system clock would overlap
|
||||
// the header's menu button. Pad the content by the system bars (and any
|
||||
// display cutout); the padded strip shows the WebView's dark background so it
|
||||
// reads as one surface with the header and footer bars.
|
||||
// Android 15 (targetSdk 35) draws the app edge to edge, so content would sit
|
||||
// under the status and navigation bars and the system clock would overlap the
|
||||
// header's menu button. A WebView swallows window insets for its own use, so
|
||||
// pad a parent container instead and consume the insets there; the padded
|
||||
// strips show the container's dark background, matching the header and footer.
|
||||
val root = FrameLayout(this)
|
||||
root.setBackgroundColor(APP_BACKGROUND)
|
||||
root.addView(web, FrameLayout.LayoutParams(
|
||||
FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT))
|
||||
content = root
|
||||
root.setOnApplyWindowInsetsListener { view, insets ->
|
||||
if (Build.VERSION.SDK_INT >= 30) {
|
||||
val bars = insets.getInsets(WindowInsets.Type.systemBars() or WindowInsets.Type.displayCutout())
|
||||
@@ -104,25 +66,351 @@ class MainActivity : Activity() {
|
||||
}
|
||||
setContentView(root)
|
||||
root.requestApplyInsets()
|
||||
startForegroundService(Intent(this, ServerService::class.java))
|
||||
waitForBackend()
|
||||
val saved = preferences.getString("server", null)?.let(::serverOrigin)
|
||||
open(if (preferences.getBoolean("online", false)) saved else null)
|
||||
if (Build.VERSION.SDK_INT >= 33) {
|
||||
onBackInvokedDispatcher.registerOnBackInvokedCallback(
|
||||
OnBackInvokedDispatcher.PRIORITY_DEFAULT, ::handleBack
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun waitForBackend() = thread(name = "backend-wait") {
|
||||
val origin = "http://127.0.0.1:${ServerService.PORT}"
|
||||
private fun chooseMode() {
|
||||
val savedServer = preferences.getString("server", null)?.let(::serverOrigin)
|
||||
val options = mutableListOf(getString(R.string.connection_offline), getString(R.string.connection_server))
|
||||
if (savedServer != null) options.add(getString(R.string.library_sync))
|
||||
val current = server
|
||||
val title = if (current == null) getString(R.string.connection_settings)
|
||||
else getString(R.string.connection_status, Uri.parse(current).authority)
|
||||
AlertDialog.Builder(this).setTitle(title)
|
||||
.setItems(options.toTypedArray()) { _, item ->
|
||||
when (item) {
|
||||
0 -> select(null)
|
||||
1 -> editServer()
|
||||
2 -> if (savedServer != null) previewLibrarySync(savedServer)
|
||||
}
|
||||
}.show()
|
||||
}
|
||||
|
||||
private fun previewLibrarySync(origin: String) {
|
||||
startLocalBackend()
|
||||
val cookie = android.webkit.CookieManager.getInstance().getCookie(origin)
|
||||
val sync = LibrarySync(origin, cookie, getSharedPreferences("library-sync", MODE_PRIVATE))
|
||||
runSyncTask({ sync.choices() }) { (local, remote) ->
|
||||
val choices = LinearLayout(this).apply {
|
||||
orientation = LinearLayout.VERTICAL
|
||||
val padding = (24 * resources.displayMetrics.density).toInt()
|
||||
setPadding(padding, padding / 2, padding, 0)
|
||||
}
|
||||
fun spinner(label: Int, libraries: List<LibrarySync.Library>): Spinner {
|
||||
val title = TextView(this).apply { setText(label) }
|
||||
val spinner = Spinner(this).apply {
|
||||
id = android.view.View.generateViewId()
|
||||
adapter = ArrayAdapter(this@MainActivity, android.R.layout.simple_spinner_item, libraries.map { it.name })
|
||||
.apply { setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) }
|
||||
}
|
||||
title.labelFor = spinner.id
|
||||
choices.addView(title)
|
||||
choices.addView(spinner)
|
||||
return spinner
|
||||
}
|
||||
val localChoice = spinner(R.string.library_sync_local, local)
|
||||
val remoteChoice = spinner(R.string.library_sync_remote, remote)
|
||||
AlertDialog.Builder(this).setTitle(R.string.library_sync).setView(choices)
|
||||
.setNegativeButton(android.R.string.cancel, null)
|
||||
.setPositiveButton(R.string.library_sync_compare) { _, _ ->
|
||||
compareLibraries(sync, local[localChoice.selectedItemPosition], remote[remoteChoice.selectedItemPosition])
|
||||
}.show()
|
||||
}
|
||||
}
|
||||
|
||||
private fun compareLibraries(sync: LibrarySync, local: LibrarySync.Library, remote: LibrarySync.Library) {
|
||||
runSyncTask({ sync.prepare(local, remote) }) { plan ->
|
||||
val count = plan.toLocal.length() + plan.toRemote.length()
|
||||
val builder = AlertDialog.Builder(this).setTitle(R.string.library_sync)
|
||||
.setMessage(buildString {
|
||||
append(getString(R.string.library_sync_preview, plan.toLocal.length(), plan.toRemote.length()))
|
||||
if (plan.conflicts.isNotEmpty()) {
|
||||
append("\n\n")
|
||||
append(getString(R.string.library_sync_conflicts, plan.conflicts.size))
|
||||
append("\n")
|
||||
append(plan.conflicts.take(8).joinToString("\n") { "• $it" })
|
||||
}
|
||||
})
|
||||
.setNegativeButton(android.R.string.cancel, null)
|
||||
if (count > 0) builder.setPositiveButton(R.string.library_sync_apply) { _, _ ->
|
||||
runSyncTask({ sync.apply(plan) }) { (updated, conflicts) ->
|
||||
AlertDialog.Builder(this).setTitle(R.string.library_sync)
|
||||
.setMessage(getString(R.string.library_sync_done, updated, conflicts))
|
||||
.setPositiveButton(android.R.string.ok, null).show()
|
||||
}
|
||||
}
|
||||
builder.show()
|
||||
}
|
||||
}
|
||||
|
||||
private fun <T> runSyncTask(work: () -> T, completed: (T) -> Unit) {
|
||||
val progress = AlertDialog.Builder(this).setTitle(R.string.library_sync)
|
||||
.setMessage(R.string.library_sync_working).setCancelable(false).show()
|
||||
thread(name = "filament-library-sync") {
|
||||
val result = runCatching(work)
|
||||
runOnUiThread {
|
||||
if (isDestroyed || isFinishing) return@runOnUiThread
|
||||
progress.dismiss()
|
||||
result.onSuccess(completed).onFailure { error ->
|
||||
val status = (error as? LibrarySync.RequestFailed)?.status
|
||||
val message = when (status) {
|
||||
401 -> R.string.library_sync_sign_in
|
||||
404, 405 -> R.string.library_sync_upgrade
|
||||
else -> R.string.library_sync_error
|
||||
}
|
||||
AlertDialog.Builder(this).setTitle(R.string.library_sync)
|
||||
.setMessage(message).setPositiveButton(android.R.string.ok, null).show()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun editServer() {
|
||||
val field = EditText(this).apply {
|
||||
inputType = android.text.InputType.TYPE_CLASS_TEXT or android.text.InputType.TYPE_TEXT_VARIATION_URI
|
||||
setSingleLine(true)
|
||||
setHint(R.string.connection_example)
|
||||
setText(preferences.getString("server", ""))
|
||||
}
|
||||
val dialog = AlertDialog.Builder(this).setTitle(R.string.connection_server)
|
||||
.setView(field)
|
||||
.setNegativeButton(android.R.string.cancel, null)
|
||||
.setPositiveButton(R.string.connection_connect, null)
|
||||
.create()
|
||||
dialog.setOnShowListener {
|
||||
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
|
||||
val origin = serverOrigin(field.text.toString())
|
||||
if (origin == null) field.error = getString(R.string.connection_invalid)
|
||||
else {
|
||||
select(origin)
|
||||
dialog.dismiss()
|
||||
}
|
||||
}
|
||||
}
|
||||
dialog.show()
|
||||
}
|
||||
|
||||
private fun select(origin: String?) {
|
||||
preferences.edit().putBoolean("online", origin != null).apply {
|
||||
if (origin != null) putString("server", origin)
|
||||
}.apply()
|
||||
if (origin != server) open(origin)
|
||||
}
|
||||
|
||||
@SuppressLint("SetJavaScriptEnabled")
|
||||
private fun open(origin: String?) {
|
||||
backendWait?.interrupt()
|
||||
backendWait = null
|
||||
theme.detach()
|
||||
if (::web.isInitialized) {
|
||||
chooser?.onReceiveValue(null)
|
||||
chooser = null
|
||||
content.removeView(web)
|
||||
web.destroy()
|
||||
}
|
||||
server = origin
|
||||
val local = origin == null
|
||||
val activeOrigin = origin ?: Downloads.ORIGIN
|
||||
val view = WebView(this)
|
||||
web = view
|
||||
content.addView(view, FrameLayout.LayoutParams(-1, -1))
|
||||
updateAppearance()
|
||||
view.settings.javaScriptEnabled = true
|
||||
view.settings.domStorageEnabled = true
|
||||
if (!local) view.alpha = 0f
|
||||
view.webViewClient = object : WebViewClient() {
|
||||
private var startupPage = local
|
||||
|
||||
override fun onPageStarted(view: WebView, url: String?, favicon: android.graphics.Bitmap?) {
|
||||
if (web != view) return
|
||||
theme.detach()
|
||||
if (startupPage && url != null && sameOrigin(Uri.parse(url), activeOrigin)) view.alpha = 0f
|
||||
}
|
||||
|
||||
override fun shouldOverrideUrlLoading(view: WebView, request: android.webkit.WebResourceRequest): Boolean {
|
||||
val url = request.url
|
||||
if (url.toString() == CONNECTION_SETTINGS_URL) {
|
||||
if (request.isForMainFrame && request.hasGesture()) chooseMode()
|
||||
return true
|
||||
}
|
||||
if (sameOrigin(url, activeOrigin)) {
|
||||
val path = url.path.orEmpty()
|
||||
if (local && request.isForMainFrame && path == "/native/bambu-cloud-login") {
|
||||
@Suppress("DEPRECATION")
|
||||
startActivityForResult(Intent(this@MainActivity, BambuLoginActivity::class.java)
|
||||
.putExtra(BambuLoginActivity.EXTRA_VERSION, url.getQueryParameter("plugin_version")), BAMBU_LOGIN)
|
||||
return true
|
||||
}
|
||||
if (request.isForMainFrame && (path.contains("/artifacts/") || path.endsWith("/download"))) {
|
||||
download(url.toString(), null, null, activeOrigin)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
if (request.isForMainFrame && url.scheme in setOf("https", "http")) {
|
||||
try { startActivity(Intent(Intent.ACTION_VIEW, url)) }
|
||||
catch (_: android.content.ActivityNotFoundException) { }
|
||||
}
|
||||
return request.isForMainFrame
|
||||
}
|
||||
|
||||
override fun shouldInterceptRequest(view: WebView, request: android.webkit.WebResourceRequest): WebResourceResponse? {
|
||||
// An online page must not be able to reach the embedded backend over cleartext.
|
||||
if (!local && request.url.scheme == "http") {
|
||||
return WebResourceResponse("text/plain", "UTF-8", null)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
override fun onPageFinished(view: WebView, url: String) {
|
||||
if (web != view || !sameOrigin(Uri.parse(url), activeOrigin)) return
|
||||
if (local) view.evaluateJavascript(Downloads.BLOB_HOOK, null)
|
||||
if (startupPage) {
|
||||
view.clearHistory()
|
||||
startupPage = false
|
||||
}
|
||||
val label = JSONObject.quote(getString(R.string.connection_settings))
|
||||
view.evaluateJavascript(connectionMenuScript(label), null)
|
||||
theme.attach(view, Uri.parse(activeOrigin)) {
|
||||
view.postVisualStateCallback(0, object : WebView.VisualStateCallback() {
|
||||
override fun onComplete(requestId: Long) {
|
||||
if (web == view && !isDestroyed) view.alpha = 1f
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
override fun onReceivedError(view: WebView, request: android.webkit.WebResourceRequest,
|
||||
error: android.webkit.WebResourceError) {
|
||||
if (!local && web == view && request.isForMainFrame) {
|
||||
view.alpha = 1f
|
||||
AlertDialog.Builder(this@MainActivity).setMessage(R.string.connection_unavailable)
|
||||
.setPositiveButton(R.string.connection_retry) { _, _ -> view.reload() }
|
||||
.setNeutralButton(R.string.connection_settings) { _, _ -> chooseMode() }
|
||||
.setNegativeButton(R.string.connection_offline) { _, _ -> select(null) }
|
||||
.show()
|
||||
}
|
||||
}
|
||||
}
|
||||
if (local) view.addJavascriptInterface(downloads, Downloads.BRIDGE)
|
||||
view.setDownloadListener { url, _, disposition, mimeType, _ -> download(url, disposition, mimeType, activeOrigin) }
|
||||
view.webChromeClient = object : WebChromeClient() {
|
||||
override fun onShowFileChooser(view: WebView, callback: ValueCallback<Array<Uri>>,
|
||||
params: FileChooserParams): Boolean {
|
||||
chooser?.onReceiveValue(null)
|
||||
return try {
|
||||
startActivityForResult(params.createIntent(), CHOOSE_FILE)
|
||||
chooser = callback
|
||||
true
|
||||
} catch (_: android.content.ActivityNotFoundException) {
|
||||
chooser = null
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
if (local) {
|
||||
val startup = STARTING_HTML
|
||||
.replace("START_THEME", if (theme.dark) "dark" else "light")
|
||||
.replace("CONNECTION_SETTINGS_LABEL",
|
||||
android.text.TextUtils.htmlEncode(getString(R.string.connection_settings)))
|
||||
view.loadDataWithBaseURL(null, startup, "text/html", "UTF-8", null)
|
||||
startLocalBackend()
|
||||
backendWait = waitForBackend(view)
|
||||
} else view.loadUrl("$activeOrigin/")
|
||||
}
|
||||
|
||||
// Insert the native command into both the bundled client and older server
|
||||
// clients. React can replace the sign-in page with the workspace in-place.
|
||||
private fun connectionMenuScript(label: String) = """
|
||||
(() => {
|
||||
if (window.__webSlicerConnectionMenu) return;
|
||||
window.__webSlicerConnectionMenu = true;
|
||||
const entry = document.createElement('a');
|
||||
entry.href = '$CONNECTION_SETTINGS_URL';
|
||||
entry.textContent = $label;
|
||||
entry.className = 'button';
|
||||
entry.setAttribute('data-close-navigation', '');
|
||||
const place = () => {
|
||||
if (entry.isConnected) return;
|
||||
const menu = document.querySelector('[data-native-preferences]') || document.querySelector('#application-navigation > .action-menu:last-child > .action-menu-content');
|
||||
const signIn = document.querySelector('.local-login > section');
|
||||
if (menu) menu.prepend(entry);
|
||||
else signIn?.append(entry);
|
||||
};
|
||||
new MutationObserver(place).observe(document.body, {childList: true, subtree: true});
|
||||
place();
|
||||
})();
|
||||
""".trimIndent()
|
||||
|
||||
private fun startLocalBackend() {
|
||||
if (localStarted) return
|
||||
startForegroundService(Intent(this, ServerService::class.java))
|
||||
localStarted = true
|
||||
}
|
||||
|
||||
private fun download(url: String, disposition: String?, mimeType: String?, origin: String) {
|
||||
if (!sameOrigin(Uri.parse(url), origin)) return
|
||||
val cookie = if (origin == Downloads.ORIGIN) null else android.webkit.CookieManager.getInstance().getCookie(url)
|
||||
downloads.fromUrl(url, disposition, mimeType, origin, cookie)
|
||||
}
|
||||
|
||||
private fun waitForBackend(view: WebView) = thread(name = "backend-wait") {
|
||||
val origin = Downloads.ORIGIN
|
||||
repeat(600) {
|
||||
if (Thread.currentThread().isInterrupted) return@thread
|
||||
try {
|
||||
val connection = URL("$origin/healthz").openConnection() as HttpURLConnection
|
||||
connection.connectTimeout = 500
|
||||
if (connection.responseCode == 200) {
|
||||
runOnUiThread { web.loadUrl("$origin/") }
|
||||
val ready = try {
|
||||
connection.connectTimeout = 500
|
||||
connection.readTimeout = 500
|
||||
connection.responseCode == 200
|
||||
} finally { connection.disconnect() }
|
||||
if (ready) {
|
||||
runOnUiThread { if (!isDestroyed && web == view) view.loadUrl("$origin/") }
|
||||
return@thread
|
||||
}
|
||||
} catch (_: Exception) { }
|
||||
Thread.sleep(500)
|
||||
} catch (_: java.io.IOException) { }
|
||||
try { Thread.sleep(500) } catch (_: InterruptedException) { return@thread }
|
||||
}
|
||||
}
|
||||
|
||||
override fun onConfigurationChanged(newConfig: Configuration) {
|
||||
super.onConfigurationChanged(newConfig)
|
||||
updateAppearance()
|
||||
theme.configurationChanged()
|
||||
}
|
||||
|
||||
private fun updateAppearance() {
|
||||
val dark = theme.dark
|
||||
val background = if (dark) 0xFF20262E.toInt() else 0xFFFFFFFF.toInt()
|
||||
content.setBackgroundColor(background)
|
||||
if (::web.isInitialized) web.setBackgroundColor(background)
|
||||
if (Build.VERSION.SDK_INT >= 30) {
|
||||
val mask = WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS or
|
||||
WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS
|
||||
window.decorView.windowInsetsController?.setSystemBarsAppearance(if (dark) 0 else mask, mask)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
window.decorView.systemUiVisibility = if (dark) 0 else
|
||||
android.view.View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR or android.view.View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
backendWait?.interrupt()
|
||||
theme.detach()
|
||||
chooser?.onReceiveValue(null)
|
||||
content.removeView(web)
|
||||
web.destroy()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
@Deprecated("Activity result API is not used in this minimal host")
|
||||
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
|
||||
if (requestCode == CHOOSE_FILE) {
|
||||
@@ -134,32 +422,94 @@ class MainActivity : Activity() {
|
||||
} else super.onActivityResult(requestCode, resultCode, data)
|
||||
}
|
||||
|
||||
@Deprecated("Back handling follows the WebView history")
|
||||
override fun onBackPressed() { if (web.canGoBack()) web.goBack() else super.onBackPressed() }
|
||||
@Deprecated("Handle system Back without closing the slicer task")
|
||||
override fun onBackPressed() = handleBack()
|
||||
|
||||
private fun handleBack() {
|
||||
val view = web
|
||||
val origin = server ?: Downloads.ORIGIN
|
||||
val url = view.url
|
||||
if (url == null || !sameOrigin(Uri.parse(url), origin)) {
|
||||
moveTaskToBack(true)
|
||||
return
|
||||
}
|
||||
view.evaluateJavascript(CLOSE_WEB_OVERLAY) { handled ->
|
||||
if (isDestroyed || web !== view || handled == "true") return@evaluateJavascript
|
||||
val history = view.copyBackForwardList()
|
||||
val previous = (history.currentIndex - 1 downTo 0).firstOrNull { index ->
|
||||
sameOrigin(Uri.parse(history.getItemAtIndex(index).url), origin)
|
||||
}
|
||||
if (previous != null) view.goBackOrForward(previous - history.currentIndex)
|
||||
else moveTaskToBack(true)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val CHOOSE_FILE = 1; private const val BAMBU_LOGIN = 2
|
||||
// Matches the web client's header/footer bars (--wb-panel) so the inset strips blend in.
|
||||
private const val APP_BACKGROUND = 0xFF20262E.toInt()
|
||||
private const val CHOOSE_FILE = 1
|
||||
private const val BAMBU_LOGIN = 2
|
||||
private const val CONNECTION_SETTINGS_URL = "https://web-slicer.invalid/native/connection-settings"
|
||||
|
||||
// Shown while the local backend starts (a few seconds): the app wordmark over a
|
||||
// spinner in the client's dark theme, so the first frame is not a bare sentence.
|
||||
private val CLOSE_WEB_OVERLAY = """
|
||||
(() => {
|
||||
const dialogs = document.querySelectorAll('dialog[open]');
|
||||
const dialog = document.activeElement?.closest('dialog[open]') || dialogs[dialogs.length - 1];
|
||||
if (dialog) {
|
||||
if (dialog.requestClose) dialog.requestClose();
|
||||
else if (dialog.dispatchEvent(new Event('cancel', {cancelable:true}))) dialog.close();
|
||||
return true;
|
||||
}
|
||||
const target = document.querySelector('.menu-toggle[aria-expanded=true], .tool-bar-all[aria-expanded=true]');
|
||||
if (target) {
|
||||
if (target.matches('.menu-toggle'))
|
||||
document.dispatchEvent(new KeyboardEvent('keydown', {key:'Escape', bubbles:true}));
|
||||
else target.click();
|
||||
return true;
|
||||
}
|
||||
const workbench = document.querySelector('.workbench[data-mobile-panel]:not([data-mobile-panel=""])');
|
||||
if (workbench) {
|
||||
document.dispatchEvent(new KeyboardEvent('keydown', {key:'Escape', bubbles:true}));
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
})();
|
||||
""".trimIndent()
|
||||
|
||||
|
||||
private fun serverOrigin(value: String): String? {
|
||||
val uri = try { URI(value.trim()) } catch (_: java.net.URISyntaxException) { return null }
|
||||
if (!uri.scheme.equals("https", ignoreCase = true) || uri.host == null ||
|
||||
uri.userInfo != null || uri.rawQuery != null || uri.rawFragment != null ||
|
||||
uri.rawPath !in listOf("", "/") || uri.port !in -1..65535 || uri.port == 0) return null
|
||||
val port = if (uri.port in listOf(-1, 443)) "" else ":${uri.port}"
|
||||
return "https://${uri.host.lowercase(java.util.Locale.ROOT)}$port"
|
||||
}
|
||||
|
||||
private fun sameOrigin(url: Uri, origin: String): Boolean {
|
||||
val expected = Uri.parse(origin)
|
||||
fun port(uri: Uri) = if (uri.port != -1) uri.port else if (uri.scheme == "https") 443 else 80
|
||||
return url.scheme == expected.scheme && url.host.equals(expected.host, ignoreCase = true) &&
|
||||
url.userInfo == null && port(url) == port(expected)
|
||||
}
|
||||
// Shown while the local backend starts, using the app's appearance preference.
|
||||
private val STARTING_HTML = """
|
||||
<!DOCTYPE html><html><head>
|
||||
<!DOCTYPE html><html data-theme="START_THEME"><head>
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<style>
|
||||
:root{color-scheme:dark}*{box-sizing:border-box}
|
||||
:root{color-scheme:dark;--bg:#101a21;--fg:#dce7ec;--muted:#a6bec9;--track:#263743;--accent:#8fe3bf}
|
||||
:root[data-theme=light]{color-scheme:light;--bg:#fff;--fg:#202b30;--muted:#586771;--track:#dce3e7;--accent:#147d70}
|
||||
*{box-sizing:border-box}
|
||||
body{margin:0;min-height:100vh;display:flex;flex-direction:column;align-items:center;
|
||||
justify-content:center;gap:30px;font-family:system-ui,-apple-system,sans-serif;
|
||||
background:#101a21;color:#dce7ec;-webkit-user-select:none;user-select:none}
|
||||
background:var(--bg);color:var(--fg);-webkit-user-select:none;user-select:none}
|
||||
.ring{width:60px;height:60px}
|
||||
.ring svg{width:100%;height:100%;animation:spin 1s linear infinite}
|
||||
.ring circle{fill:none;stroke-width:5;stroke-linecap:round}
|
||||
.ring .track{stroke:#263743}
|
||||
.ring .head{stroke:#8fe3bf;stroke-dasharray:150;stroke-dashoffset:110}
|
||||
.ring .track{stroke:var(--track)}
|
||||
.ring .head{stroke:var(--accent);stroke-dasharray:150;stroke-dashoffset:110}
|
||||
.text{display:flex;flex-direction:column;align-items:center;gap:7px}
|
||||
.brand{font-size:23px;font-weight:700;letter-spacing:.3px}
|
||||
.msg{font-size:14px;color:#88a0ab}
|
||||
.msg{font-size:14px;color:var(--muted)}
|
||||
.settings{font-size:14px;color:var(--muted);padding:10px}
|
||||
.msg .dots::after{content:'';animation:dots 1.5s steps(1,end) infinite}
|
||||
@keyframes spin{to{transform:rotate(360deg)}}
|
||||
@keyframes dots{0%{content:''}25%{content:'.'}50%{content:'..'}75%{content:'...'}}
|
||||
@@ -171,6 +521,7 @@ class MainActivity : Activity() {
|
||||
<circle class="head" cx="25" cy="25" r="20"></circle></svg></div>
|
||||
<div class="text"><div class="brand">Web Slicer</div>
|
||||
<div class="msg">Starting the slicer<span class="dots"></span></div></div>
|
||||
<a class="settings" href="$CONNECTION_SETTINGS_URL">CONNECTION_SETTINGS_LABEL</a>
|
||||
</body></html>
|
||||
""".trimIndent()
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import android.content.Intent
|
||||
import android.content.pm.ServiceInfo
|
||||
import android.net.wifi.WifiManager
|
||||
import android.os.IBinder
|
||||
import android.os.ParcelFileDescriptor
|
||||
import android.system.Os
|
||||
import android.util.Log
|
||||
import java.io.File
|
||||
@@ -20,6 +21,7 @@ import kotlin.system.exitProcess
|
||||
* slicer crash cannot take the WebView down with it. One run per process.
|
||||
*/
|
||||
class ServerService : Service() {
|
||||
private var shutdownWriter: ParcelFileDescriptor? = null
|
||||
private var multicast: WifiManager.MulticastLock? = null
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
@@ -28,8 +30,11 @@ class ServerService : Service() {
|
||||
startForeground()
|
||||
if (!started) {
|
||||
started = true
|
||||
val (reader, writer) = ParcelFileDescriptor.createPipe()
|
||||
shutdownWriter = writer
|
||||
val shutdownFd = reader.detachFd()
|
||||
acquireMulticast()
|
||||
thread(name = "backend") { runBackend() }
|
||||
thread(name = "backend") { runBackend(shutdownFd) }
|
||||
}
|
||||
return START_STICKY
|
||||
}
|
||||
@@ -50,12 +55,17 @@ class ServerService : Service() {
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
// EOF asks Uvicorn to close lifespan tasks and their native workers.
|
||||
shutdownWriter?.let { writer ->
|
||||
runCatching { writer.close() }.onFailure { Log.w(TAG, "could not close backend shutdown pipe", it) }
|
||||
}
|
||||
shutdownWriter = null
|
||||
multicast?.let { if (it.isHeld) it.release() }
|
||||
multicast = null
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
private fun runBackend() {
|
||||
private fun runBackend(shutdownFd: Int) {
|
||||
val payload = Payload.install(this)
|
||||
val home = File(payload, "python")
|
||||
val libs = applicationInfo.nativeLibraryDir
|
||||
@@ -88,8 +98,8 @@ class ServerService : Service() {
|
||||
}
|
||||
PythonHost.redirectStdio()
|
||||
val status = PythonHost.run(home.path, "$libs/libpylauncher.so",
|
||||
arrayOf("webslicer", "-m", "android_main", PORT.toString()))
|
||||
Log.e(TAG, "Backend exited with status $status")
|
||||
arrayOf("webslicer", "-m", "android_main", PORT.toString(), shutdownFd.toString()))
|
||||
if (status != 0) Log.e(TAG, "Backend exited with status $status")
|
||||
// A new start gets a fresh interpreter in a fresh process.
|
||||
exitProcess(status)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
package uk.labus.webslicer
|
||||
|
||||
import android.content.SharedPreferences
|
||||
import android.net.Uri
|
||||
import android.webkit.WebMessage
|
||||
import android.webkit.WebMessagePort
|
||||
import android.webkit.WebView
|
||||
import org.json.JSONObject
|
||||
import java.util.UUID
|
||||
|
||||
/** One appearance preference for the embedded and server WebViews. */
|
||||
internal class WebTheme(
|
||||
private val preferences: SharedPreferences,
|
||||
private val systemDark: () -> Boolean,
|
||||
private val appearanceChanged: () -> Unit
|
||||
) {
|
||||
private var choice = preferences.getString("theme", null)
|
||||
private var port: WebMessagePort? = null
|
||||
val dark: Boolean get() = when (choice) {
|
||||
"dark" -> true
|
||||
"light" -> false
|
||||
else -> systemDark()
|
||||
}
|
||||
|
||||
fun attach(view: WebView, origin: Uri, ready: () -> Unit) {
|
||||
detach()
|
||||
val channel = view.createWebMessageChannel()
|
||||
val native = channel[0]
|
||||
port = native
|
||||
native.setWebMessageCallback(object : WebMessagePort.WebMessageCallback() {
|
||||
override fun onMessage(port: WebMessagePort, message: WebMessage) {
|
||||
if (this@WebTheme.port !== port) return
|
||||
val updated = message.data
|
||||
if (updated !in listOf("system", "light", "dark") || updated == choice) return
|
||||
choice = updated
|
||||
preferences.edit().putString("theme", updated).apply()
|
||||
appearanceChanged()
|
||||
}
|
||||
})
|
||||
val ticket = UUID.randomUUID().toString()
|
||||
view.evaluateJavascript(script(choice?.let(JSONObject::quote) ?: "null", systemDark(), ticket)) {
|
||||
if (port !== native) return@evaluateJavascript
|
||||
view.postWebMessage(WebMessage(ticket, arrayOf(channel[1])), origin)
|
||||
ready()
|
||||
}
|
||||
}
|
||||
|
||||
fun configurationChanged() {
|
||||
port?.postMessage(WebMessage(if (systemDark()) "dark" else "light"))
|
||||
}
|
||||
|
||||
fun detach() {
|
||||
port?.close()
|
||||
port = null
|
||||
}
|
||||
|
||||
// The server can run an older client. Use its existing preference key and
|
||||
// storage event so its selector reflects the choice already made in the app.
|
||||
private fun script(saved: String, dark: Boolean, ticket: String) = """
|
||||
(() => {
|
||||
const key = 'orca-theme';
|
||||
const read = () => {
|
||||
try {
|
||||
const value = localStorage.getItem(key);
|
||||
if (value === 'light' || value === 'dark') return value;
|
||||
} catch (_) {}
|
||||
return 'system';
|
||||
};
|
||||
let choice = $saved ?? read();
|
||||
let systemDark = $dark;
|
||||
const apply = () => {
|
||||
document.documentElement.dataset.theme = choice === 'system'
|
||||
? (systemDark ? 'dark' : 'light') : choice;
|
||||
};
|
||||
try { localStorage.setItem(key, choice); } catch (_) {}
|
||||
window.dispatchEvent(new StorageEvent('storage', {key, newValue: choice}));
|
||||
apply();
|
||||
const connect = event => {
|
||||
if (event.data !== '$ticket' || !event.ports.length) return;
|
||||
window.removeEventListener('message', connect);
|
||||
const port = event.ports[0];
|
||||
port.postMessage(choice);
|
||||
port.onmessage = event => {
|
||||
systemDark = event.data === 'dark';
|
||||
if (choice === 'system') apply();
|
||||
};
|
||||
matchMedia('(prefers-color-scheme: dark)').addEventListener('change', apply);
|
||||
document.addEventListener('change', event => {
|
||||
if (event.target instanceof HTMLSelectElement && event.target.closest('.theme-selector')) {
|
||||
choice = event.target.value;
|
||||
apply();
|
||||
port.postMessage(choice);
|
||||
}
|
||||
});
|
||||
};
|
||||
window.addEventListener('message', connect);
|
||||
})();
|
||||
""".trimIndent()
|
||||
}
|
||||
@@ -6,4 +6,25 @@
|
||||
<string name="download_failed">The download could not be saved</string>
|
||||
<string name="bambu_login_done">Signed in to Bambu Lab</string>
|
||||
<string name="bambu_login_failed">Bambu sign-in failed: %1$s</string>
|
||||
<string name="connection_settings">Connection settings</string>
|
||||
<string name="connection_offline">Offline on this device</string>
|
||||
<string name="connection_server">Connect to a Web Slicer server</string>
|
||||
<string name="connection_status">Server · %1$s</string>
|
||||
<string name="connection_example">https://slicer.example.com</string>
|
||||
<string name="connection_connect">Connect</string>
|
||||
<string name="connection_invalid">Enter an HTTPS address without a path.</string>
|
||||
<string name="connection_unavailable">The Web Slicer server could not be reached.</string>
|
||||
<string name="connection_retry">Retry</string>
|
||||
<string name="library_sync">Sync filament library</string>
|
||||
<string name="library_sync_preview">To this device: %1$d. To the server: %2$d.</string>
|
||||
<string name="library_sync_conflicts">%1$d conflicts will be left for manual review:</string>
|
||||
<string name="library_sync_local">Library on this device</string>
|
||||
<string name="library_sync_remote">Library on the server</string>
|
||||
<string name="library_sync_compare">Compare libraries</string>
|
||||
<string name="library_sync_apply">Sync changes</string>
|
||||
<string name="library_sync_working">Checking the filament libraries…</string>
|
||||
<string name="library_sync_done">Filaments updated: %1$d. Conflicts left for review: %2$d.</string>
|
||||
<string name="library_sync_sign_in">Open the server in the app and sign in to Web Slicer before syncing.</string>
|
||||
<string name="library_sync_upgrade">Update the connected Web Slicer server to a version that supports library sync.</string>
|
||||
<string name="library_sync_error">Sync could not complete. Retry to compare the current libraries.</string>
|
||||
</resources>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- The WebView and any framework HTTP only reach the app's own loopback backend.
|
||||
<!-- Only the app's own loopback backend can use cleartext HTTP.
|
||||
The backend (CPython) talks to LAN printers over its own sockets, which are
|
||||
not governed by this config, so no LAN cleartext exception is needed here. -->
|
||||
<network-security-config>
|
||||
|
||||
@@ -127,14 +127,41 @@ Resulting split:
|
||||
and MQTT. The plugin ships only in the separate cloud-enabled build, never in
|
||||
the standard APK (see "Distribution decision": both are published as distinct
|
||||
release APKs).
|
||||
- **Web client/server:** the server runs the same host and plugin (x86_64), but
|
||||
the browser cannot capture the login. It needs a device-side helper (for
|
||||
example the Android app signing in on the server's behalf, or a one-off
|
||||
DevTools user-agent override plus a bridge snippet for testing). Deferred until
|
||||
the Android path works.
|
||||
- **Web client/server:** the browser pairs a
|
||||
[portable desktop helper](../desktop/bambu-login/README.md) with the user's
|
||||
Web Slicer session. The helper opens Bambu's sign-in page in an isolated
|
||||
window and delivers the result to the confirmed HTTPS server. Pairing links
|
||||
expire after ten minutes and are single-use. In authenticated installations
|
||||
each Web Slicer user has a private Bambu runtime directory. A saved physical
|
||||
cloud printer uses its owner's Bambu session and follows normal printer grants.
|
||||
Existing single-instance sessions require a fresh sign-in when switching
|
||||
to authenticated mode.
|
||||
|
||||
### Device panel over the account
|
||||
|
||||
In Printers, **Add from Bambu Lab account** opens the account printer list.
|
||||
The account dialog also offers **Add to printers** beside each device. Select
|
||||
the nozzle preset in the printer wizard and save the cloud connection without
|
||||
entering a LAN address or access code. The connection editor exposes
|
||||
**Bambu Lab cloud** as its own host choice and reports when the build lacks
|
||||
cloud support.
|
||||
|
||||
**Import Bambu Lab presets** opens the preset import review. The native host
|
||||
downloads personal printer, process and filament presets through the plugin.
|
||||
Selected presets become shared templates on confirmation. Account preset
|
||||
synchronization is enabled by default after sign-in in single-user mode. In
|
||||
authenticated server mode, administrators can explicitly review personal
|
||||
presets before importing them into the shared template catalogue. The single-user
|
||||
backend checks the
|
||||
account periodically and publishes imported presets as shared template
|
||||
revisions. Edits to a linked template are sent back to the corresponding
|
||||
Bambu preset. When both copies changed, or a local preset already uses the
|
||||
name, the sync reports a conflict and preserves both copies. New unlinked
|
||||
local templates and deletions stay local. You can pause sync or request an
|
||||
immediate check in the account dialog. Owned presets and open projects keep
|
||||
their settings. Cloud print from the account
|
||||
dialog uses the external spool.
|
||||
|
||||
A saved Bambu connection has `bambu_transport`: `lan` (the printer's own MQTT
|
||||
broker, Developer Mode) or `cloud` (the signed-in account). A cloud connection
|
||||
stores only the serial number and runs the same panel code as LAN
|
||||
|
||||
@@ -4,6 +4,7 @@ The app starts this module in its own process thread. It serves the API under
|
||||
/api and the built web client from the same local origin, which nginx does in
|
||||
the server deployment, and listens on the loopback interface only.
|
||||
"""
|
||||
import asyncio
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
@@ -60,14 +61,36 @@ def _logging_errors(scope, send):
|
||||
return wrapped
|
||||
|
||||
|
||||
async def serve(app, port, shutdown_fd):
|
||||
import uvicorn
|
||||
# Keep forwarded idle connections available. Bound shutdown waits for
|
||||
# open preview streams before running the backend's lifespan cleanup.
|
||||
config = uvicorn.Config(app, host='127.0.0.1', port=port, log_level='info',
|
||||
lifespan='on', ws='websockets', http='h11', loop='asyncio',
|
||||
timeout_keep_alive=120, timeout_graceful_shutdown=3)
|
||||
server = uvicorn.Server(config)
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
def stop():
|
||||
loop.remove_reader(shutdown_fd)
|
||||
server.should_exit = True
|
||||
|
||||
if shutdown_fd is not None:
|
||||
os.set_inheritable(shutdown_fd, False)
|
||||
loop.add_reader(shutdown_fd, stop)
|
||||
try:
|
||||
await server.serve()
|
||||
finally:
|
||||
if shutdown_fd is not None:
|
||||
loop.remove_reader(shutdown_fd)
|
||||
os.close(shutdown_fd)
|
||||
|
||||
|
||||
def main(argv):
|
||||
port = int(argv[1]) if len(argv) > 1 else 8765
|
||||
shutdown_fd = int(argv[2]) if len(argv) > 2 else None
|
||||
frontend = Path(os.environ['WEBSLICER_FRONTEND'])
|
||||
import uvicorn
|
||||
# Clients reuse idle connections; a short keep-alive lets the server close one
|
||||
# just as a request is sent, which over a forwarded port surfaces as a hang-up.
|
||||
uvicorn.run(build(frontend), host='127.0.0.1', port=port, log_level='info',
|
||||
lifespan='on', ws='websockets', http='h11', loop='asyncio', timeout_keep_alive=120)
|
||||
asyncio.run(serve(build(frontend), port, shutdown_fd))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -22,9 +22,9 @@ flags=(-O2 -I"$py/include/python$ver" -L"$py/lib" -lpython$ver -Wl,-z,max-page-s
|
||||
"$bin/aarch64-linux-android29-clang" -shared -fPIC android/native/pyhost.c "${flags[@]}" -llog -o "$libs/libpyhost.so"
|
||||
"$bin/aarch64-linux-android29-clang" -fPIE -pie android/native/pylauncher.c "${flags[@]}" -o "$libs/libpylauncher.so"
|
||||
"$bin/llvm-strip" --strip-unneeded -o "$libs/liborca_headless.so" build/android-headless/src/headless/orca-headless
|
||||
# Optional Bambu cloud sign-in, for the cloud sideload build only (never the default
|
||||
# or a public APK): built by android/scripts/build-bambu-cloud.sh. The plugin is
|
||||
# third-party AGPL code; see android/cloud-and-connectivity.md.
|
||||
# Optional Bambu cloud sign-in, for the -cloud build only (never the standard APK):
|
||||
# built by android/scripts/build-bambu-cloud.sh. The plugin is third-party AGPL
|
||||
# code; see android/cloud-and-connectivity.md for the distribution decision.
|
||||
if [ "${ORCA_ANDROID_BAMBU_CLOUD:-0}" = 1 ]; then
|
||||
say "Bambu cloud (sideload build)"
|
||||
cp build/android-cloud/orca-bambu-cloud "$libs/libbambu_cloud_host.so"
|
||||
@@ -66,7 +66,10 @@ cp -r resources "$payload/resources"
|
||||
say "web client"
|
||||
# The web client build also compiles the WebAssembly preview renderer.
|
||||
(source "${EMSDK:-$HOME/emsdk}/emsdk_env.sh" >/dev/null 2>&1 && cd web/frontend && npm run build --silent >/dev/null)
|
||||
cp -r web/frontend/dist "$payload/frontend"
|
||||
mkdir "$payload/frontend"
|
||||
# Desktop helper archives are served by the web image only.
|
||||
find web/frontend/dist -mindepth 1 -maxdepth 1 ! -name bambu-login \
|
||||
-exec cp -rt "$payload/frontend/" -- {} +
|
||||
|
||||
say "payload.zip"
|
||||
(cd "$payload" && python3 -c "
|
||||
|
||||
+3
-3
@@ -1,6 +1,6 @@
|
||||
services:
|
||||
app:
|
||||
image: ${ORCA_IMAGE_PREFIX:-gitea.labus.uk/karol/web-slicer}-app:${ORCA_IMAGE_TAG:-0.2.2-alpha}
|
||||
image: ${ORCA_IMAGE_PREFIX:-gitea.labus.uk/karol/web-slicer}-app:${ORCA_IMAGE_TAG:-0.3.1-alpha}
|
||||
init: true
|
||||
restart: unless-stopped
|
||||
logging:
|
||||
@@ -67,7 +67,7 @@ services:
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
image: ${ORCA_IMAGE_PREFIX:-gitea.labus.uk/karol/web-slicer}-web:${ORCA_IMAGE_TAG:-0.2.2-alpha}
|
||||
image: ${ORCA_IMAGE_PREFIX:-gitea.labus.uk/karol/web-slicer}-web:${ORCA_IMAGE_TAG:-0.3.1-alpha}
|
||||
restart: unless-stopped
|
||||
logging:
|
||||
driver: json-file
|
||||
@@ -81,7 +81,7 @@ services:
|
||||
condition: service_healthy
|
||||
demo:
|
||||
profiles: [demo]
|
||||
image: ${ORCA_IMAGE_PREFIX:-gitea.labus.uk/karol/web-slicer}-demo:${ORCA_IMAGE_TAG:-0.2.2-alpha}
|
||||
image: ${ORCA_IMAGE_PREFIX:-gitea.labus.uk/karol/web-slicer}-demo:${ORCA_IMAGE_TAG:-0.3.1-alpha}
|
||||
restart: unless-stopped
|
||||
read_only: true
|
||||
cpus: 0.25
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
node_modules/
|
||||
dist/
|
||||
@@ -0,0 +1,33 @@
|
||||
# Web Slicer Bambu Login
|
||||
|
||||
This portable helper pairs a Bambu Lab login with an HTTPS Web Slicer
|
||||
instance configured for Bambu Cloud and local authentication.
|
||||
It uses an isolated browser window for the Bambu Lab sign-in page.
|
||||
The signed-in Web Slicer user generates a single-use pairing link
|
||||
that expires after ten minutes. The desktop helper sends the login result to
|
||||
the confirmed server over HTTPS and keeps no local Bambu session after closing.
|
||||
|
||||
In Web Slicer open **Bambu Lab account → Desktop helper**. Download the archive for your system
|
||||
and select **Create pairing link**.
|
||||
Copy the pairing link, paste it into the helper and confirm the server address.
|
||||
Return to Web Slicer after the helper confirms the account is connected.
|
||||
|
||||
## Packaging
|
||||
|
||||
With Node.js and npm installed, run from this directory:
|
||||
|
||||
```sh
|
||||
npm ci
|
||||
npm run package -- --platform=linux --arch=x64
|
||||
npm run package -- --platform=win32 --arch=x64
|
||||
npm run package -- --platform=darwin --arch=arm64
|
||||
```
|
||||
|
||||
To make the archives available in the account dialog, serve them under
|
||||
`/bambu-login/` as `WebSlicerBambuLogin-linux-x64.zip` and
|
||||
`WebSlicerBambuLogin-win32-x64.zip`. Archive the entire generated directory
|
||||
from `dist/`. Run
|
||||
`WebSlicerBambuLogin` on Linux, `WebSlicerBambuLogin.exe` on Windows or
|
||||
`WebSlicerBambuLogin.app` on macOS. Use `--arch=x64` for Intel Macs.
|
||||
Packages generated with these commands are development artifacts. Production
|
||||
distribution should use platform code signing and macOS notarization.
|
||||
@@ -0,0 +1,16 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<meta charset="utf-8">
|
||||
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self'; style-src 'self'">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>Web Slicer Bambu Login</title>
|
||||
<link rel="stylesheet" href="style.css">
|
||||
<h1>Connect Bambu Lab to Web Slicer</h1>
|
||||
<form>
|
||||
<label for="link">Pairing link from Web Slicer</label>
|
||||
<input id="link" type="url" autocomplete="off" required autofocus>
|
||||
<button type="submit">Open Bambu Lab sign-in</button>
|
||||
</form>
|
||||
<p role="status" id="status"></p>
|
||||
<script src="setup.js"></script>
|
||||
</html>
|
||||
@@ -0,0 +1,118 @@
|
||||
const {app, BrowserWindow, dialog, ipcMain, nativeTheme, session} = require('electron');
|
||||
const path = require('node:path');
|
||||
|
||||
const officialSignIn = 'https://bambulab.com/sign-in';
|
||||
const officialOrigins = new Set(['https://bambulab.com', 'https://www.bambulab.com']);
|
||||
const preferences = {
|
||||
preload: path.join(__dirname, 'preload.cjs'),
|
||||
contextIsolation: true,
|
||||
sandbox: true,
|
||||
nodeIntegration: false
|
||||
};
|
||||
let setup, signIn, pairing, sending;
|
||||
|
||||
function parseLink(value) {
|
||||
const url = new URL(value.trim());
|
||||
const params = new URLSearchParams(url.hash.slice(1));
|
||||
const code = params.get('bambu_pairing');
|
||||
const version = params.get('version');
|
||||
if (url.protocol !== 'https:' || url.username || url.password || !url.pathname.endsWith('/bambu-cloud/desktop-login/redeem') ||
|
||||
url.search || !code || !/^[A-Za-z0-9_-]{43}$/.test(code))
|
||||
throw new Error('Paste the HTTPS pairing link from Web Slicer.');
|
||||
url.hash = '';
|
||||
return {origin: url.origin, endpoint: url.href, code, version: /^\d{2}(\.\d{2}){2,3}$/.test(version ?? '') ? version : '02.09.01.99'};
|
||||
}
|
||||
|
||||
function openSignIn() {
|
||||
const partition = session.fromPartition('bambu-' + crypto.randomUUID());
|
||||
partition.setPermissionRequestHandler((_contents, _permission, callback) => callback(false));
|
||||
partition.setPermissionCheckHandler(() => false);
|
||||
partition.on('will-download', event => event.preventDefault());
|
||||
signIn = new BrowserWindow({title: 'Bambu Lab sign-in', width: 820, height: 760,
|
||||
webPreferences: {...preferences, session: partition}});
|
||||
const window = signIn;
|
||||
const contents = window.webContents;
|
||||
contents.setWindowOpenHandler(() => ({action: 'deny'}));
|
||||
const checkNavigation = (event) => {
|
||||
if (!officialOrigins.has(new URL(event.url).origin)) event.preventDefault();
|
||||
};
|
||||
contents.on('will-navigate', checkNavigation);
|
||||
contents.on('will-redirect', checkNavigation);
|
||||
const theme = nativeTheme.shouldUseDarkColors ? 'dark' : 'light';
|
||||
contents.setUserAgent(partition.getUserAgent() + ' BBL-Slicer/v' + pairing.version +
|
||||
' (' + theme + ') BBL-Language/' + app.getLocale().split('-')[0]);
|
||||
window.on('closed', () => {
|
||||
signIn = null;
|
||||
if (!sending) pairing = null;
|
||||
void partition.clearStorageData().catch(() => {});
|
||||
});
|
||||
return window.loadURL(officialSignIn);
|
||||
}
|
||||
|
||||
ipcMain.handle('pairing:open', async (event, value) => {
|
||||
if (!setup || event.senderFrame !== setup.webContents.mainFrame || signIn || sending)
|
||||
return 'Close the current sign-in before starting another one.';
|
||||
try {
|
||||
pairing = parseLink(value);
|
||||
} catch (error) {
|
||||
return error.message;
|
||||
}
|
||||
const result = await dialog.showMessageBox(setup, {
|
||||
type: 'question', title: 'Confirm Web Slicer server',
|
||||
message: 'Send the Bambu sign-in to this Web Slicer?',
|
||||
detail: pairing.origin, buttons: ['Cancel', 'Continue'], defaultId: 0, cancelId: 0
|
||||
});
|
||||
if (result.response !== 1) {pairing = null;return '';}
|
||||
try {
|
||||
await openSignIn();
|
||||
return 'Complete sign-in in the Bambu Lab window.';
|
||||
} catch {
|
||||
signIn?.close();
|
||||
pairing = null;
|
||||
return 'Could not open the Bambu Lab sign-in page.';
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.on('pairing:result', async (event, message) => {
|
||||
const frame = event.senderFrame;
|
||||
if (!signIn || frame !== signIn.webContents.mainFrame || !frame ||
|
||||
!officialOrigins.has(new URL(frame.url).origin) || !pairing || sending ||
|
||||
typeof message !== 'string' || message.length > 65536) return;
|
||||
let body;
|
||||
try {
|
||||
const {command, data} = JSON.parse(message);
|
||||
if (command === 'user_ticket_login' && /^[A-Za-z0-9]{4,64}$/.test(data?.ticket ?? '')) body = {ticket: data.ticket};
|
||||
if (command === 'user_login' && data && typeof data === 'object' && !Array.isArray(data)) body = {session: data};
|
||||
} catch {return;}
|
||||
if (!body) return;
|
||||
sending = true;
|
||||
const {endpoint, code} = pairing;
|
||||
let accepted = false;
|
||||
try {
|
||||
const response = await fetch(endpoint, {
|
||||
method: 'POST', redirect: 'error', signal: AbortSignal.timeout(60000),
|
||||
headers: {'Content-Type': 'application/json', Authorization: 'Bearer ' + code},
|
||||
body: JSON.stringify(body)
|
||||
});
|
||||
accepted = response.status === 204;
|
||||
} catch {/* Report a generic error without exposing credentials. */}
|
||||
signIn?.close();
|
||||
pairing = null;
|
||||
sending = false;
|
||||
if (setup && !setup.isDestroyed()) {
|
||||
await dialog.showMessageBox(setup, {
|
||||
type: accepted ? 'info' : 'error',
|
||||
message: accepted ? 'Bambu Lab account linked' : 'Could not link the Bambu Lab account',
|
||||
detail: accepted ? 'You can return to Web Slicer now.' : 'Create a new pairing link in Web Slicer and try again.'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
app.whenReady().then(() => {
|
||||
setup = new BrowserWindow({title: 'Web Slicer Bambu Login', width: 620, height: 360, webPreferences: preferences});
|
||||
setup.webContents.setWindowOpenHandler(() => ({action: 'deny'}));
|
||||
setup.webContents.on('will-navigate', event => event.preventDefault());
|
||||
setup.on('closed', () => {setup = null;app.quit();});
|
||||
return setup.loadFile(path.join(__dirname, 'index.html'));
|
||||
});
|
||||
app.on('window-all-closed', () => app.quit());
|
||||
Generated
+728
@@ -0,0 +1,728 @@
|
||||
{
|
||||
"name": "web-slicer-bambu-login",
|
||||
"version": "0.1.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "web-slicer-bambu-login",
|
||||
"version": "0.1.0",
|
||||
"devDependencies": {
|
||||
"@electron/packager": "20.3.0",
|
||||
"electron": "45.4.1"
|
||||
}
|
||||
},
|
||||
"node_modules/@electron-internal/extract-zip": {
|
||||
"version": "1.0.8",
|
||||
"resolved": "https://registry.npmjs.org/@electron-internal/extract-zip/-/extract-zip-1.0.8.tgz",
|
||||
"integrity": "sha512-8iajeLFbzNwM0m3AsQZSZgYREWglAImyGvvFSWU34FgMW8sHlzdwj9QKvv9dgN7jMP591EFUF/sLOC3Jl9YIjQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=22.12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@electron/asar": {
|
||||
"version": "4.3.2",
|
||||
"resolved": "https://registry.npmjs.org/@electron/asar/-/asar-4.3.2.tgz",
|
||||
"integrity": "sha512-2nwyO3OgmLgkYQe6TzB8FmyrBKGgmXzSO51ozoG2BpHOLPTPdQpBt/zD0MdPkhQr4UqVgw3u09y4uYxgZKhmtg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"glob": "^14.0.2",
|
||||
"minimatch": "^11.0.1"
|
||||
},
|
||||
"bin": {
|
||||
"asar": "bin/asar.mjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@electron/get": {
|
||||
"version": "5.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@electron/get/-/get-5.1.0.tgz",
|
||||
"integrity": "sha512-3kSBtG8ObcTVfXanm5vVJ6UnBLEVmVsRk1M+vGqCuMBV+XLCbJYuWQful+yIy0GQDsSlK0kHEriEHn7SPk4EnA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"debug": "^4.1.1",
|
||||
"env-paths": "^3.0.0",
|
||||
"graceful-fs": "^4.2.11",
|
||||
"progress": "^2.0.3",
|
||||
"semver": "^7.6.3",
|
||||
"sumchecker": "^3.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.12.0"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"undici": "^7.24.4"
|
||||
}
|
||||
},
|
||||
"node_modules/@electron/notarize": {
|
||||
"version": "3.1.2",
|
||||
"resolved": "https://registry.npmjs.org/@electron/notarize/-/notarize-3.1.2.tgz",
|
||||
"integrity": "sha512-S/EH6W/GTe3XiD4oYHW+6xuUWZWjc9F5gayMrNdmRLv7qG9KRYmYE26+RDgC1hYUZVY3qLpa1VftxuL+sL5VQg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"debug": "^4.4.0",
|
||||
"promise-retry": "^2.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 22.12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@electron/osx-sign": {
|
||||
"version": "2.7.2",
|
||||
"resolved": "https://registry.npmjs.org/@electron/osx-sign/-/osx-sign-2.7.2.tgz",
|
||||
"integrity": "sha512-BD5ZyKDzzC1PLzWQCl1nw+X2/ErRCJGEIPwtjfOnCH+8KRLfBe/Vr9khUuEJC5bbrVACl8uO2Q2O/UqOzrcFgw==",
|
||||
"dev": true,
|
||||
"license": "BSD-2-Clause",
|
||||
"dependencies": {
|
||||
"debug": "^4.3.4",
|
||||
"isbinaryfile": "^4.0.8",
|
||||
"plist": "^3.0.5",
|
||||
"semver": "^7.7.1"
|
||||
},
|
||||
"bin": {
|
||||
"electron-osx-flat": "bin/electron-osx-flat.mjs",
|
||||
"electron-osx-sign": "bin/electron-osx-sign.mjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@electron/packager": {
|
||||
"version": "20.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@electron/packager/-/packager-20.3.0.tgz",
|
||||
"integrity": "sha512-3MvgJgy6YJ5ti0oGGBKrWKdYwpTaoRrhranMDgHSQ6i5t56yZV9IRDyoXTuqBp97LiKqnZeAMe2wTcF/9+fP5g==",
|
||||
"dev": true,
|
||||
"license": "BSD-2-Clause",
|
||||
"dependencies": {
|
||||
"@electron-internal/extract-zip": "^1.0.1",
|
||||
"@electron/asar": "^4.0.1",
|
||||
"@electron/get": "^5.0.0",
|
||||
"@electron/notarize": "^3.1.0",
|
||||
"@electron/osx-sign": "^2.2.0",
|
||||
"@electron/universal": "^3.0.1",
|
||||
"@electron/windows-sign": "^2.0.2",
|
||||
"@malept/cross-spawn-promise": "^2.0.0",
|
||||
"debug": "^4.4.1",
|
||||
"filenamify": "^6.0.0",
|
||||
"galactus": "^2.0.2",
|
||||
"graceful-fs": "^4.2.11",
|
||||
"junk": "^4.0.1",
|
||||
"plist": "^3.1.0",
|
||||
"resedit": "^2.0.3",
|
||||
"semver": "^7.7.2",
|
||||
"yargs-parser": "^22.0.0"
|
||||
},
|
||||
"bin": {
|
||||
"electron-packager": "bin/electron-packager.mjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 22.12.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/electron/packager?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/@electron/universal": {
|
||||
"version": "3.0.6",
|
||||
"resolved": "https://registry.npmjs.org/@electron/universal/-/universal-3.0.6.tgz",
|
||||
"integrity": "sha512-MonS1kfkZdSEkLZI0pdR/TCx8ecxwRSFm7sORfwIkDI9UaIbHnk4Mgeqq+Ob9qDQRV8LZ9+hHCmimpA9BRcNxw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@electron/asar": "^4.0.0",
|
||||
"debug": "^4.3.1",
|
||||
"plist": "^3.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@electron/windows-sign": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@electron/windows-sign/-/windows-sign-2.1.0.tgz",
|
||||
"integrity": "sha512-hyRE175pWNxU3R0k7B7Zwm4KpSgK/Ql+7yqUPRfnYc9K06uVPJDLvXH6oXpl/RAKbLu0Y114xuH6BdjDhF/pKA==",
|
||||
"dev": true,
|
||||
"license": "BSD-2-Clause",
|
||||
"dependencies": {
|
||||
"debug": "^4.3.4",
|
||||
"graceful-fs": "^4.2.11",
|
||||
"postject": "^1.0.0-alpha.6"
|
||||
},
|
||||
"bin": {
|
||||
"electron-windows-sign": "bin/electron-windows-sign.mjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@isaacs/nonrecursive-glob-match": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@isaacs/nonrecursive-glob-match/-/nonrecursive-glob-match-1.1.0.tgz",
|
||||
"integrity": "sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==",
|
||||
"dev": true,
|
||||
"license": "BlueOak-1.0.0"
|
||||
},
|
||||
"node_modules/@malept/cross-spawn-promise": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@malept/cross-spawn-promise/-/cross-spawn-promise-2.0.0.tgz",
|
||||
"integrity": "sha512-1DpKU0Z5ThltBwjNySMC14g0CkbyhCaz9FkhxqNsZI6uAPJXFS8cMXlBKo26FJ8ZuW6S9GCMcR9IO5k2X5/9Fg==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
"type": "individual",
|
||||
"url": "https://github.com/sponsors/malept"
|
||||
},
|
||||
{
|
||||
"type": "tidelift",
|
||||
"url": "https://tidelift.com/subscription/pkg/npm-.malept-cross-spawn-promise?utm_medium=referral&utm_source=npm_fund"
|
||||
}
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"cross-spawn": "^7.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 12.13.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/node": {
|
||||
"version": "24.19.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.19.2.tgz",
|
||||
"integrity": "sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"undici-types": ">=7.24.0 <7.24.7"
|
||||
}
|
||||
},
|
||||
"node_modules/@xmldom/xmldom": {
|
||||
"version": "0.9.12",
|
||||
"resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.9.12.tgz",
|
||||
"integrity": "sha512-5AXjrcMClTryPe9LgZrygpB1lj7s0S9E0+W+AHaVKAVyHanafK86iPSvG5xHVSp/jC+VH1UXu0TAEmY279xH7A==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=14.6"
|
||||
}
|
||||
},
|
||||
"node_modules/balanced-match": {
|
||||
"version": "4.0.4",
|
||||
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz",
|
||||
"integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": "18 || 20 || >=22"
|
||||
}
|
||||
},
|
||||
"node_modules/base64-js": {
|
||||
"version": "1.5.1",
|
||||
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
|
||||
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/feross"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/feross"
|
||||
},
|
||||
{
|
||||
"type": "consulting",
|
||||
"url": "https://feross.org/support"
|
||||
}
|
||||
],
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/brace-expansion": {
|
||||
"version": "5.0.13",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.13.tgz",
|
||||
"integrity": "sha512-Vh3dmFbc4wZeox7M9I/0L9GfFd83Su4+yCck/OF9Gi/P/dAHn0RT7X4K9R7gMNMhDck3DvhR6QXsnQdjjgwNvQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"balanced-match": "^4.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": "20 || >=22"
|
||||
}
|
||||
},
|
||||
"node_modules/commander": {
|
||||
"version": "9.5.0",
|
||||
"resolved": "https://registry.npmjs.org/commander/-/commander-9.5.0.tgz",
|
||||
"integrity": "sha512-KRs7WVDKg86PWiuAqhDrAQnTXZKraVcCc6vFdL14qrZ/DcWwuRo7VoiYXalXO7S5GKpqYiVEwCbgFDfxNHKJBQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": "^12.20.0 || >=14"
|
||||
}
|
||||
},
|
||||
"node_modules/cross-spawn": {
|
||||
"version": "7.0.6",
|
||||
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
|
||||
"integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"path-key": "^3.1.0",
|
||||
"shebang-command": "^2.0.0",
|
||||
"which": "^2.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/debug": {
|
||||
"version": "4.4.3",
|
||||
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
|
||||
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ms": "^2.1.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"supports-color": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/electron": {
|
||||
"version": "45.4.1",
|
||||
"resolved": "https://registry.npmjs.org/electron/-/electron-45.4.1.tgz",
|
||||
"integrity": "sha512-DjsJ/eQhovkjf1vYFFyh5GB8NMx+L5bdYaonvGOlWselg3DQ0fwIF0N/+2hrPsoS4whmmNswh21ym/8dgt1y5Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@electron-internal/extract-zip": "^1.0.1",
|
||||
"@electron/get": "^5.0.0",
|
||||
"@types/node": "^24.9.0"
|
||||
},
|
||||
"bin": {
|
||||
"electron": "cli.js",
|
||||
"install-electron": "install.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 22.12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/env-paths": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/env-paths/-/env-paths-3.0.0.tgz",
|
||||
"integrity": "sha512-dtJUTepzMW3Lm/NPxRf3wP4642UWhjL2sQxc+ym2YMj1m/H2zDNQOlezafzkHwn6sMstjHTwG6iQQsctDW/b1A==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": "^12.20.0 || ^14.13.1 || >=16.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/err-code": {
|
||||
"version": "2.0.3",
|
||||
"resolved": "https://registry.npmjs.org/err-code/-/err-code-2.0.3.tgz",
|
||||
"integrity": "sha512-2bmlRpNKBxT/CRmPOlyISQpNj+qSeYvcym/uT0Jx2bMOlKLtSy1ZmLuVxSEKKyor/N5yhvp/ZiG1oE3DEYMSFA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/filename-reserved-regex": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/filename-reserved-regex/-/filename-reserved-regex-3.0.0.tgz",
|
||||
"integrity": "sha512-hn4cQfU6GOT/7cFHXBqeBg2TbrMBgdD0kcjLhvSQYYwm3s4B6cjvBfb7nBALJLAXqmU5xajSa7X2NnUud/VCdw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": "^12.20.0 || ^14.13.1 || >=16.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/filenamify": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/filenamify/-/filenamify-6.0.0.tgz",
|
||||
"integrity": "sha512-vqIlNogKeyD3yzrm0yhRMQg8hOVwYcYRfjEoODd49iCprMn4HL85gK3HcykQE53EPIpX3HcAbGA5ELQv216dAQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"filename-reserved-regex": "^3.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/flora-colossus": {
|
||||
"version": "3.0.2",
|
||||
"resolved": "https://registry.npmjs.org/flora-colossus/-/flora-colossus-3.0.2.tgz",
|
||||
"integrity": "sha512-Jk78K/Tzt6saxQPGChlJw69xuFGpWyTSAS8EdU0h/FyXwD2K46yNOXmo6nRHcZ9ooekyBAzMkwmiGNt7wOC5zg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"debug": "^4.4.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/galactus": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/galactus/-/galactus-2.0.2.tgz",
|
||||
"integrity": "sha512-HmKyTFGomdAchz4umx8MwBnrnfFmdpwiTyGA4ZOF7rya2Lmgbc9qate4yweInL+0gUBVImhaz12SBGpW3SY4Yg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"debug": "^4.4.1",
|
||||
"flora-colossus": "^3.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/glob": {
|
||||
"version": "14.0.6",
|
||||
"resolved": "https://registry.npmjs.org/glob/-/glob-14.0.6.tgz",
|
||||
"integrity": "sha512-OwXjVP2svY5EyLY75Vek96C8qK43gqrt4xsZ+qSILdnaEiJPXkd62mcfUSNx/TQErQRdu5uM5kF67sfONragKw==",
|
||||
"dev": true,
|
||||
"license": "BlueOak-1.0.0",
|
||||
"dependencies": {
|
||||
"minimatch": "^11.0.5",
|
||||
"minipass": "^7.1.3",
|
||||
"path-scurry": "^3.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "18 || 20 || >=22"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/isaacs"
|
||||
}
|
||||
},
|
||||
"node_modules/graceful-fs": {
|
||||
"version": "4.2.12",
|
||||
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.12.tgz",
|
||||
"integrity": "sha512-iuyGF2E4oafQfPsRrG2wtY2ILupMhvtdrhzrxB+0VcjsPpSPttpfYdjnGFGsTi5MaJFjI1jOKHPQ6UTbTj9TAw==",
|
||||
"dev": true,
|
||||
"license": "BlueOak-1.0.0"
|
||||
},
|
||||
"node_modules/isbinaryfile": {
|
||||
"version": "4.0.10",
|
||||
"resolved": "https://registry.npmjs.org/isbinaryfile/-/isbinaryfile-4.0.10.tgz",
|
||||
"integrity": "sha512-iHrqe5shvBUcFbmZq9zOQHBoeOhZJu6RQGrDpBgenUm/Am+F3JM2MgQj+rK3Z601fzrL5gLZWtAPH2OBaSVcyw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 8.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/gjtorikian/"
|
||||
}
|
||||
},
|
||||
"node_modules/isexe": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
|
||||
"integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/junk": {
|
||||
"version": "4.0.1",
|
||||
"resolved": "https://registry.npmjs.org/junk/-/junk-4.0.1.tgz",
|
||||
"integrity": "sha512-Qush0uP+G8ZScpGMZvHUiRfI0YBWuB3gVBYlI0v0vvOJt5FLicco+IkP0a50LqTTQhmts/m6tP5SWE+USyIvcQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12.20"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/lru-cache": {
|
||||
"version": "11.5.3",
|
||||
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz",
|
||||
"integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==",
|
||||
"dev": true,
|
||||
"license": "BlueOak-1.0.0",
|
||||
"engines": {
|
||||
"node": "20 || >=22"
|
||||
}
|
||||
},
|
||||
"node_modules/minimatch": {
|
||||
"version": "11.0.9",
|
||||
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.9.tgz",
|
||||
"integrity": "sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q==",
|
||||
"dev": true,
|
||||
"license": "BlueOak-1.0.0",
|
||||
"dependencies": {
|
||||
"@isaacs/nonrecursive-glob-match": "^1.1.0",
|
||||
"brace-expansion": "^5.0.12"
|
||||
},
|
||||
"engines": {
|
||||
"node": "20 || >=22"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/isaacs"
|
||||
}
|
||||
},
|
||||
"node_modules/minipass": {
|
||||
"version": "7.1.3",
|
||||
"resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz",
|
||||
"integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==",
|
||||
"dev": true,
|
||||
"license": "BlueOak-1.0.0",
|
||||
"engines": {
|
||||
"node": ">=16 || 14 >=14.17"
|
||||
}
|
||||
},
|
||||
"node_modules/ms": {
|
||||
"version": "2.1.3",
|
||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
|
||||
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/path-key": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
|
||||
"integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/path-scurry": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-3.0.0.tgz",
|
||||
"integrity": "sha512-1pTbQqH1wIwMi/eleQ5leFTTCkzFsPcgXNjwOA8YGGW/W4/kHT3dssE7Z6NH+zuqNLOzOB0uaD61yl7cAcVhgg==",
|
||||
"dev": true,
|
||||
"license": "BlueOak-1.0.0",
|
||||
"dependencies": {
|
||||
"lru-cache": "^11.0.0",
|
||||
"minipass": "^7.1.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": "18 || 20 || >=22"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/isaacs"
|
||||
}
|
||||
},
|
||||
"node_modules/pe-library": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/pe-library/-/pe-library-1.0.1.tgz",
|
||||
"integrity": "sha512-nh39Mo1eGWmZS7y+mK/dQIqg7S1lp38DpRxkyoHf0ZcUs/HDc+yyTjuOtTvSMZHmfSLuSQaX945u05Y2Q6UWZg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=14",
|
||||
"npm": ">=7"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/jet2jet"
|
||||
}
|
||||
},
|
||||
"node_modules/plist": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/plist/-/plist-3.1.1.tgz",
|
||||
"integrity": "sha512-ZIfcLJC+7E7FBFnDxm9MPmt7D+DidyQ26lewieO75AdhA2ayMtsJSES0iWzqJQbcVRSrTufQoy0DR94xHue0oA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@xmldom/xmldom": "^0.9.10",
|
||||
"base64-js": "^1.5.1",
|
||||
"xmlbuilder": "^15.1.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/postject": {
|
||||
"version": "1.0.0-alpha.6",
|
||||
"resolved": "https://registry.npmjs.org/postject/-/postject-1.0.0-alpha.6.tgz",
|
||||
"integrity": "sha512-b9Eb8h2eVqNE8edvKdwqkrY6O7kAwmI8kcnBv1NScolYJbo59XUF0noFq+lxbC1yN20bmC0WBEbDC5H/7ASb0A==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"commander": "^9.4.0"
|
||||
},
|
||||
"bin": {
|
||||
"postject": "dist/cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/progress": {
|
||||
"version": "2.0.3",
|
||||
"resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz",
|
||||
"integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/promise-retry": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/promise-retry/-/promise-retry-2.0.1.tgz",
|
||||
"integrity": "sha512-y+WKFlBR8BGXnsNlIHFGPZmyDf3DFMoLhaflAnyZgV6rG6xu+JwesTo2Q9R6XwYmtmwAFCkAk3e35jEdoeh/3g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"err-code": "^2.0.2",
|
||||
"retry": "^0.12.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/resedit": {
|
||||
"version": "2.0.3",
|
||||
"resolved": "https://registry.npmjs.org/resedit/-/resedit-2.0.3.tgz",
|
||||
"integrity": "sha512-oTeemxwoMuxxTYxXUwjkrOPfngTQehlv0/HoYFNkB4uzsP1Un1A9nI8JQKGOFkxpqkC7qkMs0lUsGrvUlbLNUA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"pe-library": "^1.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14",
|
||||
"npm": ">=7"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/jet2jet"
|
||||
}
|
||||
},
|
||||
"node_modules/retry": {
|
||||
"version": "0.12.0",
|
||||
"resolved": "https://registry.npmjs.org/retry/-/retry-0.12.0.tgz",
|
||||
"integrity": "sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 4"
|
||||
}
|
||||
},
|
||||
"node_modules/semver": {
|
||||
"version": "7.8.6",
|
||||
"resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz",
|
||||
"integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"bin": {
|
||||
"semver": "bin/semver.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/shebang-command": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
|
||||
"integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"shebang-regex": "^3.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/shebang-regex": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
|
||||
"integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/sumchecker": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/sumchecker/-/sumchecker-3.0.1.tgz",
|
||||
"integrity": "sha512-MvjXzkz/BOfyVDkG0oFOtBxHX2u3gKbMHIF/dXblZsgD3BWOFLmHovIpZY7BykJdAjcqRCBi1WYBNdEC9yI7vg==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"debug": "^4.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/undici": {
|
||||
"version": "7.30.2",
|
||||
"resolved": "https://registry.npmjs.org/undici/-/undici-7.30.2.tgz",
|
||||
"integrity": "sha512-mLyPQnHwUxaM/rideoK/+KL8DaAJLRl4aBCfmX444aCSLnIaomqPLtNRe2jdCYcsk5wZzXrDIQC8ZeYNRAYyIA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"engines": {
|
||||
"node": ">=20.18.1"
|
||||
}
|
||||
},
|
||||
"node_modules/undici-types": {
|
||||
"version": "7.24.6",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz",
|
||||
"integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/which": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
|
||||
"integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"isexe": "^2.0.0"
|
||||
},
|
||||
"bin": {
|
||||
"node-which": "bin/node-which"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/xmlbuilder": {
|
||||
"version": "15.1.1",
|
||||
"resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-15.1.1.tgz",
|
||||
"integrity": "sha512-yMqGBqtXyeN1e3TGYvgNgDVZ3j84W4cwkOXQswghol6APgZWaff9lnbvN7MHYJOiXsvGPXtjTYJEiC9J2wv9Eg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/yargs-parser": {
|
||||
"version": "22.0.0",
|
||||
"resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-22.0.0.tgz",
|
||||
"integrity": "sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": "^20.19.0 || ^22.12.0 || >=23"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"name": "web-slicer-bambu-login",
|
||||
"productName": "Web Slicer Bambu Login",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"main": "main.cjs",
|
||||
"scripts": {
|
||||
"start": "electron .",
|
||||
"package": "electron-packager . WebSlicerBambuLogin --out=dist --asar"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@electron/packager": "20.3.0",
|
||||
"electron": "45.4.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
const {contextBridge, ipcRenderer} = require('electron');
|
||||
|
||||
if (process.isMainFrame) {
|
||||
if (location.protocol === 'file:') {
|
||||
contextBridge.exposeInMainWorld('helper', {
|
||||
open: link => ipcRenderer.invoke('pairing:open', link)
|
||||
});
|
||||
} else if (location.origin === 'https://bambulab.com' || location.origin === 'https://www.bambulab.com') {
|
||||
contextBridge.exposeInMainWorld('wx', {
|
||||
postMessage: message => {
|
||||
if (typeof message === 'string' && message.length <= 65536)
|
||||
ipcRenderer.send('pairing:result', message);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
const form = document.querySelector('form');
|
||||
const field = document.querySelector('#link');
|
||||
const status = document.querySelector('#status');
|
||||
const button = form.querySelector('button');
|
||||
form.addEventListener('submit', async event => {
|
||||
event.preventDefault();
|
||||
button.disabled = true;
|
||||
try {
|
||||
status.textContent = await window.helper.open(field.value);
|
||||
if (status.textContent.startsWith('Complete sign-in')) field.value = '';
|
||||
} catch {
|
||||
status.textContent = 'Could not start sign-in. Make sure the helper is up to date.';
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,6 @@
|
||||
:root{color-scheme:light dark;font:16px system-ui}
|
||||
body{max-width:520px;margin:28px auto;padding:0 22px}
|
||||
h1{font-size:1.45rem;margin-bottom:24px}
|
||||
form{display:grid;gap:12px}
|
||||
input,button{font:inherit;padding:9px 12px}
|
||||
button{justify-self:start}
|
||||
@@ -7,6 +7,18 @@ diameter, density and notes. It has no physical-spool inventory, remaining-mass
|
||||
accounting, batch tracking or storage location. These are outside the product
|
||||
model; an optional inventory integration can reference the product separately.
|
||||
|
||||
A library manager can start a filament product from a system or imported
|
||||
filament preset. The picker supports search, material and manufacturer filters,
|
||||
and groups printer-specific variants by filament. The preset fills the draft with product metadata, including
|
||||
material, manufacturer, color, diameter and density. Saving creates the
|
||||
independent product. Printer availability and compatible slicing profiles
|
||||
can be added separately for each printer and nozzle.
|
||||
|
||||
Bambu AMS observations report slot metadata and assignment identity. To use a
|
||||
slot in a project, assign and confirm the product in Device and select its
|
||||
compatible slicing profile. The project records the slot and the confirmed
|
||||
assignment revision so that dispatch can check it against the live printer.
|
||||
|
||||
## Ownership and visibility
|
||||
|
||||
Products belong to explicit filament libraries, stored in the instance database.
|
||||
|
||||
@@ -324,6 +324,13 @@ known limitations. Users need only `compose.yaml` and `.env`. Do not create a
|
||||
Gitea release or upload release attachments. Do not advertise images before
|
||||
the registry and startup of the published images have been checked.
|
||||
|
||||
The web image serves portable Linux and Windows Bambu desktop helper archives
|
||||
under `/bambu-login/`. They are built from the helper source in the same
|
||||
revision. Bambu Cloud itself requires separately supplied native host and
|
||||
networking plugin binaries configured through
|
||||
`ORCA_BAMBU_CLOUD_HOST` and `ORCA_BAMBU_CLOUD_PLUGIN`. The standard app image
|
||||
does not include those binaries.
|
||||
|
||||
## Public static demo
|
||||
|
||||
The optional `demo` image uses the same GUI build and release tag. It contains
|
||||
|
||||
@@ -48,6 +48,46 @@ are intentional web-product decisions. They must not be overwritten merely to
|
||||
match upstream desktop behavior. This requirements record describes the intended
|
||||
redesign, not the currently implemented API.
|
||||
|
||||
## Surfacing new settings and GUI options
|
||||
|
||||
This fork replaces OrcaSlicer's wxWidgets desktop GUI with a React web client.
|
||||
A merge that only resolves C++ and builds is **not finished**: a new upstream
|
||||
option must actually appear in our GUI. A merge that leaves our GUI untouched is
|
||||
incomplete, not a success — every user-facing upstream addition is surfaced in
|
||||
the web client or recorded as a deliberate, explained deferral, never silently
|
||||
dropped.
|
||||
|
||||
How settings reach the web client:
|
||||
|
||||
- Field definitions, types, enum values, defaults and visibility come from the
|
||||
native **schema** (the worker's `schema` operation, generated from
|
||||
`PrintConfig.cpp`). A new `ConfigOptionDef` flows through automatically.
|
||||
- **Placement** (which page and group a key shows under) comes from
|
||||
`web/frontend/src/generated/setting-layout.json`, generated by
|
||||
`web/scripts/build-setting-layout.mjs`, which parses the page/group
|
||||
registration in `src/slic3r/GUI/Tab.cpp` (`TabPrint::build`,
|
||||
`TabFilament::build`, `TabPrinter::build_fff`, …). A key with no layout entry
|
||||
is not placed on any page, so it never renders even though the schema has it.
|
||||
|
||||
After any upstream merge that touches `PrintConfig.cpp` or `Tab.cpp`:
|
||||
|
||||
1. Regenerate the layout: `node web/scripts/build-setting-layout.mjs` and commit
|
||||
the result. The generator throws if its extraction looks incomplete; the
|
||||
count line it prints should grow by roughly the number of options upstream
|
||||
added.
|
||||
2. Open process, filament and printer settings in the web client and confirm the
|
||||
new options actually appear, with sane labels, units and enum choices.
|
||||
`web/frontend/tests/setting-layout.test.mjs` guards the extraction.
|
||||
3. Options upstream exposes through custom wxWidgets widgets, a new page, or a
|
||||
registration pattern the extractor does not match are **not** captured
|
||||
automatically. Extend the extractor or add the control to the web client so
|
||||
the option is reachable; if it genuinely does not apply to the web product,
|
||||
record that decision rather than leaving it missing.
|
||||
4. The same applies beyond the settings tabs: a new upstream GUI capability that
|
||||
users would rely on (a calibration, a device action, a project control) is
|
||||
reimplemented in the web client where it matters, not assumed present because
|
||||
the C++ merged.
|
||||
|
||||
## Validation boundaries
|
||||
|
||||
Check headless and desktop compilation, settings normalization, 3MF round trips,
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
// {"id":N,"op":"ping"|"status"|"logout"}
|
||||
// {"id":N,"op":"login_ticket","ticket":"..."}
|
||||
// {"id":N,"op":"login_session","session":{...}}
|
||||
// {"id":N,"op":"user_presets"} account preset download (REST)
|
||||
// {"id":N,"op":"devices"} bound printers (REST)
|
||||
// {"id":N,"op":"connect"} cloud MQTT session
|
||||
// {"id":N,"op":"subscribe","dev_ids":[...]}
|
||||
@@ -27,10 +28,12 @@
|
||||
|
||||
#include <atomic>
|
||||
#include <cctype>
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
@@ -68,6 +71,10 @@ using subscribe_fn = int (*)(void*, std::vector<std::string>);
|
||||
using send_fn = int (*)(void*, std::string, std::string, int, int);
|
||||
using on_message_fn = int (*)(void*, BBL::OnMessageFn);
|
||||
using on_server_fn = int (*)(void*, BBL::OnServerConnectedFn);
|
||||
using user_presets = std::map<std::string, std::map<std::string, std::string>>;
|
||||
using get_setting_list_fn = int (*)(void*, std::string, BBL::ProgressFn, BBL::WasCancelledFn);
|
||||
using put_setting_fn = int (*)(void*, std::string, std::string, std::map<std::string, std::string>*, unsigned int*);
|
||||
using get_user_presets_fn = int (*)(void*, user_presets*);
|
||||
using start_print_fn = int (*)(void*, BBL::PrintParams, BBL::OnUpdateStatusFn, BBL::WasCancelledFn, BBL::OnWaitFn);
|
||||
|
||||
std::mutex g_out;
|
||||
@@ -101,6 +108,9 @@ struct Plugin {
|
||||
on_message_fn set_on_message = nullptr;
|
||||
on_server_fn set_on_server_connected = nullptr;
|
||||
start_print_fn start_print = nullptr;
|
||||
get_user_presets_fn get_user_presets = nullptr;
|
||||
get_setting_list_fn get_setting_list = nullptr;
|
||||
put_setting_fn put_setting = nullptr;
|
||||
|
||||
std::thread print_thread;
|
||||
std::atomic<bool> printing{false};
|
||||
@@ -168,6 +178,11 @@ bool load_plugin(const std::string& path, const std::string& data_dir, const std
|
||||
&& resolve(p.lib, "bambu_network_set_on_server_connected_fn", p.set_on_server_connected)
|
||||
&& resolve(p.lib, "bambu_network_start_print", p.start_print);
|
||||
if (!ok) return false;
|
||||
if (cloud) {
|
||||
p.get_user_presets = reinterpret_cast<get_user_presets_fn>(dlsym(p.lib, "bambu_network_get_user_presets"));
|
||||
p.get_setting_list = reinterpret_cast<get_setting_list_fn>(dlsym(p.lib, "bambu_network_get_setting_list"));
|
||||
p.put_setting = reinterpret_cast<put_setting_fn>(dlsym(p.lib, "bambu_network_put_setting"));
|
||||
}
|
||||
// Private directories: the plugin keeps its session store under config/.
|
||||
const std::string config = data_dir + "/config";
|
||||
const std::string logs = data_dir + "/logs";
|
||||
@@ -368,6 +383,37 @@ json handle(Plugin& p, const json& req) {
|
||||
if (rc != 0) throw std::runtime_error("logout failed");
|
||||
return status(p);
|
||||
}
|
||||
if (op == "update_user_preset") {
|
||||
if (!p.put_setting) throw std::runtime_error("This Bambu networking plugin does not support preset updates");
|
||||
if (!p.is_user_login(p.agent) || p.get_user_id(p.agent) != req.at("account").get<std::string>())
|
||||
throw std::runtime_error("The signed-in Bambu Lab account changed");
|
||||
auto values = req.at("content").get<std::map<std::string, std::string>>();
|
||||
unsigned int http_code = 0;
|
||||
const int result = p.put_setting(p.agent, req.at("setting_id").get<std::string>(),
|
||||
req.at("name").get<std::string>(), &values, &http_code);
|
||||
if (result != 0)
|
||||
throw std::runtime_error("Bambu preset update failed (code " + std::to_string(result) + ")");
|
||||
return {{"updated", true}};
|
||||
}
|
||||
if (op == "user_presets") {
|
||||
if (!p.get_user_presets || !p.get_setting_list) throw std::runtime_error("This Bambu networking plugin does not support preset downloads");
|
||||
if (!p.is_user_login(p.agent)) throw std::runtime_error("Sign in to Bambu Lab to download presets");
|
||||
const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(35);
|
||||
const int fetched = p.get_setting_list(p.agent, req.at("bundle_version").get<std::string>(), {}, [deadline] {
|
||||
return std::chrono::steady_clock::now() >= deadline;
|
||||
});
|
||||
user_presets values;
|
||||
const int drained = p.get_user_presets(p.agent, &values);
|
||||
if (fetched != 0 || drained != 0)
|
||||
throw std::runtime_error("Bambu preset download failed (code " + std::to_string(fetched != 0 ? fetched : drained) + ")");
|
||||
if (!req.value("include_identity", false)) {
|
||||
for (auto& entry : values) {
|
||||
entry.second.erase("user_id");
|
||||
entry.second.erase("setting_id");
|
||||
}
|
||||
}
|
||||
return {{"presets", values}, {"account", p.get_user_id(p.agent)}};
|
||||
}
|
||||
if (op == "devices") return devices(p);
|
||||
if (op == "connect") {
|
||||
require_cloud(p);
|
||||
|
||||
@@ -958,3 +958,33 @@ and played through mpegts.js (magicxqq / xqq and contributors, Apache-2.0), whos
|
||||
original notices appear in the browser component credits. No video decoding,
|
||||
ffmpeg process or persistent media cache is added to the server. Stop or leave
|
||||
the panel to close the stream.
|
||||
|
||||
### Opening a model from another application
|
||||
|
||||
Send a multipart `file` to `POST /api/v1/imports/open-model` using the normal
|
||||
Web Slicer session and CSRF header. Accepted formats are 3MF, STL, STEP and
|
||||
STP, up to 512 MiB. The response is the durable import job. Its `Location`
|
||||
header opens the Web Slicer UI, which follows the job and opens the resulting
|
||||
project. API clients can poll `GET /api/v1/imports/{id}`.
|
||||
|
||||
The endpoint opens a new project. It uses the user's remembered printer or
|
||||
their only visible printer. Clients can provide `machine_id` and, optionally,
|
||||
`profile_id` in the query string. STL dimensions are kept, STEP uses native
|
||||
tessellation defaults, and 3MF is opened as geometry with the destination
|
||||
printer's settings. Optional rescaling and texture painting are skipped.
|
||||
|
||||
For a public model URL, link to the Web Slicer base URL with the fragment
|
||||
`#open-model=<encoded-model-url>`. Add `&filename=<encoded-filename>` if the
|
||||
download URL does not end in a supported extension. The browser downloads
|
||||
the file without credentials. Cross-origin downloads require CORS on the model
|
||||
host. The API never fetches model URLs.
|
||||
|
||||
Applications with private files can open a tab with
|
||||
`#open-model-from=<encoded-sender-origin>&request=<32-hex-digit-request-id>`.
|
||||
After the user has signed in, Web Slicer sends its opener a message with
|
||||
`protocol: "web-slicer.open-model.v1"`, `type: "ready"`, and `request`.
|
||||
The opener checks the window and origin and replies with the same protocol
|
||||
and request, `type: "file"`, and a browser `File` in `file`. Web Slicer
|
||||
replies with `accepted` after queuing the import, or `failed` if it cannot
|
||||
queue it. Both sides address their messages to the exact target origin.
|
||||
Keep the opener relationship for this flow.
|
||||
|
||||
@@ -16,7 +16,7 @@ COMMON_READS = {
|
||||
'/dispatches', '/profiles', '/user-profiles', '/workspace', '/accounts', '/health',
|
||||
'/capabilities', '/settings/schema', '/settings/gcode/placeholders', '/preferences/imports',
|
||||
'/printer/types', '/printer/device-agents', '/printer-library/thumbnail', '/upstream-release',
|
||||
'/emboss/fonts', '/emboss/styles', '/machine-wizard/catalog',
|
||||
'/emboss/fonts', '/emboss/styles', '/machine-wizard/catalog', '/filament-product-template',
|
||||
}
|
||||
PROJECT_READS = {
|
||||
'/open', '/selection-state', '/validation', '/measure', '/gcode/check',
|
||||
@@ -369,7 +369,7 @@ class AccessPolicy:
|
||||
return
|
||||
user = getattr(request.state, 'local_user', None)
|
||||
path = route.path.removeprefix('/api/v1')
|
||||
if path in {'/auth/login', '/auth/me', '/liveness'}:
|
||||
if path in {'/auth/login', '/auth/me', '/liveness'} or (path == '/bambu-cloud/desktop-login/redeem' and request.method == 'POST'):
|
||||
return
|
||||
if not user:
|
||||
raise HTTPException(401, 'Sign in to continue')
|
||||
@@ -377,7 +377,9 @@ class AccessPolicy:
|
||||
return # Catalogue services check current actor, ownership and printer grants transactionally.
|
||||
if path.startswith('/print-requests') or '/print-requests' in path:
|
||||
return # The service checks both resources and the frozen submission in its transaction.
|
||||
if user['admin'] or path in {'/auth/logout', '/auth/password'}:
|
||||
if user['admin'] or path in {'/auth/logout', '/auth/password'} or path == '/bambu-cloud' or path.startswith('/bambu-cloud/'):
|
||||
# Bambu cloud credentials and direct cloud job receipts are scoped to
|
||||
# the current user. Cloud printing also checks the project's grant.
|
||||
return
|
||||
params, method = request.path_params, request.method
|
||||
self.references(dict(request.query_params), user)
|
||||
@@ -435,6 +437,8 @@ class AccessPolicy:
|
||||
job = self.app.state.operations.get(params['job_id'])
|
||||
self.reference_project(job['payload']['project_id'], user, edit=method not in READ and not path.endswith('/copy'))
|
||||
return
|
||||
if path == '/imports/open-model' and method == 'POST':
|
||||
return # The handler selects only printers visible to the current actor.
|
||||
if path == '/imports' and method == 'POST':
|
||||
self.reference_project(body.get('project_id'), user, edit=True)
|
||||
selection = body.get('machine')
|
||||
|
||||
+36
-11
@@ -559,6 +559,12 @@ def public_printer(value):
|
||||
if value.get('oauth') else {})}
|
||||
|
||||
|
||||
def needs_bambu_3mf(store, state):
|
||||
machine = (state.get('machine_binding') or {}).get('machine_id')
|
||||
return bool(machine and state.get('config', {}).get('use_3mf') != '1'
|
||||
and (store.printer(machine) or {}).get('type') == 'bambu_lan')
|
||||
|
||||
|
||||
def public_project(project):
|
||||
return {key: value for key, value in project.items() if key != "path"}
|
||||
|
||||
@@ -655,7 +661,13 @@ class JobRunner:
|
||||
elif PluginJobs.possible_selection(project):
|
||||
if self.plugin_jobs is None or any((await self.plugin_jobs.effective_layout(project, (job.get('plate') or {}).get('index', 0)))[1]['names']):
|
||||
raise WorkerError('This job has no reviewed plugin execution plan; enqueue it again')
|
||||
result = await self.worker.run("slice", input=project["path"],
|
||||
source = project["path"]
|
||||
if needs_bambu_3mf(self.store, project["state"]):
|
||||
# Keep the queued project revision immutable. Direct API and
|
||||
# background jobs can bypass the interactive normalization.
|
||||
source = str(directory / "bambu-input.3mf")
|
||||
await run_with_project_profiles(self.worker, "export", project, output=source, settings={"use_3mf": "1"})
|
||||
result = await self.worker.run("slice", input=source,
|
||||
_job_lease=job['id'],
|
||||
output=str(directory / "output.gcode"),
|
||||
preview=str(directory / "preview.jsonl"),
|
||||
@@ -720,6 +732,7 @@ class JobRunner:
|
||||
if job.get('automatic') and self.store.job(job['id'])['status'] == 'cancelled':
|
||||
await asyncio.to_thread(shutil.rmtree, directory, ignore_errors=True)
|
||||
finally:
|
||||
(directory / 'bambu-input.3mf').unlink(missing_ok=True)
|
||||
AUTOMATIC_WORK.reset(automatic_context)
|
||||
|
||||
async def run(self):
|
||||
@@ -854,6 +867,7 @@ def create_app(*, data: Path | None = None, executable: Path | None = None,
|
||||
asyncio.create_task(refresh_orca_cloud(app.state.orca_cloud)),
|
||||
asyncio.create_task(app.state.orca_profile_automatic.run()),
|
||||
asyncio.create_task(app.state.background_slicing.run())]
|
||||
preset_sync_task = asyncio.create_task(app.state.bambu_preset_sync.run()) if app.state.bambu_preset_sync else None
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
@@ -872,8 +886,12 @@ def create_app(*, data: Path | None = None, executable: Path | None = None,
|
||||
await app.state.simplyprint_oauth.close()
|
||||
await app.state.orca_profile_automatic.close()
|
||||
await app.state.orca_cloud.close()
|
||||
if preset_sync_task:
|
||||
preset_sync_task.cancel()
|
||||
await asyncio.gather(preset_sync_task, return_exceptions=True)
|
||||
if getattr(app.state, 'bambu_cloud_relay', None) is not None:
|
||||
await asyncio.to_thread(app.state.bambu_cloud_relay.close)
|
||||
await app.state.close_bambu_user_hosts()
|
||||
if getattr(app.state, 'bambu_cloud', None) is not None:
|
||||
await asyncio.to_thread(app.state.bambu_cloud.close)
|
||||
await app.state.printeros_logins.close()
|
||||
@@ -911,8 +929,6 @@ def create_app(*, data: Path | None = None, executable: Path | None = None,
|
||||
install_printer_renders_api(app)
|
||||
install_printer_history_api(app)
|
||||
install_printer_commands_api(app, store)
|
||||
from .bambu_cloud import install_bambu_cloud_api
|
||||
install_bambu_cloud_api(app, store)
|
||||
app.state.job_artifacts = job_artifacts
|
||||
app.state.maintenance = maintenance
|
||||
app.state.post_processing = post_processing
|
||||
@@ -1130,6 +1146,9 @@ def create_app(*, data: Path | None = None, executable: Path | None = None,
|
||||
except ValueError as error:
|
||||
raise HTTPException(422, str(error)) from error
|
||||
value['revision'] = body.revision
|
||||
if value.get('bambu_transport') == 'cloud' and (user := app.state.access.current_user()):
|
||||
value['_bambu_account_owner'] = (app.state.access.machine_capabilities(identity)['owner_id']
|
||||
if identity else user['id'])
|
||||
if value['type'] == 'plugin':
|
||||
result = await plugin_printers.test_draft(value)
|
||||
else:
|
||||
@@ -1436,7 +1455,8 @@ def create_app(*, data: Path | None = None, executable: Path | None = None,
|
||||
try:
|
||||
sources = machine_artwork_sources(chosen)
|
||||
from .machines import create_machine_snapshot
|
||||
state = await create_machine_snapshot(worker, snapshot, chosen, geometry=snapshot.with_suffix('.mesh'))
|
||||
transport = {"use_3mf": "1"} if needs_bambu_3mf(store, {"machine_binding": chosen}) else {}
|
||||
state = await create_machine_snapshot(worker, snapshot, chosen, geometry=snapshot.with_suffix('.mesh'), settings=transport)
|
||||
await inherit_profile_artwork(snapshot, sources)
|
||||
state = bind_state(state, chosen)
|
||||
return await project_response(store.create_project(project_id, body.name, snapshot, state,
|
||||
@@ -1779,9 +1799,10 @@ def create_app(*, data: Path | None = None, executable: Path | None = None,
|
||||
# Evaluation awaits a worker; another request may have edited the project.
|
||||
if store.project(project_id)["revision"] != revision.revision:
|
||||
raise RevisionConflict(project_id)
|
||||
if not state["corrections"]:
|
||||
transport_settings = {"use_3mf": "1"} if needs_bambu_3mf(store, snapshot["state"]) else {}
|
||||
if not state["corrections"] and not transport_settings:
|
||||
return await project_response(snapshot)
|
||||
return await export_revision(project_id, revision.revision, apply_dependencies=True)
|
||||
return await export_revision(project_id, revision.revision, settings=transport_settings, apply_dependencies=True)
|
||||
|
||||
@app.patch("/api/v1/projects/{project_id}/scene", response_model=ProjectResponse, response_model_exclude_unset=True)
|
||||
async def edit_scene(project_id: str, edit: SceneEdit):
|
||||
@@ -2148,6 +2169,8 @@ def create_app(*, data: Path | None = None, executable: Path | None = None,
|
||||
product=app.state.filaments.product(physical['product_id'] if physical else refreshed['id'],machine_id=selection['machine_id'])
|
||||
values[index]='1' if key=='filament_colour_type' else product['color'];changed=True
|
||||
if changed:restored[key]=native_names(values)
|
||||
if needs_bambu_3mf(store, {"machine_binding": selection}):
|
||||
restored["use_3mf"] = "1"
|
||||
return await export_revision(project_id, body.revision, machine_binding=binding(selection),
|
||||
publish=app.state.machines.selection_publication(selection), profile_asset_sources=machine_artwork_sources(selection),
|
||||
profile_change={**arguments, 'choices': decisions}, settings=restored)
|
||||
@@ -2292,7 +2315,7 @@ def create_app(*, data: Path | None = None, executable: Path | None = None,
|
||||
return public_batch(batch)
|
||||
|
||||
def public_batch(batch):
|
||||
revision = store.project(batch['project_id'])['revision']
|
||||
revision = store.project_revision(batch['project_id'])
|
||||
return {**batch, 'stale': batch['revision'] != revision,
|
||||
'jobs': [public_job(value, revision) for value in batch['jobs']]}
|
||||
|
||||
@@ -2391,12 +2414,12 @@ def create_app(*, data: Path | None = None, executable: Path | None = None,
|
||||
@app.get("/api/v1/jobs/{job_id}", response_model=JobResponse, response_model_exclude_unset=True)
|
||||
async def job(job_id: str):
|
||||
value = store.job(job_id)
|
||||
return public_job(value, store.project(value['project_id'])['revision'])
|
||||
return public_job(value, store.project_revision(value['project_id']))
|
||||
|
||||
@app.get("/api/v1/projects/{project_id}/jobs", response_model=list[JobResponse], response_model_exclude_unset=True)
|
||||
async def project_jobs(project_id: str):
|
||||
revision = store.project(project_id)['revision']
|
||||
return [public_job(value, revision) for value in store.jobs(project_id)]
|
||||
async def project_jobs(project_id: str, updated_after: float | None = Query(default=None, ge=0, allow_inf_nan=False)):
|
||||
revision = store.project_revision(project_id)
|
||||
return [public_job(value, revision) for value in store.jobs(project_id, updated_after)]
|
||||
|
||||
@app.get('/api/v1/dispatches')
|
||||
async def dispatch_queue(limit: int = Query(default=50, ge=1, le=200), before: uuid.UUID | None = None,
|
||||
@@ -2646,6 +2669,8 @@ def create_app(*, data: Path | None = None, executable: Path | None = None,
|
||||
auth = install_auth_api(app, store)
|
||||
from .access import install_access_api
|
||||
install_access_api(app, store, auth)
|
||||
from .bambu_cloud import install_bambu_cloud_api
|
||||
install_bambu_cloud_api(app, store)
|
||||
from .filament_products import install_filament_product_api
|
||||
install_filament_product_api(app, store)
|
||||
from .print_requests import PrintRequests, install_print_request_api
|
||||
|
||||
@@ -26,7 +26,8 @@ class LocalAuthentication:
|
||||
return await send({'type': 'websocket.close', 'code': 1008})
|
||||
request = Request(scope, receive)
|
||||
path, method = scope['path'], scope['method']
|
||||
local_mutation = path in {PREFIX + '/login', PREFIX + '/logout', PREFIX + '/password'}
|
||||
library_merge = method == 'POST' and path.startswith('/api/v1/filament-libraries/') and path.endswith('/sync')
|
||||
local_mutation = path in {PREFIX + '/login', PREFIX + '/logout', PREFIX + '/password'} or library_merge
|
||||
started = False
|
||||
|
||||
async def private_send(message):
|
||||
@@ -53,14 +54,15 @@ class LocalAuthentication:
|
||||
session_hash = digest(token) if 40 <= len(token) <= 64 else ''
|
||||
user = await asyncio.to_thread(self.auth.session, session_hash, touch=True) if session_hash else None
|
||||
scope.setdefault('state', {}).update(local_user=user, local_session=session_hash)
|
||||
public = path in {PREFIX + '/me', PREFIX + '/login'}
|
||||
desktop_redeem = method == 'POST' and path == '/api/v1/bambu-cloud/desktop-login/redeem'
|
||||
public = desktop_redeem or path in {PREFIX + '/me', PREFIX + '/login'}
|
||||
if path == PREFIX + '/login' and self.auth.secure:
|
||||
origin = request.headers.get('origin')
|
||||
if origin and not origin.startswith('https://'):
|
||||
return await reject(400, 'HTTPS is required for sign in')
|
||||
if self.auth.required and not user and not public:
|
||||
return await reject(401, 'Sign in to continue', {'X-Orca-Auth-Required': '1'})
|
||||
if method not in SAFE and (self.auth.required or local_mutation or path.startswith('/api/v1/admin/')):
|
||||
if not desktop_redeem and method not in SAFE and (self.auth.required or local_mutation or path.startswith('/api/v1/admin/')):
|
||||
origin = request.headers.get('origin')
|
||||
if origin and origin not in self.allowed_origins and origin != str(request.base_url).rstrip('/'):
|
||||
return await reject(403, 'Foreign origin rejected')
|
||||
@@ -79,10 +81,11 @@ class LocalAuthentication:
|
||||
if self.auth.required and user and admin_path and not user['admin']:
|
||||
return await reject(403, 'Administrator access is required')
|
||||
# Bound the complete auth payload before FastAPI/Pydantic decode it.
|
||||
if method not in SAFE and (local_mutation or path.startswith('/api/v1/admin/')):
|
||||
if desktop_redeem or method not in SAFE and (local_mutation or path.startswith('/api/v1/admin/')):
|
||||
if request.headers.get('content-type', '').split(';')[0].lower() != 'application/json' and path != PREFIX + '/logout':
|
||||
return await reject(415, 'Use application/json')
|
||||
body = bytearray()
|
||||
limit = 8 * 1024 * 1024 if library_merge else 72 * 1024 if desktop_redeem else 8192
|
||||
try:
|
||||
async with asyncio.timeout(10):
|
||||
while True:
|
||||
@@ -90,8 +93,9 @@ class LocalAuthentication:
|
||||
if message['type'] == 'http.disconnect':
|
||||
return
|
||||
body.extend(message.get('body', b''))
|
||||
if len(body) > 8192:
|
||||
return await reject(413, 'Authentication request is too large')
|
||||
if len(body) > limit:
|
||||
detail = 'Library sync request is too large' if library_merge else 'Authentication request is too large'
|
||||
return await reject(413, detail)
|
||||
if not message.get('more_body'):
|
||||
break
|
||||
except TimeoutError:
|
||||
|
||||
@@ -64,15 +64,15 @@ class BackgroundSlicing:
|
||||
return dict(value) if value else None
|
||||
|
||||
def state(self, identity):
|
||||
project = self.store.project(identity)
|
||||
revision = self.store.project_revision(identity)
|
||||
with self.store.connection() as db:
|
||||
row = self.row(db, identity)
|
||||
if not row:
|
||||
return {'revision': 0, 'project_revision': project['revision'], 'enabled': False, 'delay_seconds': 0,
|
||||
return {'revision': 0, 'project_revision': revision, 'enabled': False, 'delay_seconds': 0,
|
||||
'plate': 0, 'post_process_mode': 'require_review', 'approved_programs': [],
|
||||
'target_revision': project['revision'], 'due_at': None, 'status': 'disabled', 'message': '', 'job_id': None}
|
||||
'target_revision': revision, 'due_at': None, 'status': 'disabled', 'message': '', 'job_id': None}
|
||||
return {**{k: row[k] for k in ('revision','enabled','delay_seconds','plate','post_process_mode',
|
||||
'approved_revision','target_revision','due_at','status','message','job_id')}, 'project_revision': project['revision'],
|
||||
'approved_revision','target_revision','due_at','status','message','job_id')}, 'project_revision': revision,
|
||||
'approved_programs': json.loads(row['approved_programs']), 'cache': {
|
||||
'keep_per_project': self.artifacts.keep, 'byte_budget': self.artifacts.byte_budget,
|
||||
'min_free_bytes': self.artifacts.min_free_bytes, 'cleanup_error': self.artifacts.error,
|
||||
|
||||
@@ -3,11 +3,11 @@
|
||||
Drives the native orca-bambu-cloud host (src/headless/BambuCloudHost.cpp), which
|
||||
loads open-bamboo-networking. Available only when both are configured through
|
||||
ORCA_BAMBU_CLOUD_HOST and ORCA_BAMBU_CLOUD_PLUGIN (the cloud sideload build);
|
||||
otherwise the API reports it as unavailable and starts nothing. One account per
|
||||
instance, so the routes fall under the administrator default in access_control.
|
||||
otherwise the API reports it as unavailable and starts nothing. Local account
|
||||
mode has one Bambu session per user. Standalone mode keeps one device session.
|
||||
|
||||
A sign-in WebView (the Android app's, mirroring upstream OrcaSlicer's `wx`
|
||||
bridge) captures what the Bambu page hands over and posts it here: either a
|
||||
A sign-in WebView in the Android app or desktop helper captures the result
|
||||
provided by the Bambu page and posts it here: either a
|
||||
short ticket or an already-complete session. Neither is logged or returned.
|
||||
"""
|
||||
import asyncio
|
||||
@@ -16,6 +16,7 @@ import json
|
||||
import os
|
||||
from pathlib import Path as FilePath
|
||||
import queue
|
||||
import re
|
||||
import secrets
|
||||
import socket
|
||||
import socketserver
|
||||
@@ -25,7 +26,7 @@ import time
|
||||
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import HTTPException, Path
|
||||
from fastapi import HTTPException, Path, Request
|
||||
from pydantic import BaseModel, ConfigDict, Field, JsonValue, model_validator
|
||||
|
||||
REPLY_TIMEOUT = 45 # A ticket exchange makes two HTTPS calls to Bambu.
|
||||
@@ -54,7 +55,8 @@ class BambuLogin(BaseModel):
|
||||
# keeps the same running merge of incremental pushes).
|
||||
# Cloud device list model codes (Bambu printer model ids, as in Studio's machine profiles).
|
||||
MODEL_NAMES = {'BL-P001': 'X1 Carbon', 'BL-P002': 'X1', 'C13': 'X1E', 'C11': 'P1P', 'C12': 'P1S',
|
||||
'N1': 'A1 mini', 'N2S': 'A1'}
|
||||
'N1': 'A1 mini', 'N2S': 'A1', 'N7': 'P2S', 'N9': 'A2L', 'N6': 'X2D',
|
||||
'O1C2': 'H2C', 'O1E': 'H2D Pro', 'O1D': 'H2D', 'O1S': 'H2S'}
|
||||
STATUS_FIELDS = ('gcode_state', 'mc_percent', 'mc_remaining_time', 'layer_num', 'total_layer_num',
|
||||
'subtask_name', 'nozzle_temper', 'nozzle_target_temper', 'bed_temper', 'bed_target_temper',
|
||||
'print_error', 'wifi_signal')
|
||||
@@ -193,7 +195,15 @@ class BambuCloudHost:
|
||||
raise RuntimeError('Bambu cloud host exited')
|
||||
if not reply.get('ok'):
|
||||
raise ValueError(reply.get('error') or 'Bambu cloud request failed')
|
||||
return reply['result']
|
||||
result = reply['result']
|
||||
if op in {'login_ticket', 'login_session', 'logout'}:
|
||||
with self.state_lock:
|
||||
self.devices.clear()
|
||||
self.printers.clear()
|
||||
self.jobs.clear()
|
||||
self.pushall_sent.clear()
|
||||
self.server_connected = bool(result.get('cloud_connected'))
|
||||
return result
|
||||
|
||||
def printer_status(self, dev_id):
|
||||
with self.state_lock:
|
||||
@@ -349,11 +359,12 @@ class CloudRelay:
|
||||
return
|
||||
dev_id = hello.get('dev_id')
|
||||
try:
|
||||
identity = self._open(dev_id)
|
||||
host = self.host(hello.get('owner')) if callable(self.host) else self.host
|
||||
identity = self._open(dev_id, host)
|
||||
except (ValueError, RuntimeError, TimeoutError) as error:
|
||||
send({'ok': False, 'error': str(error) or 'Bambu cloud is unavailable'})
|
||||
return
|
||||
listener = self.host.listen(dev_id)
|
||||
listener = host.listen(dev_id)
|
||||
closed = threading.Event()
|
||||
|
||||
def forward():
|
||||
@@ -378,13 +389,13 @@ class CloudRelay:
|
||||
if (payload.get('pushing') or {}).get('command') == 'pushall':
|
||||
# The merged report is what a fresh pushall would return; ask the
|
||||
# printer again only now and then.
|
||||
forwarded = self.host.pushall(dev_id)
|
||||
cached = self.host.full_report(dev_id)
|
||||
forwarded = host.pushall(dev_id)
|
||||
cached = host.full_report(dev_id)
|
||||
send({'id': ident, 'sent': True})
|
||||
if cached is not None and not forwarded:
|
||||
send({'message': {'print': cached}})
|
||||
else:
|
||||
self.host.call('send', dev_id=dev_id, payload=payload)
|
||||
host.call('send', dev_id=dev_id, payload=payload)
|
||||
send({'id': ident, 'sent': True})
|
||||
except (ValueError, RuntimeError, TimeoutError) as error:
|
||||
send({'id': ident, 'error': str(error) or 'Bambu cloud send failed'})
|
||||
@@ -392,7 +403,7 @@ class CloudRelay:
|
||||
pass
|
||||
finally:
|
||||
closed.set()
|
||||
self.host.unlisten(dev_id, listener)
|
||||
host.unlisten(dev_id, listener)
|
||||
|
||||
@staticmethod
|
||||
def _line(reader):
|
||||
@@ -404,15 +415,16 @@ class CloudRelay:
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
def _open(self, dev_id):
|
||||
def _open(self, dev_id, host=None):
|
||||
host = host or self.host
|
||||
if not isinstance(dev_id, str) or not dev_id.isalnum() or len(dev_id) > 64:
|
||||
raise ValueError('Invalid Bambu printer id')
|
||||
self.host.ensure_connected()
|
||||
if dev_id not in self.host.devices:
|
||||
self.host.device_list() # also subscribes the account's printers
|
||||
if dev_id not in self.host.devices:
|
||||
host.ensure_connected()
|
||||
if dev_id not in host.devices:
|
||||
host.device_list() # also subscribes the account's printers
|
||||
if dev_id not in host.devices:
|
||||
raise ValueError('This printer is not bound to the signed-in Bambu Lab account')
|
||||
return self.host.lan_identity(dev_id)
|
||||
return host.lan_identity(dev_id)
|
||||
|
||||
|
||||
def configured_host(data_root):
|
||||
@@ -425,16 +437,53 @@ def configured_host(data_root):
|
||||
|
||||
|
||||
def install_bambu_cloud_api(app, store):
|
||||
managed = app.state.auth.required
|
||||
app.state.bambu_cloud = configured_host(store.root)
|
||||
app.state.bambu_cloud_relay = None
|
||||
if app.state.bambu_cloud is not None:
|
||||
hosts = {}
|
||||
hosts_lock = threading.Lock()
|
||||
|
||||
def user_host(owner):
|
||||
if not isinstance(owner, str) or not re.fullmatch(r'[a-f0-9]{32}', owner):
|
||||
raise ValueError('Sign in to reach this Bambu Lab account')
|
||||
try:
|
||||
user = app.state.access.account(owner)
|
||||
except (KeyError, HTTPException):
|
||||
raise ValueError('The Bambu Lab account owner is unavailable') from None
|
||||
if user['disabled']:
|
||||
raise ValueError('The Bambu Lab account owner is unavailable')
|
||||
with hosts_lock:
|
||||
if owner not in hosts:
|
||||
host = configured_host(store.root / 'accounts' / owner)
|
||||
if host is None:
|
||||
raise ValueError('Bambu Lab cloud is not available')
|
||||
normalize_stored_crl(host)
|
||||
hosts[owner] = host
|
||||
return hosts[owner]
|
||||
|
||||
def account_host():
|
||||
if not managed:
|
||||
return app.state.bambu_cloud
|
||||
if app.state.bambu_cloud is None:
|
||||
return None
|
||||
user = app.state.access.current_user()
|
||||
if not user:
|
||||
raise HTTPException(401, 'Sign in to access your Bambu Lab account')
|
||||
return user_host(user['id'])
|
||||
|
||||
async def close_user_hosts():
|
||||
await asyncio.gather(*(asyncio.to_thread(host.close) for host in list(hosts.values())))
|
||||
|
||||
app.state.close_bambu_user_hosts = close_user_hosts
|
||||
app.state.bambu_account_host = account_host
|
||||
if app.state.bambu_cloud is not None and not managed:
|
||||
normalize_stored_crl(app.state.bambu_cloud) # repair a CRL saved before the concatenation fix
|
||||
if app.state.bambu_cloud is not None and app.state.bambu_cloud.cloud:
|
||||
app.state.bambu_cloud_relay = CloudRelay(app.state.bambu_cloud)
|
||||
app.state.bambu_cloud_relay = CloudRelay(user_host if managed else app.state.bambu_cloud)
|
||||
os.environ[RELAY_ENV] = app.state.bambu_cloud_relay.address # inherited by printer workers
|
||||
|
||||
async def run(op, **fields):
|
||||
host = app.state.bambu_cloud
|
||||
async def run(op, *, host=None, **fields):
|
||||
host = host or account_host()
|
||||
if host is None:
|
||||
raise HTTPException(404, 'Bambu cloud is not available in this build')
|
||||
try:
|
||||
@@ -446,25 +495,125 @@ def install_bambu_cloud_api(app, store):
|
||||
except RuntimeError as error:
|
||||
raise HTTPException(503, str(error)) from error
|
||||
|
||||
from .bambu_preset_sync import BambuPresetSync
|
||||
sync = BambuPresetSync(store, app.state.worker, run) if app.state.bambu_cloud_relay and not managed else None
|
||||
app.state.bambu_preset_sync = sync
|
||||
|
||||
class PresetSyncPreference(BaseModel):
|
||||
enabled: bool
|
||||
|
||||
async def signed_in_account():
|
||||
if sync is None:
|
||||
raise HTTPException(404, 'Bambu Lab preset synchronization is unavailable')
|
||||
state = await run('status')
|
||||
if not state.get('logged_in') or not state.get('user_id'):
|
||||
raise HTTPException(409, 'Sign in to Bambu Lab to synchronize presets')
|
||||
return state['user_id']
|
||||
|
||||
@app.get('/api/v1/bambu-cloud/preset-sync')
|
||||
async def preset_sync_state():
|
||||
account = await signed_in_account()
|
||||
return sync.state(account)
|
||||
|
||||
@app.put('/api/v1/bambu-cloud/preset-sync')
|
||||
async def preset_sync_preference(body: PresetSyncPreference):
|
||||
account = await signed_in_account()
|
||||
sync.configure(account, body.enabled)
|
||||
return sync.state(account)
|
||||
|
||||
@app.post('/api/v1/bambu-cloud/preset-sync')
|
||||
async def preset_sync_request():
|
||||
account = await signed_in_account()
|
||||
if not sync.enabled(account):
|
||||
raise HTTPException(409, 'Enable Bambu Lab preset synchronization first')
|
||||
sync.wake.set()
|
||||
return sync.state(account)
|
||||
|
||||
@app.get('/api/v1/bambu-cloud')
|
||||
async def bambu_cloud_status():
|
||||
host = app.state.bambu_cloud
|
||||
host = account_host()
|
||||
if host is None:
|
||||
return {'available': False}
|
||||
state = await run('status')
|
||||
return {'available': True, 'plugin_version': host.plugin_version, **state}
|
||||
return {'available': True, 'plugin_version': host.plugin_version, 'personal_account': managed, **state,
|
||||
**({'preset_sync': sync.state(state['user_id'])} if sync and state.get('user_id') else {})}
|
||||
|
||||
async def login(body, host=None):
|
||||
async def sign_in():
|
||||
if body.ticket is not None:
|
||||
return await run('login_ticket', host=host, ticket=body.ticket)
|
||||
return await run('login_session', host=host, session=body.session)
|
||||
if sync is None:
|
||||
state = await sign_in()
|
||||
else:
|
||||
async with sync.lock:
|
||||
state = await sign_in()
|
||||
sync.wake.set()
|
||||
if not state.get('logged_in'):
|
||||
raise HTTPException(422, 'Bambu Lab did not accept this sign-in')
|
||||
return {'available': True, 'personal_account': managed, **state}
|
||||
|
||||
desktop_codes = {}
|
||||
|
||||
@app.post('/api/v1/bambu-cloud/login')
|
||||
async def bambu_cloud_login(body: BambuLogin):
|
||||
if body.ticket is not None:
|
||||
state = await run('login_ticket', ticket=body.ticket)
|
||||
user = app.state.access.current_user()
|
||||
if user:
|
||||
desktop_codes.pop(user['id'], None)
|
||||
return await login(body)
|
||||
|
||||
@app.post('/api/v1/bambu-cloud/desktop-login')
|
||||
async def create_desktop_code(request: Request):
|
||||
host = host_or_404()
|
||||
user = request.state.local_user
|
||||
if not user or not request.state.local_session:
|
||||
raise HTTPException(403, 'Sign in to Web Slicer to use the desktop helper')
|
||||
origin = request.headers.get('origin')
|
||||
if not origin or not origin.startswith('https://'):
|
||||
raise HTTPException(400, 'Use the HTTPS Web Slicer address to pair the desktop helper')
|
||||
now = time.monotonic()
|
||||
for identity, entry in list(desktop_codes.items()):
|
||||
if entry[2] <= now:
|
||||
desktop_codes.pop(identity, None)
|
||||
token = secrets.token_urlsafe(32)
|
||||
desktop_codes[user['id']] = (token, request.state.local_session, now + 600)
|
||||
return {'code': token, 'expires_in': 600, 'plugin_version': host.plugin_version}
|
||||
|
||||
@app.delete('/api/v1/bambu-cloud/desktop-login', status_code=204)
|
||||
async def cancel_desktop_code(request: Request):
|
||||
user = request.state.local_user
|
||||
entry = desktop_codes.get(user['id']) if user else None
|
||||
if entry and entry[1] == request.state.local_session:
|
||||
desktop_codes.pop(user['id'], None)
|
||||
|
||||
@app.post('/api/v1/bambu-cloud/desktop-login/redeem', status_code=204)
|
||||
async def redeem_desktop_code(request: Request, body: BambuLogin):
|
||||
supplied = request.headers.get('authorization', '').removeprefix('Bearer ')
|
||||
if not request.headers.get('origin') and re.fullmatch(r'[A-Za-z0-9_-]{43}', supplied):
|
||||
for identity, (token, session, expires) in desktop_codes.items():
|
||||
if expires > time.monotonic() and hmac.compare_digest(supplied, token):
|
||||
break
|
||||
else:
|
||||
raise HTTPException(403, 'The pairing code is invalid or expired')
|
||||
else:
|
||||
state = await run('login_session', session=body.session)
|
||||
return {'available': True, **state}
|
||||
raise HTTPException(403, 'The pairing code is invalid or expired')
|
||||
desktop_codes.pop(identity, None)
|
||||
user = await asyncio.to_thread(app.state.auth.session, session)
|
||||
if not user or user['id'] != identity:
|
||||
raise HTTPException(403, 'The Web Slicer session has ended')
|
||||
await login(body, user_host(identity))
|
||||
|
||||
@app.post('/api/v1/bambu-cloud/logout')
|
||||
async def bambu_cloud_logout():
|
||||
return {'available': True, **await run('logout')}
|
||||
user = app.state.access.current_user()
|
||||
if user:
|
||||
desktop_codes.pop(user['id'], None)
|
||||
if sync is None:
|
||||
state = await run('logout')
|
||||
else:
|
||||
async with sync.lock:
|
||||
state = await run('logout')
|
||||
return {'available': True, 'personal_account': managed, **state}
|
||||
|
||||
@app.get('/api/v1/bambu-cloud/slicer-key')
|
||||
async def bambu_cloud_slicer_key():
|
||||
@@ -486,7 +635,7 @@ def install_bambu_cloud_api(app, store):
|
||||
return slicer_key_state(host)
|
||||
|
||||
def host_or_404():
|
||||
host = app.state.bambu_cloud
|
||||
host = account_host()
|
||||
if host is None or not host.cloud:
|
||||
raise HTTPException(404, 'Bambu cloud printers are not available in this build')
|
||||
return host
|
||||
@@ -528,6 +677,15 @@ def install_bambu_cloud_api(app, store):
|
||||
job = store.job(body.job_id)
|
||||
if job is None:
|
||||
raise HTTPException(404, 'Unknown slicing job')
|
||||
if user := app.state.access.current_user():
|
||||
app.state.access.require('project', job['project_id'], user)
|
||||
app.state.access.require_machine(store.job_machine(body.job_id), user, 'direct_print')
|
||||
if body.connection_revision is not None:
|
||||
connection = store.printer(store.job_machine(body.job_id))
|
||||
if (not connection or connection['revision'] != body.connection_revision or
|
||||
connection.get('type') != 'bambu_lan' or connection.get('bambu_transport') != 'cloud'
|
||||
or connection.get('bambu_serial_number') != dev_id):
|
||||
raise HTTPException(409, 'The saved Bambu connection changed. Open Print again.')
|
||||
result = job.get('result') or {}
|
||||
if job.get('status') != 'completed' or result.get('upload_format') != 'gcode_3mf':
|
||||
raise HTTPException(409, 'Slice for a Bambu Lab printer first (the job has no printable .gcode.3mf)')
|
||||
@@ -710,6 +868,7 @@ def gcode_task_name(filename):
|
||||
class BambuCloudPrint(BaseModel):
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
job_id: str = Field(min_length=1, max_length=64, pattern=r'^[A-Za-z0-9-]+$')
|
||||
connection_revision: int | None = Field(default=None, ge=1)
|
||||
bed_leveling: bool = True
|
||||
flow_calibration: bool = False
|
||||
timelapse: bool = False
|
||||
|
||||
@@ -26,8 +26,7 @@ RELAY_ENV = 'ORCA_BAMBU_CLOUD_RELAY'
|
||||
UNKNOWN_HOST = 'bambu-cloud.invalid'
|
||||
PLACEHOLDER_CODE = '00000000' # never sent: the account session needs no LAN code
|
||||
MAX_LINE = 1024 * 1024
|
||||
CLOUD_PRINT = ('Printing to a printer connected through the Bambu Lab account uses Bambu Lab account → '
|
||||
'Print through Bambu Lab cloud.')
|
||||
CLOUD_PRINT = 'Open Print from the sliced preview to send to the saved Bambu Lab cloud printer.'
|
||||
|
||||
|
||||
def is_cloud(connection):
|
||||
@@ -51,7 +50,7 @@ def unavailable(error=None):
|
||||
class RelayConnection:
|
||||
"""Blocking client of the relay; MQTT payloads queue up while a publish waits."""
|
||||
|
||||
def __init__(self, dev_id, timeout):
|
||||
def __init__(self, dev_id, timeout, owner=None):
|
||||
port, token = relay_address()
|
||||
self.timeout = timeout
|
||||
self.ids = itertools.count(1)
|
||||
@@ -62,7 +61,7 @@ class RelayConnection:
|
||||
raise unavailable() from error
|
||||
self.reader = self.socket.makefile('rb')
|
||||
try:
|
||||
self._write({'token': token, 'dev_id': dev_id})
|
||||
self._write({'token': token, 'dev_id': dev_id, 'owner': owner})
|
||||
hello = self._read(time.monotonic() + max(timeout, 30)) # first use may sign in and list devices
|
||||
except (OSError, TimeoutError, ValueError) as error:
|
||||
self.close()
|
||||
@@ -145,10 +144,11 @@ class CloudMQTT:
|
||||
|
||||
|
||||
class BambuCloudLink(BambuLAN):
|
||||
def __init__(self, *, serial_number, timeout=12, printer_model='', **options):
|
||||
def __init__(self, *, serial_number, timeout=12, printer_model='', account_owner=None, **options):
|
||||
# Cloud round trips (phone -> Bambu -> printer -> Bambu -> phone) are slower than LAN.
|
||||
super().__init__(f'http://{UNKNOWN_HOST}/', PLACEHOLDER_CODE, serial_number=serial_number,
|
||||
timeout=max(timeout, 20), printer_model=printer_model, **options)
|
||||
self.account_owner = account_owner
|
||||
self.resolved = False
|
||||
self._resolving = False
|
||||
|
||||
@@ -174,7 +174,7 @@ class BambuCloudLink(BambuLAN):
|
||||
"""Point LAN-side features (camera, files) at the printer's reported address."""
|
||||
if self.resolved and self._host != UNKNOWN_HOST: # an address may arrive after the first lookup
|
||||
return self
|
||||
relay = RelayConnection(self.serial_number, self.timeout)
|
||||
relay = RelayConnection(self.serial_number, self.timeout, self.account_owner)
|
||||
relay.close()
|
||||
self._apply(relay.identity)
|
||||
return self
|
||||
@@ -190,7 +190,7 @@ class BambuCloudLink(BambuLAN):
|
||||
|
||||
@contextmanager
|
||||
def session(self, *, client_id=None):
|
||||
relay = RelayConnection(self.serial_number, self.timeout)
|
||||
relay = RelayConnection(self.serial_number, self.timeout, self.account_owner)
|
||||
try:
|
||||
self._apply(relay.identity)
|
||||
yield CloudMQTT(relay, self.report_topic, self.timeout)
|
||||
@@ -230,7 +230,7 @@ def resolved_connection(connection):
|
||||
"""A LAN-shaped copy of a cloud connection for camera code that dials the printer."""
|
||||
if not is_cloud(connection):
|
||||
return connection
|
||||
relay = RelayConnection(connection.get('bambu_serial_number') or '', 20)
|
||||
relay = RelayConnection(connection.get('bambu_serial_number') or '', 20, connection.get('_bambu_account_owner'))
|
||||
relay.close()
|
||||
identity = relay.identity
|
||||
if not identity.get('ip') or not identity.get('access_code'):
|
||||
@@ -267,7 +267,8 @@ async def relay_stream(connection):
|
||||
raise ValueError('Invalid Bambu cloud relay line')
|
||||
return value
|
||||
|
||||
await write({'token': token, 'dev_id': connection.get('bambu_serial_number') or ''})
|
||||
await write({'token': token, 'dev_id': connection.get('bambu_serial_number') or '',
|
||||
'owner': connection.get('_bambu_account_owner')})
|
||||
async with asyncio.timeout(30):
|
||||
hello = await read()
|
||||
if not hello.get('ok'):
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
"""Account-scoped Bambu preset sync for shared library templates."""
|
||||
import asyncio
|
||||
from dataclasses import dataclass
|
||||
from hashlib import sha256
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
|
||||
from .orca_cloud_presets import CloudPresetCodec, SCOPES
|
||||
from .orca_profile_chunks import MAX_PROFILES, RESULT_BYTES, encoded_size
|
||||
from .profile_bundles import NAME
|
||||
|
||||
LOG = logging.getLogger(__name__)
|
||||
INTERVAL = 120
|
||||
METADATA = {'name', 'type', 'version', 'inherits', 'filament_id', 'base_id',
|
||||
'user_id', 'setting_id', 'created_time', 'updated_time', 'update_time'}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RemotePreset:
|
||||
id: str
|
||||
name: str
|
||||
content: dict
|
||||
updated_time: int = 0
|
||||
|
||||
@property
|
||||
def fingerprint(self):
|
||||
content = {key: value for key, value in self.content.items()
|
||||
if key not in {'updated_time', 'update_time', 'created_time'}}
|
||||
return sha256(json.dumps(content, sort_keys=True).encode()).hexdigest()
|
||||
|
||||
|
||||
class BambuPresetSync:
|
||||
def __init__(self, store, worker, call):
|
||||
self.store, self.worker, self.call = store, worker, call
|
||||
self.codec = CloudPresetCodec(worker)
|
||||
self.wake = asyncio.Event()
|
||||
self.lock = asyncio.Lock()
|
||||
self.status = {}
|
||||
with store.connection() as db:
|
||||
db.executescript('''
|
||||
CREATE TABLE IF NOT EXISTS bambu_preset_preferences (
|
||||
account TEXT PRIMARY KEY, enabled INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS bambu_preset_links (
|
||||
account TEXT NOT NULL, remote_id TEXT NOT NULL,
|
||||
local_id TEXT NOT NULL, revision INTEGER NOT NULL, fingerprint TEXT NOT NULL,
|
||||
PRIMARY KEY(account, remote_id), UNIQUE(local_id)
|
||||
);
|
||||
''')
|
||||
|
||||
def enabled(self, account):
|
||||
with self.store.connection() as db:
|
||||
row = db.execute('SELECT enabled FROM bambu_preset_preferences WHERE account=?', (account,)).fetchone()
|
||||
return row is None or bool(row['enabled'])
|
||||
|
||||
def state(self, account):
|
||||
return {'enabled': self.enabled(account), **self.status.get(account, {})}
|
||||
|
||||
def configure(self, account, enabled):
|
||||
with self.store.connection() as db:
|
||||
db.execute('INSERT OR REPLACE INTO bambu_preset_preferences VALUES (?,?)', (account, enabled))
|
||||
if enabled:
|
||||
self.wake.set()
|
||||
|
||||
async def run(self):
|
||||
while True:
|
||||
self.wake.clear()
|
||||
try:
|
||||
state = await self.call('status')
|
||||
account = state.get('user_id') if state.get('logged_in') else None
|
||||
if account and self.enabled(account):
|
||||
self.status[account] = {**self.status.get(account, {}), 'running': True}
|
||||
try:
|
||||
async with self.lock:
|
||||
if self.enabled(account):
|
||||
result = await self.sync(account)
|
||||
previous = self.status[account].get('catalog_changed_at')
|
||||
if result.pop('catalog_changed', False):
|
||||
previous = time.time()
|
||||
self.status[account] = {'last_sync': time.time(), 'catalog_changed_at': previous, **result}
|
||||
except Exception:
|
||||
LOG.warning('Bambu preset synchronization failed', exc_info=True)
|
||||
self.status[account]['failed'] = True
|
||||
finally:
|
||||
self.status[account]['running'] = False
|
||||
except Exception:
|
||||
LOG.debug('Bambu preset synchronization is waiting for an account', exc_info=True)
|
||||
try:
|
||||
await asyncio.wait_for(self.wake.wait(), INTERVAL)
|
||||
except TimeoutError:
|
||||
pass
|
||||
|
||||
async def sync(self, account):
|
||||
version = json.loads((self.worker.resources / 'profiles' / 'BBL.json').read_text(encoding='utf-8'))['version']
|
||||
reply = await self.call('user_presets', bundle_version=version, include_identity=True)
|
||||
if reply['account'] != account or not self.enabled(account):
|
||||
return {}
|
||||
values = reply['presets']
|
||||
if len(values) > MAX_PROFILES or encoded_size(values) > RESULT_BYTES:
|
||||
raise ValueError('Bambu preset collection exceeds the synchronization limit')
|
||||
remote = []
|
||||
for name, content in values.items():
|
||||
if (NAME.fullmatch(name) and name == name.strip() and content.get('type') in SCOPES
|
||||
and content.get('setting_id') and content.get('user_id', account) == account
|
||||
and content.keys() - METADATA):
|
||||
updated = content.get('updated_time', '')
|
||||
remote.append(RemotePreset(content['setting_id'], name, {**content, 'name': name},
|
||||
int(updated) if updated.isdecimal() else 0))
|
||||
with self.store.connection() as db:
|
||||
records = self.store.template_profiles(db=db)
|
||||
links = {row['remote_id']: row for row in db.execute(
|
||||
'SELECT * FROM bambu_preset_links WHERE account=?', (account,))}
|
||||
names = {(row['scope'], row['name']) for row in db.execute('SELECT scope,name FROM user_profiles')}
|
||||
by_id = {record['id']: record for record in records}
|
||||
pull, push = [], []
|
||||
conflicts = 0
|
||||
catalog_changed = False
|
||||
for preset in remote:
|
||||
scope = SCOPES[preset.content['type']]
|
||||
link = links.get(preset.id)
|
||||
if link is None:
|
||||
if (scope, preset.name) in names:
|
||||
conflicts += 1
|
||||
else:
|
||||
pull.append((preset, None))
|
||||
continue
|
||||
local = by_id.get(link['local_id'])
|
||||
if local is None or (local['scope'], local['name']) != (scope, preset.name):
|
||||
conflicts += 1
|
||||
continue
|
||||
remote_changed = preset.fingerprint != link['fingerprint']
|
||||
local_changed = local['revision'] != link['revision']
|
||||
if local_changed and remote_changed:
|
||||
conflicts += 1
|
||||
elif remote_changed:
|
||||
pull.append((preset, local))
|
||||
elif local_changed:
|
||||
push.append((preset, local))
|
||||
if pull:
|
||||
inspected = await self.codec.inspect([preset for preset, _ in pull], records, account)
|
||||
if not self.enabled(account):
|
||||
return {}
|
||||
with self.store.connection() as db:
|
||||
db.execute('BEGIN IMMEDIATE')
|
||||
current = {record['id']: record for record in self.store.template_profiles(db=db)}
|
||||
occupied = {(row['scope'], row['name']) for row in db.execute('SELECT scope,name FROM user_profiles')}
|
||||
for (preset, local), value in zip(pull, inspected, strict=True):
|
||||
payload = value['payload']
|
||||
identity = payload['scope'], payload['name']
|
||||
if local is None and identity in occupied or local is not None and (
|
||||
local['id'] not in current or current[local['id']]['revision'] != local['revision']):
|
||||
conflicts += 1
|
||||
continue
|
||||
saved = self.store.save_template_profile(*identity, payload, None, None, 0,
|
||||
profile_id=local['id'] if local else None, expected=local['revision'] if local else None, db=db)
|
||||
catalog_changed = True
|
||||
db.execute('INSERT INTO bambu_preset_links VALUES (?,?,?,?,?) ON CONFLICT(account, remote_id) DO UPDATE SET revision=excluded.revision,fingerprint=excluded.fingerprint',
|
||||
(account, preset.id, saved['id'], saved['revision'], preset.fingerprint))
|
||||
if push:
|
||||
exported = await self.codec.export([local for _, local in push])
|
||||
for (preset, local), value in zip(push, exported, strict=True):
|
||||
if not self.enabled(account):
|
||||
break
|
||||
try:
|
||||
current = self.store.user_profile(local['id'])
|
||||
except KeyError:
|
||||
continue
|
||||
if current['revision'] != local['revision']:
|
||||
continue
|
||||
options = {key: field for key, field in value['content'].items()
|
||||
if key not in {'user_id', 'setting_id', 'created_time', 'updated_time', 'update_time'}}
|
||||
content = {**preset.content, **options, 'name': preset.name}
|
||||
fingerprint = RemotePreset(preset.id, preset.name, content).fingerprint
|
||||
await self.call('update_user_preset', account=account, setting_id=preset.id, name=preset.name,
|
||||
content=content)
|
||||
with self.store.connection() as db:
|
||||
db.execute('UPDATE bambu_preset_links SET revision=?,fingerprint=? WHERE account=? AND remote_id=?',
|
||||
(local['revision'], fingerprint, account, preset.id))
|
||||
return {'conflicts': conflicts, 'catalog_changed': catalog_changed}
|
||||
@@ -236,6 +236,54 @@ class FilamentLibrary:
|
||||
# A transferring owner may no longer have access to the result.
|
||||
return {'id':identity,'revision':revision+1}
|
||||
|
||||
def sync_snapshot(self, identity, user=None):
|
||||
user = self.user(user)
|
||||
with self.store.connection() as db:
|
||||
db.execute('BEGIN')
|
||||
self.manage(db, identity, user)
|
||||
rows = db.execute('SELECT id,revision,data,deleted FROM filament_products WHERE library_id=? ORDER BY id LIMIT 1001',
|
||||
(identity,)).fetchall()
|
||||
if len(rows) > 1000:
|
||||
raise HTTPException(422, 'This library exceeds the mobile synchronization limit')
|
||||
products = []
|
||||
for row in rows:
|
||||
data = None if row['deleted'] else ProductData.model_validate_json(row['data']).model_dump()
|
||||
fingerprint = None if data is None else hashlib.sha256(
|
||||
json.dumps(data, sort_keys=True, separators=(',', ':')).encode()).hexdigest()
|
||||
products.append({'id': row['id'], 'revision': row['revision'], 'data': data, 'fingerprint': fingerprint})
|
||||
return {'products': products}
|
||||
|
||||
def sync_merge(self, identity, products, user=None):
|
||||
user = self.user(user)
|
||||
if len({item.id for item in products}) != len(products):
|
||||
raise HTTPException(422, 'A filament can appear only once in a synchronization batch')
|
||||
updated, conflicts = [], []
|
||||
with self.store.connection() as db:
|
||||
db.execute('BEGIN IMMEDIATE')
|
||||
self.manage(db, identity, user)
|
||||
for item in products:
|
||||
product_id = str(item.id)
|
||||
row = db.execute('SELECT * FROM filament_products WHERE id=?', (product_id,)).fetchone()
|
||||
data = item.data.model_dump()
|
||||
if row is None and item.revision == 0:
|
||||
db.execute('INSERT INTO filament_products VALUES (?,?,1,?,0,?,?)',
|
||||
(product_id, identity, json.dumps(data), time.time(), time.time()))
|
||||
elif (row is None or row['library_id'] != identity or row['deleted']
|
||||
or row['revision'] != item.revision or not self.can_change_material(db, row, data['material'])):
|
||||
conflicts.append(product_id)
|
||||
continue
|
||||
else:
|
||||
db.execute('UPDATE filament_products SET data=?,revision=revision+1,updated=? WHERE id=?',
|
||||
(json.dumps(data), time.time(), product_id))
|
||||
updated.append(product_id)
|
||||
return {'updated': updated, 'conflicts': conflicts}
|
||||
|
||||
@staticmethod
|
||||
def can_change_material(db, row, material):
|
||||
previous = json.loads(row['data'])['material']
|
||||
return previous in ('Unknown', material) or not db.execute(
|
||||
'SELECT 1 FROM filament_product_profiles WHERE product_id=?', (row['id'],)).fetchone()
|
||||
|
||||
def create_product(self, library_id, data, user=None):
|
||||
user=self.user(user);data=ProductData.model_validate(data).model_dump();identity=str(uuid.uuid4());now=time.time()
|
||||
with self.store.connection() as db:
|
||||
@@ -277,9 +325,7 @@ class FilamentLibrary:
|
||||
with self.store.connection() as db:
|
||||
db.execute('BEGIN IMMEDIATE');row=self.row(db,'filament_products',identity,active=True)
|
||||
self.manage(db,row['library_id'],user);self.check_revision(row,revision)
|
||||
previous=json.loads(row['data'])
|
||||
if previous['material'] not in ('Unknown',data['material']) and db.execute(
|
||||
'SELECT 1 FROM filament_product_profiles WHERE product_id=?',(identity,)).fetchone():
|
||||
if not self.can_change_material(db, row, data['material']):
|
||||
raise HTTPException(409,'Create a separate filament product or review its slicing profiles before changing material type')
|
||||
db.execute('UPDATE filament_products SET data=?,revision=revision+1,updated=? WHERE id=?',(json.dumps(data),time.time(),identity))
|
||||
return self.product(identity,user)
|
||||
|
||||
@@ -28,6 +28,18 @@ class ProductUpdate(ProductData):
|
||||
revision:int=Field(ge=1)
|
||||
|
||||
|
||||
class SyncProduct(BaseModel):
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
id: uuid.UUID
|
||||
revision: int = Field(ge=0)
|
||||
data: ProductData
|
||||
|
||||
|
||||
class LibrarySync(BaseModel):
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
products: list[SyncProduct] = Field(max_length=1000)
|
||||
|
||||
|
||||
class AvailabilityChange(BaseModel):
|
||||
model_config=ConfigDict(extra='forbid')
|
||||
revision:int=Field(ge=1)
|
||||
@@ -119,6 +131,14 @@ def install_filament_product_api(app,store):
|
||||
owner_id=str(body.owner_id) if body.owner_id else None,
|
||||
managers=[str(u) for u in body.managers] if body.managers is not None else None)
|
||||
|
||||
@app.get('/api/v1/filament-libraries/{library_id}/sync')
|
||||
def library_snapshot(library_id: uuid.UUID):
|
||||
return service.sync_snapshot(str(library_id))
|
||||
|
||||
@app.post('/api/v1/filament-libraries/{library_id}/sync')
|
||||
def merge_library(library_id: uuid.UUID, body: LibrarySync):
|
||||
return service.sync_merge(str(library_id), body.products)
|
||||
|
||||
@app.get('/api/v1/filament-products')
|
||||
def products(library_id:uuid.UUID|None=None,machine_id:uuid.UUID|None=None,q:str=Query(default='',max_length=128)):
|
||||
return service.products(library_id=str(library_id) if library_id else None,
|
||||
@@ -183,6 +203,13 @@ def install_filament_product_api(app,store):
|
||||
values=await app.state.template_catalog.choices(owned['template_name'])
|
||||
return [item for item in values['filaments'] if item['compatible'] and item.get('filament_type')==product['material']]
|
||||
|
||||
@app.get('/api/v1/filament-product-template')
|
||||
async def product_template(name: str = Query(min_length=1,max_length=512)):
|
||||
snapshot = await app.state.template_catalog.snapshot('filament', name)
|
||||
if snapshot is None:
|
||||
raise HTTPException(404, 'The filament template is unavailable')
|
||||
return service.legacy_metadata(snapshot.get('display_name') or name.split('/')[-1], snapshot)
|
||||
|
||||
@app.get('/api/v1/filament-products/{product_id}/profile-sources')
|
||||
async def sources(product_id:uuid.UUID,machine_id:uuid.UUID,profile_id:str):
|
||||
return await profile_sources(str(product_id),str(machine_id),profile_id)
|
||||
|
||||
@@ -8,7 +8,7 @@ import uuid
|
||||
import zipfile
|
||||
|
||||
from fastapi import File, HTTPException, UploadFile, Query
|
||||
from fastapi.responses import FileResponse
|
||||
from fastapi.responses import FileResponse, Response
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictInt, ValidationError, model_validator
|
||||
from typing import Literal
|
||||
|
||||
@@ -384,7 +384,11 @@ class ImportQueue:
|
||||
for path, report in zip(payload['paths'], reports):
|
||||
if Path(path).suffix.lower() in {'.3mf', '.amf', '.step', '.stp'}:report['suggested_units'] = 'none'
|
||||
payload['reports'] = reports
|
||||
if any(report.get('suggested_units') != 'none' or report.get('multipart') or report.get('step') or report.get('texture', {}).get('available') for report in reports):
|
||||
if payload.get('automatic_open'):
|
||||
payload['options'] = [ImportOptions(
|
||||
texture=TextureImportOptions(mode='skip') if report.get('texture', {}).get('available') else None,
|
||||
).model_dump(exclude_none=True) for report in reports]
|
||||
elif any(report.get('suggested_units') != 'none' or report.get('multipart') or report.get('step') or report.get('texture', {}).get('available') for report in reports):
|
||||
self.update(job_id, 'waiting_options', expected={'running'}, progress=35, payload=payload)
|
||||
return
|
||||
if not payload.get('staged'):
|
||||
@@ -510,8 +514,11 @@ class ImportQueue:
|
||||
state['imported_project'] = True
|
||||
payload.update(staged=str(snapshot), state=state, scaling=state.get('import_scaling'))
|
||||
if state.get('import_scaling', {}).get('pending'):
|
||||
self.update(job_id, 'waiting_scale', expected={'running'}, progress=80, payload=payload)
|
||||
return
|
||||
if payload.get('automatic_open'):
|
||||
state['import_scaling']['pending'] = []
|
||||
else:
|
||||
self.update(job_id, 'waiting_scale', expected={'running'}, progress=80, payload=payload)
|
||||
return
|
||||
state, snapshot = payload['state'], Path(payload['staged'])
|
||||
if payload.get('accept_scale'):
|
||||
scaled = directory / (uuid.uuid4().hex + '.3mf')
|
||||
@@ -733,6 +740,51 @@ def install_import_api(app, queue, receive_upload, plate_type, filament_profiles
|
||||
if not committed and attempt_root is not None:
|
||||
await file_work(shutil.rmtree, attempt_root, ignore_errors=True)
|
||||
|
||||
@app.post('/api/v1/imports/open-model', status_code=201, response_model=ImportResponse)
|
||||
async def open_model(file: UploadFile, response: Response, machine_id: uuid.UUID | None = None,
|
||||
profile_id: str | None = Query(default=None, min_length=1, max_length=64)):
|
||||
name = Path((file.filename or '').replace('\\', '/')).name
|
||||
suffix = Path(name).suffix.lower()
|
||||
if suffix not in {'.3mf', '.stl', '.step', '.stp'}:
|
||||
raise HTTPException(422, 'Choose a 3MF, STL or STEP model')
|
||||
if profile_id is not None and machine_id is None:
|
||||
raise HTTPException(422, 'Select a printer for this profile')
|
||||
machines = queue.machines.list()
|
||||
if machine_id is not None:
|
||||
selected = next((machine for machine in machines if machine['id'] == str(machine_id)), None)
|
||||
if selected is None:
|
||||
raise HTTPException(404, 'Printer not found')
|
||||
preference = {}
|
||||
else:
|
||||
preference = queue.store.machine_preference() or {}
|
||||
selected = next((machine for machine in machines if machine['id'] == preference.get('machine_id')), None)
|
||||
if selected is None and len(machines) == 1:
|
||||
selected, preference = machines[0], {}
|
||||
if selected is None:
|
||||
raise HTTPException(422, 'Choose a physical printer in Web Slicer before opening external models')
|
||||
profiles = selected['profiles']
|
||||
target_profile = profile_id or preference.get('profile_id')
|
||||
owner = next((profile for profile in profiles if profile['id'] == target_profile), None)
|
||||
if owner is None and profile_id is None:
|
||||
preference = {}
|
||||
owner = next((profile for profile in profiles if profile['id'] == selected['last_profile_id']), None)
|
||||
if owner is None and len(profiles) == 1:
|
||||
owner = profiles[0]
|
||||
if owner is None:
|
||||
raise HTTPException(422, 'Choose a printer profile before opening external models')
|
||||
selection = MachineSelection(machine_id=selected['id'], profile_id=owner['id'],
|
||||
process_id=preference.get('process_id'), filament_ids=preference.get('filament_ids'))
|
||||
try:
|
||||
payload = await import_payload(StartImport(names=[name], machine=selection,
|
||||
three_mf_mode='geometry' if suffix == '.3mf' else None))
|
||||
except KeyError as error:
|
||||
raise HTTPException(422, 'The selected printer preset is unavailable') from error
|
||||
payload['automatic_open'] = True
|
||||
job = queue.create(payload)
|
||||
accepted = await upload(job['id'], [file])
|
||||
response.headers['Location'] = f"/?import-job={job['id']}"
|
||||
return accepted
|
||||
|
||||
@app.post('/api/v1/import-archives', status_code=201, response_model=ImportArchive)
|
||||
async def archive_upload(file: UploadFile, request_id: str | None = Query(default=None, pattern=r'^[0-9a-f]{32}$')):
|
||||
async with archive_lock:
|
||||
|
||||
@@ -96,7 +96,8 @@ class JobArtifacts:
|
||||
'(SELECT 1 FROM job_artifact_pins p WHERE p.job_id=jobs.id)', (identity,)).fetchone()
|
||||
if not job:
|
||||
return False
|
||||
db.execute('UPDATE jobs SET artifacts_expired=1,artifact_cleanup_pending=1 WHERE id=?', (identity,))
|
||||
db.execute('UPDATE jobs SET artifacts_expired=1,artifact_cleanup_pending=1,updated=? WHERE id=?',
|
||||
(time.time(), identity))
|
||||
directory = self.store.root/'jobs'/identity
|
||||
try:
|
||||
if directory.is_symlink():
|
||||
|
||||
@@ -147,7 +147,7 @@ class MachineLibrary:
|
||||
if access := getattr(self.store, 'access', None):
|
||||
access.claim_new(db, 'machine', identity, owner_id)
|
||||
for variant in variants:
|
||||
self._add_profile(db, identity, variant)
|
||||
self._add_profile(db, identity, variant, connection=connection)
|
||||
if connection is not None:
|
||||
connection = self.connection_model(db, identity, connection)
|
||||
value = self.store._printer_settings({**connection, 'name': name}, {})
|
||||
@@ -475,13 +475,20 @@ class MachineLibrary:
|
||||
db.execute('UPDATE physical_machines SET revision=revision+1,updated=? WHERE id=?', (time.time(), identity))
|
||||
return self.machine(identity)
|
||||
|
||||
def _add_profile(self, db, identity, variant):
|
||||
def _add_profile(self, db, identity, variant, *, connection=None):
|
||||
label = variant['name'].strip()
|
||||
if not label or len(label) > 128 or any(ord(c) < 32 for c in label):
|
||||
raise ValueError('Invalid machine profile name')
|
||||
if db.execute('SELECT 1 FROM machine_profiles WHERE machine_id=? AND name=?', (identity, label)).fetchone():
|
||||
raise LibraryConflict('A profile with this name already belongs to this machine')
|
||||
snapshots = [clean_snapshot(value) for value in variant['presets']]
|
||||
if connection is None:
|
||||
transport = db.execute('SELECT data FROM saved_printers WHERE id=? AND deleted=0', (identity,)).fetchone()
|
||||
connection = json.loads(transport['data']) if transport else None
|
||||
if (connection or {}).get('type') == 'bambu_lan':
|
||||
for preset in snapshots:
|
||||
if preset['scope'] == 'printer':
|
||||
preset['config']['use_3mf'] = '1'
|
||||
if sum(p['scope'] == 'printer' for p in snapshots) != 1 or not all(
|
||||
any(p['scope'] == scope for p in snapshots) for scope in SCOPES):
|
||||
raise ValueError('Each machine profile needs one printer preset, processes and filaments')
|
||||
|
||||
@@ -156,9 +156,9 @@ def native_selection(selection, *, initialize_colors=False):
|
||||
return result
|
||||
|
||||
|
||||
async def create_machine_snapshot(worker, output, selection, *, geometry=None):
|
||||
async def create_machine_snapshot(worker, output, selection, *, geometry=None, settings=None):
|
||||
arguments = native_selection(selection, initialize_colors=True)
|
||||
settings = arguments.pop('settings', None)
|
||||
settings = {**arguments.pop('settings', {}), **(settings or {})}
|
||||
paths = {'output': str(output), **({'geometry': str(geometry)} if geometry is not None else {})}
|
||||
state = await worker.run('create', **paths, **arguments)
|
||||
if settings:
|
||||
|
||||
@@ -25,6 +25,7 @@ def connect_printer(connection, *, credential_database=None, **options):
|
||||
if spec.id == 'bambu_lan' and connection.get('bambu_transport') == 'cloud':
|
||||
from .bambu_cloud_link import BambuCloudLink
|
||||
return BambuCloudLink(serial_number=connection.get('bambu_serial_number') or '',
|
||||
account_owner=connection.get('_bambu_account_owner'),
|
||||
printer_model=connection.get('printer_model', ''), **options)
|
||||
if spec.id == 'bambu_lan':
|
||||
from .bambu_lan import BambuLAN
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""Native preset file conversion with reviewed, atomic shared-library imports."""
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path, PurePosixPath
|
||||
@@ -397,10 +398,51 @@ def install_profile_bundle_api(app, store, worker, native_user_profiles, receive
|
||||
@app.post('/api/v1/user-profile-imports', response_model=ImportPlan, status_code=201)
|
||||
async def stage(file: UploadFile, preserve_namespace: bool = Form(default=True),
|
||||
replace_package: bool = Form(default=False)):
|
||||
async def receive(directory):
|
||||
return await receive_upload(file, directory, LIMIT)
|
||||
return await stage_source(receive, preserve_namespace, replace_package)
|
||||
|
||||
@app.post('/api/v1/user-profile-imports/bambu-cloud', response_model=ImportPlan, status_code=201)
|
||||
async def stage_bambu_cloud():
|
||||
host = app.state.bambu_account_host()
|
||||
if host is None or not host.cloud:
|
||||
raise HTTPException(404, 'Bambu Lab cloud requires a cloud-enabled build')
|
||||
|
||||
async def receive(directory):
|
||||
from .bambu_cloud import REPLY_TIMEOUT
|
||||
try:
|
||||
bundle = json.loads((worker.resources / 'profiles' / 'Custom.json').read_text(encoding='utf-8'))
|
||||
reply = await asyncio.wait_for(asyncio.to_thread(host.call, 'user_presets',
|
||||
bundle_version=bundle['version']), REPLY_TIMEOUT)
|
||||
except TimeoutError as error:
|
||||
raise HTTPException(504, 'Bambu did not answer in time') from error
|
||||
except (RuntimeError, ValueError) as error:
|
||||
raise HTTPException(503, str(error)) from error
|
||||
source = directory / 'bambu-lab-presets.zip'
|
||||
kinds = {'printer': 'machine', 'print': 'process', 'filament': 'filament'}
|
||||
metadata = {'type', 'name', 'version', 'inherits', 'filament_id', 'created_time', 'updated_time', 'update_time', 'base_id'}
|
||||
total = count = 0
|
||||
with zipfile.ZipFile(source, 'w', compression=zipfile.ZIP_DEFLATED) as archive:
|
||||
for name, values in sorted(reply['presets'].items()):
|
||||
kind = kinds.get(values.get('type'))
|
||||
if kind is None or not values.keys() - metadata:
|
||||
continue
|
||||
data = json.dumps({**values, 'name': name, 'type': kind}, ensure_ascii=False).encode()
|
||||
total += len(data)
|
||||
count += 1
|
||||
if len(data) > 2 * 1024 * 1024 or total > LIMIT or count > 256:
|
||||
raise HTTPException(422, 'The Bambu Lab preset collection is too large to import')
|
||||
archive.writestr(f'preset-{count}.json', data)
|
||||
if not count:
|
||||
raise HTTPException(422, 'There are no printer, process or filament presets on this Bambu Lab account')
|
||||
return source
|
||||
return await stage_source(receive, False, False, cloud=True)
|
||||
|
||||
async def stage_source(receive, preserve_namespace, replace_package, *, cloud=False):
|
||||
await capable()
|
||||
directory = Path(tempfile.mkdtemp(prefix='preset-import-', dir=store.root / 'work'))
|
||||
try:
|
||||
source = await receive_upload(file, directory, LIMIT)
|
||||
source = await receive(directory)
|
||||
if source.suffix.lower() not in {'.json', '.zip', '.orca_printer', '.orca_filament', '.orca_bundle'}:
|
||||
raise HTTPException(422, 'Choose JSON, ZIP or an Orca preset bundle')
|
||||
records = store.user_profiles()
|
||||
@@ -414,12 +456,19 @@ def install_profile_bundle_api(app, store, worker, native_user_profiles, receive
|
||||
preserve_namespace=preserve_namespace, bundle_metadata=metadata)
|
||||
except (ValueError, zipfile.BadZipFile, NotImplementedError, RuntimeError) as error:
|
||||
raise HTTPException(422, 'Invalid preset file: ' + str(error)) from error
|
||||
files = []
|
||||
for index, (_, scope, document) in enumerate(entries):
|
||||
target = directory / f'profile-{index}.json'
|
||||
target.write_text(json.dumps(document, ensure_ascii=False), encoding='utf-8')
|
||||
files.append({'scope': scope, 'file': str(target)})
|
||||
result = await worker.run('profile_files', action='inspect', files=files, user_profiles=native_user_profiles(templates))
|
||||
users = native_user_profiles(templates)
|
||||
if cloud:
|
||||
kinds = {'printer': 'printer', 'process': 'print', 'filament': 'filament'}
|
||||
profiles = [{'scope': scope, 'name': document['name'], 'content': {**document, 'type': kinds[scope]}}
|
||||
for _, scope, document in entries]
|
||||
result = await worker.run('profile_files', action='cloud_inspect', profiles=profiles, user_profiles=users)
|
||||
else:
|
||||
files = []
|
||||
for index, (_, scope, document) in enumerate(entries):
|
||||
target = directory / f'profile-{index}.json'
|
||||
target.write_text(json.dumps(document, ensure_ascii=False), encoding='utf-8')
|
||||
files.append({'scope': scope, 'file': str(target)})
|
||||
result = await worker.run('profile_files', action='inspect', files=files, user_profiles=users)
|
||||
existing = {(r['scope'], r['name']): {'id': r['id'], 'revision': r['revision']} for r in templates}
|
||||
plan = {'id': uuid.uuid4().hex, 'filename': source.name, 'sha256': hashlib.sha256(source.read_bytes()).hexdigest(),
|
||||
'library_token': store.library_token(records), 'preserve_namespace': preserve_namespace, 'items': []}
|
||||
|
||||
@@ -128,6 +128,7 @@ class Store:
|
||||
# Old terminal jobs may already have run extension side effects.
|
||||
db.execute("UPDATE jobs SET execution_started=1 WHERE status!='queued'")
|
||||
db.execute('CREATE INDEX IF NOT EXISTS jobs_status_priority ON jobs(status,automatic,created)')
|
||||
db.execute('CREATE INDEX IF NOT EXISTS jobs_project_updated ON jobs(project_id,updated)')
|
||||
if "last_opened" not in {row["name"] for row in db.execute("PRAGMA table_info(projects)")}:
|
||||
db.execute("ALTER TABLE projects ADD COLUMN last_opened REAL NOT NULL DEFAULT 0")
|
||||
if "recent_opened" not in {row["name"] for row in db.execute("PRAGMA table_info(projects)")}:
|
||||
@@ -403,6 +404,13 @@ class Store:
|
||||
if publish: publish(db, project_id, 1)
|
||||
return self.project(project_id)
|
||||
|
||||
def project_revision(self, project_id: str) -> int:
|
||||
with self.connection() as db:
|
||||
row = db.execute("SELECT revision FROM projects WHERE id=?", (project_id,)).fetchone()
|
||||
if row is None:
|
||||
raise KeyError(project_id)
|
||||
return row["revision"]
|
||||
|
||||
def project(self, project_id: str, revision: int | None = None):
|
||||
with self.connection() as db:
|
||||
row = db.execute("SELECT * FROM projects WHERE id=?", (project_id,)).fetchone()
|
||||
@@ -676,10 +684,14 @@ class Store:
|
||||
result['plugin_runtime'] = json.loads(result['plugin_runtime']) if result.get('plugin_runtime') else None
|
||||
return result
|
||||
|
||||
def jobs(self, project_id: str):
|
||||
def jobs(self, project_id: str, updated_after: float | None = None):
|
||||
query = "SELECT * FROM jobs WHERE project_id=?"
|
||||
parameters = (project_id,)
|
||||
if updated_after is not None:
|
||||
query += " AND updated>=?"
|
||||
parameters = (project_id, updated_after)
|
||||
with self.connection() as db:
|
||||
return [self._job(row) for row in db.execute(
|
||||
"SELECT * FROM jobs WHERE project_id=? ORDER BY created DESC", (project_id,))]
|
||||
return [self._job(row) for row in db.execute(query + " ORDER BY created DESC", parameters)]
|
||||
|
||||
def update_job(self, job_id: str, *, status: str, progress: int = 0,
|
||||
message: str = "", result: dict | None = None):
|
||||
@@ -699,8 +711,18 @@ class Store:
|
||||
row = db.execute("SELECT revision, data FROM printer_settings WHERE id=1").fetchone()
|
||||
else:
|
||||
row = db.execute('SELECT revision, data FROM saved_printers WHERE id=? AND deleted=0', (printer_id,)).fetchone()
|
||||
return {**json.loads(row['data']), 'revision': row['revision'],
|
||||
**({'id': printer_id} if printer_id is not None else {})} if row else None
|
||||
if not row:
|
||||
return None
|
||||
value = {**json.loads(row['data']), 'revision': row['revision']}
|
||||
if printer_id is not None:
|
||||
value['id'] = printer_id
|
||||
access = getattr(self, 'access', None)
|
||||
if access and access.auth.required and value.get('bambu_transport') == 'cloud':
|
||||
owner = db.execute("SELECT user_id FROM resource_owners WHERE kind='machine' AND resource_id=?",
|
||||
(printer_id,)).fetchone()
|
||||
if owner:
|
||||
value['_bambu_account_owner'] = owner['user_id']
|
||||
return value
|
||||
|
||||
def printers(self):
|
||||
with self.connection() as db:
|
||||
|
||||
@@ -55,3 +55,35 @@ def test_completed_native_archive_passes_delivery_validation(client, printer, fi
|
||||
else:
|
||||
assert '\nM624 ' not in code
|
||||
assert f'M486 A{objects[0]["name"]}' in code
|
||||
|
||||
|
||||
@pytest.mark.parametrize('transport', ['lan', 'cloud'])
|
||||
def test_bambu_p1s_builds_3mf_for_both_transports(client, transport):
|
||||
connection = {'revision': 0, 'type': 'bambu_lan', 'bambu_transport': transport, 'auth_type': 'api_key',
|
||||
'bambu_serial_number': 'P1STEST123',
|
||||
'host': 'http://bambu-cloud.invalid/' if transport == 'cloud' else 'http://192.0.2.1/',
|
||||
**({'api_key': 'testcode1'} if transport == 'lan' else {})}
|
||||
response = client.post('/api/v1/machines', json={'name': 'Bambu transport test', 'connection': connection,
|
||||
'profiles': [{'name': '0.4 mm', 'printer': 'Bambu Lab P1S 0.4 nozzle',
|
||||
'filament_templates': ['Generic PLA']}]})
|
||||
assert response.status_code == 201, response.text
|
||||
machine = response.json()
|
||||
response = client.post('/api/v1/imports', json={'names': ['cube.obj'], 'machine': {
|
||||
'machine_id': machine['id'], 'profile_id': machine['profiles'][0]['id']}})
|
||||
assert response.status_code == 201, response.text
|
||||
task = response.json()
|
||||
response = client.post('/api/v1/imports/' + task['id'] + '/files',
|
||||
files=[('files', ('cube.obj', (ROOT/'tests/data/20mm_cube.obj').read_bytes()))])
|
||||
assert response.status_code == 200, response.text
|
||||
project = result(client, task)
|
||||
assert project['state']['config']['use_3mf'] == '1'
|
||||
# Older projects may carry a plain-G-code preference. Direct API slicing
|
||||
# still creates the transport artifact from the immutable captured input.
|
||||
project = change(client, project, 'settings', {'settings': {'use_3mf': '0'},
|
||||
'strings': {'machine_start_gcode': 'G90\nM83','before_layer_change_gcode': 'G92 E0'}}, 'PATCH')
|
||||
job = terminal_job(client, project)
|
||||
assert job['status'] == 'completed', job
|
||||
assert job['revision'] == project['revision']
|
||||
assert job['result']['upload_format'] == 'gcode_3mf'
|
||||
assert client.get('/api/v1/projects/' + project['id']).json()['revision'] == project['revision']
|
||||
assert client.get('/api/v1/jobs/' + job['id'] + '/artifacts/sliced-3mf').status_code == 200
|
||||
|
||||
@@ -40,6 +40,7 @@ def test_unavailable_without_the_cloud_build(unconfigured):
|
||||
assert unconfigured.get('/api/v1/bambu-cloud').json() == {'available': False}
|
||||
assert unconfigured.post('/api/v1/bambu-cloud/login', json={'ticket': 'ABCD1234'}).status_code == 404
|
||||
assert unconfigured.post('/api/v1/bambu-cloud/logout').status_code == 404
|
||||
assert unconfigured.post('/api/v1/user-profile-imports/bambu-cloud').status_code == 404
|
||||
|
||||
|
||||
@pytest.mark.parametrize('body', [{}, {'ticket': 'ab', 'session': {'a': 1}}, {'ticket': 'a b!'},
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from orca_web.app import create_app
|
||||
from test_machine_library import variant
|
||||
|
||||
|
||||
def test_desktop_pairing_is_per_user_and_cannot_be_replayed(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv('ORCA_AUTH_REQUIRED', 'true')
|
||||
monkeypatch.setenv('ORCA_AUTH_SECURE_COOKIE', 'true')
|
||||
monkeypatch.delenv('ORCA_BAMBU_CLOUD_HOST', raising=False)
|
||||
monkeypatch.delenv('ORCA_BAMBU_CLOUD_PLUGIN', raising=False)
|
||||
calls = []
|
||||
active = set()
|
||||
|
||||
def configured(root):
|
||||
def call(operation, **fields):
|
||||
if operation == 'login_ticket':
|
||||
calls.append((Path(root).name, fields))
|
||||
active.add(root)
|
||||
return {'logged_in': root in active, **({'user_id': 'bambu-user'} if root in active else {})}
|
||||
return SimpleNamespace(cloud=True, plugin_version='02.09.01', call=call,
|
||||
close=lambda: None, data_dir=Path(root) / 'bambu-cloud')
|
||||
|
||||
monkeypatch.setattr('orca_web.bambu_cloud.configured_host', configured)
|
||||
app = create_app(data=tmp_path, executable=tmp_path / 'missing-worker')
|
||||
password = 'desktop-pairing-test-password'
|
||||
admin = app.state.auth.create_user('admin', password, admin=True)
|
||||
app.state.auth.create_user('other', password)
|
||||
printer = app.state.machines.create('Cloud printer', [variant()],
|
||||
connection={'type': 'bambu_lan', 'bambu_transport': 'cloud',
|
||||
'host': 'http://bambu-cloud.invalid/', 'bambu_serial_number': 'ABC12345'},
|
||||
owner_id=admin['id'])
|
||||
assert app.state.store.printer(printer['id'])['_bambu_account_owner'] == admin['id']
|
||||
base = 'https://testserver'
|
||||
route = '/api/v1/bambu-cloud/desktop-login'
|
||||
with TestClient(app, base_url=base) as browser, TestClient(app, base_url=base) as helper:
|
||||
assert helper.post(route).status_code == 401
|
||||
login = browser.post('/api/v1/auth/login', json={'username': 'admin', 'password': password},
|
||||
headers={'Origin': base, 'X-Orca-CSRF': 'login'})
|
||||
assert login.status_code == 200, login.text
|
||||
headers = {'Origin': base, 'X-Orca-CSRF': login.json()['csrf_token']}
|
||||
issued = browser.post(route, headers=headers)
|
||||
assert issued.status_code == 200, issued.text
|
||||
credential = {'Authorization': 'Bearer ' + issued.json()['code']}
|
||||
assert helper.post(route + '/redeem', json={'ticket': 'TEST'}, headers={**credential, 'Origin': base}).status_code == 403
|
||||
assert helper.post(route + '/redeem', json={'ticket': 'TEST'}, headers=credential).status_code == 204
|
||||
assert helper.post(route + '/redeem', json={'ticket': 'TEST'}, headers=credential).status_code == 403
|
||||
assert calls == [(admin['id'], {'ticket': 'TEST'})]
|
||||
assert browser.get('/api/v1/bambu-cloud').json()['logged_in'] is True
|
||||
with TestClient(app, base_url=base) as other:
|
||||
signed_in = other.post('/api/v1/auth/login', json={'username': 'other', 'password': password},
|
||||
headers={'Origin': base, 'X-Orca-CSRF': 'login'})
|
||||
assert signed_in.status_code == 200
|
||||
assert other.get('/api/v1/bambu-cloud').json()['logged_in'] is False
|
||||
code = other.post(route, headers={'Origin': base, 'X-Orca-CSRF': signed_in.json()['csrf_token']})
|
||||
assert code.status_code == 200
|
||||
assert code.json()['code'] != issued.json()['code']
|
||||
|
||||
credential = {'Authorization': 'Bearer ' + browser.post(route, headers=headers).json()['code']}
|
||||
assert browser.post('/api/v1/auth/logout', headers=headers).status_code == 204
|
||||
assert helper.post(route + '/redeem', json={'ticket': 'TEST'}, headers=credential).status_code == 403
|
||||
assert len(calls) == 1
|
||||
@@ -0,0 +1,69 @@
|
||||
import asyncio
|
||||
from types import SimpleNamespace
|
||||
|
||||
from orca_web.bambu_preset_sync import BambuPresetSync
|
||||
from orca_web.store import Store
|
||||
|
||||
|
||||
def test_bambu_sync_links_updates_and_quarantines_conflicts(tmp_path):
|
||||
asyncio.run(check_bambu_sync(tmp_path))
|
||||
|
||||
|
||||
async def check_bambu_sync(tmp_path):
|
||||
resources = tmp_path / 'resources'
|
||||
(resources / 'profiles').mkdir(parents=True)
|
||||
(resources / 'profiles' / 'BBL.json').write_text('{"version":"02.04.00.00"}')
|
||||
store = Store(tmp_path / 'data')
|
||||
remote = {'name': 'Lab PLA', 'type': 'filament', 'version': '2.4.0',
|
||||
'setting_id': 'remote-id', 'filament_type': 'PLA', 'filament_density': '1.24'}
|
||||
writes = []
|
||||
|
||||
async def call(operation, **body):
|
||||
if operation == 'user_presets':
|
||||
return {'account': 'account', 'presets': {remote['name']: dict(remote)}}
|
||||
assert operation == 'update_user_preset' and body['account'] == 'account'
|
||||
assert body['setting_id'] == 'remote-id'
|
||||
writes.append(body)
|
||||
remote.update(body['content'])
|
||||
|
||||
class Codec:
|
||||
async def inspect(self, presets, records, account):
|
||||
return [{'payload': {'scope': 'filament', 'name': preset.name,
|
||||
'config': {'filament_density': preset.content['filament_density']}}} for preset in presets]
|
||||
|
||||
async def export(self, records):
|
||||
return [{'content': record['payload']['config']} for record in records]
|
||||
|
||||
sync = BambuPresetSync(store, SimpleNamespace(resources=resources), call)
|
||||
sync.codec = Codec()
|
||||
assert sync.enabled('account')
|
||||
|
||||
def change_local(density):
|
||||
record, = store.template_profiles()
|
||||
return store.save_template_profile('filament', record['name'],
|
||||
{'scope': 'filament', 'name': record['name'], 'config': {'filament_density': density}},
|
||||
None, None, 0, profile_id=record['id'], expected=record['revision'])
|
||||
|
||||
assert (await sync.sync('account'))['catalog_changed']
|
||||
imported, = store.template_profiles()
|
||||
assert not (await sync.sync('account'))['catalog_changed']
|
||||
assert store.template_profiles()[0]['revision'] == imported['revision']
|
||||
|
||||
remote['filament_density'] = '1.25'
|
||||
assert (await sync.sync('account'))['catalog_changed']
|
||||
assert store.template_profiles()[0]['payload']['config']['filament_density'] == '1.25'
|
||||
|
||||
local = change_local('1.26')
|
||||
assert (await sync.sync('account'))['conflicts'] == 0
|
||||
assert remote['filament_density'] == '1.26'
|
||||
assert not (await sync.sync('account'))['catalog_changed']
|
||||
assert store.template_profiles()[0]['revision'] == local['revision']
|
||||
|
||||
change_local('1.27')
|
||||
remote['filament_density'] = '1.28'
|
||||
assert (await sync.sync('account'))['conflicts'] == 1
|
||||
assert len(writes) == 1
|
||||
assert store.template_profiles()[0]['payload']['config']['filament_density'] == '1.27'
|
||||
sync.configure('account', False)
|
||||
assert not sync.enabled('account')
|
||||
assert sync.enabled('other-account')
|
||||
@@ -0,0 +1,30 @@
|
||||
"""External model uploads use the same durable queue with safe defaults."""
|
||||
import pytest
|
||||
|
||||
from import_setup import import_machine, wait
|
||||
from test_placement_api import ROOT, client, pytestmark
|
||||
|
||||
|
||||
@pytest.mark.parametrize('fixture', [
|
||||
'tests/data/test_stl/ASCII/20mmbox-LF.stl',
|
||||
'tests/data/curved_compound.step',
|
||||
'tests/data/test_3mf/prusa-geometry.3mf',
|
||||
])
|
||||
def test_open_model_creates_a_project_without_import_decisions(client, fixture):
|
||||
machine = import_machine(client)
|
||||
source = ROOT / fixture
|
||||
response = client.post('/api/v1/imports/open-model', files={'file': (source.name, source.read_bytes())})
|
||||
assert response.status_code == 201, response.text
|
||||
task = response.json()
|
||||
assert response.headers['Location'] == '/?import-job=' + task['id']
|
||||
task = wait(client, task, {'completed', 'waiting_options', 'waiting_scale', 'waiting_texture'})
|
||||
assert task['status'] == 'completed', task
|
||||
project = client.get('/api/v1/projects/' + task['result']['project_id']).json()
|
||||
assert project['state']['objects']
|
||||
assert project['state']['machine_binding']['machine_id'] == machine['machine_id']
|
||||
|
||||
|
||||
def test_open_model_requires_supported_file_and_printer(client):
|
||||
assert client.post('/api/v1/imports/open-model', files={'file': ('note.txt', b'note')}).status_code == 422
|
||||
assert client.post('/api/v1/imports/open-model', files={'file': ('cube.stl', b'cube')}).status_code == 422
|
||||
assert client.get('/api/v1/imports').json() == []
|
||||
@@ -154,3 +154,93 @@ def test_product_copy_rejects_calibration_for_another_known_material(setup_api):
|
||||
assert app.state.store.user_profiles()==before
|
||||
assert ca.get('/api/v1/filament-products/'+target['id']).json()['profiles']==[]
|
||||
ca.close()
|
||||
|
||||
|
||||
def test_filament_product_draft_from_preset_without_a_printer(setup_api, monkeypatch):
|
||||
app, client, _, _, _, student, _, _ = setup_api
|
||||
|
||||
async def snapshot(scope, name):
|
||||
assert (scope, name) == ('filament', 'Example PETG @ Example Printer')
|
||||
return {'config': {'filament_vendor': 'Example', 'filament_type': 'PETG', 'filament_density': '1.27'}}
|
||||
|
||||
monkeypatch.setattr(app.state.template_catalog, 'snapshot', snapshot)
|
||||
with client(student) as c:
|
||||
response = c.get('/api/v1/filament-product-template', params={'name': 'Example PETG @ Example Printer'})
|
||||
assert response.status_code == 200, response.text
|
||||
draft = response.json()
|
||||
assert (draft['name'], draft['vendor'], draft['material'], draft['density']) == ('Example PETG', 'Example', 'PETG', 1.27)
|
||||
library = c.post('/api/v1/filament-libraries/default').json()
|
||||
created = c.post('/api/v1/filament-products', json={**draft, 'library_id': library['id']})
|
||||
assert created.status_code == 201, created.text
|
||||
assert created.json()['printer_ids'] == []
|
||||
assert created.json()['profiles'] == []
|
||||
|
||||
|
||||
def test_library_sync_locks_to_managed_library_and_merges_by_revision(setup_api):
|
||||
import uuid
|
||||
|
||||
_, client, _, user, other, student, machine, _ = setup_api
|
||||
with client(user) as source, client(other) as destination, client(student) as viewer:
|
||||
library, product = create(source, machine, 'Portable PETG')
|
||||
source_path = f"/api/v1/filament-libraries/{library['id']}/sync"
|
||||
assert viewer.get(source_path).status_code == 404
|
||||
snapshot = source.get(source_path).json()['products']
|
||||
original = next(row for row in snapshot if row['id'] == product['id'])
|
||||
assert set(original['data']) == set(DATA) | {'diameter', 'density', 'notes'}
|
||||
assert original['fingerprint']
|
||||
assert 'printer_ids' not in original['data']
|
||||
|
||||
target = destination.post('/api/v1/filament-libraries/default').json()
|
||||
target_path = f"/api/v1/filament-libraries/{target['id']}/sync"
|
||||
# A UUID already claimed by another library must not move across owners.
|
||||
collision = {'id': original['id'], 'revision': 0, 'data': original['data']}
|
||||
assert destination.post(target_path, json={'products': [collision]}).json() == {
|
||||
'updated': [], 'conflicts': [original['id']]}
|
||||
|
||||
identity = str(uuid.uuid4())
|
||||
change = {**collision, 'id': identity}
|
||||
assert destination.post(target_path, json={'products': [change]}).json() == {
|
||||
'updated': [identity], 'conflicts': []}
|
||||
retry = destination.post(target_path, json={'products': [change]})
|
||||
assert retry.json() == {'updated': [], 'conflicts': [identity]}
|
||||
saved = destination.get(target_path).json()['products'][0]
|
||||
assert saved['fingerprint'] == original['fingerprint']
|
||||
updated = {**change, 'revision': saved['revision'], 'data': {**original['data'], 'notes': 'Changed on phone'}}
|
||||
assert destination.post(target_path, json={'products': [updated]}).json()['updated'] == [identity]
|
||||
assert destination.post(target_path, json={'products': [updated]}).json()['conflicts'] == [identity]
|
||||
|
||||
saved = destination.get(target_path).json()['products'][0]
|
||||
assert destination.delete('/api/v1/filament-products/'+identity, params={'revision': saved['revision']}).status_code == 200
|
||||
deleted = destination.get(target_path).json()['products'][0]
|
||||
assert deleted['data'] is None and deleted['fingerprint'] is None
|
||||
assert destination.post(target_path, json={'products': [{**updated, 'revision': deleted['revision']}]}).json()['conflicts'] == [identity]
|
||||
assert viewer.post(target_path, json={'products': [change]}).status_code == 404
|
||||
|
||||
|
||||
def test_library_sync_roundtrip_between_separate_workspaces(setup_api, monkeypatch, tmp_path):
|
||||
_, client, _, user, _, _, _, _ = setup_api
|
||||
monkeypatch.setenv('ORCA_DATA', str(tmp_path / 'phone'))
|
||||
monkeypatch.setenv('ORCA_AUTH_REQUIRED', 'false')
|
||||
monkeypatch.setenv('ORCA_AUTH_SECURE_COOKIE', 'false')
|
||||
phone_app = create_app()
|
||||
with TestClient(phone_app) as phone, client(user) as server:
|
||||
local_id = phone.post('/api/v1/filament-libraries/default').json()['id']
|
||||
remote_id = server.post('/api/v1/filament-libraries/default').json()['id']
|
||||
local_path = f'/api/v1/filament-libraries/{local_id}/sync'
|
||||
remote_path = f'/api/v1/filament-libraries/{remote_id}/sync'
|
||||
csrf = {'X-Orca-CSRF': 'login'}
|
||||
product = phone.post('/api/v1/filament-products', json={'library_id': local_id, **DATA}).json()
|
||||
original = phone.get(local_path).json()['products'][0]
|
||||
push = {'products': [{'id': product['id'], 'revision': 0, 'data': original['data']}]}
|
||||
assert server.post(remote_path, json=push).json()['updated'] == [product['id']]
|
||||
remote = server.get(remote_path).json()['products'][0]
|
||||
assert remote['fingerprint'] == original['fingerprint']
|
||||
server_edit = {**remote['data'], 'notes': 'Changed on the server'}
|
||||
assert server.patch('/api/v1/filament-products/' + product['id'],
|
||||
json={'revision': remote['revision'], **server_edit}).status_code == 200
|
||||
|
||||
pull = {'products': [{'id': product['id'], 'revision': product['revision'], 'data': server_edit}]}
|
||||
assert phone.post(local_path, json=pull).status_code == 403
|
||||
assert phone.post(local_path, json=pull, headers={**csrf, 'Origin': 'https://elsewhere.test'}).status_code == 403
|
||||
assert phone.post(local_path, json=pull, headers=csrf).json()['updated'] == [product['id']]
|
||||
assert phone.get(local_path).json()['products'][0]['fingerprint'] == server.get(remote_path).json()['products'][0]['fingerprint']
|
||||
|
||||
@@ -40,6 +40,18 @@ def test_per_project_retention_expires_only_older_automatic_results(cache):
|
||||
assert cache.store.project('project')['revision']==1
|
||||
|
||||
|
||||
def test_job_history_includes_updates_to_older_results(cache):
|
||||
old=job(cache)
|
||||
recent=job(cache)
|
||||
cursor=cache.store.job(recent)['updated']
|
||||
assert [value['id'] for value in cache.store.jobs('project', cursor)]==[recent]
|
||||
assert asyncio.run(cache.expire(old))
|
||||
delta=cache.store.jobs('project', cursor)
|
||||
assert [value['id'] for value in delta]==[recent,old]
|
||||
assert delta[1]['artifacts_expired']
|
||||
assert cache.store.project_revision('project')==1
|
||||
|
||||
|
||||
def test_backup_snapshot_keeps_live_artifacts_and_matching_expiry_flag(cache,tmp_path,monkeypatch):
|
||||
import sqlite3
|
||||
import zipfile
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
FROM debian:bookworm-slim AS native
|
||||
FROM debian:bookworm-slim@sha256:734a72b3d6142a71993b4bc580ca01d8ca687f77a2c422d96a961d3376b179bc AS native
|
||||
ARG BUILD_JOBS=6
|
||||
RUN test "${BUILD_JOBS}" -ge 1 && test "${BUILD_JOBS}" -le 6
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
|
||||
@@ -30,6 +30,22 @@ RUN node /scripts/build-setting-layout.mjs \
|
||||
&& node node_modules/typescript/bin/tsc --noEmit \
|
||||
&& node scripts/build-frontends.mjs
|
||||
|
||||
FROM node:22-bookworm-slim AS desktop-helper
|
||||
ENV UV_THREADPOOL_SIZE=1 GOMAXPROCS=2 NODE_OPTIONS="--v8-pool-size=1"
|
||||
WORKDIR /helper
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates zip \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
COPY desktop/bambu-login/package*.json ./
|
||||
RUN npm ci --ignore-scripts
|
||||
COPY desktop/bambu-login ./
|
||||
RUN npm run package -- --platform=linux --arch=x64 \
|
||||
&& npm run package -- --platform=win32 --arch=x64 \
|
||||
&& mkdir /downloads \
|
||||
&& cd dist \
|
||||
&& for package in WebSlicerBambuLogin-linux-x64 WebSlicerBambuLogin-win32-x64; do \
|
||||
zip -q -r "/downloads/${package}.zip" "${package}" || exit 1; \
|
||||
done
|
||||
|
||||
FROM nginx:stable-alpine AS static-base
|
||||
ARG SOURCE_URL
|
||||
ARG SOURCE_REVISION
|
||||
@@ -50,3 +66,4 @@ FROM static-base
|
||||
LABEL org.opencontainers.image.title="Web Slicer client"
|
||||
COPY web/deploy/nginx.conf /etc/nginx/conf.d/default.conf
|
||||
COPY --from=frontend /frontend/dist /usr/share/nginx/html
|
||||
COPY --from=desktop-helper /downloads /usr/share/nginx/html/bambu-login
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import {readFile} from 'node:fs/promises';
|
||||
import {resolve} from 'node:path';
|
||||
import {test,expect} from './fixtures';
|
||||
import {importModel,templateMachine,workspaceNav} from './workspaceFixture';
|
||||
|
||||
test.use({interfaceLanguage:'en'});
|
||||
|
||||
test('Print starts the cloud flow for the saved Bambu target',async({page},info)=>{
|
||||
test.skip(info.project.name!=='desktop');
|
||||
const machine=await templateMachine(page,'Bambu Lab P1S 0.4 nozzle',['Generic PLA']);
|
||||
const device='P1STEST123';
|
||||
const connected=await page.request.put('/api/v1/machines/'+machine.id+'/connection',{data:{
|
||||
revision:0,type:'bambu_lan',bambu_transport:'cloud',host:'http://bambu-cloud.invalid/',auth_type:'api_key',bambu_serial_number:device}});
|
||||
expect(connected.ok(),await connected.text()).toBe(true);
|
||||
const project=await importModel(page,'Bambu cloud cube.obj',await readFile(resolve('../../tests/data/20mm_cube.obj')),machine);
|
||||
const endpoint='/api/v1/projects/'+project.id;
|
||||
await page.route('**/api/v1/bambu-cloud',route=>route.fulfill({json:{available:true,logged_in:true,user_name:'Fixture'}}));
|
||||
await page.route('**/api/v1/bambu-cloud/printers',route=>route.fulfill({json:{cloud_connected:true,printers:[
|
||||
{dev_id:'OTHERDEVICE',name:'Other printer',online:true},{dev_id:device,name:'Chosen P1S',online:true}
|
||||
]}}));
|
||||
await page.route('**/api/v1/bambu-cloud/printers/'+device+'/print',route=>route.fulfill({json:{job:77}}));
|
||||
await page.route('**/api/v1/bambu-cloud/prints/77',route=>route.fulfill({json:{online:true,status:[],done:{rc:0}}}));
|
||||
await page.goto('/?project='+project.id);
|
||||
const queued=page.waitForResponse(response=>new URL(response.url()).pathname===endpoint+'/slice'&&response.status()===202);
|
||||
await page.getByRole('button',{name:'Slice model',exact:true}).click();
|
||||
const job=await (await queued).json();
|
||||
const preview=workspaceNav(page).getByRole('button',{name:'Preview',exact:true});
|
||||
await expect(preview).toBeEnabled({timeout:90000});
|
||||
await preview.click();
|
||||
const actions=page.getByRole('group',{name:'Print actions'});
|
||||
await actions.getByRole('button',{name:'Print',exact:true}).click();
|
||||
const print=page.getByRole('dialog',{name:'Print',exact:true});
|
||||
await expect(print).toBeVisible();
|
||||
await expect(print.getByText('Other printer',{exact:true})).toHaveCount(0);
|
||||
const sent=page.waitForRequest(request=>request.url().endsWith('/bambu-cloud/printers/'+device+'/print'));
|
||||
await print.getByRole('button',{name:'Start print',exact:true}).click();
|
||||
expect((await sent).postDataJSON()).toMatchObject({job_id:job.id,connection_revision:1});
|
||||
await expect(print.getByText('Sent to the printer.',{exact:true})).toBeVisible();
|
||||
});
|
||||
@@ -25,7 +25,7 @@ test('canceling project opening is silent and preserves the current draft in bot
|
||||
await page.getByRole('button',{name:'Recent projects',exact:true}).click();
|
||||
const recent=page.getByRole('dialog',{name:'Recent projects',exact:true});await recent.locator(`[data-recent-project="${ids[1]}"] > button`).first().click();
|
||||
await expect.poll(()=>rejected).toBe(2);await expect(recent).toBeVisible();await expect(recent.getByRole('alert')).toHaveCount(0);
|
||||
await recent.getByRole('button',{name:'Close history',exact:true}).click();await page.locator('.menu-close').click();
|
||||
await recent.getByRole('button',{name:'Close history',exact:true}).click();await page.locator('.menu-toggle[aria-expanded=true]').click();
|
||||
await nav.getByRole('button',{name:'Prepare',exact:true}).click();await openInspector(page);
|
||||
await expect(page.getByLabel('Position X',{exact:true})).toHaveValue('123.5');expect(opens).toBe(0);expect(new URL(page.url()).searchParams.get('project')).toBe(ids[0]);
|
||||
});
|
||||
|
||||
@@ -9,7 +9,8 @@ test('product library shares identity and creates independent compatible slicing
|
||||
const products=await(await page.request.get('/api/v1/filament-products?machine_id='+machine.id)).json();expect(products).toHaveLength(1);
|
||||
const original=await(await page.request.get('/api/v1/filament-products/'+products[0].id)).json();await page.goto('/');
|
||||
const recovery=page.getByRole('dialog',{name:'Recover autosave',exact:true});await page.addLocatorHandler(recovery,async()=>recovery.getByRole('button',{name:'Skip recovery',exact:true}).click());
|
||||
await page.getByRole('button',{name:'Application menu',exact:true}).click();await page.locator('#application-navigation').getByRole('button',{name:'Filament library',exact:true}).click();
|
||||
await page.locator('.workspace-modes:visible,.mobile-navigation:visible').getByRole('button',{name:'Filaments',exact:true}).click();
|
||||
await page.locator('.library-navigation').getByRole('button',{name:'Filament library',exact:true}).click();
|
||||
const library=page.getByRole('region',{name:'Filament library',exact:true});await expect(library).toBeVisible();
|
||||
await library.locator(`[data-product-id="${original.id}"]`).click();
|
||||
const details=library.getByRole('region',{name:'Filament details',exact:true});
|
||||
@@ -27,6 +28,7 @@ test('product library shares identity and creates independent compatible slicing
|
||||
await expect(profiles).toContainText('Fine PLA '+info.project.name);
|
||||
// New products do not require physical-spool IDs or an inventory service.
|
||||
await library.getByRole('button',{name:'Add filament',exact:true}).click();
|
||||
await page.getByRole('dialog',{name:'Choose filament preset'}).getByRole('button',{name:'Enter details manually'}).click();
|
||||
await details.getByLabel('Name',{exact:true}).fill('PETG '+info.project.name);
|
||||
await details.getByLabel('Material',{exact:true}).fill('PETG');
|
||||
await details.getByLabel('Manufacturer',{exact:true}).fill('My vendor');
|
||||
|
||||
@@ -102,10 +102,11 @@ test('opening standalone preview in another tab preserves the editor project and
|
||||
const original=await(await page.request.get(endpoint+'/download')).body();
|
||||
await page.goto('/?project='+project.id);
|
||||
await expect(page.getByRole('heading',{level:1,name:'preserved.obj',exact:true})).toBeVisible();
|
||||
await page.getByRole('button',{name:'Application menu',exact:true}).click();
|
||||
await page.locator('#application-navigation > .action-menu > summary').filter({hasText:'Preferences and help'}).click();
|
||||
await page.locator('.preferences-trigger').click();
|
||||
await page.locator('.preferences-dialog nav button').last().click();
|
||||
const opened=context.waitForEvent('page');
|
||||
await page.getByRole('link',{name:'Podgląd G-code',exact:true}).click();const viewer=await opened;
|
||||
await page.locator('.preferences-dialog>header button').click();
|
||||
await viewer.waitForLoadState();await open(viewer,'separate.gcode');
|
||||
await expect(viewer.getByLabel('Ostatni ruch',{exact:true})).toBeVisible();
|
||||
expect((await(await page.request.get(endpoint)).json()).revision).toBe(project.revision);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import {test,expect} from './fixtures';
|
||||
import {openModelFile,chooseTool,transformInput,searchSetting,visibleSettings,openMenuAction,closeAppMenu,openPrintResult} from './workspaceFixture';
|
||||
import {openModelFile,chooseTool,transformInput,searchSetting,visibleSettings,openMenuAction,openPrintResult} from './workspaceFixture';
|
||||
import {readFile} from 'node:fs/promises';
|
||||
import {resolve} from 'node:path';
|
||||
import {nativeCatalog} from './i18nFixture';
|
||||
@@ -8,15 +8,9 @@ import type {Option} from '../src/types';
|
||||
|
||||
test.use({interfaceLanguage:null,locale:'pl-PL'});
|
||||
const selector='.language-selector select';
|
||||
// The language selector is in the application menu's "Preferences and help" submenu; toHaveValue reads it hidden,
|
||||
// but choosing a language needs it shown.
|
||||
async function language(page:import('@playwright/test').Page){
|
||||
const select=page.locator(selector);
|
||||
if(!await select.isVisible()){
|
||||
const toggle=page.getByRole('button',{name:'Application menu',exact:true});
|
||||
if(await toggle.getAttribute('aria-expanded')!=='true')await toggle.click();
|
||||
if(!await select.isVisible())await page.locator('#application-navigation details.action-menu > summary').filter({hasText:/^(Preferences and help|Preferencje i pomoc|Einstellungen und Hilfe)/}).first().click();
|
||||
}
|
||||
if(!await select.isVisible())await page.locator('.preferences-trigger').click();
|
||||
return select;
|
||||
}
|
||||
|
||||
@@ -54,6 +48,7 @@ test('English default, original native translations, raw names and unsaved trans
|
||||
for(const id of ['pl','de']){
|
||||
const catalog=await nativeCatalog(id);
|
||||
await (await language(page)).selectOption(id);
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(page.locator(selector)).toHaveValue(id);
|
||||
await expect(field).toHaveAttribute('title',catalog.messages[schema.layer_height.tooltip]??schema.layer_height.tooltip);
|
||||
await expect(field).toContainText(catalog.messages[schema.layer_height.label]??schema.layer_height.label);
|
||||
@@ -68,7 +63,6 @@ test('English default, original native translations, raw names and unsaved trans
|
||||
await expect(page.locator(selector)).toHaveValue('en');
|
||||
await expect.poll(positionValue).toBe('123.456');
|
||||
await other.reload();await expect(other.locator(selector)).toHaveValue('en');
|
||||
await closeAppMenu(page);
|
||||
await openMenuAction(page,'Save as',/^(Project|Projekt)$/);
|
||||
const copy=page.getByRole('dialog',{name:/^Save as$/i});
|
||||
await expect(copy.getByRole('textbox')).toHaveValue('Drukarka.obj — copy');
|
||||
@@ -87,6 +81,7 @@ test('standalone viewer switches language while preserving original G-code and f
|
||||
await expect(page.locator('.gcode-source summary')).toBeVisible();
|
||||
await page.locator('.gcode-source summary').click();
|
||||
await (await language(page)).selectOption('pl');
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(page.getByRole('heading',{name:'Drukarka.gcode',exact:true})).toBeVisible();
|
||||
const id=new URL(page.url()).searchParams.get('gcode');
|
||||
expect(await(await page.request.get('/api/v1/gcode-files/'+id+'/download')).text()).toBe(code);
|
||||
|
||||
@@ -14,7 +14,7 @@ export const physicalOptions={interfaceLanguage:'en',configuredWorkspace:false,l
|
||||
export async function openPrinters(page:import('@playwright/test').Page){
|
||||
const recovery=page.getByRole('dialog',{name:'Recover autosave',exact:true});
|
||||
await page.addLocatorHandler(recovery,async()=>{await recovery.getByRole('button',{name:'Skip recovery',exact:true}).click();});
|
||||
await page.getByRole('button',{name:'Application menu',exact:true}).click();
|
||||
await page.locator('#application-navigation').getByRole('button',{name:'Printers',exact:true}).click();
|
||||
await page.locator('.workspace-modes:visible,.mobile-navigation:visible').getByRole('button',{name:'Printer',exact:true}).click();
|
||||
await page.locator('.library-navigation').getByRole('button',{name:'Printers',exact:true}).click();
|
||||
await page.removeLocatorHandler(recovery);
|
||||
}
|
||||
|
||||
@@ -33,8 +33,8 @@ test('the default view type opens the preview and dimming lower layers changes t
|
||||
await expect(page.getByLabel('Kolorowanie ścieżek',{exact:true})).toHaveValue('role');
|
||||
|
||||
// Toggle dimming in Preferences on the same page, so only the dimming differs between frames.
|
||||
await page.getByRole('button',{name:'Application menu',exact:true}).click();
|
||||
await page.locator('#application-navigation details.action-menu > summary').filter({hasText:'Preferences and help'}).first().click();
|
||||
await page.locator('.preferences-trigger').click();
|
||||
await page.locator('.preferences-dialog nav button').nth(1).click();
|
||||
const dim=page.getByRole('checkbox',{name:'Przyciemnij niższe warstwy',exact:true});
|
||||
await expect(dim).not.toBeChecked();
|
||||
const plain=await frame(page);
|
||||
|
||||
@@ -19,7 +19,7 @@ export async function chooseSliceResult(page: Page, jobId: string) {
|
||||
await navigation.locator('details.action-menu > summary').filter({hasText: /^(Jobs|Zadania)$/}).first().click();
|
||||
}
|
||||
await select.selectOption(jobId);
|
||||
const close = navigation.locator('.menu-close');
|
||||
const close = page.locator('.menu-toggle[aria-expanded=true]');
|
||||
if (await close.isVisible()) await close.click();
|
||||
await openPreview(page);
|
||||
}
|
||||
@@ -47,7 +47,7 @@ export async function projectMenuLink(page: Page, name: string) {
|
||||
|
||||
// Closes the application menu if it is open.
|
||||
export async function closeMenu(page: Page) {
|
||||
const close = page.locator('#application-navigation .menu-close');
|
||||
const close = page.locator('.menu-toggle[aria-expanded=true]');
|
||||
if (await close.isVisible()) await close.click();
|
||||
}
|
||||
|
||||
|
||||
@@ -36,8 +36,8 @@ test('project Printer and global Printers keep independent machine and preset co
|
||||
page.once('dialog',dialog=>dialog.dismiss());await nav.getByRole('button',{name:'Filaments',exact:true}).click();
|
||||
await expect(current.getByLabel('Print server address',{exact:true})).toHaveValue('http://unsaved.invalid');
|
||||
page.once('dialog',dialog=>dialog.accept());await current.getByRole('button',{name:'Printer preset',exact:true}).click();
|
||||
await page.getByRole('button',{name:'Application menu',exact:true}).click();
|
||||
await page.locator('#application-navigation').getByRole('button',{name:'Printers',exact:true}).click();
|
||||
await page.locator('.workspace-modes:visible,.mobile-navigation:visible').getByRole('button',{name:'Printer',exact:true}).click();
|
||||
await page.locator('.library-navigation').getByRole('button',{name:'Printers',exact:true}).click();
|
||||
const library=page.locator('.machine-library');await expect(library).toBeVisible();
|
||||
await library.locator('.machine-card').filter({hasText:b.name}).click();
|
||||
const process=b.profiles[0].presets.find(p=>p.id===b.profiles[0].default_process_id)!;
|
||||
@@ -71,8 +71,8 @@ test('project Printer and global Printers keep independent machine and preset co
|
||||
});
|
||||
await page.route('**/api/v1/printers/'+b.id+'/capabilities?*',route=>route.fulfill({json:{capabilities:{supports_status:true}}}));
|
||||
await page.route('**/api/v1/printers/'+b.id+'/status?*',route=>route.fulfill({json:{state:'printing',progress_percent:37,file_name:'test.gcode'}}));
|
||||
await page.getByRole('button',{name:'Application menu',exact:true}).click();
|
||||
await page.locator('#application-navigation').getByRole('button',{name:'Printers',exact:true}).click();
|
||||
await page.locator('.workspace-modes:visible,.mobile-navigation:visible').getByRole('button',{name:'Printer',exact:true}).click();
|
||||
await page.locator('.library-navigation').getByRole('button',{name:'Printers',exact:true}).click();
|
||||
const card=library.locator('.machine-card').filter({hasText:b.name});
|
||||
await expect(card).toContainText('Not checked');
|
||||
await library.getByRole('button',{name:'Refresh status',exact:true}).click();
|
||||
|
||||
@@ -21,14 +21,14 @@ export function workspaceTabs(page:Page){
|
||||
return page.locator('.workspace-modes:visible,.mobile-navigation:visible');
|
||||
}
|
||||
|
||||
// The Printers workspace (machine library) opens from the application menu.
|
||||
// The Printers workspace (machine library) opens inside the Printer workspace.
|
||||
export async function openPrinterLibrary(page:Page){
|
||||
const library=page.locator('.machine-library');
|
||||
await expect(async()=>{
|
||||
if(await library.isVisible())return;
|
||||
const toggle=page.getByRole('button',{name:/^(Application menu|Menu aplikacji)$/});
|
||||
if(await toggle.getAttribute('aria-expanded')!=='true')await toggle.click({timeout:5000});
|
||||
await page.locator('#application-navigation').getByRole('button',{name:/^(Printers|Drukarki)$/}).click({timeout:5000});
|
||||
const sections=page.locator('.library-navigation').getByRole('button',{name:/^(Printers|Drukarki)$/});
|
||||
if(!await sections.isVisible())await workspaceTabs(page).getByRole('button',{name:/^(Printer|Drukarka)$/}).click({timeout:5000});
|
||||
await sections.click({timeout:5000});
|
||||
await expect(library).toBeVisible({timeout:5000});
|
||||
}).toPass({timeout:60000});
|
||||
return library;
|
||||
|
||||
@@ -204,7 +204,7 @@ test('import, native profiles, WebGL model, slicing and preview', async ({page,
|
||||
color.forEach((channel, component) => expect(Math.abs(channel - range.colors[index][component])).toBeLessThanOrEqual(1));
|
||||
});
|
||||
}
|
||||
await expect(page.locator('.preview-controls:not(.move-controls)')).toContainText('Z 20.00 mm');
|
||||
await expect(page.locator('.preview-timeline .layer-limit')).toContainText('Z 20.00 mm');
|
||||
await expect(page.locator('.preview .scene canvas')).toBeVisible();
|
||||
await expect(page.getByRole('button', {name: 'Dodaj modele do projektu', exact: true})).toHaveCount(0);
|
||||
// The Toolpaths panel (path colouring) closes when the canvas is used; open it again.
|
||||
@@ -240,7 +240,8 @@ test('import, native profiles, WebGL model, slicing and preview', async ({page,
|
||||
await expect.poll(coloredPixels, {timeout: 30_000}).toBeGreaterThan(20);
|
||||
const canvasId = await page.locator('.preview .scene canvas').getAttribute('id');
|
||||
const firstLayer = page.getByLabel('Pierwsza warstwa', {exact: true});
|
||||
const lastLayer = page.getByLabel('Warstwa', {exact: true});
|
||||
const lastLayer = page.locator('.preview-timeline').getByLabel('Warstwa', {exact: true});
|
||||
await expect(lastLayer).toBeVisible();
|
||||
await expect(firstLayer).toHaveValue('0');
|
||||
const last = await lastLayer.inputValue();
|
||||
const fullPixels = await coloredPixels();
|
||||
@@ -327,7 +328,7 @@ test('import, native profiles, WebGL model, slicing and preview', async ({page,
|
||||
const finalStep = await lastMove.inputValue();
|
||||
await lastMove.focus(); await lastMove.press('Home');
|
||||
await expect(lastMove).toHaveValue('0');
|
||||
await expect(firstMove).toHaveValue('0');
|
||||
await expect(firstMove).toHaveCount(0);
|
||||
await expect.poll(coloredPixels, {timeout: 30_000}).toBeLessThan(fullPixels);
|
||||
await expect.poll(async () => {
|
||||
const text = await readout.textContent();
|
||||
@@ -350,11 +351,10 @@ test('import, native profiles, WebGL model, slicing and preview', async ({page,
|
||||
await timeSelector.selectOption('normal');
|
||||
}
|
||||
await page.getByLabel('Kolorowanie ścieżek').selectOption('role');
|
||||
await firstMove.focus(); await firstMove.press('End');
|
||||
await expect(firstMove).toHaveValue(finalStep);
|
||||
await lastMove.focus(); await lastMove.press('End');
|
||||
await expect(lastMove).toHaveValue(finalStep);
|
||||
await lastMove.focus(); await lastMove.press('Home');
|
||||
await expect(firstMove).toHaveValue('0');
|
||||
await expect(firstMove).toHaveCount(0);
|
||||
await page.getByRole('button', {name: 'Wszystkie ruchy', exact: true}).click();
|
||||
await expect(lastMove).toHaveValue(finalStep);
|
||||
await expect.poll(coloredPixels, {timeout: 30_000}).toBeGreaterThan(20);
|
||||
@@ -362,7 +362,7 @@ test('import, native profiles, WebGL model, slicing and preview', async ({page,
|
||||
await page.getByRole('button', {name: 'Tylko ta warstwa', exact: true}).click();
|
||||
await expect(firstLayer).toHaveValue(last);
|
||||
await expect.poll(async () => Number(await lastMove.inputValue())).toBeGreaterThan(0);
|
||||
await expect(firstMove).toHaveValue('0');
|
||||
await expect(firstMove).toHaveCount(0);
|
||||
await expect.poll(coloredPixels, {timeout: 30_000}).toBeLessThan(fullPixels);
|
||||
await page.getByRole('button', {name: 'Cały wydruk', exact: true}).click();
|
||||
await expect(firstLayer).toHaveValue('0');
|
||||
@@ -438,7 +438,7 @@ test('import, native profiles, WebGL model, slicing and preview', async ({page,
|
||||
await outerWall.check();
|
||||
const outerRole = metadata.header.roles.indexOf('Outer wall');
|
||||
await expect.poll(async () => shownTiming(await page.getByLabel(/^Czas: (Outer wall|Zewnętrzna ściana)$/).textContent() ?? '')).toBe(roleTimingText(outerRole));
|
||||
await expect(firstMove).toHaveValue('0');
|
||||
await expect(firstMove).toHaveCount(0);
|
||||
await expect(lastMove).toHaveValue(finalStep);
|
||||
await page.getByLabel('Ruchy jałowe', {exact: true}).check();
|
||||
await page.getByLabel('Wytarcie dyszy', {exact: true}).check();
|
||||
|
||||
@@ -80,15 +80,15 @@ test('three real prepared models and native toolpaths work without any server AP
|
||||
await expect(wall).toHaveValue(String(Number(original)+1));
|
||||
expect(await hashes()).toEqual(before);
|
||||
await page.screenshot({path:testInfo.outputPath('local-settings.png')});
|
||||
await page.getByRole('button',{name:'Application menu',exact:true}).click();
|
||||
await page.getByText('Preferences and help',{exact:true}).click();
|
||||
await page.getByRole('button',{name:'About Web Slicer',exact:true}).click();
|
||||
const about=page.getByRole('dialog',{name:'About Web Slicer'});
|
||||
await page.locator('.preferences-trigger').click();
|
||||
await page.locator('.preferences-dialog nav button').last().click();
|
||||
await page.locator('.help-about > summary').click();
|
||||
const about=page.getByRole('region',{name:'About Web Slicer'});
|
||||
await about.locator('summary').filter({hasText:'Models and licenses'}).click();
|
||||
const credits=about.locator('.demo-model-credits');
|
||||
await expect(credits.getByRole('link',{name:'Editable source',exact:true})).toHaveCount(3);
|
||||
await expect(credits.getByRole('link',{name:'License',exact:true})).toHaveCount(3);
|
||||
await about.getByRole('button',{name:'Close',exact:true}).click();
|
||||
await page.locator('.preferences-dialog>header button').click();
|
||||
await expect(page.getByRole('button',{name:/^Slice|^Potnij/})).toHaveCount(0);
|
||||
await expect(page.locator('input[type=file]:not(:disabled)')).toHaveCount(0);
|
||||
for(const path of ['/api/v1/projects/new','/api/v1/projects/demo-gear/slice','/api/v1/imports','/api/v1/printers/demo/commands']){
|
||||
|
||||
@@ -120,14 +120,14 @@ export async function runThreeMFScenario(page:Page,info:{project:{name:string};o
|
||||
expect(added.state.machine_binding).toEqual(geometry.state.machine_binding);
|
||||
expect(added.state.objects.length).toBeGreaterThan(geometry.state.objects.length);
|
||||
expect((await page.request.post(`/api/v1/projects/${added.id}/save`,{data:{revision:added.revision}})).status()).toBe(200);
|
||||
await page.getByRole('button',{name:'Application menu',exact:true}).click();
|
||||
await page.getByLabel('Preferences and help',{exact:true}).click();
|
||||
await page.locator('.preferences-trigger').click();
|
||||
const preferences=page.locator('.three-mf-preferences');
|
||||
await expect(preferences.getByLabel('Default import mode',{exact:true})).toHaveValue('geometry');
|
||||
await expect(preferences.getByLabel('Ask at every 3MF import',{exact:true})).not.toBeChecked();
|
||||
await preferences.getByLabel('Ask at every 3MF import',{exact:true}).check();
|
||||
await preferences.getByRole('button',{name:'Save',exact:true}).click();await expect(preferences.getByRole('status')).toHaveText('Saved');
|
||||
expect((await(await page.request.get('/api/v1/preferences/imports')).json()).ask).toBe(true);
|
||||
await page.keyboard.press('Escape');
|
||||
// The ZIP selector must feed the same policy, including a 3MF which is not
|
||||
// the first model. A lost admission reply must replay the captured intent.
|
||||
const zip=execFileSync('python3',['-c',
|
||||
|
||||
@@ -14,7 +14,9 @@ async function archive(download:Download){
|
||||
|
||||
test('troubleshooting shows server and browser information, copies hidden details, exports profiles and persists severity',async({page})=>{
|
||||
await page.goto('/');
|
||||
await openMenuAction(page,'Centrum diagnostyki',/^(Preferences and help|Preferencje i pomoc)$/);
|
||||
if(!await page.locator('.preferences-dialog').isVisible())await page.locator('.preferences-trigger').click();
|
||||
await page.locator('.preferences-dialog nav button').last().click();
|
||||
await page.getByRole('button',{name:'Centrum diagnostyki',exact:true}).click();
|
||||
const dialog=page.getByRole('dialog',{name:'Centrum diagnostyki',exact:true});
|
||||
await expect(dialog.getByRole('button',{name:'Eksportuj przegląd profili',exact:true})).toBeEnabled();
|
||||
await expect(dialog.getByLabel('Informacje serwera i klienta')).toContainText('user_agent');
|
||||
@@ -45,7 +47,9 @@ test('troubleshooting shows server and browser information, copies hidden detail
|
||||
expect(exported.printers.system).toBe(copied.profiles.printers.system);
|
||||
expect(exported.printers.presets.length).toBe(exported.printers.system+exported.printers.user);
|
||||
await dialog.getByRole('button',{name:'Zamknij diagnostykę',exact:true}).click();
|
||||
await openMenuAction(page,'Centrum diagnostyki',/^(Preferences and help|Preferencje i pomoc)$/);
|
||||
if(!await page.locator('.preferences-dialog').isVisible())await page.locator('.preferences-trigger').click();
|
||||
await page.locator('.preferences-dialog nav button').last().click();
|
||||
await page.getByRole('button',{name:'Centrum diagnostyki',exact:true}).click();
|
||||
await expect(dialog.getByLabel('Poziom logowania',{exact:true})).toHaveValue('trace');
|
||||
});
|
||||
|
||||
@@ -63,7 +67,9 @@ test('diagnostic archives include the saved native 3mf checkpoint and all-logs m
|
||||
expect(changed.ok()).toBe(true);const current=await changed.json();
|
||||
await page.reload();
|
||||
await expect(page.getByRole('heading',{level:1,name:'20mm_cube.obj',exact:true})).toBeVisible();
|
||||
await openMenuAction(page,'Centrum diagnostyki',/^(Preferences and help|Preferencje i pomoc)$/);
|
||||
if(!await page.locator('.preferences-dialog').isVisible())await page.locator('.preferences-trigger').click();
|
||||
await page.locator('.preferences-dialog nav button').last().click();
|
||||
await page.getByRole('button',{name:'Centrum diagnostyki',exact:true}).click();
|
||||
const dialog=page.getByRole('dialog',{name:'Centrum diagnostyki',exact:true});
|
||||
const include=dialog.getByRole('checkbox',{name:`Dołącz ostatni ręczny zapis projektu · wersja ${first.revision}`,exact:true});
|
||||
await expect(include).toBeEnabled();await include.check();
|
||||
|
||||
@@ -67,9 +67,7 @@ test('menus expose native tools, printer configuration and persistent light them
|
||||
await workspaces(page).getByRole('button',{name:'Printer',exact:true}).click();
|
||||
await expect(workspaces(page).getByRole('button',{name:'Printer',exact:true})).toHaveAttribute('aria-pressed','true');
|
||||
await workspaces(page).getByRole('button',{name:'Prepare',exact:true}).click();
|
||||
await page.getByRole('button',{name:'Application menu',exact:true}).click();
|
||||
const menu=page.getByRole('navigation',{name:'Application navigation',exact:true});
|
||||
await menu.locator('summary').filter({hasText:'Preferences and help'}).click();
|
||||
await page.locator('.preferences-trigger').click();
|
||||
await expect(page.getByLabel('Theme',{exact:true})).toBeVisible({timeout:5000});
|
||||
await page.getByLabel('Theme',{exact:true}).selectOption('light');
|
||||
await expect(page.locator('html')).toHaveAttribute('data-theme','light');
|
||||
@@ -199,12 +197,14 @@ test('project menus save independent copies and clipboard remains reachable by t
|
||||
await menu.locator(':scope > .action-menu > summary').filter({hasText:/^Project$/}).click();
|
||||
const saved=page.waitForResponse(response=>response.url().endsWith('/save')&&response.request().method()==='POST');
|
||||
await menu.getByRole('button',{name:'Save project',exact:true}).click();expect((await saved).status()).toBe(200);
|
||||
await page.getByRole('button',{name:'Application menu',exact:true}).click();
|
||||
await menu.locator(':scope > .action-menu > summary').filter({hasText:/^Project$/}).click();
|
||||
await menu.getByRole('button',{name:'Save as',exact:true}).click();
|
||||
const dialog=page.getByRole('dialog',{name:'Save as',exact:true});
|
||||
await dialog.getByLabel('Project name',{exact:true}).fill('Independent GUI copy');
|
||||
await dialog.getByRole('button',{name:'Save copy',exact:true}).click();
|
||||
await expect(page.getByRole('heading',{level:1,name:'Independent GUI copy',exact:true})).toBeVisible();
|
||||
await menu.getByRole('button',{name:'Close',exact:true}).click();
|
||||
await expect(menu).not.toBeVisible();
|
||||
expect(page.url()).not.toBe(originalUrl);
|
||||
const id=new URL(page.url()).searchParams.get('project');
|
||||
await objectSection(page,/^(Clipboard|Schowek)$/);
|
||||
|
||||
@@ -1,14 +1,19 @@
|
||||
import {selectTool} from './selectTool';
|
||||
import {test,expect} from './fixtures';
|
||||
import {readFile} from 'node:fs/promises';
|
||||
import type {JSHandle} from '@playwright/test';
|
||||
import {resolve} from 'node:path';
|
||||
import {uploadProject} from './workspaceFixture';
|
||||
import {patchProfiles,uploadProject} from './workspaceFixture';
|
||||
|
||||
test.use({interfaceLanguage:'en',actionTimeout:15000});
|
||||
test('responsive workspaces match the desktop, tablet and phone layouts',async({page},info)=>{
|
||||
test.skip(info.project.name!=='desktop');
|
||||
const response=await uploadProject(page,{name:'Layout cube.obj',mimeType:'text/plain',buffer:await readFile(resolve('../../tests/data/20mm_cube.obj'))});
|
||||
expect(response.status()).toBe(201);const project=await response.json();await page.goto('/?project='+project.id);
|
||||
expect(response.status()).toBe(201);const project=await response.json();
|
||||
const profiles=await patchProfiles(page,'/api/v1/projects/'+project.id,{revision:project.revision,
|
||||
printer:'Bambu Lab A1 0.4 nozzle',process:'0.20mm Standard @BBL A1',filaments:['Generic PLA @BBL A1']});
|
||||
expect(profiles.status(),await profiles.text()).toBe(200);
|
||||
await page.goto('/?project='+project.id);
|
||||
await expect(page.locator('.scene')).toHaveAttribute('aria-busy','false');
|
||||
await page.evaluate(()=>document.fonts.ready);
|
||||
for(const width of [1440,1024,390,320]){
|
||||
@@ -16,6 +21,20 @@ test('responsive workspaces match the desktop, tablet and phone layouts',async({
|
||||
const nav=page.locator(width<=700?'.mobile-navigation':'.workspace-modes');
|
||||
await nav.getByRole('button',{name:'Prepare',exact:true}).click();
|
||||
await expect(page.locator('.workbench-tools')).toHaveCount(0);
|
||||
if(width===1024){
|
||||
const toolbar=await page.locator('.viewport-tool-bar').boundingBox();
|
||||
const cube=await page.locator('.view-cube').boundingBox();
|
||||
expect(toolbar!.x+toolbar!.width).toBeLessThanOrEqual(cube!.x);
|
||||
const importAction=await page.locator('.viewport-import-action').boundingBox();
|
||||
if(importAction)expect(toolbar!.y).toBeGreaterThanOrEqual(importAction.y+importAction.height);
|
||||
}
|
||||
if(width<=700){
|
||||
const printSettings=nav.getByRole('button',{name:'Print settings',exact:true});
|
||||
await expect(printSettings).toHaveText('Print settings');
|
||||
const filament=await nav.getByRole('button',{name:'Filaments',exact:true}).locator('svg').boundingBox();
|
||||
expect(filament!.width).toBeGreaterThanOrEqual(22);
|
||||
expect((await nav.boundingBox())!.height).toBeLessThanOrEqual(73);
|
||||
}
|
||||
// Phones keep the camera actions behind the dock's View button.
|
||||
const view=page.locator('.dock-extra').getByRole('button',{name:'View',exact:true});
|
||||
// A tool left open at a wider size is a sheet over the dock on a phone; close it first.
|
||||
@@ -38,10 +57,12 @@ test('responsive workspaces match the desktop, tablet and phone layouts',async({
|
||||
}
|
||||
}
|
||||
await page.setViewportSize({width:1440,height:960});await page.locator('.workspace-modes').getByRole('button',{name:'Prepare',exact:true}).click();
|
||||
await page.getByRole('button',{name:'Application menu',exact:true}).click();
|
||||
await page.locator('#application-navigation > .action-menu > summary').filter({hasText:'Preferences and help'}).click();
|
||||
await page.locator('.preferences-trigger').click();
|
||||
await page.getByLabel('Theme',{exact:true}).selectOption('light');
|
||||
await page.locator('.menu-close').click();
|
||||
await page.locator('.preferences-dialog').getByRole('button',{name:'Close',exact:true}).click();
|
||||
await page.getByRole('button',{name:'Application menu',exact:true}).click();
|
||||
await page.getByRole('button',{name:'Application menu',exact:true}).click();
|
||||
await expect(page.locator('#application-navigation[data-open=true]')).toHaveCount(0);
|
||||
await expect(page.locator('html')).toHaveAttribute('data-theme','light');
|
||||
await expect(page.locator('.camera-rail .native-icon .icon-light').first()).toBeVisible();
|
||||
await page.screenshot({path:info.outputPath('orca-v2-layout-light.png')});
|
||||
@@ -65,3 +86,131 @@ test('Project creates a plate once and opens its own scene',async({page},info)=>
|
||||
// The Prepare footer names the active plate.
|
||||
await expect(page.getByRole('contentinfo')).toContainText('2');
|
||||
});
|
||||
|
||||
test('double tap and vertical drag zooms the touch canvas',async({page},info)=>{
|
||||
test.skip(info.project.name!=='mobile'||info.project.use.browserName!=='chromium');
|
||||
const response=await uploadProject(page,{name:'Zoom cube.obj',mimeType:'text/plain',buffer:await readFile(resolve('../../tests/data/20mm_cube.obj'))});
|
||||
expect(response.status()).toBe(201);
|
||||
const project=await response.json();
|
||||
await page.goto('/?project='+project.id);
|
||||
const scene=page.locator('.workbench-canvas .scene');
|
||||
await expect(scene).toHaveAttribute('aria-busy','false');
|
||||
const canvas=scene.locator('canvas').first();
|
||||
const bounds=(await canvas.boundingBox())!;
|
||||
const x=Math.round(bounds.x+bounds.width*.75);
|
||||
const y=Math.round(bounds.y+bounds.height*.55);
|
||||
const client=await page.context().newCDPSession(page);
|
||||
const gesture=async(dy:number)=>{
|
||||
await client.send('Input.dispatchTouchEvent',{type:'touchStart',touchPoints:[{x,y}]});
|
||||
await client.send('Input.dispatchTouchEvent',{type:'touchEnd',touchPoints:[]});
|
||||
await client.send('Input.dispatchTouchEvent',{type:'touchStart',touchPoints:[{x,y}]});
|
||||
await client.send('Input.dispatchTouchEvent',{type:'touchMove',touchPoints:[{x,y:y+dy}]});
|
||||
await client.send('Input.dispatchTouchEvent',{type:'touchEnd',touchPoints:[]});
|
||||
};
|
||||
const before=await canvas.screenshot();
|
||||
await gesture(-90);
|
||||
const zoomed=await canvas.screenshot();
|
||||
expect(zoomed.equals(before)).toBe(false);
|
||||
await gesture(90);
|
||||
expect((await canvas.screenshot()).equals(zoomed)).toBe(false);
|
||||
});
|
||||
|
||||
test('successive slices replace the preview and retain job history',async({page},info)=>{
|
||||
test.skip(info.project.name!=='mobile');
|
||||
const response=await uploadProject(page,{name:'Repeated cube.obj',mimeType:'text/plain',buffer:await readFile(resolve('../../tests/data/20mm_cube.obj'))});
|
||||
expect(response.status()).toBe(201);
|
||||
const project=await response.json();
|
||||
const endpoint='/api/v1/projects/'+project.id;
|
||||
const profiles=await patchProfiles(page,endpoint,{revision:project.revision,
|
||||
printer:'Bambu Lab A1 0.4 nozzle',process:'0.20mm Standard @BBL A1',filaments:['Generic PLA @BBL A1']});
|
||||
expect(profiles.status(),await profiles.text()).toBe(200);
|
||||
await page.goto('/?project='+project.id);
|
||||
const nav=page.locator('.mobile-navigation');
|
||||
const completed:string[]=[];
|
||||
const measurements:{slice:number;preview:number}[]=[];
|
||||
let previousContext:JSHandle<WebGL2RenderingContext|null>|undefined;
|
||||
for(let attempt=0;attempt<5;attempt++){
|
||||
await nav.getByRole('button',{name:'Prepare',exact:true}).click();
|
||||
if(previousContext){
|
||||
const context=previousContext;
|
||||
await expect.poll(()=>context.evaluate(gl=>gl?.isContextLost())).toBe(true);
|
||||
await context.dispose();
|
||||
}
|
||||
const queued=page.waitForResponse(result=>new URL(result.url()).pathname===endpoint+'/slice'&&result.status()===202);
|
||||
const start=Date.now();
|
||||
await page.getByRole('button',{name:'Slice model',exact:true}).click();
|
||||
const job=await (await queued).json();
|
||||
completed.push(job.id);
|
||||
await expect.poll(async()=>(await(await page.request.get('/api/v1/jobs/'+job.id)).json()).status,
|
||||
{timeout:45000,intervals:[100,200,300]}).toBe('completed');
|
||||
const sliced=Date.now();
|
||||
await nav.getByRole('button',{name:'Preview',exact:true}).click();
|
||||
await expect(page.locator('.preview .scene')).toHaveAttribute('aria-busy','false');
|
||||
await expect(page.locator('.preview-timeline input[type=range]').last()).not.toBeDisabled();
|
||||
measurements.push({slice:sliced-start,preview:Date.now()-sliced});
|
||||
previousContext=await page.locator('.preview .scene canvas').first()
|
||||
.evaluateHandle(canvas=>(canvas as HTMLCanvasElement).getContext('webgl2'));
|
||||
}
|
||||
await previousContext?.dispose();
|
||||
console.log('Mobile repeat, milliseconds:',JSON.stringify(measurements));
|
||||
const history=await (await page.request.get(endpoint+'/jobs')).json();
|
||||
expect(history.map((value:{id:string})=>value.id)).toEqual(completed.reverse());
|
||||
const delta=await (await page.request.get(endpoint+'/jobs',{params:{updated_after:history[0].updated}})).json();
|
||||
expect(delta.map((value:{id:string})=>value.id)).toEqual([history[0].id]);
|
||||
});
|
||||
|
||||
test('printer and filament libraries live within the workspace tabs',async({page},info)=>{
|
||||
await page.route('**/api/v1/bambu-cloud',route=>route.fulfill({json:{available:true,logged_in:false}}));
|
||||
await page.goto('/');
|
||||
const nav=page.locator(info.project.name==='mobile'?'.mobile-navigation':'.workspace-modes');
|
||||
const sections=page.locator('.library-navigation');
|
||||
await nav.getByRole('button',{name:'Printer',exact:true}).click();
|
||||
await sections.getByRole('button',{name:'Printers',exact:true}).click();
|
||||
await expect(nav.getByRole('button',{name:'Printer',exact:true})).toHaveAttribute('aria-pressed','true');
|
||||
const cloud=page.getByRole('region',{name:'Bambu Lab account',exact:true});
|
||||
await expect(cloud.getByRole('button',{name:'Sign in',exact:true})).toBeVisible();
|
||||
await page.getByRole('button',{name:'Add printer',exact:true}).first().click();
|
||||
const picker=page.locator('.machine-wizard .printer-library');
|
||||
for(const query of ['bambu p1',' P1 BAMBU ']){
|
||||
await picker.getByRole('searchbox').fill(query);
|
||||
await expect(picker.getByRole('heading',{name:/Bambu Lab P1/}).first()).toBeVisible();
|
||||
}
|
||||
await picker.getByRole('searchbox').fill('bambu voron');
|
||||
await expect(picker.getByRole('heading',{name:/Bambu Lab P1/})).toHaveCount(0);
|
||||
await page.locator('.machine-wizard').getByRole('button',{name:'Cancel'}).click();
|
||||
await nav.getByRole('button',{name:'Filaments',exact:true}).click();
|
||||
await sections.getByRole('button',{name:'Filament library',exact:true}).click();
|
||||
await expect(page.getByRole('region',{name:'Filament library',exact:true})).toBeVisible();
|
||||
await expect(nav.getByRole('button',{name:'Filaments',exact:true})).toHaveAttribute('aria-pressed','true');
|
||||
const menu=page.locator('.menu-toggle');
|
||||
await menu.click();
|
||||
const drawer=page.locator('#application-navigation');
|
||||
const project=drawer.locator(':scope > details').filter({has:page.getByText('Project',{exact:true})}).first();
|
||||
await project.locator(':scope > summary').click();
|
||||
const handy=project.getByText('Add Handy models',{exact:true}).locator('..');
|
||||
const open=project.getByRole('button',{name:'Open model or project',exact:true});
|
||||
const heading=(await project.locator(':scope > summary').boundingBox())!;
|
||||
const child=(await open.boundingBox())!;
|
||||
expect((await handy.boundingBox())!.height).toBe(child.height);
|
||||
expect(child.height).toBeLessThan(heading.height);
|
||||
expect(child.x).toBeGreaterThan(heading.x);
|
||||
await menu.click();
|
||||
await expect(project).not.toHaveAttribute('open','');
|
||||
await page.locator('.preferences-trigger').click();
|
||||
const preferences=page.locator('.preferences-dialog');
|
||||
await expect(preferences).toBeVisible();
|
||||
await expect(preferences.getByLabel('Theme',{exact:true})).toBeVisible();
|
||||
await preferences.getByRole('button',{name:'Controls and preview',exact:true}).click();
|
||||
await expect(preferences.getByLabel('Camera style',{exact:true})).toBeVisible();
|
||||
await preferences.getByRole('button',{name:'Help and support',exact:true}).click();
|
||||
await expect(preferences.getByRole('region',{name:'Documentation',exact:true})).toBeVisible();
|
||||
await expect(preferences.getByRole('searchbox',{name:'Search help topics'})).toBeVisible();
|
||||
await expect(preferences.locator('.help-tips article')).toBeVisible();
|
||||
await preferences.getByRole('button',{name:'Next',exact:true}).click();
|
||||
await expect(preferences.locator('.help-tip-nav [role=status]')).toContainText('2 /');
|
||||
await preferences.locator('.help-about > summary').click();
|
||||
await expect(preferences.getByRole('region',{name:'About Web Slicer',exact:true})).toBeVisible();
|
||||
await expect(page.locator('dialog[open]')).toHaveCount(1);
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(preferences).not.toBeVisible();
|
||||
});
|
||||
|
||||
@@ -189,20 +189,20 @@ export function workspaceNav(page: Page) {
|
||||
return page.locator('nav.workspace-modes, nav.mobile-navigation').filter({visible: true}).first();
|
||||
}
|
||||
// Opens the application menu and waits until it is really shown: its state can say "open" while the panel
|
||||
// is still hidden (e.g. right after a modal dialog closed), so reopen it when its Close button is not visible.
|
||||
// is still hidden (e.g. right after a modal dialog closed), so reopen it when the navigation drawer is not visible.
|
||||
export async function ensureMenuOpen(page: Page) {
|
||||
menuGeneration.set(page, (menuGeneration.get(page) ?? 0) + 1);
|
||||
const toggle = page.getByRole('button', {name: 'Application menu', exact: true});
|
||||
const close = page.locator('#application-navigation button.menu-close');
|
||||
const drawer = page.locator('#application-navigation[data-open=true]');
|
||||
if (await toggle.getAttribute('aria-expanded') !== 'true') await toggle.click();
|
||||
await settledMenu(page);
|
||||
if (!await close.isVisible()) {
|
||||
if (!await drawer.isVisible()) {
|
||||
await page.keyboard.press('Escape');
|
||||
if (await toggle.getAttribute('aria-expanded') === 'true') await toggle.click({force: true}).catch(() => undefined);
|
||||
if (await toggle.getAttribute('aria-expanded') !== 'true') await toggle.click();
|
||||
await settledMenu(page);
|
||||
}
|
||||
await expect(close).toBeVisible();
|
||||
await expect(drawer).toBeVisible();
|
||||
}
|
||||
// Pages whose application menu a helper is using right now; the deferred close below leaves them alone.
|
||||
const menuInUse = new WeakMap<Page, number>();
|
||||
@@ -713,12 +713,7 @@ export async function plateSelect(page: Page) {
|
||||
export async function closeAppMenu(page: Page) {
|
||||
const toggle = page.getByRole('button', {name: 'Application menu', exact: true});
|
||||
if (await toggle.getAttribute('aria-expanded') !== 'true') return;
|
||||
const close = page.locator('#application-navigation').getByRole('button', {name: /^(Zamknij|Close)$/}).first();
|
||||
// The menu may be closing by itself (data-close-navigation actions); never wait long on its Close button.
|
||||
const closed = async () => await toggle.getAttribute('aria-expanded') !== 'true';
|
||||
if (!await closed()) await close.click({timeout: 3000}).catch(() => undefined);
|
||||
if (!await closed()) await page.locator('.app-menu-backdrop').click({force: true, timeout: 3000}).catch(() => undefined);
|
||||
if (!await closed()) await page.keyboard.press('Escape');
|
||||
await toggle.click();
|
||||
await expect(toggle).toHaveAttribute('aria-expanded', 'false');
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
*.zip
|
||||
@@ -21,11 +21,11 @@ interface Information {
|
||||
interface License {id:string;source:string;url:string}
|
||||
const external=(url:string,label:string)=>/^https?:\/\//i.test(url)?<a href={url} target="_blank" rel="noopener noreferrer">{label}</a>:label;
|
||||
|
||||
export function AboutDialog({close}:{close:()=>void}){
|
||||
const dialog=useRef<HTMLDialogElement>(null),viewer=useRef<HTMLElement>(null),licenseRequest=useRef<AbortController|null>(null);
|
||||
export function AboutInformation(){
|
||||
const viewer=useRef<HTMLElement>(null),licenseRequest=useRef<AbortController|null>(null);
|
||||
const [info,setInfo]=useState<Information|null>(null),[reload,setReload]=useState(0),[loading,setLoading]=useState(true),[error,setError]=useState<unknown>(null);
|
||||
const [query,setQuery]=useState(''),[license,setLicense]=useState<License|null>(null),[text,setText]=useState(''),[reading,setReading]=useState(false),[licenseError,setLicenseError]=useState<unknown>(null);
|
||||
useEffect(()=>{dialog.current?.showModal();return()=>licenseRequest.current?.abort();},[]);
|
||||
useEffect(()=>()=>licenseRequest.current?.abort(),[]);
|
||||
useEffect(()=>{
|
||||
const abort=new AbortController();setLoading(true);setError(null);licenseRequest.current?.abort();setLicense(null);setReading(false);
|
||||
void api<Information>('/application-info',{signal:abort.signal}).then(value=>{
|
||||
@@ -58,8 +58,7 @@ export function AboutDialog({close}:{close:()=>void}){
|
||||
</li>);
|
||||
const used=new Set([info?.upstream.license_id,...browser.components.flatMap(value=>value.license_ids),...(info?.installed_python_distributions??[]).flatMap(value=>value.license_ids)]);
|
||||
const remaining=notices.filter(value=>!used.has(value.id)&&matches(value.source));
|
||||
return <dialog ref={dialog} className="about-dialog" aria-label={t('About Web Slicer')} onCancel={event=>{event.preventDefault();close();}}>
|
||||
<header><h2>{t('About Web Slicer')}</h2><button onClick={close}>{t('Close')}</button></header>
|
||||
return <section className="about-information" aria-label={t('About Web Slicer')}>
|
||||
<p>Web Slicer{' · '}{browser.version}</p>
|
||||
{import.meta.env.VITE_SOURCE_URL&&<p>{external(import.meta.env.VITE_SOURCE_URL,t('Fork source code'))}</p>}
|
||||
{loading&&<p role="status">{t('Loading…')}</p>}{error!=null&&<ErrorNotice error={error} onDismiss={()=>setError(null)}/>}
|
||||
@@ -93,5 +92,5 @@ export function AboutDialog({close}:{close:()=>void}){
|
||||
{!!remaining.length&&<><h3>{t('License notices')}</h3><ul aria-label={t('License notices')}>{remaining.map(value=><li key={value.id}>{readButton(value)}</li>)}</ul></>}
|
||||
</>}
|
||||
</details>
|
||||
</dialog>;
|
||||
</section>;
|
||||
}
|
||||
@@ -1,13 +1,15 @@
|
||||
import {useCallback,useEffect,useRef,useState} from 'react';
|
||||
import {api,jsonRequest} from './api';
|
||||
import {api,apiUrl,jsonRequest} from './api';
|
||||
import {ErrorNotice} from './ErrorNotice';
|
||||
import {FileInput} from './FileInput';
|
||||
import {t,useLanguage} from './i18n';
|
||||
import type {AccountPrinter} from './BambuCloudConnection';
|
||||
import type {Job} from './types';
|
||||
|
||||
export interface BambuCloudState {available:boolean;plugin_version?:string;logged_in?:boolean;user_id?:string;user_name?:string;cloud_connected?:boolean;printing?:boolean}
|
||||
export interface BambuPresetSyncState {enabled:boolean;running?:boolean;last_sync?:number;failed?:boolean;conflicts?:number;catalog_changed_at?:number|null}
|
||||
export interface BambuCloudState {preset_sync?:BambuPresetSyncState;personal_account?:boolean;available:boolean;plugin_version?:string;logged_in?:boolean;user_id?:string;user_name?:string;cloud_connected?:boolean;printing?:boolean}
|
||||
interface PrinterStatus {gcode_state?:string;mc_percent?:number;mc_remaining_time?:number;subtask_name?:string;nozzle_temper?:number;bed_temper?:number;print_error?:number;updated?:number;authorization_control?:boolean|null}
|
||||
interface CloudPrinter {dev_id:string;name:string;model?:string|null;online:boolean;print_status?:string|null;status:PrinterStatus|null}
|
||||
interface CloudPrinter extends AccountPrinter {print_status?:string|null;status:PrinterStatus|null}
|
||||
interface CloudPrint {status:{status:number;stage:string;code:number;msg:string}[];done:{rc:number;cancelled:boolean}|null;reason:'authorization_control'|'task_rejected'|'error'|null}
|
||||
|
||||
// The Bambu sign-in page hands the session only to a native WebView bridge, so
|
||||
@@ -80,16 +82,43 @@ function SlicerKeySection() {
|
||||
</details>;
|
||||
}
|
||||
|
||||
export function BambuCloudAccount({close,state,changed,job}:{close:()=>void;state:BambuCloudState;changed:(value:BambuCloudState)=>void;job:Job|null}) {
|
||||
const desktopPackages=[
|
||||
{label:'Linux x64',url:import.meta.env.BASE_URL+'bambu-login/WebSlicerBambuLogin-linux-x64.zip'},
|
||||
{label:'Windows x64',url:import.meta.env.BASE_URL+'bambu-login/WebSlicerBambuLogin-win32-x64.zip'},
|
||||
];
|
||||
|
||||
function DesktopHelperDownloads(){
|
||||
const [available,setAvailable]=useState<typeof desktopPackages|null>(null);
|
||||
useEffect(()=>{
|
||||
const controller=new AbortController();
|
||||
void Promise.all(desktopPackages.map(async item=>{
|
||||
try{
|
||||
const response=await fetch(item.url,{method:'HEAD',signal:controller.signal});
|
||||
const type=response.headers.get('content-type')?.toLowerCase();
|
||||
return response.ok&&(type?.includes('zip')||type?.includes('octet-stream'))?item:null;
|
||||
}catch{return null;}
|
||||
})).then(values=>{if(!controller.signal.aborted)setAvailable(values.filter(item=>item!==null));});
|
||||
return()=>controller.abort();
|
||||
},[]);
|
||||
if(!available)return null;
|
||||
return available.length?<div className="about-actions">
|
||||
{available.map(item=><a className="button" download key={item.url} href={item.url}>{t('Download {platform}',{platform:item.label})}</a>)}
|
||||
</div>:<p className="bambu-account-muted">{t('The desktop helper packages are unavailable on this server.')}</p>;
|
||||
}
|
||||
|
||||
export interface BambuPrintTarget {serial:string;name:string;revision:number}
|
||||
|
||||
export function BambuCloudAccount({close,state,changed,job,addPrinter,openPresets,target}:{close:()=>void;state:BambuCloudState;changed:(value:BambuCloudState)=>void;job:Job|null;addPrinter?:(printer:AccountPrinter)=>void;openPresets?:()=>void;target?:BambuPrintTarget}) {
|
||||
useLanguage();
|
||||
const dialog=useRef<HTMLDialogElement>(null);
|
||||
const [busy,setBusy]=useState(false),[error,setError]=useState<unknown>(null);
|
||||
const [pairing,setPairing]=useState(''),[copied,setCopied]=useState(false),[pairingExpires,setPairingExpires]=useState(0);
|
||||
const title=target?t('Print'):t('Bambu Lab account');
|
||||
const [printers,setPrinters]=useState<CloudPrinter[]|null>(null),[selected,setSelected]=useState('');
|
||||
const [bedLeveling,setBedLeveling]=useState(true),[flowCalibration,setFlowCalibration]=useState(false),[timelapse,setTimelapse]=useState(false);
|
||||
const [cloudPrint,setCloudPrint]=useState<{job:number;state:CloudPrint|null}|null>(null);
|
||||
useEffect(()=>{dialog.current?.showModal();},[]);
|
||||
const loadPrinters=useCallback(async()=>{
|
||||
setError(null);
|
||||
try{const value=await api<{cloud_connected:boolean;printers:CloudPrinter[]}>('/bambu-cloud/printers');setPrinters(value.printers);
|
||||
setSelected(current=>current||value.printers.find(printer=>printer.online)?.dev_id||'');}
|
||||
catch(reason){setError(reason);}
|
||||
@@ -103,15 +132,49 @@ export function BambuCloudAccount({close,state,changed,job}:{close:()=>void;stat
|
||||
.then(value=>setCloudPrint(current=>current&&{...current,state:value})).catch(setError);},2000);
|
||||
return()=>window.clearInterval(timer);
|
||||
},[cloudPrint]);
|
||||
useEffect(()=>{
|
||||
if(!pairing)return;
|
||||
const controller=new AbortController();
|
||||
const timer=window.setInterval(()=>{
|
||||
void api<BambuCloudState>('/bambu-cloud',{signal:controller.signal}).then(value=>{
|
||||
if(value.logged_in&&!controller.signal.aborted){setPairing('');changed(value);}
|
||||
}).catch(()=>{});
|
||||
},2500);
|
||||
const expiry=window.setTimeout(()=>setPairing(''),Math.max(0,pairingExpires-Date.now()));
|
||||
return()=>{controller.abort();window.clearInterval(timer);window.clearTimeout(expiry);};
|
||||
},[pairing,pairingExpires,changed]);
|
||||
async function startDesktopSignIn(){
|
||||
setBusy(true);setError(null);setCopied(false);
|
||||
try{
|
||||
const value=await api<{code:string;expires_in:number;plugin_version?:string}>('/bambu-cloud/desktop-login',jsonRequest('POST',{}));
|
||||
const url=new URL(apiUrl('/bambu-cloud/desktop-login/redeem'),location.href);
|
||||
url.hash=new URLSearchParams({bambu_pairing:value.code,version:value.plugin_version??''}).toString();
|
||||
setPairingExpires(Date.now()+value.expires_in*1000);setPairing(url.href);
|
||||
}catch(reason){setError(reason);}finally{setBusy(false);}
|
||||
}
|
||||
async function cancelDesktopSignIn(){
|
||||
setBusy(true);setError(null);
|
||||
try{await api('/bambu-cloud/desktop-login',{method:'DELETE'});setPairing('');}
|
||||
catch(reason){setError(reason);}finally{setBusy(false);}
|
||||
}
|
||||
async function configureSync(enabled?:boolean){
|
||||
setBusy(true);setError(null);
|
||||
try{
|
||||
const value=await api<BambuPresetSyncState>('/bambu-cloud/preset-sync',jsonRequest(enabled===undefined?'POST':'PUT',enabled===undefined?{}:{enabled}));
|
||||
changed({...state,preset_sync:value});
|
||||
}catch(reason){setError(reason);}finally{setBusy(false);}
|
||||
}
|
||||
async function signOut(){
|
||||
setBusy(true);setError(null);
|
||||
try{changed(await api<BambuCloudState>('/bambu-cloud/logout',jsonRequest('POST',{})));setPrinters(null);}catch(reason){setError(reason);}finally{setBusy(false);}
|
||||
}
|
||||
async function send(){
|
||||
if(!job||!selected)return;
|
||||
const device=target?.serial??selected;
|
||||
if(!job||!device||busy)return;
|
||||
setBusy(true);setError(null);
|
||||
try{const started=await api<{job:number}>(`/bambu-cloud/printers/${encodeURIComponent(selected)}/print`,
|
||||
jsonRequest('POST',{job_id:job.id,bed_leveling:bedLeveling,flow_calibration:flowCalibration,timelapse}));
|
||||
try{const started=await api<{job:number}>(`/bambu-cloud/printers/${encodeURIComponent(device)}/print`,
|
||||
jsonRequest('POST',{job_id:job.id,bed_leveling:bedLeveling,flow_calibration:flowCalibration,timelapse,
|
||||
...(target?{connection_revision:target.revision}:{})}));
|
||||
setCloudPrint({job:started.job,state:null});}
|
||||
catch(reason){setError(reason);}finally{setBusy(false);}
|
||||
}
|
||||
@@ -120,43 +183,74 @@ export function BambuCloudAccount({close,state,changed,job}:{close:()=>void;stat
|
||||
}
|
||||
const signIn=()=>{window.location.href='/native/bambu-cloud-login?plugin_version='+encodeURIComponent(state.plugin_version??'');};
|
||||
const printable=job?.status==='completed'&&job.result?.upload_format==='gcode_3mf';
|
||||
const fixedPrinter=target&&printers?.find(printer=>printer.dev_id===target.serial);
|
||||
const last=cloudPrint?.state?.status.at(-1);
|
||||
return <dialog ref={dialog} className="about-dialog" aria-label={t('Bambu Lab account')} onCancel={event=>{event.preventDefault();close();}}>
|
||||
<header><h2>{t('Bambu Lab account')}</h2><button onClick={close}>{t('Close')}</button></header>
|
||||
return <dialog ref={dialog} className="about-dialog bambu-account-dialog" aria-label={title} onCancel={event=>{event.preventDefault();if(!busy)close();}}>
|
||||
<header><h2>{title}</h2><button disabled={busy} onClick={close}>{t('Close')}</button></header>
|
||||
{state.logged_in
|
||||
?<p role="status">{t('Signed in as {name}',{name:state.user_name||state.user_id||''})}</p>
|
||||
:<p role="status">{t('Not signed in')}</p>}
|
||||
:<p role="status">{t(state.available?'Not signed in':'Bambu Lab cloud requires a cloud-enabled build.')}</p>}
|
||||
{error!=null&&<ErrorNotice error={error} onDismiss={()=>setError(null)}/>}
|
||||
<div className="about-actions">
|
||||
{state.logged_in
|
||||
?<button disabled={busy} onClick={()=>{void signOut();}}>{t('Sign out')}</button>
|
||||
:inAndroidApp()
|
||||
?<button disabled={busy} onClick={signIn}>{t('Sign in to Bambu Lab')}</button>
|
||||
:<p>{t('Signing in to Bambu Lab is available in the Android app.')}</p>}
|
||||
</div>
|
||||
{state.logged_in?(!target&&<div className="about-actions"><button disabled={busy} onClick={()=>void signOut()}>{t('Sign out')}</button></div>):
|
||||
state.available&&(inAndroidApp()
|
||||
?<div className="about-actions"><button disabled={busy} onClick={signIn}>{t('Sign in to Bambu Lab')}</button></div>
|
||||
:<section className="bambu-desktop-sign-in">
|
||||
<h3>{t('Desktop helper')}</h3>
|
||||
<p className="bambu-account-muted">{t('Download the helper, then create a pairing link and paste it into the app.')}</p>
|
||||
<DesktopHelperDownloads/>
|
||||
{pairing?<div className="bambu-pairing-fields">
|
||||
<label>{t('Desktop pairing link')}<input readOnly value={pairing} onFocus={event=>event.currentTarget.select()}/></label>
|
||||
<p className="bambu-account-muted">{t('Paste this link into the Web Slicer desktop helper. It expires after 10 minutes.')}</p>
|
||||
<div className="about-actions">
|
||||
<button className="primary" disabled={busy} onClick={()=>{void navigator.clipboard.writeText(pairing).then(()=>setCopied(true)).catch(setError);}}>{t(copied?'Copied':'Copy link')}</button>
|
||||
<button disabled={busy} onClick={()=>void cancelDesktopSignIn()}>{t('Cancel')}</button>
|
||||
</div>
|
||||
</div>:<div className="about-actions">
|
||||
<button className="primary" disabled={busy} onClick={()=>void startDesktopSignIn()}>{t('Create pairing link')}</button>
|
||||
</div>}
|
||||
</section>)}
|
||||
{!target&&state.logged_in&&state.available&&!inAndroidApp()&&<section className="bambu-desktop-sign-in">
|
||||
<h3>{t('Desktop helper')}</h3>
|
||||
<DesktopHelperDownloads/>
|
||||
</section>}
|
||||
{!target&&state.logged_in&&state.personal_account&&<p>{t('Your Bambu Lab connection is private to your Web Slicer account. Automatic sync to the shared preset library is disabled.')}</p>}
|
||||
{!target&&state.logged_in&&state.preset_sync&&<section>
|
||||
<h3>{t('Preset synchronization')}</h3>
|
||||
<label><input type="checkbox" checked={state.preset_sync.enabled} disabled={busy}
|
||||
onChange={event=>void configureSync(event.target.checked)}/> {t('Sync Bambu Lab presets automatically')}</label>
|
||||
{state.preset_sync.enabled&&<p role="status">{state.preset_sync.running?t('Synchronizing presets…'):
|
||||
state.preset_sync.failed?t('Preset sync failed. It will retry automatically.'):
|
||||
state.preset_sync.last_sync?t('Last synchronized: {time}',{time:new Date(state.preset_sync.last_sync*1000).toLocaleString()}):
|
||||
t('Waiting for the first synchronization.')}</p>}
|
||||
{!!state.preset_sync.conflicts&&<p role="status">{t('Presets needing review: {count}',{count:state.preset_sync.conflicts})}</p>}
|
||||
<button type="button" disabled={busy||!state.preset_sync.enabled||state.preset_sync.running} onClick={()=>void configureSync()}>{t('Sync now')}</button>
|
||||
</section>}
|
||||
{state.logged_in&&<section>
|
||||
<h3>{t('Printers on this account')}</h3>
|
||||
{printers===null?<p role="status">{t('Loading…')}</p>
|
||||
<h3>{target?.name??t('Printers on this account')}</h3>
|
||||
{target?(printers===null?<p role="status">{t('Loading…')}</p>:fixedPrinter?<p>{describe(fixedPrinter)}</p>:
|
||||
<p role="alert">{t('This printer is missing from your Bambu Lab account.')}</p>):printers===null?<p role="status">{t('Loading…')}</p>
|
||||
:printers.length===0?<p>{t('No printers are bound to this Bambu Lab account.')}</p>
|
||||
:<ul>{printers.map(printer=><li key={printer.dev_id}><label>
|
||||
<input type="radio" name="bambu-cloud-printer" checked={selected===printer.dev_id} onChange={()=>setSelected(printer.dev_id)}/>
|
||||
{' '}{printer.name}{printer.model?` (${printer.model})`:''}{' — '}{describe(printer)}</label>
|
||||
{addPrinter&&<button disabled={busy} onClick={()=>addPrinter(printer)}>{t('Add to printers')}</button>}
|
||||
{printer.status?.authorization_control&&<div><small>{t('Verifies commands (Authorization Control): status works, but cloud printing and control need a slicer key.')}</small></div>}</li>)}</ul>}
|
||||
{selected&&<>
|
||||
{(target?fixedPrinter:selected)&&<>
|
||||
<h3>{t('Print through Bambu Lab cloud')}</h3>
|
||||
{!printable&&<p>{t('Slice for a Bambu Lab printer first; the result is sent as a .gcode.3mf.')}</p>}
|
||||
<label><input type="checkbox" checked={bedLeveling} onChange={event=>setBedLeveling(event.target.checked)}/> {t('Bed leveling')}</label>
|
||||
<label><input type="checkbox" checked={flowCalibration} onChange={event=>setFlowCalibration(event.target.checked)}/> {t('Flow calibration')}</label>
|
||||
<label><input type="checkbox" checked={timelapse} onChange={event=>setTimelapse(event.target.checked)}/> {t('Timelapse')}</label>
|
||||
<div className="about-actions">
|
||||
<button disabled={busy||!printable||(!!cloudPrint&&!cloudPrint.state?.done)} onClick={()=>{void send();}}>{t('Send current slice')}</button>
|
||||
<button className="primary" disabled={busy||!printable||!!target&&!fixedPrinter?.online||(!!cloudPrint&&!cloudPrint.state?.done)} onClick={()=>{void send();}}>{t(target?'Start print':'Send current slice')}</button>
|
||||
{cloudPrint&&!cloudPrint.state?.done&&<button onClick={()=>{void cancel();}}>{t('Cancel')}</button>}
|
||||
</div>
|
||||
{cloudPrint&&<p role="status">{cloudPrint.state?.done?outcome(cloudPrint.state):last?progress(last):t('Sending…')}</p>}
|
||||
<p><small>{t('Prints from the external spool; AMS mapping is not supported yet. Printers that verify commands also need a slicer key (see below).')}</small></p>
|
||||
</>}
|
||||
</section>}
|
||||
{state.logged_in&&<SlicerKeySection/>}
|
||||
{state.logged_in&&openPresets&&<button disabled={busy} onClick={openPresets}>{t('Import Bambu Lab presets')}</button>}
|
||||
{!target&&state.logged_in&&<SlicerKeySection/>}
|
||||
<p><small>{t('The sign-in page is Bambu Lab’s own; your password is entered there and is never seen by Web Slicer. Plugin {version}.',{version:state.plugin_version??''})}</small></p>
|
||||
</dialog>;
|
||||
}
|
||||
|
||||
@@ -7,48 +7,40 @@ import {t} from './i18n';
|
||||
// the account the backend looks up the printer's address and access code, so
|
||||
// only the serial number is saved.
|
||||
export const CLOUD_HOST='http://bambu-cloud.invalid/';
|
||||
interface AccountPrinter {dev_id:string;name:string;model?:string|null;model_code?:string|null;online:boolean}
|
||||
export interface AccountPrinter {dev_id:string;name:string;model?:string|null;model_code?:string|null;online:boolean}
|
||||
|
||||
export const CLOUD_TYPE='bambu_cloud';
|
||||
export function cloudConnection(printer:AccountPrinter){
|
||||
return {revision:0,type:'bambu_lan',bambu_transport:'cloud',host:CLOUD_HOST,auth_type:'api_key',
|
||||
bambu_serial_number:printer.dev_id,printer_model:printer.model_code??''};
|
||||
}
|
||||
|
||||
export const isCloudDraft=(draft:Record<string,unknown>)=>draft.type==='bambu_lan'&&draft.bambu_transport==='cloud';
|
||||
|
||||
export function BambuCloudConnection({draft,field}:{draft:Record<string,unknown>;field:(key:string,value:unknown)=>void}) {
|
||||
const [available,setAvailable]=useState<boolean|null>(null);
|
||||
export function BambuCloudConnection({draft,field,signedIn}:{draft:Record<string,unknown>;field:(key:string,value:unknown)=>void;signedIn:boolean}) {
|
||||
const [printers,setPrinters]=useState<AccountPrinter[]|null>(null);
|
||||
const [error,setError]=useState('');
|
||||
const cloud=isCloudDraft(draft);
|
||||
useEffect(()=>{api<{available:boolean;logged_in?:boolean}>('/bambu-cloud')
|
||||
.then(value=>setAvailable(value.available&&!!value.logged_in)).catch(()=>setAvailable(false));},[]);
|
||||
useEffect(()=>{
|
||||
if(!cloud||!available)return;
|
||||
setError('');
|
||||
api<{printers:AccountPrinter[]}>('/bambu-cloud/printers').then(value=>setPrinters(value.printers))
|
||||
.catch(reason=>setError(reason instanceof Error?reason.message:String(reason)));
|
||||
},[cloud,available]);
|
||||
if(!available&&!cloud)return null;
|
||||
function transport(value:string){
|
||||
field('bambu_transport',value);
|
||||
field('host',value==='cloud'?CLOUD_HOST:'');
|
||||
field('bambu_serial_number','');field('printer_model','');
|
||||
}
|
||||
if(!signedIn)return;
|
||||
const controller=new AbortController();
|
||||
api<{printers:AccountPrinter[]}>('/bambu-cloud/printers',{signal:controller.signal})
|
||||
.then(value=>setPrinters(value.printers))
|
||||
.catch(reason=>{if(!controller.signal.aborted)setError(reason instanceof Error?reason.message:String(reason));});
|
||||
return()=>controller.abort();
|
||||
},[signedIn]);
|
||||
function choose(dev:string){
|
||||
const printer=printers?.find(item=>item.dev_id===dev);
|
||||
field('bambu_serial_number',dev);
|
||||
if(printer?.model_code)field('printer_model',printer.model_code);
|
||||
field('printer_model',printer?.model_code??'');
|
||||
}
|
||||
return <>
|
||||
<label>{t('Connection')}<select value={cloud?'cloud':'lan'} onChange={event=>transport(event.target.value)}>
|
||||
<option value="lan">{t('LAN (Developer Mode)')}</option>
|
||||
<option value="cloud" disabled={!available}>{t('Bambu Lab account')}</option>
|
||||
</select></label>
|
||||
{cloud&&<>
|
||||
{available===false&&<p>{t('Sign in to your Bambu Lab account in this app to use this connection.')}</p>}
|
||||
{!signedIn&&<p>{t('Sign in to your Bambu Lab account in this app to use this connection.')}</p>}
|
||||
{error&&<p role="alert">{error}</p>}
|
||||
{printers&&<label>{t('Printer on the account')}<select required value={String(draft.bambu_serial_number??'')} onChange={event=>choose(event.target.value)}>
|
||||
{signedIn&&printers&&<label>{t('Printer on the account')}<select required value={String(draft.bambu_serial_number??'')} onChange={event=>choose(event.target.value)}>
|
||||
<option value="" disabled>{t('Select')}</option>
|
||||
{printers.map(printer=><option key={printer.dev_id} value={printer.dev_id}>
|
||||
{printer.name}{printer.model?` (${printer.model})`:''}{printer.online?'':` · ${t('Offline')}`}</option>)}
|
||||
</select></label>}
|
||||
<p className="connection-description">{t('Status and controls go through the Bambu Lab cloud. The camera and printer files are reached on the local network, so they work only when this device is on the printer’s network. Printers that verify commands (Authorization Control) need a slicer key for controls. Printing uses Bambu Lab account → Print through Bambu Lab cloud.')}</p>
|
||||
</>}
|
||||
</>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import {useEffect,useRef,useState} from 'react';
|
||||
import {api} from './api';
|
||||
import {ErrorNotice} from './ErrorNotice';
|
||||
import {t} from './i18n';
|
||||
import type {MaterialTemplate} from './TemplateMaterialPicker';
|
||||
|
||||
interface Preset extends MaterialTemplate {source?:string}
|
||||
const commonMaterials=['PLA','PETG','ABS','ASA','TPU'];
|
||||
const pageSize=12;
|
||||
const presetName=(preset:Preset)=>preset.display_name??preset.name;
|
||||
|
||||
export function FilamentPresetBrowser({busy,applyError,close,manual,apply}:{busy:boolean;applyError:string;close:()=>void;manual?:()=>void;apply:(name:string)=>void}){
|
||||
const dialog=useRef<HTMLDialogElement>(null);
|
||||
const [presets,setPresets]=useState<Preset[]|null>(null),[error,setError]=useState<unknown>(null),[attempt,setAttempt]=useState(0);
|
||||
const [query,setQuery]=useState(''),[material,setMaterial]=useState(''),[vendor,setVendor]=useState(''),[limit,setLimit]=useState(pageSize);
|
||||
const [selection,setSelection]=useState<string|null>(null),[variant,setVariant]=useState('');
|
||||
useEffect(()=>{dialog.current?.showModal();},[]);
|
||||
useEffect(()=>{
|
||||
const abort=new AbortController();
|
||||
void api<{filaments:Preset[]}>('/profiles',{signal:abort.signal}).then(result=>{
|
||||
if(!abort.signal.aborted)setPresets(result.filaments.filter(item=>item.source!=='project'));
|
||||
}).catch(reason=>{if(!abort.signal.aborted)setError(reason);});
|
||||
return()=>abort.abort();
|
||||
},[attempt]);
|
||||
const materials=[...new Set(presets?.flatMap(preset=>preset.filament_type?[preset.filament_type]:[]))].sort();
|
||||
const byMaterial=presets?.filter(preset=>!material||preset.filament_type===material)??[];
|
||||
const vendors=[...new Set(byMaterial.flatMap(preset=>preset.filament_vendor?[preset.filament_vendor]:[]))].sort();
|
||||
const words=query.trim().toLocaleLowerCase().split(/\s+/);
|
||||
const groups=new Map<string,{name:string;material:string;vendor:string;presets:Preset[]}>();
|
||||
if(material||vendor||query.trim()){
|
||||
for(const preset of byMaterial){
|
||||
const brand=preset.filament_vendor??'',type=preset.filament_type??'';
|
||||
const searchable=[presetName(preset),brand,type].join(' ').toLocaleLowerCase();
|
||||
if((vendor&&brand!==vendor)||!words.every(word=>searchable.includes(word)))continue;
|
||||
const name=presetName(preset).split(' @',1)[0];
|
||||
const key=JSON.stringify([type,brand,name]);
|
||||
const group=groups.get(key)??{name,material:type,vendor:brand,presets:[]};
|
||||
group.presets.push(preset);groups.set(key,group);
|
||||
}
|
||||
}
|
||||
const results=[...groups].sort(([,a],[,b])=>a.name.localeCompare(b.name));
|
||||
const selected=selection===null?undefined:groups.get(selection);
|
||||
const chosen=selected?.presets.find(preset=>preset.name===variant);
|
||||
const filtering=Boolean(material||vendor||query.trim());
|
||||
const resetResults=()=>{setSelection(null);setVariant('');setLimit(pageSize);};
|
||||
function changeMaterial(value:string){setMaterial(value);setVendor('');resetResults();}
|
||||
function select(key:string,options:Preset[]){
|
||||
setSelection(key);setVariant(options.length===1?options[0].name:'');
|
||||
}
|
||||
return <dialog ref={dialog} className="filament-preset-browser" aria-labelledby="filament-preset-title"
|
||||
onCancel={event=>{event.preventDefault();if(!busy)close();}}>
|
||||
<header className="filament-browser-header">
|
||||
<div><h2 id="filament-preset-title">{t('Choose filament preset')}</h2>
|
||||
<p>{t('Find a filament to fill in its library details.')}</p></div>
|
||||
<button type="button" disabled={busy} onClick={close}>{t('Close')}</button>
|
||||
</header>
|
||||
<div className="filament-browser-body" aria-busy={busy||!presets&&!error}>
|
||||
{applyError&&<p className="error" role="alert">{applyError}</p>}
|
||||
{error!=null&&<><ErrorNotice error={error}/><button type="button" onClick={()=>{setError(null);setAttempt(value=>value+1);}}>{t('Retry')}</button></>}
|
||||
{!presets&&!error&&<p role="status">{t('Loading filament presets…')}</p>}
|
||||
{presets&&<fieldset className="filament-browser-controls" disabled={busy}>
|
||||
<label>{t('Search presets')}<input autoFocus type="search" value={query} placeholder={t('e.g. Bambu PLA or PETG HF')}
|
||||
onChange={event=>{setQuery(event.target.value);resetResults();}}/></label>
|
||||
<div className="filament-browser-chips" aria-label={t('Popular materials')}>
|
||||
{commonMaterials.filter(value=>materials.includes(value)).map(value=><button type="button" key={value}
|
||||
aria-pressed={material===value} onClick={()=>changeMaterial(material===value?'':value)}>{value}</button>)}
|
||||
</div>
|
||||
<div className="filament-browser-filters">
|
||||
<label>{t('Material')}<select value={material} onChange={event=>changeMaterial(event.target.value)}>
|
||||
<option value="">{t('All materials')}</option>{materials.map(value=><option key={value}>{value}</option>)}
|
||||
</select></label>
|
||||
<label>{t('Manufacturer')}<select value={vendor} onChange={event=>{setVendor(event.target.value);resetResults();}}>
|
||||
<option value="">{t('All manufacturers')}</option>{vendors.map(value=><option key={value}>{value}</option>)}
|
||||
</select></label>
|
||||
</div>
|
||||
{!filtering&&<p className="filament-browser-empty">{t('Search by name or choose a material to browse presets.')}</p>}
|
||||
{filtering&&<section aria-label={t('Matching items')}>
|
||||
{results.length===0?<p className="filament-browser-empty">{t('No matching items...')}</p>:
|
||||
<div className="filament-browser-results">{results.slice(0,limit).map(([key,group])=>
|
||||
<button type="button" key={key} aria-pressed={selection===key} onClick={()=>select(key,group.presets)}>
|
||||
<strong>{group.name}</strong>
|
||||
<span>{[group.vendor,group.material].filter(Boolean).join(' · ')}</span>
|
||||
</button>)}</div>}
|
||||
{results.length>limit&&<button type="button" className="filament-browser-more" onClick={()=>setLimit(value=>value+pageSize)}>{t('Show more')}</button>}
|
||||
</section>}
|
||||
</fieldset>}
|
||||
</div>
|
||||
<footer className="filament-browser-footer">
|
||||
{selected&&<div className="filament-browser-selection">
|
||||
<strong>{selected.name}</strong>
|
||||
{selected.presets.length>1&&<label>{t('Preset variant')}<select value={variant} disabled={busy} onChange={event=>setVariant(event.target.value)}>
|
||||
<option value="" disabled>{t('Choose a variant')}</option>
|
||||
{selected.presets.map(preset=><option value={preset.name} key={preset.name}>{presetName(preset)}</option>)}
|
||||
</select></label>}
|
||||
</div>}
|
||||
<div className="printer-actions">
|
||||
{manual&&<button type="button" disabled={busy} onClick={manual}>{t('Enter details manually')}</button>}
|
||||
<button type="button" className="primary" disabled={busy||!chosen} onClick={()=>{if(chosen)apply(chosen.name);}}>{t('Use preset')}</button>
|
||||
</div>
|
||||
</footer>
|
||||
</dialog>;
|
||||
}
|
||||
@@ -1,15 +1,20 @@
|
||||
import {useEffect,useState} from 'react';
|
||||
import {useEffect,useRef,useState} from 'react';
|
||||
import {api,jsonRequest,requestId} from './api';
|
||||
import {t} from './i18n';
|
||||
import {useError} from './uiErrors';
|
||||
import {saveLibraryCopy,type LibrarySaveIntent,type Machine,type MachineProfile,type MachinePreset} from './machines';
|
||||
import {emptyProduct,productData,productLabel,type FilamentLibrary,type FilamentProduct,type FilamentProductData} from './filamentProducts';
|
||||
import type {MaterialTemplate} from './TemplateMaterialPicker';
|
||||
import {FilamentPresetBrowser} from './FilamentPresetBrowser';
|
||||
import './filamentProducts.css';
|
||||
|
||||
type Person={id:string;username:string};
|
||||
type Template={name:string;display_name?:string;filament_vendor:string;filament_type:string};
|
||||
type Template=MaterialTemplate;
|
||||
export function FilamentProductLibrary({active,token,changed,editPreset,onDirty}:{active:boolean;token:number;changed:()=>void;
|
||||
editPreset:(machine:Machine,profile:MachineProfile,preset:MachinePreset)=>void;onDirty:(dirty:boolean)=>void}){
|
||||
const [browsing,setBrowsing]=useState<'new'|'replace'|null>(null);
|
||||
const detailsName=useRef<HTMLInputElement>(null);
|
||||
const focusDetails=useRef(false);
|
||||
const [libraries,setLibraries]=useState<FilamentLibrary[]>([]),[products,setProducts]=useState<FilamentProduct[]>([]),[machines,setMachines]=useState<Machine[]>([]);
|
||||
const [libraryId,setLibraryId]=useState(''),[selectedId,setSelectedId]=useState(''),[creating,setCreating]=useState(false);
|
||||
const [draft,setDraft]=useState<FilamentProductData>(emptyProduct),[query,setQuery]=useState(''),[limit,setLimit]=useState(60);
|
||||
@@ -28,6 +33,9 @@ export function FilamentProductLibrary({active,token,changed,editPreset,onDirty}
|
||||
}
|
||||
async function action(work:()=>Promise<void>){if(busy)return;setBusy(true);setError('');setNotice('');try{await work();}catch(reason){setError(reason);}finally{setBusy(false);}}
|
||||
useEffect(()=>{if(active)void action(async()=>{await load();});},[active,token]);
|
||||
useEffect(()=>{
|
||||
if(creating&&!browsing&&!busy&&focusDetails.current){focusDetails.current=false;detailsName.current?.focus();}
|
||||
},[creating,browsing,busy]);
|
||||
useEffect(()=>{if(selected){setDraft(productData(selected));setCreating(false);}},[selected?.id,selected?.revision]);
|
||||
useEffect(()=>{setOwner(library?.owner_id??'');setManagers(library?.managers??[]);setLibraryName(library?.name??'');},[library?.id,library?.revision]);
|
||||
useEffect(()=>{
|
||||
@@ -58,9 +66,12 @@ export function FilamentProductLibrary({active,token,changed,editPreset,onDirty}
|
||||
if(!libraries.some(l=>l.id===libraryId&&l.can_manage)){
|
||||
const value=await api<FilamentLibrary>('/filament-libraries/default',jsonRequest('POST',{}));setLibraryId(value.id);await load();
|
||||
}
|
||||
setSelectedId('');setCreating(true);setDraft({...emptyProduct});
|
||||
setBrowsing('new');
|
||||
});
|
||||
}
|
||||
function openDraft(value:FilamentProductData){
|
||||
focusDetails.current=true;setSelectedId('');setDraft(value);setCreating(true);setBrowsing(null);
|
||||
}
|
||||
const visible=products.filter(p=>(!libraryId||p.library_id===libraryId)&&`${p.vendor} ${p.name} ${p.material}`.toLocaleLowerCase().includes(query.toLocaleLowerCase()));
|
||||
async function finishSave(intent:LibrarySaveIntent,recover:boolean){
|
||||
await saveLibraryCopy(intent,recover,()=>{localStorage.removeItem(`orca-product-profile-save:${selectedId}`);setPending(null);});
|
||||
@@ -68,7 +79,12 @@ export function FilamentProductLibrary({active,token,changed,editPreset,onDirty}
|
||||
}
|
||||
return <section className="filament-product-library" aria-label={t('Filament library')}>
|
||||
<header className="product-library-heading"><div><h1>{t('Filament library')}</h1><p>{t('Filaments and their settings for your printers.')}</p></div><div className="printer-actions"><button disabled={busy} onClick={()=>void action(async()=>{if(!dirty||window.confirm(t('Discard unsaved changes?')))await load();})}>{t('Reload')}</button><button className="primary" disabled={busy} onClick={()=>void add()}>{t('Add filament')}</button></div></header>
|
||||
{error&&<p className="error" role="alert">{error}</p>}{notice&&<p role="status">{t(notice)}</p>}{busy&&<p role="status">{t('Loading…')}</p>}
|
||||
{browsing&&<FilamentPresetBrowser busy={busy} applyError={error} close={()=>{setBrowsing(null);setError('');}} manual={browsing==='new'?()=>openDraft({...emptyProduct}):undefined}
|
||||
apply={name=>void action(async()=>{
|
||||
if(browsing==='replace'&&dirty&&!window.confirm(t('Replace the filament draft with this preset?')))return;
|
||||
openDraft(await api<FilamentProductData>('/filament-product-template?'+new URLSearchParams({name})));
|
||||
})}/>}
|
||||
{error&&!browsing&&<p className="error" role="alert">{error}</p>}{notice&&<p role="status">{t(notice)}</p>}{busy&&<p role="status">{t('Loading…')}</p>}
|
||||
<div className="product-library-filters">
|
||||
{libraries.length>1&&<label>{t('Library')}<select value={libraryId} disabled={busy} onChange={e=>{if(!dirty||window.confirm(t('Discard unsaved changes?'))){setLibraryId(e.target.value);setSelectedId('');setCreating(false);}}}>{libraries.map(l=><option key={l.id} value={l.id}>{l.name}</option>)}</select></label>}
|
||||
<label>{t('Search')}<input type="search" value={query} onChange={e=>{setQuery(e.target.value);setLimit(60);}}/></label>
|
||||
@@ -87,7 +103,8 @@ export function FilamentProductLibrary({active,token,changed,editPreset,onDirty}
|
||||
});}}>
|
||||
<h2>{t(creating?'Add filament':'Filament')}</h2>
|
||||
<fieldset disabled={busy||!!selected&&!selected.can_manage}>
|
||||
<label>{t('Name')}<input required maxLength={128} value={draft.name} onChange={e=>setDraft(v=>({...v,name:e.target.value}))}/></label>
|
||||
{creating&&<div className="product-template-wizard"><button type="button" onClick={()=>{setError('');setBrowsing('replace');}}>{t('Start from a filament preset')}</button></div>}
|
||||
<label>{t('Name')}<input ref={detailsName} required maxLength={128} value={draft.name} onChange={e=>setDraft(v=>({...v,name:e.target.value}))}/></label>
|
||||
<label>{t('Manufacturer')}<input maxLength={128} value={draft.vendor} onChange={e=>setDraft(v=>({...v,vendor:e.target.value}))}/></label>
|
||||
<label>{t('Material')}<input required maxLength={64} value={draft.material} onChange={e=>setDraft(v=>({...v,material:e.target.value}))}/></label>
|
||||
<label>{t('Color')}<input type="color" value={draft.color} onChange={e=>setDraft(v=>({...v,color:e.target.value.toUpperCase()}))}/></label>
|
||||
|
||||
@@ -85,7 +85,7 @@ export function GcodeViewer(){
|
||||
<Workbench documentMode title={current?.name??t('Podgląd G-code')} status={current?localize(current.status):''}
|
||||
ready={false} preview hasPreview={current?.status==='completed'} selectPreview={()=>{}}
|
||||
projectActions={<>{openButton}{refreshButton}<a className="button" href={window.location.pathname}>{t('Edytor modeli')}</a></>}
|
||||
libraryActions={null} calibrationActions={null} deviceActions={null} jobActions={null}
|
||||
libraryActions={null} calibrationActions={null} jobActions={null}
|
||||
preferences={<><LocalAccount onManageUsers={()=>window.location.assign('?users')}/><LanguageSelector/><ThemeSelector/></>} historyActions={null} importAction={openButton}
|
||||
navigation={null} plates={null} projects={documents} scene={scene}
|
||||
footer={<footer>{controls}</footer>} inspector={null} inspectorTab="print" setInspectorTab={()=>{}}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import {useEffect,useRef,useState,type ReactNode} from 'react';
|
||||
import {createPortal} from 'react-dom';
|
||||
import {useEffect,useState,type ReactNode} from 'react';
|
||||
import {api,apiUrl} from './api';
|
||||
import {ErrorNotice} from './ErrorNotice';
|
||||
import {t,useLanguage} from './i18n';
|
||||
@@ -34,50 +33,53 @@ function hintText(text:string,action:Hint['action']):ReactNode{
|
||||
return read();
|
||||
}
|
||||
|
||||
export function HelpCenter(){
|
||||
export function HelpCenter({active}:{active:boolean}){
|
||||
useLanguage();
|
||||
const dialog=useRef<HTMLDialogElement>(null);
|
||||
const [open,setOpen]=useState(false),[tab,setTab]=useState<'help'|'tips'>('help'),[catalog,setCatalog]=useState<Catalog|null>(null);
|
||||
const [catalog,setCatalog]=useState<Catalog|null>(null);
|
||||
const [loading,setLoading]=useState(false),[error,setError]=useState<unknown>(null),[reload,setReload]=useState(0),[query,setQuery]=useState(''),[selected,setSelected]=useState(''),[failedImage,setFailedImage]=useState('');
|
||||
useEffect(()=>{if(open)dialog.current?.showModal();},[open]);
|
||||
useEffect(()=>{
|
||||
if(!open)return;const abort=new AbortController();setLoading(true);setError(null);
|
||||
if(!active)return;const abort=new AbortController();setLoading(true);setError(null);
|
||||
void api<Catalog>('/hints',{signal:abort.signal}).then(value=>{
|
||||
if(!value||typeof value.revision!=='string'||!Array.isArray(value.hints)||value.hints.some(hint=>!hint||typeof hint.id!=='string'||typeof hint.msgid!=='string'||typeof hint.key!=='string'))throw new Error('The server did not return a valid tip catalog.');
|
||||
if(!abort.signal.aborted){setCatalog(value);setSelected(previous=>value.hints.some(hint=>hint.id===previous)?previous:value.hints[0]?.id??'');}
|
||||
})
|
||||
.catch(reason=>{if(!abort.signal.aborted)setError(reason);}).finally(()=>{if(!abort.signal.aborted)setLoading(false);});
|
||||
return()=>abort.abort();
|
||||
},[open,reload]);
|
||||
},[active,reload]);
|
||||
const plain=(value:string)=>value.replace(/<\/?[ab]>/g,'');
|
||||
const hints=(catalog?.hints??[]).map(hint=>{const text=t(hint.msgid),separator=text.indexOf('\n');return {...hint,text,title:separator<0?text:text.slice(0,separator),body:separator<0?'':text.slice(separator+1)};});
|
||||
const visible=hints.filter(hint=>plain(hint.text).toLocaleLowerCase().includes(query.trim().toLocaleLowerCase())),current=visible.find(hint=>hint.id===selected)??visible[0];
|
||||
const index=current?visible.indexOf(current):-1,docs=[...new Map(visible.filter(hint=>webURL(hint.documentation_url)).map(hint=>[hint.documentation_url,hint])).values()];
|
||||
const url=current?webURL(current.documentation_url):null;
|
||||
return <><button data-close-navigation onClick={()=>{setTab('help');setQuery('');setOpen(true);}}>{t('Help')}</button>
|
||||
{open&&createPortal(<dialog ref={dialog} className="help-center" aria-label={t('Help')} onCancel={event=>{event.preventDefault();setOpen(false);}} onClose={()=>setOpen(false)}>
|
||||
<header><h2>{t('Help')}</h2><button onClick={()=>setOpen(false)}>{t('Close')}</button></header>
|
||||
<nav className="help-actions" aria-label={t('Help sections')}><button aria-pressed={tab==='help'} onClick={()=>setTab('help')}>{t('Wiki')}</button><button aria-pressed={tab==='tips'} onClick={()=>setTab('tips')}>{t('Show Tip of the Day')}</button></nav>
|
||||
<p>{t('Original OrcaSlicer documentation and tips. Desktop shortcuts and menus may differ in the web client.')}</p>
|
||||
return <div className="help-center">
|
||||
<section className="help-documentation" aria-label={t('Documentation')}>
|
||||
<div className="help-card-header"><div><h3>{t('Documentation')}</h3>
|
||||
<p>{t('Original OrcaSlicer documentation. Desktop shortcuts and menus may differ in the web client.')}</p></div>
|
||||
<a href="https://www.orcaslicer.com/wiki/" target="_blank" rel="noopener noreferrer">{t('Open the wiki')} <span aria-hidden="true">↗</span></a>
|
||||
</div>
|
||||
<label>{t('Search help topics')}<input type="search" value={query} onChange={event=>setQuery(event.target.value)}/></label>
|
||||
{loading&&<p role="status">{t('Loading…')}</p>}
|
||||
{error!=null&&<><ErrorNotice error={error}/>{catalog&&<p role="status">{t('The previous tip catalog is shown. Refresh to get the current version.')}</p>}</>}
|
||||
<div className="help-actions"><button disabled={loading} onClick={()=>setReload(value=>value+1)}>{t(error?'Retry':'Refresh')}</button></div>
|
||||
<label>{t('Search')}<input type="search" value={query} onChange={event=>setQuery(event.target.value)}/></label>
|
||||
{tab==='help'?<section aria-label={t('Documentation')}>
|
||||
<h3>{t('Documentation')}</h3><p><a href="https://www.orcaslicer.com/wiki/" target="_blank" rel="noopener noreferrer">{t('Wiki')}</a></p>
|
||||
<ul>{docs.map(hint=><li key={hint.documentation_url}><a href={webURL(hint.documentation_url)!} target="_blank" rel="noopener noreferrer">{plain(hint.title)}</a></li>)}</ul>
|
||||
{!loading&&!error&&!docs.length&&<p>{t('No matching documentation links.')}</p>}
|
||||
</section>:<section aria-label={t('Show Tip of the Day')}>
|
||||
{current?<>
|
||||
{error!=null&&<><ErrorNotice error={error}/><button type="button" onClick={()=>setReload(value=>value+1)}>{t('Retry')}</button></>}
|
||||
{query.trim()&&<ul className="help-topic-links">{docs.map(hint=><li key={hint.documentation_url}>
|
||||
<a href={webURL(hint.documentation_url)!} target="_blank" rel="noopener noreferrer">{plain(hint.title)} <span aria-hidden="true">↗</span></a>
|
||||
</li>)}</ul>}
|
||||
{query.trim()&&!loading&&!error&&!docs.length&&<p>{t('No matching documentation links.')}</p>}
|
||||
</section>
|
||||
<section className="help-tips" aria-label={t('Tips')}>
|
||||
<div className="help-card-header"><h3>{t('Tips')}</h3>
|
||||
{current&&<div className="help-tip-nav">
|
||||
<button type="button" aria-label={t('Previous')} disabled={visible.length<2} onClick={()=>setSelected(visible[(index-1+visible.length)%visible.length].id)}>←</button>
|
||||
<span role="status">{index+1} / {visible.length}</span>
|
||||
<button type="button" aria-label={t('Next')} disabled={visible.length<2} onClick={()=>setSelected(visible[(index+1)%visible.length].id)}>→</button>
|
||||
</div>}
|
||||
</div>
|
||||
{current?<article aria-label={plain(current.title)}>
|
||||
<h4>{hintText(current.title,null)}</h4><p className="help-tip-text">{hintText(current.body,current.action)}</p>
|
||||
{current.action&¤t.action.type!=='link'&&<small>{t('This tip refers to a desktop action. Use the corresponding web workspace or tool.')}</small>}
|
||||
{current.image_url&&/^[a-f0-9]{64}$/.test(current.id)&&(failedImage===current.id?<p>{t('Image unavailable.')}</p>:<img src={apiUrl('/hints/'+current.id+'/image')} alt={plain(current.title)} onError={()=>setFailedImage(current.id)}/>)}
|
||||
{url&&<a href={url} target="_blank" rel="noopener noreferrer">{t('Read the guide')} <span aria-hidden="true">↗</span></a>}
|
||||
<label>{t('Tip')}<select value={current.id} onChange={event=>setSelected(event.target.value)}>{visible.map(hint=><option key={hint.id} value={hint.id}>{plain(hint.title)}</option>)}</select></label>
|
||||
<div className="help-actions"><button disabled={visible.length<2} onClick={()=>setSelected(visible[(index-1+visible.length)%visible.length].id)}>{t('Previous')}</button><p role="status">{index+1}{' / '}{visible.length}</p><button disabled={visible.length<2} onClick={()=>setSelected(visible[(index+1)%visible.length].id)}>{t('Next')}</button></div>
|
||||
<article aria-label={plain(current.title)}><h3>{hintText(current.title,null)}</h3><p className="help-tip-text">{hintText(current.body,current.action)}</p>
|
||||
{current.action&¤t.action.type!=='link'&&<small>{t('This tip refers to a desktop action. Use the corresponding web workspace or tool.')}</small>}
|
||||
{current.image_url&&/^[a-f0-9]{64}$/.test(current.id)&&(failedImage===current.id?<p>{t('Image unavailable.')}</p>:<img src={apiUrl('/hints/'+current.id+'/image')} alt={plain(current.title)} onError={()=>setFailedImage(current.id)}/>)}
|
||||
{url&&<a href={url} target="_blank" rel="noopener noreferrer">{t('Wiki')}</a>}
|
||||
</article>
|
||||
</>:!loading&&!error&&<p>{t('No matching tips.')}</p>}
|
||||
</section>}
|
||||
</dialog>,document.body)}
|
||||
</>;
|
||||
</article>:!loading&&!error&&<p>{t('No matching tips.')}</p>}
|
||||
</section>
|
||||
</div>;
|
||||
}
|
||||
|
||||
@@ -45,8 +45,8 @@ function bundleManifest(files:File[]) {
|
||||
}
|
||||
const unfinished=new Set(['uploading','queued','running','waiting_options','waiting_texture','waiting_scale','interrupted','conflict','failed']);
|
||||
|
||||
export function Imports({request,consume,completed,historyContainer,project,schema,manage,libraryChanged}:{historyContainer?:HTMLElement|null;request:ImportRequest|null;consume:()=>void;completed:(task:ImportTask,explicit:boolean)=>Promise<void>;
|
||||
project:Project|null;schema:Record<string,Option>;manage:()=>void;libraryChanged:()=>void}) {
|
||||
export function Imports({request,consume,completed,historyContainer,project,schema,manage,libraryChanged,externalJob}:{historyContainer?:HTMLElement|null;request:ImportRequest|null;consume:()=>void;completed:(task:ImportTask,explicit:boolean)=>Promise<void>;
|
||||
project:Project|null;schema:Record<string,Option>;manage:()=>void;libraryChanged:()=>void;externalJob?:string|null}) {
|
||||
const [tasks,setTasks]=useState<ImportTask[]>([]),[error,setError,errorDetail]=useError();
|
||||
const [pollError,setPollError,pollErrorDetail]=useError();
|
||||
const [upload,setUpload]=useState<{id:string;percent:number}|null>(null);
|
||||
@@ -63,6 +63,14 @@ export function Imports({request,consume,completed,historyContainer,project,sche
|
||||
function adopt(task:ImportTask){
|
||||
owned.current.add(task.id);setTasks(values=>[task,...values.filter(value=>value.id!==task.id)]);
|
||||
}
|
||||
useEffect(()=>{
|
||||
if(!externalJob)return;
|
||||
const controller=new AbortController();
|
||||
void api<ImportTask>('/imports/'+encodeURIComponent(externalJob),{signal:controller.signal}).then(task=>{
|
||||
if(!controller.signal.aborted){adopt(task);return refreshRef.current();}
|
||||
}).catch(reason=>{if(!controller.signal.aborted)setError(reason);});
|
||||
return()=>controller.abort();
|
||||
},[externalJob]);
|
||||
async function refresh(){
|
||||
const values=await api<ImportTask[]>('/imports');setTasks(values);
|
||||
const prompt=values.find(task=>owned.current.has(task.id)&&(task.status==='waiting_options'||task.status==='waiting_scale'||task.status==='waiting_texture')&&!prompted.current.has(`${task.id}:${task.status}:${task.updated}`));
|
||||
@@ -138,6 +146,7 @@ export function Imports({request,consume,completed,historyContainer,project,sche
|
||||
setDecision(null);await refresh();
|
||||
}catch(reason){setError(reason);}finally{setBusy(false);}
|
||||
}
|
||||
const externalTask=externalJob&&tasks.find(task=>task.id===externalJob);
|
||||
const currentDecision=decision&&tasks.find(task=>task.id===decision.id);
|
||||
const pending=currentDecision&&decision?.status==='waiting_options'&¤tDecision.status==='waiting_texture'?{...currentDecision,status:'waiting_options'}:currentDecision;
|
||||
const history=<div className="import-history">{tasks.filter((task,index)=>!dismissed.current.has(task.id)&&(unfinished.has(task.status)||index<5)).map(task=><div key={task.id}>
|
||||
@@ -157,6 +166,11 @@ export function Imports({request,consume,completed,historyContainer,project,sche
|
||||
{!unfinished.has(task.status)&&<button onClick={()=>{dismissed.current.add(task.id);setTasks([...tasks]);}}>{t("Ukryj import")}</button>}
|
||||
</div>)}</div>;
|
||||
return <section aria-label={t("Import modeli")}>
|
||||
{externalTask&&externalTask.status!=='completed'&&<div className="archive-import-notice" role={externalTask.status==='failed'?'alert':'status'}>
|
||||
<p>{externalTask.names.join(', ')} · {localize(externalTask.message||externalTask.status)}</p>
|
||||
{['queued','running'].includes(externalTask.status)&&<progress max={100} value={externalTask.progress}/>}
|
||||
{['failed','interrupted'].includes(externalTask.status)&&<button disabled={busy} onClick={()=>void act(externalTask,'retry')}>{t('Ponów import')}</button>}
|
||||
</div>}
|
||||
<ArchiveImport request={archiveRequest} consume={consume} accepted={adopt} project={project} schema={schema} manage={manage} libraryChanged={libraryChanged}/>
|
||||
{machineImport&&!machineOpen&&<div className="archive-import-notice" role="status"><p>{t('An import is waiting for a physical printer.')}</p><button onClick={()=>setMachineOpen(true)}>{t('Resume import')}</button><button onClick={()=>setMachineImport(null)}>{t('Cancel')}</button></div>}
|
||||
{machineImport&&<ImportMachineChoice names={machineImport.files.map(file=>file.name)} project={project} open={machineOpen} busy={busy}
|
||||
|
||||
@@ -75,7 +75,7 @@ export function AuthBoundary({children}:{children:ReactNode}){
|
||||
<div key={session.user?.id??'anonymous'}>{children}</div>
|
||||
</AccountContext.Provider>;
|
||||
return <main className="local-login"><section aria-labelledby="local-login-title">
|
||||
<h1 id="local-login-title">{t('Sign in to Orca Web')}</h1>
|
||||
<h1 id="local-login-title">{t('Sign in to Web Slicer')}</h1>
|
||||
{!session?<><p>{t('Connecting to the server…')}</p>{error&&<p role="alert">{error}</p>}<button onClick={()=>window.location.reload()}>{t('Retry')}</button></>:
|
||||
session.secure_cookie&&window.location.protocol!=='https:'?<p role="alert">{t('HTTPS is required for sign in. Open the secure server address.')}</p>:<form onSubmit={login}>
|
||||
<label>{t('Username')}<input name="username" autoComplete="username" autoCapitalize="none" spellCheck={false} value={username} onChange={e=>setUsername(e.target.value)} required minLength={3} maxLength={64} disabled={busy}/></label>
|
||||
|
||||
@@ -9,15 +9,23 @@ import {PrinterImage,TemplatePicker} from './PrinterTemplatePicker';
|
||||
import {OwnedPrinterWizard} from './OwnedPrinterWizard';
|
||||
import {machinePath,type Machine,type MachineProfile,type MachinePreset,type PresetScope,type PrinterTemplate} from './machines';
|
||||
import './machineLibrary.css';
|
||||
import {cloudConnection,type AccountPrinter} from './BambuCloudConnection';
|
||||
import type {BambuCloudState} from './BambuCloudAccount';
|
||||
import {readPrinterState} from './readPrinterState';
|
||||
import {printerStateLabel,type PrinterStatusData} from './printerStatusTypes';
|
||||
import {ResourceAccess} from './ResourceAccess';
|
||||
import {useAuth} from './LocalAccount';
|
||||
|
||||
function AddMachine({templates,machine,done,cancel,onDirty}:{templates:PrinterTemplate[];machine?:Machine;
|
||||
function AddMachine({templates,machine,cloud,initialPrinter,done,cancel,onDirty}:{templates:PrinterTemplate[];machine?:Machine;
|
||||
cloud?:boolean;initialPrinter?:AccountPrinter;
|
||||
done:(value:Machine)=>void;cancel:()=>void;onDirty:(value:boolean)=>void}) {
|
||||
const identity=useRef(requestId());
|
||||
const [template,setTemplate]=useState<PrinterTemplate|null>(null),[name,setName]=useState('');
|
||||
const [accountPrinters,setAccountPrinters]=useState<AccountPrinter[]|null>(null);
|
||||
const [accountPrinter,setAccountPrinter]=useState<AccountPrinter|undefined>(initialPrinter);
|
||||
const bambuTemplates=templates.filter(value=>value.vendor==='BBL'||value.connection_hint==='bambu_lan');
|
||||
const matchedModel=bambuTemplates.filter(value=>value.model==='Bambu Lab '+accountPrinter?.model);
|
||||
const visibleTemplates=cloud?(matchedModel.length?matchedModel:bambuTemplates):templates;
|
||||
const [template,setTemplate]=useState<PrinterTemplate|null>(null),[name,setName]=useState(initialPrinter?.name.slice(0,128)??'');
|
||||
const [selectedTemplates,setSelectedTemplates]=useState<PrinterTemplate[]>([]),[variants,setVariants]=useState<Record<string,VariantDraft>>({});
|
||||
const [connect,setConnect]=useState(false),[connectionDirty,setConnectionDirty]=useState(false),[pending,setPending]=useState(false),[error,setError]=useError();
|
||||
const nameInput=useRef<HTMLInputElement>(null);
|
||||
@@ -26,6 +34,16 @@ function AddMachine({templates,machine,done,cancel,onDirty}:{templates:PrinterTe
|
||||
const valid=profiles.length>0&&!duplicateNames&&profiles.every(value=>value.name&&value.filament_templates.length&&variants[value.printer]?.ready);
|
||||
useEffect(()=>{onDirty(Boolean(template||name||connectionDirty));},[template,name,connectionDirty]);
|
||||
useEffect(()=>()=>onDirty(false),[]);
|
||||
useEffect(()=>{
|
||||
if(!cloud||initialPrinter)return;
|
||||
const controller=new AbortController();
|
||||
void api<{printers:AccountPrinter[]}>('/bambu-cloud/printers',{signal:controller.signal})
|
||||
.then(value=>setAccountPrinters(value.printers)).catch(reason=>{if(!controller.signal.aborted)setError(reason);});
|
||||
return()=>controller.abort();
|
||||
},[cloud,initialPrinter]);
|
||||
function selectAccountPrinter(printer:AccountPrinter){
|
||||
setAccountPrinter(printer);setName(printer.name.slice(0,128));setTemplate(null);setSelectedTemplates([]);
|
||||
}
|
||||
function choose(value:PrinterTemplate){
|
||||
const sameModel=template?.vendor===value.vendor&&template.model===value.model;
|
||||
if(!sameModel&&connectionDirty&&!window.confirm(t('Discard unsaved changes?')))return;
|
||||
@@ -38,6 +56,11 @@ function AddMachine({templates,machine,done,cancel,onDirty}:{templates:PrinterTe
|
||||
setTemplate(value);setSelectedTemplates([value]);setVariants({[value.name]:{name:label,filament_templates:[],ready:false}});
|
||||
setName(previous=>previous||value.model);setConnect(Boolean(value.connection_hint));setConnectionDirty(false);setError('');
|
||||
}
|
||||
useEffect(()=>{
|
||||
if(!accountPrinter||template||!matchedModel.length)return;
|
||||
const standard=matchedModel.find(value=>value.nozzles.length===1&&Number(value.nozzles[0])===0.4);
|
||||
if(standard)choose(standard);
|
||||
},[accountPrinter,template,templates]);
|
||||
async function save(connection:Record<string,unknown>|null){
|
||||
if(!template||pending)return;
|
||||
if(!valid){setError('Select printer presets with unique names and at least one filament each.');return;}
|
||||
@@ -63,18 +86,29 @@ function AddMachine({templates,machine,done,cancel,onDirty}:{templates:PrinterTe
|
||||
return <section className="machine-wizard">
|
||||
<header className="machine-heading"><h2>{t(machine?'Add profile':'Add printer')}</h2><button disabled={pending} onClick={cancel}>{t('Cancel')}</button></header>
|
||||
{error&&<p role="alert">{localize(error)}</p>}
|
||||
<TemplatePicker templates={templates} value={template} choose={choose} disabled={pending} multiple={!machine} selected={selectedTemplates}/>
|
||||
{cloud&&<div>
|
||||
{initialPrinter?<p>{initialPrinter.name}{initialPrinter.model&&' · '+initialPrinter.model}</p>:
|
||||
accountPrinters?<label>{t('Printer on the account')}<select value={accountPrinter?.dev_id??''} disabled={pending}
|
||||
onChange={event=>{const value=accountPrinters.find(printer=>printer.dev_id===event.target.value);if(value)selectAccountPrinter(value);}}>
|
||||
<option value="" disabled>{t('Select')}</option>{accountPrinters.map(printer=><option key={printer.dev_id} value={printer.dev_id}>
|
||||
{printer.name}{printer.model&&' · '+printer.model}</option>)}
|
||||
</select></label>:!error&&<p role="status">{t('Loading…')}</p>}
|
||||
{accountPrinters?.length===0&&<p>{t('No printers are bound to this Bambu Lab account.')}</p>}
|
||||
{accountPrinter&&<p>{t('Choose the model and nozzle preset for this cloud printer.')}</p>}
|
||||
</div>}
|
||||
{(!cloud||accountPrinter)&&<TemplatePicker templates={visibleTemplates} value={template} choose={choose} disabled={pending} multiple={!machine} selected={selectedTemplates}/>}
|
||||
{template&&<section className="machine-setup">
|
||||
{!machine&&<label>{t('Nazwa drukarki')}<input ref={nameInput} required maxLength={128} value={name} disabled={pending} onChange={event=>setName(event.target.value)}/></label>}
|
||||
{!machine&&<p>{t('Select the nozzle variants to create. Each has its own editable process and filament presets.')}</p>}
|
||||
{selectedTemplates.map(value=><PrinterVariantSetup key={value.name} template={value} value={variants[value.name]} disabled={pending}
|
||||
changed={draft=>setVariants(previous=>({...previous,[value.name]:draft}))}/>)}
|
||||
{duplicateNames&&<p role="alert">{t('Preset names must be unique.')}</p>}
|
||||
{!machine&&<label className="printer-checkbox"><input type="checkbox" disabled={pending} checked={connect} onChange={event=>{
|
||||
{!machine&&!cloud&&<label className="printer-checkbox"><input type="checkbox" disabled={pending} checked={connect} onChange={event=>{
|
||||
if(connectionDirty&&!window.confirm(t('Discard unsaved changes?')))return;
|
||||
setConnect(event.target.checked);setConnectionDirty(false);
|
||||
}}/>{t('Connection')}</label>}
|
||||
{!machine&&connect?<PrinterPanel key={template.name} inline creation={{name,type:template.connection_hint,save:async value=>save(value)}} onDirty={setConnectionDirty}/>:<>
|
||||
{accountPrinter?<button className="primary" disabled={pending||!valid||!name.trim()} onClick={()=>void save(cloudConnection(accountPrinter))}>{t('Add printer')}</button>:
|
||||
!machine&&connect?<PrinterPanel key={template.name} inline creation={{name,type:template.connection_hint,save:async value=>save(value)}} onDirty={setConnectionDirty}/>:<>
|
||||
{!machine&&<p>{t('No connection')}{' · '}{t('Export G-code')}</p>}
|
||||
<div className="dialog-actions"><button className="primary" disabled={pending||!valid||(!machine&&!name.trim())} onClick={()=>void save(null)}>{t(machine?'Add profile':'Add printer')}</button></div>
|
||||
</>}
|
||||
@@ -83,7 +117,8 @@ function AddMachine({templates,machine,done,cancel,onDirty}:{templates:PrinterTe
|
||||
</section>;
|
||||
}
|
||||
|
||||
export function MachineLibrary({active,token,changed,editPreset,onDirty,openDevice}:{active:boolean;token:number;changed:()=>void;
|
||||
export function MachineLibrary({active,token,changed,editPreset,onDirty,openDevice,bambuCloud,openBambuAccount,cloudRequest,consumeCloudRequest}:{active:boolean;token:number;changed:()=>void;
|
||||
bambuCloud?:BambuCloudState|null;openBambuAccount?:()=>void;cloudRequest?:AccountPrinter;consumeCloudRequest?:()=>void;
|
||||
editPreset:(machine:Machine,profile:MachineProfile,preset:MachinePreset)=>void;onDirty:(value:boolean)=>void;openDevice?:(id:string)=>void}) {
|
||||
const {user}=useAuth(),canAdd=!user||user.admin||user.can_add_printers;
|
||||
const [machines,setMachines]=useState<Machine[]>([]),[templates,setTemplates]=useState<PrinterTemplate[]>([]);
|
||||
@@ -107,7 +142,7 @@ export function MachineLibrary({active,token,changed,editPreset,onDirty,openDevi
|
||||
}
|
||||
}finally{if(statusRequest.current===abort){statusRequest.current=null;setReadingStatus(false);}}
|
||||
}
|
||||
const [selected,setSelected]=useState(''),[adding,setAdding]=useState<false|'machine'|'profile'|'custom-machine'|'custom-profile'>(false),[name,setName]=useState('');
|
||||
const [selected,setSelected]=useState(''),[adding,setAdding]=useState<false|'machine'|'cloud-machine'|'profile'|'custom-machine'|'custom-profile'>(false),[name,setName]=useState('');
|
||||
const [nameBase,setNameBase]=useState({name:'',revision:0});
|
||||
const [connectionReset,setConnectionReset]=useState(0);
|
||||
const [managing,setManaging]=useState<{profile:string;scope?:PresetScope;preset?:string;action?:LibraryAction}|null>(null);
|
||||
@@ -148,20 +183,33 @@ export function MachineLibrary({active,token,changed,editPreset,onDirty,openDevi
|
||||
async function mutate(work:()=>Promise<unknown>){setPending(true);setError('');try{await work();await load();changed();}catch(reason){setError(reason);}finally{setPending(false);}}
|
||||
const choose=(value:Machine)=>{if(!canLeave())return;clearDirty();setSelected(value.id);setName(value.name);setNameBase({name:value.name,revision:value.revision});setAdding(false);};
|
||||
const done=(value:Machine)=>{clearDirty();setMachines(previous=>[value,...previous.filter(p=>p.id!==value.id)]);setSelected(value.id);setName(value.name);setNameBase({name:value.name,revision:value.revision});setAdding(false);changed();};
|
||||
const [cloudPrinter,setCloudPrinter]=useState<AccountPrinter|undefined>();
|
||||
useEffect(()=>{
|
||||
if(!active||!canAdd||!cloudRequest)return;
|
||||
setCloudPrinter(cloudRequest);setAdding('cloud-machine');consumeCloudRequest?.();
|
||||
},[active,canAdd,cloudRequest,consumeCloudRequest]);
|
||||
const managed=machine?.profiles.find(profile=>profile.id===managing?.profile);
|
||||
if(machine&&managed&&canManage)return <OwnedLibraryManagement machine={machine} profile={managed} initialScope={managing?.scope} initialPreset={managing?.preset} initialAction={managing?.action} templates={templates} onDirty={markDirty}
|
||||
done={value=>{done(value);setManaging(null);}} cancel={()=>{clearDirty();setManaging(null);void load().catch(setError);}}/>;
|
||||
if((adding==='custom-machine'&&canAdd)||(adding==='custom-profile'&&canManage))return <OwnedPrinterWizard templates={templates} machine={adding==='custom-profile'?machine:undefined} done={done} onDirty={markDirty}
|
||||
cancel={()=>{if(canLeave()){clearDirty();setAdding(false);}}}/>;
|
||||
if(adding&&(adding==='profile'?canManage:canAdd))return <AddMachine templates={templates} machine={adding==='profile'?machine:undefined} done={done} onDirty={markDirty}
|
||||
if(adding&&(adding==='profile'?canManage:canAdd))return <AddMachine key={adding} templates={templates} cloud={adding==='cloud-machine'} initialPrinter={adding==='cloud-machine'?cloudPrinter:undefined} machine={adding==='profile'?machine:undefined} done={done} onDirty={markDirty}
|
||||
cancel={()=>{if(canLeave()){clearDirty();setAdding(false);}}}/>;
|
||||
return <section className="machine-library">
|
||||
<header className="machine-heading"><h1>{t('Printers')}</h1><div className="dialog-actions">
|
||||
{canAdd&&<button className="primary" disabled={pending||loading||!templates.length} onClick={()=>{if(canLeave()){clearDirty();setAdding('machine');}}}>{t('Add printer')}</button>}
|
||||
{canAdd&&bambuCloud?.available&&bambuCloud.logged_in&&<button disabled={pending||loading||!templates.length} onClick={()=>{
|
||||
if(!canLeave())return;
|
||||
clearDirty();setCloudPrinter(undefined);setAdding('cloud-machine');
|
||||
}}>{t('Add from Bambu Lab account')}</button>}
|
||||
{canAdd&&<button disabled={pending||loading||!templates.length} onClick={()=>{if(canLeave()){clearDirty();setAdding('custom-machine');}}}>{t('Create custom printer')}</button>}
|
||||
<button disabled={pending||loading} onClick={()=>{if(canLeave()){clearDirty();void load(true).catch(setError);}}}>{t('Reload')}</button>
|
||||
<button disabled={loading||readingStatus||!machines.some(value=>value.has_connection&&(value.access?.role!=='member'||value.access.permissions.monitor))} onClick={()=>void refreshStatus()}>{t(readingStatus?'Loading…':'Refresh status')}</button>
|
||||
</div></header>
|
||||
{bambuCloud?.available&&<section className="printer-cloud-account" aria-label={t('Bambu Lab account')}>
|
||||
<div><h2>{t('Bambu Lab account')}</h2><p>{t(bambuCloud.logged_in?'Signed in':'Not signed in')}</p></div>
|
||||
<button type="button" onClick={openBambuAccount}>{t(bambuCloud.logged_in?'Manage account':'Sign in')}</button>
|
||||
</section>}
|
||||
{error&&<p role="alert">{localize(error)}</p>}
|
||||
{loading&&<p role="status">{t('Loading…')}</p>}
|
||||
<div className="catalog-printer-grid">{machines.map(value=><button key={value.id} className={`catalog-printer-card machine-card ${value.id===selected?'is-selected':''}`} aria-pressed={value.id===selected} disabled={pending||!libraryReady} onClick={()=>choose(value)}>
|
||||
|
||||
@@ -72,9 +72,11 @@ export function PhysicalMaterials({printerId,revision,operation,disabled,onWorkL
|
||||
async function read(quiet=false){
|
||||
if(quiet&&streaming&&!live.current)return;
|
||||
if(reading.current)return;reading.current=true;const controller=new AbortController();request.current=controller;if(!quiet)setBusy(true);setError('');
|
||||
try{const state=await readPrinterState<MaterialState>(`${printerPath(printerId)}/filament-state?revision=${revision}${quiet?(streaming?'&observe=true':''):'&fresh=true'}`,controller.signal);
|
||||
try{const [state,available]=await Promise.all([
|
||||
readPrinterState<MaterialState>(`${printerPath(printerId)}/filament-state?revision=${revision}${quiet?(streaming?'&observe=true':''):'&fresh=true'}`,controller.signal),
|
||||
quiet&&followFeeder?null:api<FilamentProduct[]>(`/filament-products?machine_id=${printerId}`,{signal:controller.signal}),
|
||||
]);
|
||||
if(state.revision!==revision)throw new Error('The printer connection changed. Reload it before reading filament state.');
|
||||
const available=quiet&&followFeeder?null:await api<FilamentProduct[]>(`/filament-products?machine_id=${printerId}`,{signal:controller.signal});
|
||||
if(!controller.signal.aborted){
|
||||
setView(state);if(available)setProducts(available);setStale(false);setOffline(false);
|
||||
const command=operation.filament as {source?:string;operation?:string;box_id?:number;material_id?:number;material?:string;color?:string;minimum?:number;maximum?:number}|undefined;
|
||||
@@ -178,7 +180,8 @@ export function PhysicalMaterials({printerId,revision,operation,disabled,onWorkL
|
||||
return <article key={key} className="device-material-slot" data-active={slot.active}>
|
||||
<strong>{t(slot.name)}</strong>
|
||||
<div className="device-material-heading">
|
||||
<SlotColorPicker color={slot.color} disabled={locked||!slot.operations.includes('set_material')||slot.editable_fields?.includes('color')===false||!slot.material.trim()} title={slot.material.trim()?t('Change slot color'):t('Set the slot material first')} label={`${t('Change slot color')} · ${module.name} · ${slot.name}`}
|
||||
{slot.identity?.rgba?.endsWith('00')&&slot.material&&<span className="transparent-filament">{t('Transparent')}</span>}
|
||||
<SlotColorPicker color={slot.color} transparent={slot.identity?.rgba?.endsWith('00')} disabled={locked||!slot.operations.includes('set_material')||slot.editable_fields?.includes('color')===false||!slot.material.trim()} title={slot.material.trim()?t('Change slot color'):t('Set the slot material first')} label={`${t('Change slot color')} · ${module.name} · ${slot.name}`}
|
||||
commit={value=>void send({source:'physical',operation:'set_material',box_id:slot.box_id,material_id:slot.material_id,material:slot.material,color:value})}/>
|
||||
<button type="button" disabled={locked||!slot.operations.includes('set_material')||slot.editable_fields?.includes('material')===false} aria-label={`${t('Change slot material')} · ${module.name} · ${slot.name}`} title={t(slot.editable_fields?.includes('material')===false?'Choose a filament product to change the material':'Change slot material')}
|
||||
onClick={()=>{setEdit(editing?'':key);setMaterial(slot.material);}}>{slot.material||t('Unknown')}</button>
|
||||
|
||||
@@ -81,7 +81,7 @@ export function Preview({job,source,bed,bedAssets=false,section,layerEvents,layo
|
||||
const [timeMode, setTimeMode] = useState('normal');
|
||||
const [error, setError] = useError();
|
||||
const [moves, setMoves] = useState<NativeMoveSelection | null>(null);
|
||||
const [moveRange, setMoveRange] = useState({domain: '', first: 0, last: -1});
|
||||
const [moveRange, setMoveRange] = useState({domain: '', last: -1});
|
||||
const [playing,setPlaying]=useState(false);
|
||||
const [speed,setSpeed]=useState(10);
|
||||
const [markerOptions, setMarkerOptions] = useState<Record<string, boolean>>({});
|
||||
@@ -99,20 +99,20 @@ export function Preview({job,source,bed,bedAssets=false,section,layerEvents,layo
|
||||
setLayer(value - 1); setFirstLayer(current => Math.min(current, value - 1));
|
||||
}, previewShown);
|
||||
const moveDomain = JSON.stringify([resource.id, firstLayer, layer, travel, wipe, hiddenRoles, markerOptions]);
|
||||
const firstMove = moveRange.domain === moveDomain ? moveRange.first : 0;
|
||||
const firstMove = 0;
|
||||
const lastMove = moveRange.domain === moveDomain ? moveRange.last : -1;
|
||||
const moveInfo = moves?.domain === moveDomain && moves.sourceId===resource.id ? moves : null;
|
||||
useEffect(() => {setPlaying(false);setMoveRange({domain: moveDomain, first: 0, last: -1});}, [moveDomain]);
|
||||
useEffect(() => {setPlaying(false);setMoveRange({domain: moveDomain, last: -1});}, [moveDomain]);
|
||||
useEffect(()=>{
|
||||
if(!playing||!moveInfo?.count)return;
|
||||
const step=Math.max(1,Math.floor(speed/20)),count=moveInfo.count;
|
||||
const timer=setInterval(()=>setMoveRange(current=>({domain:moveDomain,first:current.domain===moveDomain?current.first:0,
|
||||
const timer=setInterval(()=>setMoveRange(current=>({domain:moveDomain,
|
||||
last:Math.min(count-1,(current.domain===moveDomain&¤t.last>=0?current.last:0)+step)})),1000*step/speed);
|
||||
return()=>clearInterval(timer);
|
||||
},[playing,speed,moveDomain,moveInfo?.count]);
|
||||
useEffect(()=>{if(playing&&moveInfo&&lastMove>=moveInfo.count-1)setPlaying(false);},[playing,lastMove,moveInfo?.count]);
|
||||
useEffect(()=>{const pause=()=>{if(document.hidden)setPlaying(false);};document.addEventListener('visibilitychange',pause);return()=>document.removeEventListener('visibilitychange',pause);},[]);
|
||||
function seekMove(last:number){setPlaying(false);setMoveRange({domain:moveDomain,first:firstMove,last});}
|
||||
function seekMove(last:number){setPlaying(false);setMoveRange({domain:moveDomain,last});}
|
||||
const native = meta?.header.native_input?.format === 'ORCAVG01' && Boolean(meta.header.renderer_roles);
|
||||
const automaticMode = native && materials.length > 1 ? 'color_print' : 'role';
|
||||
const mode = chosenMode !== null && (native || !['summary', 'color_print'].includes(chosenMode)) ? chosenMode : automaticMode;
|
||||
@@ -130,12 +130,13 @@ export function Preview({job,source,bed,bedAssets=false,section,layerEvents,layo
|
||||
const ranges = meta?.header.range_variants?.[timeMode]?.[String(mask)];
|
||||
const range = ranges?.[mode];
|
||||
useEffect(() => {
|
||||
let active = true;setMeta(null);setMoves(null);setPlaying(false);setError('');
|
||||
const controller = new AbortController();
|
||||
setMeta(null);setMoves(null);setPlaying(false);setError('');
|
||||
setLoadProgress({phase:'metadata',received:0,lastByteAt:Date.now()});
|
||||
void api<Metadata>(`${resource.basePath}/preview`).then(value => {
|
||||
if (active) {setMeta(value); setFirstLayer(0); setLayer(Math.max(0, value.layers.length - 1)); setHiddenRoles([]);}
|
||||
}).catch(reason => {if (active) setError(reason);});
|
||||
return () => {active = false;};
|
||||
void api<Metadata>(`${resource.basePath}/preview`,{signal:controller.signal}).then(value => {
|
||||
if (!controller.signal.aborted) {setMeta(value); setFirstLayer(0); setLayer(Math.max(0, value.layers.length - 1)); setHiddenRoles([]);}
|
||||
}).catch(reason => {if (!controller.signal.aborted) setError(reason);});
|
||||
return () => controller.abort();
|
||||
}, [resource.basePath,attempt]);
|
||||
async function load(signal: AbortSignal) {
|
||||
if (!meta) return new THREE.Group();
|
||||
@@ -192,8 +193,6 @@ export function Preview({job,source,bed,bedAssets=false,section,layerEvents,layo
|
||||
const controls=<> <div className="preview-controls">
|
||||
{native && <label>{t("Od warstwy ")}{localize(firstLayer + 1)} {t(" · Z ")}{localize(meta.layers[firstLayer].z.toFixed(2))} {t(" mm")}<input aria-label={t("Pierwsza warstwa")} type="range" min={0} max={meta.layers.length - 1} value={firstLayer}
|
||||
onChange={event => {const value = Number(event.target.value); setFirstLayer(value); setLayer(current => Math.max(current, value));}}/></label>}
|
||||
<label>{t("Warstwa ")}{localize(layer + 1)} {t(" · Z ")}{localize(meta.layers[layer].z.toFixed(2))} {t(" mm")}<input aria-label={t("Warstwa")} type="range" min={0} max={meta.layers.length - 1} value={layer}
|
||||
onChange={event => {const value = Number(event.target.value); setLayer(value); setFirstLayer(current => Math.min(current, value));}}/></label>
|
||||
{native && <>
|
||||
<button onClick={() => setFirstLayer(layer)}>{t("Tylko ta warstwa")}</button>
|
||||
<button onClick={() => {setFirstLayer(0); setLayer(meta.layers.length - 1);}}>{t("Cały wydruk")}</button>
|
||||
@@ -242,21 +241,18 @@ export function Preview({job,source,bed,bedAssets=false,section,layerEvents,layo
|
||||
</details>}
|
||||
{range !== undefined && <NumericLegend mode={mode} title={localize(previewModes.find(([key])=>key===mode)?.[1]??mode)} range={range}/>}
|
||||
</>;
|
||||
const playback=<> {native && moveInfo && moveInfo.count > 0 && <div className="preview-controls move-controls">
|
||||
<label>{t("Od ruchu ")}{localize(firstMove + 1)}
|
||||
<input aria-label={t("Pierwszy ruch")} type="range" min={0} max={moveInfo.count - 1} value={firstMove}
|
||||
onChange={event => {const first = Number(event.target.value);
|
||||
setPlaying(false);setMoveRange({domain: moveDomain, first, last: Math.max(first, lastMove === -1 ? moveInfo.count - 1 : lastMove)});}}/></label>
|
||||
const playback=<><div className="layer-limit"><label>{t(native?"Do warstwy ":"Warstwa ")}{localize(layer + 1)} {t(" · Z ")}{localize(meta.layers[layer].z.toFixed(2))} {t(" mm")}<input aria-label={t("Warstwa")} type="range" min={0} max={meta.layers.length - 1} value={layer}
|
||||
onChange={event => {const value = Number(event.target.value); setLayer(value); setFirstLayer(current => Math.min(current, value));}}/></label></div>
|
||||
{native && moveInfo && moveInfo.count > 0 && <div className="preview-controls move-controls">
|
||||
<label>{t("Do ruchu ")}{localize((lastMove === -1 ? moveInfo.count - 1 : lastMove) + 1)} {t(" z ")}{localize(moveInfo.count)}
|
||||
<input aria-label={t("Ostatni ruch")} type="range" min={0} max={moveInfo.count - 1}
|
||||
value={lastMove === -1 ? moveInfo.count - 1 : lastMove}
|
||||
onChange={event => {const last = Number(event.target.value);
|
||||
setPlaying(false);setMoveRange({domain: moveDomain, first: Math.min(firstMove, last), last});}}/></label>
|
||||
onChange={event => seekMove(Number(event.target.value))}/></label>
|
||||
<div className="playback-transport">
|
||||
<PlaybackButton kind="all" label={t("Wszystkie ruchy")} onClick={()=>{setPlaying(false);setMoveRange({domain:moveDomain,first:0,last:-1});}}/>
|
||||
<PlaybackButton kind="all" label={t("Wszystkie ruchy")} onClick={()=>{setPlaying(false);setMoveRange({domain:moveDomain,last:-1});}}/>
|
||||
<PlaybackButton kind="start" label={t("Początek zakresu ruchów")} onClick={()=>seekMove(firstMove)}/>
|
||||
<PlaybackButton kind="previous" label={t("Poprzedni ruch")} disabled={(lastMove===-1?moveInfo.count-1:lastMove)<=firstMove} onClick={()=>seekMove(Math.max(firstMove,(lastMove===-1?moveInfo.count-1:lastMove)-1))}/>
|
||||
<PlaybackButton kind={playing?'pause':'play'} label={t(playing?'Pauza odtwarzania':'Odtwórz ruchy')} onClick={()=>{if(playing){setPlaying(false);return;}if(lastMove===-1||lastMove>=moveInfo.count-1)setMoveRange({domain:moveDomain,first:firstMove,last:firstMove});setPlaying(true);}}/>
|
||||
<PlaybackButton kind={playing?'pause':'play'} label={t(playing?'Pauza odtwarzania':'Odtwórz ruchy')} onClick={()=>{if(playing){setPlaying(false);return;}if(lastMove===-1||lastMove>=moveInfo.count-1)setMoveRange({domain:moveDomain,last:firstMove});setPlaying(true);}}/>
|
||||
<PlaybackButton kind="next" label={t("Następny ruch")} disabled={lastMove===-1||lastMove>=moveInfo.count-1} onClick={()=>seekMove(Math.min(moveInfo.count-1,lastMove+1))}/>
|
||||
<PlaybackButton kind="end" label={t("Koniec zakresu ruchów")} onClick={()=>seekMove(moveInfo.count-1)}/>
|
||||
<label>{t("Tempo odtwarzania")}<select aria-label={t("Tempo odtwarzania")} value={speed} onChange={event=>setSpeed(Number(event.target.value))}>
|
||||
|
||||
@@ -4,6 +4,8 @@ import {api,jsonRequest,requestId} from './api';
|
||||
import {useAuth} from './LocalAccount';
|
||||
import {ResourceAccess,type ResourceAccessState} from './ResourceAccess';
|
||||
import {SendPanel} from './SendPanel';
|
||||
import {BambuCloudAccount,type BambuCloudState,type BambuPrintTarget} from './BambuCloudAccount';
|
||||
import type {PrinterConnection} from './printerConnections';
|
||||
import {errorText} from './uiErrors';
|
||||
import {localeTag,t} from './i18n';
|
||||
import type {Job} from './types';
|
||||
@@ -76,26 +78,51 @@ export function RequestPrint({job,name,stale,trigger}:{job:Job;name:string;stale
|
||||
</>;
|
||||
}
|
||||
|
||||
export function PrintAction(props:{job:Job;name:string;stale:boolean;onOpenMonitor?:(id:string)=>void;trigger?:(open:(()=>void)|null,label:string)=>ReactNode}){
|
||||
export function PrintAction(props:{job:Job;name:string;stale:boolean;onOpenMonitor?:(id:string)=>void;
|
||||
onReslice?:()=>void;bambu?:{state:BambuCloudState|null;changed:(value:BambuCloudState)=>void};
|
||||
trigger?:(open:(()=>void)|null,label:string)=>ReactNode}){
|
||||
const {user}=useAuth();
|
||||
const direct=!user||user.admin;
|
||||
const [target,setTarget]=useState<{machine_id:string;machine_name:string;connection:PrinterConnection|null}|null>(null);
|
||||
const [access,setAccess]=useState<ResourceAccessState|null>(null),[error,setError]=useState(''),[retry,setRetry]=useState(0);
|
||||
const [cloudTarget,setCloudTarget]=useState<BambuPrintTarget|null>(null);
|
||||
const reslice=useRef<HTMLDialogElement>(null);
|
||||
useEffect(()=>{
|
||||
if(!user||user.admin)return;
|
||||
if(direct&&!props.bambu)return;
|
||||
const controller=new AbortController();let current=0;
|
||||
const refresh=async()=>{
|
||||
const generation=++current;
|
||||
try{
|
||||
const target=await api<{machine_id:string}>(`/jobs/${props.job.id}/dispatch-target`,{signal:controller.signal});
|
||||
const value=await api<ResourceAccessState>(`/machines/${target.machine_id}/access`,{signal:controller.signal});
|
||||
if(!controller.signal.aborted&&generation===current){setAccess(value);setError('');}
|
||||
}catch(reason){if(!controller.signal.aborted&&generation===current){setAccess(null);setError(errorText(reason,false));}}
|
||||
const value=await api<NonNullable<typeof target>>(`/jobs/${props.job.id}/dispatch-target`,{signal:controller.signal});
|
||||
const permissions=direct?null:await api<ResourceAccessState>(`/machines/${value.machine_id}/access`,{signal:controller.signal});
|
||||
if(!controller.signal.aborted&&generation===current){setTarget(value);setAccess(permissions);setError('');}
|
||||
}catch(reason){if(!controller.signal.aborted&&generation===current){setTarget(null);setAccess(null);setError(errorText(reason,false));}}
|
||||
};
|
||||
void refresh();const timer=window.setInterval(()=>void refresh(),30_000);
|
||||
return()=>{controller.abort();clearInterval(timer);};
|
||||
},[props.job.id,user?.id,retry]);
|
||||
if(!user||user.admin||access?.permissions?.direct_print)return <SendPanel {...props}/>;
|
||||
// Without print access yet, the trigger still offers the downloads.
|
||||
},[props.job.id,user?.id,retry,direct,Boolean(props.bambu)]);
|
||||
if(error)return <>{props.trigger?.(null,'')}<span className="request-action-error" role="status">{error} <button onClick={()=>setRetry(value=>value+1)}>{t('Check printer access')}</button></span></>;
|
||||
if(!access)return <>{props.trigger?.(null,'')}<span role="status">{t('Checking printer access…')}</span></>;
|
||||
return <RequestPrint job={props.job} name={props.name} stale={props.stale} trigger={props.trigger}/>;
|
||||
if((!direct&&!access)||(props.bambu&&!target))return <>{props.trigger?.(null,'')}<span role="status">{t('Checking printer access…')}</span></>;
|
||||
if(!direct&&!access?.permissions?.direct_print)return <RequestPrint job={props.job} name={props.name} stale={props.stale} trigger={props.trigger}/>;
|
||||
const connection=target?.connection;
|
||||
if(connection?.type==='bambu_lan'&&props.onReslice&&props.job.result?.upload_format!=='gcode_3mf'){
|
||||
const open=()=>reslice.current?.showModal();
|
||||
return <>{props.trigger?props.trigger(open,t('Print')):<button onClick={open}>{t('Print')}</button>}
|
||||
<dialog ref={reslice} className="about-dialog" aria-label={t('Print')}>
|
||||
<h2>{t('Slice again for Bambu Lab')}</h2><p>{t('The saved printer needs a sliced 3MF. Slice the current project to create one.')}</p>
|
||||
<div className="about-actions"><button onClick={()=>reslice.current?.close()}>{t('Cancel')}</button>
|
||||
<button className="primary" onClick={()=>{reslice.current?.close();props.onReslice?.();}}>{t('Slice again')}</button></div>
|
||||
</dialog></>;
|
||||
}
|
||||
const serial=connection?.bambu_serial_number;
|
||||
if(target&&connection?.type==='bambu_lan'&&connection.bambu_transport==='cloud'&&typeof serial==='string'&&props.bambu){
|
||||
const open=()=>setCloudTarget({serial,name:target.machine_name,revision:connection.revision});
|
||||
return <>{props.trigger?props.trigger(open,t('Print')):<button onClick={open}>{t('Print')}</button>}
|
||||
{cloudTarget&&<BambuCloudAccount close={()=>setCloudTarget(null)} state={props.bambu.state??{available:false}}
|
||||
changed={props.bambu.changed} job={props.job} target={cloudTarget}/>}
|
||||
</>;
|
||||
}
|
||||
const trigger=props.trigger;
|
||||
return <SendPanel {...props} trigger={connection?.type==='bambu_lan'&&trigger?
|
||||
open=>trigger(open,t('Print')):trigger}/>;
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import {connectionDraft,printerPath,uploadMethods,startMethods,usablePrinterAgen
|
||||
import {RemoteConnectionOptions,AdvancedConnectionOptions,type DeviceAgentChoice} from './ConnectionOptions';
|
||||
import {PrinterPairing,PendingPairings,pendingPairingId,isPendingPairing,type Pairing} from './PrinterPairing';
|
||||
import {PrinterAgentDiscovery} from './PrinterAgentDiscovery';
|
||||
import {BambuCloudConnection,isCloudDraft} from './BambuCloudConnection';
|
||||
import {BambuCloudConnection,CLOUD_HOST,CLOUD_TYPE,isCloudDraft} from './BambuCloudConnection';
|
||||
import {machineConnection,machinePath,type Machine} from './machines';
|
||||
|
||||
interface DiscoveredHost {name:string;host:string;flashforge_serial_number?:string;bambu_serial_number?:string;printer_model?:string;}
|
||||
@@ -39,6 +39,13 @@ export function PrinterPanel({inline=false,active=true,machineId,creation,onChan
|
||||
useEffect(()=>()=>dirtyCallback.current?.(false),[]);
|
||||
const spec=types.find(value=>value.id===draft.type);
|
||||
const cloudBambu=isCloudDraft(draft);
|
||||
const [cloudState,setCloudState]=useState<{available:boolean;logged_in?:boolean}|null>(null);
|
||||
useEffect(()=>{
|
||||
if(!active)return;
|
||||
const controller=new AbortController();
|
||||
void api<{available:boolean;logged_in?:boolean}>('/bambu-cloud',{signal:controller.signal}).then(setCloudState).catch(()=>{});
|
||||
return()=>controller.abort();
|
||||
},[active]);
|
||||
const showDeviceKey=!cloudBambu&&!!spec?.auth_types.includes('api_key')&&(draft.auth_type!=='digest'||!!spec.api_key_with_digest);
|
||||
const reference=draft.plugin_agent as PluginAgentReference|null;
|
||||
const agent=agents.find(value=>value.plugin===reference?.id&&value.capability===reference?.capability);
|
||||
@@ -81,11 +88,12 @@ export function PrinterPanel({inline=false,active=true,machineId,creation,onChan
|
||||
}
|
||||
useEffect(()=>{if(inline&&active&&(!printer||machineId&&machineId!==identity))void action(()=>load(machineId??identity));},[inline,active,machineId]);
|
||||
const discard=()=>!dirty||window.confirm(t('Discard unsaved changes?'));
|
||||
function chooseType(type:string){
|
||||
function chooseType(selection:string){
|
||||
const cloud=selection===CLOUD_TYPE,type=cloud?'bambu_lan':selection;
|
||||
const next=types.find(value=>value.id===type);
|
||||
setDraft(previous=>({...previous,type,auth_type:next?.auth_types.includes(String(previous.auth_type))?previous.auth_type:next?.auth_types[0],
|
||||
setDraft(previous=>({...previous,type,host:cloud?CLOUD_HOST:isCloudDraft(previous)?'':previous.host,auth_type:next?.auth_types.includes(String(previous.auth_type))?previous.auth_type:next?.auth_types[0],
|
||||
device_agent:'',plugin_agent:null,printer_slug:'',model_group:'#',console_host:'',console_port:null,
|
||||
websocket_url:'',bambu_serial_number:'',bambu_transport:'lan',flashforge_serial_number:'',printer_model:'',simplyprint_panel_url:'',camera_origins:[],
|
||||
websocket_url:'',bambu_serial_number:'',bambu_transport:cloud?'cloud':'lan',flashforge_serial_number:'',printer_model:'',simplyprint_panel_url:'',camera_origins:[],
|
||||
upload_timeout_seconds:null}));setDiscovered([]);setSearched(false);setMessage('');
|
||||
}
|
||||
function chooseAgent(value:string){
|
||||
@@ -140,7 +148,7 @@ export function PrinterPanel({inline=false,active=true,machineId,creation,onChan
|
||||
{saveRecovery&&<p className="connection-description" aria-live="polite">{t(saveRecovery==='conflict'?'This connection was changed elsewhere. Your changes were not saved. Load saved settings before editing again.':'The save result is unknown. Load saved settings to check the server before saving again. Your form changes are preserved until then.')}</p>}
|
||||
{message&&<p role="status">{message}</p>}
|
||||
{pairingActive&&<p>{t('Finish or cancel device pairing before editing or deleting this connection.')}</p>}
|
||||
<form onSubmit={event=>{event.preventDefault();if(!printer||busy||saveRecovery)return;void action(async()=>{
|
||||
<form onSubmit={event=>{event.preventDefault();if(!printer||busy||saveRecovery||cloudBambu&&(!cloudState?.logged_in||!draft.bambu_serial_number))return;void action(async()=>{
|
||||
const payload=connectionPayload();
|
||||
if(creation){await creation.save({...payload,name:creation.name});return;}
|
||||
let value:PrinterConnection;
|
||||
@@ -154,10 +162,12 @@ export function PrinterPanel({inline=false,active=true,machineId,creation,onChan
|
||||
});}}>
|
||||
<fieldset disabled={busy||!printer||pairingActive}>
|
||||
{!machineId&&!creation&&input('name','Nazwa drukarki',{required:true,max:128})}
|
||||
<label>{t('Host type')}<select required value={String(draft.type??'')} onChange={event=>chooseType(event.target.value)}>
|
||||
<label>{t('Host type')}<select required value={cloudBambu?CLOUD_TYPE:String(draft.type??'')} onChange={event=>chooseType(event.target.value)}>
|
||||
<option disabled value="">{t('Select')}</option>{types.map(value=><option key={value.id} value={value.id}>{value.name}</option>)}
|
||||
{types.some(value=>value.id==='bambu_lan')&&<option value={CLOUD_TYPE}>{t('Bambu Lab cloud')}</option>}
|
||||
</select></label>
|
||||
{draft.type==='bambu_lan'&&<BambuCloudConnection draft={draft} field={field}/>}
|
||||
{cloudBambu&&cloudState?.available===false&&<p>{t('Bambu Lab cloud requires a cloud-enabled build.')}</p>}
|
||||
{cloudBambu&&cloudState?.available!==false&&<BambuCloudConnection draft={draft} field={field} signedIn={Boolean(cloudState?.logged_in)}/>}
|
||||
{!cloudBambu&&input('host','Adres serwera druku',{required:true})}
|
||||
{!cloudBambu&&<label>{t('Authentication')}<select value={String(draft.auth_type??'')} onChange={event=>field('auth_type',event.target.value)}>
|
||||
{(spec?.auth_types??[]).map(value=><option key={value} value={value}>{t(value==='api_key'?(spec?.api_key_label??'API key'):{none:'None',basic:'Basic authentication',digest:'Digest authentication'}[value]??value)}</option>)}
|
||||
@@ -233,7 +243,7 @@ export function PrinterPanel({inline=false,active=true,machineId,creation,onChan
|
||||
</>}
|
||||
</section>}
|
||||
{spec&&printer&&<AdvancedConnectionOptions key={`advanced:${identity}:${printer.revision}:${spec.id}`} printer={printer} spec={spec} draft={draft} field={field}/>}
|
||||
<div className="connection-form-actions"><button type="submit" className="primary" disabled={!!saveRecovery||(!creation&&!dirty)||!spec||(draft.type==='plugin'&&!validAgent)}>{t(creation?'Add printer':'Zapisz połączenie')}</button></div>
|
||||
<div className="connection-form-actions"><button type="submit" className="primary" disabled={!!saveRecovery||(!creation&&!dirty)||!spec||(cloudBambu&&(!cloudState?.logged_in||!draft.bambu_serial_number))||(draft.type==='plugin'&&!validAgent)}>{t(creation?'Add printer':'Zapisz połączenie')}</button></div>
|
||||
</fieldset>
|
||||
</form>
|
||||
{draft.type==='plugin'&&agent&&<PrinterAgentDiscovery key={`${identity}:${agent.plugin}:${agent.capability}`} agent={agent} active={active} busy={busy||pairingActive} onBusy={setBusy} refresh={refreshAgents}
|
||||
|
||||
@@ -13,7 +13,12 @@ export function PrinterImage({template,vendor,model}:{template?:PrinterTemplate;
|
||||
export function TemplatePicker({templates,value,choose,disabled,multiple=false,selected=[]}:{templates:PrinterTemplate[];value:PrinterTemplate|null;choose:(value:PrinterTemplate)=>void;disabled:boolean;multiple?:boolean;selected?:PrinterTemplate[]}) {
|
||||
const [query,setQuery]=useState(''),[vendor,setVendor]=useState(''),[limit,setLimit]=useState(24);
|
||||
const [expanded,setExpanded]=useState(!value);
|
||||
const matches=templates.filter(p=>(!vendor||p.vendor===vendor)&&`${p.vendor_name??p.vendor} ${p.model} ${p.name}`.toLocaleLowerCase().includes(query.toLocaleLowerCase()));
|
||||
const words=query.trim().toLowerCase().split(/\s+/).filter(Boolean);
|
||||
const matches=templates.filter(template=>{
|
||||
if(vendor&&template.vendor!==vendor)return false;
|
||||
const text=[template.vendor,template.vendor_name,template.model,template.name,template.display_name].join(' ').toLowerCase();
|
||||
return words.every(word=>text.includes(word));
|
||||
});
|
||||
const groups=new Map<string,PrinterTemplate[]>();
|
||||
for(const item of matches){const key=item.vendor+'\0'+item.model;groups.set(key,[...(groups.get(key)??[]),item]);}
|
||||
useEffect(()=>setLimit(24),[query,vendor]);
|
||||
|
||||
@@ -23,7 +23,7 @@ const label=(item:{name:string;payload?:{display_name?:string}})=>item.payload?.
|
||||
const receiptKey='orca-preset-bundle-review';
|
||||
function remember(id:string|null,body:Commit|null=null){try{if(id)localStorage.setItem(receiptKey,JSON.stringify({id,body}));else localStorage.removeItem(receiptKey);}catch{/* Server pending imports also recover uploads without browser storage. */}}
|
||||
|
||||
export function ProfileBundles({close,changed,schema={},openAccount}:{close:()=>void;changed:()=>void;schema?:Record<string,Option>;openAccount?:()=>void}){
|
||||
export function ProfileBundles({close,changed,schema={},openAccount,bambuCloud}:{close:()=>void;changed:()=>void;schema?:Record<string,Option>;openAccount?:()=>void;bambuCloud?:boolean}){
|
||||
const dialog=useRef<HTMLDialogElement>(null),request=useRef<AbortController|null>(null),lock=useRef(false),mounted=useRef(true);
|
||||
const [tab,setTab]=useState<'import'|'export'|'installed'|'cloud'>('import'),[childBusy,setChildBusy]=useState(false),[busy,setBusy]=useState(false),[error,setError]=useState<unknown>(null),[message,setMessage]=useState('');
|
||||
const [file,setFile]=useState<File|null>(null),[preserve,setPreserve]=useState(true),[replace,setReplace]=useState(false);
|
||||
@@ -109,6 +109,10 @@ export function ProfileBundles({close,changed,schema={},openAccount}:{close:()=>
|
||||
<label>{t('File')}<FileInput accept=".json,.zip,.orca_printer,.orca_filament,.orca_bundle" aria-label={t('Import Configs')} onChange={event=>setFile(event.currentTarget.files?.[0]??null)}/></label>
|
||||
<label><input type="checkbox" checked={preserve} onChange={event=>{setPreserve(event.target.checked);if(!event.target.checked)setReplace(false);}}/>{t('Preserve package identities')}</label>
|
||||
<label title={!preserve?t('Preserve package identities before replacing a package.'):undefined}><input type="checkbox" disabled={!preserve} checked={replace} onChange={event=>setReplace(event.target.checked)}/>{t('Replace complete packages (review removed presets before import)')}</label>
|
||||
{bambuCloud&&<button disabled={plan?.status==='pending'} onClick={()=>void action(async()=>{
|
||||
review(await api<Plan>('/user-profile-imports/bambu-cloud',jsonRequest('POST',{})));
|
||||
await load();
|
||||
})}>{t('Fetch presets from Bambu Lab')}</button>}
|
||||
<button disabled={!file||!!plan&&plan.status==='pending'} onClick={()=>void action(stage)}>{t('Review import')}</button>
|
||||
</fieldset>
|
||||
<section aria-label={t('Pending imports')}><h3>{t('Pending imports')}</h3><button disabled={busy} onClick={()=>void action(load)}>{t('Refresh')}</button>
|
||||
|
||||
@@ -29,14 +29,16 @@ export function ProjectPhysicalFilament({machine,profileId,presetId,products,dis
|
||||
return <div className="project-physical-filament">
|
||||
{source&&<><small>{t('Printer slot')}{' · '}{t('Module')}{' '}{source.box_id}{' · '}{t('Slot')}{' '}{source.material_id+1}</small><button type="button" disabled={disabled||busy} onClick={()=>choose(presetId,null)}>{t('Use without printer slot')}</button></>}
|
||||
{canRead&&<button type="button" disabled={disabled||busy} onClick={()=>view?setView(null):void read()}>{t(view?'Close printer slots':'Choose from printer')}</button>}
|
||||
{busy&&<span role="status">{t('Reading printer filaments…')}</span>}
|
||||
{busy&&<span role="status">{t(view?'Checking the slot assignment…':'Reading printer filaments…')}</span>}
|
||||
{busy&&!view&&<button type="button" onClick={()=>{request.current?.abort();setBusy(false);}}>{t('Cancel')}</button>}
|
||||
{error&&<p role="alert">{error}</p>}
|
||||
{view&&<ul aria-label={t('Printer filament slots')}>{view.slots.map(slot=>{
|
||||
const product=products.find(p=>p.id===slot.product?.id),profiles=product?.profiles.filter(p=>p.profile_id===profileId)??[];
|
||||
const product=products.find(p=>p.id===slot.product?.id),profiles=product?.profiles.filter(p=>p.machine_id===machine.id&&p.profile_id===profileId)??[];
|
||||
const preferred=profiles.filter(p=>p.preferred),automatic=profiles.length===1?profiles[0]:preferred.length===1?preferred[0]:undefined;
|
||||
const rgba=slot.identity?.rgba;
|
||||
const key=`${slot.box_id}:${slot.material_id}`,preset=tuning[key]??automatic?.preset_id;
|
||||
return <li key={key}><span className="product-swatch" style={{backgroundColor:slot.color}}/><strong>{view.modules.find(module=>module.id===slot.box_id)?.name}{' · '}{slot.name}{' · '}{slot.product?.name??slot.material}</strong>
|
||||
{slot.assignment_state!=='assigned'?<small>{t('Assign and confirm a filament product in Device first.')}</small>:!profiles.length?<small>{t('Add compatible slicing settings for this printer preset in the filament library.')}</small>:<>
|
||||
return <li key={key}><span className="product-swatch" style={{backgroundColor:rgba?'#'+rgba:slot.color}}/><strong>{view.modules.find(module=>module.id===slot.box_id)?.name}{' · '}{slot.name}{' · '}{slot.product?.name??slot.material}</strong>{rgba?.endsWith('00')&&slot.material&&<small>{t('Transparent')}</small>}
|
||||
{slot.assignment_state!=='assigned'?<small>{t('In Device, assign a filament from your library to this AMS slot and confirm it. AMS reports the loaded material but does not provide slicing settings.')}</small>:!profiles.length?<small>{t('In Filament library, add a slicing profile for this printer and nozzle. You can use an imported Bambu Lab preset.')}</small>:<>
|
||||
{profiles.length>1&&<label>{t('Slicing profile')}<select aria-label={`${t('Slicing profile')} · ${slot.name}`} disabled={busy} value={preset??''} onChange={e=>setTuning(v=>({...v,[key]:e.target.value}))}><option value="" disabled>{t('Select')}</option>{profiles.map(p=><option key={p.preset_id} value={p.preset_id}>{p.label}</option>)}</select></label>}
|
||||
<button type="button" disabled={disabled||busy||!preset||!slot.assignment_revision} onClick={()=>void useSlot(slot.box_id,slot.material_id,slot.assignment_revision!,preset)}>{t('Use this filament')}</button>
|
||||
</>}
|
||||
|
||||
@@ -181,7 +181,9 @@ export function SceneView({load, identity, bed, frameKey, initialFit='bed',pick,
|
||||
};
|
||||
const watchCamera=()=>{orientation.copy(camera.quaternion);controls.addEventListener('change',cameraChanged);};
|
||||
let deferredFit:'content'|'bed'|'selection'|null=null;
|
||||
const pointers = new Map<number, {x: number; y: number; moved: boolean}>();
|
||||
const pointers = new Map<number, {x: number; y: number; moved: boolean; at: number}>();
|
||||
let lastTap: {x: number; y: number; at: number} | null = null;
|
||||
let touchZoom: {id: number; y: number} | null = null;
|
||||
let multiTouch = false;
|
||||
let boxStart: {id:number;x:number;y:number} | null = null;
|
||||
const pointerDown = (event: PointerEvent) => {
|
||||
@@ -195,10 +197,28 @@ export function SceneView({load, identity, bed, frameKey, initialFit='bed',pick,
|
||||
renderer.domElement.setPointerCapture(event.pointerId);
|
||||
return;
|
||||
}
|
||||
pointers.set(event.pointerId, {x: event.clientX, y: event.clientY, moved: false});
|
||||
if (event.pointerType === 'touch' && touchZoom) {
|
||||
event.stopImmediatePropagation();
|
||||
return;
|
||||
}
|
||||
const tap = lastTap;
|
||||
lastTap = null;
|
||||
if (event.pointerType === 'touch' && !pointers.size && tap && zoomCamera.current &&
|
||||
event.timeStamp - tap.at <= 320 && Math.hypot(event.clientX - tap.x, event.clientY - tap.y) <= 40) {
|
||||
event.stopImmediatePropagation();
|
||||
touchZoom = {id: event.pointerId, y: event.clientY};
|
||||
renderer.domElement.setPointerCapture(event.pointerId);
|
||||
return;
|
||||
}
|
||||
pointers.set(event.pointerId, {x: event.clientX, y: event.clientY, moved: false, at: event.timeStamp});
|
||||
if (pointers.size > 1) multiTouch = true;
|
||||
};
|
||||
const pointerMove = (event: PointerEvent) => {
|
||||
if (touchZoom?.id === event.pointerId) {
|
||||
zoomCamera.current?.(Math.exp((touchZoom.y - event.clientY) / 120));
|
||||
touchZoom.y = event.clientY;
|
||||
return;
|
||||
}
|
||||
if (boxStart?.id === event.pointerId) {
|
||||
const rect = renderer.domElement.getBoundingClientRect();
|
||||
const clampX = (x:number) => Math.max(0,Math.min(rect.width,x-rect.left));
|
||||
@@ -214,6 +234,11 @@ export function SceneView({load, identity, bed, frameKey, initialFit='bed',pick,
|
||||
touchpadMove(controls, camera, renderer.domElement, event.movementX, event.movementY, event.altKey ? 'rotate' : 'pan', settings);
|
||||
};
|
||||
const pointerUp = (event: PointerEvent) => {
|
||||
if (touchZoom?.id === event.pointerId) {
|
||||
touchZoom = null;
|
||||
if (renderer.domElement.hasPointerCapture(event.pointerId)) renderer.domElement.releasePointerCapture(event.pointerId);
|
||||
return;
|
||||
}
|
||||
if (boxStart?.id === event.pointerId) {
|
||||
const start = boxStart;
|
||||
boxStart = null; controls.enabled = true; setBox(null);
|
||||
@@ -230,7 +255,10 @@ export function SceneView({load, identity, bed, frameKey, initialFit='bed',pick,
|
||||
const start = pointers.get(event.pointerId);
|
||||
pointers.delete(event.pointerId);
|
||||
if (multiTouch) {if (!pointers.size) multiTouch = false; return;}
|
||||
if (!start || start.moved || !picker.current || Math.hypot(event.clientX - start.x, event.clientY - start.y) > 5) return;
|
||||
if (!start || start.moved || Math.hypot(event.clientX - start.x, event.clientY - start.y) > 5) return;
|
||||
if (event.pointerType === 'touch' && event.timeStamp - start.at <= 250)
|
||||
lastTap = {x: event.clientX, y: event.clientY, at: event.timeStamp};
|
||||
if (!picker.current) return;
|
||||
const rect = renderer.domElement.getBoundingClientRect();
|
||||
if (!rect.width || !rect.height) return;
|
||||
const ray = new THREE.Raycaster();
|
||||
@@ -242,6 +270,8 @@ export function SceneView({load, identity, bed, frameKey, initialFit='bed',pick,
|
||||
emptyPicker.current?.(event);
|
||||
};
|
||||
const pointerCancel = (event: PointerEvent) => {
|
||||
if (touchZoom?.id === event.pointerId) touchZoom = null;
|
||||
if (event.type === 'pointercancel') lastTap = null;
|
||||
if (boxStart) {
|
||||
const id = boxStart.id; boxStart = null; controls.enabled = true; setBox(null);
|
||||
if (renderer.domElement.hasPointerCapture(id)) renderer.domElement.releasePointerCapture(id);
|
||||
@@ -414,7 +444,10 @@ export function SceneView({load, identity, bed, frameKey, initialFit='bed',pick,
|
||||
refreshInteraction();
|
||||
zoomCamera.current=factor=>{
|
||||
if(camera instanceof THREE.OrthographicCamera){camera.zoom=Math.max(0.01,Math.min(1000,camera.zoom*factor));camera.updateProjectionMatrix();}
|
||||
else camera.position.sub(controls.target).multiplyScalar(1/factor).add(controls.target);
|
||||
else {
|
||||
const offset = camera.position.sub(controls.target);
|
||||
offset.setLength(THREE.MathUtils.clamp(offset.length() / factor, 0.1, 100000)).add(controls.target);
|
||||
}
|
||||
controls.update();
|
||||
};
|
||||
orbitCamera.current=(dx,dy)=>touchpadMove(controls,camera,renderer.domElement,dx,dy,'rotate',preferences());
|
||||
@@ -476,7 +509,7 @@ export function SceneView({load, identity, bed, frameKey, initialFit='bed',pick,
|
||||
canvas.removeEventListener('lostpointercapture',pointerCancel);
|
||||
if (boxStart && canvas.hasPointerCapture(boxStart.id)) canvas.releasePointerCapture(boxStart.id);
|
||||
nativeOverlay?.dispose(); nativeOverlay = null;
|
||||
disposeObject(scene); renderer.dispose(); renderer.domElement.remove();
|
||||
disposeObject(scene); renderer.dispose(); renderer.forceContextLoss(); renderer.domElement.remove();
|
||||
};
|
||||
}, [identity, bed, frameKey, bedArtwork?.projectId, bedArtwork?.revision, bedArtwork?.origin.join(','), bedArtwork?.endpoint]);
|
||||
// Desktop camera view and label shortcuts apply to the visible scene.
|
||||
|
||||
@@ -43,11 +43,13 @@ export function Field({option, value, commit, disabled, draftChanged, gcode, res
|
||||
}) {
|
||||
const nullableNumber = option.nullable && [1, 2, 4, 5].includes(option.type);
|
||||
const displayed=override&&!override.checked?override.inherited??'nil':value;
|
||||
const [draft, setDraft] = useState(nullableNumber && displayed === 'nil' ? '' : displayed);
|
||||
const displayValue = nullableNumber && displayed === 'nil' ? '' : displayed;
|
||||
const [draft, setDraft] = useState(displayValue);
|
||||
const [editing,setEditing]=useState(false);
|
||||
const editingRef=useRef(false);
|
||||
const codeField=useRef<HTMLTextAreaElement>(null);
|
||||
const [changed, setChanged] = useState(false);
|
||||
useEffect(() => {if (!changed && !editingRef.current) setDraft(displayValue);}, [displayValue]);
|
||||
useEffect(() => () => draftChanged(false), []);
|
||||
const commitDraft = () => {
|
||||
if (!changed) return;
|
||||
@@ -170,6 +172,7 @@ export function Settings({project, schema, busy, commit, resetToken, dependencie
|
||||
commit: (key: string, value: string, index?: number, baseline?: {revision: number; value: string},reset?:ResetSetting) => void;
|
||||
}) {
|
||||
const section=useRef<HTMLElement>(null);
|
||||
const snapshotRevision=project.snapshot_revision??project.revision;
|
||||
const focused=useRef<number|null>(null);
|
||||
const [source,setSource]=useState<BaselineSource>(fixedScope?'preset':'checkpoint');
|
||||
const [base,setBase]=useState<(SettingBaseline & {project_id:string})|null>(null);
|
||||
@@ -206,21 +209,24 @@ export function Settings({project, schema, busy, commit, resetToken, dependencie
|
||||
if (!dependencies||!active) return;
|
||||
const abort = new AbortController();
|
||||
setError('');
|
||||
void readSettingsState(project.id,project.revision,abort.signal)
|
||||
void readSettingsState(project.id,snapshotRevision,abort.signal)
|
||||
.then(value => {if (!abort.signal.aborted) setState({...value,project_id:project.id});})
|
||||
.catch(reason => {if (!abort.signal.aborted) setError(reason);});
|
||||
return () => abort.abort();
|
||||
}, [project.id, project.revision, dependencies,active]);
|
||||
}, [project.id, snapshotRevision, dependencies,active]);
|
||||
useEffect(()=>{
|
||||
if(!baselineTools||!active)return;
|
||||
// On Android these native reads share one worker. Re-enable editing from
|
||||
// the dependency rules before computing the optional reset badges.
|
||||
if(dependencies&&(state?.project_id!==project.id||state.revision!==snapshotRevision))return;
|
||||
const abort=new AbortController();setBaseError('');
|
||||
void api<SettingBaseline>(`/projects/${project.id}/settings/baseline?${new URLSearchParams({source,revision:String(project.revision)})}`,{signal:abort.signal})
|
||||
void api<SettingBaseline>(`/projects/${project.id}/settings/baseline?${new URLSearchParams({source,revision:String(snapshotRevision)})}`,{signal:abort.signal})
|
||||
.then(value=>{if(!abort.signal.aborted)setBase({...value,project_id:project.id});})
|
||||
.catch(reason=>{if(!abort.signal.aborted)setBaseError(reason);});
|
||||
return()=>abort.abort();
|
||||
// Saving moves the checkpoint without a new revision: reload the base when the checkpoint changes.
|
||||
},[project.id,project.revision,project.saved_revision,source,baselineTools,active]);
|
||||
const activeBase=base?.project_id===project.id&&base.revision===project.revision&&base.source===source?base:null;
|
||||
},[project.id,snapshotRevision,project.saved_revision,source,baselineTools,active,dependencies,state?.project_id,state?.revision]);
|
||||
const activeBase=base?.project_id===project.id&&base.revision===snapshotRevision&&base.source===source?base:null;
|
||||
const resetFor=(key:string,value:string,index?:number)=>{
|
||||
const field=activeBase?.fields[key];
|
||||
if(!field || (index===undefined?!field.available.every(Boolean):!field.available[index]))return undefined;
|
||||
@@ -238,7 +244,8 @@ export function Settings({project, schema, busy, commit, resetToken, dependencie
|
||||
if(control){control.focus();focused.current=focus.nonce;}
|
||||
}
|
||||
},[focus?.key,focus?.nonce,query,mode,scope,state]);
|
||||
const currentState = state?.project_id === project.id && state.revision === project.revision ? state : null;
|
||||
const currentState = state?.project_id === project.id && state.revision === snapshotRevision ? state : null;
|
||||
const displayState = currentState ?? (state?.project_id === project.id ? state : null);
|
||||
if(currentState){
|
||||
const identity=JSON.stringify([resetToken,project.state.profile_selection,
|
||||
...['filament_self_index','filament_extruder_variant','filament_map','filament_volume_map',
|
||||
@@ -256,10 +263,10 @@ export function Settings({project, schema, busy, commit, resetToken, dependencie
|
||||
...(project.state.profile_selection?.filaments??[]).flatMap((name,index)=>
|
||||
unmixedRoles.has(key)&¤tState?.values.filament_is_mixed?.[index]==='1'?[]:[{value:String(index+1),label:`${index+1}: ${name.split('/').at(-1)||name}`}]),
|
||||
]:undefined;
|
||||
const rule = (key: string, index?: number) => ({...currentState?.fields[key]?.['-1'],
|
||||
...(index === undefined ? {} : currentState?.fields[key]?.[String(index)])});
|
||||
const rule = (key: string, index?: number) => ({...displayState?.fields[key]?.['-1'],
|
||||
...(index === undefined ? {} : displayState?.fields[key]?.[String(index)])});
|
||||
const visible = (key: string) => {
|
||||
const values = currentState?.values[key];
|
||||
const values = displayState?.values[key];
|
||||
return values?.length ? values.some((_, index) => rule(key, index).visible !== false) : rule(key).visible !== false;
|
||||
};
|
||||
const scopes = ['process','filament','printer'] as const;
|
||||
@@ -368,12 +375,12 @@ export function Settings({project, schema, busy, commit, resetToken, dependencie
|
||||
const allowed = rule(key).enum_values;
|
||||
const presented = allowed ? {...option, enum_values:option.enum_values.filter(value=>allowed.includes(value)),
|
||||
enum_labels:option.enum_values.filter(value=>allowed.includes(value)).map(value=>option.enum_labels[option.enum_values.indexOf(value)])} : option;
|
||||
const values = currentState?.values[key];
|
||||
const values = displayState?.values[key];
|
||||
if (values?.length && !option.serialized) return <Fragment key={key}>{heading}<div className="field-vector" data-setting={key}>
|
||||
{values.map((value, index) => {
|
||||
const rules = rule(key, index);
|
||||
if (rules.visible === false) return null;
|
||||
const inherited = currentState?.inheritance?.[key];
|
||||
const inherited = displayState?.inheritance?.[key];
|
||||
const inheritedValue = inherited?.values[index];
|
||||
const type = option.type & ~0x4000;
|
||||
const hasOverride=rules.override_enabled!==undefined&&!!inherited;
|
||||
@@ -387,7 +394,7 @@ export function Settings({project, schema, busy, commit, resetToken, dependencie
|
||||
? option.enum_labels[option.enum_values.indexOf(inheritedValue ?? '')] || inheritedValue : inheritedValue;
|
||||
return <label className="field" hidden={fixedScope==='filament'&&values.length>1&&materialOf(values.length,index)!==activeFilament} key={index} title={localize(option.tooltip)} data-setting-index={index}>
|
||||
<span>{localize(rules.label || option.label || option.full_label)}{localize(rules.target?` · Narzędzie ${rules.target.tool+1}${rules.target.variant?` · ${rules.target.variant}`:''}${rules.target.mode?` · ${localize(rules.target.mode==='silent'?'Cichy':'Normalny')}`:''}`:values.length > 1 ? ` · ${index + 1}` : '')} <small>{localize(option.unit)}</small></span>
|
||||
<Field reset={resetFor(key,value,index)} gcode={gcodeTools&&option.is_code?{project,key,index}:undefined} key={`${resetToken}:${key}:${index}:${value}:${hasOverride&&!checked?inheritedValue:checked}`} option={{...presented, type}} override={override}
|
||||
<Field reset={resetFor(key,value,index)} gcode={gcodeTools&&option.is_code?{project,key,index}:undefined} key={`${resetToken}:${key}:${index}`} option={{...presented, type}} override={override}
|
||||
draftChanged={dirty => draftChanged(`${key}:${index}`, dirty)}
|
||||
value={value} disabled={busy || loading || (hasOverride?rules.override_enabled===false:rules.enabled === false)}
|
||||
commit={draft => commit(key, draft, index, {revision: project.revision, value})}/>
|
||||
@@ -402,7 +409,7 @@ export function Settings({project, schema, busy, commit, resetToken, dependencie
|
||||
const value = (option.serialized?currentState?.serialized?.[key]:literalStrings ? currentState?.strings?.[key] : undefined) ?? project.state.config[key] ?? option.default ?? '';
|
||||
return <Fragment key={key}>{heading}<label className="field" data-setting={key} title={localize(option.tooltip)}>
|
||||
<span>{localize(rule(key).label || option.label || option.full_label)} <small>{localize(option.unit)}</small></span>
|
||||
<Field settingKey={key} choices={materialChoices(key)} reset={resetFor(key,value)} gcode={gcodeTools&&option.is_code?{project,key}:undefined} key={`${resetToken}:${key}:${value}`} option={presented} value={value}
|
||||
<Field settingKey={key} choices={materialChoices(key)} reset={resetFor(key,value)} gcode={gcodeTools&&option.is_code?{project,key}:undefined} key={`${resetToken}:${key}`} option={presented} value={value}
|
||||
draftChanged={dirty => draftChanged(key, dirty)}
|
||||
disabled={busy || loading || rule(key).enabled === false}
|
||||
commit={draft => commit(key, draft, undefined, {revision: project.revision, value})}/>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import {useEffect,useRef} from 'react';
|
||||
|
||||
/** Native change commits the picker; input previews must never send commands. */
|
||||
export function SlotColorPicker({color,disabled,label,title,commit}:{color:string;disabled:boolean;label:string;title?:string;commit:(color:string)=>void}){
|
||||
export function SlotColorPicker({color,transparent,disabled,label,title,commit}:{color:string;transparent?:boolean;disabled:boolean;label:string;title?:string;commit:(color:string)=>void}){
|
||||
const input=useRef<HTMLInputElement>(null),pending=useRef(false);
|
||||
const latest=useRef({color,disabled,commit});latest.current={color,disabled,commit};
|
||||
useEffect(()=>{if(input.current)input.current.value=color;pending.current=disabled;},[color,disabled]);
|
||||
@@ -14,5 +14,5 @@ export function SlotColorPicker({color,disabled,label,title,commit}:{color:strin
|
||||
};
|
||||
element.addEventListener('change',changed);return()=>element.removeEventListener('change',changed);
|
||||
},[]);
|
||||
return <input ref={input} type="color" className="device-slot-color-picker" defaultValue={color} disabled={disabled} aria-label={label} title={title??label}/>;
|
||||
return <input ref={input} type="color" className="device-slot-color-picker" data-transparent={transparent||undefined} defaultValue={color} disabled={disabled} aria-label={label} title={title??label}/>;
|
||||
}
|
||||
|
||||
@@ -1,23 +1,32 @@
|
||||
import {useSyncExternalStore} from 'react';
|
||||
import {t} from './i18n';
|
||||
|
||||
type Theme = 'dark' | 'light';
|
||||
type Theme = 'system' | 'dark' | 'light';
|
||||
const storageKey='orca-theme';
|
||||
const systemTheme=window.matchMedia('(prefers-color-scheme: dark)');
|
||||
const listeners=new Set<()=>void>();
|
||||
let theme:Theme='dark';
|
||||
try {theme=localStorage.getItem('orca-theme')==='light'?'light':'dark';} catch { /* Storage is optional. */ }
|
||||
function apply(value:Theme) {
|
||||
theme=value;document.documentElement.dataset.theme=value;
|
||||
const readTheme=(value:string|null):Theme=>value==='light'||value==='dark'?value:'system';
|
||||
let theme:Theme='system';
|
||||
try {theme=readTheme(localStorage.getItem(storageKey));} catch { /* Storage is optional. */ }
|
||||
|
||||
function apply(){
|
||||
document.documentElement.dataset.theme=theme==='system'?(systemTheme.matches?'dark':'light'):theme;
|
||||
}
|
||||
function choose(value:Theme){
|
||||
theme=value;apply();
|
||||
for(const listener of listeners)listener();
|
||||
}
|
||||
apply(theme);
|
||||
apply();
|
||||
systemTheme.addEventListener('change',()=>{if(theme==='system')apply();});
|
||||
window.addEventListener('storage',event=>{
|
||||
if(event.key==='orca-theme')apply(event.newValue==='light'?'light':'dark');
|
||||
if(event.key===storageKey||event.key===null)choose(readTheme(event.newValue));
|
||||
});
|
||||
export function ThemeSelector() {
|
||||
|
||||
export function ThemeSelector(){
|
||||
const value=useSyncExternalStore(listener=>{listeners.add(listener);return()=>{listeners.delete(listener);};},()=>theme);
|
||||
return <label className="theme-selector">{t('Theme')}<select value={value} aria-label={t('Theme')} onChange={event=>{
|
||||
const next=event.target.value as Theme;
|
||||
try {localStorage.setItem('orca-theme',next);} catch { /* Retain the in-memory choice. */ }
|
||||
apply(next);
|
||||
}}><option value="dark">{t('Dark')}</option><option value="light">{t('Light')}</option></select></label>;
|
||||
const next=readTheme(event.target.value);
|
||||
try {localStorage.setItem(storageKey,next);} catch { /* Retain the in-memory choice. */ }
|
||||
choose(next);
|
||||
}}><option value="system">{t('System theme')}</option><option value="light">{t('Light')}</option><option value="dark">{t('Dark')}</option></select></label>;
|
||||
}
|
||||
|
||||
@@ -69,12 +69,12 @@ export function PanelGroup({visible, children,draft}: {visible:boolean; children
|
||||
return <div className="panel-group" data-draft={draft} hidden={!visible}>{children}</div>;
|
||||
}
|
||||
|
||||
export function Workbench({title, status, projectActions, libraryActions, calibrationActions, deviceActions, jobActions,
|
||||
account, preferences, historyActions, importAction, importDrop, navigation, plates, projects, scene, footer, sceneStatus, inspector, toolBar, toolPanel,
|
||||
export function Workbench({title, status, projectActions, libraryActions, calibrationActions, jobActions,
|
||||
account, preferences, interactionPreferences, help, tools, historyActions, importAction, importDrop, navigation, plates, projects, scene, footer, sceneStatus, inspector, toolBar, toolPanel,
|
||||
inspectorTab, setInspectorTab, navigationTab, setNavigationTab, ready, preview, selectPreview, hasPreview,
|
||||
mobilePanel, setMobilePanel, notices,previewNavigation,previewOutput,previewTimeline,documentMode=false,workspace,selectWorkspace,settingsWorkspace,setupSummary,plateCards,plateLabel,projectDetails,projectOverview,projectLibraryActions,objectTable,objectTableActive=false}: {
|
||||
title:string; status:ReactNode; projectActions:ReactNode; libraryActions:ReactNode; calibrationActions:ReactNode;
|
||||
account?:ReactNode; deviceActions:ReactNode; jobActions:ReactNode; preferences:ReactNode; historyActions:ReactNode;
|
||||
account?:ReactNode; jobActions:ReactNode; preferences:ReactNode; interactionPreferences?:ReactNode; help?:(active:boolean)=>ReactNode; tools?:ReactNode; historyActions:ReactNode;
|
||||
importAction:ReactNode; importDrop?:(files:File[])=>void; navigation:ReactNode; plates:ReactNode; projects:ReactNode; scene:ReactNode;
|
||||
footer:ReactNode; sceneStatus?:ReactNode; inspector:ReactNode; toolBar?:ReactNode; toolPanel?:ReactNode; notices:ReactNode;
|
||||
previewNavigation:ReactNode;previewOutput:ReactNode;previewTimeline:ReactNode;
|
||||
@@ -87,6 +87,11 @@ export function Workbench({title, status, projectActions, libraryActions, calibr
|
||||
mobilePanel:'navigation'|'inspector'|null; setMobilePanel:(value:'navigation'|'inspector'|null)=>void;
|
||||
}) {
|
||||
const [menu,setMenu]=useState(false);
|
||||
const preferencesDialog=useRef<HTMLDialogElement>(null);
|
||||
const preferencesBody=useRef<HTMLDivElement>(null);
|
||||
const [preferencesOpen,setPreferencesOpen]=useState(false);
|
||||
const [preferencesPage,setPreferencesPage]=useState<'general'|'interaction'|'help'|'tools'>('general');
|
||||
useLayoutEffect(()=>{preferencesBody.current?.scrollTo(0,0);},[preferencesPage]);
|
||||
const [projectTab,setProjectTab]=useState<'overview'|'objects'|'plates'|'projects'>('overview');
|
||||
const rootRef=useRef<HTMLDivElement>(null),timelineRef=useRef<HTMLDivElement>(null);
|
||||
// Phone sheets end above the bottom navigation, so workspaces stay reachable while a tool is open.
|
||||
@@ -119,13 +124,13 @@ export function Workbench({title, status, projectActions, libraryActions, calibr
|
||||
const previous=document.activeElement instanceof HTMLElement?document.activeElement:null;
|
||||
const background=rootRef.current?.querySelectorAll<HTMLElement>('.workbench-main,.workspace-modes,.mobile-navigation');
|
||||
background?.forEach(node=>{node.inert=true;});
|
||||
navigationRef.current?.querySelector<HTMLButtonElement>('.menu-close')?.focus();
|
||||
rootRef.current?.querySelector<HTMLButtonElement>('.menu-toggle')?.focus();
|
||||
const keydown=(event:KeyboardEvent)=>{
|
||||
if(document.querySelector('dialog[open]'))return;
|
||||
if(event.key==='Escape'){event.preventDefault();setMenu(false);return;}
|
||||
if(event.key!=='Tab')return;
|
||||
const targets=Array.from(navigationRef.current?.querySelectorAll<HTMLElement>('button:not(:disabled),summary,a[href],input:not(:disabled),select:not(:disabled),textarea:not(:disabled)')??[])
|
||||
.filter(node=>node.getClientRects().length>0);
|
||||
const targets=[rootRef.current?.querySelector<HTMLElement>('.menu-toggle'),...Array.from(navigationRef.current?.querySelectorAll<HTMLElement>('button:not(:disabled),summary,a[href],input:not(:disabled),select:not(:disabled),textarea:not(:disabled)')??[])]
|
||||
.filter((node):node is HTMLElement=>!!node&&node.getClientRects().length>0);
|
||||
const first=targets[0],last=targets[targets.length-1];
|
||||
if(event.shiftKey&&document.activeElement===first){event.preventDefault();last?.focus();}
|
||||
else if(!event.shiftKey&&document.activeElement===last){event.preventDefault();first?.focus();}
|
||||
@@ -134,6 +139,7 @@ export function Workbench({title, status, projectActions, libraryActions, calibr
|
||||
return()=>{
|
||||
document.removeEventListener('keydown',keydown);
|
||||
background?.forEach(node=>{node.inert=false;});
|
||||
navigationRef.current?.querySelectorAll<HTMLDetailsElement>('details[open]').forEach(detail=>{detail.open=false;});
|
||||
if(previous?.isConnected)previous.focus();
|
||||
};
|
||||
},[menu]);
|
||||
@@ -156,9 +162,16 @@ export function Workbench({title, status, projectActions, libraryActions, calibr
|
||||
const settings=['process','filament','printer','printers','materials'].includes(current);
|
||||
const tabs: {value:Workspace;label:string;short:string}[]=[
|
||||
{value:'project',label:'Project',short:'Project'},{value:'prepare',label:'Prepare',short:'Prepare'},
|
||||
{value:'preview',label:'Preview',short:'Preview'},{value:'process',label:'Print settings',short:'Print'},
|
||||
{value:'preview',label:'Preview',short:'Preview'},{value:'process',label:'Print settings',short:'Print settings'},
|
||||
{value:'filament',label:'Filaments',short:'Filaments'},{value:'printer',label:'Printer',short:'Printer'}];
|
||||
const navIcons:Record<Workspace,string>={project:'▤',prepare:'◇',preview:'▷',process:'≡',filament:'●',printer:'▣',printers:'▣',materials:'●'};
|
||||
const navIcons:Partial<Record<Workspace,string>>={
|
||||
project:'M4 6h6l2 2h8v11H4z',
|
||||
prepare:'M12 3l8 5v8l-8 5-8-5V8zm-8 5l8 5 8-5m-8 5v8',
|
||||
preview:'M3 7l9-4 9 4-9 4zm0 5l9 4 9-4m-18 5l9 4 9-4',
|
||||
process:'M3 6h18m-18 6h18m-18 6h18M8 3v6m8 0v6M10 15v6',
|
||||
filament:'M18 10.5a8 8 0 1 1-16 0 8 8 0 0 1 16 0ZM11.5 10.5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0ZM6.8 6.8a4.9 4.9 0 0 1 6.4 0m1.6 4.7a4.9 4.9 0 0 1-3.1 3.6m-3.4 0a4.9 4.9 0 0 1-3.1-3.6m11.7 3.1c.5 3.2 1.4 5.9 5 5.9',
|
||||
printer:'M4 21V4h16v17M3 21h18M4 8h16m-8 0v4m-2 0h4l-2 3zM7 18h10',
|
||||
};
|
||||
const choose=(value:Workspace)=>{selectWorkspace?.(value);if(!selectWorkspace)selectPreview(value==='preview');setMobilePanel(null);};
|
||||
const workspaceTabs=(mobile=false)=><nav className={mobile?'mobile-navigation':'workspace-modes'} aria-label={t('Workspace navigation')}>
|
||||
{documentMode?<><a className="button" href={window.location.pathname}>{t('Edytor modeli')}</a>
|
||||
@@ -166,29 +179,46 @@ export function Workbench({title, status, projectActions, libraryActions, calibr
|
||||
<button aria-pressed={mobilePanel==='navigation'&&navigationTab==='objects'} onClick={()=>{setNavigationTab('objects');setMobilePanel('navigation');}}>{t('Toolpaths')}</button>
|
||||
<button aria-pressed={mobilePanel==='inspector'} onClick={()=>setMobilePanel('inspector')}>{t('Print result')}</button></>:
|
||||
<button aria-pressed disabled={!hasPreview} onClick={()=>setMobilePanel(null)}>{t('Preview')}</button>}</>:
|
||||
tabs.map(({value,label,short})=><button key={value} aria-label={t(label)} aria-pressed={current===value}
|
||||
disabled={value==='preview'&&!hasPreview} onClick={()=>choose(value)}>{mobile&&<span className="workspace-nav-icon" aria-hidden="true">{navIcons[value]}</span>}{t(mobile?short:label)}</button>)}
|
||||
tabs.map(({value,label,short})=><button key={value} aria-label={t(label)} aria-pressed={(current==='printers'?'printer':current==='materials'?'filament':current)===value}
|
||||
disabled={value==='preview'&&!hasPreview} onClick={()=>choose(value)}>{mobile&&<svg className="workspace-nav-icon" viewBox="0 0 24 24" aria-hidden="true"><path d={navIcons[value]}/></svg>}<span>{t(mobile?short:label)}</span></button>)}
|
||||
</nav>;
|
||||
return <div ref={rootRef} className="workbench" data-mobile-panel={mobilePanel??''}>
|
||||
{menu&&<button className="app-menu-backdrop" aria-label={t('Close')} tabIndex={-1} onClick={()=>setMenu(false)}/>}
|
||||
<header className="workbench-header">
|
||||
<button className="menu-toggle" title={t('Application menu')} aria-expanded={menu} aria-controls="application-navigation" aria-label={t('Application menu')} onClick={()=>setMenu(true)}><img src={menuIcon} alt={t('')}/></button>
|
||||
<button className="menu-toggle" title={t('Application menu')} aria-expanded={menu} aria-controls="application-navigation" aria-label={t('Application menu')} onClick={()=>setMenu(open=>!open)}><img src={menuIcon} alt=""/></button>
|
||||
<div className="brand">Web Slicer</div>
|
||||
|
||||
<h1 hidden={!title} title={title}>{title}</h1><div className="save-status">{status}</div><div className="header-account">{account}</div>
|
||||
<h1 hidden={!title} title={title}>{title}</h1><div className="save-status">{status}</div><div className="header-account">
|
||||
<span><button type="button" className="preferences-trigger" aria-haspopup="dialog" aria-label={t('Preferences and help')} title={t('Preferences and help')} onClick={()=>{preferencesDialog.current?.showModal();setPreferencesOpen(true);}}>
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M10 3h4l.7 2.5 2 .9 2.3-1.2 2 3.5-1.8 1.8v2.9l1.8 1.8-2 3.5-2.3-1.2-2 .9-.7 2.5h-4l-.7-2.5-2-.9L5 18.7l-2-3.5 1.8-1.8v-2.9L3 8.7l2-3.5 2.3 1.2 2-.9z"/><circle cx="12" cy="12" r="3"/></svg>
|
||||
</button></span>{account}</div>
|
||||
|
||||
<nav id="application-navigation" ref={navigationRef} onClick={event=>{
|
||||
if(event.target instanceof Element&&event.target.closest('[data-close-navigation]'))setMenu(false);
|
||||
}} className="desktop-app-actions" data-open={menu} aria-label={t('Application navigation')}>
|
||||
<button className="menu-close" onClick={()=>setMenu(false)}>{t('Close')}</button>
|
||||
<ActionMenu label={t('Project')}><div className="menu-history-actions">{historyActions}</div>{projectActions}</ActionMenu>
|
||||
{libraryActions&&<ActionMenu label={t('Library')}>{libraryActions}</ActionMenu>}
|
||||
{calibrationActions&&<ActionMenu label={t('Calibrate')}>{calibrationActions}</ActionMenu>}
|
||||
{deviceActions}
|
||||
{jobActions&&<ActionMenu label={t('Jobs')}>{jobActions}</ActionMenu>}
|
||||
<ActionMenu label={t('Preferences and help')}>{preferences}</ActionMenu>
|
||||
</nav>
|
||||
</header>
|
||||
<dialog ref={preferencesDialog} className="preferences-dialog" onClose={event=>{if(event.target===event.currentTarget)setPreferencesOpen(false);}} aria-labelledby="preferences-title">
|
||||
<header><h2 id="preferences-title">{t('Preferences and help')}</h2><button type="button" onClick={()=>preferencesDialog.current?.close()}>{t('Close')}</button></header>
|
||||
{(interactionPreferences||help||tools)&&<nav aria-label={t('Preferences')}>
|
||||
<button type="button" aria-pressed={preferencesPage==='general'} onClick={()=>setPreferencesPage('general')}>{t('General')}</button>
|
||||
{interactionPreferences&&<button type="button" aria-pressed={preferencesPage==='interaction'} onClick={()=>setPreferencesPage('interaction')}>{t('Controls and preview')}</button>}
|
||||
{help&&<button type="button" aria-pressed={preferencesPage==='help'} onClick={()=>setPreferencesPage('help')}>{t('Help and support')}</button>}
|
||||
{tools&&<button type="button" aria-pressed={preferencesPage==='tools'} onClick={()=>setPreferencesPage('tools')}>{t('Tools')}</button>}
|
||||
</nav>}
|
||||
<div ref={preferencesBody} className="preferences-dialog-body">
|
||||
<div className="preferences-page" hidden={preferencesPage!=='general'}>{preferences}<div data-native-preferences/></div>
|
||||
<div className="preferences-page" hidden={preferencesPage!=='interaction'}>{interactionPreferences}</div>
|
||||
<div className="preferences-page" hidden={preferencesPage!=='help'}>{help?.(preferencesOpen&&preferencesPage==='help')}</div>
|
||||
<div className="preferences-page" hidden={preferencesPage!=='tools'} onClick={event=>{
|
||||
if(event.target instanceof Element&&event.target.closest('[data-close-navigation]'))preferencesDialog.current?.close();
|
||||
}}>{tools}</div>
|
||||
</div>
|
||||
</dialog>
|
||||
<div className="workbench-notices">{notices}</div>
|
||||
{/* Desktop: the slice and print actions sit at the right of the workspace tabs; phones keep them above the bottom navigation. */}
|
||||
<div className="workbench-bar">{workspaceTabs()}<div className="workbench-footer" hidden={!inScene}>{footer}</div></div>
|
||||
|
||||
@@ -1,8 +1,18 @@
|
||||
.about-dialog{width:min(840px,calc(100vw - 32px));max-height:calc(100dvh - 32px);overflow:auto;scroll-padding-top:80px;box-sizing:border-box;padding:24px;background:var(--wb-panel);color:var(--wb-text);border:1px solid var(--wb-border);border-radius:12px}
|
||||
.about-dialog>header{box-shadow:0 -32px 0 var(--wb-panel);display:flex;align-items:center;gap:16px;position:sticky;top:0;z-index:2;background:var(--wb-panel);padding:8px 0;border:0}.about-dialog>header h2{flex:1;min-width:0;margin:0}.about-dialog>header button{flex-shrink:0}
|
||||
.about-dialog :is(h3,h4,p){margin:0;overflow-wrap:anywhere}.about-dialog>*,.about-dialog section>*,.about-dialog details>*{margin-bottom:16px}.about-dialog section{padding:16px;border:1px solid var(--wb-border);border-radius:8px}.about-dialog details>p{margin-top:16px}
|
||||
.about-dialog button,.about-dialog .button{min-height:44px}.about-dialog label{display:grid;gap:8px}.about-dialog input{max-width:100%;box-sizing:border-box}.about-actions{display:flex;align-items:start;flex-wrap:wrap;gap:12px}.about-actions button{max-width:100%;overflow-wrap:anywhere}
|
||||
.about-versions{display:grid;grid-template-columns:auto minmax(0,1fr);gap:12px}.about-versions dd{margin:0;overflow-wrap:anywhere}.about-dialog ul{padding:0;list-style:none}.about-dialog li{padding:16px 0;border-bottom:1px solid var(--wb-border);display:grid;gap:8px;min-width:0}.about-dialog h4 small{font-weight:normal;margin-left:12px}
|
||||
.about-dialog{width:min(840px,calc(100vw - 32px));max-height:calc(100dvh - 32px);overflow:auto;box-sizing:border-box;padding:24px;background:var(--wb-panel);color:var(--wb-text);border:1px solid var(--wb-border);border-radius:12px}
|
||||
.about-information{padding:14px 16px;color:var(--wb-text);min-width:0}
|
||||
.about-information :is(h3,h4,p){margin:0;overflow-wrap:anywhere}.about-information>*,.about-information section>*,.about-information details>*{margin-bottom:16px}.about-information section{padding:16px;border:1px solid var(--wb-border);border-radius:8px}.about-information details>p{margin-top:16px}
|
||||
.about-information button,.about-information .button{min-height:44px}.about-information label{display:grid;gap:8px}.about-information input{max-width:100%;box-sizing:border-box}.about-actions{display:flex;align-items:start;flex-wrap:wrap;gap:12px}.about-actions button{max-width:100%;overflow-wrap:anywhere}
|
||||
.about-versions{display:grid;grid-template-columns:auto minmax(0,1fr);gap:12px}.about-versions dd{margin:0;overflow-wrap:anywhere}.about-information ul{padding:0;list-style:none}.about-information li{padding:16px 0;border-bottom:1px solid var(--wb-border);display:grid;gap:8px;min-width:0}.about-information h4 small{font-weight:normal;margin-left:12px}
|
||||
.about-license{outline-offset:3px}.about-license pre{max-height:320px;overflow:auto;white-space:pre-wrap;overflow-wrap:anywhere;padding:12px;background:var(--wb-bg);border-radius:8px}.about-warning{border-left:3px solid var(--wb-warning,#d4b85b);padding-left:12px}
|
||||
.about-dialog .upstream-release,.upstream-release-latest{display:grid;gap:16px;min-width:0}.about-dialog .upstream-release>*{margin:0}.upstream-release a{color:var(--wb-accent);overflow-wrap:anywhere}
|
||||
@media(max-width:700px){.about-dialog{padding:16px}.about-versions{grid-template-columns:minmax(0,1fr);gap:8px}.about-versions dd{margin-bottom:8px}}
|
||||
.about-information .upstream-release,.upstream-release-latest{display:grid;gap:16px;min-width:0}.about-information .upstream-release>*{margin:0}.upstream-release a{color:var(--wb-accent);overflow-wrap:anywhere}
|
||||
@media(max-width:700px){.about-information{padding:16px}.about-versions{grid-template-columns:minmax(0,1fr);gap:8px}.about-versions dd{margin-bottom:8px}}
|
||||
|
||||
.bambu-account-dialog[open]{display:grid;align-content:start;gap:16px}
|
||||
.bambu-account-dialog>*,.bambu-account-dialog section>*{margin:0}
|
||||
.bambu-account-dialog section,.bambu-pairing-fields{display:grid;gap:12px;min-width:0}
|
||||
.bambu-account-dialog .bambu-account-muted{color:var(--wb-muted)}
|
||||
.bambu-account-dialog .about-actions{gap:12px;align-items:center}
|
||||
.bambu-account-dialog .about-actions a{display:inline-flex;align-items:center;padding:8px 14px;text-decoration:none;box-sizing:border-box}
|
||||
.bambu-account-dialog .bambu-pairing-fields{border-top:1px solid var(--wb-border);padding-top:12px}
|
||||
.bambu-account-dialog section>button,.bambu-account-dialog li>button,.bambu-account-dialog>button{justify-self:start}
|
||||
.bambu-account-dialog label:has(> input:is([type=checkbox],[type=radio])){display:flex;align-items:center;gap:8px}
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import {api} from './api';
|
||||
import {t} from './i18n';
|
||||
import type {ImportTask} from './Imports';
|
||||
|
||||
const protocol='web-slicer.open-model.v1';
|
||||
const maxBytes=512*1024*1024;
|
||||
const supported=/\.(3mf|stl|step|stp)$/i;
|
||||
|
||||
function launchParams(){
|
||||
return new URLSearchParams(window.location.hash.slice(1));
|
||||
}
|
||||
export function hasExternalModelLaunch(){
|
||||
const params=launchParams();
|
||||
return params.has('open-model')||params.has('open-model-from')||
|
||||
new URLSearchParams(window.location.search).has('import-job');
|
||||
}
|
||||
|
||||
function webURL(value:string){
|
||||
const url=new URL(value);
|
||||
if(!['http:','https:'].includes(url.protocol)||url.username||url.password)throw Error(t('Invalid model URL.'));
|
||||
return url;
|
||||
}
|
||||
|
||||
async function modelFromURL(value:string,filename:string|null,signal:AbortSignal){
|
||||
const url=webURL(value);
|
||||
const name=filename??decodeURIComponent(url.pathname.slice(url.pathname.lastIndexOf('/')+1));
|
||||
if(!supported.test(name)||/[\\/\u0000-\u001f]/.test(name))throw Error(t('Choose a 3MF, STL or STEP model.'));
|
||||
const response=await fetch(url,{credentials:'omit',referrerPolicy:'no-referrer',signal});
|
||||
if(!response.ok||!response.body)throw Error(t('Could not download the external model.'));
|
||||
if(Number(response.headers.get('Content-Length'))>maxBytes)throw Error(t('The model exceeds the 512 MiB limit.'));
|
||||
const chunks:Uint8Array<ArrayBuffer>[]=[];
|
||||
const reader=response.body.getReader();
|
||||
let size=0;
|
||||
try{
|
||||
for(;;){
|
||||
const {done,value:chunk}=await reader.read();
|
||||
if(done)break;
|
||||
size+=chunk.byteLength;
|
||||
if(size>maxBytes)throw Error(t('The model exceeds the 512 MiB limit.'));
|
||||
chunks.push(chunk);
|
||||
}
|
||||
}finally{await reader.cancel().catch(()=>{});}
|
||||
return new File(chunks,name);
|
||||
}
|
||||
|
||||
export function receiveExternalModel(receive:(file:File)=>Promise<void>,failed:(reason:unknown)=>void){
|
||||
const params=launchParams();
|
||||
const source=params.get('open-model-from'),url=params.get('open-model');
|
||||
if(!source&&!url)return;
|
||||
const abort=new AbortController();
|
||||
let dispose=()=>{};
|
||||
if(source){
|
||||
const opener=window.opener;
|
||||
try{
|
||||
const origin=webURL(source).origin;
|
||||
const token=params.get('request');
|
||||
if(!opener||!token||!/^[a-f0-9]{32}$/.test(token))throw Error(t('The external model connection was lost.'));
|
||||
let received=false;
|
||||
const announce=()=>opener.postMessage({protocol,type:'ready',request:token},origin);
|
||||
const timer=window.setInterval(announce,1000);
|
||||
const listener=(event:MessageEvent)=>{
|
||||
const data=event.data;
|
||||
if(received||event.source!==opener||event.origin!==origin||data?.protocol!==protocol||
|
||||
data.type!=='file'||data.request!==token||!(data.file instanceof File))return;
|
||||
received=true;window.clearInterval(timer);
|
||||
void receive(data.file).then(()=>opener.postMessage({protocol,type:'accepted',request:token},origin))
|
||||
.catch(reason=>{failed(reason);opener.postMessage({protocol,type:'failed',request:token},origin);});
|
||||
};
|
||||
window.addEventListener('message',listener);
|
||||
dispose=()=>{window.clearInterval(timer);window.removeEventListener('message',listener);};
|
||||
announce();
|
||||
}catch(reason){failed(reason);}
|
||||
}else if(url){
|
||||
const signal=AbortSignal.any([abort.signal,AbortSignal.timeout(120_000)]);
|
||||
void modelFromURL(url,params.get('filename'),signal).then(receive).catch(reason=>{if(!abort.signal.aborted)failed(reason);});
|
||||
}
|
||||
return ()=>{abort.abort();dispose();};
|
||||
}
|
||||
|
||||
export function uploadExternalModel(file:File,signal?:AbortSignal){
|
||||
if(!supported.test(file.name))throw Error(t('Choose a 3MF, STL or STEP model.'));
|
||||
if(file.size>maxBytes)throw Error(t('The model exceeds the 512 MiB limit.'));
|
||||
const data=new FormData();data.set('file',file);
|
||||
return api<ImportTask>('/imports/open-model',{method:'POST',body:data,signal});
|
||||
}
|
||||
@@ -13,7 +13,8 @@
|
||||
.product-library-detail h2,.product-library-detail h3{margin:0}
|
||||
.product-metadata-form,.product-profile-form,.product-availability,.product-library-administration form,.product-save-recovery{display:grid;gap:16px;min-width:0}
|
||||
.product-metadata-form fieldset,.product-library-administration fieldset{display:grid;gap:16px;margin:0;padding:0;border:0;min-width:0}
|
||||
.product-metadata-form fieldset{grid-template-columns:repeat(2,minmax(0,1fr))}.product-notes{grid-column:1/-1}
|
||||
.product-metadata-form fieldset{grid-template-columns:repeat(2,minmax(0,1fr))}.product-notes,.product-template-wizard{grid-column:1/-1}
|
||||
|
||||
.product-availability,.product-slicing-profiles,.product-library-administration{border-top:1px solid var(--wb-border);padding-top:20px;min-width:0}
|
||||
.product-slicing-profiles[open]>summary,.product-library-administration[open]>summary{margin-bottom:20px}
|
||||
.product-slicing-profiles ul{list-style:none;padding:0;margin:0 0 20px;display:grid;gap:16px}.product-slicing-profiles li{display:grid;gap:12px;padding:16px;border:1px solid var(--wb-border);border-radius:8px;min-width:0}
|
||||
@@ -24,3 +25,33 @@
|
||||
.filament-product-library input[type=color]{width:72px;height:36px;padding:4px;cursor:pointer}
|
||||
.filament-product-library input[type=color]::-webkit-color-swatch-wrapper{padding:0}
|
||||
.filament-product-library input[type=color]::-webkit-color-swatch{border:0;border-radius:3px}
|
||||
|
||||
.filament-preset-browser{
|
||||
width:min(900px,calc(100% - 32px));max-height:calc(100dvh - 32px);box-sizing:border-box;
|
||||
padding:0;border:1px solid var(--wb-border);border-radius:16px;
|
||||
background:var(--wb-panel);color:inherit;overflow:hidden;
|
||||
}
|
||||
.filament-preset-browser[open]{display:flex;flex-direction:column}
|
||||
.filament-preset-browser::backdrop{background:rgb(0 0 0 / .54)}
|
||||
.filament-browser-header,.filament-browser-footer{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:12px;padding:16px 24px}
|
||||
.filament-browser-header{border-bottom:1px solid var(--wb-border)}
|
||||
.filament-browser-header h2,.filament-browser-header p{margin:0}
|
||||
.filament-browser-header p{margin-top:4px;color:var(--wb-muted)}
|
||||
.filament-browser-body{overflow:auto;min-height:0;padding:20px 24px}
|
||||
.filament-browser-controls{display:grid;gap:14px;min-width:0;margin:0;padding:0;border:0}
|
||||
.filament-browser-controls input,.filament-browser-controls select,.filament-browser-selection select{width:100%;min-width:0;box-sizing:border-box}
|
||||
.filament-browser-chips{display:flex;flex-wrap:wrap;gap:8px}
|
||||
.filament-browser-chips button{border-radius:999px;padding-inline:14px}
|
||||
.filament-browser-chips button[aria-pressed=true],.filament-browser-results button[aria-pressed=true]{border-color:var(--wb-accent);background:var(--wb-selected)}
|
||||
.filament-browser-filters,.filament-browser-results{display:grid;gap:10px;grid-template-columns:repeat(auto-fit,minmax(min(100%,215px),1fr))}
|
||||
.filament-browser-results button{display:grid;align-content:start;text-align:start;white-space:normal;overflow-wrap:anywhere;gap:4px;padding:12px;min-height:62px}
|
||||
.filament-browser-results span,.filament-browser-empty{color:var(--wb-muted)}
|
||||
.filament-browser-empty{border:1px dashed var(--wb-border);border-radius:10px;padding:20px;margin:0}
|
||||
.filament-browser-more{margin-top:10px}
|
||||
.filament-browser-footer{border-top:1px solid var(--wb-border)}
|
||||
.filament-browser-footer .printer-actions{margin-inline-start:auto}
|
||||
.filament-browser-selection{flex:1 1 260px;min-width:0;display:grid;gap:6px;overflow-wrap:anywhere}
|
||||
@media(max-width:600px){
|
||||
.filament-preset-browser{width:calc(100% - 16px);max-height:calc(100dvh - 16px)}
|
||||
.filament-browser-header,.filament-browser-footer,.filament-browser-body{padding:12px}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user