<commit_before>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 VBChunguk
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 * */

#include "stdafx.h"
#include "luanovel.h"
#include "core.h"
#include "text.h"
#include "render-engine.h"
#include "character.h"
#include "helper.h"

#define MAX_LOADSTRING 100
#define WINDOW_STYLE WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU

HINSTANCE hInst;
HWND ghWnd;
TCHAR szTitle[MAX_LOADSTRING];
TCHAR szWindowClass[MAX_LOADSTRING];
lua_State* L;
cairo_surface_t* mainsurface;

ATOM				MyRegisterClass(HINSTANCE hInstance);
BOOL				InitInstance(HINSTANCE, int);
LRESULT CALLBACK	WndProc(HWND, UINT, WPARAM, LPARAM);

int APIENTRY _tWinMain(_In_ HINSTANCE hInstance,
                     _In_opt_ HINSTANCE hPrevInstance,
                     _In_ LPTSTR    lpCmdLine,
                     _In_ int       nCmdShow)
{
	UNREFERENCED_PARAMETER(hPrevInstance);
	UNREFERENCED_PARAMETER(lpCmdLine);

	MSG msg;

	L = luaL_newstate();
	if (L == NULL) {
		// Not enough memory
		return 1;
	}

	// Load lua libraries
	luaopen_base(L);
	luaopen_coroutine(L);
	luaopen_package(L);
	luaopen_utf8(L);
	luaopen_string(L);
	luaopen_math(L);

	LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
	LoadString(hInstance, IDC_LUANOVEL, szWindowClass, MAX_LOADSTRING);
	MyRegisterClass(hInstance);

	// Initialize luanovel library functions
	lua_checkstack(L, 5);

	lua_newtable(L);
	lua_pushliteral(L, "system");
	lua_newtable(L);
	helper_lua_addNewFunction(L, "message", [](lua_State* L) {
		const char* message = lua_tostring(L, -1);
		if (message == NULL) return 0;
		lua_pop(L, 1);
		MessageBoxA(ghWnd, message, NULL, MB_OK);
		return 0;
	});
	lua_pushliteral(L, "outputmode");
	lua_pushliteral(L, "stdout");
	lua_rawset(L, -3);
	lua_pushliteral(L, "locale");
	lua_pushliteral(L, "ko-KR");
	lua_rawset(L, -3);
	lua_rawset(L, -3);

	lua_pushliteral(L, "text");
	lua_newtable(L);
	helper_lua_addNewFunction(L, "_interpret", &_lua_text_interpret);
	lua_rawset(L, -3);

	draw_initialize(L);
	character_initialize(L);

	lua_setglobal(L, "luanovel");

	luaL_dofile(L, "init.luac");
	luaL_dofile(L, "main.txt");

	if (!InitInstance(hInstance, nCmdShow))
	{
		lua_close(L);
		return FALSE;
	}

	lua_checkstack(L, 2);
	lua_getglobal(L, "luanovel");
	helper_lua_getTableContent(L, "on_init");
	int width, height;
	if (lua_isnil(L, -1)) {
		width = 800;
		height = 600;
	}
	else {
		lua_pcall(L, 0, 0, 0);

		lua_getglobal(L, "luanovel");
		lua_pushvalue(L, -1);
		helper_lua_getTableContent(L, "rendering.width");
		width = (int)lua_tonumber(L, -1);
		lua_pop(L, 1);
		helper_lua_getTableContent(L, "rendering.height");
		height = (int)lua_tonumber(L, -1);
		lua_pop(L, 1);
	}

	mainsurface = cairo_image_surface_create(CAIRO_FORMAT_RGB24, width, height);

	RECT rc = { 0, 0, width, height };
	AdjustWindowRect(&rc, WINDOW_STYLE, FALSE);
	SetWindowPos(ghWnd, NULL,
		-1, -1, rc.right - rc.left, rc.bottom - rc.top,
		SWP_NOMOVE | SWP_NOZORDER);

	while (true)
	{
		if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
			TranslateMessage(&msg);
			DispatchMessage(&msg);
			if (msg.message == WM_QUIT) break;
		}
		else {
			lua_checkstack(L, 3);
			lua_getglobal(L, "luanovel");
			if (lua_isnil(L, -1)) {
				lua_pop(L, 1);
				break;
			}

			helper_lua_getTableContent(L, "rendering.on_draw");
			if (lua_isnil(L, -1)) {
				lua_pop(L, 1);
				break;
			}

			cairo_t* cr = cairo_create(mainsurface);
			cairo_set_source_rgb(cr, 1, 1, 1);
			cairo_paint(cr);
			lua_pushlightuserdata(L, cr);
			lua_pushliteral(L, "test");
			lua_pcall(L, 2, 0, 0);
			cairo_destroy(cr);

			InvalidateRect(ghWnd, NULL, FALSE);
		}
	}

	cairo_surface_destroy(mainsurface);

	draw_cleanup();
	lua_close(L);
	return (int) msg.wParam;
}

ATOM MyRegisterClass(HINSTANCE hInstance)
{
	WNDCLASSEX wcex;

	wcex.cbSize = sizeof(WNDCLASSEX);

	wcex.style			= CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc	= WndProc;
	wcex.cbClsExtra		= 0;
	wcex.cbWndExtra		= 0;
	wcex.hInstance		= hInstance;
	wcex.hIcon			= LoadIcon(hInstance, MAKEINTRESOURCE(IDI_LUANOVEL));
	wcex.hCursor		= LoadCursor(NULL, IDC_ARROW);
	wcex.hbrBackground	= (HBRUSH)(COLOR_WINDOW+1);
	wcex.lpszMenuName	= NULL;
	wcex.lpszClassName	= szWindowClass;
	wcex.hIconSm		= LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));

	return RegisterClassEx(&wcex);
}

BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
   HWND hWnd;

   hInst = hInstance;

   hWnd = CreateWindow(szWindowClass, szTitle, WINDOW_STYLE,
      CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);

   if (!hWnd)
   {
      return FALSE;
   }

   ShowWindow(hWnd, nCmdShow);
   UpdateWindow(hWnd);
   ghWnd = hWnd;

   return TRUE;
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	HDC hdc;
	PAINTSTRUCT ps;

	switch (message)
	{
	case WM_SIZE:
	{
		break;
	}
	case WM_PAINT:
	{
		hdc = BeginPaint(hWnd, &ps);
		cairo_surface_t* surface = cairo_win32_surface_create(hdc);
		cairo_t* cr = cairo_create(surface);
		cairo_set_source_surface(cr, mainsurface, 0, 0);
		cairo_paint(cr);
		cairo_destroy(cr);
		cairo_surface_destroy(surface);
		EndPaint(hWnd, &ps);
		break;
	}
	case WM_DESTROY:
		PostQuitMessage(0);
		break;
	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
	}
	return 0;
}
<commit_msg>Run luanovel.system.on_step every step<commit_after>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 VBChunguk
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 * */

#include "stdafx.h"
#include "luanovel.h"
#include "core.h"
#include "text.h"
#include "render-engine.h"
#include "character.h"
#include "helper.h"

#define MAX_LOADSTRING 100
#define WINDOW_STYLE WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU

HINSTANCE hInst;
HWND ghWnd;
TCHAR szTitle[MAX_LOADSTRING];
TCHAR szWindowClass[MAX_LOADSTRING];
lua_State* L;
cairo_surface_t* mainsurface;

ATOM				MyRegisterClass(HINSTANCE hInstance);
BOOL				InitInstance(HINSTANCE, int);
LRESULT CALLBACK	WndProc(HWND, UINT, WPARAM, LPARAM);
void	CALLBACK	OnStep(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime);

int APIENTRY _tWinMain(_In_ HINSTANCE hInstance,
                     _In_opt_ HINSTANCE hPrevInstance,
                     _In_ LPTSTR    lpCmdLine,
                     _In_ int       nCmdShow)
{
	UNREFERENCED_PARAMETER(hPrevInstance);
	UNREFERENCED_PARAMETER(lpCmdLine);

	MSG msg;

	L = luaL_newstate();
	if (L == NULL) {
		// Not enough memory
		return 1;
	}

	// Load lua libraries
	luaopen_base(L);
	luaopen_coroutine(L);
	luaopen_package(L);
	luaopen_utf8(L);
	luaopen_string(L);
	luaopen_math(L);

	LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
	LoadString(hInstance, IDC_LUANOVEL, szWindowClass, MAX_LOADSTRING);
	MyRegisterClass(hInstance);

	// Initialize luanovel library functions
	lua_checkstack(L, 5);

	lua_newtable(L);
	lua_pushliteral(L, "system");
	lua_newtable(L);
	helper_lua_addNewFunction(L, "message", [](lua_State* L) {
		const char* message = lua_tostring(L, -1);
		if (message == NULL) return 0;
		lua_pop(L, 1);
		MessageBoxA(ghWnd, message, NULL, MB_OK);
		return 0;
	});
	lua_pushliteral(L, "outputmode");
	lua_pushliteral(L, "stdout");
	lua_rawset(L, -3);
	lua_pushliteral(L, "locale");
	lua_pushliteral(L, "ko-KR");
	lua_rawset(L, -3);
	lua_rawset(L, -3);

	lua_pushliteral(L, "text");
	lua_newtable(L);
	helper_lua_addNewFunction(L, "_interpret", &_lua_text_interpret);
	lua_rawset(L, -3);

	draw_initialize(L);
	character_initialize(L);

	lua_pushliteral(L, "status"); // this object is saved in savefile
	lua_newtable(L);
	lua_rawset(L, -3);

	lua_setglobal(L, "luanovel");

	luaL_dofile(L, "init.luac");
	luaL_dofile(L, "main.txt");

	if (!InitInstance(hInstance, nCmdShow))
	{
		lua_close(L);
		return FALSE;
	}

	lua_checkstack(L, 2);
	lua_getglobal(L, "luanovel");
	helper_lua_getTableContent(L, "system.on_init");
	int width = 800, height = 600;
	if (lua_isfunction(L, -1)) {
		lua_pcall(L, 0, 0, 0);

		lua_getglobal(L, "luanovel");
		lua_pushvalue(L, -1);
		helper_lua_getTableContent(L, "rendering.width");
		if (lua_isnumber(L, -1)) width = (int)lua_tonumber(L, -1);
		lua_pop(L, 1);
		helper_lua_getTableContent(L, "rendering.height");
		if (lua_isnumber(L, -1)) height = (int)lua_tonumber(L, -1);
		lua_pop(L, 1);
	}

	mainsurface = cairo_image_surface_create(CAIRO_FORMAT_RGB24, width, height);

	RECT rc = { 0, 0, width, height };
	AdjustWindowRect(&rc, WINDOW_STYLE, FALSE);
	SetWindowPos(ghWnd, NULL,
		-1, -1, rc.right - rc.left, rc.bottom - rc.top,
		SWP_NOMOVE | SWP_NOZORDER);

	SetTimer(ghWnd, 1, 16, &OnStep);
	while (true)
	{
		if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
			TranslateMessage(&msg);
			DispatchMessage(&msg);
			if (msg.message == WM_QUIT) break;
		}
		else {
			lua_checkstack(L, 3);
			lua_getglobal(L, "luanovel");
			if (!lua_istable(L, -1)) {
				lua_pop(L, 1);
				continue;
			}

			helper_lua_getTableContent(L, "rendering.on_draw");
			if (!lua_isfunction(L, -1)) {
				lua_pop(L, 1);
				continue;
			}

			cairo_t* cr = cairo_create(mainsurface);
			cairo_set_source_rgb(cr, 1, 1, 1);
			cairo_paint(cr);
			lua_pushlightuserdata(L, cr);
			lua_pushliteral(L, "test");
			lua_pcall(L, 2, 0, 0);
			cairo_destroy(cr);

			InvalidateRect(ghWnd, NULL, FALSE);
		}
	}
	KillTimer(ghWnd, 1);

	cairo_surface_destroy(mainsurface);

	draw_cleanup();
	lua_close(L);
	return (int) msg.wParam;
}

