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