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