1 # ##### BEGIN GPL LICENSE BLOCK #####
3 # This program is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU General Public License
5 # as published by the Free Software Foundation; either version 2
6 # of the License, or (at your option) any later version.
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
13 # You should have received a copy of the GNU General Public License
14 # along with this program; if not, write to the Free Software Foundation,
15 # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 # ##### END GPL LICENSE BLOCK #####
22 from bpy.types import Menu, Operator
23 from bpy.props import (StringProperty,
30 from rna_prop_ui import rna_idprop_ui_prop_get, rna_idprop_ui_prop_clear
33 class MESH_OT_delete_edgeloop(Operator):
34 '''Delete an edge loop by merging the faces on each side to a single face loop'''
35 bl_idname = "mesh.delete_edgeloop"
36 bl_label = "Delete Edge Loop"
38 def execute(self, context):
39 if 'FINISHED' in bpy.ops.transform.edge_slide(value=1.0):
40 bpy.ops.mesh.select_more()
41 bpy.ops.mesh.remove_doubles()
46 rna_path_prop = StringProperty(
47 name="Context Attributes",
48 description="rna context string",
52 rna_reverse_prop = BoolProperty(
54 description="Cycle backwards",
58 rna_relative_prop = BoolProperty(
60 description="Apply relative to the current value (delta)",
65 def context_path_validate(context, data_path):
67 value = eval("context.%s" % data_path) if data_path else Ellipsis
68 except AttributeError as e:
69 if str(e).startswith("'NoneType'"):
70 # One of the items in the rna path is None, just ignore this
73 # We have a real error in the rna path, don't ignore that
79 def operator_value_is_undo(value):
80 if value in {None, Ellipsis}:
83 # typical properties or objects
84 id_data = getattr(value, "id_data", Ellipsis)
88 elif id_data is Ellipsis:
89 # handle mathutils types
90 id_data = getattr(getattr(value, "owner", None), "id_data", None)
95 # return True if its a non window ID type
96 return (isinstance(id_data, bpy.types.ID) and
97 (not isinstance(id_data, (bpy.types.WindowManager,
104 def operator_path_is_undo(context, data_path):
105 # note that if we have data paths that use strings this could fail
106 # luckily we don't do this!
108 # When we cant find the data owner assume no undo is needed.
109 data_path_head, data_path_sep, data_path_tail = data_path.rpartition(".")
111 if not data_path_head:
114 value = context_path_validate(context, data_path_head)
116 return operator_value_is_undo(value)
119 def operator_path_undo_return(context, data_path):
120 return {'FINISHED'} if operator_path_is_undo(context, data_path) else {'CANCELLED'}
123 def operator_value_undo_return(value):
124 return {'FINISHED'} if operator_value_is_undo(value) else {'CANCELLED'}
127 def execute_context_assign(self, context):
128 data_path = self.data_path
129 if context_path_validate(context, data_path) is Ellipsis:
130 return {'PASS_THROUGH'}
132 if getattr(self, "relative", False):
133 exec("context.%s += self.value" % data_path)
135 exec("context.%s = self.value" % data_path)
137 return operator_path_undo_return(context, data_path)
140 class BRUSH_OT_active_index_set(Operator):
141 '''Set active sculpt/paint brush from it's number'''
142 bl_idname = "brush.active_index_set"
143 bl_label = "Set Brush Number"
145 mode = StringProperty(
147 description="Paint mode to set brush for",
152 description="Brush number",
155 _attr_dict = {"sculpt": "use_paint_sculpt",
156 "vertex_paint": "use_paint_vertex",
157 "weight_paint": "use_paint_weight",
158 "image_paint": "use_paint_image",
161 def execute(self, context):
162 attr = self._attr_dict.get(self.mode)
166 for i, brush in enumerate((cur for cur in bpy.data.brushes if getattr(cur, attr))):
168 getattr(context.tool_settings, self.mode).brush = brush
174 class WM_OT_context_set_boolean(Operator):
175 '''Set a context value'''
176 bl_idname = "wm.context_set_boolean"
177 bl_label = "Context Set Boolean"
178 bl_options = {'UNDO', 'INTERNAL'}
180 data_path = rna_path_prop
181 value = BoolProperty(
183 description="Assignment value",
187 execute = execute_context_assign
190 class WM_OT_context_set_int(Operator): # same as enum
191 '''Set a context value'''
192 bl_idname = "wm.context_set_int"
193 bl_label = "Context Set"
194 bl_options = {'UNDO', 'INTERNAL'}
196 data_path = rna_path_prop
199 description="Assign value",
202 relative = rna_relative_prop
204 execute = execute_context_assign
207 class WM_OT_context_scale_int(Operator):
208 '''Scale an int context value'''
209 bl_idname = "wm.context_scale_int"
210 bl_label = "Context Set"
211 bl_options = {'UNDO', 'INTERNAL'}
213 data_path = rna_path_prop
214 value = FloatProperty(
216 description="Assign value",
219 always_step = BoolProperty(
221 description="Always adjust the value by a minimum of 1 when 'value' is not 1.0",
225 def execute(self, context):
226 data_path = self.data_path
227 if context_path_validate(context, data_path) is Ellipsis:
228 return {'PASS_THROUGH'}
232 if value == 1.0: # nothing to do
235 if getattr(self, "always_step", False):
242 exec("context.%s = %s(round(context.%s * value), context.%s + %s)" %
243 (data_path, func, data_path, data_path, add))
245 exec("context.%s *= value" % data_path)
247 return operator_path_undo_return(context, data_path)
250 class WM_OT_context_set_float(Operator): # same as enum
251 '''Set a context value'''
252 bl_idname = "wm.context_set_float"
253 bl_label = "Context Set Float"
254 bl_options = {'UNDO', 'INTERNAL'}
256 data_path = rna_path_prop
257 value = FloatProperty(
259 description="Assignment value",
262 relative = rna_relative_prop
264 execute = execute_context_assign
267 class WM_OT_context_set_string(Operator): # same as enum
268 '''Set a context value'''
269 bl_idname = "wm.context_set_string"
270 bl_label = "Context Set String"
271 bl_options = {'UNDO', 'INTERNAL'}
273 data_path = rna_path_prop
274 value = StringProperty(
276 description="Assign value",
280 execute = execute_context_assign
283 class WM_OT_context_set_enum(Operator):
284 '''Set a context value'''
285 bl_idname = "wm.context_set_enum"
286 bl_label = "Context Set Enum"
287 bl_options = {'UNDO', 'INTERNAL'}
289 data_path = rna_path_prop
290 value = StringProperty(
292 description="Assignment value (as a string)",
296 execute = execute_context_assign
299 class WM_OT_context_set_value(Operator):
300 '''Set a context value'''
301 bl_idname = "wm.context_set_value"
302 bl_label = "Context Set Value"
303 bl_options = {'UNDO', 'INTERNAL'}
305 data_path = rna_path_prop
306 value = StringProperty(
308 description="Assignment value (as a string)",
312 def execute(self, context):
313 data_path = self.data_path
314 if context_path_validate(context, data_path) is Ellipsis:
315 return {'PASS_THROUGH'}
316 exec("context.%s = %s" % (data_path, self.value))
317 return operator_path_undo_return(context, data_path)
320 class WM_OT_context_toggle(Operator):
321 '''Toggle a context value'''
322 bl_idname = "wm.context_toggle"
323 bl_label = "Context Toggle"
324 bl_options = {'UNDO', 'INTERNAL'}
326 data_path = rna_path_prop
328 def execute(self, context):
329 data_path = self.data_path
331 if context_path_validate(context, data_path) is Ellipsis:
332 return {'PASS_THROUGH'}
334 exec("context.%s = not (context.%s)" % (data_path, data_path))
336 return operator_path_undo_return(context, data_path)
339 class WM_OT_context_toggle_enum(Operator):
340 '''Toggle a context value'''
341 bl_idname = "wm.context_toggle_enum"
342 bl_label = "Context Toggle Values"
343 bl_options = {'UNDO', 'INTERNAL'}
345 data_path = rna_path_prop
346 value_1 = StringProperty(
348 description="Toggle enum",
351 value_2 = StringProperty(
353 description="Toggle enum",
357 def execute(self, context):
358 data_path = self.data_path
360 if context_path_validate(context, data_path) is Ellipsis:
361 return {'PASS_THROUGH'}
363 exec("context.%s = ('%s', '%s')[context.%s != '%s']" %
364 (data_path, self.value_1,
365 self.value_2, data_path,
369 return operator_path_undo_return(context, data_path)
372 class WM_OT_context_cycle_int(Operator):
373 '''Set a context value. Useful for cycling active material, '''
374 '''vertex keys, groups' etc'''
375 bl_idname = "wm.context_cycle_int"
376 bl_label = "Context Int Cycle"
377 bl_options = {'UNDO', 'INTERNAL'}
379 data_path = rna_path_prop
380 reverse = rna_reverse_prop
382 def execute(self, context):
383 data_path = self.data_path
384 value = context_path_validate(context, data_path)
385 if value is Ellipsis:
386 return {'PASS_THROUGH'}
393 exec("context.%s = value" % data_path)
395 if value != eval("context.%s" % data_path):
396 # relies on rna clamping int's out of the range
398 value = (1 << 31) - 1
402 exec("context.%s = value" % data_path)
404 return operator_path_undo_return(context, data_path)
407 class WM_OT_context_cycle_enum(Operator):
408 '''Toggle a context value'''
409 bl_idname = "wm.context_cycle_enum"
410 bl_label = "Context Enum Cycle"
411 bl_options = {'UNDO', 'INTERNAL'}
413 data_path = rna_path_prop
414 reverse = rna_reverse_prop
416 def execute(self, context):
417 data_path = self.data_path
418 value = context_path_validate(context, data_path)
419 if value is Ellipsis:
420 return {'PASS_THROUGH'}
424 # Have to get rna enum values
425 rna_struct_str, rna_prop_str = data_path.rsplit('.', 1)
426 i = rna_prop_str.find('[')
428 # just in case we get "context.foo.bar[0]"
430 rna_prop_str = rna_prop_str[0:i]
432 rna_struct = eval("context.%s.rna_type" % rna_struct_str)
434 rna_prop = rna_struct.properties[rna_prop_str]
436 if type(rna_prop) != bpy.types.EnumProperty:
437 raise Exception("expected an enum property")
439 enums = rna_struct.properties[rna_prop_str].enum_items.keys()
440 orig_index = enums.index(orig_value)
442 # Have the info we need, advance to the next item
445 advance_enum = enums[-1]
447 advance_enum = enums[orig_index - 1]
449 if orig_index == len(enums) - 1:
450 advance_enum = enums[0]
452 advance_enum = enums[orig_index + 1]
455 exec("context.%s = advance_enum" % data_path)
456 return operator_path_undo_return(context, data_path)
459 class WM_OT_context_cycle_array(Operator):
460 '''Set a context array value.
461 Useful for cycling the active mesh edit mode'''
462 bl_idname = "wm.context_cycle_array"
463 bl_label = "Context Array Cycle"
464 bl_options = {'UNDO', 'INTERNAL'}
466 data_path = rna_path_prop
467 reverse = rna_reverse_prop
469 def execute(self, context):
470 data_path = self.data_path
471 value = context_path_validate(context, data_path)
472 if value is Ellipsis:
473 return {'PASS_THROUGH'}
477 array.insert(0, array.pop())
479 array.append(array.pop(0))
482 exec("context.%s = cycle(context.%s[:])" % (data_path, data_path))
484 return operator_path_undo_return(context, data_path)
487 class WM_MT_context_menu_enum(Menu):
489 data_path = "" # BAD DESIGN, set from operator below.
491 def draw(self, context):
492 data_path = self.data_path
493 value = context_path_validate(bpy.context, data_path)
494 if value is Ellipsis:
495 return {'PASS_THROUGH'}
496 base_path, prop_string = data_path.rsplit(".", 1)
497 value_base = context_path_validate(context, base_path)
499 values = [(i.name, i.identifier) for i in value_base.bl_rna.properties[prop_string].enum_items]
501 for name, identifier in values:
502 prop = self.layout.operator("wm.context_set_enum", text=name)
503 prop.data_path = data_path
504 prop.value = identifier
507 class WM_OT_context_menu_enum(Operator):
508 bl_idname = "wm.context_menu_enum"
509 bl_label = "Context Enum Menu"
510 bl_options = {'UNDO', 'INTERNAL'}
511 data_path = rna_path_prop
513 def execute(self, context):
514 data_path = self.data_path
515 WM_MT_context_menu_enum.data_path = data_path
516 bpy.ops.wm.call_menu(name="WM_MT_context_menu_enum")
517 return {'PASS_THROUGH'}
520 class WM_OT_context_set_id(Operator):
521 '''Toggle a context value'''
522 bl_idname = "wm.context_set_id"
523 bl_label = "Set Library ID"
524 bl_options = {'UNDO', 'INTERNAL'}
526 data_path = rna_path_prop
527 value = StringProperty(
529 description="Assign value",
533 def execute(self, context):
535 data_path = self.data_path
537 # match the pointer type from the target property to bpy.data.*
538 # so we lookup the correct list.
539 data_path_base, data_path_prop = data_path.rsplit(".", 1)
540 data_prop_rna = eval("context.%s" % data_path_base).rna_type.properties[data_path_prop]
541 data_prop_rna_type = data_prop_rna.fixed_type
545 for prop in bpy.data.rna_type.properties:
546 if prop.rna_type.identifier == "CollectionProperty":
547 if prop.fixed_type == data_prop_rna_type:
548 id_iter = prop.identifier
552 value_id = getattr(bpy.data, id_iter).get(value)
553 exec("context.%s = value_id" % data_path)
555 return operator_path_undo_return(context, data_path)
558 doc_id = StringProperty(
564 doc_new = StringProperty(
565 name="Edit Description",
569 data_path_iter = StringProperty(
570 description="The data path relative to the context, must point to an iterable")
572 data_path_item = StringProperty(
573 description="The data path from each iterable to the value (int or float)")
576 class WM_OT_context_collection_boolean_set(Operator):
577 '''Set boolean values for a collection of items'''
578 bl_idname = "wm.context_collection_boolean_set"
579 bl_label = "Context Collection Boolean Set"
580 bl_options = {'UNDO', 'REGISTER', 'INTERNAL'}
582 data_path_iter = data_path_iter
583 data_path_item = data_path_item
587 items=(('TOGGLE', "Toggle", ""),
588 ('ENABLE', "Enable", ""),
589 ('DISABLE', "Disable", ""),
593 def execute(self, context):
594 data_path_iter = self.data_path_iter
595 data_path_item = self.data_path_item
597 items = list(getattr(context, data_path_iter))
602 value_orig = eval("item." + data_path_item)
606 if value_orig == True:
608 elif value_orig == False:
611 self.report({'WARNING'}, "Non boolean value found: %s[ ].%s" %
612 (data_path_iter, data_path_item))
615 items_ok.append(item)
617 # avoid undo push when nothing to do
621 if self.type == 'ENABLE':
623 elif self.type == 'DISABLE':
628 exec_str = "item.%s = %s" % (data_path_item, is_set)
629 for item in items_ok:
632 return operator_value_undo_return(item)
635 class WM_OT_context_modal_mouse(Operator):
636 '''Adjust arbitrary values with mouse input'''
637 bl_idname = "wm.context_modal_mouse"
638 bl_label = "Context Modal Mouse"
639 bl_options = {'GRAB_POINTER', 'BLOCKING', 'UNDO', 'INTERNAL'}
641 data_path_iter = data_path_iter
642 data_path_item = data_path_item
644 input_scale = FloatProperty(
645 description="Scale the mouse movement by this value before applying the delta",
648 invert = BoolProperty(
649 description="Invert the mouse input",
652 initial_x = IntProperty(options={'HIDDEN'})
654 def _values_store(self, context):
655 data_path_iter = self.data_path_iter
656 data_path_item = self.data_path_item
658 self._values = values = {}
660 for item in getattr(context, data_path_iter):
662 value_orig = eval("item." + data_path_item)
666 # check this can be set, maybe this is library data.
668 exec("item.%s = %s" % (data_path_item, value_orig))
672 values[item] = value_orig
674 def _values_delta(self, delta):
675 delta *= self.input_scale
679 data_path_item = self.data_path_item
680 for item, value_orig in self._values.items():
681 if type(value_orig) == int:
682 exec("item.%s = int(%d)" % (data_path_item, round(value_orig + delta)))
684 exec("item.%s = %f" % (data_path_item, value_orig + delta))
686 def _values_restore(self):
687 data_path_item = self.data_path_item
688 for item, value_orig in self._values.items():
689 exec("item.%s = %s" % (data_path_item, value_orig))
693 def _values_clear(self):
696 def modal(self, context, event):
697 event_type = event.type
699 if event_type == 'MOUSEMOVE':
700 delta = event.mouse_x - self.initial_x
701 self._values_delta(delta)
703 elif 'LEFTMOUSE' == event_type:
704 item = next(iter(self._values.keys()))
706 return operator_value_undo_return(item)
708 elif event_type in {'RIGHTMOUSE', 'ESC'}:
709 self._values_restore()
712 return {'RUNNING_MODAL'}
714 def invoke(self, context, event):
715 self._values_store(context)
718 self.report({'WARNING'}, "Nothing to operate on: %s[ ].%s" %
719 (self.data_path_iter, self.data_path_item))
723 self.initial_x = event.mouse_x
725 context.window_manager.modal_handler_add(self)
726 return {'RUNNING_MODAL'}
729 class WM_OT_url_open(Operator):
730 "Open a website in the Webbrowser"
731 bl_idname = "wm.url_open"
734 url = StringProperty(
736 description="URL to open",
739 def execute(self, context):
741 webbrowser.open(self.url)
745 class WM_OT_path_open(Operator):
746 "Open a path in a file browser"
747 bl_idname = "wm.path_open"
750 filepath = StringProperty(
756 def execute(self, context):
761 filepath = bpy.path.abspath(self.filepath)
762 filepath = os.path.normpath(filepath)
764 if not os.path.exists(filepath):
765 self.report({'ERROR'}, "File '%s' not found" % filepath)
768 if sys.platform[:3] == "win":
769 subprocess.Popen(['start', filepath], shell=True)
770 elif sys.platform == 'darwin':
771 subprocess.Popen(['open', filepath])
774 subprocess.Popen(['xdg-open', filepath])
776 # xdg-open *should* be supported by recent Gnome, KDE, Xfce
782 class WM_OT_doc_view(Operator):
783 '''Load online reference docs'''
784 bl_idname = "wm.doc_view"
785 bl_label = "View Documentation"
788 if bpy.app.version_cycle == "release":
789 _prefix = ("http://www.blender.org/documentation/blender_python_api_%s%s_release" %
790 ("_".join(str(v) for v in bpy.app.version[:2]), bpy.app.version_char))
792 _prefix = ("http://www.blender.org/documentation/blender_python_api_%s" %
793 "_".join(str(v) for v in bpy.app.version))
795 def _nested_class_string(self, class_string):
797 class_obj = getattr(bpy.types, class_string, None).bl_rna
799 ls.insert(0, class_obj)
800 class_obj = class_obj.nested
801 return '.'.join(class_obj.identifier for class_obj in ls)
803 def execute(self, context):
804 id_split = self.doc_id.split('.')
805 if len(id_split) == 1: # rna, class
806 url = '%s/bpy.types.%s.html' % (self._prefix, id_split[0])
807 elif len(id_split) == 2: # rna, class.prop
808 class_name, class_prop = id_split
810 if hasattr(bpy.types, class_name.upper() + '_OT_' + class_prop):
811 url = ("%s/bpy.ops.%s.html#bpy.ops.%s.%s" %
812 (self._prefix, class_name, class_name, class_prop))
815 # detect if this is a inherited member and use that name instead
816 rna_parent = getattr(bpy.types, class_name).bl_rna
817 rna_prop = rna_parent.properties[class_prop]
818 rna_parent = rna_parent.base
819 while rna_parent and rna_prop == rna_parent.properties.get(class_prop):
820 class_name = rna_parent.identifier
821 rna_parent = rna_parent.base
823 #~ class_name_full = self._nested_class_string(class_name)
824 url = ("%s/bpy.types.%s.html#bpy.types.%s.%s" %
825 (self._prefix, class_name, class_name, class_prop))
828 return {'PASS_THROUGH'}
836 class WM_OT_doc_edit(Operator):
837 '''Load online reference docs'''
838 bl_idname = "wm.doc_edit"
839 bl_label = "Edit Documentation"
844 _url = "http://www.mindrones.com/blender/svn/xmlrpc.php"
846 def _send_xmlrpc(self, data_dict):
847 print("sending data:", data_dict)
853 docblog = xmlrpc.client.ServerProxy(self._url)
854 docblog.metaWeblog.newPost(1, user, pwd, data_dict, 1)
856 def execute(self, context):
859 doc_new = self.doc_new
861 class_name, class_prop = doc_id.split('.')
864 self.report({'ERROR'}, "No input given for '%s'" % doc_id)
867 # check if this is an operator
868 op_name = class_name.upper() + '_OT_' + class_prop
869 op_class = getattr(bpy.types, op_name, None)
871 # Upload this to the web server
875 rna = op_class.bl_rna
876 doc_orig = rna.description
877 if doc_orig == doc_new:
878 return {'RUNNING_MODAL'}
880 print("op - old:'%s' -> new:'%s'" % (doc_orig, doc_new))
881 upload["title"] = 'OPERATOR %s:%s' % (doc_id, doc_orig)
883 rna = getattr(bpy.types, class_name).bl_rna
884 doc_orig = rna.properties[class_prop].description
885 if doc_orig == doc_new:
886 return {'RUNNING_MODAL'}
888 print("rna - old:'%s' -> new:'%s'" % (doc_orig, doc_new))
889 upload["title"] = 'RNA %s:%s' % (doc_id, doc_orig)
891 upload["description"] = doc_new
893 self._send_xmlrpc(upload)
897 def draw(self, context):
899 layout.label(text="Descriptor ID: '%s'" % self.doc_id)
900 layout.prop(self, "doc_new", text="")
902 def invoke(self, context, event):
903 wm = context.window_manager
904 return wm.invoke_props_dialog(self, width=600)
907 rna_path = StringProperty(
908 name="Property Edit",
909 description="Property data_path edit",
914 rna_value = StringProperty(
915 name="Property Value",
916 description="Property value edit",
920 rna_property = StringProperty(
921 name="Property Name",
922 description="Property name edit",
926 rna_min = FloatProperty(
932 rna_max = FloatProperty(
939 class WM_OT_properties_edit(Operator):
940 '''Internal use (edit a property data_path)'''
941 bl_idname = "wm.properties_edit"
942 bl_label = "Edit Property"
943 bl_options = {'REGISTER'} # only because invoke_props_popup requires.
946 property = rna_property
950 description = StringProperty(
954 def execute(self, context):
955 data_path = self.data_path
959 prop_old = getattr(self, "_last_prop", [None])[0]
962 self.report({'ERROR'}, "Direct execution not supported")
966 value_eval = eval(value)
971 item = eval("context.%s" % data_path)
973 rna_idprop_ui_prop_clear(item, prop_old)
974 exec_str = "del item['%s']" % prop_old
979 exec_str = "item['%s'] = %s" % (prop, repr(value_eval))
982 self._last_prop[:] = [prop]
984 prop_type = type(item[prop])
986 prop_ui = rna_idprop_ui_prop_get(item, prop)
988 if prop_type in {float, int}:
990 prop_ui['soft_min'] = prop_ui['min'] = prop_type(self.min)
991 prop_ui['soft_max'] = prop_ui['max'] = prop_type(self.max)
993 prop_ui['description'] = self.description
995 # otherwise existing buttons which reference freed
996 # memory may crash blender [#26510]
997 # context.area.tag_redraw()
998 for win in context.window_manager.windows:
999 for area in win.screen.areas:
1004 def invoke(self, context, event):
1005 data_path = self.data_path
1008 self.report({'ERROR'}, "Data path not set")
1009 return {'CANCELLED'}
1011 self._last_prop = [self.property]
1013 item = eval("context.%s" % data_path)
1016 prop_ui = rna_idprop_ui_prop_get(item, self.property, False) # don't create
1018 self.min = prop_ui.get("min", -1000000000)
1019 self.max = prop_ui.get("max", 1000000000)
1020 self.description = prop_ui.get("description", "")
1022 wm = context.window_manager
1023 return wm.invoke_props_dialog(self)
1026 class WM_OT_properties_add(Operator):
1027 '''Internal use (edit a property data_path)'''
1028 bl_idname = "wm.properties_add"
1029 bl_label = "Add Property"
1031 data_path = rna_path
1033 def execute(self, context):
1034 data_path = self.data_path
1035 item = eval("context.%s" % data_path)
1037 def unique_name(names):
1041 while prop_new in names:
1042 prop_new = prop + str(i)
1047 property = unique_name(item.keys())
1049 item[property] = 1.0
1053 class WM_OT_properties_context_change(Operator):
1054 "Change the context tab in a Properties Window"
1055 bl_idname = "wm.properties_context_change"
1058 context = StringProperty(
1063 def execute(self, context):
1064 context.space_data.context = self.context
1068 class WM_OT_properties_remove(Operator):
1069 '''Internal use (edit a property data_path)'''
1070 bl_idname = "wm.properties_remove"
1071 bl_label = "Remove Property"
1073 data_path = rna_path
1074 property = rna_property
1076 def execute(self, context):
1077 data_path = self.data_path
1078 item = eval("context.%s" % data_path)
1079 del item[self.property]
1083 class WM_OT_keyconfig_activate(Operator):
1084 bl_idname = "wm.keyconfig_activate"
1085 bl_label = "Activate Keyconfig"
1087 filepath = StringProperty(
1092 def execute(self, context):
1093 bpy.utils.keyconfig_set(self.filepath)
1097 class WM_OT_appconfig_default(Operator):
1098 bl_idname = "wm.appconfig_default"
1099 bl_label = "Default Application Configuration"
1101 def execute(self, context):
1104 context.window_manager.keyconfigs.active = context.window_manager.keyconfigs.default
1106 filepath = os.path.join(bpy.utils.preset_paths("interaction")[0], "blender.py")
1108 if os.path.exists(filepath):
1109 bpy.ops.script.execute_preset(filepath=filepath, menu_idname="USERPREF_MT_interaction_presets")
1114 class WM_OT_appconfig_activate(Operator):
1115 bl_idname = "wm.appconfig_activate"
1116 bl_label = "Activate Application Configuration"
1118 filepath = StringProperty(
1123 def execute(self, context):
1125 bpy.utils.keyconfig_set(self.filepath)
1127 filepath = self.filepath.replace("keyconfig", "interaction")
1129 if os.path.exists(filepath):
1130 bpy.ops.script.execute_preset(filepath=filepath, menu_idname="USERPREF_MT_interaction_presets")
1135 class WM_OT_sysinfo(Operator):
1136 '''Generate System Info'''
1137 bl_idname = "wm.sysinfo"
1138 bl_label = "System Info"
1140 def execute(self, context):
1142 sys_info.write_sysinfo(self)
1146 class WM_OT_copy_prev_settings(Operator):
1147 '''Copy settings from previous version'''
1148 bl_idname = "wm.copy_prev_settings"
1149 bl_label = "Copy Previous Settings"
1151 def execute(self, context):
1154 ver = bpy.app.version
1155 ver_old = ((ver[0] * 100) + ver[1]) - 1
1156 path_src = bpy.utils.resource_path('USER', ver_old // 100, ver_old % 100)
1157 path_dst = bpy.utils.resource_path('USER')
1159 if os.path.isdir(path_dst):
1160 self.report({'ERROR'}, "Target path %r exists" % path_dst)
1161 elif not os.path.isdir(path_src):
1162 self.report({'ERROR'}, "Source path %r exists" % path_src)
1164 shutil.copytree(path_src, path_dst, symlinks=True)
1166 # in 2.57 and earlier windows installers, system scripts were copied
1167 # into the configuration directory, don't want to copy those
1168 system_script = os.path.join(path_dst, 'scripts/modules/bpy_types.py')
1169 if os.path.isfile(system_script):
1170 shutil.rmtree(os.path.join(path_dst, 'scripts'))
1171 shutil.rmtree(os.path.join(path_dst, 'plugins'))
1173 # don't loose users work if they open the splash later.
1174 if bpy.data.is_saved is bpy.data.is_dirty is False:
1175 bpy.ops.wm.read_homefile()
1177 self.report({'INFO'}, "Reload Start-Up file to restore settings")
1180 return {'CANCELLED'}
1183 class WM_OT_keyconfig_test(Operator):
1184 "Test keyconfig for conflicts"
1185 bl_idname = "wm.keyconfig_test"
1186 bl_label = "Test Key Configuration for Conflicts"
1188 def execute(self, context):
1189 from bpy_extras import keyconfig_utils
1191 wm = context.window_manager
1192 kc = wm.keyconfigs.default
1194 if keyconfig_utils.keyconfig_test(kc):
1200 class WM_OT_keyconfig_import(Operator):
1201 "Import key configuration from a python script"
1202 bl_idname = "wm.keyconfig_import"
1203 bl_label = "Import Key Configuration..."
1205 filepath = StringProperty(
1207 description="Filepath to write file to",
1208 default="keymap.py",
1210 filter_folder = BoolProperty(
1211 name="Filter folders",
1215 filter_text = BoolProperty(
1220 filter_python = BoolProperty(
1221 name="Filter python",
1225 keep_original = BoolProperty(
1226 name="Keep original",
1227 description="Keep original file after copying to configuration folder",
1231 def execute(self, context):
1233 from os.path import basename
1236 if not self.filepath:
1237 self.report({'ERROR'}, "Filepath not set")
1238 return {'CANCELLED'}
1240 config_name = basename(self.filepath)
1242 path = bpy.utils.user_resource('SCRIPTS', os.path.join("presets", "keyconfig"), create=True)
1243 path = os.path.join(path, config_name)
1246 if self.keep_original:
1247 shutil.copy(self.filepath, path)
1249 shutil.move(self.filepath, path)
1250 except Exception as e:
1251 self.report({'ERROR'}, "Installing keymap failed: %s" % e)
1252 return {'CANCELLED'}
1254 # sneaky way to check we're actually running the code.
1255 bpy.utils.keyconfig_set(path)
1259 def invoke(self, context, event):
1260 wm = context.window_manager
1261 wm.fileselect_add(self)
1262 return {'RUNNING_MODAL'}
1264 # This operator is also used by interaction presets saving - AddPresetBase
1267 class WM_OT_keyconfig_export(Operator):
1268 "Export key configuration to a python script"
1269 bl_idname = "wm.keyconfig_export"
1270 bl_label = "Export Key Configuration..."
1272 filepath = StringProperty(
1274 description="Filepath to write file to",
1275 default="keymap.py",
1277 filter_folder = BoolProperty(
1278 name="Filter folders",
1282 filter_text = BoolProperty(
1287 filter_python = BoolProperty(
1288 name="Filter python",
1293 def execute(self, context):
1294 from bpy_extras import keyconfig_utils
1296 if not self.filepath:
1297 raise Exception("Filepath not set")
1299 if not self.filepath.endswith('.py'):
1300 self.filepath += '.py'
1302 wm = context.window_manager
1304 keyconfig_utils.keyconfig_export(wm,
1305 wm.keyconfigs.active,
1311 def invoke(self, context, event):
1312 wm = context.window_manager
1313 wm.fileselect_add(self)
1314 return {'RUNNING_MODAL'}
1317 class WM_OT_keymap_restore(Operator):
1318 "Restore key map(s)"
1319 bl_idname = "wm.keymap_restore"
1320 bl_label = "Restore Key Map(s)"
1324 description="Restore all keymaps to default",
1327 def execute(self, context):
1328 wm = context.window_manager
1331 for km in wm.keyconfigs.user.keymaps:
1332 km.restore_to_default()
1335 km.restore_to_default()
1340 class WM_OT_keyitem_restore(Operator):
1341 "Restore key map item"
1342 bl_idname = "wm.keyitem_restore"
1343 bl_label = "Restore Key Map Item"
1345 item_id = IntProperty(
1346 name="Item Identifier",
1347 description="Identifier of the item to remove",
1351 def poll(cls, context):
1352 keymap = getattr(context, "keymap", None)
1355 def execute(self, context):
1357 kmi = km.keymap_items.from_id(self.item_id)
1359 if (not kmi.is_user_defined) and kmi.is_user_modified:
1360 km.restore_item_to_default(kmi)
1365 class WM_OT_keyitem_add(Operator):
1367 bl_idname = "wm.keyitem_add"
1368 bl_label = "Add Key Map Item"
1370 def execute(self, context):
1374 km.keymap_items.new_modal("", 'A', 'PRESS')
1376 km.keymap_items.new("none", 'A', 'PRESS')
1378 # clear filter and expand keymap so we can see the newly added item
1379 if context.space_data.filter_text != "":
1380 context.space_data.filter_text = ""
1381 km.show_expanded_items = True
1382 km.show_expanded_children = True
1387 class WM_OT_keyitem_remove(Operator):
1388 "Remove key map item"
1389 bl_idname = "wm.keyitem_remove"
1390 bl_label = "Remove Key Map Item"
1392 item_id = IntProperty(
1393 name="Item Identifier",
1394 description="Identifier of the item to remove",
1398 def poll(cls, context):
1399 return hasattr(context, "keymap")
1401 def execute(self, context):
1403 kmi = km.keymap_items.from_id(self.item_id)
1404 km.keymap_items.remove(kmi)
1408 class WM_OT_keyconfig_remove(Operator):
1410 bl_idname = "wm.keyconfig_remove"
1411 bl_label = "Remove Key Config"
1414 def poll(cls, context):
1415 wm = context.window_manager
1416 keyconf = wm.keyconfigs.active
1417 return keyconf and keyconf.is_user_defined
1419 def execute(self, context):
1420 wm = context.window_manager
1421 keyconfig = wm.keyconfigs.active
1422 wm.keyconfigs.remove(keyconfig)
1426 class WM_OT_operator_cheat_sheet(Operator):
1427 bl_idname = "wm.operator_cheat_sheet"
1428 bl_label = "Operator Cheat Sheet"
1430 def execute(self, context):
1433 for op_module_name in dir(bpy.ops):
1434 op_module = getattr(bpy.ops, op_module_name)
1435 for op_submodule_name in dir(op_module):
1436 op = getattr(op_module, op_submodule_name)
1438 if text.split("\n")[-1].startswith('bpy.ops.'):
1439 op_strings.append(text)
1442 op_strings.append('')
1444 textblock = bpy.data.texts.new("OperatorList.txt")
1445 textblock.write('# %d Operators\n\n' % tot)
1446 textblock.write('\n'.join(op_strings))
1447 self.report({'INFO'}, "See OperatorList.txt textblock")
1451 class WM_OT_addon_enable(Operator):
1453 bl_idname = "wm.addon_enable"
1454 bl_label = "Enable Addon"
1456 module = StringProperty(
1458 description="Module name of the addon to enable",
1461 def execute(self, context):
1464 mod = addon_utils.enable(self.module)
1467 info = addon_utils.module_bl_info(mod)
1469 info_ver = info.get("blender", (0, 0, 0))
1471 if info_ver > bpy.app.version:
1472 self.report({'WARNING'}, ("This script was written Blender "
1473 "version %d.%d.%d and might not "
1474 "function (correctly), "
1475 "though it is enabled") %
1479 return {'CANCELLED'}
1482 class WM_OT_addon_disable(Operator):
1484 bl_idname = "wm.addon_disable"
1485 bl_label = "Disable Addon"
1487 module = StringProperty(
1489 description="Module name of the addon to disable",
1492 def execute(self, context):
1495 addon_utils.disable(self.module)
1499 class WM_OT_addon_install(Operator):
1501 bl_idname = "wm.addon_install"
1502 bl_label = "Install Addon..."
1504 overwrite = BoolProperty(
1506 description="Remove existing addons with the same ID",
1509 target = EnumProperty(
1511 items=(('DEFAULT', "Default", ""),
1512 ('PREFS', "User Prefs", "")),
1515 filepath = StringProperty(
1517 description="File path to write file to",
1519 filter_folder = BoolProperty(
1520 name="Filter folders",
1524 filter_python = BoolProperty(
1525 name="Filter python",
1529 filter_glob = StringProperty(
1530 default="*.py;*.zip",
1535 def _module_remove(path_addons, module):
1537 module = os.path.splitext(module)[0]
1538 for f in os.listdir(path_addons):
1539 f_base = os.path.splitext(f)[0]
1540 if f_base == module:
1541 f_full = os.path.join(path_addons, f)
1543 if os.path.isdir(f_full):
1548 def execute(self, context):
1555 pyfile = self.filepath
1557 if self.target == 'DEFAULT':
1558 # don't use bpy.utils.script_paths("addons") because we may not be able to write to it.
1559 path_addons = bpy.utils.user_resource('SCRIPTS', "addons", create=True)
1561 path_addons = bpy.context.user_preferences.filepaths.script_directory
1563 path_addons = os.path.join(path_addons, "addons")
1566 self.report({'ERROR'}, "Failed to get addons path")
1567 return {'CANCELLED'}
1569 # create dir is if missing.
1570 if not os.path.exists(path_addons):
1571 os.makedirs(path_addons)
1573 # Check if we are installing from a target path,
1574 # doing so causes 2+ addons of same name or when the same from/to
1575 # location is used, removal of the file!
1577 pyfile_dir = os.path.dirname(pyfile)
1578 for addon_path in addon_utils.paths():
1579 if os.path.samefile(pyfile_dir, addon_path):
1580 self.report({'ERROR'}, "Source file is in the addon search path: %r" % addon_path)
1581 return {'CANCELLED'}
1584 # done checking for exceptional case
1586 addons_old = {mod.__name__ for mod in addon_utils.modules(addon_utils.addons_fake_modules)}
1588 #check to see if the file is in compressed format (.zip)
1589 if zipfile.is_zipfile(pyfile):
1591 file_to_extract = zipfile.ZipFile(pyfile, 'r')
1593 traceback.print_exc()
1594 return {'CANCELLED'}
1597 for f in file_to_extract.namelist():
1598 WM_OT_addon_install._module_remove(path_addons, f)
1600 for f in file_to_extract.namelist():
1601 path_dest = os.path.join(path_addons, os.path.basename(f))
1602 if os.path.exists(path_dest):
1603 self.report({'WARNING'}, "File already installed to %r\n" % path_dest)
1604 return {'CANCELLED'}
1606 try: # extract the file to "addons"
1607 file_to_extract.extractall(path_addons)
1609 # zip files can create this dir with metadata, don't need it
1610 macosx_dir = os.path.join(path_addons, '__MACOSX')
1611 if os.path.isdir(macosx_dir):
1612 shutil.rmtree(macosx_dir)
1615 traceback.print_exc()
1616 return {'CANCELLED'}
1619 path_dest = os.path.join(path_addons, os.path.basename(pyfile))
1622 WM_OT_addon_install._module_remove(path_addons, os.path.basename(pyfile))
1623 elif os.path.exists(path_dest):
1624 self.report({'WARNING'}, "File already installed to %r\n" % path_dest)
1625 return {'CANCELLED'}
1627 #if not compressed file just copy into the addon path
1629 shutil.copyfile(pyfile, path_dest)
1632 traceback.print_exc()
1633 return {'CANCELLED'}
1635 addons_new = {mod.__name__ for mod in addon_utils.modules(addon_utils.addons_fake_modules)} - addons_old
1636 addons_new.discard("modules")
1638 # disable any addons we may have enabled previously and removed.
1639 # this is unlikely but do just in case. bug [#23978]
1640 for new_addon in addons_new:
1641 addon_utils.disable(new_addon)
1643 # possible the zip contains multiple addons, we could disallow this
1644 # but for now just use the first
1645 for mod in addon_utils.modules(addon_utils.addons_fake_modules):
1646 if mod.__name__ in addons_new:
1647 info = addon_utils.module_bl_info(mod)
1649 # show the newly installed addon.
1650 context.window_manager.addon_filter = 'All'
1651 context.window_manager.addon_search = info["name"]
1654 # in case a new module path was created to install this addon.
1655 bpy.utils.refresh_script_paths()
1657 # TODO, should not be a warning.
1658 #~ self.report({'WARNING'}, "File installed to '%s'\n" % path_dest)
1661 def invoke(self, context, event):
1662 wm = context.window_manager
1663 wm.fileselect_add(self)
1664 return {'RUNNING_MODAL'}
1667 class WM_OT_addon_remove(Operator):
1669 bl_idname = "wm.addon_remove"
1670 bl_label = "Remove Addon"
1672 module = StringProperty(
1674 description="Module name of the addon to remove",
1678 def path_from_addon(module):
1682 for mod in addon_utils.modules(addon_utils.addons_fake_modules):
1683 if mod.__name__ == module:
1684 filepath = mod.__file__
1685 if os.path.exists(filepath):
1686 if os.path.splitext(os.path.basename(filepath))[0] == "__init__":
1687 return os.path.dirname(filepath), True
1689 return filepath, False
1692 def execute(self, context):
1696 path, isdir = WM_OT_addon_remove.path_from_addon(self.module)
1698 self.report('WARNING', "Addon path %r could not be found" % path)
1699 return {'CANCELLED'}
1701 # in case its enabled
1702 addon_utils.disable(self.module)
1710 context.area.tag_redraw()
1713 # lame confirmation check
1714 def draw(self, context):
1715 self.layout.label(text="Remove Addon: %r?" % self.module)
1716 path, isdir = WM_OT_addon_remove.path_from_addon(self.module)
1717 self.layout.label(text="Path: %r" % path)
1719 def invoke(self, context, event):
1720 wm = context.window_manager
1721 return wm.invoke_props_dialog(self, width=600)
1724 class WM_OT_addon_expand(Operator):
1725 "Display more information on this addon"
1726 bl_idname = "wm.addon_expand"
1729 module = StringProperty(
1731 description="Module name of the addon to expand",
1734 def execute(self, context):
1737 module_name = self.module
1739 # unlikely to fail, module should have already been imported
1741 # mod = __import__(module_name)
1742 mod = addon_utils.addons_fake_modules.get(module_name)
1745 traceback.print_exc()
1746 return {'CANCELLED'}
1748 info = addon_utils.module_bl_info(mod)
1749 info["show_expanded"] = not info["show_expanded"]