/// <summary>
        /// Compute possibilities of movedItem to move without overlapping any other item
        /// </summary>
        /// <param name="movedItem">Item which possibilities are created</param>
        /// <returns>Computed possibilities</returns>
        private ItemMoveability computePossibilities(DiagramItem movedItem)
        {
            if (movedItem.IsRootItem)
            {
                return(new ItemMoveability(double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity));
            }

            var container = movedItem.ContainingDiagramCanvas;

            //we have to check possibilities relative to parent!
            //so using relative position is necessary
            var currentPosition      = getPosition(movedItem);
            var currentLocalPosition = movedItem.AsLocalPosition(currentPosition);
            var span = SceneNavigator.GetSpan(movedItem, currentLocalPosition);

            var contMargin  = container.Margin;
            var upPossib    = span.Top;
            var downPossib  = container.DesiredSize.Height - span.Bottom - contMargin.Bottom - contMargin.Top;
            var rightPossib = container.DesiredSize.Width - span.Right - contMargin.Right - contMargin.Left;
            var leftPossib  = span.Left;

            return(new ItemMoveability(
                       upPossib,
                       downPossib,
                       leftPossib,
                       rightPossib
                       ));
        }
示例#2
0
        /// <summary>
        /// Get contact points defined for given item
        /// <remarks>Note that because of simple getting contact points we store them as first four</remarks>.
        /// </summary>
        /// <param name="item">Item which points are generated.</param>
        /// <returns>Generated points.</returns>
        private IEnumerable <GraphPoint> generatePoints(DiagramItem item)
        {
            var span     = SceneNavigator.GetSpan(item, item.GlobalPosition);
            var topLeft  = new GraphPoint(span.TopLeft, TopLeftCorner, item);
            var topRight = new GraphPoint(span.TopRight, TopRightCorner, item);

            var bottomLeft  = new GraphPoint(span.BottomLeft, BottomLeftCorner, item);
            var bottomRight = new GraphPoint(span.BottomRight, BottomRightCorner, item);

            topLeft.SetEdgeStatus(topRight);
            topLeft.SetEdgeStatus(bottomLeft);

            bottomRight.SetEdgeStatus(topRight);
            bottomRight.SetEdgeStatus(bottomLeft);

            var points = new List <GraphPoint>();

            points.Add(topLeft);
            points.Add(topRight);
            points.Add(bottomLeft);
            points.Add(bottomRight);

            generateConnectorPoints(item.TopConnectorDrawings, ConnectorAlign.Top, item, points);
            generateConnectorPoints(item.LeftConnectorDrawings, ConnectorAlign.Left, item, points);
            generateConnectorPoints(item.BottomConnectorDrawings, ConnectorAlign.Bottom, item, points);
            generateConnectorPoints(item.RightConnectorDrawings, ConnectorAlign.Right, item, points);

            return(points);
        }
        public override void OnMouseDown(DiagramMouseEventArgs e)
        {
            base.OnMouseDown(e);
            DiagramItem diagramItem     = e.HitDiagramItem;
            Column      referenceColumn = ResolveColumn(diagramItem);

            if (referenceColumn != null)
            {
                // See if we're dragging other columns
                DiagramItemCollection selection = e.DiagramClientView.Selection.TopLevelItems;
                Table    table           = referenceColumn.Table;
                int      count           = selection.Count;
                Column[] selectedColumns = new Column[count];
                for (int i = 0; i < count; ++i)
                {
                    Column column = ResolveColumn(selection[i]);
                    if (null == column ||
                        (column != referenceColumn && column.Table != table))
                    {
                        return;
                    }
                    selectedColumns[i] = column;
                }
                myDragSourceColumns = selectedColumns;
                myDragSourceShape   = (ColumnElementListCompartment)diagramItem.Shape;
            }
            else
            {
                myDragSourceColumns = null;
                myDragSourceShape   = null;
            }
        }
示例#4
0
        /// <summary>
        /// Create adorner which will show dragged object.
        /// </summary>
        /// <param name="item">Dragged object.</param>
        /// <param name="dragStart">Drag start in mouse relative coordinates!!</param>
        public DragAdorner(DiagramItem item, Point dragStart)
            : base(item)
        {
            Item = item;

            _dragScope = item.DiagramContext.Provider.Output;

            _dragLayer = AdornerLayer.GetAdornerLayer(_dragScope);
            _dragLayer.Add(this);

            _hint = new MouseHint(_dragScope);


            _visualBrush         = new VisualBrush(item);
            _visualBrush.Opacity = 0.5;


            _startPosition = item.GlobalPosition;
            GlobalPosition = _startPosition;

            _center = getScaledPosition(dragStart) - _startPosition;



            IsHitTestVisible            = false;
            _dragScope.PreviewDragOver += _updatePosition;
        }
示例#5
0
        public string GetVariableTooltipText(DiagramItem item)
        {
            var o    = item.Shape.ModelElement as Entity;
            var text = "Entity: " + o.Name;

            if (!string.IsNullOrEmpty(o.CodeFacade))
            {
                text += " (" + o.CodeFacade + ")";
            }
            text += Environment.NewLine;

            text += "Fields: " + o.Fields.Count + Environment.NewLine;
            var genFieldCount = o.Fields.Count(x => !x.IsGenerated);

            if (genFieldCount > 0)
            {
                text += "Generated Fields: " + genFieldCount + Environment.NewLine;
            }
            text += "Outbound Relations: " + o.RelationshipList.Count() + Environment.NewLine;
            text += "Inbound Relations: " + o.GetRelationsWhereChild().Count() + Environment.NewLine;

            if (o.Composites.Count > 0)
            {
                text += "Composites: " + o.Composites.Count + Environment.NewLine;
            }

            return(text);
        }
        /// <summary>
        /// Select minimal need and apply it recursively for all coliding items
        /// <remarks>
        /// Notice that applying same need on all recursive collisions
        /// is enough for state where no collision has been before
        /// </remarks>
        /// </summary>
        /// <param name="need"></param>
        /// <param name="itemToMove"></param>
        private bool recursiveApplyNeed(Move need, DiagramItem itemToMove)
        {
            if (!need.HasStretchableDirection)
            {
                //we have to check if need appling is allowed
                var possibilities = computePossibilities(itemToMove);
                if (!need.IsSatisfiedBy(possibilities.GetMove(need.Direction)))
                {
                    return(false);
                }
            }

            var currentPosition = getPosition(itemToMove);
            var newPosition     = need.Apply(currentPosition);

            trySetPosition(itemToMove, newPosition);

            var collidingItems = _navigator.GetItemsInCollision(itemToMove).ToArray();

            foreach (var collidingItem in collidingItems)
            {
                //for other coliding items apply same need
                var hasSuccess = recursiveApplyNeed(need, collidingItem);
                if (!hasSuccess)
                {
                    return(false);
                }
            }

            return(true);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="DirectoryCatalogDrawing" /> class.
        /// </summary>
        /// <param name="item">The item.</param>
        public DirectoryCatalogDrawing(DiagramItem item)
            : base(item)
        {
            InitializeComponent();

            DrawingTools.SetToolTip(Caption, Definition.DrawedType);
            DrawingTools.SetImage(CaptionIcon, Image);
            InstanceID.Text = Definition.ID;

            var path     = Definition.GetPropertyValue("Path");
            var fullPath = Definition.GetPropertyValue("FullPath");
            var pattern  = Definition.GetPropertyValue("Pattern");
            var error    = Definition.GetPropertyValue("Error");

            Path.Text    = path;
            Pattern.Text = pattern;

            var fullPathInfo = DrawingTools.GetHeadingText("FullPath", fullPath);

            DrawingTools.SetToolTip(PathDock, fullPath);

            //Display error message if needed
            ErrorText.Text = error;
            var hasError = error != null;

            ErrorDock.Visibility = hasError ? Visibility.Visible : Visibility.Hidden;

            Item.FillSlot(Components, Definition.Slots.First());
        }
        public override string GetToolTipText(DiagramItem item)
        {
            string fromName = this.FromShape.AccessibleName;
            string toName   = this.ToShape.AccessibleName;

            return(string.Format("Aggregate [{0}] is hierarchically a parent to [{1}]", fromName, toName));
        }
        public override string GetToolTipText(DiagramItem item)
        {
            SocketUseShape fromShape = FromShape as SocketUseShape;
            SocketShape    toShape   = ToShape as SocketShape;

            if (fromShape == null || toShape == null)
            {
                return(base.GetToolTipText(item));
            }

            SocketUse fromSocket = fromShape.ModelElement as SocketUse;
            Socket    toSocket   = toShape.ModelElement as Socket;

            if (fromShape == null || toShape == null)
            {
                return(base.GetToolTipText(item));
            }

            string name = null;

            if (toSocket.GadgeteerHardware is Mainboard)
            {
                name = ((Mainboard)toSocket.GadgeteerHardware).Name;
            }

            else if (toSocket.GadgeteerHardware is Module)
            {
                name = ((Module)toSocket.GadgeteerHardware).Name;
            }

            return(string.Format("{0} ({1}) ↔ {2} ({3})", fromSocket.Module.Name, fromSocket.Label, name, toSocket.Label));
        }
示例#10
0
        public HeatingSensorView(HeatingSensorPresenter heatingSensorPresenter)
        {
            _presenter = heatingSensorPresenter ?? throw new ArgumentNullException(nameof(heatingSensorPresenter));

            Shape             = Create();
            Shape.DataContext = _presenter;
        }
示例#11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RecursiveDrawing"/> class.
        /// </summary>
        /// <param name="item">The recursive item.</param>
        public RecursiveDrawing(DiagramItem item)
            : base(item)
        {
            BorderThickness = new Thickness(4);
            BorderBrush     = Brushes.Red;
            Background      = Brushes.LightGray;

            var warningText = new TextBlock();

            warningText.Text       = "!Circular dependency detected!";
            warningText.Foreground = Brushes.Red;
            warningText.FontSize   = 20;

            var description = new TextBlock();

            description.Text = "Instance '" + Definition.ID + "' should be displayed here.";

            var layout = new StackPanel();

            layout.Margin = new Thickness(20);
            layout.Children.Add(warningText);
            layout.Children.Add(description);

            Child = layout;
        }
示例#12
0
        /// <summary>
        /// Turn an accessibleObject into an element in the underlying model.
        /// </summary>
        /// <param name="accessibleObject">The accessible object</param>
        /// <param name="returnShape">True to return the shape object corresponding to the
        /// accessible object instead of the underlying model element. Note that you may get
        /// a shape for a parent object if the requested accessible object is drawn as part
        /// of another object and does not have its own shape (roles, internal uniqueness constraints, etc)</param>
        /// <returns>ModelElement, or null</returns>
        public ModelElement TranslateAccessibleObject(AccessibleObject accessibleObject, bool returnShape)
        {
            DiagramItem hitItem = TranslateAccessibleObjectToDiagramItem(accessibleObject, returnShape);

            if (hitItem == null)
            {
                return(null);
            }
            else if (returnShape)
            {
                return(hitItem.Shape);
            }
            else
            {
                ModelElement retVal = null;
                foreach (object element in hitItem.RepresentedElements)
                {
                    retVal = element as ModelElement;
                    break;
                }
                PresentationElement pel = retVal as PresentationElement;
                if (pel != null)
                {
                    // Resolve to a ModelElement if we don't have one already
                    retVal = pel.ModelElement;
                }
                return(retVal);
            }
        }
        public void DrawSelectionBorder(DrawingContext dc, DiagramItem item)
        {
            if (item == null)
                return;

            DrawSelectionBorder(item.Diagram, dc, item.Border);
        }
示例#14
0
        /// <summary>
        /// Return the tooltip text for the specified item
        /// </summary>
        /// <param name="item">A DiagramItem for the selected shape. This could be the shape, or a nested child shape or field.</param>
        public override string GetToolTipText(DiagramItem item)
        {
            // Work out which shape is selected - is it this ClassShape, or
            // is it one of the comparment shapes it contains?
            if (item.Shape is ElementListCompartment compartment)
            {
                // It's a compartment shape.
                // Get a list of the elements that are represented by diagram item (should be only one)
                ModelAttribute modelAttribute = compartment.GetSubFieldRepresentedElements(item.Field, item.SubField)
                                                .OfType <ModelAttribute>()
                                                .FirstOrDefault();

                if (modelAttribute != null && modelAttribute.IsForeignKeyFor != Guid.Empty)
                {
                    Association association = modelAttribute.Store.GetAll <Association>().FirstOrDefault(x => x.Id == modelAttribute.IsForeignKeyFor);

                    if (association != null)
                    {
                        return($"FK for [{association.GetDisplayText()}]");
                    }
                }
            }

            // is this the interface lollipop?
            if (item.Shape is DecoratorHostShape && item.Field?.Name == "Interface")
            {
                return(((ModelClass)ModelElement).CustomInterfaces);
            }

            return(base.GetToolTipText(item));
        }
示例#15
0
        private void ExecuteLoadDiagramCommand(object parameter)
        {
            IsBusy = true;
            DiagramItem wholeDiagramToLoad = null;

            if (SavedDiagramId == null)
            {
                messageBoxService.ShowError("You need to select a diagram to load");
                return;
            }

            Task <DiagramViewModel> task = Task.Factory.StartNew <DiagramViewModel>(() =>
            {
                //ensure that itemsToRemove is cleared ready for any new changes within a session
                itemsToRemove = new List <SelectableDesignerItemViewModelBase>();
                DiagramViewModel diagramViewModel = new DiagramViewModel();

                wholeDiagramToLoad = databaseAccessService.FetchDiagram((int)SavedDiagramId.Value);

                LoadPerstistDesignerItems(wholeDiagramToLoad, diagramViewModel);

                return(diagramViewModel);
            });

            task.ContinueWith((ant) =>
            {
                this.DiagramViewModel = ant.Result;
                IsBusy = false;
                messageBoxService.ShowInformation(string.Format("Finished loading Diagram Id : {0}", wholeDiagramToLoad.Id));
            }, TaskContinuationOptions.OnlyOnRanToCompletion);
        }
示例#16
0
        /// <summary>
        /// Try to add edge between given points if possible.
        /// </summary>
        /// <param name="fromCandidate">Point where edge should start.</param>
        /// <param name="toCandidate">Point where edge should end.</param>
        /// <param name="target">Target that is not considered to be an obstacle.</param>
        /// <param name="obstacle">Obstacle if any is present between from and to candidate, <c>null</c> otherwise.</param>
        /// <returns><c>true</c> if edge can be added, <c>false</c> otherwise.</returns>
        private bool tryAddEdge(GraphPoint fromCandidate, GraphPoint toCandidate, DiagramItem target, out DiagramItem obstacle)
        {
            obstacle = null;
            if (
                !fromCandidate.IsInAngle(toCandidate) ||
                !toCandidate.IsInAngle(fromCandidate)
                )
            {
                //edge is not possible between given points
                return(false);
            }

            if (fromCandidate.HasEdgeStatus(toCandidate))
            {
                //edge already exists or has been forbidden earlier
                return(false);
            }

            obstacle = _navigator.GetFirstObstacle(fromCandidate.Position, toCandidate.Position);
            var isEdgeValid = obstacle == null || obstacle == target;

            fromCandidate.SetEdgeStatus(toCandidate, isEdgeValid);

            return(isEdgeValid);
        }
示例#17
0
        /// <summary>
        /// Sélection des propriétes dans la compartiment list
        /// </summary>
        /// <param name="view">The view.</param>
        /// <param name="association">The association.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="properties">The properties.</param>
        private static void SelectProperties(DiagramClientView view, Association association, Entity entity,
                                             IList <Property> properties)
        {
            IList <PresentationElement> presentations = PresentationViewsSubject.GetPresentation(entity);

            Debug.Assert(presentations.Count > 0);
            Compartment compartment = ((CompartmentShape)presentations[0]).FindCompartment("Properties");

            Debug.Assert(compartment != null);
            foreach (ShapeField field in compartment.ShapeFields)
            {
                if (field is ListField)
                {
                    foreach (Property property in properties)
                    {
                        if (property != null)
                        {
                            int         index = entity.Properties.IndexOf(property);
                            DiagramItem item  = new DiagramItem(compartment, field, new ListItemSubField(index));
                            if (!view.Selection.Contains(item))
                            {
                                view.Selection.Add(item);
                            }
                        }
                    }
                    break;
                }
            }
        }
 private string GetVariableTooltipText(DiagramItem item)
 {
     // Todo: Get the description of the classifier
     //TODO - If we are over the body of the shape, display the classifier description
     return(BaseClass.Description);
     // Otherwise if this is a classifier operation, display its full text
 }
        public override string GetToolTipText(DiagramItem item)
        {
            string fromName = this.FromShape.AccessibleName;
            string toName   = this.ToShape.AccessibleName;

            return(string.Format("Projection [{0}] handles the event [{1}]", fromName, toName));
        }
示例#20
0
        // pin & unpin handling -- begin
        // ### make sure no side effect for EVAACodeSnippetShape (reference mode)
        public bool SelectUnpinedParentShape(DiagramItem item, DiagramClientView view)
        {
            if (item == null || view == null)
            {
                return(false);
            }

            // find top-most unpined predecessor
            VDWidgetShape shape     = this;
            bool          bReSelect = false;

            while ((shape.isPinned || shape is VDHoriContainerShape || shape is VDVertContainerShape) && /* avoid selecting container */
                   shape.ParentShape != null && shape.ParentShape is VDWidgetShape)
            {
                shape     = shape.ParentShape as VDWidgetShape;
                bReSelect = true;
            }

            if (shape != null && bReSelect)// && !object.ReferenceEquals(shape, this))
            {
                item.SetItem(shape);
                view.Selection.Clear();
                view.Selection.Add(item);
                view.Selection.PrimaryItem = item;
                view.Selection.FocusedItem = item;
                return(true);
            }

            return(false);
        }
示例#21
0
 public override void CoerceSelection(DiagramItem item, DiagramClientView view, bool isAddition)
 {
     if (!SelectUnpinedParentShape(item, view))
     {
         base.CoerceSelection(item, view, isAddition);
     }
 }
        public int SaveDiagram(DiagramItem diagram)
        {
            var designerItems = _database.GetCollection <DiagramItem>("DiagramItems");

            designerItems.Upsert(diagram);
            return(diagram.Id);
        }
示例#23
0
        /// <summary>
        /// Return the tooltip text for the specified item
        /// </summary>
        /// <param name="item">A DiagramItem for the selected shape. This could be the shape, or a nested child shape or field.</param>
        public override string GetToolTipText(DiagramItem item)
        {
            // Work out which shape is selected - is it this ClassShape, or
            // is it one of the comparment shapes it contains?
            if (item.Shape is ElementListCompartment compartment)
            {
                // It's a compartment shape.
                // Get a list of the elements that are represented by diagram item (should be only one)
                ModelAttribute modelAttribute = compartment.GetSubFieldRepresentedElements(item.Field, item.SubField)
                                                .OfType <ModelAttribute>()
                                                .FirstOrDefault(a => a.IsForeignKey);

                if (modelAttribute != null)
                {
                    // Find the association this belongs with
                    ModelClass modelClass = modelAttribute.ModelClass;

                    Association association = modelClass.Store.ElementDirectory
                                              .AllElements
                                              .OfType <Association>()
                                              .FirstOrDefault(a => (a.Source == modelClass || a.Target == modelClass) &&
                                                              a.GetForeignKeyPropertyNames().Contains(modelAttribute.Name));

                    if (association != null)
                    {
                        return($"FK for [{association.GetDisplayText()}]");
                    }
                }
            }

            return(base.GetToolTipText(item));
        }
示例#24
0
        /// <summary>
        /// Compare two items
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        private int itemEdgeComparer(DiagramItem x, DiagramItem y)
        {
            var maxX = Math.Max(x.DesiredSize.Width, x.DesiredSize.Height);
            var maxY = Math.Max(y.DesiredSize.Width, y.DesiredSize.Height);

            return(maxY.CompareTo(maxX));
        }
示例#25
0
        private DragAndDrop(DiagramItem attachedElement, GetPosition get, SetPosition set)
        {
            _item = attachedElement;
            _get  = get;
            _set  = set;

            hookEvents();
        }
示例#26
0
        public override string GetToolTipText(DiagramItem item)
        {
            Generalization generalization = item.Shape.ModelElement as Generalization;

            return(generalization != null
                   ? $"{generalization.Subclass.Name} inherits from {generalization.Superclass.Name}"
                   : string.Empty);
        }
        public Geometry CalculateGeometry(DiagramItem item)
        {
            var label = item as DiagramLabel;
            if (label == null)
                throw new DiagramException("");

            return CalculateLabelGeometry(label);
        }
        public override string GetToolTipText(DiagramItem item)
        {
            BidirectionalAssociation association = item.Shape.ModelElement as BidirectionalAssociation;

            return(association != null
                   ? $"{association.Source.Name}.{association.TargetPropertyName} <--> {association.Target.Name}.{association.SourcePropertyName}"
                   : string.Empty);
        }
        public DiagramSelectionBorder CalculateBorder(DiagramItem item)
        {
            var edge = item as DiagramEdge;
            if (edge == null)
                throw new DiagramException("Тип отрисовщика не соответствует типу итема");

            return CalculateEdgeBorder(edge);
        }
        public DiagramSelectionBorder CalculateBorder(DiagramItem item)
        {
            var label = item as DiagramLabel;
            if (label == null)
                throw new DiagramException("Тип объекта не соответствует типу отрисовщика!");

            return CalculateLabelBorder(label);
        }
示例#31
0
        string GetUpcomingGames()
        {
            WeightedVote[]  votes       = context.GetModule <PollModule>().GetWeightedVotes("next");
            PollDiagramData diagramdata = new PollDiagramData(votes);
            DiagramItem     nextgame    = diagramdata.GetItems().FirstOrDefault();

            return(nextgame?.Item);
        }
        public Geometry CalculateGeometry(DiagramItem item)
        {
            var edge = item as DiagramEdge;
            if (edge == null)
                throw new DiagramException("");

            return CalculateEdgeGeometry(edge);
        }
        public Geometry CalculateGeometry(DiagramItem item)
        {
            var node = item as DiagramNode;
            if (node == null)
                throw new DiagramException("Тип итема не соответствует типу отрисовщика");

            return CalculateNodeGeometry(node);
        }
示例#34
0
        internal void RemoveSegment(DiagramItem item)
        {
            var index = _attachedItems.IndexOf(item);

            _segmentEnds.RemoveAt(index);
            _segmentStarts.RemoveAt(index);
            _attachedItems.RemoveAt(index);
        }
        public DiagramSelectionBorder CalculateBorder(DiagramItem item)
        {
            var node = item as DiagramNode;
            if (node == null)
                throw new DiagramException("Тип итема не соответствует типу отрисовщика");

            return CalculateNodeBorder(node);
        }
        public string GetVariableTooltipText(DiagramItem item)
        {
            var o = item.Shape.ModelElement as Composite;
            var text = "Composite: " + o.Name + Environment.NewLine;
            text += "Fields: " + o.Fields.Count + Environment.NewLine;

            return text;
        }
示例#37
0
        /// <summary>
        /// Indicate the source/target columns for the foreign key connector
        /// </summary>
        public override string GetToolTipText(DiagramItem item)
        {
            BinaryAssociation link = ((BarkerErModelContainsBinaryAssociation)ModelElement).BinaryAssociation;

            return(string.Format(
                       "Association #{0}; Role 1: {1}, Role 2: {2}",
                       link.Number, link.RoleCollection[0].PredicateText, link.RoleCollection[1].PredicateText));
        }
示例#38
0
        /// <summary>
        /// Determine if item can be pasted on _nextPosition.
        /// </summary>
        /// <param name="item">item to be determined.</param>
        /// <returns>Return true, if there is enough space to paste item.</returns>
        private bool hasEnoughSpace(DiagramItem item)
        {
            var thSize       = item.DesiredSize;
            var neededWidth  = thSize.Width + _nextPosition.X;
            var neededHeight = thSize.Height + _nextPosition.Y;

            return(neededWidth <= _layoutSize.Width && neededHeight <= _layoutSize.Height);
        }
示例#39
0
 // when title is selected, select its parent shape instead.
 public override void CoerceSelection(DiagramItem item, DiagramClientView view, bool isAddition)
 {
     base.CoerceSelection(item, view, isAddition);
     if (item != null && item.Shape != null && item.Shape == this && this.ParentShape != null)
     {
         view.Selection.Clear();
         view.Selection.Add(new DiagramItem(this.ParentShape));
     }
 }
        public void Draw(DrawingContext dc, Rect viewport, DiagramItem item)
        {
            var label = item as DiagramLabel;
            if (label == null)
                throw new DiagramException("Тип объекта не соответствует типу отрисовщика!");

            DrawLabel(dc, label);

            if (label.Diagram != null && label.Diagram.Selection.Contains(item))
            {
                DrawSelectionBorder(item.Diagram, dc, item.Border);
            }
        }
        public void Draw(DrawingContext dc, Rect viewport, DiagramItem item)
        {
            var edge = item as DiagramEdge;
            if (edge == null)
                throw new DiagramException("Тип отрисовщика не соответствует типу итема");

            //DrawEdge(dc, edge);
            DrawGeometry(dc, edge.Geometry, edge.Background, edge.BorderPen, edge.Diagram.Offset, edge.Diagram.Scale);
            if (edge.Diagram.Selection.Contains(edge))
            {
                DrawSelectionBorder(edge.Diagram, dc, edge.Border);
            }
        }
        public void Draw(DrawingContext dc, Rect viewport, DiagramItem item)
        {
            var node = item as DiagramNode;
            if (node == null)
                throw new DiagramException("Тип итема не соответствует типу отрисовщика");

            DrawGeometry(dc, node.Geometry, node.Background, node.BorderPen, node.Diagram.Offset, node.Diagram.Scale);
            //DrawNode(dc, node);
            if (node.Diagram.Selection.Contains(node))
            {
                DrawSelectionBorder(item.Diagram, dc, item.Border);
            }
            if (node.IsUnderCursor)
            {
                DrawBUC(item.Diagram, dc, node.Bounds);
            }
        }
示例#43
0
		/// <summary>
		/// Indicate the source/target columns for the foreign key connector
		/// </summary>
		public override string GetToolTipText(DiagramItem item)
		{
			ReferenceConstraint constraint = ((ReferenceConstraintTargetsTable)ModelElement).ReferenceConstraint;
			StringBuilder sb = new StringBuilder();
			string sourceTableName = constraint.SourceTable.Name;
			string targetTableName = constraint.TargetTable.Name;
			foreach (ColumnReference columRef in constraint.ColumnReferenceCollection)
			{
				if (sb.Length != 0)
				{
					sb.AppendLine();
				}
				sb.Append(sourceTableName);
				sb.Append(".");
				sb.Append(columRef.SourceColumn.Name);
				sb.Append(" -> ");
				sb.Append(targetTableName);
				sb.Append(".");
				sb.Append(columRef.TargetColumn.Name);
			}
			return sb.ToString();
		}
示例#44
0
		/// <summary>
		/// Select the specified <paramref name="diagramItem"/> in the spy window
		/// </summary>
		/// <param name="diagramItem">The <see cref="DiagramItem"/> to activate and show</param>
		/// <returns>true if activation was successful</returns>
		public bool ActivateDiagramItem(DiagramItem diagramItem)
		{
			if (diagramItem != null && ActivateDiagram(diagramItem.Diagram))
			{
				if (!diagramItem.IsDiagram)
				{
					myDiagramView.DiagramClientView.EnsureVisible(GetShapeBoundingBox(diagramItem.Shape), DiagramClientView.EnsureVisiblePreferences.ScrollIntoViewCenter);
					myDiagramView.Selection.Set(diagramItem);
				}
				return true;
			}
			return false;
		}
示例#45
0
 public DiagramNodeEditor(DiagramItem item, DiagramItemNode nod)
 {
     this.diagramItem = item;
     this.nod = nod;
 }
            /// <summary>
            ///     Called by the design surface to allow selection filtering
            /// </summary>
            /// <param name="currentSelection">[in] The current selection before any ShapeElements are added or removed.</param>
            /// <param name="proposedItemsToAdd">[in/out] The proposed DiagramItems to be added to the selection.</param>
            /// <param name="proposedItemsToRemove">[in/out] The proposed DiagramItems to be removed from the selection.</param>
            /// <param name="primaryItem">
            ///     [in/out] The proposed DiagramItem to become the primary DiagramItem of the selection.
            ///     A null value signifies that the last DiagramItem in the resultant selection should be assumed as the
            ///     primary DiagramItem.
            /// </param>
            /// <returns>
            ///     true if some or all of the selection was accepted; false if the entire selection proposal
            ///     was rejected. If false, appropriate feedback will be given to the user to indicate that the
            ///     selection was rejected.
            /// </returns>
            public override bool GetCompliantSelection(
                SelectedShapesCollection currentSelection, DiagramItemCollection proposedItemsToAdd,
                DiagramItemCollection proposedItemsToRemove, DiagramItem primaryItem)
            {
                base.GetCompliantSelection(currentSelection, proposedItemsToAdd, proposedItemsToRemove, primaryItem);

                var originalProposedItemsToAdd = new DiagramItem[proposedItemsToAdd.Count];
                proposedItemsToAdd.CopyTo(originalProposedItemsToAdd, 0);

                // we only perform this with selection rectangles, in which case the focused item will be the diagram 
                // and the user clicks on the "Properties" or "Navigation Properties" compartment on an entity
                if (currentSelection.FocusedItem != null
                    && currentSelection.FocusedItem.Shape == _diagram)
                {
                    foreach (var item in originalProposedItemsToAdd)
                    {
                        if (item.Shape != null
                            && item.Shape is ElementListCompartment)
                        {
                            // only perform this if we have selected the "Scalar Properties" ListCompartment or
                            // the "Navigation Properties" ListCompartment
                            var elListCompartment = item.Shape as ElementListCompartment;
                            if (elListCompartment.DefaultCreationDomainClass.Id == ViewModelProperty.DomainClassId
                                || elListCompartment.DefaultCreationDomainClass.Id == ViewModelNavigationProperty.DomainClassId)
                            {
                                // we don't perform this if a Property or NavigationProperty was selected
                                var representedShapeElements = item.RepresentedElements.OfType<ShapeElement>();
                                if (representedShapeElements.Count() == 1
                                    && representedShapeElements.Contains(item.Shape))
                                {
                                    // find the parent EntityTypeShape that houses this ListCompartment
                                    var entityTypeShape = elListCompartment.ParentShape as EntityTypeShape;
                                    Debug.Assert(
                                        entityTypeShape != null, "Why isn't the parent of the list compartment an EntityTypeShape?");
                                    var entityTypeShapeDiagramItem = new DiagramItem(entityTypeShape);

                                    // add the parent EntityTypeShape if it doesn't already exist in the collection
                                    if (!currentSelection.Contains(entityTypeShapeDiagramItem)
                                        && proposedItemsToAdd.Contains(entityTypeShapeDiagramItem) == false)
                                    {
                                        proposedItemsToAdd.Add(entityTypeShapeDiagramItem);
                                    }

                                    proposedItemsToAdd.Remove(item);
                                }
                            }
                        }
                    }
                }

                // The code below is responsible to enforce the following diagram items selection rule. (see Multiple Diagram spec).
                // - if an entity-type-shape is selected, no diagram-item can be selected in the diagram.
                // - if diagram-item that is not an entity-type-shape is selected, no entity-type-shape can be selected.
                var firstDiagramItem = FirstSelectionItem(currentSelection, proposedItemsToAdd, proposedItemsToRemove);
                if (firstDiagramItem != null
                    && proposedItemsToAdd.Count > 0)
                {
                    var isFirstDiagramItemEntityTypeShape = firstDiagramItem.Shape is EntityTypeShape;

                    // For Multi selection rules, we can only select EntityTypeShapes or else but not both.
                    foreach (var item in proposedItemsToAdd.ToList())
                    {
                        if (isFirstDiagramItemEntityTypeShape && ((item.Shape is EntityTypeShape) == false))
                        {
                            RemoveSelectedDiagramItem(item, currentSelection, proposedItemsToAdd, proposedItemsToRemove);
                        }
                        else if (isFirstDiagramItemEntityTypeShape == false
                                 && (item.Shape is EntityTypeShape))
                        {
                            RemoveSelectedDiagramItem(item, currentSelection, proposedItemsToAdd, proposedItemsToRemove);
                        }
                    }
                }
                return true;
            }
 /// <summary>
 ///     Helper method to cancel a diagram item to be selected.
 /// </summary>
 /// <param name="diagramItem"></param>
 /// <param name="currentSelection"></param>
 /// <param name="proposedItemsToAdd"></param>
 /// <param name="proposedItemsToRemove"></param>
 private static void RemoveSelectedDiagramItem(
     DiagramItem diagramItem, SelectedShapesCollection currentSelection, DiagramItemCollection proposedItemsToAdd,
     DiagramItemCollection proposedItemsToRemove)
 {
     if (currentSelection.Contains(diagramItem) == false
         && proposedItemsToAdd.Contains(diagramItem))
     {
         proposedItemsToAdd.Remove(diagramItem);
     }
     if (currentSelection.Contains(diagramItem)
         && proposedItemsToRemove.Contains(diagramItem) == false)
     {
         proposedItemsToRemove.Add(diagramItem);
     }
 }
        private void SetInitialSelectionCallback(object o)
        {
            if (ActiveDiagramView != null)
            {
                if (InitialDiagramItemSelection == null)
                {
                    // seed our "hypotenuse" with the length from upper-left to the bottom-right corner of the canvas rectangle
                    // (we don't need to Sqrt on the result since we are just comparing them, not interested in actual length)
                    var clientRectangle = ActiveDiagramView.ClientRectangle;
                    double hyp = ((clientRectangle.Width * clientRectangle.Width) + (clientRectangle.Height * clientRectangle.Height));

                    // find the entity closest to the origin
                    EntityTypeShape upperLeft = null;
                    foreach (var shape in NestedChildShapes)
                    {
                        var entityShape = shape as EntityTypeShape;
                        if (entityShape != null)
                        {
                            // calculate the distance from 0,0 to the shape's upper left corner
                            // (we don't need to Sqrt on the result since we are just comparing them, not interested in actual length)
                            var entityBounds = entityShape.AbsoluteBounds;
                            var entityHyp = ((entityBounds.X * entityBounds.X) + (entityBounds.Y * entityBounds.Y));

                            // if this is closer to the origin, remember it
                            if (entityHyp < hyp)
                            {
                                upperLeft = entityShape;
                                hyp = entityHyp;
                            }
                        }
                    }

                    // if we found one, select it and move it into view
                    if (upperLeft != null)
                    {
                        ActiveDiagramView.Focus();
                        var selectMe = new DiagramItem(upperLeft);
                        ActiveDiagramView.Selection.Set(selectMe);
                        EnsureSelectionVisible();
                    }
                }
                else
                {
                    ActiveDiagramView.Focus();
                    ActiveDiagramView.Selection.Set(InitialDiagramItemSelection);
                    EnsureSelectionVisible();
                    InitialDiagramItemSelection = null;
                }
            }
        }
        /// <summary>
        ///     Event Handler when selections in the Diagram are changed.
        ///     When the selection changes in diagram, we build the list of the diagram items that will be emphasized and we ask the diagram item's shapes to be redrawn.
        ///     When the shape is redrawn, each shape determines whether it is in the list; if yes, it will draw the emphasis shape.
        /// </summary>
        private void diagramView_OnShapeSelectionChanged(object sender, EventArgs e)
        {
            if (ActiveDiagramView != null
                && ActiveDiagramView.Selection != null)
            {
                var shapesToBeEmphasized = new DiagramItemCollection();
                var selectedShapes = ActiveDiagramView.Selection;

                // For each DiagramItem in the Selection
                // - Get the corresponding model element.
                // - See if model element implement IContainRelatedElementsToEmphasizeWhenSelected.
                // - Get related model elements.
                // - For each related model elements, instantiates DiagramItem for the ModelElement.
                foreach (DiagramItem diagramItem in selectedShapes)
                {
                    IContainRelatedElementsToEmphasizeWhenSelected relatedModelElementToEmphasize = null;
                    if (diagramItem.Shape != null
                        && diagramItem.Shape.ModelElement != null)
                    {
                        relatedModelElementToEmphasize = diagramItem.Shape.ModelElement as IContainRelatedElementsToEmphasizeWhenSelected;
                    }
                    else
                    {
                        // DiagramItem.Shape.ModelElement is null when the selected item is not a ShapeElement(for example: Property/NavigationProperty).
                        // Fortunately, we can retrieve the information from RepresentedElements property.
                        relatedModelElementToEmphasize =
                            diagramItem.RepresentedElements.OfType<ModelElement>().FirstOrDefault() as
                            IContainRelatedElementsToEmphasizeWhenSelected;
                    }

                    if (relatedModelElementToEmphasize != null)
                    {
                        // For each ModelElement get the corresponding diagram item.
                        foreach (var emphasizedModelElement in relatedModelElementToEmphasize.RelatedElementsToEmphasizeOnSelected)
                        {
                            DiagramItem emphasizedDiagramItem = null;

                            // if ModelElement is a Property, we could not just instantiate a DiagramItem and pass in the property's PresentationElement to the constructor
                            // since property's PresentationElement is not a ShapeElement.
                            var propertyBase = emphasizedModelElement as ViewModelPropertyBase;
                            if (propertyBase != null)
                            {
                                ViewModelEntityType et = null;
                                var navigationProperty = propertyBase as ViewModelNavigationProperty;
                                var property = propertyBase as ViewModelProperty;
                                if (navigationProperty != null)
                                {
                                    et = navigationProperty.EntityType;
                                }
                                else if (property != null)
                                {
                                    et = property.EntityType;
                                }
                                else
                                {
                                    Debug.Fail("Unexpected property type. Type name:" + propertyBase.GetType().Name);
                                }

                                Debug.Assert(et != null, "Could not get EntityType for property: " + propertyBase.Name);
                                if (et != null)
                                {
                                    Debug.Assert(
                                        PresentationViewsSubject.GetPresentation(et).Count() <= 1,
                                        "There should be at most 1 EntityTypeShape for EntityType:" + et.Name);
                                    var ets = PresentationViewsSubject.GetPresentation(et).FirstOrDefault() as EntityTypeShape;
                                    emphasizedDiagramItem = ets.GetDiagramItemForProperty(propertyBase);
                                }
                            }
                            else
                            {
                                var relatedPresentationElementToEmphasize =
                                    PresentationViewsSubject.GetPresentation(emphasizedModelElement).FirstOrDefault();
                                if (relatedPresentationElementToEmphasize != null)
                                {
                                    var relatedShapeElementToEmphasize = relatedPresentationElementToEmphasize as ShapeElement;

                                    if (relatedShapeElementToEmphasize != null)
                                    {
                                        emphasizedDiagramItem = new DiagramItem(relatedShapeElementToEmphasize);
                                    }
                                }
                            }

                            // Only add if the DiagramItem hasn't been added to the list and the diagram item is not a member of selected diagram item list.
                            if (emphasizedDiagramItem != null
                                && shapesToBeEmphasized.Contains(emphasizedDiagramItem) == false
                                && selectedShapes.Contains(emphasizedDiagramItem) == false)
                            {
                                shapesToBeEmphasized.Add(emphasizedDiagramItem);
                            }
                        }
                    }
                }
                EmphasizedShapes.Set(shapesToBeEmphasized);
            }
        }
        public override string GetToolTipText(DiagramItem item)
        {
            var tooltipText = base.GetToolTipText(item);

            var association = ModelElement;
            if (association != null)
            {
                // Source: {0} ({1})\nTarget {2} ({3})
                tooltipText = String.Format(
                    CultureInfo.CurrentCulture,
                    Properties.Resources.Tooltip_AssociationConnector,
                    association.SourceEntityType.Name, association.SourceMultiplicity,
                    association.TargetEntityType.Name, association.TargetMultiplicity).Replace(@"\n", "\n");
            }

            return tooltipText;
        }
 public override void CoerceSelection(DiagramItem item, DiagramClientView view, bool isAddition)
 {
     base.CoerceSelection(item, view, isAddition);
 }
示例#52
0
 public void Remove(DiagramItem item)
 {
     _items.Remove(item);
 }
		/// <summary>
		/// Override of DoHitTest so it works with non-rectilinear line segments
		/// </summary>
		public override bool DoHitTest(IGeometryHost geometryHost, PointD hitPoint, DiagramHitTestInfo hitTestInfo, bool includeTolerance)
		{
			bool retVal = false;
			LineSegment hitSegment = null;
			AnchorPoint anchorPoint = null;
			// In DSL Tools v8.2, GetHitTestTolerance is an instance method, but in DSL Tools v9.0, it is a static method.
			// We call it without a qualifier here so that it will compile against both versions.
			SizeD tolerance = GetHitTestTolerance(hitTestInfo);
			RectangleD perimeter = this.GetPerimeterBoundingBox(geometryHost);
			perimeter.Inflate(tolerance);
			if (perimeter.Contains(hitPoint))
			{
				LineSegment[] segments = this.CalculateSegments(geometryHost, hitTestInfo);
				int segmentCount = segments.Length;
				for (int i = 0; i < segmentCount; ++i)
				{
					LineSegment testSegment = segments[i];
					RectangleD testBounds = GeometryHelpers.RectangleDFrom2Pts(testSegment.StartPoint, testSegment.EndPoint);
					testBounds.Inflate(tolerance);
					if (testBounds.Contains(hitPoint))
					{
						anchorPoint = TestHitAnchor(geometryHost as BinaryLinkShape, testSegment, tolerance, hitPoint);
						if (anchorPoint != null)
						{
							retVal = true;
							hitSegment = testSegment;
							break;
						}
						double distance = DistanceFromPointToLine(hitPoint, testSegment.StartPoint, testSegment.EndPoint, true);
						if (!double.IsNaN(distance) && distance < (tolerance.Width + geometryHost.GeometryStyleSet.GetPen(geometryHost.GeometryOutlinePenId).Width / 2f))
						{
							retVal = true;
							hitSegment = testSegment;
							break;
						}
					}
				}
			}
			if (hitTestInfo != null)
			{
				DiagramItem diagramItem;
				if (retVal)
				{
					if (anchorPoint == null)
					{
						// In DSL Tools v8.2, CreateDiagramItem is an instance method, but in DSL Tools v9.0, it is a static method.
						// We call it without a qualifier here so that it will compile against both versions.
						diagramItem = CreateDiagramItem(geometryHost, hitSegment);
					}
					else
					{
						diagramItem = new DiagramItem(geometryHost as LinkShape, hitSegment, anchorPoint);
					}
				}
				else
				{
					diagramItem = null;
				}
				hitTestInfo.HitDiagramItem = diagramItem;
				hitTestInfo.HitGrabHandle = null;
			}
			return retVal;
		}
        public string GetVariableTooltipText(DiagramItem item)
        {
            var o = item.Shape.ModelElement as Function;
            var text = "Function: " + o.Name + Environment.NewLine;
            text += "Fields: " + o.Fields.Count + Environment.NewLine;
            var genFieldCount = o.Fields.Count(x => !x.IsGenerated);
            if (genFieldCount > 0)
                text += "Generated Fields: " + genFieldCount + Environment.NewLine;

            text += "Parameters: " + o.Parameters.Count + Environment.NewLine;
            var genParameterCount = o.Parameters.Count(x => !x.IsGenerated);
            if (genParameterCount > 0)
                text += "Generated Parameters: " + genParameterCount + Environment.NewLine;

            return text;
        }
		/// <summary>
		/// Track the last hit diagram item
		/// </summary>
		/// <param name="e"></param>
		protected override void OnMouseMove(DiagramMouseEventArgs e)
		{
			myLastMouseMoveItem = (DiagramItem)e.DiagramHitTestInfo.HitDiagramItem.Clone();
			base.OnMouseMove(e);
		}
		private void Reset()
		{
			mySelectedRoles = null;
			mySourceShape = null;
			myIUC = null;
			myLastMouseMoveItem = null;
			myPendingOnClickedAction = OnClickedAction.Normal;
			FactTypeShape.ActiveInternalUniquenessConstraintConnectAction = null;
		}
示例#57
0
        public void NodeAdded(DiagramItem item, NetworkObject obj)
        {
            NetworkNode node = obj as NetworkNode;
            if (node == null)
                return;

            Binding binding = new Binding();
            binding.Path = new PropertyPath("Name");
            binding.Source = node;
            item.SetBinding(DiagramItem.TextProperty, binding);

            //newNode.SetBinding(DiagramItem.TextProperty, binding);
            item.Uid = node.Id.ToString();
            item.ContextMenu = _nodeMenu;

            item.MouseLeftButtonDown += new MouseButtonEventHandler(item_MouseLeftButtonDown);
        }
示例#58
0
 public void Add(DiagramItem item)
 {
     if (_items.Contains(item) == false) _items.Add(item);
 }
示例#59
0
		/// <summary>
		/// Helper function for TranslateAccessibleObject and EnsureAccessibleObjectVisible
		/// </summary>
		private DiagramItem TranslateAccessibleObjectToDiagramItem(AccessibleObject accessibleObject, bool returnShape)
		{
			if (accessibleObject == null)
			{
				return null;
			}
			DiagramItem hitItem = null;
			DiagramClientView clientView = myClientView;
			DiagramHitTestInfo hitInfo = new DiagramHitTestInfo(clientView);
			RectangleD boundsD = clientView.DeviceToWorld(clientView.RectangleToClient(accessibleObject.Bounds));
			if (clientView.Diagram.DoHitTest(boundsD.Center, hitInfo, false))
			{
				hitItem = hitInfo.HitDiagramItem;
				if (!returnShape)
				{
					// Wind back out the parent stack if the hit test went too far
					if (hitItem.SubField != null)
					{
						if (!(accessibleObject is SubfieldAccessibleObject))
						{
							if (!(accessibleObject is FieldAccessibleObject))
							{
								hitItem = new DiagramItem(hitItem.Shape);
							}
							else
							{
								hitItem = new DiagramItem(hitItem.Shape, hitItem.Field);
							}
						}
					}
					else if (hitItem.Field != null && !(accessibleObject is FieldAccessibleObject))
					{
						hitItem = new DiagramItem(hitItem.Shape);
					}
				}
			}
			return hitItem;
		}
        public string GetVariableTooltipText(DiagramItem item)
        {
            var o = item.Shape.ModelElement as Entity;
            var text = "Entity: " + o.Name;

            if (!string.IsNullOrEmpty(o.CodeFacade))
                text += " (" + o.CodeFacade + ")";
            text += Environment.NewLine;

            text += "Fields: " + o.Fields.Count + Environment.NewLine;
            var genFieldCount = o.Fields.Count(x => !x.IsGenerated);
            if (genFieldCount > 0)
                text += "Generated Fields: " + genFieldCount + Environment.NewLine;
            text += "Outbound Relations: " + o.RelationshipList.Count() + Environment.NewLine;
            text += "Inbound Relations: " + o.GetRelationsWhereChild().Count() + Environment.NewLine;

            if (o.Composites.Count > 0)
                text += "Composites: " + o.Composites.Count + Environment.NewLine;

            return text;
        }