public static void Run() { try { // ExStart:ExportToSWFWithoutViewer // The path to the documents directory. string dataDir = RunExamples.GetDataDir_Diagrams(); // Instantiate Diagram Object and open VSD file Diagram diagram = new Diagram(dataDir + "ExportToSWFWithoutViewer.vsd"); // Instantiate the Save Options SWFSaveOptions options = new SWFSaveOptions(); // Set Save format as SWF options.SaveFormat = SaveFileFormat.SWF; // Exclude the embedded viewer options.ViewerIncluded = false; // Save the resultant SWF file diagram.Save(dataDir + "ExportToSWFWithoutViewer_out.swf", SaveFileFormat.SWF); // ExEnd:ExportToSWFWithoutViewer } catch (System.Exception ex) { System.Console.WriteLine(ex.Message + "\nThis example will only work if you apply a valid Aspose License. You can purchase full license or get 30 day temporary license from http:// Www.aspose.com/purchase/default.aspx."); } }
public static void Run() { // ExStart:UseSVGSaveOptions // The path to the documents directory. string dataDir = RunExamples.GetDataDir_LoadSaveConvert(); // Call the diagram constructor to load diagram from a VSD file Diagram diagram = new Diagram(dataDir + "Drawing1.vsdx"); SVGSaveOptions options = new SVGSaveOptions(); // Summary: // value or the font is not installed locally, they may appear as a block, // set the DefaultFont such as MingLiu or MS Gothic to show these // characters. options.DefaultFont = "MS Gothic"; // Sets the 0-based index of the first page to render. Default is 0. options.PageIndex = 0; // Set page size PageSize pgSize = new PageSize(PaperSizeFormat.A1); options.PageSize = pgSize; diagram.Save(dataDir + "UseSVGSaveOptions_out.svg", options); // ExEnd:UseSVGSaveOptions }
public static void Run() { // ExStart:ExtractAllImagesFromPage // The path to the documents directory. string dataDir = RunExamples.GetDataDir_Shapes(); // Call a Diagram class constructor to load a VSD diagram Diagram diagram = new Diagram(dataDir + "ExtractAllImagesFromPage.vsd"); // Enter page index i.e. 0 for first one foreach (Shape shape in diagram.Pages[0].Shapes) { // Filter shapes by type Foreign if (shape.Type == Aspose.Diagram.TypeValue.Foreign) { using (System.IO.MemoryStream stream = new System.IO.MemoryStream(shape.ForeignData.Value)) { // Load memory stream into bitmap object System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(stream); // Save bmp here bitmap.Save(dataDir + "ExtractAllImages" + shape.ID + "_out.bmp"); } } } // ExEnd:ExtractAllImagesFromPage }
public ConnectionCreator(Diagram diagram, Shape first, RelationshipType type) { this.diagram = diagram; this.type = type; this.first = first; firstSelected = true; }
public static void Run() { // ExStart:ConnectVisioSubShapes // The path to the documents directory. string dataDir = RunExamples.GetDataDir_Shapes(); // Set sub shape ids long shapeFromId = 2; long shapeToId = 4; // Load diagram Diagram diagram = new Diagram(dataDir + "Drawing1.vsdx"); // Access a particular page Page page = diagram.Pages.GetPage("Page-3"); // Initialize connector shape Shape shape = new Shape(); shape.Line.EndArrow.Value = 4; shape.Line.LineWeight.Value = 0.01388; // Add shape long connecter1Id = diagram.AddShape(shape, "Dynamic connector", page.ID); // Connect sub-shapes page.ConnectShapesViaConnector(shapeFromId, ConnectionPointPlace.Right, shapeToId, ConnectionPointPlace.Left, connecter1Id); // Save Visio drawing diagram.Save(dataDir + "ConnectVisioSubShapes_out.vsdx", SaveFileFormat.VSDX); // ExEnd:ConnectVisioSubShapes }
public static void Run() { // ExStart:SetShapeTextPositionAtBottom // The path to the documents directory. string dataDir = RunExamples.GetDataDir_ShapeTextBoxData(); // Load source Visio diagram Diagram diagram = new Diagram(dataDir + "Drawing1.vsdx"); // Get shape long shapeid = 1; Shape shape = diagram.Pages.GetPage("Page-1").Shapes.GetShape(shapeid); // Set text position at the bottom, // TxtLocPinY = "TxtHeight*1" and TxtPinY = "Height*0" shape.TextXForm.TxtLocPinY.Value = shape.TextXForm.TxtHeight.Value; shape.TextXForm.TxtPinY.Value = 0; // Set orientation angle double angleDeg = 0; double angleRad = (Math.PI / 180) * angleDeg; shape.TextXForm.TxtAngle.Value = angleRad; // Save Visio diagram in the local storage diagram.Save(dataDir + "SetShapeTextPositionAtBottom_out.vsdx", SaveFileFormat.VSDX); // ExEnd:SetShapeTextPositionAtBottom }
public static void Run() { try { // ExStart:ExportOfHiddenVisioPagesToSVG // The path to the documents directory. string dataDir = RunExamples.GetDataDir_Intro(); // Load an existing Visio Diagram diagram = new Diagram(dataDir + "Drawing1.vsdx"); // Get a particular page Page page = diagram.Pages.GetPage("Flow 2"); // Set Visio page visiblity page.PageSheet.PageProps.UIVisibility.Value = BOOL.True; // Initialize PDF save options SVGSaveOptions options = new SVGSaveOptions(); // Set export option of hidden Visio pages options.ExportHiddenPage = false; // Save the Visio diagram diagram.Save(dataDir + "ExportOfHiddenVisioPagesToSVG_out.svg", options); // ExEnd:ExportOfHiddenVisioPagesToSVG } catch (System.Exception ex) { System.Console.WriteLine(ex.Message + "\nThis example will only work if you apply a valid Aspose License. You can purchase full license or get 30 day temporary license from http:// Www.aspose.com/purchase/default.aspx."); } }
public static void Run() { // ExStart:AddHyperlinkToShape // The path to the documents directory. string dataDir = RunExamples.GetDataDir_Hyperlinks(); // Load source Visio diagram Diagram diagram = new Diagram(dataDir + "Drawing1.vsdx"); // Get page by name Page page = diagram.Pages.GetPage("Page-1"); // Get shape by ID Shape shape = page.Shapes.GetShape(2); // Initialize Hyperlink object Hyperlink hyperlink = new Hyperlink(); // Set address value hyperlink.Address.Value = "http:// Www.google.com/"; // Set sub address value hyperlink.SubAddress.Value = "Sub address here"; // Set description value hyperlink.Description.Value = "Description here"; // Set name hyperlink.Name = "MyHyperLink"; // Add hyperlink to the shape shape.Hyperlinks.Add(hyperlink); // Save diagram to local space diagram.Save(dataDir + "AddHyperlinkToShape_out.vsdx", SaveFileFormat.VSDX); // ExEnd:AddHyperlinkToShape }
public static void Run() { // ExStart:RetrievePageInfo // The path to the documents directory. string dataDir = RunExamples.GetDataDir_VisioPages(); // Call the diagram constructor to load diagram from a VDX file Diagram vdxDiagram = new Diagram(dataDir + "RetrievePageInfo.vdx"); foreach (Aspose.Diagram.Page page in vdxDiagram.Pages) { // Checks if current page is a background page if (page.Background == Aspose.Diagram.BOOL.True) { // Display information about the background page Console.WriteLine("Background Page ID : " + page.ID); Console.WriteLine("Background Page Name : " + page.Name); } else { // Display information about the foreground page Console.WriteLine("\nPage ID : " + page.ID); Console.WriteLine("Universal Name : " + page.NameU); Console.WriteLine("ID of the Background Page : " + page.BackPage); } } // ExEnd:RetrievePageInfo }
public static void Run() { // ExStart:CalculateCenterOfSubShapes // The path to the documents directory. string dataDir = RunExamples.GetDataDir_Shapes(); // Load Visio diagram Diagram diagram = new Diagram(dataDir + "Drawing1.vsdx"); // Get a group shape by ID and page index is 0 Shape shape = diagram.Pages[0].Shapes.GetShape(795); // Get a sub-shape of the group shape by id Shape subShape = shape.Shapes.GetShape(794); Matrix m = new Matrix(); // Apply the translation vector m.Translate(-(float)subShape.XForm.LocPinX.Value, -(float)subShape.XForm.LocPinY.Value); // Set the elements of that matrix to a rotation m.Rotate((float)subShape.XForm.Angle.Value); // Apply the translation vector m.Translate((float)subShape.XForm.PinX.Value, (float)subShape.XForm.PinY.Value); // Get pinx and piny double pinx = m.OffsetX; double piny = m.OffsetY; // Calculate the sub-shape pinx and piny double resultx = shape.XForm.PinX.Value - shape.XForm.LocPinX.Value - pinx; double resulty = shape.XForm.PinY.Value - shape.XForm.LocPinY.Value - piny; // ExEnd:CalculateCenterOfSubShapes }
public DiagramLinkWrapper(Model model, ConnectorWrapper relation, Diagram diagram){ this.model = model; this.relation = relation; this.diagram = diagram; this.wrappedDiagramLink = diagram.getDiagramLinkForRelation(relation); }
public String saveDiagram( Diagram diagram, string author, string password) { this.author = author; this.password = password; return this.saveDiagram(diagram); }
static void Main(string[] args) { // Load diagram Diagram diagram = new Diagram(@"E:\Aspose\Aspose Vs VSTO\Aspose.Diagram Vs VSTO Visio v1.1\Sample Files\Drawing1.vsd"); // Get max page ID int MaxPageId = GetMaxPageID(diagram); // Initialize a new page object Page newPage = new Page(); // Set name newPage.Name = "new page"; // Set page ID newPage.ID = MaxPageId + 1; // Or try the Page constructor // Page newPage = new Page(MaxPageId + 1); // Add a new blank page diagram.Pages.Add(newPage); // Save diagram diagram.Save(@"E:\Aspose\Aspose Vs VSTO\Aspose.Diagram Vs VSTO Visio v1.1\Sample Files\Output.vdx", SaveFileFormat.VDX); }
static void Main(string[] args) { //Save the uploaded file as PDF Diagram diagram = new Diagram("Drawing1.vsd"); //Find a particular shape and update its properties foreach (Aspose.Diagram.Shape shape in diagram.Pages[0].Shapes) { if (shape.Name.ToLower() == "process1") { shape.Text.Value.Clear(); shape.Text.Value.Add(new Txt("Hello World")); //Find custom style sheet and set as shape's text style foreach (StyleSheet styleSheet in diagram.StyleSheets) { if (styleSheet.Name == "CustomStyle1") { shape.TextStyle = styleSheet; } } //Set horizontal and vertical position of the shape shape.XForm.PinX.Value = 5; shape.XForm.PinY.Value = 5; //Set height and width of the shape shape.XForm.Height.Value = 2; shape.XForm.Width.Value = 3; } } //Save shape as VDX diagram.Save("Drawing1.vdx", SaveFileFormat.VDX); }
public static void Main(string[] args) { // The path to the documents directory. string dataDir = Path.GetFullPath("../../../Data/"); //Call the diagram constructor to load diagram from a VDX file Diagram vdxDiagram = new Diagram(dataDir + "drawing.vdx"); foreach (Aspose.Diagram.Page page in vdxDiagram.Pages) { //Checks if current page is a background page if (page.Background == Aspose.Diagram.BOOL.True) { //Display information about the background page Console.WriteLine("Background Page ID : " + page.ID); Console.WriteLine("Background Page Name : " + page.Name); } else { //Display information about the foreground page Console.WriteLine("\nPage ID : " + page.ID); Console.WriteLine("Universal Name : " + page.NameU); Console.WriteLine("ID of the Background Page : " + page.BackPage); } } Console.ReadLine(); }
public static void Run() { // ExStart:RetrieveUserDefinedCells // The path to the documents directory. string dataDir = RunExamples.GetDataDir_UserDefinedCells(); int count = 0; // Load diagram Diagram diagram = new Diagram(dataDir + "Drawing1.vsdx"); // Iterate through pages foreach (Aspose.Diagram.Page objPage in diagram.Pages) { // Iterate through shapes foreach (Aspose.Diagram.Shape objShape in objPage.Shapes) { Console.WriteLine(objShape.NameU); // Iterate through user-defined cells foreach (Aspose.Diagram.User objUserField in objShape.Users) { count++; Console.WriteLine(count + " - Name: " + objUserField.NameU + " Value: " + objUserField.Value.Val + " Prompt: " + objUserField.Prompt.Value); } } } // ExEnd:RetrieveUserDefinedCells }
public static void Run() { // ExStart:ReplaceShapePicture // The path to the documents directory. string dataDir = RunExamples.GetDataDir_Shapes(); // Call a Diagram class constructor to load the VSD diagram Diagram diagram = new Diagram(dataDir + "ExtractAllImagesFromPage.vsd"); // Convert image into bytes array byte[] imageBytes = File.ReadAllBytes(dataDir + "Picture.png"); // Enter page index i.e. 0 for first one foreach (Shape shape in diagram.Pages[0].Shapes) { // Filter shapes by type Foreign if (shape.Type == Aspose.Diagram.TypeValue.Foreign) { using (System.IO.MemoryStream stream = new System.IO.MemoryStream(shape.ForeignData.Value)) { // Replace picture shape shape.ForeignData.Value = imageBytes; } } } // Save diagram diagram.Save(dataDir + "ReplaceShapePicture_out.vsdx", SaveFileFormat.VSDX); // ExEnd:ReplaceShapePicture }
public override void ValidateMenuItems(Diagram diagram) { base.ValidateMenuItems(diagram); ConnectionKryptonContextMenu.Default.ValidateMenuItems(diagram); mnuEdit.Enabled = (diagram.SelectedElementCount == 1); UpdateTexts(); }
public static Diagram Parse(Tokenizer t) { var ans = new Diagram(); while( !(ans.HasErrors || t.OutOfChars) ) { Token next = t.NextToken(); switch (next.type) { case TokenType.TOK_EOL: // empty lines are ok break; case TokenType.TOK_TITLE: // we have a title getTitle(t,ans); break; case TokenType.TOK_NOTE: // we have a note getNote(t, ans); break; case TokenType.TOK_IDENTIFIER: parseIdentifier(t, ans, next); break; default: // anything else is a problem! ans.HasErrors = true; break; } } return ans; }
private static void getNote(Tokenizer t, Diagram d) { // a NOTE takes the form: NOTE Actor: the note is here.... Token id = t.NextToken(); if (id.type != TokenType.TOK_IDENTIFIER) { d.HasErrors = true; return; } var actor = d.MaybeNewActor(id.data); Token str = t.NextToken(); string desc = null; switch(str.type) { case TokenType.TOK_STRING: desc = str.data; break; case TokenType.TOK_EOL: desc = ""; break; default: d.HasErrors = true; return; } var ln = d.AddLine(actor, actor); ln.Desc = desc; ln.Note = true; }
public static void Run() { // The path to the documents directory. string dataDir = RunExamples.GetDataDir_Diagrams(); // 1. // Exporting VSD to VDX //Call the diagram constructor to load diagram from a VSD file Diagram diagram = new Diagram(dataDir + "ExportToXML.vsd"); //Save input VSD as VDX diagram.Save(dataDir + "outputVSDtoVDX.vdx", SaveFileFormat.VDX); // 2. // Exporting from VSD to VSX // Call the diagram constructor to load diagram from a VSD file //Save input VSD as VSX diagram.Save(dataDir + "outputVSDtoVSX.vsx", SaveFileFormat.VSX); // 3. // Export VSD to VTX //Save input VSD as VTX diagram.Save(dataDir + "outputVSDtoVTX.vtx", SaveFileFormat.VTX); }
public static void Run() { // The path to the documents directory. string dataDir = RunExamples.GetDataDir_Diagrams(); string fileName = "LayOutShapesInCompactTreeStyle.vdx"; Diagram diagram = new Diagram(dataDir + fileName); LayoutOptions compactTreeOptions = new LayoutOptions(); compactTreeOptions.LayoutStyle = LayoutStyle.CompactTree; compactTreeOptions.EnlargePage = true; compactTreeOptions.Direction = LayoutDirection.DownThenRight; diagram.Layout(compactTreeOptions); diagram.Save(dataDir + "sample_down_right.vdx", SaveFileFormat.VDX); diagram = new Diagram(dataDir + fileName); compactTreeOptions.Direction = LayoutDirection.DownThenLeft; diagram.Layout(compactTreeOptions); diagram.Save(dataDir + "sample_down_left.vdx", SaveFileFormat.VDX); diagram = new Diagram(dataDir + fileName); compactTreeOptions.Direction = LayoutDirection.RightThenDown; diagram.Layout(compactTreeOptions); diagram.Save(dataDir + "sample_right_down.vdx", SaveFileFormat.VDX); diagram = new Diagram(dataDir + fileName); compactTreeOptions.Direction = LayoutDirection.LeftThenDown; diagram.Layout(compactTreeOptions); diagram.Save(dataDir + "sample_left_down.vdx", SaveFileFormat.VDX); }
static void Main(string[] args) { string visioStencil = "sample.vss"; // Create a new diagram Diagram diagram = new Diagram(visioStencil); //Add a new rectangle shape long shapeId = diagram.AddShape( 4.25, 5.5, 2, 1, @"Rectangle", 0); Shape shape = diagram.Pages[0].Shapes.GetShape(shapeId); shape.Text.Value.Add(new Txt(@"Rectangle text.")); //Add a new star shape shapeId = diagram.AddShape( 2.0, 5.5, 2, 2, @"Star 7", 0); shape = diagram.Pages[0].Shapes.GetShape(shapeId); shape.Text.Value.Add(new Txt(@"Star text.")); //Add a new hexagon shape shapeId = diagram.AddShape( 7.0, 5.5, 2, 2, @"Hexagon", 0); shape = diagram.Pages[0].Shapes.GetShape(shapeId); shape.Text.Value.Add(new Txt(@"Hexagon text.")); //Save the new diagram diagram.Save("Drawing1.vdx", SaveFileFormat.VDX); }
public static void Main(string[] args) { // The path to the documents directory. string dataDir = Path.GetFullPath("../../../Data/"); string visioStencil = dataDir + "Basic Shapes.vss"; // Create a new diagram. Diagram diagram = new Diagram(visioStencil); //Add a new rectangle shape. long shapeId = diagram.AddShape( 4.25, 5.5, 2, 1, @"Rectangle", 0); Shape shape = diagram.Pages[0].Shapes.GetShape(shapeId); shape.Text.Value.Add(new Txt(@"Rectangle text.")); //Add a new star shape. shapeId = diagram.AddShape( 2.0, 5.5, 2, 2, @"Star 7", 0); shape = diagram.Pages[0].Shapes.GetShape(shapeId); shape.Text.Value.Add(new Txt(@"Star text.")); //Add a new hexagon shape. shapeId = diagram.AddShape( 7.0, 5.5, 2, 2, @"Hexagon", 0); shape = diagram.Pages[0].Shapes.GetShape(shapeId); shape.Text.Value.Add(new Txt(@"Hexagon text.")); //Save the new diagram. diagram.Save(dataDir + "Drawing1.vdx", SaveFileFormat.VDX); // Display Status. System.Console.WriteLine("Diagram created and saved successfully."); }
public static void Run() { // ExStart:UseDiagramSaveOptions // The path to the documents directory. string dataDir = RunExamples.GetDataDir_LoadSaveConvert(); // Call the diagram constructor to a VSDX diagram Diagram diagram = new Diagram(dataDir + "Drawing1.vsdx"); // Options when saving a diagram into Visio format DiagramSaveOptions options = new DiagramSaveOptions(SaveFileFormat.VSDX); // Summary: // When characters in the diagram are unicode and not be set with correct font // value or the font is not installed locally, they may appear as block, // image or XPS. Set the DefaultFont such as MingLiu or MS Gothic to show these // characters. options.DefaultFont = "MS Gothic"; // Summary: // Defines whether need enlarge page to fit drawing content or not. // Remarks: // Default value is false. options.AutoFitPageToDrawingContent = true; diagram.Save(dataDir + "UseDiagramSaveOptions_out.vsdx", options); // ExEnd:UseDiagramSaveOptions }
public static void Run() { // The path to the documents directory. string dataDir = RunExamples.GetDataDir_Diagrams(); string fileName = "LayOutShapesInFlowchartStyle.vdx"; Diagram diagram = new Diagram(dataDir + fileName); LayoutOptions flowChartOptions = new LayoutOptions(); flowChartOptions.LayoutStyle = LayoutStyle.FlowChart; flowChartOptions.SpaceShapes = 1f; flowChartOptions.EnlargePage = true; flowChartOptions.Direction = LayoutDirection.BottomToTop; diagram.Layout(flowChartOptions); diagram.Save(dataDir + "sample_btm_top.vdx", SaveFileFormat.VDX); diagram = new Diagram(dataDir + fileName); flowChartOptions.Direction = LayoutDirection.TopToBottom; diagram.Layout(flowChartOptions); diagram.Save(dataDir + "sample_top_btm.vdx", SaveFileFormat.VDX); diagram = new Diagram(dataDir + fileName); flowChartOptions.Direction = LayoutDirection.LeftToRight; diagram.Layout(flowChartOptions); diagram.Save(dataDir + "sample_left_right.vdx", SaveFileFormat.VDX); diagram = new Diagram(dataDir + fileName); flowChartOptions.Direction = LayoutDirection.RightToLeft; diagram.Layout(flowChartOptions); diagram.Save(dataDir + "sample_right_left.vdx", SaveFileFormat.VDX); }
public static void Main(string[] args) { // The path to the documents directory. string dataDir = Path.GetFullPath("../../../Data/"); //Call the diagram constructor to load diagram from a VSD file Diagram diagram = new Diagram(dataDir + "drawing.vsd"); //enter page index i.e. 0 for first one foreach (Shape shape in diagram.Pages[0].Shapes) { //Filter shapes by type Foreign if (shape.Type == Aspose.Diagram.TypeValue.Foreign) { using (System.IO.MemoryStream stream = new System.IO.MemoryStream(shape.ForeignData.Value)) { //Load memory stream into bitmap object System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(stream); // save bmp here bitmap.Save(dataDir + "Image" + shape.ID + ".bmp"); } } } }
public static void Run() { // ExStart:GroupShapes // The path to the documents directory. string dataDir = RunExamples.GetDataDir_Shapes(); // Load a Visio diagram Diagram diagram = new Diagram(dataDir + "Drawing1.vsdx"); // Get page by name Page page = diagram.Pages.GetPage("Page-3"); // Initialize an array of shapes Aspose.Diagram.Shape[] ss = new Aspose.Diagram.Shape[3]; // Extract and assign shapes to the array ss[0] = page.Shapes.GetShape(15); ss[1] = page.Shapes.GetShape(16); ss[2] = page.Shapes.GetShape(17); // Mark array shapes as group page.Shapes.Group(ss); // Save visio diagram diagram.Save(dataDir + "GroupShapes_out.vsdx", SaveFileFormat.VSDX); // ExEnd:GroupShapes }
public static void Run() { // ExStart:SetVisioProperties // The path to the documents directory. string dataDir = RunExamples.GetDataDir_Intro(); // Build path of an existing diagram string visioDrawing = dataDir + "Drawing1.vsdx"; // Call the diagram constructor to load diagram from a VSDX file Diagram diagram = new Diagram(visioDrawing); // Set some summary information about the diagram diagram.DocumentProps.Creator = "Ijaz"; diagram.DocumentProps.Company = "Aspose"; diagram.DocumentProps.Category = "Drawing 2D"; diagram.DocumentProps.Manager = "Sergey Polshkov"; diagram.DocumentProps.Title = "Aspose Title"; diagram.DocumentProps.TimeCreated = DateTime.Now; diagram.DocumentProps.Subject = "Visio Diagram"; diagram.DocumentProps.Template = "Aspose Template"; // Write the updated file to the disk in VSDX file format diagram.Save(dataDir + "SetVisioProperties_out.vsdx", SaveFileFormat.VSDX); // ExEnd:SetVisioProperties }
public static void Run() { // ExStart:SettingCellsInEventSection // The path to the documents directory. string dataDir = RunExamples.GetDataDir_EventSection(); // Load diagram Diagram diagram = new Diagram(dataDir + "TestTemplate.vsdm"); // Get page Aspose.Diagram.Page page = diagram.Pages.GetPage(0); // Get shape id long shapeId = page.AddShape(3.0, 3.0, 0.36, 0.36, "Square"); // Get shape Aspose.Diagram.Shape shape = page.Shapes.GetShape(shapeId); // Set event cells in the ShapeSheet shape.Event.EventXFMod.Ufe.F = "CALLTHIS(\"ThisDocument.ShowAlert\")"; shape.Event.EventDblClick.Ufe.F = "CALLTHIS(\"ThisDocument.ShowAlert\")"; shape.Event.EventDrop.Ufe.F = "CALLTHIS(\"ThisDocument.ShowAlert\")"; shape.Event.EventMultiDrop.Ufe.F = "CALLTHIS(\"ThisDocument.ShowAlert\")"; shape.Event.TheText.Ufe.F = "CALLTHIS(\"ThisDocument.ShowAlert\")"; shape.Event.TheData.Ufe.F = "CALLTHIS(\"ThisDocument.ShowAlert\")"; // Save diagram diagram.Save(dataDir + "SettingCellsInEventSection_out.vsdm", SaveFileFormat.VSDM); // ExEnd:SettingCellsInEventSection }
/// <summary> /// Gets the modified end target of the wire. /// </summary> /// <returns></returns> public IWiringEnd GetModifiedWireEndTarget(WireJoint startJoint, Diagram endDiagram, ref DiagramPoint endPoint, IWiringEnd originalWireEndTarget) { return(originalWireEndTarget); }
public override void SetupDiagram(Diagram diagram) { base.SetupDiagram(diagram); if (diagram is not RadarDiagram diagramRadar) { return; } if (!string.IsNullOrWhiteSpace(DiagramBackColor)) { var backColor = Utils.ColorFromString(DiagramBackColor); if (backColor != Color.Empty) { diagramRadar.BackColor = backColor; } } if (!string.IsNullOrWhiteSpace(DiagramBorderColor)) { var borderColor = Utils.ColorFromString(DiagramBorderColor); if (borderColor != Color.Empty) { diagramRadar.BorderVisible = true; diagramRadar.BorderColor = borderColor; } } if (DiagramFillMode.HasValue) { diagramRadar.FillStyle.FillMode = DiagramFillMode.Value; switch (DiagramFillMode.Value) { case DevExpress.XtraCharts.FillMode.Empty: break; case DevExpress.XtraCharts.FillMode.Solid: var backColor = Utils.ColorFromString(DiagramBackColor); if (backColor != Color.Empty) { diagramRadar.BackColor = backColor; } break; case DevExpress.XtraCharts.FillMode.Gradient: if (diagramRadar.FillStyle.Options is RectangleGradientFillOptions gradientOptions) { var backColor2 = Utils.ColorFromString(DiagramBackColor2); if (backColor2 != Color.Empty) { gradientOptions.Color2 = backColor2; } if (DiagramFillGradientMode.HasValue) { gradientOptions.GradientMode = DiagramFillGradientMode.Value; } } break; case DevExpress.XtraCharts.FillMode.Hatch: if (diagramRadar.FillStyle.Options is HatchFillOptions hatchOptions) { var backColor2 = Utils.ColorFromString(DiagramBackColor2); if (backColor2 != Color.Empty) { hatchOptions.Color2 = backColor2; } if (DiagramFillHatchStyle.HasValue) { hatchOptions.HatchStyle = DiagramFillHatchStyle.Value; } } break; } } if (Margins != null && Margins.Length == 1) { diagramRadar.Margins.All = Margins[0]; } else if (Margins != null && Margins.Length == 4) { diagramRadar.Margins.Left = Margins[0]; diagramRadar.Margins.Top = Margins[1]; diagramRadar.Margins.Right = Margins[2]; diagramRadar.Margins.Bottom = Margins[3]; } if (RotationDirection.HasValue) { diagramRadar.RotationDirection = RotationDirection.Value; } if (StartAngleInDegrees.HasValue) { diagramRadar.StartAngleInDegrees = StartAngleInDegrees.Value; } if (!string.IsNullOrWhiteSpace(DiagramShadowColor)) { var shadowColor = Utils.ColorFromString(DiagramShadowColor); if (shadowColor != Color.Empty) { diagramRadar.Shadow.Visible = true; diagramRadar.Shadow.Color = shadowColor; } } if (DiagramShadowSize.HasValue) { diagramRadar.Shadow.Size = DiagramShadowSize.Value; diagramRadar.Shadow.Visible = true; } }
/// <summary> /// This tool can run when the diagram supports inserting nodes, /// the model is modifiable, and there is a click (or a double-click /// if <see cref="DoubleClick"/> is true). /// </summary> /// <returns></returns> /// <remarks> /// <see cref="PrototypeData"/> must be non-null, too. /// </remarks> public override bool CanStart() { if (!base.CanStart()) { return(false); } // gotta have some node data that can be copied if (this.PrototypeData == null) { return(false); } Diagram diagram = this.Diagram; // heed IsReadOnly & AllowInsert if (diagram == null || diagram.IsReadOnly) { return(false); } if (!diagram.AllowInsert) { return(false); } // make sure the model permits adding stuff IDiagramModel model = diagram.Model; if (model == null || !model.Modifiable) { return(false); } // only works with the left button if (!IsLeftButtonDown()) { return(false); } // the mouse down point needs to be near the mouse up point if (IsBeyondDragSize()) { return(false); } // maybe requires double-click; otherwise avoid accidental double-create if (this.DoubleClick != IsDoubleClick()) { return(false); } // don't include the following check when this tool is running modally if (diagram.CurrentTool != this) { // only operates in the background, not on some Part Part part = FindPartAt(diagram.LastMousePointInModel, false); if (part != null) { return(false); } } return(true); }
/// <summary> /// Import a Visual Studio Project. /// </summary> private void ImportVisualStudioProject(Diagram diagram, ImportSettings settings, string fileName) { // TO DO }
// ======================================================================== // Methods #region === Methods /// <summary> /// Starts the functionality of the plugin. /// </summary> protected void Launch() { if (Workspace.HasActiveProject) { var settings = new ImportSettings(); using (var settingsForm = new ImportSettingsForm(settings)) { if (settingsForm.ShowDialog() == DialogResult.OK) { var diagram = new Diagram(CSharpLanguage.Instance); // Is it a file or a folder? foreach (var item in settings.Items) { // Analyse items to know if it is : // a C# source file // a folder // a .NET assembly if (Path.HasExtension(item)) { switch (Path.GetExtension(item)) { case ".cs": if (File.Exists(item)) { if (settings.NewDiagram) { diagram = new Diagram(CSharpLanguage.Instance); } ImportCSharpFile(diagram, settings, item); } break; case ".dll": case ".exe": if (File.Exists(item)) { if (settings.NewDiagram) { diagram = new Diagram(CSharpLanguage.Instance); } ImportAssembly(diagram, settings, item); } break; case ".sln": if (File.Exists(item)) { if (settings.NewDiagram) { diagram = new Diagram(CSharpLanguage.Instance); } ImportVisualStudioSolution(diagram, settings, item); } break; case ".csproj": if (File.Exists(item)) { if (settings.NewDiagram) { diagram = new Diagram(CSharpLanguage.Instance); } ImportVisualStudioProject(diagram, settings, item); } break; default: // unknow extension break; } } else { if (Directory.Exists(item)) { ImportFolder(diagram, settings, item); } } } } } } }
public Task <DiagramViewModel> GetDiagramViewModelAsync(Guid id) { var dumas = new Author() { Name = "Alexandre Dumas" }; var edmond = new Character() { Name = "Edmond Dantés" }; edmond.Aliases.Add(new Alias() { Name = "Count of Monte Christo" }); edmond.Aliases.Add(new Alias() { Name = "Sinbad the Sailor" }); edmond.Aliases.Add(new Alias() { Name = "Abbé Busoni" }); edmond.Aliases.Add(new Alias() { Name = "Lord Wilmore" }); edmond.Authors.Add(dumas); var louis = new Character() { Name = "Louis Dantés" }; louis.Authors.Add(dumas); var mercedes = new Character() { Name = "Mercédès" }; mercedes.Aliases.Add(new Alias() { Name = "Countess Mercédès Mondego" }); mercedes.Aliases.Add(new Alias() { Name = "Mlle de Morcerf" }); mercedes.Authors.Add(dumas); var fernand = new Character { Name = "Fernand Mondego" }; fernand.Aliases.Add(new Alias() { Name = "Count de Morcerf" }); fernand.Authors.Add(dumas); var albert = new Character { Name = "Albert de Morcerf" }; albert.Authors.Add(dumas); var haydee = new Character { Name = "Haydée" }; haydee.Authors.Add(dumas); edmond.RelateTo(louis, "son of", true); edmond.RelateTo(mercedes, "engaged"); edmond.RelateTo(haydee, "owns", true); edmond.RelateTo(haydee, "loves"); mercedes.RelateTo(fernand, "married"); mercedes.RelateTo(albert, "mother of", true); fernand.RelateTo(albert, "father of", true); albert.RelateTo(edmond, "challenges to a duel", true); haydee.RelateTo(fernand, "exposes", true); var betrayal = new Storyline() { Name = "The Betrayal of Ali Pasha", Description = "Lorem Ipsum etc.", }; betrayal.Authors.Add(dumas); betrayal.Characters.Add(fernand); betrayal.Characters.Add(haydee); var haydeesIdentity = new PlotElement() { Name = "Haydée is Ali Pasha's daughter", Description = "Ali Pasha's daughter was sold into slavery and, after the death of her mother, the only surviving person to know of Ali's betrayer." }; haydeesIdentity.OwningCharacters.Add(haydee); var alisBetrayer = new PlotElement() { Name = "Fernand betrayed and murdered Ali Pasha.", Description = "Fernand was the officer who betrayed and murdered Ali Pasha. If this became public, it would cause a scandal." }; alisBetrayer.OwningCharacters.Add(fernand); alisBetrayer.NeedingCharacters.Add(haydee); betrayal.PlotElements.Add(haydeesIdentity); betrayal.PlotElements.Add(alisBetrayer); var diagram = new Diagram() { Name = "The Count of Monte Cristo" }; diagram.Characters.Add(edmond); diagram.Characters.Add(louis); diagram.Characters.Add(mercedes); diagram.Characters.Add(fernand); diagram.Characters.Add(albert); diagram.Characters.Add(haydee); diagram.Authors.Add(dumas); diagram.Storylines.Add(betrayal); diagram.PlotElements.Add(alisBetrayer); diagram.PlotElements.Add(haydeesIdentity); return(Task.FromResult(new DiagramViewModel(diagram))); }
public static void Extract(XmlElement root, ref Elements allElements, ref Diagram diagram) { // Id, type, box List <Tuple <string, string, BoundingBox> > graphicInfo = new List <Tuple <string, string, BoundingBox> >(); if (diagram.Image != null) { var(realMinX, realMinY) = (30, 30); var minX = 10000; var minY = 10000; // Для отрисовки на png var graphics = root.GetElementsByTagName("plane"); var graphicsCount = graphics.Count; for (var i = 0; i < graphicsCount; i++) { try { var curContent = graphics[i]; var parentNode = curContent.ParentNode; if (parentNode.Attributes["xsi:type"].Value != "com.genmymodel.graphic.uml:ClassDiagram") { continue; } var graphicElements = curContent.SelectNodes("ownedDiagramElements"); var graphicElementsCount = graphicElements.Count; for (var j = 0; j < graphicElementsCount; j++) { var curElement = graphicElements[j]; var elementType = curElement.Attributes["xsi:type"].Value; var elementId = ""; if (curElement.Attributes["modelElement"] != null) { elementId = curElement.Attributes["modelElement"].Value; } var curX = 0; var curY = 0; if (curElement.Attributes["x"] != null) { curX = int.Parse(curElement.Attributes["x"].Value); } if (curElement.Attributes["y"] != null) { curY = int.Parse(curElement.Attributes["y"].Value); } // Для нормировки if (curX < minX) { minX = curX; } if (curY < minY) { minY = curY; } var curW = 0; var curH = 0; var isVisible = false; if (curElement.Attributes["width"] != null) { curW = int.Parse(curElement.Attributes["width"].Value); isVisible = true; } if (curElement.Attributes["height"] != null) { curH = int.Parse(curElement.Attributes["height"].Value); isVisible = true; } if (!isVisible) { continue; } var bbox = new BoundingBox(curX, curY, curW, curH); var item = new Tuple <string, string, BoundingBox>(elementId, elementType, bbox); graphicInfo.Add(item); } } catch (Exception ex) { Main.MainFormInstance.Invoke(new Action(() => { MessageBox.Show("Ошибка", "Ошибка в экспорте координат элементов: " + ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Error); })); } } // Нормировка for (var i = 0; i < graphicInfo.Count; i++) { var offsetX = realMinX - minX; var offsetY = realMinY - minY; graphicInfo[i].Item3.X += offsetX; graphicInfo[i].Item3.Y += offsetY; } } else { isThereImage = false; } // Сами элементы диаграммы var xmlElements = root.GetElementsByTagName("packagedElement"); var elementsCount = xmlElements.Count; for (var i = 0; i < elementsCount; i++) { try { var curElement = xmlElements[i]; var elementType = curElement.Attributes["xsi:type"].Value; var elementId = curElement.Attributes["xmi:id"].Value; var nameAttribute = curElement.Attributes["name"]; var elementName = nameAttribute != null ? nameAttribute.Value : ""; switch (elementType) { case "uml:Package": var elementGraphicInfo = graphicInfo.Find(a => a.Item1 == elementId && a.Item2 == "com.genmymodel.graphic.uml:PackageWidget"); if (elementGraphicInfo == null && isThereImage) { break; } var box = elementGraphicInfo?.Item3; allElements.Packages.Add(new Package(elementId, elementName, box)); break; case "uml:Class": case "uml:Interface": var xsiType = "com.genmymodel.graphic.uml:ClassWidget"; var russianName = "Класс"; var isInterface = false; if (elementType == "uml:Interface") { xsiType = "com.genmymodel.graphic.uml:InterfaceWidget"; russianName = "Интерфейс"; isInterface = true; } elementGraphicInfo = graphicInfo.Find(a => a.Item1 == elementId && a.Item2 == xsiType); if (elementGraphicInfo == null && isThereImage) { break; } box = elementGraphicInfo?.Item3; var attributes = new List <Attribute>(); var operations = new List <Operation>(); // Считываем атрибуты var attributeElements = curElement.SelectNodes("ownedAttribute"); var attribElementsCount = attributeElements.Count; for (var k = 0; k < attribElementsCount; k++) { var curAttrib = attributeElements[k]; var attribId = curAttrib.Attributes["xmi:id"].Value; var attribName = curAttrib.Attributes["name"].Value; var attribVisibility = Visibility.none; if (curAttrib.Attributes["visibility"] != null) { attribVisibility = (Visibility)Enum.Parse(typeof(Visibility), curAttrib.Attributes["visibility"].Value, true); } var attribDataTypeId = GetDataType(curAttrib, box, ref diagram); attributes.Add(new Attribute(attribId, attribName, attribVisibility, attribDataTypeId)); } // Считываем операции var operationElements = curElement.SelectNodes("ownedOperation"); var operationElementsCount = operationElements.Count; for (var k = 0; k < operationElementsCount; k++) { var curOperation = operationElements[k]; var operationId = curOperation.Attributes["xmi:id"].Value; var operationName = curOperation.Attributes["name"].Value; var returnDataTypeId = ""; var parameters = new List <Parameter>(); var parametersElements = curOperation.SelectNodes("ownedParameter"); var parametersCount = parametersElements.Count; for (var t = 0; t < parametersCount; t++) { var curParameter = parametersElements[t]; var paramId = curParameter.Attributes["xmi:id"].Value; var paramName = curParameter.Attributes["name"].Value; // Для возвращаемого значения операции if (curParameter.Attributes["direction"] != null && curParameter.Attributes["direction"].Value == "return") { returnDataTypeId = GetDataType(curParameter, box, ref diagram); } else { // Обычный параметр var paramDataType = GetDataType(curParameter, box, ref diagram); parameters.Add(new Parameter(paramId, paramName, paramDataType)); } } var operationVisibility = Visibility.@public; if (curOperation.Attributes["visibility"] != null) { operationVisibility = (Visibility)Enum.Parse(typeof(Visibility), curOperation.Attributes["visibility"].Value, true); } operations.Add(new Operation(operationId, operationName, parameters, operationVisibility, returnDataTypeId)); } // Смотрим обобщение (наследование) var generalClassesIdxs = new List <string>(); var generalizationElements = curElement.SelectNodes("generalization"); var genElementsCount = generalizationElements.Count; for (var k = 0; k < genElementsCount; k++) { var curGeneralization = generalizationElements[k]; generalClassesIdxs.Add(curGeneralization.Attributes["general"].Value); } // Смотрим интерфейсы var interfaceSuppliersIdxs = new List <string>(); var interfaceElements = curElement.SelectNodes("interfaceRealization"); var interfaceElementsCount = interfaceElements.Count; for (var k = 0; k < interfaceElementsCount; k++) { var curRealization = interfaceElements[k]; interfaceSuppliersIdxs.Add(curRealization.Attributes["supplier"].Value); } var newClass = new Class(elementId, elementName, box, attributes, operations, generalClassesIdxs, isInterface, interfaceSuppliersIdxs); // Проверим на дублирование var isExist = allElements.Classes.Exists(a => a.Name == elementName); if (isExist) { diagram.Mistakes.Add(new Mistake(2, $"{russianName} с таким именем уже существует", box, ALL_MISTAKES.CD_DUPLICATE_NAME)); break; } allElements.Classes.Add(newClass); break; case "uml:Association": string[] navigableEndIdxs = null; if (curElement.Attributes["navigableOwnedEnd"] != null) { navigableEndIdxs = curElement.Attributes["navigableOwnedEnd"].Value.Split(' '); } var ownedEnds = curElement.SelectNodes("ownedEnd"); string ownedElementId1 = "", role1 = "", mult1 = "", ownedElementId2 = "", role2 = "", mult2 = ""; BoundingBox box1 = null, box2 = null; bool navigalable1 = false, navigalable2 = false; ConnectionType connType1 = ConnectionType.Association, connType2 = ConnectionType.Association; // Смотрим каждый из концов связи for (var j = 0; j < 2; j++) { var curOwnedEnd = ownedEnds[j]; var curOwnedEndId = curOwnedEnd.Attributes["xmi:id"].Value; string curRole = ""; if (curOwnedEnd.Attributes["name"] != null) { curRole = curOwnedEnd.Attributes["name"].Value; } // id элемента, к которому идет данная связь var curOwnedElementId = curOwnedEnd.Attributes["type"].Value; var curConnectionType = ConnectionType.Association; if (curOwnedEnd.Attributes["aggregation"] != null) { curConnectionType = (ConnectionType)Array.IndexOf(ReservedNames.ConnectionTypes, curOwnedEnd.Attributes["aggregation"].Value); } var curNavigation = false; if (navigableEndIdxs != null) { curNavigation = navigableEndIdxs.Contains(curOwnedEndId); } var curLowerValue = "0"; if (curOwnedEnd.SelectSingleNode("lowerValue").Attributes["value"] != null) { curLowerValue = curOwnedEnd.SelectSingleNode("lowerValue").Attributes["value"].Value; } var curUpperValue = curOwnedEnd.SelectSingleNode("upperValue").Attributes["value"].Value; var curMult = curLowerValue + ".." + curUpperValue; elementGraphicInfo = graphicInfo.Find(a => a.Item1 == curOwnedEndId && a.Item2 == "com.genmymodel.graphic.uml:MemberEndMultiplicityWidget"); var curBox = elementGraphicInfo?.Item3; if (j == 0) { ownedElementId1 = curOwnedElementId; role1 = curRole; mult1 = curMult; box1 = curBox; navigalable1 = curNavigation; connType1 = curConnectionType; } else { ownedElementId2 = curOwnedElementId; role2 = curRole; mult2 = curMult; box2 = curBox; navigalable2 = curNavigation; connType2 = curConnectionType; } } allElements.Connections.Add(new Connection(elementId, elementName, ownedElementId1, role1, mult1, box1, navigalable1, connType1, ownedElementId2, role2, mult2, box2, navigalable2, connType2)); break; case "uml:DataType": allElements.Types.Add(new DataType(elementId, elementName)); break; case "uml:Usage": var clientId = curElement.Attributes["client"].Value; var supplierId = curElement.Attributes["supplier"].Value; allElements.Dependences.Add(new Dependence(elementId, "use", clientId, supplierId, DependenceType.Usage)); break; case "uml:Dependency": clientId = curElement.Attributes["client"].Value; supplierId = curElement.Attributes["supplier"].Value; allElements.Dependences.Add(new Dependence(elementId, elementName, clientId, supplierId, DependenceType.Dependency)); break; case "uml:Enumeration": elementGraphicInfo = graphicInfo.Find(a => a.Item1 == elementId && a.Item2 == "com.genmymodel.graphic.uml:EnumerationWidget"); if (elementGraphicInfo == null && isThereImage) { break; } box = elementGraphicInfo?.Item3; var literals = new List <Literal>(); var literalElements = curElement.SelectNodes("ownedLiteral"); var literalElementsCount = literalElements.Count; for (var k = 0; k < literalElementsCount; k++) { var curLiteral = literalElements[k]; var literalId = curLiteral.Attributes["xmi:id"].Value; var literalName = curLiteral.Attributes["name"].Value; literals.Add(new Literal(literalId, literalName)); } // Проверим на дублирование isExist = allElements.Enumerations.Exists(a => a.Name == elementName); if (isExist) { diagram.Mistakes.Add(new Mistake(2, "Перечисление с таким именем уже существует", box, ALL_MISTAKES.CD_DUPLICATE_NAME)); break; } allElements.Enumerations.Add(new Enumeration(elementId, elementName, box, literals)); break; default: elementGraphicInfo = graphicInfo.Find(a => a.Item1 == elementId); if (elementGraphicInfo == null && isThereImage) { break; } box = elementGraphicInfo.Item3; diagram.Mistakes.Add(new Mistake(2, "Недопустимый элемент", box, ALL_MISTAKES.CD_IMPOSSIBLE_ELEMENT)); break; } } catch (Exception ex) { Main.MainFormInstance.Invoke(new Action(() => { MessageBox.Show("Ошибка", "Ошибка в экспорте элементов: " + ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Error); })); } } // Проверяем комментарии (ограничения) var xmlComments = root.GetElementsByTagName("ownedComment"); var commentsCount = xmlComments.Count; for (var i = 0; i < commentsCount; i++) { try { var curComment = xmlComments[i]; var commentId = curComment.Attributes["xmi:id"].Value; var elementGraphicInfo = graphicInfo.Find(a => a.Item1 == commentId); if (elementGraphicInfo == null && isThereImage) { break; } var box = elementGraphicInfo?.Item3; var annotatedElementId = ""; if (curComment.Attributes["annotatedElement"] != null) { annotatedElementId = curComment.Attributes["annotatedElement"].Value; } var body = ""; if (curComment.Attributes["body"] != null) { body = curComment.Attributes["body"].Value.TrimStart().TrimEnd(); } allElements.Comments.Add(new Comment(commentId, body, box, annotatedElementId)); } catch (Exception ex) { Main.MainFormInstance.Invoke(new Action(() => { MessageBox.Show("Ошибка", "Ошибка в экспорте комментариев: " + ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Error); })); } } }
public Controller(Diagram d) { this.Diagram = d; }
/// <summary> /// Detects whether the shape element is present and visible on the indicated diagram, or on the current diagram if none is passed /// </summary> /// <param name="shapeElement">ShapeElement to find</param> /// <param name="diagram">Diagram to interrogate</param> /// <returns>True if found, false otherwise</returns> internal static bool IsVisible(this ShapeElement shapeElement, Diagram diagram = null) { Diagram targetDiagram = diagram ?? EFModel.ModelRoot.GetCurrentDiagram(); return(targetDiagram != null && shapeElement.Diagram == targetDiagram && shapeElement.IsVisible); }
protected PositionableElementViewHelper(Diagram diagram) : base(diagram) { }
/// <inheritdoc /> public override BorderNode MakeDefaultBorderNode(Diagram startDiagram, Diagram endDiagram, Wire wire, StructureIntersection intersection) { return(MakeBorderNode <LoopTunnel>()); }
/// <summary> /// Detects whether the model element has a visible shape on the indicated diagram, or on the current diagram if none is passed /// </summary> /// <param name="modelElement">ModelElement represented by the shape in question</param> /// <param name="diagram">Diagram to interrogate</param> /// <returns>True if found, false otherwise</returns> internal static bool IsVisible(this ModelElement modelElement, Diagram diagram = null) { return(modelElement.GetShapeElement(diagram)?.IsVisible(diagram) == true); }
public void Compile() { //| x1 y2 x2 y1 | //|--+--[ ]--[OSR]--[/]--+--[/]----( )--| //| | y1 | | //| +--[ ]--------------+ | //| | //| x2 y1 x1 y2 | //|--+--[ ]--[OSR]--[/]--+--[/]----( )--| //| | y2 | | //| +--[ ]--------------+ | Diagram TestDiagram = new Diagram(); TestDiagram.MasterRelay = true; #region Declare Components Rung Rung1 = new Rung(); Rung Rung2 = new Rung(); var Y1 = new Coil(); Y1.Name = "1"; var Y2 = new Coil(); Y2.Name = "2"; var X1 = new Contact(); X1.Name = "1"; var X1I = new Contact(); X1I.Name = "1"; X1I.IsInverted = true; var X2 = new Contact(); X2.Name = "2"; var X2I = new Contact(); X2I.Name = "2"; X2I.IsInverted = true; var Y1C = new Contact(); Y1C.Name = "1"; Y1C.Type = Contact.ContactType.OutputPin; var Y1CI = new Contact(); Y1CI.Name = "1"; Y1CI.Type = Contact.ContactType.OutputPin; Y1CI.IsInverted = true; var Y2C = new Contact(); Y2C.Name = "2"; Y2C.Type = Contact.ContactType.OutputPin; var Y2CI = new Contact(); Y2CI.Name = "2"; Y2CI.Type = Contact.ContactType.OutputPin; Y2CI.IsInverted = true; #endregion Declare Components #region Build Circuit Rung1.Add(Y1); Rung1.InsertBefore(X2I, Y1); Rung1.Add(X1); Rung1.InsertUnder(Y1C, X1); Rung1.InsertAfter(Y2CI, X1); Rung1.InsertBefore(new OSR(), Y2CI); TestDiagram.Add(Rung1); Rung2.Add(Y2); //ELF elf = new ELF(); //elf.Name = "test"; //elf.Code = "int a = 10;"; //Rung2.Add(elf); Rung2.InsertBefore(X1I, Y2); Rung2.Add(X2); Rung2.InsertUnder(Y2C, X2); Rung2.InsertAfter(Y1CI, X2); Rung2.InsertBefore(new OSR(), Y1CI); TestDiagram.InsertUnder(Rung2, Rung1); #endregion Build Circuit TestDiagram.RefreshPins(); TestDiagram.Pins[0].Pin = "3"; TestDiagram.Pins[1].Pin = "9"; TestDiagram.Pins[2].Pin = "8"; TestDiagram.Pins[3].Pin = "4"; Console.WriteLine(); Console.Write(Compiler.DiagramCompiler.CompileDiagram(TestDiagram)); }
/// <ToBeCompleted></ToBeCompleted> public void CreateDiagram(string name) { diagram = new Diagram(name); owner.Project.Repository.Insert(diagram); Diagram = diagram; }
private UIElement GetPage(int pageNumber) { if (this.Diagram == null) { return(null); } DiagramPanel panel = this.Diagram.Panel; if (panel == null) { return(null); } int x = pageNumber % this.EffectiveColumns; int y = pageNumber / this.EffectiveColumns; Rect b = this.EffectiveBounds; Size sz = this.EffectivePageSize; Rect viewb = new Rect(b.X + x * sz.Width, b.Y + y * sz.Height, Math.Min(sz.Width, Math.Max(1, b.Width - x * sz.Width)), Math.Min(sz.Height, Math.Max(1, b.Height - y * sz.Height))); double sc = this.EffectiveScale; Size pixsz = new Size(viewb.Width * sc, viewb.Height * sc); DiagramPanel ppanel = panel.GrabPrintingPanel(viewb, sc, this.PartsToPrint); Thickness th = this.Margin; if (Double.IsNaN(th.Left) || th.Left > pixsz.Width / 2) { th.Left = Math.Min(50, pixsz.Width / 2); } if (Double.IsNaN(th.Top) || th.Top > pixsz.Height / 2) { th.Top = Math.Min(50, pixsz.Height / 2); } PrintManager.PageInfo info = new PrintManager.PageInfo() { Diagram = this.Diagram, Index = pageNumber + 1, Count = this.PageCount, Column = x + 1, ColumnCount = this.EffectiveColumns, Row = y + 1, RowCount = this.EffectiveRows, TotalBounds = this.EffectiveBounds, ViewportBounds = viewb, Scale = sc, Size = this.PageSize, Viewport = new Rect(th.Left, th.Top, pixsz.Width, pixsz.Height) }; Canvas root = new Canvas(); Diagram diagram = this.Diagram; if (diagram != null && (this.PageOptions & PrintPageOptions.Background) != 0) { root.Background = diagram.Background; } DataTemplate backtemplate = this.BackgroundTemplate; if (backtemplate != null) { ContentPresenter back = new ContentPresenter(); back.Content = info; back.ContentTemplate = backtemplate; Canvas.SetLeft(back, th.Left); Canvas.SetTop(back, th.Top); root.Children.Add(back); } if (diagram != null && diagram.GridVisible && diagram.GridPattern != null && (this.PageOptions & PrintPageOptions.Grid) != 0) { GridPattern grid = diagram.GridPattern; grid.DoUpdateBackgroundGrid(panel, new Rect(viewb.X, viewb.Y, sz.Width, sz.Height), sc, false); grid.Width = viewb.Width; grid.Height = viewb.Height; Canvas.SetLeft(grid, th.Left); Canvas.SetTop(grid, th.Top); root.Children.Add(grid); } // instead of ppanel.UpdateScrollTransform(new Point(viewb.X, viewb.Y), sc, pixsz, false): var tg = new System.Windows.Media.TransformGroup(); tg.Children.Add(new System.Windows.Media.TranslateTransform() { X = -viewb.X, Y = -viewb.Y }); tg.Children.Add(new System.Windows.Media.ScaleTransform() { ScaleX = sc, ScaleY = sc }); ppanel.RenderTransform = tg; // clip foreach (UIElement lay in ppanel.Children) { lay.Clip = new System.Windows.Media.RectangleGeometry() { Rect = new Rect(viewb.X, viewb.Y, pixsz.Width / sc, pixsz.Height / sc) }; } Canvas.SetLeft(ppanel, th.Left); Canvas.SetTop(ppanel, th.Top); root.Children.Add(ppanel); DataTemplate foretemplate = this.ForegroundTemplate; if (foretemplate != null) { ContentPresenter fore = new ContentPresenter(); fore.Content = info; fore.ContentTemplate = foretemplate; Canvas.SetLeft(fore, th.Left); Canvas.SetTop(fore, th.Top); root.Children.Add(fore); } root.Measure(this.PageSize); root.Arrange(new Rect(0, 0, this.PageSize.Width, this.PageSize.Height)); return(root); }
public SelectionBehavior(Diagram diagram) : base(diagram) { Diagram.MouseDown += OnMouseDown; Diagram.TouchStart += OnTouchStart; }
/// <summary> /// Adds the <see cref="Diagram"/> specified by <paramref name="diagram"/> to this <see cref="MultiDiagramDocView"/>. /// </summary> /// <param name="diagram">The <see cref="Diagram"/> to be added to this <see cref="MultiDiagramDocView"/>.</param> public void AddDiagram(Diagram diagram) { AddDiagram(diagram, false); }
/// <summary> /// Create a default <see cref="PrintManager"/>. /// </summary> public PrintManager() { this.ForegroundTemplate = Diagram.FindDefault <DataTemplate>("DefaultPrintManagerForegroundTemplate"); }
public virtual void ValidateMenuItems(Diagram diagram) { this.diagram = diagram; }
/// <see cref="IDiagramEditor.SaveAsync"/> public Task SaveAsync() { _autoSaveTimer.TryStop(); if (_saveExecuting) { return(Tasks.FromSuccess()); } _saveExecuting = true; IsIdle = false; CancelRefreshes(); // PlantUML seems to have a problem detecting encoding if the // first line is not an empty line. if (!Char.IsWhiteSpace(CodeEditor.Content, 0)) { CodeEditor.Content = Environment.NewLine + CodeEditor.Content; } Diagram.Content = CodeEditor.Content; Diagram.TryDeduceImageFile(); // Create a backup if this is the first time the diagram being modified // after opening. bool makeBackup = false; if (_firstSaveAfterOpen) { makeBackup = true; _firstSaveAfterOpen = false; } var progress = _notifications.StartProgress(false); progress.Report(new ProgressUpdate { PercentComplete = 100, Message = String.Format(CultureInfo.CurrentCulture, Resources.Progress_SavingDiagram, Diagram.File.Name) }); var saveTask = _diagramIO.SaveAsync(Diagram, makeBackup) .Then(() => _compiler.CompileToFileAsync(Diagram.File, ImageFormat)); saveTask.ContinueWith(t => { if (t.IsFaulted && t.Exception != null) { progress.Report(ProgressUpdate.Failed(t.Exception.InnerException)); } else if (!t.IsCanceled) { DiagramImage = _diagramRenderers[ImageFormat].Render(Diagram); Diagram.ImageFormat = ImageFormat; CodeEditor.IsModified = false; progress.Report(ProgressUpdate.Completed(Resources.Progress_DiagramSaved)); OnSaved(); } _saveExecuting = false; IsIdle = true; _refreshTimer.TryStop(); }, CancellationToken.None, TaskContinuationOptions.None, _uiScheduler); return(saveTask); }
protected internal override IEnumerable <ToolStripItem> GetContextMenuItems(Diagram diagram) { return(AssociationContextMenu.Default.GetMenuItems(diagram)); }
/// <summary> /// This basically just sets the value of <see cref="Northwoods.GoXam.Node.Position"/>, /// but with animated movement. /// </summary> /// <param name="node"></param> /// <param name="newpos">a new position in model coordinates</param> /// <remarks> /// There is no animation if <see cref="Animated"/> is false, /// if the <see cref="AnimationTime"/> is very small, or /// if the original position and the new position are very near to each other /// or offscreen. /// </remarks> public void MoveAnimated(Node node, Point newpos) { if (node == null) { return; } VerifyAccess(); Point oldloc = node.Location; Rect oldb = node.Bounds; //Diagram.Debug("LayoutManager.MoveAnimated: " + Diagram.Str(node) + " " + Diagram.Str(node.Position) + " -- > " + Diagram.Str(newpos)); // always move the node node.Position = newpos; if (this.Story != null) { // if MoveAnimated is called more than once for a Node, remove any previous saved animation PointAnimation anim = null; if (this.Animations.TryGetValue(node, out anim)) { //Diagram.Debug(" removed animation for " + node.ToString()); this.Story.Children.Remove(anim); } } // try not to bother with animations that won't be visibly useful if (!this.Animated) { return; } if (this.AnimationTime <= 10) { return; } // two pixels or more (but that's in model coordinates) if (Math.Abs(newpos.X - oldb.X) < 2 && Math.Abs(newpos.Y - oldb.Y) < 2) { return; } FrameworkElement elt = node.VisualElement; if (elt == null) { return; } // only do animation for nodes whose new or old bounds are visible in the view //?? this doesn't work reliably: Diagram diagram = this.Diagram; if (diagram == null || diagram.Panel == null) { return; } Rect nearRect = diagram.Panel.InflatedViewportBounds; Rect newb = new Rect(newpos.X, newpos.Y, oldb.Width, oldb.Height); if (!Geo.Intersects(nearRect, oldb) && !Geo.Intersects(nearRect, newb)) { return; } // start an animation //Diagram.Debug(" MoveAnimated " + Diagram.Str(new Point(oldb.X, oldb.Y)) + Diagram.Str(node.Position)); if (Double.IsNaN(oldloc.X)) { oldloc.X = this.DefaultLocation.X; } if (Double.IsNaN(oldloc.Y)) { oldloc.Y = this.DefaultLocation.Y; } PointAnimation a = new PointAnimation(); a.From = oldloc; a.Duration = this.AnimationDuration; Storyboard.SetTarget(a, elt); Storyboard.SetTargetProperty(a, new PropertyPath(Node.LocationProperty)); Storyboard story = this.Story; if (story == null) // when called from outside of DoLayoutDiagram { Storyboard singlestory = new Storyboard(); singlestory.Children.Add(a); StartStoryboard(singlestory); } else { StartingLayoutAnimation(); story.Children.Add(a); // collect animations for later action, all at once this.Animations[node] = a; } }
protected override bool CloneEntity(Diagram diagram) { return(diagram.InsertEnum(EnumType.Clone())); }
public PolygonManager(GraphScroller scroller) { this.scroller = scroller; diagram = scroller.Diagram; }
public override void ValidateMenuItems(Diagram diagram) { base.ValidateMenuItems(diagram); mnuCut.Enabled = diagram.CanCutToClipboard; mnuCopy.Enabled = diagram.CanCopyToClipboard; }
/// <summary> /// Reparents the joints and get joints to connect. /// </summary> /// <param name="jointsInNewParent">The joints in new parent.</param> /// <param name="existingWire">The existing wire.</param> /// <param name="diagramToReparentTo">The diagram to reparent to.</param> /// <param name="commonJointInOldWire">The common joint in old wire.</param> /// <param name="commonJointInNewWire">The common joint in new wire.</param> public void ReparentJointsAndGetJointsToConnect(IEnumerable <WireJoint> jointsInNewParent, Wire existingWire, Diagram diagramToReparentTo, IWireShapingContext shapingContext, out WireJoint commonJointInOldWire, out WireJoint commonJointInNewWire) { throw new NotImplementedException(); }
public ClassViewModel(Diagram diagram) { this.diagram = diagram; }
public ZoomBehavior(Diagram diagram) : base(diagram) { Diagram.Wheel += Diagram_Wheel; }
public ClassViewModel() { diagram = new Diagram(); }
public bool PassesThroughDiagram(Diagram diagram, DiagramPoint sibling1, DiagramPoint sibling2) { return(true); }