<commit_before>//=============================================================================================================
/**
* @file     settingscontroller.cpp
* @author   Juan Garcia-Prieto <Juan.GarciaPrieto@uth.tmc.edu> <juangpc@gmail.com>;
*           Wayne Mead <wayne.mead@uth.tmc.edu> <wayne.isk@gmail.com>;
*           Lorenz Esch <Lorenz.Esch@tu-ilmenau.de>;
*           Matti Hamalainen <msh@nmr.mgh.harvard.edu>;
*           John C. Mosher <John.C.Mosher@uth.tmc.edu> <jcmosher@gmail.com>;
* @version  1.0
* @date     September, 2019
*
* @section  LICENSE
*
* Copyright (C) 2019, Juan Garcia-Prieto and Matti Hamalainen. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that
* the following conditions are met:
*     * Redistributions of source code must retain the above copyright notice, this list of conditions and the
*       following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
*       the following disclaimer in the documentation and/or other materials provided with the distribution.
*     * Neither the name of MNE-CPP authors nor the names of its contributors may be used
*       to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
* @brief    SettingsController class definition.
*
*/

//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "settingscontroller.h"
#include "fiffanonymizer.h"

//*************************************************************************************************************
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================

//*************************************************************************************************************
//=============================================================================================================
// Eigen INCLUDES
//=============================================================================================================

//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace MNEANONYMIZE;

//*************************************************************************************************************
//=============================================================================================================
// DEFINE GLOBAL METHODS
//=============================================================================================================

//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================

SettingsController::SettingsController(const QStringList &arguments)
: m_bMultipleInFiles(false)
{
    initParser();
    parseInputs(arguments);
    execute();
}

//*************************************************************************************************************

SettingsController::~SettingsController()
{
    m_pAppList.clear();
}

//*************************************************************************************************************

void SettingsController::initParser()
{

    m_parser.setApplicationDescription(QCoreApplication::translate("main",
                                                                   m_anonymizer.description.toUtf8()));
    m_parser.addHelpOption();
    m_parser.addVersionOption();

    QCommandLineOption inFileOpt("in",QCoreApplication::translate("main","File to anonymize. Wildcards are allowed and several --in <infile> statements can be present."),
                                 QCoreApplication::translate("main","infile"));
    m_parser.addOption(inFileOpt);

    QCommandLineOption outFileOpt("out",QCoreApplication::translate("main","Output file <outfile>. Only allowed when anonymizing one single file."),
                                  QCoreApplication::translate("main","outfile"));
    m_parser.addOption(outFileOpt);

    QCommandLineOption verboseOpt("verbose",QCoreApplication::translate("main","Prints out more information."));
    m_parser.addOption(verboseOpt);

    QCommandLineOption quietOpt("quiet",QCoreApplication::translate("main","Show no output."));
    m_parser.addOption(quietOpt);

    QCommandLineOption deleteInFileOpt("delete_input_file_after",
                                       QCoreApplication::translate("main","Delete input fiff file after anonymization."));
    m_parser.addOption(deleteInFileOpt);

    QCommandLineOption deleteInFileConfirmOpt("avoid_delete_confirmation",
                                              QCoreApplication::translate("main","Avoid confirming the deletion of the input fiff file."));
    m_parser.addOption(deleteInFileConfirmOpt);

    QCommandLineOption bruteOpt("brute",QCoreApplication::translate("main","Anonymize weight, height XXX if present in the input fiff file."));
    m_parser.addOption(bruteOpt);

    QCommandLineOption measDateOpt("measurement_date",
                                   QCoreApplication::translate("main","Specify the measurement date. Only when anonymizing a single file. Format: YYYMMDD "),
                                   QCoreApplication::translate("main","days"));
    m_parser.addOption(measDateOpt);

    QCommandLineOption measDateOffsetOpt("measurement_date_offset",
                                         QCoreApplication::translate("main","Specify number of days to subtract to the measurement <date>. Only allowed when anonymizing a single file."),
                                         QCoreApplication::translate("main","date"));
    m_parser.addOption(measDateOffsetOpt);

    QCommandLineOption birthdayOpt("subject_birthday",
                                   QCoreApplication::translate("main","Specify the subject's birthday <date>. Only allowed when anonymizing a single file. Format: YYYMMDD "),
                                   QCoreApplication::translate("main","date"));
    m_parser.addOption(birthdayOpt);

    QCommandLineOption birthdayOffsetOpt("subject_birthday_offset",
                                         QCoreApplication::translate("main","Specify number of <days> to subtract to the subject's birthday. Only allowed when anonymizing a single file. "),
                                         QCoreApplication::translate("main","days"));
    m_parser.addOption(birthdayOffsetOpt);

    QCommandLineOption SubjectIdOpt("his",QCoreApplication::translate("main","Specify the Subject's Id# within the Hospital system. Only allowed when anonymizing a single file. "),
                                          QCoreApplication::translate("main","id#"));
    m_parser.addOption(SubjectIdOpt);
}

//*************************************************************************************************************

void SettingsController::parseInputs(const QStringList& arguments)
{
    m_parser.process(arguments);

    parseInputAndOutputFiles();

    if(m_parser.isSet("verbose")) {
        m_anonymizer.setVerboseMode(true);
    }

    if(m_parser.isSet("brute")) {
        m_anonymizer.setBruteMode(true);
    }

    if(m_parser.isSet("quiet")) {
        if(m_anonymizer.getVerboseMode()) {
            m_anonymizer.setVerboseMode(false);
        }
        m_anonymizer.setQuietMode(true);
    }

    if(m_parser.isSet("delete_input_file_after")) {
        m_anonymizer.setDeleteInputFileAfter(true);
    }

    if(m_parser.isSet("avoid_delete_confirmation")) {
        m_anonymizer.setDeleteInputFileAfterConfirmation(false);
    }

    if(m_parser.isSet("measurement_date")) {
        if(m_bMultipleInFiles) {
            qDebug() << "Error. Multiple Input files. You cannot specify the option \"measurement_date\".";
            m_parser.showHelp();
        }

        QString d(m_parser.value("measurement_date"));
        m_anonymizer.setMeasurementDay(d);
    }

    if(m_parser.isSet("measurement_date_offset")) {
        if(m_bMultipleInFiles) {
            qDebug() << "Error. Multiple Input files. You cannot specify the option \"measurement_date_offset\".";
            m_parser.showHelp();
        }

        QString doffset(m_parser.value("measurement_date_offset"));
        m_anonymizer.setMeasurementDayOffset(doffset.toInt());
    }

    if(m_parser.isSet("subject_birthday")) {
        if(m_bMultipleInFiles) {
            qDebug() << "Error. Multiple Input files. You cannot specify the option \"subject_birthday\".";
            m_parser.showHelp();
        }

        QString birthday(m_parser.value("subject_birthday"));
        m_anonymizer.setSubjectBirthday(birthday);
    }

    if(m_parser.isSet("subject_birthday_offset")) {
        if(m_bMultipleInFiles) {
            qDebug() << "Error. Multiple Input files. You cannot specify the option \"subject_birthday_offset\".";
            m_parser.showHelp();
        }
        QString bdoffset(m_parser.value("subject_birthday_offset"));
        m_anonymizer.setSubjectBirthdayOffset(bdoffset.toInt());
    }

    if(m_parser.isSet("his")) {
        if(m_bMultipleInFiles) {
            qDebug() << "Error. Multiple Input files. You cannot specify the optio \"his\".";
            m_parser.showHelp();
        }

        m_anonymizer.setSubjectHisId(m_parser.value("his").toInt());
    }
}

//*************************************************************************************************************

void SettingsController::parseInputAndOutputFiles()
{
    if(m_parser.isSet("in")) {
        QStringList inFilesAux(m_parser.values("in"));

        for(QString f: inFilesAux) {
            QFileInfo inFileInfo(QDir::toNativeSeparators(f));
            inFileInfo.makeAbsolute();

            if(inFileInfo.isDir()) {
                qDebug() << "Error. " << f << " is a folder.";
            }

            QStringList filter;
            filter << inFileInfo.fileName();
            QDirIterator it(inFileInfo.absoluteDir().absolutePath(),filter,QDir::AllEntries | QDir::NoSymLinks | QDir::NoDotAndDotDot);

            while(it.hasNext()) {
                QFileInfo fi(it.next());

                if(fi.isFile() && fi.isReadable()) {
                    m_SLInFiles.append(fi.absoluteFilePath());
                }
            }
        }
    }

    if(m_SLInFiles.size() == 0) {
        qDebug() << "Error. No valid input files.";
        m_parser.showHelp();
    } else if(m_SLInFiles.size() == 1) {
        m_bMultipleInFiles = false;
    } else {
        m_bMultipleInFiles = true;
    }

    if(m_bMultipleInFiles) {
        if(m_parser.isSet("out")) {
            qDebug() << "Warning. Multiple input files selected. Output filename option will be ignored.";
        }

        for(QString fi:m_SLInFiles) {
            QFileInfo fInfo(fi);
            QString fout = QDir(fInfo.absolutePath()).filePath(
                        fInfo.baseName() + "_anonymized." + fInfo.completeSuffix());
            m_SLOutFiles.append(fout);
        }
    } else {
        QString fileOutName;

        if(m_parser.isSet("out")) {
            QFileInfo fInfo(m_parser.value("out"));
            fInfo.makeAbsolute();
            fileOutName = fInfo.absoluteFilePath();
        } else {
            QFileInfo fInfo(m_SLInFiles.first());
            fileOutName = QDir(fInfo.absolutePath()).filePath(
                        fInfo.baseName() + "_anonymized." + fInfo.completeSuffix());
        }

        m_SLOutFiles.append(fileOutName);
    }

    if(m_SLInFiles.size() != m_SLOutFiles.size()) {
        qDebug() << "Error. something went wrong while parsing the input files.";
    }
}

//*************************************************************************************************************

void SettingsController::generateAnonymizerInstances()
{
    if(m_SLInFiles.isEmpty() || m_SLOutFiles.isEmpty()) {
        qDebug() << "SettingsController::generateAnonymizerInstances - No input and/or output file names specified.";
        return;
    }

    if(m_bMultipleInFiles) {
        for(int i=0; i< m_SLInFiles.size(); ++i) {
            QSharedPointer<FiffAnonymizer> pAppAux(new FiffAnonymizer(m_anonymizer));
            pAppAux->setFileIn(m_SLInFiles.at(i));
            pAppAux->setFileOut(m_SLOutFiles.at(i));
            //m_pAppList.append(QSharedPointer<FiffAnonymizer>(pAppAux));
            //note that QList will copy & append.
            m_pAppList.append(pAppAux);
        }
    } else {
        m_anonymizer.setFileIn(m_SLInFiles.first());
        m_anonymizer.setFileOut(m_SLOutFiles.first());
    }
}

//*************************************************************************************************************

void SettingsController::execute()
{
    generateAnonymizerInstances();
    if(m_bMultipleInFiles) {
        for(int th_i=0; th_i<m_pAppList.size(); ++th_i) {
            QSharedPointer<QFuture<void> > promise( new QFuture<void>);
            FiffAnonymizer localApp(*m_pAppList.at(th_i));
            *promise = QtConcurrent::run(localApp,&FiffAnonymizer::anonymizeFile);
            promisesList.append(promise);
        }

        for(int p_i=0;p_i<promisesList.size();++p_i) {
            promisesList.at(p_i)->waitForFinished();
        }
    } else {
        m_anonymizer.anonymizeFile();
    }
}
<commit_msg>[ci skip] Parse SubjectHisId input and call setSubjectHisId with string<commit_after>//=============================================================================================================
/**
* @file     settingscontroller.cpp
* @author   Juan Garcia-Prieto <Juan.GarciaPrieto@uth.tmc.edu> <juangpc@gmail.com>;
*           Wayne Mead <wayne.mead@uth.tmc.edu> <wayne.isk@gmail.com>;
*           Lorenz Esch <Lorenz.Esch@tu-ilmenau.de>;
*           Matti Hamalainen <msh@nmr.mgh.harvard.edu>;
*           John C. Mosher <John.C.Mosher@uth.tmc.edu> <jcmosher@gmail.com>;
* @version  1.0
* @date     September, 2019
*
* @section  LICENSE
*
* Copyright (C) 2019, Juan Garcia-Prieto and Matti Hamalainen. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that
* the following conditions are met:
*     * Redistributions of source code must retain the above copyright notice, this list of conditions and the
*       following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
*       the following disclaimer in the documentation and/or other materials provided with the distribution.
*     * Neither the name of MNE-CPP authors nor the names of its contributors may be used
*       to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
* @brief    SettingsController class definition.
*
*/

//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "settingscontroller.h"
#include "fiffanonymizer.h"

//*************************************************************************************************************
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================

//*************************************************************************************************************
//=============================================================================================================
// Eigen INCLUDES
//=============================================================================================================

//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace MNEANONYMIZE;

//*************************************************************************************************************
//=============================================================================================================
// DEFINE GLOBAL METHODS
//=============================================================================================================

//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================

SettingsController::SettingsController(const QStringList &arguments)
: m_bMultipleInFiles(false)
{
    initParser();
    parseInputs(arguments);
    execute();
}

//*************************************************************************************************************

SettingsController::~SettingsController()
{
    m_pAppList.clear();
}

//*************************************************************************************************************

void SettingsController::initParser()
{

    m_parser.setApplicationDescription(QCoreApplication::translate("main",
                                                                   m_anonymizer.description.toUtf8()));
    m_parser.addHelpOption();
    m_parser.addVersionOption();

    QCommandLineOption inFileOpt("in",QCoreApplication::translate("main","File to anonymize. Wildcards are allowed and several --in <infile> statements can be present."),
                                 QCoreApplication::translate("main","infile"));
    m_parser.addOption(inFileOpt);

    QCommandLineOption outFileOpt("out",QCoreApplication::translate("main","Output file <outfile>. Only allowed when anonymizing one single file."),
                                  QCoreApplication::translate("main","outfile"));
    m_parser.addOption(outFileOpt);

    QCommandLineOption verboseOpt("verbose",QCoreApplication::translate("main","Prints out more information."));
    m_parser.addOption(verboseOpt);

    QCommandLineOption quietOpt("quiet",QCoreApplication::translate("main","Show no output."));
    m_parser.addOption(quietOpt);

    QCommandLineOption deleteInFileOpt("delete_input_file_after",
                                       QCoreApplication::translate("main","Delete input fiff file after anonymization."));
    m_parser.addOption(deleteInFileOpt);

    QCommandLineOption deleteInFileConfirmOpt("avoid_delete_confirmation",
                                              QCoreApplication::translate("main","Avoid confirming the deletion of the input fiff file."));
    m_parser.addOption(deleteInFileConfirmOpt);

    QCommandLineOption bruteOpt("brute",QCoreApplication::translate("main","Anonymize weight, height XXX if present in the input fiff file."));
    m_parser.addOption(bruteOpt);

    QCommandLineOption measDateOpt("measurement_date",
                                   QCoreApplication::translate("main","Specify the measurement date. Only when anonymizing a single file. Format: YYYMMDD "),
                                   QCoreApplication::translate("main","days"));
    m_parser.addOption(measDateOpt);

    QCommandLineOption measDateOffsetOpt("measurement_date_offset",
                                         QCoreApplication::translate("main","Specify number of days to subtract to the measurement <date>. Only allowed when anonymizing a single file."),
                                         QCoreApplication::translate("main","date"));
    m_parser.addOption(measDateOffsetOpt);

    QCommandLineOption birthdayOpt("subject_birthday",
                                   QCoreApplication::translate("main","Specify the subject's birthday <date>. Only allowed when anonymizing a single file. Format: YYYMMDD "),
                                   QCoreApplication::translate("main","date"));
    m_parser.addOption(birthdayOpt);

    QCommandLineOption birthdayOffsetOpt("subject_birthday_offset",
                                         QCoreApplication::translate("main","Specify number of <days> to subtract to the subject's birthday. Only allowed when anonymizing a single file. "),
                                         QCoreApplication::translate("main","days"));
    m_parser.addOption(birthdayOffsetOpt);

    QCommandLineOption SubjectIdOpt("his",QCoreApplication::translate("main","Specify the Subject's Id# within the Hospital system. Only allowed when anonymizing a single file. "),
                                          QCoreApplication::translate("main","id#"));
    m_parser.addOption(SubjectIdOpt);
}

//*************************************************************************************************************

void SettingsController::parseInputs(const QStringList& arguments)
{
    m_parser.process(arguments);

    parseInputAndOutputFiles();

    if(m_parser.isSet("verbose")) {
        m_anonymizer.setVerboseMode(true);
    }

    if(m_parser.isSet("brute")) {
        m_anonymizer.setBruteMode(true);
    }

    if(m_parser.isSet("quiet")) {
        if(m_anonymizer.getVerboseMode()) {
            m_anonymizer.setVerboseMode(false);
        }
        m_anonymizer.setQuietMode(true);
    }

    if(m_parser.isSet("delete_input_file_after")) {
        m_anonymizer.setDeleteInputFileAfter(true);
    }

    if(m_parser.isSet("avoid_delete_confirmation")) {
        m_anonymizer.setDeleteInputFileAfterConfirmation(false);
    }

    if(m_parser.isSet("measurement_date")) {
        if(m_bMultipleInFiles) {
            qDebug() << "Error. Multiple Input files. You cannot specify the option \"measurement_date\".";
            m_parser.showHelp();
        }

        QString d(m_parser.value("measurement_date"));
        m_anonymizer.setMeasurementDay(d);
    }

    if(m_parser.isSet("measurement_date_offset")) {
        if(m_bMultipleInFiles) {
            qDebug() << "Error. Multiple Input files. You cannot specify the option \"measurement_date_offset\".";
            m_parser.showHelp();
        }

        QString doffset(m_parser.value("measurement_date_offset"));
        m_anonymizer.setMeasurementDayOffset(doffset.toInt());
    }

    if(m_parser.isSet("subject_birthday")) {
        if(m_bMultipleInFiles) {
            qDebug() << "Error. Multiple Input files. You cannot specify the option \"subject_birthday\".";
            m_parser.showHelp();
        }

        QString birthday(m_parser.value("subject_birthday"));
        m_anonymizer.setSubjectBirthday(birthday);
    }

    if(m_parser.isSet("subject_birthday_offset")) {
        if(m_bMultipleInFiles) {
            qDebug() << "Error. Multiple Input files. You cannot specify the option \"subject_birthday_offset\".";
            m_parser.showHelp();
        }
        QString bdoffset(m_parser.value("subject_birthday_offset"));
        m_anonymizer.setSubjectBirthdayOffset(bdoffset.toInt());
    }

    if(m_parser.isSet("his")) {
        if(m_bMultipleInFiles) {
            qDebug() << "Error. Multiple Input files. You cannot specify the optio \"his\".";
            m_parser.showHelp();
        }

        m_anonymizer.setSubjectHisId(m_parser.value("his"));
    }
}

//*************************************************************************************************************

void SettingsController::parseInputAndOutputFiles()
{
    if(m_parser.isSet("in")) {
        QStringList inFilesAux(m_parser.values("in"));

        for(QString f: inFilesAux) {
            QFileInfo inFileInfo(QDir::toNativeSeparators(f));
            inFileInfo.makeAbsolute();

            if(inFileInfo.isDir()) {
                qDebug() << "Error. " << f << " is a folder.";
            }

            QStringList filter;
            filter << inFileInfo.fileName();
            QDirIterator it(inFileInfo.absoluteDir().absolutePath(),filter,QDir::AllEntries | QDir::NoSymLinks | QDir::NoDotAndDotDot);

            while(it.hasNext()) {
                QFileInfo fi(it.next());

                if(fi.isFile() && fi.isReadable()) {
                    m_SLInFiles.append(fi.absoluteFilePath());
                }
            }
        }
    }

    if(m_SLInFiles.size() == 0) {
        qDebug() << "Error. No valid input files.";
        m_parser.showHelp();
    } else if(m_SLInFiles.size() == 1) {
        m_bMultipleInFiles = false;
    } else {
        m_bMultipleInFiles = true;
    }

    if(m_bMultipleInFiles) {
        if(m_parser.isSet("out")) {
            qDebug() << "Warning. Multiple input files selected. Output filename option will be ignored.";
        }

        for(QString fi:m_SLInFiles) {
            QFileInfo fInfo(fi);
            QString fout = QDir(fInfo.absolutePath()).filePath(
                        fInfo.baseName() + "_anonymized." + fInfo.completeSuffix());
            m_SLOutFiles.append(fout);
        }
    } else {
        QString fileOutName;

        if(m_parser.isSet("out")) {
            QFileInfo fInfo(m_parser.value("out"));
            fInfo.makeAbsolute();
            fileOutName = fInfo.absoluteFilePath();
        } else {
            QFileInfo fInfo(m_SLInFiles.first());
            fileOutName = QDir(fInfo.absolutePath()).filePath(
                        fInfo.baseName() + "_anonymized." + fInfo.completeSuffix());
        }

        m_SLOutFiles.append(fileOutName);
    }

    if(m_SLInFiles.size() != m_SLOutFiles.size()) {
        qDebug() << "Error. something went wrong while parsing the input files.";
    }
}

//*************************************************************************************************************

void SettingsController::generateAnonymizerInstances()
{
    if(m_SLInFiles.isEmpty() || m_SLOutFiles.isEmpty()) {
        qDebug() << "SettingsController::generateAnonymizerInstances - No input and/or output file names specified.";
        return;
    }

    if(m_bMultipleInFiles) {
        for(int i=0; i< m_SLInFiles.size(); ++i) {
            QSharedPointer<FiffAnonymizer> pAppAux(new FiffAnonymizer(m_anonymizer));
            pAppAux->setFileIn(m_SLInFiles.at(i));
            pAppAux->setFileOut(m_SLOutFiles.at(i));
            //m_pAppList.append(QSharedPointer<FiffAnonymizer>(pAppAux));
            //note that QList will copy & append.
            m_pAppList.append(pAppAux);
        }
    } else {
        m_anonymizer.setFileIn(m_SLInFiles.first());
        m_anonymizer.setFileOut(m_SLOutFiles.first());
    }
}

//*************************************************************************************************************

void SettingsController::execute()
{
    generateAnonymizerInstances();
    if(m_bMultipleInFiles) {
        for(int th_i=0; th_i<m_pAppList.size(); ++th_i) {
            QSharedPointer<QFuture<void> > promise( new QFuture<void>);
            FiffAnonymizer localApp(*m_pAppList.at(th_i));
            *promise = QtConcurrent::run(localApp,&FiffAnonymizer::anonymizeFile);
            promisesList.append(promise);
        }

        for(int p_i=0;p_i<promisesList.size();++p_i) {
            promisesList.at(p_i)->waitForFinished();
        }
    } else {
        m_anonymizer.anonymizeFile();
    }
}
<|endoftext|>


