/*
This file was auto-generated by mupdfwrap.py.
*/


#include "mupdf/exceptions.h"
#include "mupdf/internal.h"

#include 
#include 


namespace mupdf
{


struct internal_state
{
	internal_state()
	{
		m_locks.user = this;
		m_locks.lock = lock;
		m_locks.unlock = unlock;
		m_ctx = fz_new_context(NULL /*alloc*/, &m_locks, FZ_STORE_DEFAULT);
		fz_register_document_handlers(m_ctx);
	}
	static void lock(void *user, int lock)
	{
		internal_state*    self = (internal_state*) user;
		self->m_mutexes[lock].lock();
	}
	static void unlock(void *user, int lock)
	{
		internal_state*    self = (internal_state*) user;
		self->m_mutexes[lock].unlock();
	}
	~internal_state()
	{
		fz_drop_context(m_ctx);
	}

	fz_context*         m_ctx;
	std::mutex          m_mutex;    /* Serialise access to m_ctx. */

	/* Provide thread support to mupdf. */
	std::mutex          m_mutexes[FZ_LOCK_MAX];
	fz_locks_context    m_locks;
};

static internal_state  s_state;

struct internal_thread_state
{
	internal_thread_state()
	: m_ctx(NULL)
	{}
	fz_context* get_context()
	{
		if (!m_ctx) {
			/* Make a context for this thread by cloning the global
			context. */
			std::lock_guard lock( s_state.m_mutex);
			m_ctx = fz_clone_context(s_state.m_ctx);
		}
		return m_ctx;
	}
	~internal_thread_state()
	{
		if (m_ctx) {
			fz_drop_context( m_ctx);
		}
	}
	fz_context* m_ctx;
};

static thread_local internal_thread_state  s_thread_state;

fz_context* internal_context_get()
{
	return s_thread_state.get_context();
}


} /* End of namespace mupdf. */