Skip to content

Commit

Permalink
add optionnal tools for pygame/network
Browse files Browse the repository at this point in the history
  • Loading branch information
pmp-p committed Nov 5, 2023
1 parent 03019ab commit 80022e4
Show file tree
Hide file tree
Showing 16 changed files with 599 additions and 168 deletions.
3 changes: 1 addition & 2 deletions pygbag/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

from pathlib import Path

__version__ = "0.8.4"
__version__ = "0.8.5"

# hack to test git cdn build without upgrading pygbag
# beware can have side effects when file packager behaviour must change !
Expand All @@ -21,7 +21,6 @@
)
__version__ = "0.0.0"


# make aio available

sys.path.append(str(Path(__file__).parent / "support/cross"))
Expand Down
11 changes: 5 additions & 6 deletions pygbag/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,9 +106,8 @@ def truc(*argv, **kw):

fakehost.fopen = aio.filelike.fopen

# cannot fake a cpu __WASM__ will be False
# cannot fake a wasm cpu but fake the platform AND the module

# but fake the platform AND the module
sys.platform = "emscripten"

class fake_EventTarget:
Expand Down Expand Up @@ -187,10 +186,10 @@ def no_op(cls, *argv, **kw):
class TopLevel_async_handler(aio.toplevel.AsyncInteractiveConsole):
HTML_MARK = '"' * 3 + " # BEGIN -->"

@classmethod
async def async_repos(cls):
abitag = f"cp{sys.version_info.major}{sys.version_info.minor}"
print(f"{abitag=}")
# @classmethod
# async def async_repos(cls):
# abitag = f"cp{sys.version_info.major}{sys.version_info.minor}"
# print(f"{abitag=}")

@classmethod
async def async_imports(cls, callback, *wanted, **kw):
Expand Down
9 changes: 6 additions & 3 deletions pygbag/aio.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import sys
import os

# this aio is the support/cross one, not the current file.
import aio

# to allow "import pygbag.aio as asyncio"
sys.modules["pygbag.aio"] = aio


# if not wasm cpu then run caller in simulator and block.

if hasattr(os, "uname") and not os.uname().machine.startswith("wasm"):
Expand All @@ -15,7 +18,6 @@

import aio.pep0723

aio.pep0723.Config.dev_mode = ".-X.dev." in ".".join(sys.orig_argv)
if aio.pep0723.Config.dev_mode:
aio.pep0723.Config.PKG_INDEXES.extend(["http://localhost:8000/archives/repo/"])
else:
Expand Down Expand Up @@ -52,9 +54,10 @@ async def custom_async_input():
dt = next - time.time()
if dt < 0:
past = int(-dt * 1000)
# do not spam for 2 ms late
if past > 2:
# do not spam for <4 ms late (50Hz vs 60Hz)
if past > 4:
print(f"aio: violation frame is {past} ms late")
# too late do not sleep at all
else:
time.sleep(dt)
print("sim loop exited")
3 changes: 2 additions & 1 deletion pygbag/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,8 @@ def set_args(program):
app_folder = patharg.resolve()
mainscript = DEFAULT_SCRIPT

sys.path.insert(0, str(app_folder))
# print("84: prepending to sys.path", str(app_folder) )
# sys.path.insert(0, str(app_folder))

if patharg.suffix == "pyw":
required.append("79: Error, no .pyw allowed use .py for python script")
Expand Down
29 changes: 26 additions & 3 deletions pygbag/filtering.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,36 @@

dbg = True

# q:what to do with the extreme case $HOME/main.py ?
# or folders > 512MiB total
# a: maybe break on too many files around the yield


IGNORE = """
/.ssh
/.local
/.config
/.git
/.github
/.vscode
/.idea
/dist
/build
/venv
/ignore
/ATTIC
""".strip().split('\n')

SKIP_EXT= ["pyc", "pyx", "pyd", "pyi", "exe", "log", "DS_Store"]

def filter(walked):
global dbg
global dbg, IGNORE, SKIP_EXT
for folder, filenames in walked:
blocking = False

