Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Production/Installer/Installer/HeightMap.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
"Loading": 327,
"Loading": 323,
"ConfirmUninstall": 393
}
118 changes: 101 additions & 17 deletions Production/Installer/Installer/InstallerApi.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
window.InstallerEvents.<Event>(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
Expand All @@ -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")
Expand All @@ -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.<Event>(Payload). Payload is JSON-encoded, never spliced raw."""
Expand Down Expand Up @@ -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 {
Expand All @@ -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 "",
Expand Down Expand Up @@ -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:
Expand All @@ -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):
Expand Down Expand Up @@ -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}
Expand Down Expand Up @@ -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
Expand Down
82 changes: 67 additions & 15 deletions Production/Installer/Installer/Legacy.py
Original file line number Diff line number Diff line change
Expand Up @@ -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=<folder>, 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.
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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():
Expand All @@ -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):
Expand All @@ -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}
Loading