ploxion-logisim/app.blade.php

1618 lines
156 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

{{-- SPDX-License-Identifier: GPL-3.0-or-later — l'interface d'un portage de Logisim-evolution (GPL-3.0, © ses auteurs : symboles,
propriétés, comportement) ; ce fichier est sous GPL-3.0-or-later, le reste du repo reste MIT.
PL0XION logisim ⊼ (RS-7 30.10 : « un ploxion vhdl à la logisim, et que ça me donne aussi des .circ », « je veux pouvoir faire du
logisim directement dans le xerboxion, dans le labo », « upload chaque circuit dans ma propre bibliothèque », « le truc d'auteur et
de signature », « pouvoir les partager », « un visualiseur pdf à côté » pour les labos de la HEIG). La quête du bion du jour.
✥ éditer : poser, déplacer, câbler (tire depuis un port ou un bout de fil), R tourne, Suppr efface, Ctrl+Z / Ctrl+Y
☝ toucher : basculer les broches d'entrée, les boutons ; ▶ l'horloge
▦ table de vérité · ⊞ Karnaugh (SOP / POS minimales) · ≡ VHDL · ◧ l'énoncé PDF à côté (gardé avec le projet)
□ bloc vide : une interface (entrées, sorties) + sa table à remplir ; « construire » en fait des portes
⧉ ma bibliothèque (mes bions VHDL, dans mon compte) ; ouvrir / enregistrer des .circ de Logisim-evolution, auteur et
signature gardés (owner, date, uuid ; « integrity » n'est jamais inventée).
Le moteur est le bion jOSCircuit (partials/_circuit_bion, tests : node bin/verify-circuit.mjs). Desktop d'abord ; au téléphone,
les panneaux deviennent des feuilles et les boutons sont en bas. Rien ne tourne en fond : l'horloge seulement sur ▶ et visible. --}}
@include('partials._circuit_bion')
<style>
.lgs{--fond:#0b0f14;--panneau:#10161e;--ligne:#1f2a36;--texte:#dfe8f2;--doux:#8b9bb0;--acc:#3fe0d0;--un:#3df07a;--zero:#1f6b3a;--x:#4c8dff;--e:#ff5050;--bus:#c9d4e0;
position:absolute;inset:0;display:grid;grid-template-columns:210px 1fr 230px;grid-template-rows:auto minmax(0,1fr) fit-content(42%);background:var(--fond);color:var(--texte);font:13px/1.35 var(--xr-font-ui,ui-sans-serif,system-ui);overflow:hidden}
.lgs.sans-g{grid-template-columns:0 1fr 230px}.lgs.sans-d{grid-template-columns:210px 1fr 0}.lgs.sans-g.sans-d{grid-template-columns:0 1fr 0}
.lgs__top{grid-column:1/-1;display:flex;align-items:center;gap:4px;padding:5px 8px;border-bottom:1px solid var(--ligne);background:var(--panneau);flex-wrap:wrap;min-width:0}
.lgs__top b{font-size:.95rem;margin-right:4px;white-space:nowrap}
.lgs__nom{background:transparent;border:1px solid transparent;color:var(--texte);font:inherit;padding:3px 5px;border-radius:5px;width:150px}
.lgs__nom:hover,.lgs__nom:focus{border-color:var(--ligne);outline:none}
.lgs button{font:inherit;color:var(--texte);background:#16202b;border:1px solid var(--ligne);border-radius:6px;padding:4px 8px;cursor:pointer;white-space:nowrap}
.lgs button:hover{border-color:#36506a}.lgs button.on{background:var(--acc);color:#05201d;border-color:var(--acc)}
.lgs button:disabled{opacity:.4;cursor:default}
.lgs__sep{width:1px;height:20px;background:var(--ligne);margin:0 3px}
.lgs__g,.lgs__d{overflow-y:auto;overflow-x:hidden;border-right:1px solid var(--ligne);background:var(--panneau);min-width:0}
.lgs__d{border-right:0;border-left:1px solid var(--ligne)}
.lgs__h{font-size:.66rem;letter-spacing:.08em;text-transform:uppercase;color:var(--doux);padding:9px 10px 4px;display:flex;align-items:center;gap:6px}
.lgs__h button{margin-left:auto;padding:1px 6px;font-size:.72rem}
.lgs__it{display:flex;align-items:center;gap:7px;padding:4px 10px;cursor:pointer;border-left:2px solid transparent;user-select:none;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.lgs__it:hover{background:#151e28}.lgs__it.on{border-left-color:var(--acc);background:#132029}
.lgs__it i{font-style:normal;width:26px;flex:0 0 26px;text-align:center;color:var(--acc);font-family:ui-monospace,monospace;font-size:.75rem}
.lgs__it small{margin-left:auto;color:var(--doux);font-size:.68rem}
.lgs__cat{padding:6px 10px 2px;color:var(--doux);font-size:.72rem;cursor:pointer;user-select:none}
.lgs__centre{position:relative;min-width:0;min-height:0;display:flex}
.lgs__plan{flex:1;position:relative;min-width:0;overflow:hidden;background:var(--toile);touch-action:none}
/* la toile de Logisim : blanche, traits noirs ; valeurs : 1 = rgb(0,210,0), 0 = rgb(0,100,0), inconnu = rgb(40,40,255), erreur = rgb(192,0,0), bus = noir */
.lgs{--toile:#fff;--trait:#000;--corps:#fff;--grille:#bbb;--etiq:#333;--doux2:#555;--un:#00d200;--zero:#006400;--x:#2828ff;--e:#c00000;--bus:#000;--selc:#c06000;--bandeau:#000;--bandeau-t:#fff;--label:#0000ff}
.lgs.toile-sombre{--toile:#0d131a;--trait:#c9d4e0;--corps:#16202b;--grille:#2a3a4c;--etiq:#9fb3c8;--doux2:#7f93a8;--un:#3df07a;--zero:#1f6b3a;--x:#4c8dff;--e:#ff5050;--bus:#c9d4e0;--selc:#3fe0d0;--bandeau:#24364a;--bandeau-t:#e6f0fa;--label:#6cb6ff}
.lgs__plan svg{position:absolute;inset:0;width:100%;height:100%;display:block}
.lgs__pdf{flex:0 0 44%;display:none;flex-direction:column;border-left:1px solid var(--ligne);background:#1a1d22;min-width:0}
.lgs.avec-pdf .lgs__pdf{display:flex}
.lgs__pdf header{display:flex;align-items:center;gap:6px;padding:5px 8px;border-bottom:1px solid var(--ligne);background:var(--panneau)}
.lgs__pdf header span{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--doux)}
.lgs__pdf object,.lgs__pdf iframe{flex:1;width:100%;border:0;background:#2a2d33}
.lgs__pdfvide{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px;padding:20px;text-align:center;color:var(--doux)}
.lgs__bas{grid-column:1/-1;border-top:1px solid var(--ligne);background:var(--panneau);display:flex;flex-direction:column;min-height:0;overflow:hidden}
.lgs__onglets{display:flex;gap:3px;padding:4px 8px;align-items:center;flex-wrap:wrap}
.lgs__onglets .r{margin-left:auto;color:var(--doux);font-size:.72rem}
.lgs__corps{overflow:auto;padding:6px 10px 10px;min-height:0}
.lgs.ferme .lgs__corps{display:none}
.lgs table.tv{border-collapse:collapse;font:12px ui-monospace,monospace}
.lgs table.tv th,.lgs table.tv td{border:1px solid var(--ligne);padding:2px 7px;text-align:center}
.lgs table.tv th{color:var(--doux);font-weight:500;position:sticky;top:0;background:var(--panneau)}
.lgs table.tv td.s{color:#ffd27a;cursor:default}.lgs table.tv td.s.ed{cursor:pointer}.lgs table.tv td.s.ed:hover{background:#1c2836}
.lgs table.tv th.sep,.lgs table.tv td.sep{border-left:2px solid #36506a}
.lgs .km{display:inline-block;margin:0 14px 10px 0;vertical-align:top}
.lgs .km table{border-collapse:collapse;font:12px ui-monospace,monospace}
.lgs .km td,.lgs .km th{width:30px;height:28px;text-align:center;border:1px solid var(--ligne)}
.lgs .km th{color:var(--doux);font-weight:500;border:0}
.lgs .km td{position:relative}
.lgs .imp{display:inline-flex;align-items:center;gap:5px;margin:2px 8px 2px 0;font:12px ui-monospace,monospace;cursor:default}
.lgs .imp b{width:12px;height:12px;border-radius:3px;display:inline-block}
.lgs pre{margin:0;font:12px/1.45 ui-monospace,monospace;white-space:pre;color:#cfe3f5}
.lgs__attrs label{display:flex;align-items:center;gap:6px;padding:3px 10px;font-size:.78rem}
.lgs__attrs label span{width:96px;color:var(--doux);flex:0 0 auto;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.lgs input[type=checkbox]{flex:0 0 auto !important;width:16px;height:16px;padding:0;accent-color:var(--acc)}
.lgs__attrs input,.lgs__attrs select,.lgs input.ch,.lgs select.ch{flex:1;min-width:0;background:#0d131a;color:var(--texte);border:1px solid var(--ligne);border-radius:5px;padding:3px 5px;font:inherit}
.lgs__note{padding:6px 10px;color:var(--doux);font-size:.74rem}
.lgs__note code{color:#cfe3f5}
.lgs__aide{position:absolute;left:10px;bottom:10px;color:var(--doux);font-size:.72rem;pointer-events:none;background:rgba(11,15,20,.8);padding:4px 8px;border-radius:6px;max-width:70%}
.lgs__toast{position:absolute;left:50%;top:56px;transform:translateX(-50%);background:#16303a;border:1px solid var(--acc);padding:6px 12px;border-radius:8px;z-index:5;max-width:80%}
.lgs__modal{position:absolute;inset:0;background:rgba(0,0,0,.55);display:flex;align-items:center;justify-content:center;z-index:6}
.lgs__modal > div{background:var(--panneau);border:1px solid var(--ligne);border-radius:10px;padding:14px;width:min(420px,92%);max-height:86%;overflow:auto}
.lgs__modal h3{margin:0 0 8px;font-size:1rem}.lgs__modal label{display:block;margin:8px 0 3px;color:var(--doux);font-size:.78rem}
.lgs__modal input,.lgs__modal textarea{width:100%;box-sizing:border-box;background:#0d131a;color:var(--texte);border:1px solid var(--ligne);border-radius:6px;padding:6px;font:inherit}
.lgs__modal .act{display:flex;gap:6px;justify-content:flex-end;margin-top:12px}
.lgs__mob{display:none}
.lgs button:focus-visible,.lgs input:focus-visible,.lgs select:focus-visible,.lgs__it:focus-visible{outline:2px solid var(--acc);outline-offset:2px}
.lgs__menu{position:absolute;z-index:7;min-width:200px;background:var(--panneau);border:1px solid #36506a;border-radius:10px;box-shadow:0 10px 30px rgba(0,0,0,.55);padding:4px;display:flex;flex-direction:column}
.lgs__menu b{padding:6px 10px 4px;color:var(--doux);font-size:.72rem;font-weight:500}
.lgs__menu button{text-align:left;border:0;background:transparent;padding:10px 12px;border-radius:7px;font-size:.92rem;min-height:44px}
.lgs__menu button:hover,.lgs__menu button:focus-visible{background:#1c2836}
.lgs__menu button.danger{color:#ff8a8a}
.lgs__ariane{position:absolute;left:8px;top:8px;display:flex;align-items:center;gap:4px;flex-wrap:wrap;z-index:3;background:rgba(16,22,30,.92);padding:4px 6px;border-radius:8px;border:1px solid var(--ligne)}
.lgs__ariane span{color:var(--doux)}.lgs__ariane small{color:var(--doux);margin-left:6px;font-size:.7rem}
.lgs__arbre .lgs__it{padding-top:2px;padding-bottom:2px;font-size:.8rem}
.lgs__lab{position:absolute;z-index:5;font:13px ui-sans-serif,system-ui;padding:3px 6px;border:2px solid var(--acc);border-radius:5px;background:#fff;color:#000;min-width:90px}
.lgs__bandeau{padding:5px 8px;margin-bottom:6px;border-radius:6px;background:#2a2410;color:#ffd27a;font-size:.78rem}
.lgs svg text{font-family:ui-sans-serif,system-ui;pointer-events:none}
@media (max-width: 760px){
.lgs{grid-template-columns:1fr !important;grid-template-rows:auto minmax(0,1fr) fit-content(50%) auto}
.lgs__top .bureau{display:none}
.lgs__top{flex-wrap:nowrap;overflow-x:auto;-webkit-overflow-scrolling:touch;scrollbar-width:none;padding:6px}
.lgs__top::-webkit-scrollbar{display:none}
.lgs__top b{display:none}.lgs__nom{width:120px;flex:0 0 auto}.lgs__sep{display:none}
.lgs button{min-height:44px;min-width:44px;font-size:.95rem}
.lgs__it{padding:10px 12px;font-size:.95rem}.lgs__cat{padding:10px 12px}
.lgs__attrs label{padding:6px 12px;font-size:.92rem}.lgs__attrs input,.lgs__attrs select{min-height:38px;font-size:16px}
.lgs table.tv td,.lgs table.tv th{padding:8px 12px;font-size:15px}
.lgs__g,.lgs__d{position:absolute;left:0;right:0;bottom:52px;max-height:62%;z-index:4;border:0;border-top:1px solid var(--ligne);display:none;box-shadow:0 -10px 30px rgba(0,0,0,.5)}
.lgs.feuille-g .lgs__g,.lgs.feuille-d .lgs__d{display:block}
.lgs.ferme .lgs__bas{display:none}
.lgs.avec-pdf .lgs__plan{display:none}.lgs__pdf{flex:1 1 auto}
.lgs__mob{display:flex;grid-column:1/-1;gap:4px;padding:6px;border-top:1px solid var(--ligne);background:var(--panneau);padding-bottom:calc(6px + env(safe-area-inset-bottom))}
.lgs__mob button{flex:1;padding:10px 2px;font-size:.85rem;min-height:48px}
.lgs__aide{display:none}
}
.lgs__fen{position:absolute;z-index:6;display:flex;flex-direction:column;background:var(--panneau);border:1px solid #36506a;border-radius:10px;box-shadow:0 14px 40px rgba(0,0,0,.55);resize:both;overflow:hidden;min-width:220px;min-height:120px}
.lgs__fen > header{display:flex;align-items:center;gap:6px;padding:5px 6px 5px 10px;border-bottom:1px solid var(--ligne);cursor:move;user-select:none;touch-action:none}
.lgs__fen > header b{flex:1;font-weight:500;font-size:.8rem;color:var(--doux);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.lgs__fen > header button{padding:2px 8px}
.lgs__fencorps{flex:1;overflow:auto;padding:6px 10px 10px;min-height:0}
.lgs__bulle{position:absolute;z-index:4;pointer-events:none;background:rgba(16,22,30,.95);color:var(--texte);border:1px solid #36506a;border-radius:7px;padding:4px 8px;font:12px/1.35 ui-monospace,monospace;white-space:nowrap;display:none}
.lgs__bulle b{color:var(--acc);font-weight:600}
.lgs .chrono{overflow-x:auto;overflow-y:hidden;position:relative}
.lgs .chrono svg{display:block}
.lgs .chrono text{font:11px ui-monospace,monospace;fill:var(--doux)}
.lgs .chrono .nom{fill:#cfe3f5;cursor:pointer}
.lgs .chrono .val{fill:#cfe3f5;font-size:10px}
.lgs .chronoBarre{display:flex;gap:4px;align-items:center;flex-wrap:wrap;margin-bottom:6px}
.lgs .chronoLu{font:12px ui-monospace,monospace;color:var(--doux);min-height:16px;margin-top:4px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.lgs select.hz{background:#16202b;color:var(--texte);border:1px solid var(--ligne);border-radius:6px;padding:4px 4px;font:inherit}
.lgs table.mem{border-collapse:collapse;font:12px ui-monospace,monospace}
.lgs table.mem td,.lgs table.mem th{padding:1px 5px;text-align:center}
.lgs table.mem th{color:var(--doux);font-weight:500}
.lgs table.mem td{cursor:pointer;color:#cfe3f5}.lgs table.mem td:hover{background:#1c2836}
.lgs table.mem td.ici{background:#2a2410;color:#ffd27a}
.lgs table.mem td.nz{color:#fff}
@media (max-width: 760px){
.lgs__fen{left:0 !important;right:0;width:auto !important;top:auto !important;bottom:52px;height:auto !important;max-height:58%;border-radius:12px 12px 0 0;resize:none}
.lgs__bulle{display:none !important}
}
</style>
<script>
(function () {
'use strict';
var ID = 'logisim', NS = 'logisim', C = window.jOSCircuit;
function esc(s) { return String(s === undefined || s === null ? '' : s).replace(/[&<>"']/g, function (c) { return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]; }); }
function ls(k, v) { try { if (v === undefined) return localStorage.getItem(k); if (v === null) localStorage.removeItem(k); else localStorage.setItem(k, v); } catch (e) { return null; } }
function B() { return window.jOSBoxion; }
function telecharger(nom, texte, type) {
var u = URL.createObjectURL(new Blob([texte], { type: type || 'text/plain' })), a = document.createElement('a');
a.href = u; a.download = nom; document.body.appendChild(a); a.click(); a.remove(); setTimeout(function () { URL.revokeObjectURL(u); }, 2000);
}
function slug(s) { return String(s || 'projet').toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 60) || 'projet'; }
var COUL = ['#3fe0d0', '#ffb347', '#c38bff', '#ff6b8a', '#7ad3ff', '#b6e36b', '#ffd27a', '#ff8f5a'];
function describe() {
var p = null; try { p = JSON.parse(ls('xb:logisim:auto') || 'null'); } catch (e) {}
return { v: 1, id: ID, title: 'Logisim', icon: '⊼', items: [{ p: 1, kind: 'text', label: 'projet', value: p ? p.nom : '—' }, { p: 2, kind: 'stat', label: 'circuits', value: p ? String(Object.keys(p.circuits || {}).length) : '0' }] };
}
function mount(container, ctx) {
ctx = ctx || {};
var st = {
projet: null, cur: 'main', outil: 'edit', pose: null, sel: { c: {}, w: {} }, vue: { x: 0, y: 0, z: 1 },
sim: null, joue: false, hz: +(ls('xb:logisim:hz') || 4), onglet: ls('xb:logisim:onglet') || 'table', basFerme: ls('xb:logisim:bas') === 'ferme',
histo: [], futur: [], pdf: null, pile: [], sortieKm: 0, filA: null, survol: null, biblio: null, auteur: ls('xb:logisim:auteur') || ''
};
C.signature.owner = st.auteur;
container.innerHTML =
'<div class="lgs">' +
'<div class="lgs__top">' +
'<b>⊼ logisim</b><input class="lgs__nom" data-nomprojet title="nom du projet">' +
'<button data-act="nouveau" title="nouveau projet">✚</button><button data-act="ouvrir" title="ouvrir un .circ (ou glisse-le sur le plan)">⇪ .circ</button><button data-act="circ" title="enregistrer en .circ (Logisim-evolution)">⇩ .circ</button><button data-act="fichiers" title="ouvrir depuis le xerboxion : boxion, nexus, bureau, portions… (.circ ou l\'énoncé .pdf)">⌂ fichiers</button><button data-act="versfichiers" class="bureau" title="enregistrer le .circ dans les fichiers du xerboxion">⌂⇩</button><button data-act="projets" title="mes projets (dans mon compte)">▤</button><button data-act="public" title="circuits publics : partager, reprendre sur n\'importe quel PC sans compte">◎ public</button>' +
'<span class="lgs__sep"></span>' +
'<button data-outil="edit" title="éditer (E)">✥</button><button data-outil="poke" title="toucher : basculer les entrées (T)">⊙</button><button data-outil="fil" class="bureau" title="fil point à point (W)">╱</button>' +
'<span class="lgs__sep"></span>' +
'<button data-act="annuler" title="annuler (Ctrl+Z)">↶</button><button data-act="refaire" title="refaire (Ctrl+Y)">↷</button>' +
'<button data-act="tourner" class="bureau" title="tourner (R)">⟳</button><button data-act="suppr" class="bureau" title="supprimer (Suppr)">✕</button>' +
'<span class="lgs__sep"></span>' +
'<button data-act="joue" title="horloge : lancer / arrêter">▷</button><button data-act="tic" title="un tic d\'horloge">▷|</button><span data-hzhaut></span><button data-act="raz" title="remettre l\'état à zéro">⟲</button>' +
'<span class="lgs__sep"></span>' +
'<button data-act="ajuster" class="bureau" title="tout voir (F)">⤢</button><button data-act="pdf" title="l\'énoncé PDF à côté">◧ PDF</button><button data-act="toile" class="bureau" title="toile claire (Logisim) / sombre">◐</button><button data-act="reglages" title="auteur, signature">✎</button>' +
'<button data-act="g" class="bureau" title="panneau de gauche">◨</button><button data-act="d" class="bureau" title="panneau de droite">◧</button>' +
'</div>' +
'<div class="lgs__g" data-g></div>' +
'<div class="lgs__centre"><div class="lgs__plan" data-plan><svg data-svg></svg><div class="lgs__ariane" data-ariane style="display:none"></div><div class="lgs__aide" data-aide></div></div>' +
'<div class="lgs__pdf" data-pdfpanneau></div></div>' +
'<div class="lgs__d" data-d></div>' +
'<div class="lgs__bas"><div class="lgs__onglets" data-onglets></div><div class="lgs__corps" data-corps></div></div>' +
'<div class="lgs__mob" role="toolbar" aria-label="outils"><button data-mob="g">▤ pièces</button><button data-mob="outil">✥</button><button data-mob="d">◫ réglage</button><button data-mob="bas">▦ table</button><button data-mob="pdf">◧ PDF</button></div>' +
'<input type="file" accept=".circ,application/xml,text/xml" data-fichier hidden><input type="file" accept="application/pdf,.pdf" data-fichierpdf hidden><input type="file" accept=".circ" data-fichierbib hidden>' +
'</div>';
try { if (getComputedStyle(container).position === 'static') container.style.position = 'relative'; if (container.clientHeight < 200) container.style.minHeight = 'calc(100vh - 60px)'; } catch (e0) {}
var R = container.querySelector('.lgs'), $ = function (s) { return R.querySelector(s); };
R.setAttribute('role', 'application'); R.setAttribute('aria-label', 'Logisim : éditeur de circuits logiques');
R.querySelector('.lgs__top').setAttribute('role', 'toolbar'); R.querySelector('[data-svg]').setAttribute('role', 'img');
R.querySelector('[data-plan]').setAttribute('tabindex', '0');
var svg = $('[data-svg]'), plan = $('[data-plan]');
var mobile = function () { return window.matchMedia && window.matchMedia('(max-width: 760px)').matches; };
if (mobile() && ls('xb:logisim:bas') === null) st.basFerme = true; // au téléphone : le plan d'abord, ▦ ouvre la table
// ------------------------------------------------------------ projet, historique, sauvegarde
function circ() { return st.projet.circuits[st.cur]; }
function toast(m, ms) { var t = document.createElement('div'); t.className = 'lgs__toast'; t.setAttribute('role', 'status'); t.setAttribute('aria-live', 'polite'); t.textContent = m; R.appendChild(t); setTimeout(function () { t.remove(); }, ms || 2400); }
function instantane() { return JSON.stringify(st.projet); }
function avant() { st.histo.push(instantane()); if (st.histo.length > 80) st.histo.shift(); st.futur = []; }
var tSauve = null;
function sauver() {
clearTimeout(tSauve);
tSauve = setTimeout(function () {
var j = instantane(); ls('xb:logisim:auto', j);
var b = B(); if (b && b.saveSoon) b.saveSoon(NS, 'p:' + slug(st.projet.nom), st.projet, 'circuit · ' + st.projet.nom, 1500);
}, 300);
}
function modifie(cs) { st.projet.modifie = true; (cs || []).forEach(function (c) { c.modifie = true; }); }
// LA FRACTALE (RS-7 : « si je clique longtemps sur add1bit dans add4bits, j'arrive dans add1bit ») : la pile des instances traversées ;
// la simulation reste celle de la RACINE, on regarde dedans par le chemin d'instance (les valeurs de CETTE instance-là)
function racineNom() { return st.pile.length ? st.pile[0].circuit : st.cur; }
function cheminInst() { return st.pile.length ? st.pile[st.pile.length - 1].chemin : ''; }
function reconstruire() {
var ancien = st.sim;
if (st.pile.length && !st.projet.circuits[racineNom()]) st.pile = [];
try { st.sim = new C.Sim(C.construire(st.projet, racineNom())); st.sim.reprendre(ancien); } catch (e) { st.sim = null; console.warn('logisim', e); }
if (st.chrono) echantillon('edit');
}
function entrer(c) { // dans l'instance c (un bloc du circuit affiché)
if (!c || c.t !== 'sub' || !st.projet.circuits[c.a.circuit]) return;
if (!st.pile.length) st.pile = [{ circuit: st.cur, chemin: '' }];
st.pile.push({ circuit: c.a.circuit, chemin: cheminInst() + '/' + c.id, nom: c.a.label || c.a.circuit });
st.cur = c.a.circuit; st.sel = { c: {}, w: {} }; ajuster(); tout();
}
function allerA(i) { if (i < 0 || i >= st.pile.length) return; st.pile = st.pile.slice(0, i + 1); st.cur = st.pile[i].circuit; if (i === 0) st.pile = []; st.sel = { c: {}, w: {} }; ajuster(); tout(); }
function filAriane() {
var el = $('[data-ariane]'); if (!el) return;
if (!st.pile.length) { el.innerHTML = ''; el.style.display = 'none'; return; }
el.style.display = '';
el.innerHTML = st.pile.map(function (p, i) { return (i ? '<span>›</span>' : '') + '<button data-ariane-i="' + i + '"' + (i === st.pile.length - 1 ? ' class="on"' : '') + '>' + esc(i ? p.nom : p.circuit) + '</button>'; }).join('') + '<small>valeurs de cette instance</small>';
}
function changer(fn, cs) { avant(); fn(); modifie(cs); reconstruire(); sauver(); dessiner(); panneaux(); bas(); }
function charger(p, garderVue) {
st.projet = p; st.cur = p.circuits[p.main] ? p.main : Object.keys(p.circuits)[0];
st.sel = { c: {}, w: {} }; st.histo = []; st.futur = []; st.pdf = null;
reconstruire(); if (!garderVue) ajuster(); sauver(); tout();
chargerPdf();
}
function annuler() { if (!st.histo.length) return; st.futur.push(instantane()); st.projet = JSON.parse(st.histo.pop()); if (!st.projet.circuits[st.cur]) st.cur = st.projet.main; st.sel = { c: {}, w: {} }; reconstruire(); sauver(); tout(); }
function refaire() { if (!st.futur.length) return; st.histo.push(instantane()); st.projet = JSON.parse(st.futur.pop()); st.sel = { c: {}, w: {} }; reconstruire(); sauver(); tout(); }
// ------------------------------------------------------------ géométrie d'affichage
function bornes(c) {
if (c.t === 'sub') { var sc = st.projet.circuits[c.a.circuit]; if (sc) { var f = C.formeBloc(sc, c.a.circuit); return [c.x + f.bx, c.y + f.by, c.x + f.bx + f.W, c.y + f.by + f.H]; } }
if (c.t === 'text') { var t = String(c.a.text || ''); return [c.x - t.length * 3.5 - 4, c.y - 8, c.x + t.length * 3.5 + 4, c.y + 8]; }
if (c.t === 'pin') { var o = C.oriente(-20, 0, c.a.facing || 'east'), dx = c.a.facing === 'west' || c.a.facing === 'east' ? o[0] : 0, dy = c.a.facing === 'north' || c.a.facing === 'south' ? o[1] : 0; if (c.a.output) { dx = -dx; dy = -dy; } var x1 = c.x + Math.min(0, dx) - (dy ? 10 : 0), y1 = c.y + Math.min(0, dy) - (dx ? 10 : 0); return [x1, y1, x1 + (dx ? 20 : 20), y1 + (dy ? 20 : 20)]; }
var dB = C.T[c.t]; if (dB && dB.boite) { var bx = dB.boite(c); return [c.x + bx[0], c.y + bx[1], c.x + bx[0] + bx[2], c.y + bx[1] + bx[3]]; }
var ps = C.portsAbs(c, st.projet), xs = ps.map(function (p) { return p.x; }).concat([c.x]), ys = ps.map(function (p) { return p.y; }).concat([c.y]);
var b = [Math.min.apply(null, xs), Math.min.apply(null, ys), Math.max.apply(null, xs), Math.max.apply(null, ys)];
var d = C.T[c.t];
if (d && d.lib === 1 && c.t !== 'tri') { var r = C.oriente(-((+c.a.size || 50)), 0, c.a.facing || 'east'); var h = Math.max(25, (b[3] - b[1]) / 2 + 5), wv = Math.abs(r[0]) || 0; if (c.a.facing === 'north' || c.a.facing === 'south') { b[0] = Math.min(b[0], c.x - h); b[2] = Math.max(b[2], c.x + h); } else { b[1] = Math.min(b[1], c.y - h); b[3] = Math.max(b[3], c.y + h); } }
if (b[2] - b[0] < 20) { b[0] -= 10; b[2] += 10; } if (b[3] - b[1] < 20) { b[1] -= 10; b[3] += 10; }
return b;
}
function matrice(f) { return f === 'west' ? 'matrix(-1,0,0,1,0,0)' : f === 'north' ? 'matrix(0,-1,1,0,0,0)' : f === 'south' ? 'matrix(0,1,1,0,0,0)' : ''; }
function couleurBits(v) {
if (!v) return 'var(--doux2)';
if (v.length > 1) return v.some(function (b) { return b === 'e'; }) ? 'var(--e)' : 'var(--bus)';
var b = v[0]; return b === 1 ? 'var(--un)' : b === 0 ? 'var(--zero)' : b === 'e' ? 'var(--e)' : 'var(--x)';
}
var TR = 'fill="none" stroke="var(--trait)" stroke-width="2"', TRP = 'fill="var(--corps)" stroke="var(--trait)" stroke-width="2"';
function dongle(x, y) { return '<circle cx="' + x + '" cy="' + y + '" r="4.5" ' + TRP + '/>'; } // painter.drawDongle (9 px)
function txt(x, y, t, o) { o = o || {}; return '<text x="' + x + '" y="' + y + '" text-anchor="' + (o.a || 'middle') + '" font-size="' + (o.t || 11) + '" fill="' + (o.c || 'var(--trait)') + '"' + (o.b ? ' font-weight="700"' : '') + (o.m ? ' font-family="ui-monospace,monospace"' : '') + '>' + esc(t) + '</text>'; }
// le bouclier du OU (PainterShaped.computeShield) : bord gauche courbe, avec des « ailes » quand les entrées dépassent
function bouclier(W, H) {
var dc = W < 40 ? 8 : W < 60 ? 13 : 20, base = 'M' + (-W) + ',' + (-W / 2) + ' Q' + (-W + dc) + ',0 ' + (-W) + ',' + (W / 2);
if (H <= W) return base;
var dx = Math.min(20, ((H - W) / 2) / 4);
return 'M' + (-W) + ',' + (-H / 2) + ' Q' + (-W + dx) + ',' + (-(W + H) / 4) + ' ' + (-W) + ',' + (-W / 2) + ' Q' + (-W + dc) + ',0 ' + (-W) + ',' + (W / 2) + ' Q' + (-W + dx) + ',' + ((W + H) / 4) + ' ' + (-W) + ',' + (H / 2);
}
function xBouclier(W, y) { var dc = W < 40 ? 8 : W < 60 ? 13 : 20; if (Math.abs(y) > W / 2) return -W; var t = (y / (W / 2) + 1) / 2; return -W + 2 * t * (1 - t) * dc; }
function corpsOu(W) { var k = W < 40 ? [10, 15, 30, 22] : W < 60 ? [20, 25, 50, 37] : [25, 35, 70, 50]; return 'M0,0 Q' + (-k[0]) + ',' + (-k[1]) + ' ' + (-k[2]) + ',' + (-k[1]) + ' Q' + (-k[3]) + ',0 ' + (-k[2]) + ',' + k[1] + ' Q' + (-k[0]) + ',' + k[1] + ' 0,0Z'; }
// les portes « shaped » de Logisim (PainterShaped) dans le repère est, puis la matrice de l'orientation
function formePorte(c) {
var d = C.T[c.t], size = +c.a.size || 50, neg = d.negOut ? 10 : 0, bonus = d.bonus || 0, nIn = Math.max(2, +c.a.inputs || 2);
var pE = d.ports({ a: Object.assign({}, c.a, { facing: 'east', inputs: nIn, size: size, width: 1 }) }).slice(1);
var ymn = Math.min.apply(null, pE.map(function (p) { return p.y; })), ymx = Math.max.apply(null, pE.map(function (p) { return p.y; }));
var H = Math.max(size, 10 + (ymx - ymn)), W = size, s = '<g transform="translate(' + (-neg) + ',0)">';
if (c.t === 'and' || c.t === 'nand') {
s += '<path d="M' + (-W / 2) + ',' + (-W / 2) + ' L' + (-W + 1) + ',' + (-W / 2) + ' L' + (-W + 1) + ',' + (W / 2) + ' L' + (-W / 2) + ',' + (W / 2) + ' A' + (W / 2) + ',' + (W / 2) + ' 0 0 0 ' + (-W / 2) + ',' + (-W / 2) + 'Z" ' + TRP + '/>';
if (H > W) s += '<line x1="' + (-W + 1) + '" y1="' + (-H / 2) + '" x2="' + (-W + 1) + '" y2="' + (H / 2) + '" ' + TR + '/>';
} else if (c.t === 'or' || c.t === 'nor') {
s += '<path d="' + corpsOu(W) + '" ' + TRP + '/>' + (H > W ? '<path d="' + bouclier(W, H) + '" ' + TR + '/>' : '');
} else if (c.t === 'xor' || c.t === 'xnor') {
s += '<path d="' + corpsOu(W) + '" ' + TRP + '/><g transform="translate(-10,0)"><path d="' + bouclier(W, H) + '" ' + TR + '/></g>';
} else { // parités : le rectangle de Logisim avec « 2k+1 » / « 2k »
s += '<rect x="' + (-W) + '" y="' + (-H / 2) + '" width="' + W + '" height="' + H + '" ' + TRP + '/>' + txt(-W / 2, 4, d.g);
}
s += '</g>';
if (neg) s += dongle(-5, 0);
// les fils d'entrée jusqu'au corps (getInputLineLengths), et les bulles des entrées inversées
pE.forEach(function (p, i) {
var bord = (c.t === 'or' || c.t === 'nor') ? xBouclier(W, p.y) - neg : (c.t === 'xor' || c.t === 'xnor') ? xBouclier(W, p.y) - 10 - neg : -W - neg - bonus;
if (c.a['negate' + i] === true || c.a['negate' + i] === 'true') { s += dongle(p.x + 5, p.y); return; }
if (bord > p.x + 1) s += '<line x1="' + p.x + '" y1="' + p.y + '" x2="' + bord + '" y2="' + p.y + '" stroke="var(--trait)" stroke-width="3"/>';
});
return '<g transform="translate(' + c.x + ',' + c.y + ') ' + matrice(c.a.facing) + '">' + s + '</g>';
}
function radixTexte(v, w, rx) {
if (!v) return '';
var n = C.entier(v); if (n === null || !rx || rx === '2') return C.texteMot(v);
if (rx === '16') return n.toString(16).toUpperCase().padStart(Math.ceil(w / 4), '0');
if (rx === '8') return n.toString(8);
if (rx === '10signed' && w > 1 && n >= Math.pow(2, w - 1)) return String(n - Math.pow(2, w));
return String(n);
}
function etiquette(c, b, defLoc) {
var t = c.a.label; if (!t) return '';
var loc = attrVal(c, 'labelloc') || defLoc, fm = /(\d+)\s*$/.exec(attrVal(c, 'labelfont') || ''), tf = fm ? Math.min(28, +fm[1]) : 16, gras = !/plain/i.test(attrVal(c, 'labelfont') || 'bold');
var cx = (b[0] + b[2]) / 2, cy = (b[1] + b[3]) / 2, x = cx, y = cy + tf * .35, an = 'middle';
if (loc === 'west') { x = b[0] - 4; an = 'end'; } else if (loc === 'east') { x = b[2] + 4; an = 'start'; } else if (loc === 'north') y = b[1] - 4; else if (loc === 'south') y = b[3] + tf;
return '<text x="' + x + '" y="' + y + '" text-anchor="' + an + '" font-size="' + tf + '" fill="var(--label)"' + (gras ? ' font-weight="700"' : '') + '>' + esc(t) + '</text>';
}
function itDe(c) { var ch = cheminInst(); return st.sim ? st.sim.m.comps.find(function (x) { return x.c && x.c.id === c.id && x.chemin === ch; }) : null; }
function valIn(c, i) { var it = itDe(c); return it && it.ins[i] ? st.sim.lire(it.ins[i]) : null; }
function dessinComp(c, choisi) {
var t = c.t, d = C.T[t], s = '', b = bornes(c), lab = '';
if (d && d.lib === 1 && t !== 'not' && t !== 'buf' && t !== 'tri' && t !== 'trinot') s += formePorte(c);
else if (t === 'not' || t === 'buf' || t === 'tri' || t === 'trinot') {
var g0;
if (t === 'trinot') { var etr = +c.a.size === 20 ? 0 : 10, gc = c.a.control === 'left' ? -1 : 1; g0 = (etr ? '<path d="M-10,0 L-29,-7 L-29,7 Z" ' + TRP + '/><circle cx="-4.5" cy="0" r="4.5" ' + TRP + '/><line x1="-30" y1="0" x2="-29" y2="0" ' + TR + '/>' : '<polyline points="-7,-1 -19,-6 -19,6 -7,1" ' + TR + '/><circle cx="-3" cy="0" r="3" ' + TRP + '/>') + '<line x1="' + (-10 - etr) + '" y1="' + (10 * gc) + '" x2="' + (-10 - etr) + '" y2="' + (4 * gc) + '" ' + TR + '/>'; }
else if (t === 'not') g0 = +c.a.size === 20 ? '<polyline points="-7,-1 -19,-6 -19,6 -7,1" ' + TR + '/><circle cx="-3" cy="0" r="3" ' + TRP + '/>' : '<path d="M-10,0 L-29,-7 L-29,7 Z" ' + TRP + '/><circle cx="-4.5" cy="0" r="4.5" ' + TRP + '/><line x1="-30" y1="0" x2="-29" y2="0" ' + TR + '/>';
else g0 = '<path d="M0,0 L-20,-9 L-20,9 Z" ' + TRP + '/>' + (t === 'tri' ? '<line x1="-10" y1="10" x2="-10" y2="5" ' + TR + '/>' : '');
s += '<g transform="translate(' + c.x + ',' + c.y + ') ' + matrice(c.a.facing) + '">' + g0 + '</g>';
} else if (t === 'pin') {
// Pin de Logisim : entrée = carré, sortie = arrondi ; la valeur dedans (les bits, poids fort à gauche)
var v = st.sim ? st.sim.valeurDe(c, cheminInst()) : null, wd = +c.a.width || 1, rx = attrVal(c, 'radix'), vt = v ? radixTexte(v, wd, rx) : '';
var nCh = rx && rx !== '2' ? Math.max(2, vt.length) : Math.min(8, wd), bw = wd === 1 ? 20 : nCh * 8 + 6, bh = wd === 1 ? 20 : (rx && rx !== '2' ? 1 : Math.ceil(wd / 8)) * 14 + 6;
var bx2 = b[0], by2 = b[1];
if (wd > 1) { var f2 = c.a.facing || (c.a.output ? 'west' : 'east'), sens = c.a.output ? 1 : -1; if (f2 === 'east' || f2 === 'west') { var dirx = (f2 === 'east' ? -1 : 1) * (c.a.output ? -1 : 1); bx2 = dirx < 0 ? c.x - bw : c.x; by2 = c.y - bh / 2; } else { var diry = (f2 === 'south' ? -1 : 1) * (c.a.output ? -1 : 1); bx2 = c.x - bw / 2; by2 = diry < 0 ? c.y - bh : c.y; } b = [bx2, by2, bx2 + bw, by2 + bh]; }
s += '<rect x="' + b[0] + '" y="' + b[1] + '" width="' + (b[2] - b[0]) + '" height="' + (b[3] - b[1]) + '" rx="' + (c.a.output ? (wd === 1 ? 10 : 6) : 0) + '" ' + TRP + '/>';
if (wd === 1) s += (v && (v[0] === 0 || v[0] === 1) ? '<circle cx="' + ((b[0] + b[2]) / 2) + '" cy="' + ((b[1] + b[3]) / 2) + '" r="6.5" fill="' + couleurBits(v) + '"/>' : '') + txt((b[0] + b[2]) / 2, (b[1] + b[3]) / 2 + 4, vt || 'x', { c: v && (v[0] === 0 || v[0] === 1) ? '#fff' : 'var(--x)', b: 1 });
else if (rx && rx !== '2') s += txt(b[0] + 3, b[1] + 15, vt, { a: 'start', m: 1 });
else for (var li = 0; li < Math.ceil(wd / 8); li++) s += txt(b[0] + 3, b[1] + 15 + 14 * li, vt.slice(li * 8, li * 8 + 8), { a: 'start', m: 1 });
lab = etiquette(c, b, c.a.output ? 'east' : 'west');
} else if (t === 'sub') {
var sc = st.projet.circuits[c.a.circuit], f = sc ? C.formeBloc(sc, c.a.circuit) : null;
if (f) {
var X = c.x + f.bx, Y = c.y + f.by;
if (f.forme === 'evolution') { // DefaultEvolutionAppearance : cadre, bandeau noir en bas avec le nom, les ports en traits
s += '<rect x="' + (X + 10) + '" y="' + Y + '" width="' + (f.W - 20) + '" height="' + f.H + '" ' + TRP + '/>';
s += '<rect x="' + (X + 10) + '" y="' + (Y + f.H - 20) + '" width="' + (f.W - 20) + '" height="20" fill="var(--bandeau)"/>';
s += txt(X + f.W / 2, Y + f.H - 6, c.a.circuit, { c: 'var(--bandeau-t)', b: 1 });
} else if (f.forme === 'classic') { // DefaultClassicAppearance : rectangle + l'encoche en haut
s += '<rect x="' + X + '" y="' + Y + '" width="' + f.W + '" height="' + f.H + '" ' + TRP + '/><path d="M' + (X + (f.W - 8) / 2) + ',' + (Y + 1) + ' Q' + (X + f.W / 2) + ',' + (Y + 11) + ' ' + (X + (f.W + 8) / 2) + ',' + (Y + 1) + '" ' + TR + '/>';
} else s += '<rect x="' + X + '" y="' + Y + '" width="' + f.W + '" height="' + f.H + '" ' + TRP + '/>' + txt(X + f.W / 2, Y + f.H / 2 + 4, c.a.circuit, { t: 10, c: 'var(--etiq)' });
f.entrees.concat(f.sorties).forEach(function (e) {
var px = c.x + e.x, py = c.y + e.y, bus = e.w > 1;
if (f.forme === 'evolution') {
var dedans = e.cote === 'w' ? 10 : -10;
s += '<rect x="' + (dedans > 0 ? px : px - 10) + '" y="' + (py - (bus ? 2 : 1)) + '" width="10" height="' + (bus ? 4 : 2) + '" fill="var(--trait)"/>' + txt(px + (dedans > 0 ? 15 : -15), py + 4, e.n, { a: dedans > 0 ? 'start' : 'end', t: 10 });
} else s += '<circle cx="' + px + '" cy="' + py + '" r="' + (e.pin.a.output ? 2.5 : 2) + '" fill="var(--trait)"/>';
});
} else s += '<rect x="' + (c.x - 20) + '" y="' + (c.y - 20) + '" width="40" height="40" fill="none" stroke="var(--e)" stroke-dasharray="4 3"/>' + txt(c.x, c.y + 4, c.a.circuit + ' ?', { t: 10, c: 'var(--e)' });
if (c.a.label) lab = txt((b[0] + b[2]) / 2, b[1] - 4, c.a.label, { t: 10, c: 'var(--etiq)' });
} else if (t === 'splitter') { // le splitter de Logisim : une épine épaisse, des traits fins vers chaque bout
var e2 = C.T.splitter.ends(c), horiz = !c.a.facing || c.a.facing === 'east' || c.a.facing === 'west', m = horiz ? (c.a.facing === 'west' ? -1 : 1) : (c.a.facing === 'north' ? 1 : -1);
var sp = horiz ? m * 6 : -m * 6, xs = e2.map(function (p) { return p[0]; }).concat([0]), ys = e2.map(function (p) { return p[1]; }).concat([0]);
s += '<g transform="translate(' + c.x + ',' + c.y + ')">';
if (horiz) { s += '<line x1="0" y1="0" x2="' + sp + '" y2="0" stroke="var(--trait)" stroke-width="4"/><line x1="' + sp + '" y1="' + Math.min.apply(null, ys) + '" x2="' + sp + '" y2="' + Math.max.apply(null, ys) + '" stroke="var(--trait)" stroke-width="4"/>'; e2.forEach(function (p) { s += '<line x1="' + sp + '" y1="' + p[1] + '" x2="' + p[0] + '" y2="' + p[1] + '" stroke="var(--trait)" stroke-width="2"/>'; }); }
else { s += '<line x1="0" y1="0" x2="0" y2="' + sp + '" stroke="var(--trait)" stroke-width="4"/><line x1="' + Math.min.apply(null, xs) + '" y1="' + sp + '" x2="' + Math.max.apply(null, xs) + '" y2="' + sp + '" stroke="var(--trait)" stroke-width="4"/>'; e2.forEach(function (p) { s += '<line x1="' + p[0] + '" y1="' + sp + '" x2="' + p[0] + '" y2="' + p[1] + '" stroke="var(--trait)" stroke-width="2"/>'; }); }
s += '</g>';
} else if (t === 'led') {
var lv = valIn(c, 0), cx2 = (b[0] + b[2]) / 2, cy2 = (b[1] + b[3]) / 2;
s += '<circle cx="' + cx2 + '" cy="' + cy2 + '" r="9" fill="' + (lv && lv[0] === 1 ? (c.a.color || '#f03030') : '#404040') + '" stroke="var(--trait)" stroke-width="2"/>';
} else if (t === 'rgbled') {
var it3 = itDe(c), on3 = function (i) { var vv = it3 && it3.ins[i] ? st.sim.lire(it3.ins[i]) : null; return vv && vv[0] === 1; }, rgb = [on3(0), on3(1), on3(2)];
s += '<circle cx="' + ((b[0] + b[2]) / 2) + '" cy="' + ((b[1] + b[3]) / 2) + '" r="9" fill="' + (rgb.some(Boolean) ? 'rgb(' + (rgb[0] ? 255 : 0) + ',' + (rgb[1] ? 255 : 0) + ',' + (rgb[2] ? 255 : 0) + ')' : '#404040') + '" stroke="var(--trait)" stroke-width="2"/>';
} else if (t === 'dip') { // un interrupteur par sortie, levé = 1 (⊙ toucher pour basculer)
var itd = itDe(c), vd = itd && itd.st.v || 0, mx = (b[0] + b[2]) / 2, my = (b[1] + b[3]) / 2;
s += '<rect x="' + b[0] + '" y="' + b[1] + '" width="' + (b[2] - b[0]) + '" height="' + (b[3] - b[1]) + '" fill="#2a3f8a" stroke="var(--trait)" stroke-width="2"/>';
C.portsAbs(c, st.projet).forEach(function (q, i) {
var hz2 = Math.abs(q.y - my) > Math.abs(q.x - mx), cx3 = hz2 ? q.x : (q.x + mx) / 2, cy3 = hz2 ? (q.y + my) / 2 : q.y, on4 = (vd >>> i) & 1;
s += '<rect x="' + (cx3 - 3.5) + '" y="' + (cy3 - 9) + '" width="7" height="18" fill="#fff" stroke="#000" stroke-width=".8"' + (hz2 ? '' : ' transform="rotate(90 ' + cx3 + ' ' + cy3 + ')"') + '/><rect x="' + (cx3 - 3) + '" y="' + (on4 ? cy3 - 8.5 : cy3) + '" width="6" height="8.5" fill="#333"' + (hz2 ? '' : ' transform="rotate(90 ' + cx3 + ' ' + cy3 + ')"') + '/>';
});
} else if (t === 'ram' || t === 'rom') { // la boîte de Logisim : le titre, puis le contenu autour de l'adresse courante
var awr = Math.max(1, +c.a.addrWidth || 8), dwr = Math.max(1, +c.a.dataWidth || 8), itr = itDe(c), adr = itr ? C.entier(st.sim.lire(itr.ins[0])) : null;
var vals = t === 'rom' ? C.lireContenu(c.a.contents) : (function () { var m2 = itr && itr.st.mem || {}, r2 = []; Object.keys(m2).forEach(function (k) { r2[+k] = m2[k]; }); return r2; })();
var parL2 = dwr > 16 ? 2 : dwr > 8 ? 4 : 8, ligne0 = adr === null ? 0 : Math.max(0, Math.floor(adr / parL2) - 1) * parL2, hd2 = Math.ceil(dwr / 4);
s += '<rect x="' + b[0] + '" y="' + b[1] + '" width="' + (b[2] - b[0]) + '" height="' + (b[3] - b[1]) + '" ' + TRP + '/>' + txt((b[0] + b[2]) / 2, b[1] + 14, (t === 'ram' ? 'RAM ' : 'ROM ') + Math.pow(2, awr) + ' x ' + dwr, { t: 11, b: 1 });
s += '<rect x="' + (b[0] + 30) + '" y="' + (b[1] + 22) + '" width="' + (b[2] - b[0] - 60) + '" height="64" fill="none" stroke="var(--doux2)" stroke-width=".8"/>';
for (var lr = 0; lr < 4 && ligne0 + lr * parL2 < Math.pow(2, awr); lr++) {
var a1 = ligne0 + lr * parL2, ly = b[1] + 36 + lr * 15, ligne = a1.toString(16).padStart(Math.ceil(awr / 4), '0') + ' ';
s += txt(b[0] + 36, ly, ligne, { t: 10, m: 1, a: 'start', c: 'var(--doux2)' });
for (var k3 = 0; k3 < parL2 && a1 + k3 < Math.pow(2, awr); k3++) { var xk = b[0] + 36 + (Math.ceil(awr / 4) + 1) * 6.2 + k3 * (hd2 + 1) * 6.4; s += (adr === a1 + k3 ? '<rect x="' + (xk - 1) + '" y="' + (ly - 9) + '" width="' + (hd2 * 6.4 + 2) + '" height="12" fill="#ffd27a" opacity=".5"/>' : '') + txt(xk, ly, (vals[a1 + k3] || 0).toString(16).padStart(hd2, '0'), { t: 10, m: 1, a: 'start' }); }
}
C.portsDe(c).forEach(function (p) { var ax3 = c.x + p.x, ay3 = c.y + p.y, g3 = ax3 <= b[0] + 1; if (p.n === 'CLK' && g3) s += '<path d="M' + b[0] + ',' + (ay3 - 5) + ' l7,5 l-7,5" ' + TR + '/>'; else s += txt(ax3 + (g3 ? 4 : -4), ay3 + 4, p.n, { a: g3 ? 'start' : 'end', t: 9 }); });
} else if (t === 'tty') { // le terminal de Logisim : texte noir sur fond clair
var itt = itDe(c), tx = itt && itt.st.txt || '';
s += '<rect x="' + b[0] + '" y="' + b[1] + '" width="' + (b[2] - b[0]) + '" height="' + (b[3] - b[1]) + '" fill="#f4f4ec" stroke="var(--trait)" stroke-width="2" rx="4"/>';
tx.split('\n').forEach(function (l, i) { s += '<text x="' + (b[0] + 6) + '" y="' + (b[1] + 17 + i * 15) + '" style="font:11px ui-monospace,monospace;white-space:pre" fill="#000">' + esc(l) + '</text>'; });
s += '<path d="M' + c.x + ',' + (c.y - 5) + ' l7,5 l-7,5" ' + TR + '/>';
} else if (t === 'keyboard') { // le clavier : son tampon ; ⊙ le toucher puis taper
var itk = itDe(c), bf = itk && itk.st.buf || [], actif = st.clavier === c.id;
s += '<rect x="' + b[0] + '" y="' + b[1] + '" width="' + (b[2] - b[0]) + '" height="' + (b[3] - b[1]) + '" fill="var(--corps)" stroke="' + (actif ? 'var(--selc)' : 'var(--trait)') + '" stroke-width="' + (actif ? 3 : 2) + '" rx="4"/>';
s += '<text x="' + (b[0] + 18) + '" y="' + (b[1] + 16) + '" style="font:12px ui-monospace,monospace;white-space:pre" fill="var(--trait)">' + esc(bf.map(function (k) { return k === 13 ? '⏎' : k < 32 ? '·' : String.fromCharCode(k); }).join('').slice(0, 16) || (actif ? 'tape…' : '')) + '</text>';
s += '<path d="M' + c.x + ',' + (c.y - 5) + ' l7,5 l-7,5" ' + TR + '/>';
} else if (t === 'button') {
var bv = itDe(c), on = bv && bv.st.v;
s += '<rect x="' + (b[0] + (on ? 3 : 0)) + '" y="' + (b[1] + (on ? 3 : 0)) + '" width="17" height="17" fill="#ccc" stroke="var(--trait)" stroke-width="1.5"/>' + (on ? '' : '<path d="M' + (b[0] + 17) + ',' + b[1] + ' l3,3 v17 h-17 l-3,-3" fill="#999" stroke="var(--trait)" stroke-width="1"/>');
} else if (t === 'const') { // la constante de Logisim : seulement la valeur
var kv = +c.a.value || 0, kw = +c.a.width || 1, kt = kw === 1 ? String(kv & 1) : '0x' + kv.toString(16);
s += txt(c.x - (c.a.facing === 'west' ? -3 : 3) - (c.a.facing === 'west' ? 0 : kt.length * 3.3), c.y + 4, kt, { c: kw === 1 ? (kv & 1 ? 'var(--un)' : 'var(--zero)') : 'var(--trait)', b: 1, m: 1, a: 'middle' });
} else if (t === 'clock') {
var cv = st.sim ? st.sim.valeurEn(c.x, c.y, cheminInst()) : null, hi = cv && cv[0] === 1;
s += '<rect x="' + (c.x - 20) + '" y="' + (c.y - 10) + '" width="20" height="20" ' + TRP + '/><path d="M' + (c.x - 16) + ',' + (c.y + 4) + ' h4 v-8 h5 v8 h4" fill="none" stroke="' + (hi ? 'var(--un)' : 'var(--zero)') + '" stroke-width="2"/>';
} else if (t === 'probe') {
var pv = st.sim ? st.sim.valeurEn(c.x, c.y, cheminInst()) : null, pt2 = pv ? radixTexte(pv, pv.length, attrVal(c, 'radix')) : 'x', pw = Math.max(20, pt2.length * 7 + 8);
s += '<rect x="' + (c.x - pw) + '" y="' + (c.y - 10) + '" width="' + pw + '" height="20" rx="8" fill="var(--corps)" stroke="var(--trait)" stroke-width="1.5"/>' + txt(c.x - pw / 2, c.y + 4, pt2, { m: 1, c: couleurBits(pv) });
} else if (t === 'tunnel') { // le pentagone de Logisim, pointe sur le port
var tl = c.a.label || 't', tw2 = tl.length * 7 + 14, fs = c.a.facing || 'west', flip = fs === 'west' ? 1 : -1;
if (fs === 'west' || fs === 'east') s += '<path d="M' + c.x + ',' + c.y + ' l' + (6 * flip) + ',-9 h' + ((tw2 - 6) * flip) + ' v18 h' + (-(tw2 - 6) * flip) + 'Z" ' + TRP + '/>' + txt(c.x + flip * (tw2 / 2 + 3), c.y + 4, tl);
else { var fl2 = fs === 'north' ? 1 : -1; s += '<path d="M' + c.x + ',' + c.y + ' l-9,' + (6 * fl2) + ' v' + (14 * fl2) + ' h18 v' + (-14 * fl2) + 'Z" ' + TRP + '/>' + txt(c.x, c.y + fl2 * 16 + 4, tl, { t: 10 }); }
} else if (t === 'text') {
s += txt(c.x, c.y + 4, c.a.text, { t: 12 });
} else if (t === 'mux' || t === 'demux') { // trapèze (PlexersLibrary.drawTrapezoid), « 0 » près de l'entrée 0
var tri = 10, horiz2 = !c.a.facing || c.a.facing === 'east' || c.a.facing === 'west', fe = c.a.facing || 'east';
var pts2 = horiz2 ? ((t === 'mux') === (fe === 'east') ? [[b[0], b[1]], [b[2], b[1] + tri], [b[2], b[3] - tri], [b[0], b[3]]] : [[b[0], b[1] + tri], [b[2], b[1]], [b[2], b[3]], [b[0], b[3] - tri]])
: ((t === 'mux') === (fe === 'south') ? [[b[0], b[1]], [b[2], b[1]], [b[2] - tri, b[3]], [b[0] + tri, b[3]]] : [[b[0] + tri, b[1]], [b[2] - tri, b[1]], [b[2], b[3]], [b[0], b[3]]]);
s += '<polygon points="' + pts2.map(function (q) { return q.join(','); }).join(' ') + '" ' + TRP + '/>' + txt((b[0] + b[2]) / 2, (b[1] + b[3]) / 2 + 4, t === 'mux' ? 'MUX' : 'DMX', { t: 8, b: 1 });
var p0 = C.portsAbs(c, st.projet)[t === 'mux' ? 0 : 0]; if (p0) s += txt(p0.x + (p0.x <= b[0] ? 6 : -6), p0.y + 4, '0', { t: 9 });
} else if (t === 'decoder') {
s += '<rect x="' + b[0] + '" y="' + b[1] + '" width="' + (b[2] - b[0]) + '" height="' + (b[3] - b[1]) + '" ' + TRP + '/>' + txt((b[0] + b[2]) / 2, (b[1] + b[3]) / 2 + 4, 'DEC', { t: 8, b: 1 });
} else if (t === 'hex' || t === 'seg7') {
var it7 = itDe(c), segOn = {};
if (t === 'hex') {
var hv = it7 ? C.entier(st.sim.lire(it7.ins[0])) : null, HEX = [0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, 0x7F, 0x6F, 0x77, 0x7C, 0x39, 0x5E, 0x79, 0x71];
if (hv !== null) 'abcdefg'.split('').forEach(function (k, i) { segOn[k] = (HEX[hv] >> i) & 1; });
b = [c.x - 15, c.y - 60, c.x + 25, c.y];
} else { b = [c.x - 5, c.y, c.x + 35, c.y + 60]; if (it7) ['a', 'b', 'c', 'd', 'e', 'f', 'g'].forEach(function (k) { var i = ['a', 'b', 'c', 'd', 'e', 'f', 'g'].indexOf(k); var pi = C.portsDe(c).findIndex(function (q) { return q.n === k; }); var vv = it7.ins[pi] ? st.sim.lire(it7.ins[pi]) : null; segOn[k] = vv && vv[0] === 1; }); }
s += '<rect x="' + b[0] + '" y="' + b[1] + '" width="40" height="60" fill="#404040" stroke="var(--trait)" stroke-width="2"/>';
var ox = b[0] + 8, oy = b[1] + 8, SG = { a: [3, 0, 19, 4], b: [21, 2, 4, 19], c: [21, 22, 4, 19], d: [3, 39, 19, 4], e: [-1, 22, 4, 19], f: [-1, 2, 4, 19], g: [3, 20, 19, 4] };
Object.keys(SG).forEach(function (k) { var r = SG[k]; s += '<rect x="' + (ox + r[0]) + '" y="' + (oy + r[1]) + '" width="' + r[2] + '" height="' + r[3] + '" fill="' + (segOn[k] ? '#f03030' : '#5a2a2a') + '"/>'; });
} else {
// boîtes de Logisim : additionneur « + », soustracteur « − », bascules (D / Q / triangle d'horloge), registre, compteur…
var g = d ? d.g : (c.circName || '?');
var bxL = { add: '+', sub: '−', mul: '×', neg: '-x', cmp: '' }[t];
s += '<rect x="' + b[0] + '" y="' + b[1] + '" width="' + Math.max(10, b[2] - b[0]) + '" height="' + Math.max(10, b[3] - b[1]) + '" ' + TRP + (t === '?' ? ' stroke-dasharray="4 3"' : '') + '/>';
if (bxL !== undefined) s += txt((b[0] + b[2]) / 2, (b[1] + b[3]) / 2 + 6, bxL, { t: 18 });
else if (t === 'shiftreg') s += txt((b[0] + b[2]) / 2, b[1] + 13, 'SR' + (+c.a.length || 8), { t: 9 });
else if (d && d.lib === 4) s += txt((b[0] + b[2]) / 2, b[1] + 13, t === 'reg' ? '' : t === 'counter' ? 'ctr' : '', { t: 9 });
else s += txt((b[0] + b[2]) / 2, (b[1] + b[3]) / 2 + 4, g, { t: g.length > 4 ? 9 : 11 });
C.portsDe(c).forEach(function (p) {
var ax2 = c.x + p.x, ay2 = c.y + p.y, gauche2 = ax2 <= b[0] + 1, droite = ax2 >= b[2] - 1, bas2 = ay2 >= b[3] - 1, haut = ay2 <= b[1] + 1;
if (p.n === 'CLK' && gauche2) { s += '<path d="M' + b[0] + ',' + (ay2 - 5) + ' l7,5 l-7,5" ' + TR + '/>'; return; }
if (p.n === 'CLK' && bas2) { s += '<path d="M' + (ax2 - 5) + ',' + b[3] + ' l5,-7 l5,7" ' + TR + '/>'; return; }
if ((t === 'cmp' || (d && d.lib === 4)) && t !== 'shiftreg') s += txt(ax2 + (gauche2 ? 4 : droite ? -4 : 0), ay2 + (bas2 ? -3 : haut ? 10 : 4), p.n === 'Q̄' ? 'Q\'' : p.n, { a: gauche2 ? 'start' : droite ? 'end' : 'middle', t: 9 });
});
}
if (c.a.label && t !== 'pin' && t !== 'tunnel' && t !== 'sub') lab = etiquette(c, b, 'north');
if (choisi) s += '<rect x="' + (b[0] - 4) + '" y="' + (b[1] - 4) + '" width="' + (b[2] - b[0] + 8) + '" height="' + (b[3] - b[1] + 8) + '" fill="none" stroke="var(--selc)" stroke-dasharray="3 3" rx="2"/>';
return '<g data-c="' + esc(c.id) + '">' + s + lab + '</g>';
}
// ---- le bus (RS-7 : « des input et output de logisim utilisables comme bions pour en faire un xer ») : les sorties du circuit ouvert
// partent en ploxion.logisim.sortie {circuit, broche, v, de} et ploxion.logisim.<broche> ; une sortie d'un ▣ circuit posé dans le xer
// qui porte le nom d'une de mes entrées la pilote (comme un tunnel entre ploxions)
var dejaDit = {}, offsBus = [];
function diffuser() {
var p = window.jOSPorts; if (!p || !st.sim) return;
var itf = C.interfaceDe(circ());
itf.sorties.forEach(function (pin, i) {
var v = st.sim.valeurDe(pin), n = C.nomBroche(pin, i), e = v ? C.entier(v) : null, k = st.cur + '/' + n;
if (dejaDit[k] === e) return; dejaDit[k] = e;
p.emit(ID, 'sortie', { circuit: st.cur, broche: n, v: e, de: 'logisim' }); p.emit(ID, n, e);
});
}
(function () {
var p = window.jOSPorts; if (!p) return;
offsBus.push(p.on('ploxion.circuit.sortie', function (d) {
if (!d || !st.sim || typeof d.broche !== 'string' || d.v === null || d.v === undefined) return;
var pin = C.interfaceDe(circ()).entrees.find(function (q, i) { return C.nomBroche(q, i) === d.broche; });
if (pin) { st.sim.poser(pin, +d.v); dessiner(); }
}));
})();
var raf = 0;
function dessiner() { if (raf) return; raf = requestAnimationFrame(function () { raf = 0; rendu(); }); }
function rendu() {
if (!st.projet) return;
var cc = circ(), z = st.vue.z, rect = plan.getBoundingClientRect();
var W = rect.width || 800, H = rect.height || 500;
var x0 = st.vue.x, y0 = st.vue.y, x1 = x0 + W / z, y1 = y0 + H / z;
var s = '<defs><pattern id="lgs-grille" width="10" height="10" patternUnits="userSpaceOnUse"><circle cx="0" cy="0" r="' + (z > .6 ? .9 : 0) + '" fill="var(--grille)"/></pattern></defs>';
s += '<g transform="scale(' + z + ') translate(' + (-x0) + ',' + (-y0) + ')">';
s += '<rect x="' + Math.floor(x0 / 10) * 10 + '" y="' + Math.floor(y0 / 10) * 10 + '" width="' + (x1 - x0 + 20) + '" height="' + (y1 - y0 + 20) + '" fill="url(#lgs-grille)"/>';
// fils
(cc.wires || []).forEach(function (wv, i) {
var v = st.sim ? st.sim.valeurEn(wv[0], wv[1], cheminInst()) : null, bus = v && v.length > 1;
s += '<line x1="' + wv[0] + '" y1="' + wv[1] + '" x2="' + wv[2] + '" y2="' + wv[3] + '" stroke="' + (st.sel.w[i] ? 'var(--selc)' : couleurBits(v)) + '" stroke-width="' + (bus ? 4 : 3) + '" stroke-linecap="round"/>';
});
// jonctions (3 bouts ou plus au même point, ou un bout sur un fil)
var cnt = {};
(cc.wires || []).forEach(function (wv) { [[wv[0], wv[1]], [wv[2], wv[3]]].forEach(function (p) { var k = p[0] + ',' + p[1]; cnt[k] = (cnt[k] || 0) + 1; (cc.wires || []).forEach(function (o) { if (o !== wv && C.surSegment(o, p[0], p[1])) cnt[k] = (cnt[k] || 0) + 2; }); }); });
for (var k in cnt) if (cnt[k] >= 3) { var p = k.split(','); var v2 = st.sim ? st.sim.valeurEn(+p[0], +p[1], cheminInst()) : null; s += '<circle cx="' + p[0] + '" cy="' + p[1] + '" r="3.5" fill="' + couleurBits(v2) + '"/>'; }
// composants
(cc.comps || []).forEach(function (c) { s += dessinComp(c, !!st.sel.c[c.id]); });
// ports
(cc.comps || []).forEach(function (c) { C.portsAbs(c, st.projet).forEach(function (p) { s += '<circle cx="' + p.x + '" cy="' + p.y + '" r="' + (p.d === 'out' ? 2 : 1.6) + '" fill="var(--doux2)"/>'; }); });
if (st.fil) s += '<polyline points="' + st.fil.pts.map(function (q) { return q.join(','); }).join(' ') + '" fill="none" stroke="var(--acc)" stroke-width="2.4" stroke-dasharray="5 4"/>';
if (st.filA) s += '<circle cx="' + st.filA[0] + '" cy="' + st.filA[1] + '" r="5" fill="none" stroke="var(--acc)" stroke-width="2"/>';
if (st.cadre) { var q = st.cadre; s += '<rect x="' + Math.min(q[0], q[2]) + '" y="' + Math.min(q[1], q[3]) + '" width="' + Math.abs(q[2] - q[0]) + '" height="' + Math.abs(q[3] - q[1]) + '" fill="rgba(63,224,208,.08)" stroke="var(--acc)" stroke-dasharray="4 3"/>'; }
if (st.fantome) s += '<g opacity=".55">' + dessinComp(st.fantome, false) + '</g>';
if (st.survol) s += '<circle cx="' + st.survol[0] + '" cy="' + st.survol[1] + '" r="6" fill="none" stroke="#ffd27a" stroke-width="1.5"/>';
s += '</g>';
svg.innerHTML = s;
var aide = $('[data-aide]');
aide.textContent = st.pose ? 'clique pour poser « ' + st.pose + ' » · Échap pour arrêter' : st.outil === 'poke' ? '☝ clique une entrée pour la basculer · glisse le fond pour te déplacer' : st.outil === 'fil' ? '╱ clique le départ puis l\'arrivée' : '✥ tire depuis un port pour câbler · molette = zoom · glisse le fond = sélection (Maj+glisser ou clic milieu = déplacer la vue)';
try { diffuser(); } catch (e) {}
if (st.sim && st.sim.oscille) aide.textContent = '△ le circuit oscille (boucle sans fin) — ' + aide.textContent;
}
// ------------------------------------------------------------ vue
function versPlan(ev) { var r = plan.getBoundingClientRect(); return [st.vue.x + (ev.clientX - r.left) / st.vue.z, st.vue.y + (ev.clientY - r.top) / st.vue.z]; }
function grille(p) { return [Math.round(p[0] / 10) * 10, Math.round(p[1] / 10) * 10]; }
function ajuster() {
if (!st.projet) return;
var cc = circ(), xs = [], ys = [];
(cc.comps || []).forEach(function (c) { var b = bornes(c); xs.push(b[0], b[2]); ys.push(b[1], b[3]); });
(cc.wires || []).forEach(function (wv) { xs.push(wv[0], wv[2]); ys.push(wv[1], wv[3]); });
var r = plan.getBoundingClientRect(), W = r.width || 800, H = r.height || 500;
if (!xs.length) { st.vue = { x: -40, y: -40, z: mobile() ? 1.2 : 1.4 }; dessiner(); return; }
var a = Math.min.apply(null, xs) - 40, b = Math.min.apply(null, ys) - 40, c2 = Math.max.apply(null, xs) + 40, d = Math.max.apply(null, ys) + 40;
var z = Math.max(.25, Math.min(2.2, Math.min(W / (c2 - a), H / (d - b))));
st.vue = { x: a - (W / z - (c2 - a)) / 2, y: b - (H / z - (d - b)) / 2, z: z };
dessiner();
}
function zoom(f, cx, cy) {
var r = plan.getBoundingClientRect(), px = cx === undefined ? r.width / 2 : cx - r.left, py = cy === undefined ? r.height / 2 : cy - r.top;
var wx = st.vue.x + px / st.vue.z, wy = st.vue.y + py / st.vue.z, z = Math.max(.2, Math.min(4, st.vue.z * f));
st.vue = { x: wx - px / z, y: wy - py / z, z: z }; dessiner();
}
// ------------------------------------------------------------ toucher / sélectionner
function compEn(p) {
var cs = circ().comps || [];
for (var i = cs.length - 1; i >= 0; i--) { var b = bornes(cs[i]); if (p[0] >= b[0] - 3 && p[0] <= b[2] + 3 && p[1] >= b[1] - 3 && p[1] <= b[3] + 3) return cs[i]; }
return null;
}
function filEn(p) {
var ws = circ().wires || [], tol = 5 / Math.min(1, st.vue.z);
for (var i = ws.length - 1; i >= 0; i--) {
var wv = ws[i], x0 = Math.min(wv[0], wv[2]), x1 = Math.max(wv[0], wv[2]), y0 = Math.min(wv[1], wv[3]), y1 = Math.max(wv[1], wv[3]);
if (p[0] >= x0 - tol && p[0] <= x1 + tol && p[1] >= y0 - tol && p[1] <= y1 + tol) return i;
}
return -1;
}
function pointAccroche(p) { // un port ou un bout de fil tout près
var tol = 8 / st.vue.z, best = null, bd = tol;
(circ().comps || []).forEach(function (c) { C.portsAbs(c, st.projet).forEach(function (q) { var d = Math.hypot(q.x - p[0], q.y - p[1]); if (d <= bd) { bd = d; best = [q.x, q.y]; } }); });
(circ().wires || []).forEach(function (wv) { [[wv[0], wv[1]], [wv[2], wv[3]]].forEach(function (q) { var d = Math.hypot(q[0] - p[0], q[1] - p[1]); if (d <= bd) { bd = d; best = q; } }); });
return best;
}
function chemin(a, b) { // en L : d'abord horizontal
if (a[0] === b[0] || a[1] === b[1]) return [a, b];
return [a, [b[0], a[1]], b];
}
// après un déplacement : fusionner les fils colinéaires bout à bout (sans rien au point commun) et retirer les doublons
function nettoyerFils() {
C.normaliserFils(circ(), st.projet); st.sel.w = {};
}
function ajouterFil(pts) {
var nv = [];
for (var i = 0; i + 1 < pts.length; i++) if (pts[i][0] !== pts[i + 1][0] || pts[i][1] !== pts[i + 1][1]) nv.push([pts[i][0], pts[i][1], pts[i + 1][0], pts[i + 1][1]]);
if (!nv.length) return;
changer(function () { circ().wires = (circ().wires || []).concat(nv); C.normaliserFils(circ(), st.projet); });
}
function poserComp(t, p) {
var c;
if (t.indexOf('bloc:') === 0) { c = C.comp('sub', p[0], p[1], { circuit: t.slice(5) }); if (t.slice(5) === st.cur) { toast('un circuit ne se contient pas lui-même'); return; } }
else if (t.indexOf('bib:') === 0) { var nom = importerDeBiblio(t.slice(4)); if (!nom) return; c = C.comp('sub', p[0], p[1], { circuit: nom }); }
else {
c = C.comp(t, p[0], p[1]);
if (t === 'pin' && st.poseSortie) { c.a.output = true; c.a.facing = 'west'; }
if (t === 'pin') { var n = (circ().comps || []).filter(function (x) { return x.t === 'pin' && !!x.a.output === !!c.a.output; }).length; c.a.label = (c.a.output ? 'S' : 'E') + n; }
}
changer(function () { circ().comps.push(c); });
st.sel = { c: {}, w: {} }; st.sel.c[c.id] = 1; panneaux(); dessiner();
}
function selection() { return (circ().comps || []).filter(function (c) { return st.sel.c[c.id]; }); }
function supprimer() {
var n = Object.keys(st.sel.c).length + Object.keys(st.sel.w).length; if (!n) return;
changer(function () {
circ().comps = circ().comps.filter(function (c) { return !st.sel.c[c.id]; });
circ().wires = circ().wires.filter(function (wv, i) { return !st.sel.w[i]; });
});
st.sel = { c: {}, w: {} }; panneaux(); dessiner();
}
function tourner() {
var cs = selection().filter(function (c) { return c.a.facing !== undefined && ['add', 'sub', 'mul', 'neg', 'cmp', 'dff', 'tff', 'jkff', 'srff', 'reg', 'counter', 'hex', 'seg7', 'text'].indexOf(c.t) < 0; });
if (!cs.length) return;
changer(function () { cs.forEach(function (c) { var i = C.DIRS.indexOf(c.a.facing || 'east'); c.a.facing = C.DIRS[(i + 1) % 4]; }); }, cs);
}
// COPIER-COLLER (RS-7 : « qu'on puisse copier coller correctement ») : les pièces choisies, les fils choisis ET les fils qui ne relient
// que des pièces choisies (un nœud qui touche une pièce non choisie reste) ; les blocs emportent leurs circuits ; le presse-papiers vit
// dans le navigateur (d'un circuit à l'autre, d'un projet à l'autre, d'un onglet à l'autre) ; on colle là où est la souris
var pressePapier = null;
function copier(couper) {
var cs = selection(), cc = circ(), ws = (cc.wires || []).filter(function (wv, i) { return st.sel.w[i]; });
if (!cs.length && !ws.length) return;
var nds = C.noeuds(cc, st.projet), R0 = function (x, y) { return nds[C.cle(x, y)] || C.cle(x, y); }, choisi = {}, autre = {}, avecFil = {};
(cc.comps || []).forEach(function (c) { C.portsAbs(c, st.projet).forEach(function (q) { var r = R0(q.x, q.y); if (st.sel.c[c.id]) choisi[r] = (choisi[r] || 0) + 1; else autre[r] = 1; }); });
ws.forEach(function (wv) { avecFil[R0(wv[0], wv[1])] = 1; });
(cc.wires || []).forEach(function (wv, i) { if (st.sel.w[i]) return; var r = R0(wv[0], wv[1]); if (!autre[r] && ((choisi[r] || 0) >= 2 || (choisi[r] && avecFil[r]))) ws.push(wv.slice()); });
var circuits = {}; (function besoin(liste) { liste.forEach(function (c) { if (c.t === 'sub' && !circuits[c.a.circuit] && st.projet.circuits[c.a.circuit]) { circuits[c.a.circuit] = st.projet.circuits[c.a.circuit]; besoin(st.projet.circuits[c.a.circuit].comps || []); } }); })(cs);
var xs = [], ys = []; cs.forEach(function (c) { var b = bornes(c); xs.push(b[0]); ys.push(b[1]); }); ws.forEach(function (wv) { xs.push(Math.min(wv[0], wv[2])); ys.push(Math.min(wv[1], wv[3])); });
pressePapier = JSON.stringify({ jOSCircuit: 1, de: st.cur, comps: cs, wires: ws, circuits: circuits, x: Math.floor(Math.min.apply(null, xs) / 10) * 10, y: Math.floor(Math.min.apply(null, ys) / 10) * 10 });
ls('xb:logisim:pp', pressePapier);
try { if (navigator.clipboard && window.isSecureContext) navigator.clipboard.writeText(pressePapier).catch(function () {}); } catch (e) {}
toast((couper ? '✂ ' : '⎘ ') + cs.length + ' pièce(s), ' + ws.length + ' fil(s)' + (couper ? ' coupés' : ' copiés'));
if (couper) supprimer();
}
function contient(n, cible, vus) { vus = vus || {}; if (vus[n]) return false; vus[n] = 1; var cc = st.projet.circuits[n]; return !!cc && (cc.comps || []).some(function (x) { return x.t === 'sub' && (x.a.circuit === cible || contient(x.a.circuit, cible, vus)); }); }
function coller(ici) {
var pp = null; try { pp = JSON.parse(ls('xb:logisim:pp') || pressePapier || 'null'); } catch (e) {}
if (!pp || !pp.comps) { toast('rien à coller'); return; }
var cible = ici === 'decale' ? [pp.x + 20, pp.y + 20] : ici || st.souris || [pp.x + 20, pp.y + 20], dx = Math.round((cible[0] - pp.x) / 10) * 10, dy = Math.round((cible[1] - pp.y) / 10) * 10, ids = {}, wsel = {}, refus = 0;
if (pp.de === st.cur && dx === 0 && dy === 0) { dx = 20; dy = 20; }
changer(function () {
Object.keys(pp.circuits || {}).forEach(function (n) { if (!st.projet.circuits[n]) { var x = JSON.parse(JSON.stringify(pp.circuits[n])); x.nom = n; st.projet.circuits[n] = x; } });
pp.comps.forEach(function (c) {
if (c.t === 'sub' && (c.a.circuit === st.cur || contient(c.a.circuit, st.cur))) { refus++; return; }
var n = C.comp(c.t, c.x + dx, c.y + dy, c.a); if (c.meta) { n.meta = Object.assign({}, c.meta, n.meta || {}); delete n.meta.integrity; } if (c.raw) { n.raw = c.raw; n.lib = c.lib; n.libDesc = c.libDesc; n.circName = c.circName; n.ports = c.ports; }
ids[n.id] = 1; circ().comps.push(n);
});
(pp.wires || []).forEach(function (wv) { wsel[circ().wires.length] = 1; circ().wires.push([wv[0] + dx, wv[1] + dy, wv[2] + dx, wv[3] + dy]); });
});
st.sel = { c: ids, w: wsel }; panneaux(); dessiner();
if (refus) toast('un bloc ne peut pas se contenir lui-même : ' + refus + ' laissé(s)');
}
var geste = null, touches = {};
// le déplacement part TOUJOURS de l'état d'origine (pas de coudes empilés) : pièces et fils choisis translatés, et chaque fil non choisi
// dont un bout touche ce qui bouge (un port d'une pièce choisie, un bout d'un fil choisi) est étiré : le bout suit, un coude garde l'angle droit
function debutDeplacer(g) {
var pos = {}, ancres = {}, cc = circ();
selection().forEach(function (c) { pos[c.id] = [c.x, c.y]; C.portsAbs(c, st.projet).forEach(function (q) { ancres[q.x + ',' + q.y] = 1; }); });
cc.wires.forEach(function (wv, i) { if (st.sel.w[i]) { ancres[wv[0] + ',' + wv[1]] = 1; ancres[wv[2] + ',' + wv[3]] = 1; } });
return { type: 'deplacer', d: g, dx: 0, dy: 0, avant: instantane(), pos: pos, fils: cc.wires.map(function (wv) { return wv.slice(); }), selW: Object.assign({}, st.sel.w), ancres: ancres };
}
function appliquerDeplacer(G, dx, dy) {
var cc = circ(), nv = [], sel = {};
selection().forEach(function (c) { var o = G.pos[c.id]; if (o) { c.x = o[0] + dx; c.y = o[1] + dy; } });
G.fils.forEach(function (wv, i) {
if (G.selW[i]) { sel[nv.length] = 1; nv.push([wv[0] + dx, wv[1] + dy, wv[2] + dx, wv[3] + dy]); return; }
var a = G.ancres[wv[0] + ',' + wv[1]], b = G.ancres[wv[2] + ',' + wv[3]];
if (a && b) { nv.push([wv[0] + dx, wv[1] + dy, wv[2] + dx, wv[3] + dy]); return; }
if (!a && !b) { nv.push(wv.slice()); return; }
var F = a ? [wv[2], wv[3]] : [wv[0], wv[1]], M = a ? [wv[0] + dx, wv[1] + dy] : [wv[2] + dx, wv[3] + dy], horiz = wv[1] === wv[3];
var coude = horiz ? [M[0], F[1]] : [F[0], M[1]];
[[F, coude], [coude, M]].forEach(function (sg) { if (sg[0][0] !== sg[1][0] || sg[0][1] !== sg[1][1]) nv.push([sg[0][0], sg[0][1], sg[1][0], sg[1][1]]); });
});
cc.wires = nv; st.sel.w = sel;
}
plan.addEventListener('pointerdown', function (ev) {
if (!st.projet) return;
try { plan.setPointerCapture(ev.pointerId); } catch (e0) {}
touches[ev.pointerId] = [ev.clientX, ev.clientY];
var ids = Object.keys(touches);
if (ids.length === 2) { var a = touches[ids[0]], b = touches[ids[1]]; geste = { type: 'pince', d: Math.hypot(a[0] - b[0], a[1] - b[1]), m: [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2], vue: Object.assign({}, st.vue) }; st.fil = null; st.cadre = null; return; }
var p = versPlan(ev), g = grille(p);
if (ev.button === 2) { clearTimeout(st.tLong); return; }
if (ev.button === 1 || (ev.shiftKey && !st.pose)) { geste = { type: 'pan', d: [ev.clientX, ev.clientY], vue: Object.assign({}, st.vue) }; ev.preventDefault(); return; }
if (st.pose) { poserComp(st.pose, g); if (mobile() || !ev.ctrlKey && st.pose.indexOf('bib:') === 0) st.pose = null; st.fantome = null; panneaux(); dessiner(); return; }
var cLong = compEn(p), wLong = cLong ? -1 : filEn(p), tactile = ev.pointerType === 'touch';
if ((cLong || wLong >= 0) && !st.pose) {
var x0p = ev.clientX, y0p = ev.clientY; clearTimeout(st.tLong);
st.tLong = setTimeout(function () {
if (geste && geste.type === 'deplacer' && geste.bouge) return;
if (geste && geste.type === 'deplacer' && geste.avant) { /* rien n'a bougé : pas d'historique */ }
geste = null; st.cadre = null; st.fil = null;
if (cLong && cLong.t === 'sub' && !tactile) entrer(cLong);
else menu(x0p, y0p, cLong ? { c: cLong } : { w: wLong });
try { if (navigator.vibrate) navigator.vibrate(15); } catch (e) {}
}, 520);
st.longDe = [x0p, y0p];
}
if (st.outil === 'poke') {
var c0 = compEn(p);
if (c0 && cheminInst() && c0.t === 'pin') { toast('dans une instance : ses entrées viennent du circuit parent (remonte avec le fil d\'Ariane)'); return; }
if (c0 && st.sim && c0.t === 'dip') { var qs = C.portsAbs(c0, st.projet), ib = 0, db = 1e9; qs.forEach(function (q, i) { var dd = Math.hypot(q.x - p[0], q.y - p[1]); if (dd < db) { db = dd; ib = i; } }); st.sim.basculerBit(c0, ib); echantillon('geste'); dessiner(); bas(); return; }
if (c0 && (c0.t === 'ram' || c0.t === 'rom')) { st.memId = c0.id; montrerMem(); return; }
if (c0 && c0.t === 'keyboard') { st.clavier = c0.id; toast('clavier : tape, Entrée, ← ; Échap pour arrêter'); dessiner(); return; }
if (st.clavier) { st.clavier = null; dessiner(); }
if (c0 && st.sim && ((c0.t === 'pin' && !c0.a.output) || c0.t === 'button' || c0.t === 'clock')) { st.sim.basculer(c0); echantillon('geste'); if (c0.t === 'button') geste = { type: 'bouton', c: c0 }; dessiner(); bas(); return; }
geste = { type: 'pan', d: [ev.clientX, ev.clientY], vue: Object.assign({}, st.vue) }; return;
}
if (st.outil === 'fil') {
var q = pointAccroche(p) || g;
if (!st.filA) { st.filA = q; dessiner(); return; }
ajouterFil(chemin(st.filA, q)); st.filA = null; dessiner(); return;
}
// éditer
var acc = pointAccroche(p), c = compEn(p);
var surPortDeC = acc && (!c || C.portsAbs(c, st.projet).some(function (q) { return q.x === acc[0] && q.y === acc[1]; }) || !c);
if (acc && (surPortDeC || !c)) { geste = { type: 'fil', a: acc }; st.fil = { pts: [acc] }; return; }
if (c) {
if (!st.sel.c[c.id] && !(ev.ctrlKey || ev.metaKey)) st.sel = { c: {}, w: {} };
if (ev.ctrlKey || ev.metaKey) { if (st.sel.c[c.id]) delete st.sel.c[c.id]; else st.sel.c[c.id] = 1; } else st.sel.c[c.id] = 1;
geste = debutDeplacer(g);
panneaux(); dessiner(); return;
}
var wi = filEn(p);
if (wi >= 0) {
if (!(ev.ctrlKey || ev.metaKey)) st.sel = { c: {}, w: {} };
st.sel.w[wi] = 1; geste = debutDeplacer(g); panneaux(); dessiner(); return;
}
st.sel = { c: {}, w: {} }; panneaux();
if (ev.pointerType === 'touch') { geste = { type: 'pan', d: [ev.clientX, ev.clientY], vue: Object.assign({}, st.vue) }; dessiner(); return; }
geste = { type: 'cadre' }; st.cadre = [p[0], p[1], p[0], p[1]]; dessiner();
});
plan.addEventListener('pointermove', function (ev) {
if (touches[ev.pointerId]) touches[ev.pointerId] = [ev.clientX, ev.clientY];
if (st.tLong && st.longDe && Math.hypot(ev.clientX - st.longDe[0], ev.clientY - st.longDe[1]) > 6) { clearTimeout(st.tLong); st.tLong = null; }
var p = versPlan(ev), g = grille(p);
st.souris = g;
if (!geste) {
if (st.pose) { var t = st.pose; st.fantome = t.indexOf(':') < 0 ? C.comp(t, g[0], g[1], t === 'pin' && st.poseSortie ? { output: true, facing: 'west' } : {}) : t.indexOf('bloc:') === 0 ? { id: '_', t: 'sub', x: g[0], y: g[1], a: { circuit: t.slice(5) } } : null; dessiner(); }
else if (st.outil !== 'poke') { var acc = pointAccroche(p); var s0 = st.survol; st.survol = acc; if (String(s0) !== String(acc)) dessiner(); }
return;
}
if (geste.type === 'pince') {
var ids = Object.keys(touches); if (ids.length < 2) return;
var a = touches[ids[0]], b = touches[ids[1]], d = Math.hypot(a[0] - b[0], a[1] - b[1]), m = [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2], r = plan.getBoundingClientRect();
var z = Math.max(.2, Math.min(4, geste.vue.z * d / geste.d));
var wx = geste.vue.x + (geste.m[0] - r.left) / geste.vue.z, wy = geste.vue.y + (geste.m[1] - r.top) / geste.vue.z;
st.vue = { x: wx - (m[0] - r.left) / z, y: wy - (m[1] - r.top) / z, z: z }; dessiner(); return;
}
if (geste.type === 'pan') { st.vue.x = geste.vue.x - (ev.clientX - geste.d[0]) / st.vue.z; st.vue.y = geste.vue.y - (ev.clientY - geste.d[1]) / st.vue.z; dessiner(); return; }
if (geste.type === 'fil') { st.fil = { pts: chemin(geste.a, pointAccroche(p) || g) }; dessiner(); return; }
if (geste.type === 'cadre') { st.cadre[2] = p[0]; st.cadre[3] = p[1]; dessiner(); return; }
if (geste.type === 'deplacer') {
var dx = g[0] - geste.d[0], dy = g[1] - geste.d[1]; if (dx === geste.dx && dy === geste.dy) return;
geste.dx = dx; geste.dy = dy; geste.bouge = true; appliquerDeplacer(geste, dx, dy); dessiner();
}
});
function finGeste(ev) {
delete touches[ev.pointerId]; clearTimeout(st.tLong); st.tLong = null;
if (!geste) return;
var g0 = geste; geste = null;
if (g0.type === 'bouton' && st.sim) { st.sim.basculer(g0.c); echantillon('geste'); dessiner(); bas(); return; }
if (g0.type === 'fil') { var pts = st.fil ? st.fil.pts : null; st.fil = null; if (pts && pts.length > 1) ajouterFil(pts); else dessiner(); return; }
if (g0.type === 'cadre') {
var q = st.cadre; st.cadre = null;
var x0 = Math.min(q[0], q[2]), x1 = Math.max(q[0], q[2]), y0 = Math.min(q[1], q[3]), y1 = Math.max(q[1], q[3]);
if (x1 - x0 > 4 || y1 - y0 > 4) {
circ().comps.forEach(function (c) { var b = bornes(c); if (b[0] >= x0 && b[2] <= x1 && b[1] >= y0 && b[3] <= y1) st.sel.c[c.id] = 1; });
circ().wires.forEach(function (wv, i) { if (Math.min(wv[0], wv[2]) >= x0 && Math.max(wv[0], wv[2]) <= x1 && Math.min(wv[1], wv[3]) >= y0 && Math.max(wv[1], wv[3]) <= y1) st.sel.w[i] = 1; });
}
panneaux(); dessiner(); return;
}
if (g0.type === 'deplacer' && g0.bouge) { nettoyerFils(); st.histo.push(g0.avant); st.futur = []; modifie(selection()); reconstruire(); sauver(); dessiner(); bas(); }
}
plan.addEventListener('pointerup', finGeste);
function menu(x, y, cible) {
var anc = R.querySelector('.lgs__menu'); if (anc) anc.remove();
var m = document.createElement('div'); m.className = 'lgs__menu'; m.setAttribute('role', 'menu');
var acts = [];
if (cible.c) {
var c = cible.c, d = C.T[c.t] || {};
st.sel = { c: {}, w: {} }; st.sel.c[c.id] = 1; panneaux(); dessiner();
if (c.t === 'sub') acts.push(['entrer', '↳ entrer dans ' + c.a.circuit]);
if (c.t === 'pin' && !c.a.output && !cheminInst()) acts.push(['basculer', '⊙ basculer la valeur']);
acts.push(['etiquette', '✎ ' + (c.t === 'text' ? 'texte' : 'étiquette')], ['proprietes', '◫ propriétés']);
if (c.a.facing !== undefined) acts.push(['tourner', '⟳ tourner']);
acts.push(['dupliquer', '⧉ dupliquer'], ['copier', '⎘ copier'], ['supprimer', '✕ supprimer']);
m.innerHTML = '<b>' + esc((d.circ || c.a.circuit || c.t) + (c.a.label ? ' « ' + c.a.label + ' »' : '')) + '</b>';
} else {
st.sel = { c: {}, w: {} }; st.sel.w[cible.w] = 1; panneaux(); dessiner();
acts.push(['supprimer', '✕ supprimer ce fil'], ['supprimerTout', '✕ supprimer tout le fil relié']);
m.innerHTML = '<b>fil</b>';
}
acts.forEach(function (a) { var b = document.createElement('button'); b.setAttribute('role', 'menuitem'); b.setAttribute('data-menu', a[0]); if (/^supprimer/.test(a[0])) b.className = 'danger'; b.textContent = a[1]; m.appendChild(b); });
R.appendChild(m);
var Rr = R.getBoundingClientRect(), mw = m.offsetWidth || 220, mh = m.offsetHeight || 240;
m.style.left = Math.max(6, Math.min(x - Rr.left, Rr.width - mw - 6)) + 'px'; m.style.top = Math.max(6, Math.min(y - Rr.top, Rr.height - mh - 6)) + 'px';
var b0 = m.querySelector('button'); if (b0) b0.focus();
m.addEventListener('keydown', function (ev) { if (ev.key === 'Escape') m.remove(); });
m.addEventListener('click', function (ev) {
var b = ev.target.closest('[data-menu]'); if (!b) return; var k = b.getAttribute('data-menu'), c = cible.c; m.remove();
if (k === 'entrer') entrer(c);
else if (k === 'basculer' && st.sim) { st.sim.basculer(c); dessiner(); bas(); }
else if (k === 'etiquette') editerEtiquette(c);
else if (k === 'proprietes') { if (mobile()) { R.classList.add('feuille-d'); R.classList.remove('feuille-g'); } else R.classList.remove('sans-d'); panneauD(); }
else if (k === 'tourner') tourner();
else if (k === 'dupliquer') { copier(); coller('decale'); }
else if (k === 'copier') copier();
else if (k === 'supprimer') supprimer();
else if (k === 'supprimerTout') { // tout le fil relié : les segments du même nœud
var nds = C.noeuds(circ(), st.projet), wv = circ().wires[cible.w], r0 = nds[C.cle(wv[0], wv[1])];
circ().wires.forEach(function (w2, i) { if (nds[C.cle(w2[0], w2[1])] === r0) st.sel.w[i] = 1; }); supprimer();
}
});
setTimeout(function () { document.addEventListener('pointerdown', function hors(ev) { if (!m.contains(ev.target)) { m.remove(); document.removeEventListener('pointerdown', hors, true); } }, true); }, 0);
}
function editerEtiquette(c) {
var anc = R.querySelector('.lgs__lab'); if (anc) anc.remove();
var b = bornes(c), r = plan.getBoundingClientRect(), Rr = R.getBoundingClientRect(), z = st.vue.z, k = c.t === 'text' ? 'text' : 'label';
var inp = document.createElement('input'); inp.className = 'lgs__lab'; inp.value = c.a[k] || ''; inp.placeholder = k === 'text' ? 'texte' : 'étiquette';
inp.style.left = Math.max(4, (r.left - Rr.left) + (b[0] - st.vue.x) * z) + 'px'; inp.style.top = Math.max(4, (r.top - Rr.top) + (b[1] - st.vue.y) * z - 34) + 'px';
R.appendChild(inp); inp.focus(); inp.select();
var fini = false;
function fin(garder) { if (fini) return; fini = true; var v = inp.value; inp.remove(); if (garder && v !== (c.a[k] || '')) changer(function () { c.a[k] = v; }, [c]); }
inp.addEventListener('keydown', function (ev) { ev.stopPropagation(); if (ev.key === 'Enter') fin(true); else if (ev.key === 'Escape') fin(false); });
inp.addEventListener('blur', function () { fin(true); });
}
var dernierTap = { t: 0, id: null };
plan.addEventListener('dblclick', function (ev) {
if (st.outil !== 'edit' || st.pose) return;
var c = compEn(versPlan(ev)); if (c) { ev.preventDefault(); editerEtiquette(c); }
});
plan.addEventListener('pointerup', function (ev) { // le double-tap au téléphone
if (ev.pointerType !== 'touch' || st.outil !== 'edit') return;
var c = compEn(versPlan(ev)), t = Date.now();
if (c && dernierTap.id === c.id && t - dernierTap.t < 350) { editerEtiquette(c); dernierTap = { t: 0, id: null }; } else dernierTap = { t: t, id: c ? c.id : null };
});
plan.addEventListener('pointercancel', finGeste);
plan.addEventListener('contextmenu', function (ev) { // clic droit = le menu (comme Logisim)
ev.preventDefault(); clearTimeout(st.tLong); geste = null;
var p = versPlan(ev), c = compEn(p), wi = c ? -1 : filEn(p);
if (c || wi >= 0) menu(ev.clientX, ev.clientY, c ? { c: c } : { w: wi });
});
plan.addEventListener('wheel', function (ev) { ev.preventDefault(); if (ev.ctrlKey || Math.abs(ev.deltaY) >= Math.abs(ev.deltaX)) zoom(Math.pow(1.0015, -ev.deltaY), ev.clientX, ev.clientY); else { st.vue.x += ev.deltaX / st.vue.z; dessiner(); } }, { passive: false });
plan.addEventListener('dragover', function (ev) { ev.preventDefault(); });
plan.addEventListener('drop', function (ev) { ev.preventDefault(); var f = ev.dataTransfer.files && ev.dataTransfer.files[0]; if (!f) return; if (/\.pdf$/i.test(f.name) || f.type === 'application/pdf') ouvrirPdf(f); else lireCirc(f); });
R.addEventListener('keydown', function (ev) { if ((ev.key === 'Enter' || ev.key === ' ') && ev.target.classList && ev.target.classList.contains('lgs__it')) { ev.preventDefault(); ev.target.click(); } });
function surTouche(ev) {
if (!R.isConnected) return;
var t = ev.target; if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.tagName === 'SELECT')) return;
if (!R.contains(document.activeElement) && document.activeElement !== document.body) return;
var k = ev.key.toLowerCase(), mod = ev.ctrlKey || ev.metaKey;
if (st.clavier && st.outil === 'poke' && !mod) { // le Keyboard de Logisim : les touches vont dans son tampon
var ck = (circ().comps || []).find(function (c) { return c.id === st.clavier; }), itc = ck && itDe(ck);
if (!ck || ev.key === 'Escape') { st.clavier = null; dessiner(); return; }
var code = ev.key === 'Enter' ? 13 : ev.key === 'Backspace' ? 8 : ev.key === 'Tab' ? 9 : ev.key.length === 1 ? ev.key.charCodeAt(0) : -1;
if (code < 0 || !itc) return;
ev.preventDefault(); C.T.keyboard.taper(itc.st, code, ck); st.sim.propager(); echantillon('geste'); dessiner(); return;
}
if (mod && k === 'z') { ev.preventDefault(); ev.shiftKey ? refaire() : annuler(); }
else if (mod && k === 'y') { ev.preventDefault(); refaire(); }
else if (mod && k === 'c') copier();
else if (mod && k === 'x') { ev.preventDefault(); copier(true); }
else if (mod && k === 'v') coller();
else if (mod && k === 'd') { ev.preventDefault(); copier(); coller('decale'); }
else if (mod && k === 'a') { ev.preventDefault(); st.sel = { c: {}, w: {} }; (circ().comps || []).forEach(function (c) { st.sel.c[c.id] = 1; }); (circ().wires || []).forEach(function (wv, i) { st.sel.w[i] = 1; }); panneaux(); dessiner(); }
else if (mod && k === 's') { ev.preventDefault(); exporterCirc(); }
else if (k === 'delete' || k === 'backspace') { ev.preventDefault(); supprimer(); }
else if (k === 'escape') { st.pose = null; st.fantome = null; st.filA = null; st.fil = null; st.sel = { c: {}, w: {} }; panneaux(); dessiner(); }
else if (k === 'r' && !mod) tourner();
else if (k === 'e' && !mod) outil('edit');
else if (k === 't' && !mod) outil('poke');
else if (k === 'w' && !mod) outil('fil');
else if (k === 'f' && !mod) ajuster();
else if (k.indexOf('arrow') === 0 && selection().length) {
ev.preventDefault(); var d = { arrowleft: [-10, 0], arrowright: [10, 0], arrowup: [0, -10], arrowdown: [0, 10] }[k];
changer(function () { selection().forEach(function (c) { c.x += d[0]; c.y += d[1]; }); }, selection());
}
}
document.addEventListener('keydown', surTouche);
function outil(o) { st.outil = o; st.pose = null; st.fantome = null; st.filA = null; R.querySelectorAll('[data-outil]').forEach(function (b) { b.classList.toggle('on', b.getAttribute('data-outil') === o); }); var m = $('[data-mob="outil"]'); if (m) m.textContent = o === 'edit' ? '✥ éditer' : o === 'poke' ? '☝ toucher' : '╱ fil'; dessiner(); }
// ------------------------------------------------------------ panneau gauche : projet, pièces, bibliothèque
var catOuverte = JSON.parse(ls('xb:logisim:cats') || '{"cablage":1,"portes":1}');
function panneauG() {
var p = st.projet, h = '<div class="lgs__h">circuits<button data-act="bloc" title="un bloc conceptuel : entrées, sorties, sa table">□ bloc</button><button data-act="formule" title="un circuit depuis une formule">ƒ</button><button data-act="nvcirc" title="un circuit vide">✚</button></div>';
Object.keys(p.circuits).forEach(function (n) {
var c = p.circuits[n], itf = C.interfaceDe(c);
h += '<div class="lgs__it' + (n === st.cur ? ' on' : '') + '" data-circ="' + esc(n) + '"><i>' + (n === p.main ? '◆' : c.mode === 'table' ? '□' : '▣') + '</i>' + esc(n) + '<small>' + itf.entrees.length + '→' + itf.sorties.length + '</small></div>';
});
// l'arbre : la hiérarchie des instances depuis la racine (où l'on est, parmi tous les circuits reliés)
var rac = racineNom(), lignesA = [], compte = 0;
(function arbre(nom, ch, prof, vus) {
var cc = p.circuits[nom]; if (!cc || prof > 8 || compte > 120) return;
(cc.comps || []).filter(function (x) { return x.t === 'sub'; }).forEach(function (x) {
if (vus.indexOf(x.a.circuit) >= 0) return; compte++;
var ch2 = ch + '/' + x.id, ici = cheminInst() === ch2;
lignesA.push('<div class="lgs__it' + (ici ? ' on' : '') + '" data-arbre="' + esc(ch2) + '" style="padding-left:' + (12 + prof * 14) + 'px"><i>▣</i>' + esc(x.a.label ? x.a.label + ' : ' + x.a.circuit : x.a.circuit) + '</div>');
arbre(x.a.circuit, ch2, prof + 1, vus.concat([x.a.circuit]));
});
})(rac, '', 0, [rac]);
if (lignesA.length) h += '<div class="lgs__h">hiérarchie de ' + esc(rac) + '</div><div class="lgs__arbre"><div class="lgs__it' + (!cheminInst() ? ' on' : '') + '" data-arbre=""><i>◆</i>' + esc(rac) + '</div>' + lignesA.join('') + '</div>';
h += '<div class="lgs__h">pièces</div>';
C.CATS.forEach(function (cat) {
h += '<div class="lgs__cat" data-cat="' + cat[0] + '">' + (catOuverte[cat[0]] ? '▾ ' : '▸ ') + esc(cat[1]) + '</div>';
if (!catOuverte[cat[0]]) return;
cat[2].forEach(function (t) {
// les NOMS DE LOGISIM, en anglais comme dans sa palette (RS-7 : « je veux les xor, or, and… là c'est en français, ça marche pas »)
var d = C.T[t], nom = t === 'pin' ? 'Pin (input)' : d.circ || t;
var bulle = { xnor: 'XNOR = équivalence (le « XAND ») : 1 quand les entrées sont égales', xor: 'XOR : à plus de 2 entrées, 1 quand EXACTEMENT une est à 1 (Logisim)', odd: '1 quand un nombre impair d\'entrées est à 1', tri: 'Controlled Buffer : passe quand EN = 1, sinon flottant (Z)' }[t] || '';
h += '<div class="lgs__it' + (st.pose === t && !(t === 'pin' && st.poseSortie) ? ' on' : '') + '" data-pose="' + t + '"' + (bulle ? ' title="' + esc(bulle) + '"' : '') + '><i>' + esc(d.g) + '</i>' + esc(nom) + '</div>';
if (t === 'pin') h += '<div class="lgs__it' + (st.pose === 'pin' && st.poseSortie ? ' on' : '') + '" data-pose="pin" data-sortie="1"><i>◨</i>Pin (output)</div>';
});
});
h += '<div class="lgs__cat" data-cat="blocs">' + (catOuverte.blocs !== 0 ? '▾ ' : '▸ ') + 'blocs du projet</div>';
if (catOuverte.blocs !== 0) Object.keys(p.circuits).forEach(function (n) { if (n !== st.cur) h += '<div class="lgs__it' + (st.pose === 'bloc:' + n ? ' on' : '') + '" data-pose="bloc:' + esc(n) + '"><i>▣</i>' + esc(n) + '</div>'; });
h += '<div class="lgs__h">⧉ ma bibliothèque<button data-act="publier" title="mettre ce circuit (et ses blocs) dans ma bibliothèque">↑ ce bloc</button></div>';
var bib = st.biblio;
if (!bib) h += '<div class="lgs__note">' + (B() ? '…' : 'connecte-toi pour garder ta bibliothèque dans ton compte') + '</div>';
else {
var noms = Object.keys(bib.blocs || {}).sort();
if (!noms.length) h += '<div class="lgs__note">vide — « ↑ ce bloc » y range le circuit ouvert (avec ses sous-blocs, son auteur, sa table)</div>';
noms.forEach(function (n) { var b = bib.blocs[n]; h += '<div class="lgs__it' + (st.pose === 'bib:' + n ? ' on' : '') + '" data-pose="bib:' + esc(n) + '" title="' + esc((b.desc || '') + (b.auteur ? ' · ' + b.auteur : '')) + '"><i>⧉</i>' + esc(n) + '<small data-bibsuppr="' + esc(n) + '" title="retirer">✕</small></div>'; });
(bib.liees || []).forEach(function (l, i) { h += '<div class="lgs__cat">⧉ ' + esc(l.nom) + ' <small data-delier="' + i + '" title="délier">✕</small></div>'; Object.keys(l.projet.circuits).forEach(function (n) { h += '<div class="lgs__it" data-pose="lie:' + i + ':' + esc(n) + '"><i>▣</i>' + esc(n) + '</div>'; }); });
}
h += '<div class="lgs__note"><button data-act="lier" title="une bibliothèque existante (.circ) : ses circuits deviennent des pièces">⧉ lier une bibliothèque .circ</button></div>';
$('[data-g]').innerHTML = h;
}
// ------------------------------------------------------------ panneau droit : attributs
// les attributs, sous les NOMS DE LOGISIM (comme son panneau « Properties »)
var CHAMPS = {
facing: ['Facing', ['east', 'south', 'west', 'north'], { east: 'East', south: 'South', west: 'West', north: 'North' }],
width: ['Data Bits', 'n'], inputs: ['Number Of Inputs', 'n'], size: ['Gate Size', [30, 50, 70], { 30: 'Narrow', 50: 'Medium', 70: 'Wide' }], label: ['Label', 't'], output: ['Output?', 'b'],
value: ['Value', 'n'], select: ['Select Bits', 'n'], selloc: ['Select Location', ['bl', 'tr'], { bl: 'Bottom/Left', tr: 'Top/Right' }],
enable: ['Include Enable?', 'b'], disabled: ['Disabled Output', ['0', 'Z'], { 0: 'Zero', Z: 'Floating' }],
mode: ['Numeric Type', ['unsigned', 'twosComplement'], { unsigned: 'Unsigned', twosComplement: "2's Complement" }], trigger: ['Trigger', ['rising', 'falling', 'high', 'low'], { rising: 'Rising Edge', falling: 'Falling Edge', high: 'High Level', low: 'Low Level' }],
fanout: ['Fan Out', 'n'], incoming: ['Bit Width In', 'n'], appear: ['Appearance', ['left', 'right', 'center', 'legacy'], { left: 'Left-handed', right: 'Right-handed', center: 'Centered', legacy: 'Legacy' }], spacing: ['Spacing', 'n'],
max: ['Maximum Value', 'n'], text: ['Text', 't'], color: ['On Color', 't'],
pull: ['Pull Direction', ['0', '1', 'X'], { 0: 'Zero', 1: 'One', X: 'Error' }], in_width: ['Bit Width In', 'n'], out_width: ['Bit Width Out', 'n'],
shift: ['Shift Type', ['ll', 'lr', 'ar', 'rl', 'rr'], { ll: 'Logical Left', lr: 'Logical Right', ar: 'Arithmetic Right', rl: 'Rotate Left', rr: 'Rotate Right' }],
seed: ['Seed', 'n'], type: ['Type', ['sign', 'zero', 'one', 'input', 'low1', 'high1', 'low0', 'high0'], { sign: 'Sign', zero: 'Zero', one: 'One', input: 'Input', low1: 'Lowest-order 1', high1: 'Highest-order 1', low0: 'Lowest-order 0', high0: 'Highest-order 0' }],
behavior: ['Behavior', ['simple', 'tristate', 'pulldown', 'pullup'], { simple: 'Simple', tristate: 'Tri-state', pulldown: 'Pull Down', pullup: 'Pull Up' }],
radix: ['Radix', ['2', '8', '10signed', '10unsigned', '16'], { 2: 'Binary', 8: 'Octal', '10signed': 'Signed Decimal', '10unsigned': 'Unsigned Decimal', 16: 'Hexadecimal' }],
labelloc: ['Label Location', ['north', 'south', 'east', 'west'], { north: 'North', south: 'South', east: 'East', west: 'West' }],
labelfont: ['Label Font', 't'], initial: ['Reset value', 'n'],
control: ['Control Line', ['right', 'left'], { right: 'Right-handed', left: 'Left-handed' }],
appearance: ['Appearance', ['classic', 'NewPins', 'logisim_evolution'], { classic: 'Classic Logisim', NewPins: 'Evolution', logisim_evolution: 'Logisim-evolution' }],
group: ['Output Bits', 'n'], length: ['Number of Stages', 'n'], parallel: ['Parallel Load', 'b'], addrWidth: ['Address Bit Width', 'n'], dataWidth: ['Data Bit Width', 'n'],
databus: ['Data Interface', ['bibus', 'bidir', 'bibusControlled'], { bibus: 'Separate load and store ports', bidir: 'One bidirectional data port', bibusControlled: 'Separate ports, controlled output' }], clearpin: ['Use Clear Pin', 'b'],
number: ['Number of switches', 'n'], rows: ['Rows', 'n'], cols: ['Columns', 'n'], buflen: ['Buffer Length', 'n'], highDuration: ['High Duration', 'n'], lowDuration: ['Low Duration', 'n'], phaseOffset: ['Phase Offset', 'n'], contents: ['Contents', 'mem']
};
// en plus des défauts du type : ce que Logisim montre pour chaque pièce
var EN_PLUS = { pin: ['behavior', 'labelloc', 'labelfont', 'radix', 'initial', 'appearance'], probe: ['radix', 'label', 'labelloc'], tunnel: ['labelfont'], const: [], led: ['labelloc'], button: ['labelloc'] };
var SIGNATURE = { owner: 'Owner', date: 'Creation date', version: 'Logisim version', uuid: 'UUID', integrity: 'Integrity' };
var CHAMPS_A = { control: 1, rows: 1, cols: 1, buflen: 1, group: 1, length: 1, parallel: 1, addrWidth: 1, dataWidth: 1, databus: 1, clearpin: 1, number: 1, highDuration: 1, lowDuration: 1, phaseOffset: 1, contents: 1, pull: 1, in_width: 1, out_width: 1, shift: 1, seed: 1, type: 1, facing: 1, width: 1, inputs: 1, size: 1, label: 1, output: 1, value: 1, select: 1, selloc: 1, enable: 1, disabled: 1, mode: 1, trigger: 1, fanout: 1, incoming: 1, appear: 1, spacing: 1, max: 1, text: 1, color: 1 }; // ce que le moteur lit dans c.a ; le reste vit dans meta (et repart tel quel au .circ)
function attrVal(c, k) { var d = C.T[c.t] || {}; return c.a[k] !== undefined ? c.a[k] : (c.meta && c.meta[k] !== undefined ? c.meta[k] : (d.a || {})[k]); }
function panneauD() {
var cs = selection(), h = '';
if (cs.length === 1) {
var c = cs[0], d = C.T[c.t] || {};
h += '<div class="lgs__h" style="text-transform:none;letter-spacing:0;font-size:.82rem;color:var(--texte)">' + esc(c.t === 'sub' ? c.a.circuit : (d.circ || c.circName || c.t)) + (c.a.label ? ' « ' + esc(c.a.label) + ' »' : '') + '</div><div class="lgs__attrs">';
var cles = Object.keys(Object.assign({}, d.a || {}, c.a)).concat(EN_PLUS[c.t] || []);
Object.keys(c.meta || {}).forEach(function (k) { if (!SIGNATURE[k] && cles.indexOf(k) < 0) cles.push(k); }); // tout ce que le fichier porte
cles = cles.filter(function (k, i) { return cles.indexOf(k) === i; });
if ((c.t === 'mux' || c.t === 'demux' || c.t === 'decoder') && cles.indexOf('enable') < 0) cles.push('enable');
if (d.lib === 1 && d.a && d.a.inputs !== undefined) for (var ni = 0; ni < Math.max(2, +c.a.inputs || 2); ni++) cles.push('negate' + ni);
cles.forEach(function (k) {
var f = CHAMPS[k];
if (/^negate\d+$/.test(k)) f = ['Negate ' + String.fromCharCode(65 + +k.slice(6)), 'b'];
if (!f && c.meta && c.meta[k] !== undefined) f = [k, 't']; // un attribut du fichier qu'on ne connaît pas : éditable tel quel
if (!f) return;
if (k === 'size' && (c.t === 'not' || c.t === 'trinot')) f = ['Gate Size', [20, 30], { 20: 'Narrow', 30: 'Wide' }];
if (k === 'size' && (c.t === 'mux' || c.t === 'demux')) f = ['Size', ['wide', 'narrow'], { wide: 'Wide', narrow: 'Narrow' }];
if (k === 'output' && c.t === 'pin') f = ['Output?', 'b'];
if (f[1] === 'mem') { h += '<label><span>' + esc(f[0]) + '</span><button data-act="memouvrir" style="flex:1">▤ (cliquer pour éditer)</button></label>'; return; }
if (k === 'appearance' && (c.t === 'ram' || c.t === 'rom' || c.t === 'shiftreg')) f = ['Appearance', ['classic', 'logisim_evolution'], { classic: 'Classic Logisim', logisim_evolution: 'Logisim-evolution' }];
var vk = attrVal(c, k);
if (k === 'facing' && ['add', 'sub', 'mul', 'neg', 'cmp', 'dff', 'tff', 'jkff', 'srff', 'reg', 'counter', 'hex', 'seg7'].indexOf(c.t) >= 0) return;
h += '<label><span>' + esc(f[0]) + '</span>';
if (Array.isArray(f[1])) h += '<select data-attr="' + k + '">' + f[1].map(function (o) { return '<option value="' + o + '"' + (String(vk) === String(o) ? ' selected' : '') + '>' + esc(f[2] && f[2][o] || o) + '</option>'; }).join('') + '</select>';
else if (f[1] === 'b') h += '<input type="checkbox" data-attr="' + k + '"' + (vk === true || vk === 'true' ? ' checked' : '') + '>';
else h += '<input data-attr="' + k + '" value="' + esc(vk === undefined ? '' : vk) + '"' + (f[1] === 'n' ? ' inputmode="numeric"' : '') + '>';
h += '</label>';
});
h += '</div>';
if (c.t === 'ram') h += '<div class="lgs__note"><button data-act="memouvrir">▤ le contenu (simulation)</button></div>';
if (c.t === 'sub') h += '<div class="lgs__note"><button data-ouvrirbloc="' + esc(c.a.circuit) + '">↳ entrer dans ce bloc</button> <small>(ou appui long)</small></div>';
var m = c.meta || {};
if (m.owner || m.date || m.version) {
h += '<div class="lgs__attrs">' + ['owner', 'date', 'version'].map(function (k) { return '<label><span>' + SIGNATURE[k] + '</span><input data-attr="' + k + '" value="' + esc(m[k] || '') + '"' + (k === 'owner' ? '' : ' readonly') + '></label>'; }).join('') + '</div>';
h += m.integrity ? (c.modifie ? '<div class="lgs__bandeau" style="margin:6px 10px">△ modifié : Logisim recalculera l\'integrity à l\'enregistrement</div>' : '<div class="lgs__bandeau" style="margin:6px 10px;background:#0f3a1a;color:#9ff0b0">✓ Integrity check : celle d\'origine</div>') : '';
}
} else if (cs.length > 1 || Object.keys(st.sel.w).length) {
h += '<div class="lgs__h">' + cs.length + ' pièce(s), ' + Object.keys(st.sel.w).length + ' fil(s)</div><div class="lgs__note"><button data-act="suppr">✕ supprimer</button> <button data-act="tourner">⟳ tourner</button></div>';
} else {
var cc = circ(), itf = C.interfaceDe(cc);
h += '<div class="lgs__h">circuit ' + esc(st.cur) + '</div><div class="lgs__attrs">';
h += '<label><span>nom</span><input data-circattr="nom" value="' + esc(st.cur) + '"></label>';
h += '<label><span>description</span><input data-circattr="desc" value="' + esc(cc.desc || '') + '"></label>';
h += '<label><span>forme fixe</span><input type="checkbox" data-circattr="fixe"' + (cc.fixe ? ' checked' : '') + '></label></div>';
h += '<div class="lgs__note">' + itf.entrees.length + ' entrée(s), ' + itf.sorties.length + ' sortie(s) · ' + (cc.comps || []).length + ' pièces · ' + (cc.wires || []).length + ' fils' + (cc.mode === 'table' ? '<br>□ bloc défini par sa table (▦ en bas) — « construire » en fait des portes' : '') + '</div>';
h += '<div class="lgs__note"><button data-act="enbion" title="ce circuit comme bion : ses entrées / sorties sur le bus, à poser dans un xer">▣ en bion (xer)</button></div>';
h += '<div class="lgs__note">' + (st.cur !== st.projet.main ? '<button data-act="principal">◆ en faire le principal</button> ' : '') + (Object.keys(st.projet.circuits).length > 1 ? '<button data-act="supprcirc">✕ supprimer ce circuit</button>' : '') + '</div>';
h += '<div class="lgs__note">E éditer · T toucher · W fil · R tourner · F tout voir · double-clic = étiquette · Ctrl+S .circ</div>';
}
$('[data-d]').innerHTML = h;
}
function panneaux() { var cs6 = selection(); if (cs6.length === 1 && (cs6[0].t === 'ram' || cs6[0].t === 'rom') && st.memId !== cs6[0].id) { st.memId = cs6[0].id; if (st.onglet === 'mem' || st.fen.mem) bas(); } panneauG(); panneauD(); try { a11y(); } catch (e) {} }
// ------------------------------------------------------------ bas : table, Karnaugh, VHDL
function bas() {
var O = [['table', '▦ table'], ['km', '⊞ Karnaugh'], ['chrono', '⌇ chronogramme'], ['vhdl', '≡ VHDL'], ['circ', '⧉ .circ']];
if (memComp() || st.onglet === 'mem' || st.fen.mem) O.push(['mem', '▤ mémoire']);
var hh = $('[data-hzhaut]'); if (hh && !hh.firstChild) hh.innerHTML = choixHz();
$('[data-onglets]').innerHTML = O.map(function (o) { return '<button data-onglet="' + o[0] + '"' + (st.onglet === o[0] && !st.basFerme ? ' class="on"' : '') + (st.fen[o[0]] ? ' title="en fenêtre"' : '') + '>' + o[1] + (st.fen[o[0]] ? ' ◳' : '') + '</button>'; }).join('') +
(!st.basFerme && !st.fen[st.onglet] ? '<button data-act="detacher" title="détacher en fenêtre flottante (par-dessus le plan)" aria-label="détacher en fenêtre">◳</button>' : '') + '<button data-act="bas" title="replier">' + (st.basFerme ? '▴' : '▾') + '</button><span class="r" data-etat></span>';
R.classList.toggle('ferme', st.basFerme);
if (!st.basFerme) {
var corps = $('[data-corps]'), h = '';
try { h = st.fen[st.onglet] ? '<div class="lgs__note">' + esc(TITRES[st.onglet]) + ' est en fenêtre flottante. <button data-fenint="' + st.onglet + '">⇲ la remettre ici</button></div>' : contenuOnglet(st.onglet); }
catch (e) { h = '<div class="lgs__note">△ ' + esc(e.message) + '</div>'; console.warn(e); }
corps.innerHTML = h;
if (st.onglet === 'chrono' && !st.fen.chrono) majChrono();
}
fenetres(); try { a11y(); } catch (e) {}
}
function montrerMem() { if (st.fen.mem) { fenetres(); return; } st.onglet = 'mem'; st.basFerme = false; bas(); setTimeout(dessiner, 30); }
function ongletTable() {
var t = C.tableDe(st.projet, st.cur), cc = circ();
if (!t.entrees.length && !t.sorties.length) return '<div class="lgs__note">pas de broches : pose des broches d\'entrée et de sortie (ou crée un □ bloc vide)</div>';
if (t.trop) return '<div class="lgs__note">' + t.entrees.length + ' bits d\'entrée : la table aurait 2^' + t.entrees.length + ' lignes (max ' + C.MAX_ENTREES + ' bits)</div>';
var ed = !t.sequentiel, h = '';
var portes = (cc.comps || []).some(function (x) { return x.t !== 'pin' && x.t !== 'text'; });
if (cc.mode === 'table' && portes) h += '<div class="lgs__bandeau">△ la table a été modifiée : c\'est elle qui fait foi. ⇢ construire refait les portes.</div>';
h += '<div style="margin-bottom:6px"><button data-act="construire" title="Quine-McCluskey → portes ET / OU / NON">⇢ construire le circuit</button> <button data-act="formule" title="un circuit depuis une formule">ƒ formule</button> <span class="lgs__note">' + (ed ? 'touche une sortie : 0 → 1 → x (indifférent)' : '△ circuit séquentiel : la table montre l\'état actuel des bascules') + '</span></div>';
h += '</div><table class="tv"><tr>' + t.entrees.map(function (n) { return '<th>' + esc(n) + '</th>'; }).join('') + t.sorties.map(function (n, i) { return '<th' + (i === 0 ? ' class="sep"' : '') + '>' + esc(n) + '</th>'; }).join('') + '</tr>';
var n = t.entrees.length;
for (var r = 0; r < (1 << n); r++) {
h += '<tr>';
for (var j = 0; j < n; j++) h += '<td>' + ((r >> (n - 1 - j)) & 1) + '</td>';
t.valeurs.forEach(function (col, i) { h += '<td class="s' + (ed ? ' ed' : '') + (i === 0 ? ' sep' : '') + '"' + (ed ? ' data-cell="' + i + ':' + r + '"' : '') + '>' + esc(col[r] || 'x') + '</td>'; });
h += '</tr>';
}
return h + '</table>';
}
function ongletKm() {
var t = C.tableDe(st.projet, st.cur), n = t.entrees.length;
if (!t.sorties.length) return '<div class="lgs__note">pas de sortie</div>';
if (n < 2 || n > 6) return '<div class="lgs__note">Karnaugh : de 2 à 6 variables (ici ' + n + ')</div>';
var si = Math.min(st.sortieKm, t.sorties.length - 1), col = t.valeurs[si], m = C.minimiser(n, col), K = C.karnaugh(n);
var h = '<div style="margin-bottom:6px">sortie <select class="ch" data-kmsortie style="width:auto">' + t.sorties.map(function (s, i) { return '<option value="' + i + '"' + (i === si ? ' selected' : '') + '>' + esc(s) + '</option>'; }).join('') + '</select></div>';
var vL = t.entrees.slice(K.extra, K.extra + K.nl), vC = t.entrees.slice(K.extra + K.nl), vE = t.entrees.slice(0, K.extra);
function code(g, k) { return g.toString(2).padStart(k, '0'); }
K.cartes.forEach(function (carte) {
h += '<div class="km">' + (K.extra ? '<div class="lgs__note">' + esc(vE.join('')) + ' = ' + carte.titre + '</div>' : '') + '<table><tr><th style="font-size:10px">' + esc(vL.join('')) + '\\' + esc(vC.join('')) + '</th>' + K.gc.map(function (g) { return '<th>' + code(g, K.nc) + '</th>'; }).join('') + '</tr>';
K.gl.forEach(function (gl, r) {
h += '<tr><th>' + code(gl, K.nl) + '</th>';
K.gc.forEach(function (gc, c) {
var i = carte.cell(r, c), v = col[i] || 'x', ombres = [];
m.sop.forEach(function (p, k) { if ((i & ~p.m) === (p.v & ~p.m)) ombres.push(COUL[k % COUL.length]); });
var bord = ombres.map(function (cl, k) { return 'inset 0 0 0 ' + (2 + 3 * k) + 'px ' + cl; }).join(',');
h += '<td style="' + (bord ? 'box-shadow:' + bord + ';' : '') + (v === '1' ? 'color:#ffd27a;font-weight:600' : v === '0' ? 'color:#5b6b7d' : 'color:#4c8dff') + '" title="ligne ' + i + '">' + v + '</td>';
});
h += '</tr>';
});
h += '</table></div>';
});
h += '<div style="margin-top:4px">';
m.sop.forEach(function (p, k) { h += '<span class="imp"><b style="background:' + COUL[k % COUL.length] + '"></b>' + esc(C.exprSop([p], t.entrees, 'math')) + '</span>'; });
h += '</div><div class="lgs__note">SOP minimale : <code>' + esc(t.sorties[si]) + ' = ' + esc(C.exprSop(m.sop, t.entrees, 'math', m.tout)) + '</code><br>POS minimale : <code>' + esc(t.sorties[si]) + ' = ' + esc(C.exprPos(m.pos, t.entrees, 'math', m.rien)) + '</code><br>VHDL : <code>' + esc(C.vhdlNom(t.sorties[si])) + ' &lt;= ' + esc(C.exprSop(m.sop, t.entrees, 'vhdl', m.tout)) + ';</code></div>';
return h;
}
// ------------------------------------------------------------ fichiers .circ, projets, bibliothèque
function exporterCirc() { telecharger(slug(st.projet.nom) + '.circ', C.versCirc(st.projet), 'application/xml'); }
function lireCirc(f) {
var r = new FileReader();
r.onload = function () {
var res = C.depuisCirc(String(r.result), f.name);
if (res.erreur) { toast('✗ ' + res.erreur); return; }
charger(res.projet);
toast('⇪ ' + f.name + ' : ' + Object.keys(res.projet.circuits).length + ' circuit(s)' + (res.avertissements.length ? ' · △ ' + res.avertissements.length + ' remarque(s) (console)' : ''), 3600);
if (res.avertissements.length) console.info('logisim · import', res.avertissements);
};
r.readAsText(f);
}
function nouveau() {
var p = C.nouveauProjet('projet ' + new Date().toISOString().slice(0, 10));
var m = p.circuits.main;
m.comps.push(C.comp('pin', 60, 60, { label: 'A' }), C.comp('pin', 60, 120, { label: 'B' }), C.comp('pin', 300, 90, { label: 'S', output: true, facing: 'west' }));
charger(p);
}
function mesProjets() {
var b = B();
if (!b || !b.list) { modal('<h3>▤ mes projets</h3><div class="lgs__note">connecte-toi pour garder tes projets dans ton compte (ici : seulement le dernier, dans ce navigateur).</div>'); return; }
b.list(NS).then(function (items) {
items = (items || []).filter(function (it) { return /^p:/.test(it.key || ''); });
modal('<h3>▤ mes projets</h3>' + (items.length ? items.map(function (it) { return '<div class="lgs__it" data-chargerp="' + esc(it.key) + '"><i>⊼</i>' + esc((it.name || it.key).replace(/^circuit · /, '')) + '<small>' + esc(String(it.savedAt || it.updated || '').slice(0, 10)) + '</small></div>'; }).join('') : '<div class="lgs__note">aucun encore</div>'));
});
}
function chargerBiblio() {
var b = B(); if (!b || !b.get) { st.biblio = { blocs: {}, liees: [] }; panneauG(); return; }
Promise.resolve(b.get(NS, 'biblio')).then(function (d) { st.biblio = d && d.blocs ? d : { blocs: {}, liees: [] }; st.biblio.liees = st.biblio.liees || []; panneauG(); }).catch(function () { st.biblio = { blocs: {}, liees: [] }; panneauG(); });
}
function sauverBiblio() { var b = B(); if (b && b.save) b.save(NS, 'biblio', st.biblio, 'ma bibliothèque logisim'); }
function publier() {
if (!st.biblio) return;
var noms = C.circuitsUtilises(st.projet, st.cur), circuits = {};
noms.forEach(function (n) { circuits[n] = JSON.parse(JSON.stringify(st.projet.circuits[n])); });
st.biblio.blocs[st.cur] = { circuits: circuits, racine: st.cur, desc: circ().desc || '', auteur: st.auteur, date: new Date().toISOString() };
sauverBiblio(); panneauG(); toast('⧉ « ' + st.cur + ' » est dans ta bibliothèque' + (noms.length > 1 ? ' (avec ' + (noms.length - 1) + ' sous-bloc(s))' : ''));
}
function importerCircuits(circuits, racine) { // dans le projet ; un nom pris par un circuit DIFFÉRENT → suffixe
var ren = {};
Object.keys(circuits).forEach(function (n) {
var mien = st.projet.circuits[n];
if (!mien) { ren[n] = n; return; }
if (JSON.stringify(mien.comps) === JSON.stringify(circuits[n].comps)) { ren[n] = null; return; }
var i = 2; while (st.projet.circuits[n + '_' + i]) i++; ren[n] = n + '_' + i;
});
Object.keys(circuits).forEach(function (n) {
if (ren[n] === null) return;
var c = JSON.parse(JSON.stringify(circuits[n])); c.nom = ren[n];
(c.comps || []).forEach(function (x) { if (x.t === 'sub' && ren[x.a.circuit]) x.a.circuit = ren[x.a.circuit]; });
st.projet.circuits[ren[n]] = c;
});
return ren[racine] || racine;
}
function importerDeBiblio(n) {
var e = st.biblio && st.biblio.blocs[n]; if (!e) return null;
return importerCircuits(e.circuits, e.racine || n);
}
function lierBiblio(f) {
var r = new FileReader();
r.onload = function () {
var res = C.depuisCirc(String(r.result), f.name); if (res.erreur) { toast('✗ ' + res.erreur); return; }
st.biblio = st.biblio || { blocs: {}, liees: [] }; st.biblio.liees.push({ nom: f.name.replace(/\.circ$/i, ''), projet: res.projet });
sauverBiblio(); panneauG(); toast('⧉ ' + f.name + ' liée : ' + Object.keys(res.projet.circuits).length + ' bloc(s) dans tes pièces');
};
r.readAsText(f);
}
// ------------------------------------------------------------ l'énoncé PDF (gardé avec le projet)
function chargerPdf() {
var l = st.projet && st.projet.labo;
if (l && l.pdf && B() && B().fileUrl) { st.pdf = { url: B().fileUrl(l.pdf), nom: l.nom }; if (ls('xb:logisim:pdf') !== 'off' && !mobile()) R.classList.add('avec-pdf'); }
else if (l && l.chemin && F()) { F().readBlob(l.chemin).then(function (b) { if (!b || st.projet.labo !== l) return; st.pdf = { url: URL.createObjectURL(b), nom: l.nom, blob: true }; if (ls('xb:logisim:pdf') !== 'off' && !mobile()) R.classList.add('avec-pdf'); panneauPdf(); }); }
panneauPdf();
}
function ouvrirPdf(f, chemin) {
if (st.pdf && st.pdf.blob) URL.revokeObjectURL(st.pdf.url);
st.pdf = { url: URL.createObjectURL(f), nom: f.name, blob: true };
R.classList.add('avec-pdf'); ls('xb:logisim:pdf', 'on'); panneauPdf(); dessiner();
if (chemin) { st.projet.labo = { chemin: chemin, nom: f.name }; sauver(); toast('◧ énoncé lié à « ' + st.projet.nom + ' »'); return; } // déjà dans le xerboxion : on garde le chemin
var b = B();
if (b && b.uploadFile) b.uploadFile(f, 'logisim', f.name).then(function (d) {
var id = d && (d.id || (d.item && d.item.id) || (d.file && d.file.id));
if (id) { st.projet.labo = { pdf: id, nom: f.name }; sauver(); toast('◧ énoncé gardé avec « ' + st.projet.nom + ' »'); }
}).catch(function () {});
}
function panneauPdf() {
var P = $('[data-pdfpanneau]');
if (!st.pdf) { P.innerHTML = '<header><b>◧ énoncé</b><span></span><button data-act="pdf" title="fermer l\'énoncé">✕</button></header><div class="lgs__pdfvide">glisse le PDF de l\'énoncé ici ou sur le plan<span><button data-act="pdfouvrir">⇪ depuis le PC</button> <button data-act="fichiers">⌂ depuis le xerboxion</button></span><small>il restera ouvert à côté de ce projet (dans ton compte)</small></div>'; return; }
P.innerHTML = '<header><b>◧</b><span title="' + esc(st.pdf.nom) + '">' + esc(st.pdf.nom) + '</span><button data-act="pdfouvrir" title="un autre PDF">⇪</button><a href="' + esc(st.pdf.url) + '" target="_blank" rel="noopener"><button title="ouvrir en grand">⤢</button></a><button data-act="pdf" title="fermer le panneau">✕</button></header><iframe src="' + esc(st.pdf.url) + '#view=FitH" title="énoncé"></iframe>';
}
// ------------------------------------------------------------ ⌂ les fichiers du xerboxion (le bion jOSFiles : PC, boxion, nexus, bureau, portions…)
function F() { return window.jOSFiles && window.jOSFiles.pick ? window.jOSFiles : null; }
function depuisFichiers() {
if (!F()) { toast('le sélecteur du xerboxion n\'est pas chargé ici : ⇪ .circ ouvre depuis ton PC'); return; }
F().pick({ mode: 'open', ext: ['circ', 'pdf'] }).then(function (p) {
if (!p) return;
var nom = String(p).split('/').pop();
if (/\.pdf$/i.test(p)) return F().readBlob(p).then(function (b) { if (b) ouvrirPdf(new File([b], nom, { type: 'application/pdf' }), p); else toast('✗ PDF illisible'); });
return F().readText(p).then(function (t) {
if (t === null || t === undefined) { toast('✗ fichier illisible'); return; }
var res = C.depuisCirc(t, nom); if (res.erreur) { toast('✗ ' + res.erreur); return; }
charger(res.projet); st.projet.chemin = p; sauver(); toast('⌂ ' + p);
});
});
}
function versFichiers() {
if (!F()) { toast('le sélecteur du xerboxion n\'est pas chargé ici : ⇩ .circ télécharge sur ton PC'); return; }
F().pick({ mode: 'save', ext: ['circ'], name: slug(st.projet.nom) + '.circ' }).then(function (p) {
if (!p) return;
return F().write(p, C.versCirc(st.projet)).then(function (r) { if (r) { st.projet.chemin = p; sauver(); } toast(r ? '⌂ enregistré : ' + p : '✗ pas enregistré'); });
});
}
// ------------------------------------------------------------ ◎ les circuits publics (lire sans compte, publier avec)
function connecte() { var m = document.querySelector('meta[name=user-authenticated]'); return !!(m && m.getAttribute('content') === '1'); }
function csrf() { var m = document.querySelector('meta[name=csrf-token]'); return m ? m.getAttribute('content') : ''; }
function ouvrirPublic(slugP) {
return fetch('/px/logisim/c/' + encodeURIComponent(slugP), { credentials: 'same-origin' }).then(function (r) { if (!r.ok) throw new Error(r.status === 404 ? 'ce circuit public n\'existe plus' : 'HTTP ' + r.status); return r.text().then(function (t) { return { t: t, nom: decodeURIComponent(r.headers.get('X-Logisim-Nom') || slugP) }; }); })
.then(function (d) {
var res = C.depuisCirc(d.t, d.nom); if (res.erreur) throw new Error(res.erreur);
res.projet.nom = d.nom; res.projet.public = { slug: slugP };
charger(res.projet); toast('◎ ' + d.nom + ' (public)');
}).catch(function (e) { toast('✗ ' + e.message); });
}
function dlgPublic() {
var m = modal('<h3>◎ circuits publics</h3><div class="lgs__note">Lisibles par tout le monde, sans compte : reprends-les sur n\'importe quel PC (le lien suffit), modifie, puis republie connecté.</div><div data-pub-form></div><div class="lgs__h">publiés</div><div data-pub-liste><div class="lgs__note">…</div></div>', function (ev, mm) {
var a = ev.target.closest('[data-pubouvrir]'); if (a) { mm.remove(); ouvrirPublic(a.getAttribute('data-pubouvrir')); return; }
a = ev.target.closest('[data-pubretirer]'); if (a) { if (!confirm('retirer ce circuit public ? le lien ne marchera plus')) return; fetch('/px/logisim/retirer/' + a.getAttribute('data-pubretirer'), { method: 'POST', credentials: 'same-origin', headers: { 'X-CSRF-TOKEN': csrf(), Accept: 'application/json' } }).then(function () { mm.remove(); dlgPublic(); }); return; }
a = ev.target.closest('[data-pubcopie]'); if (a) { try { navigator.clipboard.writeText(location.origin + '/px/logisim?c=' + a.getAttribute('data-pubcopie')); toast('⎘ lien copié'); } catch (e) {} return; }
if (!ev.target.closest('[data-publier]')) return;
var v = function (k) { var el = mm.querySelector('[data-p="' + k + '"]'); return el.type === 'checkbox' ? el.checked : el.value; };
var pub = st.projet.public || {};
fetch('/px/logisim/publier', { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'X-CSRF-TOKEN': csrf() },
body: JSON.stringify({ nom: v('nom'), desc: v('desc'), licence: v('licence'), liste: v('liste'), auteur: st.auteur, slug: v('maj') && pub.slug ? pub.slug : '', circ: C.versCirc(st.projet) }) })
.then(function (r) { return r.json().then(function (d) { return { ok: r.ok, d: d }; }); })
.then(function (x) {
if (!x.ok) { toast('✗ ' + (x.d.error || 'refusé')); return; }
st.projet.public = { slug: x.d.slug, mien: true }; sauver(); mm.remove();
try { navigator.clipboard.writeText(x.d.url); } catch (e) {}
toast('◎ publié — le lien est copié : ' + x.d.url, 4200);
}).catch(function () { toast('✗ réseau'); });
});
var pub = st.projet.public || {};
m.querySelector('[data-pub-form]').innerHTML = connecte()
? '<label>nom</label><input data-p="nom" value="' + esc(st.projet.nom) + '"><label>description</label><input data-p="desc" placeholder="(optionnel)">' +
'<label>licence</label><select data-p="licence" class="ch" style="width:100%">' + [['CC-BY-4.0', 'CC BY 4.0 (libre, citer l\'auteur)'], ['CC-BY-SA-4.0', 'CC BY-SA 4.0 (libre, même licence)'], ['CC0-1.0', 'CC0 (domaine public)'], ['MIT', 'MIT'], ['GPL-3.0', 'GPL 3.0'], ['tous-droits', 'tous droits réservés (visible, pas libre)']].map(function (o) { return '<option value="' + o[0] + '">' + esc(o[1]) + '</option>'; }).join('') + '</select>' +
'<label><input type="checkbox" data-p="liste" checked style="width:auto"> dans la liste publique (sinon : seulement par le lien)</label>' +
(pub.slug && pub.mien ? '<label><input type="checkbox" data-p="maj" checked style="width:auto"> mettre à jour le même lien</label>' : '<input type="hidden" data-p="maj" value="">') +
'<div class="act"><button data-publier class="on">◎ publier ce projet</button></div>'
: '<div class="lgs__note">connecte-toi pour publier ; ouvrir un circuit public marche sans compte.</div>';
fetch('/px/logisim/publics.json', { credentials: 'same-origin', headers: { Accept: 'application/json' } }).then(function (r) { return r.json(); }).then(function (d) {
var L = (d && d.circuits) || [];
m.querySelector('[data-pub-liste]').innerHTML = L.length ? L.map(function (c) {
return '<div class="lgs__it" data-pubouvrir="' + esc(c.slug) + '"><i>◎</i><span>' + esc(c.nom) + '<br><small style="margin:0">' + esc(c.auteur) + ' · ' + esc(c.licence) + ' · ' + esc(String(c.maj).slice(0, 10)) + (c.liste ? '' : ' · non listé') + '</small></span>' +
'<small data-pubcopie="' + esc(c.slug) + '" title="copier le lien">⎘</small><a href="/px/logisim/c/' + esc(c.slug) + '?dl=1" title=".circ" style="color:inherit"><small>⇩</small></a>' + (c.mien ? '<small data-pubretirer="' + esc(c.slug) + '" title="retirer">✕</small>' : '') + '</div>';
}).join('') : '<div class="lgs__note">aucun circuit public pour l\'instant</div>';
}).catch(function () { m.querySelector('[data-pub-liste]').innerHTML = '<div class="lgs__note">✗ liste indisponible</div>'; });
}
// ------------------------------------------------------------ modales
function modal(h, sur) {
var m = document.createElement('div'); m.className = 'lgs__modal'; m.innerHTML = '<div>' + h + '</div>'; R.appendChild(m);
m.addEventListener('click', function (ev) { if (ev.target === m) m.remove(); var a = ev.target.closest('[data-chargerp]'); if (a) { B().get(NS, a.getAttribute('data-chargerp')).then(function (p) { if (p && p.circuits) charger(p); m.remove(); }); } if (sur) sur(ev, m); });
return m;
}
function dlgBloc() {
modal('<h3>□ un bloc conceptuel</h3><div class="lgs__note">Une interface et sa table : il marche tout de suite dans tes circuits, tu feras la logique dedans ensuite.</div>' +
'<label>nom</label><input data-b="nom" placeholder="additionneur_1b">' +
'<label>entrées (« bus[4] » pour 4 bits)</label><input data-b="e" placeholder="a, b, cin">' +
'<label>sorties</label><input data-b="s" placeholder="s, cout">' +
'<label>description</label><input data-b="d" placeholder="(optionnel)">' +
'<div class="act"><button data-x>annuler</button><button data-ok class="on">créer</button></div>', function (ev, m) {
if (ev.target.closest('[data-x]')) m.remove();
if (!ev.target.closest('[data-ok]')) return;
var v = function (k) { return m.querySelector('[data-b="' + k + '"]').value.trim(); };
avant();
var r = C.blocVide(st.projet, v('nom'), v('e'), v('s'));
if (r.erreur) { st.histo.pop(); toast('✗ ' + r.erreur); return; }
r.circuit.desc = v('d'); m.remove(); st.cur = v('nom'); st.onglet = 'table'; st.basFerme = false;
modifie(); reconstruire(); sauver(); ajuster(); tout();
});
setTimeout(function () { var i = R.querySelector('[data-b="nom"]'); if (i) i.focus(); }, 30);
}
function dlgFormule() {
modal('<h3>ƒ un circuit depuis une formule</h3><div class="lgs__note">Une sortie par ligne. ET : <code>· * & and</code> (ou <code>a b</code>) · OU : <code>+ | or</code> · XOR : <code>^ ⊕ xor</code> · NON : <code>¬ ~ ! not</code>, <code>a\'</code> · aussi <code>nand nor xnor</code>, <code>0 1</code>, parenthèses.</div>' +
'<label>nom du circuit</label><input data-f="nom" placeholder="mon_circuit">' +
'<label>formules</label><textarea data-f="txt" rows="4" placeholder="s = a·b + c&#39;&#10;t = a xor b" style="font-family:ui-monospace,monospace"></textarea>' +
'<label><input type="checkbox" data-f="cons" checked style="width:auto"> construire les portes (minimisées) ; sinon : seulement la table</label>' +
'<div class="act"><button data-x>annuler</button><button data-ok class="on">générer</button></div>', function (ev, m) {
if (ev.target.closest('[data-x]')) m.remove();
if (!ev.target.closest('[data-ok]')) return;
var nom = m.querySelector('[data-f="nom"]').value.trim() || 'formule', txt = m.querySelector('[data-f="txt"]').value;
if (st.projet.circuits[nom]) { var i = 2; while (st.projet.circuits[nom + '_' + i]) i++; nom = nom + '_' + i; }
avant();
var r = C.depuisFormule(st.projet, nom, txt, m.querySelector('[data-f="cons"]').checked);
if (r.erreur) { st.histo.pop(); toast('✗ ' + r.erreur, 3600); return; }
m.remove(); st.cur = nom; st.onglet = 'table'; st.basFerme = false; modifie(); reconstruire(); sauver(); ajuster(); tout();
toast('ƒ ' + nom + ' : ' + r.circuit.table.sorties.length + ' sortie(s)' + (r.remarque ? ' · ' + r.remarque : ''), 3200);
});
setTimeout(function () { var i = R.querySelector('[data-f="txt"]'); if (i) i.focus(); }, 30);
}
function dlgReglages() {
modal('<h3>⚙ auteur et signature</h3><div class="lgs__note">Comme Logisim 4.0.0.t : chaque pièce que tu poses porte <code>owner</code>, <code>date</code>, <code>uuid</code>, <code>version</code>. Les pièces d\'un .circ importé gardent leur auteur. La signature <code>integrity</code> n\'est jamais inventée : celle d\'une pièce modifiée est retirée, Logisim la recalcule quand tu enregistres chez lui.</div>' +
'<label>auteur (owner)</label><input data-r="auteur" value="' + esc(st.auteur) + '" placeholder="ton identifiant Logisim">' +
'<div class="act"><button data-x>fermer</button><button data-ok class="on">garder</button></div>', function (ev, m) {
if (ev.target.closest('[data-x]')) m.remove();
if (!ev.target.closest('[data-ok]')) return;
st.auteur = m.querySelector('[data-r="auteur"]').value.trim().replace(/[^\w.@-]/g, '_'); ls('xb:logisim:auteur', st.auteur); C.signature.owner = st.auteur; m.remove(); toast(st.auteur ? '✓ tes pièces seront signées ' + st.auteur : 'signature coupée');
});
}
// ------------------------------------------------------------ événements des panneaux
R.addEventListener('click', function (ev) {
var t = ev.target, a;
if ((a = t.closest('[data-outil]'))) { outil(a.getAttribute('data-outil')); return; }
if ((a = t.closest('[data-fenint]'))) { integrer(a.getAttribute('data-fenint')); return; }
if ((a = t.closest('[data-fenfermer]'))) { delete st.fen[a.getAttribute('data-fenfermer')]; sauverFen(); fenetres(); bas(); return; }
if ((a = t.closest('[data-chronosig]'))) { st.chronoCache[a.getAttribute('data-chronosig')] = 1; bas(); return; }
if ((a = t.closest('[data-mempage]'))) { st.memPage += +a.getAttribute('data-mempage'); bas(); return; }
if ((a = t.closest('[data-memmot]'))) {
var cm3 = memComp(); if (!cm3) return; var ad = +a.getAttribute('data-memmot'), vs3 = memVals(cm3), nv = prompt('mot n° 0x' + ad.toString(16) + ' (hexa)', (vs3[ad] || 0).toString(16));
if (nv === null) return; var x3 = parseInt(String(nv).replace(/^0x/i, ''), 16); if (isNaN(x3)) return; vs3[ad] = x3 % Math.pow(2, Math.max(1, +cm3.a.dataWidth || 8)); memEcrire(cm3, vs3); return;
}
if ((a = t.closest('[data-onglet]'))) { var o = a.getAttribute('data-onglet'); st.basFerme = st.onglet === o ? !st.basFerme : false; st.onglet = o; ls('xb:logisim:onglet', o); ls('xb:logisim:bas', st.basFerme ? 'ferme' : 'ouvert'); bas(); return; }
if ((a = t.closest('[data-circ]'))) { st.cur = a.getAttribute('data-circ'); st.pile = []; st.sel = { c: {}, w: {} }; reconstruire(); ajuster(); tout(); if (mobile()) R.classList.remove('feuille-g'); return; }
if ((a = t.closest('[data-ariane-i]'))) { allerA(+a.getAttribute('data-ariane-i')); return; }
if ((a = t.closest('[data-arbre]'))) { // aller à une instance de l'arbre : refaire la pile le long du chemin
var ch = a.getAttribute('data-arbre'), rac2 = racineNom(), ids = ch.split('/').filter(Boolean), pile = [{ circuit: rac2, chemin: '' }], nomC = rac2, acc = '';
for (var ii = 0; ii < ids.length; ii++) { var inst = (st.projet.circuits[nomC].comps || []).find(function (x) { return x.id === ids[ii]; }); if (!inst) break; acc += '/' + inst.id; nomC = inst.a.circuit; pile.push({ circuit: nomC, chemin: acc, nom: inst.a.label || nomC }); }
st.pile = pile.length > 1 ? pile : []; st.cur = nomC; st.sel = { c: {}, w: {} }; ajuster(); tout(); return;
}
if ((a = t.closest('[data-ouvrirbloc]'))) { var sc0 = selection()[0]; if (sc0 && sc0.t === 'sub') entrer(sc0); return; }
if ((a = t.closest('[data-bibsuppr]'))) { ev.stopPropagation(); var nm = a.getAttribute('data-bibsuppr'); if (confirm('retirer « ' + nm + ' » de ta bibliothèque ?')) { delete st.biblio.blocs[nm]; sauverBiblio(); panneauG(); } return; }
if ((a = t.closest('[data-delier]'))) { ev.stopPropagation(); st.biblio.liees.splice(+a.getAttribute('data-delier'), 1); sauverBiblio(); panneauG(); return; }
if ((a = t.closest('[data-cat]'))) { var k = a.getAttribute('data-cat'); catOuverte[k] = catOuverte[k] === 0 || !catOuverte[k] ? (k === 'blocs' && catOuverte[k] === undefined ? 0 : 1) : 0; ls('xb:logisim:cats', JSON.stringify(catOuverte)); panneauG(); return; }
if ((a = t.closest('[data-pose]'))) {
var tp = a.getAttribute('data-pose'), sortie = !!a.getAttribute('data-sortie');
if (tp.indexOf('lie:') === 0) { var parts = tp.split(':'), lib = st.biblio.liees[+parts[1]]; if (!lib) return; var noms = C.circuitsUtilises(lib.projet, parts.slice(2).join(':')), cs = {}; noms.forEach(function (n) { cs[n] = lib.projet.circuits[n]; }); avant(); var nn = importerCircuits(cs, parts.slice(2).join(':')); sauver(); tp = 'bloc:' + nn; }
st.pose = st.pose === tp && st.poseSortie === sortie ? null : tp; st.poseSortie = sortie; if (st.outil !== 'edit') outil('edit'); st.pose = st.pose; panneauG();
if (mobile()) R.classList.remove('feuille-g');
return;
}
if ((a = t.closest('[data-cell]'))) {
var pr = a.getAttribute('data-cell').split(':'), si = +pr[0], ri = +pr[1], cc = circ();
if (cc.mode !== 'table' || !cc.table) { var tb0 = C.tableDe(st.projet, st.cur); cc.table = { sorties: tb0.valeurs.slice() }; cc.mode = 'table'; }
changer(function () { var col = cc.table.sorties[si] || ''; var v = col[ri] || 'x'; var nv = v === '0' ? '1' : v === '1' ? 'x' : '0'; cc.table.sorties[si] = col.slice(0, ri) + nv + col.slice(ri + 1); });
return;
}
if ((a = t.closest('[data-mob]'))) {
var mb = a.getAttribute('data-mob');
if (mb === 'g') { R.classList.toggle('feuille-g'); R.classList.remove('feuille-d'); }
else if (mb === 'd') { R.classList.toggle('feuille-d'); R.classList.remove('feuille-g'); }
else if (mb === 'outil') outil(st.outil === 'edit' ? 'poke' : st.outil === 'poke' ? 'fil' : 'edit');
else if (mb === 'bas') { st.basFerme = !st.basFerme; bas(); }
else if (mb === 'pdf') { R.classList.toggle('avec-pdf'); panneauPdf(); }
return;
}
if (!(a = t.closest('[data-act]'))) return;
var act = a.getAttribute('data-act');
if (act === 'nouveau') { if (!st.projet.modifie || confirm('un nouveau projet ? (celui-ci reste dans ▤ mes projets)')) nouveau(); }
else if (act === 'ouvrir') $('[data-fichier]').click();
else if (act === 'circ') exporterCirc();
else if (act === 'projets') mesProjets();
else if (act === 'fichiers') depuisFichiers();
else if (act === 'versfichiers') versFichiers();
else if (act === 'public') dlgPublic();
else if (act === 'annuler') annuler();
else if (act === 'refaire') refaire();
else if (act === 'tourner') tourner();
else if (act === 'suppr') supprimer();
else if (act === 'ajuster') ajuster();
else if (act === 'joue') { st.joue = !st.joue; R.querySelectorAll('[data-act="joue"]').forEach(function (b) { b.classList.toggle('on', st.joue); b.textContent = st.joue ? '‖' : '▷'; }); horloge(); }
else if (act === 'tic') { if (st.sim) { st.sim.tic(); echantillon('tic'); dessiner(); bas(); } }
else if (act === 'raz') { st.sim = null; st.chrono = new C.Chrono(600); reconstruire(); dessiner(); bas(); }
else if (act === 'detacher') detacher(st.onglet);
else if (act === 'memouvrir') { var cs5 = selection(); if (cs5[0]) { st.memId = cs5[0].id; montrerMem(); } }
else if (act === 'chronoplus' || act === 'chronomoins') { st.chronoPas = Math.max(4, Math.min(80, Math.round(st.chronoPas * (act === 'chronoplus' ? 1.4 : 1 / 1.4)))); ls('xb:logisim:chronopas', st.chronoPas); majChrono(); }
else if (act === 'chronovider') { st.chrono.vider(); echantillon('debut'); majChrono(); }
else if (act === 'chronotout') { st.chronoCache = {}; bas(); }
else if (act === 'chronovcd') telecharger(slug(st.projet.nom) + '-' + slug(racineNom()) + '.vcd', st.chrono.versVcd(racineNom()), 'text/plain');
else if (act === 'memcharger') { var fm = R.querySelector('[data-memfichier]'); if (fm) fm.click(); }
else if (act === 'memsauver') { var cm = memComp(); if (cm) { var vs = memVals(cm), nm = vs.length; while (nm > 0 && !vs[nm - 1]) nm--; var Lm = ['v3.0 hex words plain']; for (var im = 0; im < nm; im += 8) Lm.push(vs.slice(im, im + 8).map(function (x) { return (x || 0).toString(16); }).join(' ')); telecharger(slug(cm.a.label || cm.t) + '.txt', Lm.join('\n') + '\n', 'text/plain'); } }
else if (act === 'memvider') { var cv2 = memComp(); if (cv2 && confirm('tout le contenu à zéro ?')) memEcrire(cv2, []); }
else if (act === 'pdf') { R.classList.toggle('avec-pdf'); ls('xb:logisim:pdf', R.classList.contains('avec-pdf') ? 'on' : 'off'); panneauPdf(); setTimeout(dessiner, 50); }
else if (act === 'pdfouvrir') $('[data-fichierpdf]').click();
else if (act === 'reglages') dlgReglages();
else if (act === 'toile') { R.classList.toggle('toile-sombre'); ls('xb:logisim:toile', R.classList.contains('toile-sombre') ? 'sombre' : 'claire'); dessiner(); }
else if (act === 'g') { R.classList.toggle('sans-g'); setTimeout(dessiner, 30); }
else if (act === 'd') { R.classList.toggle('sans-d'); setTimeout(dessiner, 30); }
else if (act === 'bas') { st.basFerme = !st.basFerme; ls('xb:logisim:bas', st.basFerme ? 'ferme' : 'ouvert'); bas(); setTimeout(dessiner, 30); }
else if (act === 'bloc') dlgBloc();
else if (act === 'formule') dlgFormule();
else if (act === 'nvcirc') { var nm2 = prompt('nom du circuit'); if (nm2 && /^[A-Za-z][A-Za-z0-9_]*$/.test(nm2) && !st.projet.circuits[nm2]) { changer(function () { st.projet.circuits[nm2] = C.nouveauCircuit(nm2); }); st.cur = nm2; reconstruire(); ajuster(); tout(); } else if (nm2) toast('nom : lettres, chiffres, _ (et pas déjà pris)'); }
else if (act === 'principal') { changer(function () { st.projet.main = st.cur; }); }
else if (act === 'supprcirc') { var utilise = Object.keys(st.projet.circuits).some(function (n) { return (st.projet.circuits[n].comps || []).some(function (c) { return c.t === 'sub' && c.a.circuit === st.cur; }); }); if (utilise) { toast('ce circuit est utilisé comme bloc ailleurs'); return; } if (confirm('supprimer le circuit « ' + st.cur + ' » ?')) { var vieux = st.cur; changer(function () { delete st.projet.circuits[vieux]; if (st.projet.main === vieux) st.projet.main = Object.keys(st.projet.circuits)[0]; }); st.cur = st.projet.main; reconstruire(); ajuster(); tout(); } }
else if (act === 'construire') { avant(); var r2 = C.construireDepuisTable(st.projet, st.cur); if (r2.erreur) { st.histo.pop(); toast('✗ ' + r2.erreur); return; } modifie(); reconstruire(); sauver(); ajuster(); tout(); toast('⇢ ' + r2.portes + ' pièce(s) posées depuis la table'); }
else if (act === 'figer') { var tb = C.tableDe(st.projet, st.cur); changer(function () { circ().table = { sorties: tb.valeurs.slice() }; circ().mode = 'table'; }); toast('□ la table est la spécification ; « construire » refait les portes'); }
else if (act === 'vhdlcopie') { try { navigator.clipboard.writeText(C.versVhdl(st.projet, st.cur)); toast('⎘ VHDL copié'); } catch (e) {} }
else if (act === 'vhdldl') telecharger(C.vhdlNom(st.cur) + '.vhd', C.versVhdl(st.projet, st.cur), 'text/x-vhdl');
else if (act === 'publier') publier();
else if (act === 'enbion') {
publier();
modal('<h3>▣ ' + esc(st.cur) + ' en bion</h3><div class="lgs__note">Il est dans ta bibliothèque. Pose le ploxion <b>▣ circuit</b> dans un xer (compositeur) et choisis-le : ses entrées deviennent des broches à cliquer, ses sorties des voyants, et tout passe sur le bus :</div>' +
'<div class="lgs__note"><code>ploxion.circuit.sortie {circuit, broche, v}</code> · <code>ploxion.circuit.&lt;broche&gt;</code><br>Deux circuits posés côte à côte se parlent par le NOM des broches (une sortie « s » pilote les entrées « s »), comme des tunnels. Ce circuit-ci, ouvert dans logisim, est déjà sur le bus.</div>' +
'<div class="act"><a href="/px/circuit?b=' + encodeURIComponent(st.cur) + '" target="_blank" rel="noopener"><button class="on">▣ l\'ouvrir en bion</button></a></div>');
}
else if (act === 'lier') $('[data-fichierbib]').click();
});
R.addEventListener('change', function (ev) {
var t = ev.target, a;
if (t.matches('[data-fichier]')) { if (t.files[0]) lireCirc(t.files[0]); t.value = ''; return; }
if (t.matches('[data-fichierpdf]')) { if (t.files[0]) ouvrirPdf(t.files[0]); t.value = ''; return; }
if (t.matches('[data-fichierbib]')) { if (t.files[0]) lierBiblio(t.files[0]); t.value = ''; return; }
if (t.matches('[data-kmsortie]')) { st.sortieKm = +t.value; bas(); return; }
if (t.matches('[data-hz]')) { st.hz = +t.value || 4; ls('xb:logisim:hz', st.hz); R.querySelectorAll('[data-hz]').forEach(function (x) { x.value = String(st.hz); }); horloge(); return; }
if (t.matches('[data-memfichier]')) { var fi = t.files[0], cm4 = memComp(); if (fi && cm4) { var rd = new FileReader(); rd.onload = function () { memEcrire(cm4, C.lireContenu(String(rd.result || ''))); toast('▤ ' + fi.name + ' chargé'); }; rd.readAsText(fi); } t.value = ''; return; }
if (t.matches('[data-nomprojet]')) { var v0 = t.value.trim() || 'projet'; changer(function () { st.projet.nom = v0; }); return; }
if ((a = t.closest('[data-attr]'))) {
var k = a.getAttribute('data-attr'), c = selection()[0]; if (!c) return;
var v = a.type === 'checkbox' ? a.checked : a.value, num = ['width', 'inputs', 'size', 'value', 'select', 'fanout', 'incoming', 'spacing', 'max', 'in_width', 'out_width', 'seed', 'addrWidth', 'dataWidth', 'length', 'number', 'group', 'highDuration', 'lowDuration', 'phaseOffset', 'rows', 'cols', 'buflen'];
if (/^negate\d+$/.test(k)) num = [];
if (num.indexOf(k) >= 0 && !(k === 'size' && (c.t === 'mux' || c.t === 'demux'))) { v = k === 'value' || k === 'max' ? (String(v).indexOf('0x') === 0 ? parseInt(v, 16) : parseInt(v, 10)) : parseInt(v, 10); if (isNaN(v)) return; if (k === 'width') v = Math.max(1, Math.min(32, v)); if (k === 'inputs') v = Math.max(2, Math.min(32, v)); if (k === 'select') v = Math.max(1, Math.min(5, v)); }
if (SIGNATURE[k]) { changer(function () { c.meta = c.meta || {}; c.meta[k] = v; }, [c]); return; }
var dansMeta = c.a[k] === undefined && !(k in ((C.T[c.t] || {}).a || {})) && !CHAMPS_A[k];
changer(function () { if (dansMeta) { c.meta = c.meta || {}; c.meta[k] = v; } else c.a[k] = v; if (k === 'output' && c.t === 'pin') c.a.facing = v ? 'west' : 'east'; }, [c]);
return;
}
if ((a = t.closest('[data-circattr]'))) {
var ka = a.getAttribute('data-circattr'), cc = circ();
if (ka === 'desc') changer(function () { cc.desc = a.value; });
else if (ka === 'fixe') changer(function () { cc.fixe = a.checked; });
else if (ka === 'nom') {
var nv = a.value.trim(), vx = st.cur;
if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(nv) || st.projet.circuits[nv]) { toast('nom : lettres, chiffres, _ (et pas déjà pris)'); a.value = vx; return; }
changer(function () { var p = st.projet; p.circuits[nv] = p.circuits[vx]; p.circuits[nv].nom = nv; delete p.circuits[vx]; if (p.main === vx) p.main = nv; Object.keys(p.circuits).forEach(function (n) { (p.circuits[n].comps || []).forEach(function (c) { if (c.t === 'sub' && c.a.circuit === vx) c.a.circuit = nv; }); }); });
st.cur = nv; tout();
}
}
});
// ------------------------------------------------------------ les DÉTAILS en fenêtre (RS-7 : « si y a des éléments qui sont des détails, une fenêtre
// qui hover ou qu'on peut intégrer dans la page ») : chaque onglet du bas se détache (⧉) en fenêtre flottante par-dessus le plan, se déplace,
// se redimensionne, se ré-intègre (⇲) ; plusieurs à la fois ; leur place est gardée. Au téléphone : une feuille en bas.
var TITRES = { table: '▦ table de vérité', km: '⊞ Karnaugh', chrono: '⌇ chronogramme', vhdl: '≡ VHDL', circ: '⧉ .circ', mem: '▤ mémoire' };
st.fen = (function () { try { return JSON.parse(ls('xb:logisim:fen') || '{}') || {}; } catch (e) { return {}; } })();
function sauverFen() { ls('xb:logisim:fen', JSON.stringify(st.fen)); }
function contenuOnglet(o) {
if (o === 'table') return ongletTable();
if (o === 'km') return ongletKm();
if (o === 'chrono') return ongletChrono();
if (o === 'mem') return ongletMem();
if (o === 'vhdl') return '<div style="margin-bottom:6px"><button data-act="vhdlcopie">⎘ copier</button> <button data-act="vhdldl">⇩ .vhd</button> <span class="lgs__note">une entité par circuit (ce circuit et ses blocs) ; flasher sur une carte : plus tard</span></div><pre>' + esc(C.versVhdl(st.projet, st.cur)) + '</pre>';
if (o === 'circ') return '<div style="margin-bottom:6px"><button data-act="circ">⇩ enregistrer le .circ</button> <span class="lgs__note">s\'ouvre dans Logisim-evolution ; auteur et signatures gardés</span></div><pre>' + esc(C.versCirc(st.projet).slice(0, 20000)) + '</pre>';
return '';
}
function detacher(o) {
var r = R.getBoundingClientRect(), n = Object.keys(st.fen).length;
var fw = o === 'chrono' ? Math.min(720, r.width - 30) : Math.min(520, r.width - 30);
st.fen[o] = { x: Math.max(8, r.width - fw - 24 - 24 * n), y: 60 + 24 * n, w: fw, h: o === 'chrono' ? 260 : 330 };
if (st.onglet === o) { var autre = ['table', 'km', 'chrono', 'vhdl', 'circ'].filter(function (k) { return !st.fen[k]; })[0]; if (autre) st.onglet = autre; else st.basFerme = true; }
sauverFen(); bas();
}
function integrer(o) { delete st.fen[o]; st.onglet = o; st.basFerme = false; ls('xb:logisim:onglet', o); sauverFen(); bas(); setTimeout(dessiner, 30); }
function fenetres() {
R.querySelectorAll('.lgs__fen').forEach(function (el) { if (!st.fen[el.getAttribute('data-fen')]) el.remove(); });
Object.keys(st.fen).forEach(function (o) {
var f = st.fen[o], el = R.querySelector('.lgs__fen[data-fen="' + o + '"]');
if (!el) {
el = document.createElement('div'); el.className = 'lgs__fen'; el.setAttribute('data-fen', o); el.setAttribute('role', 'dialog'); el.setAttribute('aria-label', TITRES[o] || o);
el.innerHTML = '<header data-fendrag="' + o + '"><b>' + esc(TITRES[o] || o) + '</b><button data-fenint="' + o + '" title="intégrer dans la page (en bas)" aria-label="intégrer dans la page">⇲</button><button data-fenfermer="' + o + '" title="fermer" aria-label="fermer">✕</button></header><div class="lgs__fencorps"></div>';
el.style.left = f.x + 'px'; el.style.top = f.y + 'px'; el.style.width = f.w + 'px'; el.style.height = f.h + 'px';
R.appendChild(el);
}
var corps = el.querySelector('.lgs__fencorps'), sx = corps.scrollLeft, sy = corps.scrollTop;
try { corps.innerHTML = contenuOnglet(o); } catch (e) { corps.innerHTML = '<div class="lgs__note">△ ' + esc(e.message) + '</div>'; }
corps.scrollLeft = sx; corps.scrollTop = sy;
});
if (R.querySelector('.lgs__fen [data-chrono]')) majChrono();
}
var fenGeste = null;
R.addEventListener('pointerdown', function (ev) {
var h = ev.target.closest('[data-fendrag]'); if (!h || ev.target.closest('button')) return;
var el = h.parentNode; fenGeste = { o: h.getAttribute('data-fendrag'), el: el, d: [ev.clientX, ev.clientY], p: [el.offsetLeft, el.offsetTop] };
R.querySelectorAll('.lgs__fen').forEach(function (x) { x.style.zIndex = 6; }); el.style.zIndex = 7;
try { h.setPointerCapture(ev.pointerId); } catch (e) {} ev.preventDefault();
});
R.addEventListener('pointermove', function (ev) {
if (!fenGeste) return;
var x = Math.max(0, Math.min(R.clientWidth - 80, fenGeste.p[0] + ev.clientX - fenGeste.d[0])), y = Math.max(0, Math.min(R.clientHeight - 40, fenGeste.p[1] + ev.clientY - fenGeste.d[1]));
fenGeste.el.style.left = x + 'px'; fenGeste.el.style.top = y + 'px';
});
R.addEventListener('pointerup', function (ev) {
var el = ev.target.closest && ev.target.closest('.lgs__fen');
if (fenGeste) { var f = st.fen[fenGeste.o]; if (f) { f.x = fenGeste.el.offsetLeft; f.y = fenGeste.el.offsetTop; sauverFen(); } fenGeste = null; return; }
if (el && st.fen[el.getAttribute('data-fen')]) { var g = st.fen[el.getAttribute('data-fen')]; if (Math.abs(g.w - el.offsetWidth) > 2 || Math.abs(g.h - el.offsetHeight) > 2) { g.w = el.offsetWidth; g.h = el.offsetHeight; sauverFen(); if (el.getAttribute('data-fen') === 'chrono') majChrono(); } }
});
// ------------------------------------------------------------ le CHRONOGRAMME (RS-7 : « toute la partie avec la clock, avec les timing diagram ») :
// comme le Timing Diagram de Logisim : un échantillon par tic d'horloge (et par geste entre deux tics), une ligne par broche / horloge / sonde du
// circuit racine ; 1 bit = créneaux, un bus = des cases avec la valeur ; survol = la valeur de chaque signal à cet instant ; ⇩ .vcd pour GTKWave
st.chrono = new C.Chrono(600); st.chronoDe = null; st.chronoPas = +(ls('xb:logisim:chronopas') || 22); st.chronoCache = {};
function echantillon(r) {
if (!st.sim) return;
if (st.chronoDe !== racineNom()) { st.chrono = new C.Chrono(600); st.chronoDe = racineNom(); st.chronoCache = {}; }
if (st.chrono.prendre(st.sim, r)) majChronoBientot();
}
var tChrono = null;
function majChronoBientot() { if (tChrono) return; tChrono = requestAnimationFrame(function () { tChrono = null; majChrono(); }); }
var HZ = [0.25, 0.5, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024];
function choixHz() { return '<select class="hz" data-hz title="fréquence des tics (Tick Frequency de Logisim) ; une horloge 1/1 fait un cycle en 2 tics" aria-label="fréquence des tics">' + HZ.map(function (h) { return '<option value="' + h + '"' + (h === st.hz ? ' selected' : '') + '>' + (h >= 1 ? h + ' Hz' : h + ' Hz') + '</option>'; }).join('') + '</select>'; }
function ongletChrono() {
return '<div class="chronoBarre"><button data-act="joue" title="horloge : lancer / arrêter">' + (st.joue ? '‖' : '▷') + '</button><button data-act="tic" title="un tic">▷|</button>' + choixHz() +
'<button data-act="chronomoins" title="resserrer">−</button><button data-act="chronoplus" title="élargir">+</button><button data-act="chronovider" title="vider le chronogramme">⌫</button><button data-act="chronovcd" title="exporter en .vcd (GTKWave)">⇩ .vcd</button>' +
(Object.keys(st.chronoCache).length ? '<button data-act="chronotout" title="remontrer les signaux masqués">◉ tout montrer</button>' : '') + '<span class="lgs__note" data-chronoinfo></span></div>' +
'<div class="chrono" data-chrono></div><div class="chronoLu" data-chronolu>survole le chronogramme : la valeur de chaque signal à cet instant · clic sur un nom : le masquer</div>';
}
function rx(v, w) { if (v.length === 1) return v; if (/[^01]/.test(v)) return v.indexOf('E') >= 0 ? 'E' : 'x'; var n = parseInt(v, 2); return w > 4 ? '0x' + n.toString(16) : n.toString(16); }
function majChrono() {
var boites = R.querySelectorAll('[data-chrono]'); if (!boites.length) return;
var ch = st.chrono, ech = ch.ech, n = ech.length, pas = st.chronoPas, H = 26, G = 110;
var ids = ch.ordre.filter(function (id) { return !st.chronoCache[id] && ech.some(function (e) { return e.v[id] !== undefined; }); });
R.querySelectorAll('[data-chronoinfo]').forEach(function (el) { el.textContent = n + ' échantillon(s) · tic ' + (st.sim ? st.sim.tics || 0 : 0); });
var W = G + Math.max(1, n) * pas + 12, Ht = 18 + ids.length * H + 4;
var s = '<svg width="' + W + '" height="' + Ht + '" data-chronosvg>';
for (var i = 0; i < n; i++) { var x = G + i * pas; if (ech[i].r === 'tic' && (i % Math.max(1, Math.round(44 / pas)) === 0)) s += '<text x="' + (x + 2) + '" y="11">' + ech[i].t + '</text>'; s += '<line x1="' + x + '" y1="14" x2="' + x + '" y2="' + Ht + '" stroke="' + (ech[i].r === 'tic' ? '#1c2836' : '#2a2410') + '"/>'; }
ids.forEach(function (id, k) {
var sg = ch.sig[id], y0 = 18 + k * H, haut = y0 + 5, bas = y0 + H - 6, mil = (haut + bas) / 2;
s += '<text class="nom" x="6" y="' + (mil + 4) + '" data-chronosig="' + esc(id) + '">' + esc(String(sg.nom).slice(0, 14)) + (sg.w > 1 ? ' [' + sg.w + ']' : '') + '</text>';
if (sg.w === 1) {
var d = '', prec = null;
for (var j = 0; j < n; j++) {
var v = ech[j].v[id], xa = G + j * pas, xb = xa + pas, y = v === '1' ? haut : v === '0' ? bas : mil;
if (v === undefined) { prec = null; continue; }
d += (prec === null ? 'M' + xa + ',' + y : 'L' + xa + ',' + y) + ' L' + xb + ',' + y + ' ';
if (v !== '1' && v !== '0') s += '<line x1="' + xa + '" y1="' + mil + '" x2="' + xb + '" y2="' + mil + '" stroke="' + (v === 'E' ? 'var(--e)' : 'var(--x)') + '" stroke-width="2"/>';
prec = y;
}
s += '<path d="' + d + '" fill="none" stroke="var(--un)" stroke-width="1.6"/>';
} else {
var j0 = 0;
while (j0 < n) {
var v0 = ech[j0].v[id], j1 = j0; while (j1 < n && ech[j1].v[id] === v0) j1++;
if (v0 !== undefined) {
var a0 = G + j0 * pas, b0 = G + j1 * pas, e = Math.min(4, (b0 - a0) / 2), col = /E/.test(v0) ? 'var(--e)' : /[xz]/.test(v0) ? 'var(--x)' : '#9fb3c8';
s += '<path d="M' + a0 + ',' + mil + ' L' + (a0 + e) + ',' + haut + ' L' + (b0 - e) + ',' + haut + ' L' + b0 + ',' + mil + ' L' + (b0 - e) + ',' + bas + ' L' + (a0 + e) + ',' + bas + ' Z" fill="none" stroke="' + col + '" stroke-width="1.4"/>';
var tx = rx(v0, sg.w); if ((b0 - a0) > tx.length * 6.2 + 6) s += '<text class="val" x="' + ((a0 + b0) / 2) + '" y="' + (mil + 3.5) + '" text-anchor="middle">' + esc(tx) + '</text>';
}
j0 = j1;
}
}
});
s += '<line data-curseur x1="0" y1="14" x2="0" y2="' + Ht + '" stroke="var(--acc)" stroke-width="1" style="display:none"/></svg>';
if (!n) s = '<div class="lgs__note">pas encore d\'échantillon : ▷ lance l\'horloge, ▷| fait un tic, ou touche une entrée (⊙)</div>';
boites.forEach(function (b) { var fin = b.scrollLeft + b.clientWidth >= b.scrollWidth - 30; b.innerHTML = s; if (fin) b.scrollLeft = b.scrollWidth; });
}
R.addEventListener('pointermove', function (ev) {
var sv = ev.target.closest && ev.target.closest('[data-chronosvg]'); if (!sv) return;
var r = sv.getBoundingClientRect(), x = ev.clientX - r.left, i = Math.floor((x - 110) / st.chronoPas), ch = st.chrono;
var lu = sv.parentNode.parentNode.querySelector('[data-chronolu]'), cur = sv.querySelector('[data-curseur]');
if (i < 0 || i >= ch.ech.length) { if (cur) cur.style.display = 'none'; return; }
if (cur) { cur.setAttribute('x1', 110 + i * st.chronoPas + st.chronoPas / 2); cur.setAttribute('x2', 110 + i * st.chronoPas + st.chronoPas / 2); cur.style.display = ''; }
var e = ch.ech[i];
if (lu) lu.textContent = (e.r === 'tic' ? 'tic ' + e.t : 'geste (tic ' + e.t + ')') + ' · ' + ch.ordre.filter(function (id) { return e.v[id] !== undefined && !st.chronoCache[id]; }).map(function (id) { return ch.sig[id].nom + '=' + rx(e.v[id], ch.sig[id].w); }).join(' ');
});
// ------------------------------------------------------------ la MÉMOIRE d'une RAM / ROM (l'éditeur hexa de Logisim) : clic sur un mot = le changer ;
// ROM : le contenu est un attribut (dans le .circ) ; RAM : l'état de la simulation (volatile, comme Logisim)
st.memId = null; st.memPage = 0;
function memComp() { var cc = circ(); return st.memId ? (cc.comps || []).find(function (c) { return c.id === st.memId && (c.t === 'ram' || c.t === 'rom'); }) : null; }
function memVals(c) {
if (c.t === 'rom') return C.lireContenu(c.a.contents);
var it = itDe(c), m = it && it.st.mem || {}, r = []; Object.keys(m).forEach(function (k) { r[+k] = m[k]; }); return r;
}
function ongletMem() {
var c = memComp(); if (!c) return '<div class="lgs__note">choisis une RAM ou une ROM sur le plan : son contenu s\'affiche ici (clic sur un mot pour le changer)</div>';
var aw = Math.max(1, +c.a.addrWidth || 8), dw = Math.max(1, +c.a.dataWidth || 8), taille = Math.pow(2, aw), parL = dw > 16 ? 4 : dw > 8 ? 8 : 16, page = 256, nP = Math.ceil(taille / page);
st.memPage = Math.max(0, Math.min(nP - 1, st.memPage)); var v = memVals(c), it = itDe(c), adr = it ? C.entier(st.sim.lire(it.ins[0])) : null, hd = Math.ceil(dw / 4), ha = Math.ceil(aw / 4);
var h = '<div class="chronoBarre"><b style="font-weight:500">' + (c.t === 'rom' ? 'ROM' : 'RAM') + ' ' + taille + ' × ' + dw + ' bits' + (c.a.label ? ' « ' + esc(c.a.label) + ' »' : '') + '</b>' +
(nP > 1 ? '<button data-mempage="-1" title="page précédente">‹</button><span class="lgs__note">' + (st.memPage + 1) + ' / ' + nP + '</span><button data-mempage="1" title="page suivante">›</button>' : '') +
'<button data-act="memcharger" title="charger une image (Logisim v2.0 raw / v3.0 hex, ou addr/data)">⇪ charger</button><button data-act="memsauver" title="enregistrer l\'image (v3.0 hex words plain)">⇩ image</button><button data-act="memvider" title="tout à zéro">⌫</button></div>';
h += '<table class="mem"><tr><th></th>'; for (var k = 0; k < parL; k++) h += '<th>' + k.toString(16) + '</th>'; h += '</tr>';
for (var a0 = st.memPage * page; a0 < Math.min(taille, (st.memPage + 1) * page); a0 += parL) {
h += '<tr><th>' + a0.toString(16).padStart(ha, '0') + '</th>';
for (var j = 0; j < parL && a0 + j < taille; j++) { var x = v[a0 + j] || 0; h += '<td data-memmot="' + (a0 + j) + '" class="' + (adr === a0 + j ? 'ici' : '') + (x ? ' nz' : '') + '">' + x.toString(16).padStart(hd, '0') + '</td>'; }
h += '</tr>';
}
return h + '</table><input type="file" data-memfichier hidden>';
}
function memEcrire(c, vals) {
if (c.t === 'rom') { changer(function () { c.a.contents = C.ecrireContenu(vals, +c.a.addrWidth || 8, +c.a.dataWidth || 8); }, [c]); return; }
var it = itDe(c); if (!it) return; var m = {}; vals.forEach(function (x, i) { if (x) m[i] = x; }); it.st.mem = m; st.sim.propager(); dessiner(); bas();
}
// ------------------------------------------------------------ la BULLE au survol (comme les infobulles de Logisim sur les ports) : le nom, la
// largeur et la valeur d'un port ou d'un fil sous la souris
var bulle = document.createElement('div'); bulle.className = 'lgs__bulle'; bulle.setAttribute('aria-hidden', 'true'); plan.appendChild(bulle);
function survolInfo(ev) {
if (ev.pointerType !== 'mouse' || geste || !st.projet) { bulle.style.display = 'none'; return; }
var p = versPlan(ev), cc = circ(), tr = null, rayon = 6 / Math.max(.5, st.vue.z);
(cc.comps || []).some(function (c) { return C.portsAbs(c, st.projet).some(function (q) { if (Math.abs(q.x - p[0]) <= rayon && Math.abs(q.y - p[1]) <= rayon) { tr = { c: c, q: q }; return true; } }); });
var txt2 = '';
if (tr) { var v = st.sim ? st.sim.valeurEn(tr.q.x, tr.q.y, cheminInst()) : null; txt2 = '<b>' + esc(tr.q.n || '?') + '</b> · ' + esc((C.T[tr.c.t] || {}).circ || tr.c.t) + ' · ' + (tr.q.d === 'out' ? 'sortie' : tr.q.d === 'in' ? 'entrée' : 'e/s') + ' · ' + tr.q.w + ' bit' + (tr.q.w > 1 ? 's' : '') + (v ? ' = ' + esc(valTexte(v)) : ''); }
else { var wi = filEn(p); if (wi >= 0) { var wv = cc.wires[wi], v2 = st.sim ? st.sim.valeurEn(wv[0], wv[1], cheminInst()) : null; if (v2) txt2 = 'fil · ' + v2.length + ' bit' + (v2.length > 1 ? 's' : '') + ' = ' + esc(valTexte(v2)); } }
if (!txt2) { bulle.style.display = 'none'; return; }
var r = plan.getBoundingClientRect(); bulle.innerHTML = txt2; bulle.style.display = 'block';
var bx = ev.clientX - r.left + 14, by = ev.clientY - r.top + 16; if (bx + bulle.offsetWidth > r.width - 4) bx = ev.clientX - r.left - bulle.offsetWidth - 10; if (by + bulle.offsetHeight > r.height - 4) by = ev.clientY - r.top - bulle.offsetHeight - 10;
bulle.style.left = bx + 'px'; bulle.style.top = by + 'px';
}
function valTexte(v) { var t = C.texteMot(v); if (v.length === 1 || /[^01]/.test(t)) return t; var n = parseInt(t, 2); return t + ' = 0x' + n.toString(16) + ' = ' + n; }
plan.addEventListener('pointermove', survolInfo);
plan.addEventListener('pointerleave', function () { bulle.style.display = 'none'; });
// ------------------------------------------------------------ horloge (seulement sur ▶ et visible)
var tHorloge = null;
function horloge() {
clearInterval(tHorloge); tHorloge = null;
if (!st.joue) return;
var periode = Math.max(16, 1000 / st.hz), parBattement = Math.max(1, Math.round(st.hz * periode / 1000));
tHorloge = setInterval(function () { if (document.hidden || !R.isConnected || !st.sim) return; for (var i = 0; i < parBattement; i++) { st.sim.tic(); st.chrono.prendre(st.sim, 'tic'); } majChronoBientot(); dessiner(); if (st.fen.mem || st.onglet === 'mem') fenetresMem(); }, periode);
}
function fenetresMem() { // la mémoire suit l'adresse courante pendant que l'horloge tourne (sans tout redessiner)
var el = st.fen.mem ? R.querySelector('.lgs__fen[data-fen="mem"] .lgs__fencorps') : (!st.basFerme && st.onglet === 'mem' ? $('[data-corps]') : null);
if (el) el.innerHTML = ongletMem();
}
function a11y() { // chaque bouton à glyphe a un nom pour les lecteurs d'écran ; le plan est décrit
R.querySelectorAll('button[title]:not([aria-label])').forEach(function (b) { b.setAttribute('aria-label', b.getAttribute('title')); });
R.querySelectorAll('[data-outil]').forEach(function (b) { b.setAttribute('aria-pressed', b.classList.contains('on') ? 'true' : 'false'); });
R.querySelectorAll('.lgs__it').forEach(function (it) { if (!it.hasAttribute('tabindex')) { it.setAttribute('tabindex', '0'); it.setAttribute('role', 'button'); } });
var cc = circ(); svg.setAttribute('aria-label', 'circuit ' + st.cur + ' : ' + (cc.comps || []).length + ' pièces, ' + (cc.wires || []).length + ' fils');
}
function tout() { $('[data-nomprojet]').value = st.projet.nom; panneaux(); bas(); filAriane(); dessiner(); a11y(); }
var ro = window.ResizeObserver ? new ResizeObserver(function () { dessiner(); }) : null; if (ro) ro.observe(plan);
// ------------------------------------------------------------ départ : le dernier projet, sinon un circuit d'exemple
if (ls('xb:logisim:toile') === 'sombre') R.classList.add('toile-sombre');
outil('edit');
var depart = null; try { depart = JSON.parse(ls('xb:logisim:auto') || 'null'); } catch (e) {}
var lien = ctx.c || (function () { try { return new URLSearchParams(location.search).get('c'); } catch (e) { return null; } })();
if (depart && depart.circuits) charger(depart); else nouveau();
if (lien && /^[a-z0-9][a-z0-9-]{2,80}$/.test(lien)) ouvrirPublic(lien);
if (ls('xb:logisim:pdf') === 'off') R.classList.remove('avec-pdf');
chargerBiblio();
echantillon('debut');
if (!st.auteur) setTimeout(function () { toast('✎ dis ton nom d\'auteur (owner) pour signer tes pièces comme Logisim', 4200); }, 900);
return { unmount: function () {
st.joue = false; clearInterval(tHorloge); clearTimeout(tSauve); if (raf) cancelAnimationFrame(raf);
document.removeEventListener('keydown', surTouche); if (ro) ro.disconnect(); offsBus.forEach(function (f) { try { f(); } catch (e) {} });
if (st.pdf && st.pdf.blob) URL.revokeObjectURL(st.pdf.url);
try { ls('xb:logisim:auto', instantane()); } catch (e) {}
container.innerHTML = '';
} };
}
window.jOSApps = window.jOSApps || {};
window.jOSApps[ID] = { manifest: { id: ID, name: 'Logisim', icon: '⊼' }, mount: mount, describe: describe };
})();
</script>