From e3c31e43e51e6f066ee32ffd3a2ffe23283f83b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Thu, 22 Oct 2026 16:37:46 -0300 Subject: [PATCH] feat: residue and a solid background stop a ready sheet before payment Dropstar's items 2 and 3 (2026-10-21): both were warnings the customer could pay past; now one dot is enough to stop the order. - every pixel is read (images in strips at 1:1, large PNGs while they stream, PDFs rendered in strips at about 0,2 mm): the old check shrank the image first and could miss a small dot, or sampled every n-th pixel - a residue is ink under 2 mm on both sides, measured from where the ink starts and ends in each cell: the same dot gets the same verdict wherever it falls on the grid, from 0,5 to 4 mm (his acceptance test) - a solid background is under 1,5 % of transparent pixels; a JPG sheet always has one - the sheet says how many dots there are, circles them on the preview, and asks to erase them and send again; the order waits for the check to end - the page no longer offers JPG for a ready sheet Co-Authored-By: Claude Opus 5.5 --- docs/CONTEXT.md | 6 +- tests/artwork_browser_test.mjs | 48 +++++++++++++-- web/index.html | 12 ++-- web/site-config.js | 4 +- web/site-pdf.js | 105 ++++++++++++++++++++++++++++----- web/site-quality.js | 12 ++++ web/site-sheet.js | 105 +++++++++++++++++++++++---------- web/site-upload.js | 37 ++++++++---- 8 files changed, 258 insertions(+), 71 deletions(-) diff --git a/docs/CONTEXT.md b/docs/CONTEXT.md index 05b2728..176a7be 100644 --- a/docs/CONTEXT.md +++ b/docs/CONTEXT.md @@ -349,7 +349,11 @@ two orders spent in Imprimindo together counts once; a stage's median is per order, the sum of its passages. Layout version 3 (web/site-packing.js): rows with exact sizes, 5 mm margins top and bottom and between rows, and across the width 5 mm or the space left shared out equally (1,5 mm at least); the -shape packing is used only when it saves 1 cm or more. Waiting on +shape packing is used only when it saves 1 cm or more. A ready sheet with a +residue (ink under 2 mm on both sides, measured in pixels from the ink map in +web/site-sheet.js) or without transparency (under 1,5 % of transparent +pixels; every JPG) cannot be paid for; the preview circles each dot. PDFs +over 150 MB and CDR/AI/PSD/TIFF are not checked. Waiting on Dropstar: the Tiny category/seller/tag conflict, residue and opaque background blocking, the print-file footer, the packing margins, the DTF terms, the manual-file value, the proof print, and mirroring. diff --git a/tests/artwork_browser_test.mjs b/tests/artwork_browser_test.mjs index 642472d..01b6da1 100644 --- a/tests/artwork_browser_test.mjs +++ b/tests/artwork_browser_test.mjs @@ -133,12 +133,15 @@ try{ if(drop)$('zona').dispatchEvent(new DragEvent('drop',{dataTransfer:dt,bubbles:true,cancelable:true})); else{$('inp').files=dt.files;$('inp').dispatchEvent(new Event('change',{bubbles:true}));} }; - // A genuine mounted sheet spans the film width with printable resolution. - window.sendSheet=async()=>{ + // A genuine mounted sheet spans the film width with printable resolution, + // on a transparent background; or with a solid one, or a residue dot. + window.sendSheet=async({fundo=false,ponto=false}={})=>{ const cm=larguraFilme(), px=Math.ceil(cm/2.54*150); const c=document.createElement('canvas');c.width=px;c.height=Math.round(px*0.6); - const ctx=c.getContext('2d');ctx.fillStyle='white';ctx.fillRect(0,0,c.width,c.height); + const ctx=c.getContext('2d'); + if(fundo){ctx.fillStyle='white';ctx.fillRect(0,0,c.width,c.height);} ctx.fillStyle='#222';ctx.fillRect(40,40,px/4,px/4); + if(ponto)ctx.fillRect(Math.round(px*0.8),Math.round(c.height/2),4,4); const blob=await new Promise(r=>c.toBlob(r,'image/png')); const dt=new DataTransfer();dt.items.add(new File([blob],'folha-montada.png',{type:'image/png'})); $('inp').files=dt.files;$('inp').dispatchEvent(new Event('change',{bubbles:true})); @@ -273,6 +276,39 @@ try{ assert.equal(await evaluate(`document.querySelectorAll('.folhaPrevia').length`),1); await evaluate(`(()=>{folhas.push({f:new File(['manual'],'manual.cdr'),med:null,rep:1,m:1,an:null});pintaFolha();})()`); await waitFor(()=>evaluate(`itemAtual?.nota===0 && itemAtual?.unit===TABELA[modo]`),'mixed analyzed and manual sheets use table pricing'); + // Residue and a solid background stop the order before payment (Dropstar, + // 2026-10-21). A residue is ink under 2 mm on both sides, measured in real + // millimetres: the same dot, wherever it falls on the 1 mm grid, gets the + // same verdict, from 0,5 to 4 mm. + assert.deepEqual(await evaluate(`(async()=>{ + const medir=async(mm,dx,dy)=>{const c=document.createElement('canvas');c.width=5700;c.height=600; + const ctx=c.getContext('2d');ctx.fillStyle='#000';ctx.fillRect(100,100,3000,300); + const lado=Math.round(mm*10);ctx.fillRect(4000+dx,300+dy,lado,lado); + return analisarMapa(await mapaDaImagem(c,57)).residuos;}; + const out={}; + for(const mm of [0.5,1.5,1.9,2.1,4])out[mm]=[await medir(mm,0,0),await medir(mm,5,0),await medir(mm,0,5),await medir(mm,5,5)]; + return out;})()`), + {'0.5':[1,1,1,1],'1.5':[1,1,1,1],'1.9':[1,1,1,1],'2.1':[0,0,0,0],'4':[0,0,0,0]}); + // A large PNG is read as a stream; every pixel goes into the same ink map. + assert.deepEqual(await evaluate(`(async()=>{ + const c=document.createElement('canvas');c.width=5700;c.height=600; + const ctx=c.getContext('2d');ctx.fillStyle='#000';ctx.fillRect(100,100,3000,300);ctx.fillRect(4005,305,12,12); + const blob=await new Promise(r=>c.toBlob(r,'image/png')); + const lido=await previaPngGrande(new File([blob],'folha.png'),600,null,57); + const a=analisarMapa(lido.mapa), b=analisarMapa(await mapaDaImagem(c,57)); + return {stream:[a.residuos,a.artes,a.fundoChapado,a.pontos[0].mm],direct:[b.residuos,b.artes,b.fundoChapado,b.pontos[0].mm]};})()`), + {stream:[1,1,false,1.2],direct:[1,1,false,1.2]}); + await click('#bVoltar');await click('[data-modo="file"]'); + await evaluate('sendSheet({ponto:true})'); + await waitFor(()=>evaluate(`folhas.length===1 && folhas[0].pct==null && folhas[0].an?.residuos===1`),'residue found'); + await waitFor(()=>evaluate(`$('aoVivo').textContent.includes('ponto de recorte') && itemAtual===null`),'residue stops the order'); + assert.equal(await evaluate(`$('lista').textContent.includes('Sobrou 1 ponto de recorte na sua folha')`),true); + await waitFor(()=>evaluate(`folhas[0].previewSrc.startsWith('data:image/webp')`),'residue circled on the preview'); + await evaluate(`folhas=[];pintaFolha()`); + await evaluate('sendSheet({fundo:true})'); + await waitFor(()=>evaluate(`folhas[0]?.an?.fundoChapado===true && itemAtual===null && $('aoVivo').textContent.includes('fundo transparente')`),'solid background stops the order'); + assert.equal(await evaluate(`$('lista').textContent.includes('O fundo da sua folha não é transparente')`),true); + await evaluate(`folhas=[];pintaFolha()`); // An image too small to span the film is refused, never silently repriced. await click('#bVoltar');await click('[data-modo="file"]'); await evaluate('sendImage()'); @@ -296,6 +332,10 @@ try{ assert.deepEqual(rotated,{larg:50.8,alt:25.4,fonte:'página do PDF · UserUnit 2'}); const rendered=await evaluate(`rasterizarPdf(${pdfFile(pdfData({media:'[0 0 720 1440]',crop:'[0 0 360 720]',rotate:90,unit:2}))},50.8,25.4).then(r=>({ok:!!r.tela,error:r.erro||null}))`); assert.deepEqual(rendered,{ok:true,error:null}); + // A PDF sheet gets the same ink map, rendered in strips: a blank page is all transparent. + const mapped=await evaluate(`rasterizarPdf(${pdfFile(pdfData())},25.4,12.7,true).then(r=>{const a=analisarMapa(r.mapa); + return {fundo:a.fundoChapado,residuos:a.residuos,largura:r.mapa.wPx}})`); + assert.deepEqual(mapped,{fundo:false,residuos:0,largura:1270}); const multi=await evaluate(`medirFolha(${pdfFile(pdfData({pages:2}))})`); assert.equal(multi.rejected,true);assert.match(multi.reason,/2 páginas/); const beyondSpec=await evaluate(`medirFolha(${pdfFile(pdfData({media:'[0 0 20000 720]'}))})`); @@ -368,6 +408,6 @@ try{ console.log('Supplied image:',JSON.stringify(layout)); } assert.deepEqual(errors,[]); - console.log('PASS: JPG/PNG upload and drop, packed copies, 5 mm gaps, aspect ratio, live width/quantity/rotation/mirror, metres, ready-sheet pricing/repeats, UV, stale renders, strict inline CSP.'); + console.log('PASS: JPG/PNG upload and drop, packed copies, 5 mm gaps, aspect ratio, live width/quantity/rotation/mirror, metres, ready-sheet pricing/repeats, residue and solid background stop the order, UV, stale renders, strict inline CSP.'); }catch(error){console.error(error);if(stderr)console.error(stderr.slice(-1200));process.exitCode=1;} finally{ws?.close();chrome.kill();server.closeAllConnections();await new Promise(r=>server.close(r));} diff --git a/web/index.html b/web/index.html index 47a03cf..3c7c902 100644 --- a/web/index.html +++ b/web/index.html @@ -879,8 +879,8 @@ h2 em{font-style:normal;color:var(--laranja)}
Manda em PNG e sai na hora
    -
  • PNG ou JPG com fundo transparente entram direto, sem passar - por ninguém, e não têm limite de comprimento. Só que a gente lê a resolução +
  • PNG com fundo transparente entra direto, sem passar + por ninguém, e não tem limite de comprimento. Só que a gente lê a resolução do arquivo: se a arte foi ampliada antes de exportar, isso não aparece para nós — e sai serrilhado no filme do mesmo jeito
  • PDF é o que conferimos melhor. Nele medimos a resolução de @@ -891,6 +891,8 @@ h2 em{font-style:normal;color:var(--laranja)}
  • TIFF, PSD, AI e CDR a gente aceita, mas ninguém consegue conferir sozinho: alguém abre na mão, sai mais devagar e o metro vai pela tabela, sem desconto de nota
  • +
  • Folha em JPG não passa: JPG não tem fundo transparente, e o + branco do fundo sai no filme. Exporte a folha em PNG ou PDF
  • Em artes avulsas só PNG e JPG: a montagem precisa enxergar a sua arte para encaixar pela forma