<commit_before>/*******************************************************************************
*     ALMA - Atacama Large Millimiter Array
*    (c) European Southern Observatory, 2002
*    Copyright by ESO (in the framework of the ALMA collaboration)
*    and Cosylab 2002, All rights reserved
*
*    This library is free software; you can redistribute it and/or
*    modify it under the terms of the GNU Lesser General Public
*    License as published by the Free Software Foundation; either
*    version 2.1 of the License, or (at your option) any later version.
*
*    This library is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
*    Lesser General Public License for more details.
*
*    You should have received a copy of the GNU Lesser General Public
*    License along with this library; if not, write to the Free Software
*    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
*
* "@(#) $Id: acsContainerDaemonImpl.cpp,v 1.5 2007/10/31 13:59:33 ntroncos Exp $"
*
* who       when        what
* --------  ---------   ----------------------------------------------
* msekoran  2006-06-21  created
*/

#include "acsContainerDaemonImpl.h"
#include <tao/IORTable/IORTable.h>
#include <acserr.h>
#include <acsdaemonErrType.h>
#include <ACSErrTypeCommon.h>

/*****************************************************************/

ACSContainerDaemonImpl::ACSContainerDaemonImpl (LoggingProxy &logProxy) :
    m_isInitialized(false),
    m_logProxy(logProxy)
{
    // noop here

    m_isInitialized = true;
}

ACSContainerDaemonImpl::~ACSContainerDaemonImpl (void)
{
}

int
ACSContainerDaemonImpl::init_ORB  (int& argc, char *argv [])
{
    m_orb = CORBA::ORB_init(argc, argv, "TAO");

    try
	{
	// get a reference to the RootPOA
	CORBA::Object_var obj = m_orb->resolve_initial_references("RootPOA");
	PortableServer::POA_var root_poa = PortableServer::POA::_narrow(obj.in());
	PortableServer::POAManager_var poa_manager = root_poa->the_POAManager();

	// create policies
	CORBA::PolicyList policy_list;
	policy_list.length(5);
	policy_list[0] = root_poa->create_request_processing_policy(PortableServer::USE_DEFAULT_SERVANT);
	policy_list[1] =  root_poa->create_id_uniqueness_policy(PortableServer::MULTIPLE_ID);
	policy_list[2] = root_poa->create_id_assignment_policy(PortableServer::USER_ID);
	policy_list[3] = root_poa->create_servant_retention_policy(PortableServer::NON_RETAIN);
	policy_list[4] =  root_poa->create_lifespan_policy(PortableServer::PERSISTENT);

	// create a ACSDaemon POA with policies
	PortableServer::POA_var poa = root_poa->create_POA("ACSContainerDaemon", poa_manager.in(), policy_list);

	// destroy policies
	for (CORBA::ULong i = 0; i < policy_list.length(); ++i)
	    {
	    CORBA::Policy_ptr policy = policy_list[i];
	    policy->destroy();
	    }

	// set as default servant
	poa->set_servant(this);

	// create reference
	PortableServer::ObjectId_var oid = PortableServer::string_to_ObjectId("ACSContainerDaemon");
	obj = poa->create_reference_with_id (oid.in(), _interface_repository_id());
	m_ior = m_orb->object_to_string(obj.in());

	// bind to IOR table
      	CORBA::Object_var table_object = m_orb->resolve_initial_references("IORTable");
	IORTable::Table_var adapter = IORTable::Table::_narrow(table_object.in());

	if (CORBA::is_nil(adapter.in()))
	    {
	    ACS_SHORT_LOG ((LM_ERROR, "Nil IORTable"));
	    return -1;
	    }
	else
	    {
	    adapter->bind("ACSContainerDaemon", m_ior.in());
	    }

	// activate POA
	poa_manager->activate();

	ACS_SHORT_LOG((LM_INFO, "ACS Container Daemon is waiting for incoming requests."));

	}
    catch( CORBA::Exception &ex )
	{
	ACE_PRINT_EXCEPTION (ex, "EXCEPTION CAUGHT");
	return -1;
	}

    return 0;
}

int
ACSContainerDaemonImpl::startup (int argc, char *argv[])
{
    ACS_SHORT_LOG ((LM_INFO, "Starting up the ACS Container Daemon..."));

    // Initalize the ORB.
    if (init_ORB (argc, argv) != 0)
	{
	return -1;
	}

    // Initialize AES.
    if (!ACSError::init(m_orb.in()))
	{
	ACS_SHORT_LOG ((LM_ERROR, "Failed to initalize the ACS Error System."));
	return -1;
	}

    ACS_SHORT_LOG ((LM_INFO, "ACS Container Daemon is initialized."));

    return 0;
}

int
ACSContainerDaemonImpl::run (void)
{
    ACS_SHORT_LOG ((LM_INFO, "ACS Container Daemon is up and running..."));

    try
	{
	this->m_orb->run ();
	}
    catch(...)
	{
	return -1;
	}

    return 0;
}

void
ACSContainerDaemonImpl::shutdown ()
{

    // shutdown the ORB.
    if (!CORBA::is_nil (m_orb.in ()))
	{
	this->m_orb->shutdown (true);

	}

    // shutdown AES
    ACSError::done();
}

/************************** CORBA interface ****************************/

void
ACSContainerDaemonImpl::start_container (
    const char * container_type,
    const char * container_name,
    ::CORBA::Short instance_number,
    const char * additional_command_line
    )
    ACE_THROW_SPEC ((
			CORBA::SystemException,
			::acsdaemonErrType::FailedToStartContainerEx,
			::ACSErrTypeCommon::BadParameterEx
			))
{
    if (container_type == 0 ||
	*container_type == 0)
	{
	::ACSErrTypeCommon::BadParameterExImpl ex(__FILE__, __LINE__,
						  "::ACSContainerDaemonImpl::start_container");
	ex.setParameter("container_type");
	throw ex.getBadParameterEx();
	}

    if (container_name == 0 ||
	*container_name == 0)
	{
	::ACSErrTypeCommon::BadParameterExImpl ex(__FILE__, __LINE__,
						  "::ACSContainerDaemonImpl::start_container");
	ex.setParameter("container_name");
	throw ex.getBadParameterEx();
	}

    const char * cmdln = (additional_command_line ? additional_command_line : "");

    // execute: "acsStartContainer -<type> -b <instance> <name> <args>"
    // TODO checks for ';', '&', '|' chars, they can run any other command!

    //get the directory name to store the container stdout
    std::string logDirectory="~/.acs/commandcenter/";
    std::string containerName(container_name);
    std::string::size_type pos=containerName.rfind("/");
    if(pos != std::string::npos){
    	logDirectory.append(containerName,0,pos+1);
    	containerName.erase(0,pos+1);
    }
    //create the directory
    std::string mkdir("mkdir -p ");
    mkdir.append(logDirectory);
    ACE_OS::system(mkdir.c_str());

    std::string timeStamp(getStringifiedTimeStamp().c_str());

    char command[1000];
    snprintf(command, 1000, "acsStartContainer -%s -b %d %s %s &> %sacsStartContainer_%s_%s&", container_type, instance_number, container_name, cmdln, logDirectory.c_str(), containerName.c_str(), timeStamp.c_str());

    ACS_SHORT_LOG ((LM_INFO, "Executing: '%s'.", command));

    int result = ACE_OS::system(command);

    if (result < 0)
	{
	throw ::acsdaemonErrType::FailedToStartContainerExImpl(
	    __FILE__, __LINE__,
	    "::ACSContainerDaemonImpl::start_container").getFailedToStartContainerEx();
	}

}

void
ACSContainerDaemonImpl::stop_container (
    const char * container_name,
    ::CORBA::Short instance_number,
    const char * additional_command_line
    )
    ACE_THROW_SPEC ((
			CORBA::SystemException,
			::acsdaemonErrType::FailedToStopContainerEx,
			::ACSErrTypeCommon::BadParameterEx
			))
{
    if (container_name == 0 ||
	*container_name == 0)
	{
	::ACSErrTypeCommon::BadParameterExImpl ex(__FILE__, __LINE__,
						  "::ACSContainerDaemonImpl::stop_container");
	ex.setParameter("container_name");
	throw ex.getBadParameterEx();
	}

    const char * cmdln = (additional_command_line ? additional_command_line : "");

    //get the directory name to store the container stdout
    std::string logDirectory="~/.acs/commandcenter/";
    std::string containerName(container_name);
    std::string::size_type pos=containerName.rfind("/");
    if(pos != std::string::npos){
    	logDirectory.append(containerName,0,pos);
    	containerName.erase(0,pos);
    }
    //create the directory
    std::string mkdir("mkdir -p ");
    mkdir.append(logDirectory);
    ACE_OS::system(mkdir.c_str());

    std::string timeStamp(getStringifiedTimeStamp().c_str());

    // execute: "acsStopContainer -b <instance> <name> <args>"
    // TODO checks for ';', '&', '|' chars, they can run any other command!
    char command[1000];
    snprintf(command, 1000, "acsStopContainer -b %d %s %s &> %sacsStopContainer_%s_%s&", instance_number, container_name, cmdln, logDirectory.c_str(), containerName.c_str(), timeStamp.c_str());

    ACS_SHORT_LOG ((LM_INFO, "Executing: '%s'.", command));

    int result = ACE_OS::system(command);

    if (result < 0)
	{
	throw ::acsdaemonErrType::FailedToStopContainerExImpl(
	    __FILE__, __LINE__,
	    "::ACSContainerDaemonImpl::stop_container").getFailedToStopContainerEx();
	}

}

<commit_msg>Fix for COMP-1317 in acsStopContainer<commit_after>/*******************************************************************************
*     ALMA - Atacama Large Millimiter Array
*    (c) European Southern Observatory, 2002
*    Copyright by ESO (in the framework of the ALMA collaboration)
*    and Cosylab 2002, All rights reserved
*
*    This library is free software; you can redistribute it and/or
*    modify it under the terms of the GNU Lesser General Public
*    License as published by the Free Software Foundation; either
*    version 2.1 of the License, or (at your option) any later version.
*
*    This library is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
*    Lesser General Public License for more details.
*
*    You should have received a copy of the GNU Lesser General Public
*    License along with this library; if not, write to the Free Software
*    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
*
* "@(#) $Id: acsContainerDaemonImpl.cpp,v 1.6 2007/10/31 16:23:24 ntroncos Exp $"
*
* who       when        what
* --------  ---------   ----------------------------------------------
* msekoran  2006-06-21  created
*/

#include "acsContainerDaemonImpl.h"
#include <tao/IORTable/IORTable.h>
#include <acserr.h>
#include <acsdaemonErrType.h>
#include <ACSErrTypeCommon.h>

/*****************************************************************/

ACSContainerDaemonImpl::ACSContainerDaemonImpl (LoggingProxy &logProxy) :
    m_isInitialized(false),
    m_logProxy(logProxy)
{
    // noop here

    m_isInitialized = true;
}

ACSContainerDaemonImpl::~ACSContainerDaemonImpl (void)
{
}

int
ACSContainerDaemonImpl::init_ORB  (int& argc, char *argv [])
{
    m_orb = CORBA::ORB_init(argc, argv, "TAO");

    try
	{
	// get a reference to the RootPOA
	CORBA::Object_var obj = m_orb->resolve_initial_references("RootPOA");
	PortableServer::POA_var root_poa = PortableServer::POA::_narrow(obj.in());
	PortableServer::POAManager_var poa_manager = root_poa->the_POAManager();

	// create policies
	CORBA::PolicyList policy_list;
	policy_list.length(5);
	policy_list[0] = root_poa->create_request_processing_policy(PortableServer::USE_DEFAULT_SERVANT);
	policy_list[1] =  root_poa->create_id_uniqueness_policy(PortableServer::MULTIPLE_ID);
	policy_list[2] = root_poa->create_id_assignment_policy(PortableServer::USER_ID);
	policy_list[3] = root_poa->create_servant_retention_policy(PortableServer::NON_RETAIN);
	policy_list[4] =  root_poa->create_lifespan_policy(PortableServer::PERSISTENT);

	// create a ACSDaemon POA with policies
	PortableServer::POA_var poa = root_poa->create_POA("ACSContainerDaemon", poa_manager.in(), policy_list);

	// destroy policies
	for (CORBA::ULong i = 0; i < policy_list.length(); ++i)
	    {
	    CORBA::Policy_ptr policy = policy_list[i];
	    policy->destroy();
	    }

	// set as default servant
	poa->set_servant(this);

	// create reference
	PortableServer::ObjectId_var oid = PortableServer::string_to_ObjectId("ACSContainerDaemon");
	obj = poa->create_reference_with_id (oid.in(), _interface_repository_id());
	m_ior = m_orb->object_to_string(obj.in());

	// bind to IOR table
      	CORBA::Object_var table_object = m_orb->resolve_initial_references("IORTable");
	IORTable::Table_var adapter = IORTable::Table::_narrow(table_object.in());

	if (CORBA::is_nil(adapter.in()))
	    {
	    ACS_SHORT_LOG ((LM_ERROR, "Nil IORTable"));
	    return -1;
	    }
	else
	    {
	    adapter->bind("ACSContainerDaemon", m_ior.in());
	    }

	// activate POA
	poa_manager->activate();

	ACS_SHORT_LOG((LM_INFO, "ACS Container Daemon is waiting for incoming requests."));

	}
    catch( CORBA::Exception &ex )
	{
	ACE_PRINT_EXCEPTION (ex, "EXCEPTION CAUGHT");
	return -1;
	}

    return 0;
}

int
ACSContainerDaemonImpl::startup (int argc, char *argv[])
{
    ACS_SHORT_LOG ((LM_INFO, "Starting up the ACS Container Daemon..."));

    // Initalize the ORB.
    if (init_ORB (argc, argv) != 0)
	{
	return -1;
	}

    // Initialize AES.
    if (!ACSError::init(m_orb.in()))
	{
	ACS_SHORT_LOG ((LM_ERROR, "Failed to initalize the ACS Error System."));
	return -1;
	}

    ACS_SHORT_LOG ((LM_INFO, "ACS Container Daemon is initialized."));

    return 0;
}

int
ACSContainerDaemonImpl::run (void)
{
    ACS_SHORT_LOG ((LM_INFO, "ACS Container Daemon is up and running..."));

    try
	{
	this->m_orb->run ();
	}
    catch(...)
	{
	return -1;
	}

    return 0;
}

void
ACSContainerDaemonImpl::shutdown ()
{

    // shutdown the ORB.
    if (!CORBA::is_nil (m_orb.in ()))
	{
	this->m_orb->shutdown (true);

	}

    // shutdown AES
    ACSError::done();
}

/************************** CORBA interface ****************************/

void
ACSContainerDaemonImpl::start_container (
    const char * container_type,
    const char * container_name,
    ::CORBA::Short instance_number,
    const char * additional_command_line
    )
    ACE_THROW_SPEC ((
			CORBA::SystemException,
			::acsdaemonErrType::FailedToStartContainerEx,
			::ACSErrTypeCommon::BadParameterEx
			))
{
    if (container_type == 0 ||
	*container_type == 0)
	{
	::ACSErrTypeCommon::BadParameterExImpl ex(__FILE__, __LINE__,
						  "::ACSContainerDaemonImpl::start_container");
	ex.setParameter("container_type");
	throw ex.getBadParameterEx();
	}

    if (container_name == 0 ||
	*container_name == 0)
	{
	::ACSErrTypeCommon::BadParameterExImpl ex(__FILE__, __LINE__,
						  "::ACSContainerDaemonImpl::start_container");
	ex.setParameter("container_name");
	throw ex.getBadParameterEx();
	}

    const char * cmdln = (additional_command_line ? additional_command_line : "");

    // execute: "acsStartContainer -<type> -b <instance> <name> <args>"
    // TODO checks for ';', '&', '|' chars, they can run any other command!

    //get the directory name to store the container stdout
    std::string logDirectory="~/.acs/commandcenter/";
    std::string containerName(container_name);
    std::string::size_type pos=containerName.rfind("/");
    if(pos != std::string::npos){
    	logDirectory.append(containerName,0,pos+1);
    	containerName.erase(0,pos+1);
    }
    //create the directory
    std::string mkdir("mkdir -p ");
    mkdir.append(logDirectory);
    ACE_OS::system(mkdir.c_str());

    std::string timeStamp(getStringifiedTimeStamp().c_str());

    char command[1000];
    snprintf(command, 1000, "acsStartContainer -%s -b %d %s %s &> %sacsStartContainer_%s_%s&", container_type, instance_number, container_name, cmdln, logDirectory.c_str(), containerName.c_str(), timeStamp.c_str());

    ACS_SHORT_LOG ((LM_INFO, "Executing: '%s'.", command));

    int result = ACE_OS::system(command);

    if (result < 0)
	{
	throw ::acsdaemonErrType::FailedToStartContainerExImpl(
	    __FILE__, __LINE__,
	    "::ACSContainerDaemonImpl::start_container").getFailedToStartContainerEx();
	}

}

void
ACSContainerDaemonImpl::stop_container (
    const char * container_name,
    ::CORBA::Short instance_number,
    const char * additional_command_line
    )
    ACE_THROW_SPEC ((
			CORBA::SystemException,
			::acsdaemonErrType::FailedToStopContainerEx,
			::ACSErrTypeCommon::BadParameterEx
			))
{
    if (container_name == 0 ||
	*container_name == 0)
	{
	::ACSErrTypeCommon::BadParameterExImpl ex(__FILE__, __LINE__,
						  "::ACSContainerDaemonImpl::stop_container");
	ex.setParameter("container_name");
	throw ex.getBadParameterEx();
	}

    const char * cmdln = (additional_command_line ? additional_command_line : "");

    //get the directory name to store the container stdout
    std::string logDirectory="~/.acs/commandcenter/";
    std::string containerName(container_name);
    std::string::size_type pos=containerName.rfind("/");
    if(pos != std::string::npos){
    	logDirectory.append(containerName,0,pos+1);
    	containerName.erase(0,pos+1);
    }
    //create the directory
    std::string mkdir("mkdir -p ");
    mkdir.append(logDirectory);
    ACE_OS::system(mkdir.c_str());

    std::string timeStamp(getStringifiedTimeStamp().c_str());

    // execute: "acsStopContainer -b <instance> <name> <args>"
    // TODO checks for ';', '&', '|' chars, they can run any other command!
    char command[1000];
    snprintf(command, 1000, "acsStopContainer -b %d %s %s &> %sacsStopContainer_%s_%s&", instance_number, container_name, cmdln, logDirectory.c_str(), containerName.c_str(), timeStamp.c_str());

    ACS_SHORT_LOG ((LM_INFO, "Executing: '%s'.", command));

    int result = ACE_OS::system(command);

    if (result < 0)
	{
	throw ::acsdaemonErrType::FailedToStopContainerExImpl(
	    __FILE__, __LINE__,
	    "::ACSContainerDaemonImpl::stop_container").getFailedToStopContainerEx();
	}

}

<|endoftext|>


<commit_before>#include <iostream>
#include <queue>
#include <utility>
#include <stdio.h>
#include <vector>
using namespace std;
typedef  pair<long long ,long long> node;

long long re[1000000];
int main(int argc, char const *argv[])
{
	priority_queue<node ,vector<node> ,greater<node> > pq;

	pq.push(node(1,2));
	node n;
	int i=0;
	while(i<100){

		node n=pq.top();
		//printf("%d",i);
		pq.pop();
		switch(n.second){
			case 2:
				pq.push(node(n.first*2,2));

			case 3:
				pq.push(node(n.first*3,3));

			case 5:
				pq.push(node(n.first*5,5));
		}
		re[i++]=n.first;
	}
	for (int j = 0; j < i; ++j)
	{
		printf("%d\n",re[j]);
	}

	return 0;
}
<commit_msg>update 346588<commit_after>#include <iostream>
#include <queue>
#include <utility>
#include <stdio.h>
#include <vector>
using namespace std;
typedef  pair<long long ,long long> node;

long long re[1000000];
int main(int argc, char const *argv[])
{
	priority_queue<node ,vector<node> ,greater<node> > pq;

	pq.push(node(1,2));
	node n;
	int i=0;
	while(i<1000){

		node n=pq.top();
		//printf("%d",i);
		pq.pop();
		switch(n.second){
			case 2:
				pq.push(node(n.first*2,2));

			case 3:
				pq.push(node(n.first*3,3));

			case 5:
				pq.push(node(n.first*5,5));
		}
		re[i++]=n.first;
	}
	for (int j = 0; j < i; ++j)
	{
		printf("%d\n",re[j]);
	}

	return 0;
}
<|endoftext|>


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

#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/extensions/api/commands/command_service.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/browser/ui/views/bookmarks/bookmark_bubble_view.h"
#include "extensions/common/manifest_constants.h"

typedef ExtensionApiTest BookmarkOverrideTest;

namespace {
// Bookmark this page keybinding.
#if defined(OS_MACOSX)
const char kBookmarkKeybinding[] = "Command+D";
#else
const char kBookmarkKeybinding[] = "Ctrl+D";
#endif  // defined(OS_MACOSX)
}

// Test that invoking the IDC_BOOKMARK_PAGE command (as done by the wrench menu)
// brings up the bookmark UI, if no extension requests to override ctrl-D and
// the user has assigned it to an extension.
IN_PROC_BROWSER_TEST_F(BookmarkOverrideTest, NonOverrideBookmarkPage) {
  ASSERT_TRUE(test_server()->Start());
  ASSERT_TRUE(RunExtensionTest("keybinding/basics")) << message_;
  const extensions::Extension* extension = GetSingleLoadedExtension();

  extensions::CommandService* command_service =
      extensions::CommandService::Get(browser()->profile());

  // Simulate the user setting the keybinding to Ctrl+D.
  command_service->UpdateKeybindingPrefs(
      extension->id(), extensions::manifest_values::kBrowserActionCommandEvent,
      kBookmarkKeybinding);

  // Check that the BookmarkBubbleView is shown when executing
  // IDC_BOOKMARK_PAGE.
  EXPECT_FALSE(BookmarkBubbleView::IsShowing());
  chrome::ExecuteCommand(browser(), IDC_BOOKMARK_PAGE);
  EXPECT_TRUE(BookmarkBubbleView::IsShowing());
}
<commit_msg>Add test for clicking bookmark star in presence of ctrl-D keybinding<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/extensions/api/commands/command_service.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/views/bookmarks/bookmark_bubble_view.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/location_bar/star_view.h"
#include "chrome/browser/ui/views/toolbar/toolbar_view.h"
#include "chrome/test/base/ui_test_utils.h"
#include "extensions/common/manifest_constants.h"
#include "extensions/test/result_catcher.h"

typedef ExtensionApiTest BookmarkOverrideTest;

namespace {
// Bookmark this page keybinding.
#if defined(OS_MACOSX)
const char kBookmarkKeybinding[] = "Command+D";
#else
const char kBookmarkKeybinding[] = "Ctrl+D";
#endif  // defined(OS_MACOSX)
}

