import{u as TA,r as j,w as DA,o as Me,a as G,c as U,b as s,t as d,d as fg,e as HA,f as wg,g as O,h as ig,i as nA,j as eA,n as nt,k as gA,F as bA,l as LA,m as rA,v as aA,p as Xe,q as PA,s as CA,x as UA,y as Bt,z as st,_ as aI,A as we}from"./index-E7j_fXTF.js";const QI={class:"space-y-6"},EI={class:"text-xl font-semibold text-gray-900 mb-4"},lI={class:"text-gray-600 mb-6"},cI={key:0},hI={key:1},uI={key:2},dI={key:0,class:"space-y-4"},fI={class:"bg-blue-50 border-2 border-blue-200 rounded-lg p-6"},wI={class:"flex items-center justify-center space-x-3"},yI={class:"text-lg font-medium text-blue-900"},pI={class:"text-sm text-blue-700 mt-1"},DI={key:1,class:"space-y-4"},mI={class:"bg-green-50 border-2 border-green-200 rounded-lg p-4"},FI={class:"flex items-start justify-between mb-3"},kI={class:"flex items-center"},vI={class:"text-lg font-medium text-green-900"},SI={class:"grid grid-cols-1 md:grid-cols-3 gap-4 mt-4"},GI={class:"bg-white rounded-lg p-3"},RI={class:"block text-sm font-medium text-gray-700 mb-1"},UI={class:"text-base font-semibold text-gray-900"},NI={class:"bg-white rounded-lg p-3"},bI={class:"block text-sm font-medium text-gray-700 mb-1"},LI={class:"text-base font-semibold text-gray-900"},MI={class:"bg-white rounded-lg p-3"},JI={class:"block text-sm font-medium text-gray-700 mb-1"},xI={class:"text-base font-semibold text-gray-900"},HI={class:"mt-3 text-sm text-green-700"},YI={class:"border border-gray-200 rounded-lg p-4"},KI={key:0,class:"mt-4"},TI={key:2,class:"space-y-4"},VI={class:"bg-yellow-50 border border-yellow-200 rounded-lg p-4"},qI={class:"flex items-start"},OI={class:"font-medium text-yellow-900"},WI={class:"text-sm text-yellow-700 mt-1"},PI={class:"border-2 border-gray-300 rounded-lg p-4"},ZI={class:"text-lg font-medium text-gray-900 mb-4"},XI={class:"flex justify-end"},jI=["disabled"],zI={__name:"ChipConfig",props:{modelValue:{type:Object,default:()=>({model:"",display:{width:320,height:240,color:"RGB565"}})}},emits:["update:modelValue","next"],setup(e,{emit:A}){const{t:g}=TA(),t=A,I=nA(()=>[{value:"",label:g("chipConfig.selectChip")},{value:"esp32s3",label:"ESP32-S3"},{value:"esp32c3",label:"ESP32-C3"},{value:"esp32c5",label:"ESP32-C5"},{value:"esp32c6",label:"ESP32-C6"},{value:"esp32p4",label:"ESP32-P4"},{value:"esp32",label:"ESP32"},{value:"others",label:g("common.other")}]),o={name:"ConfigForm",props:{config:{type:Object,required:!0},showRequired:{type:Boolean,default:!1}},render(){const y=this.$t;return eA("div",{class:"grid grid-cols-1 md:grid-cols-3 gap-4"},[eA("div",[eA("label",{class:"block text-sm font-medium text-gray-700 mb-2"},[y("chipConfig.chipRequired")+" ",this.showRequired&&eA("span",{class:"text-red-500"},"*")]),eA("select",{class:"w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-primary-500",value:this.config.model,onChange:v=>{this.config.model=v.target.value}},fg(I).map(v=>eA("option",{value:v.value,key:v.value},v.label)))]),eA("div",[eA("label",{class:"block text-sm font-medium text-gray-700 mb-2"},[y("chipConfig.widthRequired")+" ",this.showRequired&&eA("span",{class:"text-red-500"},"*")]),eA("input",{type:"number",class:"w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-primary-500",value:this.config.display.width,min:128,max:800,placeholder:"320",onInput:v=>{this.config.display.width=Number(v.target.value)}})]),eA("div",[eA("label",{class:"block text-sm font-medium text-gray-700 mb-2"},[y("chipConfig.heightRequired")+" ",this.showRequired&&eA("span",{class:"text-red-500"},"*")]),eA("input",{type:"number",class:"w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-primary-500",value:this.config.display.height,min:128,max:600,placeholder:"240",onInput:v=>{this.config.display.height=Number(v.target.value)}})])])}},{deviceInfo:i,isDeviceOnline:r,hasToken:C}=ig(),B=j(C.value),n=j(!1),Q=j(""),a=j(!1),E=j({model:"",display:{width:320,height:240,color:"RGB565"}}),h={"ESP32-S3":"esp32s3",ESP32S3:"esp32s3","ESP32-C3":"esp32c3",ESP32C3:"esp32c3","ESP32-C5":"esp32c5",ESP32C5:"esp32c5","ESP32-P4":"esp32p4",ESP32P4:"esp32p4","ESP32-C6":"esp32c6",ESP32C6:"esp32c6",ESP32:"esp32"},w=()=>{var y,v;try{if(!r.value)return B.value||(Q.value=g("chipConfig.deviceOffline"),n.value=!1),!1;const N=(y=i.value.chip)==null?void 0:y.model;if(!N||N==="未知")return!1;let L=h[N.toUpperCase()]||h[N]||N.toLowerCase().replace(/-/g,"");["esp32s3","esp32c3","esp32c5","esp32p4","esp32c6","esp32","others"].includes(L)||(L="others");const k=(v=i.value.screen)==null?void 0:v.resolution;if(!k||k==="未知")return!1;const[m,M]=k.split("x").map(Number);return!m||!M||isNaN(m)||isNaN(M)?(Q.value=g("chipConfig.resolutionFormatError"),n.value=!1,B.value=!1,!1):(E.value={model:L,display:{width:m,height:M,color:"RGB565"}},t("update:modelValue",{model:L,display:{width:m,height:M,color:"RGB565"}}),n.value=!0,Q.value="",B.value=!1,console.log("✓ 设备配置加载成功:",{chip:L,width:m,height:M}),!0)}catch(N){return console.error("加载设备配置失败:",N),Q.value=g("chipConfig.loadingError"),n.value=!1,B.value=!1,!1}},u=nA(()=>E.value.model&&E.value.display.width&&E.value.display.height),l=nA(()=>E.value.model?E.value.model.toUpperCase().replace(/ESP32/i,"ESP32-"):""),f=nA(()=>E.value.display),c=()=>{a.value=!a.value},D=()=>{u.value&&t("next")};return DA(()=>E.value,y=>{t("update:modelValue",{model:y.model,display:{...y.display}})},{deep:!0}),DA(()=>r.value,y=>{y&&!n.value&&(B.value=!0,Q.value="",setTimeout(()=>{w()},100))}),DA(()=>[i.value.chip,i.value.screen],()=>{r.value&&!n.value&&w()},{deep:!0}),Me(()=>{if(!C.value){B.value=!1,Q.value=g("chipConfig.manualConfigRequired"),console.log("⚠ 未检测到设备连接,使用手动配置模式");return}r.value&&i.value.chip&&i.value.chip.model!=="未知"&&i.value.screen&&i.value.screen.resolution!=="未知"?(console.log("✓ 检测到已缓存的设备信息,立即加载"),w()):r.value?(console.log("⏳ 设备在线,等待设备信息加载..."),B.value=!0,setTimeout(()=>{w()},500),setTimeout(()=>{B.value&&!n.value&&r.value&&(B.value=!1,!i.value.chip||i.value.chip.model==="未知"?Q.value=g("chipConfig.chipModelError"):!i.value.screen||i.value.screen.resolution==="未知"?Q.value=g("chipConfig.resolutionError"):Q.value=g("chipConfig.timeoutError"),console.warn("⚠ 设备配置加载超时:",Q.value))},1e4)):(console.log("⏳ 等待设备连接..."),B.value=!0,setTimeout(()=>{B.value&&!n.value&&!r.value&&(B.value=!1,Q.value=g("chipConfig.manualConfigHint"),console.warn("⚠ 等待设备连接超时"))},1e4))}),(y,v)=>(G(),U("div",QI,[s("div",null,[s("h2",EI,d(y.$t("chipConfig.title")),1),s("p",lI,[B.value?(G(),U("span",cI,d(y.$t("chipConfig.loadingFromDevice")),1)):n.value?(G(),U("span",hI,d(y.$t("chipConfig.loadedFromDevice")),1)):(G(),U("span",uI,d(y.$t("chipConfig.manualConfig")),1))])]),B.value?(G(),U("div",dI,[s("div",fI,[s("div",wI,[v[0]||(v[0]=s("svg",{class:"animate-spin h-6 w-6 text-blue-600",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24"},[s("circle",{class:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor","stroke-width":"4"}),s("path",{class:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})],-1)),s("div",null,[s("h3",yI,d(y.$t("chipConfig.loadingTitle")),1),s("p",pI,d(y.$t("chipConfig.loadingDesc")),1)])])])])):fg(r)&&n.value?(G(),U("div",DI,[s("div",mI,[s("div",FI,[s("div",kI,[v[1]||(v[1]=s("div",{class:"w-5 h-5 bg-green-500 rounded-full flex items-center justify-center mr-2"},[s("svg",{class:"w-3 h-3 text-white",fill:"currentColor",viewBox:"0 0 20 20"},[s("path",{"fill-rule":"evenodd",d:"M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z","clip-rule":"evenodd"})])],-1)),s("h3",vI,d(y.$t("chipConfig.autoLoadedTitle")),1)])]),s("div",SI,[s("div",GI,[s("label",RI,d(y.$t("chipConfig.chipModel")),1),s("div",UI,d(l.value),1)]),s("div",NI,[s("label",bI,d(y.$t("chipConfig.screenWidth")),1),s("div",LI,d(f.value.width)+" px",1)]),s("div",MI,[s("label",JI,d(y.$t("chipConfig.screenHeight")),1),s("div",xI,d(f.value.height)+" px",1)])]),s("div",HI," ✓ "+d(y.$t("chipConfig.colorFormat"))+" "+d(f.value.color),1)]),s("div",YI,[s("button",{onClick:c,class:"flex items-center text-sm text-gray-600 hover:text-gray-900"},[v[2]||(v[2]=s("svg",{class:"w-4 h-4 mr-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},[s("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"}),s("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"})],-1)),HA(" "+d(a.value?y.$t("chipConfig.collapseManual"):y.$t("chipConfig.manualEdit")),1)]),a.value?(G(),U("div",KI,[wg(o,{config:E.value},null,8,["config"])])):O("",!0)])])):(G(),U("div",TI,[s("div",VI,[s("div",qI,[v[3]||(v[3]=s("svg",{class:"w-5 h-5 text-yellow-600 mr-3 flex-shrink-0 mt-0.5",fill:"currentColor",viewBox:"0 0 20 20"},[s("path",{"fill-rule":"evenodd",d:"M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z","clip-rule":"evenodd"})],-1)),s("div",null,[s("h4",OI,d(y.$t("chipConfig.manualConfigDesc")),1),s("p",WI,d(Q.value||y.$t("chipConfig.manualConfigHint")),1)])])]),s("div",PI,[s("h3",ZI,d(y.$t("chipConfig.manualConfigTitle")),1),wg(o,{config:E.value,"show-required":!0},null,8,["config"])])])),s("div",XI,[s("button",{onClick:D,disabled:!u.value,class:"bg-primary-500 hover:bg-primary-600 disabled:bg-gray-300 text-white px-6 py-2 rounded-lg font-medium transition-colors"},d(y.$t("chipConfig.next")),9,jI)])]))}},_I={class:"space-y-6"},$I={class:"text-lg font-medium text-gray-900 mb-2"},Ao={class:"text-gray-600"},eo={key:0,class:"bg-orange-50 border border-orange-200 rounded-lg p-4"},go={class:"text-sm text-orange-800"},to={class:"mt-1"},Io={key:1,class:"space-y-6"},oo={class:"flex space-x-4"},io={key:0,class:"space-y-4"},ro={class:"block text-sm font-medium text-gray-700"},Co={class:"relative"},no=["value"],Bo=["value"],so={key:1,class:"space-y-4 bg-gray-50 p-4 rounded-lg border border-gray-200"},ao={class:"font-medium text-gray-900"},Qo={class:"grid grid-cols-1 md:grid-cols-2 gap-4"},Eo={class:"block text-sm font-medium text-gray-700 mb-1"},lo=["placeholder"],co={key:0,class:"text-xs text-red-500 mt-1"},ho={class:"block text-sm font-medium text-gray-700 mb-1"},uo=["placeholder"],fo={key:0,class:"text-xs text-red-500 mt-1"},wo={class:"grid grid-cols-1 md:grid-cols-3 gap-4"},yo={class:"block text-sm font-medium text-gray-700 mb-1"},po={class:"flex items-center space-x-2"},Do={class:"text-sm text-gray-600 w-8"},mo={class:"text-xs text-gray-500 mt-1"},Fo={class:"block text-sm font-medium text-gray-700 mb-1"},ko={key:0,class:"text-xs text-red-500 mt-1"},vo={class:"block text-sm font-medium text-gray-700 mb-1"},So={value:"mn6_en"},Go={class:"bg-blue-50 border border-blue-200 rounded-lg p-3"},Ro={class:"text-sm text-blue-800"},Uo={class:"mt-1 list-disc list-inside space-y-1"},No={key:0},bo={key:1},Lo={key:2},Mo={__name:"WakewordConfig",props:{modelValue:{type:Object,required:!0},chipModel:{type:String,required:!0}},emits:["update:modelValue"],setup(e,{emit:A}){const{t:g}=TA(),t=e,I=A,o=[{id:"wn9s_hilexin",name:"Hi, Espressif",model:"WakeNet9s"},{id:"wn9s_hiesp",name:"Hi,ESP",model:"WakeNet9s"},{id:"wn9s_nihaoxiaozhi",name:"Hello Xiaozhi",model:"WakeNet9s"},{id:"wn9s_hijason",name:"Hi,Jason",model:"WakeNet9s"},{id:"wn9s_alexa",name:"Alexa",model:"WakeNet9s"},{id:"wn9_hilexin",name:"Hi, Espressif",model:"WakeNet9"},{id:"wn9_hiesp",name:"Hi,ESP",model:"WakeNet9"},{id:"wn9_nihaoxiaozhi_tts",name:"Hello Xiaozhi",model:"WakeNet9"},{id:"wn9_hijason_tts2",name:"Hi,Jason",model:"WakeNet9"},{id:"wn9_himfive",name:"Hi,M Five",model:"WakeNet9"},{id:"wn9_alexa",name:"Alexa",model:"WakeNet9"},{id:"wn9_jarvis_tts",name:"Jarvis",model:"WakeNet9"},{id:"wn9_computer_tts",name:"Computer",model:"WakeNet9"},{id:"wn9_heywillow_tts",name:"Hey,Willow",model:"WakeNet9"},{id:"wn9_sophia_tts",name:"Sophia",model:"WakeNet9"},{id:"wn9_heyprinter_tts",name:"Hey,Printer",model:"WakeNet9"},{id:"wn9_hijoy_tts",name:"Hi,Joy",model:"WakeNet9"},{id:"wn9_heywanda_tts",name:"Hey,Wand",model:"WakeNet9"},{id:"wn9_astrolabe_tts",name:"Astrolabe",model:"WakeNet9"},{id:"wn9_heyily_tts2",name:"Hey,Ily",model:"WakeNet9"},{id:"wn9_hijolly_tts2",name:"Hi,Jolly",model:"WakeNet9"},{id:"wn9_hifairy_tts2",name:"Hi,Fairy",model:"WakeNet9"},{id:"wn9_bluechip_tts2",name:"Blue Chip",model:"WakeNet9"},{id:"wn9_hiandy_tts2",name:"Hi,Andy",model:"WakeNet9"},{id:"wn9_heyivy_tts2",name:"Hey,Ivy",model:"WakeNet9"},{id:"wn9_histackchan_tts3",name:"Hi,Stack Chan",model:"WakeNet9"},{id:"wn9_hiwalle_tts2",name:"Hi,Wall E",model:"WakeNet9"},{id:"wn9_hilili_tts",name:"Hi,Lily",model:"WakeNet9"},{id:"wn9_hitelly_tts",name:"Hi,Telly",model:"WakeNet9"},{id:"wn9_linaiban_tts2",name:"Lina Board",model:"WakeNet9"}],i=nA(()=>{const l=t.chipModel.toLowerCase();return l==="esp32s3"||l==="esp32p4"}),r=nA(()=>{const l=t.chipModel.toLowerCase();return l==="esp32c3"||l==="esp32c5"||l==="esp32c6"}),C=nA(()=>t.chipModel.toLowerCase()==="esp32s3"),B=nA(()=>i.value||r.value),n=nA(()=>i.value?o.filter(l=>l.model==="WakeNet9"):r.value?o.filter(l=>l.model==="WakeNet9s"):[]),Q=j({name:"",command:"",threshold:20,duration:3e3,model:"mn6_en"}),a=j({name:"",command:"",duration:""}),E=()=>{let l=!0;return a.value={name:"",command:"",duration:""},Q.value.name.trim()||(a.value.name=g("wakewordConfig.errors.nameRequired"),l=!1),Q.value.command.trim()?Q.value.model.includes("_en")&&/[!,.?]/.test(Q.value.command)&&(a.value.command=g("wakewordConfig.errors.noPunctuation"),l=!1):(a.value.command=g("wakewordConfig.errors.commandRequired"),l=!1),(!Q.value.duration||Q.value.duration<500||Q.value.duration>1e4)&&(a.value.duration=g("wakewordConfig.errors.durationRange"),l=!1),l},h=j(!1),w=l=>{var f;I("update:modelValue",{...t.modelValue,type:l,preset:l==="preset"&&(t.modelValue.preset||((f=n.value[0])==null?void 0:f.id))||"",custom:{...t.modelValue.custom,...Q.value}})},u=l=>{I("update:modelValue",{...t.modelValue,preset:l})};return DA(Q,l=>{h.value||t.modelValue.type==="custom"&&(E(),I("update:modelValue",{...t.modelValue,custom:{...l}}))},{deep:!0}),DA(()=>t.modelValue.custom,l=>{l&&(h.value=!0,Q.value={name:l.name||"",command:l.command||"",threshold:l.threshold!==void 0?l.threshold:20,duration:l.duration!==void 0?l.duration:3e3,model:l.model||"mn6_en"},nt(()=>{h.value=!1}))},{deep:!0,immediate:!0}),(l,f)=>(G(),U("div",_I,[s("div",null,[s("h3",$I,d(l.$t("wakewordConfig.title")),1),s("p",Ao,d(l.$t("wakewordConfig.description")),1)]),B.value?(G(),U("div",Io,[s("div",oo,[s("button",{onClick:f[0]||(f[0]=c=>w("none")),class:gA(["px-4 py-2 border rounded-lg transition-colors",e.modelValue.type==="none"?"border-primary-500 bg-primary-50 text-primary-700":"border-gray-300 hover:border-gray-400"])},d(l.$t("wakewordConfig.noWakeword")),3),s("button",{onClick:f[1]||(f[1]=c=>w("preset")),class:gA(["px-4 py-2 border rounded-lg transition-colors",e.modelValue.type==="preset"?"border-primary-500 bg-primary-50 text-primary-700":"border-gray-300 hover:border-gray-400"])},d(l.$t("wakewordConfig.presetWakeword")),3),C.value?(G(),U("button",{key:0,onClick:f[2]||(f[2]=c=>w("custom")),class:gA(["px-4 py-2 border rounded-lg transition-colors",e.modelValue.type==="custom"?"border-primary-500 bg-primary-50 text-primary-700":"border-gray-300 hover:border-gray-400"])},d(l.$t("wakewordConfig.customWakeword")),3)):O("",!0)]),e.modelValue.type==="preset"?(G(),U("div",io,[s("label",ro,d(l.$t("wakewordConfig.selectWakeword")),1),s("div",Co,[s("select",{value:e.modelValue.preset,onChange:f[3]||(f[3]=c=>u(c.target.value)),class:"w-full border border-gray-300 rounded-md px-3 py-2 pr-10 bg-white focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-primary-500"},[(G(!0),U(bA,null,LA(n.value,c=>(G(),U("option",{key:c.id,value:c.id},d(c.name)+" ("+d(c.model)+") ",9,Bo))),128))],40,no)])])):O("",!0),e.modelValue.type==="custom"?(G(),U("div",so,[s("h4",ao,d(l.$t("wakewordConfig.customSettings")),1),s("div",Qo,[s("div",null,[s("label",Eo,[HA(d(l.$t("wakewordConfig.wakewordName"))+" ",1),f[9]||(f[9]=s("span",{class:"text-red-500"},"*",-1))]),rA(s("input",{type:"text","onUpdate:modelValue":f[4]||(f[4]=c=>Q.value.name=c),placeholder:l.$t("wakewordConfig.wakewordNamePlaceholder"),class:gA(["w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary-500",{"border-red-500":a.value.name}])},null,10,lo),[[aA,Q.value.name]]),a.value.name?(G(),U("p",co,d(a.value.name),1)):O("",!0)]),s("div",null,[s("label",ho,[HA(d(l.$t("wakewordConfig.wakewordCommand"))+" ",1),f[10]||(f[10]=s("span",{class:"text-red-500"},"*",-1))]),rA(s("input",{type:"text","onUpdate:modelValue":f[5]||(f[5]=c=>Q.value.command=c),placeholder:l.$t("wakewordConfig.wakewordCommandPlaceholderEN"),class:gA(["w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary-500",{"border-red-500":a.value.command}])},null,10,uo),[[aA,Q.value.command]]),a.value.command?(G(),U("p",fo,d(a.value.command),1)):O("",!0)])]),s("div",wo,[s("div",null,[s("label",yo,d(l.$t("wakewordConfig.threshold")),1),s("div",po,[rA(s("input",{type:"range","onUpdate:modelValue":f[6]||(f[6]=c=>Q.value.threshold=c),min:"0",max:"100",step:"1",class:"flex-1"},null,512),[[aA,Q.value.threshold,void 0,{number:!0}]]),s("span",Do,d(Q.value.threshold),1)]),s("p",mo,d(l.$t("wakewordConfig.thresholdDesc")),1)]),s("div",null,[s("label",Fo,d(l.$t("wakewordConfig.duration"))+" (ms) ",1),rA(s("input",{type:"number","onUpdate:modelValue":f[7]||(f[7]=c=>Q.value.duration=c),min:"500",max:"10000",step:"100",class:gA(["w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary-500",{"border-red-500":a.value.duration}])},null,2),[[aA,Q.value.duration,void 0,{number:!0}]]),a.value.duration?(G(),U("p",ko,d(a.value.duration),1)):O("",!0)]),s("div",null,[s("label",vo,d(l.$t("wakewordConfig.selectModel")),1),rA(s("select",{"onUpdate:modelValue":f[8]||(f[8]=c=>Q.value.model=c),class:"w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary-500"},[s("option",So,d(l.$t("wakewordConfig.mn6en")),1)],512),[[Xe,Q.value.model]])])])])):O("",!0),s("div",Go,[s("div",Ro,[s("strong",null,d(l.$t("wakewordConfig.tips.tipLabel")),1),s("ul",Uo,[s("li",null,d(l.$t("wakewordConfig.tips.optional")),1),r.value?(G(),U("li",No,d(l.$t("wakewordConfig.tips.wakeNet9sOnly")),1)):i.value?(G(),U("li",bo,d(l.$t("wakewordConfig.tips.wakeNet9Full")),1)):O("",!0),C.value?(G(),U("li",Lo,d(l.$t("wakewordConfig.tips.customSupport")),1)):O("",!0)])])])])):(G(),U("div",eo,[s("div",go,[s("strong",null,d(l.$t("wakewordConfig.notice")),1),s("p",to,d(l.$t("wakewordConfig.unsupportedMessage",{chipModel:e.chipModel})),1)])]))]))}};class Jo{constructor(){this.dbName="XiaozhiConfigDB",this.version=1,this.db=null,this.initialized=!1}async initialize(){if(!(this.initialized&&this.db))return new Promise((A,g)=>{const t=indexedDB.open(this.dbName,this.version);t.onerror=()=>{console.error("IndexedDB 初始化失败:",t.error),g(t.error)},t.onsuccess=()=>{this.db=t.result,this.initialized=!0,console.log("IndexedDB 初始化成功"),A()},t.onupgradeneeded=I=>{const o=I.target.result;if(o.objectStoreNames.contains("configs")||o.createObjectStore("configs",{keyPath:"key"}).createIndex("timestamp","timestamp",{unique:!1}),!o.objectStoreNames.contains("files")){const i=o.createObjectStore("files",{keyPath:"id"});i.createIndex("type","type",{unique:!1}),i.createIndex("timestamp","timestamp",{unique:!1})}if(!o.objectStoreNames.contains("temp_data")){const i=o.createObjectStore("temp_data",{keyPath:"key"});i.createIndex("type","type",{unique:!1}),i.createIndex("timestamp","timestamp",{unique:!1})}console.log("IndexedDB 表结构创建完成")}})}async saveConfig(A){this.initialized||await this.initialize();const t={key:"current_config",config:this.sanitizeConfigForStorage(A),timestamp:Date.now()};return new Promise((I,o)=>{const C=this.db.transaction(["configs"],"readwrite").objectStore("configs").put(t);C.onerror=()=>{console.error("保存配置失败:",C.error),o(C.error)},C.onsuccess=()=>{console.log("配置已保存到 IndexedDB"),I()}})}sanitizeConfigForStorage(A){var t,I,o,i,r,C,B,n,Q,a;const g=JSON.parse(JSON.stringify(A||{}));try{if((I=(t=g==null?void 0:g.theme)==null?void 0:t.font)!=null&&I.custom&&(g.theme.font.custom.file=null),((i=(o=g==null?void 0:g.theme)==null?void 0:o.emoji)==null?void 0:i.type)==="custom"){g.theme.emoji.custom||(g.theme.emoji.custom={});const E=((C=(r=g.theme.emoji)==null?void 0:r.custom)==null?void 0:C.images)||{},h={};if(Object.keys(E).forEach(w=>{h[w]=null}),g.theme.emoji.custom.images=h,g.theme.emoji.custom.emotionMap,g.theme.emoji.custom.fileMap){const w=g.theme.emoji.custom.fileMap,u={};Object.keys(w).forEach(l=>{u[l]=null}),g.theme.emoji.custom.fileMap=u}}(n=(B=g==null?void 0:g.theme)==null?void 0:B.skin)!=null&&n.light&&(g.theme.skin.light.backgroundImage=null),(a=(Q=g==null?void 0:g.theme)==null?void 0:Q.skin)!=null&&a.dark&&(g.theme.skin.dark.backgroundImage=null)}catch{}return g}async loadConfig(){return this.initialized||await this.initialize(),new Promise((A,g)=>{const o=this.db.transaction(["configs"],"readonly").objectStore("configs").get("current_config");o.onerror=()=>{console.error("加载配置失败:",o.error),g(o.error)},o.onsuccess=()=>{const i=o.result;i?(console.log("从 IndexedDB 恢复配置成功"),A({config:i.config,timestamp:i.timestamp})):A(null)}})}async saveFile(A,g,t,I={}){this.initialized||await this.initialize();const o=await this.fileToArrayBuffer(g);let i={};try{i=I?JSON.parse(JSON.stringify(I)):{}}catch{i={...I}}const r={id:A,type:t,name:g.name,size:g.size,mimeType:g.type,lastModified:g.lastModified,data:o,metadata:i,timestamp:Date.now()};return new Promise((C,B)=>{const a=this.db.transaction(["files"],"readwrite").objectStore("files").put(r);a.onerror=()=>{console.error("保存文件失败:",a.error),B(a.error)},a.onsuccess=()=>{console.log(`文件 ${g.name} 已保存到 IndexedDB`),C()}})}async loadFile(A){return this.initialized||await this.initialize(),new Promise((g,t)=>{const i=this.db.transaction(["files"],"readonly").objectStore("files").get(A);i.onerror=()=>{console.error("加载文件失败:",i.error),t(i.error)},i.onsuccess=()=>{const r=i.result;if(r){const C=new Blob([r.data],{type:r.mimeType}),B=new File([C],r.name,{type:r.mimeType,lastModified:r.lastModified});B.storedId=r.id,B.storedType=r.type,B.storedMetadata=r.metadata,B.storedTimestamp=r.timestamp,console.log(`文件 ${r.name} 从 IndexedDB 恢复成功`),g(B)}else g(null)}})}async getFilesByType(A){return this.initialized||await this.initialize(),new Promise((g,t)=>{const r=this.db.transaction(["files"],"readonly").objectStore("files").index("type").getAll(A);r.onerror=()=>{console.error("获取文件列表失败:",r.error),t(r.error)},r.onsuccess=()=>{const B=(r.result||[]).map(n=>{const Q=new Blob([n.data],{type:n.mimeType}),a=new File([Q],n.name,{type:n.mimeType,lastModified:n.lastModified});return a.storedId=n.id,a.storedType=n.type,a.storedMetadata=n.metadata,a.storedTimestamp=n.timestamp,a});g(B)}})}async saveTempData(A,g,t,I={}){this.initialized||await this.initialize();const o={key:A,type:t,data:g,metadata:I,timestamp:Date.now()};return new Promise((i,r)=>{const n=this.db.transaction(["temp_data"],"readwrite").objectStore("temp_data").put(o);n.onerror=()=>{console.error("保存临时数据失败:",n.error),r(n.error)},n.onsuccess=()=>{console.log(`临时数据 ${A} 已保存`),i()}})}async loadTempData(A){return this.initialized||await this.initialize(),new Promise((g,t)=>{const i=this.db.transaction(["temp_data"],"readonly").objectStore("temp_data").get(A);i.onerror=()=>{console.error("加载临时数据失败:",i.error),t(i.error)},i.onsuccess=()=>{const r=i.result;g(r||null)}})}async clearAll(){this.initialized||await this.initialize();const A=["configs","files","temp_data"];return new Promise((g,t)=>{const I=this.db.transaction(A,"readwrite");let o=0,i=!1;const r=()=>{o++,o===A.length&&(i?t(new Error("清空部分数据时出现错误")):(console.log("所有存储数据已清空"),g()))};A.forEach(C=>{const n=I.objectStore(C).clear();n.onerror=()=>{console.error(`清空 ${C} 失败:`,n.error),i=!0,r()},n.onsuccess=()=>{console.log(`${C} 已清空`),r()}})})}async deleteFile(A){return this.initialized||await this.initialize(),new Promise((g,t)=>{const i=this.db.transaction(["files"],"readwrite").objectStore("files").delete(A);i.onerror=()=>{console.error("删除文件失败:",i.error),t(i.error)},i.onsuccess=()=>{console.log(`文件 ${A} 已删除`),g()}})}async getStorageInfo(){this.initialized||await this.initialize();const A=["configs","files","temp_data"],g={};for(const I of A){const o=await new Promise((i,r)=>{const n=this.db.transaction([I],"readonly").objectStore(I).count();n.onerror=()=>r(n.error),n.onsuccess=()=>i(n.result)});g[I]={count:o}}const t=await this.loadConfig();return g.lastSaved=t?new Date(t.timestamp):null,g}async hasStoredConfig(){try{return await this.loadConfig()!==null}catch(A){return console.error("检查存储配置时出错:",A),!1}}fileToArrayBuffer(A){return new Promise((g,t)=>{const I=new FileReader;I.onload=()=>g(I.result),I.onerror=()=>t(new Error("读取文件失败")),I.readAsArrayBuffer(A)})}close(){this.db&&(this.db.close(),this.db=null,this.initialized=!1,console.log("IndexedDB 连接已关闭"))}}const cA=new Jo;class Ie{static async saveFontFile(A,g={}){if(A){const t="custom_font";try{await cA.saveFile(t,A,"font",{size:g.size||20,bpp:g.bpp||4,charset:g.charset||"deepseek"}),console.log(`字体文件已保存: ${A.name}`)}catch(I){console.warn(`保存字体文件失败: ${A.name}`,I)}}}static async saveEmojiFile(A,g,t={}){var I,o;if(g&&A){const i=A.startsWith("hash_")?A:`emoji_${A}`;try{const r=((I=t==null?void 0:t.size)==null?void 0:I.width)??64,C=((o=t==null?void 0:t.size)==null?void 0:o.height)??64;await cA.saveFile(i,g,"emoji",{name:A,size:{width:r,height:C},format:t==null?void 0:t.format,emotions:t==null?void 0:t.emotions}),console.log(`表情文件已保存: ${i} - ${g.name}`)}catch(r){console.warn(`保存表情文件失败: ${A}`,r)}}}static async saveBackgroundFile(A,g,t={}){if(g&&A){const I=`background_${A}`;try{let o={};try{o=t?JSON.parse(JSON.stringify(t)):{}}catch{o={...t}}await cA.saveFile(I,g,"background",{mode:A,...o}),console.log(`背景文件已保存: ${A} - ${g.name}`)}catch(o){console.warn(`保存背景文件失败: ${A}`,o)}}}static async restoreFontFile(){try{return await cA.loadFile("custom_font")}catch(A){return console.warn("恢复字体文件失败:",A),null}}static async restoreEmojiFile(A){if(!A)return null;try{const g=A.startsWith("hash_")?A:`emoji_${A}`;return await cA.loadFile(g)}catch(g){return console.warn(`恢复表情文件失败: ${A}`,g),null}}static async restoreBackgroundFile(A){if(!A)return null;try{const g=`background_${A}`;return await cA.loadFile(g)}catch(g){return console.warn(`恢复背景文件失败: ${A}`,g),null}}static async deleteFontFile(){try{await cA.deleteFile("custom_font"),console.log("字体文件已删除")}catch(A){console.warn("删除字体文件失败:",A)}}static async deleteEmojiFile(A){if(A)try{const g=A.startsWith("hash_")?A:`emoji_${A}`;await cA.deleteFile(g),console.log(`表情文件已删除: ${g}`)}catch(g){console.warn(`删除表情文件失败: ${A}`,g)}}static async deleteBackgroundFile(A){if(A)try{const g=`background_${A}`;await cA.deleteFile(g),console.log(`背景文件已删除: ${A}`)}catch(g){console.warn(`删除背景文件失败: ${A}`,g)}}static async getStorageInfo(){try{return await cA.getStorageInfo()}catch(A){return console.warn("获取存储信息失败:",A),{configs:{count:0},files:{count:0},temp_data:{count:0},lastSaved:null}}}static async clearAllFiles(){try{await cA.clearAll(),console.log("所有存储文件已清理")}catch(A){throw console.warn("清理存储文件失败:",A),A}}}const xo={class:"space-y-6"},Ho={class:"text-lg font-medium text-gray-900 mb-2"},Yo={class:"text-gray-600"},Ko={class:"space-y-4"},To={class:"flex space-x-4"},Vo={key:0,class:"space-y-4"},qo={class:"bg-gray-50 border border-gray-200 rounded-lg p-6 text-center"},Oo={class:"mt-2 text-gray-600"},Wo={key:1,class:"space-y-4"},Po={class:"font-medium text-gray-900"},Zo={class:"grid grid-cols-1 md:grid-cols-4 gap-4"},Xo=["onClick"],jo={class:"flex items-start justify-between"},zo={class:"flex-1"},_o={class:"font-medium text-gray-900 mb-1"},$o={class:"text-sm text-gray-600 space-y-1"},Ai={key:0,class:"flex-shrink-0 ml-3"},ei={key:2,class:"space-y-6"},gi={class:"font-medium text-gray-900"},ti={class:"space-y-2"},Ii={class:"block text-sm font-medium text-gray-700"},oi={key:0},ii={class:"mt-2"},ri={class:"text-gray-500"},Ci={class:"text-xs text-gray-400 mt-1"},ni={key:1,class:"text-green-600"},Bi={class:"mt-1 font-medium"},si={key:0,class:"grid grid-cols-1 md:grid-cols-3 gap-4"},ai={class:"block text-sm font-medium text-gray-700 mb-2"},Qi={class:"text-xs text-gray-500 mt-1"},Ei={class:"block text-sm font-medium text-gray-700 mb-2"},li={value:1},ci={value:2},hi={value:4},ui={class:"block text-sm font-medium text-gray-700 mb-2"},di={value:"qwen"},fi={value:"deepseek"},wi={value:"latin"},yi={value:"full"},pi={class:"flex items-center justify-between p-4 bg-gray-50 rounded-lg border border-gray-200"},Di={class:"flex-1"},mi={class:"font-medium text-gray-900"},Fi={class:"text-sm text-gray-500 mt-1"},ki={class:"ml-4"},vi={class:"relative inline-flex items-center cursor-pointer"},Si=["checked"],Gi={__name:"FontConfig",props:{modelValue:{type:Object,required:!0}},emits:["update:modelValue"],setup(e,{emit:A}){const{t:g}=TA(),t=e,I=A,o=j(null),i=[{id:"font_puhui_deepseek_14_1",size:14,bpp:1,fileSize:"~180KB"},{id:"font_puhui_deepseek_16_4",size:16,bpp:4,fileSize:"~720KB"},{id:"font_puhui_deepseek_20_4",size:20,bpp:4,fileSize:"~1.1MB"},{id:"font_puhui_deepseek_30_4",size:30,bpp:4,fileSize:"~2.5MB"},{id:"font_noto_qwen_14_1",size:14,bpp:1,fileSize:"~626KB"},{id:"font_noto_qwen_16_4",size:16,bpp:4,fileSize:"~2.0MB"},{id:"font_noto_qwen_20_4",size:20,bpp:4,fileSize:"~2.9MB"},{id:"font_noto_qwen_30_4",size:30,bpp:4,fileSize:"~5.8MB"}],r=nA(()=>i.map(u=>{let l;return u.id.startsWith("font_puhui_deepseek_")?l=g("fontConfig.charsetDeepseek"):u.id.startsWith("font_noto_qwen_")&&(l=g("fontConfig.charsetQwen")),{...u,name:g("fontConfig.presetFontNames."+u.id),charset:l}})),C=j({size:20,bpp:4,charset:"qwen"}),B=u=>{I("update:modelValue",{...t.modelValue,type:u,preset:u==="preset"?t.modelValue.preset||"font_puhui_deepseek_20_4":"",custom:{...t.modelValue.custom,file:t.modelValue.custom.file||null}})},n=u=>{I("update:modelValue",{...t.modelValue,preset:u,custom:{...t.modelValue.custom,file:t.modelValue.custom.file||null}})},Q=u=>{const l=u.target.files[0];l&&E(l)},a=u=>{u.preventDefault();const l=u.dataTransfer.files;l.length>0&&E(l[0])},E=async u=>{u&&(u.type.includes("font")||u.name.toLowerCase().match(/\.(ttf|woff|woff2)$/))?(I("update:modelValue",{...t.modelValue,custom:{...t.modelValue.custom,file:u,...C.value}}),await Ie.saveFontFile(u,C.value)):alert(g("fontConfig.selectValidFontFile"))},h=async()=>{I("update:modelValue",{...t.modelValue,custom:{...t.modelValue.custom,file:null}}),o.value&&(o.value.value=""),await Ie.deleteFontFile()},w=j(!1);return DA(()=>C.value,u=>{w.value||t.modelValue.type==="custom"&&t.modelValue.custom.file&&I("update:modelValue",{...t.modelValue,custom:{...t.modelValue.custom,...u}})},{deep:!0}),DA(()=>t.modelValue.custom,u=>{u.size&&u.bpp&&u.charset&&(w.value=!0,C.value={size:u.size,bpp:u.bpp,charset:u.charset},nt(()=>{w.value=!1}))},{deep:!0,immediate:!0}),(u,l)=>{var f;return G(),U("div",xo,[s("div",null,[s("h3",Ho,d(u.$t("fontConfig.title")),1),s("p",Yo,d(u.$t("fontConfig.description")),1)]),s("div",Ko,[s("div",To,[s("button",{onClick:l[0]||(l[0]=c=>B("none")),class:gA(["px-4 py-2 border rounded-lg transition-colors",e.modelValue.type==="none"?"border-primary-500 bg-primary-50 text-primary-700":"border-gray-300 hover:border-gray-400"])},d(u.$t("fontConfig.noFonts")),3),s("button",{onClick:l[1]||(l[1]=c=>B("preset")),class:gA(["px-4 py-2 border rounded-lg transition-colors",e.modelValue.type==="preset"?"border-primary-500 bg-primary-50 text-primary-700":"border-gray-300 hover:border-gray-400"])},d(u.$t("fontConfig.presetFonts")),3),s("button",{onClick:l[2]||(l[2]=c=>B("custom")),class:gA(["px-4 py-2 border rounded-lg transition-colors",e.modelValue.type==="custom"?"border-primary-500 bg-primary-50 text-primary-700":"border-gray-300 hover:border-gray-400"])},d(u.$t("fontConfig.customFonts")),3)])]),e.modelValue.type==="none"?(G(),U("div",Vo,[s("div",qo,[l[10]||(l[10]=s("svg",{class:"mx-auto h-12 w-12 text-gray-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor"},[s("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M6 18L18 6M6 6l12 12"})],-1)),s("p",Oo,d(u.$t("fontConfig.noFontsDescription")),1)])])):O("",!0),e.modelValue.type==="preset"?(G(),U("div",Wo,[s("h4",Po,d(u.$t("fontConfig.presetFonts")),1),s("div",Zo,[(G(!0),U(bA,null,LA(r.value,c=>(G(),U("div",{key:c.id,onClick:D=>n(c.id),class:gA(["border-2 rounded-lg p-4 cursor-pointer transition-all",e.modelValue.preset===c.id?"border-primary-500 bg-primary-50":"border-gray-200 hover:border-gray-300"])},[s("div",jo,[s("div",zo,[s("h5",_o,d(c.name),1),s("div",$o,[s("div",null,d(u.$t("fontConfig.fontSize"))+" "+d(c.size)+"px",1),s("div",null,d(u.$t("fontConfig.bitDepth"))+" "+d(c.bpp)+"bpp",1),s("div",null,d(u.$t("fontConfig.charset"))+" "+d(c.charset),1),s("div",null,d(u.$t("fontConfig.fileSize"))+" "+d(c.fileSize),1)])]),e.modelValue.preset===c.id?(G(),U("div",Ai,[...l[11]||(l[11]=[s("div",{class:"w-5 h-5 bg-primary-500 rounded-full flex items-center justify-center"},[s("svg",{class:"w-3 h-3 text-white",fill:"currentColor",viewBox:"0 0 20 20"},[s("path",{"fill-rule":"evenodd",d:"M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z","clip-rule":"evenodd"})])],-1)])])):O("",!0)])],10,Xo))),128))])])):O("",!0),e.modelValue.type==="custom"?(G(),U("div",ei,[s("h4",gi,d(u.$t("fontConfig.customFonts")),1),s("div",ti,[s("label",Ii,d(u.$t("fontConfig.fontFile")),1),s("div",{onDrop:a,onDragover:l[4]||(l[4]=PA(()=>{},["prevent"])),onDragenter:l[5]||(l[5]=PA(()=>{},["prevent"])),class:"border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:border-gray-400 transition-colors"},[s("input",{ref_key:"fileInput",ref:o,type:"file",accept:".ttf,.woff,.woff2",onChange:Q,class:"hidden"},null,544),e.modelValue.custom.file?(G(),U("div",ni,[l[13]||(l[13]=s("svg",{class:"mx-auto h-8 w-8",fill:"currentColor",viewBox:"0 0 20 20"},[s("path",{"fill-rule":"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z","clip-rule":"evenodd"})],-1)),s("p",Bi,d((f=e.modelValue.custom.file)==null?void 0:f.name),1),s("button",{onClick:h,class:"text-red-600 hover:text-red-500 text-sm mt-1"},d(u.$t("fontConfig.removeFile")),1)])):(G(),U("div",oi,[l[12]||(l[12]=s("svg",{class:"mx-auto h-12 w-12 text-gray-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor"},[s("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"})],-1)),s("div",ii,[s("button",{onClick:l[3]||(l[3]=c=>u.$refs.fileInput.click()),class:"text-primary-600 hover:text-primary-500 font-medium"},d(u.$t("fontConfig.clickSelectFontFile")),1),s("p",ri,d(u.$t("fontConfig.orDragFileHere")),1)]),s("p",Ci,d(u.$t("fontConfig.supportedFormats")),1)]))],32)]),e.modelValue.custom.file?(G(),U("div",si,[s("div",null,[s("label",ai,d(u.$t("fontConfig.fontSizePx")),1),rA(s("input",{type:"number","onUpdate:modelValue":l[6]||(l[6]=c=>C.value.size=c),min:"8",max:"80",class:"w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-primary-500"},null,512),[[aA,C.value.size,void 0,{number:!0}]]),s("p",Qi,d(u.$t("fontConfig.range"))+" 8-80px",1)]),s("div",null,[s("label",Ei,d(u.$t("fontConfig.bitDepthBpp")),1),rA(s("select",{"onUpdate:modelValue":l[7]||(l[7]=c=>C.value.bpp=c),class:"w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-primary-500"},[s("option",li,d(u.$t("fontConfig.monochrome")),1),s("option",ci,d(u.$t("fontConfig.fourColors")),1),s("option",hi,d(u.$t("fontConfig.sixteenColors")),1)],512),[[Xe,C.value.bpp]])]),s("div",null,[s("label",ui,d(u.$t("fontConfig.characterSet")),1),rA(s("select",{"onUpdate:modelValue":l[8]||(l[8]=c=>C.value.charset=c),class:"w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-primary-500"},[s("option",di,d(u.$t("fontConfig.qwen18409")),1),s("option",fi,d(u.$t("fontConfig.deepseekR1")),1),s("option",wi,d(u.$t("fontConfig.latin1")),1),s("option",yi,d(u.$t("fontConfig.fullCharset")),1)],512),[[Xe,C.value.charset]])])])):O("",!0)])):O("",!0),s("div",pi,[s("div",Di,[s("h4",mi,d(u.$t("fontConfig.hideSubtitle")),1),s("p",Fi,d(u.$t("fontConfig.hideSubtitleDescription")),1)]),s("div",ki,[s("label",vi,[s("input",{type:"checkbox",checked:e.modelValue.hide_subtitle,onChange:l[9]||(l[9]=c=>I("update:modelValue",{...e.modelValue,hide_subtitle:c.target.checked})),class:"sr-only peer"},null,40,Si),l[14]||(l[14]=s("div",{class:"w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-primary-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary-500"},null,-1))])])])])}}},Ri={class:"space-y-6"},Ui={class:"text-lg font-medium text-gray-900 mb-2"},Ni={class:"text-gray-600"},bi={class:"space-y-4"},Li={class:"flex flex-wrap gap-3"},Mi={key:0,class:"text-sm text-gray-500"},Ji={key:0,class:"space-y-4"},xi={class:"font-medium text-gray-900"},Hi={class:"grid grid-cols-1 md:grid-cols-2 gap-6"},Yi=["onClick"],Ki={class:"flex items-start justify-between mb-3"},Ti={class:"font-medium text-gray-900"},Vi={class:"text-sm text-gray-600"},qi={class:"text-xs text-gray-500 mt-1"},Oi={key:0,class:"flex-shrink-0 ml-3"},Wi={class:"grid grid-cols-7 gap-1 justify-items-center overflow-hidden"},Pi=["src","alt"],Zi={key:1,class:"space-y-6"},Xi={class:"font-medium text-gray-900"},ji={class:"grid grid-cols-1 md:grid-cols-2 gap-4"},zi={class:"block text-sm font-medium text-gray-700 mb-2"},_i={class:"block text-sm font-medium text-gray-700 mb-2"},$i={class:"space-y-4"},Ar={class:"font-medium text-gray-900"},er={class:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-4"},gr={class:"text-center"},tr={class:"text-lg mb-1"},Ir={class:"text-xs text-gray-600 flex items-center justify-center gap-1"},or={key:0,class:"text-red-500"},ir=["onDrop"],rr=["onChange"],Cr=["onClick"],nr={class:"text-xs text-gray-500"},Br={key:1,class:"w-full h-full relative"},sr=["src","alt"],ar=["onClick"],Qr={class:"text-xs text-gray-500 mt-2"},Er={__name:"EmojiConfig",props:{modelValue:{type:Object,required:!0}},emits:["update:modelValue"],setup(e,{emit:A}){const{t:g}=TA(),t=e,I=A,o=async f=>{const c=await f.arrayBuffer(),D=await crypto.subtle.digest("SHA-256",c);return Array.from(new Uint8Array(D)).map(N=>N.toString(16).padStart(2,"0")).join("")},i=[{id:"twemoji32",name:g("emojiConfig.twitterEmojiName",{size:32}),description:g("emojiConfig.twitterEmojiDescription",{size:32}),size:32,format:"png",preview:["neutral","happy","laughing","funny","sad","angry","crying"]},{id:"twemoji64",name:g("emojiConfig.twitterEmojiName",{size:64}),description:g("emojiConfig.twitterEmojiDescription",{size:64}),size:64,format:"png",preview:["neutral","happy","laughing","funny","sad","angry","crying"]},{id:"noto-emoji_64",name:g("emojiConfig.notoEmojiName",{size:64}),description:g("emojiConfig.notoEmojiDescription",{size:64}),size:64,format:"gif",preview:["neutral","happy","laughing","funny","sad","angry","crying"]},{id:"noto-emoji_128",name:g("emojiConfig.notoEmojiName",{size:128}),description:g("emojiConfig.notoEmojiDescription",{size:128}),size:128,format:"gif",preview:["neutral","happy","laughing","funny","sad","angry","crying"]}],r=nA(()=>[{key:"neutral",name:g("emojiConfig.emotions.neutral"),emoji:"😶"},{key:"happy",name:g("emojiConfig.emotions.happy"),emoji:"🙂"},{key:"laughing",name:g("emojiConfig.emotions.laughing"),emoji:"😆"},{key:"funny",name:g("emojiConfig.emotions.funny"),emoji:"😂"},{key:"sad",name:g("emojiConfig.emotions.sad"),emoji:"😔"},{key:"angry",name:g("emojiConfig.emotions.angry"),emoji:"😠"},{key:"crying",name:g("emojiConfig.emotions.crying"),emoji:"😭"},{key:"loving",name:g("emojiConfig.emotions.loving"),emoji:"😍"},{key:"embarrassed",name:g("emojiConfig.emotions.embarrassed"),emoji:"😳"},{key:"surprised",name:g("emojiConfig.emotions.surprised"),emoji:"😯"},{key:"shocked",name:g("emojiConfig.emotions.shocked"),emoji:"😱"},{key:"thinking",name:g("emojiConfig.emotions.thinking"),emoji:"🤔"},{key:"winking",name:g("emojiConfig.emotions.winking"),emoji:"😉"},{key:"cool",name:g("emojiConfig.emotions.cool"),emoji:"😎"},{key:"relaxed",name:g("emojiConfig.emotions.relaxed"),emoji:"😌"},{key:"delicious",name:g("emojiConfig.emotions.delicious"),emoji:"🤤"},{key:"kissy",name:g("emojiConfig.emotions.kissy"),emoji:"😘"},{key:"confident",name:g("emojiConfig.emotions.confident"),emoji:"😏"},{key:"sleepy",name:g("emojiConfig.emotions.sleepy"),emoji:"😴"},{key:"silly",name:g("emojiConfig.emotions.silly"),emoji:"😜"},{key:"confused",name:g("emojiConfig.emotions.confused"),emoji:"🙄"}]),C=j({size:{width:32,height:32}}),B=f=>{if(t.modelValue.type===f)return;const c={...t.modelValue,type:f};f==="none"?(c.preset="",c.custom={...t.modelValue.custom,images:t.modelValue.custom.images||{}}):f==="preset"?(c.preset=t.modelValue.preset||"twemoji32",c.custom={...t.modelValue.custom,images:t.modelValue.custom.images||{}}):f==="custom"&&(c.preset="",c.custom={...t.modelValue.custom,images:t.modelValue.custom.images||{}}),I("update:modelValue",c)},n=f=>{t.modelValue.preset!==f&&I("update:modelValue",{...t.modelValue,preset:f,custom:{...t.modelValue.custom,images:t.modelValue.custom.images||{}}})},Q=(f,c)=>{const D=f.target.files[0];D&&E(c,D)},a=(f,c)=>{f.preventDefault();const D=f.dataTransfer.files;D.length>0&&E(c,D[0])},E=async(f,c)=>{const D=["png","gif"],y=c.name.split(".").pop().toLowerCase();if(!D.includes(y)){alert(g("emojiConfig.selectValidFormat"));return}const v=await o(c),N=t.modelValue.custom||{},L={...N.fileMap||{}},X={...N.emotionMap||{}},k={...N.images||{}};let m=[];for(const[M,oA]of Object.entries(X))oA===v&&M!==f&&m.push(M);m.length>0&&console.log(g("emojiConfig.sharedFileMessage",{emotionKey:f,existingEmotions:m.join(", ")})),L[v]=c,X[f]=v,k[f]=c,I("update:modelValue",{...t.modelValue,custom:{...N,size:C.value.size,images:k,fileMap:L,emotionMap:X}}),await Ie.saveEmojiFile(`hash_${v}`,c,{size:C.value.size,format:y,emotions:[...m,f]})},h=async f=>{const c=t.modelValue.custom||{},D={...c.images},y={...c.emotionMap||{}},v={...c.fileMap||{}},N=y[f];delete D[f],delete y[f],Object.values(y).filter(X=>X===N).length===0&&N?(delete v[N],await Ie.deleteEmojiFile(`hash_${N}`),console.log(g("emojiConfig.fileDeleted",{fileHash:N}))):console.log(g("emojiConfig.fileRetained",{fileHash:N})),I("update:modelValue",{...t.modelValue,custom:{...c,images:D,emotionMap:y,fileMap:v}})},w=(f,c)=>{const D=i.find(v=>v.id===f),y=(D==null?void 0:D.format)||"png";return`./static/emojis/${f}/${c}.${y}`},u=f=>{if(t.modelValue.type==="preset")return w(t.modelValue.preset,f);{const c=t.modelValue.custom.images[f];return c instanceof File||c instanceof Blob?URL.createObjectURL(c):null}},l=f=>{console.warn(g("emojiConfig.imageLoadFailed"),f.target.src),f.target.style.display="none"};return DA(()=>C.value.size,f=>{if(t.modelValue.type==="custom"){const c=t.modelValue.custom;JSON.stringify(c.size)!==JSON.stringify(f)&&I("update:modelValue",{...t.modelValue,custom:{...c,size:f}})}},{deep:!0}),t.modelValue.custom.size&&(C.value={size:{...t.modelValue.custom.size}}),(f,c)=>(G(),U("div",Ri,[s("div",null,[s("h3",Ui,d(f.$t("emojiConfig.title")),1),s("p",Ni,d(f.$t("emojiConfig.description")),1)]),s("div",bi,[s("div",Li,[s("button",{onClick:c[0]||(c[0]=D=>B("none")),class:gA(["px-4 py-2 border rounded-lg transition-colors",e.modelValue.type==="none"?"border-primary-500 bg-primary-50 text-primary-700":"border-gray-300 hover:border-gray-400"])},d(f.$t("emojiConfig.noEmojiPack")),3),s("button",{onClick:c[1]||(c[1]=D=>B("preset")),class:gA(["px-4 py-2 border rounded-lg transition-colors",e.modelValue.type==="preset"?"border-primary-500 bg-primary-50 text-primary-700":"border-gray-300 hover:border-gray-400"])},d(f.$t("emojiConfig.presetEmojiPack")),3),s("button",{onClick:c[2]||(c[2]=D=>B("custom")),class:gA(["px-4 py-2 border rounded-lg transition-colors",e.modelValue.type==="custom"?"border-primary-500 bg-primary-50 text-primary-700":"border-gray-300 hover:border-gray-400"])},d(f.$t("emojiConfig.customEmojiPack")),3)]),e.modelValue.type==="none"?(G(),U("p",Mi,d(f.$t("emojiConfig.noEmojiPackDescription")),1)):O("",!0)]),e.modelValue.type==="preset"?(G(),U("div",Ji,[s("h4",xi,d(f.$t("emojiConfig.selectPresetEmojiPack")),1),s("div",Hi,[(G(),U(bA,null,LA(i,D=>s("div",{key:D.id,onClick:y=>n(D.id),class:gA(["border-2 rounded-lg p-4 cursor-pointer transition-all",e.modelValue.preset===D.id?"border-primary-500 bg-primary-50":"border-gray-200 hover:border-gray-300"])},[s("div",Ki,[s("div",null,[s("h5",Ti,d(D.name),1),s("p",Vi,d(D.description),1),s("div",qi,d(f.$t("emojiConfig.size"))+": "+d(D.size)+"px × "+d(D.size)+"px ",1)]),e.modelValue.preset===D.id?(G(),U("div",Oi,[...c[7]||(c[7]=[s("div",{class:"w-5 h-5 bg-primary-500 rounded-full flex items-center justify-center"},[s("svg",{class:"w-3 h-3 text-white",fill:"currentColor",viewBox:"0 0 20 20"},[s("path",{"fill-rule":"evenodd",d:"M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z","clip-rule":"evenodd"})])],-1)])])):O("",!0)]),s("div",Wi,[(G(!0),U(bA,null,LA(D.preview,y=>(G(),U("div",{key:y,style:CA({width:D.size+"px",height:D.size+"px"}),class:"bg-gray-100 rounded flex items-center justify-center"},[s("img",{src:w(D.id,y),alt:y,style:CA({width:D.size+"px",height:D.size+"px"}),class:"object-contain rounded",onError:l},null,44,Pi)],4))),128))])],10,Yi)),64))])])):O("",!0),e.modelValue.type==="custom"?(G(),U("div",Zi,[s("h4",Xi,d(f.$t("emojiConfig.customEmojiPackConfig")),1),s("div",ji,[s("div",null,[s("label",zi,d(f.$t("emojiConfig.maxImageWidth")),1),rA(s("input",{type:"number","onUpdate:modelValue":c[3]||(c[3]=D=>C.value.size.width=D),min:"16",max:"200",class:"w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-primary-500"},null,512),[[aA,C.value.size.width,void 0,{number:!0}]])]),s("div",null,[s("label",_i,d(f.$t("emojiConfig.maxImageHeight")),1),rA(s("input",{type:"number","onUpdate:modelValue":c[4]||(c[4]=D=>C.value.size.height=D),min:"16",max:"200",class:"w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-primary-500"},null,512),[[aA,C.value.size.height,void 0,{number:!0}]])])]),s("div",$i,[s("h5",Ar,d(f.$t("emojiConfig.uploadEmojiImages")),1),s("div",er,[(G(!0),U(bA,null,LA(r.value,D=>(G(),U("div",{key:D.key,class:"space-y-2"},[s("div",gr,[s("div",tr,d(D.emoji),1),s("div",Ir,[s("span",null,d(D.name),1),D.key==="neutral"?(G(),U("span",or,d(f.$t("emojiConfig.required")),1)):O("",!0)])]),s("div",{onDrop:y=>a(y,D.key),onDragover:c[5]||(c[5]=PA(()=>{},["prevent"])),onDragenter:c[6]||(c[6]=PA(()=>{},["prevent"])),class:gA(["border-2 border-dashed rounded-lg p-2 text-center cursor-pointer transition-colors aspect-square flex flex-col items-center justify-center",e.modelValue.custom.images[D.key]?"border-green-300 bg-green-50":D.key==="neutral"?"border-red-300 bg-red-50":"border-gray-300 hover:border-gray-400"])},[s("input",{ref_for:!0,ref:D.key+"Input",type:"file",accept:".png,.gif",onChange:y=>Q(y,D.key),class:"hidden"},null,40,rr),e.modelValue.custom.images[D.key]?(G(),U("div",Br,[u(D.key)?(G(),U("img",{key:0,src:u(D.key),alt:D.name,class:"w-full h-full object-cover rounded",onError:l},null,40,sr)):O("",!0),s("button",{onClick:y=>h(D.key),class:"absolute -top-1 -right-1 w-4 h-4 bg-red-500 text-white rounded-full flex items-center justify-center text-xs hover:bg-red-600"}," × ",8,ar)])):(G(),U("div",{key:0,onClick:y=>{var v;return(v=f.$refs[D.key+"Input"][0])==null?void 0:v.click()}},[c[8]||(c[8]=s("svg",{class:"w-6 h-6 text-gray-400 mx-auto mb-1",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor"},[s("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M12 6v6m0 0v6m0-6h6m-6 0H6"})],-1)),s("div",nr,d(f.$t("emojiConfig.clickToUploadOrDrag")),1)],8,Cr))],42,ir)]))),128))]),s("div",Qr,d(f.$t("emojiConfig.neutralRequiredNotice")),1)])])):O("",!0)]))}},lr={class:"space-y-6"},cr={class:"text-lg font-medium text-gray-900 mb-2"},hr={class:"text-gray-600"},ur={class:"space-y-4"},dr={class:"font-medium text-gray-900 flex items-center"},fr={class:"border border-gray-200 rounded-lg p-4 space-y-4"},wr={class:"flex space-x-4"},yr={key:0,class:"space-y-3"},pr={class:"flex items-center space-x-3"},Dr={class:"text-sm font-medium text-gray-700"},mr={class:"flex items-center space-x-2"},Fr={class:"flex items-center space-x-3"},kr={class:"text-sm font-medium text-gray-700"},vr={class:"flex items-center space-x-2"},Sr={key:1,class:"space-y-3"},Gr={class:"text-sm font-medium text-gray-700"},Rr={class:"mt-1 text-sm text-gray-600"},Ur={key:1,class:"space-y-2"},Nr=["src"],br={class:"text-sm text-green-700 font-medium"},Lr={class:"flex items-center space-x-3"},Mr={class:"text-sm font-medium text-gray-700"},Jr={class:"flex items-center space-x-2"},xr={class:"space-y-4"},Hr={class:"font-medium text-gray-900 flex items-center"},Yr={class:"border border-gray-200 rounded-lg p-4 space-y-4"},Kr={class:"flex space-x-4"},Tr={key:0,class:"space-y-3"},Vr={class:"flex items-center space-x-3"},qr={class:"text-sm font-medium text-gray-700"},Or={class:"flex items-center space-x-2"},Wr={class:"flex items-center space-x-3"},Pr={class:"text-sm font-medium text-gray-700"},Zr={class:"flex items-center space-x-2"},Xr={key:1,class:"space-y-3"},jr={class:"text-sm font-medium text-gray-700"},zr={class:"mt-1 text-sm text-gray-600"},_r={key:1,class:"space-y-2"},$r=["src"],AC={class:"text-sm text-green-700 font-medium"},eC={class:"flex items-center space-x-3"},gC={class:"text-sm font-medium text-gray-700"},tC={class:"flex items-center space-x-2"},IC={class:"space-y-4"},oC={class:"font-medium text-gray-900"},iC={class:"grid grid-cols-1 md:grid-cols-2 gap-4"},rC={class:"space-y-2"},CC={class:"text-sm font-medium text-gray-700"},nC={class:"absolute inset-0 bg-white bg-opacity-10 flex items-center justify-center rounded-lg"},BC={class:"space-y-2"},sC={class:"text-sm font-medium text-gray-700"},aC={class:"absolute inset-0 bg-black bg-opacity-10 flex items-center justify-center rounded-lg"},QC={class:"bg-blue-50 border border-blue-200 rounded-lg p-4"},EC={class:"font-medium text-blue-900 mb-2"},lC={class:"flex flex-wrap gap-2"},cC={__name:"BackgroundConfig",props:{modelValue:{type:Object,required:!0}},emits:["update:modelValue"],setup(e,{emit:A}){const{t:g}=TA(),t=e,I=A,o=j(null),i=j(null),r=nA({get:()=>t.modelValue.light.backgroundColor,set:k=>E(k)}),C=nA({get:()=>t.modelValue.dark.backgroundColor,set:k=>h(k)}),B=nA({get:()=>t.modelValue.light.textColor,set:k=>w(k)}),n=nA({get:()=>t.modelValue.dark.textColor,set:k=>u(k)}),Q=k=>{I("update:modelValue",{...t.modelValue,light:{...t.modelValue.light,backgroundType:k,backgroundImage:k==="image"?t.modelValue.light.backgroundImage:null}})},a=k=>{I("update:modelValue",{...t.modelValue,dark:{...t.modelValue.dark,backgroundType:k,backgroundImage:k==="image"?t.modelValue.dark.backgroundImage:null}})},E=k=>{I("update:modelValue",{...t.modelValue,light:{...t.modelValue.light,backgroundColor:k}})},h=k=>{I("update:modelValue",{...t.modelValue,dark:{...t.modelValue.dark,backgroundColor:k}})},w=k=>{I("update:modelValue",{...t.modelValue,light:{...t.modelValue.light,textColor:k}})},u=k=>{I("update:modelValue",{...t.modelValue,dark:{...t.modelValue.dark,textColor:k}})},l=(k,m)=>{const M=k.target.files[0];M&&c(m,M)},f=(k,m)=>{k.preventDefault();const M=k.dataTransfer.files;M.length>0&&c(m,M[0])},c=async(k,m)=>{m&&m.type.startsWith("image/")?(I("update:modelValue",{...t.modelValue,[k]:{...t.modelValue[k],backgroundImage:m}}),await Ie.saveBackgroundFile(k,m)):alert(g("backgroundConfig.selectValidImage"))},D=async k=>{I("update:modelValue",{...t.modelValue,[k]:{...t.modelValue[k],backgroundImage:null}}),k==="light"&&o.value&&(o.value.value=""),k==="dark"&&i.value&&(i.value.value=""),await Ie.deleteBackgroundFile(k)},y=k=>{const m=t.modelValue[k].backgroundImage;return m?URL.createObjectURL(m):null},v=()=>t.modelValue.light.backgroundType==="image"&&t.modelValue.light.backgroundImage?{backgroundImage:`url(${y("light")})`,backgroundSize:"cover",backgroundPosition:"center"}:{backgroundColor:t.modelValue.light.backgroundColor},N=()=>t.modelValue.dark.backgroundType==="image"&&t.modelValue.dark.backgroundImage?{backgroundImage:`url(${y("dark")})`,backgroundSize:"cover",backgroundPosition:"center"}:{backgroundColor:t.modelValue.dark.backgroundColor},L=(k,m)=>{const M=X(k)?"#000000":"#ffffff",oA=X(m)?"#000000":"#ffffff";I("update:modelValue",{...t.modelValue,light:{...t.modelValue.light,backgroundType:"color",backgroundColor:k,textColor:M,backgroundImage:null},dark:{...t.modelValue.dark,backgroundType:"color",backgroundColor:m,textColor:oA,backgroundImage:null}})},X=k=>{const m=k.replace("#",""),M=parseInt(m.substr(0,2),16),oA=parseInt(m.substr(2,2),16),F=parseInt(m.substr(4,2),16);return(M*299+oA*587+F*114)/1e3>128};return(k,m)=>(G(),U("div",lr,[s("div",null,[s("h3",cr,d(k.$t("backgroundConfig.title")),1),s("p",hr,d(k.$t("backgroundConfig.description")),1)]),s("div",ur,[s("h4",dr,[m[33]||(m[33]=s("svg",{class:"w-5 h-5 mr-2 text-yellow-500",fill:"currentColor",viewBox:"0 0 20 20"},[s("path",{"fill-rule":"evenodd",d:"M10 2a1 1 0 011 1v1a1 1 0 11-2 0V3a1 1 0 011-1zm4 8a4 4 0 11-8 0 4 4 0 018 0zm-.464 4.95l.707.707a1 1 0 001.414-1.414l-.707-.707a1 1 0 00-1.414 1.414zm2.12-10.607a1 1 0 010 1.414l-.706.707a1 1 0 11-1.414-1.414l.707-.707a1 1 0 011.414 0zM17 11a1 1 0 100-2h-1a1 1 0 100 2h1zm-7 4a1 1 0 011 1v1a1 1 0 11-2 0v-1a1 1 0 011-1zM5.05 6.464A1 1 0 106.465 5.05l-.708-.707a1 1 0 00-1.414 1.414l.707.707zm1.414 8.486l-.707.707a1 1 0 01-1.414-1.414l.707-.707a1 1 0 011.414 1.414zM4 11a1 1 0 100-2H3a1 1 0 000 2h1z","clip-rule":"evenodd"})],-1)),HA(" "+d(k.$t("backgroundConfig.lightMode")),1)]),s("div",fr,[s("div",wr,[s("button",{onClick:m[0]||(m[0]=M=>Q("color")),class:gA(["px-3 py-2 text-sm border rounded transition-colors",e.modelValue.light.backgroundType==="color"?"border-primary-500 bg-primary-50 text-primary-700":"border-gray-300 hover:border-gray-400"])},d(k.$t("backgroundConfig.solidBackground")),3),s("button",{onClick:m[1]||(m[1]=M=>Q("image")),class:gA(["px-3 py-2 text-sm border rounded transition-colors",e.modelValue.light.backgroundType==="image"?"border-primary-500 bg-primary-50 text-primary-700":"border-gray-300 hover:border-gray-400"])},d(k.$t("backgroundConfig.imageBackground")),3)]),e.modelValue.light.backgroundType==="color"?(G(),U("div",yr,[s("div",pr,[s("label",Dr,d(k.$t("backgroundConfig.backgroundColor")),1),s("div",mr,[rA(s("input",{type:"color","onUpdate:modelValue":m[2]||(m[2]=M=>r.value=M),class:"w-10 h-10 border border-gray-300 rounded cursor-pointer"},null,512),[[aA,r.value]]),rA(s("input",{type:"text","onUpdate:modelValue":m[3]||(m[3]=M=>r.value=M),class:"border border-gray-300 rounded px-3 py-2 text-sm font-mono w-24"},null,512),[[aA,r.value]])]),s("div",{style:CA({backgroundColor:r.value}),class:"w-16 h-10 border border-gray-300 rounded shadow-inner"},null,4)]),s("div",Fr,[s("label",kr,d(k.$t("backgroundConfig.textColor")),1),s("div",vr,[rA(s("input",{type:"color","onUpdate:modelValue":m[4]||(m[4]=M=>B.value=M),class:"w-10 h-10 border border-gray-300 rounded cursor-pointer"},null,512),[[aA,B.value]]),rA(s("input",{type:"text","onUpdate:modelValue":m[5]||(m[5]=M=>B.value=M),class:"border border-gray-300 rounded px-3 py-2 text-sm font-mono w-24"},null,512),[[aA,B.value]])]),s("div",{style:CA({backgroundColor:B.value}),class:"w-16 h-10 border border-gray-300 rounded shadow-inner"},null,4)])])):O("",!0),e.modelValue.light.backgroundType==="image"?(G(),U("div",Sr,[s("label",Gr,d(k.$t("backgroundConfig.backgroundImage")),1),s("div",{onDrop:m[9]||(m[9]=M=>f(M,"light")),onDragover:m[10]||(m[10]=PA(()=>{},["prevent"])),onDragenter:m[11]||(m[11]=PA(()=>{},["prevent"])),class:gA(["border-2 border-dashed rounded-lg p-4 text-center cursor-pointer transition-colors",e.modelValue.light.backgroundImage?"border-green-300 bg-green-50":"border-gray-300 hover:border-gray-400"])},[s("input",{ref_key:"lightImageInput",ref:o,type:"file",accept:"image/*",onChange:m[6]||(m[6]=M=>l(M,"light")),class:"hidden"},null,544),e.modelValue.light.backgroundImage?(G(),U("div",Ur,[s("img",{src:y("light"),alt:"{{ $t('backgroundConfig.lightModePreview') }}背景",class:"max-w-32 max-h-32 mx-auto rounded shadow"},null,8,Nr),s("p",br,d(e.modelValue.light.backgroundImage.name),1),s("button",{onClick:m[8]||(m[8]=M=>D("light")),class:"text-red-600 hover:text-red-500 text-sm"},d(k.$t("backgroundConfig.removeImage")),1)])):(G(),U("div",{key:0,onClick:m[7]||(m[7]=M=>k.$refs.lightImageInput.click())},[m[34]||(m[34]=s("svg",{class:"mx-auto h-8 w-8 text-gray-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor"},[s("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})],-1)),s("p",Rr,d(k.$t("backgroundConfig.clickOrDragToUpload")),1)]))],34),s("div",Lr,[s("label",Mr,d(k.$t("backgroundConfig.textColor")),1),s("div",Jr,[rA(s("input",{type:"color","onUpdate:modelValue":m[12]||(m[12]=M=>B.value=M),class:"w-10 h-10 border border-gray-300 rounded cursor-pointer"},null,512),[[aA,B.value]]),rA(s("input",{type:"text","onUpdate:modelValue":m[13]||(m[13]=M=>B.value=M),class:"border border-gray-300 rounded px-3 py-2 text-sm font-mono w-24"},null,512),[[aA,B.value]])]),s("div",{style:CA({backgroundColor:B.value}),class:"w-16 h-10 border border-gray-300 rounded shadow-inner"},null,4)])])):O("",!0)])]),s("div",xr,[s("h4",Hr,[m[35]||(m[35]=s("svg",{class:"w-5 h-5 mr-2 text-gray-600",fill:"currentColor",viewBox:"0 0 20 20"},[s("path",{d:"M17.293 13.293A8 8 0 016.707 2.707a8.001 8.001 0 1010.586 10.586z"})],-1)),HA(" "+d(k.$t("backgroundConfig.darkMode")),1)]),s("div",Yr,[s("div",Kr,[s("button",{onClick:m[14]||(m[14]=M=>a("color")),class:gA(["px-3 py-2 text-sm border rounded transition-colors",e.modelValue.dark.backgroundType==="color"?"border-primary-500 bg-primary-50 text-primary-700":"border-gray-300 hover:border-gray-400"])},d(k.$t("backgroundConfig.solidBackground")),3),s("button",{onClick:m[15]||(m[15]=M=>a("image")),class:gA(["px-3 py-2 text-sm border rounded transition-colors",e.modelValue.dark.backgroundType==="image"?"border-primary-500 bg-primary-50 text-primary-700":"border-gray-300 hover:border-gray-400"])},d(k.$t("backgroundConfig.imageBackground")),3)]),e.modelValue.dark.backgroundType==="color"?(G(),U("div",Tr,[s("div",Vr,[s("label",qr,d(k.$t("backgroundConfig.backgroundColor")),1),s("div",Or,[rA(s("input",{type:"color","onUpdate:modelValue":m[16]||(m[16]=M=>C.value=M),class:"w-10 h-10 border border-gray-300 rounded cursor-pointer"},null,512),[[aA,C.value]]),rA(s("input",{type:"text","onUpdate:modelValue":m[17]||(m[17]=M=>C.value=M),class:"border border-gray-300 rounded px-3 py-2 text-sm font-mono w-24"},null,512),[[aA,C.value]])]),s("div",{style:CA({backgroundColor:C.value}),class:"w-16 h-10 border border-gray-300 rounded shadow-inner"},null,4)]),s("div",Wr,[s("label",Pr,d(k.$t("backgroundConfig.textColor")),1),s("div",Zr,[rA(s("input",{type:"color","onUpdate:modelValue":m[18]||(m[18]=M=>n.value=M),class:"w-10 h-10 border border-gray-300 rounded cursor-pointer"},null,512),[[aA,n.value]]),rA(s("input",{type:"text","onUpdate:modelValue":m[19]||(m[19]=M=>n.value=M),class:"border border-gray-300 rounded px-3 py-2 text-sm font-mono w-24"},null,512),[[aA,n.value]])]),s("div",{style:CA({backgroundColor:n.value}),class:"w-16 h-10 border border-gray-300 rounded shadow-inner"},null,4)])])):O("",!0),e.modelValue.dark.backgroundType==="image"?(G(),U("div",Xr,[s("label",jr,d(k.$t("backgroundConfig.backgroundImage")),1),s("div",{onDrop:m[23]||(m[23]=M=>f(M,"dark")),onDragover:m[24]||(m[24]=PA(()=>{},["prevent"])),onDragenter:m[25]||(m[25]=PA(()=>{},["prevent"])),class:gA(["border-2 border-dashed rounded-lg p-4 text-center cursor-pointer transition-colors",e.modelValue.dark.backgroundImage?"border-green-300 bg-green-50":"border-gray-300 hover:border-gray-400"])},[s("input",{ref_key:"darkImageInput",ref:i,type:"file",accept:"image/*",onChange:m[20]||(m[20]=M=>l(M,"dark")),class:"hidden"},null,544),e.modelValue.dark.backgroundImage?(G(),U("div",_r,[s("img",{src:y("dark"),alt:"{{ $t('backgroundConfig.darkModePreview') }}背景",class:"max-w-32 max-h-32 mx-auto rounded shadow"},null,8,$r),s("p",AC,d(e.modelValue.dark.backgroundImage.name),1),s("button",{onClick:m[22]||(m[22]=M=>D("dark")),class:"text-red-600 hover:text-red-500 text-sm"},d(k.$t("backgroundConfig.removeImage")),1)])):(G(),U("div",{key:0,onClick:m[21]||(m[21]=M=>k.$refs.darkImageInput.click())},[m[36]||(m[36]=s("svg",{class:"mx-auto h-8 w-8 text-gray-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor"},[s("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})],-1)),s("p",zr,d(k.$t("backgroundConfig.clickOrDragToUpload")),1)]))],34),s("div",eC,[s("label",gC,d(k.$t("backgroundConfig.textColor")),1),s("div",tC,[rA(s("input",{type:"color","onUpdate:modelValue":m[26]||(m[26]=M=>n.value=M),class:"w-10 h-10 border border-gray-300 rounded cursor-pointer"},null,512),[[aA,n.value]]),rA(s("input",{type:"text","onUpdate:modelValue":m[27]||(m[27]=M=>n.value=M),class:"border border-gray-300 rounded px-3 py-2 text-sm font-mono w-24"},null,512),[[aA,n.value]])]),s("div",{style:CA({backgroundColor:n.value}),class:"w-16 h-10 border border-gray-300 rounded shadow-inner"},null,4)])])):O("",!0)])]),s("div",IC,[s("h4",oC,d(k.$t("backgroundConfig.backgroundPreview")),1),s("div",iC,[s("div",rC,[s("div",CC,d(k.$t("backgroundConfig.lightModePreview")),1),s("div",{style:CA(v()),class:"h-32 border border-gray-300 rounded-lg flex items-center justify-center text-sm relative overflow-hidden"},[s("div",nC,[s("span",{style:CA({color:e.modelValue.light.textColor})},d(k.$t("backgroundConfig.chatArea")),5)])],4)]),s("div",BC,[s("div",sC,d(k.$t("backgroundConfig.darkModePreview")),1),s("div",{style:CA(N()),class:"h-32 border border-gray-300 rounded-lg flex items-center justify-center text-sm relative overflow-hidden"},[s("div",aC,[s("span",{style:CA({color:e.modelValue.dark.textColor})},d(k.$t("backgroundConfig.chatArea")),5)])],4)])])]),s("div",QC,[s("h5",EC,d(k.$t("backgroundConfig.quickConfig")),1),s("div",lC,[s("button",{onClick:m[28]||(m[28]=M=>L("#ffffff","#1f2937")),class:"px-3 py-1 text-sm bg-white border border-gray-300 rounded hover:bg-gray-50"},d(k.$t("backgroundConfig.defaultColors")),1),s("button",{onClick:m[29]||(m[29]=M=>L("#f5f5f4","#374151")),class:"px-3 py-1 text-sm bg-stone-100 border border-gray-300 rounded hover:bg-stone-200"},d(k.$t("backgroundConfig.stoneTexture")),1),s("button",{onClick:m[30]||(m[30]=M=>L("#fef7cd","#7c2d12")),class:"px-3 py-1 text-sm bg-yellow-100 border border-gray-300 rounded hover:bg-yellow-200"},d(k.$t("backgroundConfig.sunnyColors")),1),s("button",{onClick:m[31]||(m[31]=M=>L("#e0f2fe","#1e40af")),class:"px-3 py-1 text-sm bg-sky-100 border border-gray-300 rounded hover:bg-sky-200"},d(k.$t("backgroundConfig.skyBlue")),1),s("button",{onClick:m[32]||(m[32]=M=>L("#fdf2f8","#be185d")),class:"px-3 py-1 text-sm bg-pink-100 border border-gray-300 rounded hover:bg-pink-200"},d(k.$t("backgroundConfig.romanticPink")),1)])])]))}},hC={class:"space-y-6"},uC={class:"text-xl font-semibold text-gray-900 mb-4"},dC={class:"text-gray-600 mb-6"},fC={class:"border-b border-gray-200"},wC={class:"-mb-px flex space-x-4 sm:space-x-8"},yC=["onClick"],pC={class:"flex items-center"},DC={class:"hidden sm:inline"},mC={class:"min-h-96"},FC={class:"flex justify-between"},kC={__name:"ThemeDesign",props:{modelValue:{type:Object,required:!0},chipModel:{type:String,required:!0},activeTab:{type:String,default:"wakeword"}},emits:["update:modelValue","next","prev","tabChange"],setup(e,{emit:A}){const{t:g}=TA(),t={render(){return eA("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},[eA("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4m-4-8a3 3 0 01-3-3V5a3 3 0 116 0v6a3 3 0 01-3 3z"})])}},I={render(){return eA("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"currentColor",viewBox:"0 0 640 640"},[eA("path",{d:"M320 96C329.5 96 338 101.5 341.9 110.2L515.1 496L536 496C549.3 496 560 506.7 560 520C560 533.3 549.3 544 536 544L440 544C426.7 544 416 533.3 416 520C416 506.7 426.7 496 440 496L462.5 496L426.6 416L213.4 416L177.5 496L200 496C213.3 496 224 506.7 224 520C224 533.3 213.3 544 200 544L104 544C90.7 544 80 533.3 80 520C80 506.7 90.7 496 104 496L124.9 496L298.1 110.2C302 101.5 310.5 96 320 96zM320 178.6L235 368L405 368L320 178.6z"})])}},o={render(){return eA("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},[eA("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M14.828 14.828a4 4 0 01-5.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})])}},i={render(){return eA("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"currentColor",viewBox:"0 0 640 640"},[eA("path",{d:"M160 144C151.2 144 144 151.2 144 160L144 480C144 488.8 151.2 496 160 496L480 496C488.8 496 496 488.8 496 480L496 160C496 151.2 488.8 144 480 144L160 144zM96 160C96 124.7 124.7 96 160 96L480 96C515.3 96 544 124.7 544 160L544 480C544 515.3 515.3 544 480 544L160 544C124.7 544 96 515.3 96 480L96 160zM224 192C241.7 192 256 206.3 256 224C256 241.7 241.7 256 224 256C206.3 256 192 241.7 192 224C192 206.3 206.3 192 224 192zM360 264C368.5 264 376.4 268.5 380.7 275.8L460.7 411.8C465.1 419.2 465.1 428.4 460.8 435.9C456.5 443.4 448.6 448 440 448L200 448C191.1 448 182.8 443 178.7 435.1C174.6 427.2 175.2 417.6 180.3 410.3L236.3 330.3C240.8 323.9 248.1 320.1 256 320.1C263.9 320.1 271.2 323.9 275.7 330.3L292.9 354.9L339.4 275.9C343.7 268.6 351.6 264.1 360.1 264.1z"})])}},r=e,C=A,B=j(r.activeTab),n=nA(()=>[{id:"wakeword",name:g("themeDesign.tabs.wakeword"),icon:t},{id:"font",name:g("themeDesign.tabs.font"),icon:I},{id:"emoji",name:g("themeDesign.tabs.emoji"),icon:o},{id:"background",name:g("themeDesign.tabs.background"),icon:i}]),Q=nA({get:()=>r.modelValue,set:h=>C("update:modelValue",h)}),a=()=>{var u,l,f;const h=r.modelValue.wakeword;if(h.type==="custom"){if(!((u=h.custom.name)!=null&&u.trim())){alert(g("wakewordConfig.errors.nameRequired"));return}if(!((l=h.custom.command)!=null&&l.trim())){alert(g("wakewordConfig.errors.commandRequired"));return}if(!h.custom.duration||h.custom.duration<500||h.custom.duration>1e4){alert(g("wakewordConfig.errors.durationRange"));return}}const w=r.modelValue.font;if(w.type==="custom"&&!((f=w.custom)!=null&&f.file)){alert(g("fontConfig.selectValidFontFile"));return}C("next")},E=h=>{B.value=h,C("tabChange",h)};return DA(()=>r.activeTab,h=>{B.value=h}),(h,w)=>(G(),U("div",hC,[s("div",null,[s("h2",uC,d(h.$t("themeDesign.title")),1),s("p",dC,d(h.$t("themeDesign.description")),1)]),s("div",fC,[s("nav",wC,[(G(!0),U(bA,null,LA(n.value,u=>(G(),U("button",{key:u.id,onClick:l=>E(u.id),class:gA(["py-2 px-1 border-b-2 font-medium text-sm relative",B.value===u.id?"border-primary-500 text-primary-600":"border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300"])},[s("span",pC,[(G(),UA(Bt(u.icon),{class:"w-5 h-5 sm:mr-2"})),s("span",DC,d(u.name),1)])],10,yC))),128))])]),s("div",mC,[B.value==="wakeword"?(G(),UA(Mo,{key:0,modelValue:Q.value.wakeword,"onUpdate:modelValue":w[0]||(w[0]=u=>Q.value.wakeword=u),chipModel:e.chipModel},null,8,["modelValue","chipModel"])):O("",!0),B.value==="font"?(G(),UA(Gi,{key:1,modelValue:Q.value.font,"onUpdate:modelValue":w[1]||(w[1]=u=>Q.value.font=u)},null,8,["modelValue"])):O("",!0),B.value==="emoji"?(G(),UA(Er,{key:2,modelValue:Q.value.emoji,"onUpdate:modelValue":w[2]||(w[2]=u=>Q.value.emoji=u)},null,8,["modelValue"])):O("",!0),B.value==="background"?(G(),UA(cC,{key:3,modelValue:Q.value.skin,"onUpdate:modelValue":w[3]||(w[3]=u=>Q.value.skin=u)},null,8,["modelValue"])):O("",!0)]),s("div",FC,[s("button",{onClick:w[4]||(w[4]=u=>h.$emit("prev")),class:"bg-gray-500 hover:bg-gray-600 text-white px-6 py-2 rounded-lg font-medium transition-colors"},d(h.$t("themeDesign.previous")),1),s("button",{onClick:a,class:"bg-primary-500 hover:bg-primary-600 text-white px-6 py-2 rounded-lg font-medium transition-colors"},d(h.$t("themeDesign.next")),1)])]))}},vC=(e,A)=>{const g=e.__vccOpts||e;for(const[t,I]of A)g[t]=I;return g},SC={class:"space-y-6"},GC={class:"text-xl font-semibold text-gray-900 mb-4"},RC={class:"text-gray-600 mb-6"},UC={class:"flex flex-col lg:flex-row gap-8"},NC={class:"flex-1"},bC={class:"text-lg font-medium text-gray-900 mb-4"},LC={class:"bg-gray-100 p-4 rounded-lg"},MC={class:"max-w-full overflow-auto flex justify-center"},JC={class:"bg-gray-800 p-6 rounded-2xl shadow-2xl inline-block"},xC={class:"bg-gray-900 p-2 rounded-xl"},HC={class:"relative z-10 flex flex-col items-center justify-center p-4 text-center"},YC={class:"mb-4"},KC={key:0,class:"emoji-container"},TC=["src","alt"],VC={key:1,class:"emoji-container"},qC={class:"text-center"},OC={class:"text-sm"},WC={class:"text-xs"},PC={key:0,class:"absolute inset-0 flex items-center justify-center"},ZC={class:"animate-pulse text-gray-400 text-xs"},XC={class:"mt-3 text-center text-xs text-gray-400"},jC={class:"w-full lg:w-80"},zC={class:"text-lg font-medium text-gray-900 mb-4"},_C={class:"space-y-6 bg-white border border-gray-200 rounded-lg p-4"},$C={class:"block text-sm font-medium text-gray-700 mb-2"},An={class:"block text-sm font-medium text-gray-700 mb-2"},en={key:0,class:"flex flex-wrap gap-2 max-h-32 overflow-y-auto justify-center"},gn=["onClick","title"],tn={key:0},In=["src","alt"],on={key:1,class:"text-lg"},rn={key:1,class:"text-center py-4 text-gray-500 bg-gray-50 rounded-lg border-2 border-dashed"},Cn={class:"text-2xl mb-2"},nn={class:"text-sm"},Bn={class:"block text-sm font-medium text-gray-700 mb-2"},sn={class:"flex space-x-2"},an={class:"border-t pt-4"},Qn={class:"font-medium text-gray-900 mb-2"},En={class:"text-xs text-gray-600 space-y-1"},ln={key:0},cn={class:"flex items-center"},hn={key:0,class:"ml-2 animate-pulse text-blue-500"},un={key:1},dn={class:"flex justify-between"},fn={__name:"GenerateSummary",props:{config:{type:Object,required:!0}},emits:["prev","generate"],setup(e){const{t:A}=TA(),g=e,t=j(A("generateSummary.defaultPreviewText")),I=j("happy"),o=j("light"),i=j(!1),r=j(""),C=nA(()=>[{key:"neutral",name:A("generateSummary.emotions.neutral"),emoji:"😶"},{key:"happy",name:A("generateSummary.emotions.happy"),emoji:"🙂"},{key:"laughing",name:A("generateSummary.emotions.laughing"),emoji:"😆"},{key:"funny",name:A("generateSummary.emotions.funny"),emoji:"😂"},{key:"sad",name:A("generateSummary.emotions.sad"),emoji:"😔"},{key:"angry",name:A("generateSummary.emotions.angry"),emoji:"😠"},{key:"crying",name:A("generateSummary.emotions.crying"),emoji:"😭"},{key:"loving",name:A("generateSummary.emotions.loving"),emoji:"😍"},{key:"surprised",name:A("generateSummary.emotions.surprised"),emoji:"😯"},{key:"thinking",name:A("generateSummary.emotions.thinking"),emoji:"🤔"},{key:"cool",name:A("generateSummary.emotions.cool"),emoji:"😎"},{key:"sleepy",name:A("generateSummary.emotions.sleepy"),emoji:"😴"}]),B=nA(()=>{if(g.config.theme.emoji.type==="preset"&&g.config.theme.emoji.preset)return C.value;if(g.config.theme.emoji.type==="custom"){const F=g.config.theme.emoji.custom.images;return C.value.filter(S=>F[S.key])}else return[]}),n=nA(()=>c(I.value)),Q=()=>{const{width:F,height:S}=g.config.chip.display;return{width:`${F}px`,height:`${S}px`}},a=()=>{const F=g.config.theme.skin[o.value];if(F.backgroundType==="image"&&F.backgroundImage)try{if(F.backgroundImage&&typeof F.backgroundImage=="object"&&F.backgroundImage.size)return{backgroundImage:`url(${URL.createObjectURL(F.backgroundImage)})`,backgroundSize:"cover",backgroundPosition:"center"}}catch(S){console.warn("Failed to load background preview:",S)}return{backgroundColor:F.backgroundColor||"#ffffff"}},E={twemoji32:32,twemoji64:64,"noto-emoji_64":64,"noto-emoji_128":128},h=()=>{let F=48;return g.config.theme.emoji.type==="preset"?F=E[g.config.theme.emoji.preset]||32:g.config.theme.emoji.custom.size&&(F=Math.min(g.config.theme.emoji.custom.size.width,g.config.theme.emoji.custom.size.height)),{width:`${F}px`,height:`${F}px`}},w=()=>{let F=14;if(g.config.theme.font.type==="preset"){const J=g.config.theme.font.preset;J.includes("_14_")?F=14:J.includes("_16_")?F=16:J.includes("_20_")?F=20:J.includes("_30_")&&(F=30)}else g.config.theme.font.custom.size&&(F=g.config.theme.font.custom.size);const S=o.value==="dark"?g.config.theme.skin.dark.textColor:g.config.theme.skin.light.textColor;return{fontSize:`${F}px`,color:S,fontFamily:l(),textShadow:o.value==="dark"?"1px 1px 2px rgba(0,0,0,0.5)":"1px 1px 2px rgba(255,255,255,0.5)"}},u=async()=>{document.querySelectorAll("style[data-font-preview]").forEach(S=>S.remove()),i.value=!1,r.value="";try{if(g.config.theme.font.type==="preset"){const S=g.config.theme.font.preset;let J,V;S&&S.startsWith("font_noto_qwen_")?(J="NotoPreview",V="./static/fonts/noto_qwen.ttf"):(J="PuHuiPreview",V="./static/fonts/puhui_deepseek.ttf");const q=document.createElement("style");q.setAttribute("data-font-preview","true"),q.textContent=` @font-face { font-family: '${J}'; src: url('${V}') format('truetype'); font-display: swap; } `,document.head.appendChild(q),await document.fonts.load(`16px "${J}"`),r.value=J,i.value=!0}else if(g.config.theme.font.custom.file)try{const S=g.config.theme.font.custom.file;if(!S||typeof S!="object"||!S.size)throw new Error("Invalid font file object");const J="CustomFontPreview",V=URL.createObjectURL(S),q=document.createElement("style");q.setAttribute("data-font-preview","true"),q.textContent=` @font-face { font-family: '${J}'; src: url('${V}'); font-display: swap; } `,document.head.appendChild(q),await document.fonts.load(`16px "${J}"`),r.value=J,i.value=!0}catch(S){console.warn("Failed to load custom font preview:",S),r.value="system-ui",i.value=!0}else r.value="system-ui",i.value=!0}catch(S){console.warn("Font loading failed:",S),r.value="system-ui",i.value=!0}},l=()=>i.value&&r.value?`"${r.value}", "Noto Sans", "Segoe UI", sans-serif`:'"Noto Sans", "Segoe UI", sans-serif',f={twemoji32:"png",twemoji64:"png","noto-emoji_64":"gif","noto-emoji_128":"gif"},c=F=>{if(g.config.theme.emoji.type==="preset"){const S=g.config.theme.emoji.preset,J=f[S]||"png";return`./static/emojis/${S}/${F}.${J}`}else if(g.config.theme.emoji.type==="custom"&&g.config.theme.emoji.custom.images[F])try{const S=g.config.theme.emoji.custom.images[F];if(S&&typeof S=="object"&&S.size)return URL.createObjectURL(S)}catch(S){console.warn(`Failed to load emoji preview (${F}):`,S)}return null},D=F=>{const S=C.value.find(J=>J.key===F);return S?S.emoji:"😶"},y=()=>{if(g.config.theme.emoji.type==="preset"){const F=E[g.config.theme.emoji.preset]||32;return Math.min(F+16,80)}else if(g.config.theme.emoji.custom.size){const F=Math.min(g.config.theme.emoji.custom.size.width,g.config.theme.emoji.custom.size.height);return Math.min(F+16,80)}return 48},v=()=>{if(g.config.theme.emoji.type==="preset"){const F=E[g.config.theme.emoji.preset]||32;return Math.min(F,64)}else if(g.config.theme.emoji.custom.size)return Math.min(g.config.theme.emoji.custom.size.width,g.config.theme.emoji.custom.size.height,64);return 32},N=F=>{I.value=F},L={wn9s_hilexin:"generateModal.wakewordNames.wn9s_hilexin",wn9s_hiesp:"generateModal.wakewordNames.wn9s_hiesp",wn9s_nihaoxiaozhi:"generateModal.wakewordNames.wn9s_nihaoxiaozhi",wn9s_hijason:"Hi, Jason",wn9s_alexa:"Alexa",wn9_hilexin:"Hi, Espressif",wn9_hiesp:"Hi, ESP",wn9_nihaoxiaozhi_tts:"generateModal.wakewordNames.wn9_nihaoxiaozhi_tts",wn9_hijason_tts2:"Hi, Jason",wn9_himfive:"Hi, M Five",wn9_alexa:"generateModal.wakewordNames.wn9_alexa",wn9_jarvis_tts:"Jarvis",wn9_computer_tts:"Computer",wn9_heywillow_tts:"Hey, Willow",wn9_sophia_tts:"Sophia",wn9_heyprinter_tts:"Hey, Printer",wn9_hijoy_tts:"Hi, Joy",wn9_heywanda_tts:"Hey, Wand",wn9_astrolabe_tts:"Astrolabe",wn9_heyily_tts2:"Hey, Ily",wn9_hijolly_tts2:"Hi, Jolly",wn9_hifairy_tts2:"Hi, Fairy",wn9_bluechip_tts2:"Blue Chip",wn9_hiandy_tts2:"Hi, Andy",wn9_heyivy_tts2:"Hey, Ivy",wn9_histackchan_tts3:"Hi, Stack Chan",wn9_hiwalle_tts2:"Hi, Wall E",wn9_hilili_tts:"Hi, Lily",wn9_hitelly_tts:"Hi, Telly",wn9_linaiban_tts2:"Lina Board"},X=F=>{const S=L[F];return S!=null&&S.startsWith("generateModal.")?A(S):S||F},k=()=>{const F=g.config.theme.wakeword;return!F||F.type==="none"?A("wakewordConfig.noWakeword"):F.type==="preset"?X(F.preset):F.type==="custom"?F.custom.name||A("wakewordConfig.customWakeword"):A("wakewordConfig.noWakeword")},m=()=>{if(g.config.theme.font.type==="preset")return A("fontConfig.presetFontNames."+g.config.theme.font.preset)||g.config.theme.font.preset;{const F=g.config.theme.font.custom;return A("generateSummary.customFont",{size:F.size})}},M=()=>{if(g.config.theme.emoji.type==="preset"&&g.config.theme.emoji.preset)return{twemoji32:"Twemoji 32×32",twemoji64:"Twemoji 64×64","noto-emoji_64":"Noto Emoji 64×64","noto-emoji_128":"Noto Emoji 128×128"}[g.config.theme.emoji.preset]||g.config.theme.emoji.preset;if(g.config.theme.emoji.type==="custom"){const F=Object.keys(g.config.theme.emoji.custom.images).length;return A("generateSummary.customEmoji",{count:F})}else return g.config.theme.emoji.type==="none"?A("emojiConfig.noEmojiPack"):A("generateSummary.notConfigured")},oA=()=>{const F=g.config.theme.skin.light.backgroundType==="image"?A("generateSummary.image"):A("generateSummary.color"),S=g.config.theme.skin.dark.backgroundType==="image"?A("generateSummary.image"):A("generateSummary.color");return A("generateSummary.skinLight",{type:F})+"/"+A("generateSummary.skinDark",{type:S})};return DA(()=>g.config.theme.font,()=>{u()},{deep:!0}),Me(async()=>{B.value.length>0?I.value=B.value[0].key:I.value="",await u()}),st(()=>{document.querySelectorAll("style[data-font-preview]").forEach(S=>S.remove())}),(F,S)=>(G(),U("div",SC,[s("div",null,[s("h2",GC,d(F.$t("generateSummary.title")),1),s("p",RC,d(F.$t("generateSummary.description")),1)]),s("div",UC,[s("div",NC,[s("h3",bC,d(F.$t("generateSummary.devicePreview")),1),s("div",LC,[s("div",MC,[s("div",JC,[s("div",xC,[s("div",{style:CA(Q()),class:"relative rounded-lg overflow-hidden border-2 border-gray-700 flex flex-col items-center justify-center"},[s("div",{style:CA(a()),class:"absolute inset-0"},null,4),s("div",HC,[s("div",YC,[I.value&&B.value.length>0?(G(),U("div",KC,[n.value?(G(),U("img",{key:0,src:n.value,alt:I.value,style:CA(h()),class:"emoji-image"},null,12,TC)):(G(),U("div",{key:1,style:CA(h()),class:"emoji-fallback bg-gray-200 rounded-full flex items-center justify-center text-2xl"},d(D(I.value)),5))])):(G(),U("div",VC,[s("div",{style:CA(h()),class:"emoji-placeholder flex items-center justify-center text-gray-400 border-2 border-dashed border-gray-300 rounded bg-gray-50"},[s("div",qC,[s("div",OC,d(e.config.theme.emoji.type==="none"?"📦":"😕"),1),s("div",WC,d(e.config.theme.emoji.type==="none"?F.$t("emojiConfig.noEmojiPack"):F.$t("generateSummary.noEmotionConfigured")),1)])],4)]))]),e.config.theme.font.hide_subtitle?O("",!0):(G(),U("div",{key:0,style:CA(w()),class:"text-message max-w-full break-words relative"},[i.value?O("",!0):(G(),U("div",PC,[s("div",ZC,d(F.$t("generateSummary.fontLoading")),1)])),s("div",{class:gA({"opacity-0":!i.value})},d(t.value),3)],4))])],4)]),s("div",XC,d(e.config.chip.display.width)+" × "+d(e.config.chip.display.height)+" "+d(e.config.chip.model.toUpperCase()),1)])])])]),s("div",jC,[s("h3",zC,d(F.$t("generateSummary.previewSettings")),1),s("div",_C,[s("div",null,[s("label",$C,d(F.$t("generateSummary.previewText")),1),rA(s("textarea",{"onUpdate:modelValue":S[0]||(S[0]=J=>t.value=J),class:"w-full border border-gray-300 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-primary-500",rows:"3",placeholder:"Hi, I'm your friend Xiaozhi!"},null,512),[[aA,t.value]])]),s("div",null,[s("label",An,d(F.$t("generateSummary.currentEmotion")),1),B.value.length>0?(G(),U("div",en,[(G(!0),U(bA,null,LA(B.value,J=>(G(),U("button",{key:J.key,onClick:V=>N(J.key),class:gA(["p-2 border rounded transition-colors flex items-center justify-center",I.value===J.key?"border-primary-500 bg-primary-50":"border-gray-200 hover:border-gray-300"]),title:J.name,style:CA({width:y()+"px",height:y()+"px"})},[c(J.key)?(G(),U("div",tn,[s("img",{src:c(J.key),alt:J.name,style:CA({width:v()+"px",height:v()+"px"}),class:"object-contain rounded"},null,12,In)])):(G(),U("div",on,d(J.emoji),1))],14,gn))),128))])):(G(),U("div",rn,[s("div",Cn,d(e.config.theme.emoji.type==="none"?"📦":"😕"),1),s("div",nn,d(e.config.theme.emoji.type==="none"?F.$t("emojiConfig.noEmojiPackDescription"):F.$t("generateSummary.configureEmojiFirst")),1)]))]),s("div",null,[s("label",Bn,d(F.$t("generateSummary.themeMode")),1),s("div",sn,[s("button",{onClick:S[1]||(S[1]=J=>o.value="light"),class:gA(["flex-1 py-2 px-3 text-sm border rounded transition-colors",o.value==="light"?"border-primary-500 bg-primary-50 text-primary-700":"border-gray-300 hover:border-gray-400"])}," 🌞 "+d(F.$t("generateSummary.lightMode")),3),s("button",{onClick:S[2]||(S[2]=J=>o.value="dark"),class:gA(["flex-1 py-2 px-3 text-sm border rounded transition-colors",o.value==="dark"?"border-primary-500 bg-primary-50 text-primary-700":"border-gray-300 hover:border-gray-400"])}," 🌙 "+d(F.$t("generateSummary.darkMode")),3)])]),s("div",an,[s("h4",Qn,d(F.$t("generateSummary.configSummary")),1),s("div",En,[e.config.theme.wakeword?(G(),U("div",ln,d(F.$t("generateSummary.wakeword"))+" "+d(k()),1)):O("",!0),s("div",cn,[s("span",null,d(F.$t("generateSummary.font"))+" "+d(m()),1),i.value?O("",!0):(G(),U("span",hn,d(F.$t("generateSummary.loading")),1))]),s("div",null,d(F.$t("generateSummary.emotion"))+" "+d(M()),1),s("div",null,d(F.$t("generateSummary.skin"))+" "+d(oA()),1),e.config.theme.font.hide_subtitle?(G(),U("div",un,d(F.$t("generateSummary.hideSubtitle"))+" "+d(F.$t("common.yes")),1)):O("",!0)])])])])]),s("div",dn,[s("button",{onClick:S[3]||(S[3]=J=>F.$emit("prev")),class:"bg-gray-500 hover:bg-gray-600 text-white px-6 py-2 rounded-lg font-medium transition-colors"},d(F.$t("generateSummary.previous")),1),s("button",{onClick:S[4]||(S[4]=J=>F.$emit("generate")),class:"bg-green-500 hover:bg-green-600 text-white px-8 py-2 rounded-lg font-medium transition-colors flex items-center"},[S[5]||(S[5]=s("svg",{class:"w-5 h-5 mr-2",fill:"currentColor",viewBox:"0 0 20 20"},[s("path",{"fill-rule":"evenodd",d:"M3 17a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm3.293-7.707a1 1 0 011.414 0L9 10.586V3a1 1 0 112 0v7.586l1.293-1.293a1 1 0 111.414 1.414l-3 3a1 1 0 01-1.414 0l-3-3a1 1 0 010-1.414z","clip-rule":"evenodd"})],-1)),HA(" "+d(F.$t("generateSummary.generate")),1)])])]))}},wn=vC(fn,[["__scopeId","data-v-38d663e6"]]);/*! https://mths.be/codepointat v0.2.0 by @mathias */String.prototype.codePointAt||function(){var e=function(){try{var g={},t=Object.defineProperty,I=t(g,g,g)&&t}catch{}return I}(),A=function(g){if(this==null)throw TypeError();var t=String(this),I=t.length,o=g?Number(g):0;if(o!=o&&(o=0),!(o<0||o>=I)){var i=t.charCodeAt(o),r;return i>=55296&&i<=56319&&I>o+1&&(r=t.charCodeAt(o+1),r>=56320&&r<=57343)?(i-55296)*1024+r-56320+65536:i}};e?e(String.prototype,"codePointAt",{value:A,configurable:!0,writable:!0}):String.prototype.codePointAt=A}();var rg=0,at=-3;function se(){this.table=new Uint16Array(16),this.trans=new Uint16Array(288)}function yn(e,A){this.source=e,this.sourceIndex=0,this.tag=0,this.bitcount=0,this.dest=A,this.destLen=0,this.ltree=new se,this.dtree=new se}var Qt=new se,Et=new se,Cg=new Uint8Array(30),ng=new Uint16Array(30),lt=new Uint8Array(30),ct=new Uint16Array(30),pn=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),yg=new se,GA=new Uint8Array(320);function ht(e,A,g,t){var I,o;for(I=0;I>>=1,A}function RA(e,A,g){if(!A)return g;for(;e.bitcount<24;)e.tag|=e.source[e.sourceIndex++]<>>16-A;return e.tag>>>=A,e.bitcount-=A,t+g}function je(e,A){for(;e.bitcount<24;)e.tag|=e.source[e.sourceIndex++]<>>=1,++I,g+=A.table[I],t-=A.table[I];while(t>=0);return e.tag=o,e.bitcount-=I,A.trans[g+t]}function Fn(e,A,g){var t,I,o,i,r,C;for(t=RA(e,5,257),I=RA(e,5,1),o=RA(e,4,4),i=0;i<19;++i)GA[i]=0;for(i=0;i8;)e.sourceIndex--,e.bitcount-=8;if(A=e.source[e.sourceIndex+1],A=256*A+e.source[e.sourceIndex],g=e.source[e.sourceIndex+3],g=256*g+e.source[e.sourceIndex+2],A!==(~g&65535))return at;for(e.sourceIndex+=4,t=A;t;--t)e.dest[e.destLen++]=e.source[e.sourceIndex++];return e.bitcount=0,rg}function vn(e,A){var g=new yn(e,A),t,I,o;do{switch(t=mn(g),I=RA(g,2,0),I){case 0:o=kn(g);break;case 1:o=Dg(g,Qt,Et);break;case 2:Fn(g,g.ltree,g.dtree),o=Dg(g,g.ltree,g.dtree);break;default:o=at}if(o!==rg)throw new Error("Data error")}while(!t);return g.destLenthis.x2&&(this.x2=e)),typeof A=="number"&&((isNaN(this.y1)||isNaN(this.y2))&&(this.y1=A,this.y2=A),Athis.y2&&(this.y2=A))};VA.prototype.addX=function(e){this.addPoint(e,null)};VA.prototype.addY=function(e){this.addPoint(null,e)};VA.prototype.addBezier=function(e,A,g,t,I,o,i,r){var C=[e,A],B=[g,t],n=[I,o],Q=[i,r];this.addPoint(e,A),this.addPoint(i,r);for(var a=0;a<=1;a++){var E=6*C[a]-12*B[a]+6*n[a],h=-3*C[a]+9*B[a]-9*n[a]+3*Q[a],w=3*B[a]-3*C[a];if(h===0){if(E===0)continue;var u=-w/E;0=0&&C>0&&(r+=" "),r+=A(B)}return r}for(var t="",I=0;I=0&&e<=255,"Byte value should be between 0 and 255."),[e]};P.BYTE=vA(1);x.CHAR=function(e){return[e.charCodeAt(0)]};P.CHAR=vA(1);x.CHARARRAY=function(e){typeof e>"u"&&(e="",console.warn("Undefined CHARARRAY encountered and treated as an empty string. This is probably caused by a missing glyph name."));for(var A=[],g=0;g"u"?0:e.length};x.USHORT=function(e){return[e>>8&255,e&255]};P.USHORT=vA(2);x.SHORT=function(e){return e>=Fg&&(e=-(2*Fg-e)),[e>>8&255,e&255]};P.SHORT=vA(2);x.UINT24=function(e){return[e>>16&255,e>>8&255,e&255]};P.UINT24=vA(3);x.ULONG=function(e){return[e>>24&255,e>>16&255,e>>8&255,e&255]};P.ULONG=vA(4);x.LONG=function(e){return e>=kg&&(e=-(2*kg-e)),[e>>24&255,e>>16&255,e>>8&255,e&255]};P.LONG=vA(4);x.FIXED=x.ULONG;P.FIXED=P.ULONG;x.FWORD=x.SHORT;P.FWORD=P.SHORT;x.UFWORD=x.USHORT;P.UFWORD=P.USHORT;x.LONGDATETIME=function(e){return[0,0,0,0,e>>24&255,e>>16&255,e>>8&255,e&255]};P.LONGDATETIME=vA(8);x.TAG=function(e){return W.argument(e.length===4,"Tag should be exactly 4 ASCII characters."),[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]};P.TAG=vA(4);x.Card8=x.BYTE;P.Card8=P.BYTE;x.Card16=x.USHORT;P.Card16=P.USHORT;x.OffSize=x.BYTE;P.OffSize=P.BYTE;x.SID=x.USHORT;P.SID=P.USHORT;x.NUMBER=function(e){return e>=-107&&e<=107?[e+139]:e>=108&&e<=1131?(e=e-108,[(e>>8)+247,e&255]):e>=-1131&&e<=-108?(e=-e-108,[(e>>8)+251,e&255]):e>=-32768&&e<=32767?x.NUMBER16(e):x.NUMBER32(e)};P.NUMBER=function(e){return x.NUMBER(e).length};x.NUMBER16=function(e){return[28,e>>8&255,e&255]};P.NUMBER16=vA(3);x.NUMBER32=function(e){return[29,e>>24&255,e>>16&255,e>>8&255,e&255]};P.NUMBER32=vA(5);x.REAL=function(e){var A=e.toString(),g=/\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(A);if(g){var t=parseFloat("1e"+((g[2]?+g[2]:0)+g[1].length));A=(Math.round(e*t)/t).toString()}for(var I="",o=0,i=A.length;o>8&255,A[A.length]=t&255}return A};P.UTF16=function(e){return e.length*2};var ze={"x-mac-croatian":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈ƫȅ ÀÃÕŒœĐ—“”‘’÷◊©⁄€‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ","x-mac-cyrillic":"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю","x-mac-gaelic":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØḂ±≤≥ḃĊċḊḋḞḟĠġṀæøṁṖṗɼƒſṠ«»… ÀÃÕŒœ–—“”‘’ṡẛÿŸṪ€‹›Ŷŷṫ·Ỳỳ⁊ÂÊÁËÈÍÎÏÌÓÔ♣ÒÚÛÙıÝýŴŵẄẅẀẁẂẃ","x-mac-greek":"Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦€ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ­","x-mac-icelandic":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüݰ¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-inuit":"ᐃᐄᐅᐆᐊᐋᐱᐲᐳᐴᐸᐹᑉᑎᑏᑐᑑᑕᑖᑦᑭᑮᑯᑰᑲᑳᒃᒋᒌᒍᒎᒐᒑ°ᒡᒥᒦ•¶ᒧ®©™ᒨᒪᒫᒻᓂᓃᓄᓅᓇᓈᓐᓯᓰᓱᓲᓴᓵᔅᓕᓖᓗᓘᓚᓛᓪᔨᔩᔪᔫᔭ… ᔮᔾᕕᕖᕗ–—“”‘’ᕘᕙᕚᕝᕆᕇᕈᕉᕋᕌᕐᕿᖀᖁᖂᖃᖄᖅᖏᖐᖑᖒᖓᖔᖕᙱᙲᙳᙴᙵᙶᖖᖠᖡᖢᖣᖤᖥᖦᕼŁł","x-mac-ce":"ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ",macintosh:"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-romanian":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂȘ∞±≤≥¥µ∂∑∏π∫ªºΩăș¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›Țț‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-turkish":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙˆ˜¯˘˙˚¸˝˛ˇ"};oe.MACSTRING=function(e,A,g,t){var I=ze[t];if(I!==void 0){for(var o="",i=0;i=128&&(o=g[o],o===void 0))return;t[I]=o}return t}};P.MACSTRING=function(e,A){var g=x.MACSTRING(e,A);return g!==void 0?g.length:0};function _e(e){return e>=-128&&e<=127}function Rn(e,A,g){for(var t=0,I=e.length;A>8&255,C+256&255)}return o}x.VARDELTAS=function(e){for(var A=0,g=[];A=-128&&t<=127?A=Un(e,A,g):A=Nn(e,A,g)}return g};x.INDEX=function(e){for(var A=1,g=[A],t=[],I=0;I>8,A[Q+1]=a&255,A=A.concat(t[n])}return A};P.TABLE=function(e){for(var A=0,g=e.fields.length,t=0;t0)return new p(this.data,this.offset+A).parseStruct(e)};p.prototype.parsePointer32=function(e){var A=this.parseOffset32();if(A>0)return new p(this.data,this.offset+A).parseStruct(e)};p.prototype.parseListOfLists=function(e){for(var A=this.parseOffset16List(),g=A.length,t=this.relativeOffset,I=new Array(g),o=0;o>1,A.skip("uShort",3),e.glyphIndexMap={};for(var i=new T.Parser(g,t+I+14),r=new T.Parser(g,t+I+16+o*2),C=new T.Parser(g,t+I+16+o*4),B=new T.Parser(g,t+I+16+o*6),n=t+I+16+o*8,Q=0;Q=0;I-=1){var o=T.getUShort(e,A+4+I*8),i=T.getUShort(e,A+4+I*8+2);if(o===3&&(i===0||i===1||i===10)||o===0&&(i===0||i===1||i===2||i===3||i===4)){t=T.getULong(e,A+4+I*8+4);break}}if(t===-1)throw new Error("No valid cmap sub-tables found.");var r=new T.Parser(e,A+t);if(g.format=r.parseUShort(),g.format===12)Yn(g,r);else if(g.format===4)Kn(g,r,e,A,t);else throw new Error("Only format 4 and 12 cmap tables are supported (found format "+g.format+").");return g}function Vn(e,A,g){e.segments.push({end:A,start:A,delta:-(A-g),offset:0,glyphIndex:g})}function qn(e){e.segments.push({end:65535,start:65535,delta:1,offset:0})}function On(e){var A=!0,g;for(g=e.length-1;g>0;g-=1){var t=e.get(g);if(t.unicode>65535){console.log("Adding CMAP format 12 (needed!)"),A=!1;break}}var I=[{name:"version",type:"USHORT",value:0},{name:"numTables",type:"USHORT",value:A?1:2},{name:"platformID",type:"USHORT",value:3},{name:"encodingID",type:"USHORT",value:1},{name:"offset",type:"ULONG",value:A?12:20}];A||(I=I.concat([{name:"cmap12PlatformID",type:"USHORT",value:3},{name:"cmap12EncodingID",type:"USHORT",value:10},{name:"cmap12Offset",type:"ULONG",value:0}])),I=I.concat([{name:"format",type:"USHORT",value:4},{name:"cmap4Length",type:"USHORT",value:0},{name:"language",type:"USHORT",value:0},{name:"segCountX2",type:"USHORT",value:0},{name:"searchRange",type:"USHORT",value:0},{name:"entrySelector",type:"USHORT",value:0},{name:"rangeShift",type:"USHORT",value:0}]);var o=new Y.Table("cmap",I);for(o.segments=[],g=0;g>4,i=I&15;if(o===g||(A+=t[o],i===g))break;A+=t[i]}return parseFloat(A)}function oB(e,A){var g,t,I,o;if(A===28)return g=e.parseByte(),t=e.parseByte(),g<<8|t;if(A===29)return g=e.parseByte(),t=e.parseByte(),I=e.parseByte(),o=e.parseByte(),g<<24|t<<16|I<<8|o;if(A===30)return IB(e);if(A>=32&&A<=246)return A-139;if(A>=247&&A<=250)return g=e.parseByte(),(A-247)*256+g+108;if(A>=251&&A<=254)return g=e.parseByte(),-(A-251)*256-g-108;throw new Error("Invalid b0 "+A)}function iB(e){for(var A={},g=0;g>1,C.length=0,n=!0}function N(L){for(var X,k,m,M,oA,F,S,J,V,q,$,AA,_=0;_1&&!n&&(D=C.shift()+l,n=!0),E+=C.pop(),y(a,E);break;case 5:for(;C.length>0;)a+=C.shift(),E+=C.shift(),r.lineTo(a,E);break;case 6:for(;C.length>0&&(a+=C.shift(),r.lineTo(a,E),C.length!==0);)E+=C.shift(),r.lineTo(a,E);break;case 7:for(;C.length>0&&(E+=C.shift(),r.lineTo(a,E),C.length!==0);)a+=C.shift(),r.lineTo(a,E);break;case 8:for(;C.length>0;)t=a+C.shift(),I=E+C.shift(),o=t+C.shift(),i=I+C.shift(),a=o+C.shift(),E=i+C.shift(),r.curveTo(t,I,o,i,a,E);break;case 10:oA=C.pop()+w,F=h[oA],F&&N(F);break;case 11:return;case 12:switch(iA=L[_],_+=1,iA){case 35:t=a+C.shift(),I=E+C.shift(),o=t+C.shift(),i=I+C.shift(),S=o+C.shift(),J=i+C.shift(),V=S+C.shift(),q=J+C.shift(),$=V+C.shift(),AA=q+C.shift(),a=$+C.shift(),E=AA+C.shift(),C.shift(),r.curveTo(t,I,o,i,S,J),r.curveTo(V,q,$,AA,a,E);break;case 34:t=a+C.shift(),I=E,o=t+C.shift(),i=I+C.shift(),S=o+C.shift(),J=i,V=S+C.shift(),q=i,$=V+C.shift(),AA=E,a=$+C.shift(),r.curveTo(t,I,o,i,S,J),r.curveTo(V,q,$,AA,a,E);break;case 36:t=a+C.shift(),I=E+C.shift(),o=t+C.shift(),i=I+C.shift(),S=o+C.shift(),J=i,V=S+C.shift(),q=i,$=V+C.shift(),AA=q+C.shift(),a=$+C.shift(),r.curveTo(t,I,o,i,S,J),r.curveTo(V,q,$,AA,a,E);break;case 37:t=a+C.shift(),I=E+C.shift(),o=t+C.shift(),i=I+C.shift(),S=o+C.shift(),J=i+C.shift(),V=S+C.shift(),q=J+C.shift(),$=V+C.shift(),AA=q+C.shift(),Math.abs($-a)>Math.abs(AA-E)?a=$+C.shift():E=AA+C.shift(),r.curveTo(t,I,o,i,S,J),r.curveTo(V,q,$,AA,a,E);break;default:console.log("Glyph "+A.index+": unknown operator 1200"+iA),C.length=0}break;case 14:C.length>0&&!n&&(D=C.shift()+l,n=!0),Q&&(r.closePath(),Q=!1);break;case 18:v();break;case 19:case 20:v(),_+=B+7>>3;break;case 21:C.length>2&&!n&&(D=C.shift()+l,n=!0),E+=C.pop(),a+=C.pop(),y(a,E);break;case 22:C.length>1&&!n&&(D=C.shift()+l,n=!0),a+=C.pop(),y(a,E);break;case 23:v();break;case 24:for(;C.length>2;)t=a+C.shift(),I=E+C.shift(),o=t+C.shift(),i=I+C.shift(),a=o+C.shift(),E=i+C.shift(),r.curveTo(t,I,o,i,a,E);a+=C.shift(),E+=C.shift(),r.lineTo(a,E);break;case 25:for(;C.length>6;)a+=C.shift(),E+=C.shift(),r.lineTo(a,E);t=a+C.shift(),I=E+C.shift(),o=t+C.shift(),i=I+C.shift(),a=o+C.shift(),E=i+C.shift(),r.curveTo(t,I,o,i,a,E);break;case 26:for(C.length%2&&(a+=C.shift());C.length>0;)t=a,I=E+C.shift(),o=t+C.shift(),i=I+C.shift(),a=o,E=i+C.shift(),r.curveTo(t,I,o,i,a,E);break;case 27:for(C.length%2&&(E+=C.shift());C.length>0;)t=a+C.shift(),I=E,o=t+C.shift(),i=I+C.shift(),a=o+C.shift(),E=i,r.curveTo(t,I,o,i,a,E);break;case 28:X=L[_],k=L[_+1],C.push((X<<24|k<<16)>>16),_+=2;break;case 29:oA=C.pop()+e.gsubrsBias,F=e.gsubrs[oA],F&&N(F);break;case 30:for(;C.length>0&&(t=a,I=E+C.shift(),o=t+C.shift(),i=I+C.shift(),a=o+C.shift(),E=i+(C.length===1?C.shift():0),r.curveTo(t,I,o,i,a,E),C.length!==0);)t=a+C.shift(),I=E,o=t+C.shift(),i=I+C.shift(),E=i+C.shift(),a=o+(C.length===1?C.shift():0),r.curveTo(t,I,o,i,a,E);break;case 31:for(;C.length>0&&(t=a+C.shift(),I=E,o=t+C.shift(),i=I+C.shift(),E=i+C.shift(),a=o+(C.length===1?C.shift():0),r.curveTo(t,I,o,i,a,E),C.length!==0);)t=a,I=E+C.shift(),o=t+C.shift(),i=I+C.shift(),a=o+C.shift(),E=i+(C.length===1?C.shift():0),r.curveTo(t,I,o,i,a,E);break;default:iA<32?console.log("Glyph "+A.index+": unknown operator "+iA):iA<247?C.push(iA-139):iA<251?(X=L[_],_+=1,C.push((iA-247)*256+X+108)):iA<255?(X=L[_],_+=1,C.push(-(iA-251)*256-X-108)):(X=L[_],k=L[_+1],m=L[_+2],M=L[_+3],_+=4,C.push((X<<24|k<<16|m<<8|M)/65536))}}}return N(g),A.advanceWidth=D,r}function sB(e,A,g,t){var I=[],o,i=new T.Parser(e,A),r=i.parseCard8();if(r===0)for(var C=0;C=t)throw new Error("CFF table CID Font FDSelect has bad FD index value "+o+" (FD count "+t+")");I.push(o)}else if(r===3){var B=i.parseCard16(),n=i.parseCard16();if(n!==0)throw new Error("CFF Table CID Font FDSelect format 3 range has bad initial GID "+n);for(var Q,a=0;a=t)throw new Error("CFF table CID Font FDSelect has bad FD index value "+o+" (FD count "+t+")");if(Q>g)throw new Error("CFF Table CID Font FDSelect format 3 range has bad GID "+Q);for(;n=0&&(g=t),t=A.indexOf(e),t>=0?g=t+ve.length:(g=ve.length+A.length,A.push(e)),g}function QB(){return new Y.Record("Header",[{name:"major",type:"Card8",value:1},{name:"minor",type:"Card8",value:0},{name:"hdrSize",type:"Card8",value:4},{name:"major",type:"Card8",value:1}])}function EB(e){var A=new Y.Record("Name INDEX",[{name:"names",type:"INDEX",value:[]}]);A.names=[];for(var g=0;g=g.begin&&e=1&&(g.ulCodePageRange1=t.parseULong(),g.ulCodePageRange2=t.parseULong()),g.version>=2&&(g.sxHeight=t.parseShort(),g.sCapHeight=t.parseShort(),g.usDefaultChar=t.parseUShort(),g.usBreakChar=t.parseUShort(),g.usMaxContent=t.parseUShort()),g}function VB(e){return new Y.Table("OS/2",[{name:"version",type:"USHORT",value:3},{name:"xAvgCharWidth",type:"SHORT",value:0},{name:"usWeightClass",type:"USHORT",value:0},{name:"usWidthClass",type:"USHORT",value:0},{name:"fsType",type:"USHORT",value:0},{name:"ySubscriptXSize",type:"SHORT",value:650},{name:"ySubscriptYSize",type:"SHORT",value:699},{name:"ySubscriptXOffset",type:"SHORT",value:0},{name:"ySubscriptYOffset",type:"SHORT",value:140},{name:"ySuperscriptXSize",type:"SHORT",value:650},{name:"ySuperscriptYSize",type:"SHORT",value:699},{name:"ySuperscriptXOffset",type:"SHORT",value:0},{name:"ySuperscriptYOffset",type:"SHORT",value:479},{name:"yStrikeoutSize",type:"SHORT",value:49},{name:"yStrikeoutPosition",type:"SHORT",value:258},{name:"sFamilyClass",type:"SHORT",value:0},{name:"bFamilyType",type:"BYTE",value:0},{name:"bSerifStyle",type:"BYTE",value:0},{name:"bWeight",type:"BYTE",value:0},{name:"bProportion",type:"BYTE",value:0},{name:"bContrast",type:"BYTE",value:0},{name:"bStrokeVariation",type:"BYTE",value:0},{name:"bArmStyle",type:"BYTE",value:0},{name:"bLetterform",type:"BYTE",value:0},{name:"bMidline",type:"BYTE",value:0},{name:"bXHeight",type:"BYTE",value:0},{name:"ulUnicodeRange1",type:"ULONG",value:0},{name:"ulUnicodeRange2",type:"ULONG",value:0},{name:"ulUnicodeRange3",type:"ULONG",value:0},{name:"ulUnicodeRange4",type:"ULONG",value:0},{name:"achVendID",type:"CHARARRAY",value:"XXXX"},{name:"fsSelection",type:"USHORT",value:0},{name:"usFirstCharIndex",type:"USHORT",value:0},{name:"usLastCharIndex",type:"USHORT",value:0},{name:"sTypoAscender",type:"SHORT",value:0},{name:"sTypoDescender",type:"SHORT",value:0},{name:"sTypoLineGap",type:"SHORT",value:0},{name:"usWinAscent",type:"USHORT",value:0},{name:"usWinDescent",type:"USHORT",value:0},{name:"ulCodePageRange1",type:"ULONG",value:0},{name:"ulCodePageRange2",type:"ULONG",value:0},{name:"sxHeight",type:"SHORT",value:0},{name:"sCapHeight",type:"SHORT",value:0},{name:"usDefaultChar",type:"USHORT",value:0},{name:"usBreakChar",type:"USHORT",value:0},{name:"usMaxContext",type:"USHORT",value:0}],e)}var tg={parse:TB,make:VB,unicodeRanges:gg,getUnicodeRange:KB};function qB(e,A){var g={},t=new T.Parser(e,A);switch(g.version=t.parseVersion(),g.italicAngle=t.parseFixed(),g.underlinePosition=t.parseShort(),g.underlineThickness=t.parseShort(),g.isFixedPitch=t.parseULong(),g.minMemType42=t.parseULong(),g.maxMemType42=t.parseULong(),g.minMemType1=t.parseULong(),g.maxMemType1=t.parseULong(),g.version){case 1:g.names=_A.slice();break;case 2:g.numberOfGlyphs=t.parseUShort(),g.glyphNameIndex=new Array(g.numberOfGlyphs);for(var I=0;I=_A.length){var i=t.parseChar();g.names.push(t.parseString(i))}break;case 2.5:g.numberOfGlyphs=t.parseUShort(),g.offset=new Array(g.numberOfGlyphs);for(var r=0;rQ.value.tag?1:-1}),A.fields=A.fields.concat(t),A.fields=A.fields.concat(I),A}function xg(e,A,g){for(var t=0;t0){var o=e.glyphs.get(I);return o.getMetrics()}}return g}function jB(e){for(var A=0,g=0;gu||C===void 0)&&u>0&&(C=u),B 123 are reserved for internal usage");if(w.name!==".notdef"){var f=w.getMetrics();A.push(f.xMin),g.push(f.yMin),t.push(f.xMax),I.push(f.yMax),i.push(f.leftSideBearing),r.push(f.rightSideBearing),o.push(w.advanceWidth)}}var c={xMin:Math.min.apply(null,A),yMin:Math.min.apply(null,g),xMax:Math.max.apply(null,t),yMax:Math.max.apply(null,I),advanceWidthMax:Math.max.apply(null,o),advanceWidthAvg:jB(o),minLeftSideBearing:Math.min.apply(null,i),maxLeftSideBearing:Math.max.apply(null,i),minRightSideBearing:Math.min.apply(null,r)};c.ascender=e.ascender,c.descender=e.descender;var D=Ut.make({flags:3,unitsPerEm:e.unitsPerEm,xMin:c.xMin,yMin:c.yMin,xMax:c.xMax,yMax:c.yMax,lowestRecPPEM:3,createdTimestamp:e.createdTimestamp}),y=Nt.make({ascender:c.ascender,descender:c.descender,advanceWidthMax:c.advanceWidthMax,minLeftSideBearing:c.minLeftSideBearing,minRightSideBearing:c.minRightSideBearing,xMaxExtent:c.maxLeftSideBearing+(c.xMax-c.xMin),numberOfHMetrics:e.glyphs.length}),v=Mt.make(e.glyphs.length),N=tg.make(Object.assign({xAvgCharWidth:Math.round(c.advanceWidthAvg),usFirstCharIndex:C,usLastCharIndex:B,ulUnicodeRange1:n,ulUnicodeRange2:Q,ulUnicodeRange3:a,ulUnicodeRange4:E,sTypoAscender:c.ascender,sTypoDescender:c.descender,sTypoLineGap:0,usWinAscent:c.yMax,usWinDescent:Math.abs(c.yMin),ulCodePageRange1:1,sxHeight:xg(e,"xyvw",{yMax:Math.round(c.ascender/2)}).yMax,sCapHeight:xg(e,"HIKLEFJMNTZBDPRAGOQSUVWXY",c).yMax,usDefaultChar:e.hasChar(" ")?32:0,usBreakChar:e.hasChar(" ")?32:0},e.tables.os2)),L=bt.make(e.glyphs),X=ft.make(e.glyphs),k=e.getEnglishName("fontFamily"),m=e.getEnglishName("fontSubfamily"),M=k+" "+m,oA=e.getEnglishName("postScriptName");oA||(oA=k.replace(/\s/g,"")+"-"+m);var F={};for(var S in e.names)F[S]=e.names[S];F.uniqueID||(F.uniqueID={en:e.getEnglishName("manufacturer")+":"+M}),F.postScriptName||(F.postScriptName={en:oA}),F.preferredFamily||(F.preferredFamily=e.names.fontFamily),F.preferredSubfamily||(F.preferredSubfamily=e.names.fontSubfamily);var J=[],V=Kt.make(F,J),q=J.length>0?Lt.make(J):void 0,$=Tt.make(),AA=Rt.make(e.glyphs,{version:e.getEnglishName("version"),fullName:M,familyName:k,weightName:m,postScriptName:oA,unitsPerEm:e.unitsPerEm,fontBBox:[0,c.yMin,c.ascender,c.advanceWidthMax]}),_=e.metas&&Object.keys(e.metas).length>0?qt.make(e.metas):void 0,iA=[D,y,v,N,V,X,$,AA,L];q&&iA.push(q),e.tables.gsub&&iA.push(Vt.make(e.tables.gsub)),_&&iA.push(_);for(var b=Ot(iA),H=b.encode(),Z=Qg(H),IA=b.fields,z=!1,lA=0;lA>>1,o=e[I].tag;if(o===A)return I;o>>1,o=e[I];if(o===A)return I;o>>1;g=e[o];var i=g.start;if(i===A)return g;i0)return g=e[t-1],A>g.end?0:g}function ce(e,A){this.font=e,this.tableName=A}ce.prototype={searchTag:Ke,binSearch:Hg,getTable:function(e){var A=this.font.tables[this.tableName];return!A&&e&&(A=this.font.tables[this.tableName]=this.createDefaultTable()),A},getScriptNames:function(){var e=this.getTable();return e?e.scripts.map(function(A){return A.tag}):[]},getDefaultScriptName:function(){var e=this.getTable();if(e){for(var A=!1,g=0;g=0)return t[I].script;if(A){var o={tag:e,script:{defaultLangSys:{reserved:0,reqFeatureIndex:65535,featureIndexes:[]},langSysRecords:[]}};return t.splice(-1-I,0,o),o.script}}},getLangSysTable:function(e,A,g){var t=this.getScriptTable(e,g);if(t){if(!A||A==="dflt"||A==="DFLT")return t.defaultLangSys;var I=Ke(t.langSysRecords,A);if(I>=0)return t.langSysRecords[I].langSys;if(g){var o={tag:A,langSys:{reserved:0,reqFeatureIndex:65535,featureIndexes:[]}};return t.langSysRecords.splice(-1-I,0,o),o.langSys}}},getFeatureTable:function(e,A,g,t){var I=this.getLangSysTable(e,A,t);if(I){for(var o,i=I.featureIndexes,r=this.font.tables[this.tableName].features,C=0;C=r[B-1].tag,"Features must be added in alphabetical order."),o={tag:g,feature:{params:0,lookupListIndexes:[]}},r.push(o),i.push(B),o.feature}}},getLookupTables:function(e,A,g,t,I){var o=this.getFeatureTable(e,A,g,I),i=[];if(o){for(var r,C=o.lookupListIndexes,B=this.font.tables[this.tableName].lookups,n=0;n=0?g:-1;case 2:var t=Yg(e.ranges,A);return t?t.index+A-t.start:-1}},expandCoverage:function(e){if(e.format===1)return e.glyphs;for(var A=[],g=e.ranges,t=0;t1,'Multiple: "by" must be an array of two or more ids');var I=this.getLookupTables(g,t,e,2,!0)[0],o=Eg(I,1,{substFormat:1,coverage:{format:1,glyphs:[]},sequences:[]});W.assert(o.coverage.format===1,"Multiple: unable to modify coverage table format "+o.coverage.format);var i=A.sub,r=this.binSearch(o.coverage.glyphs,i);r<0&&(r=-1-r,o.coverage.glyphs.splice(r,0,i),o.sequences.splice(r,0,0)),o.sequences[r]=A.by};dA.prototype.addAlternate=function(e,A,g,t){var I=this.getLookupTables(g,t,e,3,!0)[0],o=Eg(I,1,{substFormat:1,coverage:{format:1,glyphs:[]},alternateSets:[]});W.assert(o.coverage.format===1,"Alternate: unable to modify coverage table format "+o.coverage.format);var i=A.sub,r=this.binSearch(o.coverage.glyphs,i);r<0&&(r=-1-r,o.coverage.glyphs.splice(r,0,i),o.alternateSets.splice(r,0,0)),o.alternateSets[r]=A.by};dA.prototype.addLigature=function(e,A,g,t){var I=this.getLookupTables(g,t,e,4,!0)[0],o=I.subtables[0];o||(o={substFormat:1,coverage:{format:1,glyphs:[]},ligatureSets:[]},I.subtables[0]=o),W.assert(o.coverage.format===1,"Ligature: unable to modify coverage table format "+o.coverage.format);var i=A.sub[0],r=A.sub.slice(1),C={ligGlyph:A.by,components:r},B=this.binSearch(o.coverage.glyphs,i);if(B>=0){for(var n=o.ligatureSets[B],Q=0;Q0?(o=e.parseByte(),A&I||(o=-o),o=g+o):(A&I)>0?o=g:o=g+e.parseShort(),o}function Pt(e,A,g){var t=new T.Parser(A,g);e.numberOfContours=t.parseShort(),e._xMin=t.parseShort(),e._yMin=t.parseShort(),e._xMax=t.parseShort(),e._yMax=t.parseShort();var I,o;if(e.numberOfContours>0){for(var i=e.endPointIndices=[],r=0;r0)for(var Q=t.parseByte(),a=0;a0){var E=[],h;if(B>0){for(var w=0;w=0,E.push(h);for(var u=0,l=0;l0?(I&2)>0?(y.dx=t.parseShort(),y.dy=t.parseShort()):y.matchedPoints=[t.parseUShort(),t.parseUShort()]:(I&2)>0?(y.dx=t.parseChar(),y.dy=t.parseChar()):y.matchedPoints=[t.parseByte(),t.parseByte()],(I&8)>0?y.xScale=y.yScale=t.parseF2Dot14():(I&64)>0?(y.xScale=t.parseF2Dot14(),y.yScale=t.parseF2Dot14()):(I&128)>0&&(y.xScale=t.parseF2Dot14(),y.scale01=t.parseF2Dot14(),y.scale10=t.parseF2Dot14(),y.yScale=t.parseF2Dot14()),e.components.push(y),D=!!(I&32)}if(I&256){e.instructionLength=t.parseUShort(),e.instructions=[];for(var v=0;vA.points.length-1||t.matchedPoints[1]>I.points.length-1)throw Error("Matched points out of range in "+A.name);var i=A.points[t.matchedPoints[0]],r=I.points[t.matchedPoints[1]],C={xScale:t.xScale,scale01:t.scale01,scale10:t.scale10,yScale:t.yScale,dx:0,dy:0};r=Te([r],C)[0],C.dx=i.x-r.x,C.dy=i.y-r.y,o=Te(I.points,C)}A.points=A.points.concat(o)}}return Zt(A.points)}function ts(e,A,g,t){for(var I=new MA.GlyphSet(t),o=0;o2)){var g=this.font,t=this._prepState;if(!t||t.ppem!==A){var I=this._fpgmState;if(!I){ZA.prototype=ss,I=this._fpgmState=new ZA("fpgm",g.tables.fpgm),I.funcs=[],I.font=g,exports.DEBUG&&(console.log("---EXEC FPGM---"),I.step=-1);try{Ae(I)}catch(B){console.log("Hinting error in FPGM:"+B),this._errorState=3;return}}ZA.prototype=I,t=this._prepState=new ZA("prep",g.tables.prep),t.ppem=A;var o=g.tables.cvt;if(o)for(var i=t.cvt=new Array(o.length),r=A/g.unitsPerEm,C=0;C1))try{return _t(e,t)}catch(B){this._errorState<1&&(console.log("Hinting error:"+B),console.log("Note: further hinting errors are silenced")),this._errorState=1;return}}};_t=function(e,A){var g=A.ppem/A.font.unitsPerEm,t=g,I=e.components,o,i,r;if(ZA.prototype=A,!I)r=new ZA("glyf",e.instructions),exports.DEBUG&&(console.log("---EXEC GLYPH---"),r.step=-1),Ig(e,r,g,t),i=r.gZone;else{var C=A.font;i=[],o=[];for(var B=0;B=176&&o<=183)t+=o-176+1;else if(o>=184&&o<=191)t+=(o-184+1)*2;else if(A&&I===1&&o===27)break;while(I>0);e.ip=t}function Tg(e,A){exports.DEBUG&&console.log(A.step,"SVTCA["+e.axis+"]"),A.fv=A.pv=A.dpv=e}function Vg(e,A){exports.DEBUG&&console.log(A.step,"SPVTCA["+e.axis+"]"),A.pv=A.dpv=e}function qg(e,A){exports.DEBUG&&console.log(A.step,"SFVTCA["+e.axis+"]"),A.fv=e}function Og(e,A){var g=A.stack,t=g.pop(),I=g.pop(),o=A.z2[t],i=A.z1[I];exports.DEBUG&&console.log("SPVTL["+e+"]",t,I);var r,C;e?(r=o.y-i.y,C=i.x-o.x):(r=i.x-o.x,C=i.y-o.y),A.pv=A.dpv=de(r,C)}function Wg(e,A){var g=A.stack,t=g.pop(),I=g.pop(),o=A.z2[t],i=A.z1[I];exports.DEBUG&&console.log("SFVTL["+e+"]",t,I);var r,C;e?(r=o.y-i.y,C=i.x-o.x):(r=i.x-o.x,C=i.y-o.y),A.fv=de(r,C)}function as(e){var A=e.stack,g=A.pop(),t=A.pop();exports.DEBUG&&console.log(e.step,"SPVFS[]",g,t),e.pv=e.dpv=de(t,g)}function Qs(e){var A=e.stack,g=A.pop(),t=A.pop();exports.DEBUG&&console.log(e.step,"SPVFS[]",g,t),e.fv=de(t,g)}function Es(e){var A=e.stack,g=e.pv;exports.DEBUG&&console.log(e.step,"GPV[]"),A.push(g.x*16384),A.push(g.y*16384)}function ls(e){var A=e.stack,g=e.fv;exports.DEBUG&&console.log(e.step,"GFV[]"),A.push(g.x*16384),A.push(g.y*16384)}function cs(e){e.fv=e.pv,exports.DEBUG&&console.log(e.step,"SFVTPV[]")}function hs(e){var A=e.stack,g=A.pop(),t=A.pop(),I=A.pop(),o=A.pop(),i=A.pop(),r=e.z0,C=e.z1,B=r[g],n=r[t],Q=C[I],a=C[o],E=e.z2[i];exports.DEBUG&&console.log("ISECT[], ",g,t,I,o,i);var h=B.x,w=B.y,u=n.x,l=n.y,f=Q.x,c=Q.y,D=a.x,y=a.y,v=(h-u)*(c-y)-(w-l)*(f-D),N=h*l-w*u,L=f*y-c*D;E.x=(N*(f-D)-L*(h-u))/v,E.y=(N*(c-y)-L*(w-l))/v}function us(e){e.rp0=e.stack.pop(),exports.DEBUG&&console.log(e.step,"SRP0[]",e.rp0)}function ds(e){e.rp1=e.stack.pop(),exports.DEBUG&&console.log(e.step,"SRP1[]",e.rp1)}function fs(e){e.rp2=e.stack.pop(),exports.DEBUG&&console.log(e.step,"SRP2[]",e.rp2)}function ws(e){var A=e.stack.pop();switch(exports.DEBUG&&console.log(e.step,"SZP0[]",A),e.zp0=A,A){case 0:e.tZone||Je(e),e.z0=e.tZone;break;case 1:e.z0=e.gZone;break;default:throw new Error("Invalid zone pointer")}}function ys(e){var A=e.stack.pop();switch(exports.DEBUG&&console.log(e.step,"SZP1[]",A),e.zp1=A,A){case 0:e.tZone||Je(e),e.z1=e.tZone;break;case 1:e.z1=e.gZone;break;default:throw new Error("Invalid zone pointer")}}function ps(e){var A=e.stack.pop();switch(exports.DEBUG&&console.log(e.step,"SZP2[]",A),e.zp2=A,A){case 0:e.tZone||Je(e),e.z2=e.tZone;break;case 1:e.z2=e.gZone;break;default:throw new Error("Invalid zone pointer")}}function Ds(e){var A=e.stack.pop();switch(exports.DEBUG&&console.log(e.step,"SZPS[]",A),e.zp0=e.zp1=e.zp2=A,A){case 0:e.tZone||Je(e),e.z0=e.z1=e.z2=e.tZone;break;case 1:e.z0=e.z1=e.z2=e.gZone;break;default:throw new Error("Invalid zone pointer")}}function ms(e){e.loop=e.stack.pop(),exports.DEBUG&&console.log(e.step,"SLOOP[]",e.loop)}function Fs(e){exports.DEBUG&&console.log(e.step,"RTG[]"),e.round=AI}function ks(e){exports.DEBUG&&console.log(e.step,"RTHG[]"),e.round=Cs}function vs(e){var A=e.stack.pop();exports.DEBUG&&console.log(e.step,"SMD[]",A),e.minDis=A/64}function Ss(e){exports.DEBUG&&console.log(e.step,"ELSE[]"),gI(e,!1)}function Gs(e){var A=e.stack.pop();exports.DEBUG&&console.log(e.step,"JMPR[]",A),e.ip+=A-1}function Rs(e){var A=e.stack.pop();exports.DEBUG&&console.log(e.step,"SCVTCI[]",A),e.cvCutIn=A/64}function Us(e){var A=e.stack;exports.DEBUG&&console.log(e.step,"DUP[]"),A.push(A[A.length-1])}function Ve(e){exports.DEBUG&&console.log(e.step,"POP[]"),e.stack.pop()}function Ns(e){exports.DEBUG&&console.log(e.step,"CLEAR[]"),e.stack.length=0}function bs(e){var A=e.stack,g=A.pop(),t=A.pop();exports.DEBUG&&console.log(e.step,"SWAP[]"),A.push(g),A.push(t)}function Ls(e){var A=e.stack;exports.DEBUG&&console.log(e.step,"DEPTH[]"),A.push(A.length)}function Ms(e){var A=e.stack,g=A.pop(),t=A.pop();exports.DEBUG&&console.log(e.step,"LOOPCALL[]",g,t);var I=e.ip,o=e.prog;e.prog=e.funcs[g];for(var i=0;i1?"loop "+(A.loop-r)+": ":"")+"SHP["+(e?"rp1":"rp2")+"]",B)}A.loop=1}function jg(e,A){var g=A.stack,t=e?A.rp1:A.rp2,I=(e?A.z0:A.z1)[t],o=A.fv,i=A.pv,r=g.pop(),C=A.z2[A.contours[r]],B=C;exports.DEBUG&&console.log(A.step,"SHC["+e+"]",r);var n=i.distance(I,I,!1,!0);do B!==I&&o.setRelative(B,B,n,i),B=B.nextPointOnContour;while(B!==C)}function zg(e,A){var g=A.stack,t=e?A.rp1:A.rp2,I=(e?A.z0:A.z1)[t],o=A.fv,i=A.pv,r=g.pop();exports.DEBUG&&console.log(A.step,"SHZ["+e+"]",r);var C;switch(r){case 0:C=A.tZone;break;case 1:C=A.gZone;break;default:throw new Error("Invalid zone")}for(var B,n=i.distance(I,I,!1,!0),Q=C.length-2,a=0;a1?"loop "+(e.loop-g)+": ":"")+"SHPIX[]",i,I),t.setRelative(r,r,I),t.touch(r)}e.loop=1}function Ts(e){for(var A=e.stack,g=e.rp1,t=e.rp2,I=e.loop,o=e.z0[g],i=e.z1[t],r=e.fv,C=e.dpv,B=e.z2;I--;){var n=A.pop(),Q=B[n];exports.DEBUG&&console.log(e.step,(e.loop>1?"loop "+(e.loop-I)+": ":"")+"IP[]",n,g,"<->",t),r.interpolate(Q,o,i,C),r.touch(Q)}e.loop=1}function _g(e,A){var g=A.stack,t=g.pop()/64,I=g.pop(),o=A.z1[I],i=A.z0[A.rp0],r=A.fv,C=A.pv;r.setRelative(o,i,t,C),r.touch(o),exports.DEBUG&&console.log(A.step,"MSIRP["+e+"]",t,I),A.rp1=A.rp0,A.rp2=I,e&&(A.rp0=I)}function Vs(e){for(var A=e.stack,g=e.rp0,t=e.z0[g],I=e.loop,o=e.fv,i=e.pv,r=e.z1;I--;){var C=A.pop(),B=r[C];exports.DEBUG&&console.log(e.step,(e.loop>1?"loop "+(e.loop-I)+": ":"")+"ALIGNRP[]",C),o.setRelative(B,t,0,i),o.touch(B)}e.loop=1}function qs(e){exports.DEBUG&&console.log(e.step,"RTDG[]"),e.round=rs}function $g(e,A){var g=A.stack,t=g.pop(),I=g.pop(),o=A.z0[I],i=A.fv,r=A.pv,C=A.cvt[t];exports.DEBUG&&console.log(A.step,"MIAP["+e+"]",t,"(",C,")",I);var B=r.distance(o,Ee);e&&(Math.abs(B-C)",r),A.stack.push(Math.round(r*64))}function zs(e){exports.DEBUG&&console.log(e.step,"MPPEM[]"),e.stack.push(e.ppem)}function _s(e){exports.DEBUG&&console.log(e.step,"FLIPON[]"),e.autoFlip=!0}function $s(e){var A=e.stack,g=A.pop(),t=A.pop();exports.DEBUG&&console.log(e.step,"LT[]",g,t),A.push(tg?1:0)}function ga(e){var A=e.stack,g=A.pop(),t=A.pop();exports.DEBUG&&console.log(e.step,"GTEQ[]",g,t),A.push(t>=g?1:0)}function ta(e){var A=e.stack,g=A.pop(),t=A.pop();exports.DEBUG&&console.log(e.step,"EQ[]",g,t),A.push(g===t?1:0)}function Ia(e){var A=e.stack,g=A.pop(),t=A.pop();exports.DEBUG&&console.log(e.step,"NEQ[]",g,t),A.push(g!==t?1:0)}function oa(e){var A=e.stack,g=A.pop();exports.DEBUG&&console.log(e.step,"ODD[]",g),A.push(Math.trunc(g)%2?1:0)}function ia(e){var A=e.stack,g=A.pop();exports.DEBUG&&console.log(e.step,"EVEN[]",g),A.push(Math.trunc(g)%2?0:1)}function ra(e){var A=e.stack.pop();exports.DEBUG&&console.log(e.step,"IF[]",A),A||(gI(e,!0),exports.DEBUG&&console.log(e.step,"EIF[]"))}function Ca(e){exports.DEBUG&&console.log(e.step,"EIF[]")}function na(e){var A=e.stack,g=A.pop(),t=A.pop();exports.DEBUG&&console.log(e.step,"AND[]",g,t),A.push(g&&t?1:0)}function Ba(e){var A=e.stack,g=A.pop(),t=A.pop();exports.DEBUG&&console.log(e.step,"OR[]",g,t),A.push(g||t?1:0)}function sa(e){var A=e.stack,g=A.pop();exports.DEBUG&&console.log(e.step,"NOT[]",g),A.push(g?0:1)}function qe(e,A){var g=A.stack,t=g.pop(),I=A.fv,o=A.pv,i=A.ppem,r=A.deltaBase+(e-1)*16,C=A.deltaShift,B=A.z0;exports.DEBUG&&console.log(A.step,"DELTAP["+e+"]",t,g);for(var n=0;n>4);if(E===i){var h=(a&15)-8;h>=0&&h++,exports.DEBUG&&console.log(A.step,"DELTAPFIX",Q,"by",h*C);var w=B[Q];I.setRelative(w,w,h*C,o)}}}function aa(e){var A=e.stack,g=A.pop();exports.DEBUG&&console.log(e.step,"SDB[]",g),e.deltaBase=g}function Qa(e){var A=e.stack,g=A.pop();exports.DEBUG&&console.log(e.step,"SDS[]",g),e.deltaShift=Math.pow(.5,g)}function Ea(e){var A=e.stack,g=A.pop(),t=A.pop();exports.DEBUG&&console.log(e.step,"ADD[]",g,t),A.push(t+g)}function la(e){var A=e.stack,g=A.pop(),t=A.pop();exports.DEBUG&&console.log(e.step,"SUB[]",g,t),A.push(t-g)}function ca(e){var A=e.stack,g=A.pop(),t=A.pop();exports.DEBUG&&console.log(e.step,"DIV[]",g,t),A.push(t*64/g)}function ha(e){var A=e.stack,g=A.pop(),t=A.pop();exports.DEBUG&&console.log(e.step,"MUL[]",g,t),A.push(t*g/64)}function ua(e){var A=e.stack,g=A.pop();exports.DEBUG&&console.log(e.step,"ABS[]",g),A.push(Math.abs(g))}function da(e){var A=e.stack,g=A.pop();exports.DEBUG&&console.log(e.step,"NEG[]",g),A.push(-g)}function fa(e){var A=e.stack,g=A.pop();exports.DEBUG&&console.log(e.step,"FLOOR[]",g),A.push(Math.floor(g/64)*64)}function wa(e){var A=e.stack,g=A.pop();exports.DEBUG&&console.log(e.step,"CEILING[]",g),A.push(Math.ceil(g/64)*64)}function Fe(e,A){var g=A.stack,t=g.pop();exports.DEBUG&&console.log(A.step,"ROUND[]"),g.push(A.round(t/64)*64)}function ya(e){var A=e.stack,g=A.pop(),t=A.pop();exports.DEBUG&&console.log(e.step,"WCVTF[]",g,t),e.cvt[t]=g*e.ppem/e.font.unitsPerEm}function Oe(e,A){var g=A.stack,t=g.pop(),I=A.ppem,o=A.deltaBase+(e-1)*16,i=A.deltaShift;exports.DEBUG&&console.log(A.step,"DELTAC["+e+"]",t,g);for(var r=0;r>4);if(n===I){var Q=(B&15)-8;Q>=0&&Q++;var a=Q*i;exports.DEBUG&&console.log(A.step,"DELTACFIX",C,"by",a),A.cvt[C]+=a}}}function pa(e){var A=e.stack.pop();exports.DEBUG&&console.log(e.step,"SROUND[]",A),e.round=eI;var g;switch(A&192){case 0:g=.5;break;case 64:g=1;break;case 128:g=2;break;default:throw new Error("invalid SROUND value")}switch(e.srPeriod=g,A&48){case 0:e.srPhase=0;break;case 16:e.srPhase=.25*g;break;case 32:e.srPhase=.5*g;break;case 48:e.srPhase=.75*g;break;default:throw new Error("invalid SROUND value")}A&=15,A===0?e.srThreshold=0:e.srThreshold=(A/8-.5)*g}function Da(e){var A=e.stack.pop();exports.DEBUG&&console.log(e.step,"S45ROUND[]",A),e.round=eI;var g;switch(A&192){case 0:g=Math.sqrt(2)/2;break;case 64:g=Math.sqrt(2);break;case 128:g=2*Math.sqrt(2);break;default:throw new Error("invalid S45ROUND value")}switch(e.srPeriod=g,A&48){case 0:e.srPhase=0;break;case 16:e.srPhase=.25*g;break;case 32:e.srPhase=.5*g;break;case 48:e.srPhase=.75*g;break;default:throw new Error("invalid S45ROUND value")}A&=15,A===0?e.srThreshold=0:e.srThreshold=(A/8-.5)*g}function ma(e){exports.DEBUG&&console.log(e.step,"ROFF[]"),e.round=is}function Fa(e){exports.DEBUG&&console.log(e.step,"RUTG[]"),e.round=ns}function ka(e){exports.DEBUG&&console.log(e.step,"RDTG[]"),e.round=Bs}function va(e){var A=e.stack.pop();exports.DEBUG&&console.log(e.step,"SCANCTRL[]",A)}function gt(e,A){var g=A.stack,t=g.pop(),I=g.pop(),o=A.z2[t],i=A.z1[I];exports.DEBUG&&console.log(A.step,"SDPVTL["+e+"]",t,I);var r,C;e?(r=o.y-i.y,C=i.x-o.x):(r=i.x-o.x,C=i.y-o.y),A.dpv=de(r,C)}function Sa(e){var A=e.stack,g=A.pop(),t=0;exports.DEBUG&&console.log(e.step,"GETINFO[]",g),g&1&&(t=35),g&32&&(t|=4096),A.push(t)}function Ga(e){var A=e.stack,g=A.pop(),t=A.pop(),I=A.pop();exports.DEBUG&&console.log(e.step,"ROLL[]"),A.push(t),A.push(g),A.push(I)}function Ra(e){var A=e.stack,g=A.pop(),t=A.pop();exports.DEBUG&&console.log(e.step,"MAX[]",g,t),A.push(Math.max(t,g))}function Ua(e){var A=e.stack,g=A.pop(),t=A.pop();exports.DEBUG&&console.log(e.step,"MIN[]",g,t),A.push(Math.min(t,g))}function Na(e){var A=e.stack.pop();exports.DEBUG&&console.log(e.step,"SCANTYPE[]",A)}function ba(e){var A=e.stack.pop(),g=e.stack.pop();switch(exports.DEBUG&&console.log(e.step,"INSTCTRL[]",A,g),A){case 1:e.inhibitGridFit=!!g;return;case 2:e.ignoreCvt=!!g;return;default:throw new Error("invalid INSTCTRL[] selector")}}function qA(e,A){var g=A.stack,t=A.prog,I=A.ip;exports.DEBUG&&console.log(A.step,"PUSHB["+e+"]");for(var o=0;o=0?1:-1,u=Math.abs(u),e&&(f=o.cvt[r],t&&Math.abs(u-f)":"_")+(t?"R":"_")+(I===0?"Gr":I===1?"Bl":I===2?"Wh":"")+"]",e?r+"("+o.cvt[r]+","+f+")":"",C,"(d =",w,"->",l*u,")"),o.rp1=o.rp0,o.rp2=C,A&&(o.rp0=C)}zt=[Tg.bind(void 0,xA),Tg.bind(void 0,NA),Vg.bind(void 0,xA),Vg.bind(void 0,NA),qg.bind(void 0,xA),qg.bind(void 0,NA),Og.bind(void 0,0),Og.bind(void 0,1),Wg.bind(void 0,0),Wg.bind(void 0,1),as,Qs,Es,ls,cs,hs,us,ds,fs,ws,ys,ps,Ds,ms,Fs,ks,vs,Ss,Gs,Rs,void 0,void 0,Us,Ve,Ns,bs,Ls,xs,Hs,void 0,void 0,void 0,Ms,Js,Ys,void 0,Pg.bind(void 0,0),Pg.bind(void 0,1),Zg.bind(void 0,xA),Zg.bind(void 0,NA),Xg.bind(void 0,0),Xg.bind(void 0,1),jg.bind(void 0,0),jg.bind(void 0,1),zg.bind(void 0,0),zg.bind(void 0,1),Ks,Ts,_g.bind(void 0,0),_g.bind(void 0,1),Vs,qs,$g.bind(void 0,0),$g.bind(void 0,1),Os,Ws,Ps,Zs,Xs,js,At.bind(void 0,0),At.bind(void 0,1),void 0,et.bind(void 0,0),et.bind(void 0,1),zs,void 0,_s,void 0,void 0,$s,Aa,ea,ga,ta,Ia,oa,ia,ra,Ca,na,Ba,sa,qe.bind(void 0,1),aa,Qa,Ea,la,ca,ha,ua,da,fa,wa,Fe.bind(void 0,0),Fe.bind(void 0,1),Fe.bind(void 0,2),Fe.bind(void 0,3),void 0,void 0,void 0,void 0,ya,qe.bind(void 0,2),qe.bind(void 0,3),Oe.bind(void 0,1),Oe.bind(void 0,2),Oe.bind(void 0,3),pa,Da,void 0,void 0,ma,void 0,Fa,ka,Ve,Ve,void 0,void 0,void 0,void 0,void 0,va,gt.bind(void 0,0),gt.bind(void 0,1),Sa,void 0,Ga,Ra,Ua,Na,ba,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,qA.bind(void 0,1),qA.bind(void 0,2),qA.bind(void 0,3),qA.bind(void 0,4),qA.bind(void 0,5),qA.bind(void 0,6),qA.bind(void 0,7),qA.bind(void 0,8),OA.bind(void 0,1),OA.bind(void 0,2),OA.bind(void 0,3),OA.bind(void 0,4),OA.bind(void 0,5),OA.bind(void 0,6),OA.bind(void 0,7),OA.bind(void 0,8),K.bind(void 0,0,0,0,0,0),K.bind(void 0,0,0,0,0,1),K.bind(void 0,0,0,0,0,2),K.bind(void 0,0,0,0,0,3),K.bind(void 0,0,0,0,1,0),K.bind(void 0,0,0,0,1,1),K.bind(void 0,0,0,0,1,2),K.bind(void 0,0,0,0,1,3),K.bind(void 0,0,0,1,0,0),K.bind(void 0,0,0,1,0,1),K.bind(void 0,0,0,1,0,2),K.bind(void 0,0,0,1,0,3),K.bind(void 0,0,0,1,1,0),K.bind(void 0,0,0,1,1,1),K.bind(void 0,0,0,1,1,2),K.bind(void 0,0,0,1,1,3),K.bind(void 0,0,1,0,0,0),K.bind(void 0,0,1,0,0,1),K.bind(void 0,0,1,0,0,2),K.bind(void 0,0,1,0,0,3),K.bind(void 0,0,1,0,1,0),K.bind(void 0,0,1,0,1,1),K.bind(void 0,0,1,0,1,2),K.bind(void 0,0,1,0,1,3),K.bind(void 0,0,1,1,0,0),K.bind(void 0,0,1,1,0,1),K.bind(void 0,0,1,1,0,2),K.bind(void 0,0,1,1,0,3),K.bind(void 0,0,1,1,1,0),K.bind(void 0,0,1,1,1,1),K.bind(void 0,0,1,1,1,2),K.bind(void 0,0,1,1,1,3),K.bind(void 0,1,0,0,0,0),K.bind(void 0,1,0,0,0,1),K.bind(void 0,1,0,0,0,2),K.bind(void 0,1,0,0,0,3),K.bind(void 0,1,0,0,1,0),K.bind(void 0,1,0,0,1,1),K.bind(void 0,1,0,0,1,2),K.bind(void 0,1,0,0,1,3),K.bind(void 0,1,0,1,0,0),K.bind(void 0,1,0,1,0,1),K.bind(void 0,1,0,1,0,2),K.bind(void 0,1,0,1,0,3),K.bind(void 0,1,0,1,1,0),K.bind(void 0,1,0,1,1,1),K.bind(void 0,1,0,1,1,2),K.bind(void 0,1,0,1,1,3),K.bind(void 0,1,1,0,0,0),K.bind(void 0,1,1,0,0,1),K.bind(void 0,1,1,0,0,2),K.bind(void 0,1,1,0,0,3),K.bind(void 0,1,1,0,1,0),K.bind(void 0,1,1,0,1,1),K.bind(void 0,1,1,0,1,2),K.bind(void 0,1,1,0,1,3),K.bind(void 0,1,1,1,0,0),K.bind(void 0,1,1,1,0,1),K.bind(void 0,1,1,1,0,2),K.bind(void 0,1,1,1,0,3),K.bind(void 0,1,1,1,1,0),K.bind(void 0,1,1,1,1,1),K.bind(void 0,1,1,1,1,2),K.bind(void 0,1,1,1,1,3)];function re(e){this.char=e,this.state={},this.activeState=null}function lg(e,A,g){this.contextName=g,this.startIndex=e,this.endOffset=A}function La(e,A,g){this.contextName=e,this.openRange=null,this.ranges=[],this.checkStart=A,this.checkEnd=g}function FA(e,A){this.context=e,this.index=A,this.length=e.length,this.current=e[A],this.backtrack=e.slice(0,A),this.lookahead=e.slice(A+1)}function xe(e){this.eventId=e,this.subscribers=[]}function Ma(e){var A=this,g=["start","end","next","newToken","contextStart","contextEnd","insertToken","removeToken","removeRange","replaceToken","replaceRange","composeRUD","updateContextsRanges"];g.forEach(function(I){Object.defineProperty(A.events,I,{value:new xe(I)})}),e&&g.forEach(function(I){var o=e[I];typeof o=="function"&&A.events[I].subscribe(o)});var t=["insertToken","removeToken","removeRange","replaceToken","replaceRange","composeRUD"];t.forEach(function(I){A.events[I].subscribe(A.updateContextsRanges)})}function BA(e){this.tokens=[],this.registeredContexts={},this.contextCheckers=[],this.events={},this.registeredModifiers=[],Ma.call(this,e)}re.prototype.setState=function(e,A){return this.state[e]=A,this.activeState={key:e,value:this.state[e]},this.activeState};re.prototype.getState=function(e){return this.state[e]||null};BA.prototype.inboundIndex=function(e){return e>=0&&e0&&e<=this.lookahead.length):return this.lookahead[e-1];default:return null}};BA.prototype.rangeToText=function(e){if(e instanceof lg)return this.getRangeTokens(e).map(function(A){return A.char}).join("")};BA.prototype.getText=function(){return this.tokens.map(function(e){return e.char}).join("")};BA.prototype.getContext=function(e){var A=this.registeredContexts[e];return A||null};BA.prototype.on=function(e,A){var g=this.events[e];return g?g.subscribe(A):null};BA.prototype.dispatch=function(e,A){var g=this,t=this.events[e];t instanceof xe&&t.subscribers.forEach(function(I){I.apply(g,A||[])})};BA.prototype.registerContextChecker=function(e,A,g){if(this.getContext(e))return{FAIL:"context name '"+e+"' is already registered."};if(typeof A!="function")return{FAIL:"missing context start check."};if(typeof g!="function")return{FAIL:"missing context end check."};var t=new La(e,A,g);return this.registeredContexts[e]=t,this.contextCheckers.push(t),t};BA.prototype.getRangeTokens=function(e){var A=e.startIndex+e.endOffset;return[].concat(this.tokens.slice(e.startIndex,A))};BA.prototype.getContextRanges=function(e){var A=this.getContext(e);return A?A.ranges:{FAIL:"context checker '"+e+"' is not registered."}};BA.prototype.resetContextsRanges=function(){var e=this.registeredContexts;for(var A in e)if(e.hasOwnProperty(A)){var g=e[A];g.ranges=[]}};BA.prototype.updateContextsRanges=function(){this.resetContextsRanges();for(var e=this.tokens.map(function(t){return t.char}),A=0;A=I.start&&e<=I.end){var o=e-I.start;return I.index+o}}break;default:return-1}return-1}function xa(e,A){var g=fe(e,A.coverage);return g===-1?null:e+A.deltaGlyphId}function Ha(e,A){var g=fe(e,A.coverage);return g===-1?null:A.substitute[g]}function We(e,A){for(var g=[],t=0;t=0;g--){var t=A[g],I=tI(t),o=jA(t);if(!I&&!o)return!0;if(I)return!1}return!1}function AQ(e){if(tI(e.current))return!1;for(var A=0;A0}g("fontFamily"),g("weightName"),g("manufacturer"),g("copyright"),g("version"),this.unitsPerEm>0};tA.prototype.toTables=function(){return _B.fontToTable(this)};tA.prototype.toBuffer=function(){return console.warn("Font.toBuffer is deprecated. Use Font.toArrayBuffer instead."),this.toArrayBuffer()};tA.prototype.toArrayBuffer=function(){for(var e=this.toTables(),A=e.encode(),g=new ArrayBuffer(A.length),t=new Uint8Array(g),I=0;I=1.2&&(I.markGlyphSets=g.parsePointer(pQ)),I}var mQ={parse:DQ},kA=new Array(10);kA[1]=function(){var A=this.offset+this.relativeOffset,g=this.parseUShort();if(g===1)return{posFormat:1,coverage:this.parsePointer(p.coverage),value:this.parseValueRecord()};if(g===2)return{posFormat:2,coverage:this.parsePointer(p.coverage),values:this.parseValueRecordList()};W.assert(!1,"0x"+A.toString(16)+": GPOS lookup type 1 format must be 1 or 2.")};kA[2]=function(){var A=this.offset+this.relativeOffset,g=this.parseUShort();W.assert(g===1||g===2,"0x"+A.toString(16)+": GPOS lookup type 2 format must be 1 or 2.");var t=this.parsePointer(p.coverage),I=this.parseUShort(),o=this.parseUShort();if(g===1)return{posFormat:g,coverage:t,valueFormat1:I,valueFormat2:o,pairSets:this.parseList(p.pointer(p.list(function(){return{secondGlyph:this.parseUShort(),value1:this.parseValueRecord(I),value2:this.parseValueRecord(o)}})))};if(g===2){var i=this.parsePointer(p.classDef),r=this.parsePointer(p.classDef),C=this.parseUShort(),B=this.parseUShort();return{posFormat:g,coverage:t,valueFormat1:I,valueFormat2:o,classDef1:i,classDef2:r,class1Count:C,class2Count:B,classRecords:this.parseList(C,p.list(B,function(){return{value1:this.parseValueRecord(I),value2:this.parseValueRecord(o)}}))}}};kA[3]=function(){return{error:"GPOS Lookup 3 not supported"}};kA[4]=function(){return{error:"GPOS Lookup 4 not supported"}};kA[5]=function(){return{error:"GPOS Lookup 5 not supported"}};kA[6]=function(){return{error:"GPOS Lookup 6 not supported"}};kA[7]=function(){return{error:"GPOS Lookup 7 not supported"}};kA[8]=function(){return{error:"GPOS Lookup 8 not supported"}};kA[9]=function(){return{error:"GPOS Lookup 9 not supported"}};function FQ(e,A){A=A||0;var g=new p(e,A),t=g.parseVersion(1);return W.argument(t===1||t===1.1,"Unsupported GPOS table version "+t),t===1?{version:t,scripts:g.parseScriptList(),features:g.parseFeatureList(),lookups:g.parseLookupList(kA)}:{version:t,scripts:g.parseScriptList(),features:g.parseFeatureList(),lookups:g.parseLookupList(kA),variations:g.parseFeatureVariationsList()}}var kQ=new Array(10);function vQ(e){return new Y.Table("GPOS",[{name:"version",type:"ULONG",value:65536},{name:"scripts",type:"TABLE",value:new Y.ScriptList(e.scripts)},{name:"features",type:"TABLE",value:new Y.FeatureList(e.features)},{name:"lookups",type:"TABLE",value:new Y.LookupList(e.lookups,kQ)}])}var SQ={parse:FQ,make:vQ};function GQ(e){var A={};e.skip("uShort");var g=e.parseUShort();W.argument(g===0,"Unsupported kern sub-table version."),e.skip("uShort",2);var t=e.parseUShort();e.skip("uShort",3);for(var I=0;I1&&console.warn("Only the first kern subtable is supported."),e.skip("uLong");var t=e.parseUShort(),I=t&255;if(e.skip("uShort"),I===0){var o=e.parseUShort();e.skip("uShort",3);for(var i=0;i"u",I=t&&!g.isUrl?MQ:JQ;return new Promise(function(o,i){I(e,function(r,C){if(r){if(A)return A(r);i(r)}var B;try{B=ug(C,g)}catch(n){if(A)return A(n,null);i(n)}if(A)return A(null,B);o(B)})})}function YQ(e,A){var g=require("fs"),t=g.readFileSync(e);return ug(Wt(t),A)}var og=Object.freeze({__proto__:null,Font:tA,Glyph:uA,Path:QA,BoundingBox:VA,_parse:T,parse:ug,load:HQ,loadSync:YQ});const KQ=()=>aI(()=>import("./ft_render-ByO_jG18.js"),[]);let R=null,le=0;const TQ=new Promise(e=>{KQ().then(A=>{A.default().then(g=>{R=g,e()})})});function rt(e){return e/65536}function pA(e){return e/64}function ne(e){return e>=0?e:e+256}let oI,iI,rI,dg,CI,nI,BI;async function VQ(){if(await TQ,R._init_constants(),oI=R.cwrap("FT_New_Memory_Face","number",["number","number","number","number","number"]),iI=R.cwrap("FT_Set_Char_Size","number",["number","number","number","number","number"]),rI=R.cwrap("FT_Set_Pixel_Sizes","number",["number","number","number"]),dg=R.cwrap("FT_Get_Char_Index","number",["number","number"]),CI=R.cwrap("FT_Load_Glyph","number",["number","number","number"]),nI=R.cwrap("FT_Get_Sfnt_Table","number",["number","number"]),R.cwrap("FT_Get_Kerning","number",["number","number","number","number","number"]),BI=R.cwrap("FT_Done_Face","number",["number"]),!le){let e=R._malloc(4);try{let A=R.ccall("FT_Init_FreeType","number",["number"],[e]);if(A)throw new Error(`error in FT_Init_FreeType: ${A}`);le=R.getValue(e,"i32")}finally{R._free(e)}}}function qQ(e,A){let g,t;if(e instanceof ArrayBuffer)t=e.byteLength;else if(e instanceof Uint8Array)t=e.byteLength;else if(e&&typeof e.length=="number")t=e.length;else throw new Error("Invalid font source format");let I={ptr:0,font:R._malloc(t)};const o=e instanceof ArrayBuffer?new Uint8Array(e):e;R.writeArrayToMemory(o,I.font);let i=R._malloc(4);try{if(g=oI(le,I.font,t,0,i),g)throw new Error(`error in FT_New_Memory_Face: ${g}`);I.ptr=R.getValue(i,"i32")}finally{R._free(i)}if(g=iI(I.ptr,0,A*64,300,300),g)throw new Error(`error in FT_Set_Char_Size: ${g}`);if(g=rI(I.ptr,0,A),g)throw new Error(`error in FT_Set_Pixel_Sizes: ${g}`);let r=R.getValue(I.ptr+R.OFFSET_FACE_UNITS_PER_EM,"i16"),C=R.getValue(I.ptr+R.OFFSET_FACE_ASCENDER,"i16"),B=R.getValue(I.ptr+R.OFFSET_FACE_DESCENDER,"i16"),n=R.getValue(I.ptr+R.OFFSET_FACE_HEIGHT,"i16");return Object.assign(I,{units_per_em:r,ascender:C,descender:B,height:n})}function OQ(e){let A=nI(e.ptr,R.FT_SFNT_OS2);if(!A)throw new Error("os/2 table not found for this font");let g=R.getValue(A+R.OFFSET_TT_OS2_ASCENDER,"i16"),t=R.getValue(A+R.OFFSET_TT_OS2_DESCENDER,"i16"),I=R.getValue(A+R.OFFSET_TT_OS2_LINEGAP,"i16");return{typoAscent:g,typoDescent:t,typoLineGap:I}}function Ze(e,A){return dg(e.ptr,A)!==0}function WQ(e,A,g={}){let t=dg(e.ptr,A);if(t===0)throw new Error(`glyph does not exist for codepoint ${A}`);let I=R.FT_LOAD_RENDER;g.mono?I|=R.FT_LOAD_TARGET_MONO:g.lcd?I|=R.FT_LOAD_TARGET_LCD:g.lcd_v?I|=R.FT_LOAD_TARGET_LCD_V:g.autohint_strong?I|=R.FT_LOAD_TARGET_NORMAL:I|=R.FT_LOAD_TARGET_LIGHT,g.autohint_off?I|=R.FT_LOAD_NO_AUTOHINT:I|=R.FT_LOAD_FORCE_AUTOHINT,g.use_color_info&&(I|=R.FT_LOAD_COLOR);let o=CI(e.ptr,t,I);if(o)throw new Error(`error in FT_Load_Glyph: ${o}`);let i=R.getValue(e.ptr+R.OFFSET_FACE_GLYPH,"i32"),r={glyph_index:R.getValue(i+R.OFFSET_GLYPH_INDEX,"i32"),metrics:{width:pA(R.getValue(i+R.OFFSET_GLYPH_METRICS_WIDTH,"i32")),height:pA(R.getValue(i+R.OFFSET_GLYPH_METRICS_HEIGHT,"i32")),horiBearingX:pA(R.getValue(i+R.OFFSET_GLYPH_METRICS_HORI_BEARING_X,"i32")),horiBearingY:pA(R.getValue(i+R.OFFSET_GLYPH_METRICS_HORI_BEARING_Y,"i32")),horiAdvance:pA(R.getValue(i+R.OFFSET_GLYPH_METRICS_HORI_ADVANCE,"i32")),vertBearingX:pA(R.getValue(i+R.OFFSET_GLYPH_METRICS_VERT_BEARING_X,"i32")),vertBearingY:pA(R.getValue(i+R.OFFSET_GLYPH_METRICS_VERT_BEARING_Y,"i32")),vertAdvance:pA(R.getValue(i+R.OFFSET_GLYPH_METRICS_VERT_ADVANCE,"i32"))},linearHoriAdvance:rt(R.getValue(i+R.OFFSET_GLYPH_LINEAR_HORI_ADVANCE,"i32")),linearVertAdvance:rt(R.getValue(i+R.OFFSET_GLYPH_LINEAR_VERT_ADVANCE,"i32")),advance:{x:pA(R.getValue(i+R.OFFSET_GLYPH_ADVANCE_X,"i32")),y:pA(R.getValue(i+R.OFFSET_GLYPH_ADVANCE_Y,"i32"))},bitmap:{width:R.getValue(i+R.OFFSET_GLYPH_BITMAP_WIDTH,"i32"),rows:R.getValue(i+R.OFFSET_GLYPH_BITMAP_ROWS,"i32"),pitch:R.getValue(i+R.OFFSET_GLYPH_BITMAP_PITCH,"i32"),num_grays:R.getValue(i+R.OFFSET_GLYPH_BITMAP_NUM_GRAYS,"i16"),pixel_mode:R.getValue(i+R.OFFSET_GLYPH_BITMAP_PIXEL_MODE,"i8"),palette_mode:R.getValue(i+R.OFFSET_GLYPH_BITMAP_PALETTE_MODE,"i8")},bitmap_left:R.getValue(i+R.OFFSET_GLYPH_BITMAP_LEFT,"i32"),bitmap_top:R.getValue(i+R.OFFSET_GLYPH_BITMAP_TOP,"i32"),lsb_delta:pA(R.getValue(i+R.OFFSET_GLYPH_LSB_DELTA,"i32")),rsb_delta:pA(R.getValue(i+R.OFFSET_GLYPH_RSB_DELTA,"i32"))},C=r.bitmap.width,B=r.bitmap.rows,n=r.bitmap_left,Q=r.bitmap_top,a=R.getValue(i+R.OFFSET_GLYPH_BITMAP_BUFFER,"i32"),E=Math.abs(r.bitmap.pitch),h=r.linearHoriAdvance,w=r.linearVertAdvance,u=r.bitmap.pixel_mode,l=[];for(let f=0;f255&&(k=255),X=(255-k)*X/255,D.push(X)}else{let v=R.getValue(c+y,"i8");D.push(ne(v))}l.push(D)}return{x:n,y:Q,width:C,height:B,advance_x:h,advance_y:w,pixels:l,freetype:r}}function PQ(e){let A=BI(e.ptr);if(A)throw new Error(`error in FT_Done_Face: ${A}`);R._free(e.font),e.ptr=0,e.font=0}function ZQ(){let e=R.ccall("FT_Done_FreeType","number",["number"],[le]);if(e)throw new Error(`error in FT_Done_FreeType: ${e}`);le=0}class KA extends Error{constructor(A){super(A),this.name="AppError",Error.captureStackTrace&&Error.captureStackTrace(this,KA)}}class XQ{constructor(){this.data={}}add_range(A,g,t,I){let o=I-g,i=[];for(let r=g;r<=t;r++)this._set_char(A,r,r+o),i.push(r);return i}add_symbols(A,g){let t=[];for(let I of g){let o=I.codePointAt(0);this._set_char(A,o,o),t.push(o)}return t}_set_char(A,g,t){this.data[t]={font:A,code:g}}get(){return this.data}}async function jQ(e){await VQ();let A={};e.font.forEach(a=>{A[a.source_path]=a});let g={},t={};for(let{source_path:a,source_bin:E}of e.font)if(!g[a])try{let h=E;h instanceof File?h=await h.arrayBuffer():h instanceof Uint8Array&&(h=h.buffer.slice(h.byteOffset,h.byteOffset+h.byteLength)),g[a]=og.parse(h),t[a]=qQ(h,e.size)}catch(h){throw new KA(`Cannot load font "${a}": ${h.message}`)}let I=new XQ;for(let{source_path:a,ranges:E}of e.font){let h=t[a];for(let w of E){if(w.range)for(let u=0;ua-E).map(Number);for(let a of r){let E=o[a].code,h=o[a].font;if(!Ze(t[h],E))continue;let w=WQ(t[h],E,{autohint_off:A[h].autohint_off,autohint_strong:A[h].autohint_strong,lcd:e.lcd,lcd_v:e.lcd_v,mono:!e.lcd&&!e.lcd_v&&e.bpp===1,use_color_info:e.use_color_info});i.push({code:a,advanceWidth:w.advance_x,bbox:{x:w.x,y:w.y-w.height,width:w.width,height:w.height},kerning:{},freetype:w.freetype,pixels:w.pixels})}if(!e.no_kerning){let a=i.map(E=>E.code);for(let{code:E,kerning:h}of i){let w=o[E].code,u=o[E].font,l=g[u],f=l.charToGlyph(String.fromCodePoint(w));for(let c of a){if(o[c].font!==u)continue;let D=o[c].code,y=l.charToGlyph(String.fromCodePoint(D)),v=l.getKerningValue(f,y);v&&(h[c]=v*e.size/l.unitsPerEm)}}}let C=t[e.font[0].source_path],B=e.size/C.units_per_em,n=OQ(C),Q=g[e.font[0].source_path].tables.post;for(let a of Object.values(t))PQ(a);return ZQ(),{ascent:Math.max(...i.map(a=>a.bbox.y+a.bbox.height)),descent:Math.min(...i.map(a=>a.bbox.y)),typoAscent:Math.round(n.typoAscent*B),typoDescent:Math.round(n.typoDescent*B),typoLineGap:Math.round(n.typoLineGap*B),size:e.size,glyphs:i,underlinePosition:Math.round(Q.underlinePosition*B),underlineThickness:Math.round(Q.underlineThickness*B)}}function zQ(){return 16}function _Q(e,A){return 16+(A-e+1)}function $Q(e){return 16+e*2}function Ct(e){e=e.sort((t,I)=>t-I);let A=[];for(let t=0;t=0?A[o-1].dist:0,r;e[t]-e[o]<256&&(r=_Q(e[o],e[t]),i+r=0;){let I=A[t];g.unshift([I.format,e.slice(I.start,I.end+1)]),t=I.start-1}return g}const hA=4,AE=(e,A,g)=>{e.setUint32(g,A,!0),e.setUint32(g+4,0,!0)};class eE{constructor(A,g){if(this.src=A,this.opts=g,this.font_name=g.lv_font_name,this.font_name||(this.font_name=g.output||"font"),g.bpp===3&&g.no_compress)throw new KA('LVGL supports "--bpp 3" with compression only');this.init_tables()}init_tables(){this.head=new gE(this),this.glyf=new IE(this),this.cmap=new oE(this),this.kern=new iE(this)}toCBin(){const[A,g]=this.glyf.toCBin(),t=this.cmap.toCBin(hA),I=this.kern.toCBin(hA),o=12+hA*6+0,i=8+hA*4,r=new ArrayBuffer(o+i),C=new DataView(r),B=(u,l)=>C.setUint32(l,u,!0);var n=0;B(0,n),n+=hA,B(0,n),n+=hA,B(0,n),n+=hA,C.setUint32(n,this.src.ascent-this.src.descent,!0),n+=4,C.setInt32(n,-this.src.descent,!0),n+=4,C.setUint8(n,this.src.subpixels_mode||0),n+=1,C.setInt8(n,this.src.underlinePosition||0),n+=1,C.setInt8(n,this.src.underlineThickness||0),n+=1,n+=1,B(o,n),n+=hA,B(0,n),n+=hA,B(0,n),n+=hA;const Q=this.head.kern_ref();B(i+I.byteLength,n),n+=hA,B(i+I.byteLength+A.byteLength,n),n+=hA,B(i+I.byteLength+A.byteLength+g.byteLength,n),n+=hA,B(Q.dsc==="NULL"?0:i,n),n+=hA,C.setUint16(n,Q.scale,!0),n+=2;const a=this.cmap.getMapNumber(),E=this.opts.bpp,h=Q.classes,w=this.glyf.getCompressionCode();return C.setUint16(n,a|E<<9|h<<13|w<<14,!0),n+=2,this.concatArrayBuffers([r,I,A,g,t])}concatArrayBuffers(A){const g=A.reduce((i,r)=>i+r.byteLength,0),t=new ArrayBuffer(g),I=new Uint8Array(t);let o=0;for(const i of A)I.set(new Uint8Array(i),o),o+=i.byteLength;return t}}class gE{constructor(A){this.font=A}kern_ref(){return this.font,{scale:0,dsc:"NULL",classes:0}}}class tE{constructor(A){this.buffer=new Uint8Array(A),this.byteIndex=0,this.bitIndex=0,this.bigEndian=!0}writeBits(A,g){for(;g>0;){const t=Math.min(8-this.bitIndex,g),I=(1<>g-t&I;this.bigEndian?this.buffer[this.byteIndex]|=o<<8-this.bitIndex-t:this.buffer[this.byteIndex]|=o<=8&&(this.byteIndex++,this.bitIndex=0),g-=t}}getUsedBytes(){return this.bitIndex>0?this.byteIndex+1:this.byteIndex}}class IE{constructor(A){this.font=A,this.lv_data=[],this.lv_compiled=!1}pixelsToBpp(A){const g=this.font.opts.bpp;return A.map(t=>t.map(I=>I>>>8-g))}storePixels(A,g){this.getCompressionCode()===0?this.storePixelsRaw(A,g):this.storePixelsCompressed(A,g)}storePixelsRaw(A,g){const t=this.font.opts.bpp;for(let I=0;I{const I=A.glyph_id[t.code],o=this.lv_bitmap(t);this.lv_data[I]={bin:o,offset:g,glyph:t},g+=o.byteLength})}toCBin(){this.lv_compile();const A=this.lv_data.slice(1).filter(i=>i).map(i=>i.bin),g=this.balign4(this.concatArrayBuffers(A)),t=new ArrayBuffer(this.lv_data.length*16+16),I=new DataView(t);let o=1;return this.lv_data.forEach(i=>{if(i){const r=Math.round(i.glyph.advanceWidth*16);I.setUint32(o*16,i.offset,!0),I.setUint32(o*16+4,r,!0),I.setUint16(o*16+8,i.glyph.bbox.width,!0),I.setUint16(o*16+10,i.glyph.bbox.height,!0),I.setInt16(o*16+12,i.glyph.bbox.x,!0),I.setInt16(o*16+14,i.glyph.bbox.y,!0)}o++}),[g,t]}balign4(A){const g=A.byteLength%4;if(g===0)return A;const t=4-g,I=new ArrayBuffer(t);return this.concatArrayBuffers([A,I])}concatArrayBuffers(A){const g=A.reduce((i,r)=>i+r.byteLength,0),t=new ArrayBuffer(g),I=new Uint8Array(t);let o=0;for(const i of A)I.set(new Uint8Array(i),o),o+=i.byteLength;return t}getCompressionCode(){return this.font.opts.no_compress||this.font.opts.bpp===1?0:this.font.opts.no_prefilter?2:1}}class oE{constructor(A){this.font=A,this.lv_compiled=!1,this.lv_subtables=[],this.subtables_plan=null,this.buildGlyphIdMap()}buildGlyphIdMap(){const A=this.font;A.glyph_id={},A.src.glyphs&&A.src.glyphs.forEach((g,t)=>{A.glyph_id[g.code]=t+1})}lv_format2enum(A){switch(A){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(A){return["format0","sparse","format0_tiny","sparse_tiny"].indexOf(A)}getMapNumber(){if(!this.subtables_plan){const A=this.font;if(!A.src.glyphs||A.src.glyphs.length===0)return 0;this.subtables_plan=Ct(A.src.glyphs.map(g=>g.code))}return this.subtables_plan.length}glyphByCode(A){const g=this.font;return g.src.glyphs?g.src.glyphs.find(t=>t.code===A):null}collect_format0_data(A,g,t){const I=this.font,o=[];for(let i=A;i<=g;i++){const r=I.glyph_id[i]||0;o.push(r?r-t:0)}return o}collect_sparse_data(A,g){const t=this.font;let I=[],o=[];for(let i of A){let r=this.glyphByCode(i),C=t.glyph_id[r.code],B=i-A[0],n=C-g;if(B<0||B>65535)throw new Error("Codepoint delta out of range");if(n<0||n>65535)throw new Error("Glyph ID delta out of range");I.push(B),o.push(n)}return{codes:I,ids:o}}toCBin(A){const g=this.font;if(!g.src.glyphs||g.src.glyphs.length===0)return new ArrayBuffer(0);this.subtables_plan||(this.subtables_plan=Ct(g.src.glyphs.map(Q=>Q.code)));const t=this.subtables_plan;let I=0;const o=12+A*2+(A==4?0:4),i=new ArrayBuffer(t.length*o),r=new DataView(i),C=A==4?(Q,a)=>r.setUint32(a,Q,!0):(Q,a)=>AE(r,Q,a),B=[];let n=i.byteLength;for(let[Q,a]of t){let E=this.glyphByCode(a[0]),h=g.glyph_id[E.code],w=a[0],u=a[a.length-1],l=!1,f=!1,c=0,D=new ArrayBuffer(0),y=new ArrayBuffer(0);if(Q!=="format0_tiny")if(Q==="format0"){f=!0;let N=this.collect_format0_data(w,u,h);c=N.length,D=this.balign4(this.uint8ArrayToBuffer(new Uint8Array(N)))}else if(Q==="sparse_tiny"){l=!0;let N=this.collect_sparse_data(a,h);c=N.codes.length,y=this.balign4(this.uint16ArrayToBuffer(new Uint16Array(N.codes)))}else{l=!0,f=!0;let N=this.collect_sparse_data(a,h);c=N.codes.length,y=this.balign4(this.uint16ArrayToBuffer(new Uint16Array(N.codes))),D=this.align4(this.uint16ArrayToBuffer(new Uint16Array(N.ids)))}let v=I*o;r.setUint32(v,w,!0),v+=4,r.setUint16(v,u-w+1,!0),v+=2,r.setUint16(v,h,!0),v+=2,C(l?n:0,v),v+=A,n+=y.byteLength,C(f?n:0,v),v+=A,n+=D.byteLength,r.setUint16(v,c,!0),v+=2,r.setUint8(v,this.lv_format2int(Q)),v+=1,B.push(y),B.push(D),I++}return this.concatArrayBuffers([i,...B])}balign4(A){const g=A.byteLength%4;if(g===0)return A;const t=4-g,I=new ArrayBuffer(t);return this.concatArrayBuffers([A,I])}align4(A){const g=A.byteLength%4;if(g===0)return A;const t=4-g,I=new ArrayBuffer(t);return this.concatArrayBuffers([A,I])}uint8ArrayToBuffer(A){const g=new ArrayBuffer(A.byteLength);return new Uint8Array(g).set(A),g}uint16ArrayToBuffer(A){return A.buffer.slice(0,A.byteLength)}concatArrayBuffers(A){const g=A.reduce((i,r)=>i+r.byteLength,0),t=new ArrayBuffer(g),I=new Uint8Array(t);let o=0;for(const i of A)I.set(new Uint8Array(i),o),o+=i.byteLength;return t}}class iE{constructor(A){this.font=A}toCBin(A){return new ArrayBuffer(0)}}function rE(e,A){if(!e.output)throw new KA('Output is required for "cbin" writer');const t=new eE(A,e).toCBin();return{[e.output]:t}}class CE{constructor(){this.initialized=!1,this.supportedFormats=["ttf","woff","woff2","otf"],this.charsetCache=new Map}async initialize(){if(!this.initialized)try{if(typeof og>"u")throw new Error("opentype.js not loaded");this.initialized=!0,console.log("BrowserFontConverter initialized")}catch(A){throw console.error("BrowserFontConverter initialization failed:",A),A}}validateFont(A){if(!A)return!1;if(A instanceof File){const g=A.name.toLowerCase(),t=A.type.toLowerCase(),I=this.supportedFormats.some(i=>g.endsWith(`.${i}`)),o=["font/ttf","font/truetype","application/x-font-ttf","font/woff","font/woff2","application/font-woff","font/otf","application/x-font-otf"].some(i=>t.includes(i));return I||o}return A instanceof ArrayBuffer&&A.byteLength>0}async getFontInfo(A){try{let g;if(A instanceof File)g=await A.arrayBuffer();else if(A instanceof ArrayBuffer)g=A;else throw new Error("Unsupported font file type");const t=og.parse(g);return{familyName:this.getLocalizedName(t.names.fontFamily)||"Unknown",fullName:this.getLocalizedName(t.names.fullName)||"Unknown",postScriptName:this.getLocalizedName(t.names.postScriptName)||"Unknown",version:this.getLocalizedName(t.names.version)||"Unknown",unitsPerEm:t.unitsPerEm,ascender:t.ascender,descender:t.descender,numGlyphs:t.numGlyphs,supported:!0}}catch(g){return console.error("Failed to get font information:",g),{familyName:"Unknown",supported:!1,error:g.message}}}getLocalizedName(A){return A?A.en||A[Object.keys(A)[0]]:null}async convertToCBIN(A){this.initialized||await this.initialize();const{fontFile:g,fontName:t,fontSize:I=20,bpp:o=4,charset:i="deepseek",symbols:r="",range:C="",compression:B=!1,lcd:n=!1,lcd_v:Q=!1,progressCallback:a=null}=A;if(!this.validateFont(g))throw new KA("Unsupported font file format");try{a&&a(0,"Starting font processing...");let E;g instanceof File?E=await g.arrayBuffer():E=g,a&&a(10,"Parsing font structure...");const{ranges:h,charSymbols:w}=await this.parseCharacterInputAsync(i,r,C);a&&a(20,"Preparing conversion parameters...");const u={font:[{source_path:t||"custom_font",source_bin:E,ranges:[{range:h,symbols:w}],autohint_off:!1,autohint_strong:!1}],size:I,bpp:o,lcd:n,lcd_v:Q,no_compress:!B,no_kerning:!1,use_color_info:!1,format:"cbin",output:t||"font"};a&&a(30,"Collecting font data...");const l=await jQ(u);a&&a(70,"Generating CBIN format...");const f=rE(u,l),c=u.output;return a&&a(100,"Conversion completed!"),f[c]}catch(E){throw console.error("Font conversion failed:",E),new KA(`Font conversion failed: ${E.message}`)}}async parseCharacterInputAsync(A,g,t){let I=[],o=g||"";return A==="full"?(I=[0,65535,0],{ranges:I,charSymbols:o}):(A&&A!=="custom"&&(o=await this.getCharsetContentAsync(A)+o),t&&(I=this.parseUnicodeRange(t)),{ranges:I,charSymbols:o})}parseCharacterInput(A,g,t){let I=[],o=g||"";return A==="full"?(I=[0,65535,0],{ranges:I,charSymbols:o}):(A&&A!=="custom"&&(o=this.getCharsetContent(A)+o),t&&(I=this.parseUnicodeRange(t)),{ranges:I,charSymbols:o})}async loadCharsetFromFile(A){const t={latin:"./static/charsets/latin1.txt",deepseek:"./static/charsets/deepseek.txt",qwen:"./static/charsets/qwen18409.txt"}[A];if(!t)return null;try{const I=await fetch(t);if(!I.ok)throw new Error(`Failed to load charset file: ${I.status}`);const i=(await I.text()).split(` `).join("");return this.charsetCache.set(A,i),i}catch(I){return console.error(`Failed to load charset ${A}:`,I),null}}getCharsetContent(A){const g={};return(A==="latin"||A==="deepseek"||A==="qwen")&&this.charsetCache.has(A)?this.charsetCache.get(A):A==="basic"?this.getCharsetContent("latin"):g[A]||""}async getCharsetContentAsync(A){if(A==="basic"&&(A="latin"),this.charsetCache.has(A))return this.charsetCache.get(A);if(A==="latin"||A==="deepseek"||A==="qwen"){const g=await this.loadCharsetFromFile(A);if(g)return g}return this.getCharsetContent(A)}parseUnicodeRange(A){const g=[],t=A.split(",");for(const I of t){const o=I.trim();if(o)if(o.includes("-")){const[i,r]=o.split("-"),C=this.parseHexOrDec(i),B=this.parseHexOrDec(r);C!==null&&B!==null&&g.push(C,B,C)}else{const i=this.parseHexOrDec(o);i!==null&&g.push(i,i,i)}}return g}parseHexOrDec(A){const g=A.trim();if(g.startsWith("0x")||g.startsWith("0X")){const I=parseInt(g,16);return isNaN(I)?null:I}const t=parseInt(g,10);return isNaN(t)?null:t}async estimateSizeAsync(A){const{fontSize:g=20,bpp:t=4,charset:I="latin",symbols:o="",range:i=""}=A;let r=o.length;if(I==="full")r=65536;else if(I&&I!=="custom"){const n=await this.getCharsetContentAsync(I);r+=n.length}if(i){const n=this.parseUnicodeRange(i);for(let Q=0;Q0}catch(A){return console.error("加载 FST 模型失败",A),!1}}packString(A,g){const t=new Uint8Array(g),I=Math.min(A.length,g);for(let o=0;o>8&255,g[2]=A>>16&255,g[3]=A>>24&255,g}packModels(){if(this.models.size===0)throw new Error("没有模型数据可打包");let A=0;const g=[];for(const[B,n]of Array.from(this.models.entries()).sort((Q,a)=>Q[0].localeCompare(a[0]))){A+=n.size;const Q=Array.from(n.entries()).sort((a,E)=>a[0].localeCompare(E[0]));g.push({name:B,files:Q})}const t=this.models.size;let I=4;for(const B of g)I+=36,I+=B.files.length*40;const o=I+Array.from(this.models.values()).reduce((B,n)=>B+Array.from(n.values()).reduce((Q,a)=>Q+a.byteLength,0),0),i=new Uint8Array(o);let r=0;i.set(this.packUint32(t),r),r+=4;let C=I;for(const B of g){i.set(this.packString(B.name,32),r),r+=32,i.set(this.packUint32(B.files.length),r),r+=4;for(const[n,Q]of B.files)i.set(this.packString(n,32),r),r+=32,i.set(this.packUint32(C),r),r+=4,i.set(this.packUint32(Q.byteLength),r),r+=4,C+=Q.byteLength}for(const B of g)for(const[n,Q]of B.files)i.set(new Uint8Array(Q),r),r+=Q.byteLength;return i.buffer}static isValidModel(A,g){return g==="esp32c3"||g==="esp32c6"?A.startsWith("wn9s_"):A.startsWith("wn9_")}clear(){this.models.clear()}getStats(){let A=0,g=0;for(const t of this.models.values()){A+=t.size;for(const I of t.values())g+=I.byteLength}return{modelCount:this.models.size,fileCount:A,totalSize:g,models:Array.from(this.models.keys())}}validatePackingCompatibility(){const A="test_model",g=this.packString(A,32),t=305419896,I=this.packUint32(t);return{stringPacking:{input:A,output:Array.from(g).map(o=>`0x${o.toString(16).padStart(2,"0")}`),isASCII:g.every((o,i)=>i>=A.length||o===A.charCodeAt(i))},intPacking:{input:`0x${t.toString(16)}`,output:Array.from(I).map(o=>`0x${o.toString(16).padStart(2,"0")}`),isLittleEndian:I[0]===120&&I[3]===18}}}}class sE{constructor(){this.files=[],this.textEncoder=new TextEncoder}addFile(A,g,t={}){A.length>32&&console.warn(`Filename "${A}" exceeds 32 bytes and will be truncated`),this.files.push({filename:A,data:g,size:g.byteLength,width:t.width||0,height:t.height||0})}async getImageDimensions(A){return new Promise(g=>{try{const t=new Blob([A]),I=URL.createObjectURL(t),o=new Image;o.onload=()=>{URL.revokeObjectURL(I),g({width:o.width,height:o.height})},o.onerror=()=>{URL.revokeObjectURL(I),g({width:0,height:0})},o.src=I}catch{g({width:0,height:0})}})}parseSpecialImageFormat(A,g){const t=A.toLowerCase().split(".").pop();if([".sjpg",".spng",".sqoi"].includes("."+t))try{const I=new DataView(g),o=I.getUint16(14,!0),i=I.getUint16(16,!0);return{width:o,height:i}}catch(I){console.warn(`Failed to parse special image format: ${A}`,I)}return{width:0,height:0}}packUint32(A){const g=new Uint8Array(4);return g[0]=A&255,g[1]=A>>8&255,g[2]=A>>16&255,g[3]=A>>24&255,g}packUint16(A){const g=new Uint8Array(2);return g[0]=A&255,g[1]=A>>8&255,g}packString(A,g){const t=new Uint8Array(g),I=this.textEncoder.encode(A),o=Math.min(I.length,g);return t.set(I.slice(0,o),0),t}computeChecksum(A){let g=0;for(let t=0;t{const I=g.filename.split(".").pop()||"",o=t.filename.split(".").pop()||"";if(I!==o)return I.localeCompare(o);const i=g.filename.replace(/\.[^/.]+$/,""),r=t.filename.replace(/\.[^/.]+$/,"");return i.localeCompare(r)})}async generate(A=null){if(this.files.length===0)throw new Error("No files to package");A&&A(0,"Starting to package files...");const g=this.sortFiles(this.files),t=g.length,I=[];let o=0;for(let f=0;f0||v.height>0)D=v.width,y=v.height;else{const N=c.filename.toLowerCase().split(".").pop();if(["png","jpg","jpeg","gif","bmp","webp"].includes(N)){const L=await this.getImageDimensions(c.data);D=L.width,y=L.height}}}I.push({filename:c.filename,data:c.data,size:c.size,offset:o,width:D,height:y}),o+=2+c.size}A&&A(40,"Building file mapping table...");const i=t*44,r=new Uint8Array(i);let C=0;for(const f of I)r.set(this.packString(f.filename,32),C),C+=32,r.set(this.packUint32(f.size),C),C+=4,r.set(this.packUint32(f.offset),C),C+=4,r.set(this.packUint16(f.width),C),C+=2,r.set(this.packUint16(f.height),C),C+=2;A&&A(60,"Merging file data...");const B=new Uint8Array(o);let n=0;for(let f=0;f0?Math.round(A/this.files.length):0}}printFileList(){if(console.log("=== Packaged File List ==="),console.log(`Total files: ${this.files.length}`),this.files.length===0){console.log("No files available");return}this.sortFiles(this.files).forEach((t,I)=>{var C;const o=((C=t.filename.split(".").pop())==null?void 0:C.toLowerCase())||"unknown",i=(t.size/1024).toFixed(2),r=t.width&&t.height?`${t.width}x${t.height}`:"N/A";console.log(`${String(I+1).padStart(3," ")}. ${t.filename}`),console.log(` Type: ${o.toUpperCase()}`),console.log(` Size: ${i} KB (${t.size} bytes)`),console.log(` Dimensions: ${r}`),console.log("")});const g=this.getStats();console.log("=== File Statistics ==="),console.log(`Total size: ${(g.totalSize/1024).toFixed(2)} KB`),console.log(`Average size: ${(g.averageFileSize/1024).toFixed(2)} KB`),console.log("File type distribution:"),Object.entries(g.fileTypes).forEach(([t,I])=>{console.log(` ${t.toUpperCase()}: ${I} files`)})}clear(){this.files=[]}}let ke={tool:{workerLocalUrl:`var gifsicle=function(){Me="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0,"undefined"!=typeof __filename&&(Me=Me||__filename);var Me,c=function(e){var j,r,h=void 0!==(e=e||{})?e:{},t=(h.ready=new Promise(function(e,r){j=e}),h.preRun=h.preRun||[],h.preRun.push(function(){if(h.folder&&h.folder.length)for(let e=0;e>10,56320|1023&s)))):i+=String.fromCharCode(u)}return i}function W(e,r){return e?g(E,e,r):""}function X(e,r,t,n){if(!(0>6,r[t++]=128|63&s}else if(s<=65535){if(i<=t+2)break;r[t++]=224|s>>12,r[t++]=128|s>>6&63,r[t++]=128|63&s}else{if(i<=t+3)break;r[t++]=240|s>>18,r[t++]=128|s>>12&63,r[t++]=128|s>>6&63,r[t++]=128|63&s}}return r[t]=0,t-o}function G(e){for(var r=0,t=0;t>2]=e}var x={splitPath:function(e){return/^(\\/?|)([\\s\\S]*?)((?:\\.{1,2}|[^\\/]+?|)(\\.[^.\\/]*|))(?:[\\/]*)$/.exec(e).slice(1)},normalizeArray:function(e,r){for(var t=0,n=e.length-1;0<=n;n--){var o=e[n];"."===o?e.splice(n,1):".."===o?(e.splice(n,1),t++):t&&(e.splice(n,1),t--)}if(r)for(;t;t--)e.unshift("..");return e},normalize:function(e){var r="/"===e.charAt(0),t="/"===e.substr(-1);return(e=(e=x.normalizeArray(e.split("/").filter(function(e){return!!e}),!r).join("/"))||r?e:".")&&t&&(e+="/"),(r?"/":"")+e},dirname:function(e){var e=x.splitPath(e),r=e[0],e=e[1];return r||e?r+(e=e&&e.substr(0,e.length-1)):"."},basename:function(e){if("/"===e)return"/";var r=e.lastIndexOf("/");return-1===r?e:e.substr(r+1)},extname:function(e){return x.splitPath(e)[3]},join:function(){var e=Array.prototype.slice.call(arguments,0);return x.normalize(e.join("/"))},join2:function(e,r){return x.normalize(e+"/"+r)}},R={resolve:function(){for(var e="",r=!1,t=arguments.length-1;-1<=t&&!r;t--){var n=0<=t?arguments[t]:T.cwd();if("string"!=typeof n)throw new TypeError("Arguments to path.resolve must be strings");if(!n)return"";e=n+"/"+e,r="/"===n.charAt(0)}return(r?"/":"")+(e=x.normalizeArray(e.split("/").filter(function(e){return!!e}),!r).join("/"))||"."},relative:function(e,r){function t(e){for(var r=0;r>>0),0!=t&&(r=Math.max(r,256)),t=e.contents,e.contents=new Uint8Array(r),0r)e.contents.length=r;else for(;e.contents.length=e.node.usedBytes)return 0;var a=Math.min(e.node.usedBytes-o,n);if(8>>0)%T.nameTable.length},hashAddNode:function(e){var r=T.hashName(e.parent.id,e.name);e.name_next=T.nameTable[r],T.nameTable[r]=e},hashRemoveNode:function(e){var r=T.hashName(e.parent.id,e.name);if(T.nameTable[r]===e)T.nameTable[r]=e.name_next;else for(var t=T.nameTable[r];t;){if(t.name_next===e){t.name_next=e.name_next;break}t=t.name_next}},lookupNode:function(e,r){var t=T.mayLookup(e);if(t)throw new T.ErrnoError(t,e);for(var t=T.hashName(e.id,r),n=T.nameTable[t];n;n=n.name_next){var o=n.name;if(n.parent.id===e.id&&o===r)return n}return T.lookup(e,r)},createNode:function(e,r,t,n){e=new T.FSNode(e,r,t,n);return T.hashAddNode(e),e},destroyNode:function(e){T.hashRemoveNode(e)},isRoot:function(e){return e===e.parent},isMountpoint:function(e){return!!e.mounted},isFile:function(e){return 32768==(61440&e)},isDir:function(e){return 16384==(61440&e)},isLink:function(e){return 40960==(61440&e)},isChrdev:function(e){return 8192==(61440&e)},isBlkdev:function(e){return 24576==(61440&e)},isFIFO:function(e){return 4096==(61440&e)},isSocket:function(e){return 49152==(49152&e)},flagModes:{r:0,rs:1052672,"r+":2,w:577,wx:705,xw:705,"w+":578,"wx+":706,"xw+":706,a:1089,ax:1217,xa:1217,"a+":1090,"ax+":1218,"xa+":1218},modeStringToFlags:function(e){var r=T.flagModes[e];if(void 0===r)throw new Error("Unknown file open mode: "+e);return r},flagsToPermissionString:function(e){var r=["r","w","rw"][3&e];return 512&e&&(r+="w"),r},nodePermissions:function(e,r){return T.ignorePermissions||(-1===r.indexOf("r")||292&e.mode)&&(-1===r.indexOf("w")||146&e.mode)&&(-1===r.indexOf("x")||73&e.mode)?0:2},mayLookup:function(e){var r=T.nodePermissions(e,"x");return r||(e.node_ops.lookup?0:2)},mayCreate:function(e,r){try{T.lookupNode(e,r);return 20}catch(e){}return T.nodePermissions(e,"wx")},mayDelete:function(e,r,t){var n;try{n=T.lookupNode(e,r)}catch(e){return e.errno}r=T.nodePermissions(e,"wx");if(r)return r;if(t){if(!T.isDir(n.mode))return 54;if(T.isRoot(n)||T.getPath(n)===T.cwd())return 10}else if(T.isDir(n.mode))return 31;return 0},mayOpen:function(e,r){return e?T.isLink(e.mode)?32:T.isDir(e.mode)&&("r"!==T.flagsToPermissionString(r)||512&r)?31:T.nodePermissions(e,T.flagsToPermissionString(r)):44},MAX_OPEN_FDS:4096,nextfd:function(e,r){r=r||T.MAX_OPEN_FDS;for(var t=e=e||0;t<=r;t++)if(!T.streams[t])return t;throw new T.ErrnoError(33)},getStream:function(e){return T.streams[e]},createStream:function(e,r,t){T.FSStream||(T.FSStream=function(){},T.FSStream.prototype={object:{get:function(){return this.node},set:function(e){this.node=e}},isRead:{get:function(){return 1!=(2097155&this.flags)}},isWrite:{get:function(){return 0!=(2097155&this.flags)}},isAppend:{get:function(){return 1024&this.flags}}});var n,o=new T.FSStream;for(n in e)o[n]=e[n];e=o;r=T.nextfd(r,t);return e.fd=r,T.streams[r]=e},closeStream:function(e){T.streams[e]=null},chrdev_stream_ops:{open:function(e){var r=T.getDevice(e.node.rdev);e.stream_ops=r.stream_ops,e.stream_ops.open&&e.stream_ops.open(e)},llseek:function(){throw new T.ErrnoError(70)}},major:function(e){return e>>8},minor:function(e){return 255&e},makedev:function(e,r){return e<<8|r},registerDevice:function(e,r){T.devices[e]={stream_ops:r}},getDevice:function(e){return T.devices[e]},getMounts:function(e){for(var r=[],t=[e];t.length;){var n=t.pop();r.push(n),t.push.apply(t,n.mounts)}return r},syncfs:function(r,t){"function"==typeof r&&(t=r,r=!1),T.syncFSRequests++,1=n.length&&i(null)}n.forEach(function(e){if(!e.type.syncfs)return a(null);e.type.syncfs(e,r,a)})},mount:function(e,r,t){var n,o="/"===t,i=!t;if(o&&T.root)throw new T.ErrnoError(10);if(!o&&!i){i=T.lookupPath(t,{follow_mount:!1});if(t=i.path,n=i.node,T.isMountpoint(n))throw new T.ErrnoError(10);if(!T.isDir(n.mode))throw new T.ErrnoError(54)}i={type:e,opts:r,mountpoint:t,mounts:[]},r=e.mount(i);return(r.mount=i).root=r,o?T.root=r:n&&(n.mounted=i,n.mount&&n.mount.mounts.push(i)),r},unmount:function(e){e=T.lookupPath(e,{follow_mount:!1});if(!T.isMountpoint(e.node))throw new T.ErrnoError(28);var e=e.node,r=e.mounted,n=T.getMounts(r),r=(Object.keys(T.nameTable).forEach(function(e){for(var r=T.nameTable[e];r;){var t=r.name_next;-1!==n.indexOf(r.mount)&&T.destroyNode(r),r=t}}),e.mounted=null,e.mount.mounts.indexOf(r));e.mount.mounts.splice(r,1)},lookup:function(e,r){return e.node_ops.lookup(e,r)},mknod:function(e,r,t){var n=T.lookupPath(e,{parent:!0}).node,e=x.basename(e);if(!e||"."===e||".."===e)throw new T.ErrnoError(28);var o=T.mayCreate(n,e);if(o)throw new T.ErrnoError(o);if(n.node_ops.mknod)return n.node_ops.mknod(n,e,r,t);throw new T.ErrnoError(63)},create:function(e,r){return T.mknod(e,r=(r=void 0!==r?r:438)&4095|32768,0)},mkdir:function(e,r){return T.mknod(e,r=(r=void 0!==r?r:511)&1023|16384,0)},mkdirTree:function(e,r){for(var t=e.split("/"),n="",o=0;othis.length-1||e<0))return r=e%this.chunkSize,e=e/this.chunkSize|0,this.getter(e)[r]},o.prototype.setDataGetter=function(e){this.getter=e},o.prototype.cacheLength=function(){var e=new XMLHttpRequest;if(e.open("HEAD",a,!1),e.send(null),!(200<=e.status&&e.status<300||304===e.status))throw new Error("Couldn't load "+a+". Status: "+e.status);var r,n=Number(e.getResponseHeader("Content-length")),t=(r=e.getResponseHeader("Accept-Ranges"))&&"bytes"===r,e=(r=e.getResponseHeader("Content-Encoding"))&&"gzip"===r,o=1048576,i=(t||(o=n),this);i.setDataGetter(function(e){var r=e*o,t=(e+1)*o-1,t=Math.min(t,n-1);if(void 0===i.chunks[e]&&(i.chunks[e]=function(e,r){if(r=i.length)return 0;var a=Math.min(i.length-o,n);if(i.slice)for(var s=0;s>2]=n.dev,k[t+4>>2]=0,k[t+8>>2]=n.ino,k[t+12>>2]=n.mode,k[t+16>>2]=n.nlink,k[t+20>>2]=n.uid,k[t+24>>2]=n.gid,k[t+28>>2]=n.rdev,k[t+32>>2]=0,F=[n.size>>>0,(S=n.size,1<=+ne(S)?0>>0:~~+oe((S-(~~S>>>0))/4294967296)>>>0:0)],k[t+40>>2]=F[0],k[t+44>>2]=F[1],k[t+48>>2]=4096,k[t+52>>2]=n.blocks,k[t+56>>2]=n.atime.getTime()/1e3|0,k[t+60>>2]=0,k[t+64>>2]=n.mtime.getTime()/1e3|0,k[t+68>>2]=0,k[t+72>>2]=n.ctime.getTime()/1e3|0,k[t+76>>2]=0,F=[n.ino>>>0,(S=n.ino,1<=+ne(S)?0>>0:~~+oe((S-(~~S>>>0))/4294967296)>>>0:0)],k[t+80>>2]=F[0],k[t+84>>2]=F[1],0},doMsync:function(e,r,t,n,o){e=E.slice(e,e+t);T.msync(r,e,o,t,n)},doMkdir:function(e,r){return"/"===(e=x.normalize(e))[e.length-1]&&(e=e.substr(0,e.length-1)),T.mkdir(e,r,0),0},doMknod:function(e,r,t){switch(61440&r){case 32768:case 8192:case 24576:case 4096:case 49152:break;default:return-28}return T.mknod(e,r,t),0},doReadlink:function(e,r,t){if(t<=0)return-28;var e=T.readlink(e),n=Math.min(t,G(e)),o=y[r+n];return X(e,E,r,t+1),y[r+n]=o,n},doAccess:function(e,r){if(-8&r)return-28;e=T.lookupPath(e,{follow:!0}).node;if(!e)return-44;var t="";return 4&r&&(t+="r"),2&r&&(t+="w"),1&r&&(t+="x"),t&&T.nodePermissions(e,t)?-2:0},doDup:function(e,r,t){var n=T.getStream(t);return n&&T.close(n),T.open(e,r,0,t,t).fd},doReadv:function(e,r,t,n){for(var o=0,i=0;i>2],s=k[r+(8*i+4)>>2],a=T.read(e,y,a,s,n);if(a<0)return-1;if(o+=a,a>2],s=k[r+(8*i+4)>>2],a=T.write(e,y,a,s,n);if(a<0)return-1;o+=a}return o},varargs:void 0,get:function(){return N.varargs+=4,k[N.varargs-4>>2]},getStr:function(e){return W(e)},getStreamFromFD:function(e){e=T.getStream(e);if(e)return e;throw new T.ErrnoError(8)},get64:function(e,r){return e}};var ge={};function z(){if(!z.strings){var e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:C||"./this.program"};for(r in ge)e[r]=ge[r];var r,t=[];for(r in e)t.push(r+"="+e[r]);z.strings=t}return z.strings}function ve(e,r,t,n){this.parent=e=e||this,this.mount=e.mount,this.mounted=null,this.id=T.nextInode++,this.name=r,this.mode=t,this.node_ops={},this.stream_ops={},this.rdev=n}function ye(e,r,t){t=0>2]=t/1e3|0,k[r+4>>2]=t%1e3*1e3*1e3|0,0},d:function(e,r,t){N.varargs=t;try{var n=N.getStreamFromFD(e);switch(r){case 0:return(o=N.get())<0?-28:T.open(n.path,n.flags,0,o).fd;case 1:case 2:return 0;case 3:return n.flags;case 4:var o=N.get();return n.flags|=o,0;case 12:o=N.get();return K[o+0>>1]=2,0;case 13:case 14:return 0;case 16:case 8:return-28;case 9:return A(28),-1;default:return-28}}catch(e){return void 0!==T&&e instanceof T.ErrnoError||D(e),-e.errno}},i:function(e,r,t){N.varargs=t;try{var n=N.getStreamFromFD(e);switch(r){case 21509:case 21505:return n.tty?0:-59;case 21510:case 21511:case 21512:case 21506:case 21507:case 21508:return n.tty?0:-59;case 21519:if(!n.tty)return-59;var o=N.get();return k[o>>2]=0;case 21520:return n.tty?-28:-59;case 21531:o=N.get();return T.ioctl(n,r,o);case 21523:case 21524:return n.tty?0:-59;default:D("bad ioctl syscall "+r)}}catch(e){return void 0!==T&&e instanceof T.ErrnoError||D(e),-e.errno}},e:function(e,r,t){N.varargs=t;try{var n=N.getStr(e),o=N.get();return T.open(n,r,o).fd}catch(e){return void 0!==T&&e instanceof T.ErrnoError||D(e),-e.errno}},t:function(e){try{return e=N.getStr(e),T.rmdir(e),0}catch(e){return void 0!==T&&e instanceof T.ErrnoError||D(e),-e.errno}},j:function(e){try{var r=N.umask;return N.umask=e,r}catch(e){return void 0!==T&&e instanceof T.ErrnoError||D(e),-e.errno}},u:function(e){try{return e=N.getStr(e),T.unlink(e),0}catch(e){return void 0!==T&&e instanceof T.ErrnoError||D(e),-e.errno}},v:function(e,r,t,n){try{D("cannot wait on child processes")}catch(e){return void 0!==T&&e instanceof T.ErrnoError||D(e),-e.errno}},n:function(e,r,t){E.copyWithin(e,r,r+t)},b:function(e){var r=E.length,t=2147483648;if(t<(e>>>=0))return!1;for(var n,o=1;o<=4;o*=2){var i=r*(1+.2/o),i=Math.min(i,e+100663296);if(function(e){try{return p.grow(e-v.byteLength+65535>>>16),Y(p.buffer),1}catch(e){}}(Math.min(t,(0<(i=Math.max(16777216,e,i))%(n=65536)&&(i+=n-i%n),i))))return!0}return!1},p:function(a,s){var u=0;return z().forEach(function(e,r){for(var t=s+u,n=(k[a+4*r>>2]=t,e),o=t,r=void 0,i=0;i>0]=n.charCodeAt(i);r||(y[o>>0]=0),u+=e.length+1}),0},q:function(e,r){var t=z(),n=(k[e>>2]=t.length,0);return t.forEach(function(e){n+=e.length+1}),k[r>>2]=n,0},c:function(e){xe(e)},f:function(e){try{var r=N.getStreamFromFD(e);return T.close(r),0}catch(e){return void 0!==T&&e instanceof T.ErrnoError||D(e),e.errno}},r:function(e,r){try{var t=N.getStreamFromFD(e),n=t.tty?2:T.isDir(t.mode)?3:T.isLink(t.mode)?7:4;return y[r>>0]=n,0}catch(e){return void 0!==T&&e instanceof T.ErrnoError||D(e),e.errno}},h:function(e,r,t,n){try{var o=N.getStreamFromFD(e),i=N.doReadv(o,r,t);return k[n>>2]=i,0}catch(e){return void 0!==T&&e instanceof T.ErrnoError||D(e),e.errno}},m:function(e,r,t,n,o){try{var i=N.getStreamFromFD(e),a=4294967296*t+(r>>>0),s=9007199254740992;return a<=-s||s<=a?-61:(T.llseek(i,a,n),F=[i.position>>>0,(S=i.position,1<=+ne(S)?0>>0:~~+oe((S-(~~S>>>0))/4294967296)>>>0:0)],k[o>>2]=F[0],k[o+4>>2]=F[1],i.getdents&&0==a&&0===n&&(i.getdents=null),0)}catch(e){return void 0!==T&&e instanceof T.ErrnoError||D(e),e.errno}},g:function(e,r,t,n){try{var o=N.getStreamFromFD(e),i=N.doWritev(o,r,t);return k[n>>2]=i,0}catch(e){return void 0!==T&&e instanceof T.ErrnoError||D(e),e.errno}},memory:p,o:function(){w("missing function: popen"),D(-1)},l:function(){return 6},k:function(){},table:I},_e=(!function(){var r={a:ke};function t(e,r){e=e.exports;h.asm=e,ue()}function n(e){t(e.instance)}function o(e){return(l||!L&&!c||"function"!=typeof fetch||de(P)?new Promise(function(e,r){e(pe())}):fetch(P,{credentials:"same-origin"}).then(function(e){if(e.ok)return e.arrayBuffer();throw"failed to load wasm binary file at '"+P+"'"}).catch(pe)).then(function(e){return WebAssembly.instantiate(e,r)}).then(e,function(e){w("failed to asynchronously prepare wasm: "+e),D(e)})}if(se(),h.instantiateWasm)try{h.instantiateWasm(r,t);return}catch(e){return w("Module.instantiateWasm callback failed with error: "+e)}l||"function"!=typeof WebAssembly.instantiateStreaming||ce(P,fe)||de(P)||"function"!=typeof fetch?o(n):fetch(P,{credentials:"same-origin"}).then(function(e){return WebAssembly.instantiateStreaming(e,r).then(n,function(e){return w("wasm streaming compile failed: "+e),w("falling back to ArrayBuffer instantiation"),o(n)})})}(),h.___wasm_call_ctors=function(){return(_e=h.___wasm_call_ctors=h.asm.w).apply(null,arguments)}),be=h._malloc=function(){return(be=h._malloc=h.asm.x).apply(null,arguments)},De=h.___errno_location=function(){return(De=h.___errno_location=h.asm.y).apply(null,arguments)},Se=(h._main=function(){return(h._main=h.asm.z).apply(null,arguments)},h.stackAlloc=function(){return(Se=h.stackAlloc=h.asm.A).apply(null,arguments)});function Fe(e){this.name="ExitStatus",this.message="Program terminated with exit("+e+")",this.status=e}function Pe(r){var t=h._main;r=r||[];try{for(let e=0;e>2]=V(C);for(var n=1;n>2)+n]=V(e[n-1]);return k[(t>>2)+r]=0,{argc:r,argv:t}}(s.split(" ").filter(e=>Boolean(e)));if(0!==(n=t(o,i)))break}xe(n,!0)}catch(e){if(e instanceof Fe)return;if("unwind"==e)return void(d=!0);var a=e;e&&"object"==typeof e&&e.stack&&(a=[e,e.stack]),w("exception thrown: "+a),u(1,e)}}function Ae(e){function r(){Ee||(Ee=!0,h.calledRun=!0,U||(h.noFSInit||T.init.initialized||T.init(),Z(J),T.ignorePermissions=!1,Z(Q),j(h),h.onRuntimeInitialized&&h.onRuntimeInitialized(),Re&&Pe(e),te()))}e=e||a,0<_||(re(),0<_||(h.setStatus?(h.setStatus("Running..."),setTimeout(function(){setTimeout(function(){h.setStatus("")},1),r()},1)):r()))}function xe(e,r){r&&d&&0===e||(d||(U=!0,h.onExit&&h.onExit(e)),u(e,new Fe(e)))}if(h.dynCall_vi=function(){return(h.dynCall_vi=h.asm.B).apply(null,arguments)},b=function e(){Ee||Ae(),Ee||(b=e)},h.run=Ae,h.preInit)for("function"==typeof h.preInit&&(h.preInit=[h.preInit]);0{0{t+=String.fromCharCode(e),10===e&&(console.error(t),t="")},stdout:e=>{r+=String.fromCharCode(e),10===e&&(console.log(r),r="")}};const l=[];return async(e={})=>{let{data:i=null,command:a=[],folder:s=[],isStrict:u=!1}=e;return await new Promise(e=>{l.push(e),1===l.length&&l[0]()}),new Promise((r,t)=>{let n=!1,o="";c({stdout:f.stdout,stderr:e=>{o+=String.fromCharCode(e),10===e&&(console.error(o),u&&t(o))},arguments:a,input:i,folder:s,output:e=>{r(e),n=!0}}).then(()=>{(0,f.flush)(),n||t(),0{var e=await gifsicle(r.data).catch(e=>{postMessage(e)});postMessage(e)})().catch(e=>{postMessage(null)})};`,workerBlobUrl:"",worker(){return this.workerBlobUrl||(this.workerLocalUrl?this.workerBlobUrl=URL.createObjectURL(new Blob([this.workerLocalUrl])):this.workerBlobUrl="../src/worker.js",this.workerBlobUrl)},errorLink(){return` Check: https://github.com/renzhezhilu/gifsicle-wasm-browser`},testType(e){return e instanceof Element?"element":Object.prototype.toString.call(e).replace(/\[object\s(.+)\]/,"$1").toLowerCase()},async textToUrl(e){return this.worker()},loadCommand(e){var A=this.testType(e);if(e.length===0)throw" the content can not be blank"+this.errorLink();if(A==="array")return e.map(g=>g.replace(/\n/gi," "));throw" types:"+A+", must be an array"+this.errorLink()},loadOne(e){return new Promise(async(A,g)=>{var t=this.testType(e);if(["string"].includes(t))fetch(e).then(I=>{if(I.status!==200)throw"<"+e+"> Url error!!!"+this.errorLink();return I.arrayBuffer()}).then(I=>A(I));else if(["blob","file"].includes(t))new Response(e).arrayBuffer().then(I=>A(I));else{if(!["arraybuffer"].includes(t))throw" types:"+t+", only supports Url, blob, file, arraybuffer"+this.errorLink();A(e)}})},loadFile(e){return new Promise(async(A,g)=>{var t=this.testType(e);if(t!=="array")throw" types:"+t+", only supports Array"+this.errorLink();if(e.length===0)throw" the content can not be blank"+this.errorLink();t=e.map(I=>this.loadOne(I.file)),Promise.all(t).then(function(I){var o=e.map((i,r)=>(i.file=I[r],i));A(o)}).catch(function(I){})})},loadFolder(e){return new Promise(async(A,g)=>{var t=this.testType(e);if(!["array"].includes(t))throw" types:"+t+", only supports Array"+this.errorLink();A(e)})}},run(e={}){return new Promise(async(A,g)=>{let{input:t=[],command:I="",folder:o=[],isStrict:i=!1,start:r=E=>{}}=e;var C=await this.tool.textToUrl();let B=new Worker(C);var n=this.tool.loadCommand(I),Q=await this.tool.loadFile(t),a=(r(Q),await this.tool.loadFolder(o));B.postMessage({data:Q,command:n,folder:a,isStrict:i}),B.onmessage=async function(E){if(!E.data||typeof E.data=="string")return B.terminate(),void g(E.data);let h=[];for(let u=0;u=0&&n.push(`--loopcount=${C}`),r&&r>0&&n.push(`--lossy=${r}`),i&&n.push(`-O${this.optimizationLevel}`),n.push("1.gif"),n.push("-o /out/output.gif");const Q=n.join(" ");this.debug&&(console.log("GIF 缩放命令:",Q),console.log("输入文件大小:",A.size||"未知"));const a=await ke.run({input:[{file:A,name:"1.gif"}],command:[Q]});if(!a||a.length===0)throw new Error("gifsicle 处理失败,未返回结果");const E=a[0];if(this.debug&&(console.log("GIF 缩放完成"),console.log("输出文件大小:",E.size),A.size)){const h=((1-E.size/A.size)*100).toFixed(2);console.log(`压缩率: ${h}%`)}return new Blob([E],{type:"image/gif"})}catch(B){throw console.error("GIF 缩放失败:",B),new Error(`GIF 缩放失败: ${B.message}`)}}async scaleGifBatch(A){const g=[];for(let t=0;t=0&&i.push(`--loopcount=${o}`),t&&t>0&&i.push(`--lossy=${t}`),i.push(`-O${I}`),i.push("1.gif"),i.push("-o /out/output.gif");const r=i.join(" ");this.debug&&console.log("GIF 优化命令:",r);const C=await ke.run({input:[{file:A,name:"1.gif"}],command:[r]});if(!C||C.length===0)throw new Error("gifsicle 优化失败");return new Blob([C[0]],{type:"image/gif"})}catch(i){throw console.error("GIF 优化失败:",i),new Error(`GIF 优化失败: ${i.message}`)}}async getGifInfo(A){try{const g=await ke.run({input:[{file:A,name:"1.gif"}],command:["--info 1.gif -o /out/info.txt"]});if(!g||g.length===0)throw new Error("无法获取 GIF 信息");const I=await g[0].text();return this.parseGifInfo(I)}catch(g){return console.error("获取 GIF 信息失败:",g),{size:A.size||0,type:"image/gif"}}}parseGifInfo(A){const g={frames:0,width:0,height:0,colors:0,loopCount:0};try{const t=A.match(/(\d+) images?/);t&&(g.frames=parseInt(t[1]));const I=A.match(/logical screen (\d+)x(\d+)/);I&&(g.width=parseInt(I[1]),g.height=parseInt(I[2]));const o=A.match(/(\d+) colors/);if(o&&(g.colors=parseInt(o[1])),A.includes("loop forever"))g.loopCount=0;else{const i=A.match(/loop count (\d+)/);i&&(g.loopCount=parseInt(i[1]))}}catch(t){console.warn("解析 GIF 信息时出错:",t)}return g}async cropGif(A,g){const{x:t,y:I,width:o,height:i}=g;try{const r=["-U",`--crop ${t},${I}+${o}x${i}`,"1.gif","-o /out/output.gif"].join(" ");this.debug&&console.log("GIF 裁剪命令:",r);const C=await ke.run({input:[{file:A,name:"1.gif"}],command:[r]});if(!C||C.length===0)throw new Error("gifsicle 裁剪失败");return new Blob([C[0]],{type:"image/gif"})}catch(r){throw console.error("GIF 裁剪失败:",r),new Error(`GIF 裁剪失败: ${r.message}`)}}dispose(){this.debug&&console.log("WasmGifScaler disposed")}setDebug(A){this.debug=A}setQuality(A){if(A<1||A>200)throw new Error("质量参数必须在 1-200 之间");this.quality=A}setOptimizationLevel(A){if(A<1||A>3)throw new Error("优化级别必须在 1-3 之间");this.optimizationLevel=A}}class sI{constructor(){this.config=null,this.resources=new Map,this.tempFiles=[],this.fontConverterBrowser=nE,this.convertedFonts=new Map,this.wakenetPacker=new BE,this.spiffsGenerator=new sE,this.gifScaler=new aE({quality:30,debug:!0,scalingMode:"auto",optimize:!0,optimizationLevel:2}),this.configStorage=cA,this.autoSaveEnabled=!0}setConfig(A,g={}){if(((g==null?void 0:g.strict)??!0)&&!this.validateConfig(A))throw new Error("Configuration object validation failed");return this.config={...A},this}validateConfig(A){var I,o,i;if(!A)return!1;if(!((I=A.chip)!=null&&I.model))return console.error("Missing chip model configuration"),!1;const g=A.chip.display;if(!(g!=null&&g.width)||!(g!=null&&g.height))return console.error("Missing display resolution configuration"),!1;const t=(o=A.theme)==null?void 0:o.font;return(t==null?void 0:t.type)==="preset"&&!t.preset?(console.error("Preset font configuration is incomplete"),!1):(t==null?void 0:t.type)==="custom"&&!((i=t.custom)!=null&&i.file)?(console.error("Custom font file not provided"),!1):!0}addResource(A,g,t,I="other"){return this.resources.set(A,{file:g,filename:t,size:g.size,type:g.type,lastModified:g.lastModified||Date.now(),resourceType:I}),this.autoSaveEnabled&&g instanceof File&&this.saveFileToStorage(A,g,I).catch(o=>{console.warn(`Auto-saving file ${t} failed:`,o)}),this}async saveFileToStorage(A,g,t){try{await this.configStorage.saveFile(A,g,t),console.log(`File ${g.name} auto-saved to storage`)}catch(I){throw console.error(`Failed to save file to storage: ${g.name}`,I),I}}async restoreResourceFromStorage(A){try{const g=await this.configStorage.loadFile(A);return g?(this.resources.set(A,{file:g,filename:g.name,size:g.size,type:g.type,lastModified:g.lastModified,resourceType:g.storedType,fromStorage:!0}),console.log(`Resource ${A} restored from storage successfully: ${g.name}`),!0):!1}catch(g){return console.error(`Failed to restore resource from storage: ${A}`,g),!1}}async restoreAllResourcesFromStorage(A){var t,I,o,i,r,C,B,n,Q,a,E;if(!A)return;const g=[];if((I=(t=A.theme)==null?void 0:t.font)!=null&&I.custom&&((o=A.theme.font.custom)==null?void 0:o.file)===null){const h="custom_font";if(await this.restoreResourceFromStorage(h)){const w=this.resources.get(h);w&&(A.theme.font.custom.file=w.file,g.push(`Custom font: ${w.filename}`),console.log(`Custom font restored even when type is '${A.theme.font.type}'`))}}if(((r=(i=A.theme)==null?void 0:i.emoji)==null?void 0:r.type)==="custom"&&A.theme.emoji.custom){const h=A.theme.emoji.custom,w=h.emotionMap||{},u=h.fileMap||{},l=h.images||{};if(Object.keys(w).length>0||Object.keys(u).length>0){const f=new Set;for(const c of Object.keys(u))u[c]===null&&f.add(c);for(const c of f){let D=`hash_${c}`,y=await this.restoreResourceFromStorage(D);if(!y){const v=`emoji_hash_${c}`;y=await this.restoreResourceFromStorage(v),y&&(D=v)}if(y){const v=this.resources.get(D);if(v){u[c]=v.file;const N=Object.entries(w).filter(([L,X])=>X===c).map(([L,X])=>L);N.forEach(L=>{l[L]=v.file}),g.push(`Emoji file ${c.substring(0,8)}... (used for: ${N.join(", ")})`)}}}Object.keys(u).forEach(c=>{A.theme.emoji.custom.fileMap[c]=u[c]}),Object.keys(l).forEach(c=>{A.theme.emoji.custom.images[c]=l[c]})}else{for(const[f,c]of Object.entries(l))if(c===null){const D=`emoji_${f}`;if(await this.restoreResourceFromStorage(D)){const y=this.resources.get(D);y&&(l[f]=y.file,g.push(`Emoji ${f}: ${y.filename}`))}}A.theme.emoji.custom.images=l}}if(((n=(B=(C=A.theme)==null?void 0:C.skin)==null?void 0:B.light)==null?void 0:n.backgroundType)==="image"&&A.theme.skin.light.backgroundImage===null){const h="background_light";if(await this.restoreResourceFromStorage(h)){const w=this.resources.get(h);w&&(A.theme.skin.light.backgroundImage=w.file,g.push(`Light background: ${w.filename}`))}}if(((E=(a=(Q=A.theme)==null?void 0:Q.skin)==null?void 0:a.dark)==null?void 0:E.backgroundType)==="image"&&A.theme.skin.dark.backgroundImage===null){const h="background_dark";if(await this.restoreResourceFromStorage(h)){const w=this.resources.get(h);w&&(A.theme.skin.dark.backgroundImage=w.file,g.push(`Dark background: ${w.filename}`))}}try{const h=this.getFontInfo();if(h&&h.type==="custom"){const w=`converted_font_${h.filename}`,u=await this.configStorage.loadTempData(w);u&&(this.convertedFonts.set(h.filename,u.data),console.log(`Converted font data restored: ${h.filename}`))}}catch(h){console.warn("Error restoring converted font data:",h)}g.length>0&&console.log("Files restored from storage:",g)}getWakewordModelInfo(){if(!this.config||!this.config.chip||!this.config.theme)return null;const A=this.config.chip.model,g=this.config.theme.wakeword;return!g||g.type==="none"?null:g.type==="preset"?{type:A==="esp32c3"||A==="esp32c6"?"WakeNet9s":"WakeNet9",name:g.preset,filename:"srmodels.bin"}:g.type==="custom"?{type:"MultiNet",name:g.custom.model,filename:"srmodels.bin",custom:g.custom}:null}getFontInfo(){if(!this.config||!this.config.theme||!this.config.theme.font)return null;const A=this.config.theme.font;if(A.type==="preset")return{type:"preset",filename:`${A.preset}.bin`,source:A.preset};if(A.type==="custom"&&A.custom.file){const g=A.custom;return{type:"custom",filename:`font_custom_${g.size}_${g.bpp}.bin`,source:A.custom.file,config:{size:g.size,bpp:g.bpp,charset:g.charset}}}return null}getEmojiCollectionInfo(){if(!this.config||!this.config.theme||!this.config.theme.emoji)return[];const A=this.config.theme.emoji,g=[];if(A.type==="preset"){const t=["neutral","happy","laughing","funny","sad","angry","crying","loving","embarrassed","surprised","shocked","thinking","winking","cool","relaxed","delicious","kissy","confident","sleepy","silly","confused"],o={twemoji32:{size:32,format:"png"},twemoji64:{size:64,format:"png"},"noto-emoji_64":{size:64,format:"gif"},"noto-emoji_128":{size:128,format:"gif"}}[A.preset]||{size:64,format:"png"};t.forEach(i=>{g.push({name:i,file:`${i}.${o.format}`,source:`preset:${A.preset}`,size:{width:o.size,height:o.size}})})}else if(A.type==="custom"){A.custom.images;const t=A.custom.emotionMap||{},I=A.custom.fileMap||{},o=A.custom.size||{width:64,height:64};if(Object.keys(t).length===0||Object.keys(I).length===0)throw console.error("❌ Error: Detected old version of emoji data structure"),console.error("Please clear browser cache or reset configuration, then re-upload emoji images"),new Error("Incompatible emoji data structure: Missing fileMap or emotionMap. Please reconfigure emojis.");const i=new Map;Object.entries(t).forEach(([r,C])=>{const B=I[C];if(B){if(!i.has(C)){const Q=B.name?B.name.split(".").pop().toLowerCase():"png",a=`emoji_${C.substring(0,8)}.${Q}`;i.set(C,a)}const n=i.get(C);g.push({name:r,file:n,source:B,fileHash:C,size:{...o}})}}),console.log(`Emoji deduplication: ${Object.keys(t).length} emojis using ${i.size} different image files`),g.find(r=>r.name==="neutral")||console.warn("Warning: neutral emoji not provided, default image will be used")}return g}getSkinInfo(){if(!this.config||!this.config.theme||!this.config.theme.skin)return{};const A=this.config.theme.skin,g={};return A.light&&(g.light={text_color:A.light.textColor||"#000000",background_color:A.light.backgroundColor||"#ffffff"},A.light.backgroundType==="image"&&A.light.backgroundImage&&(g.light.background_image="background_light.raw")),A.dark&&(g.dark={text_color:A.dark.textColor||"#ffffff",background_color:A.dark.backgroundColor||"#121212"},A.dark.backgroundType==="image"&&A.dark.backgroundImage&&(g.dark.background_image="background_dark.raw")),g}generateIndexJson(){if(!this.config)throw new Error("Configuration object not set");const A={version:1,chip_model:this.config.chip.model,hide_subtitle:this.config.theme.font.hide_subtitle||!1,display_config:{width:this.config.chip.display.width,height:this.config.chip.display.height,monochrome:!1,color:this.config.chip.display.color||"RGB565"}},g=this.getWakewordModelInfo();if(g&&(A.srmodels=g.filename,g.type==="MultiNet"&&g.custom)){const i=g.custom;A.multinet_model={language:i.model.includes("_en")?"en":"cn",duration:i.duration||3e3,threshold:i.threshold/100,commands:[{command:i.command,text:i.name,action:"wake"}]}}const t=this.getFontInfo();t&&(A.text_font=t.filename);const I=this.getSkinInfo();Object.keys(I).length>0&&(A.skin=I);const o=this.getEmojiCollectionInfo();return o.length>0&&(A.emoji_collection=o.map(i=>({name:i.name,file:i.file}))),A}preparePackageResources(){var r,C,B,n;const A={files:[],indexJson:this.generateIndexJson(),config:{...this.config}},g=this.getWakewordModelInfo();g&&g.name&&A.files.push({type:"wakeword",name:g.name,filename:g.filename,modelType:g.type,isCustom:g.type==="MultiNet"});const t=this.getFontInfo();t&&A.files.push({type:"font",filename:t.filename,source:t.source,config:t.config||null});const I=this.getEmojiCollectionInfo(),o=new Set;I.forEach(Q=>{if(Q.fileHash){if(o.has(Q.fileHash)){console.log(`Skipping duplicate file: ${Q.name} -> ${Q.file} (hash: ${Q.fileHash.substring(0,8)})`);return}o.add(Q.fileHash)}A.files.push({type:"emoji",name:Q.name,filename:Q.file,source:Q.source,size:Q.size,fileHash:Q.fileHash})});const i=(C=(r=this.config)==null?void 0:r.theme)==null?void 0:C.skin;return((B=i==null?void 0:i.light)==null?void 0:B.backgroundType)==="image"&&i.light.backgroundImage&&A.files.push({type:"background",filename:"background_light.raw",source:i.light.backgroundImage,mode:"light"}),((n=i==null?void 0:i.dark)==null?void 0:n.backgroundType)==="image"&&i.dark.backgroundImage&&A.files.push({type:"background",filename:"background_dark.raw",source:i.dark.backgroundImage,mode:"dark"}),A}async preprocessCustomFonts(A=null){const g=this.getFontInfo();if(g&&g.type==="custom"&&!this.convertedFonts.has(g.filename)){A&&A(20,"Converting custom font...");try{const t={fontFile:g.source,fontName:g.filename.replace(/\.bin$/,""),fontSize:g.config.size,bpp:g.config.bpp,charset:g.config.charset,symbols:g.config.symbols||"",range:g.config.range||"",compression:!1,progressCallback:(o,i)=>{A&&A(20+o*.2,`Font conversion: ${i}`)}};let I;if(await this.fontConverterBrowser.initialize(),I=await this.fontConverterBrowser.convertToCBIN(t),this.convertedFonts.set(g.filename,I),this.autoSaveEnabled){const o=`converted_font_${g.filename}`;try{await this.configStorage.saveTempData(o,I,"converted_font",{filename:g.filename,size:g.config.size,bpp:g.config.bpp,charset:g.config.charset}),console.log(`Converted font saved to storage: ${g.filename}`)}catch(i){console.warn(`Failed to save converted font: ${g.filename}`,i)}}}catch(t){throw console.error("Font conversion failed:",t),new Error(`Font conversion failed: ${t.message}`)}}}async generateAssetsBin(A=null){if(!this.config)throw new Error("Configuration object not set");try{A&&A(0,"Starting generation..."),await this.preprocessCustomFonts(A),await new Promise(I=>setTimeout(I,100)),A&&A(40,"Preparing resource files...");const g=this.preparePackageResources();this.wakenetPacker.clear(),this.spiffsGenerator.clear(),await this.processResourceFiles(g,A),await new Promise(I=>setTimeout(I,100)),A&&A(90,"Generating final file..."),this.spiffsGenerator.printFileList();const t=await this.spiffsGenerator.generate((I,o)=>{A&&A(90+I*.1,o)});return A&&A(100,"Generation completed"),new Blob([t],{type:"application/octet-stream"})}catch(g){throw console.error("Failed to generate assets.bin:",g),g}}downloadAssetsBin(A,g="assets.bin"){const t=URL.createObjectURL(A),I=document.createElement("a");I.href=t,I.download=g,document.body.appendChild(I),I.click(),document.body.removeChild(I),URL.revokeObjectURL(t)}async getFontInfoWithDetails(A=null){var g,t,I,o;try{const i=A||((o=(I=(t=(g=this.config)==null?void 0:g.theme)==null?void 0:t.font)==null?void 0:I.custom)==null?void 0:o.file);if(!i)return null;let r;return await this.fontConverterBrowser.initialize(),r=await this.fontConverterBrowser.getFontInfo(i),{...r,file:i,isCustom:!0}}catch(i){return console.error("Failed to get font details:",i),null}}async estimateFontSize(A=null){var g,t,I;try{const o=A||((I=(t=(g=this.config)==null?void 0:g.theme)==null?void 0:t.font)==null?void 0:I.custom);if(!o)return null;const i={fontSize:o.size,bpp:o.bpp,charset:o.charset,symbols:o.symbols||"",range:o.range||""};let r;return r=this.fontConverterBrowser.estimateSize(i),r}catch(o){return console.error("Failed to estimate font size:",o),null}}validateCustomFont(A){const g=[],t=[];return A.file?this.fontConverterBrowser.validateFont(A.file)||g.push("Font file format not supported"):g.push("Missing font file"),(A.size<8||A.size>80)&&g.push("Font size must be between 8-80"),[1,2,4,8].includes(A.bpp)||g.push("BPP must be 1, 2, 4 or 8"),!A.charset&&!A.symbols&&!A.range&&t.push("No charset, symbols or range specified, default charset will be used"),{valid:g.length===0,errors:g,warnings:t}}getConverterStatus(){return{initialized:this.fontConverterBrowser.initialized,supportedFormats:this.fontConverterBrowser.supportedFormats}}async processResourceFiles(A,g=null){let t=0;const I=A.files.length,o=new TextEncoder().encode(JSON.stringify(A.indexJson,null,2));console.log("index.json",A.indexJson),this.spiffsGenerator.addFile("index.json",o.buffer);for(const i of A.files){const r=40+t/I*40;g&&g(r,`Processing file: ${i.filename}`);try{await this.processResourceFile(i),t++}catch(C){throw console.error(`Failed to process resource file: ${i.filename}`,C),new Error(`Failed to process resource file: ${i.filename} - ${C.message}`)}}}async processResourceFile(A){switch(A.type){case"wakeword":await this.processWakewordModel(A);break;case"font":await this.processFontFile(A);break;case"emoji":await this.processEmojiFile(A);break;case"background":await this.processBackgroundFile(A);break;default:console.warn(`Unknown resource type: ${A.type}`)}}async processWakewordModel(A){if(!await this.wakenetPacker.loadModelFromShare(A.name))throw new Error(`Failed to load wakeword model: ${A.name}`);const t=this.wakenetPacker.packModels();this.spiffsGenerator.addFile(A.filename,t)}async processFontFile(A){if(A.config){const g=this.convertedFonts.get(A.filename);if(g)this.spiffsGenerator.addFile(A.filename,g);else throw new Error(`Converted font not found: ${A.filename}`)}else{const g=await this.loadPresetFont(A.source);this.spiffsGenerator.addFile(A.filename,g)}}async processEmojiFile(A){var i,r;let g,t=!1,I="png",o=!1;if(typeof A.source=="string"&&A.source.startsWith("preset:")){const C=A.source.replace("preset:","");g=await this.loadPresetEmoji(C,A.name)}else{const C=A.source;o=this.isGifFile(C),I=C.name.split(".").pop().toLowerCase();try{const n=await this.getImageDimensions(C),Q=A.size||{width:64,height:64};(n.width>Q.width||n.height>Q.height)&&(t=!0,console.log(`Emoji ${A.name} needs scaling: ${n.width}x${n.height} -> ${Q.width}x${Q.height}`))}catch(n){console.warn(`Failed to get emoji image dimensions: ${A.name}`,n)}t||(g=await this.fileToArrayBuffer(C))}if(t)try{const C=A.size||{width:64,height:64};if(o){console.log(`Using WasmGifScaler to process GIF emoji: ${A.name}`);const B=await this.gifScaler.scaleGif(A.source,{maxWidth:C.width,maxHeight:C.height,keepAspectRatio:!0,lossy:30});g=await this.fileToArrayBuffer(B)}else g=await this.scaleImageToFit(A.source,C,I)}catch(C){console.error(`Failed to scale emoji image: ${A.name}`,C),g=await this.fileToArrayBuffer(A.source)}this.spiffsGenerator.addFile(A.filename,g,{width:((i=A.size)==null?void 0:i.width)||0,height:((r=A.size)==null?void 0:r.height)||0}),A.fileHash&&console.log(`Emoji file added: ${A.filename} (hash: ${A.fileHash.substring(0,8)})`)}async processBackgroundFile(A){const g=await this.fileToArrayBuffer(A.source),t=await this.convertImageToRgb565(g);this.spiffsGenerator.addFile(A.filename,t)}async loadPresetFont(A){try{const g=await fetch(`./static/fonts/${A}.bin`);if(!g.ok)throw new Error(`HTTP ${g.status}`);return await g.arrayBuffer()}catch(g){throw new Error(`Failed to load preset font: ${A} - ${g.message}`)}}async loadPresetEmoji(A,g){try{const I={twemoji32:"png",twemoji64:"png","noto-emoji_64":"gif","noto-emoji_128":"gif"}[A]||"png",o=await fetch(`./static/emojis/${A}/${g}.${I}`);if(!o.ok)throw new Error(`HTTP ${o.status}`);return await o.arrayBuffer()}catch(t){throw new Error(`Failed to load preset emoji: ${A}/${g} - ${t.message}`)}}fileToArrayBuffer(A){return new Promise((g,t)=>{const I=new FileReader;I.onload=()=>g(I.result),I.onerror=()=>t(new Error("Failed to read file")),I.readAsArrayBuffer(A)})}async scaleImageToFit(A,g,t="png"){return new Promise((I,o)=>{const i=A instanceof File?A:new Blob([A]),r=URL.createObjectURL(i),C=new Image;C.onload=()=>{try{const B=document.createElement("canvas"),n=B.getContext("2d");B.width=g.width,B.height=g.height;const Q=C.width/C.height,a=g.width/g.height;let E,h,w,u;Q>a?(E=g.width,h=g.width/Q,w=0,u=(g.height-h)/2):(h=g.height,E=g.height*Q,w=(g.width-E)/2,u=0),t==="png"?n.clearRect(0,0,B.width,B.height):(n.fillStyle="#FFFFFF",n.fillRect(0,0,B.width,B.height)),n.drawImage(C,w,u,E,h),B.toBlob(l=>{const f=new FileReader;f.onload=()=>I(f.result),f.onerror=()=>o(new Error("Failed to convert image data")),f.readAsArrayBuffer(l)},`image/${t}`),URL.revokeObjectURL(r)}catch(B){URL.revokeObjectURL(r),o(B)}},C.onerror=()=>{URL.revokeObjectURL(r),o(new Error("Unable to load image"))},C.src=r})}isGifFile(A){return A.type==="image/gif"?!0:A.name.split(".").pop().toLowerCase()==="gif"}async getImageDimensions(A){return new Promise((g,t)=>{const I=A instanceof File?A:new Blob([A]),o=URL.createObjectURL(I),i=new Image;i.onload=()=>{URL.revokeObjectURL(o),g({width:i.width,height:i.height})},i.onerror=()=>{URL.revokeObjectURL(o),t(new Error("Unable to get image dimensions"))},i.src=o})}async convertImageToRgb565(A){return new Promise((g,t)=>{const I=new Blob([A]),o=URL.createObjectURL(I),i=new Image;i.onload=()=>{var r,C,B,n,Q,a;try{const E=document.createElement("canvas"),h=E.getContext("2d",{willReadFrequently:!0});E.width=((B=(C=(r=this.config)==null?void 0:r.chip)==null?void 0:C.display)==null?void 0:B.width)||320,E.height=((a=(Q=(n=this.config)==null?void 0:n.chip)==null?void 0:Q.display)==null?void 0:a.height)||240;const w=i.width/i.height,u=E.width/E.height;let l,f,c,D;w>u?(f=E.height,l=E.height*w,c=(E.width-l)/2,D=0):(l=E.width,f=E.width/w,c=0,D=(E.height-f)/2),h.drawImage(i,c,D,l,f);const v=h.getImageData(0,0,E.width,E.height).data,N=new ArrayBuffer(E.width*E.height*2),L=new Uint16Array(N);for(let _=0;_>3,b=v[_+1]>>2,H=v[_+2]>>3;L[_/4]=iA<<11|b<<5|H}const X=25,k=18,m=E.width*2,M=28,oA=M+N.byteLength,F=new ArrayBuffer(oA),S=new Uint8Array(F),J=new DataView(F);let V=0;const q=0|k<<8|X;J.setUint32(V,q,!0),V+=4;const $=E.height<<16|E.width;J.setUint32(V,$,!0),V+=4;const AA=0|m;J.setUint32(V,AA,!0),V+=4,J.setUint32(V,N.byteLength,!0),V+=4,J.setUint32(V,M,!0),V+=4,J.setUint32(V,0,!0),V+=4,J.setUint32(V,0,!0),V+=4,S.set(new Uint8Array(N),M),URL.revokeObjectURL(o),g(F)}catch(E){URL.revokeObjectURL(o),t(E)}},i.onerror=()=>{URL.revokeObjectURL(o),t(new Error("Unable to load image"))},i.src=o})}cleanup(){this.resources.clear(),this.tempFiles=[],this.convertedFonts.clear(),this.wakenetPacker.clear(),this.spiffsGenerator.clear(),this.gifScaler.dispose()}async clearAllStoredData(){try{await this.configStorage.clearAll(),this.cleanup(),console.log("All stored data cleared")}catch(A){throw console.error("Failed to clear stored data:",A),A}}async getStorageStatus(){try{const A=await this.configStorage.getStorageInfo();return{hasStoredData:await this.configStorage.hasStoredConfig(),storageInfo:A,autoSaveEnabled:this.autoSaveEnabled}}catch(A){return console.error("Failed to get storage status:",A),{hasStoredData:!1,storageInfo:null,autoSaveEnabled:this.autoSaveEnabled}}}setAutoSave(A){this.autoSaveEnabled=A,console.log(`Auto-save ${A?"enabled":"disabled"}`)}getResourceSummary(){const A=[],g=this.preparePackageResources(),t={wakeword:0,font:0,emoji:0,background:0};return g.files.forEach(I=>{t[I.type]=(t[I.type]||0)+1;let o="";switch(I.type){case"wakeword":o=`Wakeword model: ${I.name} (${I.modelType})`;break;case"font":I.config?o=`Custom font: size ${I.config.size}px, BPP ${I.config.bpp}`:o=`Preset font: ${I.source}`;break;case"emoji":o=`Emoji: ${I.name} (${I.size.width}x${I.size.height})`;break;case"background":o=`${I.mode==="light"?"Light":"Dark"} mode background`;break}A.push({type:I.type,filename:I.filename,description:o})}),{files:A,counts:t,totalFiles:A.length,indexJson:g.indexJson}}}const QE={class:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4"},EE={class:"bg-white rounded-lg shadow-xl max-w-2xl w-full max-h-[90vh] overflow-hidden"},lE={class:"flex items-center justify-between p-6 border-b border-gray-200"},cE={class:"text-lg font-medium text-gray-900"},hE={key:1,class:"text-sm text-orange-600 font-medium"},uE={class:"p-6 overflow-y-auto",style:{"max-height":"calc(90vh - 140px)"}},dE={key:0,class:"space-y-6"},fE={class:"font-medium text-gray-900 mb-3"},wE={class:"bg-gray-50 rounded-lg p-4 space-y-2 text-sm"},yE={class:"flex justify-between"},pE={class:"text-gray-600"},DE={class:"font-medium"},mE={class:"flex justify-between"},FE={class:"text-gray-600"},kE={class:"font-medium"},vE={class:"flex justify-between"},SE={class:"text-gray-600"},GE={class:"font-medium"},RE={class:"flex justify-between"},UE={class:"text-gray-600"},NE={class:"font-medium"},bE={class:"flex justify-between"},LE={class:"text-gray-600"},ME={class:"font-medium"},JE={class:"font-medium text-gray-900 mb-3"},xE={class:"space-y-2 max-h-64 overflow-y-auto"},HE={class:"flex items-center"},YE={class:"text-sm font-medium text-gray-900"},KE={class:"text-sm text-gray-700"},TE={key:0,class:"text-xs text-gray-500 ml-1"},VE={key:1,class:"text-xs text-gray-500 ml-1"},qE={key:1,class:"space-y-6 text-center"},OE={class:"space-y-4"},WE={class:"text-gray-600 mt-2"},PE={class:"bg-gray-200 rounded-full h-2 overflow-hidden"},ZE={class:"text-sm text-gray-600"},XE={class:"mt-1"},jE={class:"space-y-2 text-left"},zE={class:"flex-shrink-0 mr-3"},_E={key:0,class:"w-5 h-5 bg-green-500 rounded-full flex items-center justify-center"},$E={key:1,class:"w-5 h-5 bg-primary-500 rounded-full animate-pulse"},Al={key:2,class:"w-5 h-5 bg-gray-300 rounded-full"},el={key:2,class:"text-center space-y-6"},gl={class:"text-gray-600 mt-2"},tl={class:"bg-green-50 border border-green-200 rounded-lg p-4"},Il={class:"text-sm text-green-800 space-y-1"},ol={class:"space-y-3"},il=["disabled"],rl={key:3,class:"space-y-6 text-center"},Cl={class:"space-y-4"},nl={class:"text-gray-600"},Bl={class:"bg-gray-200 rounded-full h-2 overflow-hidden"},sl={class:"text-sm text-gray-600"},al={class:"mt-1"},Ql={key:4,class:"text-center mt-4"},El={class:"text-sm text-red-600"},ll={class:"flex justify-end space-x-3 p-6 border-t border-gray-200"},cl=["disabled"],hl={__name:"GenerateModal",props:{config:{type:Object,required:!0}},emits:["close","generate","startFlash","cancelFlash"],setup(e,{emit:A}){const{t:g}=TA(),t=e,I=A,{deviceInfo:o}=ig(),i=j(!1),r=j(!1),C=j(0),B=j(""),n=j(""),Q=j(""),a=j(null),E=j(null),h=j(!1),w=j(!1),u=j(0),l=j(""),f=j(""),c=nA(()=>[{id:1,name:g("progressSteps.init"),status:"pending"},{id:2,name:g("progressSteps.font"),status:"pending"},{id:3,name:g("progressSteps.wakeword"),status:"pending"},{id:4,name:g("progressSteps.emoji"),status:"pending"},{id:5,name:g("progressSteps.background"),status:"pending"},{id:6,name:g("progressSteps.index"),status:"pending"},{id:7,name:g("progressSteps.spiffs"),status:"pending"},{id:8,name:g("progressSteps.package"),status:"pending"}]),D=j([]),y=we({render:()=>eA("svg",{fill:"currentColor",viewBox:"0 0 20 20"},[eA("path",{d:"M4 3a2 2 0 00-2 2v1a1 1 0 001 1h14a1 1 0 001-1V5a2 2 0 00-2-2H4zM3 8a1 1 0 011-1h12a1 1 0 011 1v5a2 2 0 01-2 2H5a2 2 0 01-2-2V8z"})])}),v=we({render:()=>eA("svg",{fill:"currentColor",viewBox:"0 0 20 20"},[eA("path",{"fill-rule":"evenodd",d:"M7 4a3 3 0 016 0v4a3 3 0 11-6 0V4zm4 10.93A7.001 7.001 0 0017 8a1 1 0 10-2 0A5 5 0 015 8a1 1 0 00-2 0 7.001 7.001 0 006 6.93V17H6a1 1 0 100 2h8a1 1 0 100-2h-3v-2.07z","clip-rule":"evenodd"})])}),N=we({render:()=>eA("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},[eA("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M8 4l8 16m-6-6h4"})])}),L=we({render:()=>eA("svg",{fill:"currentColor",viewBox:"0 0 20 20"},[eA("path",{"fill-rule":"evenodd",d:"M4 3a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V5a2 2 0 00-2-2H4zm12 12H4l4-8 3 6 2-4 3 6z","clip-rule":"evenodd"})])}),X=nA(()=>D.value.length>0),k={wn9s_hilexin:"generateModal.wakewordNames.wn9s_hilexin",wn9s_hiesp:"generateModal.wakewordNames.wn9s_hiesp",wn9s_nihaoxiaozhi:"generateModal.wakewordNames.wn9s_nihaoxiaozhi",wn9s_hijason:"Hi, Jason",wn9s_alexa:"Alexa",wn9_hilexin:"Hi, Espressif",wn9_hiesp:"Hi, ESP",wn9_nihaoxiaozhi_tts:"generateModal.wakewordNames.wn9_nihaoxiaozhi_tts",wn9_hijason_tts2:"Hi, Jason",wn9_himfive:"Hi, M Five",wn9_alexa:"generateModal.wakewordNames.wn9_alexa",wn9_jarvis_tts:"Jarvis",wn9_computer_tts:"Computer",wn9_heywillow_tts:"Hey, Willow",wn9_sophia_tts:"Sophia",wn9_heyprinter_tts:"Hey, Printer",wn9_hijoy_tts:"Hi, Joy",wn9_heywanda_tts:"Hey, Wand",wn9_astrolabe_tts:"Astrolabe",wn9_heyily_tts2:"Hey, Ily",wn9_hijolly_tts2:"Hi, Jolly",wn9_hifairy_tts2:"Hi, Fairy",wn9_bluechip_tts2:"Blue Chip",wn9_hiandy_tts2:"Hi, Andy",wn9_heyivy_tts2:"Hey, Ivy",wn9_histackchan_tts3:"Hi, Stack Chan",wn9_hiwalle_tts2:"Hi, Wall E",wn9_hilili_tts:"Hi, Lily",wn9_hitelly_tts:"Hi, Telly",wn9_linaiban_tts2:"Lina Board"},m=b=>{const H=k[b];return H!=null&&H.startsWith("generateModal.")?g(H):H||b},M=()=>{const b=t.config.theme.wakeword;return!b||b.type==="none"?g("wakewordConfig.noWakeword"):b.type==="preset"?m(b.preset):b.type==="custom"?b.custom.name||g("wakewordConfig.customWakeword"):g("wakewordConfig.noWakeword")},oA=()=>t.config.theme.font.type==="preset"?t.config.theme.font.preset.replace("font_","").replace("_"," "):g("generateModal.customFont"),F=()=>t.config.theme.emoji.type==="preset"&&t.config.theme.emoji.preset?{twemoji32:"Twemoji 32×32",twemoji64:"Twemoji 64×64","noto-emoji_64":"Noto Emoji 64×64","noto-emoji_128":"Noto Emoji 128×128"}[t.config.theme.emoji.preset]||t.config.theme.emoji.preset:t.config.theme.emoji.type==="custom"?g("generateModal.customEmoji"):t.config.theme.emoji.type==="none"?g("emojiConfig.noEmojiPack"):g("generateModal.notConfigured"),S=()=>{D.value=[],D.value.push({id:"index",name:"index.json",description:"Configuration index file",icon:y,iconColor:"text-blue-500",size:"1KB"});const b=t.config.theme.wakeword;if(b&&b.type!=="none"&&D.value.push({id:"srmodels",name:"srmodels.bin",description:b.type==="custom"?"Custom command model":"Preset wake word model",icon:v,iconColor:"text-green-500",size:b.type==="custom"?"~1.2MB":"~300KB"}),t.config.theme.font.type==="preset"){const H={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"};D.value.push({id:"font",name:`${t.config.theme.font.preset}.bin`,description:"Preset font file",icon:N,iconColor:"text-yellow-500",size:H[t.config.theme.font.preset]||"500KB"})}else if(t.config.theme.font.custom.file){const H=t.config.theme.font.custom,Z=Math.max(100,H.size*H.size*H.bpp*.7);D.value.push({id:"font",name:`font_custom_${H.size}_${H.bpp}.bin`,description:"Custom font file",icon:N,iconColor:"text-yellow-500",size:Z>1024?`${(Z/1024).toFixed(1)}MB`:`${Math.round(Z)}KB`,estimated:!0})}if(t.config.theme.emoji.type==="preset"&&t.config.theme.emoji.preset){const H=["neutral","happy","laughing","funny","sad","angry","crying","loving","embarrassed","surprised","shocked","thinking","winking","cool","relaxed","delicious","kissy","confident","sleepy","silly","confused"],Z=t.config.theme.emoji.preset==="twemoji64"?"3KB":"1KB";H.forEach(IA=>{D.value.push({id:`emoji_${IA}`,name:`${IA}.png`,description:`${IA} emoji image`,icon:L,iconColor:"text-pink-500",size:Z})})}else if(t.config.theme.emoji.type==="custom"){const H=t.config.theme.emoji.custom,Z=H.emotionMap||{},IA=H.fileMap||{};if(H.images,Object.keys(Z).length===0||Object.keys(IA).length===0){console.error(g("errors.incompatibleEmojiData"));return}const z=new Map,lA=new Map;Object.entries(Z).forEach(([wA,yA])=>{const JA=IA[yA];if(JA){if(!z.has(yA)){const ee=Math.round(JA.size/1024);z.set(yA,{file:JA,size:ee>1024?`${(ee/1024).toFixed(1)}MB`:`${ee}KB`,emotions:[]})}z.get(yA).emotions.push(wA),lA.set(wA,yA)}}),z.forEach((wA,yA)=>{const JA=wA.emotions.join(", "),ee=wA.emotions.length>1;D.value.push({id:`emoji_${yA.substring(0,8)}`,name:`emoji_${yA.substring(0,8)}.${wA.file.name.split(".").pop()}`,description:ee?`Shared emoji images (${JA})`:`${JA} emoji image`,icon:L,iconColor:ee?"text-purple-500":"text-pink-500",size:wA.size,isCustomEmoji:!0})}),z.size1024?`${(IA/1024).toFixed(1)}MB`:`${IA}KB`,estimated:!0})}if(t.config.theme.skin.dark.backgroundType==="image"&&t.config.theme.skin.dark.backgroundImage){const{width:H,height:Z}=t.config.chip.display,IA=Math.round(H*Z*2/1024);D.value.push({id:"bg_dark",name:"background_dark.raw",description:"Dark mode background image",icon:L,iconColor:"text-indigo-500",size:IA>1024?`${(IA/1024).toFixed(1)}MB`:`${IA}KB`,estimated:!0})}},J=b=>{if(b===0)return"0 B";const H=1024,Z=["B","KB","MB","GB"],IA=Math.floor(Math.log(b)/Math.log(H));return`${parseFloat((b/Math.pow(H,IA)).toFixed(2))} ${Z[IA]}`},V=b=>{if(b<1e3)return`${b}ms`;if(b<6e4)return`${(b/1e3).toFixed(1)}s`;{const H=Math.floor(b/6e4),Z=Math.floor(b%6e4/1e3);return`${H}m ${Z}s`}},q=async()=>{i.value=!0,C.value=0,E.value=Date.now();try{const b=new sI;b.setConfig(t.config);const H=await b.generateAssetsBin((z,lA)=>{C.value=parseInt(z),B.value=lA;const wA=Math.floor(z/(100/c.value.length));c.value.forEach((yA,JA)=>{JA{z.status="completed"}),I("generate",D.value.map(z=>({id:z.id,name:z.name})))}catch(b){console.error("Failed to generate assets.bin:",b),i.value=!1,r.value=!1,alert(g("errors.generationFailed",{error:b.message}))}},$=()=>{if(a.value){const b=URL.createObjectURL(a.value),H=document.createElement("a");H.href=b,H.download="assets.bin",H.style.display="none",document.body.appendChild(H),H.click(),document.body.removeChild(H),URL.revokeObjectURL(b)}else console.error(g("errors.noFileToDownload"))},AA=async()=>{try{const H=new URLSearchParams(window.location.search).get("token");if(!H){h.value=!1;return}const Z=await fetch("/api/messaging/device/tools/list",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${H}`}});h.value=Z.ok}catch(b){console.error(g("flashProgress.unableToGetDeviceStatus"),b),h.value=!1}},_=async()=>{if(!a.value){alert(g("errors.noFileToDownload"));return}if(!h.value){alert(g("errors.deviceOffline"));return}if(o.value.assetsPartition&&o.value.assetsPartition.size){const b=o.value.assetsPartition.size,H=a.value.size;if(H>b){const Z=(H/1024/1024).toFixed(2),IA=(b/1024/1024).toFixed(2);alert(g("errors.fileTooLarge",{fileSize:Z,partitionSize:IA}));return}}w.value=!0,u.value=0,l.value=g("flashProgress.startingFileTransfer"),f.value="";try{I("startFlash",{blob:a.value,onProgress:(b,H)=>{u.value=b,l.value=H},onComplete:()=>{w.value=!1,u.value=100,l.value=g("flashProgress.flashCompleted")},onError:b=>{w.value=!1,f.value=b,console.error(g("flashProgress.onlineFlashFailed",{error:b}))}})}catch(b){w.value=!1,f.value=g("flashProgress.onlineFlashFailed",{error:b.message}),console.error(g("flashProgress.onlineFlashFailed",{error:b}))}},iA=()=>{confirm(g("errors.flashCancelConfirm"))&&(w.value=!1,u.value=0,l.value="",f.value="",I("cancelFlash"))};return Me(async()=>{S(),await AA()}),(b,H)=>(G(),U("div",QE,[s("div",EE,[s("div",lE,[s("h3",cE,d(b.$t("generateModal.title")),1),w.value?(G(),U("div",hE,d(b.$t("generateModal.flashingInProgress")),1)):(G(),U("button",{key:0,onClick:H[0]||(H[0]=Z=>b.$emit("close")),class:"text-gray-400 hover:text-gray-500"},[...H[3]||(H[3]=[s("svg",{class:"w-6 h-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor"},[s("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M6 18L18 6M6 6l12 12"})],-1)])]))]),s("div",uE,[!i.value&&!r.value?(G(),U("div",dE,[s("div",null,[s("h4",fE,d(b.$t("generateModal.confirmConfig")),1),s("div",wE,[s("div",yE,[s("span",pE,d(b.$t("generateModal.chipModel")),1),s("span",DE,d(e.config.chip.model.toUpperCase()),1)]),s("div",mE,[s("span",FE,d(b.$t("generateModal.resolution")),1),s("span",kE,d(e.config.chip.display.width)+"×"+d(e.config.chip.display.height),1)]),s("div",vE,[s("span",SE,d(b.$t("generateModal.wakeword")),1),s("span",GE,d(M()),1)]),s("div",RE,[s("span",UE,d(b.$t("generateModal.font")),1),s("span",NE,d(oA()),1)]),s("div",bE,[s("span",LE,d(b.$t("generateModal.emoji")),1),s("span",ME,d(F()),1)])])]),s("div",null,[s("h4",JE,d(b.$t("generateModal.fileList")),1),s("div",xE,[(G(!0),U(bA,null,LA(D.value,Z=>(G(),U("div",{key:Z.id,class:"flex items-center justify-between px-3 py-2 border border-gray-200 rounded bg-gray-50"},[s("div",HE,[(G(),UA(Bt(Z.icon),{class:gA(["w-4 h-4 mr-2",Z.iconColor])},null,8,["class"])),s("span",YE,d(Z.name),1)]),s("div",KE,[HA(d(Z.size)+" ",1),Z.estimated?(G(),U("span",TE,d(b.$t("generateModal.estimated")),1)):O("",!0),Z.isCustomEmoji?(G(),U("span",VE,d(b.$t("generateModal.compressed")),1)):O("",!0)])]))),128))])])])):O("",!0),i.value?(G(),U("div",qE,[H[5]||(H[5]=s("div",{class:"flex items-center justify-center"},[s("div",{class:"animate-spin rounded-full h-16 w-16 border-b-2 border-primary-500"})],-1)),s("div",OE,[s("p",WE,d(b.$t("generateModal.generating")),1),s("div",PE,[s("div",{class:"bg-primary-500 h-2 rounded-full transition-all duration-500 ease-out",style:CA({width:C.value+"%"})},null,4)]),s("div",ZE,[s("div",null,d(B.value),1),s("div",XE,d(b.$t("generateModal.progress",{progress:C.value})),1)])]),s("div",jE,[(G(!0),U(bA,null,LA(c.value,Z=>(G(),U("div",{key:Z.id,class:"flex items-center text-sm"},[s("div",zE,[Z.status==="completed"?(G(),U("div",_E,[...H[4]||(H[4]=[s("svg",{class:"w-3 h-3 text-white",fill:"currentColor",viewBox:"0 0 20 20"},[s("path",{"fill-rule":"evenodd",d:"M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z","clip-rule":"evenodd"})],-1)])])):Z.status==="processing"?(G(),U("div",$E)):(G(),U("div",Al))]),s("span",{class:gA([Z.status==="completed"?"text-green-700":Z.status==="processing"?"text-primary-700":"text-gray-500"])},d(Z.name),3)]))),128))])])):O("",!0),r.value&&!w.value?(G(),U("div",el,[H[8]||(H[8]=s("div",{class:"mx-auto flex items-center justify-center"},[s("svg",{class:"w-20 h-20 text-green-600",fill:"currentColor",viewBox:"0 0 20 20"},[s("path",{"fill-rule":"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z","clip-rule":"evenodd"})])],-1)),s("div",null,[s("p",gl,d(b.$t("generateModal.completed")),1)]),s("div",tl,[s("div",Il,[s("div",null,d(b.$t("generateModal.filename")),1),s("div",null,d(b.$t("generateModal.fileSize",{size:n.value})),1),s("div",null,d(b.$t("generateModal.generationTime",{time:Q.value})),1)])]),s("div",ol,[s("button",{onClick:$,class:"w-full bg-gray-100 hover:bg-gray-200 text-gray-700 px-6 py-3 rounded-lg font-medium transition-colors flex items-center justify-center"},[H[6]||(H[6]=s("svg",{class:"w-5 h-5 mr-2",fill:"currentColor",viewBox:"0 0 20 20"},[s("path",{"fill-rule":"evenodd",d:"M3 17a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm3.293-7.707a1 1 0 011.414 0L9 10.586V3a1 1 0 112 0v7.586l1.293-1.293a1 1 0 111.414 1.414l-3 3a1 1 0 01-1.414 0l-3-3a1 1 0 010-1.414z","clip-rule":"evenodd"})],-1)),HA(" "+d(b.$t("generateModal.downloadAssets")),1)]),s("button",{onClick:_,disabled:!h.value,class:"w-full bg-blue-500 hover:bg-blue-600 disabled:bg-gray-300 text-white px-6 py-3 rounded-lg font-medium transition-colors flex items-center justify-center"},[H[7]||(H[7]=s("svg",{class:"w-5 h-5 mr-2",fill:"currentColor",viewBox:"0 0 20 20"},[s("path",{"fill-rule":"evenodd",d:"M3 17a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm3.293-7.707a1 1 0 011.414 0L9 10.586V3a1 1 0 112 0v7.586l1.293-1.293a1 1 0 111.414 1.414l-3 3a1 1 0 01-1.414 0l-3-3a1 1 0 010-1.414z","clip-rule":"evenodd"})],-1)),HA(" "+d(b.$t("generateModal.flashToDevice")),1)],8,il)])])):O("",!0),w.value&&!f.value?(G(),U("div",rl,[H[9]||(H[9]=s("div",{class:"flex items-center justify-center"},[s("div",{class:"animate-spin rounded-full h-16 w-16 border-b-2 border-blue-500"})],-1)),s("div",Cl,[s("p",nl,d(b.$t("generateModal.flashing")),1),s("div",Bl,[s("div",{class:"bg-blue-500 h-2 rounded-full transition-all duration-500 ease-out",style:CA({width:u.value+"%"})},null,4)]),s("div",sl,[s("div",null,d(l.value),1),s("div",al,d(b.$t("generateModal.progress",{progress:u.value})),1)])]),s("button",{onClick:iA,class:"px-4 py-2 text-sm font-medium text-red-600 bg-red-50 hover:bg-red-100 rounded-md transition-colors"},d(b.$t("generateModal.flashingCancel")),1)])):O("",!0),f.value?(G(),U("div",Ql,[s("p",El,d(f.value),1)])):O("",!0)]),s("div",ll,[!i.value&&!r.value?(G(),U("button",{key:0,onClick:H[1]||(H[1]=Z=>b.$emit("close")),class:"px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-md transition-colors"},d(b.$t("common.cancel")),1)):O("",!0),!i.value&&!r.value?(G(),U("button",{key:1,onClick:q,disabled:!X.value,class:"px-6 py-2 text-sm font-medium text-white bg-primary-500 hover:bg-primary-600 disabled:bg-gray-300 rounded-md transition-colors"},d(b.$t("common.start"))+" "+d(b.$t("common.generate")),9,cl)):O("",!0),r.value&&!w.value?(G(),U("button",{key:2,onClick:H[2]||(H[2]=Z=>b.$emit("close")),class:"px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-md transition-colors"},d(b.$t("common.close")),1)):O("",!0)])])]))}};class ul{constructor(A){this.token=A,this.ws=null,this.isConnected=!1,this.isCancelled=!1,this.chunkSize=64*1024,this.onProgress=null,this.onError=null,this.onComplete=null,this.onDownloadUrlReady=null,this.onTransferStarted=null,this.currentSession=null,this.totalBytesSent=0,this.isSendingChunk=!1}async connect(){return new Promise((A,g)=>{try{const t=`wss://api.tenclass.net/transfer/?token=${encodeURIComponent(this.token)}`;this.ws=new WebSocket(t),this.ws.onopen=()=>{this.isConnected=!0,console.log("WebSocket connected to transfer server"),A()},this.ws.onmessage=I=>{this.handleMessage(I)},this.ws.onerror=I=>{console.error("WebSocket error:",I),this.isConnected=!1,g(new Error("WebSocket connection failed"))},this.ws.onclose=I=>{console.log("WebSocket closed:",I.code,I.reason),this.isConnected=!1},setTimeout(()=>{this.isConnected||(this.ws.close(),g(new Error("WebSocket connection timeout")))},1e4)}catch(t){g(new Error(`Failed to create WebSocket connection: ${t.message}`))}})}handleMessage(A){try{if(typeof A.data=="string"){const g=JSON.parse(A.data);switch(g.type){case"file_created":this.currentSession&&(this.currentSession.url=g.url,this.onDownloadUrlReady&&this.onDownloadUrlReady(g.url));break;case"transfer_started":this.currentSession&&(this.currentSession.transferStarted=!0,this.onTransferStarted&&this.onTransferStarted(),this.currentSession.transferReady&&this.sendFileData());break;case"ack":if(this.currentSession){const{blob:t}=this.currentSession,I=t.size,o=g.bytesSent;if(o<0){console.error("Invalid server bytesSent (negative):",o),this.isSendingChunk=!1,this.onError&&this.onError(new Error("Server returned invalid byte count"));return}if(o>I){console.error(`Server bytesSent (${o}) exceeds fileSize (${I})`),this.isSendingChunk=!1,this.onError&&this.onError(new Error("Server byte count exceeds file size"));return}this.isSendingChunk=!1,o>this.currentSession.bytesSent&&(this.currentSession.bytesSent=o),this.sendFileData()}break;case"transfer_completed":if(this.currentSession){const t=this.currentSession.blob.size;this.totalBytesSent!==t&&console.warn(`Transfer size mismatch: sent ${this.totalBytesSent} bytes, expected ${t} bytes`)}this.onComplete&&this.onComplete();break;case"error":console.error("Transfer error:",g.message),this.onError&&this.onError(new Error(g.message));break}}}catch(g){console.error("Error handling message:",g),this.onError&&this.onError(g)}}async sendFileData(){if(this.isSendingChunk||!this.currentSession||this.isCancelled)return;const{blob:A}=this.currentSession,g=A.size;let t=this.currentSession.bytesSent;if(t>=g){this.onProgress&&this.onProgress(100,"Transfer completed, waiting for device confirmation...");return}if(this.isSendingChunk=!0,t>g){console.error(`Critical error: bytesSent (${t}) exceeds fileSize (${g})`),this.onError&&this.onError(new Error("Transfer byte count exceeds file size"));return}const I=Math.max(0,g-t),o=Math.min(this.chunkSize,I);if(o<=0)return;const i=A.slice(t,t+o);try{const r=await new Promise((Q,a)=>{const E=new FileReader;E.onload=()=>Q(E.result),E.onerror=()=>a(new Error("File read failed")),E.readAsArrayBuffer(i)});if(this.isCancelled)return;this.ws.send(r);const C=t+o;if(this.currentSession.bytesSent=C,this.totalBytesSent+=o,C>g){console.error(`Critical error: bytesSent (${C}) exceeds fileSize (${g})`),this.onError&&this.onError(new Error("Transfer byte count exceeds file size"));return}if(this.totalBytesSent>g){console.error(`Critical error: totalBytesSent (${this.totalBytesSent}) exceeds fileSize (${g})`),this.onError&&this.onError(new Error("Total sent bytes exceed file size"));return}const B=Math.round(C/g*60)+40,n=`Transferring... ${Math.round(C/1024)}KB / ${Math.round(g/1024)}KB`;this.onProgress&&this.onProgress(B,n)}catch(r){console.error("Error sending file chunk:",r),this.isSendingChunk=!1,this.onError&&this.onError(r)}}async initializeSession(A,g,t,I){return new Promise((o,i)=>{this.onProgress=g,this.onError=r=>{t&&t(r),i(r)},this.onDownloadUrlReady=r=>{I&&I(r),o(r)},this.isCancelled=!1;try{this.onProgress&&this.onProgress(5,"Connecting to transfer server..."),this.connect().then(()=>{this.onProgress&&this.onProgress(10,"Creating file session...");const r={type:"create_file",fileName:"assets.bin",fileSize:A.size};this.ws.send(JSON.stringify(r)),this.currentSession={blob:A,bytesSent:0,fileSize:A.size,transferStarted:!1,transferReady:!0},this.totalBytesSent=0}).catch(r=>{console.error("Transfer initialization failed:",r),this.onError&&this.onError(r)})}catch(r){console.error("Transfer initialization failed:",r),this.onError&&this.onError(r)}})}async startTransfer(A,g,t){return new Promise((I,o)=>{if(this.onProgress=A,this.onError=i=>{this.isSendingChunk=!1,g&&g(i),o(i)},this.onComplete=()=>{this.isSendingChunk=!1,t&&t(),I()},!this.currentSession||!this.currentSession.blob){const i=new Error("Transfer session not initialized");this.onError&&this.onError(i),o(i);return}this.currentSession.transferReady=!0,this.currentSession.transferStarted&&this.sendFileData()})}async transferFile(A,g,t,I,o){if(o){await this.initializeSession(A,g,t,o);return}this.onProgress=g,this.onError=t,this.onComplete=I,this.isCancelled=!1;try{this.onProgress&&this.onProgress(5,"Connecting to transfer server..."),await this.connect(),this.onProgress&&this.onProgress(10,"Creating file session...");const i={type:"create_file",fileName:"assets.bin",fileSize:A.size};this.ws.send(JSON.stringify(i)),this.currentSession={blob:A,bytesSent:0,fileSize:A.size,transferStarted:!1,transferReady:!0}}catch(i){console.error("Transfer initialization failed:",i),this.onError&&this.onError(i)}}cancel(){this.isCancelled=!0,this.isSendingChunk=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.close()}destroy(){this.cancel(),this.onProgress=null,this.onError=null,this.onComplete=null,this.onDownloadUrlReady=null,this.onTransferStarted=null,this.totalBytesSent=0,this.isSendingChunk=!1}}const dl={class:"flex items-center justify-between mb-2"},fl={class:"flex items-center"},wl={class:"text-blue-800 font-medium"},yl={class:"text-blue-600 text-sm mb-3"},pl={class:"flex justify-end space-x-2"},Dl={class:"flex items-center justify-center mb-8"},ml={class:"flex flex-col items-center"},Fl={class:"text-sm mt-2 text-gray-600"},kl={key:0,class:"w-16 h-0.5 bg-gray-300 mx-4"},vl={class:"bg-white rounded-lg shadow-sm border p-6"},Gl={__name:"HomePage",setup(e){const{callMcpTool:A}=ig(),{t:g}=TA(),t=j(0),I=j(!1),o=j("wakeword"),i=j(!1),r=j(!1),C=j(!1),B=j(!0),n=new sI,Q=j(null),a=j(null),E=[{titleKey:"steps.chip",key:"chip"},{titleKey:"steps.theme",key:"theme"},{titleKey:"steps.generate",key:"generate"}],h=j({chip:{model:"",display:{width:320,height:240,color:"RGB565"}},theme:{wakeword:{type:"none",preset:"",custom:{name:"",command:"",threshold:20,duration:3e3,model:"mn6_en"}},font:{type:"none",preset:"",hide_subtitle:!1,custom:{file:null,size:20,bpp:4,charset:"deepseek"}},emoji:{type:"none",preset:"",custom:{size:{width:160,height:120},images:{}}},skin:{light:{backgroundType:"color",backgroundColor:"#ffffff",textColor:"#000000",backgroundImage:null},dark:{backgroundType:"color",backgroundColor:"#121212",textColor:"#ffffff",backgroundImage:null}}}}),w=S=>S{t.value{t.value>0&&t.value--},f=()=>{I.value=!0},c=async S=>{},D=()=>new URLSearchParams(window.location.search).get("token"),y=async(S,J={})=>await A(S,J),v=async S=>{const{blob:J,onProgress:V,onComplete:q,onError:$}=S;try{const AA=D();if(!AA)throw new Error(g("flashProgress.authTokenMissing"));V(5,g("flashProgress.checkingDeviceStatus"));try{if(!await y("self.get_device_status"))throw new Error(g("flashProgress.deviceOfflineOrUnresponsive",{error:g("flashProgress.unableToGetDeviceStatus")}))}catch(z){console.error("Failed to check device status:",z),$(g("flashProgress.deviceOfflineOrUnresponsive",{error:z.message}));return}V(15,g("flashProgress.initializingTransferService")),a.value=new ul(AA);let _=null;const iA=new Promise((z,lA)=>{_=z});let b=null;const H=new Promise((z,lA)=>{b=z});a.value.onTransferStarted=()=>{b&&(b(),b=null)},await a.value.initializeSession(J,(z,lA)=>{V(15+z*.75,lA)},z=>{console.error("Failed to initialize the WebSocket session:",z),$(g("flashProgress.initializeTransferFailed",{error:z.message}))},z=>{_(z)});const Z=await iA;V(30,g("flashProgress.settingDeviceDownloadUrl"));try{await y("self.assets.set_download_url",{url:Z})}catch(z){console.error("Failed to set the device download URL:",z),$(g("flashProgress.setDownloadUrlFailed",{error:z.message}));return}V(40,g("flashProgress.rebootingDevice")),y("self.reboot").catch(z=>{console.warn("Reboot call warning (the device may have already restarted):",z)}),V(50,g("flashProgress.waitingForDeviceReboot"));const IA=new Promise((z,lA)=>{setTimeout(()=>lA(new Error(g("flashProgress.deviceRebootTimeout"))),6e4)});await Promise.race([H,IA]),V(60,g("flashProgress.startingFileTransfer")),await a.value.startTransfer((z,lA)=>{const wA=60+z*.4;V(Math.round(wA),lA)},z=>{$(g("flashProgress.onlineFlashFailed",{error:z.message}))},()=>{q()}),a.value.onTransferStarted=null}catch(AA){console.error("Online flashing failed:",AA),$(g("flashProgress.onlineFlashFailed",{error:AA.message}))}},N=()=>{a.value&&(a.value.cancel(),a.value.destroy(),a.value=null)},L=S=>{o.value=S},X=async()=>{var S,J,V;try{B.value=!0;const q=await cA.loadConfig();if(q){h.value=q.config,t.value=0,o.value="wakeword",i.value=!0,r.value=!0,await k(),Q.value&&clearTimeout(Q.value),Q.value=setTimeout(()=>{i.value=!1},5e3),n.setConfig(h.value,{strict:!1}),await n.restoreAllResourcesFromStorage(h.value);try{const $=((V=(J=(S=h.value)==null?void 0:S.theme)==null?void 0:J.emoji)==null?void 0:V.custom)||{},AA=$.images||{},_=$.fileMap||{},iA=$.emotionMap||{};h.value={...h.value,theme:{...h.value.theme,emoji:{...h.value.theme.emoji,custom:{...$,images:{...AA},fileMap:{..._},emotionMap:{...iA}}}}}}catch($){console.error("Failed to refresh emoji config references:",$)}}else i.value=!1,r.value=!1}catch(q){console.error("Failed to load the saved configuration:",q),i.value=!1,r.value=!1}finally{B.value=!1}},k=async()=>{var S,J,V;try{const q=(V=(J=(S=h.value)==null?void 0:S.theme)==null?void 0:J.emoji)==null?void 0:V.custom;if(!q)return;const $=Object.keys(q.images||{}).length>0,AA=q.fileMap&&Object.keys(q.fileMap).length>0,_=q.emotionMap&&Object.keys(q.emotionMap).length>0;if($&&(!AA||!_)){console.warn("Detected an incompatible legacy emoji data structure"),console.log("Cleaning legacy emoji data...");try{const b=Object.keys(q.images||{});for(const H of b)await cA.deleteFile(`emoji_${H}`);console.log(`Deleted ${b.length} legacy emoji files`)}catch(b){console.warn("Failed while deleting legacy emoji files:",b)}h.value.theme.emoji.custom={size:q.size||{width:64,height:64},images:{},fileMap:{},emotionMap:{}},h.value.theme.emoji.type==="custom"&&(h.value.theme.emoji.type="",console.log("Reset the emoji type so it can be selected again")),await m(),console.log("Legacy emoji data was fully cleared"),setTimeout(()=>{alert(`An incompatible legacy emoji data structure was removed. The new version deduplicates shared image files to save storage space. Please re-upload your custom emoji images.`)},500)}}catch(q){console.error("Failed to clean up legacy emoji data:",q)}},m=async()=>{try{await cA.saveConfig(h.value)}catch(S){console.error("Failed to save configuration:",S)}},M=async()=>{try{C.value=!0,await n.clearAllStoredData();const S={model:h.value.chip.model,display:{...h.value.chip.display}};h.value={chip:S,theme:{wakeword:{type:"none",preset:"",custom:{name:"",command:"",threshold:20,model:"mn6_en"}},font:{type:"none",preset:"",hide_subtitle:!1,custom:{file:null,size:20,bpp:4,charset:"deepseek"}},emoji:{type:"none",preset:"",custom:{size:{width:64,height:64},images:{}}},skin:{light:{backgroundType:"color",backgroundColor:"#ffffff",textColor:"#000000",backgroundImage:null},dark:{backgroundType:"color",backgroundColor:"#121212",textColor:"#ffffff",backgroundImage:null}}}},t.value=0,o.value="wakeword",i.value=!1,r.value=!1}catch(S){console.error("Failed to reset configuration:",S),alert(g("errors.resetFailed"))}finally{C.value=!1}};DA(h,async S=>{!B.value&&r.value&&await m()},{deep:!0}),Me(async()=>{await cA.initialize(),await X()}),st(()=>{Q.value&&clearTimeout(Q.value)});const oA=()=>{i.value=!1,Q.value&&clearTimeout(Q.value)},F=()=>{Q.value&&clearTimeout(Q.value),Q.value=setTimeout(()=>{i.value=!1},5e3)};return(S,J)=>(G(),U("div",null,[i.value?(G(),U("div",{key:0,class:"fixed bottom-4 right-4 z-50 bg-blue-50 border border-blue-200 rounded-lg p-4 shadow-lg transition-opacity duration-300 min-w-[300px]",onMouseenter:F},[s("div",dl,[s("div",fl,[J[3]||(J[3]=s("svg",{class:"w-5 h-5 text-blue-500 mr-2",fill:"currentColor",viewBox:"0 0 20 20"},[s("path",{"fill-rule":"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z","clip-rule":"evenodd"})],-1)),s("span",wl,d(S.$t("configNotice.title")),1)]),s("button",{onClick:oA,class:"text-gray-500 hover:text-gray-700"},[...J[4]||(J[4]=[s("svg",{class:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24"},[s("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M6 18L18 6M6 6l12 12"})],-1)])])]),s("p",yl,d(S.$t("configNotice.message")),1),s("div",pl,[s("button",{onClick:M,class:"px-3 py-1 text-sm text-red-600 hover:text-red-800 font-medium"},d(S.$t("configNotice.restart")),1)])],32)):O("",!0),s("div",Dl,[(G(),U(bA,null,LA(E,(V,q)=>s("div",{key:q,class:"flex items-center"},[s("div",ml,[s("div",{class:gA(w(q))},d(q+1),3),s("span",Fl,d(S.$t(V.titleKey)),1)]),qh.value.chip=V),onNext:u},null,8,["modelValue"])):O("",!0),t.value===1?(G(),UA(kC,{key:1,modelValue:h.value.theme,"onUpdate:modelValue":J[1]||(J[1]=V=>h.value.theme=V),chipModel:h.value.chip.model,activeTab:o.value,onNext:u,onPrev:l,onTabChange:L},null,8,["modelValue","chipModel","activeTab"])):O("",!0),t.value===2?(G(),UA(wn,{key:2,config:h.value,onGenerate:f,onPrev:l},null,8,["config"])):O("",!0)]),I.value?(G(),UA(hl,{key:1,config:h.value,onClose:J[2]||(J[2]=V=>I.value=!1),onGenerate:c,onStartFlash:v,onCancelFlash:N},null,8,["config"])):O("",!0)]))}};export{Gl as default};