viewing docs for nested classes would fail, expects bpy.types.Scene.SceneGameData...
[blender.git] / release / scripts / modules / bpy_ops.py
1 # for slightly faster access
2 from bpy.__ops__ import add             as op_add
3 from bpy.__ops__ import remove          as op_remove
4 from bpy.__ops__ import dir             as op_dir
5 from bpy.__ops__ import call            as op_call
6 from bpy.__ops__ import as_string       as op_as_string
7 from bpy.__ops__ import get_rna as op_get_rna
8
9 # Keep in sync with WM_types.h
10 context_dict = {
11         'INVOKE_DEFAULT':0,
12         'INVOKE_REGION_WIN':1,
13         'INVOKE_AREA':2,
14         'INVOKE_SCREEN':3,
15         'EXEC_DEFAULT':4,
16         'EXEC_REGION_WIN':5,
17         'EXEC_AREA':6,
18         'EXEC_SCREEN':7,
19 }
20
21 class bpy_ops(object):
22         '''
23         Fake module like class.
24
25          bpy.ops
26         '''
27
28         def __getattr__(self, module):
29                 '''
30                 gets a bpy.ops submodule
31                 '''
32                 if module.startswith('__'):
33                         raise AttributeError(module)
34                 return bpy_ops_submodule(module)
35                 
36         def add(self, pyop):
37                 op_add(pyop)
38         
39         def remove(self, pyop):
40                 op_remove(pyop)
41         
42         def __dir__(self):
43                 
44                 submodules = set()
45                 
46                 # add this classes functions
47                 for id_name in dir(self.__class__):
48                         if not id_name.startswith('__'):
49                                 submodules.add(id_name)
50                 
51                 for id_name in op_dir():
52                         id_split = id_name.split('_OT_', 1)
53                         
54                         if len(id_split) == 2:
55                                 submodules.add(id_split[0].lower())
56                         else:
57                                 submodules.add(id_split[0])
58                 
59                 return list(submodules)
60                 
61         def __repr__(self):
62                 return "<module like class 'bpy.ops'>"
63
64
65 class bpy_ops_submodule(object):
66         '''
67         Utility class to fake submodules.
68         
69         eg. bpy.ops.object
70         '''
71         __keys__ = ('module',)
72         
73         def __init__(self, module):
74                 self.module = module
75                 
76         def __getattr__(self, func):
77                 '''
78                 gets a bpy.ops.submodule function
79                 '''
80                 return bpy_ops_submodule_op(self.module, func)
81                 
82         def __dir__(self):
83                 
84                 functions = set()
85                 
86                 module_upper = self.module.upper()
87                 
88                 for id_name in op_dir():
89                         id_split = id_name.split('_OT_', 1)
90                         if len(id_split) == 2 and module_upper == id_split[0]:
91                                 functions.add(id_split[1])
92                 
93                 return list(functions)
94         
95         def __repr__(self):
96                 return "<module like class 'bpy.ops.%s'>" % self.module
97
98 class bpy_ops_submodule_op(object):
99         '''
100         Utility class to fake submodule operators.
101         
102         eg. bpy.ops.object.somefunc
103         '''
104         __keys__ = ('module', 'func')
105         def __init__(self, module, func):
106                 self.module = module
107                 self.func = func
108         
109         def idname(self):
110                 # submod.foo -> SUBMOD_OT_foo
111                 return self.module.upper() + '_OT_' + self.func
112         
113         def __call__(self, *args, **kw):
114                 
115                 # Get the operator from blender
116                 if len(args) > 1:
117                         raise ValueError("only one argument for the execution context is supported ")
118                 
119                 if args:
120                         try:
121                                 context = context_dict[args[0]]
122                         except:
123                                 raise ValueError("Expected a single context argument in: " + str(list(context_dict.keys())))
124                         
125                         return op_call(self.idname(), kw, context)
126                 
127                 else:
128                         return op_call(self.idname(), kw)
129         
130         def get_rna(self):
131                 '''
132                 currently only used for '__rna__'
133                 '''
134                 return op_get_rna(self.idname())
135                         
136         
137         def __repr__(self): # useful display, repr(op)
138                 return op_as_string(self.idname())
139         
140         def __str__(self): # used for print(...)
141                 return "<function bpy.ops.%s.%s at 0x%x'>" % (self.module, self.func, id(self))
142
143 import bpy
144 bpy.ops = bpy_ops()
145
146 # TODO, C macro's cant define settings :|
147
148 class MESH_OT_delete_edgeloop(bpy.types.Operator):
149         '''Export a single object as a stanford PLY with normals, colours and texture coordinates.'''
150         __idname__ = "mesh.delete_edgeloop"
151         __label__ = "Delete Edge Loop"
152         
153         def execute(self, context):
154                 bpy.ops.tfm.edge_slide(value=1.0)
155                 bpy.ops.mesh.select_more()
156                 bpy.ops.mesh.remove_doubles()
157                 return ('FINISHED',)
158
159 rna_path_prop = bpy.props.StringProperty(attr="path", name="Context Attributes", description="rna context string", maxlen= 1024, default= "")
160 rna_reverse_prop = bpy.props.BoolProperty(attr="reverse", name="Reverse", description="Cycle backwards", default= False)
161
162 class NullPathMember:
163         pass
164
165 def context_path_validate(context, path):
166         import sys
167         try:
168                 value = eval("context.%s" % path)
169         except AttributeError:
170                 if "'NoneType'" in str(sys.exc_info()[1]):
171                         # One of the items in the rna path is None, just ignore this
172                         value = NullPathMember
173                 else:
174                         # We have a real error in the rna path, dont ignore that
175                         raise
176         
177         return value
178                 
179         
180
181 def execute_context_assign(self, context):
182         if context_path_validate(context, self.path) == NullPathMember:
183                 return ('PASS_THROUGH',)
184         
185         exec("context.%s=self.value" % self.path)
186         return ('FINISHED',)
187
188 class WM_OT_context_set_boolean(bpy.types.Operator):
189         '''Set a context value.'''
190         __idname__ = "wm.context_set_boolean"
191         __label__ = "Context Set"
192         __props__ = [rna_path_prop, bpy.props.BoolProperty(attr="value", name="Value", description="Assignment value", default= True)]
193         execute = execute_context_assign
194
195 class WM_OT_context_set_int(bpy.types.Operator): # same as enum
196         '''Set a context value.'''
197         __idname__ = "wm.context_set_int"
198         __label__ = "Context Set"
199         __props__ = [rna_path_prop, bpy.props.IntProperty(attr="value", name="Value", description="Assignment value", default= 0)]
200         execute = execute_context_assign
201                 
202 class WM_OT_context_set_float(bpy.types.Operator): # same as enum
203         '''Set a context value.'''
204         __idname__ = "wm.context_set_int"
205         __label__ = "Context Set"
206         __props__ = [rna_path_prop, bpy.props.FloatProperty(attr="value", name="Value", description="Assignment value", default= 0.0)]
207         execute = execute_context_assign
208
209 class WM_OT_context_set_string(bpy.types.Operator): # same as enum
210         '''Set a context value.'''
211         __idname__ = "wm.context_set_string"
212         __label__ = "Context Set"
213         __props__ = [rna_path_prop, bpy.props.StringProperty(attr="value", name="Value", description="Assignment value", maxlen= 1024, default= "")]
214         execute = execute_context_assign
215
216 class WM_OT_context_set_enum(bpy.types.Operator):
217         '''Set a context value.'''
218         __idname__ = "wm.context_set_enum"
219         __label__ = "Context Set"
220         __props__ = [rna_path_prop, bpy.props.StringProperty(attr="value", name="Value", description="Assignment value (as a string)", maxlen= 1024, default= "")]
221         execute = execute_context_assign
222
223 class WM_OT_context_toggle(bpy.types.Operator):
224         '''Toggle a context value.'''
225         __idname__ = "wm.context_toggle"
226         __label__ = "Context Toggle"
227         __props__ = [rna_path_prop]
228         def execute(self, context):
229                 
230                 if context_path_validate(context, self.path) == NullPathMember:
231                         return ('PASS_THROUGH',)
232                 
233                 exec("context.%s=not (context.%s)" % (self.path, self.path)) # security nuts will complain.
234                 return ('FINISHED',)
235
236 class WM_OT_context_toggle_enum(bpy.types.Operator):
237         '''Toggle a context value.'''
238         __idname__ = "wm.context_toggle_enum"
239         __label__ = "Context Toggle Values"
240         __props__ = [
241                 rna_path_prop,
242                 bpy.props.StringProperty(attr="value_1", name="Value", description="Toggle enum", maxlen= 1024, default= ""),
243                 bpy.props.StringProperty(attr="value_2", name="Value", description="Toggle enum", maxlen= 1024, default= "")
244         ]
245         def execute(self, context):
246                 
247                 if context_path_validate(context, self.path) == NullPathMember:
248                         return ('PASS_THROUGH',)
249                 
250                 exec("context.%s = ['%s', '%s'][context.%s!='%s']" % (self.path, self.value_1, self.value_2, self.path, self.value_2)) # security nuts will complain.
251                 return ('FINISHED',)
252
253 class WM_OT_context_cycle_int(bpy.types.Operator):
254         '''Set a context value. Useful for cycling active material, vertex keys, groups' etc.'''
255         __idname__ = "wm.context_cycle_int"
256         __label__ = "Context Int Cycle"
257         __props__ = [rna_path_prop, rna_reverse_prop]
258         def execute(self, context):
259                 
260                 value = context_path_validate(context, self.path)
261                 if value == NullPathMember:
262                         return ('PASS_THROUGH',)
263                 
264                 self.value = value
265                 if self.reverse:        self.value -= 1
266                 else:           self.value += 1
267                 execute_context_assign(self, context)
268                 
269                 if self.value != eval("context.%s" % self.path):
270                         # relies on rna clamping int's out of the range
271                         if self.reverse:        self.value =  (1<<32)
272                         else:           self.value = -(1<<32)
273                         execute_context_assign(self, context)
274                         
275                 return ('FINISHED',)
276
277 class WM_OT_context_cycle_enum(bpy.types.Operator):
278         '''Toggle a context value.'''
279         __idname__ = "wm.context_cycle_enum"
280         __label__ = "Context Enum Cycle"
281         __props__ = [rna_path_prop, rna_reverse_prop]
282         def execute(self, context):
283                 
284                 value = context_path_validate(context, self.path)
285                 if value == NullPathMember:
286                         return ('PASS_THROUGH',)
287                 
288                 orig_value = value
289                 
290                 # Have to get rna enum values
291                 rna_struct_str, rna_prop_str =  self.path.rsplit('.', 1)
292                 i = rna_prop_str.find('[')
293                 if i != -1: rna_prop_str = rna_prop_str[0:i] # just incse we get "context.foo.bar[0]"
294                 
295                 rna_struct = eval("context.%s.rna_type" % rna_struct_str)
296                 
297                 rna_prop = rna_struct.properties[rna_prop_str]
298                 
299                 if type(rna_prop) != bpy.types.EnumProperty:
300                         raise Exception("expected an enum property")
301                 
302                 enums = rna_struct.properties[rna_prop_str].items.keys()
303                 orig_index = enums.index(orig_value)
304                 
305                 # Have the info we need, advance to the next item
306                 if self.reverse:
307                         if orig_index==0:                       advance_enum = enums[-1]
308                         else:                                   advance_enum = enums[orig_index-1]
309                 else:
310                         if orig_index==len(enums)-1:    advance_enum = enums[0]
311                         else:                                   advance_enum = enums[orig_index+1]
312                 
313                 # set the new value
314                 exec("context.%s=advance_enum" % self.path)
315                 return ('FINISHED',)
316
317 doc_id = bpy.props.StringProperty(attr="doc_id", name="Doc ID", description="ID for the documentation", maxlen= 1024, default= "")
318 doc_new = bpy.props.StringProperty(attr="doc_new", name="Doc New", description="", maxlen= 1024, default= "")
319
320
321 class WM_OT_doc_view(bpy.types.Operator):
322         '''Load online reference docs'''
323         __idname__ = "wm.doc_view"
324         __label__ = "View Documentation"
325         __props__ = [doc_id]
326         _prefix = 'http://www.blender.org/documentation/250PythonDoc'
327         
328         def _nested_class_string(self, class_string):
329                 ls = []
330                 class_obj = getattr(bpy.types, class_string, None).__rna__
331                 while class_obj:
332                         ls.insert(0, class_obj)
333                         class_obj = class_obj.nested
334                 return '.'.join([class_obj.identifier for class_obj in ls])
335         
336         def execute(self, context):
337                 id_split = self.doc_id.split('.')
338                 # Example url, http://www.graphicall.org/ftp/ideasman42/html/bpy.types.Space3DView-class.html#background_image
339                 # Example operator http://www.graphicall.org/ftp/ideasman42/html/bpy.ops.boid-module.html#boidrule_add
340                 if len(id_split) == 1: # rna, class
341                         url= '%s/bpy.types.%s-class.html' % (self._prefix, id_split[0])
342                 elif len(id_split) == 2: # rna, class.prop
343                         class_name, class_prop = id_split
344                         
345                         class_name_full = self._nested_class_string(class_name) # It so happens that epydoc nests these
346                         
347                         if hasattr(bpy.types, class_name.upper() + '_OT_' + class_prop):
348                                 url= '%s/bpy.ops.%s-module.html#%s' % (self._prefix, class_name_full, class_prop)
349                         else:
350                                 url= '%s/bpy.types.%s-class.html#%s' % (self._prefix, class_name_full, class_prop)
351                         
352                 else:
353                         return ('PASS_THROUGH',)
354                 
355                 import webbrowser
356                 webbrowser.open(url)
357                 
358                 return ('FINISHED',)
359
360
361 class WM_OT_doc_edit(bpy.types.Operator):
362         '''Load online reference docs'''
363         __idname__ = "wm.doc_edit"
364         __label__ = "Edit Documentation"
365         __props__ = [doc_id, doc_new]
366         
367         def execute(self, context):
368                 
369                 class_name, class_prop = self.doc_id.split('.')
370                 
371                 if self.doc_new:
372                         
373                         if hasattr(bpy.types, class_name.upper() + '_OT_' + class_prop):
374                                 # operator
375                                 print("operator - old:'%s' -> new:'%s'" % ('<TODO>', self.doc_new))
376                         else:
377                                 doc_orig = getattr(bpy.types, class_name).__rna__.properties[class_prop].description
378                                 if doc_orig != self.doc_new:
379                                         print("rna - old:'%s' -> new:'%s'" % (doc_orig, self.doc_new))
380                                         # aparently we can use xml/rpc to upload docs to an online review board
381                                         # Ugh, will run this on every edit.... better not make any mistakes
382                                 
383                 return ('FINISHED',)
384         
385         def invoke(self, context, event):
386                 wm = context.manager
387                 wm.invoke_props_popup(self.__operator__, event)
388                 return ('RUNNING_MODAL',)
389
390
391 bpy.ops.add(MESH_OT_delete_edgeloop)
392
393 bpy.ops.add(WM_OT_context_set_boolean)
394 bpy.ops.add(WM_OT_context_set_int)
395 bpy.ops.add(WM_OT_context_set_float)
396 bpy.ops.add(WM_OT_context_set_string)
397 bpy.ops.add(WM_OT_context_set_enum)
398 bpy.ops.add(WM_OT_context_toggle)
399 bpy.ops.add(WM_OT_context_toggle_enum)
400 bpy.ops.add(WM_OT_context_cycle_enum)
401 bpy.ops.add(WM_OT_context_cycle_int)
402
403 bpy.ops.add(WM_OT_doc_view)
404 bpy.ops.add(WM_OT_doc_edit)