Bring back the switch for Discord Rich Presence, in the game's Game tab and in the launcher's Settings.

The presence is off by default and its only switch was a row of the settings menu's Menu tab, which the Ocarina menu
left out, so it could be turned on only by editing nx2navi.ini. The row is in the Game tab now, and the launcher's
Settings has a Discord Status row that writes discord_rpc to the game's nx2navi.ini (launcher/gameini.py, which
reads the file as runtime/cfg.c does and changes only the line it sets). The connection itself works: the installed
game's --probe-discord connects and sets the status.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
chrg6
2026-11-09 08:51:07 -05:00
parent f58ad1d23e
commit 7fc21407c3
6 changed files with 126 additions and 6 deletions

79
launcher/gameini.py Normal file
View File

@@ -0,0 +1,79 @@
"""The game's own settings, nx2navi.ini in the game folder, for the few the launcher's Settings switch.
Read the way runtime/cfg.c reads the file: a UTF-8 byte order mark is skipped, lines starting with #, ; or [ are
not settings, a key is matched without regard to case and with or without its NX2NAVI_ prefix, a value in double
quotes loses them, an empty value leaves the setting at its default, and the last line for a key wins. Sections do
not matter to the game; a key the file does not have yet goes under its section, as the game writes it.
A change rewrites only the line it touches, through a temporary file, so the rest of the file stays as it was.
"""
import os
from pathlib import Path
PREFIX = 'NX2NAVI_'
def _path(game_dir):
return Path(game_dir) / 'nx2navi.ini'
def _key(text):
k = text.strip().upper()
return k[len(PREFIX):] if k.startswith(PREFIX) else k
def _lines(game_dir):
try: # newline='': the file's own line ends, which a change keeps
with open(_path(game_dir), encoding='utf-8-sig', errors='replace', newline='') as f:
text = f.read()
except OSError:
return []
return text.splitlines(keepends=True)
def _setting(line):
"""(key, value) of a settings line, or None."""
s = line.strip()
if not s or s[0] in '#;[' or '=' not in s:
return None
k, v = s.split('=', 1)
v = v.strip()
if len(v) >= 2 and v[0] == v[-1] == '"':
v = v[1:-1]
return _key(k), v
def get(game_dir, key):
"""The value the file gives key ('' when it gives none: the game's default applies)."""
want, value = _key(key), ''
for line in _lines(game_dir):
kv = _setting(line)
if kv and kv[0] == want:
value = kv[1]
return value
def put(game_dir, section, key, value):
"""Write key = value: on the key's last line when the file has one, else under [section] (made at the end when
the file has none). The game folder must exist; the file is made when it does not."""
lines, want = _lines(game_dir), _key(key)
entry = f'{key.lower()} = {value}'
nl = '\r\n' if lines and lines[0].endswith('\r\n') else '\n'
at = max((i for i, line in enumerate(lines) if (_setting(line) or ('',))[0] == want), default=-1)
if at >= 0:
end = lines[at][len(lines[at].rstrip('\r\n')):] or nl
lines[at] = entry + end
else:
head = next((i for i, line in enumerate(lines) if line.strip().lower() == f'[{section.lower()}]'), -1)
if head >= 0:
if not lines[head].endswith(('\n', '\r')): # the header is the file's last line
lines[head] += nl
lines.insert(head + 1, entry + nl)
else:
if lines and not lines[-1].endswith(('\n', '\r')):
lines[-1] += nl
lines += [nl] if lines else []
lines += [f'[{section}]{nl}', entry + nl]
path = _path(game_dir)
tmp = path.with_name(path.name + '.tmp')
tmp.write_text(''.join(lines), encoding='utf-8', newline='')
os.replace(tmp, path)

View File

