<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1999-2008 Robert Osfield
 *
 * This software is open source and may be redistributed and/or modified under
 * the terms of the GNU General Public License (GPL) version 2.0.
 * The full license is in LICENSE.txt file included with this distribution,.
 *
 * This software 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
 * include LICENSE.txt for more details.
*/

#include <osg/Timer>

#include <osgDB/ReaderWriter>
#include <osgDB/FileNameUtils>
#include <osgDB/Registry>

#include <osgWidget/VncClient>

extern "C" {
#include <rfb/rfbclient.h>
}

class LibVncImage : public osgWidget::VncImage
{
    public:

        LibVncImage();

        bool connect(const std::string& hostname);

        void close();

        virtual bool sendPointerEvent(int x, int y, int buttonMask);

        double getTimeOfLastUpdate() const { return _timeOfLastUpdate; }
        double getTimeOfLastRender() const { return _timeOfLastRender; }

        double time() const { return osg::Timer::instance()->time_s(); }

        virtual bool sendKeyEvent(int key, bool keyDown);

        virtual void setFrameLastRendered(const osg::FrameStamp* frameStamp);

        void updated();

        static rfbBool resizeImage(rfbClient* client);

        static void updateImage(rfbClient* client,int x,int y,int w,int h);

        double                      _timeOfLastUpdate;
        double                      _timeOfLastRender;

        bool                        _active;
        osg::ref_ptr<osg::RefBlock> _inactiveBlock;

    protected:

        virtual ~LibVncImage();

        class RfbThread : public osg::Referenced, public OpenThreads::Thread
        {
        public:

            RfbThread(rfbClient* client, LibVncImage* image):
                _client(client),
                _image(image),
                _done(false) {}

            virtual ~RfbThread()
            {
                _done = true;
                while(isRunning())
                {
                    OpenThreads::Thread::YieldCurrentThread();
                }
            }

            virtual void run()
            {
                do
                {
                    if (_image->_active)
                    {
                        int i=WaitForMessage(_client,5000);
                        if(i<0)
                            return;

                        if(i)
                        {
                            osg::notify(osg::NOTICE)<<"Handling "<<i<<" messages"<<std::endl;

                            if(!HandleRFBServerMessage(_client))
                            return;

                            _image->updated();
                        }
                    }
                    else
                    {
                        _image->_inactiveBlock->block();
                    }

                    double deltaTime = _image->getTimeOfLastRender() - _image->getTimeOfLastUpdate();
                    if (deltaTime<-0.01)
                    {
                        //osg::notify(osg::NOTICE)<<"Inactive"<<std::endl;
                        //_image->_active = false;
                    }
                    else
                    {
                        _image->_active = true;
                    }

                } while (!_done && !testCancel());
            }

            rfbClient*                      _client;
            osg::observer_ptr<LibVncImage>  _image;
            bool                            _done;

        };

    public:

        rfbClient* _client;

        osg::ref_ptr<RfbThread>     _rfbThread;

};

LibVncImage::LibVncImage():
    _client(0)
{
    // setPixelBufferObject(new osg::PixelBufferObject(this);

    _inactiveBlock = new osg::RefBlock;

}

LibVncImage::~LibVncImage()
{
    close();
}

static rfbBool rfbInitConnection(rfbClient* client)
{
  /* Unless we accepted an incoming connection, make a TCP connection to the
     given VNC server */

  if (!client->listenSpecified) {
    if (!client->serverHost || !ConnectToRFBServer(client,client->serverHost,client->serverPort))
      return FALSE;
  }

  /* Initialise the VNC connection, including reading the password */

  if (!InitialiseRFBConnection(client))
    return FALSE;

  if (!SetFormatAndEncodings(client))
    return FALSE;

  client->width=client->si.framebufferWidth;
  client->height=client->si.framebufferHeight;
  client->MallocFrameBuffer(client);

  if (client->updateRect.x < 0) {
    client->updateRect.x = client->updateRect.y = 0;
    client->updateRect.w = client->width;
    client->updateRect.h = client->height;
  }

  if (client->appData.scaleSetting>1)
  {
      if (!SendScaleSetting(client, client->appData.scaleSetting))
          return FALSE;
      if (!SendFramebufferUpdateRequest(client,
                  client->updateRect.x / client->appData.scaleSetting,
                  client->updateRect.y / client->appData.scaleSetting,
                  client->updateRect.w / client->appData.scaleSetting,
                  client->updateRect.h / client->appData.scaleSetting,
                  FALSE))
          return FALSE;
  }
  else
  {
      if (!SendFramebufferUpdateRequest(client,
                  client->updateRect.x, client->updateRect.y,
                  client->updateRect.w, client->updateRect.h,
                  FALSE))
      return FALSE;
  }

  return TRUE;
}

bool LibVncImage::connect(const std::string& hostname)
{
    if (hostname.empty()) return false;

    if (_client) close();

    _client = rfbGetClient(8,3,4);
    _client->canHandleNewFBSize = TRUE;
    _client->MallocFrameBuffer = resizeImage;
    _client->GotFrameBufferUpdate = updateImage;
    _client->HandleKeyboardLedState = 0;
    _client->HandleTextChat = 0;

    rfbClientSetClientData(_client, 0, this);

    _client->serverHost = strdup(hostname.c_str());

    // _client->serverPort = ;
    // _client->appData.qualityLevel = ;
    // _client->appData.encodings = ;
    // _client->appData.compressLevel = ;
    // _client->appData.scaleSetting = ;

    if(rfbInitConnection(_client))
    {
        _rfbThread = new RfbThread(_client, this);
        _rfbThread->startThread();

        return true;
    }
    else
    {
        close();

        return false;
    }
}

void LibVncImage::close()
{
    if (_rfbThread.valid())
    {
        _inactiveBlock->release();

        // stop the client thread
        _rfbThread = 0;
    }

    if (_client)
    {
        // close the client
        rfbClientCleanup(_client);
        _client = 0;
    }
}

rfbBool LibVncImage::resizeImage(rfbClient* client)
{
    osg::Image* image = (osg::Image*)(rfbClientGetClientData(client, 0));

    int width=client->width;
    int height=client->height;
    int depth=client->format.bitsPerPixel;

    osg::notify(osg::NOTICE)<<"resize "<<width<<", "<<height<<", "<<depth<<" image = "<<image<<std::endl;

    image->allocateImage(width,height,1,GL_RGBA,GL_UNSIGNED_BYTE);

    client->frameBuffer= (uint8_t*)(image->data());

    return TRUE;
}

void LibVncImage::updateImage(rfbClient* client,int x,int y,int w,int h)
{
    osg::Image* image = (osg::Image*)(rfbClientGetClientData(client, 0));
    image->dirty();
}

bool LibVncImage::sendPointerEvent(int x, int y, int buttonMask)
{
    if (_client)
    {
        SendPointerEvent(_client ,x, y, buttonMask);
        return true;
    }
    return false;
}

bool LibVncImage::sendKeyEvent(int key, bool keyDown)
{
    if (_client)
    {
        SendKeyEvent(_client, key, keyDown ? TRUE : FALSE);
        return true;
    }
    return false;
}

void LibVncImage::setFrameLastRendered(const osg::FrameStamp*)
{
    _timeOfLastRender = time();

    if (!_active) _inactiveBlock->release();
    _active = true;
}

void LibVncImage::updated()
{
    _timeOfLastUpdate = time();
}

class ReaderWriterVNC : public osgDB::ReaderWriter
{
    public:

        ReaderWriterVNC()
        {
            supportsExtension("vnc","VNC plugin");
        }

        virtual const char* className() const { return "VNC plugin"; }

        virtual osgDB::ReaderWriter::ReadResult readObject(const std::string& file, const osgDB::ReaderWriter::Options* options) const
        {
            return readImage(file,options);
        }

        virtual osgDB::ReaderWriter::ReadResult readImage(const std::string& fileName, const osgDB::ReaderWriter::Options* options) const
        {
            if (!osgDB::equalCaseInsensitive(osgDB::getFileExtension(fileName),"vnc"))
            {
                return osgDB::ReaderWriter::ReadResult::FILE_NOT_HANDLED;
            }

            std::string hostname = osgDB::getNameLessExtension(fileName);

            osg::notify(osg::NOTICE)<<"Hostname = "<<hostname<<std::endl;

            osg::ref_ptr<LibVncImage> image = new LibVncImage;
            image->setDataVariance(osg::Object::DYNAMIC);

            image->setOrigin(osg::Image::TOP_LEFT);

            if (!image->connect(hostname))
            {
                return "Could not connect to "+hostname;
            }

            return image.get();
        }

        virtual osgDB::ReaderWriter::ReadResult readNode(const std::string& fileName, const osgDB::ReaderWriter::Options* options) const
        {
            osgDB::ReaderWriter::ReadResult result = readImage(fileName, options);
            if (!result.validImage()) return result;

            osg::ref_ptr<osgWidget::VncClient> vncClient = new osgWidget::VncClient();
            if (vncClient->assign(dynamic_cast<osgWidget::VncImage*>(result.getImage())))
            {
                return vncClient.release();
            }
            else
            {
                return osgDB::ReaderWriter::ReadResult::FILE_NOT_HANDLED;
            }
        }
};

// now register with Registry to instantiate the above
// reader/writer.
REGISTER_OSGPLUGIN(vnc, ReaderWriterVNC)

<commit_msg>Converted osg::notify to OSG_INFO etc.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1999-2008 Robert Osfield
 *
 * This software is open source and may be redistributed and/or modified under
 * the terms of the GNU General Public License (GPL) version 2.0.
 * The full license is in LICENSE.txt file included with this distribution,.
 *
 * This software 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
 * include LICENSE.txt for more details.
*/

#include <osg/Timer>

#include <osgDB/ReaderWriter>
#include <osgDB/FileNameUtils>
#include <osgDB/Registry>

#include <osgWidget/VncClient>

extern "C" {
#include <rfb/rfbclient.h>
}

class LibVncImage : public osgWidget::VncImage
{
    public:

        LibVncImage();

        bool connect(const std::string& hostname);

        void close();

        virtual bool sendPointerEvent(int x, int y, int buttonMask);

        double getTimeOfLastUpdate() const { return _timeOfLastUpdate; }
        double getTimeOfLastRender() const { return _timeOfLastRender; }

        double time() const { return osg::Timer::instance()->time_s(); }

        virtual bool sendKeyEvent(int key, bool keyDown);

        virtual void setFrameLastRendered(const osg::FrameStamp* frameStamp);

        void updated();

        static rfbBool resizeImage(rfbClient* client);

