#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> selections=[];private readonly Dictionary 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 nextStep=new(){Dock=DockStyle.Fill,AutoSize=true,Padding=new(0,4,0,8)};private readonly ToolTip tips=new();private readonly TabControl tabs=new(){Dock=DockStyle.Fill}; 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 Button contextAction=new(){Text="Open Context",AutoSize=true},intentAction=new(){Text="Open Intent",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[] displayedDocuments=[]; private TrayDocument? Current=>displayedDocuments.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(660,640);Size=new(880,820);DoubleBuffered=true; var layout=new TableLayoutPanel{Dock=DockStyle.Fill,Padding=new(24),ColumnCount=1,RowCount=8};layout.ColumnStyles.Add(new(SizeType.Percent,100));for(int i=0;i<8;i++)layout.RowStyles.Add(new(i==6?SizeType.Percent:SizeType.AutoSize,i==6?100:0)); var header=new FlowLayoutPanel{Dock=DockStyle.Fill,AutoSize=true,WrapContents=true}; header.Controls.Add(new Label{Text="PlotDirector",Font=new("Segoe UI",22,FontStyle.Bold),AutoSize=true,Margin=new(0,0,20,12)}); header.Controls.Add(Button("Connect / Sign in",()=>{tabs.SelectedIndex=1;site.Focus();}));header.Controls.Add(Button("Settings",()=>tabs.SelectedIndex=1));header.Controls.Add(Button("Help",()=>cloud.OpenSite("help")));layout.Controls.Add(header,0,0); layout.Controls.Add(status,0,1);layout.Controls.Add(nextStep,0,2); var manuscript=new TableLayoutPanel{Dock=DockStyle.Fill,AutoSize=true,ColumnCount=2,Padding=new(12)};manuscript.ColumnStyles.Add(new(SizeType.Percent,100));manuscript.ColumnStyles.Add(new(SizeType.AutoSize)); manuscript.Controls.Add(new Label{Text="CURRENT MANUSCRIPT",AutoSize=true,Font=new(Font,FontStyle.Bold)},0,0); manuscript.Controls.Add(Button("Use active Word document",()=>{var active=control.Documents.FirstOrDefault(d=>d.Active);if(active!=null){selected=active.Session;documents.SelectedItem=active;chapterKey="";}}),1,0); manuscript.Controls.Add(documents,0,1);manuscript.SetColumnSpan(documents,2);manuscript.Controls.Add(books,0,2);manuscript.Controls.Add(bookButton,1,2);manuscript.Controls.Add(remember,0,3);manuscript.SetColumnSpan(remember,2);layout.Controls.Add(manuscript,0,3); remember.Text="Remember this book when I save the document";bookButton.Text="Link book";detect.Text="Find chapters";review.Text="Review scenes in PlotDirector"; var actions=new FlowLayoutPanel{AutoSize=true,Dock=DockStyle.Fill,WrapContents=true,Padding=new(0,8,0,8)};actions.Controls.AddRange([detect,analyse,cancel,review,contextAction,intentAction]);layout.Controls.Add(actions,0,4); analyse.Tag="primary"; var activity=new TableLayoutPanel{Dock=DockStyle.Fill,AutoSize=true,ColumnCount=1,Padding=new(0,4,0,10)};activity.ColumnStyles.Add(new(SizeType.Percent,100));activity.Controls.Add(progressText);activity.Controls.Add(progress);layout.Controls.Add(activity,0,5); var chapterTab=new TabPage("Your chapters"){Padding=new(12)};chapterTab.Controls.Add(chapters);chapters.DrawMode=DrawMode.OwnerDrawFixed;chapters.ItemHeight=(int)Math.Round(52*DeviceDpi/96d);DpiChanged+=(_,_)=>{chapters.ItemHeight=(int)Math.Round(52*DeviceDpi/96d);chapters.Invalidate();};chapters.IntegralHeight=false;chapters.BorderStyle=BorderStyle.None; chapters.DrawItem+=DrawChapter;chapters.MouseMove+=(_,e)=>{var index=chapters.IndexFromPoint(e.Location);var title=index>=0?((ChapterItem)chapters.Items[index]).Title:"";if(tips.GetToolTip(chapters)!=title)tips.SetToolTip(chapters,title);}; var choices=new FlowLayoutPanel{Dock=DockStyle.Top,AutoSize=true};choices.Controls.AddRange([Button("Select all",()=>{for(var i=0;i{for(var i=0;icloud.Connect(site.Text.Trim())),1,0);settingsLayout.Controls.Add(connection);settingsLayout.Controls.Add(diagnostics); var options=new FlowLayoutPanel{Dock=DockStyle.Fill,AutoSize=true};options.Controls.AddRange([Button("Check connection",()=>_ = cloud.CheckConnection()),Button("Sign out",()=>cloud.SignOut()),Button("Open support folder",()=>System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(directory){UseShellExecute=true}))]);settingsLayout.Controls.Add(options);settings.Controls.Add(settingsLayout);tabs.TabPages.AddRange([chapterTab,settings]);layout.Controls.Add(tabs,0,6); layout.Controls.Add(new Label{AutoSize=true,Dock=DockStyle.Fill,Padding=new(0,12,0,0),Text="Your words stay yours. Analysis uploads only chapters you confirm. Import needs a separate preview and confirmation."},0,7);Controls.Add(layout); tips.SetToolTip(analyse,"Choose a linked book and select chapters first. Sends prose only after you confirm.");tips.SetToolTip(review,"Open saved scene suggestions and approve them before importing.");tips.SetToolTip(detect,"Reads Heading 1 chapter boundaries without changing your words."); ApplyTheme();Microsoft.Win32.SystemEvents.UserPreferenceChanged+=OnPreferences; 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().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, may retain an encrypted import capture if you approved that permission at sign-in, 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"));contextAction.Click+=(_,_)=>Safe(()=>Open("context"));intentAction.Click+=(_,_)=>Safe(()=>Open("intent"));tips.SetToolTip(contextAction,"Link an authorised book to open its reference workspace.");tips.SetToolTip(intentAction,"Link an authorised book to open its writing objectives."); var menu=new ContextMenuStrip();menu.Items.Add("Open PlotDirector Companion",null,(_,_)=>Reveal());menu.Items.Add("Open PlotDirector",null,(_,_)=>Safe(()=>Open("book")));menu.Items.Add("Help & connection",null,(_,_)=>{Reveal();tabs.SelectedIndex=1;});menu.Items.Add(new ToolStripSeparator());menu.Items.Add("Quit Companion",null,(_,_)=>Exit()); 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.PresentationDocuments;displayedDocuments=docs;var key=string.Join("|",docs.Select(d=>d.Session+":"+d.Title+":"+d.Active));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; SetText(status,CompanionPresentation.Connection(state.Health,DateTime.UtcNow)+" · "+(d==null?"Word not connected":"Word connected")); SetText(nextStep,CompanionPresentation.Next(d!=null,d?.Book>0,d?.Chapters.Length??0,d!=null&&(d.Job!=Guid.Empty||d.Pending.Count>0))); SetText(progressText,string.IsNullOrEmpty(error)?d?.Status??"Waiting for your manuscript.":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&&state.Health?.Authentication=="verified"&&state.Health?.Ai is not ("not-configured" or "not-entitled");cancel.Enabled=d!=null&&(d.Job!=Guid.Empty||d.Pending.Count>0);bookButton.Enabled=d!=null&&state.Books.Length>0&&d.Job==Guid.Empty;review.Enabled=d?.Book>0;contextAction.Enabled=intentAction.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)return;var item=(ChapterItem)chapters.Items[e.Index];var d=Current;e.DrawBackground(); var selectedRow=(e.State&DrawItemState.Selected)!=0;var ink=selectedRow?SystemColors.HighlightText:chapters.ForeColor; int Px(int value)=>(int)Math.Round(value*DeviceDpi/96d);var box=new Rectangle(e.Bounds.Left+Px(6),e.Bounds.Top+Px(17),Px(16),Px(16));ControlPaint.DrawCheckBox(e.Graphics,box,chapters.GetItemChecked(e.Index)?ButtonState.Checked:ButtonState.Normal); TextRenderer.DrawText(e.Graphics,item.Title,Font,new Rectangle(e.Bounds.Left+Px(32),e.Bounds.Top+Px(4),e.Bounds.Width-Px(40),Px(24)),ink,TextFormatFlags.EndEllipsis|TextFormatFlags.SingleLine); var analysed=d?.Completed.Any(c=>c.Item1==d.Revision&&c.Item2==d.Book&&c.Item3==item.Start)==true; var working=d?.Current?.Start==item.Start&&d.Job!=Guid.Empty; TextRenderer.DrawText(e.Graphics,CompanionPresentation.Chapter(working,analysed,d?.FailedChapters.Contains((d.Revision,d.Book,item.Start))==true),Font,new Rectangle(e.Bounds.Left+Px(32),e.Bounds.Top+Px(28),e.Bounds.Width-Px(40),Px(22)),ink,TextFormatFlags.EndEllipsis|TextFormatFlags.SingleLine);e.DrawFocusRectangle(); } 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){Microsoft.Win32.SystemEvents.UserPreferenceChanged-=OnPreferences;timer.Dispose();tips.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