<commit_before>
#include <list>
#include <vector>
#include <unordered_map>
#include <iostream>
#include <array>
#include <string>
#include <functional>
#include <memory>
#include <GL/glew.h>
#include <SDL.h>
#include <SDL_rwops.h>
#include <SDL_net.h>
#include <SDL_thread.h>
#include <physfs.h>
#include <scheme-private.h>
#include <res_path.h>

#include "tuple.h"
#include "twodee.h"
#include "threedee.h"
#include "quat.h"
#include "colour.h"
#include "matrix44.h"
#include "hashstring.h"
#include "locator.h"
#include "servicecounter.h"
#include "service.h"
#include "servicecheckout.h"
#include "serviceregistry.h"
#include "observer.h"
#include "mouse.h"
#include "keyboard.h"
#include "image.h"
#include "texture.h"
#include "shader.h"
#include "program.h"
#include "buffer.h"
#include "bufferbuilder.h"
#include "scripting.h"
#include "torus.h"
#include "renderstate.h"
#include "sprite.h"
#include "timer.h"
#include "tinyscm_if.h"
#include "panel.h"
#include "gui.h"
#include "nanovg.h"
#include "nanovg_gl.h"
#include "blendish.h"
#include "oui.h"
#include "gui.h"

bool	quit = false;

using namespace venk;

const int screen_width  = 640;
const int screen_height = 480;

std::vector< std::shared_ptr<Sprite> > spriteBank;

SDL_sem* global_lock = nullptr;

void render(double alpha, SDL_Window* window, SDL_Renderer* renderer) {
	(void) renderer;
	(void) alpha;
	(void) window;

}

void update(double t, double dt) {
	(void) t;
	(void) dt;
}

void *malloc_shim(PHYSFS_uint64 size) {
	return SDL_malloc((size_t) size);
}

void *realloc_shim(void *mem, PHYSFS_uint64 size) {
	return SDL_realloc(mem, (size_t) size);
}

int initPhysfs(char **argv)
{
	PHYSFS_Allocator sdlAllocator;
	sdlAllocator.Init = nullptr;
	sdlAllocator.Deinit = nullptr;
	sdlAllocator.Malloc = malloc_shim;
	sdlAllocator.Realloc = realloc_shim;
	sdlAllocator.Free = SDL_free;
	int physfsok = PHYSFS_init(argv[0]);
	if(!physfsok) {
		std::cerr << "PhysicsFS Init error" << PHYSFS_getLastError() << std::endl;
		return physfsok;
	}
	PHYSFS_setAllocator(&sdlAllocator);
	physfsok = PHYSFS_setSaneConfig("yagc", "skeleton", "ZIP", 0, 0);
	if(!physfsok) {
		std::cerr << "PhysicsFS Init error" << PHYSFS_getLastError() << std::endl;
		return physfsok;
	}
	std::cout << "Resource path is: " << getResourcePath() << std::endl;
	PHYSFS_mount(getResourcePath().c_str(), nullptr, 1);
	if(!physfsok) {
		std::cerr << "PhysicsFS Init error" << PHYSFS_getLastError() << std::endl;
	}
	return physfsok;
}

std::shared_ptr<SDL_Window> create_window() {

	SDL_SetHint(SDL_HINT_RENDER_DRIVER, "opengl");
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);

	// create window
	auto window_deleter = [](SDL_Window *w) {
		if(w) SDL_DestroyWindow(w);
	};
	std::shared_ptr<SDL_Window> window(SDL_CreateWindow("SDLSkeleton",
														SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
														screen_width, screen_height,
														SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL),
									   window_deleter);
	if(!window) {
		std::cerr << "Unable to create SDL_Window" << std::endl;
	}
	return window;
}

std::shared_ptr<SDL_Renderer> create_renderer(SDL_Window* window) {
	// we created window, create renderer
	auto renderer_deleter = [](SDL_Renderer *r) {
		if(r) SDL_DestroyRenderer(r);
	};
	Uint32 n_drivers = SDL_GetNumRenderDrivers();
	std::cout << n_drivers << " render drivers available" << std::endl;
	for(Uint32 i = 0; i < n_drivers; i++) {
		SDL_RendererInfo info;
		SDL_GetRenderDriverInfo(i, &info);
		std::cout << i << " " << info.name << std::endl;
	}
	Uint32 flags = SDL_RENDERER_ACCELERATED  |  SDL_RENDERER_TARGETTEXTURE;
	std::shared_ptr<SDL_Renderer> renderer(SDL_CreateRenderer(window, -1, flags),  renderer_deleter);
	return renderer;
}

int main(int argc, char **argv) {

	if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER |  SDL_INIT_EVENTS) != 0) {
		std::cerr << "SDL_Init error: " << SDL_GetError() << std::endl;
		return 1;
	} else {
		(void) argc;
		(void) argv;
		if(SDLNet_Init() < 0) {
			std::cerr << "SDLNet_Init: " << SDLNet_GetError() << std::endl;
			return -1;
		}
		initPhysfs(argv);
		ServiceRegistry<ScriptingService>::initialise();
		if (argc > 1) {
			ServiceCheckout<ScriptingService> scripting;
			for(int i = 0; i < argc-1; i++) {
				scripting->load(argv[i-1]);
			}
		}
		std::shared_ptr<SDL_Window> window(create_window());
		if (window) {
			std::shared_ptr<SDL_Renderer> renderer(create_renderer(window.get()));
			if(renderer) {
				// we created renderer, get info about it
				SDL_RendererInfo info;
				SDL_GetRendererInfo(renderer.get(), &info);
				std::cout << " Renderer chosen " << info.name << std::endl;
				SDL_GLContext glctx = SDL_GL_CreateContext(window.get());
				SDL_assert(glctx != nullptr);

				// init glew so we can do OpenGL properly
				Uint32 err = glewInit();
				if(err != GLEW_OK) {
					std::cerr << "Glew init failed " << glewGetErrorString(GLEW_VERSION) << std::endl;
					SDL_Quit();
					exit(-1);
				}
				GLdouble maj = 0;
				glGetDoublev(GL_MAJOR_VERSION, &maj);
				GLdouble min = 0;
				glGetDoublev(GL_MINOR_VERSION, &min);
				std::cout << "OpenGL Version: " << maj << "." << min << std::endl;
				//Use Vsync
				if(SDL_GL_SetSwapInterval(1) < 0) {
					std::cerr <<  "Warning: Unable to set VSync! SDL Error: " << SDL_GetError() << std::endl;
				}
				// Enable depth testing
				glEnable(GL_DEPTH_TEST);
				glDepthFunc(GL_LEQUAL);
				glViewport(0, 0, screen_width, screen_height);
				SDL_assert(glGetError() == GL_NO_ERROR);

				// Now, we need keyboard and mouse
				ServiceRegistry<MouseService>::initialise();
				ServiceRegistry<KeyboardService>::initialise();
				ServiceRegistry<ImageService>::initialise();
				ServiceCheckout<ImageService> images;
				std::shared_ptr<Image> testcard(images->loadImage("test.tga"));
				std::shared_ptr<Image> boulders(images->loadImage("boulders.png"));
				ServiceRegistry<TextureService>::initialise();
				ServiceCheckout<TextureService> textures;
				std::shared_ptr<Texture> backdrop(textures->makeTexture(testcard.get()));
				std::shared_ptr<Texture> spritesheet(textures->makeTexture(boulders.get()));
				ServiceRegistry<ProgramService>::initialise();
				ServiceRegistry<BufferManagerService>::initialise();
				ServiceRegistry<RenderStateService>::initialise();
				ServiceRegistry<SpriteService>::initialise();
				{
					ServiceCheckout<SpriteService> sprites;
					for(int i = 0; i < 6; i++) {
						for(int j = 0; j < 6; j++) {
							spriteBank.push_back(sprites->createSprite(backdrop, i, j, 16, 16));
						}
					}
				}
#ifdef USE_GUI
				ServiceRegistry<GuiService>::initialise();
#endif
				{
					ServiceCheckout<TextureService> textures;
					std::shared_ptr<Texture> background(textures->makeTexture(testcard.get()));
					ServiceCheckout<ProgramService> programs;
					std::shared_ptr<Program> backdrop_shader(programs->loadProgram("backdrop"));
					SDL_assert(backdrop_shader->isValid());
					double  t    = 0.0;
					double  dt   = 0.01;
					double currentTime = timeNow();
					double accumulator = dt;
					global_lock = SDL_CreateSemaphore( 1 );
					SDL_Event e;
					while(!quit) {
						double newTime = timeNow();
						double frameTime = newTime - currentTime;
						if(frameTime > 0.25)
							frameTime = 0.25;
						currentTime = newTime;
						accumulator += frameTime;
						while(accumulator >= dt) {
							SDL_SemWait(global_lock);
							update(t, dt);
							SDL_SemPost(global_lock);
							t += dt;
							accumulator -= dt;
						}
						const double alpha = accumulator / dt;
						SDL_SemWait(global_lock);

						render(1.0 - alpha, window.get(), renderer.get());
#ifdef USE_GUI
						{
							ServiceCheckout<GuiService> gui;
							gui->render();
						}
#endif
						SDL_GL_SwapWindow(window.get());

						SDL_SemPost(global_lock);

						//Handle events on queue
						SDL_PumpEvents();
						while(SDL_PeepEvents(&e,1,SDL_PEEKEVENT, SDL_FIRSTEVENT, SDL_LASTEVENT) != 0) {
							//User requests quit
							if(e.type == SDL_QUIT) {
								quit = true;
							}
							// theoretically this code could be replaced by an event filter (TODO)
							switch(e.type)
							{
								case SDL_MOUSEWHEEL:
								case SDL_MOUSEMOTION:
								case SDL_MOUSEBUTTONUP:
								case SDL_MOUSEBUTTONDOWN:
									{
										SDL_SemWait(global_lock);
										ServiceCheckout<MouseService> squeak;
										squeak->mouse();
										SDL_SemPost(global_lock);

									}
									break;
								case SDL_KEYUP:
								case SDL_KEYDOWN:
									{
										SDL_SemWait(global_lock);
										ServiceCheckout<KeyboardService> keyb;
										keyb->keyboard();
										SDL_SemPost(global_lock);

									}
									break;
								default:
									SDL_PeepEvents(&e, 1, SDL_GETEVENT, SDL_FIRSTEVENT, SDL_LASTEVENT);
									break;
							}
						}
					}
					// quit main loop
					if (global_lock != nullptr) {
						SDL_DestroySemaphore(global_lock);
						global_lock = nullptr;
					}
				}
#ifdef USE_GUI
				ServiceRegistry<GuiService>::shutdown();
#endif
				spriteBank.erase(spriteBank.begin(), spriteBank.end());
				ServiceRegistry<SpriteService>::shutdown();
				ServiceRegistry<RenderStateService>::shutdown();
				ServiceRegistry<BufferManagerService>::shutdown();
				ServiceRegistry<ProgramService>::shutdown();
				ServiceRegistry<TextureService>::shutdown();
				SDL_GL_DeleteContext(glctx);

				ServiceRegistry<ImageService>::shutdown();
				ServiceRegistry<KeyboardService>::shutdown();
				ServiceRegistry<MouseService>::shutdown();
			}
		}
		ServiceRegistry<ScriptingService>::shutdown();
		SDLNet_Quit();
		int phsyfhshutdown = PHYSFS_deinit();
		if(!phsyfhshutdown) {
			std::cerr << "Physfs shutdown failed:" << PHYSFS_getLastError() << std::endl;
		}
		SDL_Quit();
		return 0;
	}
}

