LayerNames returns empty list after Open command launch from modeless dialog?

Hello,

I manage to put together a small UI named ModelessUILayerNamesTest.py showing the problem. It depends on Meier_UI_Utility.py so you need to put it into your Rhino search path. When you click its single Load Project button, it prompts you to open the SmallMultiLayerD20.3dm project having 4 layers with a single icosahedron on each one.

Opening this project, you will see traces in the console showing that the rs.LayerNames() function returns an empty list even though the project loaded without error and everything else seems to work.

I hope this small self-contained example will help you suggest me some work around for my modeless despair :wink:

Thanks!

UIModelessTest.zip (22.5 KB)

Hi Bruno,

Your sample was the key for figuring out what is going on - thanks for spending the time to type this up.

I’ll try my best to explain what is going on and how you can fix your code.

First, if you open the Layers.py file included with Rhino, you will see the following definition for the rs.LayerNames method:

def LayerNames(sort=False):
    rc = []
    for layer in scriptcontext.doc.Layers:
        if not layer.IsDeleted: rc.append(layer.FullPath)
    if sort: rc.sort()
    return rc

Notice the scriptcontext.doc statement. If you open scriptcontext.py, again included with Rhino, you will see this:

'''The Active Rhino document (Rhino.RhinoDoc in RhinoCommon) while a script
is executing. This variable is set by Rhino before the execution of every script.
'''
doc = None

When you first run your script, scriptcontext.doc is set to the active document.

Your script then calls rs.Command and opens a new document. The document referenced by scriptcontext.doc is no longer valid.

You then call rs.LayerNames, which tries to get layer names from an invalid document. Thus, nothing is returned.

To fix this problem, add the following statement immediately after opening a new document:

scriptcontext.doc = Rhino.RhinoDoc.ActiveDoc

Now, scriptcontext.doc references a valid document and all rs methods will work.

@stevebaer, @Alain, I’m not sure you’ve run into this before (I certainly haven’t). Something to bookmark I guess…

Let me know if there are any questions.

– Dale

1 Like

Thank you very much Dale! That was exactly the problem!

I renamed the title of the post to help people with similar problem find this solution more easily :wink: