HelloSun commited on
Commit
48e919b
·
verified ·
1 Parent(s): 1cd0943

Fix DOS screen on HiDPI (was 2x too large and cropped): device-pixel presenter, sharp scaling, 4:3, zoom modes

Browse files
Files changed (6) hide show
  1. README.md +1 -0
  2. app.js +56 -17
  3. dev/HANDOFF.md +6 -2
  4. dev/dosllm-dev.zip +2 -2
  5. index.html +2 -2
  6. style.css +9 -0
README.md CHANGED
@@ -30,6 +30,7 @@ turns each HTTP request DOS sends on **port 80** into an HTTPS `fetch()`. It rel
30
  ## Things to know
31
 
32
  - **Chinese and English both work.** DOS runs **小貓中文** (Big5 display + Zhuyin input), so the question and the answer are shown in Chinese on the DOS screen; type in DOS with `Ctrl+Space` (注音). Characters Big5 does not have (Simplified Chinese, emoji) show as `?`; Chinese questions ask the model for Traditional Chinese. Replies are limited to ~40 words / ~80 Chinese characters.
 
33
  - The Big5 <-> UTF-8 conversion happens in the page (`big5.js`); DOS only ever sees Big5.
34
  - Your question is sent to the chosen public Space (it is a third-party service). Do not type secrets.
35
  - If DOS ever hangs, press **重新開機** (reboot). Another Space can be tried under "進階" if it exposes a `/chat` endpoint with the same 9 parameters as `tencent/Hy3`.
 
30
  ## Things to know
31
 
32
  - **Chinese and English both work.** DOS runs **小貓中文** (Big5 display + Zhuyin input), so the question and the answer are shown in Chinese on the DOS screen; type in DOS with `Ctrl+Space` (注音). Characters Big5 does not have (Simplified Chinese, emoji) show as `?`; Chinese questions ask the model for Traditional Chinese. Replies are limited to ~40 words / ~80 Chinese characters.
33
+ - The DOS screen is 640x400 (XiaoMao). The page presents it in device pixels, 4:3 like a real VGA monitor by default, sharp on HiDPI screens; the card has a zoom selector (fit width / integer / 2x scrollable) and a 4:3 checkbox.
34
  - The Big5 <-> UTF-8 conversion happens in the page (`big5.js`); DOS only ever sees Big5.
35
  - Your question is sent to the chosen public Space (it is a third-party service). Do not type secrets.
36
  - If DOS ever hangs, press **重新開機** (reboot). Another Space can be tried under "進階" if it exposes a `/chat` endpoint with the same 9 parameters as `tencent/Hy3`.
app.js CHANGED
@@ -60,18 +60,54 @@
60
  const atPrompt = () => /^[A-Z]:\\>$/.test(lastLine().trim());
61
  async function typeLine(text) { await vm.keyboard_send_text(`${text}\n`, 25); await sleep(250); }
62
 
63
- // The VGA text layer is a fixed-size DOM block; scale it to the card width with CSS.
64
- function fitScreen() {
65
- const box = $('screen'); const text = box.firstElementChild; const canvas = box.querySelector('canvas');
66
- if (!box.clientWidth) return;
67
- const useCanvas = canvas && getComputedStyle(canvas).display !== 'none' && canvas.width > 0;
68
- const layer = useCanvas ? canvas : text;
69
- const w = useCanvas ? canvas.width : text.offsetWidth, h = useCanvas ? canvas.height : text.offsetHeight;
70
- if (!w || !h) return;
71
- const k = box.clientWidth / w;
72
- layer.style.transformOrigin = '0 0'; layer.style.transform = `scale(${k})`; box.style.height = `${Math.round(h * k)}px`;
73
  }
74
- window.addEventListener('resize', fitScreen);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
  // What G.EXE prints: a line "A> ..." followed by indented continuation lines (Chinese text wraps anywhere).