        static void updateImage(rfbClient* client,int x,int y,int w,int h);

        double                      _timeOfLastUpdate;
        double                      _timeOfLastRender;

        bool                        _active;
        osg::ref_ptr<osg::RefBlock> _inactiveBlock;

    protected:

        virtual ~LibVncImage();

        class RfbThread : public osg::Referenced, public OpenThreads::Thread
        {
        public:

            RfbThread(rfbClient* client, LibVncImage* image):
                _client(client),
                _image(image),
                _done(false) {}

            virtual ~RfbThread()
            {
                _done = true;
                while(isRunning())
                {
                    OpenThreads::Thread::YieldCurrentThread();
                }
            }

            virtual void run()
            {
                do
                {
                    if (_image->_active)
                    {
                        int i=WaitForMessage(_client,5000);
                        if(i<0)
                            return;

                        if(i)
                        {
                            OSG_NOTICE<<"Handling "<<i<<" messages"<<std::endl;

                            if(!HandleRFBServerMessage(_client))
                            return;

                            _image->updated();
                        }
                    }
                    else
                    {
                        _image->_inactiveBlock->block();
                    }

                    double deltaTime = _image->getTimeOfLastRender() - _image->getTimeOfLastUpdate();
                    if (deltaTime<-0.01)
                    {
                        //OSG_NOTICE<<"Inactive"<<std::endl;
                        //_image->_active = false;
                    }
                    else
                    {
                        _image->_active = true;
                    }

                } while (!_done && !testCancel());
            }

            rfbClient*                      _client;
            osg::observer_ptr<LibVncImage>  _image;
            bool                            _done;

        };

    public:

        rfbClient* _client;

        osg::ref_ptr<RfbThread>     _rfbThread;

};

LibVncImage::LibVncImage():
    _client(0)
{
    // setPixelBufferObject(new osg::PixelBufferObject(this);

    _inactiveBlock = new osg::RefBlock;

}

LibVncImage::~LibVncImage()
{
    close();
}

static rfbBool rfbInitConnection(rfbClient* client)
{
  /* Unless we accepted an incoming connection, make a TCP connection to the
     given VNC server */

  if (!client->listenSpecified) {
    if (!client->serverHost || !ConnectToRFBServer(client,client->serverHost,client->serverPort))
      return FALSE;
  }

  /* Initialise the VNC connection, including reading the password */

  if (!InitialiseRFBConnection(client))
    return FALSE;

  if (!SetFormatAndEncodings(client))
    return FALSE;

  client->width=client->si.framebufferWidth;
  client->height=client->si.framebufferHeight;
  client->MallocFrameBuffer(client);

  if (client->updateRect.x < 0) {
    client->updateRect.x = client->updateRect.y = 0;
    client->updateRect.w = client->width;
    client->updateRect.h = client->height;
  }

  if (client->appData.scaleSetting>1)
  {
      if (!SendScaleSetting(client, client->appData.scaleSetting))
          return FALSE;
      if (!SendFramebufferUpdateRequest(client,
                  client->updateRect.x / client->appData.scaleSetting,
                  client->updateRect.y / client->appData.scaleSetting,
                  client->updateRect.w / client->appData.scaleSetting,
                  client->updateRect.h / client->appData.scaleSetting,
                  FALSE))
          return FALSE;
  }
  else
  {
      if (!SendFramebufferUpdateRequest(client,
                  client->updateRect.x, client->updateRect.y,
                  client->updateRect.w, client->updateRect.h,
                  FALSE))
      return FALSE;
  }

  return TRUE;
}

bool LibVncImage::connect(const std::string& hostname)
{
    if (hostname.empty()) return false;

    if (_client) close();

    _client = rfbGetClient(8,3,4);
    _client->canHandleNewFBSize = TRUE;
    _client->MallocFrameBuffer = resizeImage;
    _client->GotFrameBufferUpdate = updateImage;
    _client->HandleKeyboardLedState = 0;
    _client->HandleTextChat = 0;

    rfbClientSetClientData(_client, 0, this);

    _client->serverHost = strdup(hostname.c_str());

    // _client->serverPort = ;
    // _client->appData.qualityLevel = ;
    // _client->appData.encodings = ;
    // _client->appData.compressLevel = ;
    // _client->appData.scaleSetting = ;

    if(rfbInitConnection(_client))
    {
        _rfbThread = new RfbThread(_client, this);
        _rfbThread->startThread();

        return true;
    }
    else
    {
        close();

        return false;
    }
}

void LibVncImage::close()
{
    if (_rfbThread.valid())
    {
        _inactiveBlock->release();

        // stop the client thread
        _rfbThread = 0;
    }

    if (_client)
    {
        // close the client
        rfbClientCleanup(_client);
        _client = 0;
    }
}

rfbBool LibVncImage::resizeImage(rfbClient* client)
{
    osg::Image* image = (osg::Image*)(rfbClientGetClientData(client, 0));

    int width=client->width;
    int height=client->height;
    int depth=client->format.bitsPerPixel;

    OSG_NOTICE<<"resize "<<width<<", "<<height<<", "<<depth<<" image = "<<image<<std::endl;

    image->allocateImage(width,height,1,GL_RGBA,GL_UNSIGNED_BYTE);

    client->frameBuffer= (uint8_t*)(image->data());

    return TRUE;
}

void LibVncImage::updateImage(rfbClient* client,int x,int y,int w,int h)
{
    osg::Image* image = (osg::Image*)(rfbClientGetClientData(client, 0));
    image->dirty();
}

bool LibVncImage::sendPointerEvent(int x, int y, int buttonMask)
{
    if (_client)
    {
        SendPointerEvent(_client ,x, y, buttonMask);
        return true;
    }
    return false;
}

bool LibVncImage::sendKeyEvent(int key, bool keyDown)
{
    if (_client)
    {
        SendKeyEvent(_client, key, keyDown ? TRUE : FALSE);
        return true;
    }
    return false;
}

void LibVncImage::setFrameLastRendered(const osg::FrameStamp*)
{
    _timeOfLastRender = time();

    if (!_active) _inactiveBlock->release();
    _active = true;
}

void LibVncImage::updated()
{
    _timeOfLastUpdate = time();
}

class ReaderWriterVNC : public osgDB::ReaderWriter
{
    public:

        ReaderWriterVNC()
        {
            supportsExtension("vnc","VNC plugin");
        }

        virtual const char* className() const { return "VNC plugin"; }

        virtual osgDB::ReaderWriter::ReadResult readObject(const std::string& file, const osgDB::ReaderWriter::Options* options) const
        {
            return readImage(file,options);
        }

        virtual osgDB::ReaderWriter::ReadResult readImage(const std::string& fileName, const osgDB::ReaderWriter::Options* options) const
        {
            if (!osgDB::equalCaseInsensitive(osgDB::getFileExtension(fileName),"vnc"))
            {
                return osgDB::ReaderWriter::ReadResult::FILE_NOT_HANDLED;
            }

            std::string hostname = osgDB::getNameLessExtension(fileName);

            OSG_NOTICE<<"Hostname = "<<hostname<<std::endl;

            osg::ref_ptr<LibVncImage> image = new LibVncImage;
            image->setDataVariance(osg::Object::DYNAMIC);

            image->setOrigin(osg::Image::TOP_LEFT);

            if (!image->connect(hostname))
            {
                return "Could not connect to "+hostname;
            }

            return image.get();
        }

        virtual osgDB::ReaderWriter::ReadResult readNode(const std::string& fileName, const osgDB::ReaderWriter::Options* options) const
        {
            osgDB::ReaderWriter::ReadResult result = readImage(fileName, options);
            if (!result.validImage()) return result;

            osg::ref_ptr<osgWidget::VncClient> vncClient = new osgWidget::VncClient();
            if (vncClient->assign(dynamic_cast<osgWidget::VncImage*>(result.getImage())))
            {
                return vncClient.release();
            }
            else
            {
                return osgDB::ReaderWriter::ReadResult::FILE_NOT_HANDLED;
            }
        }
};

// now register with Registry to instantiate the above
// reader/writer.
REGISTER_OSGPLUGIN(vnc, ReaderWriterVNC)

<|endoftext|>


<commit_before>#include <osg/Group>
#include <osgDB/FileUtils>
#include <osgDB/FileNameUtils>
#include <osgDB/ReadFile>
#include <osgDB/Registry>
#include <osgDB/Options>

#include <sstream>
#include "unzip.h"

class ReaderWriterZIP : public osgDB::ReaderWriter
{
    public:

        ReaderWriterZIP()
        {
            supportsExtension("zip","Zip archive format");
        }

        virtual const char* className() const { return "ZIP Database Reader/Writer"; }

        virtual ReadResult readNode(const std::string& file, const osgDB::Options* options) const
        {
            ReadResult rresult = ReadResult::FILE_NOT_HANDLED;

            //Check to see if option is to load and extract to filesystem
            bool bExtractToFileSystem = false;
            if (options)
            {
                std::string optExtractTo = options->getPluginStringData("zipextract");
                if (!(optExtractTo.empty()))
                {
                    if (osgDB::convertToLowerCase(optExtractTo)=="filesystem")
                    {
                        bExtractToFileSystem = true;
                    }
                }
            }

            if (bExtractToFileSystem)
            {
                rresult = original_readNode(file,options);
            }
            else
            {
                std::string ext = osgDB::getLowerCaseFileExtension(file);
                if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;

                std::string fileName = osgDB::findDataFile( file, options );
                if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;

                osg::notify(osg::INFO)<<"ReaderWriterZIP::readNode( "<<fileName.c_str()<<" )\n";

                // First open file as stream
                std::ifstream srcFileStrm(fileName.c_str(),std::ios::in|std::ios::binary);
                if (!srcFileStrm.fail())
                {
                    // Now read entire zip file into stream buffer
                    std::stringstream tmpStrmBuffer;
                    srcFileStrm.seekg(0,std::ios_base::beg);
                    tmpStrmBuffer.operator <<(srcFileStrm.rdbuf());
                    srcFileStrm.close();

                    // Setup appropriate options
                    osg::ref_ptr<Options> local_opt = options ?
                        static_cast<Options*>(options->clone(osg::CopyOp::SHALLOW_COPY)) :
                        new Options;

                    // minor issue associated with database path list, as in context of zip file it
                    // doesn't make sense. Need to set to empty path for other plugins to access
                    local_opt->getDatabasePathList().push_front(osgDB::getFilePath(file));

                    //    Now pass through to memory zip handler
                    rresult = readNode(tmpStrmBuffer,local_opt.get());

                    // Clean up options
                    local_opt->getDatabasePathList().pop_front();
                }
            }

            return rresult;
        }

        virtual ReadResult readNode(std::istream& fin,const osgDB::Options* options) const
        {
            ReadResult result = ReadResult(ReadResult::FILE_NOT_HANDLED);

            if (!fin.fail())
            {
                unsigned int ulzipFileLength;
                fin.seekg(0,std::ios_base::end);
                ulzipFileLength = fin.tellg();
                fin.seekg(0,std::ios_base::beg);

                // Decompress stream to standard stream
                HZIP hz;

                // Need to decouple stream content as I can't see any other way to get access to a byte array
                // containing the content in the stream. One saving grace here is that we know that the
                // stream has already been fully read in, hence no need to concern ourselves with asynchronous
                // reads.

                //void * pMemBuffer = malloc(ulzipFileLength);
                char * pMemBuffer = new char [ulzipFileLength];
                if (pMemBuffer)
                {
                    fin.read(pMemBuffer,ulzipFileLength);
                    if ((unsigned int)fin.gcount()==ulzipFileLength)
                    {
                        hz = OpenZip(pMemBuffer, ulzipFileLength, "");  SetUnzipBaseDir(hz,_T("\\"));

                        ZIPENTRY ze;
                        GetZipItem(hz,-1,&ze);
                        int numitems=ze.index;

                        // Initialise top level group
                        osg::ref_ptr<osg::Group> grp = new osg::Group;
                        if (grp.valid())
                        {
                            // Now loop through each file in zip
                            for (int i=0; i<numitems; i++)
                            {
                                GetZipItem(hz,i,&ze);
                                std::string StreamName = ze.name;
                                std::stringstream buffer;

                                char *ibuf = new char[ze.unc_size];
                                if (ibuf)
                                {
                                    UnzipItem(hz,i, ibuf, ze.unc_size);
                                    buffer.write(ibuf,ze.unc_size);
                                    delete[] ibuf;
                                    // Now ready to read node //

                                    std::string file_ext = osgDB::getFileExtension(StreamName);

                                    ReaderWriter* rw = osgDB::Registry::instance()->getReaderWriterForExtension(file_ext);
                                    if (rw)
                                    {
                                        // Setup appropriate options
                                        osg::ref_ptr<Options> local_opt = options ?
                                            static_cast<Options*>(options->clone(osg::CopyOp::SHALLOW_COPY)) :
                                            new Options;

                                        local_opt->setPluginStringData("STREAM_FILENAME",osgDB::getSimpleFileName(StreamName));

                                        result = rw->readNode(buffer,local_opt.get());
                                        if (result.validNode())
                                        {
                                            grp->addChild( result.takeNode() );
                                        }
                                    }
                                }
                            }
                            if( grp->getNumChildren() == 0 )
                                result = ReadResult(ReadResult::FILE_NOT_HANDLED);
                            else
                                result = grp.get();
                        }
                        else
                            result = ReadResult(ReadResult::FILE_NOT_HANDLED);
                    }
                    else
                        result = ReadResult(ReadResult::FILE_NOT_HANDLED);
                    delete [] pMemBuffer;
                }
                else
                    result = ReadResult(ReadResult::FILE_NOT_HANDLED);

            }
            return result;
        }

        virtual ReadResult original_readNode(const std::string& file, const osgDB::Options* options) const
        {

            std::string ext = osgDB::getLowerCaseFileExtension(file);
            if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;

            std::string fileName = osgDB::findDataFile( file, options );
            if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;

            osg::notify(osg::INFO)<<"ReaderWriterZIP::readNode( "<<fileName.c_str()<<" )\n";

            char dirname[128];
            char command[1024];

        #if defined(WIN32) && !defined(__CYGWIN__)
            if ( getenv("TEMP") != NULL ){
               strcpy(dirname, getenv("TEMP"));
            }else{
               //TEMP environment variable not set so pick current directory.
               strcpy(dirname, "./");
            }
            strcat(dirname, "\\.osgdb_zip");

            mkdir(dirname);
            // Using unzip.exe from http://www.info-zip.org/pub/infozip/UnZip.html
            // unzip.exe must be in your path.  (PATH environment variable).

            // OR - WinRAR

            // Checking for WinRAR
            std::string winrar = std::string( getenv( "ProgramFiles" ) ) + "/WinRAR/winrar.exe";
            if ( osgDB::fileExists(winrar) ) {
                sprintf( command,
                    "%s x -o+ \"%s\" \"%s\"", winrar.c_str(),
                    fileName.c_str(), dirname);
            } else {
                sprintf( command,
                    "unzip -o -qq \"%s\" -d \"%s\"",
                    fileName.c_str(), dirname);
            }

        #else
            sprintf( dirname, "/tmp/.zip%06d", getpid());
            mkdir( dirname, 0700 );

            sprintf( command,
                "unzip %s -d %s",
                fileName.c_str(), dirname);

        #endif

            osg::notify(osg::INFO)<<"Running command '"<<command<<"'"<<std::endl;
            if ( system( command ) ) {
                return ReadResult::FILE_NOT_HANDLED;
            }

            osg::ref_ptr<osg::Group> grp = new osg::Group;

            osg::ref_ptr<osgDB::ReaderWriter::Options> local_options = options ? static_cast<osgDB::ReaderWriter::Options*>(options->clone(osg::CopyOp::SHALLOW_COPY)) : new osgDB::ReaderWriter::Options;
            local_options->getDatabasePathList().push_front(dirname);

            // deactivate the automatic generation of images to geode's.
            bool prevCreateNodeFromImage = osgDB::Registry::instance()->getCreateNodeFromImage();
            osgDB::Registry::instance()->setCreateNodeFromImage(false);

            osgDB::DirectoryContents contents = osgDB::getDirectoryContents(dirname);
            for(osgDB::DirectoryContents::iterator itr = contents.begin();
                itr != contents.end();
                ++itr)
            {
                std::string file_ext = osgDB::getFileExtension(*itr);
                if (!acceptsExtension(file_ext) &&
                    *itr!=std::string(".") &&
                    *itr!=std::string(".."))
                {
                    osg::Node *node = osgDB::readNodeFile( *itr, local_options.get() );
                    grp->addChild( node );
                }
            }

            osgDB::Registry::instance()->setCreateNodeFromImage(prevCreateNodeFromImage);

        #if defined(WIN32) && !defined(__CYGWIN__)
            // note, is this the right command for windows?
            // is there any way of overiding the Y/N option? RO.
            sprintf( command, "erase /S /Q \"%s\"", dirname );
            int result = system( command );
        #else

            sprintf( command, "rm -rf %s", dirname );
            int result = system( command );
        #endif
            if (result!=0) return ReadResult::ERROR_IN_READING_FILE;

            if( grp->getNumChildren() == 0 )
            {
                return ReadResult::FILE_NOT_HANDLED;
            }

            return grp.get();
        }

};

// now register with sgRegistry to instantiate the above
// reader/writer.
REGISTER_OSGPLUGIN(zip, ReaderWriterZIP)
<commit_msg>From Chris Denham, "I discovered a memory leak in the ZIP plugin, which was caused by a missing call to CloseZip. I attach a modified ReaderWriterZIP.cpp  (based on version 2.9.5 revision 10374). This includes a little bit of code tidying, but the only functional change is a test of the return value of OpenZip and the addition of a call to CloseZip."<commit_after>#include <osg/Group>
#include <osgDB/FileUtils>
#include <osgDB/FileNameUtils>
#include <osgDB/ReadFile>
#include <osgDB/Registry>
#include <osgDB/Options>

#include <sstream>
#include "unzip.h"

class ReaderWriterZIP : public osgDB::ReaderWriter
{
    public:

        ReaderWriterZIP()
        {
            supportsExtension("zip","Zip archive format");
        }

        virtual const char* className() const { return "ZIP Database Reader/Writer"; }

        virtual ReadResult readNode(const std::string& file, const osgDB::Options* options) const
        {
            ReadResult rresult = ReadResult::FILE_NOT_HANDLED;

            //Check to see if option is to load and extract to filesystem
            bool bExtractToFileSystem = false;
            if (options)
            {
                std::string optExtractTo = options->getPluginStringData("zipextract");
                if (!(optExtractTo.empty()))
                {
                    if (osgDB::convertToLowerCase(optExtractTo)=="filesystem")
                    {
                        bExtractToFileSystem = true;
                    }
                }
            }

            if (bExtractToFileSystem)
            {
                rresult = original_readNode(file,options);
            }
            else
            {
                std::string ext = osgDB::getLowerCaseFileExtension(file);
                if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;

                std::string fileName = osgDB::findDataFile( file, options );
                if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;

                osg::notify(osg::INFO)<<"ReaderWriterZIP::readNode( "<<fileName.c_str()<<" )\n";

                // First open file as stream
                std::ifstream srcFileStrm(fileName.c_str(),std::ios::in|std::ios::binary);
                if (!srcFileStrm.fail())
                {
                    // Now read entire zip file into stream buffer
                    std::stringstream tmpStrmBuffer;
                    srcFileStrm.seekg(0,std::ios_base::beg);
                    tmpStrmBuffer.operator <<(srcFileStrm.rdbuf());
                    srcFileStrm.close();

                    // Setup appropriate options
                    osg::ref_ptr<Options> local_opt = options ?
                        static_cast<Options*>(options->clone(osg::CopyOp::SHALLOW_COPY)) :
                        new Options;

                    // minor issue associated with database path list, as in context of zip file it
                    // doesn't make sense. Need to set to empty path for other plugins to access
                    local_opt->getDatabasePathList().push_front(osgDB::getFilePath(file));

                    //    Now pass through to memory zip handler
                    rresult = readNode(tmpStrmBuffer,local_opt.get());

                    // Clean up options
                    local_opt->getDatabasePathList().pop_front();
                }
            }

            return rresult;
        }

