Skip to content

Commit

Permalink
Merge pull request #142 from SpectralVectors/autopep8
Browse files Browse the repository at this point in the history
Autopep8
  • Loading branch information
pppalain authored Mar 21, 2024
2 parents d0e75bf + 9e9cd34 commit 0ad061a
Show file tree
Hide file tree
Showing 121 changed files with 7,667 additions and 6,723 deletions.
241 changes: 133 additions & 108 deletions scripts/addons/cam/__init__.py

Large diffs are not rendered by default.

52 changes: 28 additions & 24 deletions scripts/addons/cam/async_op.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,27 @@

import types


@types.coroutine
def progress_async(text, n=None,value_type='%'):
def progress_async(text, n=None, value_type='%'):
"""function for reporting during the script, works for background operations in the header."""
throw_exception=yield ('progress',{'text':text,'n':n,"value_type":value_type})
throw_exception = yield ('progress', {'text': text, 'n': n, "value_type": value_type})
if throw_exception is not None:
raise throw_exception


class AsyncCancelledException(Exception):
pass


class AsyncOperatorMixin:

def __init__(self):
self.timer=None
self.coroutine=None
self._is_cancelled=False
self.timer = None
self.coroutine = None
self._is_cancelled = False

def modal(self,context,event):
def modal(self, context, event):
if bpy.app.background:
return {'PASS_THROUGH'}

Expand All @@ -35,10 +38,10 @@ def modal(self,context,event):
except Exception as e:
context.window_manager.event_timer_remove(self.timer)
bpy.context.workspace.status_text_set(None)
self.report({'ERROR'},str(e))
self.report({'ERROR'}, str(e))
return {'FINISHED'}
elif event.type == 'ESC':
self._is_cancelled=True
self._is_cancelled = True
self.tick(context)
context.window_manager.event_timer_remove(self.timer)
bpy.context.workspace.status_text_set(None)
Expand All @@ -48,7 +51,7 @@ def modal(self,context,event):
else:
return {'PASS_THROUGH'}

def show_progress(self,context,text, n,value_type):
def show_progress(self, context, text, n, value_type):
if n is not None:
progress_text = f"{text}: {n:.2f}{value_type}"
else:
Expand All @@ -57,45 +60,46 @@ def show_progress(self,context,text, n,value_type):
sys.stdout.write(f"Progress: {progress_text}\n")
sys.stdout.flush()

def tick(self,context):
if self.coroutine==None:
self.coroutine=self.execute_async(context)
def tick(self, context):
if self.coroutine == None:
self.coroutine = self.execute_async(context)
try:
if self._is_cancelled:
(msg,args)=self.coroutine.send(AsyncCancelledException("Cancelled with ESC key"))
(msg, args) = self.coroutine.send(AsyncCancelledException("Cancelled with ESC key"))
raise StopIteration
else:
(msg,args)=self.coroutine.send(None)
if msg=='progress':
self.show_progress(context,**args)
(msg, args) = self.coroutine.send(None)
if msg == 'progress':
self.show_progress(context, **args)
else:
sys.stdout.write(f"{msg},{args}")
return True
except StopIteration:
return False
except Exception as e:
print("Exception thrown in tick:",e)
print("Exception thrown in tick:", e)

def execute(self, context):
if bpy.app.background:
# running in background - don't run as modal,
# otherwise tests all fail
while self.tick(context)==True:
while self.tick(context) == True:
pass
return {'FINISHED'}
else:
self.timer=context.window_manager.event_timer_add(.001, window=context.window)
self.timer = context.window_manager.event_timer_add(.001, window=context.window)
context.window_manager.modal_handler_add(self)
return {'RUNNING_MODAL'}

class AsyncTestOperator(bpy.types.Operator,AsyncOperatorMixin):

class AsyncTestOperator(bpy.types.Operator, AsyncOperatorMixin):
"""test async operator"""
bl_idname = "object.cam_async_test_operator"
bl_label = "Test operator for async stuff"
bl_options = {'REGISTER', 'UNDO','BLOCKING'}
bl_options = {'REGISTER', 'UNDO', 'BLOCKING'}

async def execute_async(self,context):
async def execute_async(self, context):
for x in range(100):
await progress_async("Async test:",x)
await progress_async("Async test:", x)

#bpy.utils.register_class(AsyncTestOperator)
# bpy.utils.register_class(AsyncTestOperator)
92 changes: 48 additions & 44 deletions scripts/addons/cam/autoupdate.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import sys
import calendar


class UpdateChecker(bpy.types.Operator):
"""check for updates"""
bl_idname = "render.cam_check_updates"
Expand All @@ -21,31 +22,31 @@ def execute(self, context):
if bpy.app.background:
return {"FINISHED"}
last_update_check = bpy.context.preferences.addons['cam'].preferences.last_update_check
today=date.today().toordinal()
today = date.today().toordinal()
update_source = bpy.context.preferences.addons['cam'].preferences.update_source
match = re.match(r"https://github.com/([^/]+/[^/]+)",update_source)
match = re.match(r"https://github.com/([^/]+/[^/]+)", update_source)
if match:
update_source = f"https://api.github.com/repos/{match.group(1)}/releases"

print(f"update check: {update_source}")
if update_source=="None" or len(update_source)==0:
if update_source == "None" or len(update_source) == 0:
return {'FINISHED'}

bpy.context.preferences.addons['cam'].preferences.new_version_available = ""
bpy.ops.wm.save_userpref()
# get list of releases from github release
if update_source.endswith("/releases"):
with urlopen(update_source,timeout=2.0) as response:
with urlopen(update_source, timeout=2.0) as response:
body = response.read().decode("UTF-8")
# find the tag name
release_list=json.loads(body)
release_list = json.loads(body)
if len(release_list) > 0:
release = release_list[0]
tag = release["tag_name"]
print(f"Found release: {tag}")
match = re.match(r".*(\d+)\.(\s*\d+)\.(\s*\d+)",tag)
match = re.match(r".*(\d+)\.(\s*\d+)\.(\s*\d+)", tag)
if match:
version_num = tuple(map(int,match.groups()))
version_num = tuple(map(int, match.groups()))
print(f"Found version: {version_num}")
bpy.context.preferences.addons['cam'].preferences.last_update_check = today

Expand All @@ -54,17 +55,18 @@ def execute(self, context):
[str(x) for x in version_num])
bpy.ops.wm.save_userpref()
elif update_source.endswith("/commits"):
with urlopen(update_source+"?per_page=1",timeout=2) as response:
with urlopen(update_source+"?per_page=1", timeout=2) as response:
body = response.read().decode("UTF-8")
# find the tag name
commit_list=json.loads(body)
commit_sha=commit_list[0]['sha']
commit_date=commit_list[0]['commit']['author']['date']
commit_list = json.loads(body)
commit_sha = commit_list[0]['sha']
commit_date = commit_list[0]['commit']['author']['date']
if bpy.context.preferences.addons['cam'].preferences.last_commit_hash != commit_sha:
bpy.context.preferences.addons['cam'].preferences.new_version_available=commit_date
bpy.context.preferences.addons['cam'].preferences.new_version_available = commit_date
bpy.ops.wm.save_userpref()
return {'FINISHED'}


class Updater(bpy.types.Operator):
"""update to newer version if possible """
bl_idname = "render.cam_update_now"
Expand All @@ -74,27 +76,27 @@ class Updater(bpy.types.Operator):
def execute(self, context):
print("update check")
last_update_check = bpy.context.preferences.addons['cam'].preferences.last_update_check
today=date.today().toordinal()
today = date.today().toordinal()
update_source = bpy.context.preferences.addons['cam'].preferences.update_source
if update_source=="None" or len(update_source)==0:
if update_source == "None" or len(update_source) == 0:
return {'FINISHED'}
match = re.match(r"https://github.com/([^/]+/[^/]+)",update_source)
match = re.match(r"https://github.com/([^/]+/[^/]+)", update_source)
if match:
update_source = f"https://api.github.com/repos/{match.group(1)}/releases"

# get list of releases from github release
if update_source.endswith("/releases"):
with urlopen(update_source,timeout=2) as response:
with urlopen(update_source, timeout=2) as response:
body = response.read().decode("UTF-8")
# find the tag name
release_list=json.loads(body)
release_list = json.loads(body)
if len(release_list) > 0:
release = release_list[0]
tag = release["tag_name"]
print(f"Found release: {tag}")
match = re.match(r".*(\d+)\.(\s*\d+)\.(\s*\d+)",tag)
match = re.match(r".*(\d+)\.(\s*\d+)\.(\s*\d+)", tag)
if match:
version_num = tuple(map(int,match.groups()))
version_num = tuple(map(int, match.groups()))
print(f"Found version: {version_num}")
bpy.context.preferences.addons['cam'].preferences.last_update_check = today
bpy.ops.wm.save_userpref()
Expand All @@ -105,62 +107,64 @@ def execute(self, context):
self.install_zip_from_url(zip_url)
return {'FINISHED'}
elif update_source.endswith("/commits"):
with urlopen(update_source+"?per_page=1",timeout=2) as response:
with urlopen(update_source+"?per_page=1", timeout=2) as response:
body = response.read().decode("UTF-8")
# find the tag name
commit_list=json.loads(body)
commit_sha=commit_list[0]['sha']
commit_list = json.loads(body)
commit_sha = commit_list[0]['sha']
if bpy.context.preferences.addons['cam'].preferences.last_commit_hash != commit_sha:
# get zipball from this commit
zip_url = update_source.replace("/commits",f"/zipball/{commit_sha}")
zip_url = update_source.replace("/commits", f"/zipball/{commit_sha}")
self.install_zip_from_url(zip_url)
bpy.context.preferences.addons['cam'].preferences.last_commit_hash = commit_sha
bpy.ops.wm.save_userpref()
return {'FINISHED'}
def install_zip_from_url(self,zip_url):

def install_zip_from_url(self, zip_url):
with urlopen(zip_url) as zip_response:
zip_body=zip_response.read()
buffer= io.BytesIO(zip_body)
zf=zipfile.ZipFile(buffer,mode='r')
files=zf.infolist()
zip_body = zip_response.read()
buffer = io.BytesIO(zip_body)
zf = zipfile.ZipFile(buffer, mode='r')
files = zf.infolist()
cam_addon_path = pathlib.Path(__file__).parent
for fileinfo in files:
filename=fileinfo.filename
filename = fileinfo.filename
if fileinfo.is_dir() == False:
path_pos=filename.replace("\\","/").find("/scripts/addons/cam/")
if path_pos!=-1:
relative_path=filename[path_pos+len("/scripts/addons/cam/"):]
path_pos = filename.replace("\\", "/").find("/scripts/addons/cam/")
if path_pos != -1:
relative_path = filename[path_pos+len("/scripts/addons/cam/"):]
out_path = cam_addon_path / relative_path
print(out_path)
# check folder exists
out_path.parent.mkdir(parents=True,exist_ok=True)
with zf.open(filename,"r") as in_file, open(out_path,"wb") as out_file:
time_struct=(*fileinfo.date_time,0,0,0)
mtime=calendar.timegm(time_struct)
out_path.parent.mkdir(parents=True, exist_ok=True)
with zf.open(filename, "r") as in_file, open(out_path, "wb") as out_file:
time_struct = (*fileinfo.date_time, 0, 0, 0)
mtime = calendar.timegm(time_struct)
out_file.write(in_file.read())
os.utime(out_path,times=(mtime,mtime))
os.utime(out_path, times=(mtime, mtime))
# TODO: check for newer times
# TODO: what about if a file is deleted...
# updated everything, now mark as updated and reload scripts
bpy.context.preferences.addons['cam'].preferences.just_updated=True
bpy.context.preferences.addons['cam'].preferences.just_updated = True
bpy.context.preferences.addons['cam'].preferences.new_version_available = ""
bpy.ops.wm.save_userpref()
# unload ourself from python module system
delete_list=[]
delete_list = []
for m in sys.modules.keys():
if m.startswith("cam.") or m=='cam':
if m.startswith("cam.") or m == 'cam':
delete_list.append(m)
for d in delete_list:
del sys.modules[d]
bpy.ops.script.reload()


class UpdateSourceOperator(bpy.types.Operator):
bl_idname = "render.cam_set_update_source"
bl_label = "Set blendercam update source"

new_source: bpy.props.StringProperty(default='')
def execute(self,context):
bpy.context.preferences.addons['cam'].preferences.update_source=self.new_source

def execute(self, context):
bpy.context.preferences.addons['cam'].preferences.update_source = self.new_source
bpy.ops.wm.save_userpref()
return {'FINISHED'}
Loading

0 comments on commit 0ad061a

Please sign in to comment.