From 2d26071c74a24484e454c9b962229ff1064efcad Mon Sep 17 00:00:00 2001 From: Paradox Date: Tue, 3 Nov 2026 23:55:27 +0530 Subject: [PATCH 01/11] RAMMIT 1.1.2: installer window fixes, old-version put-off, themed tooltips Installer: - A resize that arrives while the title bar is held waits and is applied on let-go (size only, real DPI scale). Fixes the window staying at the Loading height (#8). - HeightMap.json Loading 327 -> 323, so the window no longer trims itself right after opening and the card's top and bottom gaps are even. - Ignore without "don't ask again" now puts the old test version off: LegacyInstallPath in the registry, an OLD VERSION button and a line on both menus. With RAMMIT already installed, the two "move" choices copy the accounts into it without reinstalling (Legacy.RunMove). - The tick box's check mark is hidden while unticked (#2). App: - Main window and config wizard: same hold-then-apply resize (WindowSize.py). - Main window opens at its HeightMap.json height for the saved option. - Themed tooltips (JS/Tooltip.js) replace the native title tooltips; every control has one. Square by default, rounded in CBlock (--TooltipRadius). - Theme swatch drawn with straight-edged layers instead of conic-gradient. - Version 1.1.2, changelog, docs. --- Production/Installer/Installer/HeightMap.json | 2 +- .../Installer/Installer/InstallerApi.py | 84 ++++++++++++++++++- Production/Installer/Installer/Legacy.py | 52 +++++++++--- Production/Installer/Installer/Setup.py | 1 + .../Installer/Installer/Ui/CSS/Installer.css | 8 ++ .../Installer/Ui/HTML/Installer.html | 8 +- .../Installer/Installer/Ui/JS/Installer.js | 74 +++++++++++++--- .../Installer/Installer/Ui/JS/Screens.js | 2 + Production/Installer/Tests/SmokeExe.py | 2 +- Production/Installer/Tests/TestInstaller.py | 74 +++++++++++++++- Production/Installer/Tests/TestUi.mjs | 2 +- Production/RAMMIT-Stable/App/Api.py | 16 ++-- Production/RAMMIT-Stable/App/Main.py | 15 +++- Production/RAMMIT-Stable/App/Version.py | 2 +- Production/RAMMIT-Stable/App/WindowSize.py | 69 +++++++++++++++ Production/RAMMIT-Stable/CHANGELOG.md | 14 +++- .../RAMMIT-Stable/Docs/HowToMakeATheme.txt | 4 +- Production/RAMMIT-Stable/Docs/README.txt | 4 +- .../RAMMIT-Stable/Src/CBlock/CSS/Style.css | 40 ++++++++- .../RAMMIT-Stable/Src/CBlock/HTML/Index.html | 20 ++--- .../RAMMIT-Stable/Src/CBlock/HTML/Wizard.html | 8 +- .../RAMMIT-Stable/Src/CBlock/JS/Main.js | 2 + .../RAMMIT-Stable/Src/CBlock/JS/Tooltip.js | 66 +++++++++++++++ .../RAMMIT-Stable/Src/CBlock/JS/Wizard.js | 2 + .../RAMMIT-Stable/Src/CBlock/Theme.json | 2 +- .../RAMMIT-Stable/Src/Dark/CSS/Style.css | 35 +++++++- .../RAMMIT-Stable/Src/Dark/HTML/Index.html | 20 ++--- .../RAMMIT-Stable/Src/Dark/HTML/Wizard.html | 8 +- Production/RAMMIT-Stable/Src/Dark/JS/Main.js | 2 + .../RAMMIT-Stable/Src/Dark/JS/Tooltip.js | 66 +++++++++++++++ .../RAMMIT-Stable/Src/Dark/JS/Wizard.js | 2 + .../RAMMIT-Stable/Src/Light/CSS/Style.css | 35 +++++++- .../RAMMIT-Stable/Src/Light/HTML/Index.html | 20 ++--- .../RAMMIT-Stable/Src/Light/HTML/Wizard.html | 8 +- Production/RAMMIT-Stable/Src/Light/JS/Main.js | 2 + .../RAMMIT-Stable/Src/Light/JS/Tooltip.js | 66 +++++++++++++++ .../RAMMIT-Stable/Src/Light/JS/Wizard.js | 2 + .../Src/MyCustomTheme/CSS/Style.css | 35 +++++++- .../Src/MyCustomTheme/HTML/Index.html | 20 ++--- .../Src/MyCustomTheme/HTML/Wizard.html | 8 +- .../Src/MyCustomTheme/JS/Main.js | 2 + .../Src/MyCustomTheme/JS/Tooltip.js | 66 +++++++++++++++ .../Src/MyCustomTheme/JS/Wizard.js | 2 + Production/RAMMIT-Stable/Tests/TestBackend.py | 24 ++++++ Production/RAMMIT-Stable/requirements.txt | 2 +- 45 files changed, 892 insertions(+), 106 deletions(-) create mode 100644 Production/RAMMIT-Stable/App/WindowSize.py create mode 100644 Production/RAMMIT-Stable/Src/CBlock/JS/Tooltip.js create mode 100644 Production/RAMMIT-Stable/Src/Dark/JS/Tooltip.js create mode 100644 Production/RAMMIT-Stable/Src/Light/JS/Tooltip.js create mode 100644 Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Tooltip.js diff --git a/Production/Installer/Installer/HeightMap.json b/Production/Installer/Installer/HeightMap.json index c475c67..12272ea 100644 --- a/Production/Installer/Installer/HeightMap.json +++ b/Production/Installer/Installer/HeightMap.json @@ -1,4 +1,4 @@ { - "Loading": 327, + "Loading": 323, "ConfirmUninstall": 393 } diff --git a/Production/Installer/Installer/InstallerApi.py b/Production/Installer/Installer/InstallerApi.py index fe9b324..ded2555 100644 --- a/Production/Installer/Installer/InstallerApi.py +++ b/Production/Installer/Installer/InstallerApi.py @@ -11,6 +11,8 @@ window.InstallerEvents.(payload): Progress / UninstallProgress (Test1's progress fields), Done (the result) and Failed ({Message, Details, Running}). """ +import ctypes +import ctypes.wintypes import json import os import threading @@ -25,6 +27,7 @@ from Log import Logger WindowWidth = 560 +SwpNoMove, SwpNoZOrder, SwpNoActivate = 0x2, 0x4, 0x10 Events = ("Progress", "UninstallProgress", "Done", "Failed") LegacyModes = ("", "MoveRemove", "MoveKeep") ConfigChoices = ("", "KeepNew", "UseOld") @@ -47,12 +50,56 @@ def __init__(self, StartScreen=""): self._LastHeight = 0 # Installer.py sets the start height self._Frame = None self._Resized = False + self._Dragging = False self._LastPath = "" # ------------------------------------------------------------ wiring (Installer.py) def _AttachWindow(self, Window): self._Window = Window + if hasattr(Window, "events"): # the tests' stand-in window has none + Window.events.shown += self._WatchDrags + + def _WatchDrags(self): + """Grabbing or dragging the title bar starts Windows' move loop, which keeps the size the window had when it + began: a resize sent meanwhile is undone (it only flickers). So while the window is held, ResizeInstaller just + records the height, and when the loop ends (ResizeEnd fires for moves too) it is applied once.""" + try: + Native = self._Window.native + Native.ResizeBegin += lambda _Sender, _Args: setattr(self, "_Dragging", True) + Native.ResizeEnd += self._OnLetGo + except Exception as Error: + Logger.warning("Can't watch window drags: %s", type(Error).__name__) + + def _OnLetGo(self, _Sender, _Args): + self._Dragging = False + threading.Thread(target=self._ReapplyHeight, daemon=True).start() + + def _ReapplyHeight(self): + Window, Target = self._Window, self._LastHeight + if not Window or not Target: + return + try: + Native = Window.native + Scale = self._WindowScale(Native) + if abs(Native.Height / Scale - Target) >= 2: + self._SetHeight(Native, round(Target * Scale)) + except Exception: + pass + + @staticmethod + def _WindowScale(Native): + """The window's real DPI scale. Not Form.DeviceDpi: pywebview's SetProcessDPIAware leaves that at 96.""" + return max(1.0, ctypes.windll.user32.GetDpiForWindow(ctypes.wintypes.HWND(Native.Handle.ToInt64())) / 96.0) + + @staticmethod + def _SetHeight(Native, PhysicalHeight): + """Size only (SWP_NOMOVE): pywebview's resize also writes a position read a moment ago, which drags the + window back if it is still moving.""" + Hwnd = ctypes.wintypes.HWND(Native.Handle.ToInt64()) + Rect = ctypes.wintypes.RECT() + ctypes.windll.user32.GetWindowRect(Hwnd, ctypes.byref(Rect)) + ctypes.windll.user32.SetWindowPos(Hwnd, None, 0, 0, Rect.right - Rect.left, PhysicalHeight, SwpNoMove | SwpNoZOrder | SwpNoActivate) def _Emit(self, Event, Payload): """window.InstallerEvents.(Payload). Payload is JSON-encoded, never spliced raw.""" @@ -123,7 +170,7 @@ def BootFinished(self): def GetState(self): State = Setup.InstalledState() - LegacyInfo = None if State["Installed"] else Legacy.Detect() + LegacyInfo = Legacy.Detect() # also when installed: an old version put off with Ignore stays on the menu Kept = None if State["Installed"] or LegacyInfo else Setup.FindKeptConfig() DefaultPath = State["Path"] or (Kept["Path"] if Kept and Kept["Installable"] else Locations.Current.DefaultInstallPath) return { @@ -132,7 +179,8 @@ def GetState(self): "Branch": State["Branch"], "Path": State["Path"], "DefaultPath": DefaultPath, - "Legacy": {"Path": LegacyInfo["Path"], "Version": LegacyInfo["Version"]} if LegacyInfo else None, + "Legacy": {"Path": LegacyInfo["Path"], "Version": LegacyInfo["Version"], "Deferred": LegacyInfo["Deferred"]} + if LegacyInfo else None, "KeptConfig": {"Path": Kept["Path"], "Accounts": Kept["Accounts"], "Test1": Kept["Test1"]} if Kept else None, "UndoVersion": Setup.UndoVersion(State["Version"]) if State["Installed"] else "", "StartScreen": "ConfirmUninstall" if self._StartScreen == "ConfirmUninstall" and State["Installed"] else "", @@ -304,11 +352,39 @@ def Job(): return Legacy.RunRemove(LegacyInfo["Path"], self._UninstallProgress) return self._StartJob("LegacyRemove", Job) + def _LegacyAndInstalled(self): + State = Setup.InstalledState() + LegacyInfo = Legacy.Detect() + if not State["Installed"] or not LegacyInfo: + raise Setup.SetupError("The old version can't be found any more." if State["Installed"] else "RAMMIT isn't installed.") + return LegacyInfo["Path"], State["Path"] + + def CheckLegacyMove(self): + """Choices 1/2 with RAMMIT already installed (no reinstall): asks which accounts to keep when both have some.""" + try: + Folder, InstallPath = self._LegacyAndInstalled() + except Setup.SetupError as Error: + return {"Error": str(Error)} + if Setup.FindRunning([Folder, InstallPath]): + return {"Error": "RAMMIT is running.", "Running": True} + return {"Ok": True, "NeedsConfigChoice": Legacy.AccountsPresent(os.path.join(InstallPath, "Config")) + and Legacy.AccountsPresent(Legacy.ConfigDir(Folder))} + + def StartLegacyMove(self, Mode, ConfigChoice=""): + if Mode not in ("MoveRemove", "MoveKeep") or ConfigChoice not in ConfigChoices: + return {"Error": "Bad request."} + + def Job(): + Folder, InstallPath = self._LegacyAndInstalled() + return Legacy.RunMove(Folder, InstallPath, Mode, ConfigChoice or "KeepNew", self._UninstallProgress) + return self._StartJob("LegacyMove", Job) + def IgnoreLegacy(self, DontAskAgain): if not isinstance(DontAskAgain, bool): return {"Error": "Bad request."} try: - Legacy.Ignore(DontAskAgain) + LegacyInfo = Legacy.Detect() # the folder comes from the registry, never from the page + Legacy.Ignore(DontAskAgain, LegacyInfo["Path"] if LegacyInfo else "") except OSError: return {"Error": "Couldn't save that choice."} return {"Ok": True} @@ -345,6 +421,8 @@ def ResizeInstaller(self, Height, ViewportHeight=None): if abs(Target - self._LastHeight) < 2: return self._LastHeight = Target + if self._Dragging: + return # held: Windows would undo it (flicker); _OnLetGo applies it try: Window.resize(WindowWidth, Target) except Exception: diff --git a/Production/Installer/Installer/Legacy.py b/Production/Installer/Installer/Legacy.py index 23254b1..77bede2 100644 --- a/Production/Installer/Installer/Legacy.py +++ b/Production/Installer/Installer/Legacy.py @@ -10,7 +10,8 @@ 1. MoveRemove copy Config\\ files into the new install, then Remove(IncludeConfig=True) 2. MoveKeep copy Config\\ files into the new install, leave the old one alone 3. Remove Remove(IncludeConfig=True) without copying (the UI asks to confirm first) - 4. Ignore nothing; with "don't ask again" the registry gets IgnoreLegacyInstall=1 + 4. Ignore with "don't ask again" the registry gets IgnoreLegacyInstall=1; without it, LegacyInstallPath=, + and later runs open the menu with an OLD VERSION button instead of this screen Only names Test1 is known to ship are ever deleted. Account files are copied as files and never read (they hold login cookies); "has accounts" is judged by file size alone. @@ -51,13 +52,16 @@ def ReadVersion(Folder): def Detect(): - """{Path, Version, Shortcuts} for a Test1 install the registry points at, unless the user said ignore it.""" - Folder = Setup.RegRead("InstallPath") - if not Folder or not os.path.isdir(Folder) or Setup.RegRead("IgnoreLegacyInstall") == "1": + """{Path, Version, Shortcuts, Deferred} for a Test1 install the registry points at (InstallPath, or LegacyInstallPath + once the user pressed Ignore), unless the user said never ask again. Deferred = it was put off with Ignore.""" + if Setup.RegRead("IgnoreLegacyInstall") == "1": return None - if not IsLegacyFolder(Folder): - return None - return {"Path": Folder, "Version": ReadVersion(Folder), "Shortcuts": FindShortcuts()} + PutOff = Setup.RegRead("LegacyInstallPath") + for Folder in (Setup.RegRead("InstallPath"), PutOff): + if Folder and os.path.isdir(Folder) and IsLegacyFolder(Folder): + return {"Path": Folder, "Version": ReadVersion(Folder), "Shortcuts": FindShortcuts(), + "Deferred": bool(PutOff) and Paths.SamePath(Folder, PutOff)} + return None def UnknownEntries(Folder): @@ -157,8 +161,9 @@ def RemoveShortcuts(): def ClearRegistry(Folder): - """Test1's values: Version, ConfigPath, CleanupPath, and InstallPath while it still points at the old folder.""" - for Name in ("Version", "ConfigPath", "CleanupPath"): + """Test1's values: Version, ConfigPath, CleanupPath, and InstallPath while it still points at the old folder; + plus LegacyInstallPath (the old version is dealt with).""" + for Name in ("Version", "ConfigPath", "CleanupPath", "LegacyInstallPath"): Setup.RegDeleteValue(Name) Current = Setup.RegRead("InstallPath") if Current and Folder and Paths.SamePath(Current, Folder): @@ -166,9 +171,14 @@ def ClearRegistry(Folder): Setup.TidyRegistry() -def Ignore(DontAskAgain): +def Ignore(DontAskAgain, Folder=""): + """Ticked: never ask again. Unticked: remember the folder, so it stays reachable from the menu (even after a new + install takes over InstallPath) without blocking the way in.""" if DontAskAgain: Setup.RegWrite("IgnoreLegacyInstall", "1") + Setup.RegDeleteValue("LegacyInstallPath") + elif Folder: + Setup.RegWrite("LegacyInstallPath", Folder) def RunRemove(Folder, Report): @@ -184,3 +194,25 @@ def RunRemove(Folder, Report): Report(Pct=100) Logger.info("Old version removed from %s (left: %d)", Folder, len(Result["Left"])) return {"Path": Folder, "Left": Result["Left"]} + + +def RunMove(Folder, InstallPath, Mode, Choice, Report): + """Choices 1 and 2 when RAMMIT is already installed: nothing is reinstalled, only the old version's accounts and + settings come across (MoveConfig, same rules as an install). MoveRemove then removes the old version like choice 3. + The registry's InstallPath and Version belong to the installed RAMMIT, so only Test1's own values go.""" + if Setup.FindRunning([Folder, InstallPath]): + raise Setup.SetupError("RAMMIT is running. Close it first.", Running=True) + Report(Label="Moving accounts and settings", Pct=10, ActiveStage=0) + Warnings = MoveConfig(Folder, InstallPath, Choice) + Left = [] + if Mode == "MoveRemove": + Report(Label="Removing the old version", Pct=50) + Left = Remove(Folder, IncludeConfig=True)["Left"] + RemoveShortcuts() + Report(Pct=100, ActiveStage=1) + Report(Label="Cleaning up") + for Name in ("ConfigPath", "CleanupPath", "LegacyInstallPath"): + Setup.RegDeleteValue(Name) + Report(Pct=100) + Logger.info("Old version's config moved into %s (%s)", InstallPath, Mode) + return {"Path": Folder, "InstallPath": InstallPath, "Mode": Mode, "Left": Left, "Warnings": Warnings} diff --git a/Production/Installer/Installer/Setup.py b/Production/Installer/Installer/Setup.py index db94be1..5e61288 100644 --- a/Production/Installer/Installer/Setup.py +++ b/Production/Installer/Installer/Setup.py @@ -859,6 +859,7 @@ def OnBytes(Done, Total): if LegacyMode in ("MoveRemove", "MoveKeep") and LegacyMoved: Report(StageDetail="Moving accounts and settings") Warnings += Legacy.MoveConfig(LegacyMoved, InstallPath, ConfigChoice) + RegDeleteValue("LegacyInstallPath") # dealt with: no OLD VERSION button any more if LegacyMode == "MoveRemove" and LegacyMoved: Report(StageDetail="Removing the old version") Result = Legacy.Remove(LegacyMoved, IncludeConfig=True) diff --git a/Production/Installer/Installer/Ui/CSS/Installer.css b/Production/Installer/Installer/Ui/CSS/Installer.css index 1f1dcf5..be1216c 100644 --- a/Production/Installer/Installer/Ui/CSS/Installer.css +++ b/Production/Installer/Installer/Ui/CSS/Installer.css @@ -42,6 +42,7 @@ --BorderLight: #333333; --BtnEdit: #1a6b3a; --Green2: #1a6b3a; + --Legacy: #4b3f8f; /* OLD VERSION button: muted violet */ --BtnNeutral: #222222; --ScrollbarThumb: #444444; --ScrollbarThumbHover: #555555; @@ -254,6 +255,10 @@ body { background: var(--Accent); } +.BtnInst.Legacy { + background: var(--Legacy); +} + .BtnInst.Success { background: var(--Green2); } @@ -693,6 +698,8 @@ body { .InstCheckboxRow .CheckboxBox i { font-size: 11px; color: var(--Accent); + /* hidden, not display: none, so the box keeps its size while unticked (#2) */ + visibility: hidden; } .InstCheckboxRow input[type="checkbox"]:checked + .CheckboxBox { @@ -702,6 +709,7 @@ body { .InstCheckboxRow input[type="checkbox"]:checked + .CheckboxBox i { color: var(--BgCard); + visibility: visible; } /* ===== SCREEN SLIDE TRANSITIONS ===== */ diff --git a/Production/Installer/Installer/Ui/HTML/Installer.html b/Production/Installer/Installer/Ui/HTML/Installer.html index c6706ce..774a6fb 100644 --- a/Production/Installer/Installer/Ui/HTML/Installer.html +++ b/Production/Installer/Installer/Ui/HTML/Installer.html @@ -37,7 +37,7 @@
An older test version of RAMMIT (...) is installed in ....
- What should happen to it? The first choice is recommended. + What should happen to it? The first choice is recommended.
@@ -69,10 +69,12 @@
RAMMIT is not installed on this system.
+ Press Install to set it up, or Cancel to exit.
+
@@ -82,11 +84,13 @@
RAMMIT is already installed on this system.
Installed version: ... - Latest: ...
+ Choose an action below.
+
@@ -309,7 +313,7 @@
-
Old version removed.
+
Old version removed.
diff --git a/Production/Installer/Installer/Ui/JS/Installer.js b/Production/Installer/Installer/Ui/JS/Installer.js index 6348445..cafc15c 100644 --- a/Production/Installer/Installer/Ui/JS/Installer.js +++ b/Production/Installer/Installer/Ui/JS/Installer.js @@ -163,10 +163,38 @@ function ApplyState(S) { ById('LegacyVer').textContent = S.Legacy.Version ? 'v' + S.Legacy.Version : 'unknown version'; ById('LegacyPath').textContent = S.Legacy.Path; ById('LegacyConfirmPath').textContent = S.Legacy.Path; + document.querySelectorAll('.LegacyMenuVer').forEach(E => { E.textContent = ById('LegacyVer').textContent; }); + document.querySelectorAll('.LegacyMenuPath').forEach(E => { E.textContent = S.Legacy.Path; }); } + ShowLegacyButtons(); UpdateUndo(); } +// An old version put off with Ignore: reachable from either menu, on the same screen with the same four choices. +// With RAMMIT already installed, the two "move" choices don't reinstall it (MoveIntoInstalled). +function ShowLegacyButtons() { + const PutOff = !!(State.Legacy && State.Legacy.Deferred); + ById('FreshLegacyBtn').hidden = ById('InstalledLegacyBtn').hidden = !PutOff; + ById('FreshLegacyLine').hidden = ById('InstalledLegacyLine').hidden = !PutOff; +} + +// Choices 1/2 with RAMMIT already installed: only the old version's accounts and settings come across (and +// MoveRemove then removes it). Asks which accounts to keep when both have some, like an install does. +async function MoveIntoInstalled(ConfigChoice) { + const Back = () => Go('Legacy', 'LegacyMove'); + const Check = await Api.CheckLegacyMove().catch(Error => ({ Error: String(Error) })); + if (Check.Running) { ShowRunning('move your accounts', () => MoveIntoInstalled(ConfigChoice), Back); return; } + if (Check.Error) { ShowError(Check.Error, '', null, Back); return; } + if (Check.NeedsConfigChoice && !ConfigChoice) { + ById('UseOldBtn').textContent = "USE THE OLD VERSION'S ACCOUNTS"; + Go('ConfigConflict', 'LegacyMove'); + return; + } + ResetUninstallProgress('Moving your accounts...'); + Go('ProgressUninstall', 'LegacyMove'); + StartJob('LegacyMove', () => Api.StartLegacyMove(State.LegacyMode, ConfigChoice || ''), Back); +} + // Accounts an earlier uninstall kept (or Test1's uninstall): mentioned on the fresh menu, offered on Install. function ShowKept() { const Kept = State.Installed || State.LegacyMode ? null : State.KeptConfig; @@ -289,11 +317,25 @@ On('Done', async Result => { Lines.push([], ["If something broke, please open an issue - we'd love a second chance."]); SetLines(ById('UninstallDoneText'), Lines); Go('UninstallDone'); + } else if (Result.Action === 'LegacyMove') { + State.Legacy = null; + State.LegacyMode = ''; + ShowLegacyButtons(); + const Lines = [['Your accounts and settings from the old version are now in ', { Em: Result.InstallPath, Class: 'Path' }, '.']]; + if (Result.Mode === 'MoveRemove') Lines.push(['The old version was removed from ', { Em: Result.Path, Class: 'Path' }, '.']); + else Lines.push(['The old version was left as it is in ', { Em: Result.Path, Class: 'Path' }, '.']); + if (Result.Left && Result.Left.length) Lines.push(['Files it didn\'t install were left there: ', { Em: Result.Left.slice(0, 3).join(', ') }, '.']); + Lines.push(...Warn(Result), ['Press ', { Em: 'Continue' }, ' to go back to the menu.']); + ById('LegacyDoneTitle').textContent = 'Accounts moved.'; + SetLines(ById('LegacyDoneText'), Lines); + Go('LegacyDone'); } else if (Result.Action === 'LegacyRemove') { State.Legacy = null; + ShowLegacyButtons(); + ById('LegacyDoneTitle').textContent = 'Old version removed.'; const Lines = [['The old test version was removed from ', { Em: Result.Path, Class: 'Path' }, '.']]; if (Result.Left && Result.Left.length) Lines.push(['Files it didn\'t install were left there: ', { Em: Result.Left.slice(0, 3).join(', ') }, '.']); - Lines.push(['Press ', { Em: 'Continue' }, ' to install the new RAMMIT.']); + Lines.push(['Press ', { Em: 'Continue' }, State.Installed ? ' to go back to the menu.' : ' to install the new RAMMIT.']); SetLines(ById('LegacyDoneText'), Lines); Go('LegacyDone'); } else { @@ -344,6 +386,8 @@ const CloseWindow = () => Api.CloseWindow().catch(() => window.close()); Click('FreshInstallBtn', () => NeedVersions(() => Go('Version', 'Install'), () => Go('MenuFresh', 'Install'))); Click('FreshCancelBtn', CloseWindow); +Click('FreshLegacyBtn', () => Go('Legacy', 'LegacyInstall')); +Click('InstalledLegacyBtn', () => Go('Legacy', 'LegacyMove')); Click('InstalledCancelBtn', CloseWindow); Click('UpdateBtn', () => { ById('ChangeVersionError').textContent = State.VersionsLoaded ? '' : "Couldn't load the version list. You can still undo the last change."; @@ -374,9 +418,14 @@ Click('LaunchBtn', async () => { }); // Older RAMMIT found -Click('LegacyMoveRemoveBtn', () => { State.LegacyMode = 'MoveRemove'; NeedVersions(() => Go('Version', 'LegacyInstall'), () => Go('Legacy', 'LegacyInstall')); }); +Click('LegacyMoveRemoveBtn', () => { + State.LegacyMode = 'MoveRemove'; + if (State.Installed) { MoveIntoInstalled(); return; } + NeedVersions(() => Go('Version', 'LegacyInstall'), () => Go('Legacy', 'LegacyInstall')); +}); Click('LegacyMoveKeepBtn', () => { State.LegacyMode = 'MoveKeep'; + if (State.Installed) { MoveIntoInstalled(); return; } // The new one can't share the old one's folder when the old one stays. if (State.Legacy && ById('InstallPath').value.trim().toLowerCase() === State.Legacy.Path.toLowerCase()) ById('InstallPath').value = State.Legacy.Path + '-New'; NeedVersions(() => Go('Version', 'LegacyInstall'), () => Go('Legacy', 'LegacyInstall')); @@ -386,7 +435,10 @@ Click('LegacyIgnoreBtn', async () => { const Result = await Api.IgnoreLegacy(ById('LegacyDontAsk').checked); if (Result && Result.Error) { ShowError(Result.Error, '', null, () => Go('Legacy')); return; } State.LegacyMode = ''; - Go('MenuFresh', 'Install'); + // Ticked: gone for good. Unticked: put off - it stays on the menu as OLD VERSION. + State.Legacy = ById('LegacyDontAsk').checked ? null : Object.assign({}, State.Legacy, { Deferred: true }); + ShowLegacyButtons(); + Go(Nav.CurrentMenu, State.Installed ? 'Update' : 'Install'); }); Click('LegacyConfirmBackBtn', () => Go('Legacy', 'LegacyRemove')); Click('LegacyConfirmRemoveBtn', () => { @@ -397,12 +449,13 @@ Click('LegacyConfirmRemoveBtn', () => { StartJob('LegacyRemove', () => Api.StartLegacyRemove(), Back); }, Back); }); -Click('LegacyDoneContinueBtn', () => { State.LegacyMode = ''; Go('MenuFresh', 'Install'); }); +Click('LegacyDoneContinueBtn', () => { State.LegacyMode = ''; Go(Nav.CurrentMenu, State.Installed ? 'Update' : 'Install'); }); // Settings clash -Click('KeepNewBtn', () => StartInstall('KeepNew')); -Click('UseOldBtn', () => StartInstall('UseOld')); -Click('ConflictBackBtn', () => Go('Version', State.LegacyMode ? 'LegacyInstall' : 'Install')); +const MovingIntoInstalled = () => !!(State.Installed && State.LegacyMode); +Click('KeepNewBtn', () => (MovingIntoInstalled() ? MoveIntoInstalled('KeepNew') : StartInstall('KeepNew'))); +Click('UseOldBtn', () => (MovingIntoInstalled() ? MoveIntoInstalled('UseOld') : StartInstall('UseOld'))); +Click('ConflictBackBtn', () => (MovingIntoInstalled() ? Go('Legacy', 'LegacyMove') : Go('Version', State.LegacyMode ? 'LegacyInstall' : 'Install'))); // Running Click('RunningCloseBtn', async () => { @@ -471,13 +524,14 @@ async function Load() { ById('FooterVersion').textContent = State.Installed ? V(State.Version) : ''; ShowChangeButton(); if (State.Installed) { Go('MenuInstalled', 'Update'); return; } // Repair/Undo/Uninstall still work - if (State.Legacy) { Go('Legacy', 'LegacyInstall'); return; } + if (State.Legacy && !State.Legacy.Deferred) { Go('Legacy', 'LegacyInstall'); return; } + if (State.Legacy) { Go('MenuFresh', 'Install'); return; } // put off: the menu, with OLD VERSION ShowError(Result.Error, Result.Details, () => { Go('Loading'); Load().catch(ReportError); }, null, "Couldn't load the versions."); return; } if (State.Installed) Go('MenuInstalled', 'Update'); - else if (State.Legacy) Go('Legacy', 'LegacyInstall'); - else Go('MenuFresh', 'Install'); + else if (State.Legacy && !State.Legacy.Deferred) Go('Legacy', 'LegacyInstall'); + else Go('MenuFresh', 'Install'); // with OLD VERSION when the old one was put off } Boot().catch(Error => { ReportError(Error); ShowError(String(Error), '', null, null); }); diff --git a/Production/Installer/Installer/Ui/JS/Screens.js b/Production/Installer/Installer/Ui/JS/Screens.js index 8b56673..518f5bf 100644 --- a/Production/Installer/Installer/Ui/JS/Screens.js +++ b/Production/Installer/Installer/Ui/JS/Screens.js @@ -12,6 +12,7 @@ const Crumbs = { // new LegacyInstall: ['Old version', 'Version', 'Progress', 'Done'], LegacyRemove: ['Old version', 'Confirm', 'Progress', 'Done'], + LegacyMove: ['Old version', 'Progress', 'Done'], // choices 1/2 with RAMMIT already installed }; const CrumbScreens = { @@ -21,6 +22,7 @@ const CrumbScreens = { Uninstall: ['MenuInstalled', 'ConfirmUninstall', 'ProgressUninstall', 'UninstallDone'], LegacyInstall: ['Legacy', 'Version', 'Progress', 'InstallDone'], LegacyRemove: ['Legacy', 'LegacyConfirm', 'ProgressUninstall', 'LegacyDone'], + LegacyMove: ['Legacy', 'ProgressUninstall', 'LegacyDone'], }; const ResultScreens = ['ActionDone', 'InstallDone', 'UninstallDone', 'LegacyDone']; diff --git a/Production/Installer/Tests/SmokeExe.py b/Production/Installer/Tests/SmokeExe.py index f08e6fb..d0e21c7 100644 --- a/Production/Installer/Tests/SmokeExe.py +++ b/Production/Installer/Tests/SmokeExe.py @@ -37,7 +37,7 @@ def FindWindow(): Rect = win32gui.GetWindowRect(Hwnd) StartHeight = Rect[3] - Rect[1] # The release list was fetched, the menu shown, and the window resized so its client area is exactly the - # 371 logical px the menu page measures (start size from HeightMap.json is 327 incl. the frame). + # 371 logical px the menu page measures (start size from HeightMap.json is 323 incl. the frame). Scale = ctypes.windll.user32.GetDpiForWindow(Hwnd) / 96 Grown = Support.WaitUntil(lambda: any("/repos/" in P for P in Server.Requests) and abs(win32gui.GetClientRect(Hwnd)[3] / Scale - 371) <= 2, 60, 0.2) diff --git a/Production/Installer/Tests/TestInstaller.py b/Production/Installer/Tests/TestInstaller.py index 7be0f3a..8ad87c5 100644 --- a/Production/Installer/Tests/TestInstaller.py +++ b/Production/Installer/Tests/TestInstaller.py @@ -10,6 +10,7 @@ import shutil import subprocess import unittest +from unittest import mock import winreg import zipfile @@ -553,7 +554,7 @@ def test_detection(self): self.assertEqual(Setup.Classify(self.Old), "Legacy") State = InstallerApi.InstallerApi().GetState() self.assertFalse(State["Installed"]) - self.assertEqual(State["Legacy"], {"Path": self.Old, "Version": "1.0.0"}) + self.assertEqual(State["Legacy"], {"Path": self.Old, "Version": "1.0.0", "Deferred": False}) def test_choice1_move_and_remove_into_another_folder(self): Result = self.Install("1.1.0", LegacyMode="MoveRemove", LegacyPath=self.Old) @@ -612,8 +613,59 @@ def test_choice4_ignore(self): self.assertIsNone(Legacy.Detect()) with self.assertRaises(Setup.SetupError): # and its folder still can't be installed over Setup.CheckTarget(self.Old) + + def test_Choice4IgnoreWithoutDontAskPutsItOff(self): + InstallerApi.InstallerApi().IgnoreLegacy(False) + self.assertEqual(Setup.RegRead("LegacyInstallPath"), self.Old) + self.assertTrue(Legacy.Detect()["Deferred"]) # the menu opens, with OLD VERSION + self.Install("1.1.0") # a new install takes over InstallPath: the old one is still remembered + State = InstallerApi.InstallerApi().GetState() + self.assertTrue(State["Installed"]) + self.assertEqual(State["Legacy"], {"Path": self.Old, "Version": "1.0.0", "Deferred": True}) + Legacy.RunRemove(self.Old, lambda **_P: None) # dealt with: forgotten + self.assertIsNone(Setup.RegRead("LegacyInstallPath")) + self.assertIsNone(Legacy.Detect()) + + def test_Choice4DontAskAgainForgetsAPutOffOne(self): + Legacy.Ignore(False, self.Old) + Legacy.Ignore(True) + self.assertIsNone(Setup.RegRead("LegacyInstallPath")) + self.assertIsNone(Legacy.Detect()) + + def test_Choice2MoveAndKeepForgetsAPutOffOne(self): + Legacy.Ignore(False, self.Old) + self.Install("1.1.0", LegacyMode="MoveKeep", LegacyPath=self.Old) + self.assertIsNone(Setup.RegRead("LegacyInstallPath")) + self.assertIsNone(Legacy.Detect()) self.assertTrue(os.path.isfile(os.path.join(self.Old, "Src", "Version.json"))) + def test_MoveIntoInstalledRammitKeepsTheOldOneAndDoesNotReinstall(self): + self.Install("1.1.0") # RAMMIT installed, the old version put off with Ignore + Legacy.Ignore(False, self.Old) + Api = InstallerApi.InstallerApi() + self.assertEqual(Api.CheckLegacyMove(), {"Ok": True, "NeedsConfigChoice": False}) + self.assertEqual(Api.StartLegacyMove("Reinstall"), {"Error": "Bad request."}) + Manifest = Setup.ReadManifest(self.Target) + Result = Legacy.RunMove(self.Old, self.Target, "MoveKeep", "KeepNew", NoReport) + self.assertEqual((Result["Mode"], Result["InstallPath"]), ("MoveKeep", self.Target)) + self.assertIn("OldTester", Read(os.path.join(self.Target, "Config", "Accounts.json"))) + self.assertEqual(Setup.ReadManifest(self.Target), Manifest) # nothing reinstalled + self.assertTrue(os.path.isfile(os.path.join(self.Old, "Src", "Version.json"))) # old one kept + self.assertEqual((Setup.RegRead("InstallPath"), Setup.RegRead("Version")), (self.Target, "1.1.0")) + self.assertIsNone(Setup.RegRead("LegacyInstallPath")) + self.assertIsNone(Legacy.Detect()) + + def test_MoveIntoInstalledRammitThenRemoveTheOldOne(self): + self.Install("1.1.0") + Legacy.Ignore(False, self.Old) + Legacy.RunMove(self.Old, self.Target, "MoveRemove", "KeepNew", NoReport) + self.assertIn("OldTester", Read(os.path.join(self.Target, "Config", "Accounts.json"))) + self.assertFalse(os.path.exists(self.Old)) + self.assertFalse(any(os.path.exists(P) for P in Setup.ShortcutPaths() + if Setup.ReadShortcut(P)[0].lower().endswith("powershell.exe"))) + self.assertEqual((Setup.RegRead("InstallPath"), Setup.RegRead("Version")), (self.Target, "1.1.0")) + self.assertIsNone(Legacy.Detect()) + def test_config_clash_keep_new_or_use_old(self): self.Install("1.0.0") Write(os.path.join(self.Target, "Config", "Accounts.json"), '[{"username": "NewTester"}]') @@ -696,6 +748,26 @@ def test_no_public_state_and_bad_arguments_return_errors(self): self.assertIsNone(Api.ResizeInstaller("tall")) self.assertIn("Error", Api.Launch()) + def test_ResizeWaitsForLetGoWhileHeld(self): + Window = Support.EventWindow() + Window.native = mock.Mock(Height=409, DeviceDpi=96) # 327 logical px at 125%; DeviceDpi stays 96 (pywebview) + Api = InstallerApi.InstallerApi() + Api._AttachWindow(Window) + Api._LastHeight, Api._Frame = 327, 39 + Api._Dragging = True # title bar held: only record the height (a resize now would just flicker) + Api.ResizeInstaller(411, 288) + self.assertIsNone(Window.LastResize) + self.assertEqual(Api._LastHeight, 450) + with mock.patch.object(InstallerApi.InstallerApi, "_SetHeight") as SetHeight, \ + mock.patch.object(InstallerApi.InstallerApi, "_WindowScale", return_value=1.25): + Api._Dragging = False + Api._ReapplyHeight() # what letting go runs + SetHeight.assert_called_once_with(Window.native, round(450 * 1.25)) + SetHeight.reset_mock() + Window.native.Height = round(450 * 1.25) # already right: nothing to do + Api._ReapplyHeight() + SetHeight.assert_not_called() + class TestUiServer(unittest.TestCase): @classmethod diff --git a/Production/Installer/Tests/TestUi.mjs b/Production/Installer/Tests/TestUi.mjs index 6ea2a89..e93f26e 100644 --- a/Production/Installer/Tests/TestUi.mjs +++ b/Production/Installer/Tests/TestUi.mjs @@ -225,7 +225,7 @@ try { await Open(); await Shot('08-MenuInstalled', 'MenuInstalled'); Check('installed menu: versions + buttons (no separate Change version)', (await Text('#InstalledVer')) === 'v1.0.0' && (await Text('#LatestVer')) === 'v1.1.0' - && JSON.stringify(await Page.$$eval('[data-screen=MenuInstalled] .BtnInst', Els => Els.map(E => E.textContent))) === '["UPDATE / DOWNGRADE","REPAIR","UNINSTALL","CANCEL"]'); + && JSON.stringify(await Page.$$eval('[data-screen=MenuInstalled] .BtnInst', Els => Els.filter(E => !E.hidden).map(E => E.textContent))) === '["UPDATE / DOWNGRADE","REPAIR","UNINSTALL","CANCEL"]'); // OLD VERSION is hidden: no old version put off await ClickBtn('UpdateBtn'); await Shot('09-UpdateDowngrade', 'ChangeVersion'); Check('update/downgrade: crumbs', (await Crumbs()) === 'Menu > Version* > Progress > Done', await Crumbs()); diff --git a/Production/RAMMIT-Stable/App/Api.py b/Production/RAMMIT-Stable/App/Api.py index 82f35be..1e0e905 100644 --- a/Production/RAMMIT-Stable/App/Api.py +++ b/Production/RAMMIT-Stable/App/Api.py @@ -18,6 +18,7 @@ from App import MultiInstance, Roblox, Storage, Themes from App.Log import Logger from App.Version import AppChannel, AppName, AppVersion, VersionLabel +from App.WindowSize import HeldWindow LockedLoginMessage = "This saved login can't be read on this PC or Windows user. Remove the account and add it again." RobloxFirstMessage = "Roblox was already open when RAMMIT started, so only one client can run. Close every Roblox window, then launch again." @@ -35,6 +36,8 @@ def __init__(self, Server=None): self._Batch = self._EmptyBatch() self._MainWindow = None self._WizardWindow = None + self._MainSizer = None # App/WindowSize.HeldWindow: resizes that wait while the title bar is held + self._WizardSizer = None self._WizardEditName = "" self._LoginWindow = None self._LoginLock = threading.Lock() @@ -46,6 +49,7 @@ def __init__(self, Server=None): def _AttachMainWindow(self, Window): self._MainWindow = Window + self._MainSizer = HeldWindow(Window) def _ChosenThemeId(self): return self._Settings.get("Theme", Themes.DefaultThemeId) @@ -209,10 +213,12 @@ def OpenConfigWizard(self, EditName=""): Window.events.closed += self._OnWizardClosed GuardNavigation(Window, self._Server, "Wizard.html") self._WizardWindow = Window + self._WizardSizer = HeldWindow(Window) return {"Ok": True} def _OnWizardClosed(self): self._WizardWindow = None + self._WizardSizer = None def GetWizardData(self): with self._DataLock: @@ -486,9 +492,9 @@ def ResizeWindow(self, Height): Height = max(400, min(int(Height), 1400)) except (TypeError, ValueError): return - if self._MainWindow: + if self._MainSizer: try: - self._MainWindow.resize(int(900 * 0.85), int(Height * 0.85)) + self._MainSizer.Resize(int(900 * 0.85), int(Height * 0.85)) except Exception: pass @@ -497,12 +503,12 @@ def ResizeWizard(self, Height): Height = max(200, min(int(Height), 1200)) except (TypeError, ValueError): return - Window = self._WizardWindow - if Window: + Window, Sizer = self._WizardWindow, self._WizardSizer + if Window and Sizer: try: if abs(Height - Window.height) < 2: # Test1: skip tiny resizes so the window doesn't jitter return - Window.resize(Themes.LoadHeightMap(self._ActiveThemeId())[0]["WizardWindow"]["Width"], Height) + Sizer.Resize(Themes.LoadHeightMap(self._ActiveThemeId())[0]["WizardWindow"]["Width"], Height) except Exception: pass diff --git a/Production/RAMMIT-Stable/App/Main.py b/Production/RAMMIT-Stable/App/Main.py index e9e8629..0329516 100644 --- a/Production/RAMMIT-Stable/App/Main.py +++ b/Production/RAMMIT-Stable/App/Main.py @@ -10,7 +10,18 @@ from App.Log import Logger, Setup as SetupLog from App.Version import VersionLabel -WindowWidth, WindowHeight, WindowScale = 900, 700, 0.85 +WindowWidth, WindowScale = 900, 0.85 + + +def StartHeight(Bridge): + """Opening height from this theme's HeightMap.json for the saved launch option, so the window opens at + the right size. The page still resizes on boot (it alone can measure a theme note).""" + Map = Themes.LoadHeightMap(Bridge._ActiveThemeId())[0]["MainWindow"] + Settings = Bridge._Settings + Height = Map.get(Settings.get("LaunchOption"), Map["Home"]) + if (Settings.get("LaunchParams") or {}).get("PlayerMode") in ("min_only", "max_only", "range"): + Height += Map["PlayerFilterExtra"] + return max(400, min(Height, 1400)) # same limits as Api.ResizeWindow def Run(): @@ -29,7 +40,7 @@ def Run(): url=Server.Url("Index.html"), js_api=Bridge, width=int(WindowWidth * WindowScale), - height=int(WindowHeight * WindowScale), + height=int(StartHeight(Bridge) * WindowScale), resizable=False, background_color=Themes.BackgroundColor(Bridge._ActiveThemeId()), ) diff --git a/Production/RAMMIT-Stable/App/Version.py b/Production/RAMMIT-Stable/App/Version.py index bec0130..586383b 100644 --- a/Production/RAMMIT-Stable/App/Version.py +++ b/Production/RAMMIT-Stable/App/Version.py @@ -7,7 +7,7 @@ """ AppName = "RAMMIT" -AppVersion = "1.1.1" +AppVersion = "1.1.2" try: from App.BuildInfo import AppChannel, AppCommit diff --git a/Production/RAMMIT-Stable/App/WindowSize.py b/Production/RAMMIT-Stable/App/WindowSize.py new file mode 100644 index 0000000..7410b99 --- /dev/null +++ b/Production/RAMMIT-Stable/App/WindowSize.py @@ -0,0 +1,69 @@ +"""Resizing a window the user may be holding (main window and config wizard). + +Grabbing or dragging a title bar starts Windows' move loop, which keeps the size the window had when it began: a +resize sent meanwhile is undone, or only flickers. So while a window is held, Resize() only records the height, and +when the loop ends (ResizeEnd fires for moves too) it is applied once. That resize sets the size only (SWP_NOMOVE), +because pywebview's resize also writes a position read a moment ago, which drags the window back if it is still +moving. Same fix as the installer's (Production/Installer, InstallerApi._WatchDrags). +""" +import ctypes +import ctypes.wintypes +import threading + +from App.Log import Logger + +SwpNoMove, SwpNoZOrder, SwpNoActivate = 0x2, 0x4, 0x10 + + +class HeldWindow: + """Wraps a pywebview window. Keep it in a _-prefixed Api attribute: pywebview exposes public ones to the page.""" + + def __init__(self, Window): + self._Window = Window + self._Dragging = False + self._Width = 0 # logical px last asked for + self._Height = 0 + Events = getattr(Window, "events", None) + if hasattr(Events, "shown"): # the UI tests' stand-in window has no shown event + Events.shown += self._WatchDrags + + def _WatchDrags(self): + try: + Native = self._Window.native + Native.ResizeBegin += lambda _Sender, _Args: setattr(self, "_Dragging", True) + Native.ResizeEnd += self._OnLetGo + except Exception as Error: + Logger.warning("Can't watch window drags: %s", type(Error).__name__) + + def Resize(self, Width, Height): + self._Width, self._Height = Width, Height + if self._Dragging: + return # held: Windows would undo it; _OnLetGo applies it + self._Window.resize(Width, Height) + + def _OnLetGo(self, _Sender, _Args): + self._Dragging = False + threading.Thread(target=self._ReapplyHeight, daemon=True).start() + + def _ReapplyHeight(self): + if not self._Height: + return + try: + Native = self._Window.native + Scale = self._WindowScale(Native) + if abs(Native.Height / Scale - self._Height) >= 2: + self._SetHeight(Native, round(self._Height * Scale)) + except Exception: + pass + + @staticmethod + def _WindowScale(Native): + """The window's real DPI scale. Not Form.DeviceDpi: pywebview's SetProcessDPIAware leaves that at 96.""" + return max(1.0, ctypes.windll.user32.GetDpiForWindow(ctypes.wintypes.HWND(Native.Handle.ToInt64())) / 96.0) + + @staticmethod + def _SetHeight(Native, PhysicalHeight): + Hwnd = ctypes.wintypes.HWND(Native.Handle.ToInt64()) + Rect = ctypes.wintypes.RECT() + ctypes.windll.user32.GetWindowRect(Hwnd, ctypes.byref(Rect)) + ctypes.windll.user32.SetWindowPos(Hwnd, None, 0, 0, Rect.right - Rect.left, PhysicalHeight, SwpNoMove | SwpNoZOrder | SwpNoActivate) diff --git a/Production/RAMMIT-Stable/CHANGELOG.md b/Production/RAMMIT-Stable/CHANGELOG.md index f215863..9d14765 100644 --- a/Production/RAMMIT-Stable/CHANGELOG.md +++ b/Production/RAMMIT-Stable/CHANGELOG.md @@ -1,5 +1,17 @@ # Changelog +## 1.1.2 (2026-11) + +- **Installer:** the window no longer stays at the Loading screen's height. Grabbing or dragging the title bar while the screen changed undid the resize; a resize that arrives while the window is held now waits and is applied once when you let go. +- **Installer:** the window opens at the Loading screen's real height (`HeightMap.json` Loading 327 → 323), so it no longer shrinks a few pixels right after opening, and the space above and below the card is even. +- **Installer:** pressing **Ignore** on the "older test version" screen without ticking "Don't ask again" now puts it off instead of asking every time: the menu opens as normal, with an **OLD VERSION** button and a line saying where the old version is. It stays reachable after installing the new RAMMIT, and goes away once the old version is moved or removed. +- **Installer:** with RAMMIT already installed, the old version's screen keeps all four choices. The two "move my accounts" choices then copy its accounts and settings into the installed RAMMIT without reinstalling it, and the first one removes the old version afterwards. +- **Installer:** the "Uninstall Config/ folder too" tick box no longer shows its check mark while unticked (#2). +- **Tooltips:** every button and setting has a tooltip, drawn in the theme's own colours instead of the plain Windows one. It follows the cursor and flips to the other side near the window's edges. CBlock's are rounded; a custom theme can set `--TooltipRadius`. +- The main window opens at its `HeightMap.json` height for the saved launch option, instead of opening shorter and resizing once the page has loaded. +- The main window and the config window keep the right height when you grab or drag their title bar while they resize: the resize waits and is applied when you let go (the same fix as the installer's). +- The theme colour swatch next to the Theme drop-down has straight edges instead of jagged ones. + ## 1.1.1 (2026-11) - **Installer:** uninstalling now removes the Desktop and Start Menu shortcuts even when Windows writes the folder with its short name (e.g. `C:\Users\JOHNSM~1\...` instead of `C:\Users\John Smith\...`). Before, the shortcuts were left behind in that case. @@ -49,7 +61,7 @@ Full audit; details in [SECURITY.md](SECURITY.md). - Config wizard uses Test1's tuned per-method heights and sizing logic (`HeightMap.json` › `WizardWindow`). ### Added -- **CBlock theme** (`Src\CBlock`): the Industrialist Simulator / CBlock website look. It has the same layout as Dark, with black and near-black panels, one violet accent (`#5d1fa9`) and thin indigo rings. Fields use the site's `.Field` style. Buttons follow the site: `.Btn.Filled` for the main actions (LAUNCH, CONFIRM) and outlined `.Btn` for the secondary ones (ADD, EDIT, REMOVE, CANCEL), each inverting on hover. Panel titles are uppercase and use a lighter violet for readability. Sizes are unchanged, so the height map holds. +- **CBlock theme** (`Src\CBlock`): the CBlock website look. It has the same layout as Dark, with black and near-black panels, one violet accent (`#5d1fa9`) and thin indigo rings. Fields use the site's `.Field` style. Buttons follow the site: `.Btn.Filled` for the main actions (LAUNCH, CONFIRM) and outlined `.Btn` for the secondary ones (ADD, EDIT, REMOVE, CANCEL), each inverting on hover. Panel titles are uppercase and use a lighter violet for readability. Sizes are unchanged, so the height map holds. ### Changed - Launchers: **Fishstrap** replaces Voidstrap (Roblox / Bloxstrap / Fishstrap, as in Test1). A saved "Voidstrap" setting falls back to Roblox. diff --git a/Production/RAMMIT-Stable/Docs/HowToMakeATheme.txt b/Production/RAMMIT-Stable/Docs/HowToMakeATheme.txt index 9e23bcf..c7862d8 100644 --- a/Production/RAMMIT-Stable/Docs/HowToMakeATheme.txt +++ b/Production/RAMMIT-Stable/Docs/HowToMakeATheme.txt @@ -8,7 +8,7 @@ A theme is just a folder. Every theme RAMMIT can use lives in the Src\ Dark\ the default look (comes with RAMMIT) Light\ the 2016 Roblox look (comes with RAMMIT) - CBlock\ the CBlock / Industrialist look (comes with RAMMIT) + CBlock\ the CBlock look (comes with RAMMIT) MyCustomTheme\ an example custom theme (comes with RAMMIT) OceanBlue\ <- your theme goes here, next to the others @@ -42,7 +42,7 @@ press the "?" button, then "Making your own theme". "SupportedVersions" says which RAMMIT versions your theme was made for. The version is at the bottom of the Settings panel - (for example "RAMMIT v1.1.1 - Stable"). + (for example "RAMMIT v1.1.2 - Stable"). "1.0" any 1.0.x (1.0.0, 1.0.1, ...) "1.0.2" exactly 1.0.2 "1.2+" 1.2.0 and everything newer diff --git a/Production/RAMMIT-Stable/Docs/README.txt b/Production/RAMMIT-Stable/Docs/README.txt index 5fa2d39..470a70a 100644 --- a/Production/RAMMIT-Stable/Docs/README.txt +++ b/Production/RAMMIT-Stable/Docs/README.txt @@ -1,5 +1,5 @@ ======================================================== - RAMMIT - Roblox Multi-Account Launcher (v1.1.1) + RAMMIT - Roblox Multi-Account Launcher (v1.1.2) Setup Guide (read this first) ======================================================== @@ -10,7 +10,7 @@ them at the same time on one PC. You do NOT need Python or any other program installed - everything RAMMIT needs is inside this folder. The bottom of the Settings panel shows your version, for example -"RAMMIT v1.1.1 · Stable". Please include it when you report a problem. +"RAMMIT v1.1.2 · Stable". Please include it when you report a problem. WHAT YOU NEED diff --git a/Production/RAMMIT-Stable/Src/CBlock/CSS/Style.css b/Production/RAMMIT-Stable/Src/CBlock/CSS/Style.css index 0436d0a..8aecad4 100644 --- a/Production/RAMMIT-Stable/Src/CBlock/CSS/Style.css +++ b/Production/RAMMIT-Stable/Src/CBlock/CSS/Style.css @@ -1,6 +1,6 @@ /* ===================================================================== THEME: CBlock - The look of the Industrialist Simulator website: near-black panels on + The look of the CBlock website: near-black panels on black, one deep violet accent (#5d1fa9), thin indigo borders, flat. Same variables as Dark - see HowToMakeATheme.txt next to RAMMIT.exe. ===================================================================== */ @@ -32,6 +32,7 @@ --Font: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; --Radius: 8px; /* panel corners */ --ButtonRadius: 4px; /* button and text-box corners */ + --TooltipRadius: 4px; /* tooltip corners (other themes: square) */ } /* ===================================================================== @@ -1152,7 +1153,13 @@ body.WizardBody { box-sizing: border-box; border: 1px solid var(--BorderLight); border-radius: 2px; - background: conic-gradient(var(--S2) 0 25%, var(--S3) 0 50%, var(--S0) 0 75%, var(--S1) 0); + /* Three half-size layers over --S1, not a conic-gradient: its hard stops come out jagged at + fractional sizes and DPI scaling, these straight edges stay crisp. */ + background: + linear-gradient(var(--S2), var(--S2)) right top / 50% 50% no-repeat, + linear-gradient(var(--S3), var(--S3)) right bottom / 50% 50% no-repeat, + linear-gradient(var(--S0), var(--S0)) left bottom / 50% 50% no-repeat, + var(--S1); } /* Exactly as tall as the picker (the button keeps its natural height, so the row and the @@ -1241,12 +1248,39 @@ body.WizardBody { border-radius: var(--ButtonRadius); } +/* Tooltips (JS/Tooltip.js): follow the cursor, flip to its other side at the window's edges. Outside .Container, so + not zoomed. Square unless the theme sets --TooltipRadius. Width is the text's own (max-content), so measuring it + does not depend on where it currently sits; long text wraps, and "\n" starts a new line. */ +.Tooltip { + position: fixed; + left: 0; + top: 0; + z-index: 9999; + width: max-content; + max-width: min(320px, calc(100vw - 8px)); + padding: 4px 8px; + background: var(--Card); + border: 1px solid var(--BorderLight); + border-radius: var(--TooltipRadius, 0px); + color: var(--Text); + font-family: var(--Font); + font-size: 11px; + white-space: pre-line; + pointer-events: none; + opacity: 0; + transition: opacity 0.15s; +} + +.Tooltip.Visible { + opacity: 1; +} + /* ===================================================================== THEME EXTRAS - rules only this theme has. Keep them below this line. ===================================================================== */ /* CBlock: flat panels, 1px indigo rings, outlined buttons that invert on hover (the - Industrialist site's .Btn / .Field / .DropdownToggle look). Nothing here changes a size: + CBlock site's .Btn / .Field / .DropdownToggle look). Nothing here changes a size: rings are inset box-shadows or outlines, so HeightMap.json still fits. */ /* Panels: the site's 1px #18122a border, drawn inside the box. */ diff --git a/Production/RAMMIT-Stable/Src/CBlock/HTML/Index.html b/Production/RAMMIT-Stable/Src/CBlock/HTML/Index.html index 4cfcd08..9a5b0d9 100644 --- a/Production/RAMMIT-Stable/Src/CBlock/HTML/Index.html +++ b/Production/RAMMIT-Stable/Src/CBlock/HTML/Index.html @@ -39,7 +39,7 @@
-
+
Home ▼
@@ -81,12 +81,12 @@
- - - + + +
-
+
@@ -112,7 +112,7 @@
-
+
Roblox ▼
@@ -125,19 +125,19 @@
- +
- + - +
- +
diff --git a/Production/RAMMIT-Stable/Src/CBlock/HTML/Wizard.html b/Production/RAMMIT-Stable/Src/CBlock/HTML/Wizard.html index fff89a1..4f577bd 100644 --- a/Production/RAMMIT-Stable/Src/CBlock/HTML/Wizard.html +++ b/Production/RAMMIT-Stable/Src/CBlock/HTML/Wizard.html @@ -23,11 +23,11 @@
- +
-
+
Home ▼
@@ -43,8 +43,8 @@
- - + +
diff --git a/Production/RAMMIT-Stable/Src/CBlock/JS/Main.js b/Production/RAMMIT-Stable/Src/CBlock/JS/Main.js index a42dbb8..49c21fd 100644 --- a/Production/RAMMIT-Stable/Src/CBlock/JS/Main.js +++ b/Production/RAMMIT-Stable/Src/CBlock/JS/Main.js @@ -11,6 +11,7 @@ import { InitSettingsPanel, RestoreSettingsPanel } from './Settings.js'; import { InitThemePicker, LoadThemes } from './Themes.js'; import { InitTours, StartTour } from './Tours.js'; import { ShowLaunchError, ShowStatus } from './Status.js'; +import { InitTooltips } from './Tooltip.js'; function WireButtons() { ById('AddAccountBtn').addEventListener('click', () => AddAccount().catch(ReportError)); @@ -22,6 +23,7 @@ function WireButtons() { } async function Boot() { + InitTooltips(); WireButtons(); InitLaunchPanel(); InitSettingsPanel(); diff --git a/Production/RAMMIT-Stable/Src/CBlock/JS/Tooltip.js b/Production/RAMMIT-Stable/Src/CBlock/JS/Tooltip.js new file mode 100644 index 0000000..5635396 --- /dev/null +++ b/Production/RAMMIT-Stable/Src/CBlock/JS/Tooltip.js @@ -0,0 +1,66 @@ +// Themed tooltips (the CBlock tooltip), instead of the browser's own. +// Any element with data-tooltip="..." or a title="..." gets one: a title is moved into data-tooltip when hovered, +// so the native tooltip never shows and no existing title has to change. "\n" in the text starts a new line. +// Look: .Tooltip in Style.css (colours from the theme; --TooltipRadius rounds it, 0 by default). + +const OffsetX = 12, OffsetY = 16; // from the cursor +const FlipGap = 12; // from the cursor when flipped to its left / above it +let Tip = null; +let Target = null; +let LastX = 0, LastY = 0; + +// Takes over a title (also one set again later, e.g. an account's status) and returns the text to show. +function ReadText(Node) { + if (Node.hasAttribute('title')) { + Node.dataset.tooltip = Node.getAttribute('title'); + Node.removeAttribute('title'); + } + return (Node.dataset.tooltip || '').replace(/\\n/g, '\n'); +} + +// Right of / below the cursor; where that would leave the window, the other side of the cursor instead. +function Place() { + const Width = Tip.offsetWidth, Height = Tip.offsetHeight; + let X = LastX + OffsetX, Y = LastY + OffsetY; + if (X + Width > innerWidth) X = LastX - FlipGap - Width; + if (Y + Height > innerHeight) Y = LastY - FlipGap - Height; + Tip.style.left = Math.max(0, X) + 'px'; + Tip.style.top = Math.max(0, Y) + 'px'; +} + +function Show(Node) { + const Text = ReadText(Node); + if (!Text) { Hide(); return; } + Target = Node; + Tip.textContent = Text; + Place(); // before it fades in, so it never flashes where it was last time + Tip.classList.add('Visible'); +} + +function Hide() { + Target = null; + if (Tip) Tip.classList.remove('Visible'); +} + +export function InitTooltips() { + Tip = document.createElement('div'); + Tip.className = 'Tooltip'; + Tip.setAttribute('role', 'tooltip'); + document.body.append(Tip); + + document.addEventListener('mouseover', Event => { + LastX = Event.clientX; LastY = Event.clientY; + const Node = Event.target.closest('[data-tooltip], [title]'); + if (Node) Show(Node); else if (Target) Hide(); + }); + document.addEventListener('mousemove', Event => { + LastX = Event.clientX; LastY = Event.clientY; + if (!Target) return; + if (!Target.isConnected) { Hide(); return; } // re-drawn under the cursor: no mouseout ever comes + if (Target.hasAttribute('title')) Show(Target); else Place(); + }); + document.addEventListener('mouseout', Event => { if (!Event.relatedTarget) Hide(); }); // left the window + document.addEventListener('mousedown', Hide); + document.addEventListener('scroll', Hide, true); + window.addEventListener('blur', Hide); +} diff --git a/Production/RAMMIT-Stable/Src/CBlock/JS/Wizard.js b/Production/RAMMIT-Stable/Src/CBlock/JS/Wizard.js index bad69c1..9bca02a 100644 --- a/Production/RAMMIT-Stable/Src/CBlock/JS/Wizard.js +++ b/Production/RAMMIT-Stable/Src/CBlock/JS/Wizard.js @@ -11,6 +11,7 @@ import { Api, WaitForApi, ReportError } from './Bridge.js'; import { ById } from './Dom.js'; import { InitSelect, SetSelectValue, GetSelectValue } from './Select.js'; import { CreateLaunchForm, FilterMethods } from './LaunchForm.js'; +import { InitTooltips } from './Tooltip.js'; let SizeMap = { Home: 287, ExtraPadding: 20 }; let InitDone = false; @@ -60,6 +61,7 @@ ById('ConfirmBtn').addEventListener('click', async () => { }); async function Boot() { + InitTooltips(); await WaitForApi('GetWizardData'); const HeightMap = await Api.GetHeightMap().catch(() => null); if (HeightMap && HeightMap.WizardWindow) SizeMap = HeightMap.WizardWindow; diff --git a/Production/RAMMIT-Stable/Src/CBlock/Theme.json b/Production/RAMMIT-Stable/Src/CBlock/Theme.json index 0c82b2a..f31c288 100644 --- a/Production/RAMMIT-Stable/Src/CBlock/Theme.json +++ b/Production/RAMMIT-Stable/Src/CBlock/Theme.json @@ -1,6 +1,6 @@ { "Name": "CBlock", "Author": "RAMMIT", - "Description": "The CBlock / Industrialist look.", + "Description": "The CBlock look.", "SupportedVersions": ["1.0", "1.1"] } \ No newline at end of file diff --git a/Production/RAMMIT-Stable/Src/Dark/CSS/Style.css b/Production/RAMMIT-Stable/Src/Dark/CSS/Style.css index 73e42c1..b8b879f 100644 --- a/Production/RAMMIT-Stable/Src/Dark/CSS/Style.css +++ b/Production/RAMMIT-Stable/Src/Dark/CSS/Style.css @@ -1154,7 +1154,13 @@ body.WizardBody { box-sizing: border-box; border: 1px solid var(--BorderLight); border-radius: 2px; - background: conic-gradient(var(--S2) 0 25%, var(--S3) 0 50%, var(--S0) 0 75%, var(--S1) 0); + /* Three half-size layers over --S1, not a conic-gradient: its hard stops come out jagged at + fractional sizes and DPI scaling, these straight edges stay crisp. */ + background: + linear-gradient(var(--S2), var(--S2)) right top / 50% 50% no-repeat, + linear-gradient(var(--S3), var(--S3)) right bottom / 50% 50% no-repeat, + linear-gradient(var(--S0), var(--S0)) left bottom / 50% 50% no-repeat, + var(--S1); } /* Exactly as tall as the picker (the button keeps its natural height, so the row and the @@ -1243,6 +1249,33 @@ body.WizardBody { border-radius: var(--ButtonRadius); } +/* Tooltips (JS/Tooltip.js): follow the cursor, flip to its other side at the window's edges. Outside .Container, so + not zoomed. Square unless the theme sets --TooltipRadius. Width is the text's own (max-content), so measuring it + does not depend on where it currently sits; long text wraps, and "\n" starts a new line. */ +.Tooltip { + position: fixed; + left: 0; + top: 0; + z-index: 9999; + width: max-content; + max-width: min(320px, calc(100vw - 8px)); + padding: 4px 8px; + background: var(--Card); + border: 1px solid var(--BorderLight); + border-radius: var(--TooltipRadius, 0px); + color: var(--Text); + font-family: var(--Font); + font-size: 11px; + white-space: pre-line; + pointer-events: none; + opacity: 0; + transition: opacity 0.15s; +} + +.Tooltip.Visible { + opacity: 1; +} + /* ===================================================================== THEME EXTRAS - rules only this theme has. Keep them below this line. ===================================================================== */ diff --git a/Production/RAMMIT-Stable/Src/Dark/HTML/Index.html b/Production/RAMMIT-Stable/Src/Dark/HTML/Index.html index 4cfcd08..9a5b0d9 100644 --- a/Production/RAMMIT-Stable/Src/Dark/HTML/Index.html +++ b/Production/RAMMIT-Stable/Src/Dark/HTML/Index.html @@ -39,7 +39,7 @@
-
+
Home ▼
@@ -81,12 +81,12 @@
- - - + + +
-
+
@@ -112,7 +112,7 @@
-
+
Roblox ▼
@@ -125,19 +125,19 @@
- +
- + - +
- +
diff --git a/Production/RAMMIT-Stable/Src/Dark/HTML/Wizard.html b/Production/RAMMIT-Stable/Src/Dark/HTML/Wizard.html index fff89a1..4f577bd 100644 --- a/Production/RAMMIT-Stable/Src/Dark/HTML/Wizard.html +++ b/Production/RAMMIT-Stable/Src/Dark/HTML/Wizard.html @@ -23,11 +23,11 @@
- +
-
+
Home ▼
@@ -43,8 +43,8 @@
- - + +
diff --git a/Production/RAMMIT-Stable/Src/Dark/JS/Main.js b/Production/RAMMIT-Stable/Src/Dark/JS/Main.js index a42dbb8..49c21fd 100644 --- a/Production/RAMMIT-Stable/Src/Dark/JS/Main.js +++ b/Production/RAMMIT-Stable/Src/Dark/JS/Main.js @@ -11,6 +11,7 @@ import { InitSettingsPanel, RestoreSettingsPanel } from './Settings.js'; import { InitThemePicker, LoadThemes } from './Themes.js'; import { InitTours, StartTour } from './Tours.js'; import { ShowLaunchError, ShowStatus } from './Status.js'; +import { InitTooltips } from './Tooltip.js'; function WireButtons() { ById('AddAccountBtn').addEventListener('click', () => AddAccount().catch(ReportError)); @@ -22,6 +23,7 @@ function WireButtons() { } async function Boot() { + InitTooltips(); WireButtons(); InitLaunchPanel(); InitSettingsPanel(); diff --git a/Production/RAMMIT-Stable/Src/Dark/JS/Tooltip.js b/Production/RAMMIT-Stable/Src/Dark/JS/Tooltip.js new file mode 100644 index 0000000..5635396 --- /dev/null +++ b/Production/RAMMIT-Stable/Src/Dark/JS/Tooltip.js @@ -0,0 +1,66 @@ +// Themed tooltips (the CBlock tooltip), instead of the browser's own. +// Any element with data-tooltip="..." or a title="..." gets one: a title is moved into data-tooltip when hovered, +// so the native tooltip never shows and no existing title has to change. "\n" in the text starts a new line. +// Look: .Tooltip in Style.css (colours from the theme; --TooltipRadius rounds it, 0 by default). + +const OffsetX = 12, OffsetY = 16; // from the cursor +const FlipGap = 12; // from the cursor when flipped to its left / above it +let Tip = null; +let Target = null; +let LastX = 0, LastY = 0; + +// Takes over a title (also one set again later, e.g. an account's status) and returns the text to show. +function ReadText(Node) { + if (Node.hasAttribute('title')) { + Node.dataset.tooltip = Node.getAttribute('title'); + Node.removeAttribute('title'); + } + return (Node.dataset.tooltip || '').replace(/\\n/g, '\n'); +} + +// Right of / below the cursor; where that would leave the window, the other side of the cursor instead. +function Place() { + const Width = Tip.offsetWidth, Height = Tip.offsetHeight; + let X = LastX + OffsetX, Y = LastY + OffsetY; + if (X + Width > innerWidth) X = LastX - FlipGap - Width; + if (Y + Height > innerHeight) Y = LastY - FlipGap - Height; + Tip.style.left = Math.max(0, X) + 'px'; + Tip.style.top = Math.max(0, Y) + 'px'; +} + +function Show(Node) { + const Text = ReadText(Node); + if (!Text) { Hide(); return; } + Target = Node; + Tip.textContent = Text; + Place(); // before it fades in, so it never flashes where it was last time + Tip.classList.add('Visible'); +} + +function Hide() { + Target = null; + if (Tip) Tip.classList.remove('Visible'); +} + +export function InitTooltips() { + Tip = document.createElement('div'); + Tip.className = 'Tooltip'; + Tip.setAttribute('role', 'tooltip'); + document.body.append(Tip); + + document.addEventListener('mouseover', Event => { + LastX = Event.clientX; LastY = Event.clientY; + const Node = Event.target.closest('[data-tooltip], [title]'); + if (Node) Show(Node); else if (Target) Hide(); + }); + document.addEventListener('mousemove', Event => { + LastX = Event.clientX; LastY = Event.clientY; + if (!Target) return; + if (!Target.isConnected) { Hide(); return; } // re-drawn under the cursor: no mouseout ever comes + if (Target.hasAttribute('title')) Show(Target); else Place(); + }); + document.addEventListener('mouseout', Event => { if (!Event.relatedTarget) Hide(); }); // left the window + document.addEventListener('mousedown', Hide); + document.addEventListener('scroll', Hide, true); + window.addEventListener('blur', Hide); +} diff --git a/Production/RAMMIT-Stable/Src/Dark/JS/Wizard.js b/Production/RAMMIT-Stable/Src/Dark/JS/Wizard.js index bad69c1..9bca02a 100644 --- a/Production/RAMMIT-Stable/Src/Dark/JS/Wizard.js +++ b/Production/RAMMIT-Stable/Src/Dark/JS/Wizard.js @@ -11,6 +11,7 @@ import { Api, WaitForApi, ReportError } from './Bridge.js'; import { ById } from './Dom.js'; import { InitSelect, SetSelectValue, GetSelectValue } from './Select.js'; import { CreateLaunchForm, FilterMethods } from './LaunchForm.js'; +import { InitTooltips } from './Tooltip.js'; let SizeMap = { Home: 287, ExtraPadding: 20 }; let InitDone = false; @@ -60,6 +61,7 @@ ById('ConfirmBtn').addEventListener('click', async () => { }); async function Boot() { + InitTooltips(); await WaitForApi('GetWizardData'); const HeightMap = await Api.GetHeightMap().catch(() => null); if (HeightMap && HeightMap.WizardWindow) SizeMap = HeightMap.WizardWindow; diff --git a/Production/RAMMIT-Stable/Src/Light/CSS/Style.css b/Production/RAMMIT-Stable/Src/Light/CSS/Style.css index a7f7ddc..17f11e7 100644 --- a/Production/RAMMIT-Stable/Src/Light/CSS/Style.css +++ b/Production/RAMMIT-Stable/Src/Light/CSS/Style.css @@ -1152,7 +1152,13 @@ body.WizardBody { box-sizing: border-box; border: 1px solid var(--BorderLight); border-radius: 2px; - background: conic-gradient(var(--S2) 0 25%, var(--S3) 0 50%, var(--S0) 0 75%, var(--S1) 0); + /* Three half-size layers over --S1, not a conic-gradient: its hard stops come out jagged at + fractional sizes and DPI scaling, these straight edges stay crisp. */ + background: + linear-gradient(var(--S2), var(--S2)) right top / 50% 50% no-repeat, + linear-gradient(var(--S3), var(--S3)) right bottom / 50% 50% no-repeat, + linear-gradient(var(--S0), var(--S0)) left bottom / 50% 50% no-repeat, + var(--S1); } /* Exactly as tall as the picker (the button keeps its natural height, so the row and the @@ -1241,6 +1247,33 @@ body.WizardBody { border-radius: var(--ButtonRadius); } +/* Tooltips (JS/Tooltip.js): follow the cursor, flip to its other side at the window's edges. Outside .Container, so + not zoomed. Square unless the theme sets --TooltipRadius. Width is the text's own (max-content), so measuring it + does not depend on where it currently sits; long text wraps, and "\n" starts a new line. */ +.Tooltip { + position: fixed; + left: 0; + top: 0; + z-index: 9999; + width: max-content; + max-width: min(320px, calc(100vw - 8px)); + padding: 4px 8px; + background: var(--Card); + border: 1px solid var(--BorderLight); + border-radius: var(--TooltipRadius, 0px); + color: var(--Text); + font-family: var(--Font); + font-size: 11px; + white-space: pre-line; + pointer-events: none; + opacity: 0; + transition: opacity 0.15s; +} + +.Tooltip.Visible { + opacity: 1; +} + /* ===================================================================== THEME EXTRAS - rules only this theme has. Keep them below this line. ===================================================================== */ diff --git a/Production/RAMMIT-Stable/Src/Light/HTML/Index.html b/Production/RAMMIT-Stable/Src/Light/HTML/Index.html index 4cfcd08..9a5b0d9 100644 --- a/Production/RAMMIT-Stable/Src/Light/HTML/Index.html +++ b/Production/RAMMIT-Stable/Src/Light/HTML/Index.html @@ -39,7 +39,7 @@
-
+
Home ▼
@@ -81,12 +81,12 @@
- - - + + +
-
+
@@ -112,7 +112,7 @@
-
+
Roblox ▼
@@ -125,19 +125,19 @@
- +
- + - +
- +
diff --git a/Production/RAMMIT-Stable/Src/Light/HTML/Wizard.html b/Production/RAMMIT-Stable/Src/Light/HTML/Wizard.html index fff89a1..4f577bd 100644 --- a/Production/RAMMIT-Stable/Src/Light/HTML/Wizard.html +++ b/Production/RAMMIT-Stable/Src/Light/HTML/Wizard.html @@ -23,11 +23,11 @@
- +
-
+
Home ▼
@@ -43,8 +43,8 @@
- - + +
diff --git a/Production/RAMMIT-Stable/Src/Light/JS/Main.js b/Production/RAMMIT-Stable/Src/Light/JS/Main.js index a42dbb8..49c21fd 100644 --- a/Production/RAMMIT-Stable/Src/Light/JS/Main.js +++ b/Production/RAMMIT-Stable/Src/Light/JS/Main.js @@ -11,6 +11,7 @@ import { InitSettingsPanel, RestoreSettingsPanel } from './Settings.js'; import { InitThemePicker, LoadThemes } from './Themes.js'; import { InitTours, StartTour } from './Tours.js'; import { ShowLaunchError, ShowStatus } from './Status.js'; +import { InitTooltips } from './Tooltip.js'; function WireButtons() { ById('AddAccountBtn').addEventListener('click', () => AddAccount().catch(ReportError)); @@ -22,6 +23,7 @@ function WireButtons() { } async function Boot() { + InitTooltips(); WireButtons(); InitLaunchPanel(); InitSettingsPanel(); diff --git a/Production/RAMMIT-Stable/Src/Light/JS/Tooltip.js b/Production/RAMMIT-Stable/Src/Light/JS/Tooltip.js new file mode 100644 index 0000000..5635396 --- /dev/null +++ b/Production/RAMMIT-Stable/Src/Light/JS/Tooltip.js @@ -0,0 +1,66 @@ +// Themed tooltips (the CBlock tooltip), instead of the browser's own. +// Any element with data-tooltip="..." or a title="..." gets one: a title is moved into data-tooltip when hovered, +// so the native tooltip never shows and no existing title has to change. "\n" in the text starts a new line. +// Look: .Tooltip in Style.css (colours from the theme; --TooltipRadius rounds it, 0 by default). + +const OffsetX = 12, OffsetY = 16; // from the cursor +const FlipGap = 12; // from the cursor when flipped to its left / above it +let Tip = null; +let Target = null; +let LastX = 0, LastY = 0; + +// Takes over a title (also one set again later, e.g. an account's status) and returns the text to show. +function ReadText(Node) { + if (Node.hasAttribute('title')) { + Node.dataset.tooltip = Node.getAttribute('title'); + Node.removeAttribute('title'); + } + return (Node.dataset.tooltip || '').replace(/\\n/g, '\n'); +} + +// Right of / below the cursor; where that would leave the window, the other side of the cursor instead. +function Place() { + const Width = Tip.offsetWidth, Height = Tip.offsetHeight; + let X = LastX + OffsetX, Y = LastY + OffsetY; + if (X + Width > innerWidth) X = LastX - FlipGap - Width; + if (Y + Height > innerHeight) Y = LastY - FlipGap - Height; + Tip.style.left = Math.max(0, X) + 'px'; + Tip.style.top = Math.max(0, Y) + 'px'; +} + +function Show(Node) { + const Text = ReadText(Node); + if (!Text) { Hide(); return; } + Target = Node; + Tip.textContent = Text; + Place(); // before it fades in, so it never flashes where it was last time + Tip.classList.add('Visible'); +} + +function Hide() { + Target = null; + if (Tip) Tip.classList.remove('Visible'); +} + +export function InitTooltips() { + Tip = document.createElement('div'); + Tip.className = 'Tooltip'; + Tip.setAttribute('role', 'tooltip'); + document.body.append(Tip); + + document.addEventListener('mouseover', Event => { + LastX = Event.clientX; LastY = Event.clientY; + const Node = Event.target.closest('[data-tooltip], [title]'); + if (Node) Show(Node); else if (Target) Hide(); + }); + document.addEventListener('mousemove', Event => { + LastX = Event.clientX; LastY = Event.clientY; + if (!Target) return; + if (!Target.isConnected) { Hide(); return; } // re-drawn under the cursor: no mouseout ever comes + if (Target.hasAttribute('title')) Show(Target); else Place(); + }); + document.addEventListener('mouseout', Event => { if (!Event.relatedTarget) Hide(); }); // left the window + document.addEventListener('mousedown', Hide); + document.addEventListener('scroll', Hide, true); + window.addEventListener('blur', Hide); +} diff --git a/Production/RAMMIT-Stable/Src/Light/JS/Wizard.js b/Production/RAMMIT-Stable/Src/Light/JS/Wizard.js index bad69c1..9bca02a 100644 --- a/Production/RAMMIT-Stable/Src/Light/JS/Wizard.js +++ b/Production/RAMMIT-Stable/Src/Light/JS/Wizard.js @@ -11,6 +11,7 @@ import { Api, WaitForApi, ReportError } from './Bridge.js'; import { ById } from './Dom.js'; import { InitSelect, SetSelectValue, GetSelectValue } from './Select.js'; import { CreateLaunchForm, FilterMethods } from './LaunchForm.js'; +import { InitTooltips } from './Tooltip.js'; let SizeMap = { Home: 287, ExtraPadding: 20 }; let InitDone = false; @@ -60,6 +61,7 @@ ById('ConfirmBtn').addEventListener('click', async () => { }); async function Boot() { + InitTooltips(); await WaitForApi('GetWizardData'); const HeightMap = await Api.GetHeightMap().catch(() => null); if (HeightMap && HeightMap.WizardWindow) SizeMap = HeightMap.WizardWindow; diff --git a/Production/RAMMIT-Stable/Src/MyCustomTheme/CSS/Style.css b/Production/RAMMIT-Stable/Src/MyCustomTheme/CSS/Style.css index 01e49d8..51d0f35 100644 --- a/Production/RAMMIT-Stable/Src/MyCustomTheme/CSS/Style.css +++ b/Production/RAMMIT-Stable/Src/MyCustomTheme/CSS/Style.css @@ -1151,7 +1151,13 @@ body.WizardBody { box-sizing: border-box; border: 1px solid var(--BorderLight); border-radius: 2px; - background: conic-gradient(var(--S2) 0 25%, var(--S3) 0 50%, var(--S0) 0 75%, var(--S1) 0); + /* Three half-size layers over --S1, not a conic-gradient: its hard stops come out jagged at + fractional sizes and DPI scaling, these straight edges stay crisp. */ + background: + linear-gradient(var(--S2), var(--S2)) right top / 50% 50% no-repeat, + linear-gradient(var(--S3), var(--S3)) right bottom / 50% 50% no-repeat, + linear-gradient(var(--S0), var(--S0)) left bottom / 50% 50% no-repeat, + var(--S1); } /* Exactly as tall as the picker (the button keeps its natural height, so the row and the @@ -1240,6 +1246,33 @@ body.WizardBody { border-radius: var(--ButtonRadius); } +/* Tooltips (JS/Tooltip.js): follow the cursor, flip to its other side at the window's edges. Outside .Container, so + not zoomed. Square unless the theme sets --TooltipRadius. Width is the text's own (max-content), so measuring it + does not depend on where it currently sits; long text wraps, and "\n" starts a new line. */ +.Tooltip { + position: fixed; + left: 0; + top: 0; + z-index: 9999; + width: max-content; + max-width: min(320px, calc(100vw - 8px)); + padding: 4px 8px; + background: var(--Card); + border: 1px solid var(--BorderLight); + border-radius: var(--TooltipRadius, 0px); + color: var(--Text); + font-family: var(--Font); + font-size: 11px; + white-space: pre-line; + pointer-events: none; + opacity: 0; + transition: opacity 0.15s; +} + +.Tooltip.Visible { + opacity: 1; +} + /* ===================================================================== THEME EXTRAS - rules only this theme has. Keep them below this line. ===================================================================== */ diff --git a/Production/RAMMIT-Stable/Src/MyCustomTheme/HTML/Index.html b/Production/RAMMIT-Stable/Src/MyCustomTheme/HTML/Index.html index 4cfcd08..9a5b0d9 100644 --- a/Production/RAMMIT-Stable/Src/MyCustomTheme/HTML/Index.html +++ b/Production/RAMMIT-Stable/Src/MyCustomTheme/HTML/Index.html @@ -39,7 +39,7 @@
-
+
Home ▼
@@ -81,12 +81,12 @@
- - - + + +
-
+
@@ -112,7 +112,7 @@
-
+
Roblox ▼
@@ -125,19 +125,19 @@
- +
- + - +
- +
diff --git a/Production/RAMMIT-Stable/Src/MyCustomTheme/HTML/Wizard.html b/Production/RAMMIT-Stable/Src/MyCustomTheme/HTML/Wizard.html index fff89a1..4f577bd 100644 --- a/Production/RAMMIT-Stable/Src/MyCustomTheme/HTML/Wizard.html +++ b/Production/RAMMIT-Stable/Src/MyCustomTheme/HTML/Wizard.html @@ -23,11 +23,11 @@
- +
-
+
Home ▼
@@ -43,8 +43,8 @@
- - + +
diff --git a/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Main.js b/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Main.js index a42dbb8..49c21fd 100644 --- a/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Main.js +++ b/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Main.js @@ -11,6 +11,7 @@ import { InitSettingsPanel, RestoreSettingsPanel } from './Settings.js'; import { InitThemePicker, LoadThemes } from './Themes.js'; import { InitTours, StartTour } from './Tours.js'; import { ShowLaunchError, ShowStatus } from './Status.js'; +import { InitTooltips } from './Tooltip.js'; function WireButtons() { ById('AddAccountBtn').addEventListener('click', () => AddAccount().catch(ReportError)); @@ -22,6 +23,7 @@ function WireButtons() { } async function Boot() { + InitTooltips(); WireButtons(); InitLaunchPanel(); InitSettingsPanel(); diff --git a/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Tooltip.js b/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Tooltip.js new file mode 100644 index 0000000..5635396 --- /dev/null +++ b/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Tooltip.js @@ -0,0 +1,66 @@ +// Themed tooltips (the CBlock tooltip), instead of the browser's own. +// Any element with data-tooltip="..." or a title="..." gets one: a title is moved into data-tooltip when hovered, +// so the native tooltip never shows and no existing title has to change. "\n" in the text starts a new line. +// Look: .Tooltip in Style.css (colours from the theme; --TooltipRadius rounds it, 0 by default). + +const OffsetX = 12, OffsetY = 16; // from the cursor +const FlipGap = 12; // from the cursor when flipped to its left / above it +let Tip = null; +let Target = null; +let LastX = 0, LastY = 0; + +// Takes over a title (also one set again later, e.g. an account's status) and returns the text to show. +function ReadText(Node) { + if (Node.hasAttribute('title')) { + Node.dataset.tooltip = Node.getAttribute('title'); + Node.removeAttribute('title'); + } + return (Node.dataset.tooltip || '').replace(/\\n/g, '\n'); +} + +// Right of / below the cursor; where that would leave the window, the other side of the cursor instead. +function Place() { + const Width = Tip.offsetWidth, Height = Tip.offsetHeight; + let X = LastX + OffsetX, Y = LastY + OffsetY; + if (X + Width > innerWidth) X = LastX - FlipGap - Width; + if (Y + Height > innerHeight) Y = LastY - FlipGap - Height; + Tip.style.left = Math.max(0, X) + 'px'; + Tip.style.top = Math.max(0, Y) + 'px'; +} + +function Show(Node) { + const Text = ReadText(Node); + if (!Text) { Hide(); return; } + Target = Node; + Tip.textContent = Text; + Place(); // before it fades in, so it never flashes where it was last time + Tip.classList.add('Visible'); +} + +function Hide() { + Target = null; + if (Tip) Tip.classList.remove('Visible'); +} + +export function InitTooltips() { + Tip = document.createElement('div'); + Tip.className = 'Tooltip'; + Tip.setAttribute('role', 'tooltip'); + document.body.append(Tip); + + document.addEventListener('mouseover', Event => { + LastX = Event.clientX; LastY = Event.clientY; + const Node = Event.target.closest('[data-tooltip], [title]'); + if (Node) Show(Node); else if (Target) Hide(); + }); + document.addEventListener('mousemove', Event => { + LastX = Event.clientX; LastY = Event.clientY; + if (!Target) return; + if (!Target.isConnected) { Hide(); return; } // re-drawn under the cursor: no mouseout ever comes + if (Target.hasAttribute('title')) Show(Target); else Place(); + }); + document.addEventListener('mouseout', Event => { if (!Event.relatedTarget) Hide(); }); // left the window + document.addEventListener('mousedown', Hide); + document.addEventListener('scroll', Hide, true); + window.addEventListener('blur', Hide); +} diff --git a/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Wizard.js b/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Wizard.js index bad69c1..9bca02a 100644 --- a/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Wizard.js +++ b/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Wizard.js @@ -11,6 +11,7 @@ import { Api, WaitForApi, ReportError } from './Bridge.js'; import { ById } from './Dom.js'; import { InitSelect, SetSelectValue, GetSelectValue } from './Select.js'; import { CreateLaunchForm, FilterMethods } from './LaunchForm.js'; +import { InitTooltips } from './Tooltip.js'; let SizeMap = { Home: 287, ExtraPadding: 20 }; let InitDone = false; @@ -60,6 +61,7 @@ ById('ConfirmBtn').addEventListener('click', async () => { }); async function Boot() { + InitTooltips(); await WaitForApi('GetWizardData'); const HeightMap = await Api.GetHeightMap().catch(() => null); if (HeightMap && HeightMap.WizardWindow) SizeMap = HeightMap.WizardWindow; diff --git a/Production/RAMMIT-Stable/Tests/TestBackend.py b/Production/RAMMIT-Stable/Tests/TestBackend.py index f5ec7b6..ace71c7 100644 --- a/Production/RAMMIT-Stable/Tests/TestBackend.py +++ b/Production/RAMMIT-Stable/Tests/TestBackend.py @@ -444,6 +444,30 @@ def test_ThemeApi(self): self.assertEqual(self.Api.GetHeightMap()["WizardWindow"]["Width"], 400) self.assertIn("Error", self.Api.UpdateSetting("Theme", "../../Config")) + def test_MainWindowOpensAtHeightMapHeight(self): + from App import Main + Map = Themes.LoadHeightMap("Dark")[0]["MainWindow"] + self.assertEqual(Main.StartHeight(self.Api), Map["Home"]) + self.Api.UpdateSettings({"LaunchOption": "Game URL", "LaunchParams": {"PlayerMode": "range"}}) + self.assertEqual(Main.StartHeight(self.Api), Map["Game URL"] + Map["PlayerFilterExtra"]) + + def test_ResizeWaitsForLetGoWhileWindowIsHeld(self): + from App import WindowSize + Window = mock.MagicMock() + Window.native = mock.Mock(Height=595, DeviceDpi=96) # 476 logical px at 125%; DeviceDpi stays 96 (pywebview) + self.Api._AttachMainWindow(Window) + Sizer = self.Api._MainSizer + Sizer._Dragging = True # title bar held: only record the height (Windows would undo a resize now) + self.Api.ResizeWindow(800) + Window.resize.assert_not_called() + with mock.patch.object(WindowSize.HeldWindow, "_SetHeight") as SetHeight, \ + mock.patch.object(WindowSize.HeldWindow, "_WindowScale", return_value=1.25): + Sizer._Dragging = False + Sizer._ReapplyHeight() # what letting go runs + SetHeight.assert_called_once_with(Window.native, round(int(800 * 0.85) * 1.25)) + self.Api.ResizeWindow(716) # not held: straight through + Window.resize.assert_called_once_with(int(900 * 0.85), int(716 * 0.85)) + def test_FindLoginCookie(self): Morsel = mock.Mock(value="tok") self.assertEqual(ApiModule.Api._FindLoginCookie([{"other": mock.Mock(value="x"), ".ROBLOSECURITY": Morsel}]), "tok") diff --git a/Production/RAMMIT-Stable/requirements.txt b/Production/RAMMIT-Stable/requirements.txt index 7303e3d..418ca92 100644 --- a/Production/RAMMIT-Stable/requirements.txt +++ b/Production/RAMMIT-Stable/requirements.txt @@ -1,4 +1,4 @@ -# Versions RAMMIT 1.1.1 was built and tested with (Python 3.13.14, Windows 11). +# Versions RAMMIT 1.1.2 was built and tested with (Python 3.13.14, Windows 11). # Runtime pywebview==6.2.1 pywin32==312 From c32cfa14a64cd5f0571203bdad0b920627bcd555 Mon Sep 17 00:00:00 2001 From: Paradox Date: Wed, 4 Nov 2026 00:25:00 +0530 Subject: [PATCH 02/11] Launch tracking: match clients to accounts by launch ticket, count only game windows A launch's one-time ticket travels in the roblox-player: link on the game client's command line, so MultiInstance.ClientTracker matches each RobloxPlayerBeta.exe to the account that launched it (tickets stay in memory, never logged). Only processes with a visible WINDOWSCLIENT window count as running, so the --launch-to-tray process a closed game leaves behind, and its tray right-click menu, no longer add an instance. The page marks an account '...' while Roblox starts, a check once its game window is open, and clears it when that window closes (GetCounter returns each account's live state). --- Production/RAMMIT-Stable/App/Api.py | 15 ++- Production/RAMMIT-Stable/App/MultiInstance.py | 113 ++++++++++++++---- Production/RAMMIT-Stable/CHANGELOG.md | 1 + .../RAMMIT-Stable/Src/CBlock/JS/Launch.js | 31 ++++- .../RAMMIT-Stable/Src/Dark/JS/Launch.js | 31 ++++- .../RAMMIT-Stable/Src/Light/JS/Launch.js | 31 ++++- .../Src/MyCustomTheme/JS/Launch.js | 31 ++++- Production/RAMMIT-Stable/Tests/TestBackend.py | 33 ++++- Production/RAMMIT-Stable/Tests/UiHarness.py | 4 +- 9 files changed, 233 insertions(+), 57 deletions(-) diff --git a/Production/RAMMIT-Stable/App/Api.py b/Production/RAMMIT-Stable/App/Api.py index 1e0e905..defad9d 100644 --- a/Production/RAMMIT-Stable/App/Api.py +++ b/Production/RAMMIT-Stable/App/Api.py @@ -32,7 +32,7 @@ def __init__(self, Server=None): self._Settings = Storage.LoadSettings() self._Configs = Storage.LoadConfigs() self._DataLock = threading.RLock() - self._TrackedPids = set() + self._Clients = MultiInstance.ClientTracker() # which running client is which account (holds launch tickets) self._Batch = self._EmptyBatch() self._MainWindow = None self._WizardWindow = None @@ -312,7 +312,7 @@ def _LaunchOne(self, Username, Option, Params): return {"Error": "Player counts must be whole numbers."} with MultiInstance.LaunchLock: - Running = MultiInstance.CountRunning(self._TrackedPids) + Running = MultiInstance.CountRunning(self._Clients) if Running >= self._Settings["MaxInstances"]: return {"Error": "Instance limit reached."} if not MultiInstance.HoldMutex() and Running > 0: @@ -339,8 +339,8 @@ def _LaunchOne(self, Username, Option, Params): LaunchUrl = Roblox.BuildLaunchUrl(Ticket, PlaceId, JobId, LinkCode) except ValueError as Error: return {"Error": str(Error)} - Proc = subprocess.Popen([Exe, LaunchUrl], creationflags=subprocess.CREATE_NO_WINDOW) - self._TrackedPids.add(Proc.pid) + self._Clients.Expect(Ticket, Account["Username"]) # before the client exists, so no scan can miss it + subprocess.Popen([Exe, LaunchUrl], creationflags=subprocess.CREATE_NO_WINDOW) Logger.info("Launched %s (%s)", Username, Option) return {"Ok": True} @@ -415,8 +415,11 @@ def GetGameMaxPlayers(self, PlaceId): return Roblox.GetGameMaxPlayers(PlaceId) if Roblox.IsPlaceId(PlaceId) else 0 def GetCounter(self): - return {"Running": MultiInstance.CountRunning(self._TrackedPids), "Max": self._Settings["MaxInstances"], - "MultiReady": MultiInstance.IsReady()} + """Running count, plus each launched account's live state: {"Accounts": {Username: "starting" / "running"}} + (a closed client's account is simply absent).""" + Running = MultiInstance.CountRunning(self._Clients) + return {"Running": Running, "Max": self._Settings["MaxInstances"], "MultiReady": MultiInstance.IsReady(), + "Accounts": self._Clients.Accounts()} # ------------------------------------------------------------ settings diff --git a/Production/RAMMIT-Stable/App/MultiInstance.py b/Production/RAMMIT-Stable/App/MultiInstance.py index 10da777..6138031 100644 --- a/Production/RAMMIT-Stable/App/MultiInstance.py +++ b/Production/RAMMIT-Stable/App/MultiInstance.py @@ -9,13 +9,18 @@ event and Windows refuses the mutex (error 6, ERROR_INVALID_HANDLE). HoldMutex() is retried before every launch; once every Roblox window is closed it succeeds. -Counting uses both libraries together: pywin32 finds visible Roblox windows, psutil confirms -the owning process and tracks clients RAMMIT just spawned (they have no window for a few -seconds - without that a batch launch would overshoot MaxInstances). +Counting and tracking (ClientTracker): a client is a RobloxPlayerBeta.exe that owns a visible +WINDOWSCLIENT window (the game). Other visible windows don't count: closing a game starts a +"--launch-to-tray" RobloxPlayerBeta that only has a tray icon, and its right-click menu is a +visible window too. Each launch's one-time ticket travels in the roblox-player: link on the +game process's command line, so matching it tells which account a client belongs to (and so +which one closed). Launches still starting (no game window for ~9 s) are counted too, or a +batch launch would overshoot MaxInstances. Tickets stay in memory and are never logged. """ import msvcrt import os import threading +import time import psutil import win32event @@ -79,36 +84,94 @@ def LockCookieFile(): return False -def _IsPlayer(Pid): - try: - Proc = psutil.Process(Pid) - return Proc.is_running() and Proc.name() == PlayerExe - except (psutil.Error, OSError): - return False +GameWindowClass = "WINDOWSCLIENT" +StartTimeout = 120 # seconds a launch may take to show up before it stops counting as "starting" + + +def _PlayerPids(): + """Pids of every RobloxPlayerBeta.exe. Names only: asking every process for more is very slow.""" + Pids = set() + for Proc in psutil.process_iter(["name"]): + if Proc.info["name"] == PlayerExe: + Pids.add(Proc.pid) + return Pids -def CountRunning(TrackedPids=None): - """Number of running Roblox clients. Prunes dead pids from TrackedPids in place.""" +def _GameWindowPids(): + """Pids that own a visible game window.""" Pids = set() def OnWindow(Hwnd, _Extra): - if win32gui.IsWindowVisible(Hwnd): - try: - _Thread, Pid = win32process.GetWindowThreadProcessId(Hwnd) - if _IsPlayer(Pid): - Pids.add(Pid) - except Exception: - pass + try: + if win32gui.IsWindowVisible(Hwnd) and win32gui.GetClassName(Hwnd) == GameWindowClass: + Pids.add(win32process.GetWindowThreadProcessId(Hwnd)[1]) + except Exception: + pass return True try: win32gui.EnumWindows(OnWindow, None) except Exception as Error: Logger.warning("EnumWindows failed: %s", Error) - if TrackedPids is not None: - for Pid in list(TrackedPids): - if _IsPlayer(Pid): - Pids.add(Pid) - else: - TrackedPids.discard(Pid) - return len(Pids) + return Pids + + +def _CommandLine(Pid): + try: + return " ".join(psutil.Process(Pid).cmdline()) + except (psutil.Error, OSError): + return "" + + +class ClientTracker: + """Which account each running Roblox client belongs to. Keep it in a _-prefixed Api attribute: it holds tickets.""" + + def __init__(self): + self._Lock = threading.Lock() + self._Expected = [] # (launch ticket, Username, time launched) per launch; dropped once matched or after StartTimeout + self._Owners = {} # player pid -> Username, or None for a client that isn't one of RAMMIT's launches + self._Last = {} # Username -> "starting" / "running", from the last Scan() + + def Expect(self, Ticket, Username): + with self._Lock: + self._Expected.append((Ticket, Username, time.monotonic())) + + def Scan(self): + """Number of running clients (game windows + launches still starting); also refreshes Accounts().""" + PlayerPids, WindowPids = _PlayerPids(), _GameWindowPids() + with self._Lock: + Now = time.monotonic() + for Pid in list(self._Owners): + if Pid not in PlayerPids: + del self._Owners[Pid] + for Pid in PlayerPids - set(self._Owners): + Line = _CommandLine(Pid) + Owner = None + for Entry in self._Expected: + if "gameinfo:" + Entry[0] in Line: + Owner = Entry[1] + self._Expected.remove(Entry) + break + if Owner or Pid in WindowPids or not Line: # tray and helper processes get looked at again later + self._Owners[Pid] = Owner + self._Expected = [Entry for Entry in self._Expected if Now - Entry[2] <= StartTimeout] + Accounts = {Username: "starting" for _Ticket, Username, _At in self._Expected} + for Pid, Username in self._Owners.items(): + if Username: + if Pid in WindowPids: + Accounts[Username] = "running" + else: + Accounts.setdefault(Username, "starting") + Starting = len(self._Expected) + sum(1 for Pid, Username in self._Owners.items() if Username and Pid not in WindowPids) + self._Last = Accounts + return len(WindowPids & PlayerPids) + Starting + + def Accounts(self): + """{Username: "starting" or "running"} for RAMMIT's own launches, as of the last Scan(). Closed ones are absent.""" + with self._Lock: + return dict(self._Last) + + +def CountRunning(Tracker=None): + """Number of running Roblox clients: processes with a visible game window, plus Tracker's launches still starting.""" + return (Tracker or ClientTracker()).Scan() diff --git a/Production/RAMMIT-Stable/CHANGELOG.md b/Production/RAMMIT-Stable/CHANGELOG.md index 9d14765..2dfd787 100644 --- a/Production/RAMMIT-Stable/CHANGELOG.md +++ b/Production/RAMMIT-Stable/CHANGELOG.md @@ -7,6 +7,7 @@ - **Installer:** pressing **Ignore** on the "older test version" screen without ticking "Don't ask again" now puts it off instead of asking every time: the menu opens as normal, with an **OLD VERSION** button and a line saying where the old version is. It stays reachable after installing the new RAMMIT, and goes away once the old version is moved or removed. - **Installer:** with RAMMIT already installed, the old version's screen keeps all four choices. The two "move my accounts" choices then copy its accounts and settings into the installed RAMMIT without reinstalling it, and the first one removes the old version afterwards. - **Installer:** the "Uninstall Config/ folder too" tick box no longer shows its check mark while unticked (#2). +- **Launch tracking:** RAMMIT now knows which Roblox client belongs to which account, by matching each launch's one-time ticket on the client's command line. An account shows "•••" while Roblox starts, "✓" only once its game window is open, and its mark clears when that window closes, so you can see which account closed. The running counter only counts real game windows: Roblox's tray process (started when a game closes) and its right-click menu no longer count as an instance. - **Tooltips:** every button and setting has a tooltip, drawn in the theme's own colours instead of the plain Windows one. It follows the cursor and flips to the other side near the window's edges. CBlock's are rounded; a custom theme can set `--TooltipRadius`. - The main window opens at its `HeightMap.json` height for the saved launch option, instead of opening shorter and resizing once the page has loaded. - The main window and the config window keep the right height when you grab or drag their title bar while they resize: the resize waits and is applied when you let go (the same fix as the installer's). diff --git a/Production/RAMMIT-Stable/Src/CBlock/JS/Launch.js b/Production/RAMMIT-Stable/Src/CBlock/JS/Launch.js index 6bce60c..56bcbde 100644 --- a/Production/RAMMIT-Stable/Src/CBlock/JS/Launch.js +++ b/Production/RAMMIT-Stable/Src/CBlock/JS/Launch.js @@ -56,8 +56,8 @@ async function LaunchSelected() { const Names = SelectedInListOrder(); if (!Names.length) { ShowLaunchError('No account selected.'); return; } SetLaunchStatus(Names.length > 1 ? `Launching 1 / ${Names.length}...` : 'Launching...'); - State.AccountStatus = {}; - ApplyAccountStatus(); + LastResults = {}; + RenderAccountStatus(); const Option = GetSelectValue(ById('LaunchOptionSelect')); const Result = await Api.LaunchAccounts(Names, Option, Form.GetParams(), State.SelectedConfig); if (Result && Result.Error) { ShowLaunchError(Result.Error); return; } @@ -87,19 +87,36 @@ function SetBatchRunning(Running) { else ApplySelection(); } +// Row marks come from two places: the batch's results (queued / launching / skipped / error) and, once an account's +// launch went through, its client's live state from GetCounter (App/MultiInstance.ClientTracker): "•••" while Roblox +// starts, "✓" once its game window is open, nothing again once that window closes. const StatusCells = { - ok: { State: 'Ok', Text: '✓' }, launching: { State: 'Launching', Text: '•••' }, + launching: { State: 'Launching', Text: '•••' }, queued: { State: 'Queued', Text: '…' }, skipped: { State: 'Queued', Text: '–' }, }; +const LiveCells = { + starting: { State: 'Launching', Text: '•••', Title: 'Roblox is starting' }, + running: { State: 'Ok', Text: '✓', Title: 'Open in Roblox' }, +}; +let LastResults = {}; // username -> the batch's result for it +let LiveAccounts = {}; // username -> "starting" / "running" -function ApplyProgress(Progress) { +function RenderAccountStatus() { State.AccountStatus = {}; - Object.entries(Progress.Results || {}).forEach(([Name, Value]) => { + Object.entries(LastResults).forEach(([Name, Value]) => { const Text = String(Value); - if (StatusCells[Text]) State.AccountStatus[Name] = StatusCells[Text]; + if (Text === 'ok') { // launched: the live state decides; until the first counter tick, it's starting + if (State.BatchRunning) State.AccountStatus[Name] = LiveCells.starting; + } else if (StatusCells[Text]) State.AccountStatus[Name] = StatusCells[Text]; else if (Text.startsWith('error:')) State.AccountStatus[Name] = { State: 'Error', Text: '✗', Title: Text.slice(6) }; }); + Object.entries(LiveAccounts).forEach(([Name, Live]) => { if (LiveCells[Live]) State.AccountStatus[Name] = LiveCells[Live]; }); ApplyAccountStatus(); +} + +function ApplyProgress(Progress) { + LastResults = Progress.Results || {}; + RenderAccountStatus(); if (Progress.Running) SetLaunchStatus(`Launching ${Math.min(Progress.Done + 1, Progress.Total)} / ${Progress.Total}...`); } @@ -126,6 +143,8 @@ export async function UpdateCounter() { Label.textContent = `RUNNING: ${Counter.Running} / ${Counter.Max}` + (Counter.MultiReady === false ? ' ⚠' : ''); Label.title = Counter.MultiReady === false ? 'Roblox was already open when RAMMIT started, so only one client can run. Close every Roblox window and RAMMIT will take over on the next launch.' : ''; + LiveAccounts = Counter.Accounts || {}; + RenderAccountStatus(); } catch (_) { /* backend busy - next tick */ } } diff --git a/Production/RAMMIT-Stable/Src/Dark/JS/Launch.js b/Production/RAMMIT-Stable/Src/Dark/JS/Launch.js index 6bce60c..56bcbde 100644 --- a/Production/RAMMIT-Stable/Src/Dark/JS/Launch.js +++ b/Production/RAMMIT-Stable/Src/Dark/JS/Launch.js @@ -56,8 +56,8 @@ async function LaunchSelected() { const Names = SelectedInListOrder(); if (!Names.length) { ShowLaunchError('No account selected.'); return; } SetLaunchStatus(Names.length > 1 ? `Launching 1 / ${Names.length}...` : 'Launching...'); - State.AccountStatus = {}; - ApplyAccountStatus(); + LastResults = {}; + RenderAccountStatus(); const Option = GetSelectValue(ById('LaunchOptionSelect')); const Result = await Api.LaunchAccounts(Names, Option, Form.GetParams(), State.SelectedConfig); if (Result && Result.Error) { ShowLaunchError(Result.Error); return; } @@ -87,19 +87,36 @@ function SetBatchRunning(Running) { else ApplySelection(); } +// Row marks come from two places: the batch's results (queued / launching / skipped / error) and, once an account's +// launch went through, its client's live state from GetCounter (App/MultiInstance.ClientTracker): "•••" while Roblox +// starts, "✓" once its game window is open, nothing again once that window closes. const StatusCells = { - ok: { State: 'Ok', Text: '✓' }, launching: { State: 'Launching', Text: '•••' }, + launching: { State: 'Launching', Text: '•••' }, queued: { State: 'Queued', Text: '…' }, skipped: { State: 'Queued', Text: '–' }, }; +const LiveCells = { + starting: { State: 'Launching', Text: '•••', Title: 'Roblox is starting' }, + running: { State: 'Ok', Text: '✓', Title: 'Open in Roblox' }, +}; +let LastResults = {}; // username -> the batch's result for it +let LiveAccounts = {}; // username -> "starting" / "running" -function ApplyProgress(Progress) { +function RenderAccountStatus() { State.AccountStatus = {}; - Object.entries(Progress.Results || {}).forEach(([Name, Value]) => { + Object.entries(LastResults).forEach(([Name, Value]) => { const Text = String(Value); - if (StatusCells[Text]) State.AccountStatus[Name] = StatusCells[Text]; + if (Text === 'ok') { // launched: the live state decides; until the first counter tick, it's starting + if (State.BatchRunning) State.AccountStatus[Name] = LiveCells.starting; + } else if (StatusCells[Text]) State.AccountStatus[Name] = StatusCells[Text]; else if (Text.startsWith('error:')) State.AccountStatus[Name] = { State: 'Error', Text: '✗', Title: Text.slice(6) }; }); + Object.entries(LiveAccounts).forEach(([Name, Live]) => { if (LiveCells[Live]) State.AccountStatus[Name] = LiveCells[Live]; }); ApplyAccountStatus(); +} + +function ApplyProgress(Progress) { + LastResults = Progress.Results || {}; + RenderAccountStatus(); if (Progress.Running) SetLaunchStatus(`Launching ${Math.min(Progress.Done + 1, Progress.Total)} / ${Progress.Total}...`); } @@ -126,6 +143,8 @@ export async function UpdateCounter() { Label.textContent = `RUNNING: ${Counter.Running} / ${Counter.Max}` + (Counter.MultiReady === false ? ' ⚠' : ''); Label.title = Counter.MultiReady === false ? 'Roblox was already open when RAMMIT started, so only one client can run. Close every Roblox window and RAMMIT will take over on the next launch.' : ''; + LiveAccounts = Counter.Accounts || {}; + RenderAccountStatus(); } catch (_) { /* backend busy - next tick */ } } diff --git a/Production/RAMMIT-Stable/Src/Light/JS/Launch.js b/Production/RAMMIT-Stable/Src/Light/JS/Launch.js index 6bce60c..56bcbde 100644 --- a/Production/RAMMIT-Stable/Src/Light/JS/Launch.js +++ b/Production/RAMMIT-Stable/Src/Light/JS/Launch.js @@ -56,8 +56,8 @@ async function LaunchSelected() { const Names = SelectedInListOrder(); if (!Names.length) { ShowLaunchError('No account selected.'); return; } SetLaunchStatus(Names.length > 1 ? `Launching 1 / ${Names.length}...` : 'Launching...'); - State.AccountStatus = {}; - ApplyAccountStatus(); + LastResults = {}; + RenderAccountStatus(); const Option = GetSelectValue(ById('LaunchOptionSelect')); const Result = await Api.LaunchAccounts(Names, Option, Form.GetParams(), State.SelectedConfig); if (Result && Result.Error) { ShowLaunchError(Result.Error); return; } @@ -87,19 +87,36 @@ function SetBatchRunning(Running) { else ApplySelection(); } +// Row marks come from two places: the batch's results (queued / launching / skipped / error) and, once an account's +// launch went through, its client's live state from GetCounter (App/MultiInstance.ClientTracker): "•••" while Roblox +// starts, "✓" once its game window is open, nothing again once that window closes. const StatusCells = { - ok: { State: 'Ok', Text: '✓' }, launching: { State: 'Launching', Text: '•••' }, + launching: { State: 'Launching', Text: '•••' }, queued: { State: 'Queued', Text: '…' }, skipped: { State: 'Queued', Text: '–' }, }; +const LiveCells = { + starting: { State: 'Launching', Text: '•••', Title: 'Roblox is starting' }, + running: { State: 'Ok', Text: '✓', Title: 'Open in Roblox' }, +}; +let LastResults = {}; // username -> the batch's result for it +let LiveAccounts = {}; // username -> "starting" / "running" -function ApplyProgress(Progress) { +function RenderAccountStatus() { State.AccountStatus = {}; - Object.entries(Progress.Results || {}).forEach(([Name, Value]) => { + Object.entries(LastResults).forEach(([Name, Value]) => { const Text = String(Value); - if (StatusCells[Text]) State.AccountStatus[Name] = StatusCells[Text]; + if (Text === 'ok') { // launched: the live state decides; until the first counter tick, it's starting + if (State.BatchRunning) State.AccountStatus[Name] = LiveCells.starting; + } else if (StatusCells[Text]) State.AccountStatus[Name] = StatusCells[Text]; else if (Text.startsWith('error:')) State.AccountStatus[Name] = { State: 'Error', Text: '✗', Title: Text.slice(6) }; }); + Object.entries(LiveAccounts).forEach(([Name, Live]) => { if (LiveCells[Live]) State.AccountStatus[Name] = LiveCells[Live]; }); ApplyAccountStatus(); +} + +function ApplyProgress(Progress) { + LastResults = Progress.Results || {}; + RenderAccountStatus(); if (Progress.Running) SetLaunchStatus(`Launching ${Math.min(Progress.Done + 1, Progress.Total)} / ${Progress.Total}...`); } @@ -126,6 +143,8 @@ export async function UpdateCounter() { Label.textContent = `RUNNING: ${Counter.Running} / ${Counter.Max}` + (Counter.MultiReady === false ? ' ⚠' : ''); Label.title = Counter.MultiReady === false ? 'Roblox was already open when RAMMIT started, so only one client can run. Close every Roblox window and RAMMIT will take over on the next launch.' : ''; + LiveAccounts = Counter.Accounts || {}; + RenderAccountStatus(); } catch (_) { /* backend busy - next tick */ } } diff --git a/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Launch.js b/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Launch.js index 6bce60c..56bcbde 100644 --- a/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Launch.js +++ b/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Launch.js @@ -56,8 +56,8 @@ async function LaunchSelected() { const Names = SelectedInListOrder(); if (!Names.length) { ShowLaunchError('No account selected.'); return; } SetLaunchStatus(Names.length > 1 ? `Launching 1 / ${Names.length}...` : 'Launching...'); - State.AccountStatus = {}; - ApplyAccountStatus(); + LastResults = {}; + RenderAccountStatus(); const Option = GetSelectValue(ById('LaunchOptionSelect')); const Result = await Api.LaunchAccounts(Names, Option, Form.GetParams(), State.SelectedConfig); if (Result && Result.Error) { ShowLaunchError(Result.Error); return; } @@ -87,19 +87,36 @@ function SetBatchRunning(Running) { else ApplySelection(); } +// Row marks come from two places: the batch's results (queued / launching / skipped / error) and, once an account's +// launch went through, its client's live state from GetCounter (App/MultiInstance.ClientTracker): "•••" while Roblox +// starts, "✓" once its game window is open, nothing again once that window closes. const StatusCells = { - ok: { State: 'Ok', Text: '✓' }, launching: { State: 'Launching', Text: '•••' }, + launching: { State: 'Launching', Text: '•••' }, queued: { State: 'Queued', Text: '…' }, skipped: { State: 'Queued', Text: '–' }, }; +const LiveCells = { + starting: { State: 'Launching', Text: '•••', Title: 'Roblox is starting' }, + running: { State: 'Ok', Text: '✓', Title: 'Open in Roblox' }, +}; +let LastResults = {}; // username -> the batch's result for it +let LiveAccounts = {}; // username -> "starting" / "running" -function ApplyProgress(Progress) { +function RenderAccountStatus() { State.AccountStatus = {}; - Object.entries(Progress.Results || {}).forEach(([Name, Value]) => { + Object.entries(LastResults).forEach(([Name, Value]) => { const Text = String(Value); - if (StatusCells[Text]) State.AccountStatus[Name] = StatusCells[Text]; + if (Text === 'ok') { // launched: the live state decides; until the first counter tick, it's starting + if (State.BatchRunning) State.AccountStatus[Name] = LiveCells.starting; + } else if (StatusCells[Text]) State.AccountStatus[Name] = StatusCells[Text]; else if (Text.startsWith('error:')) State.AccountStatus[Name] = { State: 'Error', Text: '✗', Title: Text.slice(6) }; }); + Object.entries(LiveAccounts).forEach(([Name, Live]) => { if (LiveCells[Live]) State.AccountStatus[Name] = LiveCells[Live]; }); ApplyAccountStatus(); +} + +function ApplyProgress(Progress) { + LastResults = Progress.Results || {}; + RenderAccountStatus(); if (Progress.Running) SetLaunchStatus(`Launching ${Math.min(Progress.Done + 1, Progress.Total)} / ${Progress.Total}...`); } @@ -126,6 +143,8 @@ export async function UpdateCounter() { Label.textContent = `RUNNING: ${Counter.Running} / ${Counter.Max}` + (Counter.MultiReady === false ? ' ⚠' : ''); Label.title = Counter.MultiReady === false ? 'Roblox was already open when RAMMIT started, so only one client can run. Close every Roblox window and RAMMIT will take over on the next launch.' : ''; + LiveAccounts = Counter.Accounts || {}; + RenderAccountStatus(); } catch (_) { /* backend busy - next tick */ } } diff --git a/Production/RAMMIT-Stable/Tests/TestBackend.py b/Production/RAMMIT-Stable/Tests/TestBackend.py index ace71c7..c15d99a 100644 --- a/Production/RAMMIT-Stable/Tests/TestBackend.py +++ b/Production/RAMMIT-Stable/Tests/TestBackend.py @@ -410,7 +410,38 @@ def test_LaunchOneHappyPath(self): Args = Popen.call_args[0][0] self.assertEqual(Args[0], "C:\\R.exe") self.assertIn("placeId=123", Args[1]) - self.assertIn(4242, self.Api._TrackedPids) + self.assertEqual([Name for _Ticket, Name, _At in self.Api._Clients._Expected], ["B"]) # waiting for its client + + def test_ClientTrackerMatchesClientsToAccountsByTicket(self): + from App import MultiInstance + Tracker = MultiInstance.ClientTracker() + Tracker.Expect("TICKETA", "A") + Tracker.Expect("TICKETB", "B") + Lines = {10: "RobloxPlayerBeta.exe roblox-player:1+launchmode:play+gameinfo:TICKETA+launchtime:1", + 11: "RobloxPlayerBeta.exe roblox-player:1+launchmode:play+gameinfo:TICKETB+launchtime:2", + 12: "RobloxPlayerBeta.exe --launch-to-tray"} # a closed game's tray process: no ticket, never counted + + def Scan(Players, Windows): + with mock.patch.object(MultiInstance, "_PlayerPids", return_value=set(Players)), \ + mock.patch.object(MultiInstance, "_GameWindowPids", return_value=set(Windows)), \ + mock.patch.object(MultiInstance, "_CommandLine", side_effect=lambda Pid: Lines[Pid]): + return Tracker.Scan(), Tracker.Accounts() + + self.assertEqual(Scan([], []), (2, {"A": "starting", "B": "starting"})) # launched, no client yet + self.assertEqual(Scan([10, 11], [10]), (2, {"A": "running", "B": "starting"})) # B's window not shown yet + self.assertEqual(Scan([10, 11], [10, 11]), (2, {"A": "running", "B": "running"})) + self.assertEqual(Scan([11, 12], [11]), (1, {"B": "running"})) # A closed: its game window and process are gone + self.assertEqual(Scan([12], []), (0, {})) + + def test_OnlyGameWindowsCount(self): + # Roblox's tray right-click menu (SystrayContextMenu) is a visible window too, and a hidden game window isn't open yet. + from App import MultiInstance + Windows = {1: ("WINDOWSCLIENT", True, 11), 2: ("SystrayContextMenu", True, 12), 3: ("WINDOWSCLIENT", False, 13)} + with mock.patch.object(MultiInstance.win32gui, "EnumWindows", side_effect=lambda Fn, _X: [Fn(H, None) for H in Windows]), \ + mock.patch.object(MultiInstance.win32gui, "IsWindowVisible", side_effect=lambda H: Windows[H][1]), \ + mock.patch.object(MultiInstance.win32gui, "GetClassName", side_effect=lambda H: Windows[H][0]), \ + mock.patch.object(MultiInstance.win32process, "GetWindowThreadProcessId", side_effect=lambda H: (0, Windows[H][2])): + self.assertEqual(MultiInstance._GameWindowPids(), {11}) def test_RobloxAlreadyRunningGivesClearError(self): self.Api._Settings["MaxInstances"] = 5 diff --git a/Production/RAMMIT-Stable/Tests/UiHarness.py b/Production/RAMMIT-Stable/Tests/UiHarness.py index 079fe4f..9357ba4 100644 --- a/Production/RAMMIT-Stable/Tests/UiHarness.py +++ b/Production/RAMMIT-Stable/Tests/UiHarness.py @@ -89,7 +89,9 @@ def FakePopen(Args, **_Kw): ApiModule.webview.create_window = FakeWindow ApiModule.subprocess = types.SimpleNamespace(Popen=FakePopen, CREATE_NO_WINDOW=0) MultiInstance.Enable = MultiInstance.LockCookieFile = MultiInstance.HoldMutex = MultiInstance.IsReady = lambda: True -MultiInstance.CountRunning = lambda _Pids=None: Fake["Running"] +MultiInstance.CountRunning = lambda _Tracker=None: Fake["Running"] +# No real clients here: every account RAMMIT launched counts as open (its row shows the running mark). +MultiInstance.ClientTracker.Accounts = lambda Self: {Name: "running" for _Ticket, Name, _At in Self._Expected} Roblox.GetAuthTicket = lambda _Cookie: "FAKETICKET0123" Roblox.FindLauncherPath = lambda _L: r"C:\Fake\RobloxPlayerBeta.exe" Roblox.FetchServers = lambda _P, _C=None, MaxPages=10: [dict(S) for S in FakeServers] From d0915934abfe55032a670661395da487c693780a Mon Sep 17 00:00:00 2001 From: Paradox Date: Wed, 4 Nov 2026 00:43:23 +0530 Subject: [PATCH 03/11] Launch status: counter label shows open game windows, 'Launched' waits for the windows GetCounter's Running now counts open game windows only; launches still starting still count towards Max Instances (CountRunning IncludeStarting). The status line says 'Launched X/Y' only once those accounts' windows are open: during a batch it shows 'Launched' in the launch delay after an account whose window is already open, otherwise 'Launching X / Y...'; after the last launch it waits for the windows, giving up after 30 s. --- Production/RAMMIT-Stable/App/Api.py | 2 +- Production/RAMMIT-Stable/App/MultiInstance.py | 14 ++++--- Production/RAMMIT-Stable/CHANGELOG.md | 2 +- .../RAMMIT-Stable/Src/CBlock/JS/Launch.js | 40 +++++++++++++++++-- .../RAMMIT-Stable/Src/Dark/JS/Launch.js | 40 +++++++++++++++++-- .../RAMMIT-Stable/Src/Light/JS/Launch.js | 40 +++++++++++++++++-- .../Src/MyCustomTheme/JS/Launch.js | 40 +++++++++++++++++-- Production/RAMMIT-Stable/Tests/TestBackend.py | 7 ++-- Production/RAMMIT-Stable/Tests/UiHarness.py | 2 +- 9 files changed, 163 insertions(+), 24 deletions(-) diff --git a/Production/RAMMIT-Stable/App/Api.py b/Production/RAMMIT-Stable/App/Api.py index defad9d..00a07fa 100644 --- a/Production/RAMMIT-Stable/App/Api.py +++ b/Production/RAMMIT-Stable/App/Api.py @@ -417,7 +417,7 @@ def GetGameMaxPlayers(self, PlaceId): def GetCounter(self): """Running count, plus each launched account's live state: {"Accounts": {Username: "starting" / "running"}} (a closed client's account is simply absent).""" - Running = MultiInstance.CountRunning(self._Clients) + Running = MultiInstance.CountRunning(self._Clients, IncludeStarting=False) # the label: open game windows only return {"Running": Running, "Max": self._Settings["MaxInstances"], "MultiReady": MultiInstance.IsReady(), "Accounts": self._Clients.Accounts()} diff --git a/Production/RAMMIT-Stable/App/MultiInstance.py b/Production/RAMMIT-Stable/App/MultiInstance.py index 6138031..e833af8 100644 --- a/Production/RAMMIT-Stable/App/MultiInstance.py +++ b/Production/RAMMIT-Stable/App/MultiInstance.py @@ -136,8 +136,9 @@ def Expect(self, Ticket, Username): with self._Lock: self._Expected.append((Ticket, Username, time.monotonic())) - def Scan(self): - """Number of running clients (game windows + launches still starting); also refreshes Accounts().""" + def Scan(self, IncludeStarting=True): + """Number of running clients: game windows, plus launches still starting unless IncludeStarting is False (the + instance limit counts them, so a batch can't overshoot; the counter label doesn't). Also refreshes Accounts().""" PlayerPids, WindowPids = _PlayerPids(), _GameWindowPids() with self._Lock: Now = time.monotonic() @@ -164,7 +165,7 @@ def Scan(self): Accounts.setdefault(Username, "starting") Starting = len(self._Expected) + sum(1 for Pid, Username in self._Owners.items() if Username and Pid not in WindowPids) self._Last = Accounts - return len(WindowPids & PlayerPids) + Starting + return len(WindowPids & PlayerPids) + (Starting if IncludeStarting else 0) def Accounts(self): """{Username: "starting" or "running"} for RAMMIT's own launches, as of the last Scan(). Closed ones are absent.""" @@ -172,6 +173,7 @@ def Accounts(self): return dict(self._Last) -def CountRunning(Tracker=None): - """Number of running Roblox clients: processes with a visible game window, plus Tracker's launches still starting.""" - return (Tracker or ClientTracker()).Scan() +def CountRunning(Tracker=None, IncludeStarting=True): + """Number of running Roblox clients: processes with a visible game window, plus (unless IncludeStarting is False) + Tracker's launches still starting.""" + return (Tracker or ClientTracker()).Scan(IncludeStarting) diff --git a/Production/RAMMIT-Stable/CHANGELOG.md b/Production/RAMMIT-Stable/CHANGELOG.md index 2dfd787..eead19f 100644 --- a/Production/RAMMIT-Stable/CHANGELOG.md +++ b/Production/RAMMIT-Stable/CHANGELOG.md @@ -7,7 +7,7 @@ - **Installer:** pressing **Ignore** on the "older test version" screen without ticking "Don't ask again" now puts it off instead of asking every time: the menu opens as normal, with an **OLD VERSION** button and a line saying where the old version is. It stays reachable after installing the new RAMMIT, and goes away once the old version is moved or removed. - **Installer:** with RAMMIT already installed, the old version's screen keeps all four choices. The two "move my accounts" choices then copy its accounts and settings into the installed RAMMIT without reinstalling it, and the first one removes the old version afterwards. - **Installer:** the "Uninstall Config/ folder too" tick box no longer shows its check mark while unticked (#2). -- **Launch tracking:** RAMMIT now knows which Roblox client belongs to which account, by matching each launch's one-time ticket on the client's command line. An account shows "•••" while Roblox starts, "✓" only once its game window is open, and its mark clears when that window closes, so you can see which account closed. The running counter only counts real game windows: Roblox's tray process (started when a game closes) and its right-click menu no longer count as an instance. +- **Launch tracking:** RAMMIT now knows which Roblox client belongs to which account, by matching each launch's one-time ticket on the client's command line. An account shows "•••" while Roblox starts, "✓" only once its game window is open, and its mark clears when that window closes, so you can see which account closed. The running counter only counts open game windows: launches still starting count only towards Max Instances, and Roblox's tray process (started when a game closes) and its right-click menu no longer count at all. The status line under the launch button only says "Launched" once the accounts' windows are open (it stops waiting after 30 seconds). - **Tooltips:** every button and setting has a tooltip, drawn in the theme's own colours instead of the plain Windows one. It follows the cursor and flips to the other side near the window's edges. CBlock's are rounded; a custom theme can set `--TooltipRadius`. - The main window opens at its `HeightMap.json` height for the saved launch option, instead of opening shorter and resizing once the page has loaded. - The main window and the config window keep the right height when you grab or drag their title bar while they resize: the resize waits and is applied when you let go (the same fix as the installer's). diff --git a/Production/RAMMIT-Stable/Src/CBlock/JS/Launch.js b/Production/RAMMIT-Stable/Src/CBlock/JS/Launch.js index 56bcbde..4bcdd8b 100644 --- a/Production/RAMMIT-Stable/Src/CBlock/JS/Launch.js +++ b/Production/RAMMIT-Stable/Src/CBlock/JS/Launch.js @@ -56,6 +56,8 @@ async function LaunchSelected() { const Names = SelectedInListOrder(); if (!Names.length) { ShowLaunchError('No account selected.'); return; } SetLaunchStatus(Names.length > 1 ? `Launching 1 / ${Names.length}...` : 'Launching...'); + Waiting = null; + LastProgress = null; LastResults = {}; RenderAccountStatus(); const Option = GetSelectValue(ById('LaunchOptionSelect')); @@ -114,14 +116,44 @@ function RenderAccountStatus() { ApplyAccountStatus(); } +// The status line only says "Launched" once the game windows are open (as RAMMIT's earlier test builds did): while an account +// is being launched, or its window isn't open yet, it says "Launching X / Y..."; in the launch delay after an account +// whose window is already open, "Launched X/Y". After the last launch it waits for the windows, then ShowLaunchDone +// (which clears itself); it gives up waiting after WindowWait. +const WindowWait = 30000; +let LastProgress = null; +let Waiting = null; // { Names, Ok, Total, Since } after a batch, until its windows are open + +const IsOpen = Name => LiveAccounts[Name] === 'running'; + +function BatchStatusText(Progress) { + const Results = Progress.Results || {}; + if (Object.values(Results).includes('launching')) return `Launching ${Math.min(Progress.Done + 1, Progress.Total)} / ${Progress.Total}...`; + const Last = Object.keys(Results).filter(Name => Results[Name] === 'ok').pop(); + return Last && IsOpen(Last) ? `Launched ${Progress.Done}/${Progress.Total}` : `Launching ${Progress.Done} / ${Progress.Total}...`; +} + +function RenderLaunchStatus() { + if (State.BatchRunning && LastProgress) { SetLaunchStatus(BatchStatusText(LastProgress)); return; } + if (!Waiting) return; + if (Waiting.Names.every(IsOpen) || Date.now() - Waiting.Since > WindowWait) { + ShowLaunchDone(`Launched ${Waiting.Ok}/${Waiting.Total}`); + Waiting = null; + } else { + SetLaunchStatus(`Launching ${Waiting.Total} / ${Waiting.Total}...`); + } +} + function ApplyProgress(Progress) { LastResults = Progress.Results || {}; + LastProgress = Progress; RenderAccountStatus(); - if (Progress.Running) SetLaunchStatus(`Launching ${Math.min(Progress.Done + 1, Progress.Total)} / ${Progress.Total}...`); + if (Progress.Running) RenderLaunchStatus(); } function FinishBatch(Progress) { - const Values = Object.values(Progress.Results || {}).map(String); + const Results = Progress.Results || {}; + const Values = Object.values(Results).map(String); const Ok = Values.filter(V => V === 'ok').length; const Errors = Values.filter(V => V.startsWith('error:')); if (Errors.length || Progress.Message) { @@ -130,7 +162,8 @@ function FinishBatch(Progress) { if (Errors.length) Text += ` — ${Errors.length} failed: ${Errors[0].slice(6)}`; ShowLaunchError(Text); } else { - ShowLaunchDone(`Launched ${Ok}/${Progress.Total}`); + Waiting = { Names: Object.keys(Results).filter(Name => Results[Name] === 'ok'), Ok, Total: Progress.Total, Since: Date.now() }; + RenderLaunchStatus(); } UpdateCounter(); } @@ -145,6 +178,7 @@ export async function UpdateCounter() { ? 'Roblox was already open when RAMMIT started, so only one client can run. Close every Roblox window and RAMMIT will take over on the next launch.' : ''; LiveAccounts = Counter.Accounts || {}; RenderAccountStatus(); + RenderLaunchStatus(); } catch (_) { /* backend busy - next tick */ } } diff --git a/Production/RAMMIT-Stable/Src/Dark/JS/Launch.js b/Production/RAMMIT-Stable/Src/Dark/JS/Launch.js index 56bcbde..4bcdd8b 100644 --- a/Production/RAMMIT-Stable/Src/Dark/JS/Launch.js +++ b/Production/RAMMIT-Stable/Src/Dark/JS/Launch.js @@ -56,6 +56,8 @@ async function LaunchSelected() { const Names = SelectedInListOrder(); if (!Names.length) { ShowLaunchError('No account selected.'); return; } SetLaunchStatus(Names.length > 1 ? `Launching 1 / ${Names.length}...` : 'Launching...'); + Waiting = null; + LastProgress = null; LastResults = {}; RenderAccountStatus(); const Option = GetSelectValue(ById('LaunchOptionSelect')); @@ -114,14 +116,44 @@ function RenderAccountStatus() { ApplyAccountStatus(); } +// The status line only says "Launched" once the game windows are open (as RAMMIT's earlier test builds did): while an account +// is being launched, or its window isn't open yet, it says "Launching X / Y..."; in the launch delay after an account +// whose window is already open, "Launched X/Y". After the last launch it waits for the windows, then ShowLaunchDone +// (which clears itself); it gives up waiting after WindowWait. +const WindowWait = 30000; +let LastProgress = null; +let Waiting = null; // { Names, Ok, Total, Since } after a batch, until its windows are open + +const IsOpen = Name => LiveAccounts[Name] === 'running'; + +function BatchStatusText(Progress) { + const Results = Progress.Results || {}; + if (Object.values(Results).includes('launching')) return `Launching ${Math.min(Progress.Done + 1, Progress.Total)} / ${Progress.Total}...`; + const Last = Object.keys(Results).filter(Name => Results[Name] === 'ok').pop(); + return Last && IsOpen(Last) ? `Launched ${Progress.Done}/${Progress.Total}` : `Launching ${Progress.Done} / ${Progress.Total}...`; +} + +function RenderLaunchStatus() { + if (State.BatchRunning && LastProgress) { SetLaunchStatus(BatchStatusText(LastProgress)); return; } + if (!Waiting) return; + if (Waiting.Names.every(IsOpen) || Date.now() - Waiting.Since > WindowWait) { + ShowLaunchDone(`Launched ${Waiting.Ok}/${Waiting.Total}`); + Waiting = null; + } else { + SetLaunchStatus(`Launching ${Waiting.Total} / ${Waiting.Total}...`); + } +} + function ApplyProgress(Progress) { LastResults = Progress.Results || {}; + LastProgress = Progress; RenderAccountStatus(); - if (Progress.Running) SetLaunchStatus(`Launching ${Math.min(Progress.Done + 1, Progress.Total)} / ${Progress.Total}...`); + if (Progress.Running) RenderLaunchStatus(); } function FinishBatch(Progress) { - const Values = Object.values(Progress.Results || {}).map(String); + const Results = Progress.Results || {}; + const Values = Object.values(Results).map(String); const Ok = Values.filter(V => V === 'ok').length; const Errors = Values.filter(V => V.startsWith('error:')); if (Errors.length || Progress.Message) { @@ -130,7 +162,8 @@ function FinishBatch(Progress) { if (Errors.length) Text += ` — ${Errors.length} failed: ${Errors[0].slice(6)}`; ShowLaunchError(Text); } else { - ShowLaunchDone(`Launched ${Ok}/${Progress.Total}`); + Waiting = { Names: Object.keys(Results).filter(Name => Results[Name] === 'ok'), Ok, Total: Progress.Total, Since: Date.now() }; + RenderLaunchStatus(); } UpdateCounter(); } @@ -145,6 +178,7 @@ export async function UpdateCounter() { ? 'Roblox was already open when RAMMIT started, so only one client can run. Close every Roblox window and RAMMIT will take over on the next launch.' : ''; LiveAccounts = Counter.Accounts || {}; RenderAccountStatus(); + RenderLaunchStatus(); } catch (_) { /* backend busy - next tick */ } } diff --git a/Production/RAMMIT-Stable/Src/Light/JS/Launch.js b/Production/RAMMIT-Stable/Src/Light/JS/Launch.js index 56bcbde..4bcdd8b 100644 --- a/Production/RAMMIT-Stable/Src/Light/JS/Launch.js +++ b/Production/RAMMIT-Stable/Src/Light/JS/Launch.js @@ -56,6 +56,8 @@ async function LaunchSelected() { const Names = SelectedInListOrder(); if (!Names.length) { ShowLaunchError('No account selected.'); return; } SetLaunchStatus(Names.length > 1 ? `Launching 1 / ${Names.length}...` : 'Launching...'); + Waiting = null; + LastProgress = null; LastResults = {}; RenderAccountStatus(); const Option = GetSelectValue(ById('LaunchOptionSelect')); @@ -114,14 +116,44 @@ function RenderAccountStatus() { ApplyAccountStatus(); } +// The status line only says "Launched" once the game windows are open (as RAMMIT's earlier test builds did): while an account +// is being launched, or its window isn't open yet, it says "Launching X / Y..."; in the launch delay after an account +// whose window is already open, "Launched X/Y". After the last launch it waits for the windows, then ShowLaunchDone +// (which clears itself); it gives up waiting after WindowWait. +const WindowWait = 30000; +let LastProgress = null; +let Waiting = null; // { Names, Ok, Total, Since } after a batch, until its windows are open + +const IsOpen = Name => LiveAccounts[Name] === 'running'; + +function BatchStatusText(Progress) { + const Results = Progress.Results || {}; + if (Object.values(Results).includes('launching')) return `Launching ${Math.min(Progress.Done + 1, Progress.Total)} / ${Progress.Total}...`; + const Last = Object.keys(Results).filter(Name => Results[Name] === 'ok').pop(); + return Last && IsOpen(Last) ? `Launched ${Progress.Done}/${Progress.Total}` : `Launching ${Progress.Done} / ${Progress.Total}...`; +} + +function RenderLaunchStatus() { + if (State.BatchRunning && LastProgress) { SetLaunchStatus(BatchStatusText(LastProgress)); return; } + if (!Waiting) return; + if (Waiting.Names.every(IsOpen) || Date.now() - Waiting.Since > WindowWait) { + ShowLaunchDone(`Launched ${Waiting.Ok}/${Waiting.Total}`); + Waiting = null; + } else { + SetLaunchStatus(`Launching ${Waiting.Total} / ${Waiting.Total}...`); + } +} + function ApplyProgress(Progress) { LastResults = Progress.Results || {}; + LastProgress = Progress; RenderAccountStatus(); - if (Progress.Running) SetLaunchStatus(`Launching ${Math.min(Progress.Done + 1, Progress.Total)} / ${Progress.Total}...`); + if (Progress.Running) RenderLaunchStatus(); } function FinishBatch(Progress) { - const Values = Object.values(Progress.Results || {}).map(String); + const Results = Progress.Results || {}; + const Values = Object.values(Results).map(String); const Ok = Values.filter(V => V === 'ok').length; const Errors = Values.filter(V => V.startsWith('error:')); if (Errors.length || Progress.Message) { @@ -130,7 +162,8 @@ function FinishBatch(Progress) { if (Errors.length) Text += ` — ${Errors.length} failed: ${Errors[0].slice(6)}`; ShowLaunchError(Text); } else { - ShowLaunchDone(`Launched ${Ok}/${Progress.Total}`); + Waiting = { Names: Object.keys(Results).filter(Name => Results[Name] === 'ok'), Ok, Total: Progress.Total, Since: Date.now() }; + RenderLaunchStatus(); } UpdateCounter(); } @@ -145,6 +178,7 @@ export async function UpdateCounter() { ? 'Roblox was already open when RAMMIT started, so only one client can run. Close every Roblox window and RAMMIT will take over on the next launch.' : ''; LiveAccounts = Counter.Accounts || {}; RenderAccountStatus(); + RenderLaunchStatus(); } catch (_) { /* backend busy - next tick */ } } diff --git a/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Launch.js b/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Launch.js index 56bcbde..4bcdd8b 100644 --- a/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Launch.js +++ b/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Launch.js @@ -56,6 +56,8 @@ async function LaunchSelected() { const Names = SelectedInListOrder(); if (!Names.length) { ShowLaunchError('No account selected.'); return; } SetLaunchStatus(Names.length > 1 ? `Launching 1 / ${Names.length}...` : 'Launching...'); + Waiting = null; + LastProgress = null; LastResults = {}; RenderAccountStatus(); const Option = GetSelectValue(ById('LaunchOptionSelect')); @@ -114,14 +116,44 @@ function RenderAccountStatus() { ApplyAccountStatus(); } +// The status line only says "Launched" once the game windows are open (as RAMMIT's earlier test builds did): while an account +// is being launched, or its window isn't open yet, it says "Launching X / Y..."; in the launch delay after an account +// whose window is already open, "Launched X/Y". After the last launch it waits for the windows, then ShowLaunchDone +// (which clears itself); it gives up waiting after WindowWait. +const WindowWait = 30000; +let LastProgress = null; +let Waiting = null; // { Names, Ok, Total, Since } after a batch, until its windows are open + +const IsOpen = Name => LiveAccounts[Name] === 'running'; + +function BatchStatusText(Progress) { + const Results = Progress.Results || {}; + if (Object.values(Results).includes('launching')) return `Launching ${Math.min(Progress.Done + 1, Progress.Total)} / ${Progress.Total}...`; + const Last = Object.keys(Results).filter(Name => Results[Name] === 'ok').pop(); + return Last && IsOpen(Last) ? `Launched ${Progress.Done}/${Progress.Total}` : `Launching ${Progress.Done} / ${Progress.Total}...`; +} + +function RenderLaunchStatus() { + if (State.BatchRunning && LastProgress) { SetLaunchStatus(BatchStatusText(LastProgress)); return; } + if (!Waiting) return; + if (Waiting.Names.every(IsOpen) || Date.now() - Waiting.Since > WindowWait) { + ShowLaunchDone(`Launched ${Waiting.Ok}/${Waiting.Total}`); + Waiting = null; + } else { + SetLaunchStatus(`Launching ${Waiting.Total} / ${Waiting.Total}...`); + } +} + function ApplyProgress(Progress) { LastResults = Progress.Results || {}; + LastProgress = Progress; RenderAccountStatus(); - if (Progress.Running) SetLaunchStatus(`Launching ${Math.min(Progress.Done + 1, Progress.Total)} / ${Progress.Total}...`); + if (Progress.Running) RenderLaunchStatus(); } function FinishBatch(Progress) { - const Values = Object.values(Progress.Results || {}).map(String); + const Results = Progress.Results || {}; + const Values = Object.values(Results).map(String); const Ok = Values.filter(V => V === 'ok').length; const Errors = Values.filter(V => V.startsWith('error:')); if (Errors.length || Progress.Message) { @@ -130,7 +162,8 @@ function FinishBatch(Progress) { if (Errors.length) Text += ` — ${Errors.length} failed: ${Errors[0].slice(6)}`; ShowLaunchError(Text); } else { - ShowLaunchDone(`Launched ${Ok}/${Progress.Total}`); + Waiting = { Names: Object.keys(Results).filter(Name => Results[Name] === 'ok'), Ok, Total: Progress.Total, Since: Date.now() }; + RenderLaunchStatus(); } UpdateCounter(); } @@ -145,6 +178,7 @@ export async function UpdateCounter() { ? 'Roblox was already open when RAMMIT started, so only one client can run. Close every Roblox window and RAMMIT will take over on the next launch.' : ''; LiveAccounts = Counter.Accounts || {}; RenderAccountStatus(); + RenderLaunchStatus(); } catch (_) { /* backend busy - next tick */ } } diff --git a/Production/RAMMIT-Stable/Tests/TestBackend.py b/Production/RAMMIT-Stable/Tests/TestBackend.py index c15d99a..5387f01 100644 --- a/Production/RAMMIT-Stable/Tests/TestBackend.py +++ b/Production/RAMMIT-Stable/Tests/TestBackend.py @@ -421,13 +421,14 @@ def test_ClientTrackerMatchesClientsToAccountsByTicket(self): 11: "RobloxPlayerBeta.exe roblox-player:1+launchmode:play+gameinfo:TICKETB+launchtime:2", 12: "RobloxPlayerBeta.exe --launch-to-tray"} # a closed game's tray process: no ticket, never counted - def Scan(Players, Windows): + def Scan(Players, Windows, IncludeStarting=True): with mock.patch.object(MultiInstance, "_PlayerPids", return_value=set(Players)), \ mock.patch.object(MultiInstance, "_GameWindowPids", return_value=set(Windows)), \ mock.patch.object(MultiInstance, "_CommandLine", side_effect=lambda Pid: Lines[Pid]): - return Tracker.Scan(), Tracker.Accounts() + return Tracker.Scan(IncludeStarting), Tracker.Accounts() - self.assertEqual(Scan([], []), (2, {"A": "starting", "B": "starting"})) # launched, no client yet + self.assertEqual(Scan([], []), (2, {"A": "starting", "B": "starting"})) # launched, no client yet: counts for the limit + self.assertEqual(Scan([], [], IncludeStarting=False)[0], 0) # but not on the counter label self.assertEqual(Scan([10, 11], [10]), (2, {"A": "running", "B": "starting"})) # B's window not shown yet self.assertEqual(Scan([10, 11], [10, 11]), (2, {"A": "running", "B": "running"})) self.assertEqual(Scan([11, 12], [11]), (1, {"B": "running"})) # A closed: its game window and process are gone diff --git a/Production/RAMMIT-Stable/Tests/UiHarness.py b/Production/RAMMIT-Stable/Tests/UiHarness.py index 9357ba4..735a998 100644 --- a/Production/RAMMIT-Stable/Tests/UiHarness.py +++ b/Production/RAMMIT-Stable/Tests/UiHarness.py @@ -89,7 +89,7 @@ def FakePopen(Args, **_Kw): ApiModule.webview.create_window = FakeWindow ApiModule.subprocess = types.SimpleNamespace(Popen=FakePopen, CREATE_NO_WINDOW=0) MultiInstance.Enable = MultiInstance.LockCookieFile = MultiInstance.HoldMutex = MultiInstance.IsReady = lambda: True -MultiInstance.CountRunning = lambda _Tracker=None: Fake["Running"] +MultiInstance.CountRunning = lambda _Tracker=None, IncludeStarting=True: Fake["Running"] # No real clients here: every account RAMMIT launched counts as open (its row shows the running mark). MultiInstance.ClientTracker.Accounts = lambda Self: {Name: "running" for _Ticket, Name, _At in Self._Expected} Roblox.GetAuthTicket = lambda _Cookie: "FAKETICKET0123" From 5a0e928983eb6284dbe990716778dda12528cd7d Mon Sep 17 00:00:00 2001 From: Paradox Date: Wed, 4 Nov 2026 00:55:55 +0530 Subject: [PATCH 04/11] Launch tracking: follow the launched process to its game window On a real PC the process RAMMIT starts can hand the game to a '--launch-to-tray' child, which then opens the window without the ticket on its command line, so ticket matching alone never marked the account open. ClientTracker now owns the started pid (Started) and lets a child take the account over while it hasn't shown its window yet (also covers Bloxstrap / Fishstrap starting Roblox as a child). A tray child started after the window was shown, when a game closes, takes nothing. The ticket stays a fallback. --- Production/RAMMIT-Stable/App/Api.py | 3 +- Production/RAMMIT-Stable/App/MultiInstance.py | 87 +++++++++++++------ Production/RAMMIT-Stable/Tests/TestBackend.py | 42 +++++---- Production/RAMMIT-Stable/Tests/UiHarness.py | 6 +- 4 files changed, 94 insertions(+), 44 deletions(-) diff --git a/Production/RAMMIT-Stable/App/Api.py b/Production/RAMMIT-Stable/App/Api.py index 00a07fa..feaf90c 100644 --- a/Production/RAMMIT-Stable/App/Api.py +++ b/Production/RAMMIT-Stable/App/Api.py @@ -340,7 +340,8 @@ def _LaunchOne(self, Username, Option, Params): except ValueError as Error: return {"Error": str(Error)} self._Clients.Expect(Ticket, Account["Username"]) # before the client exists, so no scan can miss it - subprocess.Popen([Exe, LaunchUrl], creationflags=subprocess.CREATE_NO_WINDOW) + Proc = subprocess.Popen([Exe, LaunchUrl], creationflags=subprocess.CREATE_NO_WINDOW) + self._Clients.Started(Ticket, Proc.pid) Logger.info("Launched %s (%s)", Username, Option) return {"Ok": True} diff --git a/Production/RAMMIT-Stable/App/MultiInstance.py b/Production/RAMMIT-Stable/App/MultiInstance.py index e833af8..0a024aa 100644 --- a/Production/RAMMIT-Stable/App/MultiInstance.py +++ b/Production/RAMMIT-Stable/App/MultiInstance.py @@ -12,10 +12,11 @@ Counting and tracking (ClientTracker): a client is a RobloxPlayerBeta.exe that owns a visible WINDOWSCLIENT window (the game). Other visible windows don't count: closing a game starts a "--launch-to-tray" RobloxPlayerBeta that only has a tray icon, and its right-click menu is a -visible window too. Each launch's one-time ticket travels in the roblox-player: link on the -game process's command line, so matching it tells which account a client belongs to (and so -which one closed). Launches still starting (no game window for ~9 s) are counted too, or a -batch launch would overshoot MaxInstances. Tickets stay in memory and are never logged. +visible window too. Which account a client belongs to comes from the process RAMMIT started and +its children (Roblox may hand a launch to a child that opens the window), or the launch's +one-time ticket on the command line; so RAMMIT also knows which account closed. Launches still +starting (no game window for ~9 s) count towards MaxInstances, or a batch launch would +overshoot it. Tickets stay in memory and are never logged. """ import msvcrt import os @@ -123,48 +124,84 @@ def _CommandLine(Pid): return "" +def _ParentPid(Pid): + try: + return psutil.Process(Pid).ppid() + except (psutil.Error, OSError): + return None + + +def _Alive(Pid): + return psutil.pid_exists(Pid) + + +GoneKeep = 60 # seconds a finished launch process is remembered, so a client it started can still take over its account + + class ClientTracker: - """Which account each running Roblox client belongs to. Keep it in a _-prefixed Api attribute: it holds tickets.""" + """Which account each running Roblox client belongs to. Keep it in a _-prefixed Api attribute: it holds tickets. + + The process RAMMIT starts belongs to the account (Started). A Roblox process whose parent belongs to an account that + hasn't shown its game window yet takes that account over: Roblox can hand a launch to a "--launch-to-tray" child + that opens the window, and Bloxstrap / Fishstrap start Roblox as a child. Failing that, the launch ticket on the + command line. A child started after the window was shown (the tray process a closed game leaves) takes nothing.""" def __init__(self): self._Lock = threading.Lock() - self._Expected = [] # (launch ticket, Username, time launched) per launch; dropped once matched or after StartTimeout - self._Owners = {} # player pid -> Username, or None for a client that isn't one of RAMMIT's launches + self._Expected = [] # (launch ticket, Username, time launched) per launch whose process isn't known yet + self._Owners = {} # pid -> {"User": Username or None, "Since", "Shown": had a game window, "Gone": time or None} self._Last = {} # Username -> "starting" / "running", from the last Scan() def Expect(self, Ticket, Username): with self._Lock: self._Expected.append((Ticket, Username, time.monotonic())) + def Started(self, Ticket, Pid): + """The process RAMMIT started for the launch Expect()ed with Ticket.""" + with self._Lock: + for Entry in self._Expected: + if Entry[0] == Ticket: + self._Expected.remove(Entry) + self._Owners[Pid] = {"User": Entry[1], "Since": Entry[2], "Shown": False, "Gone": None} + break + def Scan(self, IncludeStarting=True): """Number of running clients: game windows, plus launches still starting unless IncludeStarting is False (the instance limit counts them, so a batch can't overshoot; the counter label doesn't). Also refreshes Accounts().""" PlayerPids, WindowPids = _PlayerPids(), _GameWindowPids() with self._Lock: Now = time.monotonic() - for Pid in list(self._Owners): - if Pid not in PlayerPids: + for Pid, Info in list(self._Owners.items()): + if Info["Gone"] is None and Pid not in PlayerPids and not _Alive(Pid): + Info["Gone"] = Now + if Info["Gone"] is not None and Now - Info["Gone"] > GoneKeep: del self._Owners[Pid] + elif Pid in WindowPids: + Info["Shown"] = True for Pid in PlayerPids - set(self._Owners): - Line = _CommandLine(Pid) - Owner = None - for Entry in self._Expected: - if "gameinfo:" + Entry[0] in Line: - Owner = Entry[1] - self._Expected.remove(Entry) - break - if Owner or Pid in WindowPids or not Line: # tray and helper processes get looked at again later - self._Owners[Pid] = Owner + Owner, Since = None, Now + Parent = self._Owners.get(_ParentPid(Pid)) + if Parent and Parent["User"] and not Parent["Shown"]: + Owner, Since = Parent["User"], Parent["Since"] + else: + Line = _CommandLine(Pid) + for Entry in self._Expected: + if "gameinfo:" + Entry[0] in Line: + Owner, Since = Entry[1], Entry[2] + self._Expected.remove(Entry) + break + self._Owners[Pid] = {"User": Owner, "Since": Since, "Shown": Pid in WindowPids, "Gone": None} self._Expected = [Entry for Entry in self._Expected if Now - Entry[2] <= StartTimeout] Accounts = {Username: "starting" for _Ticket, Username, _At in self._Expected} - for Pid, Username in self._Owners.items(): - if Username: - if Pid in WindowPids: - Accounts[Username] = "running" - else: - Accounts.setdefault(Username, "starting") - Starting = len(self._Expected) + sum(1 for Pid, Username in self._Owners.items() if Username and Pid not in WindowPids) + for Pid, Info in self._Owners.items(): + if not Info["User"] or Info["Gone"] is not None: + continue + if Pid in WindowPids: + Accounts[Info["User"]] = "running" + elif not Info["Shown"] and Now - Info["Since"] <= StartTimeout: + Accounts.setdefault(Info["User"], "starting") self._Last = Accounts + Starting = sum(1 for State in Accounts.values() if State == "starting") return len(WindowPids & PlayerPids) + (Starting if IncludeStarting else 0) def Accounts(self): diff --git a/Production/RAMMIT-Stable/Tests/TestBackend.py b/Production/RAMMIT-Stable/Tests/TestBackend.py index 5387f01..92a3bd7 100644 --- a/Production/RAMMIT-Stable/Tests/TestBackend.py +++ b/Production/RAMMIT-Stable/Tests/TestBackend.py @@ -410,29 +410,39 @@ def test_LaunchOneHappyPath(self): Args = Popen.call_args[0][0] self.assertEqual(Args[0], "C:\\R.exe") self.assertIn("placeId=123", Args[1]) - self.assertEqual([Name for _Ticket, Name, _At in self.Api._Clients._Expected], ["B"]) # waiting for its client + self.assertEqual(self.Api._Clients._Owners[4242]["User"], "B") # the started process belongs to the account + self.assertEqual(self.Api._Clients._Expected, []) - def test_ClientTrackerMatchesClientsToAccountsByTicket(self): + def test_ClientTrackerFollowsLaunchesToTheirGameWindows(self): + # As seen on a real PC: the process RAMMIT starts can hand the game to a "--launch-to-tray" child that opens the + # window; a game that closes leaves a tray child too, which must not take the account over. from App import MultiInstance Tracker = MultiInstance.ClientTracker() Tracker.Expect("TICKETA", "A") - Tracker.Expect("TICKETB", "B") - Lines = {10: "RobloxPlayerBeta.exe roblox-player:1+launchmode:play+gameinfo:TICKETA+launchtime:1", - 11: "RobloxPlayerBeta.exe roblox-player:1+launchmode:play+gameinfo:TICKETB+launchtime:2", - 12: "RobloxPlayerBeta.exe --launch-to-tray"} # a closed game's tray process: no ticket, never counted - - def Scan(Players, Windows, IncludeStarting=True): - with mock.patch.object(MultiInstance, "_PlayerPids", return_value=set(Players)), \ + Tracker.Started("TICKETA", 20) # A: RAMMIT started pid 20 + Tracker.Expect("TICKETB", "B") # B: its process is only found by its ticket (pid 30) + Lines = {20: "RobloxPlayerBeta.exe roblox-player:1+launchmode:play+gameinfo:TICKETA+launchtime:1", + 21: "RobloxPlayerBeta.exe --launch-to-tray", 22: "RobloxPlayerBeta.exe --launch-to-tray", + 30: "RobloxPlayerBeta.exe roblox-player:1+launchmode:play+gameinfo:TICKETB+launchtime:2"} + Parents = {20: 1, 21: 20, 22: 21, 30: 1} + Players = set() + + def Scan(Running, Windows, IncludeStarting=True): + Players.clear() + Players.update(Running) + with mock.patch.object(MultiInstance, "_PlayerPids", return_value=set(Running)), \ mock.patch.object(MultiInstance, "_GameWindowPids", return_value=set(Windows)), \ - mock.patch.object(MultiInstance, "_CommandLine", side_effect=lambda Pid: Lines[Pid]): + mock.patch.object(MultiInstance, "_CommandLine", side_effect=lambda Pid: Lines[Pid]), \ + mock.patch.object(MultiInstance, "_ParentPid", side_effect=lambda Pid: Parents[Pid]), \ + mock.patch.object(MultiInstance, "_Alive", side_effect=lambda Pid: Pid in Players): return Tracker.Scan(IncludeStarting), Tracker.Accounts() - self.assertEqual(Scan([], []), (2, {"A": "starting", "B": "starting"})) # launched, no client yet: counts for the limit - self.assertEqual(Scan([], [], IncludeStarting=False)[0], 0) # but not on the counter label - self.assertEqual(Scan([10, 11], [10]), (2, {"A": "running", "B": "starting"})) # B's window not shown yet - self.assertEqual(Scan([10, 11], [10, 11]), (2, {"A": "running", "B": "running"})) - self.assertEqual(Scan([11, 12], [11]), (1, {"B": "running"})) # A closed: its game window and process are gone - self.assertEqual(Scan([12], []), (0, {})) + self.assertEqual(Scan([20], []), (2, {"A": "starting", "B": "starting"})) # no windows yet: count for the limit + self.assertEqual(Scan([20], [], IncludeStarting=False)[0], 0) # but not on the counter label + self.assertEqual(Scan([21], [21]), (2, {"A": "running", "B": "starting"})) # 20 handed A to 21, which opened it + self.assertEqual(Scan([21, 30], [21, 30]), (2, {"A": "running", "B": "running"})) # B found by its ticket + self.assertEqual(Scan([22, 30], [30]), (1, {"B": "running"})) # A closed; its tray child 22 isn't A + self.assertEqual(Scan([22], []), (0, {})) def test_OnlyGameWindowsCount(self): # Roblox's tray right-click menu (SystrayContextMenu) is a visible window too, and a hidden game window isn't open yet. diff --git a/Production/RAMMIT-Stable/Tests/UiHarness.py b/Production/RAMMIT-Stable/Tests/UiHarness.py index 735a998..482f3c3 100644 --- a/Production/RAMMIT-Stable/Tests/UiHarness.py +++ b/Production/RAMMIT-Stable/Tests/UiHarness.py @@ -82,7 +82,9 @@ class FakeProc: def FakePopen(Args, **_Kw): Fake["Launches"].append(Args[1]) Fake["Running"] += 1 - return FakeProc() + Proc = FakeProc() + Proc.pid = FakeProc.pid - len(Fake["Launches"]) # one pid per launch, like real ones + return Proc webview.create_window = FakeWindow @@ -91,7 +93,7 @@ def FakePopen(Args, **_Kw): MultiInstance.Enable = MultiInstance.LockCookieFile = MultiInstance.HoldMutex = MultiInstance.IsReady = lambda: True MultiInstance.CountRunning = lambda _Tracker=None, IncludeStarting=True: Fake["Running"] # No real clients here: every account RAMMIT launched counts as open (its row shows the running mark). -MultiInstance.ClientTracker.Accounts = lambda Self: {Name: "running" for _Ticket, Name, _At in Self._Expected} +MultiInstance.ClientTracker.Accounts = lambda Self: {Info["User"]: "running" for Info in Self._Owners.values() if Info["User"]} Roblox.GetAuthTicket = lambda _Cookie: "FAKETICKET0123" Roblox.FindLauncherPath = lambda _L: r"C:\Fake\RobloxPlayerBeta.exe" Roblox.FetchServers = lambda _P, _C=None, MaxPages=10: [dict(S) for S in FakeServers] From 22a126dd03db679db4ef60af9f2be3df75785df5 Mon Sep 17 00:00:00 2001 From: Paradox Date: Wed, 4 Nov 2026 01:01:52 +0530 Subject: [PATCH 05/11] Changelog: launch tracking follows the launched process and its children --- Production/RAMMIT-Stable/CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Production/RAMMIT-Stable/CHANGELOG.md b/Production/RAMMIT-Stable/CHANGELOG.md index eead19f..0fec8aa 100644 --- a/Production/RAMMIT-Stable/CHANGELOG.md +++ b/Production/RAMMIT-Stable/CHANGELOG.md @@ -7,7 +7,7 @@ - **Installer:** pressing **Ignore** on the "older test version" screen without ticking "Don't ask again" now puts it off instead of asking every time: the menu opens as normal, with an **OLD VERSION** button and a line saying where the old version is. It stays reachable after installing the new RAMMIT, and goes away once the old version is moved or removed. - **Installer:** with RAMMIT already installed, the old version's screen keeps all four choices. The two "move my accounts" choices then copy its accounts and settings into the installed RAMMIT without reinstalling it, and the first one removes the old version afterwards. - **Installer:** the "Uninstall Config/ folder too" tick box no longer shows its check mark while unticked (#2). -- **Launch tracking:** RAMMIT now knows which Roblox client belongs to which account, by matching each launch's one-time ticket on the client's command line. An account shows "•••" while Roblox starts, "✓" only once its game window is open, and its mark clears when that window closes, so you can see which account closed. The running counter only counts open game windows: launches still starting count only towards Max Instances, and Roblox's tray process (started when a game closes) and its right-click menu no longer count at all. The status line under the launch button only says "Launched" once the accounts' windows are open (it stops waiting after 30 seconds). +- **Launch tracking:** RAMMIT now knows which Roblox client belongs to which account. It follows the process it started, including when Roblox hands the game to a child process that opens the window, and falls back to matching each launch's one-time ticket on the client's command line. An account shows "•••" while Roblox starts, "✓" only once its game window is open, and its mark clears when that window closes, so you can see which account closed. The running counter only counts open game windows: launches still starting count only towards Max Instances, and Roblox's tray process (started when a game closes) and its right-click menu no longer count at all. The status line under the launch button only says "Launched" once the accounts' windows are open (it stops waiting after 30 seconds). - **Tooltips:** every button and setting has a tooltip, drawn in the theme's own colours instead of the plain Windows one. It follows the cursor and flips to the other side near the window's edges. CBlock's are rounded; a custom theme can set `--TooltipRadius`. - The main window opens at its `HeightMap.json` height for the saved launch option, instead of opening shorter and resizing once the page has loaded. - The main window and the config window keep the right height when you grab or drag their title bar while they resize: the resize waits and is applied when you let go (the same fix as the installer's). From 5d5be766d600c58522fc2ed055a11de2311278a3 Mon Sep 17 00:00:00 2001 From: Paradox Date: Wed, 4 Nov 2026 04:01:13 +0530 Subject: [PATCH 06/11] Expired logins: red rows, RENEW and RENEW AND LAUNCH (from the Test1 build) Saved logins are checked against users/authenticated at start-up and every 5 minutes (401 = expired; anything else leaves the mark alone), and a launch whose auth ticket gets a 401 marks the account too. Expired accounts get the red Danger row; with exactly one of them selected, + ADD becomes RENEW and LAUNCH becomes RENEW AND LAUNCH (signs in again, launches only if renewed). Renew compares Roblox user ids (saved with each account from now on, filled in for existing ones by the check), falling back to the username when no id is known yet: the same user replaces that account's login in place, even after a rename; a different user is added as a new account. --- Production/RAMMIT-Stable/App/Api.py | 160 ++++++++++++++---- Production/RAMMIT-Stable/App/Main.py | 1 + Production/RAMMIT-Stable/App/Roblox.py | 25 ++- Production/RAMMIT-Stable/App/Storage.py | 12 +- Production/RAMMIT-Stable/CHANGELOG.md | 1 + .../RAMMIT-Stable/Src/CBlock/CSS/Style.css | 38 ++++- .../RAMMIT-Stable/Src/CBlock/JS/Accounts.js | 30 +++- .../RAMMIT-Stable/Src/CBlock/JS/Launch.js | 4 +- .../RAMMIT-Stable/Src/Dark/CSS/Style.css | 30 +++- .../RAMMIT-Stable/Src/Dark/JS/Accounts.js | 30 +++- .../RAMMIT-Stable/Src/Dark/JS/Launch.js | 4 +- .../RAMMIT-Stable/Src/Light/CSS/Style.css | 30 +++- .../RAMMIT-Stable/Src/Light/JS/Accounts.js | 30 +++- .../RAMMIT-Stable/Src/Light/JS/Launch.js | 4 +- .../Src/MyCustomTheme/CSS/Style.css | 30 +++- .../Src/MyCustomTheme/JS/Accounts.js | 30 +++- .../Src/MyCustomTheme/JS/Launch.js | 4 +- Production/RAMMIT-Stable/Tests/TestBackend.py | 37 ++++ Production/RAMMIT-Stable/Tests/UiHarness.py | 3 +- 19 files changed, 422 insertions(+), 81 deletions(-) diff --git a/Production/RAMMIT-Stable/App/Api.py b/Production/RAMMIT-Stable/App/Api.py index feaf90c..0ad5b38 100644 --- a/Production/RAMMIT-Stable/App/Api.py +++ b/Production/RAMMIT-Stable/App/Api.py @@ -23,6 +23,8 @@ LockedLoginMessage = "This saved login can't be read on this PC or Windows user. Remove the account and add it again." RobloxFirstMessage = "Roblox was already open when RAMMIT started, so only one client can run. Close every Roblox window, then launch again." LoginTimeoutSeconds = 300 +LoginCheckSeconds = 300 # how often saved logins are checked for expiry (the first check runs at start-up) +ExpiredMessage = "Cookie expired. Renew this account." class Api: @@ -33,6 +35,7 @@ def __init__(self, Server=None): self._Configs = Storage.LoadConfigs() self._DataLock = threading.RLock() self._Clients = MultiInstance.ClientTracker() # which running client is which account (holds launch tickets) + self._Expired = set() # lowercase usernames whose saved login Roblox rejected (401): shown red, RENEW offered self._Batch = self._EmptyBatch() self._MainWindow = None self._WizardWindow = None @@ -99,45 +102,70 @@ def LogClientError(self, Message): def GetAccounts(self): with self._DataLock: - return [{"Username": A["Username"], "DisplayName": A["DisplayName"], "Locked": A["Cookie"] is None} + return [{"Username": A["Username"], "DisplayName": A["DisplayName"], "Locked": A["Cookie"] is None, + "Expired": A["Username"].lower() in self._Expired} for A in self._Accounts] def AddAccount(self): + return self._OpenLogin("RAMMIT - Login to Roblox") + + def RenewAccount(self, Username): + """Sign in again for an expired account (RENEW). Waits until the login window is done, so RENEW AND LAUNCH can + launch right after: {"Renewed": True} when the same Roblox user signed in, {"Renewed": False} when it was a + different account (added as a new one) or the window was closed.""" + Account = self._AccountByName(Username) + if not Account: + return {"Error": "Account not found."} + Done = threading.Event() + Outcome = {} + Opened = self._OpenLogin("RAMMIT - Renew Cookie", RenewFor=Account["Username"], Done=Done, Outcome=Outcome) + if "Error" in Opened: + return Opened + Done.wait(LoginTimeoutSeconds + 10) + return {"Ok": True, "Renewed": Outcome.get("Result") == "Renewed"} + + def _OpenLogin(self, Title, RenewFor=None, Done=None, Outcome=None): with self._LoginLock: if self._LoginWindow is not None: return {"Error": "A login window is already open."} - Window = webview.create_window("RAMMIT - Login to Roblox", url="https://www.roblox.com/login", width=480, height=640) + Window = webview.create_window(Title, url="https://www.roblox.com/login", width=480, height=640) self._LoginWindow = Window Window.events.closed += self._OnLoginClosed - threading.Thread(target=self._PollLogin, args=(Window,), name="LoginPoll", daemon=True).start() + threading.Thread(target=self._PollLogin, args=(Window, RenewFor, Done, Outcome), name="LoginPoll", daemon=True).start() return {"Ok": True} def _OnLoginClosed(self): with self._LoginLock: self._LoginWindow = None - def _PollLogin(self, Window): - time.sleep(2) - Deadline = time.time() + LoginTimeoutSeconds - while time.time() < Deadline and self._LoginWindow is Window: - try: - Cookie = self._FindLoginCookie(Window.get_cookies()) - except Exception: - return # window was closed - if Cookie: - # The WebView2 cookie store is shared by RAMMIT's windows for the whole session. - # Clearing it means the next "+ ADD" shows a fresh login instead of re-saving this account. + def _PollLogin(self, Window, RenewFor=None, Done=None, Outcome=None): + try: + time.sleep(2) + Deadline = time.time() + LoginTimeoutSeconds + while time.time() < Deadline and self._LoginWindow is Window: try: - Window.clear_cookies() + Cookie = self._FindLoginCookie(Window.get_cookies()) except Exception: - pass - self._FinishLogin(Cookie) - break - time.sleep(1.5) - with self._LoginLock: - if self._LoginWindow is Window: - self._LoginWindow = None - self._DestroyQuietly(Window) + return # window was closed + if Cookie: + # The WebView2 cookie store is shared by RAMMIT's windows for the whole session. + # Clearing it means the next "+ ADD" shows a fresh login instead of re-saving this account. + try: + Window.clear_cookies() + except Exception: + pass + Result = self._FinishLogin(Cookie, RenewFor) + if Outcome is not None: + Outcome["Result"] = Result + break + time.sleep(1.5) + with self._LoginLock: + if self._LoginWindow is Window: + self._LoginWindow = None + self._DestroyQuietly(Window) + finally: + if Done: + Done.set() @staticmethod def _FindLoginCookie(CookieJars): @@ -147,24 +175,82 @@ def _FindLoginCookie(CookieJars): return Morsel.value return None - def _FinishLogin(self, Cookie): - User = Roblox.GetAuthenticatedUser(Cookie) - if not User: + def _FinishLogin(self, Cookie, RenewFor=None): + """Saves a new login. Renewing (RenewFor = an account's username): the same Roblox user replaces that account's + login in place (same user id, or same username if its id isn't known yet); a different user is added as a new + account instead. Returns "Renewed", "Added", or None on failure.""" + State, User = Roblox.CheckLogin(Cookie) + if State != "Valid": self._Notify("ShowMessage", {"Text": "Login worked but Roblox did not confirm the account. Try again.", "Error": True}) - return - Username, DisplayName = User + return None + UserId, Username, DisplayName = User + Username, DisplayName = Storage.CleanText(Username, 50), Storage.CleanText(DisplayName, 50) try: with self._DataLock: - self._Accounts = [A for A in self._Accounts if A["Username"].lower() != Username.lower()] - self._Accounts.append({"Username": Storage.CleanText(Username, 50), "DisplayName": Storage.CleanText(DisplayName, 50), - "Cookie": Cookie, "Stored": None}) + Target = next((A for A in self._Accounts if RenewFor and A["Username"].lower() == RenewFor.lower()), None) + Same = Target is not None and (Target["UserId"] == UserId if Target["UserId"] else Target["Username"].lower() == Username.lower()) + if Same: + OldName = Target["Username"] + Target.update({"Username": Username, "DisplayName": DisplayName, "UserId": UserId, "Cookie": Cookie, "Stored": None}) + self._Expired.discard(OldName.lower()) + if OldName != Username: # renamed on Roblox: keep it selected under its new name + self._Settings["SelectedAccounts"] = [Username if N == OldName else N for N in self._Settings["SelectedAccounts"]] + self._SaveSettings() + else: + self._Accounts = [A for A in self._Accounts if A["Username"].lower() != Username.lower() and A["UserId"] != UserId] + self._Accounts.append({"Username": Username, "DisplayName": DisplayName, "UserId": UserId, "Cookie": Cookie, "Stored": None}) + self._Expired.discard(Username.lower()) Storage.SaveAccounts(self._Accounts) except Exception as Error: Logger.error("Could not save account %s: %s", Username, type(Error).__name__) self._Notify("ShowMessage", {"Text": "Could not save the account securely.", "Error": True}) - return - Logger.info("Saved account %s", Username) + return None + if Same: + Logger.info("Renewed account %s", Username) + else: + Logger.info("Saved account %s", Username) + if RenewFor: + self._Notify("ShowMessage", {"Text": f"Signed in as @{Username}, not @{RenewFor}: added it as a new account.", "Error": True}) self._Notify("AccountsChanged") + return "Renewed" if Same else "Added" + + def _StartLoginChecks(self): + """Called by Main.py once the window exists: checks every saved login now, then every LoginCheckSeconds.""" + threading.Thread(target=self._CheckLogins, name="LoginChecks", daemon=True).start() + + def _CheckLogins(self, Forever=True): + while True: + with self._DataLock: + Accounts = [(A["Username"], A["Cookie"]) for A in self._Accounts if A["Cookie"]] + Changed = Save = False + for Username, Cookie in Accounts: + State, User = Roblox.CheckLogin(Cookie) + with self._DataLock: + Account = next((A for A in self._Accounts if A["Username"] == Username), None) + if not Account or Account["Cookie"] != Cookie: + continue # removed or renewed meanwhile + Key = Username.lower() + if State == "Expired" and Key not in self._Expired: + self._Expired.add(Key) + Changed = True + elif State == "Valid": + if Key in self._Expired: + self._Expired.discard(Key) + Changed = True + if not Account["UserId"]: + Account["UserId"] = User[0] + Save = True + if Save: + try: + with self._DataLock: + Storage.SaveAccounts(self._Accounts) + except Exception as Error: + Logger.error("Could not save account ids: %s", type(Error).__name__) + if Changed: + self._Notify("AccountsChanged") + if not Forever: + return + time.sleep(LoginCheckSeconds) def RemoveAccounts(self, Usernames): if not isinstance(Usernames, list): @@ -173,6 +259,7 @@ def RemoveAccounts(self, Usernames): with self._DataLock: Before = len(self._Accounts) self._Accounts = [A for A in self._Accounts if A["Username"].lower() not in Doomed] + self._Expired -= Doomed Storage.SaveAccounts(self._Accounts) self._Settings["SelectedAccounts"] = [U for U in self._Settings["SelectedAccounts"] if U.lower() not in Doomed] self._SaveSettings() @@ -333,8 +420,13 @@ def _LaunchOne(self, Username, Option, Params): return {"Error": "No servers found matching filters."} JobId = Server["id"] Ticket = Roblox.GetAuthTicket(Cookie) + if Ticket is Roblox.LoginExpired: + with self._DataLock: + self._Expired.add(Account["Username"].lower()) + self._Notify("AccountsChanged") + return {"Error": ExpiredMessage} if not Ticket: - return {"Error": "Auth failed. The saved login may have expired - remove and re-add the account."} + return {"Error": "Auth failed."} try: LaunchUrl = Roblox.BuildLaunchUrl(Ticket, PlaceId, JobId, LinkCode) except ValueError as Error: diff --git a/Production/RAMMIT-Stable/App/Main.py b/Production/RAMMIT-Stable/App/Main.py index 0329516..35551a2 100644 --- a/Production/RAMMIT-Stable/App/Main.py +++ b/Production/RAMMIT-Stable/App/Main.py @@ -58,6 +58,7 @@ def OnMainClosed(): Bridge._DestroyQuietly(Other) Window.events.closed += OnMainClosed + Bridge._StartLoginChecks() # expired saved logins turn red (first check now, then every few minutes) webview.start() Server.Stop() Logger.info("RAMMIT closed") diff --git a/Production/RAMMIT-Stable/App/Roblox.py b/Production/RAMMIT-Stable/App/Roblox.py index 56046b2..9b420e0 100644 --- a/Production/RAMMIT-Stable/App/Roblox.py +++ b/Production/RAMMIT-Stable/App/Roblox.py @@ -59,29 +59,38 @@ def PlaceIdFromGameUrl(Url): # ---------------------------------------------------------------- auth -def GetAuthenticatedUser(Cookie): - """(Username, DisplayName) for a login cookie, or None.""" +LoginExpired = object() # GetAuthTicket's answer when Roblox rejects the saved login (401): it has expired + + +def CheckLogin(Cookie): + """("Valid", (UserId, Username, DisplayName)), ("Expired", None) when Roblox rejects the login (401), or + ("Unknown", None) for anything else (offline, rate limited, ...), so a bad connection never marks a login expired.""" try: Response = requests.get("https://users.roblox.com/v1/users/authenticated", headers=_CookieHeader(Cookie), timeout=Timeout) + if Response.status_code == 401: + return "Expired", None if Response.status_code != 200: Logger.warning("users/authenticated returned %s", Response.status_code) - return None + return "Unknown", None Data = Response.json() - if isinstance(Data, dict) and isinstance(Data.get("name"), str): - return Data["name"], Data.get("displayName") or Data["name"] + if isinstance(Data, dict) and isinstance(Data.get("name"), str) and isinstance(Data.get("id"), int): + return "Valid", (Data["id"], Data["name"], Data.get("displayName") or Data["name"]) except (requests.RequestException, ValueError) as Error: Logger.warning("users/authenticated failed: %s", type(Error).__name__) - return None + return "Unknown", None def GetAuthTicket(Cookie): - """One-time ticket the Roblox client exchanges for a session. Handles the CSRF dance and 429s.""" + """One-time ticket the Roblox client exchanges for a session, LoginExpired if Roblox rejects the login (401), or + None. Handles the CSRF dance and 429s.""" Url = "https://auth.roblox.com/v1/authentication-ticket/" Headers = {"User-Agent": "Roblox/WinInet", "Referer": "https://www.roblox.com/develop", "RBX-For-Gameauth": "true", "Content-Type": "application/json", **_CookieHeader(Cookie)} try: First = requests.post(Url, headers=Headers, timeout=Timeout) Csrf = First.headers.get("x-csrf-token") + if First.status_code == 401: + return LoginExpired if First.status_code != 403 or not Csrf: Logger.warning("auth ticket CSRF step returned %s", First.status_code) return None @@ -90,6 +99,8 @@ def GetAuthTicket(Cookie): Second = requests.post(Url, headers=Headers, timeout=Timeout) if Second.status_code == 200: return Second.headers.get("rbx-authentication-ticket") or None + if Second.status_code == 401: + return LoginExpired if Second.status_code != 429: Logger.warning("auth ticket returned %s", Second.status_code) return None diff --git a/Production/RAMMIT-Stable/App/Storage.py b/Production/RAMMIT-Stable/App/Storage.py index 6f881a9..468efaa 100644 --- a/Production/RAMMIT-Stable/App/Storage.py +++ b/Production/RAMMIT-Stable/App/Storage.py @@ -271,8 +271,9 @@ def SaveConfigs(Configs): # ---------------------------------------------------------------- accounts -# In memory: {"Username", "DisplayName", "Cookie" (plain text or None), "Stored" (on-disk cookie string)} -# Cookie is None when the saved login cannot be decrypted (folder copied from another PC/user). +# In memory: {"Username", "DisplayName", "UserId" (Roblox's numeric id, or None until known), "Cookie" (plain text or +# None), "Stored" (on-disk cookie string)}. Cookie is None when the saved login cannot be decrypted (folder copied from +# another PC/user). UserId tells a renewed login apart from a different account (usernames can change). def LoadAccounts(): Disk = ReadJson(Paths.AccountsFile, []) @@ -296,9 +297,11 @@ def LoadAccounts(): Cookie = Stored Stored = None NeedsMigration = True + UserId = Entry.get("userId") Accounts.append({ "Username": CleanText(Entry["username"], 50), "DisplayName": CleanText(Entry.get("displayName") or Entry["username"], 50), + "UserId": UserId if isinstance(UserId, int) and not isinstance(UserId, bool) and UserId > 0 else None, "Cookie": Cookie, "Stored": Stored, }) @@ -313,5 +316,8 @@ def SaveAccounts(Accounts): for Account in Accounts: if not Account.get("Stored"): Account["Stored"] = Crypto.Encrypt(Account["Cookie"]) - Disk.append({"username": Account["Username"], "displayName": Account["DisplayName"], "cookie": Account["Stored"]}) + Entry = {"username": Account["Username"], "displayName": Account["DisplayName"], "cookie": Account["Stored"]} + if Account.get("UserId"): + Entry["userId"] = Account["UserId"] + Disk.append(Entry) WriteJsonAtomic(Paths.AccountsFile, Disk) diff --git a/Production/RAMMIT-Stable/CHANGELOG.md b/Production/RAMMIT-Stable/CHANGELOG.md index 0fec8aa..62bbced 100644 --- a/Production/RAMMIT-Stable/CHANGELOG.md +++ b/Production/RAMMIT-Stable/CHANGELOG.md @@ -8,6 +8,7 @@ - **Installer:** with RAMMIT already installed, the old version's screen keeps all four choices. The two "move my accounts" choices then copy its accounts and settings into the installed RAMMIT without reinstalling it, and the first one removes the old version afterwards. - **Installer:** the "Uninstall Config/ folder too" tick box no longer shows its check mark while unticked (#2). - **Launch tracking:** RAMMIT now knows which Roblox client belongs to which account. It follows the process it started, including when Roblox hands the game to a child process that opens the window, and falls back to matching each launch's one-time ticket on the client's command line. An account shows "•••" while Roblox starts, "✓" only once its game window is open, and its mark clears when that window closes, so you can see which account closed. The running counter only counts open game windows: launches still starting count only towards Max Instances, and Roblox's tray process (started when a game closes) and its right-click menu no longer count at all. The status line under the launch button only says "Launched" once the accounts' windows are open (it stops waiting after 30 seconds). +- **Expired logins** (back from the Test1 build): saved logins are checked at start-up and every 5 minutes, and an account whose login Roblox rejects turns red. With exactly that account selected, **+ ADD** becomes **RENEW** and **LAUNCH** becomes **RENEW AND LAUNCH**, which signs you in again first. Renewing keeps the account if the same Roblox user signs in (checked by user ID, so a renamed account still counts); a different user is added as a new account instead. A launch that Roblox rejects also marks the account. A check that can't reach Roblox never marks anything. - **Tooltips:** every button and setting has a tooltip, drawn in the theme's own colours instead of the plain Windows one. It follows the cursor and flips to the other side near the window's edges. CBlock's are rounded; a custom theme can set `--TooltipRadius`. - The main window opens at its `HeightMap.json` height for the saved launch option, instead of opening shorter and resizing once the page has loaded. - The main window and the config window keep the right height when you grab or drag their title bar while they resize: the resize waits and is applied when you let go (the same fix as the installer's). diff --git a/Production/RAMMIT-Stable/Src/CBlock/CSS/Style.css b/Production/RAMMIT-Stable/Src/CBlock/CSS/Style.css index 8aecad4..044053f 100644 --- a/Production/RAMMIT-Stable/Src/CBlock/CSS/Style.css +++ b/Production/RAMMIT-Stable/Src/CBlock/CSS/Style.css @@ -175,6 +175,21 @@ body { color: var(--OnAccent); } +/* A saved login Roblox rejected (expired): red row until it's renewed. */ +.ListItem.Expired { + background: var(--Danger); +} + +.ListItem.Expired:hover { + background: var(--DangerHover); +} + +.ListItem.Expired.Selected { + background: var(--Danger); + font-weight: 700; + color: var(--Accent); +} + .ListButtons { display: flex; gap: 10px; @@ -364,7 +379,7 @@ body { gap: 10px; } -.BtnAdd, .BtnEdit, .BtnRemove { +.BtnAdd, .BtnEdit, .BtnRemove, .BtnRenew { flex: 1; padding: 10px; border: none; @@ -388,7 +403,12 @@ body { background: var(--Danger); } -.BtnAdd:hover, .BtnEdit:hover, .BtnRemove:hover { +/* + ADD turns into RENEW while exactly one expired account is selected (Accounts.js). */ +.BtnRenew { + background: var(--EditButton); +} + +.BtnAdd:hover, .BtnEdit:hover, .BtnRemove:hover, .BtnRenew:hover { opacity: 0.85; } @@ -981,11 +1001,11 @@ body { transition: background 0.15s ease; } -.BtnLaunch, .BtnAdd, .BtnEdit, .BtnRemove, .BtnSelect, .BtnSave, .BtnIcon, .TourBtn { +.BtnLaunch, .BtnAdd, .BtnEdit, .BtnRemove, .BtnRenew, .BtnSelect, .BtnSave, .BtnIcon, .TourBtn { transition: background 0.15s ease, opacity 0.15s ease, transform 0.1s ease; } -.BtnLaunch:active, .BtnAdd:active, .BtnEdit:active, .BtnRemove:active, +.BtnLaunch:active, .BtnAdd:active, .BtnEdit:active, .BtnRemove:active, .BtnRenew:active, .BtnSelect:active, .BtnSave:active, .BtnIcon:active, .TourBtn:active { transform: scale(0.97); } @@ -1243,7 +1263,7 @@ body.WizardBody { } /* Buttons and text boxes follow the theme's ButtonRadius (0 = square, the Dark look). */ -.BtnAdd, .BtnEdit, .BtnRemove, .BtnSelect, .BtnLaunch, .BtnSave, +.BtnAdd, .BtnEdit, .BtnRemove, .BtnRenew, .BtnSelect, .BtnLaunch, .BtnSave, .SettingsGrid input[type="text"], .ChannelRow input, .LaunchInput, .CustomSelectTrigger { border-radius: var(--ButtonRadius); } @@ -1317,7 +1337,7 @@ body.WizardBody { .CustomSelectOption:hover { background: #18122a; color: var(--Text); } /* Buttons: 6px corners like the site's .Btn. */ -.BtnAdd, .BtnEdit, .BtnRemove, .BtnSelect, .BtnLaunch, .BtnSave, .BtnConfirm, .BtnCancel, .TourBtn { +.BtnAdd, .BtnEdit, .BtnRemove, .BtnRenew, .BtnSelect, .BtnLaunch, .BtnSave, .BtnConfirm, .BtnCancel, .TourBtn { border-radius: 6px; transition: background 0.2s, color 0.2s, box-shadow 0.2s, opacity 0.15s, transform 0.1s ease; } @@ -1336,11 +1356,11 @@ body.WizardBody { .TourBtn.Primary { background: var(--Accent); color: var(--OnAccent); box-shadow: inset 0 0 0 1px var(--Accent); } .TourBtn.Primary:hover { background: transparent; color: #9a63e0; opacity: 1; } -/* .Btn: + ADD (violet), EDIT (green), - REMOVE and wizard CANCEL (red). */ +/* .Btn: + ADD (violet), EDIT and RENEW (green), - REMOVE and wizard CANCEL (red). */ .BtnAdd { background: transparent; color: #9a63e0; box-shadow: inset 0 0 0 1px var(--Accent); } .BtnAdd:hover { background: var(--Accent); color: var(--OnAccent); opacity: 1; } -.BtnEdit { background: transparent; color: var(--Success); box-shadow: inset 0 0 0 1px var(--Success); } -.BtnEdit:hover { background: var(--Success); color: #000000; opacity: 1; } +.BtnEdit, .BtnRenew { background: transparent; color: var(--Success); box-shadow: inset 0 0 0 1px var(--Success); } +.BtnEdit:hover, .BtnRenew:hover { background: var(--Success); color: #000000; opacity: 1; } .BtnRemove, .BtnRow .BtnCancel { background: transparent; color: var(--Danger); box-shadow: inset 0 0 0 1px var(--Danger); } .BtnRemove:hover, .BtnRow .BtnCancel:hover { background: var(--Danger); color: #000000; opacity: 1; } diff --git a/Production/RAMMIT-Stable/Src/CBlock/JS/Accounts.js b/Production/RAMMIT-Stable/Src/CBlock/JS/Accounts.js index 8bfdbe0..5e00227 100644 --- a/Production/RAMMIT-Stable/Src/CBlock/JS/Accounts.js +++ b/Production/RAMMIT-Stable/Src/CBlock/JS/Accounts.js @@ -16,7 +16,7 @@ export async function RefreshAccounts() { const Label = El('span', { Class: 'AcctLabel', Text: Account.DisplayName + ' ' }, El('span', { Class: 'AcctUser', Text: `(@${Account.Username})` }), Account.Locked ? El('span', { Class: 'AcctLocked', Text: '⚠', Title: 'This saved login was made on another PC or Windows user. Remove it and add the account again.' }) : null); - const Row = El('li', { Class: 'AccountItem ListItem' }, Check, Label, El('span', { Class: 'AcctStatus' })); + const Row = El('li', { Class: 'AccountItem ListItem' + (Account.Expired ? ' Expired' : '') }, Check, Label, El('span', { Class: 'AcctStatus' })); Check.addEventListener('click', Event => { Event.stopPropagation(); ToggleAccount(Index); }); Row.addEventListener('click', Event => OnAccountClick(Event, Index)); return Row; @@ -66,14 +66,30 @@ export function ToggleSelectAll() { export const SelectedInListOrder = () => State.Accounts.map(A => A.Username).filter(Name => State.Selected.has(Name)); +// The one selected account, when exactly one is selected and its saved login has expired: + ADD becomes RENEW and +// LAUNCH becomes RENEW AND LAUNCH for it. +export function RenewTarget() { + if (State.Selected.size !== 1) return null; + const Name = [...State.Selected][0]; + const Account = State.Accounts.find(A => A.Username === Name); + return Account && Account.Expired ? Account.Username : null; +} + export function ApplySelection() { ById('AccountList').querySelectorAll('.ListItem').forEach((Row, Index) => { Row.classList.toggle('Selected', State.Selected.has(State.Accounts[Index].Username)); }); const Count = State.Selected.size; + const Renew = RenewTarget(); + const AddBtn = ById('AddAccountBtn'); + AddBtn.classList.toggle('BtnAdd', !Renew); + AddBtn.classList.toggle('BtnRenew', !!Renew); + AddBtn.textContent = Renew ? 'RENEW' : '+ ADD'; + AddBtn.removeAttribute('title'); + AddBtn.dataset.tooltip = Renew ? `Sign in again as @${Renew} (its saved login expired)` : 'Sign in to a Roblox account and save it'; ById('SelectionCount').textContent = Count ? ` (${Count} SELECTED)` : ''; ById('SelectAllBtn').textContent = (State.Accounts.length > 0 && Count >= State.Accounts.length) ? 'CLEAR' : 'SELECT ALL'; - if (!State.BatchRunning) ById('LaunchBtn').textContent = Count > 1 ? `LAUNCH ${Count} SELECTED` : 'LAUNCH SELECTED'; + if (!State.BatchRunning) ById('LaunchBtn').textContent = Renew ? 'RENEW AND LAUNCH' : Count > 1 ? `LAUNCH ${Count} SELECTED` : 'LAUNCH SELECTED'; } export function ApplyAccountStatus() { @@ -96,10 +112,20 @@ function SaveSelection() { } export async function AddAccount() { + const Renew = RenewTarget(); + if (Renew) { await RenewAccount(Renew); return; } // the button reads RENEW const Result = await Api.AddAccount(); if (Result && Result.Error) ShowLaunchError(Result.Error); } +// Sign in again for an expired account. True when that same Roblox user signed in (a different one is added instead). +export async function RenewAccount(Username) { + const Result = await Api.RenewAccount(Username); + if (Result && Result.Error) ShowLaunchError(Result.Error); + await RefreshAccounts(); + return !!(Result && Result.Renewed); +} + export async function RemoveSelectedAccounts() { const Names = SelectedInListOrder(); if (!Names.length) return; diff --git a/Production/RAMMIT-Stable/Src/CBlock/JS/Launch.js b/Production/RAMMIT-Stable/Src/CBlock/JS/Launch.js index 4bcdd8b..0705310 100644 --- a/Production/RAMMIT-Stable/Src/CBlock/JS/Launch.js +++ b/Production/RAMMIT-Stable/Src/CBlock/JS/Launch.js @@ -6,7 +6,7 @@ import { ById, Debounce } from './Dom.js'; import { InitSelect, SetSelectValue, GetSelectValue } from './Select.js'; import { CreateLaunchForm } from './LaunchForm.js'; import { State } from './State.js'; -import { ApplySelection, ApplyAccountStatus, SelectedInListOrder } from './Accounts.js'; +import { ApplySelection, ApplyAccountStatus, SelectedInListOrder, RenewTarget, RenewAccount } from './Accounts.js'; import { SetLaunchStatus, ShowLaunchError, ShowLaunchDone } from './Status.js'; import { ThemeNoteExtra } from './Themes.js'; @@ -53,6 +53,8 @@ function OnLaunchClick() { } async function LaunchSelected() { + const Renew = RenewTarget(); + if (Renew && !(await RenewAccount(Renew))) return; // RENEW AND LAUNCH: sign in again first, launch only if it worked const Names = SelectedInListOrder(); if (!Names.length) { ShowLaunchError('No account selected.'); return; } SetLaunchStatus(Names.length > 1 ? `Launching 1 / ${Names.length}...` : 'Launching...'); diff --git a/Production/RAMMIT-Stable/Src/Dark/CSS/Style.css b/Production/RAMMIT-Stable/Src/Dark/CSS/Style.css index b8b879f..cb2bddd 100644 --- a/Production/RAMMIT-Stable/Src/Dark/CSS/Style.css +++ b/Production/RAMMIT-Stable/Src/Dark/CSS/Style.css @@ -176,6 +176,21 @@ body { color: var(--OnAccent); } +/* A saved login Roblox rejected (expired): red row until it's renewed. */ +.ListItem.Expired { + background: var(--Danger); +} + +.ListItem.Expired:hover { + background: var(--DangerHover); +} + +.ListItem.Expired.Selected { + background: var(--Danger); + font-weight: 700; + color: var(--Accent); +} + .ListButtons { display: flex; gap: 10px; @@ -365,7 +380,7 @@ body { gap: 10px; } -.BtnAdd, .BtnEdit, .BtnRemove { +.BtnAdd, .BtnEdit, .BtnRemove, .BtnRenew { flex: 1; padding: 10px; border: none; @@ -389,7 +404,12 @@ body { background: var(--Danger); } -.BtnAdd:hover, .BtnEdit:hover, .BtnRemove:hover { +/* + ADD turns into RENEW while exactly one expired account is selected (Accounts.js). */ +.BtnRenew { + background: var(--EditButton); +} + +.BtnAdd:hover, .BtnEdit:hover, .BtnRemove:hover, .BtnRenew:hover { opacity: 0.85; } @@ -982,11 +1002,11 @@ body { transition: background 0.15s ease; } -.BtnLaunch, .BtnAdd, .BtnEdit, .BtnRemove, .BtnSelect, .BtnSave, .BtnIcon, .TourBtn { +.BtnLaunch, .BtnAdd, .BtnEdit, .BtnRemove, .BtnRenew, .BtnSelect, .BtnSave, .BtnIcon, .TourBtn { transition: background 0.15s ease, opacity 0.15s ease, transform 0.1s ease; } -.BtnLaunch:active, .BtnAdd:active, .BtnEdit:active, .BtnRemove:active, +.BtnLaunch:active, .BtnAdd:active, .BtnEdit:active, .BtnRemove:active, .BtnRenew:active, .BtnSelect:active, .BtnSave:active, .BtnIcon:active, .TourBtn:active { transform: scale(0.97); } @@ -1244,7 +1264,7 @@ body.WizardBody { } /* Buttons and text boxes follow the theme's ButtonRadius (0 = square, the Dark look). */ -.BtnAdd, .BtnEdit, .BtnRemove, .BtnSelect, .BtnLaunch, .BtnSave, +.BtnAdd, .BtnEdit, .BtnRemove, .BtnRenew, .BtnSelect, .BtnLaunch, .BtnSave, .SettingsGrid input[type="text"], .ChannelRow input, .LaunchInput, .CustomSelectTrigger { border-radius: var(--ButtonRadius); } diff --git a/Production/RAMMIT-Stable/Src/Dark/JS/Accounts.js b/Production/RAMMIT-Stable/Src/Dark/JS/Accounts.js index 8bfdbe0..5e00227 100644 --- a/Production/RAMMIT-Stable/Src/Dark/JS/Accounts.js +++ b/Production/RAMMIT-Stable/Src/Dark/JS/Accounts.js @@ -16,7 +16,7 @@ export async function RefreshAccounts() { const Label = El('span', { Class: 'AcctLabel', Text: Account.DisplayName + ' ' }, El('span', { Class: 'AcctUser', Text: `(@${Account.Username})` }), Account.Locked ? El('span', { Class: 'AcctLocked', Text: '⚠', Title: 'This saved login was made on another PC or Windows user. Remove it and add the account again.' }) : null); - const Row = El('li', { Class: 'AccountItem ListItem' }, Check, Label, El('span', { Class: 'AcctStatus' })); + const Row = El('li', { Class: 'AccountItem ListItem' + (Account.Expired ? ' Expired' : '') }, Check, Label, El('span', { Class: 'AcctStatus' })); Check.addEventListener('click', Event => { Event.stopPropagation(); ToggleAccount(Index); }); Row.addEventListener('click', Event => OnAccountClick(Event, Index)); return Row; @@ -66,14 +66,30 @@ export function ToggleSelectAll() { export const SelectedInListOrder = () => State.Accounts.map(A => A.Username).filter(Name => State.Selected.has(Name)); +// The one selected account, when exactly one is selected and its saved login has expired: + ADD becomes RENEW and +// LAUNCH becomes RENEW AND LAUNCH for it. +export function RenewTarget() { + if (State.Selected.size !== 1) return null; + const Name = [...State.Selected][0]; + const Account = State.Accounts.find(A => A.Username === Name); + return Account && Account.Expired ? Account.Username : null; +} + export function ApplySelection() { ById('AccountList').querySelectorAll('.ListItem').forEach((Row, Index) => { Row.classList.toggle('Selected', State.Selected.has(State.Accounts[Index].Username)); }); const Count = State.Selected.size; + const Renew = RenewTarget(); + const AddBtn = ById('AddAccountBtn'); + AddBtn.classList.toggle('BtnAdd', !Renew); + AddBtn.classList.toggle('BtnRenew', !!Renew); + AddBtn.textContent = Renew ? 'RENEW' : '+ ADD'; + AddBtn.removeAttribute('title'); + AddBtn.dataset.tooltip = Renew ? `Sign in again as @${Renew} (its saved login expired)` : 'Sign in to a Roblox account and save it'; ById('SelectionCount').textContent = Count ? ` (${Count} SELECTED)` : ''; ById('SelectAllBtn').textContent = (State.Accounts.length > 0 && Count >= State.Accounts.length) ? 'CLEAR' : 'SELECT ALL'; - if (!State.BatchRunning) ById('LaunchBtn').textContent = Count > 1 ? `LAUNCH ${Count} SELECTED` : 'LAUNCH SELECTED'; + if (!State.BatchRunning) ById('LaunchBtn').textContent = Renew ? 'RENEW AND LAUNCH' : Count > 1 ? `LAUNCH ${Count} SELECTED` : 'LAUNCH SELECTED'; } export function ApplyAccountStatus() { @@ -96,10 +112,20 @@ function SaveSelection() { } export async function AddAccount() { + const Renew = RenewTarget(); + if (Renew) { await RenewAccount(Renew); return; } // the button reads RENEW const Result = await Api.AddAccount(); if (Result && Result.Error) ShowLaunchError(Result.Error); } +// Sign in again for an expired account. True when that same Roblox user signed in (a different one is added instead). +export async function RenewAccount(Username) { + const Result = await Api.RenewAccount(Username); + if (Result && Result.Error) ShowLaunchError(Result.Error); + await RefreshAccounts(); + return !!(Result && Result.Renewed); +} + export async function RemoveSelectedAccounts() { const Names = SelectedInListOrder(); if (!Names.length) return; diff --git a/Production/RAMMIT-Stable/Src/Dark/JS/Launch.js b/Production/RAMMIT-Stable/Src/Dark/JS/Launch.js index 4bcdd8b..0705310 100644 --- a/Production/RAMMIT-Stable/Src/Dark/JS/Launch.js +++ b/Production/RAMMIT-Stable/Src/Dark/JS/Launch.js @@ -6,7 +6,7 @@ import { ById, Debounce } from './Dom.js'; import { InitSelect, SetSelectValue, GetSelectValue } from './Select.js'; import { CreateLaunchForm } from './LaunchForm.js'; import { State } from './State.js'; -import { ApplySelection, ApplyAccountStatus, SelectedInListOrder } from './Accounts.js'; +import { ApplySelection, ApplyAccountStatus, SelectedInListOrder, RenewTarget, RenewAccount } from './Accounts.js'; import { SetLaunchStatus, ShowLaunchError, ShowLaunchDone } from './Status.js'; import { ThemeNoteExtra } from './Themes.js'; @@ -53,6 +53,8 @@ function OnLaunchClick() { } async function LaunchSelected() { + const Renew = RenewTarget(); + if (Renew && !(await RenewAccount(Renew))) return; // RENEW AND LAUNCH: sign in again first, launch only if it worked const Names = SelectedInListOrder(); if (!Names.length) { ShowLaunchError('No account selected.'); return; } SetLaunchStatus(Names.length > 1 ? `Launching 1 / ${Names.length}...` : 'Launching...'); diff --git a/Production/RAMMIT-Stable/Src/Light/CSS/Style.css b/Production/RAMMIT-Stable/Src/Light/CSS/Style.css index 17f11e7..167758f 100644 --- a/Production/RAMMIT-Stable/Src/Light/CSS/Style.css +++ b/Production/RAMMIT-Stable/Src/Light/CSS/Style.css @@ -174,6 +174,21 @@ body { color: var(--OnAccent); } +/* A saved login Roblox rejected (expired): red row until it's renewed. */ +.ListItem.Expired { + background: var(--Danger); +} + +.ListItem.Expired:hover { + background: var(--DangerHover); +} + +.ListItem.Expired.Selected { + background: var(--Danger); + font-weight: 700; + color: var(--Accent); +} + .ListButtons { display: flex; gap: 10px; @@ -363,7 +378,7 @@ body { gap: 10px; } -.BtnAdd, .BtnEdit, .BtnRemove { +.BtnAdd, .BtnEdit, .BtnRemove, .BtnRenew { flex: 1; padding: 10px; border: none; @@ -387,7 +402,12 @@ body { background: var(--Danger); } -.BtnAdd:hover, .BtnEdit:hover, .BtnRemove:hover { +/* + ADD turns into RENEW while exactly one expired account is selected (Accounts.js). */ +.BtnRenew { + background: var(--EditButton); +} + +.BtnAdd:hover, .BtnEdit:hover, .BtnRemove:hover, .BtnRenew:hover { opacity: 0.85; } @@ -980,11 +1000,11 @@ body { transition: background 0.15s ease; } -.BtnLaunch, .BtnAdd, .BtnEdit, .BtnRemove, .BtnSelect, .BtnSave, .BtnIcon, .TourBtn { +.BtnLaunch, .BtnAdd, .BtnEdit, .BtnRemove, .BtnRenew, .BtnSelect, .BtnSave, .BtnIcon, .TourBtn { transition: background 0.15s ease, opacity 0.15s ease, transform 0.1s ease; } -.BtnLaunch:active, .BtnAdd:active, .BtnEdit:active, .BtnRemove:active, +.BtnLaunch:active, .BtnAdd:active, .BtnEdit:active, .BtnRemove:active, .BtnRenew:active, .BtnSelect:active, .BtnSave:active, .BtnIcon:active, .TourBtn:active { transform: scale(0.97); } @@ -1242,7 +1262,7 @@ body.WizardBody { } /* Buttons and text boxes follow the theme's ButtonRadius (0 = square, the Dark look). */ -.BtnAdd, .BtnEdit, .BtnRemove, .BtnSelect, .BtnLaunch, .BtnSave, +.BtnAdd, .BtnEdit, .BtnRemove, .BtnRenew, .BtnSelect, .BtnLaunch, .BtnSave, .SettingsGrid input[type="text"], .ChannelRow input, .LaunchInput, .CustomSelectTrigger { border-radius: var(--ButtonRadius); } diff --git a/Production/RAMMIT-Stable/Src/Light/JS/Accounts.js b/Production/RAMMIT-Stable/Src/Light/JS/Accounts.js index 8bfdbe0..5e00227 100644 --- a/Production/RAMMIT-Stable/Src/Light/JS/Accounts.js +++ b/Production/RAMMIT-Stable/Src/Light/JS/Accounts.js @@ -16,7 +16,7 @@ export async function RefreshAccounts() { const Label = El('span', { Class: 'AcctLabel', Text: Account.DisplayName + ' ' }, El('span', { Class: 'AcctUser', Text: `(@${Account.Username})` }), Account.Locked ? El('span', { Class: 'AcctLocked', Text: '⚠', Title: 'This saved login was made on another PC or Windows user. Remove it and add the account again.' }) : null); - const Row = El('li', { Class: 'AccountItem ListItem' }, Check, Label, El('span', { Class: 'AcctStatus' })); + const Row = El('li', { Class: 'AccountItem ListItem' + (Account.Expired ? ' Expired' : '') }, Check, Label, El('span', { Class: 'AcctStatus' })); Check.addEventListener('click', Event => { Event.stopPropagation(); ToggleAccount(Index); }); Row.addEventListener('click', Event => OnAccountClick(Event, Index)); return Row; @@ -66,14 +66,30 @@ export function ToggleSelectAll() { export const SelectedInListOrder = () => State.Accounts.map(A => A.Username).filter(Name => State.Selected.has(Name)); +// The one selected account, when exactly one is selected and its saved login has expired: + ADD becomes RENEW and +// LAUNCH becomes RENEW AND LAUNCH for it. +export function RenewTarget() { + if (State.Selected.size !== 1) return null; + const Name = [...State.Selected][0]; + const Account = State.Accounts.find(A => A.Username === Name); + return Account && Account.Expired ? Account.Username : null; +} + export function ApplySelection() { ById('AccountList').querySelectorAll('.ListItem').forEach((Row, Index) => { Row.classList.toggle('Selected', State.Selected.has(State.Accounts[Index].Username)); }); const Count = State.Selected.size; + const Renew = RenewTarget(); + const AddBtn = ById('AddAccountBtn'); + AddBtn.classList.toggle('BtnAdd', !Renew); + AddBtn.classList.toggle('BtnRenew', !!Renew); + AddBtn.textContent = Renew ? 'RENEW' : '+ ADD'; + AddBtn.removeAttribute('title'); + AddBtn.dataset.tooltip = Renew ? `Sign in again as @${Renew} (its saved login expired)` : 'Sign in to a Roblox account and save it'; ById('SelectionCount').textContent = Count ? ` (${Count} SELECTED)` : ''; ById('SelectAllBtn').textContent = (State.Accounts.length > 0 && Count >= State.Accounts.length) ? 'CLEAR' : 'SELECT ALL'; - if (!State.BatchRunning) ById('LaunchBtn').textContent = Count > 1 ? `LAUNCH ${Count} SELECTED` : 'LAUNCH SELECTED'; + if (!State.BatchRunning) ById('LaunchBtn').textContent = Renew ? 'RENEW AND LAUNCH' : Count > 1 ? `LAUNCH ${Count} SELECTED` : 'LAUNCH SELECTED'; } export function ApplyAccountStatus() { @@ -96,10 +112,20 @@ function SaveSelection() { } export async function AddAccount() { + const Renew = RenewTarget(); + if (Renew) { await RenewAccount(Renew); return; } // the button reads RENEW const Result = await Api.AddAccount(); if (Result && Result.Error) ShowLaunchError(Result.Error); } +// Sign in again for an expired account. True when that same Roblox user signed in (a different one is added instead). +export async function RenewAccount(Username) { + const Result = await Api.RenewAccount(Username); + if (Result && Result.Error) ShowLaunchError(Result.Error); + await RefreshAccounts(); + return !!(Result && Result.Renewed); +} + export async function RemoveSelectedAccounts() { const Names = SelectedInListOrder(); if (!Names.length) return; diff --git a/Production/RAMMIT-Stable/Src/Light/JS/Launch.js b/Production/RAMMIT-Stable/Src/Light/JS/Launch.js index 4bcdd8b..0705310 100644 --- a/Production/RAMMIT-Stable/Src/Light/JS/Launch.js +++ b/Production/RAMMIT-Stable/Src/Light/JS/Launch.js @@ -6,7 +6,7 @@ import { ById, Debounce } from './Dom.js'; import { InitSelect, SetSelectValue, GetSelectValue } from './Select.js'; import { CreateLaunchForm } from './LaunchForm.js'; import { State } from './State.js'; -import { ApplySelection, ApplyAccountStatus, SelectedInListOrder } from './Accounts.js'; +import { ApplySelection, ApplyAccountStatus, SelectedInListOrder, RenewTarget, RenewAccount } from './Accounts.js'; import { SetLaunchStatus, ShowLaunchError, ShowLaunchDone } from './Status.js'; import { ThemeNoteExtra } from './Themes.js'; @@ -53,6 +53,8 @@ function OnLaunchClick() { } async function LaunchSelected() { + const Renew = RenewTarget(); + if (Renew && !(await RenewAccount(Renew))) return; // RENEW AND LAUNCH: sign in again first, launch only if it worked const Names = SelectedInListOrder(); if (!Names.length) { ShowLaunchError('No account selected.'); return; } SetLaunchStatus(Names.length > 1 ? `Launching 1 / ${Names.length}...` : 'Launching...'); diff --git a/Production/RAMMIT-Stable/Src/MyCustomTheme/CSS/Style.css b/Production/RAMMIT-Stable/Src/MyCustomTheme/CSS/Style.css index 51d0f35..d73154e 100644 --- a/Production/RAMMIT-Stable/Src/MyCustomTheme/CSS/Style.css +++ b/Production/RAMMIT-Stable/Src/MyCustomTheme/CSS/Style.css @@ -173,6 +173,21 @@ body { color: var(--OnAccent); } +/* A saved login Roblox rejected (expired): red row until it's renewed. */ +.ListItem.Expired { + background: var(--Danger); +} + +.ListItem.Expired:hover { + background: var(--DangerHover); +} + +.ListItem.Expired.Selected { + background: var(--Danger); + font-weight: 700; + color: var(--Accent); +} + .ListButtons { display: flex; gap: 10px; @@ -362,7 +377,7 @@ body { gap: 10px; } -.BtnAdd, .BtnEdit, .BtnRemove { +.BtnAdd, .BtnEdit, .BtnRemove, .BtnRenew { flex: 1; padding: 10px; border: none; @@ -386,7 +401,12 @@ body { background: var(--Danger); } -.BtnAdd:hover, .BtnEdit:hover, .BtnRemove:hover { +/* + ADD turns into RENEW while exactly one expired account is selected (Accounts.js). */ +.BtnRenew { + background: var(--EditButton); +} + +.BtnAdd:hover, .BtnEdit:hover, .BtnRemove:hover, .BtnRenew:hover { opacity: 0.85; } @@ -979,11 +999,11 @@ body { transition: background 0.15s ease; } -.BtnLaunch, .BtnAdd, .BtnEdit, .BtnRemove, .BtnSelect, .BtnSave, .BtnIcon, .TourBtn { +.BtnLaunch, .BtnAdd, .BtnEdit, .BtnRemove, .BtnRenew, .BtnSelect, .BtnSave, .BtnIcon, .TourBtn { transition: background 0.15s ease, opacity 0.15s ease, transform 0.1s ease; } -.BtnLaunch:active, .BtnAdd:active, .BtnEdit:active, .BtnRemove:active, +.BtnLaunch:active, .BtnAdd:active, .BtnEdit:active, .BtnRemove:active, .BtnRenew:active, .BtnSelect:active, .BtnSave:active, .BtnIcon:active, .TourBtn:active { transform: scale(0.97); } @@ -1241,7 +1261,7 @@ body.WizardBody { } /* Buttons and text boxes follow the theme's ButtonRadius (0 = square, the Dark look). */ -.BtnAdd, .BtnEdit, .BtnRemove, .BtnSelect, .BtnLaunch, .BtnSave, +.BtnAdd, .BtnEdit, .BtnRemove, .BtnRenew, .BtnSelect, .BtnLaunch, .BtnSave, .SettingsGrid input[type="text"], .ChannelRow input, .LaunchInput, .CustomSelectTrigger { border-radius: var(--ButtonRadius); } diff --git a/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Accounts.js b/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Accounts.js index 8bfdbe0..5e00227 100644 --- a/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Accounts.js +++ b/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Accounts.js @@ -16,7 +16,7 @@ export async function RefreshAccounts() { const Label = El('span', { Class: 'AcctLabel', Text: Account.DisplayName + ' ' }, El('span', { Class: 'AcctUser', Text: `(@${Account.Username})` }), Account.Locked ? El('span', { Class: 'AcctLocked', Text: '⚠', Title: 'This saved login was made on another PC or Windows user. Remove it and add the account again.' }) : null); - const Row = El('li', { Class: 'AccountItem ListItem' }, Check, Label, El('span', { Class: 'AcctStatus' })); + const Row = El('li', { Class: 'AccountItem ListItem' + (Account.Expired ? ' Expired' : '') }, Check, Label, El('span', { Class: 'AcctStatus' })); Check.addEventListener('click', Event => { Event.stopPropagation(); ToggleAccount(Index); }); Row.addEventListener('click', Event => OnAccountClick(Event, Index)); return Row; @@ -66,14 +66,30 @@ export function ToggleSelectAll() { export const SelectedInListOrder = () => State.Accounts.map(A => A.Username).filter(Name => State.Selected.has(Name)); +// The one selected account, when exactly one is selected and its saved login has expired: + ADD becomes RENEW and +// LAUNCH becomes RENEW AND LAUNCH for it. +export function RenewTarget() { + if (State.Selected.size !== 1) return null; + const Name = [...State.Selected][0]; + const Account = State.Accounts.find(A => A.Username === Name); + return Account && Account.Expired ? Account.Username : null; +} + export function ApplySelection() { ById('AccountList').querySelectorAll('.ListItem').forEach((Row, Index) => { Row.classList.toggle('Selected', State.Selected.has(State.Accounts[Index].Username)); }); const Count = State.Selected.size; + const Renew = RenewTarget(); + const AddBtn = ById('AddAccountBtn'); + AddBtn.classList.toggle('BtnAdd', !Renew); + AddBtn.classList.toggle('BtnRenew', !!Renew); + AddBtn.textContent = Renew ? 'RENEW' : '+ ADD'; + AddBtn.removeAttribute('title'); + AddBtn.dataset.tooltip = Renew ? `Sign in again as @${Renew} (its saved login expired)` : 'Sign in to a Roblox account and save it'; ById('SelectionCount').textContent = Count ? ` (${Count} SELECTED)` : ''; ById('SelectAllBtn').textContent = (State.Accounts.length > 0 && Count >= State.Accounts.length) ? 'CLEAR' : 'SELECT ALL'; - if (!State.BatchRunning) ById('LaunchBtn').textContent = Count > 1 ? `LAUNCH ${Count} SELECTED` : 'LAUNCH SELECTED'; + if (!State.BatchRunning) ById('LaunchBtn').textContent = Renew ? 'RENEW AND LAUNCH' : Count > 1 ? `LAUNCH ${Count} SELECTED` : 'LAUNCH SELECTED'; } export function ApplyAccountStatus() { @@ -96,10 +112,20 @@ function SaveSelection() { } export async function AddAccount() { + const Renew = RenewTarget(); + if (Renew) { await RenewAccount(Renew); return; } // the button reads RENEW const Result = await Api.AddAccount(); if (Result && Result.Error) ShowLaunchError(Result.Error); } +// Sign in again for an expired account. True when that same Roblox user signed in (a different one is added instead). +export async function RenewAccount(Username) { + const Result = await Api.RenewAccount(Username); + if (Result && Result.Error) ShowLaunchError(Result.Error); + await RefreshAccounts(); + return !!(Result && Result.Renewed); +} + export async function RemoveSelectedAccounts() { const Names = SelectedInListOrder(); if (!Names.length) return; diff --git a/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Launch.js b/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Launch.js index 4bcdd8b..0705310 100644 --- a/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Launch.js +++ b/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Launch.js @@ -6,7 +6,7 @@ import { ById, Debounce } from './Dom.js'; import { InitSelect, SetSelectValue, GetSelectValue } from './Select.js'; import { CreateLaunchForm } from './LaunchForm.js'; import { State } from './State.js'; -import { ApplySelection, ApplyAccountStatus, SelectedInListOrder } from './Accounts.js'; +import { ApplySelection, ApplyAccountStatus, SelectedInListOrder, RenewTarget, RenewAccount } from './Accounts.js'; import { SetLaunchStatus, ShowLaunchError, ShowLaunchDone } from './Status.js'; import { ThemeNoteExtra } from './Themes.js'; @@ -53,6 +53,8 @@ function OnLaunchClick() { } async function LaunchSelected() { + const Renew = RenewTarget(); + if (Renew && !(await RenewAccount(Renew))) return; // RENEW AND LAUNCH: sign in again first, launch only if it worked const Names = SelectedInListOrder(); if (!Names.length) { ShowLaunchError('No account selected.'); return; } SetLaunchStatus(Names.length > 1 ? `Launching 1 / ${Names.length}...` : 'Launching...'); diff --git a/Production/RAMMIT-Stable/Tests/TestBackend.py b/Production/RAMMIT-Stable/Tests/TestBackend.py index 92a3bd7..24f6e1c 100644 --- a/Production/RAMMIT-Stable/Tests/TestBackend.py +++ b/Production/RAMMIT-Stable/Tests/TestBackend.py @@ -463,6 +463,43 @@ def test_InstanceLimit(self): with mock.patch.object(ApiModule.MultiInstance, "CountRunning", return_value=1): self.assertEqual(self.Api._LaunchOne("A", "Home", {}), {"Error": "Instance limit reached."}) + def test_LoginCheckMarksExpiredAndFillsInUserIds(self): + Answers = {"c-A": ("Expired", None), "c-B": ("Valid", (101, "B", "b")), "c-C": ("Unknown", None)} + with mock.patch.object(ApiModule.Roblox, "CheckLogin", side_effect=lambda Cookie: Answers[Cookie]): + self.Api._CheckLogins(Forever=False) + Expired = {A["Username"]: A["Expired"] for A in self.Api.GetAccounts()} + self.assertEqual(Expired, {"A": True, "B": False, "C": False}) # unknown (offline...) never turns red + self.assertEqual([A["UserId"] for A in Storage.LoadAccounts()], [None, 101, None]) # saved for renewing + Answers["c-A"] = ("Valid", (100, "A", "a")) # e.g. Roblox was briefly unhappy + self.Api._CheckLogins(Forever=False) + self.assertFalse(self.Api.GetAccounts()[0]["Expired"]) + + def test_RenewKeepsTheSameUserAndAddsADifferentOne(self): + self.Api._Accounts[0]["UserId"] = 7 + self.Api._Expired = {"a", "b", "c"} + self.Api.UpdateSetting("SelectedAccounts", ["A"]) + with mock.patch.object(ApiModule.Roblox, "CheckLogin", return_value=("Valid", (7, "A2", "Renamed"))): + self.assertEqual(self.Api._FinishLogin("new-A", "A"), "Renewed") # same user id: renamed on Roblox, same row + with mock.patch.object(ApiModule.Roblox, "CheckLogin", return_value=("Valid", (12, "C", "c"))): + self.assertEqual(self.Api._FinishLogin("new-C", "C"), "Renewed") # no id saved yet: same username counts + with mock.patch.object(ApiModule.Roblox, "CheckLogin", return_value=("Valid", (9, "Other", "o"))): + self.assertEqual(self.Api._FinishLogin("other", "B"), "Added") # someone else signed in: a new account + Accounts = {A["Username"]: A for A in self.Api.GetAccounts()} + self.assertEqual(list(Accounts), ["A2", "B", "C", "Other"]) + self.assertEqual({Name: A["Expired"] for Name, A in Accounts.items()}, {"A2": False, "B": True, "C": False, "Other": False}) + self.assertEqual(self.Api.GetSettings()["SelectedAccounts"], ["A2"]) + self.assertEqual([A["UserId"] for A in Storage.LoadAccounts()], [7, None, 12, 9]) + self.assertIn("Error", self.Api.RenewAccount("Nobody")) + + def test_ExpiredLoginAtLaunchMarksTheAccount(self): + with mock.patch.object(ApiModule.MultiInstance, "CountRunning", return_value=0), \ + mock.patch.object(ApiModule.MultiInstance, "LockCookieFile"), \ + mock.patch.object(ApiModule.MultiInstance, "HoldMutex", return_value=True), \ + mock.patch.object(ApiModule.Roblox, "FindLauncherPath", return_value="C:\\R.exe"), \ + mock.patch.object(ApiModule.Roblox, "GetAuthTicket", return_value=ApiModule.Roblox.LoginExpired): + self.assertEqual(self.Api._LaunchOne("A", "Home", {}), {"Error": ApiModule.ExpiredMessage}) + self.assertTrue(self.Api.GetAccounts()[0]["Expired"]) + def test_RemoveAccountsByName(self): self.Api.UpdateSetting("SelectedAccounts", ["A", "B"]) self.assertEqual(self.Api.RemoveAccounts(["a", "Zed"]), {"Removed": 1}) diff --git a/Production/RAMMIT-Stable/Tests/UiHarness.py b/Production/RAMMIT-Stable/Tests/UiHarness.py index 482f3c3..e300e58 100644 --- a/Production/RAMMIT-Stable/Tests/UiHarness.py +++ b/Production/RAMMIT-Stable/Tests/UiHarness.py @@ -99,7 +99,8 @@ def FakePopen(Args, **_Kw): Roblox.FetchServers = lambda _P, _C=None, MaxPages=10: [dict(S) for S in FakeServers] Roblox.GetGameMaxPlayers = lambda _P: 20 Roblox.ResolveVipLink = lambda Url, _C=None: ("606849621", "AbC123") if "share" in Url or "privateServerLinkCode" in Url else (None, None) -Roblox.GetAuthenticatedUser = lambda Cookie: (Cookie.split("-", 1)[1], "New " + Cookie.split("-", 1)[1]) +Roblox.CheckLogin = lambda Cookie: ("Valid", (int.from_bytes(Cookie.split("-", 1)[1].encode(), "big"), # one id per name + Cookie.split("-", 1)[1], "New " + Cookie.split("-", 1)[1])) Roblox.GetChannel = lambda: Fake["Channel"] Roblox.SetChannel = lambda C: bool(Roblox.ChannelPattern.match(C)) and (Fake.__setitem__("Channel", C) or True) Themes.OpenThemesFolder = lambda: None From ef0b63a18f5a3812e54bec244cd86dab558aa398 Mon Sep 17 00:00:00 2001 From: Paradox Date: Fri, 6 Nov 2026 05:38:21 +0530 Subject: [PATCH 07/11] Installer: Desktop / Start Menu shortcut tick boxes, LAUNCH RAMMIT on the update done screen The Version screen has two tick boxes (both on by default); only the ticked shortcuts are made, the choice is saved in the registry (Shortcuts), and update / repair / undo recreate just those instead of always both. Installs from before have nothing saved and keep both. The done screen says which shortcuts were added. The update / repair / undo done screen gets LAUNCH RAMMIT beside CLOSE, like the install done screen. --- .../Installer/Installer/InstallerApi.py | 7 +++- Production/Installer/Installer/Setup.py | 37 ++++++++++++++----- .../Installer/Installer/Ui/CSS/Installer.css | 6 +++ .../Installer/Ui/HTML/Installer.html | 18 ++++++++- .../Installer/Installer/Ui/JS/Installer.js | 24 +++++++++--- Production/Installer/Tests/TestInstaller.py | 15 +++++++- Production/Installer/Tests/TestUi.mjs | 2 +- Production/RAMMIT-Stable/CHANGELOG.md | 2 + 8 files changed, 90 insertions(+), 21 deletions(-) diff --git a/Production/Installer/Installer/InstallerApi.py b/Production/Installer/Installer/InstallerApi.py index ded2555..cd1bfb1 100644 --- a/Production/Installer/Installer/InstallerApi.py +++ b/Production/Installer/Installer/InstallerApi.py @@ -276,8 +276,10 @@ def StartInstall(self, Version, InstallPath, Options=None): Options = Options if isinstance(Options, dict) else {} LegacyMode, ConfigChoice = Options.get("Legacy", ""), Options.get("ConfigChoice", "") KeptChoice = Options.get("KeptConfig", "") + Shortcuts = Options.get("Shortcuts", list(Setup.ShortcutNames)) # the ticked shortcut boxes if (LegacyMode not in LegacyModes or ConfigChoice not in ConfigChoices or KeptChoice not in KeptChoices - or not isinstance(InstallPath, str)): + or not isinstance(InstallPath, str) or not isinstance(Shortcuts, list) + or not all(Name in Setup.ShortcutNames for Name in Shortcuts)): return {"Error": "Bad request."} LegacyInfo = Legacy.Detect() if LegacyMode else None if LegacyMode and not LegacyInfo: @@ -289,7 +291,8 @@ def Job(): Kept = Setup.FindKeptConfig() if KeptChoice and not LegacyMode else None return Setup.RunInstall(Release["Version"], InstallPath, self._Progress, Release=Release, Kind="Install", LegacyMode=LegacyMode, LegacyPath=LegacyInfo["Path"] if LegacyInfo else "", - ConfigChoice=ConfigChoice or "KeepNew", Kept=Kept, UseKept=KeptChoice == "Use") + ConfigChoice=ConfigChoice or "KeepNew", Kept=Kept, UseKept=KeptChoice == "Use", + Shortcuts=Shortcuts) return self._StartJob("Install", Job) def _InstalledOrError(self): diff --git a/Production/Installer/Installer/Setup.py b/Production/Installer/Installer/Setup.py index 5e61288..508f4f3 100644 --- a/Production/Installer/Installer/Setup.py +++ b/Production/Installer/Installer/Setup.py @@ -169,9 +169,24 @@ def _FolderSize(Folder): # ------------------------------------------------------------ shortcuts (straight at RAMMIT.exe, never PowerShell) -def ShortcutPaths(): +ShortcutNames = ("Desktop", "StartMenu") # the two the installer offers (tick boxes on the Version screen) +ShortcutsValue = "Shortcuts" # registry: which ones were chosen at install, e.g. "Desktop,StartMenu" or "" + + +def ShortcutPath(Name): L = Locations.Current - return [os.path.join(L.DesktopDir, "RAMMIT.lnk"), os.path.join(L.StartMenuDir, "RAMMIT.lnk")] + return os.path.join(L.DesktopDir if Name == "Desktop" else L.StartMenuDir, "RAMMIT.lnk") + + +def ShortcutPaths(): + return [ShortcutPath(Name) for Name in ShortcutNames] + + +def ChosenShortcuts(): + """The shortcuts chosen at install, for an update / repair / undo to recreate. Installs from before the choice + existed have none saved: both, as they always got.""" + Saved = RegRead(ShortcutsValue) + return list(ShortcutNames) if Saved is None else [Name for Name in Saved.split(",") if Name in ShortcutNames] def _Shell(): @@ -190,10 +205,10 @@ def ReadShortcut(LinkPath): return "", "" -def CreateShortcuts(InstallPath): +def CreateShortcuts(InstallPath, Names=ShortcutNames): Exe = os.path.join(InstallPath, "RAMMIT.exe") Shell = _Shell() - for LinkPath in ShortcutPaths(): + for LinkPath in [ShortcutPath(Name) for Name in ShortcutNames if Name in Names]: os.makedirs(os.path.dirname(LinkPath), exist_ok=True) Link = Shell.CreateShortCut(LinkPath) Link.TargetPath = Exe @@ -791,10 +806,12 @@ def CheckTarget(InstallPath, LegacyMode="", LegacyPath=""): def RunInstall(Version, InstallPath, Report, Release=None, CachedSlot="", Kind="Install", - LegacyMode="", LegacyPath="", ConfigChoice="KeepNew", Kept=None, UseKept=True): + LegacyMode="", LegacyPath="", ConfigChoice="KeepNew", Kept=None, UseKept=True, Shortcuts=None): """The whole pipeline (module docstring). Report(**Progress) gets Test1's progress fields. Kept = FindKeptConfig() for a fresh install (UseKept: bring those accounts back or start fresh). - Returns {Version, Branch, Path, Warnings, MovedLegacy, KeptLine, OldVersion}.""" + Shortcuts = the shortcut names ticked for an install; None (update / repair / undo) = the ones chosen at install. + Returns {Version, Branch, Path, Warnings, MovedLegacy, KeptLine, OldVersion, Shortcuts}.""" + Shortcuts = ChosenShortcuts() if Shortcuts is None else [Name for Name in ShortcutNames if Name in Shortcuts] Warnings = [] KeptLine = "" Check = CheckTarget(InstallPath, LegacyMode, LegacyPath) @@ -879,6 +896,7 @@ def OnBytes(Done, Total): Report(StageDetail="Writing registry", StagePct=25, OverallPct=93) RegWrite("InstallPath", InstallPath) RegWrite("Version", Version) + RegWrite(ShortcutsValue, ",".join(Shortcuts)) try: CopySetupExe() WriteUninstallEntry(InstallPath, Version) @@ -887,16 +905,17 @@ def OnBytes(Done, Total): Logger.warning("Apps entry failed: %s", Error) Report(StageDetail="Creating shortcuts", StagePct=60, OverallPct=96) try: - CreateShortcuts(InstallPath) + CreateShortcuts(InstallPath, Shortcuts) except Exception as Error: - Warnings.append("The desktop shortcut couldn't be created.") + Warnings.append("The shortcuts couldn't be created.") Logger.warning("Shortcuts failed: %s", type(Error).__name__) + Shortcuts = [] Report(StageDetail="Saving a copy for Undo", StagePct=85, OverallPct=98) UpdateCache(Version, ZipPath, Sha, OldVersion, FromSlot=CachedSlot, Branch=Branch) Report(StagePct=100, StageDetail="", OverallPct=100) Logger.info("%s finished: v%s in %s (was %s)", Kind, Version, InstallPath, OldVersion or "not installed") return {"Version": Version, "Branch": Branch, "Path": InstallPath, "Warnings": Warnings, "OldVersion": OldVersion, - "MovedLegacy": LegacyMode in ("MoveRemove", "MoveKeep"), "KeptLine": KeptLine} + "MovedLegacy": LegacyMode in ("MoveRemove", "MoveKeep"), "KeptLine": KeptLine, "Shortcuts": Shortcuts} finally: _RemoveStaging(Staging) shutil.rmtree(TempDir, ignore_errors=True) diff --git a/Production/Installer/Installer/Ui/CSS/Installer.css b/Production/Installer/Installer/Ui/CSS/Installer.css index be1216c..67744ba 100644 --- a/Production/Installer/Installer/Ui/CSS/Installer.css +++ b/Production/Installer/Installer/Ui/CSS/Installer.css @@ -679,6 +679,12 @@ body { cursor: pointer; } +/* Two tick boxes on one line (the Desktop / Start Menu shortcut choice). */ +.InstCheckboxPair { + display: flex; + gap: 24px; +} + .InstCheckboxRow input[type="checkbox"] { display: none; } diff --git a/Production/Installer/Installer/Ui/HTML/Installer.html b/Production/Installer/Installer/Ui/HTML/Installer.html index 774a6fb..48c19bc 100644 --- a/Production/Installer/Installer/Ui/HTML/Installer.html +++ b/Production/Installer/Installer/Ui/HTML/Installer.html @@ -132,6 +132,19 @@ Show dev versions +
+ + +
+
-
- +
+ +
diff --git a/Production/Installer/Installer/Ui/JS/Installer.js b/Production/Installer/Installer/Ui/JS/Installer.js index cafc15c..1d8ea88 100644 --- a/Production/Installer/Installer/Ui/JS/Installer.js +++ b/Production/Installer/Installer/Ui/JS/Installer.js @@ -283,7 +283,8 @@ async function StartInstall(ConfigChoice) { ById('InstallPath').value = Check.Path; ResetProgress('Installing RAMMIT...'); Go('Progress', Flow); - StartJob('Install', () => Api.StartInstall(Version, Check.Path, { Legacy: State.LegacyMode, ConfigChoice: ConfigChoice || '', KeptConfig: Kept }), Back); + const Shortcuts = [['ShortcutDesktop', 'Desktop'], ['ShortcutStartMenu', 'StartMenu']].filter(([Id]) => ById(Id).checked).map(([, Name]) => Name); + StartJob('Install', () => Api.StartInstall(Version, Check.Path, { Legacy: State.LegacyMode, ConfigChoice: ConfigChoice || '', KeptConfig: Kept, Shortcuts }), Back); } // '' (nothing kept, or the old Test1 flow), 'Use' (bring the kept accounts back) or 'Fresh' (start without them). @@ -293,6 +294,14 @@ const KeptChoice = () => (State.KeptConfig && !State.LegacyMode ? (ById('UseKept const Warn = Result => (Result.Warnings || []).map(Text => [Text]); +// What the install made, from the ticked shortcut boxes: [] when neither was ticked. +function ShortcutLine(Made) { + const Places = { Desktop: 'the Desktop', StartMenu: 'the Start Menu' }; + const Where = (Made || []).map(Name => Places[Name]).filter(Boolean); + if (!Where.length) return []; + return [[Where.length > 1 ? `Shortcuts were added to ${Where.join(' and ')}.` : `A shortcut was added to ${Where[0]}.`]]; +} + On('Progress', UpdateProgress); On('UninstallProgress', UpdateUninstallProgress); @@ -304,7 +313,7 @@ On('Done', async Result => { ['Installed ', { Em: WithBranch(Result.Version, Result.Branch) }, ' to ', { Em: Result.Path, Class: 'Path' }, '.'], ...(Result.MovedLegacy ? [['Your accounts and settings came across from the old version.']] : []), ...(Result.KeptLine ? [[Result.KeptLine]] : []), - ['A desktop shortcut has been created.'], + ...ShortcutLine(Result.Shortcuts), ...Warn(Result), [], ['Have fun - and ping us if anything breaks.'], @@ -411,11 +420,14 @@ Click('UninstallConfirmBtn', () => StartAction('Uninstall')); Click('InstallDoneCloseBtn', CloseWindow); Click('ActionDoneCloseBtn', CloseWindow); Click('UninstallDoneCloseBtn', CloseWindow); -Click('LaunchBtn', async () => { +// LAUNCH RAMMIT on both done screens (install, and update / repair / undo): starts it and closes the installer. +async function LaunchRammit(DoneScreen) { const Result = await Api.Launch(); - if (Result && Result.Error) ShowError(Result.Error, '', null, () => Go('InstallDone'), "RAMMIT didn't start."); + if (Result && Result.Error) ShowError(Result.Error, '', null, () => Go(DoneScreen), "RAMMIT didn't start."); else CloseWindow(); -}); +} +Click('LaunchBtn', () => LaunchRammit('InstallDone')); +Click('ActionLaunchBtn', () => LaunchRammit('ActionDone')); // Older RAMMIT found Click('LegacyMoveRemoveBtn', () => { @@ -500,7 +512,7 @@ ById('InstallPath').addEventListener('input', () => { ById('PathError').textCont async function Boot() { // A reload can bring back old tick boxes (browser form restore) that no longer match State. document.querySelectorAll('.ShowTestVersions, #RemoveConfigs, #LegacyDontAsk').forEach(Box => { Box.checked = false; }); - ById('UseKept').checked = true; + ['UseKept', 'ShortcutDesktop', 'ShortcutStartMenu'].forEach(Id => { ById(Id).checked = true; }); WatchSize(); BuildCrumbs(); FitWindow(); diff --git a/Production/Installer/Tests/TestInstaller.py b/Production/Installer/Tests/TestInstaller.py index 8ad87c5..0ee588f 100644 --- a/Production/Installer/Tests/TestInstaller.py +++ b/Production/Installer/Tests/TestInstaller.py @@ -355,6 +355,19 @@ def test_shortcuts_removed_when_paths_differ_only_by_short_names(self): Setup.RemoveShortcuts(Short) self.assertFalse(any(os.path.exists(P) for P in Setup.ShortcutPaths())) + def test_ShortcutsAreTheTickedOnesAndUpdatesKeepTheChoice(self): + Desktop, StartMenu = Setup.ShortcutPath("Desktop"), Setup.ShortcutPath("StartMenu") + self.assertEqual(self.Install("1.0.0", Shortcuts=["StartMenu"])["Shortcuts"], ["StartMenu"]) + self.assertEqual((os.path.isfile(Desktop), os.path.isfile(StartMenu)), (False, True)) + self.assertEqual(Setup.RegRead(Setup.ShortcutsValue), "StartMenu") + self.Install("1.1.0", Kind="Update") # no choice passed: the one made at install + self.assertEqual((os.path.isfile(Desktop), os.path.isfile(StartMenu)), (False, True)) + os.remove(StartMenu) + self.assertEqual(self.Install("1.1.0", Shortcuts=[])["Shortcuts"], []) # neither ticked + self.assertEqual((os.path.isfile(Desktop), os.path.isfile(StartMenu)), (False, False)) + Setup.RegDeleteValue(Setup.ShortcutsValue) # an install from before the choice existed: both, as always + self.assertEqual(Setup.ChosenShortcuts(), ["Desktop", "StartMenu"]) + def test_uninstall_with_config_removes_config_and_backups_only(self): self.Install("1.0.0") Write(os.path.join(self.Target, "Config", "Settings.json"), "{}") @@ -435,7 +448,7 @@ def test_reinstall_elsewhere_brings_accounts_and_backups_and_removes_the_old_fol self.assertIn("KeptTester", Read(os.path.join(self.Other, "Config", "Accounts.json"))) self.assertEqual(len(os.listdir(os.path.join(self.Other, "Config.Backup"))), 1) self.assertFalse(os.path.exists(self.Target)) - self.assertEqual(set(Support.RegValues(self.L.RegKeyPath)), {"InstallPath", "Version"}) + self.assertEqual(set(Support.RegValues(self.L.RegKeyPath)), {"InstallPath", "Version", "Shortcuts"}) self.assertIsNone(Setup.FindKeptConfig()) def test_reinstall_same_folder_fresh_puts_accounts_aside(self): diff --git a/Production/Installer/Tests/TestUi.mjs b/Production/Installer/Tests/TestUi.mjs index 80ac340..d6334ec 100644 --- a/Production/Installer/Tests/TestUi.mjs +++ b/Production/Installer/Tests/TestUi.mjs @@ -215,7 +215,7 @@ try { await Shot('07-InstallDone', 'InstallDone'); const DoneText = await Text('#InstallDoneText'); Check('install done: Test1 wording with real version + path', DoneText.startsWith('Installed v1.0.0 to ') && DoneText.includes(DefaultPath) - && DoneText.includes('A desktop shortcut has been created.') && DoneText.includes('Have fun - and ping us if anything breaks.'), DoneText); + && DoneText.includes('Shortcuts were added to the Desktop and the Start Menu.') && DoneText.includes('Have fun - and ping us if anything breaks.'), DoneText); let St = await Hook('State'); Check('install: registry + Apps entry written (test keys)', St.Registry && St.Registry.Version === '1.0.0' && St.Apps && St.Apps.DisplayVersion === '1.0.0'); await ClickBtn('LaunchBtn'); diff --git a/Production/RAMMIT-Stable/CHANGELOG.md b/Production/RAMMIT-Stable/CHANGELOG.md index 62bbced..c4916fb 100644 --- a/Production/RAMMIT-Stable/CHANGELOG.md +++ b/Production/RAMMIT-Stable/CHANGELOG.md @@ -7,6 +7,8 @@ - **Installer:** pressing **Ignore** on the "older test version" screen without ticking "Don't ask again" now puts it off instead of asking every time: the menu opens as normal, with an **OLD VERSION** button and a line saying where the old version is. It stays reachable after installing the new RAMMIT, and goes away once the old version is moved or removed. - **Installer:** with RAMMIT already installed, the old version's screen keeps all four choices. The two "move my accounts" choices then copy its accounts and settings into the installed RAMMIT without reinstalling it, and the first one removes the old version afterwards. - **Installer:** the "Uninstall Config/ folder too" tick box no longer shows its check mark while unticked (#2). +- **Installer:** you choose whether to get a **Desktop shortcut** and a **Start Menu shortcut** (both ticked by default), and the done screen says which were added. Updates, repairs and undo keep that choice instead of always recreating both. +- **Installer:** the update / repair / undo done screen has **LAUNCH RAMMIT** next to **CLOSE**, like the install done screen. - **Launch tracking:** RAMMIT now knows which Roblox client belongs to which account. It follows the process it started, including when Roblox hands the game to a child process that opens the window, and falls back to matching each launch's one-time ticket on the client's command line. An account shows "•••" while Roblox starts, "✓" only once its game window is open, and its mark clears when that window closes, so you can see which account closed. The running counter only counts open game windows: launches still starting count only towards Max Instances, and Roblox's tray process (started when a game closes) and its right-click menu no longer count at all. The status line under the launch button only says "Launched" once the accounts' windows are open (it stops waiting after 30 seconds). - **Expired logins** (back from the Test1 build): saved logins are checked at start-up and every 5 minutes, and an account whose login Roblox rejects turns red. With exactly that account selected, **+ ADD** becomes **RENEW** and **LAUNCH** becomes **RENEW AND LAUNCH**, which signs you in again first. Renewing keeps the account if the same Roblox user signs in (checked by user ID, so a renamed account still counts); a different user is added as a new account instead. A launch that Roblox rejects also marks the account. A check that can't reach Roblox never marks anything. - **Tooltips:** every button and setting has a tooltip, drawn in the theme's own colours instead of the plain Windows one. It follows the cursor and flips to the other side near the window's edges. CBlock's are rounded; a custom theme can set `--TooltipRadius`. From 92b11b2bfcc211039333ff0e5f0457baaa21753d Mon Sep 17 00:00:00 2001 From: Paradox Date: Fri, 6 Nov 2026 05:47:57 +0530 Subject: [PATCH 08/11] README: spell out RAMMIT (Roblox Account Manager and Multi Instance Tool) --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 0ccf858..c880997 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@ # RAMMIT +Roblox Account Manager and Multi Instance Tool + **Save your Roblox accounts once, tick the ones you want, and open a separate Roblox window for each with one click.** A free, open-source Windows app. [![CI](https://github.com/CBlockDigital/RAMMIT/actions/workflows/CI.yml/badge.svg)](https://github.com/CBlockDigital/RAMMIT/actions/workflows/CI.yml) From e0d7b3d8105b4fb2367207a900cebc1adb72fb99 Mon Sep 17 00:00:00 2001 From: Paradox Date: Fri, 6 Nov 2026 06:05:25 +0530 Subject: [PATCH 09/11] Installer: 'don't ask again' for the old version is LegacyInstallPath=Ignore One registry value instead of two: LegacyInstallPath holds the put-off old folder, or 'Ignore' once the user ticked 'don't ask again' and pressed Ignore (for good, no undo). IgnoreLegacyInstall=1 from installers before 1.1.2 is carried over on the next run and then removed. --- Production/Installer/Installer/Legacy.py | 18 ++++++++++++------ Production/Installer/Installer/Locations.py | 2 +- Production/Installer/Installer/Setup.py | 2 +- Production/Installer/Tests/TestInstaller.py | 10 ++++++++-- Production/Installer/Tests/TestUi.mjs | 2 +- 5 files changed, 23 insertions(+), 11 deletions(-) diff --git a/Production/Installer/Installer/Legacy.py b/Production/Installer/Installer/Legacy.py index 77bede2..9040c66 100644 --- a/Production/Installer/Installer/Legacy.py +++ b/Production/Installer/Installer/Legacy.py @@ -10,8 +10,8 @@ 1. MoveRemove copy Config\\ files into the new install, then Remove(IncludeConfig=True) 2. MoveKeep copy Config\\ files into the new install, leave the old one alone 3. Remove Remove(IncludeConfig=True) without copying (the UI asks to confirm first) - 4. Ignore with "don't ask again" the registry gets IgnoreLegacyInstall=1; without it, LegacyInstallPath=, - and later runs open the menu with an OLD VERSION button instead of this screen + 4. Ignore with "don't ask again" the registry gets LegacyInstallPath=Ignore (for good, no undo); without it, + LegacyInstallPath=, and later runs open the menu with an OLD VERSION button instead of this screen Only names Test1 is known to ship are ever deleted. Account files are copied as files and never read (they hold login cookies); "has accounts" is judged by file size alone. @@ -51,12 +51,18 @@ def ReadVersion(Folder): return Version if re.match(r"^[0-9A-Za-z.\-]{1,20}$", Version) else "" +IgnoredForGood = "Ignore" # LegacyInstallPath's value once the user ticked "don't ask again" and pressed Ignore +OldIgnoreValue = "IgnoreLegacyInstall" # where installers before 1.1.2 kept that; moved over by Detect() + + def Detect(): """{Path, Version, Shortcuts, Deferred} for a Test1 install the registry points at (InstallPath, or LegacyInstallPath once the user pressed Ignore), unless the user said never ask again. Deferred = it was put off with Ignore.""" - if Setup.RegRead("IgnoreLegacyInstall") == "1": - return None + if Setup.RegRead(OldIgnoreValue) == "1": # installers before 1.1.2 kept "don't ask again" in its own value + Ignore(True) PutOff = Setup.RegRead("LegacyInstallPath") + if PutOff == IgnoredForGood: + return None for Folder in (Setup.RegRead("InstallPath"), PutOff): if Folder and os.path.isdir(Folder) and IsLegacyFolder(Folder): return {"Path": Folder, "Version": ReadVersion(Folder), "Shortcuts": FindShortcuts(), @@ -175,8 +181,8 @@ def Ignore(DontAskAgain, Folder=""): """Ticked: never ask again. Unticked: remember the folder, so it stays reachable from the menu (even after a new install takes over InstallPath) without blocking the way in.""" if DontAskAgain: - Setup.RegWrite("IgnoreLegacyInstall", "1") - Setup.RegDeleteValue("LegacyInstallPath") + Setup.RegWrite("LegacyInstallPath", IgnoredForGood) + Setup.RegDeleteValue(OldIgnoreValue) elif Folder: Setup.RegWrite("LegacyInstallPath", Folder) diff --git a/Production/Installer/Installer/Locations.py b/Production/Installer/Installer/Locations.py index b2be301..fe03e77 100644 --- a/Production/Installer/Installer/Locations.py +++ b/Production/Installer/Installer/Locations.py @@ -1,7 +1,7 @@ """Every folder and registry key the installer touches, resolved in one place. Normal mode (what users get): - registry HKCU\\Software\\CBlock Digital\\RAMMIT InstallPath, Version, IgnoreLegacyInstall + registry HKCU\\Software\\CBlock Digital\\RAMMIT InstallPath, Version, LegacyInstallPath Apps list HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\RAMMIT shortcuts \\RAMMIT.lnk and \\Programs\\RAMMIT.lnk install %LOCALAPPDATA%\\RAMMIT (default, the user can pick another folder) diff --git a/Production/Installer/Installer/Setup.py b/Production/Installer/Installer/Setup.py index 508f4f3..e8d54f7 100644 --- a/Production/Installer/Installer/Setup.py +++ b/Production/Installer/Installer/Setup.py @@ -977,7 +977,7 @@ def RunUninstall(InstallPath, RemoveConfig, Report): except OSError: pass ConfigKept = _HasFiles(os.path.join(InstallPath, "Config")) - # Registry: the whole key goes (InstallPath, Version, IgnoreLegacyInstall, any old Test1 values). When Config + # Registry: the whole key goes (InstallPath, Version, LegacyInstallPath, any old Test1 values). When Config # stays, one value remembers where, so the next install can offer those accounts again (FindKeptConfig). RegDeleteKey() if ConfigKept: diff --git a/Production/Installer/Tests/TestInstaller.py b/Production/Installer/Tests/TestInstaller.py index 0ee588f..2d99a95 100644 --- a/Production/Installer/Tests/TestInstaller.py +++ b/Production/Installer/Tests/TestInstaller.py @@ -388,7 +388,7 @@ def test_clean_uninstall_removes_the_folder(self): def test_full_uninstall_leaves_no_registry_key_and_no_setup_folder(self): self.Install("1.0.0") - Setup.RegWrite("IgnoreLegacyInstall", "1") + Legacy.Ignore(True) Write(self.L.LogFile, "old log") Write(self.L.LogFile + ".1", "older log") Setup.RunUninstall(self.Target, True, NoReport) @@ -642,8 +642,14 @@ def test_Choice4IgnoreWithoutDontAskPutsItOff(self): def test_Choice4DontAskAgainForgetsAPutOffOne(self): Legacy.Ignore(False, self.Old) Legacy.Ignore(True) - self.assertIsNone(Setup.RegRead("LegacyInstallPath")) + self.assertEqual(Setup.RegRead("LegacyInstallPath"), Legacy.IgnoredForGood) + self.assertIsNone(Legacy.Detect()) + + def test_OldDontAskAgainValueIsCarriedOver(self): + Setup.RegWrite(Legacy.OldIgnoreValue, "1") # what installers before 1.1.2 wrote self.assertIsNone(Legacy.Detect()) + self.assertIsNone(Setup.RegRead(Legacy.OldIgnoreValue)) + self.assertEqual(Setup.RegRead("LegacyInstallPath"), Legacy.IgnoredForGood) def test_Choice2MoveAndKeepForgetsAPutOffOne(self): Legacy.Ignore(False, self.Old) diff --git a/Production/Installer/Tests/TestUi.mjs b/Production/Installer/Tests/TestUi.mjs index d6334ec..0bc9046 100644 --- a/Production/Installer/Tests/TestUi.mjs +++ b/Production/Installer/Tests/TestUi.mjs @@ -370,7 +370,7 @@ try { await Page.click('[data-screen=Legacy] .InstCheckboxRow'); await ClickBtn('LegacyIgnoreBtn'); await OnScreen('MenuFresh'); - Check('ignore + don\'t ask again saved', (await Hook('State')).Registry.IgnoreLegacyInstall === '1'); + Check('ignore + don\'t ask again saved', (await Hook('State')).Registry.LegacyInstallPath === 'Ignore'); await Open(); Check('not asked again', await OnScreen('MenuFresh')); From b54cb5b24c2e0e99d9b70ec9fb93e9a94dbc9109 Mon Sep 17 00:00:00 2001 From: Paradox Date: Fri, 6 Nov 2026 06:19:46 +0530 Subject: [PATCH 10/11] Shortcuts open the RAMMIT: protocol, and RAMMIT re-points it when its folder was moved The installer registers HKCU\Software\Classes\RAMMIT (starts RAMMIT.exe, no link data passed on) and makes RAMMIT.url shortcuts that open RAMMIT:, with the icon copied to RAMMIT-Setup\ so it never moves. Its own old RAMMIT.lnk shortcuts are replaced; uninstall removes the .url files and the protocol. App/Install.Sync (frozen exe only, at start-up): when the installer's InstallPath has no RAMMIT.exe any more and RAMMIT runs from elsewhere, the folder was moved, so InstallPath, the protocol and the Apps entry are pointed here and every RAMMIT: shortcut works again, wherever it is. A second copy started while the installed one is in place changes nothing. Test mode uses its own protocol name and refuses the real one. --- Production/Installer/Installer/Legacy.py | 2 +- Production/Installer/Installer/Locations.py | 14 +- Production/Installer/Installer/Setup.py | 134 +++++++++++++++--- Production/Installer/Tests/Support.py | 13 ++ Production/Installer/Tests/TestEndToEnd.py | 3 +- Production/Installer/Tests/TestInstaller.py | 51 +++++-- Production/Installer/Tests/UiHarness.py | 2 + Production/RAMMIT-Stable/App/Install.py | 62 ++++++++ Production/RAMMIT-Stable/App/Main.py | 14 +- Production/RAMMIT-Stable/CHANGELOG.md | 2 + Production/RAMMIT-Stable/README.md | 1 + Production/RAMMIT-Stable/Tests/TestBackend.py | 55 +++++++ 12 files changed, 311 insertions(+), 42 deletions(-) create mode 100644 Production/RAMMIT-Stable/App/Install.py diff --git a/Production/Installer/Installer/Legacy.py b/Production/Installer/Installer/Legacy.py index 9040c66..c1e4ace 100644 --- a/Production/Installer/Installer/Legacy.py +++ b/Production/Installer/Installer/Legacy.py @@ -150,7 +150,7 @@ def Remove(Folder, IncludeConfig): def FindShortcuts(): """Test1's RAMMIT.lnk files: they start PowerShell, which reads the registry and runs RAMMIT.exe.""" Found = [] - for LinkPath in Setup.ShortcutPaths(): + for LinkPath in Setup.LinkPaths(): if os.path.isfile(LinkPath): Target, Arguments = Setup.ReadShortcut(LinkPath) if Target.lower().endswith("powershell.exe") and "cblock digital" in Arguments.lower(): diff --git a/Production/Installer/Installer/Locations.py b/Production/Installer/Installer/Locations.py index fe03e77..ea9777e 100644 --- a/Production/Installer/Installer/Locations.py +++ b/Production/Installer/Installer/Locations.py @@ -3,14 +3,17 @@ Normal mode (what users get): registry HKCU\\Software\\CBlock Digital\\RAMMIT InstallPath, Version, LegacyInstallPath Apps list HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\RAMMIT - shortcuts \\RAMMIT.lnk and \\Programs\\RAMMIT.lnk + protocol HKCU\\Software\\Classes\\RAMMIT (RAMMIT: starts RAMMIT.exe; the shortcuts open it) + shortcuts \\RAMMIT.url and \\Programs\\RAMMIT.url install %LOCALAPPDATA%\\RAMMIT (default, the user can pick another folder) - setup copy %LOCALAPPDATA%\\RAMMIT-Setup\\RAMMIT-Setup.exe, Cache\\ (zips for Undo), Setup.log + setup copy %LOCALAPPDATA%\\RAMMIT-Setup\\RAMMIT-Setup.exe, RAMMIT.ico (shortcut icon), Cache\\ (zips for Undo), + Setup.log Test mode (environment variable RAMMIT_INSTALLER_TEST=1) moves ALL of it somewhere harmless, so tests and manual try-outs can never touch a real install: registry HKCU\\Software\\CBlock Digital\\RAMMIT-InstallerTest (override: RAMMIT_INSTALLER_REGKEY) Apps list ...\\Uninstall\\RAMMIT-InstallerTest (override: RAMMIT_INSTALLER_UNINSTALL_NAME) + protocol ...\\Classes\\RAMMIT-InstallerTest (override: RAMMIT_INSTALLER_PROTOCOL) folders %TEMP%\\RAMMIT-InstallerTest\\{Desktop, StartMenu, LocalAppData} (override: RAMMIT_INSTALLER_TEST_ROOT) releases RAMMIT_INSTALLER_RELEASES_URL may point at a fake release server (ignored outside test mode) @@ -22,6 +25,7 @@ RealRegKeyPath = r"Software\CBlock Digital\RAMMIT" UninstallParentPath = r"Software\Microsoft\Windows\CurrentVersion\Uninstall" RealUninstallName = "RAMMIT" +RealProtocolName = "RAMMIT" SetupExeName = "RAMMIT-Setup.exe" @@ -34,6 +38,7 @@ def __init__(self): self.TestRoot = Root self.RegKeyPath = os.environ.get("RAMMIT_INSTALLER_REGKEY") or r"Software\CBlock Digital\RAMMIT-InstallerTest" self.UninstallName = os.environ.get("RAMMIT_INSTALLER_UNINSTALL_NAME") or "RAMMIT-InstallerTest" + self.ProtocolName = os.environ.get("RAMMIT_INSTALLER_PROTOCOL") or "RAMMIT-InstallerTest" self.DesktopDir = os.path.join(Root, "Desktop") self.StartMenuDir = os.path.join(Root, "StartMenu") LocalAppData = os.path.join(Root, "LocalAppData") @@ -42,17 +47,20 @@ def __init__(self): self.TestRoot = "" self.RegKeyPath = RealRegKeyPath self.UninstallName = RealUninstallName + self.ProtocolName = RealProtocolName self.DesktopDir = _KnownFolder("Desktop", os.path.join(os.environ.get("USERPROFILE", ""), "Desktop")) self.StartMenuDir = os.path.join(os.environ.get("APPDATA", ""), "Microsoft", "Windows", "Start Menu", "Programs") LocalAppData = os.environ.get("LOCALAPPDATA", "") self.ReleasesUrlOverride = "" self.UninstallKeyPath = UninstallParentPath + "\\" + self.UninstallName + self.ProtocolKeyPath = r"Software\Classes" + "\\" + self.ProtocolName self.DefaultInstallPath = os.path.join(LocalAppData, "RAMMIT") # Kept OUTSIDE the install folder: the folder swap and the manifest-only uninstall never touch it. self.SetupDir = os.path.join(LocalAppData, "RAMMIT-Setup") self.CacheDir = os.path.join(self.SetupDir, "Cache") self.LogFile = os.path.join(self.SetupDir, "Setup.log") self.SetupExePath = os.path.join(self.SetupDir, SetupExeName) + self.IconPath = os.path.join(self.SetupDir, "RAMMIT.ico") # the shortcuts' icon: here, it never moves self._CheckTestModeIsolated() def _CheckTestModeIsolated(self): @@ -64,6 +72,8 @@ def _CheckTestModeIsolated(self): Problems.append("registry key") if self.UninstallName.lower() == RealUninstallName.lower() or "test" not in self.UninstallName.lower(): Problems.append("uninstall entry") + if self.ProtocolName.lower() == RealProtocolName.lower() or "test" not in self.ProtocolName.lower(): + Problems.append("protocol") RealLocal = os.path.normcase(os.path.join(os.environ.get("LOCALAPPDATA", "?"), "RAMMIT")) if os.path.normcase(self.DefaultInstallPath) == RealLocal: Problems.append("install folder") diff --git a/Production/Installer/Installer/Setup.py b/Production/Installer/Installer/Setup.py index e8d54f7..4bde810 100644 --- a/Production/Installer/Installer/Setup.py +++ b/Production/Installer/Installer/Setup.py @@ -167,21 +167,85 @@ def _FolderSize(Folder): return Total -# ------------------------------------------------------------ shortcuts (straight at RAMMIT.exe, never PowerShell) +# ------------------------------------------------------------ shortcuts (RAMMIT.url files that open RAMMIT:) +# A shortcut that names a path breaks when the RAMMIT folder is moved. These open the RAMMIT: protocol instead +# (HKCU\Software\Classes\RAMMIT, pointing at RAMMIT.exe), which RAMMIT points back at itself when it starts from a +# moved folder (App/Install.py), so every shortcut keeps working wherever it is, copies the user made included. +# Their icon is a copy in RAMMIT-Setup\, which never moves. Installers before 1.1.2 made RAMMIT.lnk files straight +# at RAMMIT.exe (and Test1 made PowerShell ones, see Legacy.py); ours are replaced by .url ones on the next install. ShortcutNames = ("Desktop", "StartMenu") # the two the installer offers (tick boxes on the Version screen) ShortcutsValue = "Shortcuts" # registry: which ones were chosen at install, e.g. "Desktop,StartMenu" or "" -def ShortcutPath(Name): +def _ShortcutDir(Name): L = Locations.Current - return os.path.join(L.DesktopDir if Name == "Desktop" else L.StartMenuDir, "RAMMIT.lnk") + return L.DesktopDir if Name == "Desktop" else L.StartMenuDir + + +def ShortcutPath(Name): + return os.path.join(_ShortcutDir(Name), "RAMMIT.url") def ShortcutPaths(): return [ShortcutPath(Name) for Name in ShortcutNames] +def LinkPaths(): + """Where the RAMMIT.lnk shortcuts of Test1 and of installers before 1.1.2 are.""" + return [os.path.join(_ShortcutDir(Name), "RAMMIT.lnk") for Name in ShortcutNames] + + +def _DeleteKeyTree(KeyPath): + try: + with winreg.OpenKey(winreg.HKEY_CURRENT_USER, KeyPath) as Key: + SubKeys = [winreg.EnumKey(Key, Index) for Index in range(winreg.QueryInfoKey(Key)[0])] + except OSError: + return + for Name in SubKeys: + _DeleteKeyTree(KeyPath + "\\" + Name) + RegDeleteKey(KeyPath) + + +def RegisterProtocol(InstallPath): + """RAMMIT: starts this install's RAMMIT.exe. Nothing from the link is passed on, so a RAMMIT: link on a web page can + only open RAMMIT (after the browser asks), nothing more.""" + L = Locations.Current + Exe = os.path.join(InstallPath, "RAMMIT.exe") + for Sub, Value in (("", f"URL:{L.ProtocolName}"), ("DefaultIcon", f'"{Exe}",0'), (r"shell\open\command", f'"{Exe}"')): + with winreg.CreateKeyEx(winreg.HKEY_CURRENT_USER, L.ProtocolKeyPath + ("\\" + Sub if Sub else ""), 0, + winreg.KEY_WRITE) as Key: + winreg.SetValueEx(Key, "", 0, winreg.REG_SZ, Value) + if not Sub: + winreg.SetValueEx(Key, "URL Protocol", 0, winreg.REG_SZ, "") + + +def ProtocolTarget(): + """The RAMMIT.exe that RAMMIT: starts, or "" when it isn't registered.""" + Command = RegRead("", Locations.Current.ProtocolKeyPath + r"\shell\open\command") or "" + return Command.strip().strip('"') + + +def UnregisterProtocol(): + _DeleteKeyTree(Locations.Current.ProtocolKeyPath) + + +def ReadUrlShortcut(Path): + """The URL= of a .url shortcut, or "" when it can't be read.""" + try: + with open(Path, encoding="mbcs", errors="replace") as File: + for Line in File: + if Line.lower().startswith("url="): + return Line[4:].strip() + except OSError: + pass + return "" + + +def IsOurShortcut(Path): + return ReadUrlShortcut(Path).lower() == Locations.Current.ProtocolName.lower() + ":" + + def ChosenShortcuts(): """The shortcuts chosen at install, for an update / repair / undo to recreate. Installs from before the choice existed have none saved: both, as they always got.""" @@ -205,32 +269,54 @@ def ReadShortcut(LinkPath): return "", "" -def CreateShortcuts(InstallPath, Names=ShortcutNames): - Exe = os.path.join(InstallPath, "RAMMIT.exe") - Shell = _Shell() - for LinkPath in [ShortcutPath(Name) for Name in ShortcutNames if Name in Names]: - os.makedirs(os.path.dirname(LinkPath), exist_ok=True) - Link = Shell.CreateShortCut(LinkPath) - Link.TargetPath = Exe - Link.Arguments = "" - Link.WorkingDirectory = InstallPath - Link.IconLocation = Exe + ",0" - Link.Description = "RAMMIT - Roblox Multi-Account Launcher" - Link.save() +def _ShortcutIcon(InstallPath): + """A copy of RAMMIT's icon in RAMMIT-Setup\\ (stays put when the RAMMIT folder moves), or RAMMIT.exe itself.""" + L = Locations.Current + Source = os.path.join(InstallPath, "Src", "Dark", "RAMMIT.ico") + try: + if os.path.isfile(Source): + os.makedirs(L.SetupDir, exist_ok=True) + shutil.copyfile(Source, L.IconPath) + except OSError as Error: + Logger.warning("Shortcut icon not copied: %s", type(Error).__name__) + return L.IconPath if os.path.isfile(L.IconPath) else os.path.join(InstallPath, "RAMMIT.exe") -def RemoveShortcuts(InstallPath): - """Removes RAMMIT.lnk only where it points at this install's RAMMIT.exe.""" +def CreateShortcuts(InstallPath, Names=ShortcutNames): + """RAMMIT.url for each ticked name (register the protocol first). Our old RAMMIT.lnk files go.""" + _RemoveOldLinks(InstallPath) + Icon = _ShortcutIcon(InstallPath) + Text = f"[InternetShortcut]\nURL={Locations.Current.ProtocolName}:\nIconFile={Icon}\nIconIndex=0\n" + for Path in [ShortcutPath(Name) for Name in ShortcutNames if Name in Names]: + os.makedirs(os.path.dirname(Path), exist_ok=True) + with open(Path, "w", encoding="mbcs", errors="replace") as File: + File.write(Text) + + +def _RemoveOldLinks(InstallPath): + """Removes RAMMIT.lnk only where it points at this install's RAMMIT.exe (made by installers before 1.1.2).""" Exe = os.path.join(InstallPath, "RAMMIT.exe") - for LinkPath in ShortcutPaths(): + for LinkPath in LinkPaths(): if os.path.isfile(LinkPath): Target, _Args = ReadShortcut(LinkPath) # SamePath resolves 8.3 short names (C:\Users\RUNNER~1) the .lnk may store differently from ours. if Target and Paths.SamePath(Target, Exe): - try: - os.remove(LinkPath) - except OSError as Error: - Logger.warning("Could not remove shortcut %s: %s", LinkPath, type(Error).__name__) + _RemoveFile(LinkPath) + + +def RemoveShortcuts(InstallPath): + """Removes our RAMMIT.url files, and RAMMIT.lnk files pointing at this install's RAMMIT.exe.""" + _RemoveOldLinks(InstallPath) + for Path in ShortcutPaths(): + if os.path.isfile(Path) and IsOurShortcut(Path): + _RemoveFile(Path) + + +def _RemoveFile(Path): + try: + os.remove(Path) + except OSError as Error: + Logger.warning("Could not remove shortcut %s: %s", Path, type(Error).__name__) # ------------------------------------------------------------ folders @@ -905,6 +991,7 @@ def OnBytes(Done, Total): Logger.warning("Apps entry failed: %s", Error) Report(StageDetail="Creating shortcuts", StagePct=60, OverallPct=96) try: + RegisterProtocol(InstallPath) CreateShortcuts(InstallPath, Shortcuts) except Exception as Error: Warnings.append("The shortcuts couldn't be created.") @@ -985,6 +1072,7 @@ def RunUninstall(InstallPath, RemoveConfig, Report): TidyRegistry() RemoveUninstallEntry() RemoveShortcuts(InstallPath) + UnregisterProtocol() Report(Pct=100) Logger.info("Uninstalled %s (config removed: %s, kept: %s, left: %d)", InstallPath, RemoveConfig, ConfigKept, len(Left)) RemoveSetupFolder() @@ -1004,7 +1092,7 @@ def RemoveSetupFolder(): ClearCache() import Log Log.Close() - for Name in ("Setup.log", "Setup.log.1"): + for Name in ("Setup.log", "Setup.log.1", os.path.basename(L.IconPath)): try: os.remove(os.path.join(L.SetupDir, Name)) except OSError: diff --git a/Production/Installer/Tests/Support.py b/Production/Installer/Tests/Support.py index bdecd15..48c31bb 100644 --- a/Production/Installer/Tests/Support.py +++ b/Production/Installer/Tests/Support.py @@ -41,11 +41,13 @@ def __init__(self, Label="Unit"): self.Root = tempfile.mkdtemp(prefix=f"RAMMIT-InstallerTest-{Label}-") self.RegKey = rf"Software\CBlock Digital\RAMMIT-InstallerTest-{Tag}" self.UninstallName = f"RAMMIT-InstallerTest-{Tag}" + self.ProtocolName = f"RAMMIT-InstallerTest-{Tag}" os.environ.update({ "RAMMIT_INSTALLER_TEST": "1", "RAMMIT_INSTALLER_TEST_ROOT": self.Root, "RAMMIT_INSTALLER_REGKEY": self.RegKey, "RAMMIT_INSTALLER_UNINSTALL_NAME": self.UninstallName, + "RAMMIT_INSTALLER_PROTOCOL": self.ProtocolName, }) import Locations self.Locations = Locations.Reload() @@ -62,6 +64,8 @@ def Cleanup(self): winreg.DeleteKey(winreg.HKEY_CURRENT_USER, Path) except OSError: pass + import Setup + Setup._DeleteKeyTree(r"Software\Classes" + "\\" + self.ProtocolName) DeleteEmptyParent(self.RegKey) shutil.rmtree(self.Root, ignore_errors=True) @@ -147,6 +151,15 @@ def MakeLegacyShortcut(LinkPath): Link.save() +def MakeOldShortcut(LinkPath, Exe): + """What installers before 1.1.2 made: RAMMIT.lnk straight at RAMMIT.exe.""" + import win32com.client + os.makedirs(os.path.dirname(LinkPath), exist_ok=True) + Link = win32com.client.Dispatch("WScript.Shell").CreateShortCut(LinkPath) + Link.TargetPath = Exe + Link.save() + + class FakeReleaseServer: """A local stand-in for api.github.com + the release downloads. diff --git a/Production/Installer/Tests/TestEndToEnd.py b/Production/Installer/Tests/TestEndToEnd.py index 6222b83..6ab93ff 100644 --- a/Production/Installer/Tests/TestEndToEnd.py +++ b/Production/Installer/Tests/TestEndToEnd.py @@ -84,7 +84,8 @@ def test_full_story(self): self.assertGreater(Entry["EstimatedSize"], 10000) for LinkPath in Setup.ShortcutPaths(): self.assertTrue(LinkPath.startswith(self.Env.Root)) - self.assertEqual(os.path.normcase(Setup.ReadShortcut(LinkPath)[0]), os.path.normcase(self.File("RAMMIT.exe"))) + self.assertEqual(Setup.ReadUrlShortcut(LinkPath), self.L.ProtocolName + ":") + self.assertEqual(os.path.normcase(Setup.ProtocolTarget()), os.path.normcase(self.File("RAMMIT.exe"))) State = self.Api.GetState() self.assertEqual((State["Installed"], State["Version"], State["UndoVersion"]), (True, "1.0.0", "")) self.assertTrue(self.Api.ListVersions(False)["UpdateAvailable"]) diff --git a/Production/Installer/Tests/TestInstaller.py b/Production/Installer/Tests/TestInstaller.py index 2d99a95..0d699ea 100644 --- a/Production/Installer/Tests/TestInstaller.py +++ b/Production/Installer/Tests/TestInstaller.py @@ -218,10 +218,9 @@ def test_fresh_install_writes_manifest_registry_entry_and_shortcuts(self): self.assertEqual(Entry["DisplayVersion"], "1.0.0") self.assertIn("/Uninstall", Entry["UninstallString"]) self.assertEqual(Entry["InstallLocation"], self.Target) - for LinkPath in Setup.ShortcutPaths(): - Target, Arguments = Setup.ReadShortcut(LinkPath) - self.assertTrue(Paths.SamePath(Target, os.path.join(self.Target, "RAMMIT.exe")), Target) - self.assertEqual(Arguments, "") + for LinkPath in Setup.ShortcutPaths(): # open RAMMIT:, which starts this install's RAMMIT.exe + self.assertEqual(Setup.ReadUrlShortcut(LinkPath), self.L.ProtocolName + ":") + self.assertTrue(Paths.SamePath(Setup.ProtocolTarget(), os.path.join(self.Target, "RAMMIT.exe")), Setup.ProtocolTarget()) self.assertFalse(os.path.exists(self.Target + Setup.StagingSuffix)) self.assertFalse(os.path.exists(os.path.join(self.Target, Setup.StagingMarker))) self.assertEqual(Setup.CachedRelease("Installed")["Version"], "1.0.0") @@ -338,10 +337,11 @@ def test_manifest_only_uninstall_never_deletes_unknown_files(self): self.assertEqual(Support.RegValues(self.L.RegKeyPath), {Setup.KeptValue: self.Target}) self.assertIsNone(Support.RegValues(self.L.UninstallKeyPath)) self.assertFalse(any(os.path.exists(P) for P in Setup.ShortcutPaths())) + self.assertIsNone(Support.RegValues(self.L.ProtocolKeyPath)) # RAMMIT: goes too self.assertFalse(os.path.exists(self.L.CacheDir)) def test_shortcuts_removed_when_paths_differ_only_by_short_names(self): - # GitHub's runner has TEMP = C:\Users\RUNNER~1\...; the .lnk stores the long form. Same folder, so remove. + # GitHub's runner has TEMP = C:\Users\RUNNER~1\...; an old .lnk stores the long form. Same folder, so remove. import ctypes Long = os.path.join(os.path.dirname(self.Target), "RAMMIT Long Folder Name") os.makedirs(Long, exist_ok=True) @@ -350,9 +350,28 @@ def test_shortcuts_removed_when_paths_differ_only_by_short_names(self): Short = Buffer.value if not Short or os.path.normcase(Short) == os.path.normcase(Long): self.skipTest("this drive doesn't make 8.3 short names") - Setup.CreateShortcuts(Long) - self.assertTrue(all(os.path.isfile(P) for P in Setup.ShortcutPaths())) + for LinkPath in Setup.LinkPaths(): + Support.MakeOldShortcut(LinkPath, os.path.join(Long, "RAMMIT.exe")) Setup.RemoveShortcuts(Short) + self.assertFalse(any(os.path.exists(P) for P in Setup.LinkPaths())) + + def test_ShortcutsOpenTheProtocolAndReplaceOldLinks(self): + Old = Setup.LinkPaths() + for LinkPath in Old: # an install from before 1.1.2: .lnk files straight at RAMMIT.exe + Support.MakeOldShortcut(LinkPath, os.path.join(self.Target, "RAMMIT.exe")) + Elsewhere = os.path.join(self.Env.Root, "Mine", "RAMMIT.lnk") # one the user made: never touched + Support.MakeOldShortcut(Elsewhere, os.path.join(self.Target, "RAMMIT.exe")) + self.Install("1.0.0") + self.assertFalse(any(os.path.exists(P) for P in Old)) + self.assertTrue(os.path.isfile(Elsewhere)) + self.assertTrue(all(Setup.IsOurShortcut(P) for P in Setup.ShortcutPaths())) + Values = Support.RegValues(self.L.ProtocolKeyPath) + self.assertEqual((Values[""], Values["URL Protocol"]), ("URL:" + self.L.ProtocolName, "")) + Somebody = os.path.join(self.L.DesktopDir, "Other.url") # not ours: uninstall leaves it alone + with open(Somebody, "w") as File: + File.write("[InternetShortcut]\nURL=https://example.com/\n") + Setup.RunUninstall(self.Target, True, NoReport) + self.assertTrue(os.path.isfile(Somebody)) self.assertFalse(any(os.path.exists(P) for P in Setup.ShortcutPaths())) def test_ShortcutsAreTheTickedOnesAndUpdatesKeepTheChoice(self): @@ -411,11 +430,13 @@ def test_tidy_registry_removes_empty_parent_but_never_a_used_one(self): def test_shortcut_to_something_else_is_left_alone(self): self.Install("1.0.0") - Other = Setup.ShortcutPaths()[0] - os.remove(Other) - Support.MakeLegacyShortcut(Other) + Other = Setup.ShortcutPaths()[0] # a RAMMIT.url that opens something else + Write(Other, "[InternetShortcut]\nURL=https://example.com/\n") + Lnk = Setup.LinkPaths()[0] # and a RAMMIT.lnk that isn't straight at this RAMMIT.exe + Support.MakeLegacyShortcut(Lnk) Setup.RunUninstall(self.Target, True, NoReport) self.assertTrue(os.path.isfile(Other)) + self.assertTrue(os.path.isfile(Lnk)) # ------------------------------------------------------------------------------------------------ kept accounts @@ -556,7 +577,7 @@ def setUp(self): Setup.RegWrite("InstallPath", self.Old) Setup.RegWrite("Version", "1.0.0") Setup.RegWrite("ConfigPath", "x") - for LinkPath in Setup.ShortcutPaths(): + for LinkPath in Setup.LinkPaths(): Support.MakeLegacyShortcut(LinkPath) def test_detection(self): @@ -578,8 +599,8 @@ def test_choice1_move_and_remove_into_another_folder(self): self.assertFalse(os.path.exists(self.Old)) self.assertEqual(Setup.RegRead("InstallPath"), self.Target) self.assertIsNone(Setup.RegRead("ConfigPath")) - for LinkPath in Setup.ShortcutPaths(): # PowerShell shortcuts replaced by direct ones - self.assertTrue(Setup.ReadShortcut(LinkPath)[0].lower().endswith("rammit.exe")) + self.assertFalse(any(os.path.exists(P) for P in Setup.LinkPaths())) # PowerShell shortcuts replaced by RAMMIT: ones + self.assertTrue(all(Setup.IsOurShortcut(P) for P in Setup.ShortcutPaths())) self.assertIsNone(Legacy.Detect()) def test_choice1_into_the_old_folder_itself(self): @@ -741,6 +762,10 @@ def test_test_mode_refuses_real_names(self): os.environ["RAMMIT_INSTALLER_UNINSTALL_NAME"] = "RAMMIT" with self.assertRaises(RuntimeError): Locations.Reload() + os.environ["RAMMIT_INSTALLER_UNINSTALL_NAME"] = "RAMMIT-InstallerTest-X" + os.environ["RAMMIT_INSTALLER_PROTOCOL"] = "RAMMIT" # the real RAMMIT: protocol + with self.assertRaises(RuntimeError): + Locations.Reload() def test_release_override_ignored_outside_test_mode(self): os.environ.pop("RAMMIT_INSTALLER_TEST", None) diff --git a/Production/Installer/Tests/UiHarness.py b/Production/Installer/Tests/UiHarness.py index 84366f7..04bdc16 100644 --- a/Production/Installer/Tests/UiHarness.py +++ b/Production/Installer/Tests/UiHarness.py @@ -36,6 +36,7 @@ "RAMMIT_INSTALLER_TEST_ROOT": ScratchDir, "RAMMIT_INSTALLER_REGKEY": r"Software\CBlock Digital\RAMMIT-InstallerTest-Ui", "RAMMIT_INSTALLER_UNINSTALL_NAME": "RAMMIT-InstallerTest-Ui", + "RAMMIT_INSTALLER_PROTOCOL": "RAMMIT-InstallerTest-Ui", }) sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import Support # noqa: E402 (also puts Installer\ on sys.path) @@ -64,6 +65,7 @@ def DeleteKeys(): winreg.DeleteKey(winreg.HKEY_CURRENT_USER, Path) except OSError: pass + Setup.UnregisterProtocol() # Creating the test key also created "Software\CBlock Digital": remove it again if nothing else is in it. Parent = L.RegKeyPath.rsplit("\\", 1)[0] try: diff --git a/Production/RAMMIT-Stable/App/Install.py b/Production/RAMMIT-Stable/App/Install.py new file mode 100644 index 0000000..546a9b3 --- /dev/null +++ b/Production/RAMMIT-Stable/App/Install.py @@ -0,0 +1,62 @@ +"""Keeps the installer's registry entries right when the RAMMIT folder was moved by hand. + +The installer (Production/Installer) records where RAMMIT is (HKCU\\Software\\CBlock Digital\\RAMMIT, InstallPath) and +registers the RAMMIT: protocol that its shortcuts open (HKCU\\Software\\Classes\\RAMMIT). When RAMMIT starts from another +folder and the recorded one no longer has a RAMMIT.exe, the folder was moved: both are pointed here (plus the Settings > +Apps entry), so every RAMMIT: shortcut works again, wherever it is, and the installer finds RAMMIT for updates. + +A second copy started while the installed one is still in place changes nothing, and neither does a copy that was never +installed (no InstallPath). Main.py only calls this from the frozen exe, so running from source never touches the registry. +""" +import os +import winreg + +RegKeyPath = r"Software\CBlock Digital\RAMMIT" +ProtocolKeyPath = r"Software\Classes\RAMMIT" +UninstallKeyPath = r"Software\Microsoft\Windows\CurrentVersion\Uninstall\RAMMIT" + + +def _Read(KeyPath, Name=""): + try: + with winreg.OpenKey(winreg.HKEY_CURRENT_USER, KeyPath) as Key: + return str(winreg.QueryValueEx(Key, Name)[0]) + except OSError: + return None + + +def _Write(KeyPath, Name, Value): + with winreg.CreateKeyEx(winreg.HKEY_CURRENT_USER, KeyPath, 0, winreg.KEY_WRITE) as Key: + winreg.SetValueEx(Key, Name, 0, winreg.REG_SZ, Value) + + +def _SamePath(First, Second): + return os.path.normcase(os.path.realpath(First)) == os.path.normcase(os.path.realpath(Second)) + + +def _RegisterProtocol(ProtocolKey, Exe): + """Same entries as the installer's Setup.RegisterProtocol: RAMMIT: starts Exe, with nothing from the link.""" + _Write(ProtocolKey, "", "URL:RAMMIT") + _Write(ProtocolKey, "URL Protocol", "") + _Write(ProtocolKey + r"\DefaultIcon", "", f'"{Exe}",0') + _Write(ProtocolKey + r"\shell\open\command", "", f'"{Exe}"') + + +def Sync(BaseDir, RegKey=RegKeyPath, ProtocolKey=ProtocolKeyPath, UninstallKey=UninstallKeyPath): + """Returns "Moved" (InstallPath and RAMMIT: now point at BaseDir), "Fixed" (only RAMMIT: was re-pointed), or "".""" + Recorded = _Read(RegKey, "InstallPath") + Exe = os.path.join(BaseDir, "RAMMIT.exe") + if not Recorded or not os.path.isfile(Exe): + return "" # never installed with the installer (or uninstalled) + Result = "" + if not _SamePath(Recorded, BaseDir): + if os.path.isfile(os.path.join(Recorded, "RAMMIT.exe")): + return "" # the installed RAMMIT is still there: this is another copy, leave its entries alone + _Write(RegKey, "InstallPath", BaseDir) + if _Read(UninstallKey, "UninstallString") is not None: + _Write(UninstallKey, "InstallLocation", BaseDir) + _Write(UninstallKey, "DisplayIcon", f'"{Exe}",0') + Result = "Moved" + if _Read(ProtocolKey + r"\shell\open\command") != f'"{Exe}"': + _RegisterProtocol(ProtocolKey, Exe) + Result = Result or "Fixed" + return Result diff --git a/Production/RAMMIT-Stable/App/Main.py b/Production/RAMMIT-Stable/App/Main.py index 35551a2..c14e2dc 100644 --- a/Production/RAMMIT-Stable/App/Main.py +++ b/Production/RAMMIT-Stable/App/Main.py @@ -1,9 +1,10 @@ -"""Starts RAMMIT: logging -> multi-instance lock -> local UI server -> main window.""" +"""Starts RAMMIT: logging -> install registry check -> multi-instance lock -> local UI server -> main window.""" import os +import sys import webview -from App import MultiInstance, Paths, Themes +from App import Install, MultiInstance, Paths, Themes from App.Splash import SplashScreen from App.Api import Api, GuardNavigation from App.LocalServer import LocalServer @@ -27,6 +28,15 @@ def StartHeight(Bridge): def Run(): SetupLog() Logger.info("RAMMIT %s starting from %s", VersionLabel(), Paths.BaseDir) + if getattr(sys, "frozen", False): # only the installed exe: running from source never touches the registry + try: + Done = Install.Sync(Paths.BaseDir) + if Done == "Moved": + Logger.info("RAMMIT was moved here: the registry and the RAMMIT: shortcuts now point at this folder") + elif Done: + Logger.info("RAMMIT: shortcuts re-pointed at this folder") + except OSError as Error: + Logger.warning("Could not update the install's registry entries: %s", type(Error).__name__) os.chdir(Paths.BaseDir) Paths.EnsureConfigDir() MultiInstance.Enable() diff --git a/Production/RAMMIT-Stable/CHANGELOG.md b/Production/RAMMIT-Stable/CHANGELOG.md index c4916fb..46444f2 100644 --- a/Production/RAMMIT-Stable/CHANGELOG.md +++ b/Production/RAMMIT-Stable/CHANGELOG.md @@ -9,6 +9,8 @@ - **Installer:** the "Uninstall Config/ folder too" tick box no longer shows its check mark while unticked (#2). - **Installer:** you choose whether to get a **Desktop shortcut** and a **Start Menu shortcut** (both ticked by default), and the done screen says which were added. Updates, repairs and undo keep that choice instead of always recreating both. - **Installer:** the update / repair / undo done screen has **LAUNCH RAMMIT** next to **CLOSE**, like the install done screen. +- **Shortcuts survive moving RAMMIT:** the installer's shortcuts (`RAMMIT.url`) now open the `RAMMIT:` protocol instead of naming RAMMIT's folder. If you move the RAMMIT folder by hand, open `RAMMIT.exe` from its new place once: it points the protocol, the installer's registry entry and the Settings > Apps entry at the new folder, and every RAMMIT shortcut works again, wherever you put it. A second copy started while the installed one is still in place changes nothing. Old `RAMMIT.lnk` shortcuts are replaced on the next install or update. +- **Installer:** "don't ask again" for an old version is now stored as `LegacyInstallPath=Ignore` instead of a separate `IgnoreLegacyInstall` value (the old value is carried over). - **Launch tracking:** RAMMIT now knows which Roblox client belongs to which account. It follows the process it started, including when Roblox hands the game to a child process that opens the window, and falls back to matching each launch's one-time ticket on the client's command line. An account shows "•••" while Roblox starts, "✓" only once its game window is open, and its mark clears when that window closes, so you can see which account closed. The running counter only counts open game windows: launches still starting count only towards Max Instances, and Roblox's tray process (started when a game closes) and its right-click menu no longer count at all. The status line under the launch button only says "Launched" once the accounts' windows are open (it stops waiting after 30 seconds). - **Expired logins** (back from the Test1 build): saved logins are checked at start-up and every 5 minutes, and an account whose login Roblox rejects turns red. With exactly that account selected, **+ ADD** becomes **RENEW** and **LAUNCH** becomes **RENEW AND LAUNCH**, which signs you in again first. Renewing keeps the account if the same Roblox user signs in (checked by user ID, so a renamed account still counts); a different user is added as a new account instead. A launch that Roblox rejects also marks the account. A check that can't reach Roblox never marks anything. - **Tooltips:** every button and setting has a tooltip, drawn in the theme's own colours instead of the plain Windows one. It follows the cursor and flips to the other side near the window's edges. CBlock's are rounded; a custom theme can set `--TooltipRadius`. diff --git a/Production/RAMMIT-Stable/README.md b/Production/RAMMIT-Stable/README.md index 9259ab6..86f27b9 100644 --- a/Production/RAMMIT-Stable/README.md +++ b/Production/RAMMIT-Stable/README.md @@ -60,6 +60,7 @@ README.txt, HowToMakeATheme.txt | `LocalServer.py` | Hardened static server for the active theme folder | | `Themes.py` | Theme discovery, `HeightMap.json`, fallback to Dark | | `Paths.py`, `Log.py`, `Version.py` | Locations, the log file, the version string | +| `Install.py` | When the installed folder was moved by hand, points the installer's registry entries and the `RAMMIT:` shortcut protocol at the new place | ### Frontend (`Src//JS/`, plain ES modules, no build step) diff --git a/Production/RAMMIT-Stable/Tests/TestBackend.py b/Production/RAMMIT-Stable/Tests/TestBackend.py index 24f6e1c..1962848 100644 --- a/Production/RAMMIT-Stable/Tests/TestBackend.py +++ b/Production/RAMMIT-Stable/Tests/TestBackend.py @@ -42,6 +42,61 @@ def test_IsInside(self): self.assertFalse(Paths.IsInside(Paths.SrcDir, os.path.join(Paths.SrcDir, "..", "Config"))) +class TestInstallSync(unittest.TestCase): + """App/Install.Sync against throw-away keys (never the real HKCU\\...\\RAMMIT or RAMMIT: protocol).""" + + def setUp(self): + import uuid + Tag = uuid.uuid4().hex[:8] + self.Keys = (rf"Software\CBlock Digital\RAMMIT-AppTest-{Tag}", rf"Software\Classes\RAMMIT-AppTest-{Tag}", + rf"Software\Microsoft\Windows\CurrentVersion\Uninstall\RAMMIT-AppTest-{Tag}") + self.Root = tempfile.mkdtemp(prefix="RAMMIT-InstallSync-") + self.Old, self.New = os.path.join(self.Root, "Old"), os.path.join(self.Root, "New") + for Folder in (self.Old, self.New): + os.makedirs(Folder) + open(os.path.join(Folder, "RAMMIT.exe"), "w").close() + + def tearDown(self): + import winreg + + def Delete(Path): + try: + with winreg.OpenKey(winreg.HKEY_CURRENT_USER, Path) as Key: + Subs = [winreg.EnumKey(Key, I) for I in range(winreg.QueryInfoKey(Key)[0])] + for Sub in Subs: + Delete(Path + "\\" + Sub) + winreg.DeleteKey(winreg.HKEY_CURRENT_USER, Path) + except OSError: + pass + for Path in self.Keys: + Delete(Path) + shutil.rmtree(self.Root, ignore_errors=True) + + def Sync(self, BaseDir): + from App import Install + return Install.Sync(BaseDir, *self.Keys) + + def test_MovedFolderTakesOverAndSecondCopyDoesNot(self): + from App import Install + RegKey, ProtocolKey, UninstallKey = self.Keys + self.assertEqual(self.Sync(self.New), "") # never installed: nothing written + self.assertIsNone(Install._Read(RegKey, "InstallPath")) + Install._Write(RegKey, "InstallPath", self.Old) + Install._Write(UninstallKey, "UninstallString", "x") + self.assertEqual(self.Sync(self.New), "") # the installed copy is still there: a second copy changes nothing + self.assertEqual(Install._Read(RegKey, "InstallPath"), self.Old) + os.remove(os.path.join(self.Old, "RAMMIT.exe")) # moved away + self.assertEqual(self.Sync(self.New), "Moved") + Exe = os.path.join(self.New, "RAMMIT.exe") + self.assertEqual(Install._Read(RegKey, "InstallPath"), self.New) + self.assertEqual(Install._Read(ProtocolKey + r"\shell\open\command"), f'"{Exe}"') + self.assertEqual(Install._Read(ProtocolKey, "URL Protocol"), "") + self.assertEqual(Install._Read(UninstallKey, "InstallLocation"), self.New) + self.assertEqual(self.Sync(self.New), "") # already right + Install._Write(ProtocolKey + r"\shell\open\command", "", '"C:\\Elsewhere\\RAMMIT.exe"') + self.assertEqual(self.Sync(self.New), "Fixed") + + class TestVersion(unittest.TestCase): def test_VersionIsPlainNumbers(self): self.assertRegex(Version.AppVersion, r"^\d+\.\d+\.\d+$") From 644c68a58fc1d00f5863172782572df0e79726e2 Mon Sep 17 00:00:00 2001 From: CBlockDigital <287527750+CBlockDigital@users.noreply.github.com> Date: Mon, 9 Nov 2026 13:08:43 +0530 Subject: [PATCH 11/11] RAMMIT 1.2.0: fixes from the PR review Version - 1.2.0 in App/Version.py, the changelog, the docs and the requirements header; "1.2" added to SupportedVersions in all four built-in themes. Issue #8 and window sizing - Installer: FitWindow sends ResizeInstaller one at a time; a height measured meanwhile waits and only the newest is sent. InstallerApi applies resizes and the let-go reapply under one lock; the frame fallback uses GetDpiForWindow. - App: Bridge.OneAtATime for the main window and the config wizard; WindowSize uses the same lock. Installer - Removing a put-off old version keeps the installed RAMMIT's Version value. - A failed write while carrying over IgnoreLegacyInstall no longer breaks start-up. - Moving an old version's accounts never copies what a link or junction points at, and neither does a Config backup. - A shortcut whose icon path isn't ANSI-encodable gets the default icon. - Unused LegacyRecommend span removed; Installer.css header corrected. App - App/Install.py only takes over from a folder the installer made (Manifest.json), never from a removable drive or the installer's test mode. - RENEW AND LAUNCH keeps an account renamed on Roblox selected and launches it. - ClientTracker: launch ids, tickets kept until the window shows, process-reuse check for every tracked pid, each launch counted once, a failed start is forgotten, psutil errors caught. - An expired-at-launch result no longer marks a login renewed or re-added meanwhile. - "Launched" waits for a counter poll sent after the batch ended. UI - New --OnExpired theme colour: expired rows, their @username and marks are readable in every theme; a selected expired row gets a ring. - Tooltips keep titles as aria-label / aria-description, update while shown. - Mid-batch status reads "X / Y done, next launch soon..."; tour text updated; Tools/RenderTheme.py draws the straight-edged swatch. Tests and docs - New unit and UI tests for every fix above (each shown to fail without it); the app UI harness drives the real ClientTracker. - User guide (RENEW, login checks), theme guide (--OnExpired, --TooltipRadius, SupportedVersions example), README module tables, CHANGELOG 1.2.0. Co-Authored-By: Claude Opus 5.5 --- .../Installer/Installer/InstallerApi.py | 51 ++-- Production/Installer/Installer/Legacy.py | 32 +- Production/Installer/Installer/Setup.py | 23 +- .../Installer/Installer/Ui/CSS/Installer.css | 11 +- .../Installer/Ui/HTML/Installer.html | 2 +- .../Installer/Installer/Ui/JS/Screens.js | 26 +- Production/Installer/Tests/Support.py | 3 +- Production/Installer/Tests/TestInstaller.py | 104 ++++++- Production/Installer/Tests/TestUi.mjs | 34 ++- Production/Installer/Tests/UiHarness.py | 30 +- Production/RAMMIT-Stable/App/Api.py | 35 ++- Production/RAMMIT-Stable/App/Install.py | 25 +- Production/RAMMIT-Stable/App/MultiInstance.py | 131 ++++++-- Production/RAMMIT-Stable/App/Version.py | 2 +- Production/RAMMIT-Stable/App/WindowSize.py | 29 +- Production/RAMMIT-Stable/CHANGELOG.md | 19 +- .../RAMMIT-Stable/Docs/HowToMakeATheme.txt | 12 +- Production/RAMMIT-Stable/Docs/README.txt | 14 +- Production/RAMMIT-Stable/README.md | 6 +- .../RAMMIT-Stable/Src/CBlock/CSS/Style.css | 21 +- .../RAMMIT-Stable/Src/CBlock/JS/Accounts.js | 14 +- .../RAMMIT-Stable/Src/CBlock/JS/Bridge.js | 24 ++ .../RAMMIT-Stable/Src/CBlock/JS/Launch.js | 24 +- .../RAMMIT-Stable/Src/CBlock/JS/Tooltip.js | 35 ++- .../RAMMIT-Stable/Src/CBlock/JS/TourData.js | 2 +- .../RAMMIT-Stable/Src/CBlock/JS/Wizard.js | 7 +- .../RAMMIT-Stable/Src/CBlock/Theme.json | 2 +- .../RAMMIT-Stable/Src/Dark/CSS/Style.css | 21 +- .../RAMMIT-Stable/Src/Dark/JS/Accounts.js | 14 +- .../RAMMIT-Stable/Src/Dark/JS/Bridge.js | 24 ++ .../RAMMIT-Stable/Src/Dark/JS/Launch.js | 24 +- .../RAMMIT-Stable/Src/Dark/JS/Tooltip.js | 35 ++- .../RAMMIT-Stable/Src/Dark/JS/TourData.js | 2 +- .../RAMMIT-Stable/Src/Dark/JS/Wizard.js | 7 +- Production/RAMMIT-Stable/Src/Dark/Theme.json | 2 +- .../RAMMIT-Stable/Src/Light/CSS/Style.css | 21 +- .../RAMMIT-Stable/Src/Light/JS/Accounts.js | 14 +- .../RAMMIT-Stable/Src/Light/JS/Bridge.js | 24 ++ .../RAMMIT-Stable/Src/Light/JS/Launch.js | 24 +- .../RAMMIT-Stable/Src/Light/JS/Tooltip.js | 35 ++- .../RAMMIT-Stable/Src/Light/JS/TourData.js | 2 +- .../RAMMIT-Stable/Src/Light/JS/Wizard.js | 7 +- Production/RAMMIT-Stable/Src/Light/Theme.json | 2 +- .../Src/MyCustomTheme/CSS/Style.css | 22 +- .../Src/MyCustomTheme/JS/Accounts.js | 14 +- .../Src/MyCustomTheme/JS/Bridge.js | 24 ++ .../Src/MyCustomTheme/JS/Launch.js | 24 +- .../Src/MyCustomTheme/JS/Tooltip.js | 35 ++- .../Src/MyCustomTheme/JS/TourData.js | 2 +- .../Src/MyCustomTheme/JS/Wizard.js | 7 +- .../Src/MyCustomTheme/Theme.json | 2 +- Production/RAMMIT-Stable/Tests/TestBackend.py | 288 +++++++++++++++++- Production/RAMMIT-Stable/Tests/TestUi.mjs | 75 +++++ Production/RAMMIT-Stable/Tests/UiHarness.py | 71 ++++- Production/RAMMIT-Stable/Tools/RenderTheme.py | 5 +- Production/RAMMIT-Stable/requirements.txt | 2 +- 56 files changed, 1296 insertions(+), 251 deletions(-) diff --git a/Production/Installer/Installer/InstallerApi.py b/Production/Installer/Installer/InstallerApi.py index cd1bfb1..2ab900d 100644 --- a/Production/Installer/Installer/InstallerApi.py +++ b/Production/Installer/Installer/InstallerApi.py @@ -51,6 +51,7 @@ def __init__(self, StartScreen=""): self._Frame = None self._Resized = False self._Dragging = False + self._ResizeLock = threading.Lock() # ResizeInstaller and the let-go reapply run on different threads self._LastPath = "" # ------------------------------------------------------------ wiring (Installer.py) @@ -76,16 +77,17 @@ def _OnLetGo(self, _Sender, _Args): threading.Thread(target=self._ReapplyHeight, daemon=True).start() def _ReapplyHeight(self): - Window, Target = self._Window, self._LastHeight - if not Window or not Target: - return - try: - Native = Window.native - Scale = self._WindowScale(Native) - if abs(Native.Height / Scale - Target) >= 2: - self._SetHeight(Native, round(Target * Scale)) - except Exception: - pass + with self._ResizeLock: + Window, Target = self._Window, self._LastHeight + if not Window or not Target: + return + try: + Native = Window.native + Scale = self._WindowScale(Native) + if abs(Native.Height / Scale - Target) >= 2: + self._SetHeight(Native, round(Target * Scale)) + except Exception: + pass @staticmethod def _WindowScale(Native): @@ -417,25 +419,26 @@ def ResizeInstaller(self, Height, ViewportHeight=None): Window = self._Window if not Window: return - if self._Frame is None and self._LastHeight and not self._Resized and 0 < Viewport < self._LastHeight: - self._Frame = self._LastHeight - Viewport - Target = Height + (self._Frame if self._Frame is not None else self._FrameHeight()) - self._Resized = True - if abs(Target - self._LastHeight) < 2: - return - self._LastHeight = Target - if self._Dragging: - return # held: Windows would undo it (flicker); _OnLetGo applies it - try: - Window.resize(WindowWidth, Target) - except Exception: - pass + with self._ResizeLock: + if self._Frame is None and self._LastHeight and not self._Resized and 0 < Viewport < self._LastHeight: + self._Frame = self._LastHeight - Viewport + Target = Height + (self._Frame if self._Frame is not None else self._FrameHeight()) + self._Resized = True + if abs(Target - self._LastHeight) < 2: + return + self._LastHeight = Target + if self._Dragging: + return # held: Windows would undo it (flicker); _OnLetGo applies it + try: + Window.resize(WindowWidth, Target) + except Exception: + pass def _FrameHeight(self): """Fallback when the page didn't send its viewport height: title bar + borders read from the native form.""" try: Native = self._Window.native - Scale = max(1.0, Native.DeviceDpi / 96.0) + Scale = self._WindowScale(Native) # not Native.DeviceDpi, which stays at 96 (see _WindowScale) return int(round((Native.Height - Native.ClientSize.Height) / Scale)) except Exception: return 39 diff --git a/Production/Installer/Installer/Legacy.py b/Production/Installer/Installer/Legacy.py index c1e4ace..a998f4d 100644 --- a/Production/Installer/Installer/Legacy.py +++ b/Production/Installer/Installer/Legacy.py @@ -52,14 +52,18 @@ def ReadVersion(Folder): IgnoredForGood = "Ignore" # LegacyInstallPath's value once the user ticked "don't ask again" and pressed Ignore -OldIgnoreValue = "IgnoreLegacyInstall" # where installers before 1.1.2 kept that; moved over by Detect() +OldIgnoreValue = "IgnoreLegacyInstall" # where installers before 1.2.0 kept that; moved over by Detect() def Detect(): """{Path, Version, Shortcuts, Deferred} for a Test1 install the registry points at (InstallPath, or LegacyInstallPath once the user pressed Ignore), unless the user said never ask again. Deferred = it was put off with Ignore.""" - if Setup.RegRead(OldIgnoreValue) == "1": # installers before 1.1.2 kept "don't ask again" in its own value - Ignore(True) + if Setup.RegRead(OldIgnoreValue) == "1": # installers before 1.2.0 kept "don't ask again" in its own value + try: + Ignore(True) + except OSError as Error: # can't move it over now: still honour it, and try again next time + Logger.warning("Could not move the old 'don't ask again' setting: %s", type(Error).__name__) + return None PutOff = Setup.RegRead("LegacyInstallPath") if PutOff == IgnoredForGood: return None @@ -101,12 +105,20 @@ def MoveConfig(LegacyFolder, InstallPath, Choice="KeepNew"): Config that already holds accounts: Choice KeepNew keeps it (and backs up the old files), UseOld replaces it (after backing it up). Returns notes for the result screen.""" Source = ConfigDir(LegacyFolder) + if os.path.islink(Source) or os.path.isjunction(Source): # only real files come across, never what a link points at + Logger.warning("Old Config folder is a link: nothing moved") + return [] Present = {Name.lower(): Name for Name in _ListLower(Source)} Wanted = [(Present[Name.lower()], Name) for Name in ConfigFiles if Name.lower() in Present] + Links = [Pair for Pair in Wanted if os.path.islink(os.path.join(Source, Pair[0]))] + if Links: # only real files come across, never what a link points at + Logger.warning("Skipped %d old config files that are links", len(Links)) + Wanted = [Pair for Pair in Wanted if Pair not in Links] if not Wanted: return [] Destination = os.path.join(InstallPath, "Config") - if AccountsPresent(Destination) and AccountsPresent(Source) and Choice != "UseOld": + OldAccounts = any(Name == "Accounts.json" for _Found, Name in Wanted) and AccountsPresent(Source) + if AccountsPresent(Destination) and OldAccounts and Choice != "UseOld": Setup.BackupConfig(InstallPath, "Test1", Source=Source) return ["Your newer accounts were kept. The old version's settings are saved in Config.Backup."] if os.path.isdir(Destination) and os.listdir(Destination): @@ -167,13 +179,15 @@ def RemoveShortcuts(): def ClearRegistry(Folder): - """Test1's values: Version, ConfigPath, CleanupPath, and InstallPath while it still points at the old folder; - plus LegacyInstallPath (the old version is dealt with).""" - for Name in ("Version", "ConfigPath", "CleanupPath", "LegacyInstallPath"): + """Test1's values: ConfigPath, CleanupPath, and InstallPath and Version while InstallPath still points at the old + folder (once a new RAMMIT is installed they are its own); plus LegacyInstallPath (the old version is dealt with).""" + for Name in ("ConfigPath", "CleanupPath", "LegacyInstallPath"): Setup.RegDeleteValue(Name) Current = Setup.RegRead("InstallPath") - if Current and Folder and Paths.SamePath(Current, Folder): - Setup.RegDeleteValue("InstallPath") + if not Current or (Folder and Paths.SamePath(Current, Folder)): + Setup.RegDeleteValue("Version") + if Current: + Setup.RegDeleteValue("InstallPath") Setup.TidyRegistry() diff --git a/Production/Installer/Installer/Setup.py b/Production/Installer/Installer/Setup.py index 4bde810..430f275 100644 --- a/Production/Installer/Installer/Setup.py +++ b/Production/Installer/Installer/Setup.py @@ -171,7 +171,7 @@ def _FolderSize(Folder): # A shortcut that names a path breaks when the RAMMIT folder is moved. These open the RAMMIT: protocol instead # (HKCU\Software\Classes\RAMMIT, pointing at RAMMIT.exe), which RAMMIT points back at itself when it starts from a # moved folder (App/Install.py), so every shortcut keeps working wherever it is, copies the user made included. -# Their icon is a copy in RAMMIT-Setup\, which never moves. Installers before 1.1.2 made RAMMIT.lnk files straight +# Their icon is a copy in RAMMIT-Setup\, which never moves. Installers before 1.2.0 made RAMMIT.lnk files straight # at RAMMIT.exe (and Test1 made PowerShell ones, see Legacy.py); ours are replaced by .url ones on the next install. ShortcutNames = ("Desktop", "StartMenu") # the two the installer offers (tick boxes on the Version screen) @@ -192,7 +192,7 @@ def ShortcutPaths(): def LinkPaths(): - """Where the RAMMIT.lnk shortcuts of Test1 and of installers before 1.1.2 are.""" + """Where the RAMMIT.lnk shortcuts of Test1 and of installers before 1.2.0 are.""" return [os.path.join(_ShortcutDir(Name), "RAMMIT.lnk") for Name in ShortcutNames] @@ -286,7 +286,12 @@ def CreateShortcuts(InstallPath, Names=ShortcutNames): """RAMMIT.url for each ticked name (register the protocol first). Our old RAMMIT.lnk files go.""" _RemoveOldLinks(InstallPath) Icon = _ShortcutIcon(InstallPath) - Text = f"[InternetShortcut]\nURL={Locations.Current.ProtocolName}:\nIconFile={Icon}\nIconIndex=0\n" + Text = f"[InternetShortcut]\nURL={Locations.Current.ProtocolName}:\n" + try: + Icon.encode("mbcs") # .url files are read in the ANSI code page + Text += f"IconFile={Icon}\nIconIndex=0\n" + except UnicodeEncodeError: # e.g. a user name outside it: a broken icon path would be worse than the default icon + Logger.warning("Shortcut icon path can't be written in the ANSI code page; using the default icon") for Path in [ShortcutPath(Name) for Name in ShortcutNames if Name in Names]: os.makedirs(os.path.dirname(Path), exist_ok=True) with open(Path, "w", encoding="mbcs", errors="replace") as File: @@ -294,7 +299,7 @@ def CreateShortcuts(InstallPath, Names=ShortcutNames): def _RemoveOldLinks(InstallPath): - """Removes RAMMIT.lnk only where it points at this install's RAMMIT.exe (made by installers before 1.1.2).""" + """Removes RAMMIT.lnk only where it points at this install's RAMMIT.exe (made by installers before 1.2.0).""" Exe = os.path.join(InstallPath, "RAMMIT.exe") for LinkPath in LinkPaths(): if os.path.isfile(LinkPath): @@ -589,11 +594,16 @@ def BackupConfig(InstallPath, Label, Source=None, Keep=BackupKeep): while os.path.exists(Target): Extra += 1 Target = os.path.join(Root, f"{Base}-{Extra}") - shutil.copytree(Source, Target) + shutil.copytree(Source, Target, ignore=_Links) PruneBackups(Root, Keep) return Target +def _Links(Folder, Names): + """copytree's ignore: links and junctions are left out, so a backup never copies what one points at.""" + return {Name for Name in Names if os.path.islink(os.path.join(Folder, Name)) or os.path.isjunction(os.path.join(Folder, Name))} + + def PruneBackups(Root, Keep=BackupKeep): """Deletes all but the newest Keep backup folders. Folders that don't look like backups are never touched.""" Found = [] @@ -982,7 +992,8 @@ def OnBytes(Done, Total): Report(StageDetail="Writing registry", StagePct=25, OverallPct=93) RegWrite("InstallPath", InstallPath) RegWrite("Version", Version) - RegWrite(ShortcutsValue, ",".join(Shortcuts)) + RegWrite(ShortcutsValue, ",".join(Shortcuts)) # the user's choice, kept even if making them fails below: + # the next update / repair then tries again try: CopySetupExe() WriteUninstallEntry(InstallPath, Version) diff --git a/Production/Installer/Installer/Ui/CSS/Installer.css b/Production/Installer/Installer/Ui/CSS/Installer.css index 67744ba..4b6c9b7 100644 --- a/Production/Installer/Installer/Ui/CSS/Installer.css +++ b/Production/Installer/Installer/Ui/CSS/Installer.css @@ -1,9 +1,11 @@ /* RAMMIT installer styles. * - * Everything from "BASE" down to "SCREEN SLIDE TRANSITIONS" is Test1's installer CSS, copied unchanged: - * the :root colours and reset from the top of Test1's Src/CSS/Style.css, its CUSTOM SELECT section (used by the - * version picker) and its whole INSTALLER section. The installer always uses this fixed Dark look, because it - * runs before any theme has been picked. + * Everything from "BASE" down to "SCREEN SLIDE TRANSITIONS" is Test1's installer CSS: the :root colours and + * reset from the top of Test1's Src/CSS/Style.css, its CUSTOM SELECT section (used by the version picker) and its + * whole INSTALLER section. The installer always uses this fixed Dark look, because it runs before any theme has + * been picked. It is copied unchanged except for these, which sit next to the rules they belong with: + * - --Legacy and .BtnInst.Legacy (the OLD VERSION button), and .InstCheckboxPair (the two shortcut tick boxes); + * - .InstCheckboxRow .CheckboxBox i: the check mark is hidden while unticked (#2). * * New rules for the screens the new installer adds are at the end, under "ADDITIONS"; they reuse the same * variables and sizes so those screens look native. @@ -703,7 +705,6 @@ body { .InstCheckboxRow .CheckboxBox i { font-size: 11px; - color: var(--Accent); /* hidden, not display: none, so the box keeps its size while unticked (#2) */ visibility: hidden; } diff --git a/Production/Installer/Installer/Ui/HTML/Installer.html b/Production/Installer/Installer/Ui/HTML/Installer.html index 48c19bc..2eaf81c 100644 --- a/Production/Installer/Installer/Ui/HTML/Installer.html +++ b/Production/Installer/Installer/Ui/HTML/Installer.html @@ -37,7 +37,7 @@
An older test version of RAMMIT (...) is installed in ....
- What should happen to it? The first choice is recommended. + What should happen to it? The first choice is recommended.
diff --git a/Production/Installer/Installer/Ui/JS/Screens.js b/Production/Installer/Installer/Ui/JS/Screens.js index 518f5bf..1e43f10 100644 --- a/Production/Installer/Installer/Ui/JS/Screens.js +++ b/Production/Installer/Installer/Ui/JS/Screens.js @@ -125,6 +125,30 @@ export function Go(Screen, Action) { let LastSent = 0; let FitQueued = false; +// pywebview runs every call to Python on its own thread, so two ResizeInstaller calls in flight can finish in +// either order and leave the window at the older height (issue #8). Only one is sent at a time; a height measured +// meanwhile waits, and only the newest one is sent once the call in flight has finished. A call that never answers +// stops holding the others up after GiveUpMs (Python applies resizes under one lock, so they still land in order). +const GiveUpMs = 3000; +let Sending = false; +let Waiting = null; + +function SendHeight(Needed, Viewport) { + if (Sending) { + Waiting = [Needed, Viewport]; + return; + } + Sending = true; + const GiveUp = new Promise(Resolve => setTimeout(Resolve, GiveUpMs)); + Promise.race([Api.ResizeInstaller(Needed, Viewport), GiveUp]).catch(ReportError).finally(() => { + Sending = false; + if (Waiting) { + const [NextNeeded, NextViewport] = Waiting; + Waiting = null; + SendHeight(NextNeeded, NextViewport); + } + }); +} export function FitWindow() { if (FitQueued) return; @@ -140,7 +164,7 @@ export function FitWindow() { window.InstallerFitHeight = Needed; // read by the UI tests if (Math.abs(Needed - LastSent) < 2) return; LastSent = Needed; - Api.ResizeInstaller(Needed, window.innerHeight).catch(ReportError); + SendHeight(Needed, window.innerHeight); }); } diff --git a/Production/Installer/Tests/Support.py b/Production/Installer/Tests/Support.py index 48c31bb..79ebbd6 100644 --- a/Production/Installer/Tests/Support.py +++ b/Production/Installer/Tests/Support.py @@ -107,6 +107,7 @@ def MakeAppZip(Version, Extra=None, Prefix="RAMMIT/"): "Runtime/python313.dll": "fake runtime " + Version, "Src/Dark/HTML/Index.html": f"{Version}", "Src/Dark/Theme.json": '{"Name": "Dark"}', + "Src/Dark/RAMMIT.ico": "fake icon", # what the shortcuts' icon is copied from } Files.update(Extra or {}) Buffer = io.BytesIO() @@ -152,7 +153,7 @@ def MakeLegacyShortcut(LinkPath): def MakeOldShortcut(LinkPath, Exe): - """What installers before 1.1.2 made: RAMMIT.lnk straight at RAMMIT.exe.""" + """What installers before 1.2.0 made: RAMMIT.lnk straight at RAMMIT.exe.""" import win32com.client os.makedirs(os.path.dirname(LinkPath), exist_ok=True) Link = win32com.client.Dispatch("WScript.Shell").CreateShortCut(LinkPath) diff --git a/Production/Installer/Tests/TestInstaller.py b/Production/Installer/Tests/TestInstaller.py index 0d699ea..be54ff3 100644 --- a/Production/Installer/Tests/TestInstaller.py +++ b/Production/Installer/Tests/TestInstaller.py @@ -357,7 +357,7 @@ def test_shortcuts_removed_when_paths_differ_only_by_short_names(self): def test_ShortcutsOpenTheProtocolAndReplaceOldLinks(self): Old = Setup.LinkPaths() - for LinkPath in Old: # an install from before 1.1.2: .lnk files straight at RAMMIT.exe + for LinkPath in Old: # an install from before 1.2.0: .lnk files straight at RAMMIT.exe Support.MakeOldShortcut(LinkPath, os.path.join(self.Target, "RAMMIT.exe")) Elsewhere = os.path.join(self.Env.Root, "Mine", "RAMMIT.lnk") # one the user made: never touched Support.MakeOldShortcut(Elsewhere, os.path.join(self.Target, "RAMMIT.exe")) @@ -367,12 +367,28 @@ def test_ShortcutsOpenTheProtocolAndReplaceOldLinks(self): self.assertTrue(all(Setup.IsOurShortcut(P) for P in Setup.ShortcutPaths())) Values = Support.RegValues(self.L.ProtocolKeyPath) self.assertEqual((Values[""], Values["URL Protocol"]), ("URL:" + self.L.ProtocolName, "")) + Command = Support.RegValues(self.L.ProtocolKeyPath + r"\shell\open\command")[""] + self.assertEqual(Command, '"' + os.path.join(self.Target, "RAMMIT.exe") + '"') # nothing from the link (no %1) + self.assertTrue(os.path.isfile(self.L.IconPath)) # the icon is a copy in RAMMIT-Setup\, which never moves + with open(Setup.ShortcutPath("Desktop"), encoding="mbcs") as File: + self.assertIn("IconFile=" + self.L.IconPath + "\n", File.read()) Somebody = os.path.join(self.L.DesktopDir, "Other.url") # not ours: uninstall leaves it alone with open(Somebody, "w") as File: File.write("[InternetShortcut]\nURL=https://example.com/\n") Setup.RunUninstall(self.Target, True, NoReport) self.assertTrue(os.path.isfile(Somebody)) self.assertFalse(any(os.path.exists(P) for P in Setup.ShortcutPaths())) + self.assertIsNone(Support.RegValues(self.L.ProtocolKeyPath)) + self.assertFalse(os.path.exists(self.L.IconPath)) + + def test_ShortcutIconPathOutsideTheAnsiCodePageFallsBackToTheDefaultIcon(self): + # An emoji: no Windows ANSI code page can write it, whatever language this PC is set to + with mock.patch.object(Setup, "_ShortcutIcon", return_value="C:\\Users\\\U0001F600\\RAMMIT.ico"): + Setup.CreateShortcuts(self.Target, ["Desktop"]) + with open(Setup.ShortcutPath("Desktop"), encoding="mbcs") as File: + Text = File.read() + self.assertTrue(Setup.IsOurShortcut(Setup.ShortcutPath("Desktop"))) # it still opens RAMMIT + self.assertNotIn("IconFile", Text) # a "?"-mangled icon path would be worse than the default icon def test_ShortcutsAreTheTickedOnesAndUpdatesKeepTheChoice(self): Desktop, StartMenu = Setup.ShortcutPath("Desktop"), Setup.ShortcutPath("StartMenu") @@ -634,7 +650,7 @@ def test_choice3_remove_without_moving(self): self.assertEqual(os.listdir(self.Old), ["MyStuff.txt"]) self.assertIsNone(Setup.RegRead("InstallPath")) self.assertIsNone(Setup.RegRead("Version")) - self.assertFalse(any(os.path.exists(P) for P in Setup.ShortcutPaths())) + self.assertFalse(any(os.path.exists(P) for P in Setup.LinkPaths())) # Test1's PowerShell shortcuts os.remove(os.path.join(self.Old, "MyStuff.txt")) Support.MakeLegacyInstall(self.Old) Legacy.RunRemove(self.Old, lambda **_P: None) @@ -659,6 +675,53 @@ def test_Choice4IgnoreWithoutDontAskPutsItOff(self): Legacy.RunRemove(self.Old, lambda **_P: None) # dealt with: forgotten self.assertIsNone(Setup.RegRead("LegacyInstallPath")) self.assertIsNone(Legacy.Detect()) + self.assertEqual((Setup.RegRead("InstallPath"), Setup.RegRead("Version")), (self.Target, "1.1.0")) # the new one's + + def test_OldDontAskAgainStillHonouredWhenItCantBeMoved(self): + Setup.RegWrite(Legacy.OldIgnoreValue, "1") + with mock.patch.object(Setup, "RegWrite", side_effect=OSError): + self.assertIsNone(Legacy.Detect()) # no error on the way into the installer + self.assertEqual(Setup.RegRead(Legacy.OldIgnoreValue), "1") # moved over next time instead + + def test_MoveConfigSkipsLinkedFiles(self): + # Making a real symbolic link needs Developer Mode or admin, so the old accounts file only reports being one. + Accounts = os.path.join(self.Old, "Config", "accounts.json") + RealIsLink = os.path.islink + Destination = os.path.join(self.Env.Root, "NewRAMMIT") + os.makedirs(Destination) + with mock.patch.object(Legacy.os.path, "islink", side_effect=lambda P: Paths.SamePath(P, Accounts) or RealIsLink(P)): + Legacy.MoveConfig(self.Old, Destination) + self.assertFalse(os.path.exists(os.path.join(Destination, "Config", "Accounts.json"))) + self.assertTrue(os.path.isfile(os.path.join(Destination, "Config", "Settings.json"))) # real files still come + + def test_MoveConfigLeavesALinkedConfigFolderAlone(self): + import _winapi # a junction needs no admin rights, unlike a symbolic link + Outside = os.path.join(self.Env.Root, "Outside") + os.makedirs(Outside) + Write(os.path.join(Outside, "accounts.json"), '[{"Username": "NotTheirs"}]') + shutil.rmtree(os.path.join(self.Old, "Config")) + _winapi.CreateJunction(Outside, os.path.join(self.Old, "Config")) + Destination = os.path.join(self.Env.Root, "NewRAMMIT") + os.makedirs(Destination) + self.assertEqual(Legacy.MoveConfig(self.Old, Destination), []) + self.assertFalse(os.path.exists(os.path.join(Destination, "Config"))) + os.rmdir(os.path.join(self.Old, "Config")) # removes the junction only + + def test_ConfigBackupNeverCopiesWhatALinkPointsAt(self): + import _winapi + Outside = os.path.join(self.Env.Root, "Outside") + os.makedirs(Outside) + Write(os.path.join(Outside, "Secret.txt"), "not part of the config") + Config = os.path.join(self.Env.Root, "NewRAMMIT", "Config") + os.makedirs(Config) + Write(os.path.join(Config, "Accounts.json"), '[{"Username": "Mine"}]') + _winapi.CreateJunction(Outside, os.path.join(Config, "Linked")) + try: + Backup = Setup.BackupConfig(os.path.dirname(Config), "Test") + self.assertTrue(os.path.isfile(os.path.join(Backup, "Accounts.json"))) + self.assertFalse(os.path.exists(os.path.join(Backup, "Linked"))) + finally: + os.rmdir(os.path.join(Config, "Linked")) def test_Choice4DontAskAgainForgetsAPutOffOne(self): Legacy.Ignore(False, self.Old) @@ -667,7 +730,7 @@ def test_Choice4DontAskAgainForgetsAPutOffOne(self): self.assertIsNone(Legacy.Detect()) def test_OldDontAskAgainValueIsCarriedOver(self): - Setup.RegWrite(Legacy.OldIgnoreValue, "1") # what installers before 1.1.2 wrote + Setup.RegWrite(Legacy.OldIgnoreValue, "1") # what installers before 1.2.0 wrote self.assertIsNone(Legacy.Detect()) self.assertIsNone(Setup.RegRead(Legacy.OldIgnoreValue)) self.assertEqual(Setup.RegRead("LegacyInstallPath"), Legacy.IgnoredForGood) @@ -701,8 +764,7 @@ def test_MoveIntoInstalledRammitThenRemoveTheOldOne(self): Legacy.RunMove(self.Old, self.Target, "MoveRemove", "KeepNew", NoReport) self.assertIn("OldTester", Read(os.path.join(self.Target, "Config", "Accounts.json"))) self.assertFalse(os.path.exists(self.Old)) - self.assertFalse(any(os.path.exists(P) for P in Setup.ShortcutPaths() - if Setup.ReadShortcut(P)[0].lower().endswith("powershell.exe"))) + self.assertFalse(any(os.path.exists(P) for P in Setup.LinkPaths())) # Test1's PowerShell shortcuts self.assertEqual((Setup.RegRead("InstallPath"), Setup.RegRead("Version")), (self.Target, "1.1.0")) self.assertIsNone(Legacy.Detect()) @@ -812,6 +874,38 @@ def test_ResizeWaitsForLetGoWhileHeld(self): Api._ReapplyHeight() SetHeight.assert_not_called() + def test_ResizeWatchesTheTitleBarOnceTheWindowIsUp(self): + class Event: # what pythonnet's .NET events and pywebview's events support: += and firing + def __init__(self): + self.Handlers = [] + + def __iadd__(self, Handler): + self.Handlers.append(Handler) + return self + + def Fire(self, *Args): + for Handler in self.Handlers: + Handler(*Args) + + Window = Support.EventWindow() + Window.events = mock.Mock(shown=Event()) + Window.native = mock.Mock(Height=409, ResizeBegin=Event(), ResizeEnd=Event()) + Api = InstallerApi.InstallerApi() + Api._AttachWindow(Window) + Api._LastHeight, Api._Frame = 327, 39 + Window.events.shown.Fire() # ResizeBegin / ResizeEnd are watched from now on + Window.native.ResizeBegin.Fire(None, None) # title bar grabbed + Api.ResizeInstaller(411, 288) + self.assertIsNone(Window.LastResize) + with mock.patch.object(InstallerApi.InstallerApi, "_SetHeight") as SetHeight, \ + mock.patch.object(InstallerApi.InstallerApi, "_WindowScale", return_value=1.25), \ + mock.patch.object(InstallerApi.threading, "Thread", side_effect=lambda target, daemon: mock.Mock(start=target)): + Window.native.ResizeEnd.Fire(None, None) # let go: applied once, size only + SetHeight.assert_called_once_with(Window.native, round(450 * 1.25)) + self.assertFalse(Api._Dragging) + Api.ResizeInstaller(361, 288) # not held: straight through + self.assertEqual(Window.LastResize, [InstallerApi.WindowWidth, 400]) + class TestUiServer(unittest.TestCase): @classmethod diff --git a/Production/Installer/Tests/TestUi.mjs b/Production/Installer/Tests/TestUi.mjs index 0bc9046..3ed1f8b 100644 --- a/Production/Installer/Tests/TestUi.mjs +++ b/Production/Installer/Tests/TestUi.mjs @@ -199,6 +199,9 @@ try { const DefaultPath = (await CallApi('GetState')).DefaultPath; await Page.$eval('#InstallPath', (E, P) => { E.value = P; }, DefaultPath); + await Page.$eval('#ShortcutDesktop', E => E.closest('label').click()); // only a Start Menu shortcut + Check('shortcut tick boxes: Desktop unticked, Start Menu ticked', !(await Page.$eval('#ShortcutDesktop', E => E.checked)) + && await Page.$eval('#ShortcutStartMenu', E => E.checked)); await Hook('Running', { Running: true }); await Hook('Server', { ChunkDelay: 0.12 }); await ClickBtn('VersionInstallBtn'); @@ -215,15 +218,25 @@ try { await Shot('07-InstallDone', 'InstallDone'); const DoneText = await Text('#InstallDoneText'); Check('install done: Test1 wording with real version + path', DoneText.startsWith('Installed v1.0.0 to ') && DoneText.includes(DefaultPath) - && DoneText.includes('Shortcuts were added to the Desktop and the Start Menu.') && DoneText.includes('Have fun - and ping us if anything breaks.'), DoneText); + && DoneText.includes('A shortcut was added to the Start Menu.') && DoneText.includes('Have fun - and ping us if anything breaks.'), DoneText); let St = await Hook('State'); Check('install: registry + Apps entry written (test keys)', St.Registry && St.Registry.Version === '1.0.0' && St.Apps && St.Apps.DisplayVersion === '1.0.0'); + Check('install: only the ticked shortcut is made and remembered', St.Registry.Shortcuts === 'StartMenu', JSON.stringify(St.Registry)); await ClickBtn('LaunchBtn'); Check('LAUNCH RAMMIT starts the app and closes the installer', await WaitFor(async () => { const S = await Hook('State'); return S.Launches === 1 && S.Closed >= 1; })); // ------------------------------------------------------------ B. installed + // Opening sends two heights about 17 ms apart (the Loading screen's, then the menu's). With every resize slowed + // down, they would overlap unless the page waits for each one (#8). + await Hook('SlowResize', { Delay: 0.3 }); await Open(); await Shot('08-MenuInstalled', 'MenuInstalled'); + await Sleep(1500); // every resize the page asked for has finished + St = await Hook('State'); + const FitNow = await Page.evaluate(() => window.InstallerFitHeight); + Check('resizes go one at a time and the newest height wins (#8)', St.ResizesInFlight === 1 && Math.abs(St.LastAskedHeight - FitNow) < 2, + `in flight ${St.ResizesInFlight}, last asked ${St.LastAskedHeight}, needed ${FitNow}`); + await Hook('SlowResize', { Delay: 0 }); Check('installed menu: versions + buttons (no separate Change version)', (await Text('#InstalledVer')) === 'v1.0.0' && (await Text('#LatestVer')) === 'v1.1.0' && JSON.stringify(await Page.$$eval('[data-screen=MenuInstalled] .BtnInst', Els => Els.filter(E => !E.hidden).map(E => E.textContent))) === '["UPDATE / DOWNGRADE","REPAIR","UNINSTALL","CANCEL"]'); // OLD VERSION is hidden: no old version put off await ClickBtn('UpdateBtn'); @@ -248,6 +261,11 @@ try { Check('update: heading', (await Text('#ProgressHeading')) === 'Updating RAMMIT to v1.1.0...', await Text('#ProgressHeading')); await Shot('10-ActionDone', 'ActionDone'); Check('update done', (await Text('#ActionDoneTitle')) === 'Updated successfully.' && (await Text('#ActionDoneText')).startsWith('RAMMIT is now on v1.1.0.'), await Text('#ActionDoneText')); + const BeforeLaunch = await Hook('State'); + await ClickBtn('ActionLaunchBtn'); + Check('update done: LAUNCH RAMMIT starts the app and closes the installer', await WaitFor(async () => { + const S = await Hook('State'); return S.Launches === BeforeLaunch.Launches + 1 && S.Closed > BeforeLaunch.Closed; })); + Check('update keeps the shortcut choice', (await Hook('State')).Registry.Shortcuts === 'StartMenu'); await Open(); await OnScreen('MenuInstalled'); @@ -301,6 +319,7 @@ try { Check('tick box changes the warning (Test1)', /also remove your Config\/ folder/.test(await Text('#ConfirmUninstallMsg'))); Check('ticked check icon is visible (#2)', (await CheckIconVisibility()) === 'visible'); await Page.click('[data-screen=ConfirmUninstall] .InstCheckboxRow'); + Check('unticked again: check icon hidden again (#2)', (await CheckIconVisibility()) === 'hidden'); await Hook('Accounts', { Path: DefaultPath }); // RAMMIT has run once: there is a Config folder to keep await Hook('SlowUninstall', { Delay: 0.4 }); await ClickBtn('UninstallConfirmBtn'); @@ -363,16 +382,25 @@ try { await ClickBtn('LegacyDoneContinueBtn'); await OnScreen('MenuFresh'); - // choice 4: ignore + don't ask again + // choice 4 without "don't ask again": put off, reachable from the menu's OLD VERSION button await Hook('Legacy', {}); await Open(); await OnScreen('Legacy'); + await ClickBtn('LegacyIgnoreBtn'); + await OnScreen('MenuFresh'); + Check('ignore puts it off: OLD VERSION on the menu', await Visible('#FreshLegacyBtn') && (await Hook('State')).Registry.LegacyInstallPath === Old); + await Open(); + Check('put off: the installer opens on the menu', await OnScreen('MenuFresh') && await Visible('#FreshLegacyBtn')); + await ClickBtn('FreshLegacyBtn'); + await OnScreen('Legacy'); + + // choice 4: ignore + don't ask again await Page.click('[data-screen=Legacy] .InstCheckboxRow'); await ClickBtn('LegacyIgnoreBtn'); await OnScreen('MenuFresh'); Check('ignore + don\'t ask again saved', (await Hook('State')).Registry.LegacyInstallPath === 'Ignore'); await Open(); - Check('not asked again', await OnScreen('MenuFresh')); + Check('not asked again', await OnScreen('MenuFresh') && !(await Visible('#FreshLegacyBtn'))); // ------------------------------------------------------------ D. no internet on a fresh PC await Hook('Server', { Offline: true, Forget: true }); diff --git a/Production/Installer/Tests/UiHarness.py b/Production/Installer/Tests/UiHarness.py index 04bdc16..3fb979a 100644 --- a/Production/Installer/Tests/UiHarness.py +++ b/Production/Installer/Tests/UiHarness.py @@ -15,6 +15,8 @@ POST /__TestHook/Server {"HoldList", "ChunkDelay", "Offline", "Forget"} -> fake release server behaviour (Forget: drop the cached list) POST /__TestHook/Running {"Running": true|false} -> pretend RAMMIT is (not) running POST /__TestHook/SlowUninstall {"Delay": seconds per progress step} + POST /__TestHook/SlowResize {"Delay": seconds} -> every ResizeInstaller call takes that long (and resets the + most calls seen in flight at once, which State reports as ResizesInFlight) POST /__TestHook/Legacy makes a fake Test1 install at \\OldRAMMIT and points the registry at it POST /__TestHook/Accounts {"Path"} -> writes a dummy Config\\Accounts.json there (no cookies) POST /__TestHook/StartScreen {"Screen"} -> as if started with /Uninstall @@ -78,7 +80,8 @@ def DeleteKeys(): DeleteKeys() -Fake = {"Events": [], "EventLog": [], "Lock": threading.Lock(), "LastResize": None, "Launches": 0, "Closed": 0, "Running": False, "UninstallDelay": 0.0} +Fake = {"Events": [], "EventLog": [], "Lock": threading.Lock(), "LastResize": None, "Launches": 0, "Closed": 0, "Running": False, "UninstallDelay": 0.0, + "ResizeDelay": 0.0, "InFlight": 0, "MostInFlight": 0, "LastAsked": None} class FakeWindow: @@ -118,6 +121,25 @@ def SlowUninstallProgress(**Data): Bridge._UninstallProgress = SlowUninstallProgress +RealResizeInstaller = Bridge.ResizeInstaller + + +def CountedResizeInstaller(Height, ViewportHeight=None): + """The real ResizeInstaller, counting how many calls overlap (the page must send them one at a time, #8).""" + with Fake["Lock"]: + Fake["InFlight"] += 1 + Fake["MostInFlight"] = max(Fake["MostInFlight"], Fake["InFlight"]) + try: + if Fake["ResizeDelay"]: + time.sleep(Fake["ResizeDelay"]) + Fake["LastAsked"] = Height + return RealResizeInstaller(Height, ViewportHeight) + finally: + with Fake["Lock"]: + Fake["InFlight"] -= 1 + + +Bridge.ResizeInstaller = CountedResizeInstaller class TestHandler(UiServer._Handler): @@ -141,6 +163,11 @@ def do_POST(self): elif self.path == "/__TestHook/SlowUninstall": Fake["UninstallDelay"] = float(Body["Delay"]) Result = {"Ok": True} + elif self.path == "/__TestHook/SlowResize": + with Fake["Lock"]: + Fake["ResizeDelay"] = float(Body["Delay"]) + Fake["MostInFlight"] = Fake["InFlight"] + Result = {"Ok": True} elif self.path == "/__TestHook/Legacy": Old = os.path.join(ScratchDir, "OldRAMMIT") if not os.path.isdir(Old): @@ -175,6 +202,7 @@ def do_GET(self): return self._Json(list(Fake["EventLog"])) if self.path == "/__TestHook/State": return self._Json({"LastResize": Fake["LastResize"], "Launches": Fake["Launches"], "Closed": Fake["Closed"], + "ResizesInFlight": Fake["MostInFlight"], "LastAskedHeight": Fake["LastAsked"], "Registry": Support.RegValues(L.RegKeyPath), "Apps": Support.RegValues(L.UninstallKeyPath)}) return super().do_GET() diff --git a/Production/RAMMIT-Stable/App/Api.py b/Production/RAMMIT-Stable/App/Api.py index 0ad5b38..9c59ba1 100644 --- a/Production/RAMMIT-Stable/App/Api.py +++ b/Production/RAMMIT-Stable/App/Api.py @@ -111,8 +111,9 @@ def AddAccount(self): def RenewAccount(self, Username): """Sign in again for an expired account (RENEW). Waits until the login window is done, so RENEW AND LAUNCH can - launch right after: {"Renewed": True} when the same Roblox user signed in, {"Renewed": False} when it was a - different account (added as a new one) or the window was closed.""" + launch right after: {"Renewed": True, "Username": its name now} when the same Roblox user signed in (the name + changes when the account was renamed on Roblox), {"Renewed": False} when it was a different account (added as a + new one) or the window was closed.""" Account = self._AccountByName(Username) if not Account: return {"Error": "Account not found."} @@ -122,7 +123,9 @@ def RenewAccount(self, Username): if "Error" in Opened: return Opened Done.wait(LoginTimeoutSeconds + 10) - return {"Ok": True, "Renewed": Outcome.get("Result") == "Renewed"} + if Outcome.get("Result") == "Renewed": + return {"Ok": True, "Renewed": True, "Username": Outcome.get("Username", Account["Username"])} + return {"Ok": True, "Renewed": False} def _OpenLogin(self, Title, RenewFor=None, Done=None, Outcome=None): with self._LoginLock: @@ -154,7 +157,7 @@ def _PollLogin(self, Window, RenewFor=None, Done=None, Outcome=None): Window.clear_cookies() except Exception: pass - Result = self._FinishLogin(Cookie, RenewFor) + Result = self._FinishLogin(Cookie, RenewFor, Outcome) if Outcome is not None: Outcome["Result"] = Result break @@ -175,10 +178,10 @@ def _FindLoginCookie(CookieJars): return Morsel.value return None - def _FinishLogin(self, Cookie, RenewFor=None): + def _FinishLogin(self, Cookie, RenewFor=None, Outcome=None): """Saves a new login. Renewing (RenewFor = an account's username): the same Roblox user replaces that account's login in place (same user id, or same username if its id isn't known yet); a different user is added as a new - account instead. Returns "Renewed", "Added", or None on failure.""" + account instead. Returns "Renewed", "Added", or None on failure; Outcome["Username"] gets the saved name.""" State, User = Roblox.CheckLogin(Cookie) if State != "Valid": self._Notify("ShowMessage", {"Text": "Login worked but Roblox did not confirm the account. Try again.", "Error": True}) @@ -193,9 +196,10 @@ def _FinishLogin(self, Cookie, RenewFor=None): OldName = Target["Username"] Target.update({"Username": Username, "DisplayName": DisplayName, "UserId": UserId, "Cookie": Cookie, "Stored": None}) self._Expired.discard(OldName.lower()) - if OldName != Username: # renamed on Roblox: keep it selected under its new name + if OldName != Username: # renamed on Roblox: keep it selected, and its open client, under its new name self._Settings["SelectedAccounts"] = [Username if N == OldName else N for N in self._Settings["SelectedAccounts"]] self._SaveSettings() + self._Clients.Rename(OldName, Username) else: self._Accounts = [A for A in self._Accounts if A["Username"].lower() != Username.lower() and A["UserId"] != UserId] self._Accounts.append({"Username": Username, "DisplayName": DisplayName, "UserId": UserId, "Cookie": Cookie, "Stored": None}) @@ -205,6 +209,8 @@ def _FinishLogin(self, Cookie, RenewFor=None): Logger.error("Could not save account %s: %s", Username, type(Error).__name__) self._Notify("ShowMessage", {"Text": "Could not save the account securely.", "Error": True}) return None + if Outcome is not None: + Outcome["Username"] = Username if Same: Logger.info("Renewed account %s", Username) else: @@ -422,8 +428,12 @@ def _LaunchOne(self, Username, Option, Params): Ticket = Roblox.GetAuthTicket(Cookie) if Ticket is Roblox.LoginExpired: with self._DataLock: - self._Expired.add(Account["Username"].lower()) - self._Notify("AccountsChanged") + # Not when a new login was saved meanwhile: RENEW updates this same entry, + ADD replaces it. + Marked = any(A is Account for A in self._Accounts) and Account["Cookie"] is Cookie + if Marked: + self._Expired.add(Account["Username"].lower()) + if Marked: + self._Notify("AccountsChanged") return {"Error": ExpiredMessage} if not Ticket: return {"Error": "Auth failed."} @@ -432,7 +442,12 @@ def _LaunchOne(self, Username, Option, Params): except ValueError as Error: return {"Error": str(Error)} self._Clients.Expect(Ticket, Account["Username"]) # before the client exists, so no scan can miss it - Proc = subprocess.Popen([Exe, LaunchUrl], creationflags=subprocess.CREATE_NO_WINDOW) + try: + Proc = subprocess.Popen([Exe, LaunchUrl], creationflags=subprocess.CREATE_NO_WINDOW) + except OSError as Error: + self._Clients.Forget(Ticket) # or it would count as "starting" until it times out + Logger.warning("Could not start Roblox: %s", type(Error).__name__) + return {"Error": "Could not start Roblox."} self._Clients.Started(Ticket, Proc.pid) Logger.info("Launched %s (%s)", Username, Option) return {"Ok": True} diff --git a/Production/RAMMIT-Stable/App/Install.py b/Production/RAMMIT-Stable/App/Install.py index 546a9b3..d414551 100644 --- a/Production/RAMMIT-Stable/App/Install.py +++ b/Production/RAMMIT-Stable/App/Install.py @@ -5,15 +5,22 @@ folder and the recorded one no longer has a RAMMIT.exe, the folder was moved: both are pointed here (plus the Settings > Apps entry), so every RAMMIT: shortcut works again, wherever it is, and the installer finds RAMMIT for updates. -A second copy started while the installed one is still in place changes nothing, and neither does a copy that was never -installed (no InstallPath). Main.py only calls this from the frozen exe, so running from source never touches the registry. +Only a folder the installer made can take over: it holds the installer's Manifest.json, which a copy unzipped from a +release (or opened straight from the zip) doesn't. A second copy started while the installed one is still in place changes +nothing, and neither does a copy that was never installed (no InstallPath), one on a removable drive (it would break again +once the drive is gone), or one started by the installer's test mode (RAMMIT_INSTALLER_TEST=1, inherited from the test +installer, which must never touch the real entries). Main.py only calls this from the frozen exe, so running from source +never touches the registry. """ +import ctypes import os import winreg RegKeyPath = r"Software\CBlock Digital\RAMMIT" ProtocolKeyPath = r"Software\Classes\RAMMIT" UninstallKeyPath = r"Software\Microsoft\Windows\CurrentVersion\Uninstall\RAMMIT" +ManifestName = "Manifest.json" # what the installer writes into every folder it installs (Installer/Setup.py) +DriveRemovable = 2 # GetDriveTypeW def _Read(KeyPath, Name=""): @@ -33,6 +40,16 @@ def _SamePath(First, Second): return os.path.normcase(os.path.realpath(First)) == os.path.normcase(os.path.realpath(Second)) +def _OnRemovableDrive(Folder): + Drive = os.path.splitdrive(os.path.abspath(Folder))[0] + if not Drive or Drive.startswith("\\\\"): + return False # a network share is fixed enough + try: + return ctypes.windll.kernel32.GetDriveTypeW(Drive + "\\") == DriveRemovable + except (AttributeError, OSError): + return False + + def _RegisterProtocol(ProtocolKey, Exe): """Same entries as the installer's Setup.RegisterProtocol: RAMMIT: starts Exe, with nothing from the link.""" _Write(ProtocolKey, "", "URL:RAMMIT") @@ -43,10 +60,14 @@ def _RegisterProtocol(ProtocolKey, Exe): def Sync(BaseDir, RegKey=RegKeyPath, ProtocolKey=ProtocolKeyPath, UninstallKey=UninstallKeyPath): """Returns "Moved" (InstallPath and RAMMIT: now point at BaseDir), "Fixed" (only RAMMIT: was re-pointed), or "".""" + if os.environ.get("RAMMIT_INSTALLER_TEST") == "1": + return "" # started by the installer's test mode Recorded = _Read(RegKey, "InstallPath") Exe = os.path.join(BaseDir, "RAMMIT.exe") if not Recorded or not os.path.isfile(Exe): return "" # never installed with the installer (or uninstalled) + if not os.path.isfile(os.path.join(BaseDir, ManifestName)) or _OnRemovableDrive(BaseDir): + return "" # not a folder the installer made (e.g. a release zip's copy), or on a removable drive Result = "" if not _SamePath(Recorded, BaseDir): if os.path.isfile(os.path.join(Recorded, "RAMMIT.exe")): diff --git a/Production/RAMMIT-Stable/App/MultiInstance.py b/Production/RAMMIT-Stable/App/MultiInstance.py index 0a024aa..4a39912 100644 --- a/Production/RAMMIT-Stable/App/MultiInstance.py +++ b/Production/RAMMIT-Stable/App/MultiInstance.py @@ -86,15 +86,19 @@ def LockCookieFile(): GameWindowClass = "WINDOWSCLIENT" -StartTimeout = 120 # seconds a launch may take to show up before it stops counting as "starting" +StartTimeout = 120 # seconds a launch whose process RAMMIT never saw start keeps counting as "starting" +StartingCap = 600 # a launch process that is still alive counts as "starting" until its game window shows, at most this long def _PlayerPids(): """Pids of every RobloxPlayerBeta.exe. Names only: asking every process for more is very slow.""" Pids = set() - for Proc in psutil.process_iter(["name"]): - if Proc.info["name"] == PlayerExe: - Pids.add(Proc.pid) + try: + for Proc in psutil.process_iter(["name"]): + if Proc.info["name"] == PlayerExe: + Pids.add(Proc.pid) + except (psutil.Error, OSError) as Error: + Logger.warning("Could not list processes: %s", type(Error).__name__) return Pids @@ -131,6 +135,14 @@ def _ParentPid(Pid): return None +def _CreateTime(Pid): + """When the process with this pid started, or None. Tells a reused pid from the process RAMMIT tracked.""" + try: + return psutil.Process(Pid).create_time() + except (psutil.Error, OSError): + return None + + def _Alive(Pid): return psutil.pid_exists(Pid) @@ -141,30 +153,56 @@ def _Alive(Pid): class ClientTracker: """Which account each running Roblox client belongs to. Keep it in a _-prefixed Api attribute: it holds tickets. - The process RAMMIT starts belongs to the account (Started). A Roblox process whose parent belongs to an account that - hasn't shown its game window yet takes that account over: Roblox can hand a launch to a "--launch-to-tray" child - that opens the window, and Bloxstrap / Fishstrap start Roblox as a child. Failing that, the launch ticket on the - command line. A child started after the window was shown (the tray process a closed game leaves) takes nothing.""" + Every launch gets an id. The process RAMMIT starts belongs to the launch (Started). A Roblox process whose parent + belongs to a launch that hasn't shown its game window yet takes that launch over: Roblox can hand a launch to a + "--launch-to-tray" child that opens the window, and Bloxstrap / Fishstrap start Roblox as a child. Failing that, the + launch ticket on the command line (kept until the launch's window shows, so a process that isn't a child, such as + one Roblox's updater starts, is still found). A child started after the window was shown (the tray process a closed + game leaves) takes nothing. A launch counts as "starting" once, however many of its processes are alive.""" def __init__(self): self._Lock = threading.Lock() - self._Expected = [] # (launch ticket, Username, time launched) per launch whose process isn't known yet - self._Owners = {} # pid -> {"User": Username or None, "Since", "Shown": had a game window, "Gone": time or None} - self._Last = {} # Username -> "starting" / "running", from the last Scan() + self._NextLaunch = 1 + # per launch until its game window shows (or it times out): {"Ticket", "User", "At", "Launch", "Pid": started pid} + self._Expected = [] + # pid -> {"User": Username or None, "Since", "Launch": id or None, "Shown": had a game window, + # "Gone": time or None, "Created": the process's start time (a reused pid is a different process)} + self._Owners = {} + self._ShownLaunches = set() # launches whose game window has shown: they never count as "starting" again + self._CappedLaunches = set() # launches that passed StartingCap without a game window (logged once) + self._Last = {} # Username -> "starting" / "running", from the last Scan() def Expect(self, Ticket, Username): with self._Lock: - self._Expected.append((Ticket, Username, time.monotonic())) + self._Expected.append({"Ticket": Ticket, "User": Username, "At": time.monotonic(), "Launch": self._NextLaunch, + "Pid": None}) + self._NextLaunch += 1 def Started(self, Ticket, Pid): """The process RAMMIT started for the launch Expect()ed with Ticket.""" + Created = _CreateTime(Pid) with self._Lock: for Entry in self._Expected: - if Entry[0] == Ticket: - self._Expected.remove(Entry) - self._Owners[Pid] = {"User": Entry[1], "Since": Entry[2], "Shown": False, "Gone": None} + if Entry["Ticket"] == Ticket and Entry["Pid"] is None: + Entry["Pid"] = Pid + self._Owners[Pid] = {"User": Entry["User"], "Since": Entry["At"], "Launch": Entry["Launch"], + "Shown": False, "Gone": None, "Created": Created} break + def Forget(self, Ticket): + """The launch Expect()ed with Ticket never started (starting its process failed).""" + with self._Lock: + self._Expected = [Entry for Entry in self._Expected if Entry["Ticket"] != Ticket] + + def Rename(self, OldName, NewName): + """An account was renamed on Roblox (renewed under its new name): its launches and clients stay its own.""" + with self._Lock: + for Item in self._Expected + list(self._Owners.values()): + if Item["User"] == OldName: + Item["User"] = NewName + if OldName in self._Last: + self._Last[NewName] = self._Last.pop(OldName) + def Scan(self, IncludeStarting=True): """Number of running clients: game windows, plus launches still starting unless IncludeStarting is False (the instance limit counts them, so a batch can't overshoot; the counter label doesn't). Also refreshes Accounts().""" @@ -172,40 +210,67 @@ def Scan(self, IncludeStarting=True): with self._Lock: Now = time.monotonic() for Pid, Info in list(self._Owners.items()): + # The pid now belongs to another process (any program, also after the tracked one was marked Gone): + # the tracked one is gone. Dropping it lets the loop below look at the new process in this same Scan. + Reused = Info["Created"] is not None and _CreateTime(Pid) not in (None, Info["Created"]) + if Reused or (Info["Gone"] is not None and Info["Created"] is None and Pid in PlayerPids): + del self._Owners[Pid] + continue if Info["Gone"] is None and Pid not in PlayerPids and not _Alive(Pid): Info["Gone"] = Now if Info["Gone"] is not None and Now - Info["Gone"] > GoneKeep: del self._Owners[Pid] - elif Pid in WindowPids: + elif Info["Gone"] is None and Pid in WindowPids: Info["Shown"] = True + if Info["Launch"]: + self._ShownLaunches.add(Info["Launch"]) for Pid in PlayerPids - set(self._Owners): - Owner, Since = None, Now + Owner, Since, Launch = None, Now, None Parent = self._Owners.get(_ParentPid(Pid)) - if Parent and Parent["User"] and not Parent["Shown"]: - Owner, Since = Parent["User"], Parent["Since"] + if Parent and Parent["User"] and not Parent["Shown"] and Parent["Launch"] not in self._ShownLaunches: + Owner, Since, Launch = Parent["User"], Parent["Since"], Parent["Launch"] else: Line = _CommandLine(Pid) for Entry in self._Expected: - if "gameinfo:" + Entry[0] in Line: - Owner, Since = Entry[1], Entry[2] - self._Expected.remove(Entry) + if "gameinfo:" + Entry["Ticket"] in Line: + Owner, Since, Launch = Entry["User"], Entry["At"], Entry["Launch"] + Entry["Pid"] = Entry["Pid"] or Pid break - self._Owners[Pid] = {"User": Owner, "Since": Since, "Shown": Pid in WindowPids, "Gone": None} - self._Expected = [Entry for Entry in self._Expected if Now - Entry[2] <= StartTimeout] - Accounts = {Username: "starting" for _Ticket, Username, _At in self._Expected} + Shown = Pid in WindowPids + self._Owners[Pid] = {"User": Owner, "Since": Since, "Launch": Launch, "Shown": Shown, "Gone": None, + "Created": _CreateTime(Pid)} + if Shown and Launch: + self._ShownLaunches.add(Launch) + # A launch is done once its window shows. One whose process was never seen gives up after StartTimeout. + self._Expected = [Entry for Entry in self._Expected if Entry["Launch"] not in self._ShownLaunches + and Now - Entry["At"] <= (StartingCap if Entry["Pid"] else StartTimeout)] + Accounts, Starting = {}, {} # Starting: launch id -> Username for Pid, Info in self._Owners.items(): - if not Info["User"] or Info["Gone"] is not None: - continue - if Pid in WindowPids: + if Info["User"] and Info["Gone"] is None and Pid in WindowPids: Accounts[Info["User"]] = "running" - elif not Info["Shown"] and Now - Info["Since"] <= StartTimeout: - Accounts.setdefault(Info["User"], "starting") + for Info in self._Owners.values(): + Launch = Info["Launch"] + if not Info["User"] or Info["Gone"] is not None or not Launch or Launch in self._ShownLaunches: + continue + if Now - Info["Since"] <= StartingCap: + Starting[Launch] = Info["User"] + elif Launch not in self._CappedLaunches: + self._CappedLaunches.add(Launch) + Logger.warning("A Roblox launch has shown no game window for %d s; it no longer counts as starting", StartingCap) + for Entry in self._Expected: + if Entry["Pid"] is None: # its process isn't known yet + Starting.setdefault(Entry["Launch"], Entry["User"]) + for Username in Starting.values(): # also over "running": a relaunch isn't open until its own window is + Accounts[Username] = "starting" + Live = {Info["Launch"] for Info in self._Owners.values()} | {Entry["Launch"] for Entry in self._Expected} + self._ShownLaunches &= Live + self._CappedLaunches &= Live self._Last = Accounts - Starting = sum(1 for State in Accounts.values() if State == "starting") - return len(WindowPids & PlayerPids) + (Starting if IncludeStarting else 0) + return len(WindowPids & PlayerPids) + (len(Starting) if IncludeStarting else 0) def Accounts(self): - """{Username: "starting" or "running"} for RAMMIT's own launches, as of the last Scan(). Closed ones are absent.""" + """{Username: "starting" or "running"} for RAMMIT's own launches, as of the last Scan(). Closed ones are absent. + "starting" while any launch of the account is still starting, also when it already has another game open.""" with self._Lock: return dict(self._Last) diff --git a/Production/RAMMIT-Stable/App/Version.py b/Production/RAMMIT-Stable/App/Version.py index 586383b..927cb1b 100644 --- a/Production/RAMMIT-Stable/App/Version.py +++ b/Production/RAMMIT-Stable/App/Version.py @@ -7,7 +7,7 @@ """ AppName = "RAMMIT" -AppVersion = "1.1.2" +AppVersion = "1.2.0" try: from App.BuildInfo import AppChannel, AppCommit diff --git a/Production/RAMMIT-Stable/App/WindowSize.py b/Production/RAMMIT-Stable/App/WindowSize.py index 7410b99..2b62d31 100644 --- a/Production/RAMMIT-Stable/App/WindowSize.py +++ b/Production/RAMMIT-Stable/App/WindowSize.py @@ -21,6 +21,7 @@ class HeldWindow: def __init__(self, Window): self._Window = Window self._Dragging = False + self._Lock = threading.Lock() # Resize (a page call's thread) and the let-go reapply (its own thread) self._Width = 0 # logical px last asked for self._Height = 0 Events = getattr(Window, "events", None) @@ -36,25 +37,27 @@ def _WatchDrags(self): Logger.warning("Can't watch window drags: %s", type(Error).__name__) def Resize(self, Width, Height): - self._Width, self._Height = Width, Height - if self._Dragging: - return # held: Windows would undo it; _OnLetGo applies it - self._Window.resize(Width, Height) + with self._Lock: + self._Width, self._Height = Width, Height + if self._Dragging: + return # held: Windows would undo it; _OnLetGo applies it + self._Window.resize(Width, Height) def _OnLetGo(self, _Sender, _Args): self._Dragging = False threading.Thread(target=self._ReapplyHeight, daemon=True).start() def _ReapplyHeight(self): - if not self._Height: - return - try: - Native = self._Window.native - Scale = self._WindowScale(Native) - if abs(Native.Height / Scale - self._Height) >= 2: - self._SetHeight(Native, round(self._Height * Scale)) - except Exception: - pass + with self._Lock: + if not self._Height: + return + try: + Native = self._Window.native + Scale = self._WindowScale(Native) + if abs(Native.Height / Scale - self._Height) >= 2: + self._SetHeight(Native, round(self._Height * Scale)) + except Exception: + pass @staticmethod def _WindowScale(Native): diff --git a/Production/RAMMIT-Stable/CHANGELOG.md b/Production/RAMMIT-Stable/CHANGELOG.md index 46444f2..c4f2fbd 100644 --- a/Production/RAMMIT-Stable/CHANGELOG.md +++ b/Production/RAMMIT-Stable/CHANGELOG.md @@ -1,22 +1,23 @@ # Changelog -## 1.1.2 (2026-11) +## 1.2.0 (2026-11) -- **Installer:** the window no longer stays at the Loading screen's height. Grabbing or dragging the title bar while the screen changed undid the resize; a resize that arrives while the window is held now waits and is applied once when you let go. +- **Installer:** the window no longer stays at the Loading screen's height. Grabbing or dragging the title bar while the screen changed undid the resize; a resize that arrives while the window is held now waits and is applied once when you let go. Two resizes sent close together could also finish in the wrong order and leave the window at the older height; they are now sent one at a time, and only the newest waiting one is sent, so the newest height always wins (#8). - **Installer:** the window opens at the Loading screen's real height (`HeightMap.json` Loading 327 → 323), so it no longer shrinks a few pixels right after opening, and the space above and below the card is even. - **Installer:** pressing **Ignore** on the "older test version" screen without ticking "Don't ask again" now puts it off instead of asking every time: the menu opens as normal, with an **OLD VERSION** button and a line saying where the old version is. It stays reachable after installing the new RAMMIT, and goes away once the old version is moved or removed. - **Installer:** with RAMMIT already installed, the old version's screen keeps all four choices. The two "move my accounts" choices then copy its accounts and settings into the installed RAMMIT without reinstalling it, and the first one removes the old version afterwards. -- **Installer:** the "Uninstall Config/ folder too" tick box no longer shows its check mark while unticked (#2). +- **Installer:** the "Uninstall Config/ folder too" tick box no longer shows its check mark while unticked (#2, fixed in #5 by ShahadatTest). - **Installer:** you choose whether to get a **Desktop shortcut** and a **Start Menu shortcut** (both ticked by default), and the done screen says which were added. Updates, repairs and undo keep that choice instead of always recreating both. - **Installer:** the update / repair / undo done screen has **LAUNCH RAMMIT** next to **CLOSE**, like the install done screen. -- **Shortcuts survive moving RAMMIT:** the installer's shortcuts (`RAMMIT.url`) now open the `RAMMIT:` protocol instead of naming RAMMIT's folder. If you move the RAMMIT folder by hand, open `RAMMIT.exe` from its new place once: it points the protocol, the installer's registry entry and the Settings > Apps entry at the new folder, and every RAMMIT shortcut works again, wherever you put it. A second copy started while the installed one is still in place changes nothing. Old `RAMMIT.lnk` shortcuts are replaced on the next install or update. +- **Shortcuts survive moving RAMMIT:** the installer's shortcuts (`RAMMIT.url`) now open the `RAMMIT:` protocol instead of naming RAMMIT's folder. If you move the RAMMIT folder by hand, open `RAMMIT.exe` from its new place once: it points the protocol, the installer's registry entry and the Settings > Apps entry at the new folder, and every RAMMIT shortcut works again, wherever you put it. A second copy started while the installed one is still in place changes nothing. Old `RAMMIT.lnk` shortcuts are replaced on the next install or update. Only a folder the installer made can take over (it has the installer's `Manifest.json`): a copy unzipped from a release, one on a USB stick and one started by the installer's test mode change nothing. Windows doesn't offer **Pin to taskbar** for these `.url` shortcuts as it did for the old `.lnk` ones: pin RAMMIT from its taskbar button while it runs instead. If the icon's path can't be written in the shortcut (a Windows user name with characters outside its code page), the shortcut shows the default icon. - **Installer:** "don't ask again" for an old version is now stored as `LegacyInstallPath=Ignore` instead of a separate `IgnoreLegacyInstall` value (the old value is carried over). -- **Launch tracking:** RAMMIT now knows which Roblox client belongs to which account. It follows the process it started, including when Roblox hands the game to a child process that opens the window, and falls back to matching each launch's one-time ticket on the client's command line. An account shows "•••" while Roblox starts, "✓" only once its game window is open, and its mark clears when that window closes, so you can see which account closed. The running counter only counts open game windows: launches still starting count only towards Max Instances, and Roblox's tray process (started when a game closes) and its right-click menu no longer count at all. The status line under the launch button only says "Launched" once the accounts' windows are open (it stops waiting after 30 seconds). -- **Expired logins** (back from the Test1 build): saved logins are checked at start-up and every 5 minutes, and an account whose login Roblox rejects turns red. With exactly that account selected, **+ ADD** becomes **RENEW** and **LAUNCH** becomes **RENEW AND LAUNCH**, which signs you in again first. Renewing keeps the account if the same Roblox user signs in (checked by user ID, so a renamed account still counts); a different user is added as a new account instead. A launch that Roblox rejects also marks the account. A check that can't reach Roblox never marks anything. -- **Tooltips:** every button and setting has a tooltip, drawn in the theme's own colours instead of the plain Windows one. It follows the cursor and flips to the other side near the window's edges. CBlock's are rounded; a custom theme can set `--TooltipRadius`. +- **Launch tracking:** RAMMIT now knows which Roblox client belongs to which account. It follows the process it started, including when Roblox hands the game to a child process that opens the window, and falls back to matching each launch's one-time ticket on the client's command line. An account shows "•••" while Roblox starts, "✓" only once its game window is open, and its mark clears when that window closes, so you can see which account closed. The running counter only counts open game windows: launches still starting count only towards Max Instances, and Roblox's tray process (started when a game closes) and its right-click menu no longer count at all. The status line under the launch button only says "Launched" once the accounts' windows are open (it stops waiting after 30 seconds). Each launch counts once towards Max Instances, also when the account already has a game open (its row shows "•••" until the new window is open); a launch whose window never shows stops counting after 10 minutes. If Roblox can't be started at all, the row shows the error instead of "•••". A client is still found by its ticket when it isn't a child of the process RAMMIT started (for example after a Roblox update), and a process number Windows reuses for another program is never taken for an account's client. +- **Expired logins** (back from the Test1 build): saved logins are checked at start-up and every 5 minutes, and an account whose login Roblox rejects turns red. With exactly that account selected, **+ ADD** becomes **RENEW** and **LAUNCH** becomes **RENEW AND LAUNCH**, which signs you in again first. Renewing keeps the account if the same Roblox user signs in (checked by user ID, so a renamed account still counts); a different user is added as a new account instead. A launch that Roblox rejects also marks the account. A check that can't reach Roblox never marks anything. The check sends each saved login only to Roblox (`users.roblox.com`), as a launch already does. Renewing an account that was renamed on Roblox keeps it selected under its new name, so **RENEW AND LAUNCH** launches it. An expired row stays readable in every theme, selected or not (a theme sets its text colour with `--OnExpired`). +- **Tooltips:** every button and setting has a tooltip, drawn in the theme's own colours instead of the plain Windows one. It follows the cursor and flips to the other side near the window's edges. CBlock's are rounded; a custom theme can set `--TooltipRadius`. A button that shows only an icon keeps its tooltip text as its name for screen readers, and a tooltip that is showing updates when its text changes (for example **+ ADD** turning into **RENEW**). - The main window opens at its `HeightMap.json` height for the saved launch option, instead of opening shorter and resizing once the page has loaded. -- The main window and the config window keep the right height when you grab or drag their title bar while they resize: the resize waits and is applied when you let go (the same fix as the installer's). -- The theme colour swatch next to the Theme drop-down has straight edges instead of jagged ones. +- The main window and the config window keep the right height when you grab or drag their title bar while they resize: the resize waits and is applied when you let go (the same fix as the installer's). They also send their resizes one at a time, like the installer. +- The theme colour swatch next to the Theme drop-down has straight edges instead of jagged ones. `Tools/RenderTheme.py` draws its swatch the same way. +- **Themes:** the built-in themes list `"1.2"` in `SupportedVersions`. A theme you made for 1.0 or 1.1 opens in Dark after this update until you allow it, or add `"1.2"` to its `Theme.json`. To get the red expired rows, RENEW and the tooltips in it, copy Dark's `HTML\`, `JS\` and the LAYOUT part of `CSS\Style.css` into it. New colour variables: `--OnExpired`, and `--TooltipRadius` (optional). ## 1.1.1 (2026-11) diff --git a/Production/RAMMIT-Stable/Docs/HowToMakeATheme.txt b/Production/RAMMIT-Stable/Docs/HowToMakeATheme.txt index c7862d8..478aa0b 100644 --- a/Production/RAMMIT-Stable/Docs/HowToMakeATheme.txt +++ b/Production/RAMMIT-Stable/Docs/HowToMakeATheme.txt @@ -37,16 +37,16 @@ press the "?" button, then "Making your own theme". "Name": "Ocean Blue", "Author": "Your Name", "Description": "Deep blue with a teal accent.", - "SupportedVersions": ["1.0"] + "SupportedVersions": ["1.2"] } "SupportedVersions" says which RAMMIT versions your theme was made for. The version is at the bottom of the Settings panel - (for example "RAMMIT v1.1.2 - Stable"). + (for example "RAMMIT v1.2.0 - Stable"). "1.0" any 1.0.x (1.0.0, 1.0.1, ...) "1.0.2" exactly 1.0.2 "1.2+" 1.2.0 and everything newer - You can list several: ["1.0", "1.1"]. + You can list several: ["1.1", "1.2"]. If someone picks your theme on a RAMMIT version it doesn't list, RAMMIT asks them first. After a RAMMIT update it opens in Dark and asks before using your theme. Leave the field out and RAMMIT never @@ -87,8 +87,10 @@ press the "?" button, then "Making your own theme". --AccentHover Accent when the mouse is over it --Success launched marks, CONFIRM, the channel tick --SuccessHover - --Danger - REMOVE, errors, CANCEL + --Danger - REMOVE, errors, CANCEL, the row of an expired login --DangerHover + --OnExpired text on an expired login's red row: white, or a dark + colour if your --Danger is light (check it's readable) --Warning "launching" marks and warnings --Border thin lines --BorderLight slightly brighter lines @@ -102,6 +104,8 @@ press the "?" button, then "Making your own theme". e.g. 'Bahnschrift', 'Segoe UI', sans-serif --Radius corner rounding of panels, e.g. 8px --ButtonRadius corner rounding of buttons and boxes, e.g. 6px + --TooltipRadius corner rounding of tooltips, e.g. 4px (optional: + leave it out for square ones) Tip: light theme? Start from the "Light" folder - it already has dark text on light panels. Starting from Dark and only changing the diff --git a/Production/RAMMIT-Stable/Docs/README.txt b/Production/RAMMIT-Stable/Docs/README.txt index 470a70a..46306b9 100644 --- a/Production/RAMMIT-Stable/Docs/README.txt +++ b/Production/RAMMIT-Stable/Docs/README.txt @@ -1,5 +1,5 @@ ======================================================== - RAMMIT - Roblox Multi-Account Launcher (v1.1.2) + RAMMIT - Roblox Multi-Account Launcher (v1.2.0) Setup Guide (read this first) ======================================================== @@ -10,7 +10,7 @@ them at the same time on one PC. You do NOT need Python or any other program installed - everything RAMMIT needs is inside this folder. The bottom of the Settings panel shows your version, for example -"RAMMIT v1.1.2 · Stable". Please include it when you report a problem. +"RAMMIT v1.2.0 · Stable". Please include it when you report a problem. WHAT YOU NEED @@ -96,9 +96,15 @@ TROUBLESHOOTING * "Accounts won't launch": Make sure Roblox is installed and you can open it normally first. Hover the red X next to an account to read why it failed. + * An account's row turned red, or "Cookie expired. Renew this account.": + Its saved login expired (for example you changed your password). + Click that account alone: + ADD becomes RENEW (and LAUNCH becomes + RENEW AND LAUNCH). Press it and sign in to the same account again. + RAMMIT checks the saved logins with Roblox (users.roblox.com only) + when it starts and every 5 minutes; nothing goes anywhere else. * "Auth failed": - The saved login expired (for example you changed your password). - Remove the account and add it again. + Roblox didn't answer, or asked RAMMIT to slow down. Wait a minute and + try again. * A log file is kept at Config\RAMMIT.log (it never contains logins). diff --git a/Production/RAMMIT-Stable/README.md b/Production/RAMMIT-Stable/README.md index 86f27b9..9d238dc 100644 --- a/Production/RAMMIT-Stable/README.md +++ b/Production/RAMMIT-Stable/README.md @@ -56,10 +56,11 @@ README.txt, HowToMakeATheme.txt | `Storage.py` | Config files: atomic writes, settings schema + validation, legacy migration, configs, accounts | | `Crypto.py` | DPAPI encryption of saved login cookies | | `Roblox.py` | Roblox web APIs, server picking, VIP links, the `roblox-player:` launch URI, launcher path, registry channel | -| `MultiInstance.py` | Singleton-name mutex and cookie-file lock; counts running clients (pywin32 + psutil) | +| `MultiInstance.py` | Singleton-name mutex and cookie-file lock; counts running clients (game windows only) and tracks which client is which account (`ClientTracker`: the launched process, its children, then the launch ticket) | | `LocalServer.py` | Hardened static server for the active theme folder | | `Themes.py` | Theme discovery, `HeightMap.json`, fallback to Dark | | `Paths.py`, `Log.py`, `Version.py` | Locations, the log file, the version string | +| `WindowSize.py` | Resizes the main window and the config wizard; while the title bar is held, waits and applies the height once it is let go | | `Install.py` | When the installed folder was moved by hand, points the installer's registry entries and the `RAMMIT:` shortcut protocol at the new place | ### Frontend (`Src//JS/`, plain ES modules, no build step) @@ -67,13 +68,14 @@ README.txt, HowToMakeATheme.txt | Module | Responsibility | |---|---| | `Main.js` / `Wizard.js` | Entry points of `Index.html` / `Wizard.html` | -| `Bridge.js` | `Api.X()` proxy to Python, `On(event)` for Python→JS events, `ReportError` | +| `Bridge.js` | `Api.X()` proxy to Python, `On(event)` for Python→JS events, `ReportError`, `OneAtATime` (calls such as resizes, one at a time) | | `State.js` | Shared main-window state | | `Dom.js` | `El()` element builder (always `textContent`), `Debounce`, helpers | | `Select.js` | The custom drop-down component | | `LaunchForm.js` | Launch-method fields + Players/Ping filters (shared by both pages) | | `Accounts.js`, `Configs.js`, `Launch.js`, `Settings.js`, `Themes.js` | One per panel | | `Status.js` | The two status lines | +| `Tooltip.js` | Themed tooltips for every `title` / `data-tooltip` (shown as plain text) | | `TourData.js` / `Tours.js` | Tutorial content / tutorial engine | ## Where to change X diff --git a/Production/RAMMIT-Stable/Src/CBlock/CSS/Style.css b/Production/RAMMIT-Stable/Src/CBlock/CSS/Style.css index 044053f..19187d6 100644 --- a/Production/RAMMIT-Stable/Src/CBlock/CSS/Style.css +++ b/Production/RAMMIT-Stable/Src/CBlock/CSS/Style.css @@ -20,6 +20,7 @@ --SuccessHover: #2bb886; --Danger: #f87171; /* - REMOVE, errors, cancel */ --DangerHover: #ef5a5a; + --OnExpired: #000000; /* text on an expired login's red row */ --Warning: #fbbf24; /* "launching" marks, warnings */ --Border: #18122a; --BorderLight: #18122a; @@ -175,9 +176,12 @@ body { color: var(--OnAccent); } -/* A saved login Roblox rejected (expired): red row until it's renewed. */ +/* A saved login Roblox rejected (expired): red row until it's renewed. Its text is --OnExpired (white, or a dark + colour where --Danger is light). Selected, it stays red and gets a ring in that colour: the accent can be as dark + as the red. Themes from before --OnExpired get white. */ .ListItem.Expired { background: var(--Danger); + color: var(--OnExpired, #ffffff); } .ListItem.Expired:hover { @@ -186,8 +190,9 @@ body { .ListItem.Expired.Selected { background: var(--Danger); + color: var(--OnExpired, #ffffff); font-weight: 700; - color: var(--Accent); + box-shadow: inset 0 0 0 2px var(--OnExpired, #ffffff); } .ListButtons { @@ -709,6 +714,16 @@ body { color: var(--OnAccent); } +/* On an expired login's red row (selected or not), the @username and the status mark use the row's text colour: + a red error mark on the red row would vanish. */ +.ListItem.Expired .AcctUser, +.ListItem.Expired .AcctStatus.Queued, +.ListItem.Expired .AcctStatus.Launching, +.ListItem.Expired .AcctStatus.Ok, +.ListItem.Expired .AcctStatus.Error { + color: var(--OnExpired, #ffffff); +} + .BtnSelect { flex: 1; padding: 10px; @@ -1270,7 +1285,7 @@ body.WizardBody { /* Tooltips (JS/Tooltip.js): follow the cursor, flip to its other side at the window's edges. Outside .Container, so not zoomed. Square unless the theme sets --TooltipRadius. Width is the text's own (max-content), so measuring it - does not depend on where it currently sits; long text wraps, and "\n" starts a new line. */ + does not depend on where it currently sits; long text wraps, and a line break in the text starts a new line. */ .Tooltip { position: fixed; left: 0; diff --git a/Production/RAMMIT-Stable/Src/CBlock/JS/Accounts.js b/Production/RAMMIT-Stable/Src/CBlock/JS/Accounts.js index 5e00227..44b02d7 100644 --- a/Production/RAMMIT-Stable/Src/CBlock/JS/Accounts.js +++ b/Production/RAMMIT-Stable/Src/CBlock/JS/Accounts.js @@ -85,11 +85,14 @@ export function ApplySelection() { AddBtn.classList.toggle('BtnAdd', !Renew); AddBtn.classList.toggle('BtnRenew', !!Renew); AddBtn.textContent = Renew ? 'RENEW' : '+ ADD'; - AddBtn.removeAttribute('title'); - AddBtn.dataset.tooltip = Renew ? `Sign in again as @${Renew} (its saved login expired)` : 'Sign in to a Roblox account and save it'; + AddBtn.title = Renew ? `Sign in again as @${Renew} (its saved login expired)` : 'Sign in to a Roblox account and save it'; ById('SelectionCount').textContent = Count ? ` (${Count} SELECTED)` : ''; ById('SelectAllBtn').textContent = (State.Accounts.length > 0 && Count >= State.Accounts.length) ? 'CLEAR' : 'SELECT ALL'; - if (!State.BatchRunning) ById('LaunchBtn').textContent = Renew ? 'RENEW AND LAUNCH' : Count > 1 ? `LAUNCH ${Count} SELECTED` : 'LAUNCH SELECTED'; + if (!State.BatchRunning) { + const LaunchBtn = ById('LaunchBtn'); + LaunchBtn.textContent = Renew ? 'RENEW AND LAUNCH' : Count > 1 ? `LAUNCH ${Count} SELECTED` : 'LAUNCH SELECTED'; + LaunchBtn.title = Renew ? `Sign in again as @${Renew}, then launch it` : 'Launch every ticked account, one after another'; + } } export function ApplyAccountStatus() { @@ -119,9 +122,14 @@ export async function AddAccount() { } // Sign in again for an expired account. True when that same Roblox user signed in (a different one is added instead). +// An account renamed on Roblox comes back under its new name; it stays selected under that name. export async function RenewAccount(Username) { const Result = await Api.RenewAccount(Username); if (Result && Result.Error) ShowLaunchError(Result.Error); + if (Result && Result.Renewed && Result.Username && Result.Username !== Username) { + State.Selected.delete(Username); + State.Selected.add(Result.Username); + } await RefreshAccounts(); return !!(Result && Result.Renewed); } diff --git a/Production/RAMMIT-Stable/Src/CBlock/JS/Bridge.js b/Production/RAMMIT-Stable/Src/CBlock/JS/Bridge.js index b974d8b..b0dd3e5 100644 --- a/Production/RAMMIT-Stable/Src/CBlock/JS/Bridge.js +++ b/Production/RAMMIT-Stable/Src/CBlock/JS/Bridge.js @@ -17,6 +17,30 @@ export const Api = new Proxy({}, { }, }); +// Fn(...Args) one call at a time. pywebview runs every call to Python on its own thread, so two calls in flight can +// finish in either order (two resizes would leave the window at the older height). While one runs, only the newest +// arguments wait and are sent when it has finished; older ones are dropped. Errors are ignored, like a resize's. +// A call that never answers stops holding the others up after GiveUpMs (App/WindowSize.py applies resizes under one +// lock, so a late one still lands before the next). +export function OneAtATime(Fn, GiveUpMs = 3000) { + let Running = false; + let Waiting = null; + const Run = (...Args) => { + if (Running) { Waiting = Args; return; } + Running = true; + const GiveUp = new Promise(Resolve => setTimeout(Resolve, GiveUpMs)); + Promise.race([Promise.resolve().then(() => Fn(...Args)), GiveUp]).catch(() => {}).finally(() => { + Running = false; + if (Waiting) { + const Next = Waiting; + Waiting = null; + Run(...Next); + } + }); + }; + return Run; +} + const Handlers = {}; window.RammitEvents = { AccountsChanged: Payload => Fire('AccountsChanged', Payload), diff --git a/Production/RAMMIT-Stable/Src/CBlock/JS/Launch.js b/Production/RAMMIT-Stable/Src/CBlock/JS/Launch.js index 0705310..dc6463c 100644 --- a/Production/RAMMIT-Stable/Src/CBlock/JS/Launch.js +++ b/Production/RAMMIT-Stable/Src/CBlock/JS/Launch.js @@ -1,7 +1,7 @@ // LAUNCHER CONTROLS panel: launch option + its boxes, the launch/cancel button, batch progress, // the RUNNING counter, and window height. -import { Api, ReportError } from './Bridge.js'; +import { Api, ReportError, OneAtATime } from './Bridge.js'; import { ById, Debounce } from './Dom.js'; import { InitSelect, SetSelectValue, GetSelectValue } from './Select.js'; import { CreateLaunchForm } from './LaunchForm.js'; @@ -17,6 +17,7 @@ let Form = null; let BatchPoll = null; const SaveParams = Debounce(() => Api.UpdateSetting('LaunchParams', Form.GetParams()).catch(ReportError), 300); +const ResizeWindow = OneAtATime(Height => Api.ResizeWindow(Height)); export async function LoadHeightMap() { const Map = await Api.GetHeightMap(); @@ -44,7 +45,7 @@ export function ResizeForCurrentOption() { const PlayerSel = ById('PlayerModeSelect'); if (PlayerSel && ['min_only', 'max_only', 'range'].includes(GetSelectValue(PlayerSel))) Height += HeightMap.PlayerFilterExtra || 0; Height += ThemeNoteExtra(); // exactly as much as a note under the Theme list adds (0 when there is none) - Api.ResizeWindow(Height).catch(() => {}); + ResizeWindow(Height); } function OnLaunchClick() { @@ -87,8 +88,10 @@ function SetBatchRunning(Running) { State.BatchRunning = Running; const Button = ById('LaunchBtn'); Button.classList.toggle('Cancel', Running); - if (Running) Button.textContent = 'CANCEL LAUNCH'; - else ApplySelection(); + if (Running) { + Button.textContent = 'CANCEL LAUNCH'; + Button.title = 'Stop the launch: accounts not started yet are skipped'; + } else ApplySelection(); } // Row marks come from two places: the batch's results (queued / launching / skipped / error) and, once an account's @@ -120,11 +123,13 @@ function RenderAccountStatus() { // The status line only says "Launched" once the game windows are open (as RAMMIT's earlier test builds did): while an account // is being launched, or its window isn't open yet, it says "Launching X / Y..."; in the launch delay after an account -// whose window is already open, "Launched X/Y". After the last launch it waits for the windows, then ShowLaunchDone -// (which clears itself); it gives up waiting after WindowWait. +// whose window is already open, "X / Y done, next launch soon...". After the last launch it waits for the windows, +// then ShowLaunchDone (which clears itself); it gives up waiting after WindowWait. The windows count as open only on +// a counter poll that started after the batch ended: an earlier one can still show a client that has since closed. const WindowWait = 30000; let LastProgress = null; let Waiting = null; // { Names, Ok, Total, Since } after a batch, until its windows are open +let LastPollAsked = 0; // when the newest counter poll whose answer is in LiveAccounts was sent const IsOpen = Name => LiveAccounts[Name] === 'running'; @@ -132,13 +137,14 @@ function BatchStatusText(Progress) { const Results = Progress.Results || {}; if (Object.values(Results).includes('launching')) return `Launching ${Math.min(Progress.Done + 1, Progress.Total)} / ${Progress.Total}...`; const Last = Object.keys(Results).filter(Name => Results[Name] === 'ok').pop(); - return Last && IsOpen(Last) ? `Launched ${Progress.Done}/${Progress.Total}` : `Launching ${Progress.Done} / ${Progress.Total}...`; + // Waiting out the launch delay: not "Launched ...", which only ever means the whole batch is done + return Last && IsOpen(Last) ? `${Progress.Done} / ${Progress.Total} done, next launch soon...` : `Launching ${Progress.Done} / ${Progress.Total}...`; } function RenderLaunchStatus() { if (State.BatchRunning && LastProgress) { SetLaunchStatus(BatchStatusText(LastProgress)); return; } if (!Waiting) return; - if (Waiting.Names.every(IsOpen) || Date.now() - Waiting.Since > WindowWait) { + if ((LastPollAsked >= Waiting.Since && Waiting.Names.every(IsOpen)) || Date.now() - Waiting.Since > WindowWait) { ShowLaunchDone(`Launched ${Waiting.Ok}/${Waiting.Total}`); Waiting = null; } else { @@ -172,6 +178,7 @@ function FinishBatch(Progress) { export async function UpdateCounter() { try { + const Asked = Date.now(); const Counter = await Api.GetCounter(); const Label = ById('CounterLabel'); // MultiReady is false when Roblox was already open before RAMMIT started (see App/MultiInstance.py). @@ -179,6 +186,7 @@ export async function UpdateCounter() { Label.title = Counter.MultiReady === false ? 'Roblox was already open when RAMMIT started, so only one client can run. Close every Roblox window and RAMMIT will take over on the next launch.' : ''; LiveAccounts = Counter.Accounts || {}; + LastPollAsked = Math.max(LastPollAsked, Asked); RenderAccountStatus(); RenderLaunchStatus(); } catch (_) { /* backend busy - next tick */ } diff --git a/Production/RAMMIT-Stable/Src/CBlock/JS/Tooltip.js b/Production/RAMMIT-Stable/Src/CBlock/JS/Tooltip.js index 5635396..e9e42f8 100644 --- a/Production/RAMMIT-Stable/Src/CBlock/JS/Tooltip.js +++ b/Production/RAMMIT-Stable/Src/CBlock/JS/Tooltip.js @@ -1,6 +1,8 @@ // Themed tooltips (the CBlock tooltip), instead of the browser's own. // Any element with data-tooltip="..." or a title="..." gets one: a title is moved into data-tooltip when hovered, -// so the native tooltip never shows and no existing title has to change. "\n" in the text starts a new line. +// so the native tooltip never shows and no existing title has to change. A line break in the text starts a new line. +// The text is shown as plain text (textContent), never as HTML. While a tooltip shows, a changed title or +// data-tooltip on its element (e.g. + ADD turning into RENEW) updates it straight away. // Look: .Tooltip in Style.css (colours from the theme; --TooltipRadius rounds it, 0 by default). const OffsetX = 12, OffsetY = 16; // from the cursor @@ -8,14 +10,23 @@ const FlipGap = 12; // from the cursor when flipped to its left / let Tip = null; let Target = null; let LastX = 0, LastY = 0; +const Watch = new MutationObserver(() => { if (Target) Refresh(); }); // Takes over a title (also one set again later, e.g. an account's status) and returns the text to show. +// Screen readers used the title as the element's name (an icon-only button) or its description (anything with text), +// so it moves to aria-label or aria-description, unless the page set that attribute to something else. function ReadText(Node) { if (Node.hasAttribute('title')) { - Node.dataset.tooltip = Node.getAttribute('title'); + const Old = Node.dataset.tooltip; + const Text = Node.getAttribute('title'); + Node.dataset.tooltip = Text; Node.removeAttribute('title'); + const Attr = Node.textContent.trim() ? 'aria-description' : 'aria-label'; + const Ours = !Node.hasAttribute(Attr) || Node.getAttribute(Attr) === Old; + if (Ours && Text) Node.setAttribute(Attr, Text); + else if (Ours) Node.removeAttribute(Attr); } - return (Node.dataset.tooltip || '').replace(/\\n/g, '\n'); + return Node.dataset.tooltip || ''; } // Right of / below the cursor; where that would leave the window, the other side of the cursor instead. @@ -31,14 +42,28 @@ function Place() { function Show(Node) { const Text = ReadText(Node); if (!Text) { Hide(); return; } + if (Target !== Node) { + Watch.disconnect(); + Watch.observe(Node, { attributes: true, attributeFilter: ['title', 'data-tooltip'] }); + } Target = Node; Tip.textContent = Text; Place(); // before it fades in, so it never flashes where it was last time Tip.classList.add('Visible'); } +// The element under the cursor changed its text, or the cursor moved: keep the tooltip right. +function Refresh() { + if (!Target.isConnected) { Hide(); return; } // re-drawn under the cursor: no mouseout ever comes + const Text = ReadText(Target); + if (!Text) { Hide(); return; } + if (Tip.textContent !== Text) Tip.textContent = Text; + Place(); +} + function Hide() { Target = null; + Watch.disconnect(); if (Tip) Tip.classList.remove('Visible'); } @@ -55,9 +80,7 @@ export function InitTooltips() { }); document.addEventListener('mousemove', Event => { LastX = Event.clientX; LastY = Event.clientY; - if (!Target) return; - if (!Target.isConnected) { Hide(); return; } // re-drawn under the cursor: no mouseout ever comes - if (Target.hasAttribute('title')) Show(Target); else Place(); + if (Target) Refresh(); }); document.addEventListener('mouseout', Event => { if (!Event.relatedTarget) Hide(); }); // left the window document.addEventListener('mousedown', Hide); diff --git a/Production/RAMMIT-Stable/Src/CBlock/JS/TourData.js b/Production/RAMMIT-Stable/Src/CBlock/JS/TourData.js index b4d118a..1da4146 100644 --- a/Production/RAMMIT-Stable/Src/CBlock/JS/TourData.js +++ b/Production/RAMMIT-Stable/Src/CBlock/JS/TourData.js @@ -40,7 +40,7 @@ export const Tours = [ Body: 'The button counts what you picked — LAUNCH 4 SELECTED.

They open one after another rather than all in the same instant. Changed your mind halfway? The button turns into CANCEL LAUNCH and stops the ones that have not started yet.' }, { Target: '#AccountList', Title: 'Watch how each one goes', Body: 'While a launch runs, every row shows where it is up to:', - Keys: [['…', 'waiting its turn'], ['•••', 'starting up now'], ['✓', 'launched'], ['✗', 'failed — hover it to read why']] }, + Keys: [['…', 'waiting its turn'], ['•••', 'starting up now'], ['✓', 'its game window is open (clears when it closes)'], ['✗', 'failed — hover it to read why']] }, { Target: '.StatusFooter', Title: 'Keeping score', Body: 'RUNNING shows how many instances are open against your limit.

Underneath it, the line reads Launching 3 / 5... as it works, then Launched 5/5 when it is done. If any failed, it tells you how many and what went wrong.' }, ], diff --git a/Production/RAMMIT-Stable/Src/CBlock/JS/Wizard.js b/Production/RAMMIT-Stable/Src/CBlock/JS/Wizard.js index 9bca02a..a069311 100644 --- a/Production/RAMMIT-Stable/Src/CBlock/JS/Wizard.js +++ b/Production/RAMMIT-Stable/Src/CBlock/JS/Wizard.js @@ -7,7 +7,7 @@ // drop-down closed + ExtraPadding, plus only the part of an open drop-down that would be cut off. // The CSS keeps the same box model as Test1's wizard, so its heights apply 1:1. -import { Api, WaitForApi, ReportError } from './Bridge.js'; +import { Api, WaitForApi, ReportError, OneAtATime } from './Bridge.js'; import { ById } from './Dom.js'; import { InitSelect, SetSelectValue, GetSelectValue } from './Select.js'; import { CreateLaunchForm, FilterMethods } from './LaunchForm.js'; @@ -15,6 +15,7 @@ import { InitTooltips } from './Tooltip.js'; let SizeMap = { Home: 287, ExtraPadding: 20 }; let InitDone = false; +const ResizeWizard = OneAtATime(Height => Api.ResizeWizard(Height)); function FitToContent() { setTimeout(() => { @@ -29,7 +30,7 @@ function FitToContent() { const Clipped = OpenSelect.querySelector('.CustomSelectOptions').getBoundingClientRect().bottom - window.innerHeight; if (Clipped > 0) Needed += Clipped + 5; } - Api.ResizeWizard(Needed).catch(() => {}); + ResizeWizard(Needed); }, 10); } @@ -43,7 +44,7 @@ const Form = CreateLaunchForm(ById('DynamicFields'), { InitSelect(ById('MethodSelect'), Method => { Form.Render(Method, {}); - if (InitDone) Api.ResizeWizard(SizeMap[Method] || SizeMap.Home).catch(() => {}); + if (InitDone) ResizeWizard(SizeMap[Method] || SizeMap.Home); }); // Opening/closing any drop-down, and clicks elsewhere, re-measure. Picking a method does not // (it snaps to the map above), so clicks inside the method list are skipped. diff --git a/Production/RAMMIT-Stable/Src/CBlock/Theme.json b/Production/RAMMIT-Stable/Src/CBlock/Theme.json index f31c288..6e32d78 100644 --- a/Production/RAMMIT-Stable/Src/CBlock/Theme.json +++ b/Production/RAMMIT-Stable/Src/CBlock/Theme.json @@ -2,5 +2,5 @@ "Name": "CBlock", "Author": "RAMMIT", "Description": "The CBlock look.", - "SupportedVersions": ["1.0", "1.1"] + "SupportedVersions": ["1.0", "1.1", "1.2"] } \ No newline at end of file diff --git a/Production/RAMMIT-Stable/Src/Dark/CSS/Style.css b/Production/RAMMIT-Stable/Src/Dark/CSS/Style.css index cb2bddd..d80519c 100644 --- a/Production/RAMMIT-Stable/Src/Dark/CSS/Style.css +++ b/Production/RAMMIT-Stable/Src/Dark/CSS/Style.css @@ -22,6 +22,7 @@ --SuccessHover: #218838; --Danger: #dc3545; /* - REMOVE, errors, cancel */ --DangerHover: #c82333; + --OnExpired: #ffffff; /* text on an expired login's red row */ --Warning: #ffc107; /* "launching" marks, warnings */ --Border: #252525; --BorderLight: #333333; @@ -176,9 +177,12 @@ body { color: var(--OnAccent); } -/* A saved login Roblox rejected (expired): red row until it's renewed. */ +/* A saved login Roblox rejected (expired): red row until it's renewed. Its text is --OnExpired (white, or a dark + colour where --Danger is light). Selected, it stays red and gets a ring in that colour: the accent can be as dark + as the red. Themes from before --OnExpired get white. */ .ListItem.Expired { background: var(--Danger); + color: var(--OnExpired, #ffffff); } .ListItem.Expired:hover { @@ -187,8 +191,9 @@ body { .ListItem.Expired.Selected { background: var(--Danger); + color: var(--OnExpired, #ffffff); font-weight: 700; - color: var(--Accent); + box-shadow: inset 0 0 0 2px var(--OnExpired, #ffffff); } .ListButtons { @@ -710,6 +715,16 @@ body { color: var(--OnAccent); } +/* On an expired login's red row (selected or not), the @username and the status mark use the row's text colour: + a red error mark on the red row would vanish. */ +.ListItem.Expired .AcctUser, +.ListItem.Expired .AcctStatus.Queued, +.ListItem.Expired .AcctStatus.Launching, +.ListItem.Expired .AcctStatus.Ok, +.ListItem.Expired .AcctStatus.Error { + color: var(--OnExpired, #ffffff); +} + .BtnSelect { flex: 1; padding: 10px; @@ -1271,7 +1286,7 @@ body.WizardBody { /* Tooltips (JS/Tooltip.js): follow the cursor, flip to its other side at the window's edges. Outside .Container, so not zoomed. Square unless the theme sets --TooltipRadius. Width is the text's own (max-content), so measuring it - does not depend on where it currently sits; long text wraps, and "\n" starts a new line. */ + does not depend on where it currently sits; long text wraps, and a line break in the text starts a new line. */ .Tooltip { position: fixed; left: 0; diff --git a/Production/RAMMIT-Stable/Src/Dark/JS/Accounts.js b/Production/RAMMIT-Stable/Src/Dark/JS/Accounts.js index 5e00227..44b02d7 100644 --- a/Production/RAMMIT-Stable/Src/Dark/JS/Accounts.js +++ b/Production/RAMMIT-Stable/Src/Dark/JS/Accounts.js @@ -85,11 +85,14 @@ export function ApplySelection() { AddBtn.classList.toggle('BtnAdd', !Renew); AddBtn.classList.toggle('BtnRenew', !!Renew); AddBtn.textContent = Renew ? 'RENEW' : '+ ADD'; - AddBtn.removeAttribute('title'); - AddBtn.dataset.tooltip = Renew ? `Sign in again as @${Renew} (its saved login expired)` : 'Sign in to a Roblox account and save it'; + AddBtn.title = Renew ? `Sign in again as @${Renew} (its saved login expired)` : 'Sign in to a Roblox account and save it'; ById('SelectionCount').textContent = Count ? ` (${Count} SELECTED)` : ''; ById('SelectAllBtn').textContent = (State.Accounts.length > 0 && Count >= State.Accounts.length) ? 'CLEAR' : 'SELECT ALL'; - if (!State.BatchRunning) ById('LaunchBtn').textContent = Renew ? 'RENEW AND LAUNCH' : Count > 1 ? `LAUNCH ${Count} SELECTED` : 'LAUNCH SELECTED'; + if (!State.BatchRunning) { + const LaunchBtn = ById('LaunchBtn'); + LaunchBtn.textContent = Renew ? 'RENEW AND LAUNCH' : Count > 1 ? `LAUNCH ${Count} SELECTED` : 'LAUNCH SELECTED'; + LaunchBtn.title = Renew ? `Sign in again as @${Renew}, then launch it` : 'Launch every ticked account, one after another'; + } } export function ApplyAccountStatus() { @@ -119,9 +122,14 @@ export async function AddAccount() { } // Sign in again for an expired account. True when that same Roblox user signed in (a different one is added instead). +// An account renamed on Roblox comes back under its new name; it stays selected under that name. export async function RenewAccount(Username) { const Result = await Api.RenewAccount(Username); if (Result && Result.Error) ShowLaunchError(Result.Error); + if (Result && Result.Renewed && Result.Username && Result.Username !== Username) { + State.Selected.delete(Username); + State.Selected.add(Result.Username); + } await RefreshAccounts(); return !!(Result && Result.Renewed); } diff --git a/Production/RAMMIT-Stable/Src/Dark/JS/Bridge.js b/Production/RAMMIT-Stable/Src/Dark/JS/Bridge.js index b974d8b..b0dd3e5 100644 --- a/Production/RAMMIT-Stable/Src/Dark/JS/Bridge.js +++ b/Production/RAMMIT-Stable/Src/Dark/JS/Bridge.js @@ -17,6 +17,30 @@ export const Api = new Proxy({}, { }, }); +// Fn(...Args) one call at a time. pywebview runs every call to Python on its own thread, so two calls in flight can +// finish in either order (two resizes would leave the window at the older height). While one runs, only the newest +// arguments wait and are sent when it has finished; older ones are dropped. Errors are ignored, like a resize's. +// A call that never answers stops holding the others up after GiveUpMs (App/WindowSize.py applies resizes under one +// lock, so a late one still lands before the next). +export function OneAtATime(Fn, GiveUpMs = 3000) { + let Running = false; + let Waiting = null; + const Run = (...Args) => { + if (Running) { Waiting = Args; return; } + Running = true; + const GiveUp = new Promise(Resolve => setTimeout(Resolve, GiveUpMs)); + Promise.race([Promise.resolve().then(() => Fn(...Args)), GiveUp]).catch(() => {}).finally(() => { + Running = false; + if (Waiting) { + const Next = Waiting; + Waiting = null; + Run(...Next); + } + }); + }; + return Run; +} + const Handlers = {}; window.RammitEvents = { AccountsChanged: Payload => Fire('AccountsChanged', Payload), diff --git a/Production/RAMMIT-Stable/Src/Dark/JS/Launch.js b/Production/RAMMIT-Stable/Src/Dark/JS/Launch.js index 0705310..dc6463c 100644 --- a/Production/RAMMIT-Stable/Src/Dark/JS/Launch.js +++ b/Production/RAMMIT-Stable/Src/Dark/JS/Launch.js @@ -1,7 +1,7 @@ // LAUNCHER CONTROLS panel: launch option + its boxes, the launch/cancel button, batch progress, // the RUNNING counter, and window height. -import { Api, ReportError } from './Bridge.js'; +import { Api, ReportError, OneAtATime } from './Bridge.js'; import { ById, Debounce } from './Dom.js'; import { InitSelect, SetSelectValue, GetSelectValue } from './Select.js'; import { CreateLaunchForm } from './LaunchForm.js'; @@ -17,6 +17,7 @@ let Form = null; let BatchPoll = null; const SaveParams = Debounce(() => Api.UpdateSetting('LaunchParams', Form.GetParams()).catch(ReportError), 300); +const ResizeWindow = OneAtATime(Height => Api.ResizeWindow(Height)); export async function LoadHeightMap() { const Map = await Api.GetHeightMap(); @@ -44,7 +45,7 @@ export function ResizeForCurrentOption() { const PlayerSel = ById('PlayerModeSelect'); if (PlayerSel && ['min_only', 'max_only', 'range'].includes(GetSelectValue(PlayerSel))) Height += HeightMap.PlayerFilterExtra || 0; Height += ThemeNoteExtra(); // exactly as much as a note under the Theme list adds (0 when there is none) - Api.ResizeWindow(Height).catch(() => {}); + ResizeWindow(Height); } function OnLaunchClick() { @@ -87,8 +88,10 @@ function SetBatchRunning(Running) { State.BatchRunning = Running; const Button = ById('LaunchBtn'); Button.classList.toggle('Cancel', Running); - if (Running) Button.textContent = 'CANCEL LAUNCH'; - else ApplySelection(); + if (Running) { + Button.textContent = 'CANCEL LAUNCH'; + Button.title = 'Stop the launch: accounts not started yet are skipped'; + } else ApplySelection(); } // Row marks come from two places: the batch's results (queued / launching / skipped / error) and, once an account's @@ -120,11 +123,13 @@ function RenderAccountStatus() { // The status line only says "Launched" once the game windows are open (as RAMMIT's earlier test builds did): while an account // is being launched, or its window isn't open yet, it says "Launching X / Y..."; in the launch delay after an account -// whose window is already open, "Launched X/Y". After the last launch it waits for the windows, then ShowLaunchDone -// (which clears itself); it gives up waiting after WindowWait. +// whose window is already open, "X / Y done, next launch soon...". After the last launch it waits for the windows, +// then ShowLaunchDone (which clears itself); it gives up waiting after WindowWait. The windows count as open only on +// a counter poll that started after the batch ended: an earlier one can still show a client that has since closed. const WindowWait = 30000; let LastProgress = null; let Waiting = null; // { Names, Ok, Total, Since } after a batch, until its windows are open +let LastPollAsked = 0; // when the newest counter poll whose answer is in LiveAccounts was sent const IsOpen = Name => LiveAccounts[Name] === 'running'; @@ -132,13 +137,14 @@ function BatchStatusText(Progress) { const Results = Progress.Results || {}; if (Object.values(Results).includes('launching')) return `Launching ${Math.min(Progress.Done + 1, Progress.Total)} / ${Progress.Total}...`; const Last = Object.keys(Results).filter(Name => Results[Name] === 'ok').pop(); - return Last && IsOpen(Last) ? `Launched ${Progress.Done}/${Progress.Total}` : `Launching ${Progress.Done} / ${Progress.Total}...`; + // Waiting out the launch delay: not "Launched ...", which only ever means the whole batch is done + return Last && IsOpen(Last) ? `${Progress.Done} / ${Progress.Total} done, next launch soon...` : `Launching ${Progress.Done} / ${Progress.Total}...`; } function RenderLaunchStatus() { if (State.BatchRunning && LastProgress) { SetLaunchStatus(BatchStatusText(LastProgress)); return; } if (!Waiting) return; - if (Waiting.Names.every(IsOpen) || Date.now() - Waiting.Since > WindowWait) { + if ((LastPollAsked >= Waiting.Since && Waiting.Names.every(IsOpen)) || Date.now() - Waiting.Since > WindowWait) { ShowLaunchDone(`Launched ${Waiting.Ok}/${Waiting.Total}`); Waiting = null; } else { @@ -172,6 +178,7 @@ function FinishBatch(Progress) { export async function UpdateCounter() { try { + const Asked = Date.now(); const Counter = await Api.GetCounter(); const Label = ById('CounterLabel'); // MultiReady is false when Roblox was already open before RAMMIT started (see App/MultiInstance.py). @@ -179,6 +186,7 @@ export async function UpdateCounter() { Label.title = Counter.MultiReady === false ? 'Roblox was already open when RAMMIT started, so only one client can run. Close every Roblox window and RAMMIT will take over on the next launch.' : ''; LiveAccounts = Counter.Accounts || {}; + LastPollAsked = Math.max(LastPollAsked, Asked); RenderAccountStatus(); RenderLaunchStatus(); } catch (_) { /* backend busy - next tick */ } diff --git a/Production/RAMMIT-Stable/Src/Dark/JS/Tooltip.js b/Production/RAMMIT-Stable/Src/Dark/JS/Tooltip.js index 5635396..e9e42f8 100644 --- a/Production/RAMMIT-Stable/Src/Dark/JS/Tooltip.js +++ b/Production/RAMMIT-Stable/Src/Dark/JS/Tooltip.js @@ -1,6 +1,8 @@ // Themed tooltips (the CBlock tooltip), instead of the browser's own. // Any element with data-tooltip="..." or a title="..." gets one: a title is moved into data-tooltip when hovered, -// so the native tooltip never shows and no existing title has to change. "\n" in the text starts a new line. +// so the native tooltip never shows and no existing title has to change. A line break in the text starts a new line. +// The text is shown as plain text (textContent), never as HTML. While a tooltip shows, a changed title or +// data-tooltip on its element (e.g. + ADD turning into RENEW) updates it straight away. // Look: .Tooltip in Style.css (colours from the theme; --TooltipRadius rounds it, 0 by default). const OffsetX = 12, OffsetY = 16; // from the cursor @@ -8,14 +10,23 @@ const FlipGap = 12; // from the cursor when flipped to its left / let Tip = null; let Target = null; let LastX = 0, LastY = 0; +const Watch = new MutationObserver(() => { if (Target) Refresh(); }); // Takes over a title (also one set again later, e.g. an account's status) and returns the text to show. +// Screen readers used the title as the element's name (an icon-only button) or its description (anything with text), +// so it moves to aria-label or aria-description, unless the page set that attribute to something else. function ReadText(Node) { if (Node.hasAttribute('title')) { - Node.dataset.tooltip = Node.getAttribute('title'); + const Old = Node.dataset.tooltip; + const Text = Node.getAttribute('title'); + Node.dataset.tooltip = Text; Node.removeAttribute('title'); + const Attr = Node.textContent.trim() ? 'aria-description' : 'aria-label'; + const Ours = !Node.hasAttribute(Attr) || Node.getAttribute(Attr) === Old; + if (Ours && Text) Node.setAttribute(Attr, Text); + else if (Ours) Node.removeAttribute(Attr); } - return (Node.dataset.tooltip || '').replace(/\\n/g, '\n'); + return Node.dataset.tooltip || ''; } // Right of / below the cursor; where that would leave the window, the other side of the cursor instead. @@ -31,14 +42,28 @@ function Place() { function Show(Node) { const Text = ReadText(Node); if (!Text) { Hide(); return; } + if (Target !== Node) { + Watch.disconnect(); + Watch.observe(Node, { attributes: true, attributeFilter: ['title', 'data-tooltip'] }); + } Target = Node; Tip.textContent = Text; Place(); // before it fades in, so it never flashes where it was last time Tip.classList.add('Visible'); } +// The element under the cursor changed its text, or the cursor moved: keep the tooltip right. +function Refresh() { + if (!Target.isConnected) { Hide(); return; } // re-drawn under the cursor: no mouseout ever comes + const Text = ReadText(Target); + if (!Text) { Hide(); return; } + if (Tip.textContent !== Text) Tip.textContent = Text; + Place(); +} + function Hide() { Target = null; + Watch.disconnect(); if (Tip) Tip.classList.remove('Visible'); } @@ -55,9 +80,7 @@ export function InitTooltips() { }); document.addEventListener('mousemove', Event => { LastX = Event.clientX; LastY = Event.clientY; - if (!Target) return; - if (!Target.isConnected) { Hide(); return; } // re-drawn under the cursor: no mouseout ever comes - if (Target.hasAttribute('title')) Show(Target); else Place(); + if (Target) Refresh(); }); document.addEventListener('mouseout', Event => { if (!Event.relatedTarget) Hide(); }); // left the window document.addEventListener('mousedown', Hide); diff --git a/Production/RAMMIT-Stable/Src/Dark/JS/TourData.js b/Production/RAMMIT-Stable/Src/Dark/JS/TourData.js index b4d118a..1da4146 100644 --- a/Production/RAMMIT-Stable/Src/Dark/JS/TourData.js +++ b/Production/RAMMIT-Stable/Src/Dark/JS/TourData.js @@ -40,7 +40,7 @@ export const Tours = [ Body: 'The button counts what you picked — LAUNCH 4 SELECTED.

They open one after another rather than all in the same instant. Changed your mind halfway? The button turns into CANCEL LAUNCH and stops the ones that have not started yet.' }, { Target: '#AccountList', Title: 'Watch how each one goes', Body: 'While a launch runs, every row shows where it is up to:', - Keys: [['…', 'waiting its turn'], ['•••', 'starting up now'], ['✓', 'launched'], ['✗', 'failed — hover it to read why']] }, + Keys: [['…', 'waiting its turn'], ['•••', 'starting up now'], ['✓', 'its game window is open (clears when it closes)'], ['✗', 'failed — hover it to read why']] }, { Target: '.StatusFooter', Title: 'Keeping score', Body: 'RUNNING shows how many instances are open against your limit.

Underneath it, the line reads Launching 3 / 5... as it works, then Launched 5/5 when it is done. If any failed, it tells you how many and what went wrong.' }, ], diff --git a/Production/RAMMIT-Stable/Src/Dark/JS/Wizard.js b/Production/RAMMIT-Stable/Src/Dark/JS/Wizard.js index 9bca02a..a069311 100644 --- a/Production/RAMMIT-Stable/Src/Dark/JS/Wizard.js +++ b/Production/RAMMIT-Stable/Src/Dark/JS/Wizard.js @@ -7,7 +7,7 @@ // drop-down closed + ExtraPadding, plus only the part of an open drop-down that would be cut off. // The CSS keeps the same box model as Test1's wizard, so its heights apply 1:1. -import { Api, WaitForApi, ReportError } from './Bridge.js'; +import { Api, WaitForApi, ReportError, OneAtATime } from './Bridge.js'; import { ById } from './Dom.js'; import { InitSelect, SetSelectValue, GetSelectValue } from './Select.js'; import { CreateLaunchForm, FilterMethods } from './LaunchForm.js'; @@ -15,6 +15,7 @@ import { InitTooltips } from './Tooltip.js'; let SizeMap = { Home: 287, ExtraPadding: 20 }; let InitDone = false; +const ResizeWizard = OneAtATime(Height => Api.ResizeWizard(Height)); function FitToContent() { setTimeout(() => { @@ -29,7 +30,7 @@ function FitToContent() { const Clipped = OpenSelect.querySelector('.CustomSelectOptions').getBoundingClientRect().bottom - window.innerHeight; if (Clipped > 0) Needed += Clipped + 5; } - Api.ResizeWizard(Needed).catch(() => {}); + ResizeWizard(Needed); }, 10); } @@ -43,7 +44,7 @@ const Form = CreateLaunchForm(ById('DynamicFields'), { InitSelect(ById('MethodSelect'), Method => { Form.Render(Method, {}); - if (InitDone) Api.ResizeWizard(SizeMap[Method] || SizeMap.Home).catch(() => {}); + if (InitDone) ResizeWizard(SizeMap[Method] || SizeMap.Home); }); // Opening/closing any drop-down, and clicks elsewhere, re-measure. Picking a method does not // (it snaps to the map above), so clicks inside the method list are skipped. diff --git a/Production/RAMMIT-Stable/Src/Dark/Theme.json b/Production/RAMMIT-Stable/Src/Dark/Theme.json index fbb9f43..d431714 100644 --- a/Production/RAMMIT-Stable/Src/Dark/Theme.json +++ b/Production/RAMMIT-Stable/Src/Dark/Theme.json @@ -2,5 +2,5 @@ "Name": "Dark", "Author": "RAMMIT", "Description": "The default dark look.", - "SupportedVersions": ["1.0", "1.1"] + "SupportedVersions": ["1.0", "1.1", "1.2"] } \ No newline at end of file diff --git a/Production/RAMMIT-Stable/Src/Light/CSS/Style.css b/Production/RAMMIT-Stable/Src/Light/CSS/Style.css index 167758f..d436d76 100644 --- a/Production/RAMMIT-Stable/Src/Light/CSS/Style.css +++ b/Production/RAMMIT-Stable/Src/Light/CSS/Style.css @@ -20,6 +20,7 @@ --SuccessHover: #029a49; --Danger: #e2231a; /* - REMOVE, errors, cancel */ --DangerHover: #c41d15; + --OnExpired: #ffffff; /* text on an expired login's red row */ --Warning: #f5a623; /* "launching" marks, warnings */ --Border: #d5d5d5; --BorderLight: #c2c2c2; @@ -174,9 +175,12 @@ body { color: var(--OnAccent); } -/* A saved login Roblox rejected (expired): red row until it's renewed. */ +/* A saved login Roblox rejected (expired): red row until it's renewed. Its text is --OnExpired (white, or a dark + colour where --Danger is light). Selected, it stays red and gets a ring in that colour: the accent can be as dark + as the red. Themes from before --OnExpired get white. */ .ListItem.Expired { background: var(--Danger); + color: var(--OnExpired, #ffffff); } .ListItem.Expired:hover { @@ -185,8 +189,9 @@ body { .ListItem.Expired.Selected { background: var(--Danger); + color: var(--OnExpired, #ffffff); font-weight: 700; - color: var(--Accent); + box-shadow: inset 0 0 0 2px var(--OnExpired, #ffffff); } .ListButtons { @@ -708,6 +713,16 @@ body { color: var(--OnAccent); } +/* On an expired login's red row (selected or not), the @username and the status mark use the row's text colour: + a red error mark on the red row would vanish. */ +.ListItem.Expired .AcctUser, +.ListItem.Expired .AcctStatus.Queued, +.ListItem.Expired .AcctStatus.Launching, +.ListItem.Expired .AcctStatus.Ok, +.ListItem.Expired .AcctStatus.Error { + color: var(--OnExpired, #ffffff); +} + .BtnSelect { flex: 1; padding: 10px; @@ -1269,7 +1284,7 @@ body.WizardBody { /* Tooltips (JS/Tooltip.js): follow the cursor, flip to its other side at the window's edges. Outside .Container, so not zoomed. Square unless the theme sets --TooltipRadius. Width is the text's own (max-content), so measuring it - does not depend on where it currently sits; long text wraps, and "\n" starts a new line. */ + does not depend on where it currently sits; long text wraps, and a line break in the text starts a new line. */ .Tooltip { position: fixed; left: 0; diff --git a/Production/RAMMIT-Stable/Src/Light/JS/Accounts.js b/Production/RAMMIT-Stable/Src/Light/JS/Accounts.js index 5e00227..44b02d7 100644 --- a/Production/RAMMIT-Stable/Src/Light/JS/Accounts.js +++ b/Production/RAMMIT-Stable/Src/Light/JS/Accounts.js @@ -85,11 +85,14 @@ export function ApplySelection() { AddBtn.classList.toggle('BtnAdd', !Renew); AddBtn.classList.toggle('BtnRenew', !!Renew); AddBtn.textContent = Renew ? 'RENEW' : '+ ADD'; - AddBtn.removeAttribute('title'); - AddBtn.dataset.tooltip = Renew ? `Sign in again as @${Renew} (its saved login expired)` : 'Sign in to a Roblox account and save it'; + AddBtn.title = Renew ? `Sign in again as @${Renew} (its saved login expired)` : 'Sign in to a Roblox account and save it'; ById('SelectionCount').textContent = Count ? ` (${Count} SELECTED)` : ''; ById('SelectAllBtn').textContent = (State.Accounts.length > 0 && Count >= State.Accounts.length) ? 'CLEAR' : 'SELECT ALL'; - if (!State.BatchRunning) ById('LaunchBtn').textContent = Renew ? 'RENEW AND LAUNCH' : Count > 1 ? `LAUNCH ${Count} SELECTED` : 'LAUNCH SELECTED'; + if (!State.BatchRunning) { + const LaunchBtn = ById('LaunchBtn'); + LaunchBtn.textContent = Renew ? 'RENEW AND LAUNCH' : Count > 1 ? `LAUNCH ${Count} SELECTED` : 'LAUNCH SELECTED'; + LaunchBtn.title = Renew ? `Sign in again as @${Renew}, then launch it` : 'Launch every ticked account, one after another'; + } } export function ApplyAccountStatus() { @@ -119,9 +122,14 @@ export async function AddAccount() { } // Sign in again for an expired account. True when that same Roblox user signed in (a different one is added instead). +// An account renamed on Roblox comes back under its new name; it stays selected under that name. export async function RenewAccount(Username) { const Result = await Api.RenewAccount(Username); if (Result && Result.Error) ShowLaunchError(Result.Error); + if (Result && Result.Renewed && Result.Username && Result.Username !== Username) { + State.Selected.delete(Username); + State.Selected.add(Result.Username); + } await RefreshAccounts(); return !!(Result && Result.Renewed); } diff --git a/Production/RAMMIT-Stable/Src/Light/JS/Bridge.js b/Production/RAMMIT-Stable/Src/Light/JS/Bridge.js index b974d8b..b0dd3e5 100644 --- a/Production/RAMMIT-Stable/Src/Light/JS/Bridge.js +++ b/Production/RAMMIT-Stable/Src/Light/JS/Bridge.js @@ -17,6 +17,30 @@ export const Api = new Proxy({}, { }, }); +// Fn(...Args) one call at a time. pywebview runs every call to Python on its own thread, so two calls in flight can +// finish in either order (two resizes would leave the window at the older height). While one runs, only the newest +// arguments wait and are sent when it has finished; older ones are dropped. Errors are ignored, like a resize's. +// A call that never answers stops holding the others up after GiveUpMs (App/WindowSize.py applies resizes under one +// lock, so a late one still lands before the next). +export function OneAtATime(Fn, GiveUpMs = 3000) { + let Running = false; + let Waiting = null; + const Run = (...Args) => { + if (Running) { Waiting = Args; return; } + Running = true; + const GiveUp = new Promise(Resolve => setTimeout(Resolve, GiveUpMs)); + Promise.race([Promise.resolve().then(() => Fn(...Args)), GiveUp]).catch(() => {}).finally(() => { + Running = false; + if (Waiting) { + const Next = Waiting; + Waiting = null; + Run(...Next); + } + }); + }; + return Run; +} + const Handlers = {}; window.RammitEvents = { AccountsChanged: Payload => Fire('AccountsChanged', Payload), diff --git a/Production/RAMMIT-Stable/Src/Light/JS/Launch.js b/Production/RAMMIT-Stable/Src/Light/JS/Launch.js index 0705310..dc6463c 100644 --- a/Production/RAMMIT-Stable/Src/Light/JS/Launch.js +++ b/Production/RAMMIT-Stable/Src/Light/JS/Launch.js @@ -1,7 +1,7 @@ // LAUNCHER CONTROLS panel: launch option + its boxes, the launch/cancel button, batch progress, // the RUNNING counter, and window height. -import { Api, ReportError } from './Bridge.js'; +import { Api, ReportError, OneAtATime } from './Bridge.js'; import { ById, Debounce } from './Dom.js'; import { InitSelect, SetSelectValue, GetSelectValue } from './Select.js'; import { CreateLaunchForm } from './LaunchForm.js'; @@ -17,6 +17,7 @@ let Form = null; let BatchPoll = null; const SaveParams = Debounce(() => Api.UpdateSetting('LaunchParams', Form.GetParams()).catch(ReportError), 300); +const ResizeWindow = OneAtATime(Height => Api.ResizeWindow(Height)); export async function LoadHeightMap() { const Map = await Api.GetHeightMap(); @@ -44,7 +45,7 @@ export function ResizeForCurrentOption() { const PlayerSel = ById('PlayerModeSelect'); if (PlayerSel && ['min_only', 'max_only', 'range'].includes(GetSelectValue(PlayerSel))) Height += HeightMap.PlayerFilterExtra || 0; Height += ThemeNoteExtra(); // exactly as much as a note under the Theme list adds (0 when there is none) - Api.ResizeWindow(Height).catch(() => {}); + ResizeWindow(Height); } function OnLaunchClick() { @@ -87,8 +88,10 @@ function SetBatchRunning(Running) { State.BatchRunning = Running; const Button = ById('LaunchBtn'); Button.classList.toggle('Cancel', Running); - if (Running) Button.textContent = 'CANCEL LAUNCH'; - else ApplySelection(); + if (Running) { + Button.textContent = 'CANCEL LAUNCH'; + Button.title = 'Stop the launch: accounts not started yet are skipped'; + } else ApplySelection(); } // Row marks come from two places: the batch's results (queued / launching / skipped / error) and, once an account's @@ -120,11 +123,13 @@ function RenderAccountStatus() { // The status line only says "Launched" once the game windows are open (as RAMMIT's earlier test builds did): while an account // is being launched, or its window isn't open yet, it says "Launching X / Y..."; in the launch delay after an account -// whose window is already open, "Launched X/Y". After the last launch it waits for the windows, then ShowLaunchDone -// (which clears itself); it gives up waiting after WindowWait. +// whose window is already open, "X / Y done, next launch soon...". After the last launch it waits for the windows, +// then ShowLaunchDone (which clears itself); it gives up waiting after WindowWait. The windows count as open only on +// a counter poll that started after the batch ended: an earlier one can still show a client that has since closed. const WindowWait = 30000; let LastProgress = null; let Waiting = null; // { Names, Ok, Total, Since } after a batch, until its windows are open +let LastPollAsked = 0; // when the newest counter poll whose answer is in LiveAccounts was sent const IsOpen = Name => LiveAccounts[Name] === 'running'; @@ -132,13 +137,14 @@ function BatchStatusText(Progress) { const Results = Progress.Results || {}; if (Object.values(Results).includes('launching')) return `Launching ${Math.min(Progress.Done + 1, Progress.Total)} / ${Progress.Total}...`; const Last = Object.keys(Results).filter(Name => Results[Name] === 'ok').pop(); - return Last && IsOpen(Last) ? `Launched ${Progress.Done}/${Progress.Total}` : `Launching ${Progress.Done} / ${Progress.Total}...`; + // Waiting out the launch delay: not "Launched ...", which only ever means the whole batch is done + return Last && IsOpen(Last) ? `${Progress.Done} / ${Progress.Total} done, next launch soon...` : `Launching ${Progress.Done} / ${Progress.Total}...`; } function RenderLaunchStatus() { if (State.BatchRunning && LastProgress) { SetLaunchStatus(BatchStatusText(LastProgress)); return; } if (!Waiting) return; - if (Waiting.Names.every(IsOpen) || Date.now() - Waiting.Since > WindowWait) { + if ((LastPollAsked >= Waiting.Since && Waiting.Names.every(IsOpen)) || Date.now() - Waiting.Since > WindowWait) { ShowLaunchDone(`Launched ${Waiting.Ok}/${Waiting.Total}`); Waiting = null; } else { @@ -172,6 +178,7 @@ function FinishBatch(Progress) { export async function UpdateCounter() { try { + const Asked = Date.now(); const Counter = await Api.GetCounter(); const Label = ById('CounterLabel'); // MultiReady is false when Roblox was already open before RAMMIT started (see App/MultiInstance.py). @@ -179,6 +186,7 @@ export async function UpdateCounter() { Label.title = Counter.MultiReady === false ? 'Roblox was already open when RAMMIT started, so only one client can run. Close every Roblox window and RAMMIT will take over on the next launch.' : ''; LiveAccounts = Counter.Accounts || {}; + LastPollAsked = Math.max(LastPollAsked, Asked); RenderAccountStatus(); RenderLaunchStatus(); } catch (_) { /* backend busy - next tick */ } diff --git a/Production/RAMMIT-Stable/Src/Light/JS/Tooltip.js b/Production/RAMMIT-Stable/Src/Light/JS/Tooltip.js index 5635396..e9e42f8 100644 --- a/Production/RAMMIT-Stable/Src/Light/JS/Tooltip.js +++ b/Production/RAMMIT-Stable/Src/Light/JS/Tooltip.js @@ -1,6 +1,8 @@ // Themed tooltips (the CBlock tooltip), instead of the browser's own. // Any element with data-tooltip="..." or a title="..." gets one: a title is moved into data-tooltip when hovered, -// so the native tooltip never shows and no existing title has to change. "\n" in the text starts a new line. +// so the native tooltip never shows and no existing title has to change. A line break in the text starts a new line. +// The text is shown as plain text (textContent), never as HTML. While a tooltip shows, a changed title or +// data-tooltip on its element (e.g. + ADD turning into RENEW) updates it straight away. // Look: .Tooltip in Style.css (colours from the theme; --TooltipRadius rounds it, 0 by default). const OffsetX = 12, OffsetY = 16; // from the cursor @@ -8,14 +10,23 @@ const FlipGap = 12; // from the cursor when flipped to its left / let Tip = null; let Target = null; let LastX = 0, LastY = 0; +const Watch = new MutationObserver(() => { if (Target) Refresh(); }); // Takes over a title (also one set again later, e.g. an account's status) and returns the text to show. +// Screen readers used the title as the element's name (an icon-only button) or its description (anything with text), +// so it moves to aria-label or aria-description, unless the page set that attribute to something else. function ReadText(Node) { if (Node.hasAttribute('title')) { - Node.dataset.tooltip = Node.getAttribute('title'); + const Old = Node.dataset.tooltip; + const Text = Node.getAttribute('title'); + Node.dataset.tooltip = Text; Node.removeAttribute('title'); + const Attr = Node.textContent.trim() ? 'aria-description' : 'aria-label'; + const Ours = !Node.hasAttribute(Attr) || Node.getAttribute(Attr) === Old; + if (Ours && Text) Node.setAttribute(Attr, Text); + else if (Ours) Node.removeAttribute(Attr); } - return (Node.dataset.tooltip || '').replace(/\\n/g, '\n'); + return Node.dataset.tooltip || ''; } // Right of / below the cursor; where that would leave the window, the other side of the cursor instead. @@ -31,14 +42,28 @@ function Place() { function Show(Node) { const Text = ReadText(Node); if (!Text) { Hide(); return; } + if (Target !== Node) { + Watch.disconnect(); + Watch.observe(Node, { attributes: true, attributeFilter: ['title', 'data-tooltip'] }); + } Target = Node; Tip.textContent = Text; Place(); // before it fades in, so it never flashes where it was last time Tip.classList.add('Visible'); } +// The element under the cursor changed its text, or the cursor moved: keep the tooltip right. +function Refresh() { + if (!Target.isConnected) { Hide(); return; } // re-drawn under the cursor: no mouseout ever comes + const Text = ReadText(Target); + if (!Text) { Hide(); return; } + if (Tip.textContent !== Text) Tip.textContent = Text; + Place(); +} + function Hide() { Target = null; + Watch.disconnect(); if (Tip) Tip.classList.remove('Visible'); } @@ -55,9 +80,7 @@ export function InitTooltips() { }); document.addEventListener('mousemove', Event => { LastX = Event.clientX; LastY = Event.clientY; - if (!Target) return; - if (!Target.isConnected) { Hide(); return; } // re-drawn under the cursor: no mouseout ever comes - if (Target.hasAttribute('title')) Show(Target); else Place(); + if (Target) Refresh(); }); document.addEventListener('mouseout', Event => { if (!Event.relatedTarget) Hide(); }); // left the window document.addEventListener('mousedown', Hide); diff --git a/Production/RAMMIT-Stable/Src/Light/JS/TourData.js b/Production/RAMMIT-Stable/Src/Light/JS/TourData.js index b4d118a..1da4146 100644 --- a/Production/RAMMIT-Stable/Src/Light/JS/TourData.js +++ b/Production/RAMMIT-Stable/Src/Light/JS/TourData.js @@ -40,7 +40,7 @@ export const Tours = [ Body: 'The button counts what you picked — LAUNCH 4 SELECTED.

They open one after another rather than all in the same instant. Changed your mind halfway? The button turns into CANCEL LAUNCH and stops the ones that have not started yet.' }, { Target: '#AccountList', Title: 'Watch how each one goes', Body: 'While a launch runs, every row shows where it is up to:', - Keys: [['…', 'waiting its turn'], ['•••', 'starting up now'], ['✓', 'launched'], ['✗', 'failed — hover it to read why']] }, + Keys: [['…', 'waiting its turn'], ['•••', 'starting up now'], ['✓', 'its game window is open (clears when it closes)'], ['✗', 'failed — hover it to read why']] }, { Target: '.StatusFooter', Title: 'Keeping score', Body: 'RUNNING shows how many instances are open against your limit.

Underneath it, the line reads Launching 3 / 5... as it works, then Launched 5/5 when it is done. If any failed, it tells you how many and what went wrong.' }, ], diff --git a/Production/RAMMIT-Stable/Src/Light/JS/Wizard.js b/Production/RAMMIT-Stable/Src/Light/JS/Wizard.js index 9bca02a..a069311 100644 --- a/Production/RAMMIT-Stable/Src/Light/JS/Wizard.js +++ b/Production/RAMMIT-Stable/Src/Light/JS/Wizard.js @@ -7,7 +7,7 @@ // drop-down closed + ExtraPadding, plus only the part of an open drop-down that would be cut off. // The CSS keeps the same box model as Test1's wizard, so its heights apply 1:1. -import { Api, WaitForApi, ReportError } from './Bridge.js'; +import { Api, WaitForApi, ReportError, OneAtATime } from './Bridge.js'; import { ById } from './Dom.js'; import { InitSelect, SetSelectValue, GetSelectValue } from './Select.js'; import { CreateLaunchForm, FilterMethods } from './LaunchForm.js'; @@ -15,6 +15,7 @@ import { InitTooltips } from './Tooltip.js'; let SizeMap = { Home: 287, ExtraPadding: 20 }; let InitDone = false; +const ResizeWizard = OneAtATime(Height => Api.ResizeWizard(Height)); function FitToContent() { setTimeout(() => { @@ -29,7 +30,7 @@ function FitToContent() { const Clipped = OpenSelect.querySelector('.CustomSelectOptions').getBoundingClientRect().bottom - window.innerHeight; if (Clipped > 0) Needed += Clipped + 5; } - Api.ResizeWizard(Needed).catch(() => {}); + ResizeWizard(Needed); }, 10); } @@ -43,7 +44,7 @@ const Form = CreateLaunchForm(ById('DynamicFields'), { InitSelect(ById('MethodSelect'), Method => { Form.Render(Method, {}); - if (InitDone) Api.ResizeWizard(SizeMap[Method] || SizeMap.Home).catch(() => {}); + if (InitDone) ResizeWizard(SizeMap[Method] || SizeMap.Home); }); // Opening/closing any drop-down, and clicks elsewhere, re-measure. Picking a method does not // (it snaps to the map above), so clicks inside the method list are skipped. diff --git a/Production/RAMMIT-Stable/Src/Light/Theme.json b/Production/RAMMIT-Stable/Src/Light/Theme.json index 41c7d07..cd8abe7 100644 --- a/Production/RAMMIT-Stable/Src/Light/Theme.json +++ b/Production/RAMMIT-Stable/Src/Light/Theme.json @@ -2,5 +2,5 @@ "Name": "2016 Roblox", "Author": "RAMMIT", "Description": "The light blue-and-green look of the old roblox.com.", - "SupportedVersions": ["1.0", "1.1"] + "SupportedVersions": ["1.0", "1.1", "1.2"] } \ No newline at end of file diff --git a/Production/RAMMIT-Stable/Src/MyCustomTheme/CSS/Style.css b/Production/RAMMIT-Stable/Src/MyCustomTheme/CSS/Style.css index d73154e..4a375bc 100644 --- a/Production/RAMMIT-Stable/Src/MyCustomTheme/CSS/Style.css +++ b/Production/RAMMIT-Stable/Src/MyCustomTheme/CSS/Style.css @@ -19,6 +19,7 @@ --SuccessHover: #218838; --Danger: #dc3545; /* - REMOVE, errors, cancel */ --DangerHover: #c82333; + --OnExpired: #ffffff; /* text on an expired login's red row */ --Warning: #ffc107; /* "launching" marks, warnings */ --Border: #22273d; --BorderLight: #30364f; @@ -31,6 +32,7 @@ --Font: 'Segoe UI', sans-serif; --Radius: 8px; /* panel corners */ --ButtonRadius: 6px; /* button and text-box corners */ + /* --TooltipRadius: 4px; tooltip corners: remove the comment marks to round them (square without) */ } /* ===================================================================== @@ -173,9 +175,12 @@ body { color: var(--OnAccent); } -/* A saved login Roblox rejected (expired): red row until it's renewed. */ +/* A saved login Roblox rejected (expired): red row until it's renewed. Its text is --OnExpired (white, or a dark + colour where --Danger is light). Selected, it stays red and gets a ring in that colour: the accent can be as dark + as the red. Themes from before --OnExpired get white. */ .ListItem.Expired { background: var(--Danger); + color: var(--OnExpired, #ffffff); } .ListItem.Expired:hover { @@ -184,8 +189,9 @@ body { .ListItem.Expired.Selected { background: var(--Danger); + color: var(--OnExpired, #ffffff); font-weight: 700; - color: var(--Accent); + box-shadow: inset 0 0 0 2px var(--OnExpired, #ffffff); } .ListButtons { @@ -707,6 +713,16 @@ body { color: var(--OnAccent); } +/* On an expired login's red row (selected or not), the @username and the status mark use the row's text colour: + a red error mark on the red row would vanish. */ +.ListItem.Expired .AcctUser, +.ListItem.Expired .AcctStatus.Queued, +.ListItem.Expired .AcctStatus.Launching, +.ListItem.Expired .AcctStatus.Ok, +.ListItem.Expired .AcctStatus.Error { + color: var(--OnExpired, #ffffff); +} + .BtnSelect { flex: 1; padding: 10px; @@ -1268,7 +1284,7 @@ body.WizardBody { /* Tooltips (JS/Tooltip.js): follow the cursor, flip to its other side at the window's edges. Outside .Container, so not zoomed. Square unless the theme sets --TooltipRadius. Width is the text's own (max-content), so measuring it - does not depend on where it currently sits; long text wraps, and "\n" starts a new line. */ + does not depend on where it currently sits; long text wraps, and a line break in the text starts a new line. */ .Tooltip { position: fixed; left: 0; diff --git a/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Accounts.js b/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Accounts.js index 5e00227..44b02d7 100644 --- a/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Accounts.js +++ b/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Accounts.js @@ -85,11 +85,14 @@ export function ApplySelection() { AddBtn.classList.toggle('BtnAdd', !Renew); AddBtn.classList.toggle('BtnRenew', !!Renew); AddBtn.textContent = Renew ? 'RENEW' : '+ ADD'; - AddBtn.removeAttribute('title'); - AddBtn.dataset.tooltip = Renew ? `Sign in again as @${Renew} (its saved login expired)` : 'Sign in to a Roblox account and save it'; + AddBtn.title = Renew ? `Sign in again as @${Renew} (its saved login expired)` : 'Sign in to a Roblox account and save it'; ById('SelectionCount').textContent = Count ? ` (${Count} SELECTED)` : ''; ById('SelectAllBtn').textContent = (State.Accounts.length > 0 && Count >= State.Accounts.length) ? 'CLEAR' : 'SELECT ALL'; - if (!State.BatchRunning) ById('LaunchBtn').textContent = Renew ? 'RENEW AND LAUNCH' : Count > 1 ? `LAUNCH ${Count} SELECTED` : 'LAUNCH SELECTED'; + if (!State.BatchRunning) { + const LaunchBtn = ById('LaunchBtn'); + LaunchBtn.textContent = Renew ? 'RENEW AND LAUNCH' : Count > 1 ? `LAUNCH ${Count} SELECTED` : 'LAUNCH SELECTED'; + LaunchBtn.title = Renew ? `Sign in again as @${Renew}, then launch it` : 'Launch every ticked account, one after another'; + } } export function ApplyAccountStatus() { @@ -119,9 +122,14 @@ export async function AddAccount() { } // Sign in again for an expired account. True when that same Roblox user signed in (a different one is added instead). +// An account renamed on Roblox comes back under its new name; it stays selected under that name. export async function RenewAccount(Username) { const Result = await Api.RenewAccount(Username); if (Result && Result.Error) ShowLaunchError(Result.Error); + if (Result && Result.Renewed && Result.Username && Result.Username !== Username) { + State.Selected.delete(Username); + State.Selected.add(Result.Username); + } await RefreshAccounts(); return !!(Result && Result.Renewed); } diff --git a/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Bridge.js b/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Bridge.js index b974d8b..b0dd3e5 100644 --- a/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Bridge.js +++ b/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Bridge.js @@ -17,6 +17,30 @@ export const Api = new Proxy({}, { }, }); +// Fn(...Args) one call at a time. pywebview runs every call to Python on its own thread, so two calls in flight can +// finish in either order (two resizes would leave the window at the older height). While one runs, only the newest +// arguments wait and are sent when it has finished; older ones are dropped. Errors are ignored, like a resize's. +// A call that never answers stops holding the others up after GiveUpMs (App/WindowSize.py applies resizes under one +// lock, so a late one still lands before the next). +export function OneAtATime(Fn, GiveUpMs = 3000) { + let Running = false; + let Waiting = null; + const Run = (...Args) => { + if (Running) { Waiting = Args; return; } + Running = true; + const GiveUp = new Promise(Resolve => setTimeout(Resolve, GiveUpMs)); + Promise.race([Promise.resolve().then(() => Fn(...Args)), GiveUp]).catch(() => {}).finally(() => { + Running = false; + if (Waiting) { + const Next = Waiting; + Waiting = null; + Run(...Next); + } + }); + }; + return Run; +} + const Handlers = {}; window.RammitEvents = { AccountsChanged: Payload => Fire('AccountsChanged', Payload), diff --git a/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Launch.js b/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Launch.js index 0705310..dc6463c 100644 --- a/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Launch.js +++ b/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Launch.js @@ -1,7 +1,7 @@ // LAUNCHER CONTROLS panel: launch option + its boxes, the launch/cancel button, batch progress, // the RUNNING counter, and window height. -import { Api, ReportError } from './Bridge.js'; +import { Api, ReportError, OneAtATime } from './Bridge.js'; import { ById, Debounce } from './Dom.js'; import { InitSelect, SetSelectValue, GetSelectValue } from './Select.js'; import { CreateLaunchForm } from './LaunchForm.js'; @@ -17,6 +17,7 @@ let Form = null; let BatchPoll = null; const SaveParams = Debounce(() => Api.UpdateSetting('LaunchParams', Form.GetParams()).catch(ReportError), 300); +const ResizeWindow = OneAtATime(Height => Api.ResizeWindow(Height)); export async function LoadHeightMap() { const Map = await Api.GetHeightMap(); @@ -44,7 +45,7 @@ export function ResizeForCurrentOption() { const PlayerSel = ById('PlayerModeSelect'); if (PlayerSel && ['min_only', 'max_only', 'range'].includes(GetSelectValue(PlayerSel))) Height += HeightMap.PlayerFilterExtra || 0; Height += ThemeNoteExtra(); // exactly as much as a note under the Theme list adds (0 when there is none) - Api.ResizeWindow(Height).catch(() => {}); + ResizeWindow(Height); } function OnLaunchClick() { @@ -87,8 +88,10 @@ function SetBatchRunning(Running) { State.BatchRunning = Running; const Button = ById('LaunchBtn'); Button.classList.toggle('Cancel', Running); - if (Running) Button.textContent = 'CANCEL LAUNCH'; - else ApplySelection(); + if (Running) { + Button.textContent = 'CANCEL LAUNCH'; + Button.title = 'Stop the launch: accounts not started yet are skipped'; + } else ApplySelection(); } // Row marks come from two places: the batch's results (queued / launching / skipped / error) and, once an account's @@ -120,11 +123,13 @@ function RenderAccountStatus() { // The status line only says "Launched" once the game windows are open (as RAMMIT's earlier test builds did): while an account // is being launched, or its window isn't open yet, it says "Launching X / Y..."; in the launch delay after an account -// whose window is already open, "Launched X/Y". After the last launch it waits for the windows, then ShowLaunchDone -// (which clears itself); it gives up waiting after WindowWait. +// whose window is already open, "X / Y done, next launch soon...". After the last launch it waits for the windows, +// then ShowLaunchDone (which clears itself); it gives up waiting after WindowWait. The windows count as open only on +// a counter poll that started after the batch ended: an earlier one can still show a client that has since closed. const WindowWait = 30000; let LastProgress = null; let Waiting = null; // { Names, Ok, Total, Since } after a batch, until its windows are open +let LastPollAsked = 0; // when the newest counter poll whose answer is in LiveAccounts was sent const IsOpen = Name => LiveAccounts[Name] === 'running'; @@ -132,13 +137,14 @@ function BatchStatusText(Progress) { const Results = Progress.Results || {}; if (Object.values(Results).includes('launching')) return `Launching ${Math.min(Progress.Done + 1, Progress.Total)} / ${Progress.Total}...`; const Last = Object.keys(Results).filter(Name => Results[Name] === 'ok').pop(); - return Last && IsOpen(Last) ? `Launched ${Progress.Done}/${Progress.Total}` : `Launching ${Progress.Done} / ${Progress.Total}...`; + // Waiting out the launch delay: not "Launched ...", which only ever means the whole batch is done + return Last && IsOpen(Last) ? `${Progress.Done} / ${Progress.Total} done, next launch soon...` : `Launching ${Progress.Done} / ${Progress.Total}...`; } function RenderLaunchStatus() { if (State.BatchRunning && LastProgress) { SetLaunchStatus(BatchStatusText(LastProgress)); return; } if (!Waiting) return; - if (Waiting.Names.every(IsOpen) || Date.now() - Waiting.Since > WindowWait) { + if ((LastPollAsked >= Waiting.Since && Waiting.Names.every(IsOpen)) || Date.now() - Waiting.Since > WindowWait) { ShowLaunchDone(`Launched ${Waiting.Ok}/${Waiting.Total}`); Waiting = null; } else { @@ -172,6 +178,7 @@ function FinishBatch(Progress) { export async function UpdateCounter() { try { + const Asked = Date.now(); const Counter = await Api.GetCounter(); const Label = ById('CounterLabel'); // MultiReady is false when Roblox was already open before RAMMIT started (see App/MultiInstance.py). @@ -179,6 +186,7 @@ export async function UpdateCounter() { Label.title = Counter.MultiReady === false ? 'Roblox was already open when RAMMIT started, so only one client can run. Close every Roblox window and RAMMIT will take over on the next launch.' : ''; LiveAccounts = Counter.Accounts || {}; + LastPollAsked = Math.max(LastPollAsked, Asked); RenderAccountStatus(); RenderLaunchStatus(); } catch (_) { /* backend busy - next tick */ } diff --git a/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Tooltip.js b/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Tooltip.js index 5635396..e9e42f8 100644 --- a/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Tooltip.js +++ b/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Tooltip.js @@ -1,6 +1,8 @@ // Themed tooltips (the CBlock tooltip), instead of the browser's own. // Any element with data-tooltip="..." or a title="..." gets one: a title is moved into data-tooltip when hovered, -// so the native tooltip never shows and no existing title has to change. "\n" in the text starts a new line. +// so the native tooltip never shows and no existing title has to change. A line break in the text starts a new line. +// The text is shown as plain text (textContent), never as HTML. While a tooltip shows, a changed title or +// data-tooltip on its element (e.g. + ADD turning into RENEW) updates it straight away. // Look: .Tooltip in Style.css (colours from the theme; --TooltipRadius rounds it, 0 by default). const OffsetX = 12, OffsetY = 16; // from the cursor @@ -8,14 +10,23 @@ const FlipGap = 12; // from the cursor when flipped to its left / let Tip = null; let Target = null; let LastX = 0, LastY = 0; +const Watch = new MutationObserver(() => { if (Target) Refresh(); }); // Takes over a title (also one set again later, e.g. an account's status) and returns the text to show. +// Screen readers used the title as the element's name (an icon-only button) or its description (anything with text), +// so it moves to aria-label or aria-description, unless the page set that attribute to something else. function ReadText(Node) { if (Node.hasAttribute('title')) { - Node.dataset.tooltip = Node.getAttribute('title'); + const Old = Node.dataset.tooltip; + const Text = Node.getAttribute('title'); + Node.dataset.tooltip = Text; Node.removeAttribute('title'); + const Attr = Node.textContent.trim() ? 'aria-description' : 'aria-label'; + const Ours = !Node.hasAttribute(Attr) || Node.getAttribute(Attr) === Old; + if (Ours && Text) Node.setAttribute(Attr, Text); + else if (Ours) Node.removeAttribute(Attr); } - return (Node.dataset.tooltip || '').replace(/\\n/g, '\n'); + return Node.dataset.tooltip || ''; } // Right of / below the cursor; where that would leave the window, the other side of the cursor instead. @@ -31,14 +42,28 @@ function Place() { function Show(Node) { const Text = ReadText(Node); if (!Text) { Hide(); return; } + if (Target !== Node) { + Watch.disconnect(); + Watch.observe(Node, { attributes: true, attributeFilter: ['title', 'data-tooltip'] }); + } Target = Node; Tip.textContent = Text; Place(); // before it fades in, so it never flashes where it was last time Tip.classList.add('Visible'); } +// The element under the cursor changed its text, or the cursor moved: keep the tooltip right. +function Refresh() { + if (!Target.isConnected) { Hide(); return; } // re-drawn under the cursor: no mouseout ever comes + const Text = ReadText(Target); + if (!Text) { Hide(); return; } + if (Tip.textContent !== Text) Tip.textContent = Text; + Place(); +} + function Hide() { Target = null; + Watch.disconnect(); if (Tip) Tip.classList.remove('Visible'); } @@ -55,9 +80,7 @@ export function InitTooltips() { }); document.addEventListener('mousemove', Event => { LastX = Event.clientX; LastY = Event.clientY; - if (!Target) return; - if (!Target.isConnected) { Hide(); return; } // re-drawn under the cursor: no mouseout ever comes - if (Target.hasAttribute('title')) Show(Target); else Place(); + if (Target) Refresh(); }); document.addEventListener('mouseout', Event => { if (!Event.relatedTarget) Hide(); }); // left the window document.addEventListener('mousedown', Hide); diff --git a/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/TourData.js b/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/TourData.js index b4d118a..1da4146 100644 --- a/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/TourData.js +++ b/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/TourData.js @@ -40,7 +40,7 @@ export const Tours = [ Body: 'The button counts what you picked — LAUNCH 4 SELECTED.

They open one after another rather than all in the same instant. Changed your mind halfway? The button turns into CANCEL LAUNCH and stops the ones that have not started yet.' }, { Target: '#AccountList', Title: 'Watch how each one goes', Body: 'While a launch runs, every row shows where it is up to:', - Keys: [['…', 'waiting its turn'], ['•••', 'starting up now'], ['✓', 'launched'], ['✗', 'failed — hover it to read why']] }, + Keys: [['…', 'waiting its turn'], ['•••', 'starting up now'], ['✓', 'its game window is open (clears when it closes)'], ['✗', 'failed — hover it to read why']] }, { Target: '.StatusFooter', Title: 'Keeping score', Body: 'RUNNING shows how many instances are open against your limit.

Underneath it, the line reads Launching 3 / 5... as it works, then Launched 5/5 when it is done. If any failed, it tells you how many and what went wrong.' }, ], diff --git a/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Wizard.js b/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Wizard.js index 9bca02a..a069311 100644 --- a/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Wizard.js +++ b/Production/RAMMIT-Stable/Src/MyCustomTheme/JS/Wizard.js @@ -7,7 +7,7 @@ // drop-down closed + ExtraPadding, plus only the part of an open drop-down that would be cut off. // The CSS keeps the same box model as Test1's wizard, so its heights apply 1:1. -import { Api, WaitForApi, ReportError } from './Bridge.js'; +import { Api, WaitForApi, ReportError, OneAtATime } from './Bridge.js'; import { ById } from './Dom.js'; import { InitSelect, SetSelectValue, GetSelectValue } from './Select.js'; import { CreateLaunchForm, FilterMethods } from './LaunchForm.js'; @@ -15,6 +15,7 @@ import { InitTooltips } from './Tooltip.js'; let SizeMap = { Home: 287, ExtraPadding: 20 }; let InitDone = false; +const ResizeWizard = OneAtATime(Height => Api.ResizeWizard(Height)); function FitToContent() { setTimeout(() => { @@ -29,7 +30,7 @@ function FitToContent() { const Clipped = OpenSelect.querySelector('.CustomSelectOptions').getBoundingClientRect().bottom - window.innerHeight; if (Clipped > 0) Needed += Clipped + 5; } - Api.ResizeWizard(Needed).catch(() => {}); + ResizeWizard(Needed); }, 10); } @@ -43,7 +44,7 @@ const Form = CreateLaunchForm(ById('DynamicFields'), { InitSelect(ById('MethodSelect'), Method => { Form.Render(Method, {}); - if (InitDone) Api.ResizeWizard(SizeMap[Method] || SizeMap.Home).catch(() => {}); + if (InitDone) ResizeWizard(SizeMap[Method] || SizeMap.Home); }); // Opening/closing any drop-down, and clicks elsewhere, re-measure. Picking a method does not // (it snaps to the map above), so clicks inside the method list are skipped. diff --git a/Production/RAMMIT-Stable/Src/MyCustomTheme/Theme.json b/Production/RAMMIT-Stable/Src/MyCustomTheme/Theme.json index 347108d..a7ed237 100644 --- a/Production/RAMMIT-Stable/Src/MyCustomTheme/Theme.json +++ b/Production/RAMMIT-Stable/Src/MyCustomTheme/Theme.json @@ -2,5 +2,5 @@ "Name": "My Custom Theme", "Author": "RAMMIT example", "Description": "Example custom theme - copy this folder to make your own.", - "SupportedVersions": ["1.0", "1.1"] + "SupportedVersions": ["1.0", "1.1", "1.2"] } \ No newline at end of file diff --git a/Production/RAMMIT-Stable/Tests/TestBackend.py b/Production/RAMMIT-Stable/Tests/TestBackend.py index 1962848..ee7d441 100644 --- a/Production/RAMMIT-Stable/Tests/TestBackend.py +++ b/Production/RAMMIT-Stable/Tests/TestBackend.py @@ -54,7 +54,8 @@ def setUp(self): self.Old, self.New = os.path.join(self.Root, "Old"), os.path.join(self.Root, "New") for Folder in (self.Old, self.New): os.makedirs(Folder) - open(os.path.join(Folder, "RAMMIT.exe"), "w").close() + for Name in ("RAMMIT.exe", "Manifest.json"): # what an installer-made folder has + open(os.path.join(Folder, Name), "w").close() def tearDown(self): import winreg @@ -95,6 +96,24 @@ def test_MovedFolderTakesOverAndSecondCopyDoesNot(self): self.assertEqual(self.Sync(self.New), "") # already right Install._Write(ProtocolKey + r"\shell\open\command", "", '"C:\\Elsewhere\\RAMMIT.exe"') self.assertEqual(self.Sync(self.New), "Fixed") + self.assertNotIn("%", Install._Read(ProtocolKey + r"\shell\open\command")) # nothing from the link is passed on + + def test_OnlyAnInstallerMadeFolderTakesOver(self): + from App import Install + RegKey, ProtocolKey, _UninstallKey = self.Keys + Install._Write(RegKey, "InstallPath", self.Old) + os.remove(os.path.join(self.Old, "RAMMIT.exe")) # the installed RAMMIT is gone + os.remove(os.path.join(self.New, "Manifest.json")) # e.g. a copy unzipped from a release + self.assertEqual(self.Sync(self.New), "") + self.assertEqual(Install._Read(RegKey, "InstallPath"), self.Old) + self.assertIsNone(Install._Read(ProtocolKey + r"\shell\open\command")) + open(os.path.join(self.New, "Manifest.json"), "w").close() + with mock.patch.object(Install, "_OnRemovableDrive", return_value=True): + self.assertEqual(self.Sync(self.New), "") # a USB stick: it would break again once the stick is gone + with mock.patch.dict(os.environ, {"RAMMIT_INSTALLER_TEST": "1"}): + self.assertEqual(self.Sync(self.New), "") # started by the installer's test mode + self.assertEqual(Install._Read(RegKey, "InstallPath"), self.Old) + self.assertEqual(self.Sync(self.New), "Moved") class TestVersion(unittest.TestCase): @@ -222,6 +241,47 @@ def test_BuildLaunchUrlRejectsInjection(self): with self.assertRaises(ValueError, msg=Args): Roblox.BuildLaunchUrl(*Args) + @staticmethod + def Reply(Status, Body=None, Headers=None): + Response = mock.Mock(status_code=Status, headers=Headers or {}) + Response.json.side_effect = (lambda: Body) if not isinstance(Body, Exception) else Body + return Response + + def test_CheckLoginOnlyA401MeansExpired(self): + # Being offline, rate limited or answered oddly must never turn an account red. + Get = "App.Roblox.requests.get" + Valid = {"id": 7, "name": "Bob", "displayName": "Bobby"} + with mock.patch(Get, return_value=self.Reply(200, Valid)): + self.assertEqual(Roblox.CheckLogin("fake"), ("Valid", (7, "Bob", "Bobby"))) + with mock.patch(Get, return_value=self.Reply(401)): + self.assertEqual(Roblox.CheckLogin("fake"), ("Expired", None)) + for Status in (403, 429, 500, 503): + with mock.patch(Get, return_value=self.Reply(Status)): + self.assertEqual(Roblox.CheckLogin("fake"), ("Unknown", None), Status) + for Body in ({"id": "7", "name": "Bob"}, {"name": "Bob"}, [], ValueError("not JSON")): + with mock.patch(Get, return_value=self.Reply(200, Body)): + self.assertEqual(Roblox.CheckLogin("fake"), ("Unknown", None), Body) + with mock.patch(Get, side_effect=Roblox.requests.ConnectionError): + self.assertEqual(Roblox.CheckLogin("fake"), ("Unknown", None)) + + def test_GetAuthTicketOnlyA401MeansExpired(self): + Post = "App.Roblox.requests.post" + Csrf = self.Reply(403, Headers={"x-csrf-token": "csrf"}) + with mock.patch(Post, side_effect=[Csrf, self.Reply(200, Headers={"rbx-authentication-ticket": "T"})]): + self.assertEqual(Roblox.GetAuthTicket("fake"), "T") + with mock.patch(Post, return_value=self.Reply(401)): + self.assertIs(Roblox.GetAuthTicket("fake"), Roblox.LoginExpired) # rejected at the CSRF step + with mock.patch(Post, side_effect=[Csrf, self.Reply(401)]): + self.assertIs(Roblox.GetAuthTicket("fake"), Roblox.LoginExpired) # rejected at the ticket step + with mock.patch(Post, return_value=self.Reply(403)): + self.assertIsNone(Roblox.GetAuthTicket("fake")) # no CSRF token: not "expired" + with mock.patch(Post, side_effect=[Csrf, self.Reply(500)]): + self.assertIsNone(Roblox.GetAuthTicket("fake")) + with mock.patch(Post, side_effect=Roblox.requests.ConnectionError): + self.assertIsNone(Roblox.GetAuthTicket("fake")) + with mock.patch(Post, side_effect=[Csrf] + [self.Reply(429)] * 4), mock.patch("App.Roblox.time.sleep"): + self.assertIsNone(Roblox.GetAuthTicket("fake")) # still rate limited after the retries + Servers = [{"id": "f" * 8 + JobA[8:], "playing": 10, "maxPlayers": 10, "ping": 5}, {"id": "a" * 8 + JobA[8:], "playing": 1, "maxPlayers": 10, "ping": 200}, {"id": "b" * 8 + JobA[8:], "playing": 5, "maxPlayers": 10, "ping": 40}, @@ -466,16 +526,23 @@ def test_LaunchOneHappyPath(self): self.assertEqual(Args[0], "C:\\R.exe") self.assertIn("placeId=123", Args[1]) self.assertEqual(self.Api._Clients._Owners[4242]["User"], "B") # the started process belongs to the account - self.assertEqual(self.Api._Clients._Expected, []) + Entries = self.Api._Clients._Expected # the ticket stays until the game window shows (ticket fallback) + self.assertEqual([(E["User"], E["Pid"]) for E in Entries], [("B", 4242)]) + + def test_LaunchThatCantStartIsForgotten(self): + with mock.patch.object(ApiModule.MultiInstance, "CountRunning", return_value=0), \ + mock.patch.object(ApiModule.MultiInstance, "LockCookieFile"), \ + mock.patch.object(ApiModule.MultiInstance, "HoldMutex", return_value=True), \ + mock.patch.object(ApiModule.Roblox, "FindLauncherPath", return_value="C:\\R.exe"), \ + mock.patch.object(ApiModule.Roblox, "GetAuthTicket", return_value="TICKET"), \ + mock.patch.object(ApiModule.subprocess, "Popen", side_effect=FileNotFoundError): + self.assertEqual(self.Api._LaunchOne("A", "Home", {}), {"Error": "Could not start Roblox."}) + self.assertEqual(self.Api._Clients._Expected, []) # it doesn't count as "starting" for 2 minutes def test_ClientTrackerFollowsLaunchesToTheirGameWindows(self): # As seen on a real PC: the process RAMMIT starts can hand the game to a "--launch-to-tray" child that opens the # window; a game that closes leaves a tray child too, which must not take the account over. from App import MultiInstance - Tracker = MultiInstance.ClientTracker() - Tracker.Expect("TICKETA", "A") - Tracker.Started("TICKETA", 20) # A: RAMMIT started pid 20 - Tracker.Expect("TICKETB", "B") # B: its process is only found by its ticket (pid 30) Lines = {20: "RobloxPlayerBeta.exe roblox-player:1+launchmode:play+gameinfo:TICKETA+launchtime:1", 21: "RobloxPlayerBeta.exe --launch-to-tray", 22: "RobloxPlayerBeta.exe --launch-to-tray", 30: "RobloxPlayerBeta.exe roblox-player:1+launchmode:play+gameinfo:TICKETB+launchtime:2"} @@ -489,9 +556,16 @@ def Scan(Running, Windows, IncludeStarting=True): mock.patch.object(MultiInstance, "_GameWindowPids", return_value=set(Windows)), \ mock.patch.object(MultiInstance, "_CommandLine", side_effect=lambda Pid: Lines[Pid]), \ mock.patch.object(MultiInstance, "_ParentPid", side_effect=lambda Pid: Parents[Pid]), \ + mock.patch.object(MultiInstance, "_CreateTime", side_effect=lambda Pid: 1000.0 + Pid), \ mock.patch.object(MultiInstance, "_Alive", side_effect=lambda Pid: Pid in Players): return Tracker.Scan(IncludeStarting), Tracker.Accounts() + with mock.patch.object(MultiInstance, "_CreateTime", side_effect=lambda Pid: 1000.0 + Pid): + Tracker = MultiInstance.ClientTracker() + Tracker.Expect("TICKETA", "A") + Tracker.Started("TICKETA", 20) # A: RAMMIT started pid 20 + Tracker.Expect("TICKETB", "B") # B: its process is only found by its ticket (pid 30) + self.assertEqual(Scan([20], []), (2, {"A": "starting", "B": "starting"})) # no windows yet: count for the limit self.assertEqual(Scan([20], [], IncludeStarting=False)[0], 0) # but not on the counter label self.assertEqual(Scan([21], [21]), (2, {"A": "running", "B": "starting"})) # 20 handed A to 21, which opened it @@ -499,6 +573,129 @@ def Scan(Running, Windows, IncludeStarting=True): self.assertEqual(Scan([22, 30], [30]), (1, {"B": "running"})) # A closed; its tray child 22 isn't A self.assertEqual(Scan([22], []), (0, {})) + def TrackerScanner(self, Tracker, Lines, Parents, Created): + """Scan(Running, Windows) with the OS probes faked. Created: pid -> process start time.""" + from App import MultiInstance + Players = set() + + def Scan(Running, Windows, IncludeStarting=True): + Players.clear() + Players.update(Running) + with mock.patch.object(MultiInstance, "_PlayerPids", return_value=set(Running)), \ + mock.patch.object(MultiInstance, "_GameWindowPids", return_value=set(Windows)), \ + mock.patch.object(MultiInstance, "_CommandLine", side_effect=lambda Pid: Lines.get(Pid, "")), \ + mock.patch.object(MultiInstance, "_ParentPid", side_effect=lambda Pid: Parents.get(Pid, 1)), \ + mock.patch.object(MultiInstance, "_CreateTime", side_effect=lambda Pid: Created.get(Pid)), \ + mock.patch.object(MultiInstance, "_Alive", side_effect=lambda Pid: Pid in Players): + return Tracker.Scan(IncludeStarting), Tracker.Accounts() + return Scan + + def test_ClientTrackerFindsALaterProcessByItsTicket(self): + # Roblox's updater can start the real client with the original link: not a child of the process RAMMIT started. + from App import MultiInstance + Created = {20: 1.0, 40: 2.0} + with mock.patch.object(MultiInstance, "_CreateTime", side_effect=lambda Pid: Created.get(Pid)): + Tracker = MultiInstance.ClientTracker() + Tracker.Expect("TICKETA", "A") + Tracker.Started("TICKETA", 20) + Scan = self.TrackerScanner(Tracker, {40: "RobloxPlayerBeta.exe roblox-player:1+gameinfo:TICKETA+x"}, {40: 99}, Created) + self.assertEqual(Scan([20], []), (1, {"A": "starting"})) + self.assertEqual(Scan([40], []), (1, {"A": "starting"})) # 20 exited; 40 carries A's ticket: still one launch + self.assertEqual(Scan([40], [40]), (1, {"A": "running"})) + self.assertEqual(Tracker._Expected, []) # window shown: the ticket is dropped + + def test_ClientTrackerIgnoresAReusedPid(self): + from App import MultiInstance + Created = {20: 1.0} + with mock.patch.object(MultiInstance, "_CreateTime", side_effect=lambda Pid: Created.get(Pid)): + Tracker = MultiInstance.ClientTracker() + Tracker.Expect("TICKETA", "A") + Tracker.Started("TICKETA", 20) + Scan = self.TrackerScanner(Tracker, {}, {}, Created) + self.assertEqual(Scan([20], [20]), (1, {"A": "running"})) + Created[20] = 5.0 # A's client closed and Windows gave pid 20 to an unrelated Roblox process + self.assertEqual(Scan([20], [20]), (1, {})) # counted as a client, but not as A's + + def test_ClientTrackerCountsEachLaunchOnce(self): + # Relaunching an account that already has a game open counts towards the limit, and a launch that hands over to + # a child is still one launch. + from App import MultiInstance + Created = {20: 1.0, 21: 2.0, 50: 3.0} + with mock.patch.object(MultiInstance, "_CreateTime", side_effect=lambda Pid: Created.get(Pid)): + Tracker = MultiInstance.ClientTracker() + Tracker.Expect("T1", "A") + Tracker.Started("T1", 20) + Scan = self.TrackerScanner(Tracker, {}, {21: 20}, Created) + self.assertEqual(Scan([20], [20]), (1, {"A": "running"})) + with mock.patch.object(MultiInstance, "_CreateTime", side_effect=lambda Pid: Created.get(Pid)): + Tracker.Expect("T2", "A") + Tracker.Started("T2", 50) + self.assertEqual(Scan([20, 50], [20]), (2, {"A": "starting"})) # A's second launch counts, and isn't open yet + Parents = {21: 20} + Scan = self.TrackerScanner(Tracker, {}, Parents, Created) + self.assertEqual(Scan([20, 21, 50], [20])[0], 2) # 21 is a child of 20, whose launch is open: takes nothing + self.assertEqual(Scan([20, 21, 50], [20, 50]), (2, {"A": "running"})) + + def test_ClientTrackerCountsTwoStartingLaunchesOfOneAccount(self): + # e.g. a second batch started before the first one's window showed: two clients are on their way + from App import MultiInstance + Created = {20: 1.0, 50: 2.0} + with mock.patch.object(MultiInstance, "_CreateTime", side_effect=lambda Pid: Created.get(Pid)): + Tracker = MultiInstance.ClientTracker() + for Ticket, Pid in (("T1", 20), ("T2", 50)): + Tracker.Expect(Ticket, "A") + Tracker.Started(Ticket, Pid) + Scan = self.TrackerScanner(Tracker, {}, {}, Created) + self.assertEqual(Scan([20, 50], []), (2, {"A": "starting"})) + + def test_ClientTrackerAdoptsAGonePidReusedByAHandoffChild(self): + # Alice's client (pid 100) closed; Bob's launch hands its game to a child that Windows gives pid 100. + from App import MultiInstance + Created = {100: 1.0, 200: 2.0} + with mock.patch.object(MultiInstance, "_CreateTime", side_effect=lambda Pid: Created.get(Pid)): + Tracker = MultiInstance.ClientTracker() + Tracker.Expect("TA", "Alice") + Tracker.Started("TA", 100) + Parents = {100: 1} + Scan = self.TrackerScanner(Tracker, {}, Parents, Created) + self.assertEqual(Scan([100], [100]), (1, {"Alice": "running"})) + self.assertEqual(Scan([], []), (0, {})) # Alice closed: pid 100 is remembered as Gone for a while + with mock.patch.object(MultiInstance, "_CreateTime", side_effect=lambda Pid: Created.get(Pid)): + Tracker.Expect("TB", "Bob") + Tracker.Started("TB", 200) + Created[100], Parents[100] = 3.0, 200 # Bob's child reuses pid 100, and 200 exits + self.assertEqual(Scan([100], []), (1, {"Bob": "starting"})) # adopted at once, not after the Gone wait + self.assertEqual(Scan([100], [100]), (1, {"Bob": "running"})) + + def test_ClientTrackerDropsALauncherPidReusedByAnotherProgram(self): + # A Bloxstrap launcher (not a RobloxPlayerBeta) died before any window; Windows gave its pid to notepad. + from App import MultiInstance + Created = {300: 1.0} + with mock.patch.object(MultiInstance, "_CreateTime", side_effect=lambda Pid: Created.get(Pid)): + Tracker = MultiInstance.ClientTracker() + Tracker.Expect("TC", "Carol") + Tracker.Started("TC", 300) + Created[300] = 9.0 # notepad.exe now has pid 300: alive, but not a RobloxPlayerBeta + with mock.patch.object(MultiInstance, "_PlayerPids", return_value=set()), \ + mock.patch.object(MultiInstance, "_GameWindowPids", return_value=set()), \ + mock.patch.object(MultiInstance, "_CreateTime", side_effect=lambda Pid: Created.get(Pid)), \ + mock.patch.object(MultiInstance, "_Alive", return_value=True): + self.assertEqual(Tracker.Scan(), 0) # no longer a launch "starting" for 10 minutes + self.assertEqual(Tracker.Accounts(), {}) + self.assertNotIn(300, Tracker._Owners) + + def test_ClientTrackerRenameAndForget(self): + from App import MultiInstance + with mock.patch.object(MultiInstance, "_CreateTime", return_value=1.0): + Tracker = MultiInstance.ClientTracker() + Tracker.Expect("T1", "A") + Tracker.Started("T1", 20) + Tracker.Expect("T2", "B") + Tracker.Forget("T2") + Tracker.Rename("A", "A2") + Scan = self.TrackerScanner(Tracker, {}, {}, {20: 1.0}) + self.assertEqual(Scan([20], [20]), (1, {"A2": "running"})) + def test_OnlyGameWindowsCount(self): # Roblox's tray right-click menu (SystrayContextMenu) is a visible window too, and a hidden game window isn't open yet. from App import MultiInstance @@ -534,7 +731,9 @@ def test_RenewKeepsTheSameUserAndAddsADifferentOne(self): self.Api._Expired = {"a", "b", "c"} self.Api.UpdateSetting("SelectedAccounts", ["A"]) with mock.patch.object(ApiModule.Roblox, "CheckLogin", return_value=("Valid", (7, "A2", "Renamed"))): - self.assertEqual(self.Api._FinishLogin("new-A", "A"), "Renewed") # same user id: renamed on Roblox, same row + Outcome = {} + self.assertEqual(self.Api._FinishLogin("new-A", "A", Outcome), "Renewed") # same user id: renamed on Roblox + self.assertEqual(Outcome["Username"], "A2") # RENEW AND LAUNCH selects it under its new name with mock.patch.object(ApiModule.Roblox, "CheckLogin", return_value=("Valid", (12, "C", "c"))): self.assertEqual(self.Api._FinishLogin("new-C", "C"), "Renewed") # no id saved yet: same username counts with mock.patch.object(ApiModule.Roblox, "CheckLogin", return_value=("Valid", (9, "Other", "o"))): @@ -555,6 +754,81 @@ def test_ExpiredLoginAtLaunchMarksTheAccount(self): self.assertEqual(self.Api._LaunchOne("A", "Home", {}), {"Error": ApiModule.ExpiredMessage}) self.assertTrue(self.Api.GetAccounts()[0]["Expired"]) + def test_ExpiredAtLaunchDoesNotMarkAJustRenewedLogin(self): + self.Api._Expired.clear() + Account = self.Api._Accounts[0] + + def RenewedMeanwhile(_Cookie): # RENEW saved a new login while this launch was asking for a ticket + Account["Cookie"] = "renewed-A" + return ApiModule.Roblox.LoginExpired + with mock.patch.object(ApiModule.MultiInstance, "CountRunning", return_value=0), \ + mock.patch.object(ApiModule.MultiInstance, "LockCookieFile"), \ + mock.patch.object(ApiModule.MultiInstance, "HoldMutex", return_value=True), \ + mock.patch.object(ApiModule.Roblox, "FindLauncherPath", return_value="C:\\R.exe"), \ + mock.patch.object(ApiModule.Roblox, "GetAuthTicket", side_effect=RenewedMeanwhile): + self.assertEqual(self.Api._LaunchOne("A", "Home", {}), {"Error": ApiModule.ExpiredMessage}) + self.assertFalse(self.Api.GetAccounts()[0]["Expired"]) + + def test_ExpiredAtLaunchDoesNotMarkAReaddedLogin(self): + self.Api._Expired.clear() + + def ReaddedMeanwhile(_Cookie): # + ADD saved a new login for the same account while this launch waited + with mock.patch.object(ApiModule.Roblox, "CheckLogin", return_value=("Valid", (55, "A", "a"))): + self.Api._FinishLogin("new-A") + return ApiModule.Roblox.LoginExpired + with mock.patch.object(ApiModule.MultiInstance, "CountRunning", return_value=0), \ + mock.patch.object(ApiModule.MultiInstance, "LockCookieFile"), \ + mock.patch.object(ApiModule.MultiInstance, "HoldMutex", return_value=True), \ + mock.patch.object(ApiModule.Roblox, "FindLauncherPath", return_value="C:\\R.exe"), \ + mock.patch.object(ApiModule.Roblox, "GetAuthTicket", side_effect=ReaddedMeanwhile): + self.assertEqual(self.Api._LaunchOne("A", "Home", {}), {"Error": ApiModule.ExpiredMessage}) + self.assertFalse({A["Username"]: A["Expired"] for A in self.Api.GetAccounts()}["A"]) + + def test_RenewAccountReturnsTheNewName(self): + def FakeOpenLogin(_Title, RenewFor=None, Done=None, Outcome=None): + Outcome.update({"Result": "Renewed", "Username": "A2"}) + Done.set() + return {"Ok": True} + with mock.patch.object(self.Api, "_OpenLogin", side_effect=FakeOpenLogin): + self.assertEqual(self.Api.RenewAccount("A"), {"Ok": True, "Renewed": True, "Username": "A2"}) + + def Closed(_Title, RenewFor=None, Done=None, Outcome=None): + Done.set() + return {"Ok": True} + with mock.patch.object(self.Api, "_OpenLogin", side_effect=Closed): + self.assertEqual(self.Api.RenewAccount("A"), {"Ok": True, "Renewed": False}) + + def test_WindowSizeWiresUpTheDragEvents(self): + from App import WindowSize + + class Event: # what pythonnet's .NET events and pywebview's events support: += and firing + def __init__(self): + self.Handlers = [] + + def __iadd__(self, Handler): + self.Handlers.append(Handler) + return self + + def Fire(self, *Args): + for Handler in self.Handlers: + Handler(*Args) + + Window = mock.MagicMock() + Window.events.shown = Event() + Window.native = mock.Mock(Height=595, ResizeBegin=Event(), ResizeEnd=Event()) + Sizer = WindowSize.HeldWindow(Window) + Window.events.shown.Fire() # the window is up: ResizeBegin / ResizeEnd are watched + Window.native.ResizeBegin.Fire(None, None) # title bar grabbed + Sizer.Resize(765, 800) + Window.resize.assert_not_called() + with mock.patch.object(WindowSize.HeldWindow, "_SetHeight") as SetHeight, \ + mock.patch.object(WindowSize.HeldWindow, "_WindowScale", return_value=1.25), \ + mock.patch.object(WindowSize.threading, "Thread", side_effect=lambda target, daemon: mock.Mock(start=target)): + Window.native.ResizeEnd.Fire(None, None) # let go: applied once, size only + SetHeight.assert_called_once_with(Window.native, 1000) + Sizer.Resize(765, 700) + Window.resize.assert_called_once_with(765, 700) + def test_RemoveAccountsByName(self): self.Api.UpdateSetting("SelectedAccounts", ["A", "B"]) self.assertEqual(self.Api.RemoveAccounts(["a", "Zed"]), {"Removed": 1}) diff --git a/Production/RAMMIT-Stable/Tests/TestUi.mjs b/Production/RAMMIT-Stable/Tests/TestUi.mjs index bda796f..58b09b3 100644 --- a/Production/RAMMIT-Stable/Tests/TestUi.mjs +++ b/Production/RAMMIT-Stable/Tests/TestUi.mjs @@ -68,6 +68,31 @@ const Pick = async (Id, Value) => { await Page.evaluate((Id2, V) => [...document.querySelectorAll(`#${Id2} .CustomSelectOption`)].find(O => O.dataset.value === V).click(), Id, Value); await Wait(350); }; +// WCAG contrast ratio between FgSel's text colour and BgSel's background colour. A see-through text colour +// (rgba) is first blended over the background, as the screen shows it. +const Contrast = (FgSel, BgSel) => Page.evaluate((Fg, Bg) => { + const Rgba = Text => { const [R, G, B, A = 1] = Text.match(/[\d.]+/g).map(Number); return [R, G, B, A]; }; + const Lum = Colour => { + const [R, G, B] = Colour.map(V => { V /= 255; return V <= 0.03928 ? V / 12.92 : ((V + 0.055) / 1.055) ** 2.4; }); + return 0.2126 * R + 0.7152 * G + 0.0722 * B; + }; + const Back = Rgba(getComputedStyle(document.querySelector(Bg)).backgroundColor).slice(0, 3); + const [R, G, B, Alpha] = Rgba(getComputedStyle(document.querySelector(Fg)).color); + const Front = [R, G, B].map((V, I) => V * Alpha + Back[I] * (1 - Alpha)); + const A = Lum(Front), C = Lum(Back); + return (Math.max(A, C) + 0.05) / (Math.min(A, C) + 0.05); +}, FgSel, BgSel); +// An expired login's row and its @username are readable, unselected and selected, in the theme that is showing. +const ExpiredRowContrast = async () => { + const Row = '#AccountList .ListItem:nth-child(1)'; + await WaitFor(async () => !!(await Page.$(Row + '.Expired'))); + const Plain = Math.min(await Contrast(Row, Row), await Contrast(Row + ' .AcctUser', Row)); + await RowClick(0); + const Picked = Math.min(await Contrast(Row, Row), await Contrast(Row + ' .AcctUser', Row)); + await RowClick(0); // clicking the only selected row again clears it + return [Plain, Picked]; +}; +const TipText = () => Page.$eval('.Tooltip', E => E.classList.contains('Visible') ? E.textContent : '').catch(() => ''); const SetValue = async (Target, Sel, Value) => { await Target.$eval(Sel, E => { E.value = ''; E.focus(); }); await Target.type(Sel, Value); }; const Shot = async Name => { if (ShotDir) await Page.screenshot({ path: path.join(ShotDir, Name + '.png') }); }; const WaitLaunchDone = async () => { for (let I = 0; I < 60; I++) { const T = await Text('#LaunchStatus'); if (T && T.startsWith('Launched')) return T; await Wait(150); } return Text('#LaunchStatus'); }; @@ -190,6 +215,15 @@ try { St = await Hook('State'); Check('launch via saved config', Done4 === 'Launched 1/1' && St.Launches.at(-1).includes('placeId=2753915549') && St.Launches.at(-1).includes('gameId=11111111'), Done4 + ' ' + St.Launches.at(-1)); + // The real ClientTracker decides the marks: "•••" until the client's game window shows, then "✓". + await Hook('Windows', [false]); + await Page.click('#LaunchBtn'); + Check('row shows ••• while Roblox starts', await WaitFor(async () => (await Text('#AccountList .ListItem:nth-child(4) .AcctStatus.Launching')) === '•••')); + Check('status waits for the game window', (await Text('#LaunchStatus') || '').startsWith('Launching'), await Text('#LaunchStatus')); + await Hook('Windows', [true]); + const Done5 = await WaitLaunchDone(); + Check('row shows ✓ once the window is open', Done5 === 'Launched 1/1' && (await Text('#AccountList .ListItem:nth-child(4) .AcctStatus.Ok')) === '✓', Done5); + const Wiz = await Browser.newPage(); await Wiz.setViewport({ width: 400, height: 640 }); await Wiz.evaluateOnNewDocument(Shim); @@ -227,6 +261,40 @@ try { await RowClick(4); await Page.click('#RemoveAccountBtn'); Check('remove account (after confirm)', await WaitFor(async () => await Count('#AccountList .ListItem') === 4)); + + // ------------------------------------------------------------ expired logins, RENEW, tooltips + await Hook('Expire', []); // a first check saves each account's Roblox user id + await Hook('Expire', ['ObbyQueen']); + Check('expired login turns its row red', await WaitFor(async () => await Count('#AccountList .ListItem.Expired') === 1 + && !!(await Page.$('#AccountList .ListItem:nth-child(3).Expired')))); + Check('expired row text readable', await Contrast('#AccountList .ListItem:nth-child(3)', '#AccountList .ListItem:nth-child(3)') >= 4.5); + await RowClick(2); + Check('one expired account selected: RENEW / RENEW AND LAUNCH', (await Text('#AddAccountBtn')) === 'RENEW' && (await Text('#LaunchBtn')) === 'RENEW AND LAUNCH'); + const Sel = '#AccountList .ListItem:nth-child(3)'; + Check('selected expired row text readable', await Contrast(Sel, Sel) >= 4.5 && await Contrast(Sel + ' .AcctUser', Sel) >= 4.5, + String(await Contrast(Sel, Sel))); + Check('selected expired row is marked', await Page.$eval(Sel, E => getComputedStyle(E).boxShadow) !== 'none'); + await Page.hover('#AddAccountBtn'); await Wait(200); + Check('themed tooltip shows the button\'s current text', (await TipText()) === 'Sign in again as @ObbyQueen (its saved login expired)', await TipText()); + Check('native title taken over, kept as the description for screen readers', !(await Page.$eval('#AddAccountBtn', E => E.hasAttribute('title'))) + && (await Page.$eval('#AddAccountBtn', E => E.getAttribute('aria-description'))) === 'Sign in again as @ObbyQueen (its saved login expired)'); + await Page.$eval('#AddAccountBtn', E => { E.dataset.tooltip = 'Changed meanwhile'; }); await Wait(150); + Check('tooltip follows a changed text while shown', (await TipText()) === 'Changed meanwhile', await TipText()); + await Page.hover('#ReloadThemesBtn'); await Wait(200); + Check('icon-only button keeps its name for screen readers', (await Page.$eval('#ReloadThemesBtn', E => E.getAttribute('aria-label'))) === 'Reload this theme (after editing its files)'); + await Page.mouse.move(5, 5); await Wait(200); + Check('tooltip hides', (await TipText()) === ''); + // Renewed as the same Roblox user under a new name: it stays selected and RENEW AND LAUNCH goes on to launch it. + await Hook('SameUser', ['ObbyQueen2', 'ObbyQueen']); + await Hook('NextLogin', ['ObbyQueen2']); + const LaunchesBefore = (await Hook('State')).Launches.length; + await Page.$eval('#LaunchStatus', E => { E.textContent = ''; }); // so an older "Launched" line can't count + await Page.click('#LaunchBtn'); + const Done6 = await WaitLaunchDone(); + St = await Hook('State'); + Check('RENEW AND LAUNCH after a rename launches the renamed account', Done6 === 'Launched 1/1' && St.Launches.length === LaunchesBefore + 1, Done6); + Check('renamed account stays selected, no longer red', (await Text(Sel + ' .AcctUser')) === '(@ObbyQueen2)' + && !!(await Page.$(Sel + '.Selected')) && await Count('#AccountList .ListItem.Expired') === 0); Check('add while login window open is refused', !!(await CallApi('AddAccount')).Ok && !!(await CallApi('AddAccount')).Error); // ------------------------------------------------------------ themes @@ -236,6 +304,13 @@ try { Check('Light theme loads', (await Bg()) === 'rgb(228, 228, 228)' && (await Text('#ThemeSelect .CustomSelectText')) === '2016 Roblox', await Bg()); Check('Light uses its own stylesheet', await Page.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--Accent').trim()) === '#00a2ff'); await Shot('03-Light'); + await Hook('Expire', ['NovaBuilds']); + const LightExpired = await ExpiredRowContrast(); + Check('Light: expired row and @username readable', Math.min(...LightExpired) >= 4.5, LightExpired.join(' / ')); + await Promise.all([Page.waitForNavigation({ waitUntil: 'load' }), Pick('ThemeSelect', 'CBlock')]); await Wait(900); + const CBlockExpired = await ExpiredRowContrast(); + Check('CBlock: expired row and @username readable (dark text on its light red)', Math.min(...CBlockExpired) >= 4.5, CBlockExpired.join(' / ')); + await Hook('Expire', []); await Promise.all([Page.waitForNavigation({ waitUntil: 'load' }), Pick('ThemeSelect', 'MyCustomTheme')]); await Wait(900); Check('MyCustomTheme loads', (await Bg()) === 'rgb(13, 15, 26)', await Bg()); await Shot('04-MyCustomTheme'); diff --git a/Production/RAMMIT-Stable/Tests/UiHarness.py b/Production/RAMMIT-Stable/Tests/UiHarness.py index e300e58..b02d46d 100644 --- a/Production/RAMMIT-Stable/Tests/UiHarness.py +++ b/Production/RAMMIT-Stable/Tests/UiHarness.py @@ -9,7 +9,15 @@ POST /__TestApi/ body = JSON list of args -> calls Api.(*args) GET /__TestHook/Events pending Python->JS notifications POST /__TestHook/Login body = ["Username"] -> simulates a finished Roblox login + POST /__TestHook/NextLogin body = ["Username"] -> the next login window signs in as Username (RENEW) + POST /__TestHook/SameUser body = ["NewName", "OldName"] -> NewName is OldName renamed on Roblox (same user id) + POST /__TestHook/Expire body = ["Username", ...] -> Roblox now rejects those logins; runs the login check + POST /__TestHook/Windows body = [false] -> every client closes, and new ones don't show their game window + ("starting"); [true] -> they all show it GET /__TestHook/State launches so far, fake running count, last main-window resize + +The client tracking (MultiInstance.ClientTracker) is the real one: only the process and window probes are faked, over +one fake Roblox process per launch. """ import json import os @@ -41,7 +49,8 @@ import webview # noqa: E402 from App import Api as ApiModule, LocalServer as ServerModule, MultiInstance, Roblox, Themes # noqa: E402 -Fake = {"Launches": [], "Running": 0, "Channel": "production", "Events": [], "Lock": threading.Lock()} +Fake = {"Launches": [], "Running": 0, "Channel": "production", "Events": [], "Lock": threading.Lock(), + "Pids": set(), "Windows": set(), "ShowWindows": True, "Expired": set(), "Ids": {}, "NextLogin": None} FakeServers = [{"id": "11111111-1111-1111-1111-111111111111", "playing": 3, "maxPlayers": 20, "ping": 80}, {"id": "22222222-2222-2222-2222-222222222222", "playing": 15, "maxPlayers": 20, "ping": 30}, {"id": "33333333-3333-3333-3333-333333333333", "playing": 20, "maxPlayers": 20, "ping": 10}] @@ -69,7 +78,9 @@ def destroy(self): pass def get_cookies(self): - return [] + with Fake["Lock"]: + Name, Fake["NextLogin"] = Fake["NextLogin"], None + return [{".ROBLOSECURITY": types.SimpleNamespace(value="FakeCookie-" + Name)}] if Name else [] def clear_cookies(self): pass @@ -84,23 +95,45 @@ def FakePopen(Args, **_Kw): Fake["Running"] += 1 Proc = FakeProc() Proc.pid = FakeProc.pid - len(Fake["Launches"]) # one pid per launch, like real ones + with Fake["Lock"]: + Fake["Pids"].add(Proc.pid) + if Fake["ShowWindows"]: + Fake["Windows"].add(Proc.pid) return Proc +def FakeCountRunning(Tracker=None, IncludeStarting=True): + if Tracker: + Tracker.Scan(IncludeStarting) # the real tracking, over the fake processes and windows below + return Fake["Running"] + + +def FakeUserId(Name): + return Fake["Ids"].get(Name) or int.from_bytes(Name.encode(), "big") # one id per name, unless renamed + + +def FakeCheckLogin(Cookie): + Name = Cookie.split("-", 1)[1] + return ("Expired", None) if Name in Fake["Expired"] else ("Valid", (FakeUserId(Name), Name, "New " + Name)) + + webview.create_window = FakeWindow ApiModule.webview.create_window = FakeWindow ApiModule.subprocess = types.SimpleNamespace(Popen=FakePopen, CREATE_NO_WINDOW=0) MultiInstance.Enable = MultiInstance.LockCookieFile = MultiInstance.HoldMutex = MultiInstance.IsReady = lambda: True -MultiInstance.CountRunning = lambda _Tracker=None, IncludeStarting=True: Fake["Running"] -# No real clients here: every account RAMMIT launched counts as open (its row shows the running mark). -MultiInstance.ClientTracker.Accounts = lambda Self: {Info["User"]: "running" for Info in Self._Owners.values() if Info["User"]} +MultiInstance.CountRunning = FakeCountRunning +MultiInstance._PlayerPids = lambda: set(Fake["Pids"]) +MultiInstance._GameWindowPids = lambda: set(Fake["Windows"]) +MultiInstance._CommandLine = lambda _Pid: "" +MultiInstance._ParentPid = lambda _Pid: 1 +MultiInstance._CreateTime = lambda _Pid: 1.0 +MultiInstance._Alive = lambda Pid: Pid in Fake["Pids"] Roblox.GetAuthTicket = lambda _Cookie: "FAKETICKET0123" Roblox.FindLauncherPath = lambda _L: r"C:\Fake\RobloxPlayerBeta.exe" Roblox.FetchServers = lambda _P, _C=None, MaxPages=10: [dict(S) for S in FakeServers] Roblox.GetGameMaxPlayers = lambda _P: 20 Roblox.ResolveVipLink = lambda Url, _C=None: ("606849621", "AbC123") if "share" in Url or "privateServerLinkCode" in Url else (None, None) -Roblox.CheckLogin = lambda Cookie: ("Valid", (int.from_bytes(Cookie.split("-", 1)[1].encode(), "big"), # one id per name - Cookie.split("-", 1)[1], "New " + Cookie.split("-", 1)[1])) +Roblox.CheckLogin = FakeCheckLogin Roblox.GetChannel = lambda: Fake["Channel"] Roblox.SetChannel = lambda C: bool(Roblox.ChannelPattern.match(C)) and (Fake.__setitem__("Channel", C) or True) Themes.OpenThemesFolder = lambda: None @@ -116,6 +149,25 @@ def do_POST(self): elif self.path == "/__TestHook/Login": Bridge._FinishLogin("FakeCookie-" + Body[0]) Result = {"Ok": True} + elif self.path == "/__TestHook/NextLogin": + Fake["NextLogin"] = Body[0] + Result = {"Ok": True} + elif self.path == "/__TestHook/SameUser": + Fake["Ids"][Body[0]] = FakeUserId(Body[1]) + Result = {"Ok": True} + elif self.path == "/__TestHook/Expire": + Fake["Expired"] = set(Body) + Bridge._CheckLogins(Forever=False) + Result = {"Ok": True} + elif self.path == "/__TestHook/Windows": + with Fake["Lock"]: + Fake["ShowWindows"] = bool(Body[0]) + if Fake["ShowWindows"]: + Fake["Windows"] |= Fake["Pids"] + else: # every client so far closes + Fake["Pids"].clear() + Fake["Windows"].clear() + Result = {"Ok": True} else: Result = {"HarnessError": "unknown"} self._Json(Result) @@ -136,7 +188,10 @@ def _Json(self, Value): self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(Data))) self.end_headers() - self.wfile.write(Data) + try: + self.wfile.write(Data) + except (ConnectionAbortedError, BrokenPipeError): + pass # the page navigated away mid-request (theme switch): nothing to answer Bridge = None diff --git a/Production/RAMMIT-Stable/Tools/RenderTheme.py b/Production/RAMMIT-Stable/Tools/RenderTheme.py index be2fb79..2584dca 100644 --- a/Production/RAMMIT-Stable/Tools/RenderTheme.py +++ b/Production/RAMMIT-Stable/Tools/RenderTheme.py @@ -296,7 +296,10 @@ def ComposeSheet(Tools, Theme, Parts): h1 {{ margin: 18px 30px 0; font-size: 30px; font-weight: 700; }} h1 span {{ font-weight: 400; color: #a9a4bd; font-size: 22px; }} .Swatch {{ display: inline-block; width: 26px; height: 26px; vertical-align: -4px; margin-right: 12px; border-radius: 3px; - border: 1px solid #3a3548; background: conic-gradient({Swatch[2]} 0 25%, {Swatch[3]} 0 50%, {Swatch[0]} 0 75%, {Swatch[1]} 0); }} + border: 1px solid #3a3548; + background: linear-gradient({Swatch[2]}, {Swatch[2]}) right top / 50% 50% no-repeat, + linear-gradient({Swatch[3]}, {Swatch[3]}) right bottom / 50% 50% no-repeat, + linear-gradient({Swatch[0]}, {Swatch[0]}) left bottom / 50% 50% no-repeat, {Swatch[1]}; }} .Label {{ font-size: 22px; color: #a98be8; margin-bottom: 8px; }} .Column {{ display: flex; flex-direction: column; gap: 26px; }} img {{ display: block; }} diff --git a/Production/RAMMIT-Stable/requirements.txt b/Production/RAMMIT-Stable/requirements.txt index 418ca92..d2768e0 100644 --- a/Production/RAMMIT-Stable/requirements.txt +++ b/Production/RAMMIT-Stable/requirements.txt @@ -1,4 +1,4 @@ -# Versions RAMMIT 1.1.2 was built and tested with (Python 3.13.14, Windows 11). +# Versions RAMMIT 1.2.0 was built and tested with (Python 3.13.14, Windows 11). # Runtime pywebview==6.2.1 pywin32==312