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.

No comments:

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.