148 lines
17 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.

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using PlotDirector.Companion.Client;
using PlotDirector.Companion.Protocol;
namespace PlotDirector.WordAddIn
{
// Modeless, DPI-aware value-only review. Rendering is bounded to two 40-row pages.
public sealed class AnalysisWindow : Form
{
private readonly Label status=new Label{AutoSize=true,MaximumSize=new Size(1100,0),Margin=new Padding(8)};
private readonly ProgressBar progress=new ProgressBar{Dock=DockStyle.Fill,Height=6,Maximum=100};
private readonly TreeView local=new TreeView{Dock=DockStyle.Fill,CheckBoxes=true,HideSelection=false,ShowNodeToolTips=true};
private readonly TreeView ai=new TreeView{CheckBoxes=true,Dock=DockStyle.Fill,HideSelection=false,ShowNodeToolTips=true};
private readonly TextBox details=new TextBox{Dock=DockStyle.Fill,Multiline=true,ReadOnly=true,ScrollBars=ScrollBars.Vertical};
private readonly ComboBox books=new ComboBox{DropDownStyle=ComboBoxStyle.DropDownList,Width=300,DisplayMember="Title",ValueMember="BookId"};
private readonly Label pages=new Label{AutoSize=true,Margin=new Padding(8)};
private readonly Button cancel=new Button{Text="Cancel",AutoSize=true};
private readonly Button next=new Button{Text="Next",AutoSize=true},previous=new Button{Text="Previous",AutoSize=true};
private readonly TabControl tabs=new TabControl{Dock=DockStyle.Fill};
private bool rebinding;
private readonly Dictionary<Guid,Guid> selectionSnapshots=new Dictionary<Guid,Guid>();
private readonly Dictionary<Guid,StructureSelection> choices=new Dictionary<Guid,StructureSelection>();
private StructureSelection selection=new StructureSelection();
private readonly TextBox savedContext=new TextBox{Dock=DockStyle.Fill,Multiline=true,ReadOnly=true,ScrollBars=ScrollBars.Vertical};
private readonly TextBox savedIntent=new TextBox{Dock=DockStyle.Fill,Multiline=true,ReadOnly=true,ScrollBars=ScrollBars.Vertical};
private readonly TextBox previewText=new TextBox{Dock=DockStyle.Fill,Multiline=true,ReadOnly=true,ScrollBars=ScrollBars.Vertical};
private readonly Button ask=new Button{Text="AI: analyse checked chapters",AutoSize=true};
private readonly Button previewButton=new Button{Text="Preview selected import",AutoSize=true};
private readonly Button openContext=new Button{Text="Open full saved Context",AutoSize=true},openIntent=new Button{Text="Open saved Intent",AutoSize=true},openBook=new Button{Text="Continue in PlotDirector",AutoSize=true};
private int aiOffset;private Guid session,authenticationContext,localSnapshot;private string renderKey="";private string bookKey="";private string aiRenderKey="";
private IList<StructureSuggestion> aiItems=new List<StructureSuggestion>();
public AnalysisWindow(Action analyse,Action stop,Action<int> page,Action<AiConsent> submit,Action<StructureSuggestion> navigate,Action<int> selectBook,Action<AiConsent> previewImport,Action<string> open,Action checkConnection)
{
Text="PlotDirector — Manuscript review";Font=new Font("Segoe UI",9F);AutoScaleMode=AutoScaleMode.Dpi;MinimumSize=new Size(680,480);Width=980;Height=680;ShowInTaskbar=false;
status.MaximumSize=new Size(Math.Max(400,ClientSize.Width-40),0);
var layout=new TableLayoutPanel{Dock=DockStyle.Fill,ColumnCount=1,RowCount=6,Padding=new Padding(10)};
layout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent,100));
layout.RowStyles.Add(new RowStyle(SizeType.AutoSize));layout.RowStyles.Add(new RowStyle(SizeType.Absolute,8));layout.RowStyles.Add(new RowStyle(SizeType.AutoSize));
layout.RowStyles.Add(new RowStyle(SizeType.Percent,70));layout.RowStyles.Add(new RowStyle(SizeType.Percent,30));layout.RowStyles.Add(new RowStyle(SizeType.AutoSize));
var actions=new FlowLayoutPanel{Dock=DockStyle.Fill,AutoSize=true,WrapContents=true,Padding=new Padding(0,6,0,6)};
var repeat=new Button{Text="Detect structure",AutoSize=true};repeat.Click+=(_,__)=>analyse();
ask.Click+=(_,__)=>{
var chosen=selection.Items.Where(item=>item.Kind=="Chapter").ToArray();
if(chosen.Length==0){MessageBox.Show("Check one or more chapter nodes in Local structure first.","PlotDirector");return;}
var consent=new AiConsent{SessionId=session,SnapshotId=localSnapshot,AuthenticationContext=authenticationContext,BookId=SelectedBook,Chapters=chosen};
if(consent.BookId<=0){MessageBox.Show("Connect, then select an authorised PlotDirector book.","PlotDirector");return;}
if(MessageBox.Show("Send "+chosen.Length+" selected chapter(s) for book "+(books.SelectedItem as CompanionBook)?.Title+" to PlotDirector's configured AI provider? This may incur AI costs. Existing markers and manuscript text will not change.","Confirm chapter upload",MessageBoxButtons.OKCancel)==DialogResult.OK)submit(consent);
};
cancel.Click+=(_,__)=>{if(tabs.SelectedIndex==4)previewText.Text="Preview cancelled; no records changed.";stop();};
books.SelectedIndexChanged+=(_,__)=>{if(!rebinding){selectBook(SelectedBook);previewText.Clear();}};
var check=new Button{Text="Check connection",AutoSize=true};check.Click+=(_,__)=>checkConnection();
previewButton.Click+=(_,__)=>{
var chosen=selection.Items;if(chosen.Length==0){details.Text="Check chapter and scene rows to preview. Parent chapters are required; choose one local/AI interpretation at each position.";return;}
var consent=new AiConsent{SessionId=session,SnapshotId=localSnapshot,AuthenticationContext=authenticationContext,BookId=SelectedBook,Chapters=chosen};
if(MessageBox.Show("Send selected titles and structural positions to PlotDirector for a read-only import preview? No prose is uploaded and nothing is committed.","Preview import",MessageBoxButtons.OKCancel)==DialogResult.OK){previewImport(consent);tabs.SelectedIndex=4;previewText.Text="Preparing a read-only server preview…";}
};
var clear=new Button{Text="Clear selection",AutoSize=true};clear.Click+=(_,__)=>{selection.Clear();rebinding=true;foreach(TreeNode node in local.Nodes){node.Checked=false;foreach(TreeNode child in node.Nodes)child.Checked=false;}foreach(TreeNode node in ai.Nodes){node.Checked=false;foreach(TreeNode child in node.Nodes)child.Checked=false;}rebinding=false;};
actions.Controls.AddRange(new Control[]{repeat,books,ask,previewButton,clear,cancel,check});
var localTab=new TabPage("Local structure");localTab.Controls.Add(local);var aiTab=new TabPage("AI scene suggestions");aiTab.Controls.Add(ai);var contextTab=new TabPage("Context · saved data");var intentTab=new TabPage("Intent · saved objectives");var importTab=new TabPage("Import preview");
contextTab.Controls.Add(savedContext);openContext.Dock=DockStyle.Bottom;contextTab.Controls.Add(openContext);
intentTab.Controls.Add(savedIntent);openIntent.Dock=DockStyle.Bottom;intentTab.Controls.Add(openIntent);
importTab.Controls.Add(previewText);openBook.Dock=DockStyle.Bottom;importTab.Controls.Add(openBook);
openContext.Click+=(_,__)=>open("context");openIntent.Click+=(_,__)=>open("intent");openBook.Click+=(_,__)=>open("book");
tabs.TabPages.AddRange(new[]{localTab,aiTab,contextTab,intentTab,importTab});
local.AfterCheck+=Checked;ai.AfterCheck+=Checked;
var footer=new FlowLayoutPanel{Dock=DockStyle.Fill,AutoSize=true};footer.Controls.AddRange(new Control[]{previous,next,pages});
previous.Click+=(_,__)=>{if(tabs.SelectedIndex==0)page(-1);else if(tabs.SelectedIndex==1){aiOffset=Math.Max(0,aiOffset-40);RenderAi();}};
next.Click+=(_,__)=>{if(tabs.SelectedIndex==0)page(1);else if(tabs.SelectedIndex==1){aiOffset+=40;RenderAi();}};
tabs.SelectedIndexChanged+=(_,__)=>{details.Text="Select a result to inspect its source and reasoning.";if(tabs.SelectedIndex==1)RenderAi();else UpdatePages();};
local.AfterSelect+=(_,e)=>Inspect(e.Node);ai.AfterSelect+=(_,e)=>Inspect(e.Node);
local.NodeMouseDoubleClick+=(_,e)=>{if(e.Node.Tag is StructureSuggestion item)navigate(item);};
ai.NodeMouseDoubleClick+=(_,e)=>{if(e.Node.Tag is StructureSuggestion item)navigate(item);};
layout.Controls.Add(status,0,0);layout.Controls.Add(progress,0,1);layout.Controls.Add(actions,0,2);layout.Controls.Add(tabs,0,3);layout.Controls.Add(details,0,4);layout.Controls.Add(footer,0,5);Controls.Add(layout);
Resize+=(_,__)=>status.MaximumSize=new Size(Math.Max(400,ClientSize.Width-40),0);
}
public void ForgetBookSelection(){rebinding=true;try{books.SelectedIndex=-1;}finally{rebinding=false;}}
public int SelectedBook=>books.SelectedItem is CompanionBook book?book.BookId:0;
public void ShowSavedTab(bool intent){tabs.SelectedIndex=intent?3:2;}
private AnalysisPage current;
public void Render(AnalysisReview review,string connection,Guid document,string documentName,Guid authentication,CompanionBook[] available,string cloud,string aiStatus,IList<StructureSuggestion> results,bool running,DocumentBinding binding,ConnectionHealth health,bool workflowSupported)
{
if(session!=document){session=document;renderKey="";aiRenderKey="";ForgetBookSelection();aiOffset=0;local.Nodes.Clear();ai.Nodes.Clear();details.Clear();}
if(!choices.TryGetValue(document,out selection)){if(choices.Count>=32){choices.Clear();selectionSnapshots.Clear();}selection=new StructureSelection();choices[document]=selection;}
var snapshot=review?.SnapshotId??Guid.Empty;if(selectionSnapshots.TryGetValue(document,out var previousSnapshot)&&previousSnapshot!=snapshot)selection.Clear();selectionSnapshots[document]=snapshot;
authenticationContext=authentication;localSnapshot=review?.SnapshotId??Guid.Empty;
current=review?.Page;aiItems=results??new List<StructureSuggestion>();
status.Text=(documentName??"No active document")+" · Agent: "+connection+" · "+cloud+"\n"+(review?.Running==true?review.Status:string.IsNullOrEmpty(aiStatus)?review?.Status:aiStatus);
if(current!=null)status.Text+="\n"+current.WordCount.ToString("N0")+" approximate words · "+current.ChapterCount+" local chapter candidates · "+current.SceneCount+" local scene candidates. "+(current.Truncated?"Result limit reached. ":"")+"Double-click to navigate; select to inspect evidence.";
progress.Value=review?.Progress??0;cancel.Enabled=running||review?.Running==true||binding?.Preview?.State=="loading";
var workspace=binding?.Workspace;
var verified=workspace?.State?.StartsWith("saved-",StringComparison.Ordinal)==true;
var cached=health==null||health.Server!="online"||DateTime.UtcNow-health.VerifiedUtc>=TimeSpan.FromSeconds(90)?" · cached/unverified; Check connection":"";
savedContext.Text=(workspace?.Title??"No book selected")+"\r\nSaved PlotDirector data · read-only · "+(workspace?.State??"unselected")+cached+"\r\n\r\n"+(string.IsNullOrWhiteSpace(workspace?.Context)?"No saved context for this location. Select a book; recognised saved chapter/scene markers are verified against that book. Local/AI suggestions do not create saved context.":workspace.Context);
savedIntent.Text=(workspace?.Title??"No book selected")+"\r\nSaved writing objectives · read-only · "+(workspace?.State??"unselected")+cached+"\r\n\r\n"+(string.IsNullOrWhiteSpace(workspace?.Intent)?"No saved writing objective at this location. Set chapter goals or scene purpose in PlotDirector; no intent is invented or silently saved here.":workspace.Intent);
openContext.Enabled=verified&&!string.IsNullOrEmpty(workspace.ContextPath);openIntent.Enabled=verified&&!string.IsNullOrEmpty(workspace.IntentPath);openBook.Enabled=verified;
var plan=binding?.Preview;
if(plan!=null)previewText.Text=plan.State+"\r\nSelected: "+plan.Chapters+" chapters / "+plan.Scenes+" scenes\r\nAlready saved: "+plan.ExistingChapters+" chapters / "+plan.ExistingScenes+" scenes\r\n\r\n"+plan.Message+"\r\n\r\nCreated: 0. Replaced: 0. Native commit is unavailable; use the established PlotDirector workflow.";
else previewText.Text="Select chapter and scene rows, then Preview selected import. This validates the target through PlotDirector's existing importer. Native commit is unavailable; selections are not silently transferred to onboarding.";
var fresh=health!=null&&DateTime.UtcNow-health.VerifiedUtc<TimeSpan.FromSeconds(90)&&health.Authentication=="verified"&&health.Server=="online";
ask.Enabled=fresh&&verified&&!running&&review?.Running!=true&&review?.Page!=null&&(health.Ai=="configured"||health.Ai=="last-request-succeeded");
previewButton.Enabled=workflowSupported&&fresh&&verified&&!running&&review?.Running!=true&&plan?.State!="loading"&&review?.Page!=null;
var key=string.Join("|",available.Select(b=>b.BookId+":"+b.Title));
rebinding=true;try{if(bookKey!=key){bookKey=key;books.DataSource=available;books.DropDownWidth=650;}var selected=binding?.BookId??0;if(available.Any(b=>b.BookId==selected))books.SelectedValue=selected;else books.SelectedIndex=-1;}finally{rebinding=false;}
var newKey=(review?.SnapshotId.ToString()??"")+":"+(current?.Offset??-1);
if(renderKey!=newKey){renderKey=newKey;details.Text="Select a result to inspect its source and reasoning.";Fill(local,current?.Items??Array.Empty<StructureSuggestion>());}
if(tabs.SelectedIndex==1)RenderAi();else UpdatePages();
}
private void Inspect(TreeNode node)
{if(node.Tag is StructureSuggestion item)details.Text=item.Title+Environment.NewLine+item.Origin+" · "+item.Confidence+Environment.NewLine+item.Reason+Environment.NewLine+"Word position "+item.Start+". Double-click to navigate without changing text.";}
private void Fill(TreeView tree,IEnumerable<StructureSuggestion> values)
{
rebinding=true;tree.BeginUpdate();try{tree.Nodes.Clear();var parents=new Dictionary<int,TreeNode>();
foreach(var item in values)
{
var chapterStart=item.Kind=="Chapter"?item.Start:item.ChapterStart;
if(!parents.TryGetValue(chapterStart,out var parent))
{
var chapter=item.Kind=="Chapter"?item:new StructureSuggestion{Kind="Chapter",Start=chapterStart,End=item.ChapterEnd,Title=string.IsNullOrEmpty(item.ChapterTitle)?"Before first chapter / unassigned":item.ChapterTitle,Origin="Local structure",Reason="Chapter context for this results page."};
parent=new TreeNode("Chapter · "+chapter.Title){Checked=selection.Contains(chapter),Tag=chapterStart>=0?(object)chapter:null,ToolTipText=chapter.Title};parents.Add(chapterStart,parent);tree.Nodes.Add(parent);
}
if(item.Kind!="Chapter")parent.Nodes.Add(new TreeNode(item.Title+" ["+item.Origin+"]"){Checked=selection.Contains(item),Tag=item,ToolTipText=item.Title});
}
tree.ExpandAll();}finally{tree.EndUpdate();rebinding=false;}
}
private void RenderAi(){if(aiOffset>=aiItems.Count)aiOffset=0;var key=aiOffset+":"+aiItems.Count+":"+session+string.Join("|",aiItems.Skip(aiOffset).Take(40).Select(s=>s.Start+":"+s.Title+":"+s.Reason));if(aiRenderKey!=key){aiRenderKey=key;Fill(ai,aiItems.Skip(aiOffset).Take(40));}UpdatePages();}
private void Checked(object sender,TreeViewEventArgs args)
{
if(rebinding||!(args.Node.Tag is StructureSuggestion item))return;
if(item.Kind!="Chapter"&&item.Kind!="Scene"){rebinding=true;args.Node.Checked=false;rebinding=false;details.Text="Error/evidence rows cannot be selected for upload or import.";return;}
if(!selection.Set(item,args.Node.Checked)){rebinding=true;args.Node.Checked=false;rebinding=false;details.Text="Preview selection is limited to 80 rows. Use smaller batches.";}
if(args.Action!=TreeViewAction.Unknown)foreach(TreeNode child in args.Node.Nodes)child.Checked=args.Node.Checked;
rebinding=true;try{foreach(var tree in new[]{local,ai})foreach(TreeNode node in tree.Nodes){if(node.Tag is StructureSuggestion parent)node.Checked=selection.Contains(parent);foreach(TreeNode child in node.Nodes)if(child.Tag is StructureSuggestion row)child.Checked=selection.Contains(row);}}finally{rebinding=false;}UpdatePages();
}
private void UpdatePages()
{
if(tabs.SelectedIndex>1){previous.Enabled=false;next.Enabled=false;pages.Text="Read-only saved data / preview; no automatic changes";return;}
var offset=tabs.SelectedIndex==0?(current?.Offset??0):aiOffset;var total=tabs.SelectedIndex==0?(current?.Total??0):aiItems.Count;
pages.Text=total==0?"No results":"Showing "+(offset+1)+"–"+Math.Min(total,offset+40)+" of "+total;
pages.Text+=" · "+selection.Items.Length+" selected across pages (limit 80)";
previous.Enabled=offset>0;next.Enabled=offset+40<total;
}
}
}