@@ -900,9 +902,11 @@ h2 em{font-style:normal;color:var(--laranja)} O que só você resolve
  • Fundo branco ou colorido. Precisa ser transparente de - verdade — branco parecendo transparente sai branco no filme
  • + verdade — branco parecendo transparente sai branco no filme. Sem isso, o site + não deixa pagar
  • Pontinho de recorte. A impressora enxerga qualquer - resíduo e imprime. Não existe pequeno demais
  • + resíduo e imprime. Não existe pequeno demais: o site mostra onde cada um está + e só deixa pagar depois que você apagar
  • Cópias sobrepostas. Duas iguais com 1 mm de diferença saem duplicadas
  • Menos de 96 DPI. Abaixo disso não imprimimos: sai diff --git a/web/site-config.js b/web/site-config.js index 256599d..b0636f0 100644 --- a/web/site-config.js +++ b/web/site-config.js @@ -35,12 +35,12 @@ const fmt=b=>b<1048576?(b/1024).toFixed(0)+' KB' // ── modos const MODOS={ file: {tit:'Arquivo por metro', lg:'DTF têxtil · 57 cm', larg:57, multi:true, folha:true, - zt:'Arraste sua folha montada aqui', zs:'PNG, JPG ou PDF · 57 cm de largura'}, + zt:'Arraste sua folha montada aqui', zs:'PNG ou PDF com fundo transparente · 57 cm de largura'}, avulsa:{tit:'Artes avulsas', lg:'DTF têxtil · 57 cm', larg:57, multi:true, zt:'Arraste suas artes aqui', zs:'PNG ou JPG com fundo transparente · informe a largura de cada uma'}, uvfile:{tit:'Arquivo por metro · UV', lg:'Adesivo UV · 28,5 cm', larg:28.5, multi:true, folha:true, - zt:'Arraste sua folha de UV aqui', zs:'PNG, JPG ou PDF · 28,5 cm de largura'}, + zt:'Arraste sua folha de UV aqui', zs:'PNG ou PDF com fundo transparente · 28,5 cm de largura'}, uv: {tit:'Artes avulsas · UV', lg:'Adesivo UV · 28,5 cm', larg:28.5, multi:true, zt:'Arraste suas artes de UV', zs:'PNG ou JPG com fundo transparente · informe a largura de cada arte'} diff --git a/web/site-pdf.js b/web/site-pdf.js index c2baed5..e717ad2 100644 --- a/web/site-pdf.js +++ b/web/site-pdf.js @@ -85,11 +85,14 @@ function resumoDpi(lista){ } // Rasteriza a primeira página a 1 mm por pixel e devolve a tela para a análise -async function rasterizarPdf(file, larguraCm, alturaCm){ +// The page drawn small for the preview and, with comMapa, again in strips at +// about 0,2 mm per pixel for the ink map the residue check measures. +const PDF_PX_POR_CM=50, PDF_MAPA_PX=30e6; +async function rasterizarPdf(file, larguraCm, alturaCm, comMapa){ const lib=await carregarPdfJs(); if(!lib) return {erro:'não foi possível carregar o leitor de PDF'}; // Decide after the worker check; the old timeout always used 30 seconds. - const espera=temWorker===false ? 90000 : 30000; + const espera=(temWorker===false ? 90000 : 30000)*(comMapa ? 2 : 1); const folga=temWorker===false ? 2.2 : 1; let loading=null, doc=null, rendering=null, expired=false, timer=null; const trabalho=(async()=>{ @@ -117,7 +120,28 @@ async function rasterizarPdf(file, larguraCm, alturaCm){ let dpis=[]; try{ dpis=dpiDasImagens(page,ops); }catch(e){} const r=resumoDpi(dpis); - return {tela:cv, dpi:r? r.ponderado:null, res:r}; + let mapa=null; + if(comMapa){ + const altura=alturaCm||larguraCm*vp1.height/vp1.width; + const pxPorCm=Math.min(PDF_PX_POR_CM, Math.sqrt(PDF_MAPA_PX/(larguraCm*altura))); + const vpM=page.getViewport({scale:pxPorCm*larguraCm/vp1.width}); + const W=Math.max(1,Math.round(vpM.width)), H=Math.max(1,Math.round(vpM.height)); + mapa=novoMapa(W,H,larguraCm); + const faixa=Math.max(1,Math.min(H,Math.floor(4e6/W))); + const cvM=document.createElement('canvas'); cvM.width=W; cvM.height=faixa; + const ctxM=cvM.getContext('2d',{willReadFrequently:true}); + for(let topo=0;topo{ + if(tipo===3){ for(let x=0;x{}); leitor.cancel().catch(()=>{}); - return y>=h ? cv : null; + if(y{ const im=new Image(); im.onload=()=>res(im); im.onerror=()=>res(null); im.src=src; }); + if(!img) return src; + const s=Math.min(1,1200/img.naturalWidth), cv=document.createElement('canvas'); + cv.width=Math.max(1,Math.round(img.naturalWidth*s)); cv.height=Math.max(1,Math.round(img.naturalHeight*s)); + const ctx=cv.getContext('2d'); + ctx.drawImage(img,0,0,cv.width,cv.height); + const r=Math.max(9,cv.width*0.014); + ctx.lineWidth=Math.max(2,r/4); ctx.strokeStyle='#E0301E'; ctx.font='700 '+Math.round(r*1.1)+'px Inter, sans-serif'; + for(const p of pontos){ + const x=p.x*cv.width, y=p.y*cv.height; + ctx.beginPath(); ctx.arc(x,y,r,0,2*Math.PI); ctx.stroke(); + const t=n1(p.mm)+' mm', tw=ctx.measureText(t).width, tx=Math.min(x+r+4,cv.width-tw-4); + ctx.fillStyle='rgba(255,255,255,.9)'; ctx.fillRect(tx-3,y-r*0.7,tw+6,r*1.4); + ctx.fillStyle='#E0301E'; ctx.fillText(t,tx,y+r*0.4); + } + return cv.toDataURL('image/webp',0.9); +} // Moves one sheet's progress bar in place: repainting the whole list and the // preview on every step made "Sua folha" flicker while a large file was read. function pintaProgressoFolha(x){ @@ -381,17 +444,27 @@ function chipsDaFolha(a){ const dpi = a.vetor ? chip('ok','Arte vetorial') : chip(a.dpi>=DPI_AVISA?'ok':a.dpi>=DPI_RECUSA?'av':'er', a.dpi+' DPI'); if(a.grande) return dpi+chip('nt','Peças, resíduos e fundo: a equipe confere'); - return dpi+ - (a.fundoChapado? chip('er','Fundo chapado') : chip('ok','Fundo transparente'))+ + // Sem transparência a folha inteira é uma peça só: não há resíduo a contar. + if(a.fundoChapado) return dpi+chip('er','Fundo chapado'); + return dpi+chip('ok','Fundo transparente')+ (a.residuos? chip('er',a.residuos+' resíduo'+(a.residuos>1?'s':'')) : chip('ok','Sem resíduos'))+ (a.encostadas? chip('fix',a.encostadas+' peças coladas · separamos grátis') : chip('ok','Peças separadas')); } -function avisosDaFolha(a){ +// Resíduo e fundo chapado barram o pedido (Dropstar, 21/10/2026): o texto diz +// quantos pontos, onde estão e o que fazer, sem "arquivo com problema". +function avisosDaFolha(a,nome){ if(a.grande) return ''; - return (a.fundoChapado? '

    O fundo não é transparente. '+ - 'Branco parecendo transparente sai branco no filme. Exporte com fundo transparente.

    ' : '')+ - (a.residuos? '

    '+a.residuos+' pontinho'+(a.residuos>1?'s soltos serão impressos':' solto será impresso')+ - '. A impressora imprime qualquer resíduo de recorte. Apague no arquivo e envie de novo.

    ' : ''); + if(a.fundoChapado) return /\.jpe?g$/i.test(nome||'') + ? '

    JPG não tem fundo transparente. O que parece branco na tela sai branco '+ + 'no filme. Exporte a folha em PNG ou PDF, com fundo transparente, e envie de novo.

    ' + : '

    O fundo da sua folha não é transparente. O que parece branco na tela sai '+ + 'branco no filme. Exporte a folha com fundo transparente, em PNG ou PDF, e envie de novo.

    '; + if(!a.residuos) return ''; + const n=a.residuos, varios=n>1; + return '

    '+(varios?'Sobraram ':'Sobrou ')+n+(varios?' pontos':' ponto')+ + ' de recorte na sua folha. São restos da remoção de fundo: não aparecem na sua tela, mas a '+ + 'impressora enxerga e imprime. Apague '+(varios?'os pontos':'o ponto')+' na ferramenta que você '+ + 'usou e envie de novo. '+(varios?'Os círculos vermelhos na prévia mostram onde estão.':'O círculo vermelho na prévia mostra onde está.')+'

    '; } function detalhesDaFolha(a,i,aberto){ const linhas = a.grande @@ -423,7 +496,7 @@ function pintaFolha(){ if(lido){ medida='
    '+n1(x.med.larg)+' × '+n1(x.med.alt)+' cm'+ ''+escapeHTML(extDe(x.f.name))+' · '+fmt(x.f.size)+'
    '+ - (a? '
      '+chipsDaFolha(a)+'
    '+avisosDaFolha(a)+detalhesDaFolha(a,i,x.detAberto) : '')+ + (a? '
      '+chipsDaFolha(a)+'
    '+avisosDaFolha(a,x.f.name)+detalhesDaFolha(a,i,x.detAberto) : '')+ (suspeito? '

    Este PDF passa do tamanho que o formato comporta. '+ 'A especificação para em 508 cm e o seu tem '+n1(x.med.alt)+' cm. '+ 'Ele abre certo só em quem o gerou — aqui vai precisar de tratamento. '+ diff --git a/web/site-quality.js b/web/site-quality.js index e9327da..0719e1e 100644 --- a/web/site-quality.js +++ b/web/site-quality.js @@ -3,6 +3,9 @@ Loaded as classic scripts in the order listed there: they share one global scope and run top to bottom, exactly as the original did. */ // ── enviar +// Folha que a impressora estragaria: com resíduo de recorte ou sem fundo +// transparente. Só vale para o que o navegador conferiu. +const folhaBarrada=x=>!!(x.an && !x.an.grande && (x.an.fundoChapado || x.an.residuos)); // Avalia sozinho conforme o cliente sobe e preenche. Devolve o que ainda falta, // para a fila dizer em texto em vez de travar num botão. function avaliar(){ @@ -16,6 +19,15 @@ function avaliar(){ const semMedida=folhas.filter(x=>!(x.m>0)).length; if(semMedida) return {pronto:false, falta:'Informe o comprimento de '+semMedida+ ' folha'+(semMedida>1?'s':'')+'.'}; + // Resíduo e fundo chapado barram antes do pagamento, com um ponto só + // (Dropstar, 21/10/2026): então o pedido espera a conferência terminar. + const lendo=folhas.find(x=>x.pct!=null); + if(lendo) return {pronto:false, falta:'Conferindo '+lendo.f.name+'…'}; + const barrada=folhas.find(folhaBarrada); + if(barrada) return {pronto:false, falta:barrada.an.fundoChapado + ? barrada.f.name+' está sem fundo transparente. Exporte a folha com fundo transparente, em PNG ou PDF, e envie de novo.' + : barrada.f.name+' tem '+barrada.an.residuos+' ponto'+(barrada.an.residuos>1?'s':'')+ + ' de recorte. Apague e envie de novo.'}; metros=folhaTotalM(); reencaixado=false; const ans=folhas.map(x=>x.an).filter(Boolean); diff --git a/web/site-sheet.js b/web/site-sheet.js index 1d2799e..f5f3eeb 100644 --- a/web/site-sheet.js +++ b/web/site-sheet.js @@ -3,7 +3,7 @@ Loaded as classic scripts in the order listed there: they share one global scope and run top to bottom, exactly as the original did. */ // ── Análise real da folha: lê o canal alfa, separa cada ilha de arte e mede. -// Grade de 1 mm. Só roda em arquivo que o navegador abre; PDF precisa do servidor. +// A grade de 1 mm agrupa a tinta; a medida de cada ilha sai dos pixels. const MM=0.1; // grade fina: 1 mm const CELULAS_MAX=1200000; // teto de custo da análise // Folha grande vira grade mais grossa. Sem isso, 57 x 480 cm dá 2,7 milhões de @@ -46,39 +46,75 @@ function grupos(bits,cw,ch){ return {marca,n}; } +// ── Mapa de tinta: cada pixel da folha lido, nenhum pulado. +// Regra da Dropstar (21/10/2026): resíduo é uma ilha de tinta menor que 2 mm +// nos dois lados, e um ponto só já barra o pedido. Reduzir a imagem antes de +// olhar perde ponto pequeno, e medir pela grade erra até uma célula: o mesmo +// ponto de 1,5 mm saía resíduo ou arte conforme caía na grade. Aqui a grade só +// agrupa; cada célula guarda onde a tinta começa e termina, em pixels, e cada +// ilha é medida por esses extremos, em milímetros reais. +const ALFA_TINTA=10; // acima disto o pixel leva tinta (e branco de base) +function novoMapa(wPx,hPx,larguraCm){ + const pxPorCm=wPx/larguraCm, passo=passoDe(larguraCm,hPx/pxPorCm), pxCel=passo*pxPorCm; + const cw=Math.max(1,Math.ceil(wPx/pxCel)), ch=Math.max(1,Math.ceil(hPx/pxCel)), n=cw*ch; + const colDe=new Uint32Array(wPx); + for(let x=0;xx1[c]) x1[c]=x; y1[c]=y; } + } + m.tinta+=tinta; +} +// Uma imagem que o navegador abre, lida em faixas no tamanho real (1:1). +async function mapaDaImagem(img,larguraCm){ + const w=img.naturalWidth||img.width, h=img.naturalHeight||img.height; + const m=novoMapa(w,h,larguraCm); + const faixa=Math.max(1,Math.min(h,Math.floor(4e6/w))); + const cv=document.createElement('canvas'); cv.width=w; cv.height=faixa; + const ctx=cv.getContext('2d',{willReadFrequently:true}); + ctx.imageSmoothingEnabled=false; + for(let topo=0;toposetTimeout(r)); // a página não congela + } + return m; +} + // ── O que a folha permite medir, e só isso. -// Peça = pixels a menos de 2 mm entre si · letras de uma palavra ficam juntas. +// Peça = tinta a menos de 2 mm entre si · letras de uma palavra ficam juntas. // Encostadas = peças que só se unem quando a folga chega a 6 mm. const R_PECA=1, R_PERTO=2; // peça: 2 mm · aviso de encostadas: 4 mm -function analisarFolha(img, larguraCm){ - const alturaCmEst=larguraCm*img.height/img.width; - const passo=passoDe(larguraCm, alturaCmEst); - const cw=Math.max(8,Math.round(larguraCm/passo)); - const ch=Math.max(8,Math.round(cw*img.height/img.width)); - const cv=document.createElement('canvas'); cv.width=cw; cv.height=ch; - const ctx=cv.getContext('2d',{willReadFrequently:true}); - ctx.clearRect(0,0,cw,ch); ctx.drawImage(img,0,0,cw,ch); - const d=ctx.getImageData(0,0,cw,ch).data; - - const bits=new Uint8Array(cw*ch); - let opacos=0; - for(let i=0,j=3;i10){ bits[i]=1; opacos++; } - - // peças: agrupa pela distância real entre pixels +const RESIDUO_MM=2; +function analisarMapa(m){ + const {cw,ch,bits}=m; const gp=grupos(inchar(bits,cw,ch,R_PECA), cw, ch); const caixas=[]; for(let p=0;pc.x1)c.x1=x; if(yc.y1)c.y1=y; - c.area++; + const c=caixas[id] || (caixas[id]={x0:m.x0[p],x1:m.x1[p],y0:m.y0[p],y1:m.y1[p],id}); + if(m.x0[p]c.x1)c.x1=m.x1[p]; + if(m.y0[p]c.y1)c.y1=m.y1[p]; } - const pecasTodas=caixas.filter(Boolean); - const limRes=Math.max(1, Math.round(0.2/passo)); // 2 mm na grade em uso - const residuos=pecasTodas.filter(o=>(o.x1-o.x0)!((o.x1-o.x0)px/m.pxPorCm*10; + const ilhas=caixas.filter(Boolean).map(c=>({...c, wMm:mm(c.x1-c.x0+1), hMm:mm(c.y1-c.y0+1)})); + const residuos=ilhas.filter(c=>c.wMmc.id)); // encostadas: peças diferentes que se unem quando a folga chega a 6 mm const gper=grupos(inchar(bits,cw,ch,R_PERTO), cw, ch); @@ -86,22 +122,27 @@ function analisarFolha(img, larguraCm){ for(let p=0;p{ if(set.size>1) encostadas+=set.size; }); + const total=m.wPx*m.hPx; return { - dpi: Math.round(img.width/(larguraCm/2.54)), - artes: artes.length, + dpi: Math.round(m.wPx/(m.larguraCm/2.54)), + artes: ilhas.length-residuos.length, residuos: residuos.length, + // Onde está cada ponto, em fração da folha: os círculos da prévia. + pontos: residuos.map(c=>({x:(c.x0+c.x1+1)/2/m.wPx, y:(c.y0+c.y1+1)/2/m.hPx, + mm:+Math.max(c.wMm,c.hMm).toFixed(1)})), encostadas, - fundoChapado: opacos/(cw*ch) > 0.985, - aproveitamento: Math.max(1,Math.min(100,Math.round(opacos/(cw*ch)*100))), - alturaCm: ch*passo, - grade: +(passo*10).toFixed(1) // mm por célula analisada + // Sem transparência: o que parece branco na tela sai branco no filme. + fundoChapado: (total-m.tinta)/total < 0.015, + aproveitamento: Math.max(1,Math.min(100,Math.round(m.tinta/total*100))), + alturaCm: m.hPx/m.pxPorCm, + grade: +(m.passo*10).toFixed(1) // mm por célula que agrupa }; } diff --git a/web/site-upload.js b/web/site-upload.js index fd34818..69a03ff 100644 --- a/web/site-upload.js +++ b/web/site-upload.js @@ -28,6 +28,12 @@ Z.addEventListener('keydown',e=>{if(e.key==='Enter'||e.key===' '){I.click();e.pr if(ev==='drop') sel([...e.dataTransfer.files]); })); I.addEventListener('change',()=>sel([...I.files])); +// A sheet with residue gets its preview circled where the dots are. +async function marcaResiduos(x){ + if(!(x.an && x.an.residuos && !x.an.fundoChapado && x.previewSrc && x.an.pontos?.length)) return; + const marcada=await previaMarcada(x.previewSrc, x.an.pontos); + if(folhas.includes(x)){ x.previewSrc=marcada; pintaFolha(); } +} function sel(fs){ if(!fs.length) return; // Pixels cannot tell a loose artwork from a finished sheet, so the customer @@ -64,6 +70,8 @@ function sel(fs){ // stream into a small copy: the preview, and the sheet check. x.an={dpi:md.dpiFolha, grande:true, artes:0, residuos:0, encostadas:0, fundoChapado:false, aproveitamento:0, alturaCm:md.alt, fonteDpi:'arquivo'}; + // A JPG has no transparency: its background is always solid. + if(/\.jpe?g$/i.test(x.f.name)){ x.an={...x.an, grande:false, fundoChapado:true, residuos:0, pontos:[]}; } if(!/\.png$/i.test(x.f.name)){ x.pct=null; pintaFolha(); return; } x.pct=60; x.leitura={inicio:Date.now(), p:0}; pintaFolha(); let mostrado=0; @@ -71,36 +79,41 @@ function sel(fs){ const pct=60+Math.floor(p*38); x.leitura.p=p; if(pct-mostrado>=1){ mostrado=pct; x.pct=pct; pintaProgressoFolha(x); } - }).then(cv=>{ - if(cv && folhas.includes(x)){ + }, md.larg).then(lido=>{ + if(lido && folhas.includes(x)){ + const cv=lido.cv; x.previewSrc=cv.toDataURL('image/webp',0.85); x.miniSrc=miniatura(cv); x.fotoSrc=miniatura(cv,480,720); try{ - const an=analisarFolha(cv, md.larg); + const an=analisarMapa(lido.mapa); x.an={...an, dpi:md.dpiFolha, fonteDpi:'arquivo', grande:false}; }catch(e){} } - }).catch(()=>{}).finally(()=>{ x.pct=null; pintaFolha(); }); + }).catch(()=>{}).finally(()=>{ x.pct=null; pintaFolha(); marcaResiduos(x); }); }else if(md && RENDERIZA.test(x.f.name)){ - carregarImagem(x.f).then(img=>{ - if(img){ x.previewSrc=img.src; x.miniSrc=miniatura(img); x.fotoSrc=miniatura(img,480,720); try{ x.an=analisarFolha(img, md.larg); if(x.an) x.an.fonteDpi='arquivo'; } - catch(e){} } - x.pct=null; pintaFolha(); + carregarImagem(x.f).then(async img=>{ + if(img){ + x.previewSrc=img.src; x.miniSrc=miniatura(img); x.fotoSrc=miniatura(img,480,720); + x.pct=80; pintaFolha(); + try{ x.an={...analisarMapa(await mapaDaImagem(img, md.larg)), fonteDpi:'arquivo'}; }catch(e){} + } + x.pct=null; pintaFolha(); marcaResiduos(x); }); }else if(md && /\.pdf$/i.test(x.f.name) && x.f.size>GRANDE_BYTES){ x.semAnalise='PDF grande: a resolução das imagens de dentro é conferida pela equipe'; x.pct=null; pintaFolha(); }else if(md && /\.pdf$/i.test(x.f.name)){ x.pct=70; pintaFolha(); - rasterizarPdf(x.f, md.larg, md.alt).then(r=>{ + rasterizarPdf(x.f, md.larg, md.alt, true).then(r=>{ if(r && r.erro){ x.semAnalise = r.erro + (r.semWorker ? ' · este navegador não deixa o leitor rodar em segundo plano' : ''); } - if(r && r.tela){ + if(r && r.tela && r.mapa){ x.miniSrc=miniatura(r.tela); x.fotoSrc=miniatura(r.tela,480,720); + x.previewSrc=r.tela.toDataURL('image/webp',0.85); try{ - x.an=analisarFolha(r.tela, md.larg); + x.an=analisarMapa(r.mapa); // vetor puro não tem resolução · nota máxima, e está certo x.an.dpi = r.dpi==null ? DPI_AVISA : r.dpi; x.an.vetor = r.dpi==null; @@ -108,7 +121,7 @@ function sel(fs){ x.an.res = r.res || null; }catch(e){} } - x.pct=null; pintaFolha(); + x.pct=null; pintaFolha(); marcaResiduos(x); }); }else{ x.pct=null; pintaFolha(); } });