Skip to content

Commit

Permalink
Open file from launch arg
Browse files Browse the repository at this point in the history
  • Loading branch information
NiceneNerd committed May 28, 2020
1 parent 1977fbc commit 0015b98
Show file tree
Hide file tree
Showing 8 changed files with 172 additions and 68 deletions.
113 changes: 86 additions & 27 deletions wildbits/__main__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from json import dumps
from pathlib import Path
from platform import system
from sys import argv
from typing import Union
from zlib import crc32

Expand All @@ -23,18 +25,46 @@ class Api:
def browse(self) -> Union[str, None]:
result = self.window.create_file_dialog(webview.OPEN_DIALOG)
if result:
return result[0]
return result if isinstance(result, str) else result[0]
else:
return None

def handle_file(self):
if len(argv) == 1:
return
try:
file = Path(argv[1])
assert file.exists()
except (ValueError, AssertionError, FileNotFoundError):
return
tab = ""
if file.suffix in botw.extensions.SARC_EXTS:
res = self.open_sarc_file(file)
self.window.evaluate_js(
f"window.openSarc({dumps(res, ensure_ascii=False)});"
)
tab = "sarc"
elif file.suffix in {".srsizetable", ".rsizetable"}:
res = self.open_rstb_file(file)
self.window.evaluate_js(
f"window.openRstb({dumps(res, ensure_ascii=False)});"
)
tab = "rstb"
elif file.suffix in (
botw.extensions.BYML_EXTS | botw.extensions.AAMP_EXTS | {".msbt"}
):
res = self.open_yaml_file(file)
self.window.evaluate_js(
f"window.openYaml({dumps(res, ensure_ascii=False)});"
)
tab = "yaml"
if tab:
self.window.evaluate_js(f"window.setTab('{tab}')")

###############
# SARC Editor #
###############
def open_sarc(self) -> dict:
result = self.browse()
if not result:
return {}
file = Path(result)
def open_sarc_file(self, file: Path):
try:
self._open_sarc, tree, modded = _sarc.open_sarc(file)
except (ValueError, RuntimeError, oead.InvalidDataError):
Expand All @@ -46,6 +76,13 @@ def open_sarc(self) -> dict:
"be": self._open_sarc.get_endianness() == oead.Endianness.Big,
}

def open_sarc(self) -> dict:
result = self.browse()
if not result:
return {}
file = Path(result)
return self.open_sarc_file(file)

def create_sarc(self, be: bool, alignment: int) -> dict:
tmp_sarc = oead.SarcWriter(
oead.Endianness.Big if be else oead.Endianness.Little,
Expand All @@ -63,7 +100,7 @@ def save_sarc(self, path: str = "") -> dict:
if not path:
result = self.window.create_file_dialog(webview.SAVE_DIALOG)
if result:
path = result[0]
path = result if isinstance(result, str) else result[0]
else:
return {"error": "Cancelled"}
path = Path(path)
Expand All @@ -83,7 +120,7 @@ def extract_sarc_file(self, file: str) -> dict:
webview.SAVE_DIALOG, save_filename=filename
)
if output:
out = Path(output[0])
out = Path(output if isinstance(output, str) else output[0])
try:
out.write_bytes(
_sarc.get_nested_file_data(self._open_sarc, file, unyaz=False)
Expand Down Expand Up @@ -133,7 +170,9 @@ def update_sarc_folder(self) -> dict:
return {}
try:
self._open_sarc, tree, modded = _sarc.open_sarc(
_sarc.update_from_folder(self._open_sarc, Path(result[0]))
_sarc.update_from_folder(
self._open_sarc, Path(result if isinstance(result) else result[0])
)
)
except (FileNotFoundError, OSError, ValueError) as e:
return {"error": str(e)}
Expand All @@ -144,10 +183,11 @@ def extract_sarc(self):
if not result:
return {}
try:
output = Path(result[0])
output = Path(result if isinstance(result, str) else result[0])
for file in self._open_sarc.get_files():
(output / file.name).parent.mkdir(parents=True, exist_ok=True)
(output / file.name).write_bytes(file.data)
name = file.name if not file.name.startswith("/") else file.name[1:]
(output / name).parent.mkdir(parents=True, exist_ok=True)
(output / name).write_bytes(file.data)
except (FileNotFoundError, OSError) as e:
return {"error": str(e)}
return {}
Expand All @@ -169,11 +209,7 @@ def get_sarc_yaml(self, path: str) -> dict:
###############
# RSTB Editor #
###############
def open_rstb(self) -> dict:
result = self.browse()
if not result:
return {}
file = Path(result)
def open_rstb_file(self, file: Path) -> dict:
try:
self._open_rstb, self._open_rstb_be = _rstb.open_rstb(file)
except (ValueError, IndexError) as e:
Expand All @@ -187,6 +223,13 @@ def open_rstb(self) -> dict:
"be": self._open_rstb_be,
}

