#!/usr/bin/python3 import math import os from pathlib import Path import re import sys import tempfile DISPLAY = "External: gamescope|||Windowed" NATIVE_RESOLUTION = "EnableSteamNativeExternalResolution" SCREENSAVER_IN_GAME = ("Customization", "Screensaver", "WhileInGame") TOKEN = re.compile(r'\s+|//[^\n]*|"(?:\\.|[^"\\])*"|[{}]') class Block: def __init__(self, pairs, end, offsets=()): self.pairs = pairs self.end = end self.offsets = offsets def get(self, name): matches = [value for key, value in self.pairs if key.lower() == name.lower()] if len(matches) > 1: raise ValueError("duplicate UI setting") return matches[0] if matches else None def offset(self, name): return next(at for (key, _), at in zip(self.pairs, self.offsets) if key.lower() == name.lower()) def parse(text): tokens = [] position = 0 for match in TOKEN.finditer(text): if match.start() != position: raise ValueError("invalid config.vdf") position = match.end() token = match.group() if not token.isspace() and not token.startswith('//'): tokens.append((token, match.start())) if position != len(text): raise ValueError("invalid config.vdf") def block(index, nested=False): pairs, offsets = [], [] while index < len(tokens): token, offset = tokens[index] if token == '}': if not nested: raise ValueError("unexpected closing brace") return Block(pairs, offset, offsets), index + 1 if not token.startswith('"') or index + 1 == len(tokens): raise ValueError("missing config value") key = token[1:-1] value, at = tokens[index + 1] index += 2 if value == '{': value, index = block(index, True) elif value.startswith('"'): value = value[1:-1] else: raise ValueError("invalid config value") pairs.append((key, value)) offsets.append(at) if nested: raise ValueError("unclosed config block") return Block(pairs, len(text), offsets), index return block(0)[0] def initial_scale(width, height): if not 320 <= width <= 16384 or not 320 <= height <= 16384: raise ValueError("invalid session size") return 1.3281567096710205 * math.sqrt(width * height / (1280 * 720)) def seed_text(text, scale): root = parse(text).get('InstallConfigStore') if not isinstance(root, Block): raise ValueError("missing InstallConfigStore") ui = root.get('UI') display = ui.get('display') if isinstance(ui, Block) else None if ui is not None and not isinstance(ui, Block): raise ValueError("invalid UI settings") if display is not None and not isinstance(display, Block): raise ValueError("invalid display settings") if display is not None: if any(name.lower() != 'current' and isinstance(value, Block) and value.get('ScaleFactor') is not None for name, value in display.pairs): return text, False entry = f'"{DISPLAY}"\n{{\n"ScaleFactor" "{scale:.9f}"\n}}\n' if display is not None: at, indent = display.end, 3 elif ui is not None: entry = '"display"\n{\n' + entry + '}\n' at, indent = ui.end, 2 else: entry = '"UI"\n{\n"display"\n{\n' + entry + '}\n}\n' at, indent = root.end, 1 insertion = '\n' + '\n'.join('\t' * indent + line for line in entry.splitlines()) + '\n' return text[:at] + insertion + text[at:], True def seed_value(text, path, value): root = parse(text).get('InstallConfigStore') if not isinstance(root, Block): raise ValueError("missing InstallConfigStore") *sections, name = path block, depth = root, 1 while sections: child = block.get(sections[0]) if child is None: break if not isinstance(child, Block): raise ValueError(f"invalid {sections[0]} settings") block, depth = child, depth + 1 sections.pop(0) if not sections and block.get(name) is not None: return text, False lines = [(len(sections), f'"{name}"\t\t"{value}"')] for level, section in reversed(list(enumerate(sections))): lines = [(level, f'"{section}"'), (level, '{')] + lines + [(level, '}')] insertion = ''.join('\t' * (depth + level) + line + '\n' for level, line in lines) at = text.rfind('\n', 0, block.end) + 1 if text[at:block.end].strip(): at, insertion = block.end, '\n' + insertion return text[:at] + insertion + text[at:], True def seed_native_resolution(text): return seed_value(text, ('Gamescope', NATIVE_RESOLUTION), '1') def seed_no_screensaver_in_game(text): return seed_value(text, SCREENSAVER_IN_GAME, '0') def atomic_write(path, text): path.parent.mkdir(parents=True, exist_ok=True) fd, temporary = tempfile.mkstemp(prefix='.' + path.name, dir=path.parent) try: with os.fdopen(fd, 'w') as output: output.write(text) os.replace(temporary, path) finally: if os.path.exists(temporary): os.unlink(temporary) def initialize(steam_root, width, height): scale = initial_scale(width, height) return seed_once(steam_root, 'droiddeck-ui-scale-initialized', lambda text: seed_text(text, scale), f'== steam: initial handheld UI scale {scale:.3f}') def seed_once(steam_root, marker_name, seed, message): config = Path(steam_root) / 'config/config.vdf' marker = config.with_name(marker_name) if marker.exists(): return False text = config.read_text() if config.exists() else '"InstallConfigStore"\n{\n}\n' updated, changed = seed(text) if changed: atomic_write(config, updated) print(message) atomic_write(marker, '1\n') return changed def initialize_native_resolution(steam_root): return seed_once(steam_root, 'droiddeck-native-resolution-initialized', seed_native_resolution, '== steam: native resolution on the session display') def initialize_screensaver(steam_root): return seed_once(steam_root, 'droiddeck-screensaver-initialized', seed_no_screensaver_in_game, '== steam: no screensaver over a running game') if __name__ == '__main__': status = 0 try: initialize(sys.argv[1], int(sys.argv[2]), int(sys.argv[3])) except (OSError, ValueError, RecursionError) as error: print('== steam: left UI scale unchanged: ' + str(error), file=sys.stderr) status = 1 for what, step in (('native resolution', initialize_native_resolution), ('screensaver', initialize_screensaver)): try: step(sys.argv[1]) except (OSError, ValueError, RecursionError) as error: print(f'== steam: left {what} unchanged: {error}', file=sys.stderr) status = 1 sys.exit(status)