167 lines
23 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#if WINDOWS
using System.Drawing;
using System.IO.Pipes;
using System.Windows.Forms;
namespace PlotDirector.Companion.Agent;
internal static class TrayApplication
{
public static int Run(string[] args)
{
var directory=Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),"PlotDirector","Companion");Directory.CreateDirectory(directory);if(File.Exists(Path.Combine(directory,"paused")))File.Delete(Path.Combine(directory,"paused"));
var endpoint=AgentEndpoint.CurrentUserPipeName();FileStream singleton;
try{singleton=new(Path.Combine(directory,"agent-"+System.Diagnostics.Process.GetCurrentProcess().SessionId+".lock"),FileMode.OpenOrCreate,FileAccess.ReadWrite,FileShare.None);}
catch(IOException){try{using var pipe=new NamedPipeClientStream(".",endpoint+".activate",PipeDirection.Out,PipeOptions.CurrentUserOnly);pipe.Connect(2000);pipe.WriteByte(1);}catch(IOException){}catch(TimeoutException){}return 0;}
using(singleton)using(var shutdown=new CancellationTokenSource())using(var cloud=new CloudGateway(settingsPath:Path.Combine(directory,"server-url.txt")))using(var ai=new ChapterAiWork(cloud)){
Application.SetHighDpiMode(HighDpiMode.PerMonitorV2);Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false);
var log=new AgentLog(directory);var sessions=new SessionManager(cloud,ai,new DocumentWorkspaceWork(cloud));var control=new TrayCoordinator(sessions,cloud,ai);
using var window=new CompanionWindow(control,cloud,shutdown,directory);var handle=window.Handle;
control.OpenRequested+=()=>{if(!window.IsDisposed)window.BeginInvoke(new Action(window.Reveal));};
var host=new PipeHost(endpoint,sessions,log.Write,control);var serve=host.RunAsync(shutdown.Token);
var reconnect=cloud.RunConnectionLoop(shutdown.Token);var work=control.Tick(shutdown.Token);var heartbeat=control.Heartbeat(shutdown.Token);
var activate=Task.Run(async()=>{while(!shutdown.IsCancellationRequested){await using var pipe=new NamedPipeServerStream(endpoint+".activate",PipeDirection.In,1,PipeTransmissionMode.Byte,PipeOptions.Asynchronous|PipeOptions.CurrentUserOnly);await pipe.WaitForConnectionAsync(shutdown.Token);var value=new byte[1];if(await pipe.ReadAsync(value,shutdown.Token)>0)window.BeginInvoke(new Action(window.Reveal));}});
log.Write("tray-start publisher=Nick-Beckley");if(args.Contains("--open"))window.Reveal();
Application.Run();shutdown.Cancel();try{Task.WhenAll(serve,work,heartbeat,activate,reconnect).Wait(TimeSpan.FromSeconds(3));}catch(AggregateException){}cloud.StopAsync().GetAwaiter().GetResult();log.Write("tray-stop");
}return 0;
}
}
internal sealed class CompanionWindow:Form
{
private readonly TrayCoordinator control;private readonly CloudGateway cloud;private readonly CancellationTokenSource shutdown;private readonly string directory;
private readonly Icon brand=Icon.ExtractAssociatedIcon(Application.ExecutablePath) ?? (Icon)SystemIcons.Application.Clone();private readonly NotifyIcon tray;private readonly System.Windows.Forms.Timer timer=new(){Interval=750};
private readonly ToolTip tips=new();private bool exiting,refreshing,advanced,choosingBook;private Guid selected,lastActive;private TrayDocument[] displayed=[];private string docsKey="",error="";
private readonly ComboBox documents=new(){DropDownStyle=ComboBoxStyle.DropDownList,Dock=DockStyle.Top,AccessibleName="Word manuscript"};
private readonly ComboBox books=new(){DropDownStyle=ComboBoxStyle.DropDownList,Dock=DockStyle.Top,DisplayMember="Title",AccessibleName="PlotDirector book",DropDownWidth=620};
private readonly Label serverStatus=Label(),wordStatus=Label(),account=Label(),bookTitle=Label(),projectTitle=Label(),guidance=Label(),notice=Label();
private readonly Button authorise=new(){Text="Sign in with your browser",AutoSize=true};private readonly CoverView cover=new(){Dock=DockStyle.Fill,MinimumSize=new(110,164)};
private Label? settingsNotice;private Label? dialogNotice;private Form? settings;private CheckBox? advancedToggle;private TextBox? site,diagnostics;private Panel? advancedPanel;
private string coverKey="";private DateTime coverRetry;private CancellationTokenSource? coverStop;private bool coverLoading;
private TrayDocument? Current=>displayed.FirstOrDefault(d=>d.Session==selected);
public CompanionWindow(TrayCoordinator control,CloudGateway cloud,CancellationTokenSource shutdown,string directory)
{
this.control=control;this.cloud=cloud;this.shutdown=shutdown;this.directory=directory;advanced=cloud.Preferences.AdvancedMode;
Text="PlotDirector Companion";Icon=brand;Font=new("Segoe UI",10);AutoScaleMode=AutoScaleMode.Dpi;MinimumSize=new(400,460);DoubleBuffered=true;
var preferences=cloud.Preferences;
var firstCompactLayout=!preferences.CompactLayoutApplied;
var workArea=Screen.FromPoint(Cursor.Position).WorkingArea.Size;
Size=new(Math.Clamp(firstCompactLayout?410:preferences.Width,400,Math.Max(400,Math.Min(1000,workArea.Width))),
Math.Clamp(firstCompactLayout?510:preferences.Height,460,Math.Max(460,Math.Min(1100,workArea.Height))));
var layout=Stack(14);layout.Dock=DockStyle.Fill;layout.AutoSize=false;layout.AutoScroll=true;Controls.Add(layout);
var header=new TableLayoutPanel{Dock=DockStyle.Top,AutoSize=true,ColumnCount=2,Margin=new(0,0,0,8)};header.ColumnStyles.Add(new(SizeType.Percent,100));header.ColumnStyles.Add(new(SizeType.AutoSize));
var name=Label("PlotDirector");name.Font=new("Segoe UI",24,FontStyle.Bold);header.Controls.Add(name,0,0);header.Controls.Add(Button("Settings",ShowSettings),1,0);
var version=Label("COMPANION · "+typeof(CompanionWindow).Assembly.GetName().Version);version.Font=new("Segoe UI",9);header.Controls.Add(version,0,1);layout.Controls.Add(header);
var connection=Card();connection.Controls.Add(Heading("YOUR CONNECTIONS"));connection.Controls.Add(serverStatus);connection.Controls.Add(account);connection.Controls.Add(wordStatus);connection.Controls.Add(authorise);layout.Controls.Add(connection);
authorise.Click+=(_,_)=>Safe(()=>cloud.Connect(cloud.Status().ServerUrl));
var manuscript=Card();manuscript.Controls.Add(Heading("CURRENT MANUSCRIPT"));manuscript.Controls.Add(documents);manuscript.Controls.Add(guidance);
var bookLayout=new TableLayoutPanel{Dock=DockStyle.Top,AutoSize=true,ColumnCount=2,Margin=new(0,6,0,4),MinimumSize=new(0,164)};bookLayout.ColumnStyles.Add(new(SizeType.Absolute,110));bookLayout.ColumnStyles.Add(new(SizeType.Percent,100));bookLayout.Controls.Add(cover,0,0);
var details=Stack(8);details.Controls.Add(Heading("PLOTDIRECTOR BOOK"));bookTitle.Font=new("Segoe UI",14,FontStyle.Bold);details.Controls.Add(bookTitle);details.Controls.Add(projectTitle);details.Controls.Add(Button("Change book…",ChangeBook));bookLayout.Controls.Add(details,1,0);
details.SizeChanged+=(_,_)=>{var titleWidth=Math.Max(1,details.ClientSize.Width-details.Padding.Horizontal-bookTitle.Margin.Horizontal);bookTitle.MaximumSize=new(titleWidth,0);projectTitle.MaximumSize=new(titleWidth,0);};
manuscript.Controls.Add(bookLayout);layout.Controls.Add(manuscript);
var open=Button("Open PlotDirector ↗",()=>cloud.OpenSite());open.Tag="primary";open.Dock=DockStyle.Top;open.MinimumSize=new(0,44);layout.Controls.Add(open);
notice.Margin=new(0,12,0,0);layout.Controls.Add(notice);
documents.SelectedIndexChanged+=(_,_)=>{if(!refreshing&&documents.SelectedItem is TrayDocument doc){selected=doc.Session;SavePreferences();RefreshState();}};
Shown+=(_,_)=>{if(firstCompactLayout)SavePreferences();};
ResizeEnd+=(_,_)=>SavePreferences();
var menu=new ContextMenuStrip();menu.Items.Add("Open Companion",null,(_,_)=>Reveal());menu.Items.Add("Open PlotDirector",null,(_,_)=>Safe(()=>cloud.OpenSite()));menu.Items.Add("Settings",null,(_,_)=>{Reveal();ShowSettings();});menu.Items.Add(new ToolStripSeparator());menu.Items.Add("Exit Companion",null,(_,_)=>Exit());
tray=new(){Icon=brand,Text="PlotDirector Companion",ContextMenuStrip=menu,Visible=true};tray.DoubleClick+=(_,_)=>Reveal();
FormClosing+=(_,e)=>{if(!exiting){e.Cancel=true;SavePreferences();settings?.Hide();Hide();}};
ApplyTheme();Microsoft.Win32.SystemEvents.UserPreferenceChanged+=OnPreferences;timer.Tick+=(_,_)=>RefreshState();timer.Start();RefreshState();
}
private static Label Label(string text="")=>new(){Text=text,AutoSize=true,Dock=DockStyle.Top,MaximumSize=new(1600,0),Margin=new(0,3,0,5)};
private static Label Heading(string text){var label=Label(text);label.Font=new("Segoe UI",9,FontStyle.Bold);label.Margin=new(0,0,0,9);return label;}
private static TableLayoutPanel Stack(int padding=0){var panel=new TableLayoutPanel{Dock=DockStyle.Top,AutoSize=true,AutoSizeMode=AutoSizeMode.GrowAndShrink,ColumnCount=1,Padding=new(padding),Margin=new(0)};panel.ColumnStyles.Add(new(SizeType.Percent,100));return panel;}
private static RoundedCard Card()=>new(){Dock=DockStyle.Top,AutoSize=true,AutoSizeMode=AutoSizeMode.GrowAndShrink,Padding=new(10),Margin=new(0,0,0,8),ColumnCount=1};
private Button Button(string text,Action action){var button=new Button{Text=text,AutoSize=true,MinimumSize=new(0,34)};button.Click+=(_,_)=>Safe(action);return button;}
private void Safe(Action action){try{error="";action();}catch(Exception e)when(e is InvalidOperationException or ArgumentException or IOException or System.ComponentModel.Win32Exception){error=e.Message;}if(dialogNotice is {IsDisposed:false})SetText(dialogNotice,error);RefreshState();}
private void SavePreferences(){var size=WindowState==FormWindowState.Normal?Size:RestoreBounds.Size;var prefs=cloud.Preferences;prefs.CompactLayoutApplied=true;prefs.Width=size.Width;prefs.Height=size.Height;prefs.AdvancedMode=advanced;prefs.LastManuscript=Current?.Manuscript??prefs.LastManuscript;cloud.SavePreferences(prefs);}
public void Reveal(){Show();WindowState=FormWindowState.Normal;Activate();}
private async void ChangeBook()
{
if(choosingBook)return;choosingBook=true;
try{
if(Current==null){error="Open a manuscript in Word before choosing a book.";return;}
var session=selected;await cloud.CheckConnection();if(IsDisposed||!Visible)return;
var current=control.PresentationDocuments.FirstOrDefault(d=>d.Session==session);if(current==null)throw new InvalidOperationException("That Word document closed while books were refreshing.");
using var dialog=new Form{Text="Choose a PlotDirector book",Icon=brand,Font=Font,AutoScaleMode=AutoScaleMode.Dpi,MinimumSize=new(440,260),Size=new(540,300),StartPosition=FormStartPosition.CenterParent};
var stack=Stack(20);dialogNotice=Label();stack.Controls.Add(Label("Associate this manuscript with a book in your account. Manuscript text is not sent or changed."));books.DataSource=cloud.Status().Books;books.SelectedItem=cloud.Status().Books.FirstOrDefault(b=>b.BookId==current.Book);stack.Controls.Add(books);
var remember=new CheckBox{Text="Also remember in Word metadata (save Word normally)",AutoSize=true,Checked=cloud.Preferences.RememberInDocument};stack.Controls.Add(remember);
stack.Controls.Add(Button("Use this book",()=>{if(books.SelectedItem is not Protocol.CompanionBook book)throw new InvalidOperationException("Sign in and choose an available book.");if(!control.Documents.Any(d=>d.Session==session))throw new InvalidOperationException("That Word document is no longer connected.");control.SelectBook(session,book.BookId,remember.Checked);var prefs=cloud.Preferences;prefs.RememberInDocument=remember.Checked;cloud.SavePreferences(prefs);dialog.Close();}));
stack.Controls.Add(dialogNotice);dialog.Controls.Add(stack);PaintTheme(dialog);dialog.ShowDialog(this);stack.Controls.Remove(books);dialogNotice=null;
}catch(Exception e)when(e is InvalidOperationException or ArgumentException or IOException or System.ComponentModel.Win32Exception){if(!IsDisposed){error=e.Message;RefreshState();}}
finally{choosingBook=false;}
}
private void ShowSettings()
{
if(settings!=null&&!settings.IsDisposed){settings.Show(this);settings.Activate();return;}
settings=new Form{Text="PlotDirector · Settings",Icon=brand,Font=Font,AutoScaleMode=AutoScaleMode.Dpi,MinimumSize=new(540,460),Size=new(800,780),StartPosition=FormStartPosition.CenterParent};
var workArea=Screen.FromControl(this).WorkingArea.Size;
settings.Size=new(Math.Min(settings.Width,workArea.Width),Math.Min(settings.Height,workArea.Height));
var root=Stack(22);root.Dock=DockStyle.Fill;root.AutoSize=false;root.AutoScroll=true;settings.Controls.Add(root);
settingsNotice=Label();root.Controls.Add(settingsNotice);root.Controls.Add(Heading("CONNECTION & ACCOUNT"));site=new(){Text=cloud.Status().ServerUrl,Dock=DockStyle.Top,AccessibleName="PlotDirector server HTTPS address"};root.Controls.Add(site);
root.Controls.Add(Label("Your approved connection reconnects automatically. Changing account requires browser approval."));
var accountActions=new FlowLayoutPanel{Dock=DockStyle.Top,AutoSize=true};accountActions.Controls.Add(Button("Change account…",()=>cloud.ChangeAccount(site.Text.Trim())));accountActions.Controls.Add(Button("Sign out",()=>{if(MessageBox.Show(settings,"Sign out and revoke this Companion’s approval? You will need browser approval to connect again.","Sign out",MessageBoxButtons.OKCancel)==DialogResult.OK)cloud.SignOut();}));root.Controls.Add(accountActions);
root.Controls.Add(Button("Use server address",()=>{if(site.Text.Trim().TrimEnd('/')!=cloud.Status().ServerUrl.TrimEnd('/'))cloud.Connect(site.Text.Trim());}));
advancedToggle=new(){Text="Advanced mode · troubleshooting and document maintenance",AutoSize=true,Checked=advanced,Dock=DockStyle.Top,Margin=new(0,16,0,10)};
root.Controls.Add(advancedToggle);advancedPanel=Stack();advancedPanel.Visible=advanced;root.Controls.Add(advancedPanel);
advancedPanel.Controls.Add(Heading("TROUBLESHOOTING"));diagnostics=new(){Multiline=true,ReadOnly=true,Dock=DockStyle.Top,Height=160,ScrollBars=ScrollBars.Vertical,AccessibleName="Connection and document diagnostics"};advancedPanel.Controls.Add(diagnostics);
var checks=new FlowLayoutPanel{Dock=DockStyle.Top,AutoSize=true};checks.Controls.Add(Button("Check connection",()=>_ = cloud.ReconnectAsync()));checks.Controls.Add(Button("Check Word registration",()=>{if(Current==null)throw new InvalidOperationException("Open and select a Word document first.");control.RefreshPresence(selected);}));checks.Controls.Add(Button("Open logs folder",()=>System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(directory){UseShellExecute=true})));advancedPanel.Controls.Add(checks);
advancedPanel.Controls.Add(Heading("SELECTED WORD DOCUMENT"));advancedPanel.Controls.Add(Label("Maintenance touches only PlotDirector-owned markers and association properties. Word is never saved automatically. If interrupted, inspect again before retrying."));
var maintenanceActions=new FlowLayoutPanel{Dock=DockStyle.Top,AutoSize=true};
foreach(var entry in new[]{("Inspect hidden identifiers","inspect"),("Remove PlotDirector markers…","markers"),("Reset document association…","reset"),("Clean and unlink…","clean")}){var kind=entry.Item2;maintenanceActions.Controls.Add(Button(entry.Item1,()=>Maintenance(kind)));}
advancedPanel.Controls.Add(maintenanceActions);
advancedToggle.CheckedChanged+=(_,_)=>{advanced=advancedToggle.Checked;advancedPanel.Visible=advanced;SavePreferences();};
root.Controls.Add(Button("Help",()=>cloud.OpenSite("help")));settings.FormClosing+=(_,_)=>SavePreferences();PaintTheme(settings);RefreshState();settings.Show(this);
}
private void Maintenance(string kind)
{
var doc=Current??throw new InvalidOperationException("Select a connected Word document in the Companion first.");
if(!control.CanMaintain(doc.Session))throw new InvalidOperationException("This Word add-in does not support maintenance. Install the matching updated version first.");
if(kind!="inspect"&&MessageBox.Show(settings??this,$"{(kind=="markers"?"Remove PlotDirector markers from":kind=="reset"?"Reset the PlotDirector association of":"Clean and unlink")} “{doc.Title}”?\n\nOnly PlotDirector-owned metadata will be removed. Manuscript words and formatting are retained. This cannot be undone through the Companion; keep a saved copy first. Word will not be saved automatically.","Confirm document maintenance",MessageBoxButtons.OKCancel,MessageBoxIcon.Warning)!=DialogResult.OK)return;
control.Maintain(doc.Session,kind);
}
private void RefreshState()
{
var state=cloud.Status();displayed=control.PresentationDocuments;refreshing=true;
try{
var active=displayed.FirstOrDefault(d=>d.Active)?.Session??Guid.Empty;if(active!=Guid.Empty&&active!=lastActive)selected=active;lastActive=active;
var key=string.Join("|",displayed.Select(d=>d.Session+":"+d.Title+":"+d.Active));if(key!=docsKey){docsKey=key;if(!displayed.Any(d=>d.Session==selected))selected=displayed.FirstOrDefault(d=>d.Active)?.Session??displayed.FirstOrDefault(d=>d.Manuscript==cloud.Preferences.LastManuscript)?.Session??displayed.FirstOrDefault()?.Session??Guid.Empty;documents.DataSource=displayed;documents.SelectedItem=Current;}
var doc=Current;var book=state.Books.FirstOrDefault(b=>b.BookId==doc?.Book);
SetText(serverStatus,"PlotDirector · "+CompanionPresentation.Connection(state.Health,DateTime.UtcNow));SetText(account,state.Health?.AccountName??"Not signed in");
SetText(wordStatus,CompanionPresentation.WordStatus(doc!=null,doc?.Book??0,doc?.LastPresenceUtc??DateTime.MinValue,doc?.LastPresenceKey??"",DateTime.UtcNow));
authorise.Visible=CompanionPresentation.NeedsAuthorisation(state.Health);authorise.Enabled=!string.IsNullOrWhiteSpace(state.ServerUrl);
SetText(guidance,doc==null?"Open a manuscript in Microsoft Word. Your words stay in Word until you request an import in PlotDirector.":doc.Book==0?"Choose the PlotDirector book for this manuscript.":control.ChapterProgressForDisplay(doc.Session) is {} chapters?(chapters.State=="Synchronised"?"Up to date":chapters.Message):"Import, Context and Intent are available in PlotDirector.");
SetText(bookTitle,book==null?"No book associated":string.IsNullOrEmpty(book.BookTitle)?book.Title:book.BookTitle);SetText(projectTitle,book?.ProjectTitle??"Choose a book to connect your writing workspace.");
var noticeText=error!=""?error:doc?.AssociationNotice??"";SetText(notice,noticeText);if(settingsNotice is {IsDisposed:false}){SetText(settingsNotice,error);settingsNotice.Visible=error!="";}notice.Visible=noticeText!="";tips.SetToolTip(serverStatus,state.Health?.Explanation??"Connect in Settings.");
var text=$"Server: {state.ServerUrl}\r\nAccount: {state.Health?.AccountName}\r\n{state.Health?.Explanation}\r\n"+string.Join("\r\n",displayed.Select(d=>$"{d.Title} · session {d.Session} · book {d.Book}"))+"\r\n"+doc?.WordDiagnostics+"\r\n"+doc?.Status+"\r\n"+doc?.MaintenanceReport+"\r\n"+(doc==null?"":control.ChapterDiagnostics(doc.Session));
if(diagnostics is {IsDisposed:false}&&diagnostics.Text!=text)diagnostics.Text=text;
if(books.Parent!=null&&!books.IsDisposed){var signature=state.AuthenticationContext+":"+string.Join("|",state.Books.Select(b=>b.BookId+":"+b.Title));if(books.Tag as string!=signature){var chosen=(books.SelectedItem as Protocol.CompanionBook)?.BookId;books.Tag=signature;books.DataSource=state.Books;books.SelectedItem=state.Books.FirstOrDefault(b=>b.BookId==chosen);}}
var next=state.AuthenticationContext+":"+(book?.BookId??0);if(next!=coverKey){coverKey=next;coverRetry=DateTime.MinValue;coverStop?.Cancel();cover.SetImage(null);cover.Caption=bookTitle.Text;cover.Invalidate();coverLoading=false;}
if(book!=null&&!coverLoading&&DateTime.UtcNow>=coverRetry&&state.Health?.State=="Connected")_ = LoadCover(book.BookId,state.AuthenticationContext,next);
var trayText="PlotDirector · "+(state.Health?.State??"Disconnected");if(tray.Text!=trayText)tray.Text=trayText.Length>63?trayText[..63]:trayText;
}finally{refreshing=false;}
}
private async Task LoadCover(int book,Guid context,string key)
{
coverLoading=true;coverRetry=DateTime.UtcNow.AddMinutes(5);var stop=new CancellationTokenSource();coverStop=stop;
try{var reply=await cloud.Get<Protocol.BookCoverReply>($"api/native-companion/books/{book}/cover",context,stop.Token);if(stop.IsCancellationRequested||IsDisposed||key!=coverKey)return;
Image? image=null;if(reply.Png!=""){using var stream=new MemoryStream(Convert.FromBase64String(reply.Png));using var decoded=Image.FromStream(stream);if(decoded.Width>600||decoded.Height>900)throw new InvalidDataException("Cover dimensions exceeded.");image=new Bitmap(decoded);}cover.SetImage(image);coverRetry=DateTime.MaxValue;
}catch(Exception e)when(e is HttpRequestException or IOException or InvalidOperationException or OperationCanceledException or System.Text.Json.JsonException or ArgumentException or FormatException){/* Cover absence/failure never interrupts authoring or changes account trust. */}
finally{if(key==coverKey)coverLoading=false;stop.Dispose();if(ReferenceEquals(coverStop,stop))coverStop=null;}
}
private static void SetText(Label label,string text){if(label.Text!=text)label.Text=text;}
private void OnPreferences(object sender,Microsoft.Win32.UserPreferenceChangedEventArgs e){if(IsHandleCreated&&!IsDisposed)BeginInvoke(new Action(ApplyTheme));}
private void ApplyTheme(){PaintTheme(this);if(settings is {IsDisposed:false})PaintTheme(settings);}
private void PaintTheme(Control root)
{
bool? dark=null;try{using var key=Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize");if(key?.GetValue("AppsUseLightTheme") is int value)dark=value==0;}catch(System.Security.SecurityException){}
var night=CompanionPresentation.Dark(dark);var background=night?Color.FromArgb(27,25,31):Color.FromArgb(246,243,238);var surface=night?Color.FromArgb(42,38,46):Color.FromArgb(255,253,250);var ink=night?Color.FromArgb(240,233,225):Color.FromArgb(49,40,51);var accent=night?Color.FromArgb(207,178,204):Color.FromArgb(100,60,96);
void Paint(Control item,bool card=false){card|=item is RoundedCard;item.BackColor=card?surface:background;item.ForeColor=ink;if(item is RoundedCard rounded)rounded.Outside=background;
if(item is Button button){button.FlatStyle=FlatStyle.Flat;button.FlatAppearance.BorderSize=0;button.Padding=new(10,5,10,5);button.Margin=new(0,4,8,4);button.BackColor=button.Tag as string=="primary"?accent:surface;button.ForeColor=button.Tag as string=="primary"?(night?background:Color.White):ink;}
if(item is TextBox or ComboBox)item.BackColor=surface;foreach(Control child in item.Controls)Paint(child,card);item.Invalidate();}
Paint(root);
}
private void Exit(){SavePreferences();exiting=true;File.WriteAllText(Path.Combine(directory,"paused"),"User exited Companion");shutdown.Cancel();tray.Visible=false;Application.Exit();}
protected override void Dispose(bool disposing){if(disposing){Microsoft.Win32.SystemEvents.UserPreferenceChanged-=OnPreferences;coverStop?.Cancel();timer.Dispose();settings?.Dispose();tips.Dispose();tray.Dispose();brand.Dispose();}base.Dispose(disposing);}
}
#endif