Using the Schematic API

Now reading version 16.1. For the latest, read: Using the Schematic API for version 22
 

Parent page: Using the Altium Designer API

Please note that this documentation was last updated for an older version of Altium Designer. While many of the principles and approaches will remain the same, be aware that interfaces, objects, methods, properties, and the like will have changed since then, and will not reflect the entirety of those found in later versions of the software.

Using the Schematic Editor Interfaces

The Schematic API allows a programmer to fetch or modify Schematic objects and their attributes from a Schematic document. The objects shown on a document are stored in its corresponding design database.

The Schematic interfaces exposed by the Schematic editor refer to opened Schematic documents and the objects on them.

An interface is a means of access to an object in memory. To have access to the Schematic server and update Schematic design objects, you need to invoke the SchServer function which extracts the ISch_ServerInterface interface. This is the main interface and contains many interfaces within. With this interface, you can proceed further by iterating for certain PCB objects.

The IPCB_ServerInterface and ISch_Document interfaces are amongst the main interfaces that you deal with when extracting data from a Schematic or Schematic Library document. Below is the simplified Schematic object interface hierarchy:

Simplified Schematic Objects Interfaces hierarchy

ISch_BasicContainer
      ISch_GraphicalObject
            ISch_Arc
                  ISch_EllipticalArc
            ISch_Line
                  ISch_BusEntry
                        ISch_ConnectionLine
            ISch_Polygon
                  ISch_BasicPolyline
                        ISch_Polyline
                        ISch_Bezier
                        ISch_Wire

Main Schematic Interfaces

  • The ISCH_ServerInterface interface is the main interface in the Schematic API. To use Schematic interfaces, you need to obtain the ISch_ServerInterface object by invoking the SchServer function. The ISch_ServerInterface interface is the gateway to fetching other Schematic objects.
  • The ISch_GraphicalObject interface is a generic interface used for all Schematic design object interfaces.
  • The ISch_Document interface points to an existing Schematic document in Altium Designer.

When you need to deal with Schematic design objects in Altium Designer, the starting point is to invoke the SchServer function and with the ISch_ServerInterface interface, you can extract the all other derived schematic interfaces that are exposed from the ISch_ServerInterface interface.

SchServer Function example

If SchServer = Nil Then Exit;
 
If Not Supports (SchServer.GetCurrentSchDocument, ISch_Document, CurrentSheet) Then Exit;
 
ParentIterator := CurrentSheet.SchIterator_Create;
If ParentIterator = Nil Then Exit;

Accessing properties and methods of Schematic Interfaces

For each Schematic object interface, there will be methods and properties listed (not all interfaces will have both methods and properties listed, some will only have methods).

A property of an object interface is like a variable, you get or set a value in a property, but some properties are read-only properties, meaning they can only return values but cannot be set. A property is implemented by its Get and Set methods. For example, the Selection property has two methods Function GetState_Selection : Boolean; and Procedure SetState_Selection(B : Boolean);

Property Values Example

Component.Selection := True      //set the value 
ASelected := Component.Selection //get the value

The ISch_GraphicalObject is the base interface for all descendant Schematic design object interfaces such as ISch_Arc and ISch_Line, therefore all the methods and properties from the base interface are available in the descendant design objects.

For example the Selection property and its associated Function GetState_Selection : Boolean; and Procedure SetState_Selection (B : Boolean); methods declared in the ISch_GraphicalObject interface are inherited in the descendant interfaces such as ISch_Arc and ISch_Line interfaces.

This Selection property is not in the ISch_Arc, but you will notice that the ISch_Arc interface is inherited from the base ISch_GraphicalObject interface and this interface has a Selection property along with its associated methods (GetState function and SetState procedure for example).

If you can't find a method or a property in an object interface that you expect it to be in, then the next step is to look into the base ISch_GraphicalObject interface — this can be used to access most of the objects in Schematic.

Typecasting Schematic Interface Objects