<commit_msg>It renders..something..<commit_after>
#include <list>
#include <vector>
#include <unordered_map>
#include <iostream>
#include <array>
#include <string>
#include <functional>
#include <memory>
#include <GL/glew.h>
#include <SDL.h>
#include <SDL_rwops.h>
#include <SDL_net.h>
#include <SDL_thread.h>
#include <physfs.h>
#include <scheme-private.h>
#include <res_path.h>

#include "tuple.h"
#include "twodee.h"
#include "threedee.h"
#include "quat.h"
#include "colour.h"
#include "matrix44.h"
#include "hashstring.h"
#include "locator.h"
#include "servicecounter.h"
#include "service.h"
#include "servicecheckout.h"
#include "serviceregistry.h"
#include "observer.h"
#include "mouse.h"
#include "keyboard.h"
#include "image.h"
#include "texture.h"
#include "shader.h"
#include "program.h"
#include "buffer.h"
#include "bufferbuilder.h"
#include "scripting.h"
#include "torus.h"
#include "renderstate.h"
#include "sprite.h"
#include "timer.h"
#include "tinymt32.h"
#include "random.h"
#include "tinyscm_if.h"
#include "panel.h"
#include "gui.h"
#include "nanovg.h"
#include "nanovg_gl.h"
#include "blendish.h"
#include "oui.h"
#include "gui.h"

bool	quit = false;

using namespace venk;

const int screen_width  = 640;
const int screen_height = 480;

std::vector< std::shared_ptr<Sprite> > spriteBank;

SDL_sem* global_lock = nullptr;

void render(double alpha, SDL_Window* window, SDL_Renderer* renderer) {
	(void) renderer;
	(void) alpha;
	(void) window;
	ServiceCheckout<SpriteService> sprites;
	sprites->render(alpha, window, renderer);
}

void update(double t, double dt) {
	(void) t;
	(void) dt;
}

void *malloc_shim(PHYSFS_uint64 size) {
	return SDL_malloc((size_t) size);
}

void *realloc_shim(void *mem, PHYSFS_uint64 size) {
	return SDL_realloc(mem, (size_t) size);
}

int initPhysfs(char **argv)
{
	PHYSFS_Allocator sdlAllocator;
	sdlAllocator.Init = nullptr;
	sdlAllocator.Deinit = nullptr;
	sdlAllocator.Malloc = malloc_shim;
	sdlAllocator.Realloc = realloc_shim;
	sdlAllocator.Free = SDL_free;
	int physfsok = PHYSFS_init(argv[0]);
	if(!physfsok) {
		std::cerr << "PhysicsFS Init error" << PHYSFS_getLastError() << std::endl;
		return physfsok;
	}
	PHYSFS_setAllocator(&sdlAllocator);
	physfsok = PHYSFS_setSaneConfig("yagc", "skeleton", "ZIP", 0, 0);
	if(!physfsok) {
		std::cerr << "PhysicsFS Init error" << PHYSFS_getLastError() << std::endl;
		return physfsok;
	}
	std::cout << "Resource path is: " << getResourcePath() << std::endl;
	PHYSFS_mount(getResourcePath().c_str(), nullptr, 1);
	if(!physfsok) {
		std::cerr << "PhysicsFS Init error" << PHYSFS_getLastError() << std::endl;
	}
	return physfsok;
}

std::shared_ptr<SDL_Window> create_window() {

	SDL_SetHint(SDL_HINT_RENDER_DRIVER, "opengl");
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);

	// create window
	auto window_deleter = [](SDL_Window *w) {
		if(w) SDL_DestroyWindow(w);
	};
	std::shared_ptr<SDL_Window> window(SDL_CreateWindow("SDLSkeleton",
														SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
														screen_width, screen_height,
														SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL),
									   window_deleter);
	if(!window) {
		std::cerr << "Unable to create SDL_Window" << std::endl;
	}
	return window;
}

std::shared_ptr<SDL_Renderer> create_renderer(SDL_Window* window) {
	// we created window, create renderer
	auto renderer_deleter = [](SDL_Renderer *r) {
		if(r) SDL_DestroyRenderer(r);
	};
	Uint32 n_drivers = SDL_GetNumRenderDrivers();
	std::cout << n_drivers << " render drivers available" << std::endl;
	for(Uint32 i = 0; i < n_drivers; i++) {
		SDL_RendererInfo info;
		SDL_GetRenderDriverInfo(i, &info);
		std::cout << i << " " << info.name << std::endl;
	}
	Uint32 flags = SDL_RENDERER_ACCELERATED  |  SDL_RENDERER_TARGETTEXTURE;
	std::shared_ptr<SDL_Renderer> renderer(SDL_CreateRenderer(window, -1, flags),  renderer_deleter);
	return renderer;
}

int main(int argc, char **argv) {

	if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER |  SDL_INIT_EVENTS) != 0) {
		std::cerr << "SDL_Init error: " << SDL_GetError() << std::endl;
		return 1;
	} else {
		(void) argc;
		(void) argv;
		if(SDLNet_Init() < 0) {
			std::cerr << "SDLNet_Init: " << SDLNet_GetError() << std::endl;
			return -1;
		}
		initPhysfs(argv);
		ServiceRegistry<ScriptingService>::initialise();
		if (argc > 1) {
			ServiceCheckout<ScriptingService> scripting;
			for(int i = 0; i < argc-1; i++) {
				scripting->load(argv[i-1]);
			}
		}
		std::shared_ptr<SDL_Window> window(create_window());
		if (window) {
			std::shared_ptr<SDL_Renderer> renderer(create_renderer(window.get()));
			if(renderer) {
				// we created renderer, get info about it
				SDL_RendererInfo info;
				SDL_GetRendererInfo(renderer.get(), &info);
				std::cout << " Renderer chosen " << info.name << std::endl;
				SDL_GLContext glctx = SDL_GL_CreateContext(window.get());
				SDL_assert(glctx != nullptr);

				// init glew so we can do OpenGL properly
				Uint32 err = glewInit();
				if(err != GLEW_OK) {
					std::cerr << "Glew init failed " << glewGetErrorString(GLEW_VERSION) << std::endl;
					SDL_Quit();
					exit(-1);
				}
				GLdouble maj = 0;
				glGetDoublev(GL_MAJOR_VERSION, &maj);
				GLdouble min = 0;
				glGetDoublev(GL_MINOR_VERSION, &min);
				std::cout << "OpenGL Version: " << maj << "." << min << std::endl;
				//Use Vsync
				if(SDL_GL_SetSwapInterval(1) < 0) {
					std::cerr <<  "Warning: Unable to set VSync! SDL Error: " << SDL_GetError() << std::endl;
				}
				// Enable depth testing
				glEnable(GL_DEPTH_TEST);
				glDepthFunc(GL_LEQUAL);
				glViewport(0, 0, screen_width, screen_height);
				SDL_assert(glGetError() == GL_NO_ERROR);

				// Now, we need keyboard and mouse
				ServiceRegistry<MouseService>::initialise();
				ServiceRegistry<KeyboardService>::initialise();
				ServiceRegistry<ImageService>::initialise();
				ServiceCheckout<ImageService> images;
				std::shared_ptr<Image> testcard(images->loadImage("test.tga"));
				std::shared_ptr<Image> boulders(images->loadImage("boulders.png"));
				ServiceRegistry<TextureService>::initialise();
				ServiceCheckout<TextureService> textures;
				std::shared_ptr<Texture> backdrop(textures->makeTexture(testcard.get()));
				std::shared_ptr<Texture> spritesheet(textures->makeTexture(boulders.get()));
				ServiceRegistry<ProgramService>::initialise();
				ServiceRegistry<BufferManagerService>::initialise();
				ServiceRegistry<RenderStateService>::initialise();
				ServiceRegistry<SpriteService>::initialise();
				{
					ServiceCheckout<SpriteService> sprites;
					RandomContext spriteRandom;
					for(int i = 0; i < 6; i++) {
						for(int j = 0; j < 6; j++) {
							std::shared_ptr<Sprite> sprite(sprites->createSprite(backdrop, i, j, 16, 16));
							sprite->setXY(spriteRandom.nextRandom(), spriteRandom.nextRandom());
							spriteBank.push_back(sprite);

						}
					}
				}
#ifdef USE_GUI
				ServiceRegistry<GuiService>::initialise();
#endif
				{
					ServiceCheckout<TextureService> textures;
					std::shared_ptr<Texture> background(textures->makeTexture(testcard.get()));
					ServiceCheckout<ProgramService> programs;
					std::shared_ptr<Program> backdrop_shader(programs->loadProgram("backdrop"));
					SDL_assert(backdrop_shader->isValid());
					double  t    = 0.0;
					double  dt   = 0.01;
					double currentTime = timeNow();
					double accumulator = dt;
					global_lock = SDL_CreateSemaphore( 1 );
					SDL_Event e;
					while(!quit) {
						double newTime = timeNow();
						double frameTime = newTime - currentTime;
						if(frameTime > 0.25)
							frameTime = 0.25;
						currentTime = newTime;
						accumulator += frameTime;
						while(accumulator >= dt) {
							SDL_SemWait(global_lock);
							update(t, dt);
							SDL_SemPost(global_lock);
							t += dt;
							accumulator -= dt;
						}
						const double alpha = accumulator / dt;
						SDL_SemWait(global_lock);

						render(1.0 - alpha, window.get(), renderer.get());
#ifdef USE_GUI
						{
							ServiceCheckout<GuiService> gui;
							gui->render();
						}
#endif
						SDL_GL_SwapWindow(window.get());

						SDL_SemPost(global_lock);

						//Handle events on queue
						SDL_PumpEvents();
						while(SDL_PeepEvents(&e,1,SDL_PEEKEVENT, SDL_FIRSTEVENT, SDL_LASTEVENT) != 0) {
							//User requests quit
							if(e.type == SDL_QUIT) {
								quit = true;
							}
							// theoretically this code could be replaced by an event filter (TODO)
							switch(e.type)
							{
								case SDL_MOUSEWHEEL:
								case SDL_MOUSEMOTION:
								case SDL_MOUSEBUTTONUP:
								case SDL_MOUSEBUTTONDOWN:
									{
										SDL_SemWait(global_lock);
										ServiceCheckout<MouseService> squeak;
										squeak->mouse();
										SDL_SemPost(global_lock);

									}
									break;
								case SDL_KEYUP:
								case SDL_KEYDOWN:
									{
										SDL_SemWait(global_lock);
										ServiceCheckout<KeyboardService> keyb;
										keyb->keyboard();
										SDL_SemPost(global_lock);

									}
									break;
								default:
									SDL_PeepEvents(&e, 1, SDL_GETEVENT, SDL_FIRSTEVENT, SDL_LASTEVENT);
									break;
							}
						}
					}
					// quit main loop
					if (global_lock != nullptr) {
						SDL_DestroySemaphore(global_lock);
						global_lock = nullptr;
					}
				}
#ifdef USE_GUI
				ServiceRegistry<GuiService>::shutdown();
#endif
				spriteBank.erase(spriteBank.begin(), spriteBank.end());
				ServiceRegistry<SpriteService>::shutdown();
				ServiceRegistry<RenderStateService>::shutdown();
				ServiceRegistry<BufferManagerService>::shutdown();
				ServiceRegistry<ProgramService>::shutdown();
				ServiceRegistry<TextureService>::shutdown();
				SDL_GL_DeleteContext(glctx);

				ServiceRegistry<ImageService>::shutdown();
				ServiceRegistry<KeyboardService>::shutdown();
				ServiceRegistry<MouseService>::shutdown();
			}
		}
		ServiceRegistry<ScriptingService>::shutdown();
		SDLNet_Quit();
		int phsyfhshutdown = PHYSFS_deinit();
		if(!phsyfhshutdown) {
			std::cerr << "Physfs shutdown failed:" << PHYSFS_getLastError() << std::endl;
		}
		SDL_Quit();
		return 0;
	}
}

<|endoftext|>


<commit_before>/* Rapicorn
 * Copyright (C) 2006 Tim Janik
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * A copy of the GNU Lesser General Public License should ship along
 * with this library; if not, see http://www.gnu.org/copyleft/.
 */
#ifndef __RAPICORN_CORE_HH__
#define __RAPICORN_CORE_HH__

#include <rcore/rapicornconfig.h>
#include <rcore/enumdefs.hh>
#include <rcore/rapicorncpu.hh>
#include <rcore/rapicorndebugtools.hh>
#include <rcore/loop.hh>
#include <rcore/main.hh>
#include <rcore/markup.hh>
#include <rcore/pixmap.hh>
#include <rcore/quicktimer.hh>
#include <rcore/rapicornmath.hh>
#include <rcore/rapicornmsg.hh>
#include <rcore/rapicornsignal.hh>
#include <rcore/rapicornthread.hh>
#include <rcore/rapicornutf8.hh>
#include <rcore/utilities.hh>
#include <rcore/rapicornxml.hh>
#include <rcore/regex.hh>
#include <rcore/strings.hh>

/**
 * @namespace Rapicorn
 * The Rapicorn namespace encompasses core utilities and toolkit
 * functionality. The core utilities are available via including
 * <rapicorn-core.hh> and the toolkit functionality can be included
 * as <rapicorn.hh>.
 */
namespace Rapicorn {}

#endif // __RAPICORN_CORE_HH__
/* vim:set ts=8 sts=2 sw=2: */
<commit_msg>RCORE: provide brief doc for Rapicorn namespace<commit_after>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html
#ifndef __RAPICORN_CORE_HH__
#define __RAPICORN_CORE_HH__

#include <rcore/rapicornconfig.h>
#include <rcore/enumdefs.hh>
#include <rcore/rapicorncpu.hh>
#include <rcore/rapicorndebugtools.hh>
#include <rcore/loop.hh>
#include <rcore/main.hh>
#include <rcore/markup.hh>
#include <rcore/pixmap.hh>
#include <rcore/quicktimer.hh>
#include <rcore/rapicornmath.hh>
#include <rcore/rapicornmsg.hh>
#include <rcore/rapicornsignal.hh>
#include <rcore/rapicornthread.hh>
#include <rcore/rapicornutf8.hh>
#include <rcore/utilities.hh>
#include <rcore/rapicornxml.hh>
#include <rcore/regex.hh>
#include <rcore/strings.hh>

/**
 * @namespace Rapicorn
 * @brief The Rapicorn namespace encompasses core utilities and toolkit functionality.
 *
 * The core utilities are available via including <rapicorn-core.hh> and
 * the toolkit functionality can be included via <rapicorn.hh>.
 */
namespace Rapicorn {}

#endif // __RAPICORN_CORE_HH__
<|endoftext|>


<commit_before>#include <iostream>
#include <cassert>
#include <memory>
#include <string>
#include <sys/stat.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <dirent.h>

#include <grpc++/grpc++.h>

#include "tafs.grpc.pb.h"

using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::ServerWriter;
using grpc::Status;
using tafs::OpenReq;
using tafs::OpenReply;
using tafs::AccessReq;
using tafs::AccessReply;
using tafs::ReadReq;
using tafs::ReadReply;
using tafs::WriteReq;
using tafs::WriteReply;
using tafs::TruncateReq;
using tafs::TruncateReply;
using tafs::RenameReq;
using tafs::RenameReply;
using tafs::MknodReq;
using tafs::MknodReply;
using tafs::UnlinkReq;
using tafs::UnlinkReply;
using tafs::ReadDirReq;
using tafs::ReadDirReply;
using tafs::MkDirReq;
using tafs::MkDirReply;
using tafs::RmDirReq;
using tafs::RmDirReply;
using tafs::GetAttrReq;
using tafs::GetAttrReply;
using tafs::ToyAFS;

// Logic and data behind the server's behavior.
class GreeterServiceImpl final : public ToyAFS::Service {
    public:
        const std::string path_prefix;
        GreeterServiceImpl(): path_prefix("/tmp/tafs") {
        }

        /**
         * Access
         */
        Status Access(ServerContext* context, const AccessReq* request,
                AccessReply* reply) override {
            // default errno = 0
            reply->set_err(0);

            std::string path = path_prefix + request->path();

            int res;

            res = access(path.c_str(), request->mode());
            if (res == -1) {
                reply->set_err(-errno);
                return Status::OK;
            }
            reply->set_err(res);
            return Status::OK;
        }

        /**
         * GetAttr
         */
        Status GetAttr(ServerContext* context, const GetAttrReq* request,
                GetAttrReply* reply) override {
            // default errno = 0
            reply->set_err(0);
            int res;
            struct stat stbuf;
            std::string path = path_prefix + request->path();

            printf("GetAttr: %s \n", path.c_str());

            res = lstat(path.c_str(), &stbuf);
            if (res == -1) {
                reply->set_err(-errno);
            }
            else {
                std::string buf;

                int stat_size = sizeof(struct stat);
                buf.resize(stat_size);

                assert(buf.size() == sizeof(struct stat));
                memcpy(&buf[0], &stbuf, buf.size());
                reply->set_buf(buf);
            }
            return Status::OK;
        }

        /**
         * Open
         */
        Status Open(ServerContext* context, const OpenReq* request,
                OpenReply* reply) override {
            // default errno = 0
            reply->set_err(0);

            std::string path = path_prefix + request->path();

            int res;

            res = open(path.c_str(), request->flag());
            if (res == -1) {
                reply->set_err(-errno);
                return Status::OK;
            }
            close(res);
            reply->set_err(res);
            return Status::OK;
        }

        /**
         * Read
         */
        Status Read(ServerContext* context, const ReadReq* request,
                ReadReply* reply) override {
            // default errno = 0
            reply->set_num_bytes(0);
            int res;
            std::string path = path_prefix + request->path();
            int size = request->size();
            int offset = request->offset();

            int fd = open(path.c_str(), O_RDONLY);
            if (fd == -1) {
                reply->set_num_bytes(-1);
                return Status::OK;
            }

            std::string buf;
            buf.resize(size);
            res = pread(fd, &buf[0], size, offset);
            if (res == -1) {
                reply->set_num_bytes(-errno);
            }
            close(fd);
            reply->set_buf(buf);
            reply->set_num_bytes(res);

            return Status::OK;
        }

        /**
         * Write
         */
        Status Write(ServerContext* context, const WriteReq* request,
                WriteReply* reply) override {
            // default errno = 0
            reply->set_num_bytes(-errno);
            std::string path = path_prefix + request->path();
            int fd;
            int res;
            int size = request->size();
            int offset = request->offset();

            fd = open(path.c_str(), O_WRONLY);
            if (fd == -1) {
                reply->set_num_bytes(-errno);
                return Status::OK;
            }

            std::string buf = request->buf();
            res = pwrite(fd, &buf[0], size, offset);

            if (res == -1) {
                reply->set_num_bytes(-errno);
                return Status::OK;
            }

            close(fd);
            reply->set_num_bytes(res);
            return Status::OK;
        }

