<commit_before>#include "CaesarProject.h"

CAESAR_SETTINGS* pCaesarSettings = NULL;

CaesarProject::CaesarProject()
    : IProject(PROJECT_CAESAR), m_encryptor(NULL), m_ciphertext(NULL), m_realCiphertextLength(0) { }

CaesarProject::~CaesarProject() {
    if (m_encryptor != NULL) { delete m_encryptor; m_encryptor = NULL; }
    if (m_ciphertext != NULL) { delete[] m_ciphertext; m_ciphertext = NULL; }
}

string CaesarProject::shortDescription() const {
    return "CAESAR -- competition for authenticated encryption";
}

string CaesarProject::testingConfiguration() {
    string config =
            "<CAESAR>"
            "    <USAGE_TYPE>301</USAGE_TYPE>"
            "    <ALGORITHM>1</ALGORITHM>"
            "    <LIMIT_NUM_OF_ROUNDS>0</LIMIT_NUM_OF_ROUNDS>"
            "    <ALGORITHM_ROUNDS>3</ALGORITHM_ROUNDS>"
            "    <PLAINTEXT_LENGTH>16</PLAINTEXT_LENGTH>"
            "    <AD_LENGTH>0</AD_LENGTH>"
            "    <PLAINTEXT_TYPE>0</PLAINTEXT_TYPE>"
            "    <KEY_TYPE>2</KEY_TYPE>"
            "    <AD_TYPE>0</AD_TYPE>"
            "    <SMN_TYPE>0</SMN_TYPE>"
            "    <PMN_TYPE>0</PMN_TYPE>"
            "    <GENERATE_STREAM>0</GENERATE_STREAM>"
            "    <STREAM_SIZE>5242880</STREAM_SIZE>"
            "</CAESAR>";
    return config;
}

int CaesarProject::loadProjectConfiguration(TiXmlNode* pRoot) {
    m_caesarSettings.usageType = atoi(getXMLElementValue(pRoot,"CAESAR/USAGE_TYPE").c_str());
    m_caesarSettings.algorithm = atoi(getXMLElementValue(pRoot,"CAESAR/ALGORITHM").c_str());
    m_caesarSettings.limitAlgRounds = (atoi(getXMLElementValue(pRoot,"CAESAR/LIMIT_NUM_OF_ROUNDS").c_str())) ? true : false;
    m_caesarSettings.algorithmRoundsCount = atoi(getXMLElementValue(pRoot,"CAESAR/ALGORITHM_ROUNDS").c_str());
    istringstream(getXMLElementValue(pRoot,"CAESAR/PLAINTEXT_LENGTH")) >> m_caesarSettings.plaintextLength;
    istringstream(getXMLElementValue(pRoot,"CAESAR/AD_LENGTH")) >> m_caesarSettings.adLength;
    m_caesarSettings.plaintextType = atoi(getXMLElementValue(pRoot,"CAESAR/PLAINTEXT_TYPE").c_str());
    m_caesarSettings.keyType = atoi(getXMLElementValue(pRoot,"CAESAR/KEY_TYPE").c_str());
    m_caesarSettings.adType = atoi(getXMLElementValue(pRoot,"CAESAR/AD_TYPE").c_str());
    m_caesarSettings.smnType = atoi(getXMLElementValue(pRoot,"CAESAR/SMN_TYPE").c_str());
    m_caesarSettings.pmnType = atoi(getXMLElementValue(pRoot,"CAESAR/PMN_TYPE").c_str());
    m_caesarSettings.generateStream = (atoi(getXMLElementValue(pRoot,"CAESAR/GENERATE_STREAM").c_str())) ? true : false;
    istringstream(getXMLElementValue(pRoot,"CAESAR/STREAM_SIZE")) >> m_caesarSettings.streamSize;
    pCaesarSettings = &m_caesarSettings;

    // adjust number of rounds if necessary
    if (!m_caesarSettings.limitAlgRounds) { m_caesarSettings.algorithmRoundsCount = -1; }

    // bind project settings into global settings
    pGlobals->settings->project = (void*) pCaesarSettings;

    // TODO configuration checks

    return STAT_OK;
}

int CaesarProject::initializeProject() {
    // allocate encryptor
    m_encryptor = new Encryptor;
    // allocate ciphertext buffer
    m_ciphertext = new bits_t[pCaesarSettings->ciphertextLength];

    // TODO create headers for human readable test vector file

    return STAT_OK;
}

int CaesarProject::initializeProjectState() {
    int status = m_encryptor->setup();
    if (status == STAT_OK) {
        mainLogger.out(LOGGER_INFO) << "Cipher initialized (" << m_encryptor->shortDescription() << ")." << endl;
    } else {
        mainLogger.out(LOGGER_ERROR) << "Cipher could not be initialized (" << statusToString(status) << ")." << endl;
    }
    return status;
}

int CaesarProject::saveProjectState(TiXmlNode* pRoot) const {
    int status = STAT_OK;
    TiXmlElement* pRoot2 = pRoot->ToElement();
    pRoot2->SetAttribute("loadable",0);
    return STAT_OK;
}

int CaesarProject::loadProjectState(TiXmlNode* pRoot) {
    return STAT_OK;
}

int CaesarProject::createTestVectorFilesHeaders() const {
    ofstream tvFile;
    tvFile.open(FILE_TEST_VECTORS, ios_base::trunc | ios_base::binary);
    if (!tvFile.is_open()) {
        mainLogger.out(LOGGER_ERROR) << "Cannot write file for test vectors (" << FILE_TEST_VECTORS << ")." << endl;
        return STAT_FILE_WRITE_FAIL;
    }
    tvFile << dec << left;
    tvFile << pCaesarSettings->algorithm << " \t\t(algorithm:" << m_encryptor->shortDescription() << ")" << endl;
    tvFile << pCaesarSettings->limitAlgRounds << " \t\t(limit algorithm rounds?)" << endl;
    tvFile << pCaesarSettings->algorithmRoundsCount << " \t\t(algorithm rounds - if limited)" << endl;
    tvFile << pCaesarSettings->plaintextLength << " \t\t(plaintext length)" << endl;
    tvFile << pCaesarSettings->adLength << " \t\t(associated data length)" << endl;
    tvFile << pCaesarSettings->plaintextType << " \t\t(plaintext type)" << endl;
    tvFile << pCaesarSettings->keyType << " \t\t(key type)" << endl;
    tvFile << pCaesarSettings->adType << " \t\t(associated data type)" << endl;
    tvFile << pCaesarSettings->smnType << " \t\t(secret message number type)" << endl;
    tvFile << pCaesarSettings->pmnType << " \t\t(public message number type)" << endl;
    tvFile.close();

    return STAT_OK;
}

int CaesarProject::generateTestVectors() {
    int status = STAT_OK;

    // if set so, do not generate test vectors but generate data stream to cout
    if (pCaesarSettings->generateStream) {
        status = generateCipherDataStream();
        if (status != STAT_OK) {
            return status;
        } else {
            return STAT_INTENTIONAL_EXIT;
        }
    }

    // generate cipher stream
    for (int vector = 0; vector < pGlobals->settings->testVectors.setSize/2; vector++) {
        status = prepareSingleTestVector(pGlobals->testVectors.inputs[vector], pGlobals->testVectors.outputs[vector]);
        if (status != STAT_OK) { break; }
    }
    if (status != STAT_OK) {
        mainLogger.out(LOGGER_ERROR) << "Cipher data generation failed." << endl;
        return status;
    }
    // generate random vectors
    for (int vector = pGlobals->settings->testVectors.setSize/2; vector < pGlobals->settings->testVectors.setSize; vector++) {
        // random stream
        for (int byte = 0; byte < pGlobals->settings->testVectors.inputLength; byte++) {
            rndGen->getRandomFromInterval(255, pGlobals->testVectors.inputs[vector] + byte);
        }
        // 0xff to denote random stream
        for (int byte = 0; byte < pGlobals->settings->testVectors.outputLength; byte++) {
            pGlobals->testVectors.outputs[vector][byte] = UCHAR_MAX;
        }
    }

    return status;
}

int CaesarProject::prepareSingleTestVector(unsigned char* tvInputs, unsigned char* tvOutputs) {
    int status = STAT_OK;
    switch (pCaesarSettings->usageType) {
    case CAESAR_DISTINGUISHER:
        // ciphertext stream
        status = m_encryptor->encrypt(m_ciphertext, &m_realCiphertextLength);
        if (status != STAT_OK) { return status; }
        // copy authentication tag
        memcpy(tvInputs, m_ciphertext+m_caesarSettings.plaintextLength,
                min(m_realCiphertextLength-m_caesarSettings.plaintextLength, (length_t)pGlobals->settings->testVectors.inputLength));
        // fill with zeroes
        if ((int) (m_realCiphertextLength-m_caesarSettings.plaintextLength) < pGlobals->settings->testVectors.inputLength) {
            mainLogger.out(LOGGER_WARNING) << "Authentication tag shorter than test vector input -- padded with zeroes." << endl;
            for (int byte = static_cast<int>(m_caesarSettings.plaintextLength); byte < pGlobals->settings->testVectors.inputLength; byte++) {
                tvInputs[byte] = 0;
            }
        }
        status = m_encryptor->update();
        if (status != STAT_OK) { return status; }
        // 0x00 to denote ciphertext stream
        for (int byte = 0; byte < pGlobals->settings->testVectors.outputLength; byte++) {
            tvOutputs[byte] = 0;
        }
        break;
    default:
        mainLogger.out(LOGGER_ERROR) << "Unknown usage type (" << pCaesarSettings->usageType << ") in " << shortDescription() << endl;
        return STAT_INVALID_ARGUMETS;
        break;
    }
    return status;
}

int CaesarProject::generateCipherDataStream() {
    int status = STAT_OK;

    unsigned char* tvOutputs = new unsigned char[pGlobals->settings->testVectors.outputLength];
    memset(tvOutputs,0,pGlobals->settings->testVectors.outputLength);
    unsigned char* tvInputs = new unsigned char[pGlobals->settings->testVectors.inputLength];
    memset(tvInputs,0,pGlobals->settings->testVectors.inputLength);

    string streamFilename = CAESAR_FILE_STREAM;
    mainLogger.out(LOGGER_INFO) << "Generating cipher data stream for " << m_encryptor->shortDescription() << "." << endl;

    ostream* vectorStream = NULL;
    if (pCaesarSettings->streamSize == 0) {
        vectorStream = &cout;
        mainLogger.out(LOGGER_INFO) << "Sneding binary stream to standard output." << endl;
    } else {
        vectorStream = new ofstream(streamFilename, ios_base::binary | ios_base::trunc);
        mainLogger.out(LOGGER_INFO) << "Saving binary stream to file '" << streamFilename << "'." << endl;
    }
    unsigned long alreadyGenerated = 0;
    while (pCaesarSettings->streamSize == 0 ? true : alreadyGenerated <= pCaesarSettings->streamSize) {
        for (int testVectorNumber = 0; testVectorNumber < pGlobals->settings->testVectors.setSize; testVectorNumber++) {
            if (status != STAT_OK) break;

            // get test vector
            status = prepareSingleTestVector(tvInputs,tvOutputs);

            for (int index = 0; index < pGlobals->settings->testVectors.inputLength; index++) {
                (*vectorStream) << tvInputs[index];
            }
            alreadyGenerated += pGlobals->settings->testVectors.inputLength;
        }
    }

    if (pCaesarSettings->streamSize != 0) {
        delete vectorStream;
        vectorStream = NULL;
    }
    if (status == STAT_OK) {
        mainLogger.out(LOGGER_INFO) << "Cipher data generation successful (" << alreadyGenerated << " bytes)." << endl;
    } else {
        mainLogger.out(LOGGER_ERROR) << "Cipher data generation failed (" << alreadyGenerated << " bytes generated)." << endl;
    }

    delete[] tvInputs;
    delete[] tvOutputs;

    return status;
}
<commit_msg>binary test vector file fix<commit_after>#include "CaesarProject.h"