// Test that clicking the star brings up the bookmark UI, if no extension
// requests to override ctrl-D and the user has assigned it to an extension.
IN_PROC_BROWSER_TEST_F(BookmarkOverrideTest, NonOverrideStarClick) {
  ASSERT_TRUE(test_server()->Start());
  ASSERT_TRUE(RunExtensionTest("keybinding/basics")) << message_;
  const extensions::Extension* extension = GetSingleLoadedExtension();

  extensions::CommandService* command_service =
      extensions::CommandService::Get(browser()->profile());

  // Simulate the user setting the keybinding to Ctrl+D.
  command_service->UpdateKeybindingPrefs(
      extension->id(), extensions::manifest_values::kBrowserActionCommandEvent,
      kBookmarkKeybinding);

  // Check that the BookmarkBubbleView is shown when clicking on the star.
  BrowserView* browser_view = reinterpret_cast<BrowserView*>(
      browser()->window());
  views::View* star_view =
      browser_view->GetToolbarView()->location_bar()->star_view();

  ui::MouseEvent pressed_event(ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(),
                               ui::EF_LEFT_MOUSE_BUTTON,
                               ui::EF_LEFT_MOUSE_BUTTON);
  ui::MouseEvent released_event(ui::ET_MOUSE_RELEASED, gfx::Point(),
                                gfx::Point(), ui::EF_LEFT_MOUSE_BUTTON,
                                ui::EF_LEFT_MOUSE_BUTTON);

  // Verify that clicking once shows the bookmark bubble.
  EXPECT_FALSE(BookmarkBubbleView::IsShowing());
  star_view->OnMousePressed(pressed_event);
  EXPECT_FALSE(BookmarkBubbleView::IsShowing());
  star_view->OnMouseReleased(released_event);
  EXPECT_TRUE(BookmarkBubbleView::IsShowing());
}

// Test that invoking the IDC_BOOKMARK_PAGE command (as done by the wrench menu)
// brings up the bookmark UI, if no extension requests to override ctrl-D and
// the user has assigned it to an extension.
IN_PROC_BROWSER_TEST_F(BookmarkOverrideTest, NonOverrideBookmarkPage) {
  ASSERT_TRUE(test_server()->Start());
  ASSERT_TRUE(RunExtensionTest("keybinding/basics")) << message_;
  const extensions::Extension* extension = GetSingleLoadedExtension();

  extensions::CommandService* command_service =
      extensions::CommandService::Get(browser()->profile());

  // Simulate the user setting the keybinding to Ctrl+D.
  command_service->UpdateKeybindingPrefs(
      extension->id(), extensions::manifest_values::kBrowserActionCommandEvent,
      kBookmarkKeybinding);

  // Check that the BookmarkBubbleView is shown when executing
  // IDC_BOOKMARK_PAGE.
  EXPECT_FALSE(BookmarkBubbleView::IsShowing());
  chrome::ExecuteCommand(browser(), IDC_BOOKMARK_PAGE);
  EXPECT_TRUE(BookmarkBubbleView::IsShowing());
}
<|endoftext|>


<commit_before>/*
  Q Light Controller Plus
  oscpacketizer.cpp

  Copyright (c) Massimo Callegari

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0.txt

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

#include "oscpacketizer.h"

#include <QStringList>
#include <QDebug>

OSCPacketizer::OSCPacketizer()
{
}

OSCPacketizer::~OSCPacketizer()
{
}

/*********************************************************************
 * Sender functions
 *********************************************************************/

void OSCPacketizer::setupOSCDmx(QByteArray &data, quint32 universe, quint32 channel, uchar value)
{
    data.clear();
    QString path = QString("/%1/dmx/%2").arg(universe).arg(channel);
    data.append(path);

    // add trailing zeros to reach a multiple of 4
    int zeroNumber = 4 - (path.length() % 4);
    if (zeroNumber != 0 && zeroNumber != 4)
        data.append(QByteArray(zeroNumber, 0x00));

    data.append(",f");
    data.append((char)0x00);
    data.append((char)0x00);
    float fVal = (float)value;
    data.append(*(((char *)&fVal) + 3));
    data.append(*(((char *)&fVal) + 2));
    data.append(*(((char *)&fVal) + 1));
    data.append(*(((char *)&fVal) + 0));
}

void OSCPacketizer::setupOSCGeneric(QByteArray &data, QString &path, QString types, QByteArray &values)
{
    data.clear();
    if (path.isEmpty())
    {
        qDebug() << Q_FUNC_INFO << "Empty path, can't create packet";
        return;
    }

    data.append(path);
    // add trailing zeros to reach a multiple of 4
    int zeroNumber = 4 - (path.length() % 4);
    if (zeroNumber > 0)
        data.append(QByteArray(zeroNumber, 0x00));

    data.append(",");
    data.append(types);

    zeroNumber = 4 - ((types.length() + 1) % 4);
    if (zeroNumber > 0)
        data.append(QByteArray(zeroNumber, 0x00));

    for (int i = 0; i < types.length() && i < values.length(); i++)
    {
        if (types.at(i) == 'f')
        {
            uchar val = (uchar)values.at(i);
            float fVal = (float)val / 255.0;
            data.append(*(((char *)&fVal) + 3));
            data.append(*(((char *)&fVal) + 2));
            data.append(*(((char *)&fVal) + 1));
            data.append(*(((char *)&fVal) + 0));
        }
    }
}

/*********************************************************************
 * Receiver functions
 *********************************************************************/
bool OSCPacketizer::parseMessage(QByteArray &data, QString &path, QByteArray &values)
{
    path.clear();
    values.clear();

    QList<TagType> typeArray;
    bool tagsEnded = false;

    // first of all look for a comma
    int commaPos = data.indexOf(0x2C);
    if (commaPos == -1)
        return false;

    path = QString(data.mid(0, commaPos));
    qDebug() << " [OSC] path extracted:" << path;

    int currPos = commaPos + 1;
    while (tagsEnded == false)
    {
        switch (data.at(currPos))
        {
            case 0x00: tagsEnded = true; break;
            case 0x62: /* 'b' */ typeArray.append(Blob); break;
            case 0x66: /* 'f' */ typeArray.append(Float); break;
            case 0x69: /* 'i' */ typeArray.append(Integer); break;
            case 0x73: /* 's' */ typeArray.append(String); break;
            default: break;
        }
        currPos++;
    }
    // round current position to 4
    if (typeArray.count() < 4)
        currPos += (2 - typeArray.count());

    qDebug () << "[OSC] Tags found:" << typeArray.count() << "currpos at" << currPos;

    foreach(TagType tag, typeArray)
    {
        switch (tag)
        {
            case Integer:
            {
                if (currPos + 4 > data.size())
                    break;
                quint32 iVal;

                *((uchar*)(&iVal) + 3) = data.at(currPos);
                *((uchar*)(&iVal) + 2) = data.at(currPos + 1);
                *((uchar*)(&iVal) + 1) = data.at(currPos + 2);
                *((uchar*)(&iVal) + 0) = data.at(currPos + 3);

                if (iVal < 256)
                    values.append((char)iVal);
                else
                    values.append((char)(iVal / 0xFFFFFF));

                qDebug() << "[OSC] iVal:" << iVal;
                currPos += 4;
            }
            break;
            case Float:
            {
                if (currPos + 4 > data.size())
                    break;
                float fVal;

                *((uchar*)(&fVal) + 3) = data.at(currPos);
                *((uchar*)(&fVal) + 2) = data.at(currPos + 1);
                *((uchar*)(&fVal) + 1) = data.at(currPos + 2);
                *((uchar*)(&fVal) + 0) = data.at(currPos + 3);

                values.append((char)(255.0 * fVal));

                qDebug() << "[OSC] fVal:" << fVal;

                currPos += 4;
            }
            break;
            case String:
            {
                int firstZeroPos = data.indexOf('\0', currPos);
                QString str = QString(data.mid(currPos, firstZeroPos - currPos));
                qDebug() << "[OSC] sVal:" << str;
                // align current position to a multiple of 4
                int zeroNumber = 4 - (str.length() % 4);
                currPos = firstZeroPos + zeroNumber;
            }
            break;
            default: break;
        }
    }

    return true;
}

<commit_msg>plugins/osc: fixed 0 padding of generic outgoing packets<commit_after>/*
  Q Light Controller Plus
  oscpacketizer.cpp

  Copyright (c) Massimo Callegari

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0.txt

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

#include "oscpacketizer.h"

#include <QStringList>
#include <QDebug>

OSCPacketizer::OSCPacketizer()
{
}

OSCPacketizer::~OSCPacketizer()
{
}

/*********************************************************************
 * Sender functions
 *********************************************************************/

void OSCPacketizer::setupOSCDmx(QByteArray &data, quint32 universe, quint32 channel, uchar value)
{
    data.clear();
    QString path = QString("/%1/dmx/%2").arg(universe).arg(channel);
    data.append(path);

    // add trailing zeros to reach a multiple of 4
    int zeroNumber = 4 - (path.length() % 4);
    if (zeroNumber > 0)
        data.append(QByteArray(zeroNumber, 0x00));

    data.append(",f");
    data.append((char)0x00);
    data.append((char)0x00);
    float fVal = (float)value;
    data.append(*(((char *)&fVal) + 3));
    data.append(*(((char *)&fVal) + 2));
    data.append(*(((char *)&fVal) + 1));
    data.append(*(((char *)&fVal) + 0));
}

void OSCPacketizer::setupOSCGeneric(QByteArray &data, QString &path, QString types, QByteArray &values)
{
    data.clear();
    if (path.isEmpty())
    {
        qDebug() << Q_FUNC_INFO << "Empty path, can't create packet";
        return;
    }

    data.append(path);
    // add trailing zeros to reach a multiple of 4
    int zeroNumber = 4 - (path.length() % 4);
    if (zeroNumber > 0)
        data.append(QByteArray(zeroNumber, 0x00));

    data.append(",");
    data.append(types);

    zeroNumber = 4 - ((types.length() + 1) % 4);
    if (zeroNumber > 0)
        data.append(QByteArray(zeroNumber, 0x00));

    for (int i = 0; i < types.length() && i < values.length(); i++)
    {
        if (types.at(i) == 'f')
        {
            uchar val = (uchar)values.at(i);
            float fVal = (float)val / 255.0;
            data.append(*(((char *)&fVal) + 3));
            data.append(*(((char *)&fVal) + 2));
            data.append(*(((char *)&fVal) + 1));
            data.append(*(((char *)&fVal) + 0));
        }
    }
}

/*********************************************************************
 * Receiver functions
 *********************************************************************/