77
  const CJK = /[\u3000-\u9fff\uff00-\uffef]/;
@@ -128,11 +164,11 @@
128
  autostart: true, disable_speaker: true,
129
  });
130
  window.dosVm = vm; // handy for tests: window.dosVm.screen_adapter.get_text_screen()
131
- vm.add_listener('screen-set-size', () => window.setTimeout(fitScreen, 50));
132
  vm.keyboard_set_status(false);
133
- const focus = () => { vm.keyboard_set_status(true); $('screen').classList.add('focus'); };
134
- $('screen').addEventListener('mousedown', focus);
135
- $('screen').addEventListener('touchstart', focus, { passive: true });
136
  watchBoot();
137
  }
138
 
@@ -195,7 +231,7 @@
195
  // yet seen Ctrl when Space arrives and the toggle is missed.
196
  async function toggleIme() {
197
  if (!vm || !ready) return;
198
- vm.keyboard_set_status(true); $('screen').classList.add('focus');
199
  vm.keyboard_send_scancodes([0x1D]); await sleep(250);
200
  vm.keyboard_send_scancodes([0x39]); await sleep(150);
201
  vm.keyboard_send_scancodes([0xB9]); await sleep(150);
@@ -217,6 +253,9 @@
217
  chips().forEach((c) => c.addEventListener('click', () => ask(c.textContent)));
218
  $('rebootButton').addEventListener('click', reboot);
219
  $('imeButton').addEventListener('click', toggleIme);
220
- window.setInterval(fitScreen, 500);
 
 
 
221
  boot().catch((e) => { $('netText').textContent = 'BOOT ERROR'; $('note').textContent = `啟動失敗:${e && e.message ? e.message : e}`; console.error(e); });
222
  })();
 
60
  const atPrompt = () => /^[A-Z]:\\>$/.test(lastLine().trim());
61
  async function typeLine(text) { await vm.keyboard_send_text(`${text}\n`, 25); await sleep(250); }
62
 
63
+ // ---- screen presentation -------------------------------------------------------------------------------
64
+ // Before XiaoMao loads (first ~2 s) v86 shows an 80x25 DOM text layer; scale it to the card width with CSS.
65
+ function fitText() {
66
+ const stage = $('stage'); const text = $('screen').firstElementChild;
67
+ if (!stage.clientWidth || !text || !text.offsetWidth) return;
68
+ const k = stage.clientWidth / text.offsetWidth;
69
+ text.style.transformOrigin = '0 0'; text.style.transform = `scale(${k})`; stage.style.height = `${Math.round(text.offsetHeight * k)}px`;
 
 
 
70
  }
71
+ // With XiaoMao the VGA is in a 640x400 graphics mode and v86 draws it on its own canvas, whose CSS size it sets from
72
+ // devicePixelRatio. Scaling that canvas with CSS (the first version) broke on HiDPI screens (shown 2x too large and cropped) and
73
+ // gave uneven strokes at fractional scales. So v86's canvas is hidden and its pixels are presented here, in device pixels:
74
+ // - integer scale in device pixels: nearest neighbour (perfectly sharp)
75
+ // - otherwise: nearest-neighbour up to the next integer, then smooth down ("sharp bilinear"): even strokes, no shimmer
76
+ let zoom = (window.localStorage && localStorage.getItem('dosllm.zoom')) || 'fit';
77
+ let aspect43 = !(window.localStorage && localStorage.getItem('dosllm.aspect') === '0');
78
+ const view = $('view'); const vctx = view.getContext('2d');
79
+ const off = document.createElement('canvas'); const octx = off.getContext('2d');
80
+ window.presentInfo = {};
81
+ function present() {
82
+ if (!vm) return;
83
+ const stage = $('stage'); const host = $('screen'); const src = host.querySelector('canvas'); const vga = vm.v86.cpu.devices.vga;
84
+ const graphical = !!(vga && vga.graphical_mode && src && src.width > 0 && src.height > 0);
85
+ host.classList.toggle('hidden', graphical); view.style.display = graphical ? 'block' : 'none';
86
+ if (!graphical) { stage.classList.remove('scroll'); fitText(); return; }
87
+ const dpr = window.devicePixelRatio || 1; const avail = stage.clientWidth; if (!avail) return;
88
+ const nw = src.width, nh = src.height;
89
+ let sx; let sy; // CSS pixels per source pixel
90
+ if (zoom === 'crisp') { sx = Math.max(1, Math.floor(avail * dpr / nw)) / dpr; sy = sx; } // integer device pixels, square
91
+ else {
92
+ sx = zoom === 'big' ? 2 : avail / nw;
93
+ sy = sx * (aspect43 ? (nw / nh) / (4 / 3) : 1); // 640x400 shown as 4:3 like a real VGA monitor: rows 1.2x taller
94
+ }
95
+ let pw = Math.round(nw * sx * dpr); let ph = Math.round(nh * sy * dpr);
96
+ const area = pw * ph; if (area > 16e6) { const f = Math.sqrt(16e6 / area); pw = Math.round(pw * f); ph = Math.round(ph * f); } // keep memory sane
97
+ if (view.width !== pw || view.height !== ph) { view.width = pw; view.height = ph; }
98
+ const cw = pw / dpr; const chh = ph / dpr; view.style.width = `${cw}px`; view.style.height = `${chh}px`;
99
+ stage.style.height = `${Math.round(chh)}px`; stage.classList.toggle('scroll', cw > avail + 1);
100
+ const kx = Math.ceil(pw / nw); const ky = Math.ceil(ph / nh);
101
+ if (pw === nw * kx && ph === nh * ky) { vctx.imageSmoothingEnabled = false; vctx.drawImage(src, 0, 0, pw, ph); }
102
+ else {
103
+ const ow = nw * Math.min(kx, 8); const oh = nh * Math.min(ky, 8);
104
+ if (off.width !== ow || off.height !== oh) { off.width = ow; off.height = oh; }
105
+ octx.imageSmoothingEnabled = false; octx.drawImage(src, 0, 0, ow, oh);
106
+ vctx.imageSmoothingEnabled = true; vctx.imageSmoothingQuality = 'high'; vctx.drawImage(off, 0, 0, pw, ph);
107
+ }
108
+ window.presentInfo = { dpr, avail, native: [nw, nh], css: [Math.round(cw), Math.round(chh)], device: [pw, ph], scaleDevice: [+(pw / nw).toFixed(3), +(ph / nh).toFixed(3)], zoom, aspect43 };
109
+ }
110
+ window.addEventListener('resize', present);
111
 
112
  // What G.EXE prints: a line "A> ..." followed by indented continuation lines (Chinese text wraps anywhere).
113
  const CJK = /[\u3000-\u9fff\uff00-\uffef]/;
 
164
  autostart: true, disable_speaker: true,
165
  });
166
  window.dosVm = vm; // handy for tests: window.dosVm.screen_adapter.get_text_screen()
167
+ vm.add_listener('screen-set-size', () => window.setTimeout(present, 50));
168
  vm.keyboard_set_status(false);
169
+ const focus = () => { vm.keyboard_set_status(true); $('stage').classList.add('focus'); };
170
+ $('stage').addEventListener('mousedown', focus);
171
+ $('stage').addEventListener('touchstart', focus, { passive: true });
172
  watchBoot();
173
  }
174
 
 
231
  // yet seen Ctrl when Space arrives and the toggle is missed.
