<commit_before>/*
 *	clipsnoop.cc
 *
 *	Snoop the contents of the clipboard
 *
 *	Neil Mayhew - 2008-11-20
 *
 *	$Id: clipsnoop.cc,v 1.1 2008-11-24 04:29:52 mayhewn Exp $
 */

#include <gtkmm.h>
#include <algorithm>
#include <iostream>

#include "HexDump.h"

class ClipDumper
{
	Glib::RefPtr<Gtk::Clipboard> clipboard;
	std::list<std::string> targets;
	std::list<std::string>::const_iterator current;

public:
	ClipDumper()
		: clipboard(Gtk::Clipboard::get())
	{
	}

	void on_received_target(const Gtk::SelectionData& data)
	{
		std::cout << "Got target: " << data.get_target() << "\n";

		// Dump target data
		if (data.get_data())
			HexDump(data.get_data(), data.get_length());
		else
			std::cout << "<null>\n";

		// Iterate
		fetch_target();
	}

	void on_received_targets(const Glib::StringArrayHandle& targets_array)
	{
		// Save the list of clipboard target types
		std::list<std::string> tmp(targets_array);
		targets.swap(tmp);

		// Dump the list to std::cout
		std::copy(targets.begin(), targets.end(), std::ostream_iterator<std::string>(std::cout, "\n"));

		// Start iterating through them, one callback at a time
		current = targets.begin();
		fetch_target();
	}

	void fetch_target()
	{
		if (current != targets.end())
		{
			// Fetch the data for the next target type
			clipboard->request_contents(*current,
				sigc::mem_fun(*this, &ClipDumper::on_received_target));
			++current;
		}
		else
		{
			Gtk::Main::quit();
		}
	}

	void start()
	{
		// Discover what target types are available
		clipboard->request_targets(sigc::mem_fun(*this, &ClipDumper::on_received_targets));
	}
};

int main(int argc, char *argv[])
{
	Gtk::Main kit(argc, argv);
	ClipDumper dumper;

	// Initiate by registering a callback from the start of the main loop
	Gtk::Main::signal_run().connect(sigc::mem_fun(dumper, &ClipDumper::start));
	Gtk::Main::run();

	return 0;
}

<commit_msg>Avoid infinite recursion<commit_after>/*
 *	clipsnoop.cc
 *
 *	Snoop the contents of the clipboard
 *
 *	Neil Mayhew - 2008-11-20
 *
 *	$Id: clipsnoop.cc,v 1.1 2008-11-24 04:29:52 mayhewn Exp $
 */

#include <gtkmm.h>
#include <algorithm>
#include <iostream>

#include "HexDump.h"

class ClipDumper
{
	Glib::RefPtr<Gtk::Clipboard> clipboard;
	std::list<std::string> targets;
	std::list<std::string>::const_iterator current;

public:
	ClipDumper()
		: clipboard(Gtk::Clipboard::get())
	{
	}

	void on_received_target(const Gtk::SelectionData& data)
	{
		std::cout << "Got target: " << data.get_target() << "\n";

		// Dump target data
		if (data.get_data())
			HexDump(data.get_data(), data.get_length());
		else
			std::cout << "<null>\n";

		// Iterate
		fetch_target();
	}

	void on_received_targets(const Glib::StringArrayHandle& targets_array)
	{
		// Save the list of clipboard target types
		std::list<std::string> tmp(targets_array);
		targets.swap(tmp);

		// Dump the list to std::cout
		std::copy(targets.begin(), targets.end(), std::ostream_iterator<std::string>(std::cout, "\n"));

		// Start iterating through them, one callback at a time
		current = targets.begin();
		fetch_target();
	}

	void fetch_target()
	{
		if (current != targets.end())
		{
			// Fetch the data for the next target type
			clipboard->request_contents(*current++,
				sigc::mem_fun(*this, &ClipDumper::on_received_target));
		}
		else
		{
			Gtk::Main::quit();
		}
	}

	void start()
	{
		// Discover what target types are available
		clipboard->request_targets(sigc::mem_fun(*this, &ClipDumper::on_received_targets));
	}
};

int main(int argc, char *argv[])
{
	Gtk::Main kit(argc, argv);
	ClipDumper dumper;

	// Initiate by registering a callback from the start of the main loop
	Gtk::Main::signal_run().connect(sigc::mem_fun(dumper, &ClipDumper::start));
	Gtk::Main::run();

	return 0;
}

<|endoftext|>


