Saturday, August 11, 2012

Creating Linked Entities with DrawJig

In AutoCAD discussion group's .NET forum, an user asked how to create linked objects (see here). I suggested that Jig, TransientGraphics and/or Overrule could be considered as the solution. I was thinking then to give it a try myself, but did not have time to actually write some code. However, this topic kept hanging on somewhere in my mind: what would I do if I were facing this task? So, I finally squeeze some time to sit down doing something with it, hence this post.

Let assume some requirement of this task, which may not be the same as the question raised in the AutoCAD discussion group. Say, user wants to use AutoCAD to draw a simple diagram, a kind of flow chart, which includes circles and lines. Let's also assume that a circle can be linked to one or more other circles by lines.

Drawing circles and lines would be very simple with AutoCAD. But what if user wants to move a drawn circle in the flow chart that is linked to other circles? It would be ideal that all lines that link to this moving circle from other circles and all lines that link to other circles from this moving circle would follow the move. So to user, it looks like the lines and circles are physically linked.

Now we can see that the only thing we need to deal with is when user want to change the existing flow chart by moving a node, represented by a circle, around, but still keep the links between nodes, represented by lines. To me, it sounds a lot like a jig. So, I decided to give jig a try.

Now I saw these tasks ahead of me:
  • Make a circle be aware of which line is connected to it from other circle and which line is connected to other circle from itself;
  • A line is used to connect only 2 circles, and knows which 2 circles it is connected.
  • Create a custom "MOVE" command for user to move circles in the flow chart
  • To make things simple, if user wants to change link between circles, he/she simply remove the link and recreate the link between any 2 circles