        virtual ReadResult readNode(std::istream& fin,const osgDB::Options* options) const
        {
            ReadResult result = ReadResult(ReadResult::FILE_NOT_HANDLED);

            if (fin.fail()) return result;

            fin.seekg(0,std::ios_base::end);
            unsigned int ulzipFileLength = fin.tellg();
            fin.seekg(0,std::ios_base::beg);

            // Need to decouple stream content as I can't see any other way to get access to a byte array
            // containing the content in the stream. One saving grace here is that we know that the
            // stream has already been fully read in, hence no need to concern ourselves with asynchronous
            // reads.
            char * pMemBuffer = new char [ulzipFileLength];
            if (!pMemBuffer) return result;

            fin.read(pMemBuffer, ulzipFileLength);
            if ((unsigned int)fin.gcount() == ulzipFileLength)
            {
                HZIP hz = OpenZip(pMemBuffer, ulzipFileLength, "");
                if (hz)
                {
                    ZIPENTRY ze;
                    GetZipItem(hz,-1,&ze);
                    int numitems=ze.index;

                    // Initialise top level group
                    osg::ref_ptr<osg::Group> grp = new osg::Group;
                    if (grp.valid())
                    {
                        // Now loop through each file in zip
                        for (int i = 0; i < numitems; i++)
                        {
                            GetZipItem(hz,i,&ze);
                            std::string StreamName = ze.name;
                            std::stringstream buffer;

                            char *ibuf = new char[ze.unc_size];
                            if (ibuf)
                            {
                                UnzipItem(hz,i, ibuf, ze.unc_size);
                                buffer.write(ibuf,ze.unc_size);
                                delete[] ibuf;
                                // Now ready to read node //

                                std::string file_ext = osgDB::getFileExtension(StreamName);

                                ReaderWriter* rw = osgDB::Registry::instance()->getReaderWriterForExtension(file_ext);
                                if (rw)
                                {
                                    // Setup appropriate options
                                    osg::ref_ptr<Options> local_opt = options ?
                                        static_cast<Options*>(options->clone(osg::CopyOp::SHALLOW_COPY)) :
                                        new Options;

                                    local_opt->setPluginStringData("STREAM_FILENAME",osgDB::getSimpleFileName(StreamName));

                                    ReadResult readResult = rw->readNode(buffer,local_opt.get());
                                    if (readResult.validNode())
                                    {
                                        grp->addChild(readResult.takeNode());
                                    }
                                }
                            }
                        }
                        if (grp->getNumChildren() > 0)
                        {
                            result = grp.get();
                        }
                    }
                    CloseZip(hz);
                }
            }
            delete [] pMemBuffer;

            return result;
        }

        virtual ReadResult original_readNode(const std::string& file, const osgDB::Options* options) const
        {

            std::string ext = osgDB::getLowerCaseFileExtension(file);
            if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;

            std::string fileName = osgDB::findDataFile( file, options );
            if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;

            osg::notify(osg::INFO)<<"ReaderWriterZIP::readNode( "<<fileName.c_str()<<" )\n";

            char dirname[128];
            char command[1024];

        #if defined(WIN32) && !defined(__CYGWIN__)
            if ( getenv("TEMP") != NULL ){
               strcpy(dirname, getenv("TEMP"));
            }else{
               //TEMP environment variable not set so pick current directory.
               strcpy(dirname, "./");
            }
            strcat(dirname, "\\.osgdb_zip");

            mkdir(dirname);
            // Using unzip.exe from http://www.info-zip.org/pub/infozip/UnZip.html
            // unzip.exe must be in your path.  (PATH environment variable).

            // OR - WinRAR

            // Checking for WinRAR
            std::string winrar = std::string( getenv( "ProgramFiles" ) ) + "/WinRAR/winrar.exe";
            if ( osgDB::fileExists(winrar) ) {
                sprintf( command,
                    "%s x -o+ \"%s\" \"%s\"", winrar.c_str(),
                    fileName.c_str(), dirname);
            } else {
                sprintf( command,
                    "unzip -o -qq \"%s\" -d \"%s\"",
                    fileName.c_str(), dirname);
            }

        #else
            sprintf( dirname, "/tmp/.zip%06d", getpid());
            mkdir( dirname, 0700 );

            sprintf( command,
                "unzip %s -d %s",
                fileName.c_str(), dirname);

        #endif

            osg::notify(osg::INFO)<<"Running command '"<<command<<"'"<<std::endl;
            if ( system( command ) ) {
                return ReadResult::FILE_NOT_HANDLED;
            }

            osg::ref_ptr<osg::Group> grp = new osg::Group;

            osg::ref_ptr<osgDB::ReaderWriter::Options> local_options = options ? static_cast<osgDB::ReaderWriter::Options*>(options->clone(osg::CopyOp::SHALLOW_COPY)) : new osgDB::ReaderWriter::Options;
            local_options->getDatabasePathList().push_front(dirname);

            // deactivate the automatic generation of images to geode's.
            bool prevCreateNodeFromImage = osgDB::Registry::instance()->getCreateNodeFromImage();
            osgDB::Registry::instance()->setCreateNodeFromImage(false);

            osgDB::DirectoryContents contents = osgDB::getDirectoryContents(dirname);
            for(osgDB::DirectoryContents::iterator itr = contents.begin();
                itr != contents.end();
                ++itr)
            {
                std::string file_ext = osgDB::getFileExtension(*itr);
                if (!acceptsExtension(file_ext) &&
                    *itr!=std::string(".") &&
                    *itr!=std::string(".."))
                {
                    osg::Node *node = osgDB::readNodeFile( *itr, local_options.get() );
                    grp->addChild( node );
                }
            }

            osgDB::Registry::instance()->setCreateNodeFromImage(prevCreateNodeFromImage);

        #if defined(WIN32) && !defined(__CYGWIN__)
            // note, is this the right command for windows?
            // is there any way of overiding the Y/N option? RO.
            sprintf( command, "erase /S /Q \"%s\"", dirname );
            int result = system( command );
        #else

            sprintf( command, "rm -rf %s", dirname );
            int result = system( command );
        #endif
            if (result!=0) return ReadResult::ERROR_IN_READING_FILE;

            if( grp->getNumChildren() == 0 )
            {
                return ReadResult::FILE_NOT_HANDLED;
            }

            return grp.get();
        }

};

// now register with sgRegistry to instantiate the above
// reader/writer.
REGISTER_OSGPLUGIN(zip, ReaderWriterZIP)
<|endoftext|>


<commit_before>/**
 * Path manipulation utilities
 */

#include "path.h"
#include <string>
#include <sys/stat.h>
#include <sys/types.h>
#include <limits.h>
#include <stdlib.h>

#ifdef windows
#	include <io.h>
#	define realpath(in, out) _fullpath(out, in, PATH_MAX)
#endif

/**
 * Normalize path by removing "./", "../" and resolving symlinks
 */
std::string path_normalize(std::string path) {
	char * p = new char[PATH_MAX];
	realpath(path.c_str(), p);
	std::string result(p);
	delete[] p;
	return result;
/*
	std::string result = path;

	size_t pos = 0;
	int state = 1; // 0 bad, 1 just after dirname, 2 dot
	while (pos != result.length()) {
		char ch = result.at(pos);
		switch (ch) {
			case '/':
			case '\\':
				if (state == 0) { state = 1; }
				if (state == 2) {
					pos -= 1;
					result.erase(pos, 2);
				}
			break;

			case '.':
				if (state == 1) {
					state = 2;
				} else {
					state = 0;
				}
			break;
			default: state = 0; break;
		}
		pos++;
	}

	return result;
*/
}

/**
 * Return file name component of path
 */
std::string path_filename(std::string path) {
	size_t pos = path_lastslash(path);
	if (pos != std::string::npos) { path.erase(0, pos+1); }
	return path;
}

/**
 * Return directory name component of path
 */
std::string path_dirname(std::string path) {
	size_t pos = path_lastslash(path);
	if (pos != std::string::npos) { path.erase(pos, path.length()-pos); }
	return path;
}

/**
 * Return index of last slash (normal or backslash) in a path
 */
size_t path_lastslash(std::string path) {
	size_t pos = path.find_last_of('/');
	if (pos == std::string::npos) { pos = path.find_last_of('\\'); }
	return pos;
}

/**
 * Is this path absolute?
 */
bool path_isabsolute(std::string path) {
#ifdef windows
	size_t pos = path.find(':');
	return (pos != std::string::npos);
#else
	if (path.length() == 0) { return false; }
	return (path.at(0) == '/');
#endif
}

/**
 * Does a file exist at this path?
 */
bool path_file_exists(std::string path) {
	struct stat st;
	if (stat(path.c_str(), &st) != 0) { return false; } /* does not exist */
	if (st.st_mode & S_IFDIR) { return false; } /* is directory */
	return true;
}

/**
 * Does a directory exist at this path?
 */
bool path_dir_exists(std::string path) {
	struct stat st;
	if (stat(path.c_str(), &st) != 0) { return false; } /* does not exist */
	if (st.st_mode & S_IFDIR) { return true; } /* is directory */
	return false;
}

/**
 * Get current working directory
 */
std::string path_getcwd() {
	return getcwd(NULL, 0);
}

/**
 * Change current directory
 */
void path_chdir(std::string dir) {
#ifdef VERBOSE
	printf("[path_chdir] chdir to '%s'\n", dir.c_str());
#endif
	chdir(dir.c_str());
}
<commit_msg>memory leak fix<commit_after>/**
 * Path manipulation utilities
 */

#include "path.h"
#include <string>
#include <sys/stat.h>
#include <sys/types.h>
#include <limits.h>
#include <stdlib.h>

#ifdef windows
#	include <io.h>
#	define realpath(in, out) _fullpath(out, in, PATH_MAX)
#endif

/**
 * Normalize path by removing "./", "../" and resolving symlinks
 */
std::string path_normalize(std::string path) {
	char * p = new char[PATH_MAX];
	realpath(path.c_str(), p);
	std::string result(p);
	delete[] p;
	return result;
/*
	std::string result = path;

	size_t pos = 0;
	int state = 1; // 0 bad, 1 just after dirname, 2 dot
	while (pos != result.length()) {
		char ch = result.at(pos);
		switch (ch) {
			case '/':
			case '\\':
				if (state == 0) { state = 1; }
				if (state == 2) {
					pos -= 1;
					result.erase(pos, 2);
				}
			break;

			case '.':
				if (state == 1) {
					state = 2;
				} else {
					state = 0;
				}
			break;
			default: state = 0; break;
		}
		pos++;
	}

	return result;
*/
}

/**
 * Return file name component of path
 */
std::string path_filename(std::string path) {
	size_t pos = path_lastslash(path);
	if (pos != std::string::npos) { path.erase(0, pos+1); }
	return path;
}

/**
 * Return directory name component of path
 */
std::string path_dirname(std::string path) {
	size_t pos = path_lastslash(path);
	if (pos != std::string::npos) { path.erase(pos, path.length()-pos); }
	return path;
}

/**
 * Return index of last slash (normal or backslash) in a path
 */
size_t path_lastslash(std::string path) {
	size_t pos = path.find_last_of('/');
	if (pos == std::string::npos) { pos = path.find_last_of('\\'); }
	return pos;
}

/**
 * Is this path absolute?
 */
bool path_isabsolute(std::string path) {
#ifdef windows
	size_t pos = path.find(':');
	return (pos != std::string::npos);
#else
	if (path.length() == 0) { return false; }
	return (path.at(0) == '/');
#endif
}

/**
 * Does a file exist at this path?
 */
bool path_file_exists(std::string path) {
	struct stat st;
	if (stat(path.c_str(), &st) != 0) { return false; } /* does not exist */
	if (st.st_mode & S_IFDIR) { return false; } /* is directory */
	return true;
}

/**
 * Does a directory exist at this path?
 */
bool path_dir_exists(std::string path) {
	struct stat st;
	if (stat(path.c_str(), &st) != 0) { return false; } /* does not exist */
	if (st.st_mode & S_IFDIR) { return true; } /* is directory */
	return false;
}

/**
 * Get current working directory
 */
std::string path_getcwd() {
	char * buf = getcwd(NULL, 0);
	std::string result(buf);
	free(buf);
	return result;
}

/**
 * Change current directory
 */
void path_chdir(std::string dir) {
#ifdef VERBOSE
	printf("[path_chdir] chdir to '%s'\n", dir.c_str());
#endif
	chdir(dir.c_str());
}
<|endoftext|>


<commit_before>#ifndef HEADER_GUARD_MODE_H
#define HEADER_GUARD_MODE_H

#include <functional>
#include <map>
#include <string>

extern std::map < char, std::function<void ()> > global_normal_map;
extern std::map < char, std::function<void ()> > global_insert_map;

struct mode {
    public:
    mode(const std::string&, bool (*const handle)(char));

    bool operator()(char);

    mode(const mode&);
    mode& operator=(const mode&);

    std::string get_name();

    static mode fundamental; // use global maps only

    private:
    std::string name;
    // true = has binding
    bool (*handle)(char);
};
#endif
<commit_msg>Move mode's properties to beginning<commit_after>#ifndef HEADER_GUARD_MODE_H
#define HEADER_GUARD_MODE_H

#include <functional>
#include <map>
#include <string>

extern std::map < char, std::function<void ()> > global_normal_map;
extern std::map < char, std::function<void ()> > global_insert_map;

struct mode {
    private:
    std::string name;
    // true = has binding
    bool (*handle)(char);

    public:
    mode(const std::string&, bool (*const handle)(char));

    bool operator()(char);

    mode(const mode&);
    mode& operator=(const mode&);

    std::string get_name();

    static mode fundamental; // use global maps only
};
#endif
<|endoftext|>


