Skip to content

Commit

Permalink
fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
adamhathcock committed Dec 3, 2024
1 parent 4a7a961 commit 1ea4acb
Show file tree
Hide file tree
Showing 8 changed files with 121 additions and 95 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,12 @@ protected override ValueTask<T> MainToWorkerAsync<T>(Func<ValueTask<T>> action)
}
else
{
return QueuedTask.Run(async() => await action().BackToCurrent()).AsValueTask();
return QueuedTask.Run(async () => await action().BackToCurrent()).AsValueTask();
}
}

protected override ValueTask<T> WorkerToMainAsync<T>(Func<ValueTask<T>> action) => QueuedTask.Run(async() => await action().BackToCurrent()).AsValueTask();
protected override ValueTask<T> WorkerToMainAsync<T>(Func<ValueTask<T>> action) =>
QueuedTask.Run(async () => await action().BackToCurrent()).AsValueTask();

protected override ValueTask<T> MainToWorker<T>(Func<T> action)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,47 +82,51 @@ private void OnMapViewChanged(ActiveMapViewChangedEventArgs args)
}

protected override void HostAppSaveState(string modelCardState) =>
_threadContext.RunOnWorker(() =>
{
Map map = MapView.Active.Map;
// Read existing metadata - To prevent messing existing metadata. 🤞 Hope other add-in developers will do same :D
var existingMetadata = map.GetMetadata();

// Parse existing metadata
XDocument existingXmlDocument = !string.IsNullOrEmpty(existingMetadata)
? XDocument.Parse(existingMetadata)
: new XDocument(new XElement("metadata"));

XElement xmlModelCards = new("SpeckleModelCards", modelCardState);

// Check if SpeckleModelCards element already exists at root and update it
var speckleModelCardsElement = existingXmlDocument.Root?.Element("SpeckleModelCards");
if (speckleModelCardsElement != null)
_threadContext
.RunOnWorker(() =>
{
speckleModelCardsElement.ReplaceWith(xmlModelCards);
}
else
{
existingXmlDocument.Root?.Add(xmlModelCards);
}

map.SetMetadata(existingXmlDocument.ToString());
}).Wait();
Map map = MapView.Active.Map;
// Read existing metadata - To prevent messing existing metadata. 🤞 Hope other add-in developers will do same :D
var existingMetadata = map.GetMetadata();

// Parse existing metadata
XDocument existingXmlDocument = !string.IsNullOrEmpty(existingMetadata)
? XDocument.Parse(existingMetadata)
: new XDocument(new XElement("metadata"));

XElement xmlModelCards = new("SpeckleModelCards", modelCardState);

// Check if SpeckleModelCards element already exists at root and update it
var speckleModelCardsElement = existingXmlDocument.Root?.Element("SpeckleModelCards");
if (speckleModelCardsElement != null)
{
speckleModelCardsElement.ReplaceWith(xmlModelCards);
}
else
{
existingXmlDocument.Root?.Add(xmlModelCards);
}

map.SetMetadata(existingXmlDocument.ToString());
})
.Wait();

