312 lines
25 KiB
C#
312 lines
25 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Diagnostics;
|
|
using PlotDirector.Companion.Client;
|
|
using Word=Microsoft.Office.Interop.Word;
|
|
using PlotDirector.Companion.Protocol;
|
|
using PlotDirector.Companion.Protocol.Manuscript;
|
|
namespace PlotDirector.WordAddIn
|
|
{
|
|
public sealed partial class WordAdapter
|
|
{
|
|
private string serverBook = "", serverChapter = "", serverScene = "";
|
|
private int serverBookId;
|
|
private long serverRevision = -1;
|
|
private long chapterLiveReads,chapterXmlReads,chapterComCalls,chapterParagraphVisits,chapterCommandPolls,chapterRcwReleases,chapterPlainBatches;
|
|
private bool nativeChapterTextSupported,nativeChapterPositionsSupported,liveChapterTextSupported;
|
|
private ChapterSyncProgress serverChapterProgress;
|
|
private string lastRibbonCommand="";
|
|
|
|
public bool HasRibbonBook => active != null && ConnectionState == "connected" && serverBookId > 0 && serverChapterProgress?.State != "Sign-in required";
|
|
public string RibbonBook => active != null && serverBook.Length > 0 ? serverBook
|
|
: active?.BookId > 0 ? "Saved book association" : "No linked book";
|
|
private bool HasCurrentRibbonState => HasRibbonBook && active.Revision == serverRevision;
|
|
public string RibbonLocation => HasCurrentRibbonState && serverScene.Length > 0
|
|
? (serverChapter.Length == 0 ? serverScene : serverChapter + " · " + serverScene)
|
|
: "Location unverified";
|
|
|
|
public string RibbonChapter => HasCurrentRibbonState && serverChapter.Length > 0 ? serverChapter : "Chapter unverified";
|
|
public string RibbonScene => HasCurrentRibbonState && serverScene.Length > 0 ? serverScene : "Scene unverified";
|
|
|
|
public string ChapterStatusLabel
|
|
{
|
|
get
|
|
{
|
|
if (ConnectionState != "connected") return "Not connected";
|
|
if (serverChapterProgress?.State == "Sign-in required") return "Sign-in required";
|
|
if (!HasRibbonBook) return "No linked book";
|
|
if (!HasCurrentRibbonState) return "Changes found";
|
|
if (serverChapterProgress == null) return "Not yet checked";
|
|
switch (serverChapterProgress.State)
|
|
{
|
|
case "Checking": return "Synchronising";
|
|
case "Save required": return "Save to synchronise";
|
|
case "Synchronised":
|
|
if (serverChapterProgress.Total > 0 && serverChapterProgress.Matching == serverChapterProgress.Total)
|
|
return "Up to date";
|
|
return "Review needed";
|
|
case "Needs review": return "Review needed";
|
|
case "Changed": return "Changes found";
|
|
default: return "Not yet checked";
|
|
}
|
|
}
|
|
}
|
|
|
|
public string RibbonSyncProgress => HasCurrentRibbonState && serverChapterProgress?.Total > 0
|
|
? ChapterStatusLabel == "Up to date" ? serverChapterProgress.Total + " chapters verified"
|
|
: serverChapterProgress.Matching + " of " + serverChapterProgress.Total + " chapters accepted"
|
|
: ChapterStatusLabel == "Review needed" ? "See Companion diagnostics" : " ";
|
|
public string ChapterStatusTip => (HasCurrentRibbonState || serverChapterProgress?.State == "Sign-in required" ? serverChapterProgress?.Message : null)
|
|
?? "Synchronise to verify the manuscript position.";
|
|
|
|
public void OpenWritingWorkspace(string command)
|
|
{
|
|
if (HasRibbonBook)
|
|
link.TryPost(new Message { Kind = command, SessionId = active.Session, Revision = active.Revision });
|
|
}
|
|
|
|
public void RequestChapterSynchronisation(bool repair)
|
|
{
|
|
lastRibbonCommand=repair?"Repair Synchronisation":"Synchronise";
|
|
if (!HasRibbonBook) { ShowChapterCommandFailure("Open a linked manuscript and connect Companion first."); return; }
|
|
if (!link.TryPost(new Message { Kind = repair ? "tray-repair" : "tray-sync", SessionId = active.Session, Revision = active.Revision }))
|
|
{
|
|
ShowChapterCommandFailure("The local queue is busy. Retry shortly.");
|
|
return;
|
|
}
|
|
serverChapterProgress = new ChapterSyncProgress{State="Checking",Message="Request sent to Companion."};
|
|
invalidateRibbon();
|
|
}
|
|
|
|
private void ShowChapterCommandFailure(string reason)
|
|
{
|
|
System.Windows.Forms.MessageBox.Show(reason,lastRibbonCommand);
|
|
}
|
|
|
|
public void ShowTroubleshooting() => System.Windows.Forms.MessageBox.Show(Diagnostics, "PlotDirector Troubleshooting");
|
|
|
|
private void ReceiveChapterStatus(Message message)
|
|
{
|
|
if (active == null || active.Session != message.SessionId || active.Revision != message.Revision) return;
|
|
if (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 &&
|
|
serverChapterProgress?.Matching == message.ChapterProgress?.Matching &&
|
|
serverChapterProgress?.Message == message.ChapterProgress?.Message) return;
|
|
serverBookId = message.BookId;
|
|
serverRevision = message.Revision;
|
|
serverBook = message.BookTitle ?? "";
|
|
serverChapter = message.ChapterTitle ?? "";
|
|
serverScene = message.SceneTitle ?? "";
|
|
serverChapterProgress = message.ChapterProgress;
|
|
invalidateRibbon();
|
|
}
|
|
|
|
private void ChangeActiveDocument(LocalDocument document)
|
|
{
|
|
if (active == document) return;
|
|
active = document;
|
|
serverBookId = 0;
|
|
serverRevision = -1;
|
|
serverBook = serverChapter = serverScene = "";
|
|
serverChapterProgress = null;
|
|
invalidateRibbon();
|
|
}
|
|
private sealed class ChapterRead
|
|
{
|
|
public readonly Stopwatch Total=Stopwatch.StartNew();public double ActiveMs,ComMs,ReleaseMs,QueueMs,QuietMs,OtherWorkMs,TimerHostMs;public long ComCalls,ParagraphVisits,ReleaseCalls,PlainBatches;public AdapterCommand Command;public int Phase,Seek,Steps,Start,End,Offset;public string Text="",Xml="",NextId="";public bool Begun; public int IdentityPosition; public readonly System.Text.StringBuilder Identities = new System.Text.StringBuilder(); public string IdentityFrames = ""; public bool NativeTextRequired,PhysicalPositions,LiveText;
|
|
public readonly List<ChapterParagraph> NativePositions=new List<ChapterParagraph>();
|
|
public int PendingStart,PendingEnd,ShapeIndex,SegmentPosition,SegmentAnchor;public string PendingText="";public ChapterParagraph PendingPosition;
|
|
public readonly Dictionary<int,ChapterPictureAnchor> PendingAnchors=new Dictionary<int,ChapterPictureAnchor>();
|
|
public readonly System.Text.StringBuilder SegmentText=new System.Text.StringBuilder(); public readonly System.Text.StringBuilder NativeText = new System.Text.StringBuilder();
|
|
}
|
|
private readonly Dictionary<Guid,ChapterRead> chapterReads=new Dictionary<Guid,ChapterRead>();
|
|
private void RefreshChapterTimer(){if(disposed)return;var interval=scheduler.HasRunnableChapterWork?5:25;if(timer.Interval!=interval)timer.Interval=interval;}
|
|
private void CancelChapterRead(LocalDocument doc){chapterReads.Remove(doc.Session);scheduler.Cancel("chapter:"+doc.Session);RefreshChapterTimer();}
|
|
private void StartChapterRead(LocalDocument doc,AdapterCommand command)
|
|
{
|
|
if(doc.Extraction!=null||doc.Maintenance!=null)throw new InvalidOperationException("Word already has an explicit read or maintenance request. Retry chapter validation afterwards.");
|
|
if(chapterReads.Count>=2&&!chapterReads.ContainsKey(doc.Session))throw new InvalidOperationException("Two document chapter reads are already pending. Activate this manuscript and retry.");
|
|
CancelChapterRead(doc);chapterReads[doc.Session]=new ChapterRead{Command=command,Seek=Math.Max(0,Math.Min(command.Chapter==null?0:command.Chapter.Start,doc.End-1))};
|
|
if(!scheduler.Post("chapter:"+doc.Session,()=>ReadChapterStep(doc))){CancelChapterRead(doc);throw new InvalidOperationException("Word queue is busy; accepted checkpoints are preserved. Retry shortly.");}
|
|
RefreshChapterTimer();
|
|
}
|
|
private string ReadLiveParagraphId(Word.Paragraph paragraph)
|
|
{
|
|
var value = Com(() => paragraph.ParaID, "chapter-paragraph-id");
|
|
var id = WordParagraphIdentity.Normalise(value.ToString("X8", System.Globalization.CultureInfo.InvariantCulture));
|
|
if (id.Length == 0) throw new InvalidOperationException("Word did not provide a native paragraph ID. Review this chapter or use the explicit fallback.");
|
|
return id;
|
|
}
|
|
private void ReleaseChapter(object value)
|
|
{
|
|
if(value==null)return;var started=Stopwatch.GetTimestamp();
|
|
try{Release(value);}finally{if(executingChapterRead!=null){executingChapterRead.ReleaseCalls++;executingChapterRead.ReleaseMs+=(Stopwatch.GetTimestamp()-started)*1000d/Stopwatch.Frequency;}}
|
|
}
|
|
// Conservative accelerator: structural/picture chapters retain the qualified XML/position reader.
|
|
// Collection RCWs are released before returning to the scheduler.
|
|
private bool IsPlainChapter(Word.Range range)
|
|
{
|
|
Word.Tables tables=null;Word.Fields fields=null;Word.Revisions revisions=null;
|
|
Word.Footnotes footnotes=null;Word.Endnotes endnotes=null;Word.InlineShapes inline=null;
|
|
try
|
|
{
|
|
tables=Com(()=>range.Tables);if(Com(()=>tables.Count)!=0)return false;
|
|
fields=Com(()=>range.Fields);if(Com(()=>fields.Count)!=0)return false;
|
|
revisions=Com(()=>range.Revisions);if(Com(()=>revisions.Count)!=0)return false;
|
|
footnotes=Com(()=>range.Footnotes);if(Com(()=>footnotes.Count)!=0)return false;
|
|
endnotes=Com(()=>range.Endnotes);if(Com(()=>endnotes.Count)!=0)return false;
|
|
inline=Com(()=>range.InlineShapes);if(Com(()=>inline.Count)!=0)return false;
|
|
return true;
|
|
}
|
|
catch(System.Runtime.InteropServices.COMException){return false;}
|
|
finally{ReleaseChapter(inline);ReleaseChapter(endnotes);ReleaseChapter(footnotes);ReleaseChapter(revisions);ReleaseChapter(fields);ReleaseChapter(tables);}
|
|
}
|
|
private void CheckChapterShape(LocalDocument doc,ChapterRead read)
|
|
{
|
|
Word.Shapes shapes=null;Word.Shape shape=null;Word.Range anchor=null;
|
|
try
|
|
{
|
|
shapes=Com(()=>doc.Document.Shapes);var count=Com(()=>shapes.Count);
|
|
if(count>128){read.Phase=12;return;}
|
|
if(read.ShapeIndex>count){read.LiveText=true;read.IdentityPosition=read.Start;read.Phase=7;return;}
|
|
shape=Com(()=>shapes[read.ShapeIndex]);anchor=Com(()=>shape.Anchor);
|
|
var start=Com(()=>anchor.Start);
|
|
if(start>=read.Start&&start<read.End){read.Phase=12;return;}
|
|
read.ShapeIndex++;
|
|
}
|
|
finally{ReleaseChapter(anchor);ReleaseChapter(shape);ReleaseChapter(shapes);}
|
|
}
|
|
// Keep collection/range RCWs only within this bounded STA step. No count or
|
|
// full collection enumeration, and no cached native identity from an older session.
|
|
private void ReadPlainChapterBatch(LocalDocument doc,ChapterRead read)
|
|
{
|
|
Word.Range remaining=null,paragraphRange=null;Word.Paragraphs collection=null;Word.Paragraph paragraph=null;
|
|
var budget=Stopwatch.StartNew();
|
|
try
|
|
{
|
|
read.PlainBatches++;remaining=Com(()=>doc.Document.Range(read.IdentityPosition,read.End));collection=Com(()=>remaining.Paragraphs);
|
|
for(var index=1;ChapterIdentityRead.CanContinue(index-1,budget.Elapsed.TotalMilliseconds);index++)
|
|
{
|
|
try
|
|
{
|
|
if(doc.Revision!=read.Command.Revision||closing.Contains(doc.Document))throw new InvalidOperationException("Word changed during native paragraph verification.");
|
|
paragraph=Com(()=>collection[index]);paragraphRange=Com(()=>paragraph.Range);
|
|
var start=Com(()=>paragraphRange.Start);var end=Com(()=>paragraphRange.End);
|
|
read.IdentityPosition=ChapterIdentityRead.Append(read.Identities,read.IdentityPosition,read.End,start,end,ReadLiveParagraphId(paragraph),(int)Com(()=>paragraph.OutlineLevel));
|
|
read.ParagraphVisits++;
|
|
if(end==read.End){read.IdentityFrames=read.Identities.ToString();read.Phase=4;break;}
|
|
}
|
|
finally{ReleaseChapter(paragraphRange);paragraphRange=null;ReleaseChapter(paragraph);paragraph=null;}
|
|
}
|
|
if(!Com(()=>doc.Document.Saved)||Com(()=>application.BackgroundSavingStatus)!=0)throw new InvalidOperationException("Save Word before accepting native paragraph evidence.");
|
|
}
|
|
finally{ReleaseChapter(paragraphRange);ReleaseChapter(paragraph);ReleaseChapter(collection);ReleaseChapter(remaining);}
|
|
}
|
|
private ChapterRead executingChapterRead;
|
|
private void CompleteChapterReadMetrics(ChapterRead read,double finalStepMs)
|
|
{
|
|
Metric("chapter-read-active",read.ActiveMs+finalStepMs);Metric("chapter-read-rcw-release",read.ReleaseMs);Metric("chapter-read-com",read.ComMs);
|
|
Metric("chapter-read-queue",read.QueueMs);Metric("chapter-read-author-wait",read.QuietMs);
|
|
Metric("chapter-read-other-work",read.OtherWorkMs);Metric("chapter-read-timer-host-wait",read.TimerHostMs);
|
|
chapterComCalls+=read.ComCalls;chapterParagraphVisits+=read.ParagraphVisits;chapterRcwReleases+=read.ReleaseCalls;chapterPlainBatches+=read.PlainBatches;
|
|
}
|
|
private void ReadChapterStep(LocalDocument doc)
|
|
{
|
|
ChapterRead read;if(!chapterReads.TryGetValue(doc.Session,out read))return;
|
|
if(!documents.ContainsKey(doc.Document)||doc.Revision!=read.Command.Revision||closing.Contains(doc.Document)||ConnectionState!="connected"){CancelChapterRead(doc);return;}
|
|
var watch=Stopwatch.StartNew();executingChapterRead=read;Word.Range point=null,heading=null,range=null;Word.Paragraphs paragraphs=null;Word.Paragraph paragraph=null;
|
|
try
|
|
{
|
|
if((read.Phase<4||read.Phase==6||read.Phase==7||read.Phase==9||read.Phase==10||read.Phase==11||read.Phase==12)&&(!Com(()=>doc.Document.Saved)||Com(()=>application.BackgroundSavingStatus)!=0))throw new InvalidOperationException("Save Word and wait for background saving before validating chapters.");
|
|
if(read.Phase==0){
|
|
if(++read.Steps>128)throw new InvalidOperationException("No bounded Heading 1 boundary could be verified. Use manuscript repair; existing mappings are preserved.");
|
|
point=Com(()=>doc.Document.Range(read.Seek,read.Seek));paragraphs=Com(()=>point.Paragraphs);paragraph=Com(()=>paragraphs[1]);range=Com(()=>paragraph.Range);
|
|
var start=Com(()=>range.Start);var outline=(int)Com(()=>paragraph.OutlineLevel);
|
|
if(outline==1){read.Start=start;read.Seek=start+1;read.Phase=1;}
|
|
else{heading=Com(()=>point.GoTo(What:Word.WdGoToItem.wdGoToHeading,Which:Word.WdGoToDirection.wdGoToPrevious));var previous=Com(()=>heading.Start);if(previous>=read.Seek||previous==0&&start==0){read.Start=-1;read.Seek=0;read.Phase=1;}else read.Seek=previous;}
|
|
}else if(read.Phase==1){
|
|
if(++read.Steps>256)throw new InvalidOperationException("Chapter boundary search exceeded its bound; review the document structure.");
|
|
point=Com(()=>doc.Document.Range(read.Seek,read.Seek));heading=Com(()=>point.GoTo(What:Word.WdGoToItem.wdGoToHeading,Which:Word.WdGoToDirection.wdGoToNext));var next=Com(()=>heading.Start);
|
|
if(next<=read.Seek||next>=doc.End){if(read.Start<0)throw new InvalidOperationException("No Heading 1 chapter is available at this Word location.");read.End=DocumentEnd(doc.Document);read.Phase=2;}
|
|
else{paragraphs=Com(()=>heading.Paragraphs);paragraph=Com(()=>paragraphs[1]);var level=(int)Com(()=>paragraph.OutlineLevel);
|
|
if(level==1){if(read.Start<0){read.Start=next;read.Seek=next+1;}else{read.End=next;read.Seek=next;read.Phase=6;}}
|
|
else read.Seek=next+1;
|
|
}
|
|
}else if(read.Phase==6){
|
|
point=Com(()=>doc.Document.Range(read.Seek,read.Seek));
|
|
paragraphs=Com(()=>point.Paragraphs);paragraph=Com(()=>paragraphs[1]);
|
|
range=Com(()=>paragraph.Range);
|
|
if (Com(()=>range.Start) != read.End || (int)Com(()=>paragraph.OutlineLevel) != 1)
|
|
throw new InvalidOperationException("The next chapter boundary changed during validation.");
|
|
read.NextId=ReadLiveParagraphId(paragraph);read.Phase=2;
|
|
}else if(read.Phase==2){
|
|
if(read.End<=read.Start||read.End-read.Start>ChapterFingerprint.MaxCharacters)throw new InvalidOperationException("This chapter exceeds the bounded fast reader. Use bounded manuscript synchronisation; no mapping was guessed.");
|
|
if(!read.Begun){if(!link.TryPost(new Message{Kind="chapter-begin",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=read.Command.Id,OperationId=read.Command.OperationId,BookId=read.Command.BookId,DocumentEnd=doc.End,Start=read.Start,End=read.End,WordSaved=true,ChapterTitle=read.NextId}))return;read.Begun=true;}
|
|
range=Com(()=>doc.Document.Range(read.Start,read.End));read.Text=Com(()=>range.Text,"chapter-range-text")??"";
|
|
if(read.Text.Length>read.End-read.Start)throw new InvalidOperationException("Word range text exceeds its native positions at "+read.Start+"; this structural expansion requires review.");
|
|
read.PhysicalPositions=read.Text.Length!=read.End-read.Start;
|
|
if(read.PhysicalPositions&&(!nativeChapterPositionsSupported||!read.Command.NativeChapterPositions))
|
|
throw new InvalidOperationException("This chapter has native Word positions without text. Update Companion and the Development server for measured picture-anchor support; existing mappings are retained.");
|
|
read.Phase=3;
|
|
}else if(read.Phase==11){CheckChapterShape(doc,read);
|
|
}else if(read.Phase==3||read.Phase==12){
|
|
range=Com(()=>doc.Document.Range(read.Start,read.End));
|
|
if(read.Phase==3&&liveChapterTextSupported&&!read.PhysicalPositions&&IsPlainChapter(range))
|
|
{
|
|
read.ShapeIndex=1;read.Phase=11;return;
|
|
}
|
|
read.Xml=Com(()=>range.WordOpenXML,"chapter-range-xml")??"";
|
|
if(read.Xml.Length>8*1024*1024)throw new InvalidOperationException("Chapter XML exceeds the bounded transport. Use existing bounded synchronisation.");
|
|
// Drawings, native position gaps and measured breaks need direct paragraph text.
|
|
// A lexical false positive merely performs extra verification.
|
|
read.NativeTextRequired=read.PhysicalPositions||read.Text.IndexOf('\f')>=0||read.Xml.IndexOf(":drawing",StringComparison.Ordinal)>=0||read.Xml.IndexOf("<drawing",StringComparison.Ordinal)>=0;
|
|
if(read.NativeTextRequired&&!nativeChapterTextSupported)throw new InvalidOperationException("Update the Companion agent to verify picture paragraphs. Existing mappings are retained.");
|
|
read.IdentityPosition=read.Start;read.Phase=7;
|
|
}else if(read.Phase==7){
|
|
if(read.LiveText){ReadPlainChapterBatch(doc,read);return;}
|
|
// Structural/native-position extraction retains its qualified one-paragraph step.
|
|
point=Com(()=>doc.Document.Range(read.IdentityPosition,read.IdentityPosition));
|
|
paragraphs=Com(()=>point.Paragraphs);paragraph=Com(()=>paragraphs[1]);range=Com(()=>paragraph.Range);
|
|
var start=Com(()=>range.Start);var end=Com(()=>range.End);
|
|
if(start!=read.IdentityPosition||end<=start||end>read.End||read.Identities.Length/(read.LiveText?24:16)>=ChapterFingerprint.MaxParagraphs)
|
|
throw new InvalidOperationException("Live Word paragraph boundaries do not match the chapter.");
|
|
if(read.PhysicalPositions)
|
|
{
|
|
read.ParagraphVisits++;var nativeText=Com(()=>range.Text,"chapter-native-paragraph-text")??"";
|
|
var evidence=new ChapterParagraph{NativeId=ReadLiveParagraphId(paragraph),Length=nativeText.Length,WordLength=end-start,Outline=(int)Com(()=>paragraph.OutlineLevel)};
|
|
if(nativeText.Length<=0||nativeText.Length>end-start)throw new InvalidOperationException("Unsupported native paragraph text at Word position "+start+": span "+(end-start)+", text units "+nativeText.Length+".");
|
|
if(nativeText.Length==end-start)CompleteChapterNativeParagraph(read,evidence,nativeText,end);
|
|
else{read.PendingStart=start;read.PendingEnd=end;read.PendingText=nativeText;read.PendingPosition=evidence;read.PendingAnchors.Clear();read.ShapeIndex=1;read.Phase=9;}
|
|
return;
|
|
}
|
|
if(read.NativeTextRequired)
|
|
{
|
|
var nativeText=Com(()=>range.Text,"chapter-native-paragraph-text")??"";
|
|
if(nativeText.Length!=end-start)throw new InvalidOperationException("Native paragraph text and Word span disagree; picture positions were not guessed.");
|
|
read.NativeText.Append(nativeText);
|
|
}
|
|
read.ParagraphVisits++;read.Identities.Append(ReadLiveParagraphId(paragraph));
|
|
read.Identities.Append((end-start).ToString("X8",System.Globalization.CultureInfo.InvariantCulture));
|
|
if(read.LiveText)read.Identities.Append(((int)Com(()=>paragraph.OutlineLevel)).ToString("X8",System.Globalization.CultureInfo.InvariantCulture));
|
|
read.IdentityPosition=end;
|
|
if(end==read.End){if(read.NativeTextRequired&&read.NativeText.ToString()!=read.Text)throw new InvalidOperationException("Native paragraph text does not equal the chapter range; retry after saving Word.");read.IdentityFrames=read.Identities.ToString();read.Phase=4;}
|
|
}else if(read.Phase==9){ReadChapterPictureAnchor(doc,read);
|
|
}else if(read.Phase==10){ReadChapterPositionSegment(doc,read);
|
|
}else{
|
|
if(!read.Begun){if(!link.TryPost(new Message{Kind="chapter-begin",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=read.Command.Id,OperationId=read.Command.OperationId,BookId=read.Command.BookId,DocumentEnd=doc.End,Start=read.Start,End=read.End,WordSaved=true,ChapterTitle=read.NextId}))return;read.Begun=true;}
|
|
for(int n=0;n<4&&watch.ElapsedMilliseconds<20;n++){
|
|
var source=read.Phase==4?read.Text:read.Phase==5?read.Xml:read.IdentityFrames;
|
|
if(read.Offset<source.Length){var count=Math.Min(2048,source.Length-read.Offset);if(!link.TryPost(new Message{Kind="chapter-chunk",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=read.Command.Id,Action=read.Phase==4?"text":read.Phase==5?"xml":read.LiveText?"live-text":read.PhysicalPositions?"positions":read.NativeTextRequired?"ids-exact":"ids",Start=read.Offset,OperationMessage=source.Substring(read.Offset,count)}))return;read.Offset+=count;}
|
|
else if(read.Phase<8){read.Phase=read.Phase==4&&!read.LiveText?5:8;read.Offset=0;}
|
|
else{if(!link.TryPost(new Message{Kind="chapter-end",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=read.Command.Id}))return;CompleteChapterReadMetrics(read,watch.Elapsed.TotalMilliseconds);Metric(read.LiveText?"chapter-live-text-complete":"chapter-xml-complete",read.Total.Elapsed.TotalMilliseconds);if(read.LiveText)chapterLiveReads++;else chapterXmlReads++;CancelChapterRead(doc);return;}
|
|
}
|
|
}
|
|
}
|
|
catch(Exception error)when(error is System.Runtime.InteropServices.COMException||error is InvalidOperationException||error is ArgumentException||error is NullReferenceException){CancelChapterRead(doc);Reply(read.Command,"Chapter validation stopped: "+error.Message);lastResult="Chapter validation stopped: "+error.Message;}
|
|
finally{ReleaseChapter(range);ReleaseChapter(paragraph);ReleaseChapter(paragraphs);ReleaseChapter(heading);ReleaseChapter(point);read.ActiveMs+=watch.Elapsed.TotalMilliseconds;executingChapterRead=null;Metric("chapter-ui-step",watch.Elapsed.TotalMilliseconds);if(chapterReads.ContainsKey(doc.Session)&&!scheduler.Post("chapter:"+doc.Session,()=>ReadChapterStep(doc))){CancelChapterRead(doc);Reply(read.Command,"Chapter validation stopped: Word queue is busy. Accepted checkpoints are preserved.");}}
|
|
}
|
|
}
|
|
}
|