Saturday, December 31, 2016

Splitting Polyline/Curve With AutoCAD Civil 3D Labels Associated - Updated

The code shown in my previous post, as I mentioned there, only re-creates single Civil3D segment label when a polyline/curve is split. However, each segment of a split-able curve/polyline could be annotated by multiple labels (in different label styles, of course). Also, the code shown in that post does not re-store the labels in their original locations. I was able to find a few hours sitting down to update the code to cover these issues.

The solution is to search drawing to find all labels that associate to the polyline/curve to be split, and save these labels' information for later need (when re-creating labels). So, I defined this class SegmentLabelInfo:

using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
 
namespace Civil3DLabels
{
    public enum SegmentLabelType
    {
        LineLabel=0,
        CurveLabel=1,
    }
 
    public class SegmentLabelInfo
    {
        public ObjectId LabelStyleId { setget; }
        public string LabelLayer { setget; }
        public Point3d LabelPosition { setget; }
        public SegmentLabelType LabelType { setget; }
 
        public SegmentLabelInfo()
        {
            LabelStyleId = ObjectId.Null;
            LabelLayer = "";
            LabelPosition = Point3d.Origin;
            LabelType = SegmentLabelType.LineLabel;
        }
 
        public bool IsOnCurve(ObjectId curveId, out double ratio)
        {
            ratio = 0.5;
            bool onCurve = false;
 
            Point3d pt;
            using (var tran = 
                curveId.Database.TransactionManager.StartTransaction())
            {
                var curve = (Curve)tran.GetObject(
                    curveId, OpenMode.ForRead);
                pt = curve.GetClosestPointTo(LabelPosition, false);
 
                //If the label anchored on this curve
                var dist = LabelPosition.DistanceTo(pt);
                onCurve = dist <= Tolerance.Global.EqualPoint;
 
                //the distance from curve's start point to anchor point
                dist = curve.GetDistAtPoint(pt);
                ratio = dist / curve.GetDistAtPoint(curve.EndPoint);
 
                tran.Commit();
            }
 
            return onCurve;
        }
    }
}

As the code shows, besides the 4 public properties used to store a label's information, a method IsOnCurve() is also defined to determine if the label sits on one of the segment split from the original polyline/curve; if yes, what location (distance to the start point) the label is at (output parameter ratio).

Now, here is the updated working code, where I changed the class name from PolylineSplitter to MyPolylineSplitter:

using System.Collections.Generic;
using System.Linq;
using CadApp = Autodesk.AutoCAD.ApplicationServices.Application;
using CadDb = Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using CivilApp = Autodesk.Civil.ApplicationServices.CivilApplication;
using Civil = Autodesk.Civil;
using CivilDb = Autodesk.Civil.DatabaseServices;
using Autodesk.Civil.DatabaseServices.Styles;
 
[assemblyCommandClass(typeof(Civil3DLabels.MyPolylineSplitter))]
 
namespace Civil3DLabels
{
    public class MyPolylineSplitter
    {
        private const string DXF_LABEL = "AECC_GENERAL_SEGMENT_LABEL";
 
        [CommandMethod("ExplodePoly")]
        public void DoSplit()
        {
            var dwg = CadApp.DocumentManager.MdiActiveDocument;
            var ed = dwg.Editor;
            try
            {
                Split(dwg);
            }
            catch (System.Exception ex)
            {
                ed.WriteMessage("\nError: {0}", ex.Message);
                ed.WriteMessage("\n*Cancel*");
            }
 
            Autodesk.AutoCAD.Internal.Utils.PostCommandPrompt();
        }
        public void Split(Document dwg)
        {
            CadDb.ObjectId polyId = SelectPolyline(dwg.Editor);
            if (polyId.IsNull) return;
 
            //Collect all labels' information that associate with the polyline
            IEnumerable<SegmentLabelInfo> labels = FindAssociatedLabels(polyId);
            
            //Get default line/curve label style IDs
            var defaultLineLabelStyleId = CadDb.ObjectId.Null;
            var defaultCurveLabelStyleId = CadDb.ObjectId.Null;
            if (labels.Count() > 0)
            {
                GetSettingsCmdAddSegmentLabelDefaultStyles(
                    out defaultLineLabelStyleId, out defaultCurveLabelStyleId);
            }
 
            using (var tran = dwg.TransactionManager.StartTransaction())
            {
                var poly = (CadDb.Polyline)tran.GetObject(
                    polyId, CadDb.OpenMode.ForRead);
 
                //Find current space
                var curSpace = (CadDb.BlockTableRecord)tran.GetObject(
                    poly.OwnerId, CadDb.OpenMode.ForRead);
 
                //Newly created entities because of the splitting
                var newIds = new List<CadDb.ObjectId>();
 
                //Get split segments and add them into current space
                using (var ents = GetSplitCurvesFromPolyline(poly))
                {
                    if (ents.Count > 1)
                    {   
                        curSpace.UpgradeOpen();
                        foreach (CadDb.DBObject ent in ents)
                        {
                            var id = curSpace.AppendEntity(ent as CadDb.Entity);
                            tran.AddNewlyCreatedDBObject(ent, true);
 
                            newIds.Add(id);
                        }
 
                        // Erase the polyline,
                        // Associated labels would also be gone
                        poly.UpgradeOpen();
                        poly.Erase(true);
                    }
                    else
                    {
                        ents[0].Dispose();
                    }
                }
 
                //Add label to each newly added entities
                if (newIds.Count>0 && labels.Count()>0)
                {      
                    foreach (var entId in newIds)
                    {
                        AddSegmentLabel(
                            entId, 
                            labels, 
                            defaultLineLabelStyleId, 
                            defaultCurveLabelStyleId,
                            tran);
                    }
                }
 
                tran.Commit();
            }         
        }
 
        #region private methods
 
        private CadDb.ObjectId SelectPolyline(Editor ed)
        {
            var opt = new PromptEntityOptions(
                "\nSelect a polyline:");
            opt.SetRejectMessage("\nInvalid: not a polyline.");
            opt.AddAllowedClass(typeof(CadDb.Polyline), true);
 
            var res = ed.GetEntity(opt);
            if (res.Status==PromptStatus.OK)
            {
                return res.ObjectId;
            }
            else
            {
                return CadDb.ObjectId.Null;
            }
        }
 
        private CadDb.DBObjectCollection GetSplitCurvesFromPolyline(
            CadDb.Polyline poly)
        {
            var points = new Point3dCollection();
            for (int i = 0; i < poly.NumberOfVertices; i++)
            {
                points.Add(poly.GetPoint3dAt(i));
            }
 
            var dbObjects = poly.GetSplitCurves(points);
 
            return dbObjects;
        }
 
        private IEnumerable<SegmentLabelInfo> FindAssociatedLabels(
            CadDb.ObjectId polyId)
        {
            var labels = new List<SegmentLabelInfo>();
 
            CadDb.Database db = polyId.Database;
 
            using (var tran = db.TransactionManager.StartTransaction())
            {
                var ent = (CadDb.Entity)tran.GetObject(
                    polyId, CadDb.OpenMode.ForRead);
                var space = (CadDb.BlockTableRecord)tran.GetObject(
                    ent.OwnerId, CadDb.OpenMode.ForRead);
 
                foreach (CadDb.ObjectId id in space)
                {
                    if (id.ObjectClass.DxfName.ToUpper() == DXF_LABEL)
                    {
                        var label = tran.GetObject(
                            id, CadDb.OpenMode.ForRead) as CivilDb.Label;
                        if (label != null && label.FeatureId==polyId)
                        {
                            var info = new SegmentLabelInfo()
                            {
                                LabelStyleId = label.StyleId,
                                LabelLayer = label.Layer,
                                LabelPosition = label.AnchorInfo.Location
                            };
 
                            // Since each label uses either line label style or curve label style
                            // We test if the label style is line label style.
                            // if not, the label style must be curve label style
                            var lineStyles =
                                CivilApp.ActiveDocument.Styles.LabelStyles.GeneralLineLabelStyles;
                            info.LabelType = IsSegmentLabelStyle(label.StyleId, lineStyles, tran) ?
                                SegmentLabelType.LineLabel : SegmentLabelType.CurveLabel;
 
                            labels.Add(info);
                        }
                    }
                }
 
                tran.Commit();
            }
 
            return labels;
        }
 
        private void AddSegmentLabel(
            CadDb.ObjectId entId, 
            IEnumerable<SegmentLabelInfo> labels,
            CadDb.ObjectId defaultLineLabelStyleId, 
            CadDb.ObjectId defaultCurveLabelStyleId, 
            CadDb.Transaction tran )
        {
            foreach (var labelInfo in labels)
            {
                double ratio;
                if (labelInfo.IsOnCurve(entId, out ratio))
                {
                    var lineLabel = labelInfo.LabelType == SegmentLabelType.LineLabel ?
                        labelInfo.LabelStyleId : defaultLineLabelStyleId;
                    var curveLabel = labelInfo.LabelType == SegmentLabelType.CurveLabel ?
                        labelInfo.LabelStyleId : defaultCurveLabelStyleId;
 
                    //Add label to the segment
                    var id = CivilDb.GeneralSegmentLabel.Create(
                        entId, ratio, lineLabel, curveLabel);
                    var label = (CivilDb.Label)tran.GetObject(
                        id, CadDb.OpenMode.ForRead);
                    if (label.Layer.ToUpper()!=labelInfo.LabelLayer.ToUpper())
                    {
                        label.UpgradeOpen();
                        label.Layer = labelInfo.LabelLayer;
                    }
                }
            }
        }
 
        private bool IsSegmentLabelStyle(
            CadDb.ObjectId styleId, 
            IEnumerable<CadDb.ObjectId> styleCollection, 
            CadDb.Transaction tran)
        {
            bool found = false;
 
            foreach (CadDb.ObjectId id in styleCollection)
            {
                if (styleId == id)
                {
                    found = true;
                }
                else
                {
                    var style = (LabelStyle)tran.GetObject(
                        id, CadDb.OpenMode.ForRead);
                    if (style.ChildrenCount > 0)
                    {
                        var styleIds = new List<CadDb.ObjectId>();
                        for (int i = 0; i < style.ChildrenCount; i++)
                        {
                            styleIds.Add(style[i]);
                        }
 
                        //Recursive call
                        found =
                            IsSegmentLabelStyle(styleId, styleIds, tran);
                    }
                }
 
                if (found) break;
            }
 
            return found;
        }
 
        private void GetSettingsCmdAddSegmentLabelDefaultStyles(
            out CadDb.ObjectId lineLabelStyleId,
            out CadDb.ObjectId curveLabelStyleId)
        {
            var settings = CivilApp.ActiveDocument.Settings;
            var cmdSettings = 
                settings.GetSettings<Civil.Settings.SettingsCmdAddSegmentLabel>();
 
            lineLabelStyleId = cmdSettings.Styles.LineLabelStyleId.Value;
            curveLabelStyleId = cmdSettings.Styles.CurveLabelStyleId.Value;
        }
        
        #endregion
    }
}

The polyline to be split in this video clip is annotated with 2 labels for each of its segment; some of the labels are on different layers (in different colors); Also, the labels' anchor point (location) on the segment have been dragged randomly along the segment. After execute command "ExplodePoly", all labels look like unchanged, even though they are all re-created.

Tuesday, December 27, 2016

Splitting Polyline/Curve With AutoCAD Civil 3D Labels Associated

In the era of using plain AutoCAD, I had written routines in AutoLISP and VBA to split a polyline into individual segment (e.g. breaking polyline at each vertex). After AutoCAD .NET API came, it is even easier to do this splitting: simply calling Curve.GetSplitCurves() will gives you back all the individual segment of a polyline/curve, based in the input points on the polyline/curve; in the case of polyline, most likely these points are the polyline's vertices.

However, once we moved from plain AutoCAD to some of the AutoCAD vertical products, in my case, it was AutoCAD Map, then AutoCAD Civil, thing can get complicated. 

With AutoCAD Map, the polylines, to which we used to do splitting, may have Object Data (a kind of attribute data that can be attached to AutoCAD entity, a bit similar to XData) attached. Once the usual splitting is done the attached data is gone, because the splitting is actually creating the individual segment of the polyline as new entities and the original polyline is erased.

With AutoCAD Civil, the splitting target polyline, besides possible Object Data being attached, may also be annotated with AutoCAD Civil label. In the case of Civil label, if the entity (polyline) being labelled is erased, the label will also be erased automatically. So, when my office moved from AutoCAD Map to AutoCAD Civil a while a go, I was asked to modify our polyline splitting tool (which have already handled the attached Object Data issue as aforementioned) to retain AutoCAD Civil label, if the polyline has been labelled.

Labelling is huge part of AutoCAD Civil 3D in terms of its customization. I am still pretty new on this. It took quite some study for me to figure out a working solution, be it is optimized or not. Since there is not as much programming resources available on AutoCAD Map/Civil3D, as on plain AutoCAD, I thought sharing my solution with fellow programmers would be good thing.

Here are the requirements:

1. Split a polyline (assume it is LWPolyline for the simplicity) into individual segment at each vertices;
2. If the polyline has been annotated with labels (assume the label is general segment line/curve label), the labels in the same label style remain.

Here are the logics of the solution:

1. Determine if the polyline is annotated with labels. If yes, what the 2 label styles (for line and curve segment) are used;
2. Get all individual segments and add them into database; 
3. Erase the polyline (then the labels annotating the polyline are gone);
4. Recreate labels on each individual segment with label style determined in Step 1.

Translating the logics into code:
using System.Collections.Generic;
using CadApp = Autodesk.AutoCAD.ApplicationServices.Application;
using CadDb = Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using CivilApp = Autodesk.Civil.ApplicationServices.CivilApplication;
using Civil = Autodesk.Civil;
using CivilDb = Autodesk.Civil.DatabaseServices;
using Autodesk.Civil.DatabaseServices.Styles;
 
[assemblyCommandClass(typeof(Civil3DLabels.PolylineSplitter))]
 
namespace Civil3DLabels
{
    public class PolylineSplitter
    {
        private const string DXF_LABEL = "AECC_GENERAL_SEGMENT_LABEL";
 
        [CommandMethod("SplitPoly")]
        public void DoSplit()
        {
            var dwg = CadApp.DocumentManager.MdiActiveDocument;
            var ed = dwg.Editor;
            try
            {
                Split(dwg);
            }
            catch (System.Exception ex)
            {
                ed.WriteMessage("\nError: {0}", ex.Message);
                ed.WriteMessage("\n*Cancel*");
            }
 
            Autodesk.AutoCAD.Internal.Utils.PostCommandPrompt();
        }
        public void Split(Document dwg)
        {
            CadDb.ObjectId polyId = SelectPolyline(dwg.Editor);
            if (polyId.IsNull) return;
 
            // If the polyline is annotated with general segmen
            // label, find the label styles (line label and curve label),
            //If not labels, both label styles are ObjectId.Null.
            CadDb.ObjectId lineLabelStyleId;
            CadDb.ObjectId curveLabelStyleId;
            GetCurveGeneralSegmentLabelStyles(
                polyId, out lineLabelStyleId, out curveLabelStyleId);
            bool hasLabel = !lineLabelStyleId.IsNull && !curveLabelStyleId.IsNull;
 
            using (var tran = dwg.TransactionManager.StartTransaction())
            {
                var poly = (CadDb.Polyline)tran.GetObject(
                    polyId, CadDb.OpenMode.ForRead);
 
                //Find current space
                var curSpace = (CadDb.BlockTableRecord)tran.GetObject(
                    poly.OwnerId, CadDb.OpenMode.ForRead);
 
                //Newly created entities because of the splitting
                var newIds = new List<CadDb.ObjectId>();
 
                //Get split segments and add them into current space
                using (var ents = GetSplitCurvesFromPolyline(poly))
                {
                    if (ents.Count > 1)
                    {   
                        curSpace.UpgradeOpen();
                        foreach (CadDb.DBObject ent in ents)
                        {
                            var id = curSpace.AppendEntity(ent as CadDb.Entity);
                            tran.AddNewlyCreatedDBObject(ent, true);
 
                            newIds.Add(id);
                        }
 
                        //Erase the polyline (label would also be gone, if exist
                        poly.UpgradeOpen();
                        poly.Erase(true);
                    }
                    else
                    {
                        ents[0].Dispose();
                    }
                }
 
                //Add label to each newly added entities
                if (newIds.Count>0 && hasLabel)
                {      
                    AddGeneralSegmentLabels(
                        newIds, lineLabelStyleId, curveLabelStyleId);
                }
 
                tran.Commit();
            }         
        }
 
        #region private methods
 
        private CadDb.ObjectId SelectPolyline(Editor ed)
        {
            var opt = new PromptEntityOptions(
                "\nSelect a polyline:");
            opt.SetRejectMessage("\nInvalid: not a polyline.");
            opt.AddAllowedClass(typeof(CadDb.Polyline), true);
 
            var res = ed.GetEntity(opt);
            if (res.Status==PromptStatus.OK)
            {
                return res.ObjectId;
            }
            else
            {
                return CadDb.ObjectId.Null;
            }
        }
 
        private CadDb.DBObjectCollection GetSplitCurvesFromPolyline(
            CadDb.Polyline poly)
        {
            var points = new Point3dCollection();
            for (int i = 0; i < poly.NumberOfVertices; i++)
            {
                points.Add(poly.GetPoint3dAt(i));
            }
 
            var dbObjects = poly.GetSplitCurves(points);
 
            return dbObjects;
        }
 
        private void AddGeneralSegmentLabels(
            IEnumerable<CadDb.ObjectId> featureIds, 
            CadDb.ObjectId lineLabelStyleId, 
            CadDb.ObjectId curveLabelStyleId)
        {
            foreach (var featureId in featureIds)
            {
                var labelId = CivilDb.GeneralSegmentLabel.Create(
                    featureId, 0.5, lineLabelStyleId, curveLabelStyleId);
            }
        }
 
        private void GetCurveGeneralSegmentLabelStyles(
            CadDb.ObjectId curveId,
            out CadDb.ObjectId lineStyleId, 
            out CadDb.ObjectId curveStyleId)
        {
            bool hasLabel = false;
            lineStyleId = CadDb.ObjectId.Null;
            curveStyleId = CadDb.ObjectId.Null;
 
            var id1 = CadDb.ObjectId.Null;
            var id2 = CadDb.ObjectId.Null;
 
            using (var tran = curveId.Database.TransactionManager.StartTransaction())
            {
                var ent = (CadDb.Entity)tran.GetObject(curveId, CadDb.OpenMode.ForRead);
                var space = (CadDb.BlockTableRecord)tran.GetObject(
                    ent.OwnerId, CadDb.OpenMode.ForRead);
 
                foreach (CadDb.ObjectId id in space)
                {
                    if (id.ObjectClass.DxfName.ToUpper() == DXF_LABEL)
                    {
                        var label = tran.GetObject(
                            id, CadDb.OpenMode.ForRead) as CivilDb.Label;
                        if (label != null)
                        {
                            if (label.FeatureId == curveId)
                            {
                                if (!hasLabel) hasLabel = true;
 
                                if (id1.IsNull)
                                {
                                    id1 = label.StyleId;
                                }
                                else if (label.StyleId != id1)
                                {
                                    id2 = label.StyleId;
                                }
                            }
                        }
                    }
 
                    if (!id1.IsNull && !id2.IsNull) break;
                }
 
                //Only go further when at least one style is found
                if (hasLabel)
                {
                    if (!id1.IsNull)
                    {
                        //if it is Line Segment Style or Curve Segment Style
                        var civilDoc = CivilApp.ActiveDocument;
                        var lineStyles = 
                            civilDoc.Styles.LabelStyles.GeneralLineLabelStyles;
                        var curveStyles = 
                            civilDoc.Styles.LabelStyles.GeneralCurveLabelStyles;
 
                        if (IsTheLineSegmentStyle(id1, lineStyles, tran))
                        {
                            lineStyleId = id1;
                            if (!id2.IsNull)
                            {
                                if (IsTheLineSegmentStyle(id2, curveStyles, tran))
                                {
                                    curveStyleId = id2;
                                }
                            }
                        }
                        else
                        {
                            if (IsTheLineSegmentStyle(id1, curveStyles, tran))
                            {
                                curveStyleId = id1;
                                if (!id2.IsNull)
                                {
                                    if (IsTheLineSegmentStyle(id2, lineStyles, tran))
                                    {
                                        lineStyleId = id2;
                                    }
                                }
                            }
                        }
                    }
 
                    // The annotated polyline may only have line label or curve label
                    // So, here is to get default label style (either line label style
                    // or curve label style
                    CadDb.ObjectId defaultLineStyleId;
                    CadDb.ObjectId defaultCurveStyleId;
                    GetSettingsCmdAddSegmentLabelDefaultStyles(
                        out defaultCurveStyleId, out defaultLineStyleId);
 
                    if (lineStyleId.IsNull) lineStyleId = defaultLineStyleId;
                    if (curveStyleId.IsNull) curveStyleId = defaultCurveStyleId;
                }
 
                tran.Commit();
            }
        }
 