def open_rstb(self) -> dict:
result = self.browse()
if not result:
return {}
file = Path(result)
return self.open_rstb_file(file)

def browse_file_size(self) -> dict:
result = self.browse()
if not result:
Expand Down Expand Up @@ -216,7 +259,7 @@ def save_rstb(self, path: str = "") -> dict:
file_types=tuple(["RSTB File (*.rsizetable; *.srsizetable)"]),
)
if result:
path = result[0]
path = result if isinstance(result, str) else result[0]
else:
return {"error": "Cancelled"}
path = Path(path)
Expand All @@ -233,19 +276,17 @@ def export_rstb(self) -> dict:
if not result:
return {}
try:
_rstb.rstb_to_json(self._open_rstb, Path(result[0]))
_rstb.rstb_to_json(
self._open_rstb, Path(result if isinstance(result, str) else result[0])
)
except Exception as e:
return {"error": str(e)}
return {}

###############
# YAML Editor #
###############
def open_yaml(self) -> dict:
result = self.browse()
if not result:
return {}
file = Path(result)
def open_yaml_file(self, file: Path) -> dict:
try:
opened = _yaml.open_yaml(file)
except ValueError:
Expand All @@ -258,11 +299,18 @@ def open_yaml(self) -> dict:
"type": opened["type"],
}

def open_yaml(self) -> dict:
result = self.browse()
if not result:
return {}
file = Path(result)
return self.open_yaml_file(file)

def save_yaml(self, yaml: str, obj_type: str, be: bool, path: str) -> dict:
if not path:
result = self.window.create_file_dialog(webview.SAVE_DIALOG)
if result:
path = result[0]
path = result if isinstance(result, str) else result[0]
else:
return {"error": "Cancelled"}
try:
Expand Down Expand Up @@ -290,12 +338,23 @@ def main():
gui: str = ""
if system() == "Windows":
try:
# fmt: off
from cefpython3 import cefpython

del cefpython
gui = "cef"
# fmt: on
except ImportError:
pass
webview.start(debug=True, http_server=True, gui=gui)
elif system() == "Linux":
try:
# fmt: off
from PyQt5 import QtWebEngine
del QtWebEngine
gui = "qt"
# fmt: on
except ImportError:
gui = "gtk"
webview.start(debug=True, http_server=gui == "", gui=gui, func=api.handle_file)


if __name__ == "__main__":
Expand Down
28 changes: 25 additions & 3 deletions wildbits/_sarc.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@
from . import util


def fix_slash(func):
def fixed_func(*args, **kwargs):
return func(args[0], args[1].replace("\\/", "/"), *args[2:], **kwargs)

return fixed_func


def open_sarc(sarc: Union[Path, Sarc]) -> (Sarc, dict, list):
if isinstance(sarc, Path):
data = util.unyaz_if_yazd(sarc.read_bytes())
Expand Down Expand Up @@ -37,7 +44,7 @@ def get_sarc_tree(parent_sarc: Sarc) -> (dict, list):
)
if util.get_hashtable(
parent_sarc.get_endianness() == Endianness.Big
).is_file_modded(file.name, bytes(file.data)):
).is_file_modded(file.name.replace(".s", "."), bytes(file.data)):
modded.add(file.name)
return tree, modded

Expand All @@ -48,10 +55,12 @@ def get_sarc_tree(parent_sarc: Sarc) -> (dict, list):


@lru_cache(10)
@fix_slash
def get_nested_file(sarc: Sarc, file: str):
if file.endswith("/"):
file = file[0:-1]
return get_parent_sarc(sarc, file).get_file(file.split("//")[-1])
parent = get_parent_sarc(sarc, file)
return parent.get_file(file.split("//")[-1])


@lru_cache(10)
Expand All @@ -61,6 +70,7 @@ def get_nested_file_data(sarc: Sarc, file: str, unyaz: bool = True) -> bytes:


@lru_cache(32)
@fix_slash
def get_nested_file_meta(sarc: Sarc, file: str, wiiu: bool) -> {}:
if file.endswith("/"):
file = file[0:-1]
Expand All @@ -71,7 +81,9 @@ def get_nested_file_meta(sarc: Sarc, file: str, wiiu: bool) -> {}:
"rstb": util.get_rstb_value(filename, data, wiiu),
"modified": util.get_hashtable(wiiu).is_file_modded(
file.split("//")[-1].replace(".s", "."), data
),
)
if ".ssarc//" not in file
else False,
"size": len(data),
"is_yaml": (
Path(filename).suffix
Expand All @@ -81,6 +93,7 @@ def get_nested_file_meta(sarc: Sarc, file: str, wiiu: bool) -> {}:


@lru_cache(8)
@fix_slash
def get_parent_sarc(root_sarc: Sarc, file: str) -> Sarc:
if file.endswith("/"):
file = file[0:-1]
Expand All @@ -100,6 +113,7 @@ def get_parent_sarc(root_sarc: Sarc, file: str) -> Sarc:
return parent


@fix_slash
def delete_file(root_sarc: Sarc, file: str) -> Sarc:
if file.endswith("/"):
file = file[0:-1]
Expand All @@ -110,6 +124,8 @@ def delete_file(root_sarc: Sarc, file: str) -> Sarc:
while root_sarc != parent:
_, child = new_sarc.write()
file = file[0 : file.rindex("//")]
if file.endswith("/"):
file = file[:-1]
parent = get_parent_sarc(root_sarc, file)
new_sarc = SarcWriter.from_sarc(parent)
ext = file[file.rindex(".") :]
Expand All @@ -119,6 +135,7 @@ def delete_file(root_sarc: Sarc, file: str) -> Sarc:
return Sarc(new_sarc.write()[1])


@fix_slash
def rename_file(root_sarc: Sarc, file: str, new_name: str) -> Sarc:
if file.endswith("/"):
file = file[0:-1]
Expand All @@ -134,6 +151,8 @@ def rename_file(root_sarc: Sarc, file: str, new_name: str) -> Sarc:
while root_sarc != parent:
_, child = new_sarc.write()
file = file[0 : file.rindex("//")]
if file.endswith("/"):
file = file[:-1]
parent = get_parent_sarc(root_sarc, file)
new_sarc = SarcWriter.from_sarc(parent)
ext = file[file.rindex(".") :]
Expand All @@ -143,6 +162,7 @@ def rename_file(root_sarc: Sarc, file: str, new_name: str) -> Sarc:
return Sarc(new_sarc.write()[1])


@fix_slash
def add_file(root_sarc: Sarc, file: str, data: memoryview) -> Sarc:
if file.endswith("/"):
file = file[0:-1]
Expand All @@ -154,6 +174,8 @@ def add_file(root_sarc: Sarc, file: str, data: memoryview) -> Sarc:
while root_sarc != parent:
_, child = new_sarc.write()
file = file[0 : file.rindex("//")]
if file.endswith("/"):
file = file[:-1]
parent = get_parent_sarc(root_sarc, file)
new_sarc = SarcWriter.from_sarc(parent)
ext = file[file.rindex(".") :]
Expand Down
2 changes: 1 addition & 1 deletion wildbits/_yaml.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def get_sarc_yaml(file) -> dict:
obj_type = "msbt"
else:
if file.data[0:4] == b"Yaz0":
data = oead.yaz0.decompress(file.data)
file.data = oead.yaz0.decompress(file.data)
if file.data[0:4] == b"AAMP":
obj = oead.aamp.ParameterIO.from_binary(file.data)
be = False
Expand Down
Loading

0 comments on commit 0015b98

Please sign in to comment.