<commit_before>//=============================================================================================================
/**
 * @file     settingscontrollergui.cpp
 * @author   Juan GPC <juangpc@gmail.com>
 * @since    0.1.0
 * @date     May, 2020
 *
 * @section  LICENSE
 *
 * Copyright (C) 2020, Juan GPC. 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    SettingsControllerGUI class definition.
 *
 */

//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "settingscontrollergui.h"
#include "mainwindow.h"

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

#include <QDir>
#include <QStandardPaths>

//=============================================================================================================
// EIGEN INCLUDES
//=============================================================================================================

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

using namespace MNEANONYMIZE;

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

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

SettingsControllerGui::SettingsControllerGui(const QStringList& arguments)
: m_pWin(QSharedPointer<MainWindow> (new MainWindow(this)))
{
    initParser();
    parseInputs(arguments);
    setupCommunication();

    initializeOptionsState();

    m_pWin->show();

    if(m_pAnonymizer->isFileInSet())
    {
        readData();
    }
}

void SettingsControllerGui::executeAnonymizer()
{
    m_pAnonymizer->anonymizeFile();
}

void SettingsControllerGui::readData()
{
    //set output to a randomFilename
    QString stringTempDir(QStandardPaths::writableLocation(QStandardPaths::TempLocation));
    QString fileOutStr(QDir(stringTempDir).filePath(generateRandomFileName()));
    m_pAnonymizer->setFileOut(fileOutStr);
    m_pAnonymizer->anonymizeFile();
    QFile fileOut(fileOutStr);
    fileOut.remove();
    m_pAnonymizer->setFileOut(m_fiOutFileInfo.absoluteFilePath());
}

void SettingsControllerGui::fileInChanged(const QString& strInFile)
{
    QFileInfo newfiInFile(strInFile);

    if(newfiInFile.isDir())
    {
        m_pWin->showMessage("Invalid input file. That's a directory");
        m_pWin->setLineEditInFile(m_fiInFileInfo.absoluteFilePath());
        return;
    }
    if(QString::compare(newfiInFile.suffix(),QString("fif")) != 0)
    {
        m_pWin->showMessage("The input file extension must be \".fif\" 0.");
        m_pWin->setLineEditOutFile(m_fiOutFileInfo.absoluteFilePath());
        return;
    }
    QFileInfo inDir(newfiInFile.absolutePath());
    if(!inDir.isReadable())
    {
        m_pWin->showMessage("You might not have reading permissions to this folder");
        m_pWin->setLineEditInFile(m_fiInFileInfo.absoluteFilePath());
        return;
    }

    if( m_fiInFileInfo != newfiInFile )
    {
        m_fiInFileInfo.setFile(strInFile);
        m_pAnonymizer->setFileIn(m_fiInFileInfo.absoluteFilePath());

        if(m_fiInFileInfo.isFile() && m_fiInFileInfo.isReadable())
        {
            readData();
        }
    generateDefaultOutputFileName();
    m_pWin->setLineEditInFile(m_fiOutFileInfo.absoluteFilePath());
    }
}

void SettingsControllerGui::fileOutChanged(const QString& strOutFile)
{
    QFileInfo newfiOutFile(strOutFile);
    if(m_fiOutFileInfo.isDir())
    {
        m_pWin->showMessage("Invalid output file. That's a directory!");
        m_pWin->setLineEditOutFile(m_fiOutFileInfo.absoluteFilePath());
        return;
    }

    if(QString::compare(newfiOutFile.suffix(),QString("fif")) != 0)
    {
        m_pWin->showMessage("The output file extension must be \".fif\" 0.");
        m_pWin->setLineEditOutFile(m_fiOutFileInfo.absoluteFilePath());
        return;
    }

    QFileInfo outDir(newfiOutFile.absolutePath());
    if(!outDir.isWritable())
    {
        m_pWin->showMessage("You might not have writing permissions to this folder");
        m_pWin->setLineEditOutFile(m_fiOutFileInfo.absoluteFilePath());
        return;
    }

    if(m_fiOutFileInfo != newfiOutFile)
    {
        m_fiOutFileInfo.setFile(strOutFile);
        m_pAnonymizer->setFileOut(m_fiOutFileInfo.absoluteFilePath());
    }
}

void SettingsControllerGui::setupCommunication()
{

    //from view to model
    QObject::connect(m_pWin.data(),&MainWindow::fileInChanged,
                     this,&SettingsControllerGui::fileInChanged);
    QObject::connect(m_pWin.data(),&MainWindow::fileOutChanged,
                     this,&SettingsControllerGui::fileOutChanged);

    QObject::connect(m_pWin.data(),&MainWindow::fileOutChanged,
                     m_pAnonymizer.data(),&FiffAnonymizer::setFileOut);
    QObject::connect(m_pWin.data(),&MainWindow::fileOutChanged,
                     m_pAnonymizer.data(),&FiffAnonymizer::setFileOut);
    QObject::connect(m_pWin.data(),&MainWindow::fileOutChanged,
                     m_pAnonymizer.data(),&FiffAnonymizer::setFileOut);
    QObject::connect(m_pWin.data(),&MainWindow::fileOutChanged,
                     m_pAnonymizer.data(),&FiffAnonymizer::setFileOut);
    QObject::connect(m_pWin.data(),&MainWindow::fileOutChanged,
                     m_pAnonymizer.data(),&FiffAnonymizer::setFileOut);
    QObject::connect(m_pWin.data(),&MainWindow::fileOutChanged,
                     m_pAnonymizer.data(),&FiffAnonymizer::setFileOut);
    QObject::connect(m_pWin.data(),&MainWindow::fileOutChanged,
                     m_pAnonymizer.data(),&FiffAnonymizer::setFileOut);
    QObject::connect(m_pWin.data(),&MainWindow::fileOutChanged,
                     m_pAnonymizer.data(),&FiffAnonymizer::setFileOut);

    //from model to view
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingIdFileVersion,
                     m_pWin.data(),&MainWindow::setLineEditIdFileVersion);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingIdMeasurementDate,
                     m_pWin.data(),&MainWindow::setLineEditIdMeasurementDate);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingIdMac,
                     m_pWin.data(),&MainWindow::setLineEditIdMacAddress);

    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingFileMeasurementDate,
                     m_pWin.data(),&MainWindow::setLineEditFileMeasurementDate);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingFileComment,
                     m_pWin.data(),&MainWindow::setLineEditFileComment);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingFileExperimenter,
                     m_pWin.data(),&MainWindow::setLineEditFileExperimenter);

    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectId,
                     m_pWin.data(),&MainWindow::setLineEditSubjectId);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectFirstName,
                     m_pWin.data(),&MainWindow::setLineEditSubjectFirstName);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectMiddleName,
                     m_pWin.data(),&MainWindow::setLineEditSubjectMiddleName);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectLastName,
                     m_pWin.data(),&MainWindow::setLineEditSubjectLastName);

    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectBirthday,
                     m_pWin.data(),&MainWindow::setLineEditSubjectBirthday);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectSex,
                     m_pWin.data(),&MainWindow::setLineEditSubjectSex);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectHand,
                     m_pWin.data(),&MainWindow::setLineEditSubjectHand);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectWeight,
                     m_pWin.data(),&MainWindow::setLineEditSubjectHand);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectHeight,
                     m_pWin.data(),&MainWindow::setLineEditSubjectHeight);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectComment,
                     m_pWin.data(),&MainWindow::setLineEditSubjectComment);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectHisId,
                     m_pWin.data(),&MainWindow::setLineEditSubjectHisId);

    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingProjectId,
                     m_pWin.data(),&MainWindow::setLineEditProjectId);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingProjectName,
                     m_pWin.data(),&MainWindow::setLineEditProjectName);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingProjectAim,
                     m_pWin.data(),&MainWindow::setLineEditProjectAim);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingProjectPersons,
                     m_pWin.data(),&MainWindow::setLineEditProjectPersons);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingProjectComment,
                     m_pWin.data(),&MainWindow::setLineEditProjectComment);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::mriDataFoundInFile,
                     m_pWin.data(),&MainWindow::setLabelMriDataFoundVisible);
}

void SettingsControllerGui::initializeOptionsState()
{
    m_pWin->setLineEditInFile(m_fiInFileInfo.absoluteFilePath());
    m_pWin->setLineEditOutFile(m_fiOutFileInfo.absoluteFilePath());

    m_pWin->setCheckBoxBruteMode(m_pAnonymizer->getBruteMode());
//    m_pWin->setCheckBoxDeleteInputFileAfter(m_bDeleteInputFileAfter);
//    m_pWin->setCheckBoxAvoidDeleteConfirmation(m_bDeleteInputFileConfirmation);
    m_pWin->setMeasurementDate(m_pAnonymizer->getMeasurementDate());
    m_pWin->setCheckBoxMeasurementDateOffset(m_pAnonymizer->getUseMeasurementDayOffset());
    m_pWin->setMeasurementDateOffset(m_pAnonymizer->getMeasurementDayOffset());
    m_pWin->setCheckBoxSubjectBirthdayOffset(m_pAnonymizer->getUseSubjectBirthdayOffset());
    m_pWin->setSubjectBirthdayOffset(m_pAnonymizer->getSubjectBirthdayOffset());
    if(m_bHisIdSpecified)
    {
        m_pWin->setSubjectHis(m_pAnonymizer->getSubjectHisID());
    }
}
<commit_msg>parse command inputs to gui options<commit_after>//=============================================================================================================
/**
 * @file     settingscontrollergui.cpp
 * @author   Juan GPC <juangpc@gmail.com>
 * @since    0.1.0
 * @date     May, 2020
 *
 * @section  LICENSE
 *
 * Copyright (C) 2020, Juan GPC. 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    SettingsControllerGUI class definition.
 *
 */

//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "settingscontrollergui.h"
#include "mainwindow.h"

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

#include <QDir>
#include <QStandardPaths>

//=============================================================================================================
// EIGEN INCLUDES
//=============================================================================================================

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

using namespace MNEANONYMIZE;

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

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

SettingsControllerGui::SettingsControllerGui(const QStringList& arguments)
: m_pWin(QSharedPointer<MainWindow> (new MainWindow(this)))
{
    initParser();
    parseInputs(arguments);
    setupCommunication();

    initializeOptionsState();

    m_pWin->show();

    if(m_pAnonymizer->isFileInSet())
    {
        readData();
    }
}

void SettingsControllerGui::executeAnonymizer()
{
    m_pAnonymizer->anonymizeFile();
}

void SettingsControllerGui::readData()
{
    //set output to a randomFilename
    QString stringTempDir(QStandardPaths::writableLocation(QStandardPaths::TempLocation));
    QString fileOutStr(QDir(stringTempDir).filePath(generateRandomFileName()));
    m_pAnonymizer->setFileOut(fileOutStr);
    m_pAnonymizer->anonymizeFile();
    QFile fileOut(fileOutStr);
    fileOut.remove();
    m_pAnonymizer->setFileOut(m_fiOutFileInfo.absoluteFilePath());
}

void SettingsControllerGui::fileInChanged(const QString& strInFile)
{
    QFileInfo newfiInFile(strInFile);

    if(newfiInFile.isDir())
    {
        m_pWin->showMessage("Invalid input file. That's a directory");
        m_pWin->setLineEditInFile(m_fiInFileInfo.absoluteFilePath());
        return;
    }
    if(QString::compare(newfiInFile.suffix(),QString("fif")) != 0)
    {
        m_pWin->showMessage("The input file extension must be \".fif\" 0.");
        m_pWin->setLineEditOutFile(m_fiOutFileInfo.absoluteFilePath());
        return;
    }
    QFileInfo inDir(newfiInFile.absolutePath());
    if(!inDir.isReadable())
    {
        m_pWin->showMessage("You might not have reading permissions to this folder");
        m_pWin->setLineEditInFile(m_fiInFileInfo.absoluteFilePath());
        return;
    }

    if( m_fiInFileInfo != newfiInFile )
    {
        m_fiInFileInfo.setFile(strInFile);
        m_pAnonymizer->setFileIn(m_fiInFileInfo.absoluteFilePath());

        if(m_fiInFileInfo.isFile() && m_fiInFileInfo.isReadable())
        {
            readData();
        }
    generateDefaultOutputFileName();
    m_pWin->setLineEditInFile(m_fiOutFileInfo.absoluteFilePath());
    }
}

void SettingsControllerGui::fileOutChanged(const QString& strOutFile)
{
    QFileInfo newfiOutFile(strOutFile);
    if(m_fiOutFileInfo.isDir())
    {
        m_pWin->showMessage("Invalid output file. That's a directory!");
        m_pWin->setLineEditOutFile(m_fiOutFileInfo.absoluteFilePath());
        return;
    }

    if(QString::compare(newfiOutFile.suffix(),QString("fif")) != 0)
    {
        m_pWin->showMessage("The output file extension must be \".fif\" 0.");
        m_pWin->setLineEditOutFile(m_fiOutFileInfo.absoluteFilePath());
        return;
    }

    QFileInfo outDir(newfiOutFile.absolutePath());
    if(!outDir.isWritable())
    {
        m_pWin->showMessage("You might not have writing permissions to this folder");
        m_pWin->setLineEditOutFile(m_fiOutFileInfo.absoluteFilePath());
        return;
    }

    if(m_fiOutFileInfo != newfiOutFile)
    {
        m_fiOutFileInfo.setFile(strOutFile);
        m_pAnonymizer->setFileOut(m_fiOutFileInfo.absoluteFilePath());
    }
}

void SettingsControllerGui::setupCommunication()
{

    //from view to model
    QObject::connect(m_pWin.data(),&MainWindow::fileInChanged,
                     this,&SettingsControllerGui::fileInChanged);
    QObject::connect(m_pWin.data(),&MainWindow::fileOutChanged,
                     this,&SettingsControllerGui::fileOutChanged);

    QObject::connect(m_pWin.data(),&MainWindow::fileOutChanged,
                     m_pAnonymizer.data(),&FiffAnonymizer::setFileOut);
    QObject::connect(m_pWin.data(),&MainWindow::fileOutChanged,
                     m_pAnonymizer.data(),&FiffAnonymizer::setFileOut);
    QObject::connect(m_pWin.data(),&MainWindow::fileOutChanged,
                     m_pAnonymizer.data(),&FiffAnonymizer::setFileOut);
    QObject::connect(m_pWin.data(),&MainWindow::fileOutChanged,
                     m_pAnonymizer.data(),&FiffAnonymizer::setFileOut);
    QObject::connect(m_pWin.data(),&MainWindow::fileOutChanged,
                     m_pAnonymizer.data(),&FiffAnonymizer::setFileOut);
    QObject::connect(m_pWin.data(),&MainWindow::fileOutChanged,
                     m_pAnonymizer.data(),&FiffAnonymizer::setFileOut);
    QObject::connect(m_pWin.data(),&MainWindow::fileOutChanged,
                     m_pAnonymizer.data(),&FiffAnonymizer::setFileOut);
    QObject::connect(m_pWin.data(),&MainWindow::fileOutChanged,
                     m_pAnonymizer.data(),&FiffAnonymizer::setFileOut);

    //from model to view
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingIdFileVersion,
                     m_pWin.data(),&MainWindow::setLineEditIdFileVersion);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingIdMeasurementDate,
                     m_pWin.data(),&MainWindow::setLineEditIdMeasurementDate);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingIdMac,
                     m_pWin.data(),&MainWindow::setLineEditIdMacAddress);

    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingFileMeasurementDate,
                     m_pWin.data(),&MainWindow::setLineEditFileMeasurementDate);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingFileComment,
                     m_pWin.data(),&MainWindow::setLineEditFileComment);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingFileExperimenter,
                     m_pWin.data(),&MainWindow::setLineEditFileExperimenter);

    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectId,
                     m_pWin.data(),&MainWindow::setLineEditSubjectId);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectFirstName,
                     m_pWin.data(),&MainWindow::setLineEditSubjectFirstName);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectMiddleName,
                     m_pWin.data(),&MainWindow::setLineEditSubjectMiddleName);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectLastName,
                     m_pWin.data(),&MainWindow::setLineEditSubjectLastName);

    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectBirthday,
                     m_pWin.data(),&MainWindow::setLineEditSubjectBirthday);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectSex,
                     m_pWin.data(),&MainWindow::setLineEditSubjectSex);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectHand,
                     m_pWin.data(),&MainWindow::setLineEditSubjectHand);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectWeight,
                     m_pWin.data(),&MainWindow::setLineEditSubjectHand);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectHeight,
                     m_pWin.data(),&MainWindow::setLineEditSubjectHeight);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectComment,
                     m_pWin.data(),&MainWindow::setLineEditSubjectComment);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingSubjectHisId,
                     m_pWin.data(),&MainWindow::setLineEditSubjectHisId);

    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingProjectId,
                     m_pWin.data(),&MainWindow::setLineEditProjectId);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingProjectName,
                     m_pWin.data(),&MainWindow::setLineEditProjectName);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingProjectAim,
                     m_pWin.data(),&MainWindow::setLineEditProjectAim);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingProjectPersons,
                     m_pWin.data(),&MainWindow::setLineEditProjectPersons);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::readingProjectComment,
                     m_pWin.data(),&MainWindow::setLineEditProjectComment);
    QObject::connect(m_pAnonymizer.data(),&FiffAnonymizer::mriDataFoundInFile,
                     m_pWin.data(),&MainWindow::setLabelMriDataFoundVisible);
}

void SettingsControllerGui::initializeOptionsState()
{
    if(m_pAnonymizer->isFileInSet())
    {
        m_pWin->setLineEditInFile(m_fiInFileInfo.absoluteFilePath());
    }
    if(m_pAnonymizer->isFileOutSet())
    {
        m_pWin->setLineEditOutFile(m_fiOutFileInfo.absoluteFilePath());
    }

    m_pWin->setCheckBoxBruteMode(m_pAnonymizer->getBruteMode());
    m_pWin->setMeasurementDate(m_pAnonymizer->getMeasurementDate());
    m_pWin->setCheckBoxMeasurementDateOffset(m_pAnonymizer->getUseMeasurementDayOffset());
    m_pWin->setMeasurementDateOffset(m_pAnonymizer->getMeasurementDayOffset());
    m_pWin->setCheckBoxSubjectBirthdayOffset(m_pAnonymizer->getUseSubjectBirthdayOffset());
    m_pWin->setSubjectBirthdayOffset(m_pAnonymizer->getSubjectBirthdayOffset());
    if(m_bHisIdSpecified)
    {
        m_pWin->setSubjectHis(m_pAnonymizer->getSubjectHisID());
    }
}
<|endoftext|>


<commit_before>#include "Configuration.hpp"

#include <QTreeWidget>
#include <QTreeWidgetItem>

#include <stdio.h>
#include <assert.h>

#include <iostream>

std::list<Configurable*>* Configurable::_configurables;

// Role for tree column zero for storing ConfigItem pointers.
static const int ConfigItemRole = Qt::UserRole;

Q_DECLARE_METATYPE(ConfigItem*)  // FIXME: verify this

ConfigItem::ConfigItem(Configuration* config, const QString& name,
                       std::string description) {
    _config = config;
    _treeItem = nullptr;
    _path = name.split('/');
    _description = description;
}

ConfigItem::~ConfigItem() {
    if (_treeItem) {
        // FIXME - Things are getting deleted in a non-GUI thread
        // 		delete _treeItem;
        _treeItem = nullptr;
    }
}

void ConfigItem::valueChanged(const QString& str) {
    if (_treeItem) {
        _treeItem->setText(1, str);
    }
}

void ConfigItem::setupItem() { _treeItem->setText(1, toString()); }

////////

ConfigBool::ConfigBool(Configuration* tree, QString name, bool value,
                       std::string description)
    : ConfigItem(tree, name, description) {
    _value = value;
    addItem();
}

QString ConfigBool::toString() { return _value ? "true" : "false"; }

bool ConfigBool::value() {
    if (_treeItem) {
        _value = _treeItem->checkState(1) == Qt::Checked;
    }
    return _value;
}

void ConfigBool::setValue(const QString& str) {
    if (str == "true") {
        _value = true;
    } else if (str == "false") {
        _value = false;
    } else {
        // Use what's in the tree in case this was called because the user
        // clicked on it
        _value = (_treeItem->checkState(1) == Qt::Checked);
    }
    setupItem();
}

void ConfigBool::setupItem() {
    if (_treeItem) {
        _treeItem->setCheckState(1, _value ? Qt::Checked : Qt::Unchecked);
        // FIXME - Can't change the checkbox anymore.  Why not?
        _treeItem->setFlags(_treeItem->flags() | Qt::ItemIsUserCheckable);
    }
}

////////

ConfigInt::ConfigInt(Configuration* config, QString name, int value,
                     std::string description)
    : ConfigItem(config, name, description) {
    _value = value;
    addItem();
}

QString ConfigInt::toString() { return QString::number(_value); }

void ConfigInt::setValue(const QString& str) { _value = str.toInt(); }

////////

ConfigDouble::ConfigDouble(Configuration* config, QString name, double value,
                           std::string description)
    : ConfigItem(config, name, description) {
    _value = value;
    addItem();
}

QString ConfigDouble::toString() { return QString::number(_value); }

void ConfigDouble::setValue(const QString& str) { _value = str.toDouble(); }

Configuration::Configuration() {
    _tree = nullptr;

    // Create the XML root element
    _doc.appendChild(_doc.createElement("config"));
}

std::shared_ptr<Configuration> Configuration::FromRegisteredConfigurables() {
    std::shared_ptr<Configuration> config = std::make_shared<Configuration>();
    for (Configurable* obj : Configurable::configurables()) {
        obj->createConfiguration(config.get());
    }
    return config;
}

void Configuration::addItem(ConfigItem* item) {
    _allItems.push_back(item);

    if (_tree) {
        addToTree(item);
    }
}

void Configuration::addToTree(ConfigItem* item) {
    // Find the parent of this item by following the tree through all but the
    // last item in the path
    QTreeWidgetItem* parent = _tree->invisibleRootItem();
    const QStringList& path = item->path();
    QStringList::const_iterator last = path.end();
    --last;
    for (QStringList::const_iterator i = path.begin(); i != last; ++i) {
        QTreeWidgetItem* next = nullptr;
        for (int j = 0; j < parent->childCount(); ++j) {
            QTreeWidgetItem* child = parent->child(j);
            if (child->text(0) == *i) {
                next = child;
                break;
            }
        }

        if (!next) {
            // Create this item
            next = new QTreeWidgetItem(parent);
            next->setText(0, *i);
        }

        parent = next;
    }

    // Create a tree item
    item->_treeItem = new QTreeWidgetItem(parent);
    item->_treeItem->setFlags(item->_treeItem->flags() | Qt::ItemIsEditable);
    item->_treeItem->setData(0, ConfigItemRole, QVariant::fromValue(item));
    item->_treeItem->setText(0, path.back());

    if (item->_description != "") {
        item->_treeItem->setToolTip(0, QString(item->_description.c_str()));
    }

    item->setupItem();
}

void Configuration::tree(QTreeWidget* tree) {
    assert(!_tree);

    _tree = tree;
    connect(_tree, SIGNAL(itemChanged(QTreeWidgetItem*, int)), this,
            SLOT(itemChanged(QTreeWidgetItem*, int)));

    // Add items that were created before we got a tree
    for (ConfigItem* item : _allItems) {
        addToTree(item);
    }
}

ConfigItem* Configuration::configItem(QTreeWidgetItem* ti) {
    return ti->data(0, ConfigItemRole).value<ConfigItem*>();
}

void Configuration::itemChanged(QTreeWidgetItem* item, int column) {
    if (column == 1) {
        ConfigItem* ci = configItem(item);
        if (ci) {
            ci->setValue(item->text(1));
        }
    }
}

ConfigItem* Configuration::nameLookup(const QString& name) const {
    QStringList path = name.split('/');
    for (ConfigItem* item : _allItems) {
        if (item->path() == path) {
            return item;
        }
    }
    return nullptr;
}

bool Configuration::load(const QString& filename, QString& error) {
    QFile file(filename);
    if (!file.open(QFile::ReadOnly)) {
        error = file.errorString();
        return false;
    }

    QDomDocument newDoc;
    QString domError;
    int errorLine = 0, errorColumn = 0;
    if (!newDoc.setContent(&file, &domError, &errorLine, &errorColumn)) {
        error = QString("%1:%2: %3")
                    .arg(QString::number(errorLine),
                         QString::number(errorColumn), domError);
        return false;
    }

    QDomElement root = newDoc.firstChildElement("config");
    if (root.isNull()) {
        error = "XML does not contain root <config> element";
        return false;
    }

    _doc = newDoc;
    for (ConfigItem* item : _allItems) {
        QDomElement el = root;
        for (QString str : item->path()) {
            bool isInt = false;
            int value = str.toInt(&isInt);
            if (isInt) {
                str = QString("item%1").arg(value);
            } else {
                // Sanitize the string
                str.replace(' ', '_');
            }

            // Find the element for the next part of the path
            el = el.firstChildElement(str);
            if (el.isNull()) {
                break;
            }
        }

        if (!el.isNull()) {
            QString str = el.attribute("value");
            if (!str.isNull()) {
                item->setValue(str);
                item->valueChanged(str);
            }
        }
    }

    return true;
}

bool Configuration::save(const QString& filename, QString& error) {
    QFile file(filename);
    if (!file.open(QFile::WriteOnly)) {
        error = file.errorString();
        return false;
    }

    QDomElement root = _doc.firstChildElement("config");

    // Update the DOM
    // FIXME - Remove superfluous vector elements
    for (ConfigItem* item : _allItems) {
        QDomElement el = root;
        for (QString str : item->path()) {
            bool isInt = false;
            int value = str.toInt(&isInt);
            if (isInt) {
                str = QString("item%1").arg(value);
            } else {
                // Sanitize the string
                str.replace(' ', '_');
            }

            // Find the element for the next part of the path
            QDomElement child = el.firstChildElement(str);
            if (child.isNull()) {
                child = _doc.createElement(str);
                el.appendChild(child);
            }

            el = child;
        }

        // Set the value
        el.setAttribute("value", item->toString());
    }

    // Write XML
    QByteArray data = _doc.toByteArray();
    bool ok = (file.write(data) == data.size());
    if (!ok) {
        // Didn't write all the data
        error = file.errorString();
    }

    return ok;
}

Configurable::Configurable() {
    if (!_configurables) {
        _configurables = new std::list<Configurable*>();
    }

    _configurables->push_back(this);
}

const std::list<Configurable*>& Configurable::configurables() {
    if (!_configurables) {
        _configurables = new std::list<Configurable*>();
    }

    return *_configurables;
}
<commit_msg>removed unnecessary iostream include from Configuration.cpp<commit_after>#include "Configuration.hpp"

#include <QTreeWidget>
#include <QTreeWidgetItem>

#include <stdio.h>
#include <assert.h>

std::list<Configurable*>* Configurable::_configurables;

// Role for tree column zero for storing ConfigItem pointers.
static const int ConfigItemRole = Qt::UserRole;

Q_DECLARE_METATYPE(ConfigItem*)  // FIXME: verify this

ConfigItem::ConfigItem(Configuration* config, const QString& name,
                       std::string description) {
    _config = config;
    _treeItem = nullptr;
    _path = name.split('/');
    _description = description;
}

ConfigItem::~ConfigItem() {
    if (_treeItem) {
        // FIXME - Things are getting deleted in a non-GUI thread
        // 		delete _treeItem;
        _treeItem = nullptr;
    }
}

void ConfigItem::valueChanged(const QString& str) {
    if (_treeItem) {
        _treeItem->setText(1, str);
    }
}

void ConfigItem::setupItem() { _treeItem->setText(1, toString()); }

////////

ConfigBool::ConfigBool(Configuration* tree, QString name, bool value,
                       std::string description)
    : ConfigItem(tree, name, description) {
    _value = value;
    addItem();
}

QString ConfigBool::toString() { return _value ? "true" : "false"; }

bool ConfigBool::value() {
    if (_treeItem) {
        _value = _treeItem->checkState(1) == Qt::Checked;
    }
    return _value;
}

void ConfigBool::setValue(const QString& str) {
    if (str == "true") {
        _value = true;
    } else if (str == "false") {
        _value = false;
    } else {
        // Use what's in the tree in case this was called because the user
        // clicked on it
        _value = (_treeItem->checkState(1) == Qt::Checked);
    }
    setupItem();
}

void ConfigBool::setupItem() {
    if (_treeItem) {
        _treeItem->setCheckState(1, _value ? Qt::Checked : Qt::Unchecked);
        // FIXME - Can't change the checkbox anymore.  Why not?
        _treeItem->setFlags(_treeItem->flags() | Qt::ItemIsUserCheckable);
    }
}

////////

ConfigInt::ConfigInt(Configuration* config, QString name, int value,
                     std::string description)
    : ConfigItem(config, name, description) {
    _value = value;
    addItem();
}

QString ConfigInt::toString() { return QString::number(_value); }

void ConfigInt::setValue(const QString& str) { _value = str.toInt(); }

////////

ConfigDouble::ConfigDouble(Configuration* config, QString name, double value,
                           std::string description)
    : ConfigItem(config, name, description) {
    _value = value;
    addItem();
}

QString ConfigDouble::toString() { return QString::number(_value); }

void ConfigDouble::setValue(const QString& str) { _value = str.toDouble(); }

Configuration::Configuration() {
    _tree = nullptr;

    // Create the XML root element
    _doc.appendChild(_doc.createElement("config"));
}

std::shared_ptr<Configuration> Configuration::FromRegisteredConfigurables() {
    std::shared_ptr<Configuration> config = std::make_shared<Configuration>();
    for (Configurable* obj : Configurable::configurables()) {
        obj->createConfiguration(config.get());
    }
    return config;
}

void Configuration::addItem(ConfigItem* item) {
    _allItems.push_back(item);

    if (_tree) {
        addToTree(item);
    }
}

void Configuration::addToTree(ConfigItem* item) {
    // Find the parent of this item by following the tree through all but the
    // last item in the path
    QTreeWidgetItem* parent = _tree->invisibleRootItem();
    const QStringList& path = item->path();
    QStringList::const_iterator last = path.end();
    --last;
    for (QStringList::const_iterator i = path.begin(); i != last; ++i) {
        QTreeWidgetItem* next = nullptr;
        for (int j = 0; j < parent->childCount(); ++j) {
            QTreeWidgetItem* child = parent->child(j);
            if (child->text(0) == *i) {
                next = child;
                break;
            }
        }

        if (!next) {
            // Create this item
            next = new QTreeWidgetItem(parent);
            next->setText(0, *i);
        }

        parent = next;
    }

    // Create a tree item
    item->_treeItem = new QTreeWidgetItem(parent);
    item->_treeItem->setFlags(item->_treeItem->flags() | Qt::ItemIsEditable);
    item->_treeItem->setData(0, ConfigItemRole, QVariant::fromValue(item));
    item->_treeItem->setText(0, path.back());

    if (item->_description != "") {
        item->_treeItem->setToolTip(0, QString(item->_description.c_str()));
    }

    item->setupItem();
}

void Configuration::tree(QTreeWidget* tree) {
    assert(!_tree);

    _tree = tree;
    connect(_tree, SIGNAL(itemChanged(QTreeWidgetItem*, int)), this,
            SLOT(itemChanged(QTreeWidgetItem*, int)));

    // Add items that were created before we got a tree
    for (ConfigItem* item : _allItems) {
        addToTree(item);
    }
}

ConfigItem* Configuration::configItem(QTreeWidgetItem* ti) {
    return ti->data(0, ConfigItemRole).value<ConfigItem*>();
}

void Configuration::itemChanged(QTreeWidgetItem* item, int column) {
    if (column == 1) {
        ConfigItem* ci = configItem(item);
        if (ci) {
            ci->setValue(item->text(1));
        }
    }
}

ConfigItem* Configuration::nameLookup(const QString& name) const {
    QStringList path = name.split('/');
    for (ConfigItem* item : _allItems) {
        if (item->path() == path) {
            return item;
        }
    }
    return nullptr;
}

bool Configuration::load(const QString& filename, QString& error) {
    QFile file(filename);
    if (!file.open(QFile::ReadOnly)) {
        error = file.errorString();
        return false;
    }

    QDomDocument newDoc;
    QString domError;
    int errorLine = 0, errorColumn = 0;
    if (!newDoc.setContent(&file, &domError, &errorLine, &errorColumn)) {
        error = QString("%1:%2: %3")
                    .arg(QString::number(errorLine),
                         QString::number(errorColumn), domError);
        return false;
    }

    QDomElement root = newDoc.firstChildElement("config");
    if (root.isNull()) {
        error = "XML does not contain root <config> element";
        return false;
    }

    _doc = newDoc;
    for (ConfigItem* item : _allItems) {
        QDomElement el = root;
        for (QString str : item->path()) {
            bool isInt = false;
            int value = str.toInt(&isInt);
            if (isInt) {
                str = QString("item%1").arg(value);
            } else {
                // Sanitize the string
                str.replace(' ', '_');
            }

            // Find the element for the next part of the path
            el = el.firstChildElement(str);
            if (el.isNull()) {
                break;
            }
        }

        if (!el.isNull()) {
            QString str = el.attribute("value");
            if (!str.isNull()) {
                item->setValue(str);
                item->valueChanged(str);
            }
        }
    }

    return true;
}

bool Configuration::save(const QString& filename, QString& error) {
    QFile file(filename);
    if (!file.open(QFile::WriteOnly)) {
        error = file.errorString();
        return false;
    }

    QDomElement root = _doc.firstChildElement("config");

    // Update the DOM
    // FIXME - Remove superfluous vector elements
    for (ConfigItem* item : _allItems) {
        QDomElement el = root;
        for (QString str : item->path()) {
            bool isInt = false;
            int value = str.toInt(&isInt);
            if (isInt) {
                str = QString("item%1").arg(value);
            } else {
                // Sanitize the string
                str.replace(' ', '_');
            }

            // Find the element for the next part of the path
            QDomElement child = el.firstChildElement(str);
            if (child.isNull()) {
                child = _doc.createElement(str);
                el.appendChild(child);
            }

            el = child;
        }

        // Set the value
        el.setAttribute("value", item->toString());
    }

    // Write XML
    QByteArray data = _doc.toByteArray();
    bool ok = (file.write(data) == data.size());
    if (!ok) {
        // Didn't write all the data
        error = file.errorString();
    }

    return ok;
}

Configurable::Configurable() {
    if (!_configurables) {
        _configurables = new std::list<Configurable*>();
    }

    _configurables->push_back(this);
}

const std::list<Configurable*>& Configurable::configurables() {
    if (!_configurables) {
        _configurables = new std::list<Configurable*>();
    }

    return *_configurables;
}
<|endoftext|>


<commit_before>/************************************************************************************
**
* @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved.
*
*************************************************************************************/
/**
* @file		g_tcp_server.cpp
* @version
* @brief
* @author   duye
* @date     2014-09-30
* @note
*
*  1. 2014-09-30 duye Created this file
*
*/
#include <g_tcp_server.h>

namespace gcom {

TcpServer::TcpServer() {}
TcpServer::TcpServer(const IPPortPair& server_addr, const std::string& net_card)
	: NetworkServer(server_addr, net_card) {}
TcpServer::~TcpServer() {}

GResult TcpServer::start()
{
	return G_YES;
}

GResult TcpServer::start(const IPPortPair& server_addr, const std::string& net_card)
{
	setServerAddr(server_addr);
	setNetCard(net_card);
	return start();
}

GResult TcpServer::restart()
{
	if (state() != G_SERVER_WORK)
	{
		return start();
	}

	return G_YES;
}

GResult TcpServer::stop()
{
	return G_YES;
}

GResult TcpServer::routine()
{
	for (;;)
	{
		gsys::System::sleep(2);
	}

	return G_YES;
}
}
<commit_msg>Update g_tcp_server.cpp<commit_after>/************************************************************************************
**
* @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved.
*
*************************************************************************************/
/**
* @file	    g_tcp_server.cpp
* @version
* @brief
* @author   duye
* @date     2014-09-30
* @note
*
*  1. 2014-09-30 duye Created this file
*
*/
#include <g_socket.h>
#include <g_tcp_server.h>

namespace gcom {

static const GInt8* LOG_PREFIX = "gohoop.gcom.network.tcpserver";

TcpServer::TcpServer() : m_serverSocket(nullptr){}
TcpServer::TcpServer(const IPPortPair& server_addr, const std::string& net_card)
    : NetworkServer(server_addr, net_card)
    , m_serverSocket(nullptr) {}
TcpServer::~TcpServer()
{
    delete m_serverSocket;
    m_serverSocket = nullptr;
}

GResult TcpServer::start()
{
    if (server_addr.ipAddr().ipStr().empty())
    {
    	G_LOG_ERROR(LOG_PREFIX, "server address no setting");
    	return G_NO;
    }

    SocketInfo socket_info;
    socket_info.setProtocol(G_IPPROTO_TCP);
    socket_info.setServerIP(serverAddr().ipAddr().ip());
    socket_info.setServerPort(serverAddr().port());
    socket_info.setLocalIfName(netCard());

    m_serverSocket = new gsys::ServerSocket();
    if (IS_NO(m_serverSocket->bind(socket_info)))
    {
    	G_LOG_ERROR(LOG_PREFIX, "bind server address failed");
    	return G_NO;
    }

    if (IS_NO(m_serverSocket->listen()))
    {
    	G_LOG_ERROR(LOG_PREFIX, "listen server address failed");
    	return G_NO;
    }

    startTask();

    return G_YES;
}

GResult TcpServer::start(const IPPortPair& server_addr, const std::string& net_card)
{
    setServerAddr(server_addr);
    setNetCard(net_card);
    return start();
}

GResult TcpServer::restart()
{
    if (state() != G_SERVER_WORK)
    {
    	return start();
    }

    return G_YES;
}

GResult TcpServer::stop()
{
    return G_YES;
}

GResult TcpServer::routine()
{
    for (;;)
    {
    	SockAddr& client_addr;
    	if (IS_YES(m_serverSocket->accept(client_addr, )))
    	{
    	    G_LOG_INFO(LOG_PREFIX, "accept client address %s:%d", );
    	}

    	gsys::System::sleep(2);
    }

    return G_YES;
}
}
<|endoftext|>


<commit_before>/***********************************************************************************
**
* @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved.
*
************************************************************************************/
/**
* @file		g_logger_impl.cpp
* @version
* @brief
* @author	duye
* @date		2014-07-01
* @note
*
*  1. 2014-07-01 duye Created this file
*
*/
#include <stdio.h>
#include <g_file.h>
#include <g_logger_impl.h>

// the max buffer size of in one line
static const GUint64 DEF_ONE_LINE_BUF_SIZE = 1024;

// the configuration file name
static const GInt8* DEF_CONF_FILE_NAME = "glog.xml";

GLoggerImpl::GLoggerImpl()
{
	m_error[0] = 0;
}

GLoggerImpl::~GLoggerImpl()
{
}

GLoggerImpl* GLoggerImpl::GetInstance()
{
	static GLoggerImpl glogger;
	return &glogger;
}

GResult GLoggerImpl::init()
{
	m_logLevelMap.insert(std::make_pair(LOG_ERROR, "ERROR"));
	m_logLevelMap.insert(std::make_pair(LOG_WARN, "WARN"));
	m_logLevelMap.insert(std::make_pair(LOG_INFO, "INFO"));
	m_logLevelMap.insert(std::make_pair(LOG_DEBUG, "DEBUG"));
	m_logLevelMap.insert(std::make_pair(LOG_TRACE, "TRACE"));

	// read configuration file
	if (m_iniFile.loadFile(DEF_CONF_FILE_NAME) != G_YES)
	{
	    setError("load file '%s' failed", DEF_CONF_FILE_NAME);
	    return G_NO;
	}

	return G_YES;
}

GResult GLoggerImpl::uninit()
{
	return G_YES;
}

void GLoggerImpl::printLog(const GLogLevel logLevel,
	const GInt8* module,
	const GInt8* file,
	const GUint32 line,
	const GInt8* function,
	const GInt8* args, ...)
{
	ModuleRule* moduleRule = NULL;
	if (findModuleRule(std::string(module), moduleRule) == G_NO)
	{
		return;
	}

	if (logLevel > moduleRule->getLogLevel())
	{
		return;
	}

	GInt8 printBuf[DEF_ONE_LINE_BUF_SIZE] = {0};
	GUint64 pos = 0;

	// add log level and module name
	pos += sprintf(printBuf + pos, "<%s>[%s]", m_logLevelMap[logLevel], module);

	switch (moduleRule->getPrintLevel())
	{
	case PRINT_BASIC:
		break;
	case PRINT_MORE:
		// add file and function
		pos += sprintf(printBuf + pos, "(%s:%s)", file, function);
		break;
	case PRINT_FULL:
		// add file, line number and function
		pos += sprintf(printBuf + pos, "(%s:%s:%d)", file, function, line);
		break;
	default:
		return;
	}

	// add log content
	pos += GSys::format(printBuf + pos, DEF_ONE_LINE_BUF_SIZE - pos, args);

	// add word wrap
	if (m_globalRule.isWordWrap())
	{
		pos += sprintf(printBuf + pos, "\n");
	}

	printf("%s", printBuf);
}

GInt8* GLoggerImpl::getError()
{
	return m_error;
}

