<commit_before>/************************************************************************/
/*                                                                      */
/*    Wire.cpp                                                          */
/*                                                                      */
/*    I2C  implemenation                                                */
/*                                                                      */
/************************************************************************/
/*    Author:     Keith Vogel                                           */
/*    Copyright 2014, Digilent Inc.                                     */
/************************************************************************/
/*
*
* Copyright (c) 2013-2014, Digilent <www.digilentinc.com>
* Contact Digilent for the latest version.
*
* This program is free software; distributed under the terms of
* BSD 3-clause license ("Revised BSD License", "New BSD License", or "Modified BSD License")
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1.    Redistributions of source code must retain the above copyright notice, this
*        list of conditions and the following disclaimer.
* 2.    Redistributions in binary form must reproduce the above copyright notice,
*        this list of conditions and the following disclaimer in the documentation
*        and/or other materials provided with the distribution.
* 3.    Neither the name(s) of the above-listed copyright holder(s) nor the names
*        of its contributors may be used to endorse or promote products derived
*        from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/************************************************************************/
/*  Revision History:                                                   */
/*    8/4/2014(KeithV): Created                                         */
/************************************************************************/
// DTWI is not on the path and we don't want the user to have
// to explicitly include the library. So just grab it and compile it
#include "../DTWI/DTWI.cpp"
#define ENABLE_END
#include <Wire.h>

DTWI0 di2c;
TwoWire Wire;

// Initialize Class Variables //////////////////////////////////////////////////

uint8_t TwoWire::rxBuffer[BUFFER_LENGTH];
uint8_t TwoWire::rxBufferIndex = 0;
uint8_t TwoWire::rxBufferLength = 0;

uint8_t TwoWire::txAddress = 0;
uint8_t TwoWire::txBuffer[BUFFER_LENGTH];
uint8_t TwoWire::txBufferIndex = 0;
uint8_t TwoWire::txBufferLength = 0;

uint8_t TwoWire::transmitting = 0;
void (*TwoWire::user_onRequest)(void);
void (*TwoWire::user_onReceive)(int);

uint32_t TwoWire::beginCount = 0;

static void (*onReceiveServiceR) (uint8_t*, int) = NULL;
static void (*onRequestServiceR)(void)           = NULL;
static uint32_t iSessionCur                     = 0xFF;

static void onI2C(int id, void * tptr)
{
    DTWI::I2C_STATUS status = di2c.getStatus();
    uint8_t data;

    if(status.fSlave)
    {
        if(status.fRead)
        {
            while(di2c.available() > 0)
            {
                onReceiveServiceR(NULL, di2c.available());
            }
        }

        // on writing out, we only call once when the
        // new session starts
        else if(status.fWrite && iSessionCur != status.iSession)
        {
            iSessionCur = status.iSession;
            onRequestServiceR();
        }
    }
}

static bool beginSlave(void (*onReceiveService) (uint8_t*, int), void (*onRequestService)(void))
{
    if(getTaskId(onI2C) == -1)
    {
        createTask(onI2C, 0, TASK_ENABLE, NULL);
    };
    onReceiveServiceR = onReceiveService;
    onRequestServiceR = onRequestService;
    iSessionCur = 0xFF;

    return(true);
}

// Constructors ////////////////////////////////////////////////////////////////

TwoWire::TwoWire()
{
}

// Public Methods //////////////////////////////////////////////////////////////

void TwoWire::begin(void)
{
    if(beginCount == 0)
    {
    beginCount++;
        // there are no callback in Master mode
        destroyTask(getTaskId(onI2C));
        di2c.beginMaster();
    }
}

void TwoWire::begin(uint8_t address)
{
    if(beginCount == 0)
    {
        beginCount++;

        // make sure we put the callback in the task manager
        beginSlave(onReceiveService, onRequestService);
        di2c.beginSlave(address);
    }
}

// The end function is a non-standard function which is intended to mirror the end function
// of the SPI and DSPI libraries.  It decrements the open counter and, when zero, will
// (eventually) disable the I2C interface.  This is yet to be completed.
//
// Until it is completed this is an option function enabled in the Wire.h header file.

#ifdef ENABLE_END
void TwoWire::end() {
    DTWI::I2C_STATUS status = di2c.getStatus();

    if(beginCount == 0)
    {
        return;
    }

    destroyTask(getTaskId(onI2C));
    beginCount = 0;

    if(status.fMaster)
    {
        di2c.endMaster();
    }
    else if(status.fSlave)
    {
        // forcefully end the slave
        di2c.endSlave(true);
    }

    // clean out the read / write buffer
    di2c.abort();
    di2c.discard();
    }
#endif

void TwoWire::begin(int address)
{
  begin((uint8_t)address);
}

uint8_t TwoWire::requestFrom(uint8_t address, uint8_t quantity)
{
    DTWI::I2C_STATUS status;

    // may have to wait for the last action to finish before
    // a repeated start can occur
    while(!di2c.startMasterRead(address, quantity));

    do
    {
        status = di2c.getStatus();
    } while(status.fMyBus && !status.fNacking);

    while(!di2c.stopMaster());

    return(di2c.available());
}

uint8_t TwoWire::requestFrom(int address, int quantity)
{
  return requestFrom((uint8_t)address, (uint8_t)quantity);
}

void TwoWire::beginTransmission(uint8_t address)
{
    while(!di2c.startMasterWrite(address));
}

void TwoWire::beginTransmission(int address)
{
  beginTransmission((uint8_t)address);
}

uint8_t TwoWire::endTransmission(uint8_t fStopBit)
{
    if(fStopBit)
    {
        while(!di2c.stopMaster());
    }
    return(true);
}
uint8_t TwoWire::endTransmission(void)
{
    return(endTransmission(true));
}

// must be called in:
// slave tx event callback
// or after beginTransmission(address)
int TwoWire::write(uint8_t data)
{
    return(di2c.write((const byte *) &data, 1));
}
void TwoWire::send(uint8_t data) { write(data); }

// must be called in:
// slave tx event callback
// or after beginTransmission(address)
int TwoWire::write(uint8_t* data, uint8_t quantity)
{
    return(di2c.write((const byte *) data, quantity));
}
void TwoWire::send(uint8_t* data, uint8_t quantity) { write(data, quantity); }

// must be called in:
// slave tx event callback
// or after beginTransmission(address)
int TwoWire::write(char* data)
{
    return(write((uint8_t*) data, strlen(data)));
}
void TwoWire::send(char* data) { write(data); }

// must be called in:
// slave tx event callback
// or after beginTransmission(address)
int TwoWire::write(int data)
{
    return(write((uint8_t) data));
}
void TwoWire::send(int data) { write(data); }

// must be called in:
// slave rx event callback
// or after requestFrom(address, numBytes)
uint8_t TwoWire::available(void)
{
  return (di2c.available());
}

uint8_t TwoWire::receive(void) {
	return(read());
}

// must be called in:
// slave rx event callback
// or after requestFrom(address, numBytes)
uint8_t TwoWire::read(void)
{
    byte    data;

    if(di2c.read(&data, 1) == 1)
    {
        return((uint8_t) data);
  }

	return('\0');
}

// behind the scenes function that is called when data is received
void TwoWire::onReceiveService(uint8_t* inBytes, int numBytes)
{
  // don't bother if user hasn't registered a callback
  if(!user_onReceive){
    return;
  }
  // don't bother if rx buffer is in use by a master requestFrom() op
  // i know this drops data, but it allows for slight stupidity
  // meaning, they may not have read all the master requestFrom() data yet
    user_onReceive(numBytes);
}

// behind the scenes function that is called when data is requested
void TwoWire::onRequestService(void)
{
  // don't bother if user hasn't registered a callback
  if(!user_onRequest){
    return;
  }
  // alert user program
  user_onRequest();
}

// sets function called on slave write
void TwoWire::onReceive( void (*function)(int) )
{
  user_onReceive = function;
}

// sets function called on slave read
void TwoWire::onRequest( void (*function)(void) )
{
  user_onRequest = function;
}

<commit_msg>Fix for #95 : update Wire.cpp to MPIDE's version.<commit_after>/************************************************************************/
/*                                                                      */
/*    Wire.cpp                                                          */
/*                                                                      */
/*    I2C  implemenation                                                */
/*                                                                      */
/************************************************************************/
/*    Author:     Keith Vogel                                           */
/*    Copyright 2014, Digilent Inc.                                     */
/************************************************************************/
/*
*
* Copyright (c) 2013-2014, Digilent <www.digilentinc.com>
* Contact Digilent for the latest version.
*
* This program is free software; distributed under the terms of
* BSD 3-clause license ("Revised BSD License", "New BSD License", or "Modified BSD License")
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1.    Redistributions of source code must retain the above copyright notice, this
*        list of conditions and the following disclaimer.
* 2.    Redistributions in binary form must reproduce the above copyright notice,
*        this list of conditions and the following disclaimer in the documentation
*        and/or other materials provided with the distribution.
* 3.    Neither the name(s) of the above-listed copyright holder(s) nor the names
*        of its contributors may be used to endorse or promote products derived
*        from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/************************************************************************/
/*  Revision History:                                                   */
/*    8/4/2014(KeithV): Created                                         */
/************************************************************************/
// DTWI is not on the path and we don't want the user to have
// to explicitly include the library. So just grab it and compile it
#include "../DTWI/DTWI.cpp"
#define ENABLE_END
#include <Wire.h>

DTWI0 di2c;
TwoWire Wire;

// Initialize Class Variables //////////////////////////////////////////////////

uint8_t TwoWire::rxBuffer[BUFFER_LENGTH];
uint8_t TwoWire::rxBufferIndex = 0;
uint8_t TwoWire::rxBufferLength = 0;

uint8_t TwoWire::txAddress = 0;
uint8_t TwoWire::txBuffer[BUFFER_LENGTH];
uint8_t TwoWire::txBufferIndex = 0;
uint8_t TwoWire::txBufferLength = 0;

uint8_t TwoWire::transmitting = 0;
void (*TwoWire::user_onRequest)(void);
void (*TwoWire::user_onReceive)(int);

uint32_t TwoWire::beginCount = 0;

static void (*onReceiveServiceR) (uint8_t*, int) = NULL;
static void (*onRequestServiceR)(void)           = NULL;
static uint32_t iSessionCur                     = 0xFF;

static void onI2C(int id, void * tptr)
{
    DTWI::I2C_STATUS status = di2c.getStatus();
    uint8_t data;

    if(status.fSlave)
    {
        if(status.fRead)
        {
            while(di2c.available() > 0)
            {
                onReceiveServiceR(NULL, di2c.available());
            }
        }

        // on writing out, we only call once when the
        // new session starts
        else if(status.fWrite && iSessionCur != status.iSession)
        {
            iSessionCur = status.iSession;
            onRequestServiceR();
        }
    }
}

static bool beginSlave(void (*onReceiveService) (uint8_t*, int), void (*onRequestService)(void))
{
    if(getTaskId(onI2C) == -1)
    {
        createTask(onI2C, 0, TASK_ENABLE, NULL);
    };
    onReceiveServiceR = onReceiveService;
    onRequestServiceR = onRequestService;
    iSessionCur = 0xFF;

    return(true);
}

// Constructors ////////////////////////////////////////////////////////////////

TwoWire::TwoWire()
{
}

// Public Methods //////////////////////////////////////////////////////////////

void TwoWire::begin(void)
{
    if(beginCount == 0)
    {
    beginCount++;
        // there are no callback in Master mode
        destroyTask(getTaskId(onI2C));
        di2c.beginMaster();
    }
}

void TwoWire::begin(uint8_t address)
{
    if(beginCount == 0)
    {
        beginCount++;

        // make sure we put the callback in the task manager
        beginSlave(onReceiveService, onRequestService);
        di2c.beginSlave(address);
    }
}

// The end function is a non-standard function which is intended to mirror the end function
// of the SPI and DSPI libraries.  It decrements the open counter and, when zero, will
// (eventually) disable the I2C interface.  This is yet to be completed.
//
// Until it is completed this is an option function enabled in the Wire.h header file.

#ifdef ENABLE_END
void TwoWire::end() {
    DTWI::I2C_STATUS status = di2c.getStatus();

    if(beginCount == 0)
    {
        return;
    }

    destroyTask(getTaskId(onI2C));
    beginCount = 0;

    if(status.fMaster)
    {
        di2c.endMaster();
    }
    else if(status.fSlave)
    {
        // forcefully end the slave
        di2c.endSlave(true);
    }

    // clean out the read / write buffer
    di2c.abort();
    di2c.discard();
    }
#endif

void TwoWire::begin(int address)
{
  begin((uint8_t)address);
}

uint8_t TwoWire::requestFrom(uint8_t address, uint8_t quantity)
{
    DTWI::I2C_STATUS i2cStatus = di2c.getStatus();

    // see if the bus is already in use
    if(i2cStatus.fBusInUse && !i2cStatus.fMyBus)
    {
        return(0);
    }

    // may have to wait for the last action to finish before
    // a repeated start can occur
    while(!di2c.startMasterRead(address, quantity) && di2c.getStatus().fMyBus);

    do
    {
        i2cStatus = di2c.getStatus();
    } while(i2cStatus.fMyBus && !i2cStatus.fNacking);

    while(!di2c.stopMaster());

    return(di2c.available());
}

uint8_t TwoWire::requestFrom(int address, int quantity)
{
  return requestFrom((uint8_t)address, (uint8_t)quantity);
}

void TwoWire::beginTransmission(uint8_t address)
{
    DTWI::I2C_STATUS i2cStatus = di2c.getStatus();

    // if someone else has the bus, then we won't get it; get out
    if(i2cStatus.fBusInUse  && !i2cStatus.fMyBus)
    {
        return;
    }

    // we only want to loop on this with a repeated start
    // otherwise it will pass on the first try
    while(!di2c.startMasterWrite(address) && di2c.getStatus().fMyBus);
}

void TwoWire::beginTransmission(int address)
{
  beginTransmission((uint8_t)address);
}

uint8_t TwoWire::endTransmission(uint8_t fStopBit)
{
    uint8_t retStatus = 0;
    DTWI::I2C_STATUS i2cStatus;

    // if not my bus, then the beginMaster failed and we either had
    // a collision or the slave acked, in either case report a NACK from the slave
    if(!di2c.getStatus().fMyBus)
    {
        return(2);
    }

    // wait for the transmit buffer is empty
    while(di2c.getStatus().fWrite && di2c.transmitting() != 0);

    // Get the current status
    i2cStatus = di2c.getStatus();

    // what happened to the bus, we use to have it?
    // other error
    if(!i2cStatus.fMyBus)
    {
        return(4);
    }

    // we have the bus, but not writing
    // the otherside NACKed our Write
    else if(!i2cStatus.fWrite)
    {
            retStatus = 3;
    }

    // put a stop bit out if we are not going to attempt a repeated start
    if(fStopBit)
    {
        while(!di2c.stopMaster());
    }

    return(retStatus);
}

uint8_t TwoWire::endTransmission(void)
{
    return(endTransmission(true));
}

// must be called in:
// slave tx event callback
// or after beginTransmission(address)
int TwoWire::write(uint8_t data)
{
    return(di2c.write((const byte *) &data, 1));
}
void TwoWire::send(uint8_t data) { write(data); }

// must be called in:
// slave tx event callback
// or after beginTransmission(address)
int TwoWire::write(uint8_t* data, uint8_t quantity)
{
    return(di2c.write((const byte *) data, quantity));
}
void TwoWire::send(uint8_t* data, uint8_t quantity) { write(data, quantity); }

// must be called in:
// slave tx event callback
// or after beginTransmission(address)
int TwoWire::write(char* data)
{
    return(write((uint8_t*) data, strlen(data)));
}
void TwoWire::send(char* data) { write(data); }

// must be called in:
// slave tx event callback
// or after beginTransmission(address)
int TwoWire::write(int data)
{
    return(write((uint8_t) data));
}
void TwoWire::send(int data) { write(data); }

// must be called in:
// slave rx event callback
// or after requestFrom(address, numBytes)
uint8_t TwoWire::available(void)
{
  return (di2c.available());
}

uint8_t TwoWire::receive(void) {
	return(read());
}

// must be called in:
// slave rx event callback
// or after requestFrom(address, numBytes)
uint8_t TwoWire::read(void)
{
    byte    data;

    if(di2c.read(&data, 1) == 1)
    {
        return((uint8_t) data);
  }

	return('\0');
}

// behind the scenes function that is called when data is received
void TwoWire::onReceiveService(uint8_t* inBytes, int numBytes)
{
  // don't bother if user hasn't registered a callback
  if(!user_onReceive){
    return;
  }
  // don't bother if rx buffer is in use by a master requestFrom() op
  // i know this drops data, but it allows for slight stupidity
  // meaning, they may not have read all the master requestFrom() data yet
    user_onReceive(numBytes);
}

// behind the scenes function that is called when data is requested
void TwoWire::onRequestService(void)
{
  // don't bother if user hasn't registered a callback
  if(!user_onRequest){
    return;
  }
  // alert user program
  user_onRequest();
}

// sets function called on slave write
void TwoWire::onReceive( void (*function)(int) )
{
  user_onReceive = function;
}

// sets function called on slave read
void TwoWire::onRequest( void (*function)(void) )
{
  user_onRequest = function;
}

<|endoftext|>


<commit_before>#include "bananagrams.hpp"

using std::cerr;
using std::endl;
using std::string;

Typer::Typer()
{
	ch = 'A' - 1;
}

bool Typer::get_ch(char* chr)
{
	if (ch >= 'A' && ch <= 'Z')
	{
		*chr = ch;
		ch = 'A' - 1;
		return true;
	}
	return false;
}

bool Typer::process_event(sf::Event& event)
{
	if (event.type == sf::Event::KeyPressed && event.key.code >= sf::Keyboard::Key::A && event.key.code <= sf::Keyboard::Key::Z)
		ch = event.key.code - sf::Keyboard::Key::A + 'A';
	return true;
}

MouseControls::MouseControls(State* m)
{
	state = m;
}

bool MouseControls::process_event(sf::Event& event)
{
	switch(event.type)
	{
		case sf::Event::MouseButtonPressed:
			if (event.mouseButton.button == sf::Mouse::Left)
				state->start_selection = true;
			else if (event.mouseButton.button == sf::Mouse::Right)
				state->mremove = true;
			break;
		case sf::Event::MouseButtonReleased:
			state->update = true;
			if (event.mouseButton.button == sf::Mouse::Left)
				state->end_selection = true;
			else if (event.mouseButton.button == sf::Mouse::Right)
				state->mremove = false;
			break;
		case sf::Event::MouseMoved:
			{
				state->update = true;
				state->pos[0] = event.mouseMove.x;
				state->pos[1] = event.mouseMove.y;
			}
			break;
		case sf::Event::MouseWheelMoved:
			state->wheel_delta = event.mouseWheel.delta;
			break;
		default:
			break;
	}

	return true;
}

KeyControls::Command::Command(repeat_t rep)
{
	pressed = false;
	ready = true;
	repeat = rep;
}

KeyControls::KeyControls()
{
	set_defaults();
}

void KeyControls::bind(const sf::Event::KeyEvent& key, const string& command, repeat_t rep)
{
	binds[key] = command;
	commands[command] = Command(rep);
}

void KeyControls::rebind(const sf::Event::KeyEvent& key, const string& command)
{
	if (!has_bind(command))
		throw NotFound(command);
	binds[key] = command;
	commands[command].pressed = false;
	commands[command].ready = true;
}

void KeyControls::set_defaults()
{
	// TODO is there a better way to structure these?
	binds.clear();
	commands.clear();

	sf::Event::KeyEvent key;
	key.alt = false;
	key.control = false;
	key.shift = false;
	key.system = false;

	key.code = sf::Keyboard::Key::Left;
	bind(key, "left", REPEAT);
	key.code = sf::Keyboard::Right;
	bind(key, "right", REPEAT);
	key.code = sf::Keyboard::Up;
	bind(key, "up", REPEAT);
	key.code = sf::Keyboard::Down;
	bind(key, "down", REPEAT);
	key.shift = true;
	key.code = sf::Keyboard::Left;
	bind(key, "left_fast", REPEAT);
	key.code = sf::Keyboard::Right;
	bind(key, "right_fast", REPEAT);
	key.code = sf::Keyboard::Up;
	bind(key, "up_fast", REPEAT);
	key.code = sf::Keyboard::Down;
	bind(key, "down_fast", REPEAT);
	key.control = true;
	key.shift = false;
	key.code = sf::Keyboard::Key::Up;
	bind(key, "zoom_in", HOLD);
	key.code = sf::Keyboard::Key::Down;
	bind(key, "zoom_out", HOLD);
	key.shift = true;
	key.code = sf::Keyboard::Key::Up;
	bind(key, "zoom_in_fast", HOLD);
	key.code = sf::Keyboard::Key::Down;
	bind(key, "zoom_out_fast", HOLD);
	key.control = false;
	key.shift = false;
	key.code = sf::Keyboard::BackSpace;
	bind(key, "remove", REPEAT);
	key.code = sf::Keyboard::Space;
	bind(key, "peel", PRESS);
	key.control = true;
	key.code = sf::Keyboard::C;
	bind(key, "center", PRESS);
	key.code = sf::Keyboard::D;
	bind(key, "dump", PRESS);
	key.code = sf::Keyboard::X;
	bind(key, "cut", PRESS);
	key.code = sf::Keyboard::V;
	bind(key, "paste", PRESS);
	key.code = sf::Keyboard::F;
	bind(key, "flip", PRESS);
	key.control = false;
	key.code = sf::Keyboard::LControl;
	bind(key, "quick_place", HOLD);
}

bool KeyControls::load_from_file(const string& filename)
{
	YAML::Node bindings = YAML::LoadFile(filename);

	if (!bindings.IsMap())
	{
		cerr << "Ignoring bad config file\n"
		return false;
	}

	for (auto binding : bindings)
	{
		try
		{
			rebind(binding.second.as<sf::Event::KeyEvent>(), binding.first.as<string>());
		}
		catch (NotFound)
		{
			cerr << "Unrecognized command: " << binding.first.as<string>() << endl;
		}
		catch (YAML::TypedBadConversion<sf::Event::KeyEvent>)
		{
			// YAML conversion already prints errors
		}
	}

	return true;
}

bool KeyControls::operator[](const string& command)
{
	Command& c = commands[command];
	bool press = c.pressed;

	if (c.get_repeat() != HOLD)
		c.pressed = false;

	return press;
}

bool KeyControls::process_event(sf::Event& event)
{
	if (event.type == sf::Event::KeyPressed)
	{
		// TODO this doesn't work if you release modifier keys in different orders
		auto it = binds.find(event.key);
		if (it != binds.end())
		{
			Command& c = commands[it->second];
			switch (c.get_repeat())
			{
				case PRESS:
					if (c.ready)
					{
						c.pressed = true;
						c.ready = false;
					}
					break;
				case REPEAT:
				case HOLD:
					c.pressed = true;
					break;
			}

			// don't continue bound keypresses
			return false;
		}
	}
	else if (event.type == sf::Event::KeyReleased)
	{
		switch (event.key.code)
		{
			case sf::Keyboard::Key::LAlt:
			case sf::Keyboard::Key::RAlt:
				for (auto pair : binds)
					if (commands[pair.second].get_repeat() == HOLD && (pair.first.alt || pair.first.code == sf::Keyboard::Key::LAlt || pair.first.code == sf::Keyboard::Key::RAlt))
						commands[pair.second].pressed = false;
				break;
			case sf::Keyboard::Key::LControl:
			case sf::Keyboard::Key::RControl:
				for (auto pair : binds)
					if (commands[pair.second].get_repeat() == HOLD && (pair.first.control || pair.first.code == sf::Keyboard::Key::LControl || pair.first.code == sf::Keyboard::Key::RControl))
						commands[pair.second].pressed = false;
				break;
			case sf::Keyboard::Key::LShift:
			case sf::Keyboard::Key::RShift:
				for (auto pair : binds)
					if (commands[pair.second].get_repeat() == HOLD && (pair.first.shift || pair.first.code == sf::Keyboard::Key::LShift || pair.first.code == sf::Keyboard::Key::RShift))
						commands[pair.second].pressed = false;
				break;
			case sf::Keyboard::Key::LSystem:
			case sf::Keyboard::Key::RSystem:
				for (auto pair : binds)
					if (commands[pair.second].get_repeat() == HOLD && (pair.first.system || pair.first.code == sf::Keyboard::Key::LSystem || pair.first.code == sf::Keyboard::Key::RSystem))
						commands[pair.second].pressed = false;
				break;
			default:
				break;
		}
		auto it = binds.find(event.key);
		if (it != binds.end())
		{
			Command& c = commands[it->second];
			switch (c.get_repeat())
			{
				case PRESS:
					c.ready = true;
					break;
				case REPEAT:
					break;
				case HOLD:
					c.pressed = false;
					break;
			}
		}
	}

	return true;
}
<commit_msg>Soft error when config.yaml doesn't exist<commit_after>#include "bananagrams.hpp"

using std::cerr;
using std::endl;
using std::string;

Typer::Typer()
{
	ch = 'A' - 1;
}

bool Typer::get_ch(char* chr)
{
	if (ch >= 'A' && ch <= 'Z')
	{
		*chr = ch;
		ch = 'A' - 1;
		return true;
	}
	return false;
}

bool Typer::process_event(sf::Event& event)
{
	if (event.type == sf::Event::KeyPressed && event.key.code >= sf::Keyboard::Key::A && event.key.code <= sf::Keyboard::Key::Z)
		ch = event.key.code - sf::Keyboard::Key::A + 'A';
	return true;
}

MouseControls::MouseControls(State* m)
{
	state = m;
}

bool MouseControls::process_event(sf::Event& event)
{
	switch(event.type)
	{
		case sf::Event::MouseButtonPressed:
			if (event.mouseButton.button == sf::Mouse::Left)
				state->start_selection = true;
			else if (event.mouseButton.button == sf::Mouse::Right)
				state->mremove = true;
			break;
		case sf::Event::MouseButtonReleased:
			state->update = true;
			if (event.mouseButton.button == sf::Mouse::Left)
				state->end_selection = true;
			else if (event.mouseButton.button == sf::Mouse::Right)
				state->mremove = false;
			break;
		case sf::Event::MouseMoved:
			{
				state->update = true;
				state->pos[0] = event.mouseMove.x;
				state->pos[1] = event.mouseMove.y;
			}
			break;
		case sf::Event::MouseWheelMoved:
			state->wheel_delta = event.mouseWheel.delta;
			break;
		default:
			break;
	}

	return true;
}

KeyControls::Command::Command(repeat_t rep)
{
	pressed = false;
	ready = true;
	repeat = rep;
}

KeyControls::KeyControls()
{
	set_defaults();
}

void KeyControls::bind(const sf::Event::KeyEvent& key, const string& command, repeat_t rep)
{
	binds[key] = command;
	commands[command] = Command(rep);
}

void KeyControls::rebind(const sf::Event::KeyEvent& key, const string& command)
{
	if (!has_bind(command))
		throw NotFound(command);
	binds[key] = command;
	commands[command].pressed = false;
	commands[command].ready = true;
}

void KeyControls::set_defaults()
{
	// TODO is there a better way to structure these?
	binds.clear();
	commands.clear();

	sf::Event::KeyEvent key;
	key.alt = false;
	key.control = false;
	key.shift = false;
	key.system = false;

	key.code = sf::Keyboard::Key::Left;
	bind(key, "left", REPEAT);
	key.code = sf::Keyboard::Right;
	bind(key, "right", REPEAT);
	key.code = sf::Keyboard::Up;
	bind(key, "up", REPEAT);
	key.code = sf::Keyboard::Down;
	bind(key, "down", REPEAT);
	key.shift = true;
	key.code = sf::Keyboard::Left;
	bind(key, "left_fast", REPEAT);
	key.code = sf::Keyboard::Right;
	bind(key, "right_fast", REPEAT);
	key.code = sf::Keyboard::Up;
	bind(key, "up_fast", REPEAT);
	key.code = sf::Keyboard::Down;
	bind(key, "down_fast", REPEAT);
	key.control = true;
	key.shift = false;
	key.code = sf::Keyboard::Key::Up;
	bind(key, "zoom_in", HOLD);
	key.code = sf::Keyboard::Key::Down;
	bind(key, "zoom_out", HOLD);
	key.shift = true;
	key.code = sf::Keyboard::Key::Up;
	bind(key, "zoom_in_fast", HOLD);
	key.code = sf::Keyboard::Key::Down;
	bind(key, "zoom_out_fast", HOLD);
	key.control = false;
	key.shift = false;
	key.code = sf::Keyboard::BackSpace;
	bind(key, "remove", REPEAT);
	key.code = sf::Keyboard::Space;
	bind(key, "peel", PRESS);
	key.control = true;
	key.code = sf::Keyboard::C;
	bind(key, "center", PRESS);
	key.code = sf::Keyboard::D;
	bind(key, "dump", PRESS);
	key.code = sf::Keyboard::X;
	bind(key, "cut", PRESS);
	key.code = sf::Keyboard::V;
	bind(key, "paste", PRESS);
	key.code = sf::Keyboard::F;
	bind(key, "flip", PRESS);
	key.control = false;
	key.code = sf::Keyboard::LControl;
	bind(key, "quick_place", HOLD);
}

bool KeyControls::load_from_file(const string& filename)
{
	bool bad = false;
	YAML::Node bindings;
	try
	{
		bindings = YAML::LoadFile(filename);
	}
	catch (YAML::BadFile)
	{
		bad = true;
	}

	if (bad || !bindings.IsMap())
	{
		cerr << "Ignoring bad/missing config file\n";
		return false;
	}

	for (auto binding : bindings)
	{
		try
		{
			rebind(binding.second.as<sf::Event::KeyEvent>(), binding.first.as<string>());
		}
		catch (NotFound)
		{
			cerr << "Unrecognized command: " << binding.first.as<string>() << endl;
		}
		catch (YAML::TypedBadConversion<sf::Event::KeyEvent>)
		{
			// YAML conversion already prints errors
		}
	}

	return true;
}

bool KeyControls::operator[](const string& command)
{
	Command& c = commands[command];
	bool press = c.pressed;

	if (c.get_repeat() != HOLD)
		c.pressed = false;

	return press;
}