<commit_before>/*
 * qconnman - Connman Applet
 * Copyright (C) 2011 O.S. Systems
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "wirelesspage.h"
#include "connman.h"
#include "authdialog.h"
#include "hiddennetworkdialog.h"

#include <qconnman/manager.h>
#include <qconnman/service.h>

#include <QListView>
#include <QMessageBox>
#include <QDebug>
#include <QTreeView>

WirelessPage::WirelessPage(const QModelIndex &technology, Manager *manager, QWidget *parent):
    QWidget(parent),
    m_technology(technology),
    m_service(NULL)
{
    ui.setupUi(this);

    m_wireless = static_cast<ManagerNode*>(technology.internalPointer())->object<Technology *>();

    ui.enabled->setChecked(m_wireless->isPowered());
    ui.ipv4Widget->hide();

    ui.networkList->setModel(manager);
    ui.networkList->setRootModelIndex(technology);
    ui.networkList->setCurrentIndex(-1);

    connect(manager, SIGNAL(servicesChanged()), SLOT(configureService()));
    connect(m_wireless, SIGNAL(dataChanged()), SLOT(updateUi()));
    connect(ui.enabled, SIGNAL(toggled(bool)), SLOT(toggleTechnology(bool)));
    connect(ui.networkList, SIGNAL(currentIndexChanged(int)), SLOT(setService(int)));

    configureService();
    updateUi();
}

void WirelessPage::updateUi()
{
    ui.enabled->setChecked(m_wireless->isPowered());

    if (m_service && m_wireless->isPowered() && (m_service->state() == Service::ReadyState || m_service->state() == Service::OnlineState))
    {
        ui.status->setText("Connected");
        ui.ipv4Widget->setService(m_service);
        ui.ipv4Widget->unhide();
        ui.advancedButton->setEnabled(true);
    }
    else if (!m_service || (m_service->state() == Service::IdleState || m_service->state() == Service::DisconnectState))
    {
        ui.status->setText("Disconnected");
        ui.ipv4Widget->hide();
    }
}

void WirelessPage::configureService()
{
    for (int i = 0; i < m_technology.model()->rowCount(m_technology); i++)
    {
        Service *service = static_cast<ManagerNode *>(m_technology.child(i, 0).internalPointer())->object<Service *>();
        if (service->type() != "wifi") continue;

        if (service->state() == Service::ReadyState || service->state() == Service::OnlineState)
        {
            ui.networkList->setCurrentIndex(i);
            m_service = service;
            updateUi();
            break;
        }
    }
}

void WirelessPage::unconfigureService()
{
    Service *service = (Service *)QObject::sender();
    if (!service)
        return;
    m_service = NULL;
}

void WirelessPage::toggleTechnology(bool enable)
{
    m_wireless->setPowered(enable);
    if (!enable)
        ui.networkList->setCurrentIndex(-1);
}

void WirelessPage::setService(int index)
{
	if (index == -1) return;

    ManagerNode *node = static_cast<ManagerNode *>(m_technology.child(index, 1).internalPointer());
    m_service = node->object<Service *>();

    ui.ipv4Widget->setService(m_service);

    connect(m_service, SIGNAL(dataChanged()), SLOT(updateUi()));
    connect(m_service, SIGNAL(destroyed()), SLOT(unconfigureService()));

    if (m_service->state() == Service::ReadyState || m_service->state() == Service::OnlineState)
        ui.ipv4Widget->unhide();
    else
        ui.ipv4Widget->hide();
}
<commit_msg>Connect to service<commit_after>/*
 * qconnman - Connman Applet
 * Copyright (C) 2011 O.S. Systems
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "wirelesspage.h"
#include "connman.h"
#include "authdialog.h"
#include "hiddennetworkdialog.h"

#include <qconnman/manager.h>
#include <qconnman/service.h>

#include <QListView>
#include <QMessageBox>
#include <QDebug>
#include <QTreeView>

WirelessPage::WirelessPage(const QModelIndex &technology, Manager *manager, QWidget *parent):
    QWidget(parent),
    m_technology(technology),
    m_service(NULL)
{
    ui.setupUi(this);

    m_wireless = static_cast<ManagerNode*>(technology.internalPointer())->object<Technology *>();

    ui.enabled->setChecked(m_wireless->isPowered());
    ui.ipv4Widget->hide();

    ui.networkList->setModel(manager);
    ui.networkList->setRootModelIndex(technology);
    ui.networkList->setCurrentIndex(-1);

    connect(manager, SIGNAL(servicesChanged()), SLOT(configureService()));
    connect(m_wireless, SIGNAL(dataChanged()), SLOT(updateUi()));
    connect(ui.enabled, SIGNAL(toggled(bool)), SLOT(toggleTechnology(bool)));
    connect(ui.networkList, SIGNAL(currentIndexChanged(int)), SLOT(setService(int)));

    configureService();
    updateUi();
}

void WirelessPage::updateUi()
{
    ui.enabled->setChecked(m_wireless->isPowered());

    if (m_service && m_wireless->isPowered() && (m_service->state() == Service::ReadyState || m_service->state() == Service::OnlineState))
    {
        ui.status->setText("Connected");
        ui.ipv4Widget->setService(m_service);
        ui.ipv4Widget->unhide();
        ui.advancedButton->setEnabled(true);
    }
    else if (!m_service || (m_service->state() == Service::IdleState || m_service->state() == Service::DisconnectState))
    {
        ui.status->setText("Disconnected");
        ui.ipv4Widget->hide();
    }
}

void WirelessPage::configureService()
{
    for (int i = 0; i < m_technology.model()->rowCount(m_technology); i++)
    {
        Service *service = static_cast<ManagerNode *>(m_technology.child(i, 0).internalPointer())->object<Service *>();
        if (service->type() != "wifi") continue;

        if (service->state() == Service::ReadyState || service->state() == Service::OnlineState)
        {
            ui.networkList->setCurrentIndex(i);
            m_service = service;
            updateUi();
            break;
        }
    }
}

void WirelessPage::unconfigureService()
{
    Service *service = (Service *)QObject::sender();
    if (!service)
        return;
    m_service = NULL;
}

void WirelessPage::toggleTechnology(bool enable)
{
    m_wireless->setPowered(enable);
    if (!enable)
        ui.networkList->setCurrentIndex(-1);
}

void WirelessPage::setService(int index)
{
	if (index == -1) return;

    ManagerNode *node = static_cast<ManagerNode *>(m_technology.child(index, 1).internalPointer());
    m_service = node->object<Service *>();

    ui.ipv4Widget->setService(m_service);

    connect(m_service, SIGNAL(dataChanged()), SLOT(updateUi()));
    connect(m_service, SIGNAL(destroyed()), SLOT(unconfigureService()));

    if (m_service->state() == Service::ReadyState || m_service->state() == Service::OnlineState)
        ui.ipv4Widget->unhide();
    else
        ui.ipv4Widget->hide();

    m_service->connect();
}
<|endoftext|>


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

#include <yeti/yeti.h>

#include <csignal>
#include <cstdlib>
#include <ctime>

#include <iostream>

#include <map>
#include <mutex>
#include <string>
#include <yeti/logger.h>

namespace yeti {

const std::map<int, std::string> SIGNAME = {
    { SIGABRT, "SIGABRT" },
    { SIGFPE, "SIGFPE" },
    { SIGILL, "SIGILL" },
    { SIGINT, "SIGINT" },
    { SIGSEGV, "SIGSEGV" },
    { SIGTERM, "SIGTERM" }
};

void ShutdownLog() {
  yeti::Logger::instance().Shutdown();
}

void SignalHandler(int sig_num) {
  std::fprintf(stderr, "caught %s: start flushing log...\n",
               SIGNAME.at(sig_num).c_str());
  std::exit(sig_num);
}

void RegisterSignals() {
  std::atexit(ShutdownLog);
  for (const auto& entry : SIGNAME) {
    signal(entry.first, SignalHandler);
  }
}

std::string _CreateLogStr(const yeti::LogData& log_data) {
  std::map<std::string, std::string> subs;
  subs["%(LEVEL)"] = log_data.level;
  subs["%(FILENAME)"] = log_data.filename;
  subs["%(FUNCNAME)"] = log_data.funcname;
  subs["%(MSG)"] = log_data.msg;

  if (log_data.log_format.find("%(PID)") != std::string::npos) {
    subs["%(PID)"] = std::to_string(log_data.pid);
  }

  if (log_data.log_format.find("%(TID)") != std::string::npos) {
    std::hash<std::thread::id> hash_fn;
    std::ostringstream oss;
    oss << std::hex << std::uppercase << hash_fn(log_data.tid);
    subs["%(TID)"] = oss.str();
  }

  if (log_data.log_format.find("%(DATE)") != std::string::npos) {
    using namespace std::chrono;
    char date_buf[16] = { 0 };
    auto sec = duration_cast<seconds>(log_data.time.time_since_epoch());
    std::time_t t = sec.count();
    std::strftime(date_buf, sizeof(date_buf), "%F", std::localtime(&t));
    subs["%(DATE)"] = date_buf;
  }

  if (log_data.log_format.find("%(TIME)") != std::string::npos) {
    using namespace std::chrono;
    char time_buf[32] = { 0 };
    auto nanos = duration_cast<nanoseconds>(log_data.time.time_since_epoch());
    auto sec = duration_cast<seconds>(log_data.time.time_since_epoch());
    std::time_t t = sec.count();
    std::size_t frac = nanos.count() % 1000000000;
    std::strftime(time_buf, sizeof(time_buf), "%T", std::localtime(&t));
    std::string time_str = std::string(time_buf) + "." + std::to_string(frac);
    subs["%(TIME)"] = time_str;
  }

  if (log_data.log_format.find("%(LINE)") != std::string::npos) {
    subs["%(LINE)"] = std::to_string(log_data.line);
  }

  if (log_data.log_format.find("%(MSG_ID)") != std::string::npos) {
    subs["%(MSG_ID)"] = std::to_string(log_data.msg_id);
  }

  std::string result = log_data.log_format;
  size_t pos = 0;
  for (const auto& entry : subs) {
    while ((pos = result.find(entry.first)) != std::string::npos) {
      result.replace(pos, entry.first.length(), entry.second);
    }
  }
  return result;
}

void _EnqueueLogTask(LogData* log_data) {
  log_data->log_format = yeti::Logger::instance().GetFormatStr();
  log_data->time = std::chrono::high_resolution_clock::now();
  log_data->pid = getpid();
  log_data->tid = std::this_thread::get_id();
  log_data->fd = yeti::Logger::instance().GetFileDesc();
  bool is_colored = yeti::Logger::instance().IsColored();

  LogData printed_data = *log_data;
  auto print_func = [printed_data, is_colored] {
    std::string log_str = _CreateLogStr(printed_data) + "\n";
    if (isatty(fileno(printed_data.fd)) != 0 && is_colored) {
      log_str = printed_data.color + log_str + std::string(YETI_RESET);
    }
    std::fprintf(printed_data.fd, log_str.c_str());
  };

  yeti::Logger::instance().EnqueueTask(print_func);
}

}  // namespace yeti
<commit_msg>Fixed ANSI escape code bug at WIN32<commit_after>// Copyright (c) 2014, Dmitry Senin (seninds@gmail.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//   1. Redistributions of source code must retain the above copyright notice,
//      this list of conditions and the following disclaimer.
//   2. Redistributions in binary form must reproduce the above copyright
//      notice, this list of conditions and the following disclaimer in the
//      documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// yeti - C++ lightweight threadsafe logging
// URL: https://github.com/seninds/yeti.git

#include <yeti/yeti.h>

#include <csignal>
#include <cstdlib>
#include <ctime>

#include <iostream>

#include <map>
#include <mutex>
#include <string>
#include <yeti/logger.h>

namespace yeti {

const std::map<int, std::string> SIGNAME = {
    { SIGABRT, "SIGABRT" },
    { SIGFPE, "SIGFPE" },
    { SIGILL, "SIGILL" },
    { SIGINT, "SIGINT" },
    { SIGSEGV, "SIGSEGV" },
    { SIGTERM, "SIGTERM" }
};

void ShutdownLog() {
  yeti::Logger::instance().Shutdown();
}

void SignalHandler(int sig_num) {
  std::fprintf(stderr, "caught %s: start flushing log...\n",
               SIGNAME.at(sig_num).c_str());
  std::exit(sig_num);
}

void RegisterSignals() {
  std::atexit(ShutdownLog);
  for (const auto& entry : SIGNAME) {
    signal(entry.first, SignalHandler);
  }
}

std::string _CreateLogStr(const yeti::LogData& log_data) {
  std::map<std::string, std::string> subs;
  subs["%(LEVEL)"] = log_data.level;
  subs["%(FILENAME)"] = log_data.filename;
  subs["%(FUNCNAME)"] = log_data.funcname;
  subs["%(MSG)"] = log_data.msg;

  if (log_data.log_format.find("%(PID)") != std::string::npos) {
    subs["%(PID)"] = std::to_string(log_data.pid);
  }

  if (log_data.log_format.find("%(TID)") != std::string::npos) {
    std::hash<std::thread::id> hash_fn;
    std::ostringstream oss;
    oss << std::hex << std::uppercase << hash_fn(log_data.tid);
    subs["%(TID)"] = oss.str();
  }

  if (log_data.log_format.find("%(DATE)") != std::string::npos) {
    using namespace std::chrono;
    char date_buf[16] = { 0 };
    auto sec = duration_cast<seconds>(log_data.time.time_since_epoch());
    std::time_t t = sec.count();
    std::strftime(date_buf, sizeof(date_buf), "%F", std::localtime(&t));
    subs["%(DATE)"] = date_buf;
  }

  if (log_data.log_format.find("%(TIME)") != std::string::npos) {
    using namespace std::chrono;
    char time_buf[32] = { 0 };
    auto nanos = duration_cast<nanoseconds>(log_data.time.time_since_epoch());
    auto sec = duration_cast<seconds>(log_data.time.time_since_epoch());
    std::time_t t = sec.count();
    std::size_t frac = nanos.count() % 1000000000;
    std::strftime(time_buf, sizeof(time_buf), "%T", std::localtime(&t));
    std::string time_str = std::string(time_buf) + "." + std::to_string(frac);
    subs["%(TIME)"] = time_str;
  }

  if (log_data.log_format.find("%(LINE)") != std::string::npos) {
    subs["%(LINE)"] = std::to_string(log_data.line);
  }

  if (log_data.log_format.find("%(MSG_ID)") != std::string::npos) {
    subs["%(MSG_ID)"] = std::to_string(log_data.msg_id);
  }

  std::string result = log_data.log_format;
  size_t pos = 0;
  for (const auto& entry : subs) {
    while ((pos = result.find(entry.first)) != std::string::npos) {
      result.replace(pos, entry.first.length(), entry.second);
    }
  }
  return result;
}

void _EnqueueLogTask(LogData* log_data) {
  log_data->log_format = yeti::Logger::instance().GetFormatStr();
  log_data->time = std::chrono::high_resolution_clock::now();
  log_data->pid = getpid();
  log_data->tid = std::this_thread::get_id();
  log_data->fd = yeti::Logger::instance().GetFileDesc();
  bool is_colored = yeti::Logger::instance().IsColored();

  LogData printed_data = *log_data;
  auto print_func = [printed_data, is_colored] {
    std::string log_str = _CreateLogStr(printed_data) + "\n";

// To colorize stdout and stderr in Windows cmd.exe it is necessary
// to include windows.h and use SetConsoleTextAttribute().
// It is terrible, so I decided to disable coloring at WIN32 platform.
#ifndef _WIN32
    if (isatty(fileno(printed_data.fd)) != 0 && is_colored) {
      log_str = printed_data.color + log_str + std::string(YETI_RESET);
    }
#endif  // _WIN32

    std::fprintf(printed_data.fd, log_str.c_str());
  };

  yeti::Logger::instance().EnqueueTask(print_func);
}

}  // namespace yeti
<|endoftext|>


<commit_before>#include	<cstdlib>
#include	<cmath>
#include	<fstream>
#include	<sstream>
#include	<iostream>
#include	<iomanip>
#include	<string>
#include	<vector>
#include	<algorithm>
#include	<exception>
#include	<sys/time.h>
#include	"modules/htmTree.h"
#include	"modules/kdTree.h"
#include        "misc.h"
#include        "feat.h"
#include        "structs.h"
#include        "collision.h"
#include        "global.h"
//reduce redistributes, updates  07/02/15 rnc
int main(int argc, char **argv) {
	//// Initializations ---------------------------------------------
	srand48(1234); // Make sure we have reproducability
	check_args(argc);
	Time t, time; // t for global, time for local
	init_time(t);
	Feat F;

	// Read parameters file //
	F.readInputFile(argv[1]);
	printFile(argv[1]);
    std::cout.flush();
	// Read galaxies
	Gals G, Secret;
    MTL Targ, SStars, SkyF;
    if(F.Ascii){
        printf("to read galaxies\n");
        std::cout.flush();
        G=read_galaxies_ascii(F);}
    else{
        G = read_galaxies(F);
    }
	F.Ngal = G.size();

	printf("# Read %s galaxies from %s \n",f(F.Ngal).c_str(),F.galFile.c_str());
        std::cout.flush();
    std::vector<int> count;
    count=count_galaxies(G);
    printf(" Number of galaxies by type, QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF\n");
    for(int i=0;i<2;i++){printf (" type %d number  %d  \n",i, count[i]);}
    // make MTL
    //read_MTL(G,F,Secret,Targ);
    //write_MTLfile(Secret,Targ,F);
    make_MTL_SS_SF(G,Targ,SStars,SkyF,Secret,F);
    write_MTL_SS_SFfile(Targ,SStars,SkyF,Secret,F);
	return(0);

}
<commit_msg>print only part of count<commit_after>#include	<cstdlib>
#include	<cmath>
#include	<fstream>
#include	<sstream>
#include	<iostream>
#include	<iomanip>
#include	<string>
#include	<vector>
#include	<algorithm>
#include	<exception>
#include	<sys/time.h>
#include	"modules/htmTree.h"
#include	"modules/kdTree.h"
#include        "misc.h"
#include        "feat.h"
#include        "structs.h"
#include        "collision.h"
#include        "global.h"
//reduce redistributes, updates  07/02/15 rnc
int main(int argc, char **argv) {
	//// Initializations ---------------------------------------------
	srand48(1234); // Make sure we have reproducability
	check_args(argc);
	Time t, time; // t for global, time for local
	init_time(t);
	Feat F;

	// Read parameters file //
	F.readInputFile(argv[1]);
	printFile(argv[1]);
    std::cout.flush();
	// Read galaxies
	Gals G, Secret;
    MTL Targ, SStars, SkyF;
    if(F.Ascii){
        printf("to read galaxies\n");
        std::cout.flush();
        G=read_galaxies_ascii(F);}
    else{
        G = read_galaxies(F);
    }
	F.Ngal = G.size();

	printf("# Read %s galaxies from %s \n",f(F.Ngal).c_str(),F.galFile.c_str());
        std::cout.flush();
    std::vector<int> count;
    count=count_galaxies(G);
    printf(" Number of galaxies by type, QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF\n");
    std::cout.flush();
    for(int i=0;i<2;i++){printf (" type %d number  %d  \n",i, count[i]);}
    // make MTL
    //read_MTL(G,F,Secret,Targ);
    //write_MTLfile(Secret,Targ,F);
    make_MTL_SS_SF(G,Targ,SStars,SkyF,Secret,F);
    write_MTL_SS_SFfile(Targ,SStars,SkyF,Secret,F);
	return(0);

}
<|endoftext|>


<commit_before>#include <Wire.h>
#include <DS1307RTC.h>
#include <core.h>
#include "thermostat.h"
#include "rtc.h"

tmElements_t _rtcNow;

tmElementsPtr_t rtcNow() {
  if (!RTC.read(_rtcNow)) {
    Serial.println(F("Read RTC failed!"));
    Serial.println();
  }

  return &_rtcNow;
}

void setRtc(tmElements_t &now) {
  if (!RTC.write(now)) {
    Serial.println(F("Set DS1307 time failed"));
    Serial.println();
  }
}

void setupRTC() {
  _rtcNow.Year = 2016 - 1970;
  _rtcNow.Month = 11;
  _rtcNow.Day = 22;
  _rtcNow.Hour = 15;
  _rtcNow.Minute = 50;
  _rtcNow.Second = 0;
  _rtcNow.Wday = 3;

  if (!RTC.read(_rtcNow)) {
    if (RTC.chipPresent()) {
      // RTC maybe not inited
      Serial.println(F("DS1307 not inited, set time to 2016-11-25 15:50:00"));
      setRtc(_rtcNow);

      return;
    }

    Serial.println(F("DS1307 read error!  Please check the circuitry."));
    Serial.println();
  }
}

struct Node {
  alarmFunc fn;
  tmElements_t when;
  Node *next;

  Node(tmElements_t aWhen, alarmFunc aFn) : fn(aFn), when(aWhen), next(NULL) {}
};

struct Queue {
  Node *head;

  void add(Node *);
  void remove(Node *);

  Queue() : head(NULL) {}
};

void Queue::add(Node *node) {
  if (head == NULL) {
    head = node;
    return;
  }

  for (Node *p = head; ; p = p->next) {
    if (p->next == NULL) {
      p->next = node;
      break;
    }
  }
}

void Queue::remove(Node *node) {
  for (Node *p = head, *prev = NULL; p != NULL; prev = p, p = p->next) {
    if (p == node) {
      if (prev == NULL) {
        head = p->next;
      } else {
        prev->next = p->next;
      }
      delete node;
      break;
    }
  }
}

Queue alarms;

void checkAlarm() {
  tmElementsPtr_t now = rtcNow();
  for (Node *p = alarms.head; p != NULL; p = p->next) {
    if (p->when.Month != 255 && p->when.Month != now->Month) {
      continue;
    }

    if (p->when.Day != 255 && p->when.Day != now->Day) {
      continue;
    }

    if (p->when.Wday != 255 && p->when.Wday != now->Wday) {
      continue;
    }

    if (p->when.Hour != 255 && p->when.Hour != now->Hour) {
      continue;
    }

    if (p->when.Minute != 255 && p->when.Minute != now->Minute) {
      continue;
    }

    p->fn(now);
  }
}

void *defineRtcAlarm(tmElements_t when, alarmFunc fn) {
  static bool rtcHosted = false;
  if (!rtcHosted) {
    rtcHosted = true;
    core::clock::interval(30 * 1000, &checkAlarm); // check alarm every 30 seconds.
  }

  Node *node = new Node(when, fn);
  alarms.add(node);
  return node;
}

void removeRtcAlarm(void *handle) {
  alarms.remove((Node*)handle);
}
<commit_msg>Align rtc alarm to second 00<commit_after>#include <Wire.h>
#include <DS1307RTC.h>
#include <core.h>
#include "thermostat.h"
#include "rtc.h"

tmElements_t _rtcNow;

tmElementsPtr_t rtcNow() {
  if (!RTC.read(_rtcNow)) {
    Serial.println(F("Read RTC failed!"));
    Serial.println();
  }

  return &_rtcNow;
}

void setRtc(tmElements_t &now) {
  if (!RTC.write(now)) {
    Serial.println(F("Set DS1307 time failed"));
    Serial.println();
  }
}

void setupRTC() {
  _rtcNow.Year = 2016 - 1970;
  _rtcNow.Month = 11;
  _rtcNow.Day = 22;
  _rtcNow.Hour = 15;
  _rtcNow.Minute = 50;
  _rtcNow.Second = 0;
  _rtcNow.Wday = 3;

  if (!RTC.read(_rtcNow)) {
    if (RTC.chipPresent()) {
      // RTC maybe not inited
      Serial.println(F("DS1307 not inited, set time to 2016-11-25 15:50:00"));
      setRtc(_rtcNow);

      return;
    }

    Serial.println(F("DS1307 read error!  Please check the circuitry."));
    Serial.println();
  }
}

struct Node {
  alarmFunc fn;
  tmElements_t when;
  Node *next;

  Node(tmElements_t aWhen, alarmFunc aFn) : fn(aFn), when(aWhen), next(NULL) {}
};

struct Queue {
  Node *head;

  void add(Node *);
  void remove(Node *);

  Queue() : head(NULL) {}
};

void Queue::add(Node *node) {
  if (head == NULL) {
    head = node;
    return;
  }

  for (Node *p = head; ; p = p->next) {
    if (p->next == NULL) {
      p->next = node;
      break;
    }
  }
}

void Queue::remove(Node *node) {
  for (Node *p = head, *prev = NULL; p != NULL; prev = p, p = p->next) {
    if (p == node) {
      if (prev == NULL) {
        head = p->next;
      } else {
        prev->next = p->next;
      }
      delete node;
      break;
    }
  }
}

Queue alarms;

void checkAlarm() {
  tmElementsPtr_t now = rtcNow();
  for (Node *p = alarms.head; p != NULL; p = p->next) {
    if (p->when.Month != 255 && p->when.Month != now->Month) {
      continue;
    }

    if (p->when.Day != 255 && p->when.Day != now->Day) {
      continue;
    }

    if (p->when.Wday != 255 && p->when.Wday != now->Wday) {
      continue;
    }

    if (p->when.Hour != 255 && p->when.Hour != now->Hour) {
      continue;
    }

    if (p->when.Minute != 255 && p->when.Minute != now->Minute) {
      continue;
    }

    p->fn(now);
  }
}

void startRtcAlarm() {
  // Start Rtc alarm interval at second zero align to rtc alarm resolution of 1
  // minute.
  // TODO: if user adjust RTC time, then this align is not effect.
  core::clock::interval((int32_t)(60) * 1000, &checkAlarm); // check alarm every 60 seconds.
}

void *defineRtcAlarm(tmElements_t when, alarmFunc fn) {
  static bool rtcHosted = false;
  if (!rtcHosted) {
    rtcHosted = true;

    int32_t delay = 60 - rtcNow()->Second;
    delay %= 60;
    core::clock::delay(delay * 1000, startRtcAlarm);
  }

  Node *node = new Node(when, fn);
  alarms.add(node);
  return node;
}

void removeRtcAlarm(void *handle) {
  alarms.remove((Node*)handle);
}
<|endoftext|>


<commit_before>/**\file twist_publisher.cpp
 * \brief Description...
 *
 * @version 1.0
 * @author Carlos Miguel Correia da Costa
 */

// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   <includes>   <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
#include <robot_localization_tools/twist_publisher.h>
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   </includes>  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

namespace robot_localization_tools {

// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   <imports>   <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   </imports>  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

// =============================================================================  <public-section>  ============================================================================
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   <constructors-destructor>   <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   </constructors-destructor>  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   <TwistPublisher-functions>   <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
void TwistPublisher::setupConfigurationFromParameterServer(ros::NodeHandlePtr& node_handle, ros::NodeHandlePtr& private_node_handle) {
	std::string twist_publisher_topic;
	private_node_handle->param("TwistPublisher/twist_publisher_topic", twist_publisher_topic, std::string("cmd_vel"));
	twist_publisher_ = node_handle->advertise<geometry_msgs::Twist>(twist_publisher_topic, 10, true);
}

void TwistPublisher::publishTwistFromParameterServer(ros::NodeHandlePtr& private_node_handle) {
	XmlRpc::XmlRpcValue twist_msgs_yaml;
	private_node_handle->getParam("TwistPublisher/Messages", twist_msgs_yaml);
	geometry_msgs::Twist twist_msg;

	for (int twist_msg_config = 0; twist_msg_config < twist_msgs_yaml.size(); ++twist_msg_config) {
		twist_msg.linear.x = twist_msgs_yaml[twist_msg_config]["linear.x"];
		twist_msg.angular.z = twist_msgs_yaml[twist_msg_config]["angular.z"];
		twist_publisher_.publish(twist_msg);

		ros::Duration twist_duration(twist_msgs_yaml[twist_msg_config]["duration"]);
		twist_duration.sleep();
	}
}
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   </TwistPublisher-functions>  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// =============================================================================  </public-section>  ===========================================================================

// =============================================================================   <protected-section>   =======================================================================
// =============================================================================   </protected-section>  =======================================================================

// =============================================================================   <private-section>   =========================================================================
// =============================================================================   </private-section>  =========================================================================

// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   <template instantiations>   <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   </template instantiations>  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

} /* namespace robot_localization_tools */

<commit_msg>Added member / info checks to allow yaml with incomplete fields.<commit_after>/**\file twist_publisher.cpp
 * \brief Description...
 *
 * @version 1.0
 * @author Carlos Miguel Correia da Costa
 */

// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   <includes>   <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
#include <robot_localization_tools/twist_publisher.h>
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   </includes>  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

