diff --git a/examples/convert_smartobject_to_layer.py b/examples/convert_smartobject_to_layer.py index 5ff63957..7d81f6ab 100644 --- a/examples/convert_smartobject_to_layer.py +++ b/examples/convert_smartobject_to_layer.py @@ -1,6 +1,5 @@ """Convert Smart object to artLayer.""" -# Import builtin modules # Import built-in modules from textwrap import dedent diff --git a/examples/emboss_action.py b/examples/emboss_action.py index 9fa08d92..2dbc7626 100644 --- a/examples/emboss_action.py +++ b/examples/emboss_action.py @@ -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 }, }, } diff --git a/examples/import_image_as_layer.py b/examples/import_image_as_layer.py index 41eab47f..45468a73 100644 --- a/examples/import_image_as_layer.py +++ b/examples/import_image_as_layer.py @@ -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 diff --git a/examples/replace_images.py b/examples/replace_images.py index 9ccf9952..cec73ad0 100644 --- a/examples/replace_images.py +++ b/examples/replace_images.py @@ -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 diff --git a/examples/session_smart_sharpen.py b/examples/session_smart_sharpen.py index 974d16af..9e89cef8 100644 --- a/examples/session_smart_sharpen.py +++ b/examples/session_smart_sharpen.py @@ -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), diff --git a/examples/smart_sharpen.py b/examples/smart_sharpen.py index c23d554a..d92a158a 100644 --- a/examples/smart_sharpen.py +++ b/examples/smart_sharpen.py @@ -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), diff --git a/photoshop/api/action_manager/__init__.py b/photoshop/api/action_manager/__init__.py index a579d1e8..b9ab3d35 100644 --- a/photoshop/api/action_manager/__init__.py +++ b/photoshop/api/action_manager/__init__.py @@ -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 diff --git a/photoshop/api/action_manager/_main_types/_type_mapper.py b/photoshop/api/action_manager/_main_types/_type_mapper.py index 06f5b88c..37016520 100644 --- a/photoshop/api/action_manager/_main_types/_type_mapper.py +++ b/photoshop/api/action_manager/_main_types/_type_mapper.py @@ -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"] @@ -34,7 +35,7 @@ def unpack(val): typestr = pytype2str[vtype] try: args = val._unpacker() - except: + except BaseException: args = (val,) return (typestr, args) diff --git a/photoshop/api/action_manager/_main_types/action_descriptor.py b/photoshop/api/action_manager/_main_types/action_descriptor.py index 70256db8..2bac93e1 100644 --- a/photoshop/api/action_manager/_main_types/action_descriptor.py +++ b/photoshop/api/action_manager/_main_types/action_descriptor.py @@ -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.""" @@ -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 @@ -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: @@ -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 diff --git a/photoshop/api/action_manager/_main_types/action_descriptor_iterator.py b/photoshop/api/action_manager/_main_types/action_descriptor_iterator.py index 066a8069..e2ee3303 100644 --- a/photoshop/api/action_manager/_main_types/action_descriptor_iterator.py +++ b/photoshop/api/action_manager/_main_types/action_descriptor_iterator.py @@ -1,10 +1,10 @@ -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 @@ -12,7 +12,7 @@ def __next__(self) -> str: self.n += 1 try: keyid = self.curobj.getKey(self.n) - except: + except BaseException: raise StopIteration keystr = id2str(keyid) return keystr diff --git a/photoshop/api/action_manager/_main_types/action_list.py b/photoshop/api/action_manager/_main_types/action_list.py index 5d719bf8..8e206d33 100644 --- a/photoshop/api/action_manager/_main_types/action_list.py +++ b/photoshop/api/action_manager/_main_types/action_list.py @@ -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 @@ -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 @@ -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) @@ -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 diff --git a/photoshop/api/action_manager/_main_types/action_list_iterator.py b/photoshop/api/action_manager/_main_types/action_list_iterator.py index 9de7e352..b269ea56 100644 --- a/photoshop/api/action_manager/_main_types/action_list_iterator.py +++ b/photoshop/api/action_manager/_main_types/action_list_iterator.py @@ -5,7 +5,7 @@ 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 @@ -13,7 +13,7 @@ def __next__(self) -> Any: self.n += 1 try: elem = self.curobj.uget(self.n) - except: + except BaseException: raise StopIteration() return elem diff --git a/photoshop/api/action_manager/_main_types/action_reference.py b/photoshop/api/action_manager/_main_types/action_reference.py index 75f57680..d551ba1d 100644 --- a/photoshop/api/action_manager/_main_types/action_reference.py +++ b/photoshop/api/action_manager/_main_types/action_reference.py @@ -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) @@ -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 @@ -54,7 +53,7 @@ def __len__(self): try: target = target.getContainer() rlen += 1 - except: + except BaseException: rlen -= 1 break return rlen diff --git a/photoshop/api/action_manager/_main_types/action_reference_iterator.py b/photoshop/api/action_manager/_main_types/action_reference_iterator.py index 6eb6e8d9..2f93ac29 100644 --- a/photoshop/api/action_manager/_main_types/action_reference_iterator.py +++ b/photoshop/api/action_manager/_main_types/action_reference_iterator.py @@ -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 @@ -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) diff --git a/photoshop/api/action_manager/desc_value_types/enumerated.py b/photoshop/api/action_manager/desc_value_types/enumerated.py index bc97b00a..97607b2e 100644 --- a/photoshop/api/action_manager/desc_value_types/enumerated.py +++ b/photoshop/api/action_manager/desc_value_types/enumerated.py @@ -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"]) diff --git a/photoshop/api/action_manager/desc_value_types/typeid.py b/photoshop/api/action_manager/desc_value_types/typeid.py index 2897f352..0fc10a19 100644 --- a/photoshop/api/action_manager/desc_value_types/typeid.py +++ b/photoshop/api/action_manager/desc_value_types/typeid.py @@ -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"]) diff --git a/photoshop/api/action_manager/desc_value_types/unitdouble.py b/photoshop/api/action_manager/desc_value_types/unitdouble.py index 83b734bd..0d0ee5a9 100644 --- a/photoshop/api/action_manager/desc_value_types/unitdouble.py +++ b/photoshop/api/action_manager/desc_value_types/unitdouble.py @@ -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"]) diff --git a/photoshop/api/action_manager/jprint.py b/photoshop/api/action_manager/jprint.py index 56e2d72f..fe1daf4f 100644 --- a/photoshop/api/action_manager/jprint.py +++ b/photoshop/api/action_manager/jprint.py @@ -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 diff --git a/photoshop/api/action_manager/js_converter/__init__.py b/photoshop/api/action_manager/js_converter/__init__.py index 2d29a8f1..b12651f5 100644 --- a/photoshop/api/action_manager/js_converter/__init__.py +++ b/photoshop/api/action_manager/js_converter/__init__.py @@ -1 +1,4 @@ from .convert import dump + + +__all__ = ["dump"] diff --git a/photoshop/api/action_manager/js_converter/convert.py b/photoshop/api/action_manager/js_converter/convert.py index cfe671c7..65ef748b 100644 --- a/photoshop/api/action_manager/js_converter/convert.py +++ b/photoshop/api/action_manager/js_converter/convert.py @@ -5,13 +5,17 @@ # Import built-in modules import json - -from ..desc_value_types import * -from ..ref_form_types import * -from ..utils import hash2str +import sys + +from ..desc_value_types import Enumerated +from ..desc_value_types import TypeID +from ..desc_value_types import UnitDouble +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 str2hash -from ..utils import str2id from .injection_js import injection from .node_execjs import execjs @@ -49,7 +53,7 @@ def unhead(string): str2refgetpacker = { "default": lambda x: ReferenceKey(unhead(x["DesiredClass"]), unhead(x["Value"])), "Enumerated": lambda x: ReferenceKey( - unhead(x["DesiredClass"]), Enumerated(unhead(x["Value"]["enumtype"]), unhead(x["Value"]["enumval"])) + unhead(x["DesiredClass"]), Enumerated(unhead(x["Value"]["enumtype"]), unhead(x["Value"]["enumval"])) # noqa ), "Identifier": lambda x: ReferenceKey(unhead(x["DesiredClass"]), Identifier + int(x["Value"])), "Index": lambda x: ReferenceKey(unhead(x["DesiredClass"]), Index + int(x["Value"])), @@ -59,7 +63,7 @@ def unhead(string): def parsedict(tdict): - if not "_classID" in tdict: + if "_classID" not in tdict: tdict["_classID"] = None else: tdict["_classID"] = unhead(tdict["_classID"]) @@ -79,13 +83,38 @@ def parseref(tdict): plist = ["!ref"] plist.extend( [ - (str2refgetpacker[val["type"]](e) if type(val := e["Value"]) == dict else str2refgetpacker["default"](e)) + ( + str2refgetpacker[val["type"]](e) + if type(val := e["Value"]) == dict # noqa + else str2refgetpacker["default"](e) + ) for e in d2l ] ) return plist +# Monkey patching for py37 + + +if sys.version.split("(")[0].split(".")[1] <= 7: + + def parseref(tdict): # noqa + d2l = [tdict[str(i)] for i in range(tdict["len"])] + plist = ["!ref"] + plist.extend( + [ + ( + str2refgetpacker[e["Value"]["type"]](e) + if type(e["Value"]) == dict + else str2refgetpacker["default"](e) + ) + for e in d2l + ] + ) + return plist + + def json2obj(jsont): obj_init = json.loads(jsont) obj_desc = parsedict(obj_init["ActionDescriptor"]) if "ActionDescriptor" in obj_init else None diff --git a/photoshop/api/action_manager/js_converter/injection_js.py b/photoshop/api/action_manager/js_converter/injection_js.py index db14ad05..6d2c07a4 100644 --- a/photoshop/api/action_manager/js_converter/injection_js.py +++ b/photoshop/api/action_manager/js_converter/injection_js.py @@ -1,3 +1,5 @@ +# flake8: noqa + """Defines injection, a variable which contains js code. These js code implements Photoshop functions, and lures a piece of js code to output all its information on executing executeAction function. diff --git a/photoshop/api/action_manager/js_converter/node_execjs.py b/photoshop/api/action_manager/js_converter/node_execjs.py index 0604c6a8..a8789a49 100644 --- a/photoshop/api/action_manager/js_converter/node_execjs.py +++ b/photoshop/api/action_manager/js_converter/node_execjs.py @@ -8,7 +8,7 @@ # Node.js check nodestate = os.popen("node --version") -if not re.match("^v\d*\.\d*\.\d*", nodestate.read()): +if not re.match(r"^v\d*\.\d*\.\d*", nodestate.read()): raise RuntimeError("Please check if Node.js is installed to PATH!") diff --git a/photoshop/api/action_manager/ref_form_types/_marker.py b/photoshop/api/action_manager/ref_form_types/_marker.py index 50d60fec..5a0c20b2 100644 --- a/photoshop/api/action_manager/ref_form_types/_marker.py +++ b/photoshop/api/action_manager/ref_form_types/_marker.py @@ -16,5 +16,5 @@ def __repr__(self): def __eq__(self, other): try: return self.name == other.name and self.value == other.value - except: + except BaseException: return False diff --git a/photoshop/api/action_manager/ref_form_types/referencekey.py b/photoshop/api/action_manager/ref_form_types/referencekey.py index 955478b4..21ed10d9 100644 --- a/photoshop/api/action_manager/ref_form_types/referencekey.py +++ b/photoshop/api/action_manager/ref_form_types/referencekey.py @@ -9,11 +9,14 @@ from ..desc_value_types import Enumerated from ..desc_value_types import TypeID -from ..utils import * +from ..utils import id2str +from ..utils import str2id from ._marker import marker -from .identifier import Identifier -from .index import Index -from .offset import Offset + +# Identifier, Index, Offset are used by getting them in globals(). +from .identifier import Identifier # noqa: F401 +from .index import Index # noqa: F401 +from .offset import Offset # noqa: F401 psreftype2str = { @@ -31,12 +34,12 @@ def _packer(cls, obj): dcls = id2str(obj.getDesiredClass()) try: get_func = getattr(obj, "get" + ftype) - except: + except BaseException: get_func = None if ftype == "Class": v = None elif ftype == "Enumerated": - v = Enumerated(id2str(obj.getEnumeratedType()), id2str(obj.getEnumeratedValue())) + v = Enumerated(id2str(obj.getEnumeratedType()), id2str(obj.getEnumeratedValue())) # noqa elif ftype == "Property": v = TypeID(id2str(obj.getProperty())) elif ftype == "Name": diff --git a/photoshop/api/action_manager/utils.py b/photoshop/api/action_manager/utils.py index 293238e0..69464515 100644 --- a/photoshop/api/action_manager/utils.py +++ b/photoshop/api/action_manager/utils.py @@ -42,7 +42,7 @@ def str2id(psstr: str) -> str: typeid = str2hash(psstr) try: restr = converter.id2str(psstr) - except: + except BaseException: restr = "" if not restr: typeid = converter.str2id(psstr)