diff --git a/Cargo.lock b/Cargo.lock index ee61a57463..17afafa588 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2536,6 +2536,8 @@ dependencies = [ "iced_core", "iced_fonts_macros", "iced_widget", + "num-format", + "num-traits", "web-time", ] @@ -3733,6 +3735,16 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "num-format" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a652d9771a63711fd3c3deb670acfbe5c30a4072e664d7a3bf5a9e1056ac72c3" +dependencies = [ + "arrayvec", + "itoa", +] + [[package]] name = "num-integer" version = "0.1.46" diff --git a/Cargo.toml b/Cargo.toml index 7fe8273a2b..d3b542ed8d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,7 +28,7 @@ url = "2" iced = { git = "https://github.com/iced-rs/iced.git", rev = "23604ff22ab0aad9e00b9327cb7b8546ed84db39", features = ["image", "svg", "advanced", "canvas", "smol", "markdown"] } iced_runtime = { git = "https://github.com/iced-rs/iced.git", rev = "23604ff22ab0aad9e00b9327cb7b8546ed84db39" } iced_core = { git = "https://github.com/iced-rs/iced.git", rev = "23604ff22ab0aad9e00b9327cb7b8546ed84db39" } -iced_aw = { git = "https://github.com/HakanSeven12/iced_aw.git", branch = "agent/fix-iced-fonts", features = ["menu", "context_menu", "color_picker", "drop_down"] } +iced_aw = { git = "https://github.com/HakanSeven12/iced_aw.git", branch = "agent/fix-iced-fonts", features = ["menu", "context_menu", "drop_down", "number_input"] } bytemuck = { version = "1.25", features = ["derive"] } glam = { version = "0.33", features = ["bytemuck"] } rfd = "0.17" diff --git a/assets/icons/ui/eyedropper.svg b/assets/icons/ui/eyedropper.svg new file mode 100644 index 0000000000..fe34cd3f91 --- /dev/null +++ b/assets/icons/ui/eyedropper.svg @@ -0,0 +1 @@ + diff --git a/locales/ar-SA/opencadstudio.ftl b/locales/ar-SA/opencadstudio.ftl index 8ae21b684f..3e064a7f86 100644 --- a/locales/ar-SA/opencadstudio.ftl +++ b/locales/ar-SA/opencadstudio.ftl @@ -1350,15 +1350,14 @@ common = .dismiss = إغلاق .value-8a8de8 = ? .select-color-8dddf1 = { common.select-color }… - .no-recent-colors-yet = لا توجد ألوان حديثة بعد - .true-color-rgb = { common.true-color } RGB __ocs_fmt_0__, __ocs_fmt_1__, __ocs_fmt_2__ .index-color = { common.color } (ACI) .true-color = { common.color } (RGB) .standard-colors = { common.standard } · { common.color } + .color-hex = سداسي عشري + .nearest-index-color = أقرب فهرس + .exact-index-match = تطابق تام مع الفهرس .cad-color-index-aci-10-249 = فهرس ألوان ACI 10–249 - .color-family-shade-intensity = { common.color-family } → · { common.shade } / { properties.intensity } ↓ .grayscale-250-255 = { common.grayscale } 250–255 - .recently-used = المستخدمة مؤخرًا .isometric-drafting = الرسم متساوي القياس .f5-cycles-the-active-plane = يبدّل F5 المستوى النشط بالتتابع. .units-5430a1 = { common.units }… diff --git a/locales/bg-BG/opencadstudio.ftl b/locales/bg-BG/opencadstudio.ftl index 77df7cecdf..e02e20d0f9 100644 --- a/locales/bg-BG/opencadstudio.ftl +++ b/locales/bg-BG/opencadstudio.ftl @@ -1337,15 +1337,14 @@ common = .dismiss = Затваряне .value-8a8de8 = ? .select-color-8dddf1 = { common.select-color }… - .no-recent-colors-yet = Все още няма скорошни цветове - .true-color-rgb = { common.true-color } RGB __ocs_fmt_0__, __ocs_fmt_1__, __ocs_fmt_2__ .index-color = { common.color } (ACI) .true-color = { common.color } (RGB) .standard-colors = { common.standard } · { common.color } + .color-hex = Hex + .nearest-index-color = Най-близък индекс + .exact-index-match = Точно съвпадение с индекс .cad-color-index-aci-10-249 = ACI Цветови индекс 10–249 - .color-family-shade-intensity = { common.color-family } → · { common.shade } / { properties.intensity } ↓ .grayscale-250-255 = { common.grayscale } 250–255 - .recently-used = Последно използвани .isometric-drafting = Изометрично чертане .f5-cycles-the-active-plane = F5 превключва последователно активната равнина. .units-5430a1 = { common.units }… diff --git a/locales/cs-CZ/opencadstudio.ftl b/locales/cs-CZ/opencadstudio.ftl index 9c46559d10..544cbc5c6c 100644 --- a/locales/cs-CZ/opencadstudio.ftl +++ b/locales/cs-CZ/opencadstudio.ftl @@ -1337,15 +1337,14 @@ common = .dismiss = Zavřít .value-8a8de8 = ? .select-color-8dddf1 = { common.select-color }… - .no-recent-colors-yet = Zatím žádné nedávné barvy - .true-color-rgb = { common.true-color } RGB __ocs_fmt_0__, __ocs_fmt_1__, __ocs_fmt_2__ .index-color = { common.color } (ACI) .true-color = { common.color } (RGB) .standard-colors = { common.standard } · { common.color } + .color-hex = Hex + .nearest-index-color = Nejbližší index + .exact-index-match = Přesná shoda s indexem .cad-color-index-aci-10-249 = Barevný index ACI 10–249 - .color-family-shade-intensity = { common.color-family } → · { common.shade } / { properties.intensity } ↓ .grayscale-250-255 = { common.grayscale } 250–255 - .recently-used = Nedávno použité .isometric-drafting = Izometrické kreslení .f5-cycles-the-active-plane = F5 cyklicky přepíná aktivní rovinu. .units-5430a1 = { common.units }… diff --git a/locales/de-DE/opencadstudio.ftl b/locales/de-DE/opencadstudio.ftl index 9e70f9e311..8ca17932f8 100644 --- a/locales/de-DE/opencadstudio.ftl +++ b/locales/de-DE/opencadstudio.ftl @@ -1338,15 +1338,14 @@ common = .dismiss = Schließen .value-8a8de8 = ? .select-color-8dddf1 = { common.select-color }… - .no-recent-colors-yet = Noch keine zuletzt verwendeten Farben - .true-color-rgb = { common.true-color } RGB __ocs_fmt_0__, __ocs_fmt_1__, __ocs_fmt_2__ .index-color = { common.color } (ACI) .true-color = { common.color } (RGB) .standard-colors = { common.standard } · { common.color } + .color-hex = Hex + .nearest-index-color = Nächster Index + .exact-index-match = Exakter Index-Treffer .cad-color-index-aci-10-249 = ACI Farbindex 10–249 - .color-family-shade-intensity = { common.color-family } → · { common.shade } / { properties.intensity } ↓ .grayscale-250-255 = { common.grayscale } 250–255 - .recently-used = Zuletzt verwendet .isometric-drafting = Isometrisches Zeichnen .f5-cycles-the-active-plane = F5 wechselt die aktive Ebene der Reihe nach. .units-5430a1 = { common.units }… diff --git a/locales/el-GR/opencadstudio.ftl b/locales/el-GR/opencadstudio.ftl index d6ecc823e5..7c28112e92 100644 --- a/locales/el-GR/opencadstudio.ftl +++ b/locales/el-GR/opencadstudio.ftl @@ -1339,15 +1339,14 @@ common = .dismiss = Κλείσιμο .value-8a8de8 = ? .select-color-8dddf1 = { common.select-color }… - .no-recent-colors-yet = Δεν υπάρχουν ακόμη πρόσφατα χρώματα - .true-color-rgb = { common.true-color } RGB __ocs_fmt_0__, __ocs_fmt_1__, __ocs_fmt_2__ .index-color = { common.color } (ACI) .true-color = { common.color } (RGB) .standard-colors = { common.standard } · { common.color } + .color-hex = Hex + .nearest-index-color = Πλησιέστερος δείκτης + .exact-index-match = Ακριβής αντιστοίχιση δείκτη .cad-color-index-aci-10-249 = Δείκτης χρώματος ACI 10–249 - .color-family-shade-intensity = { common.color-family } → · { common.shade } / { properties.intensity } ↓ .grayscale-250-255 = { common.grayscale } 250–255 - .recently-used = Πρόσφατα χρησιμοποιημένα .isometric-drafting = Ισομετρική σχεδίαση .f5-cycles-the-active-plane = Το F5 εναλλάσσει το ενεργό επίπεδο. .units-5430a1 = { common.units }… diff --git a/locales/en-US/opencadstudio.ftl b/locales/en-US/opencadstudio.ftl index 078294c99a..20d9158c5c 100644 --- a/locales/en-US/opencadstudio.ftl +++ b/locales/en-US/opencadstudio.ftl @@ -1338,15 +1338,14 @@ common = .dismiss = Dismiss .value-8a8de8 = ? .select-color-8dddf1 = Select Color... - .no-recent-colors-yet = No recent colors yet - .true-color-rgb = True Color RGB __ocs_fmt_0__, __ocs_fmt_1__, __ocs_fmt_2__ .index-color = Index Color .true-color = True Color .standard-colors = Standard colors + .color-hex = Hex + .nearest-index-color = Nearest index + .exact-index-match = Exact index match .cad-color-index-aci-10-249 = CAD Color Index (ACI) 10–249 - .color-family-shade-intensity = Color family → · Shade / intensity ↓ .grayscale-250-255 = Grayscale 250–255 - .recently-used = Recently used .isometric-drafting = Isometric drafting .f5-cycles-the-active-plane = F5 cycles the active plane. .units-5430a1 = Units… diff --git a/locales/es-ES/opencadstudio.ftl b/locales/es-ES/opencadstudio.ftl index a1cc0ff99d..02f7d27aa9 100644 --- a/locales/es-ES/opencadstudio.ftl +++ b/locales/es-ES/opencadstudio.ftl @@ -1338,15 +1338,14 @@ common = .dismiss = Cerrar .value-8a8de8 = ? .select-color-8dddf1 = { common.select-color }… - .no-recent-colors-yet = Aún no hay colores recientes - .true-color-rgb = { common.true-color } RGB __ocs_fmt_0__, __ocs_fmt_1__, __ocs_fmt_2__ .index-color = { common.color } (ACI) .true-color = { common.color } (RGB) .standard-colors = { common.standard } · { common.color } + .color-hex = Hex + .nearest-index-color = Índice más cercano + .exact-index-match = Coincide con un índice .cad-color-index-aci-10-249 = Índice de color ACI 10–249 - .color-family-shade-intensity = { common.color-family } → · { common.shade } / { properties.intensity } ↓ .grayscale-250-255 = { common.grayscale } 250–255 - .recently-used = Usados recientemente .isometric-drafting = Dibujo isométrico .f5-cycles-the-active-plane = F5 alterna el plano activo. .units-5430a1 = { common.units }… diff --git a/locales/fi-FI/opencadstudio.ftl b/locales/fi-FI/opencadstudio.ftl index 7147a6f328..2cd800ab58 100644 --- a/locales/fi-FI/opencadstudio.ftl +++ b/locales/fi-FI/opencadstudio.ftl @@ -1337,15 +1337,14 @@ common = .dismiss = Sulje .value-8a8de8 = ? .select-color-8dddf1 = { common.select-color }… - .no-recent-colors-yet = Ei vielä viimeksi käytettyjä värejä - .true-color-rgb = { common.true-color } RGB __ocs_fmt_0__, __ocs_fmt_1__, __ocs_fmt_2__ .index-color = { common.color } (ACI) .true-color = { common.color } (RGB) .standard-colors = { common.standard } · { common.color } + .color-hex = Hex + .nearest-index-color = Lähin indeksi + .exact-index-match = Täsmälleen indeksiväri .cad-color-index-aci-10-249 = ACI väriindeksi 10–249 - .color-family-shade-intensity = { common.color-family } → · { common.shade } / { properties.intensity } ↓ .grayscale-250-255 = { common.grayscale } 250–255 - .recently-used = Viimeksi käytetyt .isometric-drafting = Isometrinen piirtäminen .f5-cycles-the-active-plane = F5 vaihtaa aktiivista tasoa. .units-5430a1 = { common.units }… diff --git a/locales/fr-FR/opencadstudio.ftl b/locales/fr-FR/opencadstudio.ftl index 2974e3e5ca..562ba530dc 100644 --- a/locales/fr-FR/opencadstudio.ftl +++ b/locales/fr-FR/opencadstudio.ftl @@ -1338,15 +1338,14 @@ common = .dismiss = Fermer .value-8a8de8 = ? .select-color-8dddf1 = { common.select-color }… - .no-recent-colors-yet = Aucune couleur récente - .true-color-rgb = { common.true-color } RGB __ocs_fmt_0__, __ocs_fmt_1__, __ocs_fmt_2__ .index-color = { common.color } (ACI) .true-color = { common.color } (RGB) .standard-colors = { common.standard } · { common.color } + .color-hex = Hex + .nearest-index-color = Index le plus proche + .exact-index-match = Correspondance exacte d'index .cad-color-index-aci-10-249 = ACI Indice de couleur 10–249 - .color-family-shade-intensity = { common.color-family } → · { common.shade } / { properties.intensity } ↓ .grayscale-250-255 = { common.grayscale } 250–255 - .recently-used = Utilisés récemment .isometric-drafting = Dessin isométrique .f5-cycles-the-active-plane = F5 fait défiler les plans actifs. .units-5430a1 = { common.units }… diff --git a/locales/hi-IN/opencadstudio.ftl b/locales/hi-IN/opencadstudio.ftl index 0480734a70..38dd1bc640 100644 --- a/locales/hi-IN/opencadstudio.ftl +++ b/locales/hi-IN/opencadstudio.ftl @@ -1326,15 +1326,14 @@ common = .dismiss = बंद करें .value-8a8de8 = ? .select-color-8dddf1 = { common.select-color }… - .no-recent-colors-yet = अभी कोई हालिया रंग नहीं है - .true-color-rgb = { common.true-color } RGB __ocs_fmt_0__, __ocs_fmt_1__, __ocs_fmt_2__ .index-color = { common.color } (ACI) .true-color = { common.color } (RGB) .standard-colors = { common.standard } · { common.color } + .color-hex = हेक्स + .nearest-index-color = निकटतम इंडेक्स + .exact-index-match = इंडेक्स से सटीक मेल .cad-color-index-aci-10-249 = ACI रंग सूचकांक 10–249 - .color-family-shade-intensity = { common.color-family } → · { common.shade } / { properties.intensity } ↓ .grayscale-250-255 = { common.grayscale } 250–255 - .recently-used = हाल में उपयोग किए गए .isometric-drafting = सममितीय आरेखन .f5-cycles-the-active-plane = F5 सक्रिय तल को क्रम से बदलता है। .units-5430a1 = { common.units }… diff --git a/locales/hu-HU/opencadstudio.ftl b/locales/hu-HU/opencadstudio.ftl index d99eea6b37..c2c689c6f2 100644 --- a/locales/hu-HU/opencadstudio.ftl +++ b/locales/hu-HU/opencadstudio.ftl @@ -1337,15 +1337,14 @@ common = .dismiss = Bezárás .value-8a8de8 = ? .select-color-8dddf1 = { common.select-color }… - .no-recent-colors-yet = Még nincsenek legutóbbi színek - .true-color-rgb = { common.true-color } RGB __ocs_fmt_0__, __ocs_fmt_1__, __ocs_fmt_2__ .index-color = { common.color } (ACI) .true-color = { common.color } (RGB) .standard-colors = { common.color } ({ common.standard }) + .color-hex = Hex + .nearest-index-color = Legközelebbi index + .exact-index-match = Pontos indexegyezés .cad-color-index-aci-10-249 = ACI színindex 10–249 - .color-family-shade-intensity = { common.color-family } → · { common.shade } / { properties.intensity } ↓ .grayscale-250-255 = { common.grayscale } 250–255 - .recently-used = Legutóbb használt .isometric-drafting = Izometrikus rajzolás .f5-cycles-the-active-plane = Az F5 váltja az aktív síkot. .units-5430a1 = { common.units }… diff --git a/locales/it-IT/opencadstudio.ftl b/locales/it-IT/opencadstudio.ftl index de2d9153e7..8af2dad92f 100644 --- a/locales/it-IT/opencadstudio.ftl +++ b/locales/it-IT/opencadstudio.ftl @@ -1337,15 +1337,14 @@ common = .dismiss = Chiudi .value-8a8de8 = ? .select-color-8dddf1 = { common.select-color }… - .no-recent-colors-yet = Nessun colore recente - .true-color-rgb = { common.true-color } RGB __ocs_fmt_0__, __ocs_fmt_1__, __ocs_fmt_2__ .index-color = { common.color } (ACI) .true-color = { common.color } (RGB) .standard-colors = { common.standard } · { common.color } + .color-hex = Hex + .nearest-index-color = Indice più vicino + .exact-index-match = Corrispondenza esatta indice .cad-color-index-aci-10-249 = ACI Indice colori 10–249 - .color-family-shade-intensity = { common.color-family } → · { common.shade } / { properties.intensity } ↓ .grayscale-250-255 = { common.grayscale } 250–255 - .recently-used = Usati di recente .isometric-drafting = Disegno isometrico .f5-cycles-the-active-plane = F5 alterna il piano attivo. .units-5430a1 = { common.units }… diff --git a/locales/ja-JP/opencadstudio.ftl b/locales/ja-JP/opencadstudio.ftl index 272c408464..e221469e4d 100644 --- a/locales/ja-JP/opencadstudio.ftl +++ b/locales/ja-JP/opencadstudio.ftl @@ -1328,15 +1328,14 @@ common = .dismiss = 閉じる .value-8a8de8 = ? .select-color-8dddf1 = { common.select-color }… - .no-recent-colors-yet = 最近使った色はありません - .true-color-rgb = { common.true-color } RGB __ocs_fmt_0__, __ocs_fmt_1__, __ocs_fmt_2__ .index-color = { common.color } (ACI) .true-color = { common.color } (RGB) .standard-colors = { common.standard } · { common.color } + .color-hex = 16進 + .nearest-index-color = 最も近いインデックス + .exact-index-match = インデックスと完全一致 .cad-color-index-aci-10-249 = ACI カラーインデックス 10–249 - .color-family-shade-intensity = { common.color-family } → · { common.shade } / { properties.intensity } ↓ .grayscale-250-255 = { common.grayscale } 250–255 - .recently-used = 最近使用した色 .isometric-drafting = アイソメ図作成 .f5-cycles-the-active-plane = F5でアクティブな平面を順に切り替えます。 .units-5430a1 = { common.units }… diff --git a/locales/ko-KR/opencadstudio.ftl b/locales/ko-KR/opencadstudio.ftl index a24c5a4967..931a8f7460 100644 --- a/locales/ko-KR/opencadstudio.ftl +++ b/locales/ko-KR/opencadstudio.ftl @@ -1337,15 +1337,14 @@ common = .dismiss = 닫기 .value-8a8de8 = ? .select-color-8dddf1 = { common.select-color }… - .no-recent-colors-yet = 최근 사용한 색상이 없습니다 - .true-color-rgb = { common.true-color } RGB __ocs_fmt_0__, __ocs_fmt_1__, __ocs_fmt_2__ .index-color = { common.color } (ACI) .true-color = { common.color } (RGB) .standard-colors = { common.standard } · { common.color } + .color-hex = 16진수 + .nearest-index-color = 가장 가까운 인덱스 + .exact-index-match = 인덱스와 정확히 일치 .cad-color-index-aci-10-249 = ACI 컬러 인덱스 10–249 - .color-family-shade-intensity = { common.color-family } → · { common.shade } / { properties.intensity } ↓ .grayscale-250-255 = { common.grayscale } 250–255 - .recently-used = 최근 사용 .isometric-drafting = 등각 제도 .f5-cycles-the-active-plane = F5 키로 활성 평면을 순환 전환합니다. .units-5430a1 = { common.units }… diff --git a/locales/lo-LA/opencadstudio.ftl b/locales/lo-LA/opencadstudio.ftl index 7fc072257b..49f8057440 100644 --- a/locales/lo-LA/opencadstudio.ftl +++ b/locales/lo-LA/opencadstudio.ftl @@ -1343,15 +1343,14 @@ common = .dismiss = ປິດອອກ .value-8a8de8 = ? .select-color-8dddf1 = ເລືອກສີ... - .no-recent-colors-yet = ຍັງບໍ່ມີສີຫຼ້າສຸດ - .true-color-rgb = True Color RGB __ocs_fmt_0__, __ocs_fmt_1__, __ocs_fmt_2__ .index-color = ສີດັດຊະນີ .true-color = True Color .standard-colors = ສີມາດຕະຖານ + .color-hex = Hex + .nearest-index-color = ດັດຊະນີທີ່ໃກ້ທີ່ສຸດ + .exact-index-match = ກົງກັບດັດຊະນີພໍດີ .cad-color-index-aci-10-249 = CAD Color Index (ACI) 10–249 - .color-family-shade-intensity = ກຸ່ມສີ → · ລະດັບສີ / ຄວາມເຂັ້ມ ↓ .grayscale-250-255 = ລະດັບສີເທົາ 250–255 - .recently-used = ໃຊ້ຫຼ້າສຸດ .isometric-drafting = ການຂຽນແບບໄອໂຊເມຕຣິກ .f5-cycles-the-active-plane = F5 ປ່ຽນລະນາບທີ່ໃຊ້ງານວຽນໄປ. .units-5430a1 = ຫົວໜ່ວຍ… diff --git a/locales/nl-NL/opencadstudio.ftl b/locales/nl-NL/opencadstudio.ftl index a73bc3748d..fb4af2b560 100644 --- a/locales/nl-NL/opencadstudio.ftl +++ b/locales/nl-NL/opencadstudio.ftl @@ -1336,15 +1336,14 @@ common = .dismiss = Sluiten .value-8a8de8 = ? .select-color-8dddf1 = { common.select-color }… - .no-recent-colors-yet = Nog geen recente kleuren - .true-color-rgb = { common.true-color } RGB __ocs_fmt_0__, __ocs_fmt_1__, __ocs_fmt_2__ .index-color = { common.color } (ACI) .true-color = { common.color } (RGB) .standard-colors = { common.standard } · { common.color } + .color-hex = Hex + .nearest-index-color = Dichtstbijzijnde index + .exact-index-match = Exacte indexkleur .cad-color-index-aci-10-249 = ACI Kleurindex 10–249 - .color-family-shade-intensity = { common.color-family } → · { common.shade } / { properties.intensity } ↓ .grayscale-250-255 = { common.grayscale } 250–255 - .recently-used = Recent gebruikt .isometric-drafting = Isometrisch tekenen .f5-cycles-the-active-plane = F5 wisselt het actieve vlak. .units-5430a1 = { common.units }… diff --git a/locales/pl-PL/opencadstudio.ftl b/locales/pl-PL/opencadstudio.ftl index bc0f2f9672..cc06b8293a 100644 --- a/locales/pl-PL/opencadstudio.ftl +++ b/locales/pl-PL/opencadstudio.ftl @@ -1337,15 +1337,14 @@ common = .dismiss = Zamknij .value-8a8de8 = ? .select-color-8dddf1 = { common.select-color }… - .no-recent-colors-yet = Brak ostatnio używanych kolorów - .true-color-rgb = { common.true-color } RGB __ocs_fmt_0__, __ocs_fmt_1__, __ocs_fmt_2__ .index-color = { common.color } (ACI) .true-color = { common.color } (RGB) .standard-colors = { common.standard } · { common.color } + .color-hex = Hex + .nearest-index-color = Najbliższy indeks + .exact-index-match = Dokładne dopasowanie indeksu .cad-color-index-aci-10-249 = Indeks kolorów ACI 10–249 - .color-family-shade-intensity = { common.color-family } → · { common.shade } / { properties.intensity } ↓ .grayscale-250-255 = { common.grayscale } 250–255 - .recently-used = Ostatnio używane .isometric-drafting = Rysowanie izometryczne .f5-cycles-the-active-plane = F5 przełącza aktywną płaszczyznę. .units-5430a1 = { common.units }… diff --git a/locales/pt-BR/opencadstudio.ftl b/locales/pt-BR/opencadstudio.ftl index 4e504b8a25..3b8aedc440 100644 --- a/locales/pt-BR/opencadstudio.ftl +++ b/locales/pt-BR/opencadstudio.ftl @@ -1338,15 +1338,14 @@ common = .dismiss = Fechar .value-8a8de8 = ? .select-color-8dddf1 = { common.select-color }… - .no-recent-colors-yet = Nenhuma cor recente ainda - .true-color-rgb = { common.true-color } RGB __ocs_fmt_0__, __ocs_fmt_1__, __ocs_fmt_2__ .index-color = { common.color } (ACI) .true-color = { common.color } (RGB) .standard-colors = { common.standard } · { common.color } + .color-hex = Hex + .nearest-index-color = Índice mais próximo + .exact-index-match = Corresponde exatamente ao índice .cad-color-index-aci-10-249 = Índice de cor ACI 10–249 - .color-family-shade-intensity = { common.color-family } → · { common.shade } / { properties.intensity } ↓ .grayscale-250-255 = { common.grayscale } 250–255 - .recently-used = Usados recentemente .isometric-drafting = Desenho isométrico .f5-cycles-the-active-plane = F5 alterna o plano ativo. .units-5430a1 = { common.units }… diff --git a/locales/ru-RU/opencadstudio.ftl b/locales/ru-RU/opencadstudio.ftl index 00699e37b9..c8e2554134 100644 --- a/locales/ru-RU/opencadstudio.ftl +++ b/locales/ru-RU/opencadstudio.ftl @@ -1341,15 +1341,14 @@ common = .dismiss = Закрыть .value-8a8de8 = ? .select-color-8dddf1 = { common.select-color }… - .no-recent-colors-yet = Недавно использованных цветов пока нет - .true-color-rgb = { common.true-color } RGB __ocs_fmt_0__, __ocs_fmt_1__, __ocs_fmt_2__ .index-color = { common.color } (ACI) .true-color = { common.color } (RGB) .standard-colors = { common.standard } · { common.color } + .color-hex = Hex + .nearest-index-color = Ближайший индекс + .exact-index-match = Точное совпадение с индексом .cad-color-index-aci-10-249 = Индекс цвета ACI 10–249 - .color-family-shade-intensity = { common.color-family } → · { common.shade } / { properties.intensity } ↓ .grayscale-250-255 = { common.grayscale } 250–255 - .recently-used = Недавно использованные .isometric-drafting = Изометрическое черчение .f5-cycles-the-active-plane = F5 циклически переключает активную плоскость. .units-5430a1 = { common.units }… diff --git a/locales/tr-TR/opencadstudio.ftl b/locales/tr-TR/opencadstudio.ftl index 10fec03ec3..a2fe8529d2 100644 --- a/locales/tr-TR/opencadstudio.ftl +++ b/locales/tr-TR/opencadstudio.ftl @@ -1324,15 +1324,14 @@ common = .dismiss = Kapat .value-8a8de8 = ? .select-color-8dddf1 = { common.select-color }… - .no-recent-colors-yet = Henüz son kullanılan renk yok - .true-color-rgb = { common.true-color } RGB __ocs_fmt_0__, __ocs_fmt_1__, __ocs_fmt_2__ .index-color = { common.color } (ACI) .true-color = { common.color } (RGB) .standard-colors = { common.standard } · { common.color } + .color-hex = Hex + .nearest-index-color = En yakın indeks + .exact-index-match = Tam indeks eşleşmesi .cad-color-index-aci-10-249 = ACI renk dizini 10–249 - .color-family-shade-intensity = { common.color-family } → · { common.shade } / { properties.intensity } ↓ .grayscale-250-255 = { common.grayscale } 250–255 - .recently-used = Son kullanılanlar .isometric-drafting = İzometrik çizim .f5-cycles-the-active-plane = F5 etkin düzlemi sırayla değiştirir. .units-5430a1 = { common.units }… diff --git a/locales/zh-CN/opencadstudio.ftl b/locales/zh-CN/opencadstudio.ftl index 710214e955..af02d48a43 100644 --- a/locales/zh-CN/opencadstudio.ftl +++ b/locales/zh-CN/opencadstudio.ftl @@ -1325,15 +1325,14 @@ common = .dismiss = 关闭 .value-8a8de8 = ? .select-color-8dddf1 = { common.select-color }… - .no-recent-colors-yet = 尚无最近使用的颜色 - .true-color-rgb = { common.true-color } RGB __ocs_fmt_0__, __ocs_fmt_1__, __ocs_fmt_2__ .index-color = { common.color } (ACI) .true-color = { common.color } (RGB) .standard-colors = { common.standard } · { common.color } + .color-hex = 十六进制 + .nearest-index-color = 最接近的索引色 + .exact-index-match = 与索引色完全匹配 .cad-color-index-aci-10-249 = ACI 颜色索引 10–249 - .color-family-shade-intensity = { common.color-family } → · { common.shade } / { properties.intensity } ↓ .grayscale-250-255 = { common.grayscale } 250–255 - .recently-used = 最近使用 .isometric-drafting = 等轴测绘图 .f5-cycles-the-active-plane = F5 循环切换活动平面。 .units-5430a1 = { common.units }… diff --git a/locales/zh-TW/opencadstudio.ftl b/locales/zh-TW/opencadstudio.ftl index ca3f9fd1d4..11b4868a6e 100644 --- a/locales/zh-TW/opencadstudio.ftl +++ b/locales/zh-TW/opencadstudio.ftl @@ -1337,15 +1337,14 @@ common = .dismiss = 關閉 .value-8a8de8 = ? .select-color-8dddf1 = { common.select-color }… - .no-recent-colors-yet = 尚無最近使用的顏色 - .true-color-rgb = { common.true-color } RGB __ocs_fmt_0__, __ocs_fmt_1__, __ocs_fmt_2__ .index-color = { common.color } (ACI) .true-color = { common.color } (RGB) .standard-colors = { common.standard } · { common.color } + .color-hex = 十六進位 + .nearest-index-color = 最接近的索引色 + .exact-index-match = 與索引色完全相符 .cad-color-index-aci-10-249 = ACI 顏色索引 10–249 - .color-family-shade-intensity = { common.color-family } → · { common.shade } / { properties.intensity } ↓ .grayscale-250-255 = { common.grayscale } 250–255 - .recently-used = 最近使用 .isometric-drafting = 等角製圖 .f5-cycles-the-active-plane = F5 循環切換作用中平面。 .units-5430a1 = { common.units }… diff --git a/src/app/dock/view.rs b/src/app/dock/view.rs index 7fb744d6ab..a50d6ee86d 100644 --- a/src/app/dock/view.rs +++ b/src/app/dock/view.rs @@ -391,8 +391,8 @@ impl OpenCADStudio { .location(id) .map_or(crate::app::config::DockSide::Right, |(side, _)| side), matches!( - self.color_pick_target, - Some((crate::app::ColorPickTarget::Gradient(_), _)) + self.color_picker.as_ref().map(|picker| &picker.target), + Some(crate::app::ColorPickTarget::Gradient(_)) ), ), crate::ui::dock::PanelId::BlockPalette => { diff --git a/src/app/mod.rs b/src/app/mod.rs index e15238efc7..73e7b8c630 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -844,9 +844,6 @@ pub(super) struct OpenCADStudio { pub(crate) sheet_set_pending_layout: Option<(String, String)>, /// The subset / set Import Layout as Sheet adds to, while its file picker is open. pub(crate) sheet_set_import_parent: Option, - /// Which viewport background the colour wheel is editing, or `None` when - /// it is closed. One slot, because only one wheel can be open at a time. - pub(crate) bg_picker: Option, /// General edge-stack dock layout for the side panels. pub(crate) dock: crate::ui::dock::DockState, /// Pallet revealed although it auto-hides (its edge's group, or its @@ -966,10 +963,8 @@ pub(super) struct OpenCADStudio { #[cfg(target_arch = "wasm32")] web_autosave_clear_after: Vec, // ── Floating panel windows ──────────────────────────────────────────── - /// Active `iced_aw` colour picker: destination plus its initial colour. - color_pick_target: Option<(ColorPickTarget, AcadColor)>, - /// Visible page in the shared CAD colour picker. - color_picker_tab: ColorPickerTab, + /// The open Select Color panel, if any. + color_picker: Option, /// Recently committed real colours, newest first. /// ACI and True Color remain semantically distinct even when their RGB matches. recent_colors: Vec, @@ -1670,21 +1665,19 @@ pub struct SaveOutcome { refreshed_preview: Option>, result: Result<(), crate::io::SaveFailure>, } -/// Which viewport background a colour-wheel session is editing. +/// Which Options colour the interface colour picker is editing. #[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum BgTarget { - Model, - Paper, - Desk, +pub enum UiColor { + ModelBackground, + PaperBackground, + DeskBackground, + /// One of the six theme colours, by its row in Options. + Theme(usize), + Crosshair, + SnapMarker, + CommandText, } -/// Active page in the shared CAD colour picker. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -pub enum ColorPickerTab { - #[default] - Index, - TrueColor, -} /// Where a colour chosen in the standalone palette window should be applied. #[derive(Debug, Clone)] pub enum ColorPickTarget { @@ -1710,6 +1703,8 @@ pub enum ColorPickTarget { LayerState(usize), /// The MText editor's selection (or global) colour. MText, + /// An Options interface colour (true colour only). + Interface(UiColor), } /// Table records the clipboard entities depend on, snapshotted from the source @@ -2465,12 +2460,6 @@ pub enum Message { ModelSpaceModeChanged(config::ModelSpaceMode), /// Change Model Space custom background color as hex or empty for default. ModelSpaceBgChanged(String), - /// Open the colour wheel on one of the viewport backgrounds. - BgPickerOpen(BgTarget), - /// Dismiss the wheel, changing nothing. - BgPickerCancel, - /// Accept the wheel's colour for whichever background it was opened on. - BgPickerSubmit(iced::Color), /// Change Paper Space custom sheet background color as hex or empty for default. PaperSpaceBgChanged(String), /// Change Paper Space desk surround background (#RRGGBB). @@ -4175,10 +4164,8 @@ pub enum Message { DsColorMore(DsField), /// Open the shared CAD colour picker for a field and its current colour. OpenColorWindow(ColorPickTarget, AcadColor), - /// Switch between Index Color and True Color. - ColorPickerTabChanged(ColorPickerTab), - /// Change the pending colour without committing it yet. - ColorPickerColorChanged(AcadColor), + /// Interaction inside the Select Color panel. + ColorPicker(crate::ui::color_select::ColorPickerMsg), /// Close the colour picker without choosing. CloseColorPicker, /// Commit the colour chosen in the shared picker. @@ -4565,7 +4552,6 @@ impl OpenCADStudio { sheet_set: Default::default(), sheet_set_pending_layout: None, sheet_set_import_parent: None, - bg_picker: None, block_palette: Default::default(), xref_manager: Default::default(), dock: Default::default(), @@ -4614,8 +4600,7 @@ impl OpenCADStudio { web_autosave_consumed: None, #[cfg(target_arch = "wasm32")] web_autosave_clear_after: Vec::new(), - color_pick_target: None, - color_picker_tab: ColorPickerTab::Index, + color_picker: None, recent_colors: Vec::new(), active_modal: None, hyperlink_editor_handles: Vec::new(), diff --git a/src/app/update/mod.rs b/src/app/update/mod.rs index f9593c4cf2..c467d0468f 100644 --- a/src/app/update/mod.rs +++ b/src/app/update/mod.rs @@ -378,6 +378,41 @@ impl OpenCADStudio { let tab = &self.tabs[self.active_tab]; (started, tab.id, tab.scene.geometry_epoch) }); + // The Select Color panel can open on top of another dialog, so it + // takes the keyboard first: Esc cancels, Enter confirms, the arrows + // walk the index palette, and every other keystroke is swallowed. + if self.color_picker.is_some() { + use crate::ui::color_select::ColorPickerMsg; + match &msg { + Message::CommandEscape => { + return self.update(Message::ColorPicker(ColorPickerMsg::Cancel)); + } + Message::CommandFinalize => { + return self.update(Message::ColorPicker(ColorPickerMsg::Ok)); + } + Message::ShortcutPressed(key) => match key.rsplit('+').next() { + Some("ESCAPE") => { + return self.update(Message::ColorPicker(ColorPickerMsg::Cancel)); + } + Some("ENTER" | "RETURN") => { + return self.update(Message::ColorPicker(ColorPickerMsg::Ok)); + } + Some("TAB") => { + return crate::ui::color_select::picker::focus_step( + !key.contains("SHIFT+"), + ); + } + _ => {} + }, + Message::ArrowKeyPressed { direction, .. } => { + return self.update(Message::ColorPicker(ColorPickerMsg::Arrow(*direction))); + } + _ => {} + } + if is_modal_blocked_key_msg(&msg) { + return Task::none(); + } + } // A modal dialog must capture the keyboard the same way it already // captures the mouse. Otherwise keystrokes from the global key // subscription leak past the modal into the command line and fire as @@ -4275,7 +4310,7 @@ impl OpenCADStudio { Message::PaneClicked(pane) => self.on_pane_clicked(pane), Message::PaneDragged(ev) => self.on_pane_dragged(ev), Message::PaneMove(idx, local) => { - if self.color_pick_target.is_some() { + if self.color_picker.is_some() { return Task::none(); } let p = self.pane_canvas_point(idx, local); @@ -8736,39 +8771,6 @@ impl OpenCADStudio { Task::none() } - Message::BgPickerOpen(target) => { - self.bg_picker = Some(target); - Task::none() - } - - Message::BgPickerCancel => { - self.bg_picker = None; - Task::none() - } - - Message::BgPickerSubmit(color) => { - // Hand the result to the same handler the typed hex field - // uses, so the wheel and the field cannot drift apart on - // validation, persistence or the MatchTheme fallback. - let hex = crate::app::config::rgb_to_hex([ - (color.r * 255.0).round() as u8, - (color.g * 255.0).round() as u8, - (color.b * 255.0).round() as u8, - ]); - match self.bg_picker.take() { - Some(crate::app::BgTarget::Model) => { - Task::done(Message::ModelSpaceBgChanged(hex)) - } - Some(crate::app::BgTarget::Paper) => { - Task::done(Message::PaperSpaceBgChanged(hex)) - } - Some(crate::app::BgTarget::Desk) => { - Task::done(Message::DeskSpaceBgChanged(hex)) - } - None => Task::none(), - } - } - Message::ModelSpaceBgChanged(hex) => { self.model_bg_input = hex.clone(); if hex.trim().is_empty() { @@ -11603,10 +11605,10 @@ impl OpenCADStudio { ) { self.graphic_attributes.open_menu = None; } - self.color_pick_target = Some((target, color)); - - // Always open the shared CAD colour picker on the indexed ACI page. - self.color_picker_tab = crate::app::ColorPickerTab::Index; + let (current, varies) = self.color_picker_current(&target, color); + self.color_picker = Some(crate::ui::color_select::ColorPicker::new( + target, current, varies, + )); self.modal_offset = iced::Vector::ZERO; self.ds_color_open = None; self.mls_color_open = None; @@ -11621,29 +11623,87 @@ impl OpenCADStudio { Task::none() } - Message::ColorPickerTabChanged(tab) => { - self.color_picker_tab = tab; - Task::none() - } - Message::ColorPickerColorChanged(color) => { - if let Some((_, current)) = self.color_pick_target.as_mut() { - *current = color; + Message::ColorPicker(msg) => { + let Some(picker) = self.color_picker.as_mut() else { + return Task::none(); + }; + match picker.update(msg) { + Some(crate::ui::color_select::Outcome::Commit(color)) => { + self.update(Message::ColorWindowPick(color)) + } + Some(crate::ui::color_select::Outcome::Cancel) => { + self.color_picker = None; + Task::none() + } + Some(crate::ui::color_select::Outcome::Screenshot) => { + use crate::ui::color_select::{eyedropper::EyedropperMsg, ColorPickerMsg}; + match self.main_window { + Some(id) => iced::window::screenshot(id).map(|shot| { + Message::ColorPicker(ColorPickerMsg::Eyedropper( + EyedropperMsg::Shot(shot), + )) + }), + // Nothing to capture: leave the eyedropper instead + // of waiting for a screenshot that never comes. + None => self.update(Message::ColorPicker(ColorPickerMsg::Cancel)), + } + } + None => Task::none(), } - Task::none() } Message::CloseColorPicker => { - self.color_pick_target = None; + self.color_picker = None; Task::none() } Message::ColorWindowPick(color) => { - self.note_recent_color(color); + // Interface colours are not drawing colours: keep them out of + // the recent list. + if !matches!( + self.color_picker.as_ref().map(|picker| &picker.target), + Some(crate::app::ColorPickTarget::Interface(_)) + ) { + self.note_recent_color(color); + } self.on_color_window_pick(color) } Message::DsSetHandle { field, value } => self.on_ds_set_handle(field, value), } } + /// The colour the Select Color panel shows as "Current", and whether the + /// selection it edits has mixed colours. A mixed selection starts from the + /// colour of its most recently drawn object (the highest handle). + fn color_picker_current( + &self, + target: &crate::app::ColorPickTarget, + color: codec::types::Color, + ) -> (codec::types::Color, bool) { + if !matches!(target, crate::app::ColorPickTarget::Properties) { + return (color, false); + } + let i = self.active_tab; + let document = &self.tabs[i].scene.document; + let mut colors = self + .property_target_handles(i) + .into_iter() + .filter_map(|handle| { + document + .get_entity(handle) + .map(|entity| (handle, entity.common().color)) + }) + .collect::>(); + let Some(&(_, first)) = colors.first() else { + return (color, false); + }; + if colors.iter().all(|&(_, c)| c == first) { + return (first, false); + } + colors.sort_by_key(|&(handle, _)| handle); + let newest = colors.last().map_or(color, |&(_, c)| c); + (newest, true) + } + pub(crate) fn note_recent_color(&mut self, color: codec::types::Color) { // Keep only real colours in the recent list. ByLayer / ByBlock / None // are logical CAD states rather than reusable colours. diff --git a/src/app/update/style.rs b/src/app/update/style.rs index 2deac74ecc..bb944373d4 100644 --- a/src/app/update/style.rs +++ b/src/app/update/style.rs @@ -1137,11 +1137,35 @@ impl OpenCADStudio { } pub(super) fn on_color_window_pick(&mut self, color: codec::types::Color) -> Task { + if let Some(crate::app::ColorPickTarget::Interface(target)) = self + .color_picker + .as_ref() + .map(|picker| picker.target.clone()) + { + self.color_picker = None; + let Some((r, g, b)) = crate::ui::color_select::math::color_rgb(color) else { + return Task::none(); + }; + // Hand the result to the same handler the typed hex field uses, so + // the picker and the field cannot drift apart on validation or + // persistence. + let hex = crate::app::config::rgb_to_hex([r, g, b]); + use crate::app::UiColor; + return Task::done(match target { + UiColor::ModelBackground => Message::ModelSpaceBgChanged(hex), + UiColor::PaperBackground => Message::PaperSpaceBgChanged(hex), + UiColor::DeskBackground => Message::DeskSpaceBgChanged(hex), + UiColor::Theme(index) => Message::OptionsThemeColorChanged(index, hex), + UiColor::Crosshair => Message::CrosshairColorChanged(hex), + UiColor::SnapMarker => Message::SnapMarkerColorChanged(hex), + UiColor::CommandText => Message::CommandTextColorChanged(hex), + }); + } if matches!( - self.color_pick_target.as_ref().map(|(target, _)| target), + self.color_picker.as_ref().map(|picker| &picker.target), Some(crate::app::ColorPickTarget::PlotStyle) ) { - self.color_pick_target = None; + self.color_picker = None; let rgb = match color { codec::types::Color::Rgb { r, g, b } => Some((r, g, b)), @@ -1156,7 +1180,7 @@ impl OpenCADStudio { return self.on_plot_style_panel_apply(); } let s = crate::ui::color_select::color_to_aci_string(color); - let edit = match self.color_pick_target.take().map(|(target, _)| target) { + let edit = match self.color_picker.take().map(|picker| picker.target) { Some(crate::app::ColorPickTarget::Gradient(index)) => { Some(Message::GraphicAttributes(GraphicAttributesMsg::Gradient( crate::ui::window::gradient_editor::GradientMsg::Color(index, color), @@ -1199,7 +1223,10 @@ impl OpenCADStudio { Some(crate::app::ColorPickTarget::LayerState(idx)) => { Some(Message::LayerStateEditorLayerColor(idx, color)) } - Some(crate::app::ColorPickTarget::PlotStyle) => None, + // Handled before this match. + Some( + crate::app::ColorPickTarget::PlotStyle | crate::app::ColorPickTarget::Interface(_), + ) => None, None => None, }; if let Some(m) = edit { diff --git a/src/app/update/viewport.rs b/src/app/update/viewport.rs index 2f81f6abeb..343e3b37a5 100644 --- a/src/app/update/viewport.rs +++ b/src/app/update/viewport.rs @@ -1119,7 +1119,7 @@ impl OpenCADStudio { p: Point, expected_viewport: Option, ) -> Task { - if self.color_pick_target.is_some() { + if self.color_picker.is_some() { return Task::none(); } @@ -1207,7 +1207,7 @@ impl OpenCADStudio { // leaks through the stack to the pane mouse_area beneath and // would track the crosshair over the dropdown's empty areas. // Drop the move here instead. (#227) - if self.ribbon.open_dropdown.is_some() || self.color_pick_target.is_some() { + if self.ribbon.open_dropdown.is_some() || self.color_picker.is_some() { return Task::none(); } let i = self.active_tab; diff --git a/src/app/view/mod.rs b/src/app/view/mod.rs index 7714bf6e1a..db73b3a847 100644 --- a/src/app/view/mod.rs +++ b/src/app/view/mod.rs @@ -2304,42 +2304,20 @@ bg={bg_ms:.1}ms n={view_count}" } } - if let Some((_, current)) = self.color_pick_target.as_ref() { - match self.color_picker_tab { - super::ColorPickerTab::Index => { - let content = - crate::ui::color_select::index_color_page(*current, &self.recent_colors); - - crate::ui::modal::modal( - base, - t!("Select Color"), - content, - Message::CloseColorPicker, - self.modal_offset, - crate::ui::modal::ModalOptions::NOTICE, - ) - } - - super::ColorPickerTab::TrueColor => { - let initial = crate::ui::properties::acad_color_display(*current).0; - let modal_base = crate::ui::modal::backdrop(base, Message::CloseColorPicker); - - iced_aw::ColorPicker::new( - true, - initial, - modal_base, - // Cancel inside True Color returns to the indexed page instead - // of closing the whole CAD colour picker. - Message::ColorPickerTabChanged(super::ColorPickerTab::Index), - |color| { - Message::ColorWindowPick(crate::ui::color_select::iced_to_acad_color( - color, - )) - }, - ) - .into() - } + if let Some(picker) = self.color_picker.as_ref() { + // While the eyedropper is picking, the panel steps aside so the + // whole window can be sampled. + if let Some(eyedropper) = picker.eyedropper_view() { + return iced::widget::stack![base, eyedropper].into(); } + crate::ui::modal::modal( + base, + t!("Select Color"), + picker.view(), + Message::CloseColorPicker, + self.modal_offset, + crate::ui::modal::ModalOptions::NOTICE, + ) } else { base } diff --git a/src/app/view/modal.rs b/src/app/view/modal.rs index 8e297f43f0..348c4bd976 100644 --- a/src/app/view/modal.rs +++ b/src/app/view/modal.rs @@ -381,7 +381,6 @@ impl OpenCADStudio { &self.model_bg_input, &self.paper_bg_input, &self.desk_bg_input, - self.bg_picker, dirty, close_confirm, flow, diff --git a/src/locale_catalog.rs b/src/locale_catalog.rs index 6d26598c67..7fd608a1d6 100644 --- a/src/locale_catalog.rs +++ b/src/locale_catalog.rs @@ -4714,15 +4714,14 @@ pub(super) fn message_attribute(source: &str) -> Option<(&'static str, &'static "Dismiss" => Some(("common", "dismiss")), "?" => Some(("common", "value-8a8de8")), "Select Color..." => Some(("common", "select-color-8dddf1")), - "No recent colors yet" => Some(("common", "no-recent-colors-yet")), - "True Color RGB {r}, {g}, {b}" => Some(("common", "true-color-rgb")), "Index Color" => Some(("common", "index-color")), "True Color" => Some(("common", "true-color")), "Standard colors" => Some(("common", "standard-colors")), + "Hex" => Some(("common", "color-hex")), + "Nearest index" => Some(("common", "nearest-index-color")), + "Exact index match" => Some(("common", "exact-index-match")), "CAD Color Index (ACI) 10–249" => Some(("common", "cad-color-index-aci-10-249")), - "Color family → · Shade / intensity ↓" => Some(("common", "color-family-shade-intensity")), "Grayscale 250–255" => Some(("common", "grayscale-250-255")), - "Recently used" => Some(("common", "recently-used")), "Isometric drafting" => Some(("common", "isometric-drafting")), "F5 cycles the active plane." => Some(("common", "f5-cycles-the-active-plane")), "Units…" => Some(("common", "units-5430a1")), diff --git a/src/ui/color_select/editor.rs b/src/ui/color_select/editor.rs new file mode 100644 index 0000000000..ea97384c77 --- /dev/null +++ b/src/ui/color_select/editor.rs @@ -0,0 +1,523 @@ +//! The colour editor: HSB or RGB sliders, or a saturation/brightness field +//! with a hue strip, plus a hex box. Shared by the CAD Select Color panel and +//! the interface colour picker. + +use super::math::{self, Hsb}; +use super::widgets::ColorArea; +use super::ColorPickerMsg; +use crate::app::Message; +use crate::t; +use iced::widget::{ + button, column, container, row, slider, stack, text, text_input, vertical_slider, Space, +}; +use iced::{Background, Border, Color, Element, Gradient, Length, Radians, Theme}; + +const ROW_HEIGHT: f32 = 26.0; +const TRACK: f32 = 18.0; +const STRIP_WIDTH: f32 = 22.0; +/// Gap between slider rows. Together with `FIELD_HEIGHT` it puts the hex row +/// at the same height in every mode: 3 × 26 + 2 × 14 + 12 = 108 + 10. +const ROW_GAP: f32 = 14.0; +const FIELD_HEIGHT: f32 = 108.0; +const MODE_WIDTH: f32 = 40.0; +const MODE_HEIGHT: f32 = 24.0; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum EditorMode { + #[default] + Hsb, + Rgb, + Field, +} + +#[derive(Debug, Clone)] +pub enum EditorMsg { + Mode(EditorMode), + Hue(f32), + /// Saturation in percent. + Saturation(f32), + /// Brightness in percent. + Brightness(f32), + /// Saturation and brightness from the field, both 0–1. + Field(f32, f32), + Red(u8), + Green(u8), + Blue(u8), + HexInput(String), + HexSubmit, +} + +pub struct ColorEditor { + mode: EditorMode, + /// Kept beside `rgb` so hue and saturation survive grays and black. + hsb: Hsb, + rgb: (u8, u8, u8), + hex_draft: Option, +} + +impl ColorEditor { + pub fn new(rgb: (u8, u8, u8)) -> Self { + let mut editor = Self { + mode: EditorMode::default(), + hsb: Hsb { + h: 0.0, + s: 0.0, + b: 1.0, + }, + rgb, + hex_draft: None, + }; + editor.set_rgb(rgb); + editor + } + + pub fn rgb(&self) -> (u8, u8, u8) { + self.rgb + } + + pub fn set_rgb(&mut self, (r, g, b): (u8, u8, u8)) { + let next = math::rgb_to_hsb(r, g, b); + // A gray has no hue and black no saturation; keep the previous ones + // so the sliders and field don't jump. + let gray = next.s == 0.0 || next.b == 0.0; + self.hsb = Hsb { + h: if gray { self.hsb.h } else { next.h }, + s: if next.b == 0.0 { self.hsb.s } else { next.s }, + b: next.b, + }; + self.rgb = (r, g, b); + self.hex_draft = None; + } + + fn set_hsb(&mut self, hsb: Hsb) { + self.hsb = Hsb { + h: hsb.h.clamp(0.0, 360.0), + s: hsb.s.clamp(0.0, 1.0), + b: hsb.b.clamp(0.0, 1.0), + }; + self.rgb = self.hsb.to_rgb(); + self.hex_draft = None; + } + + /// Apply a message; returns whether the colour changed. + pub fn update(&mut self, msg: EditorMsg) -> bool { + let before = self.rgb; + let (r, g, b) = self.rgb; + match msg { + EditorMsg::Mode(mode) => self.mode = mode, + EditorMsg::Hue(h) => self.set_hsb(Hsb { h, ..self.hsb }), + EditorMsg::Saturation(s) => self.set_hsb(Hsb { + s: s / 100.0, + ..self.hsb + }), + EditorMsg::Brightness(v) => self.set_hsb(Hsb { + b: v / 100.0, + ..self.hsb + }), + EditorMsg::Field(s, b) => self.set_hsb(Hsb { s, b, ..self.hsb }), + EditorMsg::Red(v) => self.set_rgb((v, g, b)), + EditorMsg::Green(v) => self.set_rgb((r, v, b)), + EditorMsg::Blue(v) => self.set_rgb((r, g, v)), + EditorMsg::HexInput(value) => { + // Six digits are unambiguous, so apply them while typing; the + // short #RGB form waits for Enter. + let complete = value.trim().trim_start_matches('#').len() == 6; + if let Some(rgb) = math::parse_hex(&value).filter(|_| complete) { + self.set_rgb(rgb); + } + self.hex_draft = Some(value); + } + EditorMsg::HexSubmit => { + if let Some(rgb) = self.hex_draft.take().and_then(|d| math::parse_hex(&d)) { + self.set_rgb(rgb); + } + } + } + self.rgb != before + } + + /// `mode_end` sits at the far right of the mode buttons (the pipette); + /// `hex_end` at the far right of the hex row (the nearest index colour). + /// The field view shows the hex value beside H, S and B and leaves out + /// `hex_end`; the slider views end on a hex row. + pub fn view<'a>( + &'a self, + mode_end: Option>, + hex_end: Option>, + ) -> Element<'a, Message> { + let view = column![self.mode_row(mode_end)].spacing(12); + match self.mode { + EditorMode::Hsb | EditorMode::Rgb => view + .push(self.slider_rows()) + .push(self.hex_row(hex_end)) + .into(), + EditorMode::Field => view.push(self.field_view()).into(), + } + } + + /// HSB, RGB and the gradient-field button, with `end` at the far right. + fn mode_row<'a>(&self, end: Option>) -> Element<'a, Message> { + let mode_button = |content: Element<'a, Message>, mode: EditorMode| { + let active = self.mode == mode; + button(container(content).center(Length::Fill)) + .on_press(msg(EditorMsg::Mode(mode))) + .width(MODE_WIDTH) + .height(MODE_HEIGHT) + .padding(0) + .style(move |theme: &Theme, status| { + super::picker::toggle_style(theme, active, status) + }) + }; + // The field button is only its gradient, without a frame; it takes + // colour when its mode is active and stays gray otherwise. + let field_active = self.mode == EditorMode::Field; + let field_button = button(Space::new().width(MODE_WIDTH).height(MODE_HEIGHT)) + .on_press(msg(EditorMsg::Mode(EditorMode::Field))) + .padding(0) + .style(move |_theme: &Theme, _status| { + let middle = if field_active { + Color::from_rgb8(0x3A, 0xA0, 0xFF) + } else { + Color::from_rgb8(0x80, 0x80, 0x80) + }; + let icon = gradient_box( + 3.0 * std::f32::consts::FRAC_PI_4, + &[(0.0, Color::WHITE), (0.5, middle), (1.0, Color::BLACK)], + ); + button::Style { + background: icon.background, + border: Border { + radius: 5.0.into(), + ..Border::default() + }, + ..Default::default() + } + }); + let mut modes = row![ + mode_button(text("HSB").size(13).into(), EditorMode::Hsb), + mode_button(text("RGB").size(13).into(), EditorMode::Rgb), + field_button, + Space::new().width(Length::Fill), + ] + .spacing(6); + if let Some(end) = end { + modes = modes.push(end); + } + modes.into() + } + + /// Three gradient sliders: hue, saturation and brightness, or red, green + /// and blue. + fn slider_rows<'a>(&self) -> Element<'a, Message> { + let Hsb { h, s, b } = self.hsb; + let (r, g, bl) = self.rgb; + let rows = if self.mode == EditorMode::Rgb { + let ends = |lo: (u8, u8, u8), hi: (u8, u8, u8)| { + vec![(0.0, rgb_color(lo)), (1.0, rgb_color(hi))] + }; + let byte = |f: fn(u8) -> EditorMsg| move |v: f32| f(v.round() as u8); + column![ + channel( + "R", + f32::from(r), + 255.0, + None, + ends((0, g, bl), (255, g, bl)), + byte(EditorMsg::Red) + ), + channel( + "G", + f32::from(g), + 255.0, + None, + ends((r, 0, bl), (r, 255, bl)), + byte(EditorMsg::Green) + ), + channel( + "B", + f32::from(bl), + 255.0, + None, + ends((r, g, 0), (r, g, 255)), + byte(EditorMsg::Blue) + ), + ] + } else { + column![ + channel("H", h, 360.0, Some('°'), hue_stops(), EditorMsg::Hue), + channel( + "S", + s * 100.0, + 100.0, + Some('%'), + vec![(0.0, hsb_color(h, 0.0, b)), (1.0, hsb_color(h, 1.0, b))], + EditorMsg::Saturation, + ), + channel( + "B", + b * 100.0, + 100.0, + Some('%'), + vec![(0.0, Color::BLACK), (1.0, hsb_color(h, s, 1.0))], + EditorMsg::Brightness, + ), + ] + }; + rows.spacing(ROW_GAP).into() + } + + /// The saturation/brightness field with its hue strip, and below it H, S + /// and B on the left and the hex value on the right. + fn field_view<'a>(&self) -> Element<'a, Message> { + let Hsb { h, s, b } = self.hsb; + let area = ColorArea::new(hsb_color(h, 1.0, 1.0), rgb_color(self.rgb), s, b, |s, b| { + msg(EditorMsg::Field(s, b)) + }) + .height(Length::Fixed(FIELD_HEIGHT)); + // A vertical slider grows upwards; the strip runs red at the top. + let strip = stack![ + container(Space::new()) + .width(STRIP_WIDTH) + .height(FIELD_HEIGHT) + .style(|_theme: &Theme| gradient_box(std::f32::consts::PI, &hue_stops())), + vertical_slider(0.0..=360.0, 360.0 - h, |v| msg(EditorMsg::Hue(360.0 - v))) + .width(STRIP_WIDTH) + .height(FIELD_HEIGHT) + .style(handle_style), + ]; + let value = + |letter: &'static str, v: f32, max: f32, unit: char, f: fn(f32) -> EditorMsg| { + row![ + text(letter).size(12).font(iced::Font::MONOSPACE), + number_box(v, max, Some(unit), f), + ] + .spacing(4) + .align_y(iced::Center) + }; + column![ + row![area, strip].spacing(12), + row![ + value("H", h, 360.0, '°', EditorMsg::Hue), + value("S", s * 100.0, 100.0, '%', EditorMsg::Saturation), + value("B", b * 100.0, 100.0, '%', EditorMsg::Brightness), + Space::new().width(Length::Fill), + self.hex_field(), + ] + .spacing(10) + .align_y(iced::Center), + ] + // 108 + 10 matches the slider views' 3 × 26 + 2 × 14 + 12. + .spacing(10) + .into() + } + + /// The hex value with `end` (the nearest index colour) at the far right. + fn hex_row<'a>(&self, end: Option>) -> Element<'a, Message> { + let mut hex_row = row![self.hex_field(), Space::new().width(Length::Fill)] + .spacing(8) + .align_y(iced::Center); + if let Some(end) = end { + hex_row = hex_row.push(end); + } + hex_row.into() + } + + fn hex_field<'a>(&self) -> Element<'a, Message> { + let (r, g, b) = self.rgb; + let hex = self + .hex_draft + .clone() + .unwrap_or_else(|| math::hex_string(r, g, b)); + row![ + text(t!("Hex")).size(11).style(super::picker::muted_text), + text_input("", &hex) + .on_input(|value| msg(EditorMsg::HexInput(value))) + .on_submit(msg(EditorMsg::HexSubmit)) + .size(12) + .font(iced::Font::MONOSPACE) + .padding([5, 6]) + .width(Length::Fixed(74.0)), + ] + .spacing(8) + .align_y(iced::Center) + .into() + } +} + +fn msg(editor: EditorMsg) -> Message { + Message::ColorPicker(ColorPickerMsg::Editor(editor)) +} + +/// One labelled channel: a gradient slider and its number box. +fn channel<'a>( + letter: &'static str, + value: f32, + max: f32, + unit: Option, + stops: Vec<(f32, Color)>, + on_change: impl Fn(f32) -> EditorMsg + Copy + 'static, +) -> Element<'a, Message> { + // iced's slider splits its own rail at the handle, which would squeeze a + // gradient; draw the gradient underneath and keep the rail transparent. + let track = container( + container(Space::new()) + .width(Length::Fill) + .height(TRACK) + .style(move |_theme: &Theme| gradient_box(std::f32::consts::FRAC_PI_2, &stops)), + ) + .height(ROW_HEIGHT) + .center_y(ROW_HEIGHT); + row![ + container(text(letter).size(12).font(iced::Font::MONOSPACE)) + .width(12) + .align_x(iced::Center), + stack![ + track, + slider(0.0..=max, value, move |v| msg(on_change(v))) + .height(ROW_HEIGHT) + .shift_step(10.0) + .style(handle_style), + ], + number_box(value, max, unit, on_change), + ] + .spacing(8) + .align_y(iced::Center) + .into() +} + +/// A compact spin box with the unit drawn inside, after the digits. +fn number_box( + value: f32, + max: f32, + unit: Option, + on_change: impl Fn(f32) -> EditorMsg + Copy + 'static, +) -> Element<'static, Message> { + let input = + iced_aw::widget::NumberInput::new(&(value.round() as u16), 0..=max as u16, move |v| { + msg(on_change(f32::from(v))) + }) + .set_size(12.0) + .font(iced::Font::MONOSPACE) + .width(Length::Fixed(54.0)) + // Padding under 5 would make NumberInput swap its arrows for + / −; + // the extra right padding keeps the digits clear of the arrows. + .padding(iced::Padding { + top: 5.0, + right: 18.0, + bottom: 5.0, + left: 2.0, + }) + .align_x(iced::alignment::Horizontal::Right) + .style( + |theme: &Theme, _status| iced_aw::style::number_input::Style { + button_background: None, + icon_color: theme.palette().background.base.text.scale_alpha(0.75), + }, + ); + match unit { + Some(code_point) => input + .icon(text_input::Icon { + font: iced::Font::MONOSPACE, + code_point, + size: Some(iced::Pixels(12.0)), + spacing: 1.0, + side: text_input::Side::Right, + }) + .into(), + None => input.into(), + } +} + +/// Transparent rail with a white bar handle, for both slider directions. +fn handle_style(_theme: &Theme, _status: slider::Status) -> slider::Style { + slider::Style { + rail: slider::Rail { + backgrounds: (Color::TRANSPARENT.into(), Color::TRANSPARENT.into()), + width: TRACK, + border: Border::default(), + }, + handle: slider::Handle { + shape: slider::HandleShape::Rectangle { + width: 8, + border_radius: 3.0.into(), + }, + background: Color::WHITE.into(), + border_width: 1.0, + border_color: Color::from_rgba(0.0, 0.0, 0.0, 0.4), + }, + } +} + +/// A rounded box filled with a linear gradient. Angles run clockwise from +/// "bottom to top": a quarter turn is left to right, a half turn top to bottom. +fn gradient_box(angle: f32, stops: &[(f32, Color)]) -> container::Style { + let linear = stops.iter().fold( + iced::gradient::Linear::new(Radians(angle)), + |linear, &(at, color)| linear.add_stop(at, color), + ); + container::Style { + background: Some(Background::Gradient(Gradient::Linear(linear))), + border: Border { + color: Color::from_rgba(0.0, 0.0, 0.0, 0.35), + width: 1.0, + radius: 5.0.into(), + }, + ..Default::default() + } +} + +fn hue_stops() -> Vec<(f32, Color)> { + (0..=6) + .map(|step| { + let at = step as f32 / 6.0; + (at, hsb_color(at * 360.0, 1.0, 1.0)) + }) + .collect() +} + +fn hsb_color(h: f32, s: f32, b: f32) -> Color { + rgb_color(math::hsb_to_rgb(h, s, b)) +} + +pub(super) fn rgb_color((r, g, b): (u8, u8, u8)) -> Color { + Color::from_rgb8(r, g, b) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sliders_produce_colours() { + let mut e = ColorEditor::new((255, 0, 0)); + assert!(e.update(EditorMsg::Hue(120.0))); + assert_eq!(e.rgb(), (0, 255, 0)); + e.update(EditorMsg::Red(10)); + assert_eq!(e.rgb(), (10, 255, 0)); + assert!(!e.update(EditorMsg::Mode(EditorMode::Rgb))); + } + + #[test] + fn hue_survives_a_trip_through_gray() { + let mut e = ColorEditor::new((0, 0, 255)); + e.update(EditorMsg::Saturation(0.0)); + e.update(EditorMsg::Saturation(100.0)); + assert_eq!(e.rgb(), (0, 0, 255)); + } + + #[test] + fn hex_applies_six_digits_while_typing() { + let mut e = ColorEditor::new((0, 0, 0)); + assert!(!e.update(EditorMsg::HexInput("#39BF".into()))); + assert!(e.update(EditorMsg::HexInput("#39BFFC".into()))); + assert_eq!(e.rgb(), (57, 191, 252)); + } + + #[test] + fn short_hex_waits_for_enter() { + let mut e = ColorEditor::new((0, 0, 0)); + assert!(!e.update(EditorMsg::HexInput("#3bf".into()))); + assert!(e.update(EditorMsg::HexSubmit)); + assert_eq!(e.rgb(), (0x33, 0xBB, 0xFF)); + } +} diff --git a/src/ui/color_select/eyedropper.rs b/src/ui/color_select/eyedropper.rs new file mode 100644 index 0000000000..2d24822b9e --- /dev/null +++ b/src/ui/color_select/eyedropper.rs @@ -0,0 +1,184 @@ +//! Pick a colour from anywhere inside the application window. +//! +//! While active, a transparent layer covers the window with a crosshair. The +//! first mouse move after the panel is hidden asks iced for a screenshot of +//! the window; a magnifier beside the cursor shows the pixels around it from +//! that screenshot, and a click picks the centre pixel. + +use super::editor::rgb_color; +use super::{math, ColorPickerMsg}; +use crate::app::Message; +use iced::widget::{column, container, mouse_area, pin, row, stack, text, Space}; +use iced::window::Screenshot; +use iced::{Border, Color, Element, Length, Point, Theme}; + +/// Pixels shown across the magnifier (odd, so one sits in the centre). +const GRID: i32 = 11; +const CELL: f32 = 10.0; +/// Gap between the cursor and the magnifier. +const OFFSET: f32 = 20.0; + +#[derive(Debug, Clone)] +pub enum EyedropperMsg { + Start, + Move(Point), + Shot(Screenshot), + Pick, +} + +#[derive(Default)] +pub struct Eyedropper { + shot: Option, + requested: bool, + cursor: Option, +} + +impl Eyedropper { + /// Track the cursor. Returns true when the window screenshot should be + /// requested now — the panel is gone from the screen by then. + pub fn track(&mut self, cursor: Point) -> bool { + self.cursor = Some(cursor); + let request = self.shot.is_none() && !self.requested; + self.requested = true; + request + } + + pub fn set_shot(&mut self, shot: Screenshot) { + self.shot = Some(shot); + } + + /// The pixel under the cursor, once the screenshot has arrived. + pub fn picked(&self) -> Option<(u8, u8, u8)> { + sample(self.shot.as_ref()?, self.cursor?, 0, 0) + } + + pub fn view(&self) -> Element<'_, Message> { + let eye = |m| Message::ColorPicker(ColorPickerMsg::Eyedropper(m)); + let catcher = mouse_area(Space::new().width(Length::Fill).height(Length::Fill)) + .on_move(move |p| eye(EyedropperMsg::Move(p))) + .on_press(eye(EyedropperMsg::Pick)) + .interaction(iced::mouse::Interaction::Crosshair); + + let (Some(shot), Some(cursor)) = (self.shot.as_ref(), self.cursor) else { + return catcher.into(); + }; + + let half = GRID / 2; + let mut grid = column![]; + for dy in -half..=half { + let mut line = row![]; + for dx in -half..=half { + let fill = sample(shot, cursor, dx, dy).map_or(Color::TRANSPARENT, rgb_color); + let centre = dx == 0 && dy == 0; + line = line.push(container(Space::new()).width(CELL).height(CELL).style( + move |_theme: &Theme| container::Style { + background: Some(fill.into()), + border: Border { + color: if centre { + Color::WHITE + } else { + Color::TRANSPARENT + }, + width: if centre { 1.5 } else { 0.0 }, + radius: 0.0.into(), + }, + ..Default::default() + }, + )); + } + grid = grid.push(line); + } + let (r, g, b) = self.picked().unwrap_or((0, 0, 0)); + let loupe = container( + column![ + grid, + text(math::hex_string(r, g, b)) + .size(11) + .font(iced::Font::MONOSPACE), + ] + .spacing(4) + .align_x(iced::Center), + ) + .padding(4) + .style(|theme: &Theme| { + let palette = theme.palette(); + container::Style { + background: Some(palette.background.base.color.into()), + text_color: Some(palette.background.base.text), + border: Border { + color: palette.background.strong.color, + width: 1.0, + radius: 6.0.into(), + }, + ..Default::default() + } + }); + + // Keep the magnifier on screen: flip it to the other side of the + // cursor near the right and bottom edges. + let size = GRID as f32 * CELL + 8.0; + let window_w = shot.size.width as f32 / shot.scale_factor; + let window_h = shot.size.height as f32 / shot.scale_factor; + // In a very small window neither side fits; stay inside the top-left. + let x = if cursor.x + OFFSET + size > window_w { + cursor.x - OFFSET - size + } else { + cursor.x + OFFSET + } + .max(0.0); + let y = if cursor.y + OFFSET + size + 20.0 > window_h { + cursor.y - OFFSET - size - 20.0 + } else { + cursor.y + OFFSET + } + .max(0.0); + stack![catcher, pin(loupe).x(x).y(y)].into() + } +} + +/// The screenshot pixel `dx`, `dy` physical pixels away from a logical point. +fn sample(shot: &Screenshot, at: Point, dx: i32, dy: i32) -> Option<(u8, u8, u8)> { + let x = (at.x * shot.scale_factor) as i64 + i64::from(dx); + let y = (at.y * shot.scale_factor) as i64 + i64::from(dy); + let (w, h) = (i64::from(shot.size.width), i64::from(shot.size.height)); + if !(0..w).contains(&x) || !(0..h).contains(&y) { + return None; + } + let i = ((y * w + x) * 4) as usize; + let px = shot.rgba.get(i..i + 3)?; + Some((px[0], px[1], px[2])) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn shot() -> Screenshot { + // 4×2 physical pixels at scale 2: pixel (x, y) has red = x, green = y. + let mut rgba = Vec::new(); + for y in 0..2u8 { + for x in 0..4u8 { + rgba.extend([x, y, 9, 255]); + } + } + Screenshot::new(rgba, iced::Size::new(4, 2), 2.0) + } + + #[test] + fn samples_physical_pixels_from_logical_points() { + let s = shot(); + assert_eq!(sample(&s, Point::new(1.0, 0.5), 0, 0), Some((2, 1, 9))); + assert_eq!(sample(&s, Point::new(1.0, 0.5), 1, -1), Some((3, 0, 9))); + assert_eq!(sample(&s, Point::new(1.9, 0.0), 1, 0), None); + } + + #[test] + fn asks_for_one_screenshot_and_picks_after_it_arrives() { + let mut e = Eyedropper::default(); + assert!(e.track(Point::new(0.0, 0.0))); + assert!(!e.track(Point::new(1.0, 0.0))); + assert_eq!(e.picked(), None); + e.set_shot(shot()); + assert_eq!(e.picked(), Some((2, 0, 9))); + } +} diff --git a/src/ui/color_select/math.rs b/src/ui/color_select/math.rs new file mode 100644 index 0000000000..74ab9968d5 --- /dev/null +++ b/src/ui/color_select/math.rs @@ -0,0 +1,194 @@ +//! Colour maths and formatting for the Select Color panel. +//! +//! Everything here is pure so it can be unit tested without a UI: HSB/RGB +//! conversion, hex formatting and parsing, nearest-index lookup and the +//! short names the panel shows. + +use codec::types::Color as AcadColor; + +/// Hue in degrees (0–360), saturation and brightness in 0–1. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Hsb { + pub h: f32, + pub s: f32, + pub b: f32, +} + +impl Hsb { + pub fn to_rgb(self) -> (u8, u8, u8) { + hsb_to_rgb(self.h, self.s, self.b) + } +} + +/// Convert hue (degrees), saturation and brightness (0–1) to 8-bit RGB. +pub fn hsb_to_rgb(h: f32, s: f32, b: f32) -> (u8, u8, u8) { + let h = h.rem_euclid(360.0); + let s = s.clamp(0.0, 1.0); + let b = b.clamp(0.0, 1.0); + let channel = |n: f32| { + let k = (n + h / 60.0) % 6.0; + let v = b - b * s * k.min(4.0 - k).clamp(0.0, 1.0); + (v * 255.0).round() as u8 + }; + (channel(5.0), channel(3.0), channel(1.0)) +} + +/// Convert 8-bit RGB to HSB. Grays have no hue; they report 0. +pub fn rgb_to_hsb(r: u8, g: u8, b: u8) -> Hsb { + let (r, g, b) = ( + f32::from(r) / 255.0, + f32::from(g) / 255.0, + f32::from(b) / 255.0, + ); + let max = r.max(g).max(b); + let min = r.min(g).min(b); + let delta = max - min; + let mut h = if delta == 0.0 { + 0.0 + } else if max == r { + 60.0 * (((g - b) / delta) % 6.0) + } else if max == g { + 60.0 * ((b - r) / delta + 2.0) + } else { + 60.0 * ((r - g) / delta + 4.0) + }; + if h < 0.0 { + h += 360.0; + } + let s = if max == 0.0 { 0.0 } else { delta / max }; + Hsb { h, s, b: max } +} + +/// RGB of an ACI entry, or `None` outside 1–255. +pub fn aci_rgb(index: u8) -> Option<(u8, u8, u8)> { + codec::types::aci_table::aci_to_rgb(index) +} + +/// The RGB a concrete colour displays as. Logical colours have none. +pub fn color_rgb(color: AcadColor) -> Option<(u8, u8, u8)> { + match color { + AcadColor::Index(i) => aci_rgb(i), + AcadColor::Rgb { r, g, b } => Some((r, g, b)), + _ => None, + } +} + +/// The closest index colour to an RGB value. +pub fn nearest_aci(r: u8, g: u8, b: u8) -> u8 { + codec::types::aci_table::nearest_aci(r, g, b) +} + +/// `#RRGGBB`, upper case — the same format the Options hex fields store. +pub fn hex_string(r: u8, g: u8, b: u8) -> String { + crate::app::config::rgb_to_hex([r, g, b]) +} + +/// Parse `#RRGGBB`, `RRGGBB`, `#RGB` or `RGB`. Unlike `config::parse_hex`, +/// which Options uses, this also accepts the short three-digit form. +pub fn parse_hex(text: &str) -> Option<(u8, u8, u8)> { + let digits = text.trim().trim_start_matches('#'); + if !digits.chars().all(|c| c.is_ascii_hexdigit()) { + return None; + } + let expanded: String = match digits.len() { + 3 => digits.chars().flat_map(|c| [c, c]).collect(), + 6 => digits.to_string(), + _ => return None, + }; + let value = u32::from_str_radix(&expanded, 16).ok()?; + Some(((value >> 16) as u8, (value >> 8) as u8, value as u8)) +} + +/// The short name shown on the Current / New swatch. +pub fn short_name(color: AcadColor) -> String { + match color { + AcadColor::Index(i) => format!("ACI {i}"), + AcadColor::Rgb { r, g, b } => hex_string(r, g, b), + AcadColor::ByLayer => "ByLayer".to_string(), + AcadColor::ByBlock => "ByBlock".to_string(), + AcadColor::None => "None".to_string(), + } +} + +/// One-line description for the panel's info line. +pub fn describe(color: AcadColor) -> String { + match color { + AcadColor::Index(i) => { + let (r, g, b) = aci_rgb(i).unwrap_or((128, 128, 128)); + format!("ACI {i} · RGB {r}, {g}, {b}") + } + AcadColor::Rgb { r, g, b } => format!("RGB {r}, {g}, {b} · {}", hex_string(r, g, b)), + other => short_name(other), + } +} + +/// Black or white text, whichever reads better on the given background. +pub fn ink_is_dark(r: u8, g: u8, b: u8) -> bool { + 0.299 * f32::from(r) + 0.587 * f32::from(g) + 0.114 * f32::from(b) > 150.0 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn hsb_round_trips_primary_and_mixed_colours() { + for (r, g, b) in [ + (255, 0, 0), + (0, 255, 0), + (0, 0, 255), + (57, 191, 252), + (120, 200, 80), + (128, 128, 128), + (0, 0, 0), + (255, 255, 255), + ] { + let hsb = rgb_to_hsb(r, g, b); + assert_eq!(hsb.to_rgb(), (r, g, b), "round trip of {r},{g},{b}"); + } + } + + #[test] + fn hue_of_pure_colours() { + assert_eq!(rgb_to_hsb(255, 0, 0).h, 0.0); + assert!((rgb_to_hsb(0, 255, 0).h - 120.0).abs() < 0.01); + assert!((rgb_to_hsb(0, 0, 255).h - 240.0).abs() < 0.01); + assert_eq!(rgb_to_hsb(80, 80, 80).s, 0.0); + } + + #[test] + fn hue_wraps_around() { + assert_eq!(hsb_to_rgb(360.0, 1.0, 1.0), (255, 0, 0)); + assert_eq!(hsb_to_rgb(-120.0, 1.0, 1.0), hsb_to_rgb(240.0, 1.0, 1.0)); + } + + #[test] + fn nearest_aci_comes_from_the_codec_table() { + assert_eq!(nearest_aci(255, 0, 0), 1); + assert_eq!(nearest_aci(250, 5, 5), 1); + } + + #[test] + fn short_names() { + assert_eq!(short_name(AcadColor::Index(140)), "ACI 140"); + assert_eq!( + short_name(AcadColor::Rgb { + r: 57, + g: 191, + b: 252 + }), + "#39BFFC" + ); + assert_eq!(short_name(AcadColor::ByLayer), "ByLayer"); + } + + #[test] + fn hex_formats_and_parses() { + assert_eq!(hex_string(57, 191, 252), "#39BFFC"); + assert_eq!(parse_hex("#39bffc"), Some((57, 191, 252))); + assert_eq!(parse_hex("39BFFC"), Some((57, 191, 252))); + assert_eq!(parse_hex("#3bf"), Some((0x33, 0xBB, 0xFF))); + assert_eq!(parse_hex("#39BFF"), None); + assert_eq!(parse_hex("zzzzzz"), None); + } +} diff --git a/src/ui/color_select.rs b/src/ui/color_select/mod.rs similarity index 58% rename from src/ui/color_select.rs rename to src/ui/color_select/mod.rs index 3658a251e5..adcefdf2f3 100644 --- a/src/ui/color_select.rs +++ b/src/ui/color_select/mod.rs @@ -3,6 +3,15 @@ //! properties panel and every style editor so colour selection looks and //! behaves the same everywhere. +pub mod editor; +pub mod eyedropper; +pub mod math; +pub mod picker; +pub mod widgets; + +pub use math::nearest_aci; +pub use picker::{ColorPicker, ColorPickerMsg, Outcome}; + use crate::app::Message; use crate::t; use crate::ui::properties::acad_color_display; @@ -34,42 +43,6 @@ pub fn color_to_aci_string(c: AcadColor) -> String { } } -/// Convert an Iced colour chosen by `iced_aw::ColorPicker` into a DWG true -/// colour. ACI-only destinations map it to their closest indexed colour later. -pub fn iced_to_acad_color(color: Color) -> AcadColor { - // Truncate the way the picker labels its channels, so the stored colour - // is the one the dialog showed; rounding drifted dragged values by one - // (#1621). - let byte = |c: f32| (c * 255.0) as u8; - AcadColor::Rgb { - r: byte(color.r), - g: byte(color.g), - b: byte(color.b), - } -} - -/// Return the closest CAD Color Index for an RGB colour. -pub fn nearest_aci(r: u8, g: u8, b: u8) -> u8 { - let mut best = 7; - let mut best_distance = u32::MAX; - - for index in 1..=255 { - let Some((ar, ag, ab)) = codec::types::aci_table::aci_to_rgb(index) else { - continue; - }; - let dr = i32::from(r) - i32::from(ar); - let dg = i32::from(g) - i32::from(ag); - let db = i32::from(b) - i32::from(ab); - let distance = (dr * dr + dg * dg + db * db) as u32; - if distance < best_distance { - best = index; - best_distance = distance; - } - } - - best -} - /// Decode an ACI integer string back into an `AcadColor`. pub fn aci_string_to_color(s: &str) -> AcadColor { match s.trim().parse::().unwrap_or(256) { @@ -352,174 +325,3 @@ pub fn drop_down_below<'a>( } dd.into() } - -/// Full CAD indexed-colour page used by the standalone Select Color dialog. -/// -/// This only edits the pending colour. The caller commits it with -/// `Message::ColorWindowPick`, so choosing a swatch does not immediately close -/// the dialog. -pub fn index_color_page<'a>( - current: AcadColor, - recent_colors: &'a [AcadColor], -) -> Element<'a, Message> { - let swatch_button = |color: AcadColor, size: f32| -> Element<'a, Message> { - let (bg, _) = acad_color_display(color); - let selected = current == color; - - button( - text("") - .width(Length::Fixed(size)) - .height(Length::Fixed(size)), - ) - .on_press(Message::ColorPickerColorChanged(color)) - .style(move |theme: &Theme, status| { - let hovered = matches!(status, button::Status::Hovered | button::Status::Pressed); - - button::Style { - background: Some(Background::Color(bg)), - border: Border { - color: if selected || hovered { - theme.palette().primary.base.color - } else { - theme.palette().background.neutral.color - }, - width: if selected { - 2.5 - } else if hovered { - 1.5 - } else { - 1.0 - }, - radius: 1.0.into(), - }, - ..Default::default() - } - }) - .padding(0) - .into() - }; - - // The first standard indexed CAD colours. - let mut standard = row![].spacing(4); - for idx in 1u8..=9 { - standard = standard.push(swatch_button(AcadColor::Index(idx), 22.0)); - } - - // ACI 10-249. - // - // Each group of ten indices belongs together. Arrange the 24 colour - // families horizontally and their ten shade/intensity variants vertically. - // This makes the palette read as a colour spectrum instead of a raw numeric - // sequence. - let mut palette_rows = column![].spacing(2); - - for variant in 0u8..10 { - let mut palette_row = row![].spacing(2); - - for family in 1u8..=24 { - let idx = family * 10 + variant; - palette_row = palette_row.push(swatch_button(AcadColor::Index(idx), 16.0)); - } - - palette_rows = palette_rows.push(palette_row); - } - - // ACI 250-255 are the grayscale entries and are shown separately. - let mut grayscale = row![].spacing(4); - - for idx in 250u8..=255 { - grayscale = grayscale.push(swatch_button(AcadColor::Index(idx), 22.0)); - } - - let recent: Element<'a, Message> = if recent_colors.is_empty() { - text(crate::t!("No recent colors yet")) - .size(10) - .style(|theme: &Theme| iced::widget::text::Style { - color: Some(theme.palette().background.base.text.scale_alpha(0.55)), - }) - .into() - } else { - let mut recent_row = row![].spacing(4); - - for &color in recent_colors.iter().take(12) { - recent_row = recent_row.push(swatch_button(color, 22.0)); - } - - recent_row.into() - }; - - let selected_text = match current { - AcadColor::Index(i) => { - let (r, g, b) = codec::types::aci_table::aci_to_rgb(i).unwrap_or((128, 128, 128)); - format!("ACI {i} RGB {r}, {g}, {b}") - } - AcadColor::Rgb { r, g, b } => crate::tf!("True Color RGB {r}, {g}, {b}").into_owned(), - AcadColor::ByLayer => t!("ByLayer").into_owned(), - AcadColor::ByBlock => t!("ByBlock").into_owned(), - AcadColor::None => t!("None").into_owned(), - }; - - let tabs = row![ - button(text(crate::t!("Index Color")).size(12)) - .style(button::primary) - .padding([5, 14]), - button(text(crate::t!("True Color")).size(12)) - .on_press(Message::ColorPickerTabChanged( - crate::app::ColorPickerTab::TrueColor - )) - .style(button::secondary) - .padding([5, 14]), - ] - .spacing(4); - - let actions = container( - row![ - button(text(crate::t!("Cancel")).size(11)) - .on_press(Message::CloseColorPicker) - .style(button::secondary) - .padding([5, 14]), - button(text(crate::t!("OK")).size(11)) - .on_press(Message::ColorWindowPick(current)) - .style(button::primary) - .padding([5, 18]), - ] - .spacing(8), - ) - .width(Length::Fill) - .align_x(iced::alignment::Horizontal::Right); - - container( - column![ - tabs, - text(crate::t!("Standard colors")).size(11), - standard, - text(crate::t!("CAD Color Index (ACI) 10–249")).size(11), - text(crate::t!("Color family → · Shade / intensity ↓")) - .size(9) - .style(|theme: &Theme| iced::widget::text::Style { - color: Some(theme.palette().background.base.text.scale_alpha(0.65)), - }), - container(palette_rows) - .padding(6) - .style(|theme: &Theme| container::Style { - background: Some(Background::Color(theme.palette().background.weakest.color)), - border: Border { - color: theme.palette().background.neutral.color, - width: 1.0, - radius: 3.0.into(), - }, - ..Default::default() - }), - text(crate::t!("Grayscale 250–255")).size(11), - grayscale, - text(crate::t!("Recently used")).size(11), - recent, - text(selected_text).size(11), - actions, - ] - .spacing(9), - ) - .padding(10) - .width(Length::Fixed(470.0)) - .into() -} diff --git a/src/ui/color_select/picker.rs b/src/ui/color_select/picker.rs new file mode 100644 index 0000000000..ccd63b85da --- /dev/null +++ b/src/ui/color_select/picker.rs @@ -0,0 +1,897 @@ +//! The Select Color panel: state, update logic and view. +//! +//! The panel edits a pending colour and only reports it back on OK, so every +//! caller keeps applying colours through the same `ColorWindowPick` path. +//! Opened for an interface colour (any colour in Options) it shows only the +//! colour editor: no tabs, no index colours. + +use super::editor::{rgb_color, ColorEditor, EditorMsg}; +use super::eyedropper::{Eyedropper, EyedropperMsg}; +use super::math; +use crate::app::{ArrowKey, ColorPickTarget, Message}; +use crate::t; +use crate::ui::properties::acad_color_display; +use codec::types::Color as AcadColor; +use iced::widget::{button, column, container, row, text, Space}; +use iced::{Background, Border, Color, Element, Length, Theme}; + +const PANEL_WIDTH: f32 = 400.0; +/// Scope for Tab / Shift+Tab, so focus cycles through the panel's own +/// fields instead of the dialogs and command line underneath. +const PANEL_ID: &str = "select-color-panel"; +const BODY_HEIGHT: f32 = 352.0; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum ColorPickerTab { + #[default] + Index, + TrueColor, +} + +#[derive(Debug, Clone)] +pub enum ColorPickerMsg { + Tab(ColorPickerTab), + /// A swatch was clicked. + Pick(AcadColor), + /// Set the new colour back to the current one. + Revert, + Editor(EditorMsg), + /// Replace the true colour with its nearest index colour. + UseNearest, + Arrow(ArrowKey), + Eyedropper(EyedropperMsg), + Ok, + Cancel, +} + +/// What the caller has to do after an update. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum Outcome { + Commit(AcadColor), + Cancel, + /// Capture the window for the eyedropper. + Screenshot, +} + +pub struct ColorPicker { + pub target: ColorPickTarget, + /// The colour shown as "Current". For a mixed selection this is the colour + /// of the most recently drawn object. + current: AcadColor, + varies: bool, + pending: AcadColor, + tab: ColorPickerTab, + editor: ColorEditor, + eyedropper: Option, +} + +impl ColorPicker { + pub fn new(target: ColorPickTarget, current: AcadColor, varies: bool) -> Self { + let tab = if matches!(current, AcadColor::Rgb { .. }) { + ColorPickerTab::TrueColor + } else { + ColorPickerTab::Index + }; + Self { + target, + current, + varies, + pending: current, + tab, + editor: ColorEditor::new(math::color_rgb(current).unwrap_or((255, 255, 255))), + eyedropper: None, + } + } + + pub fn pending(&self) -> AcadColor { + self.pending + } + + pub fn tab(&self) -> ColorPickerTab { + self.tab + } + + /// Interface colours (Options) only get the colour editor. + fn editor_only(&self) -> bool { + matches!(self.target, ColorPickTarget::Interface(_)) + } + + fn set_pending(&mut self, color: AcadColor) { + self.pending = color; + if let Some(rgb) = math::color_rgb(color) { + self.editor.set_rgb(rgb); + } + } + + fn rgb(&self) -> (u8, u8, u8) { + self.editor.rgb() + } + + pub fn update(&mut self, msg: ColorPickerMsg) -> Option { + // While picking from the screen only the eyedropper listens; Esc + // backs out of it rather than closing the panel. + if let Some(eye) = self.eyedropper.as_mut() { + match msg { + ColorPickerMsg::Eyedropper(EyedropperMsg::Move(p)) => { + return eye.track(p).then_some(Outcome::Screenshot); + } + ColorPickerMsg::Eyedropper(EyedropperMsg::Shot(shot)) => eye.set_shot(shot), + ColorPickerMsg::Eyedropper(EyedropperMsg::Pick) => { + if let Some((r, g, b)) = eye.picked() { + self.eyedropper = None; + self.set_pending(AcadColor::Rgb { r, g, b }); + } + } + // Esc leaves the eyedropper but keeps the panel open. + ColorPickerMsg::Cancel => self.eyedropper = None, + _ => {} + } + return None; + } + match msg { + ColorPickerMsg::Tab(tab) => self.tab = tab, + ColorPickerMsg::Pick(color) => self.set_pending(color), + ColorPickerMsg::Revert => self.set_pending(self.current), + ColorPickerMsg::Editor(editor) => { + if self.editor.update(editor) { + let (r, g, b) = self.editor.rgb(); + self.pending = AcadColor::Rgb { r, g, b }; + } + } + ColorPickerMsg::UseNearest => { + let (r, g, b) = self.rgb(); + self.set_pending(AcadColor::Index(math::nearest_aci(r, g, b))); + } + ColorPickerMsg::Arrow(direction) => { + if let (ColorPickerTab::Index, AcadColor::Index(index)) = (self.tab, self.pending) { + if let Some(next) = step_index(index, direction) { + self.set_pending(AcadColor::Index(next)); + } + } + } + ColorPickerMsg::Eyedropper(EyedropperMsg::Start) => { + self.eyedropper = Some(Eyedropper::default()); + } + ColorPickerMsg::Eyedropper(_) => {} + ColorPickerMsg::Ok => { + // Apply a value still being typed, as if Enter had been pressed. + self.update(ColorPickerMsg::Editor(EditorMsg::HexSubmit)); + return Some(Outcome::Commit(self.pending)); + } + ColorPickerMsg::Cancel => return Some(Outcome::Cancel), + } + None + } + + /// The full-window eyedropper layer, while it is active. + pub fn eyedropper_view(&self) -> Option> { + self.eyedropper.as_ref().map(Eyedropper::view) + } + + pub fn view(&self) -> Element<'_, Message> { + let editor_only = self.editor_only(); + let body = if editor_only || self.tab == ColorPickerTab::TrueColor { + self.true_color_tab() + } else { + self.index_tab() + }; + + // The interface picker shrinks to the editor; the CAD panel keeps one + // height across its tabs, with the info line at the bottom. + let mut body = column![body].spacing(8); + if !editor_only { + body = body.push(Space::new().height(Length::Fill)); + let fill = + math::color_rgb(self.pending).map_or(Color::from_rgb8(128, 128, 128), rgb_color); + body = body + .push( + container(Space::new()) + .width(Length::Fill) + .height(1) + .style(|theme: &Theme| filled(theme.palette().background.weak.color)), + ) + .push( + row![ + container(Space::new()) + .width(12) + .height(12) + .style(move |_theme: &Theme| swatch_style(fill)), + text(math::describe(self.pending)) + .size(11) + .font(iced::Font::MONOSPACE), + ] + .spacing(8) + .align_y(iced::Center), + ); + } + let body = container(body) + .padding(12) + .width(Length::Fill) + .height(if editor_only { + Length::Shrink + } else { + Length::Fixed(BODY_HEIGHT) + }) + .style(panel_style); + + let actions = row![ + Space::new().width(Length::Fill), + button(text(t!("Cancel")).size(12)) + .on_press(picker_msg(ColorPickerMsg::Cancel)) + .style(button::secondary) + .padding([6, 16]), + button(text(t!("OK")).size(12)) + .on_press(picker_msg(ColorPickerMsg::Ok)) + .style(button::primary) + .padding([6, 22]), + ] + .spacing(8); + + let mut panel = column![].spacing(12).width(PANEL_WIDTH); + if !editor_only { + panel = panel.push(self.tabs()); + } + container(panel.push(self.preview_row()).push(body).push(actions)) + .id(PANEL_ID) + .into() + } + + fn tabs(&self) -> Element<'_, Message> { + let tab = |label: String, tab: ColorPickerTab| { + let active = self.tab == tab; + button(container(text(label).size(12)).center_x(Length::Fill)) + .on_press(picker_msg(ColorPickerMsg::Tab(tab))) + .width(Length::Fill) + .padding([5, 4]) + .style(move |theme: &Theme, status| segment_style(theme, active, status)) + }; + container( + row![ + tab(t!("Index Color").into_owned(), ColorPickerTab::Index), + tab(t!("True Color").into_owned(), ColorPickerTab::TrueColor), + ] + .spacing(2), + ) + .padding(2) + .style(panel_style) + .into() + } + + /// Current and New side by side across the full width, the divider + /// under the middle of the tab bar. Clicking Current reverts. + fn preview_row(&self) -> Element<'_, Message> { + let half = |label: String, value: String, fill: Color| { + let ink = if ink_is_dark(fill) { + Color::from_rgb8(0x11, 0x12, 0x14) + } else { + Color::WHITE + }; + column![ + text(label).size(11).color(ink.scale_alpha(0.85)), + Space::new().height(Length::Fill), + text(value).size(11).font(iced::Font::MONOSPACE).color(ink), + ] + .padding([8, 10]) + .width(Length::Fill) + .height(Length::Fill) + }; + let (current_bg, _) = acad_color_display(self.current); + let (new_bg, _) = acad_color_display(self.pending); + let current_value = if self.varies { + "*VARIES*".to_string() + } else { + math::short_name(self.current) + }; + let current = button(half(t!("Current").into_owned(), current_value, current_bg)) + .on_press(picker_msg(ColorPickerMsg::Revert)) + .padding(0) + .width(Length::Fill) + .height(Length::Fill) + .style(move |_theme: &Theme, _status| button::Style { + background: Some(current_bg.into()), + border: Border { + radius: iced::border::radius(7.0).right(0.0), + ..Border::default() + }, + ..Default::default() + }); + let divider = container(Space::new()) + .width(1) + .height(Length::Fill) + .style(|_theme: &Theme| filled(Color::from_rgba(0.0, 0.0, 0.0, 0.35))); + let new = container(half( + t!("New").into_owned(), + math::short_name(self.pending), + new_bg, + )) + .style(move |_theme: &Theme| container::Style { + border: Border { + radius: iced::border::radius(7.0).left(0.0), + ..Border::default() + }, + ..filled(new_bg) + }); + container(row![current, divider, new]) + .width(Length::Fill) + .height(60) + .padding(1) + .style(|theme: &Theme| container::Style { + border: Border { + color: theme.palette().background.strong.color, + width: 1.0, + radius: 8.0.into(), + }, + ..Default::default() + }) + .clip(true) + .into() + } + + fn index_tab(&self) -> Element<'_, Message> { + let section = |label: String| text(label).size(11); + let swatches = |range: std::ops::RangeInclusive| { + range.fold(row![].spacing(5), |line, index| { + line.push(self.swatch_button(index, 30.0, 26.0)) + }) + }; + // ACI 10–249 come in groups of ten: 24 hue families across, their ten + // shades down. + let grid = (0u8..10).fold(column![].spacing(2), |grid, shade| { + grid.push((1u8..=24).fold(row![].spacing(2), |line, family| { + line.push(self.swatch_button(family * 10 + shade, 13.0, 13.0)) + })) + }); + column![ + column![section(t!("Standard colors").into_owned()), swatches(1..=9)].spacing(6), + column![ + section(t!("CAD Color Index (ACI) 10–249").into_owned()), + grid + ] + .spacing(6), + column![ + section(t!("Grayscale 250–255").into_owned()), + swatches(250..=255) + ] + .spacing(6), + ] + .spacing(12) + .into() + } + + fn swatch_button(&self, index: u8, width: f32, height: f32) -> Element<'_, Message> { + let fill = rgb_color(math::aci_rgb(index).unwrap_or((128, 128, 128))); + let selected = self.pending == AcadColor::Index(index); + button(Space::new().width(width).height(height)) + .on_press(picker_msg(ColorPickerMsg::Pick(AcadColor::Index(index)))) + .padding(0) + .style(move |theme: &Theme, status| { + let hovered = matches!(status, button::Status::Hovered | button::Status::Pressed); + button::Style { + background: Some(fill.into()), + border: Border { + color: if selected || hovered { + theme.palette().primary.base.color + } else { + Color::from_rgba(0.0, 0.0, 0.0, 0.35) + }, + width: if selected { + 2.5 + } else if hovered { + 1.5 + } else { + 1.0 + }, + radius: 2.0.into(), + }, + ..Default::default() + } + }) + .into() + } + + fn true_color_tab(&self) -> Element<'_, Message> { + // The eyedropper reads the window back from the GPU, which the web + // build cannot do. + let pipette: Option> = if cfg!(target_arch = "wasm32") { + None + } else { + Some( + // Just the icon, without a button frame. + button( + // Gray at rest; the accent colour while the pointer is on it. + iced::widget::svg(crate::ui::icons::themed_handle( + crate::ui::icons::EYEDROPPER, + )) + .width(24) + .height(24) + .style(|theme: &Theme, status| iced::widget::svg::Style { + color: Some(match status { + iced::widget::svg::Status::Hovered => { + theme.palette().primary.base.color + } + iced::widget::svg::Status::Idle => { + theme.palette().background.base.text.scale_alpha(0.5) + } + }), + }), + ) + .on_press(picker_msg(ColorPickerMsg::Eyedropper(EyedropperMsg::Start))) + .padding(0) + .style(|_theme: &Theme, _status| button::Style::default()) + .into(), + ) + }; + let nearest = (!self.editor_only()).then(|| self.nearest_button()); + self.editor.view(pipette, nearest) + } + + fn nearest_button(&self) -> Element<'_, Message> { + let (r, g, b) = self.rgb(); + let nearest = math::nearest_aci(r, g, b); + let nearest_rgb = math::aci_rgb(nearest).unwrap_or((128, 128, 128)); + let exact = nearest_rgb == (r, g, b) && !matches!(self.pending, AcadColor::Index(_)); + let fill = rgb_color(nearest_rgb); + row![ + text(if exact { + t!("Exact index match") + } else { + t!("Nearest index") + }) + .size(11) + .style(move |theme: &Theme| text::Style { + color: Some(if exact { + theme.palette().success.base.color + } else { + theme.palette().background.base.text.scale_alpha(0.65) + }), + }), + button( + row![ + container(Space::new()) + .width(16) + .height(16) + .style(move |_theme: &Theme| swatch_style(fill)), + text(format!("ACI {nearest}")) + .size(12) + .font(iced::Font::MONOSPACE), + ] + .spacing(6) + .align_y(iced::Center), + ) + .on_press(picker_msg(ColorPickerMsg::UseNearest)) + .padding([4, 8]) + .style(move |theme: &Theme, status| toggle_style(theme, exact, status)), + ] + .spacing(8) + .align_y(iced::Center) + .into() + } +} + +/// Move through the index palette with the arrow keys: the 24×10 block moves +/// by family (left/right) and shade (up/down); the standard and gray rows +/// move along their row. +fn step_index(index: u8, direction: ArrowKey) -> Option { + let along_row = |first: u8, last: u8| match direction { + ArrowKey::Left if index > first => Some(index - 1), + ArrowKey::Right if index < last => Some(index + 1), + _ => None, + }; + match index { + 1..=9 => along_row(1, 9), + 250..=255 => along_row(250, 255), + 10..=249 => { + let (family, shade) = (index / 10, index % 10); + match direction { + ArrowKey::Left if family > 1 => Some(index - 10), + ArrowKey::Right if family < 24 => Some(index + 10), + ArrowKey::Up if shade > 0 => Some(index - 1), + ArrowKey::Down if shade < 9 => Some(index + 1), + _ => None, + } + } + _ => None, + } +} + +/// Move keyboard focus to the next (or previous) field inside the panel. +pub fn focus_step(forward: bool) -> iced::Task { + use iced::advanced::widget::operation::{focusable, scope}; + let id = iced::widget::Id::new(PANEL_ID); + iced_runtime::task::effect(if forward { + iced_runtime::Action::widget(scope(id, focusable::focus_next())) + } else { + iced_runtime::Action::widget(scope(id, focusable::focus_previous())) + }) +} + +fn picker_msg(msg: ColorPickerMsg) -> Message { + Message::ColorPicker(msg) +} + +fn ink_is_dark(color: Color) -> bool { + let [r, g, b, _] = color.into_rgba8(); + math::ink_is_dark(r, g, b) +} + +fn filled(color: Color) -> container::Style { + container::Style { + background: Some(color.into()), + ..Default::default() + } +} + +pub(super) fn muted_text(theme: &Theme) -> text::Style { + text::Style { + color: Some(theme.palette().background.base.text.scale_alpha(0.65)), + } +} + +fn swatch_style(fill: Color) -> container::Style { + container::Style { + background: Some(fill.into()), + border: Border { + color: Color::from_rgba(0.0, 0.0, 0.0, 0.4), + width: 1.0, + radius: 3.0.into(), + }, + ..Default::default() + } +} + +fn panel_style(theme: &Theme) -> container::Style { + let palette = theme.palette(); + container::Style { + background: Some(palette.background.weakest.color.into()), + border: Border { + color: palette.background.weak.color, + width: 1.0, + radius: 8.0.into(), + }, + ..Default::default() + } +} + +fn segment_style(theme: &Theme, active: bool, status: button::Status) -> button::Style { + let palette = theme.palette(); + button::Style { + background: if active { + Some(palette.background.strong.color.into()) + } else if matches!(status, button::Status::Hovered) { + Some(palette.background.weak.color.into()) + } else { + None + }, + text_color: if active { + palette.background.strong.text + } else { + palette.background.base.text + }, + border: Border { + radius: 5.0.into(), + ..Border::default() + }, + ..Default::default() + } +} + +pub(super) fn toggle_style(theme: &Theme, active: bool, status: button::Status) -> button::Style { + let palette = theme.palette(); + button::Style { + background: Some(Background::Color(if active { + palette.primary.weak.color + } else if matches!(status, button::Status::Hovered) { + palette.background.weak.color + } else { + palette.background.base.color + })), + text_color: if active { + palette.primary.weak.text + } else { + palette.background.base.text + }, + border: Border { + color: if active { + palette.primary.base.color + } else { + palette.background.strong.color + }, + width: 1.0, + radius: 5.0.into(), + }, + ..Default::default() + } +} + +#[cfg(test)] +mod tests { + use super::super::editor::EditorMode; + use super::*; + + fn picker(current: AcadColor) -> ColorPicker { + ColorPicker::new(ColorPickTarget::Ribbon, current, false) + } + + fn edit(p: &mut ColorPicker, msg: EditorMsg) { + p.update(ColorPickerMsg::Editor(msg)); + } + + #[test] + fn opens_on_the_tab_that_fits_the_current_colour() { + assert_eq!(picker(AcadColor::Index(30)).tab(), ColorPickerTab::Index); + assert_eq!( + picker(AcadColor::Rgb { r: 1, g: 2, b: 3 }).tab(), + ColorPickerTab::TrueColor + ); + assert_eq!(picker(AcadColor::ByLayer).tab(), ColorPickerTab::Index); + } + + #[test] + fn revert_restores_the_current_colour() { + let mut p = picker(AcadColor::Index(30)); + p.update(ColorPickerMsg::Pick(AcadColor::Index(140))); + assert_eq!(p.pending(), AcadColor::Index(140)); + p.update(ColorPickerMsg::Revert); + assert_eq!(p.pending(), AcadColor::Index(30)); + } + + #[test] + fn ok_commits_and_cancel_does_not() { + let mut p = picker(AcadColor::Index(30)); + p.update(ColorPickerMsg::Pick(AcadColor::Index(5))); + assert_eq!( + p.update(ColorPickerMsg::Ok), + Some(Outcome::Commit(AcadColor::Index(5))) + ); + assert_eq!(p.update(ColorPickerMsg::Cancel), Some(Outcome::Cancel)); + } + + #[test] + fn ok_applies_a_hex_value_still_being_typed() { + let mut p = picker(AcadColor::Index(30)); + edit(&mut p, EditorMsg::HexInput("#3bf".into())); + assert_eq!( + p.update(ColorPickerMsg::Ok), + Some(Outcome::Commit(AcadColor::Rgb { + r: 0x33, + g: 0xBB, + b: 0xFF + })) + ); + } + + #[test] + fn the_editor_produces_true_colours() { + let mut p = picker(AcadColor::Index(1)); + edit(&mut p, EditorMsg::Hue(120.0)); + assert_eq!(p.pending(), AcadColor::Rgb { r: 0, g: 255, b: 0 }); + edit(&mut p, EditorMsg::Mode(EditorMode::Rgb)); + assert_eq!(p.pending(), AcadColor::Rgb { r: 0, g: 255, b: 0 }); + } + + #[test] + fn nearest_turns_a_true_colour_into_an_index() { + let mut p = picker(AcadColor::Rgb { r: 250, g: 4, b: 4 }); + p.update(ColorPickerMsg::UseNearest); + assert_eq!(p.pending(), AcadColor::Index(1)); + } + + #[test] + fn arrow_keys_walk_the_index_grid() { + assert_eq!(step_index(140, ArrowKey::Right), Some(150)); + assert_eq!(step_index(140, ArrowKey::Left), Some(130)); + assert_eq!(step_index(140, ArrowKey::Down), Some(141)); + assert_eq!(step_index(140, ArrowKey::Up), None); + assert_eq!(step_index(249, ArrowKey::Right), None); + assert_eq!(step_index(5, ArrowKey::Right), Some(6)); + assert_eq!(step_index(255, ArrowKey::Right), None); + + let mut p = picker(AcadColor::Index(140)); + p.update(ColorPickerMsg::Arrow(ArrowKey::Right)); + assert_eq!(p.pending(), AcadColor::Index(150)); + } + + #[test] + fn eyedropper_picks_a_pixel_and_esc_only_leaves_it() { + let mut p = picker(AcadColor::Index(30)); + p.update(ColorPickerMsg::Eyedropper(EyedropperMsg::Start)); + assert_eq!( + p.update(ColorPickerMsg::Eyedropper(EyedropperMsg::Move( + iced::Point::ORIGIN + ))), + Some(Outcome::Screenshot) + ); + // Esc and Enter while picking never close the panel. + assert_eq!(p.update(ColorPickerMsg::Ok), None); + assert_eq!(p.update(ColorPickerMsg::Cancel), None); + assert!(p.eyedropper_view().is_none()); + + p.update(ColorPickerMsg::Eyedropper(EyedropperMsg::Start)); + p.update(ColorPickerMsg::Eyedropper(EyedropperMsg::Move( + iced::Point::ORIGIN, + ))); + let shot = iced::window::Screenshot::new(vec![10, 20, 30, 255], iced::Size::new(1, 1), 1.0); + p.update(ColorPickerMsg::Eyedropper(EyedropperMsg::Shot(shot))); + p.update(ColorPickerMsg::Eyedropper(EyedropperMsg::Pick)); + assert!(p.eyedropper_view().is_none()); + assert_eq!( + p.pending(), + AcadColor::Rgb { + r: 10, + g: 20, + b: 30 + } + ); + } + + // ── Headless UI tests ─────────────────────────────────────────────── + // + // These run the real widgets through iced's simulator. Setting + // OCS_COLOR_PICKER_SNAPSHOTS to a folder also writes a PNG per view. + + fn simulator(picker: &ColorPicker) -> iced_test::simulator::Simulator<'_, Message> { + iced_test::simulator::Simulator::with_size( + iced::Settings { + fonts: vec![std::borrow::Cow::Borrowed(iced_aw::ICED_AW_FONT_BYTES)], + ..iced::Settings::default() + }, + (PANEL_WIDTH + 24.0, 560.0), + container(picker.view()).padding(12), + ) + } + + fn published(ui: iced_test::simulator::Simulator<'_, Message>) -> Vec { + ui.into_messages() + .filter_map(|message| match message { + Message::ColorPicker(msg) => Some(msg), + _ => None, + }) + .collect() + } + + #[test] + fn clicking_a_tab_switches_it() { + let p = picker(AcadColor::Index(30)); + let mut ui = simulator(&p); + ui.click(t!("True Color").as_ref()).expect("True Color tab"); + assert!(published(ui) + .iter() + .any(|msg| matches!(msg, ColorPickerMsg::Tab(ColorPickerTab::TrueColor)))); + } + + #[test] + fn dragging_a_slider_publishes_values() { + let mut p = picker(AcadColor::Rgb { + r: 57, + g: 191, + b: 252, + }); + edit(&mut p, EditorMsg::Mode(EditorMode::Rgb)); + let mut ui = simulator(&p); + let label = ui.find("R").expect("R label"); + let bounds = label.visible_bounds().expect("R visible"); + ui.point_at(iced::Point::new(bounds.x + 40.0, bounds.center_y())); + ui.simulate(iced_test::simulator::click()); + assert!(published(ui) + .iter() + .any(|msg| matches!(msg, ColorPickerMsg::Editor(EditorMsg::Red(v)) if *v < 57))); + } + + #[test] + fn interface_colours_show_only_the_editor() { + let p = ColorPicker::new( + ColorPickTarget::Interface(crate::app::UiColor::ModelBackground), + AcadColor::Rgb { + r: 30, + g: 30, + b: 30, + }, + false, + ); + let mut ui = simulator(&p); + assert!(ui.find(t!("Index Color").as_ref()).is_err()); + assert!(ui.find(t!("Nearest index").as_ref()).is_err()); + assert!(ui.find("HSB").is_ok()); + } + + #[test] + fn every_view_renders() { + let folder = std::env::var_os("OCS_COLOR_PICKER_SNAPSHOTS").map(std::path::PathBuf::from); + let blue = AcadColor::Rgb { + r: 57, + g: 191, + b: 252, + }; + let views: [( + &str, + ColorPickTarget, + AcadColor, + ColorPickerTab, + EditorMode, + bool, + ); 7] = [ + ( + "index", + ColorPickTarget::Properties, + AcadColor::Index(140), + ColorPickerTab::Index, + EditorMode::Hsb, + false, + ), + ( + "varies", + ColorPickTarget::Properties, + AcadColor::Index(30), + ColorPickerTab::Index, + EditorMode::Hsb, + true, + ), + ( + "hsb", + ColorPickTarget::Properties, + blue, + ColorPickerTab::TrueColor, + EditorMode::Hsb, + false, + ), + ( + "rgb", + ColorPickTarget::Properties, + blue, + ColorPickerTab::TrueColor, + EditorMode::Rgb, + false, + ), + ( + "field", + ColorPickTarget::Properties, + blue, + ColorPickerTab::TrueColor, + EditorMode::Field, + false, + ), + ( + "exact", + ColorPickTarget::Properties, + AcadColor::Rgb { r: 255, g: 0, b: 0 }, + ColorPickerTab::TrueColor, + EditorMode::Hsb, + false, + ), + ( + "interface", + ColorPickTarget::Interface(crate::app::UiColor::ModelBackground), + AcadColor::Rgb { + r: 33, + g: 40, + b: 48, + }, + ColorPickerTab::TrueColor, + EditorMode::Hsb, + false, + ), + ]; + for theme in [ + crate::ui::style::fusion_theme::fusion_black(), + crate::ui::style::fusion_theme::fusion_white(), + ] { + for (name, target, color, tab, mode, varies) in views.clone() { + let mut p = ColorPicker::new(target, color, varies); + p.update(ColorPickerMsg::Tab(tab)); + edit(&mut p, EditorMsg::Mode(mode)); + let mut ui = simulator(&p); + let snapshot = ui.snapshot(&theme).expect("snapshot"); + if let Some(folder) = &folder { + let shade = if theme.palette().background.base.color.r < 0.5 { + "dark" + } else { + "light" + }; + let path = folder.join(format!("{shade}-{name}.png")); + let _ = std::fs::remove_file(&path); + snapshot.matches_image(&path).expect("write snapshot"); + } + } + } + } +} diff --git a/src/ui/color_select/widgets/color_area.rs b/src/ui/color_select/widgets/color_area.rs new file mode 100644 index 0000000000..9ed22d1da3 --- /dev/null +++ b/src/ui/color_select/widgets/color_area.rs @@ -0,0 +1,258 @@ +//! Saturation/brightness field for one hue. +//! +//! Drawn as three layered quads instead of pixel by pixel: the solid hue, a +//! white-to-transparent wash from left to right, and a transparent-to-black +//! wash from top to bottom. Saturation runs left to right, brightness bottom +//! to top. Dragging anywhere moves the marker. + +use iced::advanced::layout::{self, Layout}; +use iced::advanced::widget::{self, tree, Widget}; +use iced::advanced::{mouse, renderer, Shell}; +use iced::gradient::Linear; +use iced::{ + Background, Border, Color, Element, Event, Gradient, Length, Point, Radians, Rectangle, + Renderer, Size, Theme, +}; + +const RADIUS: f32 = 5.0; +const MARKER: f32 = 16.0; + +pub struct ColorArea<'a, Message> { + /// Fully saturated, full-brightness colour of the current hue. + hue_color: Color, + /// The colour under the marker. + marker_color: Color, + saturation: f32, + brightness: f32, + on_change: Box Message + 'a>, + width: Length, + height: Length, +} + +#[derive(Default)] +struct State { + dragging: bool, +} + +impl<'a, Message> ColorArea<'a, Message> { + /// `saturation` and `brightness` are 0–1; `on_change` receives the same. + pub fn new( + hue_color: Color, + marker_color: Color, + saturation: f32, + brightness: f32, + on_change: impl Fn(f32, f32) -> Message + 'a, + ) -> Self { + Self { + hue_color, + marker_color, + saturation: saturation.clamp(0.0, 1.0), + brightness: brightness.clamp(0.0, 1.0), + on_change: Box::new(on_change), + width: Length::Fill, + height: Length::Fixed(150.0), + } + } + + pub fn height(mut self, height: impl Into) -> Self { + self.height = height.into(); + self + } + + fn values_at(bounds: Rectangle, cursor: Point) -> (f32, f32) { + let s = ((cursor.x - bounds.x) / bounds.width.max(1.0)).clamp(0.0, 1.0); + let b = 1.0 - ((cursor.y - bounds.y) / bounds.height.max(1.0)).clamp(0.0, 1.0); + (s, b) + } +} + +impl Widget for ColorArea<'_, Message> { + fn tag(&self) -> tree::Tag { + tree::Tag::of::() + } + + fn state(&self) -> tree::State { + tree::State::new(State::default()) + } + + fn size(&self) -> Size { + Size::new(self.width, self.height) + } + + fn layout( + &mut self, + _tree: &mut widget::Tree, + _renderer: &Renderer, + limits: &layout::Limits, + ) -> layout::Node { + layout::atomic(limits, self.width, self.height) + } + + fn update( + &mut self, + tree: &mut widget::Tree, + event: &Event, + layout: Layout<'_>, + cursor: mouse::Cursor, + _renderer: &Renderer, + shell: &mut Shell<'_, Message>, + _viewport: &Rectangle, + ) { + let state = tree.state.downcast_mut::(); + let bounds = layout.bounds(); + let publish = |shell: &mut Shell<'_, Message>, position: Point| { + let (s, b) = Self::values_at(bounds, position); + shell.publish((self.on_change)(s, b)); + shell.capture_event(); + }; + match event { + Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) => { + if let Some(position) = cursor.position_over(bounds) { + state.dragging = true; + publish(shell, position); + } + } + Event::Mouse(mouse::Event::CursorMoved { .. }) if state.dragging => { + if let Some(position) = cursor.position() { + publish(shell, position); + } + } + Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) if state.dragging => { + state.dragging = false; + shell.capture_event(); + } + _ => {} + } + } + + fn mouse_interaction( + &self, + tree: &widget::Tree, + layout: Layout<'_>, + cursor: mouse::Cursor, + _viewport: &Rectangle, + _renderer: &Renderer, + ) -> mouse::Interaction { + if tree.state.downcast_ref::().dragging || cursor.is_over(layout.bounds()) { + mouse::Interaction::Crosshair + } else { + mouse::Interaction::default() + } + } + + fn draw( + &self, + _tree: &widget::Tree, + renderer: &mut Renderer, + _theme: &Theme, + _style: &renderer::Style, + layout: Layout<'_>, + _cursor: mouse::Cursor, + _viewport: &Rectangle, + ) { + use iced::advanced::Renderer as _; + + let bounds = layout.bounds(); + let rounded = renderer::Quad { + bounds, + border: Border { + radius: RADIUS.into(), + ..Border::default() + }, + ..renderer::Quad::default() + }; + let wash = |angle: f32, from: Color, to: Color| { + Background::Gradient(Gradient::Linear( + Linear::new(Radians(angle)) + .add_stop(0.0, from) + .add_stop(1.0, to), + )) + }; + + renderer.fill_quad(rounded, self.hue_color); + renderer.fill_quad( + rounded, + wash( + std::f32::consts::FRAC_PI_2, + Color::WHITE, + Color { + a: 0.0, + ..Color::WHITE + }, + ), + ); + renderer.fill_quad( + renderer::Quad { + border: Border { + color: Color::from_rgba(0.0, 0.0, 0.0, 0.5), + width: 1.0, + radius: RADIUS.into(), + }, + ..rounded + }, + wash( + std::f32::consts::PI, + Color { + a: 0.0, + ..Color::BLACK + }, + Color::BLACK, + ), + ); + + let centre = Point::new( + bounds.x + bounds.width * self.saturation, + bounds.y + bounds.height * (1.0 - self.brightness), + ); + let marker = |size: f32| Rectangle { + x: centre.x - size / 2.0, + y: centre.y - size / 2.0, + width: size, + height: size, + }; + renderer.fill_quad( + renderer::Quad { + bounds: marker(MARKER + 2.0), + border: Border { + radius: ((MARKER + 2.0) / 2.0).into(), + ..Border::default() + }, + ..renderer::Quad::default() + }, + Color::from_rgba(0.0, 0.0, 0.0, 0.55), + ); + renderer.fill_quad( + renderer::Quad { + bounds: marker(MARKER), + border: Border { + color: Color::WHITE, + width: 2.0, + radius: (MARKER / 2.0).into(), + }, + ..renderer::Quad::default() + }, + self.marker_color, + ); + } +} + +impl<'a, Message: 'a> From> for Element<'a, Message> { + fn from(area: ColorArea<'a, Message>) -> Self { + Element::new(area) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn corners_map_to_saturation_and_brightness() { + let bounds = Rectangle::new(Point::new(10.0, 20.0), Size::new(200.0, 100.0)); + let at = |x, y| ColorArea::<()>::values_at(bounds, Point::new(x, y)); + assert_eq!(at(10.0, 20.0), (0.0, 1.0)); + assert_eq!(at(210.0, 120.0), (1.0, 0.0)); + assert_eq!(at(110.0, 70.0), (0.5, 0.5)); + assert_eq!(at(-5.0, 500.0), (0.0, 0.0)); + } +} diff --git a/src/ui/color_select/widgets/mod.rs b/src/ui/color_select/widgets/mod.rs new file mode 100644 index 0000000000..f25fc5ffa9 --- /dev/null +++ b/src/ui/color_select/widgets/mod.rs @@ -0,0 +1,5 @@ +//! Widgets the Select Color panel needs that iced does not provide. + +mod color_area; + +pub use color_area::ColorArea; diff --git a/src/ui/icons.rs b/src/ui/icons.rs index 02416477ce..35caaca190 100644 --- a/src/ui/icons.rs +++ b/src/ui/icons.rs @@ -62,6 +62,7 @@ static LAY_ULK: &[u8] = include_bytes!("../../assets/icons/layers/layulk.svg"); // All are black-on-transparent; recolour them at the call site with [`tinted`]. pub static CHECK: &[u8] = include_bytes!("../../assets/icons/ui/check.svg"); pub static CLOSE: &[u8] = include_bytes!("../../assets/icons/ui/close.svg"); +pub static EYEDROPPER: &[u8] = include_bytes!("../../assets/icons/ui/eyedropper.svg"); pub static PLUS: &[u8] = include_bytes!("../../assets/icons/ui/plus.svg"); pub static REFRESH: &[u8] = include_bytes!("../../assets/icons/ui/refresh.svg"); pub static SWAP: &[u8] = include_bytes!("../../assets/icons/ui/swap.svg"); diff --git a/src/ui/window/options.rs b/src/ui/window/options.rs index a6ff74874e..5b1ea49f9b 100644 --- a/src/ui/window/options.rs +++ b/src/ui/window/options.rs @@ -157,22 +157,17 @@ impl fmt::Display for Labelled { } } -/// A background swatch that opens the colour wheel when clicked. +/// A colour swatch that opens the Select Color panel when clicked. /// -/// The wheel sits alongside the hex field rather than replacing it: typing +/// The swatch sits beside the hex field rather than replacing it: typing /// `#1E1E1E` stays the fastest way to reproduce an exact colour, while the -/// wheel is for choosing one by eye. -fn bg_swatch_picker<'a>( - target: crate::app::BgTarget, - rgb: [u8; 3], - open: Option, -) -> Element<'a, Message> { - let colour = iced::Color::from_rgb8(rgb[0], rgb[1], rgb[2]); +/// panel is for choosing one by eye. +fn color_swatch<'a>(target: crate::app::UiColor, [r, g, b]: [u8; 3]) -> Element<'a, Message> { let swatch = container(Space::new()) .width(28) .height(22) .style(move |theme: &Theme| container::Style { - background: Some(Background::Color(colour)), + background: Some(Background::Color(iced::Color::from_rgb8(r, g, b))), border: Border { color: theme.palette().background.strong.color, width: 1.0, @@ -180,18 +175,14 @@ fn bg_swatch_picker<'a>( }, ..Default::default() }); - let underlay = button(swatch) - .on_press(Message::BgPickerOpen(target)) + button(swatch) + .on_press(Message::OpenColorWindow( + crate::app::ColorPickTarget::Interface(target), + codec::types::Color::Rgb { r, g, b }, + )) .padding(0) - .style(button::text); - iced_aw::ColorPicker::new( - open == Some(target), - colour, - underlay, - Message::BgPickerCancel, - Message::BgPickerSubmit, - ) - .into() + .style(button::text) + .into() } #[allow(clippy::too_many_arguments)] @@ -227,7 +218,6 @@ pub fn view_window<'a>( model_bg_input: &'a str, paper_bg_input: &'a str, desk_bg_input: &'a str, - bg_picker: Option, dirty: bool, close_confirm: bool, sizing: crate::ui::modal::ModalSizing, @@ -307,18 +297,8 @@ pub fn view_window<'a>( let mut color_controls = column![].spacing(8); for (index, (label, color)) in colors.into_iter().enumerate() { - let swatch = container(Space::new()) - .width(28) - .height(22) - .style(move |theme: &Theme| container::Style { - background: Some(Background::Color(color)), - border: Border { - color: theme.palette().background.strong.color, - width: 1.0, - radius: 3.0.into(), - }, - ..Default::default() - }); + let [r, g, bl, _] = color.into_rgba8(); + let swatch = color_swatch(crate::app::UiColor::Theme(index), [r, g, bl]); color_controls = color_controls.push( row![ text(label).size(12).width(110), @@ -528,61 +508,18 @@ pub fn view_window<'a>( .spacing(0) .width(sizing.width); - let crosshair_rgb = crosshair_color.unwrap_or([255, 255, 255]); - let crosshair_swatch = - container(Space::new()) - .width(28) - .height(22) - .style(move |theme: &Theme| container::Style { - background: Some(Background::Color(iced::Color::from_rgb8( - crosshair_rgb[0], - crosshair_rgb[1], - crosshair_rgb[2], - ))), - border: Border { - color: theme.palette().background.strong.color, - width: 1.0, - radius: 3.0.into(), - }, - ..Default::default() - }); - - let command_rgb = command_text_color.unwrap_or([220, 220, 220]); - let command_swatch = - container(Space::new()) - .width(28) - .height(22) - .style(move |theme: &Theme| container::Style { - background: Some(Background::Color(iced::Color::from_rgb8( - command_rgb[0], - command_rgb[1], - command_rgb[2], - ))), - border: Border { - color: theme.palette().background.strong.color, - width: 1.0, - radius: 3.0.into(), - }, - ..Default::default() - }); - - let snap_rgb = snap_marker_color.unwrap_or([255, 230, 26]); - let snap_swatch = container(Space::new()) - .width(28) - .height(22) - .style(move |theme: &Theme| container::Style { - background: Some(Background::Color(iced::Color::from_rgb8( - snap_rgb[0], - snap_rgb[1], - snap_rgb[2], - ))), - border: Border { - color: theme.palette().background.strong.color, - width: 1.0, - radius: 3.0.into(), - }, - ..Default::default() - }); + let crosshair_swatch = color_swatch( + crate::app::UiColor::Crosshair, + crosshair_color.unwrap_or([255, 255, 255]), + ); + let command_swatch = color_swatch( + crate::app::UiColor::CommandText, + command_text_color.unwrap_or([220, 220, 220]), + ); + let snap_swatch = color_swatch( + crate::app::UiColor::SnapMarker, + snap_marker_color.unwrap_or([255, 230, 26]), + ); let model_bg_rgb = model_space .custom_bg @@ -742,7 +679,7 @@ pub fn view_window<'a>( display = display.push(Space::new().height(10)).push( row![ text(crate::t!("Model background")).size(12).width(140), - bg_swatch_picker(crate::app::BgTarget::Model, model_bg_rgb, bg_picker), + color_swatch(crate::app::UiColor::ModelBackground, model_bg_rgb), text_input("#RRGGBB", model_bg_input) .on_input(Message::ModelSpaceBgChanged) .width(150), @@ -755,7 +692,7 @@ pub fn view_window<'a>( display = display.push(Space::new().height(10)).push( row![ text(crate::t!("Paper background")).size(12).width(140), - bg_swatch_picker(crate::app::BgTarget::Paper, paper_bg_rgb, bg_picker), + color_swatch(crate::app::UiColor::PaperBackground, paper_bg_rgb), text_input("#RRGGBB", paper_bg_input) .on_input(Message::PaperSpaceBgChanged) .width(150), @@ -767,7 +704,7 @@ pub fn view_window<'a>( display = display.push(Space::new().height(10)).push( row![ text(crate::t!("Desk surround")).size(12).width(140), - bg_swatch_picker(crate::app::BgTarget::Desk, desk_bg_rgb, bg_picker), + color_swatch(crate::app::UiColor::DeskBackground, desk_bg_rgb), text_input("#RRGGBB", desk_bg_input) .on_input(Message::DeskSpaceBgChanged) .width(150),