mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
[feat] add pack bin logic and UI
This commit is contained in:
parent
904876bd89
commit
cd2efb5dfd
22 changed files with 6085 additions and 99 deletions
62
main/manager-web/package-lock.json
generated
62
main/manager-web/package-lock.json
generated
|
|
@ -13,7 +13,10 @@
|
||||||
"dotenv": "^16.5.0",
|
"dotenv": "^16.5.0",
|
||||||
"element-ui": "^2.15.14",
|
"element-ui": "^2.15.14",
|
||||||
"flyio": "^0.6.14",
|
"flyio": "^0.6.14",
|
||||||
|
"gif.js": "^0.2.0",
|
||||||
|
"gifuct-js": "^2.1.2",
|
||||||
"normalize.css": "^8.0.1",
|
"normalize.css": "^8.0.1",
|
||||||
|
"opentype.js": "^1.3.4",
|
||||||
"opus-decoder": "^0.7.7",
|
"opus-decoder": "^0.7.7",
|
||||||
"opus-recorder": "^8.0.5",
|
"opus-recorder": "^8.0.5",
|
||||||
"sm-crypto": "^0.3.13",
|
"sm-crypto": "^0.3.13",
|
||||||
|
|
@ -5831,6 +5834,21 @@
|
||||||
"assert-plus": "^1.0.0"
|
"assert-plus": "^1.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/gif.js": {
|
||||||
|
"version": "0.2.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/gif.js/-/gif.js-0.2.0.tgz",
|
||||||
|
"integrity": "sha512-bYxCoT8OZKmbxY8RN4qDiYuj4nrQDTzgLRcFVovyona1PTWNePzI4nzOmotnlOFIzTk/ZxAHtv+TfVLiBWj/hw==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/gifuct-js": {
|
||||||
|
"version": "2.1.2",
|
||||||
|
"resolved": "https://registry.npmmirror.com/gifuct-js/-/gifuct-js-2.1.2.tgz",
|
||||||
|
"integrity": "sha512-rI2asw77u0mGgwhV3qA+OEgYqaDn5UNqgs+Bx0FGwSpuqfYn+Ir6RQY5ENNQ8SbIiG/m5gVa7CD5RriO4f4Lsg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"js-binary-schema-parser": "^2.0.3"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/glob": {
|
"node_modules/glob": {
|
||||||
"version": "7.2.3",
|
"version": "7.2.3",
|
||||||
"resolved": "https://registry.npmmirror.com/glob/-/glob-7.2.3.tgz",
|
"resolved": "https://registry.npmmirror.com/glob/-/glob-7.2.3.tgz",
|
||||||
|
|
@ -7041,6 +7059,12 @@
|
||||||
"@sideway/pinpoint": "^2.0.0"
|
"@sideway/pinpoint": "^2.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/js-binary-schema-parser": {
|
||||||
|
"version": "2.0.3",
|
||||||
|
"resolved": "https://registry.npmmirror.com/js-binary-schema-parser/-/js-binary-schema-parser-2.0.3.tgz",
|
||||||
|
"integrity": "sha512-xezGJmOb4lk/M1ZZLTR/jaBHQ4gG/lqQnJqdIv4721DMggsa1bDVlHXNeHYogaIEHD9vCRv0fcL4hMA+Coarkg==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/js-message": {
|
"node_modules/js-message": {
|
||||||
"version": "1.0.7",
|
"version": "1.0.7",
|
||||||
"resolved": "https://registry.npmmirror.com/js-message/-/js-message-1.0.7.tgz",
|
"resolved": "https://registry.npmmirror.com/js-message/-/js-message-1.0.7.tgz",
|
||||||
|
|
@ -8031,6 +8055,22 @@
|
||||||
"opener": "bin/opener-bin.js"
|
"opener": "bin/opener-bin.js"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/opentype.js": {
|
||||||
|
"version": "1.3.4",
|
||||||
|
"resolved": "https://registry.npmmirror.com/opentype.js/-/opentype.js-1.3.4.tgz",
|
||||||
|
"integrity": "sha512-d2JE9RP/6uagpQAVtJoF0pJJA/fgai89Cc50Yp0EJHk+eLp6QQ7gBoblsnubRULNY132I0J1QKMJ+JTbMqz4sw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"string.prototype.codepointat": "^0.2.1",
|
||||||
|
"tiny-inflate": "^1.0.3"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"ot": "bin/ot"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 8.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/opus-decoder": {
|
"node_modules/opus-decoder": {
|
||||||
"version": "0.7.7",
|
"version": "0.7.7",
|
||||||
"resolved": "https://registry.npmmirror.com/opus-decoder/-/opus-decoder-0.7.7.tgz",
|
"resolved": "https://registry.npmmirror.com/opus-decoder/-/opus-decoder-0.7.7.tgz",
|
||||||
|
|
@ -10353,6 +10393,12 @@
|
||||||
"node": ">=8"
|
"node": ">=8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/string.prototype.codepointat": {
|
||||||
|
"version": "0.2.1",
|
||||||
|
"resolved": "https://registry.npmmirror.com/string.prototype.codepointat/-/string.prototype.codepointat-0.2.1.tgz",
|
||||||
|
"integrity": "sha512-2cBVCj6I4IOvEnjgO/hWqXjqBGsY+zwPmHl12Srk9IXSZ56Jwwmy+66XO5Iut/oQVR7t5ihYdLB0GMa4alEUcg==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/string.prototype.matchall": {
|
"node_modules/string.prototype.matchall": {
|
||||||
"version": "4.0.12",
|
"version": "4.0.12",
|
||||||
"resolved": "https://registry.npmmirror.com/string.prototype.matchall/-/string.prototype.matchall-4.0.12.tgz",
|
"resolved": "https://registry.npmmirror.com/string.prototype.matchall/-/string.prototype.matchall-4.0.12.tgz",
|
||||||
|
|
@ -10767,6 +10813,12 @@
|
||||||
"integrity": "sha512-eHY7nBftgThBqOyHGVN+l8gF0BucP09fMo0oO/Lb0w1OF80dJv+lDVpXG60WMQvkcxAkNybKsrEIE3ZtKGmPrA==",
|
"integrity": "sha512-eHY7nBftgThBqOyHGVN+l8gF0BucP09fMo0oO/Lb0w1OF80dJv+lDVpXG60WMQvkcxAkNybKsrEIE3ZtKGmPrA==",
|
||||||
"dev": true
|
"dev": true
|
||||||
},
|
},
|
||||||
|
"node_modules/tiny-inflate": {
|
||||||
|
"version": "1.0.3",
|
||||||
|
"resolved": "https://registry.npmmirror.com/tiny-inflate/-/tiny-inflate-1.0.3.tgz",
|
||||||
|
"integrity": "sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/to-regex-range": {
|
"node_modules/to-regex-range": {
|
||||||
"version": "5.0.1",
|
"version": "5.0.1",
|
||||||
"resolved": "https://registry.npmmirror.com/to-regex-range/-/to-regex-range-5.0.1.tgz",
|
"resolved": "https://registry.npmmirror.com/to-regex-range/-/to-regex-range-5.0.1.tgz",
|
||||||
|
|
@ -11096,6 +11148,16 @@
|
||||||
"node": ">= 0.4.0"
|
"node": ">= 0.4.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/uuid": {
|
||||||
|
"version": "3.4.0",
|
||||||
|
"resolved": "https://registry.npmmirror.com/uuid/-/uuid-3.4.0.tgz",
|
||||||
|
"integrity": "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==",
|
||||||
|
"deprecated": "Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details.",
|
||||||
|
"license": "MIT",
|
||||||
|
"bin": {
|
||||||
|
"uuid": "bin/uuid"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/validate-npm-package-license": {
|
"node_modules/validate-npm-package-license": {
|
||||||
"version": "3.0.4",
|
"version": "3.0.4",
|
||||||
"resolved": "https://registry.npmmirror.com/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz",
|
"resolved": "https://registry.npmmirror.com/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz",
|
||||||
|
|
|
||||||
|
|
@ -13,7 +13,10 @@
|
||||||
"dotenv": "^16.5.0",
|
"dotenv": "^16.5.0",
|
||||||
"element-ui": "^2.15.14",
|
"element-ui": "^2.15.14",
|
||||||
"flyio": "^0.6.14",
|
"flyio": "^0.6.14",
|
||||||
|
"gif.js": "^0.2.0",
|
||||||
|
"gifuct-js": "^2.1.2",
|
||||||
"normalize.css": "^8.0.1",
|
"normalize.css": "^8.0.1",
|
||||||
|
"opentype.js": "^1.3.4",
|
||||||
"opus-decoder": "^0.7.7",
|
"opus-decoder": "^0.7.7",
|
||||||
"opus-recorder": "^8.0.5",
|
"opus-recorder": "^8.0.5",
|
||||||
"sm-crypto": "^0.3.13",
|
"sm-crypto": "^0.3.13",
|
||||||
|
|
|
||||||
|
|
@ -45,11 +45,6 @@
|
||||||
@generate="handleGenerate"
|
@generate="handleGenerate"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<CustomThemeGenerateModal
|
|
||||||
:visible.sync="generateModalVisible"
|
|
||||||
:config="config"
|
|
||||||
/>
|
|
||||||
</el-dialog>
|
</el-dialog>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
|
@ -57,15 +52,13 @@
|
||||||
import CustomThemeChipConfig from './custom-theme/CustomThemeChipConfig.vue';
|
import CustomThemeChipConfig from './custom-theme/CustomThemeChipConfig.vue';
|
||||||
import CustomThemeDesign from './custom-theme/CustomThemeDesign.vue';
|
import CustomThemeDesign from './custom-theme/CustomThemeDesign.vue';
|
||||||
import CustomThemeSummary from './custom-theme/CustomThemeSummary.vue';
|
import CustomThemeSummary from './custom-theme/CustomThemeSummary.vue';
|
||||||
import CustomThemeGenerateModal from './custom-theme/CustomThemeGenerateModal.vue';
|
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
name: 'CustomThemeDialog',
|
name: 'CustomThemeDialog',
|
||||||
components: {
|
components: {
|
||||||
CustomThemeChipConfig,
|
CustomThemeChipConfig,
|
||||||
CustomThemeDesign,
|
CustomThemeDesign,
|
||||||
CustomThemeSummary,
|
CustomThemeSummary
|
||||||
CustomThemeGenerateModal
|
|
||||||
},
|
},
|
||||||
props: {
|
props: {
|
||||||
visible: {
|
visible: {
|
||||||
|
|
@ -80,7 +73,6 @@ export default {
|
||||||
data() {
|
data() {
|
||||||
return {
|
return {
|
||||||
currentStep: 1,
|
currentStep: 1,
|
||||||
generateModalVisible: false,
|
|
||||||
config: {
|
config: {
|
||||||
chip: {
|
chip: {
|
||||||
model: '',
|
model: '',
|
||||||
|
|
@ -104,12 +96,7 @@ export default {
|
||||||
dark: { backgroundType: 'color', backgroundColor: '#121212', textColor: '#ffffff', backgroundImage: '' }
|
dark: { backgroundType: 'color', backgroundColor: '#121212', textColor: '#ffffff', backgroundImage: '' }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
steps: [
|
|
||||||
{ id: 1, title: this.$t('device.customThemeStep1'), desc: this.$t('device.customThemeChipConfigDesc') },
|
|
||||||
{ id: 2, title: this.$t('device.customThemeStep2'), desc: this.$t('device.customThemeDesignDesc') },
|
|
||||||
{ id: 3, title: this.$t('device.customThemeStep3'), desc: this.$t('device.customThemeSummaryDesc') }
|
|
||||||
]
|
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
computed: {
|
computed: {
|
||||||
|
|
@ -120,6 +107,13 @@ export default {
|
||||||
set(val) {
|
set(val) {
|
||||||
this.$emit('update:visible', val);
|
this.$emit('update:visible', val);
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
steps() {
|
||||||
|
return [
|
||||||
|
{ id: 1, title: this.$t('device.customThemeStep1'), desc: this.$t('device.customThemeChipConfigDesc') },
|
||||||
|
{ id: 2, title: this.$t('device.customThemeStep2'), desc: this.$t('device.customThemeDesignDesc') },
|
||||||
|
{ id: 3, title: this.$t('device.customThemeStep3'), desc: this.$t('device.customThemeSummaryDesc') }
|
||||||
|
];
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
methods: {
|
methods: {
|
||||||
|
|
@ -130,7 +124,8 @@ export default {
|
||||||
if (this.currentStep > 1) this.currentStep -= 1;
|
if (this.currentStep > 1) this.currentStep -= 1;
|
||||||
},
|
},
|
||||||
handleGenerate() {
|
handleGenerate() {
|
||||||
this.generateModalVisible = true;
|
// 通过事件通知父组件打开生成模态框
|
||||||
|
this.$emit('generate', this.config);
|
||||||
},
|
},
|
||||||
handleClose() {
|
handleClose() {
|
||||||
this.dialogVisible = false;
|
this.dialogVisible = false;
|
||||||
|
|
@ -223,4 +218,3 @@ export default {
|
||||||
min-height: 420px;
|
min-height: 420px;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -58,7 +58,7 @@
|
||||||
v-model="customConfig.display.width"
|
v-model="customConfig.display.width"
|
||||||
:min="128"
|
:min="128"
|
||||||
:max="800"
|
:max="800"
|
||||||
:placeholder="320"
|
placeholder="320"
|
||||||
@change="handleCustomConfigChange"
|
@change="handleCustomConfigChange"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -68,7 +68,7 @@
|
||||||
v-model="customConfig.display.height"
|
v-model="customConfig.display.height"
|
||||||
:min="128"
|
:min="128"
|
||||||
:max="600"
|
:max="600"
|
||||||
:placeholder="240"
|
placeholder="240"
|
||||||
@change="handleCustomConfigChange"
|
@change="handleCustomConfigChange"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -1,42 +1,161 @@
|
||||||
<template>
|
<template>
|
||||||
<el-dialog
|
<el-dialog
|
||||||
:visible.sync="dialogVisible"
|
:visible.sync="dialogVisible"
|
||||||
width="520px"
|
width="700px"
|
||||||
:title="$t('device.customThemeGenerateModalTitle')"
|
:title="$t('device.customThemeGenerateModalTitle')"
|
||||||
:close-on-click-modal="false"
|
:close-on-click-modal="false"
|
||||||
|
:close-on-press-escape="true"
|
||||||
|
:modal-append-to-body="true"
|
||||||
|
:append-to-body="true"
|
||||||
|
:lock-scroll="true"
|
||||||
@close="handleClose"
|
@close="handleClose"
|
||||||
|
custom-class="generate-modal-dialog"
|
||||||
>
|
>
|
||||||
<div class="progress-body">
|
<!-- 第一步:配置确认页面 -->
|
||||||
<div class="progress-row">
|
<div v-if="!isGenerating && !isCompleted" class="config-confirm-page">
|
||||||
<el-progress :percentage="progress" :status="validStatus"></el-progress>
|
<!-- 配置确认 -->
|
||||||
|
<div class="config-section">
|
||||||
|
<h4 class="section-title">请确认您的配置</h4>
|
||||||
|
<div class="config-info-box">
|
||||||
|
<div class="config-item">
|
||||||
|
<span class="config-label">芯片型号:</span>
|
||||||
|
<span class="config-value">{{ getChipModel() }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="config-item">
|
||||||
|
<span class="config-label">分辨率:</span>
|
||||||
|
<span class="config-value">{{ getResolution() }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="config-item">
|
||||||
|
<span class="config-label">唤醒词:</span>
|
||||||
|
<span class="config-value">{{ getWakewordName() }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="config-item">
|
||||||
|
<span class="config-label">字体:</span>
|
||||||
|
<span class="config-value">{{ getFontName() }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="config-item">
|
||||||
|
<span class="config-label">表情包:</span>
|
||||||
|
<span class="config-value">{{ getEmojiName() }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="progress-steps">
|
|
||||||
|
<!-- 文件列表 -->
|
||||||
|
<div class="file-list-section">
|
||||||
|
<h4 class="section-title">包含的文件列表</h4>
|
||||||
|
<div class="file-list-container">
|
||||||
|
<div
|
||||||
|
v-for="item in fileList"
|
||||||
|
:key="item.id"
|
||||||
|
class="file-item"
|
||||||
|
>
|
||||||
|
<div class="file-info-left">
|
||||||
|
<i :class="item.iconClass" :style="{ color: item.iconColor }"></i>
|
||||||
|
<span class="file-name">{{ item.name }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="file-size">
|
||||||
|
{{ item.size }}
|
||||||
|
<span v-if="item.estimated" class="estimated">预估</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 第二步:生成进度页面 -->
|
||||||
|
<div v-if="isGenerating" class="generating-page">
|
||||||
|
<div class="loading-spinner-container">
|
||||||
|
<div class="loading-spinner"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="progress-section">
|
||||||
|
<p class="progress-title">正在生成 assets.bin</p>
|
||||||
|
<div class="progress-bar-container">
|
||||||
|
<div
|
||||||
|
class="progress-bar-fill"
|
||||||
|
:style="{ width: progress + '%' }"
|
||||||
|
></div>
|
||||||
|
</div>
|
||||||
|
<div class="progress-info">
|
||||||
|
<div class="current-step">{{ currentStep }}</div>
|
||||||
|
<div class="progress-percent">{{ progress }}% 完成</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 进度步骤列表 -->
|
||||||
|
<div class="progress-steps-list">
|
||||||
<div
|
<div
|
||||||
v-for="step in progressSteps"
|
v-for="step in progressSteps"
|
||||||
:key="step.id"
|
:key="step.id"
|
||||||
class="step"
|
class="progress-step-item"
|
||||||
:class="step.status"
|
|
||||||
>
|
>
|
||||||
<span class="dot"></span>
|
<div class="step-icon">
|
||||||
<span>{{ step.name }}</span>
|
<i v-if="step.status === 'completed'" class="el-icon-check step-check-icon"></i>
|
||||||
|
<div v-else-if="step.status === 'processing'" class="step-processing-dot"></div>
|
||||||
|
<div v-else class="step-pending-dot"></div>
|
||||||
|
</div>
|
||||||
|
<span :class="[
|
||||||
|
'step-name',
|
||||||
|
step.status === 'completed' ? 'step-completed' :
|
||||||
|
step.status === 'processing' ? 'step-processing' :
|
||||||
|
'step-pending'
|
||||||
|
]">{{ step.name }}</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="file-info" v-if="isCompleted">
|
</div>
|
||||||
<div>{{ $t('device.customThemeFileName') }}: assets.bin</div>
|
|
||||||
<div>{{ $t('device.customThemeFileSize') }}: {{ generatedFileSize }}</div>
|
<!-- 第三步:完成页面 -->
|
||||||
<div>{{ $t('device.customThemeGenerateTime') }}: {{ generationTime }}</div>
|
<div v-if="isCompleted && !isGenerating" class="completed-page">
|
||||||
|
<div class="success-icon">
|
||||||
|
<i class="el-icon-success"></i>
|
||||||
|
</div>
|
||||||
|
<div class="success-text">assets.bin 已生成完成</div>
|
||||||
|
<div class="result-box">
|
||||||
|
<div class="result-item">文件名: assets.bin</div>
|
||||||
|
<div class="result-item">文件大小: {{ generatedFileSize }}</div>
|
||||||
|
<div class="result-item">生成时间: {{ generationTime }}</div>
|
||||||
|
</div>
|
||||||
|
<div class="action-buttons column">
|
||||||
|
<el-button type="primary" @click="downloadFile" :disabled="!generatedBlob" class="action-btn">
|
||||||
|
下载 assets.bin
|
||||||
|
</el-button>
|
||||||
|
<el-button @click="startOnlineFlash" :disabled="!generatedBlob" class="action-btn secondary">
|
||||||
|
在线烧录到设备
|
||||||
|
</el-button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div slot="footer" class="dialog-footer">
|
|
||||||
<el-button @click="handleClose" v-if="!isGenerating">{{ $t('device.customThemeClose') }}</el-button>
|
<!-- 底部按钮 -->
|
||||||
<el-button type="primary" :disabled="isGenerating" @click="handleDownload" v-if="isCompleted">
|
<div slot="footer" class="dialog-footer" v-if="!isGenerating && !isCompleted">
|
||||||
{{ $t('device.customThemeDownload') }}
|
<el-button @click="handleClose">
|
||||||
|
取消
|
||||||
|
</el-button>
|
||||||
|
<el-button
|
||||||
|
type="primary"
|
||||||
|
@click="startGeneration"
|
||||||
|
:disabled="!hasSelectedFiles"
|
||||||
|
>
|
||||||
|
开始生成
|
||||||
</el-button>
|
</el-button>
|
||||||
</div>
|
</div>
|
||||||
</el-dialog>
|
</el-dialog>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
|
// 延迟导入 AssetsBuilder,避免组件加载时出错
|
||||||
|
let AssetsBuilder = null;
|
||||||
|
const loadAssetsBuilder = async () => {
|
||||||
|
if (!AssetsBuilder) {
|
||||||
|
try {
|
||||||
|
const module = await import('@/utils/AssetsBuilder.js');
|
||||||
|
AssetsBuilder = module.default || module;
|
||||||
|
} catch (error) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return AssetsBuilder;
|
||||||
|
};
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
name: 'CustomThemeGenerateModal',
|
name: 'CustomThemeGenerateModal',
|
||||||
props: {
|
props: {
|
||||||
|
|
@ -46,18 +165,46 @@ export default {
|
||||||
},
|
},
|
||||||
config: {
|
config: {
|
||||||
type: Object,
|
type: Object,
|
||||||
required: true
|
default: () => ({
|
||||||
|
chip: {
|
||||||
|
model: '',
|
||||||
|
display: { width: 320, height: 240, color: 'RGB565' },
|
||||||
|
preset: ''
|
||||||
|
},
|
||||||
|
theme: {
|
||||||
|
wakeword: '',
|
||||||
|
font: { type: 'preset', preset: '', custom: { file: null, name: '', size: 16, bpp: 4 } },
|
||||||
|
emoji: { type: 'preset', preset: '', custom: { images: {}, size: { width: 32, height: 32 } } },
|
||||||
|
skin: {
|
||||||
|
light: { backgroundType: 'color', backgroundColor: '#ffffff', textColor: '#000000', backgroundImage: '' },
|
||||||
|
dark: { backgroundType: 'color', backgroundColor: '#121212', textColor: '#ffffff', backgroundImage: '' }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
data() {
|
data() {
|
||||||
return {
|
return {
|
||||||
isGenerating: false,
|
isGenerating: false,
|
||||||
isCompleted: false,
|
isCompleted: false,
|
||||||
|
fileList: [],
|
||||||
progress: 0,
|
progress: 0,
|
||||||
progressStatus: null,
|
currentStep: '',
|
||||||
generatedFileSize: '0 KB',
|
generationStartTime: null,
|
||||||
|
generatedBlob: null,
|
||||||
|
generatedFileSize: '',
|
||||||
generationTime: '',
|
generationTime: '',
|
||||||
progressSteps: []
|
deviceOnline: false,
|
||||||
|
progressSteps: [
|
||||||
|
{ id: 1, name: '初始化生成器', status: 'pending' },
|
||||||
|
{ id: 2, name: '处理字体文件', status: 'pending' },
|
||||||
|
{ id: 3, name: '打包唤醒词模型', status: 'pending' },
|
||||||
|
{ id: 4, name: '处理表情图片', status: 'pending' },
|
||||||
|
{ id: 5, name: '处理背景图片', status: 'pending' },
|
||||||
|
{ id: 6, name: '生成索引文件', status: 'pending' },
|
||||||
|
{ id: 7, name: '构建SPIFFS映射', status: 'pending' },
|
||||||
|
{ id: 8, name: '完成打包', status: 'pending' }
|
||||||
|
]
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
computed: {
|
computed: {
|
||||||
|
|
@ -69,17 +216,29 @@ export default {
|
||||||
this.$emit('update:visible', val);
|
this.$emit('update:visible', val);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
validStatus() {
|
hasSelectedFiles() {
|
||||||
return this.progressStatus && ['success', 'exception', 'warning', 'text'].includes(this.progressStatus)
|
return this.fileList.length > 0;
|
||||||
? this.progressStatus
|
}
|
||||||
: undefined;
|
},
|
||||||
|
mounted() {
|
||||||
|
if (this.visible) {
|
||||||
|
this.resetState();
|
||||||
|
this.initializeFileList();
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
watch: {
|
watch: {
|
||||||
visible(newVal) {
|
visible(newVal) {
|
||||||
if (newVal) {
|
if (newVal) {
|
||||||
this.resetState();
|
this.resetState();
|
||||||
this.$nextTick(this.startGenerate);
|
this.initializeFileList();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
config: {
|
||||||
|
deep: true,
|
||||||
|
handler() {
|
||||||
|
if (this.visible) {
|
||||||
|
this.initializeFileList();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
@ -87,89 +246,591 @@ export default {
|
||||||
resetState() {
|
resetState() {
|
||||||
this.isGenerating = false;
|
this.isGenerating = false;
|
||||||
this.isCompleted = false;
|
this.isCompleted = false;
|
||||||
|
this.fileList = [];
|
||||||
this.progress = 0;
|
this.progress = 0;
|
||||||
this.progressStatus = null;
|
this.currentStep = '';
|
||||||
|
this.generationStartTime = null;
|
||||||
this.progressSteps = [
|
this.progressSteps = [
|
||||||
{ id: 1, name: this.$t('device.customThemeStep1'), status: 'pending' },
|
{ id: 1, name: '初始化生成器', status: 'pending' },
|
||||||
{ id: 2, name: this.$t('device.customThemeStep2'), status: 'pending' },
|
{ id: 2, name: '处理字体文件', status: 'pending' },
|
||||||
{ id: 3, name: this.$t('device.customThemeStep3'), status: 'pending' }
|
{ id: 3, name: '打包唤醒词模型', status: 'pending' },
|
||||||
|
{ id: 4, name: '处理表情图片', status: 'pending' },
|
||||||
|
{ id: 5, name: '处理背景图片', status: 'pending' },
|
||||||
|
{ id: 6, name: '生成索引文件', status: 'pending' },
|
||||||
|
{ id: 7, name: '构建SPIFFS映射', status: 'pending' },
|
||||||
|
{ id: 8, name: '完成打包', status: 'pending' }
|
||||||
];
|
];
|
||||||
},
|
},
|
||||||
startGenerate() {
|
getChipModel() {
|
||||||
this.isGenerating = true;
|
if (!this.config || !this.config.chip || !this.config.chip.model) {
|
||||||
this.simulate();
|
return '未配置';
|
||||||
|
}
|
||||||
|
return this.config.chip.model.toUpperCase();
|
||||||
},
|
},
|
||||||
simulate() {
|
getResolution() {
|
||||||
let idx = 0;
|
if (!this.config || !this.config.chip || !this.config.chip.display) {
|
||||||
const run = () => {
|
return '未配置';
|
||||||
if (idx >= this.progressSteps.length) {
|
}
|
||||||
this.isGenerating = false;
|
return `${this.config.chip.display.width}×${this.config.chip.display.height}`;
|
||||||
this.isCompleted = true;
|
},
|
||||||
this.progress = 100;
|
getWakewordName() {
|
||||||
this.progressStatus = 'success';
|
if (!this.config || !this.config.theme || !this.config.theme.wakeword) {
|
||||||
this.generatedFileSize = '2.5 MB';
|
return '未配置';
|
||||||
this.generationTime = new Date().toLocaleString('zh-CN');
|
}
|
||||||
return;
|
const names = {
|
||||||
}
|
'wn9s_alexa': 'Alexa',
|
||||||
this.$set(this.progressSteps, idx, { ...this.progressSteps[idx], status: 'processing' });
|
'wn9s_hiesp': 'Hi,ESP',
|
||||||
this.progress = Math.round(((idx + 1) / this.progressSteps.length) * 100);
|
'wn9s_hijason': 'Hi,Jason',
|
||||||
setTimeout(() => {
|
'wn9s_hilexin': 'Hi,乐鑫',
|
||||||
this.$set(this.progressSteps, idx, { ...this.progressSteps[idx], status: 'completed' });
|
'wn9s_nihaoxiaozhi': '你好小智',
|
||||||
idx += 1;
|
'wn7_xiaoaitongxue': '小爱同学'
|
||||||
run();
|
|
||||||
}, 800);
|
|
||||||
};
|
};
|
||||||
run();
|
return names[this.config.theme.wakeword] || this.config.theme.wakeword || '未配置';
|
||||||
},
|
},
|
||||||
handleDownload() {
|
getFontName() {
|
||||||
this.$message.success('assets.bin');
|
if (!this.config || !this.config.theme || !this.config.theme.font) {
|
||||||
|
return '未配置';
|
||||||
|
}
|
||||||
|
if (this.config.theme.font.type === 'preset') {
|
||||||
|
const preset = this.config.theme.font.preset || '';
|
||||||
|
const presetNames = {
|
||||||
|
'font_puhui_deepseek_14_1': '普惠体 14px',
|
||||||
|
'font_puhui_deepseek_16_4': '普惠体 16px',
|
||||||
|
'font_puhui_deepseek_20_4': '普惠体 20px',
|
||||||
|
'font_puhui_deepseek_30_4': '普惠体 30px'
|
||||||
|
};
|
||||||
|
return presetNames[preset] || preset || '未配置';
|
||||||
|
} else {
|
||||||
|
const custom = this.config.theme.font.custom;
|
||||||
|
if (custom && custom.size) {
|
||||||
|
return `自定义字体 ${custom.size}px`;
|
||||||
|
}
|
||||||
|
return '自定义字体';
|
||||||
|
}
|
||||||
|
},
|
||||||
|
getEmojiName() {
|
||||||
|
if (!this.config || !this.config.theme || !this.config.theme.emoji) {
|
||||||
|
return '未配置';
|
||||||
|
}
|
||||||
|
if (this.config.theme.emoji.type === 'preset' && this.config.theme.emoji.preset) {
|
||||||
|
return this.config.theme.emoji.preset === 'twemoji64' ? 'Twemoji 64×64' : 'Twemoji 32×32';
|
||||||
|
} else if (this.config.theme.emoji.type === 'custom') {
|
||||||
|
const count = Object.keys(this.config.theme.emoji.custom.images || {}).length;
|
||||||
|
return count > 0 ? `自定义表情 ${count}张` : '未配置';
|
||||||
|
}
|
||||||
|
return '未配置';
|
||||||
|
},
|
||||||
|
initializeFileList() {
|
||||||
|
this.fileList = [];
|
||||||
|
|
||||||
|
// 添加索引文件
|
||||||
|
this.fileList.push({
|
||||||
|
id: 'index',
|
||||||
|
name: 'index.json',
|
||||||
|
iconClass: 'el-icon-document',
|
||||||
|
iconColor: '#409eff',
|
||||||
|
size: '1KB'
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!this.config || !this.config.theme) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 添加唤醒词模型
|
||||||
|
if (this.config.theme.wakeword) {
|
||||||
|
this.fileList.push({
|
||||||
|
id: 'srmodels',
|
||||||
|
name: 'srmodels.bin',
|
||||||
|
iconClass: 'el-icon-microphone',
|
||||||
|
iconColor: '#67c23a',
|
||||||
|
size: '~2.1MB'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 添加字体文件
|
||||||
|
if (this.config.theme.font && this.config.theme.font.type === 'preset') {
|
||||||
|
const fontSizes = {
|
||||||
|
'font_puhui_deepseek_14_1': '180KB',
|
||||||
|
'font_puhui_deepseek_16_4': '720KB',
|
||||||
|
'font_puhui_deepseek_20_4': '1.1MB',
|
||||||
|
'font_puhui_deepseek_30_4': '2.5MB'
|
||||||
|
};
|
||||||
|
const preset = this.config.theme.font.preset || '';
|
||||||
|
this.fileList.push({
|
||||||
|
id: 'font',
|
||||||
|
name: `${preset}.bin`,
|
||||||
|
iconClass: 'el-icon-edit-outline',
|
||||||
|
iconColor: '#e6a23c',
|
||||||
|
size: fontSizes[preset] || '500KB'
|
||||||
|
});
|
||||||
|
} else if (this.config.theme.font && this.config.theme.font.custom && this.config.theme.font.custom.file) {
|
||||||
|
const custom = this.config.theme.font.custom;
|
||||||
|
const estimatedSize = Math.max(100, custom.size * custom.size * custom.bpp * 0.1);
|
||||||
|
this.fileList.push({
|
||||||
|
id: 'font',
|
||||||
|
name: `font_custom_${custom.size}_${custom.bpp}.bin`,
|
||||||
|
iconClass: 'el-icon-edit-outline',
|
||||||
|
iconColor: '#e6a23c',
|
||||||
|
size: estimatedSize > 1024 ? `${(estimatedSize/1024).toFixed(1)}MB` : `${Math.round(estimatedSize)}KB`,
|
||||||
|
estimated: true
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 添加表情文件
|
||||||
|
if (this.config.theme.emoji && this.config.theme.emoji.type === 'preset' && this.config.theme.emoji.preset) {
|
||||||
|
const emotionList = ['neutral', 'happy', 'laughing', 'funny', 'sad', 'angry', 'crying', 'loving', 'embarrassed', 'surprised', 'shocked', 'thinking', 'winking', 'cool', 'relaxed', 'delicious', 'kissy', 'confident', 'sleepy', 'silly', 'confused'];
|
||||||
|
const size = this.config.theme.emoji.preset === 'twemoji64' ? '3KB' : '1KB';
|
||||||
|
emotionList.forEach(emotion => {
|
||||||
|
this.fileList.push({
|
||||||
|
id: `emoji_${emotion}`,
|
||||||
|
name: `${emotion}.png`,
|
||||||
|
iconClass: 'el-icon-picture',
|
||||||
|
iconColor: '#f56c6c',
|
||||||
|
size: size
|
||||||
|
});
|
||||||
|
});
|
||||||
|
} else if (this.config.theme.emoji && this.config.theme.emoji.type === 'custom' && this.config.theme.emoji.custom.images) {
|
||||||
|
Object.entries(this.config.theme.emoji.custom.images).forEach(([emotion, file]) => {
|
||||||
|
if (file) {
|
||||||
|
const fileSizeKB = Math.round(file.size / 1024);
|
||||||
|
this.fileList.push({
|
||||||
|
id: `emoji_${emotion}`,
|
||||||
|
name: file.name || `${emotion}.png`,
|
||||||
|
iconClass: 'el-icon-picture',
|
||||||
|
iconColor: '#f56c6c',
|
||||||
|
size: fileSizeKB > 1024 ? `${(fileSizeKB/1024).toFixed(1)}MB` : `${fileSizeKB}KB`
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 添加背景文件
|
||||||
|
if (this.config.theme.skin && this.config.theme.skin.light &&
|
||||||
|
this.config.theme.skin.light.backgroundType === 'image' &&
|
||||||
|
this.config.theme.skin.light.backgroundImage) {
|
||||||
|
const { width, height } = this.config.chip.display || { width: 320, height: 240 };
|
||||||
|
const estimatedSize = Math.round(width * height * 2 / 1024);
|
||||||
|
this.fileList.push({
|
||||||
|
id: 'bg_light',
|
||||||
|
name: 'background_light.raw',
|
||||||
|
iconClass: 'el-icon-picture',
|
||||||
|
iconColor: '#909399',
|
||||||
|
size: estimatedSize > 1024 ? `${(estimatedSize/1024).toFixed(1)}MB` : `${estimatedSize}KB`,
|
||||||
|
estimated: true
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.config.theme.skin && this.config.theme.skin.dark &&
|
||||||
|
this.config.theme.skin.dark.backgroundType === 'image' &&
|
||||||
|
this.config.theme.skin.dark.backgroundImage) {
|
||||||
|
const { width, height } = this.config.chip.display || { width: 320, height: 240 };
|
||||||
|
const estimatedSize = Math.round(width * height * 2 / 1024);
|
||||||
|
this.fileList.push({
|
||||||
|
id: 'bg_dark',
|
||||||
|
name: 'background_dark.raw',
|
||||||
|
iconClass: 'el-icon-picture',
|
||||||
|
iconColor: '#909399',
|
||||||
|
size: estimatedSize > 1024 ? `${(estimatedSize/1024).toFixed(1)}MB` : `${estimatedSize}KB`,
|
||||||
|
estimated: true
|
||||||
|
});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
async startGeneration() {
|
||||||
|
this.isGenerating = true;
|
||||||
|
this.progress = 0;
|
||||||
|
this.generationStartTime = Date.now();
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 动态加载 AssetsBuilder
|
||||||
|
const AssetsBuilderClass = await loadAssetsBuilder();
|
||||||
|
// 创建AssetsBuilder实例
|
||||||
|
const builder = new AssetsBuilderClass();
|
||||||
|
builder.setConfig(this.config);
|
||||||
|
|
||||||
|
// 生成assets.bin
|
||||||
|
const blob = await builder.generateAssetsBin((progressPercent, message) => {
|
||||||
|
this.progress = parseInt(progressPercent);
|
||||||
|
this.currentStep = message;
|
||||||
|
|
||||||
|
// 更新进度步骤状态
|
||||||
|
const stepIndex = Math.floor(progressPercent / (100 / this.progressSteps.length));
|
||||||
|
this.progressSteps.forEach((step, index) => {
|
||||||
|
if (index < stepIndex) {
|
||||||
|
step.status = 'completed';
|
||||||
|
} else if (index === stepIndex) {
|
||||||
|
step.status = 'processing';
|
||||||
|
} else {
|
||||||
|
step.status = 'pending';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// 完成生成
|
||||||
|
this.isGenerating = false;
|
||||||
|
this.isCompleted = true;
|
||||||
|
|
||||||
|
// 标记所有步骤为完成
|
||||||
|
this.progressSteps.forEach(step => {
|
||||||
|
step.status = 'completed';
|
||||||
|
});
|
||||||
|
|
||||||
|
// 存储生成的文件用于下载
|
||||||
|
this.generatedBlob = blob;
|
||||||
|
this.generatedFileSize = this.formatFileSize(blob.size);
|
||||||
|
const endTime = Date.now();
|
||||||
|
const duration = endTime - this.generationStartTime;
|
||||||
|
this.generationTime = this.formatDuration(duration);
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('生成 assets.bin 失败:', error);
|
||||||
|
this.$message.error('生成失败: ' + (error.message || '未知错误'));
|
||||||
|
|
||||||
|
// 重置状态
|
||||||
|
this.isGenerating = false;
|
||||||
|
this.isCompleted = false;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
formatFileSize(bytes) {
|
||||||
|
if (bytes === 0) return '0 B';
|
||||||
|
const k = 1024;
|
||||||
|
const sizes = ['B', 'KB', 'MB', 'GB'];
|
||||||
|
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||||
|
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
|
||||||
|
},
|
||||||
|
formatDuration(milliseconds) {
|
||||||
|
if (milliseconds < 1000) {
|
||||||
|
return `${milliseconds}ms`;
|
||||||
|
} else if (milliseconds < 60000) {
|
||||||
|
return `${(milliseconds / 1000).toFixed(1)}s`;
|
||||||
|
} else {
|
||||||
|
const minutes = Math.floor(milliseconds / 60000);
|
||||||
|
const seconds = Math.floor((milliseconds % 60000) / 1000);
|
||||||
|
return `${minutes}m ${seconds}s`;
|
||||||
|
}
|
||||||
},
|
},
|
||||||
handleClose() {
|
handleClose() {
|
||||||
this.dialogVisible = false;
|
this.dialogVisible = false;
|
||||||
|
},
|
||||||
|
downloadFile() {
|
||||||
|
if (!this.generatedBlob) {
|
||||||
|
this.$message.error('没有可下载的文件');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const url = URL.createObjectURL(this.generatedBlob);
|
||||||
|
const a = document.createElement('a');
|
||||||
|
a.href = url;
|
||||||
|
a.download = 'assets.bin';
|
||||||
|
document.body.appendChild(a);
|
||||||
|
a.click();
|
||||||
|
document.body.removeChild(a);
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
},
|
||||||
|
startOnlineFlash() {
|
||||||
|
// 占位实现:只提示,后续按需求接入真正烧录流程
|
||||||
|
if (!this.generatedBlob) {
|
||||||
|
this.$message.error('请先生成文件');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.$message.info('在线烧录功能待接入设备联调');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
.progress-body {
|
.config-confirm-page {
|
||||||
min-height: 160px;
|
padding: 0;
|
||||||
}
|
}
|
||||||
.progress-row {
|
|
||||||
|
.config-section {
|
||||||
|
margin-bottom: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.section-title {
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 500;
|
||||||
|
color: #111827;
|
||||||
margin-bottom: 12px;
|
margin-bottom: 12px;
|
||||||
}
|
}
|
||||||
.progress-steps {
|
|
||||||
display: grid;
|
.config-info-box {
|
||||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
background: #f9fafb;
|
||||||
gap: 6px;
|
border-radius: 8px;
|
||||||
}
|
padding: 16px;
|
||||||
.step {
|
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
flex-direction: column;
|
||||||
gap: 6px;
|
gap: 8px;
|
||||||
font-size: 12px;
|
}
|
||||||
|
|
||||||
|
.config-item {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.config-label {
|
||||||
color: #6b7280;
|
color: #6b7280;
|
||||||
}
|
}
|
||||||
.step .dot {
|
|
||||||
width: 10px;
|
.config-value {
|
||||||
height: 10px;
|
font-weight: 500;
|
||||||
border-radius: 50%;
|
color: #111827;
|
||||||
background: #e5e7eb;
|
|
||||||
}
|
}
|
||||||
.step.processing .dot {
|
|
||||||
background: #f59e0b;
|
.file-list-section {
|
||||||
|
margin-top: 24px;
|
||||||
}
|
}
|
||||||
.step.completed .dot {
|
|
||||||
background: #10b981;
|
.file-list-container {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 8px;
|
||||||
|
max-height: 256px;
|
||||||
|
overflow-y: auto;
|
||||||
}
|
}
|
||||||
.file-info {
|
|
||||||
margin-top: 12px;
|
.file-item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
padding: 8px 12px;
|
||||||
|
border: 1px solid #e5e7eb;
|
||||||
|
border-radius: 6px;
|
||||||
|
background: #f9fafb;
|
||||||
|
}
|
||||||
|
|
||||||
|
.file-info-left {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.file-info-left i {
|
||||||
|
font-size: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.file-name {
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 500;
|
||||||
|
color: #111827;
|
||||||
|
}
|
||||||
|
|
||||||
|
.file-size {
|
||||||
font-size: 13px;
|
font-size: 13px;
|
||||||
color: #374151;
|
color: #374151;
|
||||||
line-height: 1.6;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.estimated {
|
||||||
|
font-size: 11px;
|
||||||
|
color: #9ca3af;
|
||||||
|
margin-left: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
.dialog-footer {
|
.dialog-footer {
|
||||||
text-align: right;
|
text-align: right;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* 生成进度页面样式 */
|
||||||
|
.generating-page {
|
||||||
|
text-align: center;
|
||||||
|
padding: 20px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.loading-spinner-container {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
margin-bottom: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.loading-spinner {
|
||||||
|
width: 64px;
|
||||||
|
height: 64px;
|
||||||
|
border: 3px solid #e5e7eb;
|
||||||
|
border-top-color: #409eff;
|
||||||
|
border-radius: 50%;
|
||||||
|
animation: spin 1s linear infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes spin {
|
||||||
|
to {
|
||||||
|
transform: rotate(360deg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.progress-section {
|
||||||
|
margin-bottom: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.progress-title {
|
||||||
|
color: #6b7280;
|
||||||
|
font-size: 14px;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.progress-bar-container {
|
||||||
|
width: 100%;
|
||||||
|
height: 8px;
|
||||||
|
background: #e5e7eb;
|
||||||
|
border-radius: 4px;
|
||||||
|
overflow: hidden;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.progress-bar-fill {
|
||||||
|
height: 100%;
|
||||||
|
background: #409eff;
|
||||||
|
border-radius: 4px;
|
||||||
|
transition: width 0.5s ease-out;
|
||||||
|
}
|
||||||
|
|
||||||
|
.progress-info {
|
||||||
|
font-size: 13px;
|
||||||
|
color: #6b7280;
|
||||||
|
}
|
||||||
|
|
||||||
|
.current-step {
|
||||||
|
margin-bottom: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.progress-percent {
|
||||||
|
margin-top: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.progress-steps-list {
|
||||||
|
text-align: left;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 8px;
|
||||||
|
margin-top: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.completed-page {
|
||||||
|
text-align: center;
|
||||||
|
padding: 24px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.success-icon {
|
||||||
|
font-size: 64px;
|
||||||
|
color: #67c23a;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.success-text {
|
||||||
|
font-size: 16px;
|
||||||
|
font-weight: 600;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
color: #2c3e50;
|
||||||
|
}
|
||||||
|
|
||||||
|
.result-box {
|
||||||
|
background: #f6ffed;
|
||||||
|
border: 1px solid #b7eb8f;
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 12px 16px;
|
||||||
|
display: inline-block;
|
||||||
|
text-align: left;
|
||||||
|
color: #3a3a3a;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.result-item + .result-item {
|
||||||
|
margin-top: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.action-buttons {
|
||||||
|
display: flex;
|
||||||
|
gap: 12px;
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.action-buttons.column {
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: stretch;
|
||||||
|
}
|
||||||
|
|
||||||
|
.action-btn {
|
||||||
|
width: 100%;
|
||||||
|
height: 40px;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.action-btn.secondary {
|
||||||
|
background: #ecf5ff;
|
||||||
|
border-color: #c6e2ff;
|
||||||
|
color: #409eff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.action-btn.secondary:hover {
|
||||||
|
background: #d9ecff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.progress-step-item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.step-icon {
|
||||||
|
flex-shrink: 0;
|
||||||
|
width: 20px;
|
||||||
|
height: 20px;
|
||||||
|
margin-right: 12px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.step-check-icon {
|
||||||
|
color: #67c23a;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.step-processing-dot {
|
||||||
|
width: 20px;
|
||||||
|
height: 20px;
|
||||||
|
background: #409eff;
|
||||||
|
border-radius: 50%;
|
||||||
|
animation: pulse 1.5s ease-in-out infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
.step-pending-dot {
|
||||||
|
width: 20px;
|
||||||
|
height: 20px;
|
||||||
|
background: #d1d5db;
|
||||||
|
border-radius: 50%;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes pulse {
|
||||||
|
0%, 100% {
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
50% {
|
||||||
|
opacity: 0.5;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.step-name {
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.step-completed {
|
||||||
|
color: #67c23a;
|
||||||
|
}
|
||||||
|
|
||||||
|
.step-processing {
|
||||||
|
color: #409eff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.step-pending {
|
||||||
|
color: #9ca3af;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.generate-modal-dialog .el-dialog__body {
|
||||||
|
padding: 24px;
|
||||||
|
max-height: calc(90vh - 140px);
|
||||||
|
overflow-y: auto;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
|
||||||
1351
main/manager-web/src/utils/AssetsBuilder.js
Normal file
1351
main/manager-web/src/utils/AssetsBuilder.js
Normal file
File diff suppressed because it is too large
Load diff
543
main/manager-web/src/utils/ConfigStorage.js
Normal file
543
main/manager-web/src/utils/ConfigStorage.js
Normal file
|
|
@ -0,0 +1,543 @@
|
||||||
|
/**
|
||||||
|
* ConfigStorage 类
|
||||||
|
* 用于管理配置和文件的 IndexedDB 存储
|
||||||
|
*
|
||||||
|
* 主要功能:
|
||||||
|
* - 存储和恢复用户配置
|
||||||
|
* - 存储和恢复用户上传的文件
|
||||||
|
* - 提供清空配置的功能
|
||||||
|
*/
|
||||||
|
|
||||||
|
class ConfigStorage {
|
||||||
|
constructor() {
|
||||||
|
this.dbName = 'XiaozhiConfigDB'
|
||||||
|
this.version = 1
|
||||||
|
this.db = null
|
||||||
|
this.initialized = false
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 初始化 IndexedDB
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
async initialize() {
|
||||||
|
if (this.initialized && this.db) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const request = indexedDB.open(this.dbName, this.version)
|
||||||
|
|
||||||
|
request.onerror = () => {
|
||||||
|
console.error('IndexedDB 初始化失败:', request.error)
|
||||||
|
reject(request.error)
|
||||||
|
}
|
||||||
|
|
||||||
|
request.onsuccess = () => {
|
||||||
|
this.db = request.result
|
||||||
|
this.initialized = true
|
||||||
|
console.log('IndexedDB 初始化成功')
|
||||||
|
resolve()
|
||||||
|
}
|
||||||
|
|
||||||
|
request.onupgradeneeded = (event) => {
|
||||||
|
const db = event.target.result
|
||||||
|
|
||||||
|
// 创建配置存储表
|
||||||
|
if (!db.objectStoreNames.contains('configs')) {
|
||||||
|
const configStore = db.createObjectStore('configs', { keyPath: 'key' })
|
||||||
|
configStore.createIndex('timestamp', 'timestamp', { unique: false })
|
||||||
|
}
|
||||||
|
|
||||||
|
// 创建文件存储表
|
||||||
|
if (!db.objectStoreNames.contains('files')) {
|
||||||
|
const fileStore = db.createObjectStore('files', { keyPath: 'id' })
|
||||||
|
fileStore.createIndex('type', 'type', { unique: false })
|
||||||
|
fileStore.createIndex('timestamp', 'timestamp', { unique: false })
|
||||||
|
}
|
||||||
|
|
||||||
|
// 创建临时存储表(用于转换后的字体等)
|
||||||
|
if (!db.objectStoreNames.contains('temp_data')) {
|
||||||
|
const tempStore = db.createObjectStore('temp_data', { keyPath: 'key' })
|
||||||
|
tempStore.createIndex('type', 'type', { unique: false })
|
||||||
|
tempStore.createIndex('timestamp', 'timestamp', { unique: false })
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('IndexedDB 表结构创建完成')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 保存配置到 IndexedDB
|
||||||
|
* @param {Object} config - 完整的配置对象
|
||||||
|
* @param {number} currentStep - 当前步骤
|
||||||
|
* @param {string} activeThemeTab - 活动的主题标签
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
async saveConfig(config, currentStep = 0, activeThemeTab = 'wakeword') {
|
||||||
|
if (!this.initialized) {
|
||||||
|
await this.initialize()
|
||||||
|
}
|
||||||
|
|
||||||
|
const sanitizedConfig = this.sanitizeConfigForStorage(config)
|
||||||
|
|
||||||
|
const configData = {
|
||||||
|
key: 'current_config',
|
||||||
|
config: sanitizedConfig, // 深拷贝并剔除不可序列化字段
|
||||||
|
currentStep,
|
||||||
|
activeThemeTab,
|
||||||
|
timestamp: Date.now()
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const transaction = this.db.transaction(['configs'], 'readwrite')
|
||||||
|
const store = transaction.objectStore('configs')
|
||||||
|
const request = store.put(configData)
|
||||||
|
|
||||||
|
request.onerror = () => {
|
||||||
|
console.error('保存配置失败:', request.error)
|
||||||
|
reject(request.error)
|
||||||
|
}
|
||||||
|
|
||||||
|
request.onsuccess = () => {
|
||||||
|
console.log('配置已保存到 IndexedDB')
|
||||||
|
resolve()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成可安全存储的配置对象
|
||||||
|
* - File/Blob 等不可序列化字段统一置为 null
|
||||||
|
* - 保留 images 的键,以便后续按键名从存储恢复
|
||||||
|
*/
|
||||||
|
sanitizeConfigForStorage(config) {
|
||||||
|
const cloned = JSON.parse(JSON.stringify(config || {}))
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 字体文件
|
||||||
|
if (cloned?.theme?.font?.type === 'custom') {
|
||||||
|
if (!cloned.theme.font.custom) cloned.theme.font.custom = {}
|
||||||
|
cloned.theme.font.custom.file = null
|
||||||
|
}
|
||||||
|
|
||||||
|
// 表情图片
|
||||||
|
if (cloned?.theme?.emoji?.type === 'custom') {
|
||||||
|
const images = cloned.theme.emoji?.custom?.images || {}
|
||||||
|
const sanitizedImages = {}
|
||||||
|
Object.keys(images).forEach((k) => {
|
||||||
|
// 无论反序列化为何形态,都统一置为 null,表示待恢复
|
||||||
|
sanitizedImages[k] = null
|
||||||
|
})
|
||||||
|
if (!cloned.theme.emoji.custom) cloned.theme.emoji.custom = {}
|
||||||
|
cloned.theme.emoji.custom.images = sanitizedImages
|
||||||
|
}
|
||||||
|
|
||||||
|
// 背景图片
|
||||||
|
if (cloned?.theme?.skin?.light) {
|
||||||
|
cloned.theme.skin.light.backgroundImage = null
|
||||||
|
}
|
||||||
|
if (cloned?.theme?.skin?.dark) {
|
||||||
|
cloned.theme.skin.dark.backgroundImage = null
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
// 忽略清理异常,返回已克隆对象
|
||||||
|
}
|
||||||
|
|
||||||
|
return cloned
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从 IndexedDB 恢复配置
|
||||||
|
* @returns {Promise<Object|null>} 配置数据或null
|
||||||
|
*/
|
||||||
|
async loadConfig() {
|
||||||
|
if (!this.initialized) {
|
||||||
|
await this.initialize()
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const transaction = this.db.transaction(['configs'], 'readonly')
|
||||||
|
const store = transaction.objectStore('configs')
|
||||||
|
const request = store.get('current_config')
|
||||||
|
|
||||||
|
request.onerror = () => {
|
||||||
|
console.error('加载配置失败:', request.error)
|
||||||
|
reject(request.error)
|
||||||
|
}
|
||||||
|
|
||||||
|
request.onsuccess = () => {
|
||||||
|
const result = request.result
|
||||||
|
if (result) {
|
||||||
|
console.log('从 IndexedDB 恢复配置成功')
|
||||||
|
resolve({
|
||||||
|
config: result.config,
|
||||||
|
currentStep: result.currentStep || 0,
|
||||||
|
activeThemeTab: result.activeThemeTab || 'wakeword',
|
||||||
|
timestamp: result.timestamp
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
resolve(null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 保存文件到 IndexedDB
|
||||||
|
* @param {string} id - 文件ID
|
||||||
|
* @param {File} file - 文件对象
|
||||||
|
* @param {string} type - 文件类型 (font, emoji, background)
|
||||||
|
* @param {Object} metadata - 额外的元数据
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
async saveFile(id, file, type, metadata = {}) {
|
||||||
|
if (!this.initialized) {
|
||||||
|
await this.initialize()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 将文件转换为 ArrayBuffer 以便存储
|
||||||
|
const arrayBuffer = await this.fileToArrayBuffer(file)
|
||||||
|
|
||||||
|
// 确保 metadata 可被结构化克隆(去除 Proxy/Ref/循环等)
|
||||||
|
let safeMetadata = {}
|
||||||
|
try {
|
||||||
|
safeMetadata = metadata ? JSON.parse(JSON.stringify(metadata)) : {}
|
||||||
|
} catch (e) {
|
||||||
|
// 回退为浅拷贝的纯对象
|
||||||
|
safeMetadata = { ...metadata }
|
||||||
|
}
|
||||||
|
|
||||||
|
const fileData = {
|
||||||
|
id,
|
||||||
|
type,
|
||||||
|
name: file.name,
|
||||||
|
size: file.size,
|
||||||
|
mimeType: file.type,
|
||||||
|
lastModified: file.lastModified,
|
||||||
|
data: arrayBuffer,
|
||||||
|
metadata: safeMetadata,
|
||||||
|
timestamp: Date.now()
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const transaction = this.db.transaction(['files'], 'readwrite')
|
||||||
|
const store = transaction.objectStore('files')
|
||||||
|
const request = store.put(fileData)
|
||||||
|
|
||||||
|
request.onerror = () => {
|
||||||
|
console.error('保存文件失败:', request.error)
|
||||||
|
reject(request.error)
|
||||||
|
}
|
||||||
|
|
||||||
|
request.onsuccess = () => {
|
||||||
|
console.log(`文件 ${file.name} 已保存到 IndexedDB`)
|
||||||
|
resolve()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从 IndexedDB 加载文件
|
||||||
|
* @param {string} id - 文件ID
|
||||||
|
* @returns {Promise<File|null>} 文件对象或null
|
||||||
|
*/
|
||||||
|
async loadFile(id) {
|
||||||
|
if (!this.initialized) {
|
||||||
|
await this.initialize()
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const transaction = this.db.transaction(['files'], 'readonly')
|
||||||
|
const store = transaction.objectStore('files')
|
||||||
|
const request = store.get(id)
|
||||||
|
|
||||||
|
request.onerror = () => {
|
||||||
|
console.error('加载文件失败:', request.error)
|
||||||
|
reject(request.error)
|
||||||
|
}
|
||||||
|
|
||||||
|
request.onsuccess = () => {
|
||||||
|
const result = request.result
|
||||||
|
if (result) {
|
||||||
|
// 将 ArrayBuffer 转换回 File 对象
|
||||||
|
const blob = new Blob([result.data], { type: result.mimeType })
|
||||||
|
const file = new File([blob], result.name, {
|
||||||
|
type: result.mimeType,
|
||||||
|
lastModified: result.lastModified
|
||||||
|
})
|
||||||
|
|
||||||
|
// 添加额外的元数据
|
||||||
|
file.storedId = result.id
|
||||||
|
file.storedType = result.type
|
||||||
|
file.storedMetadata = result.metadata
|
||||||
|
file.storedTimestamp = result.timestamp
|
||||||
|
|
||||||
|
console.log(`文件 ${result.name} 从 IndexedDB 恢复成功`)
|
||||||
|
resolve(file)
|
||||||
|
} else {
|
||||||
|
resolve(null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取指定类型的所有文件
|
||||||
|
* @param {string} type - 文件类型
|
||||||
|
* @returns {Promise<Array>} 文件列表
|
||||||
|
*/
|
||||||
|
async getFilesByType(type) {
|
||||||
|
if (!this.initialized) {
|
||||||
|
await this.initialize()
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const transaction = this.db.transaction(['files'], 'readonly')
|
||||||
|
const store = transaction.objectStore('files')
|
||||||
|
const index = store.index('type')
|
||||||
|
const request = index.getAll(type)
|
||||||
|
|
||||||
|
request.onerror = () => {
|
||||||
|
console.error('获取文件列表失败:', request.error)
|
||||||
|
reject(request.error)
|
||||||
|
}
|
||||||
|
|
||||||
|
request.onsuccess = () => {
|
||||||
|
const results = request.result || []
|
||||||
|
const files = results.map(result => {
|
||||||
|
const blob = new Blob([result.data], { type: result.mimeType })
|
||||||
|
const file = new File([blob], result.name, {
|
||||||
|
type: result.mimeType,
|
||||||
|
lastModified: result.lastModified
|
||||||
|
})
|
||||||
|
|
||||||
|
file.storedId = result.id
|
||||||
|
file.storedType = result.type
|
||||||
|
file.storedMetadata = result.metadata
|
||||||
|
file.storedTimestamp = result.timestamp
|
||||||
|
|
||||||
|
return file
|
||||||
|
})
|
||||||
|
|
||||||
|
resolve(files)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 保存临时数据(如转换后的字体等)
|
||||||
|
* @param {string} key - 数据键
|
||||||
|
* @param {ArrayBuffer} data - 数据
|
||||||
|
* @param {string} type - 数据类型
|
||||||
|
* @param {Object} metadata - 元数据
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
async saveTempData(key, data, type, metadata = {}) {
|
||||||
|
if (!this.initialized) {
|
||||||
|
await this.initialize()
|
||||||
|
}
|
||||||
|
|
||||||
|
const tempData = {
|
||||||
|
key,
|
||||||
|
type,
|
||||||
|
data,
|
||||||
|
metadata,
|
||||||
|
timestamp: Date.now()
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const transaction = this.db.transaction(['temp_data'], 'readwrite')
|
||||||
|
const store = transaction.objectStore('temp_data')
|
||||||
|
const request = store.put(tempData)
|
||||||
|
|
||||||
|
request.onerror = () => {
|
||||||
|
console.error('保存临时数据失败:', request.error)
|
||||||
|
reject(request.error)
|
||||||
|
}
|
||||||
|
|
||||||
|
request.onsuccess = () => {
|
||||||
|
console.log(`临时数据 ${key} 已保存`)
|
||||||
|
resolve()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 加载临时数据
|
||||||
|
* @param {string} key - 数据键
|
||||||
|
* @returns {Promise<Object|null>} 临时数据或null
|
||||||
|
*/
|
||||||
|
async loadTempData(key) {
|
||||||
|
if (!this.initialized) {
|
||||||
|
await this.initialize()
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const transaction = this.db.transaction(['temp_data'], 'readonly')
|
||||||
|
const store = transaction.objectStore('temp_data')
|
||||||
|
const request = store.get(key)
|
||||||
|
|
||||||
|
request.onerror = () => {
|
||||||
|
console.error('加载临时数据失败:', request.error)
|
||||||
|
reject(request.error)
|
||||||
|
}
|
||||||
|
|
||||||
|
request.onsuccess = () => {
|
||||||
|
const result = request.result
|
||||||
|
resolve(result || null)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清空所有存储的数据
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
async clearAll() {
|
||||||
|
if (!this.initialized) {
|
||||||
|
await this.initialize()
|
||||||
|
}
|
||||||
|
|
||||||
|
const storeNames = ['configs', 'files', 'temp_data']
|
||||||
|
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const transaction = this.db.transaction(storeNames, 'readwrite')
|
||||||
|
let completedStores = 0
|
||||||
|
let hasError = false
|
||||||
|
|
||||||
|
const checkComplete = () => {
|
||||||
|
completedStores++
|
||||||
|
if (completedStores === storeNames.length) {
|
||||||
|
if (hasError) {
|
||||||
|
reject(new Error('清空部分数据时出现错误'))
|
||||||
|
} else {
|
||||||
|
console.log('所有存储数据已清空')
|
||||||
|
resolve()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
storeNames.forEach(storeName => {
|
||||||
|
const store = transaction.objectStore(storeName)
|
||||||
|
const request = store.clear()
|
||||||
|
|
||||||
|
request.onerror = () => {
|
||||||
|
console.error(`清空 ${storeName} 失败:`, request.error)
|
||||||
|
hasError = true
|
||||||
|
checkComplete()
|
||||||
|
}
|
||||||
|
|
||||||
|
request.onsuccess = () => {
|
||||||
|
console.log(`${storeName} 已清空`)
|
||||||
|
checkComplete()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 删除指定文件
|
||||||
|
* @param {string} id - 文件ID
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
async deleteFile(id) {
|
||||||
|
if (!this.initialized) {
|
||||||
|
await this.initialize()
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const transaction = this.db.transaction(['files'], 'readwrite')
|
||||||
|
const store = transaction.objectStore('files')
|
||||||
|
const request = store.delete(id)
|
||||||
|
|
||||||
|
request.onerror = () => {
|
||||||
|
console.error('删除文件失败:', request.error)
|
||||||
|
reject(request.error)
|
||||||
|
}
|
||||||
|
|
||||||
|
request.onsuccess = () => {
|
||||||
|
console.log(`文件 ${id} 已删除`)
|
||||||
|
resolve()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取存储使用情况
|
||||||
|
* @returns {Promise<Object>} 存储统计信息
|
||||||
|
*/
|
||||||
|
async getStorageInfo() {
|
||||||
|
if (!this.initialized) {
|
||||||
|
await this.initialize()
|
||||||
|
}
|
||||||
|
|
||||||
|
const storeNames = ['configs', 'files', 'temp_data']
|
||||||
|
const info = {}
|
||||||
|
|
||||||
|
for (const storeName of storeNames) {
|
||||||
|
const count = await new Promise((resolve, reject) => {
|
||||||
|
const transaction = this.db.transaction([storeName], 'readonly')
|
||||||
|
const store = transaction.objectStore(storeName)
|
||||||
|
const request = store.count()
|
||||||
|
|
||||||
|
request.onerror = () => reject(request.error)
|
||||||
|
request.onsuccess = () => resolve(request.result)
|
||||||
|
})
|
||||||
|
|
||||||
|
info[storeName] = { count }
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取上次保存配置的时间
|
||||||
|
const configData = await this.loadConfig()
|
||||||
|
info.lastSaved = configData ? new Date(configData.timestamp) : null
|
||||||
|
|
||||||
|
return info
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查是否有存储的配置
|
||||||
|
* @returns {Promise<boolean>}
|
||||||
|
*/
|
||||||
|
async hasStoredConfig() {
|
||||||
|
try {
|
||||||
|
const config = await this.loadConfig()
|
||||||
|
return config !== null
|
||||||
|
} catch (error) {
|
||||||
|
console.error('检查存储配置时出错:', error)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将文件转换为 ArrayBuffer
|
||||||
|
* @param {File} file - 文件对象
|
||||||
|
* @returns {Promise<ArrayBuffer>}
|
||||||
|
*/
|
||||||
|
fileToArrayBuffer(file) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const reader = new FileReader()
|
||||||
|
reader.onload = () => resolve(reader.result)
|
||||||
|
reader.onerror = () => reject(new Error('读取文件失败'))
|
||||||
|
reader.readAsArrayBuffer(file)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 关闭数据库连接
|
||||||
|
*/
|
||||||
|
close() {
|
||||||
|
if (this.db) {
|
||||||
|
this.db.close()
|
||||||
|
this.db = null
|
||||||
|
this.initialized = false
|
||||||
|
console.log('IndexedDB 连接已关闭')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 创建单例实例
|
||||||
|
const configStorage = new ConfigStorage()
|
||||||
|
|
||||||
|
export default configStorage
|
||||||
663
main/manager-web/src/utils/GifScaler.js
Normal file
663
main/manager-web/src/utils/GifScaler.js
Normal file
|
|
@ -0,0 +1,663 @@
|
||||||
|
/**
|
||||||
|
* GifScaler 类
|
||||||
|
* 用于对 GIF 表情进行缩放处理
|
||||||
|
*
|
||||||
|
* 主要功能:
|
||||||
|
* - 解析 GIF 文件的每一帧
|
||||||
|
* - 对每一帧进行缩放处理
|
||||||
|
* - 重新生成缩放后的 GIF 文件
|
||||||
|
* - 支持保持原始动画时序
|
||||||
|
*
|
||||||
|
* 依赖建议:
|
||||||
|
* 为了支持完整的多帧 GIF 处理,建议安装以下依赖:
|
||||||
|
* ```bash
|
||||||
|
* npm install gif.js gifuct-js
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* 使用示例:
|
||||||
|
* ```javascript
|
||||||
|
* const scaler = new GifScaler({
|
||||||
|
* quality: 10,
|
||||||
|
* debug: true,
|
||||||
|
* scalingMode: 'auto', // 'auto', 'smooth', 'sharp', 'pixelated'
|
||||||
|
* workers: 2, // 使用 2 个 worker 线程进行并行处理
|
||||||
|
* workerScript: '/share/gif.worker.js' // Worker 脚本路径
|
||||||
|
* })
|
||||||
|
* const scaledGif = await scaler.scaleGif(gifFile, {
|
||||||
|
* maxWidth: 64,
|
||||||
|
* maxHeight: 64,
|
||||||
|
* keepAspectRatio: true
|
||||||
|
* })
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
// 可选依赖:如果未安装则使用降级方案
|
||||||
|
// 注意:这些依赖需要手动安装: npm install gifuct-js gif.js
|
||||||
|
let parseGIF, decompressFrames, GIF
|
||||||
|
try {
|
||||||
|
// 尝试动态导入(如果使用 ES6 modules)
|
||||||
|
if (typeof require !== 'undefined') {
|
||||||
|
try {
|
||||||
|
const gifuct = require('gifuct-js')
|
||||||
|
parseGIF = gifuct.parseGIF || gifuct.default?.parseGIF
|
||||||
|
decompressFrames = gifuct.decompressFrames || gifuct.default?.decompressFrames
|
||||||
|
} catch (e) {
|
||||||
|
console.warn('gifuct-js 未安装,GIF 处理功能将受限')
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
GIF = require('gif.js')
|
||||||
|
if (GIF && GIF.default) GIF = GIF.default
|
||||||
|
} catch (e) {
|
||||||
|
console.warn('gif.js 未安装,GIF 处理功能将受限')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.warn('GIF 依赖加载失败,GIF 处理功能将受限:', e)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class GifScaler {
|
||||||
|
constructor(options = {}) {
|
||||||
|
this.options = {
|
||||||
|
quality: options.quality || 10, // GIF 质量 (1-20, 越小质量越高)
|
||||||
|
repeat: options.repeat !== undefined ? options.repeat : -1, // 重复次数 (-1 为无限循环)
|
||||||
|
debug: options.debug || false, // 调试模式
|
||||||
|
scalingMode: options.scalingMode || 'auto', // 缩放模式: 'auto', 'smooth', 'sharp', 'pixelated'
|
||||||
|
workers: options.workers || 2, // Worker 线程数量 (1-4, 更多线程可以提高大型 GIF 的处理速度)
|
||||||
|
// 在 Vue2 + webpack 环境中没有 import.meta.env,使用浏览器 origin 作为默认前缀,避免 undefined
|
||||||
|
workerScript: options.workerScript || `${(typeof window !== 'undefined' ? window.location.origin : '')}/workers/gif.worker.js`, // Worker 脚本路径
|
||||||
|
...options
|
||||||
|
}
|
||||||
|
|
||||||
|
this.canvas = null
|
||||||
|
this.ctx = null
|
||||||
|
this.frames = []
|
||||||
|
this.delays = []
|
||||||
|
this.originalWidth = 0
|
||||||
|
this.originalHeight = 0
|
||||||
|
this.targetWidth = 0
|
||||||
|
this.targetHeight = 0
|
||||||
|
this.gifRepeat = 0 // 默认无限循环
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 初始化 Canvas 和上下文
|
||||||
|
* @param {number} width - Canvas 宽度
|
||||||
|
* @param {number} height - Canvas 高度
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
initCanvas(width, height) {
|
||||||
|
this.canvas = document.createElement('canvas')
|
||||||
|
this.canvas.width = width
|
||||||
|
this.canvas.height = height
|
||||||
|
this.ctx = this.canvas.getContext('2d')
|
||||||
|
|
||||||
|
if (this.options.debug) {
|
||||||
|
console.log(`Canvas initialized: ${width}x${height}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析 GIF 文件并提取所有帧
|
||||||
|
* @param {File|Blob} gifFile - GIF 文件
|
||||||
|
* @returns {Promise<Array>} 返回帧数据数组
|
||||||
|
*/
|
||||||
|
async parseGifFrames(gifFile) {
|
||||||
|
try {
|
||||||
|
// 只使用 gifuct-js 进行 GIF 解析
|
||||||
|
return await this.parseGifWithGifuct(gifFile)
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(`GIF 解析失败: ${error.message}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 使用 gifuct-js 进行高级 GIF 解析
|
||||||
|
* @param {File|Blob} gifFile - GIF 文件
|
||||||
|
* @returns {Promise<Array>} 返回帧数据数组
|
||||||
|
*/
|
||||||
|
async parseGifWithGifuct(gifFile) {
|
||||||
|
const arrayBuffer = await this.fileToArrayBuffer(gifFile)
|
||||||
|
const gif = parseGIF(arrayBuffer)
|
||||||
|
const frames = decompressFrames(gif, true)
|
||||||
|
|
||||||
|
this.originalWidth = gif.lsd.width
|
||||||
|
this.originalHeight = gif.lsd.height
|
||||||
|
this.frames = []
|
||||||
|
this.delays = []
|
||||||
|
|
||||||
|
// 读取原始GIF的循环信息
|
||||||
|
// 如果用户没有手动设置repeat,则使用原始GIF的循环设置
|
||||||
|
if (this.options.repeat === -1) { // 使用默认值
|
||||||
|
// gif.lsd.globalColorTableFlag, gif.applicationExtensions 等信息中可能包含循环信息
|
||||||
|
// 检查是否有 NETSCAPE2.0 应用扩展,它定义了循环次数
|
||||||
|
let originalRepeat = 0 // 0 表示无限循环
|
||||||
|
|
||||||
|
if (gif.applicationExtensions) {
|
||||||
|
const netscapeExt = gif.applicationExtensions.find(ext =>
|
||||||
|
ext.identifier === 'NETSCAPE' && ext.authenticationCode === '2.0'
|
||||||
|
)
|
||||||
|
if (netscapeExt && netscapeExt.data && netscapeExt.data.length >= 3) {
|
||||||
|
// NETSCAPE2.0 格式:[0x01, 低字节, 高字节]
|
||||||
|
originalRepeat = netscapeExt.data[1] + (netscapeExt.data[2] << 8)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.gifRepeat = originalRepeat
|
||||||
|
|
||||||
|
if (this.options.debug) {
|
||||||
|
console.log(`原始GIF循环设置: ${originalRepeat === 0 ? '无限循环' : originalRepeat + '次'}`)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
this.gifRepeat = this.options.repeat
|
||||||
|
}
|
||||||
|
|
||||||
|
// 创建主画布来处理每一帧
|
||||||
|
const canvas = document.createElement('canvas')
|
||||||
|
canvas.width = this.originalWidth
|
||||||
|
canvas.height = this.originalHeight
|
||||||
|
const ctx = canvas.getContext('2d', { willReadFrequently: true })
|
||||||
|
|
||||||
|
// 保存前一帧的图像数据(用于disposal type 3)
|
||||||
|
let previousFrameData = null
|
||||||
|
|
||||||
|
for (let i = 0; i < frames.length; i++) {
|
||||||
|
const frame = frames[i]
|
||||||
|
|
||||||
|
// 根据 disposal 方法处理画布
|
||||||
|
if (i === 0) {
|
||||||
|
// 第一帧:清除整个画布为透明
|
||||||
|
ctx.clearRect(0, 0, canvas.width, canvas.height)
|
||||||
|
} else if (frame.disposalType === 2) {
|
||||||
|
// 清除到背景色(透明)
|
||||||
|
ctx.clearRect(0, 0, canvas.width, canvas.height)
|
||||||
|
} else if (frame.disposalType === 3 && previousFrameData) {
|
||||||
|
// 恢复到前一帧状态
|
||||||
|
ctx.putImageData(previousFrameData, 0, 0)
|
||||||
|
}
|
||||||
|
// disposalType 0 和 1:不清除,保持当前内容
|
||||||
|
|
||||||
|
// 保存当前状态(用于disposalType 3)
|
||||||
|
if (frame.disposalType === 3) {
|
||||||
|
previousFrameData = ctx.getImageData(0, 0, this.originalWidth, this.originalHeight)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 创建帧画布并绘制当前帧
|
||||||
|
const frameCanvas = document.createElement('canvas')
|
||||||
|
frameCanvas.width = frame.dims.width
|
||||||
|
frameCanvas.height = frame.dims.height
|
||||||
|
const frameCtx = frameCanvas.getContext('2d', { willReadFrequently: true })
|
||||||
|
|
||||||
|
// 确保帧画布背景透明
|
||||||
|
frameCtx.clearRect(0, 0, frame.dims.width, frame.dims.height)
|
||||||
|
|
||||||
|
// 绘制帧像素数据
|
||||||
|
const imageData = new ImageData(frame.patch, frame.dims.width, frame.dims.height)
|
||||||
|
frameCtx.putImageData(imageData, 0, 0)
|
||||||
|
|
||||||
|
// 将帧绘制到主画布上
|
||||||
|
ctx.drawImage(frameCanvas, frame.dims.left || 0, frame.dims.top || 0)
|
||||||
|
|
||||||
|
// 获取完整帧的图像数据
|
||||||
|
const fullFrameImageData = ctx.getImageData(0, 0, this.originalWidth, this.originalHeight)
|
||||||
|
this.frames.push(fullFrameImageData)
|
||||||
|
this.delays.push(frame.delay || 100)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.options.debug) {
|
||||||
|
console.log(`GIF parsed (gifuct-js): ${this.originalWidth}x${this.originalHeight}, frames: ${this.frames.length}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.frames
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 缩放单个图像帧
|
||||||
|
* @param {ImageData} imageData - 源图像数据
|
||||||
|
* @param {number} targetWidth - 目标宽度
|
||||||
|
* @param {number} targetHeight - 目标高度
|
||||||
|
* @returns {ImageData} 缩放后的图像数据
|
||||||
|
*/
|
||||||
|
scaleFrame(imageData, targetWidth, targetHeight) {
|
||||||
|
const sourceCanvas = document.createElement('canvas')
|
||||||
|
const sourceCtx = sourceCanvas.getContext('2d')
|
||||||
|
sourceCanvas.width = imageData.width
|
||||||
|
sourceCanvas.height = imageData.height
|
||||||
|
|
||||||
|
// 确保源画布背景透明
|
||||||
|
sourceCtx.clearRect(0, 0, imageData.width, imageData.height)
|
||||||
|
sourceCtx.putImageData(imageData, 0, 0)
|
||||||
|
|
||||||
|
const targetCanvas = document.createElement('canvas')
|
||||||
|
const targetCtx = targetCanvas.getContext('2d', { willReadFrequently: true })
|
||||||
|
targetCanvas.width = targetWidth
|
||||||
|
targetCanvas.height = targetHeight
|
||||||
|
|
||||||
|
// 确保目标画布背景透明
|
||||||
|
targetCtx.clearRect(0, 0, targetWidth, targetHeight)
|
||||||
|
|
||||||
|
// 根据缩放模式选择不同的缩放策略
|
||||||
|
const scaleRatio = Math.min(targetWidth / imageData.width, targetHeight / imageData.height)
|
||||||
|
const scalingMode = this.getOptimalScalingMode(scaleRatio)
|
||||||
|
|
||||||
|
// 对于大幅缩放,使用特殊的多步缩放算法来减少边缘模糊
|
||||||
|
if (scaleRatio < 0.5 && scalingMode === 'pixelated') {
|
||||||
|
this.scaleWithEdgePreservation(sourceCtx, targetCtx, imageData.width, imageData.height, targetWidth, targetHeight)
|
||||||
|
} else {
|
||||||
|
this.applyScalingMode(targetCtx, scalingMode)
|
||||||
|
targetCtx.drawImage(
|
||||||
|
sourceCanvas,
|
||||||
|
0, 0, imageData.width, imageData.height,
|
||||||
|
0, 0, targetWidth, targetHeight
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return targetCtx.getImageData(0, 0, targetWidth, targetHeight)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据缩放比例获取最优的缩放模式
|
||||||
|
* @param {number} scaleRatio - 缩放比例
|
||||||
|
* @returns {string} 缩放模式
|
||||||
|
*/
|
||||||
|
getOptimalScalingMode(scaleRatio) {
|
||||||
|
if (this.options.scalingMode !== 'auto') {
|
||||||
|
return this.options.scalingMode
|
||||||
|
}
|
||||||
|
|
||||||
|
// 自动选择缩放模式
|
||||||
|
if (scaleRatio >= 0.5) {
|
||||||
|
// 缩放比例较大时,使用平滑缩放保持质量
|
||||||
|
return 'smooth'
|
||||||
|
} else if (scaleRatio >= 0.25) {
|
||||||
|
// 中等缩放比例,使用锐化缩放保持边缘清晰
|
||||||
|
return 'sharp'
|
||||||
|
} else {
|
||||||
|
// 大幅缩小时,使用像素化缩放避免模糊
|
||||||
|
return 'pixelated'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 应用指定的缩放模式
|
||||||
|
* @param {CanvasRenderingContext2D} ctx - Canvas上下文
|
||||||
|
* @param {string} mode - 缩放模式
|
||||||
|
*/
|
||||||
|
applyScalingMode(ctx, mode) {
|
||||||
|
switch (mode) {
|
||||||
|
case 'smooth':
|
||||||
|
// 平滑缩放 - 适合小幅缩放
|
||||||
|
ctx.imageSmoothingEnabled = true
|
||||||
|
ctx.imageSmoothingQuality = 'high'
|
||||||
|
break
|
||||||
|
|
||||||
|
case 'sharp':
|
||||||
|
// 锐化缩放 - 适合中等缩放,保持边缘清晰
|
||||||
|
ctx.imageSmoothingEnabled = true
|
||||||
|
ctx.imageSmoothingQuality = 'high'
|
||||||
|
break
|
||||||
|
|
||||||
|
case 'pixelated':
|
||||||
|
// 像素化缩放 - 适合大幅缩放,避免模糊
|
||||||
|
ctx.imageSmoothingEnabled = false
|
||||||
|
break
|
||||||
|
|
||||||
|
default:
|
||||||
|
// 默认平滑缩放
|
||||||
|
ctx.imageSmoothingEnabled = true
|
||||||
|
ctx.imageSmoothingQuality = 'high'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 边缘保持缩放算法 - 减少线条变粗的问题
|
||||||
|
* @param {CanvasRenderingContext2D} sourceCtx - 源Canvas上下文
|
||||||
|
* @param {CanvasRenderingContext2D} targetCtx - 目标Canvas上下文
|
||||||
|
* @param {number} sourceWidth - 源宽度
|
||||||
|
* @param {number} sourceHeight - 源高度
|
||||||
|
* @param {number} targetWidth - 目标宽度
|
||||||
|
* @param {number} targetHeight - 目标高度
|
||||||
|
*/
|
||||||
|
scaleWithEdgePreservation(sourceCtx, targetCtx, sourceWidth, sourceHeight, targetWidth, targetHeight) {
|
||||||
|
const scaleRatio = Math.min(targetWidth / sourceWidth, targetHeight / sourceHeight)
|
||||||
|
|
||||||
|
// 如果缩放比例很小,使用多步缩放来保持边缘清晰
|
||||||
|
if (scaleRatio < 0.5) {
|
||||||
|
// 创建中间画布,分步缩放
|
||||||
|
const intermediateCanvas = document.createElement('canvas')
|
||||||
|
const intermediateCtx = intermediateCanvas.getContext('2d')
|
||||||
|
|
||||||
|
// 第一步:缩放到中间尺寸(至少50%)
|
||||||
|
const intermediateWidth = Math.max(sourceWidth * 0.5, targetWidth)
|
||||||
|
const intermediateHeight = Math.max(sourceHeight * 0.5, targetHeight)
|
||||||
|
|
||||||
|
intermediateCanvas.width = intermediateWidth
|
||||||
|
intermediateCanvas.height = intermediateHeight
|
||||||
|
|
||||||
|
// 使用像素化缩放进行第一步
|
||||||
|
intermediateCtx.imageSmoothingEnabled = false
|
||||||
|
intermediateCtx.drawImage(
|
||||||
|
sourceCtx.canvas,
|
||||||
|
0, 0, sourceWidth, sourceHeight,
|
||||||
|
0, 0, intermediateWidth, intermediateHeight
|
||||||
|
)
|
||||||
|
|
||||||
|
// 第二步:从中间尺寸缩放到目标尺寸
|
||||||
|
if (intermediateWidth !== targetWidth || intermediateHeight !== targetHeight) {
|
||||||
|
// 如果还需要进一步缩放,使用平滑缩放
|
||||||
|
targetCtx.imageSmoothingEnabled = true
|
||||||
|
targetCtx.imageSmoothingQuality = 'high'
|
||||||
|
targetCtx.drawImage(
|
||||||
|
intermediateCanvas,
|
||||||
|
0, 0, intermediateWidth, intermediateHeight,
|
||||||
|
0, 0, targetWidth, targetHeight
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
// 直接复制
|
||||||
|
targetCtx.drawImage(intermediateCanvas, 0, 0)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// 缩放比例较大,直接使用像素化缩放
|
||||||
|
targetCtx.imageSmoothingEnabled = false
|
||||||
|
targetCtx.drawImage(
|
||||||
|
sourceCtx.canvas,
|
||||||
|
0, 0, sourceWidth, sourceHeight,
|
||||||
|
0, 0, targetWidth, targetHeight
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 计算保持宽高比的目标尺寸
|
||||||
|
* @param {number} originalWidth - 原始宽度
|
||||||
|
* @param {number} originalHeight - 原始高度
|
||||||
|
* @param {number} maxWidth - 最大宽度
|
||||||
|
* @param {number} maxHeight - 最大高度
|
||||||
|
* @returns {Object} 包含 width 和 height 的对象
|
||||||
|
*/
|
||||||
|
calculateTargetSize(originalWidth, originalHeight, maxWidth, maxHeight) {
|
||||||
|
const ratio = Math.min(maxWidth / originalWidth, maxHeight / originalHeight)
|
||||||
|
|
||||||
|
return {
|
||||||
|
width: Math.round(originalWidth * ratio),
|
||||||
|
height: Math.round(originalHeight * ratio)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 主要的缩放函数
|
||||||
|
* @param {File|Blob} gifFile - 输入的 GIF 文件
|
||||||
|
* @param {Object} scaleOptions - 缩放选项
|
||||||
|
* @param {number} scaleOptions.maxWidth - 最大宽度
|
||||||
|
* @param {number} scaleOptions.maxHeight - 最大高度
|
||||||
|
* @param {boolean} scaleOptions.keepAspectRatio - 是否保持宽高比
|
||||||
|
* @returns {Promise<Blob>} 返回缩放后的 GIF Blob
|
||||||
|
*/
|
||||||
|
async scaleGif(gifFile, scaleOptions) {
|
||||||
|
try {
|
||||||
|
const { maxWidth, maxHeight, keepAspectRatio = true } = scaleOptions
|
||||||
|
|
||||||
|
if (!maxWidth || !maxHeight) {
|
||||||
|
throw new Error('必须指定最大宽度和高度')
|
||||||
|
}
|
||||||
|
|
||||||
|
// 解析原始 GIF
|
||||||
|
await this.parseGifFrames(gifFile)
|
||||||
|
|
||||||
|
// 计算目标尺寸
|
||||||
|
let targetSize
|
||||||
|
if (keepAspectRatio) {
|
||||||
|
targetSize = this.calculateTargetSize(
|
||||||
|
this.originalWidth,
|
||||||
|
this.originalHeight,
|
||||||
|
maxWidth,
|
||||||
|
maxHeight
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
targetSize = { width: maxWidth, height: maxHeight }
|
||||||
|
}
|
||||||
|
|
||||||
|
this.targetWidth = targetSize.width
|
||||||
|
this.targetHeight = targetSize.height
|
||||||
|
|
||||||
|
// 检查是否需要缩放
|
||||||
|
if (this.targetWidth === this.originalWidth && this.targetHeight === this.originalHeight) {
|
||||||
|
if (this.options.debug) {
|
||||||
|
console.log('无需缩放,返回原始文件')
|
||||||
|
}
|
||||||
|
return gifFile
|
||||||
|
}
|
||||||
|
|
||||||
|
// 缩放所有帧
|
||||||
|
const scaledFrames = this.frames.map(frame =>
|
||||||
|
this.scaleFrame(frame, this.targetWidth, this.targetHeight)
|
||||||
|
)
|
||||||
|
|
||||||
|
// 生成新的 GIF
|
||||||
|
const scaledGifBlob = await this.generateGif(scaledFrames, this.delays)
|
||||||
|
|
||||||
|
if (this.options.debug) {
|
||||||
|
console.log(`GIF 缩放完成: ${this.originalWidth}x${this.originalHeight} -> ${this.targetWidth}x${this.targetHeight}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
return scaledGifBlob
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(`GIF 缩放失败: ${error.message}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成新的 GIF 文件
|
||||||
|
* @param {Array<ImageData>} frames - 图像帧数组
|
||||||
|
* @param {Array<number>} delays - 延迟数组
|
||||||
|
* @returns {Promise<Blob>} 生成的 GIF Blob
|
||||||
|
*/
|
||||||
|
async generateGif(frames, delays) {
|
||||||
|
try {
|
||||||
|
// 统一使用 gif.js 生成 GIF,无论单帧还是多帧
|
||||||
|
return await this.generateGifWithGifJs(frames, delays)
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(`GIF 生成失败: ${error.message}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 使用 gif.js 生成动态 GIF
|
||||||
|
* @param {Array<ImageData>} frames - 图像帧数组
|
||||||
|
* @param {Array<number>} delays - 延迟数组
|
||||||
|
* @returns {Promise<Blob>} 生成的 GIF Blob
|
||||||
|
*/
|
||||||
|
async generateGifWithGifJs(frames, delays) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
if (!GIF) {
|
||||||
|
throw new Error('gif.js 未安装,无法生成 GIF 文件。请运行: npm install gif.js')
|
||||||
|
}
|
||||||
|
const gif = new GIF({
|
||||||
|
workers: this.options.workers,
|
||||||
|
quality: this.options.quality,
|
||||||
|
width: this.targetWidth,
|
||||||
|
height: this.targetHeight,
|
||||||
|
transparent: 'rgba(255, 0, 255, 0)',
|
||||||
|
repeat: this.gifRepeat !== undefined ? this.gifRepeat : 0, // 0表示无限循环
|
||||||
|
workerScript: this.options.workerScript // 指定 worker 脚本路径
|
||||||
|
// gif.js 会自动处理透明像素,不需要手动设置 transparent 选项
|
||||||
|
})
|
||||||
|
|
||||||
|
// 添加所有帧
|
||||||
|
frames.forEach((frameData, index) => {
|
||||||
|
const canvas = document.createElement('canvas')
|
||||||
|
canvas.width = this.targetWidth
|
||||||
|
canvas.height = this.targetHeight
|
||||||
|
const ctx = canvas.getContext('2d', { willReadFrequently: true })
|
||||||
|
|
||||||
|
// 确保画布背景透明
|
||||||
|
ctx.clearRect(0, 0, this.targetWidth, this.targetHeight)
|
||||||
|
ctx.putImageData(frameData, 0, 0)
|
||||||
|
|
||||||
|
gif.addFrame(canvas, { delay: delays[index] || 100 })
|
||||||
|
})
|
||||||
|
|
||||||
|
gif.on('finished', (blob) => {
|
||||||
|
if (this.options.debug) {
|
||||||
|
console.log(`GIF generated: ${frames.length} frames, ${blob.size} bytes, repeat: ${this.gifRepeat === 0 ? '无限循环' : this.gifRepeat + '次'}`)
|
||||||
|
}
|
||||||
|
resolve(blob)
|
||||||
|
})
|
||||||
|
|
||||||
|
gif.on('abort', () => {
|
||||||
|
reject(new Error('GIF 生成被中止'))
|
||||||
|
})
|
||||||
|
|
||||||
|
gif.render()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取 GIF 信息
|
||||||
|
* @param {File|Blob} gifFile - GIF 文件
|
||||||
|
* @returns {Promise<Object>} GIF 信息对象
|
||||||
|
*/
|
||||||
|
async getGifInfo(gifFile) {
|
||||||
|
try {
|
||||||
|
// 使用 parseGifWithGifuct 解析获取信息
|
||||||
|
await this.parseGifWithGifuct(gifFile)
|
||||||
|
|
||||||
|
return {
|
||||||
|
width: this.originalWidth,
|
||||||
|
height: this.originalHeight,
|
||||||
|
frameCount: this.frames.length,
|
||||||
|
totalDuration: this.delays.reduce((sum, delay) => sum + delay, 0),
|
||||||
|
repeat: this.gifRepeat,
|
||||||
|
fileSize: gifFile.size
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(`获取 GIF 信息失败: ${error.message}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查是否需要缩放
|
||||||
|
* @param {File|Blob} gifFile - GIF 文件
|
||||||
|
* @param {number} maxWidth - 最大宽度
|
||||||
|
* @param {number} maxHeight - 最大高度
|
||||||
|
* @returns {Promise<boolean>} 是否需要缩放
|
||||||
|
*/
|
||||||
|
async needsScaling(gifFile, maxWidth, maxHeight) {
|
||||||
|
const info = await this.getGifInfo(gifFile)
|
||||||
|
return info.width > maxWidth || info.height > maxHeight
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将文件转换为 ArrayBuffer
|
||||||
|
* @param {File|Blob} file - 文件对象
|
||||||
|
* @returns {Promise<ArrayBuffer>} ArrayBuffer
|
||||||
|
*/
|
||||||
|
async fileToArrayBuffer(file) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const reader = new FileReader()
|
||||||
|
reader.onload = () => resolve(reader.result)
|
||||||
|
reader.onerror = () => reject(new Error('文件读取失败'))
|
||||||
|
reader.readAsArrayBuffer(file)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 批量缩放多个 GIF 文件
|
||||||
|
* @param {Array<File>} gifFiles - GIF 文件数组
|
||||||
|
* @param {Object} scaleOptions - 缩放选项
|
||||||
|
* @returns {Promise<Array<Blob>>} 缩放后的 GIF 数组
|
||||||
|
*/
|
||||||
|
async scaleBatchGifs(gifFiles, scaleOptions) {
|
||||||
|
const results = []
|
||||||
|
|
||||||
|
for (let i = 0; i < gifFiles.length; i++) {
|
||||||
|
try {
|
||||||
|
if (this.options.debug) {
|
||||||
|
console.log(`处理第 ${i + 1}/${gifFiles.length} 个文件`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const scaledGif = await this.scaleGif(gifFiles[i], scaleOptions)
|
||||||
|
results.push({
|
||||||
|
index: i,
|
||||||
|
success: true,
|
||||||
|
result: scaledGif,
|
||||||
|
originalFile: gifFiles[i]
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
results.push({
|
||||||
|
index: i,
|
||||||
|
success: false,
|
||||||
|
error: error.message,
|
||||||
|
originalFile: gifFiles[i]
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return results
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取建议的缩放尺寸
|
||||||
|
* @param {number} originalWidth - 原始宽度
|
||||||
|
* @param {number} originalHeight - 原始高度
|
||||||
|
* @param {Array<Object>} targetSizes - 目标尺寸数组,如 [{name: '32x32', width: 32, height: 32}]
|
||||||
|
* @returns {Object} 建议的缩放配置
|
||||||
|
*/
|
||||||
|
getSuggestedScaling(originalWidth, originalHeight, targetSizes = []) {
|
||||||
|
const suggestions = []
|
||||||
|
|
||||||
|
// 默认目标尺寸
|
||||||
|
const defaultSizes = [
|
||||||
|
{ name: 'emoji_32', width: 32, height: 32 },
|
||||||
|
{ name: 'emoji_64', width: 64, height: 64 },
|
||||||
|
{ name: 'small', width: 48, height: 48 },
|
||||||
|
{ name: 'medium', width: 96, height: 96 }
|
||||||
|
]
|
||||||
|
|
||||||
|
const sizes = targetSizes.length > 0 ? targetSizes : defaultSizes
|
||||||
|
|
||||||
|
sizes.forEach(size => {
|
||||||
|
const targetSize = this.calculateTargetSize(
|
||||||
|
originalWidth,
|
||||||
|
originalHeight,
|
||||||
|
size.width,
|
||||||
|
size.height
|
||||||
|
)
|
||||||
|
|
||||||
|
suggestions.push({
|
||||||
|
name: size.name,
|
||||||
|
target: size,
|
||||||
|
actual: targetSize,
|
||||||
|
needsScaling: targetSize.width !== originalWidth || targetSize.height !== originalHeight,
|
||||||
|
scaleRatio: targetSize.width / originalWidth
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
return {
|
||||||
|
original: { width: originalWidth, height: originalHeight },
|
||||||
|
suggestions
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清理资源
|
||||||
|
*/
|
||||||
|
dispose() {
|
||||||
|
if (this.canvas) {
|
||||||
|
this.canvas = null
|
||||||
|
this.ctx = null
|
||||||
|
}
|
||||||
|
this.frames = []
|
||||||
|
this.delays = []
|
||||||
|
|
||||||
|
// 清理可能的 Object URLs
|
||||||
|
if (this.tempObjectUrls) {
|
||||||
|
this.tempObjectUrls.forEach(url => URL.revokeObjectURL(url))
|
||||||
|
this.tempObjectUrls = []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default GifScaler
|
||||||
447
main/manager-web/src/utils/SpiffsGenerator.js
Normal file
447
main/manager-web/src/utils/SpiffsGenerator.js
Normal file
|
|
@ -0,0 +1,447 @@
|
||||||
|
/**
|
||||||
|
* SpiffsGenerator 类
|
||||||
|
* 模仿 spiffs_assets_gen.py 的功能,用于在浏览器端生成 assets.bin 文件
|
||||||
|
*
|
||||||
|
* 文件格式:
|
||||||
|
* {
|
||||||
|
* total_files: int (4字节) // 文件总数
|
||||||
|
* checksum: int (4字节) // 校验和
|
||||||
|
* combined_data_length: int (4字节) // 数据总长度
|
||||||
|
* mmap_table: [ // 文件映射表
|
||||||
|
* {
|
||||||
|
* name: char[32] // 文件名 (32字节)
|
||||||
|
* size: int (4字节) // 文件大小
|
||||||
|
* offset: int (4字节) // 文件偏移量
|
||||||
|
* width: short (2字节) // 图片宽度
|
||||||
|
* height: short (2字节) // 图片高度
|
||||||
|
* }
|
||||||
|
* ...
|
||||||
|
* ]
|
||||||
|
* file_data: [ // 文件数据
|
||||||
|
* 0x5A 0x5A + file1_data // 每个文件前面加0x5A5A标识
|
||||||
|
* 0x5A 0x5A + file2_data
|
||||||
|
* ...
|
||||||
|
* ]
|
||||||
|
* }
|
||||||
|
*/
|
||||||
|
|
||||||
|
class SpiffsGenerator {
|
||||||
|
constructor() {
|
||||||
|
this.files = []
|
||||||
|
this.textEncoder = new TextEncoder()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 添加文件
|
||||||
|
* @param {string} filename - 文件名
|
||||||
|
* @param {ArrayBuffer} data - 文件数据
|
||||||
|
* @param {Object} options - 可选参数 {width?, height?}
|
||||||
|
*/
|
||||||
|
addFile(filename, data, options = {}) {
|
||||||
|
if (filename.length > 32) {
|
||||||
|
console.warn(`文件名 "${filename}" 超过32字节,将被截断`)
|
||||||
|
}
|
||||||
|
|
||||||
|
this.files.push({
|
||||||
|
filename,
|
||||||
|
data,
|
||||||
|
size: data.byteLength,
|
||||||
|
width: options.width || 0,
|
||||||
|
height: options.height || 0
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从图片文件获取尺寸信息
|
||||||
|
* @param {ArrayBuffer} imageData - 图片数据
|
||||||
|
* @returns {Promise<Object>} {width, height}
|
||||||
|
*/
|
||||||
|
async getImageDimensions(imageData) {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
try {
|
||||||
|
const blob = new Blob([imageData])
|
||||||
|
const url = URL.createObjectURL(blob)
|
||||||
|
const img = new Image()
|
||||||
|
|
||||||
|
img.onload = () => {
|
||||||
|
URL.revokeObjectURL(url)
|
||||||
|
resolve({ width: img.width, height: img.height })
|
||||||
|
}
|
||||||
|
|
||||||
|
img.onerror = () => {
|
||||||
|
URL.revokeObjectURL(url)
|
||||||
|
resolve({ width: 0, height: 0 })
|
||||||
|
}
|
||||||
|
|
||||||
|
img.src = url
|
||||||
|
} catch (error) {
|
||||||
|
resolve({ width: 0, height: 0 })
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查是否为特殊图片格式 (.sjpg, .spng, .sqoi)
|
||||||
|
* @param {string} filename - 文件名
|
||||||
|
* @param {ArrayBuffer} data - 文件数据
|
||||||
|
* @returns {Object} {width, height}
|
||||||
|
*/
|
||||||
|
parseSpecialImageFormat(filename, data) {
|
||||||
|
const ext = filename.toLowerCase().split('.').pop()
|
||||||
|
|
||||||
|
if (['.sjpg', '.spng', '.sqoi'].includes('.' + ext)) {
|
||||||
|
try {
|
||||||
|
// 特殊格式的头部结构:偏移14字节后是宽度和高度(各2字节,小端序)
|
||||||
|
const view = new DataView(data)
|
||||||
|
const width = view.getUint16(14, true) // 小端序
|
||||||
|
const height = view.getUint16(16, true) // 小端序
|
||||||
|
return { width, height }
|
||||||
|
} catch (error) {
|
||||||
|
console.warn(`解析特殊图片格式失败: ${filename}`, error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { width: 0, height: 0 }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将32位整数转换为小端序字节数组
|
||||||
|
* @param {number} value - 整数值
|
||||||
|
* @returns {Uint8Array} 4字节的小端序数组
|
||||||
|
*/
|
||||||
|
packUint32(value) {
|
||||||
|
const bytes = new Uint8Array(4)
|
||||||
|
bytes[0] = value & 0xFF
|
||||||
|
bytes[1] = (value >> 8) & 0xFF
|
||||||
|
bytes[2] = (value >> 16) & 0xFF
|
||||||
|
bytes[3] = (value >> 24) & 0xFF
|
||||||
|
return bytes
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将16位整数转换为小端序字节数组
|
||||||
|
* @param {number} value - 整数值
|
||||||
|
* @returns {Uint8Array} 2字节的小端序数组
|
||||||
|
*/
|
||||||
|
packUint16(value) {
|
||||||
|
const bytes = new Uint8Array(2)
|
||||||
|
bytes[0] = value & 0xFF
|
||||||
|
bytes[1] = (value >> 8) & 0xFF
|
||||||
|
return bytes
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将字符串打包为固定长度的二进制数据
|
||||||
|
* @param {string} string - 输入字符串
|
||||||
|
* @param {number} maxLen - 最大长度
|
||||||
|
* @returns {Uint8Array} 打包后的二进制数据
|
||||||
|
*/
|
||||||
|
packString(string, maxLen) {
|
||||||
|
const bytes = new Uint8Array(maxLen)
|
||||||
|
const encoded = this.textEncoder.encode(string)
|
||||||
|
|
||||||
|
// 复制字符串数据,确保不超过最大长度
|
||||||
|
const copyLen = Math.min(encoded.length, maxLen)
|
||||||
|
bytes.set(encoded.slice(0, copyLen), 0)
|
||||||
|
|
||||||
|
// 剩余字节为0填充
|
||||||
|
return bytes
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 计算校验和
|
||||||
|
* @param {Uint8Array} data - 数据
|
||||||
|
* @returns {number} 16位校验和
|
||||||
|
*/
|
||||||
|
computeChecksum(data) {
|
||||||
|
let checksum = 0
|
||||||
|
for (let i = 0; i < data.length; i++) {
|
||||||
|
checksum += data[i]
|
||||||
|
}
|
||||||
|
return checksum & 0xFFFF
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 对文件进行排序
|
||||||
|
* @param {Array} files - 文件列表
|
||||||
|
* @returns {Array} 排序后的文件列表
|
||||||
|
*/
|
||||||
|
sortFiles(files) {
|
||||||
|
return files.slice().sort((a, b) => {
|
||||||
|
const extA = a.filename.split('.').pop() || ''
|
||||||
|
const extB = b.filename.split('.').pop() || ''
|
||||||
|
|
||||||
|
if (extA !== extB) {
|
||||||
|
return extA.localeCompare(extB)
|
||||||
|
}
|
||||||
|
|
||||||
|
const nameA = a.filename.replace(/\.[^/.]+$/, '')
|
||||||
|
const nameB = b.filename.replace(/\.[^/.]+$/, '')
|
||||||
|
return nameA.localeCompare(nameB)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成 assets.bin 文件
|
||||||
|
* @param {Function} progressCallback - 进度回调函数
|
||||||
|
* @returns {Promise<ArrayBuffer>} 生成的 assets.bin 数据
|
||||||
|
*/
|
||||||
|
async generate(progressCallback = null) {
|
||||||
|
if (this.files.length === 0) {
|
||||||
|
throw new Error('没有文件可打包')
|
||||||
|
}
|
||||||
|
|
||||||
|
if (progressCallback) progressCallback(0, '开始打包文件...')
|
||||||
|
|
||||||
|
// 排序文件
|
||||||
|
const sortedFiles = this.sortFiles(this.files)
|
||||||
|
const totalFiles = sortedFiles.length
|
||||||
|
|
||||||
|
// 处理文件信息并获取图片尺寸
|
||||||
|
const fileInfoList = []
|
||||||
|
let mergedDataSize = 0
|
||||||
|
|
||||||
|
for (let i = 0; i < sortedFiles.length; i++) {
|
||||||
|
const file = sortedFiles[i]
|
||||||
|
let width = file.width
|
||||||
|
let height = file.height
|
||||||
|
|
||||||
|
if (progressCallback) {
|
||||||
|
progressCallback(10 + (i / totalFiles) * 30, `处理文件: ${file.filename}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果没有提供尺寸信息,尝试自动获取
|
||||||
|
if (width === 0 && height === 0) {
|
||||||
|
// 先检查特殊图片格式
|
||||||
|
const specialDimensions = this.parseSpecialImageFormat(file.filename, file.data)
|
||||||
|
if (specialDimensions.width > 0 || specialDimensions.height > 0) {
|
||||||
|
width = specialDimensions.width
|
||||||
|
height = specialDimensions.height
|
||||||
|
} else {
|
||||||
|
// 尝试作为普通图片解析
|
||||||
|
const ext = file.filename.toLowerCase().split('.').pop()
|
||||||
|
if (['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp'].includes(ext)) {
|
||||||
|
const dimensions = await this.getImageDimensions(file.data)
|
||||||
|
width = dimensions.width
|
||||||
|
height = dimensions.height
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// offset 是文件在 mergedData 中的位置,包括前缀
|
||||||
|
// 与 Python 参考代码一致:offset = len(merged_data) (在添加前缀之前)
|
||||||
|
const fileOffset = mergedDataSize
|
||||||
|
|
||||||
|
fileInfoList.push({
|
||||||
|
filename: file.filename,
|
||||||
|
data: file.data,
|
||||||
|
size: file.size,
|
||||||
|
offset: fileOffset, // 文件在 mergedData 中的位置(包括前缀)
|
||||||
|
width,
|
||||||
|
height
|
||||||
|
})
|
||||||
|
|
||||||
|
// 更新 mergedDataSize:包括前缀(2字节) + 文件数据
|
||||||
|
mergedDataSize += 2 + file.size
|
||||||
|
}
|
||||||
|
|
||||||
|
if (progressCallback) progressCallback(40, '构建文件映射表...')
|
||||||
|
|
||||||
|
// 构建映射表
|
||||||
|
const mmapTableSize = totalFiles * (32 + 4 + 4 + 2 + 2) // name + size + offset + width + height
|
||||||
|
const mmapTable = new Uint8Array(mmapTableSize)
|
||||||
|
let mmapOffset = 0
|
||||||
|
|
||||||
|
for (const fileInfo of fileInfoList) {
|
||||||
|
// 文件名 (32字节)
|
||||||
|
mmapTable.set(this.packString(fileInfo.filename, 32), mmapOffset)
|
||||||
|
mmapOffset += 32
|
||||||
|
|
||||||
|
// 文件大小 (4字节)
|
||||||
|
mmapTable.set(this.packUint32(fileInfo.size), mmapOffset)
|
||||||
|
mmapOffset += 4
|
||||||
|
|
||||||
|
// 文件偏移 (4字节)
|
||||||
|
mmapTable.set(this.packUint32(fileInfo.offset), mmapOffset)
|
||||||
|
mmapOffset += 4
|
||||||
|
|
||||||
|
// 图片宽度 (2字节)
|
||||||
|
mmapTable.set(this.packUint16(fileInfo.width), mmapOffset)
|
||||||
|
mmapOffset += 2
|
||||||
|
|
||||||
|
// 图片高度 (2字节)
|
||||||
|
mmapTable.set(this.packUint16(fileInfo.height), mmapOffset)
|
||||||
|
mmapOffset += 2
|
||||||
|
}
|
||||||
|
|
||||||
|
if (progressCallback) progressCallback(60, '合并文件数据...')
|
||||||
|
|
||||||
|
// 合并文件数据
|
||||||
|
const mergedData = new Uint8Array(mergedDataSize)
|
||||||
|
let mergedOffset = 0
|
||||||
|
|
||||||
|
for (let i = 0; i < fileInfoList.length; i++) {
|
||||||
|
const fileInfo = fileInfoList[i]
|
||||||
|
|
||||||
|
if (progressCallback) {
|
||||||
|
progressCallback(60 + (i / totalFiles) * 20, `合并文件: ${fileInfo.filename}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 添加0x5A5A前缀
|
||||||
|
mergedData[mergedOffset] = 0x5A
|
||||||
|
mergedData[mergedOffset + 1] = 0x5A
|
||||||
|
mergedOffset += 2
|
||||||
|
|
||||||
|
// 添加文件数据
|
||||||
|
mergedData.set(new Uint8Array(fileInfo.data), mergedOffset)
|
||||||
|
mergedOffset += fileInfo.size
|
||||||
|
}
|
||||||
|
|
||||||
|
if (progressCallback) progressCallback(80, '计算校验和...')
|
||||||
|
|
||||||
|
// 计算组合数据的校验和
|
||||||
|
// 注意:combinedData = mmapTable + mergedData,顺序必须与Python参考代码一致
|
||||||
|
// 设备端从偏移12开始读取,读取stored_len长度的数据,这应该等于combinedData
|
||||||
|
const combinedData = new Uint8Array(mmapTableSize + mergedDataSize)
|
||||||
|
combinedData.set(mmapTable, 0)
|
||||||
|
combinedData.set(mergedData, mmapTableSize)
|
||||||
|
|
||||||
|
// 验证数据一致性
|
||||||
|
if (mmapTable.length !== mmapTableSize) {
|
||||||
|
console.error('[SpiffsGenerator] mmapTable长度不匹配:', mmapTable.length, '!=', mmapTableSize)
|
||||||
|
}
|
||||||
|
if (mergedData.length !== mergedDataSize) {
|
||||||
|
console.error('[SpiffsGenerator] mergedData长度不匹配:', mergedData.length, '!=', mergedDataSize)
|
||||||
|
}
|
||||||
|
if (combinedData.length !== mmapTableSize + mergedDataSize) {
|
||||||
|
console.error('[SpiffsGenerator] combinedData长度不匹配:', combinedData.length, '!=', mmapTableSize + mergedDataSize)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 计算校验和(对combinedData的所有字节求和,取低16位)
|
||||||
|
// 与设备端 CalculateChecksum 逻辑一致:对数据求和,取低16位
|
||||||
|
// 注意:必须在写入文件之前计算校验码,确保使用的数据与最终写入的数据一致
|
||||||
|
const combinedDataLength = combinedData.length
|
||||||
|
const checksum = this.computeChecksum(combinedData)
|
||||||
|
|
||||||
|
// 调试日志:详细输出校验码计算过程
|
||||||
|
console.log('[SpiffsGenerator] 校验码计算:', {
|
||||||
|
totalFiles,
|
||||||
|
mmapTableSize,
|
||||||
|
mergedDataSize,
|
||||||
|
combinedDataLength,
|
||||||
|
checksum: `0x${checksum.toString(16).toUpperCase().padStart(4, '0')}`,
|
||||||
|
checksumDecimal: checksum,
|
||||||
|
mmapTableLength: mmapTable.length,
|
||||||
|
mergedDataLength: mergedData.length,
|
||||||
|
combinedDataLengthActual: combinedData.length
|
||||||
|
})
|
||||||
|
|
||||||
|
// 验证:计算前几个字节的校验码(用于调试)
|
||||||
|
if (combinedData.length > 0) {
|
||||||
|
const firstBytes = Array.from(combinedData.slice(0, Math.min(20, combinedData.length)))
|
||||||
|
const firstBytesSum = firstBytes.reduce((sum, b) => sum + b, 0)
|
||||||
|
console.log('[SpiffsGenerator] 前20字节:', firstBytes.map(b => `0x${b.toString(16).toUpperCase().padStart(2, '0')}`).join(' '))
|
||||||
|
console.log('[SpiffsGenerator] 前20字节和:', firstBytesSum)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (progressCallback) progressCallback(90, '构建最终文件...')
|
||||||
|
|
||||||
|
// 构建最终输出
|
||||||
|
// 文件格式:header (12字节) + combinedData
|
||||||
|
// header格式:[4字节文件数][4字节校验码][4字节数据长度]
|
||||||
|
// 注意:必须确保 combinedData 在写入前不被修改
|
||||||
|
const headerSize = 4 + 4 + 4 // total_files + checksum + combined_data_length
|
||||||
|
const totalSize = headerSize + combinedDataLength
|
||||||
|
const finalData = new Uint8Array(totalSize)
|
||||||
|
|
||||||
|
let offset = 0
|
||||||
|
|
||||||
|
// 写入文件总数(4字节,小端序)
|
||||||
|
finalData.set(this.packUint32(totalFiles), offset)
|
||||||
|
offset += 4
|
||||||
|
|
||||||
|
// 写入校验和(4字节,小端序)
|
||||||
|
// 注意:校验码是16位值,但作为32位写入(高16位为0)
|
||||||
|
const checksumBytes = this.packUint32(checksum)
|
||||||
|
finalData.set(checksumBytes, offset)
|
||||||
|
|
||||||
|
// 调试日志:验证校验码写入
|
||||||
|
console.log('[SpiffsGenerator] 校验码写入:', {
|
||||||
|
checksum: `0x${checksum.toString(16).toUpperCase().padStart(4, '0')}`,
|
||||||
|
packedBytes: Array.from(checksumBytes).map(b => `0x${b.toString(16).toUpperCase().padStart(2, '0')}`),
|
||||||
|
offset,
|
||||||
|
// 验证写入的校验码字节
|
||||||
|
writtenChecksum: (checksumBytes[0] | (checksumBytes[1] << 8)) & 0xFFFF
|
||||||
|
})
|
||||||
|
|
||||||
|
offset += 4
|
||||||
|
|
||||||
|
// 写入组合数据长度(4字节,小端序)
|
||||||
|
finalData.set(this.packUint32(combinedDataLength), offset)
|
||||||
|
offset += 4
|
||||||
|
|
||||||
|
// 写入组合数据(mmapTable + mergedData)
|
||||||
|
// 注意:这里必须使用之前计算校验码时使用的同一个 combinedData
|
||||||
|
finalData.set(combinedData, offset)
|
||||||
|
|
||||||
|
// 验证:重新计算写入后的 combinedData 的校验码,确保一致
|
||||||
|
const writtenCombinedData = finalData.slice(offset, offset + combinedDataLength)
|
||||||
|
const verifyChecksum = this.computeChecksum(writtenCombinedData)
|
||||||
|
if (verifyChecksum !== checksum) {
|
||||||
|
console.error('[SpiffsGenerator] 警告:写入后的校验码验证失败!', {
|
||||||
|
originalChecksum: `0x${checksum.toString(16).toUpperCase().padStart(4, '0')}`,
|
||||||
|
verifyChecksum: `0x${verifyChecksum.toString(16).toUpperCase().padStart(4, '0')}`
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
console.log('[SpiffsGenerator] 校验码验证通过:', {
|
||||||
|
checksum: `0x${checksum.toString(16).toUpperCase().padStart(4, '0')}`
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// 调试日志:验证最终文件结构
|
||||||
|
console.log('[SpiffsGenerator] 最终文件结构:', {
|
||||||
|
totalSize,
|
||||||
|
headerSize,
|
||||||
|
combinedDataLength,
|
||||||
|
fileCount: totalFiles,
|
||||||
|
checksum: `0x${checksum.toString(16).toUpperCase().padStart(4, '0')}`,
|
||||||
|
headerBytes: Array.from(finalData.slice(0, 12)).map(b => `0x${b.toString(16).toUpperCase().padStart(2, '0')}`)
|
||||||
|
})
|
||||||
|
|
||||||
|
if (progressCallback) progressCallback(100, '打包完成')
|
||||||
|
|
||||||
|
return finalData.buffer
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取文件统计信息
|
||||||
|
* @returns {Object} 统计信息
|
||||||
|
*/
|
||||||
|
getStats() {
|
||||||
|
let totalSize = 0
|
||||||
|
const fileTypes = new Map()
|
||||||
|
|
||||||
|
for (const file of this.files) {
|
||||||
|
totalSize += file.size
|
||||||
|
|
||||||
|
const ext = file.filename.split('.').pop()?.toLowerCase() || 'unknown'
|
||||||
|
fileTypes.set(ext, (fileTypes.get(ext) || 0) + 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
fileCount: this.files.length,
|
||||||
|
totalSize,
|
||||||
|
fileTypes: Object.fromEntries(fileTypes),
|
||||||
|
averageFileSize: this.files.length > 0 ? Math.round(totalSize / this.files.length) : 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清理文件列表
|
||||||
|
*/
|
||||||
|
clear() {
|
||||||
|
this.files = []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default SpiffsGenerator
|
||||||
371
main/manager-web/src/utils/WakenetModelPacker.js
Normal file
371
main/manager-web/src/utils/WakenetModelPacker.js
Normal file
|
|
@ -0,0 +1,371 @@
|
||||||
|
/**
|
||||||
|
* WakenetModelPacker 类
|
||||||
|
* 模仿 pack_model.py 的功能,用于在浏览器端打包唤醒词模型
|
||||||
|
*
|
||||||
|
* 注意:已修复与Python版本的兼容性问题:
|
||||||
|
* - 使用ASCII编码而非UTF-8编码
|
||||||
|
* - 确保小端序整数格式一致
|
||||||
|
* - 移除冗余的字符串替换操作
|
||||||
|
*
|
||||||
|
* 打包格式:
|
||||||
|
* {
|
||||||
|
* model_num: int (4字节)
|
||||||
|
* model1_info: model_info_t
|
||||||
|
* model2_info: model_info_t
|
||||||
|
* ...
|
||||||
|
* model1数据
|
||||||
|
* model2数据
|
||||||
|
* ...
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* model_info_t格式:
|
||||||
|
* {
|
||||||
|
* model_name: char[32] (32字节)
|
||||||
|
* file_number: int (4字节)
|
||||||
|
* file1_name: char[32] (32字节)
|
||||||
|
* file1_start: int (4字节)
|
||||||
|
* file1_len: int (4字节)
|
||||||
|
* file2_name: char[32] (32字节)
|
||||||
|
* file2_start: int (4字节)
|
||||||
|
* file2_len: int (4字节)
|
||||||
|
* ...
|
||||||
|
* }
|
||||||
|
*/
|
||||||
|
|
||||||
|
class WakenetModelPacker {
|
||||||
|
constructor() {
|
||||||
|
this.models = new Map()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 添加模型文件
|
||||||
|
* @param {string} modelName - 模型名称
|
||||||
|
* @param {string} fileName - 文件名
|
||||||
|
* @param {ArrayBuffer} fileData - 文件数据
|
||||||
|
*/
|
||||||
|
addModelFile(modelName, fileName, fileData) {
|
||||||
|
if (!this.models.has(modelName)) {
|
||||||
|
this.models.set(modelName, new Map())
|
||||||
|
}
|
||||||
|
this.models.get(modelName).set(fileName, fileData)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从share/wakenet_model目录加载模型
|
||||||
|
* @param {string} modelName - 模型名称 (例如: wn9s_nihaoxiaozhi)
|
||||||
|
* @returns {Promise<boolean>} 加载是否成功
|
||||||
|
*/
|
||||||
|
async loadModelFromShare(modelName) {
|
||||||
|
try {
|
||||||
|
// 所有wakenet模型都使用相同的文件名
|
||||||
|
const modelFiles = [
|
||||||
|
'_MODEL_INFO_',
|
||||||
|
'wn9_data',
|
||||||
|
'wn9_index'
|
||||||
|
]
|
||||||
|
|
||||||
|
let loadedFiles = 0
|
||||||
|
const failedFiles = []
|
||||||
|
|
||||||
|
for (const fileName of modelFiles) {
|
||||||
|
try {
|
||||||
|
// 尝试多种路径格式(根据实际部署路径调整)
|
||||||
|
const paths = [
|
||||||
|
`./static/wakenet_model/${modelName}/${fileName}`,
|
||||||
|
`/static/wakenet_model/${modelName}/${fileName}`,
|
||||||
|
`static/wakenet_model/${modelName}/${fileName}`,
|
||||||
|
`/tools/assets-generator/static/wakenet_model/${modelName}/${fileName}`,
|
||||||
|
`./tools/assets-generator/static/wakenet_model/${modelName}/${fileName}`
|
||||||
|
]
|
||||||
|
|
||||||
|
let loaded = false
|
||||||
|
for (const path of paths) {
|
||||||
|
try {
|
||||||
|
const response = await fetch(path)
|
||||||
|
if (response.ok) {
|
||||||
|
const fileData = await response.arrayBuffer()
|
||||||
|
this.addModelFile(modelName, fileName, fileData)
|
||||||
|
loadedFiles++
|
||||||
|
loaded = true
|
||||||
|
console.log(`成功加载: ${path}`)
|
||||||
|
break
|
||||||
|
} else {
|
||||||
|
console.warn(`无法加载文件: ${path}, status: ${response.status}`)
|
||||||
|
}
|
||||||
|
} catch (fetchError) {
|
||||||
|
console.warn(`尝试路径失败: ${path}`, fetchError)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!loaded) {
|
||||||
|
failedFiles.push(fileName)
|
||||||
|
console.error(`所有路径都失败,无法加载文件: ${fileName}`)
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
failedFiles.push(fileName)
|
||||||
|
console.error(`加载文件失败: ${fileName}`, error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (loadedFiles !== modelFiles.length) {
|
||||||
|
const errorMsg = `模型 ${modelName} 加载失败: 成功加载 ${loadedFiles}/${modelFiles.length} 个文件。失败的文件: ${failedFiles.join(', ')}`
|
||||||
|
console.error(errorMsg)
|
||||||
|
throw new Error(errorMsg)
|
||||||
|
}
|
||||||
|
|
||||||
|
return true
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`加载模型失败: ${modelName}`, error)
|
||||||
|
throw error // 重新抛出错误,让调用者知道具体原因
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将字符串打包为固定长度的二进制数据
|
||||||
|
* 模仿Python版本的struct_pack_string行为,使用ASCII编码
|
||||||
|
* @param {string} string - 输入字符串
|
||||||
|
* @param {number} maxLen - 最大长度
|
||||||
|
* @returns {Uint8Array} 打包后的二进制数据
|
||||||
|
*/
|
||||||
|
packString(string, maxLen) {
|
||||||
|
const bytes = new Uint8Array(maxLen)
|
||||||
|
|
||||||
|
// 使用ASCII编码,与Python版本保持一致
|
||||||
|
// 不预留null终止符空间,完整使用maxLen字节
|
||||||
|
const copyLen = Math.min(string.length, maxLen)
|
||||||
|
|
||||||
|
for (let i = 0; i < copyLen; i++) {
|
||||||
|
// 使用charCodeAt获取ASCII码,只取低8位以确保兼容性
|
||||||
|
bytes[i] = string.charCodeAt(i) & 0xFF
|
||||||
|
}
|
||||||
|
|
||||||
|
// 剩余字节保持为0(默认初始化值)
|
||||||
|
return bytes
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将32位整数转换为小端序字节数组
|
||||||
|
* 与Python版本的struct.pack('<I', value)保持一致
|
||||||
|
* @param {number} value - 整数值
|
||||||
|
* @returns {Uint8Array} 4字节的小端序数组
|
||||||
|
*/
|
||||||
|
packUint32(value) {
|
||||||
|
const bytes = new Uint8Array(4)
|
||||||
|
bytes[0] = value & 0xFF // 最低字节 (LSB)
|
||||||
|
bytes[1] = (value >> 8) & 0xFF //
|
||||||
|
bytes[2] = (value >> 16) & 0xFF //
|
||||||
|
bytes[3] = (value >> 24) & 0xFF // 最高字节 (MSB)
|
||||||
|
return bytes
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 打包所有模型为srmodels.bin格式
|
||||||
|
* @returns {ArrayBuffer} 打包后的二进制数据
|
||||||
|
*/
|
||||||
|
packModels() {
|
||||||
|
if (this.models.size === 0) {
|
||||||
|
throw new Error('没有模型数据可打包')
|
||||||
|
}
|
||||||
|
|
||||||
|
// 计算所有文件的总数和数据
|
||||||
|
let totalFileNum = 0
|
||||||
|
const modelDataList = []
|
||||||
|
|
||||||
|
// 按模型名排序遍历
|
||||||
|
for (const [modelName, files] of Array.from(this.models.entries()).sort((a, b) => a[0].localeCompare(b[0]))) {
|
||||||
|
totalFileNum += files.size
|
||||||
|
// 按文件名排序,确保与Python版本顺序一致
|
||||||
|
const sortedFiles = Array.from(files.entries()).sort((a, b) => a[0].localeCompare(b[0]))
|
||||||
|
modelDataList.push({
|
||||||
|
name: modelName,
|
||||||
|
files: sortedFiles
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// 计算头部长度: 模型数量(4) + 每个模型信息(32+4+文件数*(32+4+4))
|
||||||
|
const modelNum = this.models.size
|
||||||
|
let headerLen = 4 // model_num
|
||||||
|
|
||||||
|
for (const model of modelDataList) {
|
||||||
|
headerLen += 32 + 4 // model_name + file_number
|
||||||
|
headerLen += model.files.length * (32 + 4 + 4) // 每个文件的 name + start + len
|
||||||
|
}
|
||||||
|
|
||||||
|
// 创建输出缓冲区
|
||||||
|
const totalSize = headerLen + Array.from(this.models.values())
|
||||||
|
.reduce((total, files) => total + Array.from(files.values())
|
||||||
|
.reduce((fileTotal, fileData) => fileTotal + fileData.byteLength, 0), 0)
|
||||||
|
|
||||||
|
const output = new Uint8Array(totalSize)
|
||||||
|
let offset = 0
|
||||||
|
|
||||||
|
// 写入模型数量
|
||||||
|
output.set(this.packUint32(modelNum), offset)
|
||||||
|
offset += 4
|
||||||
|
|
||||||
|
// 写入模型信息头
|
||||||
|
let dataOffset = headerLen
|
||||||
|
|
||||||
|
for (const model of modelDataList) {
|
||||||
|
// 写入模型名称
|
||||||
|
output.set(this.packString(model.name, 32), offset)
|
||||||
|
offset += 32
|
||||||
|
|
||||||
|
// 写入文件数量
|
||||||
|
output.set(this.packUint32(model.files.length), offset)
|
||||||
|
offset += 4
|
||||||
|
|
||||||
|
// 写入每个文件的信息
|
||||||
|
for (const [fileName, fileData] of model.files) {
|
||||||
|
// 文件名
|
||||||
|
output.set(this.packString(fileName, 32), offset)
|
||||||
|
offset += 32
|
||||||
|
|
||||||
|
// 文件起始位置
|
||||||
|
output.set(this.packUint32(dataOffset), offset)
|
||||||
|
offset += 4
|
||||||
|
|
||||||
|
// 文件长度
|
||||||
|
output.set(this.packUint32(fileData.byteLength), offset)
|
||||||
|
offset += 4
|
||||||
|
|
||||||
|
dataOffset += fileData.byteLength
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 写入文件数据
|
||||||
|
for (const model of modelDataList) {
|
||||||
|
for (const [fileName, fileData] of model.files) {
|
||||||
|
output.set(new Uint8Array(fileData), offset)
|
||||||
|
offset += fileData.byteLength
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return output.buffer
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取可用的模型列表
|
||||||
|
* 只返回实际存在的模型文件
|
||||||
|
* @returns {Promise<Object>} 模型列表
|
||||||
|
*/
|
||||||
|
static async getAvailableModels() {
|
||||||
|
try {
|
||||||
|
// 实际存在的模型文件(根据 /tools/assets-generator/static/wakenet_model/ 目录)
|
||||||
|
const wn9sModels = [
|
||||||
|
'wn9s_alexa',
|
||||||
|
'wn9s_hiesp',
|
||||||
|
'wn9s_hijason',
|
||||||
|
'wn9s_hilexin',
|
||||||
|
'wn9s_nihaoxiaozhi'
|
||||||
|
]
|
||||||
|
|
||||||
|
const wn7Models = [
|
||||||
|
'wn7_xiaoaitongxue'
|
||||||
|
]
|
||||||
|
|
||||||
|
return {
|
||||||
|
WakeNet9: [], // 当前没有 WakeNet9 模型文件
|
||||||
|
WakeNet9s: wn9sModels,
|
||||||
|
WakeNet7: wn7Models
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('获取模型列表失败:', error)
|
||||||
|
return { WakeNet9: [], WakeNet9s: [], WakeNet7: [] }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 验证模型名称是否有效
|
||||||
|
* @param {string} modelName - 模型名称
|
||||||
|
* @param {string} chipModel - 芯片型号
|
||||||
|
* @returns {boolean} 是否有效
|
||||||
|
*/
|
||||||
|
static isValidModel(modelName, chipModel) {
|
||||||
|
// 实际存在的模型列表
|
||||||
|
const availableModels = [
|
||||||
|
'wn9s_alexa',
|
||||||
|
'wn9s_hiesp',
|
||||||
|
'wn9s_hijason',
|
||||||
|
'wn9s_hilexin',
|
||||||
|
'wn9s_nihaoxiaozhi',
|
||||||
|
'wn7_xiaoaitongxue'
|
||||||
|
]
|
||||||
|
|
||||||
|
// 检查是否是实际存在的模型
|
||||||
|
if (!availableModels.includes(modelName)) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
const isC3OrC6 = chipModel === 'esp32c3' || chipModel === 'esp32c6'
|
||||||
|
|
||||||
|
if (isC3OrC6) {
|
||||||
|
// C3/C6 芯片只支持 wn9s_ 开头的模型
|
||||||
|
return modelName.startsWith('wn9s_')
|
||||||
|
} else {
|
||||||
|
// S3/P4 芯片支持 wn9s_ 和 wn7_ 开头的模型
|
||||||
|
return modelName.startsWith('wn9s_') || modelName.startsWith('wn7_')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清理已加载的模型数据
|
||||||
|
*/
|
||||||
|
clear() {
|
||||||
|
this.models.clear()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取已加载的模型统计
|
||||||
|
* @returns {Object} 统计信息
|
||||||
|
*/
|
||||||
|
getStats() {
|
||||||
|
let totalFiles = 0
|
||||||
|
let totalSize = 0
|
||||||
|
|
||||||
|
for (const files of this.models.values()) {
|
||||||
|
totalFiles += files.size
|
||||||
|
for (const fileData of files.values()) {
|
||||||
|
totalSize += fileData.byteLength
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
modelCount: this.models.size,
|
||||||
|
fileCount: totalFiles,
|
||||||
|
totalSize,
|
||||||
|
models: Array.from(this.models.keys())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 验证打包格式的兼容性
|
||||||
|
* 用于测试与Python版本的一致性
|
||||||
|
* @returns {Object} 验证结果
|
||||||
|
*/
|
||||||
|
validatePackingCompatibility() {
|
||||||
|
// 测试字符串打包
|
||||||
|
const testString = "test_model"
|
||||||
|
const packedString = this.packString(testString, 32)
|
||||||
|
|
||||||
|
// 测试整数打包
|
||||||
|
const testInt = 0x12345678
|
||||||
|
const packedInt = this.packUint32(testInt)
|
||||||
|
|
||||||
|
return {
|
||||||
|
stringPacking: {
|
||||||
|
input: testString,
|
||||||
|
output: Array.from(packedString).map(b => `0x${b.toString(16).padStart(2, '0')}`),
|
||||||
|
isASCII: packedString.every((b, i) => i >= testString.length || b === testString.charCodeAt(i))
|
||||||
|
},
|
||||||
|
intPacking: {
|
||||||
|
input: `0x${testInt.toString(16)}`,
|
||||||
|
output: Array.from(packedInt).map(b => `0x${b.toString(16).padStart(2, '0')}`),
|
||||||
|
isLittleEndian: packedInt[0] === 0x78 && packedInt[3] === 0x12
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default WakenetModelPacker
|
||||||
|
|
||||||
16
main/manager-web/src/utils/font_conv/AppError.js
Normal file
16
main/manager-web/src/utils/font_conv/AppError.js
Normal file
|
|
@ -0,0 +1,16 @@
|
||||||
|
// Custom Error type to simplify error messaging
|
||||||
|
// ES6 版本
|
||||||
|
|
||||||
|
class AppError extends Error {
|
||||||
|
constructor(message) {
|
||||||
|
super(message)
|
||||||
|
this.name = 'AppError'
|
||||||
|
|
||||||
|
// 保持堆栈跟踪 (仅在 V8 引擎中可用)
|
||||||
|
if (Error.captureStackTrace) {
|
||||||
|
Error.captureStackTrace(this, AppError)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default AppError
|
||||||
469
main/manager-web/src/utils/font_conv/BrowserFontConverter.js
Normal file
469
main/manager-web/src/utils/font_conv/BrowserFontConverter.js
Normal file
|
|
@ -0,0 +1,469 @@
|
||||||
|
/**
|
||||||
|
* BrowserFontConverter - 完整的浏览器端字体转换器
|
||||||
|
* 基于 lv_font_conv 的核心逻辑,适配浏览器环境
|
||||||
|
*/
|
||||||
|
|
||||||
|
import opentype from 'opentype.js'
|
||||||
|
import collect_font_data from './CollectFontData.js'
|
||||||
|
import AppError from './AppError.js'
|
||||||
|
import write_cbin from './writers/CBinWriter.js'
|
||||||
|
|
||||||
|
class BrowserFontConverter {
|
||||||
|
constructor() {
|
||||||
|
this.initialized = false
|
||||||
|
this.supportedFormats = ['ttf', 'woff', 'woff2', 'otf']
|
||||||
|
this.charsetCache = new Map() // 缓存已加载的字符集
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 初始化转换器
|
||||||
|
*/
|
||||||
|
async initialize() {
|
||||||
|
if (this.initialized) return
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 检查依赖是否可用
|
||||||
|
if (typeof opentype === 'undefined') {
|
||||||
|
throw new Error('opentype.js 未加载')
|
||||||
|
}
|
||||||
|
|
||||||
|
this.initialized = true
|
||||||
|
console.log('BrowserFontConverter 初始化完成')
|
||||||
|
} catch (error) {
|
||||||
|
console.error('BrowserFontConverter 初始化失败:', error)
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 验证字体文件
|
||||||
|
*/
|
||||||
|
validateFont(fontFile) {
|
||||||
|
if (!fontFile) return false
|
||||||
|
|
||||||
|
if (fontFile instanceof File) {
|
||||||
|
const fileName = fontFile.name.toLowerCase()
|
||||||
|
const fileType = fontFile.type.toLowerCase()
|
||||||
|
|
||||||
|
const validExtension = this.supportedFormats.some(ext =>
|
||||||
|
fileName.endsWith(`.${ext}`)
|
||||||
|
)
|
||||||
|
|
||||||
|
const validMimeType = [
|
||||||
|
'font/ttf', 'font/truetype', 'application/x-font-ttf',
|
||||||
|
'font/woff', 'font/woff2', 'application/font-woff',
|
||||||
|
'font/otf', 'application/x-font-otf'
|
||||||
|
].some(type => fileType.includes(type))
|
||||||
|
|
||||||
|
return validExtension || validMimeType
|
||||||
|
}
|
||||||
|
|
||||||
|
return fontFile instanceof ArrayBuffer && fontFile.byteLength > 0
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取字体信息
|
||||||
|
*/
|
||||||
|
async getFontInfo(fontFile) {
|
||||||
|
try {
|
||||||
|
let buffer
|
||||||
|
|
||||||
|
if (fontFile instanceof File) {
|
||||||
|
buffer = await fontFile.arrayBuffer()
|
||||||
|
} else if (fontFile instanceof ArrayBuffer) {
|
||||||
|
buffer = fontFile
|
||||||
|
} else {
|
||||||
|
throw new Error('不支持的字体文件类型')
|
||||||
|
}
|
||||||
|
|
||||||
|
const font = opentype.parse(buffer)
|
||||||
|
|
||||||
|
return {
|
||||||
|
familyName: this.getLocalizedName(font.names.fontFamily) || 'Unknown',
|
||||||
|
fullName: this.getLocalizedName(font.names.fullName) || 'Unknown',
|
||||||
|
postScriptName: this.getLocalizedName(font.names.postScriptName) || 'Unknown',
|
||||||
|
version: this.getLocalizedName(font.names.version) || 'Unknown',
|
||||||
|
unitsPerEm: font.unitsPerEm,
|
||||||
|
ascender: font.ascender,
|
||||||
|
descender: font.descender,
|
||||||
|
numGlyphs: font.numGlyphs,
|
||||||
|
supported: true
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('获取字体信息失败:', error)
|
||||||
|
return {
|
||||||
|
familyName: 'Unknown',
|
||||||
|
supported: false,
|
||||||
|
error: error.message
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取本地化名称
|
||||||
|
*/
|
||||||
|
getLocalizedName(nameObj) {
|
||||||
|
if (!nameObj) return null
|
||||||
|
|
||||||
|
// 优先级:中文 > 英文 > 第一个可用的
|
||||||
|
return nameObj['zh'] || nameObj['zh-CN'] || nameObj['en'] ||
|
||||||
|
nameObj[Object.keys(nameObj)[0]]
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 转换字体为 CBIN 格式
|
||||||
|
*/
|
||||||
|
async convertToCBIN(options) {
|
||||||
|
if (!this.initialized) {
|
||||||
|
await this.initialize()
|
||||||
|
}
|
||||||
|
|
||||||
|
const {
|
||||||
|
fontFile,
|
||||||
|
fontName,
|
||||||
|
fontSize = 20,
|
||||||
|
bpp = 4,
|
||||||
|
charset = 'deepseek',
|
||||||
|
symbols = '',
|
||||||
|
range = '',
|
||||||
|
compression = false,
|
||||||
|
lcd = false,
|
||||||
|
lcd_v = false,
|
||||||
|
progressCallback = null
|
||||||
|
} = options
|
||||||
|
|
||||||
|
if (!this.validateFont(fontFile)) {
|
||||||
|
throw new AppError('不支持的字体文件格式')
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (progressCallback) progressCallback(0, '开始处理字体...')
|
||||||
|
|
||||||
|
// 准备字体数据
|
||||||
|
let fontBuffer
|
||||||
|
if (fontFile instanceof File) {
|
||||||
|
fontBuffer = await fontFile.arrayBuffer()
|
||||||
|
} else {
|
||||||
|
fontBuffer = fontFile
|
||||||
|
}
|
||||||
|
|
||||||
|
if (progressCallback) progressCallback(10, '解析字体结构...')
|
||||||
|
|
||||||
|
// 构建字符范围和符号(使用异步版本支持从文件加载字符集)
|
||||||
|
const { ranges, charSymbols } = await this.parseCharacterInputAsync(charset, symbols, range)
|
||||||
|
|
||||||
|
if (progressCallback) progressCallback(20, '准备转换参数...')
|
||||||
|
|
||||||
|
// 构建转换参数
|
||||||
|
const convertArgs = {
|
||||||
|
font: [{
|
||||||
|
source_path: fontName || 'custom_font',
|
||||||
|
source_bin: fontBuffer,
|
||||||
|
ranges: [{
|
||||||
|
range: ranges,
|
||||||
|
symbols: charSymbols
|
||||||
|
}],
|
||||||
|
autohint_off: false,
|
||||||
|
autohint_strong: false
|
||||||
|
}],
|
||||||
|
size: fontSize,
|
||||||
|
bpp: bpp,
|
||||||
|
lcd: lcd,
|
||||||
|
lcd_v: lcd_v,
|
||||||
|
no_compress: !compression,
|
||||||
|
no_kerning: false,
|
||||||
|
use_color_info: false,
|
||||||
|
format: 'cbin',
|
||||||
|
output: fontName || 'font'
|
||||||
|
}
|
||||||
|
|
||||||
|
if (progressCallback) progressCallback(30, '收集字体数据...')
|
||||||
|
|
||||||
|
// 收集字体数据
|
||||||
|
const fontData = await collect_font_data(convertArgs)
|
||||||
|
|
||||||
|
if (progressCallback) progressCallback(70, '生成 CBIN 格式...')
|
||||||
|
|
||||||
|
// 生成 CBIN 数据
|
||||||
|
const result = write_cbin(convertArgs, fontData)
|
||||||
|
const outputName = convertArgs.output
|
||||||
|
|
||||||
|
if (progressCallback) progressCallback(100, '转换完成!')
|
||||||
|
|
||||||
|
return result[outputName]
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('字体转换失败:', error)
|
||||||
|
throw new AppError(`字体转换失败: ${error.message}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析字符输入(字符集、符号、范围)- 异步版本
|
||||||
|
*/
|
||||||
|
async parseCharacterInputAsync(charset, symbols, range) {
|
||||||
|
let ranges = []
|
||||||
|
let charSymbols = symbols || ''
|
||||||
|
|
||||||
|
// 处理预设字符集
|
||||||
|
if (charset && charset !== 'custom') {
|
||||||
|
const presetChars = await this.getCharsetContentAsync(charset)
|
||||||
|
charSymbols = presetChars + charSymbols
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理 Unicode 范围
|
||||||
|
if (range) {
|
||||||
|
ranges = this.parseUnicodeRange(range)
|
||||||
|
}
|
||||||
|
|
||||||
|
return { ranges, charSymbols }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析字符输入(字符集、符号、范围)- 同步版本(向后兼容)
|
||||||
|
*/
|
||||||
|
parseCharacterInput(charset, symbols, range) {
|
||||||
|
let ranges = []
|
||||||
|
let charSymbols = symbols || ''
|
||||||
|
|
||||||
|
// 处理预设字符集
|
||||||
|
if (charset && charset !== 'custom') {
|
||||||
|
const presetChars = this.getCharsetContent(charset)
|
||||||
|
charSymbols = presetChars + charSymbols
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理 Unicode 范围
|
||||||
|
if (range) {
|
||||||
|
ranges = this.parseUnicodeRange(range)
|
||||||
|
}
|
||||||
|
|
||||||
|
return { ranges, charSymbols }
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 异步加载字符集文件
|
||||||
|
*/
|
||||||
|
async loadCharsetFromFile(charset) {
|
||||||
|
const charsetFiles = {
|
||||||
|
latin: './static/charsets/latin1.txt',
|
||||||
|
deepseek: './static/charsets/deepseek.txt',
|
||||||
|
gb2312: './static/charsets/gb2312.txt'
|
||||||
|
}
|
||||||
|
|
||||||
|
const filePath = charsetFiles[charset]
|
||||||
|
if (!filePath) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(filePath)
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`Failed to load charset file: ${response.status}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const text = await response.text()
|
||||||
|
// 将每行的字符连接成一个字符串,保留所有字符(包括空白字符)
|
||||||
|
const characters = text.split('\n').join('')
|
||||||
|
|
||||||
|
// 缓存结果
|
||||||
|
this.charsetCache.set(charset, characters)
|
||||||
|
return characters
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Failed to load charset ${charset}:`, error)
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取字符集内容(同步方法,用于已缓存的字符集)
|
||||||
|
*/
|
||||||
|
getCharsetContent(charset) {
|
||||||
|
const charsets = {}
|
||||||
|
|
||||||
|
// 如果是需要从文件加载的字符集,先检查缓存
|
||||||
|
if ((charset === 'latin' || charset === 'deepseek' || charset === 'gb2312') && this.charsetCache.has(charset)) {
|
||||||
|
return this.charsetCache.get(charset)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果请求 basic,重定向到 latin(向后兼容)
|
||||||
|
if (charset === 'basic') {
|
||||||
|
return this.getCharsetContent('latin')
|
||||||
|
}
|
||||||
|
|
||||||
|
// 默认返回空字符串,需要先调用异步方法加载
|
||||||
|
return charsets[charset] || ''
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 异步获取字符集内容
|
||||||
|
*/
|
||||||
|
async getCharsetContentAsync(charset) {
|
||||||
|
// 如果请求 basic,重定向到 latin(向后兼容)
|
||||||
|
if (charset === 'basic') {
|
||||||
|
charset = 'latin'
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果字符集已缓存,直接返回
|
||||||
|
if (this.charsetCache.has(charset)) {
|
||||||
|
return this.charsetCache.get(charset)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 对于需要从文件加载的字符集
|
||||||
|
if (charset === 'latin' || charset === 'deepseek' || charset === 'gb2312') {
|
||||||
|
const loadedCharset = await this.loadCharsetFromFile(charset)
|
||||||
|
if (loadedCharset) {
|
||||||
|
return loadedCharset
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 回退到同步方法
|
||||||
|
return this.getCharsetContent(charset)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析 Unicode 范围字符串
|
||||||
|
*/
|
||||||
|
parseUnicodeRange(rangeStr) {
|
||||||
|
const ranges = []
|
||||||
|
const parts = rangeStr.split(',')
|
||||||
|
|
||||||
|
for (const part of parts) {
|
||||||
|
const trimmed = part.trim()
|
||||||
|
if (!trimmed) continue
|
||||||
|
|
||||||
|
if (trimmed.includes('-')) {
|
||||||
|
const [start, end] = trimmed.split('-')
|
||||||
|
const startCode = this.parseHexOrDec(start)
|
||||||
|
const endCode = this.parseHexOrDec(end)
|
||||||
|
|
||||||
|
if (startCode !== null && endCode !== null) {
|
||||||
|
ranges.push(startCode, endCode, startCode)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const code = this.parseHexOrDec(trimmed)
|
||||||
|
if (code !== null) {
|
||||||
|
ranges.push(code, code, code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return ranges
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析十六进制或十进制数字
|
||||||
|
*/
|
||||||
|
parseHexOrDec(str) {
|
||||||
|
const trimmed = str.trim()
|
||||||
|
|
||||||
|
if (trimmed.startsWith('0x') || trimmed.startsWith('0X')) {
|
||||||
|
const parsed = parseInt(trimmed, 16)
|
||||||
|
return isNaN(parsed) ? null : parsed
|
||||||
|
}
|
||||||
|
|
||||||
|
const parsed = parseInt(trimmed, 10)
|
||||||
|
return isNaN(parsed) ? null : parsed
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 估算输出大小 - 异步版本
|
||||||
|
*/
|
||||||
|
async estimateSizeAsync(options) {
|
||||||
|
const { fontSize = 20, bpp = 4, charset = 'latin', symbols = '', range = '' } = options
|
||||||
|
|
||||||
|
// 计算字符数量
|
||||||
|
let charCount = symbols.length
|
||||||
|
|
||||||
|
if (charset && charset !== 'custom') {
|
||||||
|
const charsetContent = await this.getCharsetContentAsync(charset)
|
||||||
|
charCount += charsetContent.length
|
||||||
|
}
|
||||||
|
|
||||||
|
if (range) {
|
||||||
|
const ranges = this.parseUnicodeRange(range)
|
||||||
|
for (let i = 0; i < ranges.length; i += 3) {
|
||||||
|
charCount += ranges[i + 1] - ranges[i] + 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 去重字符数(粗略估算)
|
||||||
|
charCount = Math.min(charCount, charCount * 0.8)
|
||||||
|
|
||||||
|
// 估算每个字符的字节数
|
||||||
|
const avgBytesPerChar = Math.ceil((fontSize * fontSize * bpp) / 8) + 40
|
||||||
|
|
||||||
|
const estimatedSize = charCount * avgBytesPerChar + 2048 // 加上头部和索引
|
||||||
|
|
||||||
|
return {
|
||||||
|
characterCount: Math.floor(charCount),
|
||||||
|
avgBytesPerChar,
|
||||||
|
estimatedSize,
|
||||||
|
formattedSize: this.formatBytes(estimatedSize)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 估算输出大小 - 同步版本(向后兼容)
|
||||||
|
*/
|
||||||
|
estimateSize(options) {
|
||||||
|
const { fontSize = 20, bpp = 4, charset = 'latin', symbols = '', range = '' } = options
|
||||||
|
|
||||||
|
// 计算字符数量
|
||||||
|
let charCount = symbols.length
|
||||||
|
|
||||||
|
if (charset && charset !== 'custom') {
|
||||||
|
const charsetContent = this.getCharsetContent(charset)
|
||||||
|
charCount += charsetContent.length
|
||||||
|
}
|
||||||
|
|
||||||
|
if (range) {
|
||||||
|
const ranges = this.parseUnicodeRange(range)
|
||||||
|
for (let i = 0; i < ranges.length; i += 3) {
|
||||||
|
charCount += ranges[i + 1] - ranges[i] + 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 去重字符数(粗略估算)
|
||||||
|
charCount = Math.min(charCount, charCount * 0.8)
|
||||||
|
|
||||||
|
// 估算每个字符的字节数
|
||||||
|
const avgBytesPerChar = Math.ceil((fontSize * fontSize * bpp) / 8) + 40
|
||||||
|
|
||||||
|
const estimatedSize = charCount * avgBytesPerChar + 2048 // 加上头部和索引
|
||||||
|
|
||||||
|
return {
|
||||||
|
characterCount: Math.floor(charCount),
|
||||||
|
avgBytesPerChar,
|
||||||
|
estimatedSize,
|
||||||
|
formattedSize: this.formatBytes(estimatedSize)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 格式化字节大小
|
||||||
|
*/
|
||||||
|
formatBytes(bytes) {
|
||||||
|
if (bytes === 0) return '0 Bytes'
|
||||||
|
|
||||||
|
const k = 1024
|
||||||
|
const sizes = ['Bytes', 'KB', 'MB', 'GB']
|
||||||
|
const i = Math.floor(Math.log(bytes) / Math.log(k))
|
||||||
|
|
||||||
|
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清理资源
|
||||||
|
*/
|
||||||
|
cleanup() {
|
||||||
|
// 清理可能的资源引用
|
||||||
|
this.initialized = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 创建单例实例
|
||||||
|
const browserFontConverter = new BrowserFontConverter()
|
||||||
|
|
||||||
|
export default browserFontConverter
|
||||||
|
export { BrowserFontConverter }
|
||||||
174
main/manager-web/src/utils/font_conv/CollectFontData.js
Normal file
174
main/manager-web/src/utils/font_conv/CollectFontData.js
Normal file
|
|
@ -0,0 +1,174 @@
|
||||||
|
// Read fonts - ES6 version for browser
|
||||||
|
// 核心字体数据收集模块
|
||||||
|
|
||||||
|
import opentype from 'opentype.js'
|
||||||
|
import * as ft_render from './FreeType.js'
|
||||||
|
import AppError from './AppError.js'
|
||||||
|
import Ranger from './Ranger.js'
|
||||||
|
|
||||||
|
export default async function collect_font_data(args) {
|
||||||
|
await ft_render.init()
|
||||||
|
|
||||||
|
// Duplicate font options as k/v for quick access
|
||||||
|
let fonts_options = {}
|
||||||
|
args.font.forEach(f => { fonts_options[f.source_path] = f })
|
||||||
|
|
||||||
|
// read fonts
|
||||||
|
let fonts_opentype = {}
|
||||||
|
let fonts_freetype = {}
|
||||||
|
|
||||||
|
for (let { source_path, source_bin } of args.font) {
|
||||||
|
// don't load font again if it's specified multiple times in args
|
||||||
|
if (fonts_opentype[source_path]) continue
|
||||||
|
|
||||||
|
try {
|
||||||
|
let b = source_bin
|
||||||
|
|
||||||
|
// 处理不同类型的输入数据
|
||||||
|
if (b instanceof File) {
|
||||||
|
b = await b.arrayBuffer()
|
||||||
|
} else if (b instanceof Uint8Array) {
|
||||||
|
// Uint8Array
|
||||||
|
b = b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength)
|
||||||
|
}
|
||||||
|
|
||||||
|
fonts_opentype[source_path] = opentype.parse(b)
|
||||||
|
|
||||||
|
// 使用处理后的数据创建 FreeType 字体实例
|
||||||
|
fonts_freetype[source_path] = ft_render.fontface_create(b, args.size)
|
||||||
|
} catch (err) {
|
||||||
|
throw new AppError(`Cannot load font "${source_path}": ${err.message}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// merge all ranges
|
||||||
|
let ranger = new Ranger()
|
||||||
|
|
||||||
|
for (let { source_path, ranges } of args.font) {
|
||||||
|
let font = fonts_freetype[source_path]
|
||||||
|
|
||||||
|
for (let item of ranges) {
|
||||||
|
/* eslint-disable max-depth */
|
||||||
|
if (item.range) {
|
||||||
|
for (let i = 0; i < item.range.length; i += 3) {
|
||||||
|
let range = item.range.slice(i, i + 3)
|
||||||
|
let chars = ranger.add_range(source_path, ...range)
|
||||||
|
let is_empty = true
|
||||||
|
|
||||||
|
for (let code of chars) {
|
||||||
|
if (ft_render.glyph_exists(font, code)) {
|
||||||
|
is_empty = false
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (is_empty) {
|
||||||
|
let a = '0x' + range[0].toString(16)
|
||||||
|
let b = '0x' + range[1].toString(16)
|
||||||
|
throw new AppError(`Font "${source_path}" doesn't have any characters included in range ${a}-${b}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (item.symbols) {
|
||||||
|
let chars = ranger.add_symbols(source_path, item.symbols)
|
||||||
|
let is_empty = true
|
||||||
|
|
||||||
|
for (let code of chars) {
|
||||||
|
if (ft_render.glyph_exists(font, code)) {
|
||||||
|
is_empty = false
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (is_empty) {
|
||||||
|
throw new AppError(`Font "${source_path}" doesn't have any characters included in "${item.symbols}"`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mapping = ranger.get()
|
||||||
|
let glyphs = []
|
||||||
|
let all_dst_charcodes = Object.keys(mapping).sort((a, b) => a - b).map(Number)
|
||||||
|
|
||||||
|
for (let dst_code of all_dst_charcodes) {
|
||||||
|
let src_code = mapping[dst_code].code
|
||||||
|
let src_font = mapping[dst_code].font
|
||||||
|
|
||||||
|
if (!ft_render.glyph_exists(fonts_freetype[src_font], src_code)) continue
|
||||||
|
|
||||||
|
let ft_result = ft_render.glyph_render(
|
||||||
|
fonts_freetype[src_font],
|
||||||
|
src_code,
|
||||||
|
{
|
||||||
|
autohint_off: fonts_options[src_font].autohint_off,
|
||||||
|
autohint_strong: fonts_options[src_font].autohint_strong,
|
||||||
|
lcd: args.lcd,
|
||||||
|
lcd_v: args.lcd_v,
|
||||||
|
mono: !args.lcd && !args.lcd_v && args.bpp === 1,
|
||||||
|
use_color_info: args.use_color_info
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
glyphs.push({
|
||||||
|
code: dst_code,
|
||||||
|
advanceWidth: ft_result.advance_x,
|
||||||
|
bbox: {
|
||||||
|
x: ft_result.x,
|
||||||
|
y: ft_result.y - ft_result.height,
|
||||||
|
width: ft_result.width,
|
||||||
|
height: ft_result.height
|
||||||
|
},
|
||||||
|
kerning: {},
|
||||||
|
freetype: ft_result.freetype,
|
||||||
|
pixels: ft_result.pixels
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!args.no_kerning) {
|
||||||
|
let existing_dst_charcodes = glyphs.map(g => g.code)
|
||||||
|
|
||||||
|
for (let { code, kerning } of glyphs) {
|
||||||
|
let src_code = mapping[code].code
|
||||||
|
let src_font = mapping[code].font
|
||||||
|
let font = fonts_opentype[src_font]
|
||||||
|
let glyph = font.charToGlyph(String.fromCodePoint(src_code))
|
||||||
|
|
||||||
|
for (let dst_code2 of existing_dst_charcodes) {
|
||||||
|
// can't merge kerning values from 2 different fonts
|
||||||
|
if (mapping[dst_code2].font !== src_font) continue
|
||||||
|
|
||||||
|
let src_code2 = mapping[dst_code2].code
|
||||||
|
let glyph2 = font.charToGlyph(String.fromCodePoint(src_code2))
|
||||||
|
let krn_value = font.getKerningValue(glyph, glyph2)
|
||||||
|
|
||||||
|
if (krn_value) kerning[dst_code2] = krn_value * args.size / font.unitsPerEm
|
||||||
|
|
||||||
|
//let krn_value = ft_render.get_kerning(font, src_code, src_code2).x;
|
||||||
|
//if (krn_value) kerning[dst_code2] = krn_value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let first_font = fonts_freetype[args.font[0].source_path]
|
||||||
|
let first_font_scale = args.size / first_font.units_per_em
|
||||||
|
let os2_metrics = ft_render.fontface_os2_table(first_font)
|
||||||
|
let post_table = fonts_opentype[args.font[0].source_path].tables.post
|
||||||
|
|
||||||
|
for (let font of Object.values(fonts_freetype)) ft_render.fontface_destroy(font)
|
||||||
|
|
||||||
|
ft_render.destroy()
|
||||||
|
|
||||||
|
return {
|
||||||
|
ascent: Math.max(...glyphs.map(g => g.bbox.y + g.bbox.height)),
|
||||||
|
descent: Math.min(...glyphs.map(g => g.bbox.y)),
|
||||||
|
typoAscent: Math.round(os2_metrics.typoAscent * first_font_scale),
|
||||||
|
typoDescent: Math.round(os2_metrics.typoDescent * first_font_scale),
|
||||||
|
typoLineGap: Math.round(os2_metrics.typoLineGap * first_font_scale),
|
||||||
|
size: args.size,
|
||||||
|
glyphs,
|
||||||
|
underlinePosition: Math.round(post_table.underlinePosition * first_font_scale),
|
||||||
|
underlineThickness: Math.round(post_table.underlineThickness * first_font_scale)
|
||||||
|
}
|
||||||
|
}
|
||||||
326
main/manager-web/src/utils/font_conv/FreeType.js
Normal file
326
main/manager-web/src/utils/font_conv/FreeType.js
Normal file
|
|
@ -0,0 +1,326 @@
|
||||||
|
// FreeType interface for browser
|
||||||
|
// ES6 版本,适配浏览器环境
|
||||||
|
|
||||||
|
const ft_render_fabric = () => import('./freetype_build/ft_render.js')
|
||||||
|
|
||||||
|
let m = null // compiled module instance
|
||||||
|
let library = 0 // pointer to library struct in wasm memory
|
||||||
|
|
||||||
|
// workaround because of bug in emscripten:
|
||||||
|
// https://github.com/emscripten-core/emscripten/issues/5820
|
||||||
|
const runtime_initialized = new Promise(resolve => {
|
||||||
|
ft_render_fabric().then(module => {
|
||||||
|
module.default().then(module_instance => {
|
||||||
|
m = module_instance
|
||||||
|
resolve()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
function from_16_16(fixed_point) {
|
||||||
|
return fixed_point / (1 << 16)
|
||||||
|
}
|
||||||
|
|
||||||
|
function from_26_6(fixed_point) {
|
||||||
|
return fixed_point / (1 << 6)
|
||||||
|
}
|
||||||
|
|
||||||
|
function int8_to_uint8(value) {
|
||||||
|
return value >= 0 ? value : value + 0x100
|
||||||
|
}
|
||||||
|
|
||||||
|
let FT_New_Memory_Face,
|
||||||
|
FT_Set_Char_Size,
|
||||||
|
FT_Set_Pixel_Sizes,
|
||||||
|
FT_Get_Char_Index,
|
||||||
|
FT_Load_Glyph,
|
||||||
|
FT_Get_Sfnt_Table,
|
||||||
|
FT_Get_Kerning,
|
||||||
|
FT_Done_Face
|
||||||
|
|
||||||
|
export async function init() {
|
||||||
|
await runtime_initialized
|
||||||
|
m._init_constants()
|
||||||
|
|
||||||
|
FT_New_Memory_Face =
|
||||||
|
m.cwrap('FT_New_Memory_Face', 'number', [ 'number', 'number', 'number', 'number', 'number' ])
|
||||||
|
|
||||||
|
FT_Set_Char_Size =
|
||||||
|
m.cwrap('FT_Set_Char_Size', 'number', [ 'number', 'number', 'number', 'number', 'number' ])
|
||||||
|
|
||||||
|
FT_Set_Pixel_Sizes =
|
||||||
|
m.cwrap('FT_Set_Pixel_Sizes', 'number', [ 'number', 'number', 'number' ])
|
||||||
|
|
||||||
|
FT_Get_Char_Index =
|
||||||
|
m.cwrap('FT_Get_Char_Index', 'number', [ 'number', 'number' ])
|
||||||
|
|
||||||
|
FT_Load_Glyph =
|
||||||
|
m.cwrap('FT_Load_Glyph', 'number', [ 'number', 'number', 'number' ])
|
||||||
|
|
||||||
|
FT_Get_Sfnt_Table =
|
||||||
|
m.cwrap('FT_Get_Sfnt_Table', 'number', [ 'number', 'number' ])
|
||||||
|
|
||||||
|
FT_Get_Kerning =
|
||||||
|
m.cwrap('FT_Get_Kerning', 'number', [ 'number', 'number', 'number', 'number', 'number' ])
|
||||||
|
|
||||||
|
FT_Done_Face =
|
||||||
|
m.cwrap('FT_Done_Face', 'number', [ 'number' ])
|
||||||
|
|
||||||
|
if (!library) {
|
||||||
|
let ptr = m._malloc(4)
|
||||||
|
|
||||||
|
try {
|
||||||
|
let error = m.ccall('FT_Init_FreeType', 'number', [ 'number' ], [ ptr ])
|
||||||
|
|
||||||
|
if (error) throw new Error(`error in FT_Init_FreeType: ${error}`)
|
||||||
|
|
||||||
|
library = m.getValue(ptr, 'i32')
|
||||||
|
} finally {
|
||||||
|
m._free(ptr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function fontface_create(source, size) {
|
||||||
|
let error
|
||||||
|
|
||||||
|
// 正确计算字体数据的长度
|
||||||
|
let fontLength
|
||||||
|
if (source instanceof ArrayBuffer) {
|
||||||
|
fontLength = source.byteLength
|
||||||
|
} else if (source instanceof Uint8Array) {
|
||||||
|
fontLength = source.byteLength
|
||||||
|
} else if (source && typeof source.length === 'number') {
|
||||||
|
fontLength = source.length
|
||||||
|
} else {
|
||||||
|
throw new Error('Invalid font source format')
|
||||||
|
}
|
||||||
|
|
||||||
|
let face = {
|
||||||
|
ptr: 0,
|
||||||
|
font: m._malloc(fontLength)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 将 ArrayBuffer 或 Uint8Array 转换为内存
|
||||||
|
const sourceArray = source instanceof ArrayBuffer ? new Uint8Array(source) : source
|
||||||
|
m.writeArrayToMemory(sourceArray, face.font)
|
||||||
|
|
||||||
|
let ptr = m._malloc(4)
|
||||||
|
|
||||||
|
try {
|
||||||
|
error = FT_New_Memory_Face(library, face.font, fontLength, 0, ptr)
|
||||||
|
|
||||||
|
if (error) throw new Error(`error in FT_New_Memory_Face: ${error}`)
|
||||||
|
|
||||||
|
face.ptr = m.getValue(ptr, 'i32')
|
||||||
|
} finally {
|
||||||
|
m._free(ptr)
|
||||||
|
}
|
||||||
|
|
||||||
|
error = FT_Set_Char_Size(face.ptr, 0, size * 64, 300, 300)
|
||||||
|
|
||||||
|
if (error) throw new Error(`error in FT_Set_Char_Size: ${error}`)
|
||||||
|
|
||||||
|
error = FT_Set_Pixel_Sizes(face.ptr, 0, size)
|
||||||
|
|
||||||
|
if (error) throw new Error(`error in FT_Set_Pixel_Sizes: ${error}`)
|
||||||
|
|
||||||
|
let units_per_em = m.getValue(face.ptr + m.OFFSET_FACE_UNITS_PER_EM, 'i16')
|
||||||
|
let ascender = m.getValue(face.ptr + m.OFFSET_FACE_ASCENDER, 'i16')
|
||||||
|
let descender = m.getValue(face.ptr + m.OFFSET_FACE_DESCENDER, 'i16')
|
||||||
|
let height = m.getValue(face.ptr + m.OFFSET_FACE_HEIGHT, 'i16')
|
||||||
|
|
||||||
|
return Object.assign(face, {
|
||||||
|
units_per_em,
|
||||||
|
ascender,
|
||||||
|
descender,
|
||||||
|
height
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function fontface_os2_table(face) {
|
||||||
|
let sfnt_ptr = FT_Get_Sfnt_Table(face.ptr, m.FT_SFNT_OS2)
|
||||||
|
|
||||||
|
if (!sfnt_ptr) throw new Error('os/2 table not found for this font')
|
||||||
|
|
||||||
|
let typoAscent = m.getValue(sfnt_ptr + m.OFFSET_TT_OS2_ASCENDER, 'i16')
|
||||||
|
let typoDescent = m.getValue(sfnt_ptr + m.OFFSET_TT_OS2_DESCENDER, 'i16')
|
||||||
|
let typoLineGap = m.getValue(sfnt_ptr + m.OFFSET_TT_OS2_LINEGAP, 'i16')
|
||||||
|
|
||||||
|
return {
|
||||||
|
typoAscent,
|
||||||
|
typoDescent,
|
||||||
|
typoLineGap
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function get_kerning(face, code1, code2) {
|
||||||
|
let glyph1 = FT_Get_Char_Index(face.ptr, code1)
|
||||||
|
let glyph2 = FT_Get_Char_Index(face.ptr, code2)
|
||||||
|
let ptr = m._malloc(4 * 2)
|
||||||
|
|
||||||
|
try {
|
||||||
|
let error = FT_Get_Kerning(face.ptr, glyph1, glyph2, m.FT_KERNING_DEFAULT, ptr)
|
||||||
|
|
||||||
|
if (error) throw new Error(`error in FT_Get_Kerning: ${error}`)
|
||||||
|
|
||||||
|
return {
|
||||||
|
x: from_26_6(m.getValue(ptr, 'i32')),
|
||||||
|
y: from_26_6(m.getValue(ptr + 4, 'i32'))
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
m._free(ptr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function glyph_exists(face, code) {
|
||||||
|
let glyph_index = FT_Get_Char_Index(face.ptr, code)
|
||||||
|
|
||||||
|
return glyph_index !== 0
|
||||||
|
}
|
||||||
|
|
||||||
|
export function glyph_render(face, code, opts = {}) {
|
||||||
|
let glyph_index = FT_Get_Char_Index(face.ptr, code)
|
||||||
|
|
||||||
|
if (glyph_index === 0) throw new Error(`glyph does not exist for codepoint ${code}`)
|
||||||
|
|
||||||
|
let load_flags = m.FT_LOAD_RENDER
|
||||||
|
|
||||||
|
if (opts.mono) {
|
||||||
|
load_flags |= m.FT_LOAD_TARGET_MONO
|
||||||
|
|
||||||
|
} else if (opts.lcd) {
|
||||||
|
load_flags |= m.FT_LOAD_TARGET_LCD
|
||||||
|
|
||||||
|
} else if (opts.lcd_v) {
|
||||||
|
load_flags |= m.FT_LOAD_TARGET_LCD_V
|
||||||
|
|
||||||
|
} else {
|
||||||
|
/* eslint-disable no-lonely-if */
|
||||||
|
|
||||||
|
// Use "light" by default, it changes horizontal lines only.
|
||||||
|
// "normal" is more strong (with vertical lines), but will break kerning, if
|
||||||
|
// no additional care taken. More advanced rendering requires upper level
|
||||||
|
// layout support (via Harfbuzz, for example).
|
||||||
|
if (!opts.autohint_strong) load_flags |= m.FT_LOAD_TARGET_LIGHT
|
||||||
|
else load_flags |= m.FT_LOAD_TARGET_NORMAL
|
||||||
|
}
|
||||||
|
|
||||||
|
if (opts.autohint_off) load_flags |= m.FT_LOAD_NO_AUTOHINT
|
||||||
|
else load_flags |= m.FT_LOAD_FORCE_AUTOHINT
|
||||||
|
|
||||||
|
if (opts.use_color_info) load_flags |= m.FT_LOAD_COLOR
|
||||||
|
|
||||||
|
let error = FT_Load_Glyph(face.ptr, glyph_index, load_flags)
|
||||||
|
|
||||||
|
if (error) throw new Error(`error in FT_Load_Glyph: ${error}`)
|
||||||
|
|
||||||
|
let glyph = m.getValue(face.ptr + m.OFFSET_FACE_GLYPH, 'i32')
|
||||||
|
|
||||||
|
let glyph_data = {
|
||||||
|
glyph_index: m.getValue(glyph + m.OFFSET_GLYPH_INDEX, 'i32'),
|
||||||
|
metrics: {
|
||||||
|
width: from_26_6(m.getValue(glyph + m.OFFSET_GLYPH_METRICS_WIDTH, 'i32')),
|
||||||
|
height: from_26_6(m.getValue(glyph + m.OFFSET_GLYPH_METRICS_HEIGHT, 'i32')),
|
||||||
|
horiBearingX: from_26_6(m.getValue(glyph + m.OFFSET_GLYPH_METRICS_HORI_BEARING_X, 'i32')),
|
||||||
|
horiBearingY: from_26_6(m.getValue(glyph + m.OFFSET_GLYPH_METRICS_HORI_BEARING_Y, 'i32')),
|
||||||
|
horiAdvance: from_26_6(m.getValue(glyph + m.OFFSET_GLYPH_METRICS_HORI_ADVANCE, 'i32')),
|
||||||
|
vertBearingX: from_26_6(m.getValue(glyph + m.OFFSET_GLYPH_METRICS_VERT_BEARING_X, 'i32')),
|
||||||
|
vertBearingY: from_26_6(m.getValue(glyph + m.OFFSET_GLYPH_METRICS_VERT_BEARING_Y, 'i32')),
|
||||||
|
vertAdvance: from_26_6(m.getValue(glyph + m.OFFSET_GLYPH_METRICS_VERT_ADVANCE, 'i32'))
|
||||||
|
},
|
||||||
|
linearHoriAdvance: from_16_16(m.getValue(glyph + m.OFFSET_GLYPH_LINEAR_HORI_ADVANCE, 'i32')),
|
||||||
|
linearVertAdvance: from_16_16(m.getValue(glyph + m.OFFSET_GLYPH_LINEAR_VERT_ADVANCE, 'i32')),
|
||||||
|
advance: {
|
||||||
|
x: from_26_6(m.getValue(glyph + m.OFFSET_GLYPH_ADVANCE_X, 'i32')),
|
||||||
|
y: from_26_6(m.getValue(glyph + m.OFFSET_GLYPH_ADVANCE_Y, 'i32'))
|
||||||
|
},
|
||||||
|
bitmap: {
|
||||||
|
width: m.getValue(glyph + m.OFFSET_GLYPH_BITMAP_WIDTH, 'i32'),
|
||||||
|
rows: m.getValue(glyph + m.OFFSET_GLYPH_BITMAP_ROWS, 'i32'),
|
||||||
|
pitch: m.getValue(glyph + m.OFFSET_GLYPH_BITMAP_PITCH, 'i32'),
|
||||||
|
num_grays: m.getValue(glyph + m.OFFSET_GLYPH_BITMAP_NUM_GRAYS, 'i16'),
|
||||||
|
pixel_mode: m.getValue(glyph + m.OFFSET_GLYPH_BITMAP_PIXEL_MODE, 'i8'),
|
||||||
|
palette_mode: m.getValue(glyph + m.OFFSET_GLYPH_BITMAP_PALETTE_MODE, 'i8')
|
||||||
|
},
|
||||||
|
bitmap_left: m.getValue(glyph + m.OFFSET_GLYPH_BITMAP_LEFT, 'i32'),
|
||||||
|
bitmap_top: m.getValue(glyph + m.OFFSET_GLYPH_BITMAP_TOP, 'i32'),
|
||||||
|
lsb_delta: from_26_6(m.getValue(glyph + m.OFFSET_GLYPH_LSB_DELTA, 'i32')),
|
||||||
|
rsb_delta: from_26_6(m.getValue(glyph + m.OFFSET_GLYPH_RSB_DELTA, 'i32'))
|
||||||
|
}
|
||||||
|
|
||||||
|
let g_w = glyph_data.bitmap.width
|
||||||
|
let g_h = glyph_data.bitmap.rows
|
||||||
|
let g_x = glyph_data.bitmap_left
|
||||||
|
let g_y = glyph_data.bitmap_top
|
||||||
|
|
||||||
|
let buffer = m.getValue(glyph + m.OFFSET_GLYPH_BITMAP_BUFFER, 'i32')
|
||||||
|
let pitch = Math.abs(glyph_data.bitmap.pitch)
|
||||||
|
|
||||||
|
let advance_x = glyph_data.linearHoriAdvance
|
||||||
|
let advance_y = glyph_data.linearVertAdvance
|
||||||
|
|
||||||
|
let pixel_mode = glyph_data.bitmap.pixel_mode
|
||||||
|
|
||||||
|
let output = []
|
||||||
|
|
||||||
|
for (let y = 0; y < g_h; y++) {
|
||||||
|
let row_start = buffer + y * pitch
|
||||||
|
let line = []
|
||||||
|
|
||||||
|
for (let x = 0; x < g_w; x++) {
|
||||||
|
if (pixel_mode === m.FT_PIXEL_MODE_MONO) {
|
||||||
|
let value = m.getValue(row_start + ~~(x / 8), 'i8')
|
||||||
|
line.push(value & (1 << (7 - (x % 8))) ? 255 : 0)
|
||||||
|
} else if (pixel_mode === m.FT_PIXEL_MODE_BGRA) {
|
||||||
|
let blue = int8_to_uint8(m.getValue(row_start + (x * 4) + 0, 'i8'))
|
||||||
|
let green = int8_to_uint8(m.getValue(row_start + (x * 4) + 1, 'i8'))
|
||||||
|
let red = int8_to_uint8(m.getValue(row_start + (x * 4) + 2, 'i8'))
|
||||||
|
let alpha = int8_to_uint8(m.getValue(row_start + (x * 4) + 3, 'i8'))
|
||||||
|
// convert RGBA to grayscale
|
||||||
|
let grayscale = Math.round(0.299 * red + 0.587 * green + 0.114 * blue)
|
||||||
|
if (grayscale > 255) grayscale = 255
|
||||||
|
// meld grayscale into alpha channel
|
||||||
|
alpha = ((255 - grayscale) * alpha) / 255
|
||||||
|
line.push(alpha)
|
||||||
|
} else {
|
||||||
|
let value = m.getValue(row_start + x, 'i8')
|
||||||
|
line.push(int8_to_uint8(value))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
output.push(line)
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
x: g_x,
|
||||||
|
y: g_y,
|
||||||
|
width: g_w,
|
||||||
|
height: g_h,
|
||||||
|
advance_x,
|
||||||
|
advance_y,
|
||||||
|
pixels: output,
|
||||||
|
freetype: glyph_data
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function fontface_destroy(face) {
|
||||||
|
let error = FT_Done_Face(face.ptr)
|
||||||
|
|
||||||
|
if (error) throw new Error(`error in FT_Done_Face: ${error}`)
|
||||||
|
|
||||||
|
m._free(face.font)
|
||||||
|
face.ptr = 0
|
||||||
|
face.font = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
export function destroy() {
|
||||||
|
let error = m.ccall('FT_Done_FreeType', 'number', [ 'number' ], [ library ])
|
||||||
|
|
||||||
|
if (error) throw new Error(`error in FT_Done_FreeType: ${error}`)
|
||||||
|
|
||||||
|
library = 0
|
||||||
|
|
||||||
|
// don't unload wasm - slows down tests too much
|
||||||
|
//m = null
|
||||||
|
}
|
||||||
48
main/manager-web/src/utils/font_conv/Ranger.js
Normal file
48
main/manager-web/src/utils/font_conv/Ranger.js
Normal file
|
|
@ -0,0 +1,48 @@
|
||||||
|
// Merge ranges into single object
|
||||||
|
// ES6 版本
|
||||||
|
|
||||||
|
class Ranger {
|
||||||
|
constructor() {
|
||||||
|
this.data = {}
|
||||||
|
}
|
||||||
|
|
||||||
|
// input:
|
||||||
|
// -r 0x1F450 - single value, dec or hex format
|
||||||
|
// -r 0x1F450-0x1F470 - range
|
||||||
|
// -r 0x1F450=>0xF005 - single glyph with mapping
|
||||||
|
// -r 0x1F450-0x1F470=>0xF005 - range with mapping
|
||||||
|
add_range(font, start, end, mapped_start) {
|
||||||
|
let offset = mapped_start - start
|
||||||
|
let output = []
|
||||||
|
|
||||||
|
for (let i = start; i <= end; i++) {
|
||||||
|
this._set_char(font, i, i + offset)
|
||||||
|
output.push(i)
|
||||||
|
}
|
||||||
|
|
||||||
|
return output
|
||||||
|
}
|
||||||
|
|
||||||
|
// input: characters to copy, e.g. '1234567890abcdef'
|
||||||
|
add_symbols(font, str) {
|
||||||
|
let output = []
|
||||||
|
|
||||||
|
for (let chr of str) {
|
||||||
|
let code = chr.codePointAt(0)
|
||||||
|
this._set_char(font, code, code)
|
||||||
|
output.push(code)
|
||||||
|
}
|
||||||
|
|
||||||
|
return output
|
||||||
|
}
|
||||||
|
|
||||||
|
_set_char(font, code, mapped_to) {
|
||||||
|
this.data[mapped_to] = { font, code }
|
||||||
|
}
|
||||||
|
|
||||||
|
get() {
|
||||||
|
return this.data
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default Ranger
|
||||||
152
main/manager-web/src/utils/font_conv/Utils.js
Normal file
152
main/manager-web/src/utils/font_conv/Utils.js
Normal file
|
|
@ -0,0 +1,152 @@
|
||||||
|
// Font processing utilities
|
||||||
|
// ES6 版本,适配浏览器环境
|
||||||
|
|
||||||
|
function set_byte_depth(depth) {
|
||||||
|
return function (byte) {
|
||||||
|
// calculate significant bits, e.g. for depth=2 it's 0, 1, 2 or 3
|
||||||
|
let value = ~~(byte / (256 >> depth))
|
||||||
|
|
||||||
|
// spread those bits around 0..255 range, e.g. for depth=2 it's 0, 85, 170 or 255
|
||||||
|
let scale = (2 << (depth - 1)) - 1
|
||||||
|
|
||||||
|
return (value * 0xFFFF / scale) >> 8
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function set_depth(glyph, depth) {
|
||||||
|
let pixels = []
|
||||||
|
let fn = set_byte_depth(depth)
|
||||||
|
|
||||||
|
for (let y = 0; y < glyph.bbox.height; y++) {
|
||||||
|
pixels.push(glyph.pixels[y].map(fn))
|
||||||
|
}
|
||||||
|
|
||||||
|
return Object.assign({}, glyph, { pixels })
|
||||||
|
}
|
||||||
|
|
||||||
|
function count_bits(val) {
|
||||||
|
let count = 0
|
||||||
|
val = ~~val
|
||||||
|
|
||||||
|
while (val) {
|
||||||
|
count++
|
||||||
|
val >>= 1
|
||||||
|
}
|
||||||
|
|
||||||
|
return count
|
||||||
|
}
|
||||||
|
|
||||||
|
// Minimal number of bits to store unsigned value
|
||||||
|
export const unsigned_bits = count_bits
|
||||||
|
|
||||||
|
// Minimal number of bits to store signed value
|
||||||
|
export function signed_bits(val) {
|
||||||
|
if (val >= 0) return count_bits(val) + 1
|
||||||
|
|
||||||
|
return count_bits(Math.abs(val) - 1) + 1
|
||||||
|
}
|
||||||
|
|
||||||
|
// Align value to 4x - useful to create word-aligned arrays
|
||||||
|
function align4(size) {
|
||||||
|
if (size % 4 === 0) return size
|
||||||
|
return size + 4 - (size % 4)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { align4 }
|
||||||
|
|
||||||
|
// Align buffer length to 4x (returns copy with zero-filled tail)
|
||||||
|
export function balign4(buf) {
|
||||||
|
const alignedLength = align4(buf.length)
|
||||||
|
const alignedBuf = new Uint8Array(alignedLength)
|
||||||
|
alignedBuf.set(new Uint8Array(buf))
|
||||||
|
return alignedBuf.buffer
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pre-filter image to improve compression ratio
|
||||||
|
// In this case - XOR lines, because it's very effective
|
||||||
|
// in decompressor and does not depend on bpp.
|
||||||
|
export function prefilter(pixels) {
|
||||||
|
return pixels.map((line, l_idx, arr) => {
|
||||||
|
if (l_idx === 0) return line.slice()
|
||||||
|
|
||||||
|
return line.map((p, idx) => p ^ arr[l_idx - 1][idx])
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert array with uint16 data to buffer
|
||||||
|
export function bFromA16(arr) {
|
||||||
|
const buf = new ArrayBuffer(arr.length * 2)
|
||||||
|
const view = new DataView(buf)
|
||||||
|
|
||||||
|
for (let i = 0; i < arr.length; i++) {
|
||||||
|
view.setUint16(i * 2, arr[i], true) // little endian
|
||||||
|
}
|
||||||
|
|
||||||
|
return buf
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert array with uint32 data to buffer
|
||||||
|
export function bFromA32(arr) {
|
||||||
|
const buf = new ArrayBuffer(arr.length * 4)
|
||||||
|
const view = new DataView(buf)
|
||||||
|
|
||||||
|
for (let i = 0; i < arr.length; i++) {
|
||||||
|
view.setUint32(i * 4, arr[i], true) // little endian
|
||||||
|
}
|
||||||
|
|
||||||
|
return buf
|
||||||
|
}
|
||||||
|
|
||||||
|
function chunk(arr, size) {
|
||||||
|
const result = []
|
||||||
|
for (let i = 0; i < arr.length; i += size) {
|
||||||
|
result.push(arr.slice(i, i + size))
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dump long array to multiline format with X columns and Y indent
|
||||||
|
export function long_dump(arr, options = {}) {
|
||||||
|
const defaults = {
|
||||||
|
col: 8,
|
||||||
|
indent: 4,
|
||||||
|
hex: false
|
||||||
|
}
|
||||||
|
|
||||||
|
let opts = Object.assign({}, defaults, options)
|
||||||
|
let indent = ' '.repeat(opts.indent)
|
||||||
|
|
||||||
|
return chunk(Array.from(arr), opts.col)
|
||||||
|
.map(l => l.map(v => (opts.hex ? `0x${v.toString(16)}` : v.toString())))
|
||||||
|
.map(l => `${indent}${l.join(', ')}`)
|
||||||
|
.join(',\n')
|
||||||
|
}
|
||||||
|
|
||||||
|
// stable sort by pick() result
|
||||||
|
export function sort_by(arr, pick) {
|
||||||
|
return arr
|
||||||
|
.map((el, idx) => ({ el, idx }))
|
||||||
|
.sort((a, b) => (pick(a.el) - pick(b.el)) || (a.idx - b.idx))
|
||||||
|
.map(({ el }) => el)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sum(arr) {
|
||||||
|
return arr.reduce((a, v) => a + v, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 默认导出所有函数
|
||||||
|
const utils = {
|
||||||
|
set_depth,
|
||||||
|
unsigned_bits,
|
||||||
|
signed_bits,
|
||||||
|
align4,
|
||||||
|
balign4,
|
||||||
|
prefilter,
|
||||||
|
bFromA16,
|
||||||
|
bFromA32,
|
||||||
|
long_dump,
|
||||||
|
sort_by,
|
||||||
|
sum
|
||||||
|
}
|
||||||
|
|
||||||
|
export default utils
|
||||||
105
main/manager-web/src/utils/font_conv/cmap_build_subtables.js
Normal file
105
main/manager-web/src/utils/font_conv/cmap_build_subtables.js
Normal file
|
|
@ -0,0 +1,105 @@
|
||||||
|
// Find an optimal configuration of cmap tables representing set of codepoints,
|
||||||
|
// using simple breadth-first algorithm
|
||||||
|
//
|
||||||
|
// Assume that:
|
||||||
|
// - codepoints have one-to-one correspondence to glyph ids
|
||||||
|
// - glyph ids are always bigger for bigger codepoints
|
||||||
|
// - glyph ids are always consecutive (1..N without gaps)
|
||||||
|
//
|
||||||
|
// This way we can omit glyph ids from all calculations entirely: if codepoints
|
||||||
|
// fit in format0, then glyph ids also will.
|
||||||
|
//
|
||||||
|
// format6 is not considered, because if glyph ids can be delta-coded,
|
||||||
|
// multiple format0 tables are guaranteed to be smaller than a single format6.
|
||||||
|
//
|
||||||
|
// sparse format is not used because as long as glyph ids are consecutive,
|
||||||
|
// sparse_tiny will always be preferred.
|
||||||
|
//
|
||||||
|
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
|
||||||
|
function estimate_format0_tiny_size(/*start_code, end_code*/) {
|
||||||
|
return 16;
|
||||||
|
}
|
||||||
|
|
||||||
|
function estimate_format0_size(start_code, end_code) {
|
||||||
|
return 16 + (end_code - start_code + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
//function estimate_sparse_size(count) {
|
||||||
|
// return 16 + count * 4;
|
||||||
|
//}
|
||||||
|
|
||||||
|
function estimate_sparse_tiny_size(count) {
|
||||||
|
return 16 + count * 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function cmap_split(all_codepoints) {
|
||||||
|
all_codepoints = all_codepoints.sort((a, b) => a - b);
|
||||||
|
|
||||||
|
let min_paths = [];
|
||||||
|
|
||||||
|
for (let i = 0; i < all_codepoints.length; i++) {
|
||||||
|
let min = { dist: Infinity };
|
||||||
|
|
||||||
|
for (let j = 0; j <= i; j++) {
|
||||||
|
let prev_dist = (j - 1 >= 0) ? min_paths[j - 1].dist : 0;
|
||||||
|
let s;
|
||||||
|
|
||||||
|
if (all_codepoints[i] - all_codepoints[j] < 256) {
|
||||||
|
s = estimate_format0_size(all_codepoints[j], all_codepoints[i]);
|
||||||
|
|
||||||
|
/* eslint-disable max-depth */
|
||||||
|
if (prev_dist + s < min.dist) {
|
||||||
|
min = {
|
||||||
|
dist: prev_dist + s,
|
||||||
|
start: j,
|
||||||
|
end: i,
|
||||||
|
format: 'format0'
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (all_codepoints[i] - all_codepoints[j] < 256 && all_codepoints[i] - i === all_codepoints[j] - j) {
|
||||||
|
s = estimate_format0_tiny_size(all_codepoints[j], all_codepoints[i]);
|
||||||
|
|
||||||
|
/* eslint-disable max-depth */
|
||||||
|
if (prev_dist + s < min.dist) {
|
||||||
|
min = {
|
||||||
|
dist: prev_dist + s,
|
||||||
|
start: j,
|
||||||
|
end: i,
|
||||||
|
format: 'format0_tiny'
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// tiny sparse will always be preferred over full sparse because glyph ids are consecutive
|
||||||
|
if (all_codepoints[i] - all_codepoints[j] < 65536) {
|
||||||
|
s = estimate_sparse_tiny_size(i - j + 1);
|
||||||
|
|
||||||
|
if (prev_dist + s < min.dist) {
|
||||||
|
min = {
|
||||||
|
dist: prev_dist + s,
|
||||||
|
start: j,
|
||||||
|
end: i,
|
||||||
|
format: 'sparse_tiny'
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
min_paths[i] = min;
|
||||||
|
}
|
||||||
|
|
||||||
|
let result = [];
|
||||||
|
|
||||||
|
for (let i = all_codepoints.length - 1; i >= 0;) {
|
||||||
|
let path = min_paths[i];
|
||||||
|
result.unshift([ path.format, all_codepoints.slice(path.start, path.end + 1) ]);
|
||||||
|
i = path.start - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
File diff suppressed because one or more lines are too long
532
main/manager-web/src/utils/font_conv/writers/CBinFont.js
Normal file
532
main/manager-web/src/utils/font_conv/writers/CBinFont.js
Normal file
|
|
@ -0,0 +1,532 @@
|
||||||
|
// CBIN Font writer - 严格按照官方实现(浏览器兼容版)
|
||||||
|
// 遵循 font_conv_lib/writers/cbin/ 的格式
|
||||||
|
|
||||||
|
import AppError from '../AppError.js';
|
||||||
|
import cmap_build_subtables from '../cmap_build_subtables.js';
|
||||||
|
|
||||||
|
// 32位指针大小,保持与官方一致
|
||||||
|
const ptr_size = 4;
|
||||||
|
|
||||||
|
// 浏览器版本的 writeUInt64LE 实现
|
||||||
|
const writeUInt64LE = (view, val, pos) => {
|
||||||
|
view.setUint32(pos, val, true);
|
||||||
|
view.setUint32(pos + 4, 0, true);
|
||||||
|
};
|
||||||
|
|
||||||
|
class CBinFont {
|
||||||
|
constructor(fontData, options) {
|
||||||
|
this.src = fontData;
|
||||||
|
this.opts = options;
|
||||||
|
|
||||||
|
this.font_name = options.lv_font_name;
|
||||||
|
if (!this.font_name) {
|
||||||
|
this.font_name = options.output || 'font';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.bpp === 3 && options.no_compress) {
|
||||||
|
throw new AppError('LVGL supports "--bpp 3" with compression only');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 初始化各个表格处理器
|
||||||
|
this.init_tables();
|
||||||
|
}
|
||||||
|
|
||||||
|
init_tables() {
|
||||||
|
this.head = new HeadTable(this);
|
||||||
|
this.glyf = new GlyfTable(this);
|
||||||
|
this.cmap = new CmapTable(this);
|
||||||
|
this.kern = new KernTable(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
toCBin() {
|
||||||
|
// 严格按照 lv_font.js 的实现(浏览器兼容版)
|
||||||
|
const [bitmap_buf, glyph_dsc_buf] = this.glyf.toCBin();
|
||||||
|
const cmaps_buf = this.cmap.toCBin(ptr_size);
|
||||||
|
const kern_buf = this.kern.toCBin(ptr_size);
|
||||||
|
|
||||||
|
const sz_font = 12 + ptr_size * 6 + (ptr_size == 4 ? 0 : 4); // add pad, see below
|
||||||
|
const sz_font_dsc = 8 + ptr_size * 4; // add space for stride
|
||||||
|
const head_buf = new ArrayBuffer(sz_font + sz_font_dsc);
|
||||||
|
const head_view = new DataView(head_buf);
|
||||||
|
|
||||||
|
const writePTR = ptr_size == 4 ?
|
||||||
|
(val, pos) => head_view.setUint32(pos, val, true) :
|
||||||
|
(val, pos) => writeUInt64LE(head_view, val, pos);
|
||||||
|
|
||||||
|
var pos = 0;
|
||||||
|
// write lv_font_t
|
||||||
|
writePTR(0, pos); pos += ptr_size;
|
||||||
|
writePTR(0, pos); pos += ptr_size;
|
||||||
|
writePTR(0, pos); pos += ptr_size;
|
||||||
|
head_view.setUint32(pos, this.src.ascent - this.src.descent, true); pos += 4; // line_height
|
||||||
|
head_view.setInt32(pos, -this.src.descent, true); pos += 4; // base_line
|
||||||
|
|
||||||
|
head_view.setUint8(pos, this.src.subpixels_mode || 0); pos += 1;
|
||||||
|
head_view.setInt8(pos, this.src.underlinePosition || 0); pos += 1;
|
||||||
|
head_view.setInt8(pos, this.src.underlineThickness || 0); pos += 1;
|
||||||
|
pos += 1 + (ptr_size == 4 ? 0 : 4); // pad
|
||||||
|
|
||||||
|
writePTR(sz_font, pos); pos += ptr_size; // offset relative to start of lv_font_t
|
||||||
|
writePTR(0, pos); pos += ptr_size;
|
||||||
|
writePTR(0, pos); pos += ptr_size;
|
||||||
|
|
||||||
|
const kern = this.head.kern_ref();
|
||||||
|
// write lv_font_fmt_txt_dsc_t
|
||||||
|
writePTR(sz_font_dsc + kern_buf.byteLength, pos); pos += ptr_size; // glyph_bitmap offset relative to start of lv_font_fmt_txt_dsc_t
|
||||||
|
writePTR(sz_font_dsc + kern_buf.byteLength + bitmap_buf.byteLength, pos); pos += ptr_size; // glyph_dsc ofs
|
||||||
|
writePTR(sz_font_dsc + kern_buf.byteLength + bitmap_buf.byteLength + glyph_dsc_buf.byteLength, pos); pos += ptr_size; // cmaps ofs
|
||||||
|
writePTR(kern.dsc === 'NULL' ? 0 : sz_font_dsc, pos); pos += ptr_size; // kern ofs
|
||||||
|
head_view.setUint16(pos, kern.scale, true); pos += 2;
|
||||||
|
|
||||||
|
const cmap_num = this.cmap.getMapNumber();
|
||||||
|
const bpp = this.opts.bpp;
|
||||||
|
const kern_classes = kern.classes;
|
||||||
|
const bitmap_format = this.glyf.getCompressionCode();
|
||||||
|
head_view.setUint16(pos, cmap_num | (bpp << 9) | (kern_classes << (9 + 4)) | (bitmap_format << (9 + 4 + 1)), true); pos += 2;
|
||||||
|
|
||||||
|
return this.concatArrayBuffers([
|
||||||
|
head_buf,
|
||||||
|
kern_buf,
|
||||||
|
bitmap_buf,
|
||||||
|
glyph_dsc_buf,
|
||||||
|
cmaps_buf
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
concatArrayBuffers(buffers) {
|
||||||
|
// 浏览器兼容的 ArrayBuffer 合并方法
|
||||||
|
const totalLength = buffers.reduce((sum, buf) => sum + buf.byteLength, 0);
|
||||||
|
const result = new ArrayBuffer(totalLength);
|
||||||
|
const view = new Uint8Array(result);
|
||||||
|
|
||||||
|
let offset = 0;
|
||||||
|
for (const buf of buffers) {
|
||||||
|
view.set(new Uint8Array(buf), offset);
|
||||||
|
offset += buf.byteLength;
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 各个表格处理类的实现
|
||||||
|
|
||||||
|
// Head 表格处理器
|
||||||
|
class HeadTable {
|
||||||
|
constructor(font) {
|
||||||
|
this.font = font;
|
||||||
|
}
|
||||||
|
|
||||||
|
kern_ref() {
|
||||||
|
const f = this.font;
|
||||||
|
|
||||||
|
// 简化版:不支持 kerning
|
||||||
|
return {
|
||||||
|
scale: 0,
|
||||||
|
dsc: 'NULL',
|
||||||
|
classes: 0
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 浏览器兼容的简化 BitStream 实现
|
||||||
|
class SimpleBitStream {
|
||||||
|
constructor(buffer) {
|
||||||
|
this.buffer = new Uint8Array(buffer);
|
||||||
|
this.byteIndex = 0;
|
||||||
|
this.bitIndex = 0;
|
||||||
|
this.bigEndian = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
writeBits(value, bits) {
|
||||||
|
while (bits > 0) {
|
||||||
|
const bitsToWrite = Math.min(8 - this.bitIndex, bits);
|
||||||
|
const mask = (1 << bitsToWrite) - 1;
|
||||||
|
const bitValue = (value >> (bits - bitsToWrite)) & mask;
|
||||||
|
|
||||||
|
if (this.bigEndian) {
|
||||||
|
this.buffer[this.byteIndex] |= (bitValue << (8 - this.bitIndex - bitsToWrite));
|
||||||
|
} else {
|
||||||
|
this.buffer[this.byteIndex] |= (bitValue << this.bitIndex);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.bitIndex += bitsToWrite;
|
||||||
|
if (this.bitIndex >= 8) {
|
||||||
|
this.byteIndex++;
|
||||||
|
this.bitIndex = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
bits -= bitsToWrite;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
getUsedBytes() {
|
||||||
|
return this.bitIndex > 0 ? this.byteIndex + 1 : this.byteIndex;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Glyf 表格处理器 - 严格按照官方 lv_table_glyf.js 实现
|
||||||
|
class GlyfTable {
|
||||||
|
constructor(font) {
|
||||||
|
this.font = font;
|
||||||
|
this.lv_data = [];
|
||||||
|
this.lv_compiled = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 严格按照官方 table_glyf.js 的 pixelsToBpp 实现
|
||||||
|
pixelsToBpp(pixels) {
|
||||||
|
const bpp = this.font.opts.bpp;
|
||||||
|
return pixels.map(line => line.map(p => (p >>> (8 - bpp))));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 严格按照官方的 storePixels 实现
|
||||||
|
storePixels(bitStream, pixels) {
|
||||||
|
if (this.getCompressionCode() === 0) this.storePixelsRaw(bitStream, pixels);
|
||||||
|
else this.storePixelsCompressed(bitStream, pixels);
|
||||||
|
}
|
||||||
|
|
||||||
|
storePixelsRaw(bitStream, pixels) {
|
||||||
|
const bpp = this.font.opts.bpp;
|
||||||
|
|
||||||
|
for (let y = 0; y < pixels.length; y++) {
|
||||||
|
const line = pixels[y];
|
||||||
|
for (let x = 0; x < line.length; x++) {
|
||||||
|
bitStream.writeBits(line[x], bpp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
storePixelsCompressed(bitStream, pixels) {
|
||||||
|
// 简化版:暂不支持压缩,直接调用 raw 版本
|
||||||
|
this.storePixelsRaw(bitStream, pixels);
|
||||||
|
}
|
||||||
|
|
||||||
|
lv_bitmap(glyph) {
|
||||||
|
// 严格按照官方实现
|
||||||
|
const bufSize = 100 + glyph.bbox.width * glyph.bbox.height * 4;
|
||||||
|
const buf = new ArrayBuffer(bufSize);
|
||||||
|
const bs = new SimpleBitStream(buf);
|
||||||
|
bs.bigEndian = true;
|
||||||
|
|
||||||
|
const pixels = this.pixelsToBpp(glyph.pixels);
|
||||||
|
this.storePixels(bs, pixels);
|
||||||
|
|
||||||
|
// 创建实际使用的 buffer
|
||||||
|
const glyph_bitmap = new ArrayBuffer(bs.getUsedBytes());
|
||||||
|
const srcView = new Uint8Array(buf);
|
||||||
|
const destView = new Uint8Array(glyph_bitmap);
|
||||||
|
destView.set(srcView.subarray(0, bs.getUsedBytes()));
|
||||||
|
|
||||||
|
return glyph_bitmap;
|
||||||
|
}
|
||||||
|
|
||||||
|
lv_compile() {
|
||||||
|
if (this.lv_compiled) return;
|
||||||
|
|
||||||
|
this.lv_compiled = true;
|
||||||
|
|
||||||
|
const f = this.font;
|
||||||
|
this.lv_data = [];
|
||||||
|
let offset = 0;
|
||||||
|
|
||||||
|
// 严格按照官方逻辑:使用 f.glyph_id[g.code] 作为索引
|
||||||
|
f.src.glyphs.forEach(g => {
|
||||||
|
const id = f.glyph_id[g.code];
|
||||||
|
const bin = this.lv_bitmap(g);
|
||||||
|
this.lv_data[id] = {
|
||||||
|
bin,
|
||||||
|
offset,
|
||||||
|
glyph: g
|
||||||
|
};
|
||||||
|
offset += bin.byteLength;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
toCBin() {
|
||||||
|
// LV_FONT_FMT_TXT_LARGE == 1
|
||||||
|
this.lv_compile();
|
||||||
|
|
||||||
|
// 严格按照官方实现:slice(1) 跳过索引0,然后过滤有效数据
|
||||||
|
const validBins = this.lv_data.slice(1).filter(d => d).map(d => d.bin);
|
||||||
|
const bitmap_buf = this.balign4(this.concatArrayBuffers(validBins));
|
||||||
|
const glyph_dsc_buf = new ArrayBuffer(this.lv_data.length * 16 + 16);
|
||||||
|
const glyph_dsc_view = new DataView(glyph_dsc_buf);
|
||||||
|
|
||||||
|
let i = 1;
|
||||||
|
this.lv_data.forEach(d => {
|
||||||
|
if (d) {
|
||||||
|
const adv_w = Math.round(d.glyph.advanceWidth * 16);
|
||||||
|
glyph_dsc_view.setUint32(i * 16, d.offset, true);
|
||||||
|
glyph_dsc_view.setUint32(i * 16 + 4, adv_w, true);
|
||||||
|
glyph_dsc_view.setUint16(i * 16 + 8, d.glyph.bbox.width, true);
|
||||||
|
glyph_dsc_view.setUint16(i * 16 + 10, d.glyph.bbox.height, true);
|
||||||
|
glyph_dsc_view.setInt16(i * 16 + 12, d.glyph.bbox.x, true);
|
||||||
|
glyph_dsc_view.setInt16(i * 16 + 14, d.glyph.bbox.y, true);
|
||||||
|
}
|
||||||
|
i++;
|
||||||
|
});
|
||||||
|
|
||||||
|
return [bitmap_buf, glyph_dsc_buf];
|
||||||
|
}
|
||||||
|
|
||||||
|
balign4(buf) {
|
||||||
|
const remainder = buf.byteLength % 4;
|
||||||
|
if (remainder === 0) return buf;
|
||||||
|
const padding = 4 - remainder;
|
||||||
|
const paddingBuf = new ArrayBuffer(padding);
|
||||||
|
return this.concatArrayBuffers([buf, paddingBuf]);
|
||||||
|
}
|
||||||
|
|
||||||
|
concatArrayBuffers(buffers) {
|
||||||
|
const totalLength = buffers.reduce((sum, buf) => sum + buf.byteLength, 0);
|
||||||
|
const result = new ArrayBuffer(totalLength);
|
||||||
|
const view = new Uint8Array(result);
|
||||||
|
|
||||||
|
let offset = 0;
|
||||||
|
for (const buf of buffers) {
|
||||||
|
view.set(new Uint8Array(buf), offset);
|
||||||
|
offset += buf.byteLength;
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
getCompressionCode() {
|
||||||
|
if (this.font.opts.no_compress) return 0;
|
||||||
|
if (this.font.opts.bpp === 1) return 0;
|
||||||
|
|
||||||
|
if (this.font.opts.no_prefilter) return 2;
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cmap 表格处理器 - 严格按照官方 lv_table_cmap.js 实现
|
||||||
|
class CmapTable {
|
||||||
|
constructor(font) {
|
||||||
|
this.font = font;
|
||||||
|
this.lv_compiled = false;
|
||||||
|
this.lv_subtables = [];
|
||||||
|
this.subtables_plan = null;
|
||||||
|
|
||||||
|
// 建立字形ID映射,按照官方逻辑
|
||||||
|
this.buildGlyphIdMap();
|
||||||
|
}
|
||||||
|
|
||||||
|
buildGlyphIdMap() {
|
||||||
|
const f = this.font;
|
||||||
|
f.glyph_id = {};
|
||||||
|
|
||||||
|
if (f.src.glyphs) {
|
||||||
|
f.src.glyphs.forEach((glyph, index) => {
|
||||||
|
f.glyph_id[glyph.code] = index + 1; // 字形ID从1开始
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
lv_format2enum(name) {
|
||||||
|
switch (name) {
|
||||||
|
case 'format0_tiny': return 'LV_FONT_FMT_TXT_CMAP_FORMAT0_TINY';
|
||||||
|
case 'format0': return 'LV_FONT_FMT_TXT_CMAP_FORMAT0_FULL';
|
||||||
|
case 'sparse_tiny': return 'LV_FONT_FMT_TXT_CMAP_SPARSE_TINY';
|
||||||
|
case 'sparse': return 'LV_FONT_FMT_TXT_CMAP_SPARSE_FULL';
|
||||||
|
default: throw new Error('Unknown subtable format');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
lv_format2int(name) {
|
||||||
|
return ['format0','sparse','format0_tiny','sparse_tiny'].indexOf(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
getMapNumber() {
|
||||||
|
// 返回子表数量,需要先确保已经生成了子表计划
|
||||||
|
if (!this.subtables_plan) {
|
||||||
|
const f = this.font;
|
||||||
|
if (!f.src.glyphs || f.src.glyphs.length === 0) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
this.subtables_plan = cmap_build_subtables(f.src.glyphs.map(g => g.code));
|
||||||
|
}
|
||||||
|
return this.subtables_plan.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
glyphByCode(code) {
|
||||||
|
const f = this.font;
|
||||||
|
return f.src.glyphs ? f.src.glyphs.find(g => g.code === code) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
collect_format0_data(min_code, max_code, start_glyph_id) {
|
||||||
|
const f = this.font;
|
||||||
|
const data = [];
|
||||||
|
|
||||||
|
for (let code = min_code; code <= max_code; code++) {
|
||||||
|
const glyph_id = f.glyph_id[code] || 0;
|
||||||
|
// format0的数据格式是相对于start_glyph_id的偏移
|
||||||
|
data.push(glyph_id ? glyph_id - start_glyph_id : 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
collect_sparse_data(codepoints, start_glyph_id) {
|
||||||
|
const f = this.font;
|
||||||
|
let codepoints_list = [];
|
||||||
|
let ids_list = [];
|
||||||
|
|
||||||
|
for (let code of codepoints) {
|
||||||
|
let g = this.glyphByCode(code);
|
||||||
|
let id = f.glyph_id[g.code];
|
||||||
|
|
||||||
|
let code_delta = code - codepoints[0]; // 关键:相对于第一个代码点的偏移
|
||||||
|
let id_delta = id - start_glyph_id;
|
||||||
|
|
||||||
|
if (code_delta < 0 || code_delta > 65535) throw new Error('Codepoint delta out of range');
|
||||||
|
if (id_delta < 0 || id_delta > 65535) throw new Error('Glyph ID delta out of range');
|
||||||
|
|
||||||
|
codepoints_list.push(code_delta); // 推入 delta,不是原始 code
|
||||||
|
ids_list.push(id_delta);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
codes: codepoints_list,
|
||||||
|
ids: ids_list
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
toCBin(ptr_size) {
|
||||||
|
const f = this.font;
|
||||||
|
|
||||||
|
if (!f.src.glyphs || f.src.glyphs.length === 0) {
|
||||||
|
return new ArrayBuffer(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 确保只计算一次 subtables_plan
|
||||||
|
if (!this.subtables_plan) {
|
||||||
|
this.subtables_plan = cmap_build_subtables(f.src.glyphs.map(g => g.code));
|
||||||
|
}
|
||||||
|
const subtables_plan = this.subtables_plan;
|
||||||
|
let idx = 0;
|
||||||
|
|
||||||
|
const cmap_size = 12 + ptr_size * 2 + (ptr_size == 4 ? 0 : 4);
|
||||||
|
const cmaps_buf = new ArrayBuffer(subtables_plan.length * cmap_size);
|
||||||
|
const cmaps_view = new DataView(cmaps_buf);
|
||||||
|
|
||||||
|
const writePTR = ptr_size == 4 ?
|
||||||
|
(val, ofs) => cmaps_view.setUint32(ofs, val, true) :
|
||||||
|
(val, ofs) => writeUInt64LE(cmaps_view, val, ofs);
|
||||||
|
|
||||||
|
const arr_list = [];
|
||||||
|
let total_data_offset = cmaps_buf.byteLength;
|
||||||
|
|
||||||
|
for (let [format, codepoints] of subtables_plan) {
|
||||||
|
let g = this.glyphByCode(codepoints[0]);
|
||||||
|
let start_glyph_id = f.glyph_id[g.code];
|
||||||
|
let min_code = codepoints[0];
|
||||||
|
let max_code = codepoints[codepoints.length - 1];
|
||||||
|
|
||||||
|
let has_charcodes = false;
|
||||||
|
let has_ids = false;
|
||||||
|
let entries_count = 0;
|
||||||
|
|
||||||
|
let glyph_ptr = new ArrayBuffer(0);
|
||||||
|
let unicode_ptr = new ArrayBuffer(0);
|
||||||
|
|
||||||
|
if (format === 'format0_tiny') {
|
||||||
|
// use default empty values
|
||||||
|
} else if (format === 'format0') {
|
||||||
|
has_ids = true;
|
||||||
|
let d = this.collect_format0_data(min_code, max_code, start_glyph_id);
|
||||||
|
entries_count = d.length;
|
||||||
|
// 严格按照官方:Buffer.from(d)
|
||||||
|
glyph_ptr = this.balign4(this.uint8ArrayToBuffer(new Uint8Array(d)));
|
||||||
|
} else if (format === 'sparse_tiny') {
|
||||||
|
has_charcodes = true;
|
||||||
|
let d = this.collect_sparse_data(codepoints, start_glyph_id);
|
||||||
|
entries_count = d.codes.length;
|
||||||
|
unicode_ptr = this.balign4(this.uint16ArrayToBuffer(new Uint16Array(d.codes)));
|
||||||
|
} else { // assume format === 'sparse'
|
||||||
|
has_charcodes = true;
|
||||||
|
has_ids = true;
|
||||||
|
let d = this.collect_sparse_data(codepoints, start_glyph_id);
|
||||||
|
entries_count = d.codes.length;
|
||||||
|
unicode_ptr = this.balign4(this.uint16ArrayToBuffer(new Uint16Array(d.codes)));
|
||||||
|
glyph_ptr = this.align4(this.uint16ArrayToBuffer(new Uint16Array(d.ids)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 写入 cmap 头部 - 严格按照官方逻辑
|
||||||
|
let ofs = idx * cmap_size;
|
||||||
|
cmaps_view.setUint32(ofs, min_code, true); ofs += 4;
|
||||||
|
cmaps_view.setUint16(ofs, max_code - min_code + 1, true); ofs += 2;
|
||||||
|
cmaps_view.setUint16(ofs, start_glyph_id, true); ofs += 2;
|
||||||
|
// 关键:写入指针的同时立即更新 total_data_offset
|
||||||
|
writePTR(has_charcodes ? total_data_offset : 0, ofs); ofs += ptr_size;
|
||||||
|
total_data_offset += unicode_ptr.byteLength;
|
||||||
|
writePTR(has_ids ? total_data_offset : 0, ofs); ofs += ptr_size;
|
||||||
|
total_data_offset += glyph_ptr.byteLength;
|
||||||
|
cmaps_view.setUint16(ofs, entries_count, true); ofs += 2;
|
||||||
|
cmaps_view.setUint8(ofs, this.lv_format2int(format)); ofs += 1;
|
||||||
|
|
||||||
|
arr_list.push(unicode_ptr);
|
||||||
|
arr_list.push(glyph_ptr);
|
||||||
|
|
||||||
|
idx++;
|
||||||
|
}
|
||||||
|
return this.concatArrayBuffers([cmaps_buf, ...arr_list]);
|
||||||
|
}
|
||||||
|
|
||||||
|
balign4(buf) {
|
||||||
|
const remainder = buf.byteLength % 4;
|
||||||
|
if (remainder === 0) return buf;
|
||||||
|
const padding = 4 - remainder;
|
||||||
|
const paddingBuf = new ArrayBuffer(padding);
|
||||||
|
return this.concatArrayBuffers([buf, paddingBuf]);
|
||||||
|
}
|
||||||
|
|
||||||
|
align4(buf) {
|
||||||
|
const remainder = buf.byteLength % 4;
|
||||||
|
if (remainder === 0) return buf;
|
||||||
|
const padding = 4 - remainder;
|
||||||
|
const paddingBuf = new ArrayBuffer(padding);
|
||||||
|
return this.concatArrayBuffers([buf, paddingBuf]);
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8ArrayToBuffer(uint8Array) {
|
||||||
|
const buffer = new ArrayBuffer(uint8Array.byteLength);
|
||||||
|
const view = new Uint8Array(buffer);
|
||||||
|
view.set(uint8Array);
|
||||||
|
return buffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint16ArrayToBuffer(uint16Array) {
|
||||||
|
// 严格按照官方的处理方式:直接使用 Uint16Array 的 buffer
|
||||||
|
// 这等价于官方的 Buffer.from(Uint16Array.from(d.codes).buffer)
|
||||||
|
return uint16Array.buffer.slice(0, uint16Array.byteLength);
|
||||||
|
}
|
||||||
|
|
||||||
|
concatArrayBuffers(buffers) {
|
||||||
|
const totalLength = buffers.reduce((sum, buf) => sum + buf.byteLength, 0);
|
||||||
|
const result = new ArrayBuffer(totalLength);
|
||||||
|
const view = new Uint8Array(result);
|
||||||
|
|
||||||
|
let offset = 0;
|
||||||
|
for (const buf of buffers) {
|
||||||
|
view.set(new Uint8Array(buf), offset);
|
||||||
|
offset += buf.byteLength;
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Kern 表格处理器(简化版,不支持 kerning)
|
||||||
|
class KernTable {
|
||||||
|
constructor(font) {
|
||||||
|
this.font = font;
|
||||||
|
}
|
||||||
|
|
||||||
|
toCBin(ptr_size) {
|
||||||
|
// 简化版:不支持 kerning,返回空 buffer
|
||||||
|
return new ArrayBuffer(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default CBinFont;
|
||||||
16
main/manager-web/src/utils/font_conv/writers/CBinWriter.js
Normal file
16
main/manager-web/src/utils/font_conv/writers/CBinWriter.js
Normal file
|
|
@ -0,0 +1,16 @@
|
||||||
|
// CBIN format writer - ES6 version
|
||||||
|
// 将字体数据写成 CBIN 格式
|
||||||
|
|
||||||
|
import AppError from '../AppError.js'
|
||||||
|
import CBinFont from './CBinFont.js'
|
||||||
|
|
||||||
|
export default function write_cbin(args, fontData) {
|
||||||
|
if (!args.output) throw new AppError('Output is required for "cbin" writer')
|
||||||
|
|
||||||
|
const font = new CBinFont(fontData, args)
|
||||||
|
const result = font.toCBin()
|
||||||
|
|
||||||
|
return {
|
||||||
|
[args.output]: result
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -126,6 +126,15 @@
|
||||||
<CustomThemeDialog
|
<CustomThemeDialog
|
||||||
:visible.sync="customThemeDialogVisible"
|
:visible.sync="customThemeDialogVisible"
|
||||||
:device="selectedDeviceForTheme"
|
:device="selectedDeviceForTheme"
|
||||||
|
@generate="handleGenerateAssets"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<!-- 生成模态框 -->
|
||||||
|
<component
|
||||||
|
v-if="showGenerateModal && generateModalComponent"
|
||||||
|
:is="generateModalComponent"
|
||||||
|
:visible.sync="showGenerateModal"
|
||||||
|
:config="generateConfig"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -151,6 +160,9 @@ export default {
|
||||||
manualAddDeviceDialogVisible: false,
|
manualAddDeviceDialogVisible: false,
|
||||||
customThemeDialogVisible: false,
|
customThemeDialogVisible: false,
|
||||||
selectedDeviceForTheme: null,
|
selectedDeviceForTheme: null,
|
||||||
|
showGenerateModal: false,
|
||||||
|
generateModalComponent: null,
|
||||||
|
generateConfig: null,
|
||||||
selectedDeviceId: '',
|
selectedDeviceId: '',
|
||||||
searchKeyword: "",
|
searchKeyword: "",
|
||||||
activeSearchKeyword: "",
|
activeSearchKeyword: "",
|
||||||
|
|
@ -214,10 +226,26 @@ export default {
|
||||||
},
|
},
|
||||||
methods: {
|
methods: {
|
||||||
handleCustomThemeConfig(row) {
|
handleCustomThemeConfig(row) {
|
||||||
console.log('[DeviceManagement] open custom theme for device', row);
|
|
||||||
this.selectedDeviceForTheme = row;
|
this.selectedDeviceForTheme = row;
|
||||||
this.customThemeDialogVisible = true;
|
this.customThemeDialogVisible = true;
|
||||||
},
|
},
|
||||||
|
async handleGenerateAssets(config) {
|
||||||
|
// 动态加载生成模态框组件
|
||||||
|
if (!this.generateModalComponent) {
|
||||||
|
try {
|
||||||
|
const module = await import('@/components/custom-theme/CustomThemeGenerateModal.vue');
|
||||||
|
this.generateModalComponent = module.default;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[DeviceManagement] Failed to load generate modal:', error);
|
||||||
|
this.$message.error('加载生成组件失败: ' + error.message);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 保存配置并显示生成模态框
|
||||||
|
this.generateConfig = config;
|
||||||
|
await this.$nextTick();
|
||||||
|
this.showGenerateModal = true;
|
||||||
|
},
|
||||||
async getFirmwareTypes() {
|
async getFirmwareTypes() {
|
||||||
try {
|
try {
|
||||||
const res = await Api.dict.getDictDataByType('FIRMWARE_TYPE')
|
const res = await Api.dict.getDictDataByType('FIRMWARE_TYPE')
|
||||||
|
|
|
||||||
|
|
@ -93,6 +93,15 @@ module.exports = defineConfig({
|
||||||
config.optimization.minimize(true);
|
config.optimization.minimize(true);
|
||||||
},
|
},
|
||||||
configureWebpack: config => {
|
configureWebpack: config => {
|
||||||
|
// 配置 webpack 忽略 Node.js 内置模块(用于浏览器环境)
|
||||||
|
config.resolve = config.resolve || {};
|
||||||
|
config.resolve.fallback = {
|
||||||
|
...config.resolve.fallback,
|
||||||
|
fs: false,
|
||||||
|
path: false,
|
||||||
|
crypto: false
|
||||||
|
};
|
||||||
|
|
||||||
if (process.env.NODE_ENV === 'production') {
|
if (process.env.NODE_ENV === 'production') {
|
||||||
// 开启多线程编译
|
// 开启多线程编译
|
||||||
config.optimization = {
|
config.optimization = {
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue