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