<commit_before>#include <ParkingShield.h>
#include <DeviceArduino.h>

// ---------------------------------------------------------------------------------------------------- //
// Helper
// ---------------------------------------------------------------------------------------------------- //
typedef enum
{
    BUTTON_S1,
    BUTTON_S2,
    BRIGHTNESS,
    TEMPERATURE,
    INPUT_MAX
} input_t;

typedef enum
{
    LED_GREEN = ParkingShield::GREEN_LED,
    LED_YELLOW = ParkingShield::YELLOW_LED,
    LED_RED = ParkingShield::RED_LED,
    BUZZER,
    OUTPUT_MAX
} output_t;

Device::pin_t const output_pins[OUTPUT_MAX] = {Device::DIGITAL_PIN_4, Device::ANALOG_PIN_5, Device::ANALOG_PIN_4, Device::DIGITAL_PIN_5};
Device::pin_t const input_pins[INPUT_MAX] = {Device::ANALOG_PIN_0, Device::ANALOG_PIN_1, Device::ANALOG_PIN_2, Device::ANALOG_PIN_3};
Device::pin_t const sevensegment_pins[8] = {Device::DIGITAL_PIN_7,Device::DIGITAL_PIN_8,Device::DIGITAL_PIN_9,Device::DIGITAL_PIN_10,Device::DIGITAL_PIN_11,Device::DIGITAL_PIN_12,Device::DIGITAL_PIN_13,Device::DIGITAL_PIN_6};

bool isInputPinValid(input_t inputPin)
{
    return inputPin < INPUT_MAX;
}

bool isOutputPinValid(output_t outputPin)
{
    return outputPin < OUTPUT_MAX;
}

bool isLedValid(ParkingShield::led_t led)
{
    return led < ParkingShield::LED_MAX;
}

void setPinMode(Device::pin_t pin, Device::pinmode_t pinmode)
{
    Device::setPinMode(pin, pinmode);
}

void setupOutput()
{
    for (unsigned int output = 0; output < OUTPUT_MAX; output++)
        setPinMode(output_pins[output], Device::PINMODE_OUTPUT);
}

void setupInput()
{
    for (unsigned int input = 0; input < INPUT_MAX; input++)
        setPinMode(input_pins[input], Device::PINMODE_INPUT);
}

unsigned int analogReadPin(input_t inputPin)
{
    if (isInputPinValid(inputPin))
        return Device::analogReadPin(input_pins[inputPin]);

    return 0;
}

void analogWritePin(output_t outputPin, uint8_t value)
{
    if (isOutputPinValid(outputPin))
        Device::analogWritePin(output_pins[outputPin], value);
}

Device::signal_t digitalReadPin(input_t inputPin)
{
    if (isInputPinValid(inputPin))
        return Device::digitalReadPin(input_pins[inputPin]);

    return Device::SIGNAL_LOW;
}

void digitalWritePin(output_t outputPin, Device::signal_t signal)
{
    if (isOutputPinValid(outputPin))
        Device::digitalWritePin(output_pins[outputPin], signal);
}

void ParkingShield::setLed(led_t led, bool enable)
{
    if (isLedValid(led))
        digitalWritePin(static_cast<output_t>(led), enable ? Device::SIGNAL_LOW : Device::SIGNAL_HIGH);
}

void setAllLeds(bool enable)
{
    for (unsigned int led = 0; led < ParkingShield::LED_MAX; led++)
        ParkingShield::setLed(static_cast<ParkingShield::led_t>(led), enable);
}

// ---------------------------------------------------------------------------------------------------- //
// Public
// ---------------------------------------------------------------------------------------------------- //
ParkingShield::ParkingShield(void) : sevenSeg(sevensegment_pins)
{
    setupOutput();
    setupInput();

    setAllLeds(false);
}

void ParkingShield::setDebounceInterval(unsigned int interval)
{
    debounceInterval = interval;
}

void ParkingShield::setRepeatInterval(unsigned int interval)
{
    repeatInterval = interval;
}

bool ParkingShield::sampleButton(unsigned int buttonNumber, button_state_t &button)
{
    unsigned long time = Device::milliseconds();
    if (time - button.lockTime >= debounceInterval)
        button.locked = false;

    if (!button.locked)
    {
        bool button_pressed_before = button.pressed;
        button.pressed = Device::digitalReadPin(input_pins[buttonNumber]) == Device::SIGNAL_HIGH;
        if (button_pressed_before != button.pressed)
        {
            button.locked = true;
            button.lockTime = time;
        }
    }

    if (button.pressed && time - button.repeatTime >= repeatInterval)
    {
        button.repeatTime = time;
        return true;
    }
    return false;
}

bool ParkingShield::buttonS1Pressed(void)
{
  return sampleButton(BUTTON_S1, buttons[0]);
}

bool ParkingShield::buttonS2Pressed(void)
{
  return sampleButton(BUTTON_S2, buttons[1]);
}

unsigned int ParkingShield::getTemperature(void) const
{
    unsigned int tempVoltage = analogReadPin(TEMPERATURE);
    return (tempVoltage / 1024.0) * 5.0 * 100.0 - 5.0;
}

unsigned int ParkingShield::getBrightness(void) const
{
    return analogReadPin(BRIGHTNESS);
}

unsigned int ParkingShield::getAverageBrightness(void)
{
    brightnessValues[brightnessValuesPointer] = analogReadPin(BRIGHTNESS);
    brightnessValuesPointer++;
    brightnessValuesPointer %= BRIGHTNESS_ARRAY_SIZE;
    int average = 0;
    int i;
    for( i = 0; i < BRIGHTNESS_ARRAY_SIZE; ++i)
    {
        average += brightnessValues[i];
    }

    return average / BRIGHTNESS_ARRAY_SIZE;
}

void ParkingShield::setBuzzer(bool enable) const
{
    digitalWritePin(BUZZER, enable ? Device::SIGNAL_HIGH : Device::SIGNAL_LOW);
}

void ParkingShield::beep(int frequencyInHertz, long timeInMilliseconds) const
{
    int x;
    long delayAmount = (long)(1000000/frequencyInHertz);
    long loopTime = (long)((timeInMilliseconds*1000)/(delayAmount*2));
    for (x=0;x<loopTime;x++)
    {
        setBuzzer(true);
        Device::delayMicros(delayAmount);
        setBuzzer(false);
        Device::delayMicros(delayAmount);
    }

    Device::delayMillis(20);
}

void ParkingShield::playTone(int tone, int duration) const
{
    for (long i = 0; i < duration * 1000L; i += tone * 2)
    {
        setBuzzer(true);
        Device::delayMicros(tone);
        setBuzzer(false);
        Device::delayMicros(tone);
    }
}

void ParkingShield::playNote(char note, int duration) const
{
    char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' };
    int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 956 };

    // play the tone corresponding to the note name
    for (int i = 0; i < 8; i++)
    {
        if (names[i] == note)
            playTone(tones[i], duration);
    }
}

void ParkingShield::playMarch(bool shortVersion) const
{
    int const c = 261;
    int const d = 294;
    int const e = 329;
    int const f = 349;
    int const g = 391;
    int const gS = 415;
    int const a = 440;
    int const aS = 455;
    int const b = 466;
    int const cH = 523;
    int const cSH = 554;
    int const dH = 587;
    int const dSH = 622;
    int const eH = 659;
    int const fH = 698;
    int const fSH = 740;
    int const gH = 784;
    int const gSH = 830;
    int const aH = 880;
    //frequencies for the tones we're going to use
    //used http://home.mit.bme.hu/~bako/tonecalc/tonecalc.htm to get these

    //for the sheet music see:
    //http://www.musicnotes.com/sheetmusic/mtd.asp?ppn=MN0016254
    //this is just a translation of said sheet music to frequencies / time in ms
    //used 500 ms for a quart note

    beep(a, 500);
    beep(a, 500);
    beep(a, 500);
    beep(f, 350);
    beep(cH, 150);

    beep(a, 500);
    beep(f, 350);
    beep(cH, 150);
    beep(a, 1000);
    //first bit

    beep(eH, 500);
    beep(eH, 500);
    beep(eH, 500);
    beep(fH, 350);
    beep(cH, 150);

    beep(gS, 500);
    beep(f, 350);
    beep(cH, 150);
    beep(a, 1000);

    if (shortVersion)
      return;

    //second bit...

    beep(aH, 500);
    beep(a, 350);
    beep(a, 150);
    beep(aH, 500);
    beep(gSH, 250);
    beep(gH, 250);

    beep(fSH, 125);
    beep(fH, 125);
    beep(fSH, 250);
    Device::delayMillis(250);
    beep(aS, 250);
    beep(dSH, 500);
    beep(dH, 250);
    beep(cSH, 250);
    //start of the interesting bit

    beep(cH, 125);
    beep(b, 125);
    beep(cH, 250);
    Device::delayMillis(250);
    beep(f, 125);
    beep(gS, 500);
    beep(f, 375);
    beep(a, 125);

    beep(cH, 500);
    beep(a, 375);
    beep(cH, 125);
    beep(eH, 1000);
    //more interesting stuff (this doesn't quite get it right somehow)

    beep(aH, 500);
    beep(a, 350);
    beep(a, 150);
    beep(aH, 500);
    beep(gSH, 250);
    beep(gH, 250);

    beep(fSH, 125);
    beep(fH, 125);
    beep(fSH, 250);
    Device::delayMillis(250);
    beep(aS, 250);
    beep(dSH, 500);
    beep(dH, 250);
    beep(cSH, 250);
    //repeat... repeat

    beep(cH, 125);
    beep(b, 125);
    beep(cH, 250);
    Device::delayMillis(250);
    beep(f, 250);
    beep(gS, 500);
    beep(f, 375);
    beep(cH, 125);

    beep(a, 500);
    beep(f, 375);
    beep(c, 125);
    beep(a, 1000);
}

void ParkingShield::playMelody(void) const
{
    static int length = 15; // the number of notes
    static char notes[] = "ccggaagffeeddc "; // a space represents a rest
    static int beats[] = { 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 4 };
    static int tempo = 300;

    for (int i = 0; i < length; i++)
    {
        if (notes[i] == ' ') {
            Device::delayMillis(beats[i] * tempo); // rest
        } else {
            playNote(notes[i], beats[i] * tempo);
        }

        // pause between notes
        Device::delayMillis(tempo / 2);
    }
}
<commit_msg>ParkingShield: move sampleButton to private<commit_after>#include <ParkingShield.h>
#include <DeviceArduino.h>

// ---------------------------------------------------------------------------------------------------- //
// Helper
// ---------------------------------------------------------------------------------------------------- //
typedef enum
{
    BUTTON_S1,
    BUTTON_S2,
    BRIGHTNESS,
    TEMPERATURE,
    INPUT_MAX
} input_t;

typedef enum
{
    LED_GREEN = ParkingShield::GREEN_LED,
    LED_YELLOW = ParkingShield::YELLOW_LED,
    LED_RED = ParkingShield::RED_LED,
    BUZZER,
    OUTPUT_MAX
} output_t;

Device::pin_t const output_pins[OUTPUT_MAX] = {Device::DIGITAL_PIN_4, Device::ANALOG_PIN_5, Device::ANALOG_PIN_4, Device::DIGITAL_PIN_5};
Device::pin_t const input_pins[INPUT_MAX] = {Device::ANALOG_PIN_0, Device::ANALOG_PIN_1, Device::ANALOG_PIN_2, Device::ANALOG_PIN_3};
Device::pin_t const sevensegment_pins[8] = {Device::DIGITAL_PIN_7,Device::DIGITAL_PIN_8,Device::DIGITAL_PIN_9,Device::DIGITAL_PIN_10,Device::DIGITAL_PIN_11,Device::DIGITAL_PIN_12,Device::DIGITAL_PIN_13,Device::DIGITAL_PIN_6};

bool isInputPinValid(input_t inputPin)
{
    return inputPin < INPUT_MAX;
}

bool isOutputPinValid(output_t outputPin)
{
    return outputPin < OUTPUT_MAX;
}

bool isLedValid(ParkingShield::led_t led)
{
    return led < ParkingShield::LED_MAX;
}

void setPinMode(Device::pin_t pin, Device::pinmode_t pinmode)
{
    Device::setPinMode(pin, pinmode);
}

