Add native Windows Audio Review candidate
This commit is contained in:
parent
68b3a7c57f
commit
45f7b31d96
11
Docs/Writer/AudioReview-WindowsQualification.md
Normal file
11
Docs/Writer/AudioReview-WindowsQualification.md
Normal file
@ -0,0 +1,11 @@
|
||||
# Windows Audio Review 1.0.0.35 developer candidate
|
||||
|
||||
The existing Word add-in and agent now expose Windows GSMTC discovery and an explicit source picker. Select a linked Word document in Companion, choose Audio Review and select the narration source, then start the chapter review in Writer or Reader. The web controls manage review start/end and Pause on Edit. The Word Audio Review group opens Companion and provides Play, Pause and ±15-second controls for the bound review. Ending the web review releases control without stopping the external player.
|
||||
|
||||
The agent polls the optional v1 audio endpoint with the existing DesktopPairing grant and document lease. It sends current observations, uses Windows playback capabilities and rechecks the selected source before commands. Command receipts are written before Windows invocation to prevent duplicate seeks after acknowledgement loss or restart. An interrupted, indeterminate operation is reported as a failure rather than replayed. Source identity uses application and metadata; Windows does not expose a stable Chrome tab ID. Distinct browser sources with identical metadata cannot be proven distinct, so use only one active matching source. After a detected source change, end and restart the review and explicitly select the intended source. Agent restart also requires explicit source selection.
|
||||
|
||||
Pause on Edit consumes existing chapter text-change evidence. Selection, scrolling and focus alone do not create that evidence. The agent pauses a playing source when an edit observation reaches it and never resumes automatically. The existing unsaved chapter-probe schedule can delay discovery; prompt real Word pause latency and continued edit bursts were not qualified. No extra full-document polling was added.
|
||||
|
||||
The checked-in server correction prevents a failed seek acknowledgement from incrementing the seek count. The deployed Development build still needs that correction before failed-seek accounting can be qualified. This work added no migrations and changed no stored procedures, browser authentication or Production deployment.
|
||||
|
||||
A read-only physical Windows probe using the candidate GSMTC implementation discovered one paused Chrome source with a timeline and Play/seek capabilities. It did not control the source or establish that it was ElevenReader. Real Word, ElevenReader in the background, authenticated PWA playback and Writing Journey remain acceptance work. Use an authorised disposable document and a known narration source for Chapter 45. Verify both playback surfaces, edit latency versus cursor/scroll activity, source changes, unsupported seek, disconnect/expiry/reconnect, and final Journey accounting.
|
||||
@ -1,7 +1,7 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Import Project="../DeveloperVersion.props" />
|
||||
<PropertyGroup><AssemblyVersion>$(ApplicationVersion)</AssemblyVersion><FileVersion>$(ApplicationVersion)</FileVersion><Version>$(ApplicationVersion)</Version></PropertyGroup>
|
||||
<PropertyGroup><OutputType>Exe</OutputType><TargetFrameworks>net10.0;net10.0-windows</TargetFrameworks><EnableWindowsTargeting>true</EnableWindowsTargeting><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable><Company>Nick Beckley</Company></PropertyGroup>
|
||||
<PropertyGroup Condition="'$(TargetFramework)'=='net10.0-windows'"><OutputType>WinExe</OutputType><UseWindowsForms>true</UseWindowsForms><ApplicationIcon>../../PlotLine/wwwroot/favicon.ico</ApplicationIcon></PropertyGroup>
|
||||
<PropertyGroup><OutputType>Exe</OutputType><TargetFrameworks>net10.0;net10.0-windows10.0.19041.0</TargetFrameworks><EnableWindowsTargeting>true</EnableWindowsTargeting><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable><Company>Nick Beckley</Company></PropertyGroup>
|
||||
<PropertyGroup Condition="'$(TargetFramework)'=='net10.0-windows10.0.19041.0'"><OutputType>WinExe</OutputType><UseWindowsForms>true</UseWindowsForms><ApplicationIcon>../../PlotLine/wwwroot/favicon.ico</ApplicationIcon></PropertyGroup>
|
||||
<ItemGroup><ProjectReference Include="../Protocol/PlotDirector.Companion.Protocol.csproj" /></ItemGroup>
|
||||
</Project>
|
||||
|
||||
@ -110,6 +110,9 @@ public sealed class SessionManager(CloudGateway? cloud = null,ChapterAiWork? ai
|
||||
switch (message.Kind)
|
||||
{
|
||||
case "tray-context":case "tray-intent":case "tray-workspace": break;
|
||||
case "tray-audio":
|
||||
if(message.Action is not ("play" or "pause" or "back15" or "forward15"))return Reject(answer,"invalid-audio-operation");
|
||||
break;
|
||||
case "tray-sync":case "tray-repair":if(!word.ChapterCapable)return Reject(answer,"unsupported-chapter-capability");break;
|
||||
case "metrics": break;
|
||||
case "adapter-result":break;
|
||||
|
||||
@ -14,19 +14,22 @@ internal static class TrayApplication
|
||||
using(singleton)using(var shutdown=new CancellationTokenSource())using(var cloud=new CloudGateway(settingsPath:Path.Combine(directory,"server-url.txt")))using(var ai=new ChapterAiWork(cloud)){
|
||||
Application.SetHighDpiMode(HighDpiMode.PerMonitorV2);Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false);
|
||||
var log=new AgentLog(directory);var sessions=new SessionManager(cloud,ai,new DocumentWorkspaceWork(cloud));var control=new TrayCoordinator(sessions,cloud,ai);
|
||||
using var window=new CompanionWindow(control,cloud,shutdown,directory);var handle=window.Handle;
|
||||
var media=new WindowsMediaControl();var audio=new WindowsAudioReview(cloud,control,media,directory);
|
||||
control.AudioRequested+=audio.Request;
|
||||
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);
|
||||
var reconnect=cloud.RunConnectionLoop(shutdown.Token);var work=control.Tick(shutdown.Token);var heartbeat=control.Heartbeat(shutdown.Token);
|
||||
var reconnect=cloud.RunConnectionLoop(shutdown.Token);var work=control.Tick(shutdown.Token);var heartbeat=control.Heartbeat(shutdown.Token);var audioWork=Task.Run(()=>audio.Run(shutdown.Token));
|
||||
var activate=Task.Run(async()=>{while(!shutdown.IsCancellationRequested){await using var pipe=new NamedPipeServerStream(endpoint+".activate",PipeDirection.In,1,PipeTransmissionMode.Byte,PipeOptions.Asynchronous|PipeOptions.CurrentUserOnly);await pipe.WaitForConnectionAsync(shutdown.Token);var value=new byte[1];if(await pipe.ReadAsync(value,shutdown.Token)>0)window.BeginInvoke(new Action(window.Reveal));}});
|
||||
log.Write("tray-start publisher=Nick-Beckley");if(args.Contains("--open"))window.Reveal();
|
||||
Application.Run();shutdown.Cancel();try{Task.WhenAll(serve,work,heartbeat,activate,reconnect).Wait(TimeSpan.FromSeconds(3));}catch(AggregateException){}cloud.StopAsync().GetAwaiter().GetResult();log.Write("tray-stop");
|
||||
Application.Run();shutdown.Cancel();try{Task.WhenAll(serve,work,heartbeat,activate,reconnect,audioWork).Wait(TimeSpan.FromSeconds(3));}catch(AggregateException){}cloud.StopAsync().GetAwaiter().GetResult();log.Write("tray-stop");
|
||||
}return 0;
|
||||
}
|
||||
}
|
||||
internal sealed class CompanionWindow:Form
|
||||
{
|
||||
private readonly TrayCoordinator control;private readonly CloudGateway cloud;private readonly CancellationTokenSource shutdown;private readonly string directory;
|
||||
private readonly WindowsAudioReview audioReview;
|
||||
private readonly Icon brand=Icon.ExtractAssociatedIcon(Application.ExecutablePath) ?? (Icon)SystemIcons.Application.Clone();private readonly NotifyIcon tray;private readonly System.Windows.Forms.Timer timer=new(){Interval=750};
|
||||
private readonly ToolTip tips=new();private bool exiting,refreshing,advanced,choosingBook;private Guid selected,lastActive;private TrayDocument[] displayed=[];private string docsKey="",error="";
|
||||
private readonly ComboBox documents=new(){DropDownStyle=ComboBoxStyle.DropDownList,Dock=DockStyle.Top,AccessibleName="Word manuscript"};
|
||||
@ -36,9 +39,9 @@ internal sealed class CompanionWindow:Form
|
||||
private Label? settingsNotice;private Label? dialogNotice;private Form? settings;private CheckBox? advancedToggle;private TextBox? site,diagnostics;private Panel? advancedPanel;
|
||||
private string coverKey="";private DateTime coverRetry;private CancellationTokenSource? coverStop;private bool coverLoading;
|
||||
private TrayDocument? Current=>displayed.FirstOrDefault(d=>d.Session==selected);
|
||||
public CompanionWindow(TrayCoordinator control,CloudGateway cloud,CancellationTokenSource shutdown,string directory)
|
||||
public CompanionWindow(TrayCoordinator control,CloudGateway cloud,CancellationTokenSource shutdown,string directory,WindowsMediaControl media,WindowsAudioReview audio)
|
||||
{
|
||||
this.control=control;this.cloud=cloud;this.shutdown=shutdown;this.directory=directory;advanced=cloud.Preferences.AdvancedMode;
|
||||
this.control=control;this.cloud=cloud;this.shutdown=shutdown;this.directory=directory;audioReview=audio;advanced=cloud.Preferences.AdvancedMode;
|
||||
Text="PlotDirector Companion";Icon=brand;Font=new("Segoe UI",10);AutoScaleMode=AutoScaleMode.Dpi;MinimumSize=new(400,460);DoubleBuffered=true;
|
||||
var preferences=cloud.Preferences;
|
||||
var firstCompactLayout=!preferences.CompactLayoutApplied;
|
||||
@ -57,6 +60,7 @@ 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();};
|
||||
@ -70,6 +74,34 @@ internal sealed class CompanionWindow:Form
|
||||
private static Label Heading(string text){var label=Label(text);label.Font=new("Segoe UI",9,FontStyle.Bold);label.Margin=new(0,0,0,9);return label;}
|
||||
private static TableLayoutPanel Stack(int padding=0){var panel=new TableLayoutPanel{Dock=DockStyle.Top,AutoSize=true,AutoSizeMode=AutoSizeMode.GrowAndShrink,ColumnCount=1,Padding=new(padding),Margin=new(0)};panel.ColumnStyles.Add(new(SizeType.Percent,100));return panel;}
|
||||
private static RoundedCard Card()=>new(){Dock=DockStyle.Top,AutoSize=true,AutoSizeMode=AutoSizeMode.GrowAndShrink,Padding=new(10),Margin=new(0,0,0,8),ColumnCount=1};
|
||||
private async void ShowAudioReview(WindowsMediaControl media,WindowsAudioReview audio)
|
||||
{
|
||||
var doc=Current;
|
||||
if(doc==null||doc.Book<=0){MessageBox.Show(this,"Open a linked Word manuscript first.","Audio Review");return;}
|
||||
try
|
||||
{
|
||||
var sources=await Task.Run(()=>media.Discover(shutdown.Token),shutdown.Token);
|
||||
if(IsDisposed)return;
|
||||
using var dialog=new Form{Text="Audio Review media source",Width=560,Height=210,StartPosition=FormStartPosition.CenterParent};
|
||||
var content=new FlowLayoutPanel{Dock=DockStyle.Fill,FlowDirection=FlowDirection.TopDown,Padding=new Padding(12)};
|
||||
var choices=new ComboBox{Width=500,DropDownStyle=ComboBoxStyle.DropDownList};
|
||||
foreach(var source in sources)choices.Items.Add(source.Title+" · "+source.Application+" · "+source.State);
|
||||
content.Controls.Add(new Label{AutoSize=true,Text=sources.Count==0?"No identifiable Windows media source is available.":"Select the Windows media source. Chrome may expose only its last active source."});
|
||||
content.Controls.Add(choices);
|
||||
var use=new Button{Text="Use selected source",AutoSize=true,Enabled=false};
|
||||
choices.SelectedIndexChanged+=(_,_)=>use.Enabled=choices.SelectedIndex>=0;
|
||||
use.Click+=(_,_)=>{
|
||||
audio.Select(doc.Session,sources[choices.SelectedIndex].Key);
|
||||
dialog.Close();
|
||||
Safe(()=>cloud.OpenSite("Writer"));
|
||||
};
|
||||
content.Controls.Add(use);
|
||||
dialog.Controls.Add(content);
|
||||
dialog.ShowDialog(this);
|
||||
}
|
||||
catch(Exception error)when(error is OperationCanceledException or InvalidOperationException or System.Runtime.InteropServices.COMException or PlatformNotSupportedException)
|
||||
{if(!IsDisposed)MessageBox.Show(this,"Windows media discovery is unavailable.","Audio Review");}
|
||||
}
|
||||
private Button Button(string text,Action action){var button=new Button{Text=text,AutoSize=true,MinimumSize=new(0,34)};button.Click+=(_,_)=>Safe(action);return button;}
|
||||
private void Safe(Action action){try{error="";action();}catch(Exception e)when(e is InvalidOperationException or ArgumentException or IOException or System.ComponentModel.Win32Exception){error=e.Message;}if(dialogNotice is {IsDisposed:false})SetText(dialogNotice,error);RefreshState();}
|
||||
private void SavePreferences(){var size=WindowState==FormWindowState.Normal?Size:RestoreBounds.Size;var prefs=cloud.Preferences;prefs.CompactLayoutApplied=true;prefs.Width=size.Width;prefs.Height=size.Height;prefs.AdvancedMode=advanced;prefs.LastManuscript=Current?.Manuscript??prefs.LastManuscript;cloud.SavePreferences(prefs);}
|
||||
@ -132,6 +164,7 @@ internal sealed class CompanionWindow:Form
|
||||
SetText(bookTitle,book==null?"No book associated":string.IsNullOrEmpty(book.BookTitle)?book.Title:book.BookTitle);SetText(projectTitle,book?.ProjectTitle??"Choose a book to connect your writing workspace.");
|
||||
var noticeText=error!=""?error:doc?.AssociationNotice??"";SetText(notice,noticeText);if(settingsNotice is {IsDisposed:false}){SetText(settingsNotice,error);settingsNotice.Visible=error!="";}notice.Visible=noticeText!="";tips.SetToolTip(serverStatus,state.Health?.Explanation??"Connect in Settings.");
|
||||
var text=$"Server: {state.ServerUrl}\r\nAccount: {state.Health?.AccountName}\r\n{state.Health?.Explanation}\r\n"+string.Join("\r\n",displayed.Select(d=>$"{d.Title} · session {d.Session} · book {d.Book}"))+"\r\n"+doc?.WordDiagnostics+"\r\n"+doc?.Status+"\r\n"+doc?.MaintenanceReport+"\r\n"+(doc==null?"":control.ChapterDiagnostics(doc.Session));
|
||||
text+="\r\nAudio Review: "+audioReview.Status;
|
||||
if(diagnostics is {IsDisposed:false}&&diagnostics.Text!=text)diagnostics.Text=text;
|
||||
if(books.Parent!=null&&!books.IsDisposed){var signature=state.AuthenticationContext+":"+string.Join("|",state.Books.Select(b=>b.BookId+":"+b.Title));if(books.Tag as string!=signature){var chosen=(books.SelectedItem as Protocol.CompanionBook)?.BookId;books.Tag=signature;books.DataSource=state.Books;books.SelectedItem=state.Books.FirstOrDefault(b=>b.BookId==chosen);}}
|
||||
var next=state.AuthenticationContext+":"+(book?.BookId??0);if(next!=coverKey){coverKey=next;coverRetry=DateTime.MinValue;coverStop?.Cancel();cover.SetImage(null);cover.Caption=bookTitle.Text;cover.Invalidate();coverLoading=false;}
|
||||
|
||||
@ -246,7 +246,7 @@ public sealed partial class TrayCoordinator
|
||||
if(message.Kind=="chapter-observe")
|
||||
{
|
||||
if(!work.ObserveOnly||message.ChapterId!=work.ExpectedProbeChapter||message.ChapterId==null||work.Manifest==null)return;
|
||||
if(message.Action=="changed"){if(work.Dirty.Add(message.ChapterId.Value))_ = cloud.QueueWritingObservation(doc.Book,doc.Manuscript,message.ChapterId.Value,doc.Session,doc.Revision,doc.Authentication);}else work.Dirty.Remove(message.ChapterId.Value);
|
||||
if(message.Action=="changed"){if(work.Dirty.Add(message.ChapterId.Value)){doc.AudioTextChanges++;_ = cloud.QueueWritingObservation(doc.Book,doc.Manuscript,message.ChapterId.Value,doc.Session,doc.Revision,doc.Authentication);}}else work.Dirty.Remove(message.ChapterId.Value);
|
||||
work.Visited.Add(message.ChapterId.Value);work.Calculated++;work.Busy=false;work.Processing=false;work.Command=Guid.Empty;
|
||||
AdvanceChapter(doc,work);return;
|
||||
}
|
||||
|
||||
@ -11,6 +11,7 @@ public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway
|
||||
private readonly object gate=new();private readonly Dictionary<Guid,TrayDocument> documents=[];
|
||||
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;
|
||||
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);}}
|
||||
@ -40,6 +41,8 @@ public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway
|
||||
if(request.Kind=="selection"&&doc.LastPresenceKey!=""&&chapterWork.TryGetValue(doc.Session,out var localWork)&&CurrentChapterWork(doc,localWork)&&localWork.Supported)
|
||||
PumpChapterWork(doc,localWork);
|
||||
ChapterFrame(doc,request,answer);
|
||||
if(request.Kind=="tray-audio"&&answer.Status=="ok"&&doc.Active&&doc.Book>0)
|
||||
AudioRequested?.Invoke(doc.Session,request.Action);
|
||||
if(request.Kind is "tray-sync" or "tray-repair")ReceiveChapterRibbonRequest(doc,request.Kind);
|
||||
if ((request.Kind is "tray-context" or "tray-intent") && answer.Status == "ok")
|
||||
_ = OpenRibbonWorkspace(doc.Session, request.Revision, request.Kind == "tray-context" ? "context" : "intent");
|
||||
@ -196,6 +199,7 @@ public sealed partial class TrayCoordinator(SessionManager sessions,CloudGateway
|
||||
}
|
||||
public sealed class TrayDocument
|
||||
{
|
||||
internal long AudioTextChanges;
|
||||
public PlotDirector.Companion.Protocol.Manuscript.ChapterSyncProgress? ChapterProgress;
|
||||
public string LastPresenceKey="";public DateTime LastPresenceUtc;public Guid Instance,Session,Manuscript,Authentication,Job;public long Revision,PresenceSequence;public string Title="",AssociationSite="",ChapterTitle="",SceneTitle="",Status="Link this manuscript to a book, then use Import manuscript in PlotDirector.",ReviewPath="";
|
||||
internal ManuscriptCapture? RetryCapture;internal Guid RetryAuthentication;internal int RetryBook;
|
||||
|
||||
194
PlotDirector.NativeCompanion/Agent/WindowsAudioReview.cs
Normal file
194
PlotDirector.NativeCompanion/Agent/WindowsAudioReview.cs
Normal file
@ -0,0 +1,194 @@
|
||||
#if WINDOWS
|
||||
using System.Text.Json;
|
||||
using PlotDirector.Companion.Protocol;
|
||||
|
||||
namespace PlotDirector.Companion.Agent;
|
||||
|
||||
internal sealed class WindowsAudioReview(CloudGateway cloud, TrayCoordinator tray, WindowsMediaControl media, string directory)
|
||||
{
|
||||
private readonly string receipts = Path.Combine(directory, "audio-review-receipts");
|
||||
private readonly object gate = new();
|
||||
private (Guid Session, string Key) selection;
|
||||
private (Guid Review, string Operation, DateTime Expiry) pending;
|
||||
private Guid availableReview;
|
||||
private long sequence = DateTime.UtcNow.Ticks;
|
||||
private Guid lastReview, blockedReview;
|
||||
private long textChanges;
|
||||
private bool sourceSeen;
|
||||
public string Status { get; private set; } = "Select a Windows media source to connect Audio Review.";
|
||||
|
||||
public void Select(Guid session, string key)
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
selection = (session, key);
|
||||
availableReview = Guid.Empty;
|
||||
pending = default;
|
||||
}
|
||||
}
|
||||
|
||||
public void Request(Guid session, string operation)
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
if (selection.Session == session && availableReview != Guid.Empty)
|
||||
pending = (availableReview, operation, DateTime.UtcNow.AddSeconds(10));
|
||||
}
|
||||
}
|
||||
|
||||
public async Task Run(CancellationToken cancellation)
|
||||
{
|
||||
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(2));
|
||||
while (await timer.WaitForNextTickAsync(cancellation))
|
||||
{
|
||||
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)))
|
||||
{
|
||||
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.";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task Observe(TrayDocument doc, CancellationToken cancellation)
|
||||
{
|
||||
var observation = new AudioReviewObservation { BookID = doc.Book, Sequence = ++sequence };
|
||||
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;
|
||||
Status = "Start an Audio Review in Writer or Reader for the linked document.";
|
||||
return;
|
||||
}
|
||||
if (lastReview != review)
|
||||
{
|
||||
lastReview = review;
|
||||
sourceSeen = false;
|
||||
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;
|
||||
(Guid Review, string Operation, DateTime Expiry) local;
|
||||
lock (gate)
|
||||
{
|
||||
availableReview = source == null ? Guid.Empty : review;
|
||||
local = pending;
|
||||
pending = default;
|
||||
}
|
||||
if (doc.AudioTextChanges != textChanges)
|
||||
{
|
||||
textChanges = doc.AudioTextChanges;
|
||||
observation.TextModified = true;
|
||||
if (reply.PauseOnEdit && source is { State: "playing" } && IsCurrent(doc, source.Key))
|
||||
{
|
||||
try { await media.Execute(source.Key, "pause", DateTime.UtcNow.AddSeconds(2), cancellation); }
|
||||
catch (Exception error) when (error is OperationCanceledException or System.Runtime.InteropServices.COMException)
|
||||
{ cancellation.ThrowIfCancellationRequested(); }
|
||||
source = (await media.Discover(cancellation)).SingleOrDefault(s => s.Key == key);
|
||||
}
|
||||
}
|
||||
if (reply.CommandID is Guid command && command != Guid.Empty)
|
||||
{
|
||||
observation.AcknowledgedCommandID = command;
|
||||
var path = Path.Combine(receipts, review.ToString("N"), command.ToString("N"));
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
if (File.Exists(path))
|
||||
ApplyReceipt(observation, File.ReadAllText(path));
|
||||
else
|
||||
{
|
||||
// Persist intent before invoking a non-idempotent OS seek. A crash leaves an
|
||||
// unknown outcome, which is acknowledged without replaying the command.
|
||||
using (var file = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None, 1, FileOptions.WriteThrough))
|
||||
{ file.WriteByte((byte)'?'); file.Flush(true); }
|
||||
var succeeded = false;
|
||||
var operation = reply.Command;
|
||||
if (source != null && operation != null && (!observation.TextModified || !reply.PauseOnEdit || operation != "play") && reply.MediaKey == source.Key &&
|
||||
reply.ExpiresUtc is DateTime expiry && expiry > DateTime.UtcNow &&
|
||||
(operation == "back15" ? reply.RelativeSeconds == -15 :
|
||||
operation == "forward15" ? reply.RelativeSeconds == 15 : reply.RelativeSeconds == null) &&
|
||||
IsCurrent(doc, source.Key))
|
||||
{
|
||||
try { succeeded = await media.Execute(source.Key, operation, expiry, cancellation); }
|
||||
catch (Exception error) when (error is OperationCanceledException or System.Runtime.InteropServices.COMException)
|
||||
{ cancellation.ThrowIfCancellationRequested(); }
|
||||
}
|
||||
var result = succeeded ? operation is "back15" or "forward15" ? "seek" : "ok" : "failed";
|
||||
var temporary = path + ".tmp";
|
||||
File.WriteAllText(temporary, result);
|
||||
File.Move(temporary, path, true);
|
||||
ApplyReceipt(observation, result);
|
||||
if (source != null)
|
||||
source = (await media.Discover(cancellation)).SingleOrDefault(s => s.Key == key);
|
||||
}
|
||||
}
|
||||
else if (source != null && local.Review == review && IsCurrent(doc, source.Key) &&
|
||||
(!observation.TextModified || !reply.PauseOnEdit || local.Operation != "play"))
|
||||
{
|
||||
var succeeded = await media.Execute(source.Key, local.Operation, local.Expiry, cancellation);
|
||||
observation.Seeked = succeeded && local.Operation is "back15" or "forward15";
|
||||
if (!succeeded) observation.Error = "The Windows media operation was unavailable or refused.";
|
||||
source = (await media.Discover(cancellation)).SingleOrDefault(s => s.Key == key);
|
||||
}
|
||||
if (source != null && IsCurrent(doc, source.Key))
|
||||
{
|
||||
observation.State = source.State;
|
||||
observation.MediaKey = source.Key;
|
||||
observation.PositionSeconds = source.Position;
|
||||
observation.DurationSeconds = source.Duration;
|
||||
observation.PlaybackRate = source.Rate;
|
||||
observation.Operations = source.Operations;
|
||||
}
|
||||
observation.Sequence = ++sequence;
|
||||
await cloud.ObserveAudioReview(doc, observation, cancellation);
|
||||
Status = observation.Error ?? (source == null
|
||||
? "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;
|
||||
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);
|
||||
}
|
||||
|
||||
private static void ApplyReceipt(AudioReviewObservation observation, string receipt)
|
||||
{
|
||||
observation.Seeked = receipt == "seek";
|
||||
observation.Error = receipt switch
|
||||
{
|
||||
"seek" or "ok" => null,
|
||||
"?" => "The previous Windows command outcome is unknown.",
|
||||
_ => "The Windows media command was unavailable, expired or refused."
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public sealed partial class CloudGateway
|
||||
{
|
||||
internal Task<AudioReviewReply> ObserveAudioReview(TrayDocument doc, AudioReviewObservation observation, CancellationToken cancellation) =>
|
||||
Send<AudioReviewReply>(HttpMethod.Post,
|
||||
$"api/native-companion/instances/{doc.Instance}/documents/{doc.Session}/audio-review", observation,
|
||||
doc.Authentication, cancellation);
|
||||
}
|
||||
#endif
|
||||
108
PlotDirector.NativeCompanion/Agent/WindowsMediaControl.cs
Normal file
108
PlotDirector.NativeCompanion/Agent/WindowsMediaControl.cs
Normal file
@ -0,0 +1,108 @@
|
||||
#if WINDOWS
|
||||
using System.Security.Cryptography;
|
||||
using System.Text.Json;
|
||||
using Windows.Media.Control;
|
||||
|
||||
namespace PlotDirector.Companion.Agent;
|
||||
|
||||
internal sealed record NativeMediaSource(string Key, string Application, string Title, string Artist,
|
||||
string State, double? Position, double? Duration, double Rate, string[] Operations);
|
||||
|
||||
internal sealed class WindowsMediaControl
|
||||
{
|
||||
private GlobalSystemMediaTransportControlsSessionManager? manager;
|
||||
|
||||
private async Task<GlobalSystemMediaTransportControlsSessionManager> Manager(CancellationToken cancellation)
|
||||
{
|
||||
if (!OperatingSystem.IsWindowsVersionAtLeast(10, 0, 17763))
|
||||
throw new PlatformNotSupportedException("Windows media sessions require Windows 10 version 1809 or later.");
|
||||
return manager ??= await GlobalSystemMediaTransportControlsSessionManager.RequestAsync().AsTask(cancellation);
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<NativeMediaSource>> Discover(CancellationToken cancellation)
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellation);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(2));
|
||||
var sources = new List<NativeMediaSource>();
|
||||
foreach (var session in (await Manager(timeout.Token)).GetSessions())
|
||||
{
|
||||
timeout.Token.ThrowIfCancellationRequested();
|
||||
try
|
||||
{
|
||||
if (await Observe(session, timeout.Token) is { } source)
|
||||
sources.Add(source);
|
||||
}
|
||||
catch (System.Runtime.InteropServices.COMException)
|
||||
{
|
||||
// A player may disappear while Windows enumerates sessions.
|
||||
}
|
||||
}
|
||||
return sources.GroupBy(source => source.Key).Where(group => group.Count() == 1)
|
||||
.Select(group => group.Single()).ToArray();
|
||||
}
|
||||
|
||||
public async Task<bool> Execute(string key, string operation, DateTime expiresUtc, CancellationToken cancellation)
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellation);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(2));
|
||||
var token = timeout.Token;
|
||||
var current = await Manager(token);
|
||||
GlobalSystemMediaTransportControlsSession? selected = null;
|
||||
foreach (var session in current.GetSessions())
|
||||
{
|
||||
if ((await Observe(session, token))?.Key != key) continue;
|
||||
if (selected != null) return false;
|
||||
selected = session;
|
||||
}
|
||||
if (selected == null || !current.GetSessions().Contains(selected)) return false;
|
||||
var source = await Observe(selected, token);
|
||||
if (source?.Key != key || !source.Operations.Contains(operation) ||
|
||||
!current.GetSessions().Contains(selected) || DateTime.UtcNow >= expiresUtc) return false;
|
||||
token.ThrowIfCancellationRequested();
|
||||
if (operation == "play") return await selected.TryPlayAsync().AsTask(token);
|
||||
if (operation == "pause") return await selected.TryPauseAsync().AsTask(token);
|
||||
var timeline = selected.GetTimelineProperties();
|
||||
if (timeline.MaxSeekTime <= timeline.MinSeekTime || source.Position is not double position) return false;
|
||||
var offset = operation == "back15" ? -15 : 15;
|
||||
var target = Math.Clamp(timeline.StartTime.Ticks + TimeSpan.FromSeconds(position + offset).Ticks,
|
||||
timeline.MinSeekTime.Ticks, timeline.MaxSeekTime.Ticks);
|
||||
return await selected.TryChangePlaybackPositionAsync(target).AsTask(token);
|
||||
}
|
||||
|
||||
private static async Task<NativeMediaSource?> Observe(GlobalSystemMediaTransportControlsSession session,
|
||||
CancellationToken cancellation)
|
||||
{
|
||||
var metadata = await session.TryGetMediaPropertiesAsync().AsTask(cancellation);
|
||||
var application = session.SourceAppUserModelId;
|
||||
if (string.IsNullOrWhiteSpace(application) || string.IsNullOrWhiteSpace(metadata?.Title)) return null;
|
||||
// GSMTC exposes application and metadata identity. It does not expose a Chrome tab ID.
|
||||
var key = Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(
|
||||
new[] { application, metadata.Title, metadata.Artist, metadata.AlbumTitle, metadata.Subtitle })));
|
||||
var playback = session.GetPlaybackInfo();
|
||||
var timeline = session.GetTimelineProperties();
|
||||
var state = playback?.PlaybackStatus switch
|
||||
{
|
||||
GlobalSystemMediaTransportControlsSessionPlaybackStatus.Playing => "playing",
|
||||
GlobalSystemMediaTransportControlsSessionPlaybackStatus.Paused => "paused",
|
||||
GlobalSystemMediaTransportControlsSessionPlaybackStatus.Stopped => "stopped",
|
||||
_ => "unavailable"
|
||||
};
|
||||
var rate = playback?.PlaybackRate ?? 1;
|
||||
var duration = (timeline.EndTime - timeline.StartTime).TotalSeconds;
|
||||
var position = (timeline.Position - timeline.StartTime).TotalSeconds;
|
||||
if (state == "playing" && timeline.LastUpdatedTime != default)
|
||||
position += Math.Max(0, (DateTimeOffset.UtcNow - timeline.LastUpdatedTime).TotalSeconds) * rate;
|
||||
var hasTimeline = duration is > 0 and <= 86400 && timeline.LastUpdatedTime != default &&
|
||||
(timeline.Position - timeline.StartTime).TotalSeconds >= 0 && double.IsFinite(position);
|
||||
var operations = new List<string>(4);
|
||||
var controls = playback?.Controls;
|
||||
if (controls?.IsPlayEnabled == true) operations.Add("play");
|
||||
if (controls?.IsPauseEnabled == true) operations.Add("pause");
|
||||
if (controls?.IsPlaybackPositionEnabled == true && hasTimeline && timeline.MaxSeekTime > timeline.MinSeekTime)
|
||||
operations.AddRange(["back15", "forward15"]);
|
||||
return new(key, application, metadata.Title, metadata.Artist, state, hasTimeline ? Math.Clamp(position, 0, duration) : null,
|
||||
hasTimeline ? duration : null, double.IsFinite(rate) && rate is >= 0.25 and <= 4 ? rate : 1,
|
||||
state == "unavailable" ? [] : operations.ToArray());
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@ -1 +1 @@
|
||||
<Project><PropertyGroup><ApplicationVersion>1.0.0.34</ApplicationVersion></PropertyGroup></Project>
|
||||
<Project><PropertyGroup><ApplicationVersion>1.0.0.35</ApplicationVersion></PropertyGroup></Project>
|
||||
|
||||
@ -77,5 +77,9 @@ namespace PlotDirector.WordAddIn
|
||||
public void Troubleshooting(Office.IRibbonControl control) => adapter()?.ShowTroubleshooting();
|
||||
public void RemoveLegacyMarkers(Office.IRibbonControl control) => adapter()?.RemoveLegacyMarkers();
|
||||
public void OpenCompanion(Office.IRibbonControl control) => adapter()?.OpenCompanion();
|
||||
public void AudioPlay(Office.IRibbonControl control) => adapter()?.RequestAudio("play");
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
@ -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.34")]
|
||||
[assembly: AssemblyFileVersion("1.0.0.34")]
|
||||
[assembly: AssemblyVersion("1.0.0.35")]
|
||||
[assembly: AssemblyFileVersion("1.0.0.35")]
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
@ -15,6 +15,13 @@
|
||||
<group id="PlotDirectorCompanion" label="Companion">
|
||||
<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" />
|
||||
</group>
|
||||
<group id="PlotDirectorSync" label="Synchronisation">
|
||||
<box id="PlotDirectorSyncState" boxStyle="vertical">
|
||||
<labelControl id="PlotDirectorStatus" getLabel="GetStatus" />
|
||||
|
||||
@ -60,6 +60,11 @@ namespace PlotDirector.WordAddIn
|
||||
public string ChapterStatusTip => (HasCurrentRibbonState || serverChapterProgress?.State == "Sign-in required" ? serverChapterProgress?.Message : null)
|
||||
?? "Synchronise to verify the manuscript position.";
|
||||
|
||||
public void RequestAudio(string operation)
|
||||
{
|
||||
if(HasRibbonBook)link.TryPost(new Message{Kind="tray-audio",Action=operation,SessionId=active.Session,Revision=active.Revision});
|
||||
}
|
||||
|
||||
public void OpenWritingWorkspace(string command)
|
||||
{
|
||||
if (HasRibbonBook)
|
||||
|
||||
@ -9,6 +9,6 @@ $project=Join-Path $root 'Vsto\PlotDirector.WordAddIn.csproj'
|
||||
& $msbuild $project /restore '/t:Build;VisualStudioForApplicationsBuild' /p:PrepareForRunDependsOn=CopyFilesToOutputDirectory /p:Configuration=Debug /p:SignManifests=true "/p:ManifestCertificateThumbprint=$CertificateThumbprint"
|
||||
if($LASTEXITCODE -ne 0){throw 'VSTO build failed; do not register or install the add-in.'}
|
||||
$agent=Join-Path $root 'Vsto\bin\Debug\Agent'
|
||||
dotnet publish (Join-Path $root 'Agent\PlotDirector.Companion.Agent.csproj') -f net10.0-windows -c Debug -r win-x64 --self-contained false -o $agent
|
||||
dotnet publish (Join-Path $root 'Agent\PlotDirector.Companion.Agent.csproj') -f net10.0-windows10.0.19041.0 -c Debug -r win-x64 --self-contained false -o $agent
|
||||
if($LASTEXITCODE -ne 0){throw 'Agent publish failed.'}
|
||||
Write-Output 'Developer outputs prepared only. Review/trust the signed test manifest in Visual Studio. No installation or automatic update was performed.'
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
{
|
||||
"version": "1.0.0.34",
|
||||
"msiVersion": "1.0.34",
|
||||
"productCode": "{32CF6005-CA2E-40C9-9872-917C1301A674}",
|
||||
"version": "1.0.0.35",
|
||||
"msiVersion": "1.0.35",
|
||||
"productCode": "{A44E9C6F-E845-4B21-ACE4-68A4C403D3E9}",
|
||||
"upgradeCode": "{641A087B-9779-458C-B290-BCBBAD49319A}",
|
||||
"atlasBaseline": "9fed339879887964d526cff00772ffc4dc522c5d",
|
||||
"baselineProductCode": "{98F46939-764D-407F-BD1F-1D88315D010A}",
|
||||
|
||||
@ -66,7 +66,7 @@ try {
|
||||
$staging=$output+'.preparing-'+[guid]::NewGuid().ToString('N')
|
||||
New-Item -ItemType Directory -Path $staging -Force | Out-Null
|
||||
Copy-Item -Path (Join-Path $bin '*') -Destination $staging -Recurse
|
||||
Invoke-Checked dotnet @('publish','PlotDirector.NativeCompanion/Agent/PlotDirector.Companion.Agent.csproj','-f','net10.0-windows','-c','Release','-r','win-x64','--self-contained','false','-o',(Join-Path $staging 'Agent'))
|
||||
Invoke-Checked dotnet @('publish','PlotDirector.NativeCompanion/Agent/PlotDirector.Companion.Agent.csproj','-f','net10.0-windows10.0.19041.0','-c','Release','-r','win-x64','--self-contained','false','-o',(Join-Path $staging 'Agent'))
|
||||
if((& git rev-parse HEAD).Trim() -ne $commit){throw 'Git HEAD changed during the build. No package was installed; rerun after the repository is stable.'}
|
||||
if(& git status --porcelain=v1){throw 'Build generated source changes; review them before packaging. No installation was changed.'}
|
||||
$files=@(Get-ChildItem -LiteralPath $staging -Recurse -File | ForEach-Object { @{path=$_.FullName.Substring($staging.Length+1).Replace('\','/');sha256=(Get-FileHash -Algorithm SHA256 -LiteralPath $_.FullName).Hash} })
|
||||
|
||||
@ -36,7 +36,8 @@ public sealed class WriterWorkRepository(ISqlConnectionFactory factory,TimeProvi
|
||||
{
|
||||
if(!string.IsNullOrEmpty(row.MediaKey)&&!string.IsNullOrEmpty(value.MediaKey)&&row.MediaKey!=value.MediaKey)throw new ArgumentException("Media source changed; end and restart review.");
|
||||
if(string.IsNullOrEmpty(value.MediaKey))value.MediaKey=row.MediaKey??"";
|
||||
value.Seeked = value.Seeked || value.AcknowledgedCommandID.HasValue && value.AcknowledgedCommandID == row.CommandID && row.Command is "back15" or "forward15";
|
||||
value.Seeked = value.Seeked || value.Error == null && value.AcknowledgedCommandID.HasValue &&
|
||||
value.AcknowledgedCommandID == row.CommandID && row.Command is "back15" or "forward15";
|
||||
var measure=AudioReviewMetrics.Measure(row,value,now);
|
||||
var command=row.Command;var id=row.CommandID;var sent=row.CommandUtc;
|
||||
if(value.AcknowledgedCommandID==id||sent<now.AddSeconds(-10)){command=null;id=null;sent=null;}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user