bool OSCPacketizer::parseMessage(QByteArray &data, QString &path, QByteArray &values)
{
    path.clear();
    values.clear();

    QList<TagType> typeArray;
    bool tagsEnded = false;

    // first of all look for a comma
    int commaPos = data.indexOf(0x2C);
    if (commaPos == -1)
        return false;

    path = QString(data.mid(0, commaPos));
    qDebug() << " [OSC] path extracted:" << path;

    int currPos = commaPos + 1;
    while (tagsEnded == false)
    {
        switch (data.at(currPos))
        {
            case 0x00: tagsEnded = true; break;
            case 0x62: /* 'b' */ typeArray.append(Blob); break;
            case 0x66: /* 'f' */ typeArray.append(Float); break;
            case 0x69: /* 'i' */ typeArray.append(Integer); break;
            case 0x73: /* 's' */ typeArray.append(String); break;
            default: break;
        }
        currPos++;
    }
    // round current position to 4
    if (typeArray.count() < 4)
        currPos += (2 - typeArray.count());

    qDebug () << "[OSC] Tags found:" << typeArray.count() << "currpos at" << currPos;

    foreach(TagType tag, typeArray)
    {
        switch (tag)
        {
            case Integer:
            {
                if (currPos + 4 > data.size())
                    break;
                quint32 iVal;

                *((uchar*)(&iVal) + 3) = data.at(currPos);
                *((uchar*)(&iVal) + 2) = data.at(currPos + 1);
                *((uchar*)(&iVal) + 1) = data.at(currPos + 2);
                *((uchar*)(&iVal) + 0) = data.at(currPos + 3);

                if (iVal < 256)
                    values.append((char)iVal);
                else
                    values.append((char)(iVal / 0xFFFFFF));

                qDebug() << "[OSC] iVal:" << iVal;
                currPos += 4;
            }
            break;
            case Float:
            {
                if (currPos + 4 > data.size())
                    break;
                float fVal;

                *((uchar*)(&fVal) + 3) = data.at(currPos);
                *((uchar*)(&fVal) + 2) = data.at(currPos + 1);
                *((uchar*)(&fVal) + 1) = data.at(currPos + 2);
                *((uchar*)(&fVal) + 0) = data.at(currPos + 3);

                values.append((char)(255.0 * fVal));

                qDebug() << "[OSC] fVal:" << fVal;

                currPos += 4;
            }
            break;
            case String:
            {
                int firstZeroPos = data.indexOf('\0', currPos);
                QString str = QString(data.mid(currPos, firstZeroPos - currPos));
                qDebug() << "[OSC] sVal:" << str;
                // align current position to a multiple of 4
                int zeroNumber = 4 - (str.length() % 4);
                currPos = firstZeroPos + zeroNumber;
            }
            break;
            default: break;
        }
    }

    return true;
}

<|endoftext|>


<commit_before>// webadmin.cpp : Defines the entry point for the DLL application.
//

#include "bzfsAPI.h"
#include "plugin_utils.h"
#include "plugin_HTTP.h"
#include <fstream>
#include <cstring>
#include <algorithm>

class WebAdmin : public BZFSHTTPAuth, TemplateCallbackClass
{
public:
  WebAdmin();
  virtual const char * getVDir ( void ){return "webadmin";}
  virtual const char * getDescription ( void ){return "Server Administration (Login Required)";}

  void init (const char *tDir);

  virtual bool handleAuthedRequest ( int level, const HTTPRequest &request, HTTPReply &reply );

  // from TemplateCallbackClass
  virtual void keyCallback (std::string &data, const std::string &key);
  virtual bool loopCallback (const std::string &key);
  virtual bool ifCallback (const std::string &key);

private:
  size_t loopPos;
  std::map<std::string,std::string> templateVars;

  typedef void (WebAdmin::*page_callback)(const HTTPRequest &);
  std::map<std::string,page_callback> controllers;
  std::vector<std::string> pagenames;

  void mainPageCallback (const HTTPRequest &request);
  void banlistPageCallback (const HTTPRequest &request);

  bz_APIIntList players;
};

WebAdmin *webAdmin = NULL;

BZ_GET_PLUGIN_VERSION

BZF_PLUGIN_CALL int bz_Load(const char* commandLine)
{
  if(webAdmin)
    delete(webAdmin);
  webAdmin = new WebAdmin;
  webAdmin->init(commandLine);

  bz_debugMessage(4,"webadmin plugin loaded");
  return 0;
}

BZF_PLUGIN_CALL int bz_Unload(void)
{
  if(webAdmin)
    delete(webAdmin);
  webAdmin = NULL;

  bz_debugMessage(4,"webadmin plugin unloaded");
  return 0;
}

WebAdmin::WebAdmin():BZFSHTTPAuth(),loopPos(0)
{
	registerVDir();

	// add new pages here
	controllers["main"] = &WebAdmin::mainPageCallback;
	controllers["banlist"] = &WebAdmin::banlistPageCallback;
	controllers["helpmsg"] = NULL;
	controllers["group"] = NULL;

  std::map<std::string,page_callback>::iterator pair;
  for(pair = controllers.begin(); pair != controllers.end(); pair++)
    pagenames.push_back(pair->first);
}

void WebAdmin::init(const char* cmdln)
{
  templateSystem.addSearchPath(cmdln ? cmdln : "./");

  // level one has admin perms
  addPermToLevel(1,"ADMIN");

  templateSystem.addIF("IsCurrentPage",this);
  templateSystem.addIF("Error",this);

  templateSystem.addKey("Error",this);
  templateSystem.addKey("Callsign",this);
  templateSystem.addKey("BannedUser",this);
  templateSystem.addKey("PageName",this);

  templateSystem.addLoop("Navigation",this);
  templateSystem.addLoop("Players",this);
  templateSystem.addLoop("IPBanList",this);
  templateSystem.addLoop("IDBanList",this);

  templateSystem.setPluginName("webadmin", getBaseURL().c_str());

  setupAuth();
}

// event hook for [$Something] in templates
void WebAdmin::keyCallback (std::string &data, const std::string &key)
{
  const std::map<std::string,std::string>::iterator &pair = templateVars.find(key);
  if (pair != templateVars.end())
		data = pair->second;
}

// condition check for [*START] in templates
bool WebAdmin::loopCallback (const std::string &key)
{
  if (key == "players") {
    if (!loopPos) bz_getPlayerIndexList(&players);
    else if (loopPos < players.size()) {
      templateVars["playerid"] = players[loopPos];
      templateVars["callsign"] = bz_getPlayerCallsign(players[loopPos++]);
      return true;
    } else {
      players.clear();
      return loopPos = 0;
    }
  } else if (key == "navigation") {
    if (loopPos < pagenames.size()) {
      templateVars["pagename"] = pagenames[loopPos++];
      return true;
    } else return loopPos = 0;
  } else if (key == "permissions") {
    if (loopPos < bzu_standardPerms().size()) {
      templateVars["permission"] = bzu_standardPerms()[loopPos++];
      return true;
    } else return loopPos = 0;
  } else return false;
}

// condition check for [?IF] in templates
bool WebAdmin::ifCallback (const std::string &key)
{
  if (key == "iscurrentpage")
    return templateVars["pagename"] == templateVars["currentpage"];
  return false;
}

bool WebAdmin::handleAuthedRequest ( int level, const HTTPRequest &request, HTTPReply &reply )
{
  std::map<std::string,page_callback>::iterator pair;
  size_t last;
  std::string pagename = request.resource;

  switch(level) {
  case 1:
  case VERIFIED:
    last = pagename.size()-1;
    if (pagename[last] == '/') pagename.erase(last);
    if (pagename.empty()) pagename = "main";
    pair = controllers.find(pagename);
    if (pair != controllers.end()) {
      (this->*pair->second)(request);
      if (!templateSystem.processTemplateFile(reply.body, (pagename + ".tmpl").c_str())) {
        reply.returnCode = HTTPReply::e500ServerError;
          if (!templateSystem.processTemplateFile(reply.body, "500.tmpl"))
            reply.body = format("Missing template: %s.tmpl", pagename.c_str());
        }
    } else {
      reply.returnCode = HTTPReply::e404NotFound;
      if (!templateSystem.processTemplateFile(reply.body, "404.tmpl"))
        reply.body = format("No such resource: %s", pagename.c_str());
    }
    break;
  //reply.body = format("Not authenticated(Verified) sessionID %d",request.sessionID);
  default:
    reply.body = format("Not authenticated sessionID %d",request.sessionID);
  }

  reply.docType = HTTPReply::eHTML;

  templateVars.clear();
  return true;
}

void WebAdmin::mainPageCallback (const HTTPRequest &request)
{
  if (request.request != ePost) return;
  std::vector<std::string> players;
  if (!request.getParam("players", players)) return;
  std::string dummy, reason;
  bool notify = request.getParam("notify", dummy);
  request.getParam("reason", reason);
  std::vector<std::string>::iterator i;
  if (request.getParam("kick", dummy))
    for (i = players.begin(); i != players.end(); i++)
      bz_kickUser(atoi(i->c_str()), reason.c_str(), notify);
  else if (request.getParam("ipban", players)) {
    request.getParam("duration", dummy);
    int duration = atoi(dummy.c_str());
    for (i = players.begin(); i != players.end(); i++) {
      int playerID = atoi(i->c_str());
      bz_BasePlayerRecord *player = bz_getPlayerByIndex(playerID);
      bz_IPBanUser(playerID, bz_getPlayerIPAddress(playerID), duration, reason.c_str());
    }
  }
  else if (request.getParam("idban", players)) {
    request.getParam("duration", dummy);
    int duration = atoi(dummy.c_str());
    for (i = players.begin(); i != players.end(); i++) {
      int playerID = atoi(i->c_str());
      bz_BasePlayerRecord *player = bz_getPlayerByIndex(playerID);
      bz_IPBanUser(playerID, bz_getPlayerCallsign(playerID), duration, reason.c_str());
    }
  }
}

void WebAdmin::banlistPageCallback (const HTTPRequest &request)
{
  if (request.request != ePost) return;
  std::vector<std::string> banRemovals;
  std::vector<std::string>::iterator i;
  if (request.getParam("delip", banRemovals))
    for(i = banRemovals.begin(); i != banRemovals.end(); i++)
      bz_IPUnbanUser(i->c_str());
  if (request.getParam("delid", banRemovals))
    for(i = banRemovals.begin(); i != banRemovals.end(); i++)
      bz_IDUnbanUser(i->c_str());

}

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=2 expandtab
<commit_msg>more keys, ifs, loops<commit_after>// webadmin.cpp : Defines the entry point for the DLL application.
//

#include "bzfsAPI.h"
#include "plugin_utils.h"
#include "plugin_HTTP.h"
#include <fstream>
#include <cstring>
#include <algorithm>

class WebAdmin : public BZFSHTTPAuth, TemplateCallbackClass
{
public:
  WebAdmin();
  virtual const char * getVDir ( void ){return "webadmin";}
  virtual const char * getDescription ( void ){return "Server Administration (Login Required)";}

  void init (const char *tDir);

  virtual bool handleAuthedRequest ( int level, const HTTPRequest &request, HTTPReply &reply );

  // from TemplateCallbackClass
  virtual void keyCallback (std::string &data, const std::string &key);
  virtual bool loopCallback (const std::string &key);
  virtual bool ifCallback (const std::string &key);

private:
  unsigned int loopPos;
  std::map<std::string,std::string> templateVars;

  typedef void (WebAdmin::*page_callback)(const HTTPRequest &);
  std::map<std::string,page_callback> controllers;
  std::vector<std::string> pagenames;

  void mainPageCallback (const HTTPRequest &request);
  void banlistPageCallback (const HTTPRequest &request);

  bz_APIIntList players;
  bz_APIStringList *stringList;

  bool editing;
};

WebAdmin *webAdmin = NULL;

BZ_GET_PLUGIN_VERSION

BZF_PLUGIN_CALL int bz_Load(const char* commandLine)
{
  if(webAdmin)
    delete(webAdmin);
  webAdmin = new WebAdmin;
  webAdmin->init(commandLine);

  bz_debugMessage(4,"webadmin plugin loaded");
  return 0;
}

BZF_PLUGIN_CALL int bz_Unload(void)
{
  if(webAdmin)
    delete(webAdmin);
  webAdmin = NULL;

  bz_debugMessage(4,"webadmin plugin unloaded");
  return 0;
}

WebAdmin::WebAdmin():BZFSHTTPAuth(),loopPos(0)
{
	registerVDir();

	// add new pages here
	controllers["main"] = &WebAdmin::mainPageCallback;
	controllers["banlist"] = &WebAdmin::banlistPageCallback;
	controllers["helpmsg"] = NULL;
	controllers["group"] = NULL;

  std::map<std::string,page_callback>::iterator pair;
  for(pair = controllers.begin(); pair != controllers.end(); pair++)
    pagenames.push_back(pair->first);
}