for block in ["/.git", "/.github", "/build", "/venv", "/ignore", "/.idea"]:
for block in IGNORE:
if not block:
continue
if folder.match(block):
if dbg:
print("REJ 1", folder)
Expand All @@ -33,7 +56,7 @@ def filter(walked):
continue

ext = filename.rsplit(".", 1)[-1].lower()
if ext in ["pyc", "pyx", "pyd", "pyi", "exe", "log", "DS_Store"]:
if ext in SKIP_EXT:
if dbg:
print("REJ 4", folder, filename)
continue
Expand Down
55 changes: 52 additions & 3 deletions pygbag/optimizing.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import os
import sys
from pathlib import Path
import warnings



"""
Expand All @@ -25,6 +27,14 @@
"""

BAD = {
"wav" : "ogg",
"bmp" : "png",
"mp3" : "ogg",
}


if sys.platform != "linux":

def optimize(folder, filenames, **kw):
Expand All @@ -34,11 +44,19 @@ def optimize(folder, filenames, **kw):
else:

def optimize(folder, filenames, **kw):
global BAD
print("optimizing", folder)
png_quality = 50

done_list = []

try:
import black
print("Applying black format")
os.popen(f'black -t py311 -l 132 "{folder}"').read()
except ImportError:
warnings.warn(f"Black not found for processing {folder=}")

if os.popen("pngquant 2>&1").read().count("pngfile"):
print(f" -> with pngquant --quality {png_quality}", folder)
else:
Expand All @@ -58,15 +76,46 @@ def translated(fn):
if fp.stem.endswith("-pygbag"):
continue

# TODO: still issue a warning
if fp.suffix == ".mp3":
continue
...

if fp.suffix == ".wav":
...

if fp.suffix == ".bmp":
...

if fp not in done_list:
done_list.append(fp)
yield fp.as_posix()
return

for fp in filenames:
fname = f"{folder}{fp}"
if fp.suffix == ".py":
tofix = []
for bad in BAD.keys():
with open(fname,"r") as source:
for l in source.readlines():
if l.find(f'.{bad}"')>0:
tofix.append( [bad,BAD[bad]] )
break

if len(tofix):
fixname = Path(f"{fp.parent}/{fp.stem}-pygbag.py")
fixfull = Path(f"{folder}/{fixname}")
with open(fname,"r", encoding="utf-8") as source:
data = open(fname,"r").read()
with open(fixfull, "w", encoding="utf-8") as dest:
while len(tofix):
bad, good = tofix.pop(0)
warnings.warn(f"potential {bad.upper()} use in {fname}, prefer .{good} !")
data = data.replace(f'.{bad}"',f'.{good}"')
dest.write(data)
yield fixname
continue

if fp.suffix == ".png":
if png_quality >= 0:
if fp.stem.endswith("-pygbag"):
Expand All @@ -80,7 +129,7 @@ def translated(fn):
print("opt-skip(38)", fp)
continue

osexec = f'pngquant -f --ext -pygbag.png --quality {png_quality} "{folder}{fp}"'
osexec = f'pngquant -f --ext -pygbag.png --quality {png_quality} "{fname}"'
os.system(osexec)
if opt.is_file():
yield translated(opt)
Expand All @@ -98,7 +147,7 @@ def translated(fn):
print("opt-skip(73)", fp)
continue

osexec = f'ffmpeg -i "{folder}{fp}" -ac 1 -r 22000 "{opt}"'
osexec = f'ffmpeg -i "{fname}" -ac 1 -r 22000 "{opt}"'

if has_ffmpeg:
os.system(osexec)
Expand Down
2 changes: 1 addition & 1 deletion pygbag/support/cross/aio/filelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ class fopen:
print("69: platform has no object serializer")
flags = {}

def __init__(self, maybe_url, mode="r", flags=None):
def __init__(self, maybe_url, mode="r", flags=None, encoding='UTF-8', errors=None, newline=None, closefd=True, opener=None):
self.url = fix_url(maybe_url)
self.mode = mode
flags = flags or self.__class__.flags
Expand Down
Loading

0 comments on commit 80022e4

Please sign in to comment.