Repair queued Word focus intent, first-join reconciliation and Hold controls
This commit is contained in:
parent
c1aec010b6
commit
8a719dae0a
@ -1 +1 @@
|
||||
<Project><PropertyGroup><ApplicationVersion>1.0.0.45</ApplicationVersion></PropertyGroup></Project>
|
||||
<Project><PropertyGroup><ApplicationVersion>1.0.0.46</ApplicationVersion></PropertyGroup></Project>
|
||||
|
||||
12
PlotDirector.NativeCompanion/Protocol/FocusInputState.cs
Normal file
12
PlotDirector.NativeCompanion/Protocol/FocusInputState.cs
Normal file
@ -0,0 +1,12 @@
|
||||
namespace PlotDirector.Companion.Protocol;
|
||||
|
||||
// A queued input belongs to one actual Word window. Selection callbacks may arrive
|
||||
// after the mouse/key has been released; a sampled key-down bit is not evidence.
|
||||
public sealed class FocusInputState
|
||||
{
|
||||
private long sequence, pending, at;private int window;private bool confirmed;
|
||||
public void Record(int owner,long milliseconds,bool manuscriptClick){window=owner;at=milliseconds;pending=++sequence;confirmed=manuscriptClick;}
|
||||
public void Confirm(){if(pending!=0)confirmed=true;}
|
||||
public void Clear(){pending=0;confirmed=false;}
|
||||
public long Consume(int owner,long milliseconds){var result=owner==window&&confirmed&&milliseconds>=at&&milliseconds-at<=2000?pending:0;Clear();return result;}
|
||||
}
|
||||
@ -3,8 +3,8 @@ namespace PlotDirector.Companion.Protocol;
|
||||
public sealed class FocusWindowState
|
||||
{
|
||||
public Guid Id {get;}=Guid.NewGuid();public bool Held{get;private set;}public long Sequence{get;private set;}public long LastSharedRevision{get;private set;}public Guid ModeRequest{get;private set;}=Guid.NewGuid();
|
||||
private int start=-1,end=-1;private long appliedRevision=-1;private bool catchup;
|
||||
private int start=-1,end=-1;private long appliedRevision=-1,lastInput;private bool catchup;
|
||||
public void Hold(bool held){if(Held==held)return;Held=held;if(!held){appliedRevision=-1;catchup=true;}ModeRequest=Guid.NewGuid();}
|
||||
public long Observe(int nextStart,int nextEnd,bool deliberate){var changed=start!=nextStart||end!=nextEnd;start=nextStart;end=nextEnd;return changed&&deliberate&&!Held?++Sequence:0;}
|
||||
public long Observe(int nextStart,int nextEnd,bool deliberate,long input=0){var changed=start!=nextStart||end!=nextEnd;start=nextStart;end=nextEnd;var fresh=input>lastInput;if(fresh)lastInput=input;return (input==0?changed:fresh)&&deliberate&&!Held?++Sequence:0;}
|
||||
public bool Accept(long revision,Guid origin){if(revision<LastSharedRevision||revision<=appliedRevision)return false;LastSharedRevision=revision;if(Held)return false;appliedRevision=revision;var follow=catchup||origin!=Id;catchup=false;return follow;}
|
||||
}
|
||||
|
||||
@ -18,5 +18,16 @@ internal static class SharedFocusTests
|
||||
check(!a.Accept(5,a.Id)&&a.LastSharedRevision==5,"originating Word window does not echo its own selection");
|
||||
a.Hold(true);a.Observe(50,50,true);a.Hold(false);check(a.Accept(5,a.Id),"release returns to shared reference even when this same Word window originally published it");
|
||||
check(b.Accept(5,a.Id),"another following Word window can receive that selection");
|
||||
var input=new FocusInputState();
|
||||
input.Record(10,100,true);var click=input.Consume(10,150);
|
||||
check(click>0&&input.Consume(10,151)==0,"queued manuscript click survives key release and is consumed once");
|
||||
check(a.Observe(50,50,true,click)==2&&a.Observe(50,50,true,click)==0,"fresh click at unchanged editing caret publishes once after remote reveal");
|
||||
input.Record(10,200,false);input.Confirm();check(input.Consume(10,250)>0,"navigation-pane selection confirms queued input");
|
||||
input.Record(10,300,false);check(input.Consume(10,350)==0,"ribbon click without selection does not publish");
|
||||
input.Record(10,400,true);input.Clear();check(input.Consume(10,450)==0,"typing and remote navigation discard pending input");
|
||||
input.Record(10,500,true);check(input.Consume(20,550)==0,"input cannot leak to another Word window");
|
||||
input.Record(10,600,true);check(input.Consume(10,3000)==0,"expired input cannot turn passive observations into navigation");
|
||||
input.Record(10,3100,true);check(input.Consume(10,3150)>0,"genuine click works immediately after suppression");
|
||||
a.Hold(true);check(a.Observe(60,60,true,99)==0,"held deliberate input never publishes");a.Hold(false);check(a.Observe(60,60,false)==0,"release never republishes held position");
|
||||
}
|
||||
}
|
||||
|
||||
@ -37,7 +37,7 @@ namespace PlotDirector.WordAddIn
|
||||
try
|
||||
{
|
||||
Refresh("PlotDirectorStatus", GetStatus(null));
|
||||
Refresh("PlotDirectorHold",adapter()?.FocusWindowKey+GetFocusHeld(null));Refresh("PlotDirectorFocusState",adapter()?.FocusWindowKey+GetFocusState(null));
|
||||
Refresh("PlotDirectorHold",adapter()?.FocusWindowKey+GetFocusHeld(null)+CanHoldFocus(null));
|
||||
Refresh("PlotDirectorBook", GetBookTip(null));
|
||||
Refresh("PlotDirectorChapter", GetChapterTip(null));
|
||||
Refresh("PlotDirectorScene", GetSceneTip(null));
|
||||
@ -70,8 +70,8 @@ namespace PlotDirector.WordAddIn
|
||||
|
||||
public bool GetFocusHeld(Office.IRibbonControl control)=>adapter()?.WindowFocusHeld(control?.Context)==true;
|
||||
public string GetFocusAction(Office.IRibbonControl control)=>GetFocusHeld(control)?"Release Hold":"Hold";
|
||||
public string GetFocusState(Office.IRibbonControl control)=>adapter()?.WindowFocusState(control?.Context)??"Following";
|
||||
public string GetFocusTip(Office.IRibbonControl control)=>GetFocusHeld(control)?"Release Hold: catch up to shared manuscript focus. Content synchronisation stays active.":"Hold this Word window at its local position. Other windows and content synchronisation continue.";
|
||||
public bool CanHoldFocus(Office.IRibbonControl control)=>adapter()?.CanHoldFocus==true;
|
||||
public string GetFocusTip(Office.IRibbonControl control)=>!CanHoldFocus(control)?"Connect Companion and select a linked Word manuscript.":GetFocusHeld(control)?"Release Hold: catch up to shared manuscript focus. Content synchronisation stays active.":"Hold this Word window at its local position. Other windows and content synchronisation continue.";
|
||||
public void ToggleFocusHold(Office.IRibbonControl control,bool pressed){adapter()?.SetFocusHeld(pressed);Invalidate();}
|
||||
public bool CanOpenBook(Office.IRibbonControl control) => adapter()?.HasRibbonBook == true;
|
||||
public string GetBookTip(Office.IRibbonControl control) => adapter()?.RibbonBook ?? "No linked book";
|
||||
|
||||
@ -23,7 +23,7 @@
|
||||
<ProjectReference Include="..\Protocol\PlotDirector.Companion.Protocol.csproj"><Name>PlotDirector.Companion.Protocol</Name></ProjectReference>
|
||||
<ProjectReference Include="..\Client\PlotDirector.Companion.Client.csproj"><Name>PlotDirector.Companion.Client</Name></ProjectReference>
|
||||
<Compile Include="ThisAddIn.cs" /><Compile Include="ThisAddIn.Designer.cs"><DependentUpon>ThisAddIn.cs</DependentUpon></Compile>
|
||||
<Compile Include="WordAdapter.cs" /><Compile Include="WordFocus.cs" /><Compile Include="WordChapterRead.cs" />
|
||||
<Compile Include="WordAdapter.cs" /><Compile Include="WordFocus.cs" /><Compile Include="WordFocusInput.cs" /><Compile Include="WordChapterRead.cs" />
|
||||
<Compile Include="WordChapterPositions.cs" /><Compile Include="NativeRibbon.cs" /><Compile Include="AgentProcess.cs" /><Compile Include="Properties\AssemblyInfo.cs" />
|
||||
<None Include="ThisAddIn.Designer.xml"><DependentUpon>ThisAddIn.cs</DependentUpon></None>
|
||||
<EmbeddedResource Include="Ribbon.xml" />
|
||||
|
||||
@ -7,7 +7,7 @@
|
||||
<editBox id="PlotDirectorChapter" label="Chapter" getText="GetChapterTip" getSupertip="GetChapterTip" onChange="RestoreTitle" sizeString="MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" />
|
||||
<editBox id="PlotDirectorScene" label="Scene" getText="GetSceneTip" getSupertip="GetSceneTip" onChange="RestoreTitle" sizeString="MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" />
|
||||
</group>
|
||||
<group id="PlotDirectorSharedFocus" label="Manuscript focus"><toggleButton id="PlotDirectorHold" getLabel="GetFocusAction" imageMso="Lock" getPressed="GetFocusHeld" onAction="ToggleFocusHold" getSupertip="GetFocusTip"/><editBox id="PlotDirectorFocusState" label="State" getText="GetFocusState" onChange="RestoreTitle" sizeString="MMMMMMMMMMMMMMMMMMMMMMMM"/></group>
|
||||
<group id="PlotDirectorSharedFocus" label="Manuscript focus"><toggleButton id="PlotDirectorHold" getLabel="GetFocusAction" imageMso="Lock" getPressed="GetFocusHeld" onAction="ToggleFocusHold" getSupertip="GetFocusTip" getEnabled="CanHoldFocus"/></group>
|
||||
<group id="PlotDirectorWriting" label="Writing">
|
||||
<button id="PlotDirectorContext" label="Context" size="large" imageMso="ReadingMode" onAction="OpenContext" getEnabled="CanOpenBook" />
|
||||
<button id="PlotDirectorWeb" label="PlotDirector" size="large" imageMso="HyperlinkInsert" onAction="OpenPlotDirector" getEnabled="CanOpenBook" />
|
||||
|
||||
@ -62,6 +62,7 @@ namespace PlotDirector.WordAddIn
|
||||
public string ConnectionState { get; private set; } = "Connecting";
|
||||
public bool HasActiveDocument => active != null;
|
||||
public string Diagnostics => "PlotDirector " + typeof(WordAdapter).Assembly.GetName().Version + "\nAgent: " + ConnectionState
|
||||
+ "\nShared focus input hook: " + (focusHook!=IntPtr.Zero?"attached":"unavailable")
|
||||
+ "\nSelection events / observations: " + selectionNotifications + " / " + selectionReads
|
||||
+ "\nWord navigation executions: " + navigationExecutions + " · last command: " + lastNavigationId
|
||||
+ "\nOpen sessions: " + documents.Count
|
||||
@ -130,7 +131,7 @@ namespace PlotDirector.WordAddIn
|
||||
events.DocumentBeforeClose += BeforeClose;
|
||||
events.DocumentBeforeSave += BeforeSave;
|
||||
timer.Tick += Tick;
|
||||
timer.Start(); link.Start();
|
||||
StartFocusInput();timer.Start(); link.Start();
|
||||
// Already-open documents are registered in bounded UI actions, not a background COM enumeration.
|
||||
scheduler.Post("discover", DiscoverOpenDocuments);
|
||||
}
|
||||
@ -285,7 +286,7 @@ namespace PlotDirector.WordAddIn
|
||||
if(!NavigationPolicy.Current(command,doc.Session,doc.Revision,doc.Identity,DateTime.UtcNow,Com(()=>doc.Document.Saved)))throw new InvalidOperationException("Navigation expired or document changed.");
|
||||
if(completedNavigationIds.Contains(command.Id)){Reply(command,"ok");return;}
|
||||
var position=command.Chapter.Start;if(position<0||position>DocumentEnd(doc.Document))throw new InvalidOperationException("Position no longer exists.");
|
||||
Metric("navigation-identity-and-target",navigationClock.Elapsed.TotalMilliseconds,command.Id);navigationClock.Restart();Word.Range range=null;try{range=Com(()=>doc.Document.Range(position,position));if(command.BackgroundFocus)FollowSharedFocus(doc.Document,command,range);else Com(()=>{range.Select();return true;});Metric("navigation-word-selection",navigationClock.Elapsed.TotalMilliseconds,command.Id);navigationExecutions++;lastNavigationId=command.Id;if(completedNavigationIds.Count==64)completedNavigationIds.Dequeue();completedNavigationIds.Enqueue(command.Id);}finally{Release(range);}
|
||||
Metric("navigation-identity-and-target",navigationClock.Elapsed.TotalMilliseconds,command.Id);navigationClock.Restart();Word.Range range=null;try{range=Com(()=>doc.Document.Range(position,position));if(command.BackgroundFocus)FollowSharedFocus(doc.Document,command,range);else {focusInput.Clear();applyingFocus=true;try{Com(()=>{range.Select();return true;});}finally{applyingFocus=false;}}Metric("navigation-word-selection",navigationClock.Elapsed.TotalMilliseconds,command.Id);navigationExecutions++;lastNavigationId=command.Id;if(completedNavigationIds.Count==64)completedNavigationIds.Dequeue();completedNavigationIds.Enqueue(command.Id);}finally{Release(range);}
|
||||
}
|
||||
else if(command.Kind=="associate"){
|
||||
if(command.Remember){
|
||||
@ -691,7 +692,7 @@ namespace PlotDirector.WordAddIn
|
||||
private static void Release(object value) {if(value!=null&&Marshal.IsComObject(value))Marshal.ReleaseComObject(value);}
|
||||
public void Dispose()
|
||||
{
|
||||
if(disposed)return;disposed=true;timer.Stop();timer.Dispose();scheduler.Clear();
|
||||
if(disposed)return;disposed=true;StopFocusInput();timer.Stop();timer.Dispose();scheduler.Clear();
|
||||
events.DocumentOpen-=Open;events.NewDocument-=Open;events.DocumentChange-=ScheduleSelection;events.WindowActivate-=Activate;
|
||||
events.WindowSelectionChange-=SelectionChanged;events.DocumentBeforeClose-=BeforeClose;events.DocumentBeforeSave-=BeforeSave;
|
||||
link.Dispose();documents.Clear();pendingOpen.Clear();closing.Clear();dispatch.Dispose();
|
||||
|
||||
@ -9,25 +9,25 @@ namespace PlotDirector.WordAddIn
|
||||
{
|
||||
public sealed partial class WordAdapter
|
||||
{
|
||||
[DllImport("user32.dll")]private static extern short GetAsyncKeyState(int key);
|
||||
[DllImport("user32.dll")]private static extern IntPtr GetForegroundWindow();
|
||||
[DllImport("user32.dll")]private static extern uint GetWindowThreadProcessId(IntPtr window,out uint process);
|
||||
private readonly Dictionary<int,FocusWindowState> focusWindows=new Dictionary<int,FocusWindowState>();
|
||||
private readonly uint focusProcessId=(uint)Process.GetCurrentProcess().Id;private Guid deliberateFocusWindow;private bool deliberateFocusPending,applyingFocus;private string sharedFocusStatus="";
|
||||
private readonly uint focusProcessId=(uint)Process.GetCurrentProcess().Id;private bool applyingFocus;private string sharedFocusStatus="";
|
||||
private FocusWindowState FocusWindow(Word.Window window){var handle=Com(()=>window.Hwnd);FocusWindowState state;if(!focusWindows.TryGetValue(handle,out state))focusWindows[handle]=state=new FocusWindowState();return state;}
|
||||
private FocusWindowState ActiveFocusWindow(){Word.Window window=null;try{window=Com(()=>application.ActiveWindow);return window==null?null:FocusWindow(window);}catch(COMException){return null;}finally{Release(window);}}
|
||||
public bool CanHoldFocus=>focusHook!=IntPtr.Zero&&HasRibbonBook;
|
||||
public bool FocusHeld=>ActiveFocusWindow()?.Held==true;
|
||||
public bool WindowFocusHeld(object context){var window=context as Word.Window;try{return window!=null?FocusWindow(window).Held:FocusHeld;}finally{Release(window);}}
|
||||
public string FocusWindowKey=>ActiveFocusWindow()?.Id.ToString()??"";
|
||||
private string FollowingFocusLabel=>sharedFocusStatus=="word-unmapped"?"Following · mapping unavailable":sharedFocusStatus=="save-required"?"Following · save Word first":sharedFocusStatus=="word-busy"?"Following · Word busy":"Following · Hold available";
|
||||
public string FocusStateLabel=>FocusHeld?"Held · Release Hold":FollowingFocusLabel;
|
||||
public string WindowFocusState(object context)=>WindowFocusHeld(context)?"Held · Release Hold":FollowingFocusLabel;
|
||||
public void SetFocusHeld(bool held){var state=ActiveFocusWindow();if(state==null)return;state.Hold(held);deliberateFocusPending=false;scheduler.Post("selection",CaptureSelection);invalidateRibbon?.Invoke();}
|
||||
private void MarkDeliberateFocus(){uint process;GetWindowThreadProcessId(GetForegroundWindow(),out process);if(applyingFocus||process!=focusProcessId)return;foreach(var key in new[]{1,37,38,39,40,33,34,35,36,9})if((GetAsyncKeyState(key)&0x8000)!=0){deliberateFocusPending=true;deliberateFocusWindow=ActiveFocusWindow()?.Id??Guid.Empty;break;}}
|
||||
private Message FocusObservation(Word.Document document,int start,int end){var state=ActiveFocusWindow();var pending=deliberateFocusPending&&state?.Id==deliberateFocusWindow;deliberateFocusPending=false;bool any=false;Word.Windows windows=null;var alive=new HashSet<int>();try{windows=Com(()=>application.Windows);for(int i=1;i<=Com(()=>windows.Count);i++){Word.Window window=null;try{window=Com(()=>windows[i]);alive.Add(Com(()=>window.Hwnd));}finally{Release(window);}}foreach(var handle in focusWindows.Keys.Where(k=>!alive.Contains(k)).ToArray())focusWindows.Remove(handle);Release(windows);windows=Com(()=>document.Windows);for(int i=1;i<=Com(()=>windows.Count);i++){Word.Window window=null;try{window=Com(()=>windows[i]);if(!FocusWindow(window).Held)any=true;}finally{Release(window);}}}finally{Release(windows);}return new Message{CanSharedFocus=true,FocusWindowID=state?.Id??Guid.Empty,FocusHeld=state?.Held==true,AnyFollowingWindows=any,FocusModeRequest=state?.ModeRequest??Guid.Empty,DeliberateFocusSequence=state?.Observe(start,end,pending&&!applyingFocus)??0};}
|
||||
public void SetFocusHeld(bool held){var state=ActiveFocusWindow();if(state==null)return;state.Hold(held);focusInput.Clear();scheduler.Post("selection",CaptureSelection);invalidateRibbon?.Invoke();}
|
||||
private void MarkDeliberateFocus(){if(!applyingFocus)focusInput.Confirm();}
|
||||
private Message FocusObservation(Word.Document document,int start,int end){var state=ActiveFocusWindow();Word.Window inputWindow=null;long input=0;try{inputWindow=Com(()=>application.ActiveWindow);if(inputWindow!=null)input=focusInput.Consume(Com(()=>inputWindow.Hwnd),focusClock.ElapsedMilliseconds);}finally{Release(inputWindow);}bool any=false;Word.Windows windows=null;var alive=new HashSet<int>();try{windows=Com(()=>application.Windows);for(int i=1;i<=Com(()=>windows.Count);i++){Word.Window window=null;try{window=Com(()=>windows[i]);alive.Add(Com(()=>window.Hwnd));}finally{Release(window);}}foreach(var handle in focusWindows.Keys.Where(k=>!alive.Contains(k)).ToArray())focusWindows.Remove(handle);Release(windows);windows=Com(()=>document.Windows);for(int i=1;i<=Com(()=>windows.Count);i++){Word.Window window=null;try{window=Com(()=>windows[i]);if(!FocusWindow(window).Held)any=true;}finally{Release(window);}}}finally{Release(windows);}return new Message{CanSharedFocus=true,FocusWindowID=state?.Id??Guid.Empty,FocusHeld=state?.Held==true,AnyFollowingWindows=any,FocusModeRequest=state?.ModeRequest??Guid.Empty,DeliberateFocusSequence=state?.Observe(start,end,input>0&&!applyingFocus,input)??0};}
|
||||
private void FollowSharedFocus(Word.Document document,AdapterCommand command,Word.Range range)
|
||||
{
|
||||
Word.Windows windows=null;bool eligible=false,followed=false;applyingFocus=true;try{windows=Com(()=>document.Windows);for(int i=1;i<=Com(()=>windows.Count);i++){Word.Window window=null;try{window=Com(()=>windows[i]);var state=FocusWindow(window);if(!state.Accept(command.FocusVersion,command.FocusOriginWindowID))continue;eligible=true;Com(()=>{object atStart=true;window.ScrollIntoView(range,ref atStart);return true;});followed=true;}finally{Release(window);}}if(eligible&&!followed)throw new InvalidOperationException("Word could not follow in the background; its editing selection was retained.");}finally{applyingFocus=false;Release(windows);invalidateRibbon?.Invoke();}
|
||||
Word.Windows windows=null;bool eligible=false,followed=false;focusInput.Clear();applyingFocus=true;try{windows=Com(()=>document.Windows);for(int i=1;i<=Com(()=>windows.Count);i++){Word.Window window=null;try{window=Com(()=>windows[i]);var state=FocusWindow(window);if(!state.Accept(command.FocusVersion,command.FocusOriginWindowID))continue;eligible=true;Com(()=>{object atStart=true;window.ScrollIntoView(range,ref atStart);return true;});followed=true;}finally{Release(window);}}if(eligible&&!followed)throw new InvalidOperationException("Word could not follow in the background; its editing selection was retained.");}finally{applyingFocus=false;Release(windows);invalidateRibbon?.Invoke();}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
43
PlotDirector.NativeCompanion/Vsto/WordFocusInput.cs
Normal file
43
PlotDirector.NativeCompanion/Vsto/WordFocusInput.cs
Normal file
@ -0,0 +1,43 @@
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using PlotDirector.Companion.Protocol;
|
||||
|
||||
namespace PlotDirector.WordAddIn
|
||||
{
|
||||
public sealed partial class WordAdapter
|
||||
{
|
||||
private delegate IntPtr FocusHook(int code,IntPtr removed,IntPtr message);
|
||||
[StructLayout(LayoutKind.Sequential)]private struct FocusMessage{public IntPtr Window;public uint Message;public UIntPtr WParam;public IntPtr LParam;public uint Time;public int X,Y;public uint Private;}
|
||||
[DllImport("user32.dll",SetLastError=true)]private static extern IntPtr SetWindowsHookEx(int kind,FocusHook callback,IntPtr module,uint thread);
|
||||
[DllImport("user32.dll")]private static extern bool UnhookWindowsHookEx(IntPtr hook);
|
||||
[DllImport("user32.dll")]private static extern IntPtr CallNextHookEx(IntPtr hook,int code,IntPtr removed,IntPtr message);
|
||||
[DllImport("user32.dll")]private static extern IntPtr GetAncestor(IntPtr window,uint flag);
|
||||
[DllImport("user32.dll",CharSet=CharSet.Unicode)]private static extern int GetClassName(IntPtr window,StringBuilder text,int capacity);
|
||||
[DllImport("kernel32.dll")]private static extern uint GetCurrentThreadId();
|
||||
private readonly FocusInputState focusInput=new FocusInputState();private readonly System.Diagnostics.Stopwatch focusClock=System.Diagnostics.Stopwatch.StartNew();
|
||||
private FocusHook focusHookCallback;private IntPtr focusHook;
|
||||
private void StartFocusInput(){focusHookCallback=ObserveFocusInput;focusHook=SetWindowsHookEx(3,focusHookCallback,IntPtr.Zero,GetCurrentThreadId());}
|
||||
private IntPtr ObserveFocusInput(int code,IntPtr removed,IntPtr message)
|
||||
{
|
||||
// Thread-local, metadata only, no COM in the hook. Always continue Office's chain.
|
||||
try{if(code>=0&&removed==new IntPtr(1)){
|
||||
var input=(FocusMessage)Marshal.PtrToStructure(message,typeof(FocusMessage));
|
||||
if(applyingFocus)focusInput.Clear();
|
||||
else if(input.Message==0x0201||input.Message==0x0100){
|
||||
uint process;var root=GetAncestor(input.Window,2);GetWindowThreadProcessId(root,out process);
|
||||
if(process==focusProcessId&&root==GetAncestor(GetForegroundWindow(),2)){
|
||||
var key=(int)input.WParam.ToUInt64();var mouse=input.Message==0x0201;
|
||||
if(mouse||key>=33&&key<=40||key==9||key==13){
|
||||
var name=new StringBuilder(64);GetClassName(input.Window,name,name.Capacity);var body=name.ToString()=="_WwG";
|
||||
if(!mouse&&key==13&&body)focusInput.Clear();
|
||||
else{focusInput.Record(root.ToInt32(),focusClock.ElapsedMilliseconds,mouse&&body);if(mouse&&body)ScheduleSelection();}
|
||||
}else focusInput.Clear();
|
||||
}
|
||||
}else if(input.Message==0x0102||input.Message==0x010D||input.Message==0x020A||input.Message==0x020E)focusInput.Clear();
|
||||
}}catch{focusInput.Clear();}
|
||||
return CallNextHookEx(focusHook,code,removed,message);
|
||||
}
|
||||
private void StopFocusInput(){focusInput.Clear();if(focusHook!=IntPtr.Zero){UnhookWindowsHookEx(focusHook);focusHook=IntPtr.Zero;}focusHookCallback=null;}
|
||||
}
|
||||
}
|
||||
@ -1,7 +1,7 @@
|
||||
{
|
||||
"version": "1.0.0.45",
|
||||
"msiVersion": "1.0.45",
|
||||
"productCode": "{C9797E15-A318-48BF-95B8-1769AEBCA565}",
|
||||
"version": "1.0.0.46",
|
||||
"msiVersion": "1.0.46",
|
||||
"productCode": "{BEEA290D-63A3-48EF-A8C9-753B9FBA92DA}",
|
||||
"upgradeCode": "{641A087B-9779-458C-B290-BCBBAD49319A}",
|
||||
"atlasBaseline": "9fed339879887964d526cff00772ffc4dc522c5d",
|
||||
"baselineProductCode": "{98F46939-764D-407F-BD1F-1D88315D010A}",
|
||||
|
||||
17
PlotLine.Tests/Browser/shared-focus-reliability.cjs
Normal file
17
PlotLine.Tests/Browser/shared-focus-reliability.cjs
Normal file
@ -0,0 +1,17 @@
|
||||
// Isolated production asset; deterministic transport/read ordering, no account or manuscript.
|
||||
const {chromium}=require('playwright'),fs=require('node:fs'),path=require('node:path'),assert=require('node:assert/strict');
|
||||
const script=fs.readFileSync(path.join(__dirname,'../../PlotLine/wwwroot/js/shared-manuscript-focus.js'),'utf8');
|
||||
(async()=>{const browser=await chromium.launch({channel:'chrome'});try{
|
||||
const page=await browser.newPage();await page.route('https://fixture.invalid/**',r=>r.fulfill({body:'<body data-pd-user-id="7"><div data-narrative-focus><script data-narrative-initial type="application/json">{"projectID":3,"bookID":12,"chapterID":1}</script></div><input name="__RequestVerificationToken" value="fixture"><button data-shared-focus-hold><span>Hold</span></button><p data-shared-focus-status hidden></p></body>',contentType:'text/html'}));await page.goto('https://fixture.invalid/');
|
||||
await page.evaluate(()=>{window.reads=[];window.posts=[];window.moves=[];window.notices=[];window.PlotDirector={toast:{warning:m=>notices.push(m)}};window.addEventListener('plotdirector:shared-focus',e=>moves.push(e.detail));window.fetch=(url,options={})=>{if(options.method==='POST'){posts.push({url,body:String(options.body)});return Promise.resolve({ok:true,json:async()=>({...fixture,version:10})});}return new Promise(resolve=>reads.push({resolve,signal:options.signal}));};window.handlers={};window.lifecycle={};window.fixture={projectID:3,bookID:12,chapterID:1,sceneID:10,version:1,isValid:true};window.conn={state:'Disconnected',connectionId:null,on:(n,f)=>handlers[n]=f,onreconnecting:f=>lifecycle.reconnecting=f,onclose:f=>lifecycle.close=f,onreconnected:f=>lifecycle.reconnected=f};window.PlotDirectorPresenceConnection=conn;window.respond=(i,p)=>reads[i].resolve({ok:true,json:async()=>({...fixture,...p})});});
|
||||
await page.addScriptTag({content:script});
|
||||
assert.equal(await page.evaluate(()=>reads.length),0,'no authoritative read before group join');assert.equal(await page.getByRole('button',{name:'Hold',exact:true}).isEnabled(),false);
|
||||
await page.evaluate(()=>{conn.state='Connected';conn.connectionId='first';document.dispatchEvent(new Event('pd-presence-ready'));document.dispatchEvent(new Event('pd-presence-ready'));});assert.equal(await page.evaluate(()=>reads.length),1,'first ready rereads once');
|
||||
await page.evaluate(()=>{handlers.ManuscriptFocusChanged({...fixture,version:3,sceneID:30});respond(0,{version:2,sceneID:20});});await page.waitForFunction(()=>PlotDirectorSharedFocus.shared?.version===3&&document.querySelector('button').disabled===false);assert.equal(await page.evaluate(()=>PlotDirectorSharedFocus.local.sceneID),30,'late startup snapshot cannot overwrite notification');console.log('PASS initial connection race, coalescing and revision reconciliation');
|
||||
await page.getByRole('button',{name:'Hold',exact:true}).click();assert.equal(await page.getByRole('button',{name:'Release Hold',exact:true}).getAttribute('aria-pressed'),'true');const moves=await page.evaluate(()=>window.moves.length);
|
||||
await page.evaluate(()=>{conn.state='Reconnecting';lifecycle.reconnecting();});assert.equal(await page.getByRole('button',{name:'Release Hold',exact:true}).isEnabled(),false);
|
||||
await page.evaluate(()=>{conn.state='Connected';conn.connectionId='second';lifecycle.reconnected();document.dispatchEvent(new Event('pd-presence-ready'));respond(1,{version:4,sceneID:40});});await page.waitForFunction(()=>PlotDirectorSharedFocus.shared?.version===4&&document.querySelector('button').disabled===false);assert.equal(await page.evaluate(()=>window.moves.length),moves,'held recovery must retain local position');assert.equal(await page.evaluate(()=>PlotDirectorSharedFocus.local.sceneID),30);
|
||||
await page.getByRole('button',{name:'Release Hold',exact:true}).press('Enter');await page.waitForFunction(()=>reads.length===3);await page.evaluate(()=>respond(2,{version:5,sceneID:50}));await page.waitForFunction(()=>PlotDirectorSharedFocus.local.sceneID===50&&!PlotDirectorSharedFocus.held);assert.equal(await page.evaluate(()=>posts.length),1,'only held reference validation posts; release cannot publish');assert(await page.evaluate(()=>posts.every(p=>!p.url.endsWith('/Publish'))));assert.equal(await page.getByRole('button',{name:'Hold',exact:true}).getAttribute('aria-pressed'),'false');console.log('PASS reconnect preserves Hold; keyboard Release catches latest without publication');
|
||||
await page.evaluate(()=>{void PlotDirectorSharedFocus.refresh();conn.state='Reconnecting';lifecycle.reconnecting();conn.state='Connected';conn.connectionId='third';lifecycle.reconnected();respond(3,{version:99,sceneID:99});respond(4,{version:6,sceneID:60});});await page.waitForFunction(()=>PlotDirectorSharedFocus.shared?.version===6);assert.equal(await page.evaluate(()=>PlotDirectorSharedFocus.local.sceneID),60,'abandoned transport cannot overwrite new connection');console.log('PASS disconnected read cancellation and new group recovery');
|
||||
const partial=fs.readFileSync(path.join(__dirname,'../../PlotLine/Views/Shared/_FocusFollowControl.cshtml'),'utf8');assert(!partial.includes('data-shared-focus-status'));assert(!partial.includes('Following'));assert(partial.includes('disabled'));const ribbon=fs.readFileSync(path.join(__dirname,'../../PlotDirector.NativeCompanion/Vsto/Ribbon.xml'),'utf8');assert(!ribbon.includes('PlotDirectorFocusState'));assert(ribbon.includes('getEnabled="CanHoldFocus"'));console.log('PASS concise accessible toggle and no adjacent state controls');
|
||||
}finally{await browser.close();}})().catch(e=>{console.error(e);process.exitCode=1;});
|
||||
@ -30,7 +30,7 @@ public sealed class SharedManuscriptFocus(ISqlConnectionFactory factory,IHubCont
|
||||
{
|
||||
using var db=factory.CreateConnection();var result=await db.QuerySingleAsync<SharedFocusPosition>("dbo.NarrativeFocus_Coordinate",new{Action=action,UserID=user,request.ProjectID,request.BookID,request.WindowID,request.Sequence,request.ChapterID,request.SceneID,request.ParagraphID,request.ManuscriptID,request.Direction},commandType:CommandType.StoredProcedure);
|
||||
if(action!="read")diagnostics?.Write(user,request.BookID,action+"-result",request.WindowID,request.Sequence,chapter:result.ChapterID,scene:result.SceneID,paragraph:result.ParagraphID,version:result.Version,outcome:result.Changed?"changed":result.IsValid?"unchanged":"invalid");
|
||||
if(result.Changed){try{await hub.Clients.Group(NativeCompanionPresenceHub.UserGroup(user)).SendAsync("ManuscriptFocusChanged",result);}catch(Exception e){logger.LogWarning("Focus notification unavailable: {Type}",e.GetType().Name);}foreach(var lease in native.Read(user,result.BookID).Where(l=>l.Position.CanSharedFocus))try{await FollowWord(user,result,lease);}catch(Exception e){logger.LogWarning("Word focus delivery unavailable: {Type}",e.GetType().Name);}}
|
||||
if(result.Changed){try{await hub.Clients.Group(NativeCompanionPresenceHub.UserGroup(user)).SendAsync("ManuscriptFocusChanged",result);diagnostics?.Write(user,result.BookID,"signalr-send",request.WindowID,request.Sequence,chapter:result.ChapterID,scene:result.SceneID,paragraph:result.ParagraphID,version:result.Version,outcome:"user-group-dispatched");}catch(Exception e){logger.LogWarning("Focus notification unavailable: {Type}",e.GetType().Name);}foreach(var lease in native.Read(user,result.BookID).Where(l=>l.Position.CanSharedFocus))try{await FollowWord(user,result,lease);}catch(Exception e){logger.LogWarning("Word focus delivery unavailable: {Type}",e.GetType().Name);}}
|
||||
return result;
|
||||
}
|
||||
public async Task<FocusWordPosition?> WordPosition(int user,NativeLease lease,string action,SharedFocusPosition? focus=null)
|
||||
|
||||
@ -1,2 +1,2 @@
|
||||
@{var embedded=ViewContext.RouteData.Values["controller"]?.ToString()=="Writing";}
|
||||
<button type="button" class="@(embedded?"btn btn-outline-secondary btn-sm":"pd-ribbon-command")" data-shared-focus-hold aria-pressed="false" title="Hold this window independently; saved data continues updating"><svg class="pd-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="M8 4v16 M16 4v16"/></svg><span>Following · Hold</span></button><span class="small" data-shared-focus-status role="status"></span>
|
||||
<button type="button" class="@(embedded?"btn btn-outline-secondary btn-sm":"pd-ribbon-command")" data-shared-focus-hold aria-pressed="false" disabled title="Shared focus is connecting. Your local position is retained."><svg class="pd-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="M8 4v16 M16 4v16"/></svg><span>Hold</span></button>
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
<dialog id="writing-connection-details" class="writing-connection-dialog" aria-labelledby="writing-connection-title">
|
||||
<div class="d-flex justify-content-between gap-3"><h2 id="writing-connection-title" class="h5">Word connection</h2><button type="button" class="btn btn-outline-secondary btn-sm" data-close-word-details>Close</button></div>
|
||||
<p data-shared-focus-status role="status" hidden></p>
|
||||
<p data-word-connection-description>Checking the Companion’s authenticated document heartbeat…</p>
|
||||
<div data-word-document-picker>
|
||||
<label for="writing-word-document">Document to follow</label>
|
||||
|
||||
@ -25,7 +25,7 @@
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm" data-context-new>New Context window</button>
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm" data-context-refresh>Refresh saved data</button>
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm" data-context-windows>My Windows</button>
|
||||
<p data-context-status role="status">@(Model.Display?.FollowStatus ?? "Waiting for a saved scene")</p>
|
||||
<p data-context-status role="status" hidden></p>
|
||||
</header>
|
||||
<nav class="context-navigation" aria-label="Saved manuscript scenes">
|
||||
<label>Scene <select data-context-scene class="form-select form-select-sm"><option value="">Choose a saved scene</option>@foreach(var item in Model.Display?.SceneOptions ?? []){<option value="@item.Value" selected="@item.Selected">@item.Text</option>}</select></label>
|
||||
|
||||
@ -858,13 +858,11 @@ html[data-app-theme] .scenario-workspace :is(h1, h2, h3) {
|
||||
.scenario-workspace .attention-list p { grid-column: 1 / -1; }
|
||||
.scenario-workspace .scenario-warning-badge { justify-self: start; }
|
||||
/* Static focus commands reserve their width in both modes; no delayed ribbon insertion. */
|
||||
.pd-shell [data-shared-focus-hold]{width:104px;min-width:104px;max-width:104px}
|
||||
.pd-ribbon-focus [data-shared-focus-status]{width:140px;min-width:140px;max-height:68px;overflow:auto;white-space:normal;overflow-wrap:anywhere;font-size:11px;line-height:1.2;align-self:center}
|
||||
[data-context-workspace] [data-shared-focus-hold]{min-width:190px}
|
||||
.pd-shell [data-shared-focus-hold]{width:120px;min-width:120px;max-width:120px}
|
||||
[data-context-workspace] [data-shared-focus-hold]{width:120px;min-width:120px;max-width:120px}
|
||||
|
||||
/* Hold remains visible when the PWA compacts Previous/Go/Next into its existing menu. */
|
||||
.pd-shell .pd-ribbon-focus{display:grid;grid-template-columns:auto auto;grid-template-rows:1fr auto;column-gap:4px}
|
||||
.pd-ribbon-focus-mode{grid-column:1;grid-row:1;display:flex;align-items:flex-start;gap:4px}
|
||||
.pd-ribbon-focus>.pd-ribbon-commands,.pd-ribbon-focus>.pd-base-overflow{grid-column:2;grid-row:1}
|
||||
.pd-ribbon-focus>.pd-ribbon-group-label{grid-column:1/-1;grid-row:2}
|
||||
@media(max-width:760px){.pd-ribbon-focus [data-shared-focus-status]{width:90px;min-width:90px}}
|
||||
|
||||
@ -181,8 +181,8 @@
|
||||
const record=current(pane);if(!record)return;record.dirty=!!event.detail?.dirty;record.busy=!!event.detail?.busy;if(!guarded(record)&&record.stale&&!event.detail?.deferRefresh)void refreshPane(pane);announce();
|
||||
});
|
||||
}
|
||||
async function navigate(sceneId){const id=number(sceneId);if(!id)return;if(windowBusy||panes.some(p=>guarded(current(p)))){status.textContent='Save or cancel the current editor before changing manuscript position.';return;}if(!window.PlotDirectorSharedFocus){status.textContent='Focus is initialising; retry this selection.';return;}const moved=await window.PlotDirectorSharedFocus.navigate({projectID:scope.projectId,bookID:scope.bookId,sceneID:id});if(!moved)sceneSelect.value=position.sceneId||'';}
|
||||
function sharedPosition(event){const p=event.detail.position;setPosition({projectId:p.projectID,bookId:p.bookID,chapterId:p.chapterID,sceneId:p.sceneID,paragraphId:p.paragraphID});status.textContent=window.PlotDirectorSharedFocus?.held?'Held at local manuscript position · saved data remains live':'Following shared manuscript focus · saved reference data';}
|
||||
async function navigate(sceneId){const id=number(sceneId);if(!id)return;if(windowBusy||panes.some(p=>guarded(current(p)))){status.hidden=false;status.textContent='Save or cancel the current editor before changing manuscript position.';return;}if(!window.PlotDirectorSharedFocus){status.hidden=false;status.textContent='Focus is initialising; retry this selection.';return;}const moved=await window.PlotDirectorSharedFocus.navigate({projectID:scope.projectId,bookID:scope.bookId,sceneID:id});if(!moved)sceneSelect.value=position.sceneId||'';}
|
||||
function sharedPosition(event){const p=event.detail.position;setPosition({projectId:p.projectID,bookId:p.bookID,chapterId:p.chapterID,sceneId:p.sceneID,paragraphId:p.paragraphID});status.textContent='';status.hidden=true;}
|
||||
window.addEventListener('plotdirector:shared-focus',sharedPosition);
|
||||
root.querySelector('[data-context-go-focus]')?.addEventListener('click',()=>void window.PlotDirectorSharedFocus?.go());
|
||||
sceneSelect.addEventListener('change',event=>void navigate(sceneSelect.value,event.isTrusted));
|
||||
@ -196,16 +196,16 @@
|
||||
async function startConnection(){
|
||||
if(stopped||connectionStarting||!connection||connection.state&&connection.state!=='Disconnected')return;
|
||||
connectionStarting=true;
|
||||
try{await connection.start();wakeStatus(true);void recoverOffice(true);root.dispatchEvent(new Event('context-connection-ready'));}catch{status.textContent='Context notifications disconnected · retrying; saved browsing remains available';}finally{connectionStarting=false;}
|
||||
try{await connection.start();wakeStatus(true);void recoverOffice(true);root.dispatchEvent(new Event('context-connection-ready'));}catch{status.hidden=false;status.textContent='Context notifications disconnected · retrying; saved browsing remains available';}finally{connectionStarting=false;}
|
||||
}
|
||||
if(window.signalR){
|
||||
connection=new signalR.HubConnectionBuilder().withUrl('/hubs/native-companion').withAutomaticReconnect().build();
|
||||
connection.on('NativePresenceChanged',hint=>{window.dispatchEvent(new CustomEvent('plotdirector:native-presence-changed',{detail:hint}));wakeStatus();});
|
||||
connection.on('ContextPositionChanged',()=>void recoverOffice());
|
||||
connection.on('ContextInvalidated',hint=>{invalidate(hint);if(hint.kind==='structure')void refreshStructure();wakeStatus();});
|
||||
connection.onreconnecting(()=>status.textContent='Context notifications reconnecting · saved reference may be stale');
|
||||
connection.onreconnecting(()=>{status.hidden=false;status.textContent='Context notifications reconnecting · saved reference may be stale';});
|
||||
connection.onreconnected(()=>{wakeStatus(true);void recoverOffice(true);invalidate();root.dispatchEvent(new Event('context-connection-ready'));});
|
||||
connection.onclose(()=>status.textContent='Context notifications disconnected · saved browsing remains available');
|
||||
connection.onclose(()=>{status.hidden=false;status.textContent='Context notifications disconnected · saved browsing remains available';});
|
||||
void startConnection();
|
||||
}
|
||||
const timer=setInterval(()=>{void startConnection();announce();},15000);
|
||||
@ -233,5 +233,5 @@
|
||||
root.contextController={ get windowId(){return windowId;}, get position(){return {...position};}, invalidate,setPosition,get connection(){return connection;},get announcement(){return {version:1,bookID:position.bookId,windowID:windowId,panes:panes.filter(visible).map(pane=>({paneID:String(pane.index),toolID:state.panes[pane.index].tab,actions:registry.get(state.panes[pane.index].tab).actions||[],available:!windowBusy&&!!current(pane)?.node&&!current(pane).stale&&!guarded(current(pane))}))};},receiveInteraction:async delivery=>{if(windowBusy)return 'busy';const pane=panes.find(p=>String(p.index)===delivery.paneID);if(!pane||!visible(pane))return 'not-visible';const record=current(pane);if(guarded(record))return 'busy';if(!record?.node||record.stale)return 'unavailable';record.stale=true;await refreshPane(pane);if(record.stale||guarded(record))return 'unavailable';return await lifecycles[record.tab.lifecycle]?.onInteraction?.(record.node,delivery.command,{position:{...position},pane})||'not-visible';},registerLifecycle:(name,hooks)=>lifecycles[name]=hooks };
|
||||
window.addEventListener('pagehide',()=>{stopped=true;panes.forEach(pane=>{remember(pane);dispose(current(pane));});save();cancelRequests();navigationRequest?.abort();clearInterval(timer);observer.disconnect();channel?.close();void connection?.stop();});
|
||||
save();applyLayout();
|
||||
status.textContent='Shared manuscript focus initialising · local saved data remains available';
|
||||
status.textContent='';status.hidden=true;
|
||||
})();
|
||||
|
||||
@ -1,13 +1,16 @@
|
||||
// One user/book/canonical-manuscript focus stream over the window's existing presence connection.
|
||||
(()=>{'use strict';function start(){const context=document.querySelector('[data-context-workspace]'),header=document.querySelector('[data-narrative-focus]'),reader=document.querySelector('.manuscript-reader');if(!context&&!header)return;const initial=window.PlotDirectorNarrativeFocus?.state||(header?JSON.parse(header.querySelector('[data-narrative-initial]').textContent):{});let project=Number(context?.dataset.scopeProjectId||initial.projectID),book=Number(context?.dataset.scopeBookId||initial.bookID),connection,disconnected=false,latest=null,local=null,epoch=0,sequence=0,held=false,publishing=false,selectionPublishing=false,queuedTarget=null;const user=document.body.dataset.pdUserId||context?.dataset.user||'',page=crypto.randomUUID(),buttons=[...document.querySelectorAll('[data-shared-focus-hold]')],outputs=[...document.querySelectorAll('[data-shared-focus-status]')];let id=context?.contextController?.windowId||sessionStorage.getItem('pd.shared-focus.window');if(!/^[\da-f-]{36}$/i.test(id||''))id=crypto.randomUUID();sessionStorage.setItem('pd.shared-focus.window',id);const normal=p=>({projectID:Number(p.projectID||p.projectId||project),bookID:Number(p.bookID||p.bookId||book),chapterID:Number(p.chapterID||p.chapterId)||null,sceneID:Number(p.sceneID||p.sceneId)||null,paragraphID:p.paragraphID||p.paragraphId||null,manuscriptID:p.manuscriptID||p.manuscriptId||null,originWindowID:p.originWindowID||p.originWindowId||null,version:Number(p.version||0),isValid:p.isValid!==false});const key=()=>`pd.shared-focus.${user}.${id}`;const positionKey=p=>p&&[p.projectID,p.bookID,p.manuscriptID,p.chapterID,p.sceneID,p.paragraphID].join('/');function save(){try{sessionStorage.setItem(key(),JSON.stringify({held,local,sequence}));}catch{}}function restore(){try{const data=JSON.parse(sessionStorage.getItem(key())||'null');held=data?.held??context?.dataset.followMode==='snapshot';local=data?.local||normal(context?.contextController?.position||{...initial,chapterID:Number(reader?.dataset.chapterId)||initial.chapterID});sequence=data?.sequence||0;}catch{held=false;}}
|
||||
function status(message=''){buttons.forEach(b=>{(b.querySelector('span')||b).textContent=held?'Held · Release Hold':'Following · Hold';b.setAttribute('aria-pressed',String(held));b.disabled=!book;});outputs.forEach(n=>n.textContent=message||(held?'Held at local manuscript position · data updates remain live':'Following shared manuscript focus'));document.documentElement.dataset.manuscriptFocusMode=held?'held':'follow';}function apply(position,reason){local=normal(position);save();window.dispatchEvent(new CustomEvent('plotdirector:shared-focus',{detail:{position:local,reason}}));status();}function accept(packet,force=false,metadata=false){const next=normal(packet);if(next.bookID!==book||next.projectID!==project)return false;if(latest&&next.version<latest.version)return false;if(latest&&!force&&next.version===latest.version){if(metadata&&latest.isValid!==next.isValid){latest={...latest,isValid:next.isValid};if(!held)status(next.isValid?'':'Shared focus is unavailable. Select a valid chapter or scene; your local position is retained.');}return false;}latest=next;if(publishing&&queuedTarget)return true;if(!held&&next.isValid&&next.chapterID&&(force||positionKey(local)!==positionKey(next)))apply(next,next.originWindowID===id&&selectionPublishing?'selection':'shared');else if(!held&&next.isValid&&next.chapterID)status();else if(!next.isValid&&!held)status('Shared focus is unavailable. Select a valid chapter or scene; your local position is retained.');return true;}
|
||||
async function request(action,target={}){const token=document.querySelector('[name=__RequestVerificationToken]')?.value;if(!token)throw Error('Refresh this authenticated window before changing focus.');const body=new URLSearchParams({projectID:project,bookID:book,windowID:id,sequence:++sequence,__RequestVerificationToken:token});for(const[k,v]of Object.entries(target))if(v!=null&&['chapterID','sceneID','paragraphID','manuscriptID','direction'].includes(k))body.set(k,v);save();const response=await fetch('/NarrativeFocus/Shared/'+action,{method:'POST',body,cache:'no-store'});const packet=await response.json().catch(()=>null);if(!response.ok||response.redirected)throw Error(packet?.message||'Focus could not be changed. Your local reference is retained.');return normal(packet);}
|
||||
async function refresh(force=false){if(!book)return;const mine=++epoch;try{const response=await fetch(`/NarrativeFocus/Shared?projectID=${project}&bookID=${book}`,{cache:'no-store'});if(!response.ok||response.redirected)throw Error();const packet=await response.json();if(mine===epoch){const recovering=disconnected;disconnected=false;accept(packet,force,true);if(recovering){status(!held&&latest?.isValid===false?'Shared focus is unavailable. Select another position; your local reference is retained.':'');void validateLocal();}return true;}return false;}catch{disconnected=true;status('Shared focus disconnected · local position and data are retained. Reconnect to catch up.');return false;}}
|
||||
(()=>{'use strict';function start(){const context=document.querySelector('[data-context-workspace]'),header=document.querySelector('[data-narrative-focus]'),reader=document.querySelector('.manuscript-reader');if(!context&&!header)return;const initial=window.PlotDirectorNarrativeFocus?.state||(header?JSON.parse(header.querySelector('[data-narrative-initial]').textContent):{});let project=Number(context?.dataset.scopeProjectId||initial.projectID),book=Number(context?.dataset.scopeBookId||initial.bookID),connection,connected=false,authoritative=false,readFlight=null,readAbort=null,readyKey=null,generation=0,disconnected=false,latest=null,local=null,epoch=0,sequence=0,held=false,publishing=false,selectionPublishing=false,queuedTarget=null;const user=document.body.dataset.pdUserId||context?.dataset.user||'',page=crypto.randomUUID(),buttons=[...document.querySelectorAll('[data-shared-focus-hold]')],outputs=[...document.querySelectorAll('[data-shared-focus-status]')];let id=context?.contextController?.windowId||sessionStorage.getItem('pd.shared-focus.window');if(!/^[\da-f-]{36}$/i.test(id||''))id=crypto.randomUUID();sessionStorage.setItem('pd.shared-focus.window',id);const normal=p=>({projectID:Number(p.projectID||p.projectId||project),bookID:Number(p.bookID||p.bookId||book),chapterID:Number(p.chapterID||p.chapterId)||null,sceneID:Number(p.sceneID||p.sceneId)||null,paragraphID:p.paragraphID||p.paragraphId||null,manuscriptID:p.manuscriptID||p.manuscriptId||null,originWindowID:p.originWindowID||p.originWindowId||null,version:Number(p.version||0),isValid:p.isValid!==false});const key=()=>`pd.shared-focus.${user}.${id}`;const positionKey=p=>p&&[p.projectID,p.bookID,p.manuscriptID,p.chapterID,p.sceneID,p.paragraphID].join('/');function save(){try{sessionStorage.setItem(key(),JSON.stringify({held,local,sequence}));}catch{}}function restore(){try{const data=JSON.parse(sessionStorage.getItem(key())||'null');held=data?.held??context?.dataset.followMode==='snapshot';local=data?.local||normal(context?.contextController?.position||{...initial,chapterID:Number(reader?.dataset.chapterId)||initial.chapterID});sequence=data?.sequence||0;}catch{held=false;}}
|
||||
const traceEnabled=new URLSearchParams(location.search).get('focusDiagnostics')==='1',traceRows=[];function trace(stage,outcome,p=latest){if(!traceEnabled)return;traceRows.push({stage,outcome,source:context?'Context':'Review',windowID:id,bookID:book,chapterID:p?.chapterID,sceneID:p?.sceneID,paragraphID:p?.paragraphID,version:p?.version,held});if(traceRows.length>128)traceRows.shift();let panel=document.querySelector('[data-focus-diagnostics]');if(!panel){panel=document.createElement('pre');panel.dataset.focusDiagnostics='';document.body.append(panel);}panel.textContent=JSON.stringify(traceRows,null,2);}
|
||||
let lastNotice='';function status(message=''){const available=!!book&&connected&&authoritative&&!disconnected;buttons.forEach(b=>{(b.querySelector('span')||b).textContent=held?'Release Hold':'Hold';b.setAttribute('aria-pressed',String(held));b.disabled=!available;b.classList.toggle('active',held);b.title=!available?(book?'Shared focus is connecting. Your local position is retained.':'Select a book first.'):(held?'Catch up to the latest shared manuscript position.':'Hold this window at its local manuscript position.');});outputs.forEach(n=>{n.textContent=message;n.hidden=!message;});document.documentElement.dataset.manuscriptFocusMode=held?'held':'follow';if(message&&message!==lastNotice){lastNotice=message;window.PlotDirector?.toast?.warning?.(message);}if(!message)lastNotice='';}function apply(position,reason){local=normal(position);save();trace('reconcile',reason,local);window.dispatchEvent(new CustomEvent('plotdirector:shared-focus',{detail:{position:local,reason}}));status();}function accept(packet,force=false,metadata=false){const next=normal(packet);if(next.bookID!==book||next.projectID!==project)return false;if(latest&&next.version<latest.version){trace('reconcile','stale-revision',next);return false;}if(latest&&!force&&next.version===latest.version){if(metadata&&latest.isValid!==next.isValid){latest={...latest,isValid:next.isValid};if(!held)status(next.isValid?'':'Shared focus is unavailable. Select a valid chapter or scene; your local position is retained.');}return false;}latest=next;if(publishing&&queuedTarget)return true;if(!held&&next.isValid&&next.chapterID&&(force||positionKey(local)!==positionKey(next)))apply(next,next.originWindowID===id&&selectionPublishing?'selection':'shared');else if(!held&&next.isValid&&next.chapterID)status();else if(!next.isValid&&!held)status('Shared focus is unavailable. Select a valid chapter or scene; your local position is retained.');return true;}
|
||||
async function request(action,target={}){trace('request',action,normal(target));const token=document.querySelector('[name=__RequestVerificationToken]')?.value;if(!token)throw Error('Refresh this authenticated window before changing focus.');const body=new URLSearchParams({projectID:project,bookID:book,windowID:id,sequence:++sequence,__RequestVerificationToken:token});for(const[k,v]of Object.entries(target))if(v!=null&&['chapterID','sceneID','paragraphID','manuscriptID','direction'].includes(k))body.set(k,v);save();const response=await fetch('/NarrativeFocus/Shared/'+action,{method:'POST',body,cache:'no-store'});const packet=await response.json().catch(()=>null);if(!response.ok||response.redirected)throw Error(packet?.message||'Focus could not be changed. Your local reference is retained.');return normal(packet);}
|
||||
function invalidateRead(){epoch++;generation++;readAbort?.abort();readAbort=null;readFlight=null;authoritative=false;}
|
||||
function refresh(force=false){if(!book||!connected)return Promise.resolve(false);if(readFlight)return readFlight;const mine=++epoch,scope=book,transport=generation;readAbort=new AbortController();const signal=readAbort.signal;trace('read','started');const task=(async()=>{try{const response=await fetch(`/NarrativeFocus/Shared?projectID=${project}&bookID=${book}`,{cache:'no-store',signal});if(!response.ok||response.redirected)throw Error();const packet=await response.json();if(mine!==epoch||scope!==book||transport!==generation)return false;const recovering=disconnected;disconnected=false;authoritative=true;accept(packet,force,true);status(!held&&latest?.isValid===false?'Shared focus is unavailable. Select another position; your local reference is retained.':'');trace('read','reconciled');if(recovering)void validateLocal();return true;}catch(error){if(signal.aborted)return false;if(mine===epoch){disconnected=true;status('Shared focus disconnected. Your local position is retained.');trace('read','failed');}return false;}finally{if(readFlight===task){readFlight=null;readAbort=null;}}})();readFlight=task;return task;}
|
||||
async function navigate(target,forcePublication=false){const priorLocal=local;if(target.localSelection&&Number(target.bookID||book)===book){local=normal({...local,projectID:project,bookID:book,chapterID:target.chapterID,sceneID:target.sceneID||null,paragraphID:target.paragraphID});save();}if(publishing){queuedTarget=target;return true;}const effective=held?priorLocal:latest?.isValid?latest:null;if(!forcePublication&&Number(target.sceneID||target.sceneId)>0&&Number(target.sceneID||target.sceneId)===effective?.sceneID&&!effective.paragraphID&&!target.paragraphID&&!target.paragraphId)return true;if(!forcePublication&&!target.direction&&!target.sceneID&&!target.sceneId&&!target.paragraphID&&!target.paragraphId&&Number(target.chapterID||target.chapterId)>0&&Number(target.chapterID||target.chapterId)===effective?.chapterID&&!effective.sceneID&&!effective.paragraphID)return true;const paragraph=target.paragraphID||target.paragraphId;if(!forcePublication&¶graph&¶graph===effective?.paragraphID&&Number(target.chapterID||target.chapterId)===effective.chapterID)return true;if(publishing)return false;if(target.bookID&&Number(target.bookID)!==book)return false;publishing=true;const localRequest=held;selectionPublishing=target.localSelection===true;try{const normalized={chapterID:target.chapterID||target.chapterId||null,sceneID:target.sceneID||target.sceneId||null,paragraphID:target.paragraphID||target.paragraphId||null,...(target.direction?{direction:target.direction}:{}),...(target.manuscriptID?{manuscriptID:target.manuscriptID}:{})};if(held&&target.direction)Object.assign(normalized,{chapterID:local.chapterID,sceneID:local.sceneID,paragraphID:local.paragraphID});const result=await request(localRequest?'Resolve':'Publish',normalized);if(result.bookID!==book||result.projectID!==project)return false;if(localRequest){if(held)apply(result,selectionPublishing?'selection':'local');else await refresh(true);}else accept(result,true);return true;}catch(error){status(error.message);return false;}finally{publishing=false;selectionPublishing=false;if(queuedTarget){const next=queuedTarget;queuedTarget=null;void navigate(next,true);}}}
|
||||
async function toggle(){queuedTarget=null;if(held){if(!await refresh()){status('Hold retained: reconnect before catching up to authoritative shared focus.');return;}held=false;save();if(latest?.isValid&&latest.chapterID)apply(latest,'release');else status('Following · no valid shared focus; local position retained.');}else{held=true;save();status();}window.dispatchEvent(new CustomEvent('plotdirector:focus-mode',{detail:{held}}));}
|
||||
async function toggle(){if(!connected||!authoritative||disconnected)return;queuedTarget=null;if(held){if(!await refresh()){status('Hold retained: reconnect before catching up to authoritative shared focus.');return;}held=false;save();if(latest?.isValid&&latest.chapterID)apply(latest,'release');else status('Following · no valid shared focus; local position retained.');}else{held=true;save();status();}window.dispatchEvent(new CustomEvent('plotdirector:focus-mode',{detail:{held}}));}
|
||||
async function validateLocal(){if(!held||!local?.chapterID)return;try{const result=await request('Validate',local);if(!result.isValid)status('Held reference is no longer valid. Select another local position or Release Hold.');}catch{status('Held reference cannot be resolved. Select another position; data updates remain connected.');}}
|
||||
function wire(c){if(!c||connection)return;connection=c;c.on('ManuscriptFocusChanged',packet=>accept(packet));c.on('ManuscriptFocusDelivery',packet=>{if(Number(packet.bookID||packet.bookId)===book&&Number(packet.version)===latest?.version)status('Word cannot follow this reference in the background. Save and synchronise Word; other windows remain independent.');});c.on('ContextInvalidated',hint=>{if(hint.bookId&&Number(hint.bookId)!==book||hint.projectId&&Number(hint.projectId)!==project)return;window.dispatchEvent(new CustomEvent('plotdirector:reference-invalidated',{detail:hint}));void validateLocal();});c.onreconnecting(()=>{disconnected=true;status('Shared focus reconnecting · local position retained.');});c.onclose(()=>{disconnected=true;status('Shared focus disconnected · local position retained.');});c.onreconnected(()=>{void refresh().then(()=>validateLocal());});void refresh();}
|
||||
function ready(c,reconnected=false){if(!c||c!==connection||c.state!=='Connected')return;connected=true;const key=c.connectionId||'connected';if(!reconnected&&readyKey===key){if(!authoritative)void refresh();return;}readyKey=key;invalidateRead();status();trace('connection',reconnected?'reconnected':'ready');void refresh();}
|
||||
function wire(c){if(!c||connection===c)return;if(connection)return;connection=c;c.on('ManuscriptFocusChanged',packet=>{trace('notification','received',normal(packet));accept(packet);});c.on('ManuscriptFocusDelivery',packet=>{if(Number(packet.bookID||packet.bookId)===book&&Number(packet.version)===latest?.version)status('Word cannot follow this reference in the background. Save and synchronise Word; other windows remain independent.');});c.on('ContextInvalidated',hint=>{if(hint.bookId&&Number(hint.bookId)!==book||hint.projectId&&Number(hint.projectId)!==project)return;window.dispatchEvent(new CustomEvent('plotdirector:reference-invalidated',{detail:hint}));void validateLocal();});function offline(){connected=false;disconnected=true;readyKey=null;invalidateRead();status('Shared focus disconnected. Your local position is retained.');trace('connection','disconnected');}c.onreconnecting(offline);c.onclose(offline);c.onreconnected(()=>ready(c,true));ready(c);}
|
||||
const channel=!context&&window.BroadcastChannel?new BroadcastChannel('pd.shared-focus.identity.'+user):null;channel?.addEventListener('message',event=>{const m=event.data;if(m.id!==id||m.page===page)return;if(m.kind==='claim')channel.postMessage({kind:'occupied',id,page,target:m.page});if(m.kind==='occupied'&&m.target===page){id=crypto.randomUUID();sessionStorage.setItem('pd.shared-focus.window',id);held=false;sequence=0;save();status();void refresh(true);}});channel?.postMessage({kind:'claim',id,page});
|
||||
context?.addEventListener('context-capabilities-changed',()=>{const next=context.contextController?.windowId;if(next&&next!==id){id=next;held=false;sequence=0;save();status();void refresh(true);}});
|
||||
restore();status();buttons.forEach(b=>b.addEventListener('click',()=>void toggle()));document.addEventListener('pd-presence-connection',e=>wire(e.detail));document.addEventListener('pd-presence-ready',()=>wire(window.PlotDirectorPresenceConnection));context?.addEventListener('context-connection-ready',()=>wire(context.contextController?.connection));wire(context?.contextController?.connection||window.PlotDirectorPresenceConnection);window.addEventListener('focus',()=>void refresh());window.addEventListener('pagehide',()=>{save();channel?.close();});window.PlotDirectorSharedFocus={navigate,refresh,toggle,validateLocal,get held(){return held;},get local(){return local;},get shared(){return latest;},get windowID(){return id;},async go(){if(await refresh(true)&&held&&latest?.isValid)apply(latest,'local');},ownsScope:p=>Number(p.bookID)===book&&Number(p.projectID)===project,async scope(p){project=Number(p.projectID);book=Number(p.bookID);queuedTarget=null;latest=null;const wasHeld=held;restore();held=wasHeld;local=normal(p);save();status();if(held)apply(local,'local');await refresh(true);}};document.addEventListener('click',async event=>{if(!event.isTrusted||event.defaultPrevented||event.button!==0||event.ctrlKey||event.metaKey||event.shiftKey||event.altKey)return;const link=event.target.closest('a[href]');if(!link||link.target&&link.target!=='_self'||link.closest('.reader-chapter-navigation'))return;const url=new URL(link.href,location.href);if(url.origin!==location.origin||url.searchParams.get('retainNarrativeFocus')==='true')return;const match=url.pathname.match(/^\/(Scenes\/Edit|Chapters\/(?:Details|Edit)|Writer\/Chapter)\/(\d+)$/i),timeline=/^\/Timeline(?:\/Index)?$/i.test(url.pathname)&&url.searchParams.get('navigateFocus')==='true';if(!match&&!timeline)return;const selectedScene=Number([...url.searchParams].find(([key])=>key.toLowerCase()==='selectedsceneid')?.[1]);const target=timeline?{sceneID:selectedScene}:match[1].toLowerCase()==='scenes/edit'?{sceneID:Number(match[2])}:{chapterID:Number(match[2])};if(timeline&&!selectedScene)return;event.preventDefault();const adapter=window.PlotDirectorFocusWorkspace?.adapter;try{if(adapter?.beforeChange&&await adapter.beforeChange(target)===false)return;await navigate(target);url.searchParams.delete('navigateFocus');url.searchParams.set('retainNarrativeFocus','true');location.assign(url);}finally{adapter?.changeFinished?.();}});window.dispatchEvent(new Event('plotdirector:shared-focus-ready'));void refresh();if(held&&local?.chapterID){apply(local,'restore');void validateLocal();}}
|
||||
restore();status();buttons.forEach(b=>b.addEventListener('click',()=>void toggle()));document.addEventListener('pd-presence-connection',e=>wire(e.detail));document.addEventListener('pd-presence-ready',()=>{const c=window.PlotDirectorPresenceConnection;wire(c);ready(c);});context?.addEventListener('context-connection-ready',()=>{const c=context.contextController?.connection;wire(c);ready(c);});wire(context?.contextController?.connection||window.PlotDirectorPresenceConnection);window.addEventListener('focus',()=>void refresh());window.addEventListener('pagehide',()=>{save();channel?.close();});window.PlotDirectorSharedFocus={navigate,refresh,toggle,validateLocal,get held(){return held;},get local(){return local;},get shared(){return latest;},get windowID(){return id;},async go(){if(await refresh(true)&&held&&latest?.isValid)apply(latest,'local');},ownsScope:p=>Number(p.bookID)===book&&Number(p.projectID)===project,async scope(p){invalidateRead();project=Number(p.projectID);book=Number(p.bookID);queuedTarget=null;latest=null;const wasHeld=held;restore();held=wasHeld;local=normal(p);save();status();if(held)apply(local,'local');await refresh(true);}};document.addEventListener('click',async event=>{if(!event.isTrusted||event.defaultPrevented||event.button!==0||event.ctrlKey||event.metaKey||event.shiftKey||event.altKey)return;const link=event.target.closest('a[href]');if(!link||link.target&&link.target!=='_self'||link.closest('.reader-chapter-navigation'))return;const url=new URL(link.href,location.href);if(url.origin!==location.origin||url.searchParams.get('retainNarrativeFocus')==='true')return;const match=url.pathname.match(/^\/(Scenes\/Edit|Chapters\/(?:Details|Edit)|Writer\/Chapter)\/(\d+)$/i),timeline=/^\/Timeline(?:\/Index)?$/i.test(url.pathname)&&url.searchParams.get('navigateFocus')==='true';if(!match&&!timeline)return;const selectedScene=Number([...url.searchParams].find(([key])=>key.toLowerCase()==='selectedsceneid')?.[1]);const target=timeline?{sceneID:selectedScene}:match[1].toLowerCase()==='scenes/edit'?{sceneID:Number(match[2])}:{chapterID:Number(match[2])};if(timeline&&!selectedScene)return;event.preventDefault();const adapter=window.PlotDirectorFocusWorkspace?.adapter;try{if(adapter?.beforeChange&&await adapter.beforeChange(target)===false)return;await navigate(target);url.searchParams.delete('navigateFocus');url.searchParams.set('retainNarrativeFocus','true');location.assign(url);}finally{adapter?.changeFinished?.();}});window.dispatchEvent(new Event('plotdirector:shared-focus-ready'));void refresh();if(held&&local?.chapterID){apply(local,'restore');void validateLocal();}}
|
||||
if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',start,{once:true});else start();})();
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user