940123e6645e9d9a4c5b74de77bdb3095bc4d8bf
[blender-staging.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-80 compliant>
20
21 import bpy
22 from bpy.types import Menu, Operator
23
24
25 class AddPresetBase():
26     '''Base preset class, only for subclassing
27     subclasses must define
28      - preset_values
29      - preset_subdir '''
30     # bl_idname = "script.preset_base_add"
31     # bl_label = "Add a Python Preset"
32     bl_options = {'REGISTER'}  # only because invoke_props_popup requires.
33
34     name = bpy.props.StringProperty(
35             name="Name",
36             description="Name of the preset, used to make the path name",
37             maxlen=64,
38             )
39     remove_active = bpy.props.BoolProperty(
40             default=False,
41             options={'HIDDEN'},
42             )
43
44     @staticmethod
45     def as_filename(name):  # could reuse for other presets
46         for char in " !@#$%^&*(){}:\";'[]<>,.\\/?":
47             name = name.replace(char, '_')
48         return name.lower().strip()
49
50     def execute(self, context):
51         import os
52
53         if hasattr(self, "pre_cb"):
54             self.pre_cb(context)
55
56         preset_menu_class = getattr(bpy.types, self.preset_menu)
57
58         if not self.remove_active:
59             name = self.name.strip()
60             if not name:
61                 return {'FINISHED'}
62
63             filename = self.as_filename(name)
64
65             target_path = os.path.join("presets", self.preset_subdir)
66             target_path = bpy.utils.user_resource('SCRIPTS',
67                                                   target_path,
68                                                   create=True)
69
70             if not target_path:
71                 self.report({'WARNING'}, "Failed to create presets path")
72                 return {'CANCELLED'}
73
74             filepath = os.path.join(target_path, filename) + ".py"
75
76             if hasattr(self, "add"):
77                 self.add(context, filepath)
78             else:
79                 file_preset = open(filepath, 'w')
80                 file_preset.write("import bpy\n")
81
82                 if hasattr(self, "preset_defines"):
83                     for rna_path in self.preset_defines:
84                         exec(rna_path)
85                         file_preset.write("%s\n" % rna_path)
86                     file_preset.write("\n")
87
88                 for rna_path in self.preset_values:
89                     value = eval(rna_path)
90                     # convert thin wrapped sequences to simple lists to repr()
91                     try:
92                         value = value[:]
93                     except:
94                         pass
95
96                     file_preset.write("%s = %r\n" % (rna_path, value))
97
98                 file_preset.close()
99
100             preset_menu_class.bl_label = bpy.path.display_name(filename)
101
102         else:
103             preset_active = preset_menu_class.bl_label
104
105             # fairly sloppy but convenient.
106             filepath = bpy.utils.preset_find(preset_active, self.preset_subdir)
107
108             if not filepath:
109                 filepath = bpy.utils.preset_find(preset_active,
110                                                  self.preset_subdir,
111                                                  display_name=True)
112
113             if not filepath:
114                 return {'CANCELLED'}
115
116             if hasattr(self, "remove"):
117                 self.remove(context, filepath)
118             else:
119                 try:
120                     os.remove(filepath)
121                 except:
122                     import traceback
123                     traceback.print_exc()
124
125             # XXX, stupid!
126             preset_menu_class.bl_label = "Presets"
127
128         if hasattr(self, "post_cb"):
129             self.post_cb(context)
130
131         return {'FINISHED'}
132
133     def check(self, context):
134         self.name = self.as_filename(self.name.strip())
135
136     def invoke(self, context, event):
137         if not self.remove_active:
138             wm = context.window_manager
139             return wm.invoke_props_dialog(self)
140         else:
141             return self.execute(context)
142
143
144 class ExecutePreset(Operator):
145     '''Execute a preset'''
146     bl_idname = "script.execute_preset"
147     bl_label = "Execute a Python Preset"
148
149     filepath = bpy.props.StringProperty(
150             name="Path",
151             description="Path of the Python file to execute",
152             maxlen=512,
153             )
154     menu_idname = bpy.props.StringProperty(
155             name="Menu ID Name",
156             description="ID name of the menu this was called from",
157             )
158
159     def execute(self, context):
160         from os.path import basename
161         filepath = self.filepath
162
163         # change the menu title to the most recently chosen option
164         preset_class = getattr(bpy.types, self.menu_idname)
165         preset_class.bl_label = bpy.path.display_name(basename(filepath))
166
167         # execute the preset using script.python_file_run
168         bpy.ops.script.python_file_run(filepath=filepath)
169         return {'FINISHED'}
170
171
172 class AddPresetRender(AddPresetBase, Operator):
173     '''Add a Render Preset'''
174     bl_idname = "render.preset_add"
175     bl_label = "Add Render Preset"
176     preset_menu = "RENDER_MT_presets"
177
178     preset_defines = [
179         "scene = bpy.context.scene"
180     ]
181
182     preset_values = [
183         "scene.render.field_order",
184         "scene.render.fps",
185         "scene.render.fps_base",
186         "scene.render.pixel_aspect_x",
187         "scene.render.pixel_aspect_y",
188         "scene.render.resolution_percentage",
189         "scene.render.resolution_x",
190         "scene.render.resolution_y",
191         "scene.render.use_fields",
192         "scene.render.use_fields_still",
193     ]
194
195     preset_subdir = "render"
196
197
198 class AddPresetCamera(AddPresetBase, Operator):
199     '''Add a Camera Preset'''
200     bl_idname = "camera.preset_add"
201     bl_label = "Add Camera Preset"
202     preset_menu = "CAMERA_MT_presets"
203
204     preset_defines = [
205         "cam = bpy.context.object.data"
206     ]
207
208     preset_values = [
209         "cam.sensor_width"
210     ]
211
212     preset_subdir = "camera"
213
214
215 class AddPresetSSS(AddPresetBase, Operator):
216     '''Add a Subsurface Scattering Preset'''
217     bl_idname = "material.sss_preset_add"
218     bl_label = "Add SSS Preset"
219     preset_menu = "MATERIAL_MT_sss_presets"
220
221     preset_defines = [
222         ("material = "
223          "bpy.context.material.active_node_material "
224          "if bpy.context.material.active_node_material "
225          "else bpy.context.material")
226     ]
227
228     preset_values = [
229         "material.subsurface_scattering.back",
230         "material.subsurface_scattering.color",
231         "material.subsurface_scattering.color_factor",
232         "material.subsurface_scattering.error_threshold",
233         "material.subsurface_scattering.front",
234         "material.subsurface_scattering.ior",
235         "material.subsurface_scattering.radius",
236         "material.subsurface_scattering.scale",
237         "material.subsurface_scattering.texture_factor",
238     ]
239
240     preset_subdir = "sss"
241
242
243 class AddPresetCloth(AddPresetBase, Operator):
244     '''Add a Cloth Preset'''
245     bl_idname = "cloth.preset_add"
246     bl_label = "Add Cloth Preset"
247     preset_menu = "CLOTH_MT_presets"
248
249     preset_defines = [
250         "cloth = bpy.context.cloth"
251     ]
252
253     preset_values = [
254         "cloth.settings.air_damping",
255         "cloth.settings.bending_stiffness",
256         "cloth.settings.mass",
257         "cloth.settings.quality",
258         "cloth.settings.spring_damping",
259         "cloth.settings.structural_stiffness",
260     ]
261
262     preset_subdir = "cloth"
263
264
265 class AddPresetSunSky(AddPresetBase, Operator):
266     '''Add a Sky & Atmosphere Preset'''
267     bl_idname = "lamp.sunsky_preset_add"
268     bl_label = "Add Sunsky Preset"
269     preset_menu = "LAMP_MT_sunsky_presets"
270
271     preset_defines = [
272         "sky = bpy.context.object.data.sky"
273     ]
274
275     preset_values = [
276         "sky.atmosphere_extinction",
277         "sky.atmosphere_inscattering",
278         "sky.atmosphere_turbidity",
279         "sky.backscattered_light",
280         "sky.horizon_brightness",
281         "sky.spread",
282         "sky.sun_brightness",
283         "sky.sun_intensity",
284         "sky.sun_size",
285         "sky.sky_blend",
286         "sky.sky_blend_type",
287         "sky.sky_color_space",
288         "sky.sky_exposure",
289     ]
290
291     preset_subdir = "sunsky"
292
293
294 class AddPresetInteraction(AddPresetBase, Operator):
295     '''Add an Application Interaction Preset'''
296     bl_idname = "wm.interaction_preset_add"
297     bl_label = "Add Interaction Preset"
298     preset_menu = "USERPREF_MT_interaction_presets"
299
300     preset_defines = [
301         "user_preferences = bpy.context.user_preferences"
302     ]
303
304     preset_values = [
305         "user_preferences.edit.use_drag_immediately",
306         "user_preferences.edit.use_insertkey_xyz_to_rgb",
307         "user_preferences.inputs.invert_mouse_zoom",
308         "user_preferences.inputs.select_mouse",
309         "user_preferences.inputs.use_emulate_numpad",
310         "user_preferences.inputs.use_mouse_continuous",
311         "user_preferences.inputs.use_mouse_emulate_3_button",
312         "user_preferences.inputs.view_rotate_method",
313         "user_preferences.inputs.view_zoom_axis",
314         "user_preferences.inputs.view_zoom_method",
315     ]
316
317     preset_subdir = "interaction"
318
319
320 class AddPresetTrackingCamera(AddPresetBase, Operator):
321     '''Add a Tracking Camera Intrinsics  Preset'''
322     bl_idname = "clip.camera_preset_add"
323     bl_label = "Add Camera Preset"
324     preset_menu = "CLIP_MT_camera_presets"
325
326     preset_defines = [
327         "camera = bpy.context.edit_movieclip.tracking.camera"
328     ]
329
330     preset_values = [
331         "camera.sensor_width",
332         "camera.units",
333         "camera.focal_length",
334         "camera.pixel_aspect",
335         "camera.k1",
336         "camera.k2",
337         "camera.k3"
338     ]
339
340     preset_subdir = "tracking_camera"
341
342
343 class AddPresetTrackingTrackColor(AddPresetBase, Operator):
344     '''Add a Clip Track Color Preset'''
345     bl_idname = "clip.track_color_preset_add"
346     bl_label = "Add Track Color Preset"
347     preset_menu = "CLIP_MT_track_color_presets"
348
349     preset_defines = [
350         "track = bpy.context.edit_movieclip.tracking.tracks"
351     ]
352
353     preset_values = [
354         "track.color",
355         "track.use_custom_color"
356     ]
357
358     preset_subdir = "tracking_track_color"
359
360
361 class AddPresetKeyconfig(AddPresetBase, Operator):
362     '''Add a Keyconfig Preset'''
363     bl_idname = "wm.keyconfig_preset_add"
364     bl_label = "Add Keyconfig Preset"
365     preset_menu = "USERPREF_MT_keyconfigs"
366     preset_subdir = "keyconfig"
367
368     def add(self, context, filepath):
369         bpy.ops.wm.keyconfig_export(filepath=filepath)
370         bpy.utils.keyconfig_set(filepath)
371
372     def pre_cb(self, context):
373         keyconfigs = bpy.context.window_manager.keyconfigs
374         if self.remove_active:
375             preset_menu_class = getattr(bpy.types, self.preset_menu)
376             preset_menu_class.bl_label = keyconfigs.active.name
377
378     def post_cb(self, context):
379         keyconfigs = bpy.context.window_manager.keyconfigs
380         if self.remove_active:
381             keyconfigs.remove(keyconfigs.active)
382
383
384 class AddPresetOperator(AddPresetBase, Operator):
385     '''Add an Application Interaction Preset'''
386     bl_idname = "wm.operator_preset_add"
387     bl_label = "Operator Preset"
388     preset_menu = "WM_MT_operator_presets"
389
390     operator = bpy.props.StringProperty(
391             name="Operator",
392             maxlen=64,
393             options={'HIDDEN'},
394             )
395
396     # XXX, not ideal
397     preset_defines = [
398         "op = bpy.context.space_data.operator",
399     ]
400
401     @property
402     def preset_subdir(self):
403         return AddPresetOperator.operator_path(self.operator)
404
405     @property
406     def preset_values(self):
407         properties_blacklist = Operator.bl_rna.properties.keys()
408
409         prefix, suffix = self.operator.split("_OT_", 1)
410         op = getattr(getattr(bpy.ops, prefix.lower()), suffix)
411         operator_rna = op.get_rna().bl_rna
412         del op
413
414         ret = []
415         for prop_id, prop in operator_rna.properties.items():
416             if not (prop.is_hidden or prop.is_skip_save):
417                 if prop_id not in properties_blacklist:
418                     ret.append("op.%s" % prop_id)
419
420         return ret
421
422     @staticmethod
423     def operator_path(operator):
424         import os
425         prefix, suffix = operator.split("_OT_", 1)
426         return os.path.join("operator", "%s.%s" % (prefix.lower(), suffix))
427
428
429 class WM_MT_operator_presets(Menu):
430     bl_label = "Operator Presets"
431
432     def draw(self, context):
433         self.operator = context.space_data.operator.bl_idname
434         Menu.draw_preset(self, context)
435
436     @property
437     def preset_subdir(self):
438         return AddPresetOperator.operator_path(self.operator)
439
440     preset_operator = "script.execute_preset"