protected override void LoadState() =>
_threadContext.RunOnWorker(() =>
{
Map map = MapView.Active.Map;
var metadata = map.GetMetadata();
var root = XDocument.Parse(metadata).Root;
var element = root?.Element("SpeckleModelCards");
if (element is null)
_threadContext
.RunOnWorker(() =>
{
ClearAndSave();
return;
}

string modelsString = element.Value;
LoadFromString(modelsString);
}).Wait();
Map map = MapView.Active.Map;
var metadata = map.GetMetadata();
var root = XDocument.Parse(metadata).Root;
var element = root?.Element("SpeckleModelCards");
if (element is null)
{
ClearAndSave();
return;
}

string modelsString = element.Value;
LoadFromString(modelsString);
})
.Wait();
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ public class RevitThreadContext : ThreadContext
{
protected override ValueTask<T> MainToWorkerAsync<T>(Func<ValueTask<T>> action) => action();

protected override ValueTask<T> WorkerToMainAsync<T>(Func<ValueTask<T>> action) => RevitTask.RunAsync(async () => await action().BackToCurrent()).AsValueTask();
protected override ValueTask<T> WorkerToMainAsync<T>(Func<ValueTask<T>> action) =>
RevitTask.RunAsync(async () => await action().BackToCurrent()).AsValueTask();

protected override ValueTask<T> MainToWorker<T>(Func<T> action) => new(action());

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,9 @@ public RhinoHostObjectBuilder(
RhinoMaterialBaker materialBaker,
RhinoColorBaker colorBaker,
RhinoGroupBaker groupBaker,
ISdkActivityFactory activityFactory, IThreadContext threadContext)
ISdkActivityFactory activityFactory,
IThreadContext threadContext
)
{
_converter = converter;
_converterSettings = converterSettings;
Expand Down Expand Up @@ -115,13 +117,15 @@ CancellationToken cancellationToken
using (var _ = _activityFactory.Start("Pre baking layers"))
{
//TODO what is this? This is going to the UI thread
_threadContext.RunOnMain(() =>
{
using var layerNoDraw = new DisableRedrawScope(_converterSettings.Current.Document.Views);
var paths = atomicObjectsWithoutInstanceComponentsWithPath.Select(t => t.path).ToList();
paths.AddRange(instanceComponentsWithPath.Select(t => t.path));
_layerBaker.CreateAllLayersForReceive(paths, baseLayerName);
}).Wait();
_threadContext
.RunOnMain(() =>
{
using var layerNoDraw = new DisableRedrawScope(_converterSettings.Current.Document.Views);
var paths = atomicObjectsWithoutInstanceComponentsWithPath.Select(t => t.path).ToList();
paths.AddRange(instanceComponentsWithPath.Select(t => t.path));
_layerBaker.CreateAllLayersForReceive(paths, baseLayerName);
})
.Wait();
}

// 5 - Convert atomic objects
Expand Down Expand Up @@ -245,35 +249,37 @@ private void PreReceiveDeepClean(string baseLayerName)
RhinoMath.UnsetIntIndex
);

_threadContext.RunOnMain(() =>
{
_instanceBaker.PurgeInstances(baseLayerName);
_materialBaker.PurgeMaterials(baseLayerName);

var doc = _converterSettings.Current.Document;
// Cleans up any previously received objects
if (rootLayerIndex != RhinoMath.UnsetIntIndex)
_threadContext
.RunOnMain(() =>
{
var documentLayer = doc.Layers[rootLayerIndex];
var childLayers = documentLayer.GetChildren();
if (childLayers != null)
_instanceBaker.PurgeInstances(baseLayerName);
_materialBaker.PurgeMaterials(baseLayerName);

var doc = _converterSettings.Current.Document;
// Cleans up any previously received objects
if (rootLayerIndex != RhinoMath.UnsetIntIndex)
{
using var layerNoDraw = new DisableRedrawScope(doc.Views);
foreach (var layer in childLayers)
var documentLayer = doc.Layers[rootLayerIndex];
var childLayers = documentLayer.GetChildren();
if (childLayers != null)
{
var purgeSuccess = doc.Layers.Purge(layer.Index, true);
if (!purgeSuccess)
using var layerNoDraw = new DisableRedrawScope(doc.Views);
foreach (var layer in childLayers)
{
Console.WriteLine($"Failed to purge layer: {layer}");
var purgeSuccess = doc.Layers.Purge(layer.Index, true);
if (!purgeSuccess)
{
Console.WriteLine($"Failed to purge layer: {layer}");
}
}
}
doc.Layers.Purge(documentLayer.Index, true);
}
doc.Layers.Purge(documentLayer.Index, true);
}

// Cleans up any previously received group
_groupBaker.PurgeGroups(baseLayerName);
}).Wait();
// Cleans up any previously received group
_groupBaker.PurgeGroups(baseLayerName);
})
.Wait();
}

/// <summary>
Expand Down
36 changes: 19 additions & 17 deletions DUI3/Speckle.Connectors.DUI/Bridge/BrowserBridge.cs
Original file line number Diff line number Diff line change
Expand Up @@ -105,25 +105,27 @@ public string[] GetBindingsMethodNames()
}

public void RunMethod(string methodName, string requestId, string methodArgs) =>
_threadContext.RunOnThreadAsync(
async () =>
{
var task = await TopLevelExceptionHandler
.CatchUnhandledAsync(async () =>
_threadContext
.RunOnThreadAsync(
async () =>
{
var task = await TopLevelExceptionHandler
.CatchUnhandledAsync(async () =>
{
var result = await ExecuteMethod(methodName, methodArgs).ConfigureAwait(false);
string resultJson = _jsonSerializer.Serialize(result);
await NotifyUIMethodCallResultReady(requestId, resultJson).ConfigureAwait(false);
})
.ConfigureAwait(false);
if (task.Exception is not null)
{
var result = await ExecuteMethod(methodName, methodArgs).ConfigureAwait(false);
string resultJson = _jsonSerializer.Serialize(result);
string resultJson = SerializeFormattedException(task.Exception);
await NotifyUIMethodCallResultReady(requestId, resultJson).ConfigureAwait(false);
})
.ConfigureAwait(false);
if (task.Exception is not null)
{
string resultJson = SerializeFormattedException(task.Exception);
await NotifyUIMethodCallResultReady(requestId, resultJson).ConfigureAwait(false);
}
},
_threadOptions.RunCommandsOnMainThread
).Wait();
}
},
_threadOptions.RunCommandsOnMainThread
)
.Wait();