I decided to attach XData to the circles and linking lines to let the circles and lines be aware of which circles/lines it is linked to/from. Therefore my coding begins with an XData manipulation utility class. Here is it:

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using Autodesk.AutoCAD.DatabaseServices;
  5. using Autodesk.AutoCAD.Geometry;
  6.  
  7. namespace LinkedObjects
  8. {
  9.     public class LinkInfoXDataUtil
  10.     {
  11.         private const string OBJECT_LINK_APP = "MyNameSpace.LinkObjects";
  12.  
  13.         public static void SetLink(Database db,
  14.             ObjectId fromCircleId, ObjectId toCircleId, ObjectId linkLineId)
  15.         {
  16.             ObjectLinkAppExists(db, true);
  17.  
  18.             using (Transaction tran =
  19.                 db.TransactionManager.StartTransaction())
  20.             {
  21.                 Entity fromCircle = (Entity)tran.GetObject(
  22.                     fromCircleId, OpenMode.ForWrite);
  23.                 Entity toCircle = (Entity)tran.GetObject(
  24.                     toCircleId, OpenMode.ForWrite);
  25.                 Entity line = (Entity)tran.GetObject(
  26.                     linkLineId, OpenMode.ForWrite);
  27.  
  28.                 AddFromLinkToCircle(fromCircle, line.Handle.ToString());
  29.                 AddToLinkToCircle(toCircle, line.Handle.ToString());
  30.                 AddLinksToLine(line,
  31.                     fromCircle.Handle.ToString(),
  32.                     toCircle.Handle.ToString());
  33.  
  34.                 tran.Commit();
  35.             }
  36.         }
  37.  
  38.         public static void RemoveLink(Database db, ObjectId linkLineId)
  39.         {
  40.             using (Transaction tran =
  41.                 db.TransactionManager.StartTransaction())
  42.             {
  43.                 Entity line = (Entity)tran.GetObject(
  44.                     linkLineId, OpenMode.ForWrite);
  45.  
  46.                 ObjectId fromCircleId;
  47.                 ObjectId toCircleId;
  48.                 GetLinkedCirclesFromLine(
  49.                     db, tran, line, out fromCircleId, out toCircleId);
  50.  
  51.                 Entity fromCircle = (Entity)tran.GetObject(
  52.                     fromCircleId, OpenMode.ForWrite);
  53.                 Entity toCircle = (Entity)tran.GetObject(
  54.                     toCircleId, OpenMode.ForWrite);
  55.  
  56.                 //Remove line's handle from XData in circles
  57.                 RemoveFromLinkFromCircle(fromCircle, line.Handle.ToString());
  58.                 RemoveToLinkFromCircle(toCircle, line.Handle.ToString());
  59.  
  60.                 //Clear Xdata from the line
  61.                 TypedValue[] vals = new TypedValue[]
  62.                 {
  63.                     new TypedValue(
  64.                         (Int16)DxfCode.ExtendedDataRegAppName, OBJECT_LINK_APP)
  65.                 };
  66.                 ResultBuffer buffer = new ResultBuffer(vals);
  67.                 line.XData = buffer;
  68.  
  69.                 tran.Commit();
  70.             }
  71.         }
  72.  
  73.         public static void GetCirleLink(Database db, ObjectId circleId,
  74.             out List<ObjectId> fromLineIds, out List<ObjectId> toLineIds)
  75.         {
  76.             fromLineIds = new List<ObjectId>();
  77.             toLineIds = new List<ObjectId>();
  78.  
  79.             if (circleId.ObjectClass.DxfName.ToUpper() == "CIRCLE")
  80.             {
  81.                 using (Transaction tran =
  82.                     circleId.Database.TransactionManager.StartTransaction())
  83.                 {
  84.                     Entity ent = (Entity)tran.GetObject(
  85.                         circleId, OpenMode.ForRead);
  86.  
  87.                     ResultBuffer buffer =
  88.                         ent.GetXDataForApplication(OBJECT_LINK_APP);
  89.                     if (buffer == null) return;
  90.  
  91.                     TypedValue[] vals = buffer.AsArray();
  92.                     if (vals.Length == 3)
  93.                     {
  94.                         string handles;
  95.  
  96.                         //Get lines started from this circle
  97.                         handles = vals[1].Value.ToString();
  98.                         if (handles.Length > 0)
  99.                         {
  100.                             string[] hs = handles.Split('|');
  101.                             foreach (string h in hs)
  102.                             {
  103.                                 fromLineIds.Add(HandleToObjectId(db, h));
  104.                             }
  105.                         }
  106.  
  107.                         //Get lines pointing to this circle
  108.                         handles = vals[2].Value.ToString();
  109.                         if (handles.Length > 0)
  110.                         {
  111.                             string[] hs = handles.Split('|');
  112.                             foreach (string h in hs)
  113.                             {
  114.                                 toLineIds.Add(HandleToObjectId(db, h));
  115.                             }
  116.                         }
  117.                     }
  118.                     else
  119.                     {
  120.                         //Clear inavlid XData
  121.                         TypedValue[] vs = new TypedValue[]
  122.                         {
  123.                             new TypedValue(
  124.                                 (Int16)DxfCode.ExtendedDataRegAppName,
  125.                                 OBJECT_LINK_APP)
  126.                         };
  127.                         ent.UpgradeOpen();
  128.                         ent.XData = new ResultBuffer(vs);
  129.                     }
  130.  
  131.                     tran.Commit();
  132.                 }
  133.             }
  134.         }
  135.  
  136.         public static void GetLineLink(Database db, ObjectId lineId,
  137.             out ObjectId fromCircleId, out ObjectId toCircleId)
  138.         {
  139.             fromCircleId = ObjectId.Null;
  140.             toCircleId = ObjectId.Null;
  141.  
  142.             if (lineId.ObjectClass.DxfName.ToUpper() == "LINE")
  143.             {
  144.                 using (Transaction tran =
  145.                     lineId.Database.TransactionManager.StartTransaction())
  146.                 {
  147.                     Entity ent = (Entity)tran.GetObject(
  148.                         lineId, OpenMode.ForRead);
  149.                     ResultBuffer buffer =
  150.                         ent.GetXDataForApplication(OBJECT_LINK_APP);
  151.                     if (buffer == null) return;
  152.  
  153.                     TypedValue[] vals = buffer.AsArray();
  154.                     if (vals.Length == 3)
  155.                     {
  156.                         string handle;
  157.  
  158.                         //FROM circle
  159.                         handle = vals[1].Value.ToString();
  160.                         if (handle.Length > 0)
  161.                             fromCircleId = HandleToObjectId(db, handle);
  162.  
  163.                         //TO circle
  164.                         handle = vals[2].Value.ToString();
  165.                         if (handle.Length > 0)
  166.                             toCircleId = HandleToObjectId(db, handle);
  167.                     }
  168.  
  169.                     tran.Commit();
  170.                 }
  171.             }
  172.         }
  173.  
  174.         public static void GetLinkedCircleCentres(Database db, ObjectId linkLineId,
  175.             out Point3d fromCircleCentre, out Point3d toCircleCentre)
  176.         {
  177.             ObjectId fromCircleId;
  178.             ObjectId toCircleId;
  179.  
  180.             GetLineLink(db, linkLineId, out fromCircleId, out toCircleId);
  181.  
  182.             fromCircleCentre = CommonUtil.GetCircleCentre(db, fromCircleId);
  183.             toCircleCentre = CommonUtil.GetCircleCentre(db, toCircleId);
  184.         }
  185.  
  186.         #region private methoids
  187.  
  188.         private static bool ObjectLinkAppExists(Database db, bool create)
  189.         {
  190.             bool exists = false;
  191.             using (Transaction tran =
  192.                 db.TransactionManager.StartTransaction())
  193.             {
  194.                 RegAppTable appTable = (RegAppTable)tran.GetObject(
  195.                     db.RegAppTableId, OpenMode.ForRead);
  196.  
  197.                 if (appTable.Has(OBJECT_LINK_APP))
  198.                     exists = true;
  199.                 else
  200.                 {
  201.                     if (create)
  202.                     {
  203.                         RegAppTableRecord appRec = new RegAppTableRecord();
  204.                         appRec.Name = OBJECT_LINK_APP;
  205.                         appTable.UpgradeOpen();
  206.                         appTable.Add(appRec);
  207.                         tran.AddNewlyCreatedDBObject(appRec, true);
  208.                         exists = true;
  209.                     }
  210.                 }
  211.  
  212.                 tran.Commit();
  213.             }
  214.  
  215.                 return exists;
  216.         }
  217.  
  218.         private static ObjectId HandleToObjectId(
  219.             Database db, string handleString)
  220.         {
  221.             ObjectId id = ObjectId.Null;
  222.  
  223.             id = db.GetObjectId(false,
  224.                 new Handle(Int64.Parse(handleString,
  225.                     System.Globalization.NumberStyles.AllowHexSpecifier)), 0);
  226.  
  227.             return id;
  228.         }
  229.  
  230.         private static void AddFromLinkToCircle(Entity fromEnt, string handle)
  231.         {
  232.             ResultBuffer buffer =
  233.                 fromEnt.GetXDataForApplication(OBJECT_LINK_APP);
  234.             TypedValue[] vals;
  235.  
  236.             string newHandles = "";
  237.             string existingHandles = "";
  238.             string toHandles = "";
  239.  
  240.             if (buffer != null)
  241.             {
  242.                 vals = buffer.AsArray();
  243.                 existingHandles = vals[1].Value.ToString();
  244.                 toHandles = vals[2].Value.ToString();
  245.             }
  246.  
  247.             bool exists = false;
  248.             if (existingHandles.Length > 0)
  249.             {
  250.                 string[] hs = existingHandles.Split('|');
  251.                 foreach (string h in hs)
  252.                 {
  253.                     if (h.ToUpper() == handle.ToUpper())
  254.                     {
  255.                         exists = true;
  256.                         break;
  257.                     }
  258.                 }
  259.  
  260.                 if (!exists)
  261.                     newHandles = existingHandles + "|" + handle;
  262.                 else
  263.                     newHandles = existingHandles;
  264.             }
  265.             else
  266.             {
  267.                 newHandles = handle;
  268.             }
  269.  
  270.             vals = new TypedValue[]
  271.             {
  272.                 new TypedValue(
  273.                     (Int16)DxfCode.ExtendedDataRegAppName, OBJECT_LINK_APP),
  274.                 new TypedValue(
  275.                     (Int16)DxfCode.ExtendedDataAsciiString, newHandles),
  276.                 new TypedValue(
  277.                     (Int16)DxfCode.ExtendedDataAsciiString, toHandles)
  278.             };
  279.  
  280.             fromEnt.XData = new ResultBuffer(vals);
  281.         }
  282.  
  283.         private static void AddToLinkToCircle(Entity toEnt, string handle)
  284.         {
  285.             ResultBuffer buffer =
  286.                 toEnt.GetXDataForApplication(OBJECT_LINK_APP);
  287.             TypedValue[] vals;
  288.  
  289.             string newHandles = "";
  290.             string existingHandles = "";
  291.             string fromHandles = "";
  292.  
  293.             if (buffer != null)
  294.             {
  295.                 vals = buffer.AsArray();
  296.  
  297.                 existingHandles = vals[2].Value.ToString();
  298.                 fromHandles = vals[1].Value.ToString();
  299.             }
  300.  
  301.             bool exists = false;
  302.             if (existingHandles.Length > 0)
  303.             {
  304.                 string[] hs = existingHandles.Split('|');
  305.                 foreach (string h in hs)
  306.                 {
  307.                     if (h.ToUpper() == handle.ToUpper())
  308.                     {
  309.                         exists = true;
  310.                         break;
  311.                     }
  312.                 }
  313.  
  314.                 if (!exists)
  315.                     newHandles = existingHandles + "|" + handle;
  316.                 else
  317.                     newHandles = existingHandles;
  318.             }
  319.             else
  320.             {
  321.                 newHandles = handle;
  322.             }
  323.  
  324.             vals = new TypedValue[]
  325.             {
  326.                 new TypedValue(
  327.                     (Int16)DxfCode.ExtendedDataRegAppName, OBJECT_LINK_APP),
  328.                 new TypedValue(
  329.                     (Int16)DxfCode.ExtendedDataAsciiString, fromHandles),
  330.                 new TypedValue(
  331.                     (Int16)DxfCode.ExtendedDataAsciiString, newHandles)
  332.             };
  333.  
  334.             toEnt.XData = new ResultBuffer(vals);
  335.         }
  336.  
  337.         private static void AddLinksToLine(
  338.             Entity line, string fromHandle, string toHandle)
  339.         {
  340.             TypedValue[] vals = new TypedValue[]
  341.             {
  342.                 new TypedValue(
  343.                     (Int16)DxfCode.ExtendedDataRegAppName, OBJECT_LINK_APP),
  344.                 new TypedValue(
  345.                     (Int16)DxfCode.ExtendedDataAsciiString, fromHandle),
  346.                 new TypedValue(
  347.                     (Int16)DxfCode.ExtendedDataAsciiString, toHandle)
  348.             };
  349.  
  350.             line.XData = new ResultBuffer(vals);
  351.         }
  352.  
  353.         private static void GetLinkedCirclesFromLine(
  354.             Database db, Transaction tran, Entity line,
  355.             out ObjectId fromCircleId, out ObjectId toCircleId)
  356.         {
  357.             fromCircleId = ObjectId.Null;
  358.             toCircleId = ObjectId.Null;
  359.  
  360.             ResultBuffer buffer =
  361.                 line.GetXDataForApplication(OBJECT_LINK_APP);
  362.             if (buffer != null)
  363.             {
  364.                 TypedValue[] vals = buffer.AsArray();
  365.  
  366.                 string handleString;
  367.  
  368.                 handleString = vals[1].Value.ToString();
  369.                 fromCircleId = HandleToObjectId(db, handleString);
  370.  
  371.                 handleString = vals[2].Value.ToString();
  372.                 toCircleId = HandleToObjectId(db, handleString);
  373.             }
  374.         }
  375.  
  376.         private static void RemoveFromLinkFromCircle(
  377.             Entity fromCircle, string lineHandle)
  378.         {
  379.             ResultBuffer buffer =
  380.                 fromCircle.GetXDataForApplication(OBJECT_LINK_APP);
  381.             if (buffer == null) return;
  382.  
  383.             TypedValue[] vals = buffer.AsArray();
  384.             string fromHandles = vals[1].Value.ToString();
  385.             string toHandles = vals[2].Value.ToString();
  386.             if (fromHandles.Length > 0)
  387.             {
  388.                 StringBuilder newHandles = new StringBuilder();
  389.                 bool removed = false;
  390.  
  391.                 //rebuild the handles string with
  392.                 //targeted handle striing being excluded
  393.                 string[] hs = fromHandles.Split('|');
  394.                 foreach (string h in hs)
  395.                 {
  396.                     if (h.ToUpper() != lineHandle.ToUpper())
  397.                     {
  398.                         newHandles.Append(h + "|");
  399.                     }
  400.                     else
  401.                     {
  402.                         removed = true;
  403.                     }
  404.                 }
  405.  
  406.                 if (removed)
  407.                 {
  408.                     //remove the trailing "|"
  409.                     if (newHandles.ToString().EndsWith("|"))
  410.                     {
  411.                         newHandles.Length = newHandles.Length - 1;
  412.                     }
  413.  
  414.                     //recreate XData
  415.                     if (newHandles.Length == 0 && toHandles.Length == 0)
  416.                     {
  417.                         vals = new TypedValue[]
  418.                             {
  419.                                 new TypedValue(
  420.                                 (Int16)DxfCode.ExtendedDataRegAppName,
  421.                                 OBJECT_LINK_APP)
  422.                             };
  423.                     }
  424.                     else
  425.                     {
  426.                         vals = new TypedValue[]
  427.                         {
  428.                             new TypedValue(
  429.                                 (Int16)DxfCode.ExtendedDataRegAppName,
  430.                                 OBJECT_LINK_APP),
  431.                             new TypedValue(
  432.                                 (Int16)DxfCode.ExtendedDataAsciiString,
  433.                                 newHandles.ToString()),
  434.                             new TypedValue(
  435.                                 (Int16)DxfCode.ExtendedDataAsciiString,
  436.                                 toHandles)
  437.                         };
  438.                     }
  439.  
  440.                     fromCircle.XData = new ResultBuffer(vals);
  441.                 }
  442.             }
  443.         }
  444.  
  445.         private static void RemoveToLinkFromCircle(
  446.             Entity toCircle, string lineHandle)
  447.         {
  448.             ResultBuffer buffer =
  449.                 toCircle.GetXDataForApplication(OBJECT_LINK_APP);
  450.             if (buffer == null) return;
  451.  
  452.             TypedValue[] vals = buffer.AsArray();
  453.             string fromHandles = vals[1].Value.ToString();
  454.             string toHandles = vals[2].Value.ToString();
  455.             if (toHandles.Length > 0)
  456.             {
  457.                 StringBuilder newHandles = new StringBuilder();
  458.                 bool removed = false;
  459.  
  460.                 //rebuild the handles string with
  461.                 //targeted handle striing being excluded
  462.                 string[] hs = toHandles.Split('|');
  463.                 foreach (string h in hs)
  464.                 {
  465.                     if (h.ToUpper() != lineHandle.ToUpper())
  466.                     {
  467.                         newHandles.Append(h + "|");
  468.                     }
  469.                     else
  470.                     {
  471.                         removed = true;
  472.                     }
  473.                 }
  474.  
  475.                 if (removed)
  476.                 {
  477.                     //remove the trailing "|"
  478.                     if (newHandles.ToString().EndsWith("|"))
  479.                     {
  480.                         newHandles.Length = newHandles.Length - 1;
  481.                     }
  482.  
  483.                     //recreate XData
  484.                     if (newHandles.Length == 0 && fromHandles.Length == 0)
  485.                     {
  486.                         vals = new TypedValue[]
  487.                             {
  488.                                 new TypedValue(
  489.                                 (Int16)DxfCode.ExtendedDataRegAppName,
  490.                                 OBJECT_LINK_APP)
  491.                             };
  492.                     }
  493.                     else
  494.                     {
  495.                         vals = new TypedValue[]
  496.                         {
  497.                             new TypedValue(
  498.                                 (Int16)DxfCode.ExtendedDataRegAppName,
  499.                                 OBJECT_LINK_APP),
  500.                             new TypedValue(
  501.                                 (Int16)DxfCode.ExtendedDataAsciiString,
  502.                                 fromHandles),
  503.                             new TypedValue(
  504.                                 (Int16)DxfCode.ExtendedDataAsciiString,
  505.                                 newHandles.ToString())
  506.                         };
  507.                     }
  508.  
  509.                     toCircle.XData = new ResultBuffer(vals);
  510.                 }
  511.             }
  512.         }
  513.  
  514.         #endregion
  515.     }
  516. }

In order to organize my code in a bit cleaner structure, I place most generic AutoCAD operation used in this project in an AutoCAD utility class CommonUtil:

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using Autodesk.AutoCAD.ApplicationServices;
  4. using Autodesk.AutoCAD.DatabaseServices;
  5. using Autodesk.AutoCAD.EditorInput;
  6. using Autodesk.AutoCAD.Geometry;
  7.  
  8. namespace LinkedObjects
  9. {
  10.     public class CommonUtil
  11.     {
  12.         public static void PrintCancelMessage(string message = "")
  13.         {
  14.             Editor ed =
  15.                 Application.DocumentManager.MdiActiveDocument.Editor;
  16.  
  17.             if (!string.IsNullOrEmpty(message))
  18.             {
  19.                 ed.WriteMessage("\n" + message);
  20.             }
  21.             ed.WriteMessage("\n*Cancel*");
  22.             Autodesk.AutoCAD.Internal.Utils.PostCommandPrompt();
  23.         }
  24.  
  25.         public static bool PickEntity(Editor ed, Type entType,
  26.             string optionMessage, string rejectMessage, out ObjectId entId)
  27.         {
  28.             entId = ObjectId.Null;
  29.  
  30.             PromptEntityOptions opt = new PromptEntityOptions(optionMessage);
  31.             opt.SetRejectMessage(rejectMessage);
  32.             opt.AddAllowedClass(entType, true);
  33.  
  34.             PromptEntityResult res = ed.GetEntity(opt);
  35.             if (res.Status == PromptStatus.OK)
  36.             {
  37.                 entId = res.ObjectId;
  38.                 return true;
  39.             }
  40.  
  41.             return false;
  42.         }
  43.  
  44.         public static ObjectId DrawLineBetweenCircles(
  45.             Database db, ObjectId fromCircleId, ObjectId toCircleId)
  46.         {
  47.             ObjectId lineId = ObjectId.Null;
  48.  
  49.             using (Transaction tran =
  50.                 db.TransactionManager.StartTransaction())
  51.             {
  52.                 Circle fromCircle = (Circle)tran.GetObject(
  53.                     fromCircleId, OpenMode.ForRead);
  54.                 Circle toCircle = (Circle)tran.GetObject(
  55.                     toCircleId, OpenMode.ForRead);
  56.  
  57.                 ObjectId modelId =
  58.                     SymbolUtilityServices.GetBlockModelSpaceId(db);
  59.                 BlockTableRecord model = (BlockTableRecord)tran.GetObject(
  60.                     modelId, OpenMode.ForWrite);
  61.  
  62.                 using (Line line =
  63.                     new Line(fromCircle.Center, toCircle.Center))
  64.                 {
  65.                     //Change startpoint/endpoint from
  66.                     //circle's center to circle's perimeter
  67.                     Point3d pt;
  68.  
  69.                     pt = line.GetPointAtDist(fromCircle.Radius);
  70.                     line.StartPoint = pt;
  71.  
  72.                     double dist=line.Length-toCircle.Radius;
  73.                     pt = line.GetPointAtDist(dist);
  74.                     line.EndPoint = pt;
  75.  
  76.                     line.SetDatabaseDefaults(db);
  77.  
  78.                     lineId = model.AppendEntity(line);
  79.                     tran.AddNewlyCreatedDBObject(line, true);
  80.  
  81.                     tran.Commit();
  82.                 }
  83.             }
  84.  
  85.             return lineId;
  86.         }
  87.  
  88.         public static void EraseEntity(Database db, ObjectId entId)
  89.         {
  90.             using (Transaction tran = db.TransactionManager.StartTransaction())
  91.             {
  92.                 Entity ent = (Entity)tran.GetObject(entId, OpenMode.ForWrite);
  93.                 ent.Erase(true);
  94.  
  95.                 tran.Commit();
  96.             }
  97.         }
  98.  
  99.         public static Point3d GetCircleCentre(Database db, ObjectId circleId)
  100.         {
  101.             Point3d pt = new Point3d();
  102.  
  103.             using (Transaction tran = db.TransactionManager.StartTransaction())
  104.             {
  105.                 Circle c = tran.GetObject(circleId, OpenMode.ForRead) as Circle;
  106.                 if (c != null)
  107.                     pt = c.Center;
  108.                 else
  109.                     throw new ArgumentException("Entity is not a circle.");
  110.  
  111.                 tran.Commit();
  112.             }
  113.  
  114.             return pt;
  115.         }
  116.  
  117.         public static void HighlightEntities(
  118.             Database db, List<ObjectId> entIds, bool highlight)
  119.         {
  120.             using (Transaction tran =
  121.                 db.TransactionManager.StartTransaction())
  122.             {
  123.                 foreach (var id in entIds)
  124.                 {
  125.                     Entity ent = (Entity)tran.GetObject(id, OpenMode.ForWrite);
  126.  
  127.                     if (highlight)
  128.                         ent.Highlight();
  129.                     else
  130.                         ent.Unhighlight();
  131.                 }
  132.  
  133.                 tran.Commit();
  134.             }
  135.         }
  136.     }
  137. }

With all required Xdata and AutoCAD manipulation tool available, I was ready to create the Jig. Here are what I wanted to achieve:
  • When user picks the circle to move, the circle and all lines linking from/to it would be highlighted
  • When user moves mouse cursor, a set of ghost circle and the lines move with the mouse cursor
  • After user picks the moving destination point, the select circle is moved to user selected point, and all lines that link from/to this circle will be modified of their start/end points, so that they would start/end properly with the moved circle and still linked to/from other circles
Here is the Jig class:

Code Snippet
  1. using System.Collections.Generic;
  2. using Autodesk.AutoCAD.ApplicationServices;
  3. using Autodesk.AutoCAD.DatabaseServices;
  4. using Autodesk.AutoCAD.EditorInput;
  5. using Autodesk.AutoCAD.Geometry;
  6. using Autodesk.AutoCAD.GraphicsInterface;
  7.  
  8. namespace LinkedObjects
  9. {
  10.     public class LinkedCircleJig : DrawJig
  11.     {
  12.         private Document _dwg;
  13.         private Editor _ed;
  14.         private Database _db;
  15.         private ObjectId _circleId;
  16.         private List<ObjectId> _fromLineIds;
  17.         private List<ObjectId> _toLineIds;
  18.         private Point3d _basePoint;
  19.         private Point3d _currentPoint;
  20.         private Point3d _prevPoint;
  21.         private bool _cancelled = false;
  22.  
  23.         private Circle _visualCircle = null;
  24.         private List<Line> _fromVisualLines = new List<Line>();
  25.         private List<Line> _toVisualLines = new List<Line>();
  26.         private int _visualColorIndex = 1;
  27.  
  28.         public LinkedCircleJig(Document dwg, ObjectId circleId)
  29.         {
  30.             _dwg = dwg;
  31.             _ed = dwg.Editor;
  32.             _db = dwg.Database;
  33.  
  34.             _circleId = circleId;
  35.             LinkInfoXDataUtil.GetCirleLink(
  36.                 _db, _circleId, out _fromLineIds, out _toLineIds);
  37.  
  38.             _basePoint = CommonUtil.GetCircleCentre(_db, circleId);
  39.         }
  40.  
  41.         public void DragLinkedCircle()
  42.         {
  43.             _cancelled = false;
  44.  
  45.             try
  46.             {
  47.                 CreateVisualEntities();
  48.  
  49.                 _currentPoint = _basePoint;
  50.                 _prevPoint = _basePoint;
  51.  
  52.                 HighlightEntities(true);
  53.  
  54.                 _ed.Drag(this);
  55.  
  56.                 if (!_cancelled)
  57.                 {
  58.                     using (Transaction tran =
  59.                         _db.TransactionManager.StartTransaction())
  60.                     {
  61.                         //Move circle
  62.                         Vector3d displacement =
  63.                         _basePoint.GetVectorTo(_currentPoint);
  64.  
  65.                         Circle c = (Circle)tran.GetObject(
  66.                             _circleId, OpenMode.ForWrite);
  67.                         c.TransformBy(
  68.                             Matrix3d.Displacement(displacement));
  69.  
  70.                         ObjectId fCircleId;
  71.                         ObjectId tCircleId;
  72.                         
  73.                         Point3d pt;
  74.                         double dist;
  75.  
  76.                         //update FROM lines
  77.                         foreach (var id in _fromLineIds)
  78.                         {
  79.                             Line l = (Line)tran.GetObject(
  80.                                 id, OpenMode.ForWrite);
  81.  
  82.                             //get its TO circle
  83.                             LinkInfoXDataUtil.GetLineLink(
  84.                                 _db, id, out fCircleId, out tCircleId);
  85.  
  86.                             Circle tCircle = (Circle)tran.GetObject(
  87.                                 tCircleId, OpenMode.ForRead);
  88.  
  89.                             l.StartPoint = c.Center;
  90.                             l.EndPoint = tCircle.Center;
  91.  
  92.                             //Shrink line's length
  93.                             pt = l.GetPointAtDist(c.Radius);
  94.                             l.StartPoint = pt;
  95.  
  96.                             dist = l.Length - tCircle.Radius;
  97.                             pt = l.GetPointAtDist(dist);
  98.                             l.EndPoint = pt;
  99.                         }
  100.  
  101.                         //Update TO lines
  102.                         foreach (var id in _toLineIds)
  103.                         {
  104.                             Line l = (Line)tran.GetObject(
  105.                                 id, OpenMode.ForWrite);
  106.  
  107.                             //get its TO circle
  108.                             LinkInfoXDataUtil.GetLineLink(
  109.                                 _db, id, out fCircleId, out tCircleId);
  110.  
  111.                             Circle fCircle = (Circle)tran.GetObject(
  112.                                 fCircleId, OpenMode.ForRead);
  113.  
  114.                             l.StartPoint = fCircle.Center;
  115.                             l.EndPoint = c.Center;
  116.  
  117.                             //Shrink line's length
  118.                             pt = l.GetPointAtDist(fCircle.Radius);
  119.                             l.StartPoint = pt;
  120.  
  121.                             dist = l.Length - c.Radius;
  122.                             pt = l.GetPointAtDist(dist);
  123.                             l.EndPoint = pt;
  124.                         }
  125.  
  126.                         tran.Commit();
  127.                     }
  128.                 }
  129.             }
  130.             catch
  131.             {
  132.                 throw;
  133.             }
  134.             finally
  135.             {
  136.                 HighlightEntities(false);
  137.                 DisposeVisualEntities();
  138.             }
  139.         }
  140.  
  141.         #region Jig method overrides
  142.         
  143.         protected override bool WorldDraw(WorldDraw draw)
  144.         {
  145.             draw.Geometry.Draw(_visualCircle);
  146.  
  147.             foreach (var e in _fromVisualLines)
  148.                 draw.Geometry.Draw(e);
  149.  
  150.             foreach (var e in _toVisualLines)
  151.                 draw.Geometry.Draw(e);
  152.  
  153.             return true;
  154.         }
  155.  
  156.         protected override SamplerStatus Sampler(JigPrompts prompts)
  157.         {
  158.             JigPromptPointOptions jigOpt =
  159.                 new JigPromptPointOptions();
  160.  
  161.             jigOpt.UserInputControls =
  162.                 UserInputControls.Accept3dCoordinates |
  163.                 UserInputControls.NoZeroResponseAccepted |
  164.                 UserInputControls.NoDwgLimitsChecking;
  165.             jigOpt.BasePoint = _basePoint;
  166.             jigOpt.UseBasePoint = true;
  167.             jigOpt.Cursor = CursorType.RubberBand;
  168.             jigOpt.Message = "\nMove the linked circle to picked point: ";
  169.  
  170.             PromptPointResult res = prompts.AcquirePoint(jigOpt);
  171.  
  172.             if (res.Status == PromptStatus.Cancel)
  173.             {
  174.                 return SamplerStatus.Cancel;
  175.             }
  176.             else
  177.             {
  178.                 _currentPoint = res.Value;
  179.  
  180.                 if (_currentPoint == _prevPoint)
  181.                     return SamplerStatus.NoChange;
  182.                 else
  183.                 {
  184.                     //Update location of visual circle
  185.                     Vector3d displacement =
  186.                         _prevPoint.GetVectorTo(_currentPoint);
  187.  
  188.                     _visualCircle.TransformBy(
  189.                         Matrix3d.Displacement(displacement));
  190.  
  191.                     //Update each FROM visual line
  192.                     foreach (var l in _fromVisualLines)
  193.                     {
  194.                         l.StartPoint = _currentPoint;
  195.                     }
  196.  
  197.                     //Update each TO visual line
  198.                     foreach (var l in _toVisualLines)
  199.                     {
  200.                         l.EndPoint = _currentPoint;
  201.                     }
  202.  
  203.                     _prevPoint = _currentPoint;
  204.                     return SamplerStatus.OK;
  205.                 }
  206.             }
  207.         }
  208.  
  209.         #endregion
  210.  
  211.         #region private methods
  212.  
  213.         private void CreateVisualEntities()
  214.         {
  215.             using (Transaction tran =
  216.                 _db.TransactionManager.StartTransaction())
  217.             {
  218.                 //Create visual Circle
  219.                 Circle c = (Circle)tran.GetObject(
  220.                     _circleId, OpenMode.ForRead);
  221.                 _visualCircle = c.Clone() as Circle;
  222.                 _visualCircle.SetDatabaseDefaults(_db);
  223.                 _visualCircle.ColorIndex = _visualColorIndex;
  224.  
  225.                 Point3d fromPt;
  226.                 Point3d toPt;
  227.  
  228.                 //Create FROM lines
  229.                 foreach (var id in _fromLineIds)
  230.                 {
  231.                     Line l = (Line)tran.GetObject(id, OpenMode.ForRead);
  232.  
  233.                     Line vLine = l.Clone() as Line;
  234.                     vLine.SetDatabaseDefaults(_db);
  235.                     vLine.ColorIndex = _visualColorIndex;
  236.  
  237.                     //Stretch the line to FROM/TO circles' centre points
  238.                     LinkInfoXDataUtil.GetLinkedCircleCentres(
  239.                         _db, id, out fromPt, out toPt);
  240.  
  241.                     vLine.StartPoint = fromPt;
  242.                     vLine.EndPoint = toPt;
  243.  
  244.                     _fromVisualLines.Add(vLine);
  245.                 }
  246.  
  247.                 //Create TO lines
  248.                 foreach (var id in _toLineIds)
  249.                 {
  250.                     Line l = (Line)tran.GetObject(id, OpenMode.ForRead);
  251.  
  252.                     Line vLine = l.Clone() as Line;
  253.                     vLine.SetDatabaseDefaults(_db);
  254.                     vLine.ColorIndex = _visualColorIndex;
  255.  
  256.                     //Stretch the line to FROM/TO circles' centre points
  257.                     LinkInfoXDataUtil.GetLinkedCircleCentres(
  258.                         _db, id, out fromPt, out toPt);
  259.  
  260.                     vLine.StartPoint = fromPt;
  261.                     vLine.EndPoint = toPt;
  262.  
  263.                     _toVisualLines.Add(vLine);
  264.                 }
  265.             }
  266.         }
  267.  
  268.         private void HighlightEntities(bool highlight)
  269.         {
  270.             List<ObjectId> ents = new List<ObjectId>();
  271.             ents.Add(_circleId);
  272.             ents.AddRange(_fromLineIds);
  273.             ents.AddRange(_toLineIds);
  274.  
  275.             CommonUtil.HighlightEntities(_db, ents, highlight);
  276.         }
  277.  
  278.         private void DisposeVisualEntities()
  279.         {
  280.             if (_visualCircle != null)
  281.             {
  282.                 _visualCircle.Dispose();
  283.                 _visualCircle = null;
  284.             }
  285.  
  286.             foreach (var ent in _fromVisualLines)
  287.                 ent.Dispose();
  288.  
  289.             _fromVisualLines.Clear();
  290.  
  291.             foreach (var ent in _toVisualLines)
  292.                 ent.Dispose();
  293.  
  294.             _toVisualLines.Clear();
  295.         }
  296.  
  297.         #endregion
  298.     }
  299. }

Finally, with all the required functionality available in the classes, it is time to put them together, which leads to another class ObjectLinker:

Code Snippet
  1. using Autodesk.AutoCAD.ApplicationServices;
  2. using Autodesk.AutoCAD.DatabaseServices;
  3. using Autodesk.AutoCAD.EditorInput;
  4.  
  5. namespace LinkedObjects
  6. {
  7.     public class ObjectLinker
  8.     {
  9.         private Document _dwg;
  10.         private Database _db;
  11.         private Editor _ed;
  12.  
  13.         public ObjectLinker(Document dwg)
  14.         {
  15.             _dwg = dwg;
  16.             _db = dwg.Database;
  17.             _ed = _dwg.Editor;
  18.         }
  19.  
  20.         //The method does not check whether there is already
  21.         //an existing linking line between the two circles
  22.         public bool AddLinkBetweenCircles()
  23.         {
  24.             //Pick linking circle
  25.             ObjectId fromCircleId;
  26.             if (!CommonUtil.PickEntity(_ed, typeof(Circle),
  27.                 "\nPick a circle (or press any key to exit): ",
  28.                 "Not a circle!", out fromCircleId))
  29.             {
  30.                 CommonUtil.PrintCancelMessage();
  31.                 return false;
  32.             }
  33.  
  34.             //pick circle to be linked
  35.             ObjectId toCircleId;
  36.             if (!CommonUtil.PickEntity(_ed, typeof(Circle),
  37.                 "\nPick a circle (or press any key to exit): ",
  38.                 "Not a circle!", out toCircleId))
  39.             {
  40.                 CommonUtil.PrintCancelMessage();
  41.                 return false;
  42.             }
  43.  
  44.             //Draw line between the circles
  45.             ObjectId lineId = CommonUtil.DrawLineBetweenCircles(
  46.                 _db, fromCircleId, toCircleId);
  47.  
  48.             //Set link XData
  49.             LinkInfoXDataUtil.SetLink(_db, fromCircleId, toCircleId, lineId);
  50.  
  51.             _ed.WriteMessage(
  52.                 "\nLink between the 2 picked circles has been established.");
  53.  
  54.             return true;
  55.         }
  56.  
  57.         public void RemoveLinkBetweenCircles(bool eraseLineEntity)
  58.         {
  59.             //Pick line
  60.             ObjectId lineId;
  61.             if (!CommonUtil.PickEntity(_ed, typeof(Line),
  62.                 "\nPick linking line: ", "Not a line!", out lineId))
  63.             {
  64.                 CommonUtil.PrintCancelMessage();
  65.                 return;
  66.             }
  67.  
  68.             LinkInfoXDataUtil.RemoveLink(_db, lineId);
  69.  
  70.             if (eraseLineEntity)
  71.             {
  72.                 CommonUtil.EraseEntity(_db, lineId);
  73.             }
  74.         }
  75.  
  76.         public void MoveCircle()
  77.         {
  78.             //Pick a linked circle
  79.             PromptEntityOptions opt = new
  80.                 PromptEntityOptions("\nPick a linked circle:");
  81.             opt.SetRejectMessage("Invalid pick: must be a circle.");
  82.             opt.AddAllowedClass(typeof(Circle), true);
  83.             PromptEntityResult res = _ed.GetEntity(opt);
  84.             if (res.Status == PromptStatus.OK)
  85.             {
  86.                 LinkedCircleJig jig = new LinkedCircleJig(_dwg, res.ObjectId);
  87.                 jig.DragLinkedCircle();
  88.             }
  89.         }
  90.     }
  91. }

By now, the only thing left is to create commands for users to do what they want:

Code Snippet
  1. using System;
  2. using Autodesk.AutoCAD.ApplicationServices;
  3. using Autodesk.AutoCAD.DatabaseServices;
  4. using Autodesk.AutoCAD.EditorInput;
  5. using Autodesk.AutoCAD.Runtime;
  6.  
  7. [assembly: CommandClass(typeof(LinkedObjects.MyCommands))]
  8.  
  9. namespace LinkedObjects
  10. {
  11.     public class MyCommands
  12.     {
  13.         private ObjectLinker linker = null;
  14.  
  15.         [CommandMethod("LinkMyCircles")]
  16.         public void LinkCircles()
  17.         {
  18.             Document dwg = Application.DocumentManager.MdiActiveDocument;
  19.             Editor ed = dwg.Editor;
  20.  
  21.             if (linker == null) linker = new ObjectLinker(dwg);
  22.  
  23.             try
  24.             {
  25.                 while (true)
  26.                 {
  27.                     if (!linker.AddLinkBetweenCircles())
  28.                         break;
  29.                 }
  30.             }
  31.             catch (System.Exception ex)
  32.             {
  33.                 CommonUtil.PrintCancelMessage(ex.Message);
  34.             }
  35.         }
  36.  
  37.         [CommandMethod("MoveMyCircle")]
  38.         public void MoveLinkedCircle()
  39.         {
  40.             Document dwg = Application.DocumentManager.MdiActiveDocument;
  41.             Editor ed = dwg.Editor;
  42.  
  43.             if (linker == null) linker = new ObjectLinker(dwg);
  44.  
  45.             try
  46.             {
  47.                 linker.MoveCircle();
  48.             }
  49.             catch (System.Exception ex)
  50.             {
  51.                 CommonUtil.PrintCancelMessage(ex.Message);
  52.             }
  53.         }
  54.  
  55.         [CommandMethod("DelinkMyCircle")]
  56.         public void DelinkCircles()
  57.         {
  58.             Document dwg = Application.DocumentManager.MdiActiveDocument;
  59.             Editor ed = dwg.Editor;
  60.  
  61.             if (linker == null) linker = new ObjectLinker(dwg);
  62.  
  63.             try
  64.             {
  65.                 linker.RemoveLinkBetweenCircles(true);
  66.             }
  67.             catch (System.Exception ex)
  68.             {
  69.                 CommonUtil.PrintCancelMessage(ex.Message);
  70.             }
  71.         }
  72.     }
  73. }

This a quite long post with a lot of code in order to demonstrate a workable operation. I did not try my best effort to make the code more as concise as it could be. As usual, I created a video clip here to show the code in action.
Some points of interest:
  • I could have used a polyline to link 2 circles, so that I can make a segment of the polyline to look like an arrow to indicate the direction of the link. I could have also used DrawableOverrule to make the linking like to show an arrow
  • As I commented in the code, I did not check a link between 2 circles has already existed before adding link
  • It is obvious that standard AutoCAD editing commands, such as MOVE/RORATE/STRETCH...could easily destroy the links visually. Here is when ObjectOverrule could help. One of my previous post here can be used to prevent linked circles/lines from being changed. I might post an update to this post to incorporate the ObjectOverrule into this project later, if I can manage some time available.

Bug Fix Update:

There is a bug in class LinkedCircleJig: following code should be added between line 173 and 174:

_cancel=true;

Wednesday, June 6, 2012

Conditionally Replace a Command with a Custom One

Very often we create our own custom command via macro script, lisp, VBA, ... to let AutoCAD do things in the way we desire. Sometimes, we even want to redefine an existing command, so that the same command would do thing differently. For example, we may want the "SAVE" command always zoom the current view to its extents before saving. It is quite easy to redefine an existing command with a lisp routine (defun C:cmdName()...). If "cmdName" in the lisp routine is the same as any AutoCAD built-in command name, once the lisp routine is loaded, the AutoCAD built-in command would be replaced by the one defined in the lisp routine. There may also be cases that we only want to run an alternative command instead of AutoCAD build-in command under certain condition. That is, when a standard command is issued, we want a process starts to check if certain condition is met. If yes, currently issued command is stopped and an alternative command runs; otherwise, the standard command continues.

In this post, I demonstrate a way to run an alternative command in the place of standard command under certain condition(s), using .NET API.

The ApplicationServices.DocumentCollection class exposes 2 events that can be used for this purpose: DocumentLockModeChanged and DocumentLockModeChangeVetoed. That is, whenever a command is issued in AutoCAD, DocumentLockModeChanged event is fired. The DocumentLockModeChanged event handler also allows the command that causes the DocumentLockModeChanged event to be vetoed. Subsequently, if the command being vetoed (more precisely speaking, the DocumentLockModeChange being vetoed), DocumentLockModeChangeVetoed event fires, which provides us an opportunity to do something else by handling this event.

In order to generalize the way to deal with using multiple custom commands that would replace standard commands under different conditions, I define an interface like this:

Code Snippet
  1. namespace RunAlternativeCommand
  2. {
  3.     public enum CommandComparisonOption
  4.     {
  5.         CommandNameEquals=0,
  6.         CommandNameContains=1,
  7.     }
  8.  
  9.     public interface IAlternativeCommandOption
  10.     {
  11.         string[] TargetCommand { get; }
  12.         CommandComparisonOption ComparisonOption { get; }
  13.         string AlternativeCommand { get; }
  14.         bool PickFirstRequired { get; }
  15.         bool AlternativeCommandApplied();
  16.     }
  17. }

Following are 2 classes that implement the interface.

Class "AlternativeSaveCommandOption". It vetoes command "SAVE" and "QSAVE" in certain condition, and run a custom command. The condition can be anything as user needs. For example, if a specific title block exists in a drawing (assuming the title block is only inserted when the drafting work has been completed) and/or a particular attribute of the title block has been set, we want the title block to be updated with data from external data source whenever the drawing is saved. Here is the code:

Code Snippet
  1. namespace RunAlternativeCommand
  2. {  
  3.     public class AlternativeSaveCommandOption
  4.         : IAlternativeCommandOption
  5.     {
  6.         private string[] _tagetCommand;
  7.         private string _alternativeCommand;
  8.  
  9.         public AlternativeSaveCommandOption(string altCmd)
  10.         {
  11.             _tagetCommand = new string[]
  12.             {
  13.                 "SAVE", "QSAVE"
  14.             };
  15.             _alternativeCommand = altCmd;
  16.         }
  17.  
  18.         #region IAlternativeCommandOption Members
  19.  
  20.         public string[] TargetCommand
  21.         {
  22.             get { return _tagetCommand; }
  23.         }
  24.  
  25.         public CommandComparisonOption ComparisonOption
  26.         {
  27.             get { return CommandComparisonOption.CommandNameContains; }
  28.         }
  29.  
  30.         public string AlternativeCommand
  31.         {
  32.             get { return _alternativeCommand; }
  33.         }
  34.  
  35.         public bool AlternativeCommandApplied()
  36.         {
  37.             //Check the drawing to see if we want to run alternative saving.
  38.             //For example, we can check if a particular title block has been
  39.             //inserted or its particular attribute has been set. If yes,
  40.             //we want to use alternative saving process to
  41.             // 1. update the title block with data from external data source
  42.             // 2. save the drawing.
  43.  
  44.             return true;
  45.         }
  46.  
  47.         public bool PickFirstRequired
  48.         {
  49.             get { return true; }
  50.         }
  51.  
  52.         #endregion
  53.     }  
  54. }

Class "AlternativeRorateLineCommandOption". The condition for it to veto the built-in "ROTATE" command is when "ROTATE" command is issued against a pre-selected LINE entity (i.e. PickFirst mode is enabled). Here is the code:

Code Snippet
  1. using Autodesk.AutoCAD.ApplicationServices;
  2. using Autodesk.AutoCAD.EditorInput;
  3. using Autodesk.AutoCAD.DatabaseServices;
  4.  
  5. namespace RunAlternativeCommand
  6. {
  7.     public class AlternativeRotateLineCommandOption
  8.         : IAlternativeCommandOption
  9.     {
  10.         private string[] _tagetCommand;
  11.         private string _alternativeCommand;
  12.  
  13.         public AlternativeRotateLineCommandOption(string altCmd)
  14.         {
  15.             _tagetCommand = new string[] { "ROTATE" };
  16.             _alternativeCommand = altCmd;
  17.         }
  18.  
  19.         #region IAlternativeCommandOption Members
  20.  
  21.         public string[] TargetCommand
  22.         {
  23.             get { return _tagetCommand; }
  24.         }
  25.  
  26.         public CommandComparisonOption ComparisonOption
  27.         {
  28.             get { return CommandComparisonOption.CommandNameEquals; }
  29.         }
  30.  
  31.         public string AlternativeCommand
  32.         {
  33.             get { return _alternativeCommand; }
  34.         }
  35.  
  36.         public bool AlternativeCommandApplied()
  37.         {
  38.             //Since PickFirst is required,
  39.             //test if there is implied SelectionSet
  40.             ObjectIdCollection selectedIds = GetImpliedSelectionSet();
  41.  
  42.             if (selectedIds.Count > 0)
  43.             {
  44.                 foreach (ObjectId id in selectedIds)
  45.                 {
  46.                     //If the selected entities include LINE
  47.                     //then the alternative command applies
  48.                     if (id.ObjectClass.DxfName.ToUpper() == "LINE")
  49.                     {
  50.                         return true;
  51.                     }
  52.                 }
  53.             }
  54.             return false;
  55.         }
  56.  
  57.         public bool PickFirstRequired
  58.         {
  59.             get { return true; }
  60.         }
  61.  
  62.         #endregion
  63.  
  64.         #region private methods
  65.  
  66.         private ObjectIdCollection GetImpliedSelectionSet()
  67.         {
  68.             Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
  69.  
  70.             PromptSelectionResult res = ed.SelectImplied();
  71.  
  72.             if (res.Status == PromptStatus.OK)
  73.             {
  74.                 return new ObjectIdCollection(res.Value.GetObjectIds());
  75.             }
  76.  
  77.             return new ObjectIdCollection();
  78.         }
  79.  
  80.         #endregion
  81.     }
  82. }

We can have define as many classes that implement the interface "IAlternativeCommandOption" as we need to target different existing/built-in commands. The implementation of AlternativeCommandApplied() method allows us to set condition(s) so that the method would return true/false as desired.

Here are 2 custom commands that would be used in place when built-in commands being vetoed:

Code Snippet
  1. using System;
  2. using Autodesk.AutoCAD.ApplicationServices;
  3. using Autodesk.AutoCAD.DatabaseServices;
  4. using Autodesk.AutoCAD.Runtime;
  5. using Autodesk.AutoCAD.EditorInput;
  6. using Autodesk.AutoCAD.Geometry;
  7.  
  8. [assembly: CommandClass(typeof(RunAlternativeCommand.AlternativeCommands))]
  9.  
  10. namespace RunAlternativeCommand
  11. {
  12.     public class AlternativeCommands
  13.     {
  14.         #region RotateLine alternative command
  15.         
  16.         [CommandMethod("RotateLine",CommandFlags.UsePickSet)]
  17.         public static void MyRotateLineCommand()
  18.         {
  19.             Document dwg = Application.DocumentManager.MdiActiveDocument;
  20.             Editor ed = dwg.Editor;
  21.  
  22.             PromptSelectionResult res = ed.SelectImplied();
  23.             if (res.Status != PromptStatus.OK) return;
  24.  
  25.             ObjectId[] ids = res.Value.GetObjectIds();
  26.  
  27.             using (Transaction tran =
  28.                 dwg.Database.TransactionManager.StartTransaction())
  29.             {
  30.                 RotateLines(ids, tran);
  31.  
  32.                 tran.Commit();
  33.             }
  34.         }
  35.  
  36.         private static void RotateLines(ObjectId[] entIds, Transaction tran)
  37.         {
  38.             foreach (ObjectId id in entIds)
  39.             {
  40.                 Line line = tran.GetObject(id, OpenMode.ForWrite) as Line;
  41.                 if (line != null)
  42.                 {
  43.                     RotateLine(line);
  44.                 }
  45.             }
  46.         }
  47.  
  48.         private static void RotateLine(Line line)
  49.         {
  50.             //Do whatever we want. For example, we rotate line 90 degree
  51.             //with its start point as rotating base point
  52.             Point3d pt = line.StartPoint;
  53.             Matrix3d mt = Matrix3d.Rotation(Math.PI / 2, Vector3d.ZAxis, pt);
  54.             line.TransformBy(mt);
  55.         }
  56.  
  57.         #endregion
  58.  
  59.         #region Save alternative command
  60.  
  61.         [CommandMethod("SaveTB")]
  62.         public static void DoMySave()
  63.         {
  64.             Document dwg = Application.DocumentManager.MdiActiveDocument;
  65.             Editor ed = dwg.Editor;
  66.  
  67.             ed.WriteMessage(
  68.                 "\nSearching for title block...");
  69.             ed.WriteMessage(
  70.                 "\nRetrieving title block information from database...");
  71.             ed.WriteMessage("\nUpdate title block...");
  72.             ed.WriteMessage("\nSaving current drawing...");
  73.  
  74.             //Finally, save the drawing
  75.             dwg.Database.SaveAs(dwg.Name, DwgVersion.Current);
  76.  
  77.             ed.WriteMessage("\nDrawing is saved by custom saving process!\n");
  78.         }
  79.  
  80.         #endregion
  81.     }
  82. }

Finally I implement the IExtensionApplication interface to put everything together into work:

Code Snippet
  1. using System.Collections.Generic;
  2. using Autodesk.AutoCAD.ApplicationServices;
  3. using Autodesk.AutoCAD.Runtime;
  4.  
  5. [assembly: ExtensionApplication(typeof(
  6.     RunAlternativeCommand.AlternativeCommandInitializer))]
  7.  
  8. namespace RunAlternativeCommand
  9. {
  10.     public class AlternativeCommandInitializer :
  11.         IExtensionApplication
  12.     {
  13.         private static DocumentCollection docs;
  14.         private List<IAlternativeCommandOption> _altCmds;
  15.         private bool _runAltCmd = false;
  16.         private string _altCmdName = "";
  17.         private string _dwgName = "";
  18.  
  19.         public void Initialize()
  20.         {
  21.             //Initialize alternative commands
  22.             InitializeAltCmds();
  23.  
  24.             //Add event handlers to intercept commands
  25.             //so that particular command can be vetoed
  26.             //and alternative command can be run, instead.
  27.             docs = Application.DocumentManager;
  28.  
  29.             docs.DocumentLockModeChanged +=
  30.                 new DocumentLockModeChangedEventHandler(
  31.                 docs_DocumentLockModeChanged);
  32.  
  33.             docs.DocumentLockModeChangeVetoed +=
  34.                 new DocumentLockModeChangeVetoedEventHandler(
  35.                     docs_DocumentLockModeChangeVetoed);
  36.  
  37.             docs.MdiActiveDocument.Editor.WriteMessage(
  38.                 "\nAlternative commands loaded\n");
  39.         }
  40.  
  41.         public void Terminate()
  42.         {
  43.             
  44.         }
  45.  
  46.         #region initialize alternative commands
  47.         
  48.         private void InitializeAltCmds()
  49.         {
  50.             _altCmds = new List<IAlternativeCommandOption>();
  51.  
  52.             AddAltRotateLineCommand();
  53.             AddAltSaveCommand();
  54.         }
  55.  
  56.         private void AddAltRotateLineCommand()
  57.         {
  58.             AlternativeRotateLineCommandOption opt =
  59.                 new AlternativeRotateLineCommandOption("RotateLine");
  60.  
  61.             _altCmds.Add(opt);
  62.         }
  63.  
  64.         private void AddAltSaveCommand()
  65.         {
  66.             AlternativeSaveCommandOption opt =
  67.                 new AlternativeSaveCommandOption("SaveTB");
  68.  
  69.             _altCmds.Add(opt);
  70.         }
  71.  
  72.         #endregion
  73.  
  74.         #region Handle DocumentLockModeChanged/DocumentLockModeChangeVetoed
  75.  
  76.         private void docs_DocumentLockModeChangeVetoed(object sender,
  77.             DocumentLockModeChangeVetoedEventArgs e)
  78.         {
  79.             if (!_runAltCmd || !_dwgName.Equals(
  80.                 e.Document.Name,
  81.                 System.StringComparison.InvariantCultureIgnoreCase))
  82.                 return;
  83.  
  84.             //run alternative command
  85.             Document doc = Application.DocumentManager.MdiActiveDocument;
  86.  
  87.             if (!string.IsNullOrEmpty(_altCmdName))
  88.             {
  89.                 doc.SendStringToExecute(
  90.                     _altCmdName + " ", true, false, true);
  91.             }
  92.  
  93.             _runAltCmd = false;
  94.         }
  95.  
  96.         private void docs_DocumentLockModeChanged(object sender,
  97.             DocumentLockModeChangedEventArgs e)
  98.         {
  99.             //Check lock mode first
  100.             if (e.CurrentMode != DocumentLockMode.Write &&
  101.                 e.CurrentMode!=DocumentLockMode.ExclusiveWrite) return;
  102.  
  103.             _runAltCmd = false;
  104.             _dwgName = e.Document.Name;
  105.  
  106.             //Loop through alternative command options
  107.             //to see if any alternative command is set to
  108.             //replace current command
  109.             foreach (var cmdOpt in _altCmds)
  110.             {
  111.                 bool match = false;
  112.  
  113.                 CommandComparisonOption comp = cmdOpt.ComparisonOption;
  114.                 
  115.                 foreach (var opt in cmdOpt.TargetCommand)
  116.                 {
  117.                     switch (comp)
  118.                     {
  119.                         case CommandComparisonOption.CommandNameContains:
  120.                             if (e.GlobalCommandName.ToUpper().
  121.                                 Contains(opt.ToUpper()) &&
  122.                                 e.GlobalCommandName.ToUpper()!=
  123.                                 cmdOpt.AlternativeCommand.ToUpper())
  124.                             {
  125.                                 match = true;
  126.                             }
  127.                             break;
  128.                         default:
  129.                             if (e.GlobalCommandName.ToUpper()
  130.                                 == opt.ToUpper() &&
  131.                                 e.GlobalCommandName.ToUpper()!=
  132.                                 cmdOpt.AlternativeCommand.ToUpper())
  133.                             {
  134.                                 match = true;
  135.                             }
  136.                             break;
  137.                     }
  138.  
  139.                     if (match) break;
  140.                 }
  141.  
  142.                 //When the current command is a targeted command
  143.                 if (match)
  144.                 {
  145.                     //If the condition is met
  146.                     if (cmdOpt.AlternativeCommandApplied())
  147.                     {
  148.                         //Veto to current command and set
  149.                         //the alternative command to be run
  150.                         _altCmdName = cmdOpt.AlternativeCommand;
  151.                         _runAltCmd = true;
  152.  
  153.                         e.Veto();
  154.                         return;
  155.                     }
  156.                 }
  157.             }
  158.         }
  159.  
  160.         #endregion
  161.     }
  162. }

Compile the code the load it into AutoCAD. let's try out the ROTATE command against one or more LINE entity or entities. If the ROTATE command is issued with LINE entity or entities being pre-selected, we can see the custom command "RotateLine" runs instead of standard ROTATE command. However, if no LINE entity is pre-selected, ROTATE command proceeds as usual.

