dsh-design-studio 1.5.0 → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +6 -5
- package/README.md +7 -6
- package/THIRD_PARTY_NOTICES.md +108 -0
- package/assets/art/README.md +102 -0
- package/assets/art/brand-mark.webp +0 -0
- package/assets/art/check-clean.webp +0 -0
- package/assets/art/coach-markup.webp +0 -0
- package/assets/art/drop-file.webp +0 -0
- package/assets/art/empty-components.webp +0 -0
- package/assets/art/empty-data.webp +0 -0
- package/assets/art/empty-error.webp +0 -0
- package/assets/art/empty-frames.webp +0 -0
- package/assets/art/empty-history.webp +0 -0
- package/assets/art/empty-market.webp +0 -0
- package/assets/art/empty-notes.webp +0 -0
- package/assets/art/empty-search.webp +0 -0
- package/assets/art/empty-tokens.webp +0 -0
- package/assets/art/empty-works.webp +0 -0
- package/assets/art/guide-icon.webp +0 -0
- package/assets/art/kind-app.webp +0 -0
- package/assets/art/kind-desktop.webp +0 -0
- package/assets/art/kind-diagram.webp +0 -0
- package/assets/art/kind-dshplugin.webp +0 -0
- package/assets/art/kind-email.webp +0 -0
- package/assets/art/kind-embedded.webp +0 -0
- package/assets/art/kind-framed.webp +0 -0
- package/assets/art/kind-miniprogram.webp +0 -0
- package/assets/art/kind-poster.webp +0 -0
- package/assets/art/kind-slides.webp +0 -0
- package/assets/art/kind-tablet.webp +0 -0
- package/assets/art/kind-web.webp +0 -0
- package/assets/art/placeholder-inspire-img.webp +0 -0
- package/assets/art/wait-creating.webp +0 -0
- package/assets/demo.gif +0 -0
- package/assets/hero-sm.jpg +0 -0
- package/assets/motion/ai-capsule.html +124 -0
- package/assets/motion/ai-glow-input.html +112 -0
- package/assets/motion/balance-odometer.html +112 -0
- package/assets/motion/bottom-sheet.html +149 -0
- package/assets/motion/brightness-pill.html +114 -0
- package/assets/motion/comet-ring.html +95 -0
- package/assets/motion/copy-morph.html +116 -0
- package/assets/motion/cube-grid.html +103 -0
- package/assets/motion/day-night.html +120 -0
- package/assets/motion/dial-knob.html +130 -0
- package/assets/motion/dock-magnify.html +118 -0
- package/assets/motion/download-ring.html +135 -0
- package/assets/motion/expand-card.html +137 -0
- package/assets/motion/flip-card.html +100 -0
- package/assets/motion/hold-pay.html +137 -0
- package/assets/motion/holo-card.html +130 -0
- package/assets/motion/keycap.html +92 -0
- package/assets/motion/like-jelly.html +88 -0
- package/assets/motion/liquid-progress.html +113 -0
- package/assets/motion/liquid-segment.html +127 -0
- package/assets/motion/live-capsule.html +144 -0
- package/assets/motion/marker-highlight.html +94 -0
- package/assets/motion/marquee-logos.html +110 -0
- package/assets/motion/otp-code.html +111 -0
- package/assets/motion/password-eye.html +136 -0
- package/assets/motion/ruler-slider.html +140 -0
- package/assets/motion/search-expand.html +81 -0
- package/assets/motion/send-fly.html +121 -0
- package/assets/motion/skeleton-shine.html +124 -0
- package/assets/motion/star-rate.html +98 -0
- package/assets/motion/success-check.html +114 -0
- package/assets/motion/suggest-chips.html +134 -0
- package/assets/motion/swipe-row.html +126 -0
- package/assets/motion/tabbar-bounce.html +92 -0
- package/assets/motion/tactile-controls.html +89 -0
- package/assets/motion/text-scramble.html +173 -0
- package/assets/motion/toast-stack.html +115 -0
- package/assets/motion/token-stream.html +106 -0
- package/assets/motion/voice-orb.html +144 -0
- package/assets/showcase/alley-noodles-1.webp +0 -0
- package/assets/showcase/alley-noodles-2.webp +0 -0
- package/assets/showcase/alley-noodles-3.webp +0 -0
- package/assets/showcase/autumn-sale-1.webp +0 -0
- package/assets/showcase/bold-folio-1.webp +0 -0
- package/assets/showcase/bold-folio-2.webp +0 -0
- package/assets/showcase/book-club-1.webp +0 -0
- package/assets/showcase/book-club-2.webp +0 -0
- package/assets/showcase/book-club-3.webp +0 -0
- package/assets/showcase/flower-order-1.webp +0 -0
- package/assets/showcase/little-painter-1.webp +0 -0
- package/assets/showcase/little-painter-2.webp +0 -0
- package/assets/showcase/moon-fair-1.webp +0 -0
- package/assets/showcase/nail-booking-1.webp +0 -0
- package/assets/showcase/nail-booking-2.webp +0 -0
- package/assets/showcase/nail-booking-3.webp +0 -0
- package/assets/showcase/night-run-1.webp +0 -0
- package/assets/showcase/paw-diary-1.webp +0 -0
- package/assets/showcase/paw-diary-2.webp +0 -0
- package/assets/showcase/paw-diary-3.webp +0 -0
- package/assets/showcase/pixel-planet-1.webp +0 -0
- package/assets/showcase/pixel-planet-2.webp +0 -0
- package/assets/showcase/pixel-planet-3.webp +0 -0
- package/assets/showcase/pocket-ledger-1.webp +0 -0
- package/assets/showcase/pocket-ledger-2.webp +0 -0
- package/assets/showcase/shiftloom-1.webp +0 -0
- package/assets/showcase/shiftloom-2.webp +0 -0
- package/assets/showcase/slow-breath-1.webp +0 -0
- package/assets/showcase/slow-breath-2.webp +0 -0
- package/assets/showcase/slow-breath-3.webp +0 -0
- package/assets/showcase/slow-trip-1.webp +0 -0
- package/assets/showcase/slow-trip-2.webp +0 -0
- package/assets/showcase/slow-trip-3.webp +0 -0
- package/assets/showcase/slow-weekly-1.webp +0 -0
- package/assets/showcase/stay-confirm-1.webp +0 -0
- package/assets/showcase/stove-recipes-1.webp +0 -0
- package/assets/showcase/stove-recipes-2.webp +0 -0
- package/assets/showcase/strobewatch-1.webp +0 -0
- package/assets/showcase/strobewatch-2.webp +0 -0
- package/assets/showcase/tapeworks-1.webp +0 -0
- package/assets/showcase/tapeworks-2.webp +0 -0
- package/assets/showcase/tea-brand-pitch-1.webp +0 -0
- package/assets/showcase/tea-brand-pitch-2.webp +0 -0
- package/assets/showcase/tea-brand-pitch-3.webp +0 -0
- package/assets/showcase/time-bookshop-1.webp +0 -0
- package/assets/showcase/time-bookshop-2.webp +0 -0
- package/assets/showcase/water-journey-1.webp +0 -0
- package/assets/showcase/water-journey-2.webp +0 -0
- package/assets/showcase/water-journey-3.webp +0 -0
- package/assets/showcase/weekend-go-1.webp +0 -0
- package/assets/showcase/weekend-go-2.webp +0 -0
- package/assets/showcase/weekend-go-3.webp +0 -0
- package/assets/showcase/winter-soup-1.webp +0 -0
- package/assets/showcase/year-review-1.webp +0 -0
- package/assets/showcase/year-review-2.webp +0 -0
- package/assets/showcase/year-review-3.webp +0 -0
- package/lib/browser.js +3 -1
- package/lib/bundle.js +8 -3
- package/lib/canvthumb.js +9 -6
- package/lib/client.js +7428 -2624
- package/lib/components.js +4 -2
- package/lib/core.js +762 -132
- package/lib/design-page-settings.js +48 -0
- package/lib/design-scope.js +36 -0
- package/lib/design-transactions.js +259 -0
- package/lib/drop-folder.js +25 -0
- package/lib/edits.js +125 -8
- package/lib/embedded/lvgl_shot.c +133 -0
- package/lib/embedded/qml_shot.py +66 -0
- package/lib/embedded-shot.js +400 -0
- package/lib/embedded-trust.js +76 -0
- package/lib/fonts.js +30 -21
- package/lib/frames.js +23 -23
- package/lib/gallery/css.js +9 -2
- package/lib/gallery/market-routes.js +23 -7
- package/lib/gallery/pack.js +25 -8
- package/lib/gallery/policy.js +6 -4
- package/lib/gallery/routes.js +255 -83
- package/lib/gallery/submit.js +285 -57
- package/lib/gallery/use.js +13 -4
- package/lib/handoff-embedded.js +1182 -0
- package/lib/handoff.js +212 -71
- package/lib/history.js +393 -43
- package/lib/htmlpack.js +34 -13
- package/lib/impl.js +3 -0
- package/lib/index.js +661 -136
- package/lib/inspire.js +73 -26
- package/lib/kinds.js +11 -2
- package/lib/look.js +45 -25
- package/lib/mock.js +41 -4
- package/lib/motion.js +90 -0
- package/lib/page-settings.js +103 -0
- package/lib/picker.js +348 -70
- package/lib/rules.js +85 -0
- package/lib/serve.js +154 -15
- package/lib/showcase.json +22 -0
- package/lib/styles.js +16 -7
- package/lib/system.js +19 -8
- package/lib/tool.js +2 -1
- package/lib/tweaks.js +146 -9
- package/lib/works.js +151 -19
- package/locale/auto/en.json +1 -1
- package/locale/auto/zh.json +1 -1
- package/locale/en.json +1 -1
- package/locale/offline/en.json +1 -1
- package/locale/offline/zh.json +2 -2
- package/locale/zh.json +1 -1
- package/package.json +3 -2
- package/skills/ui-design/SKILL.md +56 -46
- package/skills/ui-design/frames/dsh/frame.json +1 -1
- package/skills/ui-design/references/app.md +29 -2
- package/skills/ui-design/references/components.md +1 -1
- package/skills/ui-design/references/desktop.md +1 -1
- package/skills/ui-design/references/dshplugin.md +12 -12
- package/skills/ui-design/references/embedded.md +40 -0
- package/skills/ui-design/references/frames.md +20 -20
- package/skills/ui-design/references/miniprogram.md +2 -2
- package/skills/ui-design/references/mock.md +16 -0
- package/skills/ui-design/references/poster.md +2 -1
- package/skills/ui-design/references/tweaks.md +17 -0
- package/skills/ui-design/tokens.css +19 -5
|
@@ -0,0 +1,1182 @@
|
|
|
1
|
+
/** 嵌入式工程识别,以及 LVGL / QML 的交接说明。 */
|
|
2
|
+
import fs from 'node:fs'
|
|
3
|
+
import path from 'node:path'
|
|
4
|
+
import { createHash } from 'node:crypto'
|
|
5
|
+
import { fileURLToPath } from 'node:url'
|
|
6
|
+
import { decodeEntities, tokenize } from './gallery/html.js'
|
|
7
|
+
import { scanCss } from './gallery/css.js'
|
|
8
|
+
import { FONT_DIR, loadFontIndex } from './fonts.js'
|
|
9
|
+
import { dirReader } from './comp-io.js'
|
|
10
|
+
|
|
11
|
+
export const EMBEDDED = new Set(['lvgl', 'qml'])
|
|
12
|
+
|
|
13
|
+
export function embeddedScreenFiles(rows, target) {
|
|
14
|
+
const used = new Set()
|
|
15
|
+
return new Map(rows.map(({ key }) => {
|
|
16
|
+
const words = key.replace(/\.html?$/i, '').match(/[a-z0-9]+/gi) || []
|
|
17
|
+
const stem = target === 'lvgl' ? words.join('_').toLowerCase() || 'screen'
|
|
18
|
+
: words.map((word) => word[0].toUpperCase() + word.slice(1)).join('')
|
|
19
|
+
const base = target === 'lvgl' ? 'ui_' + stem : /^[A-Z]/.test(stem) ? stem : 'Screen' + stem
|
|
20
|
+
let name = base
|
|
21
|
+
for (let index = 2; used.has(name.toLowerCase()); index++) name = base + '_' + index
|
|
22
|
+
used.add(name.toLowerCase())
|
|
23
|
+
return [key, 'screens/' + name + (target === 'lvgl' ? '.c' : 'Page.qml')]
|
|
24
|
+
}))
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// .pio 例外:PlatformIO 把 lib_deps 里的 LVGL 下到 .pio/libdeps/<环境>/lvgl(.pio/build 照样跳过)
|
|
28
|
+
const SKIP = /^(?:\.(?!pio$)|build$|debug$|release$|node_modules$)/i
|
|
29
|
+
const LVGL_DIRS = ['lvgl', 'Middlewares/Third_Party/lvgl', 'components/lvgl', 'lib/lvgl']
|
|
30
|
+
const read = (file) => { try { return fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, '') } catch { return '' } }
|
|
31
|
+
const entries = (dir) => { try { return fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0) } catch { return [] } }
|
|
32
|
+
const joinRel = (dir, file) => dir ? dir + '/' + file : file
|
|
33
|
+
|
|
34
|
+
/** 从近到远,只读四层目录;不跟目录软链接,不查构建产物;最多看 4000 项(工作区很大时别卡住) */
|
|
35
|
+
const SCAN_MAX = 4000
|
|
36
|
+
function projectFiles(root) {
|
|
37
|
+
const dirs = [{ rel: '', depth: 0 }]
|
|
38
|
+
const files = []
|
|
39
|
+
let seen = 0
|
|
40
|
+
for (const { rel, depth } of dirs) {
|
|
41
|
+
if (seen > SCAN_MAX) break
|
|
42
|
+
for (const e of entries(path.join(root, rel))) {
|
|
43
|
+
if (++seen > SCAN_MAX) break
|
|
44
|
+
const at = joinRel(rel, e.name)
|
|
45
|
+
if (e.isFile()) files.push({ name: e.name, rel, at, depth })
|
|
46
|
+
if (e.isDirectory() && depth < 4 && !SKIP.test(e.name)) dirs.push({ rel: at, depth: depth + 1 })
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return files
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const withoutCComments = (text) => text.replace(/\/\*[\s\S]*?\*\/|\/\/[^\r\n]*/g, ' ')
|
|
53
|
+
function define(text, name) {
|
|
54
|
+
return new RegExp('^\\s*#\\s*define[ \\t]+' + name + '[ \\t]+\\(?[ \\t]*([A-Za-z0-9_]+)\\b', 'm').exec(text)?.[1] || ''
|
|
55
|
+
}
|
|
56
|
+
function numberMacro(text, name) {
|
|
57
|
+
const value = define(text, name)
|
|
58
|
+
return /^\d+$/.test(value) ? Number(value) : null
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function lvglOf(root, files) {
|
|
62
|
+
const headerRank = ({ name, rel, depth }) => {
|
|
63
|
+
const at = rel.replace(/(?:^|\/)include\/lvgl$/, '')
|
|
64
|
+
const known = LVGL_DIRS.indexOf(at)
|
|
65
|
+
return (name === 'lv_version.h' ? 0 : 100) + (known >= 0 ? known : at ? 20 + depth : 5)
|
|
66
|
+
}
|
|
67
|
+
// 库只认工程里常见的几个位置(或工程本身就是 LVGL 库):别把子文件夹里另一个工程的 LVGL 当成这个目录的
|
|
68
|
+
const libAt = (rel) => { const at = rel.replace(/(?:^|\/)include\/lvgl$/, ''); return !at || LVGL_DIRS.includes(at) || /(?:^|\/)lvgl$/i.test(at) && at.split('/').length <= 3 || /^\.pio\/libdeps\/[^/]+\/lvgl$/i.test(at) }
|
|
69
|
+
const headers = files.filter((f) => /^(lv_version|lvgl)\.h$/.test(f.name) && libAt(f.rel)).sort((a, b) => headerRank(a) - headerRank(b))
|
|
70
|
+
for (const h of headers) {
|
|
71
|
+
const at = h.rel.replace(/(?:^|\/)include\/lvgl$/, '')
|
|
72
|
+
let version = withoutCComments(read(path.join(root, h.at)))
|
|
73
|
+
// 9.6 的根头文件只转发到公开头文件;即使在第三方库里也只跟这个已知位置。
|
|
74
|
+
// 9.6 的真文件写的是 #include "../include/lvgl/lv_version.h"
|
|
75
|
+
if (h.name === 'lv_version.h' && /#\s*include\s*[<"](?:\.{1,2}\/)?include\/lvgl\/lv_version\.h[>"]/.test(version)) {
|
|
76
|
+
version = withoutCComments(read(path.join(root, h.rel, 'include/lvgl/lv_version.h')))
|
|
77
|
+
}
|
|
78
|
+
const [major, minor, patch] = ['MAJOR', 'MINOR', 'PATCH'].map((part) => numberMacro(version, 'LVGL_VERSION_' + part))
|
|
79
|
+
if (!major || minor === null) continue
|
|
80
|
+
const confFile = files.find((f) => f.name === 'lv_conf.h' && !f.rel) ||
|
|
81
|
+
files.find((f) => f.name === 'lv_conf.h' && f.rel !== at && !f.rel.startsWith(at + '/')) ||
|
|
82
|
+
files.find((f) => f.name === 'lv_conf.h')
|
|
83
|
+
const conf = confFile ? withoutCComments(read(path.join(root, confFile.at))) : ''
|
|
84
|
+
const format = define(conf, 'LV_COLOR_FORMAT_DEFAULT')
|
|
85
|
+
const formats = { LV_COLOR_FORMAT_RGB565: 16, LV_COLOR_FORMAT_RGB565_SWAPPED: 16, LV_COLOR_FORMAT_RGB888: 24, LV_COLOR_FORMAT_XRGB8888: 32, LV_COLOR_FORMAT_ARGB8888: 32, LV_COLOR_FORMAT_L8: 8, LV_COLOR_FORMAT_I1: 1 }
|
|
86
|
+
const colorDepth = formats[format] ?? numberMacro(conf, 'LV_COLOR_DEPTH')
|
|
87
|
+
const fontCompressed = numberMacro(conf, 'LV_USE_FONT_COMPRESSED')
|
|
88
|
+
const buildFiles = at ? files.filter((f) => f.rel !== at && !f.rel.startsWith(at + '/')) : files.filter((f) => !f.rel)
|
|
89
|
+
const ide = buildFiles.some((f) => f.name === '.cproject' || /\.ioc$/i.test(f.name)) ? 'STM32CubeIDE'
|
|
90
|
+
: buildFiles.some((f) => /\.uvprojx$/i.test(f.name)) ? 'Keil MDK'
|
|
91
|
+
: buildFiles.some((f) => f.name === 'platformio.ini') ? 'PlatformIO'
|
|
92
|
+
: buildFiles.some((f) => f.name === 'CMakeLists.txt') ? 'CMake'
|
|
93
|
+
: buildFiles.some((f) => /^Makefile$/i.test(f.name)) ? 'Make' : ''
|
|
94
|
+
const detail = [ide, colorDepth ? colorDepth + ' 位色' : ''].filter(Boolean).join(',')
|
|
95
|
+
return { framework: 'lvgl', label: 'LVGL ' + major + '.' + minor + (detail ? '(' + detail + ')' : ''),
|
|
96
|
+
lvgl: { major, minor, patch, colorDepth, fontCompressed, ide, at: at || '.', conf: confFile ? confFile.at : '' } }
|
|
97
|
+
}
|
|
98
|
+
return null
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function qmlOf(root, files) {
|
|
102
|
+
// CMake / qmake 的项目文件优先。双版本 CMake 要看实际构建选的是哪一套。
|
|
103
|
+
const cmake = files.filter((f) => f.name === 'CMakeLists.txt' && f.depth <= 1)
|
|
104
|
+
.map((f) => read(path.join(root, f.at)).replace(/#\[\[.*?\]\]|#[^\r\n]*/gs, '')).join('\n')
|
|
105
|
+
const qtPackages = [...cmake.matchAll(/\bfind_package\s*\(\s*Qt([56])?\b([^)]*)\)/gi)]
|
|
106
|
+
const quick = qtPackages.some((m) => /(?:^|\s|")(?:Quick|Qml)(?=\s|"|$)/i.test(m[2]))
|
|
107
|
+
const majors = new Set(qtPackages.map((m) => Number(m[1])).filter(Boolean))
|
|
108
|
+
if (quick || /\bqt(?:6)?_add_qml_module\s*\(/i.test(cmake)) {
|
|
109
|
+
const major = majors.size === 1 ? [...majors][0] : majors.size === 0 && /\bqt(?:6)?_add_qml_module\s*\(/i.test(cmake) ? 6 : 0
|
|
110
|
+
return { major, build: 'CMake' }
|
|
111
|
+
}
|
|
112
|
+
for (const f of files.filter((f) => /\.pro$/i.test(f.name) && f.depth <= 1)) {
|
|
113
|
+
const pro = read(path.join(root, f.at)).replace(/#[^\r\n]*/g, '').replace(/\\\r?\n/g, ' ')
|
|
114
|
+
if (!/\bQT[ \t]*(?:\+?=|\*=)[^\r\n]*\b(?:quick|qml)\b/i.test(pro)) continue
|
|
115
|
+
const major = Number(/^[ \t]*(?:QT_MAJOR_VERSION[ \t]*=[ \t]*([56])\b|QT_VERSION[ \t]*=[ \t]*([56])\.)/m.exec(pro)?.slice(1).find(Boolean)) || 0
|
|
116
|
+
return { major, build: 'qmake' }
|
|
117
|
+
}
|
|
118
|
+
if (files.some((f) => /\.qmlproject$/i.test(f.name) && f.depth <= 1)) return { major: 0, build: 'Qt Design Studio' }
|
|
119
|
+
if (files.some((f) => f.name === 'qmldir' && f.depth <= 1 &&
|
|
120
|
+
files.some((q) => /\.qml$/i.test(q.name) && (!f.rel || q.rel === f.rel || q.rel.startsWith(f.rel + '/'))))) {
|
|
121
|
+
return { major: 0, build: '' }
|
|
122
|
+
}
|
|
123
|
+
return null
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export function detectEmbeddedProject(root) {
|
|
127
|
+
if (!root) return null
|
|
128
|
+
// 这个目录自己得像工程(顶层有工程文件或 LVGL 常放的目录):工作区里放着几个工程时,别把里面某一个当成整个工作区
|
|
129
|
+
if (!entries(root).some((e) => e.isDirectory()
|
|
130
|
+
? LVGL_DIRS.some((dir) => dir.split('/')[0] === e.name) || e.name === 'qml'
|
|
131
|
+
: /^(?:lv_version\.h|lvgl\.h|lv_conf\.h|CMakeLists\.txt|Makefile|platformio\.ini|\.cproject|qmldir)$|\.(?:ioc|uvprojx|pro|qmlproject)$/i.test(e.name))) return null
|
|
132
|
+
const files = projectFiles(root)
|
|
133
|
+
const lvgl = lvglOf(root, files)
|
|
134
|
+
if (lvgl) return lvgl
|
|
135
|
+
const qt = qmlOf(root, files)
|
|
136
|
+
return qt && { framework: 'qml', label: 'Qt' + (qt.major ? ' ' + qt.major : '') + ' QML' + (qt.build ? '(' + qt.build + ')' : ''), qt }
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function scanScreen(html) {
|
|
140
|
+
const styles = []
|
|
141
|
+
const inlineStyles = []
|
|
142
|
+
const links = []
|
|
143
|
+
const texts = []
|
|
144
|
+
const tags = []
|
|
145
|
+
let ignored = ''
|
|
146
|
+
for (const t of tokenize(String(html))) {
|
|
147
|
+
if (t.type === 'text' && t.raw === 'style') styles.push(t.text)
|
|
148
|
+
if (t.type === 'endtag' && t.tag.name === ignored) ignored = ''
|
|
149
|
+
if (t.type === 'tag') {
|
|
150
|
+
const { name } = t.tag
|
|
151
|
+
const attrs = new Map(t.tag.attrs.map((a) => [a.name, a.value]))
|
|
152
|
+
if (attrs.has('style')) inlineStyles.push(attrs.get('style'))
|
|
153
|
+
if (name === 'link' && /(?:^|\s)stylesheet(?:$|\s)/i.test(attrs.get('rel') || '')) links.push(attrs.get('href'))
|
|
154
|
+
if (!ignored && /^(head|script|style|title|noscript|defs|symbol)$/.test(name) && !t.tag.selfClosing) ignored = name
|
|
155
|
+
if (ignored || /^(meta|link)$/.test(name)) continue
|
|
156
|
+
tags.push({ name, attrs })
|
|
157
|
+
for (const attr of ['placeholder', 'alt']) if (attrs.has(attr)) texts.push(attrs.get(attr))
|
|
158
|
+
if (name === 'input' && !/^(hidden|password|checkbox|radio)$/i.test(attrs.get('type') || '') && attrs.has('value')) texts.push(attrs.get('value'))
|
|
159
|
+
}
|
|
160
|
+
if (!ignored && (t.type === 'text' || t.type === 'cdata')) texts.push(t.type === 'cdata' ? t.text : decodeEntities(t.text).text)
|
|
161
|
+
}
|
|
162
|
+
return { styles, inlineStyles, texts, tags, links }
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function cssRel(root, screen, href) {
|
|
166
|
+
const source = (href || '').trim()
|
|
167
|
+
if (!source || /^(?:[\w+.-]+:|\/\/)/.test(source)) return ''
|
|
168
|
+
let name
|
|
169
|
+
try { name = decodeURIComponent(source.split(/[?#]/)[0]) } catch { return '' }
|
|
170
|
+
if (!name) return ''
|
|
171
|
+
const base = path.join(root, path.dirname(screen))
|
|
172
|
+
const file = name.startsWith('/') ? path.resolve(root, '.' + name) : path.resolve(base, name)
|
|
173
|
+
const rel = path.relative(root, file)
|
|
174
|
+
if (!rel || rel.startsWith('..' + path.sep) || rel === '..' || path.isAbsolute(rel)) return ''
|
|
175
|
+
return rel.split(path.sep).join('/')
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function cssSources(root, screens, css) {
|
|
179
|
+
const sources = new Map()
|
|
180
|
+
if (root) {
|
|
181
|
+
const readLocal = dirReader(root)
|
|
182
|
+
const add = (rel) => { if (rel && !sources.has(rel)) sources.set(rel, readLocal(rel)?.toString('utf8') || '') }
|
|
183
|
+
add('tokens.css')
|
|
184
|
+
for (const [key, sc] of screens) for (const href of sc.links) {
|
|
185
|
+
add(cssRel(root, key, href))
|
|
186
|
+
}
|
|
187
|
+
// Map 的迭代也会读到新加进来的 @import;见过的文件不再读。
|
|
188
|
+
for (const [key, text] of sources) {
|
|
189
|
+
for (const m of text.replace(/\/\*[\s\S]*?\*\//g, '').matchAll(/@import\s+(?:url\(\s*['"]?([^'")\s]+)['"]?\s*\)|['"]([^'"]+)['"])/gi)) {
|
|
190
|
+
add(cssRel(root, key, m[1] || m[2]))
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
return [...sources.values(), css, ...[...screens.values()].flatMap((sc) => [...sc.styles, ...sc.inlineStyles])]
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function fontSizes(css) {
|
|
198
|
+
const vars = new Map()
|
|
199
|
+
const used = []
|
|
200
|
+
for (const text of css) {
|
|
201
|
+
for (const [, prop, value] of text.replace(/\/\*[\s\S]*?\*\//g, '').matchAll(/(?:^|[;{])\s*(font-size|font|--[\w-]+)\s*:\s*([^;{}]+)/gim)) {
|
|
202
|
+
if (prop.startsWith('--')) {
|
|
203
|
+
const values = vars.get(prop) || []
|
|
204
|
+
values.push(value)
|
|
205
|
+
vars.set(prop, values)
|
|
206
|
+
if (/^--(?:(?:font|text|type)-size(?:-|$)|(?:font|text)-(?:xs|sm|base|md|lg|xl|[2-9]xl)(?:-|$)|fs-)/i.test(prop)) used.push(value)
|
|
207
|
+
} else if (prop.toLowerCase() === 'font-size') used.push(value)
|
|
208
|
+
else {
|
|
209
|
+
// 简写只拿字号,跳过斜杠后面的行高。
|
|
210
|
+
const size = /\b(?:\d*\.)?\d+(?:px|rem)\b|var\([^)]*\)/i.exec(value.split('/')[0])
|
|
211
|
+
if (size) used.push(size[0])
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
const sizes = new Set()
|
|
216
|
+
const seen = new Set()
|
|
217
|
+
for (const value of used) {
|
|
218
|
+
for (const m of value.matchAll(/var\(\s*(--[\w-]+)|(?<![\w.-])(\d*\.?\d+)\s*(px|rem)\b/gi)) {
|
|
219
|
+
if (m[1]) {
|
|
220
|
+
if (!seen.has(m[1])) used.push(...(vars.get(m[1]) || []))
|
|
221
|
+
seen.add(m[1])
|
|
222
|
+
} else {
|
|
223
|
+
const size = Math.round(Number(m[2]) * (m[3].toLowerCase() === 'rem' ? 16 : 1))
|
|
224
|
+
if (Number.isSafeInteger(size) && size > 0) sizes.add(size)
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
return [...sizes].sort((a, b) => a - b)
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** 静态收集所有屏和原型数据里的字形、字号。遍历 Unicode 码点,保留扩展汉字和非 ASCII 标点。 */
|
|
232
|
+
export function collectEmbeddedFonts(htmlByKey, { root = '', css = '', mockData } = {}) {
|
|
233
|
+
const screens = new Map([...htmlByKey].map(([key, html]) => [key, scanScreen(html)]))
|
|
234
|
+
const chars = new Set()
|
|
235
|
+
const add = (value) => { for (const char of value) if (!/[\p{Cc}\p{Cs}\u200B\uFEFF]/u.test(char)) chars.add(char) }
|
|
236
|
+
for (const screen of screens.values()) for (const value of screen.texts) add(value)
|
|
237
|
+
const pending = [mockData]
|
|
238
|
+
while (pending.length) {
|
|
239
|
+
const value = pending.pop()
|
|
240
|
+
if (typeof value === 'string') add(value)
|
|
241
|
+
else if (value && typeof value === 'object') for (const child of Object.values(value)) pending.push(child)
|
|
242
|
+
}
|
|
243
|
+
const sources = cssSources(root, screens, css)
|
|
244
|
+
// 样式里 ::before / ::after 写的字(content:"℃"、"\2103"):正文里没有也要进字库
|
|
245
|
+
for (const src of sources) {
|
|
246
|
+
for (const [, v] of String(src || '').replace(/\/\*[\s\S]*?\*\//g, '').matchAll(/(?:^|[;{\s])content\s*:\s*([^;{}]+)/gi)) {
|
|
247
|
+
for (const m of v.matchAll(/"((?:[^"\\]|\\[\s\S])*)"|'((?:[^'\\]|\\[\s\S])*)'/g)) {
|
|
248
|
+
add((m[1] ?? m[2]).replace(/\\([0-9a-fA-F]{1,6})\s?|\\([\s\S])/g, (_x, hex, ch) => {
|
|
249
|
+
if (!hex) return ch === '\n' ? '' : ch
|
|
250
|
+
const cp = parseInt(hex, 16)
|
|
251
|
+
return cp > 0 && cp <= 0x10FFFF && (cp < 0xD800 || cp > 0xDFFF) ? String.fromCodePoint(cp) : ''
|
|
252
|
+
}))
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
const characters = [...chars].sort((a, b) => a.codePointAt(0) - b.codePointAt(0)).join('')
|
|
257
|
+
const sizes = fontSizes(sources)
|
|
258
|
+
const { weights, pairs } = fontWeights(sources)
|
|
259
|
+
// <b> <strong> <h1>–<h6> <th> 浏览器默认是粗体
|
|
260
|
+
if ([...screens.values()].some((sc) => sc.tags.some((t) => /^(b|strong|h[1-6]|th)$/.test(t.name)))) weights.add(700)
|
|
261
|
+
// data-var:会变的值(温度、时间、计数),转代码时留成变量
|
|
262
|
+
const vars = [...new Set([...screens.values()].flatMap((sc) => sc.tags.map((t) => t.attrs.get('data-var')).filter(Boolean)))]
|
|
263
|
+
return { characters, sizes, weights: [...weights].sort((a, b) => a - b), pairs, vars }
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** 用到的字重(400 总在)和同一条规则里写在一起的「字号 × 字重」(非常规字重的) */
|
|
267
|
+
function fontWeights(css) {
|
|
268
|
+
// 行内 style="…" 只有声明、没有花括号:包一层当一条规则
|
|
269
|
+
const text = css.map((t) => { const x = String(t || '').replace(/\/\*[\s\S]*?\*\//g, ''); return /[{}]/.test(x) ? x : '{' + x + '}' }).join('\n')
|
|
270
|
+
const vars = new Map()
|
|
271
|
+
for (const [, k, v] of text.matchAll(/(--[\w-]+)\s*:\s*([^;{}]+)/g)) if (!vars.has(k)) vars.set(k, v.trim())
|
|
272
|
+
const res = (v, d = 0) => { const m = /^var\(\s*(--[\w-]+)\s*(?:,\s*([^)]+))?\)$/.exec(String(v).trim()); return m && d < 6 ? res(vars.get(m[1]) ?? m[2] ?? '', d + 1) : String(v).trim() }
|
|
273
|
+
const W = (v) => { const x = res(v).toLowerCase(); return x === 'bold' || x === 'bolder' ? 700 : x === 'normal' ? 400 : /^[1-9]00$/.test(x) ? Number(x) : 0 }
|
|
274
|
+
const S = (v) => { const m = /^(\d*\.?\d+)(px|rem)$/i.exec(res(v)); return m ? Math.round(Number(m[1]) * (m[2].toLowerCase() === 'rem' ? 16 : 1)) : 0 }
|
|
275
|
+
const weights = new Set([400])
|
|
276
|
+
const pairs = new Map()
|
|
277
|
+
for (const [, body] of text.matchAll(/\{([^{}]*)\}/g)) {
|
|
278
|
+
let w = 0
|
|
279
|
+
let sz = 0
|
|
280
|
+
for (const [, p, v] of body.matchAll(/(?:^|;)\s*(font-weight|font-size|font)\s*:\s*([^;]+)/gi)) {
|
|
281
|
+
const prop = p.toLowerCase()
|
|
282
|
+
if (prop === 'font-weight') w = W(v) || w
|
|
283
|
+
else if (prop === 'font-size') sz = S(v) || sz
|
|
284
|
+
else for (const x of res(v).split('/')[0].trim().split(/\s+/)) { if (!w && W(x)) w = W(x); if (!sz && S(x)) sz = S(x) }
|
|
285
|
+
}
|
|
286
|
+
if (w) weights.add(w)
|
|
287
|
+
if (w && w !== 400 && sz) pairs.set(sz + 'x' + w, [sz, w])
|
|
288
|
+
}
|
|
289
|
+
return { weights, pairs: [...pairs.values()].sort((a, b) => a[0] - b[0] || a[1] - b[1]) }
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
const shellArg = (s) => "'" + s.replace(/'/g, "'\\''") + "'"
|
|
293
|
+
const FONT_EXT = /\.(ttf|otf|woff2?)$/i
|
|
294
|
+
|
|
295
|
+
let fontIndex
|
|
296
|
+
/** 字体库(dsh-fonts/<id>.woff2)里的哪一款:带 lang(zh / latin)、weights([最细, 最粗] 是可变字体) */
|
|
297
|
+
function libFont(file) {
|
|
298
|
+
if (path.basename(path.dirname(file)) !== FONT_DIR) return null
|
|
299
|
+
if (fontIndex === undefined) fontIndex = loadFontIndex()
|
|
300
|
+
const id = /^([a-z0-9-]+)\.woff2$/.exec(path.basename(file))?.[1]
|
|
301
|
+
return (id && fontIndex?.fonts.find((f) => f.id === id)) || null
|
|
302
|
+
}
|
|
303
|
+
// 不是字体库里的:看文件名像不像中文字体
|
|
304
|
+
const CJK_NAME = /(?:^|[-_ ])(?:sc|tc|cjk|hans|hant|zh|cn|chinese)(?:[-_ .]|$)|source-?han|noto-?(?:sans|serif)-?(?:sc|tc|cjk)|hei|song|kai|alibaba|harmony|misans|pingfang|yahei/i
|
|
305
|
+
const cjkFont = (file) => { const f = libFont(file); return f ? f.lang === 'zh' : CJK_NAME.test(path.basename(file)) }
|
|
306
|
+
|
|
307
|
+
/** 设计里的字体文件:main 拿来转全部字(有中文时挑中文字体),others 是另外几款(数字字体之类) */
|
|
308
|
+
function designFonts(root, cjk = true) {
|
|
309
|
+
const all = []
|
|
310
|
+
for (const folder of ['fonts', FONT_DIR]) for (const e of entries(path.join(root, folder))) if (e.isFile() && FONT_EXT.test(e.name)) all.push(path.resolve(root, folder, e.name))
|
|
311
|
+
const main = (cjk && all.find(cjkFont)) || all[0] || ''
|
|
312
|
+
return { main, others: all.filter((f) => f !== main) }
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* 字体文件 → 转换工具(lv_font_conv)和 Qt 都认的静态 TTF。实测:lv_font_conv 读不了 WOFF2;
|
|
317
|
+
* 字体库的可变字体默认是最细那档(思源黑体是 100),直接转字会变细——按设计用到的字重各切一份。
|
|
318
|
+
* 中间文件放 tmp,最终的静态 TTF 放 out(LVGL 两个都是 _src/,只拿去转字库;QML 的 out 就是要打包的目录)。
|
|
319
|
+
* @returns { cmds, files: Map(字重 → TTF 路径), prepared }(prepared:有没有要先跑的 fonttools 命令)
|
|
320
|
+
*/
|
|
321
|
+
function fontPrep(font, weights, tmp, out = tmp) {
|
|
322
|
+
const files = new Map()
|
|
323
|
+
const variable = Array.isArray(libFont(font)?.weights)
|
|
324
|
+
const web = /\.woff2?$/i.test(font)
|
|
325
|
+
if (!font || (!variable && !web)) { for (const w of weights) files.set(w, font); return { cmds: [], files, prepared: false } }
|
|
326
|
+
// 输出文件名自己起:只留字母数字(字体文件名里的空格、$()、引号不进命令)
|
|
327
|
+
const stem = path.basename(font).replace(/\.[^.]+$/, '').replace(/[^\w.-]+/g, '_').replace(/^[-.]+/, '') || 'font'
|
|
328
|
+
const src = (variable ? tmp : out) + '/' + stem + '.ttf'
|
|
329
|
+
const cmds = ['# 没有 fonttools 时先装:pip install fonttools brotli', 'mkdir -p ' + [...new Set([tmp, out])].join(' ')]
|
|
330
|
+
cmds.push(/\.woff2$/i.test(font) ? 'fonttools ttLib.woff2 decompress ' + shellArg(font) + ' -o ' + src
|
|
331
|
+
: 'python3 -c "import sys; from fontTools.ttLib import TTFont; f = TTFont(sys.argv[1]); f.flavor = None; f.save(sys.argv[2])" ' + shellArg(font) + ' ' + src)
|
|
332
|
+
if (!variable) { for (const w of weights) files.set(w, src); return { cmds, files, prepared: true } }
|
|
333
|
+
const [lo, hi] = libFont(font).weights
|
|
334
|
+
for (const w of weights) {
|
|
335
|
+
const file = out + '/' + stem + '-' + w + '.ttf'
|
|
336
|
+
// --static:别的轴(字号光学尺寸之类)也定在默认值;--update-name-table:字体名改成「… Bold」,Qt 按字重认得出
|
|
337
|
+
cmds.push('fonttools varLib.instancer ' + src + ' wght=' + Math.min(hi, Math.max(lo, w)) + ' --static --update-name-table -o ' + file)
|
|
338
|
+
files.set(w, file)
|
|
339
|
+
}
|
|
340
|
+
return { cmds, files, prepared: true }
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
function fontMd(root, htmlByKey, mockData, rows) {
|
|
344
|
+
const { characters, sizes, weights, pairs } = collectEmbeddedFonts(htmlByKey, { root, mockData })
|
|
345
|
+
// ASCII 另用 --range;重复字形会让旧版转换工具报错。
|
|
346
|
+
const symbols = [...characters].filter((c) => !/^[\x20-\x7E]$/.test(c)).join('')
|
|
347
|
+
const glyphCount = 95 + [...symbols].length
|
|
348
|
+
const { main: font, others } = designFonts(root, !!symbols)
|
|
349
|
+
// 字号 × 字重:优先用浏览器按设计尺寸量出来的;量不到才静态扫样式表(每个字号一份常规体 + 同一条规则里写了的粗体)
|
|
350
|
+
const seen = renderedFonts(rows, libFont(font)?.family)
|
|
351
|
+
const px = sizes.length ? sizes : [16]
|
|
352
|
+
const bold = seen ? [] : pairs.filter(([n, w]) => w !== 400 && px.includes(n))
|
|
353
|
+
const unpaired = seen ? [] : weights.filter((w) => w !== 400 && !bold.some(([, x]) => x === w))
|
|
354
|
+
const combos = seen || [...px.map((n) => [n, 400]), ...bold]
|
|
355
|
+
const missed = seen ? sizes.filter((n) => !rows.some((r) => r.fonts.some((x) => x[0] === n))) : []
|
|
356
|
+
const used = [...new Set(combos.map(([n]) => n))]
|
|
357
|
+
const prep = fontPrep(font, [...new Set(combos.map(([, w]) => w))], 'ui/assets/fonts/_src')
|
|
358
|
+
const fontOf = (w) => shellArg(prep.files.get(w) || font || '把这里换成用户确认的字体.ttf')
|
|
359
|
+
const estimates = combos.map(([n]) => 0.38 * n * n * glyphCount)
|
|
360
|
+
const total = estimates.reduce((sum, n) => sum + n, 0)
|
|
361
|
+
const kb = (n) => (n / 1024).toFixed(1)
|
|
362
|
+
const conv = (n, w) => 'npx lv_font_conv --no-compress --format lvgl --bpp 4 --size ' + n + ' --font ' + fontOf(w) + ' --range 0x20-0x7E' +
|
|
363
|
+
(symbols ? ' --symbols ' + shellArg(symbols) : '') + ' -o ui/assets/fonts/ui_font_' + n + (w === 400 ? '' : '_w' + w) + '.c'
|
|
364
|
+
// 字形可能含反引号,围栏要比参数里最长的一串反引号更长。
|
|
365
|
+
const commands = [...prep.cmds, 'mkdir -p ui/assets/fonts', ...combos.map(([n, w]) => conv(n, w))]
|
|
366
|
+
const fence = '`'.repeat(Math.max(3, 1 + Math.max(0, ...(commands.join('\n').match(/`+/g) || []).map((v) => v.length))))
|
|
367
|
+
return [
|
|
368
|
+
'### LVGL 字库', '',
|
|
369
|
+
'- 字形由设计台从全部屏和 mock 字符串取并集。每档预计 ' + glyphCount + ' 个字形(含 95 个可打印 ASCII)。' + (seen
|
|
370
|
+
? '字号和字重是在浏览器里按设计尺寸实际量出来的(`<b>` 套在粗体里会变得更粗这类也算进去了),每种组合转一份(文件名带 `_w<字重>` 的是非常规字重)。'
|
|
371
|
+
: '字号是静态扫描(rem 按 16px),请对照实际样式和行内手调值复核。' + (sizes.length ? '' : ' 没扫到明确字号,暂列默认 16px。')),
|
|
372
|
+
'- Flash 粗估按未压缩 4bpp 的 `0.38 × 字号² × 字形数` 计算。' + combos.map(([n, w]) => n + 'px' + (w === 400 ? '' : ' 字重 ' + w)).map((x, i) => x + ' ≈ ' + kb(estimates[i]) + ' KB').join(',') + ',合计 ≈ ' + kb(total) + ' KB。',
|
|
373
|
+
...(total > 512 * 1024 ? ['- **字库预估超过 512 KB。** 先和用户确认 Flash 余量,优先精简字号,再评估外置 Flash。'] : []),
|
|
374
|
+
...(used.length > 4 ? ['- **字号超过 4 档。** 和用户确认可合并的字号,减少字库体积。'] : []),
|
|
375
|
+
font ? '- 命令里用的是设计里的字体 `' + path.basename(font) + '`,先核对它覆盖所有字形并可随项目分发。' + (prep.prepared ? '转换工具只认 TTF / OTF:开头几条先用 fonttools 把它转成 TTF' + (Array.isArray(libFont(font)?.weights) ? ',再按用到的字重各切一份(这是可变字体,不切的话默认是最细的一档)' : '') + ';`_src/` 里是中间文件,不用编进固件。' : '')
|
|
376
|
+
: '- 先问用户用哪款字体文件(TTF / OTF);没有指定时可建议开放授权的 Noto Sans SC。把下面的字体路径换成确认的文件。',
|
|
377
|
+
...(missed.length ? ['- 样式表里还写了 ' + missed.map((n) => n + 'px').join('、') + ',可在浏览器里按设计尺寸打开各屏、各状态都没看到(多半是点了才出现的弹窗、提示,或者没用上的样式):真用到的照下面的命令补转一份(字重照那几处的样式)。'] : []),
|
|
378
|
+
...(bold.length ? ['- 粗体按样式里写在一起的字号各转一份(文件名带 `_w<字重>`),用在那几处控件上。'] : []),
|
|
379
|
+
...(unpaired.length ? ['- 设计里还用了字重 ' + unpaired.join(' / ') + '(粗体标题、`<b>` 之类),没扫出用在哪个字号:照样式找到那几处的字号,' + (Array.isArray(libFont(font)?.weights) ? '用 `fonttools varLib.instancer` 切出那档字重,' : '') + '照上面的命令补转。'] : []),
|
|
380
|
+
...(others.length ? ['- 设计里还放了 ' + others.map((f) => '`' + path.basename(f) + '`').join('、') + ':上面的命令只用 `' + path.basename(font) + '`。用到那几款的地方(多半是大号数字)照样各转一份,只收用到的字(如 `--symbols ' + shellArg('0123456789.:-%°') + '`、字号照那几处的样式),再在对应控件上换成那份字库。'] : []),
|
|
381
|
+
'- 在目标目录用 POSIX Shell 运行下列命令。保留 `--no-compress`;转换器默认压缩,目标工程没开 `LV_USE_FONT_COMPRESSED 1` 时文字会空白。',
|
|
382
|
+
'', fence + 'sh', ...commands, fence, '',
|
|
383
|
+
'- 字库文件加入构建,用 `LV_FONT_DECLARE` 声明后按字号应用到全局样式。任意输入、设备返回的任意中文需要单独确认运行时字库、回退字体和存储方案。', '',
|
|
384
|
+
]
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/* 图标导出(页面里那一半):把每屏显示出来的图标(<svg> 里 <use> 引用的、64px 以内的内联 SVG、<img>)按显示尺寸画到画布上,
|
|
388
|
+
* 拿到真实像素。单色的(所有不透明点同一个颜色)给透明度(A8)+ 颜色,LVGL 转成只带透明度的数组、运行时着色;彩色的只给 PNG。
|
|
389
|
+
* 大的内联 SVG 多半是图表、进度环,不导。装好 window.__dshIcons,由 exportEmbeddedIcons 一个状态一个状态地扫、截图核对 */
|
|
390
|
+
export const ICON_SETUP = `(() => {
|
|
391
|
+
const MAX = 1024
|
|
392
|
+
const TH = 64
|
|
393
|
+
const MEAN_TH = 12
|
|
394
|
+
const NS = 'http://www.w3.org/2000/svg'
|
|
395
|
+
const texts = new Map()
|
|
396
|
+
const text = (u) => { if (!texts.has(u)) texts.set(u, fetch(u).then((r) => (r.ok ? r.text() : '')).catch(() => '')); return texts.get(u) }
|
|
397
|
+
const PROPS = ['fill', 'fill-opacity', 'fill-rule', 'clip-rule', 'stroke', 'stroke-width', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-opacity', 'color',
|
|
398
|
+
'stop-color', 'stop-opacity', 'flood-color', 'flood-opacity', 'lighting-color', 'marker-start', 'marker-mid', 'marker-end', 'paint-order', 'vector-effect', 'shape-rendering']
|
|
399
|
+
const EFFECTS = ['opacity', 'clip-path', 'mask', 'filter', 'mix-blend-mode', 'display', 'visibility']
|
|
400
|
+
// 克隆出来的 SVG 脱离了页面的样式表:原来写在元素上的样式留着,后面再补上算好的、影响画法的样式。
|
|
401
|
+
// 外层 svg 自己的透明度、旋转在画布上做(见 place);它自己的裁剪、滤镜不复制,画出来和页面对不上就进「没导成」(见 verify)
|
|
402
|
+
const XF = ['transform', 'transform-origin', 'transform-box']
|
|
403
|
+
const styleOf = (el, root) => {
|
|
404
|
+
const st = getComputedStyle(el)
|
|
405
|
+
const list = PROPS.concat(root ? [] : EFFECTS, !root && st.transform && st.transform !== 'none' ? XF : [])
|
|
406
|
+
const own = root ? '' : (el.getAttribute('style') || '').trim()
|
|
407
|
+
return (own ? own.replace(/;?$/, ';') : '') + list.map((p) => p + ':' + st.getPropertyValue(p)).join(';')
|
|
408
|
+
}
|
|
409
|
+
const load = (src) => new Promise((ok, no) => { const im = new Image(); im.onload = () => ok(im); im.onerror = () => no(new Error('load')); im.src = src })
|
|
410
|
+
const nameOf = (x) => String(x || '').replace(/\\.[a-z0-9]+$/i, '').replace(/[^A-Za-z0-9]+/g, '_').replace(/^_+|_+$/g, '').toLowerCase().slice(0, 40)
|
|
411
|
+
const svgText = async (svg, w, h) => {
|
|
412
|
+
const clone = svg.cloneNode(true)
|
|
413
|
+
const from = [svg, ...svg.querySelectorAll('*')]
|
|
414
|
+
const to = [clone, ...clone.querySelectorAll('*')]
|
|
415
|
+
from.forEach((e, i) => { if (to[i]) to[i].setAttribute('style', styleOf(e, i === 0)) })
|
|
416
|
+
let defs = clone.querySelector('defs')
|
|
417
|
+
if (!defs) { defs = document.createElementNS(NS, 'defs'); clone.prepend(defs) }
|
|
418
|
+
// 从页面里搬过来的 symbol、渐变:页面样式表里管到它们的规则也带上(.red { fill: red } 这种)
|
|
419
|
+
const pageCss = new Set()
|
|
420
|
+
const addPageRules = (node) => {
|
|
421
|
+
const els = [node, ...node.querySelectorAll('*')]
|
|
422
|
+
for (const sh of document.styleSheets) {
|
|
423
|
+
let rules = []
|
|
424
|
+
try { rules = sh.cssRules } catch { continue }
|
|
425
|
+
for (const r of rules) {
|
|
426
|
+
if (!r.selectorText || pageCss.has(r.cssText)) continue
|
|
427
|
+
try { if (els.some((e) => e.matches(r.selectorText))) pageCss.add(r.cssText) } catch { /* 写不出的选择器 */ }
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
// symbol 里用 url(#渐变) / href="#…" 引用的渐变、蒙版、裁剪、滤镜也要一起带上(连环引用的也带)
|
|
432
|
+
const addDeps = (src, node) => {
|
|
433
|
+
const queue = [node]
|
|
434
|
+
while (queue.length) {
|
|
435
|
+
const n = queue.shift()
|
|
436
|
+
const refs = new Set()
|
|
437
|
+
for (const e of [n, ...n.querySelectorAll('*')]) for (const a of e.attributes) {
|
|
438
|
+
for (const m of a.value.matchAll(/url\\(\\s*['"]?#([^'")\\s]+)['"]?\\s*\\)/g)) refs.add(m[1])
|
|
439
|
+
if ((a.name === 'href' || a.name === 'xlink:href') && a.value.startsWith('#')) refs.add(a.value.slice(1))
|
|
440
|
+
}
|
|
441
|
+
for (const r of refs) {
|
|
442
|
+
if (defs.querySelector('[id="' + CSS.escape(r) + '"]')) continue
|
|
443
|
+
const dep = src.getElementById(r)
|
|
444
|
+
if (!dep) continue
|
|
445
|
+
defs.append(document.importNode(dep, true))
|
|
446
|
+
if (src === document && !svg.contains(dep)) addPageRules(dep)
|
|
447
|
+
queue.push(dep)
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
let name = ''
|
|
452
|
+
for (const u of to.filter((e) => e.localName === 'use')) {
|
|
453
|
+
const href = u.getAttribute('href') || u.getAttribute('xlink:href') || ''
|
|
454
|
+
let abs
|
|
455
|
+
try { abs = new URL(href, location.href) } catch { return null }
|
|
456
|
+
const id = decodeURIComponent(abs.hash.slice(1))
|
|
457
|
+
if (!id) return null
|
|
458
|
+
name = name || id
|
|
459
|
+
const file = abs.href.split('#')[0]
|
|
460
|
+
let sym = null, src = document
|
|
461
|
+
if (file === location.href.split('#')[0]) sym = document.getElementById(id)
|
|
462
|
+
else {
|
|
463
|
+
src = new DOMParser().parseFromString(await text(file), 'image/svg+xml')
|
|
464
|
+
sym = src.getElementById(id)
|
|
465
|
+
for (const st of src.querySelectorAll('style')) defs.append(document.importNode(st, true))
|
|
466
|
+
}
|
|
467
|
+
if (!sym) return null
|
|
468
|
+
if (!defs.querySelector('[id="' + CSS.escape(id) + '"]')) defs.append(document.importNode(sym, true))
|
|
469
|
+
if (src === document) addPageRules(sym)
|
|
470
|
+
addDeps(src, sym)
|
|
471
|
+
u.removeAttribute('xlink:href')
|
|
472
|
+
u.setAttribute('href', '#' + id)
|
|
473
|
+
}
|
|
474
|
+
addDeps(document, svg)
|
|
475
|
+
addDeps(document, clone) // 样式表里写的 clip-path: url(#…) 之类,算好的样式里才看得到
|
|
476
|
+
if (pageCss.size) { const css = document.createElementNS(NS, 'style'); css.textContent = [...pageCss].join('\\n'); defs.prepend(css) }
|
|
477
|
+
clone.setAttribute('xmlns', NS)
|
|
478
|
+
clone.setAttribute('width', w)
|
|
479
|
+
clone.setAttribute('height', h)
|
|
480
|
+
return { svg: new XMLSerializer().serializeToString(clone), name }
|
|
481
|
+
}
|
|
482
|
+
const pixels = async (draw, w, h) => {
|
|
483
|
+
const c = document.createElement('canvas')
|
|
484
|
+
c.width = w; c.height = h
|
|
485
|
+
const g = c.getContext('2d')
|
|
486
|
+
await draw(g)
|
|
487
|
+
return { c, d: g.getImageData(0, 0, w, h).data }
|
|
488
|
+
}
|
|
489
|
+
const colorHints = (el) => {
|
|
490
|
+
const out = []
|
|
491
|
+
for (const n of [el, ...el.querySelectorAll('*')].slice(0, 64)) {
|
|
492
|
+
const st = getComputedStyle(n)
|
|
493
|
+
for (const p of ['color', 'fill', 'stroke']) {
|
|
494
|
+
const m = /^rgba?\\((\\d+),\\s*(\\d+),\\s*(\\d+)/.exec(st.getPropertyValue(p))
|
|
495
|
+
if (m) out.push([+m[1], +m[2], +m[3]])
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
return out
|
|
499
|
+
}
|
|
500
|
+
const classify = (d, hints) => {
|
|
501
|
+
// 基准色:实心像素里最多的那个(就是设计里写的色值);细线图标一个实心像素都没有,就拿最不透明的那个点
|
|
502
|
+
const freq = new Map()
|
|
503
|
+
let top = 0, best = -1, maxA = 0, maxAt = -1
|
|
504
|
+
for (let i = 0; i < d.length; i += 4) {
|
|
505
|
+
if (d[i + 3] > maxA) { maxA = d[i + 3]; maxAt = i }
|
|
506
|
+
if (d[i + 3] !== 255) continue
|
|
507
|
+
const k = (d[i] << 16) | (d[i + 1] << 8) | d[i + 2], c = (freq.get(k) || 0) + 1
|
|
508
|
+
freq.set(k, c)
|
|
509
|
+
if (c > top) { top = c; best = k }
|
|
510
|
+
}
|
|
511
|
+
if (maxA < 32) return null
|
|
512
|
+
const ref = best >= 0 ? [best >> 16, (best >> 8) & 255, best & 255] : [d[maxAt], d[maxAt + 1], d[maxAt + 2]]
|
|
513
|
+
// 单色:每个看得见的点都和基准色一样,只容得下半透明边缘换算回来的舍入误差(越透明误差越大)。
|
|
514
|
+
// 两种颜色拼的(哪怕只差几十)一律算彩色、只给 PNG,免得着色成一种颜色
|
|
515
|
+
let mono = true
|
|
516
|
+
for (let i = 0; i < d.length && mono; i += 4) {
|
|
517
|
+
const a = d[i + 3]
|
|
518
|
+
if (a < 16) continue // 整体很淡(opacity .2)的也要看颜色,不然双色的会被当成单色
|
|
519
|
+
const tol = 3 + Math.ceil(255 / a)
|
|
520
|
+
if (Math.abs(d[i] - ref[0]) > tol || Math.abs(d[i + 1] - ref[1]) > tol || Math.abs(d[i + 2] - ref[2]) > tol) mono = false
|
|
521
|
+
}
|
|
522
|
+
// 和元素上写的 color / fill / stroke 差几个数以内就用写的那个
|
|
523
|
+
let rgb = ref, near = 9
|
|
524
|
+
for (const c of hints) {
|
|
525
|
+
const dist = Math.max(...c.map((v, i) => Math.abs(v - ref[i])))
|
|
526
|
+
if (dist < near) { near = dist; rgb = c }
|
|
527
|
+
}
|
|
528
|
+
return { mono, color: '#' + rgb.map((v) => v.toString(16).padStart(2, '0')).join('') }
|
|
529
|
+
}
|
|
530
|
+
// 像素指纹:同名、同尺寸、同颜色但形状不同(几个都没起名的内联 SVG)要各导一份
|
|
531
|
+
const digest = (d) => { let h = 2166136261; for (let i = 0; i < d.length; i++) { h ^= d[i]; h = Math.imul(h, 16777619) } return (h >>> 0).toString(16) }
|
|
532
|
+
const labelOf = (el) => el.localName === 'img' ? nameOf(String(el.currentSrc || el.src).split(/[?#]/)[0].split('/').pop()) || 'image'
|
|
533
|
+
: nameOf(((el.querySelector('use') || el).getAttribute('href') || '').split('#').pop() || el.getAttribute('aria-label') || el.id || el.classList[0] || 'svg') || 'svg'
|
|
534
|
+
const out = []
|
|
535
|
+
const seen = new Set()
|
|
536
|
+
const missed = new Set()
|
|
537
|
+
const px = new Map()
|
|
538
|
+
const stats = []
|
|
539
|
+
const failed = new Set()
|
|
540
|
+
let occ = []
|
|
541
|
+
const scan = async () => {
|
|
542
|
+
occ = []
|
|
543
|
+
for (const el of document.querySelectorAll('body svg, body img')) {
|
|
544
|
+
if (el.localName === 'svg' && el.parentElement && el.parentElement.closest('svg')) continue
|
|
545
|
+
const st = getComputedStyle(el)
|
|
546
|
+
if (st.display === 'none' || st.visibility === 'hidden' || Number(st.opacity) === 0) continue
|
|
547
|
+
// 图标自己或外层带滤镜、混合模式、蒙版:插件画不出那个效果(变暗、变淡、渐隐),直接让模型自己处理
|
|
548
|
+
let fx = false
|
|
549
|
+
for (let p = el; p && !fx; p = p.parentElement) {
|
|
550
|
+
const ps = p === el ? st : getComputedStyle(p)
|
|
551
|
+
const mask = ps.maskImage || ps.webkitMaskImage
|
|
552
|
+
fx = (ps.filter && ps.filter !== 'none') || (ps.mixBlendMode && ps.mixBlendMode !== 'normal') || (p !== el && mask && mask !== 'none')
|
|
553
|
+
}
|
|
554
|
+
if (fx) {
|
|
555
|
+
const r = el.getBoundingClientRect()
|
|
556
|
+
if (r.width >= 2 && r.height >= 2) missed.add(labelOf(el) + ' ' + Math.round(r.width) + '×' + Math.round(r.height))
|
|
557
|
+
continue
|
|
558
|
+
}
|
|
559
|
+
const box = el.getBoundingClientRect()
|
|
560
|
+
const w = Math.round(box.width), h = Math.round(box.height)
|
|
561
|
+
if (w < 2 || h < 2 || w > MAX || h > MAX) continue
|
|
562
|
+
let item = null
|
|
563
|
+
// 元素自己转了、翻了(返回箭头常用 rotate(180deg)):按没转时的大小画,再在画布中心套同样的变换,落在屏幕上那个框里
|
|
564
|
+
const tf = st.transform && st.transform !== 'none' ? new DOMMatrix(st.transform) : null
|
|
565
|
+
const cw = tf ? Math.max(1, Math.round(parseFloat(st.width)) || w) : w, ch = tf ? Math.max(1, Math.round(parseFloat(st.height)) || h) : h
|
|
566
|
+
const op = Number(st.opacity)
|
|
567
|
+
const place = (g, draw) => {
|
|
568
|
+
if (op >= 0 && op < 1) g.globalAlpha = op // 元素自己半透明(淡化、禁用):导出来也是半透明
|
|
569
|
+
if (tf) { g.translate(w / 2, h / 2); g.transform(tf.a, tf.b, tf.c, tf.d, 0, 0); g.translate(-cw / 2, -ch / 2) }
|
|
570
|
+
return draw()
|
|
571
|
+
}
|
|
572
|
+
try {
|
|
573
|
+
if (el.localName === 'svg') {
|
|
574
|
+
if (!el.querySelector('use') && (w > 64 || h > 64)) continue
|
|
575
|
+
const t = await svgText(el, cw, ch)
|
|
576
|
+
if (!t) { missed.add(nameOf(((el.querySelector('use') || el).getAttribute('href') || '').split('#').pop() || el.classList[0] || 'svg') + ' ' + w + '×' + h); continue }
|
|
577
|
+
const url = URL.createObjectURL(new Blob([t.svg], { type: 'image/svg+xml' }))
|
|
578
|
+
try {
|
|
579
|
+
const im = await load(url)
|
|
580
|
+
item = { name: nameOf(t.name || el.getAttribute('aria-label') || el.id || el.classList[0] || 'icon'), ...(await pixels((g) => place(g, () => g.drawImage(im, 0, 0, cw, ch)), w, h)) }
|
|
581
|
+
} finally { URL.revokeObjectURL(url) }
|
|
582
|
+
} else {
|
|
583
|
+
if (!el.complete || !el.naturalWidth) { missed.add(nameOf(String(el.currentSrc || el.src).split(/[?#]/)[0].split('/').pop()) + ' ' + w + '×' + h); continue }
|
|
584
|
+
const iw = el.naturalWidth, ih = el.naturalHeight
|
|
585
|
+
const fit = st.objectFit
|
|
586
|
+
let dw = cw, dh = ch
|
|
587
|
+
if (fit === 'contain' || fit === 'cover') { const k = (fit === 'contain' ? Math.min : Math.max)(cw / iw, ch / ih); dw = iw * k; dh = ih * k }
|
|
588
|
+
else if (fit === 'none') { dw = iw; dh = ih }
|
|
589
|
+
item = { name: nameOf(String(el.currentSrc || el.src).split(/[?#]/)[0].split('/').pop() || 'image'), ...(await pixels((g) => place(g, () => g.drawImage(el, (cw - dw) / 2, (ch - dh) / 2, dw, dh)), w, h)) }
|
|
590
|
+
}
|
|
591
|
+
} catch { missed.add(labelOf(el) + ' ' + w + '×' + h); continue }
|
|
592
|
+
const kind = classify(item.d, colorHints(el))
|
|
593
|
+
// 看得见却画出来是空的(引用没跟过来之类):记进「没导成」,别悄悄漏掉
|
|
594
|
+
if (!kind) { missed.add((item.name || 'icon') + ' ' + w + '×' + h); continue }
|
|
595
|
+
const name = item.name || 'icon'
|
|
596
|
+
const key = name + '|' + w + 'x' + h + '|' + (kind.mono ? kind.color : 'color') + '|' + digest(item.d)
|
|
597
|
+
let ao = 1
|
|
598
|
+
for (let p = el.parentElement; p; p = p.parentElement) ao *= Number(getComputedStyle(p).opacity)
|
|
599
|
+
occ.push({ el, key, x: box.left, y: box.top, w, h, ao })
|
|
600
|
+
if (seen.has(key)) continue
|
|
601
|
+
seen.add(key)
|
|
602
|
+
// 核对时比的是最后真用的东西:单色的就是「透明度 × 那一个颜色」(LVGL 着色后的样子)
|
|
603
|
+
if (kind.mono) {
|
|
604
|
+
const m = new Uint8ClampedArray(item.d), v = parseInt(kind.color.slice(1), 16)
|
|
605
|
+
for (let i = 0; i < m.length; i += 4) { m[i] = v >> 16; m[i + 1] = (v >> 8) & 255; m[i + 2] = v & 255 }
|
|
606
|
+
px.set(key, m)
|
|
607
|
+
} else px.set(key, item.d)
|
|
608
|
+
let a = ''
|
|
609
|
+
if (kind.mono) { const bytes = new Uint8Array(w * h); for (let i = 0; i < bytes.length; i++) bytes[i] = item.d[i * 4 + 3]; let bin = ''; for (let i = 0; i < bytes.length; i += 8192) bin += String.fromCharCode.apply(null, bytes.subarray(i, i + 8192)); a = btoa(bin) }
|
|
610
|
+
out.push({ key, name, w, h, mono: kind.mono, color: kind.mono ? kind.color : '', a, png: item.c.toDataURL('image/png').split(',')[1] })
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
const de = document.documentElement
|
|
614
|
+
const meta = [...document.querySelectorAll('meta')].find((m) => (m.getAttribute('name') || '').toLowerCase() === 'dsh-states')
|
|
615
|
+
const names = meta ? (meta.getAttribute('content') || '').split(/[,,;;\\n]+/).map((p) => (/^\\s*([A-Za-z0-9_-]{1,32})/.exec(p) || [])[1]).filter(Boolean).slice(0, 8) : []
|
|
616
|
+
const was = de.getAttribute('data-state')
|
|
617
|
+
const frame = () => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(() => r())))
|
|
618
|
+
let style = null
|
|
619
|
+
window.__dshIcons = {
|
|
620
|
+
// 每屏写了几个状态的,各状态切过去都扫一遍(报警图标只在报警状态露面)
|
|
621
|
+
states: names.length >= 2 ? names.filter((n) => n !== was) : [],
|
|
622
|
+
scan: async (n) => { if (n != null) { de.setAttribute('data-state', n); await frame() } await scan(); return occ.length },
|
|
623
|
+
// 只留这一状态的图标、别的全藏、底色透明,好截一张「页面上真实显示的样子」
|
|
624
|
+
isolate: async (on) => {
|
|
625
|
+
if (on) {
|
|
626
|
+
for (const o of occ) o.el.setAttribute('data-dsh-icon-keep', '')
|
|
627
|
+
style = document.createElement('style')
|
|
628
|
+
// 裁切、蒙版这些定义藏起来就没了效果(截出来是空的):它们里面的东西保持可见(本来也不直接画)
|
|
629
|
+
style.textContent = 'html,body{background:transparent!important}:where(*:not([data-dsh-icon-keep]):not([data-dsh-icon-keep] *)){visibility:hidden!important}[data-dsh-icon-keep]{visibility:visible!important}' +
|
|
630
|
+
':is(defs,clipPath,mask,symbol,pattern,marker,linearGradient,radialGradient,filter) *{visibility:visible!important}*,*::before,*::after{transition:none!important}'
|
|
631
|
+
document.head.append(style)
|
|
632
|
+
await frame()
|
|
633
|
+
} else {
|
|
634
|
+
for (const o of occ) o.el.removeAttribute('data-dsh-icon-keep')
|
|
635
|
+
if (style) style.remove()
|
|
636
|
+
style = null
|
|
637
|
+
await frame()
|
|
638
|
+
}
|
|
639
|
+
},
|
|
640
|
+
// 导出的像素(乘上外层的透明度)对着截图逐点比,容得下 1 像素以内的错位;对不上的不导,进「没导成」
|
|
641
|
+
verify: async (b64) => {
|
|
642
|
+
const im = await load('data:image/png;base64,' + b64)
|
|
643
|
+
const k = im.naturalWidth / innerWidth
|
|
644
|
+
for (const o of occ) {
|
|
645
|
+
if (failed.has(o.key) || o.x < 0 || o.y < 0 || o.x + o.w > innerWidth || o.y + o.h > innerHeight) continue
|
|
646
|
+
const c = document.createElement('canvas')
|
|
647
|
+
c.width = o.w; c.height = o.h
|
|
648
|
+
const g = c.getContext('2d')
|
|
649
|
+
g.drawImage(im, o.x * k, o.y * k, o.w * k, o.h * k, 0, 0, o.w, o.h)
|
|
650
|
+
const C = g.getImageData(0, 0, o.w, o.h).data, R = px.get(o.key)
|
|
651
|
+
let bad = 0, ink = 0, top = 0
|
|
652
|
+
for (let i = 3; i < R.length; i += 4) top = Math.max(top, R[i] * o.ao)
|
|
653
|
+
// 颜色另算:只看两边都够不透明的点,比去掉透明度以后的颜色(边缘盖多盖少不影响,整体变暗、偏色就看得出)
|
|
654
|
+
const solid = Math.max(24, top / 2)
|
|
655
|
+
let tint = 0, tn = 0
|
|
656
|
+
for (let y = 0; y < o.h; y++) for (let x = 0; x < o.w; x++) {
|
|
657
|
+
const i = (y * o.w + x) * 4, ra = R[i + 3] / 255 * o.ao
|
|
658
|
+
if (ra * 255 > 8 || C[i + 3] > 8) ink++
|
|
659
|
+
let best = 1e9
|
|
660
|
+
for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) {
|
|
661
|
+
const yy = y + dy, xx = x + dx
|
|
662
|
+
if (yy < 0 || xx < 0 || yy >= o.h || xx >= o.w) continue
|
|
663
|
+
const j = (yy * o.w + xx) * 4, ca = C[j + 3] / 255
|
|
664
|
+
const d = Math.max(Math.abs(R[i] * ra - C[j] * ca), Math.abs(R[i + 1] * ra - C[j + 1] * ca), Math.abs(R[i + 2] * ra - C[j + 2] * ca), Math.abs(ra * 255 - C[j + 3]))
|
|
665
|
+
if (d < best) best = d
|
|
666
|
+
}
|
|
667
|
+
if (best > TH) bad++
|
|
668
|
+
if (ra * 255 >= solid) {
|
|
669
|
+
let cb = 1e9
|
|
670
|
+
for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) {
|
|
671
|
+
const yy = y + dy, xx = x + dx
|
|
672
|
+
if (yy < 0 || xx < 0 || yy >= o.h || xx >= o.w) continue
|
|
673
|
+
const j = (yy * o.w + xx) * 4
|
|
674
|
+
if (C[j + 3] < solid) continue
|
|
675
|
+
const d = Math.max(Math.abs(R[i] - C[j]), Math.abs(R[i + 1] - C[j + 1]), Math.abs(R[i + 2] - C[j + 2]))
|
|
676
|
+
if (d < cb) cb = d
|
|
677
|
+
}
|
|
678
|
+
if (cb < 1e9) { tint += cb; tn++ }
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
// 两条都要过:没有成片的错点;够不透明的点颜色整体也不能偏(变暗滤镜之类,每个点只差几十)
|
|
682
|
+
const mean = tn ? tint / tn : 0
|
|
683
|
+
stats.push({ key: o.key, bad, ink, tn, mean: Math.round(mean * 10) / 10 })
|
|
684
|
+
if (bad > Math.max(2, ink * 0.03) || (tn >= 3 && mean > MEAN_TH)) failed.add(o.key)
|
|
685
|
+
}
|
|
686
|
+
},
|
|
687
|
+
done: () => {
|
|
688
|
+
if (style) { for (const o of occ) o.el.removeAttribute('data-dsh-icon-keep'); style.remove() }
|
|
689
|
+
if (names.length >= 2) { if (was === null) de.removeAttribute('data-state'); else de.setAttribute('data-state', was) }
|
|
690
|
+
window.__dshIconStats = stats
|
|
691
|
+
delete window.__dshIcons
|
|
692
|
+
for (const it of out) if (failed.has(it.key)) missed.add(it.name + ' ' + it.w + '×' + it.h)
|
|
693
|
+
return { icons: out.filter((it) => !failed.has(it.key)).map(({ key, ...it }) => it), missed: [...missed].slice(0, 40) }
|
|
694
|
+
},
|
|
695
|
+
}
|
|
696
|
+
return window.__dshIcons.states
|
|
697
|
+
})()`
|
|
698
|
+
|
|
699
|
+
|
|
700
|
+
/** 图标导出:每个状态扫一遍 → 只留图标截一张透明底的图 → 画出来的和截图对不上的不导(进「没导成」),免得交出一张错图。
|
|
701
|
+
* 页面对象没有透明底截图(测试替身)就只扫不核对。返回 { icons, missed } */
|
|
702
|
+
export async function exportEmbeddedIcons(page) {
|
|
703
|
+
const states = await page.eval(ICON_SETUP)
|
|
704
|
+
try {
|
|
705
|
+
for (const n of [null, ...(Array.isArray(states) ? states : [])]) {
|
|
706
|
+
const count = await page.eval(`window.__dshIcons.scan(${JSON.stringify(n)})`)
|
|
707
|
+
if (!count || typeof page.background !== 'function') continue
|
|
708
|
+
let shot = null
|
|
709
|
+
await page.eval('window.__dshIcons.isolate(true)')
|
|
710
|
+
try {
|
|
711
|
+
await page.background(true)
|
|
712
|
+
shot = await page.shot({ format: 'png' })
|
|
713
|
+
} finally {
|
|
714
|
+
await page.background(false).catch(() => {})
|
|
715
|
+
await page.eval('window.__dshIcons.isolate(false)').catch(() => {})
|
|
716
|
+
}
|
|
717
|
+
await page.eval(`window.__dshIcons.verify(${JSON.stringify(shot.toString('base64'))})`)
|
|
718
|
+
}
|
|
719
|
+
return await page.eval('window.__dshIcons.done()')
|
|
720
|
+
} catch (e) {
|
|
721
|
+
await page.eval('window.__dshIcons && window.__dshIcons.done()').catch(() => {})
|
|
722
|
+
throw e
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
const ICON_RE = /^[a-z0-9_]{1,60}$/
|
|
727
|
+
|
|
728
|
+
/** LVGL 单色图标:只带透明度的 C 数组(8.x LV_IMG_CF_ALPHA_8BIT / 9.x LV_COLOR_FORMAT_A8),运行时用 recolor 着色 */
|
|
729
|
+
export function lvglA8Source(id, w, h, alpha, major) {
|
|
730
|
+
const rows = []
|
|
731
|
+
for (let y = 0; y < h; y++) rows.push(' ' + [...alpha.subarray(y * w, y * w + w)].map((v) => '0x' + v.toString(16).padStart(2, '0')).join(','))
|
|
732
|
+
const dsc = major === 8
|
|
733
|
+
? [`const lv_img_dsc_t ${id} = {`, ' .header.cf = LV_IMG_CF_ALPHA_8BIT,', ' .header.always_zero = 0,', ' .header.reserved = 0,', ` .header.w = ${w},`, ` .header.h = ${h},`, ` .data_size = sizeof(${id}_map),`, ` .data = ${id}_map,`, '};']
|
|
734
|
+
: [`const lv_image_dsc_t ${id} = {`, ` .header = { .magic = LV_IMAGE_HEADER_MAGIC, .cf = LV_COLOR_FORMAT_A8, .flags = 0, .w = ${w}, .h = ${h}, .stride = ${w} },`, ` .data_size = sizeof(${id}_map),`, ` .data = ${id}_map,`, '};']
|
|
735
|
+
return [
|
|
736
|
+
`/* 设计台导出:${w}×${h} 单色图标,只带透明度(A8),用的时候设 recolor 着色。LVGL ${major === 8 ? '8.x' : '9.x'} */`,
|
|
737
|
+
'#ifdef LV_LVGL_H_INCLUDE_SIMPLE', '#include "lvgl.h"', '#else', '#include "lvgl/lvgl.h"', '#endif',
|
|
738
|
+
'#ifndef LV_ATTRIBUTE_LARGE_CONST', '#define LV_ATTRIBUTE_LARGE_CONST', '#endif', '',
|
|
739
|
+
`static const LV_ATTRIBUTE_LARGE_CONST uint8_t ${id}_map[] = {`, rows.join(',\n') + ',', '};', '',
|
|
740
|
+
...dsc, '',
|
|
741
|
+
].join('\n')
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
/** 把刚量到的图标像素写成文件(handoff/icons/ 下的 PNG,LVGL 再写 lvgl/ 下的 C 数组),row.icons 换成只记文件名的清单 */
|
|
745
|
+
/** handoff/icons、handoff/icons/lvgl 得是真的文件夹(或者还没有):是软链接就可能写到、删到别处去,这时不导图标 */
|
|
746
|
+
export function embeddedIconDirOk(dir) {
|
|
747
|
+
for (const d of [path.join(dir, 'icons'), path.join(dir, 'icons', 'lvgl')]) {
|
|
748
|
+
const st = fs.lstatSync(d, { throwIfNoEntry: false })
|
|
749
|
+
if (st && !st.isDirectory()) return false
|
|
750
|
+
}
|
|
751
|
+
return true
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
const ICON_FILE_RE = /^[a-z0-9_]{1,60}_\d{1,4}x\d{1,4}(?:_\d+)?(?:_[0-9a-f]{6})?\.png$/
|
|
755
|
+
const ICON_C_RE = /^icon_[a-z0-9_]{1,60}_\d{1,4}x\d{1,4}(?:_\d+)?\.c$/
|
|
756
|
+
|
|
757
|
+
function writeIconFile(file, data) {
|
|
758
|
+
try { if (fs.lstatSync(file).isSymbolicLink()) fs.unlinkSync(file) } catch { /* 没有 */ }
|
|
759
|
+
fs.writeFileSync(file, data)
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
/** 刚量到的图标像素写成文件;row.icons 换成不带像素的清单。keep 是这次没重截、还在用的那些屏:
|
|
763
|
+
* 它们占着的文件名不动,这次同名不同样的另起 _2、_3,免得分批交接互相覆盖 */
|
|
764
|
+
export function writeEmbeddedIcons(dir, rows, { target, major = 9, keep = [] }) {
|
|
765
|
+
const iconDir = path.join(dir, 'icons')
|
|
766
|
+
const lvDir = path.join(iconDir, 'lvgl')
|
|
767
|
+
if (!embeddedIconDirOk(dir)) { for (const row of rows) row.icons = undefined; return }
|
|
768
|
+
const taken = new Map()
|
|
769
|
+
for (const r of keep) for (const it of Array.isArray(r?.icons) ? r.icons : []) if (it && it.stem) taken.set(it.stem, String(it.hash || ''))
|
|
770
|
+
for (const row of rows) {
|
|
771
|
+
const got = row.icons
|
|
772
|
+
if (!got || !Array.isArray(got.icons)) { row.icons = undefined; continue }
|
|
773
|
+
const list = []
|
|
774
|
+
for (const it of got.icons) {
|
|
775
|
+
const w = Math.round(Number(it && it.w)), h = Math.round(Number(it && it.h))
|
|
776
|
+
if (!it || !ICON_RE.test(String(it.name)) || !(w > 0 && w <= 1024 && h > 0 && h <= 1024) || typeof it.png !== 'string') continue
|
|
777
|
+
const alpha = it.mono ? Buffer.from(String(it.a || ''), 'base64') : null
|
|
778
|
+
if (it.mono && (alpha.length !== w * h || !/^#[0-9a-f]{6}$/.test(String(it.color)))) continue
|
|
779
|
+
const base = `${it.name}_${w}x${h}`
|
|
780
|
+
const hash = createHash('sha1').update(it.mono ? 'a8\0' : 'png\0').update(alpha || Buffer.from(it.png, 'base64')).digest('hex').slice(0, 10)
|
|
781
|
+
let stem = base
|
|
782
|
+
for (let i = 2; taken.has(stem) && taken.get(stem) !== hash; i++) stem = `${base}_${i}`
|
|
783
|
+
taken.set(stem, hash)
|
|
784
|
+
fs.mkdirSync(iconDir, { recursive: true })
|
|
785
|
+
const png = it.mono ? `${stem}_${it.color.slice(1)}.png` : `${stem}.png`
|
|
786
|
+
writeIconFile(path.join(iconDir, png), Buffer.from(it.png, 'base64'))
|
|
787
|
+
let c = ''
|
|
788
|
+
if (it.mono && target === 'lvgl') {
|
|
789
|
+
c = `icon_${stem}`
|
|
790
|
+
fs.mkdirSync(lvDir, { recursive: true })
|
|
791
|
+
writeIconFile(path.join(lvDir, c + '.c'), lvglA8Source(c, w, h, alpha, major))
|
|
792
|
+
}
|
|
793
|
+
list.push({ name: it.name, stem, hash, w, h, mono: !!it.mono, color: it.mono ? it.color : '', png, c })
|
|
794
|
+
}
|
|
795
|
+
row.icons = list
|
|
796
|
+
row.iconsMissed = Array.isArray(got.missed) ? got.missed.map((x) => String(x).slice(0, 60)).slice(0, 40) : []
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
/** 所有屏的图标清单定下来以后:LVGL 写 icons.h(声明全部图标),清掉不再用到的旧文件(只认插件自己起的文件名) */
|
|
801
|
+
export function finishEmbeddedIcons(dir, rows, { target, major = 9 }) {
|
|
802
|
+
if (!embeddedIconDirOk(dir)) return
|
|
803
|
+
const iconDir = path.join(dir, 'icons')
|
|
804
|
+
const lvDir = path.join(iconDir, 'lvgl')
|
|
805
|
+
const pngs = new Set(), cs = new Set()
|
|
806
|
+
for (const r of rows) for (const it of Array.isArray(r.icons) ? r.icons : []) { if (it.png) pngs.add(it.png); if (it.c) cs.add(it.c) }
|
|
807
|
+
if (target === 'lvgl' && cs.size) {
|
|
808
|
+
fs.mkdirSync(lvDir, { recursive: true })
|
|
809
|
+
const decl = major === 8 ? 'LV_IMG_DECLARE' : 'LV_IMAGE_DECLARE'
|
|
810
|
+
writeIconFile(path.join(lvDir, 'icons.h'), ['/* 设计台导出的单色图标(A8,用 recolor 着色) */', '#pragma once', '#ifdef LV_LVGL_H_INCLUDE_SIMPLE', '#include "lvgl.h"', '#else', '#include "lvgl/lvgl.h"', '#endif', '', ...[...cs].sort().map((c) => `${decl}(${c});`), ''].join('\n'))
|
|
811
|
+
}
|
|
812
|
+
const sweep = (d, keep, ours) => {
|
|
813
|
+
let names = []
|
|
814
|
+
try { names = fs.readdirSync(d, { withFileTypes: true }) } catch { return }
|
|
815
|
+
for (const f of names) if ((f.isFile() || f.isSymbolicLink()) && ours(f.name) && !keep.has(f.name)) fs.rmSync(path.join(d, f.name), { force: true })
|
|
816
|
+
}
|
|
817
|
+
sweep(iconDir, pngs, (n) => ICON_FILE_RE.test(n))
|
|
818
|
+
sweep(lvDir, new Set([...cs].map((c) => c + '.c').concat(target === 'lvgl' && cs.size ? ['icons.h'] : [])), (n) => n === 'icons.h' || ICON_C_RE.test(n))
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
/** 交接里图标那几行:导好了就列清单、说怎么用;有一屏没导(没截到、截图过期)返回 null,退回原来「自己转」的说法 */
|
|
822
|
+
export function embeddedIconsMd(rows, target, major = 9) {
|
|
823
|
+
if (!rows.length || rows.some((r) => r.stale || !Array.isArray(r.icons))) return null
|
|
824
|
+
const all = new Map()
|
|
825
|
+
for (const r of rows) for (const it of r.icons) {
|
|
826
|
+
const e = all.get(it.stem) || { ...it, colors: new Set(), pngs: new Set(), screens: new Set() }
|
|
827
|
+
if (it.color) e.colors.add(it.color)
|
|
828
|
+
e.pngs.add(it.png)
|
|
829
|
+
e.screens.add(r.key)
|
|
830
|
+
all.set(it.stem, e)
|
|
831
|
+
}
|
|
832
|
+
const list = [...all.values()].sort((a, b) => a.stem.localeCompare(b.stem))
|
|
833
|
+
const missed = [...new Set(rows.flatMap((r) => (Array.isArray(r.iconsMissed) ? r.iconsMissed : [])))]
|
|
834
|
+
if (!list.length) return { lines: [], mono: 0, color: 0, missed, done: new Set() }
|
|
835
|
+
const v8 = major === 8
|
|
836
|
+
const cell = (s) => String(s).replace(/\|/g, '\\|')
|
|
837
|
+
const lines = [
|
|
838
|
+
'### 图标(插件已经导好了)', '',
|
|
839
|
+
'图标都按设计里的显示尺寸画好了,放在 `handoff/icons/`:' + (target === 'lvgl'
|
|
840
|
+
? '单色的在 `handoff/icons/lvgl/` 里有现成的 C 数组(只带透明度,用的时候设颜色),连同 `icons.h` 拷进 `ui/assets/images/`;彩色的只有 PNG,用下面「LVGL 图片」的转换工具转。'
|
|
841
|
+
: 'PNG 按显示尺寸和颜色各导一张(同一个图标两种颜色就是两个文件),拷进 `qml/assets/images/`,用 `Image { source: "assets/images/文件名.png"; width: 宽; height: 高 }`,不用 SVG。'),
|
|
842
|
+
'**别自己再拆 `icons.svg`、别开浏览器转图**(DSH 的沙箱里浏览器起不来,改 HOME 再开还会弹系统的钥匙串窗口)。', '',
|
|
843
|
+
'| 图标 | 尺寸 | 颜色 | 哪几屏 | ' + (target === 'lvgl' ? 'C 数组 | PNG |' : '文件 |'),
|
|
844
|
+
target === 'lvgl' ? '|---|---|---|---|---|---|' : '|---|---|---|---|---|',
|
|
845
|
+
...list.map((e) => '| ' + cell(e.name) + ' | ' + e.w + '×' + e.h + ' | ' + (e.mono ? [...e.colors].join(' ') : '彩色') + ' | ' + cell([...e.screens].join('、')) + ' | ' +
|
|
846
|
+
(target === 'lvgl' ? (e.c ? '`' + e.c + '`' : '—') + ' | ' : '') + [...e.pngs].map((f) => '`' + cell(f) + '`').join(' ') + ' |'),
|
|
847
|
+
'',
|
|
848
|
+
...(missed.length ? ['这几个插件没画出来,要自己转(尺寸照写的):' + missed.map((m) => '`' + cell(m) + '`').join('、') + '。', ''] : []),
|
|
849
|
+
]
|
|
850
|
+
if (target === 'lvgl' && list.some((e) => e.c)) {
|
|
851
|
+
lines.push('单色图标这样用(颜色按上表;' + (v8 ? '8.x **一定要**设 `img_recolor_opa`,不设画出来是黑的' : '9.x 的 `lv_conf.h` 里 `LV_DRAW_SW_SUPPORT_A8` 要是 1(默认就是)') + '):', '', '```c',
|
|
852
|
+
'#include "assets/images/icons.h"',
|
|
853
|
+
v8 ? 'lv_obj_t * ic = lv_img_create(parent);' : 'lv_obj_t * ic = lv_image_create(parent);',
|
|
854
|
+
(v8 ? 'lv_img_set_src' : 'lv_image_set_src') + '(ic, &' + list.find((e) => e.c).c + ');',
|
|
855
|
+
'lv_obj_set_style_' + (v8 ? 'img' : 'image') + '_recolor(ic, lv_color_hex(0x' + (list.find((e) => e.c).color || '#000000').slice(1) + '), 0);',
|
|
856
|
+
'lv_obj_set_style_' + (v8 ? 'img' : 'image') + '_recolor_opa(ic, LV_OPA_COVER, 0);',
|
|
857
|
+
'```', '')
|
|
858
|
+
}
|
|
859
|
+
return { lines, mono: list.filter((e) => e.mono).length, color: list.filter((e) => !e.mono).length, missed, done: new Set(list.filter((e) => target !== 'lvgl' || e.c).map((e) => e.name + '|' + e.w + '×' + e.h)) }
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
/** 图片清单里去掉上面图标表已经导好的(名字和每个尺寸都对上才去掉;LVGL 只去掉有 C 数组的,彩色的还要自己转) */
|
|
863
|
+
function dropExported(lines, done) {
|
|
864
|
+
if (!done?.size) return lines
|
|
865
|
+
const nameOf = (x) => String(x || '').replace(/\.[a-z0-9]+$/i, '').replace(/[^A-Za-z0-9]+/g, '_').replace(/^_+|_+$/g, '').toLowerCase().slice(0, 40)
|
|
866
|
+
return lines.filter((line) => {
|
|
867
|
+
const m = /^- `([^`]*)` — (.*)$/.exec(line)
|
|
868
|
+
if (!m) return true
|
|
869
|
+
const ref = m[1].includes('#') ? m[1].split('#').pop() : m[1].split('?')[0].split('/').pop()
|
|
870
|
+
const sizes = [...m[2].matchAll(/(([^)]*))/g)].flatMap((x) => x[1].split(' / '))
|
|
871
|
+
return !(sizes.length && sizes.every((s) => done.has(nameOf(ref) + '|' + s)))
|
|
872
|
+
})
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
/** 用浏览器量实际显示大小,包含 CSS 布局和图片的原始宽高比。 */
|
|
876
|
+
export const embeddedImageSizes = `(() => {
|
|
877
|
+
const out = []
|
|
878
|
+
for (const el of document.querySelectorAll('*')) {
|
|
879
|
+
const s = getComputedStyle(el)
|
|
880
|
+
if (s.display === 'none' || s.visibility === 'hidden') continue
|
|
881
|
+
const srcs = []
|
|
882
|
+
const name = el.localName
|
|
883
|
+
if (name === 'img') srcs.push(el.currentSrc || el.getAttribute('src'))
|
|
884
|
+
if (name === 'use' || name === 'image') srcs.push(el.getAttribute('href') || el.getAttribute('xlink:href'))
|
|
885
|
+
for (const m of s.backgroundImage.matchAll(/url\\("([^"]+)"\\)/g)) srcs.push(m[1])
|
|
886
|
+
if (!srcs.length) continue
|
|
887
|
+
const box = (name === 'use' ? el.ownerSVGElement || el : el).getBoundingClientRect()
|
|
888
|
+
if (box.width > 0 && box.height > 0) for (const src of srcs) {
|
|
889
|
+
if (src && !/^(?:data|blob):/i.test(src)) out.push([src, Math.round(box.width), Math.round(box.height)])
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
return out
|
|
893
|
+
})()`
|
|
894
|
+
|
|
895
|
+
/** 浏览器里真实画出来的「字号 | 字重 | 第一个字体名」:<b> 套在粗体里会变成 900 这种,光扫样式表看不出来。
|
|
896
|
+
* 这屏写了几个状态(<meta name="dsh-states">)的,每个状态切过去各量一遍(报警弹窗之类只在别的状态里露面),量完切回来 */
|
|
897
|
+
export const embeddedTextFonts = `(() => {
|
|
898
|
+
const out = new Set()
|
|
899
|
+
const put = (s) => out.add(Math.round(parseFloat(s.fontSize)) + '|' + (parseInt(s.fontWeight, 10) || 400) + '|' + s.fontFamily.split(',')[0].replace(/["']/g, '').trim().toLowerCase())
|
|
900
|
+
const shown = (c) => c && c !== 'none' && c !== 'normal' && /[^\\s"']/.test(c)
|
|
901
|
+
const scan = () => { for (const el of document.querySelectorAll('body *')) {
|
|
902
|
+
const s = getComputedStyle(el)
|
|
903
|
+
if (s.display === 'none' || s.visibility === 'hidden') continue
|
|
904
|
+
const r = el.getBoundingClientRect()
|
|
905
|
+
if (!r.width || !r.height) continue
|
|
906
|
+
// 自己的字、输入框里的值 / 占位字、下拉框选中的那项、::before / ::after 里写的字(°C 这种)
|
|
907
|
+
if ([...el.childNodes].some((n) => n.nodeType === 3 && n.textContent.trim())) put(s)
|
|
908
|
+
if (/^(input|textarea)$/.test(el.localName)) {
|
|
909
|
+
if (el.value) put(s)
|
|
910
|
+
else if (el.placeholder) put(getComputedStyle(el, '::placeholder'))
|
|
911
|
+
}
|
|
912
|
+
if (el.localName === 'select' && el.selectedOptions && el.selectedOptions.length) put(s)
|
|
913
|
+
for (const pe of ['::before', '::after']) { const ps = getComputedStyle(el, pe); if (shown(ps.content)) put(ps) }
|
|
914
|
+
} }
|
|
915
|
+
scan()
|
|
916
|
+
const de = document.documentElement
|
|
917
|
+
const meta = [...document.querySelectorAll('meta')].find((m) => (m.getAttribute('name') || '').toLowerCase() === 'dsh-states')
|
|
918
|
+
const names = meta ? (meta.getAttribute('content') || '').split(/[,,;;\\n]+/).map((p) => (/^\\s*([A-Za-z0-9_-]{1,32})/.exec(p) || [])[1]).filter(Boolean).slice(0, 8) : []
|
|
919
|
+
if (names.length >= 2) {
|
|
920
|
+
const was = de.getAttribute('data-state')
|
|
921
|
+
for (const n of names) { if (n === was) continue; de.setAttribute('data-state', n); scan() }
|
|
922
|
+
if (was === null) de.removeAttribute('data-state'); else de.setAttribute('data-state', was)
|
|
923
|
+
}
|
|
924
|
+
return [...out].map((x) => { const [z, w, f] = x.split('|'); return [Number(z), Number(w), f] })
|
|
925
|
+
})()`
|
|
926
|
+
|
|
927
|
+
/** 量出来的字号 × 字重(只算主字体那几处)。有一屏没量过(分批还没截到、截图过期)就返回 null,退回静态扫描,免得漏字号 */
|
|
928
|
+
function renderedFonts(rows, family) {
|
|
929
|
+
if (!rows?.length || rows.some((r) => r.stale || !Array.isArray(r.fonts))) return null
|
|
930
|
+
const all = rows.flatMap((r) => r.fonts).filter((x) => Array.isArray(x) && x[0] > 0 && x[1] > 0)
|
|
931
|
+
if (!all.length) return null
|
|
932
|
+
const fam = String(family || '').toLowerCase()
|
|
933
|
+
const mine = fam && all.some((x) => x[2] === fam) ? all.filter((x) => x[2] === fam) : all
|
|
934
|
+
return [...new Map(mine.map(([z, w]) => [z + 'x' + w, [z, w]])).values()].sort((a, b) => a[0] - b[0] || a[1] - b[1])
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
function embeddedImages(htmlByKey, rows, root) {
|
|
938
|
+
const all = new Map()
|
|
939
|
+
const byKey = new Map(rows.map((r) => [r.key, r]))
|
|
940
|
+
const readLocal = dirReader(root)
|
|
941
|
+
for (const [key, html] of htmlByKey) {
|
|
942
|
+
// 统一相对地址;本地预览 URL 的路径和设计目录中的文件路径相对应。
|
|
943
|
+
const row = byKey.get(key)
|
|
944
|
+
const page = new URL(row?.url || key, 'http://design.invalid/')
|
|
945
|
+
const add = (ref, size = '') => {
|
|
946
|
+
if (!ref || /^(?:data|blob):/i.test(ref)) return
|
|
947
|
+
let src
|
|
948
|
+
try {
|
|
949
|
+
const url = new URL(ref, page)
|
|
950
|
+
const local = url.origin === page.origin && url.protocol === page.protocol
|
|
951
|
+
const file = page.protocol === 'file:' && local ? path.relative(root, fileURLToPath(url)).split(path.sep).join('/') : decodeURIComponent(url.pathname).replace(/^\//, '')
|
|
952
|
+
src = local ? (ref.startsWith('#') ? key : file) + url.hash : url.href
|
|
953
|
+
} catch { return }
|
|
954
|
+
const sizes = all.get(src) || new Map()
|
|
955
|
+
const found = sizes.get(key) || new Set()
|
|
956
|
+
if (size) found.add(size)
|
|
957
|
+
sizes.set(key, found)
|
|
958
|
+
all.set(src, sizes)
|
|
959
|
+
}
|
|
960
|
+
const { styles, inlineStyles, tags, links } = scanScreen(html)
|
|
961
|
+
const actual = new Set()
|
|
962
|
+
if (!row?.stale && Array.isArray(row?.images)) for (const [src, w, h] of row.images) {
|
|
963
|
+
add(src, w + '×' + h)
|
|
964
|
+
try { actual.add(new URL(src, page).href) } catch { /* 静态来源继续核对 */ }
|
|
965
|
+
}
|
|
966
|
+
const staticAdd = (ref, size) => {
|
|
967
|
+
try { if (ref && !actual.has(new URL(ref, page).href)) add(ref, size) } catch { /* 无效地址 */ }
|
|
968
|
+
}
|
|
969
|
+
let svg = new Map()
|
|
970
|
+
let css = styles.join('\n')
|
|
971
|
+
for (const href of links) {
|
|
972
|
+
const local = cssRel(root, key, href)
|
|
973
|
+
if (!local) continue
|
|
974
|
+
const sheet = readLocal(local)?.toString('utf8') || ''
|
|
975
|
+
css += '\n' + sheet
|
|
976
|
+
for (const { url, kind } of scanCss(sheet).refs) {
|
|
977
|
+
if (kind === 'font') continue
|
|
978
|
+
try { staticAdd(new URL(url, new URL(href, page)).href) } catch { /* 无效地址 */ }
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
for (const { url, kind } of scanCss([...styles, ...inlineStyles].join('\n')).refs) if (kind !== 'font') staticAdd(url)
|
|
982
|
+
css = css.replace(/\/\*[\s\S]*?\*\//g, '')
|
|
983
|
+
for (const { name, attrs } of tags) {
|
|
984
|
+
if (name === 'svg') svg = attrs
|
|
985
|
+
const src = name === 'img' ? attrs.get('src') : name === 'use' || name === 'image' ? attrs.get('href') || attrs.get('xlink:href') : name === 'video' ? attrs.get('poster') : ''
|
|
986
|
+
if (!src) continue
|
|
987
|
+
const box = name === 'use' ? svg : attrs
|
|
988
|
+
const id = box.get('id')
|
|
989
|
+
const classes = (box.get('class') || '').split(/\s+/)
|
|
990
|
+
let declarations = ''
|
|
991
|
+
for (const [, selectors, rule] of css.matchAll(/([^{}]+)\{([^{}]*)\}/g)) {
|
|
992
|
+
if (selectors.split(',').some((s) => {
|
|
993
|
+
s = s.trim()
|
|
994
|
+
return s === (name === 'use' ? 'svg' : name) || id && s === '#' + id || s.startsWith('.') && classes.includes(s.slice(1))
|
|
995
|
+
})) declarations += rule + ';'
|
|
996
|
+
}
|
|
997
|
+
declarations += box.get('style') || ''
|
|
998
|
+
const dimension = (axis) => {
|
|
999
|
+
const decl = [...declarations.matchAll(new RegExp('(?:^|;)\\s*' + axis + '\\s*:\\s*([^;]+)', 'gi'))].at(-1)?.[1]
|
|
1000
|
+
const n = /^(\d*\.?\d+)(?:px)?$/i.exec((decl || box.get(axis) || '').trim())?.[1]
|
|
1001
|
+
return n ? Math.round(Number(n)) : 0
|
|
1002
|
+
}
|
|
1003
|
+
const w = dimension('width'), h = dimension('height')
|
|
1004
|
+
staticAdd(src, w && h ? w + '×' + h : w ? w + 'px 宽' : h ? h + 'px 高' : '')
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
1007
|
+
return [...all].map(([src, screens]) => '- `' + src.replace(/`/g, 'ʼ').replace(/[\r\n]/g, ' ') + '` — ' +
|
|
1008
|
+
[...screens].map(([key, sizes]) => key + '(' + ([...sizes].join(' / ') || '显示尺寸待实测') + ')').join('、'))
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
function imageMd(root, htmlByKey, rows, v8) {
|
|
1012
|
+
const icons = embeddedIconsMd(rows, 'lvgl', v8 ? 8 : 9)
|
|
1013
|
+
const all = embeddedImages(htmlByKey, rows, root)
|
|
1014
|
+
const images = dropExported(all, icons?.done)
|
|
1015
|
+
return [
|
|
1016
|
+
...(icons ? icons.lines : []),
|
|
1017
|
+
'### LVGL 图片', '',
|
|
1018
|
+
...(images.length ? images : all.length ? ['- 设计里的图片都在上面「图标」表里导好了。'] : ['- 静态扫描没有找到独立图片;内联矢量和动态素材按设计稿核对。']),
|
|
1019
|
+
'- 按上面的显示尺寸(像素)预裁切或栅格化,转好的 C 文件放进 `ui/assets/images/`。CSS 背景记录的是元素框尺寸,转换前按 `background-size` 核对;缺尺寸的在设计预览里量一下。',
|
|
1020
|
+
v8
|
|
1021
|
+
? '- 用 8.x 的 `lv_img_conv`。在临时素材目录运行 `./lv_img_conv.js logo.png -f -c CF_TRUE_COLOR_ALPHA`,再把输出的 C 文件移进 `ui/assets/images/`。单色图标用 `CF_ALPHA_8_BIT`,运行时按主题着色。描述符用 `lv_img_dsc_t`。'
|
|
1022
|
+
: '- 用目标库版本的 `scripts/LVGLImage.py`(依赖 pypng、lz4)。示例 `python3 /path/to/lvgl/scripts/LVGLImage.py --ofmt C --cf RGB565A8 -o ui/assets/images logo.png`。不透明图片可用 `RGB565`,单色图标用 `A8` 后按主题着色。描述符用 `lv_image_dsc_t`。',
|
|
1023
|
+
icons
|
|
1024
|
+
? '- 上面「图标」表里的已经导好,不用再转;只有彩色图片和插件没画出来的才用转换工具。图片 C 数组按目标大版本转换,8.x 和 9.x 的描述符和格式不能混用。'
|
|
1025
|
+
: '- `icons.svg` 的每个使用到的 symbol 单独导出(用 `rsvg-convert`、`cairosvg` 这类命令行工具,别开浏览器);图片 C 数组按目标大版本转换,8.x 和 9.x 的描述符和格式不能混用。', '',
|
|
1026
|
+
]
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
const LVGL_API = [
|
|
1030
|
+
'- 8.3:`lv_scr_act` / `lv_scr_load`、`lv_btn_create`、`lv_img_create` / `lv_img_set_zoom`、`lv_obj_add_flag` / `lv_obj_clear_flag`、`lv_obj_clear_state`、`lv_coord_t`、样式 `img_opa` / `shadow_ofs_x`。',
|
|
1031
|
+
'- 9.0–9.5:`lv_screen_active` / `lv_screen_load`、`lv_button_create`、`lv_image_create` / `lv_image_set_scale`、`lv_obj_add_flag` / `lv_obj_remove_flag`、`lv_obj_remove_state`、`int32_t`、样式 `image_opa` / `shadow_offset_x`。',
|
|
1032
|
+
'- 9.6:沿用 9.x 控件名;弃用通用 flag API,隐藏用 `lv_obj_set_hidden` / `lv_obj_is_hidden`,点击和滚动用 `lv_obj_set_clickable` / `lv_obj_set_scrollable`。查找对象改用 `lv_obj_find_by_name`;布局注册改用 `lv_layout_create`;默认色格式读 `LV_COLOR_FORMAT_DEFAULT`。',
|
|
1033
|
+
]
|
|
1034
|
+
|
|
1035
|
+
function lvglMd({ project, size }) {
|
|
1036
|
+
const lv = project?.lvgl
|
|
1037
|
+
const v8 = lv?.major === 8
|
|
1038
|
+
const recent = !lv || lv.major === 9 && lv.minor >= 6
|
|
1039
|
+
const supported = !lv || lv.major === 8 || lv.major === 9
|
|
1040
|
+
const api = v8 ? LVGL_API[0] : recent ? LVGL_API[2] : LVGL_API[1]
|
|
1041
|
+
const scroll = v8 ? 'lv_obj_clear_flag(root, LV_OBJ_FLAG_SCROLLABLE)' : recent ? 'lv_obj_set_scrollable(root, false)' : 'lv_obj_remove_flag(root, LV_OBJ_FLAG_SCROLLABLE)'
|
|
1042
|
+
return [
|
|
1043
|
+
'## 做成 LVGL C(独立 ui/)', '',
|
|
1044
|
+
lv ? '- 检测到 LVGL ' + [lv.major, lv.minor, lv.patch].filter((v) => v != null).join('.') + ',库目录 `' + lv.at + '`。'
|
|
1045
|
+
: '- 未检测到 LVGL 版本,默认按 LVGL 9.x 的最新版(9.6)设计。先向用户确认版本再写实现。工程里没有 LVGL 源码时插件在电脑上出不了图:请用户把 LVGL 放进工程(如 `lvgl/`),或者用 PlatformIO 装好依赖。',
|
|
1046
|
+
'- **先读目标工程的 LVGL 头文件,逐个核对每个要用的函数名和签名。** 只为目标版本写一套 C 代码。',
|
|
1047
|
+
supported ? '- 本次使用这一行的 API。' + api.slice(2) : '- 当前版本超出下表覆盖范围。先以项目头文件确认可用 API,再实现。',
|
|
1048
|
+
'', '### API 对照(查表用)', '', ...LVGL_API, '',
|
|
1049
|
+
'### 文件和接入', '',
|
|
1050
|
+
'- 所有新增界面代码放进 `ui/`。`ui.c` / `ui.h` 提供 `ui_init()` 和切屏入口;`ui_theme.c` 用文件级静态 `lv_style_t`,每个样式只初始化一次,别在函数里创建栈上的 `lv_style_t`。事件回调桩集中在 `ui_events.c`。',
|
|
1051
|
+
'- 一屏一对 `screens/ui_<screen>.c` / `.h`,共用控件放 `components/`,素材放 `assets/fonts/`、`assets/images/`。写 `ui/CMakeLists.txt` 和 `ui/README.md`,列出源文件、头文件目录、所用控件和集成顺序。`ui/tools/ui_dev.c` 只在电脑上出图用(见「在电脑上出图」),别加进固件构建。',
|
|
1052
|
+
'- 宿主初始化 LVGL、显示和输入后再调用 `ui_init()`。只在独立目录交付,已有同名模块先核对。保留宿主的 `main.c`、驱动、链接脚本、`lv_conf.h` 和 CubeMX 的 USER CODE 区;所需改动写入接入说明。',
|
|
1053
|
+
'- 设计尺寸 ' + size.join('×') + ' 像素。CSS flex / grid 映射到 LVGL flex / grid,固定布局照像素和对齐方式落地。屏幕根节点禁止滚动' + (supported ? '(`' + scroll + '`)' : '') + ',只有设计明确要滚动的列表才开。',
|
|
1054
|
+
'- 滑块(`lv_slider`)、弧形(`lv_arc`)的圆钮大小跟着轨道粗细走:钮要比轨道大,就用 `LV_PART_KNOB` 的 `pad_all` 往外撑(钮直径 = 轨道粗细 + 2 × pad)。给 KNOB 设 width / height 不生效,钮会缩成轨道粗细的小点;比对时这种小控件变形只占很少像素,要对着截图看。',
|
|
1055
|
+
'- `dsh-states` 对应每屏的状态枚举和状态设置函数;`data-back` 对应固定大小的页面栈,栈满要处理,栈空才走设计里的备用目的地。实体按键或旋钮用焦点组,保留设计稿的焦点、按下和禁用状态。',
|
|
1056
|
+
'- 在接入说明中按用到的能力列配置,例如 `LV_USE_FLEX` / `LV_USE_GRID`、`LV_USE_LABEL`' +
|
|
1057
|
+
(supported ? '、`' + (v8 ? 'LV_USE_BTN` / `LV_USE_IMG`、`LV_DRAW_COMPLEX' : 'LV_USE_BUTTON` / `LV_USE_IMAGE`、`LV_DRAW_SW_COMPLEX') + '`,并确认 `' + (recent ? 'LV_COLOR_FORMAT_DEFAULT' : 'LV_COLOR_DEPTH') + '`' : '') +
|
|
1058
|
+
'。' + (lv?.colorDepth ? ' 读到 ' + lv.colorDepth + ' 位色。' : '') + (lv?.fontCompressed != null ? ' 读到 `LV_USE_FONT_COMPRESSED ' + lv.fontCompressed + '`。' : ''),
|
|
1059
|
+
'',
|
|
1060
|
+
]
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
function qmlMd({ project, size, icons = false }) {
|
|
1064
|
+
const qt = project?.qt
|
|
1065
|
+
const v5 = qt?.major === 5
|
|
1066
|
+
return [
|
|
1067
|
+
'## 做成 Qt Quick / QML(独立 qml/)', '',
|
|
1068
|
+
qt?.major ? '- 检测到 Qt ' + qt.major + (qt.build ? ',构建方式 ' + qt.build : '') + '。'
|
|
1069
|
+
: '- Qt 主版本未确认' + (qt?.build ? '(检测到 ' + qt.build + ')' : '') + '。先确认实际 Qt 版本和构建方式;新模块暂按 Qt 6 / CMake 规划,使用 Qt 5 时按 Qt 5 写法调整。',
|
|
1070
|
+
'- 所有界面代码放进 `qml/`。`Main.qml` 用固定 ' + size.join('×') + ' 的窗口,最小和最大尺寸设相同,用 `StackView` 管理切页和返回;根页面不滚动,按设计给列表等局部区域加滚动。根窗口加一个 `devShow(screen, state)`(在电脑上出图用,见「在电脑上出图」)。',
|
|
1071
|
+
'- `theme/Theme.qml` 用主题单例集中定义变量和深浅色开关。把 mock 数据和可变状态放进 `state/AppState.qml` 单例,之后由 C++ 提供真实数据;单例写 `pragma Singleton`,在所在目录的 `qmldir` 里登记(`singleton Theme 1.0 Theme.qml`)。',
|
|
1072
|
+
'- 自己的 QML 文件之间用相对目录导入(`import "theme"`、`import "screens"`),别用模块 URI 导入:这样不经过构建、直接加载 `qml/Main.qml` 也能跑(插件在电脑上出图就是这样加载的)。',
|
|
1073
|
+
'- 每屏放一个 `screens/<Name>Page.qml`,共用控件放 `components/`。`dsh-states` 对应 QML `State`;`data-back` 在有上一页时调用 `StackView.pop()`,否则使用设计里的备用目的地。',
|
|
1074
|
+
'- 按设计固定像素、anchors、Row / Column / Grid 或 Qt Quick Layouts 实现。无 GPU 的板子通常走软件渲染,默认避免 QtGraphicalEffects、MultiEffect 和自定义着色器。',
|
|
1075
|
+
v5
|
|
1076
|
+
? '- 按 Qt 5.15 使用带版本号的导入 `import QtQuick 2.15`、`import QtQuick.Controls 2.15`、`import QtQuick.Layouts 1.15`。用配置或环境变量把 Qt Quick Controls 的样式固定为 `Default`(例如 `QT_QUICK_CONTROLS_STYLE=Default`),进入 QML 前设置。'
|
|
1077
|
+
: '- Qt 6 使用不带版本号的导入 `import QtQuick`、`import QtQuick.Controls`、`import QtQuick.Layouts`。用配置或环境变量把 Qt Quick Controls 的样式固定为 `Basic`(例如 `QT_QUICK_CONTROLS_STYLE=Basic`),进入 QML 前设置。',
|
|
1078
|
+
v5
|
|
1079
|
+
? '- 提供 `qml/` 下的 `.pro`、`.qrc`、`qmldir`,用资源文件打包 QML、字体和图片并登记单例。接入现有 Qt 5 CMake 工程时,在接入说明交代如何纳入同一份资源文件。'
|
|
1080
|
+
: '- 提供 `qml/CMakeLists.txt`,用 `qt_add_qml_module` 把 `qml/` 下的 QML、各目录的 `qmldir`、字体和图片都打进资源,写清模块 URI(给宿主加载入口用)。接入已有 Qt 6 qmake 工程前,确认如何构建或加载独立模块。',
|
|
1081
|
+
'- 将中文字体的 TTF/OTF 打包到 `assets/fonts/`(做法见下面「图片和字体」),用 `FontLoader` 加载并设成界面字体;板子上多半没有中文字体。',
|
|
1082
|
+
(icons
|
|
1083
|
+
? '- 图标插件已经按显示尺寸和颜色导成 PNG(见下面「图标」),拷进 `assets/images/` 直接用,不用拆 `icons.svg`。'
|
|
1084
|
+
: '- `icons.svg` 拆成单个图标文件放进 `assets/images/`(用 `rsvg-convert`、`cairosvg` 这类命令行工具导成设计尺寸的 PNG,别开浏览器);依赖 SVG 时先确认板子有 QtSvg。') + '写 `qml/README.md` 交代构建、运行、资源路径和接入步骤。',
|
|
1085
|
+
'',
|
|
1086
|
+
]
|
|
1087
|
+
}
|
|
1088
|
+
|
|
1089
|
+
export function embeddedHandoffMd(target, options) {
|
|
1090
|
+
return target === 'lvgl' ? lvglMd(options) : qmlMd(options)
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
export function embeddedAssetsMd(target, { root, htmlByKey, rows, mockData, project }) {
|
|
1094
|
+
return [...varMd(target, htmlByKey), ...(target === 'lvgl'
|
|
1095
|
+
? ['## 图片和字体', '', ...fontMd(root, htmlByKey, mockData, rows), ...imageMd(root, htmlByKey, rows, project?.lvgl?.major === 8)]
|
|
1096
|
+
: ['## 图片和字体', '', '- 按上面 QML 模块的资源路径打包设计用到的图片、图标和字体。', '',
|
|
1097
|
+
...qmlFontMd(root, htmlByKey, mockData, rows), ...qmlImagesMd(root, htmlByKey, rows), ''])]
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
function qmlImagesMd(root, htmlByKey, rows) {
|
|
1101
|
+
const icons = embeddedIconsMd(rows, 'qml')
|
|
1102
|
+
return [...(icons?.lines || []), ...dropExported(embeddedImages(htmlByKey, rows, root), icons?.done)]
|
|
1103
|
+
}
|
|
1104
|
+
|
|
1105
|
+
/** 设计里标了 data-var 的地方:会变的值,别写死成设计稿上的示例 */
|
|
1106
|
+
function varMd(target, htmlByKey) {
|
|
1107
|
+
const { vars } = collectEmbeddedFonts(htmlByKey)
|
|
1108
|
+
if (!vars.length) return []
|
|
1109
|
+
return ['## 会变的值(data-var)', '',
|
|
1110
|
+
'- 设计里标了 ' + vars.map((v) => '`' + v + '`').join('、') + ':页面上的数是示例。' +
|
|
1111
|
+
(target === 'lvgl' ? '每个做成一个更新函数(如 `ui_set_' + vars[0].replace(/\W+/g, '_') + '(...)` 里调 `lv_label_set_text_fmt`),在 `ui.h` 里声明,宿主拿到真实数据时调用。'
|
|
1112
|
+
: '每个做成 `AppState` 单例的一个属性,界面绑定它,C++ 那边更新。'),
|
|
1113
|
+
'']
|
|
1114
|
+
}
|
|
1115
|
+
|
|
1116
|
+
/** QML 的字体:网页字体先转 TTF,可变字体按用到的字重各切一个静态 TTF(板子上的 Qt 不一定认可变字体的字重轴) */
|
|
1117
|
+
function qmlFontMd(root, htmlByKey, mockData, rows) {
|
|
1118
|
+
const { characters, weights: scanned } = collectEmbeddedFonts(htmlByKey, { root, mockData })
|
|
1119
|
+
const cjk = [...characters].some((c) => /[\u2E80-\u9FFF\uAC00-\uD7AF\uF900-\uFAFF\uFF00-\uFFEF]/.test(c))
|
|
1120
|
+
const { main: font, others } = designFonts(root, cjk)
|
|
1121
|
+
const seen = font && renderedFonts(rows, libFont(font)?.family)
|
|
1122
|
+
const weights = seen ? [...new Set(seen.map(([, w]) => w))].sort((a, b) => a - b) : scanned
|
|
1123
|
+
if (!font) return ['- 设计里没有字体文件:先问用户用哪款(TTF / OTF),没有指定时可建议开放授权的 Noto Sans SC,打包进 `qml/assets/fonts/`。', '']
|
|
1124
|
+
const prep = fontPrep(font, weights, 'qml/assets/fonts/_src', 'qml/assets/fonts')
|
|
1125
|
+
const files = [...new Set(prep.files.values())]
|
|
1126
|
+
const lines = ['- 界面字体是设计里的 `' + path.basename(font) + '`,先核对字形覆盖和授权。']
|
|
1127
|
+
if (prep.prepared) {
|
|
1128
|
+
lines.push('- 它是' + (Array.isArray(libFont(font)?.weights) ? '可变字体,按设计用到的字重(' + weights.join(' / ') + ')各切一个静态 TTF' : '网页字体,先转成 TTF') + ',再打包(`_src/` 是中间文件,别打包):', '', '```sh', ...prep.cmds, '```', '')
|
|
1129
|
+
}
|
|
1130
|
+
lines.push('- 打包并用 `FontLoader` 加载:' + files.map((f) => '`' + (prep.prepared ? f.replace(/^qml\//, '') : 'assets/fonts/' + path.basename(f)) + '`').join('、') + ';同一字体族的几档字重都加载后,用 `font.weight` 选字重。')
|
|
1131
|
+
const missedW = seen ? scanned.filter((w) => !rows.some((r) => r.fonts.some((x) => x[1] === w))) : []
|
|
1132
|
+
if (missedW.length) lines.push('- 样式表里还写了字重 ' + missedW.join(' / ') + ',可在浏览器里打开各屏、各状态都没看到(多半是点了才出现的弹窗,或者没用上的样式):真用到的照上面的命令补切一份。')
|
|
1133
|
+
if (others.length) lines.push('- 设计里还有 ' + others.map((f) => '`' + path.basename(f) + '`').join('、') + '(数字字体之类):照同样的办法转成 TTF 再打包。')
|
|
1134
|
+
lines.push('')
|
|
1135
|
+
return lines
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
export function embeddedVerifyMd(target, size, dest = '') {
|
|
1139
|
+
const [w, h] = size
|
|
1140
|
+
const where = dest ? '`' + dest + '`' : '工程目录'
|
|
1141
|
+
const shot = target === 'lvgl' ? [
|
|
1142
|
+
'### 在电脑上出图:插件自己编', '',
|
|
1143
|
+
'- `compare_design` 的 `url` 填工程目录(' + where + '),插件用电脑上的 gcc / clang 把工程里的 LVGL 源码、`ui/` 下所有 `.c` 和插件自带的出图程序编在一起,画一张 ' + w + '×' + h + ' 的图再比。LVGL 库第一次要编一会儿(之后有缓存),每次只重编 `ui/`。',
|
|
1144
|
+
'- 要你写一个切屏入口 **`ui/tools/ui_dev.c`**(只在电脑上用,别加进固件构建):',
|
|
1145
|
+
'',
|
|
1146
|
+
'```c',
|
|
1147
|
+
'#include "ui.h"',
|
|
1148
|
+
'#include <string.h>',
|
|
1149
|
+
'/* screen:设计文件名去掉 .html(如 "home");state:状态名,默认状态是 "" */',
|
|
1150
|
+
'void ui_dev_show(const char * screen, const char * state)',
|
|
1151
|
+
'{',
|
|
1152
|
+
' /* 切到那一屏、那个状态,把要显示的模拟数据设好 */',
|
|
1153
|
+
'}',
|
|
1154
|
+
'```',
|
|
1155
|
+
'',
|
|
1156
|
+
'- 插件编的时候:`ui/tools/` 里只编 `ui_dev.c`(别的出图程序不用写);字库、图片的 `.c` 要放在 `ui/` 下面;`ui/` 里别引用 HAL、驱动、RTOS 的头文件。工程的 `lv_conf.h` 只搬颜色深度、字体、控件、绘制效果这些和画面有关的开关(内存、时钟、DMA2D、系统这些板子上的设置在电脑上用不了)。',
|
|
1157
|
+
'- 插件报编译错误就照着改;报「没有 C 编译器」时请用户装(Mac:`xcode-select --install`;Windows:MSYS2 的 gcc;Linux:gcc)。实在出不了图,请用户从模拟器或板子上截一张 ' + w + '×' + h + ' 的图,`url` 填图片路径。', '',
|
|
1158
|
+
] : [
|
|
1159
|
+
'### 在电脑上出图:插件自己跑', '',
|
|
1160
|
+
'- `compare_design` 的 `url` 填工程目录(' + where + '),插件用 Python 的 PySide6 离屏加载 `qml/Main.qml`,调根对象的 `devShow(屏, 状态)`,截一张 ' + w + '×' + h + ' 的图再比。控件样式按 Basic。',
|
|
1161
|
+
'- 要你在 `Main.qml` 的根窗口里加一个切屏入口(出图用,留着也不影响产品):',
|
|
1162
|
+
'',
|
|
1163
|
+
'```qml',
|
|
1164
|
+
'// screen:设计文件名去掉 .html(如 "home");state:状态名,默认状态是 ""',
|
|
1165
|
+
'function devShow(screen, state) {',
|
|
1166
|
+
' // 切到那一屏、那个状态,把要显示的模拟数据设好',
|
|
1167
|
+
'}',
|
|
1168
|
+
'```',
|
|
1169
|
+
'',
|
|
1170
|
+
'- 界面只能用 QML 自己(和 `state/AppState.qml` 这类 QML 单例)跑起来:插件不编 C++,`main.cpp` 里注册的东西电脑上出图时没有。',
|
|
1171
|
+
'- PySide6 交给插件找(也认环境变量 `DSH_PYSIDE_PYTHON`),别自己在终端查或装,写好 `devShow` 就直接调 `compare_design`。插件报「没装 PySide6」时才问用户能不能装(`python3 -m pip install PySide6`,几百 MB;装在虚拟环境里的话把那个 python 的路径设到环境变量 `DSH_PYSIDE_PYTHON`)。不装就请用户从 Qt Creator 或板子上截一张 ' + w + '×' + h + ' 的图,`url` 填图片路径。', '',
|
|
1172
|
+
]
|
|
1173
|
+
return [
|
|
1174
|
+
'## 做法和验收', '',
|
|
1175
|
+
'1. 按上面的目录和目标版本搭骨架,照屏幕表逐屏实现。先做共用控件,样式取自设计变量和用户手调值。',
|
|
1176
|
+
' 尺寸、颜色、字号看设计源码里的 CSS 值,样子对着 `handoff/shots/` 的截图;**别自己开浏览器量**(DSH 的沙箱里浏览器起不来,改 HOME 再开还会弹系统的钥匙串窗口)。',
|
|
1177
|
+
'2. 目标程序不能直接用浏览器运行。每做完一屏调 `compare_design`:`screen` 填设计文件名,`url` 填工程目录(' + where + ',插件自己出图,见下面),这屏有状态的用 `state` 逐个比。',
|
|
1178
|
+
'3. 修正位置、颜色和缺失元素。字边缘一圈零散的差异是字体渲染不同,可以不管;差异块里整块挪位、颜色不对、少了东西的要改。**过关线**:差异块里没有整块控件(按钮、滑块、卡片)挪位、变形、缺失,剩下的只落在字边缘(做对了一般在 2–5%);而且对着截图把文字、数字、单位逐个核对过(写错单位像素比不太出来)。',
|
|
1179
|
+
'4. 交付时列明完成的屏、接入和运行方法、核对过的状态及剩余差异。', '',
|
|
1180
|
+
...shot,
|
|
1181
|
+
]
|
|
1182
|
+
}
|