232
  async function toggleIme() {
233
  if (!vm || !ready) return;
234
+ vm.keyboard_set_status(true); $('stage').classList.add('focus');
235
  vm.keyboard_send_scancodes([0x1D]); await sleep(250);
236
  vm.keyboard_send_scancodes([0x39]); await sleep(150);
237
  vm.keyboard_send_scancodes([0xB9]); await sleep(150);
 
253
  chips().forEach((c) => c.addEventListener('click', () => ask(c.textContent)));
254
  $('rebootButton').addEventListener('click', reboot);
255
  $('imeButton').addEventListener('click', toggleIme);
256
+ window.setInterval(present, 66); // ~15 fps is plenty for a text screen
257
+ $('zoomSel').value = zoom; $('aspect').checked = aspect43; $('aspectLabel').style.display = zoom === 'crisp' ? 'none' : '';
258
+ $('zoomSel').addEventListener('change', () => { zoom = $('zoomSel').value; try { localStorage.setItem('dosllm.zoom', zoom); } catch (e) { /* private mode */ } $('aspectLabel').style.display = zoom === 'crisp' ? 'none' : ''; present(); });
259
+ $('aspect').addEventListener('change', () => { aspect43 = $('aspect').checked; try { localStorage.setItem('dosllm.aspect', aspect43 ? '1' : '0'); } catch (e) { /* private mode */ } present(); });
260
  boot().catch((e) => { $('netText').textContent = 'BOOT ERROR'; $('note').textContent = `啟動失敗:${e && e.message ? e.message : e}`; console.error(e); });
261
  })();
dev/HANDOFF.md CHANGED
@@ -85,8 +85,11 @@ Buttons: main ask, 4 example chips, reboot (`vm.restart()`). `window.dosVm` expo
85
  * mTCP needs `#include "global.cfg"` lowercase in `g.cfg` on Linux; `g.cfg` is mTCP's `SAMPLE.CFG` with `TCP_MAX_SOCKETS 2`. Rebuilt EXEs differ only by mTCP's embedded build date string.
86
  * **Typing into DOS:** `emu.keyboard_send_text(text, 25)`; without the 25 ms delay FreeCOM drops characters. Give each command >= 250 ms before the next.
87
  The question is sanitised twice (page and G.EXE): printable ASCII only; `" \ % & | < > ^ !` removed because FreeCOM would interpret them. DOS command line limit is 127 characters.
88
- * **Screen scaling:** in text mode v86 draws an 80x25 DOM text layer, not the canvas. `screen_set_scale()` and `use_graphical_text` produced a black/cropped screen;
89
- `fitScreen()` scales the visible layer with a CSS `transform`.
 
 
 
90
  * G.EXE uses a different local TCP port per connection (`pseudoPort() + counter`). DNS answers rotate between several A records (normal). DOS clock is **UTC**.
91
  * The page reads results from the DOS screen: lines `A> ...` plus 3-space-indented continuation lines. If you change G.EXE's output format, change `dosAnswer()` too.
92
 
@@ -96,6 +99,7 @@ Buttons: main ask, 4 example chips, reboot (`vm.restart()`). `window.dosVm` expo
96
  * `python3 -m http.server 8805 --directory dist` then
97
  `python3 tests/ask.py http://127.0.0.1:8805/ "question"` (also works on the live URL): waits for DOS networking, clicks the button, prints the log, the DOS-vs-LLM check, and saves a screenshot.
98
  * `python3 tests/stress.py 20 http://127.0.0.1:8805/`: asks N times and, if one question has not finished after 45 s, prints the DOS screen and v86's TCP connection state.
 
99
  * `python3 tests/multi.py <url> [questions...]`: a list of Chinese/English/edge-case questions on one page; `python3 tests/ime_typing.py <url>`: typing 你好 in DOS with the Zhuyin IME.
100
  * Results when this was written (local, English only, before the Chinese work): main button, example chip, reboot button all fine; **20/20 questions answered, every one `DOS = LLM`**; `17 times 23` -> DOS printed `391`.
101
  * Use `kill <pid>`; `pkill -f <name>` kills your own shell.
 
85
  * mTCP needs `#include "global.cfg"` lowercase in `g.cfg` on Linux; `g.cfg` is mTCP's `SAMPLE.CFG` with `TCP_MAX_SOCKETS 2`. Rebuilt EXEs differ only by mTCP's embedded build date string.
86
  * **Typing into DOS:** `emu.keyboard_send_text(text, 25)`; without the 25 ms delay FreeCOM drops characters. Give each command >= 250 ms before the next.
87
  The question is sanitised twice (page and G.EXE): printable ASCII only; `" \ % & | < > ^ !` removed because FreeCOM would interpret them. DOS command line limit is 127 characters.
88
+ * **Screen scaling / HiDPI (a real bug I shipped once).** In *graphics* mode v86 sets its canvas CSS size from `devicePixelRatio`. My first version scaled that canvas with a CSS
89
+ `transform` computed from `canvas.width` (640), so on DPR 2 screens (retina laptops, most phones) the screen came out 2x too large inside `overflow:hidden`: only the top-left quarter was
90
+ visible and long answers were cut off. At DPR 1 it showed fine but at 1.34x (uneven stroke widths). **Do not style v86's canvas.** `present()` in `app.js` hides it and draws its pixels
91
+ onto our own `#view` canvas in *device* pixels (see section 10). In text mode (before XiaoMao loads) v86 draws an 80x25 DOM text layer, which `fitText()` scales with a CSS transform.
92
+ `screen_set_scale()` and `use_graphical_text` produced a black/cropped screen: not used.
93
  * G.EXE uses a different local TCP port per connection (`pseudoPort() + counter`). DNS answers rotate between several A records (normal). DOS clock is **UTC**.
94
  * The page reads results from the DOS screen: lines `A> ...` plus 3-space-indented continuation lines. If you change G.EXE's output format, change `dosAnswer()` too.
95
 
 
99
  * `python3 -m http.server 8805 --directory dist` then
100
  `python3 tests/ask.py http://127.0.0.1:8805/ "question"` (also works on the live URL): waits for DOS networking, clicks the button, prints the log, the DOS-vs-LLM check, and saves a screenshot.
101
  * `python3 tests/stress.py 20 http://127.0.0.1:8805/`: asks N times and, if one question has not finished after 45 s, prints the DOS screen and v86's TCP connection state.
102
+ * `python3 tests/display.py <url> <prefix>`: presenter geometry + screenshots at DPR 1/2/3 (look at the PNGs).
103
  * `python3 tests/multi.py <url> [questions...]`: a list of Chinese/English/edge-case questions on one page; `python3 tests/ime_typing.py <url>`: typing 你好 in DOS with the Zhuyin IME.
104
  * Results when this was written (local, English only, before the Chinese work): main button, example chip, reboot button all fine; **20/20 questions answered, every one `DOS = LLM`**; `17 times 23` -> DOS printed `391`.
105
  * Use `kill <pid>`; `pkill -f <name>` kills your own shell.
dev/dosllm-dev.zip CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:2eb00b6bf51aa092e6eb25c69ef47bf26bc398811272856b673974958dfad542
3
- size 1276905
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:feb36d04635a698c0945dccdc87634bdea5b429e4e2c7cf46dfdf1bce4953c00
3
+ size 1280396
index.html CHANGED
@@ -61,8 +61,8 @@
61
 
62
  <section class="workstations one" aria-label="DOS 虛擬機">
63
  <article class="terminal-card panel">
64
- <div class="terminal-title"><span class="terminal-icon">G</span><div><h2>FreeDOS <span class="role">G.EXE</span></h2><p>點選畫面可直接用鍵盤:<code>G your question</code>;要打中文按 <code>Ctrl+Space</code> 開注音(倚天鍵位)</p></div><span class="state-pill" id="dosState">BOOT</span><button class="ghost" id="imeButton" type="button" title="等同在 DOS 畫面按 Ctrl+Space:開/關小貓中文的注音輸入">注音 Ctrl+Space</button><button class="ghost" id="rebootButton" type="button" style="margin-left:8px">重新開機</button></div>
65
- <div class="dos-screen" id="screen"><div></div><canvas></canvas></div>
66
  <div class="terminal-footer"><span>ASKED <b id="askCount">000</b></span><span>ANSWERED <b id="ansCount">000</b></span><span class="grow"></span><span id="ip">IP —</span></div>