void setupOutput()
{
    for (unsigned int output = 0; output < OUTPUT_MAX; output++)
        setPinMode(output_pins[output], Device::PINMODE_OUTPUT);
}

void setupInput()
{
    for (unsigned int input = 0; input < INPUT_MAX; input++)
        setPinMode(input_pins[input], Device::PINMODE_INPUT);
}

unsigned int analogReadPin(input_t inputPin)
{
    if (isInputPinValid(inputPin))
        return Device::analogReadPin(input_pins[inputPin]);

    return 0;
}

void analogWritePin(output_t outputPin, uint8_t value)
{
    if (isOutputPinValid(outputPin))
        Device::analogWritePin(output_pins[outputPin], value);
}

Device::signal_t digitalReadPin(input_t inputPin)
{
    if (isInputPinValid(inputPin))
        return Device::digitalReadPin(input_pins[inputPin]);

    return Device::SIGNAL_LOW;
}

void digitalWritePin(output_t outputPin, Device::signal_t signal)
{
    if (isOutputPinValid(outputPin))
        Device::digitalWritePin(output_pins[outputPin], signal);
}

void ParkingShield::setLed(led_t led, bool enable)
{
    if (isLedValid(led))
        digitalWritePin(static_cast<output_t>(led), enable ? Device::SIGNAL_LOW : Device::SIGNAL_HIGH);
}

void setAllLeds(bool enable)
{
    for (unsigned int led = 0; led < ParkingShield::LED_MAX; led++)
        ParkingShield::setLed(static_cast<ParkingShield::led_t>(led), enable);
}

bool ParkingShield::sampleButton(unsigned int buttonNumber, button_state_t &button)
{
    unsigned long time = Device::milliseconds();
    if (time - button.lockTime >= debounceInterval)
        button.locked = false;

    if (!button.locked)
    {
        bool button_pressed_before = button.pressed;
        button.pressed = Device::digitalReadPin(input_pins[buttonNumber]) == Device::SIGNAL_HIGH;
        if (button_pressed_before != button.pressed)
        {
            button.locked = true;
            button.lockTime = time;
        }
    }

    if (button.pressed && time - button.repeatTime >= repeatInterval)
    {
        button.repeatTime = time;
        return true;
    }
    return false;
}

// ---------------------------------------------------------------------------------------------------- //
// Public
// ---------------------------------------------------------------------------------------------------- //
ParkingShield::ParkingShield(void) : sevenSeg(sevensegment_pins)
{
    setupOutput();
    setupInput();

    setAllLeds(false);
}

void ParkingShield::setDebounceInterval(unsigned int interval)
{
    debounceInterval = interval;
}

void ParkingShield::setRepeatInterval(unsigned int interval)
{
    repeatInterval = interval;
}

bool ParkingShield::buttonS1Pressed(void)
{
  return sampleButton(BUTTON_S1, buttons[0]);
}

bool ParkingShield::buttonS2Pressed(void)
{
  return sampleButton(BUTTON_S2, buttons[1]);
}

unsigned int ParkingShield::getTemperature(void) const
{
    unsigned int tempVoltage = analogReadPin(TEMPERATURE);
    return (tempVoltage / 1024.0) * 5.0 * 100.0 - 5.0;
}

unsigned int ParkingShield::getBrightness(void) const
{
    return analogReadPin(BRIGHTNESS);
}

unsigned int ParkingShield::getAverageBrightness(void)
{
    brightnessValues[brightnessValuesPointer] = analogReadPin(BRIGHTNESS);
    brightnessValuesPointer++;
    brightnessValuesPointer %= BRIGHTNESS_ARRAY_SIZE;
    int average = 0;
    int i;
    for( i = 0; i < BRIGHTNESS_ARRAY_SIZE; ++i)
    {
        average += brightnessValues[i];
    }

    return average / BRIGHTNESS_ARRAY_SIZE;
}

void ParkingShield::setBuzzer(bool enable) const
{
    digitalWritePin(BUZZER, enable ? Device::SIGNAL_HIGH : Device::SIGNAL_LOW);
}

void ParkingShield::beep(int frequencyInHertz, long timeInMilliseconds) const
{
    int x;
    long delayAmount = (long)(1000000/frequencyInHertz);
    long loopTime = (long)((timeInMilliseconds*1000)/(delayAmount*2));
    for (x=0;x<loopTime;x++)
    {
        setBuzzer(true);
        Device::delayMicros(delayAmount);
        setBuzzer(false);
        Device::delayMicros(delayAmount);
    }

    Device::delayMillis(20);
}

void ParkingShield::playTone(int tone, int duration) const
{
    for (long i = 0; i < duration * 1000L; i += tone * 2)
    {
        setBuzzer(true);
        Device::delayMicros(tone);
        setBuzzer(false);
        Device::delayMicros(tone);
    }
}

void ParkingShield::playNote(char note, int duration) const
{
    char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' };
    int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 956 };

    // play the tone corresponding to the note name
    for (int i = 0; i < 8; i++)
    {
        if (names[i] == note)
            playTone(tones[i], duration);
    }
}

void ParkingShield::playMarch(bool shortVersion) const
{
    int const c = 261;
    int const d = 294;
    int const e = 329;
    int const f = 349;
    int const g = 391;
    int const gS = 415;
    int const a = 440;
    int const aS = 455;
    int const b = 466;
    int const cH = 523;
    int const cSH = 554;
    int const dH = 587;
    int const dSH = 622;
    int const eH = 659;
    int const fH = 698;
    int const fSH = 740;
    int const gH = 784;
    int const gSH = 830;
    int const aH = 880;
    //frequencies for the tones we're going to use
    //used http://home.mit.bme.hu/~bako/tonecalc/tonecalc.htm to get these

    //for the sheet music see:
    //http://www.musicnotes.com/sheetmusic/mtd.asp?ppn=MN0016254
    //this is just a translation of said sheet music to frequencies / time in ms
    //used 500 ms for a quart note

    beep(a, 500);
    beep(a, 500);
    beep(a, 500);
    beep(f, 350);
    beep(cH, 150);

    beep(a, 500);
    beep(f, 350);
    beep(cH, 150);
    beep(a, 1000);
    //first bit

    beep(eH, 500);
    beep(eH, 500);
    beep(eH, 500);
    beep(fH, 350);
    beep(cH, 150);

    beep(gS, 500);
    beep(f, 350);
    beep(cH, 150);
    beep(a, 1000);

    if (shortVersion)
      return;

    //second bit...

    beep(aH, 500);
    beep(a, 350);
    beep(a, 150);
    beep(aH, 500);
    beep(gSH, 250);
    beep(gH, 250);

    beep(fSH, 125);
    beep(fH, 125);
    beep(fSH, 250);
    Device::delayMillis(250);
    beep(aS, 250);
    beep(dSH, 500);
    beep(dH, 250);
    beep(cSH, 250);
    //start of the interesting bit

    beep(cH, 125);
    beep(b, 125);
    beep(cH, 250);
    Device::delayMillis(250);
    beep(f, 125);
    beep(gS, 500);
    beep(f, 375);
    beep(a, 125);

    beep(cH, 500);
    beep(a, 375);
    beep(cH, 125);
    beep(eH, 1000);
    //more interesting stuff (this doesn't quite get it right somehow)

    beep(aH, 500);
    beep(a, 350);
    beep(a, 150);
    beep(aH, 500);
    beep(gSH, 250);
    beep(gH, 250);

    beep(fSH, 125);
    beep(fH, 125);
    beep(fSH, 250);
    Device::delayMillis(250);
    beep(aS, 250);
    beep(dSH, 500);
    beep(dH, 250);
    beep(cSH, 250);
    //repeat... repeat

    beep(cH, 125);
    beep(b, 125);
    beep(cH, 250);
    Device::delayMillis(250);
    beep(f, 250);
    beep(gS, 500);
    beep(f, 375);
    beep(cH, 125);

    beep(a, 500);
    beep(f, 375);
    beep(c, 125);
    beep(a, 1000);
}

void ParkingShield::playMelody(void) const
{
    static int length = 15; // the number of notes
    static char notes[] = "ccggaagffeeddc "; // a space represents a rest
    static int beats[] = { 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 4 };
    static int tempo = 300;

    for (int i = 0; i < length; i++)
    {
        if (notes[i] == ' ') {
            Device::delayMillis(beats[i] * tempo); // rest
        } else {
            playNote(notes[i], beats[i] * tempo);
        }

        // pause between notes
        Device::delayMillis(tempo / 2);
    }
}
<|endoftext|>


<commit_before>#include "device.h"
#include "sysex/communicationexception.h"
#include "sysex/getcommandlist.h"
#include "sysex/getdevice.h"
#include "sysex/getethernetportinfo.h"
#include "sysex/getinfo.h"
#include "sysex/getinfolist.h"
#include "sysex/getmidiinfo.h"
#include "sysex/getmidiportinfo.h"
#include "sysex/getsaverestorelist.h"
#include "sysex/midi.h"
#include "sysex/protocolexception.h"
#include "sysex/retcommandlist.h"
#include "sysex/retinfolist.h"
#include "sysex/retsaverestorelist.h"
#include "sysex/retsetmidiinfo.h"
#include "sysex/retsetmidiportinfo.h"

#include <array>
#include <cstring>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <unistd.h>

Device::Device(unsigned int inPortNumber, unsigned int outPortNumber,
			   unsigned long serialNumber, unsigned int productId) {
	this->inPortNumber = inPortNumber;
	this->outPortNumber = outPortNumber;
	this->serialNumber = new MIDISysexValue(static_cast<long>(serialNumber), 5);
	this->productId = new MIDISysexValue(productId, 2);
	this->debug = true;
	this->informationTree = new DeviceStructure;
	try {
		connect();
	} catch (CommunicationException *e) {
		throw e;
	}
}

Device::Device(Device *device)
	: Device(
		  device->getInPortNumer(), device->getOutPortNumer(),
		  static_cast<unsigned long>(device->getSerialNumber()->getLongValue()),
		  static_cast<unsigned int>(device->getProductId()->getLongValue())) {}

Device::~Device() { disconnect(); }

BYTE_VECTOR *Device::getManufacturerHeader() {
	if (Device::manufacturerHeader == 0) {
		manufacturerHeader = new BYTE_VECTOR();
		manufacturerHeader->push_back(MANUFACTURER_SYSEX_ID[0]);
		manufacturerHeader->push_back(MANUFACTURER_SYSEX_ID[1]);
		manufacturerHeader->push_back(MANUFACTURER_SYSEX_ID[2]);
	}
	return manufacturerHeader;
}

BYTE_VECTOR *Device::getDeviceHeader() {
	if (deviceHeader == 0) {
		deviceHeader = new BYTE_VECTOR();
		deviceHeader->reserve(productId->getByteValue()->size() +
							  serialNumber->getByteValue()->size());
		deviceHeader->insert(deviceHeader->end(),
							 productId->getByteValue()->begin(),
							 productId->getByteValue()->end());
		deviceHeader->insert(deviceHeader->end(),
							 serialNumber->getByteValue()->begin(),
							 serialNumber->getByteValue()->end());
	}
	return deviceHeader;
}

BYTE_VECTOR *Device::getFullHeader() {
	if (fullHeader == 0) {
		fullHeader = new BYTE_VECTOR();
		fullHeader->reserve(Device::getManufacturerHeader()->size() +
							getDeviceHeader()->size() + 1);
		fullHeader->insert(fullHeader->end(),
						   Device::getManufacturerHeader()->begin(),
						   Device::getManufacturerHeader()->end());
		fullHeader->push_back(Device::MESSAGE_CLASS);
		fullHeader->insert(fullHeader->end(), getDeviceHeader()->begin(),
						   getDeviceHeader()->end());
	}
	return fullHeader;
}

bool Device::setupMidi() {
	std::cout << "connect" << std::endl;
	std::stringstream nameIn;
	std::stringstream nameOut;
	if (!midiin) {
		nameIn << "MioConfig In " << serialNumber->getLongValue();
		midiin = MIDI::createMidiIn(nameIn.str());
		if (!midiin)
			return false;
	}
	if (!midiin->isPortOpen())
		try {
			midiin->openPort(inPortNumber);
		} catch (...) {
			throw;
		}

	if (!midiout) {
		nameOut << "MioConfig Out " << serialNumber->getLongValue();
		midiout = MIDI::createMidiOut(nameOut.str());
		if (!midiout)
			return false;
	}
	if (!midiout->isPortOpen())
		try {
			midiout->openPort(outPortNumber);
		} catch (...) {
			throw;
		}

	return midiin->isPortOpen() && midiout->isPortOpen();
}