Try SAVE/QSAVE command would always trigger custom SAVETB command, because I did not have code to check condition(s) in AlternativeCommandApplied(0 method and it always return "true".

With the code structure showing here, it would be very easy to add more custom commands as conditional alternatives to existing commands: simply create new class that implements IAlternativeCommandOption and corresponding command methods, and then add them into the List collection of the class AlternativeCommandInitializer.

Monday, March 19, 2012

Using ObjectOverrule To Prevent Entity Being Changed

Kean Walmsley has a post on using ObjectOverrule to prevent entity being erased. The solution is surprisingly simple: simply throw an Exception in the overridden Erase() method of the ObjectOverrule. Well, it simple only someone (Kean Walmsley and Stephen Preston) let you know that you can do this.
Well, it turns out that we can do the same thing in ObjectOverrule.Open() method to prevent entity being changed.
Here I show some code first and then discuss some interesting issues with this approach.

Let's assume some scenario: a drawing has a particular block inserted, say, a title block with certain attribute. Once the block is inserted and its attribute value is set, we do not want user to change it at all; or it should only be changed programmatically so the attribute value would be kept in sync with data in CAD data source, such as enterprise production database. In my code, the ObjectOverrule will be only applicable to a BlockReference entity if the block reference has an attribute tagged as "ABC".

Here is the code of the ObjectOverrule:

Code Snippet
  1. using Autodesk.AutoCAD.ApplicationServices;
  2. using Autodesk.AutoCAD.DatabaseServices;
  3. using Autodesk.AutoCAD.Runtime;
  4. using Autodesk.AutoCAD.EditorInput;
  5.  
  6. namespace EntityModifiedOverrule
  7. {
  8.     public class EntChangeVetoOverrule : ObjectOverrule
  9.     {
  10.         private static EntChangeVetoOverrule _instance = null;
  11.         private bool _overruling;
  12.  
  13.         private EntChangeVetoOverrule()
  14.         {
  15.             _overruling = Overrule.Overruling;
  16.         }
  17.  
  18.         public static EntChangeVetoOverrule Instance
  19.         {
  20.             get
  21.             {
  22.                 if (_instance == null)
  23.                     _instance = new EntChangeVetoOverrule();
  24.  
  25.                 return _instance;
  26.             }
  27.         }
  28.  
  29.         public void StartOverrule()
  30.         {
  31.             Overrule.AddOverrule(RXClass.GetClass(
  32.                 typeof(BlockReference)), this, false);
  33.             Overrule.Overruling = true;
  34.  
  35.             //This is required in order for
  36.             //overridden IsApplicable() being used
  37.             //as custom overrule filter
  38.             this.SetCustomFilter();
  39.         }
  40.  
  41.         public void StopOverrule()
  42.         {
  43.             Overrule.RemoveOverrule(
  44.                 RXClass.GetClass(typeof(BlockReference)), this);
  45.             Overrule.Overruling = _overruling;
  46.         }
  47.  
  48.         #region override virtue methods
  49.  
  50.         public override bool IsApplicable(RXObject overruledSubject)
  51.         {
  52.             BlockReference bref = overruledSubject as BlockReference;
  53.  
  54.             if (bref == null)
  55.                 return false;
  56.             else
  57.             {
  58.                 bool isTarget = false;
  59.                 using (Transaction tran = bref.Database.
  60.                     TransactionManager.StartOpenCloseTransaction())
  61.                 {
  62.                     foreach (ObjectId id in bref.AttributeCollection)
  63.                     {
  64.                         var attr = (AttributeReference)tran.GetObject(
  65.                             id, OpenMode.ForRead);
  66.                         if (attr.Tag.ToUpper() == "ABC")
  67.                         {
  68.                             isTarget = true;
  69.                             break;
  70.                         }
  71.                     }
  72.  
  73.                     tran.Commit();
  74.                 }
  75.  
  76.                 return isTarget;
  77.             }
  78.         }
  79.  
  80.         public override void Open(DBObject dbObject, OpenMode mode)
  81.         {
  82.             Editor ed =
  83.                 Application.DocumentManager.MdiActiveDocument.Editor;
  84.  
  85.             if (mode == OpenMode.ForWrite)
  86.             {
  87.                 ed.WriteMessage("\nEntity open for writing: {0}. Denied!",
  88.                     dbObject.GetType().Name);
  89.                 throw new Autodesk.AutoCAD.Runtime.Exception(
  90.                     ErrorStatus.NotApplicable);
  91.             }
  92.             else
  93.             {
  94.                 base.Open(dbObject, mode);
  95.             }
  96.         }
  97.  
  98.         #endregion
  99.     }
  100. }


Here is the code to turn the ObjectOverrule on or off:

Code Snippet
  1. using Autodesk.AutoCAD.ApplicationServices;
  2. using Autodesk.AutoCAD.Runtime;
  3. using Autodesk.AutoCAD.EditorInput;
  4.  
  5. [assembly: CommandClass(typeof(EntityModifiedOverrule.MyCommands))]
  6.  
  7. namespace EntityModifiedOverrule
  8. {
  9.     class MyCommands
  10.     {
  11.         private static bool _myOverruleOn = false;
  12.  
  13.         [CommandMethod("MyOV")]
  14.         public static void MyCmd()
  15.         {
  16.             Document doc = Autodesk.AutoCAD.ApplicationServices.
  17.                 Application.DocumentManager.MdiActiveDocument;
  18.             Editor ed = doc.Editor;
  19.  
  20.             if (!_myOverruleOn)
  21.             {
  22.                 EntChangeVetoOverrule.Instance.StartOverrule();
  23.                 ed.WriteMessage("\nVeto Entity Modifying Overrule is on\n");
  24.                 _myOverruleOn = true;
  25.             }
  26.             else
  27.             {
  28.                 EntChangeVetoOverrule.Instance.StopOverrule();
  29.                 ed.WriteMessage("\nVeto Entity Modifying Overrule is off\n");
  30.                 _myOverruleOn = false;
  31.             }
  32.         }
  33.     }
  34. }


The IsApplicable() method is used as custom filter for this ObjectOverrule. In my code, it makes sure the Overrule only applies to a block reference that has an attribute with tag being "ABC". Obviously, one can override IsApplicable method with whatever suitable logic to filter out desirable targeting entities to apply custom Overrule.
As one would notice, in the overridden Open() method, I test the OpenMode parameter, and only when the Open method is called in "ForWrite" mode, an Exception is thrown, which effectively aborted the call to Open(), thus, prevent the entity being modified. The the Exception's construction, I use ErrorStatus.NotApplicable as the constructor's argument, but it can be any other ErrorStatus enum value.

When running the code, I can see, the block can be selected/highlighted, its information shows correctly in the property window. Trying to change something with the block, such attribute value in either attribute editing window, or in property window, nothing would happen. I also cannot erase/move/rotate... the block.

However, there is one thing that is annoying me: if I try to move the block, the block is simply disappeared on the screen. Although I can tel it is still there, but not visible, until I issue "REGEN" command. Of course, the block is still there, not moved, thanks to the Overrule.

Another interesting thing I tried is place nothing in Open method but the "throw...." statement. That is, the Overrule simply prevents any sort of opening regardless the "OpenMode". In this case, the filtered entity (the block with attribute tagged with "ABC" in my case) is simply not selectable, thus, no change can be made to it. Obviously, in this case, the applicable entity will not shown up in property window (since it is not selectable), nor the usual AutoCAD tooltip and/or Quick Properties window would also not shown when the cursor hovers on the entity.

Since my code set custom filter to apply the Overrule only to BlockReference entity, there is a side-effect that may crash AutoCAD: when start AutoCAD's built-in command "INSERT". The reason of the crash, I guess, is due to the the fact that the block has attribute and the command does the process in 2 steps: first a block reference is created and added into current space; then the block reference is opened to in order to add attribute reference. It is the second steps causes the crash because the overrule prevent the block reference object from being opened. So, if you wants to use ObjectOverrule to prevent entity being modified, you need to very carefully consider all possible situations that your Overrule could result in something unintentionally. In my case, I could write my own code to insert the specific block that the Overrule applies to.

Lastly, using ObjectOverrule to prevent entity from being change could be very confusing to untrained CAD user. So, targeted users should be very well informed on this behaviour of your custom CAD tool. Also, the CAD tool with such Overrule should be very well planned as how and when the Overrule is loaded/turned on/off.

There is one thing to be aware of with this "throw an exception" in overriden Open() method approach: you cannot test if your Overrule works or not in Visual Studio's' debugging mode. When the line of code that throws the exception runs, Visual Studio treats the exception as unhandled (as it should), thus the debuggung process stops. One can only test this type of Overrule in normal AutoCAD session without Visual Studio's debugging process attached..

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.