sliceLoadedSpools.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. // Matching what is loaded in the connected printers against the SliceModal's
  2. // profile lists (#3172).
  3. //
  4. // Two questions are answered here:
  5. //
  6. // 1. Which printer models are online, and does a printer profile belong to
  7. // one of them? A profile whose model can't be read from its name (a
  8. // user's own "My farm printer") is never ruled out.
  9. // 2. Which filament profile does a loaded slot correspond to, for the
  10. // printer profile selected in the dialog? Strongest evidence first:
  11. //
  12. // a. the profile Bambuddy saved for the slot, by its id, when it still
  13. // describes the slot (#3216) and fits the selected printer;
  14. // b. the same profile under another printer's tag, found by base name
  15. // (the name before its "@printer" suffix) — a cloud profile saved for
  16. // an X1C reaches its H2D copy this way, and bundled profiles, which
  17. // are addressed by name, are only reachable this way;
  18. // c. for a slot nobody configured through Bambuddy, the spool's own
  19. // brand text ("PLA Basic" → "Bambu PLA Basic") or, with none,
  20. // "Generic <material>".
  21. //
  22. // A slot with no match is not guessed at: the picker shows it greyed out
  23. // rather than turning its bare material into some profile.
  24. import type {
  25. LoadedSpoolPreset,
  26. LoadedSpoolPrinter,
  27. LoadedSpoolTray,
  28. PresetRef,
  29. PresetSource,
  30. UnifiedPreset,
  31. UnifiedPresetsResponse,
  32. } from '../api/client';
  33. import { slotPresetDescribesTray } from './amsHelpers';
  34. import { listedRef, refValue, SLICE_MODAL_TIER_ORDER, statesDifferentMaterial } from './slicePresetPicker';
  35. import {
  36. matchesPrinterModelSuffix,
  37. presetCompatibility,
  38. type PrinterCompatibilityIndex,
  39. } from './slicerPrinterMatch';
  40. /**
  41. * The model short name of a printer profile ("Bambu Lab X1 Carbon 0.4
  42. * nozzle" → "X1C"), or null when the name isn't a Bambu printer profile.
  43. * ``printerModels`` is the backend's long → short registry.
  44. */
  45. export function printerPresetModel(
  46. name: string | null | undefined,
  47. printerModels: Record<string, string>,
  48. ): string | null {
  49. if (!name) return null;
  50. const m = name.replace(/^#\s*/, '').trim().match(/^Bambu Lab\s+(.+?)(?:\s+[\d.]+\s*nozzle)?$/i);
  51. if (!m) return null;
  52. const fragment = m[1].trim();
  53. const full = `bambu lab ${fragment}`.toLowerCase();
  54. for (const [long, short] of Object.entries(printerModels)) {
  55. if (long.toLowerCase() === full) return short;
  56. }
  57. return fragment;
  58. }
  59. export function sameModel(a: string | null | undefined, b: string | null | undefined): boolean {
  60. if (!a || !b) return false;
  61. return matchesPrinterModelSuffix(a.trim(), b.trim());
  62. }
  63. /** Connected printers of ``model``; every connected printer when it's unknown. */
  64. export function printersOfModel(
  65. printers: LoadedSpoolPrinter[],
  66. model: string | null,
  67. ): LoadedSpoolPrinter[] {
  68. if (!model) return printers;
  69. return printers.filter((p) => sameModel(p.model, model));
  70. }
  71. /**
  72. * The model of a printer profile, read from the profile it was saved from
  73. * when there is one: the parent names the model reliably, the user's own name
  74. * ("Bambu Lab P1S 0.4 nozzle - Copy") may not (#3250, #3172).
  75. */
  76. export function printerProfileModel(
  77. name: string | null | undefined,
  78. printerModels: Record<string, string>,
  79. printerParents: Record<string, string> = {},
  80. ): string | null {
  81. if (!name) return null;
  82. const parent = Object.hasOwn(printerParents, name) ? printerParents[name] : null;
  83. return printerPresetModel(parent || name, printerModels);
  84. }
  85. /** Whether a printer profile belongs to a connected model, or can't be told. */
  86. export function isConnectedModelPreset(
  87. preset: Pick<UnifiedPreset, 'name'>,
  88. connectedModels: (string | null)[],
  89. printerModels: Record<string, string>,
  90. printerParents: Record<string, string> = {},
  91. ): boolean {
  92. const model = printerProfileModel(preset.name, printerModels, printerParents);
  93. if (model === null) return true;
  94. return connectedModels.some((c) => sameModel(c, model));
  95. }
  96. /**
  97. * A printer profile for one of the connected models, for the auto-pick while
  98. * "only online printers" is on. Prefers the 0.4 nozzle, Bambu's default, as
  99. * nothing here says which nozzle is fitted.
  100. */
  101. export function pickConnectedPrinterPreset(
  102. data: UnifiedPresetsResponse,
  103. connectedModels: (string | null)[],
  104. printerModels: Record<string, string>,
  105. printerParents: Record<string, string> = {},
  106. ): PresetRef | null {
  107. let fallback: PresetRef | null = null;
  108. for (const source of SLICE_MODAL_TIER_ORDER) {
  109. for (const preset of data[source].printer) {
  110. const model = printerProfileModel(preset.name, printerModels, printerParents);
  111. if (model === null || !connectedModels.some((c) => sameModel(c, model))) continue;
  112. const ref = { source, id: preset.id };
  113. if (/\b0\.4\s*nozzle\b/i.test(preset.name)) return ref;
  114. fallback ??= ref;
  115. }
  116. }
  117. return fallback;
  118. }
  119. /** A profile name without its "# " clone prefix and "@printer" suffix, case-folded. */
  120. export function presetBaseName(name: string): string {
  121. let s = name.replace(/^#\s*/, '');
  122. const at = s.lastIndexOf('@');
  123. if (at > 0) s = s.slice(0, at);
  124. return s.replace(/\s+/g, ' ').trim().toLowerCase();
  125. }
  126. /** The same, keeping the case, for display. */
  127. export function presetDisplayName(name: string): string {
  128. let s = name.replace(/^#\s*/, '');
  129. const at = s.lastIndexOf('@');
  130. if (at > 0) s = s.slice(0, at);
  131. return s.replace(/\s+/g, ' ').trim();
  132. }
  133. export function isLoaded(tray: LoadedSpoolTray): boolean {
  134. return Boolean(tray.tray_type);
  135. }
  136. /** The saved profile, unless the slot has been reconfigured since (#3216). */
  137. export function savedPresetFor(tray: LoadedSpoolTray): LoadedSpoolPreset | null {
  138. const saved = tray.saved_preset;
  139. if (!saved) return null;
  140. return slotPresetDescribesTray(saved.preset_id, tray.tray_info_idx, saved.tray_info_idx) ? saved : null;
  141. }
  142. function savedRef(saved: LoadedSpoolPreset, data: UnifiedPresetsResponse): PresetRef | null {
  143. if (saved.preset_source === 'local') {
  144. const m = saved.preset_id.match(/^local_(\d+)$/);
  145. return m ? { source: 'local', id: m[1] } : null;
  146. }
  147. if (saved.preset_source === 'cloud' || saved.preset_source === 'orca_cloud') {
  148. // A ref the listing hides is pointed at the twin it lists (#3386).
  149. return saved.preset_id ? listedRef(data, { source: saved.preset_source, id: saved.preset_id }) : null;
  150. }
  151. // "builtin_<filament id>" names a bundled filament by its id, which the
  152. // bundled listing doesn't carry; its saved name is matched below instead.
  153. return null;
  154. }
  155. function nameCandidates(tray: LoadedSpoolTray, saved: LoadedSpoolPreset | null): string[] {
  156. const out: string[] = [];
  157. if (saved?.preset_name) out.push(saved.preset_name);
  158. const sub = (tray.tray_sub_brands ?? '').trim();
  159. if (sub) {
  160. // Bambu's own spools report "PLA Basic"; the profile is "Bambu PLA Basic".
  161. // Only for Bambu filament ids, so a third-party "PLA Basic" isn't renamed.
  162. if (/^GF/i.test(tray.tray_info_idx ?? '') && !/^bambu\b/i.test(sub)) out.push(`Bambu ${sub}`);
  163. out.push(sub);
  164. } else if (tray.tray_type) {
  165. out.push(`Generic ${tray.tray_type}`);
  166. }
  167. const seen = new Set<string>();
  168. return out.filter((n) => {
  169. const key = presetBaseName(n);
  170. if (!key || seen.has(key)) return false;
  171. seen.add(key);
  172. return true;
  173. });
  174. }
  175. interface IndexedPreset {
  176. source: PresetSource;
  177. preset: UnifiedPreset;
  178. }
  179. /** Filament profiles by base name, each list in the dialog's tier order. */
  180. export type FilamentNameIndex = Map<string, IndexedPreset[]>;
  181. export function buildFilamentNameIndex(data: UnifiedPresetsResponse): FilamentNameIndex {
  182. const index: FilamentNameIndex = new Map();
  183. for (const source of SLICE_MODAL_TIER_ORDER) {
  184. for (const preset of data[source].filament) {
  185. const key = presetBaseName(preset.name);
  186. const list = index.get(key);
  187. if (list) list.push({ source, preset });
  188. else index.set(key, [{ source, preset }]);
  189. }
  190. }
  191. return index;
  192. }
  193. export interface SlotMatch {
  194. ref: PresetRef;
  195. preset: UnifiedPreset;
  196. }
  197. /**
  198. * The filament profile for ``tray`` on the selected printer, or null when
  199. * nothing fits. See the header for the order evidence is tried in.
  200. */
  201. export function matchSlotPreset(
  202. tray: LoadedSpoolTray,
  203. data: UnifiedPresetsResponse,
  204. index: FilamentNameIndex,
  205. selectedPrinterName: string | null,
  206. compatIndex: PrinterCompatibilityIndex,
  207. ): SlotMatch | null {
  208. if (!isLoaded(tray)) return null;
  209. const saved = savedPresetFor(tray);
  210. const fits = (p: UnifiedPreset) => presetCompatibility(p, 'filament', selectedPrinterName, compatIndex);
  211. if (saved) {
  212. const ref = savedRef(saved, data);
  213. const preset = ref ? data[ref.source].filament.find((p) => p.id === ref.id) : undefined;
  214. // The user picked this profile for the slot, so its material isn't
  215. // second-guessed — only whether it is for the selected printer.
  216. if (ref && preset && fits(preset) !== 'mismatch') return { ref, preset };
  217. }
  218. const savedSource = saved ? savedRef(saved, data)?.source : undefined;
  219. for (const name of nameCandidates(tray, saved)) {
  220. const entries = index.get(presetBaseName(name)) ?? [];
  221. // The tier the saved profile came from goes first, then the usual order.
  222. const ordered = savedSource
  223. ? [...entries.filter((e) => e.source === savedSource), ...entries.filter((e) => e.source !== savedSource)]
  224. : entries;
  225. let unknown: SlotMatch | null = null;
  226. for (const { source, preset } of ordered) {
  227. if (statesDifferentMaterial(preset, tray.tray_type ?? '')) continue;
  228. const fit = fits(preset);
  229. if (fit === 'match') return { ref: { source, id: preset.id }, preset };
  230. if (fit === 'unknown' && !unknown) unknown = { ref: { source, id: preset.id }, preset };
  231. }
  232. if (unknown) return unknown;
  233. }
  234. return null;
  235. }
  236. /** Every loaded tray of ``printers``, AMS units first, then external holders. */
  237. export function loadedTrays(printers: LoadedSpoolPrinter[]): LoadedSpoolTray[] {
  238. const out: LoadedSpoolTray[] = [];
  239. for (const printer of printers) {
  240. for (const unit of printer.ams) {
  241. for (const tray of unit.trays) if (isLoaded(tray)) out.push(tray);
  242. }
  243. for (const tray of printer.external) if (isLoaded(tray)) out.push(tray);
  244. }
  245. return out;
  246. }
  247. /** Ref values of the profiles matched by at least one loaded tray. */
  248. export function matchedFilamentRefs(
  249. printers: LoadedSpoolPrinter[],
  250. data: UnifiedPresetsResponse,
  251. index: FilamentNameIndex,
  252. selectedPrinterName: string | null,
  253. compatIndex: PrinterCompatibilityIndex,
  254. ): Set<string> {
  255. const out = new Set<string>();
  256. for (const tray of loadedTrays(printers)) {
  257. const match = matchSlotPreset(tray, data, index, selectedPrinterName, compatIndex);
  258. if (match) out.add(refValue(match.ref));
  259. }
  260. return out;
  261. }
  262. /** "#RRGGBB" from the printer's RRGGBBAA, or null when it isn't one. */
  263. export function trayColourHex(tray: Pick<LoadedSpoolTray, 'tray_color'>): string | null {
  264. const raw = (tray.tray_color ?? '').replace(/^#/, '');
  265. return /^[0-9a-fA-F]{6}/.test(raw) ? `#${raw.slice(0, 6).toUpperCase()}` : null;
  266. }