public override void Trigger(EditableView.ClickPosition.Sources source, EditableView pnlView, Transaction transaction) { string filename = FileDialog.ShowSave(FileDialog.Context.Document); if (string.IsNullOrEmpty(filename)) { return; } List <Page> list = new List <Page> { CurrentPage }; Document document = new Document(list); // constructs the document containing this page DatumList referenced = new DatumList(); CurrentPage.AddRequiredReferencesRecurseToContained(referenced.Add, Mapping.Ignore); foreach (Datum datum in referenced.Values) { switch (datum.TypeByteAsFileMarker) { case FileMarkers.Paper: break; case FileMarkers.SharedBitmap: document.AddSharedResource((SharedImage)datum); break; default: Debug.Fail("Unexpected external reference from page"); break; } } using (DataWriter writer = new DataWriter(filename, FileMarkers.Splash)) { writer.Write(document); } // We don't dispose the document because that would dispose the pages; we can just let the garbage collector cleanup the document }
public override void Trigger(EditableView.ClickPosition.Sources source, EditableView pnlView, Transaction transaction) { if (CurrentPage == null || CurrentPage.SelectedCount == 0) { return; } // the items to put on the clipboard // even if cutting, we put a different copy of the objects on the clipboard with different IDs (in case the user undoes which would restore the original objects) DatumList hash = Datum.CloneList(CurrentPage.SelectedShapes, Globals.Root.CurrentDocument); // copies shapes, changes IDs, updates links and includes references as needed // write the list of shapes into a byte buffer; this way we control the serialisation DataObject data = new DataObject(); using (MemoryStream buffer = new MemoryStream(1000)) { using (DataWriter writer = new DataWriter(buffer, FileMarkers.ShapeList)) { List <Datum> list = new List <Datum>(); list.AddRange(hash.Values); writer.WriteDatumList(list); data.SetData("Splash data", false, buffer.GetBuffer()); } } Bitmap bitmap = (Bitmap)pnlView.CreateImage(false, false, true); // will have white background - transparent gets lost somewhere within clipboard data.SetImage(bitmap); //objBitmap.Dispose()' doesn't work if this done // http://stackoverflow.com/questions/35045500/copy-svg-image-stored-as-xml-string-to-windows-clipboard-as-image-svgxml-mime-t try { var strSVG = pnlView.CreateSVG(false, true); // True) byte[] aBytes = Encoding.UTF8.GetBytes(strSVG); MemoryStream objStream = new MemoryStream(aBytes); data.SetData("image/svg+xml", objStream); //System.IO.File.WriteAllText("g:\temp\svg.svg", strSVG) } catch (UserException u) { Globals.Root.Log.WriteLine("Cannot copy as SVG: " + u.Message); } catch (Exception ex) { Utilities.LogSubError(ex); } //check for text string text = ""; foreach (Shape shape in CurrentPage.SelectedShapes) { if (shape.HasText(true) && !String.IsNullOrEmpty(shape.LabelText)) { text = shape.LabelText; break; // stop once valid text found } } if (!string.IsNullOrEmpty(text)) { data.SetText(text); } // store result on clipboard Clipboard.SetDataObject(data); if (IsCut) { CurrentPage.DeleteSelected(transaction); } }
private void PasteSplashData(Transaction transaction, EditableView pnlView) { DataObject data = (DataObject)Clipboard.GetDataObject(); byte[] buffer = (byte[])data.GetData("Splash data", false); // will be nothing if deserialisation failed if (buffer == null) { Debug.Fail("Deserialisation failed"); return; } using (MemoryStream stream = new MemoryStream(buffer, false)) using (DataReader reader = new DataReader(stream, FileMarkers.ShapeList)) { List <Datum> list = reader.ReadDataList(); // cannot insert objects directly as that would mean pasting twice inserted 2 objects with same ID Mapping hashIDChanges = new Mapping(); DatumList newList = new DatumList(); RectangleF bounds = RectangleF.Empty; // work out existing bounds of list bool includesShapes = false; foreach (Datum datum in list) { if (datum is Shape) { // assumed that all shapes need to be created into page Shape create = (Shape)datum.Clone(hashIDChanges); transaction.Create(create); newList.Add(create); Geometry.Extend(ref bounds, create.MinimalBounds); // minimal makes, for example, the snapping of axes better includesShapes = true; } else if (datum is SharedBase resource) { // no need to clone these as they are effectively invariant if (CurrentDocument.FindExistingSharedResource <Datum>(resource.ID) == null) { transaction.Edit(CurrentDocument); CurrentDocument.AddSharedResource(resource); // if ID exists in this document it is assumed to be same object } } else if (datum is ButtonStyle buttonStyle) { // as Shape, but don't add to page // if IsShared it is not cloned. Means styles in multi docs will share ID, which is good as further pasting in will reuse existing style // does need to be added to document share ButtonStyle create; if (buttonStyle.IsShared) { create = buttonStyle; if (CurrentDocument.GetButtonStyle(create.ID) == null) { CurrentDocument.AddButtonStyle(create); // is new to this doc - either by cloning, or transaction.Create(create); } } else { create = (ButtonStyle)buttonStyle.Clone(hashIDChanges); transaction.Create(create); } newList.Add(create); } else { Debug.Fail("Datum not processed by by Paste: " + datum.TypeByte); } } // want to centre shapes within current area, rather than pasting at original position (which leaves them on top of each other and largely invisible) IShapeContainer container = CurrentPage; if (includesShapes) { if (CurrentPage.SelectedCount == 1 && CurrentPage.SelectedShapes.First().AsContainer != null) { container = CurrentPage.SelectedShapes.First().AsContainer; // but in SAW don't paste automatically into an empty container - chances are it's the item which was just copied! // instead paste into that container's parent if (!container.Any()) { container = (container as Shape).Container.AsParentContainer; } } PointF target = pnlView.ViewableArea().Centre(); // Or use cursor position if better PointF cursor = pnlView.CursorPositionLocal; // Automatically selects the drawing cursor if split cursors are used // or the container if (((Datum)container).TypeByte == (byte)Shape.Shapes.Container) { target = ((Shape)container).Bounds.Centre(); } else if (cursor.X > 0 && cursor.Y > 0 && cursor.X < pnlView.Width && cursor.Y < pnlView.Height) { cursor = pnlView.MouseToData(cursor.ToPoint()); // And also need to check the cursor is within the page. the above just checked it was within the control (there may be some dead area displayed) if (cursor.X < pnlView.ViewableArea().Width&& cursor.Y < pnlView.ViewableArea().Height) { target = cursor; } } target.X -= bounds.Width / 2; target.Y -= bounds.Height / 2; // where we want the top left to be if (pnlView.SnapMode == Shape.SnapModes.Grid) { target = CurrentPage.Paper.SnapPoint2(target); } var transform = new TransformMove(target.X - bounds.X, target.Y - bounds.Y); transaction.Edit((Datum)container); foreach (Shape shape in newList.Values.OfType <Shape>()) // of type needed in case other stuff was mixed in with it { container.Contents.Add(shape); shape.Parent = container; shape.ApplyTransformation(transform); } container.FinishedModifyingContents(transaction); } foreach (Datum shape in newList.Values) { try { // order changed shape.UpdateReferencesObjectsCreated(CurrentDocument, reader); shape.UpdateReferencesIDsChanged(hashIDChanges, Globals.Root.CurrentDocument); } catch (Exception ex) { Utilities.LogSubError(ex); } } List <Shape> newShapes = newList.Values.OfType <Shape>().ToList(); if (newShapes.Count > 0 && container == CurrentPage) // don't select the shapes when pasting into a container - leaves the container selected, which allows for more pastes { CurrentPage.SelectOnly(newShapes); } pnlView.InvalidateData(CurrentPage.SelectedRefreshBoundary(), StaticView.InvalidationBuffer.All); } }
// Sets up joint based on already populated datums // Pre-Condition: DatumList is filled out private void SetupJoint(List <CyPhy.CADDatum> datumlist, List <CyPhy.CADDatum> limitreflist, Dictionary <string, DataRep.Datum> limitrefmap) { if ((CyPhyImpl as CyPhy.Connector).Children.KinematicRevoluteJointCollection.Any()) { Joint = new KinematicJoint((CyPhyImpl as CyPhy.Connector).Children.KinematicRevoluteJointCollection.First()); } else if ((CyPhyImpl as CyPhy.Connector).Children.KinematicCylindricalJointCollection.Any()) { Joint = new KinematicJoint((CyPhyImpl as CyPhy.Connector).Children.KinematicCylindricalJointCollection.First()); } else if ((CyPhyImpl as CyPhy.Connector).Children.KinematicFixedJointCollection.Any()) { Joint = new KinematicJoint((CyPhyImpl as CyPhy.Connector).Children.KinematicFixedJointCollection.First()); } else if ((CyPhyImpl as CyPhy.Connector).Children.KinematicTranslationalJointCollection.Any()) { Joint = new KinematicJoint((CyPhyImpl as CyPhy.Connector).Children.KinematicTranslationalJointCollection.First()); } // Get the datums to associate with this joint if (Joint != null) { foreach (var cyphydatum in datumlist) { Datum datarepdatum; if (DatumList.TryGetValue(cyphydatum.Name, out datarepdatum)) { // Is datum part of defining the joint? if (cyphydatum.SrcConnections.KinematicJointDefinitionCollection.Any()) { if (cyphydatum is CyPhy.Axis) { Joint.Axis = datarepdatum; } else if (cyphydatum is CyPhy.Surface) { Joint.AlignmentPlane = datarepdatum; } } } } if (limitreflist.Any() && Joint.JointType == KinematicJoint.KinematicJointType.REVOLUTE) { throw new Exception("Limit references for revolute joints are not supported currently. Guides will be used as limit references. Please remove limit references on rvlute joints from your model. Connector: " + CyPhyImpl.Name + ", Parent: " + CyPhyImpl.ParentContainer.Name); } var guides = datumlist.Where(d => d.Attributes.DefinitionNotes.Contains("GUIDE")); if (guides.Any()) { Logger.Instance.AddLogMessage("Datum is using old guide format. Please use the attribute 'IsGuide'. Connector: " + CyPhyImpl.Path, Severity.Error); return; } guides = datumlist.Where(d => d.Attributes.IsGuide); if (guides.Count() > 1) { throw new Exception("More than one guides in a kinematic joint. This is not supported yet. Connector: " + CyPhyImpl.Path); } else if (guides.Count() == 1) { Joint.RotationDefaultReference = this.DatumList[guides.First().Name]; } foreach (var limitrefdatum in limitreflist) { Datum datarepdatum; if (limitrefmap.TryGetValue(limitrefdatum.Name, out datarepdatum)) { // Is this datum part of defining the limits of the joint? if ((limitrefdatum as CyPhy.Surface).SrcConnections.KinematicTranslationalLimitReferenceCollection.Any()) { var limittype = (limitrefdatum as CyPhy.Surface).SrcConnections.KinematicTranslationalLimitReferenceCollection.First().Attributes.TranslationalLimitReferenceType; // Default if (limittype == CyPhyClasses.KinematicTranslationalLimitReference.AttributesClass.TranslationalLimitReferenceType_enum.NormalExtent) { Joint.TranslationDefaultReference = datarepdatum; } // Min else if (limittype == CyPhyClasses.KinematicTranslationalLimitReference.AttributesClass.TranslationalLimitReferenceType_enum.MinExtent) { throw new Exception("Min and max references are not yet supported. Please remove these." + CyPhyImpl.Name + ", Parent: " + CyPhyImpl.ParentContainer.Name); } // Max else { throw new Exception("Min and max references are not yet supported. Please remove these." + CyPhyImpl.Name + ", Parent: " + CyPhyImpl.ParentContainer.Name); } } } } if ((Joint.RotationLimitMax.HasValue || Joint.RotationLimitMin.HasValue) && !Joint.RotationLimitDefault.HasValue) { throw new Exception("Joint has rotation limit max or min specified, but not default. Please specify default value as well." + CyPhyImpl.Name + ", Parent: " + CyPhyImpl.ParentContainer.Name); } if (Joint.RotationLimitDefault.HasValue && Joint.RotationDefaultReference == null) { throw new Exception("Joint has rotation limit specified, but there are no guides present to be used as rotation references. Please define guides for the connection as well." + CyPhyImpl.Name + ", Parent: " + CyPhyImpl.ParentContainer.Name); } if ((Joint.TranslationLimitMax.HasValue || Joint.TranslationLimitMin.HasValue) && !Joint.TranslationLimitDefault.HasValue) { throw new Exception("Joint has translation limit max or min specified, but not default. Please specify default value as well." + CyPhyImpl.Name + ", Parent: " + CyPhyImpl.ParentContainer.Name); } if (Joint.TranslationLimitDefault.HasValue && Joint.TranslationDefaultReference == null) { throw new Exception("Joint has translation limit specified, but there is no limit reference present. Please define limit references in the connection as well." + CyPhyImpl.Name + ", Parent: " + CyPhyImpl.ParentContainer.Name); } if (Joint.RotationLimitMax.HasValue && Joint.RotationLimitMin.HasValue && Joint.RotationLimitMin.Value > Joint.RotationLimitMax.Value) { throw new Exception("Joint rotation limit min > max. Please correct this." + CyPhyImpl.Name + ", Parent: " + CyPhyImpl.ParentContainer.Name); } } }
public int GetDegreesOfFreedom() { int AxisCnt = 0, PointCnt = 0, SurfaceCnt = 0, CsysCnt = 0; int count = DatumList.Count(), dof = 0; foreach (KeyValuePair <string, Datum> item in DatumList) { string dtype = item.Value.Type.ToString(); if (dtype == "Axis") { AxisCnt++; } else if (dtype == "Point") { PointCnt++; } else if (dtype == "Surface") { SurfaceCnt++; } else if (dtype == "CoordinateSystem") { CsysCnt++; } } if (CsysCnt > 0) { switch (count) { case 0: dof = 0; break; case 1: { if (AxisCnt > 0) { dof = 4; } else { dof = 3; } } break; case 2: dof = 5; break; case 3: dof = 6; break; default: dof = 6; break; } } else { dof = 6; } return(dof); }
/// <summary> /// Returns List<KeyValuePair<(int)testCaseNumber, List<int[]>>> /// <para>Pair value List<(int[])> has index of: [0]scenarioId, [1]scenarioSnapshotId, [2]lastResultId</para> /// </summary> /// <param name="testRunId"></param> /// <returns></returns> public List <KeyValuePair <int, List <int> > > BuildTestRunSnapshotData(int testRunId) { string content = string.Empty; string testName = string.Empty; int scenarioId = -1; int scenarioSnapshotId = -1; int lastResultId = -1; var runData = new List <KeyValuePair <int, List <int> > >(); var snapshotRequestParams = new object[] { testRunId }; try { var snapshotIdTask = Task.Factory.StartNew(() => CallExecuteRequest(Method.GET, ResourceType.TestSnapshots, null, snapshotRequestParams)); var snapshotResultTask = snapshotIdTask.Result; var snapshotTaskList = new Task[] { snapshotIdTask, snapshotResultTask }; Task.WaitAll(snapshotTaskList); var snapshotIdContent = snapshotResultTask.Result.Content; DatumList dataList = new DatumList(); dataList = (DatumList)newtJson.Newtonsoft.Json.JsonConvert.DeserializeObject(snapshotIdContent, typeof(DatumList)); int dataCount = dataList.data.Count; for (int i = 0; i < dataCount; i++) { scenarioSnapshotId = dataList.data[i].id; testName = dataList.data[i].attributes.name; scenarioId = dataList.data[i].relationships.scenario.data.id; //scenarioSnapshotId = dataList.data[i].attributes.scenario_snapshot_id; Console.WriteLine($"\n### TestCase#: {scenarioId}\n### TestName: {testName}\n### ScenarioSnapshotID: {scenarioSnapshotId}"); var testResultRequestParams = new object[] { testRunId, scenarioSnapshotId }; var resultIdTask = CallExecuteRequest(Method.GET, ResourceType.TestResults, null, testResultRequestParams); Task.WaitAll(resultIdTask); var resultIdContent = resultIdTask.Result.Content; RootObject root = new RootObject(); root = (RootObject)newtJson.Newtonsoft.Json.JsonConvert.DeserializeObject(resultIdContent, typeof(RootObject)); lastResultId = root.included[0].id; Console.WriteLine($"\n### LastResultID: {lastResultId}\n"); var scenarioSnapshotData = new List <int> { testRunId, scenarioSnapshotId, lastResultId }; runData.Add(new KeyValuePair <int, List <int> >(scenarioId, scenarioSnapshotData)); } return(runData); } catch (Exception e) { log.Debug(e.Message); throw; } }