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..2ab900d 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,58 @@ def __init__(self, StartScreen=""): self._LastHeight = 0 # Installer.py sets the start height 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) 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): + 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): + """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 +172,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 +181,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 "", @@ -228,8 +278,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: @@ -241,7 +293,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): @@ -304,11 +357,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} @@ -338,23 +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 - 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 23254b1..a998f4d 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 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. @@ -50,14 +51,27 @@ 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.2.0 kept that; moved over by Detect() + + 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": - return None - if not IsLegacyFolder(Folder): + """{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.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 - return {"Path": Folder, "Version": ReadVersion(Folder), "Shortcuts": FindShortcuts()} + 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): @@ -91,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): @@ -140,7 +162,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(): @@ -157,18 +179,26 @@ 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: 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() -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.RegWrite("LegacyInstallPath", IgnoredForGood) + Setup.RegDeleteValue(OldIgnoreValue) + elif Folder: + Setup.RegWrite("LegacyInstallPath", Folder) def RunRemove(Folder, Report): @@ -184,3 +214,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/Locations.py b/Production/Installer/Installer/Locations.py index b2be301..ea9777e 100644 --- a/Production/Installer/Installer/Locations.py +++ b/Production/Installer/Installer/Locations.py @@ -1,16 +1,19 @@ """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 + 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 db94be1..430f275 100644 --- a/Production/Installer/Installer/Setup.py +++ b/Production/Installer/Installer/Setup.py @@ -167,11 +167,90 @@ 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.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) +ShortcutsValue = "Shortcuts" # registry: which ones were chosen at install, e.g. "Desktop,StartMenu" or "" + + +def _ShortcutDir(Name): + L = Locations.Current + 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.2.0 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 - return [os.path.join(L.DesktopDir, "RAMMIT.lnk"), os.path.join(L.StartMenuDir, "RAMMIT.lnk")] + 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.""" + Saved = RegRead(ShortcutsValue) + return list(ShortcutNames) if Saved is None else [Name for Name in Saved.split(",") if Name in ShortcutNames] def _Shell(): @@ -190,32 +269,59 @@ def ReadShortcut(LinkPath): return "", "" -def CreateShortcuts(InstallPath): - Exe = os.path.join(InstallPath, "RAMMIT.exe") - Shell = _Shell() - for LinkPath in ShortcutPaths(): - 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}:\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: + File.write(Text) + + +def _RemoveOldLinks(InstallPath): + """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 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 @@ -488,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 = [] @@ -791,10 +902,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) @@ -859,6 +972,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) @@ -878,6 +992,8 @@ def OnBytes(Done, Total): Report(StageDetail="Writing registry", StagePct=25, OverallPct=93) RegWrite("InstallPath", InstallPath) RegWrite("Version", Version) + 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) @@ -886,16 +1002,18 @@ def OnBytes(Done, Total): Logger.warning("Apps entry failed: %s", Error) Report(StageDetail="Creating shortcuts", StagePct=60, OverallPct=96) try: - CreateShortcuts(InstallPath) + RegisterProtocol(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) @@ -957,7 +1075,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: @@ -965,6 +1083,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() @@ -984,7 +1103,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/Installer/Ui/CSS/Installer.css b/Production/Installer/Installer/Ui/CSS/Installer.css index 7a9d3e9..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. @@ -42,6 +44,7 @@ --BorderLight: #333333; --BtnEdit: #1a6b3a; --Green2: #1a6b3a; + --Legacy: #4b3f8f; /* OLD VERSION button: muted violet */ --BtnNeutral: #222222; --ScrollbarThumb: #444444; --ScrollbarThumbHover: #555555; @@ -254,6 +257,10 @@ body { background: var(--Accent); } +.BtnInst.Legacy { + background: var(--Legacy); +} + .BtnInst.Success { background: var(--Green2); } @@ -674,6 +681,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; } @@ -692,8 +705,7 @@ body { .InstCheckboxRow .CheckboxBox i { font-size: 11px; - color: var(--Accent); - /* Hide while unticked so the mark is not shown as a ghost check (#2). */ + /* 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 c6706ce..2eaf81c 100644 --- a/Production/Installer/Installer/Ui/HTML/Installer.html +++ b/Production/Installer/Installer/Ui/HTML/Installer.html @@ -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.
+
@@ -128,6 +132,19 @@ Show dev versions +
+ + +
+