Merging r38832 through r38897 from trunk into soc-2011-tomato
[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-80 compliant>
20
21 import bpy
22
23
24 class AddPresetBase():
25     '''Base preset class, only for subclassing
26     subclasses must define
27      - preset_values
28      - preset_subdir '''
29     # bl_idname = "script.preset_base_add"
30     # bl_label = "Add a Python Preset"
31     bl_options = {'REGISTER'}  # only because invoke_props_popup requires.
32
33     name = bpy.props.StringProperty(
34             name="Name",
35             description="Name of the preset, used to make the path name",
36             maxlen=64,
37             )
38     remove_active = bpy.props.BoolProperty(
39             default=False,
40             options={'HIDDEN'},
41             )
42
43     @staticmethod
44     def as_filename(name):  # could reuse for other presets
45         for char in " !@#$%^&*(){}:\";'[]<>,.\\/?":
46             name = name.replace(char, '_')
47         return name.lower().strip()
48
49     def execute(self, context):
50         import os
51
52         if hasattr(self, "pre_cb"):
53             self.pre_cb(context)
54
55         preset_menu_class = getattr(bpy.types, self.preset_menu)
56
57         if not self.remove_active:
58             name = self.name.strip()
59             if not name:
60                 return {'FINISHED'}
61
62             filename = self.as_filename(name)
63
64             target_path = os.path.join("presets", self.preset_subdir)
65             target_path = bpy.utils.user_resource('SCRIPTS',
66                                                   target_path,
67                                                   create=True)
68
69             if not target_path:
70                 self.report({'WARNING'}, "Failed to create presets path")
71                 return {'CANCELLED'}
72
73             filepath = os.path.join(target_path, filename) + ".py"
74
75             if hasattr(self, "add"):
76                 self.add(context, filepath)
77             else:
78                 file_preset = open(filepath, 'w')
79                 file_preset.write("import bpy\n")
80
81                 if hasattr(self, "preset_defines"):
82                     for rna_path in self.preset_defines:
83                         exec(rna_path)
84                         file_preset.write("%s\n" % rna_path)
85                     file_preset.write("\n")
86
87                 for rna_path in self.preset_values:
88                     value = eval(rna_path)
89                     # convert thin wrapped sequences to simple lists to repr()
90                     try:
91                         value = value[:]
92                     except:
93                         pass
94
95                     file_preset.write("%s = %r\n" % (rna_path, value))
96
97                 file_preset.close()
98
99             preset_menu_class.bl_label = bpy.path.display_name(filename)
100
101         else:
102             preset_active = preset_menu_class.bl_label
103
104             # fairly sloppy but convenient.
105             filepath = bpy.utils.preset_find(preset_active, self.preset_subdir)
106
107             if not filepath:
108                 filepath = bpy.utils.preset_find(preset_active,
109                                                  self.preset_subdir,
110                                                  display_name=True)
111
112             if not filepath:
113                 return {'CANCELLED'}
114
115             if hasattr(self, "remove"):
116                 self.remove(context, filepath)
117             else:
118                 try:
119                     os.remove(filepath)
120                 except:
121                     import traceback
122                     traceback.print_exc()
123
124             # XXX, stupid!
125             preset_menu_class.bl_label = "Presets"
126
127         if hasattr(self, "post_cb"):
128             self.post_cb(context)
129
130         return {'FINISHED'}
131
132     def check(self, context):
133         self.name = self.as_filename(self.name.strip())
134
135     def invoke(self, context, event):
136         if not self.remove_active:
137             wm = context.window_manager
138             return wm.invoke_props_dialog(self)
139         else:
140             return self.execute(context)
141
142
143 class ExecutePreset(bpy.types.Operator):
144     ''' Executes a preset '''
145     bl_idname = "script.execute_preset"
146     bl_label = "Execute a Python Preset"
147
148     filepath = bpy.props.StringProperty(
149             name="Path",
150             description="Path of the Python file to execute",
151             maxlen=512,
152             )
153     menu_idname = bpy.props.StringProperty(
154             name="Menu ID Name",
155             description="ID name of the menu this was called from",
156             )
157
158     def execute(self, context):
159         from os.path import basename
160         filepath = self.filepath
161
162         # change the menu title to the most recently chosen option
163         preset_class = getattr(bpy.types, self.menu_idname)
164         preset_class.bl_label = bpy.path.display_name(basename(filepath))
165
166         # execute the preset using script.python_file_run
167         bpy.ops.script.python_file_run(filepath=filepath)
168         return {'FINISHED'}
169
170
171 class AddPresetRender(AddPresetBase, bpy.types.Operator):
172     '''Add a Render Preset'''
173     bl_idname = "render.preset_add"
174     bl_label = "Add Render Preset"
175     preset_menu = "RENDER_MT_presets"
176
177     preset_defines = [
178         "scene = bpy.context.scene"
179     ]
180
181     preset_values = [
182         "scene.render.field_order",
183         "scene.render.fps",
184         "scene.render.fps_base",
185         "scene.render.pixel_aspect_x",
186         "scene.render.pixel_aspect_y",
187         "scene.render.resolution_percentage",
188         "scene.render.resolution_x",
189         "scene.render.resolution_y",
190         "scene.render.use_fields",
191         "scene.render.use_fields_still",
192     ]
193
194     preset_subdir = "render"
195
196
197 class AddPresetCamera(AddPresetBase, bpy.types.Operator):
198     '''Add a Camera Preset'''
199     bl_idname = "camera.preset_add"
200     bl_label = "Add Camera Preset"
201     preset_menu = "CAMERA_MT_presets"
202
203     preset_defines = [
204         "cam = bpy.context.object.data"
205     ]
206
207     preset_values = [
208         "cam.sensor_x",
209         "cam.sensor_y",
210     ]
211
212     preset_subdir = "camera"
213
214
215 class AddPresetSSS(AddPresetBase, bpy.types.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, bpy.types.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, bpy.types.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, bpy.types.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, bpy.types.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.sensor_height",
333         "camera.units",
334         "camera.focal_length",
335         "camera.k1",
336         "camera.k2",
337         "camera.k3"
338     ]
339
340     preset_subdir = "tracking_camera"
341
342
343 class AddPresetTrackingTrackColor(AddPresetBase, bpy.types.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.active_track"
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, bpy.types.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, bpy.types.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 = bpy.types.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(bpy.types.Menu):
430     bl_label = "Operator Presets"
431
432     def draw(self, context):
433         self.operator = context.space_data.operator.bl_idname
434         bpy.types.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"