Skip to content

Instantly share code, notes, and snippets.

@tin2tin
Last active December 13, 2020 10:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tin2tin/5546d7af099c36a3c47b054b28b38542 to your computer and use it in GitHub Desktop.
Save tin2tin/5546d7af099c36a3c47b054b28b38542 to your computer and use it in GitHub Desktop.
Allows exploration of the python api via the Blender user interface. Unfinished update - from 2.57
# development_api_navigator.py
#
# ***** BEGIN GPL LICENSE BLOCK *****
#
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ***** END GPL LICENCE BLOCK *****
bl_info = {
"name": "API_Navigator",
"author": "Dany Lebel (Axon_D)",
"version": (1, 0, 3),
"blender": (2, 80, 0),
"location": "Text Editor > Properties > API Navigator Panel",
"description": "Allows exploration of the python api via the user interface",
"warning": "",
"wiki_url": "http://wiki.blender.org/index.php/Extensions:2.6/Py/"
"Scripts/Text_Editor/API_Navigator",
"tracker_url": "http://projects.blender.org/tracker/index.php?func=detail&aid=24982",
"category": "Development",
}
"""
You can browse through the tree structure of the api. Each child object appears in a list
that tries to be representative of its type. These lists are :
* Items (for an iterable object)
* Item Values (for an iterable object wich only supports index)
* Modules
* Types
* Properties
* Structs and Functions
* Methods and Functions
* Attributes
* Inaccessible (some objects may be listed but inaccessible)
The lists can be filtered to help searching in the tree. Just enter the text in the
filter section. It is also possible to explore other modules. Go the the root and select
it in the list of available modules. It will be imported dynamically.
In the text section, some informations are displayed. The type of the object,
what it returns, and its docstring. We could hope that these docstrings will be as
descriptive as possible. This text data block named api_doc_ can be toggled on and off
with the Escape key. (but a bug prevent the keymap to register correctly at start)
"""
import bpy
from console.complete_import import get_root_modules
from bpy.props import StringProperty, IntProperty, PointerProperty
############ Global Variables ############
last_text = None # last text data block
root_module = None # root module of the tree
root_m_path = "" # root_module + path as a string
current_module = None # the object itself in the tree structure
tree_level = None # the list of objects from the current_module
def init_tree_level():
global tree_level
tree_level = [[], [], [], [], [], [], [], [], []]
init_tree_level()
api_doc_ = "" # the documentation formated for the API Navigator
module_type = None # the type of current_module
return_report = "" # what current_module returns
filter_mem = {} # remember last filters entered for each path
too_long = False # is tree_level list too long to display in a panel?
############ Functions ############
def get_root_module(path):
# print('get_root_module')
global root_module
if "." in path:
root = path[: path.find(".")]
else:
root = path
try:
root_module = __import__(root)
except:
root_module = None
def evaluate(module):
# print('evaluate')
global root_module, tree_level, root_m_path
# path = bpy.context.window_manager.api_nav_props.path
try:
len_name = root_module.__name__.__len__()
root_m_path = "root_module" + module[len_name:]
current_module = eval(root_m_path)
return current_module
except:
init_tree_level
return None
def get_tree_level():
# print('get_tree_level')
path = bpy.context.window_manager.api_nav_props.path
def object_list():
# print('object_list')
global current_module, root_m_path
itm, val, mod, typ, props, struct, met, att, bug = (
[],
[],
[],
[],
[],
[],
[],
[],
[],
)
iterable = isiterable(current_module)
if iterable:
iter(current_module)
current_type = str(module_type)
if current_type != "<class 'str'>":
if iterable == "a":
# if iterable == 'a':
# current_type.__iter__()
itm = list(current_module.keys())
if not itm:
val = list(current_module)
else:
val = list(current_module)
for i in dir(current_module):
try:
t = str(type(eval(root_m_path + "." + i)))
except (AttributeError, SyntaxError):
bug += [i]
continue
if t == "<class 'module'>":
mod += [i]
elif t[0:16] == "<class 'bpy_prop":
props += [i]
elif t[8:11] == "bpy":
struct += [i]
elif t == "<class 'builtin_function_or_method'>":
met += [i]
elif t == "<class 'type'>":
typ += [i]
else:
att += [i]
return [itm, val, mod, typ, props, struct, met, att, bug]
if not path:
return [[], [], [i for i in get_root_modules()], [], [], [], [], [], []]
return object_list()
def parent(path):
"""Returns the parent path"""
# print('parent')
parent = path
if parent[-1] == "]" and "[" in parent:
while parent[-1] != "[":
parent = parent[:-1]
elif "." in parent:
while parent[-1] != ".":
parent = parent[:-1]
else:
return ""
parent = parent[:-1]
return parent
def update_filter():
"""Update the filter according to the current path"""
global filter_mem
try:
bpy.context.window_manager.api_nav_props.filter = filter_mem[
bpy.context.window_manager.api_nav_props.path
]
except:
bpy.context.window_manager.api_nav_props.filter = ""
def isiterable(mod):
try:
iter(mod)
except:
return False
try:
mod[""]
return "a"
except KeyError:
return "a"
except (AttributeError, TypeError):
return "b"
def fill_filter_mem():
global filter_mem
filter = bpy.context.window_manager.api_nav_props.filter
if filter:
filter_mem[
bpy.context.window_manager.api_nav_props.old_path
] = bpy.context.window_manager.api_nav_props.filter
else:
filter_mem.pop(bpy.context.window_manager.api_nav_props.old_path, None)
###### API Navigator parent class #######
class ApiNavigator:
"""Parent class for API Navigator"""
@staticmethod
def generate_global_values():
"""Populate the level attributes to display the panel buttons and the documentation"""
global tree_level, current_module, module_type, return_report, last_text
text = bpy.context.space_data.text
if text:
if text.name != "api_doc_":
last_text = bpy.context.space_data.text.name
elif bpy.data.texts.__len__() < 2:
last_text = None
else:
last_text = None
bpy.context.window_manager.api_nav_props.pages = 0
get_root_module(bpy.context.window_manager.api_nav_props.path)
current_module = evaluate(bpy.context.window_manager.api_nav_props.path)
module_type = str(type(current_module))
return_report = str(current_module)
tree_level = get_tree_level()
if tree_level.__len__() > 30:
global too_long
too_long = True
else:
too_long = False
ApiNavigator.generate_api_doc()
return {"FINISHED"}
@staticmethod
def generate_api_doc():
"""Format the doc string for API Navigator"""
global current_module, api_doc_, return_report, module_type
path = bpy.context.window_manager.api_nav_props.path
line = "-" * (path.__len__() + 2)
header = """\n\n\n\t\t%s\n\t %s\n\
_____________________________________________\n\
\n\
Type : %s\n\
\n\
\n\
Return : %s\n\
_____________________________________________\n\
\n\
Doc:
\n\
""" % (
path,
line,
module_type,
return_report,
)
footer = "\n\
_____________________________________________\n\
\n\
\n\
\n\
#############################################\n\
# api_doc_ #\n\
# Escape to toggle text #\n\
# (F8 to reload modules if doesn't work) #\n\
#############################################"
doc = current_module.__doc__
api_doc_ = header + str(doc) + footer
return {"FINISHED"}
@staticmethod
def doc_text_datablock():
"""Create the text databloc or overwrite it if it already exist"""
global api_doc_
space_data = bpy.context.space_data
try:
doc_text = bpy.data.texts["api_doc_"]
space_data.text = doc_text
doc_text.clear()
except:
bpy.data.texts.new(name="api_doc_")
doc_text = bpy.data.texts["api_doc_"]
space_data.text = doc_text
doc_text.write(text=api_doc_)
return {"FINISHED"}
############ Operators ############
def api_update(context):
if (
bpy.context.window_manager.api_nav_props.path
!= bpy.context.window_manager.api_nav_props.old_path
):
fill_filter_mem()
bpy.context.window_manager.api_nav_props.old_path = (
bpy.context.window_manager.api_nav_props.path
)
update_filter()
ApiNavigator.generate_global_values()
ApiNavigator.doc_text_datablock()
class Update(ApiNavigator, bpy.types.Operator):
"""Update the tree structure"""
bl_idname = "api_navigator.update"
bl_label = "API Navigator Update"
def execute(self, context):
api_update()
return {"FINISHED"}
class BackToBpy(ApiNavigator, bpy.types.Operator):
"""go back to module bpy"""
bl_idname = "api_navigator.back_to_bpy"
bl_label = "Back to bpy"
def execute(self, context):
fill_filter_mem()
if not bpy.context.window_manager.api_nav_props.path:
bpy.context.window_manager.api_nav_props.old_path = (
bpy.context.window_manager.api_nav_props.path
) = "bpy"
else:
bpy.context.window_manager.api_nav_props.old_path = (
bpy.context.window_manager.api_nav_props.path
) = "bpy"
update_filter()
self.generate_global_values()
self.doc_text_datablock()
return {"FINISHED"}
class Down(ApiNavigator, bpy.types.Operator):
"""go to this Module"""
bl_idname = "api_navigator.down"
bl_label = "API Navigator Down"
pointed_module: bpy.props.StringProperty(name="Current Module", default="")
def execute(self, context):
fill_filter_mem()
if not bpy.context.window_manager.api_nav_props.path:
bpy.context.window_manager.api_nav_props.old_path = (
bpy.context.window_manager.api_nav_props.path
) = (bpy.context.window_manager.api_nav_props.path + self.pointed_module)
else:
bpy.context.window_manager.api_nav_props.old_path = (
bpy.context.window_manager.api_nav_props.path
) = (
bpy.context.window_manager.api_nav_props.path
+ "."
+ self.pointed_module
)
update_filter()
self.generate_global_values()
self.doc_text_datablock()
return {"FINISHED"}
class Parent(ApiNavigator, bpy.types.Operator):
"""go to Parent Module"""
bl_idname = "api_navigator.parent"
bl_label = "API Navigator Parent"
def execute(self, context):
path = bpy.context.window_manager.api_nav_props.path
if path:
fill_filter_mem()
bpy.context.window_manager.api_nav_props.old_path = (
bpy.context.window_manager.api_nav_props.path
) = parent(bpy.context.window_manager.api_nav_props.path)
update_filter()
self.generate_global_values()
self.doc_text_datablock()
return {"FINISHED"}
class ClearFilter(ApiNavigator, bpy.types.Operator):
"""Clear the filter"""
bl_idname = "api_navigator.clear_filter"
bl_label = "API Nav clear filter"
def execute(self, context):
bpy.context.window_manager.api_nav_props.filter = ""
return {"FINISHED"}
class FakeButton(ApiNavigator, bpy.types.Operator):
"""The list is not displayed completely""" # only serve as an indicator
bl_idname = "api_navigator.fake_button"
bl_label = ""
class Subscript(ApiNavigator, bpy.types.Operator):
"""Subscript to this Item"""
bl_idname = "api_navigator.subscript"
bl_label = "API Navigator Subscript"
subscription: bpy.props.StringProperty(name="", default="")
def execute(self, context):
fill_filter_mem()
bpy.context.window_manager.api_nav_props.old_path = (
bpy.context.window_manager.api_nav_props.path
) = (
bpy.context.window_manager.api_nav_props.path
+ "["
+ self.subscription
+ "]"
)
update_filter()
self.generate_global_values()
self.doc_text_datablock()
return {"FINISHED"}
class Toggle_doc(ApiNavigator, bpy.types.Operator):
"""Toggle on or off api_doc_ Text"""
bl_idname = "api_navigator.toggle_doc"
bl_label = "Toggle api_doc_"
def execute(self, context):
global last_text
try:
if bpy.context.space_data.text.name != "api_doc_":
last_text = bpy.context.space_data.text.name
except:
pass
try:
text = bpy.data.texts["api_doc_"]
bpy.data.texts["api_doc_"].clear()
bpy.data.texts.remove(text)
except KeyError:
self.doc_text_datablock()
return {"FINISHED"}
try:
text = bpy.data.texts[last_text]
bpy.context.space_data.text = text
# line = bpy.ops.text.line_number() # operator doesn't seems to work ???
# bpy.ops.text.jump(line=line)
return {"FINISHED"}
except:
pass
bpy.context.space_data.text = None
return {"FINISHED"}
############ UI Panels ############
class OBJECT_PT_api_navigator(ApiNavigator, bpy.types.Panel):
bl_label = "API Navigator"
bl_idname = "TEXT_PT_api_navigator"
bl_space_type = "TEXT_EDITOR"
bl_region_type = "UI"
bl_options = {"DEFAULT_CLOSED"}
columns = 3
def iterable_draw(self):
global tree_level, current_module
iterable = isiterable(current_module)
if iterable:
iter(current_module)
current_type = str(module_type)
if current_type == "<class 'str'>":
return {"FINISHED"}
col = self.layout
# filter = bpy.context.window_manager.api_nav_props.filter # UNUSED
reduce_to = (
bpy.context.window_manager.api_nav_props.reduce_to * self.columns
)
pages = bpy.context.window_manager.api_nav_props.pages
page_index = reduce_to * pages
# rank = 0 # UNUSED
count = 0
i = 0
filtered = 0
if iterable == "a":
current_type.__iter__()
collection = list(current_module.keys())
end = collection.__len__()
box = self.layout.box()
row = box.row()
row.label(text="Items", icon="TRIA_DOWN")
box = box.box()
col = box.column(align=True)
while count < reduce_to and i < end:
mod = collection[i]
if filtered < page_index:
filtered += 1
i += 1
continue
if not (i % self.columns):
row = col.row()
row.operator(
"api_navigator.subscript", text=mod, emboss=False
).subscription = ('"' + mod + '"')
filtered += 1
i += 1
count += 1
elif iterable == "b":
box = self.layout.box()
row = box.row()
row.label(text="Item Values", icon="OOPS")
box = box.box()
col = box.column(align=True)
collection = list(current_module)
end = collection.__len__()
while count < reduce_to and i < end:
mod = str(collection[i])
if filtered < page_index:
filtered += 1
i += 1
continue
if not (i % self.columns):
row = col.row()
row.operator(
"api_navigator.subscript", text=mod, emboss=False
).subscription = str(i)
filtered += 1
i += 1
count += 1
too_long = end > 30
if too_long:
row = col.row()
row.prop(bpy.context.window_manager.api_nav_props, "reduce_to")
row.operator(
"api_navigator.fake_button", text="", emboss=False, icon="DOTSDOWN"
)
row.prop(
bpy.context.window_manager.api_nav_props, "pages", text="Pages"
)
return {"FINISHED"}
def list_draw(self, t, pages, icon, label=None, emboss=False):
global tree_level, current_module
def reduced(too_long):
if too_long:
row = col.row()
row.prop(bpy.context.window_manager.api_nav_props, "reduce_to")
row.operator(
"api_navigator.fake_button", text="", emboss=False, icon="DOTSDOWN"
)
row.prop(
bpy.context.window_manager.api_nav_props, "pages", text="Pages"
)
layout = self.layout
filter = bpy.context.window_manager.api_nav_props.filter
reduce_to = bpy.context.window_manager.api_nav_props.reduce_to * self.columns
page_index = reduce_to * pages
len = tree_level[t].__len__()
too_long = len > reduce_to
if len:
col = layout.column()
box = col.box()
row = box.row()
row.label(text=label, icon=icon)
if t < 2:
box = box.box()
row = box.row()
col = row.column(align=True)
i = 0
objects = 0
count = 0
filtered = 0
while count < reduce_to and i < len:
obj = tree_level[t][i]
if filter and filter not in obj:
i += 1
continue
elif filtered < page_index:
filtered += 1
i += 1
continue
if not (objects % self.columns):
row = col.row()
if t > 1:
row.operator(
"api_navigator.down", text=obj, emboss=emboss
).pointed_module = obj
elif t == 0:
row.operator(
"api_navigator.subscript", text=str(obj), emboss=False
).subscription = ('"' + obj + '"')
else:
row.operator(
"api_navigator.subscript", text=str(obj), emboss=False
).subscription = str(i)
filtered += 1
i += 1
objects += 1
count += 1
reduced(too_long)
return {"FINISHED"}
def draw(self, context):
global tree_level, current_module, module_type, return_report
api_update(context)
###### layout ######
layout = self.layout
layout.label(text="Tree Structure:")
col = layout.column(align=True)
col.prop(bpy.context.window_manager.api_nav_props, "path", text="")
row = col.row()
row.operator("api_navigator.parent", text="Parent", icon="BACK")
row.operator(
"api_navigator.back_to_bpy", text="", emboss=True, icon="FILE_PARENT"
)
col = layout.column()
row = col.row(align=True)
row.prop(bpy.context.window_manager.api_nav_props, "filter")
row.operator("api_navigator.clear_filter", text="", icon="PANEL_CLOSE")
col = layout.column()
pages = bpy.context.window_manager.api_nav_props.pages
self.list_draw(0, pages, "DOTSDOWN", label="Items")
self.list_draw(1, pages, "DOTSDOWN", label="Item Values")
self.list_draw(2, pages, "PACKAGE", label="Modules", emboss=True)
self.list_draw(3, pages, "WORDWRAP_ON", label="Types", emboss=False)
self.list_draw(4, pages, "BUTS", label="Properties", emboss=False)
self.list_draw(5, pages, "OOPS", label="Structs and Functions")
self.list_draw(6, pages, "SCRIPTWIN", label="Methods and Functions")
self.list_draw(7, pages, "INFO", label="Attributes")
self.list_draw(8, pages, "ERROR", label="Inaccessible")
########### Menu functions ###############
class ApiNavProps(bpy.types.PropertyGroup):
"""
Fake module like class.
bpy.context.window_manager.api_nav_props
"""
path: StringProperty(
name="path",
description="Enter bpy.ops.api_navigator to see the documentation",
default="bpy",
)
old_path: StringProperty(name="old_path", default="")
filter: StringProperty(
name="filter", description="Filter the resulting modules", default=""
)
reduce_to: IntProperty(
name="Reduce to ",
description="Display a maximum number of x entries by pages",
default=10,
min=1,
)
pages: IntProperty(name="Pages", description="Display a Page", default=0, min=0)
def register_keymaps():
kc = bpy.context.window_manager.keyconfigs.addon
if kc:
km = kc.keymaps.new(name="Text", space_type="TEXT_EDITOR")
km.keymap_items.new("api_navigator.toggle_doc", "ESC", "PRESS")
def unregister_keymaps():
kc = bpy.context.window_manager.keyconfigs.addon
if kc:
km = kc.keymaps["Text"]
kmi = km.keymap_items["api_navigator.toggle_doc"]
km.keymap_items.remove(kmi)
classes = (
ApiNavProps,
# ApiNavigator,
Update,
BackToBpy,
Down,
Parent,
ClearFilter,
FakeButton,
Subscript,
Toggle_doc,
OBJECT_PT_api_navigator,
)
def register():
from bpy.utils import register_class
for cls in classes:
register_class(cls)
bpy.types.WindowManager.api_nav_props = PointerProperty(
type=ApiNavProps, name="API Nav Props", description=""
)
register_keymaps()
# print(get_tree_level())
def unregister():
from bpy.utils import unregister_class
unregister_keymaps()
for cls in reversed(classes):
unregister_class(cls)
del bpy.types.WindowManager.api_nav_props
if __name__ == "__main__":
register()
@Skywola
Copy link

Skywola commented Dec 13, 2020

Tried running this from the text editor in Blender 2.91:
Traceback (most recent call last):
File "\api_navigator.py", line 790, in
File "\api_navigator.py", line 770, in register
RuntimeError: register_class(...):, missing bl_rna attribute from 'type' instance (may not be registered)
Error: Python script failed, check the message in the system console

Error falls on 2nd line in this:
for cls in classes: register_class(cls) bpy.types.WindowManager.api_nav_props = PointerProperty( type=ApiNavProps, name="API Nav Props", description="" )

I have seen this error before in some of my own code, but I do not remember exactly what causes it. I think it has something to do with the
bl - declarations under one of the classes.

@tin2tin
Copy link
Author

tin2tin commented Dec 13, 2020

I'm sorry. I can't remember in what state I uploaded it as a gist. It is very likely I've given the old script from 2010 an update in my script updater add-on, and just uploaded it in that state - it might not have worked at all for 2.80. It would be cool to have it working, so let me know find a way to solve those problems. There is a bit about the original script here: https://developer.blender.org/T24982

@tin2tin
Copy link
Author

tin2tin commented Dec 13, 2020

Noticed a few things in the registering code. So now a UI shows up.

I don't know how this is supposed to work - and if it does work at all.

(I noticed I wrote at the top: Unfinished update - from 2.57)

@Skywola
Copy link

Skywola commented Dec 13, 2020 via email

@Skywola
Copy link

Skywola commented Dec 13, 2020

I used the search function I created to search for the components of this part of the code . . . .

bpy.types.WindowManager.api_nav_props = PointerProperty(type=ApiNavProps, name="API Nav Props", description="")

It appears that there is nothing there of that type any more.
For wbpy.types.WindowManager:
dir(bpy.types.WindowManager), nothing close to "api_nav_props", maybe it is a custom property?
['class', 'contains', 'delattr', 'delitem', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'getitem', 'gt', 'hash', 'init', 'init_subclass', 'le', 'lt', 'module', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'setattr', 'setitem', 'sizeof', 'slots', 'str', 'subclasshook', 'addon_filter', 'addon_search', 'addon_support', 'as_pointer', 'bl_rna', 'bl_rna_get_subclass', 'bl_rna_get_subclass_py', 'clipboard', 'draw_cursor_add', 'draw_cursor_remove', 'driver_add', 'driver_remove', 'fileselect_add', 'get', 'gizmo_group_type_ensure', 'gizmo_group_type_unlink_delayed', 'id_data', 'invoke_confirm', 'invoke_popup', 'invoke_props_dialog', 'invoke_props_popup', 'invoke_search_popup', 'is_property_hidden', 'is_property_overridable_library', 'is_property_readonly', 'is_property_set', 'items', 'keyframe_delete', 'keyframe_insert', 'keys', 'modal_handler_add', 'operator_properties_last', 'path_from_id', 'path_resolve', 'piemenu_begin__internal', 'piemenu_end__internal', 'pop', 'popmenu_begin__internal', 'popmenu_end__internal', 'popover', 'popover_begin__internal', 'popover_end__internal', 'popup_menu', 'popup_menu_pie', 'preset_name', 'property_overridable_library_set', 'property_unset', 'tag_script_reload', 'type_recast', 'values']

