<commit_before>#ifdef WIN32
/////////////////////////////////////////////////////////////////////////////
// Disable unavoidable warning messages:

//  4103: used #pragma pack to change alignment
//  4114: same type qualifier used more than once
//  4201: nonstandard extension used : nameless struct/union
//  4237: "keyword" reserved for future use
//  4251: class needs to have dll-interface to export class
//  4275: non DLL-interface class used as base for DLL-interface class
//  4290: C++ Exception Specification ignored
//  4503: decorated name length exceeded, name was truncated
//  4786: string too long - truncated to 255 characters

#pragma warning(disable : 4103 4114 4201 4237 4251 4275 4290 4503 4335 4786)

#endif // WIN32

#include <osgProducer/Viewer>

#include <osg/Group>
#include <osg/Geode>
#include <osg/ShapeDrawable>
#include <osg/Texture2D>
#include <osg/PositionAttitudeTransform>
#include <osg/MatrixTransform>
#include <osg/CoordinateSystemNode>

#include <osgDB/FileUtils>
#include <osgDB/ReadFile>

#include <osgText/Text>

#include <osgTerrain/DataSet>

#include <osgSim/OverlayNode>

#include <osgGA/NodeTrackerManipulator>

class GraphicsContext {
    public:
        GraphicsContext()
        {
            rs = new Producer::RenderSurface;
            rs->setWindowRectangle(0,0,1,1);
            rs->useBorder(false);
            rs->useConfigEventThread(false);
            rs->realize();
        }

        virtual ~GraphicsContext()
        {
        }

    private:
        Producer::ref_ptr<Producer::RenderSurface> rs;
};

osg::Node* createEarth()
{
    osg::ref_ptr<osg::Node> scene;

    {
        std::string filename = osgDB::findDataFile("Images/land_shallow_topo_2048.jpg");

        // make osgTerrain::DataSet quieter..
        osgTerrain::DataSet::setNotifyOffset(1);

        osg::ref_ptr<osgTerrain::DataSet> dataSet = new osgTerrain::DataSet;

        // register the source imagery
        {
            osgTerrain::DataSet::Source* source = new osgTerrain::DataSet::Source(osgTerrain::DataSet::Source::IMAGE, filename);

            source->setCoordinateSystemPolicy(osgTerrain::DataSet::Source::PREFER_CONFIG_SETTINGS);
            source->setCoordinateSystem(osgTerrain::DataSet::coordinateSystemStringToWTK("WGS84"));

             source->setGeoTransformPolicy(osgTerrain::DataSet::Source::PREFER_CONFIG_SETTINGS_BUT_SCALE_BY_FILE_RESOLUTION);
            source->setGeoTransformFromRange(-180.0, 180.0, -90.0, 90.0);

            dataSet->addSource(source);
        }

        // set up destination database paramters.
        dataSet->setDatabaseType(osgTerrain::DataSet::LOD_DATABASE);
        dataSet->setConvertFromGeographicToGeocentric(true);
        dataSet->setDestinationName("test.osg");

        // load the source data and record sizes.
        dataSet->loadSources();

        GraphicsContext context;
        dataSet->createDestination(30);

        if (dataSet->getDatabaseType()==osgTerrain::DataSet::LOD_DATABASE) dataSet->buildDestination();
        else dataSet->writeDestination();

        scene = dataSet->getDestinationRootNode();

        // now we must get rid of all the old OpenGL objects before we start using the scene graph again
        // otherwise it'll end up in an inconsistent state.
        scene->releaseGLObjects(dataSet->getState());
        osg::Texture::flushAllDeletedTextureObjects(0);
        osg::Drawable::flushAllDeletedDisplayLists(0);
    }

    return scene.release();

}

class ModelPositionCallback : public osg::NodeCallback
{
public:

    ModelPositionCallback():
        _latitude(0.0),
        _longitude(0.0),
        _height(100000.0)
    {
        _rotation.makeRotate(osg::DegreesToRadians(90.0),0.0,0.0,1.0);
    }

    void updateParameters()
    {
        _longitude += ((2.0*osg::PI)/360.0)/20.0;
    }

    virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
    {
        updateParameters();

        osg::NodePath nodePath = nv->getNodePath();

        osg::MatrixTransform* mt = nodePath.empty() ? 0 : dynamic_cast<osg::MatrixTransform*>(nodePath.back());
        if (mt)
        {
            osg::CoordinateSystemNode* csn = 0;

            // find coordinate system node from our parental chain
            unsigned int i;
            for(i=0; i<nodePath.size() && csn==0; ++i)
            {
                csn = dynamic_cast<osg::CoordinateSystemNode*>(nodePath[i]);
            }

            if (csn)
            {

                osg::EllipsoidModel* ellipsoid = csn->getEllipsoidModel();
                if (ellipsoid)
                {
                    osg::Matrix inheritedMatrix;
                    for(i+=1; i<nodePath.size()-1; ++i)
                    {
                        osg::Transform* transform = nodePath[i]->asTransform();
                        if (transform) transform->computeLocalToWorldMatrix(inheritedMatrix, nv);
                    }

                    osg::Matrixd matrix(inheritedMatrix);

                    //osg::Matrixd matrix;
                    ellipsoid->computeLocalToWorldTransformFromLatLongHeight(_latitude,_longitude,_height,matrix);
                    matrix.preMult(osg::Matrix::rotate(_rotation));

                    mt->setMatrix(matrix);
                }

            }
        }

        traverse(node,nv);
    }

    double                  _latitude;
    double                  _longitude;
    double                  _height;
    osg::Quat               _rotation;
};

class FindNamedNodeVisitor : public osg::NodeVisitor
{
public:
    FindNamedNodeVisitor(const std::string& name):
        osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
        _name(name) {}

    virtual void apply(osg::Node& node)
    {
        if (node.getName()==_name)
        {
            _foundNodes.push_back(&node);
        }
        traverse(node);
    }

    typedef std::vector< osg::ref_ptr<osg::Node> > NodeList;

    std::string _name;
    NodeList _foundNodes;
};

int main(int argc, char **argv)
{
    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    // set up the usage document, in case we need to print out how to use this program.
    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use of particle systems.");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] image_file_left_eye image_file_right_eye");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");

    // construct the viewer.
    osgProducer::Viewer viewer(arguments);

    // set up the value with sensible default event handlers.
    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);

    viewer.getCullSettings().setComputeNearFarMode(osg::CullSettings::COMPUTE_NEAR_FAR_USING_PRIMITIVES);
    viewer.getCullSettings().setNearFarRatio(0.00001f);

    // get details on keyboard and mouse bindings used by the viewer.
    viewer.getUsage(*arguments.getApplicationUsage());

    osg::Quat rotation;
    osg::Vec4 vec4;
    while (arguments.read("--rotate-model",vec4[0],vec4[1],vec4[2],vec4[3]))
    {
        osg::Quat local_rotate;
        local_rotate.makeRotate(osg::DegreesToRadians(vec4[0]),vec4[1],vec4[2],vec4[3]);

        rotation = rotation * local_rotate;
    }

    osg::NodeCallback* nc = 0;
    std::string flightpath_filename;
    while (arguments.read("--flight-path",flightpath_filename))
    {
        std::ifstream fin(flightpath_filename.c_str());
        if (fin)
        {
            osg::AnimationPath* path = new osg::AnimationPath;
            path->read(fin);
            nc = new osg::AnimationPathCallback(path);
        }
    }

    osgGA::NodeTrackerManipulator::TrackerMode trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_ROTATION;
    std::string mode;
    while (arguments.read("--tracker-mode",mode))
    {
        if (mode=="NODE_CENTER_AND_ROTATION") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_ROTATION;
        else if (mode=="NODE_CENTER_AND_AZIM") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_AZIM;
        else if (mode=="NODE_CENTER") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER;
        else
        {
            std::cout<<"Unrecognized --tracker-mode option "<<mode<<", valid options are:"<<std::endl;
            std::cout<<"    NODE_CENTER_AND_ROTATION"<<std::endl;
            std::cout<<"    NODE_CENTER_AND_AZIM"<<std::endl;
            std::cout<<"    NODE_CENTER"<<std::endl;
            return 1;
        }
    }

    osgGA::NodeTrackerManipulator::RotationMode rotationMode = osgGA::NodeTrackerManipulator::TRACKBALL;
    while (arguments.read("--rotation-mode",mode))
    {
        if (mode=="TRACKBALL") rotationMode = osgGA::NodeTrackerManipulator::TRACKBALL;
        else if (mode=="ELEVATION_AZIM") rotationMode = osgGA::NodeTrackerManipulator::ELEVATION_AZIM;
        else
        {
            std::cout<<"Unrecognized --rotation-mode option "<<mode<<", valid options are:"<<std::endl;
            std::cout<<"    TRACKBALL"<<std::endl;
            std::cout<<"    ELEVATION_AZIM"<<std::endl;
            return 1;
        }
    }

    // if user request help write it out to cout.
    if (arguments.read("-h") || arguments.read("--help"))
    {
        arguments.getApplicationUsage()->write(std::cout);
        return 1;
    }

    // any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized();

    // report any errors if they have occured when parsing the program aguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

    // read the scene from the list of file specified commandline args.
    osg::ref_ptr<osg::Node> root = osgDB::readNodeFiles(arguments);

    if (!root) root = createEarth();

    if (!root) return 0;

    // add a viewport to the viewer and attach the scene graph.
    viewer.setSceneData(root.get());

    osg::CoordinateSystemNode* csn = dynamic_cast<osg::CoordinateSystemNode*>(root.get());
    if (csn)
    {

        bool insertOverlayNode = true;
        osg::ref_ptr<osgSim::OverlayNode> overlayNode;
        if (insertOverlayNode)
        {

            overlayNode = new osgSim::OverlayNode;

            // insert the OverlayNode between the coordinate system node and its children.
            for(unsigned int i=0; i<csn->getNumChildren(); ++i)
            {
                overlayNode->addChild( csn->getChild(i) );
            }

            csn->removeChild(0, csn->getNumChildren());
            csn->addChild(overlayNode.get());

            // tell the overlay node to continously update its overlay texture
            // as we know we'll be tracking a moving target.
            overlayNode->setContinousUpdate(true);
        }

        osg::Node* cessna = osgDB::readNodeFile("cessna.osg");
        if (cessna)
        {
            double s = 200000.0 / cessna->getBound().radius();

            osg::MatrixTransform* scaler = new osg::MatrixTransform;
            scaler->addChild(cessna);
            scaler->setMatrix(osg::Matrixd::scale(s,s,s)*osg::Matrixd::rotate(rotation));
            scaler->getOrCreateStateSet()->setMode(GL_RESCALE_NORMAL,osg::StateAttribute::ON);

            osg::MatrixTransform* mt = new osg::MatrixTransform;
            mt->addChild(scaler);

            if (!nc) nc = new ModelPositionCallback;

            mt->setUpdateCallback(nc);

            csn->addChild(mt);

            // if we are using an overaly node, use the cessna subgraph as the overlay subgraph
            if (overlayNode.valid())
            {
                overlayNode->setOverlaySubgraph(mt);
            }

            osgGA::NodeTrackerManipulator* tm = new osgGA::NodeTrackerManipulator;
            tm->setTrackerMode(trackerMode);
            tm->setRotationMode(rotationMode);
            tm->setTrackNode(scaler);

            unsigned int num = viewer.addCameraManipulator(tm);
            viewer.selectCameraManipulator(num);
        }
        else
        {
             std::cout<<"Failed to read cessna.osg"<<std::endl;
        }

    }

    // create the windows and run the threads.
    viewer.realize();

    while( !viewer.done() )
    {
        // wait for all cull and draw threads to complete.
        viewer.sync();

        // update the scene by traversing it with the the update visitor which will
        // call all node update callbacks and animations.
        viewer.update();

        // fire off the cull and draw traversals of the scene.
        viewer.frame();

    }

    // wait for all cull and draw threads to complete before exit.
    viewer.sync();

    return 0;
}
<commit_msg>Fixed function name call.<commit_after>#ifdef WIN32
/////////////////////////////////////////////////////////////////////////////
// Disable unavoidable warning messages:

//  4103: used #pragma pack to change alignment
//  4114: same type qualifier used more than once
//  4201: nonstandard extension used : nameless struct/union
//  4237: "keyword" reserved for future use
//  4251: class needs to have dll-interface to export class
//  4275: non DLL-interface class used as base for DLL-interface class
//  4290: C++ Exception Specification ignored
//  4503: decorated name length exceeded, name was truncated
//  4786: string too long - truncated to 255 characters

#pragma warning(disable : 4103 4114 4201 4237 4251 4275 4290 4503 4335 4786)

#endif // WIN32

#include <osgProducer/Viewer>

#include <osg/Group>
#include <osg/Geode>
#include <osg/ShapeDrawable>
#include <osg/Texture2D>
#include <osg/PositionAttitudeTransform>
#include <osg/MatrixTransform>
#include <osg/CoordinateSystemNode>

#include <osgDB/FileUtils>
#include <osgDB/ReadFile>

#include <osgText/Text>

#include <osgTerrain/DataSet>

#include <osgSim/OverlayNode>

#include <osgGA/NodeTrackerManipulator>

class GraphicsContext {
    public:
        GraphicsContext()
        {
            rs = new Producer::RenderSurface;
            rs->setWindowRectangle(0,0,1,1);
            rs->useBorder(false);
            rs->useConfigEventThread(false);
            rs->realize();
        }

        virtual ~GraphicsContext()
        {
        }

    private:
        Producer::ref_ptr<Producer::RenderSurface> rs;
};

osg::Node* createEarth()
{
    osg::ref_ptr<osg::Node> scene;

    {
        std::string filename = osgDB::findDataFile("Images/land_shallow_topo_2048.jpg");

        // make osgTerrain::DataSet quieter..
        osgTerrain::DataSet::setNotifyOffset(1);

        osg::ref_ptr<osgTerrain::DataSet> dataSet = new osgTerrain::DataSet;

        // register the source imagery
        {
            osgTerrain::DataSet::Source* source = new osgTerrain::DataSet::Source(osgTerrain::DataSet::Source::IMAGE, filename);

            source->setCoordinateSystemPolicy(osgTerrain::DataSet::Source::PREFER_CONFIG_SETTINGS);
            source->setCoordinateSystem(osgTerrain::DataSet::coordinateSystemStringToWTK("WGS84"));

             source->setGeoTransformPolicy(osgTerrain::DataSet::Source::PREFER_CONFIG_SETTINGS_BUT_SCALE_BY_FILE_RESOLUTION);
            source->setGeoTransformFromRange(-180.0, 180.0, -90.0, 90.0);

            dataSet->addSource(source);
        }

        // set up destination database paramters.
        dataSet->setDatabaseType(osgTerrain::DataSet::LOD_DATABASE);
        dataSet->setConvertFromGeographicToGeocentric(true);
        dataSet->setDestinationName("test.osg");

        // load the source data and record sizes.
        dataSet->loadSources();

        GraphicsContext context;
        dataSet->createDestination(30);

        if (dataSet->getDatabaseType()==osgTerrain::DataSet::LOD_DATABASE) dataSet->buildDestination();
        else dataSet->writeDestination();

        scene = dataSet->getDestinationRootNode();

        // now we must get rid of all the old OpenGL objects before we start using the scene graph again
        // otherwise it'll end up in an inconsistent state.
        scene->releaseGLObjects(dataSet->getState());
        osg::Texture::flushAllDeletedTextureObjects(0);
        osg::Drawable::flushAllDeletedDisplayLists(0);
    }

    return scene.release();

}

class ModelPositionCallback : public osg::NodeCallback
{
public:

    ModelPositionCallback():
        _latitude(0.0),
        _longitude(0.0),
        _height(100000.0)
    {
        _rotation.makeRotate(osg::DegreesToRadians(90.0),0.0,0.0,1.0);
    }

    void updateParameters()
    {
        _longitude += ((2.0*osg::PI)/360.0)/20.0;
    }

    virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
    {
        updateParameters();

        osg::NodePath nodePath = nv->getNodePath();

        osg::MatrixTransform* mt = nodePath.empty() ? 0 : dynamic_cast<osg::MatrixTransform*>(nodePath.back());
        if (mt)
        {
            osg::CoordinateSystemNode* csn = 0;

            // find coordinate system node from our parental chain
            unsigned int i;
            for(i=0; i<nodePath.size() && csn==0; ++i)
            {
                csn = dynamic_cast<osg::CoordinateSystemNode*>(nodePath[i]);
            }

            if (csn)
            {

                osg::EllipsoidModel* ellipsoid = csn->getEllipsoidModel();
                if (ellipsoid)
                {
                    osg::Matrix inheritedMatrix;
                    for(i+=1; i<nodePath.size()-1; ++i)
                    {
                        osg::Transform* transform = nodePath[i]->asTransform();
                        if (transform) transform->computeLocalToWorldMatrix(inheritedMatrix, nv);
                    }

                    osg::Matrixd matrix(inheritedMatrix);

                    //osg::Matrixd matrix;
                    ellipsoid->computeLocalToWorldTransformFromLatLongHeight(_latitude,_longitude,_height,matrix);
                    matrix.preMult(osg::Matrix::rotate(_rotation));

                    mt->setMatrix(matrix);
                }

            }
        }

        traverse(node,nv);
    }

    double                  _latitude;
    double                  _longitude;
    double                  _height;
    osg::Quat               _rotation;
};

class FindNamedNodeVisitor : public osg::NodeVisitor
{
public:
    FindNamedNodeVisitor(const std::string& name):
        osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
        _name(name) {}

    virtual void apply(osg::Node& node)
    {
        if (node.getName()==_name)
        {
            _foundNodes.push_back(&node);
        }
        traverse(node);
    }

    typedef std::vector< osg::ref_ptr<osg::Node> > NodeList;

    std::string _name;
    NodeList _foundNodes;
};

int main(int argc, char **argv)
{
    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    // set up the usage document, in case we need to print out how to use this program.
    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use of particle systems.");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] image_file_left_eye image_file_right_eye");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");

    // construct the viewer.
    osgProducer::Viewer viewer(arguments);

    // set up the value with sensible default event handlers.
    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);

    viewer.getCullSettings().setComputeNearFarMode(osg::CullSettings::COMPUTE_NEAR_FAR_USING_PRIMITIVES);
    viewer.getCullSettings().setNearFarRatio(0.00001f);

    // get details on keyboard and mouse bindings used by the viewer.
    viewer.getUsage(*arguments.getApplicationUsage());

    osg::Quat rotation;
    osg::Vec4 vec4;
    while (arguments.read("--rotate-model",vec4[0],vec4[1],vec4[2],vec4[3]))
    {
        osg::Quat local_rotate;
        local_rotate.makeRotate(osg::DegreesToRadians(vec4[0]),vec4[1],vec4[2],vec4[3]);

        rotation = rotation * local_rotate;
    }

    osg::NodeCallback* nc = 0;
    std::string flightpath_filename;
    while (arguments.read("--flight-path",flightpath_filename))
    {
        std::ifstream fin(flightpath_filename.c_str());
        if (fin)
        {
            osg::AnimationPath* path = new osg::AnimationPath;
            path->read(fin);
            nc = new osg::AnimationPathCallback(path);
        }
    }

    osgGA::NodeTrackerManipulator::TrackerMode trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_ROTATION;
    std::string mode;
    while (arguments.read("--tracker-mode",mode))
    {
        if (mode=="NODE_CENTER_AND_ROTATION") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_ROTATION;
        else if (mode=="NODE_CENTER_AND_AZIM") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_AZIM;
        else if (mode=="NODE_CENTER") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER;
        else
        {
            std::cout<<"Unrecognized --tracker-mode option "<<mode<<", valid options are:"<<std::endl;
            std::cout<<"    NODE_CENTER_AND_ROTATION"<<std::endl;
            std::cout<<"    NODE_CENTER_AND_AZIM"<<std::endl;
            std::cout<<"    NODE_CENTER"<<std::endl;
            return 1;
        }
    }

    osgGA::NodeTrackerManipulator::RotationMode rotationMode = osgGA::NodeTrackerManipulator::TRACKBALL;
    while (arguments.read("--rotation-mode",mode))
    {
        if (mode=="TRACKBALL") rotationMode = osgGA::NodeTrackerManipulator::TRACKBALL;
        else if (mode=="ELEVATION_AZIM") rotationMode = osgGA::NodeTrackerManipulator::ELEVATION_AZIM;
        else
        {
            std::cout<<"Unrecognized --rotation-mode option "<<mode<<", valid options are:"<<std::endl;
            std::cout<<"    TRACKBALL"<<std::endl;
            std::cout<<"    ELEVATION_AZIM"<<std::endl;
            return 1;
        }
    }

    // if user request help write it out to cout.
    if (arguments.read("-h") || arguments.read("--help"))
    {
        arguments.getApplicationUsage()->write(std::cout);
        return 1;
    }

    // any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized();

    // report any errors if they have occured when parsing the program aguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

    // read the scene from the list of file specified commandline args.
    osg::ref_ptr<osg::Node> root = osgDB::readNodeFiles(arguments);

    if (!root) root = createEarth();

    if (!root) return 0;

    // add a viewport to the viewer and attach the scene graph.
    viewer.setSceneData(root.get());

    osg::CoordinateSystemNode* csn = dynamic_cast<osg::CoordinateSystemNode*>(root.get());
    if (csn)
    {

        bool insertOverlayNode = true;
        osg::ref_ptr<osgSim::OverlayNode> overlayNode;
        if (insertOverlayNode)
        {

            overlayNode = new osgSim::OverlayNode;

            // insert the OverlayNode between the coordinate system node and its children.
            for(unsigned int i=0; i<csn->getNumChildren(); ++i)
            {
                overlayNode->addChild( csn->getChild(i) );
            }

            csn->removeChild(0, csn->getNumChildren());
            csn->addChild(overlayNode.get());

            // tell the overlay node to continously update its overlay texture
            // as we know we'll be tracking a moving target.
            overlayNode->setContinuousUpdate(true);
        }

        osg::Node* cessna = osgDB::readNodeFile("cessna.osg");
        if (cessna)
        {
            double s = 200000.0 / cessna->getBound().radius();

            osg::MatrixTransform* scaler = new osg::MatrixTransform;
            scaler->addChild(cessna);
            scaler->setMatrix(osg::Matrixd::scale(s,s,s)*osg::Matrixd::rotate(rotation));
            scaler->getOrCreateStateSet()->setMode(GL_RESCALE_NORMAL,osg::StateAttribute::ON);

            osg::MatrixTransform* mt = new osg::MatrixTransform;
            mt->addChild(scaler);

            if (!nc) nc = new ModelPositionCallback;

            mt->setUpdateCallback(nc);

            csn->addChild(mt);

            // if we are using an overaly node, use the cessna subgraph as the overlay subgraph
            if (overlayNode.valid())
            {
                overlayNode->setOverlaySubgraph(mt);
            }

            osgGA::NodeTrackerManipulator* tm = new osgGA::NodeTrackerManipulator;
            tm->setTrackerMode(trackerMode);
            tm->setRotationMode(rotationMode);
            tm->setTrackNode(scaler);

            unsigned int num = viewer.addCameraManipulator(tm);
            viewer.selectCameraManipulator(num);
        }
        else
        {
             std::cout<<"Failed to read cessna.osg"<<std::endl;
        }

    }

    // create the windows and run the threads.
    viewer.realize();

    while( !viewer.done() )
    {
        // wait for all cull and draw threads to complete.
        viewer.sync();

        // update the scene by traversing it with the the update visitor which will
        // call all node update callbacks and animations.
        viewer.update();

        // fire off the cull and draw traversals of the scene.
        viewer.frame();

    }

    // wait for all cull and draw threads to complete before exit.
    viewer.sync();

    return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2010 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/chromeos/login/keyboard_switch_menu.h"

#include "base/i18n/rtl.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/keyboard_library.h"
#include "chrome/browser/chromeos/input_method/input_method_util.h"
#include "chrome/browser/chromeos/status/status_area_host.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "views/controls/button/menu_button.h"
#include "views/widget/widget_gtk.h"

namespace chromeos {

KeyboardSwitchMenu::KeyboardSwitchMenu()
    : InputMethodMenu(NULL /* pref_service */,
                      StatusAreaHost::kLoginMode,
                      true /* for_out_of_box_experience_dialog */) {
}

////////////////////////////////////////////////////////////////////////////////
// InputMethodMenu::InputMethodMenuHost implementation.
void KeyboardSwitchMenu::UpdateUI(const std::string& input_method_id,
                                  const std::wstring& name,
                                  const std::wstring& tooltip,
                                  size_t num_active_input_methods) {
  // Update all view hierarchies so that the new input method name is shown in
  // the menu button.
  views::Widget::NotifyLocaleChanged();
}

////////////////////////////////////////////////////////////////////////////////
// views::ViewMenuDelegate implementation.
void KeyboardSwitchMenu::RunMenu(views::View* source, const gfx::Point& pt) {
  PrepareForMenuOpen();
  gfx::Point new_pt(pt);
  views::MenuButton* button = static_cast<views::MenuButton*>(source);
  // Keyboard switch menu is aligned on left by default.
  int reverse_offset = button->width() + button->menu_offset().x() * 2;
  if (base::i18n::IsRTL()) {
    new_pt.set_x(pt.x() + reverse_offset);
  } else {
    new_pt.set_x(pt.x() - reverse_offset);
  }
  input_method_menu().RunMenuAt(new_pt, views::Menu2::ALIGN_TOPLEFT);
}

string16 KeyboardSwitchMenu::GetCurrentKeyboardName() const {
  const int count = GetItemCount();
  for (int i = 0; i < count; ++i) {
    if (IsItemCheckedAt(i))
      return GetLabelAt(i);
  }
  VLOG(1) << "The input method menu is not ready yet.  Show a language name "
             "that matches the hardware keyboard layout";
  KeyboardLibrary *library = CrosLibrary::Get()->GetKeyboardLibrary();
  const std::string keyboard_layout_id =
      library->GetHardwareKeyboardLayoutName();
  const std::string language_code =
      input_method::GetLanguageCodeFromInputMethodId(keyboard_layout_id);
  return input_method::GetLanguageDisplayNameFromCode(language_code);
}

}  // namespace chromeos
<commit_msg>Remove use of GetHardwareKeyboardLayoutName from KeyboardSwitchMenu.<commit_after>// Copyright (c) 2010 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/chromeos/login/keyboard_switch_menu.h"

#include "base/i18n/rtl.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/keyboard_library.h"
#include "chrome/browser/chromeos/input_method/input_method_util.h"
#include "chrome/browser/chromeos/status/status_area_host.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "views/controls/button/menu_button.h"
#include "views/widget/widget_gtk.h"

namespace chromeos {

KeyboardSwitchMenu::KeyboardSwitchMenu()
    : InputMethodMenu(NULL /* pref_service */,
                      StatusAreaHost::kLoginMode,
                      true /* for_out_of_box_experience_dialog */) {
}

////////////////////////////////////////////////////////////////////////////////
// InputMethodMenu::InputMethodMenuHost implementation.
void KeyboardSwitchMenu::UpdateUI(const std::string& input_method_id,
                                  const std::wstring& name,
                                  const std::wstring& tooltip,
                                  size_t num_active_input_methods) {
  // Update all view hierarchies so that the new input method name is shown in
  // the menu button.
  views::Widget::NotifyLocaleChanged();
}

////////////////////////////////////////////////////////////////////////////////
// views::ViewMenuDelegate implementation.
void KeyboardSwitchMenu::RunMenu(views::View* source, const gfx::Point& pt) {
  PrepareForMenuOpen();
  gfx::Point new_pt(pt);
  views::MenuButton* button = static_cast<views::MenuButton*>(source);
  // Keyboard switch menu is aligned on left by default.
  int reverse_offset = button->width() + button->menu_offset().x() * 2;
  if (base::i18n::IsRTL()) {
    new_pt.set_x(pt.x() + reverse_offset);
  } else {
    new_pt.set_x(pt.x() - reverse_offset);
  }
  input_method_menu().RunMenuAt(new_pt, views::Menu2::ALIGN_TOPLEFT);
}

string16 KeyboardSwitchMenu::GetCurrentKeyboardName() const {
  const int count = GetItemCount();
  for (int i = 0; i < count; ++i) {
    if (IsItemCheckedAt(i))
      return GetLabelAt(i);
  }
  VLOG(1) << "The input method menu is not ready yet. Show the display "
          << "name of the current input method";
  InputMethodLibrary* library = CrosLibrary::Get()->GetInputMethodLibrary();
  return (input_method::GetStringUTF16(
              input_method::GetInputMethodDisplayNameFromId(
                  library->current_input_method().id)));
}

}  // namespace chromeos
<|endoftext|>


<commit_before>// Copyright (c) 2010 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/chromeos/login/screen_locker_tester.h"

#include <gdk/gdkkeysyms.h>

#include "app/l10n_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chromeos/login/mock_authenticator.h"
#include "chrome/browser/chromeos/login/screen_locker.h"
#include "chrome/browser/chromeos/login/screen_lock_view.h"
#include "views/controls/button/button.h"
#include "views/controls/label.h"
#include "views/controls/textfield/textfield.h"

namespace chromeos {

test::ScreenLockerTester* ScreenLocker::GetTester() {
  return new test::ScreenLockerTester();
}

namespace test {

bool ScreenLockerTester::IsOpen() {
  return chromeos::ScreenLocker::screen_locker_ != NULL;
}

void ScreenLockerTester::InjectMockAuthenticator(const char* password) {
  DCHECK(ScreenLocker::screen_locker_);
  ScreenLocker::screen_locker_->SetAuthenticator(
      new MockAuthenticator(ScreenLocker::screen_locker_, "", password));
}

void ScreenLockerTester::EnterPassword(const char* password) {
  DCHECK(ScreenLocker::screen_locker_);
  views::Textfield* pass = GetPasswordField();
  pass->SetText(ASCIIToUTF16(password));
  GdkEventKey eventKey;
  eventKey.keyval = GDK_Return;
  views::Textfield::Keystroke ret(&eventKey);
  ScreenLocker::screen_locker_->screen_lock_view_->HandleKeystroke(pass, ret);
}

views::Textfield* ScreenLockerTester::GetPasswordField() {
  DCHECK(ScreenLocker::screen_locker_);
  return ScreenLocker::screen_locker_->screen_lock_view_->password_field_;
}

}  // namespace test

}  // namespace chromeos
<commit_msg>Create gdk_event right way to elimination compilation error in chroot environment.  I didn't bother allocating new one because i thought none is using event object except for our code, but i was wrong.  TextField is copying the struct, which was causing the warning.<commit_after>// Copyright (c) 2010 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/chromeos/login/screen_locker_tester.h"

#include <gdk/gdkkeysyms.h>

#include "app/l10n_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chromeos/login/mock_authenticator.h"
#include "chrome/browser/chromeos/login/screen_locker.h"
#include "chrome/browser/chromeos/login/screen_lock_view.h"
#include "views/controls/button/button.h"
#include "views/controls/label.h"
#include "views/controls/textfield/textfield.h"

namespace chromeos {

test::ScreenLockerTester* ScreenLocker::GetTester() {
  return new test::ScreenLockerTester();
}

namespace test {

bool ScreenLockerTester::IsOpen() {
  return chromeos::ScreenLocker::screen_locker_ != NULL;
}

void ScreenLockerTester::InjectMockAuthenticator(const char* password) {
  DCHECK(ScreenLocker::screen_locker_);
  ScreenLocker::screen_locker_->SetAuthenticator(
      new MockAuthenticator(ScreenLocker::screen_locker_, "", password));
}

void ScreenLockerTester::EnterPassword(const char* password) {
  DCHECK(ScreenLocker::screen_locker_);
  views::Textfield* pass = GetPasswordField();
  pass->SetText(ASCIIToUTF16(password));
  GdkEvent* event = gdk_event_new(GDK_KEY_PRESS);

  event->key.keyval = GDK_Return;
  views::Textfield::Keystroke ret(&event->key);
  ScreenLocker::screen_locker_->screen_lock_view_->HandleKeystroke(pass, ret);

  gdk_event_free(event);
}

views::Textfield* ScreenLockerTester::GetPasswordField() {
  DCHECK(ScreenLocker::screen_locker_);
  return ScreenLocker::screen_locker_->screen_lock_view_->password_field_;
}

}  // namespace test

}  // namespace chromeos
<|endoftext|>


<commit_before><commit_msg>clear draw 2d when stopping game, since it can contain references to no longer valid textures<commit_after><|endoftext|>


<commit_before>/**
Released as open source by NCC Group Plc - http://www.nccgroup.com/

Developed by Gabriel Caudrelier, gabriel dot caudrelier at nccgroup dot com

https://github.com/nccgroup/pip3line

Released under AGPL see LICENSE for more information
**/

#include "tcpserverlistener.h"
#include "tcplistener.h"
#include "networkconfwidget.h"
#include <QThread>
#include <QDebug>
#include <QTimer>

InTcpServer::InTcpServer(QObject *parent) : QTcpServer(parent)
{

}

InTcpServer::~InTcpServer()
{

}
#if QT_VERSION >= 0x050000
void InTcpServer::incomingConnection(qintptr socketDescriptor)
#else
void InTcpServer::incomingConnection(int socketDescriptor)
#endif
{
    emit newClient(socketDescriptor);
}

const quint16 TcpServerListener::DEFAULT_PORT = 40000;
const QHostAddress TcpServerListener::DEFAULT_ADDRESS = QHostAddress::LocalHost;

TcpServerListener::TcpServerListener(QObject *parent) :
    BlocksSource(parent)
{
    listeningAddress = DEFAULT_ADDRESS;
    port = DEFAULT_PORT;
    server = NULL;
    workerThread = NULL;

    serverThread = new(std::nothrow) QThread();
    if (serverThread == NULL) {
        qFatal("Cannot allocate memory for serverThread X{");
    }
    moveToThread(serverThread);
    serverThread->start();

    separator='\x0a';
}

TcpServerListener::~TcpServerListener() {
    serverThread->quit();
    serverThread->wait();
    serverThread->deleteLater();
    serverThread = NULL;
    //delete server; don't need that

    if (workerThread != NULL) {
        workerThread->quit();
        workerThread->wait();
        delete workerThread;
        workerThread = NULL;
    }
}

void TcpServerListener::sendBlock(const Block & )
{
    qFatal("[TcpServerListener::sendBlock] forbidden secret");
}

bool TcpServerListener::startListening()
{
    startingWorkers();
    if (server == NULL) {
        server = new(std::nothrow) InTcpServer();
        if (server == NULL) {
            qFatal("Cannot allocate memory for QTcpServer X{");
        }
#if QT_VERSION >= 0x050000
        connect(server,SIGNAL(newClient(qintptr)), SLOT(handlingClient(qintptr)));
#else
        connect(server,SIGNAL(newClient(int)), SLOT(handlingClient(int)));
#endif
    }
    if (server->isListening()) { // already listening nothing to do
        return true;
    }

    if (!server->listen(listeningAddress,port)) {
        emit log(tr("could not start TCP server %1").arg(server->errorString()),metaObject()->className(), Pip3lineConst::LERROR);
        delete server;
        server = NULL;
        workerThread->quit();
        return false;
    }
    emit log(tr("TCP server started %1:%2").arg(listeningAddress.toString()).arg(port), "", Pip3lineConst::LSTATUS);
    emit started();
    return true;
}

void TcpServerListener::stopListening()
{
    if (server != NULL && server->isListening()) {
       emit log(tr("TCP server stopped %1:%2").arg(listeningAddress.toString()).arg(port), "", Pip3lineConst::LSTATUS);
       server->close();
       emit shutdownAllClient();
       stoppingWorkers();
       emit stopped();
       server->deleteLater();
       server = NULL;
    }
}

void TcpServerListener::postBlockForSending(Block block)
{
    TcpListener * client = static_cast<TcpListener *>(block.source);

    if (client != NULL) {
        if (clients.contains(client)) {
            client->postBlockForSending(block); // the client is going to take care of encoding the block
        } else {
            emit log(tr("Client disconnected cannot forward data block"), metaObject()->className(), Pip3lineConst::LERROR);
        }
    } else {
        qCritical() << "[TcpServerListener::postBlockForSending] NULL client";
    }
}

void TcpServerListener::clientFinished()
{
    TcpListener * client = static_cast<TcpListener *>(sender());
    if (client == NULL) {
        qWarning() << "[TcpServerListener] NULL client finished T_T";
    } else if (clients.contains(client)) {
        clients.removeAll(client);
       // qWarning() << "Client finished" << client;
    }
    else
        qCritical() << metaObject()->className() << "Could not find the client in the list" << client;

    delete client;
}

void TcpServerListener::onClientReceivedBlock(Block block)
{
    TcpListener *client = qobject_cast<TcpListener *>(sender());
    int index = clients.indexOf(client);
    if (index == -1) {
        qCritical() << tr("Could not find client in list");
    } else {
        block.sourceid = index;
        block.direction = Block::SOURCE;
        emit blockReceived(block);
    }
}

#if QT_VERSION >= 0x050000
void TcpServerListener::handlingClient(qintptr socketDescriptor)
#else
void TcpServerListener::handlingClient(int socketDescriptor)
#endif
{
    TcpListener * listener = new(std::nothrow) TcpListener(socketDescriptor);
    if (listener != NULL) {
       // qDebug() << "Listener created" << listener;
        listener->setDecodeinput(decodeInput);
        listener->setEncodeOutput(encodeOutput);
        clients.append(listener);
        listener->moveToThread(workerThread);
        connect(listener, SIGNAL(blockReceived(Block)), SLOT(onClientReceivedBlock(Block)));
        connect(listener, SIGNAL(stopped()), SLOT(clientFinished()));
        connect(listener, SIGNAL(error(QString,QString)), SIGNAL(error(QString,QString)));
        connect(listener, SIGNAL(status(QString,QString)), SIGNAL(status(QString,QString)));
        connect(this, SIGNAL(shutdownAllClient()), listener, SLOT(stopListening()),Qt::QueuedConnection);
        QTimer::singleShot(0,listener,SLOT(startListening()));
    } else {
        qFatal("Cannot allocate memory for TcpListener X{");
    }
}

void TcpServerListener::startingWorkers()
{
    if (workerThread == NULL) {
        workerThread = new(std::nothrow) QThread();
        if (workerThread == NULL) {
            qFatal("Cannot allocate memory for workerThread X{");
        }
    }
    if (workerThread != NULL) {
        workerThread->start();
    }
}

void TcpServerListener::stoppingWorkers()
{
    workerThread->quit();
    if (!workerThread->wait())
        qCritical() << metaObject()->className() << "Could not stop the worker thread";
}

QWidget *TcpServerListener::requestGui(QWidget *parent)
{
    NetworkConfWidget *ncw = new(std::nothrow)NetworkConfWidget(NetworkConfWidget::TCP_SERVER,parent);
    if (ncw == NULL) {
        qFatal("Cannot allocate memory for NetworkConfWidget X{");
    }
    ncw->setPort(port);
    ncw->setIP(listeningAddress);
    ncw->enableDecodeEncodeOption(true);
    connect(ncw, SIGNAL(newIp(QHostAddress)), this, SLOT(setListeningAddress(QHostAddress)));
    connect(ncw, SIGNAL(newPort(quint16)), this, SLOT(setPort(quint16)));
    connect(ncw, SIGNAL(start()), this, SLOT(startListening()));
    connect(ncw, SIGNAL(stop()), this, SLOT(stopListening()));
    connect(ncw,SIGNAL(restart()), this, SLOT(restart()));
    connect(this, SIGNAL(started()), ncw, SLOT(onServerStarted()));
    connect(this, SIGNAL(stopped()), ncw, SLOT(onServerStopped()));
    return ncw;
}

void TcpServerListener::setPort(const quint16 &value)
{
    if (value != port) {
        port = value;
    }

}

void TcpServerListener::setListeningAddress(const QHostAddress &value)
{
    if (value != listeningAddress) {
        listeningAddress = value;
    }
}

<commit_msg>Fix small logging bug<commit_after>/**
Released as open source by NCC Group Plc - http://www.nccgroup.com/

Developed by Gabriel Caudrelier, gabriel dot caudrelier at nccgroup dot com

https://github.com/nccgroup/pip3line

Released under AGPL see LICENSE for more information
**/

#include "tcpserverlistener.h"
#include "tcplistener.h"
#include "networkconfwidget.h"
#include <QThread>
#include <QDebug>
#include <QTimer>

InTcpServer::InTcpServer(QObject *parent) : QTcpServer(parent)
{

}

InTcpServer::~InTcpServer()
{

}
#if QT_VERSION >= 0x050000
void InTcpServer::incomingConnection(qintptr socketDescriptor)
#else
void InTcpServer::incomingConnection(int socketDescriptor)
#endif
{
    emit newClient(socketDescriptor);
}

const quint16 TcpServerListener::DEFAULT_PORT = 40000;
const QHostAddress TcpServerListener::DEFAULT_ADDRESS = QHostAddress::LocalHost;

TcpServerListener::TcpServerListener(QObject *parent) :
    BlocksSource(parent)
{
    listeningAddress = DEFAULT_ADDRESS;
    port = DEFAULT_PORT;
    server = NULL;
    workerThread = NULL;

    serverThread = new(std::nothrow) QThread();
    if (serverThread == NULL) {
        qFatal("Cannot allocate memory for serverThread X{");
    }
    moveToThread(serverThread);
    serverThread->start();

    separator='\x0a';
}

TcpServerListener::~TcpServerListener() {
    serverThread->quit();
    serverThread->wait();
    serverThread->deleteLater();
    serverThread = NULL;
    //delete server; don't need that

    if (workerThread != NULL) {
        workerThread->quit();
        workerThread->wait();
        delete workerThread;
        workerThread = NULL;
    }
}

void TcpServerListener::sendBlock(const Block & )
{
    qFatal("[TcpServerListener::sendBlock] forbidden secret");
}

bool TcpServerListener::startListening()
{
    startingWorkers();
    if (server == NULL) {
        server = new(std::nothrow) InTcpServer();
        if (server == NULL) {
            qFatal("Cannot allocate memory for QTcpServer X{");
        }
#if QT_VERSION >= 0x050000
        connect(server,SIGNAL(newClient(qintptr)), SLOT(handlingClient(qintptr)));
#else
        connect(server,SIGNAL(newClient(int)), SLOT(handlingClient(int)));
#endif
    }
    if (server->isListening()) { // already listening nothing to do
        return true;
    }

    if (!server->listen(listeningAddress,port)) {
        emit log(tr("could not start TCP server %1").arg(server->errorString()),metaObject()->className(), Pip3lineConst::LERROR);
        delete server;
        server = NULL;
        workerThread->quit();
        return false;
    }
    emit log(tr("TCP server started %1:%2").arg(listeningAddress.toString()).arg(port), "", Pip3lineConst::LSTATUS);
    emit started();
    return true;
}

void TcpServerListener::stopListening()
{
    if (server != NULL && server->isListening()) {
       emit log(tr("TCP server stopped %1:%2").arg(listeningAddress.toString()).arg(port), "", Pip3lineConst::LSTATUS);
       server->close();
       emit shutdownAllClient();
       stoppingWorkers();
       emit stopped();
       server->deleteLater();
       server = NULL;
    }
}

void TcpServerListener::postBlockForSending(Block block)
{
    TcpListener * client = static_cast<TcpListener *>(block.source);

    if (client != NULL) {
        if (clients.contains(client)) {
            client->postBlockForSending(block); // the client is going to take care of encoding the block
        } else {
            emit log(tr("Client disconnected cannot forward data block"), metaObject()->className(), Pip3lineConst::LERROR);
        }
    } else {
        qCritical() << "[TcpServerListener::postBlockForSending] NULL client";
    }
}

void TcpServerListener::clientFinished()
{
    TcpListener * client = static_cast<TcpListener *>(sender());
    if (client == NULL) {
        qWarning() << "[TcpServerListener] NULL client finished T_T";
    } else if (clients.contains(client)) {
        clients.removeAll(client);
       // qWarning() << "Client finished" << client;
    }
    else
        qCritical() << metaObject()->className() << "Could not find the client in the list" << client;

    delete client;
}

void TcpServerListener::onClientReceivedBlock(Block block)
{
    TcpListener *client = qobject_cast<TcpListener *>(sender());
    int index = clients.indexOf(client);
    if (index == -1) {
        qCritical() << tr("Could not find client in list");
    } else {
        block.sourceid = index;
        block.direction = Block::SOURCE;
        emit blockReceived(block);
    }
}

#if QT_VERSION >= 0x050000
void TcpServerListener::handlingClient(qintptr socketDescriptor)
#else
void TcpServerListener::handlingClient(int socketDescriptor)
#endif
{
    TcpListener * listener = new(std::nothrow) TcpListener(socketDescriptor);
    if (listener != NULL) {
       // qDebug() << "Listener created" << listener;
        listener->setDecodeinput(decodeInput);
        listener->setEncodeOutput(encodeOutput);
        clients.append(listener);
        listener->moveToThread(workerThread);
        connect(listener, SIGNAL(blockReceived(Block)), SLOT(onClientReceivedBlock(Block)));
        connect(listener, SIGNAL(stopped()), SLOT(clientFinished()));
        connect(listener, SIGNAL(log(QString,QString,Pip3lineConst::LOGLEVEL)), SIGNAL(log(QString,QString,Pip3lineConst::LOGLEVEL)));
        connect(this, SIGNAL(shutdownAllClient()), listener, SLOT(stopListening()),Qt::QueuedConnection);
        QTimer::singleShot(0,listener,SLOT(startListening()));
    } else {
        qFatal("Cannot allocate memory for TcpListener X{");
    }
}

void TcpServerListener::startingWorkers()
{
    if (workerThread == NULL) {
        workerThread = new(std::nothrow) QThread();
        if (workerThread == NULL) {
            qFatal("Cannot allocate memory for workerThread X{");
        }
    }
    if (workerThread != NULL) {
        workerThread->start();
    }
}

void TcpServerListener::stoppingWorkers()
{
    workerThread->quit();
    if (!workerThread->wait())
        qCritical() << metaObject()->className() << "Could not stop the worker thread";
}

QWidget *TcpServerListener::requestGui(QWidget *parent)
{
    NetworkConfWidget *ncw = new(std::nothrow)NetworkConfWidget(NetworkConfWidget::TCP_SERVER,parent);
    if (ncw == NULL) {
        qFatal("Cannot allocate memory for NetworkConfWidget X{");
    }
    ncw->setPort(port);
    ncw->setIP(listeningAddress);
    ncw->enableDecodeEncodeOption(true);
    connect(ncw, SIGNAL(newIp(QHostAddress)), this, SLOT(setListeningAddress(QHostAddress)));
    connect(ncw, SIGNAL(newPort(quint16)), this, SLOT(setPort(quint16)));
    connect(ncw, SIGNAL(start()), this, SLOT(startListening()));
    connect(ncw, SIGNAL(stop()), this, SLOT(stopListening()));
    connect(ncw,SIGNAL(restart()), this, SLOT(restart()));
    connect(this, SIGNAL(started()), ncw, SLOT(onServerStarted()));
    connect(this, SIGNAL(stopped()), ncw, SLOT(onServerStopped()));
    return ncw;
}

void TcpServerListener::setPort(const quint16 &value)
{
    if (value != port) {
        port = value;
    }

}

void TcpServerListener::setListeningAddress(const QHostAddress &value)
{
    if (value != listeningAddress) {
        listeningAddress = value;
    }
}

<|endoftext|>


<commit_before>#pragma once

#include <exception>
#include <regex>
#include <iostream>

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

namespace virus_name
{
    namespace _internal
    {
#pragma GCC diagnostic push
#ifdef __clang__
#pragma GCC diagnostic ignored "-Wglobal-constructors"
#pragma GCC diagnostic ignored "-Wexit-time-destructors"
#endif

        const std::regex cdc{"^([A-Z][A-Z][A-Z]?) "};

        constexpr const char* re_international_name = "^(?:([AB][^/]*)/)?(?:([^/]+)/)?([^/]{2,})/0*([^/]+)/(19|20)?(\\d\\d)";
        constexpr const char* re_reassortant_passage = "(?:(?:\\s+|__)(.+))?";

          // [1] - type+subtype, [2] - host, [3] - location, [4] - isolation-number (omitting leading zeros), [5] - century, [6] - year (2 last digit), [7] - reassortant and passage
          // const std::regex international{"^([AB][^/]*)/(?:([^/]+)/)?([^/]+)/0*([^/]+)/(19|20)?(\\d\\d)(?:(?:\\s+|__)(.+))?$"};
        const std::regex international{std::string(re_international_name) + re_reassortant_passage + "$"};
        const std::regex international_name{re_international_name};

        const std::regex passage_after_name{" (MDCK|SIAT|MK|E|X)[X\\?\\d]"}; // to extract cdc name only! NOT to extract passage!

#pragma GCC diagnostic pop

        inline std::string make_year(const std::smatch& m)
        {
            std::string year;
            if (m[5].length())
                year = m[5].str() + m[6].str();
            else if (m[6].str()[0] > '2')
                year = "19" + m[6].str();
            else
                year = "20" + m[6].str();
            return year;
        }

        constexpr const size_t international_name_suffix_size = 9; // len(lo/isolation-number/year) >= 9

        inline std::string location_human(std::string name, size_t prefix_size)
        {
            const auto end = name.find('/', prefix_size);
            return name.substr(prefix_size, end - prefix_size);
        }
    }

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

    class Unrecognized : public std::runtime_error { public: using std::runtime_error::runtime_error; };

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

    std::string normalize(std::string name);

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

      // Extracts virus name without passage, reassortant, extra, etc.
    inline std::string_view name(const std::string& aFullName) // pass by reference! because we return string_view to it
    {
        std::smatch m;
        if (std::regex_search(aFullName, m, _internal::international_name)) {
            return {aFullName.data(), static_cast<size_t>(m.length())};
        }
        else if (std::regex_search(aFullName, m, _internal::passage_after_name)) { // works for cdc name without extra and without reassortant (cdc names usually do not have reassortant)
            return {aFullName.data(), static_cast<size_t>(m.position())};
        }
        else {
            return aFullName;   // failed to split, perhaps cdc name without passage
        }
    }

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

    using location_func_t = std::string (*)(std::string);

      // returned cdc abbreviation starts with #
    inline std::string location(std::string name)
    {
        using namespace _internal;
        std::string location;
        std::smatch m;
        if (std::regex_match(name, m, international))
            location = m[3].str();
        else if (std::regex_search(name, m, cdc))
            location = "#" + m[1].str();
        else if (std::regex_search(name, m, international_name)) // international name with possible "garbage" after year, e.g. A/TOKYO/UT-IMS2-1/2014_HY-PR8-HA-N121K
            location = m[3].str();
        else
            throw Unrecognized{"No location in " + name};
        return location;
    }

      // Faster version of location() for A(H3N2)/ and A(H1N1)/ names without host field
    inline std::string location_human_a(std::string name)
    {
        constexpr const size_t prefix_size = 8;
        return (name.size() > (prefix_size + _internal::international_name_suffix_size) && name[prefix_size - 1] == '/') ?  _internal::location_human(name, prefix_size) : location(name);
    }

      // Faster version of location() for B/ names without host field
    inline std::string location_human_b(std::string name)
    {
        constexpr const size_t prefix_size = 2;
        return (name.size() > (prefix_size + _internal::international_name_suffix_size) && name[prefix_size - 1] == '/') ?  _internal::location_human(name, prefix_size) : location(name);
    }

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

    inline std::string_view virus_type(const std::string& name) // pass by reference! because we return string_view to it
    {
        std::smatch m;
        if (std::regex_match(name, m, _internal::international))
            return {name.data() + m.position(1), static_cast<size_t>(m.length(1))};
        throw Unrecognized("No virus_type in " + name);

    } // AntigenSerum::virus_type

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

    inline std::string year(std::string name)
    {
        std::smatch m;
        if (std::regex_match(name, m, _internal::international))
            return _internal::make_year(m);
        throw Unrecognized("No year in " + name);

    } // AntigenSerum::year

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

    inline void split(std::string name, std::string& virus_type, std::string& host, std::string& location, std::string& isolation, std::string& year, std::string& passage)
    {
        std::smatch m;
        if (std::regex_match(name, m, _internal::international)) {
            virus_type = m[1].str();
            host = m[2].str();
            location = m[3].str();
            isolation = m[4].str();
            year = _internal::make_year(m);
            passage = m[7].str();
        }
        else
            throw Unrecognized("Cannot split " + name);
    }

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

      // Extracts virus name without passage, reassortant, extra,
      // etc. and calculates match threshold (to use with
      // acmacs_chart::Antigens::find_by_name_matching), match threshold is a square
      // of virus name length.
    inline size_t match_threshold(std::string name)
    {
        size_t result = 0;
        std::smatch m;
        if (std::regex_search(name, m, _internal::international_name)) {
              // find end of year (m[6])
            const auto end_of_year_offset = static_cast<size_t>(m[6].second - name.begin());
            result = end_of_year_offset * end_of_year_offset;
              // std::cerr << "INFO: match_threshold: end_of_year_offset:" << end_of_year_offset << " name:" << name << std::endl;
        }
        return result;
    }

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

}

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>improvements in parsing virus names having "garbage" after year<commit_after>#pragma once

#include <exception>
#include <regex>
#include <iostream>

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

namespace virus_name
{
    namespace _internal
    {
#pragma GCC diagnostic push
#ifdef __clang__
#pragma GCC diagnostic ignored "-Wglobal-constructors"
#pragma GCC diagnostic ignored "-Wexit-time-destructors"
#endif

        const std::regex cdc{"^([A-Z][A-Z][A-Z]?) "};

        constexpr const char* re_international_name = "^(?:([AB][^/]*)/)?(?:([^/]+)/)?([^/]{2,})/0*([^/]+)/(19|20)?(\\d\\d)";
        constexpr const char* re_reassortant_passage = "(?:(?:\\s+|__)(.+))?";

          // [1] - type+subtype, [2] - host, [3] - location, [4] - isolation-number (omitting leading zeros), [5] - century, [6] - year (2 last digit), [7] - reassortant and passage
          // const std::regex international{"^([AB][^/]*)/(?:([^/]+)/)?([^/]+)/0*([^/]+)/(19|20)?(\\d\\d)(?:(?:\\s+|__)(.+))?$"};
        const std::regex international{std::string(re_international_name) + re_reassortant_passage + "$"};
        const std::regex international_name{re_international_name};
        const std::regex international_name_with_extra{std::string(re_international_name) + "(?:\\s*(.+))?"};

        const std::regex passage_after_name{" (MDCK|SIAT|MK|E|X)[X\\?\\d]"}; // to extract cdc name only! NOT to extract passage!

#pragma GCC diagnostic pop

        inline std::string make_year(const std::smatch& m)
        {
            std::string year;
            if (m[5].length())
                year = m[5].str() + m[6].str();
            else if (m[6].str()[0] > '2')
                year = "19" + m[6].str();
            else
                year = "20" + m[6].str();
            return year;
        }

        constexpr const size_t international_name_suffix_size = 9; // len(lo/isolation-number/year) >= 9

        inline std::string location_human(std::string name, size_t prefix_size)
        {
            const auto end = name.find('/', prefix_size);
            return name.substr(prefix_size, end - prefix_size);
        }
    }

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

    class Unrecognized : public std::runtime_error { public: using std::runtime_error::runtime_error; };

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

    std::string normalize(std::string name);

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

      // Extracts virus name without passage, reassortant, extra, etc.
    inline std::string_view name(const std::string& aFullName) // pass by reference! because we return string_view to it
    {
        std::smatch m;
        if (std::regex_search(aFullName, m, _internal::international_name)) {
            return {aFullName.data(), static_cast<size_t>(m.length())};
        }
        else if (std::regex_search(aFullName, m, _internal::passage_after_name)) { // works for cdc name without extra and without reassortant (cdc names usually do not have reassortant)
            return {aFullName.data(), static_cast<size_t>(m.position())};
        }
        else {
            return aFullName;   // failed to split, perhaps cdc name without passage
        }
    }

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

    using location_func_t = std::string (*)(std::string);

      // returned cdc abbreviation starts with #
    inline std::string location(std::string name)
    {
        using namespace _internal;
        std::string location;
        std::smatch m;
        if (std::regex_search(name, m, international_name)) // international name with possible "garbage" after year, e.g. A/TOKYO/UT-IMS2-1/2014_HY-PR8-HA-N121K
            location = m[3].str();
        else if (std::regex_search(name, m, cdc))
            location = "#" + m[1].str();
        else
            throw Unrecognized{"No location in " + name};

        // if (std::regex_match(name, m, international))
        //     location = m[3].str();
        // else if (std::regex_search(name, m, cdc))
        //     location = "#" + m[1].str();
        // else if (std::regex_search(name, m, international_name)) // international name with possible "garbage" after year, e.g. A/TOKYO/UT-IMS2-1/2014_HY-PR8-HA-N121K
        //     location = m[3].str();
        // else
        //     throw Unrecognized{"No location in " + name};

        return location;
    }

      // Faster version of location() for A(H3N2)/ and A(H1N1)/ names without host field
    inline std::string location_human_a(std::string name)
    {
        constexpr const size_t prefix_size = 8;
        return (name.size() > (prefix_size + _internal::international_name_suffix_size) && name[prefix_size - 1] == '/') ?  _internal::location_human(name, prefix_size) : location(name);
    }

      // Faster version of location() for B/ names without host field
    inline std::string location_human_b(std::string name)
    {
        constexpr const size_t prefix_size = 2;
        return (name.size() > (prefix_size + _internal::international_name_suffix_size) && name[prefix_size - 1] == '/') ?  _internal::location_human(name, prefix_size) : location(name);
    }

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

    inline std::string_view virus_type(const std::string& name) // pass by reference! because we return string_view to it
    {
        std::smatch m;
        if (std::regex_search(name, m, _internal::international_name))
            return {name.data() + m.position(1), static_cast<size_t>(m.length(1))};
        throw Unrecognized("No virus_type in " + name);

    } // AntigenSerum::virus_type

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

    inline std::string year(std::string name)
    {
        std::smatch m;
        if (std::regex_search(name, m, _internal::international_name))
            return _internal::make_year(m);
        throw Unrecognized("No year in " + name);

    } // AntigenSerum::year

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

    inline void split(std::string name, std::string& virus_type, std::string& host, std::string& location, std::string& isolation, std::string& year, std::string& passage)
    {
        std::smatch m;
        if (std::regex_match(name, m, _internal::international)) {
            virus_type = m[1].str();
            host = m[2].str();
            location = m[3].str();
            isolation = m[4].str();
            year = _internal::make_year(m);
            passage = m[7].str();
        }
        else
            throw Unrecognized("Cannot split " + name);
    }

      // split for names looking like international but with unrecognized "garbage" (extra) at the end
    inline void split_with_extra(std::string name, std::string& virus_type, std::string& host, std::string& location, std::string& isolation, std::string& year, std::string& passage, std::string& extra)
    {
        try {
            split(name, virus_type, host, location, isolation, year, passage);
        }
        catch (Unrecognized&) {
            std::smatch m;
            if (std::regex_search(name, m, _internal::international_name_with_extra)) {
                virus_type = m[1].str();
                host = m[2].str();
                location = m[3].str();
                isolation = m[4].str();
                year = _internal::make_year(m);
                extra = m[7].str();
            }
            else
                throw Unrecognized("Cannot split " + name);
        }
    }

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

    // Extracts virus name without passage, reassortant, extra,
    // etc. and calculates match threshold (to use with
    // acmacs_chart::Antigens::find_by_name_matching), match threshold is a square
    // of virus name length.
    inline size_t match_threshold(std::string name)
    {
        size_t result = 0;
        std::smatch m;
        if (std::regex_search(name, m, _internal::international_name)) {
              // find end of year (m[6])
            const auto end_of_year_offset = static_cast<size_t>(m[6].second - name.begin());
            result = end_of_year_offset * end_of_year_offset;
              // std::cerr << "INFO: match_threshold: end_of_year_offset:" << end_of_year_offset << " name:" << name << std::endl;
        }
        return result;
    }

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

}

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact:  Qt Software Information (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
**
**************************************************************************/

#include "qmlproject.h"
#include "qmlprojectconstants.h"

#include <projectexplorer/toolchain.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <extensionsystem/pluginmanager.h>
#include <utils/pathchooser.h>
#include <utils/qtcassert.h>
#include <coreplugin/icore.h>
#include <coreplugin/editormanager/editormanager.h>

#include <utils/synchronousprocess.h>
#include <utils/pathchooser.h>

#include <QtCore/QtDebug>
#include <QtCore/QDir>
#include <QtCore/QSettings>
#include <QtCore/QProcess>
#include <QtCore/QCoreApplication>

#include <QtGui/QFormLayout>
#include <QtGui/QMainWindow>
#include <QtGui/QComboBox>
#include <QtGui/QMessageBox>

using namespace QmlProjectManager;
using namespace QmlProjectManager::Internal;

////////////////////////////////////////////////////////////////////////////////////
// QmlProject
////////////////////////////////////////////////////////////////////////////////////

QmlProject::QmlProject(Manager *manager, const QString &fileName)
    : m_manager(manager),
      m_fileName(fileName)
{
    QFileInfo fileInfo(m_fileName);
    m_projectName = fileInfo.completeBaseName();

    m_file = new QmlProjectFile(this, fileName);
    m_rootNode = new QmlProjectNode(this, m_file);

    m_manager->registerProject(this);
}

QmlProject::~QmlProject()
{
    m_manager->unregisterProject(this);

    delete m_rootNode;
}

QDir QmlProject::projectDir() const
{
    return QFileInfo(file()->fileName()).dir();
}

QString QmlProject::filesFileName() const
{ return m_fileName; }

static QStringList readLines(const QString &absoluteFileName)
{
    QStringList lines;

    QFile file(absoluteFileName);
    if (file.open(QFile::ReadOnly)) {
        QTextStream stream(&file);

        forever {
            QString line = stream.readLine();
            if (line.isNull())
                break;

            line = line.trimmed();
            if (line.isEmpty())
                continue;

            lines.append(line);
        }
    }

    return lines;
}

void QmlProject::parseProject(RefreshOptions options)
{
    if (options & Files) {
        m_files = convertToAbsoluteFiles(readLines(filesFileName()));
        m_files.removeDuplicates();
    }

    if (options & Configuration) {
        // update configuration
    }

    if (options & Files)
        emit fileListChanged();
}

void QmlProject::refresh(RefreshOptions options)
{
    QSet<QString> oldFileList;
    if (!(options & Configuration))
        oldFileList = m_files.toSet();

    parseProject(options);

    if (options & Files)
        m_rootNode->refresh();
}

QStringList QmlProject::convertToAbsoluteFiles(const QStringList &paths) const
{
    const QDir projectDir(QFileInfo(m_fileName).dir());
    QStringList absolutePaths;
    foreach (const QString &file, paths) {
        QFileInfo fileInfo(projectDir, file);
        absolutePaths.append(fileInfo.absoluteFilePath());
    }
    absolutePaths.removeDuplicates();
    return absolutePaths;
}

QStringList QmlProject::files() const
{ return m_files; }

QString QmlProject::buildParser(const QString &) const
{
    return QString();
}

QString QmlProject::name() const
{
    return m_projectName;
}

Core::IFile *QmlProject::file() const
{
    return m_file;
}

Manager *QmlProject::projectManager() const
{
    return m_manager;
}

QList<ProjectExplorer::Project *> QmlProject::dependsOn()
{
    return QList<Project *>();
}

bool QmlProject::isApplication() const
{
    return true;
}

bool QmlProject::hasBuildSettings() const
{
    return false;
}

ProjectExplorer::Environment QmlProject::environment(const QString &) const
{
    return ProjectExplorer::Environment::systemEnvironment();
}

QString QmlProject::buildDirectory(const QString &) const
{
    return QString();
}

ProjectExplorer::BuildStepConfigWidget *QmlProject::createConfigWidget()
{
    return 0;
}

QList<ProjectExplorer::BuildStepConfigWidget*> QmlProject::subConfigWidgets()
{
    return QList<ProjectExplorer::BuildStepConfigWidget*>();
}

void QmlProject::newBuildConfiguration(const QString &)
{
}

QmlProjectNode *QmlProject::rootProjectNode() const
{
    return m_rootNode;
}

QStringList QmlProject::files(FilesMode) const
{
    return m_files;
}

QStringList QmlProject::targets() const
{
    QStringList targets;
    return targets;
}

QmlMakeStep *QmlProject::makeStep() const
{
    return 0;
}

void QmlProject::restoreSettingsImpl(ProjectExplorer::PersistentSettingsReader &reader)
{
    Project::restoreSettingsImpl(reader);

    if (runConfigurations().isEmpty()) {
        QSharedPointer<QmlRunConfiguration> runConf(new QmlRunConfiguration(this));
        addRunConfiguration(runConf);
    }

    refresh(Everything);
}

void QmlProject::saveSettingsImpl(ProjectExplorer::PersistentSettingsWriter &writer)
{
    Project::saveSettingsImpl(writer);
}

////////////////////////////////////////////////////////////////////////////////////
// QmlProjectFile
////////////////////////////////////////////////////////////////////////////////////

QmlProjectFile::QmlProjectFile(QmlProject *parent, QString fileName)
    : Core::IFile(parent),
      m_project(parent),
      m_fileName(fileName)
{ }

QmlProjectFile::~QmlProjectFile()
{ }

bool QmlProjectFile::save(const QString &)
{
    return false;
}

QString QmlProjectFile::fileName() const
{
    return m_fileName;
}

QString QmlProjectFile::defaultPath() const
{
    return QString();
}

QString QmlProjectFile::suggestedFileName() const
{
    return QString();
}

QString QmlProjectFile::mimeType() const
{
    return Constants::QMLMIMETYPE;
}

bool QmlProjectFile::isModified() const
{
    return false;
}

bool QmlProjectFile::isReadOnly() const
{
    return true;
}

bool QmlProjectFile::isSaveAsAllowed() const
{
    return false;
}

void QmlProjectFile::modified(ReloadBehavior *)
{
}

QmlRunConfiguration::QmlRunConfiguration(QmlProject *pro)
    : ProjectExplorer::ApplicationRunConfiguration(pro),
      m_project(pro),
      m_type(Constants::QMLRUNCONFIGURATION)
{
    setName(tr("QML Viewer"));

    m_qmlViewer = Core::Utils::SynchronousProcess::locateBinary(QLatin1String("qmlviewer"));
}

QmlRunConfiguration::~QmlRunConfiguration()
{
}

QString QmlRunConfiguration::type() const
{
    return m_type;
}

QString QmlRunConfiguration::executable() const
{
    if (! QFile::exists(m_qmlViewer)) {
        QMessageBox::information(Core::ICore::instance()->mainWindow(),
                                 tr("QML Viewer"),
                                 tr("Could not find the qmlviewer executable, please specify one."));
    }

    return m_qmlViewer;
}

QmlRunConfiguration::RunMode QmlRunConfiguration::runMode() const
{
    return Gui;
}

QString QmlRunConfiguration::workingDirectory() const
{
    QFileInfo projectFile(m_project->file()->fileName());
    return projectFile.filePath();
}

QStringList QmlRunConfiguration::commandLineArguments() const
{
    QStringList args;

    const QString s = mainScript();
    if (! s.isEmpty())
        args.append(s);

    return args;
}

ProjectExplorer::Environment QmlRunConfiguration::environment() const
{
    return ProjectExplorer::Environment::systemEnvironment();
}

QString QmlRunConfiguration::dumperLibrary() const
{
    return QString();
}

QWidget *QmlRunConfiguration::configurationWidget()
{
    QWidget *config = new QWidget;
    QFormLayout *form = new QFormLayout(config);

    QComboBox *combo = new QComboBox;

    QDir projectDir = m_project->projectDir();
    QStringList files;

    files.append(tr("<Current File>"));

    int currentIndex = -1;

    foreach (const QString &fn, m_project->files()) {
        QFileInfo fileInfo(fn);
        if (fileInfo.suffix() != QLatin1String("qml"))
            continue;

        QString fileName = projectDir.relativeFilePath(fn);
        if (fileName == m_scriptFile)
            currentIndex = files.size();

        files.append(fileName);
    }

    combo->addItems(files);
    if (currentIndex != -1)
        combo->setCurrentIndex(currentIndex);

    connect(combo, SIGNAL(activated(QString)), this, SLOT(setMainScript(QString)));

    Core::Utils::PathChooser *qmlViewer = new Core::Utils::PathChooser;
    qmlViewer->setExpectedKind(Core::Utils::PathChooser::Command);
    qmlViewer->setPath(executable());
    connect(qmlViewer, SIGNAL(changed()), this, SLOT(onQmlViewerChanged()));

    form->addRow(tr("QML Viewer"), qmlViewer);
    form->addRow(tr("Main QML File:"), combo);

    return config;
}

QString QmlRunConfiguration::mainScript() const
{
    if (m_scriptFile.isEmpty() || m_scriptFile == tr("<Current File>")) {
        Core::EditorManager *editorManager = Core::ICore::instance()->editorManager();
        if (Core::IEditor *editor = editorManager->currentEditor()) {
            return editor->file()->fileName();
        }
    }

    return m_project->projectDir().absoluteFilePath(m_scriptFile);
}

void QmlRunConfiguration::setMainScript(const QString &scriptFile)
{
    m_scriptFile = scriptFile;
}

void QmlRunConfiguration::onQmlViewerChanged()
{
    if (Core::Utils::PathChooser *chooser = qobject_cast<Core::Utils::PathChooser *>(sender())) {
        m_qmlViewer = chooser->path();
    }
}

void QmlRunConfiguration::save(ProjectExplorer::PersistentSettingsWriter &writer) const
{
    ProjectExplorer::ApplicationRunConfiguration::save(writer);

    writer.saveValue(QLatin1String("qmlviewer"), m_qmlViewer);
    writer.saveValue(QLatin1String("mainscript"), m_scriptFile);
}

void QmlRunConfiguration::restore(const ProjectExplorer::PersistentSettingsReader &reader)
{
    ProjectExplorer::ApplicationRunConfiguration::restore(reader);

    m_qmlViewer = reader.restoreValue(QLatin1String("qmlviewer")).toString();
    m_scriptFile = reader.restoreValue(QLatin1String("mainscript")).toString();

    if (m_qmlViewer.isEmpty())
        m_qmlViewer = Core::Utils::SynchronousProcess::locateBinary(QLatin1String("qmlviewer"));

    if (m_scriptFile.isEmpty())
        m_scriptFile = tr("<Current File>");
}

QmlRunConfigurationFactory::QmlRunConfigurationFactory()
    : m_type(Constants::QMLRUNCONFIGURATION)
{
}

QmlRunConfigurationFactory::~QmlRunConfigurationFactory()
{
}

bool QmlRunConfigurationFactory::canCreate(const QString &type) const
{
    if (type.startsWith(m_type))
        return true;

    return false;
}

QStringList QmlRunConfigurationFactory::canCreate(ProjectExplorer::Project *) const
{
    return QStringList();
}

QString QmlRunConfigurationFactory::nameForType(const QString &type) const
{
    return type;
}

QSharedPointer<ProjectExplorer::RunConfiguration> QmlRunConfigurationFactory::create(ProjectExplorer::Project *project,
                                                                                const QString &)
{
    QmlProject *pro = qobject_cast<QmlProject *>(project);
    QSharedPointer<ProjectExplorer::RunConfiguration> rc(new QmlRunConfiguration(pro));
    return rc;
}

<commit_msg>Set the working directory<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact:  Qt Software Information (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
**
**************************************************************************/

#include "qmlproject.h"
#include "qmlprojectconstants.h"

#include <projectexplorer/toolchain.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <extensionsystem/pluginmanager.h>
#include <utils/pathchooser.h>
#include <utils/qtcassert.h>
#include <coreplugin/icore.h>
#include <coreplugin/editormanager/editormanager.h>

#include <utils/synchronousprocess.h>
#include <utils/pathchooser.h>

#include <QtCore/QtDebug>
#include <QtCore/QDir>
#include <QtCore/QSettings>
#include <QtCore/QProcess>
#include <QtCore/QCoreApplication>

#include <QtGui/QFormLayout>
#include <QtGui/QMainWindow>
#include <QtGui/QComboBox>
#include <QtGui/QMessageBox>

using namespace QmlProjectManager;
using namespace QmlProjectManager::Internal;

////////////////////////////////////////////////////////////////////////////////////
// QmlProject
////////////////////////////////////////////////////////////////////////////////////

QmlProject::QmlProject(Manager *manager, const QString &fileName)
    : m_manager(manager),
      m_fileName(fileName)
{
    QFileInfo fileInfo(m_fileName);
    m_projectName = fileInfo.completeBaseName();

    m_file = new QmlProjectFile(this, fileName);
    m_rootNode = new QmlProjectNode(this, m_file);

    m_manager->registerProject(this);
}

QmlProject::~QmlProject()
{
    m_manager->unregisterProject(this);

    delete m_rootNode;
}

QDir QmlProject::projectDir() const
{
    return QFileInfo(file()->fileName()).dir();
}

QString QmlProject::filesFileName() const
{ return m_fileName; }

static QStringList readLines(const QString &absoluteFileName)
{
    QStringList lines;

    QFile file(absoluteFileName);
    if (file.open(QFile::ReadOnly)) {
        QTextStream stream(&file);

        forever {
            QString line = stream.readLine();
            if (line.isNull())
                break;

            line = line.trimmed();
            if (line.isEmpty())
                continue;

            lines.append(line);
        }
    }

    return lines;
}

void QmlProject::parseProject(RefreshOptions options)
{
    if (options & Files) {
        m_files = convertToAbsoluteFiles(readLines(filesFileName()));
        m_files.removeDuplicates();
    }

    if (options & Configuration) {
        // update configuration
    }

    if (options & Files)
        emit fileListChanged();
}

void QmlProject::refresh(RefreshOptions options)
{
    QSet<QString> oldFileList;
    if (!(options & Configuration))
        oldFileList = m_files.toSet();

    parseProject(options);

    if (options & Files)
        m_rootNode->refresh();
}

QStringList QmlProject::convertToAbsoluteFiles(const QStringList &paths) const
{
    const QDir projectDir(QFileInfo(m_fileName).dir());
    QStringList absolutePaths;
    foreach (const QString &file, paths) {
        QFileInfo fileInfo(projectDir, file);
        absolutePaths.append(fileInfo.absoluteFilePath());
    }
    absolutePaths.removeDuplicates();
    return absolutePaths;
}

QStringList QmlProject::files() const
{ return m_files; }

QString QmlProject::buildParser(const QString &) const
{
    return QString();
}

QString QmlProject::name() const
{
    return m_projectName;
}

Core::IFile *QmlProject::file() const
{
    return m_file;
}

Manager *QmlProject::projectManager() const
{
    return m_manager;
}

QList<ProjectExplorer::Project *> QmlProject::dependsOn()
{
    return QList<Project *>();
}

bool QmlProject::isApplication() const
{
    return true;
}

bool QmlProject::hasBuildSettings() const
{
    return false;
}

ProjectExplorer::Environment QmlProject::environment(const QString &) const
{
    return ProjectExplorer::Environment::systemEnvironment();
}

QString QmlProject::buildDirectory(const QString &) const
{
    return QString();
}

ProjectExplorer::BuildStepConfigWidget *QmlProject::createConfigWidget()
{
    return 0;
}

QList<ProjectExplorer::BuildStepConfigWidget*> QmlProject::subConfigWidgets()
{
    return QList<ProjectExplorer::BuildStepConfigWidget*>();
}

void QmlProject::newBuildConfiguration(const QString &)
{
}

QmlProjectNode *QmlProject::rootProjectNode() const
{
    return m_rootNode;
}

QStringList QmlProject::files(FilesMode) const
{
    return m_files;
}

QStringList QmlProject::targets() const
{
    QStringList targets;
    return targets;
}

QmlMakeStep *QmlProject::makeStep() const
{
    return 0;
}

void QmlProject::restoreSettingsImpl(ProjectExplorer::PersistentSettingsReader &reader)
{
    Project::restoreSettingsImpl(reader);

    if (runConfigurations().isEmpty()) {
        QSharedPointer<QmlRunConfiguration> runConf(new QmlRunConfiguration(this));
        addRunConfiguration(runConf);
    }

    refresh(Everything);
}

void QmlProject::saveSettingsImpl(ProjectExplorer::PersistentSettingsWriter &writer)
{
    Project::saveSettingsImpl(writer);
}

////////////////////////////////////////////////////////////////////////////////////
// QmlProjectFile
////////////////////////////////////////////////////////////////////////////////////

QmlProjectFile::QmlProjectFile(QmlProject *parent, QString fileName)
    : Core::IFile(parent),
      m_project(parent),
      m_fileName(fileName)
{ }

QmlProjectFile::~QmlProjectFile()
{ }

bool QmlProjectFile::save(const QString &)
{
    return false;
}

QString QmlProjectFile::fileName() const
{
    return m_fileName;
}

QString QmlProjectFile::defaultPath() const
{
    return QString();
}

QString QmlProjectFile::suggestedFileName() const
{
    return QString();
}

QString QmlProjectFile::mimeType() const
{
    return Constants::QMLMIMETYPE;
}

bool QmlProjectFile::isModified() const
{
    return false;
}

bool QmlProjectFile::isReadOnly() const
{
    return true;
}

bool QmlProjectFile::isSaveAsAllowed() const
{
    return false;
}

void QmlProjectFile::modified(ReloadBehavior *)
{
}

QmlRunConfiguration::QmlRunConfiguration(QmlProject *pro)
    : ProjectExplorer::ApplicationRunConfiguration(pro),
      m_project(pro),
      m_type(Constants::QMLRUNCONFIGURATION)
{
    setName(tr("QML Viewer"));

    m_qmlViewer = Core::Utils::SynchronousProcess::locateBinary(QLatin1String("qmlviewer"));
}

QmlRunConfiguration::~QmlRunConfiguration()
{
}

QString QmlRunConfiguration::type() const
{
    return m_type;
}

QString QmlRunConfiguration::executable() const
{
    if (! QFile::exists(m_qmlViewer)) {
        QMessageBox::information(Core::ICore::instance()->mainWindow(),
                                 tr("QML Viewer"),
                                 tr("Could not find the qmlviewer executable, please specify one."));
    }

    return m_qmlViewer;
}

QmlRunConfiguration::RunMode QmlRunConfiguration::runMode() const
{
    return Gui;
}

QString QmlRunConfiguration::workingDirectory() const
{
    QFileInfo projectFile(m_project->file()->fileName());
    return projectFile.absolutePath();
}

QStringList QmlRunConfiguration::commandLineArguments() const
{
    QStringList args;

    const QString s = mainScript();
    if (! s.isEmpty())
        args.append(s);

    return args;
}

ProjectExplorer::Environment QmlRunConfiguration::environment() const
{
    return ProjectExplorer::Environment::systemEnvironment();
}

QString QmlRunConfiguration::dumperLibrary() const
{
    return QString();
}

QWidget *QmlRunConfiguration::configurationWidget()
{
    QWidget *config = new QWidget;
    QFormLayout *form = new QFormLayout(config);

    QComboBox *combo = new QComboBox;

    QDir projectDir = m_project->projectDir();
    QStringList files;

    files.append(tr("<Current File>"));

    int currentIndex = -1;

    foreach (const QString &fn, m_project->files()) {
        QFileInfo fileInfo(fn);
        if (fileInfo.suffix() != QLatin1String("qml"))
            continue;

        QString fileName = projectDir.relativeFilePath(fn);
        if (fileName == m_scriptFile)
            currentIndex = files.size();

        files.append(fileName);
    }

    combo->addItems(files);
    if (currentIndex != -1)
        combo->setCurrentIndex(currentIndex);

    connect(combo, SIGNAL(activated(QString)), this, SLOT(setMainScript(QString)));

    Core::Utils::PathChooser *qmlViewer = new Core::Utils::PathChooser;
    qmlViewer->setExpectedKind(Core::Utils::PathChooser::Command);
    qmlViewer->setPath(executable());
    connect(qmlViewer, SIGNAL(changed()), this, SLOT(onQmlViewerChanged()));

    form->addRow(tr("QML Viewer"), qmlViewer);
    form->addRow(tr("Main QML File:"), combo);

    return config;
}

QString QmlRunConfiguration::mainScript() const
{
    if (m_scriptFile.isEmpty() || m_scriptFile == tr("<Current File>")) {
        Core::EditorManager *editorManager = Core::ICore::instance()->editorManager();
        if (Core::IEditor *editor = editorManager->currentEditor()) {
            return editor->file()->fileName();
        }
    }

    return m_project->projectDir().absoluteFilePath(m_scriptFile);
}

void QmlRunConfiguration::setMainScript(const QString &scriptFile)
{
    m_scriptFile = scriptFile;
}

void QmlRunConfiguration::onQmlViewerChanged()
{
    if (Core::Utils::PathChooser *chooser = qobject_cast<Core::Utils::PathChooser *>(sender())) {
        m_qmlViewer = chooser->path();
    }
}

void QmlRunConfiguration::save(ProjectExplorer::PersistentSettingsWriter &writer) const
{
    ProjectExplorer::ApplicationRunConfiguration::save(writer);

    writer.saveValue(QLatin1String("qmlviewer"), m_qmlViewer);
    writer.saveValue(QLatin1String("mainscript"), m_scriptFile);
}

void QmlRunConfiguration::restore(const ProjectExplorer::PersistentSettingsReader &reader)
{
    ProjectExplorer::ApplicationRunConfiguration::restore(reader);

    m_qmlViewer = reader.restoreValue(QLatin1String("qmlviewer")).toString();
    m_scriptFile = reader.restoreValue(QLatin1String("mainscript")).toString();

    if (m_qmlViewer.isEmpty())
        m_qmlViewer = Core::Utils::SynchronousProcess::locateBinary(QLatin1String("qmlviewer"));

    if (m_scriptFile.isEmpty())
        m_scriptFile = tr("<Current File>");
}

QmlRunConfigurationFactory::QmlRunConfigurationFactory()
    : m_type(Constants::QMLRUNCONFIGURATION)
{
}

QmlRunConfigurationFactory::~QmlRunConfigurationFactory()
{
}

bool QmlRunConfigurationFactory::canCreate(const QString &type) const
{
    if (type.startsWith(m_type))
        return true;

    return false;
}

QStringList QmlRunConfigurationFactory::canCreate(ProjectExplorer::Project *) const
{
    return QStringList();
}

QString QmlRunConfigurationFactory::nameForType(const QString &type) const
{
    return type;
}

QSharedPointer<ProjectExplorer::RunConfiguration> QmlRunConfigurationFactory::create(ProjectExplorer::Project *project,
                                                                                const QString &)
{
    QmlProject *pro = qobject_cast<QmlProject *>(project);
    QSharedPointer<ProjectExplorer::RunConfiguration> rc(new QmlRunConfiguration(pro));
    return rc;
}

<|endoftext|>