Skip to content

Commit

Permalink
Python-formatting (JacquesLucke#167)
Browse files Browse the repository at this point in the history
* auto format python files with `black -l 120`

* Removed unused imports from auto_load.py

* Fix bare except statements

* Remove unused import
  • Loading branch information
strike-digital authored Jul 17, 2024
1 parent 0ca56e5 commit ac5a461
Show file tree
Hide file tree
Showing 18 changed files with 169 additions and 93 deletions.
6 changes: 5 additions & 1 deletion pythonFiles/generate_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,22 @@
output_dir = Path(__file__).parent.parent / "generated"
enums_output_path = output_dir / "enums.json"


def insert_enum_data(data, identifier):
type_name, prop_name = identifier.split(".")
enum_name = type_name.lower() + prop_name.title() + "Items"
data[enum_name] = enum_prop_to_dict(type_name, prop_name)


def enum_prop_to_dict(type_name, prop_name):
type = getattr(bpy.types, type_name)
prop = type.bl_rna.properties[prop_name]
return enum_items_to_dict(prop.enum_items)


def enum_items_to_dict(items):
return [{"identifier" : item.identifier, "name" : item.name, "description" : item.description} for item in items]
return [{"identifier": item.identifier, "name": item.name, "description": item.description} for item in items]


data = {}
insert_enum_data(data, "Area.type")
Expand Down
12 changes: 7 additions & 5 deletions pythonFiles/include/blender_vscode/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,15 @@ def startup(editor_address, addons_to_load: list[AddonInfo], allow_modify_extern
handle_fatal_error("Please use a newer version of Blender")

from . import installation
installation.ensure_packages_are_installed(
["debugpy", "flask", "requests"],
allow_modify_external_python)

installation.ensure_packages_are_installed(["debugpy", "flask", "requests"], allow_modify_external_python)

from . import load_addons

path_mappings = load_addons.setup_addon_links(addons_to_load)

from . import communication

communication.setup(editor_address, path_mappings)

from . import operators, ui
Expand All @@ -33,11 +34,12 @@ def startup(editor_address, addons_to_load: list[AddonInfo], allow_modify_extern

load_addons.load(addons_to_load)


def handle_fatal_error(message):
print()
print("#"*80)
print("#" * 80)
for line in message.splitlines():
print("> ", line)
print("#"*80)
print("#" * 80)
print()
sys.exit(1)
41 changes: 28 additions & 13 deletions pythonFiles/include/blender_vscode/communication.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import bpy
import time
import flask
import debugpy
import random
import requests
import threading
from functools import partial
from . utils import run_in_main_thread
from . environment import blender_path, scripts_folder
from .utils import run_in_main_thread
from .environment import blender_path, scripts_folder

EDITOR_ADDRESS = None
OWN_SERVER_PORT = None
DEBUGPY_PORT = None


def setup(address, path_mappings):
global EDITOR_ADDRESS, OWN_SERVER_PORT, DEBUGPY_PORT
EDITOR_ADDRESS = address
Expand All @@ -26,6 +26,7 @@ def setup(address, path_mappings):
debugpy.wait_for_client()
print("Debug client attached.")


def start_own_server():
port = [None]

Expand All @@ -46,6 +47,7 @@ def server_thread_function():

return port[0]


def start_debug_server():
while True:
port = get_random_port()
Expand All @@ -56,13 +58,15 @@ def start_debug_server():
pass
return port


# Server
#########################################

server = flask.Flask("Blender Server")
post_handlers = {}

@server.route("/", methods=['POST'])

@server.route("/", methods=["POST"])
def handle_post():
data = flask.request.get_json()
print("Got POST:", data)
Expand All @@ -72,7 +76,8 @@ def handle_post():

return "OK"

@server.route("/", methods=['GET'])

@server.route("/", methods=["GET"])
def handle_get():
flask.request
data = flask.request.get_json()
Expand All @@ -87,25 +92,31 @@ def register_post_handler(type, handler):
assert type not in post_handlers
post_handlers[type] = handler


def register_post_action(type, handler):
def request_handler_wrapper(data):
run_in_main_thread(partial(handler, data))
return "OK"

register_post_handler(type, request_handler_wrapper)


# Sending Data
###############################


def send_connection_information(path_mappings):
send_dict_as_json({
"type" : "setup",
"blenderPort" : OWN_SERVER_PORT,
"debugpyPort" : DEBUGPY_PORT,
"blenderPath" : str(blender_path),
"scriptsFolder" : str(scripts_folder),
"addonPathMappings" : path_mappings
})
send_dict_as_json(
{
"type": "setup",
"blenderPort": OWN_SERVER_PORT,
"debugpyPort": DEBUGPY_PORT,
"blenderPath": str(blender_path),
"scriptsFolder": str(scripts_folder),
"addonPathMappings": path_mappings,
}
)


def send_dict_as_json(data):
print("Sending:", data)
Expand All @@ -115,14 +126,18 @@ def send_dict_as_json(data):
# Utils
###############################


def get_random_port():
return random.randint(2000, 10000)


def get_blender_port():
return OWN_SERVER_PORT


def get_debugpy_port():
return DEBUGPY_PORT


def get_editor_address():
return EDITOR_ADDRESS
2 changes: 1 addition & 1 deletion pythonFiles/include/blender_vscode/environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
blender_directory = blender_path.parent

# Test for MacOS app bundles
if platform.system()=='Darwin':
if platform.system() == "Darwin":
use_own_python = blender_directory.parent in python_path.parents
else:
use_own_python = blender_directory in python_path.parents
Expand Down
26 changes: 19 additions & 7 deletions pythonFiles/include/blender_vscode/installation.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@
import subprocess
from pathlib import Path
from . import handle_fatal_error
from . environment import python_path, use_own_python
from .environment import python_path, use_own_python

cwd_for_subprocesses = python_path.parent


def ensure_packages_are_installed(package_names, allow_modify_external_python):
if packages_are_installed(package_names):
return
Expand All @@ -17,9 +18,11 @@ def ensure_packages_are_installed(package_names, allow_modify_external_python):

install_packages(package_names)


def packages_are_installed(package_names):
return all(module_can_be_imported(name) for name in package_names)


def install_packages(package_names):
if not module_can_be_imported("pip"):
install_pip()
Expand All @@ -29,47 +32,56 @@ def install_packages(package_names):

assert packages_are_installed(package_names)


def ensure_package_is_installed(name):
if not module_can_be_imported(name):
install_package(name)


def install_package(name):
target = get_package_install_directory()
subprocess.run([str(python_path), "-m", "pip", "install", name, '--target', target], cwd=cwd_for_subprocesses)
subprocess.run([str(python_path), "-m", "pip", "install", name, "--target", target], cwd=cwd_for_subprocesses)

if not module_can_be_imported(name):
handle_fatal_error(f"could not install {name}")


def install_pip():
# try ensurepip before get-pip.py
if module_can_be_imported('ensurepip'):
subprocess.run([str(python_path), '-m', 'ensurepip', '--upgrade'], cwd=cwd_for_subprocesses)
if module_can_be_imported("ensurepip"):
subprocess.run([str(python_path), "-m", "ensurepip", "--upgrade"], cwd=cwd_for_subprocesses)
return
# pip can not necessarily be imported into Blender after this
get_pip_path = Path(__file__).parent / "external" / "get-pip.py"
subprocess.run([str(python_path), str(get_pip_path)], cwd=cwd_for_subprocesses)


def get_package_install_directory():
for path in sys.path:
if os.path.basename(path) in ("dist-packages", "site-packages"):
return path

handle_fatal_error("Don't know where to install packages. Please make a bug report.")


def module_can_be_imported(name):
try:
__import__(name)
return True
except ModuleNotFoundError:
return False


def handle_cannot_install_packages(package_names):
handle_fatal_error(textwrap.dedent(f'''\
handle_fatal_error(
textwrap.dedent(
f"""\
Installing packages in Python distributions, that
don't come with Blender, is not allowed currently.
Please enable 'blender.allowModifyExternalPython'
in VS Code or install those packages yourself:
{str(package_names):53}\
'''))

"""
)
)
4 changes: 3 additions & 1 deletion pythonFiles/include/blender_vscode/load_addons.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def load(addons_to_load: list[AddonInfo]):

try:
bpy.ops.preferences.addon_enable(module=addon_name)
except:
except Exception:
traceback.print_exc()
send_dict_as_json({"type": "enableFailure", "addonPath": str(addon_info.load_dir)})

Expand All @@ -66,10 +66,12 @@ def create_link_in_user_addon_directory(directory, link_path):

if sys.platform == "win32":
import _winapi

_winapi.CreateJunction(str(directory), str(link_path))
else:
os.symlink(str(directory), str(link_path), target_is_directory=True)


def is_in_any_addon_directory(module_path):
for path in addon_directories:
if path == module_path.parent:
Expand Down
1 change: 1 addition & 0 deletions pythonFiles/include/blender_vscode/operators/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
stop_blender,
)


def register():
for module in modules:
module.register()
23 changes: 13 additions & 10 deletions pythonFiles/include/blender_vscode/operators/addon_update.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
import sys
import traceback
from bpy.props import *
from .. utils import is_addon_legacy, redraw_all
from .. communication import send_dict_as_json, register_post_action
from ..utils import is_addon_legacy, redraw_all
from ..communication import send_dict_as_json, register_post_action


class UpdateAddonOperator(bpy.types.Operator):
bl_idname = "dev.update_addon"
Expand All @@ -15,26 +16,27 @@ class UpdateAddonOperator(bpy.types.Operator):
def execute(self, context):
try:
bpy.ops.preferences.addon_disable(module=self.module_name)
except:
except Exception:
traceback.print_exc()
send_dict_as_json({"type" : "disableFailure"})
return {'CANCELLED'}
send_dict_as_json({"type": "disableFailure"})
return {"CANCELLED"}

for name in list(sys.modules.keys()):
if name.startswith(self.module_name):
del sys.modules[name]

try:
bpy.ops.preferences.addon_enable(module=self.module_name)
except:
except Exception:
traceback.print_exc()
send_dict_as_json({"type" : "enableFailure"})
return {'CANCELLED'}
send_dict_as_json({"type": "enableFailure"})
return {"CANCELLED"}

send_dict_as_json({"type" : "addonUpdated"})
send_dict_as_json({"type": "addonUpdated"})

redraw_all()
return {'FINISHED'}
return {"FINISHED"}


def reload_addon_action(data):
module_names = []
Expand All @@ -47,6 +49,7 @@ def reload_addon_action(data):
for name in module_names:
bpy.ops.dev.update_addon(module_name=name)


def register():
bpy.utils.register_class(UpdateAddonOperator)
register_post_action("reload", reload_addon_action)
Loading

0 comments on commit ac5a461

Please sign in to comment.