<commit_before>#include <iostream>
#include <sstream>
#include <string>

#include <unistd.h>
#include <vector>
#include <algorithm>
#include <list>
#include <map>

#include <cstdlib>
#include <cstring>

#include "segment.h"
#include "message.h"
#include "register_success_message.h"
#include "register_failure_message.h"
#include "register_request_message.h"
#include "loc_success_message.h"
#include "loc_failure_message.h"
#include "loc_request_message.h"
#include "terminate_message.h"

#include "constants.h"
#include "network.h"
#include "helper_function.h"

using namespace std;

//TODO:
//MANAGE CLIENT CONNECTION
//MANAGE SERVER CONNECTION
//DATABASE
//ROUND ROBIN

static map<procedure_signature, list<server_info *>, ps_compare> proc_loc_dict;
static list<server_function_info *> roundRobinList;

/*
TODO:
ADD FUNCTION TO MAP
ADD FUNCTION TO ROUND ROBIN
IF FUNCTION EXISTS IN ROUND ROBIN DELETE OLD REPLACE WITH NEW (where)
*/

void mapPrint(){
  cout << "proc_loc_dict size: "<<proc_loc_dict.size() << endl;
  cout << "Map Print: ";
  for(map<procedure_signature, list<server_info *>, ps_compare> ::const_iterator it = proc_loc_dict.begin();
   it != proc_loc_dict.end(); it++){

    cout << it->first.name << ", " ;
  }

  cout << endl;
}

void roundRobinPrint(){
  cout << "roundRobin Print: ";
  for(list<server_function_info *> ::const_iterator it = roundRobinList.begin(); it != roundRobinList.end(); it++){
    cout << (*it)->ps->name << endl;
  }
}

void registration_request_handler(RegisterRequestMessage * message, int sock){
  const char * name = message->getName().c_str();
  int * argTypes = message->getArgTypes();
  string server_identifier = message->getServerIdentifier();
  int port = message->getPort();

  cout << "We are trying to register: " << name << endl;

  procedure_signature key(name, argTypes);

  int status = 0;

  //if 'key' dosnt exist in map, add it to the map and round robin
	if (proc_loc_dict.find(key) == proc_loc_dict.end()) {
    //The purpose of this function is so we can have copy of the argTypes that not the original
    int *memArgTypes = copyArgTypes(argTypes);

    key = procedure_signature(name, memArgTypes);
    proc_loc_dict[key] = list<server_info *>();

    //This is bad we shouldn't need a newKey and we should be able to use the key above
    //due to &* reasones I made a variable newKey for the 'info' object
    procedure_signature * newKey = new procedure_signature(name, memArgTypes);
    server_info * entry = new server_info(server_identifier, port, sock);

    //Adding to roundRobinList
    server_function_info * info = new server_function_info(entry, newKey);
    roundRobinList.push_back(info);

  } else {
    bool sameLoc = false;
    list<server_info *> hostList = proc_loc_dict[key];

    for (list<server_info *>::iterator it = hostList.begin(); it != hostList.end(); it++) {
      if((*it)->socket == sock){
        //If they have the same socket, then must be same server_address/port
        //The same procedure signature already exists on the same location
        //TODO: Move to end of round robin or something, maybe we should keep
        sameLoc = true;
      }
    }

  	if(!sameLoc){ //same procedure different socket
       server_info * new_msg_loc = new server_info(server_identifier, port, sock);
       hostList.push_back(new_msg_loc);
    }
  }

  //mapPrint();
  //roundRobinPrint();

  RegisterSuccessMessage regSuccessMsg = RegisterSuccessMessage(status);
  Segment regSuccessSeg = Segment(regSuccessMsg.getLength(), MSG_TYPE_REGISTER_SUCCESS, &regSuccessMsg);
  regSuccessSeg.send(sock);

}

/*
TODO:
USE ROUND ROBIN TO ACCESS THE CORRECT SERVER/FUNCTION FOR THE CLIENT
*/
void location_request_handler(LocRequestMessage * message, int sock){

  bool exist = false;

  cout << "Hunted name names: " << message->getName() << endl;

	for (list<server_function_info *>::const_iterator it = roundRobinList.begin(); it != roundRobinList.end(); it++){
    //If the name are the same and argTypes
    cout << "Iterator names: " << (*it)->ps->name << endl;

    if((*it)->ps->name == message->getName() && compareArr((*it)->ps->argTypes, message->getArgTypes() )){
      exist = true;

      LocSuccessMessage locSuccessMsg = LocSuccessMessage((*it)->si->server_identifier, (*it)->si->port);
      Segment locSuccessSeg = Segment(locSuccessSeg.getLength(), MSG_TYPE_LOC_SUCCESS, &locSuccessMsg);
      locSuccessSeg.send(sock);

      //When we have identified the correct procedure_signature use splice and move that service to the end
      roundRobinList.splice(roundRobinList.end(), roundRobinList, it);
      break;
 		}

  }

  if(!exist){
    int reasoncode = -5; // Need actual reasoncode
    LocFailureMessage locFailMsg = LocFailureMessage(reasoncode);
    Segment locFailSeg = Segment(locFailMsg.getLength(), MSG_TYPE_LOC_FAILURE, &locFailMsg);
    locFailSeg.send(sock);
  }
}

int request_handler(Segment * segment, int sock){
  int retval = 0;
  if(segment->getType() == MSG_TYPE_REGISTER_REQUEST){
    Message * cast1 = segment->getMessage();
    RegisterRequestMessage * rrm = dynamic_cast<RegisterRequestMessage*>(cast1);

    registration_request_handler(rrm, sock);

  }else if (segment->getType() == MSG_TYPE_LOC_REQUEST){

    cout << "Loc Request" << endl;

    Message * cast2 = segment->getMessage();
    LocRequestMessage * lqm = dynamic_cast<LocRequestMessage*>(cast2);

    location_request_handler(lqm, sock);
  }

	return retval;
}

//TODO:
//Create helper functions that can be used for rpcServer.cc
int main() {
  vector<int> myConnections;
  vector<int> myToRemove;

  // Creates the welcome socket
  int welcomeSocket = createSocket();
  int status = setUpToListen(welcomeSocket);

  cout << "BINDER_ADDRESS " << getHostAddress() << endl;
  cout << "BINDER_PORT " << getSocketPort(welcomeSocket) << endl;

  fd_set readfds;
  int n;

  while(true){
    //CONNECTIONS VECTOR
    FD_ZERO(&readfds);
    FD_SET(welcomeSocket, &readfds);

    n = welcomeSocket;

    for (vector<int>::iterator it = myConnections.begin();it != myConnections.end(); ++it) {
      int connection = *it;
      FD_SET(connection, &readfds);
       if (connection > n){
        n = connection;
      }
    }

    n = n+1;

    status = select(n, &readfds, NULL, NULL, NULL);

    if (status == -1) {
      cerr << "ERROR: select failed." << endl;
    } else {

      if (FD_ISSET(welcomeSocket, &readfds)) {
        int connectionSocket = acceptConnection(welcomeSocket);

        if (connectionSocket < 0) {
          cerr << "ERROR: while accepting connection" << endl;
          continue;
        }

        myConnections.push_back(connectionSocket);

      } else {

        for (vector<int>::iterator it = myConnections.begin(); it != myConnections.end(); ++it) {
          int tempConnection = *it;

            cout << "Socket iterator" << endl;

          if (FD_ISSET(tempConnection, &readfds)) {

            cout << "We in here" << endl;

            Segment * segment = 0;
            status = Segment::receive(tempConnection, segment);

            //TODO: More sophisticaled error handling/replies
            // Maybe status should be reasonacode instead
            if (status < 0 && segment->getType() == MSG_TYPE_REGISTER_REQUEST) {
                RegisterFailureMessage regFailMsg = RegisterFailureMessage(status);
                Segment regFailSeg = Segment(regFailMsg.getLength(), MSG_TYPE_REGISTER_FAILURE, &regFailMsg);
                regFailSeg.send(tempConnection);
                return status;
            } else if (status < 0 && segment->getType() == MSG_TYPE_LOC_REQUEST) {
                LocFailureMessage locFailMsg = LocFailureMessage(status);
                Segment regFailSeg = Segment(locFailMsg.getLength(), MSG_TYPE_LOC_FAILURE, &locFailMsg);
                regFailSeg.send(tempConnection);
                return status;
            }

            if (status == 0) {
              // client has closed the connection
              myToRemove.push_back(tempConnection);
              return status;
            }

            request_handler(segment, tempConnection);
          }
        }
      }

      for (vector<int>::iterator it = myToRemove.begin(); it != myToRemove.end(); ++it) {
        myConnections.erase(remove(myConnections.begin(), myConnections.end(), *it), myConnections.end());
        destroySocket(*it);
      }
      myToRemove.clear();
    }
  }

  // Destroys the welcome socket
  destroySocket(welcomeSocket);
}
<commit_msg>changes<commit_after>#include <iostream>
#include <sstream>
#include <string>

#include <unistd.h>
#include <vector>
#include <algorithm>
#include <list>
#include <map>

#include <cstdlib>
#include <cstring>

#include "segment.h"
#include "message.h"
#include "register_success_message.h"
#include "register_failure_message.h"
#include "register_request_message.h"
#include "loc_success_message.h"
#include "loc_failure_message.h"
#include "loc_request_message.h"
#include "terminate_message.h"

#include "constants.h"
#include "network.h"
#include "helper_function.h"

using namespace std;

//TODO:
//MANAGE CLIENT CONNECTION
//MANAGE SERVER CONNECTION
//DATABASE
//ROUND ROBIN

static map<procedure_signature, list<server_info *>, ps_compare> proc_loc_dict;
static list<server_function_info *> roundRobinList;

/*
TODO:
ADD FUNCTION TO MAP
ADD FUNCTION TO ROUND ROBIN
IF FUNCTION EXISTS IN ROUND ROBIN DELETE OLD REPLACE WITH NEW (where)
*/

void mapPrint(){
  cout << "proc_loc_dict size: "<<proc_loc_dict.size() << endl;
  cout << "Map Print: ";
  for(map<procedure_signature, list<server_info *>, ps_compare> ::const_iterator it = proc_loc_dict.begin();
   it != proc_loc_dict.end(); it++){

    cout << it->first.name << ", " ;
  }

  cout << endl;
}

void roundRobinPrint(){
  cout << "roundRobin Print: ";
  for(list<server_function_info *> ::const_iterator it = roundRobinList.begin(); it != roundRobinList.end(); it++){
    cout << (*it)->ps->name << endl;
  }
}

void registration_request_handler(RegisterRequestMessage * message, int sock){
  const char * name = message->getName().c_str();
  int * argTypes = message->getArgTypes();
  string server_identifier = message->getServerIdentifier();
  int port = message->getPort();

  cout << "We are trying to register: " << name << endl;

  procedure_signature key(name, argTypes);

  int status = 0;

  //if 'key' dosnt exist in map, add it to the map and round robin
	if (proc_loc_dict.find(key) == proc_loc_dict.end()) {
    //The purpose of this function is so we can have copy of the argTypes that not the original
    int *memArgTypes = copyArgTypes(argTypes);

    key = procedure_signature(name, memArgTypes);
    proc_loc_dict[key] = list<server_info *>();

    //This is bad we shouldn't need a newKey and we should be able to use the key above
    //due to &* reasones I made a variable newKey for the 'info' object
    procedure_signature * newKey = new procedure_signature(name, memArgTypes);
    server_info * entry = new server_info(server_identifier, port, sock);

    //Adding to roundRobinList
    server_function_info * info = new server_function_info(entry, newKey);
    roundRobinList.push_back(info);

  } else {
    bool sameLoc = false;
    list<server_info *> hostList = proc_loc_dict[key];

    for (list<server_info *>::iterator it = hostList.begin(); it != hostList.end(); it++) {
      if((*it)->socket == sock){
        //If they have the same socket, then must be same server_address/port
        //The same procedure signature already exists on the same location
        //TODO: Move to end of round robin or something, maybe we should keep
        sameLoc = true;
      }
    }

  	if(!sameLoc){ //same procedure different socket
       server_info * new_msg_loc = new server_info(server_identifier, port, sock);
       hostList.push_back(new_msg_loc);
    }
  }

  //mapPrint();
  //roundRobinPrint();

  RegisterSuccessMessage regSuccessMsg = RegisterSuccessMessage(status);
  Segment regSuccessSeg = Segment(regSuccessMsg.getLength(), MSG_TYPE_REGISTER_SUCCESS, &regSuccessMsg);
  regSuccessSeg.send(sock);

}

/*
TODO:
USE ROUND ROBIN TO ACCESS THE CORRECT SERVER/FUNCTION FOR THE CLIENT
*/
void location_request_handler(LocRequestMessage * message, int sock){

  bool exist = false;

  cout << "Hunted name names: " << message->getName() << endl;

	for (list<server_function_info *>::iterator it = roundRobinList.begin(); it != roundRobinList.end(); it++){
    //If the name are the same and argTypes
    cout << "Iterator names: " << (*it)->ps->name << endl;

    if((*it)->ps->name == message->getName() && compareArr((*it)->ps->argTypes, message->getArgTypes() )){
      exist = true;

      LocSuccessMessage locSuccessMsg = LocSuccessMessage((*it)->si->server_identifier, (*it)->si->port);
      Segment locSuccessSeg = Segment(locSuccessSeg.getLength(), MSG_TYPE_LOC_SUCCESS, &locSuccessMsg);
      locSuccessSeg.send(sock);

      //When we have identified the correct procedure_signature use splice and move that service to the end
      roundRobinList.splice(roundRobinList.end(), roundRobinList, it);
      break;
 		}
	}

  if(!exist){
    int reasoncode = -5; // Need actual reasoncode
    LocFailureMessage locFailMsg = LocFailureMessage(reasoncode);
    Segment locFailSeg = Segment(locFailMsg.getLength(), MSG_TYPE_LOC_FAILURE, &locFailMsg);
    locFailSeg.send(sock);
  }
}

int request_handler(Segment * segment, int sock){
  int retval = 0;
  if(segment->getType() == MSG_TYPE_REGISTER_REQUEST){
    Message * cast1 = segment->getMessage();
    RegisterRequestMessage * rrm = dynamic_cast<RegisterRequestMessage*>(cast1);

    registration_request_handler(rrm, sock);

  }else if (segment->getType() == MSG_TYPE_LOC_REQUEST){

    cout << "Loc Request" << endl;

    Message * cast2 = segment->getMessage();
    LocRequestMessage * lqm = dynamic_cast<LocRequestMessage*>(cast2);

    location_request_handler(lqm, sock);
  }

	return retval;
}

//TODO:
//Create helper functions that can be used for rpcServer.cc
int main() {
  vector<int> myConnections;
  vector<int> myToRemove;

  // Creates the welcome socket
  int welcomeSocket = createSocket();
  int status = setUpToListen(welcomeSocket);

  cout << "BINDER_ADDRESS " << getHostAddress() << endl;
  cout << "BINDER_PORT " << getSocketPort(welcomeSocket) << endl;

  fd_set readfds;
  int n;

  while(true){
    //CONNECTIONS VECTOR
    FD_ZERO(&readfds);
    FD_SET(welcomeSocket, &readfds);

    n = welcomeSocket;

    for (vector<int>::iterator it = myConnections.begin();it != myConnections.end(); ++it) {
      int connection = *it;
      FD_SET(connection, &readfds);
       if (connection > n){
        n = connection;
      }
    }

    n = n+1;

    status = select(n, &readfds, NULL, NULL, NULL);

    if (status == -1) {
      cerr << "ERROR: select failed." << endl;
    } else {

      if (FD_ISSET(welcomeSocket, &readfds)) {
        int connectionSocket = acceptConnection(welcomeSocket);

        if (connectionSocket < 0) {
          cerr << "ERROR: while accepting connection" << endl;
          continue;
        }

        myConnections.push_back(connectionSocket);

      } else {

        for (vector<int>::iterator it = myConnections.begin(); it != myConnections.end(); ++it) {
          int tempConnection = *it;

            cout << "Socket iterator" << endl;

          if (FD_ISSET(tempConnection, &readfds)) {

            cout << "We in here" << endl;

            Segment * segment = 0;
            status = Segment::receive(tempConnection, segment);

            //TODO: More sophisticaled error handling/replies
            // Maybe status should be reasonacode instead
            if (status < 0 && segment->getType() == MSG_TYPE_REGISTER_REQUEST) {
                RegisterFailureMessage regFailMsg = RegisterFailureMessage(status);
                Segment regFailSeg = Segment(regFailMsg.getLength(), MSG_TYPE_REGISTER_FAILURE, &regFailMsg);
                regFailSeg.send(tempConnection);
                return status;
            } else if (status < 0 && segment->getType() == MSG_TYPE_LOC_REQUEST) {
                LocFailureMessage locFailMsg = LocFailureMessage(status);
                Segment regFailSeg = Segment(locFailMsg.getLength(), MSG_TYPE_LOC_FAILURE, &locFailMsg);
                regFailSeg.send(tempConnection);
                return status;
            }

            if (status == 0) {
              // client has closed the connection
              myToRemove.push_back(tempConnection);
              return status;
            }

            request_handler(segment, tempConnection);
          }
        }
      }

      for (vector<int>::iterator it = myToRemove.begin(); it != myToRemove.end(); ++it) {
        myConnections.erase(remove(myConnections.begin(), myConnections.end(), *it), myConnections.end());
        destroySocket(*it);
      }
      myToRemove.clear();
    }
  }

  // Destroys the welcome socket
  destroySocket(welcomeSocket);
}
<|endoftext|>


<commit_before>/* This file is part of the Pangolin Project.
 * http://github.com/stevenlovegrove/Pangolin
 *
 * Copyright (c) 2014 Richard Newcombe
 *               2014 Steven Lovegrove
 *
 * 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, sublicense, 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 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
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS 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.
 */

#include <pangolin/video/drivers/openni2.h>

#include <PS1080.h>
#include <OniVersion.h>

namespace pangolin
{

VideoPixelFormat VideoFormatFromOpenNI2(openni::PixelFormat fmt)
{
    std::string pvfmt;

    switch (fmt) {
    case openni::PIXEL_FORMAT_DEPTH_1_MM:   pvfmt = "GRAY16LE"; break;
    case openni::PIXEL_FORMAT_DEPTH_100_UM: pvfmt = "GRAY16LE"; break;
    case openni::PIXEL_FORMAT_SHIFT_9_2:    pvfmt = "GRAY16LE"; break; // ?
    case openni::PIXEL_FORMAT_SHIFT_9_3:    pvfmt = "GRAY16LE"; break; // ?
    case openni::PIXEL_FORMAT_RGB888:       pvfmt = "RGB24"; break;
    case openni::PIXEL_FORMAT_GRAY8:        pvfmt = "GRAY8"; break;
    case openni::PIXEL_FORMAT_GRAY16:       pvfmt = "GRAY16LE"; break;
    case openni::PIXEL_FORMAT_YUV422:       pvfmt = "YUYV422"; break;
#if ONI_VERSION_MAJOR >= 2 && ONI_VERSION_MINOR >= 2
    case openni::PIXEL_FORMAT_YUYV:         pvfmt = "Y400A"; break;
#endif
    default:
        throw VideoException("Unknown OpenNI pixel format");
        break;
    }

    return VideoFormatFromString(pvfmt);
}

void OpenNiVideo2::PrintOpenNI2Modes(openni::SensorType sensorType)
{
    // Query supported modes for device
    const openni::Array<openni::VideoMode>& modes =
            device.getSensorInfo(sensorType)->getSupportedVideoModes();

    switch (sensorType) {
    case openni::SENSOR_COLOR: pango_print_info("OpenNI Colour Modes:\n"); break;
    case openni::SENSOR_DEPTH: pango_print_info("OpenNI Depth Modes:\n"); break;
    case openni::SENSOR_IR:    pango_print_info("OpenNI IR Modes:\n"); break;
    }

    for(int i = 0; i < modes.getSize(); i++) {
        std::string sfmt = "PangolinUnknown";
        try{
            sfmt = VideoFormatFromOpenNI2(modes[i].getPixelFormat()).format;
        }catch(VideoException){}
        pango_print_info( "  %dx%d, %d fps, %s\n",
            modes[i].getResolutionX(), modes[i].getResolutionY(),
            modes[i].getFps(), sfmt.c_str()
        );
    }
}

openni::VideoMode OpenNiVideo2::FindOpenNI2Mode(
    openni::SensorType sensorType,
    int width, int height,
    int fps, openni::PixelFormat fmt
) {
    // Query supported modes for device
    const openni::Array<openni::VideoMode>& modes =
            device.getSensorInfo(sensorType)->getSupportedVideoModes();

    // Select last listed mode which matches parameters
    int best_mode = -1;
    for(int i = 0; i < modes.getSize(); i++) {
        if( (!width || modes[i].getResolutionX() == width) &&
            (!height || modes[i].getResolutionY() == height) &&
            (!fps || modes[i].getFps() == fps) &&
            (!fmt || modes[i].getPixelFormat() == fmt)
        ) {
            best_mode = i;
        }
    }

    if(best_mode >= 0) {
        return modes[best_mode];
    }

    throw pangolin::VideoException("Video mode not supported");
}

OpenNiVideo2::OpenNiVideo2(OpenNiSensorType s1, OpenNiSensorType s2, ImageDim dim, int fps, bool realtime)
{
    streams_properties = &frame_properties["streams"];
    *streams_properties = json::value(json::array_type,false);
    streams_properties->get<json::array>().resize(2);

    sensor_type[0] = s1;
    sensor_type[1] = s2;

    use_depth = false;
    use_ir = false;
    use_rgb = false;
    depth_to_color = false;
    use_ir_and_rgb = false;

    const char* deviceURI = openni::ANY_DEVICE;
    fromFile = (deviceURI!=NULL);

    openni::Status rc = openni::OpenNI::initialize();
    if (rc != openni::STATUS_OK) {
        throw VideoException( "Unable to initialise OpenNI library", openni::OpenNI::getExtendedError() );
    }

    rc = device.open(deviceURI);
    if (rc != openni::STATUS_OK) {
        throw VideoException("Failed to open device", openni::OpenNI::getExtendedError());
    }

//    PrintOpenNI2Modes(openni::SENSOR_COLOR);
//    PrintOpenNI2Modes(openni::SENSOR_DEPTH);
//    PrintOpenNI2Modes(openni::SENSOR_IR);

    for(int i=0; i<2; ++i) {
        openni::SensorType sensortype;
        openni::PixelFormat pixelfmt;

        switch( sensor_type[i] ) {
        case OpenNiDepthRegistered:
            depth_to_color = true;
        case OpenNiDepth:
            sensortype = openni::SENSOR_DEPTH;
            pixelfmt = openni::PIXEL_FORMAT_DEPTH_1_MM;
            use_depth = true;
            break;
        case OpenNiIrProj:
        case OpenNiIr:
            sensortype = openni::SENSOR_IR;
            pixelfmt = openni::PIXEL_FORMAT_GRAY16;
            use_ir = true;
            break;
        case OpenNiIr24bit:
            sensortype = openni::SENSOR_IR;
            pixelfmt = openni::PIXEL_FORMAT_RGB888;
            use_ir = true;
            break;
        case OpenNiIr8bitProj:
        case OpenNiIr8bit:
            sensortype = openni::SENSOR_IR;
            pixelfmt = openni::PIXEL_FORMAT_GRAY8;
            use_ir = true;
            break;
        case OpenNiRgb:
            sensortype = openni::SENSOR_COLOR;
            pixelfmt = openni::PIXEL_FORMAT_RGB888;
            use_rgb = true;
            break;
        case OpenNiGrey:
            sensortype = openni::SENSOR_COLOR;
            pixelfmt = openni::PIXEL_FORMAT_GRAY8;
            use_rgb = true;
            break;
        case OpenNiUnassigned:
        default:
            continue;
        }

        openni::VideoMode onivmode;
        try {
            onivmode = FindOpenNI2Mode(sensortype, dim.x, dim.y, fps, pixelfmt);
        }catch(VideoException e) {
            pango_print_error("Unable to find compatible OpenNI Video Mode. Please choose from:\n");
            PrintOpenNI2Modes(sensortype);
            fflush(stdout);
            throw e;
        }

        if(fromFile) {
            // do something with mode?
        }

        rc = video_stream[i].create(device, sensortype);
        if(rc != openni::STATUS_OK)
            throw VideoException("Couldn't create sensor", openni::OpenNI::getExtendedError());

        rc = video_stream[i].setVideoMode(onivmode);
        if(rc != openni::STATUS_OK)
            throw VideoException("Couldn't set OpenNI VideoMode", openni::OpenNI::getExtendedError());

        video_stream[i].setMirroringEnabled(false);

        if(sensortype == openni::SENSOR_COLOR) {
            video_stream[i].getCameraSettings()->setAutoExposureEnabled(true);
            video_stream[i].getCameraSettings()->setAutoWhiteBalanceEnabled(true);
        }

        const VideoPixelFormat fmt = VideoFormatFromOpenNI2(pixelfmt);
        const StreamInfo stream(
            fmt, onivmode.getResolutionX(), onivmode.getResolutionY(),
            (onivmode.getResolutionX() * fmt.bpp) / 8,
            (unsigned char*)0 + sizeBytes
        );

        sizeBytes += stream.SizeBytes();
        streams.push_back(stream);
    }
    use_ir_and_rgb = use_rgb && use_ir;

    if(fromFile) {
        // Go as fast as we can.
        device.getPlaybackControl()->setSpeed(realtime ? 1.0f : -1.0f);
    }

    if(depth_to_color) {
        device.setImageRegistrationMode(openni::IMAGE_REGISTRATION_DEPTH_TO_COLOR);
    }else{
        device.setImageRegistrationMode(openni::IMAGE_REGISTRATION_OFF);
    }

    Start();
}

void OpenNiVideo2::UpdateProperties()
{
    json::value& jsopenni = device_properties["openni"];

#define SET_PARAM(param_type, param) \
    { \
        param_type val; \
        if(device.getProperty(param, &val) == openni::STATUS_OK) { \
            jsdevice[#param] = val; \
        } \
    }

    json::value& jsdevice = jsopenni["device"];
    SET_PARAM( unsigned long long, XN_MODULE_PROPERTY_USB_INTERFACE );
    SET_PARAM( bool,  XN_MODULE_PROPERTY_MIRROR );
#undef SET_PARAM

    json::value& stream = jsopenni["streams"];
    stream = json::value(json::array_type,false);
    stream.get<json::array>().resize(2);
    for(int i=0; i<2; ++i) {
        if(sensor_type[i] != OpenNiUnassigned)
        {
#define SET_PARAM(param_type, param) \
            {\
                param_type val; \
                if(video_stream[i].getProperty(param, &val) == openni::STATUS_OK) { \
                    jsstream[#param] = val; \
                } \
            }

            json::value& jsstream = stream[i];
            SET_PARAM( unsigned long long, XN_STREAM_PROPERTY_INPUT_FORMAT );
            SET_PARAM( unsigned long long, XN_STREAM_PROPERTY_CROPPING_MODE );

            SET_PARAM( unsigned long long, XN_STREAM_PROPERTY_CLOSE_RANGE );
            SET_PARAM( unsigned long long, XN_STREAM_PROPERTY_WHITE_BALANCE_ENABLED );
            SET_PARAM( unsigned long long, XN_STREAM_PROPERTY_GAIN );
            SET_PARAM( unsigned long long, XN_STREAM_PROPERTY_HOLE_FILTER );
            SET_PARAM( unsigned long long, XN_STREAM_PROPERTY_REGISTRATION_TYPE );
            SET_PARAM( unsigned long long, XN_STREAM_PROPERTY_CONST_SHIFT );
            SET_PARAM( unsigned long long, XN_STREAM_PROPERTY_PIXEL_SIZE_FACTOR );
            SET_PARAM( unsigned long long, XN_STREAM_PROPERTY_MAX_SHIFT );
            SET_PARAM( unsigned long long, XN_STREAM_PROPERTY_PARAM_COEFF );
            SET_PARAM( unsigned long long, XN_STREAM_PROPERTY_SHIFT_SCALE );
            SET_PARAM( unsigned long long, XN_STREAM_PROPERTY_ZERO_PLANE_DISTANCE );
            SET_PARAM( double, XN_STREAM_PROPERTY_ZERO_PLANE_PIXEL_SIZE );
            SET_PARAM( double, XN_STREAM_PROPERTY_EMITTER_DCMOS_DISTANCE );
            SET_PARAM( double, XN_STREAM_PROPERTY_DCMOS_RCMOS_DISTANCE );
#undef SET_PARAM
        }
    }
}

void OpenNiVideo2::SetDepthCloseRange(bool enable)
{
    // Set this property on all devices. It doesn't matter if it fails.
    for(int i=0; i<2; ++i) {
        video_stream[i].setProperty(XN_STREAM_PROPERTY_CLOSE_RANGE, enable);
    }
}

void OpenNiVideo2::SetDepthHoleFilter(bool enable)
{
    // Set this property on all devices. It doesn't matter if it fails.
    for(int i=0; i<2; ++i) {
        video_stream[i].setProperty(XN_STREAM_PROPERTY_HOLE_FILTER, enable);
        video_stream[i].setProperty(XN_STREAM_PROPERTY_GAIN,50);
    }
}

void OpenNiVideo2::SetDepthColorSyncEnabled(bool enable)
{
    device.setDepthColorSyncEnabled(enable);
}

void OpenNiVideo2::SetRegisterDepthToImage(bool enable)
{
    if(enable) {
        device.setImageRegistrationMode(openni::IMAGE_REGISTRATION_DEPTH_TO_COLOR);
    }else{
        device.setImageRegistrationMode(openni::IMAGE_REGISTRATION_OFF);
    }
}

OpenNiVideo2::~OpenNiVideo2()
{
    Stop();

    for(int i=0; i<2; ++i) {
        if( video_stream[i].isValid()) {
            video_stream[i].destroy();
        }
    }

    openni::OpenNI::shutdown();
}

size_t OpenNiVideo2::SizeBytes() const
{
    return sizeBytes;
}

const std::vector<StreamInfo>& OpenNiVideo2::Streams() const
{
    return streams;
}

void OpenNiVideo2::Start()
{
    for(int i=0; i<2; ++i) {
        video_stream[i].start();
    }
}

void OpenNiVideo2::Stop()
{
    for(int i=0; i<2; ++i) {
        video_stream[i].stop();
    }
}

bool OpenNiVideo2::GrabNext( unsigned char* image, bool wait )
{
    unsigned char* out_img = image;

    openni::Status rc;

    for(int i=0; i<2; ++i) {
        if(!video_stream[i].isValid()) {
            rc = openni::STATUS_NO_DEVICE;
            continue;
        }

        if(use_ir_and_rgb) video_stream[i].start();

        rc = video_stream[i].readFrame(&video_frame[i]);
        if(rc != openni::STATUS_OK) {
            pango_print_error("Error reading frame:\n%s", openni::OpenNI::getExtendedError() );
        }

        const bool toGreyscale = false;
        if(toGreyscale) {
            const int w = streams[i].Width();
            const int h = streams[i].Height();

            openni::RGB888Pixel* pColour = (openni::RGB888Pixel*)video_frame[i].getData();
            for(int i = 0 ; i  < w*h;i++){
                openni::RGB888Pixel rgb = pColour[i];
                int grey = ((int)(rgb.r&0xFF) +  (int)(rgb.g&0xFF) + (int)(rgb.b&0xFF))/3;
                grey = std::min(255,std::max(0,grey));
                out_img[i] = grey;
            }
        }else{
            memcpy(out_img, video_frame[i].getData(), streams[i].SizeBytes());
        }

        // update frame properties
        (*streams_properties)[i]["devtime_us"] = video_frame[i].getTimestamp();

        if(use_ir_and_rgb) video_stream[i].stop();

        out_img += streams[i].SizeBytes();
    }

    return rc == openni::STATUS_OK;
}

bool OpenNiVideo2::GrabNewest( unsigned char* image, bool wait )
{
    return GrabNext(image,wait);
}

}
<commit_msg>OpenNI2: Fix reading single stream.<commit_after>/* This file is part of the Pangolin Project.
 * http://github.com/stevenlovegrove/Pangolin
 *
 * Copyright (c) 2014 Richard Newcombe
 *               2014 Steven Lovegrove
 *
 * 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, sublicense, 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 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
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS 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.
 */

#include <pangolin/video/drivers/openni2.h>

#include <PS1080.h>
#include <OniVersion.h>

namespace pangolin
{

VideoPixelFormat VideoFormatFromOpenNI2(openni::PixelFormat fmt)
{
    std::string pvfmt;

    switch (fmt) {
    case openni::PIXEL_FORMAT_DEPTH_1_MM:   pvfmt = "GRAY16LE"; break;
    case openni::PIXEL_FORMAT_DEPTH_100_UM: pvfmt = "GRAY16LE"; break;
    case openni::PIXEL_FORMAT_SHIFT_9_2:    pvfmt = "GRAY16LE"; break; // ?
    case openni::PIXEL_FORMAT_SHIFT_9_3:    pvfmt = "GRAY16LE"; break; // ?
    case openni::PIXEL_FORMAT_RGB888:       pvfmt = "RGB24"; break;
    case openni::PIXEL_FORMAT_GRAY8:        pvfmt = "GRAY8"; break;
    case openni::PIXEL_FORMAT_GRAY16:       pvfmt = "GRAY16LE"; break;
    case openni::PIXEL_FORMAT_YUV422:       pvfmt = "YUYV422"; break;
#if ONI_VERSION_MAJOR >= 2 && ONI_VERSION_MINOR >= 2
    case openni::PIXEL_FORMAT_YUYV:         pvfmt = "Y400A"; break;
#endif
    default:
        throw VideoException("Unknown OpenNI pixel format");
        break;
    }

    return VideoFormatFromString(pvfmt);
}

void OpenNiVideo2::PrintOpenNI2Modes(openni::SensorType sensorType)
{
    // Query supported modes for device
    const openni::Array<openni::VideoMode>& modes =
            device.getSensorInfo(sensorType)->getSupportedVideoModes();

    switch (sensorType) {
    case openni::SENSOR_COLOR: pango_print_info("OpenNI Colour Modes:\n"); break;
    case openni::SENSOR_DEPTH: pango_print_info("OpenNI Depth Modes:\n"); break;
    case openni::SENSOR_IR:    pango_print_info("OpenNI IR Modes:\n"); break;
    }

    for(int i = 0; i < modes.getSize(); i++) {
        std::string sfmt = "PangolinUnknown";
        try{
            sfmt = VideoFormatFromOpenNI2(modes[i].getPixelFormat()).format;
        }catch(VideoException){}
        pango_print_info( "  %dx%d, %d fps, %s\n",
            modes[i].getResolutionX(), modes[i].getResolutionY(),
            modes[i].getFps(), sfmt.c_str()
        );
    }
}

openni::VideoMode OpenNiVideo2::FindOpenNI2Mode(
    openni::SensorType sensorType,
    int width, int height,
    int fps, openni::PixelFormat fmt
) {
    // Query supported modes for device
    const openni::Array<openni::VideoMode>& modes =
            device.getSensorInfo(sensorType)->getSupportedVideoModes();

    // Select last listed mode which matches parameters
    int best_mode = -1;
    for(int i = 0; i < modes.getSize(); i++) {
        if( (!width || modes[i].getResolutionX() == width) &&
            (!height || modes[i].getResolutionY() == height) &&
            (!fps || modes[i].getFps() == fps) &&
            (!fmt || modes[i].getPixelFormat() == fmt)
        ) {
            best_mode = i;
        }
    }

    if(best_mode >= 0) {
        return modes[best_mode];
    }

    throw pangolin::VideoException("Video mode not supported");
}

OpenNiVideo2::OpenNiVideo2(OpenNiSensorType s1, OpenNiSensorType s2, ImageDim dim, int fps, bool realtime)
{
    streams_properties = &frame_properties["streams"];
    *streams_properties = json::value(json::array_type,false);
    streams_properties->get<json::array>().resize(2);

    sensor_type[0] = s1;
    sensor_type[1] = s2;

    use_depth = false;
    use_ir = false;
    use_rgb = false;
    depth_to_color = false;
    use_ir_and_rgb = false;

    const char* deviceURI = openni::ANY_DEVICE;
    fromFile = (deviceURI!=NULL);

    openni::Status rc = openni::OpenNI::initialize();
    if (rc != openni::STATUS_OK) {
        throw VideoException( "Unable to initialise OpenNI library", openni::OpenNI::getExtendedError() );
    }

    rc = device.open(deviceURI);
    if (rc != openni::STATUS_OK) {
        throw VideoException("Failed to open device", openni::OpenNI::getExtendedError());
    }

//    PrintOpenNI2Modes(openni::SENSOR_COLOR);
//    PrintOpenNI2Modes(openni::SENSOR_DEPTH);
//    PrintOpenNI2Modes(openni::SENSOR_IR);

    for(int i=0; i<2; ++i) {
        openni::SensorType sensortype;
        openni::PixelFormat pixelfmt;

        switch( sensor_type[i] ) {
        case OpenNiDepthRegistered:
            depth_to_color = true;
        case OpenNiDepth:
            sensortype = openni::SENSOR_DEPTH;
            pixelfmt = openni::PIXEL_FORMAT_DEPTH_1_MM;
            use_depth = true;
            break;
        case OpenNiIrProj:
        case OpenNiIr:
            sensortype = openni::SENSOR_IR;
            pixelfmt = openni::PIXEL_FORMAT_GRAY16;
            use_ir = true;
            break;
        case OpenNiIr24bit:
            sensortype = openni::SENSOR_IR;
            pixelfmt = openni::PIXEL_FORMAT_RGB888;
            use_ir = true;
            break;
        case OpenNiIr8bitProj:
        case OpenNiIr8bit:
            sensortype = openni::SENSOR_IR;
            pixelfmt = openni::PIXEL_FORMAT_GRAY8;
            use_ir = true;
            break;
        case OpenNiRgb:
            sensortype = openni::SENSOR_COLOR;
            pixelfmt = openni::PIXEL_FORMAT_RGB888;
            use_rgb = true;
            break;
        case OpenNiGrey:
            sensortype = openni::SENSOR_COLOR;
            pixelfmt = openni::PIXEL_FORMAT_GRAY8;
            use_rgb = true;
            break;
        case OpenNiUnassigned:
        default:
            continue;
        }

        openni::VideoMode onivmode;
        try {
            onivmode = FindOpenNI2Mode(sensortype, dim.x, dim.y, fps, pixelfmt);
        }catch(VideoException e) {
            pango_print_error("Unable to find compatible OpenNI Video Mode. Please choose from:\n");
            PrintOpenNI2Modes(sensortype);
            fflush(stdout);
            throw e;
        }

        if(fromFile) {
            // do something with mode?
        }

        rc = video_stream[i].create(device, sensortype);
        if(rc != openni::STATUS_OK)
            throw VideoException("Couldn't create sensor", openni::OpenNI::getExtendedError());

        rc = video_stream[i].setVideoMode(onivmode);
        if(rc != openni::STATUS_OK)
            throw VideoException("Couldn't set OpenNI VideoMode", openni::OpenNI::getExtendedError());

        video_stream[i].setMirroringEnabled(false);

        if(sensortype == openni::SENSOR_COLOR) {
            video_stream[i].getCameraSettings()->setAutoExposureEnabled(true);
            video_stream[i].getCameraSettings()->setAutoWhiteBalanceEnabled(true);
        }

        const VideoPixelFormat fmt = VideoFormatFromOpenNI2(pixelfmt);
        const StreamInfo stream(
            fmt, onivmode.getResolutionX(), onivmode.getResolutionY(),
            (onivmode.getResolutionX() * fmt.bpp) / 8,
            (unsigned char*)0 + sizeBytes
        );

        sizeBytes += stream.SizeBytes();
        streams.push_back(stream);
    }
    use_ir_and_rgb = use_rgb && use_ir;

    if(fromFile) {
        // Go as fast as we can.
        device.getPlaybackControl()->setSpeed(realtime ? 1.0f : -1.0f);
    }

    if(depth_to_color) {
        device.setImageRegistrationMode(openni::IMAGE_REGISTRATION_DEPTH_TO_COLOR);
    }else{
        device.setImageRegistrationMode(openni::IMAGE_REGISTRATION_OFF);
    }

    Start();
}

void OpenNiVideo2::UpdateProperties()
{
    json::value& jsopenni = device_properties["openni"];

#define SET_PARAM(param_type, param) \
    { \
        param_type val; \
        if(device.getProperty(param, &val) == openni::STATUS_OK) { \
            jsdevice[#param] = val; \
        } \
    }

    json::value& jsdevice = jsopenni["device"];
    SET_PARAM( unsigned long long, XN_MODULE_PROPERTY_USB_INTERFACE );
    SET_PARAM( bool,  XN_MODULE_PROPERTY_MIRROR );
#undef SET_PARAM

    json::value& stream = jsopenni["streams"];
    stream = json::value(json::array_type,false);
    stream.get<json::array>().resize(2);
    for(int i=0; i<2; ++i) {
        if(sensor_type[i] != OpenNiUnassigned)
        {
#define SET_PARAM(param_type, param) \
            {\
                param_type val; \
                if(video_stream[i].getProperty(param, &val) == openni::STATUS_OK) { \
                    jsstream[#param] = val; \
                } \
            }

            json::value& jsstream = stream[i];
            SET_PARAM( unsigned long long, XN_STREAM_PROPERTY_INPUT_FORMAT );
            SET_PARAM( unsigned long long, XN_STREAM_PROPERTY_CROPPING_MODE );

            SET_PARAM( unsigned long long, XN_STREAM_PROPERTY_CLOSE_RANGE );
            SET_PARAM( unsigned long long, XN_STREAM_PROPERTY_WHITE_BALANCE_ENABLED );
            SET_PARAM( unsigned long long, XN_STREAM_PROPERTY_GAIN );
            SET_PARAM( unsigned long long, XN_STREAM_PROPERTY_HOLE_FILTER );
            SET_PARAM( unsigned long long, XN_STREAM_PROPERTY_REGISTRATION_TYPE );
            SET_PARAM( unsigned long long, XN_STREAM_PROPERTY_CONST_SHIFT );
            SET_PARAM( unsigned long long, XN_STREAM_PROPERTY_PIXEL_SIZE_FACTOR );
            SET_PARAM( unsigned long long, XN_STREAM_PROPERTY_MAX_SHIFT );
            SET_PARAM( unsigned long long, XN_STREAM_PROPERTY_PARAM_COEFF );
            SET_PARAM( unsigned long long, XN_STREAM_PROPERTY_SHIFT_SCALE );
            SET_PARAM( unsigned long long, XN_STREAM_PROPERTY_ZERO_PLANE_DISTANCE );
            SET_PARAM( double, XN_STREAM_PROPERTY_ZERO_PLANE_PIXEL_SIZE );
            SET_PARAM( double, XN_STREAM_PROPERTY_EMITTER_DCMOS_DISTANCE );
            SET_PARAM( double, XN_STREAM_PROPERTY_DCMOS_RCMOS_DISTANCE );
#undef SET_PARAM
        }
    }
}

void OpenNiVideo2::SetDepthCloseRange(bool enable)
{
    // Set this property on all devices. It doesn't matter if it fails.
    for(int i=0; i<2; ++i) {
        video_stream[i].setProperty(XN_STREAM_PROPERTY_CLOSE_RANGE, enable);
    }
}

void OpenNiVideo2::SetDepthHoleFilter(bool enable)
{
    // Set this property on all devices. It doesn't matter if it fails.
    for(int i=0; i<2; ++i) {
        video_stream[i].setProperty(XN_STREAM_PROPERTY_HOLE_FILTER, enable);
        video_stream[i].setProperty(XN_STREAM_PROPERTY_GAIN,50);
    }
}

void OpenNiVideo2::SetDepthColorSyncEnabled(bool enable)
{
    device.setDepthColorSyncEnabled(enable);
}

void OpenNiVideo2::SetRegisterDepthToImage(bool enable)
{
    if(enable) {
        device.setImageRegistrationMode(openni::IMAGE_REGISTRATION_DEPTH_TO_COLOR);
    }else{
        device.setImageRegistrationMode(openni::IMAGE_REGISTRATION_OFF);
    }
}

OpenNiVideo2::~OpenNiVideo2()
{
    Stop();

    for(int i=0; i<2; ++i) {
        if( video_stream[i].isValid()) {
            video_stream[i].destroy();
        }
    }

    openni::OpenNI::shutdown();
}

size_t OpenNiVideo2::SizeBytes() const
{
    return sizeBytes;
}

const std::vector<StreamInfo>& OpenNiVideo2::Streams() const
{
    return streams;
}

void OpenNiVideo2::Start()
{
    for(int i=0; i<2; ++i) {
        video_stream[i].start();
    }
}

void OpenNiVideo2::Stop()
{
    for(int i=0; i<2; ++i) {
        video_stream[i].stop();
    }
}

bool OpenNiVideo2::GrabNext( unsigned char* image, bool wait )
{
    unsigned char* out_img = image;

    openni::Status rc;

    for(int i=0; i<2; ++i) {
        if(sensor_type[i] == OpenNiUnassigned) {
            rc = openni::STATUS_OK;
            continue;
        }

        if(!video_stream[i].isValid()) {
            rc = openni::STATUS_NO_DEVICE;
            continue;
        }

        if(use_ir_and_rgb) video_stream[i].start();

        rc = video_stream[i].readFrame(&video_frame[i]);
        if(rc != openni::STATUS_OK) {
            pango_print_error("Error reading frame:\n%s", openni::OpenNI::getExtendedError() );
        }

        const bool toGreyscale = false;
        if(toGreyscale) {
            const int w = streams[i].Width();
            const int h = streams[i].Height();

            openni::RGB888Pixel* pColour = (openni::RGB888Pixel*)video_frame[i].getData();
            for(int i = 0 ; i  < w*h;i++){
                openni::RGB888Pixel rgb = pColour[i];
                int grey = ((int)(rgb.r&0xFF) +  (int)(rgb.g&0xFF) + (int)(rgb.b&0xFF))/3;
                grey = std::min(255,std::max(0,grey));
                out_img[i] = grey;
            }
        }else{
            memcpy(out_img, video_frame[i].getData(), streams[i].SizeBytes());
        }

        // update frame properties
        (*streams_properties)[i]["devtime_us"] = video_frame[i].getTimestamp();

        if(use_ir_and_rgb) video_stream[i].stop();

        out_img += streams[i].SizeBytes();
    }

    return rc == openni::STATUS_OK;
}

bool OpenNiVideo2::GrabNewest( unsigned char* image, bool wait )
{
    return GrabNext(image,wait);
}

}
<|endoftext|>


<commit_before>/* **** **** **** **** **** **** **** **** *
 *
 *         _/        _/        _/
 *        _/_/_/    _/_/_/    _/_/_/
 *       _/    _/  _/    _/  _/    _/
 *      _/    _/  _/    _/  _/    _/
 *     _/_/_/    _/_/_/    _/_/_/
 *
 * bit by bit
 * bbb/core/type/sequence/integer_range.hpp
 *
 * author: ISHII 2bit
 * mail:   bit_by_bit@2bit.jp
 *
 * **** **** **** **** **** **** **** **** */

#pragma once

#include <bbb/core/tmp/traits.hpp>
#include <bbb/core/tmp/utility.hpp>
#include <bbb/core/tmp/integer_sequence/integer_sequence.hpp>
#include <bbb/core/tmp/integer_sequence/sequence_operation.hpp>

namespace bbb {
    namespace sequence_range {
        namespace detail {
            template <typename integer_type, integer_type from, integer_type to, integer_type offset = 1>
            struct integer_range {
                using back_sequence = integer_range<integer_type, from + offset, to, offset>;
                using type = resolve_t<conditional_t<
                    from + offset <= to,
                    defer<sequence_prepend<integer_type, get_type<back_sequence>, from>>,
                    back_sequence
                >>;
            };

            template <typename integer_type, integer_type n, integer_type offset>
            struct integer_range<integer_type, n, n, offset> {
                using type = integer_sequence<integer_type>;
            };
        };

        template <typename integer_type, integer_type from, integer_type to, integer_type offset = 1>
        using integer_range = detail::integer_range<integer_type, from, to, offset>;
        template <typename integer_type, integer_type from, integer_type to, integer_type offset = 1>
        using integer_range_t = get_type<integer_range<integer_type, from, to, offset>>;

        template <std::size_t from, std::size_t to, std::size_t offset = 1>
        using index_range = integer_range<std::size_t, from, to, offset>;
        template <std::size_t from, std::size_t to, std::size_t offset = 1>
        using index_range_t = get_type<index_range<from, to, offset>>;

#ifdef BBB_EXEC_UNIT_TEST
        namespace integer_range_test {
            using test1 = unit_test::assert<
                index_range_t<0, 4>,
                index_sequence<0, 1, 2, 3>
            >;
        };
#endif
    };

    using namespace sequence_range;
};
<commit_msg>fix integer_range<commit_after>/* **** **** **** **** **** **** **** **** *
 *
 *         _/        _/        _/
 *        _/_/_/    _/_/_/    _/_/_/
 *       _/    _/  _/    _/  _/    _/
 *      _/    _/  _/    _/  _/    _/
 *     _/_/_/    _/_/_/    _/_/_/
 *
 * bit by bit
 * bbb/core/type/sequence/integer_range.hpp
 *
 * author: ISHII 2bit
 * mail:   bit_by_bit@2bit.jp
 *
 * **** **** **** **** **** **** **** **** */

#pragma once

#include <bbb/core/tmp/traits.hpp>
#include <bbb/core/tmp/utility.hpp>
#include <bbb/core/tmp/integer_sequence/integer_sequence.hpp>
#include <bbb/core/tmp/integer_sequence/sequence_operation.hpp>

namespace bbb {
    namespace sequence_range {
        namespace detail {
            template <typename integer_type, typename sequence, integer_type val>
            struct deferred_prepend {
                using type = sequence_prepend_t<integer_type, get_type<sequence>, val>;
            };

            template <typename integer_type, integer_type from, integer_type to, integer_type offset = 1>
            struct integer_range {
                using type = resolve_t<conditional_t<
                    from + offset < to,
                    deferred_prepend<integer_type, integer_range<integer_type, from + offset, to, offset>, from>,
                    defer<integer_sequence<integer_type, from>>
                >>;
            };
        };

        template <typename integer_type, integer_type from, integer_type to, integer_type offset = 1>
        using integer_range = detail::integer_range<integer_type, from, to, offset>;
        template <typename integer_type, integer_type from, integer_type to, integer_type offset = 1>
        using integer_range_t = get_type<integer_range<integer_type, from, to, offset>>;

        template <std::size_t from, std::size_t to, std::size_t offset = 1>
        using index_range = integer_range<std::size_t, from, to, offset>;
        template <std::size_t from, std::size_t to, std::size_t offset = 1>
        using index_range_t = get_type<index_range<from, to, offset>>;

#ifdef BBB_EXEC_UNIT_TEST
        namespace integer_range_test {
            using test1 = unit_test::assert<
                index_range_t<0, 4>,
                index_sequence<0, 1, 2, 3>
            >;
            using test2 = unit_test::assert<
                index_range_t<0, 4, 2>,
                index_sequence<0, 2>
            >;
            using test3 = unit_test::assert<
                index_range_t<0, 4, 3>,
                index_sequence<0, 3>
            >;
            using test4 = unit_test::assert<
                index_range_t<0, 4, 4>,
                index_sequence<0>
            >;
            using test5 = unit_test::assert<
                index_range_t<1, 4>,
                index_sequence<1, 2, 3>
            >;
        };
#endif
    };

    using namespace sequence_range;
};
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: fuhhconv.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: rt $ $Date: 2007-04-03 16:01:00 $
 *
 *  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_sd.hxx"

#ifndef _COM_SUN_STAR_I18N_TEXTCONVERSIONOPTION_HPP_
#include <com/sun/star/i18n/TextConversionOption.hpp>
#endif

#include <com/sun/star/ui/dialogs/XExecutableDialog.hpp>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <cppuhelper/bootstrap.hxx>
#include <vcl/msgbox.hxx>

#ifndef _SFXSTYLE_HXX
#include <svtools/style.hxx>
#endif

#ifndef _EEITEM_HXX
#include <svx/eeitem.hxx>
#endif

#define ITEMID_LANGUAGE EE_CHAR_LANGUAGE_CJK
#ifndef _SVX_LANGITEM_HXX
#include <svx/langitem.hxx>
#endif
#define ITEMID_FONT EE_CHAR_FONTINFO_CJK
#ifndef _SVX_FONTITEM_HXX
#include <svx/fontitem.hxx>
#endif

#include <fuhhconv.hxx>
#include "drawdoc.hxx"
#include "Outliner.hxx"
#include "DrawViewShell.hxx"
#include "OutlineViewShell.hxx"
#include "Window.hxx"

#ifndef SD_VIEW_SHELL_BASE_HXX
#include "ViewShellBase.hxx"
#endif

#include "sdresid.hxx"
#include "strings.hrc"

class SfxRequest;

#define C2U(cChar)  rtl::OUString::createFromAscii(cChar)

using namespace ::com::sun::star;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::uno;

namespace sd {

class ViewShell;

TYPEINIT1( FuHangulHanjaConversion, FuPoor );

/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/

FuHangulHanjaConversion::FuHangulHanjaConversion (
    ViewShell* pViewSh,
    ::sd::Window* pWin,
    ::sd::View* pView,
    SdDrawDocument* pDocument,
    SfxRequest& rReq )
       : FuPoor(pViewSh, pWin, pView, pDocument, rReq),
    pSdOutliner(NULL),
    bOwnOutliner(FALSE)
{
    if ( mpViewShell->ISA(DrawViewShell) )
    {
        bOwnOutliner = TRUE;
        pSdOutliner = new Outliner( mpDoc, OUTLINERMODE_TEXTOBJECT );
    }
    else if ( mpViewShell->ISA(OutlineViewShell) )
    {
        bOwnOutliner = FALSE;
        pSdOutliner = mpDoc->GetOutliner();
    }

    if (pSdOutliner)
       pSdOutliner->PrepareSpelling();
}

/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/

FuHangulHanjaConversion::~FuHangulHanjaConversion()
{
    if (pSdOutliner)
        pSdOutliner->EndConversion();

    if (bOwnOutliner)
        delete pSdOutliner;
}

FunctionReference FuHangulHanjaConversion::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )
{
    FunctionReference xFunc( new FuHangulHanjaConversion( pViewSh, pWin, pView, pDoc, rReq ) );
    return xFunc;
}

/*************************************************************************
|*
|* Suchen&Ersetzen
|*
\************************************************************************/

void FuHangulHanjaConversion::StartConversion( INT16 nSourceLanguage, INT16 nTargetLanguage,
        const Font *pTargetFont, INT32 nOptions, BOOL bIsInteractive )
{

    String aString( SdResId(STR_UNDO_HANGULHANJACONVERSION) );
    mpView->BegUndo( aString );

    ViewShellBase* pBase = PTR_CAST(ViewShellBase, SfxViewShell::Current());
    if (pBase != NULL)
        mpViewShell = pBase->GetMainViewShell().get();

    if( mpViewShell )
    {
        if ( pSdOutliner && mpViewShell->ISA(DrawViewShell) && !bOwnOutliner )
        {
            pSdOutliner->EndConversion();

            bOwnOutliner = TRUE;
            pSdOutliner = new Outliner( mpDoc, OUTLINERMODE_TEXTOBJECT );
            pSdOutliner->BeginConversion();
        }
        else if ( pSdOutliner && mpViewShell->ISA(OutlineViewShell) && bOwnOutliner )
        {
            pSdOutliner->EndConversion();
            delete pSdOutliner;

            bOwnOutliner = FALSE;
            pSdOutliner = mpDoc->GetOutliner();
            pSdOutliner->BeginConversion();
        }

        if (pSdOutliner)
            pSdOutliner->StartConversion(nSourceLanguage, nTargetLanguage, pTargetFont, nOptions, bIsInteractive );
    }

    // Due to changing between edit mode, notes mode, and handout mode the
    // view has most likely changed.  Get the new one.
    mpViewShell = pBase->GetMainViewShell().get();
    if (mpViewShell != NULL)
    {
        mpView = mpViewShell->GetView();
        mpWindow = mpViewShell->GetActiveWindow();
    }
    else
    {
        mpView = 0;
        mpWindow = NULL;
    }

    if (mpView != NULL)
        mpView->EndUndo();
}

void FuHangulHanjaConversion::ConvertStyles( INT16 nTargetLanguage, const Font *pTargetFont )
{
    if( !mpDoc )
        return;

    SfxStyleSheetBasePool* pStyleSheetPool = mpDoc->GetStyleSheetPool();
    if( !pStyleSheetPool )
        return;

    SfxStyleSheetBase* pStyle = pStyleSheetPool->First();
    while( pStyle )
    {
        SfxItemSet& rSet = pStyle->GetItemSet();

        const bool bHasParent = pStyle->GetParent().Len() != 0;

        if( !bHasParent || rSet.GetItemState( EE_CHAR_LANGUAGE_CJK, FALSE ) == SFX_ITEM_SET )
            rSet.Put( SvxLanguageItem( nTargetLanguage, EE_CHAR_LANGUAGE_CJK ) );

        if( pTargetFont &&
            ( !bHasParent || rSet.GetItemState( EE_CHAR_FONTINFO_CJK, FALSE ) == SFX_ITEM_SET ) )
        {
            // set new font attribute
            SvxFontItem aFontItem( (SvxFontItem&) rSet.Get( EE_CHAR_FONTINFO_CJK ) );
            aFontItem.GetFamilyName()   = pTargetFont->GetName();
            aFontItem.GetFamily()       = pTargetFont->GetFamily();
            aFontItem.GetStyleName()    = pTargetFont->GetStyleName();
            aFontItem.GetPitch()        = pTargetFont->GetPitch();
            aFontItem.GetCharSet()      = pTargetFont->GetCharSet();
            rSet.Put( aFontItem );
        }

        pStyle = pStyleSheetPool->Next();
    }

    mpDoc->SetLanguage( EE_CHAR_LANGUAGE_CJK, nTargetLanguage );
}

void FuHangulHanjaConversion::StartChineseConversion()
{
    //open ChineseTranslationDialog
    Reference< XComponentContext > xContext(
        ::cppu::defaultBootstrap_InitialComponentContext() ); //@todo get context from calc if that has one
    if(xContext.is())
    {
        Reference< lang::XMultiComponentFactory > xMCF( xContext->getServiceManager() );
        if(xMCF.is())
        {
            Reference< ui::dialogs::XExecutableDialog > xDialog(
                    xMCF->createInstanceWithContext(
                        rtl::OUString::createFromAscii("com.sun.star.linguistic2.ChineseTranslationDialog")
                        , xContext), UNO_QUERY);
            Reference< lang::XInitialization > xInit( xDialog, UNO_QUERY );
            if( xInit.is() )
            {
                //  initialize dialog
                Reference< awt::XWindow > xDialogParentWindow(0);
                Sequence<Any> aSeq(1);
                Any* pArray = aSeq.getArray();
                PropertyValue aParam;
                aParam.Name = rtl::OUString::createFromAscii("ParentWindow");
                aParam.Value <<= makeAny(xDialogParentWindow);
                pArray[0] <<= makeAny(aParam);
                xInit->initialize( aSeq );

                //execute dialog
                sal_Int16 nDialogRet = xDialog->execute();
                if( RET_OK == nDialogRet )
                {
                    //get some parameters from the dialog
                    sal_Bool bToSimplified = sal_True;
                    sal_Bool bUseVariants = sal_True;
                    sal_Bool bCommonTerms = sal_True;
                    Reference< beans::XPropertySet >  xProp( xDialog, UNO_QUERY );
                    if( xProp.is() )
                    {
                        try
                        {
                            xProp->getPropertyValue( C2U("IsDirectionToSimplified") ) >>= bToSimplified;
                            xProp->getPropertyValue( C2U("IsUseCharacterVariants") ) >>= bUseVariants;
                            xProp->getPropertyValue( C2U("IsTranslateCommonTerms") ) >>= bCommonTerms;
                        }
                        catch( Exception& )
                        {
                        }
                    }

                    //execute translation
                    sal_Int16 nSourceLang = bToSimplified ? LANGUAGE_CHINESE_TRADITIONAL : LANGUAGE_CHINESE_SIMPLIFIED;
                    sal_Int16 nTargetLang = bToSimplified ? LANGUAGE_CHINESE_SIMPLIFIED : LANGUAGE_CHINESE_TRADITIONAL;
                    sal_Int32 nOptions    = bUseVariants ? i18n::TextConversionOption::USE_CHARACTER_VARIANTS : 0;
                    if( !bCommonTerms )
                        nOptions = nOptions | i18n::TextConversionOption::CHARACTER_BY_CHARACTER;

                    Font aTargetFont = mpWindow->GetDefaultFont(
                                        DEFAULTFONT_CJK_PRESENTATION,
                                        nTargetLang, DEFAULTFONT_FLAGS_ONLYONE );

                    StartConversion( nSourceLang, nTargetLang, &aTargetFont, nOptions, sal_False );
                    ConvertStyles( nTargetLang, &aTargetFont );
                }
            }
            Reference< lang::XComponent > xComponent( xDialog, UNO_QUERY );
            if( xComponent.is() )
                xComponent->dispose();
        }
    }
}
} // end of namespace
<commit_msg>INTEGRATION: CWS pchfix04 (1.10.6); FILE MERGED 2007/04/25 22:31:54 hjs 1.10.6.3: RESYNC: (1.10-1.11); FILE MERGED 2007/02/05 08:38:58 os 1.10.6.2: #i73604# usage of ITEMID_* removed 2007/01/19 10:49:57 hjs 1.10.6.1: #i73650# warning free with pch<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: fuhhconv.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: kz $ $Date: 2007-05-10 15:30:04 $
 *
 *  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_sd.hxx"

#ifndef _COM_SUN_STAR_I18N_TEXTCONVERSIONOPTION_HPP_
#include <com/sun/star/i18n/TextConversionOption.hpp>
#endif

#include <com/sun/star/ui/dialogs/XExecutableDialog.hpp>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <cppuhelper/bootstrap.hxx>
#include <vcl/msgbox.hxx>

#ifndef _SFXSTYLE_HXX
#include <svtools/style.hxx>
#endif

#ifndef _EEITEM_HXX
#include <svx/eeitem.hxx>
#endif

#ifndef _SVX_LANGITEM_HXX
#include <svx/langitem.hxx>
#endif
#ifndef _SVX_FONTITEM_HXX
#include <svx/fontitem.hxx>
#endif

#include <fuhhconv.hxx>
#include "drawdoc.hxx"
#include "Outliner.hxx"
#include "DrawViewShell.hxx"
#include "OutlineViewShell.hxx"
#include "Window.hxx"

#ifndef SD_VIEW_SHELL_BASE_HXX
#include "ViewShellBase.hxx"
#endif

#include "sdresid.hxx"
#include "strings.hrc"

class SfxRequest;

#define C2U(cChar)  rtl::OUString::createFromAscii(cChar)

using namespace ::com::sun::star;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::uno;

namespace sd {

class ViewShell;

TYPEINIT1( FuHangulHanjaConversion, FuPoor );

/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/

FuHangulHanjaConversion::FuHangulHanjaConversion (
    ViewShell* pViewSh,
    ::sd::Window* pWin,
    ::sd::View* pView,
    SdDrawDocument* pDocument,
    SfxRequest& rReq )
       : FuPoor(pViewSh, pWin, pView, pDocument, rReq),
    pSdOutliner(NULL),
    bOwnOutliner(FALSE)
{
    if ( mpViewShell->ISA(DrawViewShell) )
    {
        bOwnOutliner = TRUE;
        pSdOutliner = new Outliner( mpDoc, OUTLINERMODE_TEXTOBJECT );
    }
    else if ( mpViewShell->ISA(OutlineViewShell) )
    {
        bOwnOutliner = FALSE;
        pSdOutliner = mpDoc->GetOutliner();
    }

    if (pSdOutliner)
       pSdOutliner->PrepareSpelling();
}

/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/

FuHangulHanjaConversion::~FuHangulHanjaConversion()
{
    if (pSdOutliner)
        pSdOutliner->EndConversion();

    if (bOwnOutliner)
        delete pSdOutliner;
}

FunctionReference FuHangulHanjaConversion::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )
{
    FunctionReference xFunc( new FuHangulHanjaConversion( pViewSh, pWin, pView, pDoc, rReq ) );
    return xFunc;
}

/*************************************************************************
|*
|* Suchen&Ersetzen
|*
\************************************************************************/

void FuHangulHanjaConversion::StartConversion( INT16 nSourceLanguage, INT16 nTargetLanguage,
        const Font *pTargetFont, INT32 nOptions, BOOL bIsInteractive )
{

    String aString( SdResId(STR_UNDO_HANGULHANJACONVERSION) );
    mpView->BegUndo( aString );

    ViewShellBase* pBase = PTR_CAST(ViewShellBase, SfxViewShell::Current());
    if (pBase != NULL)
        mpViewShell = pBase->GetMainViewShell().get();

    if( mpViewShell )
    {
        if ( pSdOutliner && mpViewShell->ISA(DrawViewShell) && !bOwnOutliner )
        {
            pSdOutliner->EndConversion();

            bOwnOutliner = TRUE;
            pSdOutliner = new Outliner( mpDoc, OUTLINERMODE_TEXTOBJECT );
            pSdOutliner->BeginConversion();
        }
        else if ( pSdOutliner && mpViewShell->ISA(OutlineViewShell) && bOwnOutliner )
        {
            pSdOutliner->EndConversion();
            delete pSdOutliner;

            bOwnOutliner = FALSE;
            pSdOutliner = mpDoc->GetOutliner();
            pSdOutliner->BeginConversion();
        }

        if (pSdOutliner)
            pSdOutliner->StartConversion(nSourceLanguage, nTargetLanguage, pTargetFont, nOptions, bIsInteractive );
    }

    // Due to changing between edit mode, notes mode, and handout mode the
    // view has most likely changed.  Get the new one.
    mpViewShell = pBase->GetMainViewShell().get();
    if (mpViewShell != NULL)
    {
        mpView = mpViewShell->GetView();
        mpWindow = mpViewShell->GetActiveWindow();
    }
    else
    {
        mpView = 0;
        mpWindow = NULL;
    }

    if (mpView != NULL)
        mpView->EndUndo();
}

void FuHangulHanjaConversion::ConvertStyles( INT16 nTargetLanguage, const Font *pTargetFont )
{
    if( !mpDoc )
        return;

    SfxStyleSheetBasePool* pStyleSheetPool = mpDoc->GetStyleSheetPool();
    if( !pStyleSheetPool )
        return;

    SfxStyleSheetBase* pStyle = pStyleSheetPool->First();
    while( pStyle )
    {
        SfxItemSet& rSet = pStyle->GetItemSet();

        const bool bHasParent = pStyle->GetParent().Len() != 0;

        if( !bHasParent || rSet.GetItemState( EE_CHAR_LANGUAGE_CJK, FALSE ) == SFX_ITEM_SET )
            rSet.Put( SvxLanguageItem( nTargetLanguage, EE_CHAR_LANGUAGE_CJK ) );

        if( pTargetFont &&
            ( !bHasParent || rSet.GetItemState( EE_CHAR_FONTINFO_CJK, FALSE ) == SFX_ITEM_SET ) )
        {
            // set new font attribute
            SvxFontItem aFontItem( (SvxFontItem&) rSet.Get( EE_CHAR_FONTINFO_CJK ) );
            aFontItem.GetFamilyName()   = pTargetFont->GetName();
            aFontItem.GetFamily()       = pTargetFont->GetFamily();
            aFontItem.GetStyleName()    = pTargetFont->GetStyleName();
            aFontItem.GetPitch()        = pTargetFont->GetPitch();
            aFontItem.GetCharSet()      = pTargetFont->GetCharSet();
            rSet.Put( aFontItem );
        }

        pStyle = pStyleSheetPool->Next();
    }

    mpDoc->SetLanguage( EE_CHAR_LANGUAGE_CJK, nTargetLanguage );
}

void FuHangulHanjaConversion::StartChineseConversion()
{
    //open ChineseTranslationDialog
    Reference< XComponentContext > xContext(
        ::cppu::defaultBootstrap_InitialComponentContext() ); //@todo get context from calc if that has one
    if(xContext.is())
    {
        Reference< lang::XMultiComponentFactory > xMCF( xContext->getServiceManager() );
        if(xMCF.is())
        {
            Reference< ui::dialogs::XExecutableDialog > xDialog(
                    xMCF->createInstanceWithContext(
                        rtl::OUString::createFromAscii("com.sun.star.linguistic2.ChineseTranslationDialog")
                        , xContext), UNO_QUERY);
            Reference< lang::XInitialization > xInit( xDialog, UNO_QUERY );
            if( xInit.is() )
            {
                //  initialize dialog
                Reference< awt::XWindow > xDialogParentWindow(0);
                Sequence<Any> aSeq(1);
                Any* pArray = aSeq.getArray();
                PropertyValue aParam;
                aParam.Name = rtl::OUString::createFromAscii("ParentWindow");
                aParam.Value <<= makeAny(xDialogParentWindow);
                pArray[0] <<= makeAny(aParam);
                xInit->initialize( aSeq );

                //execute dialog
                sal_Int16 nDialogRet = xDialog->execute();
                if( RET_OK == nDialogRet )
                {
                    //get some parameters from the dialog
                    sal_Bool bToSimplified = sal_True;
                    sal_Bool bUseVariants = sal_True;
                    sal_Bool bCommonTerms = sal_True;
                    Reference< beans::XPropertySet >  xProp( xDialog, UNO_QUERY );
                    if( xProp.is() )
                    {
                        try
                        {
                            xProp->getPropertyValue( C2U("IsDirectionToSimplified") ) >>= bToSimplified;
                            xProp->getPropertyValue( C2U("IsUseCharacterVariants") ) >>= bUseVariants;
                            xProp->getPropertyValue( C2U("IsTranslateCommonTerms") ) >>= bCommonTerms;
                        }
                        catch( Exception& )
                        {
                        }
                    }

                    //execute translation
                    sal_Int16 nSourceLang = bToSimplified ? LANGUAGE_CHINESE_TRADITIONAL : LANGUAGE_CHINESE_SIMPLIFIED;
                    sal_Int16 nTargetLang = bToSimplified ? LANGUAGE_CHINESE_SIMPLIFIED : LANGUAGE_CHINESE_TRADITIONAL;
                    sal_Int32 nOptions    = bUseVariants ? i18n::TextConversionOption::USE_CHARACTER_VARIANTS : 0;
                    if( !bCommonTerms )
                        nOptions = nOptions | i18n::TextConversionOption::CHARACTER_BY_CHARACTER;

                    Font aTargetFont = mpWindow->GetDefaultFont(
                                        DEFAULTFONT_CJK_PRESENTATION,
                                        nTargetLang, DEFAULTFONT_FLAGS_ONLYONE );

                    StartConversion( nSourceLang, nTargetLang, &aTargetFont, nOptions, sal_False );
                    ConvertStyles( nTargetLang, &aTargetFont );
                }
            }
            Reference< lang::XComponent > xComponent( xDialog, UNO_QUERY );
            if( xComponent.is() )
                xComponent->dispose();
        }
    }
}
} // end of namespace
<|endoftext|>


<commit_before><commit_msg>sd LOKit callback for search not found<commit_after><|endoftext|>


<commit_before>/*
  Copyright:        Copyright (C) 2003-2018 SIL International.
  Authors:          mcdurdin
*/
#include <vector>
#include <iterator>
#include <codecvt>
#include <locale>
#include "kmx_processevent.h"
#include "utfcodec.hpp"

using namespace km::kbp;
using namespace kmx;

const km_kbp_cp *km::kbp::kmx::u16chr(const km_kbp_cp *p, km_kbp_cp ch) {
  while (*p) {
    if (*p == ch) return p;
    p++;
  }
  return ch == 0 ? p : NULL;
}

const km_kbp_cp *km::kbp::kmx::u16cpy(km_kbp_cp *dst, const km_kbp_cp *src) {
  km_kbp_cp *o = dst;
  while (*src) {
    *dst++ = *src++;
  }
  *dst = 0;
  return o;
}

const km_kbp_cp *km::kbp::kmx::u16ncpy(km_kbp_cp *dst, const km_kbp_cp *src, size_t max) {
  km_kbp_cp *o = dst;
  while (*src && max > 0) {
    *dst++ = *src++;
    max--;
  }
  while(max > 0) {
    *dst++ = 0;
    max--;
  }
  return o;
}

size_t km::kbp::kmx::u16len(const km_kbp_cp *p) {
  int i = 0;
  while (*p) {
    p++;
    i++;
  }
  return i;
}

int km::kbp::kmx::u16cmp(const km_kbp_cp *p, const km_kbp_cp *q) {
  while (*p && *q) {
    if (*p != *q) return *p - *q;
    p++;
    q++;
  }
  return *p - *q;
}

int km::kbp::kmx::u16icmp(const km_kbp_cp *p, const km_kbp_cp *q) {
  while (*p && *q) {
    if (toupper(*p) != toupper(*q)) return *p - *q;
    p++;
    q++;
  }
  return *p - *q;
}

int km::kbp::kmx::u16ncmp(const km_kbp_cp *p, const km_kbp_cp *q, size_t count) {
  while (*p && *q && count) {
    if (*p != *q) return *p - *q;
    p++;
    q++;
    count--;
  }
  if (count)
    return *p - *q;
  return 0;
}

km_kbp_cp *km::kbp::kmx::u16tok(km_kbp_cp *p, km_kbp_cp ch, km_kbp_cp **ctx) {
  if (!p) {
    p = *ctx;
    if (!p) return NULL;
  }

  km_kbp_cp *q = p;
  while (*q && *q != ch) {
    q++;
  }
  if (*q) {
    *q = 0;
    q++;
    while (*q == ch) q++;
    *ctx = q;
  }
  else {
    *ctx = NULL;
  }
  return p;
}

/*
* int xstrlen( PKMX_BYTE p );
*
* Parameters: p Pointer to string to get length of
*
* Returns:    length of string
*
*   Called by:  various functions
*
* xstrlen calculates the length of a string, ignoring some special chars.
*/

PKMX_WCHAR km::kbp::kmx::incxstr(PKMX_WCHAR p)
{
  int deltaptr;			// how many bytes to jump over

  if (*p == 0) return p;
  if (*p != UC_SENTINEL)
  {
    if (*p >= 0xD800 && *p <= 0xDBFF && *(p + 1) >= 0xDC00 && *(p + 1) <= 0xDFFF) return p + 2;
    return p + 1;
  }
  else
  {
    // UC_SENTINEL(FFFF) with UC_SENTINEL_EXTENDEDEND(0x10) == variable length
    if (*(p + 1) == CODE_EXTENDED) {
      p += 2;
      while (*(p - 1) && *p && *p != UC_SENTINEL_EXTENDEDEND)
        p++;

      if (*p == 0) return p;
      if (*p == UC_SENTINEL_EXTENDEDEND)		return p + 1;
    }

    //  UC_SENTINEL(FFFF) followed by other special
    switch (*(p + 1))
    {
    case CODE_ANY:						deltaptr = 3; break;
    case CODE_NOTANY:					deltaptr = 3; break;
    case CODE_INDEX:					deltaptr = 4; break;
    case CODE_USE:						deltaptr = 3; break;
    case CODE_DEADKEY:				deltaptr = 3; break;
    case CODE_CLEARCONTEXT:		deltaptr = 3; break;
    case CODE_CALL:						deltaptr = 3; break;
    case CODE_CONTEXTEX:			deltaptr = 3; break;
    case CODE_IFOPT:          deltaptr = 5; break;
    case CODE_IFSYSTEMSTORE:	deltaptr = 5; break;
    case CODE_SETOPT:					deltaptr = 4; break;
    case CODE_SETSYSTEMSTORE:	deltaptr = 4; break;
    case CODE_RESETOPT:				deltaptr = 3; break;
    case CODE_SAVEOPT:				deltaptr = 3; break;
    default:									deltaptr = 2;
    }

    // check for \0 between FFFF and next printable character
    for (int i = 0; i < (deltaptr); i++) {
      if (*p==0)
        return p;
      p += 1;    }
    return p;

  }
  return p;

}

PKMX_WCHAR km::kbp::kmx::decxstr(PKMX_WCHAR p, PKMX_WCHAR pStart)
{
  if(p <= pStart) {
    return NULL;
  }

  p--;
  if(*p == UC_SENTINEL_EXTENDEDEND)
  {
    int n = 0;
    while(*p != UC_SENTINEL && n < 10) { p--; n++; }

    if(p < pStart) {
      // May be a malformed virtual key
      return pStart;
    }
    return p;
  }

  if(p == pStart) return p; // Don't allow test before pStart

  if(*p >= 0xDC00 && *p <= 0xDFFF && *(p-1) >= 0xD800 && *(p-1) <= 0xDBFF)
  {
    return p-1;
  }
  else if(*(p-1) == UC_SENTINEL) return p-1;
  else if(p > pStart+1 && *(p-2) == UC_SENTINEL)
  {
    switch(*(p-1))
    {
      case CODE_ANY:
      case CODE_NOTANY:
      case CODE_USE:
      case CODE_DEADKEY:
      case CODE_CLEARCONTEXT:
      case CODE_CALL:
      case CODE_CONTEXTEX:
      case CODE_RESETOPT:
      case CODE_SAVEOPT:
        return p-2;
    }
  }
  else if(p > pStart+2 && *(p-3) == UC_SENTINEL)
  {
    switch(*(p-2))
    {
      case CODE_INDEX:
      case CODE_SETOPT:
      case CODE_SETSYSTEMSTORE:
        return p-3;
    }
  }
  else if(p > pStart+3 && *(p-4) == UC_SENTINEL)
  {
    switch(*(p-3))
    {
      case CODE_IFOPT:
      case CODE_IFSYSTEMSTORE:  // I3432
        return p-4;
    }
  }
  return p;
}

int km::kbp::kmx::xstrlen_ignoreifopt(PKMX_WCHAR p)
{
  int i;
  for(i = 0; *p; i++, p=incxstr(p))
  {
    if(*p == UC_SENTINEL && (*(p+1) == CODE_IFOPT || *(p+1) == CODE_IFSYSTEMSTORE)) i--;  // I3432
  }
  return i;
}

int km::kbp::kmx::xstrlen(PKMX_WCHAR p)
{
  int i;
  for(i = 0; *p; i++, p=incxstr(p));
  return i;
}

int km::kbp::kmx::xstrpos(PKMX_WCHAR p1, PKMX_WCHAR p)
{
  int i;
  for(i = 0; p < p1; p = incxstr(p), i++);
  return i;
}

PKMX_WCHAR km::kbp::kmx::xstrchr(PKMX_WCHAR buf, PKMX_WCHAR chr)
{
  for(PKMX_WCHAR q = incxstr(buf); *buf; buf = q, q = incxstr(buf))
    if(!u16ncmp(buf, chr, (intptr_t)(q-buf)))
      return buf;
  return NULL;
}

int km::kbp::kmx::xchrcmp(PKMX_WCHAR ch1, PKMX_WCHAR ch2)
{
  PKMX_WCHAR nch1 = incxstr(ch1);
  if(nch1 == ch1) return *ch2 - *ch1; /* comparing *ch2 to nul */
  return u16ncmp(ch1, ch2, (intptr_t)(nch1-ch1));
}

PKMX_WCHAR km::kbp::kmx::strtowstr(PKMX_CHAR in)
{
  PKMX_WCHAR result;

  auto s = convert<char,char16_t>(in);
  result = new char16_t[s.length() + 1];
  s.copy(result, s.length());
  result[s.length()] = 0;
  return result;
}

PKMX_CHAR km::kbp::kmx::wstrtostr(PKMX_WCHAR in)
{
  PKMX_CHAR result;

  auto s = convert<char16_t,char>(in);
  result = new char[s.length() + 1];
  s.copy(result, s.length());
  result[s.length()] = 0;
  return result;
}
<commit_msg>Update common/core/desktop/src/kmx/kmx_xstring.cpp<commit_after>/*
  Copyright:        Copyright (C) 2003-2018 SIL International.
  Authors:          mcdurdin
*/
#include <vector>
#include <iterator>
#include <codecvt>
#include <locale>
#include "kmx_processevent.h"
#include "utfcodec.hpp"

using namespace km::kbp;
using namespace kmx;

const km_kbp_cp *km::kbp::kmx::u16chr(const km_kbp_cp *p, km_kbp_cp ch) {
  while (*p) {
    if (*p == ch) return p;
    p++;
  }
  return ch == 0 ? p : NULL;
}

const km_kbp_cp *km::kbp::kmx::u16cpy(km_kbp_cp *dst, const km_kbp_cp *src) {
  km_kbp_cp *o = dst;
  while (*src) {
    *dst++ = *src++;
  }
  *dst = 0;
  return o;
}

const km_kbp_cp *km::kbp::kmx::u16ncpy(km_kbp_cp *dst, const km_kbp_cp *src, size_t max) {
  km_kbp_cp *o = dst;
  while (*src && max > 0) {
    *dst++ = *src++;
    max--;
  }
  while(max > 0) {
    *dst++ = 0;
    max--;
  }
  return o;
}

size_t km::kbp::kmx::u16len(const km_kbp_cp *p) {
  int i = 0;
  while (*p) {
    p++;
    i++;
  }
  return i;
}

int km::kbp::kmx::u16cmp(const km_kbp_cp *p, const km_kbp_cp *q) {
  while (*p && *q) {
    if (*p != *q) return *p - *q;
    p++;
    q++;
  }
  return *p - *q;
}

int km::kbp::kmx::u16icmp(const km_kbp_cp *p, const km_kbp_cp *q) {
  while (*p && *q) {
    if (toupper(*p) != toupper(*q)) return *p - *q;
    p++;
    q++;
  }
  return *p - *q;
}

int km::kbp::kmx::u16ncmp(const km_kbp_cp *p, const km_kbp_cp *q, size_t count) {
  while (*p && *q && count) {
    if (*p != *q) return *p - *q;
    p++;
    q++;
    count--;
  }
  if (count)
    return *p - *q;
  return 0;
}

km_kbp_cp *km::kbp::kmx::u16tok(km_kbp_cp *p, km_kbp_cp ch, km_kbp_cp **ctx) {
  if (!p) {
    p = *ctx;
    if (!p) return NULL;
  }

  km_kbp_cp *q = p;
  while (*q && *q != ch) {
    q++;
  }
  if (*q) {
    *q = 0;
    q++;
    while (*q == ch) q++;
    *ctx = q;
  }
  else {
    *ctx = NULL;
  }
  return p;
}

/*
* int xstrlen( PKMX_BYTE p );
*
* Parameters: p Pointer to string to get length of
*
* Returns:    length of string
*
*   Called by:  various functions
*
* xstrlen calculates the length of a string, ignoring some special chars.
*/

PKMX_WCHAR km::kbp::kmx::incxstr(PKMX_WCHAR p)
{
  int deltaptr;			// how many bytes to jump over

  if (*p == 0) return p;
  if (*p != UC_SENTINEL)
  {
    if (*p >= 0xD800 && *p <= 0xDBFF && *(p + 1) >= 0xDC00 && *(p + 1) <= 0xDFFF) return p + 2;
    return p + 1;
  }
  else
  {
    // UC_SENTINEL(FFFF) with UC_SENTINEL_EXTENDEDEND(0x10) == variable length
    if (*(p + 1) == CODE_EXTENDED) {
      p += 2;
      while (*(p - 1) && *p && *p != UC_SENTINEL_EXTENDEDEND)
        p++;

      if (*p == 0) return p;
      if (*p == UC_SENTINEL_EXTENDEDEND)		return p + 1;
    }

    //  UC_SENTINEL(FFFF) followed by other special
    switch (*(p + 1))
    {
    case CODE_ANY:						deltaptr = 3; break;
    case CODE_NOTANY:					deltaptr = 3; break;
    case CODE_INDEX:					deltaptr = 4; break;
    case CODE_USE:						deltaptr = 3; break;
    case CODE_DEADKEY:				deltaptr = 3; break;
    case CODE_CLEARCONTEXT:		deltaptr = 3; break;
    case CODE_CALL:						deltaptr = 3; break;
    case CODE_CONTEXTEX:			deltaptr = 3; break;
    case CODE_IFOPT:          deltaptr = 5; break;
    case CODE_IFSYSTEMSTORE:	deltaptr = 5; break;
    case CODE_SETOPT:					deltaptr = 4; break;
    case CODE_SETSYSTEMSTORE:	deltaptr = 4; break;
    case CODE_RESETOPT:				deltaptr = 3; break;
    case CODE_SAVEOPT:				deltaptr = 3; break;
    default:									deltaptr = 2;
    }

    // check for \0 between FFFF and next printable character
    for (int i = 0; i < deltaptr; i++) {
      if (*p==0) {
        return p;
      }
      p++;
    }
    return p;

  }
  return p;

}

PKMX_WCHAR km::kbp::kmx::decxstr(PKMX_WCHAR p, PKMX_WCHAR pStart)
{
  if(p <= pStart) {
    return NULL;
  }

  p--;
  if(*p == UC_SENTINEL_EXTENDEDEND)
  {
    int n = 0;
    while(*p != UC_SENTINEL && n < 10) { p--; n++; }

    if(p < pStart) {
      // May be a malformed virtual key
      return pStart;
    }
    return p;
  }

  if(p == pStart) return p; // Don't allow test before pStart

  if(*p >= 0xDC00 && *p <= 0xDFFF && *(p-1) >= 0xD800 && *(p-1) <= 0xDBFF)
  {
    return p-1;
  }
  else if(*(p-1) == UC_SENTINEL) return p-1;
  else if(p > pStart+1 && *(p-2) == UC_SENTINEL)
  {
    switch(*(p-1))
    {
      case CODE_ANY:
      case CODE_NOTANY:
      case CODE_USE:
      case CODE_DEADKEY:
      case CODE_CLEARCONTEXT:
      case CODE_CALL:
      case CODE_CONTEXTEX:
      case CODE_RESETOPT:
      case CODE_SAVEOPT:
        return p-2;
    }
  }
  else if(p > pStart+2 && *(p-3) == UC_SENTINEL)
  {
    switch(*(p-2))
    {
      case CODE_INDEX:
      case CODE_SETOPT:
      case CODE_SETSYSTEMSTORE:
        return p-3;
    }
  }
  else if(p > pStart+3 && *(p-4) == UC_SENTINEL)
  {
    switch(*(p-3))
    {
      case CODE_IFOPT:
      case CODE_IFSYSTEMSTORE:  // I3432
        return p-4;
    }
  }
  return p;
}

int km::kbp::kmx::xstrlen_ignoreifopt(PKMX_WCHAR p)
{
  int i;
  for(i = 0; *p; i++, p=incxstr(p))
  {
    if(*p == UC_SENTINEL && (*(p+1) == CODE_IFOPT || *(p+1) == CODE_IFSYSTEMSTORE)) i--;  // I3432
  }
  return i;
}

int km::kbp::kmx::xstrlen(PKMX_WCHAR p)
{
  int i;
  for(i = 0; *p; i++, p=incxstr(p));
  return i;
}

int km::kbp::kmx::xstrpos(PKMX_WCHAR p1, PKMX_WCHAR p)
{
  int i;
  for(i = 0; p < p1; p = incxstr(p), i++);
  return i;
}

PKMX_WCHAR km::kbp::kmx::xstrchr(PKMX_WCHAR buf, PKMX_WCHAR chr)
{
  for(PKMX_WCHAR q = incxstr(buf); *buf; buf = q, q = incxstr(buf))
    if(!u16ncmp(buf, chr, (intptr_t)(q-buf)))
      return buf;
  return NULL;
}

int km::kbp::kmx::xchrcmp(PKMX_WCHAR ch1, PKMX_WCHAR ch2)
{
  PKMX_WCHAR nch1 = incxstr(ch1);
  if(nch1 == ch1) return *ch2 - *ch1; /* comparing *ch2 to nul */
  return u16ncmp(ch1, ch2, (intptr_t)(nch1-ch1));
}

PKMX_WCHAR km::kbp::kmx::strtowstr(PKMX_CHAR in)
{
  PKMX_WCHAR result;

  auto s = convert<char,char16_t>(in);
  result = new char16_t[s.length() + 1];
  s.copy(result, s.length());
  result[s.length()] = 0;
  return result;
}

PKMX_CHAR km::kbp::kmx::wstrtostr(PKMX_WCHAR in)
{
  PKMX_CHAR result;

  auto s = convert<char16_t,char>(in);
  result = new char[s.length() + 1];
  s.copy(result, s.length());
  result[s.length()] = 0;
  return result;
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include "otbPlaceNameToLonLat.h"

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

  if(argc!=2)
  {
    std::cout << argv[0] <<" <place name> "
        << std::endl;

    return EXIT_FAILURE;
  }

  otb::PlaceNameToLonLat::Pointer pn2LL = otb::PlaceNameToLonLat::New();
  pn2LL->SetPlaceName(std::string(argv[1]));
  pn2LL->Evaluate();

  double lon = pn2LL->GetLon();
  double lat = pn2LL->GetLat();

  std::cout << "Latitude: " << lat << std::endl;
  std::cout << "Longitude: " << lon << std::endl;

  return EXIT_SUCCESS;

}<commit_msg>STYLE: with new line at end of file<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include "otbPlaceNameToLonLat.h"

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

  if(argc!=2)
  {
    std::cout << argv[0] <<" <place name> "
        << std::endl;

    return EXIT_FAILURE;
  }

  otb::PlaceNameToLonLat::Pointer pn2LL = otb::PlaceNameToLonLat::New();
  pn2LL->SetPlaceName(std::string(argv[1]));
  pn2LL->Evaluate();

  double lon = pn2LL->GetLon();
  double lat = pn2LL->GetLat();

  std::cout << "Latitude: " << lat << std::endl;
  std::cout << "Longitude: " << lon << std::endl;

  return EXIT_SUCCESS;

}
<|endoftext|>