67
  </article>
68
  </section>
 
61
 
62
  <section class="workstations one" aria-label="DOS 虛擬機">
63
  <article class="terminal-card panel">
64
+ <div class="terminal-title"><span class="terminal-icon">G</span><div><h2>FreeDOS <span class="role">G.EXE</span></h2><p>點選畫面可直接用鍵盤:<code>G your question</code>;要打中文按 <code>Ctrl+Space</code> 開注音(倚天鍵位)</p></div><span class="state-pill" id="dosState">BOOT</span><select class="ghost" id="zoomSel" title="畫面縮放"><option value="fit">符合寬度</option><option value="crisp">整數倍(最銳利)</option><option value="big">放大 2×(可捲動)</option></select><label class="ghost" id="aspectLabel" title="真實 VGA 螢幕把 640×400 顯示成 4:3,畫素略高;取消則為正方形畫素"><input type="checkbox" id="aspect" checked> 4:3</label><button class="ghost" id="imeButton" type="button" title="等同在 DOS 畫面按 Ctrl+Space:開/關小貓中文的注音輸入">注音 Ctrl+Space</button><button class="ghost" id="rebootButton" type="button" style="margin-left:8px">重新開機</button></div>
65
+ <div class="dos-screen" id="stage"><div id="screen" class="v86host"><div></div><canvas></canvas></div><canvas id="view" aria-label="DOS 畫面"></canvas></div>
66
  <div class="terminal-footer"><span>ASKED <b id="askCount">000</b></span><span>ANSWERED <b id="ansCount">000</b></span><span class="grow"></span><span id="ip">IP —</span></div>
67
  </article>
68
  </section>
style.css CHANGED
@@ -27,3 +27,12 @@ button,input{font:inherit}
27
  .log-row .t{color:#69796d}.log-row .src{color:#94ae91}.log-row.b .src{color:var(--blue)}.log-row.bridge .src{color:#c9b26a}
28
  .log-row.ok .msg{color:var(--green)}.log-row.err .msg{color:#ff9a88}
29
  @media(max-width:800px){.workstations{grid-template-columns:1fr}.log-row{grid-template-columns:60px 54px 1fr}}
 
 
 
 
 
 
 
 
 
 
27
  .log-row .t{color:#69796d}.log-row .src{color:#94ae91}.log-row.b .src{color:var(--blue)}.log-row.bridge .src{color:#c9b26a}
28
  .log-row.ok .msg{color:var(--green)}.log-row.err .msg{color:#ff9a88}
29
  @media(max-width:800px){.workstations{grid-template-columns:1fr}.log-row{grid-template-columns:60px 54px 1fr}}
30
+
31
+ /* DOS screen: our own presenter canvas (integer / sharp-bilinear scaling, DPR aware) */
32
+ #view{display:none;margin:0 auto;image-rendering:pixelated}
33
+ .dos-screen.scroll{overflow-x:auto}
34
+ .dos-screen.scroll #view{margin:0}
35
+ .v86host.hidden{position:absolute;visibility:hidden;width:0;height:0;overflow:hidden;pointer-events:none}
36
+ .terminal-title select.ghost,.terminal-title label.ghost{display:inline-flex;align-items:center;gap:5px;margin-left:8px;height:30px;padding:0 8px;font:10px 'DM Mono',monospace}
37
+ .terminal-title label.ghost input{margin:0}
38
+ @media(max-width:700px){.terminal-title{flex-wrap:wrap}.terminal-title .ghost{margin-left:0;margin-top:6px}}