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