Skip to content

Commit

Permalink
DUI3-71 receive bindings and receive geometry (#3544)
Browse files Browse the repository at this point in the history
* Auto stash before checking out "origin/dui3/alpha"

* Fix Rhino lock

* fix build errors

* address pr comments

* address pr comments

* add jira ticket comments

* proper transaction disposal

---------

Co-authored-by: Connor Ivy <[email protected]>
Co-authored-by: Adam Hathcock <[email protected]>
  • Loading branch information
3 people authored Jul 2, 2024
1 parent a71d37d commit 56496ee
Show file tree
Hide file tree
Showing 69 changed files with 1,053 additions and 58 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="CefSharp.Wpf" IncludeAssets="compile" NoWarn="NU1903"/>
<PackageReference Include="CefSharp.Wpf" IncludeAssets="compile" NoWarn="NU1903" />
<PackageReference Include="Revit.Async" />
</ItemGroup>

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
using Speckle.Connectors.DUI.Bindings;
using Speckle.Connectors.DUI.Bridge;
using Speckle.Connectors.DUI.Models.Card;
using Speckle.Connectors.DUI.Models;
using Speckle.Connectors.Utils.Builders;
using Speckle.Connectors.Utils.Cancellation;
using Speckle.Connectors.Utils.Operations;
using Speckle.Autofac.DependencyInjection;
using Speckle.Connectors.Utils;

namespace Speckle.Connectors.Revit.Bindings;

internal class RevitReceiveBinding : IReceiveBinding
{
public string Name => "receiveBinding";
public IBridge Parent { get; }

private readonly CancellationManager _cancellationManager;
private readonly DocumentModelStore _store;
private readonly IUnitOfWorkFactory _unitOfWorkFactory;
public ReceiveBindingUICommands Commands { get; }

public RevitReceiveBinding(
DocumentModelStore store,
CancellationManager cancellationManager,
IBridge parent,
IUnitOfWorkFactory unitOfWorkFactory
)
{
Parent = parent;
_store = store;
_unitOfWorkFactory = unitOfWorkFactory;
_cancellationManager = cancellationManager;
Commands = new ReceiveBindingUICommands(parent);
}

public void CancelReceive(string modelCardId) => _cancellationManager.CancelOperation(modelCardId);

public async Task Receive(string modelCardId)
{
using var unitOfWork = _unitOfWorkFactory.Resolve<ReceiveOperation>();
try
{
// Get receiver card
if (_store.GetModelById(modelCardId) is not ReceiverModelCard modelCard)
{
// Handle as GLOBAL ERROR at BrowserBridge
throw new InvalidOperationException("No download model card was found.");
}

// Init cancellation token source -> Manager also cancel it if exist before
CancellationTokenSource cts = _cancellationManager.InitCancellationTokenSource(modelCardId);

// Receive host objects
HostObjectBuilderResult conversionResults = await unitOfWork.Service
.Execute(
modelCard.AccountId.NotNull(), // POC: I hear -you are saying why we're passing them separately. Not sure pass the DUI3-> Connectors.DUI project dependency to the SDK-> Connector.Utils
modelCard.ProjectId.NotNull(),
modelCard.ProjectName.NotNull(),
modelCard.ModelName.NotNull(),
modelCard.SelectedVersionId.NotNull(),
cts.Token,
(status, progress) =>
Commands.SetModelProgress(modelCardId, new ModelCardProgress(modelCardId, status, progress), cts)
)
.ConfigureAwait(false);

modelCard.BakedObjectIds = conversionResults.BakedObjectIds.ToList();
Commands.SetModelReceiveResult(
modelCardId,
conversionResults.BakedObjectIds,
conversionResults.ConversionResults
);
}
// Catch here specific exceptions if they related to model card.
catch (OperationCanceledException)
{
// SWALLOW -> UI handles it immediately, so we do not need to handle anything
return;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,17 @@
using Speckle.Autofac.DependencyInjection;
using Speckle.Connectors.DUI;
using Speckle.Connectors.DUI.Bindings;
using Speckle.Connectors.DUI.Bridge;
using Speckle.Connectors.DUI.Models;
using Speckle.Connectors.Revit.Bindings;
using Speckle.Connectors.Revit.HostApp;
using Speckle.Connectors.Revit.Operations.Receive;
using Speckle.Connectors.Revit.Operations.Send;
using Speckle.Connectors.Revit.Plugin;
using Speckle.Connectors.Utils;
using Speckle.Connectors.Utils.Builders;
using Speckle.Connectors.Utils.Caching;
using Speckle.Connectors.Utils.Operations;
using Speckle.Core.Models.GraphTraversal;

namespace Speckle.Connectors.Revit.DependencyInjection;

Expand All @@ -27,7 +28,7 @@ public void Load(SpeckleContainerBuilder builder)
builder.AddDUI();
//builder.AddDUIView();

builder.AddSingletonInstance<ISyncToThread, SyncToCurrentThread>();
builder.AddSingletonInstance<ISyncToThread, RevitContextAccessor>();

// POC: different versons for different versions of CEF
builder.AddSingleton(BindingOptions.DefaultBinder);
Expand All @@ -49,20 +50,23 @@ public void Load(SpeckleContainerBuilder builder)
// and where the UoW should be
// register UI bindings
builder.AddSingleton<IBinding, TestBinding>();
builder.AddSingleton<IBinding, ConfigBinding>("connectorName", "ArcGIS"); // POC: Easier like this for now, should be cleaned up later
builder.AddSingleton<IBinding, ConfigBinding>("connectorName", "Revit"); // POC: Easier like this for now, should be cleaned up later
builder.AddSingleton<IBinding, AccountBinding>();
builder.AddSingleton<IBinding, BasicConnectorBindingRevit>();
builder.AddSingleton<IBasicConnectorBinding, BasicConnectorBindingRevit>();
builder.AddSingleton<IBinding, SelectionBinding>();
builder.AddSingleton<IBinding, RevitSendBinding>();
//no receive?
builder.AddSingleton<IBinding, RevitReceiveBinding>();
builder.AddSingleton<IRevitIdleManager, RevitIdleManager>();

// send operation and dependencies
builder.AddScoped<SendOperation<ElementId>>();
builder.AddScoped<IRootObjectBuilder<ElementId>, RevitRootObjectBuilder>();

// register send conversion cache
builder.AddSingleton<ISendConversionCache, SendConversionCache>();

// receive operation and dependencies
builder.AddScoped<IHostObjectBuilder, RevitHostObjectBuilder>();
builder.AddScoped<ITransactionManager, TransactionManager>();
builder.AddSingleton(DefaultTraversal.CreateTraversalFunc());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using Autodesk.Revit.DB;

namespace Speckle.Connectors.Revit.Operations.Receive;

public interface ITransactionManager : IDisposable
{
TransactionStatus CommitSubtransaction();
TransactionStatus CommitTransaction();
void RollbackSubTransaction();
void RollbackTransaction();
void StartSubtransaction();
void StartTransaction();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
using Revit.Async;
using Speckle.Connectors.Utils.Operations;

namespace Speckle.Connectors.Revit.Operations.Receive;

internal class RevitContextAccessor : ISyncToThread
{
public Task<T> RunOnThread<T>(Func<T> func) => RevitTask.RunAsync(func);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
using Speckle.Connectors.Utils.Builders;
using Speckle.Connectors.Utils.Conversion;
using Speckle.Converters.Common;
using Speckle.Core.Logging;
using Speckle.Core.Models.GraphTraversal;
using Speckle.Core.Models;
using Speckle.Converters.RevitShared.Helpers;
using Autodesk.Revit.DB;

namespace Speckle.Connectors.Revit.Operations.Receive;

/// <summary>
/// Potentially consolidate all application specific IHostObjectBuilders
/// https://spockle.atlassian.net/browse/DUI3-465
/// </summary>
internal class RevitHostObjectBuilder : IHostObjectBuilder, IDisposable
{
private readonly IRootToHostConverter _converter;
private readonly IRevitConversionContextStack _contextStack;
private readonly GraphTraversal _traverseFunction;
private readonly ITransactionManager _transactionManager;

public RevitHostObjectBuilder(
IRootToHostConverter converter,
IRevitConversionContextStack contextStack,
GraphTraversal traverseFunction,
ITransactionManager transactionManager
)
{
_converter = converter;
_contextStack = contextStack;
_traverseFunction = traverseFunction;
_transactionManager = transactionManager;
}

public HostObjectBuilderResult Build(
Base rootObject,
string projectName,
string modelName,
Action<string, double?>? onOperationProgressed,
CancellationToken cancellationToken
)
{
var objectsToConvert = _traverseFunction
.TraverseWithProgress(rootObject, onOperationProgressed, cancellationToken)
.Where(obj => obj.Current is not Collection);

using TransactionGroup transactionGroup = new(_contextStack.Current.Document, $"Received data from {projectName}");
transactionGroup.Start();
_transactionManager.StartTransaction();

var conversionResults = BakeObjects(objectsToConvert);

_transactionManager.CommitTransaction();
transactionGroup.Assimilate();

return conversionResults;
}

// POC: Potentially refactor out into an IObjectBaker.
private HostObjectBuilderResult BakeObjects(IEnumerable<TraversalContext> objectsGraph)
{
var conversionResults = new List<ReceiveConversionResult>();
var bakedObjectIds = new List<string>();

foreach (TraversalContext tc in objectsGraph)
{
try
{
var result = _converter.Convert(tc.Current);
}
catch (Exception ex) when (!ex.IsFatal())
{
conversionResults.Add(new(Status.ERROR, tc.Current, null, null, ex));
}
}

return new(bakedObjectIds, conversionResults);
}

public void Dispose()
{
_transactionManager?.Dispose();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
using Autodesk.Revit.DB;
using Speckle.Converters.RevitShared.Helpers;

namespace Speckle.Connectors.Revit.Operations.Receive;

/// <summary>
/// Is responsible for all functionality regarding subtransactions, transactions, and transaction groups.
/// This includes starting, pausing, committing, and rolling back transactions
/// </summary>
public sealed class TransactionManager : ITransactionManager
{
private readonly IRevitConversionContextStack _contextStack;
private Document Document => _contextStack.Current.Document;

public TransactionManager(IRevitConversionContextStack contextStack)
{
_contextStack = contextStack;
}

// poc : these are being disposed. I'm not sure why I need to supress this warning
#pragma warning disable CA2213 // Disposable fields should be disposed
private Transaction? _transaction;
private SubTransaction? _subTransaction;
#pragma warning restore CA2213 // Disposable fields should be disposed

public void StartTransaction()
{
if (_transaction == null || !_transaction.IsValidObject || _transaction.GetStatus() != TransactionStatus.Started)
{
_transaction = new Transaction(Document, "Speckle Transaction");
var failOpts = _transaction.GetFailureHandlingOptions();
// POC: make sure to implement and add the failure preprocessor
// https://spockle.atlassian.net/browse/DUI3-461
//failOpts.SetFailuresPreprocessor(_errorPreprocessingService);
failOpts.SetClearAfterRollback(true);
_transaction.SetFailureHandlingOptions(failOpts);
_transaction.Start();
}
}

public TransactionStatus CommitTransaction()
{
if (
_subTransaction != null
&& _subTransaction.IsValidObject
&& _subTransaction.GetStatus() == TransactionStatus.Started
)
{
var status = _subTransaction.Commit();
if (status != TransactionStatus.Committed)
{
// POC: handle failed commit
//HandleFailedCommit(status);
}
}
if (_transaction != null && _transaction.IsValidObject && _transaction.GetStatus() == TransactionStatus.Started)
{
var status = _transaction.Commit();
if (status != TransactionStatus.Committed)
{
// POC: handle failed commit
//HandleFailedCommit(status);
}
return status;
}
return TransactionStatus.Uninitialized;
}

public void RollbackTransaction()
{
RollbackSubTransaction();
if (_transaction != null && _transaction.IsValidObject && _transaction.GetStatus() == TransactionStatus.Started)
{
_transaction.RollBack();
}
}

public void StartSubtransaction()
{
StartTransaction();
if (
_subTransaction == null
|| !_subTransaction.IsValidObject
|| _subTransaction.GetStatus() != TransactionStatus.Started
)
{
_subTransaction = new SubTransaction(Document);
_subTransaction.Start();
}
}

public TransactionStatus CommitSubtransaction()
{
if (_subTransaction != null && _subTransaction.IsValidObject)
{
var status = _subTransaction.Commit();
if (status != TransactionStatus.Committed)
{
// POC: handle failed commit
//HandleFailedCommit(status);
}
return status;
}
return TransactionStatus.Uninitialized;
}

public void RollbackSubTransaction()
{
if (
_subTransaction != null
&& _subTransaction.IsValidObject
&& _subTransaction.GetStatus() == TransactionStatus.Started
)
{
_subTransaction.RollBack();
}
}

public void Dispose()
{
_subTransaction?.Dispose();
_transaction?.Dispose();
}
}
Loading

0 comments on commit 56496ee

Please sign in to comment.