Skip to content
This repository has been archived by the owner on Nov 6, 2022. It is now read-only.

Commit

Permalink
Add ability to instance new RSI, editorconfig.
Browse files Browse the repository at this point in the history
  • Loading branch information
PJB3005 committed Jul 3, 2018
1 parent 9e65259 commit e7085f6
Show file tree
Hide file tree
Showing 4 changed files with 68 additions and 7 deletions.
5 changes: 5 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
[*.py]
insert_final_newline = true
indent_size = 4
indent_style = 4
trim_trailing_whitespace = true
4 changes: 4 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
#!/usr/bin/env python3
from rsi.__main__ import main

exit(main())
40 changes: 40 additions & 0 deletions rsi/__main__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import argparse
from pathlib import Path
from typing import Optional
from rsi import Rsi


Expand All @@ -14,16 +15,55 @@ def main() -> int:
_from_dmi.add_argument("input", help="The DMI file to read from.", type=Path)
_from_dmi.add_argument("output", help="The RSI to output to.", type=Path)

_new_rsi = subparser.add_parser("new", help="Will create a new RSI at the provided directory.")
_new_rsi.add_argument("rsi", help="The location of the new RSI. Must not exist yet.", type=Path)
_new_rsi.add_argument("dimensions", help="The dimensions of the new rsi, in <width>x<height> format, like so: 32x32.")
_new_rsi.add_argument("-c", "--copyright", action="store", help="Copyright info for this RSI file such as author.", nargs="?")
_new_rsi.add_argument("-l", "--license", action="store", help="The license of this RSI file, as valid SPDX License Identifier (Google it).", nargs="?")
_new_rsi.add_argument("--dont-make-parent-dirs", action="store_true", help="Do not create parent directories if they do not exist, instead throw an error.", dest="no_parents")

args = parser.parse_args()

if args.command == "from_dmi":
from_dmi(args.input, args.output)
return 0

if args.command == "new":
return new_rsi(args.rsi, args.dimensions, args.copyright, args.license, not args.no_parents)

print("No command specified!")
return 1


def from_dmi(inputf: Path, output: Path) -> None:
rsi = Rsi.from_dmi(inputf)
rsi.write(output)


def new_rsi(loc: Path,
dimensions: str,
rsi_copyright: Optional[str],
rsi_license: Optional[str],
make_parents: bool) -> int:
try:
dimsplit = dimensions.split("x")
if len(dimsplit) != 2:
print("Incorrect amount of dimensions passed, expected exactly 2.")
return 1
x = int(dimsplit[0])
y = int(dimsplit[1])

except ValueError:
print("Invalid dimensions passed.")
return 1

if not loc.parent.exists() and not make_parents:
print("Parent directories do not exist. Aborting.")
return 1

rsi = Rsi((x, y))
rsi.license = rsi_license
rsi.copyright = rsi_copyright
rsi.write(loc, make_parents)

return 0
26 changes: 19 additions & 7 deletions rsi/rsi.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import json
import math
from pathlib import Path
from typing import Dict, Tuple, Union, cast, TextIO, Any, List, TypeVar, Type
from typing import Dict, Tuple, Union, cast, TextIO, Any, List, Type, Optional
from PIL import Image
from .direction import Direction
from .helpers import state_name
from .state import State

T = TypeVar("T")
RSI_LATEST_COMPATIBLE = 1


Expand All @@ -16,6 +15,8 @@ def __init__(self, size: Tuple[int, int]) -> None:
# Keys are the same as the name on disk (name+flag+flag+flag...)
self.states = {} # type: Dict[str, State]
self.size = size # type: Tuple[int, int]
self.license = None # type: Optional[str]
self.copyright = None # type: Optional[str]

def get_state(self, name: str, selectors: List[str] = None) -> State:
return self.states.get(state_name(name, selectors))
Expand All @@ -28,7 +29,7 @@ def new_state(self, directions: int, name: str, selectors: List[str] = None) ->
self.set_state(newstate, name, selectors)
return newstate

def write(self, path: Union[str, Path]) -> None:
def write(self, path: Union[str, Path], make_parent_dirs: bool = True) -> None:
if isinstance(path, str):
path = Path(path)

Expand All @@ -38,13 +39,18 @@ def write(self, path: Union[str, Path]) -> None:
raise IOError("Attempted to write RSI to a non-directory.")

else:
path.mkdir()
path.mkdir(parents=make_parent_dirs)

# Write metadata json file.
metapath = path.joinpath("meta.json") # type: Path
metajson = {} # type: Dict[str, Any]
metajson["version"] = RSI_LATEST_COMPATIBLE
metajson["size"] = {"x": self.size[0], "y": self.size[1]}
if self.license is not None:
metajson["license"] = self.license

if self.copyright is not None:
metajson["copyright"] = self.copyright

states = [] # type: List[Dict[str, Any]]
for state in self.states.values():
Expand All @@ -54,7 +60,7 @@ def write(self, path: Union[str, Path]) -> None:
statedict["flags"] = state.flags
statedict["directions"] = state.directions
statedict["delays"] = state.delays
# Non-standard, but removed after the sort so the sort can use it.
# Non-standard, but removed after the sort so the sort can use it while sorting.
statedict["fullname"] = state.full_name

states.append(statedict)
Expand Down Expand Up @@ -101,7 +107,7 @@ def write(self, path: Union[str, Path]) -> None:
image.save(pngpath, "PNG")

@classmethod
def open(cls: Type[T], path: Union[str, Path]) -> "Rsi":
def open(cls, path: Union[str, Path]) -> "Rsi":
if isinstance(path, str):
path = Path(path)

Expand All @@ -114,6 +120,12 @@ def open(cls: Type[T], path: Union[str, Path]) -> "Rsi":

rsi = Rsi((meta["size"]["x"], meta["size"]["y"])) # type: Rsi

if "copyright" in meta:
rsi.copyright = meta["copyright"]

if "license" in meta:
rsi.license = meta["license"]

for state in meta["states"]:
newstate = rsi.new_state(
state["directions"], state["name"], state["select"]) # type: State
Expand Down Expand Up @@ -147,7 +159,7 @@ def open(cls: Type[T], path: Union[str, Path]) -> "Rsi":
return rsi

@classmethod
def from_dmi(cls: Type[T], path: Union[str, Path]) -> "Rsi":
def from_dmi(cls, path: Union[str, Path]) -> "Rsi":
try:
from byond.DMI import DMI
except ImportError:
Expand Down

0 comments on commit e7085f6

Please sign in to comment.