feeae5d3f9b51ce18e83e82fd45e0a07cb20c22e
[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_show_header = False
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_show_header = False
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_show_header = False
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_show_header = False
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
363         # 1. Column
364         column = split.column()
365         colsplit = column.split(percentage=0.85)
366
367         col = colsplit.column()
368         col.label(text="General:")
369         col.prop(system, "dpi")
370         col.prop(system, "frame_server_port")
371         col.prop(system, "scrollback", text="Console Scrollback")
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
415         # 2. Column
416         column = split.column()
417         colsplit = column.split(percentage=0.85)
418
419         col = colsplit.column()
420         col.label(text="OpenGL:")
421         col.prop(system, "gl_clip_alpha", slider=True)
422         col.prop(system, "use_mipmaps")
423         col.prop(system, "use_vertex_buffer_objects")
424         #Anti-aliasing is disabled as it breaks broder/lasso select
425         #col.prop(system, "use_antialiasing")
426         col.label(text="Window Draw Method:")
427         col.prop(system, "window_draw_method", text="")
428         col.label(text="Textures:")
429         col.prop(system, "gl_texture_limit", text="Limit Size")
430         col.prop(system, "texture_time_out", text="Time Out")
431         col.prop(system, "texture_collection_rate", text="Collection Rate")
432
433         col.separator()
434         col.separator()
435         col.separator()
436
437         col.label(text="Sequencer:")
438         col.prop(system, "prefetch_frames")
439         col.prop(system, "memory_cache_limit")
440
441
442         # 3. Column
443         column = split.column()
444
445         column.label(text="Solid OpenGL lights:")
446
447         split = column.split(percentage=0.1)
448         split.label()
449         split.label(text="Colors:")
450         split.label(text="Direction:")
451
452         lamp = system.solid_lights[0]
453         opengl_lamp_buttons(column, lamp)
454
455         lamp = system.solid_lights[1]
456         opengl_lamp_buttons(column, lamp)
457
458         lamp = system.solid_lights[2]
459         opengl_lamp_buttons(column, lamp)
460
461         column.separator()
462         column.separator()
463         column.separator()
464
465         column.label(text="Color Picker Type:")
466         column.row().prop(system, "color_picker_type", text="")
467
468         column.separator()
469         column.separator()
470         column.separator()
471
472         column.prop(system, "use_weight_color_range", text="Custom Weight Paint Range")
473         sub = column.column()
474         sub.active = system.use_weight_color_range
475         sub.template_color_ramp(system, "weight_color_range", expand=True)
476
477
478 class USERPREF_PT_theme(bpy.types.Panel):
479     bl_space_type = 'USER_PREFERENCES'
480     bl_label = "Themes"
481     bl_region_type = 'WINDOW'
482     bl_show_header = False
483
484     @staticmethod
485     def _theme_generic(split, themedata):
486
487         row = split.row()
488
489         subsplit = row.split(percentage=0.95)
490
491         padding1 = subsplit.split(percentage=0.15)
492         padding1.column()
493
494         subsplit = row.split(percentage=0.85)
495
496         padding2 = subsplit.split(percentage=0.15)
497         padding2.column()
498
499         colsub_pair = padding1.column(), padding2.column()
500
501         props_type = {}
502
503         for i, prop in enumerate(themedata.rna_type.properties):
504             attr = prop.identifier
505             if attr == "rna_type":
506                 continue
507
508             props_type.setdefault((prop.type, prop.subtype), []).append(prop.identifier)
509
510         for props_type, props_ls in sorted(props_type.items()):
511             for i, attr in enumerate(props_ls):
512                 colsub_pair[i % 2].row().prop(themedata, attr)
513
514     @classmethod
515     def poll(cls, context):
516         userpref = context.user_preferences
517         return (userpref.active_section == 'THEMES')
518
519     def draw(self, context):
520         layout = self.layout
521
522         theme = context.user_preferences.themes[0]
523
524         split_themes = layout.split(percentage=0.2)
525         split_themes.prop(theme, "theme_area", expand=True)
526
527         split = layout.split(percentage=0.4)
528
529
530         layout.separator()
531         layout.separator()
532
533         split = split_themes.split()
534
535         if theme.theme_area == 'USER_INTERFACE':
536             col = split.column()
537
538             ui = theme.user_interface.wcol_regular
539             col.label(text="Regular:")
540             ui_items_general(col, ui)
541
542             ui = theme.user_interface.wcol_tool
543             col.label(text="Tool:")
544             ui_items_general(col, ui)
545
546             ui = theme.user_interface.wcol_radio
547             col.label(text="Radio Buttons:")
548             ui_items_general(col, ui)
549
550             ui = theme.user_interface.wcol_text
551             col.label(text="Text:")
552             ui_items_general(col, ui)
553
554             ui = theme.user_interface.wcol_option
555             col.label(text="Option:")
556             ui_items_general(col, ui)
557
558             ui = theme.user_interface.wcol_toggle
559             col.label(text="Toggle:")
560             ui_items_general(col, ui)
561
562             ui = theme.user_interface.wcol_num
563             col.label(text="Number Field:")
564             ui_items_general(col, ui)
565
566             ui = theme.user_interface.wcol_numslider
567             col.label(text="Value Slider:")
568             ui_items_general(col, ui)
569
570             ui = theme.user_interface.wcol_box
571             col.label(text="Box:")
572             ui_items_general(col, ui)
573
574             ui = theme.user_interface.wcol_menu
575             col.label(text="Menu:")
576             ui_items_general(col, ui)
577
578             ui = theme.user_interface.wcol_pulldown
579             col.label(text="Pulldown:")
580             ui_items_general(col, ui)
581
582             ui = theme.user_interface.wcol_menu_back
583             col.label(text="Menu Back:")
584             ui_items_general(col, ui)
585
586             ui = theme.user_interface.wcol_menu_item
587             col.label(text="Menu Item:")
588             ui_items_general(col, ui)
589
590             ui = theme.user_interface.wcol_scroll
591             col.label(text="Scroll Bar:")
592             ui_items_general(col, ui)
593
594             ui = theme.user_interface.wcol_progress
595             col.label(text="Progress Bar:")
596             ui_items_general(col, ui)
597
598             ui = theme.user_interface.wcol_list_item
599             col.label(text="List Item:")
600             ui_items_general(col, ui)
601
602             ui = theme.user_interface.wcol_state
603             col.label(text="State:")
604
605             row = col.row()
606
607             subsplit = row.split(percentage=0.95)
608
609             padding = subsplit.split(percentage=0.15)
610             colsub = padding.column()
611             colsub = padding.column()
612             colsub.row().prop(ui, "inner_anim")
613             colsub.row().prop(ui, "inner_anim_sel")
614             colsub.row().prop(ui, "inner_driven")
615             colsub.row().prop(ui, "inner_driven_sel")
616
617             subsplit = row.split(percentage=0.85)
618
619             padding = subsplit.split(percentage=0.15)
620             colsub = padding.column()
621             colsub = padding.column()
622             colsub.row().prop(ui, "inner_key")
623             colsub.row().prop(ui, "inner_key_sel")
624             colsub.row().prop(ui, "blend")
625
626
627             ui = theme.user_interface
628             col.separator()
629             col.separator()
630
631             split = col.split(percentage=0.93)
632             split.prop(ui, "icon_file")
633
634             layout.separator()
635             layout.separator()
636
637         else:
638             self._theme_generic(split, getattr(theme, theme.theme_area.lower()))
639
640
641 class USERPREF_PT_file(bpy.types.Panel):
642     bl_space_type = 'USER_PREFERENCES'
643     bl_label = "Files"
644     bl_region_type = 'WINDOW'
645     bl_show_header = False
646
647     @classmethod
648     def poll(cls, context):
649         userpref = context.user_preferences
650         return (userpref.active_section == 'FILES')
651
652     def draw(self, context):
653         layout = self.layout
654
655         userpref = context.user_preferences
656         paths = userpref.filepaths
657
658         split = layout.split(percentage=0.7)
659
660         col = split.column()
661         col.label(text="File Paths:")
662
663         colsplit = col.split(percentage=0.95)
664         col1 = colsplit.split(percentage=0.3)
665
666         sub = col1.column()
667         sub.label(text="Fonts:")
668         sub.label(text="Textures:")
669         sub.label(text="Texture Plugins:")
670         sub.label(text="Sequence Plugins:")
671         sub.label(text="Render Output:")
672         sub.label(text="Scripts:")
673         sub.label(text="Sounds:")
674         sub.label(text="Temp:")
675         sub.label(text="Image Editor:")
676         sub.label(text="Animation Player:")
677
678         sub = col1.column()
679         sub.prop(paths, "font_directory", text="")
680         sub.prop(paths, "texture_directory", text="")
681         sub.prop(paths, "texture_plugin_directory", text="")
682         sub.prop(paths, "sequence_plugin_directory", text="")
683         sub.prop(paths, "render_output_directory", text="")
684         sub.prop(paths, "script_directory", text="")
685         sub.prop(paths, "sound_directory", text="")
686         sub.prop(paths, "temporary_directory", text="")
687         sub.prop(paths, "image_editor", text="")
688         subsplit = sub.split(percentage=0.3)
689         subsplit.prop(paths, "animation_player_preset", text="")
690         subsplit.prop(paths, "animation_player", text="")
691
692         col = split.column()
693         col.label(text="Save & Load:")
694         col.prop(paths, "use_relative_paths")
695         col.prop(paths, "use_file_compression")
696         col.prop(paths, "use_load_ui")
697         col.prop(paths, "use_filter_files")
698         col.prop(paths, "show_hidden_files_datablocks")
699
700         col.separator()
701         col.separator()
702
703         col.label(text="Auto Save:")
704         col.prop(paths, "save_version")
705         col.prop(paths, "recent_files")
706         col.prop(paths, "use_save_preview_images")
707         col.prop(paths, "use_auto_save_temporary_files")
708         sub = col.column()
709         sub.active = paths.use_auto_save_temporary_files
710         sub.prop(paths, "auto_save_time", text="Timer (mins)")
711
712 from space_userpref_keymap import InputKeyMapPanel
713
714
715 class USERPREF_PT_input(InputKeyMapPanel):
716     bl_space_type = 'USER_PREFERENCES'
717     bl_label = "Input"
718
719     @classmethod
720     def poll(cls, context):
721         userpref = context.user_preferences
722         return (userpref.active_section == 'INPUT')
723
724     def draw_input_prefs(self, inputs, layout):
725         # General settings
726         row = layout.row()
727         col = row.column()
728
729         sub = col.column()
730         sub.label(text="Presets:")
731         subrow = sub.row(align=True)
732         subrow.menu("USERPREF_MT_interaction_presets", text=bpy.types.USERPREF_MT_interaction_presets.bl_label)
733         subrow.operator("wm.interaction_preset_add", text="", icon='ZOOMIN')
734         sub.separator()
735
736         sub.label(text="Mouse:")
737         sub1 = sub.column()
738         sub1.active = (inputs.select_mouse == 'RIGHT')
739         sub1.prop(inputs, "use_mouse_emulate_3_button")
740         sub.prop(inputs, "use_mouse_continuous")
741
742         sub.label(text="Select With:")
743         sub.row().prop(inputs, "select_mouse", expand=True)
744
745         sub = col.column()
746         sub.label(text="Double Click:")
747         sub.prop(inputs, "mouse_double_click_time", text="Speed")
748
749         sub.separator()
750
751         sub.prop(inputs, "use_emulate_numpad")
752
753         sub.separator()
754
755         sub.label(text="Orbit Style:")
756         sub.row().prop(inputs, "view_rotate_method", expand=True)
757
758         sub.label(text="Zoom Style:")
759         sub.row().prop(inputs, "view_zoom_method", text="")
760         if inputs.view_zoom_method == 'DOLLY':
761             sub.row().prop(inputs, "view_zoom_axis", expand=True)
762             sub.prop(inputs, "invert_mouse_wheel_zoom")
763
764         #sub.prop(inputs, "use_mouse_mmb_paste")
765
766         #col.separator()
767
768         sub = col.column()
769         sub.label(text="Mouse Wheel:")
770         sub.prop(inputs, "invert_zoom_wheel", text="Invert Wheel Zoom Direction")
771         #sub.prop(view, "wheel_scroll_lines", text="Scroll Lines")
772
773         col.separator()
774         ''' not implemented yet
775         sub = col.column()
776         sub.label(text="NDOF Device:")
777         sub.prop(inputs, "ndof_pan_speed", text="Pan Speed")
778         sub.prop(inputs, "ndof_rotate_speed", text="Orbit Speed")
779         '''
780
781         row.separator()
782
783     def draw(self, context):
784         layout = self.layout
785
786         #import time
787
788         #start = time.time()
789
790         userpref = context.user_preferences
791         wm = context.manager
792
793         inputs = userpref.inputs
794
795         split = layout.split(percentage=0.25)
796
797         # Input settings
798         self.draw_input_prefs(inputs, split)
799
800         # Keymap Settings
801         self.draw_keymaps(context, split)
802
803         #print("runtime", time.time() - start)
804
805
806 class USERPREF_PT_addons(bpy.types.Panel):
807     bl_space_type = 'USER_PREFERENCES'
808     bl_label = "Addons"
809     bl_region_type = 'WINDOW'
810     bl_show_header = False
811     
812     _addons_fake_modules = {}
813
814     @classmethod
815     def poll(cls, context):
816         userpref = context.user_preferences
817         return (userpref.active_section == 'ADDONS')
818
819     @staticmethod
820     def module_get(mod_name):
821         return USERPREF_PT_addons._addons_fake_modules[mod_name]
822
823     @staticmethod
824     def _addon_list():
825         import os
826         import sys
827         import time
828
829         modules = []
830         loaded_modules = set()
831         paths = bpy.utils.script_paths("addons")
832         # if folder addons_contrib/ exists, scripts in there will be loaded
833         paths += bpy.utils.script_paths("addons_contrib")
834
835         if bpy.app.debug:
836             t_main = time.time()
837
838         # fake module importing
839         def fake_module(mod_name, mod_path, speedy=True):
840             if bpy.app.debug:
841                 print("fake_module", mod_name, mod_path)
842             import ast
843             ModuleType = type(ast)
844             if speedy:
845                 lines = []
846                 line_iter = iter(open(mod_path, "r"))
847                 l = ""
848                 while not l.startswith("bl_addon_info"):
849                     l = line_iter.readline()
850                     if len(l) == 0:
851                         break
852                 while l.rstrip():
853                     lines.append(l)
854                     l = line_iter.readline()
855                 del line_iter
856                 data = "".join(lines)
857
858             else:
859                 data = open(mod_path, "r").read()
860
861             ast_data = ast.parse(data, filename=mod_path)
862             body_info = None
863             for body in ast_data.body:
864                 if body.__class__ == ast.Assign:
865                     if len(body.targets) == 1:
866                         if getattr(body.targets[0], "id", "") == "bl_addon_info":
867                             body_info = body
868                             break
869
870             if body_info:
871                 mod = ModuleType(mod_name)
872                 mod.bl_addon_info = ast.literal_eval(body.value)
873                 mod.__file__ = mod_path
874                 mod.__time__ = os.path.getmtime(mod_path)
875                 return mod
876             else:
877                 return None
878
879         modules_stale = set(USERPREF_PT_addons._addons_fake_modules.keys())
880
881         for path in paths:
882             for f in sorted(os.listdir(path)):
883                 if f.endswith(".py"):
884                     mod_name = f[0:-3]
885                     mod_path = os.path.join(path, f)
886                 elif ("." not in f) and (os.path.isfile(os.path.join(path, f, "__init__.py"))):
887                     mod_name = f
888                     mod_path = os.path.join(path, f, "__init__.py")
889                 else:
890                     mod_name = ""
891                     mod_path = ""
892
893                 if mod_name:
894                     if mod_name in modules_stale:
895                         modules_stale.remove(mod_name)
896                     mod = USERPREF_PT_addons._addons_fake_modules.get(mod_name)
897                     if mod:
898                         if mod.__time__ != os.path.getmtime(mod_path):
899                             print("Reloading", mod_name)
900                             del USERPREF_PT_addons._addons_fake_modules[mod_name]
901                             mod = None
902
903                     if mod is None:
904                         mod = fake_module(mod_name, mod_path)
905                         if mod:
906                             USERPREF_PT_addons._addons_fake_modules[mod_name] = mod
907                     
908         
909         # just incase we get stale modules, not likely
910         for mod_stale in modules_stale:
911             del USERPREF_PT_addons._addons_fake_modules[mod_stale]
912         del modules_stale
913
914         mod_list = list(USERPREF_PT_addons._addons_fake_modules.values())
915         mod_list.sort(key=lambda mod: (mod.bl_addon_info['category'], mod.bl_addon_info['name']))
916         return mod_list
917
918     def draw(self, context):
919         layout = self.layout
920
921         userpref = context.user_preferences
922         used_ext = {ext.module for ext in userpref.addons}
923
924         # collect the categories that can be filtered on
925         addons = [(mod, addon_info_get(mod)) for mod in self._addon_list()]
926
927         cats = {info["category"] for mod, info in addons}
928         cats.discard("")
929
930         cats = ["All", "Enabled", "Disabled"] + sorted(cats)
931
932         bpy.types.Scene.EnumProperty(items=[(cat, cat, cat + " addons") for cat in cats],
933             name="Category", attr="addon_filter", description="Filter add-ons by category")
934         bpy.types.Scene.StringProperty(name="Search", attr="addon_search",
935             description="Search within the selected filter")
936
937         split = layout.split(percentage=0.2)
938         col = split.column()
939         col.prop(context.scene, "addon_filter", text="Filter", expand=True)
940         col.prop(context.scene, "addon_search", text="", icon='VIEWZOOM')
941
942         col = split.column()
943
944         filter = context.scene.addon_filter
945         search = context.scene.addon_search.lower()
946
947         for mod, info in addons:
948             module_name = mod.__name__
949
950             is_enabled = module_name in used_ext
951
952             # check if add-on should be visible with current filters
953             if (filter == "All") or \
954                     (filter == info["category"]) or \
955                     (filter == "Enabled" and is_enabled) or \
956                     (filter == "Disabled" and not is_enabled):
957
958
959                 if search and search not in info["name"].lower():
960                     if info["author"]:
961                         if search not in info["author"].lower():
962                             continue
963                     else:
964                         continue
965
966                 # Addon UI Code
967                 box = col.column().box()
968                 colsub = box.column()
969                 row = colsub.row()
970
971                 row.operator("wm.addon_expand", icon='TRIA_DOWN' if info["show_expanded"] else 'TRIA_RIGHT', emboss=False).module = module_name
972
973                 rowsub = row.row()
974                 rowsub.active = is_enabled
975                 rowsub.label(text=info["name"], icon='ERROR' if info["warning"] else 'BLENDER')
976
977                 if is_enabled:
978                     row.operator("wm.addon_disable", icon='CHECKBOX_HLT', text="", emboss=False).module = module_name
979                 else:
980                     row.operator("wm.addon_enable", icon='CHECKBOX_DEHLT', text="", emboss=False).module = module_name
981
982                 # Expanded UI (only if additional infos are available)
983                 if info["show_expanded"]:
984                     if info["description"]:
985                         split = colsub.row().split(percentage=0.15)
986                         split.label(text='Description:')
987                         split.label(text=info["description"])
988                     if info["location"]:
989                         split = colsub.row().split(percentage=0.15)
990                         split.label(text='Location:')
991                         split.label(text=info["location"])
992                     if info["author"]:
993                         split = colsub.row().split(percentage=0.15)
994                         split.label(text='Author:')
995                         split.label(text=info["author"])
996                     if info["version"]:
997                         split = colsub.row().split(percentage=0.15)
998                         split.label(text='Version:')
999                         split.label(text=info["version"])
1000                     if info["warning"]:
1001                         split = colsub.row().split(percentage=0.15)
1002                         split.label(text="Warning:")
1003                         split.label(text='  ' + info["warning"], icon='ERROR')
1004                     if info["wiki_url"] or info["tracker_url"]:
1005                         split = colsub.row().split(percentage=0.15)
1006                         split.label(text="Internet:")
1007                         if info["wiki_url"]:
1008                             split.operator("wm.url_open", text="Link to the Wiki", icon='HELP').url = info["wiki_url"]
1009                         if info["tracker_url"]:
1010                             split.operator("wm.url_open", text="Report a Bug", icon='URL').url = info["tracker_url"]
1011
1012                         if info["wiki_url"] and info["tracker_url"]:
1013                             split.separator()
1014                         else:
1015                             split.separator()
1016                             split.separator()
1017
1018         # Append missing scripts
1019         # First collect scripts that are used but have no script file.
1020         module_names = {mod.__name__ for mod, info in addons}
1021         missing_modules = {ext for ext in used_ext if ext not in module_names}
1022
1023         if missing_modules and filter in ("All", "Enabled"):
1024             col.column().separator()
1025             col.column().label(text="Missing script files")
1026
1027             module_names = {mod.__name__ for mod, info in addons}
1028             for ext in sorted(missing_modules):
1029                 # Addon UI Code
1030                 box = col.column().box()
1031                 colsub = box.column()
1032                 row = colsub.row()
1033
1034                 row.label(text=ext, icon='ERROR')
1035                 row.operator("wm.addon_disable").module = ext
1036
1037 from bpy.props import *
1038
1039
1040 def addon_info_get(mod, info_basis={"name": "", "author": "", "version": "", "blender": "", "location": "", "description": "", "wiki_url": "", "tracker_url": "", "category": "", "warning": "", "show_expanded": False}):
1041     addon_info = getattr(mod, "bl_addon_info", {})
1042
1043     # avoid re-initializing
1044     if "_init" in addon_info:
1045         return addon_info
1046
1047     if not addon_info:
1048         mod.bl_addon_info = addon_info
1049
1050     for key, value in info_basis.items():
1051         addon_info.setdefault(key, value)
1052
1053     if not addon_info["name"]:
1054         addon_info["name"] = mod.__name__
1055
1056     addon_info["_init"] = None
1057     return addon_info
1058
1059
1060 class WM_OT_addon_enable(bpy.types.Operator):
1061     "Enable an addon"
1062     bl_idname = "wm.addon_enable"
1063     bl_label = "Enable Add-On"
1064
1065     module = StringProperty(name="Module", description="Module name of the addon to enable")
1066
1067     def execute(self, context):
1068         module_name = self.properties.module
1069
1070         # note, this still gets added to _bpy_types.TypeMap
1071         import bpy_types as _bpy_types
1072         _bpy_types._register_immediate = False
1073
1074         try:
1075             mod = __import__(module_name)
1076             _bpy_types._register_module(module_name)
1077             mod.register()
1078         except:
1079             import traceback
1080             traceback.print_exc()
1081             return {'CANCELLED'}
1082
1083         ext = context.user_preferences.addons.new()
1084         ext.module = module_name
1085
1086         # check if add-on is written for current blender version, or raise a warning
1087         info = addon_info_get(mod)
1088
1089         if info.get("blender", (0, 0, 0)) > bpy.app.version:
1090             self.report("WARNING','This script was written for a newer version of Blender and might not function (correctly).\nThe script is enabled though.")
1091         
1092         _bpy_types._register_immediate = True
1093         
1094         return {'FINISHED'}
1095
1096
1097 class WM_OT_addon_disable(bpy.types.Operator):
1098     "Disable an addon"
1099     bl_idname = "wm.addon_disable"
1100     bl_label = "Disable Add-On"
1101
1102     module = StringProperty(name="Module", description="Module name of the addon to disable")
1103
1104     def execute(self, context):
1105         import bpy_types as _bpy_types
1106         module_name = self.properties.module
1107
1108         try:
1109             mod = __import__(module_name)
1110             _bpy_types._unregister_module(module_name, free=False) # dont free because we may want to enable again.
1111             mod.unregister()
1112         except:
1113             import traceback
1114             traceback.print_exc()
1115
1116         addons = context.user_preferences.addons
1117         ok = True
1118         while ok: # incase its in more then once.
1119             ok = False
1120             for ext in addons:
1121                 if ext.module == module_name:
1122                     addons.remove(ext)
1123                     ok = True
1124                     break
1125
1126         return {'FINISHED'}
1127
1128
1129 class WM_OT_addon_install(bpy.types.Operator):
1130     "Install an addon"
1131     bl_idname = "wm.addon_install"
1132     bl_label = "Install Add-On..."
1133
1134     module = StringProperty(name="Module", description="Module name of the addon to disable")
1135
1136     filepath = StringProperty(name="File Path", description="File path to write file to")
1137     filter_folder = BoolProperty(name="Filter folders", description="", default=True, options={'HIDDEN'})
1138     filter_python = BoolProperty(name="Filter python", description="", default=True, options={'HIDDEN'})
1139
1140     def execute(self, context):
1141         import traceback
1142         import zipfile
1143         pyfile = self.properties.filepath
1144
1145         path_addons = bpy.utils.script_paths("addons")[-1]
1146
1147         #check to see if the file is in compressed format (.zip)
1148         if zipfile.is_zipfile(pyfile):
1149             try:
1150                 file_to_extract = zipfile.ZipFile(pyfile, 'r')
1151
1152                 #extract the file to "addons"
1153                 file_to_extract.extractall(path_addons)
1154
1155             except:
1156                 traceback.print_exc()
1157                 return {'CANCELLED'}
1158
1159         else:
1160             path_dest = os.path.join(path_addons, os.path.basename(pyfile))
1161
1162             if os.path.exists(path_dest):
1163                 self.report({'WARNING'}, "File already installed to '%s'\n" % path_dest)
1164                 return {'CANCELLED'}
1165
1166             #if not compressed file just copy into the addon path
1167             try:
1168                 shutil.copyfile(pyfile, path_dest)
1169
1170             except:
1171                 traceback.print_exc()
1172                 return {'CANCELLED'}
1173
1174         # TODO, should not be a warning.
1175         # self.report({'WARNING'}, "File installed to '%s'\n" % path_dest)
1176         return {'FINISHED'}
1177
1178     def invoke(self, context, event):
1179         paths = bpy.utils.script_paths("addons")
1180         if not paths:
1181             self.report({'ERROR'}, "No 'addons' path could be found in " + str(bpy.utils.script_paths()))
1182             return {'CANCELLED'}
1183
1184         wm = context.manager
1185         wm.add_fileselect(self)
1186         return {'RUNNING_MODAL'}
1187
1188
1189 class WM_OT_addon_expand(bpy.types.Operator):
1190     "Display more information on this add-on"
1191     bl_idname = "wm.addon_expand"
1192     bl_label = ""
1193
1194     module = StringProperty(name="Module", description="Module name of the addon to expand")
1195
1196     def execute(self, context):
1197         module_name = self.properties.module
1198
1199         # unlikely to fail, module should have already been imported
1200         try:
1201             # mod = __import__(module_name)
1202             mod = USERPREF_PT_addons.module_get(module_name)
1203         except:
1204             import traceback
1205             traceback.print_exc()
1206             return {'CANCELLED'}
1207
1208         info = addon_info_get(mod)
1209         info["show_expanded"] = not info["show_expanded"]
1210         return {'FINISHED'}
1211
1212
1213 def register():
1214     pass
1215
1216 def unregister():
1217     pass
1218
1219 if __name__ == "__main__":
1220     register()