From d1d180805d8006f32b0a7052c12a3f88edac2696 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 09:26:19 -0800 Subject: [PATCH 01/47] i18n: Hindi labels use the interface sense of their English MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 85 Hindi rows used an unrelated sense of their English word. Desired read as देसी (local), and the range message dropped or garbled the desired bound; rulers read as शासक (sovereigns), text characters as चरित्र (personality), vector points and printer's marks as अंक (digits), fills as the verb भरता, High Contrast as उच्च न्यायालय (high court), Hide Thumbnails as हिंदुस्तान, Same as समीर and Even as शाम (evening). They now use the catalog's terms: वांछित, रूलर, कैरेक्टर, पॉइंट, मार्क्स, फ़िल्स and the plain words for the rest. The Hindi glossary test rejects each of these senses in every row whose English names the word, and the meaning test pins Desired and both range messages, minimum <= desired <= maximum. --- crates/ui-egui/src/i18n/hi.tsv | 170 +++++++++++++++---------------- crates/ui-egui/src/i18n/tests.rs | 33 +++++- docs/localization-hi.md | 17 +++- docs/localization-parity.md | 2 +- docs/target-app-parity.md | 1 + 5 files changed, 132 insertions(+), 91 deletions(-) diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 017bc03750..81a4b436ee 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -747,8 +747,8 @@ antiAlias Sharp शार्प Change Case प्रकरण बदलें Change Panel Layout पैनल लेआउट बदलें Change Screen Mode (F) स्क्रीन मोड बदलें (F) - Change to Artboard Rulers आर्टबोर्ड शासकों में परिवर्तन - Change to Global Rulers वैश्विक शासकों में परिवर्तन + Change to Artboard Rulers आर्टबोर्ड रूलर्स में परिवर्तन + Change to Global Rulers ग्लोबल रूलर्स में परिवर्तन Change to Left-to-Right Layout लेफ्ट-टू-राइट लेआउट में परिवर्तन Change to Right-to-Left Layout राइट-टू-लेफ्ट लेआउट में परिवर्तन Changed since the last check. आखिरी चेक के बाद से बदल गया। @@ -764,12 +764,12 @@ antiAlias Sharp शार्प Channel 4 चैनल 4 Character कैरेक्टर Character / Paragraph कैरेक्टर / पैराग्राफ - Character Alignment चरित्र संरेखण - Character Color चरित्र रंग - Character Direction चरित्र निर्देशन - Character options चरित्र ऑप्शन्स - Character Rotation चरित्र रोटेशन - Character Set: चरित्र सेट: + Character Alignment कैरेक्टर संरेखण + Character Color कैरेक्टर रंग + Character Direction कैरेक्टर दिशा + Character options कैरेक्टर ऑप्शन्स + Character Rotation कैरेक्टर रोटेशन + Character Set: कैरेक्टर सेट: Character Style कैरेक्टर स्टाइल Character Style Options कैरेक्टर स्टाइल ऑप्शन्स Character Styles कैरेक्टर स्टाइल्स @@ -959,7 +959,7 @@ antiAlias Sharp शार्प Compatible Gradient and Gradient Mesh Printing कंपैटिबल ग्रेडिएंट और ग्रेडिएंट मेश प्रिंटिंग Compiled or not text संकलित या टेक्स्ट नहीं Compiled script: ask its author for the .jsx file कंपाइल की हुई स्क्रिप्ट: इसके लेखक से .jsx फ़ाइल माँगें - Complement संगम + Complement पूरक Complementary पूरक Complementary 2 पूरक 2 Complete पूरा करना @@ -976,18 +976,18 @@ antiAlias Sharp शार्प Compression संपीड़न Compression › Color › Above Ppi संपीड़न › रंग › पीपीआई के ऊपर Compression: संपीड़न: - Concave अवतरण + Concave अवतल Concentric Dividers: सांद्रिक विभाजक: Condition identifier: शर्त पहचानकर्ता: Configure Shape आकार को कॉन्फ़िगर करें Conflict {n} of {count} {count} में से विरोध {n} Connect कनेक्ट - Connect Selected End Points कनेक्ट सिलेक्टेड अंत अंक + Connect Selected End Points सिलेक्टेड एंड पॉइंट्स कनेक्ट करें Consider Open Filled Paths as Closed बंद के रूप में ओपन भरा पाथ पर विचार करें Consolidate All Windows सभी विंडो एक साथ लाएँ - Constrain कंस्ट्रक्शन - Constrain Angle कंस्ट्रक्शन एंगल - Constrain Width and Height Proportions कंस्ट्रक्शन चौड़ाई और ऊंचाई के अनुपात + Constrain सीमित करें + Constrain Angle कंस्ट्रेन एंगल + Constrain Width and Height Proportions चौड़ाई और ऊंचाई का अनुपात बनाए रखें Construction Guides निर्माण गाइड Conté Crayon कॉन्टे क्रेयॉन Conté Crayon… कॉन्टे क्रेयॉन… @@ -1162,7 +1162,7 @@ antiAlias Sharp शार्प Cut Artboard कट आर्टबोर्ड Rename Artboards आर्टबोर्ड्स का नाम बदलें Cut Path कट पाथ - Cut Path at Selected Anchor Points सिलेक्टेड एंकर अंक पर पाथ काटें + Cut Path at Selected Anchor Points सिलेक्टेड एंकर पॉइंट्स पर पाथ काटें Cutout कटआउट Cutout… कटआउट… Cyan सियान @@ -1306,7 +1306,7 @@ antiAlias Sharp शार्प Description: विवरण: Deselect डीसिलेक्ट करें Design… डिजाइन… - Desired देसी + Desired वांछित Destination Folder: गंतव्य फ़ोल्डर: Destination: गंतव्य: Detail डिटेल @@ -1335,7 +1335,7 @@ antiAlias Sharp शार्प Dimensions आयाम Direct Selection प्रत्यक्ष सिलेक्शन Direct Selection Tool डायरेक्ट सिलेक्शन टूल - Direct-select anchor points to edit them. उन्हें संपादित करने के लिए डायरेक्ट-सिलेक्शन एंकर अंक। + Direct-select anchor points to edit them. एंकर पॉइंट्स को संपादित करने के लिए उन्हें डायरेक्ट-सिलेक्ट करें। Direction Balance दिशा संतुलन Direction Handles निर्देशन हैंडल Direction: दिशा: @@ -1663,7 +1663,7 @@ antiAlias Sharp शार्प Envelope #10 लिफाफाफा #10 Envelope Distort एन्वेलप डिस्टॉर्ट Envelope DL लिफ़ाफ़ा DL - Envelope Info लिफाफे की जानकारी + Envelope Info एन्वेलप जानकारी Envelope Mesh एन्वेलप मेश Envelope Options एन्वेलप ऑप्शन्स Envelope Options… एन्वेलप ऑप्शन्स… @@ -1674,7 +1674,7 @@ antiAlias Sharp शार्प Eraser Tool इरेज़र टूल Error त्रुटि Esc Esc - Even शाम + Even बराबर Even Fields सम फ़ील्ड्स Even-Numbered Anchors यहां तक कि संख्या वाले एंकर Event: कार्यक्रम: @@ -1847,7 +1847,7 @@ antiAlias Sharp शार्प Fill new strokes नए स्ट्रोक भरें Fill New Type Objects With Placeholder Text नए टाइप ऑब्जेक्ट्स में प्लेसहोल्डर टेक्स्ट भरें Fill Pattern पैटर्न भरें - Fill Rule नियम भरें + Fill Rule फ़िल रूल Fill with Placeholder Text प्लेसहोल्डर टेक्स्ट से भरें Fill: फ़िल: Fill: click for swatches, Shift-click for the color mixer फ़िल: स्वॉचेस के लिए क्लिक करें, कलर मिक्सर के लिए Shift-क्लिक करें @@ -1855,7 +1855,7 @@ antiAlias Sharp शार्प Filled Open Paths भरा खुला पाथ Filled Square भरा वर्ग Filling in form fields and signing फॉर्म फ़ील्ड में भरना और साइन करना - Fills भरता + Fills फ़िल्स Film & Video फ़िल्म और वीडियो Film Grain… फ़िल्म ग्रेन… Filter फ़िल्टर @@ -1959,7 +1959,7 @@ antiAlias Sharp शार्प fonts not copied: {fonts} फ़ॉन्ट कॉपी नहीं हुए: {fonts} Fonts whose licence doesn't allow embedding are not copied. जिन फ़ॉन्ट का लाइसेंस एम्बेडिंग की अनुमति नहीं देता है, उन्हें कॉपी नहीं किया जाता है। For Fractions: फ्रैक्शन के लिए: - Force सेना + Force बलपूर्वक Forced Line Break जबरन लाइन ब्रेक Foreground Level फ़ोरग्राउंड स्तर Forget Import Matches फॉरगेट आयात मैच @@ -1997,7 +1997,7 @@ antiAlias Sharp शार्प Full Width पूर्ण चौड़ाई Fully Inside पूरी तरह से अंदर Fully Outside पूरी तरह बाहर - Function Key: समारोह कुंजी: + Function Key: फ़ंक्शन की: Fuzziness: फ़ज़ीनेस: Gamma गामा Gamut Check गैमट जाँच @@ -2195,8 +2195,8 @@ antiAlias Sharp शार्प Hide Gradient Annotator ग्रेडिएंट एनोटेटर छिपाएँ Hide Grid ग्रिड छिपाएँ Hide Guides गाइड्स छिपाएँ - Hide Hidden Characters छिपे हुए चरित्र छुपाएं - Hide Live Paint Gaps छुपा लाइव पेंट गैप + Hide Hidden Characters हिडन कैरेक्टर छिपाएँ + Hide Live Paint Gaps लाइव पेंट गैप छिपाएँ Hide Note नोट छिपाएँ Hide Options ऑप्शन्स छिपाएँ Hide Others अन्य छिपाएँ @@ -2208,23 +2208,23 @@ antiAlias Sharp शार्प Hide Template टेम्पलेट छिपाएँ Hide Text Threads टेक्स्ट थ्रेड छुपाएं Hide Thumbnail थंबनेल छिपाएँ - Hide Thumbnails हिंदुस्तान + Hide Thumbnails थंबनेल छिपाएँ Hide Transparency Grid पारदर्शिता ग्रिड छिपाएँ Hide Units इकाइयाँ छिपाएँ Hide VectorCraft VectorCraft छिपाएँ - Hide Video Rulers वीडियो शासक + Hide Video Rulers वीडियो रूलर्स छिपाएँ High उच्च High (300 ppi) उच्च (300 ppi) - High Contrast उच्च न्यायालय - High Contrast 2 उच्च न्यायालय 2 - High Contrast 3 उच्च न्यायालय 3 + High Contrast उच्च कंट्रास्ट + High Contrast 2 उच्च कंट्रास्ट 2 + High Contrast 3 उच्च कंट्रास्ट 3 High Fidelity Photo उच्च निष्ठा फोटो High Performance (discrete) उच्च निष्पादन (डिस्क्रीट) High Quality Print उच्च गुणवत्ता वाले प्रिंट High resolution उच्च रिज़ॉल्यूशन High Resolution उच्च रिज़ॉल्यूशन Highlight हाइलाइट - Highlight Alternate Glyphs हाइलाइट अल्टरनेटर ग्लिफ़ + Highlight Alternate Glyphs अल्टरनेट ग्लिफ़ हाइलाइट करें Highlight anchors on mouse over माउस ओवर पर हाइलाइट एंकर Highlight Area हाइलाइट क्षेत्र Highlight Font Name हाइलाइट फ़ॉन्ट नाम @@ -2233,7 +2233,7 @@ antiAlias Sharp शार्प Highlight Substituted Fonts हाईलाइट सबस्टिट्यूटेड फ़ॉन्ट Highlight Substituted Glyphs बदले हुए ग्लिफ़ हाइलाइट करें Highlight Tracking हाइलाइट ट्रैकिंग - Highlight Variable उच्च प्रकाश परिवर्तनीय + Highlight Variable चर हाइलाइट करें Highlight: हाइलाइट: Hindi हिन्दी History हिस्ट्री @@ -2448,7 +2448,7 @@ antiAlias Sharp शार्प Keep Original मूल रखें Keep Plain Text प्लेन टेक्स्ट रखें Keep selected सिलेक्ट करें - Keep Shared Points Together साझा अंक एक साथ रखें + Keep Shared Points Together साझा पॉइंट्स एक साथ रखें Keep the pasted color as a new swatch with a numbered name. पेस्ट किए गए रंग को क्रमांकित नाम वाले नए स्वॉच के रूप में रखें। Keep this row's colors (exclude) इस पंक्ति के रंग (बाहर) रखें Keep visible surfaces only when expanding विस्तार करते समय केवल दृश्यमान सतहों को रखें @@ -2735,7 +2735,7 @@ antiAlias Sharp शार्प Manage Workspaces… वर्कस्पेस प्रबंधित करें… Manually मैन्युअल Marathi मराठी - Mark as trapped निशानेबाज़ी + Mark as trapped ट्रैप्ड के रूप में चिह्नित करें Mark Older Files as [Converted] When Opened पुरानी फ़ाइलें ओपन करने पर उन्हें [Converted] चिह्नित करें Marker… मार्कर… Marks मार्क्स @@ -2806,7 +2806,7 @@ antiAlias Sharp शार्प Minimize छोटा करें Minimum न्यूनतम Minimum angle न्यूनतम कोण - Minimum must not exceed Desired, nor Desired Maximum. न्यूनतम से अधिक नहीं होना चाहिए, न ही अधिकतम होना चाहिए। + Minimum must not exceed Desired, nor Desired Maximum. न्यूनतम, वांछित से अधिक नहीं होना चाहिए और वांछित, अधिकतम से अधिक नहीं होना चाहिए। Minimum: न्यूनतम: Minus Back पीछे वाला घटाएँ Minus Front सामने वाला घटाएँ @@ -3010,7 +3010,7 @@ antiAlias Sharp शार्प Next Segment अगला खंड No नहीं No actions. Press ● to record. कोई कार्रवाई नहीं। प्रेस ● रिकॉर्ड करने के लिए। - No alternates for the selected character. सिलेक्टेड चरित्र के लिए कोई ऑप्शन नहीं। + No alternates for the selected character. सिलेक्टेड कैरेक्टर के लिए कोई अल्टरनेट नहीं। No artboards match. कोई आर्टबोर्ड मैच नहीं। No assets कोई संपत्ति नहीं No assets yet. Collect art with Object › Collect for Export, or drag it into the Asset Export panel. अभी कोई एसेट नहीं है। ऑब्जेक्ट › एक्सपोर्ट के लिए कलेक्ट करें से आर्टवर्क जोड़ें या उसे एसेट एक्सपोर्ट पैनल में ड्रैग करें। @@ -3093,7 +3093,7 @@ antiAlias Sharp शार्प Number of Recent Fonts हाल ही में फ़ॉन्ट की संख्या Number: संख्या: Numbered List क्रमांकित सूची - Numbers Without Units Are Points यूनिट्स के बिना नंबर अंक हैं + Numbers Without Units Are Points यूनिट्स के बिना संख्याएँ पॉइंट में हैं Numerator न्यूमेरेटर Object ऑब्जेक्ट Object Highlighting ऑब्जेक्ट हाइलाइटिंग @@ -3267,7 +3267,7 @@ antiAlias Sharp शार्प Outer Glow… बाहरी ग्लो… Outline रूपरेखा Outline Object रूपरेखा ऑब्जेक्ट - Outline Others अन्य लोग + Outline Others अन्य को आउटलाइन व्यू में दिखाएँ Outline Stroke स्ट्रोक को आउटलाइन में बदलें Outline Text टेक्स्ट को आउटलाइन में बदलें Outlined Strokes रेखांकित स्ट्रोक @@ -3321,7 +3321,7 @@ antiAlias Sharp शार्प Pages पृष्ठ Paint Daubs पेंट डॉब्स Paint Daubs… पेंट डॉब्स… - Paint Fills पेंट भरता + Paint Fills फ़िल्स पेंट करें Paint Opacity: पेंट ओपेसिटी: Paint Stops At: पेंट स्टॉप: Paint Strokes पेंट स्ट्रोक @@ -3526,7 +3526,7 @@ antiAlias Sharp शार्प Pointillize पॉइंटिलाइज़ Pointillize… पॉइंटिलाइज़… Points पॉइंट्स - Points per segment प्रति खंड अंक + Points per segment प्रति सेगमेंट पॉइंट्स Points: पॉइंट्स: Points: clicks add free points पॉइंट्स: क्लिक से अलग-अलग पॉइंट जुड़ते हैं Polar Grid ध्रुवीय ग्रिड @@ -3858,7 +3858,7 @@ antiAlias Sharp शार्प Remove Line Breaks लाइन ब्रेक हटाएँ Remove Paragraph Breaks पैराग्राफ ब्रेक निकालें Remove Plug-in प्लग-इन निकालें - Remove Points, Keep Shape अंक निकालें, आकार रखें + Remove Points, Keep Shape पॉइंट्स हटाएँ, शेप रखें Remove Redundant Points गैरज़रूरी पॉइंट हटाएँ Remove Selected Assets सिलेक्टेड परिसंपत्तियों को हटा दें Remove Selected Entry सिलेक्टेड प्रविष्टि निकालें @@ -3963,7 +3963,7 @@ antiAlias Sharp शार्प Edit Arrowheads… एरोहेड्स संपादित करें… Reload Arrowheads एरोहेड्स फिर से लोड करें Reset Rotate View व्यू घुमाएँ रीसेट करें - Reset Ruler Origin शासकीय उत्पत्ति रीसेट करें + Reset Ruler Origin रूलर ओरिजिन रीसेट करें Reset Symbol Instance सिंबल इंस्टेंस रीसेट करें Reset Text Transform टेक्स्ट ट्रांसफॉर्मर को रीसेट करें Reset Text Transform and Scale टेक्स्ट ट्रांसफॉर्म और स्केल को रीसेट करें @@ -4037,7 +4037,7 @@ antiAlias Sharp शार्प RGB: RGB: Ridges per segment: प्रति खंड रिज: Right दाएँ - Right Complement सही पूरक + Right Complement राइट कम्प्लीमेंट Right Diagonal दायाँ विकर्ण Right Grid: राइट ग्रिड: Right in Front फ्रंट में राइट @@ -4096,14 +4096,14 @@ antiAlias Sharp शार्प Ruby रूबी Ruby… रूबी… Rule: नियम: - Ruler Origin शासकीय उत्पत्ति + Ruler Origin रूलर ओरिजिन Rulers रूलर्स Rulers & Grids रूलर्स और ग्रिड Run Length रन लंबाई Run Plug-in रन प्लग-इन Runs code the checker can't read रन कोड चेकर को पढ़ा नहीं जा सकता Russian रूसी - Same समीर + Same समान Same As Source स्रोत के समान Same file एक ही फ़ाइल Same item as a later row बाद में पंक्ति के रूप में समान आइटम @@ -4246,8 +4246,8 @@ antiAlias Sharp शार्प Saved Views सेव किया गया दृश्य Saves the current bars, toolbar and panel layout. वर्तमान बार, टूलबार और पैनल लेआउट को सेव करता है। Saving सेव किया जा रहा है - Saving {} बचत {} - Saving Poster.vectorcraft बचत Poster.vectorcraft + Saving {} {} सेव किया जा रहा है + Saving Poster.vectorcraft Poster.vectorcraft सेव किया जा रहा है Saving recovery data for {} {} के लिए रिकवरी डेटा सेव करना Scale आकार बदलें Scale Artwork with Artboard आर्टबोर्ड के साथ स्केल आर्टवर्क @@ -4311,7 +4311,7 @@ antiAlias Sharp शार्प Select a character with the Type tool to see its alternates. अल्टरनेट ग्लिफ़ देखने के लिए टाइप टूल से कोई कैरेक्टर सिलेक्ट करें। Select a parametric shape to edit it. With none selected, these set the next shape. एडिट करने के लिए पैरामीट्रिक शेप सिलेक्ट करें। कोई शेप सिलेक्ट न होने पर ये सेटिंग्स अगली शेप पर लागू होंगी। Select a text object एक टेक्स्ट ऑब्जेक्ट चुनें - Select a text object to edit its character attributes. अपने चरित्र विशेषताओं को संपादित करने के लिए एक टेक्स्ट ऑब्जेक्ट चुनें। + Select a text object to edit its character attributes. कैरेक्टर एट्रिब्यूट्स संपादित करने के लिए एक टेक्स्ट ऑब्जेक्ट चुनें। Select a text object to edit its paragraph attributes. अपनी पैराग्राफ विशेषताओं को संपादित करने के लिए एक टेक्स्ट ऑब्जेक्ट चुनें। Select a text object to set its tab stops. अपने टैब स्टॉप सेट करने के लिए एक टेक्स्ट ऑब्जेक्ट चुनें। Select All सभी सिलेक्ट करें @@ -4340,7 +4340,7 @@ antiAlias Sharp शार्प Select by Link Status… लिंक स्थिति द्वारा सिलेक्ट करें… Select Data Set डेटा सेट सिलेक्ट करें Select Embedded एम्बेडेड सिलेक्ट करें - Select Fills भरता सिलेक्ट करें + Select Fills फ़िल्स सिलेक्ट करें Select Freeform Point फ़्रीफ़ॉर्म पॉइंट सिलेक्ट करें Select Gradient Stop ग्रेडिएंट स्टॉप चुनें Select Guides गाइड्स सिलेक्ट करें @@ -4587,7 +4587,7 @@ antiAlias Sharp शार्प Show Tool Tips टूल युक्तियाँ दिखाएँ Show Toolbar शो टूलबार Show Transparency Grid पारदर्शिता ग्रिड दिखाएँ - Show Video Rulers शो वीडियो शासक + Show Video Rulers वीडियो रूलर्स दिखाएँ Show Video Safe Areas वीडियो सुरक्षित क्षेत्र दिखाएं Show Vivid/Muted चमकीले/मंद दिखाएँ Show Warm/Cool शो वार्म / कूल @@ -5032,7 +5032,7 @@ antiAlias Sharp शार्प The Print Tiling tool placed the pages. प्रिंट टाइलिंग टूल ने पृष्ठों को रखा। The samples show this brush on a blue stroke. नमूने इस ब्रश को ब्लू स्ट्रोक पर दिखाते हैं। The search stopped at its limit: search a smaller folder. सर्च अपनी लिमिट तक पहुँच गई: छोटे फ़ोल्डर में सर्च करें। - The selected character's font is not available. सिलेक्टेड चरित्र का फ़ॉन्ट उपलब्ध नहीं है। + The selected character's font is not available. सिलेक्टेड कैरेक्टर का फ़ॉन्ट उपलब्ध नहीं है। The selected objects have no CSS of their own (see below). सिलेक्टेड ऑब्जेक्ट का अपना CSS नहीं है (नीचे देखें)। The system's settings of this printer इस प्रिंटर की प्रणाली की सेटिंग These fonts aren't available. Their text shows in another font. ये फ़ॉन्ट उपलब्ध नहीं हैं। इनका टेक्स्ट दूसरे फ़ॉन्ट में दिखता है। @@ -5066,7 +5066,7 @@ antiAlias Sharp शार्प Tile Edge Color टाइल एज रंग Tile Edge Color… टाइल एज रंग… Tile Full Pages टाइल पूर्ण पृष्ठ - Tile Imageable Areas टाइल कल्पनाशील क्षेत्र + Tile Imageable Areas इमेजेबल क्षेत्र टाइल करें Tile Range: टाइल रेंज: Tile Size टाइल साइज़ Tile Type: टाइल प्रकार: @@ -5175,9 +5175,9 @@ antiAlias Sharp शार्प Transverse (the page a quarter turn on the paper) ट्रांसवर्स (पेपर पर एक चौथाई मोड़ पृष्ठ) Trap ट्रैप Trap… ट्रैप… - Traps with Process Color प्रक्रिया रंग के साथ जाल - Triad त्रिदाद - Triad 2 त्रिद 2 + Traps with Process Color प्रोसेस रंग के साथ ट्रैप + Triad त्रिक + Triad 2 त्रिक 2 Triad 3 त्रिक 3 Triangle त्रिभुज Triangle (open) त्रिभुज (ओपन) @@ -5185,7 +5185,7 @@ antiAlias Sharp शार्प Trim ट्रिम करें Trim covered geometry on Expand Appearance. Live preview keeps the full surface. Transparent paints and surfaces exceeding visibility limits retain all faces. अपीयरेंस एक्सपैंड करने पर ढकी हुई ज्यामिति ट्रिम करें। लाइव प्रीव्यू पूरी सतह रखता है। ट्रांसपेरेंट पेंट और विज़िबिलिटी लिमिट से बड़ी सतहों के सभी फेस बने रहते हैं। Trim mark weight: ट्रिम मार्क वजन: - Trim marks ट्रिम अंक + Trim marks ट्रिम मार्क्स Trim View ट्रिम देखें True Colors असली रंग True colour needs version 2004 or later: the nearest of 256 colours is written. ट्रू कलर के लिए संस्करण 2004 या बाद का चाहिए: अभी 256 रंगों में सबसे निकट वाला रंग लिखा जाता है। @@ -5412,7 +5412,7 @@ antiAlias Sharp शार्प Video 1920×1080 1920 × 1080 वीडियो Video 3840×2160 वीडियो 3840 × 2160 Video Banner 2560×1440 वीडियो बैनर 2560 × 1440 - Video Ruler Pixel Aspect Ratio: वीडियो शासक पिक्सेल दृष्टि अनुपात: + Video Ruler Pixel Aspect Ratio: वीडियो रूलर पिक्सेल आस्पेक्ट रेशियो: Fade Region Outside Artboard आर्टबोर्ड के बाहर का क्षेत्र धुंधला करें Update While Dragging खींचते समय अपडेट करें Video Thumbnail 1280×720 वीडियो थंबनेल 1280 × 720 @@ -5437,7 +5437,7 @@ antiAlias Sharp शार्प Warp Options वार्प ऑप्शन्स Warp Tool वार्प टूल Watch 184×224 घड़ी 184 × 224 - Watch 198×242 देखें 198 × 242 + Watch 198×242 घड़ी 198 × 242 Water Paper वॉटर पेपर Water Paper… वॉटर पेपर… Watercolor वॉटरकलर @@ -5930,7 +5930,7 @@ antiAlias Sharp शार्प @msg `{name}` is no recovery entry name `{name}` कोई वसूली प्रविष्टि नाम नहीं है @msg `{name}` isn't a colour swatch `{name}` रंग स्वॉच नहीं है @msg `{name}` takes a paint of its own kind (colour, gradient or pattern) `{name}` अपने ही प्रकार का पेंट लेता है (रंग, ग्रेडिएंट या पैटर्न) -@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: न्यूनतम इच्छा से अधिक नहीं होना चाहिए, न ही इच्छा अधिकतम +@msg `{name}`: Minimum must not exceed Desired, nor Desired Maximum `{name}`: न्यूनतम, वांछित से अधिक नहीं होना चाहिए और वांछित, अधिकतम से अधिक नहीं होना चाहिए @msg `{other}` doesn't trace an image `{other}` एक इमेज का पता नहीं लगा @msg `{path}` must be a bool or an object of bools `{path}` एक bool होना चाहिए या एक ऑब्जेक्ट होना चाहिए। @msg `{s}` is not a colour (#rrggbb or a preset name) `{s}` एक रंग नहीं है (#rrggbb या एक पूर्व निर्धारित नाम) @@ -6285,7 +6285,7 @@ antiAlias Sharp शार्प @msg a wraparound group is inside a compound path एक रैपराउंड समूह एक मिश्रित पाथ के अंदर है @msg action is required action आवश्यक है @msg add a format to export निर्यात करने के लिए एक फ़ॉर्मैट जोड़ें -@msg Add Points at Crossings: a path went missing क्रॉसिंग्स में अंक जोड़ें: एक पाथ गायब हो गया +@msg Add Points at Crossings: a path went missing क्रॉसिंग पर पॉइंट जोड़ें: एक पाथ गायब हो गया @msg aiVersion {v}: "pdf" (PDF-compatible, the default) or "7" (legacy .ai, version 7) aiVersion {v}: "pdf" (PDF-संगत, डिफ़ॉल्ट) या "7" (पुरानी .ai, संस्करण 7) @msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 विरासत .ai फ़ाइलों को लिखते हैं, .ait टेम्पलेट नहीं @msg All colors are within the CMYK gamut सभी रंग CMYK गामट के भीतर हैं @@ -6473,7 +6473,7 @@ antiAlias Sharp शार्प @msg choose at least one status कम से कम एक स्थिति चुनें @msg Choose original artwork, not a dimension's generated paths मूल आर्टवर्क चुनें, एक आयाम उत्पन्न पाथ नहीं @msg choose the font files to add जोड़ने के लिए फ़ॉन्ट फ़ाइलों को चुनें -@msg Choose two different points दो अलग-अलग अंक चुनें +@msg Choose two different points दो अलग-अलग पॉइंट्स चुनें @msg Choose two non-parallel straight segments दो गैर-parallel सीधे खंड चुनें @msg Choose two nonzero angle arms दो nonzero कोण हथियार चुनें @msg Click in type with a Type tool to split it इसे विभाजित करने के लिए टाइप टूल के साथ टाइप करें @@ -6665,7 +6665,7 @@ antiAlias Sharp शार्प @msg data must be an object of key: value, not {v} data: डेटा कुंजी का एक ऑब्जेक्ट होना चाहिए: मान, नहीं {v} @msg Data Recovery can't keep copies in {path}: {e} डेटा रिकवरी {path} में प्रतियां नहीं रख सकती: {e} @msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) डेटा रिकवरी की प्रतिलिपियाँ रखने के लिए कहीं नहीं है: निर्धारित प्राथमिकता → फ़ाइल हैंडलिंग → डेटा रिकवरी → फ़ोल्डर (recoveryFolder) -@msg data set `{name}` holds a control character, which a variable library can't hold डेटा सेट `{name}` में एक नियंत्रण चरित्र होता है, जो एक परिवर्तनीय लाइब्रेरी पकड़ नहीं सकता है +@msg data set `{name}` holds a control character, which a variable library can't hold डेटा सेट `{name}` में एक कंट्रोल कैरेक्टर है, जिसे वेरिएबल लाइब्रेरी में नहीं रखा जा सकता @msg data set `{name}` holds a value for `{var}`, which the library doesn't declare डेटा सेट `{name}` `{var}` के लिए एक मान रखता है, जिसे लाइब्रेरी घोषित नहीं करती है @msg data set `{name}` holds two values for `{var}` डेटा सेट `{name}` में `{var}` के लिए दो मान हैं। @msg data set `{name}` is declared twice डेटा सेट `{name}` को दो बार घोषित किया गया है @@ -6683,7 +6683,7 @@ antiAlias Sharp शार्प @msg Dimension mode does not match its source आयाम मोड अपने स्रोत से मेल नहीं खाता है @msg Dimension point is outside the canvas आयाम बिंदु कैनवास के बाहर है @msg Dimension size is outside its supported range आयाम आकार अपनी समर्थित सीमा से बाहर है -@msg direct-select anchor points of a path एक पाथ के प्रत्यक्ष सिलेक्शन एंकर अंक +@msg direct-select anchor points of a path किसी पाथ के एंकर पॉइंट्स डायरेक्ट-सिलेक्ट करें @msg direct-select anchor points to cut at (not the end points of open paths) डायरेक्ट-सिलेक्शन एंकर पॉइंट्स को कट करने के लिए ( ओपन पाथ के अंतिम बिंदु नहीं) @msg direct-select the anchor points to remove हटाने के लिए एंकर पॉइंट्स सिलेक्ट करें @msg distance must be > 0 distance: दूरी होना चाहिए > 0 @@ -6738,7 +6738,7 @@ antiAlias Sharp शार्प @msg exit isolation mode first पहले अलगाव मोड से बाहर निकलें @msg Expand Appearance: the selection has a basic appearance उपस्थिति का विस्तार: सिलेक्शन में एक बुनियादी उपस्थिति है @msg Expand: no brush strokes selected विस्तार: सिलेक्टेड कोई ब्रश स्ट्रोक नहीं -@msg Expand: no gradient fills विस्तार: कोई ग्रेडिएंट भरता नहीं +@msg Expand: no gradient fills एक्सपैंड: कोई ग्रेडिएंट फ़िल नहीं @msg Expand: nothing to expand विस्तार: विस्तार करने के लिए कुछ नहीं @msg expanded SVG styles exceed the import size limit विस्तारित SVG स्टाइल्स आयात आकार सीमा से अधिक है @msg expected {"dataBase64"} अपेक्षित: {"dataBase64"} @@ -6871,7 +6871,7 @@ antiAlias Sharp शार्प @msg Global Edit is off ग्लोबल एडिट बंद है @msg Global Edit works on paths, compound paths, symbol instances and groups of them ग्लोबल एडिट पाथ, मिश्रित पाथ, सिंबल उदाहरणों और उनके समूहों पर काम करता है @msg global must be true or false global को true या false होना चाहिए -@msg glyph {_1} is not drawn for {ch} with the character's style (such as All Caps, Small Caps or a numeral system) Glyph {_1} चरित्र की स्टाइल (जैसे सभी कैप्स, छोटे कैप्स या एक संख्यात्मक प्रणाली) के साथ {ch} के लिए तैयार नहीं है। +@msg glyph {_1} is not drawn for {ch} with the character's style (such as All Caps, Small Caps or a numeral system) Glyph {_1} कैरेक्टर की स्टाइल (जैसे सभी कैप्स, छोटे कैप्स या एक संख्यात्मक प्रणाली) के साथ {ch} के लिए तैयार नहीं है। @msg glyph {g} is not an alternate of {ch} in {_1} {_2} Glyph {g} {_1} {_2} में {ch} का एक वैकल्पिक नहीं है। @msg gradient “{name}” isn't defined in the file: a plain colour stands in for it ग्रेडिएंट "{name}" को फ़ाइल में परिभाषित नहीं किया गया है: इसके लिए एक सादे रंग खड़ा है @msg gradient must be "objects" or "mesh" gradient: ग्रेडिएंट "objects" या "mesh" होना चाहिए @@ -7127,8 +7127,8 @@ antiAlias Sharp शार्प @msg missing point लापता बिंदु @msg missing point [x,y] लापता बिंदु [x,y] @msg missing point `{key}` ([x, y]) लापता बिंदु `{key}` ([x, y]) -@msg missing points लापता अंक -@msg missing points [[x,y]…] लापता अंक [[x,y]...] +@msg missing points पॉइंट्स नहीं दिए गए +@msg missing points [[x,y]…] पॉइंट्स नहीं दिए गए [[x,y]…] @msg missing segment लापता खंड @msg missing stops लापता ठहराव @msg missing subpaths लापता subpaths @@ -7165,7 +7165,7 @@ antiAlias Sharp शार्प @msg need at least one anchor कम से कम एक एंकर की जरूरत है @msg need at least one point कम से कम एक बिंदु की जरूरत है @msg need at least two points कम से कम दो बिंदुओं की आवश्यकता -@msg needs points जरूरत अंक +@msg needs points पॉइंट्स चाहिए @msg New Window isn't available yet: a document opens in one window नई विंडो अभी तक उपलब्ध नहीं है: एक डॉक्यूमेंट एक विंडो में खुलता है @msg nineSlice must be true or false nineSlice को true या false होना चाहिए @msg nineSliceGuides must be [left, top, right, bottom], each -16..16, with left + right < 1 and top + bottom < 1 nineSliceGuides को [left, top, right, bottom] होना चाहिए, हर मान -16..16, और left + right < 1 तथा top + bottom < 1 @@ -7174,7 +7174,7 @@ antiAlias Sharp शार्प @msg no active data set कोई सक्रिय डेटा सेट नहीं @msg no active document कोई सक्रिय डॉक्यूमेंट @msg no active perspective plane कोई सक्रिय पर्सपेक्टिव विमान नहीं -@msg no anchor points selected कोई एंकर अंक नहीं चुना गया +@msg no anchor points selected कोई एंकर पॉइंट सिलेक्ट नहीं है @msg no app to open files here यहां फ़ाइलों को ओपन करने के लिए कोई ऐप नहीं है @msg no appearance item {index} कोई उपस्थिति आइटम {index} @msg no artboard कोई आर्टबोर्ड नहीं @@ -7199,7 +7199,7 @@ antiAlias Sharp शार्प @msg no brush selected कोई ब्रश नहीं चुना गया @msg no catalog कोई सूची नहीं @msg no changes since the last save आखिरी सेव के बाद से कोई बदलाव नहीं -@msg no character at byte {start} byte {start} पर कोई चरित्र नहीं +@msg no character at byte {start} byte {start} पर कोई कैरेक्टर नहीं @msg no character style `{name}` कोई कैरेक्टर स्टाइल `{name}` @msg no clock to keep a heartbeat by हार्टबीट का समय रखने के लिए कोई घड़ी नहीं @msg no color group `{name}` in the document (see swatch.list) डॉक्यूमेंट में कोई रंग समूह `{name}` (देखें swatch.list) @@ -7622,12 +7622,12 @@ antiAlias Sharp शार्प @msg plug-in trapped: {0} प्लग-इन में ट्रैप हुआ: {0} @msg Plug-ins can't be loaded from {path}: {e} प्लग-इन {path} से लोड नहीं किया जा सकता: {e} @msg point is outside the mesh बिंदु मेश के बाहर है -@msg points must be [t, left, right] with non-negative widths points: गैर-नकारात्मक चौड़ाई के साथ अंक [t, left, right] होना चाहिए -@msg points must be a non-empty [[x,y,pressure?]…] list points: अंक एक गैर-खाली होना चाहिए [[x,y, दबाव?]...] सूची -@msg points must be a non-empty list of finite [x,y] points: अंक परिमित की एक गैर-खाली सूची होना चाहिए [x,y] -@msg points must be an array or null points: अंक एक सारणी या null होना चाहिए -@msg points must be finite points: अंक परिमित होना चाहिए -@msg points must be finite [x,y] pairs points: अंक परिमित होना चाहिए [x,y] जोड़े +@msg points must be [t, left, right] with non-negative widths points: गैर-नकारात्मक चौड़ाई के साथ पॉइंट्स [t, left, right] होने चाहिए +@msg points must be a non-empty [[x,y,pressure?]…] list points: पॉइंट्स एक गैर-खाली होना चाहिए [[x,y, दबाव?]...] सूची +@msg points must be a non-empty list of finite [x,y] points: पॉइंट्स परिमित की एक गैर-खाली सूची होना चाहिए [x,y] +@msg points must be an array or null points: पॉइंट्स एक सारणी या null होना चाहिए +@msg points must be finite points: पॉइंट्स परिमित होने चाहिए +@msg points must be finite [x,y] pairs points: पॉइंट्स परिमित होने चाहिए [x,y] जोड़े @msg points must contain 1–4096 coordinates points में 1–4096 निर्देशांक होने चाहिए @msg position must be normal, superscript or subscript position: स्थिति सामान्य, सुपरस्क्रिप्ट या सबस्क्रिप्ट होना चाहिए @msg position must be topLeft, topRight, bottomLeft or bottomRight position को topLeft, topRight, bottomLeft या bottomRight होना चाहिए @@ -7701,7 +7701,7 @@ antiAlias Sharp शार्प @msg Saved to User Defined: {_1} उपयोगकर्ता परिभाषित करने के लिए सेव किया गया: {_1} @msg savedPreset: {e} savedPreset: {e} @msg Saving सेव किया जा रहा है -@msg Saving {_1} बचत {_1} +@msg Saving {_1} {_1} सेव किया जा रहा है @msg Saving recovery data for {_1} {_1} के लिए रिकवरी डेटा सेव करना @msg scale `{s}`: a factor such as 2x, a width (100w), a height (100h) or a resolution (72ppi) पैमाने `{s}`: एक कारक जैसे 2x, चौड़ाई (100w), ऊंचाई (100h) या एक रिज़ॉल्यूशन (72ppi) @msg scale must be a number above 0, at most 64 scale: पैमाने 0 से अधिक होना चाहिए, अधिकांश 64 में @@ -7792,7 +7792,7 @@ antiAlias Sharp शार्प @msg Select only dimensions केवल आयाम सिलेक्ट करें @msg select open paths to close बंद करने के लिए खुले रास्ते सिलेक्ट करें @msg select paths पाथ चुनें -@msg select paths or anchor points पाथ या एंकर अंक चुनें +@msg select paths or anchor points पाथ या एंकर पॉइंट्स चुनें @msg select paths or compound paths पाथ या यौगिक पाथ सिलेक्ट करें @msg select paths to join शामिल होने के लिए पाथ सिलेक्ट करें @msg select paths with dashed strokes to expand विस्तृत करने के लिए डैश स्ट्रोक के साथ पाथ सिलेक्ट करें @@ -7800,7 +7800,7 @@ antiAlias Sharp शार्प @msg select plain rectangles, ellipses or regular polygons to convert बदलने के लिए सादे आयत, अंडाकार या नियमित बहुभुजों सिलेक्ट करें @msg Select point type पॉइंट टाइप सिलेक्ट करें @msg select rows or objects to collect इकट्ठा करने के लिए पंक्तियों या ऑब्जेक्ट्स सिलेक्ट करें -@msg select segments, or paths, to add points to खंडों, या पाथ का सिलेक्ट करने के लिए, अंक जोड़ने के लिए +@msg select segments, or paths, to add points to पॉइंट्स जोड़ने के लिए सेगमेंट या पाथ सिलेक्ट करें @msg select some type first पहले कुछ टाइप सिलेक्ट करें @msg select something to export निर्यात करने के लिए कुछ का सिलेक्शन @msg select something to export (or turn off selectedOnly) एक्सपोर्ट करने के लिए कुछ चुनें (या selectedOnly बंद करें) @@ -7984,7 +7984,7 @@ antiAlias Sharp शार्प @msg the artboards don't fit on the canvas: fewer artboards, less spacing or a smaller size आर्टबोर्ड कैनवास पर फिट नहीं हैं: कम आर्टबोर्ड, कम रिक्ति या छोटे आकार @msg the background worker stopped पृष्ठभूमि कार्यकर्ता बंद कर दिया @msg the blend has no spine मिश्रण में कोई रीढ़ नहीं है -@msg the character's size can't be measured चरित्र का आकार मापा नहीं जा सकता है +@msg the character's size can't be measured कैरेक्टर का आकार मापा नहीं जा सकता है @msg the CMYK image couldn't be written CMYK इमेज को नहीं लिखा जा सकता @msg the Color Picker is not open रंग पिकर खुला नहीं है @msg the compound shape is too complex to expand मिश्रित आकार का विस्तार करने के लिए बहुत जटिल है @@ -8032,12 +8032,12 @@ antiAlias Sharp शार्प @msg the file was updated or encrypted already फ़ाइल को पहले से ही अद्यतन या एन्क्रिप्ट किया गया था @msg the file's layers weren't read ({_1}): it comes in as its page, in one layer फ़ाइल की लेयरें नहीं पढ़ी गईं ({_1}): यह अपने पृष्ठ के रूप में आता है, एक लेयर में @msg the file's layers weren't read from its editing data ({_1}): they come from its PDF part फ़ाइल की लेयर्स को इसके संपादन डेटा ({_1}) से नहीं पढ़ा गया था: वे अपने PDF भाग से आते हैं -@msg the file's preview header points outside the file फ़ाइल के प्रीव्यू शीर्षलेख फ़ाइल के बाहर अंक +@msg the file's preview header points outside the file फ़ाइल का प्रीव्यू हेडर फ़ाइल के बाहर की जगह बताता है @msg the file's variable bindings weren't all read (bindings skipped: {_1}): those objects aren't bound to their variables फ़ाइल के परिवर्तनीय बंधन सभी नहीं पढ़े गए थे (बाइंडिंग्स स्किप: {_1}): वे ऑब्जेक्ट अपने चर के लिए बाध्य नहीं हैं @msg the file's variable library couldn't be read: the Variables panel doesn't list it फ़ाइल के परिवर्तनीय लाइब्रेरी को पढ़ा नहीं जा सकता: चर पैनल इसे सूचीबद्ध नहीं करता है @msg the file's variable library was partly read (entries skipped: {_1}): the Variables panel lists the rest फ़ाइल की परिवर्तनीय लाइब्रेरी आंशिक रूप से पढ़ी गई थी (प्रवेशियों को छोड़ दिया: {_1}): वेरिएबल्स पैनल बाकी हिस्सों को सूचीबद्ध करता है @msg the files come to more than 1 GB: add fewer at a time फ़ाइलों को 1 GB से अधिक करने के लिए आते हैं: एक समय में कम जोड़ें -@msg the first character of a line has no character before it to kern: it moves only up and down (dy) एक पंक्ति के पहले चरित्र में बर्न से पहले कोई चरित्र नहीं है: यह केवल ऊपर और नीचे चला जाता है (डी) +@msg the first character of a line has no character before it to kern: it moves only up and down (dy) किसी लाइन के पहले कैरेक्टर से पहले कर्न करने के लिए कोई कैरेक्टर नहीं है: यह केवल ऊपर और नीचे जाता है (dy) @msg the font {_1} is not available फ़ॉन्ट {_1} उपलब्ध नहीं है @msg the format has no file extension फ़ॉर्मैट में कोई फ़ाइल एक्सटेंशन नहीं है @msg the graphic can't be read: {e} ग्राफिक पढ़ा नहीं जा सकता: {e} @@ -8224,7 +8224,7 @@ antiAlias Sharp शार्प @msg the variable library's document type declaration holds something other than entities of plain text वेरिएबल लाइब्रेरी के डॉक्यूमेंट प्रकार की घोषणा सादे टेक्स्ट की संस्थाओं के अलावा कुछ अन्य रखती है @msg the variable library's entities expand to more than {MAX_LIBRARY_BYTES} bytes वेरिएबल लाइब्रेरी की संस्थाएं {MAX_LIBRARY_BYTES} बाइट्स से अधिक विस्तार करती हैं @msg the window has no dock विंडो में कोई डॉक नहीं है -@msg the window's {what} ({points} points × {scale} DPI) cannot size a screenshot विंडो का {what} ({points} अंक × {scale} डीपीआई) एक स्क्रीनशॉट का आकार नहीं दे सकता +@msg the window's {what} ({points} points × {scale} DPI) cannot size a screenshot विंडो का {what} ({points} पॉइंट × {scale} DPI) एक स्क्रीनशॉट का आकार नहीं दे सकता @msg the WMF header is damaged WMF हेडर क्षतिग्रस्त है @msg the Word document has more than {_1} MB of formatting properties, too many to place वर्ड डॉक्यूमेंट में स्वरूपण प्रॉपर्टीज़ के {_1} MB से अधिक है, कई जगहों पर @msg the Word document has more than {MAX_PAGES} pages of properties, too many to place Word डॉक्यूमेंट में गुणों के {MAX_PAGES} से अधिक पेज हैं, रखने के लिए बहुत अधिक @@ -8323,8 +8323,8 @@ antiAlias Sharp शार्प @msg unknown brush type `{o}` अज्ञात ब्रश प्रकार `{o}` @msg unknown category `{c}` अज्ञात श्रेणी `{c}` @msg unknown category `{c}` ({_1}) अज्ञात श्रेणी `{c}` ({_1}) -@msg unknown character `{c}` अज्ञात चरित्र `{c}` -@msg unknown character style number field अज्ञात चरित्र स्टाइल संख्या क्षेत्र +@msg unknown character `{c}` अज्ञात कैरेक्टर `{c}` +@msg unknown character style number field अज्ञात कैरेक्टर स्टाइल संख्या फ़ील्ड @msg unknown CMYK profile `{name}` अज्ञात CMYK प्रोफ़ाइल `{name}` @msg unknown command `{0}` अज्ञात आदेश `{0}` @msg unknown command `{0}`; did you mean `{1}`? अज्ञात आदेश `{0}`; क्या आपको `{1}` का मतलब है? diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index d7f2c8a2ef..2aaaf8f445 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -35,6 +35,9 @@ fn hindi_resolves_locales_and_uses_zero_one_plurals() { /// Every Hindi row uses the terms `docs/localization-hi.md` sets for what its English names: /// सेव for saving, स्वॉच for a swatch, क्रॉप for cropping, रिज़ॉल्यूशन for a resolution and पाथ for /// a path, never पाठ (a reading), and a number of points is a number (संख्या) in points (पॉइंट). +/// Rows also never use a word's unrelated sense: a ruler is not शासक (a sovereign), a text character +/// is not चरित्र (a personality), a vector point or a printer's mark is not अंक (a digit), fills are +/// not भरता (the verb), Desired is not देसी (local), Even is not शाम (evening), and so on. #[test] fn hindi_rows_use_the_glossary_term_for_what_their_english_names() { let hi = Lang::from_code("hi").expect("hi registered"); @@ -43,15 +46,35 @@ fn hindi_rows_use_the_glossary_term_for_what_their_english_names() { for (_, src, translation) in &entries { let english = src.to_lowercase(); let names = |words: &[&str]| english.split(|c: char| !c.is_ascii_alphabetic()).any(|w| words.contains(&w)); - let banned: [(bool, &[&str]); 6] = [ - (names(&["save", "saves", "saved", "saving"]), &["बचा", "सहेज"]), + let banned: &[(bool, &[&str])] = &[ + (names(&["save", "saves", "saved", "saving"]), &["बचा", "बचत", "सहेज"]), (names(&["swatch", "swatches"]), &["घड़ी"]), (names(&["crop"]), &["फसल"]), (names(&["resolution", "resolutions"]), &["संकल्प"]), (names(&["path", "paths"]), &["पथ"]), (true, &["पाठ", "कई अंक"]), + (names(&["ruler", "rulers"]), &["शासक"]), + (names(&["character", "characters"]), &["चरित्र"]), + (names(&["point", "points", "mark", "marks"]), &["अंक"]), + (names(&["fill", "fills"]), &["भरता"]), + (names(&["desired"]), &["देसी", "इच्छा"]), + (names(&["even"]), &["शाम"]), + (names(&["force", "forced"]), &["सेना"]), + (names(&["same"]), &["समीर"]), + (names(&["thumbnail", "thumbnails"]), &["हिंदुस्तान"]), + (names(&["contrast"]), &["न्यायालय"]), + (names(&["function"]), &["समारोह"]), + (names(&["kern"]), &["बर्न"]), + (names(&["imageable"]), &["कल्पनाशील"]), + (names(&["constrain"]), &["कंस्ट्रक्शन"]), + (names(&["complement"]), &["संगम"]), + (names(&["concave"]), &["अवतरण"]), + (names(&["triad"]), &["त्रिद"]), + (names(&["trapped", "traps"]), &["निशानेबाज़", "जाल"]), + (names(&["alternate", "alternates"]), &["अल्टरनेटर"]), + (names(&["highlight"]), &["उच्च प्रकाश"]), ]; - for (applies, words) in banned { + for &(applies, words) in banned { if let Some(word) = words.iter().find(|w| applies && translation.contains(**w)) { wrong.push(format!("{word} in {src:?} -> {translation:?}")); } @@ -83,6 +106,10 @@ fn hindi_rows_keep_the_meaning_of_their_english() { assert!(all.contains("3 आर्टबोर्ड में से 1") && all.contains("सभी आर्टबोर्ड रखने के लिए"), "{all}"); let left_out = message(hi, "the file was read up to an error (bad xref): what follows it was left out"); assert!(left_out.contains("उसके बाद का हिस्सा छोड़ दिया गया"), "{left_out}"); + assert_eq!(tr(hi, "Desired"), "वांछित"); + let range = "न्यूनतम, वांछित से अधिक नहीं होना चाहिए और वांछित, अधिकतम से अधिक नहीं होना चाहिए"; + assert_eq!(tr(hi, "Minimum must not exceed Desired, nor Desired Maximum."), format!("{range}।")); + assert_eq!(message(hi, "`wordSpacing`: Minimum must not exceed Desired, nor Desired Maximum"), format!("`wordSpacing`: {range}")); } /// Locale tags name their language by region or script (in either case, with an encoding or diff --git a/docs/localization-hi.md b/docs/localization-hi.md index d8dbcaf145..2766a583f4 100644 --- a/docs/localization-hi.md +++ b/docs/localization-hi.md @@ -32,6 +32,13 @@ every clause such as "all" or "what follows it". Type as a text object is टा in `crates/ui-egui/src/i18n/tests.rs` checks the save, swatch, crop, resolution and path terms and the point unit in every row. +Translate a label by its sense in the interface, not by its first dictionary sense. A ruler is +रूलर, never शासक (a sovereign); a text character is कैरेक्टर, never चरित्र (a personality); a +vector point is पॉइंट and a printer's mark is मार्क, never अंक (a digit); fills are फ़िल्स, never +भरता (the verb). In a minimum, desired and maximum range, Desired is वांछित, never देसी (local), +and a range message keeps both comparisons: minimum ≤ desired ≤ maximum. The same test rejects +these senses, and others found in the catalog, in every row whose English names the word. + ## Terminology | English | Hindi | @@ -46,7 +53,10 @@ and the point unit in every row. | Artwork | आर्टवर्क | | Path / Anchor point / Handle | पाथ / एंकर पॉइंट / हैंडल | | File path on disk | फ़ाइल पाथ | -| Fill / Stroke | फ़िल / स्ट्रोक | +| Fill / Fills / Stroke | फ़िल / फ़िल्स / स्ट्रोक | +| Point (vector) / Printer's marks | पॉइंट / मार्क्स | +| Ruler / Ruler origin | रूलर / रूलर ओरिजिन | +| Minimum / Desired / Maximum | न्यूनतम / वांछित / अधिकतम | | Gradient / Mesh / Blend | ग्रेडिएंट / मेश / ब्लेंड | | Pattern / Swatch | पैटर्न / स्वॉच | | Type (text object) / Crop / Resolution | टाइप / क्रॉप / रिज़ॉल्यूशन | @@ -72,7 +82,10 @@ percentage of the application's entire interface. On 2026-11-13 the catalog has 8,732 rows, including 3,003 `@msg`, 47 `@msgplural` and 41 `@plural` rows. A wording pass on that date corrected 193 rows outside the plug-in messages for meaning, dropped clauses, English left in place and the save, swatch, crop, -resolution, path and type terms. It is not a native proofread. +resolution, path and type terms. A second pass on that date corrected 85 short labels and +messages that used a word's unrelated sense, such as देसी (local) for Desired, शासक (a +sovereign) for a ruler and उच्च न्यायालय (a high court) for High Contrast. It is not a native +proofread. The comparison covers release `v0.21.1` (`f6aa4309`) and current `main` (`3c7d9e1f`). Their non-English catalogs have no missing Hindi keys except the names deliberately kept in English. diff --git a/docs/localization-parity.md b/docs/localization-parity.md index db3d26f7ce..4fd88f73dc 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -29,7 +29,7 @@ Chinese by `imachus`). Only Georgian is recorded as reviewed by a native speaker | English | `en` | source, 100% | all | Latin | — | full | — | | Simplified Chinese (Mandarin) | `zh-hans` | 5,102 rows, 791 of them `@msg` (counted 2026-10-21): menus, `tl!` literals and messages complete when counted | all | CJK UI font from craft-fonts (BIZ UDPGothic) when embedded, else a system font; IME with marked text at the caret; vertical type partial ([type-parity.md](type-parity.md)) | no | full | — (review) | | Spanish | `es` | 4,009 / 4,020 (99.7%) | all (604 messages) | Latin | no | full | — (review) | -| Hindi | `hi` | 8,732 rows (2026-11-13): 3,003 `@msg`, 47 `@msgplural`, 41 `@plural`; no gaps in the untranslated report | menus, dialogs, tooltips and scanned messages; contributor-approved loanword terminology; agent wording pass | UI and document text shape with HarfRust; installed desktop Devanagari fallback, or a `Deva` craft-fonts face; web font still needed | contributor terminology review; 2026-11-13 wording pass on messages and longer labels, with a glossary-term test; wider proofread welcome | complete catalog, machine-assisted draft | native review, layout and web font | +| Hindi | `hi` | 8,732 rows (2026-11-13): 3,003 `@msg`, 47 `@msgplural`, 41 `@plural`; no gaps in the untranslated report | menus, dialogs, tooltips and scanned messages; contributor-approved loanword terminology; agent wording pass | UI and document text shape with HarfRust; installed desktop Devanagari fallback, or a `Deva` craft-fonts face; web font still needed | contributor terminology review; 2026-11-13 wording pass on messages and longer labels, and a word-sense pass on short labels, with a glossary-term test; wider proofread welcome | complete catalog, machine-assisted draft | native review, layout and web font | | Arabic | `ar` | 0 | none | document text: bidi layout and Paragraph Direction; interface: no right-to-left layout, no Arabic shaping in egui | no | none | 25–40 | | French | `fr` | 4,020 / 4,020 (100%) | all | Latin | no | full | — (review) | | Portuguese | `pt-br` | 6,106 catalog entries (counted 2026-10-31 on `main` at `d26dd933a`): menus, `tl!` literals and messages complete when counted; one/other plurals | all | Latin | contributor is a Brazilian Portuguese speaker; further native review welcome | full | — (review) | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 7044797d5e..87e6844bc3 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -856,6 +856,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Window › Toolbars › Keep Tools Beside the Canvas, a VectorCraft layout option that is off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge; the canvas's left edge then also docks a floating Tools panel, and workspaces keep the setting. Scores are unchanged (`window.toolsBesideCanvas`; `docked_tools_keep_the_window_edge_unless_kept_beside_the_canvas`, `tools_redock_at_the_targets_of_the_chosen_placement`). - Hindi (2026-11-06): Hindi (`hi`): 7,877-row machine-assisted catalog, zero/one singular plurals, desktop font fallback and optional Devanagari craft-fonts fallback; all 55 translation tests pass; native review and a web font remain; scores and estimates unchanged. [Terminology and limitations](localization-hi.md). - Hindi wording (2026-11-13): rows outside the plug-in messages keep their English's meaning, quantities and clauses, and use the catalog's save, swatch, crop, resolution, path and type terms; a test checks those terms and the point unit in every row; native review remains; scores and estimates unchanged. + - Hindi word senses (2026-11-13): 85 labels and messages use the interface sense of their English: Desired is वांछित and the range message keeps both comparisons, rulers are रूलर, text characters कैरेक्टर, vector points पॉइंट, fills फ़िल्स and High Contrast उच्च कंट्रास्ट; the glossary test rejects the unrelated senses in every row; native review remains; scores and estimates unchanged. - Window › Help Bar shows or hides the tool-help strip at the bottom of the window apart from the status bar (`window.helpBar`). Each setting is kept with the UI preferences and in saved workspaces, and Presentation Mode hides both bars. Layouts saved before the setting existed show the Help Bar where they show the status bar (`help_bar_toggle_is_independent_and_saved_in_workspaces`, `help_bar_and_status_bar_render_independently`, `legacy_help_bar_visibility_follows_each_layouts_status_bar`, `a_help_bar_setting_the_file_lacks_is_saved`). - Czech render-site labels: desktop/web file filters, diagnostics, suggested preset names and contributor tooltips/plurals now use catalog lookups; gradients have Czech adjective agreement and printer marks have a separate context (PDF/Print and Summary). Search, Home, toolbar/panel tooltips and Preferences already look up their labels. Every complete catalog has rows for these labels and for the Roman and Japanese printer mark styles. Evidence: `i18n::tests::czech_render_site_follow_up`, `i18n::tests::complete_catalogs_translate_render_site_labels`, `dialogs::tests_modal::printer_mark_labels_are_distinct_from_language_names`; see [localization-parity.md](localization-parity.md). - The History panel, Edit › Undo and Edit › Redo translate the names of the steps that apply or redefine a character or paragraph style and of the step that redefines a graphic style: each such step keeps its template (`Apply {name}`, `Redefine {name}`, `Redefine Graphic Style “{name}”`) and the style's name, every complete catalog has a row for each template, and the panel and the menu show the style's name as the document holds it, except the Normal styles' names, which they show in the interface language (`steps_named_after_a_style_list_the_template_around_the_name`, `undo_and_redo_name_a_style_step_around_the_style_name`). From f9e796cb10c2befc1560c1c794ab54b5803da6cb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 13:01:02 -0800 Subject: [PATCH 02/47] Live Paint: double-click floods across unstroked edges, triple-click paints the same paint With the Live Paint Bucket, a double-click on a face fills it and every face reached across edges that are hidden or draw no stroke; a stroked edge, a hidden face and a Gap Detection gap stop it. On an edge, a double-click paints the edges joined to it end to end with the same stroke paint. A triple-click fills every face of the group with the clicked face's fill, or paints every edge with the clicked edge's stroke. Shift and the Paint Fills and Paint Strokes options choose a face or an edge as for a click; Alt held paints nothing. - livePaint.fill and livePaint.strokeEdge take scope ("one", the default, "connected" or "samePaint") and match, the paint compared, and reply with count. A bad scope or match is an error, and scope with a drag's points is refused. - Each click of a double-click or triple-click paints as it arrives, as its own undo step. For a triple-click, and for a double-click on an edge, the tool sends as match the paint the face or edge had before the first of those clicks, including a first click that makes the Live Paint group from the selected paths. A double-click on a face sends no match. - PointerKind::TripleClick is new: the canvas sends it on egui's triple-click unless a modal dialog is open, as for a double-click, and ui.pointer and pointer_gesture take "tripleclick". Docs: docs/mcp.md, docs/control-protocol.md, docs/target-app-parity.md. --- crates/engine/src/cmd/buildcmds.rs | 4 +- crates/engine/src/cmd/buildcmds/live_paint.rs | 296 +++++++++++++++- crates/engine/src/tests/build.rs | 326 ++++++++++++++++++ crates/engine/src/tooling.rs | 2 +- crates/mcp/src/headless.rs | 3 +- crates/mcp/src/tests.rs | 1 + crates/mcp/src/tests/livepaint.rs | 49 +++ crates/mcp/src/tools/definitions.rs | 2 +- crates/mcp/src/tools/dispatch.rs | 2 +- crates/tools/src/addons/corner_tool.rs | 1 + crates/tools/src/addons/extend_path.rs | 2 +- crates/tools/src/addons/parametric_shape.rs | 2 +- crates/tools/src/addons/slide_anchor.rs | 2 +- crates/tools/src/addons/smart_pen.rs | 1 + crates/tools/src/builder/live_paint.rs | 116 ++++++- crates/tools/src/builder/tests.rs | 72 ++++ crates/tools/src/cropimage.rs | 1 + crates/tools/src/distort/puppet.rs | 2 +- crates/tools/src/distort/width.rs | 1 + crates/tools/src/draw2/curvature.rs | 1 + crates/tools/src/input.rs | 3 + crates/tools/src/pen.rs | 2 +- crates/tools/src/printtiling.rs | 2 +- crates/tools/src/text/tool.rs | 1 + crates/tools/src/touchtype.rs | 2 +- crates/tools/src/xform/gradient.rs | 2 +- crates/tools/src/xform/transform.rs | 1 + crates/ui-egui/src/canvas/input.rs | 23 ++ crates/ui-egui/src/control.rs | 5 +- docs/control-protocol.md | 2 +- docs/mcp.md | 20 +- docs/target-app-parity.md | 1 + 32 files changed, 917 insertions(+), 33 deletions(-) create mode 100644 crates/mcp/src/tests/livepaint.rs diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 94fe55c119..790d54214b 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -117,7 +117,7 @@ pub fn specs() -> Vec { "Live Paint Bucket", [], None, - "{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], points?: [[x,y]…] (a drag polyline starting at point; 1 to 4096 finite canvas points; fills every crossed face of the same group), continuation?: [[[x,y]…]…] (further path chunks of 1 to 4096 finite canvas points each; each starts at the preceding chunk's last point; requires points), color?|swatch?|gradient?|none? (default: current fill; a color in #rrggbbaa or #rgba is refused), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces → {group, face}", + "{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], points?: [[x,y]…] (a drag polyline starting at point; 1 to 4096 finite canvas points; fills every crossed face of the same group), continuation?: [[[x,y]…]…] (further path chunks of 1 to 4096 finite canvas points each; each starts at the preceding chunk's last point; requires points), scope?: \"one\" (default: the face alone) | \"connected\" (a double-click: also each face reached across edges that are hidden or draw no stroke, as a flood from the face; a stroked edge, a hidden face or a Gap Detection gap stops it) | \"samePaint\" (a triple-click: also every face of the group whose fill is match), not with points, match?: paint (as the document stores it, the `fill` of a face's appearance; scope samePaint only; default: the face's fill), color?|swatch?|gradient?|none? (default: current fill; a color in #rrggbbaa or #rgba is refused), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces → {group, face, count (faces filled)}", has_doc, lp_fill ), @@ -126,7 +126,7 @@ pub fn specs() -> Vec { "Live Paint Bucket (Stroke)", [], None, - "{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point → {group, edge}", + "{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), scope?: \"one\" (default: the edge alone) | \"connected\" (a double-click: also each edge joined to it, end to end, through edges whose stroke paint is match) | \"samePaint\" (a triple-click: also every edge of the group whose stroke paint is match), match?: paint (as the document stores it; scope connected or samePaint only; default: the edge's stroke paint), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point, skipping hidden edges → {group, edge, count (edges painted)}", has_doc, lp_stroke_edge ), diff --git a/crates/engine/src/cmd/buildcmds/live_paint.rs b/crates/engine/src/cmd/buildcmds/live_paint.rs index e5e7757486..faeaa20cbc 100644 --- a/crates/engine/src/cmd/buildcmds/live_paint.rs +++ b/crates/engine/src/cmd/buildcmds/live_paint.rs @@ -269,9 +269,257 @@ pub(super) fn lp_gap_options(s: &mut Session, p: &Value) -> Result { Ok(json!({ "ids": ids_json(&targets), "faces": faces, "gaps": gaps_json(&gaps), "closed": closed })) } +/// Which parts a Live Paint Bucket click paints besides the one under the pointer. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum LpScope { + /// The part under the pointer alone (a click). + One, + /// A face and the faces reached from it across unstroked edges, or an edge and the edges + /// joined to it that have the same stroke (a double-click). + Connected, + /// Every face with the same fill, or every edge with the same stroke, in the group (a + /// triple-click). + SamePaint, +} + +/// The `scope` of `livePaint.fill` and `livePaint.strokeEdge`: `one` when left out or null. +fn scope_param(p: &Value, c: &str) -> Result { + match p.get("scope").filter(|v| !v.is_null()) { + None => Ok(LpScope::One), + Some(v) => match v.as_str() { + Some("one") => Ok(LpScope::One), + Some("connected") => Ok(LpScope::Connected), + Some("samePaint") => Ok(LpScope::SamePaint), + _ => Err(bad(c, "scope must be \"one\", \"connected\" or \"samePaint\"")), + }, + } +} + +/// The `match` of `livePaint.fill` and `livePaint.strokeEdge`: a paint as the document stores it, +/// None when left out or null. With `allowed` false (a scope that compares no paints) a `match` is +/// an error naming `scopes`, the scopes it applies to. +fn match_param(p: &Value, c: &str, allowed: bool, scopes: &str) -> Result> { + let Some(v) = p.get("match").filter(|v| !v.is_null()) else { return Ok(None) }; + if !allowed { + return Err(bad(c, format!("match applies only with scope {scopes}"))); + } + serde_json::from_value::(v.clone()).map(Some).map_err(|_| bad(c, "match must be a paint as the document stores it")) +} + +/// The greatest distance (pt) between two points that the Live Paint Bucket takes as one point: +/// where edges meet, and where a face's outline runs along an edge. +const LP_JOIN_TOL: f64 = 1e-4; + +/// The cell [`LP_JOIN_TOL`] wide that holds `p`, for finding the points near it; two points within +/// [`LP_JOIN_TOL`] of each other lie in the same or neighboring cells. The cast saturates, so a +/// coordinate too large or not finite does not overflow. +fn lp_cell(p: Point) -> (i64, i64) { + ((p.x / LP_JOIN_TOL).round() as i64, (p.y / LP_JOIN_TOL).round() as i64) +} + +/// Whether `edge` draws no stroke: its stroke paint is none or its weight is 0. +fn unstroked(edge: &Node) -> bool { + edge.appearance.stroke_paint().is_none() || edge.appearance.stroke_width() <= 0.0 +} + +/// The segments of `pd`. +fn lp_segments(pd: &PathData) -> Vec { + pd.subpaths.iter().flat_map(|sp| (0..sp.segment_count()).map(|i| sp.segment(i))).collect() +} + +/// The faces of Live Paint group `group` that a flood from face `start` reaches: `start`, and each +/// face that shares with a face already reached an edge that is hidden or draws no stroke +/// ([`unstroked`]). Hidden faces are not reached and do not pass the flood on. A face runs along an +/// edge where a segment of its outline has its middle within [`LP_JOIN_TOL`] of one of the edge's +/// segments, over the part of that segment between its outline segment's ends; two faces share the +/// edge where those parts overlap along more than [`LP_JOIN_TOL`], so two faces that a Gap +/// Detection gap parts on the same side of an edge, whose parts only touch, do not. +fn flood_faces(group: &Node, start: NodeId) -> Vec { + use kurbo::{ParamCurve, ParamCurveArclen, ParamCurveNearest}; + // Each edge segment, and whether a flood crosses it. + let edges: Vec<(kurbo::CubicBez, bool)> = b::edges(group) + .into_iter() + .flat_map(|e| { + let cross = !e.visible || unstroked(e); + e.path_data().map(lp_segments).unwrap_or_default().into_iter().map(move |s| (s, cross)) + }) + .collect(); + let mut mids: std::collections::HashMap<(i64, i64), Vec<(Point, usize)>> = std::collections::HashMap::new(); + for (k, (s, _)) in edges.iter().enumerate() { + let m = s.eval(0.5); + mids.entry(lp_cell(m)).or_default().push((m, k)); + } + // The faces along each edge segment a flood crosses, each with the part of the segment it runs + // along (from and to, in the segment's own parameter). A face outline segment is usually an + // edge segment, with the same middle; one that is not (a piece of an edge segment where a Gap + // Detection line meets it, or the line itself) is measured against the edge segments near it. + let mut along: std::collections::HashMap> = std::collections::HashMap::new(); + let mut add = |k: usize, id: NodeId, piece: &kurbo::CubicBez| { + if let Some((s, true)) = edges.get(k) { + let (a, c) = (s.nearest(piece.p0, 1e-9).t, s.nearest(piece.p3, 1e-9).t); + along.entry(k).or_default().push((id, a.min(c), a.max(c))); + } + }; + let mut pieces: Vec<(kurbo::CubicBez, NodeId)> = vec![]; + for f in b::faces(group).into_iter().filter(|f| f.visible) { + for piece in f.path_data().map(lp_segments).unwrap_or_default() { + let m = piece.eval(0.5); + let (x, y) = lp_cell(m); + let same = (-1..=1) + .flat_map(|dx| (-1..=1).map(move |dy| (x.saturating_add(dx), y.saturating_add(dy)))) + .flat_map(|c| mids.get(&c).map(Vec::as_slice).unwrap_or_default()) + .find(|(q, _)| (*q - m).hypot() <= LP_JOIN_TOL); + match same { + Some(&(_, k)) => add(k, f.id, &piece), + None => pieces.push((piece, f.id)), + } + } + } + if !pieces.is_empty() { + let grid = LpEdgeGrid::new(&edges); + for (piece, id) in pieces { + let m = piece.eval(0.5); + for k in grid.near(m) { + if edges.get(k).is_some_and(|(s, cross)| *cross && s.nearest(m, 1e-9).distance_sq.sqrt() <= LP_JOIN_TOL) { + add(k, id, &piece); + } + } + } + } + let mut next: std::collections::HashMap> = std::collections::HashMap::new(); + for (k, faces) in &along { + let Some((s, _)) = edges.get(*k) else { continue }; + for (i, &(a, a0, a1)) in faces.iter().enumerate() { + for &(c, c0, c1) in faces.iter().skip(i + 1) { + let (from, to) = (a0.max(c0), a1.min(c1)); + if a != c && from < to && s.subsegment(from..to).arclen(1e-6) > LP_JOIN_TOL { + next.entry(a).or_default().push(c); + next.entry(c).or_default().push(a); + } + } + } + } + let mut reached = vec![start]; + let mut seen = std::collections::HashSet::from([start]); + let mut i = 0; + while let Some(&f) = reached.get(i) { + i += 1; + for &n in next.get(&f).map(Vec::as_slice).unwrap_or_default() { + if seen.insert(n) { + reached.push(n); + } + } + } + reached +} + +/// Most grid cells one edge segment is listed in by [`LpEdgeGrid`]; a longer one is tried for +/// every point. +const LP_GRID_SPAN: i64 = 1024; + +/// The farthest cell from the grid's origin, on each axis, that [`LpEdgeGrid`] numbers a point in. +const LP_GRID_LIMIT: f64 = 1_048_576.0; + +/// The edge segments a flood crosses, by the cells of a square grid (about one cell per segment) +/// that their bounds, widened by [`LP_JOIN_TOL`], cover. +struct LpEdgeGrid { + origin: Point, + cell: f64, + /// Segment indices by cell. + cells: std::collections::HashMap<(i64, i64), Vec>, + /// Segments whose bounds cover more than [`LP_GRID_SPAN`] cells, near every point. + wide: Vec, +} + +impl LpEdgeGrid { + /// The grid of the segments of `edges` that a flood crosses (those marked true). + fn new(edges: &[(kurbo::CubicBez, bool)]) -> Self { + use kurbo::ParamCurveExtrema; + let boxes: Vec<(usize, Rect)> = + edges.iter().enumerate().filter(|(_, e)| e.1).map(|(k, (s, _))| (k, s.bounding_box().inflate(LP_JOIN_TOL, LP_JOIN_TOL))).collect(); + let all = boxes.iter().map(|b| b.1).reduce(|a, c| a.union(c)).unwrap_or_default(); + let side = (boxes.len() as f64).sqrt().ceil().max(1.0); + let cell = all.width().max(all.height()) / side; + let cell = if cell.is_finite() && cell > LP_JOIN_TOL { cell } else { LP_JOIN_TOL }; + let mut grid = Self { origin: all.origin(), cell, cells: std::collections::HashMap::new(), wide: vec![] }; + for (k, b) in boxes { + let ((x0, y0), (x1, y1)) = (grid.cell_of(Point::new(b.x0, b.y0)), grid.cell_of(Point::new(b.x1, b.y1))); + if (x1 - x0 + 1).saturating_mul(y1 - y0 + 1) > LP_GRID_SPAN { + grid.wide.push(k); + continue; + } + for x in x0..=x1 { + for y in y0..=y1 { + grid.cells.entry((x, y)).or_default().push(k); + } + } + } + grid + } + + /// The cell `p` is in, counted from the origin (at most [`LP_GRID_LIMIT`] cells away on each + /// axis). + fn cell_of(&self, p: Point) -> (i64, i64) { + let at = |v: f64, o: f64| ((v - o) / self.cell).floor().clamp(-LP_GRID_LIMIT, LP_GRID_LIMIT) as i64; + (at(p.x, self.origin.x), at(p.y, self.origin.y)) + } + + /// The segments whose widened bounds may hold `p`. + fn near(&self, p: Point) -> impl Iterator + '_ { + self.wide.iter().chain(self.cells.get(&self.cell_of(p)).into_iter().flatten()).copied() + } +} + +/// The edges of Live Paint group `group` that are not hidden and are joined to edge `start` through +/// edges with stroke paint `paint`: `start`, and each edge with that stroke paint that has a +/// segment end within [`LP_JOIN_TOL`] of a segment end of an edge already reached. +fn connected_edges(group: &Node, start: NodeId, paint: &Paint) -> Vec { + let edges: Vec<&Arc> = + b::edges(group).into_iter().filter(|e| e.visible && (e.id == start || e.appearance.stroke_paint() == *paint)).collect(); + let ends: Vec> = edges + .iter() + .map(|e| { + e.path_data() + .map(|pd| pd.subpaths.iter().flat_map(|sp| (0..sp.segment_count()).map(|i| sp.segment(i)).flat_map(|c| [c.p0, c.p3])).collect()) + .unwrap_or_default() + }) + .collect(); + let mut at: std::collections::HashMap<(i64, i64), Vec<(Point, usize)>> = std::collections::HashMap::new(); + for (i, pts) in ends.iter().enumerate() { + for &p in pts { + at.entry(lp_cell(p)).or_default().push((p, i)); + } + } + let Some(first) = edges.iter().position(|e| e.id == start) else { return vec![] }; + let mut reached = vec![first]; + let mut seen = std::collections::HashSet::from([first]); + let mut k = 0; + while let Some(&i) = reached.get(k) { + k += 1; + for &p in ends.get(i).map(Vec::as_slice).unwrap_or_default() { + let (x, y) = lp_cell(p); + for dx in -1..=1 { + for dy in -1..=1 { + for &(q, j) in at.get(&(x.saturating_add(dx), y.saturating_add(dy))).map(Vec::as_slice).unwrap_or_default() { + if (q - p).hypot() <= LP_JOIN_TOL && seen.insert(j) { + reached.push(j); + } + } + } + } + } + } + reached.into_iter().filter_map(|i| edges.get(i).map(|e| e.id)).collect() +} + pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result { const C: &str = "livePaint.fill"; let pt = point_param(p, "point").filter(|q| finite(*q)).ok_or_else(|| bad(C, "missing point [x,y]"))?; + let scope = scope_param(p, C)?; + let like = match_param(p, C, scope == LpScope::SamePaint, "\"samePaint\"")?; + if scope != LpScope::One && p.get("points").is_some() { + return Err(bad(C, "scope applies to a click: leave out points")); + } let parse_chunk = |input: &Value, start: Point| -> Result> { let values = input .as_array() @@ -305,7 +553,7 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result { let paint = paint_from(s, p)?.unwrap_or_else(|| s.paint.fill.clone()); let group = object_param(p, "group", C)?; let roots = if group.is_none() { root_ids(s, p)? } else { vec![] }; - let (g, face) = s.edit("Live Paint Bucket", |d, sel| { + let (g, face, count) = s.edit("Live Paint Bucket", |d, sel| { let gid = match group { Some(g) => { if !d.node(g).is_some_and(is_live_paint) { @@ -332,6 +580,18 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result { .map(|f| f.id) .ok_or_else(|| EngineError::Other("no Live Paint face at that point".into()))?; let mut targets = std::collections::BTreeSet::from([fid]); + if scope != LpScope::One { + let n = d.node(gid).ok_or(EngineError::NoNode(gid))?; + if scope == LpScope::Connected { + targets.extend(flood_faces(n, fid)); + } else { + let like = match &like { + Some(m) => m.clone(), + None => d.node(fid).ok_or(EngineError::NoNode(fid))?.appearance.fill_paint(), + }; + targets.extend(b::faces(n).into_iter().filter(|f| f.visible && f.appearance.fill_paint() == like).map(|f| f.id)); + } + } if let Some(points) = points { let n = d.node(gid).ok_or(EngineError::NoNode(gid))?; // Use the existing region-crossing probes, so even a face narrower than the distance @@ -355,13 +615,14 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result { targets.extend(map.hits_along(&chunk, None).regions.iter().filter_map(|i| face_ids.get(*i).copied())); } } + let count = targets.len(); for target in targets { d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance.set_fill(paint.clone()); } - Ok((gid, fid)) + Ok((gid, fid, count)) })?; s.remember_paint(&paint); - Ok(json!({ "group": g.0, "face": face.0 })) + Ok(json!({ "group": g.0, "face": face.0, "count": count })) } pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result { @@ -375,18 +636,31 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "width out of range")); } let tol = number_or(p, "tolerance", 4.0, C)?.clamp(0.0, 1000.0); - let edge = s.edit("Live Paint Bucket", |d, _| { + let scope = scope_param(p, C)?; + let like = match_param(p, C, scope != LpScope::One, "\"connected\" or \"samePaint\"")?; + let (edge, count) = s.edit("Live Paint Bucket", |d, _| { let n = d.node(g).filter(|n| is_live_paint(n)).ok_or_else(|| bad(C, format!("{g} is not a Live Paint group")))?; - let eid = b::visible_edge_near(n, pt, tol).map(|e| e.id).ok_or_else(|| EngineError::Other("no Live Paint edge near that point".into()))?; - let e = d.node_mut(eid).ok_or(EngineError::NoNode(eid))?; - e.appearance.set_stroke(paint.clone()); - if let Some(st) = e.appearance.stroke_mut() { - st.width = width; + let start = b::visible_edge_near(n, pt, tol).ok_or_else(|| EngineError::Other("no Live Paint edge near that point".into()))?; + let eid = start.id; + let like = like.clone().unwrap_or_else(|| start.appearance.stroke_paint()); + let targets = match scope { + LpScope::One => vec![eid], + LpScope::Connected => connected_edges(n, eid, &like), + LpScope::SamePaint => std::iter::once(eid) + .chain(b::edges(n).into_iter().filter(|e| e.visible && e.id != eid && e.appearance.stroke_paint() == like).map(|e| e.id)) + .collect(), + }; + for target in &targets { + let e = d.node_mut(*target).ok_or(EngineError::NoNode(*target))?; + e.appearance.set_stroke(paint.clone()); + if let Some(st) = e.appearance.stroke_mut() { + st.width = width; + } } - Ok(eid) + Ok((eid, targets.len())) })?; s.remember_paint(&paint); - Ok(json!({ "group": g.0, "edge": edge.0 })) + Ok(json!({ "group": g.0, "edge": edge.0, "count": count })) } pub(super) fn lp_info(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 6eeace1073..c0fbd5efe0 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -2541,6 +2541,332 @@ fn live_paint_fill_skips_hidden_faces() { assert!(!node(&s, hidden).visible); } +/// A Live Paint group of 50 pt squares side by side, 50 pt tall, with their left sides at each of +/// `xs`. +fn live_squares(s: &mut Session, xs: &[f64]) -> NodeId { + let ids: Vec = xs.iter().map(|&x| rect(s, x, 0.0, 50.0, 50.0).0).collect(); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap()) +} + +/// The ids of the faces of `g` that hold `p`, in the order given. +fn faces_at(s: &Session, g: NodeId, ps: &[(f64, f64)]) -> Vec { + ps.iter().map(|&(x, y)| vectorcraft_tools::builder::face_at(&node(s, g), Point::new(x, y)).unwrap().id).collect() +} + +/// The edges of `g` whose bounds lie within `r`. +fn edges_in(s: &Session, g: NodeId, r: Rect) -> Vec { + let r = r.inflate(1e-6, 1e-6); + vectorcraft_tools::builder::edges(&node(s, g)) + .iter() + .filter(|e| e.geometric_bounds().is_some_and(|bb| r.contains(Point::new(bb.x0, bb.y0)) && r.contains(Point::new(bb.x1, bb.y1)))) + .map(|e| e.id) + .collect() +} + +/// Give `ids` stroke paint `paint` at weight 1 (none: no stroke), and `fill` to the faces in `faces`. +fn paint_parts(s: &mut Session, ids: &[NodeId], paint: &Paint, faces: &[(NodeId, Paint)]) { + s.edit("t", |d, _| { + for id in ids { + let n = d.node_mut(*id).unwrap(); + n.appearance.set_stroke(paint.clone()); + if let Some(st) = n.appearance.stroke_mut() { + st.width = 1.0; + } + } + for (id, fill) in faces { + d.node_mut(*id).unwrap().appearance.set_fill(fill.clone()); + } + Ok(()) + }) + .unwrap(); +} + +fn fill_of(s: &Session, id: NodeId) -> Paint { + node(s, id).appearance.fill_paint() +} + +/// A double-click on a face fills it and the faces reached across edges that draw no stroke; a +/// stroked edge and a hidden face stop the flood. +#[test] +fn live_paint_bucket_double_click_floods_across_unstroked_edges() { + let mut s = session(); + let g = live_squares(&mut s, &[0.0, 50.0, 100.0, 150.0]); + let [a, b, c, d] = faces_at(&s, g, &[(25.0, 25.0), (75.0, 25.0), (125.0, 25.0), (175.0, 25.0)])[..] else { panic!("four faces") }; + let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 201.0, 51.0)); + paint_parts(&mut s, &all, &Paint::None, &[]); + let stroked = edges_in(&s, g, Rect::new(150.0, 0.0, 150.0, 50.0)); + assert!(!stroked.is_empty()); + paint_parts(&mut s, &stroked, &Paint::solid(Color::rgb(0.0, 0.0, 0.0)), &[]); + let white = fill_of(&s, d); + let green = Paint::solid(Color::from_hex("#00ff00").unwrap()); + assert_ne!(white, green); + let depth = s.doc().unwrap().history.undo.len(); + let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 25], "color": "#00ff00", "scope": "connected"})).unwrap(); + assert_eq!((&r["face"], &r["count"]), (&json!(a.0), &json!(3))); + assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [green.clone(), green.clone(), green.clone(), white.clone()]); + assert_eq!(s.doc().unwrap().history.undo.len(), depth + 1, "one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!([a, b, c].iter().all(|f| fill_of(&s, *f) != green)); + // A hidden face is not filled and does not pass the flood on. + s.execute("object.setProps", &json!({"ids": [b.0], "visible": false})).unwrap(); + let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 25], "color": "#00ff00", "scope": "connected"})).unwrap(); + assert_eq!(r["count"], 1); + assert_eq!([a, b, c].map(|f| fill_of(&s, f) == green), [true, false, false]); + while s.doc().unwrap().history.undo.len() > depth { + s.execute("edit.undo", &json!({})).unwrap(); + } + // The tool: two clicks and the double-click that follows them. + let v = ViewInfo::default(); + s.select_tool("livePaintBucket", v).unwrap(); + s.paint.fill = green.clone(); + for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] { + s.pointer(&PointerEvent::new(kind, 125.0, 25.0), v).unwrap(); + } + assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [green.clone(), green.clone(), green, white]); +} + +/// The flood crosses curved edges, and reaches a face 0.012 pt wide. +#[test] +fn live_paint_bucket_double_click_floods_curved_and_narrow_faces() { + let mut s = session(); + let ids: Vec = [0.0, 60.0] + .iter() + .map(|&x| s.execute("shape.ellipse", &json!({"x": x, "y": 0, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap()) + .collect(); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 161.0, 101.0)); + paint_parts(&mut s, &all, &Paint::None, &[]); + let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [20, 50], "color": "#00ff00", "scope": "connected"})).unwrap(); + assert_eq!(r["count"], 3, "both lunes and the lens between them"); + + let mut s = session(); + let ids = [rect(&mut s, 0.0, 0.0, 50.0, 50.0).0, rect(&mut s, 49.988, 0.0, 50.0, 50.0).0]; + s.execute("select.set", &json!({"ids": ids})).unwrap(); + let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let [a, sliver, c] = faces_at(&s, g, &[(25.0, 25.0), (49.994, 25.0), (75.0, 25.0)])[..] else { panic!("three faces") }; + assert!(a != sliver && sliver != c); + let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 101.0, 51.0)); + paint_parts(&mut s, &all, &Paint::None, &[]); + let green = Paint::solid(Color::from_hex("#00ff00").unwrap()); + let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 25], "color": "#00ff00", "scope": "connected"})).unwrap(); + assert_eq!(r["count"], 3); + assert_eq!([a, sliver, c].map(|f| fill_of(&s, f)), [green.clone(), green.clone(), green]); +} + +/// The flood crosses a hidden edge, and an edge that a Gap Detection gap meets partway along, but +/// not the gap. +#[test] +fn live_paint_bucket_double_click_floods_across_hidden_edges_and_past_gaps() { + let mut s = session(); + let g = live_squares(&mut s, &[0.0, 50.0]); + let black = Paint::solid(Color::rgb(0.0, 0.0, 0.0)); + let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 101.0, 51.0)); + paint_parts(&mut s, &all, &black, &[]); + let fill = |s: &mut Session, g: NodeId, at: [f64; 2]| { + s.execute("livePaint.fill", &json!({"group": g.0, "point": at, "color": "#00ff00", "scope": "connected"})).unwrap()["count"].clone() + }; + assert_eq!(fill(&mut s, g, [25.0, 25.0]), 1, "a stroked edge stops the flood"); + s.execute("edit.undo", &json!({})).unwrap(); + let middle = edges_in(&s, g, Rect::new(50.0, 0.0, 50.0, 50.0)); + s.execute("object.setProps", &json!({"ids": middle.iter().map(|e| e.0).collect::>(), "visible": false})).unwrap(); + assert_eq!(fill(&mut s, g, [25.0, 25.0]), 2, "a hidden edge does not"); + + // Square B (100..200 by 0..100) over square C (100..200 by 100..200), and a line down the middle + // of B that stops 2 pt short of their shared edge: Gap Detection closes it, so B is two faces + // that each run along part of the shared edge, which is one edge segment. + let mut s = session(); + let mut ids = vec![rect(&mut s, 100.0, 0.0, 100.0, 100.0).0, rect(&mut s, 100.0, 100.0, 100.0, 100.0).0]; + let line = s.execute("path.create", &json!({"anchors": [{"x": 150, "y": 0}, {"x": 150, "y": 98}]})).unwrap(); + ids.push(line["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("livePaint.gapOptions", &json!({"id": g.0, "detect": true, "size": "small"})).unwrap(); + let [b1, b2, c] = faces_at(&s, g, &[(125.0, 50.0), (175.0, 50.0), (150.0, 150.0)])[..] else { panic!("three faces") }; + assert!(b1 != b2 && b2 != c && b1 != c); + let all = edges_in(&s, g, Rect::new(99.0, -1.0, 201.0, 201.0)); + paint_parts(&mut s, &all, &black, &[]); + let shared = edges_in(&s, g, Rect::new(100.0, 100.0, 200.0, 100.0)); + assert!(!shared.is_empty()); + paint_parts(&mut s, &shared, &Paint::None, &[]); + assert_eq!(fill(&mut s, g, [150.0, 150.0]), 3, "from C across the shared edge to both faces of B"); + s.execute("edit.undo", &json!({})).unwrap(); + // With the line and the shared edge stroked, only the gap lies between the two faces of B. + paint_parts(&mut s, &shared, &black, &[]); + assert_eq!(fill(&mut s, g, [125.0, 50.0]), 1, "the flood does not pass the gap"); + + // B alone, its outline drawing no stroke and the line stroked: the two faces of B run along + // different parts of the outline's bottom segment, on the same side, and the flood does not + // join them there. + let mut s = session(); + let mut ids = vec![rect(&mut s, 100.0, 0.0, 100.0, 100.0).0]; + let line = s.execute("path.create", &json!({"anchors": [{"x": 150, "y": 0}, {"x": 150, "y": 98}]})).unwrap(); + ids.push(line["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("livePaint.gapOptions", &json!({"id": g.0, "detect": true, "size": "small"})).unwrap(); + assert_eq!(vectorcraft_tools::builder::faces(&node(&s, g)).len(), 2); + let all = edges_in(&s, g, Rect::new(99.0, -1.0, 201.0, 101.0)); + paint_parts(&mut s, &all, &Paint::None, &[]); + let line = edges_in(&s, g, Rect::new(150.0, 0.0, 150.0, 98.0)); + assert!(!line.is_empty() && line.len() < all.len()); + paint_parts(&mut s, &line, &black, &[]); + assert_eq!(fill(&mut s, g, [125.0, 50.0]), 1, "the gap parts the two faces along the bottom"); +} + +/// A triple-click on a face fills every face of the group with that face's fill, joined to it or +/// not. Through the tool, the fill compared is the face's fill before the first click. +#[test] +fn live_paint_bucket_triple_click_fills_every_face_of_the_same_fill() { + let mut s = session(); + let g = live_squares(&mut s, &[0.0, 50.0, 100.0, 150.0]); + let [a, b, c, d] = faces_at(&s, g, &[(25.0, 25.0), (75.0, 25.0), (125.0, 25.0), (175.0, 25.0)])[..] else { panic!("four faces") }; + let (red, blue) = (Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0))); + let green = Paint::solid(Color::from_hex("#00ff00").unwrap()); + let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 201.0, 51.0)); + paint_parts(&mut s, &all, &Paint::None, &[(a, red.clone()), (b, blue.clone()), (c, red.clone()), (d, red.clone())]); + let stroked = edges_in(&s, g, Rect::new(100.0, 0.0, 100.0, 50.0)); + paint_parts(&mut s, &stroked, &Paint::solid(Color::rgb(0.0, 0.0, 0.0)), &[]); + let depth = s.doc().unwrap().history.undo.len(); + let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 25], "color": "#00ff00", "scope": "samePaint"})).unwrap(); + assert_eq!(r["count"], 3); + assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [green.clone(), blue.clone(), green.clone(), green.clone()]); + s.execute("edit.undo", &json!({})).unwrap(); + // The tool: the first click fills the face, the double-click floods across x = 50 into B, and + // the triple-click fills the faces that were red. + let v = ViewInfo::default(); + s.select_tool("livePaintBucket", v).unwrap(); + s.paint.fill = green.clone(); + for kind in [ + PointerKind::Down, + PointerKind::Up, + PointerKind::Down, + PointerKind::Up, + PointerKind::DoubleClick, + PointerKind::Down, + PointerKind::Up, + PointerKind::TripleClick, + ] { + s.pointer(&PointerEvent::new(kind, 25.0, 25.0), v).unwrap(); + } + assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [green.clone(), green.clone(), green.clone(), green.clone()]); + // A match given by the caller is the fill compared. + while s.doc().unwrap().history.undo.len() > depth { + s.execute("edit.undo", &json!({})).unwrap(); + } + assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [red.clone(), blue.clone(), red.clone(), red.clone()]); + let r = s + .execute( + "livePaint.fill", + &json!({"group": g.0, "point": [25, 25], "color": "#00ff00", "scope": "samePaint", "match": serde_json::to_value(&blue).unwrap()}), + ) + .unwrap(); + assert_eq!(r["count"], 2); + assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [green.clone(), green, red.clone(), red]); +} + +/// A triple-click whose first click makes the Live Paint group from the selected paths matches the +/// fill the face was made with. +#[test] +fn live_paint_bucket_triple_click_after_making_the_group_matches_the_made_fill() { + let mut s = session(); + let ids: Vec = [0.0, 100.0, 200.0].iter().map(|&x| rect(&mut s, x, 0.0, 50.0, 50.0)).collect(); + let (red, blue) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0)); + for (id, c) in ids.iter().zip([red, red, blue]) { + set_fill(&mut s, *id, c); + } + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); + let green = Paint::solid(Color::from_hex("#00ff00").unwrap()); + let v = ViewInfo::default(); + s.select_tool("livePaintBucket", v).unwrap(); + s.paint.fill = green.clone(); + for kind in [ + PointerKind::Down, + PointerKind::Up, + PointerKind::Down, + PointerKind::Up, + PointerKind::DoubleClick, + PointerKind::Down, + PointerKind::Up, + PointerKind::TripleClick, + ] { + s.pointer(&PointerEvent::new(kind, 25.0, 25.0), v).unwrap(); + } + let g = vectorcraft_tools::builder::live_paint_at(&s.doc().unwrap().doc, Point::new(25.0, 25.0)).expect("the clicks made a group"); + let faces = faces_at(&s, g, &[(25.0, 25.0), (125.0, 25.0), (225.0, 25.0)]); + assert_eq!(faces.iter().map(|f| fill_of(&s, *f)).collect::>(), [green.clone(), green, Paint::solid(blue)]); +} + +/// A double-click on an edge paints the edges joined to it that have its stroke, and a +/// triple-click every edge of the group with that stroke; an edge with another stroke is left. +#[test] +fn live_paint_bucket_double_and_triple_click_paint_joined_and_same_stroke_edges() { + let mut s = session(); + let g = live_squares(&mut s, &[0.0, 50.0, 200.0]); + let black = Paint::solid(Color::rgb(0.0, 0.0, 0.0)); + let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let green = Paint::solid(Color::from_hex("#00ff00").unwrap()); + let joined = edges_in(&s, g, Rect::new(0.0, 0.0, 100.0, 50.0)); + let apart = edges_in(&s, g, Rect::new(200.0, 0.0, 250.0, 50.0)); + let middle = edges_in(&s, g, Rect::new(50.0, 0.0, 50.0, 50.0)); + assert!(!apart.is_empty() && !middle.is_empty()); + paint_parts(&mut s, &joined, &black, &[]); + paint_parts(&mut s, &apart, &black, &[]); + paint_parts(&mut s, &middle, &red, &[]); + let stroke = |s: &Session, ids: &[NodeId]| ids.iter().map(|id| node(s, *id).appearance.stroke_paint()).collect::>(); + let outer: Vec = joined.iter().copied().filter(|e| !middle.contains(e)).collect(); + let r = + s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": [25, 0], "color": "#00ff00", "width": 3, "scope": "connected"})).unwrap(); + assert_eq!(r["count"], outer.len()); + assert!(stroke(&s, &outer).iter().all(|p| *p == green)); + assert!(outer.iter().all(|e| node(&s, *e).appearance.stroke_width() == 3.0)); + assert!(stroke(&s, &middle).iter().all(|p| *p == red), "another stroke is left"); + assert!(stroke(&s, &apart).iter().all(|p| *p == black), "edges not joined are left"); + s.execute("edit.undo", &json!({})).unwrap(); + let r = s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": [25, 0], "color": "#00ff00", "scope": "samePaint"})).unwrap(); + assert_eq!(r["count"], outer.len() + apart.len()); + assert!(stroke(&s, &outer).iter().chain(&stroke(&s, &apart)).all(|p| *p == green)); + assert!(stroke(&s, &middle).iter().all(|p| *p == red)); + // A hidden edge is not painted. + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("object.setProps", &json!({"ids": [apart[0].0], "visible": false})).unwrap(); + let r = s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": [25, 0], "color": "#00ff00", "scope": "samePaint"})).unwrap(); + assert_eq!(r["count"], outer.len() + apart.len() - 1); + assert_eq!(node(&s, apart[0]).appearance.stroke_paint(), black); +} + +/// A `scope` that is not one of the three, a `match` that is not a paint or is given with a scope +/// that compares none, and a scope with a drag's points are refused; nothing changes. +#[test] +fn live_paint_scope_and_match_are_checked() { + let mut s = session(); + let g = live(&mut s); + let none = serde_json::to_value(Paint::None).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let depth = s.doc().unwrap().history.undo.len(); + for (cmd, p) in [ + ("livePaint.fill", json!({"group": g.0, "point": [75, 50], "scope": "all"})), + ("livePaint.fill", json!({"group": g.0, "point": [75, 50], "scope": 2})), + ("livePaint.fill", json!({"group": g.0, "point": [75, 50], "match": none})), + ("livePaint.fill", json!({"group": g.0, "point": [75, 50], "scope": "connected", "match": none})), + ("livePaint.fill", json!({"group": g.0, "point": [75, 50], "scope": "samePaint", "match": "red"})), + ("livePaint.fill", json!({"group": g.0, "point": [75, 50], "scope": "connected", "points": [[75, 50], [125, 50]]})), + ("livePaint.strokeEdge", json!({"group": g.0, "point": [100, 50], "scope": "Connected"})), + ("livePaint.strokeEdge", json!({"group": g.0, "point": [100, 50], "scope": "one", "match": none})), + ("livePaint.strokeEdge", json!({"group": g.0, "point": [100, 50], "scope": "samePaint", "match": {"type": "plaid"}})), + ] { + assert!(s.execute(cmd, &p).is_err(), "{cmd} {p}"); + } + assert_eq!(s.doc().unwrap().doc, before); + assert_eq!(s.doc().unwrap().history.undo.len(), depth); + // "one" and null are a click's scope. + for scope in [json!("one"), Value::Null] { + let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [75, 50], "scope": scope})).unwrap(); + assert_eq!(r["count"], 1); + } +} + #[test] fn live_paint_release_and_expand() { let mut s = session(); diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index ae0c55ac76..8c560a4731 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -650,7 +650,7 @@ impl Session { match ev.kind { PointerKind::Down | PointerKind::Drag => self.pointer_held = true, PointerKind::Up | PointerKind::Move => self.pointer_held = false, - PointerKind::DoubleClick => {} + PointerKind::DoubleClick | PointerKind::TripleClick => {} } match ev.kind { PointerKind::Down => { diff --git a/crates/mcp/src/headless.rs b/crates/mcp/src/headless.rs index 69c7b5ba0e..8bd8afc2e5 100644 --- a/crates/mcp/src/headless.rs +++ b/crates/mcp/src/headless.rs @@ -81,6 +81,7 @@ pub(crate) fn pointer_kind(k: &str) -> Option { "up" => PointerKind::Up, "move" => PointerKind::Move, "doubleclick" | "dblclick" => PointerKind::DoubleClick, + "tripleclick" => PointerKind::TripleClick, _ => return None, }) } @@ -238,7 +239,7 @@ impl Headless { .map(|(e, backquote)| { let mods = packet_mods(e)?.unwrap_or(base); let kind = s(e, "kind").unwrap_or(""); - let kind = pointer_kind(kind).ok_or_else(|| format!("unknown pointer kind `{kind}` (down|drag|up|move|doubleclick)"))?; + let kind = pointer_kind(kind).ok_or_else(|| format!("unknown pointer kind `{kind}` (down|drag|up|move|doubleclick|tripleclick)"))?; PointerEvent::json_check(e)?; if s(e, "space") == Some("screen") { return Err("screen-space pointer events need the desktop app; use document coordinates".to_string()); diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 6529cf175d..cd34382408 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -16,6 +16,7 @@ mod gradient; mod limits; mod links; mod liquify; +mod livepaint; mod pen; mod persp; mod place; diff --git a/crates/mcp/src/tests/livepaint.rs b/crates/mcp/src/tests/livepaint.rs new file mode 100644 index 0000000000..f3952a90f6 --- /dev/null +++ b/crates/mcp/src/tests/livepaint.rs @@ -0,0 +1,49 @@ +//! The Live Paint Bucket through MCP: `pointer_gesture` sends a triple-click as `tripleclick`. + +use serde_json::{Value, json}; + +use crate::{Backend, Headless, call_tool}; + +fn ok(h: &mut Headless, name: &str, args: Value) -> Value { + let r = call_tool(h, name, &args); + assert!(!r.is_error, "{name} {args}: {r:?}"); + serde_json::from_str(r.content[0]["text"].as_str().unwrap()).unwrap_or(Value::Null) +} + +fn run(h: &mut Headless, command: &str, params: Value) -> Value { + ok(h, "run_command", json!({"command": command, "params": params})) +} + +/// The fill of each face of Live Paint group `g`, left to right. +fn fills(h: &mut Headless, g: &Value) -> Vec { + let info = run(h, "livePaint.info", json!({"group": g})); + let mut faces = info["faces"].as_array().unwrap().clone(); + faces.sort_by(|a, b| a["bounds"][0].as_f64().unwrap().total_cmp(&b["bounds"][0].as_f64().unwrap())); + faces.iter().map(|f| f["fill"].clone()).collect() +} + +#[test] +fn a_triple_click_fills_every_face_of_the_same_fill() { + let mut h = Headless::new(); + h.call("engine.execute", json!({"command": "file.new", "params": {"width": 300, "height": 300}})).unwrap(); + let a = run(&mut h, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}))["id"].clone(); + let b = run(&mut h, "shape.rectangle", json!({"x": 100, "y": 0, "width": 50, "height": 50}))["id"].clone(); + let g = run(&mut h, "livePaint.make", json!({"ids": [a, b]}))["id"].clone(); + for x in [25, 125] { + run(&mut h, "livePaint.fill", json!({"group": g, "point": [x, 25], "color": "#ff0000"})); + } + let red = fills(&mut h, &g); + assert_eq!(red[0], red[1]); + // With nothing selected, the current fill changes and the group keeps its faces' fills. + run(&mut h, "select.none", json!({})); + run(&mut h, "paint.setFill", json!({"color": "#00ff00"})); + assert_eq!(fills(&mut h, &g), red); + let ev = |kind: &str| json!({"kind": kind, "x": 25, "y": 25}); + let clicks = [ev("down"), ev("up"), ev("down"), ev("up"), ev("doubleclick"), ev("down"), ev("up")]; + ok(&mut h, "pointer_gesture", json!({"tool": "livePaintBucket", "events": clicks})); + let after_two = fills(&mut h, &g); + assert_eq!(after_two[1], red[1], "the face apart is left by the clicks and the double-click"); + assert_ne!(after_two[0], red[0]); + ok(&mut h, "pointer_gesture", json!({"events": [ev("tripleclick")]})); + assert_eq!(fills(&mut h, &g), [after_two[0].clone(), after_two[0].clone()], "both faces were red"); +} diff --git a/crates/mcp/src/tools/definitions.rs b/crates/mcp/src/tools/definitions.rs index d4d69c945f..62c87f24b4 100644 --- a/crates/mcp/src/tools/definitions.rs +++ b/crates/mcp/src/tools/definitions.rs @@ -205,7 +205,7 @@ pub fn tool_definitions() -> Vec { "type": "array", "minItems": 1, "items": obj(json!({ - "kind": {"type": "string", "enum": ["down", "drag", "up", "move", "doubleclick"]}, + "kind": {"type": "string", "enum": ["down", "drag", "up", "move", "doubleclick", "tripleclick"]}, "x": num("Document x (pt)"), "y": num("Document y (pt)"), "mods": mods_schema(), diff --git a/crates/mcp/src/tools/dispatch.rs b/crates/mcp/src/tools/dispatch.rs index b1c5af70bb..af8a95e900 100644 --- a/crates/mcp/src/tools/dispatch.rs +++ b/crates/mcp/src/tools/dispatch.rs @@ -121,7 +121,7 @@ fn dispatch(b: &mut dyn Backend, name: &str, a: &Args) -> Result vec![], } } + PointerKind::TripleClick => vec![], } } diff --git a/crates/tools/src/addons/extend_path.rs b/crates/tools/src/addons/extend_path.rs index d1f54861ca..2269396f90 100644 --- a/crates/tools/src/addons/extend_path.rs +++ b/crates/tools/src/addons/extend_path.rs @@ -131,7 +131,7 @@ impl Tool for ExtendPathTool { // Back where it started: nothing to keep. if length == 0.0 { vec![Action::Cancel] } else { vec![preview, Action::Commit] } } - PointerKind::DoubleClick => vec![], + PointerKind::DoubleClick | PointerKind::TripleClick => vec![], } } diff --git a/crates/tools/src/addons/parametric_shape.rs b/crates/tools/src/addons/parametric_shape.rs index d16cb63935..61c2b416a0 100644 --- a/crates/tools/src/addons/parametric_shape.rs +++ b/crates/tools/src/addons/parametric_shape.rs @@ -301,7 +301,7 @@ impl Tool for ParametricShapeTool { fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { match ev.kind { - PointerKind::Move => vec![], + PointerKind::Move | PointerKind::TripleClick => vec![], PointerKind::Down => { let tol = cx.point_tol(); let grip = selected(cx).and_then(|(id, s)| { diff --git a/crates/tools/src/addons/slide_anchor.rs b/crates/tools/src/addons/slide_anchor.rs index e24db4c50d..0bec99cf35 100644 --- a/crates/tools/src/addons/slide_anchor.rs +++ b/crates/tools/src/addons/slide_anchor.rs @@ -96,7 +96,7 @@ impl Tool for SlideAnchorTool { // Back where it started: nothing to keep. if t == 0.0 { vec![Action::Cancel] } else { vec![preview, Action::Commit] } } - PointerKind::DoubleClick => vec![], + PointerKind::DoubleClick | PointerKind::TripleClick => vec![], } } diff --git a/crates/tools/src/addons/smart_pen.rs b/crates/tools/src/addons/smart_pen.rs index cd72f1dd40..c25ab8f670 100644 --- a/crates/tools/src/addons/smart_pen.rs +++ b/crates/tools/src/addons/smart_pen.rs @@ -527,6 +527,7 @@ impl Tool for SmartPenTool { } _ => vec![], }, + PointerKind::TripleClick => vec![], } } diff --git a/crates/tools/src/builder/live_paint.rs b/crates/tools/src/builder/live_paint.rs index e2d6c9f77e..5b6bb3a5b8 100644 --- a/crates/tools/src/builder/live_paint.rs +++ b/crates/tools/src/builder/live_paint.rs @@ -1,10 +1,11 @@ use super::cache::RegionCache; -use super::lookup::{is_live_paint, live_paint_at, live_paint_at_where, visible_edge_near, visible_face_at}; +use super::lookup::{is_live_paint, leaf_shapes, live_paint_at, live_paint_at_where, node_outline, visible_edge_near, visible_face_at}; use super::map::{HIGHLIGHT_RED, sorted_roots}; use super::{ Action, Arc, BezPath, CLICK_TOL_PX, Cursor, Document, EDGE_NAME, FACE_NAME, FillRule, Mods, Node, NodeId, Overlay, Point, PointerEvent, PointerKind, Rect, Tool, ToolContext, ToolKey, Value, json, json_ids, path_contains, }; +use vectorcraft_color::Paint; // ---------- Live Paint Bucket ---------- @@ -171,6 +172,14 @@ enum LpPaint { /// click paints nothing. With Highlight off, the face or edge under the pointer is not /// highlighted. The cursor is a filled bucket where a click fills a face, a brush where it paints /// an edge and an empty bucket where it paints nothing; with Alt it is the Eyedropper. +/// +/// A double-click on a face fills it and the faces reached from it across edges that draw no +/// stroke (`scope: "connected"`); on an edge it paints the edges joined to it that have its stroke. +/// A triple-click on a face fills every face of the group with the face's fill, and on an edge it +/// paints every edge of the group with the edge's stroke (`scope: "samePaint"`). Each click of a +/// double-click or triple-click paints as it arrives, as its own undo step, and the paint compared +/// is the one the face or edge had before the first of its clicks. Shift and the options choose a +/// face or an edge as for a click; with Alt held a double-click or triple-click paints nothing. pub struct LivePaintBucketTool { pub(super) cache: RegionCache, pub(super) hover: LpHover, @@ -178,6 +187,9 @@ pub struct LivePaintBucketTool { at: Option<(Point, bool, bool)>, /// The fill command and polyline previewed from the press's snapshot. fill_drag: Option<(Value, Vec>)>, + /// The last [`LP_PRESSES`] presses, oldest first: the face or edge each one painted, with its + /// paint before that press, or None for a press that painted no face or edge. + presses: Vec>, fills: bool, strokes: bool, highlight: bool, @@ -185,6 +197,32 @@ pub struct LivePaintBucketTool { width: f64, } +/// The face or edge a Live Paint Bucket press paints. +#[derive(Clone, Debug, PartialEq)] +struct LpPress { + /// The face or edge; None for the face of the Live Paint group the press makes. + part: Option, + /// Its fill (a face) or stroke paint (an edge) before the press. + before: Paint, +} + +/// The fill of the face under `p` in the Live Paint group that `roots` make: the fill of the +/// front-most of their paths whose outline holds `p`, else none. +fn made_face_fill(doc: &Document, roots: &[NodeId], p: Point) -> Paint { + let mut leaves = vec![]; + for n in roots.iter().filter_map(|id| doc.node(*id)) { + leaf_shapes(n, &mut leaves); + } + leaves + .iter() + .rev() + .find(|l| node_outline(l).is_some_and(|(path, rule)| !path.is_empty() && path_contains(&path, rule, p))) + .map_or(Paint::None, |l| l.appearance.fill_paint()) +} + +/// How many presses the Live Paint Bucket keeps: the three of a triple-click. +const LP_PRESSES: usize = 3; + /// Maximum points in one Live Paint fill path chunk. pub const LP_FILL_CHUNK_POINTS: usize = 4096; @@ -195,6 +233,7 @@ impl Default for LivePaintBucketTool { hover: LpHover::None, at: None, fill_drag: None, + presses: Vec::new(), fills: true, strokes: false, highlight: true, @@ -246,6 +285,62 @@ impl LivePaintBucketTool { } } + /// Note a press: what it paints, None when it paints no face or edge. + fn note_press(&mut self, press: Option) { + if self.presses.len() == LP_PRESSES { + self.presses.remove(0); + } + self.presses.push(press); + } + + /// Note a press that paints face or edge (`edge`) `n`. + fn note_part(&mut self, n: &Node, edge: bool) { + let before = if edge { n.appearance.stroke_paint() } else { n.appearance.fill_paint() }; + self.note_press(Some(LpPress { part: Some(n.id), before })); + } + + /// The paint `part` had before the first press of a click sequence of `clicks` presses, when + /// those presses all painted `part` (the first may have made the group `part` is in); else + /// `now`. + fn before(&self, part: NodeId, clicks: usize, now: Paint) -> Paint { + let Some(run) = self.presses.len().checked_sub(clicks).and_then(|from| self.presses.get(from..)) else { return now }; + let on_part = |(i, q): (usize, &Option)| q.as_ref().is_some_and(|q| q.part == Some(part) || (i == 0 && q.part.is_none())); + match run.first() { + Some(Some(first)) if run.iter().enumerate().all(on_part) => first.before.clone(), + _ => now, + } + } + + /// What a double-click (`scope` "connected", 2 `clicks`) or a triple-click ("samePaint", 3) at + /// `p` runs: the command a click there runs, with `scope`, and the paint it compares as `match`. + fn multi_click(&self, cx: &ToolContext, p: Point, mods: Mods, scope: &str, clicks: usize) -> Vec { + if mods.alt { + return vec![]; + } + let point = json!([p.x, p.y]); + let paint = self.paints(mods.shift); + if matches!(paint, LpPaint::Strokes | LpPaint::Both) + && let Some((g, Some(e))) = lp_part_at(cx.doc, p, cx.tol(4.0), true, &|id| lp_visible(cx, id)) + { + let mut v = json!({ "group": g.0, "point": point, "tolerance": cx.tol(4.0), "scope": scope }); + if let Ok(like) = serde_json::to_value(self.before(e.id, clicks, e.appearance.stroke_paint())) { + v["match"] = like; + } + return vec![Action::Exec("livePaint.strokeEdge".into(), v)]; + } + if !matches!(paint, LpPaint::Fills | LpPaint::Both) { + return vec![]; + } + let Some((g, f)) = live_paint_at(cx.doc, p).and_then(|g| Some((g, visible_face_at(cx.doc.node(g)?, p)?))) else { return vec![] }; + let mut v = json!({ "group": g.0, "point": point, "scope": scope }); + if scope == "samePaint" + && let Ok(like) = serde_json::to_value(self.before(f.id, clicks, f.appearance.fill_paint())) + { + v["match"] = like; + } + vec![Action::Exec("livePaint.fill".into(), v)] + } + /// The highlight at `p` for a pointer with Shift and Alt held as given: none with Alt or with /// Highlight off, else the face or edge a click there paints. With Highlight off the selection's /// map is still made, for the cursor ([`Self::paints_at`]). @@ -335,6 +430,7 @@ impl Tool for LivePaintBucketTool { PointerKind::Down => { self.hover = LpHover::None; if ev.mods.alt { + self.note_press(None); if ev.mods.shift { return crate::xform::eyedropper::sample_color_at(cx, p).map_or_else(Vec::new, |color| { vec![Action::Exec("paint.sampleColor".into(), json!({ "color": crate::params::color_json(&color), "ids": [] }))] @@ -359,20 +455,28 @@ impl Tool for LivePaintBucketTool { let point = json!([p.x, p.y]); let paint = self.paints(ev.mods.shift); if matches!(paint, LpPaint::Strokes | LpPaint::Both) - && let Some((g, Some(_))) = lp_part_at(cx.doc, p, cx.tol(4.0), true, &|id| lp_visible(cx, id)) + && let Some((g, Some(e))) = lp_part_at(cx.doc, p, cx.tol(4.0), true, &|id| lp_visible(cx, id)) { + self.note_part(e, true); return vec![Action::Exec("livePaint.strokeEdge".into(), json!({ "group": g.0, "point": point, "tolerance": cx.tol(4.0) }))]; } if !matches!(paint, LpPaint::Fills | LpPaint::Both) { + self.note_press(None); return vec![]; } if let Some(g) = live_paint_at(cx.doc, p) { + match cx.doc.node(g).and_then(|n| visible_face_at(n, p)) { + Some(f) => self.note_part(f, false), + None => self.note_press(None), + } return self.begin_fill(json!({ "group": g.0, "point": point }), p); } if self.cache.at(cx, p).is_some() { let roots = sorted_roots(cx.doc, &cx.selection.objects); + self.note_press(Some(LpPress { part: None, before: made_face_fill(cx.doc, &roots, p) })); return self.begin_fill(json!({ "ids": json_ids(&roots), "point": point }), p); } + self.note_press(None); vec![] } PointerKind::Drag => self.drag_fill(p), @@ -383,10 +487,15 @@ impl Tool for LivePaintBucketTool { } acts } - _ => vec![], + PointerKind::DoubleClick => self.multi_click(cx, p, ev.mods, "connected", 2), + PointerKind::TripleClick => self.multi_click(cx, p, ev.mods, "samePaint", 3), } } + fn history_moved(&mut self) { + self.presses.clear(); + } + fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { if key == ToolKey::Escape && self.fill_drag.take().is_some() { vec![Action::Cancel] } else { vec![] } } @@ -400,6 +509,7 @@ impl Tool for LivePaintBucketTool { } fn deactivate(&mut self, _cx: &ToolContext) -> Vec { + self.presses.clear(); if self.fill_drag.take().is_some() { vec![Action::Commit] } else { vec![] } } diff --git a/crates/tools/src/builder/tests.rs b/crates/tools/src/builder/tests.rs index 298e6a1907..e6bfbee7f4 100644 --- a/crates/tools/src/builder/tests.rs +++ b/crates/tools/src/builder/tests.rs @@ -1087,6 +1087,78 @@ fn bucket_click_fills_face_and_shift_click_strokes_edge() { assert_eq!(id, "livePaint.strokeEdge"); } +/// A double-click runs a click's command with `scope: "connected"` and a triple-click with +/// `"samePaint"`, matching the paint the face or edge had before the first click there. +#[test] +fn bucket_double_and_triple_click_widen_what_a_click_paints() { + let (d, gid, f2, e) = live_group_doc(); + let red = vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)); + let mut painted = d.clone(); + painted.node_mut(f2).unwrap().appearance.set_fill(red.clone()); + painted.node_mut(e).unwrap().appearance.set_stroke(red.clone()); + let s = Selection::default(); + let p = paint(); + let (cx, later) = (cx(&d, &s, &p), cx(&painted, &s, &p)); + let face_before = serde_json::to_value(d.node(f2).unwrap().appearance.fill_paint()).unwrap(); + let edge_before = serde_json::to_value(d.node(e).unwrap().appearance.stroke_paint()).unwrap(); + let red_json = serde_json::to_value(&red).unwrap(); + assert_ne!(face_before, red_json); + assert_ne!(edge_before, red_json); + let fill = |scope: &str, like: Option<&Value>| { + let mut v = json!({ "group": gid.0, "point": [75.0, 25.0], "scope": scope }); + if let Some(like) = like { + v["match"] = like.clone(); + } + vec![Action::Exec("livePaint.fill".into(), v)] + }; + let click = |t: &mut LivePaintBucketTool, cx: &ToolContext, x: f64, m: Mods| { + t.pointer(cx, &ev(PointerKind::Down, x, 25.0).with_mods(m)); + t.pointer(cx, &ev(PointerKind::Up, x, 25.0).with_mods(m)); + }; + let mut t = LivePaintBucketTool::default(); + // The clicks paint the face as they arrive; the triple-click matches the fill from before them. + click(&mut t, &cx, 75.0, Mods::default()); + click(&mut t, &later, 75.0, Mods::default()); + assert_eq!(t.pointer(&later, &ev(PointerKind::DoubleClick, 75.0, 25.0)), fill("connected", None)); + click(&mut t, &later, 75.0, Mods::default()); + assert_eq!(t.pointer(&later, &ev(PointerKind::TripleClick, 75.0, 25.0)), fill("samePaint", Some(&face_before))); + // A new click there starts again from the fill it finds. + click(&mut t, &later, 75.0, Mods::default()); + assert_eq!(t.pointer(&later, &ev(PointerKind::TripleClick, 75.0, 25.0)), fill("samePaint", Some(&red_json))); + // A click before the triple-click's own three is not part of it. + let mut t = LivePaintBucketTool::default(); + click(&mut t, &cx, 75.0, Mods::default()); + for _ in 0..3 { + click(&mut t, &later, 75.0, Mods::default()); + } + assert_eq!(t.pointer(&later, &ev(PointerKind::TripleClick, 75.0, 25.0)), fill("samePaint", Some(&red_json))); + // Shift: the edge, matching its stroke from before the first click. + let shift = Mods { shift: true, ..Default::default() }; + let stroke = |scope: &str, like: &Value| { + vec![Action::Exec( + "livePaint.strokeEdge".into(), + json!({ "group": gid.0, "point": [51.0, 25.0], "tolerance": 4.0, "scope": scope, "match": like }), + )] + }; + click(&mut t, &cx, 51.0, shift); + click(&mut t, &later, 51.0, shift); + assert_eq!(t.pointer(&later, &ev(PointerKind::DoubleClick, 51.0, 25.0).with_mods(shift)), stroke("connected", &edge_before)); + click(&mut t, &later, 51.0, shift); + assert_eq!(t.pointer(&later, &ev(PointerKind::TripleClick, 51.0, 25.0).with_mods(shift)), stroke("samePaint", &edge_before)); + // With Alt held, or with both options off, a double-click or triple-click paints nothing. + let alt = Mods { alt: true, ..Default::default() }; + for k in [PointerKind::DoubleClick, PointerKind::TripleClick] { + assert!(t.pointer(&cx, &ev(k, 75.0, 25.0).with_mods(alt)).is_empty(), "{k:?}"); + } + t.set_option("paintFills", &json!(false)); + for k in [PointerKind::DoubleClick, PointerKind::TripleClick] { + assert!(t.pointer(&cx, &ev(k, 75.0, 25.0)).is_empty(), "{k:?}"); + } + // Outside every face, nothing is painted. + t.set_option("paintFills", &json!(true)); + assert!(t.pointer(&cx, &ev(PointerKind::DoubleClick, 400.0, 400.0)).is_empty()); +} + #[test] fn bucket_options_choose_what_a_click_paints() { let (d, gid, ..) = live_group_doc(); diff --git a/crates/tools/src/cropimage.rs b/crates/tools/src/cropimage.rs index ff716bf171..0245f75112 100644 --- a/crates/tools/src/cropimage.rs +++ b/crates/tools/src/cropimage.rs @@ -169,6 +169,7 @@ impl Tool for CropImageTool { PointerKind::Up => self.drag = None, PointerKind::DoubleClick => return self.apply(cx), PointerKind::Move => self.last = ev.pos, + PointerKind::TripleClick => {} } vec![] } diff --git a/crates/tools/src/distort/puppet.rs b/crates/tools/src/distort/puppet.rs index f141378382..2ca6ec0631 100644 --- a/crates/tools/src/distort/puppet.rs +++ b/crates/tools/src/distort/puppet.rs @@ -422,7 +422,7 @@ impl Tool for PuppetWarpTool { } None => vec![], }, - PointerKind::DoubleClick => vec![], + PointerKind::DoubleClick | PointerKind::TripleClick => vec![], } } /// Delete/Backspace remove the selected pins; with none selected they are the shortcut's diff --git a/crates/tools/src/distort/width.rs b/crates/tools/src/distort/width.rs index e7050d3a79..4ebbac4981 100644 --- a/crates/tools/src/distort/width.rs +++ b/crates/tools/src/distort/width.rs @@ -300,6 +300,7 @@ impl Tool for WidthTool { self.hover = Self::spot_at(cx, p); vec![] } + PointerKind::TripleClick => vec![], PointerKind::DoubleClick => { let Some(spot) = Self::spot_at(cx, p) else { return vec![] }; let Some((w, _)) = Self::hit(cx, &spot, p) else { diff --git a/crates/tools/src/draw2/curvature.rs b/crates/tools/src/draw2/curvature.rs index 02087d997a..06ad1c1230 100644 --- a/crates/tools/src/draw2/curvature.rs +++ b/crates/tools/src/draw2/curvature.rs @@ -653,6 +653,7 @@ impl Tool for CurvatureTool { self.pts[i].1 = !self.pts[i].1; vec![Action::Exec("path.curvature".into(), self.params())] } + PointerKind::TripleClick => vec![], } } fn notify(&mut self, cx: &ToolContext, what: &str) { diff --git a/crates/tools/src/input.rs b/crates/tools/src/input.rs index 9b53d2404c..5362147b97 100644 --- a/crates/tools/src/input.rs +++ b/crates/tools/src/input.rs @@ -29,6 +29,9 @@ pub enum PointerKind { /// Moved with no button (hover). Move, DoubleClick, + /// The third click of a triple-click, after its press and release (the second click's + /// release sends [`PointerKind::DoubleClick`]). + TripleClick, } #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] diff --git a/crates/tools/src/pen.rs b/crates/tools/src/pen.rs index a0ab57ae87..24a21d08ca 100644 --- a/crates/tools/src/pen.rs +++ b/crates/tools/src/pen.rs @@ -449,7 +449,7 @@ impl Tool for PenTool { } vec![Action::Commit] } - PointerKind::DoubleClick => vec![], + PointerKind::DoubleClick | PointerKind::TripleClick => vec![], } } fn key(&mut self, cx: &ToolContext, key: ToolKey, _m: Mods) -> Vec { diff --git a/crates/tools/src/printtiling.rs b/crates/tools/src/printtiling.rs index b4e0e06d0c..a28382daf8 100644 --- a/crates/tools/src/printtiling.rs +++ b/crates/tools/src/printtiling.rs @@ -68,7 +68,7 @@ impl Tool for PrintTilingTool { self.drag = None; vec![Action::Exec("print.tiling.set".into(), json!({ "reset": true }))] } - PointerKind::Move => vec![], + PointerKind::Move | PointerKind::TripleClick => vec![], } } diff --git a/crates/tools/src/text/tool.rs b/crates/tools/src/text/tool.rs index dd561bc616..e18754f0ca 100644 --- a/crates/tools/src/text/tool.rs +++ b/crates/tools/src/text/tool.rs @@ -113,6 +113,7 @@ impl Tool for TypeTool { } vec![] } + PointerKind::TripleClick => vec![], PointerKind::Move => { // The type being edited is no target: its guides would only point at itself. self.snap.hover(cx, ev.pos, self.editing.as_slice(), None); diff --git a/crates/tools/src/touchtype.rs b/crates/tools/src/touchtype.rs index 172487c197..9c16663492 100644 --- a/crates/tools/src/touchtype.rs +++ b/crates/tools/src/touchtype.rs @@ -386,7 +386,7 @@ impl Tool for TouchTypeTool { Some(d) if d.began => vec![Action::Commit], _ => vec![], }, - PointerKind::DoubleClick | PointerKind::Move => vec![], + PointerKind::DoubleClick | PointerKind::TripleClick | PointerKind::Move => vec![], } } diff --git a/crates/tools/src/xform/gradient.rs b/crates/tools/src/xform/gradient.rs index 9c8881b580..44a31b84eb 100644 --- a/crates/tools/src/xform/gradient.rs +++ b/crates/tools/src/xform/gradient.rs @@ -560,7 +560,7 @@ impl Tool for GradientTool { let at = a.stop_point(cx, i).unwrap_or(ev.pos); vec![Self::select_stop(i), Action::Dialog("gradientStop".into(), json!({ "index": i, "x": at.x, "y": at.y }))] } - PointerKind::Move => vec![], + PointerKind::Move | PointerKind::TripleClick => vec![], } } diff --git a/crates/tools/src/xform/transform.rs b/crates/tools/src/xform/transform.rs index 263c0ea5e4..395b235e4a 100644 --- a/crates/tools/src/xform/transform.rs +++ b/crates/tools/src/xform/transform.rs @@ -272,6 +272,7 @@ impl Tool for TransformTool { None => vec![], } } + PointerKind::TripleClick => vec![], PointerKind::Move => { if self.drag.is_none() { self.hover = if cx.selection.is_empty() { vec![] } else { snap_pick(cx, p).1 }; diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index 879f86dd1e..6e9bb90ff4 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -179,6 +179,12 @@ pub(super) fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respo { double_click(app, ui, &f, p); } + if resp.triple_clicked() + && !f.modal + && let Some(p) = at + { + triple_click(app, ui, &f, p); + } if drag.is_some() || pointer.is_moving() || mods_changed { ui.ctx().request_repaint(); } @@ -589,6 +595,23 @@ fn double_click(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, p: Pos2) { } } +/// A triple-click at `p`: the tool gets it, unless it is on an artboard's name. +fn triple_click(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, p: Pos2) { + let Pointing { m, space, xf, view, .. } = *f; + if artboard_name_at(app, ui, &xf, p).is_some() { + return; + } + let ev = PointerEvent { + kind: PointerKind::TripleClick, + pos: xf.to_doc(p), + mods: mods(m, space), + backquote: ui.input(|i| i.key_down(egui::Key::Backtick)), + pressure: 1.0, + pen: None, + }; + dispatch(app, &ev, view); +} + /// Where `button` went up in this frame, if it did. fn release_pos(ui: &Ui, button: egui::PointerButton) -> Option { ui.input(|i| { diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 1f7f715fc4..50499af278 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -9,7 +9,7 @@ //! - `ui.menu.list`: flattened menu tree //! - `ui.contextMenu.list`: the canvas context menu for the current selection, flattened //! - `ui.tool.select {tool}`, `ui.tool.list` -//! - `ui.pointer {events:[{kind: down|drag|up|move|doubleclick, x, y, backquote?, space?: "doc"|"screen"}], mods?, backquote?}`: +//! - `ui.pointer {events:[{kind: down|drag|up|move|doubleclick|tripleclick, x, y, backquote?, space?: "doc"|"screen"}], mods?, backquote?}`: //! drive the active tool through the same path as the mouse, after the synthetic input sent //! before it was applied //! - `ui.key {key, shift?, alt?, cmd?}` / `ui.text {text}`: synthetic keyboard input @@ -1799,7 +1799,7 @@ fn rotate_view_pointer( PointerKind::Up => { app.control_rotate_press = None; } - PointerKind::Move | PointerKind::DoubleClick => {} + PointerKind::Move | PointerKind::DoubleClick | PointerKind::TripleClick => {} } Ok(()) } @@ -1867,6 +1867,7 @@ fn pointer_events_inner(app: &mut VectorcraftApp, ctx: &egui::Context, req: &Con "up" => PointerKind::Up, "move" => PointerKind::Move, "doubleclick" | "dblclick" => PointerKind::DoubleClick, + "tripleclick" => PointerKind::TripleClick, other => return Err(format!("unknown pointer kind `{other}`")), }; PointerEvent::json_check(e)?; diff --git a/docs/control-protocol.md b/docs/control-protocol.md index c2d4c39b06..6f9a0ebe32 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -96,7 +96,7 @@ the two can still win that race. | `ui.menu.list` / `ui.menu.invoke` | `{command, params}` | the full menu tree / invoke an item | | `ui.contextMenu.list` | | the canvas context menu for the current selection, flattened like `ui.menu.list` (`path` holds its submenus). `ui.click {x, y, button: "right"}` on the canvas opens it, after selecting the object there unless it is already selected. With the Artboard tool it lists the artboard entries (see `docs/mcp.md`), after selecting the artboard there unless it is already selected. While a menu opened over locked objects is open, it has an `Unlock` submenu with one item for each locked object under the pointer, topmost first and at most 20, labeled with the object's name, which runs `layer.setProps {ids: [id], locked: false}`. A locked group gets one item, and the locked objects inside it get none. Hidden objects, objects on hidden, locked or template layers, and in isolation mode objects outside the isolated group get no item | | `ui.tool.select` / `ui.tool.list` | `{tool}` | | -| `ui.pointer` | `{events:[{kind: down|drag|up|move|doubleclick, x, y, space?: "doc"|"screen", mods?}]}` | drive the active tool exactly like the mouse: `mods.cmd` held at a press with any tool but a selection tool drags with the selection tool chosen last (Direct Selection with the Pen until one is), and the release gives the tool back as it was; the reply lists `selection`, `key` (the key object, null without one) and `tool`. With the Shape Builder or the Live Paint Bucket and a selection of more than 128 segments, the app finds the regions off the UI thread, so a `move` replies before the region under the pointer is highlighted, and the highlight shows in the first frame after the regions are found. With the Shape Builder and such a selection, the app also merges off the UI thread: the reply to the events that end a click or drag comes once the merge is applied. A click or drag made before the regions are found does not wait for them; the app records it and makes it once they are found. Until then the canvas keeps drawing, with the touched regions highlighted and the busy pointer. A click or drag sent meanwhile, with `mods.cmd` too, and the Shape Builder's arrow keys are made after the merge in the order sent, and the reply to such a request comes once its events are made and any merge they start is applied; a request of `move` events alone is answered at once. A command that can edit, select, save or redraw the documents (an edit, an undo, a selection, a save or an export, a tool option, another tool, another document, closing, a dialog's preview, a menu item, a command of the app's own such as `ui.recolorDialog`, the proof and separations views, a preference, added fonts) waits for the merge and the input sent before it, and runs after them; queries that only read, such as `document.inspect`, run at once on the document before the merge | +| `ui.pointer` | `{events:[{kind: down|drag|up|move|doubleclick|tripleclick, x, y, space?: "doc"|"screen", mods?}]}` | drive the active tool exactly like the mouse (`doubleclick` follows the second click's `up`, and `tripleclick` the third's): `mods.cmd` held at a press with any tool but a selection tool drags with the selection tool chosen last (Direct Selection with the Pen until one is), and the release gives the tool back as it was; the reply lists `selection`, `key` (the key object, null without one) and `tool`. With the Shape Builder or the Live Paint Bucket and a selection of more than 128 segments, the app finds the regions off the UI thread, so a `move` replies before the region under the pointer is highlighted, and the highlight shows in the first frame after the regions are found. With the Shape Builder and such a selection, the app also merges off the UI thread: the reply to the events that end a click or drag comes once the merge is applied. A click or drag made before the regions are found does not wait for them; the app records it and makes it once they are found. Until then the canvas keeps drawing, with the touched regions highlighted and the busy pointer. A click or drag sent meanwhile, with `mods.cmd` too, and the Shape Builder's arrow keys are made after the merge in the order sent, and the reply to such a request comes once its events are made and any merge they start is applied; a request of `move` events alone is answered at once. A command that can edit, select, save or redraw the documents (an edit, an undo, a selection, a save or an export, a tool option, another tool, another document, closing, a dialog's preview, a menu item, a command of the app's own such as `ui.recolorDialog`, the proof and separations views, a preference, added fonts) waits for the merge and the input sent before it, and runs after them; queries that only read, such as `document.inspect`, run at once on the document before the merge | | `ui.key` / `ui.text` | `{key, shift?, alt?, cmd?}` / `{text}` | synthetic keyboard input | | `ui.move` | `{x, y}` | screen-point pointer move | | `ui.click` / `ui.drag` | `{x, y, button?, count?, shift?, alt?, ctrl?, cmd?}` / `{x, y, toX, toY, steps?, count?, button?, shift?, alt?, ctrl?, cmd?}` | egui pointer input; see synthetic input budgets above | diff --git a/docs/mcp.md b/docs/mcp.md index 66c4cc0cff..fa14520101 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -625,8 +625,8 @@ sampler. | `inspect_document` | `{depth?, childLimit?, ids?, kind?, limit?, offset?}` | Artboards (with `color`, `#rrggbb`, for one with a background color), layer tree (ids, kinds, bounds, paint), selection, history, tool. A type node's `fill`, `stroke` and `strokeWidth` are the paint its characters show (its first run's); fills and strokes of the type object itself come as `objectFill`, `objectStroke` and `objectStrokeWidth`. Paint comes as a label (`"#ff0000"`, `"None"`, `"G1 40% (#ff9999)"` for a swatch at a tint); `paint.proxies` gives it as an object. | | `inspect_ui` | `{}` | UI state. Remote mode only. | | `select_tool` | `{tool}` | `selection`, `directSelection`, `pen`, `rectangle`, `ellipse`, `polygon`, `star`, `lineSegment`, … | -| `pointer_gesture` | `{events:[{kind,x,y,mods?,backquote?,pressure?,tiltX?,tiltY?,rotation?,holdMs?}], tool?, mods?, backquote?}` | `kind` is one of `down`, `drag`, `up`, `move`, `doubleclick`. `backquote` is the held state for each event; the top-level value supplies its default, and a `backquote` that is not a boolean is an error. Events go through the same path as the mouse. Headless, a `move` replies after the tool's highlight under the pointer is ready, including the Shape Builder's and the Live Paint Bucket's regions of a large selection, which the desktop app finds off the UI thread and highlights after the reply. The release of a Shape Builder click or drag over such a selection replies once the merge is applied, headless and in the desktop app, which computes the merge off the UI thread. In the desktop app, a gesture sent before then is made after the merge, and its reply comes once it is made; a command that can edit, select, save or redraw the documents (a preference, the proof and separations views), sent before then, waits for the merge and runs after it. | -| `pointer_gesture` | `{events:[{kind,x,y,mods?,backquote?,pressure?,tiltX?,tiltY?,rotation?,holdMs?}], tool?, mods?, backquote?}` | `kind` is one of `down`, `drag`, `up`, `move`, `doubleclick`. `backquote` is the held state for each event; the top-level value supplies its default. Events go through the same path as the mouse. Headless, a `move` replies after the tool's highlight under the pointer is ready, including the Shape Builder's and the Live Paint Bucket's regions of a large selection, which the desktop app finds off the UI thread and highlights after the reply. Remote, the events wait until the keys and other input sent before them (`press_key`, `type_text`) have reached the app, so a key pressed between two calls of one drag applies before the release. When that input is dropped because the document, a dialog or the focus changed first, the call fails and its events are not sent. The release of a Shape Builder click or drag over such a selection replies once the merge is applied, headless and in the desktop app, which computes the merge off the UI thread. In the desktop app, a gesture sent before then is made after the merge, and its reply comes once it is made; a command that can edit, select, save or redraw the documents (a preference, the proof and separations views), sent before then, waits for the merge and runs after it. | +| `pointer_gesture` | `{events:[{kind,x,y,mods?,backquote?,pressure?,tiltX?,tiltY?,rotation?,holdMs?}], tool?, mods?, backquote?}` | `kind` is one of `down`, `drag`, `up`, `move`, `doubleclick`, `tripleclick` (`doubleclick` follows the second click's `up`, and `tripleclick` the third's). `backquote` is the held state for each event; the top-level value supplies its default, and a `backquote` that is not a boolean is an error. Events go through the same path as the mouse. Headless, a `move` replies after the tool's highlight under the pointer is ready, including the Shape Builder's and the Live Paint Bucket's regions of a large selection, which the desktop app finds off the UI thread and highlights after the reply. The release of a Shape Builder click or drag over such a selection replies once the merge is applied, headless and in the desktop app, which computes the merge off the UI thread. In the desktop app, a gesture sent before then is made after the merge, and its reply comes once it is made; a command that can edit, select, save or redraw the documents (a preference, the proof and separations views), sent before then, waits for the merge and runs after it. | +| `pointer_gesture` | `{events:[{kind,x,y,mods?,backquote?,pressure?,tiltX?,tiltY?,rotation?,holdMs?}], tool?, mods?, backquote?}` | `kind` is one of `down`, `drag`, `up`, `move`, `doubleclick`, `tripleclick` (`doubleclick` follows the second click's `up`, and `tripleclick` the third's). `backquote` is the held state for each event; the top-level value supplies its default. Events go through the same path as the mouse. Headless, a `move` replies after the tool's highlight under the pointer is ready, including the Shape Builder's and the Live Paint Bucket's regions of a large selection, which the desktop app finds off the UI thread and highlights after the reply. Remote, the events wait until the keys and other input sent before them (`press_key`, `type_text`) have reached the app, so a key pressed between two calls of one drag applies before the release. When that input is dropped because the document, a dialog or the focus changed first, the call fails and its events are not sent. The release of a Shape Builder click or drag over such a selection replies once the merge is applied, headless and in the desktop app, which computes the merge off the UI thread. In the desktop app, a gesture sent before then is made after the merge, and its reply comes once it is made; a command that can edit, select, save or redraw the documents (a preference, the proof and separations views), sent before then, waits for the merge and runs after it. | | `draw_path` | `{points \| d, closed?, fill?, stroke?, strokeWidth?, dash?, cap?, join?, opacity?, name?, effects?}` | `points` is `[[x,y],…]` or `[{x,y,in?,out?,smooth?},…]`. `d` is SVG path data. The options are below. | | `draw_shape` | `{shape, …geometry, fill?, stroke?, strokeWidth?, dash?, cap?, join?, opacity?, name?, effects?}` | `rectangle`/`ellipse`: `x,y,width,height` (plus `radius` for corners). `polygon`: `cx,cy,radius,sides`. `star`: `cx,cy,radius1,radius2,points`. Polygons and stars take `rotation` in degrees clockwise (0: a corner or point straight up). `line`: `x1,y1,x2,y2`. | | `set_paint` | `{fill?, stroke?, strokeWidth?, ids?}` | Applies to the selection (or `ids`) and becomes the default for new art. Returns `{applied, objects}`: `objects` is the number of objects painted, as the `objects` of the `paint.setFill`, `paint.setStroke` and `stroke.set` replies (the largest of them): a selected group counts the objects inside it. When it is 0, a `note` says that only the paint for new art changed. | @@ -3463,6 +3463,22 @@ already walks Image Trace. Short agent entry points: `livePaint.strokeEdge` when an edge is within 4 screen pixels of the pointer and `livePaint.fill` otherwise, and Shift-click runs `livePaint.fill`. With both off, a click runs nothing. With `highlight` off, the face or edge under the pointer is not outlined. + A double-click runs the command a click there runs with `scope: "connected"`, and a triple-click with + `scope: "samePaint"`; Alt held runs nothing. On a face, `connected` fills the face and every face reached from it + across edges that draw no stroke (hidden, stroke paint none, or weight 0); a stroked edge, a hidden face, a gap + that Gap Detection closes and the group's outside stop it. `samePaint` fills every face + of the group, joined to it or not, whose fill is the `match` paint. On an edge, `connected` paints the edge and the + edges joined to it end to end whose stroke paint is `match`, and `samePaint` paints every edge of the group with + that stroke paint; the stroke's weight is not compared. Each click of a double-click or triple-click runs as it + arrives and is its own undo step. `match` is the paint the face or edge had before the first of the double-click's + two clicks or the triple-click's three, so the clicks before the last do not change what it matches. Hidden faces and edges are not painted. These rules + for what faces and edges join and what paints match are VectorCraft's own. The help page describes the gestures: + https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html. + `livePaint.fill {scope}` and `livePaint.strokeEdge {scope}` take `scope` as `"one"` (the default), `"connected"` or + `"samePaint"`; any other value is an error and changes nothing. `match` is a paint in the model JSON that + `document.node {id}` writes for an appearance's paints (`{"type": "none"}` for none), taken only with a scope that compares paints, and + defaults to the face's fill or the edge's stroke paint. `livePaint.fill` refuses a `scope` other than `"one"` with + `points`. Both replies add `count`, the number of faces or edges painted. `livePaint.merge` keeps the bottom Live Paint group's id, name, lock, visibility, transparency, appearance, opacity mask and graphic style link. With a Live Paint group among the objects, `livePaint.make` adds the others to it as `livePaint.merge` does, and so does `livePaint.fill {ids}` when `point` is outside that group's faces. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 9a9b0d06ed..342b853c02 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1406,6 +1406,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Object › Live Paint › Merge adds the other selected paths and Live Paint groups to the bottom selected Live Paint group ([Live Paint groups](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/live-paint-groups.html)), which keeps its id, the paint of its faces and edges, and its name, lock, visibility, transparency, appearance, opacity mask and graphic style link. Object › Live Paint › Make with a Live Paint group selected, and a Live Paint Bucket click on a selected path beside a selected Live Paint group, add the paths to that group the same way. Make, Merge and the Live Paint Bucket take paths, compound paths and groups of them; with type, an image or another object among the selection they report that it has to be converted to paths first and change nothing, as type and raster images can't go into a Live Paint group directly ([Create Live Paint groups](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/create-live-paint-groups.html)); before, such an object went among the group's hidden sources and vanished from the canvas. Evidence: `tests_build::live_paint_refuses_type_and_images_and_changes_nothing`. With the Live Paint Bucket selected, Alt-click on vector art samples its fill, stroke and stroke weight into the paint defaults ([Paint with the Live Paint Bucket tool](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html)). On a placed image it samples the image pixel as a solid fill with no stroke. Alt+Shift-click samples only the color under the pointer, including an intermediate gradient color or image pixels, into the active fill or stroke ([Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). Neither click paints or changes the selection or selected art, and the next Bucket click paints with the sampled paint. Evidence: `tests_build::live_paint_bucket_alt_sample_paints_next_face_without_changing_selection`. Double-clicking the Live Paint Bucket opens Live Paint Bucket Options ([Paint with the Live Paint Bucket tool](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html)): Paint Fills (on) and Paint Strokes (off) set whether a click paints faces, edges or both, Highlight turns the outline of the face or edge under the pointer on or off, and Color and Width set it (red and 4 px by default). Faces are outlined at the Width and edges at half of it, as the page says faces are highlighted with a thick line and edges with a thin line. With both on, a click paints the edge within 4 px of the pointer, else the face, and Shift switches to Paint Fills only; with one on, Shift switches to the other. The options last across tool switches and are saved with the preferences (`tool.setOption {tool: "livePaintBucket"}`). Evidence: `builder::tests::{bucket_options_choose_what_a_click_paints, bucket_options_set_the_highlight, bucket_highlights_an_edge_thinner_than_a_face}`, `dialogs::live_paint_bucket::tests::double_clicking_the_tool_opens_its_options_and_ok_sets_them`. + Live Paint Bucket double-click and triple-click, as [the help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html) describes them: a double-click on a face fills it and the faces reached across edges that draw no stroke, and on an edge it paints the edges joined to it with the same stroke; a triple-click fills every face of the group with the face's fill, or paints every edge with the edge's stroke (`livePaint.fill` and `livePaint.strokeEdge` `{scope: "connected" | "samePaint", match?}`; `pointer_gesture` and `ui.pointer` take `tripleclick`). Each click paints as it arrives, as its own undo step, and the paint compared is the one the face or edge had before the first of its clicks. Which faces and edges join and which paints match are VectorCraft's own rules. Evidence: `tests_build::{live_paint_bucket_double_click_floods_across_unstroked_edges, live_paint_bucket_double_click_floods_curved_and_narrow_faces, live_paint_bucket_double_click_floods_across_hidden_edges_and_past_gaps, live_paint_bucket_triple_click_fills_every_face_of_the_same_fill, live_paint_bucket_triple_click_after_making_the_group_matches_the_made_fill, live_paint_bucket_double_and_triple_click_paint_joined_and_same_stroke_edges, live_paint_scope_and_match_are_checked}`, `builder::tests::bucket_double_and_triple_click_widen_what_a_click_paints`, `tests::livepaint::a_triple_click_fills_every_face_of_the_same_fill` (MCP). Live Paint Make preserves the front-most covering source's fill when compound paths share a curved boundary, and Expand keeps the face fills. Regression evidence: `planar::tests::coincident_curves_keep_their_source_faces` checks source order, winding, fill rules and nearby boundaries; `tests::build::live_paint_make_and_expand_keep_abutting_compound_colors` checks native compound paths, Make, Expand and Undo/Redo. This preserves VectorCraft's source-fill rule without changing arrangement precision. Live Paint Gap Options (Object › Live Paint › Gap Options…, `livePaint.gapOptions`): with Gap Detection on, paint stops at the gaps that run from a loose end of a path to the nearest path, up to Small (3 pt), Medium (6 pt), Large (12 pt) or a custom size; Close Gaps With Paths adds an unpainted path across each gap; Preview applies the options live and draws the gaps in the Gap Preview Color. The options are saved, copied and undone with the group, and Merge keeps the bottom group's options when its Gap Detection is on, or else turns Gap Detection on with Small when another merged group has it on. When Gap Detection is off in every merged group, it stays off. View › Show Live Paint Gaps (`view.livePaintGaps`) draws the gaps of the selected Live Paint groups up to their Paint Stops At size, each in its group's Gap Preview Color, until Hide Live Paint Gaps or Hide Edges hides them ([Live Paint gaps](https://web.archive.org/web/20260105111201/https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/find-and-close-gaps-in-live-paint-groups.html)). From d84e81aec4755480eba5c241eb0f894bd5a26896 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 16:15:22 -0800 Subject: [PATCH 03/47] Live Paint: params text names its parameter on every line livePaint.fill's description listed "not with points" as its own entry, which the params parser reads as a parameter name, so every_description_parses failed. The note now sits inside the samePaint value's parentheses and says that "connected" and "samePaint" are refused with points, as lp_fill does. --- crates/engine/src/cmd/buildcmds.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 790d54214b..e0f952e754 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -117,7 +117,7 @@ pub fn specs() -> Vec { "Live Paint Bucket", [], None, - "{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], points?: [[x,y]…] (a drag polyline starting at point; 1 to 4096 finite canvas points; fills every crossed face of the same group), continuation?: [[[x,y]…]…] (further path chunks of 1 to 4096 finite canvas points each; each starts at the preceding chunk's last point; requires points), scope?: \"one\" (default: the face alone) | \"connected\" (a double-click: also each face reached across edges that are hidden or draw no stroke, as a flood from the face; a stroked edge, a hidden face or a Gap Detection gap stops it) | \"samePaint\" (a triple-click: also every face of the group whose fill is match), not with points, match?: paint (as the document stores it, the `fill` of a face's appearance; scope samePaint only; default: the face's fill), color?|swatch?|gradient?|none? (default: current fill; a color in #rrggbbaa or #rgba is refused), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces → {group, face, count (faces filled)}", + "{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], points?: [[x,y]…] (a drag polyline starting at point; 1 to 4096 finite canvas points; fills every crossed face of the same group), continuation?: [[[x,y]…]…] (further path chunks of 1 to 4096 finite canvas points each; each starts at the preceding chunk's last point; requires points), scope?: \"one\" (default: the face alone) | \"connected\" (a double-click: also each face reached across edges that are hidden or draw no stroke, as a flood from the face; a stroked edge, a hidden face or a Gap Detection gap stops it) | \"samePaint\" (a triple-click: also every face of the group whose fill is match; \"connected\" and \"samePaint\" are refused with points), match?: paint (as the document stores it, the `fill` of a face's appearance; scope samePaint only; default: the face's fill), color?|swatch?|gradient?|none? (default: current fill; a color in #rrggbbaa or #rgba is refused), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces → {group, face, count (faces filled)}", has_doc, lp_fill ), From 52aec70e19839251fca20818b8bfeb374f4108a4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 17:05:06 -0800 Subject: [PATCH 04/47] Live Paint: double-click floods along split edges, triple-click on new art skips open paths - A face outline segment that runs along several edge segments (the face has no corner where a crossing line splits the edge) now joins the face to every edge segment it runs along, not only the one under its middle, so a double-click flood no longer stops there. - The first click of a triple-click on selected paths, which makes the Live Paint group, takes the fill to match from the paths' closed subpaths only, as the group's faces do; an open path in front no longer gives the wrong fill. --- crates/engine/src/cmd/buildcmds/live_paint.rs | 74 +++++++++++++------ crates/engine/src/tests/build.rs | 30 ++++++++ crates/tools/src/builder/live_paint.rs | 14 ++-- crates/tools/src/builder/tests.rs | 38 ++++++++++ 4 files changed, 128 insertions(+), 28 deletions(-) diff --git a/crates/engine/src/cmd/buildcmds/live_paint.rs b/crates/engine/src/cmd/buildcmds/live_paint.rs index faeaa20cbc..073b0f8bd5 100644 --- a/crates/engine/src/cmd/buildcmds/live_paint.rs +++ b/crates/engine/src/cmd/buildcmds/live_paint.rs @@ -330,12 +330,13 @@ fn lp_segments(pd: &PathData) -> Vec { /// The faces of Live Paint group `group` that a flood from face `start` reaches: `start`, and each /// face that shares with a face already reached an edge that is hidden or draws no stroke /// ([`unstroked`]). Hidden faces are not reached and do not pass the flood on. A face runs along an -/// edge where a segment of its outline has its middle within [`LP_JOIN_TOL`] of one of the edge's -/// segments, over the part of that segment between its outline segment's ends; two faces share the -/// edge where those parts overlap along more than [`LP_JOIN_TOL`], so two faces that a Gap -/// Detection gap parts on the same side of an edge, whose parts only touch, do not. +/// edge segment over the part of it between the points nearest the ends of one of the face's +/// outline segments, when that part lies within [`LP_JOIN_TOL`] of the outline segment; one outline +/// segment can run along several edge segments. Two faces share the edge where those parts overlap +/// along more than [`LP_JOIN_TOL`], so two faces that a Gap Detection gap parts on the same side of +/// an edge, whose parts only touch, do not. fn flood_faces(group: &Node, start: NodeId) -> Vec { - use kurbo::{ParamCurve, ParamCurveArclen, ParamCurveNearest}; + use kurbo::{ParamCurve, ParamCurveArclen, ParamCurveExtrema, ParamCurveNearest}; // Each edge segment, and whether a flood crosses it. let edges: Vec<(kurbo::CubicBez, bool)> = b::edges(group) .into_iter() @@ -351,16 +352,13 @@ fn flood_faces(group: &Node, start: NodeId) -> Vec { } // The faces along each edge segment a flood crosses, each with the part of the segment it runs // along (from and to, in the segment's own parameter). A face outline segment is usually an - // edge segment, with the same middle; one that is not (a piece of an edge segment where a Gap - // Detection line meets it, or the line itself) is measured against the edge segments near it. + // edge segment, with the same ends; one that is not (a piece of an edge segment where a Gap + // Detection line meets it, the line itself, or a run along several edge segments where the + // face has no corner at the points that split them) is measured against the edge segments + // near it. let mut along: std::collections::HashMap> = std::collections::HashMap::new(); - let mut add = |k: usize, id: NodeId, piece: &kurbo::CubicBez| { - if let Some((s, true)) = edges.get(k) { - let (a, c) = (s.nearest(piece.p0, 1e-9).t, s.nearest(piece.p3, 1e-9).t); - along.entry(k).or_default().push((id, a.min(c), a.max(c))); - } - }; let mut pieces: Vec<(kurbo::CubicBez, NodeId)> = vec![]; + let near = |p: Point, q: Point| (p - q).hypot() <= LP_JOIN_TOL; for f in b::faces(group).into_iter().filter(|f| f.visible) { for piece in f.path_data().map(lp_segments).unwrap_or_default() { let m = piece.eval(0.5); @@ -368,9 +366,18 @@ fn flood_faces(group: &Node, start: NodeId) -> Vec { let same = (-1..=1) .flat_map(|dx| (-1..=1).map(move |dy| (x.saturating_add(dx), y.saturating_add(dy)))) .flat_map(|c| mids.get(&c).map(Vec::as_slice).unwrap_or_default()) - .find(|(q, _)| (*q - m).hypot() <= LP_JOIN_TOL); + .find(|&&(q, k)| { + near(q, m) + && edges + .get(k) + .is_some_and(|(s, _)| (near(s.p0, piece.p0) && near(s.p3, piece.p3)) || (near(s.p0, piece.p3) && near(s.p3, piece.p0))) + }); match same { - Some(&(_, k)) => add(k, f.id, &piece), + Some(&(_, k)) => { + if edges.get(k).is_some_and(|e| e.1) { + along.entry(k).or_default().push((f.id, 0.0, 1.0)); + } + } None => pieces.push((piece, f.id)), } } @@ -378,10 +385,15 @@ fn flood_faces(group: &Node, start: NodeId) -> Vec { if !pieces.is_empty() { let grid = LpEdgeGrid::new(&edges); for (piece, id) in pieces { - let m = piece.eval(0.5); - for k in grid.near(m) { - if edges.get(k).is_some_and(|(s, cross)| *cross && s.nearest(m, 1e-9).distance_sq.sqrt() <= LP_JOIN_TOL) { - add(k, id, &piece); + for k in grid.near_rect(piece.bounding_box()) { + let Some((s, true)) = edges.get(k) else { continue }; + let (a, c) = (s.nearest(piece.p0, 1e-9).t, s.nearest(piece.p3, 1e-9).t); + let (from, to) = (a.min(c), a.max(c)); + // The part of the edge segment between the piece's ends runs along the piece. + let on_piece = + [0.25, 0.5, 0.75].iter().all(|u| piece.nearest(s.eval(from + (to - from) * u), 1e-9).distance_sq.sqrt() <= LP_JOIN_TOL); + if from < to && on_piece { + along.entry(k).or_default().push((id, from, to)); } } } @@ -464,9 +476,27 @@ impl LpEdgeGrid { (at(p.x, self.origin.x), at(p.y, self.origin.y)) } - /// The segments whose widened bounds may hold `p`. - fn near(&self, p: Point) -> impl Iterator + '_ { - self.wide.iter().chain(self.cells.get(&self.cell_of(p)).into_iter().flatten()).copied() + /// The segments whose widened bounds may meet `r`, each once. + fn near_rect(&self, r: Rect) -> Vec { + let ((x0, y0), (x1, y1)) = (self.cell_of(Point::new(r.x0, r.y0)), self.cell_of(Point::new(r.x1, r.y1))); + let mut out = self.wide.clone(); + if (x1 - x0 + 1).saturating_mul(y1 - y0 + 1) > self.cells.len() as i64 { + // More cells than the grid fills: walk the filled ones. + for (&(x, y), ks) in &self.cells { + if (x0..=x1).contains(&x) && (y0..=y1).contains(&y) { + out.extend_from_slice(ks); + } + } + } else { + for x in x0..=x1 { + for y in y0..=y1 { + out.extend(self.cells.get(&(x, y)).into_iter().flatten()); + } + } + } + out.sort_unstable(); + out.dedup(); + out } } diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index c0fbd5efe0..582371ca6f 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -2715,6 +2715,36 @@ fn live_paint_bucket_double_click_floods_across_hidden_edges_and_past_gaps() { assert_eq!(fill(&mut s, g, [125.0, 50.0]), 1, "the gap parts the two faces along the bottom"); } +/// The flood crosses an edge into each face along it when a face's outline runs along the edge in +/// one segment and the edge is split where another line meets it. +#[test] +fn live_paint_bucket_double_click_floods_along_edges_split_at_a_junction() { + // A square with a line across its middle, and a line from the top at x = 30 that crosses it and + // stops 20 pt below. The bottom face's outline runs along the middle line in one segment, from + // x = 0 to 100; the middle line's edges are split at x = 30. + let mut s = session(); + let mut ids = vec![rect(&mut s, 0.0, 0.0, 100.0, 100.0).0]; + for anchors in [json!([{"x": 0, "y": 50}, {"x": 100, "y": 50}]), json!([{"x": 30, "y": 0}, {"x": 30, "y": 70}])] { + ids.push(s.execute("path.create", &json!({ "anchors": anchors })).unwrap()["id"].as_u64().unwrap()); + } + s.execute("select.set", &json!({"ids": ids})).unwrap(); + let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let [left, right, bottom] = faces_at(&s, g, &[(15.0, 25.0), (65.0, 25.0), (65.0, 75.0)])[..] else { panic!("three faces") }; + assert!(left != right && right != bottom && left != bottom); + let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 101.0, 101.0)); + paint_parts(&mut s, &all, &Paint::None, &[]); + let down = edges_in(&s, g, Rect::new(30.0, 0.0, 30.0, 70.0)); + assert!(!down.is_empty() && down.len() < all.len()); + paint_parts(&mut s, &down, &Paint::solid(Color::rgb(0.0, 0.0, 0.0)), &[]); + let green = Paint::solid(Color::from_hex("#00ff00").unwrap()); + let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [65, 75], "color": "#00ff00", "scope": "connected"})).unwrap(); + assert_eq!(r["count"], 3, "from the bottom face to both faces above the line"); + assert_eq!([left, right, bottom].map(|f| fill_of(&s, f)), [green.clone(), green.clone(), green.clone()]); + s.execute("edit.undo", &json!({})).unwrap(); + let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [15, 25], "color": "#00ff00", "scope": "connected"})).unwrap(); + assert_eq!(r["count"], 3, "from the upper left face down to the bottom face and up again"); +} + /// A triple-click on a face fills every face of the group with that face's fill, joined to it or /// not. Through the tool, the fill compared is the face's fill before the first click. #[test] diff --git a/crates/tools/src/builder/live_paint.rs b/crates/tools/src/builder/live_paint.rs index 5b6bb3a5b8..a6a6af0915 100644 --- a/crates/tools/src/builder/live_paint.rs +++ b/crates/tools/src/builder/live_paint.rs @@ -207,17 +207,19 @@ struct LpPress { } /// The fill of the face under `p` in the Live Paint group that `roots` make: the fill of the -/// front-most of their paths whose outline holds `p`, else none. +/// front-most of their paths whose closed subpaths hold `p`, else none. Open subpaths bound no face. fn made_face_fill(doc: &Document, roots: &[NodeId], p: Point) -> Paint { let mut leaves = vec![]; for n in roots.iter().filter_map(|id| doc.node(*id)) { leaf_shapes(n, &mut leaves); } - leaves - .iter() - .rev() - .find(|l| node_outline(l).is_some_and(|(path, rule)| !path.is_empty() && path_contains(&path, rule, p))) - .map_or(Paint::None, |l| l.appearance.fill_paint()) + let holds = |l: &Node| { + node_outline(l).is_some_and(|(path, rule)| { + let closed = vectorcraft_geom::PathData::new(path.subpaths.into_iter().filter(|sp| sp.closed && sp.anchors.len() >= 2).collect()); + !closed.is_empty() && path_contains(&closed, rule, p) + }) + }; + leaves.iter().rev().find(|l| holds(l)).map_or(Paint::None, |l| l.appearance.fill_paint()) } /// How many presses the Live Paint Bucket keeps: the three of a triple-click. diff --git a/crates/tools/src/builder/tests.rs b/crates/tools/src/builder/tests.rs index e6bfbee7f4..80a2dbd7a4 100644 --- a/crates/tools/src/builder/tests.rs +++ b/crates/tools/src/builder/tests.rs @@ -1159,6 +1159,44 @@ fn bucket_double_and_triple_click_widen_what_a_click_paints() { assert!(t.pointer(&cx, &ev(PointerKind::DoubleClick, 400.0, 400.0)).is_empty()); } +/// A triple-click whose first click makes the Live Paint group matches the fill of the face the +/// group makes there: an open path in front, whose outline bounds no face, does not give it. +#[test] +fn bucket_triple_click_on_a_made_group_skips_open_paths() { + use vectorcraft_color::{Color, Paint}; + use vectorcraft_geom::{PathData, SubPath}; + let (red, blue) = (Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0))); + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let back = d.alloc_id(); + let mut look = Appearance::default_art(); + look.set_fill(red.clone()); + d.insert(Some(l), 0, Node::path(back, shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), look)).unwrap(); + // An open U around (75, 25), filled blue. + let u = [Point::new(60.0, 5.0), Point::new(60.0, 45.0), Point::new(90.0, 45.0), Point::new(90.0, 5.0)]; + let front = d.alloc_id(); + let mut look = Appearance::default_art(); + look.set_fill(blue); + d.insert(Some(l), 1, Node::path(front, PathData::single(SubPath::polyline(&u, false)), look)).unwrap(); + let mut s = Selection::default(); + s.set([back, front]); + let p = paint(); + let (made, ..) = live_group_doc(); + let none = Selection::default(); + let (cx, later) = (cx(&d, &s, &p), cx(&made, &none, &p)); + let mut t = LivePaintBucketTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, 75.0, 25.0)); + t.pointer(&cx, &ev(PointerKind::Up, 75.0, 25.0)); + for _ in 0..2 { + t.pointer(&later, &ev(PointerKind::Down, 75.0, 25.0)); + t.pointer(&later, &ev(PointerKind::Up, 75.0, 25.0)); + } + let acts = t.pointer(&later, &ev(PointerKind::TripleClick, 75.0, 25.0)); + let [Action::Exec(id, v)] = acts.as_slice() else { panic!("{acts:?}") }; + assert_eq!(id, "livePaint.fill"); + assert_eq!(v["match"], serde_json::to_value(&red).unwrap()); +} + #[test] fn bucket_options_choose_what_a_click_paints() { let (d, gid, ..) = live_group_doc(); From 4dd3809f84aa85dc35e84c42822b07fc384172b5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 17:43:37 -0800 Subject: [PATCH 05/47] Live Paint: triple-click test checks the face the planar map makes The test for a triple-click whose first click makes the group now also builds the planar map from the same two paths and checks that the face at the click takes its fill from the square. The doc comment of the double-click flood names the three points it checks along each edge segment. --- crates/engine/src/cmd/buildcmds/live_paint.rs | 5 +++-- crates/tools/src/builder/tests.rs | 9 +++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/buildcmds/live_paint.rs b/crates/engine/src/cmd/buildcmds/live_paint.rs index 073b0f8bd5..b049f59f0c 100644 --- a/crates/engine/src/cmd/buildcmds/live_paint.rs +++ b/crates/engine/src/cmd/buildcmds/live_paint.rs @@ -331,8 +331,9 @@ fn lp_segments(pd: &PathData) -> Vec { /// face that shares with a face already reached an edge that is hidden or draws no stroke /// ([`unstroked`]). Hidden faces are not reached and do not pass the flood on. A face runs along an /// edge segment over the part of it between the points nearest the ends of one of the face's -/// outline segments, when that part lies within [`LP_JOIN_TOL`] of the outline segment; one outline -/// segment can run along several edge segments. Two faces share the edge where those parts overlap +/// outline segments, when that part's points at a quarter, half and three quarters of its +/// parameter range lie within [`LP_JOIN_TOL`] of the outline segment; one outline segment can run +/// along several edge segments. Two faces share the edge where those parts overlap /// along more than [`LP_JOIN_TOL`], so two faces that a Gap Detection gap parts on the same side of /// an edge, whose parts only touch, do not. fn flood_faces(group: &Node, start: NodeId) -> Vec { diff --git a/crates/tools/src/builder/tests.rs b/crates/tools/src/builder/tests.rs index 80a2dbd7a4..1e22c67b26 100644 --- a/crates/tools/src/builder/tests.rs +++ b/crates/tools/src/builder/tests.rs @@ -1178,6 +1178,15 @@ fn bucket_triple_click_on_a_made_group_skips_open_paths() { let mut look = Appearance::default_art(); look.set_fill(blue); d.insert(Some(l), 1, Node::path(front, PathData::single(SubPath::polyline(&u, false)), look)).unwrap(); + // The face the planar map makes there takes its fill from the square, as the group's would. + let shapes: Vec = [back, front] + .iter() + .enumerate() + .filter_map(|(k, id)| node_outline(d.node(*id)?).map(|(path, rule)| vectorcraft_pathops::Shape::new(path, rule, k as u64))) + .collect(); + let (regions, _) = vectorcraft_pathops::live_paint(&shapes); + let face = regions.iter().find(|r| r.contains(Point::new(75.0, 25.0))).expect("a face at (75, 25)"); + assert_eq!(face.top(), Some(0), "the square is the face's top shape"); let mut s = Selection::default(); s.set([back, front]); let p = paint(); From f59381ab59d5cc9072cecc26581484c1a9109abb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 18:19:05 -0800 Subject: [PATCH 06/47] Live Paint: a triple-click matches the paint of the face its last clicks painted A double-click or triple-click compares the paint the face or edge had before the first of its last clicks that painted it. A first click that made the Live Paint group counts only when the face it filled is that face, so clicks that move from one face to another no longer match the paint under the first click. With Space held for the view tools, a press, a double-click or a triple-click with the Live Paint Bucket paints nothing. The ui.pointer row in docs/control-protocol.md escapes the pipes in its parameters cell, so the table keeps three columns. --- crates/tools/src/builder/live_paint.rs | 46 +++++++++++++++--------- crates/tools/src/builder/tests.rs | 50 +++++++++++++++++++++++++- docs/control-protocol.md | 2 +- docs/mcp.md | 5 +-- docs/target-app-parity.md | 2 +- 5 files changed, 83 insertions(+), 22 deletions(-) diff --git a/crates/tools/src/builder/live_paint.rs b/crates/tools/src/builder/live_paint.rs index 8e3dc0d58a..ff59b22333 100644 --- a/crates/tools/src/builder/live_paint.rs +++ b/crates/tools/src/builder/live_paint.rs @@ -179,7 +179,8 @@ enum LpPaint { /// paints every edge of the group with the edge's stroke (`scope: "samePaint"`). Each click of a /// double-click or triple-click paints as it arrives, as its own undo step, and the paint compared /// is the one the face or edge had before the first of its clicks. Shift and the options choose a -/// face or an edge as for a click; with Alt held a double-click or triple-click paints nothing. +/// face or an edge as for a click; with Alt held a double-click or triple-click paints nothing. With +/// Space held for the view tools, a click, double-click or triple-click paints nothing. pub struct LivePaintBucketTool { pub(super) cache: RegionCache, pub(super) hover: LpHover, @@ -202,6 +203,8 @@ pub struct LivePaintBucketTool { struct LpPress { /// The face or edge; None for the face of the Live Paint group the press makes. part: Option, + /// Where the press was. + at: Point, /// Its fill (a face) or stroke paint (an edge) before the press. before: Paint, } @@ -295,20 +298,23 @@ impl LivePaintBucketTool { self.presses.push(press); } - /// Note a press that paints face or edge (`edge`) `n`. - fn note_part(&mut self, n: &Node, edge: bool) { + /// Note a press at `at` that paints face or edge (`edge`) `n`. + fn note_part(&mut self, n: &Node, edge: bool, at: Point) { let before = if edge { n.appearance.stroke_paint() } else { n.appearance.fill_paint() }; - self.note_press(Some(LpPress { part: Some(n.id), before })); + self.note_press(Some(LpPress { part: Some(n.id), at, before })); } - /// The paint `part` had before the first press of a click sequence of `clicks` presses, when - /// those presses all painted `part` (the first may have made the group `part` is in); else - /// `now`. - fn before(&self, part: NodeId, clicks: usize, now: Paint) -> Paint { + /// The paint `part` had before the first of the last presses of a click sequence of `clicks` + /// presses that all painted `part` (the sequence's first press may have made the group `part` + /// is in, when the face it filled there is `part`); `now` when the last press did not paint it. + fn before(&self, cx: &ToolContext, part: NodeId, clicks: usize, now: Paint) -> Paint { let Some(run) = self.presses.len().checked_sub(clicks).and_then(|from| self.presses.get(from..)) else { return now }; - let on_part = |(i, q): (usize, &Option)| q.as_ref().is_some_and(|q| q.part == Some(part) || (i == 0 && q.part.is_none())); - match run.first() { - Some(Some(first)) if run.iter().enumerate().all(on_part) => first.before.clone(), + let made_part = |q: &LpPress| live_paint_at(cx.doc, q.at).and_then(|g| visible_face_at(cx.doc.node(g)?, q.at)).is_some_and(|f| f.id == part); + let on_part = + |(i, q): (usize, &Option)| q.as_ref().is_some_and(|q| q.part == Some(part) || (i == 0 && q.part.is_none() && made_part(q))); + let from = run.len().saturating_sub(run.iter().enumerate().rev().take_while(|&iq| on_part(iq)).count()); + match run.get(from) { + Some(Some(first)) => first.before.clone(), _ => now, } } @@ -316,7 +322,8 @@ impl LivePaintBucketTool { /// What a double-click (`scope` "connected", 2 `clicks`) or a triple-click ("samePaint", 3) at /// `p` runs: the command a click there runs, with `scope`, and the paint it compares as `match`. fn multi_click(&self, cx: &ToolContext, p: Point, mods: Mods, scope: &str, clicks: usize) -> Vec { - if mods.alt { + // With Space held the press pans, zooms or rotates the view and does not reach the tool. + if mods.alt || mods.space { return vec![]; } let point = json!([p.x, p.y]); @@ -325,7 +332,7 @@ impl LivePaintBucketTool { && let Some((g, Some(e))) = lp_part_at(cx.doc, p, cx.tol(4.0), true, &|id| lp_visible(cx, id)) { let mut v = json!({ "group": g.0, "point": point, "tolerance": cx.tol(4.0), "scope": scope }); - if let Ok(like) = serde_json::to_value(self.before(e.id, clicks, e.appearance.stroke_paint())) { + if let Ok(like) = serde_json::to_value(self.before(cx, e.id, clicks, e.appearance.stroke_paint())) { v["match"] = like; } return vec![Action::Exec("livePaint.strokeEdge".into(), v)]; @@ -336,7 +343,7 @@ impl LivePaintBucketTool { let Some((g, f)) = live_paint_at(cx.doc, p).and_then(|g| Some((g, visible_face_at(cx.doc.node(g)?, p)?))) else { return vec![] }; let mut v = json!({ "group": g.0, "point": point, "scope": scope }); if scope == "samePaint" - && let Ok(like) = serde_json::to_value(self.before(f.id, clicks, f.appearance.fill_paint())) + && let Ok(like) = serde_json::to_value(self.before(cx, f.id, clicks, f.appearance.fill_paint())) { v["match"] = like; } @@ -431,6 +438,11 @@ impl Tool for LivePaintBucketTool { } PointerKind::Down => { self.hover = LpHover::None; + // With Space held the press pans, zooms or rotates the view. + if ev.mods.space { + self.note_press(None); + return vec![]; + } if ev.mods.alt { self.note_press(None); if ev.mods.shift { @@ -459,7 +471,7 @@ impl Tool for LivePaintBucketTool { if matches!(paint, LpPaint::Strokes | LpPaint::Both) && let Some((g, Some(e))) = lp_part_at(cx.doc, p, cx.tol(4.0), true, &|id| lp_visible(cx, id)) { - self.note_part(e, true); + self.note_part(e, true, p); return vec![Action::Exec("livePaint.strokeEdge".into(), json!({ "group": g.0, "point": point, "tolerance": cx.tol(4.0) }))]; } if !matches!(paint, LpPaint::Fills | LpPaint::Both) { @@ -468,14 +480,14 @@ impl Tool for LivePaintBucketTool { } if let Some(g) = live_paint_at(cx.doc, p) { match cx.doc.node(g).and_then(|n| visible_face_at(n, p)) { - Some(f) => self.note_part(f, false), + Some(f) => self.note_part(f, false, p), None => self.note_press(None), } return self.begin_fill(json!({ "group": g.0, "point": point }), p); } if self.cache.at(cx, p).is_some() { let roots = sorted_roots(cx.doc, &cx.selection.objects); - self.note_press(Some(LpPress { part: None, before: made_face_fill(cx.doc, &roots, p) })); + self.note_press(Some(LpPress { part: None, at: p, before: made_face_fill(cx.doc, &roots, p) })); return self.begin_fill(json!({ "ids": json_ids(&roots), "point": point }), p); } self.note_press(None); diff --git a/crates/tools/src/builder/tests.rs b/crates/tools/src/builder/tests.rs index 1e22c67b26..a0811c5071 100644 --- a/crates/tools/src/builder/tests.rs +++ b/crates/tools/src/builder/tests.rs @@ -1145,10 +1145,19 @@ fn bucket_double_and_triple_click_widen_what_a_click_paints() { assert_eq!(t.pointer(&later, &ev(PointerKind::DoubleClick, 51.0, 25.0).with_mods(shift)), stroke("connected", &edge_before)); click(&mut t, &later, 51.0, shift); assert_eq!(t.pointer(&later, &ev(PointerKind::TripleClick, 51.0, 25.0).with_mods(shift)), stroke("samePaint", &edge_before)); - // With Alt held, or with both options off, a double-click or triple-click paints nothing. + // With Alt or Space held, or with both options off, a double-click or triple-click paints nothing. let alt = Mods { alt: true, ..Default::default() }; + let space = Mods { space: true, ..Default::default() }; for k in [PointerKind::DoubleClick, PointerKind::TripleClick] { assert!(t.pointer(&cx, &ev(k, 75.0, 25.0).with_mods(alt)).is_empty(), "{k:?}"); + assert!(t.pointer(&cx, &ev(k, 75.0, 25.0).with_mods(space)).is_empty(), "{k:?} with Space"); + assert!(t.pointer(&cx, &ev(k, 51.0, 25.0).with_mods(Mods { shift: true, ..space })).is_empty(), "{k:?} with Shift and Space"); + } + // A press with Space held paints nothing either. + for m in [space, Mods { shift: true, ..space }] { + for (k, x) in [(PointerKind::Down, 75.0), (PointerKind::Up, 75.0), (PointerKind::Down, 51.0), (PointerKind::Up, 51.0)] { + assert!(t.pointer(&cx, &ev(k, x, 25.0).with_mods(m)).is_empty(), "{k:?} at {x} with {m:?}"); + } } t.set_option("paintFills", &json!(false)); for k in [PointerKind::DoubleClick, PointerKind::TripleClick] { @@ -1206,6 +1215,45 @@ fn bucket_triple_click_on_a_made_group_skips_open_paths() { assert_eq!(v["match"], serde_json::to_value(&red).unwrap()); } +/// A triple-click whose first click makes the Live Paint group on one face and whose other two +/// clicks fill another face matches the fill the second face had before the first click on it, +/// not the fill under the first click or the fill the clicks gave it. +#[test] +fn bucket_triple_click_after_making_the_group_on_another_face_matches_its_own_face() { + use vectorcraft_color::{Color, Paint}; + let (red, blue) = (Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0))); + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let square = d.alloc_id(); + let mut look = Appearance::default_art(); + look.set_fill(red.clone()); + d.insert(Some(l), 0, Node::path(square, shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 50.0)), look)).unwrap(); + let mut s = Selection::default(); + s.set([square]); + let p = paint(); + let (made, _, f2, _) = live_group_doc(); + let mut painted = made.clone(); + painted.node_mut(f2).unwrap().appearance.set_fill(blue.clone()); + let none = Selection::default(); + let (cx, later, after) = (cx(&d, &s, &p), cx(&made, &none, &p), cx(&painted, &none, &p)); + let mut t = LivePaintBucketTool::default(); + // The first click makes the group and fills the face at (25, 25); the next two fill (75, 25), + // the first of them painting it blue. + t.pointer(&cx, &ev(PointerKind::Down, 25.0, 25.0)); + t.pointer(&cx, &ev(PointerKind::Up, 25.0, 25.0)); + for ctx in [&later, &after] { + t.pointer(ctx, &ev(PointerKind::Down, 75.0, 25.0)); + t.pointer(ctx, &ev(PointerKind::Up, 75.0, 25.0)); + } + let acts = t.pointer(&after, &ev(PointerKind::TripleClick, 75.0, 25.0)); + let [Action::Exec(id, v)] = acts.as_slice() else { panic!("{acts:?}") }; + assert_eq!(id, "livePaint.fill"); + let own = serde_json::to_value(made.node(f2).unwrap().appearance.fill_paint()).unwrap(); + assert_ne!(own, serde_json::to_value(&red).unwrap()); + assert_ne!(own, serde_json::to_value(&blue).unwrap()); + assert_eq!(v["match"], own); +} + #[test] fn bucket_options_choose_what_a_click_paints() { let (d, gid, ..) = live_group_doc(); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index b1d100bc57..2696f2408b 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -96,7 +96,7 @@ the two can still win that race. | `ui.menu.list` / `ui.menu.invoke` | `{command, params}` | the full menu tree / invoke an item | | `ui.contextMenu.list` | | the canvas context menu for the current selection, flattened like `ui.menu.list` (`path` holds its submenus). `ui.click {x, y, button: "right"}` on the canvas opens it, after selecting the object there unless it is already selected. With the Artboard tool it lists the artboard entries (see `docs/mcp.md`), after selecting the artboard there unless it is already selected. While a menu opened over locked objects is open, it has an `Unlock` submenu with one item for each locked object under the pointer, topmost first and at most 20, labeled with the object's name, which runs `layer.setProps {ids: [id], locked: false}`. A locked group gets one item, and the locked objects inside it get none. Hidden objects, objects on hidden, locked or template layers, and in isolation mode objects outside the isolated group get no item | | `ui.tool.select` / `ui.tool.list` | `{tool}` | | -| `ui.pointer` | `{events:[{kind: down|drag|up|move|doubleclick|tripleclick, x, y, space?: "doc"|"screen", mods?}]}` | drive the active tool exactly like the mouse (`doubleclick` follows the second click's `up`, and `tripleclick` the third's): `mods.cmd` held at a press with any tool but a selection tool drags with the selection tool chosen last (Direct Selection with the Pen until one is), and the release gives the tool back as it was; the reply lists `selection`, `key` (the key object, null without one) and `tool`. With the Shape Builder or the Live Paint Bucket and a selection of more than 128 segments, the app finds the regions off the UI thread, so a `move` replies before the region under the pointer is highlighted, and the highlight shows in the first frame after the regions are found. With the Shape Builder and such a selection, the app also merges off the UI thread: the reply to the events that end a click or drag comes once the merge is applied. A click or drag made before the regions are found does not wait for them; the app records it and makes it once they are found. Until then the canvas keeps drawing, with the touched regions highlighted and the busy pointer. A click or drag sent meanwhile, with `mods.cmd` too, and the Shape Builder's arrow keys are made after the merge in the order sent, and the reply to such a request comes once its events are made and any merge they start is applied; a request of `move` events alone is answered at once. A command that can edit, select, save or redraw the documents (an edit, an undo, a selection, a save or an export, a tool option, another tool, another document, closing, a dialog's preview, a menu item, a command of the app's own such as `ui.recolorDialog`, the proof and separations views, a preference, added fonts) waits for the merge and the input sent before it, and runs after them; queries that only read, such as `document.inspect`, run at once on the document before the merge | +| `ui.pointer` | `{events:[{kind: down\|drag\|up\|move\|doubleclick\|tripleclick, x, y, space?: "doc"\|"screen", mods?}]}` | drive the active tool exactly like the mouse (`doubleclick` follows the second click's `up`, and `tripleclick` the third's): `mods.cmd` held at a press with any tool but a selection tool drags with the selection tool chosen last (Direct Selection with the Pen until one is), and the release gives the tool back as it was; the reply lists `selection`, `key` (the key object, null without one) and `tool`. With the Shape Builder or the Live Paint Bucket and a selection of more than 128 segments, the app finds the regions off the UI thread, so a `move` replies before the region under the pointer is highlighted, and the highlight shows in the first frame after the regions are found. With the Shape Builder and such a selection, the app also merges off the UI thread: the reply to the events that end a click or drag comes once the merge is applied. A click or drag made before the regions are found does not wait for them; the app records it and makes it once they are found. Until then the canvas keeps drawing, with the touched regions highlighted and the busy pointer. A click or drag sent meanwhile, with `mods.cmd` too, and the Shape Builder's arrow keys are made after the merge in the order sent, and the reply to such a request comes once its events are made and any merge they start is applied; a request of `move` events alone is answered at once. A command that can edit, select, save or redraw the documents (an edit, an undo, a selection, a save or an export, a tool option, another tool, another document, closing, a dialog's preview, a menu item, a command of the app's own such as `ui.recolorDialog`, the proof and separations views, a preference, added fonts) waits for the merge and the input sent before it, and runs after them; queries that only read, such as `document.inspect`, run at once on the document before the merge | | `ui.key` / `ui.text` | `{key, shift?, alt?, cmd?}` / `{text}` | synthetic keyboard input | | `ui.move` | `{x, y}` | screen-point pointer move | | `ui.click` / `ui.drag` | `{x, y, button?, count?, shift?, alt?, ctrl?, cmd?}` / `{x, y, toX, toY, steps?, count?, button?, shift?, alt?, ctrl?, cmd?}` | egui pointer input; see synthetic input budgets above | diff --git a/docs/mcp.md b/docs/mcp.md index dee354486d..9887f22044 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3530,14 +3530,15 @@ already walks Image Trace. Short agent entry points: Shift-click runs `livePaint.fill`. With both off, a click runs nothing. With `highlight` off, the face or edge under the pointer is not outlined. A double-click runs the command a click there runs with `scope: "connected"`, and a triple-click with - `scope: "samePaint"`; Alt held runs nothing. On a face, `connected` fills the face and every face reached from it + `scope: "samePaint"`; Alt held runs nothing. With Space held (`mods.space`, the view tools), a press, a + double-click or a triple-click runs nothing. On a face, `connected` fills the face and every face reached from it across edges that draw no stroke (hidden, stroke paint none, or weight 0); a stroked edge, a hidden face, a gap that Gap Detection closes and the group's outside stop it. `samePaint` fills every face of the group, joined to it or not, whose fill is the `match` paint. On an edge, `connected` paints the edge and the edges joined to it end to end whose stroke paint is `match`, and `samePaint` paints every edge of the group with that stroke paint; the stroke's weight is not compared. Each click of a double-click or triple-click runs as it arrives and is its own undo step. `match` is the paint the face or edge had before the first of the double-click's - two clicks or the triple-click's three, so the clicks before the last do not change what it matches. Hidden faces and edges are not painted. These rules + two clicks or the triple-click's three that painted it, so the clicks before the last do not change what it matches. Hidden faces and edges are not painted. These rules for what faces and edges join and what paints match are VectorCraft's own. The help page describes the gestures: https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html. `livePaint.fill {scope}` and `livePaint.strokeEdge {scope}` take `scope` as `"one"` (the default), `"connected"` or diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 7064ca45b4..f4a7bb708b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1437,7 +1437,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Object › Live Paint › Merge adds the other selected paths and Live Paint groups to the bottom selected Live Paint group ([Live Paint groups](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/live-paint-groups.html)), which keeps its id, the paint of its faces and edges, and its name, lock, visibility, transparency, appearance, opacity mask and graphic style link. Object › Live Paint › Make with a Live Paint group selected, and a Live Paint Bucket click on a selected path beside a selected Live Paint group, add the paths to that group the same way. Make, Merge and the Live Paint Bucket take paths, compound paths and groups of them; with type, an image or another object among the selection they report that it has to be converted to paths first and change nothing, as type and raster images can't go into a Live Paint group directly ([Create Live Paint groups](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/create-live-paint-groups.html)); before, such an object went among the group's hidden sources and vanished from the canvas. Evidence: `tests_build::live_paint_refuses_type_and_images_and_changes_nothing`. With the Live Paint Bucket selected, Alt-click on vector art samples its fill, stroke and stroke weight into the paint defaults ([Paint with the Live Paint Bucket tool](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html)). On a placed image it samples the image pixel as a solid fill with no stroke. Alt+Shift-click samples only the color under the pointer, including an intermediate gradient color or image pixels, into the active fill or stroke ([Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). Neither click paints or changes the selection or selected art, and the next Bucket click paints with the sampled paint. Evidence: `tests_build::live_paint_bucket_alt_sample_paints_next_face_without_changing_selection`. Double-clicking the Live Paint Bucket opens Live Paint Bucket Options ([Paint with the Live Paint Bucket tool](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html)): Paint Fills (on) and Paint Strokes (off) set whether a click paints faces, edges or both, Highlight turns the outline of the face or edge under the pointer on or off, and Color and Width set it (red and 4 px by default). Faces are outlined at the Width and edges at half of it, as the page says faces are highlighted with a thick line and edges with a thin line. With both on, a click paints the edge within 4 px of the pointer, else the face, and Shift switches to Paint Fills only; with one on, Shift switches to the other. The options last across tool switches and are saved with the preferences (`tool.setOption {tool: "livePaintBucket"}`). Evidence: `builder::tests::{bucket_options_choose_what_a_click_paints, bucket_options_set_the_highlight, bucket_highlights_an_edge_thinner_than_a_face}`, `dialogs::live_paint_bucket::tests::double_clicking_the_tool_opens_its_options_and_ok_sets_them`. - Live Paint Bucket double-click and triple-click, as [the help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html) describes them: a double-click on a face fills it and the faces reached across edges that draw no stroke, and on an edge it paints the edges joined to it with the same stroke; a triple-click fills every face of the group with the face's fill, or paints every edge with the edge's stroke (`livePaint.fill` and `livePaint.strokeEdge` `{scope: "connected" | "samePaint", match?}`; `pointer_gesture` and `ui.pointer` take `tripleclick`). Each click paints as it arrives, as its own undo step, and the paint compared is the one the face or edge had before the first of its clicks. Which faces and edges join and which paints match are VectorCraft's own rules. Evidence: `tests_build::{live_paint_bucket_double_click_floods_across_unstroked_edges, live_paint_bucket_double_click_floods_curved_and_narrow_faces, live_paint_bucket_double_click_floods_across_hidden_edges_and_past_gaps, live_paint_bucket_triple_click_fills_every_face_of_the_same_fill, live_paint_bucket_triple_click_after_making_the_group_matches_the_made_fill, live_paint_bucket_double_and_triple_click_paint_joined_and_same_stroke_edges, live_paint_scope_and_match_are_checked}`, `builder::tests::bucket_double_and_triple_click_widen_what_a_click_paints`, `tests::livepaint::a_triple_click_fills_every_face_of_the_same_fill` (MCP). + Live Paint Bucket double-click and triple-click, as [the help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html) describes them: a double-click on a face fills it and the faces reached across edges that draw no stroke, and on an edge it paints the edges joined to it with the same stroke; a triple-click fills every face of the group with the face's fill, or paints every edge with the edge's stroke (`livePaint.fill` and `livePaint.strokeEdge` `{scope: "connected" | "samePaint", match?}`; `pointer_gesture` and `ui.pointer` take `tripleclick`). Each click paints as it arrives, as its own undo step, and the paint compared is the one the face or edge had before the first of its clicks. Which faces and edges join and which paints match are VectorCraft's own rules. Evidence: `tests_build::{live_paint_bucket_double_click_floods_across_unstroked_edges, live_paint_bucket_double_click_floods_curved_and_narrow_faces, live_paint_bucket_double_click_floods_across_hidden_edges_and_past_gaps, live_paint_bucket_triple_click_fills_every_face_of_the_same_fill, live_paint_bucket_triple_click_after_making_the_group_matches_the_made_fill, live_paint_bucket_double_and_triple_click_paint_joined_and_same_stroke_edges, live_paint_scope_and_match_are_checked}`, `builder::tests::{bucket_double_and_triple_click_widen_what_a_click_paints, bucket_triple_click_after_making_the_group_on_another_face_matches_its_own_face}`, `tests::livepaint::a_triple_click_fills_every_face_of_the_same_fill` (MCP). Live Paint Make preserves the front-most covering source's fill when compound paths share a curved boundary, and Expand keeps the face fills. Regression evidence: `planar::tests::coincident_curves_keep_their_source_faces` checks source order, winding, fill rules and nearby boundaries; `tests::build::live_paint_make_and_expand_keep_abutting_compound_colors` checks native compound paths, Make, Expand and Undo/Redo. This preserves VectorCraft's source-fill rule without changing arrangement precision. Live Paint Gap Options (Object › Live Paint › Gap Options…, `livePaint.gapOptions`): with Gap Detection on, paint stops at the gaps that run from a loose end of a path to the nearest path, up to Small (3 pt), Medium (6 pt), Large (12 pt) or a custom size; Close Gaps With Paths adds an unpainted path across each gap; Preview applies the options live and draws the gaps in the Gap Preview Color. The options are saved, copied and undone with the group, and Merge keeps the bottom group's options when its Gap Detection is on, or else turns Gap Detection on with Small when another merged group has it on. When Gap Detection is off in every merged group, it stays off. View › Show Live Paint Gaps (`view.livePaintGaps`) draws the gaps of the selected Live Paint groups up to their Paint Stops At size, each in its group's Gap Preview Color, until Hide Live Paint Gaps or Hide Edges hides them ([Live Paint gaps](https://web.archive.org/web/20260105111201/https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/find-and-close-gaps-in-live-paint-groups.html)). From bc2caaaa37e2ac13e0e88d9264fd600990801c9c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 19:10:40 -0800 Subject: [PATCH 07/47] Live Paint: a triple-click matches the first fill of a face clicked again A triple-click whose clicks land on a face, another face, then the first face again matched the fill the first click gave that face. It now matches the fill the face had before the first click that painted it, as the tool's doc comment and docs/mcp.md say. - With Space held for the view tools, the Live Paint Bucket outlines no face or edge, as a press there paints nothing. - A scoped livePaint.fill or livePaint.strokeEdge where every face or edge reached already has the paint records no undo step; a test covers it, and one where only some faces need the paint. - An MCP test drives the bucket through ui.pointer with mods.space. - The tool's doc comment and the progress line state the rule. --- crates/engine/src/tests/build.rs | 36 +++++++++++++++++++ crates/mcp/src/tests/livepaint.rs | 24 +++++++++++++ crates/tools/src/builder/live_paint.rs | 50 ++++++++++++++------------ crates/tools/src/builder/tests.rs | 45 +++++++++++++++++++++++ docs/mcp.md | 5 +-- docs/target-app-parity.md | 2 +- 6 files changed, 136 insertions(+), 26 deletions(-) diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 299dd78a37..89f0877621 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -2566,6 +2566,42 @@ fn live_paint_stroke_edge_same_paint_and_width_is_no_op() { assert_eq!(history_state(&s).0, before.1.0 + 1); } +/// With `scope`, faces and edges that already have the paint (and the width) are skipped: when +/// every face or edge the call reaches has it, nothing changes, and when some do, only the others +/// are painted, in one undo step. `count` is every face or edge reached. +#[test] +fn live_paint_scoped_fill_and_stroke_skip_parts_with_the_paint() { + let mut s = session(); + let g = live(&mut s); + s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 50], "points": [[25, 50], [125, 50]], "color": "#00ff00"})).unwrap(); + let edges = + s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": [100, 50], "scope": "samePaint", "color": "#ff0000", "width": 3})).unwrap(); + redo_waiting_and_saved(&mut s, g); + let mut before = snapshot(&s); + let same = json!({"group": g.0, "point": [75, 50], "scope": "samePaint", "color": "#00ff00"}); + assert_eq!(s.execute("livePaint.fill", &same).unwrap()["count"], 3); + assert_unchanged(&mut s, &mut before, "a samePaint fill where every face has the paint"); + let again = json!({"group": g.0, "point": [100, 50], "scope": "samePaint", "color": "#ff0000", "width": 3}); + assert_eq!(s.execute("livePaint.strokeEdge", &again).unwrap()["count"], edges["count"]); + assert_unchanged(&mut s, &mut before, "a samePaint stroke where every edge has the paint and the width"); + // One face of the three without the paint: only it is filled, in one undo step. + let green = Paint::solid(Color::from_hex("#00ff00").unwrap()); + let red = Paint::solid(Color::from_hex("#ff0000").unwrap()); + s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 50], "color": "#ff0000"})).unwrap(); + let depth = history_state(&s).0; + let like = serde_json::to_value(&green).unwrap(); + let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 50], "scope": "samePaint", "match": like, "color": "#00ff00"})).unwrap(); + assert_eq!(r["count"], 3); + assert_eq!(history_state(&s).0, depth + 1); + let fill_at = |s: &Session, x: f64| vectorcraft_tools::builder::face_at(&node(s, g), Point::new(x, 50.0)).unwrap().appearance.fill_paint(); + for x in [25.0, 75.0, 125.0] { + assert_eq!(fill_at(&s, x), green, "{x}"); + } + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(fill_at(&s, 25.0), red); + assert_eq!((fill_at(&s, 75.0), fill_at(&s, 125.0)), (green.clone(), green)); +} + #[test] fn live_paint_gap_options_same_values_are_no_op() { let mut s = session(); diff --git a/crates/mcp/src/tests/livepaint.rs b/crates/mcp/src/tests/livepaint.rs index f3952a90f6..0165823e6f 100644 --- a/crates/mcp/src/tests/livepaint.rs +++ b/crates/mcp/src/tests/livepaint.rs @@ -47,3 +47,27 @@ fn a_triple_click_fills_every_face_of_the_same_fill() { ok(&mut h, "pointer_gesture", json!({"events": [ev("tripleclick")]})); assert_eq!(fills(&mut h, &g), [after_two[0].clone(), after_two[0].clone()], "both faces were red"); } + +/// With Space held (`mods.space`), the Live Paint Bucket's clicks, double-click and triple-click +/// paint nothing. +#[test] +fn clicks_with_space_held_paint_nothing() { + let mut h = Headless::new(); + h.call("engine.execute", json!({"command": "file.new", "params": {"width": 300, "height": 300}})).unwrap(); + let a = run(&mut h, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}))["id"].clone(); + let b = run(&mut h, "shape.rectangle", json!({"x": 100, "y": 0, "width": 50, "height": 50}))["id"].clone(); + let g = run(&mut h, "livePaint.make", json!({"ids": [a, b]}))["id"].clone(); + for x in [25, 125] { + run(&mut h, "livePaint.fill", json!({"group": g, "point": [x, 25], "color": "#ff0000"})); + } + run(&mut h, "select.none", json!({})); + run(&mut h, "paint.setFill", json!({"color": "#00ff00"})); + let red = fills(&mut h, &g); + let ev = |kind: &str| json!({"kind": kind, "x": 25, "y": 25}); + let clicks = [ev("down"), ev("up"), ev("down"), ev("up"), ev("doubleclick"), ev("down"), ev("up"), ev("tripleclick")]; + ok(&mut h, "pointer_gesture", json!({"tool": "livePaintBucket", "mods": {"space": true}, "events": clicks})); + assert_eq!(fills(&mut h, &g), red); + // Without Space, the same clicks paint. + ok(&mut h, "pointer_gesture", json!({"events": [ev("down"), ev("up")]})); + assert_ne!(fills(&mut h, &g)[0], red[0]); +} diff --git a/crates/tools/src/builder/live_paint.rs b/crates/tools/src/builder/live_paint.rs index ff59b22333..56e8e654e3 100644 --- a/crates/tools/src/builder/live_paint.rs +++ b/crates/tools/src/builder/live_paint.rs @@ -178,14 +178,16 @@ enum LpPaint { /// A triple-click on a face fills every face of the group with the face's fill, and on an edge it /// paints every edge of the group with the edge's stroke (`scope: "samePaint"`). Each click of a /// double-click or triple-click paints as it arrives, as its own undo step, and the paint compared -/// is the one the face or edge had before the first of its clicks. Shift and the options choose a -/// face or an edge as for a click; with Alt held a double-click or triple-click paints nothing. With -/// Space held for the view tools, a click, double-click or triple-click paints nothing. +/// is the one the face or edge had before the first of its clicks that painted it. A first click +/// that made the Live Paint group counts when the face it filled is the clicked face. Shift and the +/// options choose a face or an edge as for a click; with Alt held a double-click or triple-click +/// paints nothing. With Space held for the view tools, a click, double-click or triple-click paints +/// nothing and no face or edge is highlighted. pub struct LivePaintBucketTool { pub(super) cache: RegionCache, pub(super) hover: LpHover, - /// Where the pointer last moved, and whether Shift and Alt were held. - at: Option<(Point, bool, bool)>, + /// Where the pointer last moved, and the modifiers held there. + at: Option<(Point, Mods)>, /// The fill command and polyline previewed from the press's snapshot. fill_drag: Option<(Value, Vec>)>, /// The last [`LP_PRESSES`] presses, oldest first: the face or edge each one painted, with its @@ -304,17 +306,19 @@ impl LivePaintBucketTool { self.note_press(Some(LpPress { part: Some(n.id), at, before })); } - /// The paint `part` had before the first of the last presses of a click sequence of `clicks` - /// presses that all painted `part` (the sequence's first press may have made the group `part` - /// is in, when the face it filled there is `part`); `now` when the last press did not paint it. + /// The paint `part` had before the first press of a click sequence of `clicks` presses that + /// painted `part` (the sequence's first press counts when it made the group `part` is in and + /// the face it filled there is `part`); `now` when the last press did not paint it. fn before(&self, cx: &ToolContext, part: NodeId, clicks: usize, now: Paint) -> Paint { let Some(run) = self.presses.len().checked_sub(clicks).and_then(|from| self.presses.get(from..)) else { return now }; let made_part = |q: &LpPress| live_paint_at(cx.doc, q.at).and_then(|g| visible_face_at(cx.doc.node(g)?, q.at)).is_some_and(|f| f.id == part); let on_part = |(i, q): (usize, &Option)| q.as_ref().is_some_and(|q| q.part == Some(part) || (i == 0 && q.part.is_none() && made_part(q))); - let from = run.len().saturating_sub(run.iter().enumerate().rev().take_while(|&iq| on_part(iq)).count()); - match run.get(from) { - Some(Some(first)) => first.before.clone(), + if !run.last().is_some_and(|q| on_part((run.len() - 1, q))) { + return now; + } + match run.iter().enumerate().find(|&iq| on_part(iq)) { + Some((_, Some(first))) => first.before.clone(), _ => now, } } @@ -322,7 +326,7 @@ impl LivePaintBucketTool { /// What a double-click (`scope` "connected", 2 `clicks`) or a triple-click ("samePaint", 3) at /// `p` runs: the command a click there runs, with `scope`, and the paint it compares as `match`. fn multi_click(&self, cx: &ToolContext, p: Point, mods: Mods, scope: &str, clicks: usize) -> Vec { - // With Space held the press pans, zooms or rotates the view and does not reach the tool. + // With Alt held, or with Space held for the view tools, a double-click or triple-click paints nothing. if mods.alt || mods.space { return vec![]; } @@ -350,14 +354,14 @@ impl LivePaintBucketTool { vec![Action::Exec("livePaint.fill".into(), v)] } - /// The highlight at `p` for a pointer with Shift and Alt held as given: none with Alt or with - /// Highlight off, else the face or edge a click there paints. With Highlight off the selection's - /// map is still made, for the cursor ([`Self::paints_at`]). - fn hover_at(&mut self, cx: &ToolContext, p: Point, shift: bool, alt: bool) -> LpHover { - if alt { + /// The highlight at `p` for a pointer with the modifiers `mods`: none with Alt, with Space held + /// for the view tools or with Highlight off, else the face or edge a click there paints. With + /// Highlight off the selection's map is still made, for the cursor ([`Self::paints_at`]). + fn hover_at(&mut self, cx: &ToolContext, p: Point, mods: Mods) -> LpHover { + if mods.alt || mods.space { return LpHover::None; } - let target = self.target_at(cx, p, shift); + let target = self.target_at(cx, p, mods.shift); if self.highlight { target } else { LpHover::None } } @@ -432,13 +436,13 @@ impl Tool for LivePaintBucketTool { } match ev.kind { PointerKind::Move => { - self.at = Some((p, ev.mods.shift, ev.mods.alt)); - self.hover = self.hover_at(cx, p, ev.mods.shift, ev.mods.alt); + self.at = Some((p, ev.mods)); + self.hover = self.hover_at(cx, p, ev.mods); vec![] } PointerKind::Down => { self.hover = LpHover::None; - // With Space held the press pans, zooms or rotates the view. + // With Space held for the view tools, a press paints nothing. if ev.mods.space { self.note_press(None); return vec![]; @@ -573,8 +577,8 @@ impl Tool for LivePaintBucketTool { // of a Live Paint group the hover takes no map. loop { self.cache.settle(wait); - if let Some((p, shift, alt)) = self.at { - self.hover = self.hover_at(cx, p, shift, alt); + if let Some((p, mods)) = self.at { + self.hover = self.hover_at(cx, p, mods); } if !wait || !self.cache.waiting() { break; diff --git a/crates/tools/src/builder/tests.rs b/crates/tools/src/builder/tests.rs index a0811c5071..42efee075c 100644 --- a/crates/tools/src/builder/tests.rs +++ b/crates/tools/src/builder/tests.rs @@ -1254,6 +1254,51 @@ fn bucket_triple_click_after_making_the_group_on_another_face_matches_its_own_fa assert_eq!(v["match"], own); } +/// A triple-click whose clicks land on one face, another face, then the first face again matches +/// the fill the first face had before the first click on it, not the fill that click gave it. +#[test] +fn bucket_triple_click_with_a_click_on_another_face_between_matches_the_first_fill() { + use vectorcraft_color::{Color, Paint}; + let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let (d, gid, f2, _) = live_group_doc(); + let mut painted = d.clone(); + painted.node_mut(f2).unwrap().appearance.set_fill(red.clone()); + let s = Selection::default(); + let p = paint(); + let (cx, later) = (cx(&d, &s, &p), cx(&painted, &s, &p)); + let mut t = LivePaintBucketTool::default(); + // The first click paints the face at (75, 25) red; the second fills the face at (25, 25). + for (ctx, x) in [(&cx, 75.0), (&later, 25.0), (&later, 75.0)] { + t.pointer(ctx, &ev(PointerKind::Down, x, 25.0)); + t.pointer(ctx, &ev(PointerKind::Up, x, 25.0)); + } + let acts = t.pointer(&later, &ev(PointerKind::TripleClick, 75.0, 25.0)); + let own = serde_json::to_value(d.node(f2).unwrap().appearance.fill_paint()).unwrap(); + assert_ne!(own, serde_json::to_value(&red).unwrap()); + assert_eq!( + acts, + vec![Action::Exec("livePaint.fill".into(), json!({ "group": gid.0, "point": [75.0, 25.0], "scope": "samePaint", "match": own }))] + ); +} + +/// With Space held for the view tools, the pointer outlines no face or edge, as a press there +/// paints nothing. +#[test] +fn bucket_highlights_nothing_with_space_held() { + let (d, ..) = live_group_doc(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = LivePaintBucketTool::default(); + let space = Mods { space: true, ..Default::default() }; + for (x, m) in [(75.0, space), (51.0, Mods { shift: true, ..space })] { + t.pointer(&cx, &ev(PointerKind::Move, x, 25.0).with_mods(m)); + assert!(t.overlays(&cx).is_empty(), "at {x} with {m:?}"); + } + t.pointer(&cx, &ev(PointerKind::Move, 75.0, 25.0)); + assert!(!t.overlays(&cx).is_empty()); +} + #[test] fn bucket_options_choose_what_a_click_paints() { let (d, gid, ..) = live_group_doc(); diff --git a/docs/mcp.md b/docs/mcp.md index 9887f22044..4ece60e032 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3531,14 +3531,15 @@ already walks Image Trace. Short agent entry points: the pointer is not outlined. A double-click runs the command a click there runs with `scope: "connected"`, and a triple-click with `scope: "samePaint"`; Alt held runs nothing. With Space held (`mods.space`, the view tools), a press, a - double-click or a triple-click runs nothing. On a face, `connected` fills the face and every face reached from it + double-click or a triple-click runs nothing, and a move outlines no face or edge. On a face, `connected` fills the face and every face reached from it across edges that draw no stroke (hidden, stroke paint none, or weight 0); a stroked edge, a hidden face, a gap that Gap Detection closes and the group's outside stop it. `samePaint` fills every face of the group, joined to it or not, whose fill is the `match` paint. On an edge, `connected` paints the edge and the edges joined to it end to end whose stroke paint is `match`, and `samePaint` paints every edge of the group with that stroke paint; the stroke's weight is not compared. Each click of a double-click or triple-click runs as it arrives and is its own undo step. `match` is the paint the face or edge had before the first of the double-click's - two clicks or the triple-click's three that painted it, so the clicks before the last do not change what it matches. Hidden faces and edges are not painted. These rules + two clicks or the triple-click's three that painted it, so the clicks before the last do not change what it matches; + a first click that made the Live Paint group counts when the face it filled is the clicked face. Hidden faces and edges are not painted. These rules for what faces and edges join and what paints match are VectorCraft's own. The help page describes the gestures: https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html. `livePaint.fill {scope}` and `livePaint.strokeEdge {scope}` take `scope` as `"one"` (the default), `"connected"` or diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f4a7bb708b..93639260db 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1437,7 +1437,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Object › Live Paint › Merge adds the other selected paths and Live Paint groups to the bottom selected Live Paint group ([Live Paint groups](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/live-paint-groups.html)), which keeps its id, the paint of its faces and edges, and its name, lock, visibility, transparency, appearance, opacity mask and graphic style link. Object › Live Paint › Make with a Live Paint group selected, and a Live Paint Bucket click on a selected path beside a selected Live Paint group, add the paths to that group the same way. Make, Merge and the Live Paint Bucket take paths, compound paths and groups of them; with type, an image or another object among the selection they report that it has to be converted to paths first and change nothing, as type and raster images can't go into a Live Paint group directly ([Create Live Paint groups](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/create-live-paint-groups.html)); before, such an object went among the group's hidden sources and vanished from the canvas. Evidence: `tests_build::live_paint_refuses_type_and_images_and_changes_nothing`. With the Live Paint Bucket selected, Alt-click on vector art samples its fill, stroke and stroke weight into the paint defaults ([Paint with the Live Paint Bucket tool](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html)). On a placed image it samples the image pixel as a solid fill with no stroke. Alt+Shift-click samples only the color under the pointer, including an intermediate gradient color or image pixels, into the active fill or stroke ([Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). Neither click paints or changes the selection or selected art, and the next Bucket click paints with the sampled paint. Evidence: `tests_build::live_paint_bucket_alt_sample_paints_next_face_without_changing_selection`. Double-clicking the Live Paint Bucket opens Live Paint Bucket Options ([Paint with the Live Paint Bucket tool](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html)): Paint Fills (on) and Paint Strokes (off) set whether a click paints faces, edges or both, Highlight turns the outline of the face or edge under the pointer on or off, and Color and Width set it (red and 4 px by default). Faces are outlined at the Width and edges at half of it, as the page says faces are highlighted with a thick line and edges with a thin line. With both on, a click paints the edge within 4 px of the pointer, else the face, and Shift switches to Paint Fills only; with one on, Shift switches to the other. The options last across tool switches and are saved with the preferences (`tool.setOption {tool: "livePaintBucket"}`). Evidence: `builder::tests::{bucket_options_choose_what_a_click_paints, bucket_options_set_the_highlight, bucket_highlights_an_edge_thinner_than_a_face}`, `dialogs::live_paint_bucket::tests::double_clicking_the_tool_opens_its_options_and_ok_sets_them`. - Live Paint Bucket double-click and triple-click, as [the help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html) describes them: a double-click on a face fills it and the faces reached across edges that draw no stroke, and on an edge it paints the edges joined to it with the same stroke; a triple-click fills every face of the group with the face's fill, or paints every edge with the edge's stroke (`livePaint.fill` and `livePaint.strokeEdge` `{scope: "connected" | "samePaint", match?}`; `pointer_gesture` and `ui.pointer` take `tripleclick`). Each click paints as it arrives, as its own undo step, and the paint compared is the one the face or edge had before the first of its clicks. Which faces and edges join and which paints match are VectorCraft's own rules. Evidence: `tests_build::{live_paint_bucket_double_click_floods_across_unstroked_edges, live_paint_bucket_double_click_floods_curved_and_narrow_faces, live_paint_bucket_double_click_floods_across_hidden_edges_and_past_gaps, live_paint_bucket_triple_click_fills_every_face_of_the_same_fill, live_paint_bucket_triple_click_after_making_the_group_matches_the_made_fill, live_paint_bucket_double_and_triple_click_paint_joined_and_same_stroke_edges, live_paint_scope_and_match_are_checked}`, `builder::tests::{bucket_double_and_triple_click_widen_what_a_click_paints, bucket_triple_click_after_making_the_group_on_another_face_matches_its_own_face}`, `tests::livepaint::a_triple_click_fills_every_face_of_the_same_fill` (MCP). + Live Paint Bucket double-click and triple-click, as [the help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html) describes them: a double-click on a face fills it and the faces reached across edges that draw no stroke, and on an edge it paints the edges joined to it with the same stroke; a triple-click fills every face of the group with the face's fill, or paints every edge with the edge's stroke (`livePaint.fill` and `livePaint.strokeEdge` `{scope: "connected" | "samePaint", match?}`; `pointer_gesture` and `ui.pointer` take `tripleclick`). Each click paints as it arrives, as its own undo step, and the paint compared is the one the face or edge had before the first of its clicks that painted it; a first click that made the Live Paint group counts when the face it filled is the clicked face. With Space held for the view tools, a click, double-click or triple-click paints nothing. Which faces and edges join and which paints match are VectorCraft's own rules. Evidence: `tests_build::{live_paint_bucket_double_click_floods_across_unstroked_edges, live_paint_bucket_double_click_floods_curved_and_narrow_faces, live_paint_bucket_double_click_floods_across_hidden_edges_and_past_gaps, live_paint_bucket_triple_click_fills_every_face_of_the_same_fill, live_paint_bucket_triple_click_after_making_the_group_matches_the_made_fill, live_paint_bucket_double_and_triple_click_paint_joined_and_same_stroke_edges, live_paint_scope_and_match_are_checked}`, `builder::tests::{bucket_double_and_triple_click_widen_what_a_click_paints, bucket_triple_click_after_making_the_group_on_another_face_matches_its_own_face}`, `tests::livepaint::a_triple_click_fills_every_face_of_the_same_fill` (MCP). Live Paint Make preserves the front-most covering source's fill when compound paths share a curved boundary, and Expand keeps the face fills. Regression evidence: `planar::tests::coincident_curves_keep_their_source_faces` checks source order, winding, fill rules and nearby boundaries; `tests::build::live_paint_make_and_expand_keep_abutting_compound_colors` checks native compound paths, Make, Expand and Undo/Redo. This preserves VectorCraft's source-fill rule without changing arrangement precision. Live Paint Gap Options (Object › Live Paint › Gap Options…, `livePaint.gapOptions`): with Gap Detection on, paint stops at the gaps that run from a loose end of a path to the nearest path, up to Small (3 pt), Medium (6 pt), Large (12 pt) or a custom size; Close Gaps With Paths adds an unpainted path across each gap; Preview applies the options live and draws the gaps in the Gap Preview Color. The options are saved, copied and undone with the group, and Merge keeps the bottom group's options when its Gap Detection is on, or else turns Gap Detection on with Small when another merged group has it on. When Gap Detection is off in every merged group, it stays off. View › Show Live Paint Gaps (`view.livePaintGaps`) draws the gaps of the selected Live Paint groups up to their Paint Stops At size, each in its group's Gap Preview Color, until Hide Live Paint Gaps or Hide Edges hides them ([Live Paint gaps](https://web.archive.org/web/20260105111201/https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/find-and-close-gaps-in-live-paint-groups.html)). From ce3445d10685348bffd5b285dba83767cbea1d31 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 19:38:18 -0800 Subject: [PATCH 08/47] Live Paint: a Cmd double-click or triple-click with the Bucket paints nothing With Cmd (Ctrl) held, the Bucket's presses go to the selection tool Cmd lends, but the double-click and triple-click that follow reached the Bucket and painted. They now paint nothing, as with Alt. --- crates/engine/src/tests/build.rs | 22 ++++++++++++++++++++++ crates/tools/src/builder/live_paint.rs | 9 +++++---- crates/tools/src/builder/tests.rs | 1 + docs/mcp.md | 3 ++- docs/target-app-parity.md | 2 +- 5 files changed, 31 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 92d7c8caf0..49f6286e45 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -3046,6 +3046,28 @@ fn live_paint_bucket_double_click_floods_across_unstroked_edges() { assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [green.clone(), green.clone(), green, white]); } +/// With Cmd held, the Live Paint Bucket's presses go to the selection tool Cmd lends, and the +/// double-click and triple-click that follow them paint nothing. +#[test] +fn live_paint_bucket_cmd_double_and_triple_click_paint_nothing() { + let mut s = session(); + let g = live_squares(&mut s, &[0.0, 50.0, 100.0]); + let faces = faces_at(&s, g, &[(25.0, 25.0), (75.0, 25.0), (125.0, 25.0)]); + let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 151.0, 51.0)); + paint_parts(&mut s, &all, &Paint::None, &[]); + let before: Vec = faces.iter().map(|f| fill_of(&s, *f)).collect(); + let v = ViewInfo::default(); + s.select_tool("livePaintBucket", v).unwrap(); + s.paint.fill = Paint::solid(Color::from_hex("#00ff00").unwrap()); + let cmd = Mods { cmd: true, ..Default::default() }; + let (down, up) = (PointerKind::Down, PointerKind::Up); + for kind in [down, up, down, up, PointerKind::DoubleClick, down, up, PointerKind::TripleClick] { + s.pointer(&PointerEvent::new(kind, 75.0, 25.0).with_mods(cmd), v).unwrap(); + } + assert_eq!(faces.iter().map(|f| fill_of(&s, *f)).collect::>(), before); + assert_eq!(s.tool_id(), "livePaintBucket"); +} + /// The flood crosses curved edges, and reaches a face 0.012 pt wide. #[test] fn live_paint_bucket_double_click_floods_curved_and_narrow_faces() { diff --git a/crates/tools/src/builder/live_paint.rs b/crates/tools/src/builder/live_paint.rs index fab4663d9e..2ea049a9fb 100644 --- a/crates/tools/src/builder/live_paint.rs +++ b/crates/tools/src/builder/live_paint.rs @@ -180,8 +180,8 @@ enum LpPaint { /// double-click or triple-click paints as it arrives, as its own undo step, and the paint compared /// is the one the face or edge had before the first of its clicks that painted it. A first click /// that made the Live Paint group counts when the face it filled is the clicked face. Shift and the -/// options choose a face or an edge as for a click; with Alt held a double-click or triple-click -/// paints nothing. With Space held for the view tools, a click, double-click or triple-click paints +/// options choose a face or an edge as for a click; with Alt or Cmd/Ctrl held a double-click or +/// triple-click paints nothing. With Space held for the view tools, a click, double-click or triple-click paints /// nothing and no face or edge is highlighted. /// /// The Left and Right arrow keys without Shift, Alt or Cmd/Ctrl set the active paint (the fill, @@ -352,8 +352,9 @@ impl LivePaintBucketTool { /// What a double-click (`scope` "connected", 2 `clicks`) or a triple-click ("samePaint", 3) at /// `p` runs: the command a click there runs, with `scope`, and the paint it compares as `match`. fn multi_click(&self, cx: &ToolContext, p: Point, mods: Mods, scope: &str, clicks: usize) -> Vec { - // With Alt held, or with Space held for the view tools, a double-click or triple-click paints nothing. - if mods.alt || mods.space { + // With Alt held, with Space held for the view tools, or with Cmd/Ctrl held (its presses went + // to the selection tool Cmd lends), a double-click or triple-click paints nothing. + if mods.alt || mods.space || mods.cmd { return vec![]; } let point = json!([p.x, p.y]); diff --git a/crates/tools/src/builder/tests.rs b/crates/tools/src/builder/tests.rs index eb6f806246..c44863531d 100644 --- a/crates/tools/src/builder/tests.rs +++ b/crates/tools/src/builder/tests.rs @@ -1150,6 +1150,7 @@ fn bucket_double_and_triple_click_widen_what_a_click_paints() { let space = Mods { space: true, ..Default::default() }; for k in [PointerKind::DoubleClick, PointerKind::TripleClick] { assert!(t.pointer(&cx, &ev(k, 75.0, 25.0).with_mods(alt)).is_empty(), "{k:?}"); + assert!(t.pointer(&cx, &ev(k, 75.0, 25.0).with_mods(Mods { cmd: true, ..Default::default() })).is_empty(), "{k:?} with Cmd"); assert!(t.pointer(&cx, &ev(k, 75.0, 25.0).with_mods(space)).is_empty(), "{k:?} with Space"); assert!(t.pointer(&cx, &ev(k, 51.0, 25.0).with_mods(Mods { shift: true, ..space })).is_empty(), "{k:?} with Shift and Space"); } diff --git a/docs/mcp.md b/docs/mcp.md index b34d1dc880..352602d978 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3536,7 +3536,8 @@ already walks Image Trace. Short agent entry points: Shift-click runs `livePaint.fill`. With both off, a click runs nothing. With `highlight` off, the face or edge under the pointer is not outlined. A double-click runs the command a click there runs with `scope: "connected"`, and a triple-click with - `scope: "samePaint"`; Alt held runs nothing. With Space held (`mods.space`, the view tools), a press, a + `scope: "samePaint"`; Alt held runs nothing, and so does Cmd/Ctrl (`mods.cmd`), whose presses go to the selection + tool Cmd lends. With Space held (`mods.space`, the view tools), a press, a double-click or a triple-click runs nothing, and a move outlines no face or edge. On a face, `connected` fills the face and every face reached from it across edges that draw no stroke (hidden, stroke paint none, or weight 0); a stroked edge, a hidden face, a gap that Gap Detection closes and the group's outside stop it. `samePaint` fills every face diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 824d6c594d..ce24a37432 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1445,7 +1445,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Object › Live Paint › Merge adds the other selected paths and Live Paint groups to the bottom selected Live Paint group ([Live Paint groups](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/live-paint-groups.html)), which keeps its id, the paint of its faces and edges, and its name, lock, visibility, transparency, appearance, opacity mask and graphic style link. Object › Live Paint › Make with a Live Paint group selected, and a Live Paint Bucket click on a selected path beside a selected Live Paint group, add the paths to that group the same way. Make, Merge and the Live Paint Bucket take paths, compound paths and groups of them; with type, an image or another object among the selection they report that it has to be converted to paths first and change nothing, as type and raster images can't go into a Live Paint group directly ([Create Live Paint groups](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/create-live-paint-groups.html)); before, such an object went among the group's hidden sources and vanished from the canvas. Evidence: `tests_build::live_paint_refuses_type_and_images_and_changes_nothing`. With the Live Paint Bucket selected, Alt-click on vector art samples its fill, stroke and stroke weight into the paint defaults ([Paint with the Live Paint Bucket tool](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html)). On a placed image it samples the image pixel as a solid fill with no stroke. Alt+Shift-click samples only the color under the pointer, including an intermediate gradient color or image pixels, into the active fill or stroke ([Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). Neither click paints or changes the selection or selected art, and the next Bucket click paints with the sampled paint. Evidence: `tests_build::live_paint_bucket_alt_sample_paints_next_face_without_changing_selection`. Double-clicking the Live Paint Bucket opens Live Paint Bucket Options ([Paint with the Live Paint Bucket tool](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html)): Paint Fills (on) and Paint Strokes (off) set whether a click paints faces, edges or both, Highlight turns the outline of the face or edge under the pointer on or off, and Color and Width set it (red and 4 px by default). Faces are outlined at the Width and edges at half of it, as the page says faces are highlighted with a thick line and edges with a thin line. With both on, a click paints the edge within 4 px of the pointer, else the face, and Shift switches to Paint Fills only; with one on, Shift switches to the other. The options last across tool switches and are saved with the preferences (`tool.setOption {tool: "livePaintBucket"}`). Evidence: `builder::tests::{bucket_options_choose_what_a_click_paints, bucket_options_set_the_highlight, bucket_highlights_an_edge_thinner_than_a_face}`, `dialogs::live_paint_bucket::tests::double_clicking_the_tool_opens_its_options_and_ok_sets_them`. - Live Paint Bucket double-click and triple-click, as [the help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html) describes them: a double-click on a face fills it and the faces reached across edges that draw no stroke, and on an edge it paints the edges joined to it with the same stroke; a triple-click fills every face of the group with the face's fill, or paints every edge with the edge's stroke (`livePaint.fill` and `livePaint.strokeEdge` `{scope: "connected" | "samePaint", match?}`; `pointer_gesture` and `ui.pointer` take `tripleclick`). Each click paints as it arrives, as its own undo step, and the paint compared is the one the face or edge had before the first of its clicks that painted it; a first click that made the Live Paint group counts when the face it filled is the clicked face. With Space held for the view tools, a click, double-click or triple-click paints nothing and no face or edge is outlined. Which faces and edges join and which paints match are VectorCraft's own rules. Evidence: `tests_build::{live_paint_bucket_double_click_floods_across_unstroked_edges, live_paint_bucket_double_click_floods_curved_and_narrow_faces, live_paint_bucket_double_click_floods_across_hidden_edges_and_past_gaps, live_paint_bucket_triple_click_fills_every_face_of_the_same_fill, live_paint_bucket_triple_click_after_making_the_group_matches_the_made_fill, live_paint_bucket_double_and_triple_click_paint_joined_and_same_stroke_edges, live_paint_scope_and_match_are_checked}`, `builder::tests::{bucket_double_and_triple_click_widen_what_a_click_paints, bucket_triple_click_after_making_the_group_on_another_face_matches_its_own_face, bucket_triple_click_with_a_click_on_another_face_between_matches_the_first_fill, bucket_highlights_nothing_with_space_held}`, `tests::build::live_paint_scoped_fill_and_stroke_skip_parts_with_the_paint`, `tests::livepaint::{a_triple_click_fills_every_face_of_the_same_fill, clicks_with_space_held_paint_nothing}` (MCP). + Live Paint Bucket double-click and triple-click, as [the help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html) describes them: a double-click on a face fills it and the faces reached across edges that draw no stroke, and on an edge it paints the edges joined to it with the same stroke; a triple-click fills every face of the group with the face's fill, or paints every edge with the edge's stroke (`livePaint.fill` and `livePaint.strokeEdge` `{scope: "connected" | "samePaint", match?}`; `pointer_gesture` and `ui.pointer` take `tripleclick`). Each click paints as it arrives, as its own undo step, and the paint compared is the one the face or edge had before the first of its clicks that painted it; a first click that made the Live Paint group counts when the face it filled is the clicked face. With Space held for the view tools, a click, double-click or triple-click paints nothing and no face or edge is outlined, and with Cmd/Ctrl held a double-click or triple-click paints nothing. Which faces and edges join and which paints match are VectorCraft's own rules. Evidence: `tests_build::{live_paint_bucket_double_click_floods_across_unstroked_edges, live_paint_bucket_double_click_floods_curved_and_narrow_faces, live_paint_bucket_double_click_floods_across_hidden_edges_and_past_gaps, live_paint_bucket_triple_click_fills_every_face_of_the_same_fill, live_paint_bucket_triple_click_after_making_the_group_matches_the_made_fill, live_paint_bucket_double_and_triple_click_paint_joined_and_same_stroke_edges, live_paint_scope_and_match_are_checked}`, `builder::tests::{bucket_double_and_triple_click_widen_what_a_click_paints, bucket_triple_click_after_making_the_group_on_another_face_matches_its_own_face, bucket_triple_click_with_a_click_on_another_face_between_matches_the_first_fill, bucket_highlights_nothing_with_space_held}`, `tests::build::{live_paint_scoped_fill_and_stroke_skip_parts_with_the_paint, live_paint_bucket_cmd_double_and_triple_click_paint_nothing}`, `tests::livepaint::{a_triple_click_fills_every_face_of_the_same_fill, clicks_with_space_held_paint_nothing}` (MCP). Live Paint Bucket Options has Cursor Swatch Preview, as the [help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html) lists: with the Bucket selected, the active fill or stroke shows above the pointer between the color swatches before and after it in the Swatches panel, and the Left and Right arrow keys pick the swatch before or after it, as the page describes. The selected art keeps its paint. As VectorCraft's own rules, the option is on at first, the arrows step the stroke when the Stroke proxy is in front, they wrap around at the ends and still step with the preview off, a color that is no swatch shows alone until Right picks the first swatch or Left the last, and the arrows do nothing during a fill drag or with no color swatch. Evidence: `tests::build::{live_paint_bucket_arrow_keys_step_the_active_paint_through_the_swatches, live_paint_bucket_arrow_keys_handle_unmatched_paint_few_swatches_and_drags, live_paint_bucket_arrow_keys_pass_swatches_of_the_same_color_for_fill_and_stroke, swatch_arrow_keys_leave_modified_arrows_to_the_shortcuts}`. Live Paint Make preserves the front-most covering source's fill when compound paths share a curved boundary, and Expand keeps the face fills. Regression evidence: `planar::tests::coincident_curves_keep_their_source_faces` checks source order, winding, fill rules and nearby boundaries; `tests::build::live_paint_make_and_expand_keep_abutting_compound_colors` checks native compound paths, Make, Expand and Undo/Redo. This preserves VectorCraft's source-fill rule without changing arrangement precision. Live Paint Gap Options (Object › Live Paint › Gap Options…, `livePaint.gapOptions`): with Gap Detection on, paint stops at the gaps that run from a loose end of a path to the nearest path, up to Small (3 pt), Medium (6 pt), Large (12 pt) or a custom size; Close Gaps With Paths adds an unpainted path across each gap; Preview applies the options live and draws the gaps in the Gap Preview Color. The options are saved, copied and undone with the group, and Merge keeps the bottom group's options when its Gap Detection is on, or else turns Gap Detection on with Small when another merged group has it on. When Gap Detection is off in every merged group, it stays off. From abf93e31d74578f511e1ba2e7555afcc5a5b2f57 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 04:23:59 -0800 Subject: [PATCH 09/47] Canvas: translucent art blends with the paper before the monitor profile With Use Monitor Profile for Canvas converting, the art's raster was converted on its own and then drawn over the separately converted paper, so a translucent fill or an antialiased edge showed blend(convert(art), convert(paper)) rather than the converted blend. Each pixel with partial alpha over an artboard's paper, a colored artboard, the transparency grid or Hide Artboards' paper now gets the color that, drawn over the converted paper, shows the art blended with the paper in sRGB and then converted. Its alpha is kept, so a grid drawn in back still shows through. Opaque and empty pixels, art over the pasteboard and Outline convert as before, and with no profile to convert into nothing changes. The frame rendered whole, the part an edit renders again, the render worker's frame (and the pan fill), and the other windows' panes all use the same rule. The paper is part of the canvas cache key, so turning the grid on or hiding the artboards renders the art again. --- crates/ui-egui/src/caches.rs | 11 + crates/ui-egui/src/canvas.rs | 61 ++++- crates/ui-egui/src/canvas/panes.rs | 13 +- crates/ui-egui/src/canvas/raster.rs | 3 +- crates/ui-egui/src/canvas/tests.rs | 202 ++++++++++++++ crates/ui-egui/src/display_profile.rs | 377 +++++++++++++++++++++++++- docs/mcp.md | 5 +- docs/target-app-parity.md | 1 + 8 files changed, 653 insertions(+), 20 deletions(-) diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 286b4d4d02..8c6d669e14 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -164,6 +164,17 @@ pub struct CacheKey { /// The display profile the frame is converted into ([`crate::display_profile::DisplayProfile::key`]), /// 0 for none. pub display: u64, + /// The paper under the art that translucent art is blended with before the conversion + /// ([`crate::display_profile::convert_over`]). None without a display profile, and in Outline. + pub backdrop: Option>, +} + +impl CacheKey { + /// [`Self::backdrop`] with the zoom its grid's cells are measured at, as + /// [`crate::display_profile::convert_over`] takes it. + pub(crate) fn over(&self) -> Option<(&crate::display_profile::Backdrop, f64)> { + self.backdrop.as_deref().map(|b| (b, self.zoom)) + } } #[derive(Clone, Copy, Debug, Default)] diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index a947dde852..36e842dbaf 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -623,6 +623,7 @@ fn cache_key( trace_source: app.ui.trace_hold_source.clone(), // Preferences › Performance › Use Monitor Profile for Canvas. display: app.display_profile.key(app.session.prefs.monitor_profile_display), + backdrop: backdrop(app, st, app.outline_view()), } } @@ -887,9 +888,10 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { } if let (Some([x0, y0, x1, y1]), Some(tex)) = (region, &mut app.canvas.texture) { let renderer = &mut app.canvas.renderer; - let mut part = - effects.view(|| renderer.render(doc, x1 - x0, y1 - y0, Affine::translate((-f64::from(x0), -f64::from(y0))) * view, &opts)); - crate::display_profile::convert(display.as_deref(), &mut part.pixels); + let part_view = Affine::translate((-f64::from(x0), -f64::from(y0))) * view; + let mut part = effects.view(|| renderer.render(doc, x1 - x0, y1 - y0, part_view, &opts)); + let width = part.width; + crate::display_profile::convert_over(display.as_deref(), &mut part.pixels, width, part_view, key.over()); let color = color_image(&part); let options = if pixel.is_some() { egui::TextureOptions::NEAREST } else { egui::TextureOptions::LINEAR }; tex.set_partial([x0 as usize, y0 as usize], color, options); @@ -927,7 +929,8 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { let renderer = &mut app.canvas.renderer; let mut img = effects.view(|| renderer.render(doc, w, h, view, &opts)); effects.first_view_done(); - crate::display_profile::convert(display.as_deref(), &mut img.pixels); + let width = img.width; + crate::display_profile::convert_over(display.as_deref(), &mut img.pixels, width, view, key.over()); upload(app, ui.ctx(), img, pixel.is_some()); app.canvas.key = Some(key.clone()); app.canvas.shown = Some((doc.clone(), opts.clone())); @@ -982,13 +985,11 @@ fn paint_paper( let on_display = |c: Color32| crate::display_profile::color32(display.as_deref(), c); if !shows_artboards(app) { // View › Hide Artboards: no edges and no pasteboard, the whole canvas paper (#4038). - let setup = &doc.setup; - painter.rect_filled(rect, 0.0, on_display(if setup.simulate_paper { crate::panels::c32(&setup.paper()) } else { Color32::WHITE })); + painter.rect_filled(rect, 0.0, on_display(paper_color(&doc.setup))); } else { let setup = &doc.setup; - let grid = (st.transparency_grid && setup.background == vectorcraft_doc::Background::Transparent) - .then(|| checker_texture(ui.ctx(), setup, display.as_deref())); - let paper = if setup.simulate_paper { crate::panels::c32(&setup.paper()) } else { Color32::WHITE }; + let grid = shows_transparency_grid(st).then(|| checker_texture(ui.ctx(), setup, display.as_deref())); + let paper = paper_color(setup); for ab in &doc.artboards { let q = xf.quad(ab.rect); // Hard 2 pt drop shadow, right and bottom (measured: #4d4d4d then #565656 on #606060). @@ -998,14 +999,52 @@ fn paint_paper( match &grid { Some((tex, cell)) => checker(painter, &q, ab.rect, xf.zoom, tex.id(), *cell), None => { - let fill = ab.color.map_or(paper, |c| crate::panels::c32(&c) * paper); - painter.add(Shape::convex_polygon(q, on_display(fill), Stroke::NONE)); + painter.add(Shape::convex_polygon(q, on_display(artboard_paper(ab, paper)), Stroke::NONE)); } } } } } +/// The color of the paper: Simulate Colored Paper's, else white. +fn paper_color(setup: &vectorcraft_doc::DocSetup) -> Color32 { + if setup.simulate_paper { crate::panels::c32(&setup.paper()) } else { Color32::WHITE } +} + +/// The color of artboard `ab`'s paper, the paper `paper`: an artboard with a background color +/// multiplies it with the paper, each sRGB channel artboard × paper / 255, rounded. +fn artboard_paper(ab: &vectorcraft_doc::Artboard, paper: Color32) -> Color32 { + ab.color.map_or(paper, |c| crate::panels::c32(&c) * paper) +} + +/// The transparency grid covers the artboards of document `st`: it is shown, and the Background +/// Contents are transparent. +fn shows_transparency_grid(st: &vectorcraft_engine::DocState) -> bool { + st.transparency_grid && st.doc.setup.background == vectorcraft_doc::Background::Transparent +} + +/// The paper [`paint_paper`] draws for document `st`, which translucent art is blended with before +/// the display profile's conversion. None without a display profile, and in Outline (`outline`), +/// whose white canvas is the interface's. +fn backdrop(app: &VectorcraftApp, st: &vectorcraft_engine::DocState, outline: bool) -> Option> { + if outline || app.display_profile.transform(app.session.prefs.monitor_profile_display).is_none() { + return None; + } + let rgb = |c: Color32| [c.r(), c.g(), c.b()]; + let setup = &st.doc.setup; + let paper = paper_color(setup); + let b = if shows_artboards(app) { + crate::display_profile::Backdrop { + everywhere: None, + artboards: st.doc.artboards.iter().map(|ab| (ab.rect, rgb(artboard_paper(ab, paper)))).collect(), + grid: shows_transparency_grid(st).then(|| (setup.grid_colors.map(|c| rgb(crate::panels::c32(&c))), setup.grid_size.cell())), + } + } else { + crate::display_profile::Backdrop { everywhere: Some(rgb(paper)), artboards: vec![], grid: None } + }; + Some(std::sync::Arc::new(b)) +} + /// The last rendered frame, placed through the current view while a new one is on its way. fn reproject_frame(app: &VectorcraftApp, painter: &egui::Painter, xf: &Xf, rect: egui::Rect, (key_doc, rotation): (usize, f64)) { if let (Some(tex), Some(k)) = (&app.canvas.texture, &app.canvas.key) diff --git a/crates/ui-egui/src/canvas/panes.rs b/crates/ui-egui/src/canvas/panes.rs index 76fb599fda..aee571d0ce 100644 --- a/crates/ui-egui/src/canvas/panes.rs +++ b/crates/ui-egui/src/canvas/panes.rs @@ -11,7 +11,7 @@ use super::grid::LineLook; use super::outline::{c32, node_outline, stroke_path, too_many_anchors}; use super::view::fit_zoom; use super::{ - Affine, CacheKey, Point, Rect, RulerScale, Sense, Stroke, StrokeKind, Tokens, Ui, VectorcraftApp, View, Xf, artboard_edges, cache_key, + Affine, CacheKey, Point, Rect, RulerScale, Sense, Stroke, StrokeKind, Tokens, Ui, VectorcraftApp, View, Xf, artboard_edges, backdrop, cache_key, dim_on_canvas, frame_options, frame_view, grid, guides_of, json, paint_paper, pixel_region, placed_key, plugin_key, pos2, rulers, shows_artboards, textured_quad, vec2, view_rects, }; @@ -29,7 +29,7 @@ type Slot = (u64, u32); pub struct Panes { /// Renders off the UI thread (None: on it, as on wasm). worker: Option>, - worker_started: bool, + pub(crate) worker_started: bool, /// Renders on the UI thread when there is no worker. renderer: Option, /// By slot: the render shown and what it shows. @@ -109,13 +109,14 @@ impl Panes { if !current { let mut queued = false; if let Some(worker) = &self.worker { - let (job_doc, job_opts, job_display) = (doc.clone(), opts.clone(), display.clone()); + let (job_doc, job_opts, job_display, job_key) = (doc.clone(), opts.clone(), display.clone(), key.clone()); queued = worker.submit( slot, (slot, key.clone()), Box::new(move |r| { let mut img = r.render(&job_doc, w, h, view, &job_opts); - crate::display_profile::convert(job_display.as_deref(), &mut img.pixels); + let width = img.width; + crate::display_profile::convert_over(job_display.as_deref(), &mut img.pixels, width, view, job_key.over()); Some(img) }), ); @@ -127,7 +128,8 @@ impl Panes { } if !queued { let mut img = self.renderer.get_or_insert_with(vectorcraft_render::Renderer::new).render(&doc, w, h, view, &opts); - crate::display_profile::convert(display.as_deref(), &mut img.pixels); + let width = img.width; + crate::display_profile::convert_over(display.as_deref(), &mut img.pixels, width, view, key.over()); self.upload(ctx, slot, key, &img); } } @@ -328,6 +330,7 @@ pub(crate) fn pane(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) // The current document's drag and Image Trace hold are not this document's, and this view has // its own Outline or Preview. (key.dragging, key.trace_source, key.outline) = (false, None, v.outline); + key.backdrop = backdrop(app, st, v.outline); let opts = frame_options(app, &key, st.shown_mask(), smooth_images); let (fw, fh, view) = frame_view(pixel, (pw, ph), &drawn, ppp); let doc = st.doc.clone(); diff --git a/crates/ui-egui/src/canvas/raster.rs b/crates/ui-egui/src/canvas/raster.rs index f57a15a795..2f9a4f981f 100644 --- a/crates/ui-egui/src/canvas/raster.rs +++ b/crates/ui-egui/src/canvas/raster.rs @@ -226,7 +226,8 @@ pub(crate) fn render_job(r: &mut vectorcraft_render::Renderer, kept: &mut Option *kept = keeps.then(|| KeptFrame { key: job.key.clone(), opts: job.opts.clone(), view: job.view, pixels: holds_pixels.then(|| img.pixels.clone()) }); // The kept frame stays sRGB, so the next frame's copied pixels are converted only once. - crate::display_profile::convert(job.display.as_deref(), &mut img.pixels); + let width = img.width; + crate::display_profile::convert_over(job.display.as_deref(), &mut img.pixels, width, job.view, job.key.over()); WorkerFrame { img, moved, reused } } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 4d609f2b5e..791415bee0 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -2717,6 +2717,140 @@ fn the_canvas_is_drawn_through_the_display_profile_while_the_preference_is_on() assert_eq!(count(&mut app, red), Some(srgb)); } +/// With a display profile, translucent art and the anti-aliased edges of art over the paper are +/// blended with the paper in sRGB before the conversion: drawn over the converted paper, each such +/// pixel shows the converted blend. Opaque art, and art over the pasteboard, convert as before. The +/// part an edit renders again and the render worker's frame do the same, a change of the +/// transparency grid renders the art again, and Outline converts the art alone. +#[test] +fn translucent_art_over_the_paper_is_blended_before_the_display_profile() { + use crate::display_profile::{Found, Reading}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.ui.task_bar = false; + app.ui.view.rulers = false; + app.canvas.worker_started = true; // every frame on this thread + let half = app.run("shape.rectangle", json!({"x": 100, "y": 50, "width": 200, "height": 200})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"ids": [half], "color": "#ff0000"})).unwrap(); + app.run("transparency.set", json!({"ids": [half], "opacity": 50})).unwrap(); + let disc = app.run("shape.ellipse", json!({"x": 20, "y": 20, "width": 60, "height": 60})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"ids": [disc], "color": "#2040c0"})).unwrap(); + // Left of the artboard, over the pasteboard. + let outside = app.run("shape.rectangle", json!({"x": -60, "y": 100, "width": 40, "height": 40})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"ids": [outside], "color": "#00ff00"})).unwrap(); + app.run("transparency.set", json!({"ids": [outside], "opacity": 50})).unwrap(); + app.run("select.none", json!({})).unwrap(); + let ctx = egui::Context::default(); + // The art's raster one frame uploads: where it goes ([x, y] for a part), its width and its pixels. + let upload = |app: &mut VectorcraftApp| -> Option<(Option<[usize; 2]>, usize, Vec)> { + let (_, mut delta) = frame_output(app, &ctx); + let art = app.canvas.texture.as_ref()?.id(); + let up = delta.set.iter().find(|e| e.0.eq(&art)).and_then(|e| e.1.last()).map(|d| { + let egui::ImageData::Color(img) = &d.image; + (d.pos, img.width(), img.pixels.clone()) + }); + delta.clear(); + up + }; + upload(&mut app).expect("the first frame"); + let v = app.view_mut().unwrap(); + (v.zoom, v.center) = (1.0, Point::new(120.0, 150.0)); + let (_, width, srgb) = upload(&mut app).expect("the view at 100%"); + let key = app.canvas.key.clone().unwrap(); + assert!(key.backdrop.is_none(), "no display profile: nothing to blend"); + let p3 = crate::display_profile::tests::p3(); + let t = vectorcraft_color::cms::display::DisplayTransform::from_icc(&p3).unwrap(); + app.display_profile.report(Reading { display: Some("DP-1".into()), found: Found::Profile { icc: p3, from: "test".into() } }); + let (_, _, shown) = upload(&mut app).expect("drawn again, converted"); + let key = app.canvas.key.clone().unwrap(); + assert!(key.backdrop.is_some()); + let white = t.apply8([255; 3]); + // What the canvas shows of pixel `c` over the converted paper `under`, as egui blends it. + let over = |c: egui::Color32, under: [u8; 3]| { + let k = 255 - u32::from(c.a()); + [0, 1, 2].map(|i| u32::from(c.to_array()[i]) + (u32::from(under[i]) * k + 127) / 255) + }; + let plain = |s: egui::Color32| { + let mut px = s.to_array(); + t.apply_premultiplied(&mut px); + egui::Color32::from_rgba_premultiplied(px[0], px[1], px[2], px[3]) + }; + let (view_w, view_h) = (key.w, key.h); + let (_, _, view) = frame_view( + None, + (view_w, view_h), + &View { zoom: key.zoom, center: Point::new(key.cx, key.cy), rotation: key.rot, ..View::default() }, + key.ppp, + ); + let to_doc = view.inverse(); + let (mut blended, mut beside) = (0, 0); + for (i, (s, c)) in srgb.iter().zip(&shown).enumerate() { + let p = to_doc * Point::new((i % width) as f64 + 0.5, (i / width) as f64 + 0.5); + if s.a() == 0 || s.a() == 255 { + assert_eq!(*c, plain(*s), "opaque and empty pixels convert as before, at {p:?}"); + } else if (1.0..399.0).contains(&p.x) && (1.0..299.0).contains(&p.y) { + let k = 255 - u32::from(s.a()); + let mix = [0, 1, 2].map(|j| (u32::from(s.to_array()[j]) + (255 * k + 127) / 255).min(255) as u8); + let want = t.apply8(mix); + let got = over(*c, white); + assert!((0..3).all(|j| got[j].abs_diff(u32::from(want[j])) <= 1), "at {p:?}: {got:?} shown, {want:?} wanted"); + blended += 1; + } else if p.x < -1.0 { + assert_eq!(*c, plain(*s), "over the pasteboard the art converts alone, at {p:?}"); + beside += 1; + } + } + assert!(blended > 1000 && beside > 500, "{blended} pixels over the paper, {beside} over the pasteboard"); + // The test tells the two apart: the fill converted alone, over the converted paper, shows another color. + let at = view * Point::new(200.0, 150.0); + let at = at.y as usize * width + at.x as usize; + let (s, c) = (srgb[at], shown[at]); + assert!((50..=205).contains(&s.a()), "the 50% fill at the center: {s:?}"); + let alone = over(plain(s), white); + assert!((0..3).any(|j| alone[j].abs_diff(over(c, white)[j]) > 2), "{alone:?} and {:?}", over(c, white)); + // The render worker's frame of the same key is the same. + let opts = app.canvas.shown.as_ref().unwrap().1.clone(); + let doc = app.session.active().unwrap().doc.clone(); + let display = app.display_profile.transform(true); + let job = |key: &CacheKey, doc: &std::sync::Arc| crate::render_worker::Job { + key: key.clone(), + doc: doc.clone(), + w: view_w, + h: view_h, + view, + opts: opts.clone(), + scope: vectorcraft_engine::file_access::ScopeHandle::capture(), + effects: Default::default(), + may_copy: false, + may_keep: false, + display: display.clone(), + }; + let worker = crate::canvas::render_job(&mut vectorcraft_render::Renderer::new(), &mut None, &job(&key, &doc)).img; + let near = |a: &[u8], b: egui::Color32| a.iter().zip(b.to_array()).all(|(x, y)| x.abs_diff(y) <= 1); + assert!(worker.pixels.as_chunks::<4>().0.iter().zip(&shown).all(|(a, b)| near(a, *b)), "the worker's frame matches"); + // An edit renders its part again, blended too. + app.run("paint.setFill", json!({"ids": [half], "color": "#0000ff"})).unwrap(); + let (pos, part_w, part) = upload(&mut app).expect("the edit shows"); + let [x0, y0] = pos.expect("only its part"); + let key = app.canvas.key.clone().unwrap(); + let doc = app.session.active().unwrap().doc.clone(); + let whole = crate::canvas::render_job(&mut vectorcraft_render::Renderer::new(), &mut None, &job(&key, &doc)).img; + let whole = whole.pixels.as_chunks::<4>().0; + for (i, c) in part.iter().enumerate() { + let at = (y0 + i / part_w) * view_w as usize + x0 + i % part_w; + assert!(near(&whole[at], *c), "the part matches the whole frame at {at}: {c:?}, {:?}", whole[at]); + } + assert!(part.iter().filter(|c| c.a() != 0 && c.a() != 255).count() > 1000, "the blue fill is in the part"); + // The transparency grid replaces the paper under the art: drawn again. + app.run("view.transparencyGrid", json!({"on": true})).unwrap(); + assert!(upload(&mut app).is_some_and(|(pos, ..)| pos.is_none()), "the grid renders the art again"); + assert!(app.canvas.key.as_ref().and_then(|k| k.backdrop.as_ref()).is_some_and(|b| b.grid.is_some())); + // Outline: the white canvas is the interface's, so the art converts alone. + app.run("view.outline", json!({})).unwrap(); + upload(&mut app).expect("Outline renders again"); + assert!(app.canvas.key.as_ref().is_some_and(|k| k.outline && k.backdrop.is_none())); +} + /// View › Hide Template (#2000): a template layer's art leaves the canvas, and Show Template /// draws it again, dimmed as before; each re-renders at once. #[test] @@ -5527,6 +5661,74 @@ fn a_pane_draws_its_own_views_outline() { } } +/// With a display profile, a split-view pane or floating window blends translucent art with the +/// paper before the conversion, as the canvas does, and in its own Outline converts the art alone. +#[test] +fn a_pane_blends_translucent_art_before_the_display_profile() { + use crate::display_profile::{Found, Reading}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let half = app.run("shape.rectangle", json!({"x": 50, "y": 25, "width": 100, "height": 50})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"ids": [half], "color": "#ff0000"})).unwrap(); + app.run("transparency.set", json!({"ids": [half], "opacity": 50})).unwrap(); + app.run("select.none", json!({})).unwrap(); + crate::doc_windows::new_window(&mut app).unwrap(); + app.canvas.panes.worker_started = true; // every pane render on this thread + let p3 = crate::display_profile::tests::p3(); + let t = vectorcraft_color::cms::display::DisplayTransform::from_icc(&p3).unwrap(); + app.display_profile.report(Reading { display: Some("DP-1".into()), found: Found::Profile { icc: p3, from: "test".into() } }); + let ctx = egui::Context::default(); + let other = (0, 1); + let slot = (app.session.documents()[0].uid, 1); + // The pane's raster one frame uploads, and the key it was rendered for. + let pane = |app: &mut VectorcraftApp| -> (Vec, CacheKey) { + let cell = egui::Rect::from_min_size(pos2(0.0, 0.0), vec2(600.0, 400.0)); + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + panes::pane(app, ui, other, cell); + }); + let (key, tex) = app.canvas.panes.shown.get(&slot).expect("the pane's render"); + let id = tex.id(); + let pixels = out.textures_delta.set.iter().find(|e| e.0.eq(&id)).and_then(|e| e.1.last()).map(|d| { + let egui::ImageData::Color(img) = &d.image; + img.pixels.clone() + }); + let key = key.clone(); + out.textures_delta.clear(); + (pixels.expect("the pane uploads"), key) + }; + app.session.prefs.monitor_profile_display = false; + let (srgb, key) = pane(&mut app); + assert!(key.backdrop.is_none(), "no display profile: nothing to blend"); + app.session.prefs.monitor_profile_display = true; + let (shown, key) = pane(&mut app); + assert!(key.backdrop.is_some(), "the pane's Preview blends with its paper"); + assert_eq!(srgb.len(), shown.len()); + let plain = |s: egui::Color32| { + let mut px = s.to_array(); + t.apply_premultiplied(&mut px); + egui::Color32::from_rgba_premultiplied(px[0], px[1], px[2], px[3]) + }; + let mut blended = 0; + for (s, c) in srgb.iter().zip(&shown) { + if s.a() == 0 || s.a() == 255 { + assert_eq!(*c, plain(*s), "opaque and empty pixels convert as before"); + } else { + assert_eq!(c.a(), s.a(), "the alpha is kept"); + let p = plain(*s); + if (0..3).any(|j| c.to_array()[j].abs_diff(p.to_array()[j]) > 2) { + blended += 1; + } + } + } + assert!(blended > 100, "{blended} translucent pixels blended with the paper"); + // The pane's own Outline: the art converts alone, while the current view stays in Preview. + crate::doc_windows::view_mut(&mut app, other).unwrap().outline = true; + app.view_mut().unwrap().outline = false; + let (_, key) = pane(&mut app); + assert!(key.outline && key.backdrop.is_none(), "the pane's Outline has no paper to blend with"); +} + /// While the rulers' origin is dragged out of their corner, its crosshair draws over the canvas in /// the theme's dim text color in Preview, and in Outline in the dark gray that shows on the white /// canvas. diff --git a/crates/ui-egui/src/display_profile.rs b/crates/ui-egui/src/display_profile.rs index 486489e6fe..af3c756e78 100644 --- a/crates/ui-egui/src/display_profile.rs +++ b/crates/ui-egui/src/display_profile.rs @@ -1,6 +1,8 @@ //! Preferences › Performance › Use Monitor Profile for Canvas: the canvas's art, its artboards' //! paper and the transparency grid are converted from sRGB into the ICC profile of the display -//! that shows most of the main window, as the last step before they are drawn. +//! that shows most of the main window, as the last step before they are drawn. Translucent art +//! and the anti-aliased edges of art over the paper or the grid are blended with it in sRGB first, +//! and the blend is converted ([`convert_over`]). //! //! The desktop app reads the display's profile on a background thread and hands the reading to //! [`DisplayProfile::report`], which checks the profile and builds its conversion table there. @@ -14,6 +16,7 @@ use std::sync::{Arc, RwLock}; use serde_json::{Value, json}; use vectorcraft_color::cms::display::DisplayTransform; pub use vectorcraft_color::cms::display::MAX_PROFILE_BYTES; +use vectorcraft_geom::{Affine, Point, Rect}; /// What the desktop app read for the display showing the main window. #[derive(Clone, Debug, PartialEq)] @@ -221,6 +224,220 @@ pub(crate) fn convert(t: Option<&DisplayTransform>, pixels: &mut [u8]) { t.apply_premultiplied(pixels); } +/// The document's paper under the canvas's art, which the canvas draws converted into the display +/// profile before the art: [`convert_over`] blends translucent art with it before converting. +/// The pasteboard and Outline's white canvas are interface colors and are not part of it. +#[derive(Clone, Debug, PartialEq)] +pub struct Backdrop { + /// View › Hide Artboards: the sRGB color of the paper that covers the whole canvas. + pub(crate) everywhere: Option<[u8; 3]>, + /// The artboards in the order they are drawn (the last on top), each with its paper's sRGB color. + pub(crate) artboards: Vec<(Rect, [u8; 3])>, + /// The transparency grid, which covers every artboard's paper: its two sRGB colors, and its cell + /// in screen points, counted from each artboard's top left corner. + pub(crate) grid: Option<([[u8; 3]; 2], f32)>, +} + +/// A color of the backdrop: in sRGB, and as the canvas shows it, converted. +#[derive(Clone, Copy, PartialEq)] +struct Paper { + srgb: [u8; 3], + shown: [u8; 3], +} + +/// An artboard of the backdrop, as [`Over`] looks it up. +struct Board { + /// Its rectangle in the document, normalized. + rect: Rect, + /// The corner the transparency grid's cells are counted from. + origin: Point, + paper: Paper, +} + +/// No artboard at a pixel of a row ([`Over::owners`]). +const NO_BOARD: u32 = u32::MAX; + +/// The first pixel at or after `x` that no artboard has taken yet, in the chain `next` (each +/// pixel's next candidate; a pixel not taken is its own), shortening the chain on the way. +fn untaken(next: &mut [u32], x: usize) -> usize { + let mut root = x; + while next[root] as usize != root { + root = next[root] as usize; + } + let mut at = x; + while next[at] as usize != root { + let n = next[at] as usize; + next[at] = root as u32; + at = n; + } + root +} + +/// [`Backdrop`] converted for a frame: what [`convert_over`] needs for each pixel. +struct Over<'a> { + t: &'a DisplayTransform, + /// The frame's pixels → the document. + to_doc: Affine, + everywhere: Option, + boards: Vec, + /// The grid's two colors and its cell in document points. + grid: Option<([Paper; 2], f64)>, +} + +impl<'a> Over<'a> { + /// None when the backdrop has no paper, or `view` (the document → the pixels) can't be undone. + fn new(t: &'a DisplayTransform, b: &Backdrop, view: Affine, zoom: f64) -> Option { + let det = view.determinant(); + if (b.everywhere.is_none() && b.artboards.is_empty()) || !det.is_finite() || det.abs() < 1e-12 { + return None; + } + let paper = |srgb: [u8; 3]| Paper { srgb, shown: t.apply8(srgb) }; + let boards = b.artboards.iter().map(|&(r, color)| Board { rect: r.abs(), origin: r.origin(), paper: paper(color) }).collect(); + let zoom = if zoom.is_finite() && zoom > 0.0 { zoom } else { 1.0 }; + Some(Self { + t, + to_doc: view.inverse(), + everywhere: b.everywhere.map(paper), + boards, + grid: b.grid.map(|([a, c], cell)| ([paper(a), paper(c)], (f64::from(cell) / zoom).max(5e-10))), + }) + } + + /// The pixels `start..end` of the row whose centers lie at height `y` that artboard `b` covers, + /// their centers inside its rectangle. None when it covers none of the row's `width` pixels. + fn span(&self, b: &Board, y: f64, width: usize) -> Option<(usize, usize)> { + let at = self.to_doc * Point::new(0.0, y); + let [dx, dy, ..] = self.to_doc.as_coeffs(); + // Where along the row the document point stays within the rectangle, axis by axis. + let (mut lo, mut hi) = (f64::NEG_INFINITY, f64::INFINITY); + for (start, slope, min, max) in [(at.x, dx, b.rect.x0, b.rect.x1), (at.y, dy, b.rect.y0, b.rect.y1)] { + if slope == 0.0 { + if !(min <= start && start < max) { + return None; + } + } else { + let (t0, t1) = ((min - start) / slope, (max - start) / slope); + (lo, hi) = (lo.max(t0.min(t1)), hi.min(t0.max(t1))); + } + } + // Pixel i's center is i + 0.5. + let (start, end) = ((lo - 0.5).ceil().max(0.0), (hi - 0.5).ceil().min(width as f64)); + (start < end).then_some((start as usize, end as usize)) + } + + /// `owner` becomes the artboard on top at each of the `width` pixels of the row whose centers + /// lie at height `y` ([`NO_BOARD`] where there is none). Each pixel is taken once, by the + /// topmost artboard over it, so a row costs its width plus its artboards however they overlap. + fn owners(&self, y: f64, width: usize, owner: &mut Vec, next: &mut Vec) { + owner.clear(); + owner.resize(width, NO_BOARD); + next.clear(); + next.extend(0..=width as u32); + for (k, b) in self.boards.iter().enumerate().rev() { + let Some((start, end)) = self.span(b, y, width) else { continue }; + let mut x = untaken(next, start); + while x < end { + owner[x] = k as u32; + next[x] = x as u32 + 1; + x = untaken(next, x + 1); + } + } + } + + /// The paper at pixel `i` of the row at height `y`, whose artboard on top is `owner`. + fn paper_at(&self, owner: u32, i: usize, y: f64) -> Option { + let b = self.boards.get(owner as usize)?; + Some(match &self.grid { + Some((colors, cell)) => { + let p = self.to_doc * Point::new(i as f64 + 0.5, y); + let cells = ((p.x - b.origin.x) / cell).floor() + ((p.y - b.origin.y) / cell).floor(); + colors[usize::from(cells.rem_euclid(2.0) >= 1.0)] + } + None => b.paper, + }) + } + + /// Rows `first_row..` of the frame, `width` pixels each, in `pixels`. + fn rows(&self, pixels: &mut [u8], first_row: usize, width: usize) { + let mut last_px = ([0u8; 4], [0u8; 4]); + let mut last_mix = (([0u8; 4], [0u8; 3]), [0u8; 4]); + let (mut owner, mut next) = (Vec::new(), Vec::new()); + for (j, line) in pixels.chunks_exact_mut(width * 4).enumerate() { + let y = (first_row + j) as f64 + 0.5; + // Found for the row's first translucent pixel. + let mut found = false; + for (i, px) in line.as_chunks_mut::<4>().0.iter_mut().enumerate() { + let a = px[3]; + if a == 0 { + continue; + } + let paper = if a == 255 { + None + } else if self.everywhere.is_some() { + self.everywhere + } else { + if !found { + self.owners(y, width, &mut owner, &mut next); + found = true; + } + self.paper_at(owner[i], i, y) + }; + match paper { + Some(p) if last_mix.0 == (*px, p.srgb) => *px = last_mix.1, + Some(p) => { + let input = (*px, p.srgb); + // Drawn over the converted paper, the pixel shows `px` over the paper in sRGB, converted. + let under = 255 - u32::from(a); + let mix = |c: usize| (u32::from(px[c]) + (u32::from(p.srgb[c]) * under + 127) / 255).min(255) as u8; + let shown = self.t.apply8([mix(0), mix(1), mix(2)]); + for ((o, s), u) in px.iter_mut().zip(shown).zip(p.shown) { + let paper_part = ((u32::from(u) * under + 127) / 255) as i32; + *o = (i32::from(s) - paper_part).clamp(0, 255) as u8; + } + last_mix = (input, *px); + } + None if last_px.0 == *px => *px = last_px.1, + None => { + let input = *px; + self.t.apply_premultiplied(px); + last_px = (input, *px); + } + } + } + } + } +} + +/// [`convert`], with each translucent pixel over the paper or the transparency grid of `backdrop` +/// blended with it in sRGB before the conversion. The canvas draws the art over the paper +/// converted: such a pixel keeps its alpha and takes the color that, drawn over the converted +/// paper, shows the blend converted. Opaque and fully transparent pixels, and pixels over the +/// pasteboard, convert as [`convert`] converts them. The pixels are rows of `width`; `view` maps the +/// document to them, and the backdrop's `zoom` is the canvas's screen points per document point, +/// in which the grid's cells are measured. +pub(crate) fn convert_over(t: Option<&DisplayTransform>, pixels: &mut [u8], width: u32, view: Affine, backdrop: Option<(&Backdrop, f64)>) { + let Some(t) = t else { return }; + let width = width as usize; + let over = backdrop.filter(|_| width > 0 && pixels.len().is_multiple_of(width * 4)).and_then(|(b, zoom)| Over::new(t, b, view, zoom)); + let Some(over) = over else { return convert(Some(t), pixels) }; + #[cfg(not(target_arch = "wasm32"))] + { + const PIECE: usize = 256 * 1024 * 4; + let threads = std::thread::available_parallelism().map_or(1, usize::from).min(16); + if threads > 1 && pixels.len() > PIECE { + let rows = (pixels.len() / (width * 4)).div_ceil(threads); + let over = &over; + std::thread::scope(|scope| { + for (k, piece) in pixels.chunks_mut(rows * width * 4).enumerate() { + scope.spawn(move || over.rows(piece, k * rows, width)); + } + }); + return; + } + } + over.rows(pixels, 0, width); +} + /// The opaque or translucent color `c` through `t`. pub(crate) fn color32(t: Option<&DisplayTransform>, c: egui::Color32) -> egui::Color32 { let Some(t) = t else { return c }; @@ -308,4 +525,162 @@ pub(crate) mod tests { let [r, g, b] = t.apply8([255, 0, 0]); assert_eq!(color32(Some(&t), egui::Color32::RED), egui::Color32::from_rgb(r, g, b)); } + + /// What the canvas shows of pixel `px` drawn over the converted paper `under`, as egui blends it. + fn shown_over(px: [u8; 4], under: [u8; 3]) -> [u32; 3] { + let k = 255 - u32::from(px[3]); + [0, 1, 2].map(|i| u32::from(px[i]) + (u32::from(under[i]) * k + 127) / 255) + } + + /// `px` blended with the sRGB paper `paper`, converted. + fn blended(t: &DisplayTransform, px: [u8; 4], paper: [u8; 3]) -> [u8; 3] { + let k = 255 - u32::from(px[3]); + t.apply8([0, 1, 2].map(|i| (u32::from(px[i]) + (u32::from(paper[i]) * k + 127) / 255).min(255) as u8)) + } + + fn assert_near(got: [u32; 3], want: [u8; 3], at: &str) { + assert!((0..3).all(|i| got[i].abs_diff(u32::from(want[i])) <= 1), "{at}: {got:?} shown, {want:?} wanted"); + } + + /// One row of `n` pixels, every one `px`. + fn row(n: usize, px: [u8; 4]) -> Vec { + px.repeat(n) + } + + #[test] + fn translucent_pixels_over_the_paper_are_blended_before_they_are_converted() { + let t = DisplayTransform::from_icc(&p3()).unwrap(); + let half_red = [128, 0, 0, 128]; + let b = Backdrop { everywhere: None, artboards: vec![(Rect::new(0.0, 0.0, 10.0, 1.0), [255; 3])], grid: None }; + let mut px = row(20, half_red); + px[12..16].copy_from_slice(&[255, 0, 0, 255]); + px[16..20].copy_from_slice(&[0; 4]); + convert_over(Some(&t), &mut px, 20, Affine::IDENTITY, Some((&b, 1.0))); + let at = |i: usize| -> [u8; 4] { px[i * 4..i * 4 + 4].try_into().unwrap() }; + let white = t.apply8([255; 3]); + assert_near(shown_over(at(0), white), blended(&t, half_red, [255; 3]), "over the paper"); + // Converted alone and drawn over the converted paper, the pixel shows another color. + let mut alone = half_red; + t.apply_premultiplied(&mut alone); + let want = blended(&t, half_red, [255; 3]); + assert!((0..3).any(|i| shown_over(alone, white)[i].abs_diff(u32::from(want[i])) > 2), "{alone:?}"); + assert_eq!(at(0)[3], 128, "the alpha is kept"); + // Opaque and empty pixels, and pixels over the pasteboard, convert as before. + let red = t.apply8([255, 0, 0]); + assert_eq!((at(3), at(4)), ([red[0], red[1], red[2], 255], [0; 4])); + assert_eq!(at(15), alone, "over the pasteboard"); + // Without a backdrop, and without a profile, as before. + let mut plain = row(20, half_red); + convert_over(Some(&t), &mut plain, 20, Affine::IDENTITY, None); + assert_eq!(plain, row(20, alone)); + let mut srgb = row(20, half_red); + convert_over(None, &mut srgb, 20, Affine::IDENTITY, Some((&b, 1.0))); + assert_eq!(srgb, row(20, half_red)); + } + + #[test] + fn the_backdrop_is_found_through_the_view() { + let t = DisplayTransform::from_icc(&p3()).unwrap(); + // Papers far apart: a pixel blended with the wrong one shows a color several levels off. + let half = [128, 0, 0, 128]; + let (light, dark) = ([255, 230, 230], [40, 40, 30]); + // A later artboard is drawn over an earlier one. + let b = Backdrop { + everywhere: None, + artboards: vec![(Rect::new(0.0, 0.0, 100.0, 100.0), light), (Rect::new(50.0, 0.0, 100.0, 100.0), dark)], + grid: None, + }; + // A view turned a quarter clockwise and moved: pixel x runs down the document's y axis. + let view = Affine::translate((10.0, 0.0)) * Affine::rotate(std::f64::consts::FRAC_PI_2) * Affine::translate((-20.0, -60.0)); + let mut px = row(10, half); + convert_over(Some(&t), &mut px, 10, view, Some((&b, 1.0))); + // Pixel (2.5, 0.5) is document point (20.5, 67.5): on the first artboard only. + let at = |i: usize| -> [u8; 4] { px[i * 4..i * 4 + 4].try_into().unwrap() }; + assert_near(shown_over(at(2), t.apply8(light)), blended(&t, half, light), "on the first artboard"); + let view = Affine::translate((-60.0, -5.0)); + let mut px = row(10, half); + convert_over(Some(&t), &mut px, 10, view, Some((&b, 1.0))); + let at = |i: usize| -> [u8; 4] { px[i * 4..i * 4 + 4].try_into().unwrap() }; + assert_near(shown_over(at(0), t.apply8(dark)), blended(&t, half, dark), "where the second covers the first"); + // View › Hide Artboards: the paper everywhere. + let all = Backdrop { everywhere: Some(dark), artboards: vec![], grid: None }; + let mut px = row(10, half); + convert_over(Some(&t), &mut px, 10, Affine::translate((-5000.0, 0.0)), Some((&all, 1.0))); + assert_near(shown_over(px[..4].try_into().unwrap(), t.apply8(dark)), blended(&t, half, dark), "Hide Artboards"); + // Overlapping artboards under a turned and scaled view, against a direct lookup of the + // artboard on top whose rectangle holds each pixel's center. + let boards: Vec<(Rect, [u8; 3])> = (0..12u8) + .map(|k| { + let (x, y) = (f64::from(k) * 7.0, f64::from(k % 3) * 9.0); + (Rect::new(x, y, x + 15.0, y + 20.0), if k % 2 == 0 { [255, 255, 255 - k] } else { [20 + k, 20, 30] }) + }) + .collect(); + let b = Backdrop { everywhere: None, artboards: boards.clone(), grid: None }; + let view = Affine::rotate(0.3) * Affine::scale(1.7) * Affine::translate((5.0, -3.0)); + let (w, h) = (64, 48); + let mut px = row(w * h, half); + convert_over(Some(&t), &mut px, w as u32, view, Some((&b, 1.0))); + let to_doc = view.inverse(); + let mut on_paper = 0; + for i in 0..w * h { + let p = to_doc * Point::new((i % w) as f64 + 0.5, (i / w) as f64 + 0.5); + let mut want = half.to_vec(); + match boards.iter().rev().find(|(r, _)| r.contains(p)) { + Some(&(_, paper)) => { + let one = Backdrop { everywhere: Some(paper), artboards: vec![], grid: None }; + convert_over(Some(&t), &mut want, 1, Affine::IDENTITY, Some((&one, 1.0))); + on_paper += 1; + } + None => t.apply_premultiplied(&mut want), + } + assert_eq!(&px[i * 4..i * 4 + 4], &want[..], "pixel {i} at {p:?}"); + } + assert!(on_paper > 500 && on_paper < w * h, "{on_paper} pixels on the artboards"); + } + + #[test] + fn the_transparency_grid_is_blended_cell_by_cell() { + let t = DisplayTransform::from_icc(&p3()).unwrap(); + let half = [128, 0, 0, 128]; + // Far apart, so that a pixel blended with the other cell's color shows several levels off. + let (light, dark) = ([255; 3], [40; 3]); + // Cells of 10 points from the artboard's corner at (5, 0), here 1 pixel a point. + let b = Backdrop { everywhere: None, artboards: vec![(Rect::new(5.0, 0.0, 65.0, 20.0), [255, 0, 0])], grid: Some(([light, dark], 10.0)) }; + let check = |zoom: f64, cells: [(usize, [u8; 3]); 3]| { + let mut px = row(60, half); + convert_over(Some(&t), &mut px, 60, Affine::IDENTITY, Some((&b, zoom))); + for (i, paper) in cells { + assert_near( + shown_over(px[i * 4..i * 4 + 4].try_into().unwrap(), t.apply8(paper)), + blended(&t, half, paper), + &format!("pixel {i} at {zoom}"), + ); + } + }; + check(1.0, [(6, light), (16, dark), (26, light)]); + // At 200% a cell is 5 document points. + check(2.0, [(6, light), (11, dark), (16, light)]); + } + + #[test] + fn large_frames_blend_the_same_on_several_threads() { + let t = DisplayTransform::from_icc(&p3()).unwrap(); + let b = Backdrop { + everywhere: None, + artboards: vec![(Rect::new(0.0, 0.0, 500.0, 900.0), [240, 230, 220])], + grid: Some(([[255; 3], [200; 3]], 8.0)), + }; + let (w, h) = (1000, 1000); + let mut big: Vec = (0..w * h * 4).map(|i| (i * 7 % 251) as u8).collect(); + for px in big.as_chunks_mut::<4>().0 { + let a = px[3]; + for c in &mut px[..3] { + *c = (*c).min(a); + } + } + let mut one = big.clone(); + Over::new(&t, &b, Affine::IDENTITY, 1.0).unwrap().rows(&mut one, 0, w); + convert_over(Some(&t), &mut big, w as u32, Affine::IDENTITY, Some((&b, 1.0))); + assert_eq!(big, one); + } } diff --git a/docs/mcp.md b/docs/mcp.md index ca77311c58..3893c4e542 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6010,8 +6010,9 @@ Color on (HDR or Automatic Color Management) and macOS windows are converted by again. In a Wayland session, and where no profile is set or the profile is not an RGB display profile of at most 1 MiB, the canvas stays sRGB. The app reads the display again every 10 seconds and when the window moves to another display. Exports, `ui.render`, the document, panels and thumbnails are not converted; with Proof Colors on, the proof is drawn -first and then converted. The art is converted before it is drawn over the converted paper, so the blend of a -translucent object or an antialiased edge with the paper can differ slightly from a conversion of the blended color. +first and then converted. Translucent art and the antialiased edges of art over an artboard's paper or the +transparency grid are blended with it in sRGB, and the blend is converted; over the pasteboard and in Outline the art +is converted on its own. `ui.inspect` returns `displayProfile`: `{enabled, display, source, profile, from, applied, reason, osManaged}`, where `source` is `profile`, `srgbProfile` (a profile that shows sRGB unchanged), `system`, `none`, `pending` or `unsupported`, `applied` says whether the canvas is converted, and `reason` says why not. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 7e36c7f318..c9a1e2ec34 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -732,6 +732,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Document Setup modal handoff:** Document Setup → Edit Artboards applies valid settings, closes the dialog and activates the Artboard tool. Pointer-click tests cover successful handoff, invalid settings, OK, Cancel and Undo in `dialogs/document_setup.rs`. - **Document Setup › Color:** a Color tab shows the document color mode (RGB Color or CMYK Color), a Convert to CMYK or Convert to RGB box for a mode change (cleared: the colors keep their numbers), and the RGB and CMYK profiles assigned to the document, with a working-space entry for none. OK runs `edit.assignProfile` and then `file.documentColorMode` with the dialog's other changes in one `command.batch`, and the document's changes are one undo step. An unchanged Color tab adds no color commands, and Cancel, or OK with nothing changed, records no undo step. A Color tab field with a value of the wrong kind is an error, and the dialog stays open. The tab is VectorCraft's own layout; File › Document Color Mode and Edit › Assign Profile… stay as they are. Tests in `dialogs/document_setup.rs`. - **Canvas through the display's profile on Windows and X11:** Preferences › Performance › Use Monitor Profile for Canvas (on by default) converts the canvas's art, artboard paper and transparency grid from sRGB into the ICC profile of the display that shows most of the main window, after any proof, as the help page describes the monitor's profile translating the document's colors for the monitor ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=151)). Windows gives the display's default profile, and a display with Advanced Color on is left to Windows ([Microsoft Learn](https://learn.microsoft.com/en-us/windows/win32/wcs/advanced-color-icc-profiles)); X11 gives colord's profile for the output or the `_ICC_PROFILE` property. macOS converts the window itself, and a Wayland session stays sRGB. `ui.inspect` reports `displayProfile`. Tests in `color/src/cms/display.rs`, `ui-egui/src/display_profile.rs` and `canvas::tests::the_canvas_is_drawn_through_the_display_profile_while_the_preference_is_on`. +- **Translucent art blended before the display profile:** with Use Monitor Profile for Canvas converting, translucent art and the anti-aliased edges of art over an artboard's paper, a colored artboard or the transparency grid are blended with it in sRGB and the blend is converted, so the monitor's profile translates the document's colors as they are composited ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=151)). The frame rendered whole, the part an edit renders again, the render worker's frame, the pan fill and the other windows' panes do the same; over the pasteboard and in Outline the art is converted on its own, and with no profile to convert into nothing changes. Tests `display_profile::tests::translucent_pixels_over_the_paper_are_blended_before_they_are_converted`, `the_transparency_grid_is_blended_cell_by_cell`, `the_backdrop_is_found_through_the_view` and `canvas::tests::translucent_art_over_the_paper_is_blended_before_the_display_profile`. - **Out-of-gamut warning after a profile change:** the out-of-gamut warning and its closest-color correction in the Color panel and Color Picker ([the help page](https://helpx.adobe.com/illustrator/using/adjusting-colors.html)) check the color against the document's assigned CMYK profile, else the working CMYK space, and update when Edit › Assign Profile… or Edit › Color Settings… changes that space or a loaded profile changes, without a change of color. Which CMYK space the warning uses is VectorCraft's own rule. Tests: `gamut_warning_follows_a_profile_change` and `gamut_warning_follows_a_profile_loaded_again` in `dialogs/color_picker/tests.rs`. - **Assign Profile and the working spaces:** Edit › Assign Profile… tags the document and leaves the working spaces of Edit › Color Settings… as they are, in Color Settings, the Separations panel and the settings saved for the next start. Colors show and convert through the profiles assigned; a change in Color Settings keeps the profiles the document in front is assigned in use, and removing an assigned profile in use puts the working space back in its place. The profiles in use follow the document in front: a new, opened or reverted document, a switch to another tab, a close, Undo and Redo of Assign Profile, a failed batch, each step of a batch, Export All Open and the update of placed documents put that document's profiles in use, and the working spaces where it is assigned none or no document is open. View › Proof Setup › Working CMYK simulates the working CMYK space of Color Settings in Proof Colors and Separations Preview, also in a document assigned another CMYK profile. Public references: [Changing the color profile for a document and About color working spaces](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=150) and [Soft-proof presets](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=134). Tests in `engine/tests/color_settings.rs`. - **New Document's More Settings and Save Preset:** More Settings opens a pop-up over New Document with only Number of Artboards, the artboard layout, Change to Right-to-Left Layout, Spacing and Columns; Done, Escape or a click outside closes it and keeps the values. Save Preset turns the top of Preset Details into a Save Document Preset heading with the preset's name, Cancel and Save, and hides the document's name, Close and Create until the preset is saved or canceled; nothing in that mode creates a document. Save Preset's default name is the first "Preset N" no saved preset has. VectorCraft's own layout. Harness tests in `dialogs/new_document.rs` cover both. From 49d51e763d71f8d95398fada82926d90c6e2034b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 05:33:51 -0800 Subject: [PATCH 10/47] Canvas: the paper under an artboard's edge pixel follows that pixel's center The row span of each artboard took a row that runs backward across it (a mirrored or turned view) as holding its maximum edge and not its minimum one, and rounding in a sheared view could put a span end a pixel off. Each span now keeps which of its ends the rectangle holds, and each end is moved until it agrees with the test of the pixel's own center, so an edge pixel blends with the paper it lies on. --- crates/ui-egui/src/display_profile.rs | 93 +++++++++++++++++++-------- 1 file changed, 66 insertions(+), 27 deletions(-) diff --git a/crates/ui-egui/src/display_profile.rs b/crates/ui-egui/src/display_profile.rs index af3c756e78..be46424ec9 100644 --- a/crates/ui-egui/src/display_profile.rs +++ b/crates/ui-egui/src/display_profile.rs @@ -308,21 +308,52 @@ impl<'a> Over<'a> { fn span(&self, b: &Board, y: f64, width: usize) -> Option<(usize, usize)> { let at = self.to_doc * Point::new(0.0, y); let [dx, dy, ..] = self.to_doc.as_coeffs(); - // Where along the row the document point stays within the rectangle, axis by axis. - let (mut lo, mut hi) = (f64::NEG_INFINITY, f64::INFINITY); + // Where along the row the document point stays within the rectangle, axis by axis. The + // rectangle holds its minimum edge and not its maximum one, so a row that runs toward the + // minimum holds its end there and not its start: each bound keeps whether it is held. + let (mut lo, mut hi) = ((f64::NEG_INFINITY, true), (f64::INFINITY, true)); for (start, slope, min, max) in [(at.x, dx, b.rect.x0, b.rect.x1), (at.y, dy, b.rect.y0, b.rect.y1)] { if slope == 0.0 { if !(min <= start && start < max) { return None; } - } else { - let (t0, t1) = ((min - start) / slope, (max - start) / slope); - (lo, hi) = (lo.max(t0.min(t1)), hi.min(t0.max(t1))); + continue; + } + let (t0, t1) = ((min - start) / slope, (max - start) / slope); + let (from, to) = if slope > 0.0 { ((t0, true), (t1, false)) } else { ((t1, false), (t0, true)) }; + // The tighter bound wins, and of two equal bounds the one not held. + if from.0 > lo.0 || (from.0 == lo.0 && !from.1) { + lo = from; + } + if to.0 < hi.0 || (to.0 == hi.0 && !to.1) { + hi = to; } } - // Pixel i's center is i + 0.5. - let (start, end) = ((lo - 0.5).ceil().max(0.0), (hi - 0.5).ceil().min(width as f64)); - (start < end).then_some((start as usize, end as usize)) + // Pixel i's center is i + 0.5: the first pixel whose center is past `lo` (or on it, when + // held), up to the first one past `hi` (or on it, when not held). + let start = if lo.1 { (lo.0 - 0.5).ceil() } else { (lo.0 - 0.5).floor() + 1.0 }; + let end = if hi.1 { (hi.0 - 0.5).floor() + 1.0 } else { (hi.0 - 0.5).ceil() }; + let clamp = |v: f64| v.clamp(0.0, width as f64) as usize; + let (mut start, mut end) = (clamp(start), clamp(end)); + end = end.max(start); + // Rounding can put a bound a pixel away from where the rectangle's own test of each pixel's + // center puts it: move each end until the two agree. + let inside = |i: usize| b.rect.contains(self.to_doc * Point::new(i as f64 + 0.5, y)); + for _ in 0..2 { + if start < end && !inside(start) { + start += 1; + } else if start > 0 && inside(start - 1) { + start -= 1; + } + } + for _ in 0..2 { + if end > start && !inside(end - 1) { + end -= 1; + } else if end < width && inside(end) { + end += 1; + } + } + (start < end).then_some((start, end)) } /// `owner` becomes the artboard on top at each of the `width` pixels of the row whose centers @@ -615,27 +646,35 @@ pub(crate) mod tests { (Rect::new(x, y, x + 15.0, y + 20.0), if k % 2 == 0 { [255, 255, 255 - k] } else { [20 + k, 20, 30] }) }) .collect(); - let b = Backdrop { everywhere: None, artboards: boards.clone(), grid: None }; - let view = Affine::rotate(0.3) * Affine::scale(1.7) * Affine::translate((5.0, -3.0)); - let (w, h) = (64, 48); - let mut px = row(w * h, half); - convert_over(Some(&t), &mut px, w as u32, view, Some((&b, 1.0))); - let to_doc = view.inverse(); - let mut on_paper = 0; - for i in 0..w * h { - let p = to_doc * Point::new((i % w) as f64 + 0.5, (i / w) as f64 + 0.5); - let mut want = half.to_vec(); - match boards.iter().rev().find(|(r, _)| r.contains(p)) { - Some(&(_, paper)) => { - let one = Backdrop { everywhere: Some(paper), artboards: vec![], grid: None }; - convert_over(Some(&t), &mut want, 1, Affine::IDENTITY, Some((&one, 1.0))); - on_paper += 1; + let check = |boards: &[(Rect, [u8; 3])], view: Affine, (w, h): (usize, usize)| { + let b = Backdrop { everywhere: None, artboards: boards.to_vec(), grid: None }; + let mut px = row(w * h, half); + convert_over(Some(&t), &mut px, w as u32, view, Some((&b, 1.0))); + let to_doc = view.inverse(); + let mut on_paper = 0; + for i in 0..w * h { + let p = to_doc * Point::new((i % w) as f64 + 0.5, (i / w) as f64 + 0.5); + let mut want = half.to_vec(); + match boards.iter().rev().find(|(r, _)| r.contains(p)) { + Some(&(_, paper)) => { + let one = Backdrop { everywhere: Some(paper), artboards: vec![], grid: None }; + convert_over(Some(&t), &mut want, 1, Affine::IDENTITY, Some((&one, 1.0))); + on_paper += 1; + } + None => t.apply_premultiplied(&mut want), } - None => t.apply_premultiplied(&mut want), + assert_eq!(&px[i * 4..i * 4 + 4], &want[..], "pixel {i} at {p:?} through {view:?}"); } - assert_eq!(&px[i * 4..i * 4 + 4], &want[..], "pixel {i} at {p:?}"); - } - assert!(on_paper > 500 && on_paper < w * h, "{on_paper} pixels on the artboards"); + assert!(on_paper > 100 && on_paper < w * h, "{on_paper} pixels on the artboards"); + }; + check(&boards, Affine::rotate(0.3) * Affine::scale(1.7) * Affine::translate((5.0, -3.0)), (64, 48)); + // Rows that run backward across the artboards, with pixel centers on their edges: an edge + // at the minimum is on the artboard, one at the maximum is not. + check(&boards, Affine::new([-1.0, 0.0, 0.0, 1.0, 92.5, 0.0]), (96, 44)); + check(&boards, Affine::new([-1.0, 0.0, 0.0, -1.0, 92.5, 40.5]), (96, 44)); + // A sheared view where a computed bound falls on a pixel center that rounding puts just + // outside the artboard: the pixel's own center decides. + check(&[(Rect::new(-100.0, -2.0, 100.0, 100.0), [40, 40, 30])], Affine::new([3.0, 1.5, 0.1, 0.5, -0.3, 0.0]), (64, 48)); } #[test] From ddae31bad4662005d2b04a6d85db4217b6173d1e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 07:55:06 -0800 Subject: [PATCH 11/47] TIFF: alpha after another extra sample places and opens as transparency A CMYK or grayscale TIFF reads its alpha from the first extra sample whose ExtraSamples value is 1 or 2, wherever it comes among the extra samples, at 8 and 16 bits, chunky or planar. TIFF 6.0 gives each extra sample its own ExtraSamples value, in order, and asks readers to skip extra samples they do not use. - A CMYK file with alpha after an unspecified extra sample was kept as opaque inks; it is now shown as RGB with its alpha. - A grayscale file with alpha after an unspecified extra sample opened opaque. - A six-sample CMYK file whose ExtraSamples tag lists only an unspecified value no longer reads that sample as transparency. - A white-is-zero grayscale file with an alpha channel opens; it failed to read before. --- crates/doc/src/cmyk.rs | 228 +++++++++++++++++++++++--- crates/engine/src/cmd/fileio/load.rs | 4 +- crates/engine/src/cmd/fileio/tests.rs | 32 ++++ docs/target-app-parity.md | 1 + 4 files changed, 239 insertions(+), 26 deletions(-) diff --git a/crates/doc/src/cmyk.rs b/crates/doc/src/cmyk.rs index 8cd3f85a4f..94f1017347 100644 --- a/crates/doc/src/cmyk.rs +++ b/crates/doc/src/cmyk.rs @@ -155,6 +155,61 @@ pub fn exif_orientation(bytes: &[u8]) -> Option { decoded().or_else(tagged).filter(|o| *o != Orientation::NoTransforms) } +/// TIFF `bytes` with the PhotometricInterpretation (tag 262) of their first image set to 1 (black +/// is zero) in each of its entries that holds one SHORT or LONG value. The decoder gives every +/// sample of a grayscale image's pixels, in the order the file stores them, where it gives a CMYK +/// image's inks and at most the first extra sample, and doesn't read a white-is-zero image with +/// extra samples. `None` for bytes that aren't a TIFF and when the first image has no such entry. +fn as_black_is_zero(bytes: &[u8]) -> Option> { + let le = bytes.starts_with(b"II*\0"); + if !le && !bytes.starts_with(b"MM\0*") { + return None; + } + let u16_at = |at: usize| -> Option { + let b: [u8; 2] = bytes.get(at..at.checked_add(2)?)?.try_into().ok()?; + Some(if le { u16::from_le_bytes(b) } else { u16::from_be_bytes(b) }) + }; + let u32_at = |at: usize| -> Option { + let b: [u8; 4] = bytes.get(at..at.checked_add(4)?)?.try_into().ok()?; + Some(if le { u32::from_le_bytes(b) } else { u32::from_be_bytes(b) }) + }; + let ifd = usize::try_from(u32_at(4)?).ok()?; + let mut out = bytes.to_vec(); + let mut changed = false; + for i in 0..usize::from(u16_at(ifd)?) { + let e = ifd.checked_add(i.checked_mul(12)?.checked_add(2)?)?; + let (Some(tag), Some(ty), Some(count)) = (u16_at(e), u16_at(e.checked_add(2)?), u32_at(e.checked_add(4)?)) else { break }; + if tag != 262 || count != 1 { + continue; + } + // The value sits in the entry, in the file's byte order. + let one: &[u8] = match (ty, le) { + (3, true) => &[1, 0], + (3, false) => &[0, 1], + (4, true) => &[1, 0, 0, 0], + (4, false) => &[0, 0, 0, 1], + _ => continue, + }; + let at = e.checked_add(8)?; + out.get_mut(at..at.checked_add(one.len())?)?.copy_from_slice(one); + changed = true; + } + changed.then_some(out) +} + +/// The ExtraSamples values of the image `d` reads, one for each sample after its color, in order: +/// 0 not alpha, 1 associated alpha, 2 unassociated alpha. Empty without the tag. +fn extra_samples(d: &mut tiff::decoder::Decoder>) -> Vec { + d.find_tag_unsigned_vec::(tiff::tags::Tag::ExtraSamples).ok().flatten().unwrap_or_default() +} + +/// Does `kind`, the color type of the TIFF `d` reads, hold inks that [`ImageBlob::cmyk`] reads: +/// CMYK of 8 or 16 bits, with no extra sample that the file names as alpha? The decoder gives a +/// CMYK color type to a file whose alpha follows another extra sample. +fn cmyk_inks(kind: tiff::ColorType, d: &mut tiff::decoder::Decoder>) -> bool { + matches!(kind, tiff::ColorType::CMYK(8 | 16)) && !extra_samples(d).iter().any(|e| matches!(e, 1 | 2)) +} + /// Does the TIFF `d` reads store one plane per channel (PlanarConfiguration 2)? fn planar(d: &mut tiff::decoder::Decoder>) -> bool { d.find_tag_unsigned::(tiff::tags::Tag::PlanarConfiguration).ok().flatten().is_some_and(|p| p != 1) @@ -265,10 +320,11 @@ struct CmykSource { } /// The samples of CMYK TIFF `bytes` (8 or 16 bits), their inks together or one plane per ink, with -/// the TIFF's CMYK ICC profile; `None` for other images and ones larger than [`MAX_CMYK_PIXELS`]. +/// the TIFF's CMYK ICC profile; `None` for other images, CMYK ones with alpha and ones larger than +/// [`MAX_CMYK_PIXELS`]. fn tiff_source(bytes: &[u8]) -> Option { let (kind, mut d) = tiff(bytes)?; - if !matches!(kind, tiff::ColorType::CMYK(8 | 16)) { + if !cmyk_inks(kind, &mut d) { return None; } let (width, height) = d.dimensions().ok()?; @@ -358,13 +414,13 @@ impl ImageBlob { /// Does the image hold CMYK samples (a four-component JPEG or a CMYK TIFF)? Reads only its /// header. pub fn is_cmyk(&self) -> bool { - jpeg_components(&self.bytes) == Some(4) || tiff(&self.bytes).is_some_and(|(t, _)| matches!(t, tiff::ColorType::CMYK(8 | 16))) + jpeg_components(&self.bytes) == Some(4) || tiff(&self.bytes).is_some_and(|(t, mut d)| cmyk_inks(t, &mut d)) } /// Does the image hold CMYK samples of 16 bits (a CMYK TIFF), which [`Self::cmyk`] gives at 8 /// bits? Reads only its header. pub fn is_cmyk16(&self) -> bool { - tiff(&self.bytes).is_some_and(|(t, _)| matches!(t, tiff::ColorType::CMYK(16))) + tiff(&self.bytes).is_some_and(|(t, mut d)| matches!(t, tiff::ColorType::CMYK(16)) && cmyk_inks(t, &mut d)) } /// The width and height a JPEG or TIFF says it has, for any color type. Reads only its header. @@ -483,7 +539,7 @@ fn jpeg_inks(bytes: &[u8]) -> Option { fn tiff_inks(bytes: &[u8]) -> Option { let (kind, mut d) = tiff(bytes)?; let (w, h) = d.dimensions().ok()?; - if !matches!(kind, tiff::ColorType::CMYK(8 | 16)) { + if !cmyk_inks(kind, &mut d) { return None; } let n = usize::try_from(pixels(w, h)?).ok()?; @@ -527,31 +583,46 @@ pub fn turned_cmyk(bytes: &[u8], orientation: image::metadata::Orientation, ppi: } /// A TIFF whose pixels have samples after their colour, which the image decoder doesn't read at -/// all, as RGBA pixels: CMYK with an alpha channel (5 samples), each colour converted by `rgb` (ink -/// amounts 0..1 → sRGB 0..1; the inks can't be kept with the transparency, so they show as RGB), -/// and grayscale with extra samples, of which the first is the alpha when the file says so (other -/// channels are left out). Associated (premultiplied) alpha is divided back out, and a pixel with -/// no associated alpha has no color. 16-bit samples are converted at 16 bits, and only the result -/// is rounded to 8 bits. The samples may be stored together or one plane per channel. `None` for -/// other images and ones larger than [`MAX_CMYK_PIXELS`]. +/// all, as RGBA pixels: CMYK with an alpha channel, each color converted by `rgb` (ink amounts +/// 0..1 → sRGB 0..1; the inks can't be kept with the transparency, so they show as RGB), and +/// grayscale with extra samples. The alpha is the first extra sample whose ExtraSamples value +/// names it (1 or 2), whatever extra samples come before it; the other extra samples are left out, +/// and without such a value the pixels are opaque. A CMYK file with a fifth sample and no +/// ExtraSamples tag has that sample as unassociated alpha. Associated (premultiplied) alpha is +/// divided back out, and a pixel with no associated alpha has no color. 16-bit samples are +/// converted at 16 bits, and only the result is rounded to 8 bits. The samples may be stored +/// together or one plane per channel. `None` for other images, CMYK ones without alpha (their inks +/// are read by [`ImageBlob::cmyk`]) and ones larger than [`MAX_CMYK_PIXELS`]. pub fn extra_samples_tiff_rgba(bytes: &[u8], rgb: impl Fn([f32; 4]) -> [f32; 3]) -> Option { use tiff::tags::Tag; let (kind, mut d) = tiff(bytes)?; let (w, h) = d.dimensions().ok()?; // 0: white is zero, 1: black is zero (the two grayscales). let photometric = d.find_tag_unsigned::(Tag::PhotometricInterpretation).ok().flatten(); - // ExtraSamples 1: associated alpha (premultiplied colour), 2: unassociated alpha, 0: not alpha. - let extra = d.find_tag_unsigned_vec::(Tag::ExtraSamples).ok().flatten().and_then(|v| v.first().copied()); - // (samples in a pixel, how many of them are its colour, is the next one alpha?) - let (samples, colour, alpha) = match kind { - tiff::ColorType::CMYKA(8 | 16) => (5, 4, true), - tiff::ColorType::Multiband { bit_depth: 8 | 16, num_samples: n @ 2.. } if matches!(photometric, Some(0 | 1)) => { - (usize::from(n), 1, matches!(extra, Some(1 | 2))) - } + let extras = extra_samples(&mut d); + // The first extra sample named as alpha: (its place among the extra samples, is it associated?) + let named = extras.iter().position(|e| matches!(e, 1 | 2)).map(|i| (i, extras.get(i) == Some(&1))); + // (how many of a pixel's samples are its color, the alpha among the extra samples) + let (colour, alpha) = match kind { + tiff::ColorType::CMYKA(8 | 16) => (4, if extras.is_empty() { Some((0, false)) } else { named }), + tiff::ColorType::CMYK(8 | 16) if named.is_some() => (4, named), + tiff::ColorType::Multiband { bit_depth: 8 | 16, num_samples: 2.. } if matches!(photometric, Some(0 | 1)) => (1, named), _ => return None, }; let n = usize::try_from(pixels(w, h)?).ok()?; - let data = read_samples_at_depth(&mut d, n, samples)?; + // The decoder gives a CMYK pixel its inks and at most one extra sample, and doesn't read + // white-is-zero gray with extra samples: those are read as black-is-zero gray, every sample. + let given = usize::from(kind.num_samples()); + let (data, samples) = if photometric == Some(0) || alpha.is_some_and(|(i, _)| colour + i >= given) { + let all = as_black_is_zero(bytes)?; + let (all_kind, mut d) = tiff(&all)?; + let samples = usize::from(all_kind.num_samples()); + (read_samples_at_depth(&mut d, n, samples)?, samples) + } else { + (read_samples_at_depth(&mut d, n, given)?, given) + }; + // (the alpha's sample in a pixel, is it associated?), when the pixel has that sample. + let alpha = alpha.map(|(i, associated)| (colour + i, associated)).filter(|(at, _)| *at < samples); // Sample `i` of the image, 0..1. let level_at = |i: usize| match &data { Samples::Eight(v) => v.get(i).map(|&s| f32::from(s) / 255.0), @@ -564,13 +635,16 @@ pub fn extra_samples_tiff_rgba(bytes: &[u8], rgb: impl Fn([f32; 4]) -> [f32; 3]) }; let mut out = Vec::with_capacity(n.checked_mul(4)?); for first in (0..n).map(|p| p * samples) { - let (opacity, a) = if alpha { (byte_at(first + colour).unwrap_or(u8::MAX), level_at(first + colour).unwrap_or(1.0)) } else { (u8::MAX, 1.0) }; + let (opacity, a) = match alpha { + Some((at, _)) => (byte_at(first + at).unwrap_or(u8::MAX), level_at(first + at).unwrap_or(1.0)), + None => (u8::MAX, 1.0), + }; let level = |s: usize| { let v = level_at(first + s).unwrap_or(0.0); - match extra { - Some(1) if a > 0.0 => (v / a).min(1.0), + match alpha { + Some((_, true)) if a > 0.0 => (v / a).min(1.0), // No associated alpha: the color is zero (TIFF 6.0, Associated Alpha Handling). - Some(1) if alpha => 0.0, + Some((_, true)) => 0.0, _ => v, } }; @@ -875,6 +949,110 @@ mod tests { assert_eq!(gray.into_raw(), [0, 0, 0, 0], "a gray of zero"); } + /// A pixel type of `$n` samples of `$inner`, `$bits` bits each, in color space `$space`. + macro_rules! samples { + ($name:ident, $inner:ty, $space:ident, $bits:literal, $n:literal) => { + struct $name; + impl tiff::encoder::colortype::ColorType for $name { + type Inner = $inner; + const TIFF_VALUE: tiff::tags::PhotometricInterpretation = tiff::tags::PhotometricInterpretation::$space; + const BITS_PER_SAMPLE: &'static [u16] = &[$bits; $n]; + const SAMPLE_FORMAT: &'static [tiff::tags::SampleFormat] = &[tiff::tags::SampleFormat::Uint; $n]; + fn horizontal_predict(row: &[$inner], result: &mut Vec<$inner>) { + result.extend_from_slice(row); + } + } + }; + } + samples!(Cmyk6x8, u8, CMYK, 8, 6); + samples!(Cmyk6x16, u16, CMYK, 16, 6); + samples!(Gray3x8, u8, BlackIsZero, 8, 3); + samples!(WhiteGray2x8, u8, WhiteIsZero, 8, 2); + + /// A one-row TIFF of `C`'s pixels `data`, with the ExtraSamples values `extra`. + fn extras_tiff(extra: &[u16], data: &[C::Inner]) -> Vec + where + [C::Inner]: tiff::encoder::TiffValue, + { + let samples = C::BITS_PER_SAMPLE.len(); + let mut file = Cursor::new(Vec::new()); + let mut enc = tiff::encoder::TiffEncoder::new(&mut file).unwrap(); + let mut img = enc.new_image::(u32::try_from(data.len() / samples).unwrap(), 1).unwrap(); + img.encoder().write_tag(tiff::tags::Tag::ExtraSamples, extra).unwrap(); + img.write_data(data).unwrap(); + file.into_inner() + } + + /// Two pixels of four inks with an alpha sample and another extra sample, the alpha first when + /// `alpha_first`: cyan at an alpha of 128 (or premultiplied, at 128 of cyan when `associated`) + /// with an extra sample of 9, then black, opaque, with an extra sample of 64. + fn inks_alpha_and_extra(alpha_first: bool, associated: bool) -> Vec { + let cyan = if associated { 128 } else { 255 }; + let px = |inks: [u16; 4], alpha: u16, other: u16| { + let extras = if alpha_first { [alpha, other] } else { [other, alpha] }; + [&inks[..], &extras[..]].concat() + }; + [px([cyan, 0, 0, 0], 128, 9), px([0, 0, 0, 255], 255, 64)].concat() + } + + /// A CMYK TIFF whose pixels have alpha and another extra sample reads the sample its + /// ExtraSamples names as alpha, first or second, at 8 and 16 bits, and leaves the other out. + #[test] + fn a_cmyk_tiff_with_alpha_and_another_extra_sample_reads_its_alpha() { + let naive = |[c, m, y, k]: [f32; 4]| [(1.0 - c) * (1.0 - k), (1.0 - m) * (1.0 - k), (1.0 - y) * (1.0 - k)]; + for extra in [[1, 0], [2, 0], [0, 1], [0, 2]] { + let data = inks_alpha_and_extra(extra[0] != 0, extra.contains(&1)); + let eight: Vec = data.iter().map(|&v| u8::try_from(v).unwrap()).collect(); + let sixteen: Vec = data.iter().map(|&v| v * 257).collect(); + for (bits, bytes) in [(8, extras_tiff::(&extra, &eight)), (16, extras_tiff::(&extra, &sixteen))] { + let px = extra_samples_tiff_rgba(&bytes, naive).unwrap_or_else(|| panic!("{extra:?}, {bits} bits: reads")); + assert_eq!(px.into_raw(), [0, 255, 255, 128, 0, 0, 0, 255], "{extra:?}, {bits} bits: cyan at half alpha, then black"); + assert!(stored_cmyk_tiff(&bytes, None).is_none(), "{extra:?}, {bits} bits: the inks can't be kept with the alpha"); + assert!(!ImageBlob::new("image/tiff", bytes).is_cmyk(), "{extra:?}, {bits} bits"); + } + } + // Two extra samples, neither of them alpha: the inks are kept, as with one. + let bytes = extras_tiff::(&[0, 0], &[255, 0, 0, 0, 9, 128, 0, 0, 0, 255, 64, 255]); + assert!(extra_samples_tiff_rgba(&bytes, naive).is_none(), "not alpha: not this reader's"); + assert!(stored_cmyk_tiff(&bytes, None).is_some()); + let b = ImageBlob::new("image/tiff", bytes); + assert!(b.is_cmyk() && !b.is_cmyk16()); + assert_eq!(b.cmyk().map(|i| i.data), Some(vec![255, 0, 0, 0, 0, 0, 0, 255])); + } + + /// A CMYK TIFF of six samples a pixel whose ExtraSamples has only one value: the sample after + /// the inks is alpha only when that value says so, and the sample after it is never alpha. + #[test] + fn a_cmyk_tiff_with_fewer_extra_sample_values_than_samples_reads_only_a_named_alpha() { + let naive = |[c, m, y, k]: [f32; 4]| [(1.0 - c) * (1.0 - k), (1.0 - m) * (1.0 - k), (1.0 - y) * (1.0 - k)]; + let data = [255, 0, 0, 0, 128, 9, 0, 0, 0, 255, 255, 64]; + let read = |extra: u16| extra_samples_tiff_rgba(&extras_tiff::(&[extra], &data), naive).expect("reads").into_raw(); + assert_eq!(read(2), [0, 255, 255, 128, 0, 0, 0, 255], "the sample after the inks is the alpha"); + assert_eq!(read(0), [0, 255, 255, 255, 0, 0, 0, 255], "not alpha: opaque"); + } + + /// A grayscale TIFF whose alpha follows another extra sample reads that alpha. + #[test] + fn a_grayscale_tiff_with_alpha_after_another_extra_sample_reads_its_alpha() { + let read = + |extra: [u16; 2], data: &[u8]| extra_samples_tiff_rgba(&extras_tiff::(&extra, data), |_| [0.0; 3]).expect("reads").into_raw(); + // A gray of 64 at an alpha of 204 (premultiplied: 51), with an extra sample of 9. + assert_eq!(read([0, 2], &[64, 9, 204]), [64, 64, 64, 204], "unassociated"); + assert_eq!(read([0, 1], &[51, 9, 204]), [64, 64, 64, 204], "associated, divided back out"); + assert_eq!(read([2, 0], &[64, 204, 9]), [64, 64, 64, 204], "the alpha first"); + assert_eq!(read([0, 0], &[64, 9, 204]), [64, 64, 64, 255], "no alpha: opaque"); + } + + /// A grayscale TIFF whose white is zero (PhotometricInterpretation 0), with alpha, reads with + /// its levels turned around. + #[test] + fn a_white_is_zero_grayscale_tiff_with_alpha_reads_as_rgba() { + // White, opaque; black at an alpha of 128. + let bytes = extras_tiff::(&[2], &[0, 255, 255, 128]); + let px = extra_samples_tiff_rgba(&bytes, |_| [0.0; 3]).expect("reads"); + assert_eq!(px.into_raw(), [255, 255, 255, 255, 0, 0, 0, 128]); + } + /// A header claiming more tiles than can be counted: (2^32 − 1)² pixels in tiles of one pixel, /// times 2 planes. #[test] diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index bb9dc3711a..b647fa9abf 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -850,7 +850,9 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option { /// they are, with their ink amounts ([`ImageBlob::cmyk`]), except that ones storing one plane per /// ink are written again with their inks together ([`vectorcraft_doc::cmyk::stored_cmyk_tiff`]); /// CMYK TIFFs with an alpha channel, which the decoder can't read, become RGBA in the active color -/// settings' CMYK, as do CMYK Photoshop documents, whose merged image is read ([`psdread`]). +/// settings' CMYK, whichever of their extra channels is the alpha +/// ([`vectorcraft_doc::cmyk::extra_samples_tiff_rgba`]), as do CMYK Photoshop documents, whose +/// merged image is read ([`psdread`]). /// 1-bit TIFFs compressed with CCITT Group 3, which the decoder can't read either, become RGBA /// too ([`vectorcraft_doc::cmyk::group3_tiff_rgba`]). /// Grayscale TIFFs with an alpha channel or other extra channels, which the decoder can't read diff --git a/crates/engine/src/cmd/fileio/tests.rs b/crates/engine/src/cmd/fileio/tests.rs index 7374e26e2b..f7f39e5358 100644 --- a/crates/engine/src/cmd/fileio/tests.rs +++ b/crates/engine/src/cmd/fileio/tests.rs @@ -202,6 +202,38 @@ fn a_16_bit_cmyk_tiff_with_alpha_places_at_16_bits() { } } +/// A CMYK or grayscale TIFF whose alpha follows another extra sample opens and places with that +/// alpha, at 8 and 16 bits, chunky and planar; a CMYK one is not kept as inks. +#[test] +fn a_tiff_with_alpha_after_another_extra_sample_places_with_its_alpha() { + let none = vec![0u16; 6]; + let full = vec![255u16; 6]; + let other = vec![9u16, 8, 7, 6, 5, 4]; + let alpha = vec![255u16, 128, 0, 255, 64, 1]; + let cases = [ + ("CMYK", 5, vec![full.clone(), none.clone(), none.clone(), none.clone(), other.clone(), alpha.clone()]), + ("gray", 1, vec![full.clone(), other.clone(), alpha.clone()]), + ]; + for (what, photometric, channels) in cases { + for bits in [8, 16] { + let wide: Vec> = channels.iter().map(|ch| ch.iter().map(|v| if bits == 16 { v * 257 } else { *v }).collect()).collect(); + for planar in [false, true] { + let what = format!("{what}, {bits} bits, planar {planar}"); + let file = hand_tiff(photometric, bits, &[0, 2], planar, &wide); + let (inks, rgba) = kept(&what, &file); + assert_eq!(inks, None, "{what}: shown as RGB with its alpha"); + let alphas: Vec = rgba.iter().skip(3).step_by(4).copied().collect(); + assert_eq!(alphas, [255, 128, 0, 255, 64, 1], "{what}: the alpha is the second extra sample"); + let mut s = session(100.0, 100.0, 1); + s.execute("file.place", &json!({"name": "a.tif", "dataBase64": vectorcraft_format::base64_encode(&file)})).unwrap(); + let blob = &s.doc().unwrap().doc.images[&image_of(&s).key]; + let placed = image::load_from_memory(&blob.bytes).unwrap().to_rgba8().into_raw(); + assert_eq!(placed, rgba, "{what}: Place reads it as Open does"); + } + } + } +} + /// A planar TIFF whose header claims more strips than the decoder can count (here 2^31 + 1 rows /// a strip each, times 5 planes) is refused as too large to draw, without a panic. #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 9ba8866a8c..4ae7bd7bc3 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1783,6 +1783,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - EPS and DXF in and out, EMF/WMF in and out; PNG (with PNG-8), JPEG, WebP, GIF, TIFF, BMP, Targa and layered PSD export; grayscale TIFFs with an alpha channel or other extra channels place, relink and open, the alpha as the image's transparency (#1466 in part); PSD and PSB files open and place, linked or embedded, as their merged image in every colour mode and depth (#918). EPS import runs a PostScript Level 3 interpreter written from the PostScript Language Reference: resource categories and `resourceforall`, local and global VM (`currentglobal`/`setglobal`/`gcheck`), `clipsave`/`cliprestore`, subarrays and substrings that share storage, the standard dictionaries in `systemdict`, `dictstack`, `internaldict`, executable filters and strings, `load` by any key, `//name` immediate names, `token`, `execform`, user paths, `cshow`, `rootfont`, `cachestatus`, colour rendering and halftone queries, file `status` and data read with `flushfile`, and `pdfmark` marks dropped (Discord feedback, #466, #469, #474). Masked images (`ImageType 3` in its three interleavings) and reusable streams are read, and an image's several data sources are read in turn, as the reference defines (procedures that read one file get their own rows: such images came in banded, #498). `restore` puts dictionaries back as they were at the `save`, so programs that count their saves in a dictionary read to their end (part of #505). Tiling patterns come in as pattern swatches, uncoloured ones too; Type 3 fonts' glyphs as their outlines, spaced by `ashow`/`widthshow`/`xshow`/`kshow`; mesh and function-based shadings (types 1, 4–7) as gradient meshes; sampled functions (type 0) and Flate/LZW predictors are read. It is tested with programs written from the specification in the ways common generators use these features; Inkscape/cairo EPS files open as vectors. When a file's PostScript still can't be read, it opens as its TIFF preview, its Windows metafile preview (as vectors) or its EPSI preview, and the warning (in the status bar, `document.open`/`app.open`/MCP `open_file` replies and `vectorcraft-cli info`) names the error, the operator that raised it and the procedures it ran in. Legacy PostScript `.ai` files (Illustrator 3–8, written with the prolog that defines their operators) keep their groups and nested groups (`u` … `U`), between and inside clipping groups; EPS and EMF/WMF import nest clips (and groups) at most 128 deep, so a hostile file can't exhaust the stack. DXF TEXT justified Fit or Aligned spans its two points (stretched, or scaled as a whole). PDF export writes type as real, searchable text in embedded subset fonts by default, as Illustrator's PDF presets do (Convert Text to Outlines is an option; printer's marks stay shapes), so text-heavy PDFs stay small (#733). DXF export writes each fill as its outlines followed by its hatch, so laser and cutter software, which skips hatches, gets filled art and type too (#546). - TIFFs that store each channel as its own plane (PlanarConfiguration 2) place, relink and open as the same image stored pixel by pixel does, 8 and 16 bits: grayscale with an alpha channel or other extra channels, and CMYK with or without them. A planar CMYK TIFF keeps its ink amounts and is stored as a CMYK TIFF with each pixel's inks together, at the file's resolution. A TIFF whose header claims more strips or tiles than can be counted is refused as too large to draw (#1466 in part; `crates/engine/src/cmd/fileio/tests.rs`). - A 16-bit CMYK or grayscale TIFF with an alpha channel is converted from its 16-bit samples, and only the resulting color and alpha are rounded to 8 bits; associated alpha is divided out at 16 bits, and a pixel whose associated alpha is zero has no color. [TIFF 6.0](https://printtechnologies.org/standards/files/tiff-v6.pdf) gives extra samples the depth in BitsPerSample, and its Associated Alpha Handling section states the arithmetic and the zero-alpha rule for RGB data; applying them to CMYK and gray samples is VectorCraft's own rule. Each sample was cut to its high byte first, so a faint ink or a low alpha could be lost (`crates/doc/src/cmyk.rs`, `crates/engine/src/cmd/fileio/tests.rs`). + - A CMYK or grayscale TIFF whose alpha channel comes after another extra channel places and opens with that alpha, 8 and 16 bits, chunky or planar, and the other extra channels are left out. A channel that the file does not mark as alpha is not read as transparency, even when its ExtraSamples tag has fewer values than the file has extra channels, and a white-is-zero grayscale TIFF with an alpha channel opens too. [TIFF 6.0](https://printtechnologies.org/standards/files/tiff-v6.pdf) gives each extra channel its own ExtraSamples value, in order (pp. 31–32), and tells readers to skip extra channels they do not use (p. 27); reading the first channel marked as alpha is VectorCraft's own rule (`crates/doc/src/cmyk.rs`, `crates/engine/src/cmd/fileio/tests.rs`). - 1-bit TIFFs compressed with CCITT Group 3 (ITU-T T.4) place, relink and open: Compression 2 (modified Huffman) and Compression 3 with one-dimensional rows or, with T4Options bit 0, two-dimensional ones, with or without fill bits, in strips or tiles, with either FillOrder and either polarity. Rows in T.4's uncompressed mode are not read. A file whose pixels would take more than the decoding allowance as RGBA is refused as too large to draw (#1466 in part; `crates/engine/src/cmd/fileio/tests.rs`). - EPS and PostScript import keeps a CMYK image's ink amounts, as PDF import does: the samples of `image` and `colorimage` in a CMYK color space, and of a CMYK JPEG read through `DCTDecode`, come in as a CMYK TIFF, read through the image's Decode array, and the pixels a `MaskColor` or `ImageType 3` mask hides become a grayscale opacity mask (`crates/eps/src/import/tests_images.rs`). Such images came in as RGB PNGs. - EPS and PostScript import reads image data through `CCITTFaxDecode`: Group 4 (ITU-T T.6) and Group 3 one-dimensional and mixed (ITU-T T.4) data, with the filter's `K`, `Columns`, `Rows`, `EndOfBlock`, `EndOfLine`, `EncodedByteAlign` and `BlackIs1` parameters, decodes to 1-bit rows for `image` and `imagemask`. Damaged data keeps the rows decoded before it (damage in the first row is a PostScript `ioerror`), and parameters out of range or past the 256 MiB limit on decoded data are refused (`crates/eps/src/import/tests_images.rs`). Reading such a file stopped at an error naming the filter, and the file opened from a fallback, such as its preview or the art drawn before the image, or did not open. From 9954ad8a4d7e97de4e54eaee3c914e7df4aeb4d0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 08:28:44 -0800 Subject: [PATCH 12/47] Canvas: the monitor profile conversion skips artboards outside the frame convert_over looked up every artboard of the document for each row with a translucent pixel, so a frame of 2,160 rows over a document with 1,000 artboards made about 2.16 million lookups. Over::new now takes the frame's size and keeps only the artboards whose rectangles meet the frame in the document, a pixel wider on every side. --- crates/ui-egui/src/display_profile.rs | 66 ++++++++++++++++++++++++--- 1 file changed, 60 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/display_profile.rs b/crates/ui-egui/src/display_profile.rs index be46424ec9..b3f10ab27e 100644 --- a/crates/ui-egui/src/display_profile.rs +++ b/crates/ui-egui/src/display_profile.rs @@ -285,18 +285,29 @@ struct Over<'a> { } impl<'a> Over<'a> { - /// None when the backdrop has no paper, or `view` (the document → the pixels) can't be undone. - fn new(t: &'a DisplayTransform, b: &Backdrop, view: Affine, zoom: f64) -> Option { + /// For a frame of `width` × `height` pixels. None when the backdrop has no paper, or `view` + /// (the document → the pixels) can't be undone. The artboards that lie wholly outside the + /// frame are left out, so a row looks only at the artboards in view. + fn new(t: &'a DisplayTransform, b: &Backdrop, view: Affine, zoom: f64, (width, height): (usize, usize)) -> Option { let det = view.determinant(); if (b.everywhere.is_none() && b.artboards.is_empty()) || !det.is_finite() || det.abs() < 1e-12 { return None; } let paper = |srgb: [u8; 3]| Paper { srgb, shown: t.apply8(srgb) }; - let boards = b.artboards.iter().map(|&(r, color)| Board { rect: r.abs(), origin: r.origin(), paper: paper(color) }).collect(); + let to_doc = view.inverse(); + // The frame in the document, a pixel wider on every side than its pixels' centers reach. + let frame = to_doc.transform_rect_bbox(Rect::new(-1.0, -1.0, width as f64 + 1.0, height as f64 + 1.0)); + let in_view = |r: &Rect| r.x0 <= frame.x1 && frame.x0 <= r.x1 && r.y0 <= frame.y1 && frame.y0 <= r.y1; + let boards = b + .artboards + .iter() + .map(|&(r, color)| Board { rect: r.abs(), origin: r.origin(), paper: paper(color) }) + .filter(|b| in_view(&b.rect)) + .collect(); let zoom = if zoom.is_finite() && zoom > 0.0 { zoom } else { 1.0 }; Some(Self { t, - to_doc: view.inverse(), + to_doc, everywhere: b.everywhere.map(paper), boards, grid: b.grid.map(|([a, c], cell)| ([paper(a), paper(c)], (f64::from(cell) / zoom).max(5e-10))), @@ -449,7 +460,9 @@ impl<'a> Over<'a> { pub(crate) fn convert_over(t: Option<&DisplayTransform>, pixels: &mut [u8], width: u32, view: Affine, backdrop: Option<(&Backdrop, f64)>) { let Some(t) = t else { return }; let width = width as usize; - let over = backdrop.filter(|_| width > 0 && pixels.len().is_multiple_of(width * 4)).and_then(|(b, zoom)| Over::new(t, b, view, zoom)); + let over = backdrop + .filter(|_| width > 0 && pixels.len().is_multiple_of(width * 4)) + .and_then(|(b, zoom)| Over::new(t, b, view, zoom, (width, pixels.len() / (width * 4)))); let Some(over) = over else { return convert(Some(t), pixels) }; #[cfg(not(target_arch = "wasm32"))] { @@ -718,8 +731,49 @@ pub(crate) mod tests { } } let mut one = big.clone(); - Over::new(&t, &b, Affine::IDENTITY, 1.0).unwrap().rows(&mut one, 0, w); + Over::new(&t, &b, Affine::IDENTITY, 1.0, (w, h)).unwrap().rows(&mut one, 0, w); convert_over(Some(&t), &mut big, w as u32, Affine::IDENTITY, Some((&b, 1.0))); assert_eq!(big, one); } + + #[test] + fn artboards_outside_the_frame_are_not_looked_up() { + let t = DisplayTransform::from_icc(&p3()).unwrap(); + let half = [128, 0, 0, 128]; + // A row of 1,000 artboards 30 points apart, each 20 wide and 40 high. + let artboards: Vec<(Rect, [u8; 3])> = (0..1000u32) + .map(|k| { + let x = f64::from(k) * 30.0; + (Rect::new(x, 0.0, x + 20.0, 40.0), [255 - (k % 200) as u8, 240, 230]) + }) + .collect(); + let b = Backdrop { everywhere: None, artboards: artboards.clone(), grid: None }; + // A turned frame of 64 × 48 pixels over the artboards near x = 15,000. + let view = Affine::rotate(0.4) * Affine::translate((-15_000.0, -5.0)); + let (w, h) = (64, 48); + let over = Over::new(&t, &b, view, 1.0, (w, h)).unwrap(); + assert!((1..=4).contains(&over.boards.len()), "{} artboards kept", over.boards.len()); + // Each pixel still uses the artboard its center is on. + let mut px = row(w * h, half); + convert_over(Some(&t), &mut px, w as u32, view, Some((&b, 1.0))); + let to_doc = view.inverse(); + let mut on_paper = 0; + for i in 0..w * h { + let p = to_doc * Point::new((i % w) as f64 + 0.5, (i / w) as f64 + 0.5); + let mut want = half.to_vec(); + match artboards.iter().rev().find(|(r, _)| r.contains(p)) { + Some(&(_, paper)) => { + let one = Backdrop { everywhere: Some(paper), artboards: vec![], grid: None }; + convert_over(Some(&t), &mut want, 1, Affine::IDENTITY, Some((&one, 1.0))); + on_paper += 1; + } + None => t.apply_premultiplied(&mut want), + } + assert_eq!(&px[i * 4..i * 4 + 4], &want[..], "pixel {i} at {p:?}"); + } + assert!(on_paper > 100 && on_paper < w * h, "{on_paper} pixels on the artboards"); + // A frame over none of the artboards keeps none, and converts as without a backdrop. + let away = Affine::translate((0.0, -500.0)); + assert_eq!(Over::new(&t, &b, away, 1.0, (w, h)).map(|o| o.boards.len()), Some(0)); + } } From f5312d795fa2405162c5aa2984c031b30369a041 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 09:34:42 -0800 Subject: [PATCH 13/47] TIFF: stored CMYK TIFFs with alpha keep their inks; wide and large files read A document saved with a CMYK TIFF whose alpha follows another extra sample keeps it as a CMYK image with its ink amounts, so EPS and PDF export write the same inks as before; Open and Place still read such a file with its alpha. - A CMYK file with two or more samples past its inks and its ExtraSamples values, which the decoder gives no color type, reads the alpha that one of those values names, and its Orientation tag is read. - A TIFF with extra samples whose samples take more than the decoder's 256 MB buffer reads, up to the decoding allowance. - A file read as black-is-zero gray is read in place instead of copied. --- crates/doc/src/cmyk.rs | 251 +++++++++++++++++++++----- crates/engine/src/cmd/fileio/tests.rs | 5 +- docs/target-app-parity.md | 2 +- 3 files changed, 214 insertions(+), 44 deletions(-) diff --git a/crates/doc/src/cmyk.rs b/crates/doc/src/cmyk.rs index 94f1017347..032fcce596 100644 --- a/crates/doc/src/cmyk.rs +++ b/crates/doc/src/cmyk.rs @@ -124,20 +124,24 @@ pub fn oversized_tiff(bytes: &[u8]) -> Option<(u32, u32)> { (tiles || strips).then_some((width, height)) } -/// The color type of TIFF `bytes` and its decoder; `None` for [`oversized_tiff`] images too. -pub(crate) fn tiff(bytes: &[u8]) -> Option<(tiff::ColorType, tiff::decoder::Decoder>)> { +/// The decoder of TIFF `bytes`' first image; `None` for other bytes and [`oversized_tiff`] images. +fn tiff_decoder(bytes: &[u8]) -> Option>> { if !is_tiff(bytes) || oversized_tiff(bytes).is_some() { return None; } - let mut d = tiff::decoder::Decoder::new(Cursor::new(bytes)).ok()?; + tiff::decoder::Decoder::new(Cursor::new(bytes)).ok() +} + +/// The color type of TIFF `bytes` and its decoder; `None` for [`oversized_tiff`] images too. +pub(crate) fn tiff(bytes: &[u8]) -> Option<(tiff::ColorType, tiff::decoder::Decoder>)> { + let mut d = tiff_decoder(bytes)?; Some((d.colortype().ok()?, d)) } /// The Orientation tag of TIFF `bytes`' first image, of any unsigned type; `None` for other images -/// and TIFFs without one. Reads only its header. +/// and TIFFs without one. Reads only its header, for any color type. pub fn tiff_orientation(bytes: &[u8]) -> Option { - let (_, mut d) = tiff(bytes)?; - d.find_tag_unsigned::(tiff::tags::Tag::Orientation).ok().flatten() + tiff_decoder(bytes)?.find_tag_unsigned::(tiff::tags::Tag::Orientation).ok().flatten() } /// The EXIF orientation of encoded image `bytes` when it turns or flips the pixels; `None` when @@ -155,12 +159,46 @@ pub fn exif_orientation(bytes: &[u8]) -> Option { decoded().or_else(tagged).filter(|o| *o != Orientation::NoTransforms) } -/// TIFF `bytes` with the PhotometricInterpretation (tag 262) of their first image set to 1 (black -/// is zero) in each of its entries that holds one SHORT or LONG value. The decoder gives every -/// sample of a grayscale image's pixels, in the order the file stores them, where it gives a CMYK -/// image's inks and at most the first extra sample, and doesn't read a white-is-zero image with -/// extra samples. `None` for bytes that aren't a TIFF and when the first image has no such entry. -fn as_black_is_zero(bytes: &[u8]) -> Option> { +/// TIFF bytes as a reader sees them with some of them replaced: each patch is an offset and the +/// bytes read there instead, at most four, in order of offset without overlaps. The file is not +/// copied. +struct Patched<'a> { + bytes: Cursor<&'a [u8]>, + patches: Vec<(usize, &'static [u8])>, +} + +impl std::io::Read for Patched<'_> { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + let start = usize::try_from(self.bytes.position()).unwrap_or(usize::MAX); + let read = std::io::Read::read(&mut self.bytes, buf)?; + let got = buf.get_mut(..read).unwrap_or_default(); + let end = start.saturating_add(read); + // The patches are in order and apart, and each is at most four bytes long. + let first = self.patches.partition_point(|&(at, _)| at.saturating_add(4) <= start); + for &(at, with) in self.patches.get(first..).unwrap_or_default().iter().take_while(|&&(at, _)| at < end) { + for (k, &b) in with.iter().enumerate() { + if let Some(slot) = at.checked_add(k).and_then(|i| i.checked_sub(start)).and_then(|i| got.get_mut(i)) { + *slot = b; + } + } + } + Ok(read) + } +} + +impl std::io::Seek for Patched<'_> { + fn seek(&mut self, to: std::io::SeekFrom) -> std::io::Result { + std::io::Seek::seek(&mut self.bytes, to) + } +} + +/// TIFF `bytes` read with the PhotometricInterpretation (tag 262) of their first image set to 1 +/// (black is zero) in each of its entries that holds one SHORT or LONG value. The decoder gives +/// every sample of a grayscale image's pixels, in the order the file stores them, where it gives a +/// CMYK image's inks and at most the first extra sample, and doesn't read a white-is-zero image +/// with extra samples. `None` for bytes that aren't a TIFF and when the first image has no such +/// entry. +fn as_black_is_zero(bytes: &[u8]) -> Option> { let le = bytes.starts_with(b"II*\0"); if !le && !bytes.starts_with(b"MM\0*") { return None; @@ -174,8 +212,7 @@ fn as_black_is_zero(bytes: &[u8]) -> Option> { Some(if le { u32::from_le_bytes(b) } else { u32::from_be_bytes(b) }) }; let ifd = usize::try_from(u32_at(4)?).ok()?; - let mut out = bytes.to_vec(); - let mut changed = false; + let mut patches = Vec::new(); for i in 0..usize::from(u16_at(ifd)?) { let e = ifd.checked_add(i.checked_mul(12)?.checked_add(2)?)?; let (Some(tag), Some(ty), Some(count)) = (u16_at(e), u16_at(e.checked_add(2)?), u32_at(e.checked_add(4)?)) else { break }; @@ -183,7 +220,7 @@ fn as_black_is_zero(bytes: &[u8]) -> Option> { continue; } // The value sits in the entry, in the file's byte order. - let one: &[u8] = match (ty, le) { + let one: &'static [u8] = match (ty, le) { (3, true) => &[1, 0], (3, false) => &[0, 1], (4, true) => &[1, 0, 0, 0], @@ -191,10 +228,10 @@ fn as_black_is_zero(bytes: &[u8]) -> Option> { _ => continue, }; let at = e.checked_add(8)?; - out.get_mut(at..at.checked_add(one.len())?)?.copy_from_slice(one); - changed = true; + bytes.get(at..at.checked_add(one.len())?)?; + patches.push((at, one)); } - changed.then_some(out) + (!patches.is_empty()).then(|| Patched { bytes: Cursor::new(bytes), patches }) } /// The ExtraSamples values of the image `d` reads, one for each sample after its color, in order: @@ -203,13 +240,27 @@ fn extra_samples(d: &mut tiff::decoder::Decoder>) -> Vec { d.find_tag_unsigned_vec::(tiff::tags::Tag::ExtraSamples).ok().flatten().unwrap_or_default() } -/// Does `kind`, the color type of the TIFF `d` reads, hold inks that [`ImageBlob::cmyk`] reads: -/// CMYK of 8 or 16 bits, with no extra sample that the file names as alpha? The decoder gives a -/// CMYK color type to a file whose alpha follows another extra sample. +/// Does `kind`, the color type of the TIFF `d` reads, hold inks that Open and Place keep: CMYK of 8 +/// or 16 bits, with no extra sample that the file names as alpha? The decoder gives a CMYK color +/// type to a file whose alpha follows another extra sample. [`ImageBlob::cmyk`] reads the inks of +/// such a file all the same: a document saved with one as a CMYK image keeps it. fn cmyk_inks(kind: tiff::ColorType, d: &mut tiff::decoder::Decoder>) -> bool { matches!(kind, tiff::ColorType::CMYK(8 | 16)) && !extra_samples(d).iter().any(|e| matches!(e, 1 | 2)) } +/// `d` with room to decode `n` pixels of `per` samples of `bits` bits each, when they take more +/// than the decoder's own limit (256 MB of samples); `None` when they take more than +/// [`crate::MAX_RASTER_ALLOC`]. +fn with_room(d: tiff::decoder::Decoder, n: usize, per: usize, bits: u8) -> Option> { + let need = n.checked_mul(per)?.checked_mul(usize::from(bits.div_ceil(8)))?; + if u64::try_from(need).ok()? > crate::MAX_RASTER_ALLOC { + return None; + } + let mut limits = tiff::decoder::Limits::default(); + limits.decoding_buffer_size = limits.decoding_buffer_size.max(need); + Some(d.with_limits(limits)) +} + /// Does the TIFF `d` reads store one plane per channel (PlanarConfiguration 2)? fn planar(d: &mut tiff::decoder::Decoder>) -> bool { d.find_tag_unsigned::(tiff::tags::Tag::PlanarConfiguration).ok().flatten().is_some_and(|p| p != 1) @@ -251,7 +302,7 @@ enum SampleSlice<'a> { } /// [`read_samples`], keeping 16-bit samples at 16 bits. -fn read_samples_at_depth(d: &mut tiff::decoder::Decoder>, n: usize, per: usize) -> Option { +fn read_samples_at_depth(d: &mut tiff::decoder::Decoder, n: usize, per: usize) -> Option { let mut buf = tiff::decoder::DecodingResult::U8(Vec::new()); let layout = d.read_image_to_buffer(&mut buf).ok()?; match buf { @@ -414,13 +465,13 @@ impl ImageBlob { /// Does the image hold CMYK samples (a four-component JPEG or a CMYK TIFF)? Reads only its /// header. pub fn is_cmyk(&self) -> bool { - jpeg_components(&self.bytes) == Some(4) || tiff(&self.bytes).is_some_and(|(t, mut d)| cmyk_inks(t, &mut d)) + jpeg_components(&self.bytes) == Some(4) || tiff(&self.bytes).is_some_and(|(t, _)| matches!(t, tiff::ColorType::CMYK(8 | 16))) } /// Does the image hold CMYK samples of 16 bits (a CMYK TIFF), which [`Self::cmyk`] gives at 8 /// bits? Reads only its header. pub fn is_cmyk16(&self) -> bool { - tiff(&self.bytes).is_some_and(|(t, mut d)| matches!(t, tiff::ColorType::CMYK(16)) && cmyk_inks(t, &mut d)) + tiff(&self.bytes).is_some_and(|(t, _)| matches!(t, tiff::ColorType::CMYK(16))) } /// The width and height a JPEG or TIFF says it has, for any color type. Reads only its header. @@ -539,7 +590,7 @@ fn jpeg_inks(bytes: &[u8]) -> Option { fn tiff_inks(bytes: &[u8]) -> Option { let (kind, mut d) = tiff(bytes)?; let (w, h) = d.dimensions().ok()?; - if !cmyk_inks(kind, &mut d) { + if !matches!(kind, tiff::ColorType::CMYK(8 | 16)) { return None; } let n = usize::try_from(pixels(w, h)?).ok()?; @@ -549,8 +600,8 @@ fn tiff_inks(bytes: &[u8]) -> Option { /// CMYK TIFF `bytes` that no orientation turns ([`turned_cmyk`] stores the others) as Open and /// Place store them: as they are, or, when they store one plane per ink, which the image decoder /// doesn't read, their inks together in a CMYK TIFF with the resolution `ppi`, at the 8 or 16 bits -/// the file has, carrying the file's CMYK ICC profile. `None` for other images and for CMYK TIFFs -/// whose inks [`ImageBlob::cmyk`] doesn't read. +/// the file has, carrying the file's CMYK ICC profile. `None` for other images, for CMYK TIFFs +/// with an extra sample named as alpha and for ones whose inks [`ImageBlob::cmyk`] doesn't read. pub fn stored_cmyk_tiff(bytes: &[u8], ppi: Option<(f64, f64)>) -> Option> { let source = tiff_source(bytes)?; let (_, mut d) = tiff(bytes)?; @@ -564,7 +615,8 @@ pub fn stored_cmyk_tiff(bytes: &[u8], ppi: Option<(f64, f64)>) -> Option /// inks turned and written again as a CMYK TIFF with the resolution `ppi` of the turned pixels, /// with the turned width and height. A TIFF keeps its 8 or 16 bits, a JPEG has 8, and both keep /// their CMYK ICC profile (a JPEG's put together from all its APP2 segments). `None` for other -/// images and for CMYK images whose inks [`ImageBlob::cmyk`] doesn't read. +/// images, for CMYK TIFFs with an extra sample named as alpha and for CMYK images whose inks +/// [`ImageBlob::cmyk`] doesn't read. pub fn turned_cmyk(bytes: &[u8], orientation: image::metadata::Orientation, ppi: Option<(f64, f64)>) -> Option<(Vec, (u32, u32))> { let CmykSource { width, height, samples, icc } = if bytes.starts_with(&[0xFF, 0xD8]) { jpeg_source(bytes) } else { tiff_source(bytes) }?; // Four inks to a pixel, turned as four channels of the same depth are. @@ -591,35 +643,43 @@ pub fn turned_cmyk(bytes: &[u8], orientation: image::metadata::Orientation, ppi: /// ExtraSamples tag has that sample as unassociated alpha. Associated (premultiplied) alpha is /// divided back out, and a pixel with no associated alpha has no color. 16-bit samples are /// converted at 16 bits, and only the result is rounded to 8 bits. The samples may be stored -/// together or one plane per channel. `None` for other images, CMYK ones without alpha (their inks -/// are read by [`ImageBlob::cmyk`]) and ones larger than [`MAX_CMYK_PIXELS`]. +/// together or one plane per channel. A CMYK file with two or more samples past its inks and its +/// ExtraSamples values is read when one of those values names an alpha. `None` for other images, +/// CMYK ones without alpha (their inks are read by [`ImageBlob::cmyk`]), ones larger than +/// [`MAX_CMYK_PIXELS`] and ones whose samples take more than [`crate::MAX_RASTER_ALLOC`]. pub fn extra_samples_tiff_rgba(bytes: &[u8], rgb: impl Fn([f32; 4]) -> [f32; 3]) -> Option { use tiff::tags::Tag; - let (kind, mut d) = tiff(bytes)?; + let mut d = tiff_decoder(bytes)?; + // The decoder gives no color type to a CMYK file that has six or more samples besides the + // ones its ExtraSamples values count. + let kind = d.colortype().ok(); let (w, h) = d.dimensions().ok()?; - // 0: white is zero, 1: black is zero (the two grayscales). + // 0: white is zero, 1: black is zero (the two grayscales), 5: CMYK. let photometric = d.find_tag_unsigned::(Tag::PhotometricInterpretation).ok().flatten(); let extras = extra_samples(&mut d); // The first extra sample named as alpha: (its place among the extra samples, is it associated?) let named = extras.iter().position(|e| matches!(e, 1 | 2)).map(|i| (i, extras.get(i) == Some(&1))); + // The samples of a pixel that no ExtraSamples value counts. + let uncounted = d.find_tag_unsigned::(Tag::SamplesPerPixel).ok().flatten().and_then(|all| usize::from(all).checked_sub(extras.len())); // (how many of a pixel's samples are its color, the alpha among the extra samples) let (colour, alpha) = match kind { - tiff::ColorType::CMYKA(8 | 16) => (4, if extras.is_empty() { Some((0, false)) } else { named }), - tiff::ColorType::CMYK(8 | 16) if named.is_some() => (4, named), - tiff::ColorType::Multiband { bit_depth: 8 | 16, num_samples: 2.. } if matches!(photometric, Some(0 | 1)) => (1, named), + Some(tiff::ColorType::CMYKA(8 | 16)) => (4, if extras.is_empty() { Some((0, false)) } else { named }), + Some(tiff::ColorType::CMYK(8 | 16)) if named.is_some() => (4, named), + Some(tiff::ColorType::Multiband { bit_depth: 8 | 16, num_samples: 2.. }) if matches!(photometric, Some(0 | 1)) => (1, named), + None if photometric == Some(5) && named.is_some() && uncounted.is_some_and(|c| c > 5) => (4, named), _ => return None, }; let n = usize::try_from(pixels(w, h)?).ok()?; // The decoder gives a CMYK pixel its inks and at most one extra sample, and doesn't read // white-is-zero gray with extra samples: those are read as black-is-zero gray, every sample. - let given = usize::from(kind.num_samples()); + let given = kind.map_or(0, |k| usize::from(k.num_samples())); let (data, samples) = if photometric == Some(0) || alpha.is_some_and(|(i, _)| colour + i >= given) { - let all = as_black_is_zero(bytes)?; - let (all_kind, mut d) = tiff(&all)?; - let samples = usize::from(all_kind.num_samples()); - (read_samples_at_depth(&mut d, n, samples)?, samples) + let mut d = tiff::decoder::Decoder::new(as_black_is_zero(bytes)?).ok()?; + let tiff::ColorType::Multiband { bit_depth: bits @ (8 | 16), num_samples } = d.colortype().ok()? else { return None }; + let samples = usize::from(num_samples); + (read_samples_at_depth(&mut with_room(d, n, samples, bits)?, n, samples)?, samples) } else { - (read_samples_at_depth(&mut d, n, given)?, given) + (read_samples_at_depth(&mut with_room(d, n, given, kind?.bit_depth())?, n, given)?, given) }; // (the alpha's sample in a pixel, is it associated?), when the pixel has that sample. let alpha = alpha.map(|(i, associated)| (colour + i, associated)).filter(|(at, _)| *at < samples); @@ -966,6 +1026,8 @@ mod tests { } samples!(Cmyk6x8, u8, CMYK, 8, 6); samples!(Cmyk6x16, u16, CMYK, 16, 6); + samples!(Cmyk7x8, u8, CMYK, 8, 7); + samples!(Cmyk8x8, u8, CMYK, 8, 8); samples!(Gray3x8, u8, BlackIsZero, 8, 3); samples!(WhiteGray2x8, u8, WhiteIsZero, 8, 2); @@ -997,6 +1059,9 @@ mod tests { /// A CMYK TIFF whose pixels have alpha and another extra sample reads the sample its /// ExtraSamples names as alpha, first or second, at 8 and 16 bits, and leaves the other out. + /// Open and Place don't keep its inks. A blob that holds the file, as a document saved with it + /// as a CMYK image does, is a CMYK image with those inks when the alpha is the second extra + /// sample. #[test] fn a_cmyk_tiff_with_alpha_and_another_extra_sample_reads_its_alpha() { let naive = |[c, m, y, k]: [f32; 4]| [(1.0 - c) * (1.0 - k), (1.0 - m) * (1.0 - k), (1.0 - y) * (1.0 - k)]; @@ -1008,7 +1073,16 @@ mod tests { let px = extra_samples_tiff_rgba(&bytes, naive).unwrap_or_else(|| panic!("{extra:?}, {bits} bits: reads")); assert_eq!(px.into_raw(), [0, 255, 255, 128, 0, 0, 0, 255], "{extra:?}, {bits} bits: cyan at half alpha, then black"); assert!(stored_cmyk_tiff(&bytes, None).is_none(), "{extra:?}, {bits} bits: the inks can't be kept with the alpha"); - assert!(!ImageBlob::new("image/tiff", bytes).is_cmyk(), "{extra:?}, {bits} bits"); + let b = ImageBlob::new("image/tiff", bytes); + if extra[0] != 0 { + // The decoder gives these the color type of CMYK with alpha. + assert!(!b.is_cmyk() && b.cmyk().is_none(), "{extra:?}, {bits} bits: never stored as inks"); + continue; + } + assert!(b.is_cmyk(), "{extra:?}, {bits} bits: a stored one stays a CMYK image"); + assert_eq!(b.is_cmyk16(), bits == 16, "{extra:?}, {bits} bits"); + let cyan = u8::try_from(data[0]).unwrap(); + assert_eq!(b.cmyk().map(|i| i.data), Some(vec![cyan, 0, 0, 0, 0, 0, 0, 255]), "{extra:?}, {bits} bits: a stored one keeps its inks"); } } // Two extra samples, neither of them alpha: the inks are kept, as with one. @@ -1029,6 +1103,99 @@ mod tests { let read = |extra: u16| extra_samples_tiff_rgba(&extras_tiff::(&[extra], &data), naive).expect("reads").into_raw(); assert_eq!(read(2), [0, 255, 255, 128, 0, 0, 0, 255], "the sample after the inks is the alpha"); assert_eq!(read(0), [0, 255, 255, 255, 0, 0, 0, 255], "not alpha: opaque"); + // Eight samples with two values: the decoder gives the file no color type. The second + // value names the sixth sample as the alpha. + let wide = [255, 0, 0, 0, 9, 128, 17, 18]; + let px = extra_samples_tiff_rgba(&extras_tiff::(&[0, 2], &wide), naive).expect("reads"); + assert_eq!(px.into_raw(), [0, 255, 255, 128], "cyan at the alpha the second value names"); + assert!(extra_samples_tiff_rgba(&extras_tiff::(&[0, 0], &wide), naive).is_none(), "no value names an alpha: not read"); + // Seven samples with two values: the decoder reads it as CMYK with alpha. + let px = extra_samples_tiff_rgba(&extras_tiff::(&[0, 2], &wide[..7]), naive).expect("reads"); + assert_eq!(px.into_raw(), [0, 255, 255, 128], "seven samples: cyan at the alpha the second value names"); + // Its Orientation tag is read too. + let mut file = Cursor::new(Vec::new()); + let mut enc = tiff::encoder::TiffEncoder::new(&mut file).unwrap(); + let mut img = enc.new_image::(1, 1).unwrap(); + img.encoder().write_tag(tiff::tags::Tag::ExtraSamples, &[0u16, 2][..]).unwrap(); + img.encoder().write_tag(tiff::tags::Tag::Orientation, 6u16).unwrap(); + img.write_data(&wide).unwrap(); + let turned = file.into_inner(); + assert_eq!(tiff_orientation(&turned), Some(6)); + assert_eq!(exif_orientation(&turned), Some(image::metadata::Orientation::Rotate90)); + } + + /// A white-is-zero grayscale TIFF one pixel wide and `rows` tall, each pixel `samples` samples + /// of 8 bits: a level of 0, an unassociated alpha of 128, then zeros. Each row is a strip, and + /// every strip is the same bytes of the file. + fn tall_gray_tiff(rows: u32, samples: u16) -> Vec { + let at = |f: &Vec| u32::try_from(f.len()).unwrap(); + let mut f = b"II*\0\0\0\0\0".to_vec(); + let row = at(&f); + f.extend([0, 128]); + f.resize(f.len() + usize::from(samples) - 2, 0); + let offsets = at(&f); + f.extend((0..rows).flat_map(|_| row.to_le_bytes())); + let counts = at(&f); + f.extend((0..rows).flat_map(|_| u32::from(samples).to_le_bytes())); + let ifd = at(&f); + f[4..8].copy_from_slice(&ifd.to_le_bytes()); + // (tag, type (3 SHORT, 4 LONG), count, value or offset) + let entries = [ + (256u16, 4u16, 1, 1), + (257, 4, 1, rows), + (258, 3, 1, 8), + (259, 3, 1, 1), + (262, 3, 1, 0), + (273, 4, rows, offsets), + (277, 3, 1, u32::from(samples)), + (278, 4, 1, 1), + (279, 4, rows, counts), + (338, 3, 1, 2), + ]; + f.extend(u16::try_from(entries.len()).unwrap().to_le_bytes()); + for (tag, ty, count, value) in entries { + f.extend([tag.to_le_bytes(), ty.to_le_bytes()].concat()); + f.extend([count.to_le_bytes(), value.to_le_bytes()].concat()); + } + f.extend([0; 4]); + f + } + + /// A TIFF with extra samples whose samples take more than the decoder's own limit of 256 MB + /// reads: here 65,537 pixels of 4,096 samples, 4,096 bytes more than the limit. + #[test] + fn a_tiff_with_extra_samples_past_the_decoders_limit_reads() { + let (rows, samples) = (65_537, 4096); + assert!(u64::from(rows) * u64::from(samples) > 256 << 20); + let px = extra_samples_tiff_rgba(&tall_gray_tiff(rows, samples), |_| [0.0; 3]).expect("reads"); + assert_eq!((px.width(), px.height()), (1, rows)); + assert!(px.pixels().all(|p| p.0 == [255, 255, 255, 128]), "white at an alpha of 128"); + } + + /// Patched bytes read the same whole, a byte at a time and after a seek into a patch. + #[test] + fn patched_bytes_read_with_their_patches() { + use std::io::{Read, Seek, SeekFrom}; + let bytes: Vec = (10..30).collect(); + let patched = || Patched { bytes: Cursor::new(&bytes[..]), patches: vec![(4, &[1, 0]), (19, &[7, 7])] }; + let want = [10, 11, 12, 13, 1, 0, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 7]; + let mut whole = Vec::new(); + patched().read_to_end(&mut whole).unwrap(); + assert_eq!(whole, want); + let mut one = patched(); + let bytewise: Vec = (0..want.len()) + .map(|_| { + let mut b = [0]; + assert_eq!(one.read(&mut b).unwrap(), 1); + b[0] + }) + .collect(); + assert_eq!(bytewise, want); + let mut from = patched(); + from.seek(SeekFrom::Start(5)).unwrap(); + let mut b = [9; 3]; + from.read_exact(&mut b).unwrap(); + assert_eq!(b, [0, 16, 17], "the second byte of the first patch, then the file"); } /// A grayscale TIFF whose alpha follows another extra sample reads that alpha. diff --git a/crates/engine/src/cmd/fileio/tests.rs b/crates/engine/src/cmd/fileio/tests.rs index f7f39e5358..b66b22d1a8 100644 --- a/crates/engine/src/cmd/fileio/tests.rs +++ b/crates/engine/src/cmd/fileio/tests.rs @@ -203,15 +203,18 @@ fn a_16_bit_cmyk_tiff_with_alpha_places_at_16_bits() { } /// A CMYK or grayscale TIFF whose alpha follows another extra sample opens and places with that -/// alpha, at 8 and 16 bits, chunky and planar; a CMYK one is not kept as inks. +/// alpha, at 8 and 16 bits, chunky and planar; a CMYK one is not kept as inks. A CMYK one with two +/// more samples than its ExtraSamples values count does too. #[test] fn a_tiff_with_alpha_after_another_extra_sample_places_with_its_alpha() { let none = vec![0u16; 6]; let full = vec![255u16; 6]; let other = vec![9u16, 8, 7, 6, 5, 4]; let alpha = vec![255u16, 128, 0, 255, 64, 1]; + let inks = [full.clone(), none.clone(), none.clone(), none.clone()]; let cases = [ ("CMYK", 5, vec![full.clone(), none.clone(), none.clone(), none.clone(), other.clone(), alpha.clone()]), + ("CMYK, two more samples", 5, [&inks[..], &[other.clone(), alpha.clone(), other.clone(), full.clone()]].concat()), ("gray", 1, vec![full.clone(), other.clone(), alpha.clone()]), ]; for (what, photometric, channels) in cases { diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4ae7bd7bc3..af94ba55c1 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1783,7 +1783,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - EPS and DXF in and out, EMF/WMF in and out; PNG (with PNG-8), JPEG, WebP, GIF, TIFF, BMP, Targa and layered PSD export; grayscale TIFFs with an alpha channel or other extra channels place, relink and open, the alpha as the image's transparency (#1466 in part); PSD and PSB files open and place, linked or embedded, as their merged image in every colour mode and depth (#918). EPS import runs a PostScript Level 3 interpreter written from the PostScript Language Reference: resource categories and `resourceforall`, local and global VM (`currentglobal`/`setglobal`/`gcheck`), `clipsave`/`cliprestore`, subarrays and substrings that share storage, the standard dictionaries in `systemdict`, `dictstack`, `internaldict`, executable filters and strings, `load` by any key, `//name` immediate names, `token`, `execform`, user paths, `cshow`, `rootfont`, `cachestatus`, colour rendering and halftone queries, file `status` and data read with `flushfile`, and `pdfmark` marks dropped (Discord feedback, #466, #469, #474). Masked images (`ImageType 3` in its three interleavings) and reusable streams are read, and an image's several data sources are read in turn, as the reference defines (procedures that read one file get their own rows: such images came in banded, #498). `restore` puts dictionaries back as they were at the `save`, so programs that count their saves in a dictionary read to their end (part of #505). Tiling patterns come in as pattern swatches, uncoloured ones too; Type 3 fonts' glyphs as their outlines, spaced by `ashow`/`widthshow`/`xshow`/`kshow`; mesh and function-based shadings (types 1, 4–7) as gradient meshes; sampled functions (type 0) and Flate/LZW predictors are read. It is tested with programs written from the specification in the ways common generators use these features; Inkscape/cairo EPS files open as vectors. When a file's PostScript still can't be read, it opens as its TIFF preview, its Windows metafile preview (as vectors) or its EPSI preview, and the warning (in the status bar, `document.open`/`app.open`/MCP `open_file` replies and `vectorcraft-cli info`) names the error, the operator that raised it and the procedures it ran in. Legacy PostScript `.ai` files (Illustrator 3–8, written with the prolog that defines their operators) keep their groups and nested groups (`u` … `U`), between and inside clipping groups; EPS and EMF/WMF import nest clips (and groups) at most 128 deep, so a hostile file can't exhaust the stack. DXF TEXT justified Fit or Aligned spans its two points (stretched, or scaled as a whole). PDF export writes type as real, searchable text in embedded subset fonts by default, as Illustrator's PDF presets do (Convert Text to Outlines is an option; printer's marks stay shapes), so text-heavy PDFs stay small (#733). DXF export writes each fill as its outlines followed by its hatch, so laser and cutter software, which skips hatches, gets filled art and type too (#546). - TIFFs that store each channel as its own plane (PlanarConfiguration 2) place, relink and open as the same image stored pixel by pixel does, 8 and 16 bits: grayscale with an alpha channel or other extra channels, and CMYK with or without them. A planar CMYK TIFF keeps its ink amounts and is stored as a CMYK TIFF with each pixel's inks together, at the file's resolution. A TIFF whose header claims more strips or tiles than can be counted is refused as too large to draw (#1466 in part; `crates/engine/src/cmd/fileio/tests.rs`). - A 16-bit CMYK or grayscale TIFF with an alpha channel is converted from its 16-bit samples, and only the resulting color and alpha are rounded to 8 bits; associated alpha is divided out at 16 bits, and a pixel whose associated alpha is zero has no color. [TIFF 6.0](https://printtechnologies.org/standards/files/tiff-v6.pdf) gives extra samples the depth in BitsPerSample, and its Associated Alpha Handling section states the arithmetic and the zero-alpha rule for RGB data; applying them to CMYK and gray samples is VectorCraft's own rule. Each sample was cut to its high byte first, so a faint ink or a low alpha could be lost (`crates/doc/src/cmyk.rs`, `crates/engine/src/cmd/fileio/tests.rs`). - - A CMYK or grayscale TIFF whose alpha channel comes after another extra channel places and opens with that alpha, 8 and 16 bits, chunky or planar, and the other extra channels are left out. A channel that the file does not mark as alpha is not read as transparency, even when its ExtraSamples tag has fewer values than the file has extra channels, and a white-is-zero grayscale TIFF with an alpha channel opens too. [TIFF 6.0](https://printtechnologies.org/standards/files/tiff-v6.pdf) gives each extra channel its own ExtraSamples value, in order (pp. 31–32), and tells readers to skip extra channels they do not use (p. 27); reading the first channel marked as alpha is VectorCraft's own rule (`crates/doc/src/cmyk.rs`, `crates/engine/src/cmd/fileio/tests.rs`). + - A CMYK or grayscale TIFF whose alpha channel comes after another extra channel places and opens with that alpha, 8 and 16 bits, chunky or planar, and the other extra channels are left out. A channel that the file does not mark as alpha is not read as transparency, even when its ExtraSamples tag has fewer values than the file has extra channels, and a white-is-zero grayscale TIFF with an alpha channel opens too. A document saved with such a CMYK TIFF as a CMYK image keeps it as one, with its ink amounts. Such a TIFF is read when its samples take more than 256 MB, up to the decoding allowance. [TIFF 6.0](https://printtechnologies.org/standards/files/tiff-v6.pdf) gives each extra channel its own ExtraSamples value, in order (pp. 31–32), and tells readers to skip extra channels they do not use (p. 27); reading the first channel marked as alpha is VectorCraft's own rule (`crates/doc/src/cmyk.rs`, `crates/engine/src/cmd/fileio/tests.rs`). - 1-bit TIFFs compressed with CCITT Group 3 (ITU-T T.4) place, relink and open: Compression 2 (modified Huffman) and Compression 3 with one-dimensional rows or, with T4Options bit 0, two-dimensional ones, with or without fill bits, in strips or tiles, with either FillOrder and either polarity. Rows in T.4's uncompressed mode are not read. A file whose pixels would take more than the decoding allowance as RGBA is refused as too large to draw (#1466 in part; `crates/engine/src/cmd/fileio/tests.rs`). - EPS and PostScript import keeps a CMYK image's ink amounts, as PDF import does: the samples of `image` and `colorimage` in a CMYK color space, and of a CMYK JPEG read through `DCTDecode`, come in as a CMYK TIFF, read through the image's Decode array, and the pixels a `MaskColor` or `ImageType 3` mask hides become a grayscale opacity mask (`crates/eps/src/import/tests_images.rs`). Such images came in as RGB PNGs. - EPS and PostScript import reads image data through `CCITTFaxDecode`: Group 4 (ITU-T T.6) and Group 3 one-dimensional and mixed (ITU-T T.4) data, with the filter's `K`, `Columns`, `Rows`, `EndOfBlock`, `EndOfLine`, `EncodedByteAlign` and `BlackIs1` parameters, decodes to 1-bit rows for `image` and `imagemask`. Damaged data keeps the rows decoded before it (damage in the first row is a PostScript `ioerror`), and parameters out of range or past the 256 MiB limit on decoded data are refused (`crates/eps/src/import/tests_images.rs`). Reading such a file stopped at an error naming the filter, and the file opened from a fallback, such as its preview or the art drawn before the image, or did not open. From 82d675e0b2072c2bce64d9d1781ad140a27944b1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 10:10:54 -0800 Subject: [PATCH 14/47] TIFF: the decoder's default buffer limit is 256 MiB The doc comments of with_room and of the large-file test, and the progress-doc line, gave the tiff decoder's default decoding buffer (268,435,456 bytes) as 256 MB. --- crates/doc/src/cmyk.rs | 4 ++-- docs/target-app-parity.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/doc/src/cmyk.rs b/crates/doc/src/cmyk.rs index 032fcce596..8543d22d5e 100644 --- a/crates/doc/src/cmyk.rs +++ b/crates/doc/src/cmyk.rs @@ -249,7 +249,7 @@ fn cmyk_inks(kind: tiff::ColorType, d: &mut tiff::decoder::Decoder } /// `d` with room to decode `n` pixels of `per` samples of `bits` bits each, when they take more -/// than the decoder's own limit (256 MB of samples); `None` when they take more than +/// than the decoder's own limit (256 MiB of samples); `None` when they take more than /// [`crate::MAX_RASTER_ALLOC`]. fn with_room(d: tiff::decoder::Decoder, n: usize, per: usize, bits: u8) -> Option> { let need = n.checked_mul(per)?.checked_mul(usize::from(bits.div_ceil(8)))?; @@ -1161,7 +1161,7 @@ mod tests { f } - /// A TIFF with extra samples whose samples take more than the decoder's own limit of 256 MB + /// A TIFF with extra samples whose samples take more than the decoder's own limit of 256 MiB /// reads: here 65,537 pixels of 4,096 samples, 4,096 bytes more than the limit. #[test] fn a_tiff_with_extra_samples_past_the_decoders_limit_reads() { diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index af94ba55c1..5984479b3f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1783,7 +1783,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - EPS and DXF in and out, EMF/WMF in and out; PNG (with PNG-8), JPEG, WebP, GIF, TIFF, BMP, Targa and layered PSD export; grayscale TIFFs with an alpha channel or other extra channels place, relink and open, the alpha as the image's transparency (#1466 in part); PSD and PSB files open and place, linked or embedded, as their merged image in every colour mode and depth (#918). EPS import runs a PostScript Level 3 interpreter written from the PostScript Language Reference: resource categories and `resourceforall`, local and global VM (`currentglobal`/`setglobal`/`gcheck`), `clipsave`/`cliprestore`, subarrays and substrings that share storage, the standard dictionaries in `systemdict`, `dictstack`, `internaldict`, executable filters and strings, `load` by any key, `//name` immediate names, `token`, `execform`, user paths, `cshow`, `rootfont`, `cachestatus`, colour rendering and halftone queries, file `status` and data read with `flushfile`, and `pdfmark` marks dropped (Discord feedback, #466, #469, #474). Masked images (`ImageType 3` in its three interleavings) and reusable streams are read, and an image's several data sources are read in turn, as the reference defines (procedures that read one file get their own rows: such images came in banded, #498). `restore` puts dictionaries back as they were at the `save`, so programs that count their saves in a dictionary read to their end (part of #505). Tiling patterns come in as pattern swatches, uncoloured ones too; Type 3 fonts' glyphs as their outlines, spaced by `ashow`/`widthshow`/`xshow`/`kshow`; mesh and function-based shadings (types 1, 4–7) as gradient meshes; sampled functions (type 0) and Flate/LZW predictors are read. It is tested with programs written from the specification in the ways common generators use these features; Inkscape/cairo EPS files open as vectors. When a file's PostScript still can't be read, it opens as its TIFF preview, its Windows metafile preview (as vectors) or its EPSI preview, and the warning (in the status bar, `document.open`/`app.open`/MCP `open_file` replies and `vectorcraft-cli info`) names the error, the operator that raised it and the procedures it ran in. Legacy PostScript `.ai` files (Illustrator 3–8, written with the prolog that defines their operators) keep their groups and nested groups (`u` … `U`), between and inside clipping groups; EPS and EMF/WMF import nest clips (and groups) at most 128 deep, so a hostile file can't exhaust the stack. DXF TEXT justified Fit or Aligned spans its two points (stretched, or scaled as a whole). PDF export writes type as real, searchable text in embedded subset fonts by default, as Illustrator's PDF presets do (Convert Text to Outlines is an option; printer's marks stay shapes), so text-heavy PDFs stay small (#733). DXF export writes each fill as its outlines followed by its hatch, so laser and cutter software, which skips hatches, gets filled art and type too (#546). - TIFFs that store each channel as its own plane (PlanarConfiguration 2) place, relink and open as the same image stored pixel by pixel does, 8 and 16 bits: grayscale with an alpha channel or other extra channels, and CMYK with or without them. A planar CMYK TIFF keeps its ink amounts and is stored as a CMYK TIFF with each pixel's inks together, at the file's resolution. A TIFF whose header claims more strips or tiles than can be counted is refused as too large to draw (#1466 in part; `crates/engine/src/cmd/fileio/tests.rs`). - A 16-bit CMYK or grayscale TIFF with an alpha channel is converted from its 16-bit samples, and only the resulting color and alpha are rounded to 8 bits; associated alpha is divided out at 16 bits, and a pixel whose associated alpha is zero has no color. [TIFF 6.0](https://printtechnologies.org/standards/files/tiff-v6.pdf) gives extra samples the depth in BitsPerSample, and its Associated Alpha Handling section states the arithmetic and the zero-alpha rule for RGB data; applying them to CMYK and gray samples is VectorCraft's own rule. Each sample was cut to its high byte first, so a faint ink or a low alpha could be lost (`crates/doc/src/cmyk.rs`, `crates/engine/src/cmd/fileio/tests.rs`). - - A CMYK or grayscale TIFF whose alpha channel comes after another extra channel places and opens with that alpha, 8 and 16 bits, chunky or planar, and the other extra channels are left out. A channel that the file does not mark as alpha is not read as transparency, even when its ExtraSamples tag has fewer values than the file has extra channels, and a white-is-zero grayscale TIFF with an alpha channel opens too. A document saved with such a CMYK TIFF as a CMYK image keeps it as one, with its ink amounts. Such a TIFF is read when its samples take more than 256 MB, up to the decoding allowance. [TIFF 6.0](https://printtechnologies.org/standards/files/tiff-v6.pdf) gives each extra channel its own ExtraSamples value, in order (pp. 31–32), and tells readers to skip extra channels they do not use (p. 27); reading the first channel marked as alpha is VectorCraft's own rule (`crates/doc/src/cmyk.rs`, `crates/engine/src/cmd/fileio/tests.rs`). + - A CMYK or grayscale TIFF whose alpha channel comes after another extra channel places and opens with that alpha, 8 and 16 bits, chunky or planar, and the other extra channels are left out. A channel that the file does not mark as alpha is not read as transparency, even when its ExtraSamples tag has fewer values than the file has extra channels, and a white-is-zero grayscale TIFF with an alpha channel opens too. A document saved with such a CMYK TIFF as a CMYK image keeps it as one, with its ink amounts. Such a TIFF is read when its samples take more than 256 MiB, up to the decoding allowance. [TIFF 6.0](https://printtechnologies.org/standards/files/tiff-v6.pdf) gives each extra channel its own ExtraSamples value, in order (pp. 31–32), and tells readers to skip extra channels they do not use (p. 27); reading the first channel marked as alpha is VectorCraft's own rule (`crates/doc/src/cmyk.rs`, `crates/engine/src/cmd/fileio/tests.rs`). - 1-bit TIFFs compressed with CCITT Group 3 (ITU-T T.4) place, relink and open: Compression 2 (modified Huffman) and Compression 3 with one-dimensional rows or, with T4Options bit 0, two-dimensional ones, with or without fill bits, in strips or tiles, with either FillOrder and either polarity. Rows in T.4's uncompressed mode are not read. A file whose pixels would take more than the decoding allowance as RGBA is refused as too large to draw (#1466 in part; `crates/engine/src/cmd/fileio/tests.rs`). - EPS and PostScript import keeps a CMYK image's ink amounts, as PDF import does: the samples of `image` and `colorimage` in a CMYK color space, and of a CMYK JPEG read through `DCTDecode`, come in as a CMYK TIFF, read through the image's Decode array, and the pixels a `MaskColor` or `ImageType 3` mask hides become a grayscale opacity mask (`crates/eps/src/import/tests_images.rs`). Such images came in as RGB PNGs. - EPS and PostScript import reads image data through `CCITTFaxDecode`: Group 4 (ITU-T T.6) and Group 3 one-dimensional and mixed (ITU-T T.4) data, with the filter's `K`, `Columns`, `Rows`, `EndOfBlock`, `EndOfLine`, `EncodedByteAlign` and `BlackIs1` parameters, decodes to 1-bit rows for `image` and `imagemask`. Damaged data keeps the rows decoded before it (damage in the first row is a PostScript `ioerror`), and parameters out of range or past the 256 MiB limit on decoded data are refused (`crates/eps/src/import/tests_images.rs`). Reading such a file stopped at an error naming the filter, and the file opened from a fallback, such as its preview or the art drawn before the image, or did not open. From 69ce720e462a7e6644476f38908d3932c58dd7b5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 10:44:26 -0800 Subject: [PATCH 15/47] Live Paint: Live Paint Selection does nothing on a triple-click main's Live Paint Selection double-click (#7342) replaced the tool's catch-all pointer arm with an explicit DoubleClick arm, so the TripleClick kind this branch adds left the match non-exhaustive. The tool now takes no action on TripleClick: the third click's press and release already select what a click selects, as before the merge. The merge also took main's import list in the engine's Live Paint commands, which no longer named Paint while this branch's Merge code still uses it; Paint is imported again. --- crates/engine/src/cmd/buildcmds/live_paint.rs | 6 +++--- crates/tools/src/builder/live_paint.rs | 2 ++ crates/tools/src/builder/tests.rs | 16 ++++++++++++++++ 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/buildcmds/live_paint.rs b/crates/engine/src/cmd/buildcmds/live_paint.rs index 90f495f9c9..60a7a584e7 100644 --- a/crates/engine/src/cmd/buildcmds/live_paint.rs +++ b/crates/engine/src/cmd/buildcmds/live_paint.rs @@ -1,7 +1,7 @@ use super::{ - Appearance, Arc, Beside, Document, EDGE_NAME, EngineError, FACE_NAME, GapOptions, GapSize, LIVE_PAINT_NAME, Node, NodeId, PathData, Point, Rect, - Result, SOURCES_NAME, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite, ids_json, is_live_paint, json, - number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids, source_nodes, source_shapes, switch_or, + Appearance, Arc, Beside, Document, EDGE_NAME, EngineError, FACE_NAME, GapOptions, GapSize, LIVE_PAINT_NAME, Node, NodeId, Paint, PathData, Point, + Rect, Result, SOURCES_NAME, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite, ids_json, is_live_paint, + json, number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids, source_nodes, source_shapes, switch_or, }; /// `options` as stored on a Live Paint group: none for the defaults. diff --git a/crates/tools/src/builder/live_paint.rs b/crates/tools/src/builder/live_paint.rs index f43ba27a2c..e42b2649de 100644 --- a/crates/tools/src/builder/live_paint.rs +++ b/crates/tools/src/builder/live_paint.rs @@ -907,6 +907,8 @@ impl Tool for LivePaintSelectionTool { (false, false) => vec![Action::Exec("select.set".into(), json!({ "ids": json_ids(&ids) }))], } } + // The third click's press and release already selected what a click selects. + PointerKind::TripleClick => vec![], } } diff --git a/crates/tools/src/builder/tests.rs b/crates/tools/src/builder/tests.rs index 08f269ac4e..28daa4fdc9 100644 --- a/crates/tools/src/builder/tests.rs +++ b/crates/tools/src/builder/tests.rs @@ -2506,6 +2506,22 @@ fn live_paint_selection_double_click_selects_connected_faces_or_edges() { assert!(dbl(&mut t, 25.0, 1.0, alt).is_empty()); } +#[test] +fn live_paint_selection_triple_click_adds_nothing_to_its_clicks() { + let mut d = Document::new(500.0, 500.0); + let (_, [a, ..], _) = live_strip(&mut d); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = LivePaintSelectionTool::default(); + // The third click's press and release select the face under the pointer, as a click does. + assert_eq!(lp_click(&mut t, &cx, ev(PointerKind::Down, 25.0, 25.0)), vec![Action::Exec("select.set".into(), json!({ "ids": [a.0] }))]); + for m in [Mods::default(), Mods { alt: true, ..Default::default() }, Mods { shift: true, ..Default::default() }] { + assert!(t.pointer(&cx, &ev(PointerKind::TripleClick, 25.0, 25.0).with_mods(m)).is_empty()); + assert!(t.pointer(&cx, &ev(PointerKind::TripleClick, 25.0, 1.0).with_mods(m)).is_empty()); + } +} + #[test] fn live_paint_selection_double_click_skips_locked_groups_and_art_outside_isolation() { let mut d = Document::new(500.0, 500.0); From 87b861c480921263ff5623afd524263aa28b1a70 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 10:50:41 -0800 Subject: [PATCH 16/47] TIFF: extra-sample reads count the planar copy and RGBA pixels in the allowance A CMYK or grayscale TIFF with extra samples is now read only when its decoded samples, the copy that puts a planar file's samples pixel by pixel and the RGBA pixels together fit the decoding allowance; the check counted the decoded samples alone, so a small compressed file could make the reader hold about twice the allowance plus the RGBA image. - The decoder may decode no more than the counted samples, and reads no strip or tile of more compressed bytes than the file holds. - A pixel of more than 64 samples is not read (VectorCraft's own limit). --- crates/doc/src/cmyk.rs | 120 +++++++++++++++++++++++++++++--------- docs/target-app-parity.md | 2 +- 2 files changed, 95 insertions(+), 27 deletions(-) diff --git a/crates/doc/src/cmyk.rs b/crates/doc/src/cmyk.rs index 8543d22d5e..a94b7f7a4f 100644 --- a/crates/doc/src/cmyk.rs +++ b/crates/doc/src/cmyk.rs @@ -248,21 +248,40 @@ fn cmyk_inks(kind: tiff::ColorType, d: &mut tiff::decoder::Decoder matches!(kind, tiff::ColorType::CMYK(8 | 16)) && !extra_samples(d).iter().any(|e| matches!(e, 1 | 2)) } -/// `d` with room to decode `n` pixels of `per` samples of `bits` bits each, when they take more -/// than the decoder's own limit (256 MiB of samples); `None` when they take more than -/// [`crate::MAX_RASTER_ALLOC`]. -fn with_room(d: tiff::decoder::Decoder, n: usize, per: usize, bits: u8) -> Option> { +/// Most samples a pixel of a TIFF with extra samples is read with, its color included: +/// VectorCraft's own limit. +const MAX_EXTRA_SAMPLES_PIXEL: usize = 64; + +/// `d`, the decoder of a TIFF of `file` bytes, set to decode `n` pixels of `per` samples of `bits` +/// bits each into RGBA. `None` when a pixel has more than [`MAX_EXTRA_SAMPLES_PIXEL`] samples, and +/// when the decoded samples, the copy that puts a planar file's samples pixel by pixel and the +/// RGBA pixels together take more than [`crate::MAX_RASTER_ALLOC`]. The decoder may then decode +/// no more than those samples, and read no strip or tile of more compressed bytes than the file +/// holds (nor more than its own limit of 128 MiB). +fn with_room( + mut d: tiff::decoder::Decoder, + file: usize, + n: usize, + per: usize, + bits: u8, +) -> Option> { + if per > MAX_EXTRA_SAMPLES_PIXEL { + return None; + } let need = n.checked_mul(per)?.checked_mul(usize::from(bits.div_ceil(8)))?; - if u64::try_from(need).ok()? > crate::MAX_RASTER_ALLOC { + let copies = if per > 1 && planar(&mut d) { 2 } else { 1 }; + let peak = u64::try_from(need).ok()?.checked_mul(copies)?.checked_add(u64::try_from(n).ok()?.checked_mul(4)?)?; + if peak > crate::MAX_RASTER_ALLOC { return None; } let mut limits = tiff::decoder::Limits::default(); - limits.decoding_buffer_size = limits.decoding_buffer_size.max(need); + limits.decoding_buffer_size = need; + limits.intermediate_buffer_size = limits.intermediate_buffer_size.min(file); Some(d.with_limits(limits)) } /// Does the TIFF `d` reads store one plane per channel (PlanarConfiguration 2)? -fn planar(d: &mut tiff::decoder::Decoder>) -> bool { +fn planar(d: &mut tiff::decoder::Decoder) -> bool { d.find_tag_unsigned::(tiff::tags::Tag::PlanarConfiguration).ok().flatten().is_some_and(|p| p != 1) } @@ -646,7 +665,9 @@ pub fn turned_cmyk(bytes: &[u8], orientation: image::metadata::Orientation, ppi: /// together or one plane per channel. A CMYK file with two or more samples past its inks and its /// ExtraSamples values is read when one of those values names an alpha. `None` for other images, /// CMYK ones without alpha (their inks are read by [`ImageBlob::cmyk`]), ones larger than -/// [`MAX_CMYK_PIXELS`] and ones whose samples take more than [`crate::MAX_RASTER_ALLOC`]. +/// [`MAX_CMYK_PIXELS`], ones with more than [`MAX_EXTRA_SAMPLES_PIXEL`] samples a pixel and ones +/// whose samples, with the copy a planar file needs and the RGBA pixels, take more than +/// [`crate::MAX_RASTER_ALLOC`]. pub fn extra_samples_tiff_rgba(bytes: &[u8], rgb: impl Fn([f32; 4]) -> [f32; 3]) -> Option { use tiff::tags::Tag; let mut d = tiff_decoder(bytes)?; @@ -677,9 +698,9 @@ pub fn extra_samples_tiff_rgba(bytes: &[u8], rgb: impl Fn([f32; 4]) -> [f32; 3]) let mut d = tiff::decoder::Decoder::new(as_black_is_zero(bytes)?).ok()?; let tiff::ColorType::Multiband { bit_depth: bits @ (8 | 16), num_samples } = d.colortype().ok()? else { return None }; let samples = usize::from(num_samples); - (read_samples_at_depth(&mut with_room(d, n, samples, bits)?, n, samples)?, samples) + (read_samples_at_depth(&mut with_room(d, bytes.len(), n, samples, bits)?, n, samples)?, samples) } else { - (read_samples_at_depth(&mut with_room(d, n, given, kind?.bit_depth())?, n, given)?, given) + (read_samples_at_depth(&mut with_room(d, bytes.len(), n, given, kind?.bit_depth())?, n, given)?, given) }; // (the alpha's sample in a pixel, is it associated?), when the pixel has that sample. let alpha = alpha.map(|(i, associated)| (colour + i, associated)).filter(|(at, _)| *at < samples); @@ -1124,32 +1145,46 @@ mod tests { assert_eq!(exif_orientation(&turned), Some(image::metadata::Orientation::Rotate90)); } - /// A white-is-zero grayscale TIFF one pixel wide and `rows` tall, each pixel `samples` samples - /// of 8 bits: a level of 0, an unassociated alpha of 128, then zeros. Each row is a strip, and - /// every strip is the same bytes of the file. - fn tall_gray_tiff(rows: u32, samples: u16) -> Vec { + /// A white-is-zero grayscale TIFF `width` pixels wide and `rows` tall (2 or more), each pixel + /// `samples` samples of 8 bits: a level of 0, an unassociated alpha of 128, then zeros. Each + /// row is a strip, and every strip is the same bytes of the file. + fn tall_gray_tiff(width: u32, rows: u32, samples: u16) -> Vec { + gray_tiff(width, rows, samples, false) + } + + /// [`tall_gray_tiff`], or with `planar` one plane per sample, each row of each plane a strip + /// of zeros, every strip the same bytes of the file. + fn gray_tiff(width: u32, rows: u32, samples: u16, planar: bool) -> Vec { let at = |f: &Vec| u32::try_from(f.len()).unwrap(); let mut f = b"II*\0\0\0\0\0".to_vec(); let row = at(&f); - f.extend([0, 128]); - f.resize(f.len() + usize::from(samples) - 2, 0); + if planar { + f.resize(f.len() + usize::try_from(width).unwrap(), 0); + } else { + for _ in 0..width { + f.extend([0, 128]); + f.resize(f.len() + usize::from(samples) - 2, 0); + } + } + let (strips, strip) = if planar { (rows * u32::from(samples), width) } else { (rows, width * u32::from(samples)) }; let offsets = at(&f); - f.extend((0..rows).flat_map(|_| row.to_le_bytes())); + f.extend((0..strips).flat_map(|_| row.to_le_bytes())); let counts = at(&f); - f.extend((0..rows).flat_map(|_| u32::from(samples).to_le_bytes())); + f.extend((0..strips).flat_map(|_| strip.to_le_bytes())); let ifd = at(&f); f[4..8].copy_from_slice(&ifd.to_le_bytes()); // (tag, type (3 SHORT, 4 LONG), count, value or offset) let entries = [ - (256u16, 4u16, 1, 1), + (256u16, 4u16, 1, width), (257, 4, 1, rows), (258, 3, 1, 8), (259, 3, 1, 1), (262, 3, 1, 0), - (273, 4, rows, offsets), + (273, 4, strips, offsets), (277, 3, 1, u32::from(samples)), (278, 4, 1, 1), - (279, 4, rows, counts), + (279, 4, strips, counts), + (284, 3, 1, if planar { 2 } else { 1 }), (338, 3, 1, 2), ]; f.extend(u16::try_from(entries.len()).unwrap().to_le_bytes()); @@ -1162,16 +1197,49 @@ mod tests { } /// A TIFF with extra samples whose samples take more than the decoder's own limit of 256 MiB - /// reads: here 65,537 pixels of 4,096 samples, 4,096 bytes more than the limit. + /// reads: here 256 × 16,385 pixels of 64 samples, 16,384 bytes more than the limit. #[test] fn a_tiff_with_extra_samples_past_the_decoders_limit_reads() { - let (rows, samples) = (65_537, 4096); - assert!(u64::from(rows) * u64::from(samples) > 256 << 20); - let px = extra_samples_tiff_rgba(&tall_gray_tiff(rows, samples), |_| [0.0; 3]).expect("reads"); - assert_eq!((px.width(), px.height()), (1, rows)); + let (width, rows, samples) = (256, 16_385, 64); + assert!(u64::from(width * rows) * u64::from(samples) > 256 << 20); + let px = extra_samples_tiff_rgba(&tall_gray_tiff(width, rows, samples), |_| [0.0; 3]).expect("reads"); + assert_eq!((px.width(), px.height()), (width, rows)); assert!(px.pixels().all(|p| p.0 == [255, 255, 255, 128]), "white at an alpha of 128"); } + /// A pixel of more than [`MAX_EXTRA_SAMPLES_PIXEL`] samples is not read. + #[test] + fn a_tiff_with_too_many_samples_a_pixel_is_not_read() { + let samples = u16::try_from(MAX_EXTRA_SAMPLES_PIXEL).unwrap(); + assert!(extra_samples_tiff_rgba(&tall_gray_tiff(2, 2, samples), |_| [0.0; 3]).is_some(), "at the limit: reads"); + assert!(extra_samples_tiff_rgba(&tall_gray_tiff(2, 2, samples + 1), |_| [0.0; 3]).is_none(), "past it: not read"); + } + + /// A TIFF whose decoded samples fit [`crate::MAX_RASTER_ALLOC`] but not with its RGBA pixels + /// beside them is refused before its samples are decoded; so is one whose samples fit with + /// the RGBA pixels but not with the copy a planar file needs. The file holds one row of pixels, + /// which every strip reuses. + #[test] + fn a_tiff_whose_decode_with_its_rgba_takes_more_than_the_allowance_is_refused() { + let side = 8192u32; + let n = usize::try_from(u64::from(side) * u64::from(side)).unwrap(); + assert_eq!(u64::try_from(n).unwrap(), MAX_CMYK_PIXELS); + let max = usize::try_from(crate::MAX_RASTER_ALLOC).unwrap(); + // One sample fewer than fills the allowance: the samples alone fit. + let per = max / n - 1; + assert!(n * per <= max && n * per + 4 * n > max); + let bytes = tall_gray_tiff(side, side, u16::try_from(per).unwrap()); + let decoder = || tiff::decoder::Decoder::new(Cursor::new(&bytes[..])).unwrap(); + assert!(with_room(decoder(), bytes.len(), n, per, 8).is_none(), "refused before the decode"); + assert!(extra_samples_tiff_rgba(&bytes, |_| [0.0; 3]).is_none()); + // Half the allowance in samples fits with the RGBA pixels, but not twice over. + let half = max / n / 2; + assert!(with_room(decoder(), bytes.len(), n, half, 8).is_some(), "stored together: fits"); + let planar = gray_tiff(side, side, u16::try_from(half).unwrap(), true); + let decoder = tiff::decoder::Decoder::new(Cursor::new(&planar[..])).unwrap(); + assert!(with_room(decoder, planar.len(), n, half, 8).is_none(), "one plane per sample: refused"); + } + /// Patched bytes read the same whole, a byte at a time and after a seek into a patch. #[test] fn patched_bytes_read_with_their_patches() { diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 5984479b3f..5ff43bdd40 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1783,7 +1783,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - EPS and DXF in and out, EMF/WMF in and out; PNG (with PNG-8), JPEG, WebP, GIF, TIFF, BMP, Targa and layered PSD export; grayscale TIFFs with an alpha channel or other extra channels place, relink and open, the alpha as the image's transparency (#1466 in part); PSD and PSB files open and place, linked or embedded, as their merged image in every colour mode and depth (#918). EPS import runs a PostScript Level 3 interpreter written from the PostScript Language Reference: resource categories and `resourceforall`, local and global VM (`currentglobal`/`setglobal`/`gcheck`), `clipsave`/`cliprestore`, subarrays and substrings that share storage, the standard dictionaries in `systemdict`, `dictstack`, `internaldict`, executable filters and strings, `load` by any key, `//name` immediate names, `token`, `execform`, user paths, `cshow`, `rootfont`, `cachestatus`, colour rendering and halftone queries, file `status` and data read with `flushfile`, and `pdfmark` marks dropped (Discord feedback, #466, #469, #474). Masked images (`ImageType 3` in its three interleavings) and reusable streams are read, and an image's several data sources are read in turn, as the reference defines (procedures that read one file get their own rows: such images came in banded, #498). `restore` puts dictionaries back as they were at the `save`, so programs that count their saves in a dictionary read to their end (part of #505). Tiling patterns come in as pattern swatches, uncoloured ones too; Type 3 fonts' glyphs as their outlines, spaced by `ashow`/`widthshow`/`xshow`/`kshow`; mesh and function-based shadings (types 1, 4–7) as gradient meshes; sampled functions (type 0) and Flate/LZW predictors are read. It is tested with programs written from the specification in the ways common generators use these features; Inkscape/cairo EPS files open as vectors. When a file's PostScript still can't be read, it opens as its TIFF preview, its Windows metafile preview (as vectors) or its EPSI preview, and the warning (in the status bar, `document.open`/`app.open`/MCP `open_file` replies and `vectorcraft-cli info`) names the error, the operator that raised it and the procedures it ran in. Legacy PostScript `.ai` files (Illustrator 3–8, written with the prolog that defines their operators) keep their groups and nested groups (`u` … `U`), between and inside clipping groups; EPS and EMF/WMF import nest clips (and groups) at most 128 deep, so a hostile file can't exhaust the stack. DXF TEXT justified Fit or Aligned spans its two points (stretched, or scaled as a whole). PDF export writes type as real, searchable text in embedded subset fonts by default, as Illustrator's PDF presets do (Convert Text to Outlines is an option; printer's marks stay shapes), so text-heavy PDFs stay small (#733). DXF export writes each fill as its outlines followed by its hatch, so laser and cutter software, which skips hatches, gets filled art and type too (#546). - TIFFs that store each channel as its own plane (PlanarConfiguration 2) place, relink and open as the same image stored pixel by pixel does, 8 and 16 bits: grayscale with an alpha channel or other extra channels, and CMYK with or without them. A planar CMYK TIFF keeps its ink amounts and is stored as a CMYK TIFF with each pixel's inks together, at the file's resolution. A TIFF whose header claims more strips or tiles than can be counted is refused as too large to draw (#1466 in part; `crates/engine/src/cmd/fileio/tests.rs`). - A 16-bit CMYK or grayscale TIFF with an alpha channel is converted from its 16-bit samples, and only the resulting color and alpha are rounded to 8 bits; associated alpha is divided out at 16 bits, and a pixel whose associated alpha is zero has no color. [TIFF 6.0](https://printtechnologies.org/standards/files/tiff-v6.pdf) gives extra samples the depth in BitsPerSample, and its Associated Alpha Handling section states the arithmetic and the zero-alpha rule for RGB data; applying them to CMYK and gray samples is VectorCraft's own rule. Each sample was cut to its high byte first, so a faint ink or a low alpha could be lost (`crates/doc/src/cmyk.rs`, `crates/engine/src/cmd/fileio/tests.rs`). - - A CMYK or grayscale TIFF whose alpha channel comes after another extra channel places and opens with that alpha, 8 and 16 bits, chunky or planar, and the other extra channels are left out. A channel that the file does not mark as alpha is not read as transparency, even when its ExtraSamples tag has fewer values than the file has extra channels, and a white-is-zero grayscale TIFF with an alpha channel opens too. A document saved with such a CMYK TIFF as a CMYK image keeps it as one, with its ink amounts. Such a TIFF is read when its samples take more than 256 MiB, up to the decoding allowance. [TIFF 6.0](https://printtechnologies.org/standards/files/tiff-v6.pdf) gives each extra channel its own ExtraSamples value, in order (pp. 31–32), and tells readers to skip extra channels they do not use (p. 27); reading the first channel marked as alpha is VectorCraft's own rule (`crates/doc/src/cmyk.rs`, `crates/engine/src/cmd/fileio/tests.rs`). + - A CMYK or grayscale TIFF whose alpha channel comes after another extra channel places and opens with that alpha, 8 and 16 bits, chunky or planar, and the other extra channels are left out. A channel that the file does not mark as alpha is not read as transparency, even when its ExtraSamples tag has fewer values than the file has extra channels, and a white-is-zero grayscale TIFF with an alpha channel opens too. A document saved with such a CMYK TIFF as a CMYK image keeps it as one, with its ink amounts. Such a TIFF is read when its samples take more than 256 MiB, as long as its samples, the copy a planar file needs and the RGBA pixels together fit the decoding allowance; a TIFF with more than 64 samples a pixel is not read, which is VectorCraft's own limit. [TIFF 6.0](https://printtechnologies.org/standards/files/tiff-v6.pdf) gives each extra channel its own ExtraSamples value, in order (pp. 31–32), and tells readers to skip extra channels they do not use (p. 27); reading the first channel marked as alpha is VectorCraft's own rule (`crates/doc/src/cmyk.rs`, `crates/engine/src/cmd/fileio/tests.rs`). - 1-bit TIFFs compressed with CCITT Group 3 (ITU-T T.4) place, relink and open: Compression 2 (modified Huffman) and Compression 3 with one-dimensional rows or, with T4Options bit 0, two-dimensional ones, with or without fill bits, in strips or tiles, with either FillOrder and either polarity. Rows in T.4's uncompressed mode are not read. A file whose pixels would take more than the decoding allowance as RGBA is refused as too large to draw (#1466 in part; `crates/engine/src/cmd/fileio/tests.rs`). - EPS and PostScript import keeps a CMYK image's ink amounts, as PDF import does: the samples of `image` and `colorimage` in a CMYK color space, and of a CMYK JPEG read through `DCTDecode`, come in as a CMYK TIFF, read through the image's Decode array, and the pixels a `MaskColor` or `ImageType 3` mask hides become a grayscale opacity mask (`crates/eps/src/import/tests_images.rs`). Such images came in as RGB PNGs. - EPS and PostScript import reads image data through `CCITTFaxDecode`: Group 4 (ITU-T T.6) and Group 3 one-dimensional and mixed (ITU-T T.4) data, with the filter's `K`, `Columns`, `Rows`, `EndOfBlock`, `EndOfLine`, `EncodedByteAlign` and `BlackIs1` parameters, decodes to 1-bit rows for `image` and `imagemask`. Damaged data keeps the rows decoded before it (damage in the first row is a PostScript `ioerror`), and parameters out of range or past the 256 MiB limit on decoded data are refused (`crates/eps/src/import/tests_images.rs`). Reading such a file stopped at an error naming the filter, and the file opened from a fallback, such as its preview or the art drawn before the image, or did not open. From 7ef603db404699513b701d54c0750571ebb9ac0b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 11:24:56 -0800 Subject: [PATCH 17/47] Live Paint: bucket scopes follow the stroke an edge draws The Live Paint Bucket's connected and samePaint scopes kept their own copies of the face flood and the edge walk. They read an edge's stored stroke paint, so an edge that is fully transparent or whose stroke is hidden stopped a face flood and matched as stroked. The face flood also required outlines within 0.0001 pt of an edge, which a curved face that the planar map refits can miss. The engine now calls the shared flood_faces and connected_edges that Live Paint Selection uses (#7342), and compares edges by lp_stroke_paint, the paint of the topmost stroke that draws. The tool records that same paint as the match for a double-click or triple-click on an edge. The params text and docs/mcp.md describe the drawn stroke paint. --- crates/engine/src/cmd/buildcmds.rs | 2 +- crates/engine/src/cmd/buildcmds/live_paint.rs | 245 +----------------- crates/engine/src/tests/build.rs | 35 +++ crates/tools/src/builder.rs | 4 +- crates/tools/src/builder/live_paint.rs | 4 +- crates/tools/src/builder/lookup.rs | 2 +- docs/mcp.md | 11 +- 7 files changed, 52 insertions(+), 251 deletions(-) diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 738bd34750..7bf0dadfc6 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -126,7 +126,7 @@ pub fn specs() -> Vec { "Live Paint Bucket (Stroke)", [], None, - "{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), scope?: \"one\" (default: the edge alone) | \"connected\" (a double-click: also each edge joined to it, end to end, through edges whose stroke paint is match) | \"samePaint\" (a triple-click: also every edge of the group whose stroke paint is match), match?: paint (as the document stores it; scope connected or samePaint only; default: the edge's stroke paint), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point, skipping hidden edges; when every edge it reaches already has the paint and the width, nothing changes (no undo step, and the recent colors stay as they are) → {group, edge, count (edges reached)}", + "{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), scope?: \"one\" (default: the edge alone) | \"connected\" (a double-click: also each edge joined to it, end to end, through edges that draw with stroke paint match) | \"samePaint\" (a triple-click: also every edge of the group that draws with stroke paint match), match?: paint (as the document stores it; scope connected or samePaint only; default: the stroke paint the edge draws with; an edge draws with the paint of its topmost stroke that is shown, with paint, above 0 pt and not fully transparent, and with none when the edge is fully transparent or has no such stroke), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point, skipping hidden edges; when every edge it reaches already has the paint and the width, nothing changes (no undo step, and the recent colors stay as they are) → {group, edge, count (edges reached)}", has_doc, lp_stroke_edge ), diff --git a/crates/engine/src/cmd/buildcmds/live_paint.rs b/crates/engine/src/cmd/buildcmds/live_paint.rs index 60a7a584e7..2778e0495a 100644 --- a/crates/engine/src/cmd/buildcmds/live_paint.rs +++ b/crates/engine/src/cmd/buildcmds/live_paint.rs @@ -399,243 +399,6 @@ fn match_param(p: &Value, c: &str, allowed: bool, scopes: &str) -> Result