void Device::sentSysex(BYTE_VECTOR *data) {
	setLastSendMessage(data);
	midiout->sendMessage(data);
}

void Device::disconnect() {
	std::cout << "disconnect" << std::endl;
	if (midiin) {
		if (midiin->isPortOpen())
			midiin->closePort();
		delete midiin;
		midiin = 0;
	}
	if (midiout) {
		if (midiout->isPortOpen())
			midiout->closePort();
		delete midiout;
		midiout = 0;
	}
}

void Device::connect() {
	bool deviceOpen = false;
	for (int i = 0; i < WAIT_LOOPS && !deviceOpen; i++) {
		SLEEP(WAIT_TIME);
		try {
			deviceOpen = setupMidi();
		} catch (RtMidiError e) {
			throw new CommunicationException(e);
		}
	}
}

BYTE_VECTOR *Device::retrieveSysex() {
	BYTE_VECTOR *data = new BYTE_VECTOR();
	int i = 0;
	for (i = 0; i < WAIT_LOOPS && data->size() == 0; ++i) {
		SLEEP(WAIT_TIME);
		int y = 0;
		midiin->getMessage(data);
		// if there are other messages, skip them
		while ((data->size() > 0) && (data->at(0) != 0xf0) && (y < 100)) {
			midiin->getMessage(data);
			if (debug)
				std::cout << "Skipping " << std::dec << y << " midi messages"
						  << std::endl;
			y++;
		}
	}
	std::cout << "delay: " << i << std::endl;
	try {
		checkSysex(data);
	} catch (...) {
		throw;
	}
	setLastRetrieveMessage(data);
	return data;
}

bool Device::checkSysex(BYTE_VECTOR *data) {
	if (!data || data->size() <= 0)
		throw new CommunicationException(
			CommunicationException::ANSWER_TIMEOOUT, this);
	if (data->size() < 20)
		throw new ProtocolException(ProtocolException::MESSAGE_TO_SHORT, this);
	BYTE_VECTOR *dataHeader =
		new BYTE_VECTOR(data->begin() + 1, data->begin() + 12);
	BYTE_VECTOR *localHeader = getFullHeader();
	if (!MIDI::compareByteVector(dataHeader, localHeader)) {
		throw new ProtocolException(ProtocolException::WRONG_HEADER, this);
	}
	return true;
}

void Device::requestMidiPortInfos() {
	int midiPorts = getMidiInfo()->getMidiPorts();
	if (midiPortInfos == 0) {
		midiPortInfos =
			new std::map<int, std::vector<RetSetMidiPortInfo *> *>();
	}
	GetMidiPortInfo *info = new GetMidiPortInfo(this);
	for (int i = 1; i <= midiPorts; ++i) {
		std::vector<RetSetMidiPortInfo *> *v = 0;
		info->setPortNumer(i);
		RetSetMidiPortInfo *midiPortInfo = 0;
		try {
			midiPortInfo = dynamic_cast<RetSetMidiPortInfo *>(info->query());
		} catch (CommunicationException *ce) {
			std::cerr << ce->getErrorMessage();
			continue;
		}

		int portType = static_cast<int>(midiPortInfo->getPortType());
		portType <<= 8;
		portType += midiPortInfo->getJackNumberOfType();
		try {
			v = midiPortInfos->at(portType);
		} catch (const std::out_of_range &oor) {
			v = new std::vector<RetSetMidiPortInfo *>();
			midiPortInfos->insert(
				std::pair<int, std::vector<RetSetMidiPortInfo *> *>(portType,
																	v));
		}

		if (v == 0) {
			v = new std::vector<RetSetMidiPortInfo *>();
			midiPortInfos->insert(
				std::pair<int, std::vector<RetSetMidiPortInfo *> *>(portType,
																	v));
		}
		v->push_back(midiPortInfo);
	}
}

void Device::addCommandToStructure(
	Command cmd, DeviceStructureContainer *structureContainer) {
	informationTree->insert(std::pair<Command, DeviceStructureContainer *>(
		cmd, structureContainer));
}

bool Device::queryDeviceInfo() {

	GetCommandList *c = new GetCommandList(this);
	c->setDebug(true);
	try {
		SysExMessage *m = c->query();
		commands = dynamic_cast<RetCommandList *>(m);
		if (commands)
			addCommandToStructure(commands->getCommand(),
								  new DeviceStructureContainer(commands));
	} catch (...) {
		throw;
	}

	if (commands->isCommandSupported(Command::GET_INFO_LIST)) {
		GetInfoList *i = new GetInfoList(this);
		i->setDebug(true);
		try {
			ii = dynamic_cast<RetInfoList *>(i->query());
			DeviceStructureContainer *c = new DeviceStructureContainer();
			addCommandToStructure(ii->getCommand(), c);
		} catch (...) {
			throw;
		}
	}

	deviceInfo = new GetInfo(this, ii);

	if (ii->isInfoImplemented(GetInfo::DEVICE_NAME))
		deviceName = deviceInfo->getItemValue(GetInfo::DEVICE_NAME);

	if (ii->isInfoImplemented(GetInfo::ACCESSORY_NAME))
		modelName = deviceInfo->getItemValue(GetInfo::ACCESSORY_NAME);

	if (ii->isInfoImplemented(GetInfo::SERIAL_NUMBER))
		serialNumberString = deviceInfo->getItemValue(GetInfo::SERIAL_NUMBER);

	if (ii->isInfoImplemented(GetInfo::FIRMWARE_VERSION))
		firmwareVersion = deviceInfo->getItemValue(GetInfo::FIRMWARE_VERSION);

	if (ii->isInfoImplemented(GetInfo::HARDWARE_VERSION))
		hardwareVersion = deviceInfo->getItemValue(GetInfo::HARDWARE_VERSION);

	if (ii->isInfoImplemented(GetInfo::MANUFACTURER_NAME))
		manufacturerName = deviceInfo->getItemValue(GetInfo::MANUFACTURER_NAME);

	if (ii->isInfoImplemented(GetInfo::MODEL_NUMBER))
		modelNumber = deviceInfo->getItemValue(GetInfo::MODEL_NUMBER);

	if (commands->isCommandSupported(Command::GET_MIDI_INFO)) {
		GetMidiInfo *getMidiInfo = new GetMidiInfo(this);
		this->midiInfo = dynamic_cast<RetSetMidiInfo *>(getMidiInfo->query());
	}
	if (commands->isCommandSupported(Command::GET_MIDI_PORT_INFO) &&
		this->midiInfo != 0) {
		requestMidiPortInfos();
	}
	if (commands->isCommandSupported(Command::GET_SAVE_RESTORE_LIST)) {
		GetSaveRestoreList *getSaveRestoreList = new GetSaveRestoreList(this);
		RetSaveRestoreList *l =
			dynamic_cast<RetSaveRestoreList *>(getSaveRestoreList->query());
		saveRestoreList = l->getSaveRestoreList();
	}
	return true;
}

bool Device::isDeviceValid() {
	GetDevice *getDevice = new GetDevice(this);
	getDevice->setDebug(true);
	int ret = -3;
	for (int i = 0; i < WAIT_LOOPS; ++i) {
		ret = getDevice->execute();
		if (ret == 0) {
			std::cout << "device is up and answers" << std::endl;
			return true;
		}
		SLEEP(1000);
	}
	return false;
}

SysExMessage *Device::getSysExMessage(Command cmd) {
	switch (cmd) {
	case Command::GET_ETHERNET_PORT_INFO:
		return new GetEthernetPortInfo(this);
	case Command::GET_INFO_LIST:
		return new GetInfoList(this);
	case Command::GET_MIDI_INFO:
		return new GetMidiInfo(this);
	default:
		return NULL;
	}
}

MIDI_PORT_INFOS *Device::getMidiPortInfos() const { return midiPortInfos; }

void Device::setDeviceInformation(std::string modelName,
								  std::string deviceName) {
	this->modelName = modelName;
	this->deviceName = deviceName;
}

std::vector<unsigned char> *Device::getLastSendMessage() const {
	return lastSendMessage;
}

std::vector<unsigned char> *Device::getLastRetrieveMessage() const {
	return lastRetrieveMessage;
}

void Device::setLastSendMessage(std::vector<unsigned char> *value) {
	lastSendMessage = value;
}

void Device::setLastRetrieveMessage(std::vector<unsigned char> *value) {
	lastRetrieveMessage = value;
}

bool Device::getDebug() const { return debug; }

void Device::setDebug(bool value) { debug = value; }

bool Device::hasMidiSupport() { return (getMidiInfo() != 0); }

BYTE_VECTOR *Device::nextTransactionId() {
	if (transactionId > 16000)
		transactionId = 0;
	BYTE_VECTOR *v = MIDI::byteSplit(++transactionId, 2);
	return v;
}

bool Device::loadConfigurationFromDevice() {
	getCommands();

	return true;
}

BYTE_VECTOR *Device::manufacturerHeader = 0;
<commit_msg>add object to devicestructurecontainer<commit_after>#include "device.h"
#include "sysex/communicationexception.h"
#include "sysex/getcommandlist.h"
#include "sysex/getdevice.h"
#include "sysex/getethernetportinfo.h"
#include "sysex/getinfo.h"
#include "sysex/getinfolist.h"
#include "sysex/getmidiinfo.h"
#include "sysex/getmidiportinfo.h"
#include "sysex/getsaverestorelist.h"
#include "sysex/midi.h"
#include "sysex/protocolexception.h"
#include "sysex/retcommandlist.h"
#include "sysex/retinfolist.h"
#include "sysex/retsaverestorelist.h"
#include "sysex/retsetmidiinfo.h"
#include "sysex/retsetmidiportinfo.h"

#include <array>
#include <cstring>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <unistd.h>

Device::Device(unsigned int inPortNumber, unsigned int outPortNumber,
			   unsigned long serialNumber, unsigned int productId) {
	this->inPortNumber = inPortNumber;
	this->outPortNumber = outPortNumber;
	this->serialNumber = new MIDISysexValue(static_cast<long>(serialNumber), 5);
	this->productId = new MIDISysexValue(productId, 2);
	this->debug = true;
	this->informationTree = new DeviceStructure;
	try {
		connect();
	} catch (CommunicationException *e) {
		throw e;
	}
}

Device::Device(Device *device)
	: Device(
		  device->getInPortNumer(), device->getOutPortNumer(),
		  static_cast<unsigned long>(device->getSerialNumber()->getLongValue()),
		  static_cast<unsigned int>(device->getProductId()->getLongValue())) {}

Device::~Device() { disconnect(); }

BYTE_VECTOR *Device::getManufacturerHeader() {
	if (Device::manufacturerHeader == 0) {
		manufacturerHeader = new BYTE_VECTOR();
		manufacturerHeader->push_back(MANUFACTURER_SYSEX_ID[0]);
		manufacturerHeader->push_back(MANUFACTURER_SYSEX_ID[1]);
		manufacturerHeader->push_back(MANUFACTURER_SYSEX_ID[2]);
	}
	return manufacturerHeader;
}

BYTE_VECTOR *Device::getDeviceHeader() {
	if (deviceHeader == 0) {
		deviceHeader = new BYTE_VECTOR();
		deviceHeader->reserve(productId->getByteValue()->size() +
							  serialNumber->getByteValue()->size());
		deviceHeader->insert(deviceHeader->end(),
							 productId->getByteValue()->begin(),
							 productId->getByteValue()->end());
		deviceHeader->insert(deviceHeader->end(),
							 serialNumber->getByteValue()->begin(),
							 serialNumber->getByteValue()->end());
	}
	return deviceHeader;
}