        private bool IsTheLineSegmentStyle(
            CadDb.ObjectId styleId, 
            IEnumerable<CadDb.ObjectId> styleCollection, 
            CadDb.Transaction tran)
        {
            bool found = false;
 
            foreach (CadDb.ObjectId id in styleCollection)
            {
                if (styleId == id)
                {
                    found = true;
                }
                else
                {
                    var style = (LabelStyle)tran.GetObject(
                        id, CadDb.OpenMode.ForRead);
                    if (style.ChildrenCount > 0)
                    {
                        var styleIds = new List<CadDb.ObjectId>();
                        for (int i = 0; i < style.ChildrenCount; i++)
                        {
                            styleIds.Add(style[i]);
                        }
 
                        //Recursive call
                        found = 
                            IsTheLineSegmentStyle(styleId, styleIds, tran);
                    }
                }
 
                if (found) break;
            }
 
            return found;
        }
 
        private void GetSettingsCmdAddSegmentLabelDefaultStyles(
            out CadDb.ObjectId curveLabelStyleId, 
            out CadDb.ObjectId lineLabelStyleId)
        {
            var settings = CivilApp.ActiveDocument.Settings;
            var cmdSettings = 
                settings.GetSettings<Civil.Settings.SettingsCmdAddSegmentLabel>();
 
            lineLabelStyleId = cmdSettings.Styles.LineLabelStyleId.Value;
            curveLabelStyleId = cmdSettings.Styles.CurveLabelStyleId.Value;
        }

        #endregion
    }
}

In the code, the critical portion of the code is the private method GetCurveGeneralSegmentLabelStyle(), which does these things:

1. Check if the curve to be split has general segment labels associated or not.
2. If there is general segment labels associated, what the 2 label styles (line label and curve label) are.
3. Since the curve's split-able segments could be only lines, or only curves, we may only find one label style (line label style or curve label style) that is associated to the split-able curve.
4. The reason that I need to find both line and curve label styles, even the split-able curve may only use one label style, is that I need to re-create general segment labels on each split segment with Autodesk.Civil.DatabaseServices.GeneralSegmentLabel.Create(ObjectId, double, ObjectId, ObjectId), instead of Autodesk.Civil.DatabaseServices.GeneralSegmentLabel.Create(ObjectId, double). That is, I use the Create() method with 2 label styles' ObjectId passed in, instead of the Create() method that uses current default general segment label styles, set in Autodesk.Civil.Settings.SettingsCmdAddSegmentLable.Styles, which may be different from the original label styles found with the split-able curve.
5. Each of the 2 possible label styles (line or curve label styles) could have one or more child label styles, and each of the child styles could also have child styles...and so on. So the recursive method in the code to identify label style to be used.

This video clip shows the result of running the code.

The code is just a simplified way to re-label the individual segments after splitting a curve, it may not  re-create the label exactly as the original ones. For example, an original label could have been dragged along the segment from default location (centre of the segment), while the code shown here always create the label at the segment centre (the double argument of the Create() method is passed with value 0.5). So, to make the re-created label locate at exact location as the original one, when searching associated labels to the split-able curve, I would need to save the property value of GeneralSegmentLabel class of each found label of each segment, and use the value later when re-creating the label. It would need quite some extra code. I choose to leave it outside of this post.

Adittion Note

I also realize that a segment of line/curve could be annotated with multiple labels (in different label styles, of course). So, the code I posted here only works with segment being labelled with one label style. Obviously, if I want to retain all the labels in the case of multiple labels used on segments, I would need to identify all the labels that is associated to each segment before the splitting target polyline is erased. I'll see if I can find time to work out that part code later.

Tuesday, December 20, 2016

Custom AutoCAD Entity Tool Tip

I cannot recall since when AutoCAD was able to show tool tip in AutoCAD editor when user place mouse cursor over on an AutoCAD entity. But I remember many years ago I came across an small AutoCAD utility (again, I cannot remember the name, it was an either ADE or ARX tool) that did the same thing as current AutoCAD entity tool tip: when the mouse cursor hovers on top of an entity, a quite detailed information window shows up.

Since AutoCAD .NET API came along, we can quite easily to show custom data as entity tool tip with only a few lines of code. Below is sample code of doing a simple entity tool tip.

using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using CadApp = Autodesk.AutoCAD.ApplicationServices.Application;
 
[assemblyCommandClass(typeof(CustomToolTip.SimpleToolTip))]
 
namespace CustomToolTip
{
    public class SimpleToolTip
    {
        private bool _enabled = false;
        private Document _dwg = null;
 
        public SimpleToolTip()
        {
            _dwg = CadApp.DocumentManager.MdiActiveDocument;
        }
 
        [CommandMethod("SimpleTip")]
        public void RunSimpleToolTip()
        {
            var dwg = CadApp.DocumentManager.MdiActiveDocument;
            var ed = dwg.Editor;
 
            if (!_enabled)
            {
                SetPointMonitorEventHandler(true);
                _enabled = true;
                ed.WriteMessage(
                    string.Format("\nSIMPLE TIP is enabled in drawing {0}.\n",
                    System.IO.Path.GetFileName(dwg.Name)));
            }
            else
            {
                SetPointMonitorEventHandler(false);
                _enabled = false;
                ed.WriteMessage(
                    string.Format("\nSIMPLE TIP is disabled in drawing {0}.\n",
                    System.IO.Path.GetFileName(dwg.Name)));
            }
        }
 
        #region private methods
 
        private void SetPointMonitorEventHandler(bool attach)
        {
            if (attach)
            {
                _dwg.Editor.PointMonitor += Editor_PointMonitor;
            }
            else
            {
                _dwg.Editor.PointMonitor -= Editor_PointMonitor;
            }
        }
 
        private void Editor_PointMonitor(object sender, PointMonitorEventArgs e)
        {
            var fullPaths = e.Context.GetPickedEntities();
            if (fullPaths.Length == 0) return;
 
            ObjectId entId = ObjectId.Null;
            foreach (var path in fullPaths)
            {
                if (!path.IsNull)
                {
                    var ids = path.GetObjectIds();
                    if (ids.Length>0)
                    {
                        entId = ids[0];
                    }
                }
 
                if (!entId.IsNull) break;
            }
 
            if (!entId.IsNull)
            {
                // Now, with entity's ID in handle, one can decide if the entity
                // is the target entity to show custom tool tip, and yes, what 
                // information would be shown. Here I simply show DxfName
                e.AppendToolTipText(
                    "DXF NAME: " + entId.ObjectClass.DxfName);
            }
        }
 
        #endregion
    }
}

This video clip shows how the code works. One would notice that even through the method of the PointMonitorEventArgs used to set custom tool tip is called AppendToolTipText, it does not append the custom tool tip text to existing AutoCAD entity tool tip (when AutoCAD's "RollOverTips" system variable is set to 1). Instead, the custom tool tip text replaces AutoCAD built-in tool tip. Also one may notice the command method is an "instance" method, as opposed to "static" method. That means, when the command method is called (user enters command "SimpleTip"), the first time, AutoCAD creates an instance of the class SimpleToolTip on each document where the command runs. Because each drawing has its own SimpleToolTip class, I can safely have a member field in the class _dwg to hold reference to the drawing document, and use it to attach/detach Editor.PointMonitor event handler.

Although using PointMonitorEventArg.AppendToolTipText() makes it very easy to show custom tool tip, it does not provide further data formatting options to make custom tool tip better. There were a couple of discussions on AutoCAD entity tool tip in the Autodesk's discussion forum, here and here, where one of the Autodesk Expert Elite, Keith Brown, posted some code that provided a quite elegant solution. As Keith's code shows, the entry point for the custom code to manipulate AutoCAD's entity tool tip is to handle Autodesk.Windows.ComponentManager.ToolTipOpened event, where the custom tool tip content is "injected" into the showing tool tip window (WPF Visual object).

By learning from Keith's code, I came up with yet another way to show custom entity tool tip in AutoCAD: using code directly creates an instance of ToolTip class (Autodesk.Internal.Windows.ToolTip) and shows it as needed.

Firstly, this is the class that shows/closes custom tool tips MyEntityToolTip:
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using CadApp = Autodesk.AutoCAD.ApplicationServices.Application;
 
[assemblyCommandClass(typeof(CustomToolTip.MyEntityToolTip))]
 
namespace CustomToolTip
{
    public class MyEntityToolTip
    {
        private Document _dwg = null;
 
        private Autodesk.Internal.Windows.ToolTip _tipWindow = null;
        private bool _rolloverEnabled = false;
        private ObjectId _currentEntId = ObjectId.Null;
 
        private short _builtInRollTip = 1;
 
        public MyEntityToolTip()
        {
            _dwg = CadApp.DocumentManager.MdiActiveDocument;
        }
 
        [CommandMethod("EntInfo")]
        public void ShowEntityInfo()
        {
            while(true)
            {
                var opt = new PromptEntityOptions(
                    "\nSelect an entity");
                opt.Keywords.Add("eXit");
                opt.Keywords.Default = "eXit";
 
                var res = _dwg.Editor.GetEntity(opt);
                if (res.Status==PromptStatus.OK)
                {
                    ShowEntityInfo(res.ObjectId);
                    _dwg.Editor.GetString("\nPress any key to continue...");
                    if (_tipWindow!=null)
                    {
                        _tipWindow.Close();
                        _tipWindow = null;
                    }
                }
                else
                {
                    break;
                }
            }
        }
 
        [CommandMethod("MyRollOverTip")]
        public void SetRolloverTip()
        {
            if (!_rolloverEnabled)
            {
                SetRolloverEventHandler(true);
                _rolloverEnabled = true;
                _dwg.Editor.WriteMessage(
                    "\nMY ROLLOVER TOOLTIP is enabled\n");
            }
            else
            {
                SetRolloverEventHandler(false);
                _rolloverEnabled = false;
                _dwg.Editor.WriteMessage(
                    "\nMY ROLLOVER TOOLTIP is disabled\n");
            }
        }
 
        #region private methods
 
        private void ShowEntityInfo(ObjectId entId)
        {
            if (_tipWindow!=null)
            {
                _tipWindow.Close();
                _tipWindow = null;
            }
 
            _tipWindow = new Autodesk.Internal.Windows.ToolTip();
 
            _tipWindow.MaxWidth = 200;
            _tipWindow.MinWidth = 100;
 
            var myContent = new ToolTipCustomContent();
 
            myContent.HeaderText= 
                string.Format("Entity ID: {0}", entId.ToString());
 
            // Deliberately pass in long test string
            myContent.DetailText = 
                "This entity's information should be obtained " +
                "based on the drafting operation requirements.";
            myContent.FooterText= 
                string.Format("Entity Type: {0}", entId.ObjectClass.DxfName);
 
            System.Drawing.Bitmap picture;
            if (entId.ObjectClass.DxfName.ToUpper() == "CIRCLE")
                picture = Properties.Resources.Koala;
            else
                picture = Properties.Resources.Penguins;
 
            myContent.DetailPicture = picture;
 
            _tipWindow.Content = myContent;
            _tipWindow.Background = System.Windows.Media.Brushes.LightCyan;
 
            _tipWindow.Show();
        }
 
        private void SetRolloverEventHandler(bool enable)
        {
            if (enable)
            {
                _builtInRollTip = (short)CadApp.GetSystemVariable("ROLLOVERTIPS");
                CadApp.SetSystemVariable("ROLLOVERTIPS", 0);
                _dwg.Editor.Rollover += Editor_Rollover;
            }
            else
            {
                _dwg.Editor.Rollover -= Editor_Rollover;
                CadApp.SetSystemVariable("ROLLOVERTIPS", _builtInRollTip);
            }
        }
 
        private void Editor_Rollover(object sender, RolloverEventArgs e)
        {
            ObjectId entId = ObjectId.Null;
 
            var fullPath = e.Highlighted;
            if (!fullPath.IsNull)
            {
                var ids = fullPath.GetObjectIds();
                if (ids.Length>0)
                {
                    entId = ids[0];
                }
            }
 
            if (entId.IsNull)
            {
                _currentEntId = ObjectId.Null;
                if (_tipWindow != null)
                {
                    _tipWindow.Close();
                }
            }
            else
            {
                if (entId!=_currentEntId)
                {
                    ShowEntityInfo(entId);
                    _currentEntId = entId;
                }
            }
        }
        
        #endregion
    }
}

From the code one can see that I create/show/close an Autodesk.Internal.Windows.ToolTip instance in Editor.Rollover event handler. Because AutoCAD would still show its built-in rollover tool tip if system variable "ROLLOVERTIPS" is set 1, regardless my custom tool tip shows or not, I set the system variable "ROLLOVERTIPS" to 0 when my custom tool tip is enabled, and restore it back when my custom tool tip is disabled.

The actual content displayed by Autodesk.Internal.Widnows.ToolTip is a WPF UserControl. Here is its XAML code:
<UserControl x:Class="CustomToolTip.ToolTipCustomContent"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:CustomToolTip"
             mc:Ignorable="d" 
             d:DesignHeight="150" d:DesignWidth="150">
    <Grid x:Name="MyContent">
        <Grid.RowDefinitions>
            <RowDefinition Height="26" />
            <RowDefinition Height="25*" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <StackPanel x:Name="stpContentHeader" Grid.Row="0" Background="#FFFDFD44">
            <TextBlock x:Name="txtHeader" Text="" FontWeight="Bold" 
                       HorizontalAlignment="Left" VerticalAlignment="Center"
                       Margin="5,5,5,5"/>
        </StackPanel>
        <StackPanel x:Name="stpContentDetail" Grid.Row="1" Orientation="Vertical">
            <TextBlock x:Name="txtDetail" Text="" 
                       HorizontalAlignment="Left" VerticalAlignment="Top"
                       Margin="5,0,5,0" TextWrapping="Wrap"/>
            <Image x:Name="imgDetail" Visibility="Collapsed" Margin="5,5,5,5" Stretch="Fill"
                   HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
                
            </Image>
        </StackPanel>
        <StackPanel x:Name="stpContentFooter" Grid.Row="2" Background="#FFFDFD44">
            <TextBlock x:Name="txtFooter" Text="" FontWeight="Bold" 
                       HorizontalAlignment="Left" VerticalAlignment="Center"
                       Margin="5,5,5,5"/>
        </StackPanel>
    </Grid>
</UserControl>

Here is WPF UserControl's code-behind:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
 
namespace CustomToolTip
{
    /// <summary>
    /// Interaction logic for ToolTipCustomContent.xaml
    /// </summary>
    public partial class ToolTipCustomContent : UserControl
    {
        public ToolTipCustomContent()
        {
            InitializeComponent();
        }
 
        public StackPanel ContentHeaderPanel
        {
            get
            {
                return stpContentHeader;
            }
        }
 
        public StackPanel ContentDetailPanel
        {
            get
            {
                return stpContentDetail;
            }
        }
 
        public StackPanel ContentFooterPanel
        {
            get
            {
                return stpContentFooter;
            }
        }
 
        public string HeaderText
        {
            set
            {
                txtHeader.Text = value;
            }
            get
            {
                return txtHeader.Text;
            }
        }
 
        public string DetailText
        {
            set
            {
                txtDetail.Text = value;
            }
            get
            {
                return txtDetail.Text;
            }
        }
 
        public string FooterText
        {
            set
            {
                txtFooter.Text = value;
            }
            get
            {
                return txtFooter.Text;
            }
        }
 
        public System.Drawing.Bitmap DetailPicture
        {
            set
            {
                ImageSource source = null;
                if (value != null)
                {
                    source = value.ToWpfImageSource();
                }
 
                if (source==null)
                {
                    imgDetail.Visibility = Visibility.Collapsed;
                }
                else
                {
                    imgDetail.Source = source;
                    imgDetail.Visibility = Visibility.Visible;
                }
            }
        }
    }
}

In order to display custom tool tip easier, I make the tool tip to be displayed in 3 portions: header (text), detail (text and picture) and footer (text). And I expose the controls (TextBlock and Image) directly as the UserControl's properties, so that they can be set easily. Obviously, the UserControl can be fill up dynamically with any suitable control depending on data to be displayed. I added 2 PNG pictures into the project's resources, and display one picture when mouse cursor hover on CIRCLE, otherwise display another picture. To show picture in WPF's Image control, I need to convert System.Drawing.Bitmap object into System.Windows.Media.ImageSource object:
using System.Drawing.Imaging;
using System.Windows.Media.Imaging;
 
namespace CustomToolTip
{
    public static class ImageSourceExtension
    {
        public static System.Windows.Media.ImageSource ToWpfImageSource(
            this System.Drawing.Bitmap picture)
        {
            using (var memory = new System.IO.MemoryStream())
            {
                picture.Save(memory, ImageFormat.Png);
                memory.Position = 0;
 
                var bitmapImage = new BitmapImage();
                bitmapImage.BeginInit();
                bitmapImage.StreamSource = memory;
                bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                bitmapImage.EndInit();
 
                return bitmapImage;
            }
        }
    }
}

Now, go to this video clip to see the custom tool tip in action.

For the sake of completeness, I also tried Mr. Keith Brown's approach of handling ComponentManager.ToolTipOpened event. However, I used Editor.Rollover event handler instead of Editor.PointMonitor event handler to identify entity, for which the custom tool tip shows. Of course I use the same WPF UserControl as the content of the custom tool tip. See code below:
using System;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using CadApp = Autodesk.AutoCAD.ApplicationServices.Application;
using Autodesk.Windows;
 
[assemblyCommandClass(typeof(CustomToolTip.CustomRolloverToolTip))]
 
namespace CustomToolTip
{
    public class CustomRolloverToolTip
    {
        private Document _dwg = null;
        private bool _rolloverEnabled = false;
        private ObjectId _targetEntId = ObjectId.Null;
 
        public CustomRolloverToolTip()
        {
            _dwg = CadApp.DocumentManager.MdiActiveDocument;
            ComponentManager.ToolTipOpened += ComponentManager_ToolTipOpened;
        }
        
        [CommandMethod("CustomToolTip")]
        public void ShowCustomToolTip()
        {
            if (!_rolloverEnabled)
            {
                SetRolloverEventHandler(true);
                _rolloverEnabled = true;
                _dwg.Editor.WriteMessage(
                    "\nCUSTOM ROLLOVER TOOLTIP is enabled\n");
            }
            else
            {
                SetRolloverEventHandler(false);
                _rolloverEnabled = false;
                _dwg.Editor.WriteMessage(
                    "\nCUSTOM ROLLOVER TOOLTIP is disabled\n");
            }
        }
 
        #region private methods
 
        private void ComponentManager_ToolTipOpened(object sender, EventArgs e)
        {
            if (_targetEntId.IsNull) return;
            if (Convert.ToInt32(CadApp.GetSystemVariable("ROLLOVERTIPS")) == 0) return;
 
            var tipWindow = sender as Autodesk.Internal.Windows.ToolTip;
            if (tipWindow == nullreturn;
 
            tipWindow.MaxWidth = 200;
            tipWindow.MinWidth = 100;
            ShowEntityInfo(tipWindow);
 
        }
 
        private void SetRolloverEventHandler(bool enable)
        {
            if (enable)
            {
                _dwg.Editor.Rollover += Editor_Rollover;
            }
            else
            {
                _dwg.Editor.Rollover -= Editor_Rollover;
            }
        }
 
        private void Editor_Rollover(object sender, RolloverEventArgs e)
        {
            ObjectId entId = ObjectId.Null;
 
            var fullPath = e.Highlighted;
            if (!fullPath.IsNull)
            {
                var ids = fullPath.GetObjectIds();
                if (ids.Length > 0)
                {
                    entId = ids[0];
                }
            }
 
            _targetEntId = entId;
        }
 
        private void ShowEntityInfo(Autodesk.Internal.Windows.ToolTip tipWindow)
        {
            var myContent = new ToolTipCustomContent();
 
            myContent.HeaderText =
                string.Format("Entity ID: {0}", _targetEntId.ToString());
 
            // Deliberately pass in long test string
            myContent.DetailText =
                "This entity's information should be obtained " +
                "based on the drafting operation requirements.";
            myContent.FooterText =
                string.Format("Entity Type: {0}", _targetEntId.ObjectClass.DxfName);
 
            System.Drawing.Bitmap picture;
            if (_targetEntId.ObjectClass.DxfName.ToUpper() == "CIRCLE")
                picture = Properties.Resources.Koala;
            else
                picture = Properties.Resources.Penguins;
 
            myContent.DetailPicture = picture;
 
            tipWindow.Content = myContent;
            tipWindow.Background = System.Windows.Media.Brushes.LightCyan;
 
            _targetEntId = ObjectId.Null;
        }
 
        #endregion
    }
}

See this video clip showing the code in action.

If watching the 2 video clips carefully, one would notice the difference of visual effect between the 2 approaches:

With handling ComponentManager.ToolTipOpened event, the custom code has not control of when tool tip is shown and when is closed. The custom code does is to "inject" custom tool tip data and display format via a WPF ContentControl, usually a UserControl. Meanwhile, the custom tool tip is controlled by "ROLLOVERTIPS" system variable, as built-in rollover tool tip is. However, if the tool tip carries heavier data, such as picture, as the video shows, the action may be a bit sluggish, because ComponetManager shows new ToolTip window whenever the mouse cursor moves, even the cursor never leaves the entity being hovered.

With showing own ToolTip window in Editor.Rollover event handler, my code only closes the ToolTip window when mouse cursor leaves the entity being hovered, so the tool tip display is smoother.

This video clip shows the visual effect difference of the 2 approaches.


Followers

About Me

My photo
After graduating from university, I worked as civil engineer for more than 10 years. It was AutoCAD use that led me to the path of computer programming. Although I now do more generic business software development, such as enterprise system, timesheet, billing, web services..., AutoCAD related programming is always interesting me and I still get AutoCAD programming tasks assigned to me from time to time. So, AutoCAD goes, I go.