        /**
         * Truncate
         */
        Status Truncate(ServerContext* context, const TruncateReq* request,
                TruncateReply* reply) override {
            // default errno = 0
            reply->set_err(-errno);
            std::string path = path_prefix + request->path();
            int res;

            res = truncate(path.c_str(), request->size());
            if (res == -1) {
                reply->set_err(-errno);
                return Status::OK;
            }
            reply->set_err(res);
            return Status::OK;
        }

        /**
         * Rename
         */
        Status Rename(ServerContext* context, const RenameReq* request,
                RenameReply* reply) override {
            // default errno = 0
            reply->set_err(0);
            std::string oldpath = path_prefix + request->oldpath();
            std::string newpath = path_prefix + request->newpath();
            int res = rename(oldpath.c_str(), newpath.c_str());
            if (res == -1) {
                reply->set_err(-1);
            }
            reply->set_err(res);
            return Status::OK;
        }

        /**
         * Mknod
         */
        Status Mknod(ServerContext* context, const MknodReq* request,
                MknodReply* reply) override {
            // default errno = 0
            reply->set_err(-errno);
            std::string path = path_prefix + request->path();
            int mode = request->mode();
            int rdev = request->rdev();
            int res;

            /* On Linux this could just be 'mknod(path, mode, rdev)' but this
               is more portable */
            if (S_ISREG(mode)) {
                res = open(path.c_str(), O_CREAT | O_EXCL | O_WRONLY, mode);
                if (res >= 0) {
                    res = close(res);
                }
            } else if (S_ISFIFO(mode)) {
                res = mkfifo(path.c_str(), mode);
            } else {
                res = mknod(path.c_str(), mode, rdev);
            }

            if (res == -1) {
                reply->set_err(-errno);
                return Status::OK;
            }
            reply->set_err(res);
            return Status::OK;
        }

        /**
         * ReadDir
         */
        Status ReadDir(ServerContext* context, const ReadDirReq* request,
                ServerWriter<ReadDirReply>* writer) override {
            ReadDirReply* reply = new ReadDirReply();
            // default errno = 0
            reply->set_err(0);

            std::string path = path_prefix + request->path();

            DIR *dp;
            struct dirent *de;

            dp = opendir(path.c_str());
            if (dp == NULL) {
                reply->set_err(-errno);
                return Status::OK;
            }

            while ((de = readdir(dp)) != NULL) {
                std::string buf;
                buf.resize(sizeof(struct dirent));
                memcpy(&buf[0], de, buf.size());
                reply->set_buf(buf);
                writer->Write(*reply);
            }

            closedir(dp);
            return Status::OK;
        }

        /**
         * MkDir
         */
        Status MkDir(ServerContext* context, const MkDirReq* request,
                MkDirReply* reply) override {
            // default errno = 0
            reply->set_err(0);
            std::string path = path_prefix + request->path();
            int res;

            res = mkdir(path.c_str(), request->mode());
            if (res == -1) {
                reply->set_err(-errno);
                return Status::OK;
            }
            reply->set_err(res);
            return Status::OK;
        }

        /**
         * RmDir
         */
        Status RmDir(ServerContext* context, const RmDirReq* request,
                RmDirReply* reply) override {
            // default errno = 0
            reply->set_err(0);
            std::string path = path_prefix + request->path();
            int res;

            res = rmdir(path.c_str());
            if (res == -1) {
                reply->set_err(-errno);
                return Status::OK;
            }

            reply->set_err(res);
            return Status::OK;
        }

        /**
         * Unlink
         */
        Status Unlink(ServerContext* context, const UnlinkReq* request,
                UnlinkReply* reply) override {
            // default errno = 0
            reply->set_err(0);
            std::string path = path_prefix + request->path();
            int res;
            res = unlink(path.c_str());
            if (res == -1) {
                reply->set_err(-errno);
                return Status::OK;
            }
            reply->set_err(res);
            return Status::OK;
        }

};

void RunServer() {
    std::string server_address("0.0.0.0:50051");
    GreeterServiceImpl service;

    ServerBuilder builder;
    // Listen on the given address without any authentication mechanism.
    builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
    // Register "service" as the instance through which we'll communicate with
    // clients. In this case it corresponds to an *synchronous* service.
    builder.RegisterService(&service);
    // Finally assemble the server.
    std::unique_ptr<Server> server(builder.BuildAndStart());
    std::cout << "Server listening on " << server_address << std::endl;

    // Wait for the server to shutdown. Note that some other thread must be
    // responsible for shutting down the server for this call to ever return.
    server->Wait();
}

int main(int argc, char** argv) {
    RunServer();

    return 0;
}
<commit_msg>fixed server reads<commit_after>#include <iostream>
#include <cassert>
#include <memory>
#include <string>
#include <sys/stat.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <dirent.h>

#include <grpc++/grpc++.h>

#include "tafs.grpc.pb.h"

using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::ServerWriter;
using grpc::Status;
using tafs::OpenReq;
using tafs::OpenReply;
using tafs::AccessReq;
using tafs::AccessReply;
using tafs::ReadReq;
using tafs::ReadReply;
using tafs::ReadSReq;
using tafs::ReadSReply;
using tafs::WriteReq;
using tafs::WriteReply;
using tafs::TruncateReq;
using tafs::TruncateReply;
using tafs::RenameReq;
using tafs::RenameReply;
using tafs::MknodReq;
using tafs::MknodReply;
using tafs::UnlinkReq;
using tafs::UnlinkReply;
using tafs::ReadDirReq;
using tafs::ReadDirReply;
using tafs::MkDirReq;
using tafs::MkDirReply;
using tafs::RmDirReq;
using tafs::RmDirReply;
using tafs::GetAttrReq;
using tafs::GetAttrReply;
using tafs::ToyAFS;

// Logic and data behind the server's behavior.
class GreeterServiceImpl final : public ToyAFS::Service {
    public:
        const std::string path_prefix;
        GreeterServiceImpl(): path_prefix("/tmp/tafs") {
        }

        /**
         * Access
         */
        Status Access(ServerContext* context, const AccessReq* request,
                AccessReply* reply) override {
            // default errno = 0
            reply->set_err(0);

            std::string path = path_prefix + request->path();

            int res;

            res = access(path.c_str(), request->mode());
            if (res == -1) {
                reply->set_err(-errno);
                return Status::OK;
            }
            reply->set_err(res);
            return Status::OK;
        }

        /**
         * GetAttr
         */
        Status GetAttr(ServerContext* context, const GetAttrReq* request,
                GetAttrReply* reply) override {
            // default errno = 0
            reply->set_err(0);
            int res;
            struct stat stbuf;
            std::string path = path_prefix + request->path();

            printf("GetAttr: %s \n", path.c_str());

            res = lstat(path.c_str(), &stbuf);
            if (res == -1) {
                reply->set_err(-errno);
            }
            else {
                std::string buf;

                int stat_size = sizeof(struct stat);
                buf.resize(stat_size);

                assert(buf.size() == sizeof(struct stat));
                memcpy(&buf[0], &stbuf, buf.size());
                reply->set_buf(buf);
            }
            return Status::OK;
        }

        /**
         * Open
         */
        Status Open(ServerContext* context, const OpenReq* request,
                OpenReply* reply) override {
            // default errno = 0
            reply->set_err(0);

            std::string path = path_prefix + request->path();

            int res;

            res = open(path.c_str(), request->flag());
            if (res == -1) {
                reply->set_err(-errno);
                return Status::OK;
            }
            close(res);
            reply->set_err(res);
            return Status::OK;
        }

        /**
         * Read
         */
        Status Read(ServerContext* context, const ReadReq* request,
                ReadReply* reply) override {
            // default errno = 0
            reply->set_num_bytes(0);
            int res;
            std::string path = path_prefix + request->path();
            int size = request->size();
            int offset = request->offset();

            int fd = open(path.c_str(), O_RDONLY);
            if (fd == -1) {
                reply->set_num_bytes(-1);
                return Status::OK;
            }

            std::string buf;
            buf.resize(size);
            res = pread(fd, &buf[0], size, offset);
            if (res == -1) {
                reply->set_num_bytes(-errno);
            }
            close(fd);
            reply->set_buf(buf);
            reply->set_num_bytes(res);

            return Status::OK;
        }

        Status ReadS(ServerContext* context, const ReadSReq* request,
                ServerWriter<ReadSReply>* writer) override {
            ReadSReply* reply = new ReadSReply();

            reply->set_num_bytes(0);
            int res;
            std::string path = path_prefix + request->path();
            int size = request->size();
            int offset = request->offset();

            int fd = open(path.c_str(), O_RDONLY);
            if (fd == -1) {
                reply->set_num_bytes(-1);
                return Status::OK;
            }

            std::string buf;
            buf.resize(size);
            std::string bigbuf;
            bigbuf.reserve(size);

            int b = 0;
            while( ( b = pread(fd, &buf[0], size, offset)) != 0 ) {
               bigbuf += buf;
            }
            if (res == -1) {
                reply->set_num_bytes(-errno);
            }
            close(fd);

            int remain = buf.size();
            int stump = 1<<20;
            int curr = 0;

            while (remain) {
                reply->set_buf(bigbuf.substr(curr, std::min(stump, remain)));
                curr += stump;
                remain -= stump;

                reply->set_num_bytes(stump);
                writer->Write(*reply);
            }
            return Status::OK;
        }

        /**
         * Write
         */
        Status Write(ServerContext* context, const WriteReq* request,
                WriteReply* reply) override {
            // default errno = 0
            reply->set_num_bytes(-errno);
            std::string path = path_prefix + request->path();
            int fd;
            int res;
            int size = request->size();
            int offset = request->offset();

            fd = open(path.c_str(), O_WRONLY);
            if (fd == -1) {
                reply->set_num_bytes(-errno);
                return Status::OK;
            }

            std::string buf = request->buf();
            res = pwrite(fd, &buf[0], size, offset);

            if (res == -1) {
                reply->set_num_bytes(-errno);
                return Status::OK;
            }

            close(fd);
            reply->set_num_bytes(res);
            return Status::OK;
        }

        /**
         * Truncate
         */
        Status Truncate(ServerContext* context, const TruncateReq* request,
                TruncateReply* reply) override {
            // default errno = 0
            reply->set_err(-errno);
            std::string path = path_prefix + request->path();
            int res;

            res = truncate(path.c_str(), request->size());
            if (res == -1) {
                reply->set_err(-errno);
                return Status::OK;
            }
            reply->set_err(res);
            return Status::OK;
        }

        /**
         * Rename
         */
        Status Rename(ServerContext* context, const RenameReq* request,
                RenameReply* reply) override {
            // default errno = 0
            reply->set_err(0);
            std::string oldpath = path_prefix + request->oldpath();
            std::string newpath = path_prefix + request->newpath();
            int res = rename(oldpath.c_str(), newpath.c_str());
            if (res == -1) {
                reply->set_err(-1);
            }
            reply->set_err(res);
            return Status::OK;
        }

        /**
         * Mknod
         */
        Status Mknod(ServerContext* context, const MknodReq* request,
                MknodReply* reply) override {
            // default errno = 0
            reply->set_err(-errno);
            std::string path = path_prefix + request->path();
            int mode = request->mode();
            int rdev = request->rdev();
            int res;

            /* On Linux this could just be 'mknod(path, mode, rdev)' but this
               is more portable */
            if (S_ISREG(mode)) {
                res = open(path.c_str(), O_CREAT | O_EXCL | O_WRONLY, mode);
                if (res >= 0) {
                    res = close(res);
                }
            } else if (S_ISFIFO(mode)) {
                res = mkfifo(path.c_str(), mode);
            } else {
                res = mknod(path.c_str(), mode, rdev);
            }

            if (res == -1) {
                reply->set_err(-errno);
                return Status::OK;
            }
            reply->set_err(res);
            return Status::OK;
        }

        /**
         * ReadDir
         */
        Status ReadDir(ServerContext* context, const ReadDirReq* request,
                ServerWriter<ReadDirReply>* writer) override {
            ReadDirReply* reply = new ReadDirReply();
            // default errno = 0
            reply->set_err(0);

            std::string path = path_prefix + request->path();

            DIR *dp;
            struct dirent *de;

            dp = opendir(path.c_str());
            if (dp == NULL) {
                reply->set_err(-errno);
                return Status::OK;
            }

            while ((de = readdir(dp)) != NULL) {
                std::string buf;
                buf.resize(sizeof(struct dirent));
                memcpy(&buf[0], de, buf.size());
                reply->set_buf(buf);
                writer->Write(*reply);
            }

            closedir(dp);
            return Status::OK;
        }

        /**
         * MkDir
         */
        Status MkDir(ServerContext* context, const MkDirReq* request,
                MkDirReply* reply) override {
            // default errno = 0
            reply->set_err(0);
            std::string path = path_prefix + request->path();
            int res;

            res = mkdir(path.c_str(), request->mode());
            if (res == -1) {
                reply->set_err(-errno);
                return Status::OK;
            }
            reply->set_err(res);
            return Status::OK;
        }

        /**
         * RmDir
         */
        Status RmDir(ServerContext* context, const RmDirReq* request,
                RmDirReply* reply) override {
            // default errno = 0
            reply->set_err(0);
            std::string path = path_prefix + request->path();
            int res;

            res = rmdir(path.c_str());
            if (res == -1) {
                reply->set_err(-errno);
                return Status::OK;
            }

            reply->set_err(res);
            return Status::OK;
        }

        /**
         * Unlink
         */
        Status Unlink(ServerContext* context, const UnlinkReq* request,
                UnlinkReply* reply) override {
            // default errno = 0
            reply->set_err(0);
            std::string path = path_prefix + request->path();
            int res;
            res = unlink(path.c_str());
            if (res == -1) {
                reply->set_err(-errno);
                return Status::OK;
            }
            reply->set_err(res);
            return Status::OK;
        }

};

void RunServer() {
    std::string server_address("0.0.0.0:50051");
    GreeterServiceImpl service;

    ServerBuilder builder;
    // Listen on the given address without any authentication mechanism.
    builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
    // Register "service" as the instance through which we'll communicate with
    // clients. In this case it corresponds to an *synchronous* service.
    builder.RegisterService(&service);
    // Finally assemble the server.
    std::unique_ptr<Server> server(builder.BuildAndStart());
    std::cout << "Server listening on " << server_address << std::endl;

    // Wait for the server to shutdown. Note that some other thread must be
    // responsible for shutting down the server for this call to ever return.
    server->Wait();
}

int main(int argc, char** argv) {
    RunServer();

    return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2006-2008 The Chromium 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 "webkit/glue/plugins/plugin_lib.h"

#include "base/logging.h"
#include "base/message_loop.h"
#include "base/stats_counters.h"
#include "base/string_util.h"
#include "webkit/glue/webkit_glue.h"
#include "webkit/glue/plugins/plugin_instance.h"
#include "webkit/glue/plugins/plugin_host.h"
#include "webkit/glue/plugins/plugin_list.h"

namespace NPAPI
{

const char kPluginLibrariesLoadedCounter[] = "PluginLibrariesLoaded";
const char kPluginInstancesActiveCounter[] = "PluginInstancesActive";

// A list of all the instantiated plugins.
static std::vector<scoped_refptr<PluginLib> >* g_loaded_libs;

PluginLib* PluginLib::CreatePluginLib(const FilePath& filename) {
  // We can only have one PluginLib object per plugin as it controls the per
  // instance function calls (i.e. NP_Initialize and NP_Shutdown).  So we keep
  // a map of PluginLib objects.
  if (!g_loaded_libs)
    g_loaded_libs = new std::vector<scoped_refptr<PluginLib> >;

  for (size_t i = 0; i < g_loaded_libs->size(); ++i) {
    if ((*g_loaded_libs)[i]->plugin_info().path == filename)
      return (*g_loaded_libs)[i];
  }

  WebPluginInfo info;
  const PluginEntryPoints* entry_points = NULL;
  if (!PluginList::Singleton()->ReadPluginInfo(filename, &info, &entry_points))
    return NULL;

  return new PluginLib(info, entry_points);
}

void PluginLib::UnloadAllPlugins() {
  if (g_loaded_libs) {
    for (size_t i = 0; i < g_loaded_libs->size(); ++i)
      (*g_loaded_libs)[i]->Unload();

    delete g_loaded_libs;
    g_loaded_libs = NULL;
  }
}

void PluginLib::ShutdownAllPlugins() {
  if (g_loaded_libs) {
    for (size_t i = 0; i < g_loaded_libs->size(); ++i)
      (*g_loaded_libs)[i]->Shutdown();
  }
}

PluginLib::PluginLib(const WebPluginInfo& info,
                     const PluginEntryPoints* entry_points)
    : web_plugin_info_(info),
      library_(0),
      initialized_(false),
      saved_data_(0),
      instance_count_(0) {
  StatsCounter(kPluginLibrariesLoadedCounter).Increment();
  memset((void*)&plugin_funcs_, 0, sizeof(plugin_funcs_));
  g_loaded_libs->push_back(this);

  if (entry_points) {
    internal_ = true;
    entry_points_ = *entry_points;
  } else {
    internal_ = false;
    // We will read the entry points from the plugin directly.
    memset(&entry_points_, 0, sizeof(entry_points_));
  }
}

PluginLib::~PluginLib() {
  StatsCounter(kPluginLibrariesLoadedCounter).Decrement();
  if (saved_data_ != 0) {
    // TODO - delete the savedData object here
  }
}

NPPluginFuncs* PluginLib::functions() {
  return &plugin_funcs_;
}

NPError PluginLib::NP_Initialize() {
  LOG(INFO) << "PluginLib::NP_Initialize(" << web_plugin_info_.path.value() <<
               "): initialized=" << initialized_;
  if (initialized_)
    return NPERR_NO_ERROR;

  if (!Load())
    return NPERR_MODULE_LOAD_FAILED_ERROR;

  PluginHost* host = PluginHost::Singleton();
  if (host == 0)
    return NPERR_GENERIC_ERROR;

#if defined(OS_LINUX) || defined(OS_FREEBSD)
  NPError rv = entry_points_.np_initialize(host->host_functions(),
                                           &plugin_funcs_);
#else
  NPError rv = entry_points_.np_initialize(host->host_functions());
#endif
  LOG(INFO) << "PluginLib::NP_Initialize(" << web_plugin_info_.path.value() <<
               "): result=" << rv;
  initialized_ = (rv == NPERR_NO_ERROR);
  return rv;
}

void PluginLib::NP_Shutdown(void) {
  DCHECK(initialized_);
  entry_points_.np_shutdown();
}

PluginInstance* PluginLib::CreateInstance(const std::string& mime_type) {
  PluginInstance* new_instance = new PluginInstance(this, mime_type);
  instance_count_++;
  StatsCounter(kPluginInstancesActiveCounter).Increment();
  DCHECK(new_instance != 0);
  return new_instance;
}

void PluginLib::CloseInstance() {
  StatsCounter(kPluginInstancesActiveCounter).Decrement();
  instance_count_--;
  // If a plugin is running in its own process it will get unloaded on process
  // shutdown.
  if ((instance_count_ == 0) &&
       webkit_glue::IsPluginRunningInRendererProcess()) {
    Unload();
    for (size_t i = 0; i < g_loaded_libs->size(); ++i) {
      if ((*g_loaded_libs)[i].get() == this) {
        g_loaded_libs->erase(g_loaded_libs->begin() + i);
        break;
      }
    }
    if (g_loaded_libs->empty()) {
      delete g_loaded_libs;
      g_loaded_libs = NULL;
    }
  }
}

bool PluginLib::Load() {
  bool rv = false;
  base::NativeLibrary library = 0;

  if (!internal_) {
    if (library_ != 0)
      return rv;

    library = base::LoadNativeLibrary(web_plugin_info_.path);
    if (library == 0)
      return rv;

    rv = true;  // assume success now

    entry_points_.np_initialize =
        (NP_InitializeFunc)base::GetFunctionPointerFromNativeLibrary(library,
            "NP_Initialize");
    if (entry_points_.np_initialize == 0)
      rv = false;

#if !defined(OS_LINUX) && !defined(OS_FREEBSD)
    entry_points_.np_getentrypoints =
        (NP_GetEntryPointsFunc)base::GetFunctionPointerFromNativeLibrary(
            library, "NP_GetEntryPoints");
    if (entry_points_.np_getentrypoints == 0)
      rv = false;
#endif

    entry_points_.np_shutdown =
        (NP_ShutdownFunc)base::GetFunctionPointerFromNativeLibrary(library,
            "NP_Shutdown");
    if (entry_points_.np_shutdown == 0)
      rv = false;
  } else {
    rv = true;
  }

  if (rv) {
    plugin_funcs_.size = sizeof(plugin_funcs_);
    plugin_funcs_.version = (NP_VERSION_MAJOR << 8) | NP_VERSION_MINOR;
#if !defined(OS_LINUX) && !defined(OS_FREEBSD)
    if (entry_points_.np_getentrypoints(&plugin_funcs_) != NPERR_NO_ERROR)
      rv = false;
#else
    // On Linux, we get the plugin entry points during NP_Initialize.
#endif
  }

  if (!internal_) {
    if (rv)
      library_ = library;
    else
      base::UnloadNativeLibrary(library);
  }

  return rv;
}

// This class implements delayed NP_Shutdown and FreeLibrary on the plugin dll.
class FreePluginLibraryTask : public Task {
 public:
  FreePluginLibraryTask(base::NativeLibrary library,
                        NP_ShutdownFunc shutdown_func)
      : library_(library),
        NP_Shutdown_(shutdown_func) {
  }

  ~FreePluginLibraryTask() {}

  void Run() {
    if (NP_Shutdown_)
      NP_Shutdown_();

    if (library_) {
      base::UnloadNativeLibrary(library_);
      library_ = NULL;
    }
  }

 private:
  base::NativeLibrary library_;
  NP_ShutdownFunc NP_Shutdown_;
  DISALLOW_EVIL_CONSTRUCTORS(FreePluginLibraryTask);
};

void PluginLib::Unload() {
  if (!internal_ && library_) {
    // In case of single process mode, a plugin can delete itself
    // by executing a script. So delay the unloading of the library
    // so that the plugin will have a chance to unwind.
    bool defer_unload = webkit_glue::IsPluginRunningInRendererProcess();

/* TODO(dglazkov): Revisit when re-enabling the JSC build.
#if USE(JSC)
    // The plugin NPAPI instances may still be around. Delay the
    // NP_Shutdown and FreeLibrary calls at least till the next
    // peek message.
    defer_unload = true;
#endif
*/

    if (defer_unload) {
      FreePluginLibraryTask* free_library_task =
          new FreePluginLibraryTask(library_, entry_points_.np_shutdown);
      MessageLoop::current()->PostTask(FROM_HERE, free_library_task);
    } else {
      Shutdown();
      base::UnloadNativeLibrary(library_);
    }

    library_ = 0;
  }
}

void PluginLib::Shutdown() {
  if (initialized_ && !internal_) {
    NP_Shutdown();
    initialized_ = false;
  }
}

}  // namespace NPAPI
<commit_msg>Call np_getentrypoints after np_initialize on the Mac<commit_after>// Copyright (c) 2006-2008 The Chromium 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 "webkit/glue/plugins/plugin_lib.h"

#include "base/logging.h"
#include "base/message_loop.h"
#include "base/stats_counters.h"
#include "base/string_util.h"
#include "webkit/glue/webkit_glue.h"
#include "webkit/glue/plugins/plugin_instance.h"
#include "webkit/glue/plugins/plugin_host.h"
#include "webkit/glue/plugins/plugin_list.h"

namespace NPAPI
{

const char kPluginLibrariesLoadedCounter[] = "PluginLibrariesLoaded";
const char kPluginInstancesActiveCounter[] = "PluginInstancesActive";

// A list of all the instantiated plugins.
static std::vector<scoped_refptr<PluginLib> >* g_loaded_libs;

PluginLib* PluginLib::CreatePluginLib(const FilePath& filename) {
  // We can only have one PluginLib object per plugin as it controls the per
  // instance function calls (i.e. NP_Initialize and NP_Shutdown).  So we keep
  // a map of PluginLib objects.
  if (!g_loaded_libs)
    g_loaded_libs = new std::vector<scoped_refptr<PluginLib> >;

  for (size_t i = 0; i < g_loaded_libs->size(); ++i) {
    if ((*g_loaded_libs)[i]->plugin_info().path == filename)
      return (*g_loaded_libs)[i];
  }

  WebPluginInfo info;
  const PluginEntryPoints* entry_points = NULL;
  if (!PluginList::Singleton()->ReadPluginInfo(filename, &info, &entry_points))
    return NULL;

  return new PluginLib(info, entry_points);
}

void PluginLib::UnloadAllPlugins() {
  if (g_loaded_libs) {
    for (size_t i = 0; i < g_loaded_libs->size(); ++i)
      (*g_loaded_libs)[i]->Unload();

    delete g_loaded_libs;
    g_loaded_libs = NULL;
  }
}

void PluginLib::ShutdownAllPlugins() {
  if (g_loaded_libs) {
    for (size_t i = 0; i < g_loaded_libs->size(); ++i)
      (*g_loaded_libs)[i]->Shutdown();
  }
}

PluginLib::PluginLib(const WebPluginInfo& info,
                     const PluginEntryPoints* entry_points)
    : web_plugin_info_(info),
      library_(0),
      initialized_(false),
      saved_data_(0),
      instance_count_(0) {
  StatsCounter(kPluginLibrariesLoadedCounter).Increment();
  memset((void*)&plugin_funcs_, 0, sizeof(plugin_funcs_));
  g_loaded_libs->push_back(this);

  if (entry_points) {
    internal_ = true;
    entry_points_ = *entry_points;
  } else {
    internal_ = false;
    // We will read the entry points from the plugin directly.
    memset(&entry_points_, 0, sizeof(entry_points_));
  }
}

PluginLib::~PluginLib() {
  StatsCounter(kPluginLibrariesLoadedCounter).Decrement();
  if (saved_data_ != 0) {
    // TODO - delete the savedData object here
  }
}

NPPluginFuncs* PluginLib::functions() {
  return &plugin_funcs_;
}

NPError PluginLib::NP_Initialize() {
  LOG(INFO) << "PluginLib::NP_Initialize(" << web_plugin_info_.path.value() <<
               "): initialized=" << initialized_;
  if (initialized_)
    return NPERR_NO_ERROR;

  if (!Load())
    return NPERR_MODULE_LOAD_FAILED_ERROR;

  PluginHost* host = PluginHost::Singleton();
  if (host == 0)
    return NPERR_GENERIC_ERROR;

#if defined(OS_LINUX) || defined(OS_FREEBSD)
  NPError rv = entry_points_.np_initialize(host->host_functions(),
                                           &plugin_funcs_);
#else
  NPError rv = entry_points_.np_initialize(host->host_functions());
#if defined(OS_MACOSX)
  // On the Mac, we need to get entry points after calling np_initialize to
  // match the behavior of other browsers.
  if (rv == NPERR_NO_ERROR) {
    rv = entry_points_.np_getentrypoints(&plugin_funcs_);
  }
#endif  // OS_MACOSX
#endif
  LOG(INFO) << "PluginLib::NP_Initialize(" << web_plugin_info_.path.value() <<
               "): result=" << rv;
  initialized_ = (rv == NPERR_NO_ERROR);
  return rv;
}

void PluginLib::NP_Shutdown(void) {
  DCHECK(initialized_);
  entry_points_.np_shutdown();
}

PluginInstance* PluginLib::CreateInstance(const std::string& mime_type) {
  PluginInstance* new_instance = new PluginInstance(this, mime_type);
  instance_count_++;
  StatsCounter(kPluginInstancesActiveCounter).Increment();
  DCHECK(new_instance != 0);
  return new_instance;
}

void PluginLib::CloseInstance() {
  StatsCounter(kPluginInstancesActiveCounter).Decrement();
  instance_count_--;
  // If a plugin is running in its own process it will get unloaded on process
  // shutdown.
  if ((instance_count_ == 0) &&
       webkit_glue::IsPluginRunningInRendererProcess()) {
    Unload();
    for (size_t i = 0; i < g_loaded_libs->size(); ++i) {
      if ((*g_loaded_libs)[i].get() == this) {
        g_loaded_libs->erase(g_loaded_libs->begin() + i);
        break;
      }
    }
    if (g_loaded_libs->empty()) {
      delete g_loaded_libs;
      g_loaded_libs = NULL;
    }
  }
}

bool PluginLib::Load() {
  bool rv = false;
  base::NativeLibrary library = 0;

  if (!internal_) {
    if (library_ != 0)
      return rv;

    library = base::LoadNativeLibrary(web_plugin_info_.path);
    if (library == 0)
      return rv;

    rv = true;  // assume success now

    entry_points_.np_initialize =
        (NP_InitializeFunc)base::GetFunctionPointerFromNativeLibrary(library,
            "NP_Initialize");
    if (entry_points_.np_initialize == 0)
      rv = false;

#if !defined(OS_LINUX) && !defined(OS_FREEBSD)
    entry_points_.np_getentrypoints =
        (NP_GetEntryPointsFunc)base::GetFunctionPointerFromNativeLibrary(
            library, "NP_GetEntryPoints");
    if (entry_points_.np_getentrypoints == 0)
      rv = false;
#endif

    entry_points_.np_shutdown =
        (NP_ShutdownFunc)base::GetFunctionPointerFromNativeLibrary(library,
            "NP_Shutdown");
    if (entry_points_.np_shutdown == 0)
      rv = false;
  } else {
    rv = true;
  }

  if (rv) {
    plugin_funcs_.size = sizeof(plugin_funcs_);
    plugin_funcs_.version = (NP_VERSION_MAJOR << 8) | NP_VERSION_MINOR;
#if !defined(OS_LINUX) && !defined(OS_FREEBSD) && !defined(OS_MACOSX)
    if (entry_points_.np_getentrypoints(&plugin_funcs_) != NPERR_NO_ERROR)
      rv = false;
#else
    // On Linux and Mac, we get the plugin entry points during NP_Initialize.
#endif
  }

  if (!internal_) {
    if (rv)
      library_ = library;
    else
      base::UnloadNativeLibrary(library);
  }

  return rv;
}

// This class implements delayed NP_Shutdown and FreeLibrary on the plugin dll.
class FreePluginLibraryTask : public Task {
 public:
  FreePluginLibraryTask(base::NativeLibrary library,
                        NP_ShutdownFunc shutdown_func)
      : library_(library),
        NP_Shutdown_(shutdown_func) {
  }

  ~FreePluginLibraryTask() {}

  void Run() {
    if (NP_Shutdown_)
      NP_Shutdown_();

    if (library_) {
      base::UnloadNativeLibrary(library_);
      library_ = NULL;
    }
  }

 private:
  base::NativeLibrary library_;
  NP_ShutdownFunc NP_Shutdown_;
  DISALLOW_EVIL_CONSTRUCTORS(FreePluginLibraryTask);
};

void PluginLib::Unload() {
  if (!internal_ && library_) {
    // In case of single process mode, a plugin can delete itself
    // by executing a script. So delay the unloading of the library
    // so that the plugin will have a chance to unwind.
    bool defer_unload = webkit_glue::IsPluginRunningInRendererProcess();

/* TODO(dglazkov): Revisit when re-enabling the JSC build.
#if USE(JSC)
    // The plugin NPAPI instances may still be around. Delay the
    // NP_Shutdown and FreeLibrary calls at least till the next
    // peek message.
    defer_unload = true;
#endif
*/

    if (defer_unload) {
      FreePluginLibraryTask* free_library_task =
          new FreePluginLibraryTask(library_, entry_points_.np_shutdown);
      MessageLoop::current()->PostTask(FROM_HERE, free_library_task);
    } else {
      Shutdown();
      base::UnloadNativeLibrary(library_);
    }

    library_ = 0;
  }
}

void PluginLib::Shutdown() {
  if (initialized_ && !internal_) {
    NP_Shutdown();
    initialized_ = false;
  }
}

}  // namespace NPAPI
<|endoftext|>


<commit_before>#include "HTTPFramingStrategy.h"
#include <regex>

using namespace Dumais::WebServer;

int HTTPFramingStrategy::processData(char* buffer, size_t size, FullMessageInfo& info)
{
    if (info.buffer == 0)
    {
        info.buffer = new char[size];
    }
    else
    {
        char* tmp = new char[size+info.size];
        memcpy(tmp,info.buffer,info.size);
        delete info.buffer;
        info.buffer = tmp;
    }
    memcpy((char*)&info.buffer[info.size],buffer,size);
    // search for end of header
    std::string message = info.buffer;
    size_t eoh = message.find("\r\n\r\n");
    if (eoh == std::string::npos)
    {
        // Full header was not received. continue to receive data.
        info.size+=size;

        // If the buffer is bigger than 2k and we still didn't receive the end of header, then reject this connection
        if (info.size > 2048)
        {
            delete info.buffer;
            return -2;
        }
        return size;
    }

    std::regex r("transfer-encoding: *chunked",std::regex_constants::icase);
    std::smatch matches;
    if (std::regex_search(message,matches,r))
    {
        return -3;
    }

    std::regex r2("Content-Length: *(.*)",std::regex_constants::icase);
    unsigned int contentLength = 0;
    if (std::regex_search(message,matches,r2))
    {
        contentLength = atoi(matches[1].str().c_str());
    }

    // check if full message was received
    if ((info.size+size) < (eoh+4+contentLength))
    {
        // Not finished receiving content. Carry on
        info.size+=size;
        return size;
    }

    info.complete = true;

    // check if we have other data at the end of the message
    unsigned int delta = (eoh+4+contentLength)-info.size;
    if (delta < size)
    {
        info.size+=delta;
    }
    else
    {
        info.size+=size;
    }
    return delta;
}

<commit_msg>added include string.h to HTTPFramingStrategy.cpp<commit_after>#include "HTTPFramingStrategy.h"
#include <string.h> // needed for memcpy
#include <regex>

using namespace Dumais::WebServer;

int HTTPFramingStrategy::processData(char* buffer, size_t size, FullMessageInfo& info)
{
    if (info.buffer == 0)
    {
        info.buffer = new char[size];
    }
    else
    {
        char* tmp = new char[size+info.size];
        memcpy(tmp,info.buffer,info.size);
        delete info.buffer;
        info.buffer = tmp;
    }
    memcpy((char*)&info.buffer[info.size],buffer,size);
    // search for end of header
    std::string message = info.buffer;
    size_t eoh = message.find("\r\n\r\n");
    if (eoh == std::string::npos)
    {
        // Full header was not received. continue to receive data.
        info.size+=size;

        // If the buffer is bigger than 2k and we still didn't receive the end of header, then reject this connection
        if (info.size > 2048)
        {
            delete info.buffer;
            return -2;
        }
        return size;
    }

    std::regex r("transfer-encoding: *chunked",std::regex_constants::icase);
    std::smatch matches;
    if (std::regex_search(message,matches,r))
    {
        return -3;
    }

    std::regex r2("Content-Length: *(.*)",std::regex_constants::icase);
    unsigned int contentLength = 0;
    if (std::regex_search(message,matches,r2))
    {
        contentLength = atoi(matches[1].str().c_str());
    }

    // check if full message was received
    if ((info.size+size) < (eoh+4+contentLength))
    {
        // Not finished receiving content. Carry on
        info.size+=size;
        return size;
    }

    info.complete = true;

    // check if we have other data at the end of the message
    unsigned int delta = (eoh+4+contentLength)-info.size;
    if (delta < size)
    {
        info.size+=delta;
    }
    else
    {
        info.size+=size;
    }
    return delta;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: shapeexport.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: mib $ $Date: 2000-11-07 13:33:05 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library 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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _COM_SUN_STAR_TEXT_XTEXT_HPP_
#include <com/sun/star/text/XText.hpp>
#endif

#ifndef _COM_SUN_STAR_CHART_XCHARTDOCUMENT_HPP_
#include <com/sun/star/chart/XChartDocument.hpp>
#endif

#ifndef _XMLOFF_SHAPEEXPORT_HXX
#include "shapeexport.hxx"
#endif

#ifndef _SDPROPLS_HXX
#include "sdpropls.hxx"
#endif

#ifndef _SDXMLEXP_HXX
#include "sdxmlexp.hxx"
#endif

#ifndef _XMLOFF_FAMILIES_HXX_
#include "families.hxx"
#endif

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

using namespace ::rtl;
using namespace ::com::sun::star;

//////////////////////////////////////////////////////////////////////////////

XMLShapeExport::XMLShapeExport(SvXMLExport& rExp,
                                SvXMLExportPropertyMapper *pExtMapper )
:   rExport( rExp )
{
    // construct PropertyHandlerFactory
    xSdPropHdlFactory = new XMLSdPropHdlFactory;

    // construct PropertySetMapper
    UniReference < XMLPropertySetMapper > xMapper =
        new XMLPropertySetMapper(
            (XMLPropertyMapEntry*)aXMLSDProperties, xSdPropHdlFactory);
    xPropertySetMapper = new SvXMLExportPropertyMapper( xMapper );
    if( pExtMapper )
    {
        UniReference < SvXMLExportPropertyMapper > xExtMapper( pExtMapper );
        xPropertySetMapper->ChainExportMapper( xExtMapper );
    }

    rExp.GetAutoStylePool()->AddFamily(
        XML_STYLE_FAMILY_SD_GRAPHICS_ID,
        OUString(RTL_CONSTASCII_USTRINGPARAM(XML_STYLE_FAMILY_SD_GRAPHICS_NAME)),
        GetPropertySetMapper(),
        OUString(RTL_CONSTASCII_USTRINGPARAM(XML_STYLE_FAMILY_SD_GRAPHICS_PREFIX)));
    rExp.GetAutoStylePool()->AddFamily(
        XML_STYLE_FAMILY_SD_PRESENTATION_ID,
        OUString(RTL_CONSTASCII_USTRINGPARAM(XML_STYLE_FAMILY_SD_PRESENTATION_NAME)),
        GetPropertySetMapper(),
        OUString(RTL_CONSTASCII_USTRINGPARAM(XML_STYLE_FAMILY_SD_PRESENTATION_PREFIX)));
}

XMLShapeExport::~XMLShapeExport()
{
}

// This method collects all automatic styles for the given XShape
void XMLShapeExport::collectShapeAutoStyles(const uno::Reference< drawing::XShape >& xShape)
{
    uno::Reference< beans::XPropertySet > xPropSet(xShape, uno::UNO_QUERY);
    if(xPropSet.is())
    {
        // filter propset
        OUString aParentName; // parent maybe the pool in later versions
        OUString aNewName;
        std::vector< XMLPropertyState > xPropStates = GetPropertySetMapper()->Filter( xPropSet );

        if(xPropStates.size())
        {
            // there are filtered properties -> hard attributes
            // try to find this style in AutoStylePool
            aNewName = GetExport().GetAutoStylePool()->Find(
                XML_STYLE_FAMILY_SD_GRAPHICS_ID, aParentName, xPropStates);

            if(!aNewName.getLength())
            {
                // Style did not exist, add it to AutoStalePool
                GetExport().GetAutoStylePool()->Add(
                    XML_STYLE_FAMILY_SD_GRAPHICS_ID, aParentName, xPropStates);
            }
        }
    }

    // prep text styles
    uno::Reference< text::XText > xText(xShape, uno::UNO_QUERY);
    if(xText.is())
    {
        uno::Reference< beans::XPropertySetInfo > xPropSetInfo( xPropSet->getPropertySetInfo() );

        sal_Bool bIsEmptyPresObj = sal_False;

        if( xPropSetInfo.is() && xPropSetInfo->hasPropertyByName(OUString(RTL_CONSTASCII_USTRINGPARAM("IsEmptyPresentationObject"))))
        {
            uno::Any aAny = xPropSet->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("IsEmptyPresentationObject")));
            aAny >>= bIsEmptyPresObj;
        }

        if(!bIsEmptyPresObj)
        {
            GetExport().GetTextParagraphExport()->collectTextAutoStyles( xText );
        }
    }

    // check for calc ole
    const OUString aShapeType( xShape->getShapeType() );
    if( (0 == aShapeType.reverseCompareToAsciiL( RTL_CONSTASCII_STRINGPARAM( "com.sun.star.drawing.OLE2Shape" ))) ||
        (0 == aShapeType.reverseCompareToAsciiL( RTL_CONSTASCII_STRINGPARAM( "com.sun.star.presentation.CalcShape" ))) )
    {
        uno::Reference< chart::XChartDocument > xChartDoc;
        uno::Any aAny( xPropSet->getPropertyValue( OUString(RTL_CONSTASCII_USTRINGPARAM("Model") ) ) );
        aAny >>= xChartDoc;
        if( xChartDoc.is() )
        {
            GetExport().GetChartExport()->collectAutoStyles( xChartDoc );
        }
    }
}

// This method exports the given XShape
void XMLShapeExport::exportShape(const uno::Reference< drawing::XShape >& xShape,
                                 sal_Int32 nFeatures /* = SEF_DEFAULT */,
                                 com::sun::star::awt::Point* pRefPoint /* = NULL */ )
{
    uno::Reference< beans::XPropertySet > xPropSet(xShape, uno::UNO_QUERY);
    if(xPropSet.is())
    {
        OUString aParentName; // parent maybe the pool in later versions
        OUString aNewName;
        std::vector< XMLPropertyState > xPropStates( GetPropertySetMapper()->Filter( xPropSet ) );

        if(xPropStates.size())
            aNewName = GetExport().GetAutoStylePool()->Find(
                XML_STYLE_FAMILY_SD_GRAPHICS_ID, aParentName, xPropStates);

        XmlShapeType eShapeType(XmlShapeTypeNotYetSet);

        SdXMLExport::ImpCalcShapeType(xShape, eShapeType);
        SdXMLExport::ImpWriteSingleShapeStyleInfo(GetExport(), xShape,
            XML_STYLE_FAMILY_SD_GRAPHICS_ID, aNewName, eShapeType);
    }
}

void XMLShapeExport::exportAutoStyles()
{
    // export all autostyle infos

    // ...for graphic
//  if(IsFamilyGraphicUsed())
    {
        GetExport().GetAutoStylePool()->exportXML(
            XML_STYLE_FAMILY_SD_GRAPHICS_ID,
            GetExport().GetDocHandler(),
            GetExport().GetMM100UnitConverter(),
            GetExport().GetNamespaceMap());
    }

    // ...for presentation
//  if(IsFamilyPresentationUsed())
    {
        GetExport().GetAutoStylePool()->exportXML(
            XML_STYLE_FAMILY_SD_PRESENTATION_ID,
            GetExport().GetDocHandler(),
            GetExport().GetMM100UnitConverter(),
            GetExport().GetNamespaceMap());
    }
}