<commit_before>/* Copyright (C) 2013 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1.  Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"

#if ENABLE(WEB_AUDIO)

#if OS(ANDROID) && USE(WEBAUDIO_OPENMAX_DL_FFT)

#include "FFTFrame.h"

#include "AudioArray.h"
#include "VectorMath.h"
#include "dl/sp/api/armSP.h"
#include "dl/sp/api/omxSP.h"

#include <wtf/MathExtras.h>

namespace WebCore {

const int kMaxFFTPow2Size = 15;

// Normal constructor: allocates for a given fftSize.
FFTFrame::FFTFrame(unsigned fftSize)
    : m_FFTSize(fftSize)
    , m_log2FFTSize(static_cast<unsigned>(log2(fftSize)))
    , m_forwardContext(0)
    , m_inverseContext(0)
    , m_complexData(fftSize)
    , m_realData(fftSize / 2)
    , m_imagData(fftSize / 2)
{
    // We only allow power of two.
    ASSERT(1UL << m_log2FFTSize == m_FFTSize);

    m_forwardContext = contextForSize(m_log2FFTSize);
    m_inverseContext = contextForSize(m_log2FFTSize);
}

// Creates a blank/empty frame (interpolate() must later be called).
FFTFrame::FFTFrame()
    : m_FFTSize(0)
    , m_log2FFTSize(0)
    , m_forwardContext(0)
    , m_inverseContext(0)
{
}

// Copy constructor.
FFTFrame::FFTFrame(const FFTFrame& frame)
    : m_FFTSize(frame.m_FFTSize)
    , m_log2FFTSize(frame.m_log2FFTSize)
    , m_forwardContext(0)
    , m_inverseContext(0)
    , m_complexData(frame.m_FFTSize)
    , m_realData(frame.m_FFTSize / 2)
    , m_imagData(frame.m_FFTSize / 2)
{
    m_forwardContext = contextForSize(m_log2FFTSize);
    m_inverseContext = contextForSize(m_log2FFTSize);

    // Copy/setup frame data.
    unsigned nbytes = sizeof(float) * (m_FFTSize / 2);
    memcpy(realData(), frame.realData(), nbytes);
    memcpy(imagData(), frame.imagData(), nbytes);
}

void FFTFrame::initialize()
{
}

void FFTFrame::cleanup()
{
}

FFTFrame::~FFTFrame()
{
    if (m_forwardContext)
        free(m_forwardContext);
    if (m_inverseContext)
        free(m_inverseContext);
}

void FFTFrame::multiply(const FFTFrame& frame)
{
    FFTFrame& frame1 = *this;
    FFTFrame& frame2 = const_cast<FFTFrame&>(frame);

    float* realP1 = frame1.realData();
    float* imagP1 = frame1.imagData();
    const float* realP2 = frame2.realData();
    const float* imagP2 = frame2.imagData();

    unsigned halfSize = fftSize() / 2;
    float real0 = realP1[0];
    float imag0 = imagP1[0];

    VectorMath::zvmul(realP1, imagP1, realP2, imagP2, realP1, imagP1, halfSize);

    // Multiply the packed DC/nyquist component
    realP1[0] = real0 * realP2[0];
    imagP1[0] = imag0 * imagP2[0];
}

void FFTFrame::doFFT(const float* data)
{
    ASSERT(m_forwardContext);

    if (m_forwardContext) {
        AudioFloatArray complexFFT(m_FFTSize + 2);

        omxSP_FFTFwd_RToCCS_F32_Sfs(data, complexFFT.data(), m_forwardContext);

        unsigned len = m_FFTSize / 2;

        // Split FFT data into real and imaginary arrays.
        for (unsigned k = 1; k < len; ++k) {
            int index = 2 * k;
            m_realData[k] = complexFFT[index];
            m_imagData[k] = complexFFT[index + 1];
        }
        m_realData[0] = complexFFT[0];
        m_imagData[0] = complexFFT[m_FFTSize];
    }
}

void FFTFrame::doInverseFFT(float* data)
{
    ASSERT(m_inverseContext);

    if (m_inverseContext) {
        AudioFloatArray fftData(m_FFTSize + 2);

        unsigned len = m_FFTSize / 2;

        // Pack the real and imaginary data into the complex array format
        for (unsigned k = 1; k < len; ++k) {
            int index = 2 * k;
            fftData[index] = m_realData[k];
            fftData[index + 1] = m_imagData[k];
        }
        fftData[0] = m_realData[0];
        fftData[1] = 0;
        fftData[m_FFTSize] = m_imagData[0];
        fftData[m_FFTSize + 1] = 0;

        omxSP_FFTInv_CCSToR_F32_Sfs(fftData.data(), data, m_inverseContext);
    }
}

float* FFTFrame::realData() const
{
    return const_cast<float*>(m_realData.data());
}

float* FFTFrame::imagData() const
{
    return const_cast<float*>(m_imagData.data());
}

OMXFFTSpec_R_F32* FFTFrame::contextForSize(unsigned log2FFTSize)
{
    ASSERT(log2FFTSize);
    ASSERT(log2FFTSize < kMaxFFTPow2Size);
    int bufSize;
    OMXResult status = omxSP_FFTGetBufSize_R_F32(log2FFTSize, &bufSize);

    if (status == OMX_Sts_NoErr) {
        OMXFFTSpec_R_F32* context = static_cast<OMXFFTSpec_R_F32*>(malloc(bufSize));
        omxSP_FFTInit_R_F32(context, log2FFTSize);
        return context;
    }

    return 0;
}

} // namespace WebCore

#endif // #if OS(ANDROID) && !USE(WEBAUDIO_OPENMAX_DL_FFT)

#endif // ENABLE(WEB_AUDIO)
<commit_msg>Fix issue with comparing signed and unsigned for Android FFT.<commit_after>/* Copyright (C) 2013 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1.  Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"

#if ENABLE(WEB_AUDIO)

#if OS(ANDROID) && USE(WEBAUDIO_OPENMAX_DL_FFT)

#include "FFTFrame.h"

#include "AudioArray.h"
#include "VectorMath.h"
#include "dl/sp/api/armSP.h"
#include "dl/sp/api/omxSP.h"

#include <wtf/MathExtras.h>

namespace WebCore {

const unsigned kMaxFFTPow2Size = 15;

// Normal constructor: allocates for a given fftSize.
FFTFrame::FFTFrame(unsigned fftSize)
    : m_FFTSize(fftSize)
    , m_log2FFTSize(static_cast<unsigned>(log2(fftSize)))
    , m_forwardContext(0)
    , m_inverseContext(0)
    , m_complexData(fftSize)
    , m_realData(fftSize / 2)
    , m_imagData(fftSize / 2)
{
    // We only allow power of two.
    ASSERT(1UL << m_log2FFTSize == m_FFTSize);

    m_forwardContext = contextForSize(m_log2FFTSize);
    m_inverseContext = contextForSize(m_log2FFTSize);
}

// Creates a blank/empty frame (interpolate() must later be called).
FFTFrame::FFTFrame()
    : m_FFTSize(0)
    , m_log2FFTSize(0)
    , m_forwardContext(0)
    , m_inverseContext(0)
{
}

// Copy constructor.
FFTFrame::FFTFrame(const FFTFrame& frame)
    : m_FFTSize(frame.m_FFTSize)
    , m_log2FFTSize(frame.m_log2FFTSize)
    , m_forwardContext(0)
    , m_inverseContext(0)
    , m_complexData(frame.m_FFTSize)
    , m_realData(frame.m_FFTSize / 2)
    , m_imagData(frame.m_FFTSize / 2)
{
    m_forwardContext = contextForSize(m_log2FFTSize);
    m_inverseContext = contextForSize(m_log2FFTSize);

    // Copy/setup frame data.
    unsigned nbytes = sizeof(float) * (m_FFTSize / 2);
    memcpy(realData(), frame.realData(), nbytes);
    memcpy(imagData(), frame.imagData(), nbytes);
}

void FFTFrame::initialize()
{
}

void FFTFrame::cleanup()
{
}

FFTFrame::~FFTFrame()
{
    if (m_forwardContext)
        free(m_forwardContext);
    if (m_inverseContext)
        free(m_inverseContext);
}

void FFTFrame::multiply(const FFTFrame& frame)
{
    FFTFrame& frame1 = *this;
    FFTFrame& frame2 = const_cast<FFTFrame&>(frame);

    float* realP1 = frame1.realData();
    float* imagP1 = frame1.imagData();
    const float* realP2 = frame2.realData();
    const float* imagP2 = frame2.imagData();

    unsigned halfSize = fftSize() / 2;
    float real0 = realP1[0];
    float imag0 = imagP1[0];

    VectorMath::zvmul(realP1, imagP1, realP2, imagP2, realP1, imagP1, halfSize);

    // Multiply the packed DC/nyquist component
    realP1[0] = real0 * realP2[0];
    imagP1[0] = imag0 * imagP2[0];
}

void FFTFrame::doFFT(const float* data)
{
    ASSERT(m_forwardContext);

    if (m_forwardContext) {
        AudioFloatArray complexFFT(m_FFTSize + 2);

        omxSP_FFTFwd_RToCCS_F32_Sfs(data, complexFFT.data(), m_forwardContext);

        unsigned len = m_FFTSize / 2;

        // Split FFT data into real and imaginary arrays.
        for (unsigned k = 1; k < len; ++k) {
            int index = 2 * k;
            m_realData[k] = complexFFT[index];
            m_imagData[k] = complexFFT[index + 1];
        }
        m_realData[0] = complexFFT[0];
        m_imagData[0] = complexFFT[m_FFTSize];
    }
}

void FFTFrame::doInverseFFT(float* data)
{
    ASSERT(m_inverseContext);

    if (m_inverseContext) {
        AudioFloatArray fftData(m_FFTSize + 2);

        unsigned len = m_FFTSize / 2;

        // Pack the real and imaginary data into the complex array format
        for (unsigned k = 1; k < len; ++k) {
            int index = 2 * k;
            fftData[index] = m_realData[k];
            fftData[index + 1] = m_imagData[k];
        }
        fftData[0] = m_realData[0];
        fftData[1] = 0;
        fftData[m_FFTSize] = m_imagData[0];
        fftData[m_FFTSize + 1] = 0;

        omxSP_FFTInv_CCSToR_F32_Sfs(fftData.data(), data, m_inverseContext);
    }
}

float* FFTFrame::realData() const
{
    return const_cast<float*>(m_realData.data());
}

float* FFTFrame::imagData() const
{
    return const_cast<float*>(m_imagData.data());
}

OMXFFTSpec_R_F32* FFTFrame::contextForSize(unsigned log2FFTSize)
{
    ASSERT(log2FFTSize);
    ASSERT(log2FFTSize < kMaxFFTPow2Size);
    int bufSize;
    OMXResult status = omxSP_FFTGetBufSize_R_F32(log2FFTSize, &bufSize);

    if (status == OMX_Sts_NoErr) {
        OMXFFTSpec_R_F32* context = static_cast<OMXFFTSpec_R_F32*>(malloc(bufSize));
        omxSP_FFTInit_R_F32(context, log2FFTSize);
        return context;
    }

    return 0;
}

} // namespace WebCore

#endif // #if OS(ANDROID) && !USE(WEBAUDIO_OPENMAX_DL_FFT)

#endif // ENABLE(WEB_AUDIO)
<|endoftext|>


<commit_before><commit_msg>Ensure that SyncWaiter (base/waitable_event_posix.cc) condition variables cannot be destroyed (pthread_cond_destroy) during a broadcast (pthread_cond_broadcast).  SyncWaiter::Fire now holds the lock until the broadcast is complete.  Given the lock ordering, this guarantees that the condition variable cannot be destroyed until it is safe to do so.  Holding the lock through the broadcast is harmless, as pthread_cond_wait and pthread_cond_timedwait will simply block (if needed) until able to take the lock prior to returning.<commit_after><|endoftext|>


<commit_before>/*-
 * Copyright (c) 2008 Michael Marner <michael@20papercups.net>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#define MAX_RES 1600

// include system headers
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <sstream>

// include openGL headers
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>

#include <wcl/Exception.h>
#include <wcl/camera/CameraFactory.h>

using namespace std;
using namespace wcl;

Camera *cam;

void usage()
{
    printf("snapshot devicenode [filename]\n"
	   "Snapshot takes a image from a camera and displays it to the screen\n"
	   "or saves it to a file if a filename is given. It uses image magic to\n"
	   "convert the image from a rgb image to a jpg"
	   );
}

/**
 * Initialise OpenGL
 */
GLvoid init()
{
	unsigned char* data;
	glShadeModel(GL_SMOOTH);
	glClearColor(0,0,0,0);
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LEQUAL);

	data = new unsigned char[cam->getFormatBufferSize(Camera::RGB8)];

	// create a texture for the image...
	glTexImage2D(GL_TEXTURE_2D,             //target
				 0,                         //level of detail
				 3,                         //colour components
				 cam->getActiveConfiguration().width,     //width
				 cam->getActiveConfiguration().height,    //height
				 0,                         //border
				 GL_RGB,                    //image format
				 GL_UNSIGNED_BYTE,
				 data);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);

	glEnable(GL_TEXTURE_2D);

	glMatrixMode(GL_PROJECTION);
	gluOrtho2D(0,1,0,1);
	glMatrixMode(GL_MODELVIEW);
	delete data;
}

/**
 * Constantly fetch a new image from the camera to display
 */
GLvoid idle()
{
	glutPostRedisplay();
}

/**
 * Display Loop.
 */
GLvoid display()
{
	glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);

	const unsigned char* frame = cam->getFrame(Camera::RGB8);
	glTexSubImage2D(GL_TEXTURE_2D,
	                0,
					0,
					0,
					cam->getActiveConfiguration().width,
					cam->getActiveConfiguration().height,
					GL_RGB,
					GL_UNSIGNED_BYTE,
					frame);

	glMatrixMode(GL_MODELVIEW);

	glLoadIdentity();
		glColor3f(1,0,0);
		glBegin(GL_QUADS);

		glTexCoord2f(0,1);
		glVertex2f(0,0);

		glTexCoord2f(1,1);
		glVertex2f(1,0);

		glTexCoord2f(1,0);
		glVertex2f(1,1);

		glTexCoord2f(0,0);
		glVertex2f(0,1);
	glEnd();

	glFlush();
	glutSwapBuffers();

	// print out any opengl errors to the console
	GLenum error = glGetError();
	if (error != GL_NO_ERROR)
	{
		cout << gluErrorString(error) << endl;
	}
}

/**
 * This doesn't do what it is supposed to do!
 */
GLvoid reshape(int width, int height)
{
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluOrtho2D(0,1,0,1);
	glViewport(0,0, (GLsizei)width, (GLsizei)height);
	glMatrixMode(GL_MODELVIEW);
}

void keyboard(unsigned char key, int w, int h)
{
    if(key==27)
	exit(EXIT_SUCCESS);
}

int main(int argc, char** argv)
{
    bool dodisplay = false;
    const char *filename = NULL;

    switch( argc ){
	case 2: dodisplay = true; break;
	case 3: filename=argv[2]; break;
	case 1: /* fallthrough */
	default:
		usage();
		return 1;
    }

    try {
	std::vector<Camera *> cameras =
	    CameraFactory::getCameras();

	if( cameras.size() == 0 ){
	    cout << "No Camera's found" << endl;
	    return 0;
	}

	cam = CameraFactory::getCamera(argv[1]);
	Camera::Configuration c;
	c.width = MAX_RES;
	c = cam->findConfiguration(c);
	cam->setConfiguration(c);

	if( dodisplay ){
	    // Create GLUT window
	    glutInit(&argc, argv);
	    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
	    glutInitWindowSize(cam->getActiveConfiguration().width, cam->getActiveConfiguration().height);
	    glutCreateWindow(argv[0]);

	    init();

	    // register callbacks
	    glutDisplayFunc(display);
	    glutReshapeFunc(reshape);
	    glutKeyboardFunc(keyboard);
	    glutIdleFunc(idle);

	    // GO!
	    glutMainLoop();

	} else {

	    cout << "Writing Camera Image to: " << filename << endl;

	    stringstream name;
	    name << filename;
	    name << ".rgb";

	    FILE *f = fopen(name.str().c_str(), "w");
	    if ( f == NULL ){
		perror("Failed to open output file");
		return 1;
	    }

	    const unsigned char * frame = cam->getFrame(Camera::RGB8);

	    if(fwrite(frame, cam->getFormatBufferSize(Camera::RGB8), 1, f) <= 0){
		perror("Failed to write output file");
		return 1;
	    }

	    fclose(f);

	    stringstream s;
	    s << "convert ";
	    s << "-size ";
	    s << c.width;
	    s << "x";
	    s << c.height;
	    s << " -depth 8 ";
	    s << name.str();
	    s << " ";
	    s << filename;
	    s << ".jpg";

	    cout << s.str() << endl;

	    if( system(s.str().c_str()) < 0 ){
		cerr << "Failed to convert to jpg: " << s.str().c_str() << endl;
		return 1;
	    }

	    unlink( name.str().c_str() );
	}

	cam->shutdown();
	delete cam;
    }
    catch (Exception &e)
    {
	cout << "Exception Occured: " << e.what() << endl;
	return 1;
    }

    return 0;
}

<commit_msg>examples: Don't assume the user actually specifies a valid camera<commit_after>/*-
 * Copyright (c) 2008 Michael Marner <michael@20papercups.net>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#define MAX_RES 1600

// include system headers
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <sstream>

// include openGL headers
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>

#include <wcl/Exception.h>
#include <wcl/camera/CameraFactory.h>

using namespace std;
using namespace wcl;

Camera *cam;

void usage()
{
    printf("snapshot devicenode [filename]\n"
	   "Snapshot takes a image from a camera and displays it to the screen\n"
	   "or saves it to a file if a filename is given. It uses image magic to\n"
	   "convert the image from a rgb image to a jpg"
	   );
}

/**
 * Initialise OpenGL
 */
GLvoid init()
{
	unsigned char* data;
	glShadeModel(GL_SMOOTH);
	glClearColor(0,0,0,0);
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LEQUAL);

	data = new unsigned char[cam->getFormatBufferSize(Camera::RGB8)];

	// create a texture for the image...
	glTexImage2D(GL_TEXTURE_2D,             //target
				 0,                         //level of detail
				 3,                         //colour components
				 cam->getActiveConfiguration().width,     //width
				 cam->getActiveConfiguration().height,    //height
				 0,                         //border
				 GL_RGB,                    //image format
				 GL_UNSIGNED_BYTE,
				 data);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);

	glEnable(GL_TEXTURE_2D);

	glMatrixMode(GL_PROJECTION);
	gluOrtho2D(0,1,0,1);
	glMatrixMode(GL_MODELVIEW);
	delete data;
}

/**
 * Constantly fetch a new image from the camera to display
 */
GLvoid idle()
{
	glutPostRedisplay();
}

/**
 * Display Loop.
 */
GLvoid display()
{
	glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);

	const unsigned char* frame = cam->getFrame(Camera::RGB8);
	glTexSubImage2D(GL_TEXTURE_2D,
	                0,
					0,
					0,
					cam->getActiveConfiguration().width,
					cam->getActiveConfiguration().height,
					GL_RGB,
					GL_UNSIGNED_BYTE,
					frame);

	glMatrixMode(GL_MODELVIEW);

	glLoadIdentity();
		glColor3f(1,0,0);
		glBegin(GL_QUADS);

		glTexCoord2f(0,1);
		glVertex2f(0,0);

		glTexCoord2f(1,1);
		glVertex2f(1,0);

		glTexCoord2f(1,0);
		glVertex2f(1,1);

		glTexCoord2f(0,0);
		glVertex2f(0,1);
	glEnd();

	glFlush();
	glutSwapBuffers();

	// print out any opengl errors to the console
	GLenum error = glGetError();
	if (error != GL_NO_ERROR)
	{
		cout << gluErrorString(error) << endl;
	}
}

/**
 * This doesn't do what it is supposed to do!
 */
GLvoid reshape(int width, int height)
{
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluOrtho2D(0,1,0,1);
	glViewport(0,0, (GLsizei)width, (GLsizei)height);
	glMatrixMode(GL_MODELVIEW);
}

void keyboard(unsigned char key, int w, int h)
{
    if(key==27)
	exit(EXIT_SUCCESS);
}

int main(int argc, char** argv)
{
    bool dodisplay = false;
    const char *filename = NULL;

    switch( argc ){
	case 2: dodisplay = true; break;
	case 3: filename=argv[2]; break;
	case 1: /* fallthrough */
	default:
		usage();
		return 1;
    }

    try {
	std::vector<Camera *> cameras =
	    CameraFactory::getCameras();

	if( cameras.size() == 0 ){
	    cout << "No Camera's found" << endl;
	    return 0;
	}

	cam = CameraFactory::getCamera(argv[1]);
	if( cam == NULL ){
	    cout << "Camera not found" << endl;
	    return 1;
	}

	Camera::Configuration c;
	c.width = MAX_RES;
	c = cam->findConfiguration(c);
	cam->setConfiguration(c);

	if( dodisplay ){
	    // Create GLUT window
	    glutInit(&argc, argv);
	    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
	    glutInitWindowSize(cam->getActiveConfiguration().width, cam->getActiveConfiguration().height);
	    glutCreateWindow(argv[0]);

	    init();

	    // register callbacks
	    glutDisplayFunc(display);
	    glutReshapeFunc(reshape);
	    glutKeyboardFunc(keyboard);
	    glutIdleFunc(idle);

	    // GO!
	    glutMainLoop();

	} else {

	    cout << "Writing Camera Image to: " << filename << endl;

	    stringstream name;
	    name << filename;
	    name << ".rgb";

	    FILE *f = fopen(name.str().c_str(), "w");
	    if ( f == NULL ){
		perror("Failed to open output file");
		return 1;
	    }

	    const unsigned char * frame = cam->getFrame(Camera::RGB8);

	    if(fwrite(frame, cam->getFormatBufferSize(Camera::RGB8), 1, f) <= 0){
		perror("Failed to write output file");
		return 1;
	    }

	    fclose(f);

	    stringstream s;
	    s << "convert ";
	    s << "-size ";
	    s << c.width;
	    s << "x";
	    s << c.height;
	    s << " -depth 8 ";
	    s << name.str();
	    s << " ";
	    s << filename;
	    s << ".jpg";

	    cout << s.str() << endl;

	    if( system(s.str().c_str()) < 0 ){
		cerr << "Failed to convert to jpg: " << s.str().c_str() << endl;
		return 1;
	    }

	    unlink( name.str().c_str() );
	}

	cam->shutdown();
	delete cam;
    }
    catch (Exception &e)
    {
	cout << "Exception Occured: " << e.what() << endl;
	return 1;
    }

    return 0;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ttbasic.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 14:16:54 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_basic.hxx"
#include <basic/mybasic.hxx>
#include "ttbasic.hxx"

MyBasic* TTBasic::CreateMyBasic()
{
    return new MyBasic;
}
<commit_msg>INTEGRATION: CWS changefileheader (1.7.88); FILE MERGED 2008/03/28 16:07:06 rt 1.7.88.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: ttbasic.cxx,v $
 * $Revision: 1.8 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_basic.hxx"
#include <basic/mybasic.hxx>
#include "ttbasic.hxx"

MyBasic* TTBasic::CreateMyBasic()
{
    return new MyBasic;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: sbxvals.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 21:54:06 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/

#define _TLBIGINT_INT64

#ifndef _BIGINT_HXX //autogen
#include <tools/bigint.hxx>
#endif
#include "sbx.hxx"

///////////////////////////// BigInt/Currency //////////////////////////////

SbxValues::SbxValues( const BigInt &rBig ) : eType(SbxCURRENCY)
{
    rBig.INT64( &nLong64 );
}

BOOL BigInt::INT64( SbxINT64 *p ) const
{
    if( bIsBig ) {
        if( nLen > 4 || (nNum[3] & 0x8000) )
            return FALSE;

        p->nLow  = ((UINT32)nNum[1] << 16) | (UINT32)nNum[0];
        p->nHigh = ((UINT32)nNum[3] << 16) | (UINT32)nNum[2];
        if( bIsNeg )
            p->CHS();
    }
    else
        p->Set( nVal );

    return TRUE;
}

BigInt::BigInt( const SbxINT64 &r )
{
    BigInt a10000 = 0x10000;

    *this = r.nHigh;
    if( r.nHigh )
        *this *= a10000;
    *this += (USHORT)(r.nLow >> 16);
    *this *= a10000;
    *this += (USHORT)r.nLow;
}

BOOL BigInt::UINT64( SbxUINT64 *p ) const
{
    if( bIsBig ) {
        if( bIsNeg || nLen > 4 )
            return FALSE;

        p->nLow  = ((UINT32)nNum[1] << 16) | (UINT32)nNum[0];
        p->nHigh = ((UINT32)nNum[3] << 16) | (UINT32)nNum[2];
    }
    else {
        if( nVal < 0 )
            return FALSE;

        p->Set( (UINT32)nVal );
    }

    return TRUE;
}

BigInt::BigInt( const SbxUINT64 &r )
{
    BigInt a10000 = 0x10000;

    *this = BigInt(r.nHigh);
    if( r.nHigh )
        *this *= a10000;
    *this += (USHORT)(r.nLow >> 16);
    *this *= a10000;
    *this += (USHORT)r.nLow;
}
<commit_msg>INTEGRATION: CWS sixtyfour04 (1.3.70); FILE MERGED 2006/03/21 14:26:05 cmc 1.3.70.1: #i63124# make basic 64bit ok<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: sbxvals.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: vg $ $Date: 2006-04-07 08:10:14 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/

#define _TLBIGINT_INT64

#ifndef _BIGINT_HXX //autogen
#include <tools/bigint.hxx>
#endif
#include "sbx.hxx"

///////////////////////////// BigInt/Currency //////////////////////////////

SbxValues::SbxValues( const BigInt &rBig ) : eType(SbxCURRENCY)
{
    rBig.INT64( &nLong64 );
}

BOOL BigInt::INT64( SbxINT64 *p ) const
{
    if( bIsBig ) {
        if( nLen > 4 || (nNum[3] & 0x8000) )
            return FALSE;

        p->nLow  = ((UINT32)nNum[1] << 16) | (UINT32)nNum[0];
        p->nHigh = ((UINT32)nNum[3] << 16) | (UINT32)nNum[2];
        if( bIsNeg )
            p->CHS();
    }
    else
        p->Set( (INT32)nVal );

    return TRUE;
}

BigInt::BigInt( const SbxINT64 &r )
{
    BigInt a10000 = 0x10000;

    *this = r.nHigh;
    if( r.nHigh )
        *this *= a10000;
    *this += (USHORT)(r.nLow >> 16);
    *this *= a10000;
    *this += (USHORT)r.nLow;
}

BOOL BigInt::UINT64( SbxUINT64 *p ) const
{
    if( bIsBig ) {
        if( bIsNeg || nLen > 4 )
            return FALSE;

        p->nLow  = ((UINT32)nNum[1] << 16) | (UINT32)nNum[0];
        p->nHigh = ((UINT32)nNum[3] << 16) | (UINT32)nNum[2];
    }
    else {
        if( nVal < 0 )
            return FALSE;

        p->Set( (UINT32)nVal );
    }

    return TRUE;
}

BigInt::BigInt( const SbxUINT64 &r )
{
    BigInt a10000 = 0x10000;

    *this = BigInt(r.nHigh);
    if( r.nHigh )
        *this *= a10000;
    *this += (USHORT)(r.nLow >> 16);
    *this *= a10000;
    *this += (USHORT)r.nLow;
}
<|endoftext|>


<commit_before>#pragma once
//=====================================================================//
/*! @file
    @brief  波形描画テンプレート・クラス
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2017 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include <vector>
#include "gl_fw/glutils.hpp"

namespace view {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  render_waves template class
		@param[in]	UNIT	波形の型
		@param[in]	LIMIT	最大波形数
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <typename UNIT, uint32_t LIMIT>
	class render_waves {

		std::vector<UNIT>	units_;

		double	div_;

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief  コンストラクター
		*/
		//-----------------------------------------------------------------//
		render_waves() : units_(), div_(0.0) { }

		//-----------------------------------------------------------------//
		/*!
			@brief  波形生成
			@param[in]	time	生成時間 [sec]
			@param[in]	div		分解能 [sec]
			@return 生成した数
		*/
		//-----------------------------------------------------------------//
		uint32_t create_buffer(double time, double div)
		{
			if(div <= 0.0 || time <= 0.0) return 0;

			auto n = time / div;

			if(n <= 0.0) return 0;
			else if(n > static_cast<double>(LIMIT)) return 0;

			units_.resize(static_cast<uint32_t>(n));

			div_ = div;  // 分解能

			return n;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  テスト波形生成
			@param[in]	frq		周波数 [Hz]
		*/
		//-----------------------------------------------------------------//
		void build_sin(double frq)
		{
			for(uint32_t i = 0; i < units_.size(); ++i) {
//				double t = 1.0 / frq;
				double t = 1.0 / 1024.0;
				units_[i] = 32768 - static_cast<UNIT>(sin(2.0 * vtx::get_pi<double>() * t * i) * 32767.0);
			}
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  描画
   			@param[in]	width	描画幅（ピクセル）
			@param[in]	step	時間軸ステップ（65536を1.0）
		*/
		//-----------------------------------------------------------------//
		void render(uint32_t width, uint32_t tstep)
		{
			vtx::sposs list;
			list.resize(width);
			uint32_t t = 0;
			for(uint32_t i = 0; i < width; ++i) {
				list[i] = vtx::spos(i, units_[t >> 16] / 256);
				t += tstep;
			}
			gl::draw_line_strip(list);
		}
	};
}
<commit_msg>update: manage, new function<commit_after>#pragma once
//=====================================================================//
/*! @file
    @brief  波形描画テンプレート・クラス
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2017 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include <vector>
#include "gl_fw/glutils.hpp"

namespace view {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  render_waves template class
		@param[in]	UNIT	波形の型
		@param[in]	LIMIT	最大波形数
		@param[in]	CHN		チャネル数
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <typename UNIT, uint32_t LIMIT, uint32_t CHN>
	class render_waves {
	public:
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  チャネル描画パラメーター
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		struct chr_param {
			img::rgba8	color_;		///< 描画色
			int32_t		offset_;	///< 垂直オフセット（電圧）
			float		gain_;		///< 垂直ゲイン（電圧）

			bool		update_;	///< 描画の更新「true」

			chr_param() : color_(img::rgba8(255, 255)),
				offset_(0), gain_(1.0f), update_(false)
			{ }
		};

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  インフォメーション描画パラメーター
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		class info_param {
		public:
			img::rgba8	grid_color_;
			int32_t		grid_step_;
			bool		grid_enable_;

		private:
			vtx::sposs	grid_;

		public:
			info_param() : grid_color_(img::rgba8(255, 128)), grid_step_(30),
				grid_enable_(true),
				grid_()
			{ }

			void build_grid(const vtx::ipos& size)
			{
				grid_.clear();
				for(int h = 0; h < size.x; h += grid_step_) {  // |||
					grid_.push_back(vtx::spos(h, 0));
					grid_.push_back(vtx::spos(h, size.y));
				}
				for(int v = 0; v < size.y; v += grid_step_) {  // ---
					grid_.push_back(vtx::spos(0, v));
					grid_.push_back(vtx::spos(size.x, v));
				}
			}

			void render_grid()
			{
				if(!grid_.empty()) {
					glEnable(GL_LINE_STIPPLE);
					glLineStipple(1, 0b1111000011110000);
					gl::glColor(grid_color_);
					gl::draw_lines(grid_);
					glDisable(GL_LINE_STIPPLE);
				}
			}
		};

	private:
		typedef std::vector<UNIT> UNITS;

		struct ch_t {
			chr_param	param_;
			uint32_t	tstep_;
			UNITS		units_;
			vtx::sposs	lines_;

			ch_t() : param_(), tstep_(0), units_(), lines_()
			{ }
		};

		info_param	info_;

		ch_t		ch_[CHN];
		double		div_;

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief  コンストラクター
		*/
		//-----------------------------------------------------------------//
		render_waves() : ch_{ }, div_(0.0) { }

		//-----------------------------------------------------------------//
		/*!
			@brief  パラメーターを取得
			@param[in]	ch	チャネル
			@return パラメーター
		*/
		//-----------------------------------------------------------------//
		const chr_param& get_param(uint32_t ch) const
		{
			if(ch >= CHN) {
				static chr_param p;
				return p;
			}
			return ch_[ch].param_;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  パラメーターを参照
			@param[in]	ch	チャネル
			@return パラメーター
		*/
		//-----------------------------------------------------------------//
		chr_param& at_param(uint32_t ch)
		{
			if(ch >= CHN) {
				static chr_param p;
				return p;
			}
			return ch_[ch].param_;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  波形生成
			@param[in]	time	生成時間 [sec]
			@param[in]	div		分解能 [sec]
			@return 生成した数
		*/
		//-----------------------------------------------------------------//
		uint32_t create_buffer(double time, double div)
		{
			if(div <= 0.0 || time <= 0.0) return 0;

			auto n = time / div;

			if(n <= 0.0) return 0;
			else if(n > static_cast<double>(LIMIT)) return 0;

			for(int i = 0; i < CHN; ++i) {
				ch_[i].units_.resize(static_cast<uint32_t>(n));
			}
			div_ = div;  // 分解能

			return n;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  テスト波形生成
			@param[in]	frq		周波数 [Hz]
		*/
		//-----------------------------------------------------------------//
		void build_sin(double frq)
		{
#if 0
			for(uint32_t i = 0; i < units_.size(); ++i) {
//				double t = 1.0 / frq;
				double t = 1.0 / 1024.0;
				units_[i] = 32768 - static_cast<UNIT>(sin(2.0 * vtx::get_pi<double>() * t * i) * 32767.0);
			}
#endif
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  波形コピー
			@param[in]	ch		チャネル
			@param[in]	src		波形ソース
			@param[in]	len		波形数
		*/
		//-----------------------------------------------------------------//
		void copy(uint32_t ch, const UNIT* src, uint32_t len)
		{
			if(len > ch_[ch].units_.size()) len = ch_[ch].units_.size();
			for(uint32_t i = 0; i < len; ++i) {
				ch_[ch].units_[i] = *src++;
			}
			ch_[ch].param_.update_ = true;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  レンダリング
   			@param[in]	size	描画サイズ（ピクセル）
			@param[in]	step	時間軸ステップ（65536を1.0）
		*/
		//-----------------------------------------------------------------//
		void render(const vtx::ipos& size, uint32_t tstep)
		{
			bool update_grid = false;
			for(uint32_t n = 0; n < CHN; ++n) {
				ch_t& t = ch_[n];
				bool update = false;
				if(t.lines_.size() != size.x) {
					t.lines_.resize(size.x);
					update = true;
					update_grid = true;
				}
				if(t.tstep_ != tstep) {
					t.tstep_ = tstep;
					update = true;
				}
				if(update || t.param_.update_) {
					float gain = t.param_.gain_;
					uint32_t ts = 0;
					for(uint32_t i = 0; i < size.x; ++i) {
						float v = static_cast<float>(t.units_[ts >> 16]);
						t.lines_[i] = vtx::spos(i, v * gain);
						ts += tstep;
					}
					t.param_.update_ = false;
				}
				glPushMatrix();
				gl::glTranslate(0, t.param_.offset_);
				gl::glColor(t.param_.color_);
				gl::draw_line_strip(t.lines_);
				glPopMatrix();
			}
			if(update_grid) {
				info_.build_grid(size);
			}
			info_.render_grid();
		}
	};
}
<|endoftext|>


<commit_before>#pragma once

#include <memory>
#include <vector>

#include <boost/thread/tss.hpp>

#include "attribute.hpp"
#include "common.hpp"
#include "error/handler.hpp"
#include "filter.hpp"
#include "frontend.hpp"
#include "keyword.hpp"
#include "keyword/message.hpp"
#include "keyword/severity.hpp"
#include "keyword/timestamp.hpp"
#include "keyword/thread.hpp"
#include "universe.hpp"
#include "blackhole/utils/noexcept.hpp"
#include "utils/noncopyable.hpp"
#include "utils/unique.hpp"

namespace blackhole {

class scoped_attributes_concept_t;

class logger_base_t {
    bool m_enabled;

protected:
    filter_t m_filter;
    log::exception_handler_t m_exception_handler;

    std::vector<std::unique_ptr<base_frontend_t>> m_frontends;

    log::attributes_t m_global_attributes;

    boost::thread_specific_ptr<scoped_attributes_concept_t> m_scoped_attributes;

    friend class scoped_attributes_concept_t;

    friend void swap(logger_base_t&, logger_base_t&) BLACKHOLE_NOEXCEPT;

public:
    logger_base_t();

    //! @compat GCC4.4
    //! Blaming GCC4.4 - it needs explicit move constructor definition,
    //! because it cannot define default move constructor for derived class.
    logger_base_t(logger_base_t&& other) BLACKHOLE_NOEXCEPT;
    logger_base_t& operator=(logger_base_t&& other) BLACKHOLE_NOEXCEPT;

    bool enabled() const;
    void enable();
    void disable();
    void set_filter(filter_t&& filter);
    void add_attribute(const log::attribute_pair_t& attribute);
    void add_frontend(std::unique_ptr<base_frontend_t> frontend);
    void set_exception_handler(log::exception_handler_t&& handler);

    log::record_t open_record() const;
    log::record_t open_record(log::attribute_pair_t local_attribute) const;
    log::record_t open_record(log::attributes_t local_attributes) const;

    void push(log::record_t&& record) const;

private:
    log::attributes_t get_event_attributes() const;
    log::attributes_t get_thread_attributes() const;
};

// NOTE: It's not movable to avoid moving to another thread.
class scoped_attributes_concept_t {
    BLACKHOLE_DECLARE_NONCOPYABLE(scoped_attributes_concept_t);

    logger_base_t *m_logger;
    scoped_attributes_concept_t *m_previous;

    friend void swap(logger_base_t&, logger_base_t&) BLACKHOLE_NOEXCEPT;

public:
    scoped_attributes_concept_t(logger_base_t& log);
    ~scoped_attributes_concept_t();

    virtual const log::attributes_t& attributes() const = 0;

protected:
    bool has_parent() const;
    const scoped_attributes_concept_t& parent() const;
};

template<typename Level>
class verbose_logger_t : public logger_base_t {
public:
    typedef Level level_type;

public:
    verbose_logger_t() :
        logger_base_t()
    {}

    // GCC 4.4 doesn't create default copy/move constructor for derived classes.
    // It's a bug.
    verbose_logger_t(verbose_logger_t&& other) BLACKHOLE_NOEXCEPT :
        logger_base_t(std::move(other))
    {}

    verbose_logger_t& operator=(verbose_logger_t&& other) BLACKHOLE_NOEXCEPT {
        logger_base_t::operator=(std::move(other));
        return *this;
    }

    using logger_base_t::open_record;

    log::record_t open_record(Level level) const {
        log::attributes_t attributes = { keyword::severity<Level>() = level };
        return logger_base_t::open_record(std::move(attributes));
    }
};

} // namespace blackhole

#if defined(BLACKHOLE_HEADER_ONLY)
#include "blackhole/implementation/logger.ipp"
#endif
<commit_msg>[Code Style] Comments improved.<commit_after>#pragma once

#include <memory>
#include <vector>

#include <boost/thread/tss.hpp>

#include "attribute.hpp"
#include "common.hpp"
#include "error/handler.hpp"
#include "filter.hpp"
#include "frontend.hpp"
#include "keyword.hpp"
#include "keyword/message.hpp"
#include "keyword/severity.hpp"
#include "keyword/timestamp.hpp"
#include "keyword/thread.hpp"
#include "universe.hpp"
#include "blackhole/utils/noexcept.hpp"
#include "utils/noncopyable.hpp"
#include "utils/unique.hpp"

namespace blackhole {

class scoped_attributes_concept_t;

class logger_base_t {
    bool m_enabled;

protected:
    filter_t m_filter;
    log::exception_handler_t m_exception_handler;

    std::vector<std::unique_ptr<base_frontend_t>> m_frontends;

    log::attributes_t m_global_attributes;

    boost::thread_specific_ptr<scoped_attributes_concept_t> m_scoped_attributes;

    friend class scoped_attributes_concept_t;

    friend void swap(logger_base_t&, logger_base_t&) BLACKHOLE_NOEXCEPT;

public:
    logger_base_t();

    //! @compat GCC4.4
    //! Blaming GCC4.4 - it needs explicit move constructor definition,
    //! because it cannot define default move constructor for derived class.
    logger_base_t(logger_base_t&& other) BLACKHOLE_NOEXCEPT;
    logger_base_t& operator=(logger_base_t&& other) BLACKHOLE_NOEXCEPT;

    bool enabled() const;
    void enable();
    void disable();
    void set_filter(filter_t&& filter);
    void add_attribute(const log::attribute_pair_t& attribute);
    void add_frontend(std::unique_ptr<base_frontend_t> frontend);
    void set_exception_handler(log::exception_handler_t&& handler);

    log::record_t open_record() const;
    log::record_t open_record(log::attribute_pair_t local_attribute) const;
    log::record_t open_record(log::attributes_t local_attributes) const;

    void push(log::record_t&& record) const;

private:
    log::attributes_t get_event_attributes() const;
    log::attributes_t get_thread_attributes() const;
};

// NOTE: It's not movable to avoid moving to another thread.
class scoped_attributes_concept_t {
    BLACKHOLE_DECLARE_NONCOPYABLE(scoped_attributes_concept_t);

    logger_base_t *m_logger;
    scoped_attributes_concept_t *m_previous;

    friend void swap(logger_base_t&, logger_base_t&) BLACKHOLE_NOEXCEPT;

public:
    scoped_attributes_concept_t(logger_base_t& log);
    ~scoped_attributes_concept_t();

    virtual const log::attributes_t& attributes() const = 0;

protected:
    bool has_parent() const;
    const scoped_attributes_concept_t& parent() const;
};

template<typename Level>
class verbose_logger_t : public logger_base_t {
public:
    typedef Level level_type;

public:
    verbose_logger_t() :
        logger_base_t()
    {}

    //! @compat GCC4.4
    //! GCC 4.4 doesn't create default copy/move constructor for derived
    //! classes. It's a bug.
    verbose_logger_t(verbose_logger_t&& other) BLACKHOLE_NOEXCEPT :
        logger_base_t(std::move(other))
    {}

    verbose_logger_t& operator=(verbose_logger_t&& other) BLACKHOLE_NOEXCEPT {
        logger_base_t::operator=(std::move(other));
        return *this;
    }

    using logger_base_t::open_record;

    log::record_t open_record(Level level) const {
        log::attributes_t attributes = { keyword::severity<Level>() = level };
        return logger_base_t::open_record(std::move(attributes));
    }
};

} // namespace blackhole

#if defined(BLACKHOLE_HEADER_ONLY)
#include "blackhole/implementation/logger.ipp"
#endif
<|endoftext|>


<commit_before>/*
 * gnoproj
 *
 * Copyright (c) 2013-2015 FOXEL SA - http://foxel.ch
 * Please read <http://foxel.ch/license> for more information.
 *
 *
 * Author(s):
 *
 *      Stéphane Flotron <s.flotron@foxel.ch>
 *
 * Contributor(s):
 *
 *      Luc Deschenaux <luc.deschenaux@foxel.ch>
 *
 *
 * This file is part of the FOXEL project <http://foxel.ch>.
 *
 * This program 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.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *
 * Additional Terms:
 *
 *      You are required to preserve legal notices and author attributions in
 *      that material or in the Appropriate Legal Notices displayed by works
 *      containing it.
 *
 *      You are required to attribute the work as explained in the "Usage and
 *      Attribution" section of <http://foxel.ch/license>.
 */

#include "gnoproj.hpp"
#include "tools.hpp"
#include <cstring>

using namespace std;
using namespace cv;

/*********************************************************************
 * Split an input string with a delimiter and fill a string vector
 *
 *********************************************************************
 */

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

    /* Usage branch */
    if ( argc != 4 || !strcmp( argv[1], "help" ) || !strcmp(argv[1],"-h") || !strcmp(argv[1],"--help")  ) {
        /* Display help */
        printf( "Usage : %s <input_image>  <camera mac adress>  <mount point> [ <focal> ]\n\n",argv[0]);
        return 1;
    }

    // load inputs
    char* input_image_filename=argv[1]; // eqr image (input) filename
    std::string mac_address(argv[2]);  //mac adress
    std::string mount_point(argv[3]);  // mount point
    std::string input_image(input_image_filename);
    std::string output_image_filename; // output image filename

    // check is a focal length is given, and update method if necessary
    int  normalizedFocal(0);  // gnomonic projection method. 0 elphel method (default), 1 with constant focal
    double focal = 0.0;       // focal length (in mm)
    double minFocal = 0.05 ;  // lower bound for focal length
    double maxFocal = 500.0;  // upper bound for focal length
    std::string inputFocal((argc==5)?argv[4]:"");

    // verify if input is present, and if yes, if it is consistant
    if(inputFocal.length())
    {
      focal  = atof(inputFocal.c_str());
      normalizedFocal = 1;

      // check input focal
      if( focal < minFocal || focal > maxFocal)
      {
        std::cerr << "Focal length is less than " << minFocal << " mm or bigger than " << maxFocal << " mm. ";
        std::cerr << "Input focal is " << inputFocal << endl;
        return 0;
      }
    }

    // extract channel information from image name
    std::vector<string>  splitted_name;
    std::vector<string>  out_split;

    split( input_image, "-", splitted_name );
    split( input_image, "_", out_split );

    const size_t sensor_index=atoi(splitted_name[1].c_str());
    sensorData   sensorSD;

    bool  bLoadCalibration = loadCalibrationData
                   ( sensorSD,
                     sensor_index,
                     mount_point,
                     mac_address );

    // load image
    IplImage* eqr_img = cvLoadImage(input_image_filename, CV_LOAD_IMAGE_COLOR );

    /* Initialize output image structure */
    IplImage* out_img = cvCreateImage( cvSize( sensorSD.lfWidth, sensorSD.lfHeight ), IPL_DEPTH_8U , eqr_img->nChannels );

    if(!normalizedFocal){
        /* Gnomonic projection of the equirectangular tile */
        lg_ttg_elphel(
            ( inter_C8_t *) eqr_img->imageData,
            eqr_img->width,
            eqr_img->height,
            eqr_img->nChannels,
            ( inter_C8_t *) out_img->imageData,
            out_img->width,
            out_img->height,
            out_img->nChannels,
            sensorSD.lfpx0,
            sensorSD.lfpy0,
            sensorSD.lfImageFullWidth,
            sensorSD.lfImageFullHeight-1, // there's an extra pixel for wrapping
            sensorSD.lfXPosition,
            sensorSD.lfYPosition,
            sensorSD.lfRoll,
            sensorSD.lfAzimuth,
            sensorSD.lfElevation,
            sensorSD.lfHeading,
            sensorSD.lfPixelSize,
            sensorSD.lfFocalLength,
            li_bicubicf
        );

        // create output image name
        output_image_filename+=out_split[0]+"_"+out_split[1]+"-RECT-SENSOR.tiff";
    }
    else
    {
      /* Gnomonic projection of the equirectangular tile */
       lg_ttg_center(
          ( inter_C8_t *) eqr_img->imageData,
          eqr_img->width,
          eqr_img->height,
          eqr_img->nChannels,
          ( inter_C8_t *) out_img->imageData,
          out_img->width,
          out_img->height,
          out_img->nChannels,
          sensorSD.lfImageFullWidth,
          sensorSD.lfImageFullHeight-1,
          sensorSD.lfXPosition,
          sensorSD.lfYPosition,
          sensorSD.lfAzimuth + sensorSD.lfHeading + LG_PI,
          sensorSD.lfElevation,
          sensorSD.lfRoll,
          focal,
          sensorSD.lfPixelSize,
          li_bicubicf
        );

        // create output image name
        output_image_filename+=out_split[0]+out_split[1]+"-RECT-CONFOC.tiff";
    }

    /* Gnomonic image exportation */
    cvSaveImage(output_image_filename.c_str() , out_img, NULL );

    /* Free memory */
    cvReleaseImage(&eqr_img);
    cvReleaseImage(&out_img);

    return 0;
}
<commit_msg>improved exception management<commit_after>/*
 * gnoproj
 *
 * Copyright (c) 2013-2015 FOXEL SA - http://foxel.ch
 * Please read <http://foxel.ch/license> for more information.
 *
 *
 * Author(s):
 *
 *      Stéphane Flotron <s.flotron@foxel.ch>
 *
 * Contributor(s):
 *
 *      Luc Deschenaux <luc.deschenaux@foxel.ch>
 *
 *
 * This file is part of the FOXEL project <http://foxel.ch>.
 *
 * This program 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.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *
 * Additional Terms:
 *
 *      You are required to preserve legal notices and author attributions in
 *      that material or in the Appropriate Legal Notices displayed by works
 *      containing it.
 *
 *      You are required to attribute the work as explained in the "Usage and
 *      Attribution" section of <http://foxel.ch/license>.
 */

#include "gnoproj.hpp"
#include "tools.hpp"
#include <cstring>

using namespace std;
using namespace cv;

/*********************************************************************
 * Split an input string with a delimiter and fill a string vector
 *
 *********************************************************************
 */

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

    /* Usage branch */
    if ( argc != 4 || !strcmp( argv[1], "help" ) || !strcmp(argv[1],"-h") || !strcmp(argv[1],"--help")  ) {
        /* Display help */
        printf( "Usage : %s <input_image>  <camera mac adress>  <mount point> [ <focal> ]\n\n",argv[0]);
        return 1;
    }

    // load inputs
    char* input_image_filename=argv[1]; // eqr image (input) filename
    std::string mac_address(argv[2]);  //mac adress
    std::string mount_point(argv[3]);  // mount point
    std::string input_image(input_image_filename);
    std::string output_image_filename; // output image filename

    // check is a focal length is given, and update method if necessary
    int  normalizedFocal(0);  // gnomonic projection method. 0 elphel method (default), 1 with constant focal
    double focal = 0.0;       // focal length (in mm)
    double minFocal = 0.05 ;  // lower bound for focal length
    double maxFocal = 500.0;  // upper bound for focal length
    std::string inputFocal((argc==5)?argv[4]:"");

    // verify if input is present, and if yes, if it is consistant
    if(inputFocal.length())
    {
      focal  = atof(inputFocal.c_str());
      normalizedFocal = 1;

      // check input focal
      if( focal < minFocal || focal > maxFocal)
      {
        std::cerr << "Focal length is less than " << minFocal << " mm or bigger than " << maxFocal << " mm. ";
        std::cerr << "Input focal is " << inputFocal << endl;
        return 0;
      }
    }

    // extract channel information from image name
    std::vector<string>  splitted_name;
    std::vector<string>  out_split;

    split( input_image, "-", splitted_name );
    split( input_image, "_", out_split );

    const size_t sensor_index=atoi(splitted_name[1].c_str());
    sensorData   sensorSD;

    // load calibration informations
    bool  bLoadCalibration = loadCalibrationData
                   ( sensorSD,
                     sensor_index,
                     mount_point,
                     mac_address );

    if( !bLoadCalibration )
    {
        std::cerr << " Failed to load calibration informations. Exit " << std::endl;
        return -1;
    }

    // load image
    IplImage* eqr_img = cvLoadImage(input_image_filename, CV_LOAD_IMAGE_COLOR );

    /* Initialize output image structure */
    IplImage* out_img = cvCreateImage( cvSize( sensorSD.lfWidth, sensorSD.lfHeight ), IPL_DEPTH_8U , eqr_img->nChannels );

    if(!normalizedFocal){
        /* Gnomonic projection of the equirectangular tile */
        lg_ttg_elphel(
            ( inter_C8_t *) eqr_img->imageData,
            eqr_img->width,
            eqr_img->height,
            eqr_img->nChannels,
            ( inter_C8_t *) out_img->imageData,
            out_img->width,
            out_img->height,
            out_img->nChannels,
            sensorSD.lfpx0,
            sensorSD.lfpy0,
            sensorSD.lfImageFullWidth,
            sensorSD.lfImageFullHeight-1, // there's an extra pixel for wrapping
            sensorSD.lfXPosition,
            sensorSD.lfYPosition,
            sensorSD.lfRoll,
            sensorSD.lfAzimuth,
            sensorSD.lfElevation,
            sensorSD.lfHeading,
            sensorSD.lfPixelSize,
            sensorSD.lfFocalLength,
            li_bicubicf
        );

        // create output image name
        output_image_filename+=out_split[0]+"_"+out_split[1]+"-RECT-SENSOR.tiff";
    }
    else
    {
      /* Gnomonic projection of the equirectangular tile */
       lg_ttg_center(
          ( inter_C8_t *) eqr_img->imageData,
          eqr_img->width,
          eqr_img->height,
          eqr_img->nChannels,
          ( inter_C8_t *) out_img->imageData,
          out_img->width,
          out_img->height,
          out_img->nChannels,
          sensorSD.lfImageFullWidth,
          sensorSD.lfImageFullHeight-1,
          sensorSD.lfXPosition,
          sensorSD.lfYPosition,
          sensorSD.lfAzimuth + sensorSD.lfHeading + LG_PI,
          sensorSD.lfElevation,
          sensorSD.lfRoll,
          focal,
          sensorSD.lfPixelSize,
          li_bicubicf
        );

        // create output image name
        output_image_filename+=out_split[0]+out_split[1]+"-RECT-CONFOC.tiff";
    }

    /* Gnomonic image exportation */
    cvSaveImage(output_image_filename.c_str() , out_img, NULL );

    /* Free memory */
    cvReleaseImage(&eqr_img);
    cvReleaseImage(&out_img);

    return 0;
}
<|endoftext|>


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

#include <stdio.h>
#include <vector>
#include <stack>

#include <com/sun/star/registry/XImplementationRegistration.hpp>
#include <com/sun/star/lang/XComponent.hpp>

#include <com/sun/star/xml/sax/SAXParseException.hpp>
#include <com/sun/star/xml/sax/XParser.hpp>
#include <com/sun/star/xml/sax/XExtendedDocumentHandler.hpp>

#include <com/sun/star/io/XOutputStream.hpp>
#include <com/sun/star/io/XActiveDataSource.hpp>

#include <cppuhelper/servicefactory.hxx>
#include <cppuhelper/implbase1.hxx>
#include <cppuhelper/implbase3.hxx>

#include <vos/diagnose.hxx>

#include <tools/string.hxx>
#include "LocaleNode.hxx"

using namespace ::rtl;
using namespace ::std;
using namespace ::cppu;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::registry;
using namespace ::com::sun::star::xml::sax;
using namespace ::com::sun::star::io;

/************
 * Sequence of bytes -> InputStream
 ************/
class OInputStream : public WeakImplHelper1 < XInputStream >
{
public:
    OInputStream( const Sequence< sal_Int8 >&seq ) :
        m_seq( seq ),
        nPos( 0 )
        {}

public:
    virtual sal_Int32 SAL_CALL readBytes( Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead )
        throw(NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)
        {
            nBytesToRead = (nBytesToRead > m_seq.getLength() - nPos ) ?
                m_seq.getLength() - nPos :
                nBytesToRead;
            aData = Sequence< sal_Int8 > ( &(m_seq.getConstArray()[nPos]) , nBytesToRead );
            nPos += nBytesToRead;
            return nBytesToRead;
        }
    virtual sal_Int32 SAL_CALL readSomeBytes(
        ::com::sun::star::uno::Sequence< sal_Int8 >& aData,
        sal_Int32 nMaxBytesToRead )
        throw(NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)
        {
            return readBytes( aData, nMaxBytesToRead );
        }
    virtual void SAL_CALL skipBytes( sal_Int32 nBytesToSkip )
        throw(NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)
        {
            // not implemented
        }
    virtual sal_Int32 SAL_CALL available(  )
        throw(NotConnectedException, IOException, RuntimeException)
        {
            return m_seq.getLength() - nPos;
        }
    virtual void SAL_CALL closeInput(  )
        throw(NotConnectedException, IOException, RuntimeException)
        {
            // not needed
        }
    sal_Int32 nPos;
    Sequence< sal_Int8> m_seq;
};

//-------------------------------
// Helper : create an input stream from a file
//------------------------------
Reference< XInputStream > createStreamFromFile(
    const char *pcFile )
{
    FILE *f = fopen( pcFile , "rb" );
    Reference<  XInputStream >  r;

    if( f ) {
        fseek( f , 0 , SEEK_END );
        int nLength = ftell( f );
        fseek( f , 0 , SEEK_SET );

        Sequence<sal_Int8> seqIn(nLength);
        fread( seqIn.getArray() , nLength , 1 , f );

        r = Reference< XInputStream > ( new OInputStream( seqIn ) );
        fclose( f );
    }
    return r;
}

class TestDocumentHandler :
    public WeakImplHelper3< XExtendedDocumentHandler , XEntityResolver , XErrorHandler >
{
public:
    TestDocumentHandler(const char* locale, const char* outFile ) :
      of(outFile, locale), nbOfCurrencies(0), nbOfCalendars(0), nbOfCollations(0),
      nbOfFormatElements(0), nbOfDays(50), nbOfMonths(50), nbOfEras(10),
      nbOfTransliterations(0), isStartDayOfWeek(false), foundDefaultName(false),
      flag(-1), foundVarient(false), openElement(false), rootNode(0)
    {
        strncpy( theLocale, locale, sizeof(theLocale) );
        theLocale[sizeof(theLocale)-1] = 0;
    }

    ~TestDocumentHandler(  )
    {
        of.closeOutput();
    }

public: // Error handler
    virtual void SAL_CALL error(const Any& aSAXParseException) throw (SAXException, RuntimeException)
    {
        printf( "Error !\n" );
        throw  SAXException(
            OUString( RTL_CONSTASCII_USTRINGPARAM("error from error handler")) ,
            Reference < XInterface >() ,
            aSAXParseException );
    }
    virtual void SAL_CALL fatalError(const Any& aSAXParseException) throw (SAXException, RuntimeException)
    {
        printf( "Fatal Error !\n" );
    }
    virtual void SAL_CALL warning(const Any& aSAXParseException) throw (SAXException, RuntimeException)
    {
        printf( "Warning !\n" );
    }

public: // ExtendedDocumentHandler

    stack<LocaleNode *> currentNode ;
    sal_Bool  fElement ;
    LocaleNode * rootNode;

    virtual void SAL_CALL startDocument(void) throw (SAXException, RuntimeException)
    {
    printf( "parsing document %s started\n", theLocale);
    of.writeAsciiString("#include <sal/types.h>\n\n\n");
#if SUPD > 618
    of.writeAsciiString("#include <stdio.h> // debug printfs\n\n");
#endif // SUPD > 618
    of.writeAsciiString("extern \"C\" {\n\n");
    }

    virtual void SAL_CALL endDocument(void) throw (SAXException, RuntimeException)
    {
        if (rootNode)
            rootNode->generateCode(of);
        printf( "parsing document %s finished\n", theLocale);

        of.writeAsciiString("} // extern \"C\"\n\n");
        of.closeOutput();
    }

    virtual void SAL_CALL startElement(const OUString& aName,
                              const Reference< XAttributeList > & xAttribs)
        throw (SAXException,RuntimeException)
    {

        LocaleNode * l =  LocaleNode::createNode (aName, xAttribs);
        if (!currentNode.empty() ) {
            LocaleNode * ln = (LocaleNode *) currentNode . top();
            ln->addChild(l);
        } else {
            rootNode = l;
        }
        currentNode . push (l);
    }

    virtual void SAL_CALL endElement(const OUString& aName) throw (SAXException,RuntimeException)
    {
        currentNode . pop();
    }

    virtual void SAL_CALL characters(const OUString& aChars) throw (SAXException,RuntimeException)
    {

        LocaleNode * l = currentNode . top();
        l->setValue (aChars);
        ::rtl::OUString str(aChars);
        sal_Unicode nonBreakSPace[2]= {0xa, 0x0};
        if(!openElement || str.equals(nonBreakSPace))
          return;
    }

    virtual void SAL_CALL ignorableWhitespace(const OUString& aWhitespaces) throw (SAXException,RuntimeException)
    {
   }

    virtual void SAL_CALL processingInstruction(const OUString& aTarget, const OUString& aData) throw (SAXException,RuntimeException)
    {
        // ignored
    }

    virtual void SAL_CALL setDocumentLocator(const Reference< XLocator> & xLocator)
        throw (SAXException,RuntimeException)
    {
        // ignored
    }

    virtual InputSource SAL_CALL resolveEntity(
        const OUString& sPublicId,
        const OUString& sSystemId)
        throw (RuntimeException)
    {
        InputSource source;
        source.sSystemId = sSystemId;
        source.sPublicId = sPublicId;

        source.aInputStream = createStreamFromFile(
            OUStringToOString( sSystemId , RTL_TEXTENCODING_ASCII_US) );

        return source;
    }

    virtual void SAL_CALL startCDATA(void) throw (SAXException,RuntimeException)
    {
    }
    virtual void SAL_CALL endCDATA(void) throw (RuntimeException)
    {
    }
    virtual void SAL_CALL comment(const OUString& sComment) throw (SAXException,RuntimeException)
    {
    }
    virtual void SAL_CALL unknown(const OUString& sString) throw (SAXException,RuntimeException)
    {
    }

    virtual void SAL_CALL allowLineBreak( void) throw (SAXException, RuntimeException )
    {

    }

public:
    ::rtl::OUString currentElement;
    sal_Int16 nbOfCurrencies;
    sal_Int16 nbOfCalendars;
    sal_Int16 nbOfFormatElements;
    sal_Int16 nbOfTransliterations;
    sal_Int16 nbOfCollations;
    Sequence<sal_Int16> nbOfDays;
    Sequence<sal_Int16> nbOfMonths;
    Sequence<sal_Int16> nbOfEras;
    sal_Char *elementTag;
    sal_Char theLocale[50];
    sal_Int16 flag;
    OFileWriter of;
    sal_Bool isStartDayOfWeek;
    sal_Bool foundDefaultName;
    sal_Bool foundVarient;
        sal_Bool openElement;
};

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

    if( argc < 6) {
        printf( "usage : %s <locaLe> <XML inputfile> <destination file> <services.rdb location> <types.rdb location>\n", argv[0] );
        exit( 1 );
    }

    // create service manager
    Reference< XMultiServiceFactory > xSMgr;
    try
    {
        xSMgr = createRegistryServiceFactory(
            ::rtl::OUString::createFromAscii(argv[4]),
            ::rtl::OUString::createFromAscii(argv[5]) );
    }
    catch ( Exception& )
    {
        printf( "Exception on createRegistryServiceFactory\n" );
        exit(1);
    }

    Reference < XImplementationRegistration > xReg;
    try
    {
        // Create registration service
        Reference < XInterface > x = xSMgr->createInstance(
            OUString::createFromAscii( "com.sun.star.registry.ImplementationRegistration" ) );
        xReg = Reference<  XImplementationRegistration > ( x , UNO_QUERY );
    }
    catch( Exception & ) {
        printf( "Couldn't create ImplementationRegistration service\n" );
        exit(1);
    }

    OString sTestName;
    try
    {
        // Load dll for the tested component
        OUString aDllName =
            OUString::createFromAscii( "sax.uno" SAL_DLLEXTENSION );
        xReg->registerImplementation(
            OUString::createFromAscii( "com.sun.star.loader.SharedLibrary" ),
            aDllName,
            Reference< XSimpleRegistry > ()  );
    }
    catch( Exception &e ) {
        printf( "Couldn't raise sax.uno library!\n" );
        printf( "%s\n" , OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US ).getStr() );

        exit(1);
    }

    //--------------------------------
    // parser demo
    // read xml from a file and count elements
    //--------------------------------
    Reference< XInterface > x = xSMgr->createInstance(
        OUString::createFromAscii( "com.sun.star.xml.sax.Parser" ) );
    if( x.is() )
    {
        Reference< XParser > rParser( x , UNO_QUERY );

        // create and connect the document handler to the parser
        TestDocumentHandler *pDocHandler = new TestDocumentHandler( argv[1], argv[3]);

        Reference < XDocumentHandler >  rDocHandler( (XDocumentHandler *) pDocHandler );
        Reference< XEntityResolver > rEntityResolver( (XEntityResolver *) pDocHandler );

        rParser->setDocumentHandler( rDocHandler );
        rParser->setEntityResolver( rEntityResolver );

        // create the input stream
        InputSource source;
        source.aInputStream = createStreamFromFile( argv[2] );
        source.sSystemId    = OUString::createFromAscii( argv[2] );

        try
        {
            // start parsing
            rParser->parseStream( source );
        }

        catch( Exception & e )
        {
            OString o1 = OUStringToOString(e.Message, RTL_TEXTENCODING_UTF8 );
            printf( "Exception during parsing : %s\n" ,  o1.getStr() );
            exit(1);
        }
    }
    else
    {
        printf( "couln't create sax-parser component\n" );
        exit(1);
    }

    return 0;
}
<commit_msg>INTEGRATION: CWS i18n10 (1.7.48); FILE MERGED 2003/12/17 20:21:20 khong 1.7.48.1: #i22138# remove TOOLS usage from i18npool, and make i18npool a good component<commit_after>/*************************************************************************
 *
 *  $RCSfile: saxparser.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2004-01-20 13:42:07 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <stdio.h>
#include <stack>

#include <com/sun/star/registry/XImplementationRegistration.hpp>
#include <com/sun/star/lang/XComponent.hpp>

#include <com/sun/star/xml/sax/SAXParseException.hpp>
#include <com/sun/star/xml/sax/XParser.hpp>
#include <com/sun/star/xml/sax/XExtendedDocumentHandler.hpp>

#include <com/sun/star/io/XOutputStream.hpp>
#include <com/sun/star/io/XActiveDataSource.hpp>

#include <cppuhelper/servicefactory.hxx>
#include <cppuhelper/implbase1.hxx>
#include <cppuhelper/implbase3.hxx>

#include <vos/diagnose.hxx>

#include "LocaleNode.hxx"

using namespace ::rtl;
using namespace ::std;
using namespace ::cppu;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::registry;
using namespace ::com::sun::star::xml::sax;
using namespace ::com::sun::star::io;

/************
 * Sequence of bytes -> InputStream
 ************/
class OInputStream : public WeakImplHelper1 < XInputStream >
{
public:
    OInputStream( const Sequence< sal_Int8 >&seq ) :
        m_seq( seq ),
        nPos( 0 )
        {}

public:
    virtual sal_Int32 SAL_CALL readBytes( Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead )
        throw(NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)
        {
            nBytesToRead = (nBytesToRead > m_seq.getLength() - nPos ) ?
                m_seq.getLength() - nPos :
                nBytesToRead;
            aData = Sequence< sal_Int8 > ( &(m_seq.getConstArray()[nPos]) , nBytesToRead );
            nPos += nBytesToRead;
            return nBytesToRead;
        }
    virtual sal_Int32 SAL_CALL readSomeBytes(
        ::com::sun::star::uno::Sequence< sal_Int8 >& aData,
        sal_Int32 nMaxBytesToRead )
        throw(NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)
        {
            return readBytes( aData, nMaxBytesToRead );
        }
    virtual void SAL_CALL skipBytes( sal_Int32 nBytesToSkip )
        throw(NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)
        {
            // not implemented
        }
    virtual sal_Int32 SAL_CALL available(  )
        throw(NotConnectedException, IOException, RuntimeException)
        {
            return m_seq.getLength() - nPos;
        }
    virtual void SAL_CALL closeInput(  )
        throw(NotConnectedException, IOException, RuntimeException)
        {
            // not needed
        }
    sal_Int32 nPos;
    Sequence< sal_Int8> m_seq;
};

//-------------------------------
// Helper : create an input stream from a file
//------------------------------
Reference< XInputStream > createStreamFromFile(
    const char *pcFile )
{
    FILE *f = fopen( pcFile , "rb" );
    Reference<  XInputStream >  r;

    if( f ) {
        fseek( f , 0 , SEEK_END );
        int nLength = ftell( f );
        fseek( f , 0 , SEEK_SET );

        Sequence<sal_Int8> seqIn(nLength);
        fread( seqIn.getArray() , nLength , 1 , f );

        r = Reference< XInputStream > ( new OInputStream( seqIn ) );
        fclose( f );
    }
    return r;
}

class TestDocumentHandler :
    public WeakImplHelper3< XExtendedDocumentHandler , XEntityResolver , XErrorHandler >
{
public:
    TestDocumentHandler(const char* locale, const char* outFile ) :
      of(outFile, locale), nbOfCurrencies(0), nbOfCalendars(0), nbOfCollations(0),
      nbOfFormatElements(0), nbOfDays(50), nbOfMonths(50), nbOfEras(10),
      nbOfTransliterations(0), isStartDayOfWeek(false), foundDefaultName(false),
      flag(-1), foundVarient(false), openElement(false), rootNode(0)
    {
        strncpy( theLocale, locale, sizeof(theLocale) );
        theLocale[sizeof(theLocale)-1] = 0;
    }

    ~TestDocumentHandler(  )
    {
        of.closeOutput();
    }

public: // Error handler
    virtual void SAL_CALL error(const Any& aSAXParseException) throw (SAXException, RuntimeException)
    {
        printf( "Error !\n" );
        throw  SAXException(
            OUString( RTL_CONSTASCII_USTRINGPARAM("error from error handler")) ,
            Reference < XInterface >() ,
            aSAXParseException );
    }
    virtual void SAL_CALL fatalError(const Any& aSAXParseException) throw (SAXException, RuntimeException)
    {
        printf( "Fatal Error !\n" );
    }
    virtual void SAL_CALL warning(const Any& aSAXParseException) throw (SAXException, RuntimeException)
    {
        printf( "Warning !\n" );
    }

public: // ExtendedDocumentHandler

    stack<LocaleNode *> currentNode ;
    sal_Bool  fElement ;
    LocaleNode * rootNode;

    virtual void SAL_CALL startDocument(void) throw (SAXException, RuntimeException)
    {
    printf( "parsing document %s started\n", theLocale);
    of.writeAsciiString("#include <sal/types.h>\n\n\n");
#if SUPD > 618
    of.writeAsciiString("#include <stdio.h> // debug printfs\n\n");
#endif // SUPD > 618
    of.writeAsciiString("extern \"C\" {\n\n");
    }

    virtual void SAL_CALL endDocument(void) throw (SAXException, RuntimeException)
    {
        if (rootNode)
            rootNode->generateCode(of);
        printf( "parsing document %s finished\n", theLocale);

        of.writeAsciiString("} // extern \"C\"\n\n");
        of.closeOutput();
    }

    virtual void SAL_CALL startElement(const OUString& aName,
                              const Reference< XAttributeList > & xAttribs)
        throw (SAXException,RuntimeException)
    {

        LocaleNode * l =  LocaleNode::createNode (aName, xAttribs);
        if (!currentNode.empty() ) {
            LocaleNode * ln = (LocaleNode *) currentNode . top();
            ln->addChild(l);
        } else {
            rootNode = l;
        }
        currentNode . push (l);
    }

    virtual void SAL_CALL endElement(const OUString& aName) throw (SAXException,RuntimeException)
    {
        currentNode . pop();
    }

    virtual void SAL_CALL characters(const OUString& aChars) throw (SAXException,RuntimeException)
    {

        LocaleNode * l = currentNode . top();
        l->setValue (aChars);
        ::rtl::OUString str(aChars);
        sal_Unicode nonBreakSPace[2]= {0xa, 0x0};
        if(!openElement || str.equals(nonBreakSPace))
          return;
    }

    virtual void SAL_CALL ignorableWhitespace(const OUString& aWhitespaces) throw (SAXException,RuntimeException)
    {
   }

    virtual void SAL_CALL processingInstruction(const OUString& aTarget, const OUString& aData) throw (SAXException,RuntimeException)
    {
        // ignored
    }

    virtual void SAL_CALL setDocumentLocator(const Reference< XLocator> & xLocator)
        throw (SAXException,RuntimeException)
    {
        // ignored
    }

    virtual InputSource SAL_CALL resolveEntity(
        const OUString& sPublicId,
        const OUString& sSystemId)
        throw (RuntimeException)
    {
        InputSource source;
        source.sSystemId = sSystemId;
        source.sPublicId = sPublicId;

        source.aInputStream = createStreamFromFile(
            OUStringToOString( sSystemId , RTL_TEXTENCODING_ASCII_US) );

        return source;
    }

    virtual void SAL_CALL startCDATA(void) throw (SAXException,RuntimeException)
    {
    }
    virtual void SAL_CALL endCDATA(void) throw (RuntimeException)
    {
    }
    virtual void SAL_CALL comment(const OUString& sComment) throw (SAXException,RuntimeException)
    {
    }
    virtual void SAL_CALL unknown(const OUString& sString) throw (SAXException,RuntimeException)
    {
    }

    virtual void SAL_CALL allowLineBreak( void) throw (SAXException, RuntimeException )
    {

    }

public:
    ::rtl::OUString currentElement;
    sal_Int16 nbOfCurrencies;
    sal_Int16 nbOfCalendars;
    sal_Int16 nbOfFormatElements;
    sal_Int16 nbOfTransliterations;
    sal_Int16 nbOfCollations;
    Sequence<sal_Int16> nbOfDays;
    Sequence<sal_Int16> nbOfMonths;
    Sequence<sal_Int16> nbOfEras;
    sal_Char *elementTag;
    sal_Char theLocale[50];
    sal_Int16 flag;
    OFileWriter of;
    sal_Bool isStartDayOfWeek;
    sal_Bool foundDefaultName;
    sal_Bool foundVarient;
        sal_Bool openElement;
};

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

    if( argc < 6) {
        printf( "usage : %s <locaLe> <XML inputfile> <destination file> <services.rdb location> <types.rdb location>\n", argv[0] );
        exit( 1 );
    }

    // create service manager
    Reference< XMultiServiceFactory > xSMgr;
    try
    {
        xSMgr = createRegistryServiceFactory(
            ::rtl::OUString::createFromAscii(argv[4]),
            ::rtl::OUString::createFromAscii(argv[5]) );
    }
    catch ( Exception& )
    {
        printf( "Exception on createRegistryServiceFactory\n" );
        exit(1);
    }

    Reference < XImplementationRegistration > xReg;
    try
    {
        // Create registration service
        Reference < XInterface > x = xSMgr->createInstance(
            OUString::createFromAscii( "com.sun.star.registry.ImplementationRegistration" ) );
        xReg = Reference<  XImplementationRegistration > ( x , UNO_QUERY );
    }
    catch( Exception & ) {
        printf( "Couldn't create ImplementationRegistration service\n" );
        exit(1);
    }

    OString sTestName;
    try
    {
        // Load dll for the tested component
        OUString aDllName =
            OUString::createFromAscii( "sax.uno" SAL_DLLEXTENSION );
        xReg->registerImplementation(
            OUString::createFromAscii( "com.sun.star.loader.SharedLibrary" ),
            aDllName,
            Reference< XSimpleRegistry > ()  );
    }
    catch( Exception &e ) {
        printf( "Couldn't raise sax.uno library!\n" );
        printf( "%s\n" , OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US ).getStr() );

        exit(1);
    }

    //--------------------------------
    // parser demo
    // read xml from a file and count elements
    //--------------------------------
    Reference< XInterface > x = xSMgr->createInstance(
        OUString::createFromAscii( "com.sun.star.xml.sax.Parser" ) );
    if( x.is() )
    {
        Reference< XParser > rParser( x , UNO_QUERY );

        // create and connect the document handler to the parser
        TestDocumentHandler *pDocHandler = new TestDocumentHandler( argv[1], argv[3]);

        Reference < XDocumentHandler >  rDocHandler( (XDocumentHandler *) pDocHandler );
        Reference< XEntityResolver > rEntityResolver( (XEntityResolver *) pDocHandler );

        rParser->setDocumentHandler( rDocHandler );
        rParser->setEntityResolver( rEntityResolver );

        // create the input stream
        InputSource source;
        source.aInputStream = createStreamFromFile( argv[2] );
        source.sSystemId    = OUString::createFromAscii( argv[2] );

        try
        {
            // start parsing
            rParser->parseStream( source );
        }

        catch( Exception & e )
        {
            OString o1 = OUStringToOString(e.Message, RTL_TEXTENCODING_UTF8 );
            printf( "Exception during parsing : %s\n" ,  o1.getStr() );
            exit(1);
        }
    }
    else
    {
        printf( "couln't create sax-parser component\n" );
        exit(1);
    }

    return 0;
}
<|endoftext|>