PointerProperty( in the console, press tab and you get nothing, it is like this whole part of the code is no longer in the API. (I have not searched the actual API, I pretty much consider the API worthless anyway, when you can find everything you need in the console.)

@Skywola
Copy link

Skywola commented Dec 13, 2020

I found PointerProperty . . . after doing the import in the console.

PointerProperty(type=None, name="", description="", options={'ANIMATABLE'}, override=set()
.. function:: PointerProperty(type=None, name="", description="", options={'ANIMATABLE'}, override=set(), tags=set(), poll=None, update=None)
Returns a new pointer property definition.
:arg type: A subclass of :class:bpy.types.PropertyGroup or :class:bpy.types.ID.
:type type: class
:arg name: Name used in the user interface.
:type name: string
:arg description: Text used for the tooltip and api documentation.
:type description: string
:arg options: Enumerator in ['HIDDEN', 'SKIP_SAVE', 'ANIMATABLE', 'LIBRARY_EDITABLE', 'PROPORTIONAL','TEXTEDIT_UPDATE'].
:type options: set
:arg override: Enumerator in ['LIBRARY_OVERRIDABLE'].
:type override: set
:arg tags: Enumerator of tags that are defined by parent class.
:type tags: set
:arg poll: function to be called to determine whether an item is valid for this property.
The function must take 2 values (self, object) and return Bool.
:type poll: function
:arg update: Function to be called when this value is modified,
This function must take 2 values (self, context) and return None.
Warning there are no safety checks to avoid infinite recursion.

@Skywola
Copy link

Skywola commented Dec 13, 2020

Was able to get it to run without error, but all I see in the text editor is "api_doc_" as the document name, the rest is blank

@Skywola
Copy link

Skywola commented Dec 13, 2020

What you might try doing is testing out the individual functions in the console. The thing is when running in the console, you have to avoid blank spaces, so you would have to run it with them taken out. That might allow you to narrow it down to what function is failing, I do not really understand the code well, the parameters, or even more so, how it is suppose to operate.

import bpy
from console.complete_import import get_root_modules
from bpy.props import StringProperty, IntProperty, PointerProperty

############ Global Variables ############
last_text = None # last text data block
root_module = None # root module of the tree
root_m_path = "" # root_module + path as a string
current_module = None # the object itself in the tree structure
tree_level = None # the list of objects from the current_module

def init_tree_level():
global tree_level
tree_level = [[], [], [], [], [], [], [], [], []]

init_tree_level()
api_doc_ = "" # the documentation formated for the API Navigator
module_type = None # the type of current_module
return_report = "" # what current_module returns
filter_mem = {} # remember last filters entered for each path
too_long = False # is tree_level list too long to display in a panel?

############ Functions ############
def get_root_module(path):
# print('get_root_module')
global root_module
if "." in path:
root = path[: path.find(".")]
else:
root = path
try:
root_module = import(root)
except:
root_module = None

def evaluate(module):
# print('evaluate')
global root_module, tree_level, root_m_path
#
# path = bpy.context.window_manager.api_nav_props.path
try:
len_name = root_module.name.len()
root_m_path = "root_module" + module[len_name:]
current_module = eval(root_m_path)
return current_module
except:
init_tree_level
return None

def get_tree_level():
# print('get_tree_level')
path = bpy.context.window_manager.api_nav_props.path
def object_list():
# print('object_list')
global current_module, root_m_path
itm, val, mod, typ, props, struct, met, att, bug = (
[],
[],
[],
[],
[],
[],
[],
[],
[],
)
iterable = isiterable(current_module)
if iterable:
iter(current_module)
current_type = str(module_type)
if current_type != "<class 'str'>":
if iterable == "a":
# if iterable == 'a':
# current_type.iter()
itm = list(current_module.keys())
if not itm:
val = list(current_module)
else:
val = list(current_module)
for i in dir(current_module):
try:
t = str(type(eval(root_m_path + "." + i)))
except (AttributeError, SyntaxError):
bug += [i]
continue
if t == "<class 'module'>":
mod += [i]
elif t[0:16] == "<class 'bpy_prop":
props += [i]
elif t[8:11] == "bpy":
struct += [i]
elif t == "<class 'builtin_function_or_method'>":
met += [i]
elif t == "<class 'type'>":
typ += [i]
else:
att += [i]
return [itm, val, mod, typ, props, struct, met, att, bug]
#
if not path:
return [[], [], [i for i in get_root_modules()], [], [], [], [], [], []]
return object_list()

def parent(path):
"""Returns the parent path"""
# print('parent')
parent = path
if parent[-1] == "]" and "[" in parent:
while parent[-1] != "[":
parent = parent[:-1]
elif "." in parent:
while parent[-1] != ".":
parent = parent[:-1]
else:
return ""
parent = parent[:-1]
return parent

def update_filter():
"""Update the filter according to the current path"""
global filter_mem
try:
bpy.context.window_manager.api_nav_props.filter = filter_mem[
bpy.context.window_manager.api_nav_props.path
]
except:
bpy.context.window_manager.api_nav_props.filter = ""

def isiterable(mod):
try:
iter(mod)
except:
return False
try:
mod[""]
return "a"
except KeyError:
return "a"
except (AttributeError, TypeError):
return "b"

def fill_filter_mem():
global filter_mem
filter = bpy.context.window_manager.api_nav_props.filter
if filter:
filter_mem[
bpy.context.window_manager.api_nav_props.old_path
] = bpy.context.window_manager.api_nav_props.filter
else:
filter_mem.pop(bpy.context.window_manager.api_nav_props.old_path, None)

API Navigator parent class

class ApiNavigator:
"""Parent class for API Navigator"""
@staticmethod
def generate_global_values():
"""Populate the level attributes to display the panel buttons and the documentation"""
global tree_level, current_module, module_type, return_report, last_text
text = bpy.context.space_data.text
if text:
if text.name != "api_doc_":
last_text = bpy.context.space_data.text.name
elif bpy.data.texts.len() < 2:
last_text = None
else:
last_text = None
bpy.context.window_manager.api_nav_props.pages = 0
get_root_module(bpy.context.window_manager.api_nav_props.path)
current_module = evaluate(bpy.context.window_manager.api_nav_props.path)
module_type = str(type(current_module))
return_report = str(current_module)
tree_level = get_tree_level()
if tree_level.len() > 30:
global too_long
too_long = True
else:
too_long = False
ApiNavigator.generate_api_doc()
return {"FINISHED"}
#
@staticmethod
def generate_api_doc():
"""Format the doc string for API Navigator"""
global current_module, api_doc_, return_report, module_type
path = bpy.context.window_manager.api_nav_props.path
line = "-" * (path.len() + 2)
header = """\n\n\n\t\t%s\n\t %s\n
_____________________________________________\n
\n
Type : %s\n
\n
\n
Return : %s\n
_____________________________________________\n
\n
Doc:
\n
""" % (
path,
line,
module_type,
return_report,
)
footer = "\n
_____________________________________________\n
\n
\n
\n
#############################################\n\

api_doc_ #\n\

Escape to toggle text #\n\

(F8 to reload modules if doesn't work) #\n\

#############################################"
doc = current_module.doc
api_doc_ = header + str(doc) + footer
return {"FINISHED"}
#
@staticmethod
def doc_text_datablock():
"""Create the text databloc or overwrite it if it already exist"""
global api_doc_
space_data = bpy.context.space_data
try:
doc_text = bpy.data.texts["api_doc_"]
space_data.text = doc_text
doc_text.clear()
except:
bpy.data.texts.new(name="api_doc_")
doc_text = bpy.data.texts["api_doc_"]
space_data.text = doc_text
doc_text.write(text=api_doc_)
return {"FINISHED"}

############ Operators ############
def api_update(context):
if (bpy.context.window_manager.api_nav_props.path
!= bpy.context.window_manager.api_nav_props.old_path):
fill_filter_mem()
bpy.context.window_manager.api_nav_props.old_path = (
bpy.context.window_manager.api_nav_props.path
)
update_filter()
ApiNavigator.generate_global_values()
ApiNavigator.doc_text_datablock()

class Update(ApiNavigator, bpy.types.Operator):
"""Update the tree structure"""
bl_idname = "api_navigator.update"
bl_label = "API Navigator Update"
#
def execute(self, context):
api_update()
return {"FINISHED"}

class BackToBpy(ApiNavigator, bpy.types.Operator):
"""go back to module bpy"""
bl_idname = "api_navigator.back_to_bpy"
bl_label = "Back to bpy"
#
def execute(self, context):
fill_filter_mem()
if not bpy.context.window_manager.api_nav_props.path:
bpy.context.window_manager.api_nav_props.old_path = (
bpy.context.window_manager.api_nav_props.path
) = "bpy"
else:
bpy.context.window_manager.api_nav_props.old_path = (
bpy.context.window_manager.api_nav_props.path
) = "bpy"
update_filter()
self.generate_global_values()
self.doc_text_datablock()
return {"FINISHED"}

class Down(ApiNavigator, bpy.types.Operator):
"""go to this Module"""
bl_idname = "api_navigator.down"
bl_label = "API Navigator Down"
pointed_module: bpy.props.StringProperty(name="Current Module", default="")
#
def execute(self, context):
fill_filter_mem()
if not bpy.context.window_manager.api_nav_props.path:
bpy.context.window_manager.api_nav_props.old_path = (
bpy.context.window_manager.api_nav_props.path
) = (bpy.context.window_manager.api_nav_props.path + self.pointed_module)
else:
bpy.context.window_manager.api_nav_props.old_path = (
bpy.context.window_manager.api_nav_props.path
) = (
bpy.context.window_manager.api_nav_props.path
+ "."
+ self.pointed_module
)
update_filter()
self.generate_global_values()
self.doc_text_datablock()
return {"FINISHED"}

class Parent(ApiNavigator, bpy.types.Operator):
"""go to Parent Module"""
bl_idname = "api_navigator.parent"
bl_label = "API Navigator Parent"
def execute(self, context):
path = bpy.context.window_manager.api_nav_props.path
if path:
fill_filter_mem()
bpy.context.window_manager.api_nav_props.old_path = (
bpy.context.window_manager.api_nav_props.path
) = parent(bpy.context.window_manager.api_nav_props.path)
update_filter()
self.generate_global_values()
self.doc_text_datablock()
return {"FINISHED"}

class ClearFilter(ApiNavigator, bpy.types.Operator):
"""Clear the filter"""
bl_idname = "api_navigator.clear_filter"
bl_label = "API Nav clear filter"
def execute(self, context):
bpy.context.window_manager.api_nav_props.filter = ""
return {"FINISHED"}

class FakeButton(ApiNavigator, bpy.types.Operator):
"""The list is not displayed completely""" # only serve as an indicator
bl_idname = "api_navigator.fake_button"
bl_label = ""

class Subscript(ApiNavigator, bpy.types.Operator):
"""Subscript to this Item"""
bl_idname = "api_navigator.subscript"
bl_label = "API Navigator Subscript"
subscription: bpy.props.StringProperty(name="", default="")
def execute(self, context):
fill_filter_mem()
bpy.context.window_manager.api_nav_props.old_path = (
bpy.context.window_manager.api_nav_props.path
) = (
bpy.context.window_manager.api_nav_props.path
+ "["
+ self.subscription
+ "]"
)
update_filter()
self.generate_global_values()
self.doc_text_datablock()
return {"FINISHED"}

class Toggle_doc(ApiNavigator, bpy.types.Operator):
"""Toggle on or off api_doc_ Text"""
bl_idname = "api_navigator.toggle_doc"
bl_label = "Toggle api_doc_"
def execute(self, context):
global last_text
try:
if bpy.context.space_data.text.name != "api_doc_":
last_text = bpy.context.space_data.text.name
except:
pass
try:
text = bpy.data.texts["api_doc_"]
bpy.data.texts["api_doc_"].clear()
bpy.data.texts.remove(text)
except KeyError:
self.doc_text_datablock()
return {"FINISHED"}
try:
text = bpy.data.texts[last_text]
bpy.context.space_data.text = text
# line = bpy.ops.text.line_number() # operator doesn't seems to work ???
# bpy.ops.text.jump(line=line)
return {"FINISHED"}
except:
pass
bpy.context.space_data.text = None
return {"FINISHED"}

############ UI Panels ############
class OBJECT_PT_api_navigator(ApiNavigator, bpy.types.Panel):
bl_label = "API Navigator"
bl_idname = "TEXT_PT_api_navigator"
bl_space_type = "TEXT_EDITOR"
bl_region_type = "UI"
bl_options = {"DEFAULT_CLOSED"}
columns = 3
def iterable_draw(self):
global tree_level, current_module
iterable = isiterable(current_module)
if iterable:
iter(current_module)
current_type = str(module_type)
if current_type == "<class 'str'>":
return {"FINISHED"}
col = self.layout
# filter = bpy.context.window_manager.api_nav_props.filter # UNUSED
reduce_to = (
bpy.context.window_manager.api_nav_props.reduce_to * self.columns
)
pages = bpy.context.window_manager.api_nav_props.pages
page_index = reduce_to * pages
# rank = 0 # UNUSED
count = 0
i = 0
filtered = 0
if iterable == "a":
current_type.iter()
collection = list(current_module.keys())
end = collection.len()
box = self.layout.box()
row = box.row()
row.label(text="Items", icon="TRIA_DOWN")
box = box.box()
col = box.column(align=True)
while count < reduce_to and i < end:
mod = collection[i]
if filtered < page_index:
filtered += 1
i += 1
continue
if not (i % self.columns):
row = col.row()
row.operator(
"api_navigator.subscript", text=mod, emboss=False
).subscription = ('"' + mod + '"')
filtered += 1
i += 1
count += 1
elif iterable == "b":
box = self.layout.box()
row = box.row()
row.label(text="Item Values", icon="OOPS")
box = box.box()
col = box.column(align=True)
collection = list(current_module)
end = collection.len()
while count < reduce_to and i < end:
mod = str(collection[i])
if filtered < page_index:
filtered += 1
i += 1
continue
if not (i % self.columns):
row = col.row()
row.operator(
"api_navigator.subscript", text=mod, emboss=False
).subscription = str(i)
filtered += 1
i += 1
count += 1
too_long = end > 30
if too_long:
row = col.row()
row.prop(bpy.context.window_manager.api_nav_props, "reduce_to")
row.operator(
"api_navigator.fake_button", text="", emboss=False, icon="DOTSDOWN"
)
row.prop(
bpy.context.window_manager.api_nav_props, "pages", text="Pages"
)
return {"FINISHED"}
#
def list_draw(self, t, pages, icon, label=None, emboss=False):
global tree_level, current_module
def reduced(too_long):
if too_long:
row = col.row()
row.prop(bpy.context.window_manager.api_nav_props, "reduce_to")
row.operator(
"api_navigator.fake_button", text="", emboss=False, icon="DOTSDOWN"
)
row.prop(
bpy.context.window_manager.api_nav_props, "pages", text="Pages"
)
layout = self.layout
filter = bpy.context.window_manager.api_nav_props.filter
reduce_to = bpy.context.window_manager.api_nav_props.reduce_to * self.columns
page_index = reduce_to * pages
len = tree_level[t].len()
too_long = len > reduce_to
if len:
col = layout.column()
box = col.box()
row = box.row()
row.label(text=label, icon=icon)
if t < 2:
box = box.box()
row = box.row()
col = row.column(align=True)
i = 0
objects = 0
count = 0
filtered = 0
while count < reduce_to and i < len:
obj = tree_level[t][i]
if filter and filter not in obj:
i += 1
continue
elif filtered < page_index:
filtered += 1
i += 1
continue
if not (objects % self.columns):
row = col.row()
if t > 1:
row.operator(
"api_navigator.down", text=obj, emboss=emboss
).pointed_module = obj
elif t == 0:
row.operator(
"api_navigator.subscript", text=str(obj), emboss=False
).subscription = ('"' + obj + '"')
else:
row.operator(
"api_navigator.subscript", text=str(obj), emboss=False
).subscription = str(i)
filtered += 1
i += 1
objects += 1
count += 1
reduced(too_long)
return {"FINISHED"}
#
def draw(self, context):
global tree_level, current_module, module_type, return_report
api_update(context)
###### layout ######
layout = self.layout
layout.label(text="Tree Structure:")
col = layout.column(align=True)
col.prop(bpy.context.window_manager.api_nav_props, "path", text="")
row = col.row()
row.operator("api_navigator.parent", text="Parent", icon="BACK")
row.operator(
"api_navigator.back_to_bpy", text="", emboss=True, icon="FILE_PARENT"
)
col = layout.column()
row = col.row(align=True)
row.prop(bpy.context.window_manager.api_nav_props, "filter")
row.operator("api_navigator.clear_filter", text="", icon="PANEL_CLOSE")
col = layout.column()
pages = bpy.context.window_manager.api_nav_props.pages
self.list_draw(0, pages, "DOTSDOWN", label="Items")
self.list_draw(1, pages, "DOTSDOWN", label="Item Values")
self.list_draw(2, pages, "PACKAGE", label="Modules", emboss=True)
self.list_draw(3, pages, "WORDWRAP_ON", label="Types", emboss=False)
self.list_draw(4, pages, "BUTS", label="Properties", emboss=False)
self.list_draw(5, pages, "OOPS", label="Structs and Functions")
self.list_draw(6, pages, "SCRIPTWIN", label="Methods and Functions")
self.list_draw(7, pages, "INFO", label="Attributes")
self.list_draw(8, pages, "ERROR", label="Inaccessible")

########### Menu functions ###############
class ApiNavProps(bpy.types.PropertyGroup):
"""
Fake module like class.
bpy.context.window_manager.api_nav_props
"""
path: StringProperty(
name="path",
description="Enter bpy.ops.api_navigator to see the documentation",
default="bpy",
)
old_path: StringProperty(name="old_path", default="")
filter: StringProperty(
name="filter", description="Filter the resulting modules", default=""
)
reduce_to: IntProperty(
name="Reduce to ",
description="Display a maximum number of x entries by pages",
default=10,
min=1,
)
pages: IntProperty(name="Pages", description="Display a Page", default=0, min=0)

def register_keymaps():
kc = bpy.context.window_manager.keyconfigs.addon
if kc:
km = kc.keymaps.new(name="Text", space_type="TEXT_EDITOR")
km.keymap_items.new("api_navigator.toggle_doc", "ESC", "PRESS")

def unregister_keymaps():
kc = bpy.context.window_manager.keyconfigs.addon
if kc:
km = kc.keymaps["Text"]
kmi = km.keymap_items["api_navigator.toggle_doc"]
km.keymap_items.remove(kmi)

classes = (
ApiNavProps,

ApiNavigator,

Update,
BackToBpy,
Down,
Parent,
ClearFilter,
FakeButton,
Subscript,
Toggle_doc,
OBJECT_PT_api_navigator,

)

def register():
from bpy.utils import register_class
for cls in classes:
register_class(cls)
bpy.types.WindowManager.api_nav_props = PointerProperty(
type=ApiNavProps, name="API Nav Props", description=""
)
register_keymaps()
print(get_tree_level())
#
#
def unregister():
from bpy.utils import unregister_class
unregister_keymaps()
for cls in reversed(classes):
unregister_class(cls)
#
del bpy.types.WindowManager.api_nav_props

if name == "main":
register()

@tin2tin
Copy link
Author

tin2tin commented Dec 13, 2020

I'm not the coder of this script. It's this guy: https://developer.blender.org/T24982 I only ran it through my updating script, and left it unfinished as a gist here(as stated in the very first line here). This morning I updated it to run without errors too at this time: https://gist.github.com/tin2tin/5546d7af099c36a3c47b054b28b38542#gistcomment-3559734 - but currently I do not have the time to dig any deeper in this. However some people might find it useful, so it would be meaningful to get it to a working state, since we're a couple of people, who have been trying to improve the Text Editor through add-ons and collect all that info here: https://blenderartists.org/t/essential-blender-text-editor-add-ons/1163857 So if you get this script working, please share it there or anything else you want to discuss or share related to coding in Blender.

You might upload that script you posted as a gist or on pasteall or somewhere the indentation doesn't get lost? Or try with triple ` around the code, and see it the formatting becomes correct?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment