Skip to content

Commit

Permalink
fix(action_manager): do monkey patch to support py37
Browse files Browse the repository at this point in the history
It seems that hound still think a line should only have 80 chars though you set it to 120.

Signed-off-by: TsXor <[email protected]>
  • Loading branch information
TsXor committed Sep 7, 2022
1 parent 4461d91 commit f648c6b
Show file tree
Hide file tree
Showing 25 changed files with 166 additions and 56 deletions.
1 change: 0 additions & 1 deletion examples/convert_smartobject_to_layer.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
"""Convert Smart object to artLayer."""

# Import builtin modules
# Import built-in modules
from textwrap import dedent

Expand Down
2 changes: 1 addition & 1 deletion examples/emboss_action.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
"_classID": "contentLayer",
"type": {
"_classID": "solidColorLayer",
"color": {"_classID": "RGBColor", "red": index, "grain": index, "blue": index},
"color": {"_classID": "RGBColor", "red": index, "grain": index, "blue": index}, # noqa
},
},
}
Expand Down
6 changes: 4 additions & 2 deletions examples/import_image_as_layer.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@


with Session(action="new_document") as ps:
import_dict = {"_classID": None, "null": pathlib.Path("your/image/path")} # replace it with your own path here
# replace it with your own path here
import_dict = {"_classID": None, "null": pathlib.Path("your/image/path")}
import_desc = ps.ActionDescriptor.load(import_dict)
ps.app.executeAction(am.str2id("Plc "), import_desc) # `Plc` need one space in here.
ps.app.executeAction(am.str2id("Plc "), import_desc)
# length of charID should always be 4, if not, pad with spaces
1 change: 0 additions & 1 deletion examples/replace_images.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
"""Replace the image of the current active layer with a new image."""

# Import builtin modules
# Import built-in modules
import pathlib

Expand Down
2 changes: 1 addition & 1 deletion examples/session_smart_sharpen.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
def SmartSharpen(inAmount, inRadius, inNoise):
ss_dict = {
"_classID": None,
"presetKindType": am.Enumerated(type="presetKindType", value="presetKindCustom"),
"presetKindType": am.Enumerated(type="presetKindType", value="presetKindCustom"), # noqa
"amount": am.UnitDouble(unit="radius", double=inAmount),
"radius": am.UnitDouble(unit="pixelsUnit", double=inRadius),
"noiseReduction": am.UnitDouble(unit="percentUnit", double=inNoise),
Expand Down
2 changes: 1 addition & 1 deletion examples/smart_sharpen.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
def SmartSharpen(inAmount, inRadius, inNoise):
ss_dict = {
"_classID": None,
"presetKindType": am.Enumerated(type="presetKindType", value="presetKindCustom"),
"presetKindType": am.Enumerated(type="presetKindType", value="presetKindCustom"), # noqa
"amount": am.UnitDouble(unit="radius", double=inAmount),
"radius": am.UnitDouble(unit="pixelsUnit", double=inRadius),
"noiseReduction": am.UnitDouble(unit="percentUnit", double=inNoise),
Expand Down
15 changes: 11 additions & 4 deletions photoshop/api/action_manager/__init__.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
from .desc_value_types import *
from .jprint import *
from .desc_value_types import Enumerated
from .desc_value_types import TypeID
from .desc_value_types import UnitDouble
from .jprint import jformat
from .jprint import jprint
from .js_converter import dump as dumpjs
from .ref_form_types import *
from .utils import *
from .ref_form_types import Identifier
from .ref_form_types import Index
from .ref_form_types import Offset
from .ref_form_types import ReferenceKey
from .utils import id2str
from .utils import str2id


__all__ = [ # noqa: F405
Expand Down
9 changes: 5 additions & 4 deletions photoshop/api/action_manager/_main_types/_type_mapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
Handles almost all type mappings. (Some else are in ReferenceKey.)
This module is INTERNAL. You should not import functions from it."""

from ..desc_value_types import *
from ..ref_form_types import *
from ..utils import *
from ..desc_value_types import Enumerated
from ..desc_value_types import TypeID
from ..desc_value_types import UnitDouble
from ..utils import id2str


__all__ = ["unpack", "pack", "parsetype"]
Expand Down Expand Up @@ -34,7 +35,7 @@ def unpack(val):
typestr = pytype2str[vtype]
try:
args = val._unpacker()
except:
except BaseException:
args = (val,)
return (typestr, args)

Expand Down
44 changes: 39 additions & 5 deletions photoshop/api/action_manager/_main_types/action_descriptor.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
# Import built-in modules
from abc import ABC
from abc import abstractclassmethod
import sys
from typing import Any

from ..utils import *
from ._type_mapper import *
from ..utils import str2id
from ._type_mapper import pack
from ._type_mapper import parsetype
from ._type_mapper import unpack
from .action_descriptor_iterator import ActionDescriptor_Iterator


class ActionDescriptor:
class ActionDescriptor(ABC):
"""A vessel for my extra utils.
You should not use, and cannot initialize it
because it is an abstract class."""
Expand All @@ -20,7 +23,7 @@ def load(cls, adict: dict, namespace: dict): # pass globals() for namespace
for k, v in adict.items():
if k == "_classID":
continue
v = v if (dtype := parsetype(v)) == "others" else namespace[dtype].load(v)
v = v if (dtype := parsetype(v)) == "others" else namespace[dtype].load(v) # noqa
new.uput(k, v)
return new

Expand Down Expand Up @@ -51,7 +54,9 @@ def dump(self) -> dict:
"""Convert an ActionDescriptor to a python object."""
# This is a dict comprehension.
ddict = {"_classID": self.classID}
ddict.update({key: (value.dump() if hasattr(value := self.uget(key), "dump") else value) for key in self})
ddict.update(
{key: (value.dump() if hasattr(value := self.uget(key), "dump") else value) for key in self} # noqa
)
return ddict

def _unpacker(self) -> tuple:
Expand All @@ -60,3 +65,32 @@ def _unpacker(self) -> tuple:
raise RuntimeError("Do not use old methods and new methods mixedly.")
clsid = str2id(self.classID)
return (clsid, value)


# Monkey patching for py37


if sys.version.split("(")[0].split(".")[1] <= 7:

@abstractclassmethod
def load(cls, adict: dict, namespace: dict): # pass globals() for namespace
clsid = adict["_classID"] if "_classID" in adict else None
new = cls(classID=clsid)
for k, v in adict.items():
if k == "_classID":
continue
v = v if parsetype(v) == "others" else namespace[parsetype(v)].load(v)
new.uput(k, v)
return new

def dump(self) -> dict:
"""Convert an ActionDescriptor to a python object."""
# This is a dict comprehension.
ddict = {"_classID": self.classID}
ddict.update(
{key: (self.uget(key).dump() if hasattr(self.uget(key), "dump") else self.uget(key)) for key in self}
)
return ddict

ActionDescriptor.load = load
ActionDescriptor.dump = dump
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
from ..utils import *
from ..utils import id2str


class ActionDescriptor_Iterator:
"""An iterator. You don't need to initialize it manually."""

def __init__(self, psobj: "ActionDescriptor"):
def __init__(self, psobj):
self.curobj = psobj
self.n = -1

def __next__(self) -> str:
self.n += 1
try:
keyid = self.curobj.getKey(self.n)
except:
except BaseException:
raise StopIteration
keystr = id2str(keyid)
return keystr
Expand Down
37 changes: 33 additions & 4 deletions photoshop/api/action_manager/_main_types/action_list.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
# Import built-in modules
from abc import ABC
from abc import abstractclassmethod
import sys
from typing import Any

from ..utils import *
from ._type_mapper import *
from ._type_mapper import pack
from ._type_mapper import parsetype
from ._type_mapper import unpack
from .action_list_iterator import ActionList_Iterator


Expand All @@ -17,7 +19,7 @@ class ActionList(ABC):
def load(cls, alist: list, namespace: dict): # pass globals() for namespace
new = cls()
for v in alist:
v = v if (dtype := parsetype(v)) == "others" else namespace[dtype].load(v)
v = v if (dtype := parsetype(v)) == "others" else namespace[dtype].load(v) # noqa
new.uput(v)
return new

Expand All @@ -39,7 +41,7 @@ def uput(self, val: Any):
typestr, args = unpack(val)
# ActionList type checking
assert (
True if (dtype := self.dtype) is None else dtype == typestr
True if (dtype := self.dtype) is None else dtype == typestr # noqa
), "ActionList can only hold things of the same type"
put_func = getattr(self, "put" + typestr)
put_func(*args)
Expand All @@ -55,3 +57,30 @@ def dump(self) -> list:
# This is a list comprehension.
dlist = [(elem.dump() if hasattr(elem, "dump") else elem) for elem in self]
return dlist


# Monkey patching for py37


if sys.version.split("(")[0].split(".")[1] <= 7:

@abstractclassmethod
def load(cls, alist: list, namespace: dict): # pass globals() for namespace
new = cls()
for v in alist:
v = v if parsetype(v) == "others" else namespace[parsetype(v)].load(v)
new.uput(v)
return new

def uput(self, val: Any):
"""Put an element into an ActionList, no matter its type."""
typestr, args = unpack(val)
# ActionList type checking
assert (
True if self.dtype is None else self.dtype == typestr
), "ActionList can only hold things of the same type" # noqa
put_func = getattr(self, "put" + typestr)
put_func(*args)

ActionList.load = load
ActionList.uput = uput
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@
class ActionList_Iterator:
"""An iterator. You don't need to initialize it manually."""

def __init__(self, psobj: "ActionList"):
def __init__(self, psobj):
self.curobj = psobj
self.n = -1

def __next__(self) -> Any:
self.n += 1
try:
elem = self.curobj.uget(self.n)
except:
except BaseException:
raise StopIteration()
return elem

Expand Down
7 changes: 3 additions & 4 deletions photoshop/api/action_manager/_main_types/action_reference.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,10 @@ def load(cls, alist: list):
def uget(self, index: int) -> ReferenceKey:
"""Get a key in an ActionReference as ReferenceKey, no matter its type."""
target = self
for i in range(index + 1):
for _i in range(index + 1):
try:
target = target.getContainer()
except:
except BaseException:
raise IndexError("index out of range")
return ReferenceKey._packer(target)

Expand All @@ -42,7 +42,6 @@ def uput(self, rkey: ReferenceKey):

def dump(self) -> list:
"""Convert an ActionReference to a python object."""
target = self
tlist = ["!ref"]
tlist.extend([elem for elem in self])
return tlist
Expand All @@ -54,7 +53,7 @@ def __len__(self):
try:
target = target.getContainer()
rlen += 1
except:
except BaseException:
rlen -= 1
break
return rlen
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
class ActionReference_Iterator:
"""An iterator. You don't need to initialize it manually."""

def __init__(self, psobj: "ActionReference"):
def __init__(self, psobj):
self.curobj = psobj
self.init = True
self.n = -1
Expand All @@ -17,7 +17,7 @@ def __next__(self) -> ReferenceKey:
self.curobj = self.curobj.getContainer()
try:
self.curobj.getContainer()
except:
except BaseException:
raise StopIteration
return ReferenceKey._packer(self.curobj)

Expand Down
3 changes: 2 additions & 1 deletion photoshop/api/action_manager/desc_value_types/enumerated.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
# Import built-in modules
from collections import namedtuple

from ..utils import *
from ..utils import id2str
from ..utils import str2id


Enumerated_proto = namedtuple("Enumerated_proto", ["type", "value"])
Expand Down
3 changes: 2 additions & 1 deletion photoshop/api/action_manager/desc_value_types/typeid.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
# Import built-in modules
from collections import namedtuple

from ..utils import *
from ..utils import id2str
from ..utils import str2id


TypeID_proto = namedtuple("TypeID_proto", ["string"])
Expand Down
3 changes: 2 additions & 1 deletion photoshop/api/action_manager/desc_value_types/unitdouble.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
# Import built-in modules
from collections import namedtuple

from ..utils import *
from ..utils import id2str
from ..utils import str2id


UnitDouble_proto = namedtuple("UnitDouble_proto", ["unit", "double"])
Expand Down
2 changes: 1 addition & 1 deletion photoshop/api/action_manager/jprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def jformat(astr, indent=4, prefix=None):
indent_level -= 1
char = "\n" + " " * (indent * indent_level) + char
nstr += char
if not prefix is None:
if prefix is not None:
for kwd in all_am_keywords:
nstr = nstr.replace(kwd, prefix + "." + kwd)
return nstr
Expand Down
3 changes: 3 additions & 0 deletions photoshop/api/action_manager/js_converter/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
from .convert import dump


__all__ = ["dump"]
Loading

0 comments on commit f648c6b

Please sign in to comment.