protected override void AppendAdditionalComponentMenuItems(ToolStripDropDown menu) { Menu_AppendSeparator(menu); Menu_AppendItem(menu, "Select the converter you want to use:"); var kits = KitManager.GetKitsWithConvertersForApp(Applications.Rhino); foreach (var kit in kits) { Menu_AppendItem(menu, $"{kit.Name} ({kit.Description})", (s, e) => { SetConverterFromKit(kit.Name); }, true, kit.Name == Kit.Name); } Menu_AppendSeparator(menu); if (InputType == "Stream" || InputType == "Branch") { var autoReceiveMi = Menu_AppendItem(menu, "Receive automatically", (s, e) => { AutoReceive = !AutoReceive; RhinoApp.InvokeOnUiThread((Action) delegate { OnDisplayExpired(true); }); }, true, AutoReceive); autoReceiveMi.ToolTipText = "Toggle automatic receiving. If set, any upstream change will be pulled instantly. This only is applicable when receiving a stream or a branch."; } else { var autoReceiveMi = Menu_AppendItem(menu, "Automatic receiving is disabled because you have specified a direct commit."); autoReceiveMi.ToolTipText = "To enable automatic receiving, you need to input a stream rather than a specific commit."; } base.AppendAdditionalComponentMenuItems(menu); }
public void Run() { if (type == TaskType.Grasshopper) { RhinoApp.InvokeOnUiThread(new Action(() => { LoadGhDocument(); })); } }
internal void AddHistory(string name, TaskRecord record) { RhinoApp.InvokeOnUiThread(new Action(() => { TaskHistory historyGroup = GetHistoryByID(record.TaskID); if (historyGroup == null) { historyGroup = new TaskHistory(name, record.TaskID); } int index = historyGroup.TaskRows.Items.Count + 1; // record.date.ToString("[MM/dd HH:mm:ss]") TaskRow taskRow = new TaskRow(index, record); taskRow.RestoreEvent += task => RestoreEvent(task); taskRow.StoreEvent += TaskRow_StoreEvent; taskRow.DeleteEvent += TaskRow_DeleteEvent; historyGroup.AddRow(taskRow); if (historyGroup.TaskRows.Items.Count == 1) { StackLayout.Items.Add(new StackLayoutItem(historyGroup)); } })); }
/// <summary> /// 一次性设置多个历史记录,用于刚初始化Rhino的时候,把每个工作流的历史记录加载进来 /// </summary> /// <param name="name"></param> /// <param name="historyList"></param> /// <param name="id"></param> internal void SetHistory(string name, List <TaskRecord> historyList) { RhinoApp.InvokeOnUiThread(new Action(() => { historyList.ForEach(record => AddHistory(name, record)); })); }
/// <summary> /// Write the contents of the package to the Rhino document /// </summary> public void WriteToDocument() { // create delegate handler AddMaterial handler = AddMaterialHandler; // Invoke import on Rhinos main thread RhinoApp.InvokeOnUiThread(handler, new Object[] { _material }); }
public override void AppendAdditionalMenuItems(ToolStripDropDown menu) { base.AppendAdditionalMenuItems(menu); Menu_AppendSeparator(menu); if (InputType == "Stream" || InputType == "Branch") { var autoReceiveMi = Menu_AppendItem(menu, "Receive automatically", (s, e) => { AutoReceive = !AutoReceive; RhinoApp.InvokeOnUiThread((Action) delegate { OnDisplayExpired(true); }); }, true, AutoReceive); autoReceiveMi.ToolTipText = "Toggle automatic receiving. If set, any upstream change will be pulled instantly. This only is applicable when receiving a stream or a branch."; } else { var autoReceiveMi = Menu_AppendItem(menu, "Automatic receiving is disabled because you have specified a direct commit."); autoReceiveMi.ToolTipText = "To enable automatic receiving, you need to input a stream rather than a specific commit."; } var receivOnOpenMi = Menu_AppendItem( menu, "Receive when Document opened", (sender, args) => { ReceiveOnOpen = !ReceiveOnOpen; RhinoApp.InvokeOnUiThread((Action) delegate { OnDisplayExpired(true); }); }, !AutoReceive, AutoReceive || ReceiveOnOpen); receivOnOpenMi.ToolTipText = "The node will automatically perform a receive operation as soon as the document is open, or the node is copy/pasted into a new document."; Menu_AppendSeparator(menu); if (CurrentComponentState == "receiving") { Menu_AppendItem(menu, "Cancel Receive", (s, e) => { CurrentComponentState = "expired"; RequestCancellation(); }); } Menu_AppendSeparator(menu); if (StreamWrapper != null && !string.IsNullOrEmpty(ReceivedCommitId)) { Menu_AppendItem( menu, $"View commit {ReceivedCommitId} @ {StreamWrapper.ServerUrl} online ↗", (s, e) => System.Diagnostics.Process.Start($"{StreamWrapper.ServerUrl}/streams/{StreamWrapper.StreamId}/commits/{ReceivedCommitId}")); } }
public void Error(string msg) { RhinoApp.InvokeOnUiThread(new Action(() => Logs.Add(new Log { Ts = DateTime.Now.ToString("[MM/dd HH:mm:ss]"), Text = msg, LogLevel = LevelIcon(Colors.Red) }))); }
/// <summary> /// Write the contents of the package to the <see cref="Rhino.RhinoDoc"/> /// </summary> public void WriteToDocument() { // create delegate handler AddGeometry handler = AddGeometryHandler; // iterate over geometries foreach (var geometryInformation in _geometryInfos) { // Invoke import on Rhinos main thread RhinoApp.InvokeOnUiThread(handler, new Object[] { _material, geometryInformation }); } }
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", "", ""); })); }
private void HandleNewCommit() { Message = "Expired"; CurrentComponentState = "expired"; AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, $"There is a newer commit available for this {InputType}"); RhinoApp.InvokeOnUiThread((Action) delegate { if (AutoReceive) { ExpireSolution(true); } else { OnDisplayExpired(true); } }); }
public static void FtpUpload(string localFilePath, string url, string user, string password) { if (_uploadTask != null && !_uploadTask.IsCompleted) { RhinoApp.WriteLine("Please wait until the last upload has completed."); return; } StatusBar.ShowProgressMeter(0, 100, "Uploading to FTP server...", true, true); _uploadTask = Task.Run(() => { var fileName = Path.GetFileName(localFilePath); string webFilePath = $"{url}/{fileName}"; var request = (FtpWebRequest)WebRequest.Create(webFilePath); request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = new NetworkCredential(user, password); using (var inputStream = File.OpenRead(localFilePath)) using (var outputStream = request.GetRequestStream()) { var buffer = new byte[1024 * 1024]; int totalReadBytesCount = 0; int readBytesCount; while ((readBytesCount = inputStream.Read(buffer, 0, buffer.Length)) > 0) { outputStream.Write(buffer, 0, readBytesCount); totalReadBytesCount += readBytesCount; var progress = totalReadBytesCount * 100.0 / inputStream.Length; Action upload = () => StatusBar.UpdateProgressMeter((int)progress, true); Rhino.RhinoApp.InvokeOnUiThread(upload); } } RhinoApp.InvokeOnUiThread(new Action(() => StatusBar.HideProgressMeter())); using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) { Action text = () => Rhino.RhinoApp.WriteLine($"Web upload of file '{fileName}.html' complete, status: {response.StatusDescription}"); RhinoApp.InvokeOnUiThread(text); } }); }
public async void Exit() { RhinoApp.WriteLine("_(:_」∠)_ Could not connect to Noah Client, Rhino will exit in 3 second."); await Task.Delay(300); RhinoApp.InvokeOnUiThread(new Action(() => { DialogResult dialogResult = MessageBox.Show( RhinoEtoApp.MainWindow, "Noah Server 已断线并且重联5次都失败了,是否关闭Rhino", "重联失败", MessageBoxButtons.YesNo, MessageBoxType.Error); if (dialogResult == DialogResult.Yes) { RhinoApp.Exit(); } })); }
/// <summary> /// NodeInCode evaluation method, to run on separate thread /// </summary> /// <param name="prms">list of input trees</param> protected void GhostEval(object[] prms) { object locker = new object(); lock (locker) WorkerCount++; // actual work in this block if (prms.Length == 0 || trgtcomp == null) { complete = true && !interrupt; lock (locker) comptime = " 0ms"; } else if (running) { // shouldn't ever be here! complete = false; lock (locker) workerwarnings = new string[] { "Somehow a second ghost tried to start a task. It's been stopped.", }; return; //skip invoke recompute } else { Stopwatch ticker = new Stopwatch(); ticker.Start(); running = true; object[] results; // each should be a tree lock (locker) results = trgtcomp.Evaluate(prms, true, out workerwarnings); running = false; complete = true && !interrupt; ticker.Stop(); lock (locker) { comptime = WatchParse(ticker); evaluated = results; } } // end works lock (locker) WorkerCount--; RhinoApp.InvokeOnUiThread(new Action <bool>(ExpireSolution), new object[] { true, }); }
public override void DisplayProgress(object sender, ElapsedEventArgs e) { if (Workers.Count == 0) { return; } Message = ""; var total = 0.0; foreach (var kvp in ProgressReports) { Message += $"{kvp.Key}: {kvp.Value:0.00%}\n"; total += kvp.Value; } OverallProgress = total / ProgressReports.Keys.Count(); RhinoApp.InvokeOnUiThread((Action) delegate { OnDisplayExpired(true); }); }
public override void DisplayProgress(object sender, ElapsedEventArgs e) { if (Workers.Count == 0) { return; } Message = ""; var total = 0.0; foreach (var kvp in ProgressReports) { Message += $"{kvp.Key}: {kvp.Value}"; //NOTE: progress set to indeterminate until the TotalChildrenCount is correct total += kvp.Value; } OverallProgress = total / ProgressReports.Keys.Count(); RhinoApp.InvokeOnUiThread((Action) delegate { OnDisplayExpired(true); }); }
private void RestoreHistoryPanel(NoahTask task, bool endOfTask = true) { DebugEvent(string.Format("Restoring {0} History", task.name)); RhinoApp.InvokeOnUiThread(new Action(() => { if (HistoryPanel == null) { Panels.OpenPanel(HistoryPanel.PanelId); } HistoryPanel = Panels.GetPanel <HistoryPanel>(RhinoDoc.ActiveDoc); if (restoreHistory) { if (task.history.Count > 0) { DebugEvent(string.Format("{0} Has {1} History", task.name, task.history.Count)); HistoryPanel.SetHistory(task.name, task.history); restoreHistory = false; } } else { DebugEvent(string.Format("Pushing {0} History", task.name)); HistoryPanel.AddHistory(task.name, task.history.Last()); } HistoryPanel.RestoreEvent -= HistoryPanel_RestoreEvent; HistoryPanel.RestoreEvent += HistoryPanel_RestoreEvent; HistoryPanel.StoreEvent -= HistoryPanel_StoreEvent; HistoryPanel.StoreEvent += HistoryPanel_StoreEvent; HistoryPanel.DeleteEvent -= HistoryPanel_DeleteEvent; HistoryPanel.DeleteEvent += HistoryPanel_DeleteEvent; })); }
// Define the event handlers. private void OnChanged(object source, FileSystemEventArgs e) { RhinoApp.InvokeOnUiThread(ChangedHook, Pointer, (RhinoFileWatcherChangeReason)e.ChangeType, e.FullPath); }
public void Run() { RhinoApp.InvokeOnUiThread(new Action(() => { LoadGhDocument(TaskFile); })); }
private void ClearBtn_Click(object sender, EventArgs e) { RhinoApp.InvokeOnUiThread(new Action(() => Logs.Clear())); }
protected void ExpireSolutionThreadSafe(bool recompute = false) { var delegated = new ExpireSolutionDelegate(ExpireSolution); RhinoApp.InvokeOnUiThread(delegated, recompute); }
private void Socket_OnMessage(object sender, MessageEventArgs e) { RhinoApp.WriteLine(e.Data); try { ClientEventArgs eve = JsonConvert.DeserializeObject <ClientEventArgs>(e.Data); switch (eve.route) { case ClientEventType.TaskGetInput: { string type = eve.data["geoType"].ToString(); string pick = null; switch (type) { case "Point": { pick = "pt"; break; } case "Curve": { pick = "crv"; break; } case "Surface": { pick = "srf"; break; } case "Brep": { pick = "brp"; break; } case "ID": { pick = "id"; break; } } RhinoApp.InvokeOnUiThread(new Action(() => { var res = GH_Utils.PickFunction(pick); var data = JsonConvert.SerializeObject(new JObject { ["route"] = "TaskSetInput", ["id"] = eve.data["paramId"], ["data"] = "" }); Client.Send(data); })); break; } case ClientEventType.TaskProcess: { if (!vm.Enabled) { vm.Enabled = true; } vm.Geometries.Clear(); string file = eve.data["file"].ToString(); if (string.IsNullOrEmpty(file)) { throw new Exception("没有指定程序文件"); } if (!System.IO.File.Exists(file)) { throw new Exception("指定程序文件不存在"); } var ext = System.IO.Path.GetExtension(file); var dataGroup = new Dictionary <string, string>(); foreach (var data in eve.data["data"]) { if (!(data is JProperty prop)) { continue; } dataGroup.Add(prop.Name, prop.Value.ToString()); } // 参数类型转换 var param = eve.data["params"].ToString(); JArray paramArray = JArray.Parse(param); var parameters = new List <List <object> >(); foreach (var p in paramArray) { if (!p.HasValues) { continue; } string type = p["type"].ToString(); JArray valueArray = JArray.Parse(p["value"].ToString()); var values = new List <object>(); foreach (var val in valueArray) { var obj = IO.DecodeCommonObjectFromBase64(val.ToString()); if (obj == null) { continue; } vm.Geometries.Add(obj as GeometryBase); values.Add(obj as object); } if (values.Count < 1) { continue; } parameters.Add(values); } switch (ext) { case ".dll": { string name = System.IO.Path.GetFileNameWithoutExtension(file); Assembly assem = Assembly.LoadFrom(file); var type = assem.GetType($"{name}.Program", true, true); var res = type.GetMethod("Main").Invoke(null, new object[] { new object[] { parameters, dataGroup } }); if (!(res is object[] results)) { RhinoApp.WriteLine("回收输出的时候失败!"); break; } foreach (var obj in results) { if (!(obj is CommonObject common) || !(common is GeometryBase geo)) { continue; } vm.Geometries.Add(geo); } // TODO 回收结果 break; } case ".gh": { GH_Utils.RunHeadless(); // TODO 1 GH_Utils.ComputeGHFile(file); // TODO 回收输出 break; } case ".py": { var python = Rhino.Runtime.PythonScript.Create(); python.SetVariable("params", parameters); python.SetVariable("data", dataGroup); python.ExecuteFile(file); var output = python.GetVariable("output"); // TODO 回收输出 break; } case ".yml": { Actions actions = null; if (ext == ".ga") { //actions = DeserializeFromGAFile(filename); } else if (ext == ".yml") { actions = ParseActionsFromYamlFile(file); } else { throw new Exception($"{ext}格式不支持GA"); } //actions.SetInput(dialog.Results); actions.Solve(); break; } default: { throw new Exception($"不支持的程序类型{ext}"); } } RhinoDoc.ActiveDoc.Views.Redraw(); break; } default: break; } } catch (Exception ex) { RhinoApp.WriteLine(ex.Message); RhinoApp.WriteLine(ex.StackTrace); RhinoApp.WriteLine(ex.Source); } }
public override void DoWork(Action <string, double> ReportProgress, Action Done) { try { Parent.Message = "Creating..."; @base = new Base(); var hasErrors = false; inputData.Keys.ToList().ForEach(key => { var value = inputData[key]; if (value == null) { Done(); } else if (value is List <object> list) { // Value is a list of items, iterate and convert. var converted = list.Select(item => Utilities.TryConvertItemToSpeckle(item, Converter)).ToList(); try { @base[key] = converted; } catch (Exception e) { Log.CaptureException(e); Parent.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, $"{e.Message}"); Parent.Message = "Error"; RhinoApp.InvokeOnUiThread(new Action(() => Parent.OnDisplayExpired(true))); hasErrors = true; } } else { // If value is not list, it is a single item. try { var obj = Utilities.TryConvertItemToSpeckle(value, Converter); @base[key] = obj; } catch (Exception e) { Log.CaptureException(e); Parent.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, $"{e.Message}"); Parent.Message = "Error"; RhinoApp.InvokeOnUiThread(new Action(() => Parent.OnDisplayExpired(true))); hasErrors = true; } } }); if (!hasErrors) { Done(); } } catch (Exception e) { // If we reach this, something happened that we weren't expecting... Log.CaptureException(e); Parent.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Something went terribly wrong... " + e.Message); Parent.Message = "Error"; } }
private void OnRenamed(object source, RenamedEventArgs e) { RhinoApp.InvokeOnUiThread(RenamedHook, Pointer, e.OldFullPath, e.FullPath); }
private void Socket_OnMessage(object sender, MessageEventArgs e) { try { ClientEventArgs eve = JsonConvert.DeserializeObject <ClientEventArgs>(e.Data); switch (eve.route) { case ClientEventType.task: { NoahTask task = JsonConvert.DeserializeObject <NoahTask>(eve.data); task.SetWorkspace(WorkDir); TaskRunner(task); break; } case ClientEventType.message: { InfoEvent(this, eve.data); break; } case ClientEventType.data: { TaskData taskData = JsonConvert.DeserializeObject <TaskData>(eve.data); NoahTask noahTask = TaskList.Find(task => Equals(task.ID, taskData.ID)); if (noahTask == null) { DebugEvent("This task is not running!"); break; } GH_Canvas activeCanvas = Instances.ActiveCanvas; if (activeCanvas == null || !activeCanvas.IsDocument) { ErrorEvent(this, "No Active Canvas exist!"); return; } if (activeCanvas.Document.Properties.ProjectFileName != taskData.ID.ToString()) { DebugEvent("这个任务没有置于前台!"); return; } DebugEvent(taskData.type); noahTask.dataList.Add(taskData); noahTask.dataTable = taskData.table; TaskRunner(noahTask); break; } case ClientEventType.pick: { RhinoApp.InvokeOnUiThread(new Action(() => { GetOption go = null; var structrue = new GH_Structure <IGH_Goo>(); while (true) { go = new GetOption(); go.SetCommandPrompt("需要选择什么呢?"); go.AddOption(new LocalizeStringPair("Point", "点")); go.AddOption(new LocalizeStringPair("Curve", "线")); go.AddOption(new LocalizeStringPair("Surface", "面")); go.AddOption(new LocalizeStringPair("Guid", "ID")); GetResult result = go.Get(); if (result != GetResult.Option) { break; } string whereToGo = go.Option().EnglishName; if (whereToGo == "Curve") { var res = Picker.PickCurves(); if (res == null) { return; } res.ForEach(crv => structrue.Append(crv)); break; } else if (whereToGo == "Point") { var res = Picker.PickPoint(); if (res == null) { return; } res.ForEach(pt => structrue.Append(pt)); break; } else if (whereToGo == "Surface") { var res = Picker.PickFace(); if (res == null) { return; } res.ForEach(face => structrue.Append(face)); break; } else if (whereToGo == "Guid") { var res = Picker.PickGuid(); if (res == null) { return; } res.ForEach(text => structrue.Append(text)); break; } else { break; } } Client.Send(JsonConvert.SerializeObject(new JObject { ["route"] = "store-picker-data", ["guid"] = eve.data, ["bytes"] = IO.SerializeGrasshopperData(structrue) })); })); break; } default: break; } } catch (Exception ex) { ErrorEvent(this, ex.Message); } }