bool KeyControls::process_event(sf::Event& event)
{
	if (event.type == sf::Event::KeyPressed)
	{
		// TODO this doesn't work if you release modifier keys in different orders
		auto it = binds.find(event.key);
		if (it != binds.end())
		{
			Command& c = commands[it->second];
			switch (c.get_repeat())
			{
				case PRESS:
					if (c.ready)
					{
						c.pressed = true;
						c.ready = false;
					}
					break;
				case REPEAT:
				case HOLD:
					c.pressed = true;
					break;
			}

			// don't continue bound keypresses
			return false;
		}
	}
	else if (event.type == sf::Event::KeyReleased)
	{
		switch (event.key.code)
		{
			case sf::Keyboard::Key::LAlt:
			case sf::Keyboard::Key::RAlt:
				for (auto pair : binds)
					if (commands[pair.second].get_repeat() == HOLD && (pair.first.alt || pair.first.code == sf::Keyboard::Key::LAlt || pair.first.code == sf::Keyboard::Key::RAlt))
						commands[pair.second].pressed = false;
				break;
			case sf::Keyboard::Key::LControl:
			case sf::Keyboard::Key::RControl:
				for (auto pair : binds)
					if (commands[pair.second].get_repeat() == HOLD && (pair.first.control || pair.first.code == sf::Keyboard::Key::LControl || pair.first.code == sf::Keyboard::Key::RControl))
						commands[pair.second].pressed = false;
				break;
			case sf::Keyboard::Key::LShift:
			case sf::Keyboard::Key::RShift:
				for (auto pair : binds)
					if (commands[pair.second].get_repeat() == HOLD && (pair.first.shift || pair.first.code == sf::Keyboard::Key::LShift || pair.first.code == sf::Keyboard::Key::RShift))
						commands[pair.second].pressed = false;
				break;
			case sf::Keyboard::Key::LSystem:
			case sf::Keyboard::Key::RSystem:
				for (auto pair : binds)
					if (commands[pair.second].get_repeat() == HOLD && (pair.first.system || pair.first.code == sf::Keyboard::Key::LSystem || pair.first.code == sf::Keyboard::Key::RSystem))
						commands[pair.second].pressed = false;
				break;
			default:
				break;
		}
		auto it = binds.find(event.key);
		if (it != binds.end())
		{
			Command& c = commands[it->second];
			switch (c.get_repeat())
			{
				case PRESS:
					c.ready = true;
					break;
				case REPEAT:
					break;
				case HOLD:
					c.pressed = false;
					break;
			}
		}
	}

	return true;
}
<|endoftext|>


<commit_before>#include "magic.h"

using namespace cv;

Point point1, point2; /* vertical points of the bounding box */
bool drag = false;
bool select_flag = false;
Rect rect; /* bounding box */
Mat img, roiImg; /* roiImg - the part of the image in the bounding box */

void mouseHandler(int event, int x, int y, int flags, void* param){
    if (event == CV_EVENT_LBUTTONDOWN && !drag){
        /* left button clicked. ROI selection begins */
        point1 = Point(x, y);
        drag = true;
    }

    if (event == CV_EVENT_MOUSEMOVE && drag){
        /* mouse dragged. ROI being selected */
        Mat img1 = img.clone();
        point2 = Point(x, y);
        rectangle(img1, point1, point2, CV_RGB(255, 0, 0), 3, 8, 0);
        imshow("image", img1);
    }

    if (event == CV_EVENT_LBUTTONUP && drag){
        point2 = Point(x, y);
        rect = Rect(point1.x,point1.y,x-point1.x,y-point1.y);
        drag = false;
        roiImg = img(rect);
    }

    if (event == CV_EVENT_LBUTTONUP){
       /* ROI selected */
        select_flag = true;
        drag = false;
    }
}

int main(int argc, char* argv[]){
  if(argc < 2){
    printf("usage: Magic <Video_Path> [output_dir] [skip_frames] [background]\n");
  }

  std::string output;
  if(argc >= 3) {
    output = argv[2];
  } else {
    output = ".";
  }

  int skip_frames = 0;
  if(argc >= 4) {
    skip_frames = std::atoi(argv[3]);
  }

  VideoCapture cap(argv[1]); // load the video
  if(!cap.isOpened())  // check if we succeeded
        return -1;

  // Write some info about File
  int frames = cap.get(CV_CAP_PROP_FRAME_COUNT);
  double fps = cap.get(CV_CAP_PROP_FPS);
  printf("Number of Frames: %d\n", frames);
  printf("FPS: %f\n", fps);

  // Contains the working image
  Mat dst, in, temp;

  if(argc >= 5) {
    in = imread(argv[4]);
  } else {
    cap >> in;
  }

  img = in.clone();
  imshow("image", img);
  int k;
  while(1){
    cvSetMouseCallback("image", mouseHandler, NULL);
    if (select_flag){
        imshow("ROI", roiImg);  //show the image bounded by the box
    }
    rectangle(img, rect, CV_RGB(255, 0, 0), 3, 8, 0);
    imshow("image", img);
    k = waitKey(10);
    // if(k != -1) {
    //   printf("Key pressed %d\n", k);
    // }
    if (k == 27){ //ESC
        break;
    }
  }

  waitKey(1);
  destroyAllWindows();
  waitKey(1);

  if(!select_flag){
    rect = Rect(0,0,img.cols, img.rows);
  }

  // Background
  // TODO: support loading from file
  temp = in(rect);
  Mat background;
  cvtColor(temp, background, CV_RGB2GRAY);

  //Set image parameter
  vector<int> imageout_params;
  imwrite(output + "/bg.tiff", background, imageout_params);

  namedWindow("live", CV_WINDOW_AUTOSIZE );

  std::vector<Point2i> points;
  Point2f center;
  float radius;

  std::ofstream fs (output + "/positions.csv", std::ofstream::out);
  fs << "Frame,Time,Radius,x,y\n";

  for(int i = 0; i <= frames-1;i++){
    cap >> in;
    temp = in(rect);
    cvtColor(temp, dst, CV_RGB2GRAY, 0);
    absdiff(dst, background, temp);
    threshold(temp, dst, 30, 255, THRESH_BINARY);
    imshow("live", dst);

    points.clear();
    findNonZero(dst, points);
    minEnclosingCircle(points, center, radius);

    fs << i <<","<< i/fps <<","<< radius <<","<< center.x <<","<< center.y << "\n";
    std::cout << "\r" << i << "/" << frames;
    // imwrite(output + "/test-"+ std::to_string(i)+".tiff", dst, imageout_params);
  }

  fs << std::endl;
  fs.close();
}<commit_msg>skip the first frames<commit_after>#include "magic.h"

using namespace cv;

Point point1, point2; /* vertical points of the bounding box */
bool drag = false;
bool select_flag = false;
Rect rect; /* bounding box */
Mat img, roiImg; /* roiImg - the part of the image in the bounding box */

void mouseHandler(int event, int x, int y, int flags, void* param){
    if (event == CV_EVENT_LBUTTONDOWN && !drag){
        /* left button clicked. ROI selection begins */
        point1 = Point(x, y);
        drag = true;
    }

    if (event == CV_EVENT_MOUSEMOVE && drag){
        /* mouse dragged. ROI being selected */
        Mat img1 = img.clone();
        point2 = Point(x, y);
        rectangle(img1, point1, point2, CV_RGB(255, 0, 0), 3, 8, 0);
        imshow("image", img1);
    }

    if (event == CV_EVENT_LBUTTONUP && drag){
        point2 = Point(x, y);
        rect = Rect(point1.x,point1.y,x-point1.x,y-point1.y);
        drag = false;
        roiImg = img(rect);
    }

    if (event == CV_EVENT_LBUTTONUP){
       /* ROI selected */
        select_flag = true;
        drag = false;
    }
}

int main(int argc, char* argv[]){
  if(argc < 2){
    printf("usage: Magic <Video_Path> [output_dir] [skip_frames] [background]\n");
  }

  std::string output;
  if(argc >= 3) {
    output = argv[2];
  } else {
    output = ".";
  }

  int skip_frames = 0;
  if(argc >= 4) {
    skip_frames = std::atoi(argv[3]);
  }

  VideoCapture cap(argv[1]); // load the video
  if(!cap.isOpened())  // check if we succeeded
        return -1;

  // Write some info about File
  int frames = cap.get(CV_CAP_PROP_FRAME_COUNT);
  double fps = cap.get(CV_CAP_PROP_FPS);
  printf("Number of Frames: %d\n", frames);
  printf("FPS: %f\n", fps);

  // Contains the working image
  Mat dst, in, temp;

  if(argc >= 5) {
    in = imread(argv[4]);
  } else {
    cap >> in;
  }

  img = in.clone();
  imshow("image", img);
  int k;
  while(1){
    cvSetMouseCallback("image", mouseHandler, NULL);
    if (select_flag){
        imshow("ROI", roiImg);  //show the image bounded by the box
    }
    rectangle(img, rect, CV_RGB(255, 0, 0), 3, 8, 0);
    imshow("image", img);
    k = waitKey(10);
    // if(k != -1) {
    //   printf("Key pressed %d\n", k);
    // }
    if (k == 27){ //ESC
        break;
    }
  }

  waitKey(1);
  destroyAllWindows();
  waitKey(1);

  if(!select_flag){
    rect = Rect(0,0,img.cols, img.rows);
  }

  // Background
  // TODO: support loading from file
  temp = in(rect);
  Mat background;
  cvtColor(temp, background, CV_RGB2GRAY);

  //Set image parameter
  vector<int> imageout_params;
  imwrite(output + "/bg.tiff", background, imageout_params);

  namedWindow("live", CV_WINDOW_AUTOSIZE );

  std::vector<Point2i> points;
  Point2f center;
  float radius;

  std::ofstream fs (output + "/positions.csv", std::ofstream::out);
  fs << "Frame,Time,Radius,x,y\n";

  for(int i = 0; i <= frames-1;i++){
    cap >> in;
    if(i > skip_frames) {
    temp = in(rect);
    cvtColor(temp, dst, CV_RGB2GRAY, 0);
    absdiff(dst, background, temp);
    threshold(temp, dst, 30, 255, THRESH_BINARY);
    imshow("live", dst);

    points.clear();
    findNonZero(dst, points);
    minEnclosingCircle(points, center, radius);

    fs << i <<","<< i/fps <<","<< radius <<","<< center.x <<","<< center.y << "\n";
    std::cout << "\r" << i << "/" << frames;
    // imwrite(output + "/test-"+ std::to_string(i)+".tiff", dst, imageout_params);
    }
  }

  fs << std::endl;
  fs.close();
}<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: tp_Wizard_TitlesAndObjects.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: kz $ $Date: 2008-03-06 19:18:01 $
 *
 *  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 "tp_Wizard_TitlesAndObjects.hxx"
