97 lines
16 KiB
C#

#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);
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 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).Wait(TimeSpan.FromSeconds(3));}catch(AggregateException){}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 NotifyIcon tray;private readonly Icon brand=CreateBrandIcon();private readonly Dictionary<Guid,HashSet<int>> selections=[];private readonly Dictionary<Guid,long> selectionRevisions=[];private Guid renderedSession;private readonly System.Windows.Forms.Timer timer=new(){Interval=500};private bool exiting,refreshing;
private readonly ComboBox documents=new(){DropDownStyle=ComboBoxStyle.DropDownList,Dock=DockStyle.Fill,DisplayMember="Title"};
private readonly ComboBox books=new(){DropDownStyle=ComboBoxStyle.DropDownList,Dock=DockStyle.Fill,DisplayMember="Title",DropDownWidth=650};
private readonly TextBox site=new(){Dock=DockStyle.Fill,PlaceholderText="https://your-plotdirector-site/"};
private readonly Label status=new(){Dock=DockStyle.Fill,AutoSize=true};private readonly Label progressText=new(){AutoSize=true,Dock=DockStyle.Fill};
private readonly ProgressBar progress=new(){Dock=DockStyle.Fill,Maximum=100,Height=5};
private readonly CheckedListBox chapters=new(){Dock=DockStyle.Fill,CheckOnClick=true,HorizontalScrollbar=true};
private readonly TextBox diagnostics=new(){Multiline=true,ReadOnly=true,Dock=DockStyle.Fill,ScrollBars=ScrollBars.Vertical};
private readonly Button detect=new(){Text="Detect Chapters",AutoSize=true},analyse=new(){Text="Analyse selected chapters",AutoSize=true},cancel=new(){Text="Cancel",AutoSize=true},bookButton=new(){Text="Use selected book",AutoSize=true},review=new(){Text="Review in PlotDirector",AutoSize=true};
private readonly CheckBox remember=new(){Text="Remember in document metadata (save Word normally)",AutoSize=true};
private string documentKey="",bookKey="",chapterKey="";private int displayedBook=-1;private Guid displayedSession;private Guid selected;private string error="";
private TrayDocument? Current=>control.Documents.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;
Icon=brand;Text="PlotDirector Companion";Font=new("Segoe UI",10);BackColor=Color.FromArgb(249,246,240);ForeColor=Color.FromArgb(58,49,44);AutoScaleMode=AutoScaleMode.Dpi;MinimumSize=new(640,550);Size=new(850,720);
var layout=new TableLayoutPanel{Dock=DockStyle.Fill,Padding=new(18),ColumnCount=1,RowCount=9};layout.ColumnStyles.Add(new(SizeType.Percent,100));for(int i=0;i<9;i++)layout.RowStyles.Add(new(i==7?SizeType.Percent:SizeType.AutoSize,i==7?100:0));
layout.Controls.Add(new Label{Text="PlotDirector · Word at your side",Font=new(Font,FontStyle.Bold),AutoSize=true},0,0);
var connection=new TableLayoutPanel{Dock=DockStyle.Fill,AutoSize=true,ColumnCount=2};connection.ColumnStyles.Add(new(SizeType.Percent,100));connection.ColumnStyles.Add(new(SizeType.AutoSize));var signIn=Button("Connect / Sign In",()=>cloud.Connect(site.Text.Trim()));connection.Controls.Add(site,0,0);connection.Controls.Add(signIn,1,0);layout.Controls.Add(connection,0,1);
layout.Controls.Add(status,0,2);layout.Controls.Add(documents,0,3);
var association=new TableLayoutPanel{Dock=DockStyle.Fill,AutoSize=true,ColumnCount=2};association.ColumnStyles.Add(new(SizeType.Percent,100));association.ColumnStyles.Add(new(SizeType.AutoSize));association.Controls.Add(books,0,0);association.Controls.Add(bookButton,1,0);association.Controls.Add(remember,0,1);association.SetColumnSpan(remember,2);layout.Controls.Add(association,0,4);
var actions=new FlowLayoutPanel{AutoSize=true,Dock=DockStyle.Fill,WrapContents=true};actions.Controls.AddRange([detect,analyse,cancel,review,Button("Use active Word document",()=>{var active=control.Documents.FirstOrDefault(d=>d.Active);if(active!=null){selected=active.Session;documents.SelectedItem=active;chapterKey="";}}),Button("Select all",()=>{for(var i=0;i<chapters.Items.Count;i++)chapters.SetItemChecked(i,true);}),Button("Clear selection",()=>{for(var i=0;i<chapters.Items.Count;i++)chapters.SetItemChecked(i,false);}),Button("Context",()=>Open("context")),Button("Intent",()=>Open("intent"))]);layout.Controls.Add(actions,0,5);
var p=new TableLayoutPanel{Dock=DockStyle.Fill,AutoSize=true,RowCount=2};p.Controls.Add(progressText);p.Controls.Add(progress);layout.Controls.Add(p,0,6);
var tabs=new TabControl{Dock=DockStyle.Fill};var chapterTab=new TabPage("Heading 1 chapters");chapterTab.Controls.Add(chapters);var settings=new TabPage("Settings and diagnostics");settings.Controls.Add(diagnostics);var options=new FlowLayoutPanel{Dock=DockStyle.Bottom,AutoSize=true};options.Controls.AddRange([Button("Check connection",()=>_ = cloud.CheckConnection()),Button("Disconnect / forget sign-in",()=>cloud.SignOut()),Button("Open diagnostics folder",()=>System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(directory){UseShellExecute=true}))]);settings.Controls.Add(options);tabs.TabPages.AddRange([chapterTab,settings]);layout.Controls.Add(tabs,0,7);
layout.Controls.Add(new Label{AutoSize=true,Text="Chapter prose is sent only after confirmation. Manuscript text and saved story data are never overwritten."},0,8);Controls.Add(layout);
documents.SelectedIndexChanged+=(_,_)=>{if(!refreshing&&documents.SelectedItem is TrayDocument d){selected=d.Session;chapterKey="";RefreshState();}};
chapters.DoubleClick+=(_,_)=>{if(chapters.SelectedItem is ChapterItem chapter)Safe(()=>control.Navigate(selected,chapter.Start));};
chapters.ItemCheck+=(_,e)=>{if(refreshing||renderedSession==Guid.Empty)return;if(!selections.TryGetValue(renderedSession,out var chosen)){if(selections.Count>=64)selections.Clear();selections[renderedSession]=chosen=[];}var start=((ChapterItem)chapters.Items[e.Index]).Start;if(e.NewValue==CheckState.Checked)chosen.Add(start);else chosen.Remove(start);};
detect.Click+=(_,_)=>Safe(()=>control.Detect(selected));cancel.Click+=(_,_)=>Safe(()=>control.Cancel(selected));
bookButton.Click+=(_,_)=>Safe(()=>{if(books.SelectedItem is not Protocol.CompanionBook book)return;if(remember.Checked&&MessageBox.Show("Remember this book in Word document metadata? This marks the document modified. It does not save or change prose.","Remember association",MessageBoxButtons.OKCancel)!=DialogResult.OK)return;control.SelectBook(selected,book.BookId,remember.Checked);});
analyse.Click+=(_,_)=>Safe(()=>{var chosen=chapters.CheckedItems.Cast<ChapterItem>().ToArray();if(chosen.Length==0)throw new InvalidOperationException("Select one or more chapters first.");var d=Current??throw new InvalidOperationException("Open a Word document.");if(MessageBox.Show($"Send {chosen.Length} selected chapters for the chosen book to PlotDirector AI? This uploads manuscript prose, retains an encrypted capture for your reviewed import, and may incur AI costs. Existing Word text and saved story records will not change.","Confirm chapter analysis",MessageBoxButtons.OKCancel)==DialogResult.OK)control.Analyse(d.Session,chosen.Select(c=>c.Start));});
review.Click+=(_,_)=>Safe(()=>Open("review"));
var menu=new ContextMenuStrip();menu.Items.Add("Open Companion",null,(_,_)=>Reveal());menu.Items.Add("Connect / Sign In",null,(_,_)=>{Reveal();site.Focus();});menu.Items.Add("Select Book",null,(_,_)=>{Reveal();books.Focus();});
var detectMenu=menu.Items.Add("Detect Chapters",null,(_,_)=>Safe(()=>control.Detect(selected)));var analyseMenu=menu.Items.Add("Analyse Manuscript",null,(_,_)=>{Reveal();chapters.Focus();});var openMenu=menu.Items.Add("Open PlotDirector",null,(_,_)=>Safe(()=>Open("book")));menu.Items.Add("Connection Status",null,(_,_)=>Reveal());menu.Items.Add("Settings",null,(_,_)=>{Reveal();tabs.SelectedIndex=1;});menu.Items.Add("Exit",null,(_,_)=>Exit());
menu.Opening+=(_,_)=>{detectMenu.Enabled=Current!=null;analyseMenu.Enabled=Current?.Book>0;openMenu.Enabled=!string.IsNullOrWhiteSpace(cloud.Status().ServerUrl);};
tray=new(){Icon=brand,Text="PlotDirector Companion",ContextMenuStrip=menu,Visible=true};tray.DoubleClick+=(_,_)=>Reveal();FormClosing+=(_,e)=>{if(!exiting){e.Cancel=true;Hide();}};timer.Tick+=(_,_)=>RefreshState();timer.Start();RefreshState();
}
private Button Button(string text,Action action){var button=new Button{Text=text,AutoSize=true};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;}RefreshState();}
private void Open(string page){if(Current==null)cloud.OpenSite(page);else control.OpenPage(selected,page);}
public void Reveal(){Show();WindowState=FormWindowState.Normal;Activate();}
private void RefreshState()
{
var state=cloud.Status();var docs=control.Documents;var key=string.Join("|",docs.Select(d=>d.Session+":"+d.Title));refreshing=true;
try{if(key!=documentKey){documentKey=key;documents.DataSource=docs;if(!docs.Any(d=>d.Session==selected))selected=docs.FirstOrDefault(d=>d.Active)?.Session??docs.FirstOrDefault()?.Session??Guid.Empty;documents.SelectedItem=docs.FirstOrDefault(d=>d.Session==selected);}
var bkey=state.AuthenticationContext+string.Join("|",state.Books.Select(b=>b.BookId+":"+b.Title));if(bookKey!=bkey){bookKey=bkey;books.DataSource=state.Books;books.SelectedIndex=-1;displayedBook=-1;}
var d=Current;if(displayedSession!=selected||displayedBook!=(d?.Book??0)){displayedSession=selected;displayedBook=d?.Book??0;books.SelectedItem=state.Books.FirstOrDefault(b=>b.BookId==d?.Book);}
if(string.IsNullOrWhiteSpace(site.Text)&&!string.IsNullOrEmpty(state.ServerUrl))site.Text=state.ServerUrl;
var server=state.Health==null?"unknown":DateTime.UtcNow-state.Health.VerifiedUtc>TimeSpan.FromSeconds(90)&&state.Health.Server=="online"?"unverified (check connection)":state.Health.Server;
status.Text="Active in Word: "+(docs.FirstOrDefault(item=>item.Active)?.Title??"no document")+" · Working document: "+(d?.Title??"none")+"\r\nWord: "+(d==null?"unavailable":"connected")+" · Server: "+server+" · Authentication: "+(server.StartsWith("unverified")&&state.Health?.Authentication=="verified"?"cached grant":state.Health?.Authentication??"signed-out")+"\r\n"+state.Status+" · AI: "+(state.Health?.Ai??"unknown")+"\r\nBook: "+(state.Books.FirstOrDefault(b=>b.BookId==d?.Book)?.Title??"not selected")+"\r\nLocation: "+(d==null?"No document":string.Join(" / ",new[]{d.ChapterTitle,d.SceneTitle}.Where(t=>t.Length>0)))+" · Snapshot words (approx.): "+(d?.Words?.ToString("N0")??"not read / stale");
progressText.Text=string.IsNullOrEmpty(error)?d?.Status??"Open Word or sign in independently.":error;progress.Value=Math.Clamp(d?.Progress??0,0,100);
detect.Enabled=d!=null&&d.Job==Guid.Empty;analyse.Enabled=d!=null&&d.Book>0&&d.Chapters.Length>0&&d.Job==Guid.Empty&&d.Pending.Count==0;cancel.Enabled=d!=null;bookButton.Enabled=d!=null&&state.Books.Length>0&&d.Job==Guid.Empty;review.Enabled=d?.Book>0;
var ckey=d==null?"":d.Session+":"+d.Revision+string.Join("|",d.Chapters.Select(c=>c.Start+":"+c.End+":"+c.Title));if(chapterKey!=ckey){chapterKey=ckey;chapters.BeginUpdate();try{chapters.Items.Clear();renderedSession=d?.Session??Guid.Empty;if(d!=null){if(selectionRevisions.TryGetValue(d.Session,out var revision)&&revision!=d.Revision)selections.Remove(d.Session);if(selectionRevisions.Count>=64)selectionRevisions.Clear();selectionRevisions[d.Session]=d.Revision;}if(d!=null){chapters.Items.AddRange(d.Chapters.Select(c=>(object)new ChapterItem(c.Start,c.Title)).ToArray());if(selections.TryGetValue(d.Session,out var checkedStarts))for(int i=0;i<chapters.Items.Count;i++)chapters.SetItemChecked(i,checkedStarts.Contains(((ChapterItem)chapters.Items[i]).Start));}}finally{chapters.EndUpdate();}}
diagnostics.Text="PlotDirector Companion by Nick Beckley\r\n"+typeof(CompanionWindow).Assembly.GetName().Version+"\r\n"+state.Health?.Explanation+"\r\nManual chapter upload only. No automatic prose synchronisation.\r\n"+(d==null?"No Word session.":d.WordDiagnostics+"\r\n"+$"Session {d.Session}\r\nRevision {d.Revision}\r\nErrors: "+string.Join("\r\n",d.Errors.TakeLast(10)))+"\r\nClose hides this window; Exit stops the tray process. Open Companion resumes it.";
}finally{refreshing=false;}
}
private void Exit(){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){timer.Dispose();tray.Dispose();brand.Dispose();}base.Dispose(disposing);}
private static Icon CreateBrandIcon()
{
using var bitmap=new Bitmap(32,32);using(var graphics=Graphics.FromImage(bitmap)){graphics.SmoothingMode=System.Drawing.Drawing2D.SmoothingMode.AntiAlias;graphics.Clear(Color.Transparent);using var brush=new SolidBrush(Color.FromArgb(108,58,47));graphics.FillEllipse(brush,0,0,31,31);using var font=new Font("Segoe UI",19,FontStyle.Bold,GraphicsUnit.Pixel);using var ink=new SolidBrush(Color.FromArgb(255,244,223));graphics.DrawString("P",font,ink,7,3);}
var handle=bitmap.GetHicon();try{using var borrowed=Icon.FromHandle(handle);return (Icon)borrowed.Clone();}finally{DestroyIcon(handle);}
}
[System.Runtime.InteropServices.DllImport("user32.dll")]private static extern bool DestroyIcon(IntPtr handle);
private sealed record ChapterItem(int Start,string Title){public override string ToString()=>Title;}
}
#endif