void WebAdmin::init(const char* cmdln)
{
  templateSystem.addSearchPath(cmdln ? cmdln : "./");

  // level one has admin perms
  addPermToLevel(1,"ADMIN");

  templateSystem.addIF("IsCurrentPage",this);
  templateSystem.addIF("Error",this);
  templateSystem.addIF("Editing",this);

  templateSystem.addKey("Error",this);
  templateSystem.addKey("Callsign",this);
  templateSystem.addKey("BannedUser",this);
  templateSystem.addKey("PageName",this);
  templateSystem.addKey("HelpMsgName",this);
  templateSystem.addKey("HelpMsgBody",this);
  templateSystem.addKey("GroupName",this);

  templateSystem.addLoop("Navigation",this);
  templateSystem.addLoop("Players",this);
  templateSystem.addLoop("IPBanList",this);
  templateSystem.addLoop("IDBanList",this);
  templateSystem.addLoop("HelpMsgs",this);
  templateSystem.addLoop("Groups",this);

  templateSystem.setPluginName("webadmin", getBaseURL().c_str());

  setupAuth();
}

// event hook for [$Something] in templates
void WebAdmin::keyCallback (std::string &data, const std::string &key)
{
  const std::map<std::string,std::string>::iterator &pair = templateVars.find(key);
  if (pair != templateVars.end())
		data = pair->second;
}

// condition check for [*START] in templates
bool WebAdmin::loopCallback (const std::string &key)
{
  if (key == "players") {
    if (!loopPos) bz_getPlayerIndexList(&players);
    else if (loopPos < players.size()) {
      templateVars["playerid"] = players[loopPos];
      templateVars["callsign"] = bz_getPlayerCallsign(players[loopPos++]);
      return true;
    } else {
      players.clear();
      return loopPos = 0;
    }
  } else if (key == "navigation") {
    if (loopPos < pagenames.size()) {
      templateVars["pagename"] = pagenames[loopPos++];
      return true;
    } else return loopPos = 0;
  } else if (key == "permissions") {
    if (loopPos < bzu_standardPerms().size()) {
      templateVars["permission"] = bzu_standardPerms()[loopPos++];
      return true;
    } else return loopPos = 0;
  } else if (key == "helpmsgs") {
    if (!loopPos) stringList = bz_getHelpTopics();
    if (loopPos < stringList.size()) {
      templateVare["helpmsgname"] = stringList[loopPos++].c_str();
      return true;
    } else {
      delete(stringList);
      return loopPos = 0;
    }
  } else if (key == "groups") {
    if (!loopPos) stringList = bz_getGroupList();
    if (loopPos < stringList.size()) {
      templateVare["groupname"] = stringList[loopPos++].c_str();
      return true;
    } else {
      delete(stringList);
      return loopPos = 0;
    }
  } else return false;
}

// condition check for [?IF] in templates
bool WebAdmin::ifCallback (const std::string &key)
{
  if (key == "iscurrentpage")
    return templateVars["pagename"] == templateVars["currentpage"];
  if (key == "editing")
    return editing;
  return false;
}

bool WebAdmin::handleAuthedRequest ( int level, const HTTPRequest &request, HTTPReply &reply )
{
  std::map<std::string,page_callback>::iterator pair;
  size_t last;
  std::string pagename = request.resource;

  switch(level) {
  case 1:
  case VERIFIED:
    last = pagename.size()-1;
    if (pagename[last] == '/') pagename.erase(last);
    if (pagename.empty()) pagename = "main";
    pair = controllers.find(pagename);
    if (pair != controllers.end()) {
      (this->*pair->second)(request);
      if (!templateSystem.processTemplateFile(reply.body, (pagename + ".tmpl").c_str())) {
        reply.returnCode = HTTPReply::e500ServerError;
          if (!templateSystem.processTemplateFile(reply.body, "500.tmpl"))
            reply.body = format("Missing template: %s.tmpl", pagename.c_str());
        }
    } else {
      reply.returnCode = HTTPReply::e404NotFound;
      if (!templateSystem.processTemplateFile(reply.body, "404.tmpl"))
        reply.body = format("No such resource: %s", pagename.c_str());
    }
    break;
  //reply.body = format("Not authenticated(Verified) sessionID %d",request.sessionID);
  default:
    reply.body = format("Not authenticated sessionID %d, access level %d",request.sessionID,level);
  }

  reply.docType = HTTPReply::eHTML;

  templateVars.clear();
  return true;
}

void WebAdmin::mainPageCallback (const HTTPRequest &request)
{
  if (request.request != ePost) return;
  std::vector<std::string> players;
  if (!request.getParam("players", players)) return;
  std::string dummy, reason;
  bool notify = request.getParam("notify", dummy);
  request.getParam("reason", reason);
  std::vector<std::string>::iterator i;
  if (request.getParam("kick", dummy))
    for (i = players.begin(); i != players.end(); i++)
      bz_kickUser(atoi(i->c_str()), reason.c_str(), notify);
  else if (request.getParam("ipban", players)) {
    request.getParam("duration", dummy);
    int duration = atoi(dummy.c_str());
    for (i = players.begin(); i != players.end(); i++) {
      int playerID = atoi(i->c_str());
      bz_BasePlayerRecord *player = bz_getPlayerByIndex(playerID);
      bz_IPBanUser(playerID, bz_getPlayerIPAddress(playerID), duration, reason.c_str());
    }
  }
  else if (request.getParam("idban", players)) {
    request.getParam("duration", dummy);
    int duration = atoi(dummy.c_str());
    for (i = players.begin(); i != players.end(); i++) {
      int playerID = atoi(i->c_str());
      bz_BasePlayerRecord *player = bz_getPlayerByIndex(playerID);
      bz_IPBanUser(playerID, bz_getPlayerCallsign(playerID), duration, reason.c_str());
    }
  }
}

void WebAdmin::banlistPageCallback (const HTTPRequest &request)
{
  if (request.request != ePost) return;
  std::vector<std::string> banRemovals;
  std::vector<std::string>::iterator i;
  if (request.getParam("delip", banRemovals))
    for(i = banRemovals.begin(); i != banRemovals.end(); i++)
      bz_IPUnbanUser(i->c_str());
  if (request.getParam("delid", banRemovals))
    for(i = banRemovals.begin(); i != banRemovals.end(); i++)
      bz_IDUnbanUser(i->c_str());

}

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=2 expandtab
<|endoftext|>


<commit_before>#include "ovpCXMLStimulationScenarioPlayer.h"

#include <fstream>
#include <iostream>

using namespace OpenViBE;
using namespace OpenViBE::Plugins;
using namespace OpenViBE::Kernel;
using namespace OpenViBEPlugins;
using namespace OpenViBEPlugins::Stimulation;

using namespace OpenViBEToolkit;

using namespace std;

namespace OpenViBEPlugins
{
	namespace Stimulation
	{
		void CXMLStimulationScenarioPlayer::writeStimulationOutput(const void* pBuffer, const EBML::uint64 ui64BufferSize)
		{
			appendOutputChunkData<0>(pBuffer, ui64BufferSize);
		}

		void CXMLStimulationScenarioPlayer::setStimulationCount(const uint32 ui32StimulationCount)
		{
			/* TODO nothing? */
		}

		void CXMLStimulationScenarioPlayer::setStimulation(const uint32 ui32StimulationIndex, const uint64 ui64StimulationIdentifier, const uint64 ui64StimulationDate)
		{
			m_oStimulationReceived.push_back(pair<uint64, uint64>(ui64StimulationIdentifier, ui64StimulationDate));
		}

		boolean CXMLStimulationScenarioPlayer::readAutomaton(const CString& oFilename)
		{
			ifstream l_oFile(oFilename.toASCIIString());
			if(!l_oFile.good())
			{
				return false;
			}

			size_t l_iFileSize = 0;
			l_oFile.seekg(0, ios::end);
			l_iFileSize = l_oFile.tellg();
			l_oFile.seekg(0, ios::beg);

			char * l_pXmlBuffer = new char[l_iFileSize];
			l_oFile.read(l_pXmlBuffer, l_iFileSize);

			m_pXMLAutomatonReader->processData(l_pXmlBuffer, l_iFileSize);

			l_oFile.close();

			return true;
		}

		CXMLStimulationScenarioPlayer::CXMLStimulationScenarioPlayer(void) :
			m_pReader(NULL),
			m_pStimulationReaderCallBack(NULL),
			m_pWriter(NULL),
			m_pOutputWriterCallbackProxy(NULL),
			m_pStimulationOutputWriterHelper(NULL),
			m_pXMLAutomatonReader(NULL),
			m_pAutomatonController(NULL),
			m_pAutomatonContext(NULL),
			m_bEndOfAutomaton(false),
			m_ui64PreviousActivationTime(0)
		{
		}

		boolean CXMLStimulationScenarioPlayer::initialize()
		{
			m_bEndOfAutomaton = false;

			m_pStimulationReaderCallBack=createBoxAlgorithmStimulationInputReaderCallback(*this);
			m_pReader = EBML::createReader(*m_pStimulationReaderCallBack);

			m_pOutputWriterCallbackProxy = new EBML::TWriterCallbackProxy1<OpenViBEPlugins::Stimulation::CXMLStimulationScenarioPlayer>(*this, &CXMLStimulationScenarioPlayer::writeStimulationOutput);

			m_pWriter=EBML::createWriter(*m_pOutputWriterCallbackProxy);

			m_pStimulationOutputWriterHelper=createBoxAlgorithmStimulationOutputWriter();

			const IBox* l_pBoxContext=getBoxAlgorithmContext()->getStaticBoxContext();
			CString l_sFileName;

			m_pXMLAutomatonReader = Automaton::createXMLAutomatonReader();

			// Parses box settings to find input file's name
			l_pBoxContext->getSettingValue(0, l_sFileName);

			if(!readAutomaton(l_sFileName))
			{
				getBoxAlgorithmContext()->getPlayerContext()->getLogManager() << LogLevel_Warning << "Could not read automaton file\n";
				return false;
			}

			m_pAutomatonController = m_pXMLAutomatonReader->getAutomatonController();

			m_pAutomatonContext = m_pAutomatonController->getAutomatonContext();

			//we don't need the XML reader anymore
			releaseXMLAutomatonReader(m_pXMLAutomatonReader);

			m_pStimulationOutputWriterHelper->writeHeader(*m_pWriter);
			getBoxAlgorithmContext()->getDynamicBoxContext()->markOutputAsReadyToSend(0, 0, 0);

			return true;
		}

		boolean CXMLStimulationScenarioPlayer::uninitialize()
		{
			releaseBoxAlgorithmStimulationInputReaderCallback(m_pStimulationReaderCallBack);

			delete m_pOutputWriterCallbackProxy;
			m_pOutputWriterCallbackProxy= NULL;
			m_pWriter->release();
			m_pWriter = NULL;
			releaseBoxAlgorithmStimulationOutputWriter(m_pStimulationOutputWriterHelper);
			m_pStimulationOutputWriterHelper=NULL;

			releaseAutomatonController(m_pAutomatonController);
			m_pAutomatonController=NULL;

			releaseAutomatonContext(m_pAutomatonContext);
			m_pAutomatonContext=NULL;

			return true;
		}

