Skip to content

Instantly share code, notes, and snippets.

@dansanderson
Last active June 11, 2022 23:38
Show Gist options
  • Save dansanderson/3a2a2ff6c6287003d1de77432c4c1109 to your computer and use it in GitHub Desktop.
Save dansanderson/3a2a2ff6c6287003d1de77432c4c1109 to your computer and use it in GitHub Desktop.
Prints .lua.png files exported from PICO-8 on a DevTerm
# The PICO-8 text printer for the ClockworkPi DevTerm!
#
# This Python script allows you to print text directly from the PICO-8 source
# code editor. The script runs in the background and watches for you to execute
# the "EXPORT FILE.LUA.PNG" command. It does some light processing of the
# generated image file, then sends it to DevTerm's thermal printer.
#
# This is mostly just a joke/hack for the purposes of this tweet:
# https://twitter.com/dan_sanderson/status/1434253649266364417?s=20
#
# To set up DevTerm printing via CUPS:
# sudo apt -y install libcups2-dev
# git clone https://github.com/clockworkpi/DevTerm.git
# cd DevTerm/devterm_thermal_printer_cups
# make
# sudo make install
# lpoptions -d devterm_printer
#
# This script uses ImageMagick to convert the color Lua code listing to black and
# white. To install it:
# sudo apt install imagemagick
#
# This script needs Python Watchdog. To install it:
# pip3 install watchdog
#
# To run the watcher script:
# python3 p8_devterm_printwatcher.py
#
# To print code from a PICO-8 cart, within PICO-8, export the .lua.png file:
# EXPORT MYFILE.LUA.PNG
import os.path
import subprocess
import time
from watchdog.events import PatternMatchingEventHandler
from watchdog.observers import Observer
PICO8_CARTS_DIR = os.path.expanduser(
'~/.lexaloffle/pico-8/carts')
TMP_DIR = '/tmp'
IMAGEMAGICK_CONVERT_CMD = '/usr/bin/convert'
# Avoids double-triggering from how PICO-8 updates files
cooldown = {}
class Handler(PatternMatchingEventHandler):
@staticmethod
def on_modified(event):
if time.time() - cooldown.get(event.src_path, 0) < 2:
return
cooldown[event.src_path] = time.time()
if not event.src_path.endswith('.lua.png'):
return
tmp_name = os.path.join(TMP_DIR, os.path.basename(event.src_path))
print('Printing ' + event.src_path)
args = [
IMAGEMAGICK_CONVERT_CMD,
event.src_path,
'-fill', '#FFFFFF',
'-opaque', '#1D2B53',
'-threshold', '99%',
'-scale', '180%',
tmp_name
]
subprocess.run(args)
subprocess.run([
'lp',
'-o', 'scaling=0',
tmp_name
])
p = subprocess.Popen(['lp'], stdin=subprocess.PIPE)
p.stdin.write(b'\n\n\n\n\n\n\n\n')
p.communicate()
p.stdin.close()
if __name__ == "__main__":
event_handler = Handler(patterns=['*.lua.png'], ignore_directories=True)
observer = Observer()
observer.schedule(event_handler, PICO8_CARTS_DIR, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
finally:
observer.stop()
observer.join()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment