<commit_before>/**
 * This file is part of Slideshow.
 * Copyright (C) 2008-2010 David Sveningsson <ext@sidvind.com>
 *
 * Slideshow is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * Slideshow 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Slideshow.  If not, see <http://www.gnu.org/licenses/>.
 */

#ifdef HAVE_CONFIG_H
#	include "config.h"
#endif

#include "exception.h"
#include "Graphics.h"
#include "Kernel.h"
#include "module_loader.h"
#include "OS.h"
#include "Log.h"
#include "Transition.h"
#include "path.h"
#include "gl.h"
#include "ptr.h"

#include <cstdlib>
#include <cstring>
#include <memory>

#include <portable/string.h>

/* hack to get opengl functions, does not seem to be used in header even when
 * built with opengl support. */
#define ILUT_USE_OPENGL

#include <IL/il.h>
#include <IL/ilu.h>
#include <IL/ilut.h>

Graphics::Graphics(int width, int height, bool fullscreen):
	_transition(NULL),
	_width(width),
	_height(height){

	for ( unsigned int i = 0; i < 2; i++ ){
		_texture[i] = 0;
	}

	Log::verbose("Graphics: Using resoultion %dx%d\n", width, height);

	glew_init();
	imageloader_init();
	gl_setup();
	gl_set_matrices();
	gl_init_textures();
}

Graphics::~Graphics(){
	gl_cleanup_textures();
	imageloader_cleanup();
	glew_cleanup();
	module_close(&_transition->base);
}

void Graphics::glew_init(){
	GLenum err = glewInit();

	if (GLEW_OK != err){
		throw exception("Failed to initialize glew");
	}

	if ( !GLEW_VERSION_2_0 ){
		Log::warning("Graphics card does not support OpenGL 2.0+\n");
	}

	if (!GLEW_ARB_texture_non_power_of_two){
		Log::warning("Graphics card does not support ARB_texture_non_power_of_two, performance will suffer\n");
	}
}

void Graphics::glew_cleanup(){

}

void Graphics::imageloader_init(){
	ilInit();

	ILuint devilError = ilGetError();

	if (devilError != IL_NO_ERROR) {
		throw exception("Devil Error (ilInit: %s)", iluErrorString(devilError));
	}

	iluInit();
	ilutRenderer(ILUT_OPENGL);
}

void Graphics::imageloader_cleanup(){

}

void Graphics::gl_setup(){
	glShadeModel( GL_FLAT );
	glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST );
	glClearColor(0, 0, 0, 1);
	glColor4f(1, 1, 1, 1);

	glDisable( GL_DEPTH_TEST );
	glDisable( GL_LIGHTING );
	glDisable(GL_ALPHA_TEST);

	glEnable( GL_TEXTURE_2D );
	glEnable(GL_BLEND);
	glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	glClear( GL_COLOR_BUFFER_BIT );
}

void Graphics::gl_set_matrices(){
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();

	glOrtho(0, 1, 0, 1, -1.0, 1.0);
	glScalef(1, -1, 1);
	glTranslated(0, -1, 0);

	glEnable(GL_CULL_FACE);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
}

void Graphics::gl_init_textures(){
	glGenTextures(2, _texture);

	for ( unsigned int i = 0; i < 2; i++ ){
		glBindTexture(GL_TEXTURE_2D, _texture[i]);

		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	}
}

void Graphics::gl_cleanup_textures(){
	glDeleteTextures(2, _texture);
}

void Graphics::render(float state){
	transition_context_t context;

	context.texture[0] = _texture[0];
	context.texture[1] = _texture[1];
	context.state = state;

	if ( _transition ){
		_transition->render(&context);
	}
}

#ifdef WIN32
/* convert to LPCTSTR, release memory with free */
static TCHAR* to_tchar(const char* src){
	size_t len = 0;
	TCHAR* buf = NULL;

	if ( mbstowcs_s(&len, NULL, 0, src, _TRUNCATE) != 0 ){
		return NULL;
	}

	buf = (TCHAR*)malloc(sizeof(TCHAR) * (len+1));

	if ( mbstowcs_s(&len, buf, len+1, src, _TRUNCATE) != 0 ){
		return NULL;
	}

	return buf;
}

/* convert from LPCTSTR, release memory with free */
static char* from_tchar(const TCHAR* src){
	size_t len = 0;
	char* buf = NULL;

	if ( wcstombs_s(&len, NULL, 0, src, _TRUNCATE) != 0 ){
		return NULL;
	}

	buf = (char*)malloc(sizeof(char) * (len+1));

	if ( wcstombs_s(&len, buf, len+1, src, _TRUNCATE) != 0 ){
		return NULL;
	}

	return buf;
}
#endif /* WIN32 */

/**
 * Check if a filename has the .slide-extension.
 */
static bool __attribute__ ((pure))  __attribute__((nonnull)) is_slide(const char* name){
	static const char ext[] = ".slide";
	const ssize_t offset = strlen(name) - sizeof(ext) + 1; /* +1 for null terminator */

	/* name is shorter than extension */
	if ( offset < 0 ){
		return false;
	}

	return strcmp(name + offset, ext) == 0;
}

static bool __attribute__((pure)) __attribute__((nonnull)) is_url(const char* name){
	static const char prefix[] = "http://";
	return strncmp(name, prefix, strlen(prefix)) == 0;
}

void Graphics::load_file(const char* filename){
	Log::debug("Loading '%s' as local file.\n", filename);

	Ptr<char> real_name(strdup(filename));
	if ( is_slide(filename) ){
		real_name.reset(asprintf2("%s/raster/%dx%d.png", filename, _width, _height));
	}

#ifdef UNICODE
	char* tmp = real_path(real_name.get());
	Ptr<wchar_t> path(to_tchar(tmp));
	free(tmp);
#else /* UNICODE */
	Ptr<char> path(real_path(real_name.get()));
#endif /* UNICODE */

	ILuint devilID;

	/* load image @todo Dont generate buffer each time */
	ilGenImages(1, &devilID);
	ilBindImage(devilID);
	ilLoadImage(path.get());
	ILuint devilError = ilGetError();

	if( devilError != IL_NO_ERROR ){
#ifdef UNICODE
		const wchar_t* asdf = iluErrorString (devilError);
		const char* error = from_tchar(asdf);
#else /* UNICODE */
		const char* error = iluErrorString (devilError);
#endif /* UNICODE */
		throw exception("Failed to load image '%s' (ilLoadImage: %s)", path.get(), error);
	}

	ILubyte* pixels = ilGetData();
	int width  = ilGetInteger(IL_IMAGE_WIDTH);
	int height = ilGetInteger(IL_IMAGE_HEIGHT);
	int format = ilGetInteger(IL_IMAGE_FORMAT);

	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, format, GL_UNSIGNED_BYTE, pixels);

	/* free buffer */
	ilDeleteImages(1, &devilID);
}

void Graphics::load_url(const char* url){
	Log::debug("Loading '%s' as remote image.\n", url);
	throw exception("not implemented");
}

void Graphics::load_blank(){
	Log::debug("Loading blank image.\n");

	static const unsigned char black[] = {
		0, 0, 0
	};

	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1, 1, 0, GL_BGR_EXT, GL_UNSIGNED_BYTE, black);
}

void Graphics::load_image(const char* name){
	swap_textures();

	glBindTexture(GL_TEXTURE_2D, _texture[0]);

	/* null is passed when the screen should go blank (e.g. queue is empty) */
	if ( !name ){
		load_blank();
		return;
	}

	if ( is_url(name) ) {
		load_url(name);
	} else {
		load_file(name);
	}
}

void Graphics::swap_textures(){
	unsigned int tmp = _texture[0];
	_texture[0] = _texture[1];
	_texture[1] = tmp;
}

void Graphics::set_transition(const char* name){
	module_close(&_transition->base);
	_transition = (transition_module_t*)module_open(name, TRANSITION_MODULE, 0);
}
<commit_msg>adding assertions, null-checks and comments where needed<commit_after>/**
 * This file is part of Slideshow.
 * Copyright (C) 2008-2010 David Sveningsson <ext@sidvind.com>
 *
 * Slideshow is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * Slideshow 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Slideshow.  If not, see <http://www.gnu.org/licenses/>.
 */

#ifdef HAVE_CONFIG_H
#	include "config.h"
#endif

#include "exception.h"
#include "Graphics.h"
#include "Kernel.h"
#include "module_loader.h"
#include "OS.h"
#include "Log.h"
#include "Transition.h"
#include "path.h"
#include "gl.h"
#include "ptr.h"

#include <cstdlib>
#include <cstring>
#include <memory>
#include <cassert>

#include <portable/string.h>

/* hack to get opengl functions, does not seem to be used in header even when
 * built with opengl support. */
#define ILUT_USE_OPENGL

#include <IL/il.h>
#include <IL/ilu.h>
#include <IL/ilut.h>

Graphics::Graphics(int width, int height, bool fullscreen):
	_transition(NULL),
	_width(width),
	_height(height){

	for ( unsigned int i = 0; i < 2; i++ ){
		_texture[i] = 0;
	}

	Log::verbose("Graphics: Using resoultion %dx%d\n", width, height);

	glew_init();
	imageloader_init();
	gl_setup();
	gl_set_matrices();
	gl_init_textures();
}

Graphics::~Graphics(){
	gl_cleanup_textures();
	imageloader_cleanup();
	glew_cleanup();
	module_close(&_transition->base);
}

void Graphics::glew_init(){
	GLenum err = glewInit();

	if (GLEW_OK != err){
		throw exception("Failed to initialize glew");
	}

	if ( !GLEW_VERSION_2_0 ){
		Log::warning("Graphics card does not support OpenGL 2.0+\n");
	}

	if (!GLEW_ARB_texture_non_power_of_two){
		Log::warning("Graphics card does not support ARB_texture_non_power_of_two, performance will suffer\n");
	}
}

void Graphics::glew_cleanup(){

}

void Graphics::imageloader_init(){
	ilInit();

	ILuint devilError = ilGetError();

	if (devilError != IL_NO_ERROR) {
		throw exception("Devil Error (ilInit: %s)", iluErrorString(devilError));
	}

	iluInit();
	ilutRenderer(ILUT_OPENGL);
}

void Graphics::imageloader_cleanup(){

}

void Graphics::gl_setup(){
	glShadeModel( GL_FLAT );
	glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST );
	glClearColor(0, 0, 0, 1);
	glColor4f(1, 1, 1, 1);

	glDisable( GL_DEPTH_TEST );
	glDisable( GL_LIGHTING );
	glDisable(GL_ALPHA_TEST);

	glEnable( GL_TEXTURE_2D );
	glEnable(GL_BLEND);
	glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	glClear( GL_COLOR_BUFFER_BIT );
}

void Graphics::gl_set_matrices(){
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();

	glOrtho(0, 1, 0, 1, -1.0, 1.0);
	glScalef(1, -1, 1);
	glTranslated(0, -1, 0);

	glEnable(GL_CULL_FACE);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
}

void Graphics::gl_init_textures(){
	glGenTextures(2, _texture);

	for ( unsigned int i = 0; i < 2; i++ ){
		glBindTexture(GL_TEXTURE_2D, _texture[i]);

		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	}
}

void Graphics::gl_cleanup_textures(){
	glDeleteTextures(2, _texture);
}

void Graphics::render(float state){
	transition_context_t context;

	context.texture[0] = _texture[0];
	context.texture[1] = _texture[1];
	context.state = state;

	if ( _transition ){
		_transition->render(&context);
	}
}

#ifdef WIN32
/* convert to LPCTSTR, release memory with free */
static TCHAR* to_tchar(const char* src){
	assert(src);
	size_t len = 0;
	TCHAR* buf = NULL;

	if ( mbstowcs_s(&len, NULL, 0, src, _TRUNCATE) != 0 ){
		return NULL;
	}

	buf = (TCHAR*)malloc(sizeof(TCHAR) * (len+1));

	if ( mbstowcs_s(&len, buf, len+1, src, _TRUNCATE) != 0 ){
		return NULL;
	}

	return buf;
}

/* convert from LPCTSTR, release memory with free */
static char* from_tchar(const TCHAR* src){
	assert(src);
	size_t len = 0;
	char* buf = NULL;

	if ( wcstombs_s(&len, NULL, 0, src, _TRUNCATE) != 0 ){
		return NULL;
	}

	buf = (char*)malloc(sizeof(char) * (len+1));

	if ( wcstombs_s(&len, buf, len+1, src, _TRUNCATE) != 0 ){
		return NULL;
	}

	return buf;
}
#endif /* WIN32 */

/**
 * Check if a filename has the .slide-extension.
 */
static bool __attribute__ ((pure))  __attribute__((nonnull)) is_slide(const char* name){
	if ( !name ) return false;
	static const char ext[] = ".slide";
	const ssize_t offset = strlen(name) - sizeof(ext) + 1; /* +1 for null terminator */

	/* name is shorter than extension */
	if ( offset < 0 ){
		return false;
	}

	return strcmp(name + offset, ext) == 0;
}

/**
 * Test if given name is a URL.
 */
static bool __attribute__((pure)) __attribute__((nonnull)) is_url(const char* name){
	if ( !name ) return false;
	static const char prefix[] = "http://";
	return strncmp(name, prefix, strlen(prefix)) == 0;
}

void Graphics::load_file(const char* filename){
	assert(filename);

	Log::debug("Loading '%s' as local file.\n", filename);

	Ptr<char> real_name(strdup(filename));
	if ( is_slide(filename) ){
		real_name.reset(asprintf2("%s/raster/%dx%d.png", filename, _width, _height));
	}

#ifdef UNICODE
	char* tmp = real_path(real_name.get());
	Ptr<wchar_t> path(to_tchar(tmp));
	free(tmp);
#else /* UNICODE */
	Ptr<char> path(real_path(real_name.get()));
#endif /* UNICODE */

	ILuint devilID;

	/* load image @todo Dont generate buffer each time */
	ilGenImages(1, &devilID);
	ilBindImage(devilID);
	ilLoadImage(path.get());
	ILuint devilError = ilGetError();

	if( devilError != IL_NO_ERROR ){
#ifdef UNICODE
		const wchar_t* asdf = iluErrorString (devilError);
		const char* error = from_tchar(asdf);
#else /* UNICODE */
		const char* error = iluErrorString (devilError);
#endif /* UNICODE */
		throw exception("Failed to load image '%s' (ilLoadImage: %s)", path.get(), error);
	}

	ILubyte* pixels = ilGetData();
	int width  = ilGetInteger(IL_IMAGE_WIDTH);
	int height = ilGetInteger(IL_IMAGE_HEIGHT);
	int format = ilGetInteger(IL_IMAGE_FORMAT);

	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, format, GL_UNSIGNED_BYTE, pixels);

	/* free buffer */
	ilDeleteImages(1, &devilID);
}

void Graphics::load_url(const char* url){
	assert(url);

	Log::debug("Loading '%s' as remote image.\n", url);
	throw exception("not implemented");
}

void Graphics::load_blank(){
	Log::debug("Loading blank image.\n");

	static const unsigned char black[] = {
		0, 0, 0
	};

	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1, 1, 0, GL_BGR_EXT, GL_UNSIGNED_BYTE, black);
}

void Graphics::load_image(const char* name){
	swap_textures();

	glBindTexture(GL_TEXTURE_2D, _texture[0]);

	/* null is passed when the screen should go blank (e.g. queue is empty) */
	if ( !name ){
		load_blank();
		return;
	}

	if ( is_url(name) ) {
		load_url(name);
	} else {
		load_file(name);
	}
}

void Graphics::swap_textures(){
	unsigned int tmp = _texture[0];
	_texture[0] = _texture[1];
	_texture[1] = tmp;
}

void Graphics::set_transition(const char* name){
	assert(name);
	module_close(&_transition->base);
	_transition = (transition_module_t*)module_open(name, TRANSITION_MODULE, 0);
}
<|endoftext|>


<commit_before>#include <iostream>
#include <cstdio>
#include <vector>
#include <set>
#include <map>
#include <cstdlib>
#include <algorithm>
#include <sstream>
#include <queue>
#include <stack>
#include <ctime>
#include <iomanip>
#include <cmath>

#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif

using namespace std;

#define pb push_back
#define mp make_pair
#define S second
#define F first

//basic typedef
typedef long long ll;
typedef long double ld;
typedef pair<ld, ld> pld;
//structs
struct pt{ //point
    ld x, y;
};

struct ln{ //line
    ld a, b, c;
};

struct sg{ //segment
    pt a, b;
};

typedef vector<pt> pl; //polygon

//constructors
pt mpt (ld x, ld y) {
    pt obj;
    obj.x = x;
    obj.y = y;
    return obj;
}

ln mln (ld a, ld b, ld c) {
    ln obj;
    obj.a = a;
    obj.b = b;
    obj.c = c;
    return obj;
}

sg msg (pt a, pt b) {
    sg obj;
    obj.a = a;
    obj.b = b;
    return obj;
}
//io tricks
ostream &operator<<(ostream &os, pt const &p) {
    return os << p.x << " " << p.y;
}

istream &operator>>(istream &is, pt &p) {
    return is >> p.x >> p.y;
}

istream &operator>>(istream &is, ln &l) {
    return is >> l.a >> l.b >> l.c;
}

void ny (bool x) {
    if (x) cout << "YES";
    else cout << "NO";
    exit(0);
}
//consts
const ld ldINF = 1e+018;
const ld EPS = 1e-009;
const pt Npt = mpt(ldINF, ldINF);
const pld Npld = mp(ldINF, ldINF);
const sg Nsg = msg(Npt, Npt);
//equals
bool eq (ld x, ld y) {
    return fabs(x - y) < EPS;
}

bool eq (ln x, ln y) {
    return eq(x.a, y.a) && eq(x.b, y.b) && eq(x.c, y.c);
}

bool eq (pt x, pt y) {
    return eq(x.x, y.x) && eq(x.y, y.y);
}

bool eq (sg x, sg y) {
    return eq(x.a, y.a) && eq(x.b, y.b);
}
//Basic algos
int fsign (ld x) {
    if (eq(x, 0)) return 0;
    if (x > 0) return 1;
    return -1;
}

pld solveSquare (ld a, ld b, ld c) { //ax^2 + bx + c = 0
    if (eq(a, 0)) {
        if (eq(b, 0)) return Npld;
        pld ans;
        ans.F = ans.S = (-c) / b;
        return ans;
    }
    ld D = sqrt(b * b - 4 * a * c);
    pld ans;
    ans.F = (-b + D) / (2 * a);
    ans.S = (-b - D) / (2 * a);
    return ans;
}

pld segsInsc (ld l1, ld r1, ld l2, ld r2) { //intersect of two segments
    if (l1 > r1) swap(l1, r1);
    if (l2 > r2) swap(l2, r2);
    if (l1 > l2) {
        swap(l1, l2);
        swap(r1, r2);
    }
    if (l2 > r1) return Npld;
    pld ans;
    ans.F = l2;
    ans.S = min(r1, r2);
    return ans;
}

bool into (ld x, ld l, ld r) {
    if (l > r) swap(l, r);
    return x >= l && x <= r;
}

ld dist (pt p1, pt p2) { //Pythagoras
    return sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
}

ld multVect (pt s, pt v1, pt v2) { //v1 * v2
    return (v2.x - s.x) * (v1.y - s.y) - (v2.y - s.y) * (v1.x - s.x);
}
//line algos
ln makeln (pt p1, pt p2) {
    ln t;
    if (!eq(p1.y, p2.y)) {
        t.a = 1;
        t.b = (t.a * (p1.x - p2.x)) / (p2.y - p1.y);
    } else {
        t.b = 1;
        t.a = (t.b * (p2.y - p1.y)) / (p1.x - p2.x);
    }
    t.c = -(t.a * p1.x + t.b * p1.y);
    return t;
}

pt intersect (ln t1, ln t2) {
    pt r;
    if (eq(t2.a * t1.b - t2.b * t1.a, 0)) return Npt;
    if (eq(t1.a, 0)) swap(t1, t2);
    r.y = (t1.a * t2.c - t1.c * t2.a) / (t2.a * t1.b - t2.b * t1.a);
    r.x = (t1.b * r.y + t1.c) / (-t1.a);
    return r;
}

pt perp (ln l, pt p) { //perpendicular
    ld t = -(l.a * p.x + l.b * p.y + l.c) / (l.a * l.a + l.b * l.b);
    return mpt(p.x + t * l.a, p.y + t * l.b);
}

ld dist (ln l, pt p) { //perpendicular
    return fabs(l.a * p.x + l.b * p.y + l.c) / sqrt(l.a * l.a + l.b * l.b);
}

ln moveToPt (ln l, pt p) { //parallel line trough pt
    l.c = -(l.a * p.x + l.b * p.y);
    return l;
}

ld findX (ln t, ld y) {
    return (-t.b * y - t.c) / t.a;
}

ld findY (ln t, ld x) {
    return (-t.a * x - t.c) / t.b;
}

int ptRels (ln l, pt p) {
    return fsign(l.a * p.x + l.b * p.y + l.c);
}
//Areas
ld triangleArea (pt p1, pt p2, pt p3) {
    return fabs(multVect(p1, p2, p3)) / 2;
}
//segs algos
ln makeln (sg s) {
    return makeln(s.a, s.b);
}

int ptRels (sg s, pt p) {
    return fsign(multVect(s.a, s.b, p));
}

pt intersect (sg s, pt p) {
    if (into(p.x, s.a.x, s.b.x) && into(p.y, s.a.y, s.b.y) && ptRels(s, p) == 0) return p;
    return Npt;
}

sg intersect2 (sg x, sg y) {
    if (eq(x.a, x.b)) {
        if (eq(y.a, y.b))
        if (eq(x, y)) return x;
        else return Nsg;
        pt p = intersect(y, x.a);
        if (eq(p, Npt)) return Nsg;
        return msg(p, p);
    }
    if (eq(y.a, y.b)) {
        swap(x, y);
        pt p = intersect(y, x.a);
        if (eq(p, Npt)) return Nsg;
        return msg(p, p);
    }
    ln l1, l2;
    l1 = makeln(x);
    l2 = makeln(y);
    if (eq(l1, l2)) {
        if (eq(l1.b, 0)) {
            pld f = segsInsc(x.a.y, x.b.y, y.a.y, y.b.y);
            if (f == Npld) return Nsg;
            return msg(mpt(findX(l1, f.F), f.F), mpt(findX(l1, f.S), f.S));
        }
        pld f = segsInsc(x.a.x, x.b.x, y.a.x, y.b.x);
        if (f == Npld) return Nsg;
        return msg(mpt(f.F, findY(l1, f.F)), mpt(f.S, findY(l1, f.S)));
    }
    pt p = intersect(l1, l2);
    if (eq(p, Npt))
        return Nsg;
    if (into(p.x, x.a.x, x.b.x) && into(p.y, x.a.y, x.b.y) && into(p.x, y.a.x, y.b.x) && into(p.y, y.a.y, y.b.y))
        return msg(p, p);
    return Nsg;
}

ld dist (sg s, pt p) {
    pt x = perp(makeln(s), p);
    if (eq(intersect(s, x), Npt))
        return min(dist(s.a, p), dist(s.b, p));
    return dist(x, p);
}
//Rays
bool isOnRay (pt s, pt d, pt t) {
    return eq(s, t) || !ptRels(msg(s, d), t) && fsign(d.x - s.x) == fsign(t.x - s.x) && fsign(d.y - s.y) == fsign(t.y - s.y);
}

ld distRay (pt s, pt d, pt t) {
    pt px = perp(makeln(s, d), t);
    if (!isOnRay(s, d, px)) px = s;
    return dist(t, px);
}

ld fangle (pt p) {
    ld a = atan(p.y / p.x);
    if (p.y == 0 && p.x > 0) return 0;
    if (p.x < 0) return M_PI + a;
    if (p.y > 0) return a;
    return 2 * M_PI + a;

}
//Polygons
ld polygonArea (pl p) {
    ld s = 0;
    pt last = p.back();
    for (int i = 0; i < p.size(); i++) {
        s += (p[i].y + last.y) * (p[i].x - last.x);
        last = p[i];
    }
    return fabs(s / 2);
}

ll fpts (pl p) {
    pt last = p.back();
    ll pts = 0;
    for (int i = 0; i < p.size(); i++) {
        ll x = round(fabs(p[i].x - last.x));
        ll y = round(fabs(p[i].y - last.y));
        pts += __gcd(x, y);
        last = p[i];
    }
    return pts;
}

ll pickTheorem (pl p) {
    return (round(polygonArea(p)) * 2 - fpts(p) + 2) / 2;
}

int main() {

    return 0;
}
<commit_msg>Added circles algos<commit_after>#include <iostream>
#include <cstdio>
#include <vector>
#include <set>
#include <map>
#include <cstdlib>
#include <algorithm>
#include <sstream>
#include <queue>
#include <stack>
#include <ctime>
#include <iomanip>
#include <cmath>

#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif

using namespace std;

#define pb push_back
#define mp make_pair
#define S second
#define F first

//basic typedef
typedef long long ll;
typedef long double ld;
typedef pair<ld, ld> pld;
//structs
struct pt{ //point
    ld x, y;
};

struct ln{ //line
    ld a, b, c;
};

struct sg{ //segment
    pt a, b;
};

struct cr{ //circle
    pt c;
    ld r;
};

typedef vector<pt> pl; //polygon

//constructors
pt mpt (ld x, ld y) {
    pt obj;
    obj.x = x;
    obj.y = y;
    return obj;
}

ln mln (ld a, ld b, ld c) {
    ln obj;
    obj.a = a;
    obj.b = b;
    obj.c = c;
    return obj;
}

sg msg (pt a, pt b) {
    sg obj;
    obj.a = a;
    obj.b = b;
    return obj;
}

cr mcr (pt c, ld r) {
    cr t;
    t.c = c;
    t.r = r;
    return t;
}
//io tricks
ostream &operator<<(ostream &os, pt const &p) {
    return os << p.x << " " << p.y;
}

ostream &operator<<(ostream &os, sg const &s) {
    return os << "{(" << s.a << ") (" << s.b << ")}";
}

istream &operator>>(istream &is, pt &p) {
    return is >> p.x >> p.y;
}

istream &operator>>(istream &is, ln &l) {
    return is >> l.a >> l.b >> l.c;
}

void ny (bool x) {
    if (x) cout << "YES";
    else cout << "NO";
    exit(0);
}
//consts
const ld ldINF = 1e+018;
const ld EPS = 1e-009;
const pt Npt = mpt(ldINF, ldINF);
const pld Npld = mp(ldINF, ldINF);
const sg Nsg = msg(Npt, Npt);
//equals
bool eq (ld x, ld y) {
    return fabs(x - y) < EPS;
}

bool eq (ln x, ln y) {
    return eq(x.a, y.a) && eq(x.b, y.b) && eq(x.c, y.c);
}

bool eq (pt x, pt y) {
    return eq(x.x, y.x) && eq(x.y, y.y);
}

bool eq (sg x, sg y) {
    return eq(x.a, y.a) && eq(x.b, y.b);
}

bool eq (cr x, cr y) {
    return eq(x.c, y.c) && eq(x.r, y.r);
}

bool eq (pld x, pld y) {
    return eq(x.F, y.F) && eq(x.S, y.S);
}
//Basic algos
int fsign (ld x) {
    if (eq(x, 0)) return 0;
    if (x > 0) return 1;
    return -1;
}

pld solveSquare (ld a, ld b, ld c) { //ax^2 + bx + c = 0
    if (eq(a, 0)) {
        if (eq(b, 0)) return Npld;
        pld ans;
        ans.F = ans.S = (-c) / b;
        return ans;
    }
    ld D = sqrt(b * b - 4 * a * c);
    pld ans;
    ans.F = (-b + D) / (2 * a);
    ans.S = (-b - D) / (2 * a);
    return ans;
}

pld segsInsc (ld l1, ld r1, ld l2, ld r2) { //intersect of two segments
    if (l1 > r1) swap(l1, r1);
    if (l2 > r2) swap(l2, r2);
    if (l1 > l2) {
        swap(l1, l2);
        swap(r1, r2);
    }
    if (l2 > r1) return Npld;
    pld ans;
    ans.F = l2;
    ans.S = min(r1, r2);
    return ans;
}

bool into (ld x, ld l, ld r) {
    if (l > r) swap(l, r);
    return x >= l && x <= r;
}

ld dist (pt p1, pt p2) { //Pythagoras
    return sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
}

ld multVect (pt s, pt v1, pt v2) { //v1 * v2
    return (v2.x - s.x) * (v1.y - s.y) - (v2.y - s.y) * (v1.x - s.x);
}
//line algos
ln makeln (pt p1, pt p2) {
    ln t;
    if (!eq(p1.y, p2.y)) {
        t.a = 1;
        t.b = (t.a * (p1.x - p2.x)) / (p2.y - p1.y);
    } else {
        t.b = 1;
        t.a = (t.b * (p2.y - p1.y)) / (p1.x - p2.x);
    }
    t.c = -(t.a * p1.x + t.b * p1.y);
    return t;
}

pt intersect (ln t1, ln t2) {
    pt r;
    if (eq(t2.a * t1.b - t2.b * t1.a, 0)) return Npt;
    if (eq(t1.a, 0)) swap(t1, t2);
    r.y = (t1.a * t2.c - t1.c * t2.a) / (t2.a * t1.b - t2.b * t1.a);
    r.x = (t1.b * r.y + t1.c) / (-t1.a);
    return r;
}

pt perp (ln l, pt p) { //perpendicular
    ld t = -(l.a * p.x + l.b * p.y + l.c) / (l.a * l.a + l.b * l.b);
    return mpt(p.x + t * l.a, p.y + t * l.b);
}

ld dist (ln l, pt p) { //perpendicular
    return fabs(l.a * p.x + l.b * p.y + l.c) / sqrt(l.a * l.a + l.b * l.b);
}

ln moveToPt (ln l, pt p) { //parallel line trough pt
    l.c = -(l.a * p.x + l.b * p.y);
    return l;
}

ld findX (ln t, ld y) {
    return (-t.b * y - t.c) / t.a;
}

ld findY (ln t, ld x) {
    return (-t.a * x - t.c) / t.b;
}

int ptRels (ln l, pt p) {
    return fsign(l.a * p.x + l.b * p.y + l.c);
}
//Areas
ld triangleArea (pt p1, pt p2, pt p3) {
    return fabs(multVect(p1, p2, p3)) / 2;
}
//segs algos
ln makeln (sg s) {
    return makeln(s.a, s.b);
}

int ptRels (sg s, pt p) {
    return fsign(multVect(s.a, s.b, p));
}

pt intersect (sg s, pt p) {
    if (into(p.x, s.a.x, s.b.x) && into(p.y, s.a.y, s.b.y) && ptRels(s, p) == 0) return p;
    return Npt;
}

sg intersect2 (sg x, sg y) {
    if (eq(x.a, x.b)) {
        if (eq(y.a, y.b))
        if (eq(x, y)) return x;
        else return Nsg;
        pt p = intersect(y, x.a);
        if (eq(p, Npt)) return Nsg;
        return msg(p, p);
    }
    if (eq(y.a, y.b)) {
        swap(x, y);
        pt p = intersect(y, x.a);
        if (eq(p, Npt)) return Nsg;
        return msg(p, p);
    }
    ln l1, l2;
    l1 = makeln(x);
    l2 = makeln(y);
    if (eq(l1, l2)) {
        if (eq(l1.b, 0)) {
            pld f = segsInsc(x.a.y, x.b.y, y.a.y, y.b.y);
            if (f == Npld) return Nsg;
            return msg(mpt(findX(l1, f.F), f.F), mpt(findX(l1, f.S), f.S));
        }
        pld f = segsInsc(x.a.x, x.b.x, y.a.x, y.b.x);
        if (f == Npld) return Nsg;
        return msg(mpt(f.F, findY(l1, f.F)), mpt(f.S, findY(l1, f.S)));
    }
    pt p = intersect(l1, l2);
    if (eq(p, Npt))
        return Nsg;
    if (into(p.x, x.a.x, x.b.x) && into(p.y, x.a.y, x.b.y) && into(p.x, y.a.x, y.b.x) && into(p.y, y.a.y, y.b.y))
        return msg(p, p);
    return Nsg;
}

ld dist (sg s, pt p) {
    pt x = perp(makeln(s), p);
    if (eq(intersect(s, x), Npt))
        return min(dist(s.a, p), dist(s.b, p));
    return dist(x, p);
}
//Rays
bool isOnRay (pt s, pt d, pt t) {
    return eq(s, t) || !ptRels(msg(s, d), t) && fsign(d.x - s.x) == fsign(t.x - s.x) && fsign(d.y - s.y) == fsign(t.y - s.y);
}

ld distRay (pt s, pt d, pt t) {
    pt px = perp(makeln(s, d), t);
    if (!isOnRay(s, d, px)) px = s;
    return dist(t, px);
}

ld fangle (pt p) {
    ld a = atan(p.y / p.x);
    if (p.y == 0 && p.x > 0) return 0;
    if (p.x < 0) return M_PI + a;
    if (p.y > 0) return a;
    return 2 * M_PI + a;
}

ld fangle (pt p, pt a, pt b) {
    a.x -= p.x;
    a.y -= p.y;
    b.x -= p.x;
    b.y -= p.y;
    ld x = fabs(fangle(a) - fangle(b));
    return min(x, 2 * M_PI - x);
}
//Polygons
ld polygonArea (pl p) {
    ld s = 0;
    pt last = p.back();
    for (int i = 0; i < p.size(); i++) {
        s += (p[i].y + last.y) * (p[i].x - last.x);
        last = p[i];
    }
    return fabs(s / 2);
}

ll fpts (pl p) {
    pt last = p.back();
    ll pts = 0;
    for (int i = 0; i < p.size(); i++) {
        ll x = round(fabs(p[i].x - last.x));
        ll y = round(fabs(p[i].y - last.y));
        pts += __gcd(x, y);
        last = p[i];
    }
    return pts;
}

ll pickTheorem (pl p) {
    return (round(polygonArea(p)) * 2 - fpts(p) + 2) / 2;
}
//Circles
sg intersect(cr c, ln l) {
    if (!eq(l.a, 0)) {
        ld ta, tb, tc;
        ta = (l.b * l.b / l.a / l.a) + 1;
        tb = 2 * l.b * l.c / l.a / l.a;
        tb += 2 * l.b * c.c.x / l.a;
        tb -= 2 * c.c.y;
        tc = c.c.x * c.c.x;
        tc += c.c.y * c.c.y;
        tc += 2 * l.c * c.c.x / l.a;
        tc += l.c * l.c / l.a / l.a;
        tc -= c.r * c.r;
        pld ans = solveSquare(ta, tb, tc);
        if (eq(ans, Npld)) return Nsg;
        ld x0 = (-l.b * ans.F - l.c) / l.a;
        ld x1 = (-l.b * ans.S - l.c) / l.a;
        return msg(mpt(x0, ans.F), mpt(x1, ans.S));
    }
    ld y = (-l.c) / l.b;
    ld ta, tb, tc;
    ta = 1;
    tb = -2 * c.c.x;
    tc = c.c.x * c.c.x + y * y + c.c.y * c.c.y - 2 * y * c.c.y - c.r * c.r;
    pld ans = solveSquare(ta, tb, tc);
    if (eq(ans, Npld)) return Nsg;
    return msg(mpt(ans.F, y), mpt(ans.S, y));
}

sg intersect (cr c1, cr c2) {
    return intersect(c1, mln(-2 * c2.c.x, -2 * c2.c.y,
                             c2.c.x * c2.c.x + c2.c.y * c2.c.y + c1.r * c1.r - c2.r * c2.r));
}
//Very specific algos
ln rot90 (pt p1, pt p2, pt p) {
    ln l = makeln(p1, p2);
    l = makeln(mpt(0, 0), mpt(l.a, l.b));
    return moveToPt(l, p);
}

pt ptRay (pt p1, pt p2, ld l) {
    sg s = intersect(mcr(p1, l), makeln(p1, p2));
    if (isOnRay(p1, p2, s.a)) return s.a;
    return s.b;
}

int main() {

    return 0;
}
<|endoftext|>


<commit_before>/*********************************************************************
 *
 * Condor ClassAd library
 * Copyright (C) 1990-2001, CONDOR Team, Computer Sciences Department,
 * University of Wisconsin-Madison, WI, and Rajesh Raman.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of version 2.1 of the GNU Lesser General
 * Public License 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
 *
 *********************************************************************/

#include "common.h"
#include "exprTree.h"
#include "xmlSink.h"
#include "sink.h"
#include "xmlLexer.h"
#include "util.h"

using namespace std;
extern  time_t timezone;

BEGIN_NAMESPACE( classad )

static void add_tag(
    string &buffer,
	XMLLexer::TagID  tag_id,
	XMLLexer::TagType tag_type,
	const char *attribute_name = NULL,
	const char *attribute_value = NULL);

ClassAdXMLUnParser::
ClassAdXMLUnParser()
{
	compact_spacing = true;
	return;
}

ClassAdXMLUnParser::
~ClassAdXMLUnParser()
{
	return;
}

void ClassAdXMLUnParser::
SetCompactSpacing(
	bool use_compact_spacing)
{
	compact_spacing = use_compact_spacing;
	return;
}

void ClassAdXMLUnParser::Unparse(
	string    &buffer,
	ExprTree  *expr)
{
	Unparse(buffer, expr, 0);
	return;
}

void ClassAdXMLUnParser::
Unparse(
	string   &buffer,
	ExprTree *tree,
	int      indent)
{
	if( !tree ) {
		buffer = "<error:null expr>";
		return;
	} else {

		switch( tree->GetKind( ) ) {
		case ExprTree::LITERAL_NODE: {
			Value				val;
			Value::NumberFactor	factor;
			((Literal*)tree)->GetComponents(val, factor);
			Unparse(buffer, val, indent);
			break;
		}
		case ExprTree::ATTRREF_NODE:
		case ExprTree::OP_NODE:
		case ExprTree::FN_CALL_NODE: {
			ClassAdUnParser unparser;
			add_tag(buffer, XMLLexer::tagID_Expr, XMLLexer::tagType_Start);
			unparser.setXMLUnparse(true);
			unparser.Unparse(buffer, tree);
			add_tag(buffer, XMLLexer::tagID_Expr, XMLLexer::tagType_End);
			break;
		}

		case ExprTree::CLASSAD_NODE: {
			vector< pair<string, ExprTree*> > attrs;
			((ClassAd*)tree)->GetComponents(attrs);
			UnparseAux(buffer, attrs, indent);
			break;
		}

		case ExprTree::EXPR_LIST_NODE: {
			vector<ExprTree*> exprs;
			((ExprList*)tree)->GetComponents(exprs);
			UnparseAux(buffer, exprs, indent);
			break;
		}

		default:
			buffer = "";
			CondorErrno = ERR_BAD_EXPRESSION;
			CondorErrMsg = "unknown expression type";
			break;
		}
	}
	return;
}

void ClassAdXMLUnParser::
Unparse(
	string &buffer,
	Value  &val,
	int    indent)
{
	char tempBuf[512];

	switch( val.GetType( ) ) {
		case Value::NULL_VALUE:
			// I don't think this ever occurs. Am I correct?
			//buffer += "<null/>";
			break;

		case Value::STRING_VALUE: {
			string	               s;
			add_tag(buffer, XMLLexer::tagID_String, XMLLexer::tagType_Start);
			ClassAdUnParser unp;
			unp.setXMLUnparse(true);
			unp.setDelimiter(0); // change the default delimiter from \" to no delimiter
			unp.Unparse(s,val);
			s.erase(0,1);
			s.erase(s.length()-1,1);
			buffer += s;
			add_tag(buffer, XMLLexer::tagID_String, XMLLexer::tagType_End);
			break;
		}
		case Value::INTEGER_VALUE: {
			int	i;
			val.IsIntegerValue(i);
			sprintf(tempBuf, "%d", i);
			add_tag(buffer, XMLLexer::tagID_Integer, XMLLexer::tagType_Start);
			buffer += tempBuf;
			add_tag(buffer, XMLLexer::tagID_Integer, XMLLexer::tagType_End);
			break;
		}
		case Value::REAL_VALUE: {
			double real;

			val.IsRealValue(real);
			double_to_hex(real, tempBuf);
			add_tag(buffer, XMLLexer::tagID_Real, XMLLexer::tagType_Start);
			buffer += tempBuf;
			add_tag(buffer, XMLLexer::tagID_Real, XMLLexer::tagType_End);
			break;
		}
		case Value::BOOLEAN_VALUE: {
			bool b;
			val.IsBooleanValue( b );
			if (b) {
				add_tag(buffer, XMLLexer::tagID_Bool,
						XMLLexer::tagType_Empty, "v", "t");
			} else {
				add_tag(buffer, XMLLexer::tagID_Bool,
						XMLLexer::tagType_Empty, "v", "f");
			}
			break;;
		}
		case Value::UNDEFINED_VALUE: {
			add_tag(buffer, XMLLexer::tagID_Undefined,
					XMLLexer::tagType_Empty);
			break;
		}
		case Value::ERROR_VALUE: {
			add_tag(buffer, XMLLexer::tagID_Error,
					XMLLexer::tagType_Empty);
			break;
		}
		case Value::ABSOLUTE_TIME_VALUE: {
       			add_tag(buffer, XMLLexer::tagID_AbsoluteTime, XMLLexer::tagType_Start);
			ClassAdUnParser unp;
			string abstimestr;
			unp.Unparse(abstimestr,val);
			abstimestr.erase(0,9);
			abstimestr.erase(abstimestr.length()-2,2);
			buffer += abstimestr;
			add_tag(buffer, XMLLexer::tagID_AbsoluteTime, XMLLexer::tagType_End);
			break;
		}
		case Value::RELATIVE_TIME_VALUE: {
			add_tag(buffer, XMLLexer::tagID_RelativeTime, XMLLexer::tagType_Start);
			ClassAdUnParser unp;
			string reltimestr;
			unp.Unparse(reltimestr,val);
			reltimestr.erase(0,9);
			reltimestr.erase(reltimestr.length()-2,2);
			buffer += reltimestr;
			add_tag(buffer, XMLLexer::tagID_RelativeTime, XMLLexer::tagType_End);
			break;
		}
		case Value::CLASSAD_VALUE: {
			ClassAd *ad;
			vector< pair<string,ExprTree*> > attrs;
			val.IsClassAdValue(ad);
			ad->GetComponents(attrs);
			UnparseAux(buffer, attrs, indent);
			break;
		}
		case Value::LIST_VALUE: {
			const ExprList *el;
			vector<ExprTree*> exprs;
			val.IsListValue(el);
			el->GetComponents(exprs);
			UnparseAux(buffer, exprs, indent);
			break;
		}
	}
}

void ClassAdXMLUnParser::
UnparseAux(string                           &buffer,
		   vector< pair<string,ExprTree*> > &attrs,
		   int                              indent)
{
	vector< pair<string,ExprTree*> >::const_iterator itr;

	add_tag(buffer, XMLLexer::tagID_ClassAd, XMLLexer::tagType_Start);
	if (!compact_spacing) {
		buffer += '\n';
	}
	for (itr=attrs.begin(); itr!=attrs.end(); itr++) {
		if (!compact_spacing) {
			buffer.append(indent+4, ' ');
		}
		Value val;
		val.SetStringValue(itr->first);
		string idstr;
		ClassAdUnParser unp;
		unp.setXMLUnparse(true);
		unp.Unparse(idstr,val);
		idstr.erase(0,1);
		idstr.erase(idstr.length()-1,1);
		add_tag(buffer, XMLLexer::tagID_Attribute, XMLLexer::tagType_Start,
				"n", idstr.c_str());
		Unparse(buffer, itr->second, indent+4);
		add_tag(buffer, XMLLexer::tagID_Attribute, XMLLexer::tagType_End);
		if (!compact_spacing) {
			buffer += '\n';
		}
	}
	if (!compact_spacing) {
		buffer.append(indent, ' ');
	}
	add_tag(buffer, XMLLexer::tagID_ClassAd, XMLLexer::tagType_End);
	if (!compact_spacing && indent == 0) {
		buffer += '\n';
	}
	return;
}

void ClassAdXMLUnParser::
UnparseAux(
	string             &buffer,
	vector<ExprTree*>  &exprs,
	int                indent)
{
	vector<ExprTree*>::const_iterator	itr;

	add_tag(buffer, XMLLexer::tagID_List, XMLLexer::tagType_Start);
	for(itr = exprs.begin(); itr != exprs.end(); itr++) {
		Unparse(buffer, *itr, indent);
	}
	add_tag(buffer, XMLLexer::tagID_List, XMLLexer::tagType_End);
}

static void add_tag(
    string             &buffer,
	XMLLexer::TagID    tag_id,
	XMLLexer::TagType  tag_type,
	const char         *attribute_name,
	const char         *attribute_value)
{
	buffer += '<';
	if (tag_type == XMLLexer::tagType_End) {
		buffer += '/';
	}
	buffer += tag_mappings[tag_id].tag_name;
	if (attribute_name != NULL && attribute_value != NULL) {
		buffer += ' ';
		buffer += attribute_name;
		buffer += "=\"";
		buffer += attribute_value;
		buffer +=  '\"';
	}
	if (tag_type == XMLLexer::tagType_Empty) {
		buffer += '/';
	}
	buffer += '>';
}

/*
static void
UnparseRelativeTime(string &buffer, time_t rsecs)
{
	int	  days, hrs, mins, secs;
	char  tempBuf[512];

	if( rsecs < 0 ) {
		buffer += "-";
		rsecs = -rsecs;
	}
	days = rsecs;
	hrs  = days % 86400;
	mins = hrs  % 3600;
	secs = mins % 60;
	days = days / 86400;
	hrs  = hrs  / 3600;
	mins = mins / 60;

	if (days) {
		sprintf( tempBuf, "%dd", days );
		buffer += tempBuf;
	}

	sprintf(tempBuf, "%02d:%02d", hrs, mins);
	buffer += tempBuf;

	if (secs) {
		sprintf(tempBuf, ":%02d", secs);
		buffer += tempBuf;
	}
	return;
}
*/

END_NAMESPACE
<commit_msg>Added DLL_IMPORT macro to allow us to build on Windows.<commit_after>/*********************************************************************
 *
 * Condor ClassAd library
 * Copyright (C) 1990-2001, CONDOR Team, Computer Sciences Department,
 * University of Wisconsin-Madison, WI, and Rajesh Raman.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of version 2.1 of the GNU Lesser General
 * Public License 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
 *
 *********************************************************************/

#include "common.h"
#include "exprTree.h"
#include "xmlSink.h"
#include "sink.h"
#include "xmlLexer.h"
#include "util.h"

using namespace std;
extern DLL_IMPORT_MAGIC time_t timezone;

BEGIN_NAMESPACE( classad )

static void add_tag(
    string &buffer,
	XMLLexer::TagID  tag_id,
	XMLLexer::TagType tag_type,
	const char *attribute_name = NULL,
	const char *attribute_value = NULL);

ClassAdXMLUnParser::
ClassAdXMLUnParser()
{
	compact_spacing = true;
	return;
}

ClassAdXMLUnParser::
~ClassAdXMLUnParser()
{
	return;
}

void ClassAdXMLUnParser::
SetCompactSpacing(
	bool use_compact_spacing)
{
	compact_spacing = use_compact_spacing;
	return;
}

void ClassAdXMLUnParser::Unparse(
	string    &buffer,
	ExprTree  *expr)
{
	Unparse(buffer, expr, 0);
	return;
}

void ClassAdXMLUnParser::
Unparse(
	string   &buffer,
	ExprTree *tree,
	int      indent)
{
	if( !tree ) {
		buffer = "<error:null expr>";
		return;
	} else {

		switch( tree->GetKind( ) ) {
		case ExprTree::LITERAL_NODE: {
			Value				val;
			Value::NumberFactor	factor;
			((Literal*)tree)->GetComponents(val, factor);
			Unparse(buffer, val, indent);
			break;
		}
		case ExprTree::ATTRREF_NODE:
		case ExprTree::OP_NODE:
		case ExprTree::FN_CALL_NODE: {
			ClassAdUnParser unparser;
			add_tag(buffer, XMLLexer::tagID_Expr, XMLLexer::tagType_Start);
			unparser.setXMLUnparse(true);
			unparser.Unparse(buffer, tree);
			add_tag(buffer, XMLLexer::tagID_Expr, XMLLexer::tagType_End);
			break;
		}

		case ExprTree::CLASSAD_NODE: {
			vector< pair<string, ExprTree*> > attrs;
			((ClassAd*)tree)->GetComponents(attrs);
			UnparseAux(buffer, attrs, indent);
			break;
		}

		case ExprTree::EXPR_LIST_NODE: {
			vector<ExprTree*> exprs;
			((ExprList*)tree)->GetComponents(exprs);
			UnparseAux(buffer, exprs, indent);
			break;
		}

		default:
			buffer = "";
			CondorErrno = ERR_BAD_EXPRESSION;
			CondorErrMsg = "unknown expression type";
			break;
		}
	}
	return;
}

void ClassAdXMLUnParser::
Unparse(
	string &buffer,
	Value  &val,
	int    indent)
{
	char tempBuf[512];

	switch( val.GetType( ) ) {
		case Value::NULL_VALUE:
			// I don't think this ever occurs. Am I correct?
			//buffer += "<null/>";
			break;

		case Value::STRING_VALUE: {
			string	               s;
			add_tag(buffer, XMLLexer::tagID_String, XMLLexer::tagType_Start);
			ClassAdUnParser unp;
			unp.setXMLUnparse(true);
			unp.setDelimiter(0); // change the default delimiter from \" to no delimiter
			unp.Unparse(s,val);
			s.erase(0,1);
			s.erase(s.length()-1,1);
			buffer += s;
			add_tag(buffer, XMLLexer::tagID_String, XMLLexer::tagType_End);
			break;
		}
		case Value::INTEGER_VALUE: {
			int	i;
			val.IsIntegerValue(i);
			sprintf(tempBuf, "%d", i);
			add_tag(buffer, XMLLexer::tagID_Integer, XMLLexer::tagType_Start);
			buffer += tempBuf;
			add_tag(buffer, XMLLexer::tagID_Integer, XMLLexer::tagType_End);
			break;
		}
		case Value::REAL_VALUE: {
			double real;

			val.IsRealValue(real);
			double_to_hex(real, tempBuf);
			add_tag(buffer, XMLLexer::tagID_Real, XMLLexer::tagType_Start);
			buffer += tempBuf;
			add_tag(buffer, XMLLexer::tagID_Real, XMLLexer::tagType_End);
			break;
		}
		case Value::BOOLEAN_VALUE: {
			bool b;
			val.IsBooleanValue( b );
			if (b) {
				add_tag(buffer, XMLLexer::tagID_Bool,
						XMLLexer::tagType_Empty, "v", "t");
			} else {
				add_tag(buffer, XMLLexer::tagID_Bool,
						XMLLexer::tagType_Empty, "v", "f");
			}
			break;;
		}
		case Value::UNDEFINED_VALUE: {
			add_tag(buffer, XMLLexer::tagID_Undefined,
					XMLLexer::tagType_Empty);
			break;
		}
		case Value::ERROR_VALUE: {
			add_tag(buffer, XMLLexer::tagID_Error,
					XMLLexer::tagType_Empty);
			break;
		}
		case Value::ABSOLUTE_TIME_VALUE: {
       			add_tag(buffer, XMLLexer::tagID_AbsoluteTime, XMLLexer::tagType_Start);
			ClassAdUnParser unp;
			string abstimestr;
			unp.Unparse(abstimestr,val);
			abstimestr.erase(0,9);
			abstimestr.erase(abstimestr.length()-2,2);
			buffer += abstimestr;
			add_tag(buffer, XMLLexer::tagID_AbsoluteTime, XMLLexer::tagType_End);
			break;
		}
		case Value::RELATIVE_TIME_VALUE: {
			add_tag(buffer, XMLLexer::tagID_RelativeTime, XMLLexer::tagType_Start);
			ClassAdUnParser unp;
			string reltimestr;
			unp.Unparse(reltimestr,val);
			reltimestr.erase(0,9);
			reltimestr.erase(reltimestr.length()-2,2);
			buffer += reltimestr;
			add_tag(buffer, XMLLexer::tagID_RelativeTime, XMLLexer::tagType_End);
			break;
		}
		case Value::CLASSAD_VALUE: {
			ClassAd *ad;
			vector< pair<string,ExprTree*> > attrs;
			val.IsClassAdValue(ad);
			ad->GetComponents(attrs);
			UnparseAux(buffer, attrs, indent);
			break;
		}
		case Value::LIST_VALUE: {
			const ExprList *el;
			vector<ExprTree*> exprs;
			val.IsListValue(el);
			el->GetComponents(exprs);
			UnparseAux(buffer, exprs, indent);
			break;
		}
	}
}

void ClassAdXMLUnParser::
UnparseAux(string                           &buffer,
		   vector< pair<string,ExprTree*> > &attrs,
		   int                              indent)
{
	vector< pair<string,ExprTree*> >::const_iterator itr;

	add_tag(buffer, XMLLexer::tagID_ClassAd, XMLLexer::tagType_Start);
	if (!compact_spacing) {
		buffer += '\n';
	}
	for (itr=attrs.begin(); itr!=attrs.end(); itr++) {
		if (!compact_spacing) {
			buffer.append(indent+4, ' ');
		}
		Value val;
		val.SetStringValue(itr->first);
		string idstr;
		ClassAdUnParser unp;
		unp.setXMLUnparse(true);
		unp.Unparse(idstr,val);
		idstr.erase(0,1);
		idstr.erase(idstr.length()-1,1);
		add_tag(buffer, XMLLexer::tagID_Attribute, XMLLexer::tagType_Start,
				"n", idstr.c_str());
		Unparse(buffer, itr->second, indent+4);
		add_tag(buffer, XMLLexer::tagID_Attribute, XMLLexer::tagType_End);
		if (!compact_spacing) {
			buffer += '\n';
		}
	}
	if (!compact_spacing) {
		buffer.append(indent, ' ');
	}
	add_tag(buffer, XMLLexer::tagID_ClassAd, XMLLexer::tagType_End);
	if (!compact_spacing && indent == 0) {
		buffer += '\n';
	}
	return;
}

void ClassAdXMLUnParser::
UnparseAux(
	string             &buffer,
	vector<ExprTree*>  &exprs,
	int                indent)
{
	vector<ExprTree*>::const_iterator	itr;

	add_tag(buffer, XMLLexer::tagID_List, XMLLexer::tagType_Start);
	for(itr = exprs.begin(); itr != exprs.end(); itr++) {
		Unparse(buffer, *itr, indent);
	}
	add_tag(buffer, XMLLexer::tagID_List, XMLLexer::tagType_End);
}

static void add_tag(
    string             &buffer,
	XMLLexer::TagID    tag_id,
	XMLLexer::TagType  tag_type,
	const char         *attribute_name,
	const char         *attribute_value)
{
	buffer += '<';
	if (tag_type == XMLLexer::tagType_End) {
		buffer += '/';
	}
	buffer += tag_mappings[tag_id].tag_name;
	if (attribute_name != NULL && attribute_value != NULL) {
		buffer += ' ';
		buffer += attribute_name;
		buffer += "=\"";
		buffer += attribute_value;
		buffer +=  '\"';
	}
	if (tag_type == XMLLexer::tagType_Empty) {
		buffer += '/';
	}
	buffer += '>';
}

/*
static void
UnparseRelativeTime(string &buffer, time_t rsecs)
{
	int	  days, hrs, mins, secs;
	char  tempBuf[512];

	if( rsecs < 0 ) {
		buffer += "-";
		rsecs = -rsecs;
	}
	days = rsecs;
	hrs  = days % 86400;
	mins = hrs  % 3600;
	secs = mins % 60;
	days = days / 86400;
	hrs  = hrs  / 3600;
	mins = mins / 60;

	if (days) {
		sprintf( tempBuf, "%dd", days );
		buffer += tempBuf;
	}

	sprintf(tempBuf, "%02d:%02d", hrs, mins);
	buffer += tempBuf;

	if (secs) {
		sprintf(tempBuf, ":%02d", secs);
		buffer += tempBuf;
	}
	return;
}
*/

END_NAMESPACE
<|endoftext|>


<commit_before>// File_DtvccTransport - Info for DTVCC Transport strams
// Copyright (C) 2010-2010 MediaArea.net SARL, Info@MediaArea.net
//
// 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 3 of the License, or
// 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.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library. If not, see <http://www.gnu.org/licenses/>.
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//---------------------------------------------------------------------------
// Compilation conditions
#include "MediaInfo/Setup.h"
#ifdef __BORLANDC__
    #pragma hdrstop
#endif
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#if defined(MEDIAINFO_DTVCCTRANSPORT_YES)
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Text/File_DtvccTransport.h"
#if defined(MEDIAINFO_EIA608_YES)
    #include "MediaInfo/Text/File_Eia608.h"
#endif
#if defined(MEDIAINFO_EIA708_YES)
    #include "MediaInfo/Text/File_Eia708.h"
#endif
//---------------------------------------------------------------------------
namespace MediaInfoLib
{
//---------------------------------------------------------------------------

//***************************************************************************
// Infos
//***************************************************************************

//---------------------------------------------------------------------------
const char* DtvccTransport_cc_type (int8u cc_type)
{
    switch (cc_type)
    {
        case  0 : return "CEA-608 line 21 field 1 closed captions"; //closed caption 3 if this is second field
        case  1 : return "CEA-608 line 21 field 2 closed captions"; //closed caption 4 if this is second field
        case  2 : return "DTVCC Channel Packet Data";
        case  3 : return "DTVCC Channel Packet Start";
        default : return "";
    }
}

//***************************************************************************
// Constructor/Destructor
//***************************************************************************

//---------------------------------------------------------------------------
File_DtvccTransport::File_DtvccTransport()
:File__Analyze()
{
    //Configuration
    PTS_DTS_Needed=true;

    //In
    Format=Format_Unknown;

    //Temp
    Streams.resize(3); //CEA-608 Field 1, CEA-608 Field 2, CEA-708 Channel
    Streams_Count=0;
}

//---------------------------------------------------------------------------
File_DtvccTransport::~File_DtvccTransport()
{
    for (size_t Pos=0; Pos<Streams.size(); Pos++)
        delete Streams[Pos]; //Streams[Pos]=NULL
}

//***************************************************************************
// Streams management
//***************************************************************************

//---------------------------------------------------------------------------
void File_DtvccTransport::Streams_Fill()
{
    //Filling
    for (size_t Pos=0; Pos<Streams.size(); Pos++)
        if (Streams[Pos] && Streams[Pos]->Parser && Streams[Pos]->Parser->Status[IsFilled])
        {
            Merge(*Streams[Pos]->Parser);
            if (Pos<2)
                Fill(Stream_Text, StreamPos_Last, Text_ID, (Format==Format_DVD?_T("DVD-"):_T("608-"))+Ztring::ToZtring(Pos));
            Fill(Stream_Text, StreamPos_Last, "MuxingMode", Format==Format_DVD?_T("DVD-Video"):_T("EIA-708"));
        }
}

//---------------------------------------------------------------------------
void File_DtvccTransport::Streams_Finish()
{
    //Filling
    for (size_t Pos=0; Pos<Streams.size(); Pos++)
        if (Streams[Pos] && Streams[Pos]->Parser && Streams[Pos]->Parser->Status[IsFilled])
            Finish(Streams[Pos]->Parser);
}

//***************************************************************************
// Buffer - Synchro
//***************************************************************************

//---------------------------------------------------------------------------
void File_DtvccTransport::Read_Buffer_Unsynched()
{
    //Parsing
    for (size_t Pos=0; Pos<Streams.size(); Pos++)
        if (Streams[Pos] && Streams[Pos]->Parser)
            Streams[Pos]->Parser->Open_Buffer_Unsynch();
}

//***************************************************************************
// Buffer - Global
//***************************************************************************

//---------------------------------------------------------------------------
void File_DtvccTransport::Read_Buffer_Continue()
{
    //Parsing
    Element_Begin(Format==Format_DVD?"DVD Captions":"DTVCC Transport");
    int8u  cc_count;
    bool   process_cc_data_flag, additional_data_flag;
    BS_Begin();
    if (Format==Format_DVD)
    {
        //Modified DTVCC Transport from DVD
        Skip_SB(                                                "field 1 then field 2");
        Get_S1 (7, cc_count,                                    "cc_count");
        process_cc_data_flag=true;
        additional_data_flag=false;
    }
    else
    {
        //Normal DTVCC Transport
        bool process_em_data_flag;
        Get_SB (process_em_data_flag,                           "process_em_data_flag");
        Get_SB (process_cc_data_flag,                           "process_cc_data_flag");
        Get_SB (additional_data_flag,                           "additional_data_flag");
        Get_S1 (5, cc_count,                                    "cc_count");
        Skip_S1(8,                                              process_em_data_flag?"em_data":"reserved"); //Emergency message
    }
    BS_End();
    if (process_cc_data_flag)
    {
        for (int8u Pos=0; Pos<cc_count; Pos++)
        {
            Element_Begin("cc");
            int8u cc_type;
            bool  cc_valid;
            BS_Begin();
            Mark_1();
            Mark_1_NoTrustError();
            Mark_1_NoTrustError();
            Mark_1_NoTrustError();
            Mark_1_NoTrustError();
            if (Format==Format_DVD)
            {
                //Modified DTVCC Transport from DVD
                Mark_1();
                Mark_1();
                Get_S1 (1, cc_type,                             "cc_type"); Param_Info(DtvccTransport_cc_type(cc_type));
                cc_valid=true;
            }
            else
            {
                //Normal DTVCC Transport
                Get_SB (   cc_valid,                            "cc_valid");
                Get_S1 (2, cc_type,                             "cc_type"); Param_Info(DtvccTransport_cc_type(cc_type));
            }
            BS_End();
            if (cc_valid)
            {
                Element_Begin("cc_data");
                    //Calculating the parser position
                    int8u Parser_Pos=cc_type==3?2:cc_type; //cc_type 2 and 3 are for the same text

                    //Parsing
                    if (Streams[Parser_Pos]==NULL)
                        Streams[Parser_Pos]=new stream;
                    if (Streams[Parser_Pos]->Parser==NULL)
                    {
                        if (cc_type<2)
                        {
                            Streams[Parser_Pos]->Parser=new File_Eia608();
                        }
                        else
                        {
                            Streams[Parser_Pos]->Parser=new File_Eia708();
                        }
                        Open_Buffer_Init(Streams[Parser_Pos]->Parser);
                    }
                    if (!Streams[Parser_Pos]->Parser->Status[IsFinished])
                    {
                        //Parsing
                        if (Streams[Parser_Pos]->Parser->PTS_DTS_Needed)
                        {
                            Streams[Parser_Pos]->Parser->PCR=PCR;
                            Streams[Parser_Pos]->Parser->PTS=PTS;
                            Streams[Parser_Pos]->Parser->DTS=DTS;
                        }
                        if (Parser_Pos==2)
                        {
                            ((File_Eia708*)Streams[2]->Parser)->cc_type=cc_type;
                        }
                        else
                        {
                        }
                        Open_Buffer_Continue(Streams[Parser_Pos]->Parser, Buffer+(size_t)(Buffer_Offset+Element_Offset), 2);
                        Element_Offset+=2;

                        //Filled
                        if (!Streams[Parser_Pos]->IsFilled && Streams[Parser_Pos]->Parser->Status[IsFilled])
                        {
                            if (Count_Get(Stream_General)==0)
                                Accept("DTVCC Transport");
                            Streams_Count++;
                            if (Streams_Count==3)
                                Fill("DTVCC Transport");
                            Streams[Parser_Pos]->IsFilled=true;
                        }
                    }
                    else
                        Skip_XX(2,                                  "Data");
                Element_End();
            }
            else
                Skip_XX(2,                                          "Junk");
            Element_End();
        }
    }
    else
        Skip_XX(cc_count*2,                                         "Junk");

    if (Format==Format_A53_4_GA94_03)
    {
        //Normal DTVCC Transport
        BS_Begin();
        Mark_1();
        Mark_1();
        Mark_1();
        Mark_1();
        Mark_1();
        Mark_1();
        Mark_1();
        Mark_1();
        BS_End();

        if (additional_data_flag)
        {
            Skip_XX(Element_Size-Element_Offset,                "additional_user_data");
        }

        while (Element_Offset<Element_Size)
        {
            Skip_B1(                                                "Zero"); //TODO: test Zero
        }
    }

    Element_End();
}

//***************************************************************************
// C++
//***************************************************************************

} //NameSpace

#endif //MEDIAINFO_DTVCCTRANSPORT_YES

<commit_msg><commit_after>// File_DtvccTransport - Info for DTVCC Transport strams
// Copyright (C) 2010-2010 MediaArea.net SARL, Info@MediaArea.net
//
// 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 3 of the License, or
// 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.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library. If not, see <http://www.gnu.org/licenses/>.
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//---------------------------------------------------------------------------
// Compilation conditions
#include "MediaInfo/Setup.h"
#ifdef __BORLANDC__
    #pragma hdrstop
#endif
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#if defined(MEDIAINFO_DTVCCTRANSPORT_YES)
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Text/File_DtvccTransport.h"
#if defined(MEDIAINFO_EIA608_YES)
    #include "MediaInfo/Text/File_Eia608.h"
#endif
#if defined(MEDIAINFO_EIA708_YES)
    #include "MediaInfo/Text/File_Eia708.h"
#endif
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
namespace MediaInfoLib
{
//---------------------------------------------------------------------------

//***************************************************************************
// Infos
//***************************************************************************

//---------------------------------------------------------------------------
const char* DtvccTransport_cc_type (int8u cc_type)
{
    switch (cc_type)
    {
        case  0 : return "CEA-608 line 21 field 1 closed captions"; //closed caption 3 if this is second field
        case  1 : return "CEA-608 line 21 field 2 closed captions"; //closed caption 4 if this is second field
        case  2 : return "DTVCC Channel Packet Data";
        case  3 : return "DTVCC Channel Packet Start";
        default : return "";
    }
}

//***************************************************************************
// Constructor/Destructor
//***************************************************************************

//---------------------------------------------------------------------------
File_DtvccTransport::File_DtvccTransport()
:File__Analyze()
{
    //Configuration
    PTS_DTS_Needed=true;

    //In
    Format=Format_Unknown;

    //Temp
    Streams.resize(3); //CEA-608 Field 1, CEA-608 Field 2, CEA-708 Channel
    Streams_Count=0;
}

//---------------------------------------------------------------------------
File_DtvccTransport::~File_DtvccTransport()
{
    for (size_t Pos=0; Pos<Streams.size(); Pos++)
        delete Streams[Pos]; //Streams[Pos]=NULL
}

//***************************************************************************
// Streams management
//***************************************************************************

//---------------------------------------------------------------------------
void File_DtvccTransport::Streams_Fill()
{
    //Filling
    for (size_t Pos=0; Pos<Streams.size(); Pos++)
        if (Streams[Pos] && Streams[Pos]->Parser && Streams[Pos]->Parser->Status[IsFilled])
        {
            Merge(*Streams[Pos]->Parser);
            if (Pos<2)
                Fill(Stream_Text, StreamPos_Last, Text_ID, (Format==Format_DVD?_T("DVD-"):_T("608-"))+Ztring::ToZtring(Pos));
            Fill(Stream_Text, StreamPos_Last, "MuxingMode", Format==Format_DVD?_T("DVD-Video"):_T("EIA-708"));
        }
}

//---------------------------------------------------------------------------
void File_DtvccTransport::Streams_Finish()
{
    //Filling
    for (size_t Pos=0; Pos<Streams.size(); Pos++)
        if (Streams[Pos] && Streams[Pos]->Parser && Streams[Pos]->Parser->Status[IsFilled])
            Finish(Streams[Pos]->Parser);
}

//***************************************************************************
// Buffer - Synchro
//***************************************************************************

//---------------------------------------------------------------------------
void File_DtvccTransport::Read_Buffer_Unsynched()
{
    //Parsing
    for (size_t Pos=0; Pos<Streams.size(); Pos++)
        if (Streams[Pos] && Streams[Pos]->Parser)
            Streams[Pos]->Parser->Open_Buffer_Unsynch();
}

//***************************************************************************
// Buffer - Global
//***************************************************************************

//---------------------------------------------------------------------------
void File_DtvccTransport::Read_Buffer_Continue()
{
    //Parsing
    Element_Begin(Format==Format_DVD?"DVD Captions":"DTVCC Transport");
    int8u  cc_count;
    bool   process_cc_data_flag, additional_data_flag;
    BS_Begin();
    if (Format==Format_DVD)
    {
        //Modified DTVCC Transport from DVD
        Skip_SB(                                                "field 1 then field 2");
        Get_S1 (7, cc_count,                                    "cc_count");
        process_cc_data_flag=true;
        additional_data_flag=false;
    }
    else
    {
        //Normal DTVCC Transport
        bool process_em_data_flag;
        Get_SB (process_em_data_flag,                           "process_em_data_flag");
        Get_SB (process_cc_data_flag,                           "process_cc_data_flag");
        Get_SB (additional_data_flag,                           "additional_data_flag");
        Get_S1 (5, cc_count,                                    "cc_count");
        Skip_S1(8,                                              process_em_data_flag?"em_data":"reserved"); //Emergency message
    }
    BS_End();
    if (process_cc_data_flag)
    {
        for (int8u Pos=0; Pos<cc_count; Pos++)
        {
            Element_Begin("cc");
            int8u cc_type;
            bool  cc_valid;
            BS_Begin();
            Mark_1();
            Mark_1_NoTrustError();
            Mark_1_NoTrustError();
            Mark_1_NoTrustError();
            Mark_1_NoTrustError();
            if (Format==Format_DVD)
            {
                //Modified DTVCC Transport from DVD
                Mark_1();
                Mark_1();
                Get_S1 (1, cc_type,                             "cc_type"); Param_Info(DtvccTransport_cc_type(cc_type));
                cc_valid=true;
            }
            else
            {
                //Normal DTVCC Transport
                Get_SB (   cc_valid,                            "cc_valid");
                Get_S1 (2, cc_type,                             "cc_type"); Param_Info(DtvccTransport_cc_type(cc_type));
            }
            BS_End();
            if (cc_valid)
            {
                Element_Begin("cc_data");
                    //Calculating the parser position
                    int8u Parser_Pos=cc_type==3?2:cc_type; //cc_type 2 and 3 are for the same text

                    //Parsing
                    if (Streams[Parser_Pos]==NULL)
                        Streams[Parser_Pos]=new stream;
                    if (Streams[Parser_Pos]->Parser==NULL)
                    {
                        if (cc_type<2)
                        {
                            Streams[Parser_Pos]->Parser=new File_Eia608();
                        }
                        else
                        {
                            Streams[Parser_Pos]->Parser=new File_Eia708();
                        }
                        Open_Buffer_Init(Streams[Parser_Pos]->Parser);
                    }
                    if (!Streams[Parser_Pos]->Parser->Status[IsFinished])
                    {
                        //Parsing
                        if (Streams[Parser_Pos]->Parser->PTS_DTS_Needed)
                        {
                            Streams[Parser_Pos]->Parser->PCR=PCR;
                            Streams[Parser_Pos]->Parser->PTS=PTS;
                            Streams[Parser_Pos]->Parser->DTS=DTS;
                        }
                        if (Parser_Pos==2)
                        {
                            ((File_Eia708*)Streams[2]->Parser)->cc_type=cc_type;
                        }
                        else
                        {
                        }
                        Open_Buffer_Continue(Streams[Parser_Pos]->Parser, Buffer+(size_t)(Buffer_Offset+Element_Offset), 2);
                        Element_Offset+=2;

                        //Filled
                        if (!Streams[Parser_Pos]->IsFilled && Streams[Parser_Pos]->Parser->Status[IsFilled])
                        {
                            if (Count_Get(Stream_General)==0)
                                Accept("DTVCC Transport");
                            Streams_Count++;
                            if (Streams_Count==3)
                                Fill("DTVCC Transport");
                            Streams[Parser_Pos]->IsFilled=true;
                        }
                    }
                    else
                        Skip_XX(2,                                  "Data");
                Element_End();
            }
            else
                Skip_XX(2,                                          "Junk");
            Element_End();
        }
    }
    else
        Skip_XX(cc_count*2,                                         "Junk");

    if (Format==Format_A53_4_GA94_03)
    {
        //Normal DTVCC Transport
        BS_Begin();
        Mark_1();
        Mark_1();
        Mark_1();
        Mark_1();
        Mark_1();
        Mark_1();
        Mark_1();
        Mark_1();
        BS_End();

        if (additional_data_flag)
        {
            Skip_XX(Element_Size-Element_Offset,                "additional_user_data");
        }

        while (Element_Offset<Element_Size)
        {
            Skip_B1(                                                "Zero"); //TODO: test Zero
        }
    }

    Element_End();
}

//***************************************************************************
// C++
//***************************************************************************

} //NameSpace

#endif //MEDIAINFO_DTVCCTRANSPORT_YES

<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

//  Software Guide : BeginLatex
//
//  This example illustrates how to deform an image using a KernelBase spline
//  and two sets of landmarks.
//
//  \index{WarpImageFilter}
//  \index{LandmarkDisplacementFieldSource}
//
//  In addition to standard headers included in previous examples, this example
//  requires the following includes:
//
//  Software Guide : EndLatex

#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkWarpImageFilter.h"
// Software Guide : BeginCodeSnippet
#include "itkVector.h"
#include "itkLandmarkDisplacementFieldSource.h"
#include <fstream>
// Software Guide : EndCodeSnippet

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

  if( argc < 3 )
    {
    std::cerr << "Missing Parameters " << std::endl;
    std::cerr << "Usage: " << argv[0];
    std::cerr << " landmarksFile fixedImage ";
    std::cerr << "movingImage deformedMovingImage" << std::endl;
    return EXIT_FAILURE;
    }

  const     unsigned int   Dimension = 2;
  typedef   float          VectorComponentType;

  typedef   itk::Vector< VectorComponentType, Dimension >    VectorType;

  typedef   itk::Image< VectorType, Dimension >   DisplacementFieldType;

  typedef   unsigned char                            PixelType;
  typedef   itk::Image< PixelType, Dimension >       FixedImageType;
  typedef   itk::Image< PixelType, Dimension >       MovingImageType;

  typedef   itk::ImageFileReader< FixedImageType  >  FixedReaderType;
  typedef   itk::ImageFileReader< MovingImageType >  MovingReaderType;

  typedef   itk::ImageFileWriter< MovingImageType >  MovingWriterType;

  FixedReaderType::Pointer fixedReader = FixedReaderType::New();
  fixedReader->SetFileName( argv[2] );

  try
    {
    fixedReader->Update();
    }
  catch( itk::ExceptionObject & excp )
    {
    std::cerr << "Exception thrown " << std::endl;
    std::cerr << excp << std::endl;
    return EXIT_FAILURE;
    }

  MovingReaderType::Pointer movingReader = MovingReaderType::New();
  MovingWriterType::Pointer movingWriter = MovingWriterType::New();

  movingReader->SetFileName( argv[3] );
  movingWriter->SetFileName( argv[4] );

  FixedImageType::ConstPointer fixedImage = fixedReader->GetOutput();

//  Software Guide : BeginLatex
//
//  After reading in the fixed and moving images, the \code{deformer} object is
//  instantiated from the \code{itk::LandmarkDisplacementFieldSource} class, and
//  parameters of the image space and orientation are set.
//
//  Software Guide : EndLatex

// Software Guide : BeginCodeSnippet

  typedef itk::LandmarkDisplacementFieldSource<
                                DisplacementFieldType
                                             >  DisplacementSourceType;

  DisplacementSourceType::Pointer deformer = DisplacementSourceType::New();

  deformer->SetOutputSpacing( fixedImage->GetSpacing() );
  deformer->SetOutputOrigin(  fixedImage->GetOrigin() );
  deformer->SetOutputRegion(  fixedImage->GetLargestPossibleRegion() );
  deformer->SetOutputDirection( fixedImage->GetDirection() );

// Software Guide : EndCodeSnippet

//  Software Guide : BeginLatex
//
//  Source and target landmarks are then created, and the points themselves are
//  read in from a file stream.
//
//  Software Guide : EndLatex

// Software Guide : BeginCodeSnippet

  typedef DisplacementSourceType::LandmarkContainer          LandmarkContainerType;
  typedef DisplacementSourceType::LandmarkPointType          LandmarkPointType;

  LandmarkContainerType::Pointer sourceLandmarks = LandmarkContainerType::New();
  LandmarkContainerType::Pointer targetLandmarks = LandmarkContainerType::New();

  LandmarkPointType sourcePoint;
  LandmarkPointType targetPoint;

  std::ifstream pointsFile;
  pointsFile.open( argv[1] );

  unsigned int pointId = 0;

  pointsFile >> sourcePoint;
  pointsFile >> targetPoint;

  while( !pointsFile.fail() )
    {
    sourceLandmarks->InsertElement( pointId, sourcePoint );
    targetLandmarks->InsertElement( pointId, targetPoint );
    ++pointId;

    pointsFile >> sourcePoint;
    pointsFile >> targetPoint;

    }

  pointsFile.close();

//  Software Guide : EndCodeSnippet

//  Software Guide : BeginLatex
//
//  The source and target landmark objects are then assigned to \code{deformer}.
//
//  Software Guide : EndLatex

//  Software Guide : BeginCodeSnippet

  deformer->SetSourceLandmarks( sourceLandmarks.GetPointer() );
  deformer->SetTargetLandmarks( targetLandmarks.GetPointer() );

//  Software Guide : EndCodeSnippet

//  Software Guide : BeginLatex
//
//  After calling \code{UpdateLargestPossibleRegion()} on the \code{deformer},
//  the displacement field may be obtained via the \code{GetOutput()} method.
//
//  Software Guide : EndLatex

  try
    {
    deformer->UpdateLargestPossibleRegion();
    }
  catch( itk::ExceptionObject & excp )
    {
    std::cerr << "Exception thrown " << std::endl;
    std::cerr << excp << std::endl;
    return EXIT_FAILURE;
    }

  DisplacementFieldType::ConstPointer displacementField = deformer->GetOutput();

  typedef itk::WarpImageFilter< MovingImageType,
                                MovingImageType,
                                DisplacementFieldType  >  FilterType;

  FilterType::Pointer warper = FilterType::New();

  typedef itk::LinearInterpolateImageFunction<
                       MovingImageType, double >  InterpolatorType;

  InterpolatorType::Pointer interpolator = InterpolatorType::New();

  warper->SetInterpolator( interpolator );

  warper->SetOutputSpacing( displacementField->GetSpacing() );
  warper->SetOutputOrigin(  displacementField->GetOrigin() );

  warper->SetDisplacementField( displacementField );

  warper->SetInput( movingReader->GetOutput() );

  movingWriter->SetInput( warper->GetOutput() );

  try
    {
    movingWriter->Update();
    }
  catch( itk::ExceptionObject & excp )
    {
    std::cerr << "Exception thrown " << std::endl;
    std::cerr << excp << std::endl;
    return EXIT_FAILURE;
    }

  return EXIT_SUCCESS;

}
<commit_msg>COMP: Tighten LandmarkWarping2 lines for Software Guide.<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

//  Software Guide : BeginLatex
//
//  This example illustrates how to deform an image using a KernelBase spline
//  and two sets of landmarks.
//
//  \index{WarpImageFilter}
//  \index{LandmarkDisplacementFieldSource}
//
//  In addition to standard headers included in previous examples, this example
//  requires the following includes:
//
//  Software Guide : EndLatex

#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkWarpImageFilter.h"
// Software Guide : BeginCodeSnippet
#include "itkVector.h"
#include "itkLandmarkDisplacementFieldSource.h"
#include <fstream>
// Software Guide : EndCodeSnippet

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

  if( argc < 3 )
    {
    std::cerr << "Missing Parameters " << std::endl;
    std::cerr << "Usage: " << argv[0];
    std::cerr << " landmarksFile fixedImage ";
    std::cerr << "movingImage deformedMovingImage" << std::endl;
    return EXIT_FAILURE;
    }

  const     unsigned int   Dimension = 2;
  typedef   float          VectorComponentType;

  typedef   itk::Vector< VectorComponentType, Dimension >    VectorType;

  typedef   itk::Image< VectorType, Dimension >   DisplacementFieldType;

  typedef   unsigned char                            PixelType;
  typedef   itk::Image< PixelType, Dimension >       FixedImageType;
  typedef   itk::Image< PixelType, Dimension >       MovingImageType;

  typedef   itk::ImageFileReader< FixedImageType  >  FixedReaderType;
  typedef   itk::ImageFileReader< MovingImageType >  MovingReaderType;

  typedef   itk::ImageFileWriter< MovingImageType >  MovingWriterType;

  FixedReaderType::Pointer fixedReader = FixedReaderType::New();
  fixedReader->SetFileName( argv[2] );

  try
    {
    fixedReader->Update();
    }
  catch( itk::ExceptionObject & excp )
    {
    std::cerr << "Exception thrown " << std::endl;
    std::cerr << excp << std::endl;
    return EXIT_FAILURE;
    }

  MovingReaderType::Pointer movingReader = MovingReaderType::New();
  MovingWriterType::Pointer movingWriter = MovingWriterType::New();

  movingReader->SetFileName( argv[3] );
  movingWriter->SetFileName( argv[4] );

  FixedImageType::ConstPointer fixedImage = fixedReader->GetOutput();

//  Software Guide : BeginLatex
//
//  After reading in the fixed and moving images, the \code{deformer} object is
//  instantiated from the \code{itk::LandmarkDisplacementFieldSource} class, and
//  parameters of the image space and orientation are set.
//
//  Software Guide : EndLatex

// Software Guide : BeginCodeSnippet

  typedef itk::LandmarkDisplacementFieldSource<
                                DisplacementFieldType
                                             >  DisplacementSourceType;

  DisplacementSourceType::Pointer deformer = DisplacementSourceType::New();

  deformer->SetOutputSpacing( fixedImage->GetSpacing() );
  deformer->SetOutputOrigin(  fixedImage->GetOrigin() );
  deformer->SetOutputRegion(  fixedImage->GetLargestPossibleRegion() );
  deformer->SetOutputDirection( fixedImage->GetDirection() );

// Software Guide : EndCodeSnippet

//  Software Guide : BeginLatex
//
//  Source and target landmarks are then created, and the points themselves are
//  read in from a file stream.
//
//  Software Guide : EndLatex