#include "tp_Wizard_TitlesAndObjects.hrc"
#include "Strings.hrc"
#include "res_Titles.hxx"
#include "res_LegendPosition.hxx"
#include "ResId.hxx"
#include "HelpIds.hrc"
#include "macros.hxx"
#include "ChartModelHelper.hxx"
#include "AxisHelper.hxx"
#include "LegendHelper.hxx"
#include "NoWarningThisInCTOR.hxx"
#include "ControllerLockGuard.hxx"

//.............................................................................
namespace chart
{
//.............................................................................
using namespace ::com::sun::star;
using namespace ::com::sun::star::chart2;

TitlesAndObjectsTabPage::TitlesAndObjectsTabPage( svt::OWizardMachine* pParent
        , const uno::Reference< XChartDocument >& xChartModel
        , const uno::Reference< uno::XComponentContext >& xContext )
        : OWizardPage( pParent, SchResId(TP_WIZARD_TITLEANDOBJECTS) )
        , m_aFT_TitleDescription( this, SchResId( FT_TITLEDESCRIPTION ) )
        , m_aFL_Vertical( this, SchResId( FL_VERTICAL ) )
        , m_apTitleResources( new TitleResources(this,false) )
        , m_apLegendPositionResources( new LegendPositionResources(this,xContext) )
        , m_aFL_Grids( this, SchResId( FL_GRIDS ) )
        , m_aCB_Grid_X( this, SchResId( CB_X_SECONDARY ) )
        , m_aCB_Grid_Y( this, SchResId( CB_Y_SECONDARY ) )
        , m_aCB_Grid_Z( this, SchResId( CB_Z_SECONDARY ) )
        , m_xChartModel( xChartModel )
        , m_xCC( xContext )
        , m_bCommitToModel( true )
        , m_aTimerTriggeredControllerLock( uno::Reference< frame::XModel >( m_xChartModel, uno::UNO_QUERY ) )
{
    FreeResource();

    this->SetText( String( SchResId( STR_PAGE_CHART_ELEMENTS ) ) );

    Font aFont( m_aFT_TitleDescription.GetControlFont() );
    aFont.SetWeight( WEIGHT_BOLD );
    m_aFT_TitleDescription.SetControlFont( aFont );

    m_aCB_Grid_X.SetHelpId( HID_SCH_CB_XGRID );
    m_aCB_Grid_Y.SetHelpId( HID_SCH_CB_YGRID );
    m_aCB_Grid_Z.SetHelpId( HID_SCH_CB_ZGRID );

    m_apTitleResources->SetUpdateDataHdl( LINK( this, TitlesAndObjectsTabPage, ChangeHdl ));
    m_apLegendPositionResources->SetChangeHdl( LINK( this, TitlesAndObjectsTabPage, ChangeHdl ));

    m_aCB_Grid_X.SetToggleHdl( LINK( this, TitlesAndObjectsTabPage, ChangeHdl ));
    m_aCB_Grid_Y.SetToggleHdl( LINK( this, TitlesAndObjectsTabPage, ChangeHdl ));
    m_aCB_Grid_Z.SetToggleHdl( LINK( this, TitlesAndObjectsTabPage, ChangeHdl ));
}

TitlesAndObjectsTabPage::~TitlesAndObjectsTabPage()
{
}

void TitlesAndObjectsTabPage::initializePage()
{
    m_bCommitToModel = false;

    //init titles
    {
        TitleDialogData aTitleInput;
        aTitleInput.readFromModel( uno::Reference< frame::XModel >( m_xChartModel, uno::UNO_QUERY) );
        m_apTitleResources->writeToResources( aTitleInput );
    }

    //init legend
    {
        m_apLegendPositionResources->writeToResources( uno::Reference< frame::XModel >( m_xChartModel, uno::UNO_QUERY) );
    }

    //init grid checkboxes
    {
        uno::Reference< XDiagram > xDiagram = ChartModelHelper::findDiagram( m_xChartModel );
        uno::Sequence< sal_Bool > aPossibilityList;
        uno::Sequence< sal_Bool > aExistenceList;
        AxisHelper::getAxisOrGridPossibilities( aPossibilityList, xDiagram, sal_False );
        AxisHelper::getAxisOrGridExcistence( aExistenceList, xDiagram, sal_False );
        m_aCB_Grid_X.Enable( aPossibilityList[0] );
        m_aCB_Grid_Y.Enable( aPossibilityList[1] );
        m_aCB_Grid_Z.Enable( aPossibilityList[2] );
        m_aCB_Grid_X.Check( aExistenceList[0] );
        m_aCB_Grid_Y.Check( aExistenceList[1] );
        m_aCB_Grid_Z.Check( aExistenceList[2] );
    }

    m_bCommitToModel = true;
}

sal_Bool TitlesAndObjectsTabPage::commitPage( CommitPageReason /*eReason*/ )
{
    if( m_apTitleResources->IsModified() ) //titles may have changed in the meanwhile
        commitToModel();
    return sal_True;//return false if this page should not be left
}

void TitlesAndObjectsTabPage::commitToModel()
{
    bool bChanged = false;

    m_aTimerTriggeredControllerLock.startTimer();
    uno::Reference< frame::XModel >  xModel( m_xChartModel, uno::UNO_QUERY);

    ControllerLockGuard aLockedControllers( xModel );

    //commit title changes to model
    {
        TitleDialogData aTitleOutput;
        m_apTitleResources->readFromResources( aTitleOutput );
        bChanged = bChanged || aTitleOutput.writeDifferenceToModel( xModel, m_xCC );
        m_apTitleResources->ClearModifyFlag();
    }

    //commit legend changes to model
    {
        bChanged = true;
        m_apLegendPositionResources->writeToModel( xModel );
    }

    //commit grid changes to model
    {
        uno::Reference< XDiagram > xDiagram = ChartModelHelper::findDiagram( xModel );
        uno::Sequence< sal_Bool > aOldExistenceList;
        AxisHelper::getAxisOrGridExcistence( aOldExistenceList, xDiagram, sal_False );
        uno::Sequence< sal_Bool > aNewExistenceList(aOldExistenceList);
        aNewExistenceList[0]=m_aCB_Grid_X.IsChecked();
        aNewExistenceList[1]=m_aCB_Grid_Y.IsChecked();
        aNewExistenceList[2]=m_aCB_Grid_Z.IsChecked();
        AxisHelper::changeVisibilityOfGrids( xDiagram
                , aOldExistenceList, aNewExistenceList, m_xCC );
    }
}

IMPL_LINK( TitlesAndObjectsTabPage, ChangeHdl, void *, EMPTYARG )
{
    if( m_bCommitToModel )
        commitToModel();
    return 0;
}

bool TitlesAndObjectsTabPage::canAdvance() const
{
    return false;
}

//.............................................................................
} //namespace chart
//.............................................................................
<commit_msg>INTEGRATION: CWS changefileheader (1.5.20); FILE MERGED 2008/03/28 16:43:33 rt 1.5.20.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: tp_Wizard_TitlesAndObjects.cxx,v $
 * $Revision: 1.6 $
 *
 * 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 "tp_Wizard_TitlesAndObjects.hxx"
#include "tp_Wizard_TitlesAndObjects.hrc"
#include "Strings.hrc"
#include "res_Titles.hxx"
#include "res_LegendPosition.hxx"
#include "ResId.hxx"
#include "HelpIds.hrc"
#include "macros.hxx"
#include "ChartModelHelper.hxx"
#include "AxisHelper.hxx"
#include "LegendHelper.hxx"
#include "NoWarningThisInCTOR.hxx"
#include "ControllerLockGuard.hxx"

//.............................................................................
namespace chart
{
//.............................................................................
using namespace ::com::sun::star;
using namespace ::com::sun::star::chart2;

TitlesAndObjectsTabPage::TitlesAndObjectsTabPage( svt::OWizardMachine* pParent
        , const uno::Reference< XChartDocument >& xChartModel
        , const uno::Reference< uno::XComponentContext >& xContext )
        : OWizardPage( pParent, SchResId(TP_WIZARD_TITLEANDOBJECTS) )
        , m_aFT_TitleDescription( this, SchResId( FT_TITLEDESCRIPTION ) )
        , m_aFL_Vertical( this, SchResId( FL_VERTICAL ) )
        , m_apTitleResources( new TitleResources(this,false) )
        , m_apLegendPositionResources( new LegendPositionResources(this,xContext) )
        , m_aFL_Grids( this, SchResId( FL_GRIDS ) )
        , m_aCB_Grid_X( this, SchResId( CB_X_SECONDARY ) )
        , m_aCB_Grid_Y( this, SchResId( CB_Y_SECONDARY ) )
        , m_aCB_Grid_Z( this, SchResId( CB_Z_SECONDARY ) )
        , m_xChartModel( xChartModel )
        , m_xCC( xContext )
        , m_bCommitToModel( true )
        , m_aTimerTriggeredControllerLock( uno::Reference< frame::XModel >( m_xChartModel, uno::UNO_QUERY ) )
{
    FreeResource();

    this->SetText( String( SchResId( STR_PAGE_CHART_ELEMENTS ) ) );

    Font aFont( m_aFT_TitleDescription.GetControlFont() );
    aFont.SetWeight( WEIGHT_BOLD );
    m_aFT_TitleDescription.SetControlFont( aFont );

    m_aCB_Grid_X.SetHelpId( HID_SCH_CB_XGRID );
    m_aCB_Grid_Y.SetHelpId( HID_SCH_CB_YGRID );
    m_aCB_Grid_Z.SetHelpId( HID_SCH_CB_ZGRID );

    m_apTitleResources->SetUpdateDataHdl( LINK( this, TitlesAndObjectsTabPage, ChangeHdl ));
    m_apLegendPositionResources->SetChangeHdl( LINK( this, TitlesAndObjectsTabPage, ChangeHdl ));

    m_aCB_Grid_X.SetToggleHdl( LINK( this, TitlesAndObjectsTabPage, ChangeHdl ));
    m_aCB_Grid_Y.SetToggleHdl( LINK( this, TitlesAndObjectsTabPage, ChangeHdl ));
    m_aCB_Grid_Z.SetToggleHdl( LINK( this, TitlesAndObjectsTabPage, ChangeHdl ));
}

TitlesAndObjectsTabPage::~TitlesAndObjectsTabPage()
{
}

void TitlesAndObjectsTabPage::initializePage()
{
    m_bCommitToModel = false;

    //init titles
    {
        TitleDialogData aTitleInput;
        aTitleInput.readFromModel( uno::Reference< frame::XModel >( m_xChartModel, uno::UNO_QUERY) );
        m_apTitleResources->writeToResources( aTitleInput );
    }

    //init legend
    {
        m_apLegendPositionResources->writeToResources( uno::Reference< frame::XModel >( m_xChartModel, uno::UNO_QUERY) );
    }

    //init grid checkboxes
    {
        uno::Reference< XDiagram > xDiagram = ChartModelHelper::findDiagram( m_xChartModel );
        uno::Sequence< sal_Bool > aPossibilityList;
        uno::Sequence< sal_Bool > aExistenceList;
        AxisHelper::getAxisOrGridPossibilities( aPossibilityList, xDiagram, sal_False );
        AxisHelper::getAxisOrGridExcistence( aExistenceList, xDiagram, sal_False );
        m_aCB_Grid_X.Enable( aPossibilityList[0] );
        m_aCB_Grid_Y.Enable( aPossibilityList[1] );
        m_aCB_Grid_Z.Enable( aPossibilityList[2] );
        m_aCB_Grid_X.Check( aExistenceList[0] );
        m_aCB_Grid_Y.Check( aExistenceList[1] );
        m_aCB_Grid_Z.Check( aExistenceList[2] );
    }

    m_bCommitToModel = true;
}

sal_Bool TitlesAndObjectsTabPage::commitPage( CommitPageReason /*eReason*/ )
{
    if( m_apTitleResources->IsModified() ) //titles may have changed in the meanwhile
        commitToModel();
    return sal_True;//return false if this page should not be left
}

void TitlesAndObjectsTabPage::commitToModel()
{
    bool bChanged = false;

    m_aTimerTriggeredControllerLock.startTimer();
    uno::Reference< frame::XModel >  xModel( m_xChartModel, uno::UNO_QUERY);

    ControllerLockGuard aLockedControllers( xModel );

    //commit title changes to model
    {
        TitleDialogData aTitleOutput;
        m_apTitleResources->readFromResources( aTitleOutput );
        bChanged = bChanged || aTitleOutput.writeDifferenceToModel( xModel, m_xCC );
        m_apTitleResources->ClearModifyFlag();
    }

    //commit legend changes to model
    {
        bChanged = true;
        m_apLegendPositionResources->writeToModel( xModel );
    }

    //commit grid changes to model
    {
        uno::Reference< XDiagram > xDiagram = ChartModelHelper::findDiagram( xModel );
        uno::Sequence< sal_Bool > aOldExistenceList;
        AxisHelper::getAxisOrGridExcistence( aOldExistenceList, xDiagram, sal_False );
        uno::Sequence< sal_Bool > aNewExistenceList(aOldExistenceList);
        aNewExistenceList[0]=m_aCB_Grid_X.IsChecked();
        aNewExistenceList[1]=m_aCB_Grid_Y.IsChecked();
        aNewExistenceList[2]=m_aCB_Grid_Z.IsChecked();
        AxisHelper::changeVisibilityOfGrids( xDiagram
                , aOldExistenceList, aNewExistenceList, m_xCC );
    }
}

IMPL_LINK( TitlesAndObjectsTabPage, ChangeHdl, void *, EMPTYARG )
{
    if( m_bCommitToModel )
        commitToModel();
    return 0;
}

bool TitlesAndObjectsTabPage::canAdvance() const
{
    return false;
}

//.............................................................................
} //namespace chart
//.............................................................................
<|endoftext|>


<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/autocomplete/keyword_extensions_delegate_impl.h"

#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/extensions/api/omnibox/omnibox_api.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_util.h"
#include "chrome/browser/profiles/profile.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_source.h"
#include "extensions/browser/extension_system.h"
#include "extensions/browser/notification_types.h"

namespace omnibox_api = extensions::api::omnibox;

int KeywordExtensionsDelegateImpl::global_input_uid_ = 0;

KeywordExtensionsDelegateImpl::KeywordExtensionsDelegateImpl(
    Profile* profile,
    KeywordProvider* provider)
    : KeywordExtensionsDelegate(provider),
      profile_(profile),
      provider_(provider) {
  DCHECK(provider_);

  current_input_id_ = 0;
  // Extension suggestions always come from the original profile, since that's
  // where extensions run. We use the input ID to distinguish whether the
  // suggestions are meant for us.
  registrar_.Add(this,
                 extensions::NOTIFICATION_EXTENSION_OMNIBOX_SUGGESTIONS_READY,
                 content::Source<Profile>(profile_->GetOriginalProfile()));
  registrar_.Add(
      this,
      extensions::NOTIFICATION_EXTENSION_OMNIBOX_DEFAULT_SUGGESTION_CHANGED,
      content::Source<Profile>(profile_->GetOriginalProfile()));
  registrar_.Add(this,
                 extensions::NOTIFICATION_EXTENSION_OMNIBOX_INPUT_ENTERED,
                 content::Source<Profile>(profile_));
}

KeywordExtensionsDelegateImpl::~KeywordExtensionsDelegateImpl() {
}

void  KeywordExtensionsDelegateImpl::IncrementInputId() {
  current_input_id_ = ++global_input_uid_;
}

bool KeywordExtensionsDelegateImpl::IsEnabledExtension(
    const std::string& extension_id) {
  ExtensionService* extension_service =
      extensions::ExtensionSystem::Get(profile_)->extension_service();
  const extensions::Extension* extension =
      extension_service->GetExtensionById(extension_id, false);
  return extension &&
      (!profile_->IsOffTheRecord() ||
       !extensions::util::IsIncognitoEnabled(extension_id, profile_));
}

bool KeywordExtensionsDelegateImpl::Start(
    const AutocompleteInput& input,
    bool minimal_changes,
    const TemplateURL* template_url,
    const base::string16& remaining_input) {
  DCHECK(template_url);

  if (input.want_asynchronous_matches()) {
    std::string extension_id = template_url->GetExtensionId();
    if (extension_id != current_keyword_extension_id_)
      MaybeEndExtensionKeywordMode();
    if (current_keyword_extension_id_.empty())
      EnterExtensionKeywordMode(extension_id);
  }

  extensions::ApplyDefaultSuggestionForExtensionKeyword(
      profile_, template_url, remaining_input, &matches()->front());

  if (minimal_changes) {
    // If the input hasn't significantly changed, we can just use the
    // suggestions from last time. We need to readjust the relevance to
    // ensure it is less than the main match's relevance.
    for (size_t i = 0; i < extension_suggest_matches_.size(); ++i) {
      matches()->push_back(extension_suggest_matches_[i]);
      matches()->back().relevance = matches()->front().relevance - (i + 1);
    }
  } else if (input.want_asynchronous_matches()) {
    extension_suggest_last_input_ = input;
    extension_suggest_matches_.clear();

    // We only have to wait for suggest results if there are actually
    // extensions listening for input changes.
    if (extensions::ExtensionOmniboxEventRouter::OnInputChanged(
            profile_, template_url->GetExtensionId(),
            base::UTF16ToUTF8(remaining_input), current_input_id_))
      set_done(false);
  }
  return input.want_asynchronous_matches();
}

void KeywordExtensionsDelegateImpl::EnterExtensionKeywordMode(
    const std::string& extension_id) {
  DCHECK(current_keyword_extension_id_.empty());
  current_keyword_extension_id_ = extension_id;

  extensions::ExtensionOmniboxEventRouter::OnInputStarted(
      profile_, current_keyword_extension_id_);
}

void KeywordExtensionsDelegateImpl::MaybeEndExtensionKeywordMode() {
  if (!current_keyword_extension_id_.empty()) {
    extensions::ExtensionOmniboxEventRouter::OnInputCancelled(
        profile_, current_keyword_extension_id_);
    current_keyword_extension_id_.clear();
  }
}

void KeywordExtensionsDelegateImpl::Observe(
    int type,
    const content::NotificationSource& source,
    const content::NotificationDetails& details) {
  TemplateURLService* model = provider_->GetTemplateURLService();
  const AutocompleteInput& input = extension_suggest_last_input_;

  switch (type) {
    case extensions::NOTIFICATION_EXTENSION_OMNIBOX_INPUT_ENTERED:
      // Input has been accepted, so we're done with this input session. Ensure
      // we don't send the OnInputCancelled event, or handle any more stray
      // suggestions_ready events.
      current_keyword_extension_id_.clear();
      current_input_id_ = 0;
      return;

    case extensions::NOTIFICATION_EXTENSION_OMNIBOX_DEFAULT_SUGGESTION_CHANGED
        : {
      // It's possible to change the default suggestion while not in an editing
      // session.
      base::string16 keyword, remaining_input;
      if (matches()->empty() || current_keyword_extension_id_.empty() ||
          !KeywordProvider::ExtractKeywordFromInput(
              input, &keyword, &remaining_input))
        return;

      const TemplateURL* template_url(
          model->GetTemplateURLForKeyword(keyword));
      extensions::ApplyDefaultSuggestionForExtensionKeyword(
          profile_, template_url, remaining_input, &matches()->front());
      OnProviderUpdate(true);
      return;
    }

    case extensions::NOTIFICATION_EXTENSION_OMNIBOX_SUGGESTIONS_READY: {
      const omnibox_api::SendSuggestions::Params& suggestions =
          *content::Details<
              omnibox_api::SendSuggestions::Params>(details).ptr();
      if (suggestions.request_id != current_input_id_)
        return;  // This is an old result. Just ignore.

      base::string16 keyword, remaining_input;
      bool result = KeywordProvider::ExtractKeywordFromInput(
          input, &keyword, &remaining_input);
      DCHECK(result);
      const TemplateURL* template_url =
          model->GetTemplateURLForKeyword(keyword);

      // TODO(mpcomplete): consider clamping the number of suggestions to
      // AutocompleteProvider::kMaxMatches.
      for (size_t i = 0; i < suggestions.suggest_results.size(); ++i) {
        const omnibox_api::SuggestResult& suggestion =
            *suggestions.suggest_results[i];
        // We want to order these suggestions in descending order, so start with
        // the relevance of the first result (added synchronously in Start()),
        // and subtract 1 for each subsequent suggestion from the extension.
        // We recompute the first match's relevance; we know that |complete|
        // is true, because we wouldn't get results from the extension unless
        // the full keyword had been typed.
        int first_relevance = KeywordProvider::CalculateRelevance(
            input.type(), true, true, input.prefer_keyword(),
            input.allow_exact_keyword_match());
        // Because these matches are async, we should never let them become the
        // default match, lest we introduce race conditions in the omnibox user
        // interaction.
        extension_suggest_matches_.push_back(
            provider_->CreateAutocompleteMatch(
                template_url, input, keyword.length(),
                base::UTF8ToUTF16(suggestion.content), false,
                first_relevance - (i + 1)));

        AutocompleteMatch* match = &extension_suggest_matches_.back();
        match->contents.assign(base::UTF8ToUTF16(suggestion.description));
        match->contents_class =
            extensions::StyleTypesToACMatchClassifications(suggestion);
      }

      set_done(true);
      matches()->insert(matches()->end(),
                        extension_suggest_matches_.begin(),
                        extension_suggest_matches_.end());
      OnProviderUpdate(!extension_suggest_matches_.empty());
      return;
    }

    default:
      NOTREACHED();
      return;
  }
}