namespace robot_localization_tools {

// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   <imports>   <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   </imports>  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

// =============================================================================  <public-section>  ============================================================================
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   <constructors-destructor>   <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   </constructors-destructor>  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   <TwistPublisher-functions>   <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
void TwistPublisher::setupConfigurationFromParameterServer(ros::NodeHandlePtr& node_handle, ros::NodeHandlePtr& private_node_handle) {
	std::string twist_publisher_topic;
	private_node_handle->param("TwistPublisher/twist_publisher_topic", twist_publisher_topic, std::string("cmd_vel"));
	twist_publisher_ = node_handle->advertise<geometry_msgs::Twist>(twist_publisher_topic, 10, true);
}

void TwistPublisher::publishTwistFromParameterServer(ros::NodeHandlePtr& private_node_handle) {
	XmlRpc::XmlRpcValue twist_msgs_yaml;
	if (private_node_handle->getParam("TwistPublisher/Messages", twist_msgs_yaml)) {
		geometry_msgs::Twist twist_msg;

		for (int twist_msg_config = 0; twist_msg_config < twist_msgs_yaml.size(); ++twist_msg_config) {
			twist_msg.linear.x = twist_msgs_yaml[twist_msg_config].hasMember("linear.x") ? (double)twist_msgs_yaml[twist_msg_config]["linear.x"] : 0.0;
			twist_msg.angular.z = twist_msgs_yaml[twist_msg_config].hasMember("angular.z") ? (double)twist_msgs_yaml[twist_msg_config]["angular.z"] : 0.0;
			twist_publisher_.publish(twist_msg);

			ros::Duration twist_duration(twist_msgs_yaml[twist_msg_config].hasMember("duration") ? (double)twist_msgs_yaml[twist_msg_config]["duration"] : 0.0);
			twist_duration.sleep();
		}
	}
}
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   </TwistPublisher-functions>  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// =============================================================================  </public-section>  ===========================================================================

// =============================================================================   <protected-section>   =======================================================================
// =============================================================================   </protected-section>  =======================================================================

// =============================================================================   <private-section>   =========================================================================
// =============================================================================   </private-section>  =========================================================================

// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   <template instantiations>   <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   </template instantiations>  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

} /* namespace robot_localization_tools */

<|endoftext|>


<commit_before><commit_msg>fixed variable name<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Syscoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "pow.h"

#include "arith_uint256.h"
#include "chain.h"
#include "primitives/block.h"
#include "uint256.h"
#include "util.h"
#include "chainparamsbase.h"

unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)
{
	return CalculateNextWorkRequired(indexLast, params);
}
// SYSCOIN DGW diff algo
unsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, const Consensus::Params& params)
{

	/* current difficulty formula, dash - DarkGravity v3, written by Evan Duffield - evan@dashpay.io */
    // Genesis block
    if (pindexLast == NULL)
        return nProofOfWorkLimit;
    if (params.fPowNoRetargeting)
        return pindexLast->nBits;

	const arith_uint256 nProofOfWorkLimit = UintToArith256(params.powLimit);
    const CBlockIndex *BlockLastSolved = pindexLast;
    const CBlockIndex *BlockReading = pindexLast;
    int64_t nActualTimespan = 0;
    int64_t LastBlockTime = 0;
    int64_t PastBlocksMin = 24;
    int64_t PastBlocksMax = 24;
    int64_t CountBlocks = 0;
    arith_uint256 PastDifficultyAverage;
    arith_uint256 PastDifficultyAveragePrev;

    if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || BlockLastSolved->nHeight < PastBlocksMin) {
        return nProofOfWorkLimit.GetCompact();
    }

    for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) {
        if (PastBlocksMax > 0 && i > PastBlocksMax) { break; }
        CountBlocks++;

        if(CountBlocks <= PastBlocksMin) {
            if (CountBlocks == 1) { PastDifficultyAverage.SetCompact(BlockReading->nBits); }
            else { PastDifficultyAverage = ((PastDifficultyAveragePrev * CountBlocks) + (arith_uint256().SetCompact(BlockReading->nBits))) / (CountBlocks + 1); }
            PastDifficultyAveragePrev = PastDifficultyAverage;
        }

        if(LastBlockTime > 0){
            int64_t Diff = (LastBlockTime - BlockReading->GetBlockTime());
            nActualTimespan += Diff;
        }
        LastBlockTime = BlockReading->GetBlockTime();

        if (BlockReading->pprev == NULL) { assert(BlockReading); break; }
        BlockReading = BlockReading->pprev;
    }

    arith_uint256 bnNew(PastDifficultyAverage);

    int64_t _nTargetTimespan = CountBlocks * params.nPowTargetSpacing;

    if (nActualTimespan < _nTargetTimespan/3)
        nActualTimespan = _nTargetTimespan/3;
    if (nActualTimespan > _nTargetTimespan*3)
        nActualTimespan = _nTargetTimespan*3;

    // Retarget
    bnNew *= nActualTimespan;
    bnNew /= _nTargetTimespan;

    if (bnNew > nProofOfWorkLimit){
        bnNew = nProofOfWorkLimit;
    }

    return bnNew.GetCompact();
}

bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params)
{
    bool fNegative;
    bool fOverflow;
    arith_uint256 bnTarget;

    bnTarget.SetCompact(nBits, &fNegative, &fOverflow);

    // Check range
    if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit))
        return error("CheckProofOfWork(): nBits below minimum work");

    // Check proof of work matches claimed amount
	std::string chain = ChainNameFromCommandLine();
    if (UintToArith256(hash) > bnTarget)
        return error("CheckProofOfWork(): hash doesn't match nBits");

    return true;
}

arith_uint256 GetBlockProof(const CBlockIndex& block)
{
    arith_uint256 bnTarget;
    bool fNegative;
    bool fOverflow;
    bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow);
    if (fNegative || fOverflow || bnTarget == 0)
        return 0;
    // We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256
    // as it's too large for a arith_uint256. However, as 2**256 is at least as large
    // as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1,
    // or ~bnTarget / (nTarget+1) + 1.
    return (~bnTarget / (bnTarget + 1)) + 1;
}

int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params& params)
{
    arith_uint256 r;
    int sign = 1;
    if (to.nChainWork > from.nChainWork) {
        r = to.nChainWork - from.nChainWork;
    } else {
        r = from.nChainWork - to.nChainWork;
        sign = -1;
    }
    r = r * arith_uint256(params.nPowTargetSpacing) / GetBlockProof(tip);
    if (r.bits() > 63) {
        return sign * std::numeric_limits<int64_t>::max();
    }
    return sign * r.GetLow64();
}
<commit_msg>typo<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Syscoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "pow.h"

#include "arith_uint256.h"
#include "chain.h"
#include "primitives/block.h"
#include "uint256.h"
#include "util.h"
#include "chainparamsbase.h"

unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)
{
	return CalculateNextWorkRequired(pindexLast, params);
}
// SYSCOIN DGW diff algo
unsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, const Consensus::Params& params)
{

	/* current difficulty formula, dash - DarkGravity v3, written by Evan Duffield - evan@dashpay.io */
    // Genesis block

	const arith_uint256 nProofOfWorkLimit = UintToArith256(params.powLimit);
    if (pindexLast == NULL)
        return nProofOfWorkLimit.GetCompact();
    if (params.fPowNoRetargeting)
        return pindexLast->nBits;
    const CBlockIndex *BlockLastSolved = pindexLast;
    const CBlockIndex *BlockReading = pindexLast;
    int64_t nActualTimespan = 0;
    int64_t LastBlockTime = 0;
    int64_t PastBlocksMin = 24;
    int64_t PastBlocksMax = 24;
    int64_t CountBlocks = 0;
    arith_uint256 PastDifficultyAverage;
    arith_uint256 PastDifficultyAveragePrev;

    if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || BlockLastSolved->nHeight < PastBlocksMin) {
        return nProofOfWorkLimit.GetCompact();
    }

    for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) {
        if (PastBlocksMax > 0 && i > PastBlocksMax) { break; }
        CountBlocks++;

        if(CountBlocks <= PastBlocksMin) {
            if (CountBlocks == 1) { PastDifficultyAverage.SetCompact(BlockReading->nBits); }
            else { PastDifficultyAverage = ((PastDifficultyAveragePrev * CountBlocks) + (arith_uint256().SetCompact(BlockReading->nBits))) / (CountBlocks + 1); }
            PastDifficultyAveragePrev = PastDifficultyAverage;
        }

        if(LastBlockTime > 0){
            int64_t Diff = (LastBlockTime - BlockReading->GetBlockTime());
            nActualTimespan += Diff;
        }
        LastBlockTime = BlockReading->GetBlockTime();

        if (BlockReading->pprev == NULL) { assert(BlockReading); break; }
        BlockReading = BlockReading->pprev;
    }

    arith_uint256 bnNew(PastDifficultyAverage);

    int64_t _nTargetTimespan = CountBlocks * params.nPowTargetSpacing;

    if (nActualTimespan < _nTargetTimespan/3)
        nActualTimespan = _nTargetTimespan/3;
    if (nActualTimespan > _nTargetTimespan*3)
        nActualTimespan = _nTargetTimespan*3;

    // Retarget
    bnNew *= nActualTimespan;
    bnNew /= _nTargetTimespan;

    if (bnNew > nProofOfWorkLimit){
        bnNew = nProofOfWorkLimit;
    }

    return bnNew.GetCompact();
}

bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params)
{
    bool fNegative;
    bool fOverflow;
    arith_uint256 bnTarget;

    bnTarget.SetCompact(nBits, &fNegative, &fOverflow);

    // Check range
    if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit))
        return error("CheckProofOfWork(): nBits below minimum work");

    // Check proof of work matches claimed amount
	std::string chain = ChainNameFromCommandLine();
    if (UintToArith256(hash) > bnTarget)
        return error("CheckProofOfWork(): hash doesn't match nBits");

    return true;
}

arith_uint256 GetBlockProof(const CBlockIndex& block)
{
    arith_uint256 bnTarget;
    bool fNegative;
    bool fOverflow;
    bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow);
    if (fNegative || fOverflow || bnTarget == 0)
        return 0;
    // We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256
    // as it's too large for a arith_uint256. However, as 2**256 is at least as large
    // as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1,
    // or ~bnTarget / (nTarget+1) + 1.
    return (~bnTarget / (bnTarget + 1)) + 1;
}

int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params& params)
{
    arith_uint256 r;
    int sign = 1;
    if (to.nChainWork > from.nChainWork) {
        r = to.nChainWork - from.nChainWork;
    } else {
        r = from.nChainWork - to.nChainWork;
        sign = -1;
    }
    r = r * arith_uint256(params.nPowTargetSpacing) / GetBlockProof(tip);
    if (r.bits() > 63) {
        return sign * std::numeric_limits<int64_t>::max();
    }
    return sign * r.GetLow64();
}
<|endoftext|>