CAESAR_SETTINGS* pCaesarSettings = NULL;

CaesarProject::CaesarProject()
    : IProject(PROJECT_CAESAR), m_encryptor(NULL), m_ciphertext(NULL), m_realCiphertextLength(0) { }

CaesarProject::~CaesarProject() {
    if (m_encryptor != NULL) { delete m_encryptor; m_encryptor = NULL; }
    if (m_ciphertext != NULL) { delete[] m_ciphertext; m_ciphertext = NULL; }
}

string CaesarProject::shortDescription() const {
    return "CAESAR -- competition for authenticated encryption";
}

string CaesarProject::testingConfiguration() {
    string config =
            "<CAESAR>"
            "    <USAGE_TYPE>301</USAGE_TYPE>"
            "    <ALGORITHM>1</ALGORITHM>"
            "    <LIMIT_NUM_OF_ROUNDS>0</LIMIT_NUM_OF_ROUNDS>"
            "    <ALGORITHM_ROUNDS>3</ALGORITHM_ROUNDS>"
            "    <PLAINTEXT_LENGTH>16</PLAINTEXT_LENGTH>"
            "    <AD_LENGTH>0</AD_LENGTH>"
            "    <PLAINTEXT_TYPE>0</PLAINTEXT_TYPE>"
            "    <KEY_TYPE>2</KEY_TYPE>"
            "    <AD_TYPE>0</AD_TYPE>"
            "    <SMN_TYPE>0</SMN_TYPE>"
            "    <PMN_TYPE>0</PMN_TYPE>"
            "    <GENERATE_STREAM>0</GENERATE_STREAM>"
            "    <STREAM_SIZE>5242880</STREAM_SIZE>"
            "</CAESAR>";
    return config;
}

int CaesarProject::loadProjectConfiguration(TiXmlNode* pRoot) {
    m_caesarSettings.usageType = atoi(getXMLElementValue(pRoot,"CAESAR/USAGE_TYPE").c_str());
    m_caesarSettings.algorithm = atoi(getXMLElementValue(pRoot,"CAESAR/ALGORITHM").c_str());
    m_caesarSettings.limitAlgRounds = (atoi(getXMLElementValue(pRoot,"CAESAR/LIMIT_NUM_OF_ROUNDS").c_str())) ? true : false;
    m_caesarSettings.algorithmRoundsCount = atoi(getXMLElementValue(pRoot,"CAESAR/ALGORITHM_ROUNDS").c_str());
    istringstream(getXMLElementValue(pRoot,"CAESAR/PLAINTEXT_LENGTH")) >> m_caesarSettings.plaintextLength;
    istringstream(getXMLElementValue(pRoot,"CAESAR/AD_LENGTH")) >> m_caesarSettings.adLength;
    m_caesarSettings.plaintextType = atoi(getXMLElementValue(pRoot,"CAESAR/PLAINTEXT_TYPE").c_str());
    m_caesarSettings.keyType = atoi(getXMLElementValue(pRoot,"CAESAR/KEY_TYPE").c_str());
    m_caesarSettings.adType = atoi(getXMLElementValue(pRoot,"CAESAR/AD_TYPE").c_str());
    m_caesarSettings.smnType = atoi(getXMLElementValue(pRoot,"CAESAR/SMN_TYPE").c_str());
    m_caesarSettings.pmnType = atoi(getXMLElementValue(pRoot,"CAESAR/PMN_TYPE").c_str());
    m_caesarSettings.generateStream = (atoi(getXMLElementValue(pRoot,"CAESAR/GENERATE_STREAM").c_str())) ? true : false;
    istringstream(getXMLElementValue(pRoot,"CAESAR/STREAM_SIZE")) >> m_caesarSettings.streamSize;
    pCaesarSettings = &m_caesarSettings;

    // adjust number of rounds if necessary
    if (!m_caesarSettings.limitAlgRounds) { m_caesarSettings.algorithmRoundsCount = -1; }

    // bind project settings into global settings
    pGlobals->settings->project = (void*) pCaesarSettings;

    // TODO configuration checks

    return STAT_OK;
}

int CaesarProject::initializeProject() {
    // allocate encryptor
    m_encryptor = new Encryptor;
    // allocate ciphertext buffer
    m_ciphertext = new bits_t[pCaesarSettings->ciphertextLength];

    // TODO create headers for human readable test vector file

    return STAT_OK;
}

int CaesarProject::initializeProjectState() {
    int status = m_encryptor->setup();
    if (status == STAT_OK) {
        mainLogger.out(LOGGER_INFO) << "Cipher initialized (" << m_encryptor->shortDescription() << ")." << endl;
    } else {
        mainLogger.out(LOGGER_ERROR) << "Cipher could not be initialized (" << statusToString(status) << ")." << endl;
    }
    return status;
}

int CaesarProject::saveProjectState(TiXmlNode* pRoot) const {
    int status = STAT_OK;
    TiXmlElement* pRoot2 = pRoot->ToElement();
    pRoot2->SetAttribute("loadable",0);
    return STAT_OK;
}

int CaesarProject::loadProjectState(TiXmlNode* pRoot) {
    return STAT_OK;
}

int CaesarProject::createTestVectorFilesHeaders() const {
    if (pGlobals->settings->outputs.saveTestVectors) {
        ofstream tvFile;
        tvFile.open(FILE_TEST_VECTORS, ios_base::trunc | ios_base::binary);
        if (!tvFile.is_open()) {
            mainLogger.out(LOGGER_ERROR) << "Cannot write file for test vectors (" << FILE_TEST_VECTORS << ")." << endl;
            return STAT_FILE_WRITE_FAIL;
        }
        tvFile << dec << left;
        tvFile << pCaesarSettings->algorithm << " \t\t(algorithm:" << m_encryptor->shortDescription() << ")" << endl;
        tvFile << pCaesarSettings->limitAlgRounds << " \t\t(limit algorithm rounds?)" << endl;
        tvFile << pCaesarSettings->algorithmRoundsCount << " \t\t(algorithm rounds - if limited)" << endl;
        tvFile << pCaesarSettings->plaintextLength << " \t\t(plaintext length)" << endl;
        tvFile << pCaesarSettings->adLength << " \t\t(associated data length)" << endl;
        tvFile << pCaesarSettings->plaintextType << " \t\t(plaintext type)" << endl;
        tvFile << pCaesarSettings->keyType << " \t\t(key type)" << endl;
        tvFile << pCaesarSettings->adType << " \t\t(associated data type)" << endl;
        tvFile << pCaesarSettings->smnType << " \t\t(secret message number type)" << endl;
        tvFile << pCaesarSettings->pmnType << " \t\t(public message number type)" << endl;
        tvFile.close();
    }

    return STAT_OK;
}

int CaesarProject::generateTestVectors() {
    int status = STAT_OK;

    // if set so, do not generate test vectors but generate data stream to cout
    if (pCaesarSettings->generateStream) {
        status = generateCipherDataStream();
        if (status != STAT_OK) {
            return status;
        } else {
            return STAT_INTENTIONAL_EXIT;
        }
    }

    // generate cipher stream
    for (int vector = 0; vector < pGlobals->settings->testVectors.setSize/2; vector++) {
        status = prepareSingleTestVector(pGlobals->testVectors.inputs[vector], pGlobals->testVectors.outputs[vector]);
        if (status != STAT_OK) { break; }
    }
    if (status != STAT_OK) {
        mainLogger.out(LOGGER_ERROR) << "Cipher data generation failed." << endl;
        return status;
    }
    // generate random vectors
    for (int vector = pGlobals->settings->testVectors.setSize/2; vector < pGlobals->settings->testVectors.setSize; vector++) {
        // random stream
        for (int byte = 0; byte < pGlobals->settings->testVectors.inputLength; byte++) {
            rndGen->getRandomFromInterval(255, pGlobals->testVectors.inputs[vector] + byte);
        }
        // 0xff to denote random stream
        for (int byte = 0; byte < pGlobals->settings->testVectors.outputLength; byte++) {
            pGlobals->testVectors.outputs[vector][byte] = UCHAR_MAX;
        }
    }

    return status;
}

int CaesarProject::prepareSingleTestVector(unsigned char* tvInputs, unsigned char* tvOutputs) {
    int status = STAT_OK;
    switch (pCaesarSettings->usageType) {
    case CAESAR_DISTINGUISHER:
        // ciphertext stream
        status = m_encryptor->encrypt(m_ciphertext, &m_realCiphertextLength);
        if (status != STAT_OK) { return status; }
        // copy authentication tag
        memcpy(tvInputs, m_ciphertext+m_caesarSettings.plaintextLength,
                min(m_realCiphertextLength-m_caesarSettings.plaintextLength, (length_t)pGlobals->settings->testVectors.inputLength));
        // fill with zeroes
        if ((int) (m_realCiphertextLength-m_caesarSettings.plaintextLength) < pGlobals->settings->testVectors.inputLength) {
            mainLogger.out(LOGGER_WARNING) << "Authentication tag shorter than test vector input -- padded with zeroes." << endl;
            for (int byte = static_cast<int>(m_caesarSettings.plaintextLength); byte < pGlobals->settings->testVectors.inputLength; byte++) {
                tvInputs[byte] = 0;
            }
        }
        status = m_encryptor->update();
        if (status != STAT_OK) { return status; }
        // 0x00 to denote ciphertext stream
        for (int byte = 0; byte < pGlobals->settings->testVectors.outputLength; byte++) {
            tvOutputs[byte] = 0;
        }
        break;
    default:
        mainLogger.out(LOGGER_ERROR) << "Unknown usage type (" << pCaesarSettings->usageType << ") in " << shortDescription() << endl;
        return STAT_INVALID_ARGUMETS;
        break;
    }
    return status;
}

int CaesarProject::generateCipherDataStream() {
    int status = STAT_OK;

    unsigned char* tvOutputs = new unsigned char[pGlobals->settings->testVectors.outputLength];
    memset(tvOutputs,0,pGlobals->settings->testVectors.outputLength);
    unsigned char* tvInputs = new unsigned char[pGlobals->settings->testVectors.inputLength];
    memset(tvInputs,0,pGlobals->settings->testVectors.inputLength);

    string streamFilename = CAESAR_FILE_STREAM;
    mainLogger.out(LOGGER_INFO) << "Generating cipher data stream for " << m_encryptor->shortDescription() << "." << endl;

    ostream* vectorStream = NULL;
    if (pCaesarSettings->streamSize == 0) {
        vectorStream = &cout;
        mainLogger.out(LOGGER_INFO) << "Sneding binary stream to standard output." << endl;
    } else {
        vectorStream = new ofstream(streamFilename, ios_base::binary | ios_base::trunc);
        mainLogger.out(LOGGER_INFO) << "Saving binary stream to file '" << streamFilename << "'." << endl;
    }
    unsigned long alreadyGenerated = 0;
    while (pCaesarSettings->streamSize == 0 ? true : alreadyGenerated <= pCaesarSettings->streamSize) {
        for (int testVectorNumber = 0; testVectorNumber < pGlobals->settings->testVectors.setSize; testVectorNumber++) {
            if (status != STAT_OK) break;

            // get test vector
            status = prepareSingleTestVector(tvInputs,tvOutputs);

            for (int index = 0; index < pGlobals->settings->testVectors.inputLength; index++) {
                (*vectorStream) << tvInputs[index];
            }
            alreadyGenerated += pGlobals->settings->testVectors.inputLength;
        }
    }

    if (pCaesarSettings->streamSize != 0) {
        delete vectorStream;
        vectorStream = NULL;
    }
    if (status == STAT_OK) {
        mainLogger.out(LOGGER_INFO) << "Cipher data generation successful (" << alreadyGenerated << " bytes)." << endl;
    } else {
        mainLogger.out(LOGGER_ERROR) << "Cipher data generation failed (" << alreadyGenerated << " bytes generated)." << endl;
    }

    delete[] tvInputs;
    delete[] tvOutputs;

    return status;
}
<|endoftext|>


<commit_before>// @(#)root/proofx:$Id$
// Author: Gerardo Ganis  12/12/2005

/*************************************************************************
 * Copyright (C) 1995-2005, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TXUnixSocket                                                         //
//                                                                      //
// Implementation of TXSocket using PF_UNIX sockets.                    //
// Used for the internal connection between coordinator and proofserv.  //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "XpdSysPthread.h"

#include "TXUnixSocket.h"
#include "XrdProofPhyConn.h"

ClassImp(TXUnixSocket)

//_____________________________________________________________________________
TXUnixSocket::TXUnixSocket(const char *url,
                           Int_t psid, Char_t capver, TXHandler *handler, int fd)
             : TXSocket(0,'i',psid,capver,0,-1,handler)
{
   // Constructor

   // Initialization
   if (url) {

      // Create connection
      fConn = new XrdProofPhyConn(url, psid, capver, this, 0, fd);
      if (!(fConn->IsValid())) {
         Error("TXUnixSocket", "severe error occurred while opening a connection"
                               " to server [%s]", fUrl.Data());
         return;
      }

      // Fill some info
      fUser = fConn->fUser.c_str();
      fHost = fConn->fHost.c_str();
      fPort = fConn->fPort;
      fXrdProofdVersion = fConn->fRemoteProtocol;
      fRemoteProtocol = fConn->fRemoteProtocol;

      // Save also updated url
      TSocket::fUrl = fConn->fUrl.GetUrl().c_str();

      // This is needed for the reader thread to signal an interrupt
      fPid = gSystem->GetPid();
   }
}

//______________________________________________________________________________
Int_t TXUnixSocket::Reconnect()
{
   // Try reconnection after failure

   if (gDebug > 0) {
      Info("Reconnect", "%p: %p: %d: trying to reconnect on %s", this,
                        fConn, (fConn ? fConn->IsValid() : 0), fUrl.Data());
   }

   if (fXrdProofdVersion < 1005) {
      Info("Reconnect","%p: server does not support reconnections (protocol: %d < 1005)",
                       this, fXrdProofdVersion);
      return -1;
   }

   if (fConn && !fConn->IsValid()) {

      // Block any other attempt to use this connection
      XrdSysMutexHelper l(fConn->fMutex);

      fConn->Close();
      int maxtry, timewait;
      XrdProofConn::GetRetryParam(maxtry, timewait);
      XrdProofConn::SetRetryParam(300, 1);
      fConn->Connect();
      XrdProofConn::SetRetryParam();
   }

   if (gDebug > 0) {
      Info("Reconnect", "%p: %p: attempt %s", this, fConn,
                        ((fConn && fConn->IsValid()) ? "succeeded!" : "failed"));
   }

   // Done
   return ((fConn && fConn->IsValid()) ? 0 : -1);
}
<commit_msg>Add also to TXUnixSocket the possibility to disable reconnections<commit_after>// @(#)root/proofx:$Id$
// Author: Gerardo Ganis  12/12/2005

/*************************************************************************
 * Copyright (C) 1995-2005, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TXUnixSocket                                                         //
//                                                                      //
// Implementation of TXSocket using PF_UNIX sockets.                    //
// Used for the internal connection between coordinator and proofserv.  //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "XpdSysPthread.h"

#include "TXUnixSocket.h"
#include "TEnv.h"
#include "XrdProofPhyConn.h"

ClassImp(TXUnixSocket)

//_____________________________________________________________________________
TXUnixSocket::TXUnixSocket(const char *url,
                           Int_t psid, Char_t capver, TXHandler *handler, int fd)
             : TXSocket(0,'i',psid,capver,0,-1,handler)
{
   // Constructor

   // Initialization
   if (url) {

      // Create connection
      fConn = new XrdProofPhyConn(url, psid, capver, this, 0, fd);
      if (!(fConn->IsValid())) {
         Error("TXUnixSocket", "severe error occurred while opening a connection"
                               " to server [%s]", fUrl.Data());
         return;
      }

      // Fill some info
      fUser = fConn->fUser.c_str();
      fHost = fConn->fHost.c_str();
      fPort = fConn->fPort;
      fXrdProofdVersion = fConn->fRemoteProtocol;
      fRemoteProtocol = fConn->fRemoteProtocol;

      // Save also updated url
      TSocket::fUrl = fConn->fUrl.GetUrl().c_str();

      // This is needed for the reader thread to signal an interrupt
      fPid = gSystem->GetPid();
   }
}

//______________________________________________________________________________
Int_t TXUnixSocket::Reconnect()
{
   // Try reconnection after failure

   if (gDebug > 0) {
      Info("Reconnect", "%p: %p: %d: trying to reconnect on %s", this,
                        fConn, (fConn ? fConn->IsValid() : 0), fUrl.Data());
   }

   Int_t tryreconnect = gEnv->GetValue("TXSocket.Reconnect", 1);
   if (tryreconnect == 0 || fXrdProofdVersion < 1005) {
      if (tryreconnect == 0)
         Info("Reconnect","%p: reconnection attempts explicitely disabled!", this);
      else
         Info("Reconnect","%p: server does not support reconnections (protocol: %d < 1005)",
                          this, fXrdProofdVersion);
      return -1;
   }

   if (fConn && !fConn->IsValid()) {

      // Block any other attempt to use this connection
      XrdSysMutexHelper l(fConn->fMutex);

      fConn->Close();
      int maxtry, timewait;
      XrdProofConn::GetRetryParam(maxtry, timewait);
      XrdProofConn::SetRetryParam(300, 1);
      fConn->Connect();
      XrdProofConn::SetRetryParam();
   }

   if (gDebug > 0) {
      Info("Reconnect", "%p: %p: attempt %s", this, fConn,
                        ((fConn && fConn->IsValid()) ? "succeeded!" : "failed"));
   }

   // Done
   return ((fConn && fConn->IsValid()) ? 0 : -1);
}
<|endoftext|>


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

#include "chrome/browser/chromeos/net/network_change_notifier_chromeos.h"

#include "base/task.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "content/browser/browser_thread.h"

namespace {

// Delay for online change notification reporting.
const int kOnlineNotificationDelayMS = 500;

}

namespace chromeos {

NetworkChangeNotifierChromeos::NetworkChangeNotifierChromeos()
    : has_active_network_(false),
      connection_state_(chromeos::STATE_UNKNOWN) {

  chromeos::NetworkLibrary* net =
      chromeos::CrosLibrary::Get()->GetNetworkLibrary();
  net->AddNetworkManagerObserver(this);

  chromeos::PowerLibrary* power =
      chromeos::CrosLibrary::Get()->GetPowerLibrary();
  power->AddObserver(this);

  BrowserThread::PostDelayedTask(
      BrowserThread::UI, FROM_HERE,
      NewRunnableFunction(
          &NetworkChangeNotifierChromeos::UpdateInitialState, this),
      kOnlineNotificationDelayMS);
}

NetworkChangeNotifierChromeos::~NetworkChangeNotifierChromeos() {
  chromeos::NetworkLibrary* lib =
      chromeos::CrosLibrary::Get()->GetNetworkLibrary();
  lib->RemoveNetworkManagerObserver(this);
  lib->RemoveObserverForAllNetworks(this);

  chromeos::PowerLibrary* power =
      chromeos::CrosLibrary::Get()->GetPowerLibrary();
  power->RemoveObserver(this);
}

void NetworkChangeNotifierChromeos::PowerChanged(PowerLibrary* obj) {
}

void NetworkChangeNotifierChromeos::SystemResumed() {
  // Force invalidation of various net resources on system resume.
  BrowserThread::PostTask(
      BrowserThread::IO, FROM_HERE,
      NewRunnableFunction(
          &NetworkChangeNotifier::NotifyObserversOfIPAddressChange));
}

void NetworkChangeNotifierChromeos::OnNetworkManagerChanged(
    chromeos::NetworkLibrary* cros) {
  UpdateNetworkState(cros);
}

bool NetworkChangeNotifierChromeos::IsCurrentlyOffline() const {
  return connection_state_ != chromeos::STATE_ONLINE;
}

void NetworkChangeNotifierChromeos::OnNetworkChanged(
    chromeos::NetworkLibrary* cros,
    const chromeos::Network* network) {
  CHECK(network);

  // Active network changed?
  if (network->service_path() != service_path_)
    UpdateNetworkState(cros);
  else
    UpdateConnectivityState(network);
}

void NetworkChangeNotifierChromeos::UpdateNetworkState(
    chromeos::NetworkLibrary* lib) {
  const chromeos::Network* network = lib->active_network();

  // Check if active network was added, removed or changed.
  if ((!network && has_active_network_) ||
      (network && (!has_active_network_ ||
                   network->service_path() != service_path_ ||
                   network->ip_address() != ip_address_))) {
    if (has_active_network_)
      lib->RemoveObserverForAllNetworks(this);
    if (!network) {
      has_active_network_ = false;
      service_path_.clear();
      ip_address_.clear();
      connection_state_ = chromeos::STATE_UNKNOWN;
    } else {
      has_active_network_ = true;
      service_path_ = network->service_path();
      ip_address_ = network->ip_address();
    }
    UpdateConnectivityState(network);
    // If there is an active network, add observer to track its changes.
    if (network)
      lib->AddNetworkObserver(network->service_path(), this);

    BrowserThread::PostTask(
        BrowserThread::IO, FROM_HERE,
        NewRunnableFunction(
            &NetworkChangeNotifier::NotifyObserversOfIPAddressChange));
  }
}

void NetworkChangeNotifierChromeos::UpdateConnectivityState(
      const chromeos::Network* network) {
  // We don't care about all transitions of ConnectionState.  OnlineStateChange
  // notification should trigger if
  //   a) we were online and went offline
  //   b) we were offline and went online
  //   c) switched to/from captive portal
  chromeos::ConnectionState new_connection_state =
      network ? network->connection_state() : chromeos::STATE_UNKNOWN;

  bool is_online = (new_connection_state == chromeos::STATE_ONLINE);
  bool was_online = (connection_state_ == chromeos::STATE_ONLINE);
  bool is_portal = (new_connection_state == chromeos::STATE_PORTAL);
  bool was_portal = (connection_state_ == chromeos::STATE_PORTAL);
  bool is_unknown = (new_connection_state == chromeos::STATE_UNKNOWN);
  bool was_unknown = (connection_state_ == chromeos::STATE_UNKNOWN);
  connection_state_ = new_connection_state;
  if (is_online != was_online || is_portal != was_portal ||
      is_unknown != was_unknown) {
    if (!IsCurrentlyOffline()) {
      // Delay reporting of edge when we go online. dns resolution service
      // does not seem to be immediately available.
      BrowserThread::PostDelayedTask(
          BrowserThread::IO, FROM_HERE,
          NewRunnableFunction(
             &NetworkChangeNotifierChromeos::NotifyObserversOfOnlineStateChange),
          kOnlineNotificationDelayMS);
    } else {
      BrowserThread::PostTask(
          BrowserThread::IO, FROM_HERE,
          NewRunnableFunction(
             &NetworkChangeNotifierChromeos::NotifyObserversOfOnlineStateChange));
    }
  }
}

// static
void NetworkChangeNotifierChromeos::UpdateInitialState(
    NetworkChangeNotifierChromeos* self) {
  chromeos::NetworkLibrary* net =
      chromeos::CrosLibrary::Get()->GetNetworkLibrary();
  self->UpdateNetworkState(net);
}

}  // namespace net
<commit_msg>Fixed offline edge detection.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/net/network_change_notifier_chromeos.h"

#include "base/task.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "content/browser/browser_thread.h"

namespace {

// Delay for online change notification reporting.
const int kOnlineNotificationDelayMS = 500;

}

namespace chromeos {

NetworkChangeNotifierChromeos::NetworkChangeNotifierChromeos()
    : has_active_network_(false),
      connection_state_(chromeos::STATE_UNKNOWN) {

  chromeos::NetworkLibrary* net =
      chromeos::CrosLibrary::Get()->GetNetworkLibrary();
  net->AddNetworkManagerObserver(this);

  chromeos::PowerLibrary* power =
      chromeos::CrosLibrary::Get()->GetPowerLibrary();
  power->AddObserver(this);

  BrowserThread::PostDelayedTask(
      BrowserThread::UI, FROM_HERE,
      NewRunnableFunction(
          &NetworkChangeNotifierChromeos::UpdateInitialState, this),
      kOnlineNotificationDelayMS);
}

NetworkChangeNotifierChromeos::~NetworkChangeNotifierChromeos() {
  chromeos::NetworkLibrary* lib =
      chromeos::CrosLibrary::Get()->GetNetworkLibrary();
  lib->RemoveNetworkManagerObserver(this);
  lib->RemoveObserverForAllNetworks(this);

  chromeos::PowerLibrary* power =
      chromeos::CrosLibrary::Get()->GetPowerLibrary();
  power->RemoveObserver(this);
}

void NetworkChangeNotifierChromeos::PowerChanged(PowerLibrary* obj) {
}

void NetworkChangeNotifierChromeos::SystemResumed() {
  // Force invalidation of various net resources on system resume.
  BrowserThread::PostTask(
      BrowserThread::IO, FROM_HERE,
      NewRunnableFunction(
          &NetworkChangeNotifier::NotifyObserversOfIPAddressChange));
}

void NetworkChangeNotifierChromeos::OnNetworkManagerChanged(
    chromeos::NetworkLibrary* cros) {
  UpdateNetworkState(cros);
}

bool NetworkChangeNotifierChromeos::IsCurrentlyOffline() const {
  return connection_state_ != chromeos::STATE_ONLINE;
}

void NetworkChangeNotifierChromeos::OnNetworkChanged(
    chromeos::NetworkLibrary* cros,
    const chromeos::Network* network) {
  CHECK(network);

  // Active network changed?
  if (network->service_path() != service_path_)
    UpdateNetworkState(cros);
  else
    UpdateConnectivityState(network);
}

void NetworkChangeNotifierChromeos::UpdateNetworkState(
    chromeos::NetworkLibrary* lib) {
  const chromeos::Network* network = lib->active_network();

  // Check if active network was added, removed or changed.
  if ((!network && has_active_network_) ||
      (network && (!has_active_network_ ||
                   network->service_path() != service_path_ ||
                   network->ip_address() != ip_address_))) {
    if (has_active_network_)
      lib->RemoveObserverForAllNetworks(this);
    if (!network) {
      has_active_network_ = false;
      service_path_.clear();
      ip_address_.clear();
    } else {
      has_active_network_ = true;
      service_path_ = network->service_path();
      ip_address_ = network->ip_address();
    }
    UpdateConnectivityState(network);
    // If there is an active network, add observer to track its changes.
    if (network)
      lib->AddNetworkObserver(network->service_path(), this);

    BrowserThread::PostTask(
        BrowserThread::IO, FROM_HERE,
        NewRunnableFunction(
            &NetworkChangeNotifier::NotifyObserversOfIPAddressChange));
  }
}

void NetworkChangeNotifierChromeos::UpdateConnectivityState(
      const chromeos::Network* network) {
  // We don't care about all transitions of ConnectionState.  OnlineStateChange
  // notification should trigger if
  //   a) we were online and went offline
  //   b) we were offline and went online
  //   c) switched to/from captive portal
  chromeos::ConnectionState new_connection_state =
      network ? network->connection_state() : chromeos::STATE_UNKNOWN;

  bool is_online = (new_connection_state == chromeos::STATE_ONLINE);
  bool was_online = (connection_state_ == chromeos::STATE_ONLINE);
  bool is_portal = (new_connection_state == chromeos::STATE_PORTAL);
  bool was_portal = (connection_state_ == chromeos::STATE_PORTAL);
  bool is_unknown = (new_connection_state == chromeos::STATE_UNKNOWN);
  bool was_unknown = (connection_state_ == chromeos::STATE_UNKNOWN);
  connection_state_ = new_connection_state;
  if (is_online != was_online || is_portal != was_portal ||
      is_unknown != was_unknown) {
    if (!IsCurrentlyOffline()) {
      // Delay reporting of edge when we go online. dns resolution service
      // does not seem to be immediately available.
      BrowserThread::PostDelayedTask(
          BrowserThread::IO, FROM_HERE,
          NewRunnableFunction(
             &NetworkChangeNotifierChromeos::NotifyObserversOfOnlineStateChange),
          kOnlineNotificationDelayMS);
    } else {
      BrowserThread::PostTask(
          BrowserThread::IO, FROM_HERE,
          NewRunnableFunction(
             &NetworkChangeNotifierChromeos::NotifyObserversOfOnlineStateChange));
    }
  }
}

// static
void NetworkChangeNotifierChromeos::UpdateInitialState(
    NetworkChangeNotifierChromeos* self) {
  chromeos::NetworkLibrary* net =
      chromeos::CrosLibrary::Get()->GetNetworkLibrary();
  self->UpdateNetworkState(net);
}

}  // namespace net
<|endoftext|>


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

#include "chrome/browser/chromeos/status/clock_menu_button.h"

#include "base/string_util.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/system_library.h"
#include "chrome/browser/chromeos/frame/browser_view.h"
#include "chrome/browser/chromeos/status/status_area_view.h"
#include "chrome/browser/chromeos/view_ids.h"
#include "chrome/browser/pref_member.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/in_process_browser_test.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "unicode/calendar.h"
#include "unicode/timezone.h"

namespace chromeos {

class ClockMenuButtonTest : public InProcessBrowserTest {
 protected:
  ClockMenuButtonTest() : InProcessBrowserTest() {}
  ClockMenuButton* GetClockMenuButton() {
    BrowserView* view = static_cast<BrowserView*>(browser()->window());
    return static_cast<StatusAreaView*>(view->
        GetViewByID(VIEW_ID_STATUS_AREA))->clock_view();
  }
};

IN_PROC_BROWSER_TEST_F(ClockMenuButtonTest, TimezoneTest) {
  ClockMenuButton* clock = GetClockMenuButton();
  ASSERT_TRUE(clock != NULL);
  // Update timezone and make sure clock text changes.
  std::wstring text_before = clock->text();
  scoped_ptr<icu::TimeZone> timezone(icu::TimeZone::createTimeZone(
      icu::UnicodeString::fromUTF8("Asia/Hong_Kong")));
  CrosLibrary::Get()->GetSystemLibrary()->SetTimezone(timezone.get());
  std::wstring text_after = clock->text();
  EXPECT_NE(text_before, text_after);
}

}  // namespace chromeos
<commit_msg>Fixed flakyness of ClockMenuButtonTest.TimezoneTest.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/status/clock_menu_button.h"

#include "base/string_util.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/system_library.h"
#include "chrome/browser/chromeos/frame/browser_view.h"
#include "chrome/browser/chromeos/status/status_area_view.h"
#include "chrome/browser/chromeos/view_ids.h"
#include "chrome/browser/pref_member.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/in_process_browser_test.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "unicode/calendar.h"
#include "unicode/timezone.h"

namespace chromeos {

class ClockMenuButtonTest : public InProcessBrowserTest {
 protected:
  ClockMenuButtonTest() : InProcessBrowserTest() {}
  ClockMenuButton* GetClockMenuButton() {
    BrowserView* view = static_cast<BrowserView*>(browser()->window());
    return static_cast<StatusAreaView*>(view->
        GetViewByID(VIEW_ID_STATUS_AREA))->clock_view();
  }
};

IN_PROC_BROWSER_TEST_F(ClockMenuButtonTest, TimezoneTest) {
  ClockMenuButton* clock = GetClockMenuButton();
  ASSERT_TRUE(clock != NULL);

  // Update timezone and make sure clock text changes.
  scoped_ptr<icu::TimeZone> timezone_first(icu::TimeZone::createTimeZone(
      icu::UnicodeString::fromUTF8("Asia/Hong_Kong")));
  CrosLibrary::Get()->GetSystemLibrary()->SetTimezone(timezone_first.get());
  std::wstring text_before = clock->text();
  scoped_ptr<icu::TimeZone> timezone_second(icu::TimeZone::createTimeZone(
      icu::UnicodeString::fromUTF8("Pacific/Samoa")));
  CrosLibrary::Get()->GetSystemLibrary()->SetTimezone(timezone_second.get());
  std::wstring text_after = clock->text();
  EXPECT_NE(text_before, text_after);

}

}  // namespace chromeos
<|endoftext|>


<commit_before>/*
 * File: batch_soax.cc
 *
 * This file implements the batch processing of SOAX commandline
 * program.  The input images can be more than one, and the parameters
 * can vary.
 *
 * Copyright (C) 2014 Ting Xu, IDEA Lab, Lehigh University.
 */