@@ -26,7 +26,7 @@ import tkinter.font as tkfont
from pathlib import Path
from tkinter import filedialog
from .. import NAME, build, feed, gamefiles, jobs, saves, versions, winsys
from .. import NAME, build, feed, gameini, gamefiles, jobs, saves, versions, winsys
from ..context import Context
from . import art
@@ -588,6 +588,18 @@ class App:
desc=('Stable gets each finished release. Preview also gets test builds before they are '
'released, which may have new problems.',))
def discord_row(self, game_dir):
"""The game's discord_rpc setting (runtime/discord_rpc.c), kept in the game's nx2navi.ini as the game's own
menu keeps it; the game reads it when it starts."""
def on(v):
try:
gameini.put(game_dir, 'discord', 'discord_rpc', '1' if v else '0')
except OSError as e:
self.message = f'The game\'s settings could not be written: {e}'
return Row('toggle', 'Discord Status', on=on, get=lambda: gameini.get(game_dir, 'discord_rpc') == '1',
desc=('Show "Playing NX2navi" with your play time in your Discord status while the game runs. '
'The game\'s menu switches it too (Game tab).',))
def choose_dump(self):
start = str(Path(self.settings.get('dump')).parent) if self.settings.get('dump') else str(Path.home())
path = filedialog.askopenfilename(parent=self.root, title='Choose your Ocarina of Time dump',
@@ -833,6 +845,7 @@ class App:
'Keep the translated code and compiled files (about 5 GB) in the game folder, so an update '
'compiles only what changed. Off: they are deleted after each build.'),
self.channel_row(),
*([self.discord_row(gd)] if gd and Path(gd).is_dir() else []),
Row('divider'),
Row('value', 'Game Folder', gd or 'Not chosen', on=lambda: gd and self.open(gd),
desc=('Open the game folder: saves in profile, the game\'s settings in nx2navi.ini, its logs in '

View File

@@ -334,8 +334,8 @@
[discord]
# Rich Presence: "Playing NX2navi" with the play time in your Discord status while the game runs, through the
# local IPC of a running Discord client. 1 = on; the Menu tab of the settings menu (F1) switches it too, and the
# change reaches the presence thread at once.
# local IPC of a running Discord client. 1 = on; the Game tab of the settings menu (F1) and the launcher's Settings
# switch it too, and a change in the menu reaches the presence thread at once.
# discord_rpc = 0
# The Discord application whose name ("Playing <name>") and artwork the status shows: its Application ID from
# discord.com/developers/applications (General Information), digits only. Default: the NX2navi application, built

View File

@@ -182,8 +182,8 @@ static const CfgMeta metas[] = {
{"WALK_KEY", "none", NULL, LIVE}, {"WALK_SCALE", "0.51", "0.2..0.9", LIVE},
{"MENU_LANG", "", "en|ru|pt-BR|zh-Hans", LIVE},
{"AMIIBO_DIR", "", NULL, LIVE},
// Discord Rich Presence (discord_rpc.c): off by default, the Menu tab of the settings menu switches it. The
// application's id and art key default to discord_app.h's NX2NAVI_DISCORD_*_DEFAULT.
// Discord Rich Presence (discord_rpc.c): off by default, the Game tab of the settings menu and the launcher's
// Settings switch it. The application's id and art key default to discord_app.h's NX2NAVI_DISCORD_*_DEFAULT.
{"DISCORD_RPC", "0", "0|1", LIVE},
{"DISCORD_APP_ID", NX2NAVI_DISCORD_APP_ID_DEFAULT, NULL, LIVE},
{"DISCORD_IMAGE", NX2NAVI_DISCORD_IMAGE_DEFAULT, NULL, LIVE},

View File

@@ -946,6 +946,8 @@ static void tab_game(float scale) {
static const UiTextId mode[] = {UI_MENU_MODE_DOCKED, UI_MENU_MODE_HANDHELD};
opt_choice("NX2NAVI_OPERATION_MODE", UI_MENU_OPERATION_MODE, mode, 2, UI_MENU_OPERATION_MODE_DESC);
opt_toggle("NX2NAVI_ASSUME_FOCUS", UI_MENU_ASSUME_FOCUS, UI_MENU_ASSUME_FOCUS_DESC);
// discord_rpc.c reads the setting on its own thread and connects or clears the status within half a second
opt_toggle("NX2NAVI_DISCORD_RPC", UI_MENU_DISCORD_RPC, UI_MENU_DISCORD_RPC_DESC);
opt_end();
}

View File

@@ -40,7 +40,7 @@ ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
sys.path.insert(0, str(ROOT / 'tools'))
from launcher import build, feed, gamefiles, jobs, net, saves, settings, toolchain, updater, versions, winsys # noqa: E402
from launcher import build, feed, gameini, gamefiles, jobs, net, saves, settings, toolchain, updater, versions, winsys # noqa: E402
from launcher.context import Context # noqa: E402
from launcher.paths import Layout # noqa: E402
@@ -253,6 +253,32 @@ class VersionTest(unittest.TestCase):
versions.parse('banana')
class GameIniTest(Tmp):
"""The game settings the launcher switches (launcher/gameini.py), read as runtime/cfg.c reads nx2navi.ini."""
def test_new_file_gets_the_section(self):
gameini.put(self.tmp, 'discord', 'discord_rpc', '1')
self.assertEqual((self.tmp / 'nx2navi.ini').read_text(encoding='utf-8'), '[discord]\ndiscord_rpc = 1\n')
self.assertEqual(gameini.get(self.tmp, 'discord_rpc'), '1')
def test_only_the_key_line_changes(self):
ini = self.tmp / 'nx2navi.ini'
ini.write_bytes('[display]\r\nfullscreen = 1\r\n# discord_rpc = 1\r\n[discord]\r\n'
'NX2NAVI_DISCORD_RPC = "1"\r\ndiscord_app_id = 42'.encode('utf-8'))
self.assertEqual(gameini.get(self.tmp, 'DISCORD_RPC'), '1') # quotes, prefix and case as the game reads them
gameini.put(self.tmp, 'discord', 'discord_rpc', '0')
self.assertEqual(ini.read_bytes().decode('utf-8'), '[display]\r\nfullscreen = 1\r\n# discord_rpc = 1\r\n'
'[discord]\r\ndiscord_rpc = 0\r\ndiscord_app_id = 42')
self.assertEqual(gameini.get(self.tmp, 'discord_rpc'), '0')
def test_missing_key_goes_under_its_section(self):
ini = self.tmp / 'nx2navi.ini'
ini.write_bytes(b'[discord]\ndiscord_app_id = 42\n[display]\nfullscreen = 1')
self.assertEqual(gameini.get(self.tmp, 'discord_rpc'), '')
gameini.put(self.tmp, 'discord', 'discord_rpc', '1')
self.assertEqual(ini.read_bytes(), b'[discord]\ndiscord_rpc = 1\ndiscord_app_id = 42\n[display]\nfullscreen = 1')
class SettingsTest(Tmp):
def test_roundtrip_and_reset(self):
s = settings.Settings(self.layout.settings)