aicommunicator 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +55 -0
- package/README.md +93 -2
- package/bin/aic.js +20427 -0
- package/host-ui/host.js +5151 -0
- package/host-ui/index.html +483 -0
- package/host-ui/lang-en.js +631 -0
- package/package.json +30 -4
- package/plugin-guide.md +997 -0
- package/plugins/plugin-animation/LICENSE +55 -0
- package/plugins/plugin-animation/dist/logic.js +2225 -0
- package/plugins/plugin-animation/docs/manual.md +217 -0
- package/plugins/plugin-animation/manifest.json +31 -0
- package/plugins/plugin-animation/ui/icon.svg +6 -0
- package/plugins/plugin-animation/ui/index.html +2266 -0
- package/plugins/plugin-html-design/LICENSE +55 -0
- package/plugins/plugin-html-design/dist/logic.js +972 -0
- package/plugins/plugin-html-design/docs/manual.md +100 -0
- package/plugins/plugin-html-design/manifest.json +39 -0
- package/plugins/plugin-html-design/samples/exhibition-page.json +570 -0
- package/plugins/plugin-html-design/ui/icon.svg +5 -0
- package/plugins/plugin-html-design/ui/index.html +1241 -0
- package/plugins/plugin-html-slides/LICENSE +55 -0
- package/plugins/plugin-html-slides/dist/logic.js +1323 -0
- package/plugins/plugin-html-slides/docs/manual.md +121 -0
- package/plugins/plugin-html-slides/manifest.json +39 -0
- package/plugins/plugin-html-slides/samples/first-week-lecture.json +1129 -0
- package/plugins/plugin-html-slides/ui/icon.svg +5 -0
- package/plugins/plugin-html-slides/ui/index.html +1349 -0
- package/plugins/plugin-mindmap/LICENSE +55 -0
- package/plugins/plugin-mindmap/dist/logic.js +966 -0
- package/plugins/plugin-mindmap/docs/manual.md +145 -0
- package/plugins/plugin-mindmap/manifest.json +39 -0
- package/plugins/plugin-mindmap/samples/book-club.json +480 -0
- package/plugins/plugin-mindmap/ui/icon.svg +5 -0
- package/plugins/plugin-mindmap/ui/index.html +1774 -0
- package/plugins/plugin-plan/LICENSE +55 -0
- package/plugins/plugin-plan/dist/logic.js +1029 -0
- package/plugins/plugin-plan/docs/manual.md +261 -0
- package/plugins/plugin-plan/manifest.json +51 -0
- package/plugins/plugin-plan/samples/kimchi-day.json +1514 -0
- package/plugins/plugin-plan/samples/meeting-outline.json +653 -0
- package/plugins/plugin-plan/samples/reading-class.json +1577 -0
- package/plugins/plugin-plan/ui/icon.svg +7 -0
- package/plugins/plugin-plan/ui/index.html +1523 -0
- package/plugins/plugin-png/LICENSE +55 -0
- package/plugins/plugin-png/dist/logic.js +1758 -0
- package/plugins/plugin-png/docs/manual.md +344 -0
- package/plugins/plugin-png/manifest.json +35 -0
- package/plugins/plugin-png/ui/icon.svg +5 -0
- package/plugins/plugin-png/ui/index.html +2885 -0
- package/plugins/plugin-process-log/LICENSE +55 -0
- package/plugins/plugin-process-log/dist/logic.js +406 -0
- package/plugins/plugin-process-log/docs/manual.md +131 -0
- package/plugins/plugin-process-log/manifest.json +43 -0
- package/plugins/plugin-process-log/samples/design-decisions.json +241 -0
- package/plugins/plugin-process-log/ui/icon.svg +7 -0
- package/plugins/plugin-process-log/ui/index.html +721 -0
- package/plugins/plugin-story/LICENSE +55 -0
- package/plugins/plugin-story/dist/logic.js +2201 -0
- package/plugins/plugin-story/docs/manual.md +428 -0
- package/plugins/plugin-story/manifest.json +49 -0
- package/plugins/plugin-story/samples/scene-body.json +758 -0
- package/plugins/plugin-story/samples/time-and-groups.json +989 -0
- package/plugins/plugin-story/ui/icon.svg +4 -0
- package/plugins/plugin-story/ui/index.html +2783 -0
- package/plugins/plugin-svg/LICENSE +55 -0
- package/plugins/plugin-svg/dist/logic.js +2150 -0
- package/plugins/plugin-svg/docs/manual.md +314 -0
- package/plugins/plugin-svg/manifest.json +45 -0
- package/plugins/plugin-svg/samples/rocket-icon.json +1305 -0
- package/plugins/plugin-svg/samples/yard-cat.json +7796 -0
- package/plugins/plugin-svg/ui/icon.svg +4 -0
- package/plugins/plugin-svg/ui/index.html +2017 -0
- package/plugins/plugin-tree/LICENSE +55 -0
- package/plugins/plugin-tree/dist/logic.js +505 -0
- package/plugins/plugin-tree/docs/manual.md +140 -0
- package/plugins/plugin-tree/manifest.json +45 -0
- package/plugins/plugin-tree/samples/book-club.json +473 -0
- package/plugins/plugin-tree/samples/sort-memos.json +604 -0
- package/plugins/plugin-tree/ui/icon.svg +7 -0
- package/plugins/plugin-tree/ui/index.html +1305 -0
- package/schema/aic_describe.input.json +11 -0
- package/schema/aic_describe.output.json +67 -0
- package/schema/aic_observe.input.json +14 -0
- package/schema/aic_observe.output.json +47 -0
- package/schema/aic_send.input.json +15 -0
- package/schema/aic_send.output.json +38 -0
- package/schema/aic_update.input.json +19 -0
- package/schema/aic_update.output.json +39 -0
- package/schema/common.json +127 -0
- package/template/plugin/LICENSE +55 -0
- package/template/plugin/README.md +27 -0
- package/template/plugin/docs/manual.md +31 -0
- package/template/plugin/logic.js +337 -0
- package/template/plugin/manifest.json +27 -0
- package/template/plugin/ui/icon.svg +4 -0
- package/template/plugin/ui/index.html +269 -0
|
@@ -0,0 +1,2885 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8">
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
6
|
+
<title>PNG Image</title>
|
|
7
|
+
<style>
|
|
8
|
+
:root {
|
|
9
|
+
color-scheme: light dark;
|
|
10
|
+
--bg: #f5f5f2; --panel: #ffffff; --text: #1f2328; --muted: #5f6771; --line: #dcdfe3; --soft: #f0f1f3;
|
|
11
|
+
--accent: #1f6a8c; --accent-text: #ffffff; --del: #a8321f; --add: #1d7a46; --warn: #c25e00;
|
|
12
|
+
--check-a: #ffffff; --check-b: #e4e7eb;
|
|
13
|
+
--halo: rgba(255, 255, 255, .9); --sel: #1f6a8c; --sel-fill: rgba(31, 106, 140, .12); --region: #8a4bb3;
|
|
14
|
+
}
|
|
15
|
+
@media (prefers-color-scheme: dark) {
|
|
16
|
+
:root {
|
|
17
|
+
--bg: #191b1e; --panel: #22252a; --text: #e6e8eb; --muted: #a0a8b2; --line: #383d44; --soft: #2b2f35;
|
|
18
|
+
--accent: #7cc0dd; --accent-text: #10222b; --del: #f1a597; --add: #7bd6a0; --warn: #ffb066;
|
|
19
|
+
--check-a: #3a3f46; --check-b: #30343a;
|
|
20
|
+
--halo: rgba(17, 19, 22, .88); --sel: #7cc0dd; --sel-fill: rgba(124, 192, 221, .14); --region: #d3a6f0;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
* { box-sizing: border-box; }
|
|
24
|
+
html, body { height: 100%; }
|
|
25
|
+
body { margin: 0; background: var(--bg); color: var(--text); font: 14px/1.55 system-ui, "Malgun Gothic", sans-serif; display: flex; flex-direction: column; }
|
|
26
|
+
button { font: inherit; color: inherit; cursor: pointer; }
|
|
27
|
+
button:focus-visible, select:focus-visible, textarea:focus-visible, input:focus-visible, #stage:focus-visible, #drop:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
|
|
28
|
+
.btn { white-space: nowrap; background: transparent; border: 1px solid var(--line); border-radius: 5px; padding: 2px 9px; font-size: 13px; }
|
|
29
|
+
.btn:hover { background: var(--soft); }
|
|
30
|
+
.btn[aria-pressed="true"] { background: var(--accent); border-color: var(--accent); color: var(--accent-text); }
|
|
31
|
+
.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-text); }
|
|
32
|
+
.btn.small { padding: 0 6px; font-size: 12px; }
|
|
33
|
+
.btn[disabled] { opacity: .5; cursor: default; }
|
|
34
|
+
|
|
35
|
+
/* 위쪽 줄은 아이콘 한 줄이다. 이름은 title 과 aria-label 에 두고, 늘 보일 필요가 없는 것(고르기의 세부, 저장)은 메뉴에 둔다 */
|
|
36
|
+
#bar { flex: none; position: relative; z-index: 5; display: flex; flex-wrap: wrap; gap: 4px 12px; align-items: center; padding: 4px 8px; background: var(--panel); border-bottom: 1px solid var(--line); }
|
|
37
|
+
.group { display: flex; gap: 4px; align-items: center; flex-wrap: wrap; }
|
|
38
|
+
.cap { color: var(--muted); font-size: 12px; margin-right: 2px; }
|
|
39
|
+
.reason { color: var(--del); font-size: 12px; }
|
|
40
|
+
#bar select { width: auto; font-size: 13px; padding: 2px 4px; }
|
|
41
|
+
#bar .spacer { flex: 1; }
|
|
42
|
+
.btn.icon { width: 28px; height: 28px; padding: 0; display: inline-flex; align-items: center; justify-content: center; font-size: 15px; line-height: 1; }
|
|
43
|
+
.btn.icon svg, .btn.mini svg { width: 17px; height: 17px; fill: none; stroke: currentColor; stroke-width: 1.5; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
|
|
44
|
+
.btn.mini { width: 24px; height: 22px; padding: 0; display: inline-flex; align-items: center; justify-content: center; flex: none; }
|
|
45
|
+
.btn.mini svg { width: 15px; height: 15px; }
|
|
46
|
+
.menuBox { position: relative; display: flex; }
|
|
47
|
+
.menu { position: absolute; z-index: 20; top: calc(100% + 6px); right: 0; width: max-content; min-width: 220px; max-width: calc(100vw - 16px); display: grid; gap: 8px; padding: 10px 12px; background: var(--panel); border: 1px solid var(--line); border-radius: 8px; box-shadow: 0 6px 20px rgba(0, 0, 0, .2); }
|
|
48
|
+
.menu h2 { font-size: 12px; color: var(--muted); margin: 0; font-weight: 600; }
|
|
49
|
+
.menu .group { flex-wrap: nowrap; }
|
|
50
|
+
.menu .cap { white-space: nowrap; }
|
|
51
|
+
.swatch { display: inline-flex; align-items: center; gap: 4px; font-size: 13px; white-space: nowrap; }
|
|
52
|
+
.zoom { min-width: 3.6em; text-align: center; font-size: 12px; font-variant-numeric: tabular-nums; }
|
|
53
|
+
input.num { width: 4.6em; }
|
|
54
|
+
#tolRange { width: 120px; }
|
|
55
|
+
|
|
56
|
+
/* 그림이 화면을 넓게 쓴다. 오른쪽 칸은 숨긴 채 시작하고 위쪽 줄의 버튼으로 연다 */
|
|
57
|
+
#main { flex: 1; min-height: 0; display: grid; grid-template-columns: minmax(0, 1fr); gap: 8px; padding: 8px; }
|
|
58
|
+
#main[data-side="open"] { grid-template-columns: minmax(0, 1fr) 330px; }
|
|
59
|
+
#stageBox { min-width: 0; min-height: 0; display: flex; flex-direction: column; overflow: auto; }
|
|
60
|
+
#stageWrap { position: relative; flex: 1; min-height: 240px; display: flex; flex-direction: column; }
|
|
61
|
+
/* 그림 칸. 그림은 #paper 안의 SVG(#drawing)이고, 고른 곳은 같은 크기로 겹친 canvas(#selCanvas), 테두리와 이름표는 화면 픽셀 단위의 svg(#overlay)다 */
|
|
62
|
+
#stage { position: relative; flex: 1; min-height: 0; overflow: hidden; background: var(--soft); border: 1px solid var(--line); border-radius: 8px; touch-action: none; user-select: none; -webkit-user-select: none; }
|
|
63
|
+
#stage[data-tool="rect"], #stage[data-tool="ellipse"], #stage[data-tool="lasso"], #stage[data-tool="wand"] { cursor: crosshair; }
|
|
64
|
+
#stage[data-tool="pan"], #stage.panning { cursor: grab; }
|
|
65
|
+
#stage.dragging { cursor: grabbing; }
|
|
66
|
+
/* 투명한 곳이 보이게 바둑판 무늬 위에 그린다 */
|
|
67
|
+
#paper { position: absolute; left: 0; top: 0; background-color: var(--check-a); background-image: linear-gradient(45deg, var(--check-b) 25%, transparent 25%, transparent 75%, var(--check-b) 75%), linear-gradient(45deg, var(--check-b) 25%, transparent 25%, transparent 75%, var(--check-b) 75%); background-size: 16px 16px; background-position: 0 0, 8px 8px; box-shadow: 0 0 0 1px var(--line), 0 2px 10px rgba(0, 0, 0, .14); }
|
|
68
|
+
#drawing { display: block; width: 100%; height: 100%; overflow: hidden; }
|
|
69
|
+
/* 크게 확대하면 픽셀이 흐려지지 않고 네모로 보이게 한다 */
|
|
70
|
+
#paper.px #drawing { image-rendering: pixelated; }
|
|
71
|
+
#selCanvas { position: absolute; left: 0; top: 0; width: 100%; height: 100%; pointer-events: none; image-rendering: pixelated; }
|
|
72
|
+
#overlay { position: absolute; left: 0; top: 0; width: 100%; height: 100%; pointer-events: none; overflow: visible; }
|
|
73
|
+
.ov-sel { fill: none; stroke: var(--sel); stroke-width: 2; }
|
|
74
|
+
.ov-area { fill: none; stroke: var(--sel); stroke-width: 1.5; stroke-dasharray: 5 3; }
|
|
75
|
+
/* 고른 곳의 가장자리. 픽셀 경계를 따라 굵은 흰 선 위에 가는 검은 점선을 겹쳐 밝은 그림과 어두운 그림 위에서 모두 보이고,
|
|
76
|
+
확대해도 같은 화면 픽셀 굵기다. 줄이면 토막이 짧아 검은 선이 이어져 보이므로 흰 선을 더 굵게 해 양옆에 밝은 테두리가 남게 한다 */
|
|
77
|
+
.ov-ants { fill: none; vector-effect: non-scaling-stroke; }
|
|
78
|
+
.ov-ants.a { stroke: #fff; stroke-width: 3; }
|
|
79
|
+
.ov-ants.b { stroke: #000; stroke-width: 1.2; stroke-dasharray: 4 4; }
|
|
80
|
+
.ov-rubber { fill: var(--sel-fill); stroke: var(--sel); stroke-width: 1.5; stroke-dasharray: 5 3; }
|
|
81
|
+
.ov-region { fill: none; stroke: var(--region); stroke-width: 1.5; stroke-dasharray: 2 3; }
|
|
82
|
+
.ov-mark { fill: none; stroke: var(--sel); stroke-width: 2; }
|
|
83
|
+
.ov-name { font: 600 12px/1 system-ui, "Malgun Gothic", sans-serif; paint-order: stroke; stroke: var(--halo); stroke-width: 3px; stroke-linejoin: round; fill: var(--sel); }
|
|
84
|
+
.ov-name.region { fill: var(--region); }
|
|
85
|
+
.note { color: var(--muted); font-size: 12px; margin: 6px 0 0; }
|
|
86
|
+
/* 고른 뒤에 뜨는 칸. 고른 것이 있을 때만 그림 칸 위에 떠서 보인다. 그림 칸의 크기를 바꾸지 않으려는 것이다(크기가 바뀌면 그림이
|
|
87
|
+
다시 맞춰져 같은 곳을 다시 누를 때 다른 곳이 눌린다). 눈에 먼저 들어오게 보통 위(아이콘 줄 바로 아래)에 뜨고, 고른 것이 위쪽에 있어
|
|
88
|
+
가려지면 아래에 뜬다(data-at, rawdev 2026-11-25 "가능하면 상단에 둬") */
|
|
89
|
+
#talkBar { position: absolute; z-index: 3; left: 10px; right: 10px; top: 10px; max-width: 780px; margin: 0 auto; background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 8px 10px; box-shadow: 0 4px 16px rgba(0, 0, 0, .2); display: grid; gap: 6px; }
|
|
90
|
+
#talkBar[data-at="bottom"] { top: auto; bottom: 10px; }
|
|
91
|
+
#talkBar.unsent { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent), 0 4px 16px rgba(0, 0, 0, .2); }
|
|
92
|
+
#talkBar .state { margin: 0; font-size: 13px; overflow-wrap: anywhere; }
|
|
93
|
+
#talkBar .state b { font-weight: 600; }
|
|
94
|
+
#talkBar .state .warn { color: var(--warn); font-weight: 600; }
|
|
95
|
+
#talkBar .state .done { color: var(--add); font-weight: 600; }
|
|
96
|
+
#talkBar .line { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; }
|
|
97
|
+
#talkBar .line select { width: auto; flex: none; }
|
|
98
|
+
#talkBar .line input[type=text] { flex: 1; min-width: 160px; padding: 5px 8px; }
|
|
99
|
+
#talkBar .line .btn { flex: none; padding: 4px 11px; font-size: 13px; }
|
|
100
|
+
#talkBar .line .btn.primary { padding: 5px 14px; font-size: 14px; }
|
|
101
|
+
#talkBar .line .btn.icon { padding: 0; }
|
|
102
|
+
|
|
103
|
+
#side { min-height: 0; overflow: auto; }
|
|
104
|
+
aside section { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 10px 12px; margin-bottom: 12px; }
|
|
105
|
+
aside h2 { font-size: 13px; color: var(--muted); margin: 0 0 6px; font-weight: 600; }
|
|
106
|
+
aside p { margin: 4px 0; }
|
|
107
|
+
.kv { display: grid; grid-template-columns: auto 1fr; gap: 2px 8px; font-size: 13px; margin: 0; }
|
|
108
|
+
.kv dt { color: var(--muted); }
|
|
109
|
+
.kv dd { margin: 0; overflow-wrap: anywhere; }
|
|
110
|
+
.form { display: grid; gap: 6px; margin-top: 6px; }
|
|
111
|
+
.form label > span { display: block; color: var(--muted); font-size: 12px; }
|
|
112
|
+
.row2 { display: grid; grid-template-columns: 1fr 1fr; gap: 6px; }
|
|
113
|
+
.inline { display: flex; gap: 6px; align-items: center; }
|
|
114
|
+
.inline input[type=text] { flex: 1; min-width: 0; }
|
|
115
|
+
textarea, input[type=text], input[type=number], select { font: inherit; color: inherit; background: var(--panel); border: 1px solid var(--line); border-radius: 5px; padding: 3px 6px; width: 100%; }
|
|
116
|
+
.slider { display: grid; grid-template-columns: 5.2em 1fr 3.4em; gap: 6px; align-items: center; font-size: 13px; }
|
|
117
|
+
.slider > span:first-child { color: var(--muted); font-size: 12px; }
|
|
118
|
+
.slider input[type=range] { width: 100%; }
|
|
119
|
+
.slider .val { text-align: right; font-variant-numeric: tabular-nums; font-size: 12px; }
|
|
120
|
+
.slider input[type=color] { width: 100%; height: 24px; padding: 0 1px; border: 1px solid var(--line); border-radius: 4px; background: var(--panel); }
|
|
121
|
+
.rows { list-style: none; margin: 0; padding: 0; max-height: 320px; overflow: auto; }
|
|
122
|
+
.rows li { display: flex; gap: 3px; align-items: center; padding: 2px 0; border-top: 1px solid var(--line); }
|
|
123
|
+
.rows li:first-child { border-top: 0; }
|
|
124
|
+
.rows li.current { background: var(--accent); color: var(--accent-text); border-radius: 4px; }
|
|
125
|
+
.rows li.current .id { color: inherit; }
|
|
126
|
+
.rows .pick { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: left; background: none; border: 0; padding: 2px 4px; font-size: 13px; color: inherit; }
|
|
127
|
+
.rows .off { opacity: .55; }
|
|
128
|
+
.id { color: var(--muted); font-size: 11px; margin-left: 4px; }
|
|
129
|
+
.colors { display: flex; flex-wrap: wrap; gap: 4px 8px; font-size: 12px; }
|
|
130
|
+
.chipc { display: inline-flex; align-items: center; gap: 3px; }
|
|
131
|
+
.chipc i { width: 12px; height: 12px; border: 1px solid var(--line); border-radius: 2px; display: inline-block; }
|
|
132
|
+
.chip { border: 1px solid var(--line); background: var(--soft); border-radius: 999px; padding: 0 8px; font-size: 12px; }
|
|
133
|
+
.crumbs { display: flex; flex-wrap: wrap; gap: 4px; align-items: center; font-size: 12px; margin: 6px 0 2px; }
|
|
134
|
+
|
|
135
|
+
/* 그림이 없을 때의 큰 칸. 파일을 놓거나 누르거나 붙여 넣는다 */
|
|
136
|
+
#startView { flex: 1; overflow: auto; padding: 16px; display: flex; align-items: center; justify-content: center; }
|
|
137
|
+
#drop { width: min(720px, 100%); min-height: 320px; border: 2px dashed var(--line); border-radius: 12px; background: var(--panel); display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 10px; padding: 24px; text-align: center; cursor: pointer; }
|
|
138
|
+
#drop.over { border-color: var(--accent); background: var(--sel-fill); }
|
|
139
|
+
#drop .big { width: 56px; height: 56px; fill: none; stroke: var(--muted); stroke-width: 1.2; stroke-linecap: round; stroke-linejoin: round; }
|
|
140
|
+
#drop .lead { margin: 0; font-size: 16px; }
|
|
141
|
+
#drop .group { justify-content: center; margin-top: 6px; }
|
|
142
|
+
#drop .btn { padding: 5px 14px; font-size: 14px; }
|
|
143
|
+
.empty { color: var(--muted); font-size: 15px; }
|
|
144
|
+
|
|
145
|
+
/* 알림은 위쪽 줄 바로 아래에 뜬다. 아래에는 고른 뒤에 뜨는 칸이 있으므로 그 버튼을 덮지 않게 하고, 누르는 것은 알림을 지나간다.
|
|
146
|
+
위쪽 줄(z-index 5)보다 아래에 두어 열린 메뉴를 덮지 않는다 */
|
|
147
|
+
#toast { position: fixed; z-index: 4; left: 50%; top: 46px; transform: translateX(-50%); pointer-events: none; background: var(--text); color: var(--bg); padding: 5px 12px; border-radius: 6px; font-size: 14px; max-width: min(90vw, 640px); }
|
|
148
|
+
#toast.bad { background: var(--del); color: #fff; }
|
|
149
|
+
#error { color: var(--del); padding: 16px; }
|
|
150
|
+
[hidden] { display: none !important; }
|
|
151
|
+
@media (max-width: 900px) {
|
|
152
|
+
body { display: block; height: auto; }
|
|
153
|
+
#main { display: block; }
|
|
154
|
+
/* 좁은 화면에서는 위아래로 쌓는다. 그림 칸만 높이를 정하고, 도구 설명과 연 오른쪽 칸은 제 높이만큼 아래로 이어진다 */
|
|
155
|
+
#main[data-side="open"] { display: block; }
|
|
156
|
+
#stageBox { display: block; overflow: visible; margin-bottom: 8px; }
|
|
157
|
+
#stageWrap { display: block; min-height: 0; }
|
|
158
|
+
#stage { height: 62vh; min-height: 280px; }
|
|
159
|
+
#side { overflow: visible; }
|
|
160
|
+
#startView { min-height: 80vh; }
|
|
161
|
+
}
|
|
162
|
+
</style>
|
|
163
|
+
</head>
|
|
164
|
+
<body>
|
|
165
|
+
<div id="error" role="alert" hidden></div>
|
|
166
|
+
<header id="bar" hidden></header>
|
|
167
|
+
<div id="startView" hidden></div>
|
|
168
|
+
<main id="main" hidden>
|
|
169
|
+
<div id="stageBox">
|
|
170
|
+
<div id="stageWrap">
|
|
171
|
+
<div id="stage" tabindex="0" role="application" aria-label="Picture" data-tool="piece">
|
|
172
|
+
<div id="paper">
|
|
173
|
+
<svg id="drawing" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><defs id="imageDefs"></defs><defs id="pieceDefs"></defs><g id="pieces"></g></svg>
|
|
174
|
+
<canvas id="selCanvas" aria-hidden="true"></canvas>
|
|
175
|
+
</div>
|
|
176
|
+
<svg id="overlay" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"></svg>
|
|
177
|
+
</div>
|
|
178
|
+
<div id="talkBar" role="group" aria-label="Actions for the selection" hidden></div>
|
|
179
|
+
</div>
|
|
180
|
+
<p class="note" id="stageNote" hidden></p>
|
|
181
|
+
</div>
|
|
182
|
+
<aside id="side" aria-label="Pieces and info" hidden></aside>
|
|
183
|
+
</main>
|
|
184
|
+
<input id="filePick" type="file" accept="image/png,.png" aria-label="Choose PNG file" hidden>
|
|
185
|
+
<div id="toast" role="status" hidden></div>
|
|
186
|
+
<script>
|
|
187
|
+
'use strict';
|
|
188
|
+
// PNG 그림의 화면(plugin-design/png-editing.md 9절, 7절). 호스트와는 메시지로만 이야기한다(plugin-guide 4절).
|
|
189
|
+
// 그림은 논리와 같은 그리기 코드(src/draw.js 의 글을 아래 draw:begin 과 draw:end 사이에 그대로 넣은 것)로 SVG 를 만들어 보인다.
|
|
190
|
+
// 그래서 사람이 보는 그림과 코어가 PNG 로 저장하고 AI 가 read_image 로 보는 그림이 같다. 그림 파일과 고른 모양의 base64 는 개념
|
|
191
|
+
// 읽기에 들지 않아 범위 data:<이름> 으로 따로 받고, 내용에서 나온 이름이라 한 번 받은 것은 다시 받지 않는다(6.3절).
|
|
192
|
+
// 픽셀은 화면이 읽는다(2절). 그림 파일마다의 픽셀로 눌린 조각을 찾고, 지금 보이는 그림 전체의 픽셀로 비슷한 색을 고르고 색을 알아낸다.
|
|
193
|
+
// 고른 곳은 그림판 크기의 픽셀 표(1 이나 0)로 지니고, 조작에는 모양 그대로나 고른 모양 PNG(검정에 알파)로 보낸다(5.1절, 7.1절).
|
|
194
|
+
// 고른 조각의 테두리, 끄는 모양, 영역은 그림과 따로 둔 겹쳐 보기 층(#overlay)에 createElementNS 와 textContent 로 그린다.
|
|
195
|
+
// 사람이 화면에서 고치는 것은 모두 논리의 조작으로 바뀌어 AI 와 같은 경로로 저장된다.
|
|
196
|
+
const SELECTION_FORMAT = 'aic.png/selection-1';
|
|
197
|
+
const SVG_NS = 'http://www.w3.org/2000/svg';
|
|
198
|
+
// 도구의 이름과 고른 방법의 이름. 고른 언어를 안 뒤에 글을 만들도록 함수로 둔다
|
|
199
|
+
const TOOL_KEYS = ['piece', 'rect', 'ellipse', 'lasso', 'wand', 'pan'];
|
|
200
|
+
const toolName = (k) => ({ piece: t('Select piece'), rect: t('Rectangle'), ellipse: t('Ellipse'), lasso: t('Freehand'), wand: t('Similar colors'), pan: t('Move view') })[k];
|
|
201
|
+
const howWord = (k) => ({ rect: t('Rectangle'), ellipse: t('Ellipse'), lasso: t('Freehand'), wand: t('Similar colors'), mixed: t('Combined area') })[k];
|
|
202
|
+
// 논리가 한도를 주지 않았을 때 쓰는 값(3.3절). 보통은 읽은 JSON 의 limits 를 쓴다
|
|
203
|
+
const LIMITS = { imageBytes: 4194304, side: 4096, maskChars: 800000, pieces: 200, regions: 200, clip: 8, holes: 40, points: 400 };
|
|
204
|
+
// 그림을 넣을 때 남기는 태그. 논리와 화면이 같은 코드로 만들지만 넣기 전에 한 번 더 거른다
|
|
205
|
+
const DRAW_TAGS = new Set(['svg', 'defs', 'g', 'image', 'use', 'mask', 'rect', 'ellipse', 'polygon', 'filter', 'feColorMatrix', 'feComponentTransfer', 'feFuncR', 'feFuncG', 'feFuncB', 'feFlood', 'feComposite']);
|
|
206
|
+
const PNG_SIGN = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
|
|
207
|
+
const ZOOM_MIN = 0.01;
|
|
208
|
+
const ZOOM_MAX = 64;
|
|
209
|
+
const PIXELATED_AT = 3; // 이만큼 확대하면 픽셀을 네모로 보인다
|
|
210
|
+
const DRAG_PX = 4; // 이만큼 움직여야 누르기가 아니라 끌기다
|
|
211
|
+
const LASSO_PX = 3; // 둘러 그릴 때 이만큼(화면 픽셀) 움직일 때마다 꼭짓점을 더한다
|
|
212
|
+
const PNG_MIN = 16; // 코어가 PNG 로 만드는 가장 긴 변의 범위
|
|
213
|
+
const PNG_MAX = 4096;
|
|
214
|
+
const TALK_ZONE = 130; // 떠 있는 칸이 그림 칸의 위나 아래에서 가리는 높이(화면 픽셀)
|
|
215
|
+
const MAX_RECORDS = 200; // 코어가 받는 선택의 record 수 한도
|
|
216
|
+
const MAX_SEL_NAMES = 8; // 함께 고른 조각이 이보다 많으면 그림 위에 이름은 적지 않고 테두리만 보인다
|
|
217
|
+
const MAX_TALK_NAMES = 3;
|
|
218
|
+
const SAMPLE_MAX = 40000; // 고른 곳의 색과 보이는 조각을 알아낼 때 보는 픽셀 수의 한도(넘으면 띄엄띄엄 본다)
|
|
219
|
+
const DATA_BATCH = 3000000; // 그림 파일과 고른 모양을 한 번에 받는 base64 글자 수(반환 한도 8MB 안)
|
|
220
|
+
const MASK_GUESS = 200000; // 크기를 모르는 고른 모양 하나를 받을 때 어림하는 글자 수
|
|
221
|
+
const GROW_MAX = 200;
|
|
222
|
+
const OUTLINE_MAX = 60000; // 고른 곳의 가장자리 선이 이보다 많은 토막이면 감싸는 사각형만 그린다
|
|
223
|
+
const SEL_ALPHA = 38; // 고른 곳에 겹쳐 칠하는 파랑의 알파(약 0.15)
|
|
224
|
+
const SHORT_MAX = 80; // 사람이 한 조작이 성공했을 때 알림에 보이는 글자 수
|
|
225
|
+
|
|
226
|
+
// ---- screen language ----
|
|
227
|
+
// 화면 글은 영어로 적고 t() 로 감싼다(plugin-guide 3.7절). 호스트가 capabilities 의 language 로 'ko' 를 알리면 아래 KO 의 한국어를
|
|
228
|
+
// 보이고, 없거나 다른 값이면 영어다(4.4절). {이름} 은 vars 의 값으로 채운다. 논리가 만든 글(조작의 요약, 거절 까닭, 이름)은 그대로
|
|
229
|
+
// 보인다. 이 사이의 글은 src/lang.test.ts 가 떼어 내 돌려 보고, t() 의 글이 모두 KO 에 있는지 본다
|
|
230
|
+
let lang = 'en';
|
|
231
|
+
const KO = {
|
|
232
|
+
// 화면 파일에 적힌 글
|
|
233
|
+
'PNG Image': 'PNG 그림',
|
|
234
|
+
'Picture': '그림',
|
|
235
|
+
'Actions for the selection': '고른 것으로 할 일',
|
|
236
|
+
'Pieces and info': '조각과 정보',
|
|
237
|
+
'Choose PNG file': 'PNG 파일 고르기',
|
|
238
|
+
// 도구와 고른 방법
|
|
239
|
+
'Select piece': '조각 고르기',
|
|
240
|
+
'Rectangle': '사각형',
|
|
241
|
+
'Ellipse': '타원',
|
|
242
|
+
'Freehand': '둘러 그리기',
|
|
243
|
+
'Similar colors': '비슷한 색',
|
|
244
|
+
'Move view': '화면 이동',
|
|
245
|
+
'Combined area': '섞어 고른 곳',
|
|
246
|
+
// 개수(many). 한국어는 하나든 여럿이든 같은 꼴이다
|
|
247
|
+
'{n} {thing}': '{thing} {n}개',
|
|
248
|
+
'{n} {thing}s': '{thing} {n}개',
|
|
249
|
+
'piece': '조각',
|
|
250
|
+
'region': '영역',
|
|
251
|
+
'image file': '그림 파일',
|
|
252
|
+
'pixel': '픽셀',
|
|
253
|
+
'erased area': '지운 곳',
|
|
254
|
+
'visible-area shape': '보이는 곳의 모양',
|
|
255
|
+
'none': '없음',
|
|
256
|
+
'Piece {id}': '조각 {id}',
|
|
257
|
+
// PNG 파일 받기
|
|
258
|
+
'This file is a JPEG image': '이 파일은 JPEG 그림입니다',
|
|
259
|
+
'This file is a GIF image': '이 파일은 GIF 그림입니다',
|
|
260
|
+
'This file is a WebP image': '이 파일은 WebP 그림입니다',
|
|
261
|
+
'This file is a BMP image': '이 파일은 BMP 그림입니다',
|
|
262
|
+
'This file is an SVG image': '이 파일은 SVG 그림입니다',
|
|
263
|
+
'Could not read the file. Add a PNG file': '파일을 읽지 못했습니다. PNG 파일을 넣어 주세요',
|
|
264
|
+
'Only PNG files are accepted': 'PNG 파일만 받습니다',
|
|
265
|
+
'Could not read the PNG header (IHDR)': 'PNG 파일의 머리(IHDR)를 읽지 못했습니다',
|
|
266
|
+
'The file is too large ({size}, limit {limit})': '파일이 너무 큽니다({size}, 한도 {limit})',
|
|
267
|
+
'The picture is too large ({w}×{h}, longest side limit {side} pixels)': '그림이 너무 큽니다({w}×{h}, 긴 변 한도 {side} 픽셀)',
|
|
268
|
+
'Could not read the file': '파일을 읽지 못했습니다',
|
|
269
|
+
'This screen is view only, so you cannot add pictures': '보기만 하는 화면이라 그림을 넣을 수 없습니다',
|
|
270
|
+
'Could not read': '읽지 못했습니다',
|
|
271
|
+
'This screen cannot open pictures': '이 화면에서는 그림을 열지 못합니다',
|
|
272
|
+
'Could not open the picture': '그림을 열지 못했습니다',
|
|
273
|
+
'Could not read the picture': '그림을 읽지 못했습니다',
|
|
274
|
+
// 고르기와 알림
|
|
275
|
+
'You can select up to {max} pieces at once': '한 번에 {max}개까지 함께 고를 수 있습니다',
|
|
276
|
+
'No pixels selected': '고른 픽셀이 없습니다',
|
|
277
|
+
'Click inside the canvas': '그림판 안을 눌러 주세요',
|
|
278
|
+
"Could not read the picture's pixels: {error}": '그림의 픽셀을 읽지 못했습니다: {error}',
|
|
279
|
+
'Could not read the shape of the region': '영역의 모양을 읽지 못했습니다',
|
|
280
|
+
'This region has no pixels inside the canvas to select': '이 영역은 그림판 안에 고를 픽셀이 없습니다',
|
|
281
|
+
'Removed deleted pieces from the selection': '고른 조각 가운데 지워진 것을 뺐습니다',
|
|
282
|
+
'The selected pieces were deleted, so the selection was cleared': '고른 조각이 지워져 고른 것을 풀었습니다',
|
|
283
|
+
'The selected shape is too large (PNG {size} characters, limit {max} characters). Select a smaller area, or use Rectangle or Freehand': '고른 모양이 너무 큽니다(PNG {size}자, 한도 {max}자). 더 작게 고르거나 사각형이나 둘러 그리기로 골라 주세요',
|
|
284
|
+
'Could not load {names} (image files or selection shapes), so those parts are not drawn. {note}': '그림 파일이나 고른 모양 {names} 을 받지 못해 그 부분은 그리지 못했습니다. {note}',
|
|
285
|
+
'Still sending the previous operation': '앞의 조작을 보내는 중입니다',
|
|
286
|
+
'This screen is view only, so you cannot make changes': '보기만 하는 화면이라 고칠 수 없습니다',
|
|
287
|
+
'The operation was rejected': '조작이 거절되었습니다',
|
|
288
|
+
'No visible piece in the selected area': '고른 곳에 보이는 조각이 없습니다',
|
|
289
|
+
'Could not send the selection': '선택을 보내지 못했습니다',
|
|
290
|
+
'Sent the previous selection as {id}. Your current selection is not sent yet': '앞의 선택을 {id} 로 보냈습니다. 지금 고른 것은 아직 보내지 않았습니다',
|
|
291
|
+
'Sent selection {id} and your message to the AI': '선택 {id} 과 말을 AI 에게 보냈습니다',
|
|
292
|
+
'Sent selection {id} to the AI without a message': '선택 {id} 을 말 없이 AI 에게 보냈습니다',
|
|
293
|
+
// 저장
|
|
294
|
+
'{w}×{h} (original size)': '{w}×{h} (원래 크기)',
|
|
295
|
+
'{w}×{h} ({k}x)': '{w}×{h} ({k}배)',
|
|
296
|
+
'Longest side {n}': '긴 변 {n}',
|
|
297
|
+
'Saved: {name}': '저장했습니다: {name}',
|
|
298
|
+
'Could not save': '저장하지 못했습니다',
|
|
299
|
+
// 위쪽 줄
|
|
300
|
+
'{label} menu': '{label} 메뉴',
|
|
301
|
+
'Tools': '도구',
|
|
302
|
+
'Zoom level': '확대 비율',
|
|
303
|
+
'Zoom': '확대와 축소',
|
|
304
|
+
'Zoom out': '축소',
|
|
305
|
+
'Zoom in': '확대',
|
|
306
|
+
'Fit to screen': '화면에 맞춤',
|
|
307
|
+
'Canvas size': '그림판 크기',
|
|
308
|
+
'This screen is view only. Buttons for changes are hidden': '보기만 하는 화면입니다. 고치는 버튼은 숨겨져 있습니다',
|
|
309
|
+
'View only': '보기만',
|
|
310
|
+
'Invert': '뒤집기',
|
|
311
|
+
'Swaps the selected and unselected areas. If nothing is selected, selects the whole canvas': '고른 곳과 고르지 않은 곳을 바꿉니다. 고른 곳이 없으면 그림판 전체를 고릅니다',
|
|
312
|
+
'Deselect': '고른 것 풀기',
|
|
313
|
+
'Clears the selection (Esc)': '고른 것을 풉니다(Esc)',
|
|
314
|
+
'Grow': '넓히기',
|
|
315
|
+
'Moves the edge of the selected area outward': '고른 곳의 가장자리를 바깥으로 넓힙니다',
|
|
316
|
+
'Shrink': '좁히기',
|
|
317
|
+
'Moves the edge of the selected area inward': '고른 곳의 가장자리를 안으로 좁힙니다',
|
|
318
|
+
'Pixels to grow or shrink': '넓히고 좁힐 픽셀 수',
|
|
319
|
+
'Tolerance': '허용 범위',
|
|
320
|
+
'Tolerance value': '허용 범위 숫자',
|
|
321
|
+
'Connected only': '이어진 곳만',
|
|
322
|
+
'Show regions': '영역 보기',
|
|
323
|
+
'Select': '고르기',
|
|
324
|
+
'pixels': '픽셀',
|
|
325
|
+
'Similar colors tolerance': '비슷한 색의 허용 범위',
|
|
326
|
+
'Connected only (off: whole picture)': '이어진 곳만(끄면 그림 전체에서)',
|
|
327
|
+
'Add picture': '그림 올리기',
|
|
328
|
+
'Add picture: adds another PNG file as a new piece on top': '그림 올리기: 다른 PNG 파일을 맨 위의 새 조각으로 올립니다',
|
|
329
|
+
'PNG size': 'PNG 크기',
|
|
330
|
+
'Save PNG': 'PNG 로 저장',
|
|
331
|
+
'Saves the current picture as a PNG file at the chosen size. Empty areas are transparent': '지금 그림을 고른 크기의 PNG 파일로 저장합니다. 빈 곳은 투명합니다',
|
|
332
|
+
'Save': '저장',
|
|
333
|
+
'Tool help': '도구 설명',
|
|
334
|
+
// 도구 설명
|
|
335
|
+
'Click a piece to select it, or drag it to move it. Hold Shift and click to select several pieces. Clicks pass through transparent areas and select the piece visible underneath.': '조각을 누르면 그 조각을 고르고, 끌면 옮깁니다. Shift 를 누른 채 누르면 여럿을 함께 고릅니다. 투명한 곳은 눌리지 않고 그 아래에 보이는 조각이 골라집니다.',
|
|
336
|
+
'Drag to select a rectangle. Hold Shift while dragging to add to the selected area, or Alt to subtract from it. A single click selects the position and color of that point.': '끌어서 사각형으로 고릅니다. Shift 를 누른 채 끌면 고른 곳에 더하고, Alt 를 누른 채 끌면 뺍니다. 한 번 누르면 그 점의 위치와 색을 고릅니다.',
|
|
337
|
+
'Drag to select an ellipse. Hold Shift while dragging to add, or Alt to subtract. A single click selects the position and color of that point.': '끌어서 타원으로 고릅니다. Shift 를 누른 채 끌면 더하고, Alt 를 누른 채 끌면 뺍니다. 한 번 누르면 그 점의 위치와 색을 고릅니다.',
|
|
338
|
+
'Hold the mouse button and draw around an area to select its inside. Shift adds and Alt subtracts. A single click selects the position and color of that point.': '누른 채 둘러 그리면 그 안을 고릅니다. Shift 로 더하고 Alt 로 뺍니다. 한 번 누르면 그 점의 위치와 색을 고릅니다.',
|
|
339
|
+
'Selects colors similar to the spot you click. Set the tolerance and Connected only in the [Select] menu. Shift adds and Alt subtracts.': '누른 곳과 비슷한 색을 고릅니다. 허용 범위와 이어진 곳만은 [고르기] 메뉴에서 정합니다. Shift 로 더하고 Alt 로 뺍니다.',
|
|
340
|
+
'Drag to move the view.': '끌어서 화면을 옮깁니다.',
|
|
341
|
+
'Canvas {w}×{h}, {pieces}, {regions}, {images}': '그림판 {w}×{h}, {pieces}, {regions}, {images}',
|
|
342
|
+
'connected only': '이어진 곳만',
|
|
343
|
+
'whole picture': '그림 전체',
|
|
344
|
+
'Current: tolerance {tol}, {mode}.': '지금 허용 범위 {tol}, {mode}.',
|
|
345
|
+
'On a view-only screen, pieces do not move.': '보기만 하는 화면에서는 조각을 옮기지 않습니다.',
|
|
346
|
+
'Hide tool help': '도구 설명 숨기기',
|
|
347
|
+
'Show tool help': '도구 설명 보기',
|
|
348
|
+
'Hide pieces and info': '조각과 정보 숨기기',
|
|
349
|
+
'Show pieces and info (selection, piece values, piece list, region list, image files)': '조각과 정보 보기(고른 것, 조각의 값, 조각 목록, 영역 목록, 그림 파일)',
|
|
350
|
+
'Start a picture before saving': '그림을 시작한 뒤 저장할 수 있습니다',
|
|
351
|
+
'This core version does not support saving PNG yet': '이 코어 버전은 아직 PNG 저장을 받지 않습니다',
|
|
352
|
+
'Use the mouse wheel to zoom in and out. With any tool, hold Space or the middle mouse button and drag to move the view. Press Esc to deselect. Drop or paste another PNG file onto the picture to add it as a piece.': '휠로 확대하고 줄이며, 스페이스나 가운데 버튼을 누른 채 끌면 어느 도구에서든 화면을 옮깁니다. 고른 것을 풀려면 Esc 를 누릅니다. 다른 PNG 파일을 그림 칸에 놓거나 붙여 넣으면 조각으로 올립니다.',
|
|
353
|
+
'On a view-only screen, you cannot make changes or send a selection to the AI.': '보기만 하는 화면에서는 고칠 수 없고 고른 것을 AI 에게 보낼 수도 없습니다.',
|
|
354
|
+
'This host cannot receive selections from a concept screen yet.': '이 호스트는 아직 개념 화면의 선택을 받지 못합니다.',
|
|
355
|
+
'When you select something, a panel appears at the top of the picture. There you can lift or erase it, and send it to the AI with a message.': '고르면 그림 칸의 위쪽에 칸이 나옵니다. 그 칸에서 떼어 내거나 지우고, 말과 함께 AI 에게 보냅니다.',
|
|
356
|
+
'Even if you only select, the AI reads your selection when you talk to it in the AI chat. To tell a waiting AI right away, send it from that panel.': '고르기만 해도 대화창에서 말하면 AI 가 읽습니다. 기다리는 AI 에게 바로 알리려면 그 칸에서 보냅니다.',
|
|
357
|
+
'Selecting alone does not tell the AI. Send it from that panel.': '고르기만 해서는 AI 가 알지 못합니다. 그 칸에서 보냅니다.',
|
|
358
|
+
// 오른쪽 칸: 그림
|
|
359
|
+
'Sample {title} ({id})': '샘플 {title}({id})',
|
|
360
|
+
'Image file': '그림 파일',
|
|
361
|
+
'Empty canvas': '빈 그림판',
|
|
362
|
+
'Canvas': '그림판',
|
|
363
|
+
'Started from': '시작',
|
|
364
|
+
'Contents': '들어 있는 것',
|
|
365
|
+
'Plugin': '플러그인',
|
|
366
|
+
'This screen is view only. Buttons for changes are hidden.': '보기만 하는 화면입니다. 고치는 버튼은 숨겨져 있습니다.',
|
|
367
|
+
// 고른 것
|
|
368
|
+
'{count} ({names} and {more} more)': '{count}({names} 외 {more}개)',
|
|
369
|
+
'region {id}': '영역 {id}',
|
|
370
|
+
'Point {x}, {y}': '점 {x}, {y}',
|
|
371
|
+
'transparent': '투명',
|
|
372
|
+
'Selection': '고른 것',
|
|
373
|
+
'Click a piece with [Select piece], or select an area with [Rectangle], [Ellipse], [Freehand], or [Similar colors].': '[조각 고르기] 로 조각을 누르거나, [사각형], [타원], [둘러 그리기], [비슷한 색] 으로 곳을 고릅니다.',
|
|
374
|
+
'Hold Shift while selecting to add, or Alt to subtract. Press Esc to deselect.': 'Shift 를 누른 채 고르면 더하고, Alt 를 누른 채 고르면 뺍니다. 고른 것을 풀려면 Esc 를 누릅니다.',
|
|
375
|
+
'Selected piece': '고른 조각',
|
|
376
|
+
'{n} selected pieces': '함께 고른 조각 {n}개',
|
|
377
|
+
'Remove {name} from the selection': '고른 것에서 {name} 빼기',
|
|
378
|
+
'Click to remove it from the selection': '누르면 고른 것에서 뺍니다',
|
|
379
|
+
'Hold Shift and click to add or remove pieces.': 'Shift 를 누른 채 누르면 더하거나 뺍니다.',
|
|
380
|
+
'Hold Shift and click to add or remove pieces. Drag to move them together. Scale, rotation, and color adjustments are below when you select one piece.': 'Shift 를 누른 채 누르면 더하거나 뺍니다. 끌면 함께 옮깁니다. 크기, 돌림, 색 바꾸기는 하나를 골랐을 때 아래에서 합니다.',
|
|
381
|
+
'Selected area': '고른 곳',
|
|
382
|
+
'Selected with': '고른 방법',
|
|
383
|
+
'Bounding box': '감싸는 사각형',
|
|
384
|
+
'Pixels': '픽셀',
|
|
385
|
+
'Region': '영역',
|
|
386
|
+
'Visible pieces': '보이는 조각',
|
|
387
|
+
'Checking': '알아내는 중',
|
|
388
|
+
'None (transparent area)': '없음(투명한 곳)',
|
|
389
|
+
'Main colors': '주된 색',
|
|
390
|
+
'Selected point': '고른 점',
|
|
391
|
+
'Position': '위치',
|
|
392
|
+
'Color': '색',
|
|
393
|
+
'Transparent': '투명',
|
|
394
|
+
'Visible piece': '보이는 조각',
|
|
395
|
+
'None': '없음',
|
|
396
|
+
'Region name': '영역 이름',
|
|
397
|
+
'e.g. left eye': '예: 왼쪽 눈',
|
|
398
|
+
'Name region': '영역으로 남기기',
|
|
399
|
+
'Gives the selected area a name and keeps it as a region. The AI can also refer to it by this name and id': '고른 곳에 이름을 붙여 영역으로 남깁니다. AI 도 이 이름과 id 로 가리킵니다',
|
|
400
|
+
'Enter a name for the region': '영역의 이름을 적어 주세요',
|
|
401
|
+
// 고른 조각의 값
|
|
402
|
+
'Piece values': '고른 조각의 값',
|
|
403
|
+
'Name': '이름',
|
|
404
|
+
'Move': '옮김',
|
|
405
|
+
'Scale': '크기',
|
|
406
|
+
'horizontal {x}, vertical {y}': '가로 {x}, 세로 {y}',
|
|
407
|
+
'Rotation': '돌림',
|
|
408
|
+
'Hue': '색조',
|
|
409
|
+
'Saturation': '채도',
|
|
410
|
+
'Brightness': '밝기',
|
|
411
|
+
'Tint': '색 입히기',
|
|
412
|
+
'Opacity': '불투명도',
|
|
413
|
+
'Erased areas': '지운 곳',
|
|
414
|
+
'Piece name': '조각 이름',
|
|
415
|
+
'Rename': '이름 바꾸기',
|
|
416
|
+
'Move x': '옮김 x',
|
|
417
|
+
'Move y': '옮김 y',
|
|
418
|
+
'Horizontal scale': '가로 배율',
|
|
419
|
+
'Vertical scale': '세로 배율',
|
|
420
|
+
'Rotation (degrees, clockwise)': '돌림(도, 시계 방향)',
|
|
421
|
+
'Tint color': '입힐 색',
|
|
422
|
+
'Tint amount': '색 입히기 양',
|
|
423
|
+
'Restore erased': '지운 곳 되살리기',
|
|
424
|
+
'Restores all erased areas of this piece': '이 조각에서 지운 곳을 모두 되살립니다',
|
|
425
|
+
'lifted from {id}': '{id} 에서 뗀 조각',
|
|
426
|
+
'Scale and rotation are around the center of the area the piece covers.': '크기와 돌림은 조각이 차지하는 곳의 가운데를 기준으로 합니다.',
|
|
427
|
+
// 조각 목록, 영역 목록, 그림 파일
|
|
428
|
+
'approximate area {box}': '차지하는 곳(어림) {box}',
|
|
429
|
+
'No name': '이름 없음',
|
|
430
|
+
'hidden': '숨김',
|
|
431
|
+
'Show {name}': '{name} 보이기',
|
|
432
|
+
'Hide {name}': '{name} 숨기기',
|
|
433
|
+
'Move {name} up': '{name} 위로',
|
|
434
|
+
'Move {name} down': '{name} 아래로',
|
|
435
|
+
'Delete {name}': '{name} 지우기',
|
|
436
|
+
'Piece list ({n})': '조각 목록 ({n}개)',
|
|
437
|
+
'Piece list': '조각 목록',
|
|
438
|
+
'No pieces.': '조각이 없습니다.',
|
|
439
|
+
'Click to select a piece. Hold Shift and click to add it to the selection or remove it.': '누르면 그 조각을 고르고, Shift 를 누른 채 누르면 고른 것에 더하거나 뺍니다.',
|
|
440
|
+
'Region list ({n})': '영역 목록 ({n}개)',
|
|
441
|
+
'Region list': '영역 목록',
|
|
442
|
+
'Automatic region, made when you sent a selection to the AI': '고른 곳을 AI 에게 보낼 때 저절로 남은 영역',
|
|
443
|
+
'Sent area': '보낸 곳(자동 영역)',
|
|
444
|
+
'Select region': '이 영역 고르기',
|
|
445
|
+
'Delete region {name}': '{name} 영역 지우기',
|
|
446
|
+
'No regions yet. Select an area and give it a name to keep it. When you send a selected area to the AI, it is also kept as an automatic region.': '아직 영역이 없습니다. 곳을 고르고 이름을 붙이면 남습니다. 고른 곳을 AI 에게 보내면 자동 영역으로도 남습니다.',
|
|
447
|
+
'Image files ({n})': '그림 파일 ({n}개)',
|
|
448
|
+
'The pixels of an image file never change. A piece only records which parts of its image file are visible or erased, its placement, and its color adjustments.': '그림 파일의 픽셀은 바뀌지 않습니다. 조각은 그림 파일의 보이는 곳과 지운 곳, 배치, 색 바꾸기만 적습니다.',
|
|
449
|
+
// 고른 뒤에 뜨는 칸
|
|
450
|
+
'Sent to the AI (selection {id})': 'AI 에게 보냈습니다(선택 {id})',
|
|
451
|
+
'message "{said}"': '말 "{said}"',
|
|
452
|
+
'no message': '말 없음',
|
|
453
|
+
'The AI reads this selection and works on it.': 'AI 가 이 선택을 읽고 일합니다.',
|
|
454
|
+
'Selected: {sel}': '고른 것: {sel}',
|
|
455
|
+
'The AI reads this when you talk to it in the AI chat. To tell a waiting AI right away, press [Send to AI].': '대화창에서 말하면 AI 가 이것을 읽습니다. 기다리는 AI 에게 바로 알리려면 [AI 에게 보내기] 를 누릅니다.',
|
|
456
|
+
'Not sent to the AI yet.': '아직 AI 에게 보내지 않았습니다.',
|
|
457
|
+
'The message can be empty.': '말은 비워도 됩니다.',
|
|
458
|
+
'Actions for the selected area': '고른 곳으로 할 일',
|
|
459
|
+
'Lift': '떼어 내기',
|
|
460
|
+
'Lifts the selected area off the topmost visible piece into a new piece. That part of the original piece is erased': '고른 곳을 맨 위에 보이는 조각에서 떼어 새 조각으로 만듭니다. 원래 조각의 그 곳은 지워집니다',
|
|
461
|
+
'Copy': '복사해 떼기',
|
|
462
|
+
'Copies the selected area into a new piece. The original piece stays as it is': '고른 곳을 복사해 새 조각으로 만듭니다. 원래 조각은 그대로입니다',
|
|
463
|
+
'Erase': '지우기',
|
|
464
|
+
'Erases the selected area from the topmost visible piece (makes it transparent)': '고른 곳을 맨 위에 보이는 조각에서 지웁니다(투명하게)',
|
|
465
|
+
'Crop': '자르기',
|
|
466
|
+
'Crops the canvas to the rectangle around the selected area': '그림판을 고른 곳을 감싸는 사각형으로 자릅니다',
|
|
467
|
+
'Adjust colors': '색 바꾸기',
|
|
468
|
+
'Copies the selected area into a new piece so you can change its colors in the right panel': '고른 곳을 복사해 새 조각으로 떼고, 오른쪽 칸에서 그 조각의 색을 바꿉니다',
|
|
469
|
+
'Message about this selection': '이 선택에 대해 할 말',
|
|
470
|
+
'e.g. make this part brighter (optional)': '예: 이 부분만 더 밝게(비워 두어도 됩니다)',
|
|
471
|
+
'Selection role': '선택의 역할',
|
|
472
|
+
'Change this': '바꿀 곳',
|
|
473
|
+
'For reference': '참고할 곳',
|
|
474
|
+
'Send to AI': 'AI 에게 보내기',
|
|
475
|
+
'Sends the selection and your message to the AI. The message can be empty': '고른 것과 적은 말을 AI 에게 보냅니다. 말은 비워도 됩니다',
|
|
476
|
+
// 시작 화면
|
|
477
|
+
'No picture yet.': '그림이 아직 없습니다.',
|
|
478
|
+
'Drop a PNG file here, or click to choose one. You can also paste one (Ctrl+V).': 'PNG 파일을 여기에 놓거나 눌러서 고릅니다. 붙여 넣기(Ctrl+V)도 됩니다.',
|
|
479
|
+
'Only PNG files. Each file can be up to {size}, and the longest side up to {side} pixels.': 'PNG 만 받습니다. 파일 하나는 {size}, 긴 변은 {side} 픽셀까지입니다.',
|
|
480
|
+
'Choose file': '파일 고르기',
|
|
481
|
+
'Start with sample': '샘플로 시작',
|
|
482
|
+
'Start with sample ({title})': '샘플로 시작({title})',
|
|
483
|
+
'Starts with the built-in sample {title} ({id})': '내장 샘플 {title}({id})로 시작합니다',
|
|
484
|
+
};
|
|
485
|
+
/** 고른 언어의 글. KO 에 없으면 받은 글 그대로다. 화면 파일에 적힌 글을 바꿀 때도 쓴다. */
|
|
486
|
+
const ko = (text) => (lang === 'ko' && Object.prototype.hasOwnProperty.call(KO, text) ? KO[text] : text);
|
|
487
|
+
/** 화면 글. 첫 인자는 늘 영어 글 그대로(문자열 하나)이고, {이름} 을 vars 로 채운다. 채운 값은 다시 보지 않는다. */
|
|
488
|
+
function t(text, vars) {
|
|
489
|
+
const s = ko(text);
|
|
490
|
+
return vars ? s.replace(/\{(\w+)\}/g, (m, k) => (Object.prototype.hasOwnProperty.call(vars, k) ? String(vars[k]) : m)) : s;
|
|
491
|
+
}
|
|
492
|
+
// ---- screen language end ----
|
|
493
|
+
|
|
494
|
+
const errorEl = document.getElementById('error');
|
|
495
|
+
const toastEl = document.getElementById('toast');
|
|
496
|
+
const barEl = document.getElementById('bar');
|
|
497
|
+
const startEl = document.getElementById('startView');
|
|
498
|
+
const mainEl = document.getElementById('main');
|
|
499
|
+
const stage = document.getElementById('stage');
|
|
500
|
+
const paper = document.getElementById('paper');
|
|
501
|
+
const drawingEl = document.getElementById('drawing');
|
|
502
|
+
const imageDefsEl = document.getElementById('imageDefs');
|
|
503
|
+
const pieceDefsEl = document.getElementById('pieceDefs');
|
|
504
|
+
const piecesEl = document.getElementById('pieces');
|
|
505
|
+
const selCanvas = document.getElementById('selCanvas');
|
|
506
|
+
const overlay = document.getElementById('overlay');
|
|
507
|
+
const stageNote = document.getElementById('stageNote');
|
|
508
|
+
const sideEl = document.getElementById('side');
|
|
509
|
+
const talkEl = document.getElementById('talkBar');
|
|
510
|
+
const fileEl = document.getElementById('filePick');
|
|
511
|
+
|
|
512
|
+
let nextId = 1;
|
|
513
|
+
const waiting = new Map();
|
|
514
|
+
let concept = null; // 호스트의 읽기 응답. body 는 다른 참여자의 변경까지 얹은 project 의 json 이다
|
|
515
|
+
let data = null; // concept.body(6.3절의 JSON)
|
|
516
|
+
let caps = { edit: true }; // capabilities(). conceptSelection 이 있으면 선택을 보내고, conceptPick 이 있으면 고르기만 한 것도 알리며, output 에 png 가 있으면 저장한다
|
|
517
|
+
let pieceById = new Map();
|
|
518
|
+
let regionById = new Map();
|
|
519
|
+
let imageById = new Map();
|
|
520
|
+
// 그림 파일 id 와 고른 모양의 key 에서 base64 글로. 내용에서 나온 이름이라 한 번 받으면 다시 받지 않는다
|
|
521
|
+
const store = new Map();
|
|
522
|
+
const missing = new Set(); // 받지 못한 이름. 다시 읽을 때 한 번 더 받아 본다
|
|
523
|
+
let missingNote = '';
|
|
524
|
+
// 넣어 둔 그림의 글. 같으면 다시 넣지 않는다(그림 파일이 든 정의는 수 MB 라 조각을 옮길 때마다 다시 넣지 않는다)
|
|
525
|
+
const drawn = { defs: null, pieceDefs: null, body: null, size: null };
|
|
526
|
+
let drawSeq = 0; // 보이는 그림이 바뀔 때마다 늘린다. 그림 전체의 픽셀을 다시 만들지 정할 때 쓴다
|
|
527
|
+
let drawnBase = null; // 지금 그린 revision
|
|
528
|
+
let pieceEls = new Map(); // 조각 id 에서 그린 <g data-piece> 로
|
|
529
|
+
let tool = 'piece';
|
|
530
|
+
// 확대와 이동. x, y 는 그림판 왼쪽 위가 그림 칸 안에서 놓인 화면 픽셀 위치다. auto 는 사람이 아직 확대나 이동을 하지 않아
|
|
531
|
+
// 칸의 크기가 바뀌면 다시 맞추는 상태다
|
|
532
|
+
const view = { zoom: 1, x: 0, y: 0, auto: true, canvasKey: null };
|
|
533
|
+
const wandOpt = { tolerance: 32, contiguous: true };
|
|
534
|
+
let growBy = 1;
|
|
535
|
+
let showRegions = false;
|
|
536
|
+
// 지금 고른 것. kind 는 pieces(조각 id 목록 list), area(고른 곳의 픽셀 표 mask 와 감싸는 사각형 box), point(그림판의 한 픽셀 x, y)다.
|
|
537
|
+
// area 의 shape 는 도구 하나로 한 번에 고른 모양(where 로 그대로 보낸다)이고, region 은 저장된 영역에서 고른 것이거나 보내며
|
|
538
|
+
// 저장한 영역의 id 다. colors, under, color, piece 는 픽셀을 읽어 채우고 다 채우면 ready 가 참이다.
|
|
539
|
+
// shared 는 대화로 보낸 선택 { id, role, said } 다
|
|
540
|
+
let selection = null;
|
|
541
|
+
let selectionGen = 0;
|
|
542
|
+
// 코어에 알려 둔 고르기만 한 것(setPick)의 내용. 같은 것을 다시 알리지 않으려고 적어 둔다. 알린 것이 없으면 null 이다
|
|
543
|
+
let pickSent = null;
|
|
544
|
+
let pngChoice = null;
|
|
545
|
+
let talk = { role: 'change', said: '' };
|
|
546
|
+
let drag = null; // 누르고 있는 동안의 끌기
|
|
547
|
+
let sliding = false; // 오른쪽 칸의 조절 막대를 끄는 중이다. 끄는 동안은 화면에서만 미리 보인다
|
|
548
|
+
let preview = null; // { id, adjust } 조절 막대로 미리 보이는 색 바꾸기
|
|
549
|
+
let pendingRefresh = false; // 끄는 중에 온 바뀜. 끝나면 다시 읽는다
|
|
550
|
+
let spaceDown = false;
|
|
551
|
+
let committing = false;
|
|
552
|
+
let sharing = false;
|
|
553
|
+
let filePurpose = 'start';
|
|
554
|
+
// 보이는 방식의 상태. 오른쪽 칸과 도구 설명은 숨긴 채 시작하고 위쪽 줄의 버튼으로 연다. 플러그인 화면은 브라우저 저장소를
|
|
555
|
+
// 쓰지 못하므로(sandbox) 화면을 다시 불러오면 처음 상태로 돌아간다
|
|
556
|
+
let sideOpen = false;
|
|
557
|
+
let helpOn = false;
|
|
558
|
+
let openMenu = null;
|
|
559
|
+
let talkPlaced = null;
|
|
560
|
+
let nameDraft = { key: null, text: '' };
|
|
561
|
+
let regionDraft = { key: null, text: '' };
|
|
562
|
+
let tintDraft = { key: null, color: '#ff0000' };
|
|
563
|
+
|
|
564
|
+
function call(method, params) {
|
|
565
|
+
return new Promise((resolve, reject) => {
|
|
566
|
+
const id = nextId++;
|
|
567
|
+
waiting.set(id, { resolve, reject });
|
|
568
|
+
parent.postMessage({ aic: 1, id, method, params }, '*');
|
|
569
|
+
});
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
window.addEventListener('message', (e) => {
|
|
573
|
+
if (e.source !== parent) return;
|
|
574
|
+
const d = e.data;
|
|
575
|
+
if (typeof d !== 'object' || d === null || d.aic !== 1) return;
|
|
576
|
+
if (d.event === 'change') {
|
|
577
|
+
// 끌거나 조절 막대를 움직이는 중에는 다시 그리지 않고 끝난 뒤 읽는다(plugin-guide 4.7절)
|
|
578
|
+
if (drag || sliding) pendingRefresh = true;
|
|
579
|
+
else refresh();
|
|
580
|
+
return;
|
|
581
|
+
}
|
|
582
|
+
if (d.event) return;
|
|
583
|
+
const w = waiting.get(d.id);
|
|
584
|
+
if (!w) return;
|
|
585
|
+
waiting.delete(d.id);
|
|
586
|
+
if (d.error) w.reject(new Error(d.error));
|
|
587
|
+
else w.resolve(d.result);
|
|
588
|
+
});
|
|
589
|
+
|
|
590
|
+
// ---- 계산 ----
|
|
591
|
+
|
|
592
|
+
const clamp = (v, a, b) => Math.min(b, Math.max(a, v));
|
|
593
|
+
const r1 = (v) => Math.round(v * 10) / 10 || 0;
|
|
594
|
+
const r3 = (v) => Math.round(v * 1000) / 1000 || 0;
|
|
595
|
+
const num = (v) => String(Math.round(v * 100) / 100 || 0);
|
|
596
|
+
const comma = (n) => String(n).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
|
|
597
|
+
// 화면 글의 개수. one 은 t() 로 옮긴 이름이다. 영어는 하나면 그대로, 아니면 s 를 붙이고(1 piece, 3 pieces), 한국어는 수가 몇이든
|
|
598
|
+
// 같은 꼴이다(조각 3개). 두 꼴 모두 KO 에 있다
|
|
599
|
+
const many = (n, one) => (n === 1 ? t('{n} {thing}', { n: comma(n), thing: one }) : t('{n} {thing}s', { n: comma(n), thing: one }));
|
|
600
|
+
const hex2 = (v) => clamp(Math.round(v), 0, 255).toString(16).padStart(2, '0');
|
|
601
|
+
const hexColor = (r, g, b) => `#${hex2(r)}${hex2(g)}${hex2(b)}`;
|
|
602
|
+
const sizeText = (bytes) => (bytes >= 1048576 ? `${(bytes / 1048576).toFixed(1)}MB` : `${Math.max(1, Math.round(bytes / 1024))}KB`);
|
|
603
|
+
const boxText = (b) => (b ? `${num(b.x)}, ${num(b.y)} / ${num(b.w)}×${num(b.h)}` : t('none'));
|
|
604
|
+
const limits = () => ({ ...LIMITS, ...(data?.limits ?? {}) });
|
|
605
|
+
const labelOf = (p) => p.name || p.id;
|
|
606
|
+
const titleOf = (p) => (p.name ? `${p.name} (${p.id})` : t('Piece {id}', { id: p.id }));
|
|
607
|
+
|
|
608
|
+
// 행렬은 SVG 의 matrix(a b c d e f) 와 같다. 점 (x, y) 는 (a x + c y + e, b x + d y + f) 로 간다
|
|
609
|
+
function invMat(m) {
|
|
610
|
+
const [a, b, c, d, e, f] = m;
|
|
611
|
+
const det = a * d - b * c;
|
|
612
|
+
if (!Number.isFinite(det) || Math.abs(det) < 1e-12) return null;
|
|
613
|
+
return [d / det, -b / det, -c / det, a / det, (c * f - d * e) / det, (b * e - a * f) / det];
|
|
614
|
+
}
|
|
615
|
+
const mapPt = (m, x, y) => [m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]];
|
|
616
|
+
// 같은 배열에서 거꾸로 할 행렬을 여러 번 구하지 않는다. 다시 읽으면 배열이 새로 와서 저절로 버려진다
|
|
617
|
+
const invCache = new WeakMap();
|
|
618
|
+
function invOf(m) {
|
|
619
|
+
if (!invCache.has(m)) invCache.set(m, invMat(m));
|
|
620
|
+
return invCache.get(m);
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
/** 다각형 안인지(감은 수가 0 이 아니면 안. SVG polygon 의 기본 채움 규칙과 같다). */
|
|
624
|
+
function windingAt(pts, x, y) {
|
|
625
|
+
let w = 0;
|
|
626
|
+
for (let i = 0, n = pts.length; i < n; i += 1) {
|
|
627
|
+
const [x1, y1] = pts[i];
|
|
628
|
+
const [x2, y2] = pts[(i + 1) % n];
|
|
629
|
+
const side = (x2 - x1) * (y - y1) - (x - x1) * (y2 - y1);
|
|
630
|
+
if (y1 <= y) { if (y2 > y && side > 0) w += 1; } else if (y2 <= y && side < 0) w -= 1;
|
|
631
|
+
}
|
|
632
|
+
return w;
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
/**
|
|
636
|
+
* 모양이 그 점을 얼마나 덮는지(0 에서 1). 위치는 그 모양이 놓인 곳의 위치다. 고른 모양 PNG 는 그 픽셀의 알파이고, 그 픽셀을 아직
|
|
637
|
+
* 읽지 못했으면 감싸는 사각형으로 어림한다.
|
|
638
|
+
*/
|
|
639
|
+
function shapeCover(s, x, y) {
|
|
640
|
+
if (s.kind === 'rect') return x >= s.x && x < s.x + s.w && y >= s.y && y < s.y + s.h ? 1 : 0;
|
|
641
|
+
if (s.kind === 'ellipse') {
|
|
642
|
+
if (!(s.rx > 0 && s.ry > 0)) return 0;
|
|
643
|
+
const u = (x - s.cx) / s.rx;
|
|
644
|
+
const v = (y - s.cy) / s.ry;
|
|
645
|
+
return u * u + v * v <= 1 ? 1 : 0;
|
|
646
|
+
}
|
|
647
|
+
if (s.kind === 'polygon') return windingAt(s.points, x, y) !== 0 ? 1 : 0;
|
|
648
|
+
if (s.kind === 'mask') {
|
|
649
|
+
if (!(x >= s.x && x < s.x + s.w && y >= s.y && y < s.y + s.h)) return 0;
|
|
650
|
+
const px = pixReady(s.key);
|
|
651
|
+
if (!px) return 1;
|
|
652
|
+
return px.data[(Math.floor(y - s.y) * px.w + Math.floor(x - s.x)) * 4 + 3] / 255;
|
|
653
|
+
}
|
|
654
|
+
return 0;
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
/** 조각 안쪽 위치 (u, v) 를 조각에 놓인 모양이 덮는 정도. 모양의 m 은 모양의 위치를 조각 안쪽 위치로 옮긴다(3.1절). */
|
|
658
|
+
function placedCover(s, u, v) {
|
|
659
|
+
if (!s.m) return shapeCover(s, u, v);
|
|
660
|
+
const iv = invOf(s.m);
|
|
661
|
+
if (!iv) return 0;
|
|
662
|
+
const [x, y] = mapPt(iv, u, v);
|
|
663
|
+
return shapeCover(s, x, y);
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
/**
|
|
667
|
+
* 그림판 위치 (x, y) 에서 이 조각이 보이는 정도(0 에서 1). 배치 행렬의 역행렬로 조각 안쪽 위치로 옮겨, 그림 파일 안이고 보이는 곳
|
|
668
|
+
* 모두의 안이며 지운 곳 어느 것에도 덮이지 않고 그 픽셀의 알파가 0 보다 커야 보인다(9절). 그림 파일의 픽셀을 아직 읽지 못했으면 0 이다.
|
|
669
|
+
*/
|
|
670
|
+
function alphaAt(p, x, y) {
|
|
671
|
+
if (p.hidden || !(p.adjust?.opacity > 0)) return 0;
|
|
672
|
+
const im = imageById.get(p.image);
|
|
673
|
+
const px = im ? pixReady(im.id) : null;
|
|
674
|
+
const iv = px ? invOf(p.matrix) : null;
|
|
675
|
+
if (!iv) return 0;
|
|
676
|
+
const [u, v] = mapPt(iv, x, y);
|
|
677
|
+
if (!(u >= 0 && v >= 0 && u < im.width && v < im.height)) return 0;
|
|
678
|
+
let a = px.data[(Math.floor(v) * px.w + Math.floor(u)) * 4 + 3] / 255;
|
|
679
|
+
for (const s of p.clip) { if (!a) return 0; a *= placedCover(s, u, v); }
|
|
680
|
+
for (const s of p.holes) { if (!a) return 0; a *= 1 - placedCover(s, u, v); }
|
|
681
|
+
return a;
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
/** 그 점에 실제로 보이는 맨 위의 조각. 없으면 null 이다. */
|
|
685
|
+
function topPieceAt(x, y) {
|
|
686
|
+
const list = data?.pieces ?? [];
|
|
687
|
+
for (let i = list.length - 1; i >= 0; i -= 1) if (alphaAt(list[i], x, y) > 0) return list[i];
|
|
688
|
+
return null;
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
function readOnly() {
|
|
692
|
+
return caps.edit === false || Boolean(concept?.editing && concept.instance && concept.editing.id !== concept.instance);
|
|
693
|
+
}
|
|
694
|
+
/** 고른 것을 AI 에게 보낼 수 있는 화면인가. */
|
|
695
|
+
const canShare = () => Boolean(caps.conceptSelection) && !readOnly();
|
|
696
|
+
|
|
697
|
+
// ---- 고른 곳의 픽셀 표 ----
|
|
698
|
+
// 고른 곳은 그림판 크기의 Uint8Array 다(고른 픽셀 1, 아니면 0). 픽셀 (x, y) 는 [x, x+1)×[y, y+1) 을 덮고, 모양 안인지는 픽셀의
|
|
699
|
+
// 가운데로 본다. 사각형, 타원, 둘러 그리기도 이 표에 칠해 넣으므로 더하기, 빼기, 뒤집기, 넓히기, 좁히기가 모두 같은 계산이다(7.1절).
|
|
700
|
+
|
|
701
|
+
function rectMask(W, H, r) {
|
|
702
|
+
const m = new Uint8Array(W * H);
|
|
703
|
+
const x0 = clamp(Math.ceil(r.x - 0.5), 0, W);
|
|
704
|
+
const x1 = clamp(Math.ceil(r.x + r.w - 0.5), 0, W);
|
|
705
|
+
const y0 = clamp(Math.ceil(r.y - 0.5), 0, H);
|
|
706
|
+
const y1 = clamp(Math.ceil(r.y + r.h - 0.5), 0, H);
|
|
707
|
+
for (let y = y0; y < y1; y += 1) m.fill(1, y * W + x0, y * W + x1);
|
|
708
|
+
return m;
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
function ellipseMask(W, H, e) {
|
|
712
|
+
const m = new Uint8Array(W * H);
|
|
713
|
+
if (!(e.rx > 0 && e.ry > 0)) return m;
|
|
714
|
+
const y0 = clamp(Math.floor(e.cy - e.ry), 0, H);
|
|
715
|
+
const y1 = clamp(Math.ceil(e.cy + e.ry), 0, H);
|
|
716
|
+
for (let y = y0; y < y1; y += 1) {
|
|
717
|
+
const dy = (y + 0.5 - e.cy) / e.ry;
|
|
718
|
+
if (dy * dy > 1) continue;
|
|
719
|
+
const half = e.rx * Math.sqrt(1 - dy * dy);
|
|
720
|
+
const x0 = clamp(Math.ceil(e.cx - half - 0.5), 0, W);
|
|
721
|
+
const x1 = clamp(Math.floor(e.cx + half - 0.5) + 1, 0, W);
|
|
722
|
+
if (x1 > x0) m.fill(1, y * W + x0, y * W + x1);
|
|
723
|
+
}
|
|
724
|
+
return m;
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
/** 다각형을 줄마다 칠한다. 감은 수가 0 이 아닌 곳이 안이다(SVG polygon 과 같다). */
|
|
728
|
+
function polygonMask(W, H, pts) {
|
|
729
|
+
const m = new Uint8Array(W * H);
|
|
730
|
+
const n = pts.length;
|
|
731
|
+
if (n < 3) return m;
|
|
732
|
+
let minY = Infinity;
|
|
733
|
+
let maxY = -Infinity;
|
|
734
|
+
for (const p of pts) { minY = Math.min(minY, p[1]); maxY = Math.max(maxY, p[1]); }
|
|
735
|
+
const y0 = clamp(Math.floor(minY), 0, H);
|
|
736
|
+
const y1 = clamp(Math.ceil(maxY), 0, H);
|
|
737
|
+
const xs = [];
|
|
738
|
+
for (let y = y0; y < y1; y += 1) {
|
|
739
|
+
const cy = y + 0.5;
|
|
740
|
+
xs.length = 0;
|
|
741
|
+
for (let i = 0; i < n; i += 1) {
|
|
742
|
+
const [ax, ay] = pts[i];
|
|
743
|
+
const [bx, by] = pts[(i + 1) % n];
|
|
744
|
+
if ((ay <= cy && by > cy) || (by <= cy && ay > cy)) xs.push([ax + ((cy - ay) / (by - ay)) * (bx - ax), by > ay ? 1 : -1]);
|
|
745
|
+
}
|
|
746
|
+
xs.sort((a, b) => a[0] - b[0]);
|
|
747
|
+
let w = 0;
|
|
748
|
+
for (let k = 0; k < xs.length - 1; k += 1) {
|
|
749
|
+
w += xs[k][1];
|
|
750
|
+
if (w === 0) continue;
|
|
751
|
+
const x0 = clamp(Math.ceil(xs[k][0] - 0.5), 0, W);
|
|
752
|
+
const x1 = clamp(Math.ceil(xs[k + 1][0] - 0.5), 0, W);
|
|
753
|
+
if (x1 > x0) m.fill(1, y * W + x0, y * W + x1);
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
return m;
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
/** 저장된 영역이나 조작에 쓰는 모양(rect, ellipse, polygon)의 픽셀 표. 고른 모양 PNG 는 regionMask 가 한다. */
|
|
760
|
+
function shapeMask(W, H, s) {
|
|
761
|
+
if (s.kind === 'rect') return rectMask(W, H, s);
|
|
762
|
+
if (s.kind === 'ellipse') return ellipseMask(W, H, s);
|
|
763
|
+
if (s.kind === 'polygon') return polygonMask(W, H, s.points);
|
|
764
|
+
return null;
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
/**
|
|
768
|
+
* 비슷한 색 고르기. px 는 지금 보이는 그림 전체의 픽셀(RGBA)이다. 누른 픽셀과 빨강, 초록, 파랑, 알파가 저마다 허용 범위 안에서
|
|
769
|
+
* 같은 픽셀을 고른다. 이어진 곳만이면 누른 픽셀에서 위아래 왼쪽 오른쪽으로 이어진 것만이다.
|
|
770
|
+
*/
|
|
771
|
+
function wandMask(px, x, y, tol, contiguous) {
|
|
772
|
+
const { w: W, h: H, data: d } = px;
|
|
773
|
+
const m = new Uint8Array(W * H);
|
|
774
|
+
const s = (y * W + x) * 4;
|
|
775
|
+
const r = d[s];
|
|
776
|
+
const g = d[s + 1];
|
|
777
|
+
const b = d[s + 2];
|
|
778
|
+
const a = d[s + 3];
|
|
779
|
+
const near = (k) => { const i = k * 4; return Math.abs(d[i] - r) <= tol && Math.abs(d[i + 1] - g) <= tol && Math.abs(d[i + 2] - b) <= tol && Math.abs(d[i + 3] - a) <= tol; };
|
|
780
|
+
if (!contiguous) {
|
|
781
|
+
for (let k = 0; k < W * H; k += 1) if (near(k)) m[k] = 1;
|
|
782
|
+
return m;
|
|
783
|
+
}
|
|
784
|
+
const stack = new Int32Array(W * H);
|
|
785
|
+
let top = 0;
|
|
786
|
+
const k0 = y * W + x;
|
|
787
|
+
m[k0] = 1;
|
|
788
|
+
stack[top++] = k0;
|
|
789
|
+
while (top) {
|
|
790
|
+
const k = stack[--top];
|
|
791
|
+
const kx = k % W;
|
|
792
|
+
if (kx > 0 && !m[k - 1] && near(k - 1)) { m[k - 1] = 1; stack[top++] = k - 1; }
|
|
793
|
+
if (kx < W - 1 && !m[k + 1] && near(k + 1)) { m[k + 1] = 1; stack[top++] = k + 1; }
|
|
794
|
+
if (k >= W && !m[k - W] && near(k - W)) { m[k - W] = 1; stack[top++] = k - W; }
|
|
795
|
+
if (k < W * (H - 1) && !m[k + W] && near(k + W)) { m[k + W] = 1; stack[top++] = k + W; }
|
|
796
|
+
}
|
|
797
|
+
return m;
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
function combineMasks(a, b, mode) {
|
|
801
|
+
const out = new Uint8Array(a.length);
|
|
802
|
+
if (mode === 'sub') for (let i = 0; i < a.length; i += 1) out[i] = a[i] && !b[i] ? 1 : 0;
|
|
803
|
+
else for (let i = 0; i < a.length; i += 1) out[i] = a[i] || b[i] ? 1 : 0;
|
|
804
|
+
return out;
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
function invertMask(m) {
|
|
808
|
+
const out = new Uint8Array(m.length);
|
|
809
|
+
for (let i = 0; i < m.length; i += 1) out[i] = m[i] ? 0 : 1;
|
|
810
|
+
return out;
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
/** 고른 픽셀 수와 감싸는 사각형. 고른 것이 없으면 box 는 null 이다. */
|
|
814
|
+
function maskInfo(m, W, H) {
|
|
815
|
+
let x0 = W;
|
|
816
|
+
let y0 = H;
|
|
817
|
+
let x1 = -1;
|
|
818
|
+
let y1 = -1;
|
|
819
|
+
let n = 0;
|
|
820
|
+
for (let y = 0; y < H; y += 1) {
|
|
821
|
+
const row = y * W;
|
|
822
|
+
let rowN = 0;
|
|
823
|
+
for (let x = 0; x < W; x += 1) {
|
|
824
|
+
if (!m[row + x]) continue;
|
|
825
|
+
rowN += 1;
|
|
826
|
+
if (x < x0) x0 = x;
|
|
827
|
+
if (x > x1) x1 = x;
|
|
828
|
+
}
|
|
829
|
+
if (rowN) { n += rowN; if (y < y0) y0 = y; y1 = y; }
|
|
830
|
+
}
|
|
831
|
+
return n ? { box: { x: x0, y: y0, w: x1 - x0 + 1, h: y1 - y0 + 1 }, pixels: n } : { box: null, pixels: 0 };
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
// 넓히기와 좁히기는 가장 가까운 고른(또는 고르지 않은) 픽셀까지의 거리로 한다(거리의 제곱을 줄과 칸으로 나눠 구하는 방법).
|
|
835
|
+
// 그래서 몇 픽셀을 주어도 한 번에 끝나고 모서리가 둥글다
|
|
836
|
+
const EDT_INF = 1e20;
|
|
837
|
+
function edt1d(f, n, d, v, z) {
|
|
838
|
+
let k = 0;
|
|
839
|
+
v[0] = 0;
|
|
840
|
+
z[0] = -Infinity;
|
|
841
|
+
z[1] = Infinity;
|
|
842
|
+
for (let q = 1; q < n; q += 1) {
|
|
843
|
+
let s = ((f[q] + q * q) - (f[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k]);
|
|
844
|
+
while (s <= z[k]) {
|
|
845
|
+
k -= 1;
|
|
846
|
+
s = ((f[q] + q * q) - (f[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k]);
|
|
847
|
+
}
|
|
848
|
+
k += 1;
|
|
849
|
+
v[k] = q;
|
|
850
|
+
z[k] = s;
|
|
851
|
+
z[k + 1] = Infinity;
|
|
852
|
+
}
|
|
853
|
+
k = 0;
|
|
854
|
+
for (let q = 0; q < n; q += 1) {
|
|
855
|
+
while (z[k + 1] < q) k += 1;
|
|
856
|
+
d[q] = (q - v[k]) * (q - v[k]) + f[v[k]];
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
/** 사각형 r 안의 픽셀마다, r 안에서 값이 want 인 가장 가까운 픽셀까지의 거리의 제곱. */
|
|
861
|
+
function distField(m, W, r, want) {
|
|
862
|
+
const g = new Float32Array(r.w * r.h);
|
|
863
|
+
for (let j = 0; j < r.h; j += 1) for (let i = 0; i < r.w; i += 1) g[j * r.w + i] = (m[(r.y + j) * W + r.x + i] ? 1 : 0) === want ? 0 : EDT_INF;
|
|
864
|
+
const n = Math.max(r.w, r.h);
|
|
865
|
+
const f = new Float64Array(n);
|
|
866
|
+
const d = new Float64Array(n);
|
|
867
|
+
const v = new Int32Array(n);
|
|
868
|
+
const z = new Float64Array(n + 1);
|
|
869
|
+
for (let i = 0; i < r.w; i += 1) {
|
|
870
|
+
for (let j = 0; j < r.h; j += 1) f[j] = g[j * r.w + i];
|
|
871
|
+
edt1d(f, r.h, d, v, z);
|
|
872
|
+
for (let j = 0; j < r.h; j += 1) g[j * r.w + i] = d[j];
|
|
873
|
+
}
|
|
874
|
+
for (let j = 0; j < r.h; j += 1) {
|
|
875
|
+
for (let i = 0; i < r.w; i += 1) f[i] = g[j * r.w + i];
|
|
876
|
+
edt1d(f, r.w, d, v, z);
|
|
877
|
+
for (let i = 0; i < r.w; i += 1) g[j * r.w + i] = d[i];
|
|
878
|
+
}
|
|
879
|
+
return g;
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
const grownBox = (b, n, W, H) => {
|
|
883
|
+
const x = Math.max(0, b.x - n);
|
|
884
|
+
const y = Math.max(0, b.y - n);
|
|
885
|
+
return { x, y, w: Math.min(W, b.x + b.w + n) - x, h: Math.min(H, b.y + b.h + n) - y };
|
|
886
|
+
};
|
|
887
|
+
|
|
888
|
+
/** 고른 곳을 n 픽셀 넓힌다. */
|
|
889
|
+
function growMask(m, W, H, box, n) {
|
|
890
|
+
const r = grownBox(box, n, W, H);
|
|
891
|
+
const g = distField(m, W, r, 1);
|
|
892
|
+
const out = m.slice();
|
|
893
|
+
const lim = n * n;
|
|
894
|
+
for (let j = 0; j < r.h; j += 1) for (let i = 0; i < r.w; i += 1) if (g[j * r.w + i] <= lim) out[(r.y + j) * W + r.x + i] = 1;
|
|
895
|
+
return out;
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
/** 고른 곳을 n 픽셀 좁힌다. 그림판의 가장자리에서는 좁히지 않는다(그림판 밖은 고르지 않은 곳으로 보지 않는다). */
|
|
899
|
+
function shrinkMask(m, W, H, box, n) {
|
|
900
|
+
const r = grownBox(box, 1, W, H);
|
|
901
|
+
const g = distField(m, W, r, 0);
|
|
902
|
+
const out = m.slice();
|
|
903
|
+
const lim = n * n;
|
|
904
|
+
for (let j = 0; j < r.h; j += 1) {
|
|
905
|
+
for (let i = 0; i < r.w; i += 1) {
|
|
906
|
+
const k = (r.y + j) * W + r.x + i;
|
|
907
|
+
if (out[k] && g[j * r.w + i] <= lim) out[k] = 0;
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
return out;
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
/**
|
|
914
|
+
* 고른 곳의 가장자리를 픽셀 경계를 따라 그린 path 글(그림판 위치). 가로와 세로로 이어진 경계는 한 토막으로 합친다. 토막이
|
|
915
|
+
* OUTLINE_MAX 를 넘으면(잘게 흩어진 곳) null 이다. 고를 때 한 번 만들고, 확대와 이동은 transform 으로만 바꾼다.
|
|
916
|
+
*/
|
|
917
|
+
function outlineOf(m, W, H, b) {
|
|
918
|
+
const at = (x, y) => (x >= 0 && y >= 0 && x < W && y < H && m[y * W + x] ? 1 : 0);
|
|
919
|
+
const parts = [];
|
|
920
|
+
for (let y = b.y; y <= b.y + b.h; y += 1) {
|
|
921
|
+
let start = -1;
|
|
922
|
+
for (let x = b.x; x <= b.x + b.w; x += 1) {
|
|
923
|
+
const edge = x < b.x + b.w && at(x, y - 1) !== at(x, y);
|
|
924
|
+
if (edge && start < 0) start = x;
|
|
925
|
+
else if (!edge && start >= 0) { parts.push(`M${start} ${y}H${x}`); start = -1; }
|
|
926
|
+
}
|
|
927
|
+
if (parts.length > OUTLINE_MAX) return null;
|
|
928
|
+
}
|
|
929
|
+
for (let x = b.x; x <= b.x + b.w; x += 1) {
|
|
930
|
+
let start = -1;
|
|
931
|
+
for (let y = b.y; y <= b.y + b.h; y += 1) {
|
|
932
|
+
const edge = y < b.y + b.h && at(x - 1, y) !== at(x, y);
|
|
933
|
+
if (edge && start < 0) start = y;
|
|
934
|
+
else if (!edge && start >= 0) { parts.push(`M${x} ${start}V${y}`); start = -1; }
|
|
935
|
+
}
|
|
936
|
+
if (parts.length > OUTLINE_MAX) return null;
|
|
937
|
+
}
|
|
938
|
+
return parts.join('');
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
/** 둘러 그린 꼭짓점을 그림판 안으로 넣고, 겹친 것을 빼고, max 개까지 고르게 줄인다(3.3절의 꼭짓점 한도). */
|
|
942
|
+
function reducePoints(pts, max) {
|
|
943
|
+
const c = data.canvas;
|
|
944
|
+
const out = [];
|
|
945
|
+
for (const p of pts) {
|
|
946
|
+
const q = [r1(clamp(p[0], 0, c.width)), r1(clamp(p[1], 0, c.height))];
|
|
947
|
+
const last = out[out.length - 1];
|
|
948
|
+
if (!last || last[0] !== q[0] || last[1] !== q[1]) out.push(q);
|
|
949
|
+
}
|
|
950
|
+
if (out.length > 1 && out[0][0] === out[out.length - 1][0] && out[0][1] === out[out.length - 1][1]) out.pop();
|
|
951
|
+
if (out.length <= max) return out;
|
|
952
|
+
const step = out.length / max;
|
|
953
|
+
const kept = [];
|
|
954
|
+
for (let i = 0; i < max; i += 1) kept.push(out[Math.floor(i * step)]);
|
|
955
|
+
return kept;
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
/** 넓은 곳은 띄엄띄엄 본다. 보는 픽셀이 SAMPLE_MAX 를 넘지 않는 간격이다. */
|
|
959
|
+
const sampleStep = (b) => Math.max(1, Math.ceil(Math.sqrt((b.w * b.h) / SAMPLE_MAX)));
|
|
960
|
+
|
|
961
|
+
/** 고른 곳의 주된 색. 빨강, 초록, 파랑을 16 단계씩으로 묶어 많은 차례로 다섯까지다. share 는 고른 픽셀 가운데 그 색의 몫이다(투명한 픽셀은 색에 넣지 않는다). */
|
|
962
|
+
function colorsOf(px, s) {
|
|
963
|
+
const { box } = s;
|
|
964
|
+
const W = px.w;
|
|
965
|
+
const d = px.data;
|
|
966
|
+
const step = sampleStep(box);
|
|
967
|
+
const groups = new Map();
|
|
968
|
+
let n = 0;
|
|
969
|
+
for (let y = box.y; y < box.y + box.h; y += step) {
|
|
970
|
+
for (let x = box.x; x < box.x + box.w; x += step) {
|
|
971
|
+
const k = y * W + x;
|
|
972
|
+
if (!s.mask[k]) continue;
|
|
973
|
+
n += 1;
|
|
974
|
+
const i = k * 4;
|
|
975
|
+
if (d[i + 3] === 0) continue;
|
|
976
|
+
const key = ((d[i] >> 4) << 8) | ((d[i + 1] >> 4) << 4) | (d[i + 2] >> 4);
|
|
977
|
+
let g = groups.get(key);
|
|
978
|
+
if (!g) groups.set(key, (g = { n: 0, r: 0, g: 0, b: 0 }));
|
|
979
|
+
g.n += 1;
|
|
980
|
+
g.r += d[i];
|
|
981
|
+
g.g += d[i + 1];
|
|
982
|
+
g.b += d[i + 2];
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
return [...groups.values()].sort((a, b) => b.n - a.n).slice(0, 5).map((g) => ({ color: hexColor(g.r / g.n, g.g / g.n, g.b / g.n), share: Math.round((g.n / n) * 1000) / 1000 }));
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
/** 고른 곳에 실제로 보이는 조각(위에서 아래로). 픽셀마다 그곳에 보이는 맨 위 조각을 모은다. */
|
|
989
|
+
function underOf(s) {
|
|
990
|
+
const W = data.canvas.width;
|
|
991
|
+
const step = sampleStep(s.box);
|
|
992
|
+
const seen = new Set();
|
|
993
|
+
for (let y = s.box.y; y < s.box.y + s.box.h; y += step) {
|
|
994
|
+
for (let x = s.box.x; x < s.box.x + s.box.w; x += step) {
|
|
995
|
+
if (!s.mask[y * W + x]) continue;
|
|
996
|
+
const p = topPieceAt(x + 0.5, y + 0.5);
|
|
997
|
+
if (p) seen.add(p.id);
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
return data.pieces.filter((p) => seen.has(p.id)).map((p) => p.id).reverse();
|
|
1001
|
+
}
|
|
1002
|
+
|
|
1003
|
+
function colorAt(px, x, y) {
|
|
1004
|
+
const i = (y * px.w + x) * 4;
|
|
1005
|
+
return px.data[i + 3] === 0 ? null : hexColor(px.data[i], px.data[i + 1], px.data[i + 2]);
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
// ---- PNG 파일 ----
|
|
1009
|
+
|
|
1010
|
+
/** 파일 머리의 앞 바이트로 어떤 파일인지 짐작해 알림에 붙인다. */
|
|
1011
|
+
function kindWord(head) {
|
|
1012
|
+
if (head.startsWith('\xff\xd8\xff')) return `. ${t('This file is a JPEG image')}`;
|
|
1013
|
+
if (head.startsWith('GIF8')) return `. ${t('This file is a GIF image')}`;
|
|
1014
|
+
if (head.startsWith('RIFF') && head.slice(8, 12) === 'WEBP') return `. ${t('This file is a WebP image')}`;
|
|
1015
|
+
if (head.startsWith('BM')) return `. ${t('This file is a BMP image')}`;
|
|
1016
|
+
if (/^\s*<(\?xml|svg)/i.test(head)) return `. ${t('This file is an SVG image')}`;
|
|
1017
|
+
return '';
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
/**
|
|
1021
|
+
* 받은 파일을 보내기 전에 본다(4절). base64 글자만 있는지, PNG 표지와 IHDR, 너비와 높이(1 에서 limits.side), 파일 크기(limits.imageBytes).
|
|
1022
|
+
* 논리가 같은 것을 다시 보지만, 사람이 큰 파일을 넣고 오래 기다린 뒤 거절되지 않게 먼저 알린다.
|
|
1023
|
+
*/
|
|
1024
|
+
function checkPng(b64, lim) {
|
|
1025
|
+
if (typeof b64 !== 'string' || b64.length < 44 || !/^[A-Za-z0-9+/]+={0,2}$/.test(b64)) return { ok: false, why: t('Could not read the file. Add a PNG file') };
|
|
1026
|
+
let head;
|
|
1027
|
+
try { head = atob(b64.slice(0, 44)); } catch { return { ok: false, why: t('Could not read the file. Add a PNG file') }; }
|
|
1028
|
+
const byte = (i) => head.charCodeAt(i);
|
|
1029
|
+
if (!PNG_SIGN.every((v, i) => byte(i) === v)) return { ok: false, why: `${t('Only PNG files are accepted')}${kindWord(head)}` };
|
|
1030
|
+
if (head.slice(12, 16) !== 'IHDR') return { ok: false, why: t('Could not read the PNG header (IHDR)') };
|
|
1031
|
+
const u32 = (i) => byte(i) * 16777216 + byte(i + 1) * 65536 + byte(i + 2) * 256 + byte(i + 3);
|
|
1032
|
+
const width = u32(16);
|
|
1033
|
+
const height = u32(20);
|
|
1034
|
+
const bytes = Math.floor((b64.length * 3) / 4) - (b64.endsWith('==') ? 2 : b64.endsWith('=') ? 1 : 0);
|
|
1035
|
+
if (bytes > lim.imageBytes) return { ok: false, why: t('The file is too large ({size}, limit {limit})', { size: sizeText(bytes), limit: sizeText(lim.imageBytes) }) };
|
|
1036
|
+
if (width < 1 || height < 1 || width > lim.side || height > lim.side) return { ok: false, why: t('The picture is too large ({w}×{h}, longest side limit {side} pixels)', { w: width, h: height, side: lim.side }) };
|
|
1037
|
+
return { ok: true, width, height, bytes };
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
function readFileUrl(file) {
|
|
1041
|
+
return new Promise((resolve, reject) => {
|
|
1042
|
+
const r = new FileReader();
|
|
1043
|
+
r.onload = () => resolve(String(r.result));
|
|
1044
|
+
r.onerror = () => reject(new Error(t('Could not read the file')));
|
|
1045
|
+
r.readAsDataURL(file);
|
|
1046
|
+
});
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
/** 고른 파일, 놓은 파일, 붙여 넣은 파일을 받는다. 그림판이 없으면 그 그림으로 시작하고, 있으면 조각으로 올린다. */
|
|
1050
|
+
async function takeFile(file, purpose) {
|
|
1051
|
+
if (!file) return null;
|
|
1052
|
+
if (readOnly()) { toast(t('This screen is view only, so you cannot add pictures'), true); return null; }
|
|
1053
|
+
const lim = limits();
|
|
1054
|
+
if (typeof file.size === 'number' && file.size > lim.imageBytes) { toast(t('The file is too large ({size}, limit {limit})', { size: sizeText(file.size), limit: sizeText(lim.imageBytes) }), true); return null; }
|
|
1055
|
+
let url;
|
|
1056
|
+
try { url = await readFileUrl(file); } catch (err) { toast(err.message, true); return null; }
|
|
1057
|
+
return acceptDataUrl(file.name, url, purpose);
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
/** data: 주소로 읽은 파일. 머리(data:...;base64,)를 떼고 보낸다. */
|
|
1061
|
+
function acceptDataUrl(name, url, purpose) {
|
|
1062
|
+
const b64 = String(url).slice(String(url).indexOf(',') + 1);
|
|
1063
|
+
const chk = checkPng(b64, limits());
|
|
1064
|
+
if (!chk.ok) { toast(chk.why, true); return null; }
|
|
1065
|
+
const fileName = (String(name ?? '').trim() || 'picture.png').slice(0, 120);
|
|
1066
|
+
if (purpose === 'start' && !data?.canvas) {
|
|
1067
|
+
return send([{ op: 'canvas.start', input: { image: { name: fileName, data: b64 }, reason: `The person added the image file ${fileName} (${chk.width}×${chk.height}) on the screen` } }]);
|
|
1068
|
+
}
|
|
1069
|
+
return addPiece(fileName, b64);
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
async function addPiece(fileName, b64) {
|
|
1073
|
+
const name = fileName.replace(/\.png$/i, '').slice(0, 80);
|
|
1074
|
+
const res = await send([{ op: 'piece.add', as: '$올린조각', input: { image: { name: fileName, data: b64 }, name } }]);
|
|
1075
|
+
const id = res?.ids?.['$올린조각'];
|
|
1076
|
+
if (id && pieceById.has(id)) { setTool('piece'); selectPieces([id]); }
|
|
1077
|
+
return res;
|
|
1078
|
+
}
|
|
1079
|
+
|
|
1080
|
+
function chooseFile(purpose) {
|
|
1081
|
+
if (readOnly()) return;
|
|
1082
|
+
filePurpose = purpose;
|
|
1083
|
+
fileEl.value = '';
|
|
1084
|
+
fileEl.click();
|
|
1085
|
+
}
|
|
1086
|
+
fileEl.addEventListener('change', () => {
|
|
1087
|
+
const f = fileEl.files && fileEl.files[0];
|
|
1088
|
+
if (f) takeFile(f, filePurpose);
|
|
1089
|
+
});
|
|
1090
|
+
|
|
1091
|
+
const typing = (t) => t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.tagName === 'SELECT');
|
|
1092
|
+
const filesOf = (dt) => Array.from(dt?.files ?? []);
|
|
1093
|
+
window.addEventListener('dragover', (e) => {
|
|
1094
|
+
if (!filesOf(e.dataTransfer).length && !Array.from(e.dataTransfer?.types ?? []).includes('Files')) return;
|
|
1095
|
+
e.preventDefault();
|
|
1096
|
+
document.getElementById('drop')?.classList.add('over');
|
|
1097
|
+
});
|
|
1098
|
+
window.addEventListener('dragleave', () => { document.getElementById('drop')?.classList.remove('over'); });
|
|
1099
|
+
window.addEventListener('drop', (e) => {
|
|
1100
|
+
const f = filesOf(e.dataTransfer)[0];
|
|
1101
|
+
document.getElementById('drop')?.classList.remove('over');
|
|
1102
|
+
if (!f) return;
|
|
1103
|
+
e.preventDefault();
|
|
1104
|
+
takeFile(f, data?.canvas ? 'add' : 'start');
|
|
1105
|
+
});
|
|
1106
|
+
window.addEventListener('paste', (e) => {
|
|
1107
|
+
if (typing(e.target)) return;
|
|
1108
|
+
const files = filesOf(e.clipboardData);
|
|
1109
|
+
const f = files.find((x) => /png/i.test(x.type)) ?? files[0];
|
|
1110
|
+
if (!f) return;
|
|
1111
|
+
e.preventDefault();
|
|
1112
|
+
takeFile(f, data?.canvas ? 'add' : 'start');
|
|
1113
|
+
});
|
|
1114
|
+
|
|
1115
|
+
// ---- 그림 파일과 고른 모양의 base64 ----
|
|
1116
|
+
|
|
1117
|
+
/** 이 상태를 그리는 데 드는 이름(그림 파일 id 와 고른 모양의 key). 그리기 코드에 빈 글을 주고 무엇을 묻는지 본다. */
|
|
1118
|
+
function namesFor(body) {
|
|
1119
|
+
const need = new Set();
|
|
1120
|
+
if (!body?.canvas) return need;
|
|
1121
|
+
pdParts({ width: body.canvas.width, height: body.canvas.height, images: body.images, pieces: body.pieces }, (n) => { need.add(n); return ''; });
|
|
1122
|
+
return need;
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
/** 받은 글 가운데 지금 상태가 가리키지 않는 것은 버린다(그림 파일을 지운 뒤 수 MB 를 지니지 않게). */
|
|
1126
|
+
function dropUnused(body) {
|
|
1127
|
+
const keep = new Set((body?.images ?? []).map((im) => im.id));
|
|
1128
|
+
for (const p of body?.pieces ?? []) for (const s of p.clip.concat(p.holes)) if (s.kind === 'mask') keep.add(s.key);
|
|
1129
|
+
for (const r of body?.regions ?? []) if (r.shape?.kind === 'mask') keep.add(r.shape.key);
|
|
1130
|
+
for (const n of [...store.keys()]) if (!keep.has(n)) { store.delete(n); pixelCache.delete(n); }
|
|
1131
|
+
}
|
|
1132
|
+
|
|
1133
|
+
/** 이름들의 base64 를 받는다. 한 번에 받는 양이 반환 한도를 넘지 않게 나누고, 묶음이 실패하면 하나씩 다시 받는다. */
|
|
1134
|
+
async function loadNames(names, body = data) {
|
|
1135
|
+
const want = [...new Set(names)].filter((n) => !store.has(n));
|
|
1136
|
+
if (!want.length) return;
|
|
1137
|
+
const charsOf = (n) => { const im = (body?.images ?? []).find((x) => x.id === n); return im ? Math.ceil(im.bytes / 3) * 4 : MASK_GUESS; };
|
|
1138
|
+
const batches = [];
|
|
1139
|
+
let cur = [];
|
|
1140
|
+
let size = 0;
|
|
1141
|
+
for (const n of want) {
|
|
1142
|
+
const c = charsOf(n);
|
|
1143
|
+
if (cur.length && size + c > DATA_BATCH) { batches.push(cur); cur = []; size = 0; }
|
|
1144
|
+
cur.push(n);
|
|
1145
|
+
size += c;
|
|
1146
|
+
}
|
|
1147
|
+
if (cur.length) batches.push(cur);
|
|
1148
|
+
const fetchBatch = async (list) => {
|
|
1149
|
+
const r = await call('readConcept', { targets: list.map((n) => `data:${n}`) });
|
|
1150
|
+
if (!r || r.ok === false) throw new Error((r && (r.summary || r.error)) || t('Could not read'));
|
|
1151
|
+
const got = { ...(r.body?.data ?? {}), ...(r.withOthers?.data ?? {}) };
|
|
1152
|
+
for (const n of list) if (typeof got[n] === 'string') { store.set(n, got[n]); missing.delete(n); }
|
|
1153
|
+
};
|
|
1154
|
+
for (const list of batches) {
|
|
1155
|
+
try {
|
|
1156
|
+
await fetchBatch(list);
|
|
1157
|
+
} catch (err) {
|
|
1158
|
+
if (list.length === 1) { missing.add(list[0]); missingNote = err.message; continue; }
|
|
1159
|
+
for (const n of list) {
|
|
1160
|
+
try { await fetchBatch([n]); } catch (e) { missing.add(n); missingNote = e.message; }
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
1163
|
+
}
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1166
|
+
const dataOf = (name) => store.get(name) ?? '';
|
|
1167
|
+
|
|
1168
|
+
// ---- 픽셀 ----
|
|
1169
|
+
// 그림 파일마다의 픽셀(눌린 조각 찾기)과 지금 보이는 그림 전체의 픽셀(비슷한 색과 색 알아내기)이다(9절). 둘 다 필요할 때 처음 한 번 만든다.
|
|
1170
|
+
|
|
1171
|
+
const pixelCache = new Map(); // 이름에서 { ready, promise } 로. ready 는 다 읽은 { w, h, data } 다
|
|
1172
|
+
|
|
1173
|
+
function loadImage(url) {
|
|
1174
|
+
return new Promise((resolve, reject) => {
|
|
1175
|
+
if (typeof Image !== 'function') { reject(new Error(t('This screen cannot open pictures'))); return; }
|
|
1176
|
+
const img = new Image();
|
|
1177
|
+
img.onload = () => {
|
|
1178
|
+
// 그림 안의 그림까지 다 풀린 뒤 canvas 에 그린다
|
|
1179
|
+
const done = () => resolve(img);
|
|
1180
|
+
if (typeof img.decode === 'function') img.decode().then(done, done);
|
|
1181
|
+
else done();
|
|
1182
|
+
};
|
|
1183
|
+
img.onerror = () => reject(new Error(t('Could not open the picture')));
|
|
1184
|
+
img.src = url;
|
|
1185
|
+
});
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
function canvasPixels(img, w, h) {
|
|
1189
|
+
const cv = document.createElement('canvas');
|
|
1190
|
+
cv.width = w;
|
|
1191
|
+
cv.height = h;
|
|
1192
|
+
const ctx = cv.getContext('2d', { willReadFrequently: true });
|
|
1193
|
+
ctx.drawImage(img, 0, 0, w, h);
|
|
1194
|
+
return { w, h, data: ctx.getImageData(0, 0, w, h).data };
|
|
1195
|
+
}
|
|
1196
|
+
|
|
1197
|
+
/** 그림 파일이나 고른 모양 PNG 하나의 픽셀. 읽지 못하면 null 이다. */
|
|
1198
|
+
function pixelsOf(name, w, h) {
|
|
1199
|
+
let job = pixelCache.get(name);
|
|
1200
|
+
if (!job) {
|
|
1201
|
+
const b64 = store.get(name);
|
|
1202
|
+
if (!b64) return Promise.resolve(null);
|
|
1203
|
+
job = { ready: null, promise: null };
|
|
1204
|
+
job.promise = loadImage(`data:image/png;base64,${b64}`).then((img) => (job.ready = canvasPixels(img, w, h))).catch(() => { if (pixelCache.get(name) === job) pixelCache.delete(name); return null; });
|
|
1205
|
+
pixelCache.set(name, job);
|
|
1206
|
+
}
|
|
1207
|
+
return job.promise;
|
|
1208
|
+
}
|
|
1209
|
+
const pixReady = (name) => pixelCache.get(name)?.ready ?? null;
|
|
1210
|
+
|
|
1211
|
+
/** 눌린 조각을 찾는 데 드는 픽셀을 모두 읽는다(보이는 조각의 그림 파일과 고른 모양). */
|
|
1212
|
+
function ensureHitPixels() {
|
|
1213
|
+
const jobs = [];
|
|
1214
|
+
for (const p of data?.pieces ?? []) {
|
|
1215
|
+
if (p.hidden) continue;
|
|
1216
|
+
const im = imageById.get(p.image);
|
|
1217
|
+
if (im) jobs.push(pixelsOf(im.id, im.width, im.height));
|
|
1218
|
+
for (const s of p.clip.concat(p.holes)) if (s.kind === 'mask') jobs.push(pixelsOf(s.key, s.w, s.h));
|
|
1219
|
+
}
|
|
1220
|
+
return Promise.all(jobs);
|
|
1221
|
+
}
|
|
1222
|
+
|
|
1223
|
+
const sceneOf = (pieces = data.pieces) => ({ width: data.canvas.width, height: data.canvas.height, images: data.images, pieces });
|
|
1224
|
+
|
|
1225
|
+
/** SVG 글을 그림으로 열 data: 주소. 그림의 글은 숫자, id, base64 라 ASCII 이므로 보통 base64 로 싼다. */
|
|
1226
|
+
function svgDataUrl(svg) {
|
|
1227
|
+
return /^[\x00-\x7f]*$/.test(svg) ? `data:image/svg+xml;base64,${btoa(svg)}` : `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
|
|
1228
|
+
}
|
|
1229
|
+
|
|
1230
|
+
let comp = null; // { seq, w, h, data } 지금 보이는 그림 전체의 픽셀
|
|
1231
|
+
let compJob = null;
|
|
1232
|
+
/** 지금 보이는 그림 전체의 픽셀. 화면에 보인 것과 같은 SVG 글(pdSvg)을 그림으로 열어 그림판 크기의 canvas 에 그려 얻는다. */
|
|
1233
|
+
function compositePixels() {
|
|
1234
|
+
const seq = drawSeq;
|
|
1235
|
+
if (comp && comp.seq === seq) return Promise.resolve(comp);
|
|
1236
|
+
if (compJob && compJob.seq === seq) return compJob.promise;
|
|
1237
|
+
const c = data.canvas;
|
|
1238
|
+
const svg = pdSvg(sceneOf(), dataOf);
|
|
1239
|
+
const promise = loadImage(svgDataUrl(svg)).then((img) => {
|
|
1240
|
+
const out = { seq, ...canvasPixels(img, c.width, c.height) };
|
|
1241
|
+
if (drawSeq === seq) comp = out;
|
|
1242
|
+
return out;
|
|
1243
|
+
});
|
|
1244
|
+
compJob = { seq, promise };
|
|
1245
|
+
promise.catch(() => { if (compJob?.promise === promise) compJob = null; });
|
|
1246
|
+
return promise;
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1249
|
+
/** 그린 뒤 눌린 조각을 바로 찾을 수 있게 그림 파일의 픽셀을 미리 읽어 둔다. */
|
|
1250
|
+
function warmPixels() {
|
|
1251
|
+
if (!data?.canvas) return;
|
|
1252
|
+
ensureHitPixels().catch(() => {});
|
|
1253
|
+
}
|
|
1254
|
+
|
|
1255
|
+
// ---- 그림 ----
|
|
1256
|
+
|
|
1257
|
+
function setData(body) {
|
|
1258
|
+
data = body ?? null;
|
|
1259
|
+
pieceById = new Map((data?.pieces ?? []).map((p) => [p.id, p]));
|
|
1260
|
+
regionById = new Map((data?.regions ?? []).map((r) => [r.id, r]));
|
|
1261
|
+
imageById = new Map((data?.images ?? []).map((im) => [im.id, im]));
|
|
1262
|
+
const c = data?.canvas;
|
|
1263
|
+
const key = c ? `${c.id}:${c.width}x${c.height}` : null;
|
|
1264
|
+
if (key !== view.canvasKey) {
|
|
1265
|
+
// 다른 그림판이거나 크기가 바뀌었으면(자르기) 처음부터 맞추고 고른 것을 푼다
|
|
1266
|
+
view.canvasKey = key;
|
|
1267
|
+
view.auto = true;
|
|
1268
|
+
selection = null;
|
|
1269
|
+
}
|
|
1270
|
+
}
|
|
1271
|
+
|
|
1272
|
+
/** 그리기 전에 한 번 더 거른다. 그리는 태그 밖의 요소와 on 속성, #id 나 data:image/png 가 아닌 href, 다른 style 을 지운다. */
|
|
1273
|
+
function sanitizeSvg(root) {
|
|
1274
|
+
for (const n of Array.from(root.querySelectorAll('*'))) {
|
|
1275
|
+
if (!DRAW_TAGS.has(n.localName)) { n.remove(); continue; }
|
|
1276
|
+
for (const a of Array.from(n.attributes)) {
|
|
1277
|
+
const name = a.name.toLowerCase();
|
|
1278
|
+
const v = String(a.value ?? n.getAttribute(a.name) ?? '');
|
|
1279
|
+
if (name.startsWith('on')) n.removeAttribute(a.name);
|
|
1280
|
+
else if (/href$/.test(name) && !(v.startsWith('#') || v.startsWith('data:image/png;base64,'))) n.removeAttribute(a.name);
|
|
1281
|
+
else if (name === 'style' && v.replace(/\s+/g, '') !== 'mask-type:alpha') n.removeAttribute(a.name);
|
|
1282
|
+
else if (/url\(/i.test(v) && !/^url\(#[\w-]+\)$/.test(v.trim())) n.removeAttribute(a.name);
|
|
1283
|
+
}
|
|
1284
|
+
}
|
|
1285
|
+
}
|
|
1286
|
+
|
|
1287
|
+
/** SVG 조각 글을 그림 안의 한 곳(정의나 조각들)에 넣는다. HTML 로 읽지 않고 SVG 문서로 읽어 넣는다(innerHTML 을 쓰지 않는다). */
|
|
1288
|
+
function fillSvg(target, text) {
|
|
1289
|
+
if (!text) { target.replaceChildren(); return; }
|
|
1290
|
+
const doc = new DOMParser().parseFromString(`<svg xmlns="${SVG_NS}">${text}</svg>`, 'image/svg+xml');
|
|
1291
|
+
const root = doc.documentElement;
|
|
1292
|
+
if (!root || root.nodeName !== 'svg' || doc.getElementsByTagName('parsererror').length) throw new Error(t('Could not read the picture'));
|
|
1293
|
+
sanitizeSvg(root);
|
|
1294
|
+
const node = document.importNode(root, true);
|
|
1295
|
+
target.replaceChildren(...Array.from(node.childNodes));
|
|
1296
|
+
}
|
|
1297
|
+
|
|
1298
|
+
/** 조각들을 그린다. 바뀐 부분(그림 파일의 정의, 조각의 정의, 조각들)만 다시 넣는다. */
|
|
1299
|
+
function paintDrawing(pieces) {
|
|
1300
|
+
const c = data.canvas;
|
|
1301
|
+
const parts = pdParts(sceneOf(pieces), dataOf);
|
|
1302
|
+
const size = `${c.width}x${c.height}`;
|
|
1303
|
+
let changed = false;
|
|
1304
|
+
if (drawn.size !== size) {
|
|
1305
|
+
drawingEl.setAttribute('viewBox', `0 0 ${c.width} ${c.height}`);
|
|
1306
|
+
drawn.size = size;
|
|
1307
|
+
changed = true;
|
|
1308
|
+
}
|
|
1309
|
+
const defs = parts.imageDefs + parts.maskDefs;
|
|
1310
|
+
if (defs !== drawn.defs) { fillSvg(imageDefsEl, defs); drawn.defs = defs; changed = true; }
|
|
1311
|
+
if (parts.pieceDefs !== drawn.pieceDefs) { fillSvg(pieceDefsEl, parts.pieceDefs); drawn.pieceDefs = parts.pieceDefs; changed = true; }
|
|
1312
|
+
if (parts.body !== drawn.body) {
|
|
1313
|
+
fillSvg(piecesEl, parts.body);
|
|
1314
|
+
drawn.body = parts.body;
|
|
1315
|
+
pieceEls = new Map();
|
|
1316
|
+
for (const n of Array.from(piecesEl.querySelectorAll('[data-piece]'))) pieceEls.set(n.getAttribute('data-piece'), n);
|
|
1317
|
+
changed = true;
|
|
1318
|
+
}
|
|
1319
|
+
if (changed) drawSeq += 1;
|
|
1320
|
+
}
|
|
1321
|
+
|
|
1322
|
+
function drawPicture() {
|
|
1323
|
+
const has = Boolean(data?.canvas);
|
|
1324
|
+
startEl.hidden = has;
|
|
1325
|
+
mainEl.hidden = !has;
|
|
1326
|
+
barEl.hidden = !has;
|
|
1327
|
+
if (!has) {
|
|
1328
|
+
for (const n of [imageDefsEl, pieceDefsEl, piecesEl]) n.replaceChildren();
|
|
1329
|
+
drawn.defs = drawn.pieceDefs = drawn.body = drawn.size = null;
|
|
1330
|
+
pieceEls = new Map();
|
|
1331
|
+
return;
|
|
1332
|
+
}
|
|
1333
|
+
paintDrawing(data.pieces);
|
|
1334
|
+
if (view.auto) fit();
|
|
1335
|
+
else applyView();
|
|
1336
|
+
}
|
|
1337
|
+
|
|
1338
|
+
/** 오른쪽 칸의 조절 막대를 끄는 동안 그 조각의 색 바꾸기를 화면에서만 바꿔 그린다. */
|
|
1339
|
+
function paintPreview() {
|
|
1340
|
+
if (!data?.canvas) return;
|
|
1341
|
+
const pieces = preview ? data.pieces.map((p) => (p.id === preview.id ? { ...p, adjust: preview.adjust } : p)) : data.pieces;
|
|
1342
|
+
paintDrawing(pieces);
|
|
1343
|
+
}
|
|
1344
|
+
|
|
1345
|
+
const stageSize = () => ({ w: stage.clientWidth || 0, h: stage.clientHeight || 0 });
|
|
1346
|
+
|
|
1347
|
+
/** 그림 전체가 칸에 들어오게 한다. 고른 뒤에 뜨는 칸이 그림을 가리지 않게 위쪽은 비워 둔다. */
|
|
1348
|
+
function fit() {
|
|
1349
|
+
const c = data?.canvas;
|
|
1350
|
+
if (!c) return;
|
|
1351
|
+
view.auto = true;
|
|
1352
|
+
const { w, h } = stageSize();
|
|
1353
|
+
if (!(w > 0 && h > 0)) { applyView(); return; }
|
|
1354
|
+
const skip = !readOnly() && h - TALK_ZONE >= 160 ? TALK_ZONE : 0;
|
|
1355
|
+
const room = h - skip;
|
|
1356
|
+
const pad = Math.max(8, Math.min(32, w * 0.06, room * 0.06));
|
|
1357
|
+
const z = clamp(Math.min((w - 2 * pad) / c.width, (room - 2 * pad) / c.height), ZOOM_MIN, ZOOM_MAX);
|
|
1358
|
+
view.zoom = z;
|
|
1359
|
+
view.x = (w - c.width * z) / 2;
|
|
1360
|
+
view.y = skip + (room - c.height * z) / 2;
|
|
1361
|
+
applyView();
|
|
1362
|
+
}
|
|
1363
|
+
|
|
1364
|
+
function applyView() {
|
|
1365
|
+
const c = data?.canvas;
|
|
1366
|
+
if (!c) return;
|
|
1367
|
+
paper.style.left = `${view.x}px`;
|
|
1368
|
+
paper.style.top = `${view.y}px`;
|
|
1369
|
+
paper.style.width = `${c.width * view.zoom}px`;
|
|
1370
|
+
paper.style.height = `${c.height * view.zoom}px`;
|
|
1371
|
+
paper.classList.toggle('px', view.zoom >= PIXELATED_AT);
|
|
1372
|
+
if (bar.zoomText) bar.zoomText.textContent = `${Math.round(view.zoom * 100)}%`;
|
|
1373
|
+
drawOverlay();
|
|
1374
|
+
}
|
|
1375
|
+
|
|
1376
|
+
/** 칸 안의 화면 위치 (px, py) 를 그대로 두고 확대하거나 줄인다. 위치를 주지 않으면 칸 가운데다. */
|
|
1377
|
+
function zoomAt(factor, px, py) {
|
|
1378
|
+
if (!data?.canvas) return;
|
|
1379
|
+
const { w, h } = stageSize();
|
|
1380
|
+
const cx = px ?? w / 2;
|
|
1381
|
+
const cy = py ?? h / 2;
|
|
1382
|
+
const z = clamp(view.zoom * factor, ZOOM_MIN, ZOOM_MAX);
|
|
1383
|
+
const gx = (cx - view.x) / view.zoom;
|
|
1384
|
+
const gy = (cy - view.y) / view.zoom;
|
|
1385
|
+
view.zoom = z;
|
|
1386
|
+
view.x = cx - gx * z;
|
|
1387
|
+
view.y = cy - gy * z;
|
|
1388
|
+
view.auto = false;
|
|
1389
|
+
applyView();
|
|
1390
|
+
}
|
|
1391
|
+
|
|
1392
|
+
/** 그림판 위치의 사각형이 칸에 보이게 가운데로 옮긴다. */
|
|
1393
|
+
function showRect(r) {
|
|
1394
|
+
const { w, h } = stageSize();
|
|
1395
|
+
if (!(w > 0 && h > 0)) return;
|
|
1396
|
+
view.x = w / 2 - (r.x + r.w / 2) * view.zoom;
|
|
1397
|
+
view.y = h / 2 - (r.y + r.h / 2) * view.zoom;
|
|
1398
|
+
view.auto = false;
|
|
1399
|
+
applyView();
|
|
1400
|
+
}
|
|
1401
|
+
|
|
1402
|
+
/** 화면의 한 점(clientX, clientY)을 그림판 위치로. */
|
|
1403
|
+
function toDrawing(clientX, clientY) {
|
|
1404
|
+
const b = paper.getBoundingClientRect();
|
|
1405
|
+
return { x: (clientX - b.left) / view.zoom, y: (clientY - b.top) / view.zoom };
|
|
1406
|
+
}
|
|
1407
|
+
const sx = (x) => view.x + x * view.zoom;
|
|
1408
|
+
const sy = (y) => view.y + y * view.zoom;
|
|
1409
|
+
|
|
1410
|
+
// ---- 겹쳐 보기 ----
|
|
1411
|
+
|
|
1412
|
+
function svgEl(tag, attrs, text) {
|
|
1413
|
+
const n = document.createElementNS(SVG_NS, tag);
|
|
1414
|
+
for (const [k, v] of Object.entries(attrs ?? {})) if (v !== null && v !== undefined && v !== false) n.setAttribute(k, String(v));
|
|
1415
|
+
if (text !== undefined) n.textContent = text;
|
|
1416
|
+
return n;
|
|
1417
|
+
}
|
|
1418
|
+
|
|
1419
|
+
function screenRect(r, cls) {
|
|
1420
|
+
return svgEl('rect', { class: cls, x: sx(r.x), y: sy(r.y), width: Math.max(1, r.w * view.zoom), height: Math.max(1, r.h * view.zoom) });
|
|
1421
|
+
}
|
|
1422
|
+
|
|
1423
|
+
/** 이름표 글. 칸 위쪽 바깥에 두고, 위가 모자라면 안쪽 위에 둔다. */
|
|
1424
|
+
function nameText(r, text, cls = '') {
|
|
1425
|
+
const top = sy(r.y);
|
|
1426
|
+
return svgEl('text', { class: `ov-name${cls ? ` ${cls}` : ''}`, x: sx(r.x) + 2, y: top > 16 ? top - 5 : top + 14 }, text);
|
|
1427
|
+
}
|
|
1428
|
+
|
|
1429
|
+
function shapeOutline(s, cls) {
|
|
1430
|
+
if (s.kind === 'rect') return screenRect(s, cls);
|
|
1431
|
+
if (s.kind === 'ellipse') return svgEl('ellipse', { class: cls, cx: sx(s.cx), cy: sy(s.cy), rx: s.rx * view.zoom, ry: s.ry * view.zoom });
|
|
1432
|
+
if (s.kind === 'polygon') return svgEl('polygon', { class: cls, points: s.points.map((p) => `${sx(p[0])},${sy(p[1])}`).join(' ') });
|
|
1433
|
+
return screenRect(s, cls);
|
|
1434
|
+
}
|
|
1435
|
+
|
|
1436
|
+
function regionMarks() {
|
|
1437
|
+
const out = [];
|
|
1438
|
+
for (const r of data.regions ?? []) {
|
|
1439
|
+
out.push(shapeOutline(r.shape, 'ov-region'));
|
|
1440
|
+
out.push(nameText(r.box, r.name || r.id, 'region'));
|
|
1441
|
+
}
|
|
1442
|
+
return out;
|
|
1443
|
+
}
|
|
1444
|
+
|
|
1445
|
+
function selectionMarks() {
|
|
1446
|
+
const s = selection;
|
|
1447
|
+
if (!s) return [];
|
|
1448
|
+
if (s.kind === 'pieces') {
|
|
1449
|
+
const out = [];
|
|
1450
|
+
const off = drag?.type === 'piece' && drag.items && drag.dw ? drag.dw : [0, 0];
|
|
1451
|
+
const moving = new Set((drag?.items ?? []).map((it) => it.id));
|
|
1452
|
+
for (const id of s.list) {
|
|
1453
|
+
const p = pieceById.get(id);
|
|
1454
|
+
if (!p?.box) continue;
|
|
1455
|
+
const o = moving.has(id) ? off : [0, 0];
|
|
1456
|
+
const r = { x: p.box.x + o[0], y: p.box.y + o[1], w: p.box.w, h: p.box.h };
|
|
1457
|
+
out.push(screenRect(r, 'ov-sel'));
|
|
1458
|
+
if (s.list.length <= MAX_SEL_NAMES) out.push(nameText(r, titleOf(p)));
|
|
1459
|
+
}
|
|
1460
|
+
return out;
|
|
1461
|
+
}
|
|
1462
|
+
if (s.kind === 'area') {
|
|
1463
|
+
if (!s.outline) return [screenRect(s.box, 'ov-area')];
|
|
1464
|
+
const transform = `translate(${view.x} ${view.y}) scale(${view.zoom})`;
|
|
1465
|
+
return [svgEl('path', { class: 'ov-ants a', d: s.outline, transform }), svgEl('path', { class: 'ov-ants b', d: s.outline, transform })];
|
|
1466
|
+
}
|
|
1467
|
+
const g = svgEl('g', { class: 'ov-mark' });
|
|
1468
|
+
const cx = sx(s.x + 0.5);
|
|
1469
|
+
const cy = sy(s.y + 0.5);
|
|
1470
|
+
g.append(svgEl('circle', { cx, cy, r: 6 }), svgEl('path', { d: `M${cx - 10} ${cy}H${cx + 10}M${cx} ${cy - 10}V${cy + 10}` }));
|
|
1471
|
+
return [g];
|
|
1472
|
+
}
|
|
1473
|
+
|
|
1474
|
+
function dragMarks() {
|
|
1475
|
+
const d = drag;
|
|
1476
|
+
if (!d || !d.moved) return [];
|
|
1477
|
+
if ((d.type === 'rect' || d.type === 'ellipse') && d.rect) return [d.type === 'rect' ? screenRect(d.rect, 'ov-rubber') : shapeOutline(ellipseOf(d.rect), 'ov-rubber')];
|
|
1478
|
+
if (d.type === 'lasso' && d.points.length > 1) return [svgEl('polygon', { class: 'ov-rubber', points: d.points.map((p) => `${sx(p[0])},${sy(p[1])}`).join(' ') })];
|
|
1479
|
+
return [];
|
|
1480
|
+
}
|
|
1481
|
+
|
|
1482
|
+
function drawOverlay() {
|
|
1483
|
+
const { w, h } = stageSize();
|
|
1484
|
+
overlay.setAttribute('width', String(w));
|
|
1485
|
+
overlay.setAttribute('height', String(h));
|
|
1486
|
+
const out = [];
|
|
1487
|
+
if (data?.canvas) {
|
|
1488
|
+
if (showRegions) out.push(...regionMarks());
|
|
1489
|
+
out.push(...selectionMarks(), ...dragMarks());
|
|
1490
|
+
}
|
|
1491
|
+
overlay.replaceChildren(...out);
|
|
1492
|
+
}
|
|
1493
|
+
|
|
1494
|
+
// 고른 곳은 그림판 크기의 canvas 에 아주 옅은 파랑(불투명도 0.15)으로 칠해 그림 위에 겹친다. 색을 바꾸는 화면이라 고른 곳의 원래
|
|
1495
|
+
// 색이 보여야 하기 때문이다. 고른 곳을 알게 하는 것은 겹쳐 보기 층의 가장자리 선이다(selectionMarks)
|
|
1496
|
+
let selPainted = null;
|
|
1497
|
+
function drawSelCanvas() {
|
|
1498
|
+
const c = data?.canvas;
|
|
1499
|
+
if (!c) return;
|
|
1500
|
+
const s = selection?.kind === 'area' ? selection : null;
|
|
1501
|
+
if (selCanvas.width !== c.width || selCanvas.height !== c.height) {
|
|
1502
|
+
selCanvas.width = c.width;
|
|
1503
|
+
selCanvas.height = c.height;
|
|
1504
|
+
selPainted = null;
|
|
1505
|
+
}
|
|
1506
|
+
const key = s ? s.mask : null;
|
|
1507
|
+
if (key === selPainted) return;
|
|
1508
|
+
const ctx = selCanvas.getContext('2d');
|
|
1509
|
+
if (!ctx) return;
|
|
1510
|
+
ctx.clearRect(0, 0, c.width, c.height);
|
|
1511
|
+
selPainted = key;
|
|
1512
|
+
if (!s) return;
|
|
1513
|
+
const W = c.width;
|
|
1514
|
+
const m = s.mask;
|
|
1515
|
+
const { x, y, w, h } = s.box;
|
|
1516
|
+
const img = ctx.createImageData(w, h);
|
|
1517
|
+
const d = img.data;
|
|
1518
|
+
for (let j = 0; j < h; j += 1) {
|
|
1519
|
+
for (let i = 0; i < w; i += 1) {
|
|
1520
|
+
if (!m[(y + j) * W + x + i]) continue;
|
|
1521
|
+
const o = (j * w + i) * 4;
|
|
1522
|
+
d[o] = 30; d[o + 1] = 144; d[o + 2] = 255; d[o + 3] = SEL_ALPHA;
|
|
1523
|
+
}
|
|
1524
|
+
}
|
|
1525
|
+
ctx.putImageData(img, x, y);
|
|
1526
|
+
}
|
|
1527
|
+
|
|
1528
|
+
// ---- 고르기 ----
|
|
1529
|
+
|
|
1530
|
+
const ellipseOf = (r) => ({ kind: 'ellipse', cx: r.x + r.w / 2, cy: r.y + r.h / 2, rx: r.w / 2, ry: r.h / 2 });
|
|
1531
|
+
|
|
1532
|
+
/** 조작의 where 모양(5.1절)을 그림판 위치의 모양으로. */
|
|
1533
|
+
function shapeOfWhere(w) {
|
|
1534
|
+
if (w.rect) return { kind: 'rect', x: w.rect[0], y: w.rect[1], w: w.rect[2], h: w.rect[3] };
|
|
1535
|
+
if (w.ellipse) return { kind: 'ellipse', cx: w.ellipse[0], cy: w.ellipse[1], rx: w.ellipse[2], ry: w.ellipse[3] };
|
|
1536
|
+
return { kind: 'polygon', points: w.polygon };
|
|
1537
|
+
}
|
|
1538
|
+
|
|
1539
|
+
const pickedPieces = () => (selection?.kind === 'pieces' ? selection.list : []);
|
|
1540
|
+
|
|
1541
|
+
function setSelection(s) {
|
|
1542
|
+
selection = s ? { gen: (selectionGen += 1), canvas: view.canvasKey, shared: null, ready: false, ...s } : null;
|
|
1543
|
+
if (selection?.kind === 'area') selection.outline = outlineOf(selection.mask, data.canvas.width, data.canvas.height, selection.box);
|
|
1544
|
+
drawSelCanvas();
|
|
1545
|
+
render();
|
|
1546
|
+
if (selection) fillInfo(selection);
|
|
1547
|
+
else notePick();
|
|
1548
|
+
}
|
|
1549
|
+
|
|
1550
|
+
function selectPieces(list) {
|
|
1551
|
+
const ids = list.filter((id) => pieceById.has(id)).slice(0, MAX_RECORDS);
|
|
1552
|
+
if (!ids.length) { setSelection(null); return; }
|
|
1553
|
+
const cur = pickedPieces();
|
|
1554
|
+
if (cur.length === ids.length && cur.every((id, i) => id === ids[i])) return;
|
|
1555
|
+
setSelection({ kind: 'pieces', list: ids });
|
|
1556
|
+
}
|
|
1557
|
+
|
|
1558
|
+
/** 고른 조각에 더하거나, 이미 들어 있으면 뺀다(여럿 고르기). */
|
|
1559
|
+
function togglePiece(id) {
|
|
1560
|
+
const cur = pickedPieces();
|
|
1561
|
+
if (!cur.length) { selectPieces([id]); return; }
|
|
1562
|
+
const next = cur.includes(id) ? cur.filter((x) => x !== id) : [...cur, id];
|
|
1563
|
+
if (next.length > MAX_RECORDS) { toast(t('You can select up to {max} pieces at once', { max: MAX_RECORDS }), true); return; }
|
|
1564
|
+
selectPieces(next);
|
|
1565
|
+
}
|
|
1566
|
+
|
|
1567
|
+
const modeOf = (e) => (e?.altKey ? 'sub' : e?.shiftKey ? 'add' : 'replace');
|
|
1568
|
+
const addKey = (e) => Boolean(e && (e.shiftKey || e.ctrlKey || e.metaKey));
|
|
1569
|
+
|
|
1570
|
+
/**
|
|
1571
|
+
* 도구로 고른 곳을 지금 고른 곳과 합친다. 처음 고르면 그 모양 그대로이고(how, shape, wand), 더하거나 빼면 섞어 고른 곳(mixed)이라
|
|
1572
|
+
* 고른 모양 PNG 로 보낸다(7.1절).
|
|
1573
|
+
*/
|
|
1574
|
+
function applyArea(mask, mode, meta) {
|
|
1575
|
+
const c = data.canvas;
|
|
1576
|
+
const cur = selection?.kind === 'area' ? selection : null;
|
|
1577
|
+
let out = mask;
|
|
1578
|
+
let how = meta.how;
|
|
1579
|
+
let shape = meta.shape ?? null;
|
|
1580
|
+
let wand = meta.wand ?? null;
|
|
1581
|
+
if (mode !== 'replace' && cur) {
|
|
1582
|
+
out = combineMasks(cur.mask, mask, mode);
|
|
1583
|
+
how = 'mixed';
|
|
1584
|
+
shape = null;
|
|
1585
|
+
wand = null;
|
|
1586
|
+
} else if (mode === 'sub') return;
|
|
1587
|
+
const info = maskInfo(out, c.width, c.height);
|
|
1588
|
+
if (!info.pixels) { if (selection) setSelection(null); toast(t('No pixels selected')); return; }
|
|
1589
|
+
setSelection({ kind: 'area', mask: out, box: info.box, pixels: info.pixels, how, shape, wand, region: null, colors: null, under: null });
|
|
1590
|
+
}
|
|
1591
|
+
|
|
1592
|
+
function rectFrom(a, b) {
|
|
1593
|
+
const c = data.canvas;
|
|
1594
|
+
const x0 = clamp(Math.round(Math.min(a.x, b.x)), 0, c.width);
|
|
1595
|
+
const x1 = clamp(Math.round(Math.max(a.x, b.x)), 0, c.width);
|
|
1596
|
+
const y0 = clamp(Math.round(Math.min(a.y, b.y)), 0, c.height);
|
|
1597
|
+
const y1 = clamp(Math.round(Math.max(a.y, b.y)), 0, c.height);
|
|
1598
|
+
return x1 > x0 && y1 > y0 ? { x: x0, y: y0, w: x1 - x0, h: y1 - y0 } : null;
|
|
1599
|
+
}
|
|
1600
|
+
|
|
1601
|
+
function rectArea(r, mode) {
|
|
1602
|
+
const c = data.canvas;
|
|
1603
|
+
applyArea(rectMask(c.width, c.height, r), mode, { how: 'rect', shape: { rect: [r.x, r.y, r.w, r.h] } });
|
|
1604
|
+
}
|
|
1605
|
+
|
|
1606
|
+
function ellipseArea(r, mode) {
|
|
1607
|
+
const c = data.canvas;
|
|
1608
|
+
const e = ellipseOf(r);
|
|
1609
|
+
applyArea(ellipseMask(c.width, c.height, e), mode, { how: 'ellipse', shape: { ellipse: [e.cx, e.cy, e.rx, e.ry] } });
|
|
1610
|
+
}
|
|
1611
|
+
|
|
1612
|
+
function lassoArea(points, mode) {
|
|
1613
|
+
const c = data.canvas;
|
|
1614
|
+
const pts = reducePoints(points, limits().points);
|
|
1615
|
+
if (pts.length < 3) return;
|
|
1616
|
+
applyArea(polygonMask(c.width, c.height, pts), mode, { how: 'lasso', shape: { polygon: pts } });
|
|
1617
|
+
}
|
|
1618
|
+
|
|
1619
|
+
async function wandAt(p, mode) {
|
|
1620
|
+
const c = data.canvas;
|
|
1621
|
+
const x = Math.floor(p.x);
|
|
1622
|
+
const y = Math.floor(p.y);
|
|
1623
|
+
if (!(x >= 0 && y >= 0 && x < c.width && y < c.height)) { toast(t('Click inside the canvas'), true); return; }
|
|
1624
|
+
let px;
|
|
1625
|
+
try { px = await compositePixels(); } catch (err) { toast(t("Could not read the picture's pixels: {error}", { error: err.message }), true); return; }
|
|
1626
|
+
if (!data?.canvas || px.w !== data.canvas.width || px.h !== data.canvas.height) return;
|
|
1627
|
+
const wand = { x, y, tolerance: wandOpt.tolerance, contiguous: wandOpt.contiguous };
|
|
1628
|
+
applyArea(wandMask(px, x, y, wand.tolerance, wand.contiguous), mode, { how: 'wand', wand });
|
|
1629
|
+
}
|
|
1630
|
+
|
|
1631
|
+
function selectPoint(p) {
|
|
1632
|
+
const c = data.canvas;
|
|
1633
|
+
const x = Math.floor(p.x);
|
|
1634
|
+
const y = Math.floor(p.y);
|
|
1635
|
+
if (!(x >= 0 && y >= 0 && x < c.width && y < c.height)) { if (selection) setSelection(null); return; }
|
|
1636
|
+
setSelection({ kind: 'point', x, y, color: null, piece: null });
|
|
1637
|
+
}
|
|
1638
|
+
|
|
1639
|
+
/** [고르기] 메뉴의 뒤집기. 고른 곳이 없으면 그림판 전체를 고른다. */
|
|
1640
|
+
function invertSelection() {
|
|
1641
|
+
const c = data?.canvas;
|
|
1642
|
+
if (!c) return;
|
|
1643
|
+
const cur = selection?.kind === 'area' ? selection : null;
|
|
1644
|
+
const out = cur ? invertMask(cur.mask) : new Uint8Array(c.width * c.height).fill(1);
|
|
1645
|
+
applyArea(out, 'replace', { how: 'mixed' });
|
|
1646
|
+
}
|
|
1647
|
+
|
|
1648
|
+
/** [고르기] 메뉴의 넓히기(sign 1)와 좁히기(sign -1). growBy 픽셀만큼이다. */
|
|
1649
|
+
function growSelection(sign) {
|
|
1650
|
+
const c = data?.canvas;
|
|
1651
|
+
const cur = selection?.kind === 'area' ? selection : null;
|
|
1652
|
+
if (!c || !cur) return;
|
|
1653
|
+
const n = clamp(Math.round(growBy) || 1, 1, GROW_MAX);
|
|
1654
|
+
const out = sign > 0 ? growMask(cur.mask, c.width, c.height, cur.box, n) : shrinkMask(cur.mask, c.width, c.height, cur.box, n);
|
|
1655
|
+
applyArea(out, 'replace', { how: 'mixed' });
|
|
1656
|
+
}
|
|
1657
|
+
|
|
1658
|
+
/** 저장된 영역의 모양을 고른 곳으로 한다. 고른 모양 PNG 는 받아서 그 알파로 칠한다. */
|
|
1659
|
+
async function regionMask(r) {
|
|
1660
|
+
const c = data.canvas;
|
|
1661
|
+
const s = r.shape;
|
|
1662
|
+
if (s.kind !== 'mask') return shapeMask(c.width, c.height, s);
|
|
1663
|
+
await loadNames([s.key]);
|
|
1664
|
+
const px = await pixelsOf(s.key, s.w, s.h);
|
|
1665
|
+
if (!px) return null;
|
|
1666
|
+
const m = new Uint8Array(c.width * c.height);
|
|
1667
|
+
const ox = Math.round(s.x);
|
|
1668
|
+
const oy = Math.round(s.y);
|
|
1669
|
+
for (let j = 0; j < s.h; j += 1) {
|
|
1670
|
+
const Y = oy + j;
|
|
1671
|
+
if (Y < 0 || Y >= c.height) continue;
|
|
1672
|
+
for (let i = 0; i < s.w; i += 1) {
|
|
1673
|
+
const X = ox + i;
|
|
1674
|
+
if (X >= 0 && X < c.width && px.data[(j * s.w + i) * 4 + 3] > 0) m[Y * c.width + X] = 1;
|
|
1675
|
+
}
|
|
1676
|
+
}
|
|
1677
|
+
return m;
|
|
1678
|
+
}
|
|
1679
|
+
|
|
1680
|
+
async function selectRegion(id) {
|
|
1681
|
+
const r = regionById.get(id);
|
|
1682
|
+
if (!r || !data?.canvas) return;
|
|
1683
|
+
const m = await regionMask(r);
|
|
1684
|
+
if (!m) { toast(t('Could not read the shape of the region'), true); return; }
|
|
1685
|
+
const c = data.canvas;
|
|
1686
|
+
const info = maskInfo(m, c.width, c.height);
|
|
1687
|
+
if (!info.pixels) { toast(t('This region has no pixels inside the canvas to select'), true); return; }
|
|
1688
|
+
const how = { rect: 'rect', ellipse: 'ellipse', polygon: 'lasso' }[r.shape.kind] ?? 'mixed';
|
|
1689
|
+
setSelection({ kind: 'area', mask: m, box: info.box, pixels: info.pixels, how, shape: null, wand: null, region: id, colors: null, under: null });
|
|
1690
|
+
}
|
|
1691
|
+
|
|
1692
|
+
/**
|
|
1693
|
+
* 고른 것의 색과 보이는 조각을 픽셀에서 채운다. 다 채우면 ready 가 참이 되고 코어에 고르기만 한 것을 알린다. 그 사이 다른 것을
|
|
1694
|
+
* 고르거나 그림이 바뀌면 그 결과는 버린다.
|
|
1695
|
+
*/
|
|
1696
|
+
function fillInfo(s) {
|
|
1697
|
+
const seq = drawSeq;
|
|
1698
|
+
s.infoSeq = seq;
|
|
1699
|
+
s.ready = false;
|
|
1700
|
+
const job = (async () => {
|
|
1701
|
+
if (s.kind === 'area' || s.kind === 'point') {
|
|
1702
|
+
try {
|
|
1703
|
+
const [px] = await Promise.all([compositePixels(), ensureHitPixels()]);
|
|
1704
|
+
if (selection !== s || s.infoSeq !== seq) return;
|
|
1705
|
+
if (s.kind === 'area') {
|
|
1706
|
+
s.colors = colorsOf(px, s);
|
|
1707
|
+
s.under = underOf(s);
|
|
1708
|
+
} else {
|
|
1709
|
+
s.color = colorAt(px, s.x, s.y);
|
|
1710
|
+
s.piece = topPieceAt(s.x + 0.5, s.y + 0.5)?.id ?? null;
|
|
1711
|
+
}
|
|
1712
|
+
} catch (err) {
|
|
1713
|
+
if (selection !== s || s.infoSeq !== seq) return;
|
|
1714
|
+
// 그림 전체의 픽셀을 읽지 못해도 보이는 조각은 그림 파일의 픽셀로 찾는다
|
|
1715
|
+
if (s.kind === 'area') { s.colors = []; s.under = underOf(s); } else { s.color = null; s.piece = topPieceAt(s.x + 0.5, s.y + 0.5)?.id ?? null; }
|
|
1716
|
+
toast(t("Could not read the picture's pixels: {error}", { error: err.message }), true);
|
|
1717
|
+
}
|
|
1718
|
+
}
|
|
1719
|
+
if (selection !== s || s.infoSeq !== seq) return;
|
|
1720
|
+
s.ready = true;
|
|
1721
|
+
render();
|
|
1722
|
+
notePick();
|
|
1723
|
+
})();
|
|
1724
|
+
s.wait = job;
|
|
1725
|
+
return job;
|
|
1726
|
+
}
|
|
1727
|
+
|
|
1728
|
+
/** 고른 것의 색과 보이는 조각이 다 채워질 때까지 기다린다. 그 사이 다른 것을 골랐으면 false 다. */
|
|
1729
|
+
async function readyOf(s) {
|
|
1730
|
+
while (selection === s && !s.ready && s.wait) {
|
|
1731
|
+
const w = s.wait;
|
|
1732
|
+
await w;
|
|
1733
|
+
if (s.wait === w && !s.ready) break;
|
|
1734
|
+
}
|
|
1735
|
+
return selection === s && s.ready;
|
|
1736
|
+
}
|
|
1737
|
+
|
|
1738
|
+
/** 다시 읽은 뒤 고른 것을 맞춘다. 지워진 조각은 빼고, 지워진 영역은 놓고, 그림이 바뀌었으면 색과 보이는 조각을 다시 채운다. */
|
|
1739
|
+
function reconcileSelection() {
|
|
1740
|
+
const s = selection;
|
|
1741
|
+
if (!s) return;
|
|
1742
|
+
if (s.kind === 'pieces') {
|
|
1743
|
+
const live = s.list.filter((id) => pieceById.has(id));
|
|
1744
|
+
if (live.length < s.list.length) toast(live.length ? t('Removed deleted pieces from the selection') : t('The selected pieces were deleted, so the selection was cleared'));
|
|
1745
|
+
if (!live.length) { selection = null; return; }
|
|
1746
|
+
s.list = live;
|
|
1747
|
+
s.ready = true;
|
|
1748
|
+
return;
|
|
1749
|
+
}
|
|
1750
|
+
if (s.kind === 'area' && s.region && !regionById.has(s.region)) s.region = null;
|
|
1751
|
+
if (s.infoSeq !== drawSeq) fillInfo(s);
|
|
1752
|
+
}
|
|
1753
|
+
|
|
1754
|
+
/** 조작의 where(5.1절). 모양 그대로, 저장된 영역의 id, 고른 모양 PNG 가운데 하나다. 고른 모양이 한도를 넘으면 알리고 null 이다. */
|
|
1755
|
+
function whereOf(s) {
|
|
1756
|
+
if (s.shape) return s.shape;
|
|
1757
|
+
if (s.region && regionById.has(s.region)) return s.region;
|
|
1758
|
+
return maskWhere(s);
|
|
1759
|
+
}
|
|
1760
|
+
|
|
1761
|
+
/**
|
|
1762
|
+
* 고른 곳을 감싸는 사각형 크기의 PNG. 고른 픽셀은 검정에 알파 255, 아니면 알파 0 이다(3.2절). 보이는 곳(알파로 읽는 mask)과 지운 곳
|
|
1763
|
+
* (흰 바탕에 검정으로 덮는 mask) 모두에 이 PNG 하나를 쓴다.
|
|
1764
|
+
*/
|
|
1765
|
+
function maskPng(s) {
|
|
1766
|
+
const W = data.canvas.width;
|
|
1767
|
+
const { x, y, w, h } = s.box;
|
|
1768
|
+
const cv = document.createElement('canvas');
|
|
1769
|
+
cv.width = w;
|
|
1770
|
+
cv.height = h;
|
|
1771
|
+
const ctx = cv.getContext('2d');
|
|
1772
|
+
const img = ctx.createImageData(w, h);
|
|
1773
|
+
for (let j = 0; j < h; j += 1) for (let i = 0; i < w; i += 1) if (s.mask[(y + j) * W + x + i]) img.data[(j * w + i) * 4 + 3] = 255;
|
|
1774
|
+
ctx.putImageData(img, 0, 0);
|
|
1775
|
+
const url = cv.toDataURL('image/png');
|
|
1776
|
+
return url.slice(url.indexOf(',') + 1);
|
|
1777
|
+
}
|
|
1778
|
+
|
|
1779
|
+
function maskWhere(s) {
|
|
1780
|
+
const png = maskPng(s);
|
|
1781
|
+
const max = limits().maskChars;
|
|
1782
|
+
if (png.length > max) {
|
|
1783
|
+
toast(t('The selected shape is too large (PNG {size} characters, limit {max} characters). Select a smaller area, or use Rectangle or Freehand', { size: comma(png.length), max: comma(max) }), true);
|
|
1784
|
+
return null;
|
|
1785
|
+
}
|
|
1786
|
+
return { mask: { x: s.box.x, y: s.box.y, w: s.box.w, h: s.box.h, data: png } };
|
|
1787
|
+
}
|
|
1788
|
+
|
|
1789
|
+
/** 보낼 선택 내용(aic.png/selection-1, 7.2절). */
|
|
1790
|
+
function payloadOf(s) {
|
|
1791
|
+
if (s.kind === 'pieces') {
|
|
1792
|
+
const list = s.list.slice(0, MAX_RECORDS);
|
|
1793
|
+
return { format: SELECTION_FORMAT, kind: 'pieces', pieces: list, labels: list.map((id) => { const p = pieceById.get(id); return p ? labelOf(p) : id; }) };
|
|
1794
|
+
}
|
|
1795
|
+
if (s.kind === 'point') return { format: SELECTION_FORMAT, kind: 'point', x: s.x, y: s.y, color: s.color ?? null, piece: s.piece ?? null };
|
|
1796
|
+
const region = s.region && regionById.has(s.region) ? s.region : null;
|
|
1797
|
+
const where = s.shape ?? region;
|
|
1798
|
+
const p = { format: SELECTION_FORMAT, kind: 'area', where: where ?? null, region, unsaved: !where, how: s.how };
|
|
1799
|
+
if (s.how === 'wand' && s.wand) p.wand = { ...s.wand };
|
|
1800
|
+
p.box = [s.box.x, s.box.y, s.box.w, s.box.h];
|
|
1801
|
+
p.pixels = s.pixels;
|
|
1802
|
+
p.colors = (s.colors ?? []).map((c) => ({ ...c }));
|
|
1803
|
+
p.under = (s.under ?? []).slice(0, MAX_RECORDS);
|
|
1804
|
+
return p;
|
|
1805
|
+
}
|
|
1806
|
+
|
|
1807
|
+
function recordsOf(p) {
|
|
1808
|
+
if (p.kind === 'pieces') return p.pieces.slice(0, MAX_RECORDS);
|
|
1809
|
+
if (p.kind === 'point') return p.piece ? [p.piece] : [];
|
|
1810
|
+
return [...(p.region ? [p.region] : []), ...p.under].slice(0, MAX_RECORDS);
|
|
1811
|
+
}
|
|
1812
|
+
|
|
1813
|
+
/**
|
|
1814
|
+
* 고르기만 하고 아직 보내지 않은 것을 코어에 알린다(setPick, plugin-guide 4.4절). 고른 것이 바뀔 때마다(끌기가 끝났을 때 한 번),
|
|
1815
|
+
* 색과 보이는 조각을 다 채운 뒤 알린다. 고른 것이 없어지면 null 로 지운다. 같은 내용은 다시 알리지 않는다. 보낸 선택은 코어가 고른
|
|
1816
|
+
* 것을 지우고 대신하므로 알리지 않는다. 픽셀로 고른 곳은 저장하지 않으므로 unsaved 로 알린다(7.2절).
|
|
1817
|
+
*/
|
|
1818
|
+
function notePick() {
|
|
1819
|
+
if (!caps.conceptPick || readOnly() || !drawnBase) return;
|
|
1820
|
+
const s = selection && !selection.shared ? selection : null;
|
|
1821
|
+
if (s && !s.ready) return;
|
|
1822
|
+
const p = s ? payloadOf(s) : null;
|
|
1823
|
+
const key = p ? JSON.stringify(p) : null;
|
|
1824
|
+
if (key === pickSent) return;
|
|
1825
|
+
pickSent = key;
|
|
1826
|
+
call('setPick', p ? { base: drawnBase, payload: p, records: recordsOf(p) } : null).catch(() => {});
|
|
1827
|
+
}
|
|
1828
|
+
|
|
1829
|
+
// ---- 끌기 ----
|
|
1830
|
+
|
|
1831
|
+
/** [조각 고르기] 로 누른 곳의 조각. 그림 파일의 픽셀을 처음 읽는 동안은 기다린다. */
|
|
1832
|
+
async function pieceHit(x, y) {
|
|
1833
|
+
try { await ensureHitPixels(); } catch {}
|
|
1834
|
+
return topPieceAt(x, y)?.id ?? null;
|
|
1835
|
+
}
|
|
1836
|
+
|
|
1837
|
+
/** 누른 조각을 끌 준비. 고르지 않은 조각을 누르면 그 조각만 고르고, 고른 것 가운데 하나를 누르면 고른 것 모두를 끈다. */
|
|
1838
|
+
function preparePieceDrag(d) {
|
|
1839
|
+
if (d.add || !d.hit || readOnly()) return;
|
|
1840
|
+
let list = pickedPieces();
|
|
1841
|
+
if (!list.includes(d.hit)) { selectPieces([d.hit]); list = [d.hit]; d.selected = true; }
|
|
1842
|
+
d.items = list.map((id) => ({ id, el: pieceEls.get(id) })).filter((it) => it.el);
|
|
1843
|
+
for (const it of d.items) it.orig = it.el.getAttribute('transform');
|
|
1844
|
+
}
|
|
1845
|
+
|
|
1846
|
+
function startDrag(e) {
|
|
1847
|
+
if (!data?.canvas || drag) return;
|
|
1848
|
+
const panning = e.button === 1 || tool === 'pan' || spaceDown;
|
|
1849
|
+
if (!panning && e.button !== 0) return;
|
|
1850
|
+
if (e.preventDefault) e.preventDefault();
|
|
1851
|
+
if (stage.focus) stage.focus({ preventScroll: true });
|
|
1852
|
+
if (openMenu) setMenu(null);
|
|
1853
|
+
const p = toDrawing(e.clientX, e.clientY);
|
|
1854
|
+
const start = { cx: e.clientX, cy: e.clientY, p };
|
|
1855
|
+
if (panning) drag = { type: 'pan', start, vx: view.x, vy: view.y, moved: false };
|
|
1856
|
+
else if (tool === 'piece') {
|
|
1857
|
+
const d = { type: 'piece', start, add: addKey(e), moved: false, hit: undefined, items: null, dw: [0, 0] };
|
|
1858
|
+
drag = d;
|
|
1859
|
+
d.wait = pieceHit(p.x, p.y).then((hit) => { d.hit = hit; preparePieceDrag(d); return hit; });
|
|
1860
|
+
} else drag = { type: tool, start, mode: modeOf(e), moved: false, points: tool === 'lasso' ? [[p.x, p.y]] : null, rect: null };
|
|
1861
|
+
stage.classList.toggle('dragging', drag.type === 'pan');
|
|
1862
|
+
try { stage.setPointerCapture(e.pointerId); } catch {}
|
|
1863
|
+
}
|
|
1864
|
+
|
|
1865
|
+
function moveDrag(e) {
|
|
1866
|
+
const d = drag;
|
|
1867
|
+
if (!d) return;
|
|
1868
|
+
const dx = e.clientX - d.start.cx;
|
|
1869
|
+
const dy = e.clientY - d.start.cy;
|
|
1870
|
+
if (!d.moved && Math.hypot(dx, dy) < DRAG_PX) return;
|
|
1871
|
+
d.moved = true;
|
|
1872
|
+
const p = toDrawing(e.clientX, e.clientY);
|
|
1873
|
+
if (d.type === 'pan') {
|
|
1874
|
+
view.x = d.vx + dx;
|
|
1875
|
+
view.y = d.vy + dy;
|
|
1876
|
+
view.auto = false;
|
|
1877
|
+
applyView();
|
|
1878
|
+
} else if (d.type === 'piece') {
|
|
1879
|
+
// 끄는 동안은 그린 조각의 transform 앞에 옮길 거리만 붙여 미리 보인다. 놓으면 원래대로 두고 조작을 보낸다.
|
|
1880
|
+
// 조각은 픽셀 그림이라 흐려지지 않게 픽셀 단위로 옮긴다
|
|
1881
|
+
if (!d.items?.length) return;
|
|
1882
|
+
d.dw = [Math.round(dx / view.zoom), Math.round(dy / view.zoom)];
|
|
1883
|
+
for (const it of d.items) it.el.setAttribute('transform', `translate(${d.dw[0]} ${d.dw[1]})${it.orig ? ` ${it.orig}` : ''}`);
|
|
1884
|
+
drawOverlay();
|
|
1885
|
+
} else if (d.type === 'rect' || d.type === 'ellipse') {
|
|
1886
|
+
d.rect = rectFrom(d.start.p, p);
|
|
1887
|
+
drawOverlay();
|
|
1888
|
+
} else if (d.type === 'lasso') {
|
|
1889
|
+
const last = d.points[d.points.length - 1];
|
|
1890
|
+
if (Math.hypot((p.x - last[0]) * view.zoom, (p.y - last[1]) * view.zoom) >= LASSO_PX) d.points.push([p.x, p.y]);
|
|
1891
|
+
drawOverlay();
|
|
1892
|
+
}
|
|
1893
|
+
}
|
|
1894
|
+
|
|
1895
|
+
async function finishDrag(d) {
|
|
1896
|
+
if (!data?.canvas) return;
|
|
1897
|
+
if (d.type === 'piece') {
|
|
1898
|
+
const hit = await d.wait;
|
|
1899
|
+
if (d.moved && d.items?.length) { if (d.dw[0] || d.dw[1]) await sendMove(d.items.map((it) => it.id), d.dw[0], d.dw[1]); return; }
|
|
1900
|
+
if (d.add) { if (hit) togglePiece(hit); return; }
|
|
1901
|
+
if (!hit) { if (selection) setSelection(null); return; }
|
|
1902
|
+
selectPieces([hit]);
|
|
1903
|
+
return;
|
|
1904
|
+
}
|
|
1905
|
+
if (d.type === 'wand') { if (!d.moved) await wandAt(d.start.p, d.mode); return; }
|
|
1906
|
+
if (d.type === 'rect' || d.type === 'ellipse') {
|
|
1907
|
+
if (d.moved && d.rect) { if (d.type === 'rect') rectArea(d.rect, d.mode); else ellipseArea(d.rect, d.mode); return; }
|
|
1908
|
+
if (!d.moved && d.mode === 'replace') selectPoint(d.start.p);
|
|
1909
|
+
return;
|
|
1910
|
+
}
|
|
1911
|
+
if (d.type === 'lasso') {
|
|
1912
|
+
if (d.moved && d.points.length >= 3) lassoArea(d.points, d.mode);
|
|
1913
|
+
else if (!d.moved && d.mode === 'replace') selectPoint(d.start.p);
|
|
1914
|
+
}
|
|
1915
|
+
}
|
|
1916
|
+
|
|
1917
|
+
async function endDrag(e, cancel = false) {
|
|
1918
|
+
const d = drag;
|
|
1919
|
+
if (!d) return;
|
|
1920
|
+
drag = null;
|
|
1921
|
+
stage.classList.remove('dragging');
|
|
1922
|
+
try { stage.releasePointerCapture(e.pointerId); } catch {}
|
|
1923
|
+
if (d.type === 'piece' && d.items) {
|
|
1924
|
+
for (const it of d.items) {
|
|
1925
|
+
if (it.orig === null) it.el.removeAttribute('transform');
|
|
1926
|
+
else it.el.setAttribute('transform', it.orig);
|
|
1927
|
+
}
|
|
1928
|
+
}
|
|
1929
|
+
if (!cancel) {
|
|
1930
|
+
try { await finishDrag(d); } catch (err) { toast(err.message, true); }
|
|
1931
|
+
}
|
|
1932
|
+
drawOverlay();
|
|
1933
|
+
if (pendingRefresh && !drag) {
|
|
1934
|
+
pendingRefresh = false;
|
|
1935
|
+
refresh();
|
|
1936
|
+
}
|
|
1937
|
+
}
|
|
1938
|
+
|
|
1939
|
+
stage.addEventListener('pointerdown', startDrag);
|
|
1940
|
+
stage.addEventListener('pointermove', moveDrag);
|
|
1941
|
+
stage.addEventListener('pointerup', (e) => { endDrag(e); });
|
|
1942
|
+
stage.addEventListener('pointercancel', (e) => { endDrag(e, true); });
|
|
1943
|
+
stage.addEventListener('wheel', (e) => {
|
|
1944
|
+
if (!data?.canvas) return;
|
|
1945
|
+
e.preventDefault();
|
|
1946
|
+
const b = stage.getBoundingClientRect();
|
|
1947
|
+
const step = e.deltaMode === 1 ? e.deltaY * 16 : e.deltaY;
|
|
1948
|
+
zoomAt(Math.exp(-clamp(step, -120, 120) * 0.0022), e.clientX - b.left - (stage.clientLeft || 0), e.clientY - b.top - (stage.clientTop || 0));
|
|
1949
|
+
}, { passive: false });
|
|
1950
|
+
stage.addEventListener('keydown', (e) => {
|
|
1951
|
+
if (e.key === 'Escape') { if (selection) setSelection(null); }
|
|
1952
|
+
else if (e.key === '+' || e.key === '=') zoomAt(1.25);
|
|
1953
|
+
else if (e.key === '-') zoomAt(0.8);
|
|
1954
|
+
else if (e.key === '0') fit();
|
|
1955
|
+
else return;
|
|
1956
|
+
e.preventDefault();
|
|
1957
|
+
});
|
|
1958
|
+
window.addEventListener('keydown', (e) => {
|
|
1959
|
+
if (e.key === 'Escape' && openMenu) { const m = bar.menus[openMenu]; setMenu(null); m.b.focus(); return; }
|
|
1960
|
+
if (e.code === 'Space' && !typing(e.target)) { spaceDown = true; stage.classList.add('panning'); if (e.target === stage) e.preventDefault(); }
|
|
1961
|
+
});
|
|
1962
|
+
window.addEventListener('keyup', (e) => {
|
|
1963
|
+
if (e.code === 'Space') { spaceDown = false; stage.classList.remove('panning'); }
|
|
1964
|
+
});
|
|
1965
|
+
|
|
1966
|
+
// ---- 호스트 ----
|
|
1967
|
+
|
|
1968
|
+
let inflight = null;
|
|
1969
|
+
let again = false;
|
|
1970
|
+
/**
|
|
1971
|
+
* 다시 읽어 그린다. 읽는 중에 온 바뀜은 모아 두었다가 한 번만 다시 읽는다(plugin-guide 4.3절). 그림 파일과 고른 모양 가운데 아직
|
|
1972
|
+
* 없는 것을 먼저 받고 그린 뒤 그렸다고 알린다(rendered).
|
|
1973
|
+
*/
|
|
1974
|
+
function refresh() {
|
|
1975
|
+
if (inflight) { again = true; return inflight; }
|
|
1976
|
+
inflight = (async () => {
|
|
1977
|
+
try {
|
|
1978
|
+
const c = await call('readConcept');
|
|
1979
|
+
if (!c || c.ok === false) throw new Error((c && (c.summary || c.error)) || t('Could not read'));
|
|
1980
|
+
if (drag || sliding) { pendingRefresh = true; return; }
|
|
1981
|
+
const body = c.withOthers ?? c.body;
|
|
1982
|
+
missing.clear();
|
|
1983
|
+
missingNote = '';
|
|
1984
|
+
dropUnused(body);
|
|
1985
|
+
await loadNames([...namesFor(body)], body);
|
|
1986
|
+
if (drag || sliding) { pendingRefresh = true; return; }
|
|
1987
|
+
errorEl.hidden = true;
|
|
1988
|
+
// 다른 참여자(AI)의 아직 합쳐지지 않은 변경까지 얹은 상태를 그린다. 코어도 선택의 record 와 저장할 파일을 이 상태로 본다
|
|
1989
|
+
concept = { ...c, body };
|
|
1990
|
+
setData(body);
|
|
1991
|
+
preview = null;
|
|
1992
|
+
drawPicture();
|
|
1993
|
+
drawnBase = concept.base;
|
|
1994
|
+
reconcileSelection();
|
|
1995
|
+
render();
|
|
1996
|
+
if (missing.size) { errorEl.textContent = t('Could not load {names} (image files or selection shapes), so those parts are not drawn. {note}', { names: [...missing].join(', '), note: missingNote }); errorEl.hidden = false; }
|
|
1997
|
+
if (typeof c.renderToken === 'string') parent.postMessage({ aic: 1, event: 'rendered', token: c.renderToken }, '*');
|
|
1998
|
+
// 다시 읽으며 고른 것이 달라졌으면(지워진 조각이 빠짐) 코어에 알린 것도 맞춘다
|
|
1999
|
+
notePick();
|
|
2000
|
+
warmPixels();
|
|
2001
|
+
} catch (err) {
|
|
2002
|
+
errorEl.textContent = err.message;
|
|
2003
|
+
errorEl.hidden = false;
|
|
2004
|
+
}
|
|
2005
|
+
})().finally(() => {
|
|
2006
|
+
inflight = null;
|
|
2007
|
+
if (again) { again = false; refresh(); }
|
|
2008
|
+
});
|
|
2009
|
+
return inflight;
|
|
2010
|
+
}
|
|
2011
|
+
|
|
2012
|
+
/** 다시 읽기가 모두 끝날 때까지 기다린다. 읽는 중에 다시 읽기를 청했으면 그것까지 기다린다. */
|
|
2013
|
+
async function settle() {
|
|
2014
|
+
await refresh();
|
|
2015
|
+
while (inflight) await inflight;
|
|
2016
|
+
}
|
|
2017
|
+
|
|
2018
|
+
let toastTimer = null;
|
|
2019
|
+
function toast(text, bad = false) {
|
|
2020
|
+
toastEl.textContent = text;
|
|
2021
|
+
toastEl.classList.toggle('bad', bad);
|
|
2022
|
+
toastEl.hidden = false;
|
|
2023
|
+
clearTimeout(toastTimer);
|
|
2024
|
+
toastTimer = setTimeout(() => { toastEl.hidden = true; }, bad ? 7000 : 3500);
|
|
2025
|
+
}
|
|
2026
|
+
|
|
2027
|
+
/**
|
|
2028
|
+
* 성공한 조작의 알림 글. 사람은 무엇을 했는지 알고 있으므로 요약의 첫 문장만 보이고, 길면 SHORT_MAX 자에서 줄인다. 요약 전체가
|
|
2029
|
+
* 그림 위에 여러 줄로 떠 그림을 가리지 않게 하려는 것이다. 거절된 까닭은 줄이지 않는다(send).
|
|
2030
|
+
*/
|
|
2031
|
+
function shortSummary(s) {
|
|
2032
|
+
const t = String(s ?? '').trim();
|
|
2033
|
+
const m = /^[\s\S]*?[.!?](?=\s|$)/.exec(t);
|
|
2034
|
+
const first = m ? m[0] : t;
|
|
2035
|
+
return first.length > SHORT_MAX ? `${first.slice(0, SHORT_MAX - 1).trimEnd()}…` : first;
|
|
2036
|
+
}
|
|
2037
|
+
|
|
2038
|
+
/** 조작을 보낸다. 거절되면 논리가 준 summary 를 그대로 보이고 다시 읽는다. 성공하면 첫 문장만 알리고, quiet 이면 알리지 않는다. */
|
|
2039
|
+
async function send(steps, opts = {}) {
|
|
2040
|
+
if (committing) { toast(t('Still sending the previous operation'), true); return null; }
|
|
2041
|
+
if (readOnly()) { toast(t('This screen is view only, so you cannot make changes'), true); return null; }
|
|
2042
|
+
committing = true;
|
|
2043
|
+
try {
|
|
2044
|
+
const res = await call('applyOperation', { base: concept.base, steps });
|
|
2045
|
+
if (!res || !res.ok) { toast(res?.summary ?? res?.error ?? t('The operation was rejected'), true); await settle(); return null; }
|
|
2046
|
+
if (!opts.quiet) toast(shortSummary(res.summary));
|
|
2047
|
+
await settle();
|
|
2048
|
+
return res;
|
|
2049
|
+
} catch (err) {
|
|
2050
|
+
toast(err.message, true);
|
|
2051
|
+
return null;
|
|
2052
|
+
} finally {
|
|
2053
|
+
committing = false;
|
|
2054
|
+
}
|
|
2055
|
+
}
|
|
2056
|
+
|
|
2057
|
+
/** 조각 여럿을 그림판에서 (dx, dy) 만큼 옮긴다. 조작 한 번에 담아 함께 되돌려진다. move 는 정하는 값이라 지금 move 에 더해 보낸다. */
|
|
2058
|
+
function sendMove(ids, dx, dy) {
|
|
2059
|
+
const steps = [];
|
|
2060
|
+
for (const id of ids) {
|
|
2061
|
+
const p = pieceById.get(id);
|
|
2062
|
+
if (!p) continue;
|
|
2063
|
+
steps.push({ op: 'piece.place', input: { piece: id, move: [r3(p.place.move[0] + dx), r3(p.place.move[1] + dy)] } });
|
|
2064
|
+
}
|
|
2065
|
+
return steps.length ? send(steps) : null;
|
|
2066
|
+
}
|
|
2067
|
+
|
|
2068
|
+
/** 고른 곳에 실제로 보이는 맨 위 조각(7.2절의 under[0]). 떼기와 지우기가 이 조각에 한다. */
|
|
2069
|
+
async function areaTarget() {
|
|
2070
|
+
const s = selection;
|
|
2071
|
+
if (!s || s.kind !== 'area') return null;
|
|
2072
|
+
if (!(await readyOf(s))) return null;
|
|
2073
|
+
const from = s.under?.[0];
|
|
2074
|
+
if (!from) { toast(t('No visible piece in the selected area'), true); return null; }
|
|
2075
|
+
const where = whereOf(s);
|
|
2076
|
+
if (!where) return null;
|
|
2077
|
+
return { s, from, where };
|
|
2078
|
+
}
|
|
2079
|
+
|
|
2080
|
+
/** [떼어 내기](cut)와 [복사해 떼기]. 새 조각을 고르고 [조각 고르기] 로 바꿔 바로 끌어 옮길 수 있게 한다. */
|
|
2081
|
+
async function liftArea(cut) {
|
|
2082
|
+
const tg = await areaTarget();
|
|
2083
|
+
if (!tg) return null;
|
|
2084
|
+
const res = await send([{ op: 'piece.lift', as: '$새조각', input: { where: tg.where, from: tg.from, cut } }]);
|
|
2085
|
+
const id = res?.ids?.['$새조각'];
|
|
2086
|
+
if (!id || !pieceById.has(id)) return null;
|
|
2087
|
+
setTool('piece');
|
|
2088
|
+
selectPieces([id]);
|
|
2089
|
+
return id;
|
|
2090
|
+
}
|
|
2091
|
+
|
|
2092
|
+
/** [색 바꾸기]: 고른 곳을 복사로 떼어 그 조각을 고르고 오른쪽 칸의 색 조절을 연다(5.2절. 오려 내지 않아 가장자리에 틈이 비치지 않는다). */
|
|
2093
|
+
async function recolorArea() {
|
|
2094
|
+
const id = await liftArea(false);
|
|
2095
|
+
if (!id) return;
|
|
2096
|
+
setSide(true);
|
|
2097
|
+
const hue = document.querySelector('[data-keep="adj-hue"]');
|
|
2098
|
+
if (hue && hue.focus) hue.focus();
|
|
2099
|
+
}
|
|
2100
|
+
|
|
2101
|
+
async function eraseArea() {
|
|
2102
|
+
const tg = await areaTarget();
|
|
2103
|
+
if (!tg) return null;
|
|
2104
|
+
return send([{ op: 'piece.erase', input: { where: tg.where, piece: tg.from } }]);
|
|
2105
|
+
}
|
|
2106
|
+
|
|
2107
|
+
async function cropArea() {
|
|
2108
|
+
const s = selection;
|
|
2109
|
+
if (!s || s.kind !== 'area') return null;
|
|
2110
|
+
const where = whereOf(s);
|
|
2111
|
+
if (!where) return null;
|
|
2112
|
+
return send([{ op: 'canvas.crop', input: { where } }]);
|
|
2113
|
+
}
|
|
2114
|
+
|
|
2115
|
+
/**
|
|
2116
|
+
* 고른 것과 말을 AI 에게 보낸다. 픽셀로 고른 곳은 선택 내용(64KB)에 모양을 넣을 수 없어, 먼저 region.add 로 자동 영역으로 저장하고
|
|
2117
|
+
* 그 변경을 다시 그려 그렸다고 알린 뒤 그 영역 id 로 보낸다(7.2절). AI 는 where 에 그 id 를 적어 그 모양 그대로 떼거나 지운다.
|
|
2118
|
+
*/
|
|
2119
|
+
async function shareSelection() {
|
|
2120
|
+
const sel = selection;
|
|
2121
|
+
if (!sel || sharing) return;
|
|
2122
|
+
sharing = true;
|
|
2123
|
+
try {
|
|
2124
|
+
if (!(await readyOf(sel))) return;
|
|
2125
|
+
if (sel.kind === 'area' && !sel.shape && !(sel.region && regionById.has(sel.region))) {
|
|
2126
|
+
const where = maskWhere(sel);
|
|
2127
|
+
if (!where) return;
|
|
2128
|
+
const res = await send([{ op: 'region.add', as: '$고른곳', input: { where, auto: true } }], { quiet: true });
|
|
2129
|
+
const rid = res?.ids?.['$고른곳'];
|
|
2130
|
+
if (!rid || !regionById.has(rid)) return;
|
|
2131
|
+
sel.region = rid;
|
|
2132
|
+
if (!(await readyOf(sel))) return;
|
|
2133
|
+
}
|
|
2134
|
+
const p = payloadOf(sel);
|
|
2135
|
+
const role = talk.role;
|
|
2136
|
+
const said = talk.said;
|
|
2137
|
+
const res = await call('shareSelection', { base: drawnBase, role, said: said.trim(), payload: p, records: recordsOf(p) });
|
|
2138
|
+
if (!res?.ok) { toast(res?.summary ?? res?.error ?? t('Could not send the selection'), true); return; }
|
|
2139
|
+
sel.shared = { id: res.selection, role, said: said.trim() };
|
|
2140
|
+
// 선택을 보내면 코어가 이 화면의 고르기만 한 것을 지운다. 기다리는 사이 다른 것을 골랐으면 그것을 다시 알린다
|
|
2141
|
+
pickSent = null;
|
|
2142
|
+
if (selection !== sel) { notePick(); toast(t('Sent the previous selection as {id}. Your current selection is not sent yet', { id: res.selection })); return; }
|
|
2143
|
+
if (talk.said === said) talk = { role: talk.role, said: '' };
|
|
2144
|
+
toast(said.trim() ? t('Sent selection {id} and your message to the AI', { id: res.selection }) : t('Sent selection {id} to the AI without a message', { id: res.selection }));
|
|
2145
|
+
render();
|
|
2146
|
+
} catch (err) {
|
|
2147
|
+
toast(err.message, true);
|
|
2148
|
+
} finally {
|
|
2149
|
+
sharing = false;
|
|
2150
|
+
}
|
|
2151
|
+
}
|
|
2152
|
+
|
|
2153
|
+
/** PNG 로 저장할 수 있는 크기들. 배수는 원래 크기의 몇 배인지, 긴 변은 가장 긴 변의 픽셀 수다. 코어가 받는 것은 16 부터 4096 까지다. */
|
|
2154
|
+
function pngOptions() {
|
|
2155
|
+
const c = data?.canvas;
|
|
2156
|
+
if (!c) return [];
|
|
2157
|
+
const side = Math.max(c.width, c.height);
|
|
2158
|
+
const out = [];
|
|
2159
|
+
for (const k of [1, 2, 4, 8]) {
|
|
2160
|
+
if (side * k < PNG_MIN || side * k > PNG_MAX) continue;
|
|
2161
|
+
const wh = { w: Math.round(c.width * k), h: Math.round(c.height * k), k };
|
|
2162
|
+
out.push({ value: `scale:${k}`, label: k === 1 ? t('{w}×{h} (original size)', wh) : t('{w}×{h} ({k}x)', wh), req: { scale: k } });
|
|
2163
|
+
}
|
|
2164
|
+
for (const n of [256, 512, 1024]) out.push({ value: `size:${n}`, label: t('Longest side {n}', { n }), req: { size: n } });
|
|
2165
|
+
return out;
|
|
2166
|
+
}
|
|
2167
|
+
|
|
2168
|
+
/** 처음 고를 크기. PNG 를 고치는 화면이라 원래 크기다. 원래 크기를 받지 않는 작은 그림은 긴 변 256 이다. */
|
|
2169
|
+
function pngDefault(options) {
|
|
2170
|
+
return (options.find((o) => o.value === 'scale:1') ?? options.find((o) => o.value === 'size:256') ?? options[0])?.value ?? null;
|
|
2171
|
+
}
|
|
2172
|
+
|
|
2173
|
+
async function savePng() {
|
|
2174
|
+
const options = pngOptions();
|
|
2175
|
+
const pick = options.find((o) => o.value === pngChoice) ?? options.find((o) => o.value === pngDefault(options));
|
|
2176
|
+
if (!pick) return;
|
|
2177
|
+
try {
|
|
2178
|
+
const res = await call('saveOutput', { base: drawnBase ?? concept.base, format: 'png', ...pick.req });
|
|
2179
|
+
if (res?.ok) toast(`${t('Saved: {name}', { name: res.fileName ?? res.artifact })}${res.width && res.height ? ` (${res.width}×${res.height})` : ''}`);
|
|
2180
|
+
else toast(res?.summary ?? res?.error ?? t('Could not save'), true);
|
|
2181
|
+
} catch (err) {
|
|
2182
|
+
toast(err.message, true);
|
|
2183
|
+
}
|
|
2184
|
+
}
|
|
2185
|
+
|
|
2186
|
+
function startSample(s) {
|
|
2187
|
+
return send([{ op: 'canvas.start', input: { sample: s.id, reason: `The person chose the sample ${s.id} (${s.title}) on the screen` } }]);
|
|
2188
|
+
}
|
|
2189
|
+
|
|
2190
|
+
// 오른쪽 칸에서 고치는 조각의 값
|
|
2191
|
+
function sendPlace(id, patch) {
|
|
2192
|
+
return send([{ op: 'piece.place', input: { piece: id, ...patch } }]);
|
|
2193
|
+
}
|
|
2194
|
+
|
|
2195
|
+
function previewAdjust(id, patch) {
|
|
2196
|
+
const p = pieceById.get(id);
|
|
2197
|
+
if (!p) return;
|
|
2198
|
+
const base = preview?.id === id ? preview.adjust : p.adjust;
|
|
2199
|
+
preview = { id, adjust: { ...base, ...patch } };
|
|
2200
|
+
paintPreview();
|
|
2201
|
+
}
|
|
2202
|
+
|
|
2203
|
+
/** 조절 막대를 놓았을 때 색 바꾸기를 보낸다. 값이 그대로면 미리 보기만 거둔다. */
|
|
2204
|
+
function commitAdjust(id, patch) {
|
|
2205
|
+
sliding = false;
|
|
2206
|
+
const p = pieceById.get(id);
|
|
2207
|
+
preview = null;
|
|
2208
|
+
if (!p) return null;
|
|
2209
|
+
const same = Object.entries(patch).every(([k, v]) => JSON.stringify(p.adjust[k]) === JSON.stringify(v));
|
|
2210
|
+
if (same) {
|
|
2211
|
+
paintPreview();
|
|
2212
|
+
if (pendingRefresh) { pendingRefresh = false; refresh(); }
|
|
2213
|
+
return null;
|
|
2214
|
+
}
|
|
2215
|
+
pendingRefresh = false;
|
|
2216
|
+
return send([{ op: 'piece.adjust', input: { piece: id, ...patch } }]);
|
|
2217
|
+
}
|
|
2218
|
+
|
|
2219
|
+
// ---- 화면 ----
|
|
2220
|
+
|
|
2221
|
+
function el(tag, props, ...children) {
|
|
2222
|
+
const n = document.createElement(tag);
|
|
2223
|
+
for (const [k, v] of Object.entries(props ?? {})) {
|
|
2224
|
+
if (k === 'class') n.className = v;
|
|
2225
|
+
else if (k === 'on') for (const [ev, fn] of Object.entries(v)) n.addEventListener(ev, fn);
|
|
2226
|
+
else if (k === 'value') n.value = v;
|
|
2227
|
+
else if (k === 'checked') n.checked = Boolean(v);
|
|
2228
|
+
else if (v !== false && v !== null && v !== undefined) n.setAttribute(k, v === true ? '' : v);
|
|
2229
|
+
}
|
|
2230
|
+
for (const c of children.flat(Infinity)) {
|
|
2231
|
+
if (c === null || c === undefined || c === false) continue;
|
|
2232
|
+
n.append(c instanceof Node ? c : String(c));
|
|
2233
|
+
}
|
|
2234
|
+
return n;
|
|
2235
|
+
}
|
|
2236
|
+
const btn = (label, onClick, extra = {}) => el('button', { type: 'button', class: 'btn', on: { click: onClick }, ...extra }, label);
|
|
2237
|
+
const setOn = (n, on) => (on ? n.removeAttribute('disabled') : n.setAttribute('disabled', ''));
|
|
2238
|
+
|
|
2239
|
+
// 위쪽 줄과 오른쪽 칸의 틀은 한 번만 만들고, 다시 그릴 때는 안의 내용과 상태만 바꾼다
|
|
2240
|
+
const bar = {};
|
|
2241
|
+
// 아이콘은 정해진 선 그림이다. 사람의 입력이 들어가지 않고, 겹쳐 보기와 같이 createElementNS 로 만든다(20×20)
|
|
2242
|
+
const ICONS = {
|
|
2243
|
+
piece: ['M5 3v13l3.5-3.2 2.3 4.7 1.9-.9-2.3-4.6H15z'],
|
|
2244
|
+
rect: ['M3 6V3h3M9 3h2M14 3h3v3M17 9v2M17 14v3h-3M11 17H9M6 17H3v-3M3 11V9'],
|
|
2245
|
+
ellipse: ['M10 4.5c3.9 0 7 2.5 7 5.5s-3.1 5.5-7 5.5S3 13 3 10s3.1-5.5 7-5.5z'],
|
|
2246
|
+
lasso: ['M10 3.5c4 0 7 1.9 7 4.3s-3 4.3-7 4.3-7-1.9-7-4.3 3-4.3 7-4.3z', 'M6.3 11.4c-.8 1.5-.3 2.9 1.2 3.3s1.4 1.9-.2 2.8'],
|
|
2247
|
+
wand: ['M3.5 16.5l9-9', 'M14.5 2.5v2M14.5 8.5v2M10.5 6.5h2M16.5 6.5h2'],
|
|
2248
|
+
pan: ['M6.5 10.5V5.2a1.2 1.2 0 0 1 2.4 0V9M8.9 9V3.9a1.2 1.2 0 0 1 2.4 0V9M11.3 9V4.8a1.2 1.2 0 0 1 2.4 0v5.2M13.7 10V7.2a1.2 1.2 0 0 1 2.4 0v5.3c0 3-2 5.5-5 5.5h-.8c-1.8 0-3-.8-4-2.3L3.7 12a1.2 1.2 0 0 1 2-1.3l.8 1.2'],
|
|
2249
|
+
fit: ['M3 7V3h4M13 3h4v4M17 13v4h-4M7 17H3v-4'],
|
|
2250
|
+
pick: ['M3 6V3h3M9 3h2M14 3h3v3M17 9v2M3 11V9M3 14v3h3', 'M10 10l7 2.5-3 1.2-1.2 3z'],
|
|
2251
|
+
upload: ['M11 4H3v12h14v-5', 'M4.5 14l3.5-4 2.5 2.5 1.5-1.5 2.5 3', 'M15 9V2.5M12.5 5L15 2.5 17.5 5'],
|
|
2252
|
+
save: ['M10 3v9M6.5 8.5L10 12l3.5-3.5M4 14v3h12v-3'],
|
|
2253
|
+
help: ['M10 2.5a7.5 7.5 0 1 0 0 15a7.5 7.5 0 1 0 0-15z', 'M7.8 8a2.2 2.2 0 1 1 3.3 1.9c-.7.4-1.1.9-1.1 1.7M10 14.3v.2'],
|
|
2254
|
+
side: ['M3 4h14v12H3z', 'M12.5 4v12'],
|
|
2255
|
+
eye: ['M2 10s3-5.5 8-5.5S18 10 18 10s-3 5.5-8 5.5S2 10 2 10z', 'M10 7.5a2.5 2.5 0 1 0 0 5a2.5 2.5 0 1 0 0-5z'],
|
|
2256
|
+
eyeOff: ['M2 10s3-5.5 8-5.5S18 10 18 10s-3 5.5-8 5.5S2 10 2 10z', 'M3 3l14 14'],
|
|
2257
|
+
up: ['M10 16V4M5.5 8.5L10 4l4.5 4.5'],
|
|
2258
|
+
down: ['M10 4v12M5.5 11.5L10 16l4.5-4.5'],
|
|
2259
|
+
trash: ['M4 6h12M8 6V4h4v2M6 6l1 11h6l1-11'],
|
|
2260
|
+
picture: ['M3 4h14v12H3z', 'M3 13l4-4 3 3 2-2 5 5', 'M13 6.5a1.2 1.2 0 1 0 0 2.4a1.2 1.2 0 1 0 0-2.4z'],
|
|
2261
|
+
};
|
|
2262
|
+
function icon(name, cls) {
|
|
2263
|
+
const svg = svgEl('svg', { viewBox: '0 0 20 20', 'aria-hidden': 'true', focusable: 'false', class: cls });
|
|
2264
|
+
for (const d of ICONS[name]) svg.append(svgEl('path', { d }));
|
|
2265
|
+
return svg;
|
|
2266
|
+
}
|
|
2267
|
+
/** 아이콘 버튼. 이름은 읽어 주는 프로그램과 마우스를 올렸을 때의 글(title)에 둔다. */
|
|
2268
|
+
const iconBtn = (name, label, onClick, extra = {}) => el('button', { type: 'button', class: 'btn icon', 'aria-label': label, title: label, on: { click: onClick }, ...extra }, icon(name));
|
|
2269
|
+
const miniBtn = (name, label, onClick, extra = {}) => el('button', { type: 'button', class: 'btn mini', 'aria-label': label, title: label, on: { click: onClick }, ...extra }, icon(name));
|
|
2270
|
+
|
|
2271
|
+
/** 위쪽 줄의 메뉴. 버튼을 누르면 그 아래에 열리고, 다른 곳을 누르거나 Esc 를 누르면 닫힌다. */
|
|
2272
|
+
function menu(key, name, label, items) {
|
|
2273
|
+
const panel = el('div', { class: 'menu', role: 'group', 'aria-label': t('{label} menu', { label }) }, el('h2', {}, label), items);
|
|
2274
|
+
panel.hidden = true;
|
|
2275
|
+
const b = iconBtn(name, label, () => setMenu(openMenu === key ? null : key), { 'aria-haspopup': 'true', 'aria-expanded': 'false' });
|
|
2276
|
+
bar.menus[key] = { b, panel };
|
|
2277
|
+
return el('div', { class: 'menuBox' }, b, panel);
|
|
2278
|
+
}
|
|
2279
|
+
function setMenu(key) {
|
|
2280
|
+
openMenu = key;
|
|
2281
|
+
for (const [k, m] of Object.entries(bar.menus)) {
|
|
2282
|
+
m.panel.hidden = k !== key;
|
|
2283
|
+
m.b.setAttribute('aria-expanded', k === key ? 'true' : 'false');
|
|
2284
|
+
}
|
|
2285
|
+
}
|
|
2286
|
+
window.addEventListener('pointerdown', (e) => {
|
|
2287
|
+
if (openMenu && !(e.target && typeof e.target.closest === 'function' && e.target.closest('.menuBox'))) setMenu(null);
|
|
2288
|
+
}, true);
|
|
2289
|
+
|
|
2290
|
+
function setTolerance(v) {
|
|
2291
|
+
wandOpt.tolerance = clamp(Math.round(Number(v)) || 0, 0, 255);
|
|
2292
|
+
updateBar();
|
|
2293
|
+
}
|
|
2294
|
+
|
|
2295
|
+
function buildBar() {
|
|
2296
|
+
bar.tools = {};
|
|
2297
|
+
bar.menus = {};
|
|
2298
|
+
const tools = el('div', { class: 'group', role: 'group', 'aria-label': t('Tools') }, TOOL_KEYS.map((k) => (bar.tools[k] = iconBtn(k, toolName(k), () => setTool(k)))));
|
|
2299
|
+
bar.zoomText = el('span', { class: 'zoom', title: t('Zoom level') }, '100%');
|
|
2300
|
+
const zoom = el('div', { class: 'group', role: 'group', 'aria-label': t('Zoom') },
|
|
2301
|
+
btn('−', () => zoomAt(0.8), { class: 'btn icon', 'aria-label': t('Zoom out'), title: t('Zoom out') }), bar.zoomText, btn('+', () => zoomAt(1.25), { class: 'btn icon', 'aria-label': t('Zoom in'), title: t('Zoom in') }),
|
|
2302
|
+
iconBtn('fit', t('Fit to screen'), () => fit()));
|
|
2303
|
+
// 그림판 크기는 오른쪽 칸을 열지 않아도 보인다
|
|
2304
|
+
bar.size = el('span', { class: 'cap', 'aria-label': t('Canvas size') }, '');
|
|
2305
|
+
bar.ro = el('span', { class: 'cap', title: t('This screen is view only. Buttons for changes are hidden') }, t('View only'));
|
|
2306
|
+
bar.ro.hidden = true;
|
|
2307
|
+
// [고르기] 메뉴: 고른 곳을 바꾸는 것과 비슷한 색의 설정, 영역 보기
|
|
2308
|
+
bar.invert = btn(t('Invert'), () => invertSelection(), { title: t('Swaps the selected and unselected areas. If nothing is selected, selects the whole canvas') });
|
|
2309
|
+
bar.clear = btn(t('Deselect'), () => setSelection(null), { title: t('Clears the selection (Esc)') });
|
|
2310
|
+
bar.grow = btn(t('Grow'), () => growSelection(1), { title: t('Moves the edge of the selected area outward') });
|
|
2311
|
+
bar.shrink = btn(t('Shrink'), () => growSelection(-1), { title: t('Moves the edge of the selected area inward') });
|
|
2312
|
+
bar.growN = el('input', { type: 'number', class: 'num', min: '1', max: String(GROW_MAX), step: '1', value: '1', 'aria-label': t('Pixels to grow or shrink'), on: { change: (e) => { growBy = clamp(Math.round(Number(e.target.value)) || 1, 1, GROW_MAX); e.target.value = String(growBy); } } });
|
|
2313
|
+
bar.tol = el('input', { id: 'tolRange', type: 'range', min: '0', max: '255', step: '1', value: '32', 'aria-label': t('Tolerance'), on: { input: (e) => setTolerance(e.target.value) } });
|
|
2314
|
+
bar.tolNum = el('input', { type: 'number', class: 'num', min: '0', max: '255', step: '1', value: '32', 'aria-label': t('Tolerance value'), on: { change: (e) => setTolerance(e.target.value) } });
|
|
2315
|
+
bar.contig = el('input', { type: 'checkbox', checked: true, 'aria-label': t('Connected only'), on: { change: (e) => { wandOpt.contiguous = e.target.checked; updateBar(); } } });
|
|
2316
|
+
bar.regionsOn = el('input', { type: 'checkbox', 'aria-label': t('Show regions'), on: { change: (e) => { showRegions = e.target.checked; drawOverlay(); } } });
|
|
2317
|
+
const pickMenu = menu('pick', 'pick', t('Select'), [
|
|
2318
|
+
el('div', { class: 'group' }, bar.invert, bar.clear),
|
|
2319
|
+
el('div', { class: 'group' }, bar.grow, bar.shrink, bar.growN, el('span', { class: 'cap' }, t('pixels'))),
|
|
2320
|
+
el('div', { class: 'group' }, el('span', { class: 'cap' }, t('Similar colors tolerance')), bar.tol, bar.tolNum),
|
|
2321
|
+
el('label', { class: 'swatch' }, bar.contig, t('Connected only (off: whole picture)')),
|
|
2322
|
+
el('label', { class: 'swatch' }, bar.regionsOn, t('Show regions'))]);
|
|
2323
|
+
bar.upload = iconBtn('upload', t('Add picture'), () => chooseFile('add'), { title: t('Add picture: adds another PNG file as a new piece on top') });
|
|
2324
|
+
// PNG 는 코어가 그림의 SVG 를 그려 만든다. 코어가 png 를 밝힐 때만 보인다(capabilities 의 output)
|
|
2325
|
+
bar.pngSize = el('select', { 'aria-label': t('PNG size'), on: { change: (e) => { pngChoice = e.target.value; } } });
|
|
2326
|
+
bar.png = el('div', { class: 'group', role: 'group', 'aria-label': t('Save PNG') }, bar.pngSize, btn(t('Save PNG'), () => { setMenu(null); savePng(); }, { title: t('Saves the current picture as a PNG file at the chosen size. Empty areas are transparent') }));
|
|
2327
|
+
bar.saveWhy = el('span', { class: 'reason' }, '');
|
|
2328
|
+
const save = menu('save', 'save', t('Save'), [bar.png, bar.saveWhy]);
|
|
2329
|
+
bar.help = iconBtn('help', t('Tool help'), () => { helpOn = !helpOn; updateBar(); }, { 'aria-pressed': 'false' });
|
|
2330
|
+
bar.side = iconBtn('side', t('Pieces and info'), () => setSide(!sideOpen), { 'aria-pressed': 'false', 'aria-controls': 'side' });
|
|
2331
|
+
barEl.replaceChildren(tools, zoom, bar.size, el('span', { class: 'spacer' }), bar.ro, pickMenu, bar.upload, save, bar.help, bar.side);
|
|
2332
|
+
}
|
|
2333
|
+
|
|
2334
|
+
/** 오른쪽 칸(그림, 고른 것, 조각의 값, 조각 목록, 영역 목록, 그림 파일)을 열거나 닫는다. 고른다고 저절로 열리지 않는다. */
|
|
2335
|
+
function setSide(on) {
|
|
2336
|
+
sideOpen = Boolean(on);
|
|
2337
|
+
sideEl.hidden = !sideOpen;
|
|
2338
|
+
mainEl.setAttribute('data-side', sideOpen ? 'open' : 'closed');
|
|
2339
|
+
updateBar();
|
|
2340
|
+
}
|
|
2341
|
+
|
|
2342
|
+
function setTool(k) {
|
|
2343
|
+
if (!TOOL_KEYS.includes(k)) return;
|
|
2344
|
+
tool = k;
|
|
2345
|
+
stage.setAttribute('data-tool', k);
|
|
2346
|
+
updateBar();
|
|
2347
|
+
}
|
|
2348
|
+
|
|
2349
|
+
const toolHelp = (k) => ({
|
|
2350
|
+
piece: t('Click a piece to select it, or drag it to move it. Hold Shift and click to select several pieces. Clicks pass through transparent areas and select the piece visible underneath.'),
|
|
2351
|
+
rect: t('Drag to select a rectangle. Hold Shift while dragging to add to the selected area, or Alt to subtract from it. A single click selects the position and color of that point.'),
|
|
2352
|
+
ellipse: t('Drag to select an ellipse. Hold Shift while dragging to add, or Alt to subtract. A single click selects the position and color of that point.'),
|
|
2353
|
+
lasso: t('Hold the mouse button and draw around an area to select its inside. Shift adds and Alt subtracts. A single click selects the position and color of that point.'),
|
|
2354
|
+
wand: t('Selects colors similar to the spot you click. Set the tolerance and Connected only in the [Select] menu. Shift adds and Alt subtracts.'),
|
|
2355
|
+
pan: t('Drag to move the view.'),
|
|
2356
|
+
})[k];
|
|
2357
|
+
|
|
2358
|
+
/** 그림판 크기와 든 것의 수. 위쪽 줄의 그림판 크기에 마우스를 올리면 보인다. */
|
|
2359
|
+
const canvasTitle = (cv) => t('Canvas {w}×{h}, {pieces}, {regions}, {images}', { w: cv.width, h: cv.height, pieces: many(data.pieces.length, t('piece')), regions: many((data.regions ?? []).length, t('region')), images: many(data.images.length, t('image file')) });
|
|
2360
|
+
|
|
2361
|
+
function updateBar() {
|
|
2362
|
+
const ro = readOnly();
|
|
2363
|
+
for (const [k, b] of Object.entries(bar.tools)) {
|
|
2364
|
+
b.setAttribute('aria-pressed', k === tool ? 'true' : 'false');
|
|
2365
|
+
const mode = wandOpt.contiguous ? t('connected only') : t('whole picture');
|
|
2366
|
+
const extra = k === 'wand' ? ` ${t('Current: tolerance {tol}, {mode}.', { tol: wandOpt.tolerance, mode })}` : k === 'piece' && ro ? ` ${t('On a view-only screen, pieces do not move.')}` : '';
|
|
2367
|
+
b.setAttribute('title', `${toolName(k)}: ${toolHelp(k)}${extra}`);
|
|
2368
|
+
}
|
|
2369
|
+
bar.ro.hidden = !ro;
|
|
2370
|
+
bar.upload.hidden = ro;
|
|
2371
|
+
const cv = data?.canvas;
|
|
2372
|
+
bar.size.textContent = cv ? `${cv.width}×${cv.height}` : '';
|
|
2373
|
+
bar.size.setAttribute('title', cv ? canvasTitle(cv) : '');
|
|
2374
|
+
const area = selection?.kind === 'area';
|
|
2375
|
+
setOn(bar.grow, area);
|
|
2376
|
+
setOn(bar.shrink, area);
|
|
2377
|
+
setOn(bar.clear, Boolean(selection));
|
|
2378
|
+
bar.tol.value = String(wandOpt.tolerance);
|
|
2379
|
+
bar.tolNum.value = String(wandOpt.tolerance);
|
|
2380
|
+
bar.contig.checked = wandOpt.contiguous;
|
|
2381
|
+
bar.regionsOn.checked = showRegions;
|
|
2382
|
+
bar.help.setAttribute('aria-pressed', helpOn ? 'true' : 'false');
|
|
2383
|
+
bar.help.setAttribute('title', helpOn ? t('Hide tool help') : t('Show tool help'));
|
|
2384
|
+
bar.side.setAttribute('aria-pressed', sideOpen ? 'true' : 'false');
|
|
2385
|
+
bar.side.setAttribute('title', sideOpen ? t('Hide pieces and info') : t('Show pieces and info (selection, piece values, piece list, region list, image files)'));
|
|
2386
|
+
stageNote.hidden = !helpOn;
|
|
2387
|
+
if (helpOn) stageNote.textContent = noteText();
|
|
2388
|
+
const canPng = Boolean(cv) && Array.isArray(caps.output) && caps.output.includes('png');
|
|
2389
|
+
bar.png.hidden = !canPng;
|
|
2390
|
+
bar.saveWhy.textContent = canPng ? '' : !cv ? t('Start a picture before saving') : t('This core version does not support saving PNG yet');
|
|
2391
|
+
if (canPng) {
|
|
2392
|
+
// 크기 목록은 그림판 크기에 따라 달라진다. 고른 것이 목록에 없으면(자르기) 처음 고를 크기로 돌린다
|
|
2393
|
+
const options = pngOptions();
|
|
2394
|
+
if (!options.some((o) => o.value === pngChoice)) pngChoice = pngDefault(options);
|
|
2395
|
+
const key = options.map((o) => o.label).join('|');
|
|
2396
|
+
if (bar.pngSize.getAttribute('data-key') !== key) {
|
|
2397
|
+
bar.pngSize.setAttribute('data-key', key);
|
|
2398
|
+
bar.pngSize.replaceChildren(...options.map((o) => el('option', { value: o.value }, o.label)));
|
|
2399
|
+
}
|
|
2400
|
+
bar.pngSize.value = pngChoice;
|
|
2401
|
+
}
|
|
2402
|
+
}
|
|
2403
|
+
|
|
2404
|
+
/** [도구 설명] 을 켰을 때 그림 아래에 보이는 글. 지금 도구가 하는 일, 화면을 옮기는 법, 고른 것을 AI 가 아는 방법이다. */
|
|
2405
|
+
function noteText() {
|
|
2406
|
+
const common = t('Use the mouse wheel to zoom in and out. With any tool, hold Space or the middle mouse button and drag to move the view. Press Esc to deselect. Drop or paste another PNG file onto the picture to add it as a piece.');
|
|
2407
|
+
const share = readOnly() ? t('On a view-only screen, you cannot make changes or send a selection to the AI.')
|
|
2408
|
+
: !caps.conceptSelection ? t('This host cannot receive selections from a concept screen yet.')
|
|
2409
|
+
: `${t('When you select something, a panel appears at the top of the picture. There you can lift or erase it, and send it to the AI with a message.')} ${caps.conceptPick ? t('Even if you only select, the AI reads your selection when you talk to it in the AI chat. To tell a waiting AI right away, send it from that panel.') : t('Selecting alone does not tell the AI. Send it from that panel.')}`;
|
|
2410
|
+
return `${toolName(tool)}: ${toolHelp(tool)} ${common} ${share}`;
|
|
2411
|
+
}
|
|
2412
|
+
|
|
2413
|
+
const sec = {};
|
|
2414
|
+
function buildSide() {
|
|
2415
|
+
for (const k of ['info', 'sel', 'values', 'pieces', 'regions', 'images']) sec[k] = el('section', { 'data-sec': k });
|
|
2416
|
+
sideEl.replaceChildren(sec.info, sec.sel, sec.values, sec.pieces, sec.regions, sec.images);
|
|
2417
|
+
}
|
|
2418
|
+
|
|
2419
|
+
/** 오른쪽 칸과 뜨는 칸을 다시 그릴 때 쓰던 칸(data-keep)의 초점과 커서를 지킨다(plugin-guide 4.7절). */
|
|
2420
|
+
function keepFocus(fn) {
|
|
2421
|
+
const a = document.activeElement;
|
|
2422
|
+
const key = a && typeof a.getAttribute === 'function' ? a.getAttribute('data-keep') : null;
|
|
2423
|
+
const range = key && typeof a.selectionStart === 'number' ? [a.selectionStart, a.selectionEnd] : null;
|
|
2424
|
+
fn();
|
|
2425
|
+
if (!key) return;
|
|
2426
|
+
const b = document.querySelector(`[data-keep="${key}"]`);
|
|
2427
|
+
if (!b || b === a) return;
|
|
2428
|
+
b.focus();
|
|
2429
|
+
if (range && b.setSelectionRange) try { b.setSelectionRange(range[0], range[1]); } catch {}
|
|
2430
|
+
}
|
|
2431
|
+
|
|
2432
|
+
const fillSec = (n, parts) => {
|
|
2433
|
+
const list = (Array.isArray(parts) ? parts.flat(Infinity) : [parts]).filter(Boolean);
|
|
2434
|
+
n.hidden = list.length === 0;
|
|
2435
|
+
n.replaceChildren(...list);
|
|
2436
|
+
};
|
|
2437
|
+
const kv = (...pairs) => el('dl', { class: 'kv' }, pairs.filter(Boolean).map(([k, v]) => [el('dt', {}, k), el('dd', {}, v)]));
|
|
2438
|
+
const colorChips = (colors) => el('div', { class: 'colors' }, colors.map((c) => el('span', { class: 'chipc' }, el('i', { style: `background:${c.color}` }), `${c.color} ${Math.round(c.share * 100)}%`)));
|
|
2439
|
+
|
|
2440
|
+
function infoParts() {
|
|
2441
|
+
const c = data.canvas;
|
|
2442
|
+
const src = c.source ? t('Sample {title} ({id})', { title: c.source.title, id: c.source.sample }) : data.images.length ? t('Image file') : t('Empty canvas');
|
|
2443
|
+
return [
|
|
2444
|
+
el('h2', {}, t('Picture')),
|
|
2445
|
+
kv([t('Canvas'), `${c.width}×${c.height}`], [t('Started from'), src], [t('Contents'), `${many(data.pieces.length, t('piece'))}, ${many((data.regions ?? []).length, t('region'))}, ${many(data.images.length, t('image file'))}`], data.version ? [t('Plugin'), data.version] : null),
|
|
2446
|
+
readOnly() ? el('p', { class: 'note' }, t('This screen is view only. Buttons for changes are hidden.')) : null,
|
|
2447
|
+
];
|
|
2448
|
+
}
|
|
2449
|
+
|
|
2450
|
+
/** 고른 것을 한 줄로. 뜨는 칸이 무엇을 골랐는지 말할 때 쓴다. */
|
|
2451
|
+
function selText(s) {
|
|
2452
|
+
if (s.kind === 'pieces') {
|
|
2453
|
+
if (s.list.length === 1) { const p = pieceById.get(s.list[0]); return p ? titleOf(p) : s.list[0]; }
|
|
2454
|
+
const names = s.list.slice(0, MAX_TALK_NAMES).map((id) => { const p = pieceById.get(id); return p ? labelOf(p) : id; });
|
|
2455
|
+
const count = many(s.list.length, t('piece'));
|
|
2456
|
+
return s.list.length > MAX_TALK_NAMES ? t('{count} ({names} and {more} more)', { count, names: names.join(', '), more: s.list.length - MAX_TALK_NAMES }) : `${count} (${names.join(', ')})`;
|
|
2457
|
+
}
|
|
2458
|
+
if (s.kind === 'area') return `${howWord(s.how) ?? s.how} ${s.box.w}×${s.box.h}, ${many(s.pixels, t('pixel'))}${s.region && regionById.has(s.region) ? `, ${t('region {id}', { id: s.region })}` : ''}`;
|
|
2459
|
+
return `${t('Point {x}, {y}', { x: s.x, y: s.y })}${s.ready ? (s.color ? ` ${s.color}` : ` ${t('transparent')}`) : ''}`;
|
|
2460
|
+
}
|
|
2461
|
+
|
|
2462
|
+
function selParts() {
|
|
2463
|
+
const s = selection;
|
|
2464
|
+
if (!s) {
|
|
2465
|
+
return [el('h2', {}, t('Selection')),
|
|
2466
|
+
el('p', {}, t('Click a piece with [Select piece], or select an area with [Rectangle], [Ellipse], [Freehand], or [Similar colors].')),
|
|
2467
|
+
el('p', { class: 'note' }, t('Hold Shift while selecting to add, or Alt to subtract. Press Esc to deselect.'))];
|
|
2468
|
+
}
|
|
2469
|
+
if (s.kind === 'pieces') {
|
|
2470
|
+
const all = s.list.map((id) => pieceById.get(id)).filter(Boolean);
|
|
2471
|
+
return [el('h2', {}, all.length === 1 ? t('Selected piece') : t('{n} selected pieces', { n: all.length })),
|
|
2472
|
+
el('div', { class: 'crumbs' }, all.map((p) => el('button', { type: 'button', class: 'chip', 'aria-label': t('Remove {name} from the selection', { name: titleOf(p) }), title: t('Click to remove it from the selection'), on: { click: () => togglePiece(p.id) } }, labelOf(p)))),
|
|
2473
|
+
el('p', { class: 'note' }, readOnly() ? t('Hold Shift and click to add or remove pieces.') : t('Hold Shift and click to add or remove pieces. Drag to move them together. Scale, rotation, and color adjustments are below when you select one piece.'))];
|
|
2474
|
+
}
|
|
2475
|
+
if (s.kind === 'area') {
|
|
2476
|
+
const under = (s.under ?? []).map((id) => { const p = pieceById.get(id); return p ? labelOf(p) : id; });
|
|
2477
|
+
return [el('h2', {}, t('Selected area')),
|
|
2478
|
+
kv([t('Selected with'), howWord(s.how) ?? s.how], [t('Bounding box'), boxText(s.box)], [t('Pixels'), comma(s.pixels)],
|
|
2479
|
+
s.region && regionById.has(s.region) ? [t('Region'), s.region] : null,
|
|
2480
|
+
[t('Visible pieces'), !s.ready ? t('Checking') : under.length ? under.join(', ') : t('None (transparent area)')]),
|
|
2481
|
+
s.ready && s.colors?.length ? [el('p', { class: 'note' }, t('Main colors')), colorChips(s.colors)] : null,
|
|
2482
|
+
readOnly() ? null : regionForm(s)];
|
|
2483
|
+
}
|
|
2484
|
+
return [el('h2', {}, t('Selected point')), kv([t('Position'), `${s.x}, ${s.y}`], [t('Color'), !s.ready ? t('Checking') : s.color ?? t('Transparent')], [t('Visible piece'), !s.ready ? t('Checking') : s.piece ? labelOf(pieceById.get(s.piece) ?? { id: s.piece }) : t('None')])];
|
|
2485
|
+
}
|
|
2486
|
+
|
|
2487
|
+
/** 고른 곳에 이름을 붙여 영역으로 남긴다(region.add). 그림은 바뀌지 않는다. */
|
|
2488
|
+
function regionForm(s) {
|
|
2489
|
+
const key = `area:${s.gen}`;
|
|
2490
|
+
if (regionDraft.key !== key) regionDraft = { key, text: '' };
|
|
2491
|
+
const input = el('input', { type: 'text', 'data-keep': 'regionName', 'aria-label': t('Region name'), placeholder: t('e.g. left eye'), value: regionDraft.text,
|
|
2492
|
+
on: { input: (e) => { regionDraft.text = e.target.value; }, keydown: (e) => { if (e.key === 'Enter' && !e.isComposing) saveRegion(); } } });
|
|
2493
|
+
return el('div', { class: 'form' }, el('div', { class: 'inline' }, input, btn(t('Name region'), saveRegion, { title: t('Gives the selected area a name and keeps it as a region. The AI can also refer to it by this name and id') })));
|
|
2494
|
+
}
|
|
2495
|
+
|
|
2496
|
+
async function saveRegion() {
|
|
2497
|
+
const s = selection;
|
|
2498
|
+
const name = regionDraft.text.trim();
|
|
2499
|
+
if (!s || s.kind !== 'area') return null;
|
|
2500
|
+
if (!name) { toast(t('Enter a name for the region'), true); return null; }
|
|
2501
|
+
const where = whereOf(s);
|
|
2502
|
+
if (!where) return null;
|
|
2503
|
+
const res = await send([{ op: 'region.add', input: { where, name } }]);
|
|
2504
|
+
if (res) { regionDraft = { key: null, text: '' }; render(); }
|
|
2505
|
+
return res;
|
|
2506
|
+
}
|
|
2507
|
+
|
|
2508
|
+
const fmtDeg = (v) => `${Math.round(v)}°`;
|
|
2509
|
+
const fmtRate = (v) => `${Math.round(v * 100)}%`;
|
|
2510
|
+
|
|
2511
|
+
/** 하나를 고른 조각의 값. 숫자 칸은 바꾸면 보내고, 조절 막대는 끄는 동안 화면에서만 미리 보이고 놓으면 보낸다. */
|
|
2512
|
+
function valueParts() {
|
|
2513
|
+
const s = selection;
|
|
2514
|
+
if (s?.kind !== 'pieces' || s.list.length !== 1) return [];
|
|
2515
|
+
const p = pieceById.get(s.list[0]);
|
|
2516
|
+
if (!p) return [];
|
|
2517
|
+
const a = p.adjust;
|
|
2518
|
+
const pl = p.place;
|
|
2519
|
+
if (readOnly()) {
|
|
2520
|
+
return [el('h2', {}, t('Piece values')),
|
|
2521
|
+
kv([t('Name'), p.name || t('None')], [t('Move'), `${num(pl.move[0])}, ${num(pl.move[1])}`], [t('Scale'), t('horizontal {x}, vertical {y}', { x: num(pl.scale[0]), y: num(pl.scale[1]) })], [t('Rotation'), fmtDeg(pl.rotate)],
|
|
2522
|
+
[t('Hue'), fmtDeg(a.hue)], [t('Saturation'), fmtRate(a.saturate)], [t('Brightness'), fmtRate(a.brightness)], [t('Tint'), a.tint ? `${a.tint.color} ${fmtRate(a.tint.amount)}` : t('None')], [t('Opacity'), fmtRate(a.opacity)],
|
|
2523
|
+
[t('Erased areas'), `${p.holes.length}`])];
|
|
2524
|
+
}
|
|
2525
|
+
const nkey = `piece:${p.id}:${p.name}`;
|
|
2526
|
+
if (nameDraft.key !== nkey) nameDraft = { key: nkey, text: p.name };
|
|
2527
|
+
const saveName = () => { const name = nameDraft.text.trim(); if (name === p.name) return; send([{ op: 'piece.set', input: { piece: p.id, name } }]); };
|
|
2528
|
+
const name = el('input', { type: 'text', 'data-keep': 'pieceName', 'aria-label': t('Piece name'), value: nameDraft.text,
|
|
2529
|
+
on: { input: (e) => { nameDraft.text = e.target.value; }, keydown: (e) => { if (e.key === 'Enter' && !e.isComposing) saveName(); } } });
|
|
2530
|
+
const numIn = (label, keep, value, step, onChange) => el('label', {}, el('span', {}, label), el('input', { type: 'number', step, value: num(value), 'aria-label': label, 'data-keep': keep,
|
|
2531
|
+
on: { change: (e) => { const v = Number(e.target.value); if (e.target.value.trim() !== '' && Number.isFinite(v)) onChange(v); } } }));
|
|
2532
|
+
// 막대를 끌다가 처음 값으로 돌려놓으면 change 가 오지 않는다. 놓은 뒤에도 끄는 중으로 남아 있으면 그 값으로 마무리한다
|
|
2533
|
+
const release = (patchOf) => (e) => { const t = e.target; setTimeout(() => { if (sliding) commitAdjust(p.id, patchOf(Number(t.value))); }, 0); };
|
|
2534
|
+
const slider = (key, label, min, max, step, value, fmt) => {
|
|
2535
|
+
const out = el('span', { class: 'val' }, fmt(value));
|
|
2536
|
+
const patchOf = (v) => ({ [key]: v });
|
|
2537
|
+
return el('label', { class: 'slider' }, el('span', {}, label),
|
|
2538
|
+
el('input', { type: 'range', min: String(min), max: String(max), step: String(step), value: String(value), 'aria-label': label, 'data-keep': `adj-${key}`,
|
|
2539
|
+
on: { input: (e) => { sliding = true; const v = Number(e.target.value); out.textContent = fmt(v); previewAdjust(p.id, patchOf(v)); }, change: (e) => commitAdjust(p.id, patchOf(Number(e.target.value))), pointerup: release(patchOf), blur: release(patchOf) } }),
|
|
2540
|
+
out);
|
|
2541
|
+
};
|
|
2542
|
+
const tkey = `${p.id}:${a.tint?.color ?? ''}`;
|
|
2543
|
+
if (tintDraft.key !== tkey) tintDraft = { key: tkey, color: a.tint?.color ?? tintDraft.color };
|
|
2544
|
+
const amount = a.tint?.amount ?? 0;
|
|
2545
|
+
const amountOut = el('span', { class: 'val' }, fmtRate(amount));
|
|
2546
|
+
const tintOf = (v) => (v > 0 ? { color: tintDraft.color, amount: v } : null);
|
|
2547
|
+
const tintPatch = (v) => ({ tint: tintOf(v) });
|
|
2548
|
+
return [el('h2', {}, t('Piece values')),
|
|
2549
|
+
el('div', { class: 'form' },
|
|
2550
|
+
el('div', { class: 'inline' }, name, btn(t('Rename'), saveName)),
|
|
2551
|
+
el('div', { class: 'row2' }, numIn(t('Move x'), 'mx', pl.move[0], '1', (v) => sendPlace(p.id, { move: [v, pl.move[1]] })), numIn(t('Move y'), 'my', pl.move[1], '1', (v) => sendPlace(p.id, { move: [pl.move[0], v] }))),
|
|
2552
|
+
el('div', { class: 'row2' }, numIn(t('Horizontal scale'), 'sx', pl.scale[0], '0.05', (v) => sendPlace(p.id, { scale: [v, pl.scale[1]] })), numIn(t('Vertical scale'), 'sy', pl.scale[1], '0.05', (v) => sendPlace(p.id, { scale: [pl.scale[0], v] }))),
|
|
2553
|
+
numIn(t('Rotation (degrees, clockwise)'), 'rot', pl.rotate, '1', (v) => sendPlace(p.id, { rotate: v })),
|
|
2554
|
+
slider('hue', t('Hue'), -180, 180, 1, a.hue, fmtDeg),
|
|
2555
|
+
slider('saturate', t('Saturation'), 0, 2, 0.05, a.saturate, fmtRate),
|
|
2556
|
+
slider('brightness', t('Brightness'), 0, 2, 0.05, a.brightness, fmtRate),
|
|
2557
|
+
el('label', { class: 'slider' }, el('span', {}, t('Tint color')), el('input', { type: 'color', value: tintDraft.color, 'aria-label': t('Tint color'), 'data-keep': 'tintColor',
|
|
2558
|
+
on: { change: (e) => { tintDraft.color = String(e.target.value).toLowerCase(); commitAdjust(p.id, { tint: tintOf(amount > 0 ? amount : 0.5) }); } } }), el('span', {})),
|
|
2559
|
+
el('label', { class: 'slider' }, el('span', {}, t('Tint')),
|
|
2560
|
+
el('input', { type: 'range', min: '0', max: '1', step: '0.05', value: String(amount), 'aria-label': t('Tint amount'), 'data-keep': 'adj-tint',
|
|
2561
|
+
on: { input: (e) => { sliding = true; const v = Number(e.target.value); amountOut.textContent = fmtRate(v); previewAdjust(p.id, tintPatch(v)); }, change: (e) => commitAdjust(p.id, tintPatch(Number(e.target.value))), pointerup: release(tintPatch), blur: release(tintPatch) } }),
|
|
2562
|
+
amountOut),
|
|
2563
|
+
slider('opacity', t('Opacity'), 0, 1, 0.05, a.opacity, fmtRate),
|
|
2564
|
+
el('div', { class: 'group' }, btn(t('Restore erased'), () => send([{ op: 'piece.unerase', input: { piece: p.id } }]), { title: t('Restores all erased areas of this piece'), ...(p.holes.length ? {} : { disabled: true }) }))),
|
|
2565
|
+
el('p', { class: 'note' }, `${many(p.holes.length, t('erased area'))}, ${many(p.clip.length, t('visible-area shape'))}${p.from ? `, ${t('lifted from {id}', { id: p.from })}` : ''}. ${t('Scale and rotation are around the center of the area the piece covers.')}`)];
|
|
2566
|
+
}
|
|
2567
|
+
|
|
2568
|
+
// 조각 목록: 위에 그려진 것이 위에 온다
|
|
2569
|
+
function pieceListParts() {
|
|
2570
|
+
const ro = readOnly();
|
|
2571
|
+
const picked = new Set(pickedPieces());
|
|
2572
|
+
const list = data.pieces;
|
|
2573
|
+
const rows = [];
|
|
2574
|
+
for (let i = list.length - 1; i >= 0; i -= 1) {
|
|
2575
|
+
const p = list[i];
|
|
2576
|
+
const above = list[i + 1];
|
|
2577
|
+
const below = list[i - 1];
|
|
2578
|
+
rows.push(el('li', { class: picked.has(p.id) ? 'current' : '', 'data-row': p.id },
|
|
2579
|
+
el('button', { type: 'button', class: `pick${p.hidden ? ' off' : ''}`, 'data-pick': p.id, title: `${titleOf(p)}${p.box ? `, ${t('approximate area {box}', { box: boxText(p.box) })}` : ''}`, on: { click: (e) => { if (addKey(e)) togglePiece(p.id); else selectPieces([p.id]); } } },
|
|
2580
|
+
p.name || t('No name'), el('span', { class: 'id' }, `${p.id}${p.hidden ? `, ${t('hidden')}` : ''}`)),
|
|
2581
|
+
ro ? null : [
|
|
2582
|
+
miniBtn(p.hidden ? 'eyeOff' : 'eye', p.hidden ? t('Show {name}', { name: labelOf(p) }) : t('Hide {name}', { name: labelOf(p) }), () => send([{ op: 'piece.set', input: { piece: p.id, hidden: !p.hidden } }])),
|
|
2583
|
+
miniBtn('up', t('Move {name} up', { name: labelOf(p) }), () => send([{ op: 'piece.order', input: { piece: p.id, above: above.id } }]), above ? {} : { disabled: true }),
|
|
2584
|
+
miniBtn('down', t('Move {name} down', { name: labelOf(p) }), () => send([{ op: 'piece.order', input: { piece: p.id, below: below.id } }]), below ? {} : { disabled: true }),
|
|
2585
|
+
miniBtn('trash', t('Delete {name}', { name: labelOf(p) }), () => send([{ op: 'piece.remove', input: { piece: p.id } }]))]));
|
|
2586
|
+
}
|
|
2587
|
+
return [el('h2', {}, t('Piece list ({n})', { n: list.length })),
|
|
2588
|
+
rows.length ? el('ul', { class: 'rows', role: 'list', 'aria-label': t('Piece list') }, rows) : el('p', { class: 'note' }, t('No pieces.')),
|
|
2589
|
+
el('p', { class: 'note' }, t('Click to select a piece. Hold Shift and click to add it to the selection or remove it.'))];
|
|
2590
|
+
}
|
|
2591
|
+
|
|
2592
|
+
function regionParts() {
|
|
2593
|
+
const ro = readOnly();
|
|
2594
|
+
const list = data.regions ?? [];
|
|
2595
|
+
return [el('h2', {}, t('Region list ({n})', { n: list.length })),
|
|
2596
|
+
list.length ? el('ul', { class: 'rows', 'aria-label': t('Region list') }, list.map((r) => el('li', { 'data-region': r.id },
|
|
2597
|
+
el('span', { class: 'pick', title: r.note || (r.auto ? t('Automatic region, made when you sent a selection to the AI') : '') }, r.name || (r.auto ? t('Sent area') : t('No name')), el('span', { class: 'id' }, `${r.id}, ${boxText(r.box)}`)),
|
|
2598
|
+
btn(t('Select region'), () => selectRegion(r.id), { class: 'btn small' }),
|
|
2599
|
+
ro ? null : miniBtn('trash', t('Delete region {name}', { name: r.name || r.id }), () => send([{ op: 'region.remove', input: { region: r.id } }]))))) : el('p', { class: 'note' }, t('No regions yet. Select an area and give it a name to keep it. When you send a selected area to the AI, it is also kept as an automatic region.'))];
|
|
2600
|
+
}
|
|
2601
|
+
|
|
2602
|
+
function imageParts() {
|
|
2603
|
+
const used = (id) => data.pieces.filter((p) => p.image === id).length;
|
|
2604
|
+
return [el('h2', {}, t('Image files ({n})', { n: data.images.length })),
|
|
2605
|
+
el('ul', { class: 'rows' }, data.images.map((im) => el('li', {}, el('span', { class: 'pick', title: im.name }, im.name, el('span', { class: 'id' }, `${im.id}, ${im.width}×${im.height}, ${sizeText(im.bytes)}, ${many(used(im.id), t('piece'))}`))))),
|
|
2606
|
+
el('p', { class: 'note' }, t('The pixels of an image file never change. A piece only records which parts of its image file are visible or erased, its placement, and its color adjustments.'))];
|
|
2607
|
+
}
|
|
2608
|
+
|
|
2609
|
+
// 고른 뒤에 뜨는 칸. 곳을 골랐으면 그 곳으로 할 일(떼어 내기, 복사해 떼기, 지우기, 자르기, 색 바꾸기)과 말 칸, 조각이나 점을 골랐으면
|
|
2610
|
+
// 말 칸이다(9절). 고르기만 한 것은 AI 가 읽을 수는 있어도(setPick) AI 를 깨우지 않으므로 AI 에게 보내는 버튼을 늘 함께 둔다.
|
|
2611
|
+
// 보기만 하는 화면에서는 띄우지 않는다
|
|
2612
|
+
function renderTalk() {
|
|
2613
|
+
const s = selection;
|
|
2614
|
+
const ro = readOnly();
|
|
2615
|
+
const share = canShare();
|
|
2616
|
+
const edits = s?.kind === 'area' && !ro;
|
|
2617
|
+
const show = Boolean(s) && data?.canvas && (share || edits);
|
|
2618
|
+
talkEl.hidden = !show;
|
|
2619
|
+
if (!show) { talkEl.replaceChildren(); talkEl.classList.toggle('unsent', false); return; }
|
|
2620
|
+
if (talkPlaced !== s.gen) { talkPlaced = s.gen; talkEl.setAttribute('data-at', talkAt(s)); }
|
|
2621
|
+
const close = btn('×', () => setSelection(null), { class: 'btn icon', 'aria-label': t('Deselect'), title: t('Clears the selection (Esc)') });
|
|
2622
|
+
let state;
|
|
2623
|
+
if (s.shared) state = el('p', { class: 'state' }, el('span', { class: 'done' }, t('Sent to the AI (selection {id})', { id: s.shared.id })), ` ${selText(s)}${s.shared.said ? `, ${t('message "{said}"', { said: s.shared.said })}` : `, ${t('no message')}`}. ${t('The AI reads this selection and works on it.')}`);
|
|
2624
|
+
else state = el('p', { class: 'state' }, el('b', {}, t('Selected: {sel}', { sel: selText(s) })), ' ', !share ? '' : caps.conceptPick ? t('The AI reads this when you talk to it in the AI chat. To tell a waiting AI right away, press [Send to AI].') : [el('span', { class: 'warn' }, t('Not sent to the AI yet.')), ` ${t('The message can be empty.')}`]);
|
|
2625
|
+
talkEl.classList.toggle('unsent', share && !s.shared && !caps.conceptPick);
|
|
2626
|
+
const lines = [state];
|
|
2627
|
+
if (edits) {
|
|
2628
|
+
const none = s.ready && !(s.under ?? []).length;
|
|
2629
|
+
const why = none ? t('No visible piece in the selected area') : '';
|
|
2630
|
+
const target = (tip) => (why ? { title: why, disabled: true } : { title: tip });
|
|
2631
|
+
lines.push(el('div', { class: 'line', role: 'group', 'aria-label': t('Actions for the selected area') },
|
|
2632
|
+
btn(t('Lift'), () => liftArea(true), target(t('Lifts the selected area off the topmost visible piece into a new piece. That part of the original piece is erased'))),
|
|
2633
|
+
btn(t('Copy'), () => liftArea(false), target(t('Copies the selected area into a new piece. The original piece stays as it is'))),
|
|
2634
|
+
btn(t('Erase'), () => eraseArea(), target(t('Erases the selected area from the topmost visible piece (makes it transparent)'))),
|
|
2635
|
+
btn(t('Crop'), () => cropArea(), { title: t('Crops the canvas to the rectangle around the selected area') }),
|
|
2636
|
+
btn(t('Adjust colors'), () => recolorArea(), target(t('Copies the selected area into a new piece so you can change its colors in the right panel'))),
|
|
2637
|
+
share ? null : close));
|
|
2638
|
+
}
|
|
2639
|
+
if (share) {
|
|
2640
|
+
const said = el('input', { type: 'text', 'data-keep': 'said', 'aria-label': t('Message about this selection'), placeholder: t('e.g. make this part brighter (optional)'), value: talk.said,
|
|
2641
|
+
on: { input: (e) => { talk.said = e.target.value; }, keydown: (e) => { if (e.key === 'Enter' && !e.isComposing && selection) shareSelection(); } } });
|
|
2642
|
+
const role = el('select', { 'aria-label': t('Selection role'), on: { change: (e) => { talk.role = e.target.value; } } },
|
|
2643
|
+
el('option', { value: 'change', ...(talk.role === 'change' ? { selected: true } : {}) }, t('Change this')),
|
|
2644
|
+
el('option', { value: 'reference', ...(talk.role === 'reference' ? { selected: true } : {}) }, t('For reference')));
|
|
2645
|
+
lines.push(el('div', { class: 'line' }, role, said, btn(t('Send to AI'), shareSelection, { class: 'btn primary', title: t('Sends the selection and your message to the AI. The message can be empty') }), close));
|
|
2646
|
+
}
|
|
2647
|
+
talkEl.replaceChildren(...lines);
|
|
2648
|
+
}
|
|
2649
|
+
|
|
2650
|
+
/** 뜨는 칸을 띄울 곳. 보통 위(top)이고, 고른 것이 그림 칸의 위쪽에 있어 가려지면 아래(bottom)다. 고를 때 한 번만 정한다. */
|
|
2651
|
+
function talkAt(s) {
|
|
2652
|
+
const { h } = stageSize();
|
|
2653
|
+
const boxes = s.kind === 'area' ? [s.box] : s.kind === 'point' ? [{ x: s.x, y: s.y, w: 1, h: 1 }] : s.list.map((id) => pieceById.get(id)?.box).filter(Boolean);
|
|
2654
|
+
if (!boxes.length || !(h > 0)) return 'top';
|
|
2655
|
+
const top = Math.min(...boxes.map((b) => sy(b.y)));
|
|
2656
|
+
const bottom = Math.max(...boxes.map((b) => sy(b.y + b.h)));
|
|
2657
|
+
return top < TALK_ZONE && bottom <= h - TALK_ZONE ? 'bottom' : 'top';
|
|
2658
|
+
}
|
|
2659
|
+
|
|
2660
|
+
function renderStart() {
|
|
2661
|
+
if (readOnly()) {
|
|
2662
|
+
startEl.replaceChildren(el('p', { class: 'empty' }, t('No picture yet.')));
|
|
2663
|
+
return;
|
|
2664
|
+
}
|
|
2665
|
+
const lim = limits();
|
|
2666
|
+
const samples = data?.samples ?? [];
|
|
2667
|
+
const zone = el('div', { id: 'drop', on: { click: (e) => { if (e?.target && typeof e.target.closest === 'function' && e.target.closest('button')) return; chooseFile('start'); } } },
|
|
2668
|
+
icon('picture', 'big'),
|
|
2669
|
+
el('p', { class: 'lead' }, t('Drop a PNG file here, or click to choose one. You can also paste one (Ctrl+V).')),
|
|
2670
|
+
el('p', { class: 'note' }, t('Only PNG files. Each file can be up to {size}, and the longest side up to {side} pixels.', { size: sizeText(lim.imageBytes), side: lim.side })),
|
|
2671
|
+
el('div', { class: 'group' },
|
|
2672
|
+
btn(t('Choose file'), () => chooseFile('start'), { class: 'btn primary' }),
|
|
2673
|
+
samples.map((s) => btn(samples.length === 1 ? t('Start with sample') : t('Start with sample ({title})', { title: s.title }), () => startSample(s), { title: t('Starts with the built-in sample {title} ({id})', { title: s.title, id: s.id }) }))));
|
|
2674
|
+
startEl.replaceChildren(zone);
|
|
2675
|
+
}
|
|
2676
|
+
|
|
2677
|
+
function render() {
|
|
2678
|
+
if (!concept) return;
|
|
2679
|
+
if (!data?.canvas) { renderStart(); renderTalk(); return; }
|
|
2680
|
+
updateBar();
|
|
2681
|
+
keepFocus(() => {
|
|
2682
|
+
fillSec(sec.info, infoParts());
|
|
2683
|
+
fillSec(sec.sel, selParts());
|
|
2684
|
+
renderTalk();
|
|
2685
|
+
fillSec(sec.values, valueParts());
|
|
2686
|
+
fillSec(sec.pieces, pieceListParts());
|
|
2687
|
+
fillSec(sec.regions, regionParts());
|
|
2688
|
+
fillSec(sec.images, imageParts());
|
|
2689
|
+
});
|
|
2690
|
+
drawSelCanvas();
|
|
2691
|
+
drawOverlay();
|
|
2692
|
+
}
|
|
2693
|
+
|
|
2694
|
+
// 아래 draw:begin 과 draw:end 사이는 src/draw.js 의 글 그대로다. build.mjs 가 맞추고 src/screen.test.ts 가 같은지 본다.
|
|
2695
|
+
// 논리의 renderOutput(코어가 PNG 로 저장하고 AI 가 read_image 로 보는 그림)과 이 화면이 같은 글로 그린다
|
|
2696
|
+
|
|
2697
|
+
// draw:begin
|
|
2698
|
+
/** 숫자를 소수 셋째 자리까지 적는다. */
|
|
2699
|
+
function pdNum(v) {
|
|
2700
|
+
const r = Math.round(Number(v) * 1000) / 1000;
|
|
2701
|
+
return Number.isFinite(r) ? String(r === 0 ? 0 : r) : '0';
|
|
2702
|
+
}
|
|
2703
|
+
|
|
2704
|
+
/** 행렬의 숫자는 여섯째 자리까지 적는다(돌림과 크기의 곱이라 자릿수가 더 필요하다). */
|
|
2705
|
+
function pdMat(m) {
|
|
2706
|
+
return 'matrix(' + m.map((v) => { const r = Math.round(Number(v) * 1e6) / 1e6; return Number.isFinite(r) ? String(r === 0 ? 0 : r) : '0'; }).join(' ') + ')';
|
|
2707
|
+
}
|
|
2708
|
+
|
|
2709
|
+
/** id 와 키에는 영문, 숫자, 밑줄, 줄표만 남긴다. */
|
|
2710
|
+
function pdName(s) {
|
|
2711
|
+
return String(s).replace(/[^A-Za-z0-9_-]/g, '_');
|
|
2712
|
+
}
|
|
2713
|
+
|
|
2714
|
+
/** 색은 #rrggbb 만 적는다. 모양이 틀리면 검정이다. */
|
|
2715
|
+
function pdColor(s) {
|
|
2716
|
+
return /^#[0-9a-f]{6}$/.test(String(s)) ? String(s) : '#000000';
|
|
2717
|
+
}
|
|
2718
|
+
|
|
2719
|
+
function pdIsIdentity(m) {
|
|
2720
|
+
return !m || (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1 && m[4] === 0 && m[5] === 0);
|
|
2721
|
+
}
|
|
2722
|
+
|
|
2723
|
+
/**
|
|
2724
|
+
* 모양 하나를 검정으로 그린다. 고른 모양 PNG(kind mask)는 검정에 알파로 저장한 것이라 그대로 쓴다.
|
|
2725
|
+
* 보이는 곳(clip)은 알파로 읽는 mask 안에, 지운 곳(holes)은 흰 바탕 위에 검정으로 덮는 mask 안에 넣으므로 둘 다 검정이면 된다.
|
|
2726
|
+
*/
|
|
2727
|
+
function pdShape(s) {
|
|
2728
|
+
let body = '';
|
|
2729
|
+
if (s.kind === 'rect') body = '<rect x="' + pdNum(s.x) + '" y="' + pdNum(s.y) + '" width="' + pdNum(s.w) + '" height="' + pdNum(s.h) + '" fill="#000"/>';
|
|
2730
|
+
else if (s.kind === 'ellipse') body = '<ellipse cx="' + pdNum(s.cx) + '" cy="' + pdNum(s.cy) + '" rx="' + pdNum(s.rx) + '" ry="' + pdNum(s.ry) + '" fill="#000"/>';
|
|
2731
|
+
else if (s.kind === 'polygon') body = '<polygon points="' + s.points.map((p) => pdNum(p[0]) + ',' + pdNum(p[1])).join(' ') + '" fill="#000"/>';
|
|
2732
|
+
else if (s.kind === 'mask') body = '<use href="#m-' + pdName(s.key) + '" x="' + pdNum(s.x) + '" y="' + pdNum(s.y) + '"/>';
|
|
2733
|
+
return pdIsIdentity(s.m) ? body : '<g transform="' + pdMat(s.m) + '">' + body + '</g>';
|
|
2734
|
+
}
|
|
2735
|
+
|
|
2736
|
+
/**
|
|
2737
|
+
* 색 바꾸기를 filter 의 단계로 적는다. 바꾼 것이 없으면 빈 글이다. 차례는 색조, 채도, 밝기, 색 입히기다.
|
|
2738
|
+
* 모든 단계는 입력 하나를 픽셀마다 바꾸는 것(feColorMatrix, feComponentTransfer)만 쓴다. 두 입력을 합치는 단계(feFlood 와
|
|
2739
|
+
* feComposite)는 쓰지 않는다. 그림의 한 부분만 그릴 때(보기 조건) filter 의 영역이 그리는 곳 밖에 걸치면 resvg 가 두 입력의 크기가
|
|
2740
|
+
* 다르다며 멈추고, 그러면 코어가 함께 꺼진다(2026-11-25 수달 그림의 구역 q.2.1 에서 확인).
|
|
2741
|
+
*/
|
|
2742
|
+
function pdFilterSteps(a) {
|
|
2743
|
+
let out = '';
|
|
2744
|
+
if (a.hue) out += '<feColorMatrix type="hueRotate" values="' + pdNum(a.hue) + '"/>';
|
|
2745
|
+
if (a.saturate !== 1) out += '<feColorMatrix type="saturate" values="' + pdNum(a.saturate) + '"/>';
|
|
2746
|
+
if (a.brightness !== 1) {
|
|
2747
|
+
const k = pdNum(a.brightness);
|
|
2748
|
+
out += '<feComponentTransfer><feFuncR type="linear" slope="' + k + '"/><feFuncG type="linear" slope="' + k + '"/><feFuncB type="linear" slope="' + k + '"/></feComponentTransfer>';
|
|
2749
|
+
}
|
|
2750
|
+
if (a.tint && a.tint.amount > 0) {
|
|
2751
|
+
// 색마다 (1 - 양) × 원래 색 + 양 × 입힐 색. 알파는 그대로 두므로 보이는 곳에만 색이 든다
|
|
2752
|
+
const c = pdColor(a.tint.color);
|
|
2753
|
+
const t = a.tint.amount;
|
|
2754
|
+
const keep = pdNum(1 - t);
|
|
2755
|
+
const add = (i) => pdNum((parseInt(c.slice(i, i + 2), 16) / 255) * t);
|
|
2756
|
+
out += '<feColorMatrix type="matrix" values="' + keep + ' 0 0 0 ' + add(1) + ' 0 ' + keep + ' 0 0 ' + add(3) + ' 0 0 ' + keep + ' 0 ' + add(5) + ' 0 0 0 1 0"/>';
|
|
2757
|
+
}
|
|
2758
|
+
return out;
|
|
2759
|
+
}
|
|
2760
|
+
|
|
2761
|
+
/** 배치한 그림 파일의 사각형(네 꼭짓점을 감싼 것)이 그리는 곳과 넓이 있게 겹치는가. */
|
|
2762
|
+
function pdTouches(m, w, h, d) {
|
|
2763
|
+
const xs = [m[4], m[0] * w + m[4], m[2] * h + m[4], m[0] * w + m[2] * h + m[4]];
|
|
2764
|
+
const ys = [m[5], m[1] * w + m[5], m[3] * h + m[5], m[1] * w + m[3] * h + m[5]];
|
|
2765
|
+
return Math.max.apply(null, xs) > d.x && Math.min.apply(null, xs) < d.x + d.w && Math.max.apply(null, ys) > d.y && Math.min.apply(null, ys) < d.y + d.h;
|
|
2766
|
+
}
|
|
2767
|
+
|
|
2768
|
+
/**
|
|
2769
|
+
* 그림의 정의(defs)와 조각들(body)을 따로 돌려준다. 화면은 정의를 그림 파일이 바뀔 때만 다시 넣는다.
|
|
2770
|
+
* scene: { width, height, images: [{ id, width, height }], pieces: [{ id, image, hidden, matrix, clip, holes, adjust }], area? }
|
|
2771
|
+
* area 는 그림의 한 부분만 그릴 때의 사각형 { x, y, w, h } 다. 없으면 그림판 전체다.
|
|
2772
|
+
* pieces 는 아래에서 위로 그리는 차례다. matrix 는 조각의 배치 행렬 [a, b, c, d, e, f] 다.
|
|
2773
|
+
* dataOf(name): 그림 파일 id 나 고른 모양의 key 를 주면 base64 글을 돌려준다.
|
|
2774
|
+
* cull: 참이면 그리는 곳과 겹치지 않는 조각을 넣지 않는다. 파일로 낼 때(pdSvg, 보기 조건)는 꼭 켠다. 그리는 곳 밖에 통째로 나간
|
|
2775
|
+
* 조각에 불투명도나 mask 가 있으면 resvg 가 멈추고 코어가 함께 꺼진다(2026-11-25 확인). 화면은 끄는 동안 조각의 요소를 써야
|
|
2776
|
+
* 하므로 켜지 않는다(브라우저는 멈추지 않는다).
|
|
2777
|
+
*/
|
|
2778
|
+
function pdParts(scene, dataOf, cull) {
|
|
2779
|
+
const sizeOf = {};
|
|
2780
|
+
for (const im of scene.images) sizeOf[im.id] = im;
|
|
2781
|
+
const shown = scene.pieces.filter((p) => !p.hidden && sizeOf[p.image]);
|
|
2782
|
+
// 그리는 곳. 그림의 한 부분만 그릴 때(보기 조건)는 scene.area 가 그 사각형이고, 아니면 그림판 전체다
|
|
2783
|
+
const drawn = scene.area || { x: 0, y: 0, w: scene.width, h: scene.height };
|
|
2784
|
+
const usedImages = {};
|
|
2785
|
+
const maskSeen = {};
|
|
2786
|
+
let imageDefs = '';
|
|
2787
|
+
let maskDefs = '';
|
|
2788
|
+
let pieceDefs = '';
|
|
2789
|
+
let body = '';
|
|
2790
|
+
for (const p of shown) {
|
|
2791
|
+
const im = sizeOf[p.image];
|
|
2792
|
+
if (cull && !pdTouches(p.matrix, im.width, im.height, drawn)) continue;
|
|
2793
|
+
const pid = pdName(p.id);
|
|
2794
|
+
if (!usedImages[im.id]) {
|
|
2795
|
+
usedImages[im.id] = true;
|
|
2796
|
+
imageDefs += '<image id="i-' + pdName(im.id) + '" width="' + pdNum(im.width) + '" height="' + pdNum(im.height) + '" href="data:image/png;base64,' + dataOf(im.id) + '"/>';
|
|
2797
|
+
}
|
|
2798
|
+
for (const s of p.clip.concat(p.holes)) {
|
|
2799
|
+
if (s.kind !== 'mask' || maskSeen[s.key]) continue;
|
|
2800
|
+
maskSeen[s.key] = true;
|
|
2801
|
+
maskDefs += '<image id="m-' + pdName(s.key) + '" width="' + pdNum(s.w) + '" height="' + pdNum(s.h) + '" href="data:image/png;base64,' + dataOf(s.key) + '"/>';
|
|
2802
|
+
}
|
|
2803
|
+
const area = ' maskUnits="userSpaceOnUse" x="0" y="0" width="' + pdNum(im.width) + '" height="' + pdNum(im.height) + '"';
|
|
2804
|
+
let inner = '<use href="#i-' + pdName(im.id) + '"/>';
|
|
2805
|
+
if (p.holes.length) {
|
|
2806
|
+
pieceDefs += '<mask id="h-' + pid + '"' + area + '><rect x="0" y="0" width="' + pdNum(im.width) + '" height="' + pdNum(im.height) + '" fill="#fff"/>' + p.holes.map(pdShape).join('') + '</mask>';
|
|
2807
|
+
inner = '<g mask="url(#h-' + pid + ')">' + inner + '</g>';
|
|
2808
|
+
}
|
|
2809
|
+
for (let i = p.clip.length - 1; i >= 0; i -= 1) {
|
|
2810
|
+
pieceDefs += '<mask id="c-' + pid + '-' + i + '"' + area + ' mask-type="alpha" style="mask-type:alpha">' + pdShape(p.clip[i]) + '</mask>';
|
|
2811
|
+
inner = '<g mask="url(#c-' + pid + '-' + i + ')">' + inner + '</g>';
|
|
2812
|
+
}
|
|
2813
|
+
let piece = '<g data-piece="' + pid + '"' + (pdIsIdentity(p.matrix) ? '' : ' transform="' + pdMat(p.matrix) + '"') + (p.adjust.opacity !== 1 ? ' opacity="' + pdNum(p.adjust.opacity) + '"' : '') + '>' + inner + '</g>';
|
|
2814
|
+
const steps = pdFilterSteps(p.adjust);
|
|
2815
|
+
if (steps) {
|
|
2816
|
+
// filter 는 배치 밖에서 입히고, 영역은 언제나 그리는 곳(drawn) 그대로다. 조각의 배치 안에 두면 조각이 그리는 곳 밖으로 나갔을 때
|
|
2817
|
+
// filter 의 영역이 그리는 곳과 겹치지 않아 resvg 가 멈추고 코어가 함께 꺼진다(2026-11-25 확인). 색만 바꾸는 단계라 배치와 차례를
|
|
2818
|
+
// 바꿔도 결과가 같다
|
|
2819
|
+
pieceDefs += '<filter id="f-' + pid + '" filterUnits="userSpaceOnUse" x="' + pdNum(drawn.x) + '" y="' + pdNum(drawn.y) + '" width="' + pdNum(drawn.w) + '" height="' + pdNum(drawn.h) + '" color-interpolation-filters="sRGB">' + steps + '</filter>';
|
|
2820
|
+
piece = '<g filter="url(#f-' + pid + ')">' + piece + '</g>';
|
|
2821
|
+
}
|
|
2822
|
+
body += piece;
|
|
2823
|
+
}
|
|
2824
|
+
return { imageDefs: imageDefs, maskDefs: maskDefs, pieceDefs: pieceDefs, body: body };
|
|
2825
|
+
}
|
|
2826
|
+
|
|
2827
|
+
/** 파일 하나로 저장할 SVG 글. 배경은 칠하지 않아 빈 곳은 투명하다. */
|
|
2828
|
+
function pdSvg(scene, dataOf) {
|
|
2829
|
+
const parts = pdParts(scene, dataOf, true);
|
|
2830
|
+
const w = pdNum(scene.width);
|
|
2831
|
+
const h = pdNum(scene.height);
|
|
2832
|
+
return '<svg xmlns="http://www.w3.org/2000/svg" width="' + w + '" height="' + h + '" viewBox="0 0 ' + w + ' ' + h + '"><defs>' + parts.imageDefs + parts.maskDefs + parts.pieceDefs + '</defs>' + parts.body + '</svg>';
|
|
2833
|
+
}
|
|
2834
|
+
// draw:end
|
|
2835
|
+
|
|
2836
|
+
// 화면 파일에 적힌 요소들. 위쪽 줄과 오른쪽 칸을 만들기 전에 모아 두어, 언어를 바꿀 때 사람의 입력이 든 요소는 건드리지 않는다
|
|
2837
|
+
const markupEls = Array.from(document.body.querySelectorAll('*')).filter((n) => n.localName !== 'script' && n.localName !== 'style');
|
|
2838
|
+
|
|
2839
|
+
/** 화면 파일에 적힌 글(제목, 요소 안의 글, aria-label, title, placeholder)을 고른 언어로 바꾼다. 처음 언어를 알았을 때 한 번만 부른다. */
|
|
2840
|
+
function translateStatic() {
|
|
2841
|
+
document.documentElement.lang = lang;
|
|
2842
|
+
document.title = ko(document.title);
|
|
2843
|
+
for (const n of markupEls) {
|
|
2844
|
+
for (const a of ['aria-label', 'title', 'placeholder']) if (n.hasAttribute(a)) n.setAttribute(a, ko(n.getAttribute(a)));
|
|
2845
|
+
for (const c of Array.from(n.childNodes ?? [])) if (c.nodeType === 3 && c.nodeValue.trim()) c.nodeValue = c.nodeValue.replace(c.nodeValue.trim(), ko(c.nodeValue.trim()));
|
|
2846
|
+
}
|
|
2847
|
+
}
|
|
2848
|
+
|
|
2849
|
+
/**
|
|
2850
|
+
* 호스트가 알린 언어(capabilities 의 language, plugin-guide 4.4절)로 화면 글을 바꾼다. 'ko' 일 때만 한국어이고, 없거나 다른 값이면
|
|
2851
|
+
* 영어 그대로다. 사람이 언어를 바꾸면 호스트가 화면을 다시 불러오므로 처음 한 번만 본다. 이미 영어로 만든 위쪽 줄과 오른쪽 칸은 다시 만든다.
|
|
2852
|
+
*/
|
|
2853
|
+
function applyLanguage(value) {
|
|
2854
|
+
if (value !== 'ko' || lang === 'ko') return;
|
|
2855
|
+
lang = 'ko';
|
|
2856
|
+
translateStatic();
|
|
2857
|
+
setMenu(null);
|
|
2858
|
+
buildBar();
|
|
2859
|
+
buildSide();
|
|
2860
|
+
setSide(sideOpen);
|
|
2861
|
+
setTool(tool);
|
|
2862
|
+
applyView();
|
|
2863
|
+
}
|
|
2864
|
+
|
|
2865
|
+
buildBar();
|
|
2866
|
+
buildSide();
|
|
2867
|
+
setSide(false);
|
|
2868
|
+
setTool('piece');
|
|
2869
|
+
if (typeof ResizeObserver === 'function') {
|
|
2870
|
+
new ResizeObserver(() => { if (!data?.canvas) return; if (view.auto) fit(); else drawOverlay(); }).observe(stage);
|
|
2871
|
+
} else {
|
|
2872
|
+
window.addEventListener('resize', () => { if (data?.canvas) { if (view.auto) fit(); else drawOverlay(); } });
|
|
2873
|
+
}
|
|
2874
|
+
|
|
2875
|
+
parent.postMessage({ aic: 1, event: 'ready', rendered: true }, '*');
|
|
2876
|
+
call('capabilities', {}).then((cap) => {
|
|
2877
|
+
caps = { ...caps, ...(cap ?? {}) };
|
|
2878
|
+
applyLanguage(caps.language);
|
|
2879
|
+
// 고칠 수 있는 화면인지에 따라 그림을 맞추는 높이가 달라진다
|
|
2880
|
+
if (concept) { if (data?.canvas && view.auto) fit(); render(); notePick(); }
|
|
2881
|
+
}, () => {});
|
|
2882
|
+
refresh();
|
|
2883
|
+
</script>
|
|
2884
|
+
</body>
|
|
2885
|
+
</html>
|