// Software Guide : BeginCodeSnippet

  typedef DisplacementSourceType::LandmarkContainer LandmarkContainerType;
  typedef DisplacementSourceType::LandmarkPointType LandmarkPointType;

  LandmarkContainerType::Pointer sourceLandmarks =
    LandmarkContainerType::New();
  LandmarkContainerType::Pointer targetLandmarks =
    LandmarkContainerType::New();

  LandmarkPointType sourcePoint;
  LandmarkPointType targetPoint;

  std::ifstream pointsFile;
  pointsFile.open( argv[1] );

  unsigned int pointId = 0;

  pointsFile >> sourcePoint;
  pointsFile >> targetPoint;

  while( !pointsFile.fail() )
    {
    sourceLandmarks->InsertElement( pointId, sourcePoint );
    targetLandmarks->InsertElement( pointId, targetPoint );
    ++pointId;

    pointsFile >> sourcePoint;
    pointsFile >> targetPoint;

    }

  pointsFile.close();

//  Software Guide : EndCodeSnippet

//  Software Guide : BeginLatex
//
//  The source and target landmark objects are then assigned to \code{deformer}.
//
//  Software Guide : EndLatex

//  Software Guide : BeginCodeSnippet

  deformer->SetSourceLandmarks( sourceLandmarks.GetPointer() );
  deformer->SetTargetLandmarks( targetLandmarks.GetPointer() );

//  Software Guide : EndCodeSnippet

//  Software Guide : BeginLatex
//
//  After calling \code{UpdateLargestPossibleRegion()} on the \code{deformer},
//  the displacement field may be obtained via the \code{GetOutput()} method.
//
//  Software Guide : EndLatex

  try
    {
    deformer->UpdateLargestPossibleRegion();
    }
  catch( itk::ExceptionObject & excp )
    {
    std::cerr << "Exception thrown " << std::endl;
    std::cerr << excp << std::endl;
    return EXIT_FAILURE;
    }

  DisplacementFieldType::ConstPointer displacementField = deformer->GetOutput();

  typedef itk::WarpImageFilter< MovingImageType,
                                MovingImageType,
                                DisplacementFieldType  >  FilterType;

  FilterType::Pointer warper = FilterType::New();

  typedef itk::LinearInterpolateImageFunction<
                       MovingImageType, double >  InterpolatorType;

  InterpolatorType::Pointer interpolator = InterpolatorType::New();

  warper->SetInterpolator( interpolator );

  warper->SetOutputSpacing( displacementField->GetSpacing() );
  warper->SetOutputOrigin(  displacementField->GetOrigin() );

  warper->SetDisplacementField( displacementField );

  warper->SetInput( movingReader->GetOutput() );

  movingWriter->SetInput( warper->GetOutput() );

  try
    {
    movingWriter->Update();
    }
  catch( itk::ExceptionObject & excp )
    {
    std::cerr << "Exception thrown " << std::endl;
    std::cerr << excp << std::endl;
    return EXIT_FAILURE;
    }

  return EXIT_SUCCESS;

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: tabletree.hxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: hr $ $Date: 2004-11-09 12:35:33 $
 *
 *  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 EXPRESS 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 _DBAUI_TABLETREE_HXX_
#define _DBAUI_TABLETREE_HXX_

#ifndef _DBAUI_MARKTREE_HXX_
#include "marktree.hxx"
#endif

#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATABASEMETADATA_HPP_
#include <com/sun/star/sdbc/XDatabaseMetaData.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XDRIVER_HPP_
#include <com/sun/star/sdbc/XDriver.hpp>
#endif

//.........................................................................
namespace dbaui
{
//.........................................................................

//========================================================================
//= OTableTreeListBox
//========================================================================
class OTableTreeListBox : public OMarkableTreeListBox
{
protected:
    Image           m_aTableImage;
    Image           m_aViewImage;

    sal_Bool        m_bVirtualRoot; // should the first entry be visible

public:
    OTableTreeListBox( Window* pParent
                        ,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB
                        ,sal_Bool _bHiContrast,WinBits nWinStyle = NULL,sal_Bool _bVirtualRoot=sal_True );
    OTableTreeListBox( Window* pParent
                        ,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB
                        , const ResId& rResId,sal_Bool _bHiContrast,sal_Bool _bVirtualRoot=sal_True );
    /** call when HiContrast change.
    */
    virtual void notifyHiContrastChanged();

    /** fill the table list with the tables belonging to the connection described by the parameters
        @param _xConnection
            the connection, which must support the service com.sun.star.sdb.Connection
        @throws
            <type scope="com::sun::star::sdbc">SQLException</type> if no connection could be created
    */
    void
            UpdateTableList(
                const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _xConnection
            )   throw(::com::sun::star::sdbc::SQLException);

    /** fill the table list with the tables and views determined by the two given containers
        @param      _rxConnMetaData meta data describing the connection where you got the object names from. Must not be NULL.
                                    Used to split the full qualified names into it's parts.
        @param      _rxTables       table container. May be NULL.
        @param      _rxView         view container. May be NULL.
    */
    void    UpdateTableList(
                const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData >& _rxConnMetaData,
                const ::com::sun::star::uno::Sequence< ::rtl::OUString >& _rTables,
                const ::com::sun::star::uno::Sequence< ::rtl::OUString >& _rViews
            );

    /** to be used if a foreign instance added a table
    */
    SvLBoxEntry* addedTable(
                const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConn,
                const ::rtl::OUString& _rName,
                const ::com::sun::star::uno::Any& _rObject
            );

    /** to be used if a foreign instance removed a table
    */
    void    removedTable(
                const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConn,
                const ::rtl::OUString& _rName
            );

    SvLBoxEntry*    getEntryByQualifiedName(
                const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConn,
                const ::rtl::OUString& _rName
            );

    SvLBoxEntry*    getAllObjectsEntry() const;

    /** does a wildcard check of the given entry

There are two different 'checked' states: If the user checks all children of an entry, this is different
        from checking the entry itself. The second is called 'wildcard' checking, 'cause in the resulting
        table filter it's represented by a wildcard.

    */
    void            checkWildcard(SvLBoxEntry* _pEntry);

    /** determine if the given entry is 'wildcard checked'
        @see checkWildcard
    */
    sal_Bool        isWildcardChecked(SvLBoxEntry* _pEntry) const;

protected:
    virtual void InitEntry(SvLBoxEntry* _pEntry, const XubString& _rString, const Image& _rCollapsedBitmap, const Image& _rExpandedBitmap);

    virtual void checkedButton_noBroadcast(SvLBoxEntry* _pEntry);

    void implEmphasize(SvLBoxEntry* _pEntry, sal_Bool _bChecked, sal_Bool _bUpdateDescendants = sal_True, sal_Bool _bUpdateAncestors = sal_True);

    SvLBoxEntry* implAddEntry(
            const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData >& _rxConnMetaData,
            const ::rtl::OUString& _rTableName,
            const Image& _rImage,
            SvLBoxEntry* _pParentEntry,
            sal_Int32 _nType,
            sal_Bool _bCheckName = sal_True
        );

    sal_Bool haveVirtualRoot() const { return m_bVirtualRoot; }
};

//.........................................................................
}   // namespace dbaui
//.........................................................................

#endif // _DBAUI_TABLETREE_HXX_

<commit_msg>INTEGRATION: CWS dba22 (1.12.8); FILE MERGED 2004/12/13 12:29:45 oj 1.12.8.1: #i38529# check if a table is in real a view<commit_after>/*************************************************************************
 *
 *  $RCSfile: tabletree.hxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: kz $ $Date: 2005-01-21 17:19:20 $
 *
 *  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 EXPRESS 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 _DBAUI_TABLETREE_HXX_
#define _DBAUI_TABLETREE_HXX_

#ifndef _DBAUI_MARKTREE_HXX_
#include "marktree.hxx"
#endif

#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATABASEMETADATA_HPP_
#include <com/sun/star/sdbc/XDatabaseMetaData.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XDRIVER_HPP_
#include <com/sun/star/sdbc/XDriver.hpp>
#endif

//.........................................................................
namespace dbaui
{
//.........................................................................

//========================================================================
//= OTableTreeListBox
//========================================================================
class OTableTreeListBox : public OMarkableTreeListBox
{
protected:
    Image           m_aTableImage;
    Image           m_aViewImage;

    sal_Bool        m_bVirtualRoot; // should the first entry be visible

public:
    OTableTreeListBox( Window* pParent
                        ,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB
                        ,sal_Bool _bHiContrast,WinBits nWinStyle = NULL,sal_Bool _bVirtualRoot=sal_True );
    OTableTreeListBox( Window* pParent
                        ,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB
                        , const ResId& rResId,sal_Bool _bHiContrast,sal_Bool _bVirtualRoot=sal_True );

    typedef ::std::pair< ::rtl::OUString,sal_Bool>  TTableViewName;
    typedef ::std::vector< TTableViewName >         TNames;
    /** call when HiContrast change.
    */
    virtual void notifyHiContrastChanged();

    /** fill the table list with the tables belonging to the connection described by the parameters
        @param _xConnection
            the connection, which must support the service com.sun.star.sdb.Connection
        @throws
            <type scope="com::sun::star::sdbc">SQLException</type> if no connection could be created
    */
    void
            UpdateTableList(
                const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _xConnection
            )   throw(::com::sun::star::sdbc::SQLException);

    /** fill the table list with the tables and views determined by the two given containers.
        The views sequence is used to determine which table is of type view.
        @param      _rxConnMetaData meta data describing the connection where you got the object names from. Must not be NULL.
                                    Used to split the full qualified names into it's parts.
        @param      _rTables        table/view sequence
        @param      _rViews         view sequence
    */
    void    UpdateTableList(
                const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData >& _rxConnMetaData,
                const ::com::sun::star::uno::Sequence< ::rtl::OUString>& _rTables,
                const ::com::sun::star::uno::Sequence< ::rtl::OUString>& _rViews
            );

    /** to be used if a foreign instance added a table
    */
    SvLBoxEntry* addedTable(
                const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConn,
                const ::rtl::OUString& _rName,
                const ::com::sun::star::uno::Any& _rObject
            );

    /** to be used if a foreign instance removed a table
    */
    void    removedTable(
                const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConn,
                const ::rtl::OUString& _rName
            );

    SvLBoxEntry*    getEntryByQualifiedName(
                const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConn,
                const ::rtl::OUString& _rName
            );

    SvLBoxEntry*    getAllObjectsEntry() const;

    /** does a wildcard check of the given entry

There are two different 'checked' states: If the user checks all children of an entry, this is different
        from checking the entry itself. The second is called 'wildcard' checking, 'cause in the resulting
        table filter it's represented by a wildcard.

    */
    void            checkWildcard(SvLBoxEntry* _pEntry);

    /** determine if the given entry is 'wildcard checked'
        @see checkWildcard
    */
    sal_Bool        isWildcardChecked(SvLBoxEntry* _pEntry) const;

protected:
    virtual void InitEntry(SvLBoxEntry* _pEntry, const XubString& _rString, const Image& _rCollapsedBitmap, const Image& _rExpandedBitmap);

    virtual void checkedButton_noBroadcast(SvLBoxEntry* _pEntry);

    void implEmphasize(SvLBoxEntry* _pEntry, sal_Bool _bChecked, sal_Bool _bUpdateDescendants = sal_True, sal_Bool _bUpdateAncestors = sal_True);

    SvLBoxEntry* implAddEntry(
            const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData >& _rxConnMetaData,
            const ::rtl::OUString& _rTableName,
            const Image& _rImage,
            SvLBoxEntry* _pParentEntry,
            sal_Int32 _nType,
            sal_Bool _bCheckName = sal_True
        );

    sal_Bool haveVirtualRoot() const { return m_bVirtualRoot; }

    /** fill the table list with the tables and views determined by the two given containers
        @param      _rxConnMetaData meta data describing the connection where you got the object names from. Must not be NULL.
                                    Used to split the full qualified names into it's parts.
        @param      _rTables        table/view sequence, the second argument is <TRUE/> if it is a table, otherwise it is a view.
    */
    void    UpdateTableList(
                const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData >& _rxConnMetaData,
                const TNames& _rTables
            );

};

//.........................................................................
}   // namespace dbaui
//.........................................................................

#endif // _DBAUI_TABLETREE_HXX_

<|endoftext|>