Merged changes in the trunk up to revision 31403.
[blender.git] / release / scripts / ui / space_userpref.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 import bpy
21 import os
22 import shutil
23
24
25 def ui_items_general(col, context):
26     """ General UI Theme Settings (User Interface)
27     """
28
29     row = col.row()
30
31     subsplit = row.split(percentage=0.95)
32
33     padding = subsplit.split(percentage=0.15)
34     colsub = padding.column()
35     colsub = padding.column()
36     colsub.row().prop(context, "outline")
37     colsub.row().prop(context, "item", slider=True)
38     colsub.row().prop(context, "inner", slider=True)
39     colsub.row().prop(context, "inner_sel", slider=True)
40
41     subsplit = row.split(percentage=0.85)
42
43     padding = subsplit.split(percentage=0.15)
44     colsub = padding.column()
45     colsub = padding.column()
46     colsub.row().prop(context, "text")
47     colsub.row().prop(context, "text_sel")
48     colsub.prop(context, "shaded")
49     subsub = colsub.column(align=True)
50     subsub.active = context.shaded
51     subsub.prop(context, "shadetop")
52     subsub.prop(context, "shadedown")
53
54     col.separator()
55
56
57 def opengl_lamp_buttons(column, lamp):
58     split = column.split(percentage=0.1)
59
60     if lamp.enabled == True:
61         split.prop(lamp, "enabled", text="", icon='OUTLINER_OB_LAMP')
62     else:
63         split.prop(lamp, "enabled", text="", icon='LAMP_DATA')
64
65     col = split.column()
66     col.active = lamp.enabled
67     row = col.row()
68     row.label(text="Diffuse:")
69     row.prop(lamp, "diffuse_color", text="")
70     row = col.row()
71     row.label(text="Specular:")
72     row.prop(lamp, "specular_color", text="")
73
74     col = split.column()
75     col.active = lamp.enabled
76     col.prop(lamp, "direction", text="")
77
78
79 class USERPREF_HT_header(bpy.types.Header):
80     bl_space_type = 'USER_PREFERENCES'
81
82     def draw(self, context):
83         layout = self.layout
84         layout.template_header(menus=False)
85
86         userpref = context.user_preferences
87
88         layout.operator_context = 'EXEC_AREA'
89         layout.operator("wm.save_homefile", text="Save As Default")
90
91         layout.operator_context = 'INVOKE_DEFAULT'
92
93         if userpref.active_section == 'INPUT':
94             layout.operator("wm.keyconfig_export")
95             layout.operator("wm.keyconfig_import")
96         elif userpref.active_section == 'ADDONS':
97             layout.operator("wm.addon_install")
98         elif userpref.active_section == 'THEMES':
99             layout.operator("ui.reset_default_theme")
100
101
102 class USERPREF_PT_tabs(bpy.types.Panel):
103     bl_label = ""
104     bl_space_type = 'USER_PREFERENCES'
105     bl_region_type = 'WINDOW'
106     bl_show_header = False
107
108     def draw(self, context):
109         layout = self.layout
110
111         userpref = context.user_preferences
112
113         layout.prop(userpref, "active_section", expand=True)
114
115
116 class USERPREF_MT_interaction_presets(bpy.types.Menu):
117     bl_label = "Presets"
118     preset_subdir = "interaction"
119     preset_operator = "script.execute_preset"
120     draw = bpy.types.Menu.draw_preset
121
122
123 class USERPREF_MT_splash(bpy.types.Menu):
124     bl_label = "Splash"
125
126     def draw(self, context):
127         layout = self.layout
128         split = layout.split()
129         row = split.row()
130         row.label("")
131         row = split.row()
132         row.label("Interaction:")
133         row.menu("USERPREF_MT_interaction_presets", text=bpy.types.USERPREF_MT_interaction_presets.bl_label)
134
135
136 class USERPREF_PT_interface(bpy.types.Panel):
137     bl_space_type = 'USER_PREFERENCES'
138     bl_label = "Interface"
139     bl_region_type = 'WINDOW'
140     bl_show_header = False
141
142     @classmethod
143     def poll(cls, context):
144         userpref = context.user_preferences
145         return (userpref.active_section == 'INTERFACE')
146
147     def draw(self, context):
148         layout = self.layout
149
150         userpref = context.user_preferences
151         view = userpref.view
152
153         row = layout.row()
154
155         col = row.column()
156         col.label(text="Display:")
157         col.prop(view, "tooltips")
158         col.prop(view, "display_object_info", text="Object Info")
159         col.prop(view, "use_large_cursors")
160         col.prop(view, "show_view_name", text="View Name")
161         col.prop(view, "show_playback_fps", text="Playback FPS")
162         col.prop(view, "global_scene")
163         col.prop(view, "object_origin_size")
164
165         col.separator()
166         col.separator()
167         col.separator()
168
169         col.prop(view, "show_mini_axis", text="Display Mini Axis")
170         sub = col.column()
171         sub.active = view.show_mini_axis
172         sub.prop(view, "mini_axis_size", text="Size")
173         sub.prop(view, "mini_axis_brightness", text="Brightness")
174
175         col.separator()
176         row.separator()
177         row.separator()
178
179         col = row.column()
180         col.label(text="View Manipulation:")
181         col.prop(view, "auto_depth")
182         col.prop(view, "zoom_to_mouse")
183         col.prop(view, "rotate_around_selection")
184         col.prop(view, "global_pivot")
185
186         col.separator()
187
188         col.prop(view, "auto_perspective")
189         col.prop(view, "smooth_view")
190         col.prop(view, "rotation_angle")
191         
192         col.separator()
193         col.separator()
194         
195         col.label(text="2D Viewports:")
196         col.prop(view, "view2d_grid_minimum_spacing", text="Minimum Grid Spacing")
197         col.prop(view, "timecode_style")
198         
199         col.separator()
200         col.separator()
201
202         col.label(text="2D Viewports:")
203         col.prop(view, "view2d_grid_minimum_spacing", text="Minimum Grid Spacing")
204         col.prop(view, "timecode_style")
205
206         row.separator()
207         row.separator()
208
209         col = row.column()
210         #Toolbox doesn't exist yet
211         #col.label(text="Toolbox:")
212         #col.prop(view, "use_column_layout")
213         #col.label(text="Open Toolbox Delay:")
214         #col.prop(view, "open_left_mouse_delay", text="Hold LMB")
215         #col.prop(view, "open_right_mouse_delay", text="Hold RMB")
216         col.prop(view, "use_manipulator")
217         sub = col.column()
218         sub.active = view.use_manipulator
219         sub.prop(view, "manipulator_size", text="Size")
220         sub.prop(view, "manipulator_handle_size", text="Handle Size")
221         sub.prop(view, "manipulator_hotspot", text="Hotspot")
222
223         col.separator()
224         col.separator()
225         col.separator()
226
227         col.label(text="Menus:")
228         col.prop(view, "open_mouse_over")
229         col.label(text="Menu Open Delay:")
230         col.prop(view, "open_toplevel_delay", text="Top Level")
231         col.prop(view, "open_sublevel_delay", text="Sub Level")
232
233         col.separator()
234
235         col.prop(view, "show_splash")
236
237
238 class USERPREF_PT_edit(bpy.types.Panel):
239     bl_space_type = 'USER_PREFERENCES'
240     bl_label = "Edit"
241     bl_region_type = 'WINDOW'
242     bl_show_header = False
243
244     @classmethod
245     def poll(cls, context):
246         userpref = context.user_preferences
247         return (userpref.active_section == 'EDITING')
248
249     def draw(self, context):
250         layout = self.layout
251
252         userpref = context.user_preferences
253         edit = userpref.edit
254
255         row = layout.row()
256
257         col = row.column()
258         col.label(text="Link Materials To:")
259         col.prop(edit, "material_link", text="")
260
261         col.separator()
262         col.separator()
263         col.separator()
264
265         col.label(text="New Objects:")
266         col.prop(edit, "enter_edit_mode")
267         col.label(text="Align To:")
268         col.prop(edit, "object_align", text="")
269
270         col.separator()
271         col.separator()
272         col.separator()
273
274         col.label(text="Undo:")
275         col.prop(edit, "global_undo")
276         col.prop(edit, "undo_steps", text="Steps")
277         col.prop(edit, "undo_memory_limit", text="Memory Limit")
278
279         row.separator()
280         row.separator()
281
282         col = row.column()
283         col.label(text="Grease Pencil:")
284         col.prop(edit, "grease_pencil_manhattan_distance", text="Manhattan Distance")
285         col.prop(edit, "grease_pencil_euclidean_distance", text="Euclidean Distance")
286         #col.prop(edit, "grease_pencil_simplify_stroke", text="Simplify Stroke")
287         col.prop(edit, "grease_pencil_eraser_radius", text="Eraser Radius")
288         col.prop(edit, "grease_pencil_smooth_stroke", text="Smooth Stroke")
289         col.separator()
290         col.separator()
291         col.separator()
292         col.label(text="Playback:")
293         col.prop(edit, "use_negative_frames")
294
295         row.separator()
296         row.separator()
297
298         col = row.column()
299         col.label(text="Keyframing:")
300         col.prop(edit, "use_visual_keying")
301         col.prop(edit, "keyframe_insert_needed", text="Only Insert Needed")
302
303         col.separator()
304
305         col.prop(edit, "use_auto_keying", text="Auto Keyframing:")
306
307         sub = col.column()
308
309         # sub.active = edit.use_auto_keying # incorrect, timeline can enable
310         sub.prop(edit, "auto_keyframe_insert_keyingset", text="Only Insert for Keying Set")
311         sub.prop(edit, "auto_keyframe_insert_available", text="Only Insert Available")
312
313         col.separator()
314
315         col.label(text="New F-Curve Defaults:")
316         col.prop(edit, "keyframe_new_interpolation_type", text="Interpolation")
317         col.prop(edit, "keyframe_new_handle_type", text="Handles")
318         col.prop(edit, "insertkey_xyz_to_rgb", text="XYZ to RGB")
319
320         col.separator()
321         col.separator()
322         col.separator()
323
324         col.label(text="Transform:")
325         col.prop(edit, "drag_immediately")
326
327         row.separator()
328         row.separator()
329
330         col = row.column()
331         row = col.row(align=True)
332         row.prop(edit, "sculpt_paint_overlay_col", text="Sculpt Overlay Color")
333
334         col.separator()
335         col.separator()
336         col.separator()
337
338         col.label(text="Duplicate Data:")
339         col.prop(edit, "duplicate_mesh", text="Mesh")
340         col.prop(edit, "duplicate_surface", text="Surface")
341         col.prop(edit, "duplicate_curve", text="Curve")
342         col.prop(edit, "duplicate_text", text="Text")
343         col.prop(edit, "duplicate_metaball", text="Metaball")
344         col.prop(edit, "duplicate_armature", text="Armature")
345         col.prop(edit, "duplicate_lamp", text="Lamp")
346         col.prop(edit, "duplicate_material", text="Material")
347         col.prop(edit, "duplicate_texture", text="Texture")
348         #col.prop(edit, "duplicate_fcurve", text="F-Curve")
349         col.prop(edit, "duplicate_action", text="Action")
350         col.prop(edit, "duplicate_particle", text="Particle")
351
352
353 class USERPREF_PT_system(bpy.types.Panel):
354     bl_space_type = 'USER_PREFERENCES'
355     bl_label = "System"
356     bl_region_type = 'WINDOW'
357     bl_show_header = False
358
359     @classmethod
360     def poll(cls, context):
361         userpref = context.user_preferences
362         return (userpref.active_section == 'SYSTEM')
363
364     def draw(self, context):
365         layout = self.layout
366
367         userpref = context.user_preferences
368         system = userpref.system
369
370         split = layout.split()
371
372
373         # 1. Column
374         column = split.column()
375         colsplit = column.split(percentage=0.85)
376
377         col = colsplit.column()
378         col.label(text="General:")
379         col.prop(system, "dpi")
380         col.prop(system, "frame_server_port")
381         col.prop(system, "scrollback", text="Console Scrollback")
382         col.prop(system, "auto_execute_scripts")
383         col.prop(system, "tabs_as_spaces")
384
385         col.separator()
386         col.separator()
387         col.separator()
388
389         col.label(text="Sound:")
390         col.row().prop(system, "audio_device", expand=True)
391         sub = col.column()
392         sub.active = system.audio_device != 'NONE'
393         #sub.prop(system, "enable_all_codecs")
394         sub.prop(system, "audio_channels", text="Channels")
395         sub.prop(system, "audio_mixing_buffer", text="Mixing Buffer")
396         sub.prop(system, "audio_sample_rate", text="Sample Rate")
397         sub.prop(system, "audio_sample_format", text="Sample Format")
398
399         col.separator()
400         col.separator()
401         col.separator()
402
403         col.label(text="Screencast:")
404         col.prop(system, "screencast_fps")
405         col.prop(system, "screencast_wait_time")
406         col.separator()
407         col.separator()
408         col.separator()
409
410         #column = split.column()
411         #colsplit = column.split(percentage=0.85)
412
413         # No translation in 2.5 yet
414         #col.prop(system, "language")
415         #col.label(text="Translate:")
416         #col.prop(system, "translate_tooltips", text="Tooltips")
417         #col.prop(system, "translate_buttons", text="Labels")
418         #col.prop(system, "translate_toolbox", text="Toolbox")
419
420         #col.separator()
421
422         #col.prop(system, "use_textured_fonts")
423
424
425         # 2. Column
426         column = split.column()
427         colsplit = column.split(percentage=0.85)
428
429         col = colsplit.column()
430         col.label(text="OpenGL:")
431         col.prop(system, "clip_alpha", slider=True)
432         col.prop(system, "use_mipmaps")
433         col.prop(system, "use_vbos")
434         #Anti-aliasing is disabled as it breaks broder/lasso select
435         #col.prop(system, "use_antialiasing")
436         col.label(text="Window Draw Method:")
437         col.prop(system, "window_draw_method", text="")
438         col.label(text="Textures:")
439         col.prop(system, "gl_texture_limit", text="Limit Size")
440         col.prop(system, "texture_time_out", text="Time Out")
441         col.prop(system, "texture_collection_rate", text="Collection Rate")
442
443         col.separator()
444         col.separator()
445         col.separator()
446
447         col.label(text="Sequencer:")
448         col.prop(system, "prefetch_frames")
449         col.prop(system, "memory_cache_limit")
450
451
452         # 3. Column
453         column = split.column()
454
455         column.label(text="Solid OpenGL lights:")
456
457         split = column.split(percentage=0.1)
458         split.label()
459         split.label(text="Colors:")
460         split.label(text="Direction:")
461
462         lamp = system.solid_lights[0]
463         opengl_lamp_buttons(column, lamp)
464
465         lamp = system.solid_lights[1]
466         opengl_lamp_buttons(column, lamp)
467
468         lamp = system.solid_lights[2]
469         opengl_lamp_buttons(column, lamp)
470
471         column.separator()
472         column.separator()
473         column.separator()
474
475         column.label(text="Color Picker Type:")
476         column.row().prop(system, "color_picker_type", text="")
477
478         column.separator()
479         column.separator()
480         column.separator()
481
482         column.prop(system, "use_weight_color_range", text="Custom Weight Paint Range")
483         sub = column.column()
484         sub.active = system.use_weight_color_range
485         sub.template_color_ramp(system, "weight_color_range", expand=True)
486
487
488 class USERPREF_PT_theme(bpy.types.Panel):
489     bl_space_type = 'USER_PREFERENCES'
490     bl_label = "Themes"
491     bl_region_type = 'WINDOW'
492     bl_show_header = False
493
494     @staticmethod
495     def _theme_generic(split, themedata):
496
497         row = split.row()
498
499         subsplit = row.split(percentage=0.95)
500
501         padding1 = subsplit.split(percentage=0.15)
502         padding1.column()
503
504         subsplit = row.split(percentage=0.85)
505
506         padding2 = subsplit.split(percentage=0.15)
507         padding2.column()
508
509         colsub_pair = padding1.column(), padding2.column()
510
511         props_type = {}
512
513         for i, prop in enumerate(themedata.rna_type.properties):
514             attr = prop.identifier
515             if attr == "rna_type":
516                 continue
517
518             props_type.setdefault((prop.type, prop.subtype), []).append(prop.identifier)
519
520         for props_type, props_ls in sorted(props_type.items()):
521             for i, attr in enumerate(props_ls):
522                 colsub_pair[i % 2].row().prop(themedata, attr)
523
524     @classmethod
525     def poll(cls, context):
526         userpref = context.user_preferences
527         return (userpref.active_section == 'THEMES')
528
529     def draw(self, context):
530         layout = self.layout
531
532         theme = context.user_preferences.themes[0]
533
534         split_themes = layout.split(percentage=0.2)
535         split_themes.prop(theme, "theme_area", expand=True)
536
537         split = layout.split(percentage=0.4)
538
539
540         layout.separator()
541         layout.separator()
542
543         split = split_themes.split()
544
545         if theme.theme_area == 'USER_INTERFACE':
546             col = split.column()
547
548             ui = theme.user_interface.wcol_regular
549             col.label(text="Regular:")
550             ui_items_general(col, ui)
551
552             ui = theme.user_interface.wcol_tool
553             col.label(text="Tool:")
554             ui_items_general(col, ui)
555
556             ui = theme.user_interface.wcol_radio
557             col.label(text="Radio Buttons:")
558             ui_items_general(col, ui)
559
560             ui = theme.user_interface.wcol_text
561             col.label(text="Text:")
562             ui_items_general(col, ui)
563
564             ui = theme.user_interface.wcol_option
565             col.label(text="Option:")
566             ui_items_general(col, ui)
567
568             ui = theme.user_interface.wcol_toggle
569             col.label(text="Toggle:")
570             ui_items_general(col, ui)
571
572             ui = theme.user_interface.wcol_num
573             col.label(text="Number Field:")
574             ui_items_general(col, ui)
575
576             ui = theme.user_interface.wcol_numslider
577             col.label(text="Value Slider:")
578             ui_items_general(col, ui)
579
580             ui = theme.user_interface.wcol_box
581             col.label(text="Box:")
582             ui_items_general(col, ui)
583
584             ui = theme.user_interface.wcol_menu
585             col.label(text="Menu:")
586             ui_items_general(col, ui)
587
588             ui = theme.user_interface.wcol_pulldown
589             col.label(text="Pulldown:")
590             ui_items_general(col, ui)
591
592             ui = theme.user_interface.wcol_menu_back
593             col.label(text="Menu Back:")
594             ui_items_general(col, ui)
595
596             ui = theme.user_interface.wcol_menu_item
597             col.label(text="Menu Item:")
598             ui_items_general(col, ui)
599
600             ui = theme.user_interface.wcol_scroll
601             col.label(text="Scroll Bar:")
602             ui_items_general(col, ui)
603
604             ui = theme.user_interface.wcol_progress
605             col.label(text="Progress Bar:")
606             ui_items_general(col, ui)
607
608             ui = theme.user_interface.wcol_list_item
609             col.label(text="List Item:")
610             ui_items_general(col, ui)
611
612             ui = theme.user_interface.wcol_state
613             col.label(text="State:")
614
615             row = col.row()
616
617             subsplit = row.split(percentage=0.95)
618
619             padding = subsplit.split(percentage=0.15)
620             colsub = padding.column()
621             colsub = padding.column()
622             colsub.row().prop(ui, "inner_anim")
623             colsub.row().prop(ui, "inner_anim_sel")
624             colsub.row().prop(ui, "inner_driven")
625             colsub.row().prop(ui, "inner_driven_sel")
626
627             subsplit = row.split(percentage=0.85)
628
629             padding = subsplit.split(percentage=0.15)
630             colsub = padding.column()
631             colsub = padding.column()
632             colsub.row().prop(ui, "inner_key")
633             colsub.row().prop(ui, "inner_key_sel")
634             colsub.row().prop(ui, "blend")
635
636
637             ui = theme.user_interface
638             col.separator()
639             col.separator()
640
641             split = col.split(percentage=0.93)
642             split.prop(ui, "icon_file")
643
644             layout.separator()
645             layout.separator()
646
647         else:
648             self._theme_generic(split, getattr(theme, theme.theme_area.lower()))
649
650
651 class USERPREF_PT_file(bpy.types.Panel):
652     bl_space_type = 'USER_PREFERENCES'
653     bl_label = "Files"
654     bl_region_type = 'WINDOW'
655     bl_show_header = False
656
657     @classmethod
658     def poll(cls, context):
659         userpref = context.user_preferences
660         return (userpref.active_section == 'FILES')
661
662     def draw(self, context):
663         layout = self.layout
664
665         userpref = context.user_preferences
666         paths = userpref.filepaths
667
668         split = layout.split(percentage=0.7)
669
670         col = split.column()
671         col.label(text="File Paths:")
672
673         colsplit = col.split(percentage=0.95)
674         col1 = colsplit.split(percentage=0.3)
675
676         sub = col1.column()
677         sub.label(text="Fonts:")
678         sub.label(text="Textures:")
679         sub.label(text="Texture Plugins:")
680         sub.label(text="Sequence Plugins:")
681         sub.label(text="Render Output:")
682         sub.label(text="Scripts:")
683         sub.label(text="Sounds:")
684         sub.label(text="Temp:")
685         sub.label(text="Image Editor:")
686         sub.label(text="Animation Player:")
687
688         sub = col1.column()
689         sub.prop(paths, "fonts_directory", text="")
690         sub.prop(paths, "textures_directory", text="")
691         sub.prop(paths, "texture_plugin_directory", text="")
692         sub.prop(paths, "sequence_plugin_directory", text="")
693         sub.prop(paths, "render_output_directory", text="")
694         sub.prop(paths, "python_scripts_directory", text="")
695         sub.prop(paths, "sounds_directory", text="")
696         sub.prop(paths, "temporary_directory", text="")
697         sub.prop(paths, "image_editor", text="")
698         subsplit = sub.split(percentage=0.3)
699         subsplit.prop(paths, "animation_player_preset", text="")
700         subsplit.prop(paths, "animation_player", text="")
701
702         col = split.column()
703         col.label(text="Save & Load:")
704         col.prop(paths, "use_relative_paths")
705         col.prop(paths, "compress_file")
706         col.prop(paths, "load_ui")
707         col.prop(paths, "filter_file_extensions")
708         col.prop(paths, "hide_dot_files_datablocks")
709
710         col.separator()
711         col.separator()
712
713         col.label(text="Auto Save:")
714         col.prop(paths, "save_version")
715         col.prop(paths, "recent_files")
716         col.prop(paths, "save_preview_images")
717         col.prop(paths, "auto_save_temporary_files")
718         sub = col.column()
719         sub.active = paths.auto_save_temporary_files
720         sub.prop(paths, "auto_save_time", text="Timer (mins)")
721
722 from space_userpref_keymap import InputKeyMapPanel
723
724
725 class USERPREF_PT_input(InputKeyMapPanel):
726     bl_space_type = 'USER_PREFERENCES'
727     bl_label = "Input"
728
729     @classmethod
730     def poll(cls, context):
731         userpref = context.user_preferences
732         return (userpref.active_section == 'INPUT')
733
734     def draw_input_prefs(self, inputs, layout):
735         # General settings
736         row = layout.row()
737         col = row.column()
738
739         sub = col.column()
740         sub.label(text="Presets:")
741         subrow = sub.row(align=True)
742         subrow.menu("USERPREF_MT_interaction_presets", text=bpy.types.USERPREF_MT_interaction_presets.bl_label)
743         subrow.operator("wm.interaction_preset_add", text="", icon='ZOOMIN')
744         sub.separator()
745
746         sub.label(text="Mouse:")
747         sub1 = sub.column()
748         sub1.active = (inputs.select_mouse == 'RIGHT')
749         sub1.prop(inputs, "emulate_3_button_mouse")
750         sub.prop(inputs, "continuous_mouse")
751
752         sub.label(text="Select With:")
753         sub.row().prop(inputs, "select_mouse", expand=True)
754
755         sub = col.column()
756         sub.label(text="Double Click:")
757         sub.prop(inputs, "double_click_time", text="Speed")
758
759         sub.separator()
760
761         sub.prop(inputs, "emulate_numpad")
762
763         sub.separator()
764
765         sub.label(text="Orbit Style:")
766         sub.row().prop(inputs, "view_rotation", expand=True)
767
768         sub.label(text="Zoom Style:")
769         sub.row().prop(inputs, "zoom_style", text="")
770         if inputs.zoom_style == 'DOLLY':
771             sub.row().prop(inputs, "zoom_axis", expand=True)
772             sub.prop(inputs, "invert_zoom_direction")
773
774         #sub.prop(inputs, "use_middle_mouse_paste")
775
776         #col.separator()
777
778         sub = col.column()
779         sub.label(text="Mouse Wheel:")
780         sub.prop(inputs, "wheel_invert_zoom", text="Invert Wheel Zoom Direction")
781         #sub.prop(view, "wheel_scroll_lines", text="Scroll Lines")
782
783         col.separator()
784         ''' not implemented yet
785         sub = col.column()
786         sub.label(text="NDOF Device:")
787         sub.prop(inputs, "ndof_pan_speed", text="Pan Speed")
788         sub.prop(inputs, "ndof_rotate_speed", text="Orbit Speed")
789         '''
790
791         row.separator()
792
793     def draw(self, context):
794         layout = self.layout
795
796         #import time
797
798         #start = time.time()
799
800         userpref = context.user_preferences
801         wm = context.manager
802
803         inputs = userpref.inputs
804
805         split = layout.split(percentage=0.25)
806
807         # Input settings
808         self.draw_input_prefs(inputs, split)
809
810         # Keymap Settings
811         self.draw_keymaps(context, split)
812
813         #print("runtime", time.time() - start)
814
815
816 class USERPREF_PT_addons(bpy.types.Panel):
817     bl_space_type = 'USER_PREFERENCES'
818     bl_label = "Addons"
819     bl_region_type = 'WINDOW'
820     bl_show_header = False
821     
822     _addons_fake_modules = {}
823
824     @classmethod
825     def poll(cls, context):
826         userpref = context.user_preferences
827         return (userpref.active_section == 'ADDONS')
828
829     @staticmethod
830     def module_get(mod_name):
831         return USERPREF_PT_addons._addons_fake_modules[mod_name]
832
833     @staticmethod
834     def _addon_list():
835         import os
836         import sys
837         import time
838
839         modules = []
840         loaded_modules = set()
841         paths = bpy.utils.script_paths("addons")
842         # if folder addons_contrib/ exists, scripts in there will be loaded
843         paths += bpy.utils.script_paths("addons_contrib")
844
845         if bpy.app.debug:
846             t_main = time.time()
847
848         # fake module importing
849         def fake_module(mod_name, mod_path, speedy=True):
850             if bpy.app.debug:
851                 print("fake_module", mod_name, mod_path)
852             import ast
853             ModuleType = type(ast)
854             if speedy:
855                 lines = []
856                 line_iter = iter(open(mod_path, "r"))
857                 l = ""
858                 while not l.startswith("bl_addon_info"):
859                     l = line_iter.readline()
860                     if len(l) == 0:
861                         break
862                 while l.rstrip():
863                     lines.append(l)
864                     l = line_iter.readline()
865                 del line_iter
866                 data = "".join(lines)
867
868             else:
869                 data = open(mod_path, "r").read()
870
871             ast_data = ast.parse(data, filename=mod_path)
872             body_info = None
873             for body in ast_data.body:
874                 if body.__class__ == ast.Assign:
875                     if len(body.targets) == 1:
876                         if getattr(body.targets[0], "id", "") == "bl_addon_info":
877                             body_info = body
878                             break
879
880             if body_info:
881                 mod = ModuleType(mod_name)
882                 mod.bl_addon_info = ast.literal_eval(body.value)
883                 mod.__file__ = mod_path
884                 mod.__time__ = os.path.getmtime(mod_path)
885                 return mod
886             else:
887                 return None
888
889         modules_stale = set(USERPREF_PT_addons._addons_fake_modules.keys())
890
891         for path in paths:
892             for f in sorted(os.listdir(path)):
893                 if f.endswith(".py"):
894                     mod_name = f[0:-3]
895                     mod_path = os.path.join(path, f)
896                 elif ("." not in f) and (os.path.isfile(os.path.join(path, f, "__init__.py"))):
897                     mod_name = f
898                     mod_path = os.path.join(path, f, "__init__.py")
899                 else:
900                     mod_name = ""
901                     mod_path = ""
902
903                 if mod_name:
904                     if mod_name in modules_stale:
905                         modules_stale.remove(mod_name)
906                     mod = USERPREF_PT_addons._addons_fake_modules.get(mod_name)
907                     if mod:
908                         if mod.__time__ != os.path.getmtime(mod_path):
909                             print("Reloading", mod_name)
910                             del USERPREF_PT_addons._addons_fake_modules[mod_name]
911                             mod = None
912
913                     if mod is None:
914                         mod = fake_module(mod_name, mod_path)
915                         if mod:
916                             USERPREF_PT_addons._addons_fake_modules[mod_name] = mod
917                     
918         
919         # just incase we get stale modules, not likely
920         for mod_stale in modules_stale:
921             del USERPREF_PT_addons._addons_fake_modules[mod_stale]
922         del modules_stale
923
924         mod_list = list(USERPREF_PT_addons._addons_fake_modules.values())
925         mod_list.sort(key=lambda mod: (mod.bl_addon_info['category'], mod.bl_addon_info['name']))
926         return mod_list
927
928     def draw(self, context):
929         layout = self.layout
930
931         userpref = context.user_preferences
932         used_ext = {ext.module for ext in userpref.addons}
933
934         # collect the categories that can be filtered on
935         addons = [(mod, addon_info_get(mod)) for mod in self._addon_list()]
936
937         cats = {info["category"] for mod, info in addons}
938         cats.discard("")
939
940         cats = ["All", "Enabled", "Disabled"] + sorted(cats)
941
942         bpy.types.Scene.EnumProperty(items=[(cat, cat, cat + " addons") for cat in cats],
943             name="Category", attr="addon_filter", description="Filter add-ons by category")
944         bpy.types.Scene.StringProperty(name="Search", attr="addon_search",
945             description="Search within the selected filter")
946
947         split = layout.split(percentage=0.2)
948         col = split.column()
949         col.prop(context.scene, "addon_filter", text="Filter", expand=True)
950         col.prop(context.scene, "addon_search", text="", icon='VIEWZOOM')
951
952         col = split.column()
953
954         filter = context.scene.addon_filter
955         search = context.scene.addon_search.lower()
956
957         for mod, info in addons:
958             module_name = mod.__name__
959
960             is_enabled = module_name in used_ext
961
962             # check if add-on should be visible with current filters
963             if (filter == "All") or \
964                     (filter == info["category"]) or \
965                     (filter == "Enabled" and is_enabled) or \
966                     (filter == "Disabled" and not is_enabled):
967
968
969                 if search and search not in info["name"].lower():
970                     if info["author"]:
971                         if search not in info["author"].lower():
972                             continue
973                     else:
974                         continue
975
976                 # Addon UI Code
977                 box = col.column().box()
978                 colsub = box.column()
979                 row = colsub.row()
980
981                 row.operator("wm.addon_expand", icon='TRIA_DOWN' if info["expanded"] else 'TRIA_RIGHT', emboss=False).module = module_name
982
983                 rowsub = row.row()
984                 rowsub.active = is_enabled
985                 rowsub.label(text=info["name"], icon='ERROR' if info["warning"] else 'BLENDER')
986
987                 if is_enabled:
988                     row.operator("wm.addon_disable", icon='CHECKBOX_HLT', text="", emboss=False).module = module_name
989                 else:
990                     row.operator("wm.addon_enable", icon='CHECKBOX_DEHLT', text="", emboss=False).module = module_name
991
992                 # Expanded UI (only if additional infos are available)
993                 if info["expanded"]:
994                     if info["description"]:
995                         split = colsub.row().split(percentage=0.15)
996                         split.label(text='Description:')
997                         split.label(text=info["description"])
998                     if info["location"]:
999                         split = colsub.row().split(percentage=0.15)
1000                         split.label(text='Location:')
1001                         split.label(text=info["location"])
1002                     if info["author"]:
1003                         split = colsub.row().split(percentage=0.15)
1004                         split.label(text='Author:')
1005                         split.label(text=info["author"])
1006                     if info["version"]:
1007                         split = colsub.row().split(percentage=0.15)
1008                         split.label(text='Version:')
1009                         split.label(text=info["version"])
1010                     if info["warning"]:
1011                         split = colsub.row().split(percentage=0.15)
1012                         split.label(text="Warning:")
1013                         split.label(text='  ' + info["warning"], icon='ERROR')
1014                     if info["wiki_url"] or info["tracker_url"]:
1015                         split = colsub.row().split(percentage=0.15)
1016                         split.label(text="Internet:")
1017                         if info["wiki_url"]:
1018                             split.operator("wm.url_open", text="Link to the Wiki", icon='HELP').url = info["wiki_url"]
1019                         if info["tracker_url"]:
1020                             split.operator("wm.url_open", text="Report a Bug", icon='URL').url = info["tracker_url"]
1021
1022                         if info["wiki_url"] and info["tracker_url"]:
1023                             split.separator()
1024                         else:
1025                             split.separator()
1026                             split.separator()
1027
1028         # Append missing scripts
1029         # First collect scripts that are used but have no script file.
1030         module_names = {mod.__name__ for mod, info in addons}
1031         missing_modules = {ext for ext in used_ext if ext not in module_names}
1032
1033         if missing_modules and filter in ("All", "Enabled"):
1034             col.column().separator()
1035             col.column().label(text="Missing script files")
1036
1037             module_names = {mod.__name__ for mod, info in addons}
1038             for ext in sorted(missing_modules):
1039                 # Addon UI Code
1040                 box = col.column().box()
1041                 colsub = box.column()
1042                 row = colsub.row()
1043
1044                 row.label(text=ext, icon='ERROR')
1045                 row.operator("wm.addon_disable").module = ext
1046
1047 from bpy.props import *
1048
1049
1050 def addon_info_get(mod, info_basis={"name": "", "author": "", "version": "", "blender": "", "location": "", "description": "", "wiki_url": "", "tracker_url": "", "category": "", "warning": "", "expanded": False}):
1051     addon_info = getattr(mod, "bl_addon_info", {})
1052
1053     # avoid re-initializing
1054     if "_init" in addon_info:
1055         return addon_info
1056
1057     if not addon_info:
1058         mod.bl_addon_info = addon_info
1059
1060     for key, value in info_basis.items():
1061         addon_info.setdefault(key, value)
1062
1063     if not addon_info["name"]:
1064         addon_info["name"] = mod.__name__
1065
1066     addon_info["_init"] = None
1067     return addon_info
1068
1069
1070 class WM_OT_addon_enable(bpy.types.Operator):
1071     "Enable an addon"
1072     bl_idname = "wm.addon_enable"
1073     bl_label = "Enable Add-On"
1074
1075     module = StringProperty(name="Module", description="Module name of the addon to enable")
1076
1077     def execute(self, context):
1078         module_name = self.properties.module
1079
1080         # note, this still gets added to _bpy_types.TypeMap
1081         import bpy_types as _bpy_types
1082         _bpy_types._register_immediate = False
1083
1084         try:
1085             mod = __import__(module_name)
1086             _bpy_types._register_module(module_name)
1087             mod.register()
1088         except:
1089             import traceback
1090             traceback.print_exc()
1091             return {'CANCELLED'}
1092
1093         ext = context.user_preferences.addons.new()
1094         ext.module = module_name
1095
1096         # check if add-on is written for current blender version, or raise a warning
1097         info = addon_info_get(mod)
1098
1099         if info.get("blender", (0, 0, 0)) > bpy.app.version:
1100             self.report("WARNING','This script was written for a newer version of Blender and might not function (correctly).\nThe script is enabled though.")
1101         
1102         _bpy_types._register_immediate = True
1103         
1104         return {'FINISHED'}
1105
1106
1107 class WM_OT_addon_disable(bpy.types.Operator):
1108     "Disable an addon"
1109     bl_idname = "wm.addon_disable"
1110     bl_label = "Disable Add-On"
1111
1112     module = StringProperty(name="Module", description="Module name of the addon to disable")
1113
1114     def execute(self, context):
1115         import bpy_types as _bpy_types
1116         module_name = self.properties.module
1117
1118         try:
1119             mod = __import__(module_name)
1120             _bpy_types._unregister_module(module_name, free=False) # dont free because we may want to enable again.
1121             mod.unregister()
1122         except:
1123             import traceback
1124             traceback.print_exc()
1125
1126         addons = context.user_preferences.addons
1127         ok = True
1128         while ok: # incase its in more then once.
1129             ok = False
1130             for ext in addons:
1131                 if ext.module == module_name:
1132                     addons.remove(ext)
1133                     ok = True
1134                     break
1135
1136         return {'FINISHED'}
1137
1138
1139 class WM_OT_addon_install(bpy.types.Operator):
1140     "Install an addon"
1141     bl_idname = "wm.addon_install"
1142     bl_label = "Install Add-On..."
1143
1144     module = StringProperty(name="Module", description="Module name of the addon to disable")
1145
1146     filepath = StringProperty(name="File Path", description="File path to write file to")
1147     filter_folder = BoolProperty(name="Filter folders", description="", default=True, options={'HIDDEN'})
1148     filter_python = BoolProperty(name="Filter python", description="", default=True, options={'HIDDEN'})
1149
1150     def execute(self, context):
1151         import traceback
1152         import zipfile
1153         pyfile = self.properties.filepath
1154
1155         path_addons = bpy.utils.script_paths("addons")[-1]
1156
1157         #check to see if the file is in compressed format (.zip)
1158         if zipfile.is_zipfile(pyfile):
1159             try:
1160                 file_to_extract = zipfile.ZipFile(pyfile, 'r')
1161
1162                 #extract the file to "addons"
1163                 file_to_extract.extractall(path_addons)
1164
1165             except:
1166                 traceback.print_exc()
1167                 return {'CANCELLED'}
1168
1169         else:
1170             path_dest = os.path.join(path_addons, os.path.basename(pyfile))
1171
1172             if os.path.exists(path_dest):
1173                 self.report({'WARNING'}, "File already installed to '%s'\n" % path_dest)
1174                 return {'CANCELLED'}
1175
1176             #if not compressed file just copy into the addon path
1177             try:
1178                 shutil.copyfile(pyfile, path_dest)
1179
1180             except:
1181                 traceback.print_exc()
1182                 return {'CANCELLED'}
1183
1184         # TODO, should not be a warning.
1185         # self.report({'WARNING'}, "File installed to '%s'\n" % path_dest)
1186         return {'FINISHED'}
1187
1188     def invoke(self, context, event):
1189         paths = bpy.utils.script_paths("addons")
1190         if not paths:
1191             self.report({'ERROR'}, "No 'addons' path could be found in " + str(bpy.utils.script_paths()))
1192             return {'CANCELLED'}
1193
1194         wm = context.manager
1195         wm.add_fileselect(self)
1196         return {'RUNNING_MODAL'}
1197
1198
1199 class WM_OT_addon_expand(bpy.types.Operator):
1200     "Display more information on this add-on"
1201     bl_idname = "wm.addon_expand"
1202     bl_label = ""
1203
1204     module = StringProperty(name="Module", description="Module name of the addon to expand")
1205
1206     def execute(self, context):
1207         module_name = self.properties.module
1208
1209         # unlikely to fail, module should have already been imported
1210         try:
1211             # mod = __import__(module_name)
1212             mod = USERPREF_PT_addons.module_get(module_name)
1213         except:
1214             import traceback
1215             traceback.print_exc()
1216             return {'CANCELLED'}
1217
1218         info = addon_info_get(mod)
1219         info["expanded"] = not info["expanded"]
1220         return {'FINISHED'}
1221
1222
1223 def register():
1224     pass
1225
1226 def unregister():
1227     pass
1228
1229 if __name__ == "__main__":
1230     register()