[#21807] Import Key Configuration problems
[blender.git] / release / scripts / ui / space_userpref.py
index 2c5e77ec2d9ca73d97f16748943340cfc0840ede..4ee1f119f53626336e0b0305a0c69f4d0c085787 100644 (file)
@@ -171,6 +171,10 @@ class USERPREF_HT_header(bpy.types.Header):
             op.path = "keymap.py"
             op = layout.operator("wm.keyconfig_import", "Import Key Configuration...")
             op.path = "keymap.py"
+        elif userpref.active_section == 'ADDONS':
+            layout.operator_context = 'INVOKE_DEFAULT'
+            op = layout.operator("wm.addon_install", "Install Add-On...")
+            op.path = "*.py"
 
 
 class USERPREF_PT_tabs(bpy.types.Panel):
@@ -276,6 +280,10 @@ class USERPREF_PT_interface(bpy.types.Panel):
         col.prop(view, "open_toplevel_delay", text="Top Level")
         col.prop(view, "open_sublevel_delay", text="Sub Level")
 
+        col.separator()
+
+        col.prop(view, "show_splash")
+
 
 class USERPREF_PT_edit(bpy.types.Panel):
     bl_space_type = 'USER_PREFERENCES'
@@ -334,6 +342,11 @@ class USERPREF_PT_edit(bpy.types.Panel):
         #col.prop(edit, "grease_pencil_simplify_stroke", text="Simplify Stroke")
         col.prop(edit, "grease_pencil_eraser_radius", text="Eraser Radius")
         col.prop(edit, "grease_pencil_smooth_stroke", text="Smooth Stroke")
+        col.separator()
+        col.separator()
+        col.separator()
+        col.label(text="Playback:")
+        col.prop(edit, "use_negative_frames")
 
         row.separator()
         row.separator()
@@ -345,20 +358,20 @@ class USERPREF_PT_edit(bpy.types.Panel):
 
         col.separator()
 
-        col.label(text="New F-Curve Defaults:")
-        col.prop(edit, "new_interpolation_type", text="Interpolation")
-        col.prop(edit, "insertkey_xyz_to_rgb", text="XYZ to RGB")
-
-        col.separator()
-
-        col.prop(edit, "auto_keying_enable", text="Auto Keyframing:")
+        col.prop(edit, "use_auto_keying", text="Auto Keyframing:")
 
         sub = col.column()
 
-        sub.active = edit.auto_keying_enable
+        # sub.active = edit.use_auto_keying # incorrect, timeline can enable
         sub.prop(edit, "auto_keyframe_insert_keyingset", text="Only Insert for Keying Set")
         sub.prop(edit, "auto_keyframe_insert_available", text="Only Insert Available")
 
+        col.separator()
+
+        col.label(text="New F-Curve Defaults:")
+        col.prop(edit, "new_interpolation_type", text="Interpolation")
+        col.prop(edit, "insertkey_xyz_to_rgb", text="XYZ to RGB")
+
         col.separator()
         col.separator()
         col.separator()
@@ -413,7 +426,8 @@ class USERPREF_PT_system(bpy.types.Panel):
         col.prop(system, "dpi")
         col.prop(system, "frame_server_port")
         col.prop(system, "scrollback", text="Console Scrollback")
-        col.prop(system, "auto_run_python_scripts")
+        col.prop(system, "auto_execute_scripts")
+        col.prop(system, "tabs_as_spaces")
 
         col.separator()
         col.separator()
@@ -648,6 +662,19 @@ class USERPREF_PT_theme(bpy.types.Panel):
             col.prop(v3d, "object_grouped")
             col.prop(v3d, "object_grouped_active")
             col.prop(v3d, "transform")
+            col.prop(v3d, "nurb_uline")
+            col.prop(v3d, "nurb_vline")
+            col.prop(v3d, "nurb_sel_uline")
+            col.prop(v3d, "nurb_sel_vline")
+            col.prop(v3d, "handle_free")
+            col.prop(v3d, "handle_auto")
+            col.prop(v3d, "handle_vect")
+            col.prop(v3d, "handle_align")
+            col.prop(v3d, "handle_sel_free")
+            col.prop(v3d, "handle_sel_auto")
+            col.prop(v3d, "handle_sel_vect")
+            col.prop(v3d, "handle_sel_align")
+            col.prop(v3d, "act_spline")
 
             col = split.column()
             col.prop(v3d, "vertex")
@@ -656,6 +683,7 @@ class USERPREF_PT_theme(bpy.types.Panel):
             col.prop(v3d, "vertex_normal")
             col.prop(v3d, "bone_solid")
             col.prop(v3d, "bone_pose")
+            col.prop(v3d, "edge_seam")
             #col.prop(v3d, "edge") Doesn't seem to work
 
         elif theme.theme_area == 'GRAPH_EDITOR':
@@ -958,6 +986,7 @@ class USERPREF_PT_theme(bpy.types.Panel):
             col.prop(prefs, "line_input")
             col.prop(prefs, "line_info")
             col.prop(prefs, "line_error")
+            col.prop(prefs, "cursor")
 
 
 class USERPREF_PT_file(bpy.types.Panel):
@@ -993,6 +1022,7 @@ class USERPREF_PT_file(bpy.types.Panel):
         sub.label(text="Scripts:")
         sub.label(text="Sounds:")
         sub.label(text="Temp:")
+        sub.label(text="Image Editor:")
         sub.label(text="Animation Player:")
 
         sub = col1.column()
@@ -1004,6 +1034,7 @@ class USERPREF_PT_file(bpy.types.Panel):
         sub.prop(paths, "python_scripts_directory", text="")
         sub.prop(paths, "sounds_directory", text="")
         sub.prop(paths, "temporary_directory", text="")
+        sub.prop(paths, "image_editor", text="")
         subsplit = sub.split(percentage=0.3)
         subsplit.prop(paths, "animation_player_preset", text="")
         subsplit.prop(paths, "animation_player", text="")
@@ -1098,7 +1129,7 @@ class USERPREF_PT_input(bpy.types.Panel):
                 # "Add New" at end of keymap item list
                 col = self.indented_layout(col, level + 1)
                 subcol = col.split(percentage=0.2).column()
-                subcol.active = km.user_defined
+                subcol.enabled = km.user_defined
                 op = subcol.operator("wm.keyitem_add", text="Add New", icon='ZOOMIN')
 
             col.separator()
@@ -1298,7 +1329,7 @@ class USERPREF_PT_input(bpy.types.Panel):
                 # "Add New" at end of keymap item list
                 col = self.indented_layout(layout, 1)
                 subcol = col.split(percentage=0.2).column()
-                subcol.active = km.user_defined
+                subcol.enabled = km.user_defined
                 op = subcol.operator("wm.keyitem_add", text="Add New", icon='ZOOMIN')
 
     def draw_hierarchy(self, defkc, layout):
@@ -1349,21 +1380,21 @@ class USERPREF_PT_input(bpy.types.Panel):
         #print("runtime", time.time() - start)
 
 
-class USERPREF_PT_extensions(bpy.types.Panel):
+class USERPREF_PT_addons(bpy.types.Panel):
     bl_space_type = 'USER_PREFERENCES'
-    bl_label = "Extensions"
+    bl_label = "Addons"
     bl_region_type = 'WINDOW'
     bl_show_header = False
 
     def poll(self, context):
         userpref = context.user_preferences
-        return (userpref.active_section == 'EXTENSIONS')
+        return (userpref.active_section == 'ADDONS')
 
-    def _extension_list(self):
+    def _addon_list(self):
         import sys
         modules = []
         loaded_modules = set()
-        paths = bpy.utils.script_paths("extensions")
+        paths = bpy.utils.script_paths("addons")
         # sys.path.insert(0, None)
         for path in paths:
             # sys.path[0] = path
@@ -1376,49 +1407,165 @@ class USERPREF_PT_extensions(bpy.types.Panel):
         layout = self.layout
 
         userpref = context.user_preferences
-        used_ext = {ext.module for ext in userpref.extensions}
+        used_ext = {ext.module for ext in userpref.addons}
 
-        col = layout.column()
+        # collect the categories that can be filtered on
+        addons = [(mod, addon_info_get(mod)) for mod in self._addon_list()]
 
-        for mod in self._extension_list():
-            box = col.box()
-            row = box.row()
-            row.label(text=mod.__doc__)
+        cats = {info["category"] for mod, info in addons}
+        cats.discard("")
+
+        cats = ['All', 'Disabled', 'Enabled'] + sorted(cats)
+
+        bpy.types.Scene.EnumProperty(items=[(cats[i], cats[i], str(i)) for i in range(len(cats))],
+            name="Category", attr="addon_filter", description="Filter add-ons by category")
+        bpy.types.Scene.StringProperty(name="Search", attr="addon_search",
+            description="Search within the selected filter")
+
+        row = layout.row()
+        row.prop(context.scene, "addon_filter", text="Filter")
+        row.prop(context.scene, "addon_search", text="Search", icon='VIEWZOOM')
+        layout.separator()
+
+        filter = context.scene.addon_filter
+        search = context.scene.addon_search.lower()
+
+        for mod, info in addons:
             module_name = mod.__name__
-            row.operator("wm.extension_disable" if module_name in used_ext else "wm.extension_enable").module = module_name
 
+            # check if add-on should be visible with current filters
+            if filter != "All" and \
+                    filter != info["category"] and \
+                    not (module_name not in used_ext and filter == "Disabled"):
+
+                continue
+
+            if search and search not in info["name"].lower():
+                if info["author"]:
+                    if search not in info["author"].lower():
+                        continue
+                else:
+                    continue
+
+            # Addon UI Code
+            box = layout.column().box()
+            column = box.column()
+            row = column.row()
+
+            # Arrow #
+            # If there are Infos or UI is expanded
+            if info["expanded"]:
+                row.operator("wm.addon_expand", icon="TRIA_DOWN").module = module_name
+            elif info["author"] or info["version"] or info["url"] or info["location"]:
+                row.operator("wm.addon_expand", icon="TRIA_RIGHT").module = module_name
+            else:
+                # Else, block UI
+                arrow = row.column()
+                arrow.enabled = False
+                arrow.operator("wm.addon_expand", icon="TRIA_RIGHT").module = module_name
+
+            row.label(text=info["name"])
+            row.operator("wm.addon_disable" if module_name in used_ext else "wm.addon_enable").module = module_name
+
+            # Expanded UI (only if additional infos are available)
+            if info["expanded"]:
+                if info["author"]:
+                    split = column.row().split(percentage=0.15)
+                    split.label(text='Author:')
+                    split.label(text=info["author"])
+                if info["version"]:
+                    split = column.row().split(percentage=0.15)
+                    split.label(text='Version:')
+                    split.label(text=info["version"])
+                if info["location"]:
+                    split = column.row().split(percentage=0.15)
+                    split.label(text='Location:')
+                    split.label(text=info["location"])
+                if info["url"]:
+                    split = column.row().split(percentage=0.15)
+                    split.label(text="Internet:")
+                    split.operator("wm.addon_links", text="Link to the Wiki").link = info["url"]
+                    split.separator()
+                    split.separator()
+
+        # Append missing scripts
+        # First collect scripts that are used but have no script file.
+        module_names = {mod.__name__ for mod, info in addons}
+        missing_modules = {ext for ext in used_ext if ext not in module_names}
+
+        if missing_modules and filter in ("All", "Enabled"):
+            layout.column().separator()
+            layout.column().label(text="Missing script files")
+
+            module_names = {mod.__name__ for mod, info in addons}
+            for ext in sorted(missing_modules):
+                # Addon UI Code
+                box = layout.column().box()
+                column = box.column()
+                row = column.row()
+
+                row.label(text=ext, icon="ERROR")
+                row.operator("wm.addon_disable").module = ext
 
 from bpy.props import *
 
-class WM_OT_extension_enable(bpy.types.Operator):
-    "Enable an extension"
-    bl_idname = "wm.extension_enable"
-    bl_label = "Enable Extension"
 
-    module = StringProperty(name="Module", description="Module name of the extension to enable")
+def addon_info_get(mod, info_basis={"name": "", "author": "", "version": "", "blender": "", "location": "", "url": "", "category": "", "expanded": False}):
+    addon_info = getattr(mod, "bl_addon_info", {})
+
+    # avoid re-initializing
+    if "_init" in addon_info:
+        return addon_info
+
+    if not addon_info:
+        mod.bl_addon_info = addon_info
+
+    for key, value in info_basis.items():
+        addon_info.setdefault(key, value)
+
+    if not addon_info["name"]:
+        addon_info["name"] = mod.__name__
+
+    addon_info["_init"] = None
+    return addon_info
+
+
+class WM_OT_addon_enable(bpy.types.Operator):
+    "Enable an addon"
+    bl_idname = "wm.addon_enable"
+    bl_label = "Enable Add-On"
+
+    module = StringProperty(name="Module", description="Module name of the addon to enable")
 
     def execute(self, context):
-        import traceback
-        ext = context.user_preferences.extensions.new()
         module_name = self.properties.module
-        ext.module = module_name
-        
+
         try:
             mod = __import__(module_name)
-            reload(mod) # FIXME: workaround for the same class not registering twice properly
             mod.register()
         except:
+            import traceback
             traceback.print_exc()
+            return {'CANCELLED'}
+
+        ext = context.user_preferences.addons.new()
+        ext.module = module_name
+
+        # check if add-on is written for current blender version, or raise a warning
+        info = addon_info_get(mod)
+
+        if info.get("blender", (0, 0, 0)) > bpy.app.version:
+            self.report("WARNING','This script was written for a newer version of Blender and might not function (correctly).\nThe script is enabled though.")
 
         return {'FINISHED'}
 
 
-class WM_OT_extension_disable(bpy.types.Operator):
-    "Disable an extension"
-    bl_idname = "wm.extension_disable"
-    bl_label = "Disable Extension"
+class WM_OT_addon_disable(bpy.types.Operator):
+    "Disable an addon"
+    bl_idname = "wm.addon_disable"
+    bl_label = "Disable Add-On"
 
-    module = StringProperty(name="Module", description="Module name of the extension to disable")
+    module = StringProperty(name="Module", description="Module name of the addon to disable")
 
     def execute(self, context):
         import traceback
@@ -1427,23 +1574,120 @@ class WM_OT_extension_disable(bpy.types.Operator):
         try:
             mod = __import__(module_name)
             mod.unregister()
-            reload(mod) # FIXME: workaround for the same class not registering twice properly
         except:
             traceback.print_exc()
-        
-        extensions = context.user_preferences.extensions
+
+        addons = context.user_preferences.addons
         ok = True
         while ok: # incase its in more then once.
             ok = False
-            for ext in extensions:
+            for ext in addons:
                 if ext.module == module_name:
-                    extensions.remove(ext)
+                    addons.remove(ext)
                     ok = True
                     break
 
         return {'FINISHED'}
 
 
+class WM_OT_addon_install(bpy.types.Operator):
+    "Install an addon"
+    bl_idname = "wm.addon_install"
+    bl_label = "Install Add-On"
+
+    module = StringProperty(name="Module", description="Module name of the addon to disable")
+
+    path = StringProperty(name="File Path", description="File path to write file to")
+    filename = StringProperty(name="File Name", description="Name of the file")
+    directory = StringProperty(name="Directory", description="Directory of the file")
+    filter_folder = BoolProperty(name="Filter folders", description="", default=True, options={'HIDDEN'})
+    filter_python = BoolProperty(name="Filter python", description="", default=True, options={'HIDDEN'})
+
+    def execute(self, context):
+        import traceback
+        import zipfile
+        pyfile = self.properties.path
+
+        path_addons = bpy.utils.script_paths("addons")[-1]
+
+        #check to see if the file is in compressed format (.zip)
+        if zipfile.is_zipfile(pyfile):
+            try:
+                file_to_extract = zipfile.ZipFile(pyfile, 'r')
+
+                #extract the file to "addons"
+                file_to_extract.extractall(path_addons)
+
+            except:
+                traceback.print_exc()
+                return {'CANCELLED'}
+
+        else:
+            path_dest = os.path.join(path_addons, os.path.basename(pyfile))
+
+            if os.path.exists(path_dest):
+                self.report({'WARNING'}, "File already installed to '%s'\n" % path_dest)
+                return {'CANCELLED'}
+
+            #if not compressed file just copy into the addon path
+            try:
+                shutil.copyfile(pyfile, path_dest)
+
+            except:
+                traceback.print_exc()
+                return {'CANCELLED'}
+
+        # TODO, should not be a warning.
+        # self.report({'WARNING'}, "File installed to '%s'\n" % path_dest)
+        return {'FINISHED'}
+
+    def invoke(self, context, event):
+        paths = bpy.utils.script_paths("addons")
+        if not paths:
+            self.report({'ERROR'}, "No 'addons' path could be found in " + str(bpy.utils.script_paths()))
+            return {'CANCELLED'}
+
+        wm = context.manager
+        wm.add_fileselect(self)
+        return {'RUNNING_MODAL'}
+
+
+class WM_OT_addon_expand(bpy.types.Operator):
+    "Display more information on this add-on"
+    bl_idname = "wm.addon_expand"
+    bl_label = ""
+
+    module = StringProperty(name="Module", description="Module name of the addon to expand")
+
+    def execute(self, context):
+        module_name = self.properties.module
+
+        # unlikely to fail, module should have alredy been imported
+        try:
+            mod = __import__(module_name)
+        except:
+            import traceback
+            traceback.print_exc()
+            return {'CANCELLED'}
+
+        info = addon_info_get(mod)
+        info["expanded"] = not info["expanded"]
+        return {'FINISHED'}
+
+
+class WM_OT_addon_links(bpy.types.Operator):
+    "Open the Blender Wiki in the Webbrowser"
+    bl_idname = "wm.addon_links"
+    bl_label = ""
+
+    link = StringProperty(name="Link", description="Link to open")
+
+    def execute(self, context):
+        import webbrowser
+        webbrowser.open(self.properties.link)
+        return {'FINISHED'}
+
+
 class WM_OT_keyconfig_test(bpy.types.Operator):
     "Test keyconfig for conflicts"
     bl_idname = "wm.keyconfig_test"
@@ -1553,27 +1797,10 @@ class WM_OT_keyconfig_test(bpy.types.Operator):
 
 
 def _string_value(value):
-    result = ""
-    if isinstance(value, str):
-        if value != "":
-            result = "\'%s\'" % value
-    elif isinstance(value, bool):
-        if value:
-            result = "True"
-        else:
-            result = "False"
-    elif isinstance(value, float):
-        result = "%.10f" % value
-    elif isinstance(value, int):
-        result = "%d" % value
+    if isinstance(value, str) or isinstance(value, bool) or isinstance(value, float) or isinstance(value, int):
+        result = repr(value)
     elif getattr(value, '__len__', False):
-        if len(value):
-            result = "["
-            for i in range(0, len(value)):
-                result += _string_value(value[i])
-                if i != len(value)-1:
-                    result += ", "
-            result += "]"
+        repr(list(value))
     else:
         print("Export key configuration: can't write ", value)
 
@@ -1626,9 +1853,9 @@ class WM_OT_keyconfig_import(bpy.types.Operator):
         else:
             shutil.move(self.properties.path, path)
 
-        __import__(config_name)
+        exec("import " + config_name)
 
-        wm = bpy.data.window_managers[0]
+        wm = bpy.context.manager
         wm.active_keyconfig = wm.keyconfigs[config_name]
 
         return {'FINISHED'}
@@ -1670,7 +1897,7 @@ class WM_OT_keyconfig_export(bpy.types.Operator):
         f.write("# Configuration %s\n" % name)
 
         f.write("import bpy\n\n")
-        f.write("wm = bpy.data.window_managers[0]\n")
+        f.write("wm = bpy.context.manager\n")
         f.write("kc = wm.add_keyconfig('%s')\n\n" % name)
 
         for km in kc.keymaps:
@@ -1849,10 +2076,13 @@ classes = [
     USERPREF_PT_system,
     USERPREF_PT_file,
     USERPREF_PT_input,
-    USERPREF_PT_extensions,
-    
-    WM_OT_extension_enable,
-    WM_OT_extension_disable,
+    USERPREF_PT_addons,
+
+    WM_OT_addon_enable,
+    WM_OT_addon_disable,
+    WM_OT_addon_install,
+    WM_OT_addon_expand,
+    WM_OT_addon_links,
 
     WM_OT_keyconfig_export,
     WM_OT_keyconfig_import,
@@ -1870,7 +2100,11 @@ def register():
     for cls in classes:
         register(cls)
 
+
 def unregister():
     unregister = bpy.types.unregister
     for cls in classes:
         unregister(cls)
+
+if __name__ == "__main__":
+    register()