/// <summary>
/// Used by the action block to invoke the actual method called by the UI.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,12 @@ protected override ValueTask<T> WorkerToMainAsync<T>(Func<ValueTask<T>> action)

protected override ValueTask<T> MainToWorkerAsync<T>(Func<ValueTask<T>> action)
{
Task<Task<T>> f = Task.Factory.StartNew(async () => await action().BackToCurrent(), default, TaskCreationOptions.LongRunning, TaskScheduler.Default);
Task<Task<T>> f = Task.Factory.StartNew(
async () => await action().BackToCurrent(),
default,
TaskCreationOptions.LongRunning,
TaskScheduler.Default
);
return new ValueTask<T>(f.Unwrap());
}

Expand Down
5 changes: 2 additions & 3 deletions Sdk/Speckle.Connectors.Common/Threading/ThreadContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ namespace Speckle.Connectors.Common.Threading;
[GenerateAutoInterface]
public abstract class ThreadContext : IThreadContext
{


public static bool IsMainThread => Environment.CurrentManagedThreadId == 1 && !Thread.CurrentThread.IsBackground;

public async ValueTask RunOnThread(Action action, bool useMain)
Expand Down Expand Up @@ -88,7 +86,7 @@ public async ValueTask RunOnThreadAsync(Func<ValueTask> action, bool useMain)
{
await MainToWorkerAsync<object?>(async () =>
{
await action().BackToCurrent();
await action().BackToCurrent();
return new ValueTask<object?>(null);
})
.BackToCurrent();
Expand Down Expand Up @@ -117,6 +115,7 @@ public ValueTask<T> RunOnThreadAsync<T>(Func<ValueTask<T>> action, bool useMain)
}
return action();
}

protected abstract ValueTask<T> WorkerToMainAsync<T>(Func<ValueTask<T>> action);

protected abstract ValueTask<T> MainToWorkerAsync<T>(Func<ValueTask<T>> action);
Expand Down
14 changes: 11 additions & 3 deletions Sdk/Speckle.Connectors.Common/Threading/Yield.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,12 @@ namespace Speckle.Connectors.Common.Threading;

public static class TaskExtensions
{
public static ConfiguredValueTaskAwaitable<T> BackToCurrent<T> (this ValueTask<T> valueTask) => valueTask.ConfigureAwait(true);
public static ConfiguredValueTaskAwaitable<T> BackToCurrent<T>(this ValueTask<T> valueTask) =>
valueTask.ConfigureAwait(true);

public static ConfiguredValueTaskAwaitable<T> BackToAny<T>(this ValueTask<T> valueTask) =>
valueTask.ConfigureAwait(false);

public static ConfiguredValueTaskAwaitable<T> BackToAny<T>(this ValueTask<T> valueTask) => valueTask.ConfigureAwait(false);
public static ConfiguredValueTaskAwaitable BackToCurrent(this ValueTask valueTask) => valueTask.ConfigureAwait(true);

public static ConfiguredValueTaskAwaitable BackToAny(this ValueTask valueTask) => valueTask.ConfigureAwait(false);
Expand All @@ -18,11 +21,16 @@ public static class TaskExtensions
public static ConfiguredTaskAwaitable<T> BackToCurrent<T>(this Task<T> task) => task.ConfigureAwait(true);

public static ConfiguredTaskAwaitable<T> BackToAny<T>(this Task<T> task) => task.ConfigureAwait(false);

public static ValueTask AsValueTask(this Task task) => new(task);

public static ValueTask<T> AsValueTask<T>(this Task<T> task) => new(task);

public static void Wait(this Task task) => task.GetAwaiter().GetResult();

public static T Wait<T>(this Task<T> task) => task.GetAwaiter().GetResult();

public static void Wait(this ValueTask task) => task.GetAwaiter().GetResult();

public static T Wait<T>(this ValueTask<T> task) => task.GetAwaiter().GetResult();
}

0 comments on commit 1ea4acb

Please sign in to comment.