With server development, you need to deal with types of variables and objects. Interface types follow the same rules as class types in variable and value typecasts. Class type expressions can be cast to interface types, for example ISch_Pin(SchPin) provided the SchPin variable implements the interface. With scripts, they are typeless and you normally do not need to type cast objects.

You cannot directly typecast Delphi objects that are not directly implemented as interface objects if these Delphi objects do not have interfaces. For example, this code snippet produces an exception because you are typecasting a Delphi object that does not directly implement the interface.

The solution to this problem is to use the Support keyword as part of Embarcadeo Delphi’s™ VCL library. This Supports keyword checks whether a given object or interface supports a specified interface. You can call this Supports function to check if the Delphi object contains references to interface objects.

Illegal Typecasting in Server Code

SchComponent := CurrentLib.CurrentSchComponent;
If SchComponent = Nil Then Exit;
PinList := GetState_AllPins(SchComponent);
For i := 0 to PinList.Count - 1 do
Begin
    SchPin := ISch_Pin(PinList[i]); // Illegal type casting.
    ShowMessage(SchPin.Designator+':'+SchPin.Name);
End;

Using the Supports Function for Code in Server Projects

SchComponent := CurrentLib.CurrentSchComponent;
If SchComponent = Nil Then Exit;
PinList := GetState_AllPins(SchComponent);
For i := 0 to PinList.Count - 1 do
Begin
    If (Supports(TObject(ISch_Pin(PinList[i]),ISch_Pin, SchPin) Then
            ShowMessage(SchPin.Designator+':'+SchPin.Name);
End;

Another example of the Supports Function for Server Projects

If SchServer = Nil Then Exit;
If Not Supports (SchServer.GetCurrentSchDocument, ISch_Document, CurrentSheet) Then Exit;

The Schematic Database system

The Schematic editor uses a 32-bit database system and stores two types of objects - drawing and electrical objects. The database system has two different data structures which are the flat database and the spatial database. In this secondary database system, each container holds the same object kind, for example the bus entry container consists of a linear list of bus entry objects which are organized by their coordinates.

The type of database is selected automatically depending on how you wish to access schematic objects. Every existing schematic object on a schematic sheet is identified by its TSchObjectHandle value. Each Schematic object wrapped by its interface has an I_ObjectAddress function.

Schematic documents

There are two types of documents in Schematic editor; the Schematic document and the Schematic Library document. Dealing with Schematic documents is straightforward, you obtain the Schematic document in question and then you can add or delete Schematic objects.

The concept of handling a Schematic Library document is a bit more involved as each Schematic symbol (a component with its designator undefined) is part of the one and same Schematic library document and there are library documents within a Schematic library file. Therefore, you need the schematic library container before you can iterate through the symbols of a library or add/delete symbols.

Loading Schematic or Library documents in Altium Designer

There are other situations when you need to programmatically open a specific document. This is facilitated using the Client.OpenDocument and Client.ShowDocument methods.

Opening a text document, you pass in the ‘Text’ string along with the full file name string.  For Schematic and Schematic Library documents, the ‘SCH’ and ‘SCHLIB’ strings respectively need to be passed in along with the full file name string. For PCB and PCB Library documents, the ‘PCB’ and ‘PCBLIB’ strings respectively need to be passed in along with the full file name string.

Since the parameters are null terminated types for some of the functions and often the strings are TDynamicString types,  you will need to typecast these strings as PChar type.
In the code snippet below, the Filename parameter is a TDynamicString type and this parameter is typecasted as a PChar in the Client.OpenDocument method.

Opening a Schematic Document using Client.OpenDocument method

Var
    ReportDocument : IServerDocument;
Begin
    ReportDocument  := Client.OpenDocument('SCH',PChar(FileName));
    If ReportDocument <> Nil Then
        Client.ShowDocument(ReportDocument);
End

Creating Schematic or Library documents in Altium Designer

There are situations when you need to programmatically create a blank stand-alone document. This is facilitated by using the CreateNewDocumentFromDocumentKind function. For example, to create a text document you pass in the ‘Text’ string.

CreateNewDocumentFromDocumentKind example

Var
    Document : IServerDocument;
    Kind     : TDynamicString;
Begin
    //The available Kinds are PCB, PCBLib, SCH, SchLib, TEXT,...
    Kind := ‘SCH’;
    Document := CreateNewDocumentFromDocumentKind(Kind);
End;

Create a blank Schematic and add to the current project example

Var
    Doc     : IServerDocument;
    Project : IProject;
    Path    : TDynamicString;
Begin
    If SchServer = Nil then Exit;
    Project := GetWorkSpace.DM_FOcusedProject;
    If Project <> Nil Then
    Begin
        Path := GetWorkSpace.Dm_CreateNewDocument(‘SCH’);
        Project.DM_AddSourceDocument(Path);
        Doc :=  Client.OpenDocument(Pchar(‘SCH’,PChar(Path));
        Client.ShowDocument(Doc);
    End;
 
    If Not Supports (SchServer.GetCurrentSchDocument,ISchDocument,Doc) Then Exit;
End;

See the script examples in the Scripts\DelphiScript Scripts\DXP\ folder.

Generally you would like to create a document programmatically and put in the currently focused project. To do this, you would need interface access to the Workspace Manager in Altium Designer and invoke DM_FocusedProject and DM_AddSourceDocument functions.

Adding a document to a project

Procedure Command_CreateSchObjects(View : IServerDocumentView; Parameters : PChar);
Var
    Doc     : IServerDocument;
    Project : IProject;
    Path    : TDynamicString;
Begin
    If SchServer = Nil Then Exit;
    // create a blank schematic document and adds to the currently focussed project.
 
    Project := GetWorkspace.DM_FocusedProject;
    If Project <> Nil Then
    Begin
         Path := Getworkspace.DM_CreateNewDocument('SCH');
         Project.DM_AddSourceDocument(Path);
         Doc := Client.OpenDocument(PChar('SCH'), PChar(Path));
         Client.ShowDocument(Doc);
    End;
 
    If Not Supports (SchServer.GetCurrentSchDocument, ISch_Document, SchDoc) Then Exit;
    // do what you want with the schematic document!
End;

Checking the type of Schematic Documents in Altium Designer

You can use the GetCurrentSchematicDocument function from the SchServer object to check whether the current schematic document is a schematic type document.

ISch_Doc Type code snippet

Var
   CurrentSch : ISch_Doc;
Begin
    If Not Supports (SchServer.GetCurrentSchDocument, ISch_Doc,CurrentDoc)Then
    Begin
        ShowInfo('Not a Schematic Library document.');
        Exit;
    End;
//ditto
End;

This code snippet checks if the focused document is a schematic library type.

ISch_Lib Type code snippet

Var
     CurrentLib   : ISch_Lib;
Begin
    If Not Supports (SchServer.GetCurrentSchDocument, ISch_Lib,CurrentLib)Then
    Begin
        ShowInfo('Not a Schematic Librarydocument.');
        Exit;
    End;
End;

This code snippet checks if a document is a Schematic library format.

CurrentView.Kind example

This code snippet uses the Client.CurrentView.Kind method to find out the current document’s type:

If StrPas(Client.CurrentView.Kind) <> UpperCase('SchLib') Then Exit;

Setting a document to Dirty

There are situations when you need to programmatically set a document to dirty so when you close Altium Designer, it prompts you to save this document. This is facilitated by setting the ServerDocument.Modified function to true.

Setting a document Dirty example

Var
    AView           : IServerDocumentView;
    AServerDocument : IServerDocument;
Begin
    // grab the current document view using the CLient's Interface.
    AView := Client.GetCurrentView;
 
    //grab the server document which stores views by extracting the ownerdocument field.
    AServerDocument := AView.OwnerDocument;
 
    // set the document dirty.
    AServerDocument.Modified := True;
End;

See the script examples in the Scripts\DelphiScript Scripts\DXP\ folder.

Refreshing a document programmatically

When you place or modify objects on a schematic document, you often need to do a refresh of this document (you will also need to use the PreProcess / PostProcess and SchServer.RobotManager.SendMessage() methods).

  • ISch_Document.GraphicallyInvalidate;
  • RunProcess(); (Script code)
  • Commands.LaunchCommand(); (Server code)

Examples below demonstrate more than one way to update the document. You can use the ICommandLauncher.LaunchCommand method or the IProcessLauncher’s SendMessage function.

GraphicallyInvalidate and RunProcess methods in a script

//Using GraphicallyInvalidate method to refresh the screen
Var
    SchDoc : ISch_Document;
Begin
    // Refresh the screen
    SchDoc := SchServer.GetCurrentSchDocument;
    If SchDoc = Nil Then Exit;
    // modify the schematic document (new objects, objects removed etc)
    // Call to refresh the schematic document.
    SchDoc.GraphicallyInvalidate;
    ResetParameters;
    AddStringParameter('Action', 'Document');
    RunProcess('Sch:Zoom');
End;

Commands.LaunchCommand in a Server project example

Procedure ZoomToDoc;
Var
    Commands        : ICommandLauncher;
    Parameters      : PChar;
    SchematicServer : IServerModule;
Begin
    GetMem (Parameters, 256);
    Try
        SetState_Parameter(Parameters, 'Action', 'Document');
        If Supports(SchServer, IServerModule, SchematicServer) Then
        Begin
            If Supports (SchematicServer.CommandLauncher, ICommandLauncher, Commands) Then
                Commands.LaunchCommand('Zoom', Parameters, 255,Client.CurrentView);
        End;
    Finally
        FreeMem(Parameters);
    End;
End;

Client.SendMessage in a Script

You can use the Client Object’s SendMessage method to send a process and its parameters string.

Client.SendMessage('SCH:Zoom', 'Action=Document' , 255, Client.CurrentView);

Note, in a server project, the SendMessage method is available from the IProcessLauncher interface.

Schematic Objects

Schematic design objects are stored inside the database of the Schematic editor for the currently active schematic document, basic Schematic objects are called primitives.  There are two types of primitives in the Schematic editor: Electrical primitives and non-electrical primitives. Each design object has a unique object handle which is like a pointer. These handles allow you to access and change the design object’s properties.

The Schematic editor includes the following electrical primitives: Bus, Bus Entry, Junction, Port, Power Port, PCB layout directive, Pin, No ERC Directive, Sheet Entry, Sheet Symbol, Stimulus Directive, Test Vector Directive, and Wire objects. Add any new ones to the list

Non electrical primitives include: Annotation, Arc, Bezier, Ellipse, Elliptical Arc, Graphical Image, Line, Pie, Polygon, Rectangle, Rounded Rectangle, and Text Frame objects add any new ones to the list. The non-electrical primitives are used to add reference information to a sheet.  They are also used to build graphical symbols, create custom sheet borders, title blocks or adding notes and instructions.

The Schematic editor has other system objects such as a container for templates, preferences settings, a search facility, a font manager, a robot manager (capture events of the schematic editor) and so on.
Schematic objects that have child objects are called group objects. Part objects and sheet symbol objects are examples of group objects. Part Objects have pin child objects and Sheet Symbols have sheet entry child objects.
ISch_BasicContainer interface is the ancestor interface for all Schematic design objects including schematic sheets and library documents. This interface has methods that return the unique object address and set up an iterator with filters to look for specific objects within a defined region.

ISch_GraphicalObject interface is the interface for all schematic design objects with graphical attributes.

The three interfaces, ISch_MapDefiner, ISch_ModelDatafileLink, ISch_Implementation all deal with the mapping of schematic components to its models such as PCB footprint, 3D Model, Signal Integrity model and so on.

Accessing Schematic Objects

An iterator provides a way of accessing the elements of an aggregate object sequentially without exposing its underlying representation. The use of iterators provides a compact method of accessing Schematic objects without creating a mirror database across the API.  To retrieve objects on a schematic sheet or a library document, you will need to employ an iterator which is an efficient data retrieval method – there are three types of iterators – simple iterators, spatial iterators and group iterators.

  • Object iterators are used to conduct global searches.
  • Spatial iterators are used to conduct restricted searches.
  • Group iterators are used to conduct searches for primitives inside certain schematic objects.Schematic objects which have objects within them are called group objects  such as  sheet symbols and part objects.

You can specify which objects to look for in the specified region of a document with a spatial iterator. You also set up global iterators that look inside the child objects of a parent object, for example sheet entries of a sheet symbol or parameters of a schematic component.

Iterating for Schematic Objects

Var
    Pin         : ISch_Pin;
    PinIterator : ISch_Iterator;
    PinFound    : Boolean;
Begin
    PinFound := False;
    PinIterator := AComponent.SchIterator_Create;
    PinIterator.SetState_IterationDepth(eIterateAllLevels);
    PinIterator.AddFilter_ObjectSet([ePin]);
 
    Try
        Pin := PinIterator.FirstSchObject As ISch_Pin;
        While Pin <> Nil Do
        Begin
            If Not PinFound Then
                PinFound := True;
            // add pins to the PinsList container of a TStringList type.
            PinsList.Add('Pin ' + Pin.Designator +
                        ' located at (x=' + IntToStr(Pin.Location.X) +
                        ', y='            + IntToStr(Pin.Location.Y) + ')');
            Pin := PinIterator.NextSchObject As ISch_Pin;
        End;
    Finally
        AComponent.SchIterator_Destroy(PinIterator);
    End;
    If Not PinFound Then
        PinsList.Add('There are no pins for this component.');
End;

This code snippet demonstrates the method of fetching schematic objects from a schematic sheet using an iterator.

See the script examples in the Scripts\DelphiScript Scripts\Sch\ folder.

Creating/deleting new Schematic Objects

Schematic objects created using the Schematic API will need to follow a few simple steps to ensure that the database system of the Schematic editor will successfully register new objects.  The example below demonstrates the placement of a Port object onto a Schematic document programmatically.

Create and place a Port object using a script

Procedure PlaceAPort;
Var
    AName       : TDynamicString;
    Orientation : TRotationBy90;
    AElectrical : TPinElectrical;
    SchPort     : ISch_Port;
    Loc         : TLocation;
    FSchDoc     : ISch_Document;
    CurView     : IServerDocumentView;
Begin
    If SchServer = Nil Then Exit;
    FSchDoc := SchServer.GetCurrentSchDocument;
    If FSchDoc = Nil Then Exit;
 
    SchPort := SchServer.SchObjectFactory(ePort,eCreate_GlobalCopy);
    If SchPort = Nil Then Exit;
    SchPort.Location  := Point(100,100);
    SchPort.Style     := ePortRight;
    SchPort.IOType    := ePortBidirectional;
    SchPort.Alignment := eHorizontalCentreAlign;
    SchPort.Width     := 100;
    SchPort.AreaColor := 0;
    SchPort.TextColor := $FFFFFF;
    SchPort.Name      := 'Test Port';
 
    // Add a new port object in the existing Schematic document.
    FSchDoc.AddSchObject(SchPort);
    FSchDoc.GraphicallyInvalidate;
 
    // use of Server processes to refresh the screen.
    ResetParameters;
    AddStringParameter('Action', 'Document');
    RunProcess('Sch:Zoom');
End;

How the above code works

A new port object is created by the SchObjectFactory method. This function takes in two parameters, the ePort value of TObjectID type and the creation model parameter of TObjectCreationMode type. The port’s attributes need to be set accordingly then you will need to register this port object into the Schematic database.

The AddSchObject method needs to be invoked for the SchServer object which represents the schematic database. Finally the GraphicallyInvalidate call refreshes the schematic document.

Note that a RGB function is used in the code to assign a color value to the areacolor and textcolor fields.  This function is a Windows API function and takes in three parameters for the three color intensities (red, green and blue). In this case, (255,255,255) represents the white color and (0,0,0) represents the black color.

See the script examples in the Scripts\DelphiScript Scripts\Sch\ folder.

Creation of a new Schematic Object on a Library document

You can create a symbol on an existing library document in the same way as you create objects on a schematic document.

Creating a new Library Component on a new Library document

Procedure CreateALibComponent;
Var
    CurrentLib   : ISch_Lib;
    SchComponent : ISch_Component;
    R            : ISch_Rectangle;
    Location     : TLocation;
    Corner       : TLocation;
Begin
    If SchServer = Nil Then Exit;
    If Not Supports (SchServer.GetCurrentSchDocument, ISch_Lib, CurrentLib) Then Exit;
 
    If Not Supports (SchServer.SchObjectFactory(eSchComponent, eCreate_Default), ISch_Component, SchComponent) Then Exit;
 
    If Not Supports (SchServer.SchObjectFactory(eRectangle, eCreate_Default), ISch_Rectangle, R)               Then Exit;
 
    SchComponent.CurrentPartID := 1;
    SchComponent.DisplayMode   := 0;
 
    SchComponent.LibReference := 'Custom';
    CurrentLib.AddSchComponent(SchComponent);
    CurrentLib.CurrentSchComponent := SchComponent;
 
    R.LineWidth := eSmall;
    Location.X  := 10;
    Location.Y  := 10;
    R.Location  := Location;
 
    Corner.X    := 30;
    Corner.Y    := 20;
    R.Corner    := Corner;
 
    R.Color     := $FFFF;    // YELLOW
    R.AreaColor := 0;        // BLACK
    R.IsSolid   := True;
 
    R.OwnerPartId          := CurrentLib.CurrentSchComponent.CurrentPartID;
    R.OwnerPartDisplayMode := CurrentLib.CurrentSchComponent.DisplayMode;
    CurrentLib.CurrentSchComponent.AddSchObject(R);
 
    CurrentLib.CurrentSchComponent.Designator.Text := 'U';
    CurrentLib.CurrentSchComponent.ComponentDescription := 'Custom IC';
 
    ZoomToDoc;
End;

See the script examples in the Scripts\DelphiScript Scripts\Sch\ folder.

Creating Objects and refreshing the Undo/Redo system in the Schematic Editor

The simple creation of objects in the examples above does not refresh the Undo system in the Schematic Editor. To do this, you will need to employ the SchServer.RobotManager.SendMessage method.
The sequence is as follows:

  • PreProcess which initialize the robots in the Schematic server
  • Add new objects
  • PostProcess which cleans up the robots in the Schematic server.

Creating Schematic objects in a project

This example describes the correct method for allowing Undo/Redo at various different levels of objects (the first at adding components to the document and the second at adding parameters to the pin of a placed component).

Specifically this will add a constructed component to the current sheet and then a parameter to the pin.You will then be able to perform an undo., The first press of Undo removes the parameter added to the pin. The second press of Undo removes the the component that was added to the document.

    If Not Supports (SchServer.GetCurrentSchDocument, ISch_Sheet, SchDoc) Then Exit;
    If Not Supports (SchServer.SchObjectFactory (eSchComponent, eCreate_Default), ISch_Component, Component) Then Exit;
    If Not Supports (SchServer.SchObjectFactory (eRectangle, eCreate_Default), ISch_Rectangle, Rect) Then Exit;
    If Not Supports (SchServer.SchObjectFactory (ePin, eCreate_Default), ISch_Pin, Pin) Then Exit;
    If Not Supports (SchServer.SchObjectFactory (eParameter, eCreate_Default),ISch_Parameter, Param) Then Exit;
    If Supports (SchServer, IServerModule, SchematicServer) Then
    Begin
        Try
        // Initalize the Robot Manager
            SchematicServer.ProcessControl.PreProcess(Client.CurrentView, '');
 
       // Add component to current schematic sheet with undo stack enabled
            Rect.OwnerPartId := Component.CurrentPartID;
            Rect.OwnerPartDisplayMode := Component.DisplayMode;
            Location.X := 0;
            Location.Y := 0;
            Rect.Location := Location;
            Location.X := 20;
            Location.Y := 20;
            Rect.Corner := Location;
 
            Pin.OwnerPartId := Component.CurrentPartID;
            Pin.OwnerPartDisplayMode := Component.DisplayMode;
            Location.X := 20;
            Location.Y := 10;
            Pin.Location := Location;
 
            Component.AddSchObject(Rect);
            Component.AddSchObject(Pin);
            SchDoc.AddSchObject(Component);
            Component.MoveByXY(100, 100);
            SchServer.RobotManager.SendMessage(SchDoc.I_ObjectAddress, c_BroadCast,
                             SCHM_PrimitiveRegistration, Component.I_ObjectAddress);
        Finally
            // Clean up  the Robot Manager
            SchematicServer.ProcessControl.PostProcess(Client.CurrentView, '');
        End;
    End;

See the script examples in the Scripts\DelphiScript Scripts\Sch\ folder.

Removing Schematic Objects code example

    Iterator := CurrentSheet.SchIterator_Create;
    If Iterator = Nil Then Exit;
    Iterator.AddFilter_ObjectSet([ePort]);
 
    // Initalize the Robot Manager
    SchematicServer.ProcessControl.PreProcess(Client.CurrentView, '');
    Try
        Port := Iterator.FirstSchObject As ISch_Port;
        While Port <> Nil Do
        Begin
            OldPort := Port;
            Port := Iterator.NextSchObject As ISch_Port;
            CurrentSheet.RemoveSchObject(OldPort);
            SchServer.RobotManager.SendMessage(CurrentSheet.I_ObjectAddress,
                                               c_BroadCast,
                                               SCHM_PrimitiveRegistration,
                                               OldPort.I_ObjectAddress);
        End;
    Finally
        CurrentSheet.SchIterator_Destroy(Iterator);
 
    // Clean up  the Robot Manager
    SchematicServer.ProcessControl.PostProcess(Client.CurrentView, '');
End;

See the script examples in the Scripts\DelphiScript Scripts\Sch\ folder.

Modifying Schematic Objects

To modify Schematic objects on a current Schematic document, you will need to invoke certain methods in a particular order to ensure the Undo/Redo system is up to date when a schematic object’s attributes have been modified programmatically.

The sequence is as follows:

  • Invoke the PreProcess method which initialize the robots in the schematic server
  • Send a SCHM_BeginModify message
  • Modify the Schematic object by changing its attributes (Properties)
  • Send a SCHM_EndModify message
  • Invoke the PostProcess method to clean up the robots in the Schematic server.

Changing Schematic Object’s Attributes code example

Procedure FetchAndModifyObjects;
Var
    AnObject        : ISCh_GraphicalObject;
    Iterator        : ISch_Iterator;
    SchematicServer : IServerModule;
    Doc             : ISch_Document;
Begin
    SchematicServer := SchServer As IServerModule;
    Doc             := SchServer.GetCurrentSchDocument;
    Iterator        := Doc.SchIterator_Create;
    Iterator.AddFilter_ObjectSet([ePort,eWire]);
 
    SchematicServer.ProcessControl.PreProcess(Client.CurrentView, '');
    // Initialize the Robot Manager
    SchServer.ProcessControl.PreProcess(Doc, '');
 
    If Iterator = Nil Then Exit;
    Try
        AnObject := Iterator.FirstSchObject As ISch_GraphicalObject;
        While AnObject <> Nil Do
        Begin
            SchServer.RobotManager.SendMessage(AnObject.I_ObjectAddress,
 c_BroadCast, SCHM_BeginModify, c_NoEventData);
            Case AnObject.ObjectId Of
               eWire   : AnObject.Color     := $FF0000;
               ePort   : AnObject.AreaColor := $00FF00;
            End;
            SchServer.RobotManager.SendMessage(AnObject.I_ObjectAddress,
 c_BroadCast, SCHM_EndModify  , c_NoEventData);
            AnObject := Iterator.NextSchObject As ISch_GraphicalObject;
        End;
    Finally
        Doc.SchIterator_Destroy(Iterator);
    End;
 
    // Clean up the Robot Manager
    SchServer.ProcessControl.PostProcess(Doc, '');
End;

Notes
When you change the properties of a schematic object on a Schematic document, it is necessary to employ the SchServer.RobotManager.SendMessage function. This updates the various subsystems of the Schematic system such as the Undo/Redo system and setting the document as dirty so the document can be saved. Look for the SendMessage method of the ISch_RobotManager in this document.

Remember, the Schematic API only can be used to work on a currently open Schematic document in the Altium Designer. If you need to fetch specific Schematic documents, you will need the Client object’s OpenDocument and ShowDocument methods to open and display a document.

Procedure OpenAndShowASchDocument(AFileName : String);
Var
    Document : IServerDocument;
Begin
    If Client = Nil Then Exit;
    Document := Client.OpenDocument('SCH',AFileName,False);
    If Document <> Nil Then
         Client.ShowDocument(Document);
End;

See the script examples in the Scripts\DelphiScript Scripts\Sch\ folder.

Schematic interactive feedback using the Mouse

To monitor the mouse movement and clicks from your script, the ISch_Document document interface and its descendant interfaces, ISch_Lib and ISch_Sheet interfaces have several interactive feedback methods. For example, the ChooseRectangleinteractively method can be used for the Spatial iterator where it needs the bounds of a rectangle on the schematic document to search within.

  • ChooseLocationInteractively method
  • ChooseRectangleInteractively method

ChooseRectangleInteractively method example

Var
    CurrentSheet    : ISch_Document;
    SpatialIterator : ISch_Iterator;
    GraphicalObj : ISch_GraphicalObject;
    Rect            : TCoordRect;
Begin
    If SchServer = Nil Then Exit;
    CurrentSheet := SchServer.GetCurrentSchDocument;
    If CurrentSheet = Nil Then Exit;
 
    Rect := TCoordRect;
    If Not CurrentSheet.ChooseRectangleInteractively(Rect,
           'Please select the first corner',
           'Please select the final corner') Then Exit;
 
    SpatialIterator := CurrentSheet.SchIterator_Create;
    If SpatialIterator = Nil Then Exit;
    Try
        SpatialIterator.AddFilter_ObjectSet(MkSet(eJunction,eSchComponent));
        SpatialIterator.AddFilter_Area(Rect.left, Rect.bottom, Rect.right, Rect.top);
        GraphicalObj := SpatialIterator.FirstSchObject;
        While GraphicalObj <> Nil Do
        Begin
           // do what you want with the design object
           GraphicalObj := SpatialIterator.NextSchObject;
        End;
    Finally
        CurrentSheet.SchIterator_Destroy(SpatialIterator);
    End;
End;

Consult the ISch_Document interface entry in the Schematic API Reference document.
See the script examples in the Scripts\DelphiScript Scripts\Sch\ folder.

Activating the Schematic API

There are situations when Altium Designer is in a blank editing session. When Schematic documents have not been opened, the Schematic API is not active. At these times, you need to manually start the server to access to the Schematic API. Starting up the Schematic server to activate the Schematic API is done by invoking the Client.StartServer method with a ‘SCH’ parameter.
Client.StartServer('SCH');

If you find an issue, select the text/image and pressCtrl + Enterto send us your feedback.
Note

The features available depend on your Altium product access level. Compare features included in the various levels of Altium Designer Software Subscription and functionality delivered through applications provided by the Altium 365 platform.

If you don’t see a discussed feature in your software, contact Altium Sales to find out more.

Content