BYTE_VECTOR *Device::getFullHeader() {
	if (fullHeader == 0) {
		fullHeader = new BYTE_VECTOR();
		fullHeader->reserve(Device::getManufacturerHeader()->size() +
							getDeviceHeader()->size() + 1);
		fullHeader->insert(fullHeader->end(),
						   Device::getManufacturerHeader()->begin(),
						   Device::getManufacturerHeader()->end());
		fullHeader->push_back(Device::MESSAGE_CLASS);
		fullHeader->insert(fullHeader->end(), getDeviceHeader()->begin(),
						   getDeviceHeader()->end());
	}
	return fullHeader;
}

bool Device::setupMidi() {
	std::cout << "connect" << std::endl;
	std::stringstream nameIn;
	std::stringstream nameOut;
	if (!midiin) {
		nameIn << "MioConfig In " << serialNumber->getLongValue();
		midiin = MIDI::createMidiIn(nameIn.str());
		if (!midiin)
			return false;
	}
	if (!midiin->isPortOpen())
		try {
			midiin->openPort(inPortNumber);
		} catch (...) {
			throw;
		}

	if (!midiout) {
		nameOut << "MioConfig Out " << serialNumber->getLongValue();
		midiout = MIDI::createMidiOut(nameOut.str());
		if (!midiout)
			return false;
	}
	if (!midiout->isPortOpen())
		try {
			midiout->openPort(outPortNumber);
		} catch (...) {
			throw;
		}

	return midiin->isPortOpen() && midiout->isPortOpen();
}

void Device::sentSysex(BYTE_VECTOR *data) {
	setLastSendMessage(data);
	midiout->sendMessage(data);
}

void Device::disconnect() {
	std::cout << "disconnect" << std::endl;
	if (midiin) {
		if (midiin->isPortOpen())
			midiin->closePort();
		delete midiin;
		midiin = 0;
	}
	if (midiout) {
		if (midiout->isPortOpen())
			midiout->closePort();
		delete midiout;
		midiout = 0;
	}
}

void Device::connect() {
	bool deviceOpen = false;
	for (int i = 0; i < WAIT_LOOPS && !deviceOpen; i++) {
		SLEEP(WAIT_TIME);
		try {
			deviceOpen = setupMidi();
		} catch (RtMidiError e) {
			throw new CommunicationException(e);
		}
	}
}

BYTE_VECTOR *Device::retrieveSysex() {
	BYTE_VECTOR *data = new BYTE_VECTOR();
	int i = 0;
	for (i = 0; i < WAIT_LOOPS && data->size() == 0; ++i) {
		SLEEP(WAIT_TIME);
		int y = 0;
		midiin->getMessage(data);
		// if there are other messages, skip them
		while ((data->size() > 0) && (data->at(0) != 0xf0) && (y < 100)) {
			midiin->getMessage(data);
			if (debug)
				std::cout << "Skipping " << std::dec << y << " midi messages"
						  << std::endl;
			y++;
		}
	}
	std::cout << "delay: " << i << std::endl;
	try {
		checkSysex(data);
	} catch (...) {
		throw;
	}
	setLastRetrieveMessage(data);
	return data;
}

bool Device::checkSysex(BYTE_VECTOR *data) {
	if (!data || data->size() <= 0)
		throw new CommunicationException(
			CommunicationException::ANSWER_TIMEOOUT, this);
	if (data->size() < 20)
		throw new ProtocolException(ProtocolException::MESSAGE_TO_SHORT, this);
	BYTE_VECTOR *dataHeader =
		new BYTE_VECTOR(data->begin() + 1, data->begin() + 12);
	BYTE_VECTOR *localHeader = getFullHeader();
	if (!MIDI::compareByteVector(dataHeader, localHeader)) {
		throw new ProtocolException(ProtocolException::WRONG_HEADER, this);
	}
	return true;
}

void Device::requestMidiPortInfos() {
	int midiPorts = getMidiInfo()->getMidiPorts();
	if (midiPortInfos == 0) {
		midiPortInfos =
			new std::map<int, std::vector<RetSetMidiPortInfo *> *>();
	}
	GetMidiPortInfo *info = new GetMidiPortInfo(this);
	for (int i = 1; i <= midiPorts; ++i) {
		std::vector<RetSetMidiPortInfo *> *v = 0;
		info->setPortNumer(i);
		RetSetMidiPortInfo *midiPortInfo = 0;
		try {
			midiPortInfo = dynamic_cast<RetSetMidiPortInfo *>(info->query());
		} catch (CommunicationException *ce) {
			std::cerr << ce->getErrorMessage();
			continue;
		}

		int portType = static_cast<int>(midiPortInfo->getPortType());
		portType <<= 8;
		portType += midiPortInfo->getJackNumberOfType();
		try {
			v = midiPortInfos->at(portType);
		} catch (const std::out_of_range &oor) {
			v = new std::vector<RetSetMidiPortInfo *>();
			midiPortInfos->insert(
				std::pair<int, std::vector<RetSetMidiPortInfo *> *>(portType,
																	v));
		}

		if (v == 0) {
			v = new std::vector<RetSetMidiPortInfo *>();
			midiPortInfos->insert(
				std::pair<int, std::vector<RetSetMidiPortInfo *> *>(portType,
																	v));
		}
		v->push_back(midiPortInfo);
	}
}

void Device::addCommandToStructure(
	Command cmd, DeviceStructureContainer *structureContainer) {
	informationTree->insert(std::pair<Command, DeviceStructureContainer *>(
		cmd, structureContainer));
}

bool Device::queryDeviceInfo() {

	GetCommandList *c = new GetCommandList(this);
	c->setDebug(true);
	try {
		SysExMessage *m = c->query();
		commands = dynamic_cast<RetCommandList *>(m);
		if (commands)
			addCommandToStructure(commands->getCommand(),
								  new DeviceStructureContainer(commands));
	} catch (...) {
		throw;
	}

	if (commands->isCommandSupported(Command::GET_INFO_LIST)) {
		GetInfoList *i = new GetInfoList(this);
		i->setDebug(true);
		try {
			ii = dynamic_cast<RetInfoList *>(i->query());
			DeviceStructureContainer *c = new DeviceStructureContainer(ii);
			addCommandToStructure(ii->getCommand(), c);
		} catch (...) {
			throw;
		}
	}

	deviceInfo = new GetInfo(this, ii);

	if (ii->isInfoImplemented(GetInfo::DEVICE_NAME))
		deviceName = deviceInfo->getItemValue(GetInfo::DEVICE_NAME);

	if (ii->isInfoImplemented(GetInfo::ACCESSORY_NAME))
		modelName = deviceInfo->getItemValue(GetInfo::ACCESSORY_NAME);

	if (ii->isInfoImplemented(GetInfo::SERIAL_NUMBER))
		serialNumberString = deviceInfo->getItemValue(GetInfo::SERIAL_NUMBER);

	if (ii->isInfoImplemented(GetInfo::FIRMWARE_VERSION))
		firmwareVersion = deviceInfo->getItemValue(GetInfo::FIRMWARE_VERSION);

	if (ii->isInfoImplemented(GetInfo::HARDWARE_VERSION))
		hardwareVersion = deviceInfo->getItemValue(GetInfo::HARDWARE_VERSION);

	if (ii->isInfoImplemented(GetInfo::MANUFACTURER_NAME))
		manufacturerName = deviceInfo->getItemValue(GetInfo::MANUFACTURER_NAME);

	if (ii->isInfoImplemented(GetInfo::MODEL_NUMBER))
		modelNumber = deviceInfo->getItemValue(GetInfo::MODEL_NUMBER);

	if (commands->isCommandSupported(Command::GET_MIDI_INFO)) {
		GetMidiInfo *getMidiInfo = new GetMidiInfo(this);
		this->midiInfo = dynamic_cast<RetSetMidiInfo *>(getMidiInfo->query());
	}
	if (commands->isCommandSupported(Command::GET_MIDI_PORT_INFO) &&
		this->midiInfo != 0) {
		requestMidiPortInfos();
	}
	if (commands->isCommandSupported(Command::GET_SAVE_RESTORE_LIST)) {
		GetSaveRestoreList *getSaveRestoreList = new GetSaveRestoreList(this);
		RetSaveRestoreList *l =
			dynamic_cast<RetSaveRestoreList *>(getSaveRestoreList->query());
		saveRestoreList = l->getSaveRestoreList();
	}
	return true;
}

bool Device::isDeviceValid() {
	GetDevice *getDevice = new GetDevice(this);
	getDevice->setDebug(true);
	int ret = -3;
	for (int i = 0; i < WAIT_LOOPS; ++i) {
		ret = getDevice->execute();
		if (ret == 0) {
			std::cout << "device is up and answers" << std::endl;
			return true;
		}
		SLEEP(1000);
	}
	return false;
}

SysExMessage *Device::getSysExMessage(Command cmd) {
	SysExMessage *m = 0;
	switch (cmd) {
	case GET_COMMAND_LIST:
		m = new GetCommandList(this);
		break;
	case Command::GET_ETHERNET_PORT_INFO:
		m = new GetEthernetPortInfo(this);
		break;
	case Command::GET_INFO_LIST:
		m = new GetInfoList(this);
		break;
	case Command::GET_MIDI_INFO:
		m = new GetMidiInfo(this);
		break;
	default:
		return NULL;
	}
	addCommandToStructure(cmd, new DeviceStructureContainer(m));
	return m;
}

MIDI_PORT_INFOS *Device::getMidiPortInfos() const { return midiPortInfos; }

void Device::setDeviceInformation(std::string modelName,
								  std::string deviceName) {
	this->modelName = modelName;
	this->deviceName = deviceName;
}

std::vector<unsigned char> *Device::getLastSendMessage() const {
	return lastSendMessage;
}

std::vector<unsigned char> *Device::getLastRetrieveMessage() const {
	return lastRetrieveMessage;
}

void Device::setLastSendMessage(std::vector<unsigned char> *value) {
	lastSendMessage = value;
}

void Device::setLastRetrieveMessage(std::vector<unsigned char> *value) {
	lastRetrieveMessage = value;
}

bool Device::getDebug() const { return debug; }

void Device::setDebug(bool value) { debug = value; }

bool Device::hasMidiSupport() { return (getMidiInfo() != 0); }

BYTE_VECTOR *Device::nextTransactionId() {
	if (transactionId > 16000)
		transactionId = 0;
	BYTE_VECTOR *v = MIDI::byteSplit(++transactionId, 2);
	return v;
}

bool Device::loadConfigurationFromDevice() {
	getCommands();

	return true;
}

BYTE_VECTOR *Device::manufacturerHeader = 0;
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * 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: NetChartTypeTemplate.cxx,v $
 * $Revision: 1.9 $
 *
 * 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_chart2.hxx"
#include "NetChartTypeTemplate.hxx"
#include "macros.hxx"
#include "PolarCoordinateSystem.hxx"
#include "Scaling.hxx"
#include "DiagramHelper.hxx"
#include "servicenames_charttypes.hxx"
#include "DataSeriesHelper.hxx"
#include <com/sun/star/chart2/SymbolStyle.hpp>
#include <com/sun/star/chart2/Symbol.hpp>
#include <com/sun/star/drawing/LineStyle.hpp>

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

using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::rtl::OUString;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Any;
using ::osl::MutexGuard;

namespace
{
static const ::rtl::OUString lcl_aServiceName(
    RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.chart2.NetChartTypeTemplate" ));
} // anonymous namespace

namespace chart
{

NetChartTypeTemplate::NetChartTypeTemplate(
    Reference< uno::XComponentContext > const & xContext,
    const ::rtl::OUString & rServiceName,
    StackMode eStackMode,
    bool bSymbols,
    bool bHasLines ) :
        ChartTypeTemplate( xContext, rServiceName ),
        m_eStackMode( eStackMode ),
        m_bHasSymbols( bSymbols ),
        m_bHasLines( bHasLines )
{}

NetChartTypeTemplate::~NetChartTypeTemplate()
{}

StackMode NetChartTypeTemplate::getStackMode( sal_Int32 /* nChartTypeIndex */ ) const
{
    return m_eStackMode;
}

void SAL_CALL NetChartTypeTemplate::applyStyle(
    const Reference< chart2::XDataSeries >& xSeries,
    ::sal_Int32 nChartTypeIndex,
    ::sal_Int32 nSeriesIndex,
    ::sal_Int32 nSeriesCount )
    throw (uno::RuntimeException)
{
    ChartTypeTemplate::applyStyle( xSeries, nChartTypeIndex, nSeriesIndex, nSeriesCount );

    try
    {
        Reference< beans::XPropertySet > xProp( xSeries, uno::UNO_QUERY_THROW );

        DataSeriesHelper::switchSymbolsOnOrOff( xProp, m_bHasSymbols, nSeriesIndex );
        DataSeriesHelper::switchLinesOnOrOff( xProp, m_bHasLines );
    }
    catch( uno::Exception & ex )
    {
        ASSERT_EXCEPTION( ex );
    }
}

// ____ XChartTypeTemplate ____
sal_Bool SAL_CALL NetChartTypeTemplate::matchesTemplate(
    const Reference< chart2::XDiagram >& xDiagram,
    sal_Bool bAdaptProperties )
    throw (uno::RuntimeException)
{
    sal_Bool bResult = ChartTypeTemplate::matchesTemplate( xDiagram, bAdaptProperties );

    // check symbol-style
    // for a template with symbols it is ok, if there is at least one series
    // with symbols, otherwise an unknown template is too easy to achieve
    bool bSymbolsFound = false;
    if( bResult )
    {
        ::std::vector< Reference< chart2::XDataSeries > > aSeriesVec(
            DiagramHelper::getDataSeriesFromDiagram( xDiagram ));

        for( ::std::vector< Reference< chart2::XDataSeries > >::const_iterator aIt =
                 aSeriesVec.begin(); aIt != aSeriesVec.end(); ++aIt )
        {
            try
            {
                chart2::Symbol aSymbProp;
                drawing::LineStyle eLineStyle;
                Reference< beans::XPropertySet > xProp( *aIt, uno::UNO_QUERY_THROW );
                if( (xProp->getPropertyValue( C2U( "Symbol" )) >>= aSymbProp) &&
                    (aSymbProp.Style != chart2::SymbolStyle_NONE ) &&
                    (! m_bHasSymbols) )
                {
                    bResult = false;
                    break;
                }
                if( m_bHasSymbols )
                    bSymbolsFound = bSymbolsFound || (aSymbProp.Style != chart2::SymbolStyle_NONE);

                if( (xProp->getPropertyValue( C2U( "LineStyle" )) >>= eLineStyle) &&
                    (m_bHasLines != ( eLineStyle != drawing::LineStyle_NONE )) )
                {
                    bResult = false;
                    break;
                }
            }
            catch( uno::Exception & ex )
            {
                ASSERT_EXCEPTION( ex );
            }
        }

        if( m_bHasSymbols )
            bResult = bResult && bSymbolsFound;
    }

    return bResult;
}

Reference< chart2::XChartType > NetChartTypeTemplate::getChartTypeForIndex( sal_Int32 /*nChartTypeIndex*/ )
{
    Reference< chart2::XChartType > xResult;

    try
    {
        Reference< lang::XMultiServiceFactory > xFact(
            GetComponentContext()->getServiceManager(), uno::UNO_QUERY_THROW );
        xResult.set( xFact->createInstance(
                         CHART2_SERVICE_NAME_CHARTTYPE_NET ), uno::UNO_QUERY_THROW );
    }
    catch( uno::Exception & ex )
    {
        ASSERT_EXCEPTION( ex );
    }

    return xResult;
}

Reference< chart2::XChartType > SAL_CALL NetChartTypeTemplate::getChartTypeForNewSeries(
        const uno::Sequence< Reference< chart2::XChartType > >& aFormerlyUsedChartTypes )
    throw (uno::RuntimeException)
{
    Reference< chart2::XChartType > xResult( getChartTypeForIndex( 0 ) );
    ChartTypeTemplate::copyPropertiesFromOldToNewCoordianteSystem( aFormerlyUsedChartTypes, xResult );
    return xResult;
}

// ----------------------------------------

Sequence< OUString > NetChartTypeTemplate::getSupportedServiceNames_Static()
{
    Sequence< OUString > aServices( 2 );
    aServices[ 0 ] = lcl_aServiceName;
    aServices[ 1 ] = C2U( "com.sun.star.chart2.ChartTypeTemplate" );
    return aServices;
}

// implement XServiceInfo methods basing upon getSupportedServiceNames_Static
APPHELPER_XSERVICEINFO_IMPL( NetChartTypeTemplate, lcl_aServiceName );

} //  namespace chart
<commit_msg>INTEGRATION: CWS chart25 (1.9.10); FILE MERGED 2008/04/25 15:00:05 iha 1.9.10.1: #i88742# make default lines a bit stronger for line charts<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: NetChartTypeTemplate.cxx,v $
 * $Revision: 1.10 $
 *
 * 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_chart2.hxx"
#include "NetChartTypeTemplate.hxx"
#include "macros.hxx"
#include "PolarCoordinateSystem.hxx"
#include "Scaling.hxx"
#include "DiagramHelper.hxx"
#include "servicenames_charttypes.hxx"
#include "DataSeriesHelper.hxx"
#include <com/sun/star/chart2/SymbolStyle.hpp>
#include <com/sun/star/chart2/Symbol.hpp>
#include <com/sun/star/drawing/LineStyle.hpp>

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

using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::rtl::OUString;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Any;
using ::osl::MutexGuard;

namespace
{
static const ::rtl::OUString lcl_aServiceName(
    RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.chart2.NetChartTypeTemplate" ));
} // anonymous namespace

namespace chart
{

NetChartTypeTemplate::NetChartTypeTemplate(
    Reference< uno::XComponentContext > const & xContext,
    const ::rtl::OUString & rServiceName,
    StackMode eStackMode,
    bool bSymbols,
    bool bHasLines ) :
        ChartTypeTemplate( xContext, rServiceName ),
        m_eStackMode( eStackMode ),
        m_bHasSymbols( bSymbols ),
        m_bHasLines( bHasLines )
{}

NetChartTypeTemplate::~NetChartTypeTemplate()
{}

StackMode NetChartTypeTemplate::getStackMode( sal_Int32 /* nChartTypeIndex */ ) const
{
    return m_eStackMode;
}

void SAL_CALL NetChartTypeTemplate::applyStyle(
    const Reference< chart2::XDataSeries >& xSeries,
    ::sal_Int32 nChartTypeIndex,
    ::sal_Int32 nSeriesIndex,
    ::sal_Int32 nSeriesCount )
    throw (uno::RuntimeException)
{
    ChartTypeTemplate::applyStyle( xSeries, nChartTypeIndex, nSeriesIndex, nSeriesCount );

    try
    {
        Reference< beans::XPropertySet > xProp( xSeries, uno::UNO_QUERY_THROW );

        DataSeriesHelper::switchSymbolsOnOrOff( xProp, m_bHasSymbols, nSeriesIndex );
        DataSeriesHelper::switchLinesOnOrOff( xProp, m_bHasLines );
        DataSeriesHelper::makeLinesThickOrThin( xProp, true );
    }
    catch( uno::Exception & ex )
    {
        ASSERT_EXCEPTION( ex );
    }
}

// ____ XChartTypeTemplate ____
sal_Bool SAL_CALL NetChartTypeTemplate::matchesTemplate(
    const Reference< chart2::XDiagram >& xDiagram,
    sal_Bool bAdaptProperties )
    throw (uno::RuntimeException)
{
    sal_Bool bResult = ChartTypeTemplate::matchesTemplate( xDiagram, bAdaptProperties );

    // check symbol-style
    // for a template with symbols it is ok, if there is at least one series
    // with symbols, otherwise an unknown template is too easy to achieve
    bool bSymbolsFound = false;
    if( bResult )
    {
        ::std::vector< Reference< chart2::XDataSeries > > aSeriesVec(
            DiagramHelper::getDataSeriesFromDiagram( xDiagram ));

        for( ::std::vector< Reference< chart2::XDataSeries > >::const_iterator aIt =
                 aSeriesVec.begin(); aIt != aSeriesVec.end(); ++aIt )
        {
            try
            {
                chart2::Symbol aSymbProp;
                drawing::LineStyle eLineStyle;
                Reference< beans::XPropertySet > xProp( *aIt, uno::UNO_QUERY_THROW );
                if( (xProp->getPropertyValue( C2U( "Symbol" )) >>= aSymbProp) &&
                    (aSymbProp.Style != chart2::SymbolStyle_NONE ) &&
                    (! m_bHasSymbols) )
                {
                    bResult = false;
                    break;
                }
                if( m_bHasSymbols )
                    bSymbolsFound = bSymbolsFound || (aSymbProp.Style != chart2::SymbolStyle_NONE);

                if( (xProp->getPropertyValue( C2U( "LineStyle" )) >>= eLineStyle) &&
                    (m_bHasLines != ( eLineStyle != drawing::LineStyle_NONE )) )
                {
                    bResult = false;
                    break;
                }
            }
            catch( uno::Exception & ex )
            {
                ASSERT_EXCEPTION( ex );
            }
        }

        if( m_bHasSymbols )
            bResult = bResult && bSymbolsFound;
    }

    return bResult;
}

Reference< chart2::XChartType > NetChartTypeTemplate::getChartTypeForIndex( sal_Int32 /*nChartTypeIndex*/ )
{
    Reference< chart2::XChartType > xResult;

    try
    {
        Reference< lang::XMultiServiceFactory > xFact(
            GetComponentContext()->getServiceManager(), uno::UNO_QUERY_THROW );
        xResult.set( xFact->createInstance(
                         CHART2_SERVICE_NAME_CHARTTYPE_NET ), uno::UNO_QUERY_THROW );
    }
    catch( uno::Exception & ex )
    {
        ASSERT_EXCEPTION( ex );
    }

    return xResult;
}

Reference< chart2::XChartType > SAL_CALL NetChartTypeTemplate::getChartTypeForNewSeries(
        const uno::Sequence< Reference< chart2::XChartType > >& aFormerlyUsedChartTypes )
    throw (uno::RuntimeException)
{
    Reference< chart2::XChartType > xResult( getChartTypeForIndex( 0 ) );
    ChartTypeTemplate::copyPropertiesFromOldToNewCoordianteSystem( aFormerlyUsedChartTypes, xResult );
    return xResult;
}

// ----------------------------------------

Sequence< OUString > NetChartTypeTemplate::getSupportedServiceNames_Static()
{
    Sequence< OUString > aServices( 2 );
    aServices[ 0 ] = lcl_aServiceName;
    aServices[ 1 ] = C2U( "com.sun.star.chart2.ChartTypeTemplate" );
    return aServices;
}

// implement XServiceInfo methods basing upon getSupportedServiceNames_Static
APPHELPER_XSERVICEINFO_IMPL( NetChartTypeTemplate, lcl_aServiceName );

} //  namespace chart
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: NetChartTypeTemplate.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2007-07-25 08:54:19 $
 *
 *  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_chart2.hxx"
#include "NetChartTypeTemplate.hxx"
#include "macros.hxx"
#include "PolarCoordinateSystem.hxx"
#include "Scaling.hxx"
#include "DiagramHelper.hxx"
#include "servicenames_charttypes.hxx"
#include "DataSeriesHelper.hxx"

#ifndef _COM_SUN_STAR_CHART2_SYMBOLSTYLE_HPP_
#include <com/sun/star/chart2/SymbolStyle.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_SYMBOL_HPP_
#include <com/sun/star/chart2/Symbol.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_LINESTYLE_HPP_
#include <com/sun/star/drawing/LineStyle.hpp>
#endif

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

using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::rtl::OUString;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Any;
using ::osl::MutexGuard;

namespace
{
static const ::rtl::OUString lcl_aServiceName(
    RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.chart2.NetChartTypeTemplate" ));
} // anonymous namespace

namespace chart
{

NetChartTypeTemplate::NetChartTypeTemplate(
    Reference< uno::XComponentContext > const & xContext,
    const ::rtl::OUString & rServiceName,
    StackMode eStackMode,
    bool bSymbols,
    bool bHasLines ) :
        ChartTypeTemplate( xContext, rServiceName ),
        m_eStackMode( eStackMode ),
        m_bHasSymbols( bSymbols ),
        m_bHasLines( bHasLines )
{}

NetChartTypeTemplate::~NetChartTypeTemplate()
{}

StackMode NetChartTypeTemplate::getStackMode( sal_Int32 /* nChartTypeIndex */ ) const
{
    return m_eStackMode;
}

void SAL_CALL NetChartTypeTemplate::applyStyle(
    const Reference< chart2::XDataSeries >& xSeries,
    ::sal_Int32 nChartTypeIndex,
    ::sal_Int32 nSeriesIndex,
    ::sal_Int32 nSeriesCount )
    throw (uno::RuntimeException)
{
    ChartTypeTemplate::applyStyle( xSeries, nChartTypeIndex, nSeriesIndex, nSeriesCount );

    try
    {
        Reference< beans::XPropertySet > xProp( xSeries, uno::UNO_QUERY_THROW );

        DataSeriesHelper::switchSymbolsOnOrOff( xProp, m_bHasSymbols, nSeriesIndex );
        DataSeriesHelper::switchLinesOnOrOff( xProp, m_bHasLines );
    }
    catch( uno::Exception & ex )
    {
        ASSERT_EXCEPTION( ex );
    }
}

// ____ XChartTypeTemplate ____
sal_Bool SAL_CALL NetChartTypeTemplate::matchesTemplate(
    const Reference< chart2::XDiagram >& xDiagram,
    sal_Bool bAdaptProperties )
    throw (uno::RuntimeException)
{
    sal_Bool bResult = ChartTypeTemplate::matchesTemplate( xDiagram, bAdaptProperties );

    // check symbol-style
    // for a template with symbols it is ok, if there is at least one series
    // with symbols, otherwise an unknown template is too easy to achieve
    bool bSymbolsFound = false;
    if( bResult )
    {
        ::std::vector< Reference< chart2::XDataSeries > > aSeriesVec(
            DiagramHelper::getDataSeriesFromDiagram( xDiagram ));

        for( ::std::vector< Reference< chart2::XDataSeries > >::const_iterator aIt =
                 aSeriesVec.begin(); aIt != aSeriesVec.end(); ++aIt )
        {
            try
            {
                chart2::Symbol aSymbProp;
                drawing::LineStyle eLineStyle;
                Reference< beans::XPropertySet > xProp( *aIt, uno::UNO_QUERY_THROW );
                if( (xProp->getPropertyValue( C2U( "Symbol" )) >>= aSymbProp) &&
                    (aSymbProp.Style != chart2::SymbolStyle_NONE ) &&
                    (! m_bHasSymbols) )
                {
                    bResult = false;
                    break;
                }
                if( m_bHasSymbols )
                    bSymbolsFound = bSymbolsFound || (aSymbProp.Style != chart2::SymbolStyle_NONE);

                if( (xProp->getPropertyValue( C2U( "LineStyle" )) >>= eLineStyle) &&
                    (m_bHasLines != ( eLineStyle != drawing::LineStyle_NONE )) )
                {
                    bResult = false;
                    break;
                }
            }
            catch( uno::Exception & ex )
            {
                ASSERT_EXCEPTION( ex );
            }
        }

        if( m_bHasSymbols )
            bResult = bResult && bSymbolsFound;
    }

    return bResult;
}

Reference< chart2::XChartType > SAL_CALL NetChartTypeTemplate::getChartTypeForNewSeries(
        const uno::Sequence< Reference< chart2::XChartType > >& aFormerlyUsedChartTypes )
    throw (uno::RuntimeException)
{
    Reference< chart2::XChartType > xResult;

    try
    {
        Reference< lang::XMultiServiceFactory > xFact(
            GetComponentContext()->getServiceManager(), uno::UNO_QUERY_THROW );
        xResult.set( xFact->createInstance(
                         CHART2_SERVICE_NAME_CHARTTYPE_NET ), uno::UNO_QUERY_THROW );
        ChartTypeTemplate::copyPropertiesFromOldToNewCoordianteSystem( aFormerlyUsedChartTypes, xResult );
    }
    catch( uno::Exception & ex )
    {
        ASSERT_EXCEPTION( ex );
    }

    return xResult;

}

// ----------------------------------------

Sequence< OUString > NetChartTypeTemplate::getSupportedServiceNames_Static()
{
    Sequence< OUString > aServices( 2 );
    aServices[ 0 ] = lcl_aServiceName;
    aServices[ 1 ] = C2U( "com.sun.star.chart2.ChartTypeTemplate" );
    return aServices;
}

// implement XServiceInfo methods basing upon getSupportedServiceNames_Static
APPHELPER_XSERVICEINFO_IMPL( NetChartTypeTemplate, lcl_aServiceName );

} //  namespace chart
<commit_msg>INTEGRATION: CWS chart17 (1.7.32); FILE MERGED 2007/11/05 14:11:45 iha 1.7.32.1: #i63857#, #i4039# more flexible placement of data point labels, best fit for pie labels<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: NetChartTypeTemplate.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: ihi $ $Date: 2007-11-23 12:02:19 $
 *
 *  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_chart2.hxx"
#include "NetChartTypeTemplate.hxx"
#include "macros.hxx"
#include "PolarCoordinateSystem.hxx"
#include "Scaling.hxx"
#include "DiagramHelper.hxx"
#include "servicenames_charttypes.hxx"
#include "DataSeriesHelper.hxx"

#ifndef _COM_SUN_STAR_CHART2_SYMBOLSTYLE_HPP_
#include <com/sun/star/chart2/SymbolStyle.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_SYMBOL_HPP_
#include <com/sun/star/chart2/Symbol.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_LINESTYLE_HPP_
#include <com/sun/star/drawing/LineStyle.hpp>
#endif

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

using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::rtl::OUString;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Any;
using ::osl::MutexGuard;

namespace
{
static const ::rtl::OUString lcl_aServiceName(
    RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.chart2.NetChartTypeTemplate" ));
} // anonymous namespace

namespace chart
{

NetChartTypeTemplate::NetChartTypeTemplate(
    Reference< uno::XComponentContext > const & xContext,
    const ::rtl::OUString & rServiceName,
    StackMode eStackMode,
    bool bSymbols,
    bool bHasLines ) :
        ChartTypeTemplate( xContext, rServiceName ),
        m_eStackMode( eStackMode ),
        m_bHasSymbols( bSymbols ),
        m_bHasLines( bHasLines )
{}

NetChartTypeTemplate::~NetChartTypeTemplate()
{}

StackMode NetChartTypeTemplate::getStackMode( sal_Int32 /* nChartTypeIndex */ ) const
{
    return m_eStackMode;
}

void SAL_CALL NetChartTypeTemplate::applyStyle(
    const Reference< chart2::XDataSeries >& xSeries,
    ::sal_Int32 nChartTypeIndex,
    ::sal_Int32 nSeriesIndex,
    ::sal_Int32 nSeriesCount )
    throw (uno::RuntimeException)
{
    ChartTypeTemplate::applyStyle( xSeries, nChartTypeIndex, nSeriesIndex, nSeriesCount );

    try
    {
        Reference< beans::XPropertySet > xProp( xSeries, uno::UNO_QUERY_THROW );

        DataSeriesHelper::switchSymbolsOnOrOff( xProp, m_bHasSymbols, nSeriesIndex );
        DataSeriesHelper::switchLinesOnOrOff( xProp, m_bHasLines );
    }
    catch( uno::Exception & ex )
    {
        ASSERT_EXCEPTION( ex );
    }
}

// ____ XChartTypeTemplate ____
sal_Bool SAL_CALL NetChartTypeTemplate::matchesTemplate(
    const Reference< chart2::XDiagram >& xDiagram,
    sal_Bool bAdaptProperties )
    throw (uno::RuntimeException)
{
    sal_Bool bResult = ChartTypeTemplate::matchesTemplate( xDiagram, bAdaptProperties );

    // check symbol-style
    // for a template with symbols it is ok, if there is at least one series
    // with symbols, otherwise an unknown template is too easy to achieve
    bool bSymbolsFound = false;
    if( bResult )
    {
        ::std::vector< Reference< chart2::XDataSeries > > aSeriesVec(
            DiagramHelper::getDataSeriesFromDiagram( xDiagram ));

        for( ::std::vector< Reference< chart2::XDataSeries > >::const_iterator aIt =
                 aSeriesVec.begin(); aIt != aSeriesVec.end(); ++aIt )
        {
            try
            {
                chart2::Symbol aSymbProp;
                drawing::LineStyle eLineStyle;
                Reference< beans::XPropertySet > xProp( *aIt, uno::UNO_QUERY_THROW );
                if( (xProp->getPropertyValue( C2U( "Symbol" )) >>= aSymbProp) &&
                    (aSymbProp.Style != chart2::SymbolStyle_NONE ) &&
                    (! m_bHasSymbols) )
                {
                    bResult = false;
                    break;
                }
                if( m_bHasSymbols )
                    bSymbolsFound = bSymbolsFound || (aSymbProp.Style != chart2::SymbolStyle_NONE);

                if( (xProp->getPropertyValue( C2U( "LineStyle" )) >>= eLineStyle) &&
                    (m_bHasLines != ( eLineStyle != drawing::LineStyle_NONE )) )
                {
                    bResult = false;
                    break;
                }
            }
            catch( uno::Exception & ex )
            {
                ASSERT_EXCEPTION( ex );
            }
        }

        if( m_bHasSymbols )
            bResult = bResult && bSymbolsFound;
    }

    return bResult;
}

Reference< chart2::XChartType > NetChartTypeTemplate::getChartTypeForIndex( sal_Int32 /*nChartTypeIndex*/ )
{
    Reference< chart2::XChartType > xResult;

    try
    {
        Reference< lang::XMultiServiceFactory > xFact(
            GetComponentContext()->getServiceManager(), uno::UNO_QUERY_THROW );
        xResult.set( xFact->createInstance(
                         CHART2_SERVICE_NAME_CHARTTYPE_NET ), uno::UNO_QUERY_THROW );
    }
    catch( uno::Exception & ex )
    {
        ASSERT_EXCEPTION( ex );
    }

    return xResult;
}

Reference< chart2::XChartType > SAL_CALL NetChartTypeTemplate::getChartTypeForNewSeries(
        const uno::Sequence< Reference< chart2::XChartType > >& aFormerlyUsedChartTypes )
    throw (uno::RuntimeException)
{
    Reference< chart2::XChartType > xResult( getChartTypeForIndex( 0 ) );
    ChartTypeTemplate::copyPropertiesFromOldToNewCoordianteSystem( aFormerlyUsedChartTypes, xResult );
    return xResult;
}

// ----------------------------------------

Sequence< OUString > NetChartTypeTemplate::getSupportedServiceNames_Static()
{
    Sequence< OUString > aServices( 2 );
    aServices[ 0 ] = lcl_aServiceName;
    aServices[ 1 ] = C2U( "com.sun.star.chart2.ChartTypeTemplate" );
    return aServices;
}

// implement XServiceInfo methods basing upon getSupportedServiceNames_Static
APPHELPER_XSERVICEINFO_IMPL( NetChartTypeTemplate, lcl_aServiceName );

} //  namespace chart
<|endoftext|>


<commit_before>#include "dialogs.h"
#include "singletons.h"
#include <gtkmm.h>
#include <vector>

std::string open_dialog(const std::string &title,
                        const std::vector<std::pair<std::string, Gtk::ResponseType>> buttons,
                        Gtk::FileChooserAction gtk_options) {
  Gtk::FileChooserDialog dialog(title, gtk_options);
  if(Singleton::directories()->current_path!="")
    gtk_file_chooser_set_current_folder((GtkFileChooser*)dialog.gobj(), Singleton::directories()->current_path.string().c_str());
  else
    gtk_file_chooser_set_current_folder((GtkFileChooser*)dialog.gobj(), boost::filesystem::current_path().string().c_str());
  dialog.set_position(Gtk::WindowPosition::WIN_POS_CENTER_ALWAYS);
  // dialog.set_transient_for(parent); TODO add parent
  for (auto &button : buttons)
    dialog.add_button(button.first, button.second);
  return dialog.run() == Gtk::RESPONSE_OK ? dialog.get_filename() : "";
}

std::string Dialog::select_folder() {
  return open_dialog("Please choose a folder",
            {std::make_pair("Cancel", Gtk::RESPONSE_CANCEL),std::make_pair("Open", Gtk::RESPONSE_OK)},
            Gtk::FILE_CHOOSER_ACTION_SELECT_FOLDER);
}

std::string Dialog::new_file() {
  return open_dialog("Please create a new file",
            {std::make_pair("Cancel", Gtk::RESPONSE_CANCEL), std::make_pair("Save", Gtk::RESPONSE_OK)},
            Gtk::FILE_CHOOSER_ACTION_SAVE);
}

std::string Dialog::new_folder() {
  return open_dialog("Please create a new folder",
            {std::make_pair("Cancel", Gtk::RESPONSE_CANCEL),std::make_pair("Create", Gtk::RESPONSE_OK)},
            Gtk::FILE_CHOOSER_ACTION_CREATE_FOLDER);
}

std::string Dialog::select_file() {
  return open_dialog("Please choose a folder",
            {std::make_pair("Cancel", Gtk::RESPONSE_CANCEL),std::make_pair("Select", Gtk::RESPONSE_OK)},
            Gtk::FILE_CHOOSER_ACTION_OPEN);
}

std::string Dialog::save_file() {
  return open_dialog("Please choose a file",
            {std::make_pair("Cancel", Gtk::RESPONSE_CANCEL),std::make_pair("Save", Gtk::RESPONSE_OK)},
            Gtk::FILE_CHOOSER_ACTION_OPEN);
}<commit_msg>Use reference instead of copy<commit_after>#include "dialogs.h"
#include "singletons.h"
#include <gtkmm.h>
#include <vector>

std::string open_dialog(const std::string &title,
                        const std::vector<std::pair<std::string, Gtk::ResponseType>> &buttons,
                        Gtk::FileChooserAction gtk_options) {
  Gtk::FileChooserDialog dialog(title, gtk_options);
  if(Singleton::directories()->current_path!="")
    gtk_file_chooser_set_current_folder((GtkFileChooser*)dialog.gobj(), Singleton::directories()->current_path.string().c_str());
  else
    gtk_file_chooser_set_current_folder((GtkFileChooser*)dialog.gobj(), boost::filesystem::current_path().string().c_str());
  dialog.set_position(Gtk::WindowPosition::WIN_POS_CENTER_ALWAYS);
  // dialog.set_transient_for(parent); TODO add parent
  for (auto &button : buttons)
    dialog.add_button(button.first, button.second);
  return dialog.run() == Gtk::RESPONSE_OK ? dialog.get_filename() : "";
}

std::string Dialog::select_folder() {
  return open_dialog("Please choose a folder",
            {std::make_pair("Cancel", Gtk::RESPONSE_CANCEL),std::make_pair("Open", Gtk::RESPONSE_OK)},
            Gtk::FILE_CHOOSER_ACTION_SELECT_FOLDER);
}

std::string Dialog::new_file() {
  return open_dialog("Please create a new file",
            {std::make_pair("Cancel", Gtk::RESPONSE_CANCEL), std::make_pair("Save", Gtk::RESPONSE_OK)},
            Gtk::FILE_CHOOSER_ACTION_SAVE);
}

std::string Dialog::new_folder() {
  return open_dialog("Please create a new folder",
            {std::make_pair("Cancel", Gtk::RESPONSE_CANCEL),std::make_pair("Create", Gtk::RESPONSE_OK)},
            Gtk::FILE_CHOOSER_ACTION_CREATE_FOLDER);
}

std::string Dialog::select_file() {
  return open_dialog("Please choose a folder",
            {std::make_pair("Cancel", Gtk::RESPONSE_CANCEL),std::make_pair("Select", Gtk::RESPONSE_OK)},
            Gtk::FILE_CHOOSER_ACTION_OPEN);
}

std::string Dialog::save_file() {
  return open_dialog("Please choose a file",
            {std::make_pair("Cancel", Gtk::RESPONSE_CANCEL),std::make_pair("Save", Gtk::RESPONSE_OK)},
            Gtk::FILE_CHOOSER_ACTION_OPEN);
}

<|endoftext|>


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

#define _GNU_SOURCE 1
#include "va.h"
#include "va_backend.h"
#include "va_android.h"
#include "va_dricommon.h" /* needs some helper functions from this file */
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dlfcn.h>
#include <errno.h>
#ifndef ANDROID
#include <libudev.h>
#include "drmtest.h"
#endif

#define CHECK_SYMBOL(func) { if (!func) printf("func %s not found\n", #func); return VA_STATUS_ERROR_UNKNOWN; }
#define DEVICE_NAME "/dev/card0"

static VADisplayContextP pDisplayContexts = NULL;

static int open_device (char *dev_name)
{
    struct stat st;
    int fd;

    if (-1 == stat (dev_name, &st))
    {
        printf ("Cannot identify '%s': %d, %s\n",
                dev_name, errno, strerror (errno));
        return -1;
    }

    if (!S_ISCHR (st.st_mode))
    {
        printf ("%s is no device\n", dev_name);
        return -1;
    }

    fd = open (dev_name, O_RDWR);

    if (-1 == fd)
    {
        fprintf (stderr, "Cannot open '%s': %d, %s\n",
                 dev_name, errno, strerror (errno));
        return -1;
    }

    return fd;
}

static int va_DisplayContextIsValid (
    VADisplayContextP pDisplayContext
                                  )
{
    VADisplayContextP ctx = pDisplayContexts;

    while (ctx)
    {
	if (ctx == pDisplayContext && pDisplayContext->pDriverContext)
	    return 1;
	ctx = ctx->pNext;
    }
    return 0;
}

static void va_DisplayContextDestroy (
    VADisplayContextP pDisplayContext
)
{
    VADisplayContextP *ctx = &pDisplayContexts;

    /* Throw away pDisplayContext */
    while (*ctx)
    {
	if (*ctx == pDisplayContext)
	{
	    *ctx = pDisplayContext->pNext;
	    pDisplayContext->pNext = NULL;
	    break;
	}
	ctx = &((*ctx)->pNext);
    }
    free(pDisplayContext->pDriverContext->dri_state);
    free(pDisplayContext->pDriverContext);
    free(pDisplayContext);
}

#ifdef ANDROID
static VAStatus va_DisplayContextGetDriverName (
    VADisplayContextP pDisplayContext,
    char **driver_name
)
{
    VADriverContextP ctx = pDisplayContext->pDriverContext;
    struct dri_state *dri_state = (struct dri_state *)ctx->dri_state;
    char *driver_name_env;
    int vendor_id, device_id;

    struct {
        int vendor_id;
        int device_id;
        char driver_name[64];
    } devices[] = {
        { 0x8086, 0x4100, "pvr" },
        { 0x8086, 0x0130, "pvr" },
        { 0x0,    0x0,    "\0" },
    };

    memset(dri_state, 0, sizeof(*dri_state));
    dri_state->fd = open_device(DEVICE_NAME);

    if (dri_state->fd < 0) {
        fprintf(stderr,"can't open DRM devices\n");
        return VA_STATUS_ERROR_UNKNOWN;
    }

    /* TBD: other vendor driver names */
    vendor_id = devices[0].vendor_id;
    device_id = devices[0].device_id;
    *driver_name = strdup(devices[0].driver_name);

    dri_state->driConnectedFlag = VA_DUMMY;

    return VA_STATUS_SUCCESS;
}
#else
static VAStatus va_DisplayContextGetDriverName (
    VADisplayContextP pDisplayContext,
    char **driver_name
)
{
    VADriverContextP ctx = pDisplayContext->pDriverContext;
    struct dri_state *dri_state = (struct dri_state *)ctx->dri_state;
    char *driver_name_env;
    int vendor_id, device_id;
    int i = 0;

    struct {
        int vendor_id;
        int device_id;
        char driver_name[64];
    } devices[] = {
        { 0x8086, 0x4100, "pvr" },
        { 0x8086, 0x0130, "pvr" },
        { 0x0,    0x0,    "\0" },
    };

    memset(dri_state, 0, sizeof(*dri_state));
    dri_state->fd = drm_open_any(&vendor_id, &device_id);

    if (dri_state->fd < 0) {
        fprintf(stderr,"can't open DRM devices\n");
        return VA_STATUS_ERROR_UNKNOWN;
    }

    /* TBD: other vendor driver names */

    while (devices[i].device_id != 0) {
        if ((devices[i].vendor_id == vendor_id) &&
            (devices[i].device_id == device_id))
            break;
        i++;
    }

    if (devices[i].device_id != 0)
        *driver_name = strdup(devices[i].driver_name);
    else {
        fprintf(stderr,"device (0x%04x:0x%04x) is not supported\n",
                vendor_id, device_id);

        return VA_STATUS_ERROR_UNKNOWN;
    }

    printf("DRM device is opened, loading driver %s for device 0x%04x:0x%04x\n",
           driver_name, vendor_id, device_id);

    dri_state->driConnectedFlag = VA_DUMMY;

    return VA_STATUS_SUCCESS;
}
#endif

VADisplay vaGetDisplay (
    void *native_dpy /* implementation specific */
)
{
    VADisplay dpy = NULL;
    VADisplayContextP pDisplayContext = pDisplayContexts;

    if (!native_dpy)
        return NULL;

    while (pDisplayContext)
    {
        if (pDisplayContext->pDriverContext &&
            pDisplayContext->pDriverContext->native_dpy == (void *)native_dpy)
        {
            dpy = (VADisplay)pDisplayContext;
            break;
        }
        pDisplayContext = pDisplayContext->pNext;
    }

    if (!dpy)
    {
        /* create new entry */
        VADriverContextP pDriverContext;
        struct dri_state *dri_state;
        pDisplayContext = (VADisplayContextP)calloc(1, sizeof(*pDisplayContext));
        pDriverContext  = (VADriverContextP)calloc(1, sizeof(*pDriverContext));
        dri_state       = (struct dri_state*)calloc(1, sizeof(*dri_state));
        if (pDisplayContext && pDriverContext && dri_state)
        {
            pDisplayContext->vadpy_magic = VA_DISPLAY_MAGIC;

            pDriverContext->native_dpy       = (void *)native_dpy;
            pDisplayContext->pNext           = pDisplayContexts;
            pDisplayContext->pDriverContext  = pDriverContext;
            pDisplayContext->vaIsValid       = va_DisplayContextIsValid;
            pDisplayContext->vaDestroy       = va_DisplayContextDestroy;
            pDisplayContext->vaGetDriverName = va_DisplayContextGetDriverName;
            pDisplayContexts                 = pDisplayContext;
            pDriverContext->dri_state 	     = dri_state;
            dpy                              = (VADisplay)pDisplayContext;
        }
        else
        {
            if (pDisplayContext)
                free(pDisplayContext);
            if (pDriverContext)
                free(pDriverContext);
            if (dri_state)
                free(dri_state);
        }
    }

    return dpy;
}

#define CTX(dpy) (((VADisplayContextP)dpy)->pDriverContext)
#define CHECK_DISPLAY(dpy) if( !vaDisplayIsValid(dpy) ) { return VA_STATUS_ERROR_INVALID_DISPLAY; }

#ifdef ANDROID
extern "C"  {
    extern int fool_postp; /* do nothing for vaPutSurface if set */
    extern int trace_flag; /* trace vaPutSurface parameters */

    void va_TracePutSurface (
        VADisplay dpy,
        VASurfaceID surface,
        void *draw, /* the target Drawable */
        short srcx,
        short srcy,
        unsigned short srcw,
        unsigned short srch,
        short destx,
        short desty,
        unsigned short destw,
        unsigned short desth,
        VARectangle *cliprects, /* client supplied clip list */
        unsigned int number_cliprects, /* number of clip rects in the clip list */
        unsigned int flags /* de-interlacing flags */
        );
}

#define VA_TRACE(trace_func,...)                \
    if (trace_flag) {                           \
        trace_func(__VA_ARGS__);                \
    }

VAStatus vaPutSurface (
    VADisplay dpy,
    VASurfaceID surface,
    sp<ISurface> draw, /* Android Surface/Window */
    short srcx,
    short srcy,
    unsigned short srcw,
    unsigned short srch,
    short destx,
    short desty,
    unsigned short destw,
    unsigned short desth,
    VARectangle *cliprects, /* client supplied clip list */
    unsigned int number_cliprects, /* number of clip rects in the clip list */
    unsigned int flags /* de-interlacing flags */
)
{
    VADriverContextP ctx;

    if (fool_postp)
        return VA_STATUS_SUCCESS;

    if (draw == NULL)
        return VA_STATUS_ERROR_UNKNOWN;

    CHECK_DISPLAY(dpy);
    ctx = CTX(dpy);

    VA_TRACE(va_TracePutSurface, dpy, surface, static_cast<void*>(&draw), srcx, srcy, srcw, srch,
             destx, desty, destw, desth,
             cliprects, number_cliprects, flags );

    return ctx->vtable->vaPutSurface( ctx, surface, static_cast<void*>(&draw), srcx, srcy, srcw, srch,
                                     destx, desty, destw, desth,
                                     cliprects, number_cliprects, flags );
}
#endif
<commit_msg>va-android: same as X11, also always create a new VA display on android<commit_after>/*
 * Copyright (c) 2007 Intel Corporation. All Rights Reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sub license, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice (including the
 * next paragraph) shall be included in all copies or substantial portions
 * of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
 * IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR
 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#define _GNU_SOURCE 1
#include "va.h"
#include "va_backend.h"
#include "va_android.h"
#include "va_dricommon.h" /* needs some helper functions from this file */
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dlfcn.h>
#include <errno.h>
#ifndef ANDROID
#include <libudev.h>
#include "drmtest.h"
#endif

#define CHECK_SYMBOL(func) { if (!func) printf("func %s not found\n", #func); return VA_STATUS_ERROR_UNKNOWN; }
#define DEVICE_NAME "/dev/card0"

static int open_device (char *dev_name)
{
    struct stat st;
    int fd;

    if (-1 == stat (dev_name, &st))
    {
        printf ("Cannot identify '%s': %d, %s\n",
                dev_name, errno, strerror (errno));
        return -1;
    }

    if (!S_ISCHR (st.st_mode))
    {
        printf ("%s is no device\n", dev_name);
        return -1;
    }

    fd = open (dev_name, O_RDWR);

    if (-1 == fd)
    {
        fprintf (stderr, "Cannot open '%s': %d, %s\n",
                 dev_name, errno, strerror (errno));
        return -1;
    }

    return fd;
}

static int va_DisplayContextIsValid (
    VADisplayContextP pDisplayContext
                                  )
{
    return (pDisplayContext != NULL &&
            pDisplayContext->pDriverContext != NULL);
}

static void va_DisplayContextDestroy (
    VADisplayContextP pDisplayContext
)
{
    struct dri_state *dri_state;

    if (pDisplayContext == NULL)
        return;

    /* close the open-ed DRM fd */
    dri_state = (struct dri_state *)pDisplayContext->pDriverContext->dri_state;
    close(dri_state->fd);

    free(pDisplayContext->pDriverContext->dri_state);
    free(pDisplayContext->pDriverContext);
    free(pDisplayContext);
}

#ifdef ANDROID
static VAStatus va_DisplayContextGetDriverName (
    VADisplayContextP pDisplayContext,
    char **driver_name
)
{
    VADriverContextP ctx = pDisplayContext->pDriverContext;
    struct dri_state *dri_state = (struct dri_state *)ctx->dri_state;
    char *driver_name_env;
    int vendor_id, device_id;

    struct {
        int vendor_id;
        int device_id;
        char driver_name[64];
    } devices[] = {
        { 0x8086, 0x4100, "pvr" },
        { 0x8086, 0x0130, "pvr" },
        { 0x0,    0x0,    "\0" },
    };

    memset(dri_state, 0, sizeof(*dri_state));
    dri_state->fd = open_device(DEVICE_NAME);

    if (dri_state->fd < 0) {
        fprintf(stderr,"can't open DRM devices\n");
        return VA_STATUS_ERROR_UNKNOWN;
    }

    /* TBD: other vendor driver names */
    vendor_id = devices[0].vendor_id;
    device_id = devices[0].device_id;
    *driver_name = strdup(devices[0].driver_name);

    dri_state->driConnectedFlag = VA_DUMMY;

    return VA_STATUS_SUCCESS;
}
#else
static VAStatus va_DisplayContextGetDriverName (
    VADisplayContextP pDisplayContext,
    char **driver_name
)
{
    VADriverContextP ctx = pDisplayContext->pDriverContext;
    struct dri_state *dri_state = (struct dri_state *)ctx->dri_state;
    char *driver_name_env;
    int vendor_id, device_id;
    int i = 0;

    struct {
        int vendor_id;
        int device_id;
        char driver_name[64];
    } devices[] = {
        { 0x8086, 0x4100, "pvr" },
        { 0x8086, 0x0130, "pvr" },
        { 0x0,    0x0,    "\0" },
    };

    memset(dri_state, 0, sizeof(*dri_state));
    dri_state->fd = drm_open_any(&vendor_id, &device_id);

    if (dri_state->fd < 0) {
        fprintf(stderr,"can't open DRM devices\n");
        return VA_STATUS_ERROR_UNKNOWN;
    }

    /* TBD: other vendor driver names */

    while (devices[i].device_id != 0) {
        if ((devices[i].vendor_id == vendor_id) &&
            (devices[i].device_id == device_id))
            break;
        i++;
    }

    if (devices[i].device_id != 0)
        *driver_name = strdup(devices[i].driver_name);
    else {
        fprintf(stderr,"device (0x%04x:0x%04x) is not supported\n",
                vendor_id, device_id);

        return VA_STATUS_ERROR_UNKNOWN;
    }

    printf("DRM device is opened, loading driver %s for device 0x%04x:0x%04x\n",
           driver_name, vendor_id, device_id);

    dri_state->driConnectedFlag = VA_DUMMY;

    return VA_STATUS_SUCCESS;
}
#endif

VADisplay vaGetDisplay (
    void *native_dpy /* implementation specific */
)
{
    VADisplay dpy = NULL;
    VADisplayContextP pDisplayContext;

    if (!native_dpy)
        return NULL;

    if (!dpy)
    {
        /* create new entry */
        VADriverContextP pDriverContext;
        struct dri_state *dri_state;
        pDisplayContext = (VADisplayContextP)calloc(1, sizeof(*pDisplayContext));
        pDriverContext  = (VADriverContextP)calloc(1, sizeof(*pDriverContext));
        dri_state       = (struct dri_state*)calloc(1, sizeof(*dri_state));
        if (pDisplayContext && pDriverContext && dri_state)
        {
            pDisplayContext->vadpy_magic = VA_DISPLAY_MAGIC;

            pDriverContext->native_dpy       = (void *)native_dpy;
            pDisplayContext->pDriverContext  = pDriverContext;
            pDisplayContext->vaIsValid       = va_DisplayContextIsValid;
            pDisplayContext->vaDestroy       = va_DisplayContextDestroy;
            pDisplayContext->vaGetDriverName = va_DisplayContextGetDriverName;
            pDriverContext->dri_state 	     = dri_state;
            dpy                              = (VADisplay)pDisplayContext;
        }
        else
        {
            if (pDisplayContext)
                free(pDisplayContext);
            if (pDriverContext)
                free(pDriverContext);
            if (dri_state)
                free(dri_state);
        }
    }

    return dpy;
}

#define CTX(dpy) (((VADisplayContextP)dpy)->pDriverContext)
#define CHECK_DISPLAY(dpy) if( !vaDisplayIsValid(dpy) ) { return VA_STATUS_ERROR_INVALID_DISPLAY; }

#ifdef ANDROID
extern "C"  {
    extern int fool_postp; /* do nothing for vaPutSurface if set */
    extern int trace_flag; /* trace vaPutSurface parameters */

    void va_TracePutSurface (
        VADisplay dpy,
        VASurfaceID surface,
        void *draw, /* the target Drawable */
        short srcx,
        short srcy,
        unsigned short srcw,
        unsigned short srch,
        short destx,
        short desty,
        unsigned short destw,
        unsigned short desth,
        VARectangle *cliprects, /* client supplied clip list */
        unsigned int number_cliprects, /* number of clip rects in the clip list */
        unsigned int flags /* de-interlacing flags */
        );
}

#define VA_TRACE(trace_func,...)                \
    if (trace_flag) {                           \
        trace_func(__VA_ARGS__);                \
    }

VAStatus vaPutSurface (
    VADisplay dpy,
    VASurfaceID surface,
    sp<ISurface> draw, /* Android Surface/Window */
    short srcx,
    short srcy,
    unsigned short srcw,
    unsigned short srch,
    short destx,
    short desty,
    unsigned short destw,
    unsigned short desth,
    VARectangle *cliprects, /* client supplied clip list */
    unsigned int number_cliprects, /* number of clip rects in the clip list */
    unsigned int flags /* de-interlacing flags */
)
{
    VADriverContextP ctx;

    if (fool_postp)
        return VA_STATUS_SUCCESS;

    if (draw == NULL)
        return VA_STATUS_ERROR_UNKNOWN;

    CHECK_DISPLAY(dpy);
    ctx = CTX(dpy);

    VA_TRACE(va_TracePutSurface, dpy, surface, static_cast<void*>(&draw), srcx, srcy, srcw, srch,
             destx, desty, destw, desth,
             cliprects, number_cliprects, flags );

    return ctx->vtable->vaPutSurface( ctx, surface, static_cast<void*>(&draw), srcx, srcy, srcw, srch,
                                     destx, desty, destw, desth,
                                     cliprects, number_cliprects, flags );
}
#endif
<|endoftext|>


<commit_before>#include "ros/ros.h"

#include "ear.h"

Ear::Ear()
{
	m_i2c = new mraa::I2c(1);
	if(m_i2c == NULL) {
		ROS_DEBUG("Ear Constructor Failed!");
		return;
	}

	cnt = 0;

	ROS_DEBUG("Ear Constructor Successfully");
}

Ear::~Ear()
{

}

uint32_t Ear::DoListen()
{
	uint32_t dist_hi=0, dist_lo=0;
	uint8_t rx_tx_buf[2];

	if(cnt == 0) {
		cnt++;
	} else {
		/* i don't care the first time */
		m_i2c->address(USONIC_0_ADDR);
		m_i2c->writeByte(2);
		m_i2c->address(USONIC_0_ADDR);
		dist_hi = m_i2c->readByte();

		m_i2c->address(USONIC_0_ADDR);
		m_i2c->writeByte(3);
		m_i2c->address(USONIC_0_ADDR);
		dist_lo = m_i2c->readByte();
	}

	/* this is used for next time */
	m_i2c->address(USONIC_0_ADDR);
	rx_tx_buf[0] = 2;
	rx_tx_buf[1] = CMD_DETECT_0_5_METER;
	m_i2c->write(rx_tx_buf, 2);

	/* the unit is MM */
 	return (dist_hi*255 + dist_lo)*34/200;
}

int Ear::EarInit(int connector, int pin)
{
	m_connector = connector;
	m_pin = pin;

	return 0;
}<commit_msg>add LOG<commit_after>#include "ros/ros.h"

#include "ear.h"

Ear::Ear()
{
	m_i2c = new mraa::I2c(1);
	if(m_i2c == NULL) {
		ROS_DEBUG("Ear Constructor Failed!");
		return;
	}

	cnt = 0;

	ROS_DEBUG("Ear Constructor Successfully");
}

Ear::~Ear()
{

}

uint32_t Ear::DoListen()
{
	uint32_t dist_hi=0, dist_lo=0;
	uint8_t rx_tx_buf[2];

	if(cnt == 0) {
		cnt++;
	} else {
		/* i don't care the first time */
		m_i2c->address(USONIC_0_ADDR);
		m_i2c->writeByte(2);
		m_i2c->address(USONIC_0_ADDR);
		dist_hi = m_i2c->readByte();

		m_i2c->address(USONIC_0_ADDR);
		m_i2c->writeByte(3);
		m_i2c->address(USONIC_0_ADDR);
		dist_lo = m_i2c->readByte();
	}

	/* this is used for next time */
	m_i2c->address(USONIC_0_ADDR);
	rx_tx_buf[0] = 2;
	rx_tx_buf[1] = CMD_DETECT_0_5_METER;
	m_i2c->write(rx_tx_buf, 2);

ROS_INFO("--- %d:%d ---", dist_hi, dist_lo);
	/* the unit is MM */
 	return (dist_hi*255 + dist_lo)*34/200;
}

int Ear::EarInit(int connector, int pin)
{
	m_connector = connector;
	m_pin = pin;

	return 0;
}<|endoftext|>