void CALLBACK OnStep(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime)
{
	lua_checkstack(L, 3);
	lua_getglobal(L, "luanovel");
	if (!lua_istable(L, -1)) {
		lua_pop(L, 1);
		return;
	}
	helper_lua_getTableContent(L, "system.on_step");
	if (!lua_isfunction(L, -1)) {
		lua_pop(L, 1);
		return;
	}
	lua_pushliteral(L, "test"); // phase
	lua_pcall(L, 1, 0, 0);

	// internal step function
	lua_getglobal(L, "luanovel");
	if (!lua_istable(L, -1)) {
		lua_pop(L, 1);
		return;
	}
	helper_lua_getTableContent(L, "system._on_step");
	if (!lua_isfunction(L, -1)) {
		lua_pop(L, 1);
		return;
	}
	lua_pushliteral(L, "test"); // phase
	lua_pcall(L, 1, 0, 0);
}

ATOM MyRegisterClass(HINSTANCE hInstance)
{
	WNDCLASSEX wcex;

	wcex.cbSize = sizeof(WNDCLASSEX);

	wcex.style			= CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc	= WndProc;
	wcex.cbClsExtra		= 0;
	wcex.cbWndExtra		= 0;
	wcex.hInstance		= hInstance;
	wcex.hIcon			= LoadIcon(hInstance, MAKEINTRESOURCE(IDI_LUANOVEL));
	wcex.hCursor		= LoadCursor(NULL, IDC_ARROW);
	wcex.hbrBackground	= (HBRUSH)(COLOR_WINDOW+1);
	wcex.lpszMenuName	= NULL;
	wcex.lpszClassName	= szWindowClass;
	wcex.hIconSm		= LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));

	return RegisterClassEx(&wcex);
}

BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
   HWND hWnd;

   hInst = hInstance;

   hWnd = CreateWindow(szWindowClass, szTitle, WINDOW_STYLE,
      CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);

   if (!hWnd)
   {
      return FALSE;
   }

   ShowWindow(hWnd, nCmdShow);
   UpdateWindow(hWnd);
   ghWnd = hWnd;

   return TRUE;
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	HDC hdc;
	PAINTSTRUCT ps;

	switch (message)
	{
	case WM_SIZE:
	{
		break;
	}
	case WM_PAINT:
	{
		hdc = BeginPaint(hWnd, &ps);
		cairo_surface_t* surface = cairo_win32_surface_create(hdc);
		cairo_t* cr = cairo_create(surface);
		cairo_set_source_surface(cr, mainsurface, 0, 0);
		cairo_paint(cr);
		cairo_destroy(cr);
		cairo_surface_destroy(surface);
		EndPaint(hWnd, &ps);
		break;
	}
	case WM_DESTROY:
		PostQuitMessage(0);
		break;
	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
	}
	return 0;
}
<|endoftext|>


<commit_before>// Aseprite FLIC Library
// Copyright (c) 2019 Igara Studio S.A.
// Copyright (c) 2015 David Capello
//
// This file is released under the terms of the MIT license.
// Read LICENSE.txt for more information.

#include "flic.h"
#include "flic_details.h"

#include <cassert>

namespace flic {

Decoder::Decoder(FileInterface* file)
  : m_file(file)
  , m_frameCount(0)
  , m_offsetFrame1(0)
  , m_offsetFrame2(0)
{
}

bool Decoder::readHeader(Header& header)
{
  read32(); // file size
  uint16_t magic = read16();

  assert(magic == FLI_MAGIC_NUMBER || magic == FLC_MAGIC_NUMBER);
  if (magic != FLI_MAGIC_NUMBER &&
      magic != FLC_MAGIC_NUMBER)
    return false;

  header.frames = read16();
  header.width  = read16();
  header.height = read16();
  read16();                     // Color depth (it is interpreted as 8bpp anyway)
  read16();                     // Skip flags
  header.speed = read32();
  if (magic == FLI_MAGIC_NUMBER) {
    if (header.speed == 0)
      header.speed = 70;
    else
      header.speed = 1000 * header.speed / 70;
  }

  if (magic == FLC_MAGIC_NUMBER) {
    // Offset to the first and second frame
    m_file->seek(80);
    m_offsetFrame1 = read32();
    m_offsetFrame2 = read32();
  }

  if (header.width == 0) header.width = 320;
  if (header.height == 0) header.width = 200;

  m_width = header.width;
  m_height = header.height;

  // Skip padding
  m_file->seek(128);
  return true;
}

bool Decoder::readFrame(Frame& frame)
{
  switch (m_frameCount) {
    case 0:
      if (m_offsetFrame1)
        m_file->seek(m_offsetFrame1);
      break;
    case 1:
      if (m_offsetFrame2)
        m_file->seek(m_offsetFrame2);
      break;
  }

  uint32_t frameStartPos = m_file->tell();
  uint32_t frameSize = read32();
  uint16_t magic = read16();
  assert(magic == FLI_FRAME_MAGIC_NUMBER);
  (void)magic;

  uint16_t chunks = read16();
  for (int i=0; i<8; ++i)       // Padding
    m_file->read8();

  for (uint16_t i=0; i!=chunks; ++i)
    readChunk(frame);

  m_file->seek(frameStartPos+frameSize);
  ++m_frameCount;
  return true;
}

void Decoder::readChunk(Frame& frame)
{
  uint32_t chunkStartPos = m_file->tell();
  uint32_t chunkSize = read32();
  uint16_t type = read16();

  switch (type) {
    case FLI_COLOR_256_CHUNK: readColorChunk(frame, false); break;
    case FLI_DELTA_CHUNK:     readDeltaChunk(frame);        break;
    case FLI_COLOR_64_CHUNK:  readColorChunk(frame, true);  break;
    case FLI_LC_CHUNK:        readLcChunk(frame);           break;
    case FLI_BLACK_CHUNK:     readBlackChunk(frame);        break;
    case FLI_BRUN_CHUNK:      readBrunChunk(frame);         break;
    case FLI_COPY_CHUNK:      readCopyChunk(frame);         break;
    default:
      // Ignore all other kind of chunks
      break;
  }

  m_file->seek(chunkStartPos+chunkSize);
}

void Decoder::readBlackChunk(Frame& frame)
{
  std::fill(frame.pixels,
            frame.pixels+frame.rowstride*m_height, 0);
}

void Decoder::readCopyChunk(Frame& frame)
{
  assert(m_width == 320 && m_height == 200);
  if (m_width == 320 && m_height == 200) {
    for (int y=0; y<200; ++y) {
      uint8_t* it = frame.pixels + y*frame.rowstride;
      for (int x=0; x<320; ++x, ++it)
        *it = m_file->read8();
    }
  }
}

void Decoder::readColorChunk(Frame& frame, bool oldColorChunk)
{
  int npackets = read16();

  // For each packet
  int i = 0;
  while (npackets--) {
    i += m_file->read8();       // Colors to skip

    int colors = m_file->read8();
    if (colors == 0)
      colors = 256;

    for (int j=0; j<colors; ++j) {
      Color& color = frame.colormap[i+j];
      color.r = m_file->read8();
      color.g = m_file->read8();
      color.b = m_file->read8();
      if (oldColorChunk) {
        color.r = 255 * int(color.r) / 63;
        color.g = 255 * int(color.g) / 63;
        color.b = 255 * int(color.b) / 63;
      }
    }
  }
}

void Decoder::readBrunChunk(Frame& frame)
{
  for (int y=0; y<m_height; ++y) {
    uint8_t* it = frame.pixels+frame.rowstride*y;
    int x = 0;
    m_file->read8(); // Ignore number of packets (we read until x == m_width)
    while (m_file->ok() && x < m_width) {
      int count = int(int8_t(m_file->read8()));
      if (count >= 0) {
        uint8_t color = m_file->read8();
        while (count-- != 0 && x < m_width) {
          *it = color;
          ++it;
          ++x;
        }
      }
      else {
        while (count++ != 0) {
          *it = m_file->read8();
          ++it;
          ++x;
        }
      }
    }
  }
}

void Decoder::readLcChunk(Frame& frame)
{
  int skipLines = read16();
  int nlines = read16();

  for (int y=skipLines; y<skipLines+nlines; ++y) {
    uint8_t* it = frame.pixels+frame.rowstride*y;
    int x = 0;
    int npackets = m_file->read8();
    while (npackets-- && x < m_width) {
      int skip = m_file->read8();

      x += skip;
      it += skip;

      int count = int(int8_t(m_file->read8()));
      if (count >= 0) {
        uint8_t* end = frame.pixels+frame.rowstride*m_height;
        while (count-- != 0 && it < end) {
          *it = m_file->read8();
          ++it;
          ++x;
        }
        // Broken file? More bytes than available buffer
        if (it == end)
          return;
      }
      else {
        uint8_t color = m_file->read8();
        while (count++ != 0 && x < m_width) {
          *it = color;
          ++it;
          ++x;
        }
      }
    }
  }
}

void Decoder::readDeltaChunk(Frame& frame)
{
  int nlines = read16();
  int y = 0;
  while (nlines-- != 0) {
    int npackets = 0;

    while (m_file->ok()) {
      int16_t word = read16();
      if (word < 0) {          // Has bit 15 (0x8000)
        if (word & 0x4000) {   // Has bit 14 (0x4000)
          y += -word;          // Skip lines
        }
        // Only last pixel has changed
        else {
          assert(y >= 0 && y < m_height);
          if (y >= 0 && y < m_height) {
            uint8_t* it = frame.pixels + y*frame.rowstride + m_width - 1;
            *it = (word & 0xff);
          }
          ++y;
          if (nlines-- == 0)
            goto done;
        }
      }
      else {
        npackets = word;
        break;
      }
    }

    int x = 0;
    while (npackets-- != 0) {
      x += m_file->read8();           // Skip pixels
      int8_t count = m_file->read8(); // Number of words

      assert(y >= 0 && y < m_height &&
             x >= 0 && x < m_width);
      uint8_t* it = frame.pixels + y*frame.rowstride + x;

      if (count >= 0) {
        while (count-- != 0 && x < m_width) {
          int color1 = m_file->read8();
          int color2 = m_file->read8();

          *it = color1;
          ++it;
          ++x;

          if (x < m_width) {
            *it = color2;
            ++it;
            ++x;
          }
        }
      }
      else {
        int color1 = m_file->read8();
        int color2 = m_file->read8();

        while (count++ != 0 && x < m_width) {
          *it = color1;
          ++it;
          ++x;

          if (x < m_width) {
            *it = color2;
            ++it;
            ++x;
          }
        }
      }
    }

    ++y;
  }
done:;
}

uint16_t Decoder::read16()
{
  int b1 = m_file->read8();
  int b2 = m_file->read8();

  if (m_file->ok()) {
    return ((b2 << 8) | b1); // Little endian
  }
  else
    return 0;
}

uint32_t Decoder::read32()
{
  int b1 = m_file->read8();
  int b2 = m_file->read8();
  int b3 = m_file->read8();
  int b4 = m_file->read8();

  if (m_file->ok()) {
    // Little endian
    return ((b4 << 24) | (b3 << 16) | (b2 << 8) | b1);
  }
  else
    return 0;
}

} // namespace flic
<commit_msg>Fix buffer overflow with invalid color chunks<commit_after>// Aseprite FLIC Library
// Copyright (c) 2019 Igara Studio S.A.
// Copyright (c) 2015 David Capello
//
// This file is released under the terms of the MIT license.
// Read LICENSE.txt for more information.

#include "flic.h"
#include "flic_details.h"

#include <cassert>

namespace flic {

Decoder::Decoder(FileInterface* file)
  : m_file(file)
  , m_frameCount(0)
  , m_offsetFrame1(0)
  , m_offsetFrame2(0)
{
}

bool Decoder::readHeader(Header& header)
{
  read32(); // file size
  uint16_t magic = read16();

  assert(magic == FLI_MAGIC_NUMBER || magic == FLC_MAGIC_NUMBER);
  if (magic != FLI_MAGIC_NUMBER &&
      magic != FLC_MAGIC_NUMBER)
    return false;

  header.frames = read16();
  header.width  = read16();
  header.height = read16();
  read16();                     // Color depth (it is interpreted as 8bpp anyway)
  read16();                     // Skip flags
  header.speed = read32();
  if (magic == FLI_MAGIC_NUMBER) {
    if (header.speed == 0)
      header.speed = 70;
    else
      header.speed = 1000 * header.speed / 70;
  }

  if (magic == FLC_MAGIC_NUMBER) {
    // Offset to the first and second frame
    m_file->seek(80);
    m_offsetFrame1 = read32();
    m_offsetFrame2 = read32();
  }

  if (header.width == 0) header.width = 320;
  if (header.height == 0) header.width = 200;

  m_width = header.width;
  m_height = header.height;

  // Skip padding
  m_file->seek(128);
  return true;
}

bool Decoder::readFrame(Frame& frame)
{
  switch (m_frameCount) {
    case 0:
      if (m_offsetFrame1)
        m_file->seek(m_offsetFrame1);
      break;
    case 1:
      if (m_offsetFrame2)
        m_file->seek(m_offsetFrame2);
      break;
  }

  uint32_t frameStartPos = m_file->tell();
  uint32_t frameSize = read32();
  uint16_t magic = read16();
  assert(magic == FLI_FRAME_MAGIC_NUMBER);
  (void)magic;

  uint16_t chunks = read16();
  for (int i=0; i<8; ++i)       // Padding
    m_file->read8();

  for (uint16_t i=0; i!=chunks; ++i)
    readChunk(frame);

  m_file->seek(frameStartPos+frameSize);
  ++m_frameCount;
  return true;
}

void Decoder::readChunk(Frame& frame)
{
  uint32_t chunkStartPos = m_file->tell();
  uint32_t chunkSize = read32();
  uint16_t type = read16();

  switch (type) {
    case FLI_COLOR_256_CHUNK: readColorChunk(frame, false); break;
    case FLI_DELTA_CHUNK:     readDeltaChunk(frame);        break;
    case FLI_COLOR_64_CHUNK:  readColorChunk(frame, true);  break;
    case FLI_LC_CHUNK:        readLcChunk(frame);           break;
    case FLI_BLACK_CHUNK:     readBlackChunk(frame);        break;
    case FLI_BRUN_CHUNK:      readBrunChunk(frame);         break;
    case FLI_COPY_CHUNK:      readCopyChunk(frame);         break;
    default:
      // Ignore all other kind of chunks
      break;
  }

  m_file->seek(chunkStartPos+chunkSize);
}

void Decoder::readBlackChunk(Frame& frame)
{
  std::fill(frame.pixels,
            frame.pixels+frame.rowstride*m_height, 0);
}

void Decoder::readCopyChunk(Frame& frame)
{
  assert(m_width == 320 && m_height == 200);
  if (m_width == 320 && m_height == 200) {
    for (int y=0; y<200; ++y) {
      uint8_t* it = frame.pixels + y*frame.rowstride;
      for (int x=0; x<320; ++x, ++it)
        *it = m_file->read8();
    }
  }
}

void Decoder::readColorChunk(Frame& frame, bool oldColorChunk)
{
  int npackets = read16();

  // For each packet
  int i = 0;
  while (npackets--) {
    i += m_file->read8();       // Colors to skip

    int colors = m_file->read8();
    if (colors == 0)
      colors = 256;

    for (int j=0; j<colors
           // If i+j >= 256 it means that the color chunk is invalid,
           // we check this to avoid an buffer overflow of frame.colormap[]
           && i+j < 256;
         ++j) {
      Color& color = frame.colormap[i+j];
      color.r = m_file->read8();
      color.g = m_file->read8();
      color.b = m_file->read8();
      if (oldColorChunk) {
        color.r = 255 * int(color.r) / 63;
        color.g = 255 * int(color.g) / 63;
        color.b = 255 * int(color.b) / 63;
      }
    }
  }
}

void Decoder::readBrunChunk(Frame& frame)
{
  for (int y=0; y<m_height; ++y) {
    uint8_t* it = frame.pixels+frame.rowstride*y;
    int x = 0;
    m_file->read8(); // Ignore number of packets (we read until x == m_width)
    while (m_file->ok() && x < m_width) {
      int count = int(int8_t(m_file->read8()));
      if (count >= 0) {
        uint8_t color = m_file->read8();
        while (count-- != 0 && x < m_width) {
          *it = color;
          ++it;
          ++x;
        }
      }
      else {
        while (count++ != 0) {
          *it = m_file->read8();
          ++it;
          ++x;
        }
      }
    }
  }
}

void Decoder::readLcChunk(Frame& frame)
{
  int skipLines = read16();
  int nlines = read16();

  for (int y=skipLines; y<skipLines+nlines; ++y) {
    uint8_t* it = frame.pixels+frame.rowstride*y;
    int x = 0;
    int npackets = m_file->read8();
    while (npackets-- && x < m_width) {
      int skip = m_file->read8();

      x += skip;
      it += skip;

      int count = int(int8_t(m_file->read8()));
      if (count >= 0) {
        uint8_t* end = frame.pixels+frame.rowstride*m_height;
        while (count-- != 0 && it < end) {
          *it = m_file->read8();
          ++it;
          ++x;
        }
        // Broken file? More bytes than available buffer
        if (it == end)
          return;
      }
      else {
        uint8_t color = m_file->read8();
        while (count++ != 0 && x < m_width) {
          *it = color;
          ++it;
          ++x;
        }
      }
    }
  }
}

void Decoder::readDeltaChunk(Frame& frame)
{
  int nlines = read16();
  int y = 0;
  while (nlines-- != 0) {
    int npackets = 0;

    while (m_file->ok()) {
      int16_t word = read16();
      if (word < 0) {          // Has bit 15 (0x8000)
        if (word & 0x4000) {   // Has bit 14 (0x4000)
          y += -word;          // Skip lines
        }
        // Only last pixel has changed
        else {
          assert(y >= 0 && y < m_height);
          if (y >= 0 && y < m_height) {
            uint8_t* it = frame.pixels + y*frame.rowstride + m_width - 1;
            *it = (word & 0xff);
          }
          ++y;
          if (nlines-- == 0)
            goto done;
        }
      }
      else {
        npackets = word;
        break;
      }
    }

    int x = 0;
    while (npackets-- != 0) {
      x += m_file->read8();           // Skip pixels
      int8_t count = m_file->read8(); // Number of words

      assert(y >= 0 && y < m_height &&
             x >= 0 && x < m_width);
      uint8_t* it = frame.pixels + y*frame.rowstride + x;

      if (count >= 0) {
        while (count-- != 0 && x < m_width) {
          int color1 = m_file->read8();
          int color2 = m_file->read8();

          *it = color1;
          ++it;
          ++x;

          if (x < m_width) {
            *it = color2;
            ++it;
            ++x;
          }
        }
      }
      else {
        int color1 = m_file->read8();
        int color2 = m_file->read8();

        while (count++ != 0 && x < m_width) {
          *it = color1;
          ++it;
          ++x;

          if (x < m_width) {
            *it = color2;
            ++it;
            ++x;
          }
        }
      }
    }

    ++y;
  }
done:;
}

uint16_t Decoder::read16()
{
  int b1 = m_file->read8();
  int b2 = m_file->read8();

  if (m_file->ok()) {
    return ((b2 << 8) | b1); // Little endian
  }
  else
    return 0;
}

uint32_t Decoder::read32()
{
  int b1 = m_file->read8();
  int b2 = m_file->read8();
  int b3 = m_file->read8();
  int b4 = m_file->read8();

  if (m_file->ok()) {
    // Little endian
    return ((b4 << 24) | (b3 << 16) | (b2 << 8) | b1);
  }
  else
    return 0;
}

} // namespace flic
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "update_engine/dbus_service.h"

#include <string>

#include <base/logging.h>

#include "update_engine/marshal.glibmarshal.h"
#include "update_engine/omaha_request_params.h"
#include "update_engine/utils.h"

using std::string;

static const char kAUTestURLRequest[] = "autest";
static const char kAUTestURL[] =
    "https://omaha.corp.google.com:8082/service/update2";

G_DEFINE_TYPE(UpdateEngineService, update_engine_service, G_TYPE_OBJECT)

static void update_engine_service_finalize(GObject* object) {
  G_OBJECT_CLASS(update_engine_service_parent_class)->finalize(object);
}

static guint status_update_signal = 0;

static void update_engine_service_class_init(UpdateEngineServiceClass* klass) {
  GObjectClass *object_class;
  object_class = G_OBJECT_CLASS(klass);
  object_class->finalize = update_engine_service_finalize;

  status_update_signal = g_signal_new(
      "status_update",
      G_OBJECT_CLASS_TYPE(klass),
      G_SIGNAL_RUN_LAST,
      0,  // 0 == no class method associated
      NULL,  // Accumulator
      NULL,  // Accumulator data
      update_engine_VOID__INT64_DOUBLE_STRING_STRING_INT64,
      G_TYPE_NONE,  // Return type
      5,  // param count:
      G_TYPE_INT64,
      G_TYPE_DOUBLE,
      G_TYPE_STRING,
      G_TYPE_STRING,
      G_TYPE_INT64);
}

static void update_engine_service_init(UpdateEngineService* object) {
}

UpdateEngineService* update_engine_service_new(void) {
  return reinterpret_cast<UpdateEngineService*>(
      g_object_new(UPDATE_ENGINE_TYPE_SERVICE, NULL));
}

gboolean update_engine_service_attempt_update(UpdateEngineService* self,
                                              gchar* app_version,
                                              gchar* omaha_url,
                                              GError **error) {
  string update_app_version;
  string update_omaha_url;
  // Only non-official (e.g., dev and test) builds can override the current
  // version and update server URL over D-Bus. However, pointing to the
  // hardcoded test update server URL is always allowed.
  if (!chromeos_update_engine::utils::IsOfficialBuild()) {
    if (app_version) {
      update_app_version = app_version;
    }
    if (omaha_url) {
      update_omaha_url = omaha_url;
    }
  }
  if (omaha_url && strcmp(omaha_url, kAUTestURLRequest) == 0) {
    update_omaha_url = kAUTestURL;
  }
  LOG(INFO) << "Attempt update: app_version=\"" << update_app_version << "\" "
            << "omaha_url=\"" << update_omaha_url << "\"";
  self->update_attempter_->CheckForUpdate(update_app_version, update_omaha_url);
  return TRUE;
}

gboolean update_engine_service_get_status(UpdateEngineService* self,
                                          int64_t* last_checked_time,
                                          double* progress,
                                          gchar** current_operation,
                                          gchar** new_version,
                                          int64_t* new_size,
                                          GError **error) {
  string current_op;
  string new_version_str;

  CHECK(self->update_attempter_->GetStatus(last_checked_time,
                                           progress,
                                           &current_op,
                                           &new_version_str,
                                           new_size));

  *current_operation = g_strdup(current_op.c_str());
  *new_version = g_strdup(new_version_str.c_str());
  if (!(*current_operation && *new_version)) {
    *error = NULL;
    return FALSE;
  }
  return TRUE;
}

gboolean update_engine_service_get_track(UpdateEngineService* self,
                                         gchar** track,
                                         GError **error) {
  string track_str =
      chromeos_update_engine::OmahaRequestDeviceParams::GetDeviceTrack();
  *track = g_strdup(track_str.c_str());
  return TRUE;
}

gboolean update_engine_service_reboot_if_needed(UpdateEngineService* self,
                                                GError **error) {
  if (!self->update_attempter_->RebootIfNeeded()) {
    *error = NULL;
    return FALSE;
  }
  return TRUE;
}

gboolean update_engine_service_set_track(UpdateEngineService* self,
                                         gchar* track,
                                         GError **error) {
  if (track) {
    LOG(INFO) << "Setting track to: " << track;
    if (!chromeos_update_engine::OmahaRequestDeviceParams::SetDeviceTrack(
            track)) {
      *error = NULL;
      return FALSE;
    }
  }
  return TRUE;
}

gboolean update_engine_service_emit_status_update(
    UpdateEngineService* self,
    gint64 last_checked_time,
    gdouble progress,
    const gchar* current_operation,
    const gchar* new_version,
    gint64 new_size) {
  g_signal_emit(self,
                status_update_signal,
                0,
                last_checked_time,
                progress,
                current_operation,
                new_version,
                new_size);
  return TRUE;
}
<commit_msg>AU: Switch autest to the new test server URL.<commit_after>// Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "update_engine/dbus_service.h"

#include <string>

#include <base/logging.h>

#include "update_engine/marshal.glibmarshal.h"
#include "update_engine/omaha_request_params.h"
#include "update_engine/utils.h"

using std::string;

static const char kAUTestURLRequest[] = "autest";
static const char kAUTestURL[] =
    "https://omaha.sandbox.google.com/service/update2";

G_DEFINE_TYPE(UpdateEngineService, update_engine_service, G_TYPE_OBJECT)

static void update_engine_service_finalize(GObject* object) {
  G_OBJECT_CLASS(update_engine_service_parent_class)->finalize(object);
}

static guint status_update_signal = 0;

static void update_engine_service_class_init(UpdateEngineServiceClass* klass) {
  GObjectClass *object_class;
  object_class = G_OBJECT_CLASS(klass);
  object_class->finalize = update_engine_service_finalize;

  status_update_signal = g_signal_new(
      "status_update",
      G_OBJECT_CLASS_TYPE(klass),
      G_SIGNAL_RUN_LAST,
      0,  // 0 == no class method associated
      NULL,  // Accumulator
      NULL,  // Accumulator data
      update_engine_VOID__INT64_DOUBLE_STRING_STRING_INT64,
      G_TYPE_NONE,  // Return type
      5,  // param count:
      G_TYPE_INT64,
      G_TYPE_DOUBLE,
      G_TYPE_STRING,
      G_TYPE_STRING,
      G_TYPE_INT64);
}

static void update_engine_service_init(UpdateEngineService* object) {
}

UpdateEngineService* update_engine_service_new(void) {
  return reinterpret_cast<UpdateEngineService*>(
      g_object_new(UPDATE_ENGINE_TYPE_SERVICE, NULL));
}

gboolean update_engine_service_attempt_update(UpdateEngineService* self,
                                              gchar* app_version,
                                              gchar* omaha_url,
                                              GError **error) {
  string update_app_version;
  string update_omaha_url;
  // Only non-official (e.g., dev and test) builds can override the current
  // version and update server URL over D-Bus. However, pointing to the
  // hardcoded test update server URL is always allowed.
  if (!chromeos_update_engine::utils::IsOfficialBuild()) {
    if (app_version) {
      update_app_version = app_version;
    }
    if (omaha_url) {
      update_omaha_url = omaha_url;
    }
  }
  if (omaha_url && strcmp(omaha_url, kAUTestURLRequest) == 0) {
    update_omaha_url = kAUTestURL;
  }
  LOG(INFO) << "Attempt update: app_version=\"" << update_app_version << "\" "
            << "omaha_url=\"" << update_omaha_url << "\"";
  self->update_attempter_->CheckForUpdate(update_app_version, update_omaha_url);
  return TRUE;
}

gboolean update_engine_service_get_status(UpdateEngineService* self,
                                          int64_t* last_checked_time,
                                          double* progress,
                                          gchar** current_operation,
                                          gchar** new_version,
                                          int64_t* new_size,
                                          GError **error) {
  string current_op;
  string new_version_str;

  CHECK(self->update_attempter_->GetStatus(last_checked_time,
                                           progress,
                                           &current_op,
                                           &new_version_str,
                                           new_size));

  *current_operation = g_strdup(current_op.c_str());
  *new_version = g_strdup(new_version_str.c_str());
  if (!(*current_operation && *new_version)) {
    *error = NULL;
    return FALSE;
  }
  return TRUE;
}

gboolean update_engine_service_get_track(UpdateEngineService* self,
                                         gchar** track,
                                         GError **error) {
  string track_str =
      chromeos_update_engine::OmahaRequestDeviceParams::GetDeviceTrack();
  *track = g_strdup(track_str.c_str());
  return TRUE;
}

gboolean update_engine_service_reboot_if_needed(UpdateEngineService* self,
                                                GError **error) {
  if (!self->update_attempter_->RebootIfNeeded()) {
    *error = NULL;
    return FALSE;
  }
  return TRUE;
}

gboolean update_engine_service_set_track(UpdateEngineService* self,
                                         gchar* track,
                                         GError **error) {
  if (track) {
    LOG(INFO) << "Setting track to: " << track;
    if (!chromeos_update_engine::OmahaRequestDeviceParams::SetDeviceTrack(
            track)) {
      *error = NULL;
      return FALSE;
    }
  }
  return TRUE;
}

gboolean update_engine_service_emit_status_update(
    UpdateEngineService* self,
    gint64 last_checked_time,
    gdouble progress,
    const gchar* current_operation,
    const gchar* new_version,
    gint64 new_size) {
  g_signal_emit(self,
                status_update_signal,
                0,
                last_checked_time,
                progress,
                current_operation,
                new_version,
                new_size);
  return TRUE;
}
<|endoftext|>


<commit_before>static const char* const CLASS = "RankFilter";

static const char* const HELP =
"Ranks all the values in the chosen kernel"
"and takes the median acoording to the"
"chosen percentage"

#include "DDImage/Iop.h"
#include "DDImage/NukeWrapper.h"
#include "DDImage/Row.h"
#include "DDImage/Tile.h"
#include "DDImage/Knobs.h"

using namespace DD::Image;

#include <algortihm>
#include <vector>

using namespace std;

class RankFilter : public Iop
{
	int _size;
	float _value;

public:

	int maximum_inputs() const { return 1; }
	int minimum_inputs() const { return 1; }

	RankFilter (Node* node) : Iop(node)
	{
		_size = 3;
		_value = 0.5f;
	}

	~RankFilter() {}

	void _validate(bool);
	void _request(int, int, int, int, ChannelMask channels, int count);
	void engine(int, int, int, ChannelMask, Row&);

	const char* Class() const { return CLASS; }
	const char* node_help() const { return HELP; }

	static const Iop::Description d;

};

static Iop* build(Node* node)
{
	return new NukeWrapper(new RankFilter(node));
}

const Iop::Description RankFilter::d (CLASS, "Filter/RankFilter", build);

void RankFilter::engine(int y, int x, int r, ChannelMask channels, Row& row)
{

	Tile tile( input0(), x - _size, y - _size, r + _size, y+_size, channels);
	if (aborted()) { return; }

	foreach(z, channels) {

		float* outptr = row.writable(z) + x;

		for(int cur = x; cur < r; cur++) {

			vector<float> v;

			for (int px = -_size; px < _size; px++) {
				for (int py = -_size; py < _size; py++)
					v.push_back(tile[ z ][ tile.clampy(y+py) ][ tile.clampx(cur + px) ]);
			}

			size_t n = v.size() * _value;
			nth_element(v.begin(), v.begin()+n, v.end());

			*outptr++ = v[n]

		}

	}

}<commit_msg>Update Rankfilter.cpp<commit_after>static const char* const CLASS = "RankFilter";

static const char* const HELP =
"Ranks all the values in the chosen kernel"
"and takes the median acoording to the"
"chosen percentage"

#include "DDImage/Iop.h"
#include "DDImage/NukeWrapper.h"
#include "DDImage/Row.h"
#include "DDImage/Tile.h"
#include "DDImage/Knobs.h"

using namespace DD::Image;

#include <algorithm>
#include <vector>

using namespace std;

class RankFilter : public Iop
{
	int _size;
	float _value;

public:

	int maximum_inputs() const { return 1; }
	int minimum_inputs() const { return 1; }

	RankFilter (Node* node) : Iop(node)
	{
		_size = 3;
		_value = 0.5f;
	}

	~RankFilter() {}

	void _validate(bool);
	void _request(int, int, int, int, ChannelMask, int);
	void engine(int, int, int, ChannelMask, Row&);

	const char* Class() const { return CLASS; }
	const char* node_help() const { return HELP; }

	static const Iop::Description d;

};

static Iop* build(Node* node)
{
	return new NukeWrapper(new RankFilter(node));
}

const Iop::Description RankFilter::d (CLASS, "Filter/RankFilter", build);

void _validate(bool for_real)
{
	copy_info();
	info_.pad( _size );
}

void _request(int x, int y, int r, int t, ChannelMask channels, int count)
{
	input(0)->request( x - _size, y - _size, r + _size, t + _size, channels, count);
}

void RankFilter::engine(int y, int x, int r, ChannelMask channels, Row& row)
{

	Tile tile( input0(), x - _size, y - _size, r + _size, y + _size, channels);
	if (aborted()) { return; }

	foreach(z, channels) {

		float* outptr = row.writable(z) + x;

		for(int cur = x; cur < r; cur++) {

			vector<float> v;

			for (int px = -_size; px < _size; px++) {
				for (int py = -_size; py < _size; py++)
					v.push_back(tile[z][tile.clampy(y + py)][tile.clampx(cur + px)]);
			}

			size_t n = v.size() * _value;
			nth_element(v.begin(), v.begin()+n, v.end());

			*outptr++ = v[n];

		}

	}

}
<|endoftext|>


<commit_before>/*
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 */

#include "newdbwizard.h"

#include "../config.h"
#include "../dbmanager.h"
#include "../iconmanager.h"
#include "../plugins/pluginmanager.h"
#include "../plugins/sqlwrapper.h"

#include <QSqlDatabase>

/*
 * Wizard
 */
NewDbWizard::NewDbWizard(QWidget *parent)
  : QWizard(parent) {
  setupUi(this);
  setWindowIcon(IconManager::get("bookmark-new"));

  setupPages();
}

void NewDbWizard::accept() {
  if(field("savepswd").toBool()) {
    DbManager::addDatabase(field("driver").toString(),
                           field("host").toString(),
                           field("user").toString(),
                           field("pswd").toString(),
                           field("name").toString(),
                           field("alias").toString(),
                           field("usesOdbc").toBool());
  } else {
    DbManager::addDatabase(field("driver").toString(),
                           field("host").toString(),
                           field("user").toString(),
                           field("name").toString(),
                           field("alias").toString(),
                           field("usesOdbc").toBool());
  }

  emit(accepted());
  close();
}

void NewDbWizard::setupPages() {
  setPage(FirstPage, new NdwFirstPage(this));
  setPage(SecondPage, new NdwSecondPage(this));
}

/*
 * First page
 */
NdwFirstPage::NdwFirstPage(QWizard *parent)
  : QWizardPage(parent) {
  setupUi(this);

  odbcAvailable = QSqlDatabase::drivers().contains("QODBC");
  if (!odbcAvailable) {
    odbcCheckBox->setEnabled(false);
    odbcCheckBox->setToolTip(tr("You have no ODBC driver installed."));
  }

  registerField("host", hostLineEdit);
  registerField("driver", dbTypeComboBox, "currentDriver");
<<<<<<< HEAD
  registerField("useODBC", odbcCheckBox);
=======
  registerField("usesOdbc", odbcCheckBox);
>>>>>>> origin/next

  QCompleter *c = new QCompleter(QStringList("localhost"), this);
  c->setCompletionMode(QCompleter::InlineCompletion);
  hostLineEdit->setCompleter(c);

  connect(dbTypeComboBox, SIGNAL(currentIndexChanged(int)),
          this, SIGNAL(completeChanged()));
  connect(hostLineEdit, SIGNAL(textChanged(QString)),
          this, SIGNAL(completeChanged()));
}

void NdwFirstPage::initializePage() {
  dbTypeComboBox->setCurrentDriver(Config::defaultDriver);
  on_dbTypeComboBox_currentIndexChanged(0);
}

bool NdwFirstPage::isComplete() const {
  SqlWrapper *wrapper =
      PluginManager::availableWrapper(dbTypeComboBox->currentDriverName());

  if (wrapper && wrapper->requiresHostname()) {
    return hostLineEdit->text().length() > 0;
  } else {
    return true;
  }
}

void NdwFirstPage::on_dbTypeComboBox_currentIndexChanged(int index) {
  if (!odbcAvailable) {
    return;
  }

  SqlWrapper *wrapper =
      PluginManager::availableWrapper(dbTypeComboBox->currentDriverName());

  if (wrapper) {
    odbcCheckBox->setEnabled(wrapper->features() & SqlWrapper::ODBC);
  } else {
    odbcCheckBox->setEnabled(true);
  }
}

/*
 * Second page
 */
NdwSecondPage::NdwSecondPage(QWizard *parent)
  : QWizardPage(parent) {
  setupUi(this);

  registerField("name*", dbLineEdit);
  registerField("user", userLineEdit);
  registerField("savepswd", pswdCheckBox);
  registerField("pswd", pswdLineEdit);
  registerField("alias", aliasLineEdit);

  connect(dbBrowseButton, SIGNAL(clicked()), this, SLOT(browse()));
  connect(testButton, SIGNAL(clicked()), this, SLOT(test()));

  connect(dbLineEdit, SIGNAL(textChanged(QString)),
          this, SLOT(updateAlias()));
}

void NdwSecondPage::browse() {
  dbLineEdit->setText( QFileDialog::getOpenFileName(this,
                                                    tr("Open Database"),
                                                    QDir::homePath(),
                                                    tr("Database file (*.*)")
                                                    ) );
}

void NdwSecondPage::initializePage() {
  dbBrowseButton->setVisible(field("driver").toString()
                             .startsWith("QSQLITE"));
  resultLabel->setText("");
  updateAlias();
}

void NdwSecondPage::test() {
  QString driver =
      field("useODBC").toBool() ? "ODBC" : field("driver").toString();
  QSqlDatabase db = QSqlDatabase::addDatabase(driver, "testdb");
  db.setHostName(field("host").toString());
  db.setUserName(field("user").toString());
  db.setPassword(field("pswd").toString());
  db.setDatabaseName(field("name").toString());

  if(db.open()) {
    resultLabel->setText(tr("Connection succeded"));
  } else {
    resultLabel->setText(tr("Connection failed"));
    QMessageBox::critical(this,
                          tr("Connection failed"),
                          db.lastError().text());
  }

  QSqlDatabase::removeDatabase("testdb");
}

void NdwSecondPage::updateAlias() {
  // Le nom de BDD peut être un nom de fichier, dans ce cas on va le raccourcir
  QString simplifiedName = QFileInfo(dbLineEdit->text()).fileName();
  if (simplifiedName.length() == 0) {
    simplifiedName = dbLineEdit->text();
  }
  if (field("host").toString().isEmpty()) {
    aliasLineEdit->setText(tr("%1 (local)").arg(simplifiedName));
  } else {
    aliasLineEdit->setText(tr("%1 on %2")
                           .arg(simplifiedName)
                           .arg(field("host").toString()));
  }
}
<commit_msg>Joli rattage avec Git<commit_after>/*
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 */

#include "newdbwizard.h"

#include "../config.h"
#include "../dbmanager.h"
#include "../iconmanager.h"
#include "../plugins/pluginmanager.h"
#include "../plugins/sqlwrapper.h"

#include <QSqlDatabase>

/*
 * Wizard
 */
NewDbWizard::NewDbWizard(QWidget *parent)
  : QWizard(parent) {
  setupUi(this);
  setWindowIcon(IconManager::get("bookmark-new"));

  setupPages();
}

void NewDbWizard::accept() {
  if(field("savepswd").toBool()) {
    DbManager::addDatabase(field("driver").toString(),
                           field("host").toString(),
                           field("user").toString(),
                           field("pswd").toString(),
                           field("name").toString(),
                           field("alias").toString(),
                           field("usesOdbc").toBool());
  } else {
    DbManager::addDatabase(field("driver").toString(),
                           field("host").toString(),
                           field("user").toString(),
                           field("name").toString(),
                           field("alias").toString(),
                           field("usesOdbc").toBool());
  }

  emit(accepted());
  close();
}

void NewDbWizard::setupPages() {
  setPage(FirstPage, new NdwFirstPage(this));
  setPage(SecondPage, new NdwSecondPage(this));
}

/*
 * First page
 */
NdwFirstPage::NdwFirstPage(QWizard *parent)
  : QWizardPage(parent) {
  setupUi(this);

  odbcAvailable = QSqlDatabase::drivers().contains("QODBC");
  if (!odbcAvailable) {
    odbcCheckBox->setEnabled(false);
    odbcCheckBox->setToolTip(tr("You have no ODBC driver installed."));
  }

  registerField("host", hostLineEdit);
  registerField("driver", dbTypeComboBox, "currentDriver");
  registerField("usesOdbc", odbcCheckBox);

  QCompleter *c = new QCompleter(QStringList("localhost"), this);
  c->setCompletionMode(QCompleter::InlineCompletion);
  hostLineEdit->setCompleter(c);

  connect(dbTypeComboBox, SIGNAL(currentIndexChanged(int)),
          this, SIGNAL(completeChanged()));
  connect(hostLineEdit, SIGNAL(textChanged(QString)),
          this, SIGNAL(completeChanged()));
}

void NdwFirstPage::initializePage() {
  dbTypeComboBox->setCurrentDriver(Config::defaultDriver);
  on_dbTypeComboBox_currentIndexChanged(0);
}

bool NdwFirstPage::isComplete() const {
  SqlWrapper *wrapper =
      PluginManager::availableWrapper(dbTypeComboBox->currentDriverName());

  if (wrapper && wrapper->requiresHostname()) {
    return hostLineEdit->text().length() > 0;
  } else {
    return true;
  }
}

void NdwFirstPage::on_dbTypeComboBox_currentIndexChanged(int index) {
  if (!odbcAvailable) {
    return;
  }

  SqlWrapper *wrapper =
      PluginManager::availableWrapper(dbTypeComboBox->currentDriverName());

  if (wrapper) {
    odbcCheckBox->setEnabled(wrapper->features() & SqlWrapper::ODBC);
  } else {
    odbcCheckBox->setEnabled(true);
  }
}

/*
 * Second page
 */
NdwSecondPage::NdwSecondPage(QWizard *parent)
  : QWizardPage(parent) {
  setupUi(this);

  registerField("name*", dbLineEdit);
  registerField("user", userLineEdit);
  registerField("savepswd", pswdCheckBox);
  registerField("pswd", pswdLineEdit);
  registerField("alias", aliasLineEdit);

  connect(dbBrowseButton, SIGNAL(clicked()), this, SLOT(browse()));
  connect(testButton, SIGNAL(clicked()), this, SLOT(test()));

  connect(dbLineEdit, SIGNAL(textChanged(QString)),
          this, SLOT(updateAlias()));
}

void NdwSecondPage::browse() {
  dbLineEdit->setText( QFileDialog::getOpenFileName(this,
                                                    tr("Open Database"),
                                                    QDir::homePath(),
                                                    tr("Database file (*.*)")
                                                    ) );
}

void NdwSecondPage::initializePage() {
  dbBrowseButton->setVisible(field("driver").toString()
                             .startsWith("QSQLITE"));
  resultLabel->setText("");
  updateAlias();
}

void NdwSecondPage::test() {
  QString driver =
      field("useODBC").toBool() ? "ODBC" : field("driver").toString();
  QSqlDatabase db = QSqlDatabase::addDatabase(driver, "testdb");
  db.setHostName(field("host").toString());
  db.setUserName(field("user").toString());
  db.setPassword(field("pswd").toString());
  db.setDatabaseName(field("name").toString());

  if(db.open()) {
    resultLabel->setText(tr("Connection succeded"));
  } else {
    resultLabel->setText(tr("Connection failed"));
    QMessageBox::critical(this,
                          tr("Connection failed"),
                          db.lastError().text());
  }

  QSqlDatabase::removeDatabase("testdb");
}

void NdwSecondPage::updateAlias() {
  // Le nom de BDD peut être un nom de fichier, dans ce cas on va le raccourcir
  QString simplifiedName = QFileInfo(dbLineEdit->text()).fileName();
  if (simplifiedName.length() == 0) {
    simplifiedName = dbLineEdit->text();
  }
  if (field("host").toString().isEmpty()) {
    aliasLineEdit->setText(tr("%1 (local)").arg(simplifiedName));
  } else {
    aliasLineEdit->setText(tr("%1 on %2")
                           .arg(simplifiedName)
                           .arg(field("host").toString()));
  }
}
<|endoftext|>


<commit_before>/* Copyright (c) 2017-2019 Hans-Kristian Arntzen
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include "tone_filter.hpp"
#include "aligned_alloc.hpp"
#include "pole_zero_filter_design.hpp"
#include "dsp.hpp"
#include "util.hpp"
#include <complex>
#include <cmath>
#include <assert.h>

namespace Granite
{
namespace Audio
{
namespace DSP
{
enum { ToneCount = 48, FilterTaps = 8 };

static const double TwoPI = 2.0f * 3.141592653589793;
static const double OnePI = 3.141592653589793;

struct ToneFilter::Impl : Util::AlignedAllocation<ToneFilter::Impl>
{
	alignas(64) float fir_history[FilterTaps][ToneCount] = {};
	alignas(64) float iir_history[FilterTaps][ToneCount] = {};
	alignas(64) float fir_coeff[FilterTaps + 1][ToneCount] = {};
	alignas(64) float iir_coeff[FilterTaps][ToneCount] = {};
	alignas(64) float running_power[ToneCount] = {};
	unsigned index = 0;

	unsigned iir_filter_taps = 0;
	unsigned fir_filter_taps = 0;

	void filter(float *out_samples, const float *in_samples, unsigned count);
};

void ToneFilter::init(float sample_rate, float tuning_freq)
{
	PoleZeroFilterDesigner designer;
	for (int i = 0; i < ToneCount; i++)
	{
		designer.reset();

		float freq = tuning_freq * std::exp2(float(i) / 12.0f);
		float angular_freq = freq * TwoPI / sample_rate;

		// Ad-hoc IIR filter design, wooo.

#if 1
		// Add some zeroes to balance out the filter.
		designer.add_zero(1.0, 0.0);
		designer.add_zero(1.0, OnePI);

		// Add a crap-load of poles. 8-tap IIR.
		// We're going to create a resonator around the desired tone we're looking for.
		designer.add_pole(0.9995, angular_freq);
#else
		designer.add_pole(0.9995, 0.0);
		designer.add_pole(0.999, 0.0);
#endif

		impl->fir_filter_taps = designer.get_numerator_count() - 1;
		impl->iir_filter_taps = designer.get_denominator_count() - 1;

		assert(designer.get_denominator_count() <= FilterTaps);
		assert(designer.get_numerator_count() <= FilterTaps);

		// Normalize the FIR part.
		double inv_response = 1.0 / std::abs(designer.evaluate_response(angular_freq));
		for (unsigned coeff = 0; coeff < impl->fir_filter_taps + 1; coeff++)
			impl->fir_coeff[coeff][i] = float(designer.get_numerator()[coeff] * inv_response);

		// IIR part. To apply the filter, we need to negate the Z-form coeffs.
		for (unsigned coeff = 0; coeff < impl->iir_filter_taps; coeff++)
			impl->iir_coeff[coeff][i] = float(-designer.get_denominator()[coeff + 1]);

#if 0
		double impulse[16 * 1024];
		designer.impulse_response(impulse, 16 * 1024);
		if (i == 0)
		{
			for (auto &i : impulse)
				LOGI("Impulse[%d] = %f\n", unsigned(&i - impulse), i);

			double response = std::abs(designer.evaluate_response(0.0));
			LOGI("Total response: %f\n", response);
		}
#endif
	}
}

ToneFilter::ToneFilter()
{
	impl = new Impl;
}

ToneFilter::~ToneFilter()
{
	delete impl;
}

static float distort(float v)
{
	// TODO: Find something faster.
	return std::atan(v);
}

void ToneFilter::Impl::filter(float *out_samples, const float *in_samples, unsigned count)
{
	for (unsigned samp = 0; samp < count; samp++)
	{
		float final_sample = 0.0f;
		float in_sample = in_samples[samp];

		for (int tone = 0; tone < ToneCount; tone++)
		{
			float ret = fir_coeff[0][tone] * in_sample;
			for (unsigned x = 0; x < fir_filter_taps; x++)
				ret += fir_coeff[x + 1][tone] * fir_history[(index + x) & (FilterTaps - 1)][tone];
			for (unsigned x = 0; x < iir_filter_taps; x++)
				ret += iir_coeff[x][tone] * iir_history[(index + x) & (FilterTaps - 1)][tone];

			fir_history[(index - 1) & (FilterTaps - 1)][tone] = in_sample;
			iir_history[(index - 1) & (FilterTaps - 1)][tone] = ret;

			float new_power = ret * ret;
			constexpr float threshold = 0.001f;
			if (new_power < threshold)
				new_power = new_power * new_power / threshold;
			new_power = 0.9995f * running_power[tone] + 0.0005f * new_power;
			running_power[tone] = new_power;

			float rms = std::sqrt(new_power);

			//assert(abs(ret) < 1000.0f);
			final_sample += rms * distort(ret * 10.0f / (rms + 0.0001f));
		}

		out_samples[samp] = final_sample;
		index = (index - 1) & (FilterTaps - 1);
	}
}

void ToneFilter::filter(float *out_samples, const float *in_samples, unsigned count)
{
	impl->filter(out_samples, in_samples, count);
}
}
}
}
<commit_msg>Fiddle some more. Starting to sound kinda like it!<commit_after>/* Copyright (c) 2017-2019 Hans-Kristian Arntzen
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include "tone_filter.hpp"
#include "aligned_alloc.hpp"
#include "pole_zero_filter_design.hpp"
#include "dsp.hpp"
#include "util.hpp"
#include <complex>
#include <cmath>
#include <assert.h>

namespace Granite
{
namespace Audio
{
namespace DSP
{
enum { ToneCount = 48, FilterTaps = 8 };

static const double TwoPI = 2.0f * 3.141592653589793;
static const double OnePI = 3.141592653589793;

struct ToneFilter::Impl : Util::AlignedAllocation<ToneFilter::Impl>
{
	alignas(64) float fir_history[FilterTaps][ToneCount] = {};
	alignas(64) float iir_history[FilterTaps][ToneCount] = {};
	alignas(64) float fir_coeff[FilterTaps + 1][ToneCount] = {};
	alignas(64) float iir_coeff[FilterTaps][ToneCount] = {};
	alignas(64) float running_power[ToneCount] = {};
	alignas(64) float running_total_power = {};
	unsigned index = 0;

	unsigned iir_filter_taps = 0;
	unsigned fir_filter_taps = 0;

	void filter(float *out_samples, const float *in_samples, unsigned count);
};

void ToneFilter::init(float sample_rate, float tuning_freq)
{
	PoleZeroFilterDesigner designer;
	for (int i = 0; i < ToneCount; i++)
	{
		designer.reset();

		float freq = tuning_freq * std::exp2(float(i) / 12.0f);
		float angular_freq = freq * TwoPI / sample_rate;

		// Ad-hoc IIR filter design, wooo.

#if 1
		// Add some zeroes to balance out the filter.
		designer.add_zero(1.0, 0.0);
		designer.add_zero(1.0, OnePI);

		// Add a crap-load of poles. 8-tap IIR.
		// We're going to create a resonator around the desired tone we're looking for.
		designer.add_pole(0.9998, angular_freq);
#else
		designer.add_pole(0.9995, 0.0);
		designer.add_pole(0.999, 0.0);
#endif

		impl->fir_filter_taps = designer.get_numerator_count() - 1;
		impl->iir_filter_taps = designer.get_denominator_count() - 1;

		assert(designer.get_denominator_count() <= FilterTaps);
		assert(designer.get_numerator_count() <= FilterTaps);

		// Normalize the FIR part.
		double inv_response = 1.0 / std::abs(designer.evaluate_response(angular_freq));
		for (unsigned coeff = 0; coeff < impl->fir_filter_taps + 1; coeff++)
			impl->fir_coeff[coeff][i] = float(designer.get_numerator()[coeff] * inv_response);

		// IIR part. To apply the filter, we need to negate the Z-form coeffs.
		for (unsigned coeff = 0; coeff < impl->iir_filter_taps; coeff++)
			impl->iir_coeff[coeff][i] = float(-designer.get_denominator()[coeff + 1]);

#if 0
		double impulse[16 * 1024];
		designer.impulse_response(impulse, 16 * 1024);
		if (i == 0)
		{
			for (auto &i : impulse)
				LOGI("Impulse[%d] = %f\n", unsigned(&i - impulse), i);

			double response = std::abs(designer.evaluate_response(0.0));
			LOGI("Total response: %f\n", response);
		}
#endif
	}
}

ToneFilter::ToneFilter()
{
	impl = new Impl;
}

ToneFilter::~ToneFilter()
{
	delete impl;
}

static float distort(float v)
{
	// TODO: Find something faster.
	return std::atan(v);
}

void ToneFilter::Impl::filter(float *out_samples, const float *in_samples, unsigned count)
{
	for (unsigned samp = 0; samp < count; samp++)
	{
		float final_sample = 0.0f;
		float in_sample = in_samples[samp];
		running_total_power = running_total_power * 0.9995f + 0.0005f * in_sample * in_sample;

		for (int tone = 0; tone < ToneCount; tone++)
		{
			float ret = fir_coeff[0][tone] * in_sample;
			for (unsigned x = 0; x < fir_filter_taps; x++)
				ret += fir_coeff[x + 1][tone] * fir_history[(index + x) & (FilterTaps - 1)][tone];
			for (unsigned x = 0; x < iir_filter_taps; x++)
				ret += iir_coeff[x][tone] * iir_history[(index + x) & (FilterTaps - 1)][tone];

			fir_history[(index - 1) & (FilterTaps - 1)][tone] = in_sample;
			iir_history[(index - 1) & (FilterTaps - 1)][tone] = ret;

			float new_power = ret * ret;
			float threshold = 0.01f * running_total_power;
			if (new_power < threshold)
				new_power = new_power * new_power / (threshold + 0.00001f);
			new_power = 0.9995f * running_power[tone] + 0.0005f * new_power;
			running_power[tone] = new_power;

			float rms = std::sqrt(new_power);

			//assert(abs(ret) < 1000.0f);
			final_sample += rms * distort(ret * 40.0f / (rms + 0.001f));
		}

		out_samples[samp] = final_sample;
		index = (index - 1) & (FilterTaps - 1);
	}
}

void ToneFilter::filter(float *out_samples, const float *in_samples, unsigned count)
{
	impl->filter(out_samples, in_samples, count);
}
}
}
}
<|endoftext|>


<commit_before>#include "Singleton.h"

Singleton Singleton::instance;

Singleton::Singleton()
{
    facade = new Facade();
    qDebug()<< "Singlon ctor";
}

Singleton::~Singleton()
{
    if (facade)
    {
        delete facade;
        facade = NULL;
    }
}

Facade* Singleton::GetFacade()
{
    if (!facade)
        facade = new Facade();
    return facade;
}

<commit_msg>AllocMemoory exception added<commit_after>#include "Singleton.h"
#include "Exception/AllocMemoryException.h"

Singleton Singleton::instance;

Singleton::Singleton()
{
    facade = new Facade();
    qDebug()<< "Singlon ctor";
}

Singleton::~Singleton()
{
    if (facade)
    {
        delete facade;
        facade = NULL;
    }
}

Facade* Singleton::GetFacade()
{
    try
    {
        if (!facade)
            facade = new Facade();
        return facade;
    }
    catch (std::bad_alloc& exception)
    {
        throw AllocMemoryException("Error allocate memory in Singleton::GetFacade()");
    }
}

<|endoftext|>


<commit_before>// @(#)root/base:$Id$
// Author: Fons Rademakers   15/11/95

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TGuiFactory                                                          //
//                                                                      //
// This ABC is a factory for GUI components. Depending on which         //
// factory is active one gets either ROOT native (X11 based with Win95  //
// look and feel), Win32 or Mac components.                             //
// In case there is no platform dependent implementation on can run in  //
// batch mode directly using an instance of this base class.            //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TGuiFactory.h"
#include "TApplicationImp.h"
#include "TCanvasImp.h"
#include "TBrowserImp.h"
#include "TContextMenuImp.h"
#include "TControlBarImp.h"
#include "TInspectorImp.h"
#include "TROOT.h"

TGuiFactory *gGuiFactory = 0;
TGuiFactory *gBatchGuiFactory = 0;

ClassImp(TGuiFactory)

//______________________________________________________________________________
TGuiFactory::TGuiFactory(const char *name, const char *title)
    : TNamed(name, title)
{
   // TGuiFactory ctor only called by derived classes.
}

//______________________________________________________________________________
TApplicationImp *TGuiFactory::CreateApplicationImp(const char *classname, int *argc, char **argv)
{
   // Create a batch version of TApplicationImp.

   return new TApplicationImp(classname, argc, argv);
}

//______________________________________________________________________________
TCanvasImp *TGuiFactory::CreateCanvasImp(TCanvas *c, const char *title, UInt_t width, UInt_t height)
{
   // Create a batch version of TCanvasImp.

   return new TCanvasImp(c, title, width, height);
}

//______________________________________________________________________________
TCanvasImp *TGuiFactory::CreateCanvasImp(TCanvas *c, const char *title, Int_t x, Int_t y, UInt_t width, UInt_t height)
{
   // Create a batch version of TCanvasImp.

   return new TCanvasImp(c, title, x, y, width, height);
}

//______________________________________________________________________________
TBrowserImp *TGuiFactory::CreateBrowserImp(TBrowser *b, const char *title, UInt_t width, UInt_t height, Option_t *opt)
{
   // Create a batch version of TBrowserImp.

   return new TBrowserImp(b, title, width, height);
}

//______________________________________________________________________________
TBrowserImp *TGuiFactory::CreateBrowserImp(TBrowser *b, const char *title, Int_t x, Int_t y, UInt_t width, UInt_t height, Option_t *opt)
{
   // Create a batch version of TBrowserImp.

   return new TBrowserImp(b, title, x, y, width, height);
}

//______________________________________________________________________________
TContextMenuImp *TGuiFactory::CreateContextMenuImp(TContextMenu *c, const char *, const char *)
{
   // Create a batch version of TContextMenuImp.

   return new TContextMenuImp(c);
}

//______________________________________________________________________________
TControlBarImp *TGuiFactory::CreateControlBarImp(TControlBar *c, const char *title)
{
   // Create a batch version of TControlBarImp.

   return new TControlBarImp(c, title);
}

//______________________________________________________________________________
TControlBarImp *TGuiFactory::CreateControlBarImp(TControlBar *c, const char *title, Int_t x, Int_t y)
{
   // Create a batch version of TControlBarImp.

   return new TControlBarImp(c, title, x, y);
}

//______________________________________________________________________________
TInspectorImp *TGuiFactory::CreateInspectorImp(const TObject *obj, UInt_t width, UInt_t height)
{
   // Create a batch version of TInspectorImp.

   if (gROOT->IsBatch()) {
      return new TInspectorImp(obj, width, height);
   }

   gROOT->ProcessLine(Form("TInspectCanvas::Inspector((TObject*)0x%x);",obj));
   return 0;
}

<commit_msg>From Gerri: Fix compiler warnings on Linux.<commit_after>// @(#)root/base:$Id$
// Author: Fons Rademakers   15/11/95

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TGuiFactory                                                          //
//                                                                      //
// This ABC is a factory for GUI components. Depending on which         //
// factory is active one gets either ROOT native (X11 based with Win95  //
// look and feel), Win32 or Mac components.                             //
// In case there is no platform dependent implementation on can run in  //
// batch mode directly using an instance of this base class.            //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TGuiFactory.h"
#include "TApplicationImp.h"
#include "TCanvasImp.h"
#include "TBrowserImp.h"
#include "TContextMenuImp.h"
#include "TControlBarImp.h"
#include "TInspectorImp.h"
#include "TROOT.h"

TGuiFactory *gGuiFactory = 0;
TGuiFactory *gBatchGuiFactory = 0;

ClassImp(TGuiFactory)

//______________________________________________________________________________
TGuiFactory::TGuiFactory(const char *name, const char *title)
    : TNamed(name, title)
{
   // TGuiFactory ctor only called by derived classes.
}

//______________________________________________________________________________
TApplicationImp *TGuiFactory::CreateApplicationImp(const char *classname, int *argc, char **argv)
{
   // Create a batch version of TApplicationImp.

   return new TApplicationImp(classname, argc, argv);
}

//______________________________________________________________________________
TCanvasImp *TGuiFactory::CreateCanvasImp(TCanvas *c, const char *title, UInt_t width, UInt_t height)
{
   // Create a batch version of TCanvasImp.

   return new TCanvasImp(c, title, width, height);
}

//______________________________________________________________________________
TCanvasImp *TGuiFactory::CreateCanvasImp(TCanvas *c, const char *title, Int_t x, Int_t y, UInt_t width, UInt_t height)
{
   // Create a batch version of TCanvasImp.

   return new TCanvasImp(c, title, x, y, width, height);
}

//______________________________________________________________________________
TBrowserImp *TGuiFactory::CreateBrowserImp(TBrowser *b, const char *title, UInt_t width, UInt_t height, Option_t *)
{
   // Create a batch version of TBrowserImp.

   return new TBrowserImp(b, title, width, height);
}

//______________________________________________________________________________
TBrowserImp *TGuiFactory::CreateBrowserImp(TBrowser *b, const char *title, Int_t x, Int_t y, UInt_t width, UInt_t height, Option_t *)
{
   // Create a batch version of TBrowserImp.

   return new TBrowserImp(b, title, x, y, width, height);
}

//______________________________________________________________________________
TContextMenuImp *TGuiFactory::CreateContextMenuImp(TContextMenu *c, const char *, const char *)
{
   // Create a batch version of TContextMenuImp.

   return new TContextMenuImp(c);
}

//______________________________________________________________________________
TControlBarImp *TGuiFactory::CreateControlBarImp(TControlBar *c, const char *title)
{
   // Create a batch version of TControlBarImp.

   return new TControlBarImp(c, title);
}

//______________________________________________________________________________
TControlBarImp *TGuiFactory::CreateControlBarImp(TControlBar *c, const char *title, Int_t x, Int_t y)
{
   // Create a batch version of TControlBarImp.

   return new TControlBarImp(c, title, x, y);
}

//______________________________________________________________________________
TInspectorImp *TGuiFactory::CreateInspectorImp(const TObject *obj, UInt_t width, UInt_t height)
{
   // Create a batch version of TInspectorImp.

   if (gROOT->IsBatch()) {
      return new TInspectorImp(obj, width, height);
   }

   gROOT->ProcessLine(Form("TInspectCanvas::Inspector((TObject*)0x%x);",obj));
   return 0;
}

<|endoftext|>


<commit_before>// Programmed by jasonfish4
#include "exceptiondispatcher.h"

void Dispatcher::RaiseILGLAccessViolation(BYTE* ptr, BYTE save, BOOLEAN on)
{
	DWORD OldProtect;
	switch (on)
	{
	case FALSE:
		VirtualProtect(ptr, 1, PAGE_EXECUTE_READWRITE, &OldProtect);
		*(BYTE*)ptr = save;
		VirtualProtect(ptr, 1, OldProtect, &OldProtect);
		return;
	case TRUE:
		VirtualProtect(ptr, 1, PAGE_EXECUTE_READWRITE, &OldProtect);
		*(BYTE*)ptr = 0xFF;
		VirtualProtect(ptr, 1, OldProtect, &OldProtect);
		return;
	}
}

void Dispatcher::RaisePageAccessViolation(BYTE* ptr, DWORD save, BOOLEAN on)
{
	DWORD OldProtect;
	switch (on)
	{
	case FALSE:
		VirtualProtect(ptr, 1, save, &OldProtect);
		return;
	case TRUE:
		VirtualProtect(ptr, 1, PAGE_READONLY, &OldProtect);
		return;
	}
}

void Dispatcher::RaiseBreakpointException(BYTE* ptr, BYTE save, BOOLEAN on)
{
	DWORD OldProtect;
	switch (on)
	{
	case FALSE:
		VirtualProtect(ptr, 1, PAGE_EXECUTE_READWRITE, &OldProtect);
		*(BYTE*)ptr = save;
		VirtualProtect(ptr, 1, OldProtect, &OldProtect);
		return;
	case TRUE:
		VirtualProtect(ptr, 1, PAGE_EXECUTE_READWRITE, &OldProtect);
		*(BYTE*)ptr = 0xCC;
		VirtualProtect(ptr, 1, OldProtect, &OldProtect);
		return;
	}
}

void Dispatcher::RaisePrivilegedCodeException(BYTE* ptr, BYTE save, BOOLEAN on)
{
	DWORD OldProtect;
	switch (on)
	{
	case FALSE:
		VirtualProtect(ptr, 1, PAGE_EXECUTE_READWRITE, &OldProtect);
		*(BYTE*)ptr = save;
		VirtualProtect(ptr, 1, OldProtect, &OldProtect);
		return;
	case TRUE:
		VirtualProtect(ptr, 1, PAGE_EXECUTE_READWRITE, &OldProtect);
		*(BYTE*)ptr = 0xF4;
		VirtualProtect(ptr, 1, OldProtect, &OldProtect);
		return;
	}
}

PVOID Dispatcher::HandleException(Dispatcher::PoolSect segment, const char* ModuleName)
{
	switch (segment.ExceptionCode)
	{
	case STATUS_ACCESS_VIOLATION:
		Dispatcher::RaiseILGLAccessViolation((BYTE*)segment.ExceptionAddress, segment.SaveCode, FALSE);
		if (segment.UseModule)
			return (PVOID)((DWORD)GetModuleHandleA(ModuleName) + segment.ExceptionOffset);
		return (PVOID)segment.ExceptionAddress;
	case STATUS_BREAKPOINT:
		Dispatcher::RaiseBreakpointException((BYTE*)segment.ExceptionAddress, segment.SaveCode, FALSE);
		if (segment.UseModule)
			return (PVOID)((DWORD)GetModuleHandleA(ModuleName) + segment.ExceptionOffset);
		return (PVOID)segment.ExceptionAddress;
	case STATUS_PRIVILEGED_INSTRUCTION:
		Dispatcher::RaisePrivilegedCodeException((BYTE*)segment.ExceptionAddress, segment.SaveCode, FALSE);
		if (segment.UseModule)
			return (PVOID)((DWORD)GetModuleHandleA(ModuleName) + segment.ExceptionOffset);
		return (PVOID)segment.ExceptionAddress;
	}
	return NULL;
}

size_t Dispatcher::CheckSector(Dispatcher::PoolSect sector[], size_t size)
{
	for (size_t iterator = 0; iterator < size; iterator++)
	{
		if (sector[iterator].Used == FALSE)
			return iterator;
	}
	return (size + 1);
}

size_t Dispatcher::SearchSector(Dispatcher::PoolSect sector[], size_t size, DWORD address)
{
	for (size_t iterator = 0; iterator < size; iterator++)
	{
		if (sector[iterator].Used == TRUE && sector[iterator].IsAEHPresent == FALSE
			&& sector[iterator].ExceptionAddress == address)
			return iterator;
	}
	return (size + 1);
}

void Dispatcher::UnlockSector(Dispatcher::PoolSect sector[], size_t index)
{
	sector[index].IsAEHPresent = FALSE;
	sector[index].Used = FALSE;
	sector[index].ExceptionAddress = NULL;
}

void Dispatcher::LockSector(Dispatcher::PoolSect sector[], size_t index)
{
	sector[index].Used = TRUE;
	sector[index].IsAEHPresent = FALSE;
}

void Dispatcher::AddException(Dispatcher::PoolSect sector[], size_t index, BOOLEAN Type, DWORD ExceptionAddress)
{
	sector[index].ExceptionAddress = ExceptionAddress;
	sector[index].SaveCode = *(DWORD*)ExceptionAddress;
	sector[index].ExceptionType = Type;
	sector[index].Index = index;
	Dispatcher::LockSector(sector, index);

	switch (Type)
	{
	case 0:
		Dispatcher::RaisePrivilegedCodeException((BYTE*)sector[index].ExceptionAddress, 0, TRUE);
		return;
	case 1:
		Dispatcher::RaisePageAccessViolation((BYTE*)sector[index].ExceptionAddress, 0, TRUE);
		return;
	}

}
<commit_msg>Update exceptiondispatcher.cpp<commit_after>// Programmed by jasonfish4
#include "stdafx.h"
#include "exceptiondispatcher.h"
#include "rvdbg.h"

void Dispatcher::RaiseILGLAccessViolation(BYTE* ptr, BYTE save, BOOLEAN on)
{
	DWORD OldProtect;
	switch (on)
	{
	case FALSE:
		VirtualProtect(ptr, 1, PAGE_EXECUTE_READWRITE, &OldProtect);
		*(BYTE*)ptr = save;
		VirtualProtect(ptr, 1, OldProtect, &OldProtect);
		return;
	case TRUE:
		VirtualProtect(ptr, 1, PAGE_EXECUTE_READWRITE, &OldProtect);
		*(BYTE*)ptr = 0xFF;
		VirtualProtect(ptr, 1, OldProtect, &OldProtect);
		return;
	}
}

void Dispatcher::RaisePageAccessViolation(BYTE* ptr, DWORD save, BOOLEAN on)
{
	DWORD OldProtect;
	switch (on)
	{
	case FALSE:
		VirtualProtect(ptr, 1, save, &OldProtect);
		return;
	case TRUE:
		VirtualProtect(ptr, 1, PAGE_READONLY, &OldProtect);
		return;
	}
}

void Dispatcher::RaiseBreakpointException(BYTE* ptr, BYTE save, BOOLEAN on)
{
	DWORD OldProtect;
	switch (on)
	{
	case FALSE:
		VirtualProtect(ptr, 1, PAGE_EXECUTE_READWRITE, &OldProtect);
		*(BYTE*)ptr = save;
		VirtualProtect(ptr, 1, OldProtect, &OldProtect);
		return;
	case TRUE:
		VirtualProtect(ptr, 1, PAGE_EXECUTE_READWRITE, &OldProtect);
		*(BYTE*)ptr = 0xCC;
		VirtualProtect(ptr, 1, OldProtect, &OldProtect);
		return;
	}
}

void Dispatcher::RaisePrivilegedCodeException(BYTE* ptr, BYTE save, BOOLEAN on)
{
	DWORD OldProtect;
	switch (on)
	{
	case FALSE:
		VirtualProtect(ptr, 1, PAGE_EXECUTE_READWRITE, &OldProtect);
		*(BYTE*)ptr = save;
		VirtualProtect(ptr, 1, OldProtect, &OldProtect);
		return;
	case TRUE:
		VirtualProtect(ptr, 1, PAGE_EXECUTE_READWRITE, &OldProtect);
		*(BYTE*)ptr = 0xF4;
		VirtualProtect(ptr, 1, OldProtect, &OldProtect);
		return;
	}
}

PVOID Dispatcher::HandleException(Dispatcher::PoolSect segment, const char* module_name, BOOLEAN b_module)
{
	segment.UseModule = b_module;
	switch (segment.ExceptionCode)
	{
	case STATUS_ACCESS_VIOLATION:
		Dispatcher::RaiseILGLAccessViolation((BYTE*)segment.ExceptionAddress, segment.SaveCode, FALSE);
		if (segment.UseModule)
			return (PVOID)((DWORD)GetModuleHandleA(module_name) + segment.ExceptionOffset);
		return (PVOID)segment.ExceptionAddress;
	case STATUS_BREAKPOINT:
		Dispatcher::RaiseBreakpointException((BYTE*)segment.ExceptionAddress, segment.SaveCode, FALSE);
		if (segment.UseModule)
			return (PVOID)((DWORD)GetModuleHandleA(module_name) + segment.ExceptionOffset);
		return (PVOID)segment.ExceptionAddress;
	case STATUS_PRIVILEGED_INSTRUCTION:
		Dispatcher::RaisePrivilegedCodeException((BYTE*)segment.ExceptionAddress, segment.SaveCode, FALSE);
		if (segment.UseModule)
			return (PVOID)((DWORD)GetModuleHandleA(module_name) + segment.ExceptionOffset);
		return (PVOID)segment.ExceptionAddress;
	}

	return NULL;
}

size_t Dispatcher::CheckSector(Dispatcher::PoolSect sector[], size_t size)
{
	for (size_t iterator = 0; iterator < size; iterator++)
	{
		if (sector[iterator].Used == FALSE)
			return iterator;
	}
	return (size + 1);
}

size_t Dispatcher::SearchSector(Dispatcher::PoolSect sector[], size_t size, DWORD address)
{
	for (size_t iterator = 0; iterator < size; iterator++)
	{
		if (sector[iterator].Used == TRUE && sector[iterator].IsAEHPresent == FALSE
			&& sector[iterator].ExceptionAddress == address)
			return iterator;
	}
	return (size + 1);
}

void Dispatcher::UnlockSector(Dispatcher::PoolSect sector[], size_t index)
{
	memset(&sector[index], NULL, sizeof(Dispatcher::PoolSect));
}

void Dispatcher::LockSector(Dispatcher::PoolSect sector[], size_t index)
{
	sector[index].Used = TRUE;
	sector[index].IsAEHPresent = FALSE;
}

void Dispatcher::AddException(Dispatcher::PoolSect sector[], size_t index, BOOLEAN Type, DWORD ExceptionAddress)
{
	sector[index].ExceptionAddress = ExceptionAddress;
	sector[index].SaveCode = *(DWORD*)ExceptionAddress;
	sector[index].ExceptionType = Type;
	sector[index].Index = index;
	Dispatcher::LockSector(sector, index);

	switch (Type)
	{
	case IMMEDIATE_EXCEPTION:
		Dispatcher::RaisePrivilegedCodeException((BYTE*)sector[index].ExceptionAddress, 0, TRUE);
		return;
	case PAGE_EXCEPTION:
		Dispatcher::RaisePageAccessViolation((BYTE*)sector[index].ExceptionAddress, 0, TRUE);
		return;
	}

}
<|endoftext|>


<commit_before>#ifndef COMPONENTREGISTRY_HPP
#define COMPONENTREGISTRY_HPP

#include "Component.hpp"
#include "Components/Drawable.hpp"
#include "Components/Movable.hpp"
#include "Components/Physical.hpp"

namespace swift
{
	class ComponentRegistry
	{
		public:
			static Component* get(const std::string& c)
			{
				if(c == "Drawable")
					return new Drawable;
				else if(c == "Movable")
					return new Movable;
				else if(c == "Physical")
					return new Physical;
				else
					return nullptr;
			}
	};
}

#endif // COMPONENTREGISTRY_HPP
<commit_msg>Added new Name component to Registry<commit_after>#ifndef COMPONENTREGISTRY_HPP
#define COMPONENTREGISTRY_HPP

#include "Component.hpp"
#include "Components/Drawable.hpp"
#include "Components/Movable.hpp"
#include "Components/Physical.hpp"
#include "Components/Name.hpp"

namespace swift
{
	class ComponentRegistry
	{
		public:
			static Component* get(const std::string& c)
			{
				if(c == "Drawable")
					return new Drawable;
				else if(c == "Movable")
					return new Movable;
				else if(c == "Physical")
					return new Physical;
				else if(c == "Name")
					return new Name;
				else
					return nullptr;
			}
	};
}

#endif // COMPONENTREGISTRY_HPP
<|endoftext|>