/* WidgetWorkbench CheerpJ 4.3 runner. * CheerpJ Core has no documented runJNLP(url) API: parse the manifest and run JAR(s). * Deliberately SAME-ORIGIN only. Do not turn this into an open server-side URL proxy. */ const screen=document.getElementById('display'); const notice=document.getElementById('state'); const BRIDGE_JAR='/app/backend/hmi/cheerpj/workplace-resize-bridge-v2.jar'; const WORKPLACE_MANIFEST='/backend/api/hmi/v1/cheerpj/workplace/manifest.jnlp'; let busy=false; const trusted=(raw,base=location.href)=>{ const u=new URL(raw,base); if(u.origin!==location.origin)throw Error('JNLP und alle JARs müssen von derselben Origin wie WidgetWorkbench kommen.'); if(!['http:','https:'].includes(u.protocol))throw Error('Nur HTTP und HTTPS werden unterstützt.'); if(u.username||u.password||u.hash)throw Error('URL mit Zugangsdaten oder Fragment nicht unterstützt.'); return u; }; function readManifest(xml,jnlpUrl){ if(xml.length>1024*1024||/g.hasAttribute('os')||g.hasAttribute('arch')); const jars=groups.filter(g=>!g.hasAttribute('os')&&!g.hasAttribute('arch')) .flatMap(g=>Array.from(g.getElementsByTagName('jar'))); if(!jars.length||jars.length>256)throw Error('Keine JAR-Dateien oder mehr als 256 JARs.'); const jvm=groups.flatMap(g=>Array.from(g.getElementsByTagName('java')))[0]; const required=jvm?.getAttribute('version')?.match(/^(8|11|17)/)?.[1]; const warnings=[]; if(platformGroups.length)warnings.push('Plattformspezifische/native JNLP-Ressourcen werden nicht geladen.'); if(root.getElementsByTagName('nativelib').length)warnings.push('Native RXTX-/JNI-Treiber laufen nicht im Browser.'); if(jvm?.getAttribute('java-vm-args'))warnings.push('JNLP-JVM-Optionen werden nicht vollständig übernommen.'); const base=root.getAttribute('codebase')?trusted(root.getAttribute('codebase'),jnlpUrl):new URL('.',jnlpUrl); const paths=jars.map(j=>{ const href=j.getAttribute('href');if(!href)throw Error('JAR ohne href.'); const u=trusted(href,base.href.endsWith('/')?base.href:base.href+'/'); if(!u.pathname.toLowerCase().endsWith('.jar'))throw Error('Nur direkte .jar-Ressourcen unterstützt.'); if(u.search)throw Error('Signierte JAR-URLs mit Queryparametern benötigen eine besondere Integration.'); return '/app'+u.pathname; }); const main=app.getAttribute('main-class')||''; if(main&&!/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/.test(main))throw Error('Ungültige Java-Main-Klasse.'); const args=Array.from(app.childNodes).filter(e=>e.nodeType===1&&e.localName==='argument').map(e=>e.textContent||''); if(args.length>32||args.some(a=>a.length>2048))throw Error('Zu viele/lange JNLP-Argumente.'); if(!main&&paths.length>1)throw Error('JNLP mit mehreren JARs benötigt main-class für einen sicheren Klassenpfad.'); return {main,paths,args,required,warnings}; } /** Load a separate, unsigned iTAC-independent helper in the same CheerpJ runtime. * Only the immutable, locally packaged Bridge JAR is loaded; no vendor JAR is modified. * When the JVM has not created MesSuiteFrame yet, retry for a bounded startup window. */ async function attachWorkplaceResize(container, classPath, mode) { if (typeof window.cheerpjRunLibrary !== 'function') throw Error('CheerpJ Library Mode für die ResizeBridge nicht verfügbar.'); const lib=await window.cheerpjRunLibrary(classPath); const bridge=await lib.com.widgetworkbench.cheerpj.WorkplaceResizeBridge; let closed=false, inFlight=false, pending=false, lastSize='', retry=0; let retryTimer=null; const desired=()=>{ if(mode==='original')return [1280,1024]; const size=container.getBoundingClientRect(); return [Math.max(200,Math.floor(size.width)),Math.max(150,Math.floor(size.height))]; }; async function update(){ if(closed||inFlight){pending=true;return;} const [width,height]=desired(), size=width+'x'+height; if(size===lastSize && retry>=24)return; inFlight=true; try{ const found=await bridge.resize(width,height); // The frame appears asynchronously while cheerpjRunMain is active. if(Number(found)>0){lastSize=size;retry=24;} }catch(error){ console.warn('Workplace resize bridge:',error); retry=24; }finally{ inFlight=false; if(pending&&!closed){pending=false;void update();} } } const observer=typeof ResizeObserver!=='undefined' ? new ResizeObserver(()=>{retry=24;void update();}) : null; observer?.observe(container); // Retry initialization until first Workplace JFrame is shown, stop after 24 attempts. retryTimer=setInterval(()=>{ if(closed||retry>=24){clearInterval(retryTimer);return;} retry++; void update(); },750); void update(); return {stop(){closed=true;observer?.disconnect();if(retryTimer)clearInterval(retryTimer);},refresh:()=>update()}; } function status(requestId,state,message){ const text=String(message).slice(0,350); notice.textContent=text;notice.className=state==='error'?'fail':''; parent.postMessage({type:'hmi-cheerpj-state',requestId,state,message:text},location.origin); } async function start(e,data){ const id=data.requestId; try { if(busy)throw Error('Eine Java-Anwendung läuft bereits in diesem Frame.'); busy=true; const url=trusted(data.jnlpUrl); const version=Number(data.javaVersion); if(![8,11,17].includes(version))throw Error('Ungültige Java-Version.'); const isWorkplace=data.workplace===true && url.pathname===WORKPLACE_MANIFEST; const displayMode=data.displayMode==='original'?'original':'fit'; status(id,'loading','JNLP wird gelesen …'); const r=await fetch(url.href,{credentials:'same-origin',redirect:'follow',cache:'no-store'}); if(!r.ok||!r.url||trusted(r.url).origin!==location.origin)throw Error('JNLP nicht abrufbar (HTTP '+r.status+').'); const xml=await r.text(); const manifest=readManifest(xml,url.href); if(manifest.required && Number(manifest.required)!==version)throw Error('JNLP erfordert Java '+manifest.required+', Widget ist auf Java '+version+' eingestellt.'); status(id,'loading',manifest.paths.length+' Java-Bibliotheken · '+(manifest.warnings.join(' ')||'CheerpJ wird geladen …')); if(typeof window.cheerpjInit!=='function'){ await new Promise((resolve,reject)=>{let count=0;const timer=setInterval(()=>{if(typeof window.cheerpjInit==='function'){clearInterval(timer);resolve();}else if(++count>150){clearInterval(timer);reject(Error('CheerpJ CDN nicht erreichbar oder durch CSP blockiert.'));}},100);}); } await window.cheerpjInit({version,status:'none'}); if(isWorkplace && displayMode==='original'){ document.body.classList.add('cheerpj-original-mode'); window.cheerpjCreateDisplay(1280,1024,screen); }else{ window.cheerpjCreateDisplay(-1,-1,screen); } let resizeBridge=null; let cp=manifest.paths.join(':'); if(isWorkplace){ cp+=':'+BRIDGE_JAR; try{ resizeBridge=await attachWorkplaceResize(screen,cp,displayMode); }catch(error){ console.warn('Optional Workplace ResizeBridge unavailable:',error); manifest.warnings.push('ResizeBridge konnte nicht gestartet werden; Anzeige bleibt nutzbar, interne Größe möglicherweise fix.'); } } status(id,'running','Java-Anwendungsstart wird versucht. '+manifest.warnings.join(' ')); try{ const exitCode=manifest.main ? await window.cheerpjRunMain(manifest.main,cp,...manifest.args) : await window.cheerpjRunJar(manifest.paths[0],...manifest.args); status(id,'finished','Anwendung beendet (Exit-Code '+exitCode+').'); }finally{resizeBridge?.stop();} }catch(error){status(id,'error',error instanceof Error?error.message:String(error));} } window.addEventListener('message',event=>{ if(event.source!==window.parent||event.origin!==location.origin)return; const data=event.data; if(!data||data.type!=='hmi-cheerpj-launch'||typeof data.requestId!=='string'||data.requestId.length>150)return; void start(event,data); });