#include <sstream>
#include <iomanip>
#include "boost/program_options.hpp"
#include "boost/filesystem.hpp"
#include "multisnake.h"

std::string ConstructSnakeFilename(const std::string &image_path,
                                   double ridge_threshold, double stretch);
std::string GetImageSuffix(const std::string &image_path);

int main(int argc, char **argv) {
  try {
    namespace po = boost::program_options;
    po::options_description generic("Generic options");
    generic.add_options()
        ("version,v", "Print version and exit")
        ("help,h", "Print help and exit");

    po::options_description required("Required options");
    required.add_options()
        ("image,i", po::value<std::string>()->required(),
         "Directory or path of input image files")
        ("parameter,p",
         po::value<std::string>()->required(),
         "Path of default parameter file")
        ("snake,s", po::value<std::string>()->required(),
         "Directory or path of output snake files");

    soax::DataContainer ridge_range, stretch_range;
    po::options_description optional("Optional options");
    optional.add_options()
        ("ridge",
         po::value<soax::DataContainer>(&ridge_range)->multitoken(),
         "Range of ridge threshold (start step end)")
        ("stretch",
         po::value<soax::DataContainer>(&stretch_range)->multitoken(),
         "Range of stretching factor (start step end)")
        ("invert", "Use inverted image intensity");

    po::options_description all("Allowed options");
    all.add(generic).add(required).add(optional);
    po::variables_map vm;
    po::store(parse_command_line(argc, argv, all), vm);

    if (vm.count("version")) {
      const std::string version_msg(
          "SOAX Batch 3.5.4\n"
          "Copyright (C) 2014 Ting Xu, IDEA Lab, Lehigh University.");
      std::cout << version_msg << std::endl;
      return EXIT_SUCCESS;
    }

    if (vm.count("help")) {
      std::cout << "SOAX Commandline Mode: \n" << all;
      return EXIT_SUCCESS;
    }

    po::notify(vm);

    namespace fs = boost::filesystem;
    fs::path image_path(vm["image"].as<std::string>());
    if (!fs::exists(image_path)) {
      std::cerr << image_path << " does not exist. Abort." << std::endl;
      return EXIT_FAILURE;
    }

    fs::path parameter_path(vm["parameter"].as<std::string>());
    if (!fs::exists(parameter_path)) {
      std::cerr << parameter_path << " does not exist. Abort." << std::endl;
      return EXIT_FAILURE;
    }

    fs::path snake_path(vm["snake"].as<std::string>());
    if (!fs::exists(snake_path)) {
      std::cerr << snake_path << " does not exist. Abort." << std::endl;
      return EXIT_FAILURE;
    }

    try {
      soax::Multisnake multisnake;
      if (vm.count("ridge") && vm.count("stretch")) {
        std::cout << "Varying ridge threshold and stretch factor." << std::endl;

        if (fs::is_regular_file(image_path)) {
          std::cout << "Input is single image" << std::endl;

          multisnake.LoadImage(image_path.string());
          if (vm.count("invert"))  multisnake.InvertImageIntensity();
          multisnake.LoadParameters(parameter_path.string());
          multisnake.ComputeImageGradient();

          double ridge_threshold = ridge_range[0];
          while (ridge_threshold < ridge_range[2]) {
            // for (int ridge_exp = ridge_range[0]; ridge_exp < ridge_range[2];
            //      ridge_exp += static_cast<int>(ridge_range[1])) {
            //   double ridge_threshold = std::pow(2, ridge_exp);
            std::cout << "\nSegmentation started on " << image_path
                      << "\nridge_threshold is set to: " << ridge_threshold
                      << std::endl;
            multisnake.set_ridge_threshold(ridge_threshold);
            double stretch = stretch_range[0];
            while (stretch < stretch_range[2]) {
              // for (int stretch_exp = stretch_range[0];
              //      stretch_exp < stretch_range[2];
              //      stretch_exp += static_cast<int>(stretch_range[1])) {
              //   double stretch = std::pow(2, stretch_exp);
              std::cout << "stretch is set to: " << stretch << std::endl;
              soax::Snake::set_stretch_factor(stretch);

              std::cout << "=========== Current Parameters ==========="
                        << std::endl;
              multisnake.WriteParameters(std::cout);
              std::cout << "=========================================="
                        << std::endl;

              multisnake.InitializeSnakes();

              time_t start, end;
              time(&start);
              multisnake.DeformSnakes();
              time(&end);
              double time_elasped = difftime(end, start);
              multisnake.CutSnakesAtTJunctions();
              multisnake.GroupSnakes();

              std::string snake_name = ConstructSnakeFilename(
                  image_path.string(), ridge_threshold, stretch);
              std::cout << snake_name << std::endl;
              multisnake.SaveSnakes(multisnake.converged_snakes(),
                                    snake_path.string() + snake_name);

              std::cout << "Segmentation completed (Evolution time: "
                        << time_elasped << "s)" << std::endl;
              multisnake.ResetContainers();
              stretch += stretch_range[1];
            }
            ridge_threshold += ridge_range[1];
          }

        } else if (fs::is_directory(image_path)) {
          std::cout << "Input may contain multiple images." << std::endl;

          typedef std::vector<fs::path> Paths;
          Paths image_paths;
          std::copy(fs::directory_iterator(image_path), fs::directory_iterator(),
                    back_inserter(image_paths));
          std::sort(image_paths.begin(), image_paths.end());
          for (Paths::const_iterator image_it(image_paths.begin());
               image_it != image_paths.end(); ++image_it) {
            // fs::directory_iterator image_end_it;
            // for (fs::directory_iterator image_it(image_path);
            //      image_it != image_end_it; ++image_it) {
            std::string suffix = GetImageSuffix(image_it->string());
            if (suffix != "mha" && suffix != "tif" && suffix != "TIF") {
              std::cout << "Unknown image type: " << suffix << std::endl;
              continue;
            }
            multisnake.LoadImage(image_it->string());
            if (vm.count("invert"))  multisnake.InvertImageIntensity();
            multisnake.LoadParameters(parameter_path.string());
            multisnake.ComputeImageGradient();
            // vary ridge_threshold and stretch
            double ridge_threshold = ridge_range[0];
            while (ridge_threshold < ridge_range[2]) {
              std::cout << "\nSegmentation started on " << *image_it
                        << "\nridge_threshold is set to: " << ridge_threshold
                        << std::endl;
              multisnake.set_ridge_threshold(ridge_threshold);
              double stretch = stretch_range[0];
              while (stretch < stretch_range[2]) {
                std::cout << "stretch is set to: " << stretch << std::endl;
                soax::Snake::set_stretch_factor(stretch);

                std::cout << "=========== Current Parameters ==========="
                          << std::endl;
                multisnake.WriteParameters(std::cout);
                std::cout << "=========================================="
                          << std::endl;

                multisnake.InitializeSnakes();

                time_t start, end;
                time(&start);
                multisnake.DeformSnakes();
                time(&end);
                double time_elasped = difftime(end, start);

                multisnake.CutSnakesAtTJunctions();
                multisnake.GroupSnakes();

                std::string snake_name = ConstructSnakeFilename(
                    image_it->string(), ridge_threshold, stretch);
                multisnake.SaveSnakes(multisnake.converged_snakes(),
                                      snake_path.string() + snake_name);

                std::cout << "Segmentation completed (Evolution time: "
                          << time_elasped << "s)" << std::endl;
                multisnake.Reset();
                stretch += stretch_range[1];
              }
              ridge_threshold += ridge_range[1];
            }
          }
        } else {
          std::cout << image_path
                    << " is neither a regular file nor a directory"
                    << std::endl;
        }
      } else if (!vm.count("ridge") && !vm.count("stretch")) {
        std::cout << "Fixed parameters." << std::endl;
        if (fs::is_regular_file(image_path)) {
          std::cout << "Input is a single image. Please use the GUI version."
                    << std::endl;
        } else if (fs::is_directory(image_path)) {
          std::cout << "Input may contain multiple images." << std::endl;

          typedef std::vector<fs::path> Paths;
          Paths image_paths;
          std::copy(fs::directory_iterator(image_path),
                    fs::directory_iterator(),
                    back_inserter(image_paths));
          std::sort(image_paths.begin(), image_paths.end());
          for (Paths::const_iterator image_it(image_paths.begin());
               image_it != image_paths.end(); ++image_it) {
            // fs::directory_iterator image_end_it;
            // for (fs::directory_iterator image_it(image_path);
            //      image_it != image_end_it; ++image_it) {
            std::string suffix = GetImageSuffix(image_it->string());
            if (suffix != "mha" && suffix != "tif" && suffix != "TIF") {
              std::cout << "Unknown image type: " << suffix << std::endl;
              continue;
            }
            multisnake.LoadImage(image_it->string());
            if (vm.count("invert"))  multisnake.InvertImageIntensity();
            multisnake.LoadParameters(parameter_path.string());
            multisnake.ComputeImageGradient();

            std::cout << "\nSegmentation started on " << *image_it << std::endl;
            std::cout << "=========== Current Parameters ==========="
                      << std::endl;
            multisnake.WriteParameters(std::cout);
            std::cout << "=========================================="
                      << std::endl;

            multisnake.InitializeSnakes();

            time_t start, end;
            time(&start);
            multisnake.DeformSnakes();
            time(&end);
            double time_elasped = difftime(end, start);

            multisnake.CutSnakesAtTJunctions();
            multisnake.GroupSnakes();

            std::string path_str = image_it->string();
            std::string::size_type slash_pos = path_str.find_last_of("/\\");
            std::string::size_type dot_pos = path_str.find_last_of(".");
            std::string extracted_name = path_str.substr(
                slash_pos+1, dot_pos-slash_pos-1);
            multisnake.SaveSnakes(multisnake.converged_snakes(),
                                  snake_path.string() + extracted_name + ".txt");

            std::cout << "Segmentation completed (Evolution time: "
                      << time_elasped << "s)" << std::endl;
            // multisnake.junctions().Reset();
            multisnake.Reset();
          }
        } else {
          std::cout << image_path << " exists, but is neither a regular file nor a directory" << std::endl;
        }
      } else {
        std::cerr << "Cannot varing one parameter only." << std::endl;
      }

    } catch (const fs::filesystem_error &e) {
      std::cout << e.what() << std::endl;
      return EXIT_FAILURE;
    }
  } catch (std::exception &e) {
    std::cout << e.what() << std::endl;
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}

std::string ConstructSnakeFilename(const std::string &image_path,
                                   double ridge_threshold, double stretch) {
  std::string::size_type slash_pos = image_path.find_last_of("/\\");
  std::string::size_type dot_pos = image_path.find_last_of(".");
  std::string extracted_name = image_path.substr(
      slash_pos+1, dot_pos-slash_pos-1);
  // std::cout << "extracted name: " << extracted_name << std::endl;
  std::ostringstream buffer;
  // std::cout << "default: " << buffer.precision() << std::endl;
  buffer.precision(2);
  // std::cout << "current: " << buffer.precision() << std::endl;
  buffer << std::showpoint << extracted_name << "--ridge"
         << ridge_threshold << "--stretch" << stretch << ".txt";
  return buffer.str();
}

std::string GetImageSuffix(const std::string &image_path) {
  std::string::size_type dot_pos = image_path.find_last_of(".");
  // std::cout << image_path.substr(dot_pos+1) << std::endl;
  return image_path.substr(dot_pos+1);
}
<commit_msg>batch_soax do not perform extraction if corresponding snake exists.<commit_after>/*
 * File: batch_soax.cc
 *
 * This file implements the batch processing of SOAX commandline
 * program.  The input images can be more than one, and the parameters
 * can vary.
 *
 * Copyright (C) 2014 Ting Xu, IDEA Lab, Lehigh University.
 */

#include <sstream>
#include <iomanip>
#include "boost/program_options.hpp"
#include "boost/filesystem.hpp"
#include "multisnake.h"

std::string ConstructSnakeFilename(const std::string &image_path,
                                   double ridge_threshold, double stretch);
std::string GetImageSuffix(const std::string &image_path);

int main(int argc, char **argv) {
  try {
    namespace po = boost::program_options;
    po::options_description generic("Generic options");
    generic.add_options()
        ("version,v", "Print version and exit")
        ("help,h", "Print help and exit");

    po::options_description required("Required options");
    required.add_options()
        ("image,i", po::value<std::string>()->required(),
         "Directory or path of input image files")
        ("parameter,p",
         po::value<std::string>()->required(),
         "Path of default parameter file")
        ("snake,s", po::value<std::string>()->required(),
         "Directory or path of output snake files");

    soax::DataContainer ridge_range, stretch_range;
    po::options_description optional("Optional options");
    optional.add_options()
        ("ridge",
         po::value<soax::DataContainer>(&ridge_range)->multitoken(),
         "Range of ridge threshold (start step end)")
        ("stretch",
         po::value<soax::DataContainer>(&stretch_range)->multitoken(),
         "Range of stretching factor (start step end)")
        ("invert", "Use inverted image intensity");

    po::options_description all("Allowed options");
    all.add(generic).add(required).add(optional);
    po::variables_map vm;
    po::store(parse_command_line(argc, argv, all), vm);

    if (vm.count("version")) {
      const std::string version_msg(
          "SOAX Batch 3.5.4\n"
          "Copyright (C) 2014 Ting Xu, IDEA Lab, Lehigh University.");
      std::cout << version_msg << std::endl;
      return EXIT_SUCCESS;
    }

    if (vm.count("help")) {
      std::cout << "SOAX Commandline Mode: \n" << all;
      return EXIT_SUCCESS;
    }

    po::notify(vm);

    namespace fs = boost::filesystem;
    fs::path image_path(vm["image"].as<std::string>());
    if (!fs::exists(image_path)) {
      std::cerr << image_path << " does not exist. Abort." << std::endl;
      return EXIT_FAILURE;
    }

    fs::path parameter_path(vm["parameter"].as<std::string>());
    if (!fs::exists(parameter_path)) {
      std::cerr << parameter_path << " does not exist. Abort." << std::endl;
      return EXIT_FAILURE;
    }

    fs::path snake_path(vm["snake"].as<std::string>());
    if (!fs::exists(snake_path)) {
      std::cerr << snake_path << " does not exist. Abort." << std::endl;
      return EXIT_FAILURE;
    }

    try {
      soax::Multisnake multisnake;
      if (vm.count("ridge") && vm.count("stretch")) {
        std::cout << "Varying ridge threshold and stretch factor." << std::endl;

        if (fs::is_regular_file(image_path)) {
          std::cout << "Input is single image" << std::endl;

          multisnake.LoadImage(image_path.string());
          if (vm.count("invert"))  multisnake.InvertImageIntensity();
          multisnake.LoadParameters(parameter_path.string());
          multisnake.ComputeImageGradient();

          double ridge_threshold = ridge_range[0];
          while (ridge_threshold < ridge_range[2]) {
            std::cout << "\nExtraction started on " << image_path
                      << "\nridge_threshold is set to: " << ridge_threshold
                      << std::endl;
            multisnake.set_ridge_threshold(ridge_threshold);
            double stretch = stretch_range[0];
            while (stretch < stretch_range[2]) {
              std::string snake_name = ConstructSnakeFilename(
                  image_path.string(), ridge_threshold, stretch);
              fs::path output_snake_path(snake_path.string() + snake_name);
              // std::cout << "output_snake_path: " << output_snake_path << std::endl;
              if (fs::exists(output_snake_path)) {
                std::cout << snake_name << " existed. No extraction is performed."
                          << std::endl;
              } else {
                std::cout << "stretch is set to: " << stretch << std::endl;
                soax::Snake::set_stretch_factor(stretch);

                std::cout << "=========== Current Parameters ==========="
                          << std::endl;
                multisnake.WriteParameters(std::cout);
                std::cout << "=========================================="
                          << std::endl;

                multisnake.InitializeSnakes();

                time_t start, end;
                time(&start);
                multisnake.DeformSnakes();
                time(&end);
                double time_elasped = difftime(end, start);
                multisnake.CutSnakesAtTJunctions();
                multisnake.GroupSnakes();

                // std::string snake_name = ConstructSnakeFilename(
                //     image_path.string(), ridge_threshold, stretch);
                std::cout << snake_name << std::endl;
                multisnake.SaveSnakes(multisnake.converged_snakes(),
                                      snake_path.string() + snake_name);

                std::cout << "Segmentation completed (Evolution time: "
                          << time_elasped << "s)" << std::endl;
                multisnake.ResetContainers();
              }
              stretch += stretch_range[1];
            }
            ridge_threshold += ridge_range[1];
          }

        } else if (fs::is_directory(image_path)) {
          std::cout << "Input may contain multiple images." << std::endl;

          typedef std::vector<fs::path> Paths;
          Paths image_paths;
          std::copy(fs::directory_iterator(image_path), fs::directory_iterator(),
                    back_inserter(image_paths));
          std::sort(image_paths.begin(), image_paths.end());
          for (Paths::const_iterator image_it(image_paths.begin());
               image_it != image_paths.end(); ++image_it) {
            // fs::directory_iterator image_end_it;
            // for (fs::directory_iterator image_it(image_path);
            //      image_it != image_end_it; ++image_it) {
            std::string suffix = GetImageSuffix(image_it->string());
            if (suffix != "mha" && suffix != "tif" && suffix != "TIF") {
              std::cout << "Unknown image type: " << suffix << std::endl;
              continue;
            }
            multisnake.LoadImage(image_it->string());
            if (vm.count("invert"))  multisnake.InvertImageIntensity();
            multisnake.LoadParameters(parameter_path.string());
            multisnake.ComputeImageGradient();
            // vary ridge_threshold and stretch
            double ridge_threshold = ridge_range[0];
            while (ridge_threshold < ridge_range[2]) {
              std::cout << "\nSegmentation started on " << *image_it
                        << "\nridge_threshold is set to: " << ridge_threshold
                        << std::endl;
              multisnake.set_ridge_threshold(ridge_threshold);
              double stretch = stretch_range[0];
              while (stretch < stretch_range[2]) {
                std::cout << "stretch is set to: " << stretch << std::endl;
                soax::Snake::set_stretch_factor(stretch);

                std::cout << "=========== Current Parameters ==========="
                          << std::endl;
                multisnake.WriteParameters(std::cout);
                std::cout << "=========================================="
                          << std::endl;

                multisnake.InitializeSnakes();

                time_t start, end;
                time(&start);
                multisnake.DeformSnakes();
                time(&end);
                double time_elasped = difftime(end, start);

                multisnake.CutSnakesAtTJunctions();
                multisnake.GroupSnakes();

                std::string snake_name = ConstructSnakeFilename(
                    image_it->string(), ridge_threshold, stretch);
                multisnake.SaveSnakes(multisnake.converged_snakes(),
                                      snake_path.string() + snake_name);

                std::cout << "Segmentation completed (Evolution time: "
                          << time_elasped << "s)" << std::endl;
                multisnake.Reset();
                stretch += stretch_range[1];
              }
              ridge_threshold += ridge_range[1];
            }
          }
        } else {
          std::cout << image_path
                    << " is neither a regular file nor a directory"
                    << std::endl;
        }
      } else if (!vm.count("ridge") && !vm.count("stretch")) {
        std::cout << "Fixed parameters." << std::endl;
        if (fs::is_regular_file(image_path)) {
          std::cout << "Input is a single image. Please use the GUI version."
                    << std::endl;
        } else if (fs::is_directory(image_path)) {
          std::cout << "Input may contain multiple images." << std::endl;

          typedef std::vector<fs::path> Paths;
          Paths image_paths;
          std::copy(fs::directory_iterator(image_path),
                    fs::directory_iterator(),
                    back_inserter(image_paths));
          std::sort(image_paths.begin(), image_paths.end());
          for (Paths::const_iterator image_it(image_paths.begin());
               image_it != image_paths.end(); ++image_it) {
            // fs::directory_iterator image_end_it;
            // for (fs::directory_iterator image_it(image_path);
            //      image_it != image_end_it; ++image_it) {
            std::string suffix = GetImageSuffix(image_it->string());
            if (suffix != "mha" && suffix != "tif" && suffix != "TIF") {
              std::cout << "Unknown image type: " << suffix << std::endl;
              continue;
            }
            multisnake.LoadImage(image_it->string());
            if (vm.count("invert"))  multisnake.InvertImageIntensity();
            multisnake.LoadParameters(parameter_path.string());
            multisnake.ComputeImageGradient();

            std::cout << "\nSegmentation started on " << *image_it << std::endl;
            std::cout << "=========== Current Parameters ==========="
                      << std::endl;
            multisnake.WriteParameters(std::cout);
            std::cout << "=========================================="
                      << std::endl;

            multisnake.InitializeSnakes();

            time_t start, end;
            time(&start);
            multisnake.DeformSnakes();
            time(&end);
            double time_elasped = difftime(end, start);

            multisnake.CutSnakesAtTJunctions();
            multisnake.GroupSnakes();

            std::string path_str = image_it->string();
            std::string::size_type slash_pos = path_str.find_last_of("/\\");
            std::string::size_type dot_pos = path_str.find_last_of(".");
            std::string extracted_name = path_str.substr(
                slash_pos+1, dot_pos-slash_pos-1);
            multisnake.SaveSnakes(multisnake.converged_snakes(),
                                  snake_path.string() + extracted_name + ".txt");

            std::cout << "Segmentation completed (Evolution time: "
                      << time_elasped << "s)" << std::endl;
            // multisnake.junctions().Reset();
            multisnake.Reset();
          }
        } else {
          std::cout << image_path << " exists, but is neither a regular file nor a directory" << std::endl;
        }
      } else {
        std::cerr << "Cannot varing one parameter only." << std::endl;
      }

    } catch (const fs::filesystem_error &e) {
      std::cout << e.what() << std::endl;
      return EXIT_FAILURE;
    }
  } catch (std::exception &e) {
    std::cout << e.what() << std::endl;
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}

std::string ConstructSnakeFilename(const std::string &image_path,
                                   double ridge_threshold, double stretch) {
  std::string::size_type slash_pos = image_path.find_last_of("/\\");
  std::string::size_type dot_pos = image_path.find_last_of(".");
  std::string extracted_name = image_path.substr(
      slash_pos+1, dot_pos-slash_pos-1);
  // std::cout << "extracted name: " << extracted_name << std::endl;
  std::ostringstream buffer;
  // std::cout << "default: " << buffer.precision() << std::endl;
  buffer.precision(2);
  // std::cout << "current: " << buffer.precision() << std::endl;
  buffer << std::showpoint << extracted_name << "--ridge"
         << ridge_threshold << "--stretch" << stretch << ".txt";
  return buffer.str();
}

std::string GetImageSuffix(const std::string &image_path) {
  std::string::size_type dot_pos = image_path.find_last_of(".");
  // std::cout << image_path.substr(dot_pos+1) << std::endl;
  return image_path.substr(dot_pos+1);
}
<|endoftext|>


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

#include "components/plugins/renderer/webview_plugin.h"

#include "base/message_loop/message_loop.h"
#include "base/metrics/histogram_macros.h"
#include "base/numerics/safe_conversions.h"
#include "content/public/common/web_preferences.h"
#include "content/public/renderer/render_view.h"
#include "gin/converter.h"
#include "skia/ext/platform_canvas.h"
#include "third_party/WebKit/public/platform/WebSize.h"
#include "third_party/WebKit/public/platform/WebURL.h"
#include "third_party/WebKit/public/platform/WebURLRequest.h"
#include "third_party/WebKit/public/platform/WebURLResponse.h"
#include "third_party/WebKit/public/web/WebDocument.h"
#include "third_party/WebKit/public/web/WebElement.h"
#include "third_party/WebKit/public/web/WebInputEvent.h"
#include "third_party/WebKit/public/web/WebLocalFrame.h"
#include "third_party/WebKit/public/web/WebPluginContainer.h"
#include "third_party/WebKit/public/web/WebView.h"

using blink::WebCanvas;
using blink::WebCursorInfo;
using blink::WebDragData;
using blink::WebDragOperationsMask;
using blink::WebImage;
using blink::WebInputEvent;
using blink::WebLocalFrame;
using blink::WebMouseEvent;
using blink::WebPlugin;
using blink::WebPluginContainer;
using blink::WebPoint;
using blink::WebRect;
using blink::WebSize;
using blink::WebString;
using blink::WebURLError;
using blink::WebURLRequest;
using blink::WebURLResponse;
using blink::WebVector;
using blink::WebView;
using content::WebPreferences;

WebViewPlugin::WebViewPlugin(content::RenderView* render_view,
                             WebViewPlugin::Delegate* delegate,
                             const WebPreferences& preferences)
    : content::RenderViewObserver(render_view),
      delegate_(delegate),
      container_(NULL),
      web_view_(WebView::create(this)),
      finished_loading_(false),
      focused_(false) {
  // ApplyWebPreferences before making a WebLocalFrame so that the frame sees a
  // consistent view of our preferences.
  content::RenderView::ApplyWebPreferences(preferences, web_view_);
  web_frame_ = WebLocalFrame::create(blink::WebTreeScopeType::Document, this);
  web_view_->setMainFrame(web_frame_);
}

// static
WebViewPlugin* WebViewPlugin::Create(content::RenderView* render_view,
                                     WebViewPlugin::Delegate* delegate,
                                     const WebPreferences& preferences,
                                     const std::string& html_data,
                                     const GURL& url) {
  DCHECK(url.is_valid()) << "Blink requires the WebView to have a valid URL.";
  WebViewPlugin* plugin = new WebViewPlugin(render_view, delegate, preferences);
  plugin->web_view()->mainFrame()->loadHTMLString(html_data, url);
  return plugin;
}

WebViewPlugin::~WebViewPlugin() {
  web_view_->close();
  web_frame_->close();
}

void WebViewPlugin::ReplayReceivedData(WebPlugin* plugin) {
  if (!response_.isNull()) {
    plugin->didReceiveResponse(response_);
    size_t total_bytes = 0;
    for (std::list<std::string>::iterator it = data_.begin(); it != data_.end();
         ++it) {
      plugin->didReceiveData(
          it->c_str(), base::checked_cast<int, size_t>(it->length()));
      total_bytes += it->length();
    }
    UMA_HISTOGRAM_MEMORY_KB(
        "PluginDocument.Memory",
        (base::checked_cast<int, size_t>(total_bytes / 1024)));
    UMA_HISTOGRAM_COUNTS(
        "PluginDocument.NumChunks",
        (base::checked_cast<int, size_t>(data_.size())));
  }
  // We need to transfer the |focused_| to new plugin after it loaded.
  if (focused_) {
    plugin->updateFocus(true, blink::WebFocusTypeNone);
  }
  if (finished_loading_) {
    plugin->didFinishLoading();
  }
  if (error_) {
    plugin->didFailLoading(*error_);
  }
}

void WebViewPlugin::RestoreTitleText() {
  if (container_)
    container_->element().setAttribute("title", old_title_);
}

WebPluginContainer* WebViewPlugin::container() const { return container_; }

bool WebViewPlugin::initialize(WebPluginContainer* container) {
  container_ = container;
  if (container_) {
    // We must call layout again here to ensure that the container is laid
    // out before we next try to paint it, which is a requirement of the
    // document life cycle in Blink. In most cases, needsLayout is set by
    // scheduleAnimation, but due to timers controlling widget update,
    // scheduleAnimation may be invoked before this initialize call (which
    // comes through the widget update process). It doesn't hurt to mark
    // for layout again, and it does help us in the race-condition situation.
    container_->setNeedsLayout();

    old_title_ = container_->element().getAttribute("title");

    // Propagate device scale and zoom level to inner webview.
    web_view_->setDeviceScaleFactor(container_->deviceScaleFactor());
    web_view_->setZoomLevel(
        blink::WebView::zoomFactorToZoomLevel(container_->pageZoomFactor()));
  }
  return true;
}

void WebViewPlugin::destroy() {
  if (delegate_) {
    delegate_->PluginDestroyed();
    delegate_ = NULL;
  }
  container_ = NULL;
  base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
}

v8::Local<v8::Object> WebViewPlugin::v8ScriptableObject(v8::Isolate* isolate) {
  if (!delegate_)
    return v8::Local<v8::Object>();

  return delegate_->GetV8ScriptableObject(isolate);
}

void WebViewPlugin::layoutIfNeeded() {
  web_view_->layout();
}

void WebViewPlugin::paint(WebCanvas* canvas, const WebRect& rect) {
  gfx::Rect paint_rect = gfx::IntersectRects(rect_, rect);
  if (paint_rect.IsEmpty())
    return;

  paint_rect.Offset(-rect_.x(), -rect_.y());

  canvas->save();
  canvas->translate(SkIntToScalar(rect_.x()), SkIntToScalar(rect_.y()));

  // Apply inverse device scale factor, as the outer webview has already
  // applied it, and the inner webview will apply it again.
  SkScalar inverse_scale =
      SkFloatToScalar(1.0 / container_->deviceScaleFactor());
  canvas->scale(inverse_scale, inverse_scale);

  web_view_->paint(canvas, paint_rect);

  canvas->restore();
}

// Coordinates are relative to the containing window.
void WebViewPlugin::updateGeometry(const WebRect& window_rect,
                                   const WebRect& clip_rect,
                                   const WebRect& unobscured_rect,
                                   const WebVector<WebRect>& cut_outs_rects,
                                   bool is_visible) {
  if (static_cast<gfx::Rect>(window_rect) != rect_) {
    rect_ = window_rect;
    WebSize newSize(window_rect.width, window_rect.height);
    web_view_->resize(newSize);
  }

  if (delegate_)
    delegate_->OnUnobscuredRectUpdate(gfx::Rect(unobscured_rect));
}

void WebViewPlugin::updateFocus(bool focused, blink::WebFocusType focus_type) {
  focused_ = focused;
}

bool WebViewPlugin::acceptsInputEvents() { return true; }

bool WebViewPlugin::handleInputEvent(const WebInputEvent& event,
                                     WebCursorInfo& cursor) {
  // For tap events, don't handle them. They will be converted to
  // mouse events later and passed to here.
  if (event.type == WebInputEvent::GestureTap)
    return false;

  // For LongPress events we return false, since otherwise the context menu will
  // be suppressed. https://crbug.com/482842
  if (event.type == WebInputEvent::GestureLongPress)
    return false;

  if (event.type == WebInputEvent::ContextMenu) {
    if (delegate_) {
      const WebMouseEvent& mouse_event =
          reinterpret_cast<const WebMouseEvent&>(event);
      delegate_->ShowContextMenu(mouse_event);
    }
    return true;
  }
  current_cursor_ = cursor;
  bool handled = web_view_->handleInputEvent(event);
  cursor = current_cursor_;

  return handled;
}

void WebViewPlugin::didReceiveResponse(const WebURLResponse& response) {
  DCHECK(response_.isNull());
  response_ = response;
}

void WebViewPlugin::didReceiveData(const char* data, int data_length) {
  data_.push_back(std::string(data, data_length));
}

void WebViewPlugin::didFinishLoading() {
  DCHECK(!finished_loading_);
  finished_loading_ = true;
}

void WebViewPlugin::didFailLoading(const WebURLError& error) {
  DCHECK(!error_.get());
  error_.reset(new WebURLError(error));
}

bool WebViewPlugin::acceptsLoadDrops() { return false; }

void WebViewPlugin::setToolTipText(const WebString& text,
                                   blink::WebTextDirection hint) {
  if (container_)
    container_->element().setAttribute("title", text);
}

void WebViewPlugin::startDragging(WebLocalFrame*,
                                  const WebDragData&,
                                  WebDragOperationsMask,
                                  const WebImage&,
                                  const WebPoint&) {
  // Immediately stop dragging.
  web_view_->dragSourceSystemDragEnded();
}

bool WebViewPlugin::allowsBrokenNullLayerTreeView() const {
  return true;
}

void WebViewPlugin::didInvalidateRect(const WebRect& rect) {
  if (container_)
    container_->invalidateRect(rect);
}

void WebViewPlugin::didUpdateLayoutSize(const WebSize&) {
  if (container_)
    container_->setNeedsLayout();
}

void WebViewPlugin::didChangeCursor(const WebCursorInfo& cursor) {
  current_cursor_ = cursor;
}

void WebViewPlugin::scheduleAnimation() {
  if (container_)
    container_->setNeedsLayout();
}

void WebViewPlugin::didClearWindowObject(WebLocalFrame* frame) {
  if (!delegate_)
    return;

  v8::Isolate* isolate = blink::mainThreadIsolate();
  v8::HandleScope handle_scope(isolate);
  v8::Local<v8::Context> context = frame->mainWorldScriptContext();
  DCHECK(!context.IsEmpty());

  v8::Context::Scope context_scope(context);
  v8::Local<v8::Object> global = context->Global();

  global->Set(gin::StringToV8(isolate, "plugin"),
              delegate_->GetV8Handle(isolate));
}

void WebViewPlugin::didReceiveResponse(WebLocalFrame* frame,
                                       unsigned identifier,
                                       const WebURLResponse& response) {
  WebFrameClient::didReceiveResponse(frame, identifier, response);
}

void WebViewPlugin::OnDestruct() {
  // By default RenderViewObservers are destroyed along with the RenderView.
  // WebViewPlugin has a custom destruction mechanism, so we disable this.
}

void WebViewPlugin::OnZoomLevelChanged() {
  web_view_->setZoomLevel(
      blink::WebView::zoomFactorToZoomLevel(container_->pageZoomFactor()));
}
<commit_msg>Plugin Power Saver: Fix WebViewPlugin crash caused by missing nullptr check.<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/plugins/renderer/webview_plugin.h"

#include "base/message_loop/message_loop.h"
#include "base/metrics/histogram_macros.h"
#include "base/numerics/safe_conversions.h"
#include "content/public/common/web_preferences.h"
#include "content/public/renderer/render_view.h"
#include "gin/converter.h"
#include "skia/ext/platform_canvas.h"
#include "third_party/WebKit/public/platform/WebSize.h"
#include "third_party/WebKit/public/platform/WebURL.h"
#include "third_party/WebKit/public/platform/WebURLRequest.h"
#include "third_party/WebKit/public/platform/WebURLResponse.h"
#include "third_party/WebKit/public/web/WebDocument.h"
#include "third_party/WebKit/public/web/WebElement.h"
#include "third_party/WebKit/public/web/WebInputEvent.h"
#include "third_party/WebKit/public/web/WebLocalFrame.h"
#include "third_party/WebKit/public/web/WebPluginContainer.h"
#include "third_party/WebKit/public/web/WebView.h"

using blink::WebCanvas;
using blink::WebCursorInfo;
using blink::WebDragData;
using blink::WebDragOperationsMask;
using blink::WebImage;
using blink::WebInputEvent;
using blink::WebLocalFrame;
using blink::WebMouseEvent;
using blink::WebPlugin;
using blink::WebPluginContainer;
using blink::WebPoint;
using blink::WebRect;
using blink::WebSize;
using blink::WebString;
using blink::WebURLError;
using blink::WebURLRequest;
using blink::WebURLResponse;
using blink::WebVector;
using blink::WebView;
using content::WebPreferences;

WebViewPlugin::WebViewPlugin(content::RenderView* render_view,
                             WebViewPlugin::Delegate* delegate,
                             const WebPreferences& preferences)
    : content::RenderViewObserver(render_view),
      delegate_(delegate),
      container_(NULL),
      web_view_(WebView::create(this)),
      finished_loading_(false),
      focused_(false) {
  // ApplyWebPreferences before making a WebLocalFrame so that the frame sees a
  // consistent view of our preferences.
  content::RenderView::ApplyWebPreferences(preferences, web_view_);
  web_frame_ = WebLocalFrame::create(blink::WebTreeScopeType::Document, this);
  web_view_->setMainFrame(web_frame_);
}

// static
WebViewPlugin* WebViewPlugin::Create(content::RenderView* render_view,
                                     WebViewPlugin::Delegate* delegate,
                                     const WebPreferences& preferences,
                                     const std::string& html_data,
                                     const GURL& url) {
  DCHECK(url.is_valid()) << "Blink requires the WebView to have a valid URL.";
  WebViewPlugin* plugin = new WebViewPlugin(render_view, delegate, preferences);
  plugin->web_view()->mainFrame()->loadHTMLString(html_data, url);
  return plugin;
}

WebViewPlugin::~WebViewPlugin() {
  web_view_->close();
  web_frame_->close();
}

void WebViewPlugin::ReplayReceivedData(WebPlugin* plugin) {
  if (!response_.isNull()) {
    plugin->didReceiveResponse(response_);
    size_t total_bytes = 0;
    for (std::list<std::string>::iterator it = data_.begin(); it != data_.end();
         ++it) {
      plugin->didReceiveData(
          it->c_str(), base::checked_cast<int, size_t>(it->length()));
      total_bytes += it->length();
    }
    UMA_HISTOGRAM_MEMORY_KB(
        "PluginDocument.Memory",
        (base::checked_cast<int, size_t>(total_bytes / 1024)));
    UMA_HISTOGRAM_COUNTS(
        "PluginDocument.NumChunks",
        (base::checked_cast<int, size_t>(data_.size())));
  }
  // We need to transfer the |focused_| to new plugin after it loaded.
  if (focused_) {
    plugin->updateFocus(true, blink::WebFocusTypeNone);
  }
  if (finished_loading_) {
    plugin->didFinishLoading();
  }
  if (error_) {
    plugin->didFailLoading(*error_);
  }
}

void WebViewPlugin::RestoreTitleText() {
  if (container_)
    container_->element().setAttribute("title", old_title_);
}

WebPluginContainer* WebViewPlugin::container() const { return container_; }

bool WebViewPlugin::initialize(WebPluginContainer* container) {
  container_ = container;
  if (container_) {
    // We must call layout again here to ensure that the container is laid
    // out before we next try to paint it, which is a requirement of the
    // document life cycle in Blink. In most cases, needsLayout is set by
    // scheduleAnimation, but due to timers controlling widget update,
    // scheduleAnimation may be invoked before this initialize call (which
    // comes through the widget update process). It doesn't hurt to mark
    // for layout again, and it does help us in the race-condition situation.
    container_->setNeedsLayout();

    old_title_ = container_->element().getAttribute("title");

    // Propagate device scale and zoom level to inner webview.
    web_view_->setDeviceScaleFactor(container_->deviceScaleFactor());
    web_view_->setZoomLevel(
        blink::WebView::zoomFactorToZoomLevel(container_->pageZoomFactor()));
  }
  return true;
}

void WebViewPlugin::destroy() {
  if (delegate_) {
    delegate_->PluginDestroyed();
    delegate_ = NULL;
  }
  container_ = NULL;
  base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
}

v8::Local<v8::Object> WebViewPlugin::v8ScriptableObject(v8::Isolate* isolate) {
  if (!delegate_)
    return v8::Local<v8::Object>();

  return delegate_->GetV8ScriptableObject(isolate);
}

void WebViewPlugin::layoutIfNeeded() {
  web_view_->layout();
}

void WebViewPlugin::paint(WebCanvas* canvas, const WebRect& rect) {
  gfx::Rect paint_rect = gfx::IntersectRects(rect_, rect);
  if (paint_rect.IsEmpty())
    return;

  paint_rect.Offset(-rect_.x(), -rect_.y());

  canvas->save();
  canvas->translate(SkIntToScalar(rect_.x()), SkIntToScalar(rect_.y()));

  // Apply inverse device scale factor, as the outer webview has already
  // applied it, and the inner webview will apply it again.
  SkScalar inverse_scale =
      SkFloatToScalar(1.0 / container_->deviceScaleFactor());
  canvas->scale(inverse_scale, inverse_scale);

  web_view_->paint(canvas, paint_rect);

  canvas->restore();
}

// Coordinates are relative to the containing window.
void WebViewPlugin::updateGeometry(const WebRect& window_rect,
                                   const WebRect& clip_rect,
                                   const WebRect& unobscured_rect,
                                   const WebVector<WebRect>& cut_outs_rects,
                                   bool is_visible) {
  if (static_cast<gfx::Rect>(window_rect) != rect_) {
    rect_ = window_rect;
    WebSize newSize(window_rect.width, window_rect.height);
    web_view_->resize(newSize);
  }

  if (delegate_)
    delegate_->OnUnobscuredRectUpdate(gfx::Rect(unobscured_rect));
}

void WebViewPlugin::updateFocus(bool focused, blink::WebFocusType focus_type) {
  focused_ = focused;
}

bool WebViewPlugin::acceptsInputEvents() { return true; }

bool WebViewPlugin::handleInputEvent(const WebInputEvent& event,
                                     WebCursorInfo& cursor) {
  // For tap events, don't handle them. They will be converted to
  // mouse events later and passed to here.
  if (event.type == WebInputEvent::GestureTap)
    return false;

  // For LongPress events we return false, since otherwise the context menu will
  // be suppressed. https://crbug.com/482842
  if (event.type == WebInputEvent::GestureLongPress)
    return false;

  if (event.type == WebInputEvent::ContextMenu) {
    if (delegate_) {
      const WebMouseEvent& mouse_event =
          reinterpret_cast<const WebMouseEvent&>(event);
      delegate_->ShowContextMenu(mouse_event);
    }
    return true;
  }
  current_cursor_ = cursor;
  bool handled = web_view_->handleInputEvent(event);
  cursor = current_cursor_;

  return handled;
}

void WebViewPlugin::didReceiveResponse(const WebURLResponse& response) {
  DCHECK(response_.isNull());
  response_ = response;
}

void WebViewPlugin::didReceiveData(const char* data, int data_length) {
  data_.push_back(std::string(data, data_length));
}

void WebViewPlugin::didFinishLoading() {
  DCHECK(!finished_loading_);
  finished_loading_ = true;
}

void WebViewPlugin::didFailLoading(const WebURLError& error) {
  DCHECK(!error_.get());
  error_.reset(new WebURLError(error));
}

bool WebViewPlugin::acceptsLoadDrops() { return false; }

void WebViewPlugin::setToolTipText(const WebString& text,
                                   blink::WebTextDirection hint) {
  if (container_)
    container_->element().setAttribute("title", text);
}

void WebViewPlugin::startDragging(WebLocalFrame*,
                                  const WebDragData&,
                                  WebDragOperationsMask,
                                  const WebImage&,
                                  const WebPoint&) {
  // Immediately stop dragging.
  web_view_->dragSourceSystemDragEnded();
}

bool WebViewPlugin::allowsBrokenNullLayerTreeView() const {
  return true;
}

void WebViewPlugin::didInvalidateRect(const WebRect& rect) {
  if (container_)
    container_->invalidateRect(rect);
}

void WebViewPlugin::didUpdateLayoutSize(const WebSize&) {
  if (container_)
    container_->setNeedsLayout();
}

void WebViewPlugin::didChangeCursor(const WebCursorInfo& cursor) {
  current_cursor_ = cursor;
}

void WebViewPlugin::scheduleAnimation() {
  if (container_)
    container_->setNeedsLayout();
}

void WebViewPlugin::didClearWindowObject(WebLocalFrame* frame) {
  if (!delegate_)
    return;

  v8::Isolate* isolate = blink::mainThreadIsolate();
  v8::HandleScope handle_scope(isolate);
  v8::Local<v8::Context> context = frame->mainWorldScriptContext();
  DCHECK(!context.IsEmpty());

  v8::Context::Scope context_scope(context);
  v8::Local<v8::Object> global = context->Global();

  global->Set(gin::StringToV8(isolate, "plugin"),
              delegate_->GetV8Handle(isolate));
}

void WebViewPlugin::didReceiveResponse(WebLocalFrame* frame,
                                       unsigned identifier,
                                       const WebURLResponse& response) {
  WebFrameClient::didReceiveResponse(frame, identifier, response);
}

void WebViewPlugin::OnDestruct() {
  // By default RenderViewObservers are destroyed along with the RenderView.
  // WebViewPlugin has a custom destruction mechanism, so we disable this.
}

void WebViewPlugin::OnZoomLevelChanged() {
  if (container_) {
    web_view_->setZoomLevel(
      blink::WebView::zoomFactorToZoomLevel(container_->pageZoomFactor()));
  }
}
<|endoftext|>


<commit_before>// $Id$

AliEmcalEsdTpcTrackTask* AddTaskEmcalEsdTpcTrack(
  const char *name       = "TpcSpdVertexConstrainedTracks"
)
{
  // Get the pointer to the existing analysis manager via the static access method.
  //==============================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr)
  {
    ::Error("AddTaskEmcalEsdTpcTrack", "No analysis manager to connect to.");
    return NULL;
  }

  // Check the analysis type using the event handlers connected to the analysis manager.
  //==============================================================================
  if (!mgr->GetInputEventHandler())
  {
    ::Error("AddTaskEmcalEsdTpcTrack", "This task requires an input event handler");
    return NULL;
  }

  //-------------------------------------------------------
  // Init the task and do settings
  //-------------------------------------------------------

  /* hybrid track cuts*/
  AliESDtrackCuts *cutsp = new AliESDtrackCuts;
  // TPC
  TFormula *f1NClustersTPCLinearPtDep = new TFormula("f1NClustersTPCLinearPtDep","70.+30./20.*x");
  cutsp->SetMinNClustersTPCPtDep(f1NClustersTPCLinearPtDep,20.);
  cutsp->SetMinNClustersTPC(70);
  cutsp->SetMaxChi2PerClusterTPC(4);
  cutsp->SetRequireTPCStandAlone(kTRUE); //cut on NClustersTPC and chi2TPC Iter1
  cutsp->SetAcceptKinkDaughters(kFALSE);
  cutsp->SetRequireTPCRefit(kTRUE);
  cutsp->SetMaxFractionSharedTPCClusters(0.4);
  // ITS
  cutsp->SetRequireITSRefit(kTRUE);
  //accept secondaries
  cutsp->SetMaxDCAToVertexXY(2.4);
  cutsp->SetMaxDCAToVertexZ(3.2);
  cutsp->SetDCAToVertex2D(kTRUE);
  //reject fakes
  cutsp->SetMaxChi2PerClusterITS(36);
  cutsp->SetMaxChi2TPCConstrainedGlobal(36);
  cutsp->SetRequireSigmaToVertex(kFALSE);
  cutsp->SetEtaRange(-0.9,0.9);
  cutsp->SetPtRange(0.15, 1E+15);
  //tag = "Global tracks jet analysis with ITSrefit and NclsIter1=PtDep, noSPD requirement, no upper pt cut, golden chi2";
  hybsp = new AliESDtrackCuts(*cutsp);
  cutsp->SetClusterRequirementITS(AliESDtrackCuts::kSPD, AliESDtrackCuts::kAny);
  //tag += " + additonal: SPD any requirement";
  hybsp->SetRequireITSRefit(kFALSE);
  //tag += " + additional: ITSrefit=kFALSE";

  AliEmcalEsdTpcTrackTask *eTask = new AliEmcalEsdTpcTrackTask();
  eTask->SetTrackCuts(cutsp);
  eTask->SetHybridTrackCuts(hybsp);
  eTask->SetTracksName(name);

  cout << " *** TPC track to SPD vertex task configured *** " << endl;

  //-------------------------------------------------------
  // Final settings, pass to manager and set the containers
  //-------------------------------------------------------
  mgr->AddTask(eTask);

  // Create containers for input/output
  AliAnalysisDataContainer *cinput1  = mgr->GetCommonInputContainer()  ;
  mgr->ConnectInput  (eTask, 0,  cinput1 );

  return eTask;
}
<commit_msg>2011 track cuts<commit_after>// $Id$

AliEmcalEsdTpcTrackTask* AddTaskEmcalEsdTpcTrack(
  const char *name       = "TpcSpdVertexConstrainedTracks"
)
{
  // Get the pointer to the existing analysis manager via the static access method.
  //==============================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr)
  {
    ::Error("AddTaskEmcalEsdTpcTrack", "No analysis manager to connect to.");
    return NULL;
  }

  // Check the analysis type using the event handlers connected to the analysis manager.
  //==============================================================================
  if (!mgr->GetInputEventHandler())
  {
    ::Error("AddTaskEmcalEsdTpcTrack", "This task requires an input event handler");
    return NULL;
  }

  //-------------------------------------------------------
  // Init the task and do settings
  //-------------------------------------------------------

  gROOT->LoadMacro("$ALICE_ROOT/PWGJE/macros/CreateTrackCutsPWGJE.C");

  /* hybrid track cuts*/
  AliESDtrackCuts *cutsp = CreateTrackCutsPWGJE(10001007);       //1000 adds SPD any requirement
  AliESDtrackCuts *hybsp = CreateTrackCutsPWGJE(10041007);       //1004 removes ITSrefit requirement from standard set
  hybsp->SetClusterRequirementITS(AliESDtrackCuts::kSPD, AliESDtrackCuts::kOff);

  AliEmcalEsdTpcTrackTask *eTask = new AliEmcalEsdTpcTrackTask();
  eTask->SetTrackCuts(cutsp);
  eTask->SetHybridTrackCuts(hybsp);

  eTask->SetTracksName(name);

  cout << " *** Hybrid track selector task configured *** " << endl;

  //-------------------------------------------------------
  // Final settings, pass to manager and set the containers
  //-------------------------------------------------------
  mgr->AddTask(eTask);

  // Create containers for input/output
  AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();
  mgr->ConnectInput(eTask, 0, cinput1);

  return eTask;
}
<|endoftext|>