GResult GLoggerImpl::findModuleRule(const std::string& moduleName, ModuleRule*& moduleRule)
{
	GModuleRuleMap::iterator iter = m_moduleRuleMap.find(moduleName);
	if (iter == m_moduleRuleMap.end())
	{
		return G_NO;
	}

	moduleRule = iter->second;

	return G_YES;
}

void GLoggerImpl::setError(const GInt8* args, ...)
{
	GSys::format(m_error, G_ERROR_BUF_SIZE, args);
}

GlobalRule::GlobalRule() : m_fileSize(0), m_fileCount(0), m_isWordWrap(true)
{
}

GlobalRule::~GlobalRule()
{
}

void GlobalRule::setFileName(const std::string& fileName)
{
	m_fileName = fileName;
}

const std::string GlobalRule::getFileName() const
{
	return m_fileName;
}

void GlobalRule::setFileSize(const GUint64 fileSize)
{
	m_fileSize = fileSize;
}

GUint64 GlobalRule::getFileSize() const
{
	return m_fileSize;
}

void GlobalRule::setFileCount(const GUint32 fileCount)
{
	m_fileCount = fileCount;
}

GUint32 GlobalRule::getFileCount() const
{
	return m_fileCount;
}

void GlobalRule::setWordWrap(const bool isWordWrap)
{
	m_isWordWrap = isWordWrap;
}

bool GlobalRule::isWordWrap() const
{
	return m_isWordWrap;
}

ModuleRule::ModuleRule() : m_logLevel(LOG_ERROR), m_printLevel(PRINT_BASIC)
{
}

ModuleRule::~ModuleRule()
{
}

void ModuleRule::setModuleName(const std::string& moduleName)
{
	m_moduleName = moduleName;
}

const std::string& ModuleRule::getModuleName() const
{
	return m_moduleName;
}

void ModuleRule::setLogLevel(const GLogLevel logLevel)
{
	m_logLevel = logLevel;
}

const GLogLevel& ModuleRule::getLogLevel() const
{
	return m_logLevel;
}

void ModuleRule::setPrintLevel(const GPrintLevel printLevel)
{
	m_printLevel = printLevel;
}

const GPrintLevel& ModuleRule::getPrintLevel() const
{
	return m_printLevel;
}
<commit_msg>Update g_logger_impl.cpp<commit_after>/***********************************************************************************
**
* @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved.
*
************************************************************************************/
/**
* @file		g_logger_impl.cpp
* @version
* @brief
* @author	duye
* @date		2014-07-01
* @note
*
*  1. 2014-07-01 duye Created this file
*
*/
#include <stdio.h>
#include <g_file.h>
#include <g_logger_impl.h>

// the max buffer size of in one line
static const GUint64 DEF_ONE_LINE_BUF_SIZE = 1024;

// the configuration file name
static const GInt8* DEF_CONF_FILE_NAME = "glog.xml";

GLoggerImpl::GLoggerImpl()
{
	m_error[0] = 0;
}

GLoggerImpl::~GLoggerImpl()
{
}

GLoggerImpl* GLoggerImpl::GetInstance()
{
	static GLoggerImpl glogger;
	return &glogger;
}

GResult GLoggerImpl::init()
{
	m_logLevelMap.insert(std::make_pair(LOG_ERROR, "NULL"));
	m_logLevelMap.insert(std::make_pair(LOG_ERROR, "ERROR"));
	m_logLevelMap.insert(std::make_pair(LOG_WARN, "WARN"));
	m_logLevelMap.insert(std::make_pair(LOG_INFO, "INFO"));
	m_logLevelMap.insert(std::make_pair(LOG_DEBUG, "DEBUG"));
	m_logLevelMap.insert(std::make_pair(LOG_TRACE, "TRACE"));

	// parser file
	if (parserLogConf(logDoc) != G_YES)
	{
		setError("parser log conf file '%s' failed", DEF_CONF_FILE_NAME);
		return G_NO;
	}

	return G_YES;
}

GResult GLoggerImpl::uninit()
{
	return G_YES;
}

void GLoggerImpl::printLog(const GLogLevel logLevel,
	const GInt8* module,
	const GInt8* file,
	const GUint32 line,
	const GInt8* function,
	const GInt8* args, ...)
{
	ModuleRule* moduleRule = NULL;
	if (findModuleRule(std::string(module), moduleRule) == G_NO)
	{
		return;
	}

	if (logLevel > moduleRule->getLogLevel())
	{
		return;
	}

	GInt8 printBuf[DEF_ONE_LINE_BUF_SIZE] = {0};
	GUint64 pos = 0;

	// add log level and module name
	pos += sprintf(printBuf + pos, "<%s>[%s]", m_logLevelMap[logLevel], module);

	switch (moduleRule->getPrintLevel())
	{
	case PRINT_BASIC:
		break;
	case PRINT_MORE:
		// add file and function
		pos += sprintf(printBuf + pos, "(%s:%s)", file, function);
		break;
	case PRINT_FULL:
		// add file, line number and function
		pos += sprintf(printBuf + pos, "(%s:%s:%d)", file, function, line);
		break;
	default:
		return;
	}

	// add log content
	pos += GSys::format(printBuf + pos, DEF_ONE_LINE_BUF_SIZE - pos, args);

	// add word wrap
	if (m_globalRule.isWordWrap())
	{
		pos += sprintf(printBuf + pos, "\n");
	}

	printf("%s", printBuf);
}

GInt8* GLoggerImpl::getError()
{
	return m_error;
}

GResult GLoggerImpl::parserLogConf()
{
	// read configuration file
	GXmlDocument logDoc;
	if (!logDoc.loadFile(DEF_CONF_FILE_NAME))
	{
	    setError("load log conf file '%s' failed", DEF_CONF_FILE_NAME);
	    return G_NO;
	}

	logDoc.print();

	GXmlElement* rootElement = doc.rootElement();
	GXmlElement* childElement = rootElement->firstChildElement();
	for (; childElement != nullptr; childElement = childElement->nextSiblingElement())
	{
		if (childElement->tagName() == "toplevel")
		{
			const GInt8* text = childElement->getText();
			if (text != nullptr)
			{
				GLogLevel logLevel = LOG_NULL;
				if (findLogLevel(text, logLevel) != G_YES)
				{
					setError("log conf format error, please check glog.xml");
					return G_NO;
				}

				m_globalRule.setTopLogLevel(logLevel);
			}
		}
		else if (childElement->tagName() == "")
		{

		}
		else if (childElement->tagName() == "")
		{

		}
		else if (childElement->tagName() == "")
		{
				GXmlAttribute* attribute = childElement->firstAttribute();
		}

		if ()
	}

	return G_YES;
}

GResult GLoggerImpl::findLogLevel(GInt8* logLevelStr, GLogLevel& logLevel)
{
	return G_YES;
}

GResult GLoggerImpl::findModuleRule(const std::string& moduleName, ModuleRule*& moduleRule)
{
	GModuleRuleMap::iterator iter = m_moduleRuleMap.find(moduleName);
	if (iter == m_moduleRuleMap.end())
	{
		return G_NO;
	}

	moduleRule = iter->second;

	return G_YES;
}

void GLoggerImpl::setError(const GInt8* args, ...)
{
	GSys::format(m_error, G_ERROR_BUF_SIZE, args);
}

GlobalRule::GlobalRule() : m_fileSize(0), m_fileCount(0), m_isWordWrap(true)
{
}

GlobalRule::~GlobalRule()
{
}

void GlobalRule::setFileName(const std::string& fileName)
{
	m_fileName = fileName;
}

const std::string GlobalRule::getFileName() const
{
	return m_fileName;
}

void GlobalRule::setFileSize(const GUint64 fileSize)
{
	m_fileSize = fileSize;
}

GUint64 GlobalRule::getFileSize() const
{
	return m_fileSize;
}

void GlobalRule::setFileCount(const GUint32 fileCount)
{
	m_fileCount = fileCount;
}

GUint32 GlobalRule::getFileCount() const
{
	return m_fileCount;
}

void GlobalRule::setWordWrap(const bool isWordWrap)
{
	m_isWordWrap = isWordWrap;
}

bool GlobalRule::isWordWrap() const
{
	return m_isWordWrap;
}

ModuleRule::ModuleRule() : m_logLevel(LOG_ERROR), m_printLevel(PRINT_BASIC)
{
}

ModuleRule::~ModuleRule()
{
}

void ModuleRule::setModuleName(const std::string& moduleName)
{
	m_moduleName = moduleName;
}

const std::string& ModuleRule::getModuleName() const
{
	return m_moduleName;
}

void ModuleRule::setLogLevel(const GLogLevel logLevel)
{
	m_logLevel = logLevel;
}

const GLogLevel& ModuleRule::getLogLevel() const
{
	return m_logLevel;
}

void ModuleRule::setPrintLevel(const GPrintLevel printLevel)
{
	m_printLevel = printLevel;
}

