diff --git a/SpeckleGrasshopper/BaseComponents/GhReceiverCoreClient.cs b/SpeckleGrasshopper/BaseComponents/GhReceiverCoreClient.cs index 205d646..2d0c1a4 100644 --- a/SpeckleGrasshopper/BaseComponents/GhReceiverCoreClient.cs +++ b/SpeckleGrasshopper/BaseComponents/GhReceiverCoreClient.cs @@ -76,7 +76,7 @@ public override bool Write( GH_IWriter writer ) formatter.Serialize( ms, Client ); writer.SetByteArray( "speckleclient", ms.ToArray() ); } - writer.SetBoolean("deserialize", this.Deserialize); + writer.SetBoolean( "deserialize", this.Deserialize ); } catch { } return base.Write( writer ); @@ -101,7 +101,7 @@ public override bool Read( GH_IReader reader ) InitReceiverEventsAndGlobals(); } - this.Deserialize = reader.GetBoolean("deserialize"); + this.Deserialize = reader.GetBoolean( "deserialize" ); } catch { @@ -117,23 +117,34 @@ public override void AddedToDocument( GH_Document document ) if ( Client == null ) { - var myForm = new SpecklePopup.MainWindow( false, true ); - - var some = new System.Windows.Interop.WindowInteropHelper( myForm ); - some.Owner = Rhino.RhinoApp.MainWindowHandle(); - - myForm.ShowDialog(); - - if ( myForm.restApi != null && myForm.apitoken != null ) + Account account = null; + try { - RestApi = myForm.restApi; - AuthToken = myForm.apitoken; + account = LocalContext.GetDefaultAccount(); } - else + catch ( Exception err ) { - AddRuntimeMessage( GH_RuntimeMessageLevel.Error, "Account selection failed." ); - return; } + + if ( account == null ) + { + var signInWindow = new SpecklePopup.SignInWindow( true ); + var helper = new System.Windows.Interop.WindowInteropHelper( signInWindow ); + helper.Owner = Rhino.RhinoApp.MainWindowHandle(); + + signInWindow.ShowDialog(); + + if ( signInWindow.AccountListBox.SelectedIndex != -1 ) + account = signInWindow.accounts[ signInWindow.AccountListBox.SelectedIndex ]; + else + { + AddRuntimeMessage( GH_RuntimeMessageLevel.Error, "Account selection failed." ); + return; + } + } + + RestApi = account.RestApi; + AuthToken = account.Token; } StreamIdChanger = new System.Timers.Timer( 1000 ); StreamIdChanger.Enabled = false; @@ -185,15 +196,15 @@ public override void AppendAdditionalMenuItems( ToolStripDropDown menu ) GH_DocumentObject.Menu_AppendSeparator( menu ); base.AppendAdditionalMenuItems( menu ); - var toggleItem = new ToolStripMenuItem("Deserialize objects.") { Name = "Deserialize objects.", Checked = this.Deserialize, CheckOnClick = true }; - toggleItem.CheckStateChanged += (sender, e) => + var toggleItem = new ToolStripMenuItem( "Deserialize objects." ) { Name = "Deserialize objects.", Checked = this.Deserialize, CheckOnClick = true }; + toggleItem.CheckStateChanged += ( sender, e ) => { - this.Deserialize = ((ToolStripMenuItem)sender).Checked; - Rhino.RhinoApp.MainApplicationWindow.Invoke(expireComponentAction); + this.Deserialize = ( ( ToolStripMenuItem ) sender ).Checked; + Rhino.RhinoApp.InvokeOnUiThread( expireComponentAction ); }; - menu.Items.Add(toggleItem); + menu.Items.Add( toggleItem ); - GH_DocumentObject.Menu_AppendSeparator(menu); + GH_DocumentObject.Menu_AppendSeparator( menu ); GH_DocumentObject.Menu_AppendItem( menu, "Force refresh.", ( sender, e ) => { @@ -206,7 +217,7 @@ public override void AppendAdditionalMenuItems( ToolStripDropDown menu ) GH_DocumentObject.Menu_AppendItem( menu, "View stream.", ( sender, e ) => { if ( StreamId == null ) return; - System.Diagnostics.Process.Start(RestApi.Replace("/api/v1", "/#/view").Replace("/api", "/#/view") + @"/" + StreamId); + System.Diagnostics.Process.Start( RestApi.Replace( "/api/v1", "/#/view" ).Replace( "/api", "/#/view" ) + @"/" + StreamId ); } ); GH_DocumentObject.Menu_AppendItem( menu, "(API) View stream data.", ( sender, e ) => @@ -326,14 +337,14 @@ public virtual void UpdateGlobal( ) this.Message = SNJ.JsonConvert.SerializeObject( String.Format( "{0}/{1}", i, payload.Length ) ); } - foreach( var obj in newObjects ) + foreach ( var obj in newObjects ) { var matches = Client.Stream.Objects.FindAll( o => o._id == obj._id ); //TODO: Do this efficiently, this is rather brute force - for( int i = Client.Stream.Objects.Count - 1; i >= 0; i-- ) + for ( int i = Client.Stream.Objects.Count - 1; i >= 0; i-- ) { - if(Client.Stream.Objects[i]._id == obj._id) + if ( Client.Stream.Objects[ i ]._id == obj._id ) { Client.Stream.Objects[ i ] = obj; } @@ -356,14 +367,14 @@ public virtual void UpdateGlobal( ) SpeckleObjects.Clear(); - Task.Run(() => - { - ConvertedObjects = SpeckleCore.Converter.Deserialise(Client.Stream.Objects); - IsUpdating = false; - Rhino.RhinoApp.MainApplicationWindow.Invoke(expireComponentAction); + Task.Run( ( ) => + { + ConvertedObjects = SpeckleCore.Converter.Deserialise( Client.Stream.Objects ); + IsUpdating = false; + Rhino.RhinoApp.InvokeOnUiThread( expireComponentAction ); - this.Message = "Got data\n@" + DateTime.Now.ToString("hh:mm:ss"); - }); + this.Message = "Got data\n@" + DateTime.Now.ToString( "hh:mm:ss" ); + } ); } public virtual void UpdateMeta( ) @@ -471,7 +482,7 @@ public void UpdateOutputStructure( ) foreach ( var layer in toAdd ) { Param_GenericObject newParam = getGhParameter( layer ); - Params.RegisterOutputParam( newParam, layer.OrderIndex != null ? ( int ) layer.OrderIndex : k ); + Params.RegisterOutputParam( newParam, layer.OrderIndex != null ? ( int ) layer.OrderIndex : k ); k++; } @@ -487,10 +498,10 @@ public void SetObjects( IGH_DataAccess DA ) { if ( Layers == null ) return; if ( ConvertedObjects.Count == 0 && this.Deserialize ) return; - if ( Client.Stream.Objects.Count == 0 && !this.Deserialize) return; + if ( Client.Stream.Objects.Count == 0 && !this.Deserialize ) return; List chosenObjects; - if (this.Deserialize) + if ( this.Deserialize ) chosenObjects = ConvertedObjects; else chosenObjects = Client.Stream.Objects.Cast().ToList(); @@ -528,7 +539,7 @@ public void SetObjects( IGH_DataAccess DA ) subsetCount += elCount; } } - DA.SetDataTree( layer.OrderIndex!=null ? ( int ) layer.OrderIndex : k, tree ); + DA.SetDataTree( layer.OrderIndex != null ? ( int ) layer.OrderIndex : k, tree ); k++; } } diff --git a/SpeckleGrasshopper/BaseComponents/GhSenderCoreClient.cs b/SpeckleGrasshopper/BaseComponents/GhSenderCoreClient.cs index 9915d1b..81d3428 100644 --- a/SpeckleGrasshopper/BaseComponents/GhSenderCoreClient.cs +++ b/SpeckleGrasshopper/BaseComponents/GhSenderCoreClient.cs @@ -58,10 +58,10 @@ public class GhSenderClient : GH_Component, IGH_VariableParameterComponent public string State; - public GhSenderClient() - : base("Data Sender", "Anonymous Stream", + public GhSenderClient( ) + : base( "Data Sender", "Anonymous Stream", "Sends data to Speckle.", - "Speckle", "I/O") + "Speckle", "I/O" ) { SpeckleCore.SpeckleInitializer.Initialize(); SpeckleCore.LocalContext.Init(); @@ -69,141 +69,150 @@ public GhSenderClient() JobQueue = new OrderedDictionary(); } - public override void CreateAttributes() + public override void CreateAttributes( ) { - m_attributes = new GhSenderClientAttributes(this); + m_attributes = new GhSenderClientAttributes( this ); } - public override bool Write(GH_IWriter writer) + public override bool Write( GH_IWriter writer ) { try { - if (Client != null) + if ( Client != null ) { - using (var ms = new MemoryStream()) + using ( var ms = new MemoryStream() ) { var formatter = new BinaryFormatter(); - formatter.Serialize(ms, Client); + formatter.Serialize( ms, Client ); var arr = ms.ToArray(); var arrr = arr; - writer.SetByteArray("speckleclient", ms.ToArray()); - writer.SetBoolean("remotecontroller", EnableRemoteControl); - writer.SetBoolean("manualmode", ManualMode); + writer.SetByteArray( "speckleclient", ms.ToArray() ); + writer.SetBoolean( "remotecontroller", EnableRemoteControl ); + writer.SetBoolean( "manualmode", ManualMode ); } } } - catch (Exception err) + catch ( Exception err ) { throw err; } - return base.Write(writer); + return base.Write( writer ); } - public override bool Read(GH_IReader reader) + public override bool Read( GH_IReader reader ) { try { - var serialisedClient = reader.GetByteArray("speckleclient"); + var serialisedClient = reader.GetByteArray( "speckleclient" ); var copy = serialisedClient; - using (var ms = new MemoryStream()) + using ( var ms = new MemoryStream() ) { - ms.Write(serialisedClient, 0, serialisedClient.Length); - ms.Seek(0, SeekOrigin.Begin); - Client = (SpeckleApiClient)new BinaryFormatter().Deserialize(ms); + ms.Write( serialisedClient, 0, serialisedClient.Length ); + ms.Seek( 0, SeekOrigin.Begin ); + Client = ( SpeckleApiClient ) new BinaryFormatter().Deserialize( ms ); var x = Client; RestApi = Client.BaseUrl; StreamId = Client.StreamId; WasSerialised = true; } - reader.TryGetBoolean("remotecontroller", ref EnableRemoteControl); - reader.TryGetBoolean("manualmode", ref ManualMode); + reader.TryGetBoolean( "remotecontroller", ref EnableRemoteControl ); + reader.TryGetBoolean( "manualmode", ref ManualMode ); } - catch (Exception err) + catch ( Exception err ) { this.AddRuntimeMessage( GH_RuntimeMessageLevel.Error, "Failed to reinitialise sender." ); //throw err; } - return base.Read(reader); + return base.Read( reader ); } - public override void AddedToDocument(GH_Document document) + public override void AddedToDocument( GH_Document document ) { - base.AddedToDocument(document); + base.AddedToDocument( document ); Document = OnPingDocument(); - if (Client == null) + if ( Client == null ) { - NickName = "Initialising..."; Locked = true; + NickName = "Initialising"; - var myForm = new SpecklePopup.MainWindow(false, true); + Account account = null; + try + { + account = LocalContext.GetDefaultAccount(); + } + catch ( Exception err ) + { + } - var some = new System.Windows.Interop.WindowInteropHelper(myForm) + if ( account == null ) { - Owner = Rhino.RhinoApp.MainWindowHandle() - }; + var signInWindow = new SpecklePopup.SignInWindow( true ); + var helper = new System.Windows.Interop.WindowInteropHelper( signInWindow ); + helper.Owner = Rhino.RhinoApp.MainWindowHandle(); - myForm.ShowDialog(); + signInWindow.ShowDialog(); - if (myForm.restApi != null && myForm.apitoken != null) - { - Client = new SpeckleApiClient(myForm.restApi); - RestApi = myForm.restApi; - Client.IntializeSender(myForm.apitoken, Document.DisplayName, "Grasshopper", Document.DocumentID.ToString()).ContinueWith(task => + if ( signInWindow.AccountListBox.SelectedIndex != -1 ) { - Rhino.RhinoApp.MainApplicationWindow.Invoke(ExpireComponentAction); - }); - } - else - { - AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Account selection failed"); - return; + account = signInWindow.accounts[ signInWindow.AccountListBox.SelectedIndex ]; + RestApi = account.RestApi; + Client = new SpeckleApiClient( account.RestApi ); + Client.IntializeSender( account.Token, Document.DisplayName, "Grasshopper", Document.DocumentID.ToString() ).ContinueWith( task => + { + Rhino.RhinoApp.InvokeOnUiThread( ExpireComponentAction ); + } ); + } + else + { + AddRuntimeMessage( GH_RuntimeMessageLevel.Error, "Account selection failed." ); + return; + } } - } else { } - Client.OnReady += (sender, e) => + Client.OnReady += ( sender, e ) => { StreamId = Client.StreamId; - if (!WasSerialised) + if ( !WasSerialised ) { Locked = false; NickName = "Anonymous Stream"; } ////this.UpdateMetadata(); - Rhino.RhinoApp.MainApplicationWindow.Invoke(ExpireComponentAction); + Rhino.RhinoApp.InvokeOnUiThread( ExpireComponentAction ); }; Client.OnWsMessage += OnWsMessage; - Client.OnLogData += (sender, e) => + Client.OnLogData += ( sender, e ) => { - Log += DateTime.Now.ToString("dd:HH:mm:ss ") + e.EventData + "\n"; + Log += DateTime.Now.ToString( "dd:HH:mm:ss " ) + e.EventData + "\n"; }; - Client.OnError += (sender, e) => + Client.OnError += ( sender, e ) => { - AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.EventName + ": " + e.EventData); - Log += DateTime.Now.ToString("dd:HH:mm:ss ") + e.EventData + "\n"; + AddRuntimeMessage( GH_RuntimeMessageLevel.Error, e.EventName + ": " + e.EventData ); + Log += DateTime.Now.ToString( "dd:HH:mm:ss " ) + e.EventData + "\n"; }; - ExpireComponentAction = () => ExpireSolution(true); + ExpireComponentAction = ( ) => ExpireSolution( true ); - ObjectChanged += (sender, e) => UpdateMetadata(); + ObjectChanged += ( sender, e ) => UpdateMetadata(); - foreach (var param in Params.Input) + foreach ( var param in Params.Input ) { - param.ObjectChanged += (sender, e) => UpdateMetadata(); + param.ObjectChanged += ( sender, e ) => UpdateMetadata(); } - MetadataSender = new System.Timers.Timer(1000) { AutoReset = false, Enabled = false }; + MetadataSender = new System.Timers.Timer( 1000 ) { AutoReset = false, Enabled = false }; MetadataSender.Elapsed += MetadataSender_Elapsed; - DataSender = new System.Timers.Timer(2000) { AutoReset = false, Enabled = false }; + DataSender = new System.Timers.Timer( 2000 ) { AutoReset = false, Enabled = false }; DataSender.Elapsed += DataSender_Elapsed; ObjectCache = new Dictionary(); @@ -211,65 +220,65 @@ public override void AddedToDocument(GH_Document document) Grasshopper.Instances.DocumentServer.DocumentRemoved += DocumentServer_DocumentRemoved; } - private void DocumentServer_DocumentRemoved(GH_DocumentServer sender, GH_Document doc) + private void DocumentServer_DocumentRemoved( GH_DocumentServer sender, GH_Document doc ) { - if (doc.DocumentID == Document.DocumentID) + if ( doc.DocumentID == Document.DocumentID ) { DocumentIsClosing = true; } } - public virtual void OnWsMessage(object source, SpeckleEventArgs e) + public virtual void OnWsMessage( object source, SpeckleEventArgs e ) { try { - AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, e.EventObject.args.eventType + "received at " + DateTime.Now + " from " + e.EventObject.senderId); - switch ((string)e.EventObject.args.eventType) + AddRuntimeMessage( GH_RuntimeMessageLevel.Remark, e.EventObject.args.eventType + "received at " + DateTime.Now + " from " + e.EventObject.senderId ); + switch ( ( string ) e.EventObject.args.eventType ) { case "get-definition-io": - if (EnableRemoteControl == false) + if ( EnableRemoteControl == false ) { return; } Dictionary message = new Dictionary(); - message["eventType"] = "get-def-io-response"; - message["controllers"] = DefaultSpeckleInputs; - message["outputs"] = DefaultSpeckleOutputs; + message[ "eventType" ] = "get-def-io-response"; + message[ "controllers" ] = DefaultSpeckleInputs; + message[ "outputs" ] = DefaultSpeckleOutputs; - Client.SendMessage(e.EventObject.senderId, message); + Client.SendMessage( e.EventObject.senderId, message ); break; case "compute-request": - if (EnableRemoteControl == true) + if ( EnableRemoteControl == true ) { - var requestClientId = (string)e.EventObject.senderId; - if (JobQueue.Contains(requestClientId)) + var requestClientId = ( string ) e.EventObject.senderId; + if ( JobQueue.Contains( requestClientId ) ) { - JobQueue[requestClientId] = e.EventObject.args.requestParameters; + JobQueue[ requestClientId ] = e.EventObject.args.requestParameters; } else { - JobQueue.Add(requestClientId, e.EventObject.args.requestParameters); + JobQueue.Add( requestClientId, e.EventObject.args.requestParameters ); } - AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, Document.SolutionState.ToString()); + AddRuntimeMessage( GH_RuntimeMessageLevel.Remark, Document.SolutionState.ToString() ); - if (JobQueue.Count == 1) // means we just added one, so we need to start the solve loop + if ( JobQueue.Count == 1 ) // means we just added one, so we need to start the solve loop { - Rhino.RhinoApp.MainApplicationWindow.Invoke(ExpireComponentAction); + Rhino.RhinoApp.InvokeOnUiThread( ExpireComponentAction ); } } else { Dictionary computeMessage = new Dictionary(); - computeMessage["eventType"] = "compute-request-error"; - computeMessage["response"] = "Remote control is disabled for this sender"; - Client.SendMessage(e.EventObject.senderId, computeMessage); + computeMessage[ "eventType" ] = "compute-request-error"; + computeMessage[ "response" ] = "Remote control is disabled for this sender"; + Client.SendMessage( e.EventObject.senderId, computeMessage ); } break; default: - Log += DateTime.Now.ToString("dd:HH:mm:ss") + " Defaulted, could not parse event. \n"; + Log += DateTime.Now.ToString( "dd:HH:mm:ss" ) + " Defaulted, could not parse event. \n"; break; } } @@ -277,42 +286,42 @@ public virtual void OnWsMessage(object source, SpeckleEventArgs e) { } - Debug.WriteLine("[Gh Sender] Got a volatile message. Extend this class and implement custom protocols at ease."); + Debug.WriteLine( "[Gh Sender] Got a volatile message. Extend this class and implement custom protocols at ease." ); } - private void GetSpeckleParams(ref List speckleInputs, ref List speckleOutputs) + private void GetSpeckleParams( ref List speckleInputs, ref List speckleOutputs ) { speckleInputs = new List(); speckleOutputs = new List(); - foreach (var comp in Document.Objects) + foreach ( var comp in Document.Objects ) { var slider = comp as GH_NumberSlider; - if (slider != null) + if ( slider != null ) { - if (slider.NickName.Contains("SPK_IN")) + if ( slider.NickName.Contains( "SPK_IN" ) ) { var n = new SpeckleInput(); - n.Min = (double)slider.Slider.Minimum; - n.Max = (double)slider.Slider.Maximum; - n.Value = (double)slider.Slider.Value; - n.Step = getSliderStep(slider.Slider); + n.Min = ( double ) slider.Slider.Minimum; + n.Max = ( double ) slider.Slider.Maximum; + n.Value = ( double ) slider.Slider.Value; + n.Step = getSliderStep( slider.Slider ); //n.OrderIndex = Convert.ToInt32(slider.NickName.Split(':')[1]); //n.Name = slider.NickName.Split(':')[2]; n.Name = slider.NickName; n.InputType = "Slider"; n.Guid = slider.InstanceGuid.ToString(); - speckleInputs.Add(n); + speckleInputs.Add( n ); } } } } - private double getSliderStep(GH_SliderBase gH_NumberSlider) + private double getSliderStep( GH_SliderBase gH_NumberSlider ) { - switch (gH_NumberSlider.Type) + switch ( gH_NumberSlider.Type ) { case GH_SliderAccuracy.Float: - double i = 1 / Math.Pow(10, gH_NumberSlider.DecimalPlaces); + double i = 1 / Math.Pow( 10, gH_NumberSlider.DecimalPlaces ); return i; case GH_SliderAccuracy.Integer: return 1; @@ -324,201 +333,201 @@ private double getSliderStep(GH_SliderBase gH_NumberSlider) throw new NotImplementedException(); } - public override void RemovedFromDocument(GH_Document document) + public override void RemovedFromDocument( GH_Document document ) { - if (Client != null) + if ( Client != null ) { //Client.StreamUpdateAsync(Client.StreamId, new SpeckleStream() { Deleted = true }); - Client.Dispose(false); + Client.Dispose( false ); } - base.RemovedFromDocument(document); + base.RemovedFromDocument( document ); } - public override void DocumentContextChanged(GH_Document document, GH_DocumentContext context) + public override void DocumentContextChanged( GH_Document document, GH_DocumentContext context ) { - base.DocumentContextChanged(document, context); + base.DocumentContextChanged( document, context ); } - public override void AppendAdditionalMenuItems(ToolStripDropDown menu) + public override void AppendAdditionalMenuItems( ToolStripDropDown menu ) { - base.AppendAdditionalMenuItems(menu); - GH_DocumentObject.Menu_AppendItem(menu, "Copy streamId (" + StreamId + ") to clipboard.", (sender, e) => - { - if (StreamId != null) - { - System.Windows.Clipboard.SetText(StreamId); - } - }); - - GH_DocumentObject.Menu_AppendSeparator(menu); - - base.AppendAdditionalMenuItems(menu); - GH_DocumentObject.Menu_AppendItem(menu, "Force refresh.", (sender, e) => - { - if (StreamId != null) + base.AppendAdditionalMenuItems( menu ); + GH_DocumentObject.Menu_AppendItem( menu, "Copy streamId (" + StreamId + ") to clipboard.", ( sender, e ) => { - DataSender.Start(); - } - }); - - GH_DocumentObject.Menu_AppendSeparator(menu); + if ( StreamId != null ) + { + System.Windows.Clipboard.SetText( StreamId ); + } + } ); - base.AppendAdditionalMenuItems(menu); - GH_DocumentObject.Menu_AppendItem(menu, "Toggle Manual Mode (Status: " + ManualMode + ")", (sender, e) => - { - ManualMode = !ManualMode; - m_attributes.ExpireLayout(); - - if (!ManualMode && State == "Expired") - { - UpdateData(); - } - }); + GH_DocumentObject.Menu_AppendSeparator( menu ); - GH_DocumentObject.Menu_AppendSeparator(menu); - - GH_DocumentObject.Menu_AppendItem(menu, "View stream.", (sender, e) => + base.AppendAdditionalMenuItems( menu ); + GH_DocumentObject.Menu_AppendItem( menu, "Force refresh.", ( sender, e ) => { - if (StreamId == null) + if ( StreamId != null ) { - return; + DataSender.Start(); } + } ); - System.Diagnostics.Process.Start(RestApi.Replace("/api/v1", "/#/view").Replace("/api", "/#/view") + @"/" + StreamId); - }); + GH_DocumentObject.Menu_AppendSeparator( menu ); - GH_DocumentObject.Menu_AppendItem(menu, "(API) View stream data.", (sender, e) => + base.AppendAdditionalMenuItems( menu ); + GH_DocumentObject.Menu_AppendItem( menu, "Toggle Manual Mode (Status: " + ManualMode + ")", ( sender, e ) => { - if (StreamId == null) + ManualMode = !ManualMode; + m_attributes.ExpireLayout(); + + if ( !ManualMode && State == "Expired" ) { - return; + UpdateData(); } + } ); - System.Diagnostics.Process.Start(RestApi + @"/streams/" + StreamId); - }); + GH_DocumentObject.Menu_AppendSeparator( menu ); - GH_DocumentObject.Menu_AppendItem(menu, "(API) View objects data online.", (sender, e) => - { - if (StreamId == null) - { - return; - } + GH_DocumentObject.Menu_AppendItem( menu, "View stream.", ( sender, e ) => + { + if ( StreamId == null ) + { + return; + } - System.Diagnostics.Process.Start(RestApi + @"/streams/" + StreamId + @"/objects?omit=displayValue,base64"); - }); + System.Diagnostics.Process.Start( RestApi.Replace( "/api/v1", "/#/view" ).Replace( "/api", "/#/view" ) + @"/" + StreamId ); + } ); - GH_DocumentObject.Menu_AppendSeparator(menu); - GH_DocumentObject.Menu_AppendItem(menu, "Save current stream as a version.", (sender, e) => - { - var cloneResult = Client.StreamCloneAsync(StreamId).Result; - Client.Stream.Children.Add(cloneResult.Clone.StreamId); + GH_DocumentObject.Menu_AppendItem( menu, "(API) View stream data.", ( sender, e ) => + { + if ( StreamId == null ) + { + return; + } - Client.BroadcastMessage("stream", Client.StreamId, new { eventType = "update-children" }); + System.Diagnostics.Process.Start( RestApi + @"/streams/" + StreamId ); + } ); - System.Windows.MessageBox.Show("Stream version saved. CloneId: " + cloneResult.Clone.StreamId); - }); + GH_DocumentObject.Menu_AppendItem( menu, "(API) View objects data online.", ( sender, e ) => + { + if ( StreamId == null ) + { + return; + } + + System.Diagnostics.Process.Start( RestApi + @"/streams/" + StreamId + @"/objects?omit=displayValue,base64" ); + } ); + + GH_DocumentObject.Menu_AppendSeparator( menu ); + GH_DocumentObject.Menu_AppendItem( menu, "Save current stream as a version.", ( sender, e ) => + { + var cloneResult = Client.StreamCloneAsync( StreamId ).Result; + Client.Stream.Children.Add( cloneResult.Clone.StreamId ); - if (Client.Stream == null) + Client.BroadcastMessage( "stream", Client.StreamId, new { eventType = "update-children" } ); + + System.Windows.MessageBox.Show( "Stream version saved. CloneId: " + cloneResult.Clone.StreamId ); + } ); + + if ( Client.Stream == null ) { return; } - GH_DocumentObject.Menu_AppendSeparator(menu); - GH_DocumentObject.Menu_AppendItem(menu, "Enable remote control of definition", (sender, e) => + GH_DocumentObject.Menu_AppendSeparator( menu ); + GH_DocumentObject.Menu_AppendItem( menu, "Enable remote control of definition", ( sender, e ) => + { + EnableRemoteControl = !EnableRemoteControl; + if ( EnableRemoteControl ) + { + List speckleInputs = null; + List speckleOutputs = null; + GetSpeckleParams( ref speckleInputs, ref speckleOutputs ); + + DefaultSpeckleInputs = speckleInputs; + DefaultSpeckleOutputs = speckleOutputs; + } + }, true, EnableRemoteControl ); + + if ( EnableRemoteControl ) { - EnableRemoteControl = !EnableRemoteControl; - if (EnableRemoteControl) + GH_DocumentObject.Menu_AppendItem( menu, "Update/Set the default state for the controller stream.", ( sender, e ) => { - List speckleInputs = null; - List speckleOutputs = null; - GetSpeckleParams(ref speckleInputs, ref speckleOutputs); - - DefaultSpeckleInputs = speckleInputs; - DefaultSpeckleOutputs = speckleOutputs; - } - }, true, EnableRemoteControl); - - if (EnableRemoteControl) - { - GH_DocumentObject.Menu_AppendItem(menu, "Update/Set the default state for the controller stream.", (sender, e) => - { - SetDefaultState(true); - System.Windows.MessageBox.Show("Updated default state."); - }, true); + SetDefaultState( true ); + System.Windows.MessageBox.Show( "Updated default state." ); + }, true ); } - GH_DocumentObject.Menu_AppendSeparator(menu); + GH_DocumentObject.Menu_AppendSeparator( menu ); - if (Client.Stream.Parent == null) + if ( Client.Stream.Parent == null ) { - GH_DocumentObject.Menu_AppendItem(menu: menu, text: "This is a parent stream.", enabled: false, click: null); + GH_DocumentObject.Menu_AppendItem( menu: menu, text: "This is a parent stream.", enabled: false, click: null ); } else { - GH_DocumentObject.Menu_AppendItem(menu: menu, text: "Parent: " + Client.Stream.Parent, click: (sender, e) => - { - System.Windows.Clipboard.SetText(Client.Stream.Parent); - System.Windows.MessageBox.Show("Parent id copied to clipboard. Share away!"); - }); + GH_DocumentObject.Menu_AppendItem( menu: menu, text: "Parent: " + Client.Stream.Parent, click: ( sender, e ) => + { + System.Windows.Clipboard.SetText( Client.Stream.Parent ); + System.Windows.MessageBox.Show( "Parent id copied to clipboard. Share away!" ); + } ); } - GH_DocumentObject.Menu_AppendSeparator(menu); + GH_DocumentObject.Menu_AppendSeparator( menu ); - GH_DocumentObject.Menu_AppendSeparator(menu); - GH_DocumentObject.Menu_AppendItem(menu, "Children:"); - GH_DocumentObject.Menu_AppendSeparator(menu); + GH_DocumentObject.Menu_AppendSeparator( menu ); + GH_DocumentObject.Menu_AppendItem( menu, "Children:" ); + GH_DocumentObject.Menu_AppendSeparator( menu ); - foreach (string childId in Client.Stream.Children) + foreach ( string childId in Client.Stream.Children ) { - GH_DocumentObject.Menu_AppendItem(menu, "Child " + childId, (sender, e) => - { - System.Windows.Clipboard.SetText(childId); - System.Windows.MessageBox.Show("Child id copied to clipboard. Share away!"); - }); + GH_DocumentObject.Menu_AppendItem( menu, "Child " + childId, ( sender, e ) => + { + System.Windows.Clipboard.SetText( childId ); + System.Windows.MessageBox.Show( "Child id copied to clipboard. Share away!" ); + } ); } } - protected override void RegisterInputParams(GH_Component.GH_InputParamManager pManager) + protected override void RegisterInputParams( GH_Component.GH_InputParamManager pManager ) { - pManager.AddGenericParameter("A", "A", "A is for Apple", GH_ParamAccess.tree); - pManager[0].Optional = true; - pManager.AddGenericParameter("B", "B", "B is for Book", GH_ParamAccess.tree); - pManager[1].Optional = true; - pManager.AddGenericParameter("C", "C", "C is for Car", GH_ParamAccess.tree); - pManager[2].Optional = true; + pManager.AddGenericParameter( "A", "A", "A is for Apple", GH_ParamAccess.tree ); + pManager[ 0 ].Optional = true; + pManager.AddGenericParameter( "B", "B", "B is for Book", GH_ParamAccess.tree ); + pManager[ 1 ].Optional = true; + pManager.AddGenericParameter( "C", "C", "C is for Car", GH_ParamAccess.tree ); + pManager[ 2 ].Optional = true; } - protected override void RegisterOutputParams(GH_Component.GH_OutputParamManager pManager) + protected override void RegisterOutputParams( GH_Component.GH_OutputParamManager pManager ) { - pManager.AddTextParameter("log", "L", "Log data.", GH_ParamAccess.item); - pManager.AddTextParameter("stream id", "ID", "The stream's id.", GH_ParamAccess.item); + pManager.AddTextParameter( "log", "L", "Log data.", GH_ParamAccess.item ); + pManager.AddTextParameter( "stream id", "ID", "The stream's id.", GH_ParamAccess.item ); } - protected override void SolveInstance(IGH_DataAccess DA) + protected override void SolveInstance( IGH_DataAccess DA ) { - if (Client == null) + if ( Client == null ) { return; } - if (EnableRemoteControl) + if ( EnableRemoteControl ) { Message = "JobQueue: " + JobQueue.Count; } StreamId = Client.StreamId; - DA.SetData(0, Log); - DA.SetData(1, Client.StreamId); + DA.SetData( 0, Log ); + DA.SetData( 1, Client.StreamId ); - if (!Client.IsConnected) + if ( !Client.IsConnected ) { return; } - if (WasSerialised && FirstSendUpdate) + if ( WasSerialised && FirstSendUpdate ) { FirstSendUpdate = false; return; @@ -527,15 +536,15 @@ protected override void SolveInstance(IGH_DataAccess DA) State = "Expired"; // All flags are good to start an update - if (!EnableRemoteControl && !ManualMode) + if ( !EnableRemoteControl && !ManualMode ) { UpdateData(); return; } // - else if (!EnableRemoteControl && ManualMode) + else if ( !EnableRemoteControl && ManualMode ) { - AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "State is expired, update push is required."); + AddRuntimeMessage( GH_RuntimeMessageLevel.Warning, "State is expired, update push is required." ); return; } @@ -543,42 +552,42 @@ protected override void SolveInstance(IGH_DataAccess DA) // Code below deals with the remote control functionality. // Proceed at your own risk. - if (JobQueue.Count == 0) + if ( JobQueue.Count == 0 ) { SetDefaultState(); - AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Updated default state for remote control."); + AddRuntimeMessage( GH_RuntimeMessageLevel.Remark, "Updated default state for remote control." ); return; } // prepare solution and exit - if (!SolutionPrepared && JobQueue.Count != 0) + if ( !SolutionPrepared && JobQueue.Count != 0 ) { - System.Collections.DictionaryEntry t = JobQueue.Cast().ElementAt(0); - Document.ScheduleSolution(1, PrepareSolution); + System.Collections.DictionaryEntry t = JobQueue.Cast().ElementAt( 0 ); + Document.ScheduleSolution( 1, PrepareSolution ); return; } // send out solution and exit - if (SolutionPrepared) + if ( SolutionPrepared ) { SolutionPrepared = false; var BucketObjects = GetData(); var BucketLayers = GetLayers(); - var convertedObjects = Converter.Serialise(BucketObjects).Select(obj => - { - if (ObjectCache.ContainsKey(obj.Hash)) - { - return new SpecklePlaceholder() { Hash = obj.Hash, _id = ObjectCache[obj.Hash]._id }; - } + var convertedObjects = Converter.Serialise( BucketObjects ).Select( obj => + { + if ( ObjectCache.ContainsKey( obj.Hash ) ) + { + return new SpecklePlaceholder() { Hash = obj.Hash, _id = ObjectCache[ obj.Hash ]._id }; + } - return obj; - }); + return obj; + } ); // theoretically this should go through the same flow as in DataSenderElapsed(), ie creating // buckets for staggered updates, etc. but we're lazy to untangle that logic for now - var responseClone = Client.StreamCloneAsync(StreamId).Result; + var responseClone = Client.StreamCloneAsync( StreamId ).Result; var responseStream = new SpeckleStream(); responseStream.IsComputedResult = true; @@ -588,23 +597,23 @@ protected override void SolveInstance(IGH_DataAccess DA) List speckleInputs = null; List speckleOutputs = null; - GetSpeckleParams(ref speckleInputs, ref speckleOutputs); + GetSpeckleParams( ref speckleInputs, ref speckleOutputs ); responseStream.GlobalMeasures = new { input = speckleInputs, output = speckleOutputs }; // go unblocking - var responseCloneUpdate = Client.StreamUpdateAsync(responseClone.Clone.StreamId, responseStream).ContinueWith(tres => - { - Client.SendMessage(CurrentJobClient, new { eventType = "compute-response", streamId = responseClone.Clone.StreamId }); - }); + var responseCloneUpdate = Client.StreamUpdateAsync( responseClone.Clone.StreamId, responseStream ).ContinueWith( tres => + { + Client.SendMessage( CurrentJobClient, new { eventType = "compute-response", streamId = responseClone.Clone.StreamId } ); + } ); - JobQueue.RemoveAt(0); + JobQueue.RemoveAt( 0 ); Message = "JobQueue: " + JobQueue.Count; - if (JobQueue.Count != 0) + if ( JobQueue.Count != 0 ) { - Rhino.RhinoApp.MainApplicationWindow.Invoke(ExpireComponentAction); + Rhino.RhinoApp.MainApplicationWindow.Invoke( ExpireComponentAction ); } } @@ -613,31 +622,31 @@ protected override void SolveInstance(IGH_DataAccess DA) #region Remote Control Helpers // Remote controller setting up the solution - private void PrepareSolution(GH_Document gH_Document) + private void PrepareSolution( GH_Document gH_Document ) { - System.Collections.DictionaryEntry t = JobQueue.Cast().ElementAt(0); - CurrentJobClient = (string)t.Key; + System.Collections.DictionaryEntry t = JobQueue.Cast().ElementAt( 0 ); + CurrentJobClient = ( string ) t.Key; - foreach (dynamic param in (IEnumerable)t.Value) + foreach ( dynamic param in ( IEnumerable ) t.Value ) { IGH_DocumentObject controller = null; try { - controller = Document.Objects.First(doc => doc.InstanceGuid.ToString() == param.guid); + controller = Document.Objects.First( doc => doc.InstanceGuid.ToString() == param.guid ); } catch { } - if (controller != null) + if ( controller != null ) { - switch ((string)param.inputType) + switch ( ( string ) param.inputType ) { case "TextPanel": GH_Panel panel = controller as GH_Panel; - panel.UserText = (string)param.value; - panel.ExpireSolution(false); + panel.UserText = ( string ) param.value; + panel.ExpireSolution( false ); break; case "Slider": GH_NumberSlider slider = controller as GH_NumberSlider; - slider.SetSliderValue(decimal.Parse(param.value.ToString())); + slider.SetSliderValue( decimal.Parse( param.value.ToString() ) ); break; case "Toggle": break; @@ -652,16 +661,16 @@ private void PrepareSolution(GH_Document gH_Document) /// /// Sets the default state for the remote controller. Will update parent stream too. /// - private void SetDefaultState(bool force = false) + private void SetDefaultState( bool force = false ) { List speckleInputs = null; List speckleOutputs = null; - GetSpeckleParams(ref speckleInputs, ref speckleOutputs); + GetSpeckleParams( ref speckleInputs, ref speckleOutputs ); DefaultSpeckleInputs = speckleInputs; DefaultSpeckleOutputs = speckleOutputs; - if (force) + if ( force ) { ForceUpdateData(); } @@ -671,10 +680,10 @@ private void SetDefaultState(bool force = false) } Dictionary message = new Dictionary(); - message["eventType"] = "default-state-update"; - message["controllers"] = DefaultSpeckleInputs; - message["outputs"] = DefaultSpeckleOutputs; - message["originalStreamId"] = Client.StreamId; + message[ "eventType" ] = "default-state-update"; + message[ "controllers" ] = DefaultSpeckleInputs; + message[ "outputs" ] = DefaultSpeckleOutputs; + message[ "originalStreamId" ] = Client.StreamId; Client.BroadcastMessage( "stream", Client.StreamId, message ); } @@ -683,9 +692,9 @@ private void SetDefaultState(bool force = false) /// /// Will start timer (500ms). /// - public void UpdateData() + public void UpdateData( ) { - if (DocumentIsClosing) + if ( DocumentIsClosing ) { return; } @@ -700,7 +709,7 @@ public void UpdateData() /// /// Bypasses debounce timer. /// - public void ForceUpdateData() + public void ForceUpdateData( ) { BucketName = NickName; BucketLayers = GetLayers(); @@ -709,9 +718,9 @@ public void ForceUpdateData() SendUpdate(); } - private void DataSender_Elapsed(object sender, ElapsedEventArgs e) + private void DataSender_Elapsed( object sender, ElapsedEventArgs e ) { - if (!ManualMode) + if ( !ManualMode ) { SendUpdate(); } @@ -720,33 +729,33 @@ private void DataSender_Elapsed(object sender, ElapsedEventArgs e) /// /// Sends the update to the server. /// - private void SendUpdate() + private void SendUpdate( ) { - if (MetadataSender.Enabled) + if ( MetadataSender.Enabled ) { // start the timer again, as we need to make sure we're updating DataSender.Start(); return; } - if (IsSendingUpdate) + if ( IsSendingUpdate ) { return; } IsSendingUpdate = true; - Message = String.Format("Converting {0} \n objects", BucketObjects.Count); + Message = String.Format( "Converting {0} \n objects", BucketObjects.Count ); - var convertedObjects = Converter.Serialise(BucketObjects).ToList(); + var convertedObjects = Converter.Serialise( BucketObjects ).ToList(); - Message = String.Format("Creating payloads"); + Message = String.Format( "Creating payloads" ); - LocalContext.PruneExistingObjects(convertedObjects, Client.BaseUrl); + LocalContext.PruneExistingObjects( convertedObjects, Client.BaseUrl ); List persistedObjects = new List(); - if (convertedObjects.Count(obj => obj.Type == "Placeholder") != convertedObjects.Count) + if ( convertedObjects.Count( obj => obj.Type == "Placeholder" ) != convertedObjects.Count ) { // create the update payloads int count = 0; @@ -755,81 +764,81 @@ private void SendUpdate() long currentBucketSize = 0; var currentBucketObjects = new List(); var allObjects = new List(); - foreach (SpeckleObject convertedObject in convertedObjects) + foreach ( SpeckleObject convertedObject in convertedObjects ) { - if (count++ % 100 == 0) + if ( count++ % 100 == 0 ) { Message = "Converted " + count + " objects out of " + convertedObjects.Count() + "."; } // size checking & bulk object creation payloads creation - long size = Converter.getBytes(convertedObject).Length; + long size = Converter.getBytes( convertedObject ).Length; currentBucketSize += size; totalBucketSize += size; - currentBucketObjects.Add(convertedObject); + currentBucketObjects.Add( convertedObject ); // Object is too big? - if (size > 2e6) + if ( size > 2e6 ) { - AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "This stream contains a super big object. These will fail. Sorry for the bad error message - we're working on improving this."); + AddRuntimeMessage( GH_RuntimeMessageLevel.Warning, "This stream contains a super big object. These will fail. Sorry for the bad error message - we're working on improving this." ); - currentBucketObjects.Remove(convertedObject); + currentBucketObjects.Remove( convertedObject ); } - if (currentBucketSize > 5e5) // restrict max to ~500kb; should it be user config? anyway these functions should go into core. at one point. + if ( currentBucketSize > 5e5 ) // restrict max to ~500kb; should it be user config? anyway these functions should go into core. at one point. { - Debug.WriteLine("Reached payload limit. Making a new one, current #: " + objectUpdatePayloads.Count); - objectUpdatePayloads.Add(currentBucketObjects); + Debug.WriteLine( "Reached payload limit. Making a new one, current #: " + objectUpdatePayloads.Count ); + objectUpdatePayloads.Add( currentBucketObjects ); currentBucketObjects = new List(); currentBucketSize = 0; } } // add in the last bucket - if (currentBucketObjects.Count > 0) + if ( currentBucketObjects.Count > 0 ) { - objectUpdatePayloads.Add(currentBucketObjects); + objectUpdatePayloads.Add( currentBucketObjects ); } - Debug.WriteLine("Finished, payload object update count is: " + objectUpdatePayloads.Count + " total bucket size is (kb) " + totalBucketSize / 1000); + Debug.WriteLine( "Finished, payload object update count is: " + objectUpdatePayloads.Count + " total bucket size is (kb) " + totalBucketSize / 1000 ); // create bulk object creation tasks int k = 0; List responses = new List(); - foreach (var payload in objectUpdatePayloads) + foreach ( var payload in objectUpdatePayloads ) { - Message = String.Format("{0}/{1}", k++, objectUpdatePayloads.Count); + Message = String.Format( "{0}/{1}", k++, objectUpdatePayloads.Count ); try { - var objResponse = Client.ObjectCreateAsync(payload).Result; - responses.Add(objResponse); - persistedObjects.AddRange(objResponse.Resources); + var objResponse = Client.ObjectCreateAsync( payload ).Result; + responses.Add( objResponse ); + persistedObjects.AddRange( objResponse.Resources ); int m = 0; - foreach (var oL in payload) + foreach ( var oL in payload ) { - oL._id = objResponse.Resources[m++]._id; + oL._id = objResponse.Resources[ m++ ]._id; } // push sent objects in the cache non-blocking - Task.Run(() => - { - foreach (var oL in payload) - { - if (oL.Type != "Placeholder" ) - { - LocalContext.AddSentObject(oL, Client.BaseUrl); - } - } - }); + Task.Run( ( ) => + { + foreach ( var oL in payload ) + { + if ( oL.Type != "Placeholder" ) + { + LocalContext.AddSentObject( oL, Client.BaseUrl ); + } + } + } ); } - catch (Exception err) + catch ( Exception err ) { - AddRuntimeMessage(GH_RuntimeMessageLevel.Error, err.Message); + AddRuntimeMessage( GH_RuntimeMessageLevel.Error, err.Message ); return; } } @@ -843,9 +852,9 @@ private void SendUpdate() List placeholders = new List(); //foreach ( var myResponse in responses ) - foreach (var obj in persistedObjects) + foreach ( var obj in persistedObjects ) { - placeholders.Add(new SpecklePlaceholder() { _id = obj._id }); + placeholders.Add( new SpecklePlaceholder() { _id = obj._id } ); } SpeckleStream updateStream = new SpeckleStream() @@ -857,26 +866,26 @@ private void SendUpdate() // set some base properties (will be overwritten) var baseProps = new Dictionary(); - baseProps["units"] = Rhino.RhinoDoc.ActiveDoc.ModelUnitSystem.ToString(); - baseProps["tolerance"] = Rhino.RhinoDoc.ActiveDoc.ModelAbsoluteTolerance; - baseProps["angleTolerance"] = Rhino.RhinoDoc.ActiveDoc.ModelAngleToleranceRadians; + baseProps[ "units" ] = Rhino.RhinoDoc.ActiveDoc.ModelUnitSystem.ToString(); + baseProps[ "tolerance" ] = Rhino.RhinoDoc.ActiveDoc.ModelAbsoluteTolerance; + baseProps[ "angleTolerance" ] = Rhino.RhinoDoc.ActiveDoc.ModelAngleToleranceRadians; updateStream.BaseProperties = baseProps; - var response = Client.StreamUpdateAsync(Client.StreamId, updateStream).Result; + var response = Client.StreamUpdateAsync( Client.StreamId, updateStream ).Result; - Client.BroadcastMessage( "stream", Client.StreamId, new { eventType = "update-global" }); + Client.BroadcastMessage( "stream", Client.StreamId, new { eventType = "update-global" } ); Log += response.Message; - AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Data sent at " + DateTime.Now); - Message = "Data sent\n@" + DateTime.Now.ToString("hh:mm:ss"); + AddRuntimeMessage( GH_RuntimeMessageLevel.Remark, "Data sent at " + DateTime.Now ); + Message = "Data sent\n@" + DateTime.Now.ToString( "hh:mm:ss" ); IsSendingUpdate = false; State = "Ok"; } - public void UpdateMetadata() + public void UpdateMetadata( ) { - if (DocumentIsClosing) + if ( DocumentIsClosing ) { return; } @@ -887,101 +896,101 @@ public void UpdateMetadata() MetadataSender.Start(); } - private void MetadataSender_Elapsed(object sender, ElapsedEventArgs e) + private void MetadataSender_Elapsed( object sender, ElapsedEventArgs e ) { - if (ManualMode) + if ( ManualMode ) { return; } // we do not need to enque another metadata sending event as the data update superseeds the metadata one. - if (DataSender.Enabled) { return; }; + if ( DataSender.Enabled ) { return; }; SpeckleStream updateStream = new SpeckleStream() { Name = BucketName, Layers = BucketLayers }; - var updateResult = Client.StreamUpdateAsync(Client.StreamId, updateStream).Result; + var updateResult = Client.StreamUpdateAsync( Client.StreamId, updateStream ).Result; Log += updateResult.Message; - Client.BroadcastMessage("stream", Client.StreamId, new { eventType = "update-meta" }); + Client.BroadcastMessage( "stream", Client.StreamId, new { eventType = "update-meta" } ); } - public void ManualUpdate() + public void ManualUpdate( ) { - new Task(() => - { - var cloneResult = Client.StreamCloneAsync(StreamId).Result; - Client.Stream.Children.Add(cloneResult.Clone.StreamId); + new Task( ( ) => + { + var cloneResult = Client.StreamCloneAsync( StreamId ).Result; + Client.Stream.Children.Add( cloneResult.Clone.StreamId ); - Client.BroadcastMessage( "stream", Client.StreamId, new { eventType = "update-children" }); + Client.BroadcastMessage( "stream", Client.StreamId, new { eventType = "update-children" } ); - ForceUpdateData(); + ForceUpdateData(); - }).Start(); + } ).Start(); } - public List GetData() + public List GetData( ) { List data = new List(); - foreach (IGH_Param myParam in Params.Input) + foreach ( IGH_Param myParam in Params.Input ) { - foreach (object o in myParam.VolatileData.AllData(false)) + foreach ( object o in myParam.VolatileData.AllData( false ) ) { - data.Add(o); + data.Add( o ); } } - data = data.Select(obj => - { - try - { - return obj.GetType().GetProperty("Value").GetValue(obj); - } - catch - { - return null; - } - }).ToList(); + data = data.Select( obj => + { + try + { + return obj.GetType().GetProperty( "Value" ).GetValue( obj ); + } + catch + { + return null; + } + } ).ToList(); return data; } - public List GetLayers() + public List GetLayers( ) { List layers = new List(); int startIndex = 0; int count = 0; - foreach (IGH_Param myParam in Params.Input) + foreach ( IGH_Param myParam in Params.Input ) { Layer myLayer = new Layer( myParam.NickName, myParam.InstanceGuid.ToString(), - GetParamTopology(myParam), + GetParamTopology( myParam ), myParam.VolatileDataCount, startIndex, - count); + count ); - layers.Add(myLayer); + layers.Add( myLayer ); startIndex += myParam.VolatileDataCount; count++; } return layers; } - public string GetParamTopology(IGH_Param param) + public string GetParamTopology( IGH_Param param ) { string topology = ""; - foreach (Grasshopper.Kernel.Data.GH_Path mypath in param.VolatileData.Paths) + foreach ( Grasshopper.Kernel.Data.GH_Path mypath in param.VolatileData.Paths ) { - topology += mypath.ToString(false) + "-" + param.VolatileData.get_Branch(mypath).Count + " "; + topology += mypath.ToString( false ) + "-" + param.VolatileData.get_Branch( mypath ).Count + " "; } return topology; } - bool IGH_VariableParameterComponent.CanInsertParameter(GH_ParameterSide side, int index) + bool IGH_VariableParameterComponent.CanInsertParameter( GH_ParameterSide side, int index ) { - if (side == GH_ParameterSide.Input) + if ( side == GH_ParameterSide.Input ) { return true; } @@ -991,10 +1000,10 @@ bool IGH_VariableParameterComponent.CanInsertParameter(GH_ParameterSide side, in } } - bool IGH_VariableParameterComponent.CanRemoveParameter(GH_ParameterSide side, int index) + bool IGH_VariableParameterComponent.CanRemoveParameter( GH_ParameterSide side, int index ) { //We can only remove from the input - if (side == GH_ParameterSide.Input && Params.Input.Count > 1) + if ( side == GH_ParameterSide.Input && Params.Input.Count > 1 ) { return true; } @@ -1004,40 +1013,40 @@ bool IGH_VariableParameterComponent.CanRemoveParameter(GH_ParameterSide side, in } } - IGH_Param IGH_VariableParameterComponent.CreateParameter(GH_ParameterSide side, int index) + IGH_Param IGH_VariableParameterComponent.CreateParameter( GH_ParameterSide side, int index ) { Param_GenericObject param = new Param_GenericObject() { - Name = GH_ComponentParamServer.InventUniqueNickname("ABCDEFGHIJKLMNOPQRSTUVWXYZ", Params.Input) + Name = GH_ComponentParamServer.InventUniqueNickname( "ABCDEFGHIJKLMNOPQRSTUVWXYZ", Params.Input ) }; param.NickName = param.Name; param.Description = "Things to be sent around."; param.Optional = true; param.Access = GH_ParamAccess.tree; - param.AttributesChanged += (sender, e) => Debug.WriteLine("Attributes have changed! (of param)"); - param.ObjectChanged += (sender, e) => UpdateMetadata(); + param.AttributesChanged += ( sender, e ) => Debug.WriteLine( "Attributes have changed! (of param)" ); + param.ObjectChanged += ( sender, e ) => UpdateMetadata(); UpdateMetadata(); return param; } - bool IGH_VariableParameterComponent.DestroyParameter(GH_ParameterSide side, int index) + bool IGH_VariableParameterComponent.DestroyParameter( GH_ParameterSide side, int index ) { UpdateMetadata(); return true; } - void IGH_VariableParameterComponent.VariableParameterMaintenance() + void IGH_VariableParameterComponent.VariableParameterMaintenance( ) { } - public string GetTopology(IGH_Param param) + public string GetTopology( IGH_Param param ) { string topology = ""; - foreach (Grasshopper.Kernel.Data.GH_Path mypath in param.VolatileData.Paths) + foreach ( Grasshopper.Kernel.Data.GH_Path mypath in param.VolatileData.Paths ) { - topology += mypath.ToString(false) + "-" + param.VolatileData.get_Branch(mypath).Count + " "; + topology += mypath.ToString( false ) + "-" + param.VolatileData.get_Branch( mypath ).Count + " "; } return topology; } @@ -1052,7 +1061,7 @@ protected override System.Drawing.Bitmap Icon public override Guid ComponentGuid { - get { return new Guid("{e66e6873-ddcd-4089-93ff-75ae09f8ada3}"); } + get { return new Guid( "{e66e6873-ddcd-4089-93ff-75ae09f8ada3}" ); } } } @@ -1064,65 +1073,65 @@ public class GhSenderClientAttributes : Grasshopper.Kernel.Attributes.GH_Compone private Rectangle StreamNameBounds; private Rectangle PushStreamButtonRectangle; - public GhSenderClientAttributes(GhSenderClient component) : base(component) + public GhSenderClientAttributes( GhSenderClient component ) : base( component ) { Base = component; } - protected override void Layout() + protected override void Layout( ) { base.Layout(); - BaseRectangle = GH_Convert.ToRectangle(Bounds); - StreamIdBounds = new Rectangle((int)(BaseRectangle.X + (BaseRectangle.Width - 120) * 0.5), BaseRectangle.Y - 25, 120, 20); - StreamNameBounds = new Rectangle(StreamIdBounds.X, BaseRectangle.Y - 50, 120, 20); + BaseRectangle = GH_Convert.ToRectangle( Bounds ); + StreamIdBounds = new Rectangle( ( int ) ( BaseRectangle.X + ( BaseRectangle.Width - 120 ) * 0.5 ), BaseRectangle.Y - 25, 120, 20 ); + StreamNameBounds = new Rectangle( StreamIdBounds.X, BaseRectangle.Y - 50, 120, 20 ); - PushStreamButtonRectangle = new Rectangle((int)(BaseRectangle.X + (BaseRectangle.Width - 30) * 0.5), BaseRectangle.Y + BaseRectangle.Height, 30, 30); + PushStreamButtonRectangle = new Rectangle( ( int ) ( BaseRectangle.X + ( BaseRectangle.Width - 30 ) * 0.5 ), BaseRectangle.Y + BaseRectangle.Height, 30, 30 ); - if (Base.ManualMode) + if ( Base.ManualMode ) { - Rectangle newBaseRectangle = new Rectangle(BaseRectangle.X, BaseRectangle.Y, BaseRectangle.Width, BaseRectangle.Height + 33); + Rectangle newBaseRectangle = new Rectangle( BaseRectangle.X, BaseRectangle.Y, BaseRectangle.Width, BaseRectangle.Height + 33 ); Bounds = newBaseRectangle; } } - protected override void Render(GH_Canvas canvas, Graphics graphics, GH_CanvasChannel channel) + protected override void Render( GH_Canvas canvas, Graphics graphics, GH_CanvasChannel channel ) { - base.Render(canvas, graphics, channel); + base.Render( canvas, graphics, channel ); - if (channel == GH_CanvasChannel.Objects) + if ( channel == GH_CanvasChannel.Objects ) { - GH_PaletteStyle myStyle = new GH_PaletteStyle(System.Drawing.ColorTranslator.FromHtml(Base.EnableRemoteControl ? "#147DE9" : "#B3B3B3"), System.Drawing.ColorTranslator.FromHtml("#FFFFFF"), System.Drawing.ColorTranslator.FromHtml(Base.EnableRemoteControl ? "#ffffff" : "#4C4C4C")); + GH_PaletteStyle myStyle = new GH_PaletteStyle( System.Drawing.ColorTranslator.FromHtml( Base.EnableRemoteControl ? "#147DE9" : "#B3B3B3" ), System.Drawing.ColorTranslator.FromHtml( "#FFFFFF" ), System.Drawing.ColorTranslator.FromHtml( Base.EnableRemoteControl ? "#ffffff" : "#4C4C4C" ) ); - GH_PaletteStyle myTransparentStyle = new GH_PaletteStyle(System.Drawing.Color.FromArgb(0, 0, 0, 0)); + GH_PaletteStyle myTransparentStyle = new GH_PaletteStyle( System.Drawing.Color.FromArgb( 0, 0, 0, 0 ) ); - var streamIdCapsule = GH_Capsule.CreateTextCapsule(box: StreamIdBounds, textbox: StreamIdBounds, palette: Base.EnableRemoteControl ? GH_Palette.Black : GH_Palette.Transparent, text: Base.EnableRemoteControl ? "Remote Controller" : "ID: " + (Base.Client != null ? Base.Client.StreamId : "error"), highlight: 0, radius: 5); - streamIdCapsule.Render(graphics, myStyle); + var streamIdCapsule = GH_Capsule.CreateTextCapsule( box: StreamIdBounds, textbox: StreamIdBounds, palette: Base.EnableRemoteControl ? GH_Palette.Black : GH_Palette.Transparent, text: Base.EnableRemoteControl ? "Remote Controller" : "ID: " + ( Base.Client != null ? Base.Client.StreamId : "error" ), highlight: 0, radius: 5 ); + streamIdCapsule.Render( graphics, myStyle ); streamIdCapsule.Dispose(); - var streamNameCapsule = GH_Capsule.CreateTextCapsule(box: StreamNameBounds, textbox: StreamNameBounds, palette: GH_Palette.Black, text: "(S) " + Base.NickName, highlight: 0, radius: 5); - streamNameCapsule.Render(graphics, myStyle); + var streamNameCapsule = GH_Capsule.CreateTextCapsule( box: StreamNameBounds, textbox: StreamNameBounds, palette: GH_Palette.Black, text: "(S) " + Base.NickName, highlight: 0, radius: 5 ); + streamNameCapsule.Render( graphics, myStyle ); streamNameCapsule.Dispose(); - if (Base.ManualMode) + if ( Base.ManualMode ) { - var pushStreamButton = GH_Capsule.CreateCapsule(PushStreamButtonRectangle, GH_Palette.Pink, 2, 0); - pushStreamButton.Render(graphics, true ? Properties.Resources.play25px : Properties.Resources.pause25px, myTransparentStyle); + var pushStreamButton = GH_Capsule.CreateCapsule( PushStreamButtonRectangle, GH_Palette.Pink, 2, 0 ); + pushStreamButton.Render( graphics, true ? Properties.Resources.play25px : Properties.Resources.pause25px, myTransparentStyle ); } } } - public override GH_ObjectResponse RespondToMouseDown(GH_Canvas sender, GH_CanvasMouseEvent e) + public override GH_ObjectResponse RespondToMouseDown( GH_Canvas sender, GH_CanvasMouseEvent e ) { - if (e.Button == System.Windows.Forms.MouseButtons.Left) + if ( e.Button == System.Windows.Forms.MouseButtons.Left ) { - if (((RectangleF)PushStreamButtonRectangle).Contains(e.CanvasLocation)) + if ( ( ( RectangleF ) PushStreamButtonRectangle ).Contains( e.CanvasLocation ) ) { Base.ManualUpdate(); //Base.ExpireSolution( true ); return GH_ObjectResponse.Handled; } } - return base.RespondToMouseDown(sender, e); + return base.RespondToMouseDown( sender, e ); } } diff --git a/SpeckleGrasshopper/Loader.cs b/SpeckleGrasshopper/Loader.cs new file mode 100644 index 0000000..9b0d9ed --- /dev/null +++ b/SpeckleGrasshopper/Loader.cs @@ -0,0 +1,73 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Timers; +using System.Windows.Forms; +using System.Windows.Interop; +using Grasshopper.Kernel; + +namespace SpeckleGrasshopper +{ + public class Loader : GH_AssemblyPriority + { + System.Timers.Timer loadTimer; + + public Loader( ) { } + + public override GH_LoadingInstruction PriorityLoad( ) + { + loadTimer = new System.Timers.Timer( 500 ); + loadTimer.Start(); + loadTimer.Elapsed += AddSpeckleMenu; + return GH_LoadingInstruction.Proceed; + } + + private void AddSpeckleMenu( object sender, ElapsedEventArgs e ) + { + if ( Grasshopper.Instances.DocumentEditor == null ) return; + + var speckleMenu = new ToolStripMenuItem( "Speckle" ); + speckleMenu.DropDown.Items.Add( "Speckle Account Manager", null, ( s, a ) => + { + var signInWindow = new SpecklePopup.SignInWindow( false ); + var helper = new System.Windows.Interop.WindowInteropHelper( signInWindow ); + helper.Owner = Rhino.RhinoApp.MainWindowHandle(); + signInWindow.Show(); + } ); + + speckleMenu.DropDown.Items.Add( new ToolStripSeparator() ); + + speckleMenu.DropDown.Items.Add( "Speckle Home", null, ( s, a ) => + { + Process.Start( @"https://speckle.works" ); + } ); + + speckleMenu.DropDown.Items.Add( "Speckle Documentation", null, ( s, a ) => + { + Process.Start( @"https://speckle.works/docs/start" ); + } ); + + speckleMenu.DropDown.Items.Add( "Speckle Forum", null, ( s, a ) => + { + Process.Start( @"https://discourse.speckle.works" ); + } ); + + try + { + var mainMenu = Grasshopper.Instances.DocumentEditor.MainMenuStrip; + Grasshopper.Instances.DocumentEditor.Invoke( new Action( ( ) => + { + mainMenu.Items.Insert( mainMenu.Items.Count - 2, speckleMenu ); + } ) ); + loadTimer.Stop(); + } + catch ( Exception err ) + { + Debug.WriteLine( err.Message ); + } + } + } +} diff --git a/SpeckleGrasshopper/SpeckleGrasshopper.csproj b/SpeckleGrasshopper/SpeckleGrasshopper.csproj index 8ba86db..301d057 100644 --- a/SpeckleGrasshopper/SpeckleGrasshopper.csproj +++ b/SpeckleGrasshopper/SpeckleGrasshopper.csproj @@ -71,6 +71,7 @@ + @@ -137,10 +138,10 @@ 6.1.18037.13441 - 1.6.0.333-wip + 1.5.2.343 - 1.6.1.30-wip + 1.6.2.34-wip 1.5.231 diff --git a/SpeckleRhinoPlugin/SpeckleWinR6/SpeckleWinR6.csproj b/SpeckleRhinoPlugin/SpeckleWinR6/SpeckleWinR6.csproj index d2b0fbf..612fd10 100644 --- a/SpeckleRhinoPlugin/SpeckleWinR6/SpeckleWinR6.csproj +++ b/SpeckleRhinoPlugin/SpeckleWinR6/SpeckleWinR6.csproj @@ -59,10 +59,8 @@ x64 - - ..\..\SpeckleCore\SpeckleNewtonsoft.dll - SpeckleNewtonsoft - + + @@ -70,6 +68,7 @@ + @@ -128,7 +127,10 @@ 6.1.18037.13441 - 1.6.0.333-wip + 1.5.2.343 + + + 1.6.8 1.5.231 diff --git a/SpeckleRhinoPlugin/src/Interop.cs b/SpeckleRhinoPlugin/src/Interop.cs index 2d94333..4963a82 100644 --- a/SpeckleRhinoPlugin/src/Interop.cs +++ b/SpeckleRhinoPlugin/src/Interop.cs @@ -17,8 +17,10 @@ using Rhino; using System.Dynamic; using Rhino.DocObjects; +using System.Windows; using System.Windows.Forms; using Newtonsoft.Json; +using SpecklePopup; namespace SpeckleRhino { @@ -253,10 +255,25 @@ public void InstantiateFileClients( ) #region Account Management + public void ShowAccountPopup( ) + { + RhinoApp.InvokeOnUiThread( new Action( ( ) => + //Window.Dispatcher.Invoke( ( ) => + { + var signInWindow = new SpecklePopup.SignInWindow( true ); + + var helper = new System.Windows.Interop.WindowInteropHelper( signInWindow ); + helper.Owner = RhinoApp.MainWindowHandle(); + + signInWindow.ShowDialog(); + NotifySpeckleFrame( "refresh-accounts", "", "" ); + } ) ); + } + // called by the web ui public string GetUserAccounts( ) { - return JsonConvert.SerializeObject( UserAccounts, Interop.camelCaseSettings ); + return JsonConvert.SerializeObject( SpeckleCore.LocalContext.GetAllAccounts(), Interop.camelCaseSettings ); } private void ReadUserAccounts( ) @@ -324,15 +341,15 @@ public string GetAllClients( ) if ( client is RhinoSender ) { var rhSender = client as RhinoSender; - NotifySpeckleFrame( "client-add", rhSender.StreamId, JsonConvert.SerializeObject( new { stream = rhSender.Client.Stream, client = rhSender.Client }, camelCaseSettings ) ); + NotifySpeckleFrame( "client-add", rhSender.StreamId, JsonConvert.SerializeObject( new { stream = rhSender.Client.Stream, client = rhSender.Client }, camelCaseSettings ) ); continue; } var rhReceiver = client as RhinoReceiver; - NotifySpeckleFrame( "client-add", rhReceiver.StreamId, JsonConvert.SerializeObject( new { stream = rhReceiver.Client.Stream, client = rhReceiver.Client }, camelCaseSettings ) ); + NotifySpeckleFrame( "client-add", rhReceiver.StreamId, JsonConvert.SerializeObject( new { stream = rhReceiver.Client.Stream, client = rhReceiver.Client }, camelCaseSettings ) ); } - return JsonConvert.SerializeObject( UserClients, camelCaseSettings ); + return JsonConvert.SerializeObject( UserClients, camelCaseSettings ); } #endregion @@ -418,7 +435,7 @@ public void setObjectHover( string clientId, string layerId, bool status ) public void AddRemoveObjects( string clientId, string _guids, bool remove ) { - string[ ] guids = JsonConvert.DeserializeObject( _guids ); + string[ ] guids = JsonConvert.DeserializeObject( _guids ); var myClient = UserClients.FirstOrDefault( c => c.GetClientId() == clientId ); if ( myClient != null ) @@ -482,13 +499,13 @@ public string getLayersAndObjectsInfo( bool ignoreSelection = false ) { SelectedObjects = RhinoDoc.ActiveDoc.Objects.GetSelectedObjects( false, false ).ToList(); if ( SelectedObjects.Count == 0 || SelectedObjects[ 0 ] == null ) - return JsonConvert.SerializeObject( layerInfoList, camelCaseSettings ); + return JsonConvert.SerializeObject( layerInfoList, camelCaseSettings ); } else { SelectedObjects = RhinoDoc.ActiveDoc.Objects.ToList(); if ( SelectedObjects.Count == 0 || SelectedObjects[ 0 ] == null ) - return JsonConvert.SerializeObject( layerInfoList, camelCaseSettings ); + return JsonConvert.SerializeObject( layerInfoList, camelCaseSettings ); foreach ( Rhino.DocObjects.Layer ll in RhinoDoc.ActiveDoc.Layers ) { @@ -530,7 +547,7 @@ public string getLayersAndObjectsInfo( bool ignoreSelection = false ) } } - return Convert.ToBase64String( System.Text.Encoding.UTF8.GetBytes( JsonConvert.SerializeObject( layerInfoList, camelCaseSettings ) ) ); + return Convert.ToBase64String( System.Text.Encoding.UTF8.GetBytes( JsonConvert.SerializeObject( layerInfoList, camelCaseSettings ) ) ); } #endregion } diff --git a/SpeckleView b/SpeckleView index 4d2f90e..9704fdb 160000 --- a/SpeckleView +++ b/SpeckleView @@ -1 +1 @@ -Subproject commit 4d2f90eb541eb6e5177ee991ee9a4c04f2363ec7 +Subproject commit 9704fdbab3dc4d07664ea20fbd54cf15ff583c58 diff --git a/appveyor.yml b/appveyor.yml index 2262a32..18aed8d 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -12,8 +12,10 @@ init: { $releases = "https://api.github.com/repos/$env:APPVEYOR_REPO_NAME/releases" $tag = (Invoke-WebRequest $releases | ConvertFrom-Json)[0].tag_name - Update-AppveyorBuild -Version "$tag.$Env:APPVEYOR_BUILD_VERSION-wip" + $spl = $tag.Split("-")[0] + Update-AppveyorBuild -Version "$spl.$Env:APPVEYOR_BUILD_VERSION-wip" } + Write-Host "Hello. Build version is: $Env:APPVEYOR_BUILD_VERSION" # Environment Configuration image: Visual Studio 2017