151 lines
13 KiB
C#

using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Management;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
[assembly: AssemblyTitle("PlotDirector Companion Setup")]
[assembly: AssemblyCompany("Nick Beckley")]
[assembly: AssemblyProduct("PlotDirector Companion")]
internal static class Setup
{
private const string Version = SetupRelease.Version;
private const string AddinKey = @"Software\Microsoft\Office\Word\Addins\PlotDirector.WordAddIn";
private static string log;
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)] private static extern int GetCurrentPackageFullName(ref int length, StringBuilder name);
[DllImport("msi.dll", CharSet = CharSet.Unicode)] private static extern uint MsiInstallProduct(string package, string properties);
[DllImport("msi.dll")] private static extern uint MsiSetInternalUI(uint level, IntPtr parent);
[DllImport("msi.dll", CharSet = CharSet.Unicode)] private static extern int MsiQueryProductState(string product);
[DllImport("msi.dll", CharSet = CharSet.Unicode)] private static extern uint MsiEnableLog(uint mode, string path, uint attributes);
[STAThread] private static int Main(string[] args)
{
Application.EnableVisualStyles();
try
{
// A packaged caller's HKCU/LocalAppData writes are invisible to normal Word.
// WMI launches the same installer as the same user outside that package view.
int length = 0;
if (GetCurrentPackageFullName(ref length, null) != 15700)
{
using (var process = new ManagementClass("Win32_Process"))
using (var input = process.GetMethodParameters("Create"))
using (var startup = new ManagementClass("Win32_ProcessStartup").CreateInstance())
{
startup["ShowWindow"] = (ushort)0;
input["CommandLine"] = "\"" + Assembly.GetExecutingAssembly().Location + "\" --install";
input["ProcessStartupInformation"] = startup;
using (var result = process.InvokeMethod("Create", input, null))
if ((uint)result["ReturnValue"] != 0) throw new InvalidOperationException("Cannot start setup in normal Windows. Run this EXE from File Explorer.");
}
return 0;
}
var state = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "PlotDirector", "InstallerBackup", DateTime.Now.ToString("yyyyMMdd-HHmmss"));
Directory.CreateDirectory(state); log = Path.Combine(state, "setup.log");
Write("PlotDirector Companion " + Version + "; normal Windows user=" + Environment.UserName);
if (Process.GetProcessesByName("WINWORD").Length != 0) throw new InvalidOperationException("Save your work and close Word normally, then run setup again. Word was not terminated.");
CheckPrerequisites();
CompanionInstallerInventory.RequireCurrentUser(CompanionInstallerInventory.Family(SetupRelease.UpgradeCode), SetupRelease.MsiVersion);
if (!args.Contains("--install") && MessageBox.Show("Install PlotDirector Companion " + Version + " for your Windows account?\n\nIncludes the Word add-in, tray application, Start menu shortcut and launch at Windows sign-in. No manuscripts or application data will be removed.", "PlotDirector Companion Setup", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) != DialogResult.OK) return 2;
StopOwnAgent();
BackupRegistration(state);
RemoveOldDeployment(state);
var cache = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "PlotDirector", "Setup", Version);
Directory.CreateDirectory(cache);
var msi = Path.Combine(cache, "PlotDirectorCompanion.msi");
using (var source = Assembly.GetExecutingAssembly().GetManifestResourceStream("Companion.msi"))
using (var file = File.Create(msi)) source.CopyTo(file);
MsiSetInternalUI(3, IntPtr.Zero);
MsiEnableLog(0x1fff, Path.Combine(state, "windows-installer.log"), 0);
var properties = "ALLUSERS=\"\" MSIINSTALLPERUSER=1 REBOOT=ReallySuppress REINSTALLMODE=vamus";
if (MsiQueryProductState(SetupRelease.ProductCode) == 5) properties += " REINSTALL=ALL";
uint code = MsiInstallProduct(msi, properties);
Write("Windows Installer result=" + code);
if (code != 0 && code != 3010) throw new InvalidOperationException("Windows Installer failed with code " + code + ". See " + log);
var installed = CompanionInstallerInventory.Product(SetupRelease.ProductCode);
CompanionInstallerInventory.RequireCurrentUser(installed, SetupRelease.MsiVersion);
if (installed.Length != 1 || installed[0].Version != SetupRelease.MsiVersion) throw new InvalidOperationException("Installed MSI identity/version does not match this user's package. Stop and retain the setup log.");
Write("Verified MSI context=2 and current-user SID; product=" + SetupRelease.ProductCode);
var home = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs", "PlotDirector Companion");
var manifest = Path.Combine(home, "PlotDirector.WordAddIn.vsto");
var agent = Path.Combine(home, "Agent", "PlotDirector.Companion.Agent.exe");
if (FileVersionInfo.GetVersionInfo(Path.Combine(home, "PlotDirector.WordAddIn.dll")).FileVersion != Version || FileVersionInfo.GetVersionInfo(agent).FileVersion != Version) throw new InvalidDataException("Installed component version mismatch.");
// The supported VSTO installer performs signature/trust validation. No inclusion
// list, certificate store, policy or Office resiliency setting is changed here.
int trust = Run(VstoInstaller(), "/Install \"" + manifest + "\"", false);
Write("VSTO installer result=" + trust);
if (trust != 0) throw new InvalidOperationException("VSTO installation/trust failed with exit code " + trust + ". Both components are staged; rerun setup after resolving this specific error. No system repair was attempted.");
using (var key = Registry.CurrentUser.OpenSubKey(AddinKey, true))
{
key.SetValue("Manifest", new Uri(manifest).AbsoluteUri + "|vstolocal"); key.SetValue("LoadBehavior", 3, RegistryValueKind.DWord);
}
var settings = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "PlotDirector", "Companion");
Directory.CreateDirectory(settings);
// Only migrate an existing server preference, never credentials or diagnostic logs.
var oldSettings = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Packages", "OpenAI.Codex_2p2nqsd0c76g0", "LocalCache", "Local", "PlotDirector", "Companion", "server-url.txt");
if (!File.Exists(Path.Combine(settings, "server-url.txt")) && File.Exists(oldSettings)) File.Copy(oldSettings, Path.Combine(settings, "server-url.txt"));
Process.Start(new ProcessStartInfo(agent, "--open") { UseShellExecute = true });
Write("Installed both components; Word restart verification still required.");
MessageBox.Show("PlotDirector Companion " + Version + " is installed.\n\nOpen Word and choose PlotDirector > Open Companion.\nThe tray app also starts at Windows sign-in.\n\nUninstall using Windows Settings > Apps > PlotDirector Companion. Your application state and documents are retained.", "PlotDirector Companion Setup", MessageBoxButtons.OK, MessageBoxIcon.Information);
return 0;
}
catch (Exception ex) { if (log != null) Write(ex.ToString()); MessageBox.Show(ex.Message, "PlotDirector Companion Setup — stopped", MessageBoxButtons.OK, MessageBoxIcon.Error); return 1; }
}
private static void CheckPrerequisites()
{
if (!Environment.Is64BitOperatingSystem) throw new InvalidOperationException("This package requires 64-bit Windows. No prerequisites were installed.");
using (var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full"))
if (key == null || Convert.ToInt32(key.GetValue("Release", 0)) < 528040) throw new InvalidOperationException(".NET Framework 4.8 is required. No installation or repair was attempted.");
var desktop = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "dotnet", "shared", "Microsoft.WindowsDesktop.App");
if (!Directory.Exists(desktop) || !Directory.GetDirectories(desktop, "10.*").Any()) throw new InvalidOperationException("The existing .NET 10 Windows Desktop x64 runtime is required. No runtime was installed.");
if (!File.Exists(VstoInstaller())) throw new InvalidOperationException("The VSTO Runtime is required. No Office or runtime repair was attempted.");
}
private static string VstoInstaller() { return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles), @"Microsoft Shared\VSTO\10.0\VSTOInstaller.exe"); }
private static int Run(string exe, string arguments, bool hidden)
{ using (var p = Process.Start(new ProcessStartInfo(exe, arguments) { UseShellExecute = false, CreateNoWindow = hidden, WindowStyle = hidden ? ProcessWindowStyle.Hidden : ProcessWindowStyle.Normal })) { p.WaitForExit(); return p.ExitCode; } }
private static void Write(string message) { File.AppendAllText(log, DateTime.UtcNow.ToString("o") + " " + message + Environment.NewLine); }
private static void StopOwnAgent()
{
foreach (var p in Process.GetProcessesByName("PlotDirector.Companion.Agent")) using (p)
{
if (p.SessionId != Process.GetCurrentProcess().SessionId) continue;
var path = p.MainModule.FileName;
var local = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + Path.DirectorySeparatorChar;
if (!path.StartsWith(local, StringComparison.OrdinalIgnoreCase)) throw new InvalidOperationException("A Companion agent is running from another location. Exit it using its tray menu and rerun setup.");
Write("Stopping this session's Companion for upgrade: " + path); p.Kill(); if (!p.WaitForExit(5000)) throw new InvalidOperationException("Companion did not stop.");
}
}
private static void BackupRegistration(string state)
{
using (var key = Registry.CurrentUser.OpenSubKey(AddinKey))
if (key != null) Run(Path.Combine(Environment.SystemDirectory, "reg.exe"), "export \"HKCU\\" + AddinKey + "\" \"" + Path.Combine(state, "word-registration.reg") + "\" /y", true);
}
private static void RemoveOldDeployment(string state)
{
const string root = @"Software\Microsoft\VSTA\Solutions";
using (var solutions = Registry.CurrentUser.OpenSubKey(root, true))
{
if (solutions == null) return;
foreach (var name in solutions.GetSubKeyNames())
{
string url, product, subscription;
using (var key = solutions.OpenSubKey(name)) { url = key.GetValue("Url") as string; product = key.GetValue("ProductName") as string; subscription = key.GetValue("SubscriptionID") as string; }
if (product != "PlotDirector.WordAddIn" || subscription == null || !subscription.StartsWith("PlotDirector.WordAddIn.vsto,", StringComparison.Ordinal)) continue;
Uri uri; if (!Uri.TryCreate(url, UriKind.Absolute, out uri) || !uri.IsFile || Path.GetFileName(uri.LocalPath) != "PlotDirector.WordAddIn.vsto") throw new InvalidOperationException("Unexpected prior Companion deployment. No other deployment was changed.");
var backup = Path.Combine(state, "vsta-" + name + ".reg");
if (Run(Path.Combine(Environment.SystemDirectory, "reg.exe"), "export \"HKCU\\" + root + "\\" + name + "\" \"" + backup + "\" /y", true) != 0) throw new IOException("Cannot back up previous Companion deployment.");
int result = Run(VstoInstaller(), "/Uninstall \"" + url + "\" /Silent", true); Write("Previous exact Companion uninstall=" + result);
// -401 means no cached deployment exists. Retain exported metadata and
// remove only that orphan, which otherwise triggers ERROR_SXS_ASSEMBLY_NOT_FOUND.
if (result == -401) solutions.DeleteSubKeyTree(name, false);
else if (result != 0) throw new InvalidOperationException("Previous Companion uninstall failed: " + result + ". Backup retained; unrelated ClickOnce applications were not changed.");
}
}
}
}