const GPrintLevel& ModuleRule::getPrintLevel() const
{
	return m_printLevel;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: dp_registry.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2004-08-12 12:09:56 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "dp_registry.hrc"
#include "dp_misc.h"
#include "dp_resource.h"
#include "dp_interact.h"
#include "dp_ucb.h"
#include "osl/diagnose.h"
#include "rtl/ustrbuf.hxx"
#include "rtl/uri.hxx"
#include "cppuhelper/compbase1.hxx"
#include "cppuhelper/exc_hlp.hxx"
#include "com/sun/star/uno/DeploymentException.hpp"
#include "com/sun/star/lang/DisposedException.hpp"
#include "com/sun/star/lang/WrappedTargetRuntimeException.hpp"
#include "com/sun/star/lang/XServiceInfo.hpp"
#include "com/sun/star/lang/XSingleComponentFactory.hpp"
#include "com/sun/star/lang/XSingleServiceFactory.hpp"
#include "com/sun/star/container/XContentEnumerationAccess.hpp"
#include "com/sun/star/deployment/PackageRegistryBackend.hpp"
#include <vector>
#include <hash_map>
#include <memory>

using namespace ::dp_misc;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::ucb;
using ::rtl::OUString;

namespace dp_registry {

typedef ::cppu::WeakComponentImplHelper1<
    deployment::XPackageRegistry > t_helper;

//==============================================================================
class PackageRegistryImpl : private MutexHolder, public t_helper
{
    struct ci_string_hash
    {
        inline ::std::size_t operator () ( OUString const & str ) const {
            return str.toAsciiLowerCase().hashCode();
        }
    };
    struct ci_string_equals
    {
        inline bool operator () (
            OUString const & str1, OUString const & str2 ) const {
            return str1.equalsIgnoreAsciiCase( str2 );
        }
    };
    typedef ::std::hash_map<
        OUString, Reference<deployment::XPackageRegistry>,
        ci_string_hash, ci_string_equals > t_string2registry;
    t_string2registry m_media2backend;

    typedef ::std::vector<
        Reference<deployment::XPackageRegistry> > t_registryvec;
    t_registryvec m_backends;

    void insertBackend(
        Reference<deployment::XPackageRegistry> const & xBackend );

protected:
    inline void check();
    virtual void SAL_CALL disposing();

    virtual ~PackageRegistryImpl();
    PackageRegistryImpl() : t_helper( getMutex() ) {}
public:
    static Reference<deployment::XPackageRegistry> create(
        OUString const & context,
        OUString const & cachePath, bool readOnly,
        Reference<XComponentContext> const & xComponentContext );

    // XPackageRegistry
    virtual Reference<deployment::XPackage> SAL_CALL bindPackage(
        OUString const & url, OUString const & mediaType,
        Reference<XCommandEnvironment> const & xCmdEnv )
        throw (deployment::DeploymentException, CommandFailedException,
               lang::IllegalArgumentException, RuntimeException);
    virtual Sequence<OUString> SAL_CALL getSupportedMediaTypes()
        throw (RuntimeException);
};

//______________________________________________________________________________
inline void PackageRegistryImpl::check()
{
    ::osl::MutexGuard guard( getMutex() );
    if (rBHelper.bInDispose || rBHelper.bDisposed) {
        throw lang::DisposedException(
            OUSTR("PackageRegistry instance has already been disposed!"),
            static_cast<OWeakObject *>(this) );
    }
}

//______________________________________________________________________________
void PackageRegistryImpl::disposing()
{
    // dispose all registries:
    t_registryvec::const_iterator iPos( m_backends.begin() );
    t_registryvec::const_iterator const iEnd( m_backends.end() );
    for ( ; iPos != iEnd; ++iPos )
        try_dispose( *iPos );
    m_media2backend = t_string2registry();
    m_backends = t_registryvec();

    t_helper::disposing();
}

//______________________________________________________________________________
PackageRegistryImpl::~PackageRegistryImpl()
{
}

//______________________________________________________________________________
static OUString normalizeMediaType( OUString const & mediaType )
{
    ::rtl::OUStringBuffer buf;
    sal_Int32 index = 0;
    for (;;) {
        buf.append( mediaType.getToken( 0, '/', index ).trim() );
        if (index < 0)
            break;
        buf.append( static_cast< sal_Unicode >('/') );
    }
    return buf.makeStringAndClear();
}

//______________________________________________________________________________
void PackageRegistryImpl::insertBackend(
    Reference<deployment::XPackageRegistry> const & xBackend )
{
    m_backends.push_back( xBackend );

    Sequence<OUString> mtypes( xBackend->getSupportedMediaTypes() );
    OUString const * pmtypes = mtypes.getConstArray();
    sal_Int32 len = mtypes.getLength();
    for ( sal_Int32 pos = 0; pos < len; ++pos ) {
        OUString mediaType( normalizeMediaType( pmtypes[ pos ] ) );
        ::std::pair<t_string2registry::iterator, bool> mr_insertion(
            m_media2backend.insert(
                t_string2registry::value_type(mediaType, xBackend) ) );
#if OSL_DEBUG_LEVEL > 0
        if (! mr_insertion.second) {
            ::rtl::OUStringBuffer buf;
            buf.appendAscii(
                RTL_CONSTASCII_STRINGPARAM(
                    "more than one PackageRegistryBackend for "
                    "media-type=\"") );
            buf.append( mediaType );
            buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("\" => ") );
            buf.append( Reference<lang::XServiceInfo>(
                            xBackend, UNO_QUERY_THROW )->
                        getImplementationName() );
            buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("\"!") );
            OSL_ENSURE( 0, ::rtl::OUStringToOString(
                            buf.makeStringAndClear(),
                            RTL_TEXTENCODING_UTF8 ) );
        }
#endif
    }
}

namespace backend {
namespace bundle {
Reference<deployment::XPackageRegistry> create(
    Reference<deployment::XPackageRegistry> const & xRootRegistry,
    OUString const & context, OUString const & cachePath, bool readOnly,
    Reference<XComponentContext> const & xComponentContext );
}
}

//______________________________________________________________________________
Reference<deployment::XPackageRegistry> PackageRegistryImpl::create(
    OUString const & context,
    OUString const & cachePath, bool readOnly,
    Reference<XComponentContext> const & xComponentContext )
{
    PackageRegistryImpl * that = new PackageRegistryImpl;
    Reference<deployment::XPackageRegistry> xRet(that);

    // auto-detect all registered package registries:
    Reference<container::XEnumeration> xEnum(
        Reference<container::XContentEnumerationAccess>(
            xComponentContext->getServiceManager(),
            UNO_QUERY_THROW )->createContentEnumeration(
                OUSTR("com.sun.star.deployment.PackageRegistryBackend") ) );
    if (xEnum.is())
    {
        while (xEnum->hasMoreElements())
        {
            Any element( xEnum->nextElement() );
            Sequence<Any> registryArgs(
                cachePath.getLength() == 0 ? 1 : 3 );
            registryArgs[ 0 ] <<= context;
            if (cachePath.getLength() > 0)
            {
                Reference<lang::XServiceInfo> xServiceInfo(
                    element, UNO_QUERY_THROW );
                OUString registryCachePath(
                    make_url( cachePath,
                              ::rtl::Uri::encode(
                                  xServiceInfo->getImplementationName(),
                                  rtl_UriCharClassPchar,
                                  rtl_UriEncodeIgnoreEscapes,
                                  RTL_TEXTENCODING_UTF8 ) ) );
                registryArgs[ 1 ] <<= registryCachePath;
                registryArgs[ 2 ] <<= readOnly;
                if (! readOnly)
                    create_folder( 0, registryCachePath,
                                   Reference<XCommandEnvironment>() );
            }

            Reference<deployment::XPackageRegistry> xBackend;
            Reference<lang::XSingleComponentFactory> xFac( element, UNO_QUERY );
            if (xFac.is()) {
                xBackend.set(
                    xFac->createInstanceWithArgumentsAndContext(
                        registryArgs, xComponentContext ), UNO_QUERY );
            }
            else {
                Reference<lang::XSingleServiceFactory> xSingleServiceFac(
                    element, UNO_QUERY_THROW );
                xBackend.set(
                    xSingleServiceFac->createInstanceWithArguments(
                        registryArgs ), UNO_QUERY );
            }
            if (! xBackend.is()) {
                throw DeploymentException(
                    OUSTR("cannot instantiate PackageRegistryBackend service: ")
                    + Reference<lang::XServiceInfo>(
                        element, UNO_QUERY_THROW )->getImplementationName(),
                    static_cast<OWeakObject *>(that) );
            }

            that->insertBackend( xBackend );
        }
    }

    // insert bundle be:
    that->insertBackend(
        ::dp_registry::backend::bundle::create(
            that, context, cachePath, readOnly, xComponentContext ) );

    return xRet;
}

// XPackageRegistry
//______________________________________________________________________________
Reference<deployment::XPackage> PackageRegistryImpl::bindPackage(
    OUString const & url, OUString const & mediaType,
    Reference<XCommandEnvironment> const & xCmdEnv )
    throw (deployment::DeploymentException, CommandFailedException,
           lang::IllegalArgumentException, RuntimeException)
{
    check();
    if (mediaType.getLength() == 0)
    {
        // iterate all backends:
        t_registryvec::const_iterator iPos( m_backends.begin() );
        t_registryvec::const_iterator const iEnd( m_backends.end() );
        for ( ; iPos != iEnd; ++iPos )
        {
            try {
                return (*iPos)->bindPackage( url, mediaType, xCmdEnv );
            }
            catch (lang::IllegalArgumentException &) {
            }
        }
        throw lang::IllegalArgumentException(
            getResourceString(RID_STR_CANNOT_DETECT_MEDIA_TYPE) + url,
            static_cast<OWeakObject *>(this), static_cast<sal_Int16>(-1) );
    }
    else
    {
        // get backend:
        t_string2registry::const_iterator iFind(
            m_media2backend.find( normalizeMediaType(mediaType) ) );
        if (iFind == m_media2backend.end())
        {
            // xxx todo: more sophisticated media-type argument parsing...
            sal_Int32 q = mediaType.indexOf( ';' );
            if (q >= 0) {
                iFind = m_media2backend.find(
                    normalizeMediaType(
                        /* cut parameters: */ mediaType.copy( 0, q ) ) );
            }
        }
        if (iFind == m_media2backend.end())
            throw lang::IllegalArgumentException(
                getResourceString(RID_STR_UNSUPPORTED_MEDIA_TYPE) + mediaType,
                static_cast<OWeakObject *>(this), static_cast<sal_Int16>(-1) );

        return iFind->second->bindPackage( url, mediaType, xCmdEnv );
    }
}

//______________________________________________________________________________
Sequence<OUString> PackageRegistryImpl::getSupportedMediaTypes()
    throw (RuntimeException)
{
    throw RuntimeException( OUSTR("unexpected!"), 0 );
}

//==============================================================================
Reference<deployment::XPackageRegistry> SAL_CALL create(
    OUString const & context,
    OUString const & cachePath, bool readOnly,
    Reference<XComponentContext> const & xComponentContext )
{
    return PackageRegistryImpl::create(
        context, cachePath, readOnly, xComponentContext );
}

}

<commit_msg>INTEGRATION: CWS ooo20040704 (1.3.10); FILE MERGED 2004/07/02 11:19:49 cmc 1.3.10.2: #i30891# revert header and namespace change 2004/06/28 13:13:40 cmc 1.3.10.1: #i30801# allow using system stl if possible<commit_after>/*************************************************************************
 *
 *  $RCSfile: dp_registry.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2004-09-08 16:49:05 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "dp_registry.hrc"
#include "dp_misc.h"
#include "dp_resource.h"
#include "dp_interact.h"
#include "dp_ucb.h"
#include "osl/diagnose.h"
#include "rtl/ustrbuf.hxx"
#include "rtl/uri.hxx"
#include "cppuhelper/compbase1.hxx"
#include "cppuhelper/exc_hlp.hxx"
#include "com/sun/star/uno/DeploymentException.hpp"
#include "com/sun/star/lang/DisposedException.hpp"
#include "com/sun/star/lang/WrappedTargetRuntimeException.hpp"
#include "com/sun/star/lang/XServiceInfo.hpp"
#include "com/sun/star/lang/XSingleComponentFactory.hpp"
#include "com/sun/star/lang/XSingleServiceFactory.hpp"
#include "com/sun/star/container/XContentEnumerationAccess.hpp"
#include "com/sun/star/deployment/PackageRegistryBackend.hpp"
#include <vector>
#include <hash_map>
#include <memory>

