Newer
Older
Import / research / match3 / windowing.h
//  C/C++ API for Mac OS X Windowing - windowing.h
//  Created by John Ryland (jryland@xiaofrog.com), 29/10/2017
//  Copyright (c) 2017 InvertedLogic
//  All rights reserved.
#pragma once
#include <stdint.h>
#include "canvas.h"

class Application
{
public:
  Application();
  int run();
  virtual void onStart() = 0;
};

class Window
{
public:
  Window() { buffer.w = buffer.h = 0; }
  ~Window();
  void create(int w, int h);
  int getWidth() { return buffer.w; }
  int getHeight() { return buffer.h; }
  virtual void onDraw(int x1, int y1, int x2, int y2) = 0;
  virtual void onResize(int w, int h);
  virtual void onMouseEvent(int x, int y, int buttons) {}
  void refresh();
  void flush();
protected:
  void* window;
  void* view;
  Image buffer;
};

class CanvasWindow : public Window
{
public:
  CanvasWindow() : Window()
  {
    delay = 33000; // 33ms -> 30 fps
    pthread_create(&thread, NULL, refreshThread, this);
  }
  void onDraw(int x1, int y1, int x2, int y2)
  {
    drawn = true;
    drawCanvas(buffer, canvas);
  }
  void setFrameRate(int a_fps)
  {
    delay = 1000000 / a_fps;
  }
  bool drawn;
  uint32_t delay;
protected:
  Canvas canvas;
private:
  pthread_t thread;
  static void *refreshThread(void *arg)
  {
    CanvasWindow* win = (CanvasWindow*)arg;
    win->drawn = false;
    while (true) {
      usleep(win->delay);
      if (win->drawn)
        win->refresh();
    }
  }
};