<commit_msg>fixed missing refpoint and export feature<commit_after>/*************************************************************************
 *
 *  $RCSfile: shapeexport.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: cl $ $Date: 2000-11-15 12:18:13 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library 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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _COM_SUN_STAR_TEXT_XTEXT_HPP_
#include <com/sun/star/text/XText.hpp>
#endif

#ifndef _COM_SUN_STAR_CHART_XCHARTDOCUMENT_HPP_
#include <com/sun/star/chart/XChartDocument.hpp>
#endif

#ifndef _XMLOFF_SHAPEEXPORT_HXX
#include "shapeexport.hxx"
#endif

#ifndef _SDPROPLS_HXX
#include "sdpropls.hxx"
#endif

#ifndef _SDXMLEXP_HXX
#include "sdxmlexp.hxx"
#endif

#ifndef _XMLOFF_FAMILIES_HXX_
#include "families.hxx"
#endif

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

using namespace ::rtl;
using namespace ::com::sun::star;

//////////////////////////////////////////////////////////////////////////////

XMLShapeExport::XMLShapeExport(SvXMLExport& rExp,
                                SvXMLExportPropertyMapper *pExtMapper )
:   rExport( rExp )
{
    // construct PropertyHandlerFactory
    xSdPropHdlFactory = new XMLSdPropHdlFactory;

    // construct PropertySetMapper
    UniReference < XMLPropertySetMapper > xMapper =
        new XMLPropertySetMapper(
            (XMLPropertyMapEntry*)aXMLSDProperties, xSdPropHdlFactory);
    xPropertySetMapper = new SvXMLExportPropertyMapper( xMapper );
    if( pExtMapper )
    {
        UniReference < SvXMLExportPropertyMapper > xExtMapper( pExtMapper );
        xPropertySetMapper->ChainExportMapper( xExtMapper );
    }

    rExp.GetAutoStylePool()->AddFamily(
        XML_STYLE_FAMILY_SD_GRAPHICS_ID,
        OUString(RTL_CONSTASCII_USTRINGPARAM(XML_STYLE_FAMILY_SD_GRAPHICS_NAME)),
        GetPropertySetMapper(),
        OUString(RTL_CONSTASCII_USTRINGPARAM(XML_STYLE_FAMILY_SD_GRAPHICS_PREFIX)));
    rExp.GetAutoStylePool()->AddFamily(
        XML_STYLE_FAMILY_SD_PRESENTATION_ID,
        OUString(RTL_CONSTASCII_USTRINGPARAM(XML_STYLE_FAMILY_SD_PRESENTATION_NAME)),
        GetPropertySetMapper(),
        OUString(RTL_CONSTASCII_USTRINGPARAM(XML_STYLE_FAMILY_SD_PRESENTATION_PREFIX)));
}

XMLShapeExport::~XMLShapeExport()
{
}

// This method collects all automatic styles for the given XShape
void XMLShapeExport::collectShapeAutoStyles(const uno::Reference< drawing::XShape >& xShape)
{
    uno::Reference< beans::XPropertySet > xPropSet(xShape, uno::UNO_QUERY);
    if(xPropSet.is())
    {
        // filter propset
        OUString aParentName; // parent maybe the pool in later versions
        OUString aNewName;
        std::vector< XMLPropertyState > xPropStates = GetPropertySetMapper()->Filter( xPropSet );

        if(xPropStates.size())
        {
            // there are filtered properties -> hard attributes
            // try to find this style in AutoStylePool
            aNewName = GetExport().GetAutoStylePool()->Find(
                XML_STYLE_FAMILY_SD_GRAPHICS_ID, aParentName, xPropStates);

            if(!aNewName.getLength())
            {
                // Style did not exist, add it to AutoStalePool
                GetExport().GetAutoStylePool()->Add(
                    XML_STYLE_FAMILY_SD_GRAPHICS_ID, aParentName, xPropStates);
            }
        }
    }

    // prep text styles
    uno::Reference< text::XText > xText(xShape, uno::UNO_QUERY);
    if(xText.is())
    {
        uno::Reference< beans::XPropertySetInfo > xPropSetInfo( xPropSet->getPropertySetInfo() );

        sal_Bool bIsEmptyPresObj = sal_False;

        if( xPropSetInfo.is() && xPropSetInfo->hasPropertyByName(OUString(RTL_CONSTASCII_USTRINGPARAM("IsEmptyPresentationObject"))))
        {
            uno::Any aAny = xPropSet->getPropertyValue(OUString(RTL_CONSTASCII_USTRINGPARAM("IsEmptyPresentationObject")));
            aAny >>= bIsEmptyPresObj;
        }

        if(!bIsEmptyPresObj)
        {
            GetExport().GetTextParagraphExport()->collectTextAutoStyles( xText );
        }
    }

    // check for calc ole
    const OUString aShapeType( xShape->getShapeType() );
    if( (0 == aShapeType.reverseCompareToAsciiL( RTL_CONSTASCII_STRINGPARAM( "com.sun.star.drawing.OLE2Shape" ))) ||
        (0 == aShapeType.reverseCompareToAsciiL( RTL_CONSTASCII_STRINGPARAM( "com.sun.star.presentation.CalcShape" ))) )
    {
        uno::Reference< chart::XChartDocument > xChartDoc;
        uno::Any aAny( xPropSet->getPropertyValue( OUString(RTL_CONSTASCII_USTRINGPARAM("Model") ) ) );
        aAny >>= xChartDoc;
        if( xChartDoc.is() )
        {
            GetExport().GetChartExport()->collectAutoStyles( xChartDoc );
        }
    }
}

// This method exports the given XShape
void XMLShapeExport::exportShape(const uno::Reference< drawing::XShape >& xShape,
                                 sal_Int32 nFeatures /* = SEF_DEFAULT */,
                                 com::sun::star::awt::Point* pRefPoint /* = NULL */ )
{
    uno::Reference< beans::XPropertySet > xPropSet(xShape, uno::UNO_QUERY);
    if(xPropSet.is())
    {
        OUString aParentName; // parent maybe the pool in later versions
        OUString aNewName;
        std::vector< XMLPropertyState > xPropStates( GetPropertySetMapper()->Filter( xPropSet ) );

        if(xPropStates.size())
            aNewName = GetExport().GetAutoStylePool()->Find(
                XML_STYLE_FAMILY_SD_GRAPHICS_ID, aParentName, xPropStates);

        XmlShapeType eShapeType(XmlShapeTypeNotYetSet);

        SdXMLExport::ImpCalcShapeType(xShape, eShapeType);
        SdXMLExport::ImpWriteSingleShapeStyleInfo(GetExport(), xShape,
            XML_STYLE_FAMILY_SD_GRAPHICS_ID, aNewName, eShapeType, nFeatures, pRefPoint);
    }
}

void XMLShapeExport::exportAutoStyles()
{
    // export all autostyle infos

    // ...for graphic
//  if(IsFamilyGraphicUsed())
    {
        GetExport().GetAutoStylePool()->exportXML(
            XML_STYLE_FAMILY_SD_GRAPHICS_ID,
            GetExport().GetDocHandler(),
            GetExport().GetMM100UnitConverter(),
            GetExport().GetNamespaceMap());
    }

    // ...for presentation
//  if(IsFamilyPresentationUsed())
    {
        GetExport().GetAutoStylePool()->exportXML(
            XML_STYLE_FAMILY_SD_PRESENTATION_ID,
            GetExport().GetDocHandler(),
            GetExport().GetMM100UnitConverter(),
            GetExport().GetNamespaceMap());
    }
}

<|endoftext|>