Skip to content

Free games for graphing calculators: NumWorks, TI-Nspire CX, Casio fx-CG50 and soon TI-84 Plus CE. Balatro, Celeste, Hollow Knight, Minecraft and more.

Merge pull request #89 from LilyTheCuteCatgirl: dark mode for the emulator, and its window keeps its place

Mason363b2866bc24053
diff --cc tools/emu_live.py
index 69c4039c,7f8e37fd..6497cff6
--- a/tools/emu_live.py
+++ b/tools/emu_live.py
@@@ -1478,6 -1555,66 +1514,31 @@@ class FlatButton(tk.Label)
config = configure
-def builtin_artwork() -> Path:
- """A calculator of its own, for when the VS Code extension isn't installed: the same layout (HOTSPOTS,
- SCREEN) on a 1160 x 2221 picture, drawn once and kept in ~/.numplay-emulator."""
- if BUILTIN_SKIN.is_file():
- return BUILTIN_SKIN
- w, h = 1160, 2221
- im = Image.new("RGB", (w, h), (232, 234, 238))
- d = ImageDraw.Draw(im)
- d.rounded_rectangle((6, 6, w - 7, h - 7), radius=96, fill=(250, 250, 251), outline=(200, 204, 211), width=6)
- sx, sy, sw, sh = SCREEN[0] * w, SCREEN[1] * h, SCREEN[2] * w, SCREEN[3] * h
- d.rounded_rectangle((sx - 36, sy - 36, sx + sw + 36, sy + sh + 36), radius=28, fill=(38, 40, 46))
- d.rectangle((sx, sy, sx + sw, sy + sh), fill=(0, 0, 0))
- font = None
- for name in ("DejaVuSans.ttf", "/System/Library/Fonts/Supplemental/Arial.ttf", "/Library/Fonts/Arial.ttf",
- str(Path(os.environ.get("WINDIR", r"C:\Windows")) / "Fonts" / "arial.ttf")):
- try:
- font = ImageFont.truetype(name, 42)
- break
- except OSError:
- pass
- font = font or ImageFont.load_default()
- nav = {"left", "right", "up", "down", "home", "onoff", "ok", "back"}
- for key, (x, y, kw, kh) in HOTSPOTS.items():
- box = (x * w, y * h, (x + kw) * w, (y + kh) * h)
- fill = (212, 216, 222) if key in nav else (225, 228, 233) if key in FUNCTIONS else (255, 255, 255)
- d.rounded_rectangle(box, radius=min(box[2] - box[0], box[3] - box[1]) * 0.22, fill=fill,
- outline=(178, 183, 192), width=4)
- label = "DEL" if key == "backspace" else LABEL.get(key, key) # (⌫ isn't in most fonts)
- tw, th = d.textbbox((0, 0), label, font=font)[2:]
- d.text(((box[0] + box[2] - tw) / 2, (box[1] + box[3] - th) / 2), label, fill=(48, 52, 60), font=font)
- BUILTIN_SKIN.parent.mkdir(parents=True, exist_ok=True)
- im.save(BUILTIN_SKIN)
- return BUILTIN_SKIN
-
-
+ def _safe_window_geometry(placement, root):
+ """Ignore invalid/off-screen saved placements after a display change."""
+ if not isinstance(placement, dict):
+ return None
+ values = [placement.get(k) for k in ("width", "height", "x", "y")]
+ if any(type(v) is not int or abs(v) > 100000 for v in values):
+ return None
+ width, height, x, y = values
+ if width < 400 or height < 250:
+ return None
+ screen_w, screen_h = root.winfo_screenwidth(), root.winfo_screenheight()
+ if min(screen_w, screen_h) <= 0:
+ return None
+ width = min(width, screen_w)
+ height = min(height, screen_h)
+ # A title bar and at least a strip of the window should remain accessible.
+ if x + width < 160 or x > screen_w - 160 or y + height < 60 or y > screen_h - 60:
+ x = max(0, (screen_w - width) // 2)
+ y = max(0, (screen_h - height) // 2)
+ else:
+ x = max(0, min(x, screen_w - 160))
+ y = max(0, min(y, screen_h - 60))
+ return (width, height, x, y, placement.get("maximized") is True)
+
+
class CalculatorSkinApp(LiveApp):
"""NumWorks skin with mutually exclusive file and live-development modes.
@@@ -1489,8 -1626,7 +1550,8 @@@
art_path: Path, max_sleep_ms: int = 0,
profile_speed: bool = False, start_live: bool = False):
self.art_path = art_path
- art = Image.open(art_path).convert("RGBA") # (its corners and shadow are see-through)
- self.art = Image.alpha_composite(Image.new("RGBA", art.size, BG), art).convert("RGB")
- self.art = Image.open(art_path).convert("RGB")
++ self._art_rgba = Image.open(art_path).convert("RGBA") # (its corners and shadow are see-through)
++ self.art = self._art_on(BG)
self.art_px = self.art.size
self._canvas_image = None
self._canvas_screen = None
@@@ -1540,6 -1679,59 +1604,62 @@@
if start_live:
self.root.after(260, self._start_builder)
++ def _art_on(self, bg):
++ return Image.alpha_composite(Image.new("RGBA", self._art_rgba.size, bg), self._art_rgba).convert("RGB")
++
+ def _restore_window_placement(self):
+ placement = _safe_window_geometry(_read_settings().get("window"), self.root)
+ self._window_last_normal = None
+ self._window_restoring = bool(placement)
+ if placement is None:
+ return
+ width, height, x, y, maximized = placement
+ self._window_last_normal = (width, height, x, y)
+ self.root.geometry(f"{width}x{height}+{x}+{y}")
+ if maximized:
+ self.root.after(110, self._restore_window_maximized)
+ self.root.after(200, self._finish_window_restoring)
+
+ def _restore_window_maximized(self):
+ try:
+ self.root.state("zoomed")
+ except tk.TclError:
+ try:
+ self.root.attributes("-zoomed", True)
+ except tk.TclError:
+ pass
+
+ def _finish_window_restoring(self):
+ self._window_restoring = False
+
+ def _remember_window_geometry(self, event=None):
+ if event is not None and event.widget is not self.root:
+ return
+ if getattr(self, "_window_restoring", False) or self.fullscreen:
+ return
+ try:
+ if self.root.state() == "normal":
+ width, height = self.root.winfo_width(), self.root.winfo_height()
+ if width >= 400 and height >= 250:
+ self._window_last_normal = (width, height,
+ self.root.winfo_x(), self.root.winfo_y())
+ except tk.TclError:
+ pass
+
+ def _save_window_placement(self):
+ try:
+ state = self.root.state()
+ if state == "normal" and not self.fullscreen:
+ self._remember_window_geometry()
+ if self._window_last_normal is None:
+ return
+ width, height, x, y = self._window_last_normal
+ _save_setting("window", {"width": width, "height": height,
+ "x": x, "y": y,
+ "maximized": state == "zoomed" and not self.fullscreen})
+ except (OSError, ValueError, tk.TclError) as exc:
+ print(f"[NumPlay] Could not save window placement: {exc}", file=sys.stderr)
+
def _build_ui(self):
self.root.title("NumPlay emulator")
self.root.geometry("1050x800")
@@@ -1676,6 -1875,99 +1800,100 @@@
self.root.focus_force()
self.root.after(150, self.refocus_input)
+ def _toggle_dark_mode(self):
+ requested = "dark" if self.dark_mode_var.get() else "light"
+ self._apply_interface_theme(requested)
+ try:
+ _save_setting("theme", requested)
+ except OSError as exc:
+ messagebox.showwarning("NumPlay theme",
+ f"Theme changed, but could not save it for next time:\n{exc}",
+ parent=self.root)
+ self.set_status("Dark mode" if requested == "dark" else "Light mode")
+ self.root.after(75, self.refocus_input)
+
+ def _apply_interface_theme(self, requested=None, *, initial=False):
+ """Repaint Tk widgets, including log windows, without restarting Unicorn.
+
+ Colours are replaced by their palette values rather than rebuilding
+ the window: doing so would interrupt the active calculator/game and
+ live builder. FlatButton stores its own background for mouse hovering.
+ """
+ previous = THEME_PALETTES[CURRENT_THEME]
+ if requested is not None:
+ _activate_theme_palette(requested)
+ updated = THEME_PALETTES[CURRENT_THEME]
+ mapping = {old.lower(): updated[key]
+ for key, old in previous.items()}
+ tk_options = (
+ "background", "foreground", "activebackground", "activeforeground",
+ "selectcolor", "disabledforeground", "highlightbackground",
+ "highlightcolor", "insertbackground", "troughcolor",
+ )
+ visited = set()
+
+ def paint(widget):
+ # Tk menus and Toplevels can appear elsewhere in the widget tree.
+ if str(widget) in visited:
+ return
+ visited.add(str(widget))
+ try:
+ options = set(widget.keys())
+ changes = {}
+ for option in tk_options:
+ if option not in options:
+ continue
+ value = str(widget.cget(option)).lower()
+ if value in mapping and mapping[value] != value:
+ changes[option] = mapping[value]
+ if changes:
+ widget.configure(**changes)
+ if isinstance(widget, FlatButton):
+ # FlatButton remembers the hover/leave base colour.
+ primary = widget._bg.lower() == previous["ACCENT"].lower()
+ widget._bg = ACCENT if primary else PANEL_2
+ widget.configure(bg=widget._bg,
+ fg="#34343a" if primary else FG)
+ for child in widget.winfo_children():
+ paint(child)
+ except tk.TclError:
+ pass
+
+ paint(self.root)
+ self.root.configure(bg=BG)
+ for menu in (self._options_menu, self._clock_submenu, self._manual_clock_menu):
+ try:
+ menu.configure(bg=PANEL, fg=FG,
+ activebackground=SELECT, activeforeground=FG,
+ selectcolor=ACCENT)
+ except (tk.TclError, AttributeError):
+ pass # Native system menus may ignore these colours on macOS.
+
+ # ttk progress bars use the system theme unless styled explicitly.
+ try:
+ style = ttk.Style(self.root)
+ style.configure("NumPlay.Horizontal.TProgressbar",
+ background=ACCENT, troughcolor=PANEL_2, borderwidth=0)
+ for bar in (self.progress, self.upload_progress):
+ bar.configure(style="NumPlay.Horizontal.TProgressbar")
+ except (tk.TclError, AttributeError):
+ pass
+
+ # Refresh the selected view and mode labels without switching modes.
+ # Re-running the existing variable trace repaints them without calling
+ # the mode-switch commands or restarting the compiler/emulator.
+ for var in (self.view_var, self.mode_var):
+ var.set(var.get())
- # Redraw the native-screen border and preserve the original artwork.
++ # The calculator's picture on the new background (its edges are see-through), the screen's border too.
++ self.art = self._art_on(BG)
+ self._art_geometry = (0, 0, 0, 0)
+ try:
+ self._resize()
+ self.canvas.itemconfigure("native-border", outline=LINE)
+ self._draw_highlight()
+ except (tk.TclError, AttributeError):
+ pass
+
def _section(self, parent, title):
label = tk.Label(parent, text=title, bg=PANEL, fg=MUTED, font=font(9), anchor="w")
label.pack(fill="x", pady=(16, 6))