Fix for [#32016] Tracking Settings Presets not working
[blender.git] / release / scripts / startup / bl_operators / presets.py
1 # ##### BEGIN GPL LICENSE BLOCK #####
2 #
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.
7 #
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.
12 #
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.
16 #
17 # ##### END GPL LICENSE BLOCK #####
18
19 # <pep8 compliant>
20
21 import bpy
22 from bpy.types import Menu, Operator
23 from bpy.props import StringProperty, BoolProperty
24
25
26 class AddPresetBase():
27     """Base preset class, only for subclassing
28     subclasses must define
29      - preset_values
30      - preset_subdir """
31     # bl_idname = "script.preset_base_add"
32     # bl_label = "Add a Python Preset"
33     bl_options = {'REGISTER'}  # only because invoke_props_popup requires.
34
35     name = StringProperty(
36             name="Name",
37             description="Name of the preset, used to make the path name",
38             maxlen=64,
39             options={'SKIP_SAVE'},
40             )
41     remove_active = BoolProperty(
42             default=False,
43             options={'HIDDEN', 'SKIP_SAVE'},
44             )
45
46     @staticmethod
47     def as_filename(name):  # could reuse for other presets
48         for char in " !@#$%^&*(){}:\";'[]<>,.\\/?":
49             name = name.replace(char, '_')
50         return name.lower().strip()
51
52     def execute(self, context):
53         import os
54
55         if hasattr(self, "pre_cb"):
56             self.pre_cb(context)
57
58         preset_menu_class = getattr(bpy.types, self.preset_menu)
59
60         is_xml = getattr(preset_menu_class, "preset_type", None) == 'XML'
61
62         if is_xml:
63             ext = ".xml"
64         else:
65             ext = ".py"
66
67         if not self.remove_active:
68             name = self.name.strip()
69             if not name:
70                 return {'FINISHED'}
71
72             filename = self.as_filename(name)
73
74             target_path = os.path.join("presets", self.preset_subdir)
75             target_path = bpy.utils.user_resource('SCRIPTS',
76                                                   target_path,
77                                                   create=True)
78
79             if not target_path:
80                 self.report({'WARNING'}, "Failed to create presets path")
81                 return {'CANCELLED'}
82
83             filepath = os.path.join(target_path, filename) + ext
84
85             if hasattr(self, "add"):
86                 self.add(context, filepath)
87             else:
88                 print("Writing Preset: %r" % filepath)
89
90                 if is_xml:
91                     import rna_xml
92                     rna_xml.xml_file_write(context,
93                                            filepath,
94                                            preset_menu_class.preset_xml_map)
95                 else:
96
97                     def rna_recursive_attr_expand(value, rna_path_step, level):
98                         if isinstance(value, bpy.types.PropertyGroup):
99                             for sub_value_attr in value.bl_rna.properties.keys():
100                                 if sub_value_attr == "rna_type":
101                                     continue
102                                 sub_value = getattr(value, sub_value_attr)
103                                 rna_recursive_attr_expand(sub_value, "%s.%s" % (rna_path_step, sub_value_attr), level)
104                         elif type(value).__name__ == "bpy_prop_collection_idprop":  # could use nicer method
105                             file_preset.write("%s.clear()\n" % rna_path_step)
106                             for sub_value in value:
107                                 file_preset.write("item_sub_%d = %s.add()\n" % (level, rna_path_step))
108                                 rna_recursive_attr_expand(sub_value, "item_sub_%d" % level, level + 1)
109                         else:
110                             # convert thin wrapped sequences
111                             # to simple lists to repr()
112                             try:
113                                 value = value[:]
114                             except:
115                                 pass
116
117                             file_preset.write("%s = %r\n" % (rna_path_step, value))
118
119                     file_preset = open(filepath, 'w')
120                     file_preset.write("import bpy\n")
121
122                     if hasattr(self, "preset_defines"):
123                         for rna_path in self.preset_defines:
124                             exec(rna_path)
125                             file_preset.write("%s\n" % rna_path)
126                         file_preset.write("\n")
127
128                     for rna_path in self.preset_values:
129                         value = eval(rna_path)
130                         rna_recursive_attr_expand(value, rna_path, 1)
131
132                     file_preset.close()
133
134             preset_menu_class.bl_label = bpy.path.display_name(filename)
135
136         else:
137             preset_active = preset_menu_class.bl_label
138
139             # fairly sloppy but convenient.
140             filepath = bpy.utils.preset_find(preset_active,
141                                              self.preset_subdir,
142                                              ext=ext)
143
144             if not filepath:
145                 filepath = bpy.utils.preset_find(preset_active,
146                                                  self.preset_subdir,
147                                                  display_name=True,
148                                                  ext=ext)
149
150             if not filepath:
151                 return {'CANCELLED'}
152
153             if hasattr(self, "remove"):
154                 self.remove(context, filepath)
155             else:
156                 try:
157                     os.remove(filepath)
158                 except:
159                     import traceback
160                     traceback.print_exc()
161
162             # XXX, stupid!
163             preset_menu_class.bl_label = "Presets"
164
165         if hasattr(self, "post_cb"):
166             self.post_cb(context)
167
168         return {'FINISHED'}
169
170     def check(self, context):
171         self.name = self.as_filename(self.name.strip())
172
173     def invoke(self, context, event):
174         if not self.remove_active:
175             wm = context.window_manager
176             return wm.invoke_props_dialog(self)
177         else:
178             return self.execute(context)
179
180
181 class ExecutePreset(Operator):
182     """Execute a preset"""
183     bl_idname = "script.execute_preset"
184     bl_label = "Execute a Python Preset"
185
186     filepath = StringProperty(
187             subtype='FILE_PATH',
188             )
189     menu_idname = StringProperty(
190             name="Menu ID Name",
191             description="ID name of the menu this was called from",
192             )
193
194     def execute(self, context):
195         from os.path import basename, splitext
196         filepath = self.filepath
197
198         # change the menu title to the most recently chosen option
199         preset_class = getattr(bpy.types, self.menu_idname)
200         preset_class.bl_label = bpy.path.display_name(basename(filepath))
201
202         ext = splitext(filepath)[1].lower()
203
204         # execute the preset using script.python_file_run
205         if ext == ".py":
206             bpy.ops.script.python_file_run(filepath=filepath)
207         elif ext == ".xml":
208             import rna_xml
209             rna_xml.xml_file_run(context,
210                                  filepath,
211                                  preset_class.preset_xml_map)
212         else:
213             self.report({'ERROR'}, "unknown filetype: %r" % ext)
214             return {'CANCELLED'}
215
216         return {'FINISHED'}
217
218
219 class AddPresetRender(AddPresetBase, Operator):
220     """Add a Render Preset"""
221     bl_idname = "render.preset_add"
222     bl_label = "Add Render Preset"
223     preset_menu = "RENDER_MT_presets"
224
225     preset_defines = [
226         "scene = bpy.context.scene"
227     ]
228
229     preset_values = [
230         "scene.render.field_order",
231         "scene.render.fps",
232         "scene.render.fps_base",
233         "scene.render.pixel_aspect_x",
234         "scene.render.pixel_aspect_y",
235         "scene.render.resolution_percentage",
236         "scene.render.resolution_x",
237         "scene.render.resolution_y",
238         "scene.render.use_fields",
239         "scene.render.use_fields_still",
240     ]
241
242     preset_subdir = "render"
243
244
245 class AddPresetCamera(AddPresetBase, Operator):
246     """Add a Camera Preset"""
247     bl_idname = "camera.preset_add"
248     bl_label = "Add Camera Preset"
249     preset_menu = "CAMERA_MT_presets"
250
251     preset_defines = [
252         "cam = bpy.context.object.data"
253     ]
254
255     preset_values = [
256         "cam.sensor_width",
257         "cam.sensor_height",
258         "cam.sensor_fit"
259     ]
260
261     preset_subdir = "camera"
262
263
264 class AddPresetSSS(AddPresetBase, Operator):
265     """Add a Subsurface Scattering Preset"""
266     bl_idname = "material.sss_preset_add"
267     bl_label = "Add SSS Preset"
268     preset_menu = "MATERIAL_MT_sss_presets"
269
270     preset_defines = [
271         ("material = "
272          "bpy.context.material.active_node_material "
273          "if bpy.context.material.active_node_material "
274          "else bpy.context.material")
275     ]
276
277     preset_values = [
278         "material.subsurface_scattering.back",
279         "material.subsurface_scattering.color",
280         "material.subsurface_scattering.color_factor",
281         "material.subsurface_scattering.error_threshold",
282         "material.subsurface_scattering.front",
283         "material.subsurface_scattering.ior",
284         "material.subsurface_scattering.radius",
285         "material.subsurface_scattering.scale",
286         "material.subsurface_scattering.texture_factor",
287     ]
288
289     preset_subdir = "sss"
290
291
292 class AddPresetCloth(AddPresetBase, Operator):
293     """Add a Cloth Preset"""
294     bl_idname = "cloth.preset_add"
295     bl_label = "Add Cloth Preset"
296     preset_menu = "CLOTH_MT_presets"
297
298     preset_defines = [
299         "cloth = bpy.context.cloth"
300     ]
301
302     preset_values = [
303         "cloth.settings.air_damping",
304         "cloth.settings.bending_stiffness",
305         "cloth.settings.mass",
306         "cloth.settings.quality",
307         "cloth.settings.spring_damping",
308         "cloth.settings.structural_stiffness",
309     ]
310
311     preset_subdir = "cloth"
312
313
314 class AddPresetFluid(AddPresetBase, Operator):
315     """Add a Fluid Preset"""
316     bl_idname = "fluid.preset_add"
317     bl_label = "Add Fluid Preset"
318     preset_menu = "FLUID_MT_presets"
319
320     preset_defines = [
321     "fluid = bpy.context.fluid"
322     ]
323
324     preset_values = [
325     "fluid.settings.viscosity_base",
326     "fluid.settings.viscosity_exponent",
327     ]
328
329     preset_subdir = "fluid"
330
331
332 class AddPresetSunSky(AddPresetBase, Operator):
333     """Add a Sky & Atmosphere Preset"""
334     bl_idname = "lamp.sunsky_preset_add"
335     bl_label = "Add Sunsky Preset"
336     preset_menu = "LAMP_MT_sunsky_presets"
337
338     preset_defines = [
339         "sky = bpy.context.object.data.sky"
340     ]
341
342     preset_values = [
343         "sky.atmosphere_extinction",
344         "sky.atmosphere_inscattering",
345         "sky.atmosphere_turbidity",
346         "sky.backscattered_light",
347         "sky.horizon_brightness",
348         "sky.spread",
349         "sky.sun_brightness",
350         "sky.sun_intensity",
351         "sky.sun_size",
352         "sky.sky_blend",
353         "sky.sky_blend_type",
354         "sky.sky_color_space",
355         "sky.sky_exposure",
356     ]
357
358     preset_subdir = "sunsky"
359
360
361 class AddPresetInteraction(AddPresetBase, Operator):
362     """Add an Application Interaction Preset"""
363     bl_idname = "wm.interaction_preset_add"
364     bl_label = "Add Interaction Preset"
365     preset_menu = "USERPREF_MT_interaction_presets"
366
367     preset_defines = [
368         "user_preferences = bpy.context.user_preferences"
369     ]
370
371     preset_values = [
372         "user_preferences.edit.use_drag_immediately",
373         "user_preferences.edit.use_insertkey_xyz_to_rgb",
374         "user_preferences.inputs.invert_mouse_zoom",
375         "user_preferences.inputs.select_mouse",
376         "user_preferences.inputs.use_emulate_numpad",
377         "user_preferences.inputs.use_mouse_continuous",
378         "user_preferences.inputs.use_mouse_emulate_3_button",
379         "user_preferences.inputs.view_rotate_method",
380         "user_preferences.inputs.view_zoom_axis",
381         "user_preferences.inputs.view_zoom_method",
382     ]
383
384     preset_subdir = "interaction"
385
386
387 class AddPresetTrackingCamera(AddPresetBase, Operator):
388     """Add a Tracking Camera Intrinsics  Preset"""
389     bl_idname = "clip.camera_preset_add"
390     bl_label = "Add Camera Preset"
391     preset_menu = "CLIP_MT_camera_presets"
392
393     preset_defines = [
394         "camera = bpy.context.edit_movieclip.tracking.camera"
395     ]
396
397     preset_values = [
398         "camera.sensor_width",
399         "camera.units",
400         "camera.focal_length",
401         "camera.pixel_aspect",
402         "camera.k1",
403         "camera.k2",
404         "camera.k3"
405     ]
406
407     preset_subdir = "tracking_camera"
408
409
410 class AddPresetTrackingTrackColor(AddPresetBase, Operator):
411     """Add a Clip Track Color Preset"""
412     bl_idname = "clip.track_color_preset_add"
413     bl_label = "Add Track Color Preset"
414     preset_menu = "CLIP_MT_track_color_presets"
415
416     preset_defines = [
417         "track = bpy.context.edit_movieclip.tracking.tracks.active"
418     ]
419
420     preset_values = [
421         "track.color",
422         "track.use_custom_color"
423     ]
424
425     preset_subdir = "tracking_track_color"
426
427
428 class AddPresetTrackingSettings(AddPresetBase, Operator):
429     """Add a motion tracking settings preset"""
430     bl_idname = "clip.tracking_settings_preset_add"
431     bl_label = "Add Tracking Settings Preset"
432     preset_menu = "CLIP_MT_tracking_settings_presets"
433
434     preset_defines = [
435         "settings = bpy.context.edit_movieclip.tracking.settings"
436     ]
437
438     preset_values = [
439         "settings.default_correlation_min",
440         "settings.default_pattern_size",
441         "settings.default_search_size",
442         "settings.default_frames_limit",
443         "settings.default_pattern_match",
444         "settings.default_margin",
445         "settings.use_default_red_channel",
446         "settings.use_default_green_channel",
447         "settings.use_default_blue_channel"
448     ]
449
450     preset_subdir = "tracking_settings"
451
452
453 class AddPresetNodeColor(AddPresetBase, Operator):
454     """Add a Node Color Preset"""
455     bl_idname = "node.node_color_preset_add"
456     bl_label = "Add Node Color Preset"
457     preset_menu = "NODE_MT_node_color_presets"
458
459     preset_defines = [
460         "node = bpy.context.active_node"
461     ]
462
463     preset_values = [
464         "node.color",
465         "node.use_custom_color"
466     ]
467
468     preset_subdir = "node_color"
469
470
471 class AddPresetInterfaceTheme(AddPresetBase, Operator):
472     """Add a theme preset"""
473     bl_idname = "wm.interface_theme_preset_add"
474     bl_label = "Add Tracking Settings Preset"
475     preset_menu = "USERPREF_MT_interface_theme_presets"
476     preset_subdir = "interface_theme"
477
478
479 class AddPresetKeyconfig(AddPresetBase, Operator):
480     """Add a Key-config Preset"""
481     bl_idname = "wm.keyconfig_preset_add"
482     bl_label = "Add Keyconfig Preset"
483     preset_menu = "USERPREF_MT_keyconfigs"
484     preset_subdir = "keyconfig"
485
486     def add(self, context, filepath):
487         bpy.ops.wm.keyconfig_export(filepath=filepath)
488         bpy.utils.keyconfig_set(filepath)
489
490     def pre_cb(self, context):
491         keyconfigs = bpy.context.window_manager.keyconfigs
492         if self.remove_active:
493             preset_menu_class = getattr(bpy.types, self.preset_menu)
494             preset_menu_class.bl_label = keyconfigs.active.name
495
496     def post_cb(self, context):
497         keyconfigs = bpy.context.window_manager.keyconfigs
498         if self.remove_active:
499             keyconfigs.remove(keyconfigs.active)
500
501
502 class AddPresetOperator(AddPresetBase, Operator):
503     """Add an Application Interaction Preset"""
504     bl_idname = "wm.operator_preset_add"
505     bl_label = "Operator Preset"
506     preset_menu = "WM_MT_operator_presets"
507
508     operator = StringProperty(
509             name="Operator",
510             maxlen=64,
511             options={'HIDDEN'},
512             )
513
514     preset_defines = [
515         "op = bpy.context.active_operator",
516     ]
517
518     @property
519     def preset_subdir(self):
520         return AddPresetOperator.operator_path(self.operator)
521
522     @property
523     def preset_values(self):
524         properties_blacklist = Operator.bl_rna.properties.keys()
525
526         prefix, suffix = self.operator.split("_OT_", 1)
527         op = getattr(getattr(bpy.ops, prefix.lower()), suffix)
528         operator_rna = op.get_rna().bl_rna
529         del op
530
531         ret = []
532         for prop_id, prop in operator_rna.properties.items():
533             if not (prop.is_hidden or prop.is_skip_save):
534                 if prop_id not in properties_blacklist:
535                     ret.append("op.%s" % prop_id)
536
537         return ret
538
539     @staticmethod
540     def operator_path(operator):
541         import os
542         prefix, suffix = operator.split("_OT_", 1)
543         return os.path.join("operator", "%s.%s" % (prefix.lower(), suffix))
544
545
546 class WM_MT_operator_presets(Menu):
547     bl_label = "Operator Presets"
548
549     def draw(self, context):
550         self.operator = context.active_operator.bl_idname
551         Menu.draw_preset(self, context)
552
553     @property
554     def preset_subdir(self):
555         return AddPresetOperator.operator_path(self.operator)
556
557     preset_operator = "script.execute_preset"