void KeywordExtensionsDelegateImpl::OnProviderUpdate(bool updated_matches) {
  provider_->listener_->OnProviderUpdate(updated_matches);
}
<commit_msg>Autocomplete: Fix a typo that flipped the extension keyword provider check for enabling in incognito mode.<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/autocomplete/keyword_extensions_delegate_impl.h"

#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/extensions/api/omnibox/omnibox_api.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_util.h"
#include "chrome/browser/profiles/profile.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_source.h"
#include "extensions/browser/extension_system.h"
#include "extensions/browser/notification_types.h"

namespace omnibox_api = extensions::api::omnibox;

int KeywordExtensionsDelegateImpl::global_input_uid_ = 0;

KeywordExtensionsDelegateImpl::KeywordExtensionsDelegateImpl(
    Profile* profile,
    KeywordProvider* provider)
    : KeywordExtensionsDelegate(provider),
      profile_(profile),
      provider_(provider) {
  DCHECK(provider_);

  current_input_id_ = 0;
  // Extension suggestions always come from the original profile, since that's
  // where extensions run. We use the input ID to distinguish whether the
  // suggestions are meant for us.
  registrar_.Add(this,
                 extensions::NOTIFICATION_EXTENSION_OMNIBOX_SUGGESTIONS_READY,
                 content::Source<Profile>(profile_->GetOriginalProfile()));
  registrar_.Add(
      this,
      extensions::NOTIFICATION_EXTENSION_OMNIBOX_DEFAULT_SUGGESTION_CHANGED,
      content::Source<Profile>(profile_->GetOriginalProfile()));
  registrar_.Add(this,
                 extensions::NOTIFICATION_EXTENSION_OMNIBOX_INPUT_ENTERED,
                 content::Source<Profile>(profile_));
}

KeywordExtensionsDelegateImpl::~KeywordExtensionsDelegateImpl() {
}

void  KeywordExtensionsDelegateImpl::IncrementInputId() {
  current_input_id_ = ++global_input_uid_;
}

bool KeywordExtensionsDelegateImpl::IsEnabledExtension(
    const std::string& extension_id) {
  ExtensionService* extension_service =
      extensions::ExtensionSystem::Get(profile_)->extension_service();
  const extensions::Extension* extension =
      extension_service->GetExtensionById(extension_id, false);
  return extension &&
      (!profile_->IsOffTheRecord() ||
       extensions::util::IsIncognitoEnabled(extension_id, profile_));
}

bool KeywordExtensionsDelegateImpl::Start(
    const AutocompleteInput& input,
    bool minimal_changes,
    const TemplateURL* template_url,
    const base::string16& remaining_input) {
  DCHECK(template_url);

  if (input.want_asynchronous_matches()) {
    std::string extension_id = template_url->GetExtensionId();
    if (extension_id != current_keyword_extension_id_)
      MaybeEndExtensionKeywordMode();
    if (current_keyword_extension_id_.empty())
      EnterExtensionKeywordMode(extension_id);
  }

  extensions::ApplyDefaultSuggestionForExtensionKeyword(
      profile_, template_url, remaining_input, &matches()->front());

  if (minimal_changes) {
    // If the input hasn't significantly changed, we can just use the
    // suggestions from last time. We need to readjust the relevance to
    // ensure it is less than the main match's relevance.
    for (size_t i = 0; i < extension_suggest_matches_.size(); ++i) {
      matches()->push_back(extension_suggest_matches_[i]);
      matches()->back().relevance = matches()->front().relevance - (i + 1);
    }
  } else if (input.want_asynchronous_matches()) {
    extension_suggest_last_input_ = input;
    extension_suggest_matches_.clear();

    // We only have to wait for suggest results if there are actually
    // extensions listening for input changes.
    if (extensions::ExtensionOmniboxEventRouter::OnInputChanged(
            profile_, template_url->GetExtensionId(),
            base::UTF16ToUTF8(remaining_input), current_input_id_))
      set_done(false);
  }
  return input.want_asynchronous_matches();
}

void KeywordExtensionsDelegateImpl::EnterExtensionKeywordMode(
    const std::string& extension_id) {
  DCHECK(current_keyword_extension_id_.empty());
  current_keyword_extension_id_ = extension_id;

  extensions::ExtensionOmniboxEventRouter::OnInputStarted(
      profile_, current_keyword_extension_id_);
}

void KeywordExtensionsDelegateImpl::MaybeEndExtensionKeywordMode() {
  if (!current_keyword_extension_id_.empty()) {
    extensions::ExtensionOmniboxEventRouter::OnInputCancelled(
        profile_, current_keyword_extension_id_);
    current_keyword_extension_id_.clear();
  }
}

void KeywordExtensionsDelegateImpl::Observe(
    int type,
    const content::NotificationSource& source,
    const content::NotificationDetails& details) {
  TemplateURLService* model = provider_->GetTemplateURLService();
  const AutocompleteInput& input = extension_suggest_last_input_;

  switch (type) {
    case extensions::NOTIFICATION_EXTENSION_OMNIBOX_INPUT_ENTERED:
      // Input has been accepted, so we're done with this input session. Ensure
      // we don't send the OnInputCancelled event, or handle any more stray
      // suggestions_ready events.
      current_keyword_extension_id_.clear();
      current_input_id_ = 0;
      return;

    case extensions::NOTIFICATION_EXTENSION_OMNIBOX_DEFAULT_SUGGESTION_CHANGED
        : {
      // It's possible to change the default suggestion while not in an editing
      // session.
      base::string16 keyword, remaining_input;
      if (matches()->empty() || current_keyword_extension_id_.empty() ||
          !KeywordProvider::ExtractKeywordFromInput(
              input, &keyword, &remaining_input))
        return;

      const TemplateURL* template_url(
          model->GetTemplateURLForKeyword(keyword));
      extensions::ApplyDefaultSuggestionForExtensionKeyword(
          profile_, template_url, remaining_input, &matches()->front());
      OnProviderUpdate(true);
      return;
    }

    case extensions::NOTIFICATION_EXTENSION_OMNIBOX_SUGGESTIONS_READY: {
      const omnibox_api::SendSuggestions::Params& suggestions =
          *content::Details<
              omnibox_api::SendSuggestions::Params>(details).ptr();
      if (suggestions.request_id != current_input_id_)
        return;  // This is an old result. Just ignore.

      base::string16 keyword, remaining_input;
      bool result = KeywordProvider::ExtractKeywordFromInput(
          input, &keyword, &remaining_input);
      DCHECK(result);
      const TemplateURL* template_url =
          model->GetTemplateURLForKeyword(keyword);

      // TODO(mpcomplete): consider clamping the number of suggestions to
      // AutocompleteProvider::kMaxMatches.
      for (size_t i = 0; i < suggestions.suggest_results.size(); ++i) {
        const omnibox_api::SuggestResult& suggestion =
            *suggestions.suggest_results[i];
        // We want to order these suggestions in descending order, so start with
        // the relevance of the first result (added synchronously in Start()),
        // and subtract 1 for each subsequent suggestion from the extension.
        // We recompute the first match's relevance; we know that |complete|
        // is true, because we wouldn't get results from the extension unless
        // the full keyword had been typed.
        int first_relevance = KeywordProvider::CalculateRelevance(
            input.type(), true, true, input.prefer_keyword(),
            input.allow_exact_keyword_match());
        // Because these matches are async, we should never let them become the
        // default match, lest we introduce race conditions in the omnibox user
        // interaction.
        extension_suggest_matches_.push_back(
            provider_->CreateAutocompleteMatch(
                template_url, input, keyword.length(),
                base::UTF8ToUTF16(suggestion.content), false,
                first_relevance - (i + 1)));

        AutocompleteMatch* match = &extension_suggest_matches_.back();
        match->contents.assign(base::UTF8ToUTF16(suggestion.description));
        match->contents_class =
            extensions::StyleTypesToACMatchClassifications(suggestion);
      }

      set_done(true);
      matches()->insert(matches()->end(),
                        extension_suggest_matches_.begin(),
                        extension_suggest_matches_.end());
      OnProviderUpdate(!extension_suggest_matches_.empty());
      return;
    }

    default:
      NOTREACHED();
      return;
  }
}

void KeywordExtensionsDelegateImpl::OnProviderUpdate(bool updated_matches) {
  provider_->listener_->OnProviderUpdate(updated_matches);
}
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id: raster_datasource.cc 44 2005-04-22 18:53:54Z pavlenko $

// boost
#include <boost/lexical_cast.hpp>
#include <boost/filesystem/operations.hpp>

// mapnik
#include <mapnik/image_reader.hpp>

#include "raster_featureset.hpp"
#include "raster_info.hpp"
#include "raster_datasource.hpp"

using mapnik::datasource;
using mapnik::parameters;
using mapnik::image_reader;

DATASOURCE_PLUGIN(raster_datasource)

using boost::lexical_cast;
using boost::bad_lexical_cast;
using mapnik::layer_descriptor;
using mapnik::featureset_ptr;
using mapnik::query;
using mapnik::coord2d;
using mapnik::datasource_exception;

raster_datasource::raster_datasource(const parameters& params, bool bind)
    : datasource(params),
      desc_(*params.get<std::string>("type"),"utf-8"),
      extent_initialized_(false)
{
#ifdef MAPNIK_DEBUG
    std::clog << "Raster Plugin: Initializing..." << std::endl;
#endif

    boost::optional<std::string> file = params.get<std::string>("file");
    if (! file) throw datasource_exception("Raster Plugin: missing <file> parameter ");

    boost::optional<std::string> base = params.get<std::string>("base");
    if (base)
       filename_ = *base + "/" + *file;
    else
       filename_ = *file;

    format_=*params_.get<std::string>("format","tiff");

    boost::optional<double> lox = params_.get<double>("lox");
    boost::optional<double> loy = params_.get<double>("loy");
    boost::optional<double> hix = params_.get<double>("hix");
    boost::optional<double> hiy = params_.get<double>("hiy");
    boost::optional<std::string> ext = params_.get<std::string>("extent");

    if (lox && loy && hix && hiy)
    {
        extent_.init(*lox, *loy, *hix, *hiy);
        extent_initialized_ = true;
    }
    else if (ext)
    {
        extent_initialized_ = extent_.from_string(*ext);
    }

    if (! extent_initialized_)
        throw datasource_exception("Raster Plugin: valid <lox> <loy> <hix> <hiy>, or <extent> are required");

    if (bind)
    {
        this->bind();
    }
}

void raster_datasource::bind() const
{
    if (is_bound_) return;

    if (! boost::filesystem::exists(filename_))
        throw datasource_exception("Raster Plugin: " + filename_ + " does not exist");

    try
    {
        std::auto_ptr<image_reader> reader(mapnik::get_image_reader(filename_, format_));
        if (reader.get())
        {
            width_ = reader->width();
            height_ = reader->height();

#ifdef MAPNIK_DEBUG
            std::clog << "Raster Plugin: RASTER SIZE(" << width_ << "," << height_ << ")" << std::endl;
#endif
        }
    }
    catch (mapnik::image_reader_exception const& ex)
    {
        std::cerr << "Raster Plugin: image reader exception caught:" << ex.what() << std::endl;
        throw;
    }
    catch (...)
    {
        std::cerr << "Raster Plugin: exception caught" << std::endl;
        throw;
    }

    is_bound_ = true;
}

raster_datasource::~raster_datasource()
{
}

int raster_datasource::type() const
{
    return datasource::Raster;
}

std::string raster_datasource::name()
{
    return "raster";
}

mapnik::box2d<double> raster_datasource::envelope() const
{
    return extent_;
}

layer_descriptor raster_datasource::get_descriptor() const
{
    return desc_;
}

featureset_ptr raster_datasource::features(query const& q) const
{
    if (! is_bound_) bind();

    mapnik::CoordTransform t(width_, height_, extent_, 0, 0);
    mapnik::box2d<double> intersect = extent_.intersect(q.get_bbox());
    mapnik::box2d<double> ext = t.forward(intersect);

    const int width  = int(ext.maxx() + 0.5) - int(ext.minx() + 0.5);
    const int height = int(ext.maxy() + 0.5) - int(ext.miny() + 0.5);

#ifdef MAPNIK_DEBUG
    std::clog << "Raster Plugin: BOX SIZE(" << width << " " << height << ")" << std::endl;
#endif

    if (width * height > 512*512)
    {
#ifdef MAPNIK_DEBUG
        std::clog << "Raster Plugin: TILED policy" << std::endl;
#endif

        tiled_file_policy policy(filename_, format_, 256, extent_, q.get_bbox(), width_, height_);
        return featureset_ptr(new raster_featureset<tiled_file_policy>(policy, extent_, q));
    }
    else
    {
#ifdef MAPNIK_DEBUG
        std::clog << "Raster Plugin: SINGLE FILE" << std::endl;
#endif

        raster_info info(filename_, format_, extent_, width_, height_);
        single_file_policy policy(info);
        return featureset_ptr(new raster_featureset<single_file_policy>(policy, extent_, q));
    }
}

featureset_ptr raster_datasource::features_at_point(coord2d const&) const
{
    return featureset_ptr();
}

<commit_msg>raster.input: touchup error output<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id: raster_datasource.cc 44 2005-04-22 18:53:54Z pavlenko $

// boost
#include <boost/lexical_cast.hpp>
#include <boost/filesystem/operations.hpp>

// mapnik
#include <mapnik/image_reader.hpp>

#include "raster_featureset.hpp"
#include "raster_info.hpp"
#include "raster_datasource.hpp"

using mapnik::datasource;
using mapnik::parameters;
using mapnik::image_reader;

DATASOURCE_PLUGIN(raster_datasource)

using boost::lexical_cast;
using boost::bad_lexical_cast;
using mapnik::layer_descriptor;
using mapnik::featureset_ptr;
using mapnik::query;
using mapnik::coord2d;
using mapnik::datasource_exception;

raster_datasource::raster_datasource(const parameters& params, bool bind)
    : datasource(params),
      desc_(*params.get<std::string>("type"),"utf-8"),
      extent_initialized_(false)
{
#ifdef MAPNIK_DEBUG
    std::clog << "Raster Plugin: Initializing..." << std::endl;
#endif

    boost::optional<std::string> file = params.get<std::string>("file");
    if (! file) throw datasource_exception("Raster Plugin: missing <file> parameter ");

    boost::optional<std::string> base = params.get<std::string>("base");
    if (base)
       filename_ = *base + "/" + *file;
    else
       filename_ = *file;

    format_=*params_.get<std::string>("format","tiff");

    boost::optional<double> lox = params_.get<double>("lox");
    boost::optional<double> loy = params_.get<double>("loy");
    boost::optional<double> hix = params_.get<double>("hix");
    boost::optional<double> hiy = params_.get<double>("hiy");
    boost::optional<std::string> ext = params_.get<std::string>("extent");

    if (lox && loy && hix && hiy)
    {
        extent_.init(*lox, *loy, *hix, *hiy);
        extent_initialized_ = true;
    }
    else if (ext)
    {
        extent_initialized_ = extent_.from_string(*ext);
    }

    if (! extent_initialized_)
        throw datasource_exception("Raster Plugin: valid <extent> or <lox> <loy> <hix> <hiy> are required");

    if (bind)
    {
        this->bind();
    }
}

void raster_datasource::bind() const
{
    if (is_bound_) return;

    if (! boost::filesystem::exists(filename_))
        throw datasource_exception("Raster Plugin: " + filename_ + " does not exist");

    try
    {
        std::auto_ptr<image_reader> reader(mapnik::get_image_reader(filename_, format_));
        if (reader.get())
        {
            width_ = reader->width();
            height_ = reader->height();

#ifdef MAPNIK_DEBUG
            std::clog << "Raster Plugin: RASTER SIZE(" << width_ << "," << height_ << ")" << std::endl;
#endif
        }
    }
    catch (mapnik::image_reader_exception const& ex)
    {
        std::cerr << "Raster Plugin: image reader exception caught: " << ex.what() << std::endl;
        throw;
    }
    catch (...)
    {
        std::cerr << "Raster Plugin: exception caught" << std::endl;
        throw;
    }

    is_bound_ = true;
}

raster_datasource::~raster_datasource()
{
}

int raster_datasource::type() const
{
    return datasource::Raster;
}

std::string raster_datasource::name()
{
    return "raster";
}

mapnik::box2d<double> raster_datasource::envelope() const
{
    return extent_;
}

layer_descriptor raster_datasource::get_descriptor() const
{
    return desc_;
}

featureset_ptr raster_datasource::features(query const& q) const
{
    if (! is_bound_) bind();

    mapnik::CoordTransform t(width_, height_, extent_, 0, 0);
    mapnik::box2d<double> intersect = extent_.intersect(q.get_bbox());
    mapnik::box2d<double> ext = t.forward(intersect);

    const int width  = int(ext.maxx() + 0.5) - int(ext.minx() + 0.5);
    const int height = int(ext.maxy() + 0.5) - int(ext.miny() + 0.5);

#ifdef MAPNIK_DEBUG
    std::clog << "Raster Plugin: BOX SIZE(" << width << " " << height << ")" << std::endl;
#endif

    if (width * height > 512*512)
    {
#ifdef MAPNIK_DEBUG
        std::clog << "Raster Plugin: TILED policy" << std::endl;
#endif

        tiled_file_policy policy(filename_, format_, 256, extent_, q.get_bbox(), width_, height_);
        return featureset_ptr(new raster_featureset<tiled_file_policy>(policy, extent_, q));
    }
    else
    {
#ifdef MAPNIK_DEBUG
        std::clog << "Raster Plugin: SINGLE FILE" << std::endl;
#endif

        raster_info info(filename_, format_, extent_, width_, height_);
        single_file_policy policy(info);
        return featureset_ptr(new raster_featureset<single_file_policy>(policy, extent_, q));
    }
}

featureset_ptr raster_datasource::features_at_point(coord2d const&) const
{
    return featureset_ptr();
}

<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/mss_utils.H $   */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file mss_utils.H
/// @brief Main include file for the Memory Subsystem
///
// *HWP HWP Owner: Andre Marin <aamarin@us.ibm.com>
// *HWP HWP Backup: Brian Silver <bsilver@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: HB:FSP

#ifndef _MSS_P9_ATTR_UTILS_H_
#define _MSS_P9_ATTR_UTILS_H_

//TK: what is this for? BRS

#include <generic/memory/lib/utils/index.H>
#include <generic/memory/lib/utils/c_str.H>

#endif // _MSS_P9_ATTR_UTILS_H_
<commit_msg>Update HPW Level for MSS API library<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/mss_utils.H $   */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file mss_utils.H
/// @brief Main include file for the Memory Subsystem
///
// *HWP HWP Owner: Andre Marin <aamarin@us.ibm.com>
// *HWP HWP Backup: Stephen Glancy <sglancy@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: HB:FSP

#ifndef _MSS_P9_ATTR_UTILS_H_
#define _MSS_P9_ATTR_UTILS_H_

//TK: what is this for? BRS

#include <generic/memory/lib/utils/index.H>
#include <generic/memory/lib/utils/c_str.H>

#endif // _MSS_P9_ATTR_UTILS_H_
<|endoftext|>