Преглед изворни кода

Inventory: read a photo of a small spool label (#3616)
- Take photo scaled every photo to 1600 px before jsQR read it, so a
label that fills a small part of the photo lost its code; jsQR is
used on every iPhone and on every phone over plain HTTP
- When the first read finds nothing, read the photo again at its own
size, capped at 4096 px for the iOS Safari canvas limit, and free
that canvas afterwards

maziggy пре 1 дан
родитељ
комит
3b119fe1e9

+ 1 - 0
CHANGELOG.md

@@ -15,6 +15,7 @@ All notable changes to Bambuddy will be documented in this file.
 - **Choose which printer an "Any model" job takes (#2915, requested by @bryanmahin, contributed by @Keybored02 in #3547)** — Several printers of a model can take an "Any model" job, and the one with the fewest print hours always got it. **Settings > Workflow > Printer Order for Any-Model Jobs** now chooses: the fewest print hours (the default, as before), the most (use up the machines near replacement first), the printer idle the longest (by its last finished print; one that never printed goes first), or the printers' own priority, a number in **Edit Printer** (lowest first, none last). The order only ranks printers that can take the job: a busy, offline or filament-short printer is still passed over, and preferred colours still come first. Powering a printer on with an Auto Power On plug follows the same order.
 
 ### Fixed
+- **The QR scanner reads a photo of a small spool label (#3616, reported by @balin77)** — **Take photo** answered "No QR code found in the photo" when the label filled only a small part of the photo, although the phone's camera app read it at once. Where the browser has no QR decoder of its own (every iPhone, and every phone with Bambuddy opened over plain HTTP, where the photo is the only way to scan), the photo was scaled down to 1600 pixels before it was read, and a small label lost too much detail. When that finds nothing, the photo is now read again at its own size, up to 4096 pixels on the long side, which phone browsers can still handle. This takes under a second more, and only for a photo the first read could not read.
 - **An archive printed more than once shows what all its prints cost (#3609, reported by @RafalHo)** — Each plate of a multi-plate file printed one at a time is a print of the same archive, and so is a reprint. The archive card showed the file's filament and cost (all plates together) next to the first print's energy, so a seven-plate print showed the electricity of plate 1 only and matched neither one plate nor Statistics. An archive with more than one print now shows the totals of all of them: the filament they used, its cost, the energy and the wear, as Statistics adds them up, with "Total of N prints" on hover. An energy total is left out when no print was measured by a smart plug. Each print's own figures stay in the Print Log behind the prints badge; archives printed once are unchanged.
 - **A spool's slicer preset can be removed, and opening the field no longer loses its name (#3596, reported by @dertbv)** — the Slicer Preset field in the spool form had no way to remove a preset, so a configured spool could not go back to Stock, in an edit or a copy. Clicking into the field also emptied it, and saving then kept the preset but stored no name for it when the preset was not in the current list, for example a Bambu Cloud preset while the cloud list was unavailable. The spool then showed the raw preset code. The field now has a remove button, closing the list without picking shows the preset again, and text typed to search is never saved as the preset's name. The same applies to the SpoolBuddy write-tag page.
 - **The Slice dialog lists presets when a Bambu Cloud account has none of one type (#3593, reported by @KevinMidboe)** — Bambu Cloud answers "nothing here" for a preset type with an empty value instead of an empty list, for example on an account with no filament presets of its own. Bambuddy did not handle that, so with a Bambu Cloud sign-in on the Profiles page the Slice dialog showed "Failed to load presets" and offered no presets at all, local ones included, and the Profiles page's cloud list failed the same way. Such a type now reads as empty, and the presets the account does have are listed.

+ 51 - 0
frontend/src/__tests__/utils/qrDecode.test.ts

@@ -172,4 +172,55 @@ describe('decodeImageBlob', () => {
 
     expect(await decodeImageBlob(photo)).toBe('spool=6');
   });
+
+  describe('second read near full size (#3616)', () => {
+    function stubPhoto(width: number, height: number) {
+      const bitmap = stubBitmap();
+      Object.assign(bitmap, { width, height });
+      stubUnbuildableDetector();
+      return bitmap;
+    }
+    const sizes = () => jsQR.mock.calls.map((c) => [c[1], c[2]]);
+
+    it('reads a small label the downscaled photo loses at the photo size', async () => {
+      stubPhoto(3000, 2000);
+      jsQR.mockReturnValueOnce(null).mockReturnValueOnce({ data: 'spool=7' });
+
+      expect(await decodeImageBlob(photo)).toBe('spool=7');
+      expect(sizes()).toEqual([
+        [1600, 1067],
+        [3000, 2000],
+      ]);
+      expect(jsQR).toHaveBeenLastCalledWith(expect.any(Uint8ClampedArray), 3000, 2000, {
+        inversionAttempts: 'attemptBoth',
+      });
+    });
+
+    it('caps a 24 MP photo at 4096 px for the phone canvas limit', async () => {
+      stubPhoto(5712, 4284);
+      jsQR.mockReturnValue(null);
+
+      expect(await decodeImageBlob(photo)).toBeUndefined();
+      expect(sizes()).toEqual([
+        [1600, 1200],
+        [4096, 3072],
+      ]);
+    });
+
+    it('reads only once when the downscaled photo has the code', async () => {
+      stubPhoto(3000, 2000);
+      jsQR.mockReturnValue({ data: 'spool=8' });
+
+      expect(await decodeImageBlob(photo)).toBe('spool=8');
+      expect(jsQR).toHaveBeenCalledTimes(1);
+    });
+
+    it('reads a photo no larger than the first read only once', async () => {
+      stubPhoto(1200, 900);
+      jsQR.mockReturnValue(null);
+
+      expect(await decodeImageBlob(photo)).toBeUndefined();
+      expect(sizes()).toEqual([[1200, 900]]);
+    });
+  });
 });

+ 32 - 10
frontend/src/utils/qrDecode.ts

@@ -59,13 +59,27 @@ export function decodeCanvas(
   }
 }
 
+/** jsQR's first, fast read of a photo: its long side scaled down to this. */
+const PHOTO_FAST_SIDE = 1600;
+/**
+ * The second read, at the photo's own size up to this long side. iOS Safari
+ * refuses a canvas over about 16.7 MP, which a 24 MP photo would be.
+ */
+const PHOTO_FULL_SIDE = 4096;
+
+function scaledTo(bitmap: ImageBitmap, maxSide: number): [number, number] {
+  const scale = Math.min(1, maxSide / Math.max(bitmap.width, bitmap.height));
+  return [Math.max(1, Math.round(bitmap.width * scale)), Math.max(1, Math.round(bitmap.height * scale))];
+}
+
 /**
  * Decode a QR from a captured photo. The photo is taken with the phone's native
- * camera (file input + capture) — which focuses far better than an in-page
- * getUserMedia preview — so a small/dense spool QR resolves cleanly. Prefer the
- * platform decoder; fall back to jsQR (downscaling huge stills for speed — a
- * focused QR survives the downscale). Rejects only when the image itself can't
- * be opened.
+ * camera (file input + capture), which focuses far better than an in-page
+ * getUserMedia preview. Prefer the platform decoder; fall back to jsQR, first
+ * on the photo scaled down for speed, then, if that finds nothing, near its
+ * own size: a small label in the photo has too few pixels per module left
+ * after the downscale (#3616). Rejects only when the image itself can't be
+ * opened.
  */
 export async function decodeImageBlob(blob: Blob): Promise<string | undefined> {
   const bitmap = await createImageBitmap(blob, { imageOrientation: 'from-image' });
@@ -79,11 +93,19 @@ export async function decodeImageBlob(blob: Blob): Promise<string | undefined> {
         /* the platform decoder failed on this image — jsQR gets a go */
       }
     }
-    const maxSide = 1600;
-    const scale = Math.min(1, maxSide / Math.max(bitmap.width, bitmap.height));
-    const w = Math.max(1, Math.round(bitmap.width * scale));
-    const h = Math.max(1, Math.round(bitmap.height * scale));
-    return decodeCanvas(document.createElement('canvas'), bitmap, w, h, 'attemptBoth');
+    const canvas = document.createElement('canvas');
+    const [w, h] = scaledTo(bitmap, PHOTO_FAST_SIDE);
+    const fast = decodeCanvas(canvas, bitmap, w, h, 'attemptBoth');
+    if (fast) return fast;
+    const [fw, fh] = scaledTo(bitmap, PHOTO_FULL_SIDE);
+    // A photo no larger than the first read has nothing more to give.
+    if (fw === w && fh === h) return undefined;
+    const full = decodeCanvas(canvas, bitmap, fw, fh, 'attemptBoth');
+    // iOS Safari counts a canvas's memory until it is resized, not until it
+    // is collected: give the 50 MB back now, for the next photo.
+    canvas.width = 0;
+    canvas.height = 0;
+    return full;
   } finally {
     bitmap.close?.();
   }

Разлика између датотеке није приказан због своје велике величине
+ 0 - 0
static/assets/ArchivesPage-BbFcRjZp.js


Разлика између датотеке није приказан због своје велике величине
+ 0 - 0
static/assets/CamWallPage-ByKxbOTV.js


Разлика између датотеке није приказан због своје велике величине
+ 0 - 0
static/assets/CameraPage-JoCdb1UF.js


Разлика између датотеке није приказан због своје велике величине
+ 0 - 0
static/assets/ConfigureAmsSlotModal-CamYpNWM.js


Разлика између датотеке није приказан због своје велике величине
+ 0 - 0
static/assets/FileManagerPage-DWR9_PUi.js


Разлика између датотеке није приказан због своје велике величине
+ 0 - 0
static/assets/InventoryPage-COafecnL.js


Разлика између датотеке није приказан због своје велике величине
+ 0 - 0
static/assets/MaintenancePage-DhxFmmgA.js


Разлика између датотеке није приказан због своје велике величине
+ 0 - 0
static/assets/ModelSourcesPage-BPyHTEoI.js


Разлика између датотеке није приказан због своје велике величине
+ 0 - 0
static/assets/PrintersPage-DjAYYkFJ.js


Разлика између датотеке није приказан због своје велике величине
+ 0 - 0
static/assets/SettingsPage-5yMx1iFv.js


Разлика између датотеке није приказан због своје велике величине
+ 0 - 0
static/assets/SliceModal-B25cx_sm.js


Разлика између датотеке није приказан због своје велике величине
+ 0 - 0
static/assets/SpoolBuddyAmsPage-BncKkp0y.js


Разлика између датотеке није приказан због своје велике величине
+ 0 - 0
static/assets/SpoolBuddyInventoryPage-BmRe9dnG.js


Разлика између датотеке није приказан због своје велике величине
+ 1 - 1
static/assets/SpoolBuddySettingsPage-uY7wQIo1.js


Разлика између датотеке није приказан због своје велике величине
+ 0 - 0
static/assets/SpoolBuddyWriteTagPage-CngCEKjy.js


Разлика између датотеке није приказан због своје велике величине
+ 0 - 0
static/assets/index-DfbT4ybX.js


Разлика између датотеке није приказан због своје велике величине
+ 0 - 0
static/assets/inventorySearch-CPokNAPH.js


Разлика између датотеке није приказан због своје велике величине
+ 0 - 0
static/assets/locationSensorDefaults-Cfc0GvV8.js


Разлика између датотеке није приказан због своје велике величине
+ 0 - 0
static/assets/spoolCost-CoxrGS9D.js


Разлика између датотеке није приказан због своје велике величине
+ 0 - 0
static/assets/usePageFileDrop-D-w7rXS8.js


+ 1 - 1
static/index.html

@@ -26,7 +26,7 @@
 
     <!-- Splash screens for iOS -->
     <link rel="apple-touch-startup-image" href="/img/android-chrome-512x512.png" />
-    <script type="module" crossorigin src="/assets/index-BI9UraM9.js"></script>
+    <script type="module" crossorigin src="/assets/index-DfbT4ybX.js"></script>
     <link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-aKtaBQYM.js">
     <link rel="modulepreload" crossorigin href="/assets/client-CI_mRuxq.js">
     <link rel="modulepreload" crossorigin href="/assets/react-dom--SxW8qhX.js">

Неке датотеке нису приказане због велике количине промена