]*>/i,m=>m+PRELUDE)}
defApp("tv",{name:"Terminal Velocity",icon:"game",cat:"Games",w:1040,h:700,single:true,startMax:true,desc:"the game",kw:"game terminal velocity republicka strategy rpg",
init(win,b){const f=h("iframe",{title:"Terminal Velocity",style:"flex:1;border:0;width:100%;height:100%;background:#0a0a0c",allow:"autoplay; clipboard-write"});f.srcdoc=gameHTML();b.append(f);win.frame=f;win.on.focus=()=>{try{f.contentWindow.focus()}catch(e){}};f.addEventListener("load",()=>{try{f.contentWindow.focus()}catch(e){}})}});
/* --- Terminal: its own small shell over the unified VFS --- */
function tokenize(line){const out=[];let cur="",q=null,has=false;for(let i=0;i"){if(cur||has){out.push(cur);cur="";has=false}if(c===">"&&line[i+1]===">"){out.push(">>");i++}else out.push(c)}else cur+=c}if(cur||has)out.push(cur);return out}
function globToRe(g){return new RegExp("^"+g.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".")+"$","i")}
function expandGlob(a,cwd){if(!/[*?]/.test(a))return[a];const i=a.lastIndexOf("/"),dir=i>=0?a.slice(0,i+1):"",pat=a.slice(i+1);const d=V.get(dir||".",cwd);if(!d||!d.dir)return[a];const re=globToRe(pat);const r=V.ls(d).filter(n=>re.test(n.name)&&(pat[0]==="."||n.name[0]!==".")).map(n=>dir+n.name);return r.length?r:[a]}
const SH={};
const need=(n,m)=>{if(!n)throw new Error(m)};
SH.help=()=>`Terminal Velocity OS shell. Commands:
saveos download this whole OS as one .html file
ls [-lahs] [path] cd [dir] pwd cat f... head/tail [-n N] f wc [-lwc] f
grep [-inrcl] pat [f...] find [path] [-name pat] [-type f|d] tree [path]
mkdir [-p] touch rm [-r] cp mv echo text [> file] stat du df
sort uniq tac (pipes | and redirects > >> work; globs * ? too)
open path open with the right app edit path open in Notepad
play path Media Player view path Image Viewer
export path download a file to your computer
apps list apps launch app start an app by id
theme [name] list/switch themes wallpaper [name] mount (local folder)
manifest archive status neofetch clear history date uname
tv start Terminal Velocity (the game) reboot
Tab completes. Up/Down is history. Ctrl+L clears.
`;
SH.pwd=(a,io)=>io.cwd;
SH.echo=a=>a.join(" ");
SH.clear=(a,io)=>{io.t.clear();return""};
SH.date=()=>{const d=new Date(),t=d.toTimeString();return MC.dual(d)+"\n"+t};
SH.whoami=()=>"user";
SH.uname=()=>"TerminalVelocityOS "+OS.ver+" (browser) "+navigator.platform;
SH.history=(a,io)=>io.t.hist.map((l,i)=>String(i+1).padStart(4)+" "+l).join("\n");
SH.cd=(a,io)=>{const n=V.get(a[0]||"~",io.cwd);need(n,"cd: no such directory: "+a[0]);need(n.dir,"cd: not a directory: "+a[0]);io.t.cwd=V.path(n);io.t.prompt();return""};
SH.ls=(a,io)=>{const fl=a.filter(x=>x[0]==="-"&&x.length>1).join("");const L=fl.includes("l"),A=fl.includes("a"),Hh=fl.includes("h"),S=fl.includes("s");const ps=a.filter(x=>x[0]!=="-");if(!ps.length)ps.push(".");const out=[];
for(const p of ps){const n=V.get(p,io.cwd);if(!n){out.push("ls: cannot access '"+p+"': No such file or directory");continue}
let list=n.dir?V.ls(n):[n];if(!A)list=list.filter(x=>x.name[0]!==".");if(ps.length>1&&n.dir)out.push(p+":");
const sz=x=>x.dir?"-":(Hh||S?fmtBytes(x.size):String(x.size));
if(L)for(const x of list)out.push((x.dir?"d":"-")+(V.writable(x)?"rw-":"r--")+" "+sz(x).padStart(7)+" "+fmtDate(x.mt)+" "+x.name+(x.dir?"/":""));
else if(S)for(const x of list)out.push(sz(x).padStart(7)+" "+x.name+(x.dir?"/":""));
else out.push(list.map(x=>x.name+(x.dir?"/":"")).join(io.piped?"\n":" ")||"(empty)")}
return out.join("\n")};
async function catNodes(a,io){const o=[];if(!a.length&&io.in!=null)return io.in;for(const p of a){const n=V.get(p,io.cwd);need(n,"cat: "+p+": No such file");need(!n.dir,"cat: "+p+": Is a directory");if(n.src==="arch"&&V.kind(n)!=="text"&&V.kind(n)!=="md"&&V.kind(n)!=="html"&&n.size>2e6)throw new Error("cat: "+p+": big binary-ish archive file ("+fmtBytes(n.size)+"). Use open/play/view.");o.push(await V.read(n,"text"))}return o.join("")}
SH.cat=catNodes;
const nOpt=(a,d)=>{let n=d;const r=[];for(let i=0;i{const[n,r]=nOpt(a,10);return(await catNodes(r,io)).split("\n").slice(0,n).join("\n")};
SH.tail=async(a,io)=>{const[n,r]=nOpt(a,10);const l=(await catNodes(r,io)).replace(/\n$/,"").split("\n");return l.slice(-n).join("\n")};
SH.tac=async(a,io)=>(await catNodes(a,io)).replace(/\n$/,"").split("\n").reverse().join("\n");
SH.wc=async(a,io)=>{const fl=a.filter(x=>x[0]==="-").join(""),r=a.filter(x=>x[0]!=="-");const t=await catNodes(r,io);const l=t.split("\n").length-(t.endsWith("\n")?1:0),w=(t.match(/\S+/g)||[]).length,c=new Blob([t]).size;if(fl.includes("l"))return String(l);if(fl.includes("w"))return String(w);if(fl.includes("c"))return String(c);return`${l} ${w} ${c}`};
SH.sort=async(a,io)=>{const l=(await catNodes(a.filter(x=>x[0]!=="-"),io)).replace(/\n$/,"").split("\n").sort((x,y)=>x.localeCompare(y,undefined,{numeric:true}));if(a.includes("-r"))l.reverse();return l.join("\n")};
SH.uniq=async(a,io)=>{const l=(await catNodes(a,io)).replace(/\n$/,"").split("\n");return l.filter((x,i)=>i===0||x!==l[i-1]).join("\n")};
SH.grep=async(a,io)=>{let fl="";const r=[];for(const x of a)(/^-[a-z]+$/.test(x)?fl+=x.slice(1):r.push(x));need(r.length,"usage: grep [-inrcl] pattern [files]");const pat=r.shift();let re;try{re=new RegExp(pat,fl.includes("i")?"i":"")}catch(e){re=new RegExp(pat.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),fl.includes("i")?"i":"")}
const out=[];const doText=(t,nm)=>{let c=0;t.split("\n").forEach((ln,i)=>{if(re.test(ln)){c++;if(!fl.includes("c")&&!fl.includes("l"))out.push((nm?nm+":":"")+(fl.includes("n")?(i+1)+":":"")+ln)}});if(fl.includes("c"))out.push((nm?nm+":":"")+c);else if(fl.includes("l")&&c)out.push(nm)};
if(!r.length){need(io.in!=null,"grep: no input");doText(io.in,"");return out.join("\n")}
const files=[];const collect=(n,p)=>{if(!n.dir)files.push([n,p]);else if(fl.includes("r")){let c=0;for(const k of V.ls(n)){if(files.length>400)break;collect(k,p+"/"+k.name)}}};
for(const p of r){const n=V.get(p,io.cwd);need(n,"grep: "+p+": No such file");collect(n,p)}
for(const[n,p]of files){const k=V.kind(n);if(k!=="text"&&k!=="md"&&k!=="html"&&k!=="other")continue;if(n.src==="arch"&&n.size>1e6)continue;try{doText(await V.read(n,"text"),files.length>1||fl.includes("r")?p:"")}catch(e){out.push("grep: "+p+": "+e.message)}}
return out.join("\n")};
SH.find=(a,io)=>{let start=".",name=null,type=null,ic_=false;for(let i=0;i{if(out.length>=500)return;if(type==="f"&&m.dir)return;if(type==="d"&&!m.dir)return;if(name&&!name.test(m.name))return;out.push(m===n?start:(start==="."?".":start.replace(/\/$/,""))+V.path(m).slice(base.length))});
return out.join("\n")+(out.length>=500?"\n... (first 500 shown)":"")};
SH.tree=(a,io)=>{const n=V.get(a[0]||".",io.cwd);need(n,"tree: no such path");const o=[n.name||"/"];let c=0;const rec=(d,pre,dep)=>{if(dep>6)return;const k=V.ls(d).filter(x=>x.name[0]!==".");k.forEach((x,i)=>{if(c++>400)return;const last=i===k.length-1;o.push(pre+(last?"└── ":"├── ")+x.name+(x.dir?"/":""));if(x.dir)rec(x,pre+(last?" ":"│ "),dep+1)})};rec(n,"",0);if(c>400)o.push("... (truncated)");return o.join("\n")};
SH.mkdir=(a,io)=>{for(const p of a.filter(x=>x[0]!=="-"))V.mkdirp(p,io.cwd);return""};
SH.touch=async(a,io)=>{for(const p of a){const n=V.get(p,io.cwd);if(!n)await V.write(p,"",io.cwd);else if(!n.dir){n.mt=Date.now();V.save(n)}}return""};
SH.rm=async(a,io)=>{const rec=a.some(x=>/^-.*[rR]/.test(x));for(const p of a.filter(x=>x[0]!=="-")){const n=V.get(p,io.cwd);need(n,"rm: "+p+": No such file");await V.rm(n,rec)}return""};
SH.rmdir=SH.rm;
SH.mv=async(a,io)=>{need(a.length>=2,"usage: mv src dest");const d=a[a.length-1];for(const p of a.slice(0,-1)){const n=V.get(p,io.cwd);need(n,"mv: "+p+": No such file");await V.mv(n,V.norm(d,io.cwd))}return""};
SH.cp=async(a,io)=>{a=a.filter(x=>x[0]!=="-");need(a.length>=2,"usage: cp src dest");const d=a[a.length-1];for(const p of a.slice(0,-1)){const n=V.get(p,io.cwd);need(n,"cp: "+p+": No such file");await V.cp(n,V.norm(d,io.cwd))}return""};
SH.stat=(a,io)=>{const n=V.get(a[0]||".",io.cwd);need(n,"stat: no such file");const c=n.dir?V.count(n):null;return` path: ${V.path(n)}\n type: ${n.dir?"directory":V.kind(n)}\n size: ${n.dir?c.files+" files, "+fmtBytes(c.size):n.size+" ("+fmtBytes(n.size)+")"}\n store: ${n.src}${V.writable(n)?" (writable)":" (read-only)"}${n.url?"\n url: "+n.url:""}\n time: ${fmtDate(n.mt)}`};
SH.du=(a,io)=>{const n=V.get(a[0]||".",io.cwd);need(n,"du: no such path");const c=V.count(n);return`${fmtBytes(c.size)}\t${V.path(n)} (${c.files.toLocaleString()} files, ${c.dirs.toLocaleString()} dirs)`};
SH.df=async()=>{let u="",q="";try{const e=await navigator.storage.estimate();u=fmtBytes(e.usage);q=fmtBytes(e.quota)}catch(e){u="?";q="?"}const h_=V.count(V.user),A=V.count(V.arch);return`/archive ${A.files.toLocaleString()} files ${fmtBytes(A.size)} (read-only, remote)\n/home/user ${h_.files} files ${fmtBytes(h_.size)}\nbrowser storage used ${u} of ${q}`};
SH.open=(a,io)=>{need(a[0],"usage: open path");const n=V.get(a[0],io.cwd);need(n,"open: not found: "+a[0]);OS.openNode(n);return""};
SH.edit=(a,io)=>{const p=V.norm(a[0]||"/home/user/untitled.txt",io.cwd);OS.open("notepad",p);return""};
SH.play=(a,io)=>{need(a[0],"usage: play path");const n=V.get(a[0],io.cwd);need(n,"play: not found");OS.open("media",V.path(n));return""};
SH.view=(a,io)=>{need(a[0],"usage: view path");const n=V.get(a[0],io.cwd);need(n,"view: not found");OS.open("images",V.path(n));return""};
SH.export=async(a,io)=>{need(a[0],"usage: export path");const n=V.get(a[0],io.cwd);need(n&&!n.dir,"export: not a file");download(n.name,await V.read(n,"blob"));return"downloading "+n.name};
SH.apps=()=>Object.values(OS.apps).filter(a=>!a.hidden).map(a=>a.id.padEnd(10)+a.name.padEnd(22)+(a.desc||"")).join("\n");
SH.launch=(a)=>{need(a[0]&&OS.apps[a[0]],"launch: unknown app (see: apps)");OS.open(a[0],a[1]);return""};
SH.tv=()=>{OS.open("tv");return"launching Terminal Velocity..."};
SH.theme=(a)=>{if(!a[0])return THEME_ORDER.map(k=>(k===SET.theme?"* ":" ")+k.padEnd(11)+THEMES[k].n).join("\n");need(THEMES[a[0]],"theme: unknown. run `theme` to list");applyTheme(a[0]);return"theme: "+THEMES[a[0]].n};
SH.wallpaper=(a)=>{if(!a[0])return"wallpapers: auto "+WALLS.join(" ")+" (now: "+wallId()+")";need(a[0]==="auto"||WALLS.includes(a[0]),"wallpaper: unknown");SET.wall=a[0];saveSet();setWall();return"wallpaper: "+a[0]};
SH.mount=async()=>{const n=await V.mount();return"mounted at "+V.path(n)+" ("+V.count(n).files+" files)"};
SH.manifest=()=>MAN.json?`archive: ${MAN.files.toLocaleString()} files, ${fmtBytes(MAN.size)}\nsource : ${MAN.src}\ngenerated: ${MAN.gen||"?"}\nattempts:\n`+MAN.tried.map(t=>" "+(t.ok?"ok ":"fail ")+t.u+(t.why?" ("+t.why+")":"")).join("\n"):"no manifest mounted. Settings > Archive lets you load a manifest.json from a file or URL.\nattempts:\n"+MAN.tried.map(t=>" fail "+t.u+" ("+t.why+")").join("\n");
/* hidden: the ship. Not listed in help on purpose. */
SH.theseus=()=>{const A=Object.values(OS.apps),built=A.filter(a=>!a.user&&!a.hidden).length,mine=A.filter(a=>a.user).length,den=((LS.get("tvos_themes",{})||{}).saved||[]).length;
return"THE SHIP\n\nEvery plank of this system can be replaced, and it is still the ship.\nIt is one file, so a copy is not part of the ship. A copy is the whole ship.\n\nPlanks aboard now\n built in "+built+"\n added by you "+mine+" (Programs)\n themes caught "+den+" (Themes)\n"+(OS.shipUp?" this session rebuilt from its own text\n":"")+"\nWhat carries over every rebuild is your own state. Back it up and the ship can be rebuilt anywhere.\n\nOther words to try: hobbes neurath"};
SH.hobbes=()=>"HOBBES\n\nGather up the old planks and rebuild the first ship. Now there are two. Which one is Theseus' ship?\nOn the water, you must choose. Here you do not: a copy is the whole ship and so is the original.\nTo see it for yourself, open the Quine app. It starts the ship inside the ship.";
SH.neurath=()=>"NEURATH\n\n\"We are like sailors who must rebuild their ship on the open sea, never able to dismantle it in dry-dock and reconstruct it from the best components.\"\n\nThis ship is rebuilt the same way. Install or remove a program and nothing stops; the window you were working in stays open.\nOpen Programs to add a plank.";
SH.saveos=()=>{saveOS();return"saving this OS as a single .html file..."};
SH.reboot=()=>{setTimeout(()=>OS.reload(),300);return"rebooting..."};
SH.neofetch=()=>{const A=MAN.files;return` ████████╗██╗ ██╗ user@terminal-velocity\n ╚══██╔══╝██║ ██║ ---------------------\n ██║ ██║ ██║ OS: Terminal Velocity OS ${OS.ver}\n ██║ ╚██╗ ██╔╝ Host: ${navigator.userAgent.split(") ")[0].split("(").pop()||"browser"}\n ██║ ╚████╔╝ Uptime: ${fmtUp((performance.now()-OS.boot)/1000)}\n ╚═╝ ╚═══╝ Theme: ${THEMES[SET.theme].n}\n Wallpaper: ${wallId()}\n Archive: ${A?A.toLocaleString()+" files":"not mounted"}\n Windows: ${OS.wins.length} Apps: ${Object.keys(OS.apps).length}\n Screen: ${innerWidth}x${innerHeight}\n License: CC0`};
SH.sleep=async a=>{await sleep((+a[0]||1)*1000);return""};
async function runLine(line,t){/* returns output string */
const toks=tokenize(line);if(!toks.length)return"";const stages=[[]];for(const x of toks){if(x==="|")stages.push([]);else stages[stages.length-1].push(x)}
let red=null,app=false;const last=stages[stages.length-1];const ri=last.findIndex(x=>x===">"||x===">>");if(ri>=0){app=last[ri]===">>";red=last[ri+1];last.splice(ri)}
let data=null;for(const st of stages){if(!st.length)throw new Error("syntax error near |");const cmd=st[0];let args=[];for(const x of st.slice(1))args.push(...expandGlob(x,t.cwd));const f=SH[cmd];if(!f)throw new Error(cmd+": command not found (try: help)");data=await f(args,{cwd:t.cwd,in:data,t,piped:st!==stages[stages.length-1]||!!red});if(data==null)data=""}
if(red){need(red,"syntax error: missing file after >");let o=data;if(app){const n=V.get(red,t.cwd);if(n&&!n.dir)o=(await V.read(n,"text"))+(data.endsWith("\n")?data:data+"\n")}else if(!o.endsWith("\n"))o+="\n";await V.write(red,o,t.cwd);return""}
return data}
defApp("terminal",{name:"Terminal",icon:"term",cat:"System",w:700,h:460,desc:"shell over the archive",kw:"shell console cmd bash ls cd",
init(win,b,arg){const t={cwd:"/home/user",hist:[],hi:0,clear(){out.innerHTML=""},prompt(){pr.textContent=t.cwd.replace(/^\/home\/user/,"~")+" $"}};if(typeof arg==="string"){const n=V.get(arg);if(n)t.cwd=n.dir?V.path(n):V.path(n.parent)}
const out=h("div",{style:"flex:1;overflow:auto;padding:8px 10px;white-space:pre-wrap;word-break:break-word;cursor:text"}),pr=h("span",{class:"ac",style:"white-space:nowrap"}),inp=h("input",{style:"flex:1;background:none;border:0;outline:0;min-width:0",autocomplete:"off",autocapitalize:"off",spellcheck:"false"}),row=h("div",{style:"display:flex;gap:8px;padding:6px 10px;border-top:1px solid var(--bd);background:var(--pn2)"},pr,inp);
b.append(out,row);b.addEventListener("pointerup",()=>{if(!getSelection().toString())inp.focus()});win.on.focus=()=>inp.focus();t.prompt();
const say=(s,c)=>{const d=h("div",{class:c||""},String(s).replace(/\n$/,""));out.append(d);out.scrollTop=out.scrollHeight};
say("Terminal Velocity OS shell. Type `help`. The archive is at /archive, your files at ~ (/home/user).","dim");win.t=t;
const run=async line=>{say(pr.textContent+" "+line,"ac");if(!line.trim())return;t.hist.push(line);t.hi=t.hist.length;try{const o=await runLine(line,t);if(o)say(o)}catch(e){say(e.message||String(e),"")|0;out.lastChild.style.color="var(--er)"}t.prompt();out.scrollTop=out.scrollHeight};
inp.addEventListener("keydown",e=>{if(e.key==="Enter"){const l=inp.value;inp.value="";run(l)}else if(e.key==="ArrowUp"){if(t.hi>0){t.hi--;inp.value=t.hist[t.hi];e.preventDefault()}}else if(e.key==="ArrowDown"){if(t.hik.startsWith(w))}else{const i=w.lastIndexOf("/"),dir=i>=0?w.slice(0,i+1):"",base=w.slice(i+1);const d=V.get(dir||".",t.cwd);if(d&&d.dir)c=V.ls(d).filter(n=>n.name.toLowerCase().startsWith(base.toLowerCase())).map(n=>dir+n.name+(n.dir?"/":""))}
if(c.length===1){const r=c[0].includes(" ")?'"'+c[0]+'"':c[0];inp.value=pre.slice(0,pre.length-w.length)+r+v.slice(pos)}else if(c.length>1){let p=c[0];for(const x of c)while(!x.toLowerCase().startsWith(p.toLowerCase()))p=p.slice(0,-1);if(p.length>w.length)inp.value=pre.slice(0,pre.length-w.length)+p+v.slice(pos);else say(c.slice(0,80).join(" "),"dim")}}});
setTimeout(()=>inp.focus(),30)}});
/* --- Files --- */
defApp("files",{name:"Files",icon:"folder",cat:"System",w:780,h:500,desc:"file manager",kw:"explorer finder folders archive browse",
init(win,b,arg){let cwd="/archive",hist=[],hi=-1,view=LS.get("tvos_fview","grid"),sel=new Set(),clip=null,filt="",lim=400;const S={};
const path=h("input",{class:"t grow",spellcheck:"false"}),flt=h("input",{class:"t",placeholder:"filter…",style:"width:130px"}),list=h("div",{class:"fl scr grow"}),status=h("div",{class:"row dim",style:"border-top:1px solid var(--bd);border-bottom:0;font-size:12px"}),side=h("div",{class:"side"});
const nav=(p,push=true)=>{const n=V.get(p);if(!n)return toast("No such folder: "+p,1);if(!n.dir){return OS.openNode(n)}cwd=V.path(n);if(push){hist=hist.slice(0,hi+1);hist.push(cwd);hi=hist.length-1}sel.clear();lim=400;flt.value="";filt="";render()};
const cur=()=>V.get(cwd);
const bt=(i,t,f)=>h("button",{class:"btn sm",title:t,onclick:f},ic(i));
const tools=h("div",{class:"row"},bt("back","Back",()=>{if(hi>0){hi--;nav(hist[hi],false)}}),bt("fwd","Forward",()=>{if(hi{const c=cur();c&&c.parent&&nav(V.path(c.parent))}),path,flt,bt("grid","Grid / list",()=>{view=view==="grid"?"list":"grid";LS.set("tvos_fview",view);render()}),bt("folderplus","New folder",()=>mk(true)),bt("refresh","Refresh",()=>render()));
b.append(tools,h("div",{style:"display:flex;flex:1;min-height:0"},side,h("div",{style:"flex:1;min-width:0;display:flex;flex-direction:column"},list,status)));
const places=()=>{side.innerHTML="";const P=[["Archive","/archive","globe"],["Home","/home/user","folder"],["Documents","/home/user/Documents","note"],["Music & Video","/home/user/Media","music"],["Temp","/tmp","file"],["System","/system","gear"]];for(const[n,p,i]of P)side.append(h("div",{class:cwd===p||cwd.startsWith(p+"/")&&p!=="/home/user"?"on":"",onclick:()=>{if(!V.get(p))V.mkdirp(p);nav(p)}},ic(i),n));for(const m of V.ls(V.mnt))side.append(h("div",{onclick:()=>nav("/mnt/"+m.name)},ic("usb"),m.name));side.append(h("div",{onclick:async()=>{try{const n=await V.mount();nav(V.path(n))}catch(e){toast(e.message,1)}}},ic("plus"),"Mount folder…"))};
const mk=async dir=>{const n=await dlgPrompt(dir?"New folder name:":"New file name:",dir?"New folder":"untitled.txt");if(!n)return;try{const p=cwd+"/"+n;dir?V.mkdirp(p):await V.write(p,"");render()}catch(e){toast(e.message,1)}};
const render=()=>{const c=cur();if(!c){cwd="/";return render()}path.value=cwd;let items=V.ls(c);if(filt)items=items.filter(n=>n.name.toLowerCase().includes(filt));const vis=items.filter(n=>n.name[0]!=="."||SET.dot);list.innerHTML="";list.className="fl scr grow"+(view==="list"?" lst":"");
if(!c.kids.size){list.append(h("div",{class:"pad dim",style:"grid-column:1/-1"},cwd==="/archive"?(MAN.json?"Empty manifest.":"No archive mounted. The manifest could not be loaded (see Settings > Archive to supply your own manifest.json)."):"This folder is empty. Right-click for options."))}
vis.slice(0,lim).forEach(n=>{const p=V.path(n);const it=h("div",{class:"it"+(n.dir?" d":"")+(sel.has(p)?" sel":""),title:n.name+(n.size?" · "+fmtBytes(n.size):""),onclick:e=>{if(isMob()&&!e.ctrlKey){OS.openNode(n);return}if(e.ctrlKey||e.metaKey){sel.has(p)?sel.delete(p):sel.add(p)}else{sel.clear();sel.add(p)}render()},ondblclick:()=>n.dir?nav(p):OS.openNode(n),oncontextmenu:e=>{e.preventDefault();e.stopPropagation();if(!sel.has(p)){sel.clear();sel.add(p);render()}itemMenu(e,n)}},ic(V.icon(n)),list.classList.contains("lst")?[h("span",{class:"n"},n.name),h("span",{class:"m"},n.dir?V.ls(n).length+" items":fmtBytes(n.size)),h("span",{class:"m",style:"width:120px"},n.src==="arch"?"":fmtDate(n.mt))]:h("div",{},n.name));list.append(it)});
if(vis.length>lim)list.append(h("button",{class:"btn",style:"grid-column:1/-1;margin:8px",onclick:()=>{lim+=1200;render()}},"Show "+Math.min(1200,vis.length-lim)+" more of "+(vis.length-lim).toLocaleString()+" remaining"));
status.textContent=vis.length.toLocaleString()+" items"+(sel.size?" · "+sel.size+" selected":"")+(V.writable(c)?"":" · read-only")+(MAN.json&&cwd.startsWith("/archive")?" · "+MAN.src:"");places()};
const selNodes=()=>[...sel].map(p=>V.get(p)).filter(Boolean);
const itemMenu=(e,n)=>{const ns=selNodes(),w=ns.every(x=>V.writable(x)&&x.src!=="arch");const m=[{t:"Open",ic:"eye",fn:()=>OS.openNode(n)}];if(!n.dir){const k=V.kind(n);m.push({t:"Open in Notepad",ic:"note",fn:()=>OS.openNode(n,"notepad")});if(k==="audio"||k==="video")m.push({t:"Play",ic:"play",fn:()=>OS.open("media",V.path(n))});if(k==="image")m.push({t:"View",ic:"image",fn:()=>OS.open("images",V.path(n))});if(k==="html")m.push({t:"Run as app",ic:"code",fn:()=>OS.open("runner",V.path(n))});m.push({t:"Install as program",ic:"pkg",fn:()=>OS.open("programs",V.path(n))});m.push({t:"Download",ic:"dl",fn:async()=>{try{download(n.name,await V.read(n,"blob"))}catch(e){toast("Download failed: "+e.message+(n.src==="arch"?" (the archive host may block cross-site reads; use Open instead)":""),1)}}});if(n.url)m.push({t:"Open in browser tab",ic:"globe",fn:()=>window.open(n.url,"_blank")})}else{m.push({t:"Play folder",ic:"play",fn:()=>OS.open("media",{queue:V.ls(n).filter(x=>["audio","video"].includes(V.kind(x))).map(V.path)})})}
m.push("-",{t:"Copy",ic:"copy",fn:()=>{clip={nodes:ns,cut:false};toast("Copied "+ns.length)}},{t:"Cut",fn:()=>{clip={nodes:ns,cut:true}},dis:!w},{t:"Rename",ic:"edit",dis:!w||ns.length!==1,fn:async()=>{const nn=await dlgPrompt("Rename:",n.name);if(nn&&nn!==n.name)try{await V.mv(n,V.path(n.parent)+"/"+nn);render()}catch(er){toast(er.message,1)}}},{t:"Delete",ic:"trash",dis:!w,fn:async()=>{if(await dlgConfirm("Delete "+ns.length+" item(s)? This cannot be undone.","Delete","Delete")){try{for(const x of ns)await V.rm(x,true);sel.clear();render()}catch(er){toast(er.message,1)}}}},"-",{t:"Properties",fn:()=>dlgAlert(SH.stat([V.path(n)],{cwd:"/"}),n.name)});ctxMenu(e.clientX,e.clientY,m)};
list.addEventListener("contextmenu",e=>{e.preventDefault();const w=V.writable(cur());ctxMenu(e.clientX,e.clientY,[{t:"New folder",ic:"folderplus",dis:!w,fn:()=>mk(true)},{t:"New text file",ic:"note",dis:!w,fn:()=>mk(false)},{t:"Paste",ic:"copy",dis:!w||!clip,fn:async()=>{try{for(const x of clip.nodes)clip.cut?await V.mv(x,cwd):await V.cp(x,cwd);if(clip.cut)clip=null;render()}catch(er){toast(er.message,1)}}},"-",{t:"Upload files from computer…",ic:"dl",dis:!w,fn:async()=>{const fs=await pickDisk("",true);for(const f of fs)await V.write(cwd+"/"+f.name,f,null,f.type);render()}},{t:SET.dot?"Hide dotfiles":"Show dotfiles",fn:()=>{SET.dot=!SET.dot;render()}},{t:"Open Terminal here",ic:"term",fn:()=>OS.open("terminal",cwd)},{t:"Refresh",ic:"refresh",fn:render}])});
list.addEventListener("click",e=>{if(e.target===list){sel.clear();render()}});
path.addEventListener("keydown",e=>{if(e.key==="Enter")nav(path.value)});flt.addEventListener("input",()=>{filt=flt.value.toLowerCase();lim=400;render()});
b.addEventListener("keydown",e=>{if(e.key==="Delete"&&sel.size){const ns=selNodes();if(ns.every(x=>V.writable(x)))dlgConfirm("Delete "+ns.length+" item(s)?","Delete","Delete").then(async y=>{if(y){for(const x of ns)await V.rm(x,true);sel.clear();render()}})}else if(e.key==="Enter"&&sel.size===1)OS.openNode(selNodes()[0]);else if(e.key==="Backspace"&&e.target===b){const c=cur();c&&c.parent&&nav(V.path(c.parent))}});b.tabIndex=0;
const fsl=OS.on("fs",()=>{if(!win.dead&&cur())render()});win.on.close=()=>OS.off("fs",fsl);
win.nav=nav;V.mkdirp("/home/user/Documents");V.mkdirp("/home/user/Media");nav(typeof arg==="string"?arg:(MAN.json?"/archive":"/home/user"))},
onArg(win,arg){if(typeof arg==="string")win.nav(arg)}});
/* ===================== APPS 2: notepad, media, images, calc, reader, runner, archive ===================== */
/* --- generic path picker --- */
function pickPath(o){o=o||{};return dlg((b,done)=>{let cwd=o.start||(o.mode==="save"?"/home/user/Documents":MAN.json?"/archive":"/home/user");if(!V.get(cwd))cwd="/home/user";const nm=h("input",{class:"t",placeholder:"file name",value:o.name||""}),pa=h("input",{class:"t grow"}),ls=h("div",{class:"fl lst scr",style:"height:260px;border:1px solid var(--bd);border-radius:5px"});
const go=p=>{const n=V.get(p);if(n&&n.dir){cwd=V.path(n);draw()}};
const draw=()=>{pa.value=cwd;ls.innerHTML="";const c=V.get(cwd);if(c.parent)ls.append(h("div",{class:"it",onclick:()=>go(V.path(c.parent))},ic("up"),h("span",{class:"n"},"..")));let k=V.ls(c);if(o.exts)k=k.filter(n=>n.dir||o.exts.includes(V.kind(n)));k.slice(0,500).forEach(n=>ls.append(h("div",{class:"it",onclick:()=>{if(n.dir)go(V.path(n));else nm.value=n.name},ondblclick:()=>{if(!n.dir&&o.mode!=="save")done(V.path(n))}},ic(V.icon(n)),h("span",{class:"n"},n.name),h("span",{class:"m"},n.dir?"":fmtBytes(n.size)))))};
const ok=()=>{if(o.mode==="dir")return done(cwd);if(!nm.value.trim())return;done((cwd==="/"?"":cwd)+"/"+nm.value.trim())};
pa.addEventListener("keydown",e=>{if(e.key==="Enter")go(pa.value)});nm.addEventListener("keydown",e=>{if(e.key==="Enter")ok()});
b.append(h("h3",{},o.title||(o.mode==="save"?"Save as":o.mode==="dir"?"Choose folder":"Open file")),h("div",{class:"row",style:"padding:0;border:0"},pa),ls,o.mode==="dir"?"":nm,h("div",{class:"acts"},h("button",{class:"btn",onclick:()=>done(null)},"Cancel"),h("button",{class:"btn pri",onclick:ok},o.mode==="save"?"Save":o.mode==="dir"?"Choose this folder":"Open")));draw()})}
/* --- Notepad with real export --- */
defApp("notepad",{name:"Notepad",icon:"note",cat:"Accessories",w:760,h:520,single:false,desc:"text editor with real export",kw:"text editor write txt save export zip markdown",
init(win,b,arg){let tabs=[],act=null,tid=0,wrap=true,prev=false;const ed=h("textarea",{class:"t",spellcheck:"false",style:"flex:1;border:0;border-radius:0;resize:none;padding:10px;line-height:1.5;tab-size:2;white-space:pre-wrap;outline:0"}),pv=h("div",{class:"scr",style:"flex:1;padding:12px;display:none;border-left:1px solid var(--bd)"}),tabsEl=h("div",{class:"tabs"}),st=h("div",{class:"row dim",style:"border-top:1px solid var(--bd);border-bottom:0;font-size:12px"}),
fnd=h("input",{class:"t",placeholder:"find",style:"width:120px"}),rep=h("input",{class:"t",placeholder:"replace",style:"width:120px"}),fbar=h("div",{class:"row",style:"display:none"},fnd,h("button",{class:"btn sm",onclick:()=>findNext(1)},"Next"),h("button",{class:"btn sm",onclick:()=>findNext(-1)},"Prev"),rep,h("button",{class:"btn sm",onclick:replOne},"Replace"),h("button",{class:"btn sm",onclick:replAll},"All"),h("span",{class:"dim",id:"fcnt"}));
const T=()=>tabs.find(t=>t.id===act);
const newTab=(o)=>{const t=Object.assign({id:++tid,name:"untitled.txt",path:null,text:"",orig:"",dirty:false},o);tabs.push(t);sw(t.id);return t};
const sw=id=>{const c=T();if(c)c.text=ed.value;act=id;const t=T();ed.value=t.text;draw();upd();OS.title(win,"Notepad - "+t.name+(t.dirty?" •":""));ed.focus()};
const draw=()=>{tabsEl.innerHTML="";tabs.forEach(t=>{const el=h("div",{class:"tab"+(t.id===act?" on":""),onclick:()=>t.id!==act&&sw(t.id)},t.name+(t.dirty?" •":""),h("i",{onclick:e=>{e.stopPropagation();closeTab(t)}},"×"));el._t=t;el.addEventListener("pointerdown",ev=>tabDrag(ev,el,tabs,draw));tabsEl.append(el)})};
const closeTab=async t=>{if(t.id===act)t.text=ed.value;if(t.dirty&&t.text!==t.orig&&!await dlgConfirm("Discard unsaved changes to "+t.name+"?","Close tab","Discard"))return;const i=tabs.indexOf(t);tabs.splice(i,1);if(!tabs.length)newTab();else if(t.id===act)sw(tabs[Math.max(0,i-1)].id);else draw();persist()};
const upd=()=>{const t=T();if(!t)return;const v=ed.value,p=ed.selectionStart,ln=v.slice(0,p).split("\n"),words=(v.match(/\S+/g)||[]).length;st.textContent=`Ln ${ln.length}, Col ${ln[ln.length-1].length+1} · ${words} words · ${v.length} chars · ${t.path||"not saved to a file"}`;if(prev)pv.innerHTML=/\.html?$/.test(t.name)?"":md(v)};
let pt=0;const persist=()=>{clearTimeout(pt);pt=setTimeout(()=>{const c=T();if(c)c.text=ed.value;DB.set("np_session",{tabs:tabs.filter(t=>t.dirty||!t.path).map(t=>({name:t.name,path:t.path,text:t.text,orig:t.orig,dirty:t.dirty})),t:Date.now()})},500)};
ed.addEventListener("input",()=>{const t=T();t.dirty=t.text!==ed.value||t.dirty;t.dirty=ed.value!==t.orig;t.text=ed.value;draw();upd();OS.title(win,"Notepad - "+t.name+(t.dirty?" •":""));persist()});
ed.addEventListener("keyup",upd);ed.addEventListener("click",upd);
ed.addEventListener("keydown",e=>{if(e.key==="Tab"&&!e.ctrlKey){e.preventDefault();document.execCommand&&document.execCommand("insertText",false," ")}else if(e.ctrlKey&&e.key==="s"){e.preventDefault();e.shiftKey?saveAs():save()}else if(e.ctrlKey&&e.key==="f"){e.preventDefault();fbar.style.display="flex";fnd.focus()}else if(e.ctrlKey&&e.key==="n"){e.preventDefault();newTab()}else if(e.ctrlKey&&e.key==="o"){e.preventDefault();openV()}});
const load=async p=>{const n=V.get(p);if(!n||n.dir)return toast("Cannot open "+p,1);const ex=tabs.find(t=>t.path===V.path(n));if(ex)return sw(ex.id);let tx;try{tx=await V.read(n,"text")}catch(e){return toast("Cannot read "+n.name+": "+e.message,1)}const c=T();if(c&&!c.path&&!c.dirty&&!ed.value)tabs.splice(tabs.indexOf(c),1);newTab({name:n.name,path:V.path(n),text:tx,orig:tx})};
const save=async()=>{const t=T();t.text=ed.value;if(!t.path||!V.writable(V.get(t.path))&&V.get(t.path))return saveAs();try{await V.write(t.path,t.text);t.orig=t.text;t.dirty=false;draw();OS.title(win,"Notepad - "+t.name);toast("Saved "+t.path);persist()}catch(e){toast("Save failed: "+e.message,1)}};
const saveAs=async()=>{const t=T();t.text=ed.value;const p=await pickPath({mode:"save",name:t.name});if(!p)return;try{await V.write(p,t.text);t.path=p;t.name=p.split("/").pop();t.orig=t.text;t.dirty=false;draw();OS.title(win,"Notepad - "+t.name);toast("Saved "+p);persist()}catch(e){toast("Save failed: "+e.message,1)}};
const openV=async()=>{const p=await pickPath({title:"Open file"});if(p)load(p)};
const openDisk=async()=>{for(const f of await pickDisk(".txt,.md,.json,.csv,.html,.js,.css,.log,text/*",true)){const tx=await f.text();newTab({name:f.name,text:tx,orig:"",dirty:true})}};
const dlCur=()=>{const t=T();t.text=ed.value;download(t.name,t.text,"text/plain;charset=utf-8");toast("Downloading "+t.name)};
const toDisk=async()=>{const t=T();t.text=ed.value;if(window.showSaveFilePicker){try{const h_=await showSaveFilePicker({suggestedName:t.name});const w=await h_.createWritable();await w.write(t.text);await w.close();toast("Saved to your computer: "+h_.name);return}catch(e){if(e.name==="AbortError")return}}dlCur()};
const zipHome=async()=>{const c=T();if(c)c.text=ed.value;const files=[],enc=new TextEncoder();const walk=async(n,pre)=>{for(const k of V.ls(n)){if(k.dir)await walk(k,pre+k.name+"/");else{const buf=new Uint8Array(await V.read(k,"buf"));files.push({name:pre+k.name,data:buf,mt:k.mt})}}};await walk(V.user,"");for(const t of tabs)if(!t.path)files.push({name:"unsaved/"+t.name,data:enc.encode(t.text),mt:Date.now()});if(!files.length)return toast("Nothing to export yet.",1);download("terminal-velocity-files-"+new Date().toISOString().slice(0,10)+".zip",makeZip(files));toast("Exported "+files.length+" files as ZIP")};
const zipTabs=()=>{const c=T();c.text=ed.value;const enc=new TextEncoder();download("notes.zip",makeZip(tabs.map((t,i)=>({name:t.name,data:enc.encode(t.text),mt:Date.now()}))));toast("Exported "+tabs.length+" tab(s) as ZIP")};
let fpos=0;const findNext=d=>{const q=fnd.value;if(!q)return;const v=ed.value.toLowerCase(),ql=q.toLowerCase();let i=d>0?v.indexOf(ql,ed.selectionEnd):v.lastIndexOf(ql,ed.selectionStart-1);if(i<0)i=d>0?v.indexOf(ql):v.lastIndexOf(ql);if(i<0){$("#fcnt",fbar).textContent="not found";return}ed.focus();ed.setSelectionRange(i,i+q.length);$("#fcnt",fbar).textContent=(v.split(ql).length-1)+" matches";const lh=parseFloat(getComputedStyle(ed).lineHeight)||20;ed.scrollTop=Math.max(0,(ed.value.slice(0,i).split("\n").length-4)*lh)};
function replOne(){const q=fnd.value;if(!q)return;if(ed.value.slice(ed.selectionStart,ed.selectionEnd).toLowerCase()===q.toLowerCase()){const s=ed.selectionStart;ed.setRangeText(rep.value,s,ed.selectionEnd,"end");ed.dispatchEvent(new Event("input"))}findNext(1)}
function replAll(){const q=fnd.value;if(!q)return;const re=new RegExp(q.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi");ed.value=ed.value.replace(re,rep.value);ed.dispatchEvent(new Event("input"))}
fnd.addEventListener("keydown",e=>{if(e.key==="Enter")findNext(e.shiftKey?-1:1);if(e.key==="Escape"){fbar.style.display="none";ed.focus()}});
const bt=(i,t,f,txt)=>h("button",{class:"btn sm",title:t,onclick:f},ic(i),txt||"");
const bar=h("div",{class:"row"},bt("plus","New (Ctrl+N)",()=>newTab(),"New"),bt("folder","Open from Terminal Velocity OS files",openV,"Open"),bt("dl","Open a file from your computer",openDisk,"From disk"),bt("save","Save (Ctrl+S)",save,"Save"),bt("save","Save as…",saveAs,"Save as"),h("button",{class:"btn sm",title:"Download this note to your computer",onclick:dlCur},ic("dl"),"Download"),h("button",{class:"btn sm",title:"Save to anywhere on your computer (file picker, Chromium) or download",onclick:toDisk},ic("usb"),"Save to computer"),h("button",{class:"btn sm",title:"Export every file in /home/user and unsaved tabs as one ZIP",onclick:zipHome},ic("zip"),"Export all (ZIP)"),h("button",{class:"btn sm",onclick:zipTabs,title:"ZIP of open tabs"},ic("zip"),"Tabs ZIP"),h("span",{class:"grow"}),bt("search","Find (Ctrl+F)",()=>{fbar.style.display=fbar.style.display==="none"?"flex":"none";fnd.focus()}),h("button",{class:"btn sm",onclick:e=>{wrap=!wrap;ed.style.whiteSpace=wrap?"pre-wrap":"pre";e.currentTarget.classList.toggle("on",wrap)}},"Wrap"),h("button",{class:"btn sm",onclick:e=>{prev=!prev;pv.style.display=prev?"block":"none";e.currentTarget.classList.toggle("on",prev);upd()}},"Preview"),bt("code","Run as HTML app",()=>{const t=T();OS.open("runner",{code:ed.value,name:t.name})},"Run"));
bar.lastChild.previousSibling.classList.add("on");
b.append(bar,tabsEl,fbar,h("div",{style:"flex:1;display:flex;min-height:0"},ed,pv),st);
win.onclose=async()=>{const c=T();if(c)c.text=ed.value;const d=tabs.filter(t=>t.dirty&&t.text!==t.orig);if(d.length&&!await dlgConfirm(d.length+" tab(s) have unsaved changes. Close anyway? (A draft is kept and restored next time.)","Notepad","Close")){return false}persist()};
win.openPath=load;(async()=>{const s=await DB.get("np_session");if(typeof arg==="string"){await load(arg)}else if(arg&&arg.code!=null){newTab({name:arg.name||"untitled.html",text:arg.code,orig:""})}else if(s&&s.tabs&&s.tabs.length&&!OS.wins.some(w=>w!==win&&w.app==="notepad")){s.tabs.forEach(t=>newTab(t));toast("Restored "+s.tabs.length+" unsaved note(s)")}if(!tabs.length)newTab();ed.focus()})()}});
/* --- Media Player --- */
defApp("media",{name:"Media Player",icon:"media",cat:"Media",w:820,h:520,desc:"audio & video, playlists, visualizer",kw:"music video mp3 mp4 player playlist play",
init(win,b,arg){let q=[],qi=-1,shuf=false,rep=0,auto=!!LS.get("tvos_media_auto",false),noViz=false,actx=null,an=null,srcNode=null,raf=0;const v=h("video",{style:"width:100%;height:100%;background:#000;object-fit:contain",playsinline:true,preload:"metadata"}),cv=h("canvas",{style:"position:absolute;inset:0;width:100%;height:100%;pointer-events:none"}),stage=h("div",{style:"position:relative;flex:1;min-height:0;background:#000"},v,cv),plist=h("div",{class:"scr md-pl",style:"width:300px;flex:none;border-left:1px solid var(--bd)"}),
seek=h("input",{type:"range",min:0,max:1000,value:0,style:"flex:1;accent-color:var(--ac)"}),tm=h("span",{class:"dim",style:"min-width:90px;text-align:center"},"0:00 / 0:00"),vol=h("input",{type:"range",min:0,max:1,step:.01,value:.8,style:"width:80px;accent-color:var(--ac)"}),title=h("span",{class:"grow",style:"overflow-wrap:anywhere;line-height:1.3"},"Nothing playing");
const dlist=()=>{plist.innerHTML="";q.forEach((it,i)=>plist.append(h("div",{class:"si"+(i===qi?" sel":""),title:it.name,style:"align-items:flex-start",onclick:()=>play(i),oncontextmenu:e=>{e.preventDefault();ctxMenu(e.clientX,e.clientY,[{t:"Remove",ic:"trash",fn:()=>{q.splice(i,1);if(i{const n=V.get(p);if(!n||n.dir)return null;const k=V.kind(n);if(k!=="audio"&&k!=="video")return null;return{name:n.name,path:V.path(n),video:k==="video",node:n}};
const add=(paths,go)=>{const items=paths.map(mkItem).filter(Boolean);if(!items.length)return toast("No playable media there.",1);const first=q.length;q.push(...items);dlist();if(go||qi<0)play(first)};
async function play(i){if(i<0||i>=q.length)return;qi=i;const it=q[i];dlist();title.textContent=it.name;OS.title(win,"Media - "+it.name);let url;try{url=it.url||await V.read(it.node,"url")}catch(e){return toast(e.message,1)}
const tryUrl=(u,cors)=>{v.removeAttribute("crossorigin");if(cors&&!/^blob:/.test(u))v.crossOrigin="anonymous";v.src=u;v.play().catch(()=>{})};
v.onerror=()=>{if(v.crossOrigin&&!/^blob:/.test(url)){noViz=true;tryUrl(url,false)}else toast("Cannot play "+it.name+" (format unsupported or the host blocked it).",1)};tryUrl(url,!noViz&&!it.video)}
const next=d=>{if(!q.length)return;let i=shuf?Math.floor(Math.random()*q.length):qi+d;if(i>=q.length)i=rep?0:-1;if(i<0&&!shuf)i=rep?q.length-1:0;if(i>=0&&(i!==qi||rep===2||q.length===1))play(i)};
v.addEventListener("ended",()=>{if(rep===2)play(qi);else if(auto&&(qi{if(!seek.dragging)seek.value=v.duration?v.currentTime/v.duration*1000:0;tm.textContent=fmtTime(v.currentTime)+" / "+fmtTime(v.duration)});
seek.addEventListener("input",()=>{seek.dragging=1;v.currentTime=seek.value/1000*(v.duration||0)});seek.addEventListener("change",()=>seek.dragging=0);
vol.addEventListener("input",()=>v.volume=vol.value);v.volume=.8;
v.addEventListener("play",()=>{startViz();pp.replaceChildren(ic("pause"))});v.addEventListener("pause",()=>pp.replaceChildren(ic("play")));
const startViz=()=>{if(!noViz&&!actx&&v.crossOrigin||(!noViz&&!actx&&q[qi]&&/^blob:|^data:/.test(v.src))){try{actx=new (window.AudioContext||window.webkitAudioContext)();an=actx.createAnalyser();an.fftSize=128;srcNode=actx.createMediaElementSource(v);srcNode.connect(an);an.connect(actx.destination)}catch(e){actx=null;noViz=true}}if(actx&&actx.state==="suspended")actx.resume();cancelAnimationFrame(raf);loop()};
const loop=()=>{raf=requestAnimationFrame(loop);if(win.dead||win.min||OS.lpSkip())return;const c=cv.getContext("2d"),W=cv.width=cv.clientWidth,H=cv.height=cv.clientHeight;c.clearRect(0,0,W,H);const it=q[qi];if(it&&it.video&&!v.paused&&v.videoWidth)return;const n=48,bw=W/n,ac=css("ac"),a2=css("ac2");let d=null;if(an&&!noViz){d=new Uint8Array(an.frequencyBinCount);an.getByteFrequencyData(d)}const t=performance.now()/1000;
if(!it){c.fillStyle=ac;c.globalAlpha=.5;c.font="14px monospace";c.textAlign="center";c.fillText("TERMINAL VELOCITY MEDIA",W/2,H/2);return}
for(let i=0;ix))m=(d[Math.floor(i*d.length/n)]||0)/255;else m=v.paused?.03:(.25+.25*Math.sin(t*3+i*.5)+.2*Math.sin(t*5.3+i*1.3))*(.5+.5*Math.sin(t*50/60*6.283));m=Math.max(.02,Math.min(1,m));c.fillStyle=i%2?a2:ac;c.globalAlpha=.8;c.fillRect(i*bw+1,H-m*H*.8-10,bw-2,m*H*.8)}c.globalAlpha=1};
const pp=h("button",{class:"btn",onclick:()=>v.paused?v.play():v.pause()},ic("play")),bt=(i,t,f)=>h("button",{class:"btn",title:t,onclick:f},ic(i));
const spd=h("select",{class:"t",onchange:()=>v.playbackRate=+spd.value},...[.5,.75,1,1.25,1.5,2].map(x=>h("option",{value:x,selected:x===1},x+"x")));
const ctr=h("div",{class:"row"},bt("prev","Previous",()=>next(-1)),pp,bt("next","Next",()=>next(1)),seek,tm,ic("music"),vol,spd);
const ab=h("button",{class:"btn sm"+(auto?" on":""),title:"When a file ends, play the next one in the playlist. Off: each file plays once and stops.",onclick:e=>{auto=!auto;LS.set("tvos_media_auto",auto);e.currentTarget.classList.toggle("on",auto);e.currentTarget.textContent="Auto-next: "+(auto?"on":"off")}},"Auto-next: "+(auto?"on":"off")),sb=h("button",{class:"btn sm",onclick:e=>{shuf=!shuf;e.currentTarget.classList.toggle("on",shuf)}},"Shuffle"),rb=h("button",{class:"btn sm",onclick:e=>{rep=(rep+1)%3;e.currentTarget.textContent=["Repeat off","Repeat all","Repeat one"][rep];e.currentTarget.classList.toggle("on",rep>0)}},"Repeat off");
const top=h("div",{class:"row"},h("button",{class:"btn sm",onclick:async()=>{const p=await pickPath({title:"Add media"});if(p)add([p],true)}},ic("plus"),"Add from files"),h("button",{class:"btn sm",onclick:async()=>{const fs=await pickDisk("audio/*,video/*",true);if(!fs.length)return;const first=q.length;for(const f of fs){q.push({name:f.name,url:URL.createObjectURL(f),video:f.type.startsWith("video")})}dlist();play(first)}},ic("dl"),"From computer"),h("button",{class:"btn sm",onclick:async()=>{const p=await pickPath({mode:"dir",title:"Add every media file in a folder"});if(p){const d=V.get(p);add(V.ls(d).map(V.path),true)}}},ic("folder"),"Add folder"),ab,sb,rb,h("button",{class:"btn sm",onclick:()=>{q=[];qi=-1;v.removeAttribute("src");v.load();dlist()}},"Clear"),h("span",{class:"grow"}),h("button",{class:"btn sm",onclick:()=>{if(document.fullscreenElement)document.exitFullscreen();else{stage.dataset.fsx="both";stage.requestFullscreen&&stage.requestFullscreen()}}},"Fullscreen"));
b.append(top,h("div",{class:"md-row",style:"flex:1;display:flex;min-height:0"},stage,plist),h("div",{class:"row",style:"border-bottom:0;border-top:1px solid var(--bd)"},title),ctr);
win.onArg=a=>{if(typeof a==="string")add([a],true);else if(a&&a.queue)add(a.queue,true)};win.on.close=()=>{cancelAnimationFrame(raf);v.pause();v.removeAttribute("src");actx&&actx.close&&actx.close()};
b.tabIndex=0;b._space=()=>{v.paused?v.play().catch(()=>{}):v.pause()};b.addEventListener("keydown",e=>{if(e.target.tagName==="INPUT"&&e.target.type!=="range")return;if(e.key===" "){e.preventDefault();v.paused?v.play():v.pause()}else if(e.key==="ArrowRight")v.currentTime+=5;else if(e.key==="ArrowLeft")v.currentTime-=5});
dlist();loop();if(typeof arg==="string")add([arg],true);else if(arg&&arg.queue)add(arg.queue,true)},
onArg(win,a){win.onArg(a)}});
/* --- Image viewer --- */
defApp("images",{name:"Image Viewer",icon:"image",cat:"Media",w:760,h:520,desc:"view images, zoom, slideshow",kw:"picture photo png jpg svg",
init(win,b,arg){let list=[],i=0,z=1,tx=0,ty=0,rot=0,fit=true,slide=0;const img=h("img",{style:"position:absolute;left:50%;top:50%;transform-origin:center;max-width:none;user-select:none;-webkit-user-drag:none",draggable:false}),st=h("div",{style:"flex:1;position:relative;overflow:hidden;background:repeating-conic-gradient(var(--pn2) 0% 25%,var(--bg) 0% 50%) 0 0/20px 20px;touch-action:none"},img),info=h("span",{class:"dim grow"},"No image");
const apply=()=>{img.style.transform=`translate(calc(-50% + ${tx}px),calc(-50% + ${ty}px)) rotate(${rot}deg) scale(${z})`};
const fitNow=()=>{if(!img.naturalWidth)return;const W=st.clientWidth,H=st.clientHeight,r=(rot/90)%2?[img.naturalHeight,img.naturalWidth]:[img.naturalWidth,img.naturalHeight];z=Math.min(1,W/r[0]*.96,H/r[1]*.96);tx=ty=0;apply()};
const show=async(k)=>{if(k<0||k>=list.length)return;i=k;const n=list[k];let u;try{u=await V.read(n,"url")}catch(e){return toast(e.message,1)}img.onload=()=>{rot=0;fitNow();info.textContent=`${n.name} · ${img.naturalWidth}×${img.naturalHeight} · ${fmtBytes(n.size)} · ${k+1}/${list.length}`};img.onerror=()=>{info.textContent="Cannot display "+n.name};img.src=u;OS.title(win,"Image - "+n.name)};
const open=p=>{const n=V.get(p);if(!n||n.dir)return;list=V.ls(n.parent).filter(x=>V.kind(x)==="image");i=list.indexOf(n);if(i<0){list=[n];i=0}show(i)};
st.addEventListener("wheel",e=>{e.preventDefault();const f=e.deltaY<0?1.15:1/1.15;z=Math.max(.05,Math.min(40,z*f));apply()},{passive:false});
st.addEventListener("pointerdown",e=>{const sx=e.clientX-tx,sy=e.clientY-ty;st.setPointerCapture(e.pointerId);const mv=ev=>{tx=ev.clientX-sx;ty=ev.clientY-sy;apply()},up=()=>{st.removeEventListener("pointermove",mv);st.removeEventListener("pointerup",up)};st.addEventListener("pointermove",mv);st.addEventListener("pointerup",up)});
st.addEventListener("dblclick",fitNow);win.on.resize=fitNow;
const bt=(t,f,txt)=>h("button",{class:"btn sm",onclick:f},txt);
b.append(h("div",{class:"row"},bt("",()=>show(i-1),"◀ Prev"),bt("",()=>show(i+1),"Next ▶"),bt("",()=>{z*=1.25;apply()},"+"),bt("",()=>{z/=1.25;apply()},"−"),bt("",fitNow,"Fit"),bt("",()=>{z=1;tx=ty=0;apply()},"1:1"),bt("",()=>{rot=(rot+90)%360;fitNow()},"Rotate"),bt("",async()=>{const p=await pickPath({title:"Open image",exts:["image"]});if(p)open(p)},"Open…"),bt("",()=>{const n=list[i];n&&V.read(n,"blob").then(bl=>download(n.name,bl)).catch(e=>toast(e.message,1))},"Download"),h("button",{class:"btn sm",onclick:e=>{if(slide){clearInterval(slide);slide=0;e.currentTarget.classList.remove("on")}else{slide=setInterval(()=>show((i+1)%list.length),3500);e.currentTarget.classList.add("on")}}},"Slideshow")),st,h("div",{class:"row",style:"border-bottom:0;border-top:1px solid var(--bd)"},info));
win.on.close=()=>clearInterval(slide);b.tabIndex=0;b.addEventListener("keydown",e=>{if(e.key==="ArrowRight")show(i+1);else if(e.key==="ArrowLeft")show(i-1)});win.open=open;if(typeof arg==="string")open(arg);else info.textContent="Open an image from Files, or press Open…"},
single:false,onArg(w,a){}});
/* --- Calculator --- */
function calcEval(src,deg,ans){const s=String(src).replace(/×/g,"*").replace(/÷/g,"/").replace(/−/g,"-").replace(/π/g,"pi").replace(/\s+/g,"").toLowerCase();let i=0;
const F={sin:x=>Math.sin(deg?x*Math.PI/180:x),cos:x=>Math.cos(deg?x*Math.PI/180:x),tan:x=>Math.tan(deg?x*Math.PI/180:x),asin:x=>{const r=Math.asin(x);return deg?r*180/Math.PI:r},acos:x=>{const r=Math.acos(x);return deg?r*180/Math.PI:r},atan:x=>{const r=Math.atan(x);return deg?r*180/Math.PI:r},sqrt:Math.sqrt,cbrt:Math.cbrt,ln:Math.log,log:Math.log10,log2:Math.log2,exp:Math.exp,abs:Math.abs,floor:Math.floor,ceil:Math.ceil,round:Math.round,fact:x=>{if(x<0||x>170||x%1)return NaN;let r=1;for(let k=2;k<=x;k++)r*=k;return r}};
const C={pi:Math.PI,e:Math.E,ans:ans||0,tau:Math.PI*2};
function ex(){let v=tm();while(s[i]==="+"||s[i]==="-"){const o=s[i++],r=tm();v=o==="+"?v+r:v-r}return v}
function tm(){let v=pw();while(s[i]==="*"||s[i]==="/"||s[i]==="%"){const o=s[i++],r=pw();v=o==="*"?v*r:o==="/"?v/r:v%r}return v}
function pw(){let b=un();if(s[i]==="^"){i++;return Math.pow(b,pw())}return b}
function un(){if(s[i]==="-"){i++;return-un()}if(s[i]==="+"){i++;return un()}return pf()}
function pf(){let v=at();while(s[i]==="!"){i++;v=F.fact(v)}return v}
function at(){if(s[i]==="("){i++;const v=ex();if(s[i]!==")")throw new Error("missing )");i++;return v}const m=/^(\d+\.?\d*|\.\d+)(e[+-]?\d+)?/.exec(s.slice(i));if(m){i+=m[0].length;return parseFloat(m[0])}const w=/^[a-z0-9]+/.exec(s.slice(i));if(w){const k=w[0];i+=k.length;if(s[i]==="("&&F[k]){i++;const a=ex();if(s[i]!==")")throw new Error("missing )");i++;return F[k](a)}if(k in C)return C[k];throw new Error("unknown: "+k)}throw new Error("syntax error")}
if(!s)return 0;const v=ex();if(i{try{const v=calcEval(inp.value,deg,ans);res.textContent=isFinite(v)?"= "+(+v.toPrecision(12)):"= undefined";return v}catch(e){res.textContent=inp.value?e.message:"";return undefined}};
const eq=()=>{const v=calc();if(v!==undefined&&isFinite(v)){hist.push(inp.value+" = "+ +v.toPrecision(12));hl.innerHTML="";hist.slice(-6).forEach(x=>hl.append(h("div",{},x)));ans=v;inp.value=String(+v.toPrecision(12));res.textContent=""}};
inp.addEventListener("input",calc);inp.addEventListener("keydown",e=>{if(e.key==="Enter"){e.preventDefault();eq()}else if(e.key==="Escape")inp.value=""});
const keys=[["sin(","cos(","tan(","sqrt(","C"],["ln(","log(","^","(",")"],["7","8","9","÷","⌫"],["4","5","6","×","π"],["1","2","3","−","ans"],["0",".","!","+","="]];
const g=h("div",{style:"display:grid;grid-template-columns:repeat(5,1fr);gap:4px;padding:8px;flex:1"});
for(const r of keys)for(const k of r)g.append(h("button",{class:"btn"+(k==="="?" pri":""),style:"justify-content:center;font-size:15px",onpointerdown:e=>e.preventDefault(),onclick:()=>{if(k==="C"){inp.value="";res.textContent=""}else if(k==="⌫")inp.value=inp.value.slice(0,-1);else if(k==="=")eq();else inp.value+=k;if(!coarse)inp.focus();calc()}},k));
b.append(h("div",{class:"row"},h("button",{class:"btn sm",onclick:e=>{deg=!deg;e.currentTarget.textContent=deg?"DEG":"RAD";calc()}},"RAD"),h("span",{class:"dim"},coarse?"tap the display to type":"type or tap · Enter =")),hl,h("div",{style:"padding:6px 8px 0"},inp),res,g);if(!coarse)setTimeout(()=>inp.focus(),30)}});
/* --- Reader (markdown / long text) --- */
defApp("reader",{name:"Reader",icon:"file",cat:"Media",w:700,h:560,desc:"read markdown & text comfortably",kw:"book read markdown txt article essay",
init(win,b,arg){let fs=LS.get("tvos_rfs",16),path=null;const body=h("div",{class:"scr",style:"flex:1;padding:18px 8%;font-family:Georgia,'Iowan Old Style',serif;line-height:1.7"}),sty=h("style");sty.textContent=`.rd h1,.rd h2,.rd h3{color:var(--ac);line-height:1.25}.rd code,.rd pre{background:var(--bg);padding:1px 5px;border-radius:4px}.rd pre{padding:10px;overflow:auto;white-space:pre-wrap}.rd blockquote{border-left:3px solid var(--ac);margin:8px 0;padding:2px 12px;color:var(--dim)}.rd p{margin:.7em 0}`;body.classList.add("rd");
const setFs=d=>{fs=Math.max(11,Math.min(30,fs+d));body.style.fontSize=fs+"px";LS.set("tvos_rfs",fs)};setFs(0);
const open=async p=>{const n=V.get(p);if(!n||n.dir)return;let t;try{t=await V.read(n,"text")}catch(e){body.textContent="Cannot read: "+e.message;return}path=V.path(n);OS.title(win,"Reader - "+n.name);body.innerHTML=/\.md|markdown$/i.test(n.name)?md(t):"
"+esc(t)+"
";body.scrollTop=LS.get("tvos_rpos_"+path,0)};
body.addEventListener("scroll",()=>{if(path)LS.set("tvos_rpos_"+path,body.scrollTop)});
b.append(sty,h("div",{class:"row"},h("button",{class:"btn sm",onclick:async()=>{const p=await pickPath({title:"Open text or markdown"});if(p)open(p)}},ic("folder"),"Open…"),h("button",{class:"btn sm",onclick:()=>setFs(-1)},"A−"),h("button",{class:"btn sm",onclick:()=>setFs(1)},"A+"),h("button",{class:"btn sm",onclick:()=>path&&OS.open("notepad",path)},"Edit in Notepad")),body);
win.openPath=open;body.append(h("div",{class:"dim"},"Open a .md or .txt file from the archive or your files."));if(typeof arg==="string")open(arg)},onArg(w,a){typeof a==="string"&&w.openPath(a)},single:false});
/* --- HTML App Runner (sandboxed) --- */
defApp("runner",{name:"App Runner",icon:"code",cat:"Tools",w:760,h:520,desc:"run HTML apps in a sandbox",kw:"html run sandbox code web app preview",
init(win,b,arg){const ta=h("textarea",{class:"t",spellcheck:"false",style:"width:100%;height:100%;border:0;border-radius:0;resize:none;padding:10px",placeholder:"Paste HTML here and press Run. It runs in a sandbox: scripts allowed, no access to your files, saves or this OS."}),fr=h("iframe",{sandbox:"allow-scripts allow-forms allow-modals allow-popups allow-pointer-lock",style:"flex:1;border:0;background:#fff;width:100%"}),pane=h("div",{style:"flex:1;min-height:0;display:flex;flex-direction:column"},fr);let srcMode=false;
const run=()=>{fr.srcdoc=ta.value};const setSrc=on=>{srcMode=on;pane.replaceChildren(on?ta:fr)};
b.append(h("div",{class:"row"},h("button",{class:"btn sm pri",onclick:()=>{setSrc(false);run()}},ic("play"),"Run"),h("button",{class:"btn sm",onclick:()=>setSrc(!srcMode)},"Source"),h("button",{class:"btn sm",title:"Install this app so it gets its own icon, Start entry and window",onclick:()=>{if(!ta.value.trim())return toast("Nothing to install yet",1);OS.open("programs",{code:ta.value})}},ic("pkg"),"Install"),h("button",{class:"btn sm",onclick:async()=>{const p=await pickPath({title:"Open HTML"});if(p)load(p)}},ic("folder"),"Open…"),h("button",{class:"btn sm",onclick:()=>OS.open("notepad",{code:ta.value,name:"app.html"})},"Edit in Notepad"),h("button",{class:"btn sm",onclick:()=>{const u=URL.createObjectURL(new Blob([ta.value],{type:"text/html"}));window.open(u,"_blank")}},"Open in tab"),h("span",{class:"dim"},"sandboxed")),pane);
const load=async p=>{const n=V.get(p);if(!n||n.dir)return;try{ta.value=await V.read(n,"text")}catch(e){return toast(e.message,1)}OS.title(win,"App Runner - "+n.name);setSrc(false);run()};
win.load=load;if(typeof arg==="string")load(arg);else if(arg&&arg.code!=null){ta.value=arg.code;run()}else{ta.value="helloHello from the sandbox.{try{f.contentWindow.focus();const i=f.contentDocument&&f.contentDocument.getElementById("heartInput");if(i)i.focus()}catch(e){}};win.on.focus=foc;f.addEventListener("load",foc)}});
/* ===================== QUINE: the OS runs a copy of itself, which can run a copy of itself ===================== */
IP.quine="M12 12c-2-3-4-4.5-6-4.5a4.5 4.5 0 000 9c2 0 4-1.5 6-4.5s4-4.5 6-4.5a4.5 4.5 0 010 9c-2 0-4-1.5-6-4.5z";
const QN={
depth:NEST?+NEST[1]:0,src:null,
max(){return(/Mobi|Android|iPhone|iPad/.test(navigator.userAgent)||Math.min(screen.width,screen.height)<=700)?2:((navigator.deviceMemory||8)<=4?3:5)},
sleep:ms=>new Promise(r=>setTimeout(r,ms)),
async getSrc(){
if(QN.src)return QN.src;
if(NEST){try{const p=parent.eval("QN.src");if(p)return QN.src=p}catch(e){}}
let src;const u=location.href.split("#")[0].split("?")[0];
try{const r=await fetch(u,{cache:"no-cache"});if(!r.ok)throw new Error("HTTP "+r.status);src=await r.text()}
catch(e){try{src=await new Promise((ok,no)=>{const x=new XMLHttpRequest();x.open("GET",u);x.onload=()=>ok(x.responseText);x.onerror=()=>no(new Error("blocked"));x.send()})}catch(e2){throw new Error("The browser will not let this page read itself here. Open the OS from a web address (https://) instead of from a file.")}}
if(!src||src.length<50000||src.indexOf('id="tvgame"')<0)throw new Error("Could not get a complete copy of the page.");
return QN.src=src},
/* put a copy of this OS in an iframe inside host. Resolves {frame, ms} when the copy's desktop is ready */
async mount(host,depth,css,hall){
const src=await QN.getSrc(),url=URL.createObjectURL(new Blob([src],{type:"text/html"})),d=host.ownerDocument,f=d.createElement("iframe");
f.name="tvq:"+depth;f.style.cssText=css||"position:absolute;inset:0;width:100%;height:100%;border:0;background:#000";f._url=url;
const t0=performance.now();
const ready=new Promise((ok,no)=>{const iv=setInterval(()=>{let up=false;try{up=f.contentWindow.eval("typeof OS!=='undefined'&&OS.sessReady===true")}catch(e){}
if(up){clearInterval(iv);ok(performance.now()-t0)}else if(performance.now()-t0>40000){clearInterval(iv);no(new Error("The copy did not finish starting within 40 seconds."))}},40)});
if(hall){/* hall of mirrors: a glowing frame, a layer tag above it, and a small colour turn that compounds with every layer inside it */
f.style.cssText="position:absolute;inset:6%;width:88%;height:88%;border:1px solid var(--ac);border-radius:6px;background:#000;z-index:99999;box-shadow:0 0 22px var(--ac),0 0 60px rgba(0,0,0,.6);filter:hue-rotate(16deg)";
const tg=d.createElement("div");tg.textContent="LAYER "+depth;tg.style.cssText="position:absolute;left:6%;top:calc(6% - 17px);z-index:99999;font:700 11px/15px monospace;letter-spacing:.14em;padding:0 8px;border-radius:5px 5px 0 0;background:var(--ac);color:#000;pointer-events:none";host.append(tg);f._tag=tg}
f.src=url;host.append(f);
try{const ms=await ready;return{frame:f,ms}}catch(e){QN.drop(f);throw e}},
drop(f){try{const u=f._url;f._tag&&f._tag.remove();f.remove();u&&setTimeout(()=>URL.revokeObjectURL(u),500)}catch(e){}},
heap(){const m=performance.memory;return m?m.usedJSHeapSize/1048576:null},
heapFull(){const m=performance.memory;return m?m.usedJSHeapSize/m.jsHeapSizeLimit:0},
/* frame rate the same way the Benchmark Live tab does: gaps between frames, skipping the first few while the page settles, and the middle value so one stall cannot ruin it */
async fps(ms){await QN.sleep(300);return new Promise(r=>{const d=[];let last=0,t0=performance.now();const f=t=>{if(last)d.push(t-last);last=t;const el=performance.now()-t0;if((el>=ms&&d.length>=12)||el>4000){const s=d.slice(2).sort((a,b)=>a-b);r(s.length?1000/s[s.length>>1]:0)}else requestAnimationFrame(f)};requestAnimationFrame(f)})},
/* run two of the Benchmark app's own tests inside the given window (a copy of the OS), so the copy measures itself */
async measure(w){const BNx=w.eval("BN"),out={};for(const id of["int","dom"]){await BNx.tests.find(x=>x.id===id).run()}/* warm-up pass so every layer is measured the same way */for(const id of["int","dom"]){const t=BNx.tests.find(x=>x.id===id);const r=await t.run();out[id]=typeof r==="number"?r:(r&&r.v)||0}return out}
};
defApp("quine",{name:"Quine",icon:"quine",cat:"System",w:860,h:780,single:true,desc:"the OS running inside itself",kw:"quine self recursion inception nested itself copy benchmark bootstrap ouroboros",
init(win,b){
const depthTxt=QN.depth?"You are inside a copy of the OS, "+QN.depth+(QN.depth===1?" layer":" layers")+" down. Every layer is the whole ship.":"This is the real OS (layer 0).";
const stage=h("div",{style:"position:relative;flex:1 0 340px;background:#000;border:1px solid var(--bd);border-radius:8px;overflow:hidden"},h("div",{class:"dim",style:"position:absolute;inset:0;display:flex;align-items:center;justify-content:center;text-align:center;padding:20px"},"The copy will appear here."));
const msg=h("div",{class:"dim",style:"flex:none;min-height:18px;overflow-wrap:anywhere"}),res=h("div",{style:"flex:none;display:flex;flex-direction:column;gap:4px"});
let root=null,busy=false;
const bRun=h("button",{class:"btn pri"},ic("quine")," Run a copy of this OS here"),bClose=h("button",{class:"btn"},"Close the copy"),bBench=h("button",{class:"btn"},ic("gauge")," Stack and benchmark");
const nSel=h("select",{class:"t"},...Array.from({length:Math.max(1,Math.min(QN.max(),QN.max()-QN.depth))},(_,i)=>h("option",{value:i+1},(i+1)+(i?" layers":" layer"))));
const left=()=>Math.max(0,QN.max()-QN.depth);
const paint=()=>{bClose.style.display=root?"":"none";bRun.style.display=root?"none":"";[bRun,bClose,bBench,nSel].forEach(e=>e.disabled=busy);if(left()<=0){bRun.disabled=true;bBench.disabled=true;nSel.disabled=true}};
const clearStage=()=>{if(root){QN.drop(root);root=null}stage.replaceChildren(h("div",{class:"dim",style:"position:absolute;inset:0;display:flex;align-items:center;justify-content:center;text-align:center;padding:20px"},"The copy will appear here."))};
const guard=()=>{if(left()<=0){msg.textContent="Depth limit reached ("+QN.max()+" layers on this device). Going deeper risks the tab running out of memory.";return false}if(QN.heapFull()>.7){msg.textContent="Memory is already above 70% of what this tab may use. Close a copy first.";return false}return true};
bRun.onclick=async()=>{if(busy||!guard())return;busy=true;paint();msg.textContent="Reading this page's own source and booting a copy...";stage.replaceChildren();
try{const r=await QN.mount(stage,QN.depth+1);root=r.frame;msg.textContent="A copy booted in "+Math.round(r.ms)+" ms. It is running the same file you are. Open Quine in it to go deeper."}catch(e){msg.textContent=e.message;clearStage()}busy=false;paint()};
bClose.onclick=()=>{clearStage();msg.textContent="Copy closed.";paint()};
bBench.onclick=async()=>{if(busy||!guard())return;const n=+nSel.value;busy=true;paint();clearStage();res.replaceChildren();msg.textContent="Measuring layer 0 (this OS)...";
const rows=[];const T=(el,txt)=>el.textContent=txt;
try{
const base=await QN.measure(window);rows.push({d:QN.depth,boot:0,int:base.int,dom:base.dom,fps:await QN.fps(1200),heap:QN.heap()});drawRes(rows);
let cur=window,host=stage;
for(let k=1;k<=n;k++){
if(win.dead)return;if(QN.heapFull()>.75){msg.textContent="Stopped early: memory is above 75% of this tab's limit.";break}
msg.textContent="Booting layer "+(QN.depth+k)+" inside layer "+(QN.depth+k-1)+"...";
const Q=cur===window?QN:cur.eval("QN");
const r=await Q.mount(k===1?stage:cur.document.querySelector("#desk"),QN.depth+k,null,true);if(k===1)root=r.frame;cur=r.frame.contentWindow;
await QN.sleep(900);msg.textContent="Benchmarking layer "+(QN.depth+k)+" from inside it...";
const m=await QN.measure(cur);rows.push({d:QN.depth+k,boot:r.ms,int:m.int,dom:m.dom,fps:await QN.fps(1200),heap:QN.heap()});drawRes(rows)}
msg.textContent="Done. Each layer ran its own copy of the Benchmark tests inside itself. The copies are still running; close them when you are finished."}
catch(e){msg.textContent="Stopped: "+e.message}
busy=false;paint()};
function drawRes(rows){res.replaceChildren();const g="display:grid;grid-template-columns:.7fr 1fr 1.1fr 1.1fr 1fr 1fr;gap:6px;font-size:12px;font-variant-numeric:tabular-nums;";
res.append(h("div",{class:"dim",style:g+"font-weight:600"},...["Layer","Boot","Maths speed","Window speed","Page fps","Memory"].map(t=>h("div",{},t))));
const b0=rows[0];rows.forEach((r,i)=>{const pc=(v,b)=>b>0?Math.round(v/b*100)+"%":"-";res.append(h("div",{style:g+"padding:3px 0;border-top:1px solid var(--bd)"},h("div",{},r.d+(i===0?" (real)":"")),h("div",{},i?Math.round(r.boot)+" ms":"-"),h("div",{},pc(r.int,b0.int)),h("div",{},pc(r.dom,b0.dom)),h("div",{},Math.round(r.fps)),h("div",{},r.heap!=null?r.heap.toFixed(0)+" MB":"n/a")))});
if(rows.length>1)res.append(h("div",{class:"dim",style:"font-size:12px;margin-top:4px"},"Speeds are shown against layer 0 (100%). Each layer ran the Benchmark app's own integer and page-building tests inside itself. Page fps is how smoothly the whole tab draws while all layers are alive. Memory is rough: browsers round it."))}
b.style.cssText+=";display:flex;flex-direction:column;gap:8px;padding:10px;overflow-y:auto";
b.append(h("div",{style:"flex:none;overflow-wrap:anywhere"},h("b",{},"Quine. "),"This OS is one file that can read itself, so it can start a copy of itself in a window, and that copy can do the same. All layers share your saves, so a change in a copy is a change to your real data. Copies do not touch your open windows and stay out of the chat."),
h("div",{class:"dim",style:"flex:none"},depthTxt+" This device allows "+QN.max()+" layers, "+left()+" more from here."),
h("div",{class:"row",style:"flex:none;flex-wrap:wrap;gap:6px;border:0;padding:0"},bRun,bClose,bBench,nSel),stage,msg,res);
win.on.close=()=>{clearStage()};paint()}});
/* ===================== THEMES: the Themes app, a game about finding the perfect desktop ===================== */
IP.swatch="M12 3a9 9 0 100 18c1.2 0 2-.8 2-1.8 0-1-.6-1.4-.6-2.2 0-.8.7-1.5 1.6-1.5H17a4 4 0 004-4c0-4.4-4-8.5-9-8.5z M7.5 11h.01 M10 7.5h.01 M14.5 7.5h.01";
/* A theme made by Ex Nihilo is a pure function of a 40-bit "genome". The seed (V1-XXXX-XXXX) IS that genome written in 8 letters and digits, so the same seed makes the same theme on any device, forever. V1 is the version of the recipe: if the recipe ever changes it gets a new version letter, so old seeds keep working. */
const TH=(()=>{
const AL="0123456789ABCDEFGHJKMNPQRSTVWXYZ";
const F=[["hue",8],["harm",2],["bgs",3],["bgh",4],["acs",3],["acl",2],["wall",4],["font",2],["glow",2],["light",1],["dim",3],["pan",2],["rad",2],["a2s",2]];
const WT=["stars","stars","stars","rings","rings","rings","grid","grid","grid","rain","rain","flow","flow","flow","plain","none"];
const FONTS=[MONO,SANS,SERIF,MONO],FN=["Mono","Sans","Serif","Mono"],GL=["0px","4px","8px","14px"],RAD=["2px","4px","6px","10px"];
const HF=["Ember","Amber","Citrine","Lime","Moss","Jade","Cyan","Azure","Indigo","Violet","Orchid","Rose"];
const NOUN=["Harbor","Static","Garden","Signal","Tide","Relay","Orbit","Lantern","Canyon","Archive","Meridian","Cipher","Bloom","Vault","Drift","Beacon"];
const HARM=["Neighbours","Opposites","Triad","Split"],RAR=["Common","Uncommon","Rare","Epic","Legendary"],RCOL=["#9aa3a0","#4cd27a","#4aa3ff","#b66dff","#ffc83d"],TIER=[8.3,9.5,10.9,12.2];
const PH=[.4,.3,.15,.15],PG=[.3,.3,.25,.15],LOCKF={hue:["hue","bgh"],wall:["wall"],font:["font"],mood:["light"]};
const cnt=(a,v)=>a.filter(x=>x===v).length,WTI=w=>{const i=WT.indexOf(w);return i<0?14:i};
const enc=g=>{let b="";for(const[k,n]of F)b+=(g[k]&((1<{let s=String(str||"").toUpperCase().replace(/[^0-9A-Z]/g,"").replace(/O/g,"0").replace(/[IL]/g,"1");let v=2;if(s.length===10&&/^V[12]/.test(s)){v=+s[1];s=s.slice(2)}if(s.length!==8||[...s].some(c=>AL.indexOf(c)<0))return null;let b="";for(const c of s)b+=AL.indexOf(c).toString(2).padStart(5,"0");const g={v};let p=0;for(const[k,n]of F){g[k]=parseInt(b.slice(p,p+n),2);p+=n}return g};
const hex=(h,s,l)=>{h=((h%360)+360)%360;const a=s*Math.min(l,1-l),f=n=>{const k=(n+h/30)%12;return l-a*Math.max(-1,Math.min(k-3,9-k,1))};return"#"+[f(0),f(8),f(4)].map(v=>pad2(Math.round(v*255))).join("")};
const lum=c=>{c=c.replace("#","");const v=[0,2,4].map(i=>{const x=parseInt(c.substr(i,2),16)/255;return x<=.03928?x/12.92:Math.pow((x+.055)/1.055,2.4)});return .2126*v[0]+.7152*v[1]+.0722*v[2]};
const cr=(a,b)=>{const x=lum(a),y=lum(b);return(Math.max(x,y)+.05)/(Math.min(x,y)+.05)};
const fit=(h,s,l,bg,min,d)=>{let c=hex(h,s,l),n=0;while(cr(c,bg){let h=1779033703^s.length;for(let i=0;i>>19}return()=>{h=Math.imul(h^h>>>16,2246822507);h=Math.imul(h^h>>>13,3266489909);return(h^=h>>>16)>>>0}};
const mul=a=>()=>{a|=0;a=a+0x6D2B79F5|0;let t=Math.imul(a^a>>>15,1|a);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296};
const T0={
AL,F,WT,FN,HF,HARM,RAR,RCOL,enc,dec,
rngFrom:s=>mul(hs(s)()),
fam:g=>Math.floor((((g.hue*360/256)+15)%360)/30),
rar(g){const b=-Math.log2(PH[g.harm])-Math.log2(.88)-Math.log2(PG[g.glow])-Math.log2(cnt(WT,WT[g.wall])/16)-Math.log2(cnt(FN,FN[g.font])/4);let r=0;for(const t of TIER)if(b>=t)r++;return r},
roll(rng,base,lock){rng=rng||Math.random;const wp=w=>{const r=rng();let a=0;for(let i=0;iMath.random()-.5).slice(0,2+(Math.random()*2|0));
if(Math.random()<.75)n.hue=(n.hue+(Math.random()<.5?-1:1)*(8+(Math.random()*22|0))+256)%256;
for(const k of ks){const bits=F.find(x=>x[0]===k)[1];n[k]=Math.random()*(1<x[0]===k)[1];if(ks.length===1||Math.random()
{c=c.replace("#","");if(c.length===3)c=c.replace(/./g,"$&$&");const[r,g,b]=[0,2,4].map(i=>parseInt(c.substr(i,2),16)/255),mx=Math.max(r,g,b),mn=Math.min(r,g,b),l=(mx+mn)/2,d=mx-mn;let h=0,s=0;if(d){s=d/(1-Math.abs(2*l-1));h=mx===r?((g-b)/d+(gMath.max(0,Math.min(n,Math.round(x))),dh=(a,b)=>{let d=Math.abs(a-b)%360;return d>180?360-d:d};
const light=!!t.l,A=rg(v.ac),A2=rg(v.ac2),B=rg(v.bg),D=rg(v.dim),H=A[0],hd=dh(A2[0],H);let harm=0,best=1e9;[35,180,120,150].forEach((x,i)=>{const e=Math.abs(hd-x);if(eparseFloat(s)||0,near=(arr,x)=>arr.reduce((bi,y,i)=>Math.abs(y-x)THEME_ORDER.map(k=>({id:"b:"+k,key:k,name:THEMES[k].n,g:TH.approx(THEMES[k]),gen:0,founder:1,v:THEMES[k].v}));
const mine=()=>S.saved.map(s=>{const g=TH.dec(s.seed);return g?{id:"s:"+s.seed,s,name:s.name,g,gen:s.gen||1,v:TH.build(g).v}:null}).filter(Boolean);
const all=()=>founders().concat(mine()),byId=id=>all().find(c=>c.id===id);
const worn=()=>SET.theme,wornIsMine=()=>S.saved.some(s=>"g:"+s.seed===SET.theme);
const traits=g=>TH.HF[TH.fam(g)]+" · "+(g.light?"Light":"Dark")+" · "+TH.WT[g.wall]+" · "+TH.FN[g.font];
const bar=v=>h("div",{class:"bar",style:"background:"+v.bg+";height:34px;border-radius:5px;display:flex;overflow:hidden"},...["bg","pn","pn2","ac","ac2","fg","dim"].map(k=>h("i",{style:"flex:1;background:"+v[k]})));
const copy=async t=>{try{await navigator.clipboard.writeText(t);toast("Copied "+t)}catch(e){toast("Copy failed. Select the seed and copy it by hand.",1)}};
const wearG=g=>{applyTheme(TH.reg(g));draw()},wearC=c=>{if(c.founder){applyTheme(c.key);draw()}else wearG(c.g)};
const owned=g=>S.saved.some(s=>s.seed===TH.enc(g));
const catchG=(g,origin,parents,gen,quiet)=>{const sd=TH.enc(g);if(S.saved.some(x=>x.seed===sd)){toast("You already have that one");return false}
S.saved.push({seed:sd,name:TH.name(g),stars:0,t:Date.now(),gen:gen||1,parents:parents||null,origin:origin||"wild"});THS.save();if(!quiet)toast("Caught "+TH.name(g)+"!");if((gen||1)>=5&&!THS.g5){THS.g5=1;setTimeout(()=>toast("Generation "+gen+". Look how far it has drifted from the Founder. Is it the same theme? Is it the same ship?"),1200)}return true};
const wornCard=()=>{const t=THEMES[SET.theme]||THEMES.phosphor,g=TH.cur(),mineW=wornIsMine();
return h("div",{style:"flex:none;padding:6px 10px;border-bottom:1px solid var(--bd);display:flex;gap:8px;align-items:center;flex-wrap:wrap"},h("span",{class:"dim"},"Wearing:"),h("b",{},t.n),
g&&!mineW?h("button",{class:"btn sm pri",onclick:()=>{catchG(g,"wild",null,1);draw()}},"Catch this one"):null,g?h("button",{class:"btn sm",onclick:()=>copy(TH.enc(g))},TH.enc(g)):null,h("span",{class:"dim",style:"margin-left:auto"},"Wallpaper:"),h("select",{class:"t",title:"Keep the theme but choose its wallpaper. \"auto\" uses the theme's own.",onchange:e=>{SET.wall=e.target.value;saveSet();try{setWall()}catch(x){}draw()}},...["auto",...WALLN].map(w=>h("option",{value:w,selected:SET.wall===w},w==="auto"?"auto (theme's own)":w))))};
const head=()=>{const m=mine(),gen=m.reduce((a,c)=>Math.max(a,c.gen),0);
return h("div",{style:"flex:none;padding:8px 10px;border-bottom:1px solid var(--bd);display:flex;flex-direction:column;gap:6px"},
h("div",{style:"display:flex;gap:12px;flex-wrap:wrap;align-items:baseline"},h("b",{class:"ac"},"Themes"),h("span",{class:"dim"},m.length+" caught"),h("span",{class:"dim"},"deepest generation "+gen),h("span",{class:"dim"},"Dex "+dexN()+"/"+DEXT)),
h("div",{class:"row",style:"flex-wrap:wrap;gap:4px;border:0;padding:0"},...["Meadow","Den","Nursery","Dex"].map(t=>h("button",{class:"btn"+(tab===t?" pri":""),onclick:()=>{tab=t;LS.set("tvos_themes_tab",t);draw()}},t))))};
/* ---- the Dex: traits you have caught or bred ---- */
const have=()=>{const o={h:{},w:{},f:{},m:{}};for(const c of mine()){o.h[TH.fam(c.g)]=1;o.w[TH.WT[c.g.wall]]=1;o.f[TH.FN[c.g.font]]=1;o.m[c.g.light?1:0]=1}return o};
const DEXT=12+7+3+2,dexN=()=>{const o=have();return Object.values(o).reduce((a,x)=>a+Object.keys(x).length,0)};
/* ---- a creature card ---- */
const card=(c,btns,sub)=>h("div",{class:"swc"+(worn()==="g:"+(c.s?c.s.seed:"")||worn()===c.key?" on":""),style:"cursor:default"},bar(c.v),
h("div",{style:"display:flex;justify-content:space-between;gap:6px;align-items:baseline"},h("b",{style:"overflow-wrap:anywhere"},c.name),h("span",{class:"dim",style:"font-size:11px;white-space:nowrap"},c.founder?"Founder":"Gen "+c.gen)),
h("div",{class:"dim",style:"font-size:11px;overflow-wrap:anywhere"},traits(c.g)),sub?h("div",{class:"dim",style:"font-size:11px"},sub):null,
h("div",{style:"display:flex;gap:4px;flex-wrap:wrap;margin-top:4px"},...btns.filter(Boolean)));
const wildCard=(g,label)=>{const c={name:TH.name(g),g,v:TH.build(g).v,gen:1};const have=owned(g);
return card(c,[h("button",{class:"btn sm",onclick:()=>wearG(g)},"Try it on"),h("button",{class:"btn sm"+(have?"":" pri"),disabled:have,onclick:()=>{catchG(g,"wild",null,1);draw()}},have?"Caught":"Catch")],label)};
/* ---- Meadow ---- */
const newWild=()=>{wild=[];for(let i=0;i<6;i++){const g=TH.roll();if(filt.fam>=0)g.hue=Math.round((filt.fam*30+Math.random()*30-15+360)%360*256/360)%256;if(filt.mood)g.light=filt.mood===1?1:0;wild.push(g)}if(!filt.mood){const o=[0,0,0,1,1,1].sort(()=>Math.random()-.5);wild.forEach((g,i)=>g.light=o[i])}};
const meadow=()=>{if(!wild)newWild();
const fs=h("select",{class:"t",onchange:e=>{filt.fam=+e.target.value}},h("option",{value:-1},"Any colour"),...TH.HF.map((n,i)=>h("option",{value:i,selected:filt.fam===i},n)));
const ms=h("select",{class:"t",onchange:e=>{filt.mood=+e.target.value}},...[["Light or dark",0],["Light only",1],["Dark only",2]].map(([n,v])=>h("option",{value:v,selected:filt.mood===v},n)));
const wg=TH.roll(TH.rngFrom("tvos-daily-"+THS.day()));
return h("div",{class:"pad",style:"display:flex;flex-direction:column;gap:10px"},
h("div",{},"Wild themes wander in. Try one on to see it on your whole desktop, and Catch the ones you love. Rarity does not matter here, only whether you like the look."),
h("div",{class:"row",style:"flex-wrap:wrap;gap:8px;border:0;padding:0;align-items:center"},h("span",{class:"dim"},"Look for:"),fs,ms,h("button",{class:"btn pri",onclick:()=>{newWild();draw()}},ic("swatch")," Search again"),h("button",{class:"btn",onclick:async()=>{const v=await dlgPrompt("Type or paste a seed (like V2-K7QM-3F9A):","","Enter a seed");if(v==null)return;const g=TH.dec(v);if(!g)return toast("That is not a valid seed. It is 8 letters and digits, like V2-K7QM-3F9A.",1);wild=[g,...wild.slice(0,5)];draw();wearG(g)}},"Enter a seed")),
h("div",{class:"sw"},...wild.map(g=>wildCard(g))),
h("b",{},"Wanderer of the day"),h("div",{class:"dim",style:"font-size:12px"},"The same visitor for everyone today."),h("div",{class:"sw"},wildCard(wg)))};
/* ---- Den ---- */
const den=()=>{const m=mine();
const parentBtn=c=>h("button",{class:"btn sm"+(pa===c.id||pb===c.id?" pri":""),onclick:()=>{if(pa===c.id||pb===c.id){if(pa===c.id)pa=null;else pb=null}else if(!pa)pa=c.id;else if(!pb)pb=c.id;else{pa=pb;pb=c.id}if(pa&&pb){tab="Nursery";LS.set("tvos_themes_tab",tab);toast("Two parents chosen. Breed them in the Nursery.")}draw()}},pa===c.id?"Parent A":pb===c.id?"Parent B":"Parent");
const varBtn=c=>h("button",{class:"btn sm",title:"Make variations of just this theme",onclick:()=>{pa=c.id;pb="none";tab="Nursery";LS.set("tvos_themes_tab",tab);hatch();}},"Variations");
const mcard=c=>card(c,[h("button",{class:"btn sm",onclick:()=>wearC(c)},"Wear"),parentBtn(c),varBtn(c),h("button",{class:"btn sm",onclick:()=>copy(c.s.seed)},"Seed"),h("button",{class:"btn sm",onclick:async()=>{const n=await dlgPrompt("New name:",c.s.name,"Rename");if(n!=null&&n.trim()){c.s.name=n.trim().slice(0,40);THS.save();draw()}}},"Rename"),
h("button",{class:"btn sm",onclick:async()=>{if(await dlgConfirm("Release "+c.s.name+"? You can always catch it again from its seed "+c.s.seed+".","Release theme","Release")){S.saved=S.saved.filter(x=>x!==c.s);if(pa===c.id)pa=null;if(pb===c.id)pb=null;THS.save();draw()}}},"Release")],
(c.s.parents?(c.s.parents.length===1?"Variation of ":"Child of ")+c.s.parents.join(" × "):"Found wild")+" · "+c.s.seed);
const stars=c=>h("div",{style:"display:flex;gap:2px"},...[1,2,3,4,5].map(n=>h("span",{style:"cursor:pointer;font-size:15px;color:"+(n<=c.s.stars?"var(--ac)":"var(--dim)"),onclick:()=>{c.s.stars=c.s.stars===n?0:n;THS.save();draw()}},n<=c.s.stars?"★":"☆")));
return h("div",{class:"pad",style:"display:flex;flex-direction:column;gap:10px"},
h("div",{},"Your Den. Pick any two creatures with Parent (founders too) and breed them in the Nursery."),
h("b",{class:"ac"},"Caught ("+m.length+")"),m.length?h("div",{class:"sw"},...m.map(c=>{const d=mcard(c);d.insertBefore(stars(c),d.children[2]);return d})):h("div",{class:"dim"},"Nothing caught yet. Visit the Meadow, or breed two founders below."),
h("b",{class:"ac"},"Founders (the built-in themes)"),h("div",{class:"sw"},...founders().map(c=>card(c,[h("button",{class:"btn sm",onclick:()=>wearC(c)},"Wear"),parentBtn(c),varBtn(c)]))))};
/* ---- Nursery ---- */
const slot=(label,id,set,none)=>{const c=id&&id!=="none"?byId(id):null,list=all();
const sel=h("select",{class:"t",onchange:e=>{set(e.target.value||null);kids=[];draw()}},h("option",{value:""},"Choose a parent..."),none?h("option",{value:"none",selected:id==="none"},"None: make variations of A"):null,h("optgroup",{label:"Your creatures"},...list.filter(x=>!x.founder).map(x=>h("option",{value:x.id,selected:x.id===id},x.name))),h("optgroup",{label:"Founders"},...list.filter(x=>x.founder).map(x=>h("option",{value:x.id,selected:x.id===id},x.name))));
return h("div",{style:"flex:1 1 240px;display:flex;flex-direction:column;gap:6px;min-width:0"},h("b",{},label),sel,c?card(c,[h("button",{class:"btn sm",onclick:()=>wearC(c)},"Wear")]):h("div",{class:"dim",style:"border:2px dashed var(--bd);border-radius:8px;padding:20px;text-align:center"},id==="none"?"No second parent: children are variations of A":"Empty"))};
const hatch=()=>{const A=byId(pa),B=pb&&pb!=="none"?byId(pb):null,solo=pb==="none";if(!A||(!solo&&(!B||A.id===B.id)))return toast(solo?"Choose a parent":"Choose two different parents",1);
const sig=g=>{const v=TH.build(g);return Object.values(v.v).join("")+v.w},seen=new Set([sig(A.g)]);if(B)seen.add(sig(B.g));const want=solo?6:4;kids=[];let t=0;
while(kids.length{const A=pa?byId(pa):null,solo=pb==="none",B=pb&&!solo?byId(pb):null;
const leanS=h("select",{class:"t",onchange:e=>{lean=+e.target.value}},...[["Mostly A",.8],["Even mix",.5],["Mostly B",.2]].map(([n,v])=>h("option",{value:v,selected:lean===v},n)));
const focS=h("select",{class:"t",onchange:e=>{cf=e.target.value}},...[["all","Anything"],["colour","Colour only"],["wall","Wallpaper only"],["font","Typeface only"],["feel","Feel only (glow, corners, shades)"]].map(([v,n])=>h("option",{value:v,selected:cf===v},n)));
const stS=h("select",{class:"t",onchange:e=>{cs=e.target.value}},...[["gentle","Gentle"],["normal","Normal"],["wild","Wild"]].map(([v,n])=>h("option",{value:v,selected:cs===v},n)));
const kc=g=>{const c={name:TH.name(g),g,v:TH.build(g).v,gen:Math.max(A?A.gen:0,B?B.gen:0)+1};const have=owned(g);
return card(c,[h("button",{class:"btn sm",onclick:()=>wearG(g)},"Try it on"),h("button",{class:"btn sm"+(have?"":" pri"),disabled:have,onclick:()=>{catchG(g,"bred",solo?[A.name]:[A.name,B.name],c.gen);draw()}},have?"Kept":"Keep")],(solo?"Variation of "+(A?A.name:"?"):"Child of "+(A?A.name:"?")+" × "+(B?B.name:"?")))};
return h("div",{class:"pad",style:"display:flex;flex-direction:column;gap:10px"},
h("div",{},"Choose two parents and hatch a clutch of four children. Or set Parent B to None to make variations of just one theme: choose what may change (for example only the wallpaper) and how much. Each child takes its traits from one parent or the other (colour can blend), with the odd surprise. Keep the ones you love. Keep breeding children with each other to steer toward the look you want."),
h("div",{style:"display:flex;gap:10px;flex-wrap:wrap"},slot("Parent A",pa,v=>pa=v),slot("Parent B",pb,v=>pb=v,true)),
h("div",{class:"row",style:"flex-wrap:wrap;gap:8px;border:0;padding:0;align-items:center"},...(solo?[h("span",{class:"dim"},"Change:"),focS,h("span",{class:"dim"},"How much:"),stS]:[h("span",{class:"dim"},"Children take after:"),leanS]),h("button",{class:"btn pri",disabled:!A||(!solo&&(!B||pa===pb)),onclick:hatch},ic("swatch")," "+(kids.length?"Again":(solo?"Make variations":"Breed")))),
kids.length?h("div",{class:"sw"},...kids.map(kc)):h("div",{class:"dim"},A&&(B||solo)?"Press Breed.":"Pick two parents, or press Parent on two creatures in the Den. Choose None for Parent B to make variations of one theme."))};
/* ---- Dex ---- */
const dex=()=>{const o=have();const chip=(on,t)=>h("span",{style:"border:1px solid "+(on?"var(--ac)":"var(--bd)")+";color:"+(on?"var(--ac)":"var(--dim)")+";border-radius:5px;padding:2px 8px;font-size:12px"},(on?"✓ ":"")+t);
const sec=(t,items)=>h("div",{style:"display:flex;flex-direction:column;gap:5px"},h("b",{},t),h("div",{style:"display:flex;gap:5px;flex-wrap:wrap"},...items));
return h("div",{class:"pad",style:"display:flex;flex-direction:column;gap:12px"},h("div",{},"The Dex lists what you have caught or bred, so it shows what is still missing from your Den. Founders do not count. Try to fill it."),
sec("Colours ("+Object.keys(o.h).length+"/12)",TH.HF.map((n,i)=>chip(o.h[i],n))),sec("Wallpapers",WALLN.map(n=>chip(o.w[n],n))),sec("Typefaces",["Mono","Sans","Serif"].map(n=>chip(o.f[n],n))),sec("Mood",[chip(o.m[0],"Dark"),chip(o.m[1],"Light")]))};
function draw(){if(win.dead)return;root.replaceChildren(head(),wornCard(),h("div",{class:"scr",style:"flex:1;min-height:0;overflow-y:auto"},tab==="Den"?den():tab==="Nursery"?nursery():tab==="Dex"?dex():meadow()))}
root.addEventListener("keydown",e=>{if(e.target.closest("input,textarea,select"))return;if((e.key===" "||e.key==="r"||e.key==="R")&&tab==="Meadow"){e.preventDefault();newWild();draw()}});
OS.on("theme",()=>{if(!win.dead)setTimeout(draw,0)});
draw()}});
/* ===================== PROGRAMS: install and remove your own web apps ===================== */
/* Single-file HTML apps (kept as an offline copy) or links to sites that allow being shown inside other pages.
Each installed app becomes a real app (no desktop icon): Start entry, Spotlight, window. The built-in apps are not listed here and cannot be changed. */
IP.pkg="M3 8l9-5 9 5v8l-9 5-9-5z M3 8l9 5 9-5 M12 13v8";
const PG={
ICONS:["code","globe","book","music","film","image","paint","note","calc","clock","cal","task","tools","star","grid","edit","dice","eye","mic","folder","game","mon","lock","list","home","search","binder"],
MAXSRC:1500000,
cats:["My apps","Games","Media","Tools","Accessories","Internet","Study"],
frames:[],
list(){const l=LS.get("tvos_apps",[]);return Array.isArray(l)?l.filter(r=>r&&typeof r.id==="string"&&typeof r.name==="string"&&(r.kind==="src"||r.kind==="url")):[]},
save(l){return LS.set("tvos_apps",l)},
get(id){return PG.list().find(r=>r.id===id)},
aid:r=>"u-"+(r.id||r),
src:id=>{try{return localStorage.getItem("tvos_app_"+id)}catch(e){return null}},
data(id){try{const o=JSON.parse(localStorage.getItem("tvos_appd_"+id)||"{}");return o&&typeof o==="object"&&!Array.isArray(o)?o:{}}catch(e){return{}}},
slug:s=>(String(s||"app").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,14)||"app"),
newId(name){const used=new Set(PG.list().map(r=>r.id));let id,n=0;do{id=PG.slug(name)+(n++?"-"+Math.random().toString(36).slice(2,6):"")}while(used.has(id)||OS.apps[PG.aid(id)]);return id},
guessIcon(name,kind){const s=String(name).toLowerCase();const m=[[/bible|book|read|librar|gutenberg|wiki|scripture|verse/,"book"],[/music|song|audio|piano|synth|radio|sound|guitar|drum/,"music"],[/video|film|movie|tube|cinema/,"film"],[/paint|draw|sketch|art\b|colou?r/,"paint"],[/photo|image|picture|gallery/,"image"],[/note|write|journal|diary|doc|text|memo/,"note"],[/calc|math|number|sum/,"calc"],[/clock|time|timer|watch|alarm/,"clock"],[/calendar|schedule|plan|agenda/,"cal"],[/game|play|chess|puzzle|quiz|snake|tetris|card/,"game"],[/task|todo|list|check/,"task"],[/map|earth|world|news|search/,"globe"]];for(const [re,i] of m)if(re.test(s))return i;return kind==="url"?"globe":"code"},
titleOf(code){const m=/]*>([\s\S]*?)<\/title>/i.exec(code||"");if(!m)return"";const t=document.createElement("textarea");t.innerHTML=m[1];return t.value.replace(/\s+/g," ").trim().slice(0,40)},
hostOf(u){try{return new URL(u).hostname.replace(/^www\./,"")}catch(e){return u}},
niceName(h2){const p=String(h2).split(".");const n=p.length>2&&p[0].length<4?p[1]:p[0];return n.charAt(0).toUpperCase()+n.slice(1)},
normUrl(s){s=String(s||"").trim();if(!s)return"";if(!/^[a-z][a-z0-9+.-]*:\/\//i.test(s))s="https://"+s;try{const u=new URL(s);return u.protocol==="https:"||u.protocol==="http:"?u.href:""}catch(e){return""}},
/* the script that goes into every installed single-file app: private storage and links that open as Browser tabs */
shim(id,data){const J=s=>JSON.stringify(s).replace(/(function(){try{var D="+J(data)+";var t=0;function send(){clearTimeout(t);t=0;try{parent.postMessage({tvapp:'data',data:D},'*')}catch(e){}}function later(){clearTimeout(t);t=setTimeout(send,250)}"+
"function mk(p){var d=p?D:{};var o={getItem:function(k){k=String(k);return Object.prototype.hasOwnProperty.call(d,k)?d[k]:null},setItem:function(k,v){d[String(k)]=String(v);if(p)later()},removeItem:function(k){delete d[String(k)];if(p)later()},clear:function(){for(var k in d)delete d[k];if(p)later()},key:function(i){var a=Object.keys(d);return i"},
inject(src,sc){let m=/])[^>]*>/i.exec(src);if(!m)m=/])[^>]*>/i.exec(src);if(!m)m=/]*>/i.exec(src);if(!m)return sc+src;const i=m.index+m[0].length;return src.slice(0,i)+sc+src.slice(i)},
register(r){const id=PG.aid(r);defApp(id,{name:r.name,icon:(IP[r.icon]?r.icon:"code"),cat:r.cat||"My apps",desc:r.desc||(r.kind==="url"?"online app":"installed app"),kw:(r.name+" "+(r.cat||"")+" "+(r.desc||"")+" installed program app "+(r.kind==="url"?PG.hostOf(r.url):"")),w:900,h:620,single:true,user:true,deskHide:true,init:(win,b)=>PG.run(r.id,win,b)})},
refresh(){try{buildDesk()}catch(e){}OS.emit&&OS.emit("programs")},
/* run an installed app inside a window */
run(id,win,b){const r=PG.get(id);if(!r){b.append(h("div",{class:"pad"},"This program is no longer installed."));return}
const box=h("div",{style:"position:absolute;inset:0;display:flex;flex-direction:column;background:var(--bg)"});b.style.position="relative";b.append(box);
let fr;
if(r.kind==="url"){
fr=h("iframe",{style:"flex:1;border:0;background:#fff;width:100%",sandbox:BR.sandboxFor(r.url),referrerpolicy:"no-referrer",allow:"fullscreen; autoplay; encrypted-media; picture-in-picture; clipboard-write",allowfullscreen:""});
const bar=h("div",{class:"row",style:"gap:6px;font-size:12px;flex-wrap:wrap"},h("span",{class:"dim grow",style:"overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:80px",title:r.url},PG.hostOf(r.url)+" · online · blank page? the site may refuse to be shown here"),
h("button",{class:"btn sm",title:"Load it again",onclick:()=>{fr.src=r.url}},ic("refresh"),"Reload"),
h("button",{class:"btn sm",title:"Open in the Browser app",onclick:()=>BR.openUrl(r.url)},ic("globe"),"Browser tab"),
h("button",{class:"btn sm",title:"Open outside this OS",onclick:()=>window.open(r.url,"_blank","noopener")},"Outside"));
box.append(bar,fr);fr.src=r.url}
else{
const code=PG.src(r.id);if(code==null){box.append(h("div",{class:"pad"},"The saved copy of "+r.name+" is missing (it may have been cleared in Clean-up). Open Programs to remove it, then install it again."));return}
fr=h("iframe",{style:"flex:1;border:0;background:#fff;width:100%",sandbox:"allow-scripts allow-forms allow-modals allow-popups allow-downloads allow-pointer-lock allow-presentation",allow:"fullscreen; autoplay; clipboard-write; gamepad",allowfullscreen:""});
box.append(fr);fr.srcdoc=PG.inject(code,PG.shim(r.id,PG.data(r.id)))}
const f={id:r.id,name:r.name,fr,win};PG.frames.push(f);const prev=win.on.close;win.on.close=()=>{PG.frames=PG.frames.filter(x=>x!==f);prev&&prev()}},
add(rec,src){if(rec.kind==="src"){if(src.length>PG.MAXSRC){toast("That file is too big to install ("+fmtBytes(src.length)+"). The limit is "+fmtBytes(PG.MAXSRC)+".",1);return false}try{localStorage.setItem("tvos_app_"+rec.id,src)}catch(e){toast("Not enough browser storage to install this. Remove something in Clean-up first.",1);return false}}
const l=PG.list();l.push(rec);if(!PG.save(l)){try{localStorage.removeItem("tvos_app_"+rec.id)}catch(e){}toast("Could not save the program list (storage is full).",1);return false}
PG.register(rec);PG.refresh();return true},
update(rec,src){const l=PG.list(),i=l.findIndex(x=>x.id===rec.id);if(i<0)return false;if(src!=null){if(src.length>PG.MAXSRC){toast("That source is too big ("+fmtBytes(src.length)+").",1);return false}const old=PG.src(rec.id);try{localStorage.setItem("tvos_app_"+rec.id,src)}catch(e){toast("Not enough browser storage for that change.",1);return false}rec.size=src.length;void old}
l[i]=rec;if(!PG.save(l)){toast("Could not save the change.",1);return false}PG.register(rec);OS.wins.filter(w=>w.app===PG.aid(rec)).forEach(w=>OS.title(w,rec.name));PG.refresh();return true},
async remove(r){if(!await dlgConfirm("Remove "+r.name+"?\n\nIts saved copy"+(r.kind==="src"?" and any data it kept":"")+" will be deleted from this browser. You can export it first.","Remove program","Remove"))return false;
const aid=PG.aid(r);OS.wins.filter(w=>w.app===aid).forEach(w=>{try{OS.close(w)}catch(e){}});delete OS.apps[aid];
try{localStorage.removeItem("tvos_app_"+r.id);localStorage.removeItem("tvos_appd_"+r.id)}catch(e){}
PG.save(PG.list().filter(x=>x.id!==r.id));PG.refresh();toast(r.name+" removed");return true}
};
/* installed apps ask to save their data or to open links as Browser tabs */
addEventListener("message",e=>{const d=e.data;if(!d||typeof d!=="object")return;const f=PG.frames.find(x=>x.fr.contentWindow&&x.fr.contentWindow===e.source);if(!f)return;
if(d.tvapp==="data"&&d.data&&typeof d.data==="object"){let s="";try{s=JSON.stringify(d.data)}catch(x){return}if(s.length>1500000){toast(f.name+" tried to save too much data",1);return}try{localStorage.setItem("tvos_appd_"+f.id,s)}catch(x){toast("Not enough storage to save "+f.name+"'s data",1)}}
else if(d.tvos==="open"&&typeof d.url==="string"&&/^https?:\/\//i.test(d.url))BR.openUrl(d.url)});
for(const r of PG.list())PG.register(r);
defApp("programs",{name:"Programs",icon:"pkg",cat:"System",w:840,h:620,single:true,desc:"install and remove your own web apps",kw:"install uninstall remove add programs apps web app html store add remove software",
init(win,b,arg){
let view="list",q="",catF="All",edit=null,kind="url",d=null,msg="";
const blank=()=>({name:"",url:"",code:"",cat:"My apps",icon:"",desc:"",desk:true,touched:false,iconTouched:false,fileName:""});
const catsNow=()=>{const s=new Set(PG.cats);for(const r of PG.list())if(r.cat)s.add(r.cat);return[...s]};
const start=(k,o)=>{edit=null;kind=k;d=Object.assign(blank(),o||{});view="form";render()};
const openArg=async a=>{if(!a)return;if(typeof a==="string"){const n=V.get(a);if(!n||n.dir)return;try{const t=await V.read(n,"text");start("src",{code:t,name:PG.titleOf(t)||n.name.replace(/\.[a-z]+$/i,""),fileName:n.name})}catch(e){toast("Cannot read: "+e.message,1)}return}
if(a.code!=null)start("src",{code:a.code,name:a.name||PG.titleOf(a.code)});else if(a.url)start("url",{url:a.url,name:a.name||PG.niceName(PG.hostOf(a.url))})};
win.openArg=openArg;
const ago=t=>{try{return new Date(t).toLocaleDateString()}catch(e){return""}};
const rowFor=r=>{const a=OS.apps[PG.aid(r)];
return h("div",{class:"row",style:"gap:10px;flex-wrap:wrap;align-items:center;border:1px solid var(--bd);border-radius:8px;padding:8px 10px"},
h("span",{style:"font-size:22px;display:inline-flex;color:var(--ac)"},ic(IP[r.icon]?r.icon:"code")),
h("div",{class:"grow",style:"min-width:160px"},h("div",{style:"font-weight:700"},r.name),
h("div",{class:"dim",style:"font-size:12px"},r.cat+" · "+(r.kind==="url"?"Online link: "+PG.hostOf(r.url):"Saved copy, works offline · "+fmtBytes(r.size||(PG.src(r.id)||"").length))+" · added "+ago(r.added)),
r.desc?h("div",{class:"dim",style:"font-size:12px"},r.desc):null),
h("div",{style:"display:flex;gap:6px;flex-wrap:wrap"},
h("button",{class:"btn sm pri",onclick:()=>OS.open(PG.aid(r))},ic("play"),"Open"),
h("button",{class:"btn sm",onclick:()=>{edit=r;kind=r.kind;d=Object.assign(blank(),r,{code:r.kind==="src"?(PG.src(r.id)||""):"",touched:true,iconTouched:true});view="form";render()}},ic("edit"),"Edit"),
h("button",{class:"btn sm",title:r.kind==="src"?"Download as a .html file":"Copy the link",onclick:async()=>{if(r.kind==="src"){const s=PG.src(r.id);if(s==null)return toast("The saved copy is missing",1);download(PG.slug(r.name)+".html",s,"text/html");toast("Exported "+r.name)}else{try{await navigator.clipboard.writeText(r.url);toast("Link copied")}catch(e){dlgAlert(r.url,"Link")}}}},ic(r.kind==="src"?"dl":"copy"),r.kind==="src"?"Export":"Copy link"),
h("button",{class:"btn sm",title:"Uninstall",onclick:async()=>{if(await PG.remove(r))render()}},ic("trash"),"Remove")))};
const listView=()=>{const all=PG.list(),cats=["All",...[...new Set(all.map(r=>r.cat||"My apps"))].sort()];if(!cats.includes(catF))catF="All";
const ws=q.toLowerCase().split(/\s+/).filter(Boolean),rs=all.filter(r=>(catF==="All"||(r.cat||"My apps")===catF)&&ws.every(w=>(r.name+" "+r.cat+" "+(r.desc||"")+" "+(r.url||"")).toLowerCase().includes(w))).sort((x,y)=>(x.cat||"").localeCompare(y.cat||"")||x.name.localeCompare(y.name));
const sq=h("input",{class:"t grow",placeholder:"Search your programs",value:q,oninput:e=>{q=e.target.value;fill()}});
const body=h("div",{class:"scr grow",style:"display:flex;flex-direction:column;gap:8px;padding:10px;overflow:auto"});
const fill=()=>{const ws2=q.toLowerCase().split(/\s+/).filter(Boolean),r2=PG.list().filter(r=>(catF==="All"||(r.cat||"My apps")===catF)&&ws2.every(w=>(r.name+" "+r.cat+" "+(r.desc||"")+" "+(r.url||"")).toLowerCase().includes(w))).sort((x,y)=>(x.cat||"").localeCompare(y.cat||"")||x.name.localeCompare(y.name));body.replaceChildren();
if(!all.length){body.append(h("h3",{class:"ac",style:"margin:0"},"Install any web app"),
h("div",{},"An installed program gets a place in Start and in search, and its own window. It does not go on the desktop, so the desktop never fills up: open your programs from this window. The built-in apps are not listed here and stay as they are."),
h("div",{},"Two kinds can be installed: a single .html file (a saved copy that works offline and keeps its own private data), or a link to a website that allows itself to be shown inside other pages."),
h("div",{class:"dim"},"Try a suggestion. It opens the install form with the link filled in:"),
h("div",{style:"display:flex;gap:6px;flex-wrap:wrap"},...BR.sugg.slice(0,10).map(([n,u])=>h("button",{class:"btn sm",onclick:()=>start("url",{url:u,name:n,cat:"Internet"})},n))));return}
if(!r2.length)body.append(h("div",{class:"dim"},"No program matches."));else{let last="";for(const r of r2){if((r.cat||"")!==last){last=r.cat||"";body.append(h("h6",{style:"margin:6px 0 0"},last||"My apps"))}body.append(rowFor(r))}}
body.append(h("div",{class:"dim",style:"font-size:12px;margin-top:6px"},"Installed apps are stored in this browser and are included in Backup. A saved copy cannot see your files, diary or saves. Every program is a plank: add and remove as many as you like and the ship stays the ship."))};
fill();
return h("div",{class:"fl",style:"height:100%;display:flex;flex-direction:column"},
h("div",{class:"row",style:"gap:8px;flex-wrap:wrap"},h("b",{},"Programs"),h("span",{class:"dim"},all.length+" installed"),sq,h("button",{class:"btn pri",onclick:()=>start("url")},ic("plus"),"Install a program")),
all.length>1?h("div",{class:"row",style:"gap:6px;flex-wrap:wrap"},...cats.map(c=>h("button",{class:"btn sm"+(c===catF?" on":""),onclick:()=>{catF=c;render()}},c))):null,body)};
const formView=()=>{const isNew=!edit,fields={};
const setName=v=>{if(!d.touched&&fields.name){d.name=v;fields.name.value=v}if(!d.iconTouched){d.icon=PG.guessIcon(d.name,kind==="url"?"url":"src");drawIcons()}};
const tabs=isNew?h("div",{class:"row",style:"gap:6px;flex-wrap:wrap"},...[["url","From a link"],["paste","Paste source"],["file","From a file"]].map(([k,n])=>h("button",{class:"btn sm"+((k==="url"?kind==="url":k==="paste"?(kind==="src"&&!d.chooseFile):(kind==="src"&&!!d.chooseFile))?" on":""),onclick:()=>{if(k==="url")kind="url";else{kind="src";d.chooseFile=k==="file"}render()}},n))):null;
const src=()=>{if(kind==="url"){fields.url=h("input",{class:"t",placeholder:"https://www.biblegateway.com",value:d.url,oninput:e=>{d.url=e.target.value;const u=PG.normUrl(d.url);if(u)setName(PG.niceName(PG.hostOf(u)))}});return h("div",{style:"display:flex;flex-direction:column;gap:6px"},h("label",{},"Link to the site"),fields.url,h("div",{class:"dim",style:"font-size:12px"},"Needs the internet. It works for sites that allow themselves to be shown inside other pages (the Browser app lists many). If an installed site shows a blank page, it refuses; the window has a button to open it in a browser tab instead. A link app has no private storage here: the site keeps its own."))}
if(!isNew||!d.chooseFile){const ta=h("textarea",{class:"t",spellcheck:"false",style:"min-height:180px;font-family:monospace;font-size:12px;resize:vertical",placeholder:"Paste the complete HTML of a single-file app, from to .",value:d.code,oninput:e=>{d.code=e.target.value;const t=PG.titleOf(d.code);if(t)setName(t)}});ta.value=d.code;fields.code=ta;return h("div",{style:"display:flex;flex-direction:column;gap:6px"},h("label",{},isNew?"The app's HTML":"Source (change it and press Save to update the app)"),ta,h("div",{class:"dim",style:"font-size:12px"},fmtBytes(d.code.length)+" so far. Saved copies work offline. They get private storage (localStorage), but cannot see your files, diary or saves."))}
return h("div",{style:"display:flex;flex-direction:column;gap:6px"},h("label",{},"The app's .html file"),h("div",{class:"row",style:"gap:8px;flex-wrap:wrap;border:0;padding:0"},
h("button",{class:"btn",onclick:async()=>{const [f]=await pickDisk(".html,.htm,text/html");if(!f)return;const t=await f.text();d.code=t;d.fileName=f.name;d.chooseFile=true;setName(PG.titleOf(t)||f.name.replace(/\.[a-z]+$/i,""));render()}},ic("dl"),"Choose a file from this computer"),
h("button",{class:"btn",onclick:async()=>{const p=await pickPath({title:"Choose an HTML file"});if(!p)return;const n=V.get(p);if(!n||n.dir)return toast("Choose a file",1);try{const t=await V.read(n,"text");d.code=t;d.fileName=n.name;d.chooseFile=true;setName(PG.titleOf(t)||n.name.replace(/\.[a-z]+$/i,""));render()}catch(e){toast("Cannot read: "+e.message,1)}}},ic("folder"),"Choose from Files")),
d.fileName?h("div",{},"Loaded "+d.fileName+" ("+fmtBytes(d.code.length)+")"):h("div",{class:"dim"},"No file chosen yet."))};
const iconBox=h("div",{style:"display:flex;gap:4px;flex-wrap:wrap"});
function drawIcons(){iconBox.replaceChildren(...PG.ICONS.map(n=>h("button",{class:"btn sm"+(d.icon===n?" on":""),title:n,style:"padding:4px 6px",onclick:()=>{d.icon=n;d.iconTouched=true;drawIcons()}},ic(n))))}
if(!d.icon)d.icon=PG.guessIcon(d.name,kind==="url"?"url":"src");drawIcons();
fields.name=h("input",{class:"t",placeholder:"Name",value:d.name,oninput:e=>{d.name=e.target.value;d.touched=true;if(!d.iconTouched){d.icon=PG.guessIcon(d.name,kind==="url"?"url":"src");drawIcons()}}});
const dl=h("datalist",{id:"pgcats"+win.id},...catsNow().map(c=>h("option",{value:c})));
const urlEdit=!isNew&&kind==="url"?h("div",{style:"display:flex;flex-direction:column;gap:6px"},h("label",{},"Link"),h("input",{class:"t",value:d.url,oninput:e=>{d.url=e.target.value}})):null;
const go=async()=>{const name=d.name.trim().slice(0,40);if(!name)return toast("Give it a name",1);
const cat=(d.cat||"My apps").trim().slice(0,30)||"My apps",desc=(d.desc||"").trim().slice(0,120);
if(kind==="url"){const u=PG.normUrl(d.url);if(!u)return toast("Enter a link that starts with https://",1);if(/^http:/i.test(u))return toast("Only https:// links can be shown inside this OS",1);
const bk=BR.isBlocked(u);if(bk&&!await dlgConfirm(bk+" is known to refuse being shown inside other pages, so it will probably show a blank page. Install anyway?","Install anyway?","Install anyway"))return;
if(isNew){if(PG.add({id:PG.newId(name),name,kind:"url",url:u,icon:d.icon,cat,desc,desk:d.desk!==false,added:Date.now()})){toast("Installed "+name);view="list";render()}}
else{if(PG.update(Object.assign({},edit,{name,url:u,icon:d.icon,cat,desc,desk:d.desk!==false}))){toast("Saved");view="list";render()}}return}
const code=d.code;if(!code.trim()||!/<\w/.test(code))return toast("That does not look like an HTML app",1);
if(isNew){if(PG.add({id:PG.newId(name),name,kind:"src",icon:d.icon,cat,desc,desk:d.desk!==false,added:Date.now(),size:code.length},code)){toast("Installed "+name+". Open it from Programs, Start or search.");view="list";render()}}
else{if(PG.update(Object.assign({},edit,{name,icon:d.icon,cat,desc,desk:d.desk!==false}),code!==(PG.src(edit.id)||"")?code:null)){toast("Saved");view="list";render()}}};
return h("div",{class:"scr",style:"height:100%;overflow:auto;padding:12px;display:flex;flex-direction:column;gap:10px"},
h("h3",{class:"ac",style:"margin:0"},isNew?"Install a program":"Edit "+edit.name),tabs,isNew?src():(kind==="src"?src():null),urlEdit,
h("div",{style:"display:flex;flex-direction:column;gap:6px"},h("label",{},"Name"),fields.name),
h("div",{style:"display:flex;flex-direction:column;gap:6px"},h("label",{},"Category (pick one or type a new one)"),h("input",{class:"t",list:"pgcats"+win.id,value:d.cat,oninput:e=>{d.cat=e.target.value}}),dl),
h("div",{style:"display:flex;flex-direction:column;gap:6px"},h("label",{},"Icon"),iconBox),
h("div",{style:"display:flex;flex-direction:column;gap:6px"},h("label",{},"Short description (optional)"),h("input",{class:"t",value:d.desc,placeholder:"Shown in Start",oninput:e=>{d.desc=e.target.value}})),
h("div",{class:"dim",style:"font-size:12px"},"Installed programs do not go on the desktop. Open them from this window, Start or search."),
isNew?h("div",{class:"dim",style:"font-size:12px"},"Installing runs someone's code inside a sandboxed window. It cannot read your files, diary or saves. Only install apps you trust."):null,
h("div",{class:"row",style:"gap:8px;border:0;padding:0"},h("button",{class:"btn",onclick:()=>{view="list";render()}},"Cancel"),h("button",{class:"btn pri",onclick:go},isNew?"Install":"Save")))};
const render=()=>{b.replaceChildren(view==="list"?listView():formView())};
win.onProg=OS.on("programs",()=>{if(view==="list"&&!win.dead)render()});
const prevClose=win.on.close;win.on.close=()=>{try{OS.off("programs",win.onProg)}catch(e){}prevClose&&prevClose()};
render();if(arg)openArg(arg)},
onArg(w,a){w.openArg&&w.openArg(a)}});
/* ===================== CARTRIDGES: games that live outside the OS =====================
The OS holds only this player: a shelf, a Store, the sealed window a game runs in, and the saving.
The games themselves come in game packs (a pack is a single .html file such as cartridges.html; one file holds many games).
cartridges.html is the first, default store and cannot be turned off. It may name more stores in its head: .
Those files must sit in the same folder. They appear below the first store, in that order, and each can be turned off (only when none of its games is installed).
Packs are kept in IndexedDB ("tvos_cartridges"), so they are not squeezed into the 5 MB of localStorage.
What you own and every game's progress live under ONE localStorage key, tvos_cartridges, which Backup already covers
(every tvos_ key is), so a new game never needs a new OS. Each game runs in a sandboxed frame with its own private localStorage, kept here.
Other people's games can be added by link; a game on its own website saves with postMessage (see "Add by link"). ===================== */
/* One-time move: Circuit Temple, SysAdmin and My Sky used to be built into the OS and now live in the games pack as cartridges.
Any progress still sitting under their old keys is copied into this player's saves (saves[id] = {oldKey: value}), checked by reading it back,
and only then is the old key removed. If anything looks wrong nothing is deleted. The game ids in the pack must stay circuit, sysadmin and mysky. */
(()=>{try{const M={circuit:"tvos_circuit",sysadmin:"tvos_sysadmin",mysky:"tvos_mysky"},K="tvos_cartridges";const mv=[];for(const id in M){if(localStorage.getItem(M[id])!=null)mv.push(id)}if(!mv.length)return;
let r=null;try{r=JSON.parse(localStorage.getItem(K)||"null")}catch(e){return}if(r!=null&&(typeof r!=="object"||Array.isArray(r)))return;r=r||{};if(!r.saves||typeof r.saves!=="object"||Array.isArray(r.saves))r.saves={};
const done=[];for(const id of mv){const k=M[id],v=localStorage.getItem(k),cur=r.saves[id];if(!cur||typeof cur!=="object"||!Object.keys(cur).length){r.saves[id]={[k]:v};done.push(id)}else if(cur[k]===v)done.push(id)}
if(!done.length)return;localStorage.setItem(K,JSON.stringify(r));const b=JSON.parse(localStorage.getItem(K));
for(const id of done){if(b&&b.saves&&b.saves[id]&&b.saves[id][M[id]]===localStorage.getItem(M[id]))localStorage.removeItem(M[id])}}catch(e){}})();
IP.cart="M5 3h14v14l-3 4H8l-3-4z M9 3v4h6V3 M9 12h6";
const CT={
KEY:"tvos_cartridges",MAXSAVE:600000,
S:{inst:[],urls:[],saves:{},off:[]},meta:[],packs:[],dups:[],probs:{},syncing:null,ready:null,cur:null,runs:[],
load(){try{const r=JSON.parse(localStorage.getItem(CT.KEY)||"null");if(r&&typeof r==="object")CT.S={inst:Array.isArray(r.inst)?r.inst.filter(x=>typeof x==="string"):[],urls:Array.isArray(r.urls)?r.urls.filter(u=>u&&typeof u.id==="string"&&typeof u.url==="string"):[],saves:r.saves&&typeof r.saves==="object"&&!Array.isArray(r.saves)?r.saves:{},off:Array.isArray(r.off)?r.off.filter(x=>typeof x==="string"):[]}}catch(e){}},
save(){try{localStorage.setItem(CT.KEY,JSON.stringify(CT.S));return true}catch(e){toast("Could not save: the browser's storage is full.",1);return false}},
db(){return CT._db||(CT._db=new Promise((res,rej)=>{if(!window.indexedDB)return rej(new Error("no indexedDB"));const q=indexedDB.open("tvos_cartridges",1);q.onupgradeneeded=()=>q.result.createObjectStore("packs",{keyPath:"id"});q.onsuccess=()=>res(q.result);q.onerror=()=>rej(q.error)}))},
async tx(mode,fn){const db=await CT.db();return new Promise((res,rej)=>{const t=db.transaction("packs",mode);let out;const r=fn(t.objectStore("packs"));if(r)r.onsuccess=()=>{out=r.result};t.oncomplete=()=>res(out);t.onerror=t.onabort=()=>rej(t.error)})},
async init(){CT.load();let all=[];try{all=await CT.tx("readonly",s=>s.getAll())||[]}catch(e){}CT.index(all)},
async reindex(){CT.index((await CT.tx("readonly",s=>s.getAll()))||[])},
index(all){const rank=p=>p.id===CT.DEF?0:p.listed?1:2;all=all.slice().sort((a,b)=>rank(a)-rank(b)||(rank(a)===1?(a.order||0)-(b.order||0):(a.added||0)-(b.added||0)));
CT.meta=[];CT.packs=[];CT.dups=[];const seen=Object.create(null);
for(const p of all){const off=CT.S.off.indexOf(p.id)>=0;CT.packs.push({id:p.id,name:p.name,from:p.from,file:p.file||"",listed:!!p.listed,gone:!!p.gone,probed:p.probed||0,order:p.order||0,more:p.more||[],h:p.h,added:p.added,checked:p.checked||0,n:p.games.length,size:p.size||0,len:p.len||0,off,ids:p.games.map(g=>g.id)});
if(off)continue;
for(const g of p.games){if(seen[g.id]){CT.dups.push({id:g.id,name:g.meta.name,pack:p.name,first:seen[g.id]});continue}seen[g.id]=p.name;CT.meta.push(Object.assign({},g.meta,{id:g.id,packId:p.id,size:g.size||0}))}}CT.meta.sort(CT.byName)},
clean(m,id){const s=(v,n)=>String(v==null?"":v).slice(0,n);return{name:s(m.name,60)||id,sub:s(m.sub,80),desc:s(m.desc,400),status:s(m.status,24),color:/^#[0-9a-f]{6}$/i.test(m.color||"")?m.color:"#8a94a6",glyph:/^[MmLlHhVvCcSsQqTtAaZz0-9 .,\-eE]{1,700}$/.test(m.glyph||"")?m.glyph:"M5 3h14v14l-3 4H8l-3-4z M9 3v4h6V3",tags:Array.isArray(m.tags)?m.tags.slice(0,3).map(t=>s(t,20)):[]}},
parse(text,fallbackId){const d=new DOMParser().parseFromString(text,"text/html"),gs=[];
d.querySelectorAll("script.cartsrc").forEach(el=>{let m;try{m=JSON.parse(el.getAttribute("data-meta"))}catch(e){return}if(!m||typeof m!=="object")return;const id=String(m.id||"").replace(/[^a-z0-9_-]/gi,"").slice(0,40);if(!id||id==="__proto__"||id==="constructor"||id==="prototype")return;
const src=el.textContent.replace(/<~\/script/g,"<"+"/script").replace(/<~!--/g,"{const e=d.querySelector('meta[name="'+n+'"]');return e?e.getAttribute("content"):""};
const pid=String(mp("cartridges-pack")||fallbackId||"pack").replace(/[^a-z0-9_-]/gi,"").slice(0,40)||"pack";
const more=[];String(mp("cartridges-more")||"").split(/[\s,]+/).forEach(f=>{if(/^[a-z0-9][a-z0-9._-]{0,60}\.html?$/i.test(f)&&!/^cartridges\.html?$/i.test(f)&&more.indexOf(f)<0&&more.length<40)more.push(f)});
return{id:pid,name:String(mp("cartridges-pack-name")||(d.title||"").trim()||pid).slice(0,60),games:gs,more}},
addRun(g,fr){CT.runs=CT.runs.filter(r=>r.fr!==fr);const r={g,fr};CT.runs.push(r);return r},
dropRun(fr){CT.runs=CT.runs.filter(r=>r.fr!==fr)},
winFor(id){return OS.wins.find(w=>!w.dead&&w.app==="cartgame"&&w.arg===id)},
SANDBOX:"allow-scripts allow-forms allow-modals allow-popups allow-downloads allow-pointer-lock allow-presentation",
/* puts a game into a frame, whether the frame is the player in the Cartridges window or a window of its own */
async mount(fr,g){fr.removeAttribute("srcdoc");fr.removeAttribute("src");
if(g.kind==="own"){const src=await CT.src(g);if(src==null){toast("This game's pack is missing. Load it again in Game packs.",1);return null}fr.setAttribute("sandbox",CT.SANDBOX);fr.srcdoc=CT.inject(src,CT.shim(CT.S.saves[g.id]||{}))}
else{fr.setAttribute("sandbox",BR.sandboxFor(g.url));fr.setAttribute("referrerpolicy","no-referrer");fr.src=g.url}return CT.addRun(g,fr)},
openWin(g){const ex=CT.winFor(g.id);if(ex){OS.focus(ex);return ex}if(CT.runs.length>=3)toast("Several games are running. If the computer feels slow, close one you are not playing.");return OS.open("cartgame",g.id)},
hs(t){let h=5381;for(let i=0;iq.id===(opt.id||p.id));
const rec={id:opt.id||p.id,name:p.name,from:from||"",file:opt.file||"",listed:!!opt.listed,order:opt.order||0,more:p.more,h:CT.hs(text),added:old&&old.added||Date.now(),checked:Date.now(),len:text.length,games:p.games,size:p.games.reduce((a,g)=>a+g.size,0)};
try{await CT.tx("readwrite",s=>s.put(rec))}catch(e){toast("Could not keep the pack: the browser did not allow the storage.",1);return false}
await CT.reindex();if(!silent)toast("Loaded "+p.games.length+" cartridge"+(p.games.length===1?"":"s")+" from "+p.name+".");return true},
async touch(id,patch){try{const r=await CT.tx("readonly",s=>s.get(id));if(r){Object.assign(r,patch);await CT.tx("readwrite",s=>s.put(r))}}catch(e){}},
/* the default pack: cartridges.html, found next to the OS. It is loaded by itself the first time and kept up to date when online. */
DEF:"core",defState:"",HOME:"https://republicka.life/cartridges.html", /* the home of the default store: change this one line if the site ever moves */
async getText(u){const ctl=new AbortController(),t=setTimeout(()=>ctl.abort(),15000);try{const r=await fetch(u,{cache:"no-cache",credentials:"omit",signal:ctl.signal});if(!r.ok){const e=new Error("HTTP "+r.status);e.status=r.status;throw e}return await r.text()}finally{clearTimeout(t)}},
/* Brings the first store and the stores it names up to date. The first store is checked on every open; the others at most once a day, or when force is true. */
sync(force,onChange){if(CT.syncing)return CT.syncing;return CT.syncing=CT._sync(force,onChange).then(r=>{CT.syncing=null;return r},e=>{CT.syncing=null;return false})},
async _sync(force,onChange){
const ping=()=>{if(onChange)try{onChange()}catch(e){}};let ch=false,base=null;CT.probs={};
/* where the first store comes from: next to the OS if it is on a web server, otherwise (or if it is not there) the home site */
const tries=[];if(/^https?:$/.test(location.protocol))tries.push(new URL("cartridges.html",location.href).href);if(tries.indexOf(CT.HOME)<0)tries.push(CT.HOME);
let txt=null,fail=false;for(const u of tries){try{const t=await CT.getText(u);if(!/class=["']?cartsrc/.test(t))throw new Error("not a pack");txt=t;base=new URL(u);CT.coreHref=u;break}catch(e){fail=true}}
if(txt!=null){const ex=CT.packs.find(p=>p.id===CT.DEF);
try{if(ex&&ex.len===txt.length&&ex.h===CT.hs(txt))CT.defState="ok";else{const ok=await CT.addPack(txt,"the default games",true,{id:CT.DEF});CT.defState=ok?"ok":"none";if(ok)ch=true}}catch(e){CT.defState="none"}}
else CT.defState=CT.packs.some(p=>p.id===CT.DEF)?"offline":(/^https?:$/.test(location.protocol)?"none":"file");
if(!base)base=new URL(tries[tries.length-1]);
ping();
const core=CT.packs.find(p=>p.id===CT.DEF),list=core?core.more:[];
for(let i=0;iq.id===id);
if(ex&&!force&&Date.now()-ex.checked<72e6){if(ex.order!==i||!ex.listed)await CT.touch(id,{order:i,listed:true,gone:false,file:f});continue}
try{const txt=await CT.getText(new URL(f,base).href);
if(ex&&ex.len===txt.length&&ex.h===CT.hs(txt))await CT.touch(id,{checked:Date.now(),order:i,listed:true,gone:false,file:f});
else if(await CT.addPack(txt,f,true,{id,file:f,listed:true,order:i}))ch=true;else CT.probs[f]="empty"}
catch(e){CT.probs[f]=e&&e.status===404?"missing":"offline"}
await CT.reindex();ping()}
/* automatic finding: after the listed stores, try cartridges-02.html, cartridges-03.html, ... cartridges-99.html (two digits, so the order stays right past nine) and stop after two missing in a row, so one gap is forgiven */
const seen={},auto=/^cartridges-\d+\.html$/i;let probeOff=false,probed=false;
if(core){let miss=0;const due=force||!core.probed||Date.now()-core.probed>72e6;
for(let n=2;n<=99&&miss<2;n++){const cands=["cartridges-"+String(n).padStart(2,"0")+".html"];if(n<10)cands.push("cartridges-"+n+".html");
if(cands.some(f=>list.indexOf(f)>=0)){miss=0;continue}
const ord=100+n;let hit=false,off=false;
for(const f of cands){const id="s-"+CT.slug(f),ex=CT.packs.find(q=>q.id===id);
if(ex&&!force&&Date.now()-ex.checked<72e6){seen[f]=1;hit=true;if(ex.order!==ord||!ex.listed)await CT.touch(id,{order:ord,listed:true,gone:false,file:f});break}
if(!ex&&!due)continue;
try{const txt=await CT.getText(new URL(f,base).href);probed=true;if(!/class=["']?cartsrc/.test(txt))throw Object.assign(new Error("not a pack"),{status:404});
seen[f]=1;hit=true;
if(ex&&ex.len===txt.length&&ex.h===CT.hs(txt))await CT.touch(id,{checked:Date.now(),order:ord,listed:true,gone:false,file:f});
else if(await CT.addPack(txt,f,true,{id,file:f,listed:true,order:ord}))ch=true;
await CT.reindex();ping();break}
catch(e){if(e&&e.status===404){probed=true}else{off=true;break}}}
if(off){probeOff=true;break}
if(hit)miss=0;else miss++}
if(probed)await CT.touch(CT.DEF,{probed:Date.now()})}
if(core){for(const p of CT.packs.slice()){if((p.listed||p.gone)&&list.indexOf(p.file)<0&&!seen[p.file]&&!(probeOff&&auto.test(p.file))){if(p.ids.some(x=>CT.isIn(x)))await CT.touch(p.id,{listed:false,gone:true});else{try{await CT.tx("readwrite",s=>s.delete(p.id))}catch(e){}CT.S.off=CT.S.off.filter(x=>x!==p.id);CT.save()}ch=true}}}
await CT.reindex();ping();return ch},
/* get a store's original .html file again, to save it: the first store and listed or found stores from next to cartridges.html (or the home site), a manual pack from its web address */
async getRaw(p){const tries=[];
if(p.id===CT.DEF||p.file){const nm=p.id===CT.DEF?"cartridges.html":p.file,bs=[];if(CT.coreHref)bs.push(CT.coreHref);if(/^https?:$/.test(location.protocol))bs.push(new URL("cartridges.html",location.href).href);bs.push(CT.HOME);for(const b of bs){const u=nm==="cartridges.html"&&b.slice(-15)==="cartridges.html"?b:new URL(nm,b).href;if(tries.indexOf(u)<0)tries.push(u)}}
else if(/^https?:\/\//i.test(p.from||""))tries.push(p.from);
for(const u of tries){try{const t=await CT.getText(u);if(/class=["']?cartsrc/.test(t))return t}catch(e){}}return null},
canGet(p){return p.id===CT.DEF||!!p.file||/^https?:\/\//i.test(p.from||"")},
fileOf(p){return p.id===CT.DEF?"cartridges.html":p.file||(CT.slug(p.name)||"pack")+".html"},
/* turn a store off or on; it will not turn off while a game from it is installed */
async toggle(id){const p=CT.packs.find(q=>q.id===id);if(!p||id===CT.DEF)return"";
if(!p.off){const used=p.ids.filter(x=>CT.isIn(x)).map(x=>{const g=CT.meta.find(m=>m.id===x);return g?g.name:x});
if(used.length){const shown=used.slice(0,4).join(", ")+(used.length>4?" and "+(used.length-4)+" more":"");return"You need to uninstall "+shown+" before you can turn off "+p.name+"."}
CT.S.off.push(id)}else CT.S.off=CT.S.off.filter(x=>x!==id);
CT.save();await CT.reindex();return""},
slug:s=>String(s||"pack").toLowerCase().replace(/\.[a-z]+$/,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,30),
async rmPack(id){try{await CT.tx("readwrite",s=>s.delete(id))}catch(e){}const pk=CT.packs.find(q=>q.id===id),gone=pk?pk.ids:[];CT.S.inst=CT.S.inst.filter(x=>gone.indexOf(x)<0);CT.S.off=CT.S.off.filter(x=>x!==id);CT.save();await CT.reindex()},
async src(g){const p=await CT.tx("readonly",s=>s.get(g.packId));const x=p&&p.games.find(q=>q.id===g.id);return x?x.src:null},
hostOf(u){try{return new URL(u).hostname.replace(/^www\./,"")}catch(e){return u}},
byName(x,y){const p=String(x.name||"").toLowerCase(),q=String(y.name||"").toLowerCase();return pq?1:0},
all(){return CT.meta.map(g=>Object.assign({kind:"own"},g)).concat(CT.S.urls.map(u=>({id:u.id,name:u.name,sub:"Online cartridge",kind:"url",url:u.url,color:"#4a5568",glyph:"M12 3a9 9 0 100 18 9 9 0 000-18z M3 12h18 M12 3c3 3 3 15 0 18 M12 3c-3 3-3 15 0 18",desc:"A game from "+CT.hostOf(u.url)+". It needs an internet connection.",tags:["Online"]}))).sort(CT.byName)},
find(id){return CT.all().find(g=>g.id===id)},
isIn:id=>CT.S.inst.indexOf(id)>=0,
inject(src,sc){let m=/])[^>]*>/i.exec(src)||/])[^>]*>/i.exec(src)||/]*>/i.exec(src);if(!m)return sc+src;const i=m.index+m[0].length;return src.slice(0,i)+sc+src.slice(i)},
/* the script put into every game: its localStorage is private to the game and is handed back here to be kept */
shim(data){const J=JSON.stringify(data).replace(/(function(){try{var D="+J+",t=0;function send(){clearTimeout(t);t=0;try{parent.postMessage({tvc:'save',data:D},'*')}catch(e){}}function later(){clearTimeout(t);t=setTimeout(send,300)}"+
"function mk(p){var d=p?D:{};var o={getItem:function(k){k=String(k);return Object.prototype.hasOwnProperty.call(d,k)?d[k]:null},setItem:function(k,v){d[String(k)]=String(v);if(p)later()},removeItem:function(k){delete d[String(k)];if(p)later()},clear:function(){for(var k in d)delete d[k];if(p)later()},key:function(i){return Object.keys(d)[i]||null}};"+
"return new Proxy(o,{get:function(T,k){if(k==='length')return Object.keys(d).length;if(k in T)return T[k];return typeof k==='string'&&Object.prototype.hasOwnProperty.call(d,k)?d[k]:undefined},set:function(T,k,v){T.setItem(k,v);return true},deleteProperty:function(T,k){T.removeItem(k);return true},has:function(T,k){return k in T||Object.prototype.hasOwnProperty.call(d,k)},ownKeys:function(){return Object.keys(d)},getOwnPropertyDescriptor:function(T,k){return Object.prototype.hasOwnProperty.call(d,k)?{value:d[k],enumerable:true,configurable:true,writable:true}:undefined}})}"+
"var L=mk(true),Q=mk(false);Object.defineProperty(window,'localStorage',{configurable:true,get:function(){return L}});Object.defineProperty(window,'sessionStorage',{configurable:true,get:function(){return Q}});"+
"addEventListener('pagehide',function(){if(t)send()});document.addEventListener('visibilitychange',function(){if(document.hidden&&t)send()});addEventListener('message',function(e){if(e.data&&e.data.tvc==='flush'&&t)send()})}catch(e){}})()<"+"/script>"}
};
addEventListener("message",e=>{const d=e.data;if(!d||typeof d!=="object"||!d.tvc)return;const c=CT.runs.find(r=>r.fr&&r.fr.contentWindow&&e.source===r.fr.contentWindow);if(!c)return;const id=c.g.id,s=CT.S.saves[id]||(CT.S.saves[id]={});
if(d.tvc==="save"&&d.data&&typeof d.data==="object"&&!Array.isArray(d.data)){let j;try{j=JSON.stringify(d.data)}catch(x){return}if(j.length>CT.MAXSAVE){toast(c.g.name+" tried to save too much",1);return}CT.S.saves[id]=d.data;CT.save()}
else if(d.tvc==="set"&&typeof d.k==="string"){const v=String(d.v==null?"":d.v);if(v.length>CT.MAXSAVE){toast(c.g.name+" tried to save too much",1);return}s[d.k]=v;CT.save()}
else if(d.tvc==="get"&&typeof d.k==="string"){try{e.source.postMessage({tvc:"val",k:d.k,n:d.n,v:Object.prototype.hasOwnProperty.call(s,d.k)?s[d.k]:null},"*")}catch(x){}}});
defApp("cartridges",{name:"Cartridges",icon:"cart",cat:"Games",w:940,h:660,single:true,desc:"play games that live outside the OS",kw:"cartridges cartridge games game store install packs play timelord arcade shelf",
init(win,b){
const esc=s=>String(s).replace(/[&<>"]/g,c=>({"&":"&","<":"<",">":">",'"':"""}[c]));
const kb=n=>n<1024?n+" bytes":n<1048576?(n/1024).toFixed(0)+" KB":(n/1048576).toFixed(1)+" MB";
if(!document.getElementById("ctcss")){const st=document.createElement("style");st.id="ctcss";st.textContent=".ctp{position:absolute;inset:0;display:flex;flex-direction:column}.ctp nav{display:flex;gap:6px;flex-wrap:wrap;padding:8px 10px;border-bottom:1px solid var(--bd);flex:none;align-items:center}.ctp .ctm{flex:1;min-height:0;overflow:auto;padding:14px}.ctp h4{margin:0 0 2px;font-size:18px}.ctg{display:grid;grid-template-columns:repeat(auto-fill,minmax(230px,1fr));gap:12px}.ctc{border:1px solid var(--bd);border-radius:10px 10px 14px 14px;overflow:hidden;display:flex;flex-direction:column;background:var(--bg2,rgba(255,255,255,.04))}.ctc .tp{height:10px;background:rgba(0,0,0,.35);border-bottom:1px solid var(--bd);position:relative}.ctc .tp:after{content:'';position:absolute;left:50%;top:0;width:44%;height:100%;transform:translateX(-50%);border:1px solid var(--bd);border-top:0;border-radius:0 0 8px 8px;background:var(--bg,#111)}.ctc .lb{margin:10px 10px 0;border-radius:6px;height:104px;display:flex;align-items:center;justify-content:center;position:relative;overflow:hidden;border:1px solid rgba(255,255,255,.12)}.ctc .lb svg{width:56px;height:56px;fill:none;stroke:currentColor;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round}.ctc .lb b{position:absolute;left:8px;bottom:5px;font-size:10px;letter-spacing:.12em;text-transform:uppercase;color:#fff;opacity:.85}.ctc .bd{padding:8px 12px 12px;display:flex;flex-direction:column;gap:5px;flex:1}.ctc .nm{font-weight:700;font-size:15px}.ctc .ft{display:flex;gap:6px;flex-wrap:wrap;align-items:center;margin-top:auto}.cttag{font-size:11px;border:1px solid var(--bd);border-radius:99px;padding:0 8px}.ctbox{border:1px solid var(--bd);border-radius:10px;padding:10px 12px;margin:8px 0}.ctem{border:1px dashed var(--bd);border-radius:12px;padding:22px;text-align:center}.ctph{margin:18px 0 8px;display:flex;gap:8px;align-items:baseline}.ctph:first-child{margin-top:0}.ctchips{display:flex;gap:6px;flex-wrap:wrap;margin:8px 0 4px}.ctwarn{border:1px solid #c9a227;border-radius:10px;padding:8px 12px;margin:8px 0;font-size:13px}.ctp pre{border:1px solid var(--bd);border-radius:6px;padding:8px;white-space:pre-wrap;font-size:12px;overflow:auto}#ctplay{position:absolute;inset:0;display:none;flex-direction:column;background:var(--bg,#000);z-index:3}#ctplay.on{display:flex}#ctplay .pb{display:flex;gap:8px;align-items:center;padding:6px 10px;border-bottom:1px solid var(--bd);flex:none;flex-wrap:wrap}#ctplay .pb b{flex:1;min-width:90px}";document.head.append(st)}
const box=h("div",{class:"ctp"});b.style.position="relative";b.append(box);
const nav=h("nav"),main=h("div",{class:"ctm"}),play=h("div",{id:"ctplay"});play.dataset.fsx="dbl";play.setAttribute("data-fsx-bar","");box.append(nav,main,play);
const fr=h("iframe",{style:"flex:1;border:0;width:100%;background:#fff;min-height:0",allow:"fullscreen; autoplay; clipboard-write; gamepad",allowfullscreen:""});
const pt=h("b"),ps=h("span",{class:"dim",style:"font-size:12px"}),pback=h("button",{class:"btn sm"},"← Back"),prel=h("button",{class:"btn sm"},"Restart"),pwin=h("button",{class:"btn sm",title:"Keep playing in a window of its own, so you can use other apps beside it"},"New window"),pfull=h("button",{class:"btn sm"},"Full screen");
play.append(h("div",{class:"pb"},pback,pt,ps,prel,pwin,pfull),fr);
let view="shelf",ready=false,confirm=null,msg="",msg2="",q="",tagf="";
const tile=(g,mode)=>{const inst=CT.isIn(g.id);let s='
'+orphan.length+' installed game'+(orphan.length>1?"s are":" is")+' missing, because its game pack is not loaded. Load the pack again in Game packs and it comes back with its progress.
'}
else if(view==="store"){s+='
Store
Pick a game and install it. It goes on your shelf in My cartridges.'+(CT.syncing?' Checking for new games…':'')+'
Some games share a name tag (id) with a game in an earlier store, so they are hidden: '+CT.dups.slice(0,5).map(d=>esc(d.name)+' ('+esc(d.pack)+')').join(", ")+(CT.dups.length>5?" and more":"")+'.
'}
else s+='
The Store is empty because no game pack is loaded yet.
'}
else if(view==="packs"){s+='
Game packs
A game pack is one .html file that holds many games, like cartridges.html. Games are kept in this browser\'s storage, not in the OS, so there is no small limit.
'+esc(f)+(CT.probs[f]==="missing"?" is listed by cartridges.html but was not found.":" could not be loaded.")+'
').join("")+
'
'+(CT.packs.filter(CT.canGet).length>1?'':'')+'
Download saves the store\'s original file so you can keep it or put it on a USB stick. It needs an internet connection. Turning a store off hides its games. It will not turn off while one of its games is installed. Removing a manual pack removes its games from your shelf, and your progress is kept so loading it again brings the games back as you left them.
Using '+kb(used)+' of your browser\'s saving space (about 5 MB is shared by the whole OS).
'+(used>3000000?'
This is getting full. Use "Erase save" on games you no longer play.
':"")+'
'}}
else{s+='
Add by link
Add a game from the web. It must be a page that allows itself to be shown inside other pages, and it needs an internet connection.
Name
Address
'+
'Making a game for Cartridges
The easy way: make the game a single .html file that uses localStorage as normal, and put it in a game pack. Its localStorage is kept for you automatically and goes into Backup.
A game on its own website: a site cannot use another site\'s storage, so ask Cartridges to keep your save with messages:
The page must allow framing (no X-Frame-Options: DENY).
';
if(CT.S.urls.length)s+='
Your links
'+CT.S.urls.map(u=>'
'+esc(u.name)+''+esc(CT.hostOf(u.url))+'
').join("")}
main.innerHTML=s;if(view==="store")paintStore()};
/* playing */
const stopPlay=()=>{fsOff();try{fr.contentWindow.postMessage({tvc:"flush"},"*")}catch(e){}setTimeout(()=>{fr.removeAttribute("srcdoc");fr.removeAttribute("src");fr.src="about:blank";play.classList.remove("on");CT.dropRun(fr);CT.cur=null;CT.save();render()},160)};
const startPlay=async g=>{const r=await CT.mount(fr,g);if(!r)return;CT.cur=r;pt.textContent=g.name;ps.textContent=g.kind==="own"?"progress saves by itself":CT.hostOf(g.url)+" · online";
play.classList.add("on")};
pback.onclick=stopPlay;pwin.onclick=()=>{if(!CT.cur)return;const g=CT.cur.g;stopPlay();setTimeout(()=>CT.openWin(g),240)};prel.onclick=()=>{if(CT.cur)startPlay(CT.cur.g)};const fsEl=()=>document.fullscreenElement||document.webkitFullscreenElement;
const fsLabel=()=>{pfull.textContent=fsEl()===play?"Exit full screen":"Full screen"};
const fsOff=()=>{try{if(fsEl()===play)(document.exitFullscreen||document.webkitExitFullscreen).call(document)}catch(e){}};
/* the whole player (with its bar and this button) goes full screen, so there is always a way back */
pfull.onclick=()=>{try{if(fsEl()===play)fsOff();else(play.requestFullscreen||play.webkitRequestFullscreen).call(play)}catch(e){toast("Full screen is not available here.",1)}};
document.addEventListener("fullscreenchange",fsLabel);document.addEventListener("webkitfullscreenchange",fsLabel);
win.on.close=(prev=>()=>{fsOff();document.removeEventListener("fullscreenchange",fsLabel);document.removeEventListener("webkitfullscreenchange",fsLabel);try{fr.contentWindow.postMessage({tvc:"flush"},"*")}catch(e){}CT.dropRun(fr);if(CT.cur&&CT.cur.fr===fr)CT.cur=null;prev&&prev()})(win.on.close);
const arm=(k,ms)=>{confirm=k;setTimeout(()=>{if(confirm===k){confirm=null;if(ready)render()}},ms||3000)};
const doRm=(k,wipe)=>{CT.S.inst=CT.S.inst.filter(x=>x!==k);if(wipe)delete CT.S.saves[k];confirm=null;CT.save();toast(wipe?"Removed, and its progress erased.":"Removed. Your progress is kept in case you install it again.");render()};
main.addEventListener("input",e=>{if(e.target&&e.target.id==="ctq"){q=e.target.value;paintStore()}});
box.addEventListener("click",async e=>{const t=e.target.closest("[data-a],[data-v]");if(!t)return;
if(t.dataset.v){view=t.dataset.v;msg="";confirm=null;render();main.scrollTop=0;return}
const a=t.dataset.a,k=t.dataset.k;
if(a==="install"){if(!CT.isIn(k))CT.S.inst.push(k);CT.save();toast("Installed. It is in My cartridges.");render()}
else if(a==="play"){const g=CT.find(k),w=CT.winFor(k);if(w){OS.focus(w);toast("It is already open in its own window.")}else if(g)startPlay(g)}
else if(a==="win"){const g=CT.find(k);if(g)CT.openWin(g)}
else if(a==="remove"){if(CT.winFor(k)){toast("Close its window first, then remove it.",1);return}const hs=CT.S.saves[k]&&Object.keys(CT.S.saves[k]).length;if(!hs&&confirm==="r"+k)doRm(k,false);else{arm("r"+k,hs?9000:3000);render()}}
else if(a==="rmkeep")doRm(k,false);else if(a==="rmwipe")doRm(k,true);else if(a==="rmno"){confirm=null;render()}
else if(a==="tag"){tagf=tagf===k?"":k;render()}
else if(a==="toggle"){msg2=await CT.toggle(k);if(msg2)toast(msg2,1);render()}
else if(a==="erase"){if(confirm==="e"+k){delete CT.S.saves[k];confirm=null;CT.save();toast("Progress erased.");render()}else{arm("e"+k);render()}}
else if(a==="packfile"){const [f]=await pickDisk(".html,.htm,text/html");if(!f)return;try{const ok=await CT.addPack(await f.text(),f.name);msg=ok?"":"That file has no cartridges in it."}catch(x){msg="Could not read that file."}render()}
else if(a==="packurl"){let u=(main.querySelector("#ctpu").value||"").trim();if(!u)return;if(!/^[a-z][a-z0-9+.-]*:\/\//i.test(u))u="https://"+u;msg="Loading…";render();try{const r=await fetch(u,{credentials:"omit",referrerPolicy:"no-referrer"});if(!r.ok)throw new Error("HTTP "+r.status);const ok=await CT.addPack(await r.text(),CT.hostOf(u));msg=ok?"":"That page has no cartridges in it."}catch(x){msg="Could not load it. The website may not allow other pages to read it. Save the file and load it from a file instead."}render()}
else if(a==="dlpack"){const p=CT.packs.find(q=>q.id===k);if(!p)return;toast("Getting "+CT.fileOf(p)+"…",0);const t=await CT.getRaw(p);if(t==null)toast("Could not get "+CT.fileOf(p)+". Check your internet connection and try again.",1);else{download(CT.fileOf(p),t,"text/html");toast("Saved "+CT.fileOf(p)+".",0)}}
else if(a==="dlall"){const ps=CT.packs.filter(CT.canGet);toast("Getting "+ps.length+" stores…",0);const files=[],enc=new TextEncoder(),miss=[];for(const p of ps){const t=await CT.getRaw(p);if(t==null)miss.push(CT.fileOf(p));else files.push({name:CT.fileOf(p),data:enc.encode(t),mt:Date.now()})}
if(!files.length)toast("Could not get any stores. Check your internet connection and try again.",1);else{download("cartridges-stores.zip",makeZip(files));toast("Saved "+files.length+" store"+(files.length===1?"":"s")+" in cartridges-stores.zip"+(miss.length?" ("+miss.join(", ")+" could not be reached)":"")+".",0)}}
else if(a==="defcheck"){msg="";msg2="";const pr=CT.sync(true,refresh);render();await pr;render()}
else if(a==="rmpack"){if(confirm==="p"+k){confirm=null;await CT.rmPack(k);toast("Pack removed.");render()}else{arm("p"+k);render()}}
else if(a==="addurl"){const n=main.querySelector("#ctn").value.trim();let u=main.querySelector("#ctu").value.trim();if(u&&!/^[a-z][a-z0-9+.-]*:\/\//i.test(u))u="https://"+u;let ok=false;try{const x=new URL(u);ok=x.protocol==="https:"||x.protocol==="http:"}catch(er){}
if(!ok){toast("That does not look like a web address.",1);return}const id="u"+Date.now().toString(36);CT.S.urls.push({id,name:n||CT.hostOf(u),url:u});CT.S.inst.push(id);CT.save();toast("Added to My cartridges.");view="shelf";render()}
else if(a==="dellink"){CT.S.urls=CT.S.urls.filter(u=>u.id!==k);CT.S.inst=CT.S.inst.filter(x=>x!==k);CT.save();render()}});
win.openArg=async a=>{if(typeof a==="string"){const n=V.get(a);if(n&&!n.dir){try{await CT.addPack(await V.read(n,"text"),n.name);view="store";render()}catch(e){}}}};
const refresh=()=>{ready=true;if(view==="store"&&document.activeElement&&document.activeElement.id==="ctq")paintStore();else render()};
render();(CT.ready||(CT.ready=CT.init())).then(async()=>{const first=!CT.packs.some(p=>p.id===CT.DEF);if(first)main.innerHTML='
Getting the default games\u2026
';else{ready=true;if(view==="shelf"&&!CT.S.inst.length)view=CT.meta.length?"store":"packs";render()}
let landed=false;const land=()=>{if(!landed){landed=true;ready=true;if(first&&view==="shelf"&&!CT.S.inst.length)view=CT.meta.length?"store":"packs"}refresh()};
await CT.sync(false,land);land()})}});
/* a game in a window of its own (opened with the New window button in Cartridges) */
defApp("cartgame",{name:"Game",icon:"cart",cat:"Games",w:900,h:640,hidden:true,desc:"a Cartridges game in its own window",
init(win,b,arg){
b.style.position="relative";const box=h("div",{style:"position:absolute;inset:0;display:flex;flex-direction:column;background:var(--bg,#000)"});box.dataset.fsx="dbl";box.setAttribute("data-fsx-bar","");
const fr=h("iframe",{style:"flex:1;border:0;width:100%;background:#fff;min-height:0",allow:"fullscreen; autoplay; clipboard-write; gamepad",allowfullscreen:""});
const pt=h("b",{style:"flex:1;min-width:90px"}),prel=h("button",{class:"btn sm"},"Restart"),pfull=h("button",{class:"btn sm"},"Full screen"),bar=h("div",{style:"display:flex;gap:8px;align-items:center;padding:6px 10px;border-bottom:1px solid var(--bd);flex:none;flex-wrap:wrap"},pt,h("span",{class:"dim",style:"font-size:12px"},"progress saves by itself"),prel,pfull);
box.append(bar,fr);b.append(box);let g=null;
const fsEl=()=>document.fullscreenElement||document.webkitFullscreenElement,fsLabel=()=>{pfull.textContent=fsEl()===box?"Exit full screen":"Full screen"};
const fsOff=()=>{try{if(fsEl()===box)(document.exitFullscreen||document.webkitExitFullscreen).call(document)}catch(e){}};
pfull.onclick=()=>{try{if(fsEl()===box)fsOff();else(box.requestFullscreen||box.webkitRequestFullscreen).call(box)}catch(e){toast("Full screen is not available here.",1)}};
document.addEventListener("fullscreenchange",fsLabel);document.addEventListener("webkitfullscreenchange",fsLabel);
const start=async()=>{if(!g)return;await CT.mount(fr,g)};prel.onclick=start;
(CT.ready||(CT.ready=CT.init())).then(()=>{g=CT.find(typeof arg==="string"?arg:arg&&arg.id);
if(!g){b.innerHTML='
This game is not on your shelf any more. Close this window.
';return}
win.title=g.name;win.tt.textContent=g.name;OS.renderTasks();pt.textContent=g.name;start()});
win.onclose=async()=>{fsOff();try{fr.contentWindow.postMessage({tvc:"flush"},"*")}catch(e){}await new Promise(r=>setTimeout(r,220))};
win.on.close=()=>{document.removeEventListener("fullscreenchange",fsLabel);document.removeEventListener("webkitfullscreenchange",fsLabel);CT.dropRun(fr);CT.save()}}});
/* ===================== BACKUP HABIT: tray icon, honest change counting, rare reminders ===================== */
/* Only things you made count: Diary pages, files, tasks, calendar notes, sequencer patterns, Den themes, bookmarks, installed programs, game save.
Window positions, settings, themes you are wearing, history and reading places never trigger a reminder. */
const BKT={
hs(s){let x=5381;for(let i=0;i>>0).toString(36)+":"+s.length},
raw(k){try{return localStorage.getItem(k)}catch(e){return null}},
json(k,d){try{const v=JSON.parse(localStorage.getItem(k));return v==null?d:v}catch(e){return d}},
areas(){const A=[],add=(id,name,grp,n,sig)=>{if(n>0)A.push({id,name,grp,n,sig})};
const dy=BKT.json("tvos_diary",null);if(dy&&dy.e&&typeof dy.e==="object"){const ks=Object.keys(dy.e).filter(k=>{const v=dy.e[k];return v&&(typeof v==="string"?v.trim():JSON.stringify(v).length>4)});add("diary","Diary","settings",ks.length,BKT.hs(JSON.stringify(ks.map(k=>[k,dy.e[k]]))))}
const tk=BKT.json("tvos_tasks",[]);if(Array.isArray(tk))add("tasks","Tasks","settings",tk.length,BKT.hs(JSON.stringify(tk)));
const cl=BKT.json("tvos_cal",{});if(cl&&typeof cl==="object"){const ks=Object.keys(cl).filter(k=>cl[k]);add("cal","Calendar notes","settings",ks.length,BKT.hs(JSON.stringify(ks.map(k=>[k,cl[k]]))))}
const sq=BKT.raw("tvos_seq");if(sq)add("seq","Sequencer","settings",1,BKT.hs(sq));
const th=BKT.json("tvos_themes",null);if(th&&Array.isArray(th.saved))add("themes","Themes Den","settings",th.saved.length,BKT.hs(JSON.stringify(th.saved)));
const bm=BKT.json("tvos_bm",[]);if(Array.isArray(bm)){const u=bm.filter(x=>x&&x.u&&x.u!=="https://republicka.life");add("bm","Bookmarks","settings",u.length,BKT.hs(JSON.stringify(u)))}
const pg=BKT.json("tvos_apps",[]);if(Array.isArray(pg)&&pg.length){let s=BKT.raw("tvos_apps")||"";for(let i=0;i0||sph.tot.treat>0||sph.tot.win>0))add("sophia","Sophia","settings",sph.tot.pet+sph.tot.treat,BKT.hs(JSON.stringify([sph.on,sph.mode,sph.size,sph.snd,sph.tot])));
const ts=BKT.json("tvos_theseus",null);if(ts&&typeof ts==="object"){const sv=Array.isArray(ts.shelf)?ts.shelf:[],pr=ts.proj&&ts.proj.jar>0?1:0;if(sv.length||pr)add("theseus","Theseus","settings",sv.length||pr,BKT.hs(JSON.stringify([sv.map(e=>[e.id,e.nm,e.code||(e.json&&e.json.seed)]),pr?ts.proj.cur:0])))}
const ca=BKT.json("tvos_cartridges",null);if(ca&&typeof ca==="object"){const n=ca.saves&&typeof ca.saves==="object"?Object.keys(ca.saves).length:0;if(n>0||(Array.isArray(ca.urls)&&ca.urls.length))add("cartridges","Cartridges","settings",n||ca.urls.length,BKT.hs(JSON.stringify([ca.saves,ca.inst,ca.urls,ca.off])))}
const gm=BKT.raw("terminal_velocity_v3");if(gm)add("game","Game save","game",1,BKT.hs(gm));
return A},
st(){const snap=BKT.json("tvos_backup_snap",null),last=LS.get("tvos_backup_last",0),sg=(snap&&snap.sigs)||{},ft=snap?(snap.ft||0):0,as=BKT.areas(),ch=[];let files=0,all=0;
V.walk(V.user,n=>{if(!n.dir){all++;if(n.mt>ft)files++}});
for(const a of as)if(a.sig!==sg[a.id])ch.push(a);if(files)ch.push({id:"files",name:"Files",n:files,grp:"files"});
const has=as.length>0||all>0;let seen=LS.get("tvos_backup_seen",0);if(!last&&!seen&&has){seen=Date.now();LS.set("tvos_backup_seen",seen)}
const base=last||(snap&&snap.t)||seen||Date.now(),age=(Date.now()-base)/864e5;
return{ch,last,age,has,files,areas:ch.filter(a=>a.id!=="files").length}},
say(ch){return ch.map(a=>a.id==="files"?a.n+" file"+(a.n===1?"":"s"):a.name).join(", ")},
ago(s){return s.last?"Last backup "+(s.age<1?"today":Math.floor(s.age)+" day"+(Math.floor(s.age)===1?"":"s")+" ago")+".":"You have never made a backup."},
/* mark what is now safe in a backup */
mark(inc){inc=inc||{files:1,settings:1,game:1};const snap=BKT.json("tvos_backup_snap",null)||{ft:0,sigs:{}};snap.sigs=snap.sigs||{};for(const a of BKT.areas())if(inc[a.grp])snap.sigs[a.id]=a.sig;if(inc.files)snap.ft=Date.now();snap.t=Date.now();LS.set("tvos_backup_snap",snap);BKT.draw()},
level(s){if(!s.ch.length)return 0;return(s.last?s.age>=7:s.age>=2)?2:1},
draw(s){const el=document.getElementById("bkt");if(!el)return;s=s||BKT.st();const lv=BKT.level(s);el.querySelector(".dot")?.remove();
if(lv){el.append(h("i",{class:"dot",style:"background:var("+(lv===2?"--er":"--wn")+")"}))}
el.title=!s.has?"Backup: nothing to save yet":lv?"Backup: not in a backup yet: "+BKT.say(s.ch)+". "+BKT.ago(s):"Backup: everything is saved. "+BKT.ago(s)},
/* choose where to save first (so a cancel is a cancel), then pack and write. "sure" is true only when the browser confirmed the file was written. */
async make(inc,onProg){const d=new Date();let nm="TVOS-backup-"+MC.iso(d)+"_"+pad(d.getHours())+pad(d.getMinutes())+".zip",fh=null;
if(window.showSaveFilePicker){try{fh=await showSaveFilePicker({suggestedName:nm,types:[{description:"Backup ZIP",accept:{"application/zip":[".zip"]}}]})}catch(e){if(e&&e.name==="AbortError")return null;fh=null}}
const{blob,man}=await bkMake(inc,onProg);let sure=false;
if(fh){try{const w=await fh.createWritable();await w.write(blob);await w.close();sure=true;nm=fh.name||nm}catch(e){fh=null}}
if(!sure)download(nm,blob,"application/zip");
LS.set("tvos_backup_last",Date.now());BKT.mark(inc);return{nm,blob,man,sure}},
/* open a backup ZIP and prove every part of it can be read, without changing anything */
async verify(file){const out={ok:false,lines:[]};try{const z=await bkZipRead(file),mb=z.get("backup.json");if(!mb)throw new Error("no backup.json: this is not a Terminal Velocity OS backup");
const man=JSON.parse(new TextDecoder().decode(await bkBytes(mb)));if(man.format!==BK_FMT)throw new Error("unknown backup format");
let n=0,bad=[];for(const f of man.files||[]){if(f.dir)continue;const en=z.get("files"+f.p);if(!en){bad.push(f.p+" (missing)");continue}try{await bkBytes(en);n++}catch(e){bad.push(f.p+" (unreadable)")}}
let keys=0;const lb=z.get("localstorage.json");if(lb){const ls=JSON.parse(new TextDecoder().decode(await bkBytes(lb)));keys=Object.keys(ls).length}
out.lines.push("Made: "+(man.mc||man.created||"?")+" by build "+(man.build||"?"),"Files readable: "+n+(bad.length?" of "+(n+bad.length):""),"Settings and app data items readable: "+keys);
if(bad.length)out.lines.push("Problems: "+bad.slice(0,5).join(", ")+(bad.length>5?" and "+(bad.length-5)+" more":""));else out.ok=true}
catch(e){out.lines.push("This file cannot be restored: "+e.message)}
out.lines.push(out.ok?"This backup is good. Nothing was changed.":"Do not rely on this file.");return out},
async quick(){try{const r=await BKT.make({files:true,settings:true,game:true},null);if(!r)return toast("Backup cancelled. Nothing was saved.");
BKT.note((r.sure?"Saved ":"Download started: ")+r.nm+" ("+fmtBytes(r.blob.size)+")."+(r.sure?"":" Check that the file arrived.")+" Keep it in cloud storage (Google Drive, OneDrive or Dropbox) so it survives losing this device.",[["OK",()=>{}]])}catch(e){toast("Backup failed: "+e.message,1)}},
note(text,btns){const t=h("div",{class:"toast",style:"display:flex;flex-direction:column;gap:8px;pointer-events:auto"},h("div",{},text),h("div",{style:"display:flex;gap:6px;flex-wrap:wrap"},...btns.map(([n,f,pri])=>h("button",{class:"btn sm"+(pri?" pri":""),onclick:()=>{t.remove();f()}},n))));$("#toasts").append(t);return t},
menu(e){const s=BKT.st(),q=LS.get("tvos_backup_quiet",0),lv=BKT.level(s);BKT.draw(s);
ctxMenu(e.clientX,Math.max(10,e.clientY-170),[{t:!s.has?"Nothing to back up yet":lv?"Not backed up: "+BKT.say(s.ch):"Everything is backed up",dis:true},{t:BKT.ago(s),dis:true},"-",{t:"Back up now",ic:"dl",fn:()=>BKT.quick()},{t:"Backup options...",ic:"save",fn:()=>OS.open("backup")},{t:q?"Turn reminders on":"Turn reminders off",ic:"eye",fn:()=>{LS.set("tvos_backup_quiet",q?0:1);toast(q?"Backup reminders are on":"Backup reminders are off. The tray icon still shows the status.")}},{t:"Tip: keep backups in cloud storage",dis:true}])},
/* a reminder is rare: at most one a day, only for real work, and it can be snoozed or switched off */
tick(){if(document.hidden)return;const s=BKT.st();BKT.draw(s);if(!NEST&&s.has&&!LS.get("tvos_backup_intro",0)){if(!BKT.introUp){BKT.introUp=1;const done=()=>{LS.set("tvos_backup_intro",1);BKT.introUp=0};BKT.note("A note on your data: everything you make here is stored only in this browser, on this device. There is no account and no copy anywhere else. The disk icon in the tray backs it up in one click. This note stays until you close it.",[["Back up now",()=>{done();BKT.quick()},1],["Got it",done]])}return}if(NEST||LS.get("tvos_backup_quiet",0)||!s.ch.length)return;const now=Date.now();if(now=10||s.areas>=3,need=s.last?(s.age>=7||(s.age>=1&&big)):(s.age>=2);if(!need)return;LS.set("tvos_backup_toast",now);try{BKT.rem&&BKT.rem.remove()}catch(e){}
BKT.rem=BKT.note("Not in a backup yet: "+BKT.say(s.ch)+". "+BKT.ago(s)+" A backup kept in cloud storage (Google Drive, OneDrive or Dropbox) survives losing this device.",[["Back up now",()=>BKT.quick(),1],["Not now",()=>{LS.set("tvos_backup_snooze",Date.now()+3*864e5);toast("I will not ask again for 3 days")}],["Stop reminding me",()=>{LS.set("tvos_backup_quiet",1);toast("Reminders are off. You can turn them on from the tray icon.")}]])}
};
document.head.append(h("style",{},"#bkt{position:relative;display:inline-flex}#bkt .dot{position:absolute;right:-3px;top:-3px;width:8px;height:8px;border-radius:50%;border:1px solid var(--bg)}"));
setTimeout(BKT.tick,25000);setInterval(BKT.tick,120000);
/* ===================== BOOT ===================== */
const LOGO=`
████████╗███████╗██████╗ ███╗ ███╗██╗███╗ ██╗ █████╗ ██╗
╚══██╔══╝██╔════╝██╔══██╗████╗ ████║██║████╗ ██║██╔══██╗██║
██║ █████╗ ██████╔╝██╔████╔██║██║██╔██╗ ██║███████║██║
██║ ██╔══╝ ██╔══██╗██║╚██╔╝██║██║██║╚██╗██║██╔══██║██║
██║ ███████╗██║ ██║██║ ╚═╝ ██║██║██║ ╚████║██║ ██║███████╗
╚═╝ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝╚═╝ ╚═╝╚══════╝
V E L O C I T Y O S · one file · CC0 · Republicka`;
/* ===================== STARTUP LYRE: a few plucked strings, synthesised here (no audio files) =====================
Each string is a Karplus-Strong pluck: a burst of softened noise circulating in a short delay line that loses a little energy each lap,
which is how a real plucked string rings and fades. A small generated room (a convolver) adds the shimmer. Everything is computed on the
spot in a few milliseconds. Browsers only allow sound after the person has touched the page, so if sound is still locked when the desktop
appears, the chime waits up to 12 seconds for the first touch or key and then plays once; after that it lets the moment go. */
function lyreString(sr,f,secs,seed,dec,soft){soft=soft==null?.4:soft;const n=Math.floor(sr*secs),L=Math.max(2,Math.round(sr/f-.5)),buf=new Float32Array(n),d=new Float32Array(L);let r=seed>>>0||1;const rnd=()=>{r=(r*1664525+1013904223)>>>0;return r/2147483648-1};
let p=0;for(let i=0;ipk)pk=a}if(pk>0)for(let i=0;iac[bi])bi=i;let P=L-3+bi;if(bi>0&&bi>>0;d[i]=((r/2147483648)-1)*Math.pow(1-i/n,3.2)}}return b}
let lyreCtx=null;
function lyrePlay(ctx){const t0=ctx.currentTime+.06,sr=ctx.sampleRate;
/* D major, rising and settling: D4 A4 D5 F#5 A5, then a soft low D to close */
const seq=[[293.66,0,.9],[440,.2,.85],[587.33,.4,.8],[739.99,.62,.75],[880,.86,.7],[146.83,1.25,.55]];
const master=ctx.createGain();master.gain.value=0;master.connect(ctx.destination);
master.gain.setValueAtTime(0,t0);master.gain.linearRampToValueAtTime(.42,t0+.02);
const room=ctx.createConvolver();room.buffer=lyreRoom(ctx);const wet=ctx.createGain();wet.gain.value=.28;room.connect(wet);wet.connect(master);
const dry=ctx.createGain();dry.gain.value=.9;dry.connect(master);
seq.forEach(([f,at,v],i)=>{const b=ctx.createBuffer(1,Math.floor(sr*3),sr);const ls=lyreString(sr,f,3,0x9e37+i*131);b.copyToChannel(ls,0);
const s=ctx.createBufferSource();s.buffer=b;s.playbackRate.value=f/ls.fa;const g=ctx.createGain();g.gain.value=v;const pan=ctx.createStereoPanner?ctx.createStereoPanner():null;
if(pan){pan.pan.value=(i%2?.25:-.25)*(f>500?1:.5);s.connect(g);g.connect(pan);pan.connect(dry);pan.connect(room)}else{s.connect(g);g.connect(dry);g.connect(room)}
s.start(t0+at)});
master.gain.setValueAtTime(.42,t0+3.4);master.gain.linearRampToValueAtTime(0,t0+4.2);
setTimeout(()=>{try{master.disconnect()}catch(e){}},5200)}
function startupChime(force){
try{if(!force&&(NEST||SET.startupSound===false))return;
const AC=window.AudioContext||window.webkitAudioContext;if(!AC)return;
if(!lyreCtx)lyreCtx=new AC();const ctx=lyreCtx;
const go=()=>{try{lyrePlay(ctx)}catch(e){}};
if(ctx.state==="running"){go();return}
const r=ctx.resume();if(r&&r.then)r.then(()=>{if(ctx.state==="running")go()},()=>{});
setTimeout(()=>{if(ctx.state==="running")return;/* still locked: wait for the first touch or key, but only briefly */
const t=performance.now(),once=()=>{removeEventListener("pointerdown",once,true);removeEventListener("keydown",once,true);if(performance.now()-t>12000)return;ctx.resume().then(()=>{if(ctx.state==="running"&&SET.startupSound!==false)go()},()=>{})};
addEventListener("pointerdown",once,true);addEventListener("keydown",once,true);setTimeout(()=>{removeEventListener("pointerdown",once,true);removeEventListener("keydown",once,true)},12000)},150)}catch(e){}}
async function boot(){
const bl=$("#bl"),pb=$("#bp");{const dd=h("div",{id:"bded"},"Welcome Home Ivory!");bl.parentNode.insertBefore(dd,bl)}const lg=$("#blogo");{const NS="http://www.w3.org/2000/svg",L=LOGO.split("\n").filter(x=>x.length),cw=10,lh=17,W=Math.max(...L.map(x=>x.length))*cw,sv=document.createElementNS(NS,"svg");
sv.setAttribute("viewBox","0 0 "+W+" "+(L.length*lh+4));sv.setAttribute("preserveAspectRatio","xMinYMid meet");sv.style.cssText="display:block;width:100%;max-width:"+Math.round(W*0.74)+"px;height:auto;overflow:visible";
L.forEach((ln,i)=>{const t=document.createElementNS(NS,"text"),xs=[];let cs="";for(let k=0;k{skip=true};addEventListener("keydown",sk);addEventListener("pointerdown",sk);
const sp=NEST?0:({instant:0,fast:.3,normal:1,slow:2})[SET.bootSpeed||"normal"]??1;
const emit=(msg,cls)=>{if(!SET.verbose&&!/ok|er|wn/.test(cls||"")&&!/^(Terminal|desktop)/.test(msg))return;const ts=((performance.now()-t0)/1000).toFixed(mobB?3:6).padStart(mobB?7:10);bl.append(h("div",{class:cls||""},"["+ts+"] "+msg));bl.scrollTop=bl.scrollHeight;while(bl.children.length>120)bl.firstChild.remove()};
const Q=[];let pumping=0;
const pump=async()=>{if(pumping)return;pumping=1;while(Q.length){if(skip){while(Q.length)emit(...Q.shift());break}emit(...Q.shift());await sleep((30+Math.random()*60)*sp)}pumping=0};
const line=(msg,cls)=>{if(skip||!sp){emit(msg,cls);return}Q.push([msg,cls]);pump()};
const drain=async()=>{while((Q.length||pumping)&&!skip)await sleep(15)};
const step=async(msg,fn,pct,cls)=>{line(msg,cls);let r;try{r=fn?await fn():null}catch(e){line(" FAILED: "+(e&&e.message||e),"er");console.error(e)}await drain();if(pct!=null)pb.style.width=pct+"%";if(!skip&&sp&&SET.verbose)await sleep((120+Math.random()*240)*sp);return r};
const ok=(n,v)=>line(" [ OK ] "+n+(v?" "+v:""),"ok"),no=(n,v)=>line(" [FAIL] "+n+(v?" "+v:""),"wn");
line("Terminal Velocity OS "+OS.ver+" - cold boot","");
line(" "+(navigator.userAgent.length>90?navigator.userAgent.slice(0,90)+"...":navigator.userAgent),"dm");
line(" display "+innerWidth+"x"+innerHeight+" @"+(devicePixelRatio||1)+"x, "+(navigator.hardwareConcurrency||"?")+" cores, "+(navigator.language||"?")+", "+(Intl.DateTimeFormat().resolvedOptions().timeZone||"?"),"dm");
line(" calendar: "+(MC.on()?"Mythocratic Calendar - today is "+MC.dual(new Date()):"Gregorian ("+MC.dual(new Date())+")"),"dm");
line(" page origin: "+(location.protocol==="file:"?"file:// (opened from disk)":location.origin),"dm");
await step("probing browser features...",async()=>{const F=[["indexedDB",!!window.indexedDB],["localStorage",(()=>{try{localStorage.setItem("_t","1");localStorage.removeItem("_t");return true}catch(e){return false}})()],["fetch",!!window.fetch],["Blob + download",!!window.Blob&&"download"in HTMLAnchorElement.prototype],["canvas 2D",!!document.createElement("canvas").getContext],["Web Audio",!!(window.AudioContext||window.webkitAudioContext)],["crypto.subtle",!!(window.crypto&&crypto.subtle)],["MediaRecorder",!!window.MediaRecorder],["File System Access (mount folders)",!!window.showDirectoryPicker],["clipboard",!!navigator.clipboard],["Pointer Events",!!window.PointerEvent]];for(const[n,v]of F){v?ok(n):no(n,"(feature will be limited)");if(!skip&&SET.verbose)await sleep(6)}},8);
await step("storage: requesting persistence and measuring quota...",async()=>{try{const p=navigator.storage&&navigator.storage.persist?await navigator.storage.persist():false;const e=await navigator.storage.estimate();ok("persistent storage "+(p?"granted":"not granted (normal for most browsers)"),"· used "+fmtBytes(e.usage)+" of "+fmtBytes(e.quota))}catch(e){no("storage estimate","unavailable")}},14);
await step("settings: loading tvos_settings...",async()=>{ok("theme "+THEMES[SET.theme].n,"· wallpaper "+SET.wall+" · verbose "+(SET.verbose?"on":"off"))},18);
await step("graphics: "+THEME_ORDER.length+" X environments registered, "+Object.keys(IP).length+" vector icons, "+WALLS.length+" canvas wallpapers (no image files)",()=>{sizeWall();setWall()},24);
await step("filesystem: opening IndexedDB 'tvos'...",async()=>{try{await DB.open();ok("database open")}catch(e){no("IndexedDB",e.message+" - /home will not persist")}},30);
await step("filesystem: restoring /home/user...",async()=>{const n=await V.loadHome();V.mkdirp("/home/user/Documents");V.mkdirp("/home/user/Media");ok("/home/user",n+" stored entr"+(n===1?"y":"ies"))},38);
await step("filesystem: mounting /system /tmp /mnt /archive...",()=>{initSys();ok("tree mounted","(/archive read-only, /home/user writable, /tmp in memory)")},44);
const got=await step("archive: looking for manifest.json (your own, or the Republicka archive)...",()=>loadManifest(line),70);
if(got)ok("archive mounted",MAN.files.toLocaleString()+" files, "+fmtBytes(MAN.size)+" from "+MAN.src);else no("archive not mounted","- open Settings > Archive to load your own manifest.json");
pb.style.width="72%";
await step("game: verifying embedded Terminal Velocity...",()=>{const el=document.getElementById("tvgame");const len=el?el.textContent.length:0;if(len>1000&&/terminal_velocity_v3/.test(el.textContent))ok("Terminal Velocity",fmtBytes(len)+" embedded, sandboxed in its own window");else no("embedded game missing")},78);
await step("game: checking for an existing save in this browser...",()=>{try{const s=localStorage.getItem("terminal_velocity_v3");s?ok("existing Terminal Velocity save found",fmtBytes(s.length)+" - will be continued"):line(" no save yet - a fresh game will start","dm")}catch(e){no("save check",e.message)}},82);
await step("compositor: window manager, taskbar, tray, start menu, spotlight...",()=>{buildTray();buildStart();spBind();buildDesk();OS.renderTasks();try{sophiaInit()}catch(e){console.error(e)}const m=MAN.json;const a=$("#arc");a&&(a.textContent=m?"archive: "+MAN.files.toLocaleString()+" files":"archive: none")},90);
await step("apps: registered "+Object.keys(OS.apps).length+" ("+Object.values(OS.apps).filter(a=>!a.hidden).map(a=>a.name).join(", ")+")",null,94);
await step("ship: counting planks...",()=>{OS.shipUp=1;ok("rebuilt from its own text","windows, hearth, engine, archive")},96);
await step("notes: checking for unsaved drafts...",async()=>{const s=await DB.get("np_session");s&&s.tabs&&s.tabs.length?ok(s.tabs.length+" unsaved note(s) will be restored when Notepad opens"):line(" none","dm")},97);
const nog=/[?&]nogame\b/.test(location.search),sess=sessLoad(),doRestore=!NEST&&!nog&&SET.restoreSession!==false&&sess;
await step("session: "+(doRestore?(sess.w.length?"restoring "+sess.w.length+" window"+(sess.w.length===1?"":"s")+" ("+sess.w.map(o=>(OS.apps[o.a]&&OS.apps[o.a].name)||o.a).join(", ")+")":"nothing was open - starting fresh"):nog?"test mode, no restore":sess?"restore is off in Settings":"first boot - Terminal Velocity will start minimised"),null,99);
line("desktop ready in "+Math.round(performance.now()-t0)+" ms","ok");pb.style.width="100%";
await drain();if(!skip&&sp&&SET.verbose)await sleep(900*sp);
removeEventListener("keydown",sk);removeEventListener("pointerdown",sk);
const bt=$("#boot");bt.style.transition="opacity .35s";bt.style.opacity="0";await sleep(skip?0:350);bt.remove();
startupChime();
if(doRestore)sessRestore(sess);
else if(NEST){const qw=OS.open("quine");qw&&OS.minimize(qw)}
else{const returning=localStorage.getItem("tvos_session")!==null||LS.get("tvos_welcomed",false);if(!returning){OS.open("help");LS.set("tvos_welcomed",true)}else if(SET.startApp&&OS.apps[SET.startApp]&&!nog)OS.open(SET.startApp)}
sessStart()}
/* ===================== MAIN ===================== */
(function(){
applyTheme(SET.theme);
window.addEventListener("error",e=>{console.error("TVOS error:",e.message)});
boot().catch(e=>{console.error(e);const b=$("#boot");b&&b.remove();try{buildTray();buildStart();spBind();buildDesk()}catch(_){}});
})();