[GME-commit] GMESRC/SDK/Scripts GMEModelBuilder.py, NONE, 1.1 GMEObjectQuery.js, NONE, 1.1 GMEObjectQuery.py, NONE, 1.1 GMETraversor.js, 1.1, 1.2 GMETraversor.py, 1.1, 1.2
Log messages of CVS commits
gme-commit at list.isis.vanderbilt.edu
Fri May 9 09:06:45 CDT 2008
Update of /project/gme-repository/GMESRC/SDK/Scripts
In directory escher:/tmp/cvs-serv30280
Modified Files:
GMETraversor.js GMETraversor.py
Added Files:
GMEModelBuilder.py GMEObjectQuery.js GMEObjectQuery.py
Log Message:
Separated Traversal file from Query file.
For python ModelBuilder file.
CVS User: Zoltan Molnar, ISIS (zolmol)
--- NEW FILE: GMEObjectQuery.js ---
//#################################################################################
//#
//# This file contains JScript methods for project-wide traversal or query.
//# See bottom of the file for main()
//#
//#################################################################################
//#
//# Query for objects based on different criteria
//# _____________________________________________
//#
//# filter() method:
//# Usable to do a project wide search based on Name, Kind, Role, ObjectType, Level.
//# ObjectType is an enum as follows:
//# Model = 1,
//# Atom = 2,
//# Reference = 3,
//# Connection = 4,
//# Set = 5,
//# Folder = 6
//# Level (depth) can be a space-separated list of numbers or dash-separated number pairs: e.g: 1-2 5 7
//#
//# filterScoped() method:
//# Usable to do a scoped search based on Name, Kind, Role, ObjectType, Level.
//# Starts from a container, performs search down in its containment tree.
//#
//#################################################################################
var g, p;
g = gme
p = project
//#######################################################################
//# general helpers
//#######################################################################
function cout3( gme, mStr, mType)
{
gme.ConsoleMessage( mStr, mType);
}
function cout( mStr, mType)
{
g.ConsoleMessage( mStr, mType);
}
function fancy( mInStr)
{
var fancy = "<head><style type=\"text/css\">" +
"td.special{ background-color:aqua;font-size: 100%;margin-left: 20px;font-family: times, sans-serif, arial}" +
"</style>" +
"</head>" +
"<table><tr><td class=\"special\">" +
mInStr +
"</td></tr></table>";
return fancy;
}
function makeLink( o)
{
return '<a href=mga:' + o.ID + '">' + o.Name + '</a>';
}
function coll2array( in_collection)
{
var a = new Array();
for( var j = 1; j <= in_collection.Count; ++j) { // indices from 1 ... count
a.push( in_collection.Item(j));
}
return a;
}
//#######################################################################
//# transaction handlers
//#######################################################################
function begin( the_project )
{
/// in GME7 and under must use: g.oleit.BeginTransaction();
/// in GME8.5 and above use: project.BeginTransactionInNewTerr();
try {
var terr = the_project.BeginTransactionInNewTerr(); // will work on GME8
return terr;
} catch(err) {
g.oleit.BeginTransaction(); // will work on GME7
}
}
function commit( the_project, terr )
{
/// can be used also: (in all GME versions available)
//g.oleit.CommitTransaction();
the_project.CommitTransaction();
if( terr != null) {
terr.Destroy();
}
}
function abort( the_project, terr )
{
/// in GME8 you can use also:
//g.oleit.AbortTransaction();
the_project.AbortTransaction();
if( terr != null) {
terr.Destroy();
}
}
///#######################################################################
///# helper methods for filter
///#######################################################################
function print_details_what_we_search_for( object, name, kind, role, otype, level)
{
/// show some output to the console regarding what
/// kind of search the parameters are implying
var prefix = "";
var msg = "";
if( object != null) prefix = "Local query in " + makeLink( object) + " ";
else prefix = "Global query ";
if( name != "") msg += "[Name = '" + name + "'] ";
if( kind != "") msg += "[Kind = '" + kind + "'] ";
if( role != "") msg += "[Role = '" + role + "'] ";
if( otype != "") msg += "[ObjectType = '" + otype + "'] ";
if( level != "") msg += "[Level = '" + level + "'] ";
if( msg == "") // no criteria has been specified, will match all objects in scope
cout( prefix + " with no specified criteria, will match all objects in scope!");
else
cout( prefix + " for objects with " + msg);
}
function show_results_in_my_way( res)
{
/// user preferred way to show results
if( res.length > 0)
cout( "Results list:", 1);
else
cout( "No object found!", 2);
for( var k = 0; k < res.length; ++k)
cout( makeLink( res[k]), 1);
}
///#######################################################################
///# global filter on project
///#######################################################################
function filter( oname, okind, orole, otype, level)
{
/// display some information about the criteria
print_details_what_we_search_for( null, oname, okind, orole, otype, level);
var flt = p.CreateFilter();
flt.Name = oname;
flt.Kind = okind;
flt.Role = orole;
flt.ObjType = otype;
flt.Level = level;
var res = p.AllFCOs( flt); // filter used project-wide
return coll2array( res);
}
///#######################################################################
///# local filter on the object (container typically)
///#######################################################################
function filterScoped( scopeObject, oname, okind, orole, otype, level)
{
/// display some information about the criteria
print_details_what_we_search_for( scopeObject, oname, okind, orole, otype, level);
var flt = p.CreateFilter();
flt.Name = oname;
flt.Kind = okind;
flt.Role = orole;
flt.ObjType = otype;
flt.Level = level;
var res = scopeObject.GetDescendantFCOs( flt); // filter used only down under container object in the hierarchy tree
return coll2array( res);
}
///#######################################################################
///# demo methods for the usage of filter and filterScoped
///#######################################################################
function query_demo_MetaGME()
{
/// demo for the MetaGME paradigm:
/// 'it.Valid' bool indicates whether a model window is currently
/// shown (opened and active). In this case 'it.MgaModel' is a
/// valid pointer to this container, so a scoped/local search
/// can be invoked using it. Otherwise do a global search.
var objects;
if( it.Valid)
objects = filterScoped( it.MgaModel, "", "ModelProxy", "", "", ""); // kind filtering
else
objects = filter( "", "ModelProxy", "", "", ""); // same, but globally
show_results_in_my_way( objects);
}
///#######################################################################
function query_demo_SF()
{
/// demo for the SF paradigm:
/// Will demonstrate the use of Level criteria, which is relative to the container.
/// Level 1: child-parent relationship between the object and the container parameter.
/// Level 2: grandchild-grandparent relationship, etc.
/// Syntax: "1 2", "3-5", "1 2 5-7", "3-".
var objects;
/// we will search among grandchildren, great-grandchildren etc. of it.MgaModel
if( it.Valid)
objects = filterScoped( it.MgaModel, "", "", "InputSignals", "", "2-"); // role and level filtering
else
objects = filter( "", "", "InputSignals", "", "2-");
show_results_in_my_way( objects);
}
///#######################################################################
function query_demo_generic()
{
/// demo, which might make sense for any paradigm: will search for atoms (2) and references(3)
var objects;
if( it.Valid)
objects = filterScoped( it.MgaModel, "", "", "", "2 3", ""); /// looking for Atoms (2) and References (3)?
else
objects = filter( "", "", "", "2 3", ""); /// same on global scale
show_results_in_my_way( objects);
}
///#######################################################################
function query_demo()
{
var paradigm = p.MetaName; /// what is the paradigm name of the opened project?
if( paradigm == "MetaGME")
query_demo_MetaGME(); /// execute MetaGME specific demo in case a metamodel is opened
else if( paradigm == "SF")
query_demo_SF(); /// ... SF specific demo
else
query_demo_generic(); /// ... generic demo, queries for atoms and references (probably there are such elements in any paradigm)
}
///#######################################################################
///# main
cout( "--Hello World, this is JScript here!--", 1);
var terr = begin(p); /// begin transaction (strictly needed to perform r/w operations on a IMgaProject)
try {
query_demo( p);
commit( p, terr);
}
catch(err) {
cout( "Exception [" + err.message + "]. Transaction will abort.", 3);
abort( p, terr);
}
cout( "--End of script--", 1);
p = null
g = null
Index: GMETraversor.js
===================================================================
RCS file: /project/gme-repository/GMESRC/SDK/Scripts/GMETraversor.js,v
retrieving revision 1.1
retrieving revision 1.2
diff -C2 -d -r1.1 -r1.2
*** GMETraversor.js 15 Apr 2008 19:10:50 -0000 1.1
--- GMETraversor.js 9 May 2008 14:06:43 -0000 1.2
***************
*** 1,5 ****
//#################################################################################
//#
! //# This file contains JScript methods for project-wide traversal or query.
//# See bottom of the file for main()
//#
--- 1,5 ----
//#################################################################################
//#
! //# This file contains JScript methods for project-wide traversal.
//# See bottom of the file for main()
//#
***************
*** 17,40 ****
//#
//#################################################################################
- //#
- //# Query for objects based on different criteria
- //# _____________________________________________
- //#
- //# filter() method:
- //# Usable to do a project wide search based on Name, Kind, Role, ObjectType, Level.
- //# ObjectType is an enum as follows:
- //# Model = 1,
- //# Atom = 2,
- //# Reference = 3,
- //# Connection = 4,
- //# Set = 5,
- //# Folder = 6
- //# Level (depth) can be a space-separated list of numbers or dash-separated number pairs: e.g: 1-2 5 7
- //#
- //# filterScoped() method:
- //# Usable to do a scoped search based on Name, Kind, Role, ObjectType, Level.
- //# Starts from a container, performs search down in its containment tree.
- //#
- //#################################################################################
var g, p;
--- 17,20 ----
***************
*** 189,193 ****
function metaRole( o)
{
! // it seems we don't have access to meta.dll
// because it does return undefined
return o.MetaRole;
--- 169,173 ----
function metaRole( o)
{
! // it seems we don't have access to meta info JScript
// because it does return undefined
return o.MetaRole;
***************
*** 196,200 ****
function metaName( o)
{
! // it seems we don't have access to meta.dll
// because it does return undefined
return o.Meta.Name;
--- 176,180 ----
function metaName( o)
{
! // it seems we don't have access to meta info from JScript
// because it does return undefined
return o.Meta.Name;
***************
*** 248,257 ****
function begin( the_project )
{
try {
! var terr = the_project.BeginTransactionInNewTerr(); // only on GME8
! // under GME7 please use this: g.oleit.BeginTransaction();
return terr;
} catch(err) {
! g.oleit.BeginTransaction();
}
}
--- 228,239 ----
function begin( the_project )
{
+ /// in GME7 and under must use: g.oleit.BeginTransaction();
+ /// in GME8.5 and above use: project.BeginTransactionInNewTerr();
+
try {
! var terr = the_project.BeginTransactionInNewTerr(); // will work on GME8
return terr;
} catch(err) {
! g.oleit.BeginTransaction(); // will work on GME7
}
}
***************
*** 259,269 ****
function commit( the_project, terr )
{
//g.oleit.CommitTransaction();
- //if( terr != null) terr.Flush();
the_project.CommitTransaction();
if( terr != null) {
- cout( "Territory destroyed.", 1);
terr.Destroy();
}
--- 241,250 ----
function commit( the_project, terr )
{
+ /// can be used also: (in all GME versions available)
//g.oleit.CommitTransaction();
the_project.CommitTransaction();
if( terr != null) {
terr.Destroy();
}
***************
*** 272,282 ****
function abort( the_project, terr )
{
! //g.oleit.AbortTransaction(); // from GME8 on
! //if( terr != null) terr.Flush();
the_project.AbortTransaction();
if( terr != null) {
- cout( "Territory destroyed.", 1);
terr.Destroy();
}
--- 253,262 ----
function abort( the_project, terr )
{
! /// in GME8 you can use also:
! //g.oleit.AbortTransaction();
the_project.AbortTransaction();
if( terr != null) {
terr.Destroy();
}
***************
*** 416,420 ****
{
cout( o.GetGUIDDisp() + " ~ " + o.ID + " ~ " + o.Name, 1);
- //cout( "Handled", 2);
}
--- 396,399 ----
***************
*** 519,565 ****
}
- function filter( oname, okind, orole, otype, level)
- {
- var flt = p.CreateFilter();
- flt.Name = oname;
- flt.Kind = okind;
- flt.Role = orole;
- flt.ObjType = otype;
- flt.Level = level;
- var res = p.AllFCOs( flt); // filter used project-wide
- cout( "Results follow: ", 1);
- for( var i = 1; i <= res.Count; ++i)
- cout( res.Item(i).Name + " -> " + makeLink( res.Item(i)), 1);
-
- return coll2array( res);
- }
-
- function filterScoped( scopeObject, oname, okind, orole, otype, level)
- {
- var flt = p.CreateFilter();
- flt.Name = oname;
- flt.Kind = okind;
- flt.Role = orole;
- flt.ObjType = otype;
- flt.Level = level;
- var res = scopeObject.GetDescendantFCOs( flt); // filter used only down under container object in the hierarchy tree
- cout( "Results follow: ", 1);
- for( var i = 1; i <= res.Count; ++i)
- cout( res.Item(i).Name + " -> " + makeLink( res.Item(i)), 1);
-
- return coll2array( res);
- }
-
- function testFilter()
- {
- var r1;
- r1 = filter( "", "Model", "", "", ""); // kind based filtering
- r1 = filterScoped( it.MgaModel, "", "Model", "", "", "");
-
- for( var k = 0; k < r1.length; ++k)
- cout( makeLink(r1[k]), 3);
- }
-
-
function traverse()
{
--- 498,501 ----
***************
*** 582,586 ****
//# select the sort criteria here
//#-----------------------------------
! var used_sort = AspectAbsSort;
//#-----------------------------------
--- 518,522 ----
//# select the sort criteria here
//#-----------------------------------
! var used_sort = AspectHorizSort;
//#-----------------------------------
***************
*** 589,593 ****
var used_algo = traverse_levelled;
! cout( fancy('Examining project \'' + p.RootFolder.Name + '\' with ' + algo_text[used_algo] + ' method, sorting children by their ' + sort_text[ used_sort] + '.'), 1)
--- 525,529 ----
var used_algo = traverse_levelled;
! cout( 'Examining project \'' + p.RootFolder.Name + '\' with ' + algo_text[used_algo] + ' method, sorting children by their ' + sort_text[ used_sort] + '.', 1)
***************
*** 605,610 ****
//# main
! cout( fancy("--Greetings!--"), 1);
! cout( "Hello World, this is JScript here!", 1);
var terr = begin(p);
--- 541,545 ----
//# main
! cout( "--Hello World, this is JScript here!--", 1);
var terr = begin(p);
***************
*** 612,616 ****
try {
traverse();
- //testFilter();
commit( p, terr);
--- 547,550 ----
***************
*** 621,623 ****
}
! cout( "Bye, bye!", 1);
--- 555,560 ----
}
! cout( "--End of script!--", 1);
!
! p = null
! g = null
\ No newline at end of file
--- NEW FILE: GMEModelBuilder.py ---
#################################################################################
#
# This file contains Python helper methods for Model, Set, Reference objects.
# See bottom of the file for main()
#
#################################################################################
#
# Helper methods for different object types useable as follows
# ____________________________________________________________
#
# Models:
# MetaRoleObject = metaRoleByName( Model, KindString)
# MetaRoleObject = metaRole( Object)
# MetaNameString = metaName( Object)
# NewChild = newChild( Model, RoleString)
# ClonedObject = clone( WhereModel, WhichObject)
# delObj( Object)
# ChildObject = childByName( Model, Name)
# ListOfChildren = childrenByKind( Model, KindString)
# ListOfChildren = children( Model)
# Parent = parent( Object)
# Connections:
# NewConn = connect( Model, Source, Destination, ConnectionMetaRole)
# NewConn = connectThruRefChain( Model, Source, Destination, SourceReferenceChain, DestinationReferenceChain, ConnectionMetaRole)
# ListOfConns = partOfConns( Object)
# References:
# Tgt = getReferred( Ref)
# setReferred( Ref, Tgt)
# clearReference( Ref)
# ListOfRefs = referredBy( Tgt)
# Sets:
# T/F = isMemberIn( Set, Member)
# ListOfMembers = members( Set)
# ListOfSets = memberOfSets( Member)
# addToSet( Set, Member)
# remFromSet( Set, Member)
#
#################################################################################
import win32com.client
p = project # pre-existing variable defined, implements IMgaProject interface (see Interfaces/Mga.idl)
g = gme # pre-existing variable defined, implements IGMEOLEApp interface (see Interfaces/GME.idl)
#############################################################
## OBJTYPE_REFERENCE (3)
#############################################################
def getReferred( r):
if( r and r.ObjType == 3):
return r.Referred
return
def setReferred( r, o):
if( r and r.ObjType == 3):
r.Referred = o
return
def clearReference( r):
""" Clears a reference's Referred property.
r.Referred = 0 does not work unfortunately
"""
if r.ObjType == 3:
try:
r.ClearRef() # from GME8 on
except:
cout( "Exception while clearing reference: " + r.Name + "!", 3)
raise
return
def referredBy( o):
return list( o.ReferencedBy)
#############################################################
## OBJTYPE_SET (5)
#############################################################
def isMemberIn( s, o):
# GetIsMemberDisp is not giving back correct results:
#return s.ObjType == 5 and s.GetIsMemberDisp( o)
# that's why an alternative implementation is used:
#s.GetIsMemberDisp( o)
return o in members(s)
def members( s):
if( s and s.ObjType == 5):
return list( s.Members)
return
def memberOfSets( o):
return list(o.MemberOfSets)
def addToSet( s, o):
if( s and s.ObjType == 5):
s.AddMember( o)
def remFromSet( s, o):
if( s and s.ObjType == 5):
s.RemoveMember( o)
#############################################################
## OBJTYPE_CONNECTION
#############################################################
def connect( m, srco, dsto, conn_mrole):
if( m.ObjType == 1): # Model
c = m.CreateSimpleConn( conn_mrole, srco, dsto, None, None)
c.Name = conn_mrole.Name
return c
return
def connectThruRefChain( m, srco, dsto, src_ref_chain, dst_ref_chain, conn_mrole):
if( m.ObjType == 1): # Model
c = m.CreateSimpleConn( conn_mrole, srco, dsto, src_ref_chain, dst_ref_chain)
c.Name = conn_mrole.Name
return c
return
def partOfConns( o):
conn_points = list( o.PartOfConns)
conns = []
for i in range(0, len(conn_points)):
conns.append( conn_points[i].Owner)
return conns
#############################################################
## OBJTYPE_MODEL (1)
#############################################################
def metaRoleByName( m, kind_str):
if m.ObjType == 1: # Model
return m.Meta.GetRoleByNameDisp( kind_str)
#return null
def metaRole( o):
return o.MetaRole
def metaName( o):
return o.Meta.Name
def newChild( m, role_str):
if m.ObjType == 1:
mrole = metaRoleByName( m, role_str)
if mrole:
nch = m.CreateChildObject( mrole)
nch.Name = mrole.Name
return nch
return
def clone( m, orig):
""" Clones orig object into m (model or folder).
If orig is a folder, m needs to a folder too.
"""
if m.ObjType not in (1, 6): return
if not orig: return
if m.ObjType == 6: # Target is a Folder
if orig.ObjType == 6: cloned = m.CopyFolderDisp( orig) # Orig is Folder too
else: cloned = m.CopyFCODisp( orig) # Orig is FCO
elif m.ObjType == 1:
cloned = m.CopyFCODisp( orig, metaRole( orig)) # Target is Model, Orig is FCO
if cloned:
cloned.Name = "Cloned" + orig.Name
return cloned
def delObj( o):
""" Deletes an object o from its parent
"""
if not o: return
try:
o.DestroyObject()
except:
cout( "Could not remove object '" + o.Name + "'!")
raise # raise again the same exception
return
def childByName( m, name_str):
if m.ObjType == 1:
return m.GetChildFCODisp( name_str)
return
def childrenByKind( m, kind_str):
if m.ObjType == 1:
return list(m.GetChildrenOfKind( kind_str))
return
def children( m):
if m.ObjType == 1:
return list(m.ChildFCOs)
return
def parent( o):
if o.ParentFolder : return o.ParentFolder # by checking ParentFolder first, we can use the same
elif o.ObjType != 6 and o.ParentModel : return o.ParentModel # implementation for folders and fcos, since folders
# have too a method named ParentFolder
return
#######################################################################
# transaction handlers
#######################################################################
def begin( p_project ):
# alt1: return project.BeginTransactionInNewTerr() # only in GME8
# alt2: project.BeginTransaction( project.CreateTerritory( None, None, None))
# or more verbosely:
terr = p_project.CreateTerritory( None, None, None)
p_project.BeginTransaction( terr)
return terr
def commit( p_project, p_terr ):
p_project.CommitTransaction()
if p_terr:
p_terr.Destroy()
def abort( p_project, p_terr ):
p_project.AbortTransaction()
if p_terr:
p_terr.Destroy()
#######################################################################
# general helpers
#######################################################################
def cout3( _gme, _msg, _type = 1):
_gme.ConsoleMessage( _msg, _type)
def cout( _msg, _type = 1):
gme.ConsoleMessage( _msg, _type)
def fancy( _inStr):
""" Encloses incoming string into a html table cell, so
that it will be shown with custom fgcolor and bgcolor
"""
return '<head><style type="text/css">td.special{ background-color:aqua;font-size: 100%;margin-left: 20px;font-family: times, sans-serif, arial}</style></head><table><tr><td class="special">' + _inStr + '</td></tr></table>'
def fancy2( _inStr):
return '<p style="background-color: yellow">' + _inStr + '</p>'
def makeLink( o):
return '<a href=mga:' + o.ID + '">' + o.Name + '</a>'
#######################################################################
# a sorter the traverser will use
#######################################################################
def IDSort( x, y):
if( x.ID < y.ID): r = -1
elif( x.ID > y.ID): r = 1
else: r = 0
return r
#######################################################################
# a generic handler for a visited object (fco or folder)
# implement/change it the way you like it
#######################################################################
def handle( _obj):
try:
nc = 0
if _obj.ObjType == 1: # a model
paradigm = p.MetaName
if paradigm == "SF":
"""
in SF models we can create InputSignals in all containers
"""
nc = newChild( _obj, "InputSignals")
if nc: nc.Name = "this is a new creation"
elif paradigm == "MetaGME":
"""
in MetaGME models we can create Atoms in all containers
"""
nc = newChild( _obj, "Atom")
if nc: nc.Name = "this_atom_is_a_new_creation"
else:
"""
in unknown models we take the first child of the
current model and clone it based on its metarole
"""
chldrn = children( _obj)
if len( chldrn) > 0:
# select the first child to be cloned (except connections)
i = 0
while chldrn[i].ObjType == 4 and i < len( chldrn):
++i
if i < len( chldrn): # since a connection can't just exist by itself in a model there
Orig = chldrn[i] # must exist at least one 'real' fco (the endpoint of the connection)
# we have an suitable element to be cloned in Orig
if Orig and metaRole( Orig):
nc = newChild( _obj, metaRole( Orig).Name)
if nc: nc.Name = "this is a new creation based on " + Orig.Name + "'s role"
# nc holds a new child (if any)
if nc:
cout("Created " + makeLink( nc))
finally:
pass
return
#######################################################################
# traverse
#######################################################################
def traverse_levelled( _rootfolder, _comparator): # aka BFT, Breadth First Traversal with a fifo queue
to_visit = [] # a list (!tuple)
to_visit.append( _rootfolder)
while len( to_visit) > 0:
o = to_visit.pop(0) # pops the first element from the queue
handle( o) # handle current node
if o.ObjType in (1, 6): # children for Models and Folders
children = list( o.ChildObjects) # only a list
children.sort( cmp = _comparator) # can be sorted
to_visit.extend( children) # append children to the fifo queue
return
def traverse_postorder( _current, _comparator):
to_visit = [] # a list (!tuple)
if _current.ObjType in (1, 6): # children for Models and Folders
to_visit.extend( _current.ChildObjects) # remains a list
to_visit.sort( cmp = _comparator) # which can sort
# 1st: traverse subtrees
for o in to_visit:
traverse_postorder( o, _comparator)
# 2nd: handle current node
handle( _current)
return
##############################################################################################
#
# Variables existing when the script is executed are
# -----------------------------------------------------
#
# project : the project variable (see Interfaces/Mga.idl)
# gme : the main application window (see Interfaces/GME.idl for IGMEOLEApp)
# it : the actively shown model (view) (see Interfaces/GME.idl for IGMEOLEIt)
#
###############################################################################################
# main() begins
#
cout( '--Hello World, this is Python here!--', 1)
terr = begin( p) # begin transaction (strictly needed to perform r/w operations on a IMgaProject)
try:
# do a traversal of the active model (if valid), otherwise of the whole project
if it.Valid: traverse_postorder( it.MgaModel, IDSort)
else: traverse_postorder( p.RootFolder, IDSort)
#traverse_levelled( p.RootFolder, IDSort) # do a traversal
commit(p, terr) # commit transaction (strictly needed to return the project in a consistent mode)
except:
cout( 'Need to abort', 2) # 2 means MSG_WARNING (yellow)
abort(p, terr) # abort transaction if something went wrong
cout( '--End of Script--', 1)
p = None
g = None
--- NEW FILE: GMEObjectQuery.py ---
#################################################################################
#
# This file contains Python methods for project-wide or local query.
# See bottom of the file for main()
#
#################################################################################
#
# Query for objects based on different criteria
# _____________________________________________
#
#
# filter() method:
# Usable to do a project wide search based on Name, Kind, Role, ObjectType, Level.
# ObjectType is an enum as follows:
# Model = 1,
# Atom = 2,
# Reference = 3,
# Connection = 4,
# Set = 5,
# Folder = 6
# [ see objtype_enum GME/Interfaces/Meta.idl for more ]
#
# Level (depth) can be a space-separated list of numbers or dash-separated number pairs: e.g: 1-2 5 7
#
# filterScoped() method:
# Usable to do a scoped search based on Name, Kind, Role, ObjectType, Level.
# Starts from a container, performs search down in its containment tree.
#
#################################################################################
import win32com.client
p = project # alias for the project pre-existing variable, implements IMgaProject interface (see Interfaces/Mga.idl)
g = gme # alias for the gme pre-existing variable, implements IGMEOLEApp interface (see Interfaces/GME.idl)
#######################################################################
# transaction handlers
#######################################################################
def begin( p_project ):
# alt1: return project.BeginTransactionInNewTerr() # only in GME8
# alt2: project.BeginTransaction( project.CreateTerritory( None, None, None))
# or more verbosely:
terr = p_project.CreateTerritory( None, None, None)
p_project.BeginTransaction( terr)
return terr
def commit( p_project, p_terr ):
p_project.CommitTransaction()
if p_terr:
p_terr.Destroy()
def abort( p_project, p_terr ):
p_project.AbortTransaction()
if p_terr:
p_terr.Destroy()
#######################################################################
# general helpers
#######################################################################
def cout3( _gme, _msg, _type = 1):
_gme.ConsoleMessage( _msg, _type)
def cout( _msg, _type = 1):
gme.ConsoleMessage( _msg, _type)
def fancy( _inStr):
""" Encloses incoming string into a html table cell, so
that it will be shown with custom fgcolor and bgcolor
"""
return '<head><style type="text/css">td.special{ background-color:aqua;font-size: 100%;margin-left: 20px;font-family: times, sans-serif, arial}</style></head><table><tr><td class="special">' + _inStr + '</td></tr></table>'
def fancy2( _inStr):
return '<p style="background-color: yellow">' + _inStr + '</p>'
def makeLink( o):
return '<a href=mga:' + o.ID + '">' + o.Name + '</a>'
#######################################################################
# sorters
#######################################################################
def IDSort( x, y):
if( x.ID < y.ID): r = -1
elif( x.ID > y.ID): r = 1
else: r = 0
return r
def GUIDSort( x, y):
if( x.GetGUIDDisp() < y.GetGUIDDisp()): r = -1
elif( x.GetGUIDDisp() > y.GetGUIDDisp()): r = 1
else: r = 0
return r
def NameSort( x, y):
if( x.Name < y.Name): r = -1
elif( x.Name > y.Name): r = 1
else: r = 0
return r
#######################################################################
# helper methods for filter
#######################################################################
def print_details_what_we_search_for( object, name, kind, role, otype, level):
""" show some output to the console regarding what
kind of search the parameters are implying
"""
prefix = ""
msg = ""
if object: prefix = "Local query in " + makeLink( object) + " "
else: prefix = "Global query "
if name != "": msg += "[Name = '" + name + "'] "
if kind != "": msg += "[Kind = '" + kind + "'] "
if role != "": msg += "[Role = '" + role + "'] "
if otype != "": msg += "[ObjectType = '" + otype + "'] "
if level != "": msg += "[Level = '" + level + "'] "
if msg == "": # no criteria has been specified, will match all objects in scope
cout( prefix + " with no specified criteria, will match all objects in scope!")
else:
cout( prefix + " for objects with " + msg)
def show_results_in_my_way( res):
""" user preferred way to show results
"""
if len( res) > 0:
#cout( fancy("Result list:")) # fancy wraps the string into a colored HTML table cell
cout( "Result list:") # but it does not scroll down for some reason
else:
cout( "No object found!", 2) # 2: MSG_WARNING
for k in range( 0, len( res)): # show results
cout( makeLink( res[k])) # with a link so that users can click on them
#######################################################################
# global filter on project
#######################################################################
def filter( name = "", kind = "", role = "", otype = "", level = ""):
""" Global search on project
"""
# display some information about the criteria
print_details_what_we_search_for( 0, name, kind, role, otype, level)
flt = p.CreateFilter()
flt.Name = name
flt.Kind = kind
flt.Role = role
flt.ObjType = otype
flt.Level = level
res = p.AllFCOs( flt) # filter used project-wide
return list(res)
#######################################################################
# local filter on the object (container typically)
#######################################################################
def filterScoped( object, name = "", kind = "", role = "", otype = "", level = ""):
""" Search the hierarchy, starting from 'object' down
"""
# display some information about the criteria
print_details_what_we_search_for( object, name, kind, role, otype, level)
flt = p.CreateFilter()
flt.Name = name
flt.Kind = kind
flt.Role = role
flt.ObjType = otype
flt.Level = level
res = object.GetDescendantFCOs( flt) # filter used only down below container object in the hierarchy tree
return list(res)
#######################################################################
# demo methods for the usage of filter and filterScoped
#######################################################################
def query_demo_MetaGME():
""" demo for the MetaGME paradigm:
"""
# 'it.Valid' bool indicates whether a model window is currently
# shown (opened and active). In this case 'it.MgaModel' is a
# valid pointer to this container, so a scoped/local search
# can be invoked using it. Otherwise do a global search.
if it.Valid:
objects = filterScoped( it.MgaModel, "", "ModelProxy", "", "", "") # full param list used here but
else:
objects = filter( kind = "ModelProxy") # named parameters used, or we could have used again
#objects = filter( "", "ModelProxy", "", "", "") # this full parameter form
show_results_in_my_way( objects)
#######################################################################
def query_demo_SF():
""" demo for the SF paradigm:
Will demonstrate the use of Level criteria, which is relative to the container.
Level 1: child-parent relationship between the object and the container parameter.
Level 2: grandchild-grandparent relationship, etc.
Syntax: "1 2", "3-5", "1 2 5-7", "3-".
"""
# we will search among grandchildren, great-grandchildren etc. of it.MgaModel
if it.Valid:
objects = filterScoped( it.MgaModel, role = "InputSignals", level = "2-")
else:
objects = filter( role = "InputSignals", level = "2-")
show_results_in_my_way( objects)
#######################################################################
def query_demo_generic():
""" demo, which might make sense for any paradigm: will search for atoms (2) and references(3)
"""
if it.Valid:
objects = filterScoped( it.MgaModel, "", "", "", "2 3", "") # looking for Atoms (2) and References (3)?
else:
objects = filter( "", "", "", "2 3", "") # same on global scale
show_results_in_my_way( objects)
#######################################################################
def query_demo():
paradigm = p.MetaName # what is the paradigm name of the opened project?
if paradigm == "MetaGME":
query_demo_MetaGME() # execute MetaGME specific demo in case a metamodel is opened
elif paradigm == "SF":
query_demo_SF() # ... SF specific demo
else:
query_demo_generic() # ... generic demo, queries for atoms and references (probably there are such elements in any paradigm)
##############################################################################################
#
# Variables existing when the script is executed are
# -----------------------------------------------------
#
# project : the project variable (see Interfaces/Mga.idl)
# gme : the main application window (see Interfaces/GME.idl for IGMEOLEApp)
# it : the actively shown model (view) (see Interfaces/GME.idl for IGMEOLEIt)
#
###############################################################################################
# main() begins
#
cout( '--Hello World, this is Python here!--', 1)
terr = begin( p) # begin transaction (strictly needed to perform r/w operations on a IMgaProject)
try:
query_demo() # do a query
commit(p, terr) # commit transaction (strictly needed to return the project in a consistent mode)
except:
cout( 'Transaction aborted', 2) # 2 = MSG_WARNING (yellow)
abort(p, terr) # abort transaction if something went wrong
cout( '--End of Script--', 1)
p = None
g = None
Index: GMETraversor.py
===================================================================
RCS file: /project/gme-repository/GMESRC/SDK/Scripts/GMETraversor.py,v
retrieving revision 1.1
retrieving revision 1.2
diff -C2 -d -r1.1 -r1.2
*** GMETraversor.py 15 Apr 2008 19:10:50 -0000 1.1
--- GMETraversor.py 9 May 2008 14:06:43 -0000 1.2
***************
*** 1,5 ****
#################################################################################
#
! # This file contains Python methods for project-wide traversal or query.
# In addition it has helper methods for Model, Set, Reference objects.
# See bottom of the file for main()
--- 1,5 ----
#################################################################################
#
! # This file contains Python methods for project-wide traversal.
# In addition it has helper methods for Model, Set, Reference objects.
# See bottom of the file for main()
***************
*** 19,75 ****
#
#################################################################################
- #
- # Query for objects based on different criteria
- # _____________________________________________
- #
- #
- # filter() method:
- # Usable to do a project wide search based on Name, Kind, Role, ObjectType, Level.
- # ObjectType is an enum as follows:
- # Model = 1,
- # Atom = 2,
- # Reference = 3,
- # Connection = 4,
- # Set = 5,
- # Folder = 6
- # Level (depth) can be a space-separated list of numbers or dash-separated number pairs: e.g: 1-2 5 7
- #
- # filterScoped() method:
- # Usable to do a scoped search based on Name, Kind, Role, ObjectType, Level.
- # Starts from a container, performs search down in its containment tree.
- #
- #################################################################################
- #
- # Helper methods for different object types useable as follows
- # ____________________________________________________________
- #
- # Models:
- # MetaRoleObject = metaRoleByName( Model, KindString)
- # MetaRoleObject = metaRole( Object)
- # MetaNameString = metaName( Object)
- # NewChild = newChild( Model, KindString)
- # ClonedObject = clone( WhereModel, WhichObject)
- # delObj( Object)
- # ChildObject = childByName( Model, Name)
- # ListOfChildren = childrenByKind( Model, KindString)
- # ListOfChildren = children( Model)
- # Parent = parent( Object)
- # Connections:
- # NewConn = connect( Model, Source, Destination, ConnectionMetaRole)
- # NewConn = connectThruRefChain( Model, Source, Destination, SourceReferenceChain, DestinationReferenceChain, ConnectionMetaRole)
- # ListOfConns = partOfConns( Object)
- # References:
- # Tgt = getReferred( Ref)
- # setReferred( Ref, Tgt)
- # clearReference( Ref)
- # ListOfRefs = referredBy( Tgt)
- # Sets:
- # T/F = isMemberIn( Set, Member)
- # ListOfMembers = members( Set)
- # ListOfSets = memberOfSets( Member)
- # addToSet( Set, Member)
- # remFromSet( Set, Member)
- #
- #################################################################################
import win32com.client
--- 19,22 ----
***************
*** 80,269 ****
- #############################################################
- ## OBJTYPE_REFERENCE (3)
- #############################################################
- def getReferred( r):
- if( r and r.ObjType == 3):
- return r.Referred
- return
-
- def setReferred( r, o):
- if( r and r.ObjType == 3):
- r.Referred = o
- return
-
- def clearReference( r):
- """ Clears a reference's Referred property.
- r.Referred = 0 does not work unfortunately
- """
- if r.ObjType == 3:
- try:
- r.ClearRef() # from GME8 on
- except:
- cout( "Exception while clearing reference: " + r.Name + "!", 3)
- raise
- return
-
- def referredBy( o):
- return list( o.ReferencedBy)
-
- #############################################################
- ## OBJTYPE_SET (5)
- #############################################################
-
- def isMemberIn( s, o):
- # GetIsMemberDisp is not giving back correct results:
- #return s.ObjType == 5 and s.GetIsMemberDisp( o)
- # that's why an alternative implementation is used:
- #s.GetIsMemberDisp( o)
- return o in members(s)
-
- def members( s):
- if( s and s.ObjType == 5):
- return list( s.Members)
- return
-
- def memberOfSets( o):
- return list(o.MemberOfSets)
-
- def addToSet( s, o):
- if( s and s.ObjType == 5):
- s.AddMember( o)
-
-
- def remFromSet( s, o):
- if( s and s.ObjType == 5):
- s.RemoveMember( o)
-
- #############################################################
- ## OBJTYPE_CONNECTION
- #############################################################
-
- def connect( m, srco, dsto, conn_mrole):
- if( m.ObjType == 1): # Model
- c = m.CreateSimpleConn( conn_mrole, srco, dsto, None, None)
- c.Name = conn_mrole.Name
- return c
- return
-
- def connectThruRefChain( m, srco, dsto, src_ref_chain, dst_ref_chain, conn_mrole):
- if( m.ObjType == 1): # Model
- c = m.CreateSimpleConn( conn_mrole, srco, dsto, src_ref_chain, dst_ref_chain)
- c.Name = conn_mrole.Name
- return c
- return
-
- def partOfConns( o):
- conn_points = list( o.PartOfConns)
- conns = []
- for i in range(0, len(conn_points)):
- conns.append( conn_points[i].Owner)
- return conns
-
- #############################################################
- ## OBJTYPE_MODEL (1)
- #############################################################
-
- def metaRoleByName( m, kind_str):
- if m.ObjType == 1: # Model
- return m.Meta.GetRoleByNameDisp( kind_str)
- #return null
-
- def metaRole( o):
- return o.MetaRole
-
- def metaName( o):
- return o.Meta.Name
-
- def newChild( m, kind_str):
- if m.ObjType == 1:
- mrole = metaRoleByName( m, kind_str)
- if mrole:
- nch = m.CreateChildObject( mrole)
- nch.Name = mrole.Name
- return nch
- return
-
- def clone( m, orig):
- """ Clones orig object into m (model or folder).
- If orig is a folder, m needs to a folder too.
- """
- if m.ObjType not in (1, 6): return
- if not orig: return
-
- if m.ObjType == 6: # Target is a Folder
- if orig.ObjType == 6: cloned = m.CopyFolderDisp( orig) # Orig is Folder too
- else: cloned = m.CopyFCODisp( orig) # Orig is FCO
- elif m.ObjType == 1:
- cloned = m.CopyFCODisp( orig, metaRole( orig)) # Target is Model, Orig is FCO
-
- if cloned:
- cloned.Name = "Cloned" + orig.Name
- return cloned
-
- def delObj( o):
- """ Deletes an object o from its parent
- """
- if not o: return
- try:
- o.DestroyObject()
- except:
- cout( "Could not remove object '" + o.Name + "'!")
- raise # raise again the same exception
- return
-
- def childByName( m, name_str):
- if m.ObjType == 1:
- return m.GetChildFCODisp( name_str)
- return
-
- def childrenByKind( m, kind_str):
- if m.ObjType == 1:
- return list(m.GetChildrenOfKind( kind_str))
- return
-
- def children( m):
- if m.ObjType == 1:
- return list(m.ChildFCOs)
- return
-
- def parent( o):
- if o.ParentFolder : return o.ParentFolder # by checking ParentFolder first, we can use the same
- elif o.ObjType != 6 and o.ParentModel : return o.ParentModel # implementation for folders and fcos, since folders
- # have too a method named ParentFolder
- return
-
- #######################################################################
- # filter on project
- #######################################################################
-
- def filter( name = "", kind = "", role = "", otype = "", level = ""):
- flt = p.CreateFilter()
- flt.Name = name
- flt.Kind = kind
- flt.Role = role
- flt.ObjType = otype
- flt.Level = level
- res = p.AllFCOs( flt) # filter used project-wide
- cout( "Results follow: ", 1)
- for i in range(1, res.Count + 1):
- cout( res.Item(i).Name + " -> " + makeLink( res.Item(i)), 1)
-
- return list(res)
-
- def filterScoped( object, name = "", kind = "", role = "", otype = "", level = ""):
- flt = p.CreateFilter()
- flt.Name = name
- flt.Kind = kind
- flt.Role = role
- flt.ObjType = otype
- flt.Level = level
- res = object.GetDescendantFCOs( flt) # filter used only down below container object in the hierarchy tree
- cout( "Results follow: ", 1)
- for i in range(1, res.Count + 1):
- cout( res.Item(i).Name, 1)
-
- return list(res)
-
#######################################################################
# transaction handlers
--- 27,30 ----
***************
*** 413,426 ****
#######################################################################
# a generic handler for a visited object (fco or folder)
#######################################################################
! def handle( _gme, _obj):
try:
cout( _obj.ID + ' ~ ' + _obj.GetGUIDDisp() + ' ~ ' + _obj.Name)
finally:
pass
! #
! # or dump data to a file:
#
#f = open( 'c:\\visitation.txt', 'a')
#try:
--- 174,189 ----
#######################################################################
# a generic handler for a visited object (fco or folder)
+ # implement/change it the way you like it
#######################################################################
! def handle( _obj):
try:
+ # dump info to the console
cout( _obj.ID + ' ~ ' + _obj.GetGUIDDisp() + ' ~ ' + _obj.Name)
finally:
pass
!
#
+ # 1 alternative: dump data to a file:
#f = open( 'c:\\visitation.txt', 'a')
#try:
***************
*** 435,439 ****
#######################################################################
! def traverse_postorder( _gme, _current, _comparator):
to_visit = [] # a list (!tuple)
--- 198,202 ----
#######################################################################
! def traverse_postorder( _current, _comparator):
to_visit = [] # a list (!tuple)
***************
*** 444,455 ****
# 1st: traverse subtrees
for o in to_visit:
! traverse_postorder( _gme, o, _comparator)
# 2nd: handle current node
! handle( _gme, _current)
return
! def traverse_preorder( _gme, _current, _comparator):
to_visit = [] # a list (!tuple)
--- 207,218 ----
# 1st: traverse subtrees
for o in to_visit:
! traverse_postorder( o, _comparator)
# 2nd: handle current node
! handle( _current)
return
! def traverse_preorder( _current, _comparator):
to_visit = [] # a list (!tuple)
***************
*** 459,471 ****
# 1st: handle current node
! handle( _gme, _current)
# 2nd: traverse subtrees
for o in to_visit:
! traverse_preorder( _gme, o, _comparator)
return
! def traverse_inorder( _gme, _current, _comparator):
to_visit = [] # a list (!tuple)
--- 222,234 ----
# 1st: handle current node
! handle( _current)
# 2nd: traverse subtrees
for o in to_visit:
! traverse_preorder( o, _comparator)
return
! def traverse_inorder( _current, _comparator):
to_visit = [] # a list (!tuple)
***************
*** 481,496 ****
# 1st: traverse left children
for i in range( 0, separate_at):
! traverse_inorder( _gme, to_visit[i], _comparator)
# 2nd: handle current node
! handle( _gme, _current)
# 3rd: traverse right children
for i in range( separate_at, len(to_visit)):
! traverse_inorder( _gme, to_visit[i], _comparator)
return
! def traverse_levelled( _gme, _rootfolder, _comparator): # aka BFT, Breadth First Traversal with a fifo queue
to_visit = [] # a list (!tuple)
to_visit.append( _rootfolder)
--- 244,259 ----
# 1st: traverse left children
for i in range( 0, separate_at):
! traverse_inorder( to_visit[i], _comparator)
# 2nd: handle current node
! handle( _current)
# 3rd: traverse right children
for i in range( separate_at, len(to_visit)):
! traverse_inorder( to_visit[i], _comparator)
return
! def traverse_levelled( _rootfolder, _comparator): # aka BFT, Breadth First Traversal with a fifo queue
to_visit = [] # a list (!tuple)
to_visit.append( _rootfolder)
***************
*** 498,502 ****
while len( to_visit) > 0:
o = to_visit.pop(0) # pops the first element from the queue
! handle( _gme, o) # handle current node
if o.ObjType in (1, 6): # children for Models and Folders
--- 261,265 ----
while len( to_visit) > 0:
o = to_visit.pop(0) # pops the first element from the queue
! handle( o) # handle current node
if o.ObjType in (1, 6): # children for Models and Folders
***************
*** 507,512 ****
return
! def traverse_invoker( _methodFunc, _gme, _rootFolder, _comparatorFunc):
! _methodFunc( _gme, _rootFolder, _comparatorFunc) # simple call the _methodFunc with the provided parameters
return
--- 270,275 ----
return
! def traverse_invoker( _methodFunc, _rootFolder, _comparatorFunc):
! _methodFunc( _rootFolder, _comparatorFunc) # simple call the _methodFunc with the provided parameters
return
***************
*** 554,564 ****
#-----------------------------------
! traverse_invoker( used_algo, g, p.RootFolder, used_sort) # use this generic invoker or ...
#-----------------------------------
! #traverse_preorder ( g, p.RootFolder, used_sort) # or any of these direct invokations
! #traverse_postorder( g, p.RootFolder, used_sort)
! #traverse_inorder ( g, p.RootFolder, used_sort)
! #traverse_levelled ( g, p.RootFolder, used_sort)
--- 317,327 ----
#-----------------------------------
! traverse_invoker( used_algo, p.RootFolder, used_sort) # use this generic invoker or ...
#-----------------------------------
! #traverse_preorder ( p.RootFolder, used_sort) # or any of these direct invokations
! #traverse_postorder( p.RootFolder, used_sort)
! #traverse_inorder ( p.RootFolder, used_sort)
! #traverse_levelled ( p.RootFolder, used_sort)
***************
*** 576,588 ****
#
! cout( 'Hello World, this is Python here!', 1)
terr = begin( p) # begin transaction (strictly needed to perform r/w operations on a IMgaProject)
try:
traverse() # do a traversal
commit(p, terr) # commit transaction (strictly needed to return the project in a consistent mode)
except:
! cout( 'Need to abort', 2) # 2 means WARNING (yellow)
abort(p, terr) # abort transaction if something went wrong
! cout( 'End of Script', 1)
--- 339,355 ----
#
! cout( '--Hello World, this is Python here!--', 1)
terr = begin( p) # begin transaction (strictly needed to perform r/w operations on a IMgaProject)
try:
traverse() # do a traversal
+
commit(p, terr) # commit transaction (strictly needed to return the project in a consistent mode)
except:
! cout( 'Need to abort', 2) # 2 means MSG_WARNING (yellow)
abort(p, terr) # abort transaction if something went wrong
! cout( '--End of Script--', 1)
!
! p = None
! g = None
More information about the GME-commit
mailing list