using namespace ::dp_misc;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::ucb;
using ::rtl::OUString;

namespace dp_registry {

typedef ::cppu::WeakComponentImplHelper1<
    deployment::XPackageRegistry > t_helper;

//==============================================================================
class PackageRegistryImpl : private MutexHolder, public t_helper
{
    struct ci_string_hash
    {
        inline ::std::size_t operator () ( OUString const & str ) const {
            return str.toAsciiLowerCase().hashCode();
        }
    };
    struct ci_string_equals
    {
        inline bool operator () (
            OUString const & str1, OUString const & str2 ) const {
            return str1.equalsIgnoreAsciiCase( str2 );
        }
    };
    typedef ::std::hash_map<
        OUString, Reference<deployment::XPackageRegistry>,
        ci_string_hash, ci_string_equals > t_string2registry;
    t_string2registry m_media2backend;

    typedef ::std::vector<
        Reference<deployment::XPackageRegistry> > t_registryvec;
    t_registryvec m_backends;

    void insertBackend(
        Reference<deployment::XPackageRegistry> const & xBackend );

protected:
    inline void check();
    virtual void SAL_CALL disposing();

    virtual ~PackageRegistryImpl();
    PackageRegistryImpl() : t_helper( getMutex() ) {}
public:
    static Reference<deployment::XPackageRegistry> create(
        OUString const & context,
        OUString const & cachePath, bool readOnly,
        Reference<XComponentContext> const & xComponentContext );

    // XPackageRegistry
    virtual Reference<deployment::XPackage> SAL_CALL bindPackage(
        OUString const & url, OUString const & mediaType,
        Reference<XCommandEnvironment> const & xCmdEnv )
        throw (deployment::DeploymentException, CommandFailedException,
               lang::IllegalArgumentException, RuntimeException);
    virtual Sequence<OUString> SAL_CALL getSupportedMediaTypes()
        throw (RuntimeException);
};

//______________________________________________________________________________
inline void PackageRegistryImpl::check()
{
    ::osl::MutexGuard guard( getMutex() );
    if (rBHelper.bInDispose || rBHelper.bDisposed) {
        throw lang::DisposedException(
            OUSTR("PackageRegistry instance has already been disposed!"),
            static_cast<OWeakObject *>(this) );
    }
}

//______________________________________________________________________________
void PackageRegistryImpl::disposing()
{
    // dispose all registries:
    t_registryvec::const_iterator iPos( m_backends.begin() );
    t_registryvec::const_iterator const iEnd( m_backends.end() );
    for ( ; iPos != iEnd; ++iPos )
        try_dispose( *iPos );
    m_media2backend = t_string2registry();
    m_backends = t_registryvec();

    t_helper::disposing();
}

//______________________________________________________________________________
PackageRegistryImpl::~PackageRegistryImpl()
{
}

//______________________________________________________________________________
static OUString normalizeMediaType( OUString const & mediaType )
{
    ::rtl::OUStringBuffer buf;
    sal_Int32 index = 0;
    for (;;) {
        buf.append( mediaType.getToken( 0, '/', index ).trim() );
        if (index < 0)
            break;
        buf.append( static_cast< sal_Unicode >('/') );
    }
    return buf.makeStringAndClear();
}

//______________________________________________________________________________
void PackageRegistryImpl::insertBackend(
    Reference<deployment::XPackageRegistry> const & xBackend )
{
    m_backends.push_back( xBackend );

    Sequence<OUString> mtypes( xBackend->getSupportedMediaTypes() );
    OUString const * pmtypes = mtypes.getConstArray();
    sal_Int32 len = mtypes.getLength();
    for ( sal_Int32 pos = 0; pos < len; ++pos ) {
        OUString mediaType( normalizeMediaType( pmtypes[ pos ] ) );
        ::std::pair<t_string2registry::iterator, bool> mr_insertion(
            m_media2backend.insert(
                t_string2registry::value_type(mediaType, xBackend) ) );
#if OSL_DEBUG_LEVEL > 0
        if (! mr_insertion.second) {
            ::rtl::OUStringBuffer buf;
            buf.appendAscii(
                RTL_CONSTASCII_STRINGPARAM(
                    "more than one PackageRegistryBackend for "
                    "media-type=\"") );
            buf.append( mediaType );
            buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("\" => ") );
            buf.append( Reference<lang::XServiceInfo>(
                            xBackend, UNO_QUERY_THROW )->
                        getImplementationName() );
            buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("\"!") );
            OSL_ENSURE( 0, ::rtl::OUStringToOString(
                            buf.makeStringAndClear(),
                            RTL_TEXTENCODING_UTF8 ) );
        }
#endif
    }
}

namespace backend {
namespace bundle {
Reference<deployment::XPackageRegistry> create(
    Reference<deployment::XPackageRegistry> const & xRootRegistry,
    OUString const & context, OUString const & cachePath, bool readOnly,
    Reference<XComponentContext> const & xComponentContext );
}
}

//______________________________________________________________________________
Reference<deployment::XPackageRegistry> PackageRegistryImpl::create(
    OUString const & context,
    OUString const & cachePath, bool readOnly,
    Reference<XComponentContext> const & xComponentContext )
{
    PackageRegistryImpl * that = new PackageRegistryImpl;
    Reference<deployment::XPackageRegistry> xRet(that);

    // auto-detect all registered package registries:
    Reference<container::XEnumeration> xEnum(
        Reference<container::XContentEnumerationAccess>(
            xComponentContext->getServiceManager(),
            UNO_QUERY_THROW )->createContentEnumeration(
                OUSTR("com.sun.star.deployment.PackageRegistryBackend") ) );
    if (xEnum.is())
    {
        while (xEnum->hasMoreElements())
        {
            Any element( xEnum->nextElement() );
            Sequence<Any> registryArgs(
                cachePath.getLength() == 0 ? 1 : 3 );
            registryArgs[ 0 ] <<= context;
            if (cachePath.getLength() > 0)
            {
                Reference<lang::XServiceInfo> xServiceInfo(
                    element, UNO_QUERY_THROW );
                OUString registryCachePath(
                    make_url( cachePath,
                              ::rtl::Uri::encode(
                                  xServiceInfo->getImplementationName(),
                                  rtl_UriCharClassPchar,
                                  rtl_UriEncodeIgnoreEscapes,
                                  RTL_TEXTENCODING_UTF8 ) ) );
                registryArgs[ 1 ] <<= registryCachePath;
                registryArgs[ 2 ] <<= readOnly;
                if (! readOnly)
                    create_folder( 0, registryCachePath,
                                   Reference<XCommandEnvironment>() );
            }

            Reference<deployment::XPackageRegistry> xBackend;
            Reference<lang::XSingleComponentFactory> xFac( element, UNO_QUERY );
            if (xFac.is()) {
                xBackend.set(
                    xFac->createInstanceWithArgumentsAndContext(
                        registryArgs, xComponentContext ), UNO_QUERY );
            }
            else {
                Reference<lang::XSingleServiceFactory> xSingleServiceFac(
                    element, UNO_QUERY_THROW );
                xBackend.set(
                    xSingleServiceFac->createInstanceWithArguments(
                        registryArgs ), UNO_QUERY );
            }
            if (! xBackend.is()) {
                throw DeploymentException(
                    OUSTR("cannot instantiate PackageRegistryBackend service: ")
                    + Reference<lang::XServiceInfo>(
                        element, UNO_QUERY_THROW )->getImplementationName(),
                    static_cast<OWeakObject *>(that) );
            }

            that->insertBackend( xBackend );
        }
    }

    // insert bundle be:
    that->insertBackend(
        ::dp_registry::backend::bundle::create(
            that, context, cachePath, readOnly, xComponentContext ) );

    return xRet;
}

// XPackageRegistry
//______________________________________________________________________________
Reference<deployment::XPackage> PackageRegistryImpl::bindPackage(
    OUString const & url, OUString const & mediaType,
    Reference<XCommandEnvironment> const & xCmdEnv )
    throw (deployment::DeploymentException, CommandFailedException,
           lang::IllegalArgumentException, RuntimeException)
{
    check();
    if (mediaType.getLength() == 0)
    {
        // iterate all backends:
        t_registryvec::const_iterator iPos( m_backends.begin() );
        t_registryvec::const_iterator const iEnd( m_backends.end() );
        for ( ; iPos != iEnd; ++iPos )
        {
            try {
                return (*iPos)->bindPackage( url, mediaType, xCmdEnv );
            }
            catch (lang::IllegalArgumentException &) {
            }
        }
        throw lang::IllegalArgumentException(
            getResourceString(RID_STR_CANNOT_DETECT_MEDIA_TYPE) + url,
            static_cast<OWeakObject *>(this), static_cast<sal_Int16>(-1) );
    }
    else
    {
        // get backend:
        t_string2registry::const_iterator iFind(
            m_media2backend.find( normalizeMediaType(mediaType) ) );
        if (iFind == m_media2backend.end())
        {
            // xxx todo: more sophisticated media-type argument parsing...
            sal_Int32 q = mediaType.indexOf( ';' );
            if (q >= 0) {
                iFind = m_media2backend.find(
                    normalizeMediaType(
                        /* cut parameters: */ mediaType.copy( 0, q ) ) );
            }
        }
        if (iFind == m_media2backend.end())
            throw lang::IllegalArgumentException(
                getResourceString(RID_STR_UNSUPPORTED_MEDIA_TYPE) + mediaType,
                static_cast<OWeakObject *>(this), static_cast<sal_Int16>(-1) );

        return iFind->second->bindPackage( url, mediaType, xCmdEnv );
    }
}

//______________________________________________________________________________
Sequence<OUString> PackageRegistryImpl::getSupportedMediaTypes()
    throw (RuntimeException)
{
    throw RuntimeException( OUSTR("unexpected!"), 0 );
}

//==============================================================================
Reference<deployment::XPackageRegistry> SAL_CALL create(
    OUString const & context,
    OUString const & cachePath, bool readOnly,
    Reference<XComponentContext> const & xComponentContext )
{
    return PackageRegistryImpl::create(
        context, cachePath, readOnly, xComponentContext );
}

}

<|endoftext|>


<commit_before>// $Id: selector.C,v 1.15 2000/05/19 12:20:13 anker Exp $