		boolean CXMLStimulationScenarioPlayer::processInput(uint32 ui32InputIndex)
		{
			IDynamicBoxContext* l_pDynamicBoxContext=getBoxAlgorithmContext()->getDynamicBoxContext();

			for(uint32 i=0; i<l_pDynamicBoxContext->getInputChunkCount(ui32InputIndex); i++)
			{
				uint64 l_ui64StartTime;
				uint64 l_ui64EndTime;
				uint64 l_ui64ChunkSize;
				const uint8* l_pChunkBuffer=NULL;

				if(l_pDynamicBoxContext->getInputChunk(ui32InputIndex, i, l_ui64StartTime, l_ui64EndTime, l_ui64ChunkSize, l_pChunkBuffer))
				{
					m_pReader->processData(l_pChunkBuffer, l_ui64ChunkSize);
				}
				l_pDynamicBoxContext->markInputAsDeprecated(ui32InputIndex, i);
			}

			getBoxAlgorithmContext()->markAlgorithmAsReadyToProcess();

			return true;
		}

		boolean CXMLStimulationScenarioPlayer::processClock(CMessageClock &rMessageClock)
		{
			uint64 l_ui64CurrentTime = rMessageClock.getTime();

			IDynamicBoxContext * l_pDynamicBoxContext = getBoxAlgorithmContext()->getDynamicBoxContext();

			if(!m_bEndOfAutomaton)
			{
				//actualize context
				m_pAutomatonContext->setCurrentTime(rMessageClock.getTime());

				for(size_t i=0 ; i<m_oStimulationReceived.size() ; i++)
				{
					Automaton::CIdentifier l_oStimulationIdentifier = m_oStimulationReceived[i].first;
					m_pAutomatonContext->addReceivedEvent(l_oStimulationIdentifier);
				}

				//process
				m_bEndOfAutomaton = m_pAutomatonController->process();

				const Automaton::CIdentifier * l_pSentEvents = m_pAutomatonContext->getSentEvents();

				//set the number of stimulation to send
				m_pStimulationOutputWriterHelper->setStimulationCount(m_pAutomatonContext->getSentEventsCount());

				//if there were stimulations
				if(l_pSentEvents)
				{
					//adds em
					for(uint32 i = 0 ; i<m_pAutomatonContext->getSentEventsCount() ; i++)
					{
						/* TODO check Stimulation date */
						m_pStimulationOutputWriterHelper->setStimulation(i, l_pSentEvents[i], l_ui64CurrentTime);
					}

				}

				m_pStimulationOutputWriterHelper->writeBuffer(*m_pWriter);

				/* TODO check Stimulation date */
				l_pDynamicBoxContext->markOutputAsReadyToSend(0, m_ui64PreviousActivationTime, l_ui64CurrentTime);

				m_pAutomatonContext->clearSentEvents();

				//TODO clear all events?? or just used ones?
				m_pAutomatonContext->clearReceivedEvents();
			}

			m_ui64PreviousActivationTime = l_ui64CurrentTime;

			getBoxAlgorithmContext()->markAlgorithmAsReadyToProcess();

			return true;
		}

		boolean CXMLStimulationScenarioPlayer::process()
		{
			// l_pDynamicBoxContext->markOutputAsReadyToSend(0, 0, 0);
			return true;
		}

	};

};

<commit_msg>openvibe-plugins-stimulation :  * XML stimulation scenario player: corrected bug causing crash when the scenario file could not be opened<commit_after>#include "ovpCXMLStimulationScenarioPlayer.h"

#include <fstream>
#include <iostream>

using namespace OpenViBE;
using namespace OpenViBE::Plugins;
using namespace OpenViBE::Kernel;
using namespace OpenViBEPlugins;
using namespace OpenViBEPlugins::Stimulation;

using namespace OpenViBEToolkit;

using namespace std;

namespace OpenViBEPlugins
{
	namespace Stimulation
	{
		void CXMLStimulationScenarioPlayer::writeStimulationOutput(const void* pBuffer, const EBML::uint64 ui64BufferSize)
		{
			appendOutputChunkData<0>(pBuffer, ui64BufferSize);
		}

		void CXMLStimulationScenarioPlayer::setStimulationCount(const uint32 ui32StimulationCount)
		{
			/* TODO nothing? */
		}

		void CXMLStimulationScenarioPlayer::setStimulation(const uint32 ui32StimulationIndex, const uint64 ui64StimulationIdentifier, const uint64 ui64StimulationDate)
		{
			m_oStimulationReceived.push_back(pair<uint64, uint64>(ui64StimulationIdentifier, ui64StimulationDate));
		}

		boolean CXMLStimulationScenarioPlayer::readAutomaton(const CString& oFilename)
		{
			ifstream l_oFile(oFilename.toASCIIString());
			if(!l_oFile.good())
			{
				return false;
			}

			size_t l_iFileSize = 0;
			l_oFile.seekg(0, ios::end);
			l_iFileSize = l_oFile.tellg();
			l_oFile.seekg(0, ios::beg);

			char * l_pXmlBuffer = new char[l_iFileSize];
			l_oFile.read(l_pXmlBuffer, l_iFileSize);

			m_pXMLAutomatonReader->processData(l_pXmlBuffer, l_iFileSize);

			l_oFile.close();

			return true;
		}

		CXMLStimulationScenarioPlayer::CXMLStimulationScenarioPlayer(void) :
			m_pReader(NULL),
			m_pStimulationReaderCallBack(NULL),
			m_pWriter(NULL),
			m_pOutputWriterCallbackProxy(NULL),
			m_pStimulationOutputWriterHelper(NULL),
			m_pXMLAutomatonReader(NULL),
			m_pAutomatonController(NULL),
			m_pAutomatonContext(NULL),
			m_bEndOfAutomaton(false),
			m_ui64PreviousActivationTime(0)
		{
		}

		boolean CXMLStimulationScenarioPlayer::initialize()
		{
			m_bEndOfAutomaton = false;

			m_pStimulationReaderCallBack=createBoxAlgorithmStimulationInputReaderCallback(*this);
			m_pReader = EBML::createReader(*m_pStimulationReaderCallBack);

			m_pOutputWriterCallbackProxy = new EBML::TWriterCallbackProxy1<OpenViBEPlugins::Stimulation::CXMLStimulationScenarioPlayer>(*this, &CXMLStimulationScenarioPlayer::writeStimulationOutput);

			m_pWriter=EBML::createWriter(*m_pOutputWriterCallbackProxy);

			m_pStimulationOutputWriterHelper=createBoxAlgorithmStimulationOutputWriter();

			const IBox* l_pBoxContext=getBoxAlgorithmContext()->getStaticBoxContext();
			CString l_sFileName;

			m_pXMLAutomatonReader = Automaton::createXMLAutomatonReader();

			// Parses box settings to find input file's name
			l_pBoxContext->getSettingValue(0, l_sFileName);

			m_pAutomatonController=NULL;
			m_pAutomatonContext=NULL;

			if(!readAutomaton(l_sFileName))
			{
				getBoxAlgorithmContext()->getPlayerContext()->getLogManager() << LogLevel_Warning << "Could not read automaton file\n";
				return false;
			}

			m_pAutomatonController = m_pXMLAutomatonReader->getAutomatonController();

			m_pAutomatonContext = m_pAutomatonController->getAutomatonContext();

			//we don't need the XML reader anymore
			releaseXMLAutomatonReader(m_pXMLAutomatonReader);

			m_pStimulationOutputWriterHelper->writeHeader(*m_pWriter);
			getBoxAlgorithmContext()->getDynamicBoxContext()->markOutputAsReadyToSend(0, 0, 0);

			return true;
		}

		boolean CXMLStimulationScenarioPlayer::uninitialize()
		{
			if(m_pStimulationReaderCallBack)
			{
				releaseBoxAlgorithmStimulationInputReaderCallback(m_pStimulationReaderCallBack);
				m_pStimulationReaderCallBack=NULL;
			}

			delete m_pOutputWriterCallbackProxy;
			m_pOutputWriterCallbackProxy=NULL;

			if(m_pWriter)
			{
				m_pWriter->release();
				m_pWriter = NULL;
			}

			if(m_pStimulationOutputWriterHelper)
			{
				releaseBoxAlgorithmStimulationOutputWriter(m_pStimulationOutputWriterHelper);
				m_pStimulationOutputWriterHelper=NULL;
			}

			if(m_pAutomatonController)
			{
				releaseAutomatonController(m_pAutomatonController);
				m_pAutomatonController=NULL;
			}

			if(m_pAutomatonContext)
			{
				releaseAutomatonContext(m_pAutomatonContext);
				m_pAutomatonContext=NULL;
			}

			return true;
		}

		boolean CXMLStimulationScenarioPlayer::processInput(uint32 ui32InputIndex)
		{
			IDynamicBoxContext* l_pDynamicBoxContext=getBoxAlgorithmContext()->getDynamicBoxContext();

			for(uint32 i=0; i<l_pDynamicBoxContext->getInputChunkCount(ui32InputIndex); i++)
			{
				uint64 l_ui64StartTime;
				uint64 l_ui64EndTime;
				uint64 l_ui64ChunkSize;
				const uint8* l_pChunkBuffer=NULL;

				if(l_pDynamicBoxContext->getInputChunk(ui32InputIndex, i, l_ui64StartTime, l_ui64EndTime, l_ui64ChunkSize, l_pChunkBuffer))
				{
					m_pReader->processData(l_pChunkBuffer, l_ui64ChunkSize);
				}
				l_pDynamicBoxContext->markInputAsDeprecated(ui32InputIndex, i);
			}

			getBoxAlgorithmContext()->markAlgorithmAsReadyToProcess();

			return true;
		}

		boolean CXMLStimulationScenarioPlayer::processClock(CMessageClock &rMessageClock)
		{
			uint64 l_ui64CurrentTime = rMessageClock.getTime();

			IDynamicBoxContext * l_pDynamicBoxContext = getBoxAlgorithmContext()->getDynamicBoxContext();

			if(!m_bEndOfAutomaton)
			{
				//actualize context
				m_pAutomatonContext->setCurrentTime(rMessageClock.getTime());

				for(size_t i=0 ; i<m_oStimulationReceived.size() ; i++)
				{
					Automaton::CIdentifier l_oStimulationIdentifier = m_oStimulationReceived[i].first;
					m_pAutomatonContext->addReceivedEvent(l_oStimulationIdentifier);
				}

				//process
				m_bEndOfAutomaton = m_pAutomatonController->process();

				const Automaton::CIdentifier * l_pSentEvents = m_pAutomatonContext->getSentEvents();

				//set the number of stimulation to send
				m_pStimulationOutputWriterHelper->setStimulationCount(m_pAutomatonContext->getSentEventsCount());

				//if there were stimulations
				if(l_pSentEvents)
				{
					//adds em
					for(uint32 i = 0 ; i<m_pAutomatonContext->getSentEventsCount() ; i++)
					{
						/* TODO check Stimulation date */
						m_pStimulationOutputWriterHelper->setStimulation(i, l_pSentEvents[i], l_ui64CurrentTime);
					}

				}

				m_pStimulationOutputWriterHelper->writeBuffer(*m_pWriter);

				/* TODO check Stimulation date */
				l_pDynamicBoxContext->markOutputAsReadyToSend(0, m_ui64PreviousActivationTime, l_ui64CurrentTime);

				m_pAutomatonContext->clearSentEvents();

				//TODO clear all events?? or just used ones?
				m_pAutomatonContext->clearReceivedEvents();
			}

			m_ui64PreviousActivationTime = l_ui64CurrentTime;

			getBoxAlgorithmContext()->markAlgorithmAsReadyToProcess();

			return true;
		}

		boolean CXMLStimulationScenarioPlayer::process()
		{
			// l_pDynamicBoxContext->markOutputAsReadyToSend(0, 0, 0);
			return true;
		}

	};

};

<|endoftext|>