# AUTOGENERATED! DO NOT EDIT! File to edit: notebooks/00_core.ipynb (unless otherwise specified).

__all__ = ['demo_code', 'hw_cairo', 'surface_to_npy', 'surface_to_PIL', 'display_surface', 'RepeatedTimer']

# Cell
def demo_code():
    return 'demo'

# Cell
import cairocffi as cairo
from IPython.display import Image, display, clear_output

def hw_cairo(text):
    """ Write text as an angled line on a cairo ImageSurface and save to example.png, then display it."""
    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 300, 200)
    context = cairo.Context(surface)
    with context:
        context.set_source_rgb(1, 1, 1)  # White
        context.paint()
    # Restore the default source which is black.
    context.move_to(90, 140)
    context.rotate(-0.5)
    context.set_font_size(20)
    context.show_text(text)
    surface.write_to_png('outputs/hello_world_example.png')
    display(Image('outputs/hello_world_example.png'))

# Cell
import numpy as np
import PIL
def surface_to_npy(surface):
    """ Cairo ImageSurface to numpy array for inline display"""
    buf = surface.get_data()
    im = np.frombuffer(buf, dtype=np.uint8)
    h = surface.get_height()
    w = surface.get_width()
    im = np.reshape(im, [h, w, 4])
    # swap axis to get r-g-b-alpha
    im = im[:, :, [2, 1, 0, 3]]
    return im

# Cell
def surface_to_PIL(surface):
    return PIL.Image.fromarray(surface_to_npy(surface))

def display_surface(surface):
    clear_output()
    display(surface_to_PIL(surface))

# Cell
from threading import Timer
class RepeatedTimer(object):
    def __init__(self, interval, function, *args, **kwargs):
        self._timer     = None
        self.interval   = interval
        self.function   = function
        self.args       = args
        self.kwargs     = kwargs
        self.is_running = False
        self.start()

    def _run(self):
        self.is_running = False
        self.start()
        self.function(*self.args, **self.kwargs)

    def start(self):
        if not self.is_running:
            self._timer = Timer(self.interval, self._run)
            self._timer.start()
            self.is_running = True

    def stop(self):
        self._timer.cancel()
        self.is_running = False