#include <BALL/KERNEL/selector.h>

#include <BALL/CONCEPT/selectable.h>
#include <BALL/KERNEL/atom.h>
#include <BALL/KERNEL/PTE.h>
#include <BALL/KERNEL/residue.h>
#include <BALL/KERNEL/nucleotide.h>
#include <BALL/KERNEL/bond.h>

using namespace std;

namespace BALL
{

	Selector::Selector()
		:	number_of_selected_atoms_(0)
	{
	}

	Selector::Selector(const String& expression_string)
		:	number_of_selected_atoms_(0)
	{
		Expression(expression_string);
	}

	Selector::Selector(const Selector& selector)
		:	number_of_selected_atoms_(selector.number_of_selected_atoms_)
	{
	}

	Selector::~Selector()
	{
	}

	Size Selector::getNumberOfSelectedAtoms() const
	{
		return number_of_selected_atoms_;
	}

	bool Selector::start()
	{
		// reset the number of selected atoms
		number_of_selected_atoms_ = 0;

		// and continue
		return true;
	}

  Processor::Result Selector::operator () (Composite& composite)
  {
		// if the composite is an atom, we apply the expression tree...
		if (RTTI::isKindOf<Atom>(composite))
		{
			Atom& atom = dynamic_cast<Atom&>(composite);
			if (expression_.operator () (atom))
			{
				// select the atoms and increase the atom counter
				atom.select();
				number_of_selected_atoms_++;
			}
		}

    return Processor::CONTINUE;
	}

} // namespace BALL
<commit_msg>fixed: incorrect constructor call<commit_after>// $Id: selector.C,v 1.16 2000/05/19 12:50:45 oliver Exp $

#include <BALL/KERNEL/selector.h>

#include <BALL/CONCEPT/selectable.h>
#include <BALL/KERNEL/atom.h>
#include <BALL/KERNEL/PTE.h>
#include <BALL/KERNEL/residue.h>
#include <BALL/KERNEL/nucleotide.h>
#include <BALL/KERNEL/bond.h>

using namespace std;

namespace BALL
{

	Selector::Selector()
		:	number_of_selected_atoms_(0)
	{
	}

	Selector::Selector(const String& expression_string)
		:	number_of_selected_atoms_(0),
			expression_(expression_string)
	{
	}

	Selector::Selector(const Selector& selector)
		:	number_of_selected_atoms_(selector.number_of_selected_atoms_)
	{
	}

	Selector::~Selector()
	{
	}

	Size Selector::getNumberOfSelectedAtoms() const
	{
		return number_of_selected_atoms_;
	}

	bool Selector::start()
	{
		// reset the number of selected atoms
		number_of_selected_atoms_ = 0;

		// and continue
		return true;
	}

  Processor::Result Selector::operator () (Composite& composite)
  {
		// if the composite is an atom, we apply the expression tree...
		if (RTTI::isKindOf<Atom>(composite))
		{
			Atom& atom = dynamic_cast<Atom&>(composite);
			if (expression_.operator () (atom))
			{
				// select the atoms and increase the atom counter
				atom.select();
				number_of_selected_atoms_++;
			}
		}

    return Processor::CONTINUE;
	}

} // namespace BALL
<|endoftext|>


<commit_before>#include "illa/codec.h"
#include "illa/codecmgr.h"
#include "illa/surfacemgr.h"
#include "illa/swsurface.h"
#include "orz/fileops.h"
#include "orz/logger.h"
#include "orz/stopwatch.h"

#include <boost/filesystem.hpp>
#include <boost/locale.hpp>

enum
{
	Warmups = 1,
	NumRuns = 3
};

Img::CodecFactoryStore g_cfs;

Img::AbstractCodec* DetectAndLoadHeader(const std::shared_ptr<IO::FileReader> reader) {
	auto c = g_cfs.CreateCodec(IO::GetExtension(reader->Name()));
	if (c != nullptr && c->LoadHeader(reader)) {
		return c;
	}

	const Img::CodecFactoryStore::InfoVector& iv = g_cfs.CodecInfo();
	for (size_t i = 0; i < iv.size(); ++i) {
		c = g_cfs.CreateCodec(i);
		if (c == nullptr) {
			continue;
		}

		reader->Seek(0, IO::SeekMethod::Begin);
		if (!c->CanDetectFormat() || !c->LoadHeader(reader)) {
			delete c;
		}
		else {
			return c;
		}
	}
	return 0;
}

int performLoad(const std::string& filename)
{
	auto f = std::make_shared<IO::FileReader>(filename);
	if(!f->Open()) {
		std::cout << "Failed opening file" << std::endl;
		return EXIT_FAILURE;
	}
	auto pCodec = DetectAndLoadHeader(f);
	if(pCodec == nullptr) {
		std::cout << "No codec!" << std::endl;
		return EXIT_FAILURE;
	}

	if(pCodec->LoadHeader(f) == false) return EXIT_FAILURE;
	if(pCodec->Allocate() != Img::AbstractCodec::AllocationStatus::Ok) return EXIT_FAILURE;
	pCodec->LoadImageData();
	return EXIT_SUCCESS;
}

int realMain(std::string filename) {
	std::locale::global(boost::locale::generator().generate(""));
	boost::filesystem::path::imbue(std::locale());

	g_cfs.AddBuiltinCodecs();

	Img::SurfaceFactory(new Img::FactorySurfaceSoftware);

	Util::StopWatch sw;

	for (int i = 0; i < Warmups; ++i)
		if (performLoad(filename) == EXIT_FAILURE) return EXIT_FAILURE;

	sw.Start();
	for (int i = 0; i < NumRuns; ++i)
		performLoad(filename);
	int time = sw.Stop();

	Log << "Time: " << (time / NumRuns) << "\n";

	return EXIT_SUCCESS;
}

#ifdef _WIN32
int wmain(int argc, wchar_t* argv[])
{
	if (argc < 2) {
		std::cout << "Missing parameter" << std::endl;
		return EXIT_FAILURE;
	}
	return realMain(WStringToUTF8(argv[1]));
}
#else
int main(int argc, char* argv[])
{
	if (argc < 2) {
		std::cout << "Missing parameter" << std::endl;
		return EXIT_FAILURE;
	}
	realMain(argv[1]);
	return EXIT_SUCCESS;
}
#endif
<commit_msg>Command line configuration<commit_after>#include "illa/codec.h"
#include "illa/codecmgr.h"
#include "illa/surfacemgr.h"
#include "illa/swsurface.h"
#include "orz/fileops.h"
#include "orz/logger.h"
#include "orz/stopwatch.h"

#include <boost/filesystem.hpp>
#include <boost/locale.hpp>

enum
{
	Warmups = 1,
	NumRuns = 3
};

Img::CodecFactoryStore g_cfs;

Img::AbstractCodec* DetectAndLoadHeader(const std::shared_ptr<IO::FileReader> reader, bool autoDetect) {
	auto c = g_cfs.CreateCodec(IO::GetExtension(reader->Name()));
	if (c != nullptr && c->LoadHeader(reader))
	{
		return c;
	}

	if(autoDetect == false)
	{
		return nullptr;
	}

	const Img::CodecFactoryStore::InfoVector& iv = g_cfs.CodecInfo();
	for (size_t i = 0; i < iv.size(); ++i)
	{
		c = g_cfs.CreateCodec(i);
		if (c == nullptr)
		{
			continue;
		}

		reader->Seek(0, IO::SeekMethod::Begin);
		if (!c->CanDetectFormat() || !c->LoadHeader(reader))
		{
			delete c;
		}
		else
		{
			return c;
		}
	}
	return 0;
}

int performLoad(const std::string& filename, bool autoDetect)
{
	auto f = std::make_shared<IO::FileReader>(filename);
	if(!f->Open())
	{
		std::cout << "Failed opening file" << std::endl;
		return EXIT_FAILURE;
	}
	auto pCodec = DetectAndLoadHeader(f, autoDetect);
	if(pCodec == nullptr)
	{
		std::cout << "No codec!" << std::endl;
		return EXIT_FAILURE;
	}
	f->Seek(0, IO::SeekMethod::Begin);

	if(pCodec->LoadHeader(f) == false)
	{
		std::cout << "Failed loading header!" << std::endl;
		return EXIT_FAILURE;
	}

	if(pCodec->Allocate() != Img::AbstractCodec::AllocationStatus::Ok)
	{
		std::cout << "Failed allocating surface!" << std::endl;
		return EXIT_FAILURE;
	}
	pCodec->LoadImageData();
	return EXIT_SUCCESS;
}

int realMain(std::vector<std::string> args) {
	if(args.empty())
	{
		std::cout << "Missing parameter" << std::endl;
		return EXIT_FAILURE;
	}

	std::locale::global(boost::locale::generator().generate(""));
	boost::filesystem::path::imbue(std::locale());

	g_cfs.AddBuiltinCodecs();

	bool autoDetect = true;
	bool bench = false;
	std::string filename = "";

	for(auto p:args)
	{
		if(p == "--noauto")
		{
			autoDetect = false;
		}
		else if(p == "--bench")
		{
			bench = true;
		}
		else
		{
			filename = p;
		}
	}

	if(filename.empty())
	{
		std::cout << "Missing filename param" << std::endl;
		return EXIT_FAILURE;
	}

	Img::SurfaceFactory(new Img::FactorySurfaceSoftware);

	if(bench)
	{
		std::cout << "Benchmarking..." << std::endl;
		Util::StopWatch sw;

		for (int i = 0; i < Warmups; ++i)
		{
			if (performLoad(filename, autoDetect) == EXIT_FAILURE)
			{
				std::cout << "Failed during warmup, exiting ..." << std::endl;
				return EXIT_FAILURE;
			}
		}

		sw.Start();
		for (int i = 0; i < NumRuns; ++i)
		{
			performLoad(filename, autoDetect);
		}
		int time = sw.Stop();

		std::cout << "Time: " << (time / NumRuns) << std::endl;
	}
	else
	{
		return performLoad(filename, autoDetect);
	}

	return EXIT_SUCCESS;
}

#ifdef _WIN32
int wmain(int argc, wchar_t* argv[])
{
	std::vector<std::string> args;
	for(auto i = 1; i < argc; i++)
	{
		args.push_back(WStringToUTF8(argv[i]));
	}

	return realMain(args);
}
#else
int main(int argc, char* argv[])
{
	std::vector<std::string> args;
	for(auto i = 1; i < argc; i++)
	{
		args.push_back(argv[i]);
	}

	return realMain(args);
}
#endif
<|endoftext|>