Recover Audio Review controls across pauses and telemetry gaps
This commit is contained in:
parent
368c00a03a
commit
4663e04db4
13
PlotDirector.NativeCompanion/Agent/AudioSourceSelection.cs
Normal file
13
PlotDirector.NativeCompanion/Agent/AudioSourceSelection.cs
Normal file
@ -0,0 +1,13 @@
|
||||
namespace PlotDirector.Companion.Agent;
|
||||
|
||||
public static class AudioSourceSelection
|
||||
{
|
||||
public static string? Key(string? bound, string? selected, IEnumerable<string> controllable)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(bound))
|
||||
return selected == null || selected == bound ? bound : null;
|
||||
if (selected != null) return selected;
|
||||
var candidates = controllable.Take(2).ToArray();
|
||||
return candidates.Length == 1 ? candidates[0] : null;
|
||||
}
|
||||
}
|
||||
@ -154,6 +154,8 @@ public sealed partial class CloudGateway : IDisposable
|
||||
try
|
||||
{
|
||||
using var response=await http.SendAsync(request,HttpCompletionOption.ResponseHeadersRead,stop.Token);
|
||||
if(path.EndsWith("/audio-review",StringComparison.Ordinal)&&response.StatusCode==HttpStatusCode.Forbidden)
|
||||
throw new InvalidOperationException("The Audio Review document lease or book access is unavailable.");
|
||||
if(response.StatusCode==HttpStatusCode.Conflict&&path.EndsWith("/chapter-sync/reuse",StringComparison.Ordinal))throw new ChapterReuseConflictException();
|
||||
if(response.StatusCode==HttpStatusCode.Unauthorized){InvalidateAccess(context);throw new InvalidOperationException("Connection needs renewal. Retry after Companion reconnects automatically.");}
|
||||
if(!response.IsSuccessStatusCode&&path=="api/native-companion/manuscript-capture"){
|
||||
|
||||
@ -16,6 +16,8 @@ internal static class TrayApplication
|
||||
var log=new AgentLog(directory);var sessions=new SessionManager(cloud,ai,new DocumentWorkspaceWork(cloud));var control=new TrayCoordinator(sessions,cloud,ai);
|
||||
var media=new WindowsMediaControl();var audio=new WindowsAudioReview(cloud,control,media,directory);
|
||||
control.AudioRequested+=audio.Request;
|
||||
control.AudioStatus=session=>audio.ForSession(session) is { } source
|
||||
? (source.State,source.Operations) : ("unavailable",[]);
|
||||
using var window=new CompanionWindow(control,cloud,shutdown,directory,media,audio);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);
|
||||
@ -60,12 +62,11 @@ internal sealed class CompanionWindow:Form
|
||||
details.SizeChanged+=(_,_)=>{var titleWidth=Math.Max(1,details.ClientSize.Width-details.Padding.Horizontal-bookTitle.Margin.Horizontal);bookTitle.MaximumSize=new(titleWidth,0);projectTitle.MaximumSize=new(titleWidth,0);};
|
||||
manuscript.Controls.Add(bookLayout);layout.Controls.Add(manuscript);
|
||||
var open=Button("Open PlotDirector ↗",()=>cloud.OpenSite());open.Tag="primary";open.Dock=DockStyle.Top;open.MinimumSize=new(0,44);layout.Controls.Add(open);
|
||||
layout.Controls.Add(Button("Audio Review…",()=>ShowAudioReview(media,audio)));
|
||||
notice.Margin=new(0,12,0,0);layout.Controls.Add(notice);
|
||||
documents.SelectedIndexChanged+=(_,_)=>{if(!refreshing&&documents.SelectedItem is TrayDocument doc){selected=doc.Session;SavePreferences();RefreshState();}};
|
||||
Shown+=(_,_)=>{if(firstCompactLayout)SavePreferences();};
|
||||
ResizeEnd+=(_,_)=>SavePreferences();
|
||||
var menu=new ContextMenuStrip();menu.Items.Add("Open Companion",null,(_,_)=>Reveal());menu.Items.Add("Open PlotDirector",null,(_,_)=>Safe(()=>cloud.OpenSite()));menu.Items.Add("Settings",null,(_,_)=>{Reveal();ShowSettings();});menu.Items.Add(new ToolStripSeparator());menu.Items.Add("Exit Companion",null,(_,_)=>Exit());
|
||||
var menu=new ContextMenuStrip();menu.Items.Add("Open Companion",null,(_,_)=>Reveal());menu.Items.Add("Open PlotDirector",null,(_,_)=>Safe(()=>cloud.OpenSite()));menu.Items.Add("Settings",null,(_,_)=>{Reveal();ShowSettings();});menu.Items.Add("Change Audio Source…",null,(_,_)=>{Reveal();ShowAudioReview(media,audio);});menu.Items.Add(new ToolStripSeparator());menu.Items.Add("Exit Companion",null,(_,_)=>Exit());
|
||||
tray=new(){Icon=brand,Text="PlotDirector Companion",ContextMenuStrip=menu,Visible=true};tray.DoubleClick+=(_,_)=>Reveal();
|
||||
FormClosing+=(_,e)=>{if(!exiting){e.Cancel=true;SavePreferences();settings?.Hide();Hide();}};
|
||||
ApplyTheme();Microsoft.Win32.SystemEvents.UserPreferenceChanged+=OnPreferences;timer.Tick+=(_,_)=>RefreshState();timer.Start();RefreshState();
|
||||
@ -93,7 +94,6 @@ internal sealed class CompanionWindow:Form
|
||||
use.Click+=(_,_)=>{
|
||||
audio.Select(doc.Session,sources[choices.SelectedIndex].Key);
|
||||
dialog.Close();
|
||||
Safe(()=>cloud.OpenSite("Writer"));
|
||||
};
|
||||
content.Controls.Add(use);
|
||||
dialog.Controls.Add(content);
|
||||
@ -121,6 +121,21 @@ internal sealed class CompanionWindow:Form
|
||||
}catch(Exception e)when(e is InvalidOperationException or ArgumentException or IOException or System.ComponentModel.Win32Exception){if(!IsDisposed){error=e.Message;RefreshState();}}
|
||||
finally{choosingBook=false;}
|
||||
}
|
||||
private async void SignOutFromSettings()
|
||||
{
|
||||
error="Signing out…";RefreshState();
|
||||
try
|
||||
{
|
||||
await cloud.SignOutAsync();
|
||||
error=cloud.Status().Health?.Explanation??"Signed out.";
|
||||
}
|
||||
catch(Exception failure) when(failure is IOException or InvalidOperationException or UnauthorizedAccessException or System.Security.Cryptography.CryptographicException or HttpRequestException or OperationCanceledException)
|
||||
{
|
||||
error="Sign-out could not be completed securely. Check the connection and Windows profile, then retry.";
|
||||
}
|
||||
if(!IsDisposed)RefreshState();
|
||||
}
|
||||
|
||||
private void ShowSettings()
|
||||
{
|
||||
if(settings!=null&&!settings.IsDisposed){settings.Show(this);settings.Activate();return;}
|
||||
@ -130,7 +145,7 @@ internal sealed class CompanionWindow:Form
|
||||
var root=Stack(22);root.Dock=DockStyle.Fill;root.AutoSize=false;root.AutoScroll=true;settings.Controls.Add(root);
|
||||
settingsNotice=Label();root.Controls.Add(settingsNotice);root.Controls.Add(Heading("CONNECTION & ACCOUNT"));site=new(){Text=cloud.Status().ServerUrl,Dock=DockStyle.Top,AccessibleName="PlotDirector server HTTPS address"};root.Controls.Add(site);
|
||||
root.Controls.Add(Label("Your approved connection reconnects automatically. Changing account requires browser approval."));
|
||||
var accountActions=new FlowLayoutPanel{Dock=DockStyle.Top,AutoSize=true};accountActions.Controls.Add(Button("Change account…",()=>cloud.ChangeAccount(site.Text.Trim())));accountActions.Controls.Add(Button("Sign out",()=>{if(MessageBox.Show(settings,"Sign out and revoke this Companion’s approval? You will need browser approval to connect again.","Sign out",MessageBoxButtons.OKCancel)==DialogResult.OK)cloud.SignOut();}));root.Controls.Add(accountActions);
|
||||
var accountActions=new FlowLayoutPanel{Dock=DockStyle.Top,AutoSize=true};accountActions.Controls.Add(Button("Change account…",()=>cloud.ChangeAccount(site.Text.Trim())));accountActions.Controls.Add(Button("Sign out",()=>{if(MessageBox.Show(settings,"Sign out and revoke this Companion’s approval? You will need browser approval to connect again.","Sign out",MessageBoxButtons.OKCancel)==DialogResult.OK)SignOutFromSettings();}));root.Controls.Add(accountActions);
|
||||
root.Controls.Add(Button("Use server address",()=>{if(site.Text.Trim().TrimEnd('/')!=cloud.Status().ServerUrl.TrimEnd('/'))cloud.Connect(site.Text.Trim());}));
|
||||
advancedToggle=new(){Text="Advanced mode · troubleshooting and document maintenance",AutoSize=true,Checked=advanced,Dock=DockStyle.Top,Margin=new(0,16,0,10)};
|
||||
root.Controls.Add(advancedToggle);advancedPanel=Stack();advancedPanel.Visible=advanced;root.Controls.Add(advancedPanel);
|
||||
|
||||
@ -12,6 +12,7 @@ public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway
|
||||
private readonly Dictionary<Guid,Queue<AdapterCommand>> commands=[];private readonly Dictionary<Guid,Guid> leases=[];private readonly HashSet<Guid> captureInstances=[];private readonly HashSet<Guid> maintenanceInstances=[];private readonly Dictionary<Guid,(Guid Session,Guid Manuscript,Guid Authentication,string Kind,DateTime Started)> maintenance=[];private readonly Dictionary<(Guid,Guid),(Guid Manuscript,Guid Authentication,int Book,DateTime Expires)> reconnectBindings=[];
|
||||
public event Action? OpenRequested;
|
||||
internal event Action<Guid,string>? AudioRequested;
|
||||
internal Func<Guid,(string State,string[] Operations)>? AudioStatus { get; set; }
|
||||
public TrayDocument[] Documents {get{lock(gate)return documents.Values.OrderByDescending(d=>d.Observed).ToArray();}}
|
||||
public TrayDocument[] PresentationDocuments {get{lock(gate)return documents.Values.OrderByDescending(d=>d.Observed).Select(d=>d.Snapshot()).ToArray();}}
|
||||
public void Attach(Guid instance,Guid lease,bool capture=false,bool canMaintain=false,bool paragraphs=false,bool chapters=false,bool rangeChecks=false){lock(gate){Disconnected(instance);if(rangeChecks)rangeInstances.Add(instance);if(chapters)chapterInstances.Add(instance);else chapterInstances.Remove(instance);if(paragraphs)paragraphInstances.Add(instance);else paragraphInstances.Remove(instance);leases[instance]=lease;if(canMaintain)maintenanceInstances.Add(instance);else maintenanceInstances.Remove(instance);if(capture)captureInstances.Add(instance);else captureInstances.Remove(instance);}}
|
||||
@ -68,7 +69,11 @@ public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway
|
||||
}
|
||||
}
|
||||
if(documents.TryGetValue(request.SessionId,out var activeDocument)&&ChapterCapable(instance)&&request.Kind is "selection" or "metrics" or "tray-sync" or "tray-repair"){
|
||||
answer.ChapterStatusProvided=true;answer.BookId=activeDocument.Book;answer.BookTitle=cloud.Status().Books.FirstOrDefault(b=>b.BookId==activeDocument.Book)?.BookTitle??"";answer.ChapterTitle=activeDocument.ChapterTitle;answer.SceneTitle=activeDocument.SceneTitle;answer.ChapterProgress=VisibleChapterProgress(activeDocument);
|
||||
var connection=cloud.Status();
|
||||
answer.Health=connection.Health;
|
||||
answer.ChapterStatusProvided=true;answer.BookId=activeDocument.Book;answer.BookTitle=connection.Books.FirstOrDefault(b=>b.BookId==activeDocument.Book)?.BookTitle??"";answer.ChapterTitle=activeDocument.ChapterTitle;answer.SceneTitle=activeDocument.SceneTitle;answer.ChapterProgress=VisibleChapterProgress(activeDocument);
|
||||
if(connection.Health?.Authentication=="verified"&&AudioStatus?.Invoke(activeDocument.Session) is { } audio)
|
||||
{ answer.AudioState=audio.State;answer.AudioOperations=audio.Operations; }
|
||||
}
|
||||
if(commands.TryGetValue(instance,out var queue)&&queue.Count>0)answer.Command=queue.Dequeue();
|
||||
return answer;
|
||||
|
||||
@ -12,10 +12,16 @@ internal sealed class WindowsAudioReview(CloudGateway cloud, TrayCoordinator tra
|
||||
private (Guid Review, string Operation, DateTime Expiry) pending;
|
||||
private Guid availableReview;
|
||||
private long sequence = DateTime.UtcNow.Ticks;
|
||||
private Guid lastReview, blockedReview;
|
||||
private Guid lastReview;
|
||||
private string? boundKey;
|
||||
private long textChanges;
|
||||
private bool sourceSeen;
|
||||
public string Status { get; private set; } = "Select a Windows media source to connect Audio Review.";
|
||||
|
||||
private (Guid Session, NativeMediaSource Source)? Playback { get; set; }
|
||||
public NativeMediaSource? ForSession(Guid session)
|
||||
{
|
||||
lock (gate) return Playback is { } playback && playback.Session == session ? playback.Source : null;
|
||||
}
|
||||
public string Status { get; private set; } = "Start an Audio Review in Writer or Reader.";
|
||||
|
||||
public void Select(Guid session, string key)
|
||||
{
|
||||
@ -23,6 +29,7 @@ internal sealed class WindowsAudioReview(CloudGateway cloud, TrayCoordinator tra
|
||||
{
|
||||
selection = (session, key);
|
||||
availableReview = Guid.Empty;
|
||||
Playback = null;
|
||||
pending = default;
|
||||
}
|
||||
}
|
||||
@ -31,7 +38,7 @@ internal sealed class WindowsAudioReview(CloudGateway cloud, TrayCoordinator tra
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
if (selection.Session == session && availableReview != Guid.Empty)
|
||||
if (Playback is { } playback && playback.Session == session && playback.Source.Operations.Contains(operation) && availableReview != Guid.Empty)
|
||||
pending = (availableReview, operation, DateTime.UtcNow.AddSeconds(10));
|
||||
}
|
||||
}
|
||||
@ -44,15 +51,21 @@ internal sealed class WindowsAudioReview(CloudGateway cloud, TrayCoordinator tra
|
||||
var documents = tray.PresentationDocuments;
|
||||
Guid selectedSession;
|
||||
lock (gate) selectedSession = selection.Session;
|
||||
foreach (var document in documents.Where(d => d.Session == selectedSession && d.Book > 0 && cloud.Allows(d.Authentication, d.Book)))
|
||||
var eligible = documents.Where(d => d.Book > 0 && cloud.Allows(d.Authentication, d.Book)).ToArray();
|
||||
var document = eligible.FirstOrDefault(d => d.Session == selectedSession) ??
|
||||
eligible.FirstOrDefault(d => d.Active) ?? (eligible.Length == 1 ? eligible[0] : null);
|
||||
if (document == null)
|
||||
{
|
||||
try { await Observe(document, cancellation); }
|
||||
catch (Exception error) when (error is IOException or HttpRequestException or InvalidOperationException
|
||||
or OperationCanceledException or System.Runtime.InteropServices.COMException or JsonException or PlatformNotSupportedException)
|
||||
{
|
||||
lock (gate) availableReview = Guid.Empty;
|
||||
Status = "Audio Review is unavailable. Check the Companion connection and selected media source.";
|
||||
}
|
||||
lock (gate) { availableReview = Guid.Empty; Playback = null; }
|
||||
Status = "Waiting for an authenticated Word document connection.";
|
||||
continue;
|
||||
}
|
||||
try { await Observe(document, cancellation); }
|
||||
catch (Exception error) when (error is IOException or HttpRequestException or InvalidOperationException
|
||||
or OperationCanceledException or System.Runtime.InteropServices.COMException or JsonException or PlatformNotSupportedException)
|
||||
{
|
||||
lock (gate) { availableReview = Guid.Empty; Playback = null; }
|
||||
Status = error is InvalidOperationException ? error.Message : "Audio Review telemetry is interrupted. Waiting to reconnect.";
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -63,34 +76,30 @@ internal sealed class WindowsAudioReview(CloudGateway cloud, TrayCoordinator tra
|
||||
var reply = await cloud.ObserveAudioReview(doc, observation, cancellation);
|
||||
if (reply.Version != 1 || reply.ReviewID is not Guid review || review == Guid.Empty)
|
||||
{
|
||||
lock (gate) availableReview = Guid.Empty;
|
||||
lock (gate) { availableReview = Guid.Empty; Playback = null; }
|
||||
Status = "Start an Audio Review in Writer or Reader for the linked document.";
|
||||
return;
|
||||
}
|
||||
if (lastReview != review)
|
||||
{
|
||||
lastReview = review;
|
||||
sourceSeen = false;
|
||||
boundKey = null;
|
||||
textChanges = doc.AudioTextChanges;
|
||||
}
|
||||
observation.ReviewID = review;
|
||||
string? key;
|
||||
lock (gate) key = selection.Session == doc.Session ? selection.Key : null;
|
||||
if (!string.IsNullOrEmpty(reply.MediaKey) && reply.MediaKey != key) key = null;
|
||||
NativeMediaSource? source = null;
|
||||
if (key != null)
|
||||
{
|
||||
try { source = (await media.Discover(cancellation)).SingleOrDefault(s => s.Key == key); }
|
||||
catch (Exception error) when (error is OperationCanceledException or System.Runtime.InteropServices.COMException)
|
||||
{ cancellation.ThrowIfCancellationRequested(); }
|
||||
}
|
||||
if (source == null && sourceSeen) blockedReview = review;
|
||||
if (blockedReview == review) source = null;
|
||||
sourceSeen |= source != null;
|
||||
string? selectedKey;
|
||||
lock (gate) selectedKey = selection.Session == doc.Session ? selection.Key : null;
|
||||
var sources = await media.Discover(cancellation);
|
||||
var expected = string.IsNullOrEmpty(reply.MediaKey) ? boundKey : reply.MediaKey;
|
||||
var key = AudioSourceSelection.Key(expected, selectedKey,
|
||||
sources.Where(candidate => candidate.Operations.Length > 0).Select(candidate => candidate.Key));
|
||||
var source = sources.SingleOrDefault(candidate => candidate.Key == key);
|
||||
boundKey ??= source?.Key;
|
||||
(Guid Review, string Operation, DateTime Expiry) local;
|
||||
lock (gate)
|
||||
{
|
||||
availableReview = source == null ? Guid.Empty : review;
|
||||
availableReview = source?.Operations.Length > 0 ? review : Guid.Empty;
|
||||
Playback = source == null ? null : (doc.Session, source);
|
||||
local = pending;
|
||||
pending = default;
|
||||
}
|
||||
@ -159,14 +168,17 @@ internal sealed class WindowsAudioReview(CloudGateway cloud, TrayCoordinator tra
|
||||
}
|
||||
observation.Sequence = ++sequence;
|
||||
await cloud.ObserveAudioReview(doc, observation, cancellation);
|
||||
lock (gate) Playback = source != null && observation.MediaKey.Length > 0 ? (doc.Session, source) : null;
|
||||
Status = observation.Error ?? (source == null
|
||||
? "The selected media source is unavailable. End and restart Audio Review if the media source changed."
|
||||
? expected == null && key == null && sources.Count > 1
|
||||
? "More than one media source is available. Choose Change Audio Source in Companion."
|
||||
: "The selected media source is unavailable. End and restart Audio Review if the media source changed."
|
||||
: $"Windows media source: {source.Application} · {observation.State}");
|
||||
}
|
||||
|
||||
private bool IsCurrent(TrayDocument doc, string key)
|
||||
{
|
||||
lock (gate) if (selection != (doc.Session, key)) return false;
|
||||
lock (gate) if (boundKey != key || (selection.Session == doc.Session && selection.Key != key)) return false;
|
||||
return cloud.Allows(doc.Authentication, doc.Book) &&
|
||||
tray.PresentationDocuments.Any(d => d.Session == doc.Session && d.Instance == doc.Instance &&
|
||||
d.Book == doc.Book && d.Authentication == doc.Authentication);
|
||||
|
||||
@ -1 +1 @@
|
||||
<Project><PropertyGroup><ApplicationVersion>1.0.0.35</ApplicationVersion></PropertyGroup></Project>
|
||||
<Project><PropertyGroup><ApplicationVersion>1.0.0.36</ApplicationVersion></PropertyGroup></Project>
|
||||
|
||||
@ -34,6 +34,8 @@ public static class ProtocolVersion
|
||||
public sealed class Message
|
||||
{
|
||||
[DataMember] public bool ChapterStatusProvided {get;set;}
|
||||
[DataMember(EmitDefaultValue=false)] public string? AudioState { get; set; }
|
||||
[DataMember(EmitDefaultValue=false)] public string[]? AudioOperations { get; set; }
|
||||
[DataMember] public PlotDirector.Companion.Protocol.Manuscript.ChapterSyncProgress? ChapterProgress {get;set;}
|
||||
[DataMember] public string BookTitle {get;set;}="";
|
||||
[DataMember] public Guid OperationId {get;set;}
|
||||
|
||||
@ -7,6 +7,13 @@ if(args.Contains("--chapter-sync")){ChapterRangeVerificationTests.Run();ChapterR
|
||||
if(args.Contains("--native-capture-upload")){await NativeCaptureUploadTests.Run();return;}
|
||||
var passed = 0;
|
||||
void Check(bool value,string name) {if(!value)throw new Exception(name);passed++;Console.WriteLine("PASS "+name);}
|
||||
Check(AudioSourceSelection.Key(null,null,["narration"])=="narration","One controllable audio source is selected automatically");
|
||||
Check(AudioSourceSelection.Key(null,null,["narration","music"])==null,"Ambiguous media sources require selection");
|
||||
Check(AudioSourceSelection.Key(null,"narration",["narration","music"])=="narration","Explicit source selection resolves ambiguity");
|
||||
Check(AudioSourceSelection.Key("narration",null,[])=="narration"&&
|
||||
AudioSourceSelection.Key("narration",null,["narration"])=="narration","Missing telemetry retains the binding and the same paused source can recover");
|
||||
Check(AudioSourceSelection.Key("narration",null,["music"])=="narration"&&
|
||||
AudioSourceSelection.Key("narration","music",["music"])==null,"An existing review cannot switch to a different native media key");
|
||||
async Task Until(Func<bool> condition,string name) {using var timeout=new CancellationTokenSource(TimeSpan.FromSeconds(12));while(!condition()){await Task.Delay(20,timeout.Token);}Check(true,name);}
|
||||
void SchedulerChecks()
|
||||
{
|
||||
|
||||
@ -45,6 +45,10 @@ namespace PlotDirector.WordAddIn
|
||||
Refresh("PlotDirectorWeb", enabled);
|
||||
Refresh("PlotDirectorSynchronise", enabled);
|
||||
Refresh("PlotDirectorRepair", enabled);
|
||||
Refresh("PlotDirectorAudioPlay", $"{AudioShowPlay(null)}:{AudioCanPlay(null)}");
|
||||
Refresh("PlotDirectorAudioPause", $"{AudioShowPause(null)}:{AudioCanPause(null)}");
|
||||
Refresh("PlotDirectorAudioBack", $"{AudioShowSeek(null)}:{AudioCanBack(null)}");
|
||||
Refresh("PlotDirectorAudioForward", $"{AudioShowSeek(null)}:{AudioCanForward(null)}");
|
||||
}
|
||||
catch (COMException) { }
|
||||
}
|
||||
@ -81,5 +85,12 @@ namespace PlotDirector.WordAddIn
|
||||
public void AudioPause(Office.IRibbonControl control) => adapter()?.RequestAudio("pause");
|
||||
public void AudioBack(Office.IRibbonControl control) => adapter()?.RequestAudio("back15");
|
||||
public void AudioForward(Office.IRibbonControl control) => adapter()?.RequestAudio("forward15");
|
||||
public bool AudioShowPlay(Office.IRibbonControl control) => adapter()?.HasAudioControls==true && adapter()?.AudioPlaying==false;
|
||||
public bool AudioShowPause(Office.IRibbonControl control) => adapter()?.HasAudioControls==true && adapter()?.AudioPlaying==true;
|
||||
public bool AudioShowSeek(Office.IRibbonControl control) => adapter()?.HasAudioControls==true;
|
||||
public bool AudioCanPlay(Office.IRibbonControl control) => adapter()?.CanAudio("play")==true;
|
||||
public bool AudioCanPause(Office.IRibbonControl control) => adapter()?.CanAudio("pause")==true;
|
||||
public bool AudioCanBack(Office.IRibbonControl control) => adapter()?.CanAudio("back15")==true;
|
||||
public bool AudioCanForward(Office.IRibbonControl control) => adapter()?.CanAudio("forward15")==true;
|
||||
}
|
||||
}
|
||||
|
||||
@ -3,6 +3,6 @@ using System.Runtime.InteropServices;
|
||||
[assembly: AssemblyTitle("PlotDirector Word Companion — Native development")]
|
||||
[assembly: AssemblyCompany("Nick Beckley")]
|
||||
[assembly: AssemblyProduct("PlotDirector")]
|
||||
[assembly: AssemblyVersion("1.0.0.35")]
|
||||
[assembly: AssemblyFileVersion("1.0.0.35")]
|
||||
[assembly: AssemblyVersion("1.0.0.36")]
|
||||
[assembly: AssemblyFileVersion("1.0.0.36")]
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
@ -16,11 +16,11 @@
|
||||
<button id="PlotDirectorOpen" label="Open Companion" size="large" imageMso="WindowNew" onAction="OpenCompanion" />
|
||||
</group>
|
||||
<group id="PlotDirectorAudioReview" label="Audio Review">
|
||||
<button id="PlotDirectorAudioReviewOpen" label="Audio Review…" onAction="OpenCompanion" supertip="Open Companion to select a Windows media source, then manage review in Writer." />
|
||||
<button id="PlotDirectorAudioPlay" label="Play" onAction="AudioPlay" />
|
||||
<button id="PlotDirectorAudioPause" label="Pause" onAction="AudioPause" />
|
||||
<button id="PlotDirectorAudioBack" label="Back 15s" onAction="AudioBack" />
|
||||
<button id="PlotDirectorAudioForward" label="Forward 15s" onAction="AudioForward" />
|
||||
<button id="PlotDirectorAudioReviewOpen" label="Audio Review" imageMso="ReadAloud" onAction="OpenCompanion" supertip="Start an Audio Review in Writer or Reader. Companion connects automatically when one controllable player is available." />
|
||||
<button id="PlotDirectorAudioBack" label="Back 15 seconds" imageMso="PreviousRecord" onAction="AudioBack" getVisible="AudioShowSeek" getEnabled="AudioCanBack" />
|
||||
<button id="PlotDirectorAudioPlay" label="Play" imageMso="MediaPlay" onAction="AudioPlay" getVisible="AudioShowPlay" getEnabled="AudioCanPlay" />
|
||||
<button id="PlotDirectorAudioPause" label="Pause" imageMso="MediaPause" onAction="AudioPause" getVisible="AudioShowPause" getEnabled="AudioCanPause" />
|
||||
<button id="PlotDirectorAudioForward" label="Forward 15 seconds" imageMso="NextRecord" onAction="AudioForward" getVisible="AudioShowSeek" getEnabled="AudioCanForward" />
|
||||
</group>
|
||||
<group id="PlotDirectorSync" label="Synchronisation">
|
||||
<box id="PlotDirectorSyncState" boxStyle="vertical">
|
||||
|
||||
@ -75,6 +75,8 @@ namespace PlotDirector.WordAddIn
|
||||
+ "\nCompleted chapter native paragraphs / COM calls (process): " + chapterParagraphVisits + " / " + chapterComCalls
|
||||
+ "\nChapter reads live / XML (process): " + chapterLiveReads + " / " + chapterXmlReads
|
||||
+ "\n" + string.Join("\n",chapterMetrics.Select(p=>p.Key+": count="+p.Value[0]+", total ms="+p.Value[1].ToString("F1")+", max ms="+p.Value[2].ToString("F1")))
|
||||
+ "\nPlotDirector authentication: " + authenticatedState + " · " + authenticationDetail
|
||||
+ "\nAudio Review: " + audioState
|
||||
+ "\nCOM busy/errors: " + busyFailures + (lastWordError == null ? "" : " (last: " + lastWordError + ")") + "\nLast local protocol status: " + lastResult;
|
||||
|
||||
public WordAdapter(Word.Application application, Action invalidateRibbon)
|
||||
@ -89,6 +91,7 @@ namespace PlotDirector.WordAddIn
|
||||
ConnectionState = state;
|
||||
if(state!="connected")
|
||||
{traySupported=false;nativeChapterTextSupported=false;nativeChapterPositionsSupported=false;
|
||||
ClearBridgeStatus();
|
||||
foreach(var doc in documents.Values){StopAi(doc,"Agent disconnected. Successful AI suggestions retained; reconnect before retrying.");}
|
||||
}
|
||||
if (state == "connected")
|
||||
|
||||
@ -15,6 +15,12 @@ namespace PlotDirector.WordAddIn
|
||||
private long chapterLiveReads,chapterXmlReads,chapterComCalls,chapterParagraphVisits,chapterCommandPolls,chapterRcwReleases,chapterPlainBatches;
|
||||
private bool nativeChapterTextSupported,nativeChapterPositionsSupported,liveChapterTextSupported;
|
||||
private ChapterSyncProgress serverChapterProgress;
|
||||
private string audioState="", authenticatedState="", authenticationDetail="";
|
||||
private string[] audioOperations=Array.Empty<string>();
|
||||
public bool CanAudio(string operation) => HasRibbonBook && active.Revision==serverRevision &&
|
||||
Array.IndexOf(audioOperations,operation)>=0;
|
||||
public bool AudioPlaying => audioState=="playing";
|
||||
public bool HasAudioControls => CanAudio("play")||CanAudio("pause")||CanAudio("back15")||CanAudio("forward15");
|
||||
private string lastRibbonCommand="";
|
||||
|
||||
public bool HasRibbonBook => active != null && ConnectionState == "connected" && serverBookId > 0 && serverChapterProgress?.State != "Sign-in required";
|
||||
@ -62,7 +68,7 @@ namespace PlotDirector.WordAddIn
|
||||
|
||||
public void RequestAudio(string operation)
|
||||
{
|
||||
if(HasRibbonBook)link.TryPost(new Message{Kind="tray-audio",Action=operation,SessionId=active.Session,Revision=active.Revision});
|
||||
if(CanAudio(operation))link.TryPost(new Message{Kind="tray-audio",Action=operation,SessionId=active.Session,Revision=active.Revision});
|
||||
}
|
||||
|
||||
public void OpenWritingWorkspace(string command)
|
||||
@ -94,7 +100,12 @@ namespace PlotDirector.WordAddIn
|
||||
private void ReceiveChapterStatus(Message message)
|
||||
{
|
||||
if (active == null || active.Session != message.SessionId || active.Revision != message.Revision) return;
|
||||
if (serverBookId == message.BookId && serverRevision == message.Revision &&
|
||||
var operations=message.AudioOperations??Array.Empty<string>();
|
||||
var sameAudio=audioState==(message.AudioState??"")&&System.Linq.Enumerable.SequenceEqual(operations,audioOperations);
|
||||
audioState=message.AudioState??"";audioOperations=operations;
|
||||
authenticatedState=message.Health?.Authentication??"";
|
||||
authenticationDetail=message.Health?.Explanation??"";
|
||||
if (sameAudio && serverBookId == message.BookId && serverRevision == message.Revision &&
|
||||
serverBook == message.BookTitle && serverChapter == message.ChapterTitle && serverScene == message.SceneTitle &&
|
||||
serverChapterProgress?.State == message.ChapterProgress?.State &&
|
||||
serverChapterProgress?.Total == message.ChapterProgress?.Total &&
|
||||
@ -117,8 +128,17 @@ namespace PlotDirector.WordAddIn
|
||||
serverRevision = -1;
|
||||
serverBook = serverChapter = serverScene = "";
|
||||
serverChapterProgress = null;
|
||||
ClearBridgeStatus();
|
||||
invalidateRibbon();
|
||||
}
|
||||
|
||||
private void ClearBridgeStatus()
|
||||
{
|
||||
audioState="";audioOperations=Array.Empty<string>();
|
||||
authenticatedState=authenticationDetail="";
|
||||
serverChapterProgress=null;
|
||||
serverBookId=0;serverRevision=-1;
|
||||
}
|
||||
private sealed class ChapterRead
|
||||
{
|
||||
public readonly Stopwatch Total=Stopwatch.StartNew();public double ComparisonMs;public double ActiveMs,ComMs,ReleaseMs,QueueMs,QuietMs,OtherWorkMs,TimerHostMs;public long ComCalls,ParagraphVisits,ReleaseCalls,PlainBatches;public System.Threading.Tasks.Task<ChapterRangeCheck> RangeComparison;public AdapterCommand Command;public int Phase,Seek,Steps,Start,End,Offset;public string Text="",Xml="",NextId="",StartId="";public bool Begun; public int IdentityPosition; public readonly System.Text.StringBuilder Identities = new System.Text.StringBuilder(); public string IdentityFrames = ""; public bool NativeTextRequired,PhysicalPositions,LiveText,PlainIdentityBatch;
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
{
|
||||
"version": "1.0.0.35",
|
||||
"msiVersion": "1.0.35",
|
||||
"productCode": "{A44E9C6F-E845-4B21-ACE4-68A4C403D3E9}",
|
||||
"version": "1.0.0.36",
|
||||
"msiVersion": "1.0.36",
|
||||
"productCode": "{3B42423B-4315-44F9-AB7F-F9FC78867698}",
|
||||
"upgradeCode": "{641A087B-9779-458C-B290-BCBBAD49319A}",
|
||||
"atlasBaseline": "9fed339879887964d526cff00772ffc4dc522c5d",
|
||||
"baselineProductCode": "{98F46939-764D-407F-BD1F-1D88315D010A}",
|
||||
|
||||
64
PlotLine.Tests/Browser/audio-review-refresh.cjs
Normal file
64
PlotLine.Tests/Browser/audio-review-refresh.cjs
Normal file
@ -0,0 +1,64 @@
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const vm = require('node:vm');
|
||||
|
||||
const nodes = new Map();
|
||||
function node(selector) {
|
||||
if (!nodes.has(selector)) nodes.set(selector, {
|
||||
handlers: {}, value: '', disabled: false,
|
||||
querySelector: node,
|
||||
addEventListener(type, handle) { this.handlers[type] = handle; }
|
||||
});
|
||||
return nodes.get(selector);
|
||||
}
|
||||
const controls = ['play', 'pause', 'back15', 'forward15'].map(command => {
|
||||
const button = node(command);
|
||||
button.dataset = { mediaCommand: command };
|
||||
return button;
|
||||
});
|
||||
const root = { dataset: { bookId: '1' }, querySelector: node, querySelectorAll: () => controls };
|
||||
let tick;
|
||||
let session = {
|
||||
sessionID: 'fixture', kind: 'AudioReview', startedUtc: new Date().toISOString(),
|
||||
live: true, playbackState: 'playing', capabilities: 'pause,back15,forward15',
|
||||
engagedSeconds: 0, playbackSeconds: 0, uniqueSeconds: 0, sequence: 1
|
||||
};
|
||||
const posted = [];
|
||||
vm.runInNewContext(fs.readFileSync(path.join(__dirname, '../../PlotLine/wwwroot/js/writer-work.js'), 'utf8'), {
|
||||
document: { querySelectorAll: () => [root], querySelector: () => null, addEventListener() {}, visibilityState: 'visible', hasFocus: () => true },
|
||||
window: { addEventListener() {} },
|
||||
setInterval(handle) { tick = handle; }, clearInterval() {},
|
||||
URLSearchParams,
|
||||
fetch: async (url, options) => {
|
||||
if (options && url.endsWith('/Command')) posted.push(options.body.get('command'));
|
||||
return { ok: true, json: async () => ({ session }) };
|
||||
}
|
||||
});
|
||||
|
||||
(async () => {
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
for (let cycle = 0; cycle < 3; cycle++) {
|
||||
assert.equal(node('pause').disabled, false);
|
||||
await node('pause').handlers.click();
|
||||
session = { ...session, playbackState: 'paused', capabilities: 'play,back15,forward15' };
|
||||
await tick();
|
||||
assert.equal(node('play').disabled, false);
|
||||
assert.equal(node('pause').disabled, true);
|
||||
assert.equal(node('back15').disabled, false);
|
||||
await node('play').handlers.click();
|
||||
session = { ...session, playbackState: 'playing', capabilities: 'pause,back15,forward15' };
|
||||
await tick();
|
||||
}
|
||||
assert.deepEqual(posted, ['pause', 'play', 'pause', 'play', 'pause', 'play']);
|
||||
session = { ...session, live: false };
|
||||
await tick();
|
||||
assert.ok(controls.every(button => button.disabled));
|
||||
session = { ...session, live: true, playbackState: 'unavailable', capabilities: '' };
|
||||
await tick();
|
||||
assert.ok(controls.every(button => button.disabled));
|
||||
session = { ...session, playbackState: 'paused', capabilities: 'play' };
|
||||
await tick();
|
||||
assert.equal(node('play').disabled, false);
|
||||
console.log('PASS repeated PWA Play/Pause refreshes, telemetry loss, unavailable source, and recovery');
|
||||
})().catch(error => { console.error(error); process.exitCode = 1; });
|
||||
@ -38,7 +38,8 @@ public sealed class WriterWorkController(WriterWorkRepository work,NativePresenc
|
||||
{
|
||||
try {
|
||||
var current=(await work.State(Actor,bookId)).Current;if(current?.SessionID!=sessionId)current=null;
|
||||
if(current==null||!presence.Read(Actor,bookId).Any(l=>l.Instance==current.NativeInstance&&l.Session==current.NativeDocument&&l.Grant==current.NativeGrant)||command is not("play" or "pause" or "back15" or "forward15")||!(current.Capabilities??"").Split(',').Contains(command))return Conflict(new{message="This media operation is unavailable."});
|
||||
if(current==null||current.MediaReceivedUtc is not {} received||received<=DateTime.UtcNow.AddSeconds(-45)||
|
||||
current.PlaybackState is "unavailable" or "error"||!presence.Read(Actor,bookId).Any(l=>l.Instance==current.NativeInstance&&l.Session==current.NativeDocument&&l.Grant==current.NativeGrant)||command is not("play" or "pause" or "back15" or "forward15")||!(current.Capabilities??"").Split(',').Contains(command))return Conflict(new{message="This media operation is unavailable."});
|
||||
return await Change(new{Action="command",UserID=Actor,BookID=bookId,SessionID=sessionId,CommandID=Guid.NewGuid(),Command=command});
|
||||
} catch(SqlException e)when(e.Number==51000){return NotFound();}
|
||||
}
|
||||
|
||||
@ -20,7 +20,9 @@
|
||||
root.querySelector('[data-audio-state]').textContent=session.live?session.playbackState+(session.lastError?' · '+session.lastError:''):'Media controls unavailable. Updated Windows Companion with Audio Review support is required.';
|
||||
root.querySelector('[data-audio-position]').textContent=(session.positionSeconds==null?'Position unavailable':Math.round(session.positionSeconds)+' seconds'+(session.durationSeconds==null?'':' / '+Math.round(session.durationSeconds)+' seconds'))+' · '+Math.floor(session.playbackSeconds/60)+' observed playback minutes · '+Math.floor(session.uniqueSeconds/60)+' unique coverage minutes'+(session.coveragePartial?' (partial)':'');
|
||||
root.querySelector('[data-pause-on-edit]').checked=session.pauseOnEdit;
|
||||
for(const button of root.querySelectorAll('[data-media-command]'))button.disabled=!session.live||['unavailable','error'].includes(session.playbackState)||!session.capabilities?.split(',').includes(button.dataset.mediaCommand)||busy;
|
||||
// Refresh renders while holding the request guard. The click handlers enforce
|
||||
// that guard; leaving it in the DOM would disable controls after every refresh.
|
||||
for(const button of root.querySelectorAll('[data-media-command]'))button.disabled=!session.live||['unavailable','error'].includes(session.playbackState)||!session.capabilities?.split(',').includes(button.dataset.mediaCommand);
|
||||
}
|
||||
};
|
||||
const refresh=async()=>{const response=await fetch('/Writer/Work/State?bookId='+encodeURIComponent(bookId));if(!response.ok)throw Error('Session history is private or temporarily unavailable.');const data=await response.json();render(data.session);if(!data.session)root.querySelector('[data-pause-on-edit]').checked=data.defaultPauseOnEdit;};
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user