Files
homeclaw/web-ui/html/pcb-app.html
T
kimandClaude Sonnet 5.5 e03641bcc0 fix(workshop): PCB 탭 — 연결된 PCB가 없으면 마지막으로 연 PCB 대신 빈 PCB로 시작
작업실 프로젝트에 연결된 PCB가 없을 때 PCB 앱이 localStorage의 마지막 프로젝트를 열어
다른 프로젝트의 PCB(300B 앰프)가 뜨던 문제. ?ws=<프로젝트id>를 넘겨 빈 PCB로 시작하고
그 작업실 프로젝트에 묶는다. 저장 안 된 편집(dirty)이 있으면 기존 동작 유지.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 16:23:06 +09:00

1744 lines
151 KiB
HTML
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.
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>🔌 PCB 제작</title>
<style>
:root{--bg:#0f1117;--panel:#1a1d27;--panel2:#22263a;--line:#2e3250;--text:#e2e8f0;--muted:#94a3b8;--brand:#6366f1;--brand2:#818cf8;--green:#22c55e;--red:#ef4444;--yellow:#f59e0b;--r:10px;--canvas:#0d2a18;}
@media (prefers-color-scheme: light){:root{--bg:#eef1f8;--panel:#fff;--panel2:#f0f3fb;--line:#cdd3e8;--text:#1e2337;--muted:#5a6480;--brand:#4f52cc;--brand2:#4f52cc;--green:#15803d;--red:#dc2626;--yellow:#b45309;}}
*{box-sizing:border-box;margin:0;padding:0}
body{background:var(--bg);color:var(--text);font-family:'Segoe UI',system-ui,sans-serif;font-size:13px;height:100vh;display:flex;flex-direction:column;overflow:hidden}
header{display:flex;align-items:center;gap:8px;padding:8px 12px;background:var(--panel);border-bottom:1px solid var(--line);flex-wrap:wrap}
header h1{font-size:15px;margin-right:6px}
.btn{background:var(--panel2);color:var(--text);border:1px solid var(--line);border-radius:8px;padding:6px 11px;font-size:12.5px;cursor:pointer;white-space:nowrap}
.btn:hover{border-color:var(--brand)}
.btn.pri{background:var(--brand);color:#fff;border-color:var(--brand);font-weight:600}
.btn.on{border-color:var(--brand);color:var(--brand2);background:rgba(99,102,241,.16)}
.btn:disabled{opacity:.5;cursor:default}
#fr{font-size:11.5px;color:var(--muted);margin-left:auto}
.wrap{flex:1;display:grid;grid-template-columns:230px 1fr 320px;min-height:0}
aside{background:var(--panel);overflow-y:auto;padding:10px}
#left{border-right:1px solid var(--line)}#right{border-left:1px solid var(--line)}
h3{font-size:11px;text-transform:uppercase;letter-spacing:.06em;color:var(--muted);margin:10px 0 6px}
h3:first-child{margin-top:0}
input,select{background:var(--panel2);border:1px solid var(--line);border-radius:6px;padding:5px 7px;font-size:12.5px;color:var(--text);width:100%}
.lib button{display:block;width:100%;text-align:left;background:none;border:0;border-radius:6px;padding:5px 7px;color:var(--text);font-size:12.5px;cursor:pointer}
.lib button:hover{background:var(--panel2)}
.lib .sub{display:block;font-size:10.5px;color:var(--muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.lib .grp{font-size:10.5px;color:var(--muted);margin:8px 0 2px;font-weight:700}
#center{display:flex;flex-direction:column;min-width:0;min-height:0}
#bar,#sbar{display:flex;gap:6px;align-items:center;padding:6px 10px;background:var(--panel2);border-bottom:1px solid var(--line);flex-wrap:wrap;min-height:40px}
#bar .sp,#sbar .sp{flex:1}
#cv,#scv{flex:1;min-height:0;position:relative}
.tab{background:none;border:0;border-bottom:3px solid transparent;color:var(--muted);padding:7px 16px;font-size:13px;font-weight:600;cursor:pointer}
.tab.on{color:var(--brand2);border-bottom-color:var(--brand)}
#slabel{position:absolute;display:none;z-index:5;background:var(--panel);border:1px solid var(--brand);border-radius:6px;padding:3px 6px;font-size:12px;width:120px}
canvas{position:absolute;inset:0;width:100%;height:100%;display:block;touch-action:none;background:var(--canvas)}
#hint{font-size:11.5px;color:var(--muted)}
.grid2{display:grid;grid-template-columns:1fr 1fr;gap:6px 8px}
.grid2 label{font-size:11px;color:var(--muted);display:block;margin-bottom:2px}
.net{background:var(--panel2);border:1px solid var(--line);border-radius:8px;padding:6px;margin-bottom:6px}
.net input{font-weight:600;margin-bottom:4px}
.chip{display:inline-flex;gap:3px;align-items:center;background:rgba(99,102,241,.16);color:var(--brand2);border-radius:10px;padding:1px 3px 1px 7px;font-size:11px;margin:1px 2px 1px 0}
.chip button{background:none;border:0;color:inherit;cursor:pointer;font-size:12px;line-height:1}
#res{font-size:12px;line-height:1.6}
.ok{color:var(--green)}.bad{color:var(--red)}.warn{color:var(--yellow)}
.dl a{display:block;margin:3px 0;color:var(--brand2);text-decoration:none;font-size:12.5px}
details{margin-bottom:6px}summary{cursor:pointer;font-weight:700;font-size:12.5px;padding:4px 0}
.note{font-size:11px;color:var(--muted);line-height:1.5;margin-top:4px}
#simpane{display:none;flex-direction:column;border-top:2px solid var(--brand);background:var(--panel);height:300px;min-height:140px}
#simhead{display:flex;align-items:center;gap:8px;padding:5px 10px;background:var(--panel2);font-size:12px}
#simhead b{flex:1}
#simbody{flex:1;display:flex;min-height:0}
#simchart{flex:1;position:relative;min-width:0}
#sc{position:absolute;inset:0;width:100%;height:100%;background:var(--panel)}
#simside{width:300px;overflow-y:auto;padding:8px 10px;font-size:12px;border-left:1px solid var(--line)}
#simside table{width:100%;border-collapse:collapse}#simside td{padding:2px 4px;border-bottom:1px solid var(--line)}
#simside td:last-child{text-align:right;font-variant-numeric:tabular-nums}
#simside pre{white-space:pre-wrap;font-size:10.5px;color:var(--muted);max-height:180px;overflow:auto}
.srow{display:grid;grid-template-columns:1fr 1fr;gap:4px;background:var(--panel2);border:1px solid var(--line);border-radius:8px;padding:6px;margin-bottom:6px}
.srow .full{grid-column:1/3}.srow label{font-size:10.5px;color:var(--muted)}
.pchk{display:inline-flex;align-items:center;gap:3px;margin:2px 8px 2px 0;font-size:12px}.pchk input{width:auto}
#plistbox{display:none;position:absolute;top:46px;left:12px;z-index:60;width:400px;max-height:62vh;overflow:auto;background:var(--panel);border:1px solid var(--brand);border-radius:10px;padding:8px;box-shadow:0 8px 24px rgba(0,0,0,.35)}
#plistbox .prow{display:flex;gap:6px;align-items:center;padding:6px 4px;border-bottom:1px solid var(--line)}
#plistbox .prow .nm{flex:1;min-width:0;cursor:pointer}#plistbox .prow .nm b{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
#plistbox .prow .nm span{font-size:11px;color:var(--muted)}
#pname{width:210px}
#wsel{width:150px}
#pane-desc{display:none;flex:1;min-height:0;flex-direction:column;padding:8px;gap:6px;background:var(--bg)}
#desc-view{flex:1;min-height:0;overflow:auto;padding:12px 18px;background:var(--panel);border:1px solid var(--line);border-radius:8px;line-height:1.65;font-size:14px}
#desc-ta{flex:1;min-height:0;width:100%;resize:none;font:13px/1.55 'D2Coding','IBM Plex Mono',monospace;background:var(--panel);color:var(--text);border:1px solid var(--line);border-radius:8px;padding:10px}
.md h1{font-size:20px;margin:6px 0 10px}.md h2{font-size:17px;margin:18px 0 8px;padding-bottom:4px;border-bottom:1px solid var(--line)}.md h3{font-size:15px;margin:14px 0 6px}
.md p{margin:6px 0}.md ul,.md ol{margin:6px 0 6px 22px;padding:0}.md li{margin:2px 0}.md code{background:var(--panel2);padding:1px 5px;border-radius:4px;font-size:12.5px}
.md pre{background:#0d1117;color:#d6e2f0;padding:10px 12px;border-radius:8px;overflow:auto;font-size:12.5px;line-height:1.45}.md pre code{background:none;padding:0;color:inherit}
.md blockquote{margin:8px 0;padding:4px 12px;border-left:3px solid var(--brand);color:var(--muted)}.md hr{border:0;border-top:1px solid var(--line);margin:14px 0}
.md table{border-collapse:collapse;margin:8px 0;font-size:13px}.md th{background:var(--panel2);text-align:left}.md th,.md td{border:1px solid var(--line);padding:4px 10px}
#pane-cons{display:none;flex:1;min-height:0;flex-direction:column;padding:8px;gap:6px;background:var(--bg)}
.rb-console-bar{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
.rb-console-proj{font-size:12px;font-weight:600;margin-right:4px}
.rb-console-status{font-size:11px;color:var(--muted)}
.rb-console-warn{font-size:11px;color:#f59e0b}
#console-term{flex:1;min-height:320px;background:#0d1117;border:1px solid var(--line);border-radius:8px;padding:6px;overflow:hidden}
@media (max-width:1000px){
body{height:auto;overflow:auto}
.wrap{display:block}
#center{height:62vh}
aside{border:0;border-top:1px solid var(--line)}
}
</style>
</head>
<body>
<div id="plistbox"></div>
<header>
<h1>🔌 PCB 제작</h1>
<button class="btn" onclick="newProject(true)">새로 만들기</button>
<input id="pname" placeholder="프로젝트 이름 (입력하면 서버에 자동 저장)" title="사용자 작업 폴더 pcb/<이름>/ 에 자동 저장됩니다" onchange="renameProject(this.value)"><select id="wsel" onchange="setWorkshop(this.value)" title="작업실 프로젝트와 연결 — 저장할 때마다 project.json·G-code가 작업실 프로젝트의 PCB/<이름>/ 폴더에도 복사됩니다"><option value="">작업실 연결 없음</option></select><button class="btn" onclick="toggleProjects()">📁 프로젝트</button><span id="psave" style="font-size:11.5px;color:var(--muted);max-width:340px"></span>
<button class="btn" id="undo" onclick="undo()" title="실행 취소 (Ctrl+Z)" disabled>↶</button><button class="btn" id="redo" onclick="redo()" title="다시 실행 (Ctrl+Y)" disabled>↷</button>
<select id="exsel" class="btn" style="width:auto" onchange="loadExample(this.value);this.value=''"><option value="">예제 ▾</option><option value="basic">기초: 핀헤더 + 저항 배선</option><option value="smps_fb">555 승압 SMPS + 전압 피드백 (5V→12.2V 정전압)</option><option value="smps">555 승압 SMPS 기초 (피드백 없음)</option></select>
<button class="btn" onclick="saveFile()">💾 저장</button>
<button class="btn" onclick="$('file').click()">📂 불러오기</button>
<input type="file" id="file" accept=".json" style="display:none" onchange="loadFile(this)">
<span id="fr">Freerouting 확인 중…</span>
</header>
<div class="wrap">
<aside id="left">
<h3>KiCad 라이브러리 <span id="kst" style="text-transform:none;font-weight:400"></span></h3>
<div style="display:flex;gap:4px"><input id="kq" placeholder="NE555, LM358, 2N3904, 0805…" oninput="kSearchDebounced()"><select id="kk" style="width:84px" onchange="kSearch()"><option value="sym">부품</option><option value="fp">풋프린트</option></select></div>
<div class="lib" id="kres"></div>
<div id="kpick"></div>
<h3>기본 부품</h3>
<input id="libq" placeholder="검색 (예: DIP, 저항, LED)" oninput="renderLib()">
<div class="lib" id="lib"></div>
</aside>
<section id="center">
<div id="tabs" style="display:flex;background:var(--panel);border-bottom:1px solid var(--line)"><button class="tab" id="t-sch" onclick="setTab('sch')">📐 회로도</button><button class="tab" id="t-pcb" onclick="setTab('pcb')">🔌 기판</button><button class="tab" id="t-desc" onclick="setTab('desc')" title="이 프로젝트의 회로 설명(README.md) — 콘솔의 Claude도 같은 파일을 읽고 씁니다">📝 회로 설명</button><button class="tab" id="t-cons" onclick="setTab('cons')" title="이 프로젝트 폴더에서 Claude Code·셸 실행(관리자 전용)">💻 콘솔</button></div>
<div id="sbar" style="display:none">
<button class="btn on" id="s-select" onclick="setSMode('select')" title="V">↖ 선택·이동</button>
<button class="btn" id="s-wire" onclick="setSMode('wire')" title="W">✎ 배선</button>
<button class="btn" id="s-label" onclick="setSMode('label')" title="L">🏷 넷 이름</button>
<button class="btn" id="s-power" onclick="setSMode('power')" title="P">⏚ 전원</button>
<select id="spow" style="width:84px"><option>GND</option><option>+5V</option><option>+3V3</option><option>+12V</option><option>VCC</option><option>VDD</option><option>-12V</option></select>
<span id="sinfo" style="font-size:12px;color:var(--muted)"></span>
<button class="btn" onclick="schDots()" title="선택한 부품의 핀에 극성 점(권선 시작 표시)을 찍거나 지웁니다 — 트랜스·코일용">● 극성점</button>
<button class="btn" onclick="schRotate()" title="R">⟳ 회전</button>
<button class="btn" onclick="schMirror()" title="M">⇋ 반전</button>
<button class="btn" onclick="schDelete()" title="Delete">🗑 삭제</button>
<span class="sp"></span>
<button class="btn" onclick="schAutoWires()" title="기판/예제의 연결을 선과 넷 이름으로 자동 생성">⚡ 연결선 자동 생성</button>
<button class="btn" onclick="schAutoArrange()" title="신호 흐름 순서(왼쪽 입력 → 오른쪽 출력)로 부품을 열에 나눠 정렬하고 방향을 맞춘 뒤 다시 배선합니다 (실행 취소로 되돌림)">🧩 자동 정렬</button>
<button class="btn" onclick="schRewire()" title="회로도의 선·이름표·전원 기호를 모두 지우고 현재 연결(넷)대로 다시 배선 (부품 위치는 유지)">♻ 다시 배선</button>
<button class="btn" onclick="schFit()">⤢ 맞춤</button>
</div>
<div id="bar">
<button class="btn on" id="m-select" onclick="setMode('select')" title="V">↖ 선택·이동</button>
<button class="btn" id="m-connect" onclick="setMode('connect')" title="C">🔗 핀 연결</button>
<span id="selinfo" style="font-size:12px;color:var(--muted)"></span>
<input id="pval" placeholder="값 (예: 4.7k)" style="width:92px" onchange="setVal(this.value)">
<button class="btn" onclick="rotateSel()" title="R">⟳ 회전</button>
<button class="btn" onclick="deleteSel()" title="Delete">🗑 삭제</button>
<span class="sp"></span>
<button class="btn pri" id="rbtn2" onclick="doRoute()" title="Freerouting 으로 자동 배선">🧭 자동 배선</button>
<label style="font-size:11px;color:var(--muted)">격자</label>
<select id="snap" style="width:76px" onchange="draw()"><option value="0.5">0.5mm</option><option value="1.27">1.27mm</option><option value="2.54" selected>2.54mm</option><option value="0.1">0.1mm</option></select>
<button class="btn" onclick="fitView()">⤢ 맞춤</button>
</div>
<div id="pane-desc">
<div class="rb-console-bar">
<span id="desc-title" class="rb-console-proj"></span>
<button class="btn" id="desc-edit" onclick="descToggle()">✏ 편집</button>
<button class="btn" id="desc-save" onclick="descSave()" style="display:none">💾 저장</button>
<button class="btn" onclick="descDraft()" title="부품표·연결(넷)로 설명 초안을 만들어 편집창에 넣습니다">📋 초안 만들기</button>
<button class="btn" onclick="openDesc(true)" title="서버의 파일을 다시 읽기">↻ 새로고침</button>
<span id="desc-status" class="rb-console-status"></span>
</div>
<div id="desc-view" class="md"></div>
<textarea id="desc-ta" spellcheck="false" style="display:none" oninput="descDirty=true;$('desc-status').textContent='수정됨(저장 안 됨)'"></textarea>
</div>
<div id="pane-cons">
<div class="rb-console-bar">
<span id="console-proj" class="rb-console-proj"></span>
<button class="btn" onclick="consoleStart('claude')">▶ claude 시작</button>
<button class="btn" onclick="consoleStart('claude-chrome')" title="claude --chrome — 서버의 크롬을 조작하는 도구까지 연결">▶ claude + 크롬</button>
<button class="btn" onclick="consoleStart('claude-ollama')" title="ollama launch claude — 올라마 모델로 Claude Code 실행">▶ claude (올라마)</button>
<button class="btn" onclick="consoleStart('shell')">🐚 셸</button>
<button class="btn" onclick="consoleStop()">■ 종료</button>
<button class="btn" onclick="consoleClear()">🧹 지우기</button>
<span id="console-status" class="rb-console-status"></span>
</div>
<div class="rb-console-warn">⚠ 서버 전체에 접근하는 터미널입니다(관리자 로그인 + 같은 주소에서만 열림). 이 프로젝트 폴더(pcb/&lt;이름&gt;/)에서 시작합니다. Claude가 project.json을 고치면 저장 후 앱에서 "서버 것 불러오기"로 반영하세요.</div>
<div id="console-term"></div>
</div>
<div id="cv"><canvas id="c"></canvas></div>
<div id="scv" style="display:none"><canvas id="sc2"></canvas><input id="slabel" placeholder="넷 이름" autocomplete="off"></div>
<div id="simpane">
<div id="simhead"><b id="simtitle">시뮬레이션 결과</b><button class="btn" onclick="$('simpane').style.display='none';resize()">닫기 ✕</button></div>
<div id="simbody"><div id="simchart"><canvas id="sc"></canvas></div><div id="simside"></div></div>
</div>
<div id="bar" style="border-top:1px solid var(--line);border-bottom:0"><span id="hint">부품을 왼쪽에서 눌러 추가 → 끌어서 배치 → 🔗 핀 연결 모드에서 핀을 차례로 클릭해 연결 → 오른쪽에서 자동 배선</span></div>
</section>
<aside id="right">
<details open><summary>보드 · 규칙</summary>
<div class="grid2">
<div><label>가로 mm</label><input type="number" id="bw" min="10" step="1" onchange="applySettings()"></div>
<div><label>세로 mm</label><input type="number" id="bh" min="10" step="1" onchange="applySettings()"></div>
<div style="grid-column:1/3"><label>동박 구성</label>
<select id="lay" onchange="applySettings()"><option value="1B">단면 — 아랫면(B.Cu), 부품은 윗면</option><option value="1F">단면 — 윗면(F.Cu), SMD 가능</option><option value="2">양면</option></select></div>
<div><label>배선 폭 mm</label><input type="number" id="tw" step="0.05" min="0.1" onchange="applySettings()"></div>
<div><label>최소 간격 mm</label><input type="number" id="cl" step="0.05" min="0.1" onchange="applySettings()"></div>
<div><label>비아 지름 mm</label><input type="number" id="vd" step="0.1" onchange="applySettings()"></div>
<div><label>비아 드릴 mm</label><input type="number" id="vh" step="0.1" onchange="applySettings()"></div>
</div>
</details>
<details><summary>연결(넷)</summary>
<div id="nets"></div>
<div class="note">🔗 핀 연결 모드에서 핀 A → 핀 B를 클릭하면 이어집니다. 계속 클릭하면 같은 넷에 추가됩니다. Esc로 끊기.</div>
</details>
<details open><summary>자동 배선 (Freerouting)</summary>
<div class="grid2"><div><label>최대 패스</label><input type="number" id="passes" value="30" min="1" max="100"></div><div><label>제한 시간(초)</label><input type="number" id="tmo" value="120" min="10" max="600"></div></div>
<label style="display:block;margin-top:8px;font-size:12px"><input type="checkbox" id="jmp" checked style="width:auto"> 못 이은 곳은 점퍼선으로 연결 (단면)</label>
<button class="btn pri" id="rbtn" style="width:100%;margin-top:8px" onclick="doRoute()">🧭 자동 배선</button>
<div id="rres" class="note"></div>
</details>
<details><summary>밀링 설정</summary>
<div class="grid2">
<div><label>가공 폭(절삭폭) mm</label><input type="number" id="m_toolDia" step="0.05" onchange="applyMill()"></div>
<div><label>격리 패스 수</label><input type="number" id="m_passes" step="1" min="1" max="6" onchange="applyMill()"></div>
<div><label>패스 겹침 0~0.9</label><input type="number" id="m_overlap" step="0.1" onchange="applyMill()"></div>
<div><label>격리 깊이 Z mm</label><input type="number" id="m_cutZ" step="0.01" onchange="applyMill()"></div>
<div><label>이송 mm/min</label><input type="number" id="m_feed" onchange="applyMill()"></div>
<div><label>하강 mm/min</label><input type="number" id="m_plunge" onchange="applyMill()"></div>
<div><label>안전 높이 Z</label><input type="number" id="m_safeZ" step="0.5" onchange="applyMill()"></div>
<div><label>스핀들 rpm (0=수동)</label><input type="number" id="m_rpm" step="1000" onchange="applyMill()"></div>
<div><label>드릴 깊이 Z</label><input type="number" id="m_drillZ" step="0.1" onchange="applyMill()"></div>
<div><label>외곽 비트 Ø mm</label><input type="number" id="m_outlineDia" step="0.1" onchange="applyMill()"></div>
<div><label>외곽 깊이 Z</label><input type="number" id="m_outlineZ" step="0.1" onchange="applyMill()"></div>
<div><label>외곽 단차 mm</label><input type="number" id="m_outlineStep" step="0.1" onchange="applyMill()"></div>
<div style="grid-column:1/3"><label>실크 면</label><select id="m_silkSide" onchange="applyMill()"><option value="top">부품면(반대면, 보드를 뒤집어 새김) — 권장</option><option value="copper">동박면(배선 사이 빈 곳에만)</option></select></div>
<div><label>실크 깊이 Z</label><input type="number" id="m_silkZ" step="0.01" onchange="applyMill()"></div>
<div style="align-self:end"><label><input type="checkbox" id="m_silk" style="width:auto" onchange="applyMill()"> 실크(부품 윤곽) 새기기</label></div>
<div style="grid-column:1/3"><label><input type="checkbox" id="m_mirror" style="width:auto" onchange="applyMill()"> 아랫면 단면: 좌우 반전(뒤집어서 가공)</label></div>
</div>
<div class="note">V비트라면 "가공 폭"은 깊이에서의 유효 폭입니다. 최소 간격은 가공 폭 이상이어야 배선 사이가 분리됩니다.</div>
</details>
<details><summary>회로 시뮬레이션 (ngspice)</summary>
<label style="font-size:11px;color:var(--muted)">접지(0V) 넷</label><select id="s_gnd" onchange="simChanged()"></select>
<h3>전원 · 신호원</h3>
<div id="s_src"></div>
<button class="btn" onclick="addSrc()">+ 추가</button>
<h3>해석</h3>
<select id="s_an" onchange="simChanged()"><option value="op">동작점 (DC 전압·전류)</option><option value="tran">시간 응답 (파형)</option><option value="ac">주파수 응답 (AC)</option></select>
<div id="s_anp" class="grid2" style="margin-top:6px"></div>
<h3>관찰할 넷</h3>
<div id="s_probes"></div>
<button class="btn pri" id="sbtn" style="width:100%;margin-top:8px" onclick="doSim()">▶ 시뮬레이션</button>
<div id="s_msg" class="note"></div>
<div class="note">저항·커패시터·코일은 <b>값</b> 칸(4.7k, 100n)이 필요합니다. 트랜지스터·IC는 KiCad 심볼로 추가하세요. IC는 555, 연산증폭기, 78xx만 지원합니다.</div>
</details>
<details open><summary>G-code</summary>
<button class="btn pri" id="gbtn" style="width:100%" onclick="doGcode()">⚙ G-code 생성 · 미리보기</button>
<div id="res"></div>
<div class="dl" id="dl"></div>
<h3>🏭 밀링 머신 (옥토서버)</h3>
<div id="mill" class="note">확인 중…</div>
</details>
</aside>
</div>
<script>
const $=id=>document.getElementById(id);
const esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
function authH(extra){let t='';try{t=sessionStorage.getItem('smallclaw_token')||localStorage.getItem('smallclaw_token')||'';}catch(e){}const h={...(extra||{})};if(t)h['Authorization']='Bearer '+t;return h;}
async function api(url,body,method){
const r=await fetch(url,{method:method||(body?'POST':'GET'),credentials:'include',headers:authH(body?{'Content-Type':'application/json'}:{}),body:body?JSON.stringify(body):undefined});
const d=await r.json().catch(()=>({}));
if(!r.ok){const e=new Error(d.error||('서버 오류 '+r.status));e.status=r.status;e.data=d;throw e;}
return d;
}
// ───────────── 모델 ─────────────
const DEF_RULES={trace:0.4,clearance:0.3,layers:1,copper:'B.Cu',viaDia:0.9,viaDrill:0.5};
const DEF_MILL={toolDia:0.2,passes:2,overlap:0.3,cutZ:-0.1,safeZ:2,feed:200,plunge:60,rpm:10000,drillZ:-1.8,outlineDia:1.0,outlineZ:-1.8,outlineStep:0.6,mirror:true,silk:true,silkSide:'top',silkZ:-0.05};
let tab='pcb';
let FP=[],FPM={};
let P=null, routed=null, gres=null;
let view={s:12,ox:30,oy:30}, mode='select', sel=null, pending=null, drag=null, pan=null, hover=null;
const PREFIX={RES:'R',CAP:'C',LED:'D',DIODE:'D',DIP:'U',SOIC:'U',HDR:'J',TERM:'J',TO:'Q',R:'R',MOUNT:'H'};
function newProject(ask){
if(ask && P && P.parts.length && !confirm('현재 작업을 지우고 새로 만들까요?')) return;
P={board:{w:50,h:35},parts:[],nets:[],fps:{},name:'',rules:{...DEF_RULES},mill:{...DEF_MILL}};
routed=null; gres=null; sel=null; pending=null; histReset(); projDirty=false; if($('pname'))$('pname').value=''; fitView(); syncUI(); changed(true);
}
function loadSample(skipAsk){
if(!skipAsk&&P&&P.parts.length&&!confirm('현재 작업을 예제로 바꿀까요?')) return;
P={board:{w:40,h:30},parts:[
{ref:'J1',fp:'HDR-1x4',x:7.62,y:7.62,rot:0},{ref:'J2',fp:'HDR-1x4',x:30.48,y:7.62,rot:0},{ref:'R1',fp:'RES-AX-7.62',x:15.24,y:22.86,rot:0}],
nets:[{name:'A',pins:['J1-1','J2-1']},{name:'B',pins:['J1-2','J2-2']},{name:'C',pins:['J1-3','R1-1']},{name:'D',pins:['J2-3','R1-2']}],
rules:{...DEF_RULES},mill:{...DEF_MILL}};
routed=null;gres=null;sel=null;pending=null;histReset();fitView();syncUI();changed(true);
}
// 배선 결과가 지금의 배치·연결·규칙에 대한 것인지 판별하는 키(djb2)
function pcbKey(){
if(!P) return '';
const t=JSON.stringify({b:P.board,p:P.parts.map(x=>[x.ref,x.fp,x.x,x.y,x.rot]),n:P.nets.map(n=>[n.name,n.pins]),r:[P.rules.trace,P.rules.clearance,P.rules.layers,P.rules.copper,P.rules.viaDia,P.rules.viaDrill]});
let h=5381; for(let i=0;i<t.length;i++) h=((h<<5)+h+t.charCodeAt(i))|0; return String(h);
}
function save(){try{localStorage.setItem('pcb-project',JSON.stringify({...P,routed:routed||null,routedKey:routed?pcbKey():null,dirty:projDirty}));}catch(e){} if(typeof serverSaveSoon==='function') serverSaveSoon();}
function changed(keepRoute){
if(!keepRoute){ routed=null; gres=null; $('rres').textContent=''; $('res').innerHTML=''; $('dl').innerHTML=''; }
save(); renderNets(); updSel(); draw(); if(tab==='sch') drawSch(); if(typeof renderSim==='function') renderSim();
if(typeof histPush==='function') histPush();
}
// ───────────── 기하 ─────────────
function rotPoint(x,y,rot){const r=((Math.round(rot/90)*90)%360+360)%360;return r===90?[-y,x]:r===180?[-x,-y]:r===270?[y,-x]:[x,y];}
function padsOf(part){
const f=FPM[part.fp]; if(!f) return [];
const r=((Math.round(part.rot/90)*90)%360+360)%360, swap=r===90||r===270;
return f.pads.map(p=>{const [dx,dy]=rotPoint(p.x,p.y,part.rot);return {id:part.ref+'-'+p.n,ref:part.ref,n:p.n,x:part.x+dx,y:part.y+dy,w:swap?p.h:p.w,h:swap?p.w:p.h,shape:p.shape,drill:p.drill,smd:f.smd};});
}
function allPads(){return P.parts.flatMap(padsOf);}
function bboxOf(part){
const f=FPM[part.fp]; if(!f) return null; const b=f.body;
const c=[[b.x0,b.y0],[b.x1,b.y0],[b.x1,b.y1],[b.x0,b.y1]].map(([x,y])=>rotPoint(x,y,part.rot));
const xs=c.map(q=>q[0]+part.x), ys=c.map(q=>q[1]+part.y);
return {x0:Math.min(...xs),y0:Math.min(...ys),x1:Math.max(...xs),y1:Math.max(...ys)};
}
const snapV=v=>{const g=parseFloat($('snap').value)||0.5;return Math.round(v/g)*g;};
const sx=x=>x*view.s+view.ox, sy=y=>y*view.s+view.oy;
const wx=x=>(x-view.ox)/view.s, wy=y=>(y-view.oy)/view.s;
function netOfPin(id){return P.nets.findIndex(n=>n.pins.includes(id));}
function mst(pts){ // Prim — 넷의 에어와이어
if(pts.length<2) return []; const used=[0], edges=[], rest=pts.map((_,i)=>i).slice(1);
while(rest.length){let bi=-1,bj=-1,bd=Infinity;for(const i of used)for(const j of rest){const d=(pts[i].x-pts[j].x)**2+(pts[i].y-pts[j].y)**2;if(d<bd){bd=d;bi=i;bj=j;}}edges.push([pts[bi],pts[bj]]);used.push(bj);rest.splice(rest.indexOf(bj),1);}
return edges;
}
// ───────────── 그리기 ─────────────
const cv=$('c'), ctx=cv.getContext('2d');
function resize(){const r=cv.getBoundingClientRect(),d=window.devicePixelRatio||1;cv.width=Math.round(r.width*d);cv.height=Math.round(r.height*d);ctx.setTransform(d,0,0,d,0,0);draw();}
new ResizeObserver(resize).observe($('cv'));
function fitView(){const r=cv.getBoundingClientRect();if(!P||!r.width)return;const m=30;view.s=Math.max(2,Math.min((r.width-2*m)/P.board.w,(r.height-2*m)/P.board.h));view.ox=(r.width-P.board.w*view.s)/2;view.oy=(r.height-P.board.h*view.s)/2;draw();}
const LC={'F.Cu':'#ef5350','B.Cu':'#42a5f5'};
function copperColor(layer){return P.rules.layers===1?'#c9843f':(LC[layer]||'#c9843f');}
function draw(){
if(!P||!ctx) return;
const r=cv.getBoundingClientRect(); ctx.clearRect(0,0,r.width,r.height);
const W=P.board.w,H=P.board.h;
ctx.fillStyle='#10351f'; ctx.fillRect(sx(0),sy(0),W*view.s,H*view.s);
ctx.strokeStyle='#e8f5e9'; ctx.lineWidth=1.5; ctx.strokeRect(sx(0),sy(0),W*view.s,H*view.s);
const g=parseFloat($('snap').value)||2.54;
if(g*view.s>=7){ctx.fillStyle='rgba(255,255,255,.13)';for(let x=0;x<=W+1e-6;x+=g)for(let y=0;y<=H+1e-6;y+=g)ctx.fillRect(sx(x)-.5,sy(y)-.5,1.2,1.2);}
// 가공 미리보기
if(gres){
ctx.lineWidth=1;ctx.strokeStyle='#ffd54a';
for(const layer of Object.keys(gres.preview.isolation)) for(const loop of gres.preview.isolation[layer]){ctx.beginPath();loop.forEach((q,i)=>i?ctx.lineTo(sx(q[0]),sy(q[1])):ctx.moveTo(sx(q[0]),sy(q[1])));ctx.stroke();}
ctx.strokeStyle='#ff6b6b';ctx.setLineDash([6,4]);ctx.beginPath();gres.preview.outline.forEach((q,i)=>i?ctx.lineTo(sx(q[0]),sy(q[1])):ctx.moveTo(sx(q[0]),sy(q[1])));ctx.closePath();ctx.stroke();ctx.setLineDash([]);
if(gres.preview.silk&&gres.preview.silk.length){ctx.strokeStyle='#80deea';ctx.lineWidth=1;for(const l of gres.preview.silk){ctx.beginPath();l.forEach((q,i)=>i?ctx.lineTo(sx(q[0]),sy(q[1])):ctx.moveTo(sx(q[0]),sy(q[1])));ctx.stroke();}}
}
// 트레이스·비아
if(routed){
for(const t of routed.traces){ctx.strokeStyle=copperColor(t.layer);ctx.globalAlpha=.85;ctx.lineWidth=Math.max(1.5,t.w*view.s);ctx.lineCap='round';ctx.lineJoin='round';ctx.beginPath();t.pts.forEach((q,i)=>i?ctx.lineTo(sx(q[0]),sy(q[1])):ctx.moveTo(sx(q[0]),sy(q[1])));ctx.stroke();}
ctx.globalAlpha=1;
for(const v of routed.vias){ctx.fillStyle='#cfd8dc';ctx.beginPath();ctx.arc(sx(v.x),sy(v.y),P.rules.viaDia/2*view.s,0,7);ctx.fill();ctx.fillStyle='#000';ctx.beginPath();ctx.arc(sx(v.x),sy(v.y),P.rules.viaDrill/2*view.s,0,7);ctx.fill();}
}
// 점퍼선(윗면 전선)
if(routed&&routed.jumpers&&routed.jumpers.length){
const pm0=Object.fromEntries(allPads().map(p=>[p.id,p]));
ctx.save();ctx.strokeStyle='#ffa726';ctx.fillStyle='#ffa726';ctx.lineWidth=Math.max(2,0.7*view.s);ctx.lineCap='round';ctx.setLineDash([view.s*1.2,view.s*0.7]);
const jend=(j)=>{const a=j.pa?{x:j.pa[0],y:j.pa[1]}:pm0[j.a],b=j.pb?{x:j.pb[0],y:j.pb[1]}:pm0[j.b];return a&&b?[a,b]:null;};
routed.jumpers.forEach(j=>{if(!j.pa)return;ctx.setLineDash([]);for(const q of [j.pa,j.pb]){ctx.fillStyle='#cfd8dc';ctx.beginPath();ctx.arc(sx(q[0]),sy(q[1]),0.9*view.s,0,7);ctx.fill();ctx.fillStyle='#000';ctx.beginPath();ctx.arc(sx(q[0]),sy(q[1]),0.45*view.s,0,7);ctx.fill();}ctx.fillStyle='#ffa726';ctx.setLineDash([view.s*1.2,view.s*0.7]);});
routed.jumpers.forEach((j,i)=>{const e=jend(j);if(!e)return;ctx.beginPath();ctx.moveTo(sx(e[0].x),sy(e[0].y));ctx.lineTo(sx(e[1].x),sy(e[1].y));ctx.stroke();});
ctx.setLineDash([]);ctx.font='bold 11px sans-serif';
routed.jumpers.forEach((j,i)=>{const e=jend(j);if(!e)return;ctx.fillText('J'+(i+1),sx((e[0].x+e[1].x)/2)+4,sy((e[0].y+e[1].y)/2)-4);});
ctx.restore();
}
// 부품
for(const part of P.parts){
const b=bboxOf(part); if(!b) continue;
const isSel=sel===part.ref;
ctx.strokeStyle=isSel?'#fff176':'rgba(255,255,255,.55)'; ctx.lineWidth=isSel?2:1;
const cf=FPM[part.fp]&&FPM[part.fp].circle;
if(drawPartShape(part,isSel)){}
else if(cf){const cc=rotPoint(cf.cx,cf.cy,part.rot);ctx.beginPath();ctx.arc(sx(part.x+cc[0]),sy(part.y+cc[1]),cf.r*view.s,0,7);ctx.stroke();
if(/^kicad:Capacitor_THT:CP_/.test(part.fp)){const p1=padsOf(part).find(q=>q.id.endsWith('-1'));if(p1){const dx=p1.x-(part.x+cc[0]),dy=p1.y-(part.y+cc[1]),L=Math.hypot(dx,dy)||1;const ux=dx/L,uy=dy/L,X0=sx(part.x+cc[0]),Y0=sy(part.y+cc[1]),R0=cf.r*view.s; // + 쪽 호(현 너머) 영역에 빗금
ctx.save();ctx.beginPath();ctx.arc(X0,Y0,R0,0,7);ctx.clip();ctx.beginPath();ctx.rect(-1e4,-1e4,2e4,2e4);ctx.moveTo(0,0); // 원으로 자름
ctx.beginPath();const t=R0*0.35,vx=-uy,vy=ux;ctx.moveTo(X0+ux*t+vx*R0*2,Y0+uy*t+vy*R0*2);ctx.lineTo(X0+ux*t-vx*R0*2,Y0+uy*t-vy*R0*2);ctx.lineTo(X0+ux*R0*2-vx*R0*2,Y0+uy*R0*2-vy*R0*2);ctx.lineTo(X0+ux*R0*2+vx*R0*2,Y0+uy*R0*2+vy*R0*2);ctx.closePath();ctx.clip();
ctx.lineWidth=1;const step=Math.max(4,0.55*view.s);for(let k=-R0*3;k<R0*3;k+=step){ctx.beginPath();ctx.moveTo(X0+k-R0*2,Y0+R0*2);ctx.lineTo(X0+k+R0*2,Y0-R0*2);ctx.stroke();}
ctx.restore();
ctx.fillStyle=ctx.strokeStyle;ctx.font='bold 13px sans-serif';ctx.textAlign='center';ctx.fillText('+',sx(part.x+cc[0]+dx/L*cf.r*1.25),sy(part.y+cc[1]+dy/L*cf.r*1.25)+4);ctx.textAlign='left';}}}
else ctx.strokeRect(sx(b.x0),sy(b.y0),(b.x1-b.x0)*view.s,(b.y1-b.y0)*view.s);
ctx.fillStyle=isSel?'#fff176':'rgba(255,255,255,.8)'; ctx.font='11px sans-serif'; ctx.fillText(part.ref+(part.value?' '+part.value:''),sx(b.x0)+2,sy(b.y0)-3);
for(const pad of padsOf(part)){
const net=netOfPin(pad.id)>=0, cx=sx(pad.x), cy=sy(pad.y), w=pad.w*view.s, h=pad.h*view.s;
ctx.fillStyle=pending===pad.id?'#fff176':(net?'#e0a458':'#b0b7c3');
if(pad.shape==='circle'){ctx.beginPath();ctx.arc(cx,cy,w/2,0,7);ctx.fill();}else ctx.fillRect(cx-w/2,cy-h/2,w,h);
if(pad.drill>0){ctx.fillStyle='#10351f';ctx.beginPath();ctx.arc(cx,cy,pad.drill/2*view.s,0,7);ctx.fill();}
if(view.s>=14&&part.pinNames&&part.pinNames[pad.n]){ctx.fillStyle='rgba(255,255,255,.9)';ctx.font='9px sans-serif';ctx.fillText(part.pinNames[pad.n],cx+w/2+2,cy-h/2);}
if(hover===pad.id){ctx.strokeStyle='#fff';ctx.lineWidth=1.5;ctx.strokeRect(cx-w/2-2,cy-h/2-2,w+4,h+4);}
}
}
// 에어와이어(미배선 연결 안내)
const pm=Object.fromEntries(allPads().map(p=>[p.id,p]));
ctx.lineWidth=1;ctx.strokeStyle='rgba(255,255,255,.55)';ctx.setLineDash([3,3]);
if(!routed) for(const n of P.nets){for(const [a,b] of mst(n.pins.map(i=>pm[i]).filter(Boolean))){ctx.beginPath();ctx.moveTo(sx(a.x),sy(a.y));ctx.lineTo(sx(b.x),sy(b.y));ctx.stroke();}}
ctx.setLineDash([]);
if(gres){ctx.fillStyle='#000';ctx.strokeStyle='#fff';for(const h of gres.preview.drills){ctx.beginPath();ctx.arc(sx(h.x),sy(h.y),Math.max(1.5,h.d/2*view.s),0,7);ctx.fill();}}
}
// ───────────── 입력 ─────────────
function pos(e){const r=cv.getBoundingClientRect();return {x:e.clientX-r.left,y:e.clientY-r.top};}
function hitPad(mx,my){
let best=null,bd=Infinity;
for(const p of allPads()){const dx=Math.abs(mx-p.x),dy=Math.abs(my-p.y);const rx=Math.max(p.w,1.6)/2+0.3,ry=Math.max(p.h,1.6)/2+0.3;if(dx<=rx&&dy<=ry){const d=dx*dx+dy*dy;if(d<bd){bd=d;best=p;}}}
return best;
}
function hitPart(mx,my){for(let i=P.parts.length-1;i>=0;i--){const b=bboxOf(P.parts[i]);if(b&&mx>=b.x0&&mx<=b.x1&&my>=b.y0&&my<=b.y1)return P.parts[i];}return null;}
cv.addEventListener('contextmenu',e=>e.preventDefault());
cv.addEventListener('pointerdown',e=>{
cv.setPointerCapture(e.pointerId); const q=pos(e), mx=wx(q.x), my=wy(q.y);
if(e.button===1||e.button===2||e.shiftKey||e.altKey){pan={x:q.x,y:q.y,ox:view.ox,oy:view.oy};return;}
if(mode==='connect'){
const p=hitPad(mx,my);
if(!p){pending=null;draw();return;}
if(pending&&pending!==p.id) connect(pending,p.id);
pending=p.id; draw(); return;
}
const part=hitPart(mx,my);
if(part){sel=part.ref;drag={part,dx:mx-part.x,dy:my-part.y,moved:false};}
else{sel=null;pan={x:q.x,y:q.y,ox:view.ox,oy:view.oy};}
updSel();draw();
});
cv.addEventListener('pointermove',e=>{
const q=pos(e);
if(pan){view.ox=pan.ox+q.x-pan.x;view.oy=pan.oy+q.y-pan.y;draw();return;}
if(drag){drag.part.x=snapV(wx(q.x)-drag.dx);drag.part.y=snapV(wy(q.y)-drag.dy);drag.moved=true;draw();return;}
if(mode==='connect'){const p=hitPad(wx(q.x),wy(q.y));const h=p?p.id:null;if(h!==hover){hover=h;draw();}}
});
cv.addEventListener('pointerup',()=>{ if(drag&&drag.moved) changed(); drag=null; pan=null; });
cv.addEventListener('wheel',e=>{e.preventDefault();const q=pos(e),f=e.deltaY<0?1.15:1/1.15,ns=Math.min(80,Math.max(2,view.s*f));view.ox=q.x-(q.x-view.ox)*(ns/view.s);view.oy=q.y-(q.y-view.oy)*(ns/view.s);view.s=ns;draw();},{passive:false});
window.addEventListener('keydown',e=>{
if(/INPUT|SELECT|TEXTAREA/.test(document.activeElement.tagName)) return;
if(tab==='cons') return;
if(tab==='sch'){schKey(e);return;}
const k=e.key.toLowerCase();
if(k==='r') rotateSel(); else if(k==='delete'||k==='backspace') deleteSel();
else if(k==='c') setMode('connect'); else if(k==='v') setMode('select');
else if(k==='escape'){pending=null;sel=null;updSel();draw();}
else if(sel&&k.startsWith('arrow')){const p=P.parts.find(x=>x.ref===sel),g=parseFloat($('snap').value)||0.5;if(p){if(k==='arrowleft')p.x-=g;if(k==='arrowright')p.x+=g;if(k==='arrowup')p.y-=g;if(k==='arrowdown')p.y+=g;changed();e.preventDefault();}}
});
function setMode(m){if(m==='connect'&&typeof schDriven==='function'&&schDriven()){$('hint').innerHTML='<span class="warn">⚠ 회로도로 연결한 보드입니다. 연결은 📐 회로도 탭에서 고치세요.</span>';m='select';}mode=m;pending=null;hover=null;$('m-select').classList.toggle('on',m==='select');$('m-connect').classList.toggle('on',m==='connect');cv.style.cursor=m==='connect'?'crosshair':'default';draw();}
// ───────────── 편집 ─────────────
function addPart(fpId){
const f=FPM[fpId]; if(!f) return;
const pre=PREFIX[fpId.split('-')[0]]||'X'; let n=1; while(P.parts.some(p=>p.ref===pre+n)) n++;
const b=f.body; const part={ref:pre+n,fp:fpId,x:snapV(P.board.w/2-(b.x0+b.x1)/2),y:snapV(P.board.h/2-(b.y0+b.y1)/2),rot:0};
P.parts.push(part); sel=part.ref; setMode('select'); changed();
}
function rotateSel(){const p=P.parts.find(x=>x.ref===sel);if(!p)return;p.rot=(p.rot+90)%360;changed();}
function deleteSel(){
if(!sel) return; const ref=sel;
P.parts=P.parts.filter(p=>p.ref!==ref);
P.nets.forEach(n=>n.pins=n.pins.filter(id=>!id.startsWith(ref+'-')));
P.nets=P.nets.filter(n=>n.pins.length>=1); sel=null; changed();
}
function connect(a,b){
const ia=netOfPin(a), ib=netOfPin(b);
if(ia>=0&&ia===ib) return;
if(ia<0&&ib<0){let n=1;while(P.nets.some(x=>x.name==='N'+n))n++;P.nets.push({name:'N'+n,pins:[a,b]});}
else if(ia>=0&&ib<0) P.nets[ia].pins.push(b);
else if(ia<0&&ib>=0) P.nets[ib].pins.push(a);
else{P.nets[ia].pins.push(...P.nets[ib].pins);P.nets.splice(ib,1);}
changed();
}
function renderNets(){
$('nets').innerHTML=P.nets.map((n,i)=>`<div class="net"><input value="${esc(n.name)}" onchange="renameNet(${i},this.value)">${n.pins.map(id=>`<span class="chip">${esc(pinLabel(id))}<button onclick="rmPin(${i},'${esc(id)}')">✕</button></span>`).join('')}<div><button class="btn" style="padding:2px 8px;font-size:11px;margin-top:4px" onclick="rmNet(${i})">넷 삭제</button></div></div>`).join('')||'<div class="note">아직 연결이 없습니다.</div>';
}
function renameNet(i,v){if(schDriven()){renderNets();return;}v=v.trim().replace(/[^A-Za-z0-9_+\-]/g,'_');if(!v||P.nets.some((n,j)=>j!==i&&n.name===v)){renderNets();return;}P.nets[i].name=v;changed(true);}
function rmPin(i,id){P.nets[i].pins=P.nets[i].pins.filter(x=>x!==id);if(P.nets[i].pins.length<1)P.nets.splice(i,1);changed();}
function rmNet(i){P.nets.splice(i,1);changed();}
function updSel(){
const p=P.parts.find(x=>x.ref===sel);
$('selinfo').textContent=p?`${p.ref} · ${FPM[p.fp]?FPM[p.fp].name:p.fp} · ${p.rot}°`:'';
$('pval').value=p?(p.value||''):'';$('pval').disabled=!p;
}
// ───────────── KiCad 라이브러리 ─────────────
let kTimer=null,kRes=[],kPickList=[],pickCtx=null;
const clean=n=>String(n||'').replace(/~\{([^}]*)\}/g,'/$1').replace(/^~$/,'');
function kSearchDebounced(){clearTimeout(kTimer);kTimer=setTimeout(kSearch,250);}
async function kSearch(){
const q=$('kq').value.trim();
if(q.length<2){$('kres').innerHTML='';return;}
try{
const d=await api('/api/pcb/kicad/search?q='+encodeURIComponent(q)+'&kind='+$('kk').value);
kRes=d.results;
$('kres').innerHTML=d.results.map((e,i)=>d.kind==='sym'
?`<button onclick="addKSym(${i})" title="${esc(e.desc)}">${esc(e.name)}<span class="sub">${esc(e.lib)} · ${e.pins}핀 · ${esc(e.desc)}</span></button>`
:`<button onclick="addKFp(${i})" title="${esc(e.desc)}">${esc(e.name)}<span class="sub">${esc(e.lib)} · ${e.pads}패드${e.smd?' · SMD':''}</span></button>`).join('')||'<div class="note">결과 없음</div>';
}catch(e){$('kres').innerHTML=`<div class="note bad">${esc(e.message)}</div>`;}
}
function refPrefix(lib,hint){
if(hint) return hint.replace(/[^A-Za-z]/g,'')||'U';
const l=lib.toLowerCase();
return /resistor/.test(l)?'R':/capacitor/.test(l)?'C':/led|diode/.test(l)?'D':/connector|pinheader|terminal/.test(l)?'J':/inductor/.test(l)?'L':/mounting/.test(l)?'H':/transistor|to_/.test(l)?'Q':'U';
}
async function addKicadPart({fp,ref,value,pins,lib,sym}){
try{
const d=await api('/api/pcb/kicad/footprint?id='+encodeURIComponent(fp));
FPM[fp]=d.footprint; P.fps=P.fps||{}; P.fps[fp]=d.footprint;
const pre=refPrefix(lib||'',ref); let n=1; while(P.parts.some(p=>p.ref===pre+n)) n++;
const b=d.footprint.body;
const part={ref:pre+n,fp,x:snapV(P.board.w/2-(b.x0+b.x1)/2),y:snapV(P.board.h/2-(b.y0+b.y1)/2),rot:0,value:value||''};
if(sym) part.sym=sym;
if(pins){part.pinNames={};for(const q of pins){const nm=clean(q.name);if(nm)part.pinNames[q.n]=nm;}
const have=new Set(d.footprint.pads.map(x=>x.n)), miss=pins.map(q=>q.n).filter(x=>!have.has(x));
if(miss.length) $('hint').innerHTML=`<span class="warn">⚠ ${esc(part.ref)}: 심볼 핀 ${esc(miss.join(','))} 번이 풋프린트에 없습니다. 풋프린트를 확인하세요.</span>`;}
P.parts.push(part); sel=part.ref; setMode('select'); changed(); $('pval').focus();
}catch(e){$('kres').insertAdjacentHTML('afterbegin',`<div class="note bad">${esc(e.message)}</div>`);}
}
function addKFp(i){const e=kRes[i];addKicadPart({fp:`kicad:${e.lib}:${e.name}`,lib:e.lib});}
async function addKSym(i){
const e=kRes[i];
try{
const d=await api('/api/pcb/kicad/symbol?id='+encodeURIComponent(e.lib+':'+e.name));
const s=d.symbol;
if(s.footprint){$('kpick').innerHTML='';addKicadPart({fp:'kicad:'+s.footprint,ref:s.ref,value:s.value,pins:s.pins,lib:e.lib,sym:s.id});return;}
pickCtx={sym:s};kPickList=d.candidates;
$('kpick').innerHTML=`<div class="note" style="margin:8px 0 3px">⚠ <b>${esc(s.value)}</b> 는 기본 풋프린트가 없습니다. 하나 고르세요 (${s.pins.length}핀):</div><input id="kpq" placeholder="풋프린트 검색 (0805, DIP-8, TO-92…)" oninput="kPickSearch()"><div class="lib" id="kplist"></div>`;
renderPick();
}catch(err){$('kres').insertAdjacentHTML('afterbegin',`<div class="note bad">${esc(err.message)}</div>`);}
}
function renderPick(){$('kplist').innerHTML=kPickList.slice(0,40).map((e,i)=>`<button onclick="pickFp(${i})">${esc(e.name)}<span class="sub">${esc(e.lib)} · ${e.pads}패드${e.smd?' · SMD':''}</span></button>`).join('')||'<div class="note">결과 없음</div>';}
let kpT=null;
function kPickSearch(){clearTimeout(kpT);kpT=setTimeout(async()=>{const q=$('kpq').value.trim();if(q.length<2)return;try{kPickList=(await api('/api/pcb/kicad/search?kind=fp&q='+encodeURIComponent(q))).results;renderPick();}catch(e){}},250);}
function pickFp(i){const e=kPickList[i],s=pickCtx.sym;$('kpick').innerHTML='';addKicadPart({fp:`kicad:${e.lib}:${e.name}`,ref:s.ref,value:s.value,pins:s.pins,lib:e.lib,sym:s.id});}
function setVal(v){const p=P.parts.find(x=>x.ref===sel);if(!p)return;p.value=v.trim();changed(true);}
function pinLabel(id){const k=id.lastIndexOf('-'),p=P.parts.find(x=>x.ref===id.slice(0,k)),nm=p&&p.pinNames?p.pinNames[id.slice(k+1)]:'';return nm?`${id}·${nm}`:id;}
const fpFresh=new Set(); // 이 페이지 로드에서 서버에서 다시 받은 KiCad 풋프린트(저장본의 옛 외형 정보가 남지 않게)
async function registerFps(){
for(const [id,f] of Object.entries(P.fps||{})) FPM[id]=f;
for(const part of P.parts){ if(part.fp.startsWith('kicad:')&&!fpFresh.has(part.fp)){fpFresh.add(part.fp);delete FPM[part.fp];}
if(!FPM[part.fp]&&part.fp.startsWith('kicad:')){try{const d=await api('/api/pcb/kicad/footprint?id='+encodeURIComponent(part.fp));FPM[part.fp]=d.footprint;P.fps=P.fps||{};P.fps[part.fp]=d.footprint;}catch(e){}} }
draw(); if(typeof schUpdate==='function') schUpdate();
}
// ───────────── 라이브러리/설정 UI ─────────────
function renderLib(){
const q=$('libq').value.trim().toLowerCase(); let h='',g='';
for(const f of FP){ if(q&&!(f.name+' '+f.id+' '+f.group).toLowerCase().includes(q)) continue;
if(f.group!==g){g=f.group;h+=`<div class="grp">${esc(g)}</div>`;}
h+=`<button onclick="addPart('${esc(f.id)}')">${esc(f.name)}</button>`; }
$('lib').innerHTML=h||'<div class="note">결과 없음</div>';
}
function syncUI(){
$('bw').value=P.board.w;$('bh').value=P.board.h;
$('lay').value=P.rules.layers===2?'2':(P.rules.copper==='F.Cu'?'1F':'1B');
$('tw').value=P.rules.trace;$('cl').value=P.rules.clearance;$('vd').value=P.rules.viaDia;$('vh').value=P.rules.viaDrill;
for(const k of Object.keys(DEF_MILL)){const el=$('m_'+k);if(!el)continue;if(el.type==='checkbox')el.checked=!!P.mill[k];else el.value=P.mill[k];}
}
function applySettings(){
P.board.w=Math.max(10,+$('bw').value||50);P.board.h=Math.max(10,+$('bh').value||35);
const l=$('lay').value;P.rules.layers=l==='2'?2:1;P.rules.copper=l==='1F'?'F.Cu':'B.Cu';
P.rules.trace=+$('tw').value||0.4;P.rules.clearance=+$('cl').value||0.3;P.rules.viaDia=+$('vd').value||0.9;P.rules.viaDrill=+$('vh').value||0.5;
changed();fitView();
}
function applyMill(){
for(const k of Object.keys(DEF_MILL)){const el=$('m_'+k);if(!el)continue;P.mill[k]=el.type==='checkbox'?el.checked:(el.tagName==='SELECT'?el.value:(+el.value));}
gres=null;$('res').innerHTML='';$('dl').innerHTML='';save();draw();
}
// ───────────── 배선 · G-code ─────────────
async function doRoute(){
const b=$('rbtn'),b2=$('rbtn2');b.disabled=true;if(b2)b2.disabled=true;$('rres').innerHTML='Freerouting 실행 중… (보드에 따라 수 초~수 분)';
try{
const key0=pcbKey();
const d=await api('/api/pcb/route',{project:P,maxPasses:+$('passes').value||30,timeoutSec:+$('tmo').value||120,jumpers:$('jmp').checked});
if(pcbKey()!==key0){$('rres').innerHTML='<span class="warn">배선 도중 배치·연결이 바뀌어 결과를 버렸습니다. 다시 눌러 주세요.</span>';return;}
routed={traces:d.traces,vias:d.vias,jumpers:d.jumpers||[]};routedCache={key:pcbKey(),routed};gres=null;$('res').innerHTML='';$('dl').innerHTML='';
const un=d.stats.unrouted, jn=routed.jumpers.length;
const jl=jn?`<div class="note" style="margin-top:4px">점퍼선(윗면 전선, 기판의 전용 구멍 Ø0.9 두 곳을 잇기):<br>`+routed.jumpers.map((j,i)=>`J${i+1}: ${esc(j.a)} ↔ ${esc(j.b)} · ${j.len}mm${j.pa?` · 구멍 (${j.pa}) ↔ (${j.pb})`:' · 부품 구멍에 직접'}${j.smd?' ⚠SMD':''}`).join('<br>')+'</div>':'';
$('rres').innerHTML=(un===0?`<span class="ok">✔ 구리 배선 완료</span> · ${d.traces.length}구간 · 비아 ${d.vias.length}개 · ${d.stats.seconds}초`
:jn?`<span class="ok">✔ 구리 + 점퍼선 ${jn}개로 모두 연결</span> · ${d.traces.length}구간 · ${d.stats.seconds}초`
:`<span class="bad">✖ 미배선 ${un<0?'?':un}건</span> (${d.traces.length}구간 배선됨, ${d.stats.seconds}초)<br>부품을 옮기거나 회전해 교차를 줄이거나, '점퍼선' 옵션을 켜 보세요.`)+jl;
save();draw();
}catch(e){$('rres').innerHTML=`<span class="bad">${esc(e.message)}</span>`;}
finally{b.disabled=false;if(b2)b2.disabled=false;}
}
async function doGcode(){
if(!routed){$('res').innerHTML='<span class="bad">먼저 자동 배선을 실행하세요.</span>';return;}
const b=$('gbtn');b.disabled=true;$('res').textContent='생성 중…';
try{
gres=await api('/api/pcb/gcode',{project:P,routed});
const s=gres.stats;
$('res').innerHTML=`구멍 ${s.holes}개(드릴 ${s.drillSizes.join(', ')||'-'}mm) · 격리 경로 ${s.isolationLengthMm}mm · 예상 약 ${s.estMinutes}분`+gres.warnings.map(w=>`<div class="warn">⚠ ${esc(w)}</div>`).join('');
$('dl').innerHTML=Object.keys(gres.files).map(n=>`<a href="#" onclick="dlFile('${esc(n)}');return false">⬇ ${esc(n)}</a>`).join('')+'<div class="note">순서: 격리(copper) → 실크(silk-top.nc: 보드를 뒤집어 부품면, 또는 silk.nc: 동박면) → 드릴(공구 교체 시 M0 일시정지) → 외곽. jumpers.txt 는 조립 시 윗면에 납땜할 점퍼선 목록입니다. 가공 전 Z 영점·고정을 확인하세요.</div>';
millPaths={};renderMill();draw();
if(P.name&&!pconflict){
try{ if(projDirty||!P.rev) await serverSave(false);
const r=await api('/api/pcb/projects/'+encodeURIComponent(P.name)+'/gcode',{files:gres.files});
$('res').insertAdjacentHTML('beforeend',`<div class="ok" style="margin-top:4px">📁 작업 폴더 pcb/${esc(P.name)}/gcode/ 에 ${r.saved.length}개 저장됨</div>`);
}catch(e){ $('res').insertAdjacentHTML('beforeend',`<div class="warn">서버 폴더 저장 실패: ${esc(e.message)}</div>`); }
} else if(!P.name) $('res').insertAdjacentHTML('beforeend','<div class="note">프로젝트 이름을 입력하면 이 파일들이 작업 폴더 pcb/&lt;이름&gt;/gcode/ 에도 저장됩니다.</div>');
}catch(e){$('res').innerHTML=`<span class="bad">${esc(e.message)}</span>`;}
finally{b.disabled=false;}
}
function dlFile(n){const a=document.createElement('a');a.href=URL.createObjectURL(new Blob([gres.files[n]],{type:'text/plain'}));a.download=n;a.click();setTimeout(()=>URL.revokeObjectURL(a.href),2000);}
function saveFile(){const a=document.createElement('a');a.href=URL.createObjectURL(new Blob([JSON.stringify({project:P,routed},null,1)],{type:'application/json'}));a.download='pcb-project.json';a.click();setTimeout(()=>URL.revokeObjectURL(a.href),2000);}
function loadFile(inp){
const f=inp.files[0];if(!f)return;const rd=new FileReader();
rd.onload=()=>{try{const d=JSON.parse(rd.result);const pr=d.project||d;if(!pr.board||!pr.parts)throw new Error('PCB 프로젝트 파일이 아닙니다.');
P={board:pr.board,parts:pr.parts,nets:pr.nets||[],fps:pr.fps||{},sch:pr.sch,sim:pr.sim,rules:{...DEF_RULES,...(pr.rules||{})},mill:{...DEF_MILL,...(pr.mill||{})}};
registerFps();routed=d.routed&&d.routed.traces?d.routed:null;gres=null;sel=null;pending=null;histReset();fitView();syncUI();changed(true);}catch(e){alert('불러오기 실패: '+e.message);}};
rd.readAsText(f);inp.value='';
}
// ───────────── 회로 시뮬레이션 ─────────────
const SRC_DEF={dc:{dc:'5'},pulse:{v1:'0',v2:'5',per:'1m',pw:'0.5m'},sin:{off:'0',amp:'1',freq:'1k'},ac:{dc:'0',mag:'1'}};
const SRC_FIELDS={dc:[['dc','전압 V']],pulse:[['v1','낮음 V'],['v2','높음 V'],['per','주기 s'],['pw','폭 s']],sin:[['off','오프셋 V'],['amp','진폭 V'],['freq','주파수 Hz']],ac:[['dc','DC V'],['mag','크기']]};
function ensureSim(){
P.sim=P.sim||{gnd:'',sources:[],analysis:{type:'op',stop:'10m',step:'',fstart:'10',fstop:'100k',ppd:'20'},probes:[]};
const names=P.nets.map(n=>n.name);
if(!names.includes(P.sim.gnd)) P.sim.gnd=names.find(n=>/^(gnd|0|vss)$/i.test(n))||names[0]||'';
P.sim.sources=P.sim.sources.filter(s=>names.includes(s.pos));
P.sim.probes=P.sim.probes.filter(n=>names.includes(n)&&n!==P.sim.gnd);
}
function simChanged(){
ensureSim();
P.sim.gnd=$('s_gnd').value||P.sim.gnd; P.sim.analysis.type=$('s_an').value;
for(const k of ['stop','step','fstart','fstop','ppd']){const el=$('sa_'+k);if(el)P.sim.analysis[k]=el.value;}
P.sim.probes=[...document.querySelectorAll('#s_probes input:checked')].map(x=>x.value);
save(); renderSim();
}
function addSrc(){ensureSim();const pos=P.nets.map(n=>n.name).find(n=>n!==P.sim.gnd&&/vcc|vdd|5v|3v3|in|vin/i.test(n))||P.nets.map(n=>n.name).find(n=>n!==P.sim.gnd)||'';if(!pos){$('s_msg').innerHTML='<span class="bad">먼저 연결(넷)을 만드세요.</span>';return;}P.sim.sources.push({type:P.sim.sources.length?'sin':'dc',pos,...(P.sim.sources.length?SRC_DEF.sin:SRC_DEF.dc)});save();renderSim();}
function rmSrc(i){P.sim.sources.splice(i,1);save();renderSim();}
function setSrc(i,k,v){const s=P.sim.sources[i];if(k==='type'){P.sim.sources[i]={type:v,pos:s.pos,...SRC_DEF[v]};save();renderSim();return;}s[k]=v;save();}
function renderSim(){
if(!P) return; ensureSim();
const names=P.nets.map(n=>n.name), opt=(sel,list)=>list.map(n=>`<option ${n===sel?'selected':''} value="${esc(n)}">${esc(n)}</option>`).join('');
$('s_gnd').innerHTML=opt(P.sim.gnd,names);
$('s_src').innerHTML=P.sim.sources.map((s,i)=>`<div class="srow">
<div><label>종류</label><select onchange="setSrc(${i},'type',this.value)">${[['dc','DC 전원'],['pulse','펄스'],['sin','사인'],['ac','AC(주파수 해석용)']].map(([v,l])=>`<option value="${v}" ${s.type===v?'selected':''}>${l}</option>`).join('')}</select></div>
<div><label>(+) 넷</label><select onchange="setSrc(${i},'pos',this.value)">${opt(s.pos,names)}</select></div>
${SRC_FIELDS[s.type].map(([k,l])=>`<div><label>${l}</label><input value="${esc(s[k]??'')}" onchange="setSrc(${i},'${k}',this.value)"></div>`).join('')}
<div class="full"><button class="btn" style="padding:2px 8px;font-size:11px" onclick="rmSrc(${i})">삭제</button> <span class="note">(−)는 접지</span></div></div>`).join('')||'<div class="note">전원이나 신호원을 추가하세요.</div>';
$('s_an').value=P.sim.analysis.type;
const a=P.sim.analysis,f=(k,l,ph)=>`<div><label>${l}</label><input id="sa_${k}" value="${esc(a[k]??'')}" placeholder="${ph||''}" onchange="simChanged()"></div>`;
$('s_anp').innerHTML=a.type==='tran'?f('stop','총 시간 (예: 10m)')+f('step','시간 간격','자동'):a.type==='ac'?f('fstart','시작 Hz')+f('fstop','끝 Hz')+f('ppd','10배당 점 수'):'';
$('s_probes').innerHTML=names.filter(n=>n!==P.sim.gnd).map(n=>`<label class="pchk"><input type="checkbox" value="${esc(n)}" ${P.sim.probes.includes(n)?'checked':''} onchange="simChanged()">${esc(n)}</label>`).join('')||'<span class="note">넷 없음</span>';
}
async function doSim(){
ensureSim(); const a=P.sim.analysis, b=$('sbtn');
if(!P.sim.probes.length&&a.type!=='op'){P.sim.probes=P.nets.map(n=>n.name).filter(n=>n!==P.sim.gnd).slice(0,4);renderSim();}
const step=a.step&&String(a.step).trim()?a.step:undefined;
b.disabled=true;$('s_msg').textContent='ngspice 실행 중…';
try{
const d=await api('/api/pcb/simulate',{project:P,sim:{gnd:P.sim.gnd,sources:P.sim.sources,probes:P.sim.probes,analysis:{type:a.type,stop:a.stop,step,fstart:a.fstart,fstop:a.fstop,ppd:a.ppd}}});
$('s_msg').innerHTML='<span class="ok">✔ 완료</span>'+(d.warnings.length?` · 경고 ${d.warnings.length}건`:'');
showSim(d,a.type);
}catch(e){$('s_msg').innerHTML=`<span class="bad">${esc(e.message)}</span>`;}
finally{b.disabled=false;}
}
const SI=[[1e9,'G'],[1e6,'M'],[1e3,'k'],[1,''],[1e-3,'m'],[1e-6,'µ'],[1e-9,'n'],[1e-12,'p']];
function fmtSI(v,unit=''){if(!isFinite(v))return '–';if(v===0)return '0'+unit;const av=Math.abs(v);for(const [m,p] of SI){if(av>=m*0.9995)return (+(v/m).toPrecision(4))+p+unit;}return v.toExponential(2)+unit;}
let simRes=null,simHover=null;
function showSim(d,type){
simRes={...d,type};
$('simpane').style.display='flex'; $('simtitle').textContent='시뮬레이션 결과 — '+({op:'동작점',tran:'시간 응답',ac:'주파수 응답'}[type]);
let h='';
if(d.warnings.length) h+=d.warnings.map(w=>`<div class="warn" style="margin-bottom:3px">⚠ ${esc(w)}</div>`).join('');
if(d.op){
h+='<b>노드 전압</b><table>'+Object.entries(d.op.nodes).map(([n,v])=>`<tr><td>${esc(n)}</td><td>${fmtSI(v,'V')}</td></tr>`).join('')+'</table>';
if(d.op.parts.length) h+='<b style="display:block;margin-top:8px">부품 전류</b><table>'+d.op.parts.map(p=>`<tr><td>${esc(p.ref)} <span style="color:var(--muted)">${p.kind}</span></td><td>${fmtSI(p.i,'A')}${p.p!==undefined?` · ${fmtSI(p.p,'W')}`:''}</td></tr>`).join('')+'</table>';
if(Object.keys(d.op.sources).length) h+='<b style="display:block;margin-top:8px">전원 전류</b><table>'+Object.entries(d.op.sources).map(([n,v])=>`<tr><td>${esc(n)}</td><td>${fmtSI(v,'A')}</td></tr>`).join('')+'</table>';
}
h+=`<details style="margin-top:8px"><summary>SPICE 넷리스트</summary><pre>${esc(d.netlist)}</pre></details>`;
$('simside').innerHTML=h;
$('simchart').style.display=d.op?'none':'block';
$('simside').style.width=d.op?'100%':'300px';
resize(); if(!d.op) requestAnimationFrame(()=>drawChart());
}
const COLORS=['#4fc3f7','#ffb74d','#81c784','#ba68c8','#e57373','#fff176','#4db6ac','#f06292','#a1887f','#90a4ae'];
function niceStep(range,n){const raw=range/n,mag=Math.pow(10,Math.floor(Math.log10(raw))),r=raw/mag;return (r<1.5?1:r<3?2:r<7?5:10)*mag;}
function drawChart(){
const d=simRes; if(!d||!d.x) return;
const cv2=$('sc'),c=cv2.getContext('2d'),r=cv2.getBoundingClientRect(),dp=window.devicePixelRatio||1;
if(!r.width) return; cv2.width=Math.round(r.width*dp);cv2.height=Math.round(r.height*dp);c.setTransform(dp,0,0,dp,0,0);
const fg=getComputedStyle(document.body).color,muted='#94a3b8',grid='rgba(148,163,184,.22)';
const ac=d.type==='ac', panels=ac?[d.traces.filter(t=>t.unit==='dB'),d.traces.filter(t=>t.unit==='°')]:[d.traces];
const W=r.width,H=r.height,L=58,R=12,T=24,B=30,gap=ac?16:0,ph=(H-T-B-gap)/panels.length;
const x0=d.x[0],x1=d.x[d.x.length-1];
const X=v=>L+(ac?(Math.log10(v)-Math.log10(x0))/(Math.log10(x1)-Math.log10(x0)):(v-x0)/(x1-x0||1))*(W-L-R);
c.font='11px sans-serif';
panels.forEach((tr,pi)=>{
const top=T+pi*(ph+gap);
let lo=Infinity,hi=-Infinity; tr.forEach(t=>t.y.forEach(v=>{if(isFinite(v)){lo=Math.min(lo,v);hi=Math.max(hi,v);}}));
if(!isFinite(lo)){lo=0;hi=1;} if(hi-lo<1e-9){lo-=0.5;hi+=0.5;} const pad=(hi-lo)*0.06;lo-=pad;hi+=pad;
const Y=v=>top+ph-(v-lo)/(hi-lo)*ph, st=niceStep(hi-lo,5);
c.strokeStyle=grid;c.fillStyle=muted;c.lineWidth=1;c.textAlign='right';
for(let v=Math.ceil(lo/st)*st;v<=hi;v+=st){c.beginPath();c.moveTo(L,Y(v));c.lineTo(W-R,Y(v));c.stroke();c.fillText(fmtSI(v),L-5,Y(v)+4);}
c.strokeStyle=muted;c.strokeRect(L,top,W-L-R,ph);
c.fillStyle=muted;c.save();c.translate(12,top+ph/2);c.rotate(-Math.PI/2);c.textAlign='center';c.fillText(tr[0]?tr[0].unit:'',0,0);c.restore();
tr.forEach(t=>{const col=COLORS[d.traces.indexOf(t)%COLORS.length];c.strokeStyle=col;c.lineWidth=1.6;c.beginPath();let on=false;t.y.forEach((v,i)=>{if(!isFinite(v)){on=false;return;}const px=X(d.x[i]),py=Y(v);on?c.lineTo(px,py):c.moveTo(px,py);on=true;});c.stroke();});
if(simHover!==null){const i=simHover;c.strokeStyle='rgba(255,255,255,.5)';c.beginPath();c.moveTo(X(d.x[i]),top);c.lineTo(X(d.x[i]),top+ph);c.stroke();}
});
c.fillStyle=muted;c.textAlign='center';
if(ac){for(let e=Math.ceil(Math.log10(x0));e<=Math.floor(Math.log10(x1));e++){const v=Math.pow(10,e);c.fillText(fmtSI(v,'Hz'),X(v),H-14);c.strokeStyle=grid;c.beginPath();c.moveTo(X(v),T);c.lineTo(X(v),H-B);c.stroke();}}
else{const st=niceStep(x1-x0,6);for(let v=Math.ceil(x0/st)*st;v<=x1;v+=st)c.fillText(fmtSI(v,'s'),X(v),H-14);}
let lx=L; d.traces.forEach((t,i)=>{c.fillStyle=COLORS[i%COLORS.length];c.fillRect(lx,8,10,3);c.fillStyle=fg;c.textAlign='left';const hv=simHover!==null?` ${fmtSI(t.y[simHover],t.unit)}`:'';const txt=t.name+hv;c.fillText(txt,lx+14,13);lx+=c.measureText(txt).width+30;});
if(simHover!==null){c.fillStyle=muted;c.textAlign='right';c.fillText((ac?'f=':'t=')+fmtSI(d.x[simHover],ac?'Hz':'s'),W-R,13);}
}
$('sc').addEventListener('mousemove',e=>{
const d=simRes;if(!d||!d.x)return;const r=$('sc').getBoundingClientRect(),L=58,R=12,fx=(e.clientX-r.left-L)/(r.width-L-R);
if(fx<0||fx>1){simHover=null;drawChart();return;}
const x0=d.x[0],x1=d.x[d.x.length-1],tv=d.type==='ac'?Math.pow(10,Math.log10(x0)+fx*(Math.log10(x1)-Math.log10(x0))):x0+fx*(x1-x0);
let lo=0,hi=d.x.length-1;while(hi-lo>1){const m=(lo+hi)>>1;if(d.x[m]<tv)lo=m;else hi=m;} simHover=(tv-d.x[lo]<d.x[hi]-tv)?lo:hi; drawChart();
});
$('sc').addEventListener('mouseleave',()=>{simHover=null;drawChart();});
new ResizeObserver(()=>drawChart()).observe($('simchart'));
// ───────────── 밀링 머신(옥토서버 OctoPrint) ─────────────
let millSt=null, millPaths={}, millProj='', millTimer=null;
const millName=n=>n.replace(/\.(nc|gcode|gco|g)$/i,'');
async function millRefresh(){
try{ millSt=await api('/api/pcb/mill/status'); }catch(e){ millSt={error:e.message}; }
renderMill();
const busy=millSt&&millSt.job&&millSt.job.state&&/print|paus/i.test(millSt.job.state);
clearTimeout(millTimer); if(busy) millTimer=setTimeout(millRefresh,3000);
}
function renderMill(){
const el=$('mill'), st=millSt||{};
if(!st.configured){
el.innerHTML=`<div>밀링 OctoPrint 의 API 키가 필요합니다. <a href="https://mill.applecherry.net/" target="_blank" style="color:var(--brand2)">OctoPrint 설정 → API</a> 의 키를 아래에 붙여 넣으세요 (서버 금고에 암호화 저장, 관리자만).</div>
<div style="display:flex;gap:4px;margin-top:6px"><input id="mkey" type="password" placeholder="API 키" autocomplete="off"><button class="btn" onclick="millSaveKey()">저장</button></div><div id="mkmsg"></div>`;
return;
}
if(st.error&&!st.reachable){ el.innerHTML=`<span class="bad">${esc(st.error)}</span> <button class="btn" onclick="millRefresh()">↻</button> <button class="btn" onclick="millResetKey()">키 다시 입력</button>`; return; }
const state=st.state||'?', job=st.job||{}, running=/print|paus/i.test(job.state||'');
let h=`<div>상태: <b class="${/operational/i.test(state)?'ok':running?'warn':'bad'}">${esc(state)}</b>${st.port?` · ${esc(st.port)}`:''} <button class="btn" style="padding:1px 7px" onclick="millRefresh()">↻</button></div>`;
if(running||job.file){ const pc=job.completion!=null?Math.round(job.completion):0; h+=`<div style="margin-top:4px">작업: ${esc(job.file||'-')} · ${esc(job.state||'')} ${running?pc+'%':''}</div>`;
if(running) h+=`<div style="display:flex;gap:4px;margin-top:4px"><button class="btn" onclick="millJob('pause')">⏸ 일시정지</button><button class="btn" onclick="millJob('resume')">▶ 재개</button><button class="btn" onclick="millJob('cancel')" style="border-color:var(--red);color:var(--red)">■ 취소</button></div>`; }
if(gres){
const names=Object.keys(gres.files).filter(n=>/\.nc$/.test(n));
const tool=n=>/copper/.test(n)?`공구: 가공 폭 ${P.mill.toolDia}mm 비트(V비트/엔드밀)`:/silk/.test(n)?`공구: 얕게 긋는 Ø${P.mill.toolDia}mm 비트(깊이 ${P.mill.silkZ}mm)${/top/.test(n)?' — 보드를 뒤집어 부품면이 위로':''}`:/drill/.test(n)?`공구: 드릴 ${gres.stats.drillSizes.join(', ')||'-'}mm — 크기마다 M0에서 멈추니 공구 교체 후 ▶ 재개`:`공구: 엔드밀 Ø${P.mill.outlineDia}mm`;
h+=names.map(n=>`<div class="net" style="margin-top:6px"><b>${esc(n)}</b>${millPaths[n]?' <span class="ok">· 업로드됨</span>':''}<div class="note">${esc(tool(n))}</div>
<div style="display:flex;gap:4px;margin-top:4px"><button class="btn" onclick="millUpload('${esc(n)}')">⬆ 업로드</button><button class="btn pri" ${/operational/i.test(state)?'':'disabled'} onclick="millStart('${esc(n)}')">▶ 시작</button></div></div>`).join('');
} else h+='<div class="note" style="margin-top:6px">G-code 를 생성하면 파일별로 올리고 시작할 수 있습니다.</div>';
h+=`<div class="note">시작하면 스핀들이 돕니다. 시작 전에 Z 영점·기판 고정·공구를 확인하세요. <a href="https://mill.applecherry.net/" target="_blank" style="color:var(--brand2)">OctoPrint 열기 ↗</a> · <a href="#" onclick="millResetKey();return false" style="color:var(--muted)">키 변경</a></div><div id="mmsg"></div>`;
el.innerHTML=h;
}
async function millSaveKey(){
const k=$('mkey').value.trim(); if(!k) return;
try{ await api('/api/pcb/mill/key',{key:k}); $('mkmsg').innerHTML='<span class="ok">저장됨</span>'; await millRefresh(); }
catch(e){ $('mkmsg').innerHTML=`<span class="bad">${esc(e.message)}</span>`; }
}
function millResetKey(){ millSt={configured:false}; renderMill(); }
function mmsg(h){ const e=$('mmsg'); if(e) e.innerHTML=h; }
async function millUpload(name,quiet){
if(!gres) return null;
if(!millProj) millProj='board_'+new Date().toISOString().slice(0,16).replace(/[-:T]/g,'');
try{ const d=await api('/api/pcb/mill/upload',{project:millProj,files:{[name]:gres.files[name]}}); millPaths[name]=d.uploaded[0]; renderMill(); if(!quiet) mmsg(`<span class="ok">✔ 업로드: ${esc(d.uploaded[0])}</span>`); return d.uploaded[0]; }
catch(e){ mmsg(`<span class="bad">${esc(e.message)}</span>`); return null; }
}
async function millStart(name){
const what=/copper/.test(name)?'격리 가공':/drill/.test(name)?'드릴':'외곽 컷';
if(!confirm(`${what}(${name})을 시작합니다.\n\n□ Z 영점을 이 공구로 맞췄습니까?\n□ 기판이 단단히 고정됐습니까?\n□ 공구가 맞게 장착됐습니까?\n\n시작하면 스핀들이 돌고 머신이 움직입니다.`)) return;
const path=millPaths[name]||await millUpload(name,true); if(!path) return;
try{ await api('/api/pcb/mill/start',{file:path,confirm:true}); mmsg('<span class="ok">▶ 작업을 시작했습니다.</span>'); millRefresh(); }
catch(e){ mmsg(`<span class="bad">${esc(e.message)}</span>`); }
}
async function millJob(cmd){
if(cmd==='cancel'&&!confirm('진행 중인 작업을 취소할까요?')) return;
try{ await api('/api/pcb/mill/job',{command:cmd}); await millRefresh(); }catch(e){ mmsg(`<span class="bad">${esc(e.message)}</span>`); }
}
// ═════════════ 회로도 ═════════════
// 좌표는 mm(시트 좌표, y 아래로). 심볼은 KiCad 원본(y 위로)을 불러와 y 를 뒤집어 그린다.
// P.sch = { pos:{ref:{x,y,rot,mir}}, wires:[{pts:[[x,y]...]}], labels:[{x,y,name}], power:[{x,y,name}] }
// 선·이름·전원 심볼이 하나라도 있으면 P.nets 는 회로도에서 자동으로 만들어진다(기판 쪽 연결 모드는 잠긴다).
const sc2=$('sc2'), sctx=sc2.getContext('2d');
let sview={s:7,ox:60,oy:60}, smode='select', ssel=null, wiring=null, sdrag=null, spanS=null, smouse=null, sfit=false;
let SYM={}, SYMREQ={}, GEN={}, sres={nets:[],junctions:[],conn:new Set(),warn:[]};
const SGRID=1.27, r2=v=>Math.round(v*100)/100, pkey=(x,y)=>Math.round(x*100)+','+Math.round(y*100);
const sSnap=v=>Math.round(v/SGRID)*SGRID;
const ncmp=(a,b)=>(Number(a)||1e9)-(Number(b)||1e9)||String(a).localeCompare(String(b));
function ensureSch(){P.sch=P.sch||{};P.sch.pos=P.sch.pos||{};for(const k of ['wires','labels','power'])P.sch[k]=P.sch[k]||[];}
function schDriven(){ensureSch();return P.sch.wires.length>0||P.sch.labels.length>0||P.sch.power.length>0;}
// ── 심볼 그림 ──
function genGfx(part){
const f=FPM[part.fp]; if(!f) return {loading:true,units:[]};
const names=part.pinNames||{}, pre=part.ref.replace(/\d+$/,'').toUpperCase();
const key=part.fp+'|'+pre+'|'+JSON.stringify(names); if(GEN[key]) return GEN[key];
const pads=f.pads.filter(p=>!p.npth&&!String(p.n).includes('~')).map(p=>p.n).sort(ncmp);
const u={unit:1,rects:[],lines:[],circles:[],arcs:[],pins:[]};
const pin=(n,x,y,a,len)=>u.pins.push({n,name:names[n]||'',type:'passive',x,y,angle:a,length:len,hide:false});
let showNames=false, showNumbers=true;
if(pads.length===2&&/^(R|C|L|D|LED|F)$/.test(pre)){
let [a,b]=pads; if((pre==='D'||pre==='LED')&&pads.includes('2')){a='2';b='1';} // 애노드(2) 왼쪽, 캐소드(1) 오른쪽
pin(a,-5.08,0,0,2.54); pin(b,5.08,0,180,2.54); showNumbers=false;
if(pre==='C'){u.lines.push({pts:[[-2.54,0],[-0.6,0]],fill:false},{pts:[[0.6,0],[2.54,0]],fill:false},{pts:[[-0.6,-2],[-0.6,2]],fill:false},{pts:[[0.6,-2],[0.6,2]],fill:false});}
else if(pre==='L'){for(let k=0;k<4;k++)u.arcs.push({s:[-2.54+k*1.27,0],m:[-2.54+k*1.27+0.635,1.0],e:[-2.54+(k+1)*1.27,0]});}
else if(pre==='D'||pre==='LED'){u.lines.push({pts:[[-2.54,0],[-1.27,0]],fill:false},{pts:[[1.27,0],[2.54,0]],fill:false},{pts:[[-1.27,1.27],[-1.27,-1.27],[1.27,0],[-1.27,1.27]],fill:true},{pts:[[1.27,1.27],[1.27,-1.27]],fill:false});
if(pre==='LED'){u.lines.push({pts:[[-0.3,2.0],[0.9,3.2]],fill:false},{pts:[[0.7,1.6],[1.9,2.8]],fill:false});}}
else u.rects.push({x0:-2.54,y0:-1.016,x1:2.54,y1:1.016,fill:false});
} else if(/^(J|P|X|H|SW|TP|BT|BAT)$/.test(pre)||/HDR|TERM|Connector|Pin/i.test(part.fp)||pads.length<=3){
const n=pads.length; pads.forEach((q,i)=>pin(q,-2.54,(n-1)*1.27-i*2.54,0,2.54));
u.rects.push({x0:0,y0:(n-1)*1.27+1.27,x1:5.08,y1:-(n-1)*1.27-1.27,fill:true}); showNames=Object.keys(names).length>0;
} else {
const n=pads.length, rows=Math.ceil(n/2), W=10.16, left=pads.slice(0,rows), right=pads.slice(rows);
left.forEach((q,i)=>pin(q,-W/2-2.54,(rows-1)*1.27-i*2.54,0,2.54));
right.forEach((q,j)=>pin(q,W/2+2.54,-(rows-1)*1.27+j*2.54,180,2.54));
u.rects.push({x0:-W/2,y0:(rows-1)*1.27+1.27,x1:W/2,y1:-(rows-1)*1.27-1.27,fill:true}); showNames=Object.keys(names).length>0;
}
return GEN[key]={units:[u],showNames,showNumbers,nameOffset:0.508,generated:true};
}
function partGfx(part){
if(part.sym){
const g=SYM[part.sym]; if(g) return g;
if(g===null) return genGfx(part);
if(!SYMREQ[part.sym]){SYMREQ[part.sym]=1;api('/api/pcb/kicad/symbol-gfx?id='+encodeURIComponent(part.sym)).then(d=>{SYM[part.sym]=d.gfx;schUpdate();}).catch(()=>{SYM[part.sym]=null;schUpdate();});}
return {loading:true,units:[]};
}
return genGfx(part);
}
function unitBBox(u){
let x0=1e9,y0=1e9,x1=-1e9,y1=-1e9; const add=(x,y)=>{x0=Math.min(x0,x);x1=Math.max(x1,x);y0=Math.min(y0,y);y1=Math.max(y1,y);};
u.rects.forEach(r=>{add(r.x0,r.y0);add(r.x1,r.y1);}); u.lines.forEach(l=>l.pts.forEach(q=>add(q[0],q[1]))); u.circles.forEach(c=>{add(c.x-c.r,c.y-c.r);add(c.x+c.r,c.y+c.r);});
u.arcs.forEach(a=>{add(a.s[0],a.s[1]);add(a.m[0],a.m[1]);add(a.e[0],a.e[1]);});
u.pins.forEach(p=>{add(p.x,p.y);add(p.x+p.length*Math.cos(p.angle*Math.PI/180),p.y+p.length*Math.sin(p.angle*Math.PI/180));});
return x0>x1?{x0:-1,y0:-1,x1:1,y1:1}:{x0,y0,x1,y1};
}
function layoutOf(g){ // 여러 유닛(LM358 등)은 위에서 아래로 쌓는다
if(g._lay) return g._lay;
const boxes=g.units.map(unitBBox), offs=[0]; let cur=boxes.length?boxes[0].y0:0;
for(let i=1;i<boxes.length;i++){const off=boxes[i].y1-(cur-5.08);offs.push(off);cur=boxes[i].y0-off;}
let x0=1e9,y0=1e9,x1=-1e9,y1=-1e9; boxes.forEach((b,i)=>{x0=Math.min(x0,b.x0);x1=Math.max(x1,b.x1);y0=Math.min(y0,b.y0-offs[i]);y1=Math.max(y1,b.y1-offs[i]);});
if(x0>x1){x0=y0=-1;x1=y1=1;}
return g._lay={offs,box:{x0,y0,x1,y1}};
}
const sPos=ref=>{ensureSch();return P.sch.pos[ref];};
function sxf(pos,lx,ly){const x=pos.mir?-lx:lx,y=-ly,[rx,ry]=rotPoint(x,y,pos.rot||0);return [pos.x+rx,pos.y+ry];}
function partPins(part){
const pos=sPos(part.ref); if(!pos) return [];
const g=partGfx(part); if(!g||g.loading) return []; const lay=layoutOf(g), out=[];
g.units.forEach((u,i)=>u.pins.forEach(p=>{const [x,y]=sxf(pos,p.x,p.y-lay.offs[i]);out.push({n:p.n,name:p.name,x:r2(x),y:r2(y)});}));
return out;
}
function partBoxS(part){
const pos=sPos(part.ref); if(!pos) return null;
const g=partGfx(part); if(!g||g.loading) return {x0:pos.x-4,y0:pos.y-4,x1:pos.x+4,y1:pos.y+4};
const b=layoutOf(g).box, c=[[b.x0,b.y0],[b.x1,b.y0],[b.x1,b.y1],[b.x0,b.y1]].map(([x,y])=>sxf(pos,x,y)), xs=c.map(q=>q[0]), ys=c.map(q=>q[1]);
return {x0:Math.min(...xs),y0:Math.min(...ys),x1:Math.max(...xs),y1:Math.max(...ys)};
}
// 새 부품 자동 배치(그리드 흐름, 회로도 탭에서 하나만 추가했으면 화면 중앙)
function ensurePlaced(){
ensureSch(); const fresh=P.parts.filter(p=>!P.sch.pos[p.ref]); if(!fresh.length) return;
const r=sc2.getBoundingClientRect(); let k=Object.keys(P.sch.pos).length;
for(const p of fresh){
if(tab==='sch'&&fresh.length===1&&r.width) P.sch.pos[p.ref]={x:sSnap((r.width/2-sview.ox)/sview.s),y:sSnap((r.height/2-sview.oy)/sview.s),rot:0,mir:false};
else {P.sch.pos[p.ref]={x:sSnap(30+(k%4)*45),y:sSnap(30+Math.floor(k/4)*40),rot:0,mir:false};k++;}
}
}
// ── 연결 분석 ──
function distSeg(px,py,a,b){const dx=b[0]-a[0],dy=b[1]-a[1],l2=dx*dx+dy*dy;let t=l2?((px-a[0])*dx+(py-a[1])*dy)/l2:0;t=Math.max(0,Math.min(1,t));return Math.hypot(px-(a[0]+t*dx),py-(a[1]+t*dy));}
function schDerive(){
ensureSch(); const S=P.sch, par=new Map();
const find=k=>{if(!par.has(k))par.set(k,k);let r=k;while(par.get(r)!==r)r=par.get(r);let c=k;while(par.get(c)!==r){const n=par.get(c);par.set(c,r);c=n;}return r;};
const uni=(a,b)=>{const ra=find(a),rb=find(b);if(ra!==rb)par.set(ra,rb);};
const pts=[], pinNode=new Map(), pinList=[], segs=[], deg=new Map(), warn=[];
for(const part of P.parts) for(const pin of partPins(part)){const k=pkey(pin.x,pin.y),id=part.ref+'-'+pin.n;find(k);pinList.push({id,k});pts.push([pin.x,pin.y]);if(pinNode.has(id))uni(pinNode.get(id),k);else pinNode.set(id,k);}
for(const w of S.wires) w.pts.forEach((q,i)=>{const k=pkey(q[0],q[1]);find(k);pts.push(q);if(i){const a=w.pts[i-1];uni(pkey(a[0],a[1]),k);segs.push([a,q]);deg.set(k,(deg.get(k)||0)+1);const ka=pkey(a[0],a[1]);deg.set(ka,(deg.get(ka)||0)+1);}});
const named=[]; for(const l of [...S.labels,...S.power]){const k=pkey(l.x,l.y);find(k);pts.push([l.x,l.y]);named.push({k,name:l.name});}
// T 접합: 어떤 점이 다른 선분의 중간에 놓이면 그 선분과 연결
const junc=new Set();
for(const p of pts) for(const sg of segs){
const ka=pkey(sg[0][0],sg[0][1]), kb=pkey(sg[1][0],sg[1][1]), kp=pkey(p[0],p[1]);
if(kp===ka||kp===kb) continue;
if(distSeg(p[0],p[1],sg[0],sg[1])<0.011){uni(kp,ka);deg.set(kp,(deg.get(kp)||0)+3);}
}
for(const [k,d] of deg) if(d>=3) junc.add(k);
for(const n of named) uni(n.k,'L:'+n.name);
const comp=new Map();
for(const p of pinList){const r=find(p.k);if(!comp.has(r))comp.set(r,{pins:new Set(),names:new Set()});comp.get(r).pins.add(p.id);}
for(const n of named){const r=find(n.k);if(!comp.has(r))comp.set(r,{pins:new Set(),names:new Set()});comp.get(r).names.add(n.name);}
const nets=[], conn=new Set(); let auto=[];
for(const c of comp.values()){
if(!c.pins.size) continue; const pinsA=[...c.pins].sort((a,b)=>ncmp(a.split('-')[0]+'-'+a.split('-')[1],b.split('-')[0]+'-'+b.split('-')[1]));
if(c.pins.size<2&&!c.names.size) continue;
pinsA.forEach(id=>conn.add(id));
const nm=[...c.names]; if(nm.length>1) warn.push(`한 넷에 이름이 여러 개입니다: ${nm.join(', ')} → ${nm[0]} 사용`);
nets.push({name:nm[0]||'',pins:pinsA});
}
const used=new Set(nets.map(n=>n.name).filter(Boolean));
nets.filter(n=>!n.name).sort((a,b)=>ncmp(a.pins[0],b.pins[0])).forEach(n=>{let i=1;while(used.has('N'+i))i++;n.name='N'+i;used.add(n.name);});
nets.sort((a,b)=>ncmp(a.pins[0],b.pins[0]));
// 같은 이름이 서로 다른 연결로 갈라진 경우는 없다(이름은 전역 연결). 핀 번호가 풋프린트에 없는 경우 경고
for(const part of P.parts){const f=FPM[part.fp];if(!f)continue;const have=new Set(f.pads.map(q=>q.n));const missing=[...new Set(partPins(part).map(q=>q.n))].filter(n=>!have.has(n));if(missing.length)warn.push(`${part.ref}: 심볼 핀 ${missing.join(',')} 이(가) 풋프린트에 없습니다`);}
return sres={nets,junctions:[...junc].map(k=>k.split(',').map(v=>Number(v)/100)),conn,warn};
}
function schCommit(){
const r=schDerive();
if(schDriven()) P.nets=r.nets.map(n=>({name:n.name,pins:n.pins}));
changed();
$('hint').innerHTML=r.warn.length?`<span class="warn">⚠ ${esc(r.warn[0])}</span>`:'';
}
function schUpdate(){ if(!P) return; ensurePlaced(); if(tab==='sch'){schDerive();drawSch();} }
function schGuard(){ ensureSch(); if(!schDriven()&&P.nets.length&&!confirm('회로도로 연결하면 지금의 연결(넷)이 회로도 기준으로 바뀝니다. 계속할까요?')) return false; return true; }
// ── 그리기 ──
const SX=x=>x*sview.s+sview.ox, SY=y=>y*sview.s+sview.oy;
function resizeSch(){const r=sc2.getBoundingClientRect(),d=window.devicePixelRatio||1;if(!r.width)return;sc2.width=Math.round(r.width*d);sc2.height=Math.round(r.height*d);sctx.setTransform(d,0,0,d,0,0);drawSch();}
new ResizeObserver(resizeSch).observe($('scv'));
const STXT=1.0; // 회로도 글자 배율
function stext(t,x,y,align,color,size){sctx.fillStyle=color;sctx.font=Math.round((size||Math.max(8,1.27*sview.s))*STXT*10)/10+'px sans-serif';sctx.textAlign=align||'left';sctx.fillText(t,x,y);}
function drawSym(part,pos,isSel){
const g=partGfx(part), c=sctx, S=sview.s; if(!g||g.loading){const b=partBoxS(part);c.strokeStyle='#888';c.setLineDash([4,3]);c.strokeRect(SX(b.x0),SY(b.y0),(b.x1-b.x0)*S,(b.y1-b.y0)*S);c.setLineDash([]);stext(part.ref+' …',SX(b.x0)+3,SY(b.y0)+12,'left','#aaa',10);return;}
const lay=layoutOf(g), col=isSel?'#fff176':'#e8c27a';
const T=(lx,ly,i)=>{const [x,y]=sxf(pos,lx,ly-lay.offs[i]);return [SX(x),SY(y)];};
c.lineWidth=Math.max(1.5,0.28*S*1.05);c.lineJoin='round';
g.units.forEach((u,i)=>{
c.strokeStyle=col;c.fillStyle='rgba(255,235,160,.13)';
for(const r of u.rects){const a=T(r.x0,r.y0,i),b=T(r.x1,r.y0,i),d=T(r.x1,r.y1,i),e=T(r.x0,r.y1,i);c.beginPath();c.moveTo(a[0],a[1]);c.lineTo(b[0],b[1]);c.lineTo(d[0],d[1]);c.lineTo(e[0],e[1]);c.closePath();if(r.fill)c.fill();c.stroke();}
for(const l of u.lines){c.beginPath();l.pts.forEach((q,k)=>{const a=T(q[0],q[1],i);k?c.lineTo(a[0],a[1]):c.moveTo(a[0],a[1]);});if(l.fill){c.closePath();c.fill();}c.stroke();}
for(const ci of u.circles){const a=T(ci.x,ci.y,i);c.beginPath();c.arc(a[0],a[1],ci.r*S,0,7);if(ci.fill)c.fill();c.stroke();}
for(const ar of u.arcs){const a=T(ar.s[0],ar.s[1],i),m=T(ar.m[0],ar.m[1],i),e=T(ar.e[0],ar.e[1],i);c.beginPath();c.moveTo(a[0],a[1]);c.quadraticCurveTo(2*m[0]-(a[0]+e[0])/2,2*m[1]-(a[1]+e[1])/2,e[0],e[1]);c.stroke();}
for(const p of u.pins){
const rad=p.angle*Math.PI/180, ex=p.x+p.length*Math.cos(rad), ey=p.y+p.length*Math.sin(rad), a=T(p.x,p.y,i), b=T(ex,ey,i);
c.strokeStyle=isSel?'#fff176':'#7ec8e3';c.beginPath();c.moveTo(a[0],a[1]);c.lineTo(b[0],b[1]);c.stroke();
if(part.dots&&part.dots.includes(String(p.n))){const l=Math.hypot(b[0]-a[0],b[1]-a[1])||1,ux=(b[0]-a[0])/l,uy=(b[1]-a[1])/l,r=Math.max(3.5,0.65*S);c.save();c.fillStyle='#ffb74d';c.beginPath();c.arc(b[0]+ux*(r+1.5),b[1]+uy*(r+1.5),r,0,7);c.fill();c.restore();}
const open=schDriven()&&!sres.conn.has(part.ref+'-'+p.n);
if(open){c.strokeStyle='#ef5350';c.lineWidth=1.5;c.beginPath();c.arc(a[0],a[1],Math.max(2.5,0.5*S),0,7);c.stroke();c.lineWidth=Math.max(1.5,0.28*S*1.05);}
if(S<4.5) continue;
const dx=b[0]-a[0], dy=b[1]-a[1], horiz=Math.abs(dx)>=Math.abs(dy), ux=Math.sign(dx)||0, uy=Math.sign(dy)||0;
if(g.showNumbers&&p.n){const mx=(a[0]+b[0])/2,my=(a[1]+b[1])/2;if(horiz)stext(p.n,mx,my-3,'center','#9bb',Math.max(7,0.9*S));else stext(p.n,mx-3,my+3,'right','#9bb',Math.max(7,0.9*S));}
const nm=(part.pinNames&&part.pinNames[p.n])||p.name;
if(g.showNames&&nm&&nm!=='~'&&!p.hide){const off=(g.nameOffset||0.508)*S+2, label=String(nm).replace(/~\{([^}]*)\}/g,'/$1');
if(horiz)stext(label,b[0]+ux*off,b[1]+3,ux>0?'left':'right','#cde',Math.max(8,1.0*S));else stext(label,b[0],b[1]+uy*(off+4)+3,'center','#cde',Math.max(8,1.0*S));}
else if(!g.showNames&&part.pinNames&&part.pinNames[p.n]&&S>=6){ // 이름 숨김 심볼에도 핀 이름이 있으면 작게 보조 표시
stext(part.pinNames[p.n],(a[0]+b[0])/2+(horiz?0:-14),(a[1]+b[1])/2+(horiz?12:3),horiz?'center':'right','#789',Math.max(7,0.8*S));}
}
});
const b=partBoxS(part);
stext(part.ref,SX(b.x0),SY(b.y0)-4,'left',isSel?'#fff176':'#ffd27f',Math.max(9,1.2*S));
if(part.value) stext(part.value,SX(b.x0),SY(b.y1)+Math.max(11,1.3*S),'left','#c8e6c9',Math.max(9,1.15*S));
}
function drawPower(pw,isSel){
const c=sctx,S=sview.s,gnd=/^(gnd|vss|0v|agnd|dgnd|pgnd)$/i.test(pw.name),col=isSel?'#fff176':'#ff8a65';
const V={d:[0,1],u:[0,-1],l:[-1,0],r:[1,0]}, dir=pw.dir||(gnd?'d':'u'), vec=V[dir]||V.d;
const base=gnd?[0,1]:[0,-1], th=Math.atan2(vec[1],vec[0])-Math.atan2(base[1],base[0]);
c.save();c.translate(SX(pw.x),SY(pw.y));c.rotate(th);c.strokeStyle=col;c.lineWidth=Math.max(1.2,0.3*S*0.7);c.beginPath();
if(gnd){c.moveTo(0,0);c.lineTo(0,2.0*S);c.moveTo(-1.4*S,2.0*S);c.lineTo(1.4*S,2.0*S);c.moveTo(-0.9*S,2.7*S);c.lineTo(0.9*S,2.7*S);c.moveTo(-0.4*S,3.4*S);c.lineTo(0.4*S,3.4*S);}
else{c.moveTo(0,0);c.lineTo(0,-2.0*S);c.moveTo(-1.3*S,-2.0*S);c.lineTo(1.3*S,-2.0*S);}
c.stroke();c.restore();
const len=(gnd?3.6:2.0)*S, ex=SX(pw.x)+vec[0]*len, ey=SY(pw.y)+vec[1]*len, fs=Math.max(9,1.15*S);
if(vec[0]===0) stext(pw.name,ex,vec[1]>0?ey+fs:ey-4,'center',col,fs); else stext(pw.name,ex+(vec[0]>0?4:-4),ey+4,vec[0]>0?'left':'right',col,fs);
}
// 연결 안 된 가로·세로 선이 선분 한가운데서 교차하면 가로선에 오메가(∩) 다리를 놓는다(표시만 — 연결 해석은 그대로: 교차점에 끝점·이름표·접합점이 있으면 연결이므로 제외).
let _hopKey='', _hopVal=new Map();
function schHops(){
const key=JSON.stringify(P.sch.wires)+'|'+P.sch.labels.length+P.sch.power.length; if(key===_hopKey) return _hopVal;
const H=[], V=[], E=0.02, M=0.35, R=1.0, out=new Map();
P.sch.wires.forEach((w,wi)=>{for(let k=1;k<w.pts.length;k++){const a=w.pts[k-1],b=w.pts[k];
if(Math.abs(a[1]-b[1])<E&&Math.abs(a[0]-b[0])>E) H.push({wi,k,y:a[1],x0:Math.min(a[0],b[0]),x1:Math.max(a[0],b[0])});
else if(Math.abs(a[0]-b[0])<E&&Math.abs(a[1]-b[1])>E) V.push({wi,k,x:a[0],y0:Math.min(a[1],b[1]),y1:Math.max(a[1],b[1])});}});
const pts=[]; P.sch.wires.forEach(w=>w.pts.forEach(q=>pts.push(q))); for(const l of [...P.sch.labels,...P.sch.power]) pts.push([l.x,l.y]); for(const p of P.parts) for(const q of partPins(p)) pts.push([q.x,q.y]);
for(const h of H){ const xs=[];
for(const v of V){ if(v.wi===h.wi&&Math.abs(v.k-h.k)<=1) continue;
if(v.x<=h.x0+M||v.x>=h.x1-M||h.y<=v.y0+M||h.y>=v.y1-M) continue; // 끝 가까이/끝점에서 만나는 건 연결(T·꺾임)
if(pts.some(q=>Math.abs(q[0]-v.x)<0.06&&Math.abs(q[1]-h.y)<0.06)) continue; xs.push(v.x); }
xs.sort((a,b)=>a-b); const keep=[]; for(const x of xs){ if(x-R<h.x0+0.1||x+R>h.x1-0.1) continue; if(keep.length&&x-keep[keep.length-1]<2*R+0.3) continue; keep.push(x); }
if(keep.length) out.set(h.wi+':'+h.k,keep); }
_hopKey=key; _hopVal=out; return out;
}
function drawSch(){
if(!P||tab!=='sch') return;
const r=sc2.getBoundingClientRect(); sctx.clearRect(0,0,r.width,r.height); ensureSch(); const S=sview.s;
sctx.fillStyle='#0f1f2e';sctx.fillRect(0,0,r.width,r.height);
if(S>=5){sctx.fillStyle='rgba(255,255,255,.12)';const x0=Math.floor(-sview.ox/S/SGRID/2)*SGRID*2,y0=Math.floor(-sview.oy/S/SGRID/2)*SGRID*2;for(let x=x0;x<(r.width-sview.ox)/S;x+=SGRID*2)for(let y=y0;y<(r.height-sview.oy)/S;y+=SGRID*2)sctx.fillRect(SX(x)-.5,SY(y)-.5,1.2,1.2);}
// 배선
sctx.lineCap='round';sctx.lineJoin='round';
const hops=schHops(), HR=1.0;
P.sch.wires.forEach((w,i)=>{const isSel=ssel&&ssel.kind==='wire'&&ssel.i===i;sctx.strokeStyle=isSel?'#fff176':'#6fcf6f';sctx.lineWidth=Math.max(1.4,0.3*S);sctx.beginPath();
w.pts.forEach((q,k)=>{ if(!k){sctx.moveTo(SX(q[0]),SY(q[1]));return;}
const a=w.pts[k-1], hs=hops.get(i+':'+k);
if(hs&&hs.length){ const dir=q[0]>=a[0]?1:-1, xs=hs.slice().sort((m,n)=>dir*(m-n)); // 연결 안 된 교차: 가로선이 세로선을 오메가(∩)로 넘어간다
for(const hx of xs){ sctx.lineTo(SX(hx-dir*HR),SY(a[1])); sctx.arc(SX(hx),SY(a[1]),HR*S,dir>0?Math.PI:0,dir>0?0:Math.PI,dir<0); } }
sctx.lineTo(SX(q[0]),SY(q[1])); });
sctx.stroke();});
sctx.fillStyle='#6fcf6f';for(const j of sres.junctions){sctx.beginPath();sctx.arc(SX(j[0]),SY(j[1]),Math.max(2.5,0.5*S),0,7);sctx.fill();}
for(const part of P.parts){const pos=sPos(part.ref);if(pos)drawSym(part,pos,ssel&&ssel.kind==='part'&&ssel.ref===part.ref);}
P.sch.power.forEach((pw,i)=>drawPower(pw,ssel&&ssel.kind==='power'&&ssel.i===i));
P.sch.labels.forEach((l,i)=>{
const isSel=ssel&&ssel.kind==='label'&&ssel.i===i,x=SX(l.x),y=SY(l.y),col=isSel?'#fff176':'#ffb74d',fs=Math.max(9,1.15*S);
sctx.font=fs+'px sans-serif';const tw=sctx.measureText(l.name).width,d=l.dir||'r';
sctx.strokeStyle=col;sctx.lineWidth=1.3;sctx.beginPath();
if(d==='r'){sctx.moveTo(x,y);sctx.lineTo(x+0.8*S,y-0.9*S);sctx.lineTo(x+0.8*S+tw+8,y-0.9*S);sctx.stroke();stext(l.name,x+0.9*S+2,y-0.9*S-2,'left',col,fs);}
else if(d==='l'){sctx.moveTo(x,y);sctx.lineTo(x-0.8*S,y-0.9*S);sctx.lineTo(x-0.8*S-tw-8,y-0.9*S);sctx.stroke();stext(l.name,x-0.9*S-2,y-0.9*S-2,'right',col,fs);}
else if(d==='u'){sctx.moveTo(x,y);sctx.lineTo(x,y-1.0*S);sctx.moveTo(x-tw/2-4,y-1.0*S);sctx.lineTo(x+tw/2+4,y-1.0*S);sctx.stroke();stext(l.name,x,y-1.0*S-3,'center',col,fs);}
else{sctx.moveTo(x,y);sctx.lineTo(x,y+1.0*S);sctx.moveTo(x-tw/2-4,y+1.0*S);sctx.lineTo(x+tw/2+4,y+1.0*S);sctx.stroke();stext(l.name,x,y+1.0*S+fs,'center',col,fs);}
});
// 배선 중 미리보기
if(wiring&&smouse){const last=wiring[wiring.length-1],p=smouse;sctx.strokeStyle='#fff176';sctx.setLineDash([5,4]);sctx.lineWidth=1.5;sctx.beginPath();sctx.moveTo(SX(wiring[0][0]),SY(wiring[0][1]));wiring.forEach(q=>sctx.lineTo(SX(q[0]),SY(q[1])));if(p[0]!==last[0]&&p[1]!==last[1])sctx.lineTo(SX(p[0]),SY(last[1]));sctx.lineTo(SX(p[0]),SY(p[1]));sctx.stroke();sctx.setLineDash([]);}
if(smouse&&(smode==='wire'||smode==='label'||smode==='power')){sctx.strokeStyle='#fff';sctx.lineWidth=1;sctx.strokeRect(SX(smouse[0])-4,SY(smouse[1])-4,8,8);}
$('sinfo').textContent=ssel?(ssel.kind==='part'?ssel.ref:ssel.kind==='wire'?'배선':ssel.kind==='label'?'이름 '+P.sch.labels[ssel.i].name:'전원 '+P.sch.power[ssel.i].name):(schDriven()?`넷 ${sres.nets.length}개`:'');
}
function schFit(){
if(!P) return; ensureSch(); ensurePlaced(); const r=sc2.getBoundingClientRect(); if(!r.width) return;
let x0=1e9,y0=1e9,x1=-1e9,y1=-1e9; const add=b=>{x0=Math.min(x0,b.x0);y0=Math.min(y0,b.y0);x1=Math.max(x1,b.x1);y1=Math.max(y1,b.y1);};
P.parts.forEach(p=>{const b=partBoxS(p);if(b)add(b);}); P.sch.wires.forEach(w=>w.pts.forEach(q=>add({x0:q[0],y0:q[1],x1:q[0],y1:q[1]})));
if(x0>x1){x0=0;y0=0;x1=100;y1=70;} const m=16, w=x1-x0+4, h=y1-y0+6;
sview.s=Math.max(2.5,Math.min(14,Math.min((r.width-2*m)/w,(r.height-2*m)/h))); sview.ox=(r.width-w*sview.s)/2-(x0-2)*sview.s; sview.oy=(r.height-h*sview.s)/2-(y0-4)*sview.s; drawSch();
}
// ── 입력 ──
function sWorld(e){const r=sc2.getBoundingClientRect();return [(e.clientX-r.left-sview.ox)/sview.s,(e.clientY-r.top-sview.oy)/sview.s];}
function sHitPin(mx,my,tol){let best=null,bd=tol||1.6;for(const part of P.parts)for(const pin of partPins(part)){const d=Math.hypot(pin.x-mx,pin.y-my);if(d<bd){bd=d;best={ref:part.ref,...pin};}}return best;}
function sHitPart(mx,my){for(let i=P.parts.length-1;i>=0;i--){const b=partBoxS(P.parts[i]);if(b&&mx>=b.x0&&mx<=b.x1&&my>=b.y0&&my<=b.y1)return P.parts[i];}return null;}
function sHitWire(mx,my){for(let i=P.sch.wires.length-1;i>=0;i--){const w=P.sch.wires[i];for(let k=1;k<w.pts.length;k++)if(distSeg(mx,my,w.pts[k-1],w.pts[k])<0.9)return i;}return -1;}
function sHitNamed(mx,my){for(let i=P.sch.power.length-1;i>=0;i--){const p=P.sch.power[i];if(Math.abs(mx-p.x)<2&&my>p.y-3&&my<p.y+4)return {kind:'power',i};}for(let i=P.sch.labels.length-1;i>=0;i--){const l=P.sch.labels[i];if(mx>=l.x-0.5&&mx<=l.x+8&&my>=l.y-2.5&&my<=l.y+0.8)return {kind:'label',i};}return null;}
function sSnapPt(mx,my){
const pin=sHitPin(mx,my,1.6); if(pin) return [pin.x,pin.y];
for(const w of P.sch.wires) for(const q of w.pts) if(Math.hypot(q[0]-mx,q[1]-my)<1.0) return [q[0],q[1]];
return [r2(sSnap(mx)),r2(sSnap(my))];
}
function touchesNode(p){
if(sHitPin(p[0],p[1],0.05)) return true;
for(const w of P.sch.wires){for(let k=0;k<w.pts.length;k++){if(Math.hypot(w.pts[k][0]-p[0],w.pts[k][1]-p[1])<0.02)return true;if(k&&distSeg(p[0],p[1],w.pts[k-1],w.pts[k])<0.02)return true;}}
return [...P.sch.labels,...P.sch.power].some(l=>Math.hypot(l.x-p[0],l.y-p[1])<0.02);
}
// 부품 몸체(핀 제외) 경계 — 선이 부품을 가로지르지 않게 꺾는 방향을 고르는 데 쓴다
function bodyBoxS(part){
const pos=sPos(part.ref); if(!pos) return null; const g=partGfx(part); if(!g||g.loading) return null; const lay=layoutOf(g);
let x0=1e9,y0=1e9,x1=-1e9,y1=-1e9; const add=(x,y,i)=>{const [a,b]=sxf(pos,x,y-lay.offs[i]);x0=Math.min(x0,a);x1=Math.max(x1,a);y0=Math.min(y0,b);y1=Math.max(y1,b);};
g.units.forEach((u,i)=>{u.rects.forEach(r=>{add(r.x0,r.y0,i);add(r.x1,r.y1,i);});u.lines.forEach(l=>l.pts.forEach(q=>add(q[0],q[1],i)));u.circles.forEach(c=>{add(c.x-c.r,c.y-c.r,i);add(c.x+c.r,c.y+c.r,i);});u.arcs.forEach(a=>{add(a.s[0],a.s[1],i);add(a.m[0],a.m[1],i);add(a.e[0],a.e[1],i);});});
return x0>x1?null:{x0:x0+0.3,y0:y0+0.3,x1:x1-0.3,y1:y1-0.3};
}
function legHits(a,b,boxes){let n=0;const lx0=Math.min(a[0],b[0]),lx1=Math.max(a[0],b[0]),ly0=Math.min(a[1],b[1]),ly1=Math.max(a[1],b[1]);for(const r of boxes)if(lx1>r.x0&&lx0<r.x1&&ly1>r.y0&&ly0<r.y1)n++;return n;}
function ortho(pts){
const boxes=P.parts.map(bodyBoxS).filter(Boolean), out=[pts[0]];
for(let i=1;i<pts.length;i++){
const a=out[out.length-1],b=pts[i];
if(a[0]!==b[0]&&a[1]!==b[1]){
const h=[b[0],a[1]], v=[a[0],b[1]];
const sh=legHits(a,h,boxes)+legHits(h,b,boxes), sv=legHits(a,v,boxes)+legHits(v,b,boxes);
out.push(sv<sh?v:h);
}
out.push(b);
}
return out;
}
function dedupe(pts){const out=[];for(const q of pts){const l=out[out.length-1];if(!l||l[0]!==q[0]||l[1]!==q[1])out.push(q);}return out;}
function finishWire(){
if(wiring&&wiring.length>=2){ if(schGuard()){P.sch.wires.push({pts:dedupe(wiring)});schCommit();} }
wiring=null; drawSch();
}
sc2.addEventListener('contextmenu',e=>{e.preventDefault();if(wiring)finishWire();});
sc2.addEventListener('dblclick',e=>{if(smode==='wire'&&wiring)finishWire();});
sc2.addEventListener('pointerdown',e=>{
sc2.setPointerCapture(e.pointerId); const [mx,my]=sWorld(e), r=sc2.getBoundingClientRect();
if(e.button===1||e.button===2||e.shiftKey||e.altKey){spanS={x:e.clientX,y:e.clientY,ox:sview.ox,oy:sview.oy};return;}
if(smode==='wire'){
const p=sSnapPt(mx,my);
if(!wiring){wiring=[p];}
else{const last=wiring[wiring.length-1]; if(p[0]===last[0]&&p[1]===last[1])return;
const seg=ortho([last,p]); wiring.push(...seg.slice(1)); if(touchesNode(p)){finishWire();return;} }
smouse=p;drawSch();return;
}
if(smode==='label'){
const p=sSnapPt(mx,my), inp=$('slabel'); inp.style.left=Math.min(r.width-130,e.clientX-r.left+8)+'px'; inp.style.top=(e.clientY-r.top+8)+'px'; inp.style.display='block'; inp.value=''; inp.dataset.x=p[0]; inp.dataset.y=p[1]; setTimeout(()=>inp.focus(),0); return;
}
if(smode==='power'){
const p=sSnapPt(mx,my); if(!schGuard())return; P.sch.power.push({x:p[0],y:p[1],name:$('spow').value}); schCommit(); return;
}
// 선택·이동
const nm=sHitNamed(mx,my), part=sHitPart(mx,my), wi=sHitWire(mx,my);
if(nm){ssel=nm;sdrag={kind:nm.kind,i:nm.i,dx:mx-(nm.kind==='label'?P.sch.labels[nm.i].x:P.sch.power[nm.i].x),dy:my-(nm.kind==='label'?P.sch.labels[nm.i].y:P.sch.power[nm.i].y),moved:false};}
else if(part){ssel={kind:'part',ref:part.ref};const pos=sPos(part.ref);
const moves=[];const pk=new Set(partPins(part).map(q=>pkey(q.x,q.y)));P.sch.wires.forEach((w,wi2)=>w.pts.forEach((q,pi)=>{if(pk.has(pkey(q[0],q[1])))moves.push({wi:wi2,pi,x:q[0],y:q[1]});}));
sdrag={kind:'part',ref:part.ref,dx:mx-pos.x,dy:my-pos.y,x0:pos.x,y0:pos.y,moves,moved:false};}
else if(wi>=0){ssel={kind:'wire',i:wi};}
else{ssel=null;spanS={x:e.clientX,y:e.clientY,ox:sview.ox,oy:sview.oy};}
drawSch();
});
sc2.addEventListener('pointermove',e=>{
const [mx,my]=sWorld(e);
if(spanS){sview.ox=spanS.ox+e.clientX-spanS.x;sview.oy=spanS.oy+e.clientY-spanS.y;drawSch();return;}
if(smode==='wire'||smode==='label'||smode==='power'){smouse=sSnapPt(mx,my);drawSch();}
if(!sdrag) return;
if(sdrag.kind==='part'){const pos=sPos(sdrag.ref),nx=sSnap(mx-sdrag.dx),ny=sSnap(my-sdrag.dy),ddx=r2(nx-sdrag.x0),ddy=r2(ny-sdrag.y0);if(nx!==pos.x||ny!==pos.y){pos.x=r2(nx);pos.y=r2(ny);sdrag.moved=true;for(const m of sdrag.moves)P.sch.wires[m.wi].pts[m.pi]=[r2(m.x+ddx),r2(m.y+ddy)];drawSch();}}
else{const o=sdrag.kind==='label'?P.sch.labels[sdrag.i]:P.sch.power[sdrag.i];const nx=r2(sSnap(mx-sdrag.dx)),ny=r2(sSnap(my-sdrag.dy));if(nx!==o.x||ny!==o.y){o.x=nx;o.y=ny;sdrag.moved=true;drawSch();}}
});
sc2.addEventListener('pointerup',()=>{
if(sdrag&&sdrag.moved){ if(sdrag.kind==='part'){for(const w of P.sch.wires)w.pts=dedupe(ortho(w.pts));} schCommit(); }
sdrag=null; spanS=null;
});
sc2.addEventListener('wheel',e=>{e.preventDefault();const r=sc2.getBoundingClientRect(),qx=e.clientX-r.left,qy=e.clientY-r.top,f=e.deltaY<0?1.15:1/1.15,ns=Math.min(30,Math.max(2,sview.s*f));sview.ox=qx-(qx-sview.ox)*(ns/sview.s);sview.oy=qy-(qy-sview.oy)*(ns/sview.s);sview.s=ns;drawSch();},{passive:false});
$('slabel').addEventListener('keydown',e=>{
if(e.key==='Escape'){$('slabel').style.display='none';return;}
if(e.key!=='Enter') return; const inp=$('slabel'), name=inp.value.trim().replace(/[^A-Za-z0-9_+\-\/]/g,'_'); inp.style.display='none'; if(!name) return;
if(!schGuard()) return; P.sch.labels.push({x:Number(inp.dataset.x),y:Number(inp.dataset.y),name}); schCommit();
});
function schKey(e){
const k=e.key.toLowerCase();
if(k==='escape'){if(wiring){wiring=null;drawSch();}else{ssel=null;setSMode('select');}return;}
if(k==='enter'&&wiring){finishWire();return;}
if(k==='w')setSMode('wire');else if(k==='l')setSMode('label');else if(k==='p')setSMode('power');else if(k==='v')setSMode('select');
else if(k==='r')schRotate();else if(k==='m')schMirror();else if(k==='delete'||k==='backspace')schDelete();
}
function setSMode(m){smode=m;wiring=null;for(const x of ['select','wire','label','power'])$('s-'+x).classList.toggle('on',x===m);sc2.style.cursor=m==='select'?'default':'crosshair';$('slabel').style.display='none';$('hint').textContent={select:'부품을 끌어 배치 · R 회전 · M 반전 · Del 삭제',wire:'핀이나 선 끝을 클릭해 시작 → 클릭으로 꺾기 → 핀/선에 닿으면 끝(더블클릭·Enter·우클릭으로 끝내기, Esc 취소)',label:'넷 이름을 붙일 지점을 클릭 (같은 이름은 서로 연결됩니다)',power:'GND·전원 기호를 놓을 지점을 클릭 (같은 이름은 서로 연결됩니다)'}[m]||'';drawSch();}
function schRotate(){if(!ssel||ssel.kind!=='part')return;const pos=sPos(ssel.ref);pos.rot=((pos.rot||0)+90)%360;const wasMoves=[];for(const w of P.sch.wires)w.pts=dedupe(ortho(w.pts));schCommit();}
function schMirror(){if(!ssel||ssel.kind!=='part')return;const pos=sPos(ssel.ref);pos.mir=!pos.mir;schCommit();}
function schDelete(){
if(!ssel) return;
if(ssel.kind==='wire')P.sch.wires.splice(ssel.i,1); else if(ssel.kind==='label')P.sch.labels.splice(ssel.i,1); else if(ssel.kind==='power')P.sch.power.splice(ssel.i,1);
else if(ssel.kind==='part'){const ref=ssel.ref;if(!confirm(`${ref} 부품을 삭제할까요? (기판에서도 사라집니다)`))return;P.parts=P.parts.filter(p=>p.ref!==ref);delete P.sch.pos[ref];sel=null;P.nets.forEach(n=>n.pins=n.pins.filter(id=>!id.startsWith(ref+'-')));}
ssel=null; if(schDriven()) schCommit(); else {schDerive();changed();}
}
// ── 회로도 자동 배선기: 1.27mm 격자 A* (부품 몸체 회피, 꺾임 최소화, 다른 넷과는 직각 교차만 허용) ──
const RG=1.27, onGrid=v=>Math.abs(v/RG-Math.round(v/RG))<0.02;
function makeRouter(){
const key=(x,y)=>x+','+y, blocked=new Set(), occ=new Map();
let bx0=1e9,by0=1e9,bx1=-1e9,by1=-1e9;
// 장애물: 부품 전체 상자가 아니라 유닛별 몸체 그림 + 핀 선만 막는다(쌓인 유닛 사이 빈틈의 핀도 나갈 수 있게)
const blockRect=(x0,y0,x1,y1,m)=>{for(let ix=Math.ceil((x0-m)/RG);ix<=Math.floor((x1+m)/RG);ix++)for(let iy=Math.ceil((y0-m)/RG);iy<=Math.floor((y1+m)/RG);iy++)blocked.add(key(ix,iy));};
for(const part of P.parts){
const b=partBoxS(part); if(!b) continue;
bx0=Math.min(bx0,b.x0);by0=Math.min(by0,b.y0);bx1=Math.max(bx1,b.x1);by1=Math.max(by1,b.y1);
const pos=sPos(part.ref), g=partGfx(part); if(!g||g.loading||!pos){blockRect(b.x0,b.y0,b.x1,b.y1,0.8);continue;}
const lay=layoutOf(g);
g.units.forEach((u,i)=>{
let x0=1e9,y0=1e9,x1=-1e9,y1=-1e9; const add=(lx,ly)=>{const [a,c]=sxf(pos,lx,ly-lay.offs[i]);x0=Math.min(x0,a);x1=Math.max(x1,a);y0=Math.min(y0,c);y1=Math.max(y1,c);};
u.rects.forEach(r=>{add(r.x0,r.y0);add(r.x1,r.y1);});u.lines.forEach(l=>l.pts.forEach(q=>add(q[0],q[1])));u.circles.forEach(c=>{add(c.x-c.r,c.y-c.r);add(c.x+c.r,c.y+c.r);});u.arcs.forEach(a=>{add(a.s[0],a.s[1]);add(a.m[0],a.m[1]);add(a.e[0],a.e[1]);});
if(x0<=x1) blockRect(x0,y0,x1,y1,0.8);
for(const pn of u.pins){const a=pn.angle*Math.PI/180,[ax,ay]=sxf(pos,pn.x,pn.y-lay.offs[i]),[ex,ey]=sxf(pos,pn.x+pn.length*Math.cos(a),pn.y+pn.length*Math.sin(a)-lay.offs[i]);
const n=Math.max(1,Math.ceil(Math.hypot(ex-ax,ey-ay)/0.4)); for(let t=0;t<=n;t++)blockRect(ax+(ex-ax)*t/n,ay+(ey-ay)*t/n,ax+(ex-ax)*t/n,ay+(ey-ay)*t/n,0.4);}
});
}
const B={x0:Math.floor(bx0/RG)-16,y0:Math.floor(by0/RG)-16,x1:Math.ceil(bx1/RG)+16,y1:Math.ceil(by1/RG)+16};
const mark=(pts,net)=>{for(let i=1;i<pts.length;i++){const a=pts[i-1],b=pts[i],ax=Math.round(a[0]/RG),ay=Math.round(a[1]/RG),bx=Math.round(b[0]/RG),by=Math.round(b[1]/RG);
const horiz=ay===by, n=Math.max(Math.abs(bx-ax),Math.abs(by-ay)), sx=Math.sign(bx-ax), sy=Math.sign(by-ay);
for(let t=0;t<=n;t++){const k=key(ax+sx*t,ay+sy*t),end=t===0||t===n,o=occ.get(k);occ.set(k,{net,o:end||(o&&o.net===net&&o.o!==(horiz?'h':'v'))?'x':(horiz?'h':'v')});}}};
for(const w of P.sch.wires) mark(w.pts,'#ext');
for(const l of [...P.sch.labels,...P.sch.power]) occ.set(key(Math.round(l.x/RG),Math.round(l.y/RG)),{net:'#ext',o:'x'});
const DX=[1,0,-1,0], DY=[0,1,0,-1];
function route(a,b,net,rail){
const sx=Math.round(a[0]/RG),sy=Math.round(a[1]/RG),tx=b?Math.round(b[0]/RG):0,ty=b?Math.round(b[1]/RG):0;
const atGoal=(x,y)=>rail?(y===rail.iy&&x>=rail.ix0&&x<=rail.ix1):(x===tx&&y===ty), hOf=(x,y)=>rail?Math.abs(y-rail.iy):Math.abs(x-tx)+Math.abs(y-ty);
if(atGoal(sx,sy)) return [[r2(sx*RG),r2(sy*RG)]];
const heap=[], push=(f,v)=>{heap.push([f,v]);let i=heap.length-1;while(i>0){const p=(i-1)>>1;if(heap[p][0]<=heap[i][0])break;[heap[p],heap[i]]=[heap[i],heap[p]];i=p;}};
const pop=()=>{const top=heap[0],last=heap.pop();if(heap.length){heap[0]=last;let i=0;for(;;){let l=2*i+1,r=l+1,m=i;if(l<heap.length&&heap[l][0]<heap[m][0])m=l;if(r<heap.length&&heap[r][0]<heap[m][0])m=r;if(m===i)break;[heap[m],heap[i]]=[heap[i],heap[m]];i=m;}}return top;};
const gs=new Map(), from=new Map(), sk=(x,y,d)=>x+','+y+','+d;
for(let d=0;d<4;d++){gs.set(sk(sx,sy,d),0);push(hOf(sx,sy),[sx,sy,d]);}
let guard=0;
while(heap.length&&guard++<250000){
const [,[x,y,d]]=pop(), g=gs.get(sk(x,y,d));
if(atGoal(x,y)){const pts=[];let k=sk(x,y,d);while(k){const q=k.split(',').map(Number);pts.push([r2(q[0]*RG),r2(q[1]*RG)]);k=from.get(k);}pts.reverse();
const out=[pts[0]];for(let i=1;i<pts.length-1;i++){const a2=pts[i-1],b2=pts[i],c2=pts[i+1];if((b2[0]-a2[0])*(c2[1]-b2[1])-(b2[1]-a2[1])*(c2[0]-b2[0])!==0)out.push(b2);}out.push(pts[pts.length-1]);return out;}
const here=occ.get(key(x,y)), cross=here&&here.net!==net;
for(let nd=0;nd<4;nd++){
if((nd+2)%4===d) continue; if(cross&&nd!==d) continue;
const nx=x+DX[nd],ny=y+DY[nd]; if(nx<B.x0||nx>B.x1||ny<B.y0||ny>B.y1) continue;
const nk=key(nx,ny), isGoal=atGoal(nx,ny); if(!isGoal&&blocked.has(nk)) continue;
let c=1+(nd!==d?4:0); const oc=occ.get(nk);
if(oc&&oc.net!==net){ if(oc.o==='x') continue; const mv=nd%2===0?'h':'v'; if(oc.o===mv) continue; c+=10; }
const ng=g+c, ks=sk(nx,ny,nd); if(gs.has(ks)&&gs.get(ks)<=ng) continue; gs.set(ks,ng); from.set(ks,sk(x,y,d)); push(ng+hOf(nx,ny),[nx,ny,nd]);
}
}
return null;
}
return {route,mark};
}
// 기판/예제의 연결(넷)을 회로도에 자동으로 그린다.
// · GND·전원(VIN/VOUT/VCC…) 넷 → 핀마다 짧은 선 + 전원 기호
// · 그 밖의 넷 → 핀들을 최소 신장 트리로 이은 직각 배선(부품 몸체를 피해 꺾음) + 넷 이름표 1개
// · 배선이 다른 넷을 잘못 건드려 연결이 달라지면 그 넷만 짧은 선 + 이름표 방식으로 되돌린다
function schFromNetsOnce(stubMax){
const expect=window.schExpect||P.nets.map(n=>({name:n.name,pins:[...n.pins]}));
window.schFails=[]; ensureSch(); ensurePlaced(); schDerive(); const S=P.sch, pinGeo={}; let nWire=0, nStub=0, nFall=0;
for(const part of P.parts){
const pos=sPos(part.ref), g=partGfx(part); if(!pos||!g||g.loading) continue; const lay=layoutOf(g);
g.units.forEach((u,i)=>u.pins.forEach(p=>{
const id=part.ref+'-'+p.n; if(pinGeo[id]) return; const a=(p.angle+180)*Math.PI/180;
const [x,y]=sxf(pos,p.x,p.y-lay.offs[i]), [x2,y2]=sxf(pos,p.x+Math.cos(a),p.y+Math.sin(a)-lay.offs[i]);
pinGeo[id]={id,x:r2(x),y:r2(y),dx:Math.round(x2-x),dy:Math.round(y2-y)};
}));
}
const done=new Set(sres.conn), dirOf=g=>g.dx<0?'l':g.dx>0?'r':g.dy<0?'u':'d';
const isGnd=n=>/^(gnd|vss|0v|agnd|dgnd)$/i.test(n), isSup=n=>/^(vin|vout|vcc|vdd|[+-]\d)/i.test(n);
// 스터브는 이미 그려진 다른 선·핀·이름표에 닿지 않는 가장 긴 길이를 쓴다(세로로 쌓인 부품의 스터브가 겹쳐 넷이 합쳐지던 문제)
const segDist=(a,b,c,d)=>{const ccw=(p,q,r)=>(r[1]-p[1])*(q[0]-p[0])-(q[1]-p[1])*(r[0]-p[0]);if(ccw(a,c,d)*ccw(b,c,d)<0&&ccw(a,b,c)*ccw(a,b,d)<0)return 0;return Math.min(distSeg(a[0],a[1],c,d),distSeg(b[0],b[1],c,d),distSeg(c[0],c[1],a,b),distSeg(d[0],d[1],a,b));};
const stubOk=(id,g,e)=>{const a=[g.x,g.y];
for(const w of S.wires) for(let k=1;k<w.pts.length;k++){const c=w.pts[k-1],d=w.pts[k]; const own=(Math.abs(c[0]-g.x)<.02&&Math.abs(c[1]-g.y)<.02)||(Math.abs(d[0]-g.x)<.02&&Math.abs(d[1]-g.y)<.02); if(own) continue; if(segDist(a,e,c,d)<0.7) return false;}
for(const l of [...S.labels,...S.power]) if(distSeg(l.x,l.y,a,e)<0.7) return false;
for(const q of Object.values(pinGeo)) if(q.id!==id&&distSeg(q.x,q.y,a,e)<0.7) return false;
return true;};
const stubEnd=(id,g)=>{for(const Ls of [5.08,3.81,2.54,1.27]){if(Ls>stubMax)continue;const e=[r2(g.x+g.dx*Ls),r2(g.y+g.dy*Ls)];if(stubOk(id,g,e))return e;}return [r2(g.x+g.dx*1.27),r2(g.y+g.dy*1.27)];};
const stubs=(net,ids)=>{ for(const id of ids){const g=pinGeo[id]; if(!g) continue; const e=stubEnd(id,g);
S.wires.push({pts:[[g.x,g.y],e]}); (isGnd(net.name)||isSup(net.name)?S.power:S.labels).push({x:e[0],y:e[1],name:net.name,dir:dirOf(g)}); nStub++; if(typeof router!=='undefined') router.mark([[g.x,g.y],e],net.name); } };
const router=makeRouter();
// 전원 레일: 핀이 3개 이상인 전원 넷(VIN/VOUT/VCC…)은 시트 맨 위에 가로 모선 하나를 두고 핀들을 거기에 잇는다(기호는 모선 왼쪽 끝 한 곳)
let railIdx=0; const railNets=P.nets.filter(n=>isSup(n.name)&&!isGnd(n.name)&&n.pins.filter(id=>pinGeo[id]&&!done.has(id)).length>=3);
let topY=1e9; for(const part of P.parts){const b=partBoxS(part); if(b) topY=Math.min(topY,b.y0);}
// 모든 핀의 시작 선(스터브) 자리를 먼저 예약해, 먼저 그린 다른 넷의 선이 그 자리를 지나가지 못하게 한다
for(const net of P.nets){
const todo=net.pins.filter(id=>pinGeo[id]&&!done.has(id)), long=isGnd(net.name)||(isSup(net.name)&&!railNets.includes(net))||todo.length<2, Ls=long?5.08:2.54;
for(const id of todo){const g=pinGeo[id]; router.mark([[g.x,g.y],[r2(g.x+g.dx*Ls),r2(g.y+g.dy*Ls)]],net.name);}
}
const nets=[...P.nets].filter(n=>!railNets.includes(n)).sort((a,b)=>a.pins.length-b.pins.length);
for(const net of railNets){
const ids=net.pins.filter(id=>pinGeo[id]&&!done.has(id)), L=2.54, railY=r2(Math.round((topY-5.08-railIdx*7.62)/RG)*RG), riy=Math.round(railY/RG);
const xs=ids.map(id=>pinGeo[id].x+pinGeo[id].dx*L), ix0=Math.floor((Math.min(...xs)-2.54)/RG), ix1=Math.ceil((Math.max(...xs)+2.54)/RG);
const mark={w:S.wires.length,l:S.labels.length,p:S.power.length}, rails=[]; let okAll=true, minX=1e9, maxX=-1e9;
for(const id of ids){
const g=pinGeo[id], A2=[r2(g.x+g.dx*L),r2(g.y+g.dy*L)];
const mid=(onGrid(A2[0])&&onGrid(A2[1]))?router.route(A2,null,net.name,{iy:riy,ix0,ix1}):null;
if(!mid){okAll=false;window.schRailWhy='no-route '+id;break;}
const pts=dedupe([[g.x,g.y],...mid]); rails.push(pts); S.wires.push({pts}); router.mark(pts,net.name);
const e=pts[pts.length-1]; minX=Math.min(minX,e[0]); maxX=Math.max(maxX,e[0]);
}
if(okAll){
const x0=r2(minX-2.54); S.wires.push({pts:[[x0,railY],[r2(maxX),railY]]}); router.mark([[x0,railY],[r2(maxX),railY]],net.name);
S.power.push({x:x0,y:railY,name:net.name,dir:'u'});
const r=schDerive(), hit=r.nets.find(n=>n.pins.includes(ids[0]));
if(hit&&hit.pins.length===ids.length&&ids.every(id=>hit.pins.includes(id))){ nWire+=rails.length+1; railIdx++; continue; }
window.schRailWhy='verify: got '+(hit?hit.pins.join(','):'none');
}
(window.schFails=window.schFails||[]).push({net:net.name,rail:true});
S.wires.length=mark.w; S.labels.length=mark.l; S.power.length=mark.p; nFall++; stubs(net,ids);
}
for(const net of nets){
const ids=net.pins.filter(id=>pinGeo[id]&&!done.has(id)); if(!ids.length) continue;
if(isGnd(net.name)||isSup(net.name)||ids.length<2){ stubs(net,ids); continue; }
// 최소 신장 트리(스터브 끝 사이 맨해튼 거리)
const L=2.54, end=id=>{const g=pinGeo[id];return [g.x+g.dx*L,g.y+g.dy*L];}, used=[ids[0]], rest=ids.slice(1), edges=[];
while(rest.length){let bi=null,bj=null,bd=1e9;for(const i of used)for(const j of rest){const a=end(i),b=end(j),d=Math.abs(a[0]-b[0])+Math.abs(a[1]-b[1]);if(d<bd){bd=d;bi=i;bj=j;}}edges.push([bi,bj]);used.push(bj);rest.splice(rest.indexOf(bj),1);}
const mark={w:S.wires.length,l:S.labels.length,p:S.power.length}, added=[];
for(const [i,j] of edges){
const A=pinGeo[i],B=pinGeo[j],A2=[r2(A.x+A.dx*L),r2(A.y+A.dy*L)],B2=[r2(B.x+B.dx*L),r2(B.y+B.dy*L)];
let mid=(onGrid(A2[0])&&onGrid(A2[1])&&onGrid(B2[0])&&onGrid(B2[1]))?router.route(A2,B2,net.name):null;
if(!mid) mid=ortho([A2,B2]);
const pts=dedupe([[A.x,A.y],...mid,[B.x,B.y]]); S.wires.push({pts}); added.push(pts); router.mark(pts,net.name);
}
const g0=pinGeo[ids[0]]; S.labels.push({x:r2(g0.x+g0.dx*L),y:r2(g0.y+g0.dy*L),name:net.name,dir:dirOf(g0)});
// 검증: 이 넷의 핀들이 정확히 하나의 연결로 묶이고 다른 핀이 섞이지 않았는가
const r=schDerive(), hit=r.nets.find(n=>n.pins.includes(ids[0]));
if(hit&&hit.pins.length===ids.length&&ids.every(id=>hit.pins.includes(id))){ nWire+=added.length; continue; }
(window.schFails=window.schFails||[]).push({net:net.name,ids,got:hit?hit.pins:null});
S.wires.length=mark.w; S.labels.length=mark.l; S.power.length=mark.p; nFall++; stubs(net,ids);
}
// 최종 검증: 회로도에서 읽은 연결이 원래 넷과 정확히 같아야 한다(선이 서로 닿아 넷이 합쳐지면 실패)
const fin=schDerive(), key=n=>n.pins.slice().sort().join(','), want=new Map(expect.filter(n=>n.pins.length>=2).map(n=>[key(n),n.name])), got=new Set(fin.nets.filter(n=>n.pins.length>=2).map(key));
const bad=[...want.entries()].filter(([k])=>!got.has(k)).map(([,nm])=>nm).concat([...got].filter(k=>!want.has(k)).map(k=>'(합쳐짐: '+k.split(',').length+'핀)'));
if(bad.length) return {ok:false,bad,wire:nWire,stub:nStub,fallback:nFall};
schCommit(); return {ok:true,wire:nWire,stub:nStub,fallback:nFall};
}
// 연결이 틀어지면 한 번 더(스터브 짧게) 시도하고, 그래도 안 되면 원래 회로도·연결 그대로 되돌린다.
function schFromNets(){
const snapSch=JSON.stringify(P.sch), snapNets=JSON.stringify(P.nets); window.schReverted=null;
for(const mx of [5.08,2.54]){
window.schExpect=JSON.parse(snapNets);
const r=schFromNetsOnce(mx);
if(r.ok) return r;
P.sch=JSON.parse(snapSch); P.nets=JSON.parse(snapNets); window.schReverted={bad:r.bad};
}
schDerive(); changed(); return {wire:0,stub:0,fallback:0,reverted:true,bad:window.schReverted.bad};
}
function schAutoWires(){ if(!P.nets.length){$('hint').innerHTML='<span class="warn">연결(넷)이 없습니다.</span>';return;} const r=schFromNets(); if(r.reverted){$('hint').innerHTML='<span class="warn">⚠ 자동 배선이 선을 서로 닿게 해 넷이 합쳐져서 취소했습니다(원래 회로도·연결 그대로): '+esc(r.bad.slice(0,4).join(', '))+'. 부품을 좀 더 벌려 놓고 다시 시도하세요.</span>';return;} $('hint').textContent=`배선 ${r.wire}개, 전원·이름표 연결 ${r.stub}개를 만들었습니다${r.fallback?` (겹침 때문에 ${r.fallback}개 넷은 이름표 방식)`:''}. 부품을 끌어 배치를 정리하세요.`; schFit(); }
function setTab(t){
if(tab==='cons'&&t!=='cons'&&typeof closeConsoleTab==='function') closeConsoleTab();
if(tab==='desc'&&t!=='desc'&&descDirty&&typeof descSave==='function') descSave(true);
tab=t; try{localStorage.setItem('pcb-tab',t);}catch(e){}
$('t-pcb').classList.toggle('on',t==='pcb'); $('t-sch').classList.toggle('on',t==='sch'); $('t-desc').classList.toggle('on',t==='desc'); $('t-cons').classList.toggle('on',t==='cons');
$('pane-desc').style.display=t==='desc'?'flex':'none';
$('bar').style.display=t==='pcb'?'flex':'none'; $('sbar').style.display=t==='sch'?'flex':'none';
$('cv').style.display=t==='pcb'?'block':'none'; $('scv').style.display=t==='sch'?'block':'none';
$('pane-cons').style.display=t==='cons'?'flex':'none';
if(t==='desc'){openDesc();return;}
if(t==='cons'){openPcbConsole();return;}
if(t==='sch'){ensurePlaced();schDerive();resizeSch();if(!sfit){sfit=true;schFit();}setSMode(smode);}
else{resize();if(!routed&&P.nets.length&&!$('rbtn').disabled)$('rres').innerHTML='<span class="warn">아직 배선이 없습니다. 위의 "🧭 자동 배선"을 누르세요.</span>';$('hint').textContent='부품을 왼쪽에서 눌러 추가 → 끌어서 배치 → 🔗 핀 연결 모드에서 핀을 차례로 클릭해 연결 → 오른쪽에서 자동 배선';}
}
// 실제 부품 모양(저항=아령, 콘덴서=타원, 다이오드=띠 있는 원통, LED=평평한 원, 인덕터=코일, DIP=홈 있는 상자, TO-92=D자, TO-220=상자+방열판).
// 못 알아보는 부품은 false 를 돌려줘 기본 사각 외곽선으로 그린다. 선 굵기는 화면 1~2px 로 고정.
function drawPartShape(part,isSel){
const f=FPM[part.fp]; if(!f) return false;
const id=part.fp.toLowerCase(), pads=padsOf(part);
const lw=(isSel?2:1.2), fillc='rgba(255,255,255,.07)';
const fin=()=>{ctx.fillStyle=fillc;ctx.fill();ctx.lineWidth=lw/view.s;ctx.stroke();};
// ── 2핀 축 방향 부품 ──
if(pads.length===2&&!f.smd){
const A=pads.find(q=>q.n==='1')||pads[0], B=pads.find(q=>q!==A), d=Math.hypot(B.x-A.x,B.y-A.y);
const ang=Math.atan2(B.y-A.y,B.x-A.x), mx=(A.x+B.x)/2, my=(A.y+B.y)/2;
const kind=/^r/i.test(part.ref)?'R':/^l/i.test(part.ref)?'L':/^c/i.test(part.ref)?(/cp_|elko|polar|c_radial/.test(id)&&f.circle?'':'C'):/^d|^led/i.test(part.ref)?(/led/.test(id)?'LED':'D'):'';
const local=(fn)=>{ctx.save();ctx.translate(sx(mx),sy(my));ctx.rotate(ang);ctx.scale(view.s,view.s);fn();ctx.restore();};
if(kind==='R'&&d>=4.4){ local(()=>{
const bl=Math.max(2.6,Math.min(d-2.2,6.8)), rb=1.4, n=0.7, c=bl/2-rb, th=Math.asin(n/rb);
ctx.beginPath();ctx.arc(c,0,rb,Math.PI+th,3*Math.PI-th);ctx.arc(-c,0,rb,th,2*Math.PI-th);ctx.closePath();fin();
ctx.beginPath();ctx.moveTo(-d/2,0);ctx.lineTo(-bl/2,0);ctx.moveTo(bl/2,0);ctx.lineTo(d/2,0);ctx.lineWidth=lw/view.s;ctx.stroke();}); return true; }
if(kind==='C'&&d>=2.2){ local(()=>{ctx.beginPath();ctx.ellipse(0,0,d/2+1.3,Math.min(2.2,Math.max(1.3,d/3)),0,0,2*Math.PI);fin();}); return true; }
if(kind==='D'&&d>=4.4){ local(()=>{
const bl=Math.max(2.6,Math.min(d-2.2,5.4)), h=1.4; // 1번 핀(음극, 왼쪽)에 띠
ctx.beginPath();ctx.roundRect?ctx.roundRect(-bl/2,-h,bl,2*h,0.5):ctx.rect(-bl/2,-h,bl,2*h);fin();
ctx.fillStyle=ctx.strokeStyle;ctx.fillRect(-bl/2+0.35,-h,0.9,2*h);
ctx.beginPath();ctx.moveTo(-d/2,0);ctx.lineTo(-bl/2,0);ctx.moveTo(bl/2,0);ctx.lineTo(d/2,0);ctx.lineWidth=lw/view.s;ctx.stroke();}); return true; }
if(kind==='LED'){ local(()=>{
const r=Math.max(1.6,Math.min(2.9,d/2+0.8)), fl=0.82*r, ph=Math.acos(fl/r); // 평평한 쪽이 1번 핀(음극)
ctx.beginPath();ctx.arc(0,0,r,Math.PI+ph,3*Math.PI-ph);ctx.closePath();fin();}); return true; }
if(kind==='L'&&d>=4.4){ local(()=>{
const w=d-2.2, n=Math.max(3,Math.round(w/1.6)), r=w/n/2;
ctx.beginPath();ctx.moveTo(-d/2,0);ctx.lineTo(-w/2,0);for(let k=0;k<n;k++)ctx.arc(-w/2+r+k*2*r,0,r,Math.PI,0,false);ctx.lineTo(d/2,0);ctx.lineWidth=lw/view.s;ctx.stroke();}); return true; }
return false;
}
// ── 부품 자체 좌표계 (몸체 상자 기준) ──
const b=f.body, bw=b.x1-b.x0, bh=b.y1-b.y0, rot=((Math.round(part.rot/90)*90)%360+360)%360;
const loc=(fn)=>{ctx.save();ctx.translate(sx(part.x),sy(part.y));ctx.rotate(rot*Math.PI/180);ctx.scale(view.s,view.s);fn();ctx.restore();};
const padCy=f.pads.reduce((a,q)=>a+q.y,0)/Math.max(1,f.pads.length), nearTop=(b.y0+b.y1)/2>padCy; // 몸체가 핀 아래쪽이면 위쪽 변이 핀 쪽
if(/dip-|dip_|sip-/.test(id)&&/dip/.test(id)){
const p1=f.pads.find(q=>q.n==='1'); if(!p1) return false; const vert=bh>=bw; const x0=b.x0,x1=b.x1,y0=b.y0,y1=b.y1;
loc(()=>{ctx.beginPath();ctx.rect(x0,y0,bw,bh);fin();ctx.beginPath();
if(vert){const top=Math.abs(p1.y-y0)<Math.abs(p1.y-y1), cy=top?y0:y1; ctx.arc((x0+x1)/2,cy,0.9,top?0:Math.PI,top?Math.PI:2*Math.PI,false);}
else{const left=Math.abs(p1.x-x0)<Math.abs(p1.x-x1), cx=left?x0:x1; ctx.arc(cx,(y0+y1)/2,0.9,left?-Math.PI/2:Math.PI/2,left?Math.PI/2:-Math.PI/2,false);}
ctx.lineWidth=lw/view.s;ctx.stroke();}); return true; }
if(/to-92/.test(id)&&bw>0){
loc(()=>{const cx=(b.x0+b.x1)/2, rr=bw/2, flat=nearTop?b.y0:b.y1, sg=nearTop?1:-1, cy=flat+sg*Math.max(0,bh-rr)*1;
ctx.beginPath();ctx.moveTo(b.x0,flat);ctx.lineTo(b.x1,flat);ctx.lineTo(b.x1,cy);ctx.arc(cx,cy,rr,0,Math.PI*sg,sg<0);ctx.closePath();fin();}); return true; }
if(/to-220|to-247|to-126/.test(id)){
loc(()=>{ctx.beginPath();ctx.rect(b.x0,b.y0,bw,bh);fin();
const th=Math.min(1.6,bh*0.3), ty=nearTop?b.y1-th:b.y0; // 핀 반대쪽 방열판 띠 + 고정 구멍
ctx.fillStyle='rgba(255,255,255,.18)';ctx.fillRect(b.x0,ty,bw,th);
ctx.beginPath();ctx.arc((b.x0+b.x1)/2,ty+th/2,Math.min(0.9,th*0.35),0,7);ctx.lineWidth=lw/view.s;ctx.stroke();}); return true; }
return false;
}
// ───────────── 예제 ─────────────
const EX_SMPS={
board:{w:56,h:40},
note:'555 타이머(약 50kHz, 듀티 약 58%)가 MOSFET 을 켜고 끄는 승압(boost) 컨버터입니다. 입력 5V → 출력 약 12V(시뮬레이션 12.1V, 시작 직후 약 22V까지 오버슈트 후 안정). 되먹임이 없는 개방 루프라 부하에 따라 출력이 변합니다(시뮬레이션: 220~470Ω 11.6V · 1kΩ 12V · 2.2kΩ 17V · 10kΩ 26V). 그래서 R4(470Ω)를 항상 연결해 두고, 출력 커패시터는 35V 이상을 쓰세요. 주파수 f≈1.44/((R1+2·R2)·C1), 듀티 D=(R1+R2)/(R1+2·R2).',
parts:[
{ref:'J1',fp:'TERM-2P',value:'VIN 5V',pcb:[7,24,90],sch:[20,62,0]},
{ref:'J2',fp:'TERM-2P',value:'VOUT',pcb:[48,24,90],sch:[226,62,0]},
{ref:'U1',fp:'kicad:Package_DIP:DIP-8_W7.62mm',sym:'Timer:NE555P',value:'NE555',pcb:[18.5,23,270],sch:[80,70,0]},
{ref:'Q1',fp:'kicad:Package_TO_SOT_THT:TO-220-3_Vertical',sym:'Transistor_FET:IRLZ44N',value:'IRLZ44N',pcb:[31,23.5,90],sch:[148,78,0]},
{ref:'D1',fp:'kicad:Diode_THT:D_DO-41_SOD81_P10.16mm_Horizontal',sym:'Diode:1N5819',value:'1N5819',pcb:[38,32.5,270],sch:[178,46,0]},
{ref:'L1',fp:'kicad:Inductor_THT:L_Axial_L9.5mm_D4.0mm_P15.24mm_Horizontal_Fastron_SMCC',sym:'Device:L',value:'1m',pcb:[18.5,10,0],sch:[148,34,0]},
{ref:'R1',fp:'kicad:Resistor_THT:R_Axial_DIN0207_L6.3mm_D2.5mm_P10.16mm_Horizontal',sym:'Device:R',value:'4.7k',pcb:[8.5,6,90],sch:[46,24,0]},
{ref:'R2',fp:'kicad:Resistor_THT:R_Axial_DIN0207_L6.3mm_D2.5mm_P10.16mm_Horizontal',sym:'Device:R',value:'12k',pcb:[13.5,13.5,90],sch:[46,58,0]},
{ref:'R3',fp:'kicad:Resistor_THT:R_Axial_DIN0207_L6.3mm_D2.5mm_P10.16mm_Horizontal',sym:'Device:R',value:'47',pcb:[41,17.5,180],sch:[122,62,90]},
{ref:'R4',fp:'kicad:Resistor_THT:R_Axial_DIN0207_L6.3mm_D2.5mm_P10.16mm_Horizontal',sym:'Device:R',value:'470',pcb:[43,22,90],sch:[212,76,0]},
{ref:'C1',fp:'kicad:Capacitor_THT:C_Disc_D5.0mm_W2.5mm_P5.00mm',sym:'Device:C',value:'1n',pcb:[16.5,28,180],sch:[46,94,0]},
{ref:'C2',fp:'kicad:Capacitor_THT:C_Disc_D5.0mm_W2.5mm_P5.00mm',sym:'Device:C',value:'10n',pcb:[21,32,270],sch:[104,100,0]},
{ref:'C3',fp:'kicad:Capacitor_THT:C_Disc_D5.0mm_W2.5mm_P5.00mm',sym:'Device:C',value:'100n',pcb:[26,27,90],sch:[104,32,0]},
{ref:'C4',fp:'kicad:Capacitor_THT:CP_Radial_D6.3mm_P2.50mm',sym:'Device:C_Polarized',value:'22u',pcb:[48,31.5,270],sch:[196,76,0]}],
nets:[
{name:'VIN',pins:['J1-1','U1-8','U1-4','L1-1','C3-1','R1-1']},
{name:'GND',pins:['J1-2','U1-1','C1-2','C2-2','C3-2','Q1-3','C4-2','R4-2','J2-2']},
{name:'SW',pins:['L1-2','Q1-2','D1-2']},{name:'VOUT',pins:['D1-1','C4-1','R4-1','J2-1']},
{name:'OUT555',pins:['U1-3','R3-1']},{name:'GATE',pins:['R3-2','Q1-1']},
{name:'DIS',pins:['U1-7','R1-2','R2-1']},{name:'THR',pins:['U1-6','U1-2','R2-2','C1-1']},{name:'CTL',pins:['U1-5','C2-1']}],
sim:{gnd:'GND',sources:[{type:'dc',pos:'VIN',dc:'5'}],analysis:{type:'tran',stop:'40m',step:'0.4u',fstart:'10',fstop:'100k',ppd:'20'},probes:['VOUT']}
};
const EX_SMPS_FB={
board:{w:63,h:45},
note:'TL431(2.5V 기준)과 LM358 비교기가 출력 전압을 감시하다가 설정값(2.495×(1+R5/R6)≈12.2V)을 넘으면 555 의 RESET 핀을 눌러 스위칭을 잠시 멈추는 펄스 건너뛰기 방식입니다. R8·C5 는 소프트 스타트(기준 전압을 서서히 올려 시동 때 오버슈트 방지)입니다. 시뮬레이션: 부하 470Ω~100kΩ(200배)에서 출력 12.1~12.2V 유지, 오버슈트 0.08V. 출력은 R5/R6 비로 정합니다(R5=R6·(Vout/2.495−1)). LM358 의 쓰지 않는 두 번째 증폭기는 전압 팔로워로 묶어 두었습니다. 출력 커패시터는 25V 이상.',
parts:[
{ref:'J1',fp:'TERM-2P',value:'VIN 5V',pcb:[7,25,0],sch:[20,62,0]},
{ref:'J2',fp:'TERM-2P',value:'VOUT',pcb:[56.5,28.5,270],sch:[226,62,0]},
{ref:'U1',fp:'kicad:Package_DIP:DIP-8_W7.62mm',sym:'Timer:NE555P',value:'NE555',pcb:[29.5,40,180],sch:[80,70,0]},
{ref:'U2',fp:'kicad:Package_DIP:DIP-8_W7.62mm',sym:'Amplifier_Operational:LM358',value:'LM358',pcb:[17.5,29.5,90],sch:[156,150,0]},
{ref:'U3',fp:'kicad:Package_TO_SOT_THT:TO-92_Inline',sym:'Reference_Voltage:TL431LP',value:'TL431',pcb:[7.5,12,90],sch:[62,146,0]},
{ref:'Q1',fp:'kicad:Package_TO_SOT_THT:TO-220-3_Vertical',sym:'Transistor_FET:IRLZ44N',value:'IRLZ44N',pcb:[31.5,22.5,0],sch:[148,78,0]},
{ref:'D1',fp:'kicad:Diode_THT:D_DO-41_SOD81_P10.16mm_Horizontal',sym:'Diode:1N5819',value:'1N5819',pcb:[43.5,15.5,180],sch:[178,46,0]},
{ref:'L1',fp:'kicad:Inductor_THT:L_Axial_L9.5mm_D4.0mm_P15.24mm_Horizontal_Fastron_SMCC',sym:'Device:L',value:'1m',pcb:[13.5,10.5,0],sch:[148,34,0]},
{ref:'R1',fp:'kicad:Resistor_THT:R_Axial_DIN0207_L6.3mm_D2.5mm_P10.16mm_Horizontal',sym:'Device:R',value:'4.7k',pcb:[38.5,36.5,0],sch:[46,24,0]},
{ref:'R2',fp:'kicad:Resistor_THT:R_Axial_DIN0207_L6.3mm_D2.5mm_P10.16mm_Horizontal',sym:'Device:R',value:'12k',pcb:[5,29.5,90],sch:[46,58,0]},
{ref:'R3',fp:'kicad:Resistor_THT:R_Axial_DIN0207_L6.3mm_D2.5mm_P10.16mm_Horizontal',sym:'Device:R',value:'47',pcb:[27.5,27.5,0],sch:[122,62,90]},
{ref:'R4',fp:'kicad:Resistor_THT:R_Axial_DIN0207_L6.3mm_D2.5mm_P10.16mm_Horizontal',sym:'Device:R',value:'470',pcb:[42,26,0],sch:[212,76,0]},
{ref:'R5',fp:'kicad:Resistor_THT:R_Axial_DIN0207_L6.3mm_D2.5mm_P10.16mm_Horizontal',sym:'Device:R',value:'39k',pcb:[42,20.5,0],sch:[206,134,0]},
{ref:'R6',fp:'kicad:Resistor_THT:R_Axial_DIN0207_L6.3mm_D2.5mm_P10.16mm_Horizontal',sym:'Device:R',value:'10k',pcb:[47.5,15.5,0],sch:[206,166,0]},
{ref:'R7',fp:'kicad:Resistor_THT:R_Axial_DIN0207_L6.3mm_D2.5mm_P10.16mm_Horizontal',sym:'Device:R',value:'1k',pcb:[24.5,16,180],sch:[30,138,0]},
{ref:'R8',fp:'kicad:Resistor_THT:R_Axial_DIN0207_L6.3mm_D2.5mm_P10.16mm_Horizontal',sym:'Device:R',value:'10k',pcb:[19,5,180],sch:[92,134,0]},
{ref:'C1',fp:'kicad:Capacitor_THT:C_Disc_D5.0mm_W2.5mm_P5.00mm',sym:'Device:C',value:'1n',pcb:[34,35,90],sch:[46,94,0]},
{ref:'C2',fp:'kicad:Capacitor_THT:C_Disc_D5.0mm_W2.5mm_P5.00mm',sym:'Device:C',value:'10n',pcb:[22.5,28,270],sch:[104,100,0]},
{ref:'C3',fp:'kicad:Capacitor_THT:C_Disc_D5.0mm_W2.5mm_P5.00mm',sym:'Device:C',value:'100n',pcb:[35.5,10.5,0],sch:[104,32,0]},
{ref:'C5',fp:'kicad:Capacitor_THT:C_Disc_D5.0mm_W2.5mm_P5.00mm',sym:'Device:C',value:'330n',pcb:[17,20.5,90],sch:[118,150,0]},
{ref:'C4',fp:'kicad:Capacitor_THT:CP_Radial_D6.3mm_P2.50mm',sym:'Device:C_Polarized',value:'22u',pcb:[48,28.5,270],sch:[196,76,0]}],
nets:[
{name:'VIN',pins:['J1-1','U1-8','L1-1','C3-1','R1-1','U2-8','R7-1']},
{name:'GND',pins:['J1-2','U1-1','C1-2','C2-2','C3-2','C5-2','Q1-3','C4-2','R4-2','J2-2','U2-4','U2-5','R6-2','U3-2']},
{name:'SW',pins:['L1-2','Q1-2','D1-2']},{name:'VOUT',pins:['D1-1','C4-1','R4-1','J2-1','R5-1']},
{name:'OUT555',pins:['U1-3','R3-1']},{name:'GATE',pins:['R3-2','Q1-1']},
{name:'DIS',pins:['U1-7','R1-2','R2-1']},{name:'THR',pins:['U1-6','U1-2','R2-2','C1-1']},{name:'CTL',pins:['U1-5','C2-1']},
{name:'EN',pins:['U1-4','U2-1']},{name:'FB',pins:['U2-2','R5-2','R6-1']},{name:'REF',pins:['U3-1','U3-3','R7-2','R8-1']},{name:'REFS',pins:['U2-3','R8-2','C5-1']},{name:'NC_OA',pins:['U2-6','U2-7']}],
sim:{gnd:'GND',sources:[{type:'dc',pos:'VIN',dc:'5'}],analysis:{type:'tran',stop:'25m',step:'0.4u',fstart:'10',fstop:'100k',ppd:'20'},probes:['VOUT']}
};
async function loadExample(id){
if(!id) return;
if(P&&P.parts.length&&!confirm('현재 작업을 예제로 바꿀까요?')) return;
if(id==='basic'){ loadSample(true); return; }
const E=id==='smps_fb'?EX_SMPS_FB:EX_SMPS;
P={board:{...E.board},parts:E.parts.map(x=>({ref:x.ref,fp:x.fp,sym:x.sym,value:x.value,x:x.pcb[0],y:x.pcb[1],rot:x.pcb[2]})),nets:E.nets.map(n=>({name:n.name,pins:[...n.pins]})),fps:{},
sch:{pos:Object.fromEntries(E.parts.map(x=>[x.ref,{x:r2(Math.round(x.sch[0]/2.54)*2.54),y:r2(Math.round(x.sch[1]/2.54)*2.54),rot:x.sch[2]||0,mir:!!x.sch[3]}])),wires:[],labels:[],power:[]},
sim:JSON.parse(JSON.stringify(E.sim)),rules:{...DEF_RULES,trace:0.6,clearance:0.4},mill:{...DEF_MILL}};
for(const k of Object.keys(P.parts[0])) if(P.parts[0][k]===undefined) delete P.parts[0][k];
routed=null;gres=null;sel=null;pending=null;simRes=null;histReset();$('simpane').style.display='none';
// 심볼 핀 이름(라벨 표시용)과 풋프린트를 불러온다
await Promise.all(P.parts.filter(x=>x.sym).map(async part=>{try{const d=await api('/api/pcb/kicad/symbol?id='+encodeURIComponent(part.sym));part.pinNames={};for(const q of d.symbol.pins){const nm=clean(q.name);if(nm)part.pinNames[q.n]=nm;}}catch(e){}}));
await registerFps(); syncUI(); fitView();
setTab('sch'); await new Promise(r=>setTimeout(r,600)); schFromNets(); schFit();
changed(); $('hint').innerHTML='<span class="ok">✔ 예제를 불러왔습니다.</span> '+esc(E.note);
$('rres').innerHTML='자동 배선 준비 중…'; doRoute();
}
// ───────────── 실행 취소 / 다시 실행 ─────────────
// 기판·회로도 편집 상태(보드·부품·넷·규칙·회로도)만 스냅샷으로 기록한다. 시뮬레이션/밀링 설정과 풋프린트 캐시는 되돌리지 않는다.
let hist=[], hidx=-1, histBusy=false, routedCache=null; // routedCache: 마지막 배선 결과와 그 배치 키(실행 취소로 같은 배치가 되면 복원)
const histSnap=()=>JSON.stringify({board:P.board,parts:P.parts,nets:P.nets,rules:P.rules,sch:P.sch});
function histPush(){
if(histBusy||!P) return; const sn=histSnap(); if(hist[hidx]===sn) return;
hist=hist.slice(0,hidx+1); hist.push(sn); if(hist.length>100) hist.shift(); hidx=hist.length-1; updUndo();
}
function histReset(){hist=[];hidx=-1;if(!srvSuppress){projDirty=false;const e=$('pname');if(e&&!(P&&P.name))e.value='';}}
function updUndo(){const u=$('undo'),r=$('redo');if(u)u.disabled=hidx<=0;if(r)r.disabled=hidx>=hist.length-1;}
function histRestore(){
const o=JSON.parse(hist[hidx]); histBusy=true;
P.board=o.board;P.parts=o.parts;P.nets=o.nets;P.rules=o.rules;P.sch=o.sch;
routed=null;gres=null;sel=null;ssel=null;wiring=null;pending=null;
if(routedCache&&routedCache.key===pcbKey()) routed=routedCache.routed; // 배치가 배선했을 때와 같아지면 배선도 복원
syncUI();renderNets();updSel();draw();if(tab==='sch'){schDerive();drawSch();}renderSim();save();
histBusy=false;updUndo();
}
function undo(){if(hidx>0){hidx--;histRestore();}}
function redo(){if(hidx<hist.length-1){hidx++;histRestore();}}
window.addEventListener('keydown',e=>{
if(!(e.ctrlKey||e.metaKey)||/INPUT|SELECT|TEXTAREA/.test(document.activeElement.tagName)) return;
const k=e.key.toLowerCase();
if(k==='z'&&!e.shiftKey){e.preventDefault();undo();} else if(k==='y'||(k==='z'&&e.shiftKey)){e.preventDefault();redo();}
});
// 회로도의 선·이름표·전원 기호를 모두 지우고 현재 연결(넷)대로 다시 배선한다
// ── 회로도 자동 정렬: 신호 흐름 순서(왼쪽 입력 → 오른쪽 출력)로 부품을 열에 나눠 배치하고 방향도 맞춘 뒤 다시 배선한다 ──
function schAutoArrange(){
ensureSch(); ensurePlaced();
if(!P.parts.length||!P.nets.length){$('hint').innerHTML='<span class="warn">부품과 연결(넷)이 있어야 정렬할 수 있습니다.</span>';return;}
const gf=P.parts.map(p=>[p,partGfx(p)]);
if(gf.some(([,g])=>!g||g.loading)){$('hint').innerHTML='<span class="warn">부품 기호를 불러오는 중입니다. 잠시 뒤 다시 눌러 주세요.</span>';return;}
const before=JSON.stringify(P.sch), keepNets=P.nets.map(n=>({name:n.name,pins:[...n.pins]}));
const isGndN=n=>/^(gnd|pgnd|sgnd|agnd|dgnd|vss|0v)$/i.test(n), isSupN=n=>/^(vin|vout|vcc|vdd|vbus|[+-]\d)/i.test(n);
const refs=P.parts.map(p=>p.ref), idx=new Map(refs.map((r,i)=>[r,i]));
const refOf=id=>id.slice(0,id.lastIndexOf('-'));
// 넷 분류: 접지·전원·여러 부품이 물린 넷은 '레일'(배치 기준에서 약하게), 나머지는 신호
const info=P.nets.map(n=>{const rs=[...new Set(n.pins.map(refOf))].filter(r=>idx.has(r));const rail=isGndN(n.name)||isSupN(n.name)||rs.length>=5;return {n,rs,rail,gnd:isGndN(n.name),sup:isSupN(n.name)&&!isGndN(n.name)};});
const sigAdj=new Map(refs.map(r=>[r,new Set()])), allW=new Map(refs.map(r=>[r,new Map()]));
for(const f of info){ if(f.rs.length<2) continue;
for(const a of f.rs) for(const b of f.rs){ if(a===b) continue; if(!f.rail) sigAdj.get(a).add(b); const w=(f.rail?0.2:1)/(f.rs.length-1); allW.get(a).set(b,(allW.get(a).get(b)||0)+w); } }
// 1) 열 나누기: 입력 커넥터에서 연결 비용(핀이 많은 넷일수록 비싼 다리)으로 거리를 재고, 거리순으로 열마다 비슷한 수를 나눠 담는다
const seedRef=refs.find(r=>/^J\d*$/i.test(r)&&sigAdj.get(r).size)||refs.slice().sort((a,b)=>sigAdj.get(b).size-sigAdj.get(a).size)[0];
const edgeCost=new Map(refs.map(r=>[r,new Map()]));
for(const f of info){ if(f.gnd||f.rs.length<2) continue; const k=f.rs.length, c=k<=2?1:k===3?1.5:k<=5?3:k<=8?5:Infinity; if(!isFinite(c)) continue;
for(const a of f.rs) for(const b of f.rs) if(a!==b){const m=edgeCost.get(a); if(!(m.get(b)<=c)) m.set(b,c);} }
const dist=new Map([[seedRef,0]]), done=new Set();
for(;;){ let u=null,du=Infinity; for(const [r,d] of dist) if(!done.has(r)&&d<du){du=d;u=r;} if(u===null) break; done.add(u);
for(const [q,c] of edgeCost.get(u)){ const nd=du+c; if(!(dist.get(q)<=nd)) dist.set(q,nd); } }
// 거리가 안 잡힌(연결이 약한) 부품은 가장 많이 얽힌 이웃의 거리를 따른다
let rest=refs.filter(r=>!dist.has(r));
while(rest.length){
let best=null,bw=0; for(const r of rest) for(const [q,w] of allW.get(r)) if(dist.has(q)&&w>bw){bw=w;best=[r,q];}
if(!best){ const mx=Math.max(0,...dist.values())+1; for(const r of rest) dist.set(r,mx); break; }
dist.set(best[0],dist.get(best[1])+0.01); rest=rest.filter(r=>r!==best[0]);
}
const ranked=refs.slice().sort((a,b)=>dist.get(a)-dist.get(b)||idx.get(a)-idx.get(b));
const K=Math.max(3,Math.min(9,Math.round(Math.sqrt(refs.length)*1.1))), layer=new Map(ranked.map((r,i)=>[r,Math.min(K-1,Math.floor(i*K/refs.length))]));
// 2) 열 안 순서: 이웃 위치의 평균(무게중심)으로 몇 번 정렬해 선 교차를 줄인다
const nL=Math.max(...layer.values())+1, cols=Array.from({length:nL},()=>[]); refs.forEach(r=>cols[layer.get(r)].push(r));
const order=new Map(); const reorder=()=>cols.forEach(c=>c.forEach((r,i)=>order.set(r,i/Math.max(1,c.length-1))));
reorder();
for(let it=0;it<4;it++){ for(const dir of [1,-1]){ const seq=dir>0?[...cols.keys()]:[...cols.keys()].reverse();
for(const li of seq){ const c=cols[li]; const bc=new Map(c.map(r=>{const nb=[...allW.get(r)].filter(([q])=>layer.get(q)!==li&&(dir>0?layer.get(q)<li:layer.get(q)>li)).map(([q,w])=>[order.get(q),w]);const tw=nb.reduce((a,[,w])=>a+w,0);return [r,tw?nb.reduce((a,[o,w])=>a+o*w,0)/tw:order.get(r)];})); c.sort((a,b)=>bc.get(a)-bc.get(b)||ncmp(a.replace(/\D/g,''),b.replace(/\D/g,''))); reorder(); } } }
// 3) 방향: 신호 이웃이 앞 열이면 그 핀을 왼쪽에, 뒤 열이면 오른쪽에. 접지 핀은 아래, 전원 핀은 위.
const pinNet=new Map(); info.forEach(f=>f.n.pins.forEach(id=>pinNet.set(id,f)));
const refLayer=r=>layer.get(r);
for(const part of P.parts){
const pos=P.sch.pos[part.ref], saved={...pos}; let bestV=null,bs=-1e9;
for(const mir of [false,true]) for(const rot of [0,90,180,270]){
pos.rot=rot; pos.mir=mir; const pins=partPins(part); if(!pins.length) continue;
const cx=pins.reduce((a,q)=>a+q.x,0)/pins.length, cy=pins.reduce((a,q)=>a+q.y,0)/pins.length; let sc=0;
for(const pin of pins){ const f=pinNet.get(part.ref+'-'+pin.n); if(!f) continue;
const others=f.rs.filter(r=>r!==part.ref&&!f.rail); if(others.length){const d=others.reduce((a,r)=>a+Math.sign(refLayer(r)-refLayer(part.ref)),0)/others.length; sc+=d*Math.sign(pin.x-cx)*(Math.abs(pin.x-cx)>0.5?1:0);}
if(f.gnd) sc+=0.6*Math.sign(pin.y-cy)*(Math.abs(pin.y-cy)>0.5?1:0); else if(f.sup) sc-=0.6*Math.sign(pin.y-cy)*(Math.abs(pin.y-cy)>0.5?1:0); }
if(pins.length===2){ const vert=Math.abs(pins[0].y-pins[1].y)>Math.abs(pins[0].x-pins[1].x); if(vert) sc+=0.05; }
if(rot===(saved.rot||0)&&mir===!!saved.mir) sc+=0.01;
if(sc>bs){bs=sc;bestV={rot,mir};}
}
Object.assign(pos,saved); if(bestV){pos.rot=bestV.rot;pos.mir=bestV.mir;}
}
// 4) 좌표: 열마다 위에서 아래로 쌓고, 열 사이에 선·이름표가 지날 간격을 둔다
const GAPX=30, GAPY=15, MAXH=190, boxes=new Map(P.parts.map(p=>{pos0(p);return [p.ref,partBoxS(p)];}));
function pos0(p){const q=P.sch.pos[p.ref];q.x=0;q.y=0;}
const sz=r=>{const b=boxes.get(r);return {w:b.x1-b.x0,h:b.y1-b.y0,ox:-b.x0,oy:-b.y0};};
let cx0=20; const placed=[];
cols.forEach(c=>{
// 너무 길면 같은 열을 두 줄로
const heights=c.map(r=>sz(r).h+GAPY), total=heights.reduce((a,b)=>a+b,0), nSub=Math.max(1,Math.ceil(total/MAXH)), per=Math.ceil(c.length/nSub);
for(let sIdx=0;sIdx<nSub;sIdx++){
const grp=c.slice(sIdx*per,(sIdx+1)*per); if(!grp.length) continue; const w=Math.max(...grp.map(r=>sz(r).w));
let y=20; for(const r of grp){const z=sz(r),pos=P.sch.pos[r]; pos.x=sSnap(cx0+z.ox+(w-z.w)/2); pos.y=sSnap(y+z.oy); y+=z.h+GAPY; placed.push(r);}
cx0+=w+GAPX;
}
});
// 5) 다시 배선 — 안 되면 정렬 전 모습 그대로
P.sch.wires=[];P.sch.labels=[];P.sch.power=[];ssel=null;P.nets=keepNets;
const r=schFromNets();
if(r.reverted){ P.sch=JSON.parse(before); P.nets=keepNets; schDerive(); changed(); drawSch(); $('hint').innerHTML='<span class="warn">⚠ 정렬 뒤 배선에서 넷이 합쳐져 정렬을 취소했습니다(원래대로): '+esc(r.bad.slice(0,4).join(', '))+'</span>'; return; }
schFit(); drawSch();
$('hint').textContent=`${nL}개 열로 정렬하고 배선했습니다 — 선 ${r.wire}개, 이름표 연결 ${r.stub}개${r.fallback?` (겹침 때문에 ${r.fallback}개 넷은 이름표 방식)`:''}. 실행 취소(Ctrl+Z)로 되돌릴 수 있습니다.`;
}
// 극성 점: 부품의 dots(핀 번호 목록)에 든 핀의 몸체 쪽 끝에 점을 찍는다(트랜스 권선 시작 표시). 표시 전용 — 연결 해석에는 영향 없음.
function schDots(){
if(!ssel||ssel.kind!=='part'){$('hint').innerHTML='<span class="warn">극성점을 찍을 부품을 먼저 선택하세요.</span>';return;}
const part=P.parts.find(x=>x.ref===ssel.ref); if(!part) return;
const v=prompt(part.ref+' 극성 점을 찍을 핀 번호 (쉼표로 구분, 비우면 모두 지움)',(part.dots||[]).join(','));
if(v===null) return;
const list=[...new Set(v.split(/[,\s]+/).map(x=>x.trim()).filter(Boolean))];
if(list.length) part.dots=list; else delete part.dots;
changed(true); drawSch();
}
function schRewire(){
ensureSch(); if(!P.nets.length){$('hint').innerHTML='<span class="warn">연결(넷)이 없습니다.</span>';return;}
if(schDriven()&&!confirm('회로도의 선·이름표·전원 기호를 모두 지우고 다시 배선합니다. (부품 위치와 연결은 그대로, 실행 취소로 되돌릴 수 있습니다)')) return;
const keep=P.nets.map(n=>({name:n.name,pins:[...n.pins]})), before=JSON.stringify(P.sch);
P.sch.wires=[];P.sch.labels=[];P.sch.power=[];ssel=null;P.nets=keep;
schAutoWires();
if(window.schReverted){ P.sch=JSON.parse(before); P.nets=keep; schDerive(); changed(); drawSch(); } // 실패하면 다시 배선 전 모습 그대로
}
// ───────────── 프로젝트: 사용자 작업 폴더에 서버 저장 ─────────────
// 서버: <사용자 작업 폴더>/pcb/<이름>/project.json (+ gcode/). 이름을 정하면 편집·배선 때마다 자동 저장된다.
// 브라우저 localStorage 는 그대로 보조 저장(오프라인·새로고침 복구)으로 둔다.
let projDirty=false, psaveTimer=null, pconflict=false, srvSuppress=false;
const NAME_BAD=/[\\/:*?"<>|\x00-\x1f]/;
const okName=n=>n&&n===n.trim()&&n.length<=60&&!NAME_BAD.test(n)&&!n.startsWith('.');
const clock=()=>new Date().toTimeString().slice(0,8);
function setPstatus(h){const e=$('psave');if(e)e.innerHTML=h;}
function projState(){
if(!P) return;
if(!P.name){ setPstatus(P.parts.length?'<span class="warn">이 브라우저에만 저장됨 — 이름을 입력하면 서버에 저장</span>':''); return; }
if(pconflict) return;
setPstatus(projDirty?'<span class="warn">● 저장 대기…</span>':`<span class="ok">☁ 서버에 저장됨 ${P.rev?new Date(P.rev).toTimeString().slice(0,8):''}</span>`);
}
function serializable(){const {fps,rev,name,...rest}=P;return {...rest,routed:routed||null,routedKey:routed?pcbKey():null};}
function serverSaveSoon(){
if(!P||!P.name||pconflict||srvSuppress) return;
projDirty=true; projState(); clearTimeout(psaveTimer); psaveTimer=setTimeout(()=>serverSave(false),1500);
}
async function serverSave(force){
if(!P||!P.name) return false; clearTimeout(psaveTimer);
const name=P.name;
try{
setPstatus('<span class="warn">저장 중…</span>');
const d=await api('/api/pcb/projects/'+encodeURIComponent(name),{project:serializable(),baseUpdated:force?undefined:P.rev,force:!!force},'PUT');
if(P.name!==name) return false;
P.rev=d.updated; projDirty=false; pconflict=false; try{localStorage.setItem('pcb-project',JSON.stringify({...P,routed:routed||null,routedKey:routed?pcbKey():null,dirty:false}));}catch(e){}
projState(); return true;
}catch(e){
if(e.status===409){ pconflict=true; setPstatus('<span class="bad">⚠ 다른 곳에서 수정됨</span> <button class="btn" style="padding:1px 7px" onclick="conflictLoad()">서버 것 불러오기</button> <button class="btn" style="padding:1px 7px" onclick="conflictForce()">내 것으로 덮어쓰기</button>'); return false; }
setPstatus(`<span class="bad">서버 저장 실패</span> (이 브라우저에는 저장됨): ${esc(e.message)}`); return false;
}
}
async function conflictLoad(){pconflict=false;await openProject(P.name,true);}
async function conflictForce(){pconflict=false;await serverSave(true);}
async function renameProject(v){
v=(v||'').trim();
if(!v){ $('pname').value=P.name||''; return; }
if(!okName(v)){ alert('프로젝트 이름은 1~60자이며 / \\ : * ? " < > | 문자와 맨 앞의 점은 쓸 수 없습니다.'); $('pname').value=P.name||''; return; }
if(v===P.name) return;
let exists=false; try{exists=(await api('/api/pcb/projects')).projects.some(x=>x.name===v);}catch(e){}
if(P.name){ // 이미 서버에 있는 프로젝트의 이름 변경
if(exists){ alert('같은 이름의 프로젝트가 이미 있습니다.'); $('pname').value=P.name; return; }
try{await api('/api/pcb/projects/'+encodeURIComponent(P.name)+'/rename',{to:v});P.name=v;try{localStorage.setItem('pcb-last',v);}catch(e){}projState();}
catch(e){ if(e.status===400&&/없습니다/.test(e.message)){P.name=v;await serverSave(true);} else {alert('이름 변경 실패: '+e.message);$('pname').value=P.name;} }
return;
}
if(exists&&!confirm(`'${v}' 프로젝트가 이미 있습니다. 지금 작업으로 덮어쓸까요?`)){ $('pname').value=''; return; }
P.name=v; P.rev=undefined; try{localStorage.setItem('pcb-last',v);}catch(e){}
await serverSave(true);
}
async function toggleProjects(){
const b=$('plistbox'); if(b.style.display==='block'){b.style.display='none';return;}
b.style.display='block'; b.innerHTML='<div class="note">불러오는 중…</div>';
try{
const {projects}=await api('/api/pcb/projects');
b.innerHTML=`<div style="display:flex;gap:6px;margin-bottom:6px"><b style="flex:1">📁 내 PCB 프로젝트 (${projects.length})</b><button class="btn" onclick="newProject(true);$('plistbox').style.display='none'">+ 새 프로젝트</button><button class="btn" onclick="$('plistbox').style.display='none'">✕</button></div>`
+(projects.map(x=>`<div class="prow"><div class="nm" onclick="openProject('${esc(x.name).replace(/'/g,'&#39;')}')"><b>${esc(x.name)}${x.name===P.name?' · 현재':''}</b><span>${new Date(x.updated).toLocaleString()} · 부품 ${x.parts} · 넷 ${x.nets}${x.routed?' · 배선됨':''}${x.gcode?' · G-code':''}</span></div><button class="btn" title="휴지통으로" onclick="deleteProject('${esc(x.name).replace(/'/g,'&#39;')}')">🗑</button></div>`).join('')||'<div class="note">아직 저장된 프로젝트가 없습니다. 이름을 입력하면 저장됩니다.</div>')
+'<div class="note" style="margin-top:6px">저장 위치: 사용자 작업 폴더 / pcb / &lt;이름&gt; / project.json, gcode/</div>';
}catch(e){b.innerHTML=`<div class="note bad">${esc(e.message)}</div>`;}
}
async function openProject(name,silent){
if(!silent&&P&&P.name&&projDirty&&!confirm('저장되지 않은 변경이 있습니다. 그래도 다른 프로젝트를 열까요?')) return;
try{const d=await api('/api/pcb/projects/'+encodeURIComponent(name)); applyProject(d.project,name,d.updated); $('plistbox').style.display='none';}
catch(e){alert('불러오기 실패: '+e.message);}
}
// ── 회로 설명(README.md) 탭 ──
let descDirty=false, descText='', descEditing=false;
function mdInline(t){
t=esc(t); const codes=[]; t=t.replace(/`([^`]+)`/g,(m,c)=>{codes.push(c);return '\x00'+(codes.length-1)+'\x00';});
t=t.replace(/\*\*([^*]+)\*\*/g,'<b>$1</b>').replace(/(^|[^*])\*([^*\s][^*]*)\*/g,'$1<i>$2</i>');
return t.replace(/\x00(\d+)\x00/g,(m,i)=>'<code>'+codes[+i]+'</code>');
}
function mdRender(src){
const L=String(src||'').replace(/\r/g,'').split('\n'), out=[]; let i=0;
while(i<L.length){
const l=L[i];
if(/^```/.test(l)){const b=[];i++;while(i<L.length&&!/^```/.test(L[i]))b.push(L[i++]);i++;out.push('<pre><code>'+esc(b.join('\n'))+'</code></pre>');continue;}
let m=l.match(/^(#{1,4})\s+(.*)$/); if(m){out.push(`<h${m[1].length}>${mdInline(m[2])}</h${m[1].length}>`);i++;continue;}
if(/^\s*([-*_])\1{2,}\s*$/.test(l)){out.push('<hr>');i++;continue;}
if(/^>\s?/.test(l)){const b=[];while(i<L.length&&/^>\s?/.test(L[i]))b.push(L[i++].replace(/^>\s?/,''));out.push('<blockquote>'+b.map(mdInline).join('<br>')+'</blockquote>');continue;}
if(/^\|.*\|\s*$/.test(l)&&i+1<L.length&&/^\|?\s*:?-{2,}/.test(L[i+1])){
const row=r=>r.replace(/^\||\|\s*$/g,'').split('|').map(c=>c.trim()), head=row(l); i+=2; const body=[];
while(i<L.length&&/^\|.*\|\s*$/.test(L[i]))body.push(row(L[i++]));
out.push('<table><tr>'+head.map(c=>'<th>'+mdInline(c)+'</th>').join('')+'</tr>'+body.map(r=>'<tr>'+r.map(c=>'<td>'+mdInline(c)+'</td>').join('')+'</tr>').join('')+'</table>');continue;}
if(/^\s*([-*]|\d+\.)\s+/.test(l)){const ord=/^\s*\d+\./.test(l),b=[];while(i<L.length&&/^\s*([-*]|\d+\.)\s+/.test(L[i]))b.push(L[i++].replace(/^\s*([-*]|\d+\.)\s+/,''));out.push((ord?'<ol>':'<ul>')+b.map(x=>'<li>'+mdInline(x)+'</li>').join('')+(ord?'</ol>':'</ul>'));continue;}
if(!l.trim()){i++;continue;}
const b=[];while(i<L.length&&L[i].trim()&&!/^(```|#{1,4}\s|>|\s*([-*]|\d+\.)\s|\|.*\|\s*$)/.test(L[i]))b.push(L[i++]);
out.push('<p>'+b.map(mdInline).join('<br>')+'</p>');
}
return out.join('\n');
}
function descShow(){
const v=$('desc-view'),ta=$('desc-ta'); v.style.display=descEditing?'none':'block'; ta.style.display=descEditing?'block':'none';
$('desc-edit').textContent=descEditing?'👁 보기':'✏ 편집'; $('desc-save').style.display=descEditing?'':'none';
if(!descEditing) v.innerHTML=descText.trim()?mdRender(descText):'<p style="color:var(--muted)">아직 회로 설명이 없습니다. <b>📋 초안 만들기</b>로 부품표와 연결 목록이 든 초안을 만들거나, <b>✏ 편집</b>으로 직접 쓰세요. 콘솔의 Claude에게 "회로 설명을 README.md에 써 줘"라고 해도 됩니다.</p>';
}
async function openDesc(force){
$('desc-title').textContent=P&&P.name?'📝 '+P.name+' — README.md':'📝 회로 설명';
if(descDirty&&!force){descShow();return;}
if(!P||!P.name){ descText=P&&P.note?String(P.note):''; descDirty=false; descEditing=false; descShow(); $('desc-status').textContent=P&&P.note?'(예제 설명 — 프로젝트 이름을 입력하면 README.md로 저장할 수 있습니다)':'프로젝트 이름을 입력하면 설명을 서버에 저장할 수 있습니다'; return; }
try{ const d=await api('/api/pcb/projects/'+encodeURIComponent(P.name)+'/readme'); descText=d.text; $('desc-status').textContent=''; }
catch(e){ descText=''; $('desc-status').textContent=e.status===404?'':'불러오기 실패: '+e.message; }
descDirty=false; if(descEditing) $('desc-ta').value=descText; descShow();
}
function descToggle(){ descEditing=!descEditing; if(descEditing){$('desc-ta').value=descText;} else if(descDirty){descText=$('desc-ta').value;} descShow(); }
async function descSave(silent){
if(descEditing) descText=$('desc-ta').value;
if(!P||!P.name){ if(!silent) alert('프로젝트 이름을 먼저 입력하세요(설명은 프로젝트 폴더의 README.md로 저장됩니다).'); return; }
if(!projDirty&&!P.rev) await serverSave(false); // 폴더가 없으면 만든다
try{ await api('/api/pcb/projects/'+encodeURIComponent(P.name)+'/readme',{text:descText},'PUT'); descDirty=false; $('desc-status').textContent='💾 저장됨 '+new Date().toLocaleTimeString('ko-KR',{hour12:false}); if(!silent) { descEditing=false; descShow(); } }
catch(e){ $('desc-status').innerHTML='<span class="warn">저장 실패: '+esc(e.message)+'</span>'; }
}
function descDraft(){
if(!P||!P.parts.length){alert('부품이 없습니다.');return;}
if(descText.trim()&&!confirm('지금 설명을 초안으로 바꿉니다. 계속할까요? (취소하면 그대로)')) return;
const by={}; for(const p of P.parts){const k=(p.value||'')+'|'+p.fp; (by[k]=by[k]||{value:p.value||'-',fp:p.fp.replace(/^kicad:[^:]+:/,''),refs:[]}).refs.push(p.ref);}
const rows=Object.values(by).sort((a,b)=>a.refs[0].localeCompare(b.refs[0],'ko',{numeric:true}));
const nets=P.nets.slice().sort((a,b)=>b.pins.length-a.pins.length);
const t=`# ${P.name||'회로'} — 회로 설명\n\n> 부품 ${P.parts.length}개 · 연결(넷) ${P.nets.length}개 · 기판 ${P.board.w}×${P.board.h}mm (${P.rules.layers===1?'단면 '+P.rules.copper:'양면'})\n\n## 개요\n(무엇을 하는 회로인지, 입력·출력 사양을 적으세요)\n\n## 동작 원리\n(신호 흐름 순서로: 입력 → … → 출력)\n\n## 부품표\n| 부품 | 값 | 풋프린트 |\n|---|---|---|\n${rows.map(r=>`| ${r.refs.join(', ')} | ${r.value} | ${r.fp} |`).join('\n')}\n\n## 연결(넷)\n${nets.map(n=>`- **${n.name}** (${n.pins.length}핀): ${n.pins.join(', ')}`).join('\n')}\n\n## 조립·시운전 주의\n- (납땜 순서, 전원 투입 전 확인 사항, 안전 주의 등)\n`;
descText=t; descDirty=true; descEditing=true; $('desc-ta').value=t; descShow(); $('desc-status').textContent='초안을 넣었습니다 — 고쳐 쓰고 💾 저장';
}
// ── 작업실 연결 + 콘솔 ──
let wsList=null;
async function loadWsList(){
if(wsList) return wsList;
try{const d=await api('/api/workshop/data'); wsList=(d.projects||[]).filter(p=>!p.archived).map(p=>({id:p.id,name:p.name}));}catch(e){wsList=[];}
return wsList;
}
async function syncWsel(){
const sel=$('wsel'); if(!sel) return; const list=await loadWsList(); const cur=(P&&P.workshopId)||'';
sel.innerHTML='<option value="">작업실 연결 없음</option>'+list.map(p=>`<option value="${esc(p.id)}">🛠 ${esc(p.name)}</option>`).join('')+(cur&&!list.some(p=>p.id===cur)?`<option value="${esc(cur)}">${esc(cur)} (없음)</option>`:'');
sel.value=cur;
}
function setWorkshop(id){
if(!P) return; P.workshopId=id||'';
if(!P.name){ setPstatus('<span class="warn">프로젝트 이름을 먼저 입력하세요(이름이 있어야 작업실로 복사됩니다)</span>'); return; }
projDirty=true; serverSave(false).then(()=>{ if(id) setPstatus('<span class="ok">작업실 프로젝트의 PCB/'+esc(P.name)+'/ 로 복사했습니다</span>'); });
}
function currentProject(){ return P&&P.name?{id:P.name,name:P.name,pcb:true}:null; }
async function openPcbConsole(){
if(!P||!P.name||projDirty||pconflict){
if(P&&P.name&&projDirty&&!pconflict){ await serverSave(false); }
}
if(!P||!P.name){ $('console-proj').textContent='프로젝트 이름을 먼저 입력하세요(서버에 저장된 프로젝트 폴더에서 실행됩니다)'; }
if(typeof openConsole!=='function'){
await new Promise((ok,no)=>{const sc=document.createElement('script');sc.src='../js/app/workshop-console.js';sc.onload=ok;sc.onerror=()=>no(new Error('콘솔 스크립트 로드 실패'));document.head.appendChild(sc);}).catch(e=>{$('console-status').textContent=e.message;});
}
if(typeof openConsole==='function') await openConsole();
}
function applyProject(pr,name,rev){
srvSuppress=true;
P={board:pr.board,parts:pr.parts,nets:pr.nets||[],fps:{},sch:pr.sch,sim:pr.sim,rules:{...DEF_RULES,...(pr.rules||{})},mill:{...DEF_MILL,...(pr.mill||{})},workshopId:pr.workshopId||'',name,rev};
routed=null; if(pr.routed&&pr.routedKey&&pr.routedKey===pcbKey()){routed=pr.routed;routedCache={key:pr.routedKey,routed};}
gres=null;sel=null;pending=null;ssel=null;simRes=null;$('simpane').style.display='none';histReset();pconflict=false;projDirty=false;
$('pname').value=name; try{localStorage.setItem('pcb-last',name);}catch(e){}
syncWsel();
registerFps(); syncUI(); fitView(); changed(true); ensureSch(); ensurePlaced(); if(tab==='sch'){schDerive();schFit();}
srvSuppress=false; projDirty=false; projState();
}
async function deleteProject(name){
if(!confirm(`'${name}' 프로젝트를 휴지통으로 옮길까요? (작업 폴더의 pcb/.trash/ 에 보관됩니다)`)) return;
try{await api('/api/pcb/projects/'+encodeURIComponent(name),null,'DELETE'); if(P.name===name){P.name='';$('pname').value='';projDirty=false;projState();} toggleProjects();toggleProjects();}
catch(e){alert('삭제 실패: '+e.message);}
}
// 시작 시 서버 프로젝트와 맞춘다: ?p=이름 또는 마지막으로 연 프로젝트
async function reconcileProject(saved){
let want=''; try{want=new URLSearchParams(location.search).get('p')||''; if(!want)want=(saved&&saved.name)||'';}catch(e){}
if(!want) return;
try{
const d=await api('/api/pcb/projects/'+encodeURIComponent(want));
const localSame=saved&&saved.name===want;
if(localSame&&saved.dirty){
if(saved.rev===d.updated){ P.name=want; P.rev=d.updated; projDirty=true; $('pname').value=want; serverSaveSoon(); return; } // 서버는 그대로, 이 브라우저에만 반영 안 된 편집 → 올린다
if(confirm(`'${want}' 프로젝트가 이 브라우저와 서버에서 모두 바뀌었습니다.\n확인 = 이 브라우저의 작업 유지(서버 덮어쓰기)\n취소 = 서버 버전 불러오기`)){ P.name=want; P.rev=d.updated; projDirty=true; $('pname').value=want; await serverSave(true); return; }
}
applyProject(d.project,want,d.updated);
}catch(e){
if(e.status===404&&saved&&saved.name===want){ P.name=want; P.rev=undefined; $('pname').value=want; projDirty=true; serverSaveSoon(); } // 서버에서 사라졌다면 이 브라우저 본으로 복구
else if(saved&&saved.name===want){ P.name=want; $('pname').value=want; setPstatus('<span class="warn">서버에 연결할 수 없어 이 브라우저의 저장본을 씁니다</span>'); }
}
}
// ───────────── 시작 ─────────────
(async function init(){
try{FP=(await api('/api/pcb/footprints')).footprints;FPM=Object.fromEntries(FP.map(f=>[f.id,f]));}catch(e){$('lib').innerHTML=`<div class="note bad">${esc(e.message)}</div>`;}
try{const s=await api('/api/pcb/status');$('fr').innerHTML=s.installed&&s.java?`<span class="ok">● Freerouting 준비됨</span> (Java ${esc(s.java)})`:`<span class="bad">● Freerouting 미설치</span> — scripts/install-freerouting.sh`;}catch(e){$('fr').textContent='';}
let saved=null;try{saved=JSON.parse(localStorage.getItem('pcb-project')||'null');}catch(e){}
// 작업실 PCB 탭이 ?ws=<작업실 프로젝트id>만 넘기면(연결된 PCB 없음) 마지막으로 연 PCB를 열지 않고 빈 PCB로 시작 — 다른 프로젝트의 PCB가 뜨던 문제(2026-11-11).
// 저장 안 된 편집(dirty)이 있으면 날리지 않도록 기존 동작(마지막 PCB 복구)을 따른다.
let wsNew='';try{const u=new URLSearchParams(location.search);if(u.get('ws')&&!u.get('p')&&!(saved&&saved.dirty)){wsNew=u.get('ws');saved=null;}}catch(e){}
if(saved&&saved.board&&saved.parts){P={board:saved.board,parts:saved.parts,nets:saved.nets||[],fps:saved.fps||{},workshopId:saved.workshopId||'',name:saved.name||'',rev:saved.rev,sch:saved.sch,sim:saved.sim,rules:{...DEF_RULES,...(saved.rules||{})},mill:{...DEF_MILL,...(saved.mill||{})}};syncUI();renderNets();updSel();registerFps();if(saved.routed&&saved.routedKey&&saved.routedKey===pcbKey()){routed=saved.routed;routedCache={key:saved.routedKey,routed};}}
else newProject(false);
try{const k=await api('/api/pcb/kicad/status');$('kst').innerHTML=k.installed?`<span class="ok">● ${k.footprints.toLocaleString()} 풋프린트 · ${k.symbols.toLocaleString()} 심볼</span>`:'<span class="bad">미설치</span>';}catch(e){}
if(wsNew)P.workshopId=wsNew;
$('pname').value=P.name||'';projDirty=!!(saved&&saved.dirty&&saved.name===P.name);
await reconcileProject(saved);
syncWsel();
renderLib();setMode('select');renderSim();resize();fitView();millRefresh();ensureSch();ensurePlaced();histReset();histPush();projState();
let t0='sch'; try{t0=localStorage.getItem('pcb-tab')||'sch';}catch(e){} if(!['sch','pcb','desc'].includes(t0)) t0='sch'; setTab(t0); // 회로도가 맨 왼쪽·기본 탭 (마지막에 보던 탭을 기억, 콘솔은 자동으로 안 연다)
})();
</script>
</body>
</html>