<commit_before>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "cmakeprojectmanager.h"
#include "cmakeopenprojectwizard.h"
#include "cmakeprojectconstants.h"
#include "cmakeproject.h"

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

#include <coreplugin/icore.h>
#include <coreplugin/id.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/command.h>
#include <coreplugin/actionmanager/actioncontainer.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/target.h>
#include <utils/QtConcurrentTools>
#include <QtConcurrentRun>
#include <QCoreApplication>
#include <QDateTime>
#include <QDesktopServices>

using namespace CMakeProjectManager::Internal;

CMakeManager::CMakeManager(CMakeSettingsPage *cmakeSettingsPage)
    : m_settingsPage(cmakeSettingsPage)
{
    ProjectExplorer::ProjectExplorerPlugin *projectExplorer = ProjectExplorer::ProjectExplorerPlugin::instance();
    connect(projectExplorer, SIGNAL(aboutToShowContextMenu(ProjectExplorer::Project*,ProjectExplorer::Node*)),
            this, SLOT(updateContextMenu(ProjectExplorer::Project*,ProjectExplorer::Node*)));

    Core::ActionContainer *mbuild =
            Core::ActionManager::actionContainer(ProjectExplorer::Constants::M_BUILDPROJECT);
    Core::ActionContainer *mproject =
            Core::ActionManager::actionContainer(ProjectExplorer::Constants::M_PROJECTCONTEXT);
    Core::ActionContainer *msubproject =
            Core::ActionManager::actionContainer(ProjectExplorer::Constants::M_SUBPROJECTCONTEXT);

    const Core::Context projectContext(CMakeProjectManager::Constants::PROJECTCONTEXT);

    m_runCMakeAction = new QAction(QIcon(), tr("Run CMake"), this);
    Core::Command *command = Core::ActionManager::registerAction(m_runCMakeAction,
                                                                 Constants::RUNCMAKE, projectContext);
    command->setAttribute(Core::Command::CA_Hide);
    mbuild->addAction(command, ProjectExplorer::Constants::G_BUILD_DEPLOY);
    connect(m_runCMakeAction, SIGNAL(triggered()), this, SLOT(runCMake()));

    m_runCMakeActionContextMenu = new QAction(QIcon(), tr("Run CMake"), this);
    command = Core::ActionManager::registerAction(m_runCMakeActionContextMenu,
                                                  Constants::RUNCMAKECONTEXTMENU, projectContext);
    command->setAttribute(Core::Command::CA_Hide);
    mproject->addAction(command, ProjectExplorer::Constants::G_PROJECT_BUILD);
    msubproject->addAction(command, ProjectExplorer::Constants::G_PROJECT_BUILD);
    connect(m_runCMakeActionContextMenu, SIGNAL(triggered()), this, SLOT(runCMakeContextMenu()));

}

void CMakeManager::updateContextMenu(ProjectExplorer::Project *project, ProjectExplorer::Node *node)
{
    Q_UNUSED(node);
    m_contextProject = project;
}

void CMakeManager::runCMake()
{
    runCMake(ProjectExplorer::ProjectExplorerPlugin::currentProject());
}

void CMakeManager::runCMakeContextMenu()
{
    runCMake(m_contextProject);
}

void CMakeManager::runCMake(ProjectExplorer::Project *project)
{
    if (!project)
        return;
    CMakeProject *cmakeProject = qobject_cast<CMakeProject *>(project);
    if (!cmakeProject || !cmakeProject->activeTarget() || !cmakeProject->activeTarget()->activeBuildConfiguration())
        return;

    if (!ProjectExplorer::ProjectExplorerPlugin::instance()->saveModifiedFiles())
        return;

    CMakeBuildConfiguration *bc
            = static_cast<CMakeBuildConfiguration *>(cmakeProject->activeTarget()->activeBuildConfiguration());

    CMakeBuildInfo info(bc);

    CMakeOpenProjectWizard copw(Core::ICore::mainWindow(), this, CMakeOpenProjectWizard::WantToUpdate, &info);
    if (copw.exec() == QDialog::Accepted)
        cmakeProject->parseCMakeLists();
}

ProjectExplorer::Project *CMakeManager::openProject(const QString &fileName, QString *errorString)
{
    if (!QFileInfo(fileName).isFile()) {
        if (errorString)
            *errorString = tr("Failed opening project '%1': Project is not a file")
                .arg(fileName);
        return 0;
    }

    return new CMakeProject(this, fileName);
}

QString CMakeManager::mimeType() const
{
    return QLatin1String(Constants::CMAKEMIMETYPE);
}

QString CMakeManager::cmakeExecutable() const
{
    return m_settingsPage->cmakeExecutable();
}

bool CMakeManager::isCMakeExecutableValid() const
{
    return m_settingsPage->isCMakeExecutableValid();
}

void CMakeManager::setCMakeExecutable(const QString &executable)
{
    m_settingsPage->setCMakeExecutable(executable);
}

bool CMakeManager::hasCodeBlocksMsvcGenerator() const
{
    return m_settingsPage->hasCodeBlocksMsvcGenerator();
}

bool CMakeManager::hasCodeBlocksNinjaGenerator() const
{
    return m_settingsPage->hasCodeBlocksNinjaGenerator();
}

bool CMakeManager::preferNinja() const
{
    return m_settingsPage->preferNinja();
}

// need to refactor this out
// we probably want the process instead of this function
// cmakeproject then could even run the cmake process in the background, adding the files afterwards
// sounds like a plan
void CMakeManager::createXmlFile(Utils::QtcProcess *proc, const QString &arguments,
                                 const QString &sourceDirectory, const QDir &buildDirectory,
                                 const Utils::Environment &env, const QString &generator)
{
    // We create a cbp file, only if we didn't find a cbp file in the base directory
    // Yet that can still override cbp files in subdirectories
    // And we are creating tons of files in the source directories
    // All of that is not really nice.
    // The mid term plan is to move away from the CodeBlocks Generator and use our own
    // QtCreator generator, which actually can be very similar to the CodeBlock Generator
    QString buildDirectoryPath = buildDirectory.absolutePath();
    buildDirectory.mkpath(buildDirectoryPath);
    proc->setWorkingDirectory(buildDirectoryPath);
    proc->setEnvironment(env);

    const QString srcdir = buildDirectory.exists(QLatin1String("CMakeCache.txt")) ?
                QString(QLatin1Char('.')) : sourceDirectory;
    QString args;
    Utils::QtcProcess::addArg(&args, srcdir);
    Utils::QtcProcess::addArgs(&args, arguments);
    Utils::QtcProcess::addArg(&args, generator);
    proc->setCommand(cmakeExecutable(), args);
    proc->start();
}

QString CMakeManager::findCbpFile(const QDir &directory)
{
    // Find the cbp file
    //   the cbp file is named like the project() command in the CMakeList.txt file
    //   so this function below could find the wrong cbp file, if the user changes the project()
    //   2name
    QDateTime t;
    QString file;
    foreach (const QString &cbpFile , directory.entryList()) {
        if (cbpFile.endsWith(QLatin1String(".cbp"))) {
            QFileInfo fi(directory.path() + QLatin1Char('/') + cbpFile);
            if (t.isNull() || fi.lastModified() > t) {
                file = directory.path() + QLatin1Char('/') + cbpFile;
                t = fi.lastModified();
            }
        }
    }
    return file;
}

// This code is duplicated from qtversionmanager
QString CMakeManager::qtVersionForQMake(const QString &qmakePath)
{
    QProcess qmake;
    qmake.start(qmakePath, QStringList(QLatin1String("--version")));
    if (!qmake.waitForStarted()) {
        qWarning("Cannot start '%s': %s", qPrintable(qmakePath), qPrintable(qmake.errorString()));
        return QString();
    }
    if (!qmake.waitForFinished())      {
        Utils::SynchronousProcess::stopProcess(qmake);
        qWarning("Timeout running '%s'.", qPrintable(qmakePath));
        return QString();
    }
    QString output = QString::fromLocal8Bit(qmake.readAllStandardOutput());
    QRegExp regexp(QLatin1String("(QMake version|Qmake version:)[\\s]*([\\d.]*)"));
    regexp.indexIn(output);
    if (regexp.cap(2).startsWith(QLatin1String("2."))) {
        QRegExp regexp2(QLatin1String("Using Qt version[\\s]*([\\d\\.]*)"));
        regexp2.indexIn(output);
        return regexp2.cap(1);
    }
    return QString();
}
<commit_msg>CMakeProjectManager: Remove outdated comment<commit_after>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "cmakeprojectmanager.h"
#include "cmakeopenprojectwizard.h"
#include "cmakeprojectconstants.h"
#include "cmakeproject.h"

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

#include <coreplugin/icore.h>
#include <coreplugin/id.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/command.h>
#include <coreplugin/actionmanager/actioncontainer.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/target.h>
#include <utils/QtConcurrentTools>
#include <QtConcurrentRun>
#include <QCoreApplication>
#include <QDateTime>
#include <QDesktopServices>

using namespace CMakeProjectManager::Internal;

CMakeManager::CMakeManager(CMakeSettingsPage *cmakeSettingsPage)
    : m_settingsPage(cmakeSettingsPage)
{
    ProjectExplorer::ProjectExplorerPlugin *projectExplorer = ProjectExplorer::ProjectExplorerPlugin::instance();
    connect(projectExplorer, SIGNAL(aboutToShowContextMenu(ProjectExplorer::Project*,ProjectExplorer::Node*)),
            this, SLOT(updateContextMenu(ProjectExplorer::Project*,ProjectExplorer::Node*)));

    Core::ActionContainer *mbuild =
            Core::ActionManager::actionContainer(ProjectExplorer::Constants::M_BUILDPROJECT);
    Core::ActionContainer *mproject =
            Core::ActionManager::actionContainer(ProjectExplorer::Constants::M_PROJECTCONTEXT);
    Core::ActionContainer *msubproject =
            Core::ActionManager::actionContainer(ProjectExplorer::Constants::M_SUBPROJECTCONTEXT);

    const Core::Context projectContext(CMakeProjectManager::Constants::PROJECTCONTEXT);

    m_runCMakeAction = new QAction(QIcon(), tr("Run CMake"), this);
    Core::Command *command = Core::ActionManager::registerAction(m_runCMakeAction,
                                                                 Constants::RUNCMAKE, projectContext);
    command->setAttribute(Core::Command::CA_Hide);
    mbuild->addAction(command, ProjectExplorer::Constants::G_BUILD_DEPLOY);
    connect(m_runCMakeAction, SIGNAL(triggered()), this, SLOT(runCMake()));

    m_runCMakeActionContextMenu = new QAction(QIcon(), tr("Run CMake"), this);
    command = Core::ActionManager::registerAction(m_runCMakeActionContextMenu,
                                                  Constants::RUNCMAKECONTEXTMENU, projectContext);
    command->setAttribute(Core::Command::CA_Hide);
    mproject->addAction(command, ProjectExplorer::Constants::G_PROJECT_BUILD);
    msubproject->addAction(command, ProjectExplorer::Constants::G_PROJECT_BUILD);
    connect(m_runCMakeActionContextMenu, SIGNAL(triggered()), this, SLOT(runCMakeContextMenu()));

}

void CMakeManager::updateContextMenu(ProjectExplorer::Project *project, ProjectExplorer::Node *node)
{
    Q_UNUSED(node);
    m_contextProject = project;
}

void CMakeManager::runCMake()
{
    runCMake(ProjectExplorer::ProjectExplorerPlugin::currentProject());
}

void CMakeManager::runCMakeContextMenu()
{
    runCMake(m_contextProject);
}

void CMakeManager::runCMake(ProjectExplorer::Project *project)
{
    if (!project)
        return;
    CMakeProject *cmakeProject = qobject_cast<CMakeProject *>(project);
    if (!cmakeProject || !cmakeProject->activeTarget() || !cmakeProject->activeTarget()->activeBuildConfiguration())
        return;

    if (!ProjectExplorer::ProjectExplorerPlugin::instance()->saveModifiedFiles())
        return;

    CMakeBuildConfiguration *bc
            = static_cast<CMakeBuildConfiguration *>(cmakeProject->activeTarget()->activeBuildConfiguration());

    CMakeBuildInfo info(bc);

    CMakeOpenProjectWizard copw(Core::ICore::mainWindow(), this, CMakeOpenProjectWizard::WantToUpdate, &info);
    if (copw.exec() == QDialog::Accepted)
        cmakeProject->parseCMakeLists();
}

ProjectExplorer::Project *CMakeManager::openProject(const QString &fileName, QString *errorString)
{
    if (!QFileInfo(fileName).isFile()) {
        if (errorString)
            *errorString = tr("Failed opening project '%1': Project is not a file")
                .arg(fileName);
        return 0;
    }

    return new CMakeProject(this, fileName);
}

QString CMakeManager::mimeType() const
{
    return QLatin1String(Constants::CMAKEMIMETYPE);
}

QString CMakeManager::cmakeExecutable() const
{
    return m_settingsPage->cmakeExecutable();
}

bool CMakeManager::isCMakeExecutableValid() const
{
    return m_settingsPage->isCMakeExecutableValid();
}

void CMakeManager::setCMakeExecutable(const QString &executable)
{
    m_settingsPage->setCMakeExecutable(executable);
}

bool CMakeManager::hasCodeBlocksMsvcGenerator() const
{
    return m_settingsPage->hasCodeBlocksMsvcGenerator();
}

bool CMakeManager::hasCodeBlocksNinjaGenerator() const
{
    return m_settingsPage->hasCodeBlocksNinjaGenerator();
}

bool CMakeManager::preferNinja() const
{
    return m_settingsPage->preferNinja();
}

// need to refactor this out
// we probably want the process instead of this function
// cmakeproject then could even run the cmake process in the background, adding the files afterwards
// sounds like a plan
void CMakeManager::createXmlFile(Utils::QtcProcess *proc, const QString &arguments,
                                 const QString &sourceDirectory, const QDir &buildDirectory,
                                 const Utils::Environment &env, const QString &generator)
{
    QString buildDirectoryPath = buildDirectory.absolutePath();
    buildDirectory.mkpath(buildDirectoryPath);
    proc->setWorkingDirectory(buildDirectoryPath);
    proc->setEnvironment(env);

    const QString srcdir = buildDirectory.exists(QLatin1String("CMakeCache.txt")) ?
                QString(QLatin1Char('.')) : sourceDirectory;
    QString args;
    Utils::QtcProcess::addArg(&args, srcdir);
    Utils::QtcProcess::addArgs(&args, arguments);
    Utils::QtcProcess::addArg(&args, generator);
    proc->setCommand(cmakeExecutable(), args);
    proc->start();
}

QString CMakeManager::findCbpFile(const QDir &directory)
{
    // Find the cbp file
    //   the cbp file is named like the project() command in the CMakeList.txt file
    //   so this function below could find the wrong cbp file, if the user changes the project()
    //   2name
    QDateTime t;
    QString file;
    foreach (const QString &cbpFile , directory.entryList()) {
        if (cbpFile.endsWith(QLatin1String(".cbp"))) {
            QFileInfo fi(directory.path() + QLatin1Char('/') + cbpFile);
            if (t.isNull() || fi.lastModified() > t) {
                file = directory.path() + QLatin1Char('/') + cbpFile;
                t = fi.lastModified();
            }
        }
    }
    return file;
}

// This code is duplicated from qtversionmanager
QString CMakeManager::qtVersionForQMake(const QString &qmakePath)
{
    QProcess qmake;
    qmake.start(qmakePath, QStringList(QLatin1String("--version")));
    if (!qmake.waitForStarted()) {
        qWarning("Cannot start '%s': %s", qPrintable(qmakePath), qPrintable(qmake.errorString()));
        return QString();
    }
    if (!qmake.waitForFinished())      {
        Utils::SynchronousProcess::stopProcess(qmake);
        qWarning("Timeout running '%s'.", qPrintable(qmakePath));
        return QString();
    }
    QString output = QString::fromLocal8Bit(qmake.readAllStandardOutput());
    QRegExp regexp(QLatin1String("(QMake version|Qmake version:)[\\s]*([\\d.]*)"));
    regexp.indexIn(output);
    if (regexp.cap(2).startsWith(QLatin1String("2."))) {
        QRegExp regexp2(QLatin1String("Using Qt version[\\s]*([\\d\\.]*)"));
        regexp2.indexIn(output);
        return regexp2.cap(1);
    }
    return QString();
}
<|endoftext|>


<commit_before>/**
 * @file
 * @author Jason Lingle
 * @date 2012.02.03
 * @brief Contains the NetworkAssembly class
 */
#ifndef NETWORK_ASSEMBLY_HXX_
#define NETWORK_ASSEMBLY_HXX_

#include <vector>

#include "src/core/aobject.hxx"

class Antenna;
class Tuner;
class NetworkConnection;
class PacketProcessor;

/**
 * Manages the various objects that are used to provide a functional network
 * system.
 *
 * This is essentially a convenience class for managing the list of connections
 * and the memory used by the various PacketProcessors.
 */
class NetworkAssembly: public AObject {
  std::vector<NetworkConnection*> connections;
  std::vector<PacketProcessor*> packetProcessors;
  Tuner tuner;

  ///Not implemented, do not use
  NetworkAssembly(const NetworkAssembly&);

public:
  /**
   * Constructs a NetworkAssembly on the given Antenna.
   * There are initially no connections or packet processors.
   */
  NetworkAssembly(Antenna*);
  virtual ~NetworkAssembly();

  /**
   * Returns the Tuner associated with this NetworkAssembly.
   */
  Tuner* getTuner() noth;
  /**
   * Returns the number of NetworkConnections contained in this
   * NetworkAssembly.
   */
  unsigned numConnections() const noth;
  /**
   * Returns the NetworkConnection at the given index.
   */
  NetworkConnection* getConnection(unsigned ix) const noth;
  /**
   * Removes and deletes the NetworkConnection at the given index.
   */
  void removeConnection(unsigned ix) noth;
  /**
   * Removes and deletes the given NetworkConnection, which must
   * exist within this NetworkAssembly's connection list.
   */
  void removeConnection(NetworkConnection*) noth;
  /**
   * Adds the given PacketProcessor to those managed by this instance.
   * The PacketProcessor will be deleted when this NetworkAssembly is deleted.
   */
  void addPacketProcessor(PacketProcessor*) noth;
  /**
   * Updates all NetworkConnections.
   * @param et the number of milliseconds that have elapsed since the last
   * call to update()
   */
  void update(unsigned et) noth;
};

#endif /* NETWORK_ASSEMBLY_HXX_ */
<commit_msg>Add GameField information to NetworkAssembly.<commit_after>/**
 * @file
 * @author Jason Lingle
 * @date 2012.02.03
 * @brief Contains the NetworkAssembly class
 */
#ifndef NETWORK_ASSEMBLY_HXX_
#define NETWORK_ASSEMBLY_HXX_

#include <vector>

#include "src/core/aobject.hxx"

class Antenna;
class Tuner;
class NetworkConnection;
class PacketProcessor;

/**
 * Manages the various objects that are used to provide a functional network
 * system.
 *
 * This is essentially a convenience class for managing the list of connections
 * and the memory used by the various PacketProcessors.
 */
class NetworkAssembly: public AObject {
  std::vector<NetworkConnection*> connections;
  std::vector<PacketProcessor*> packetProcessors;
  Tuner tuner;

  ///Not implemented, do not use
  NetworkAssembly(const NetworkAssembly&);

public:
  /**
   * The GameField used by the networking system.
   */
  GameField*const field;
  /**
   * The Antenna used for communication.
   */
  Antenna*const antenna;

  /**
   * Constructs a NetworkAssembly on the given GameField and Antenna.
   * There are initially no connections or packet processors.
   *
   * @param field the GameField the network operates on
   * @param antenna the Antenna to use for sending and receiving of messages
   */
  NetworkAssembly(GameField* field, Antenna* antenna);
  virtual ~NetworkAssembly();

  /**
   * Returns the Tuner associated with this NetworkAssembly.
   */
  Tuner* getTuner() noth;
  /**
   * Returns the number of NetworkConnections contained in this
   * NetworkAssembly.
   */
  unsigned numConnections() const noth;
  /**
   * Returns the NetworkConnection at the given index.
   */
  NetworkConnection* getConnection(unsigned ix) const noth;
  /**
   * Removes and deletes the NetworkConnection at the given index.
   */
  void removeConnection(unsigned ix) noth;
  /**
   * Removes and deletes the given NetworkConnection, which must
   * exist within this NetworkAssembly's connection list.
   */
  void removeConnection(NetworkConnection*) noth;
  /**
   * Adds the given PacketProcessor to those managed by this instance.
   * The PacketProcessor will be deleted when this NetworkAssembly is deleted.
   */
  void addPacketProcessor(PacketProcessor*) noth;
  /**
   * Updates all NetworkConnections.
   * @param et the number of milliseconds that have elapsed since the last
   * call to update()
   */
  void update(unsigned et) noth;
};

#endif /* NETWORK_ASSEMBLY_HXX_ */
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: null_spritehelper.cxx,v $
 * $Revision: 1.6 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_canvas.hxx"

#include <canvas/debug.hxx>
#include <canvas/verbosetrace.hxx>

#include <rtl/logfile.hxx>
#include <rtl/math.hxx>

#include <canvas/canvastools.hxx>

#include <basegfx/matrix/b2dhommatrix.hxx>
#include <basegfx/point/b2dpoint.hxx>
#include <basegfx/tools/canvastools.hxx>
#include <basegfx/numeric/ftools.hxx>
#include <basegfx/polygon/b2dpolypolygontools.hxx>
#include <basegfx/polygon/b2dpolygontools.hxx>
#include <basegfx/polygon/b2dpolypolygonrasterconverter.hxx>
#include <basegfx/polygon/b2dpolygontriangulator.hxx>
#include <basegfx/polygon/b2dpolygoncutandtouch.hxx>

#include "null_canvascustomsprite.hxx"
#include "null_spritehelper.hxx"

#include <memory>

using namespace ::com::sun::star;

namespace nullcanvas
{
    SpriteHelper::SpriteHelper() :
        mpSpriteCanvas(),
        mbTextureDirty( true )
    {
    }

    void SpriteHelper::init( const geometry::RealSize2D&    rSpriteSize,
                             const SpriteCanvasRef&         rSpriteCanvas )
    {
        ENSURE_AND_THROW( rSpriteCanvas.get(),
                          "SpriteHelper::init(): Invalid device, sprite canvas or surface" );

        mpSpriteCanvas     = rSpriteCanvas;
        mbTextureDirty     = true;

        // also init base class
        CanvasCustomSpriteHelper::init( rSpriteSize,
                                        rSpriteCanvas.get() );
    }

    void SpriteHelper::disposing()
    {
        mpSpriteCanvas.clear();

        // forward to parent
        CanvasCustomSpriteHelper::disposing();
    }

    void SpriteHelper::redraw( bool& /*io_bSurfaceDirty*/ ) const
    {
        // TODO
    }

    ::basegfx::B2DPolyPolygon SpriteHelper::polyPolygonFromXPolyPolygon2D( uno::Reference< rendering::XPolyPolygon2D >& xPoly ) const
    {
        return ::canvas::tools::polyPolygonFromXPolyPolygon2D( xPoly );
    }
}
<commit_msg>INTEGRATION: CWS canvas05 (1.5.26); FILE MERGED 2008/04/21 07:27:40 thb 1.5.26.2: RESYNC: (1.5-1.6); FILE MERGED 2007/10/01 13:02:02 thb 1.5.26.1: #i78888# #i78925# #i79258# #i79437# Merge from CWS picom<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: null_spritehelper.cxx,v $
 * $Revision: 1.7 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_canvas.hxx"

#include <canvas/debug.hxx>
#include <tools/diagnose_ex.h>
#include <canvas/verbosetrace.hxx>

#include <rtl/logfile.hxx>
#include <rtl/math.hxx>

#include <canvas/canvastools.hxx>

#include <basegfx/matrix/b2dhommatrix.hxx>
#include <basegfx/point/b2dpoint.hxx>
#include <basegfx/tools/canvastools.hxx>
#include <basegfx/numeric/ftools.hxx>
#include <basegfx/polygon/b2dpolypolygontools.hxx>
#include <basegfx/polygon/b2dpolygontools.hxx>
#include <basegfx/polygon/b2dpolypolygonrasterconverter.hxx>
#include <basegfx/polygon/b2dpolygontriangulator.hxx>
#include <basegfx/polygon/b2dpolygoncutandtouch.hxx>

#include "null_canvascustomsprite.hxx"
#include "null_spritehelper.hxx"

#include <memory>

using namespace ::com::sun::star;

namespace nullcanvas
{
    SpriteHelper::SpriteHelper() :
        mpSpriteCanvas(),
        mbTextureDirty( true )
    {
    }

    void SpriteHelper::init( const geometry::RealSize2D&    rSpriteSize,
                             const SpriteCanvasRef&         rSpriteCanvas )
    {
        ENSURE_OR_THROW( rSpriteCanvas.get(),
                          "SpriteHelper::init(): Invalid device, sprite canvas or surface" );

        mpSpriteCanvas     = rSpriteCanvas;
        mbTextureDirty     = true;

        // also init base class
        CanvasCustomSpriteHelper::init( rSpriteSize,
                                        rSpriteCanvas.get() );
    }

    void SpriteHelper::disposing()
    {
        mpSpriteCanvas.clear();

        // forward to parent
        CanvasCustomSpriteHelper::disposing();
    }

    void SpriteHelper::redraw( bool& /*io_bSurfaceDirty*/ ) const
    {
        // TODO
    }

    ::basegfx::B2DPolyPolygon SpriteHelper::polyPolygonFromXPolyPolygon2D( uno::Reference< rendering::XPolyPolygon2D >& xPoly ) const
    {
        return ::basegfx::unotools::b2DPolyPolygonFromXPolyPolygon2D( xPoly );
    }
}
<|endoftext|>


<commit_before>#include "analyzer.h"

#include <boost/log/trivial.hpp>
#include <unistd.h>

using namespace std;

namespace analyzer
{

AnalyzerPtr Analyzer::Create() {
  BOOST_LOG_TRIVIAL(debug) << "analyzer::Analyzer::Create: Function call";
  auto ptr = AnalyzerPtr(new Analyzer());
  return ptr;
}

void Analyzer::StartLoop() {
  BOOST_LOG_TRIVIAL(debug) << "analyzer::Analyzer::StartLoop: Function call";

  is_loop_running_ = true;
  while (is_loop_running_) {
    BOOST_LOG_TRIVIAL(debug) << "analyzer::Analyzer::StartLoop: Loop is running";
    ExecuteAll();
    sleep(1);
  }
}

void Analyzer::StopLoop() {
  BOOST_LOG_TRIVIAL(debug) << "analyzer::Analyzer::StopLoop: Function call";
  is_loop_running_ = false;
}

bool Analyzer::IsLoopRunning() const {
  return is_loop_running_;
}

void Analyzer::StartAnalyzing() {
  BOOST_LOG_TRIVIAL(debug) << "analyzer::Analyzer::StartAnalyzing: Function call";
  is_analyzing_ = true;
}

bool Analyzer::IsAnalyzing() const {
  return is_analyzing_;
}

void Analyzer::AddObject(AnalyzerObjectInterfacePtr object) {
  BOOST_LOG_TRIVIAL(debug) << "analyzer::Analyzer::StartAnalyzing: Function call";
  objects_.insert(object);
}

Analyzer::Analyzer() :
is_loop_running_(false),
is_analyzing_(false) {
}

void Analyzer::ExecuteAll() {
  BOOST_LOG_TRIVIAL(debug) << "analyzer::Analyzer::ExecuteAll: Function call";
  if (is_analyzing_) {
    BOOST_LOG_TRIVIAL(debug) << "analyzer::Analyzer::ExecuteAll: Analyzing started";
    for (auto obj : objects_) {
      obj->Analyze();
    }
    BOOST_LOG_TRIVIAL(debug) << "analyzer::Analyzer::ExecuteAll: Analyzing finished";

    is_analyzing_ = false;
  }
}

}
<commit_msg>Change logs classification<commit_after>#include "analyzer.h"

#include <boost/log/trivial.hpp>
#include <unistd.h>

using namespace std;

namespace analyzer
{

AnalyzerPtr Analyzer::Create() {
  BOOST_LOG_TRIVIAL(debug) << "analyzer::Analyzer::Create: Function call";
  auto ptr = AnalyzerPtr(new Analyzer());
  return ptr;
}

void Analyzer::StartLoop() {
  BOOST_LOG_TRIVIAL(debug) << "analyzer::Analyzer::StartLoop: Function call";

  is_loop_running_ = true;
  while (is_loop_running_) {
    BOOST_LOG_TRIVIAL(debug) << "analyzer::Analyzer::StartLoop: Loop is running";
    ExecuteAll();
    sleep(1);
  }
}

void Analyzer::StopLoop() {
  BOOST_LOG_TRIVIAL(debug) << "analyzer::Analyzer::StopLoop: Function call";
  is_loop_running_ = false;
}

bool Analyzer::IsLoopRunning() const {
  return is_loop_running_;
}

void Analyzer::StartAnalyzing() {
  BOOST_LOG_TRIVIAL(debug) << "analyzer::Analyzer::StartAnalyzing: Function call";
  is_analyzing_ = true;
}

bool Analyzer::IsAnalyzing() const {
  return is_analyzing_;
}

void Analyzer::AddObject(AnalyzerObjectInterfacePtr object) {
  BOOST_LOG_TRIVIAL(debug) << "analyzer::Analyzer::StartAnalyzing: Function call";
  objects_.insert(object);
}

Analyzer::Analyzer() :
is_loop_running_(false),
is_analyzing_(false) {
}

void Analyzer::ExecuteAll() {
  BOOST_LOG_TRIVIAL(debug) << "analyzer::Analyzer::ExecuteAll: Function call";
  if (is_analyzing_) {
    BOOST_LOG_TRIVIAL(info) << "analyzer::Analyzer::ExecuteAll: Analyzing started";
    for (auto obj : objects_) {
      obj->Analyze();
    }
    BOOST_LOG_TRIVIAL(info) << "analyzer::Analyzer::ExecuteAll: Analyzing finished";

    is_analyzing_ = false;
  }
}

}
<|endoftext|>


<commit_before>#ifndef __CINT__
  #include <iostream.h>

  #include "AliRun.h"
  #include "AliITS.h"
  #include "AliITSgeom.h"
  #include "AliITSRecPoint.h"
  #include "AliITSclusterV2.h"

  #include "TFile.h"
  #include "TTree.h"
  #include "TParticle.h"
#endif

Int_t AliITSFindClustersV2(Char_t SlowOrFast='f') {
/****************************************************************
 *  This macro converts AliITSRecPoint(s) to AliITSclusterV2(s) *
 ****************************************************************/
   cerr<<"AliITSRecPoint(s) -> AliITSclusterV2(s)...\n";

   if (gAlice) {delete gAlice; gAlice=0;}

   TFile *in=TFile::Open("galice.root");
   if (!in->IsOpen()) { cerr<<"Can't open galice.root !\n"; return 1; }

   if (!(gAlice=(AliRun*)in->Get("gAlice"))) {
      cerr<<"Can't find gAlice !\n";
      return 2;
   }
   gAlice->GetEvent(0);

   AliITS *ITS  = (AliITS*)gAlice->GetModule("ITS");
   if (!ITS) { cerr<<"Can't find the ITS !\n"; return 3; }
   AliITSgeom *geom=ITS->GetITSgeom();

   TFile *out=TFile::Open("AliITSclustersV2.root","new");
   if (!out->IsOpen()) {
      cerr<<"Delete old AliITSclustersV2.root !\n";
      return 4;
   }
   geom->Write();

   TClonesArray *clusters=new TClonesArray("AliITSclusterV2",10000);
   TTree *cTree=new TTree("TreeC_ITS_0","ITS clusters");
   cTree->Branch("Clusters",&clusters);

   TTree *pTree=gAlice->TreeR();
   if (!pTree) { cerr<<"Can't get TreeR !\n"; return 5; }
   TBranch *branch = 0;
   if (SlowOrFast=='f') {
     branch = pTree->GetBranch("ITSRecPointsF");
   }
   else {
     branch = pTree->GetBranch("ITSRecPoints");
   }
   if (!branch) { cerr<<"Can't get ITSRecPoints branch !\n"; return 6; }
   TClonesArray *points=new TClonesArray("AliITSRecPoint",10000);
   branch->SetAddress(&points);

   TClonesArray &cl=*clusters;
   Int_t nclusters=0;
   Int_t nentr=(Int_t)branch->GetEntries();

   cerr<<"Number of entries: "<<nentr<<endl;

   Float_t lp[5]; Int_t lab[6]; //Why can't it be inside a loop ?

   for (Int_t i=0; i<nentr; i++) {
       points->Clear();
       branch->GetEvent(i);
       Int_t ncl=points->GetEntriesFast(); if (ncl==0){cTree->Fill();continue;}
       Int_t lay,lad,det; geom->GetModuleId(i,lay,lad,det);
       Float_t x,y,zshift; geom->GetTrans(lay,lad,det,x,y,zshift);
       Double_t rot[9];    geom->GetRotMatrix(lay,lad,det,rot);
       Double_t yshift = x*rot[0] + y*rot[1];
       Int_t ndet=(lad-1)*geom->GetNdetectors(lay) + (det-1);
       nclusters+=ncl;

       Float_t kmip=1; // ADC->mip normalization factor for the SDD and SSD
       if(lay==4 || lay==3){kmip=280.;};
       if(lay==6 || lay==5){kmip=38.;};

       for (Int_t j=0; j<ncl; j++) {
          AliITSRecPoint *p=(AliITSRecPoint*)points->UncheckedAt(j);
          //Float_t lp[5];
          lp[0]=-p->GetX()-yshift; if (lay==1) lp[0]=-lp[0];
          lp[1]=p->GetZ()+zshift;
          lp[2]=p->GetSigmaX2();
          lp[3]=p->GetSigmaZ2();
          lp[4]=p->GetQ(); lp[4]/=kmip;
          //Int_t lab[6];
          lab[0]=p->GetLabel(0);lab[1]=p->GetLabel(1);lab[2]=p->GetLabel(2);
          lab[3]=ndet;

          Int_t label=lab[0];
          if (label>=0) {
             TParticle *part=(TParticle*)gAlice->Particle(label);
             label=-3;
             while (part->P() < 0.005) {
                Int_t m=part->GetFirstMother();
                if (m<0) {cerr<<"Primary momentum: "<<part->P()<<endl; break;}
                label=m;
                part=(TParticle*)gAlice->Particle(label);
             }
             if      (lab[1]<0) lab[1]=label;
             else if (lab[2]<0) lab[2]=label;
             else cerr<<"No empty labels !\n";
	  }

          new(cl[j]) AliITSclusterV2(lab,lp);
       }
       cTree->Fill(); clusters->Delete();
       points->Delete();
   }
   cTree->Write();

   cerr<<"Number of clusters: "<<nclusters<<endl;

   delete cTree; delete clusters; delete points;

   delete gAlice; gAlice=0;

   in->Close();
   out->Close();

   return 0;

}

<commit_msg>Using pointers instead of arrays (Alpha)<commit_after>#ifndef __CINT__
  #include <iostream.h>

  #include "AliRun.h"
  #include "AliITS.h"
  #include "AliITSgeom.h"
  #include "AliITSRecPoint.h"
  #include "AliITSclusterV2.h"

  #include "TFile.h"
  #include "TTree.h"
  #include "TParticle.h"
#endif

Int_t AliITSFindClustersV2(Char_t SlowOrFast='f') {
/****************************************************************
 *  This macro converts AliITSRecPoint(s) to AliITSclusterV2(s) *
 ****************************************************************/
   cerr<<"AliITSRecPoint(s) -> AliITSclusterV2(s)...\n";

   if (gAlice) {delete gAlice; gAlice=0;}

   TFile *in=TFile::Open("galice.root");
   if (!in->IsOpen()) { cerr<<"Can't open galice.root !\n"; return 1; }

   if (!(gAlice=(AliRun*)in->Get("gAlice"))) {
      cerr<<"Can't find gAlice !\n";
      return 2;
   }
   gAlice->GetEvent(0);

   AliITS *ITS  = (AliITS*)gAlice->GetModule("ITS");
   if (!ITS) { cerr<<"Can't find the ITS !\n"; return 3; }
   AliITSgeom *geom=ITS->GetITSgeom();

   TFile *out=TFile::Open("AliITSclustersV2.root","new");
   if (!out->IsOpen()) {
      cerr<<"Delete old AliITSclustersV2.root !\n";
      return 4;
   }
   geom->Write();

   TClonesArray *clusters=new TClonesArray("AliITSclusterV2",10000);
   TTree *cTree=new TTree("TreeC_ITS_0","ITS clusters");
   cTree->Branch("Clusters",&clusters);

   TTree *pTree=gAlice->TreeR();
   if (!pTree) { cerr<<"Can't get TreeR !\n"; return 5; }
   TBranch *branch = 0;
   if (SlowOrFast=='f') {
     branch = pTree->GetBranch("ITSRecPointsF");
   }
   else {
     branch = pTree->GetBranch("ITSRecPoints");
   }
   if (!branch) { cerr<<"Can't get ITSRecPoints branch !\n"; return 6; }
   TClonesArray *points=new TClonesArray("AliITSRecPoint",10000);
   branch->SetAddress(&points);

   TClonesArray &cl=*clusters;
   Int_t nclusters=0;
   Int_t nentr=(Int_t)branch->GetEntries();

   cerr<<"Number of entries: "<<nentr<<endl;

   //   Float_t lp[5]; Int_t lab[6]; //Why can't it be inside a loop ?
   Float_t * lp = new Float_t[5];
   Int_t * lab = new Int_t[6];

   for (Int_t i=0; i<nentr; i++) {
       points->Clear();
       branch->GetEvent(i);
       Int_t ncl=points->GetEntriesFast(); if (ncl==0){cTree->Fill();continue;}
       Int_t lay,lad,det; geom->GetModuleId(i,lay,lad,det);
       Float_t x,y,zshift; geom->GetTrans(lay,lad,det,x,y,zshift);
       Double_t rot[9];    geom->GetRotMatrix(lay,lad,det,rot);
       Double_t yshift = x*rot[0] + y*rot[1];
       Int_t ndet=(lad-1)*geom->GetNdetectors(lay) + (det-1);
       nclusters+=ncl;

       Float_t kmip=1; // ADC->mip normalization factor for the SDD and SSD
       if(lay==4 || lay==3){kmip=280.;};
       if(lay==6 || lay==5){kmip=38.;};

       for (Int_t j=0; j<ncl; j++) {
          AliITSRecPoint *p=(AliITSRecPoint*)points->UncheckedAt(j);
          //Float_t lp[5];
          lp[0]=-p->GetX()-yshift; if (lay==1) lp[0]=-lp[0];
          lp[1]=p->GetZ()+zshift;
          lp[2]=p->GetSigmaX2();
          lp[3]=p->GetSigmaZ2();
          lp[4]=p->GetQ(); lp[4]/=kmip;
          //Int_t lab[6];
          lab[0]=p->GetLabel(0);lab[1]=p->GetLabel(1);lab[2]=p->GetLabel(2);
          lab[3]=ndet;

          Int_t label=lab[0];
          if (label>=0) {
             TParticle *part=(TParticle*)gAlice->Particle(label);
             label=-3;
             while (part->P() < 0.005) {
                Int_t m=part->GetFirstMother();
                if (m<0) {cerr<<"Primary momentum: "<<part->P()<<endl; break;}
                label=m;
                part=(TParticle*)gAlice->Particle(label);
             }
             if      (lab[1]<0) lab[1]=label;
             else if (lab[2]<0) lab[2]=label;
             else cerr<<"No empty labels !\n";
	  }

          new(cl[j]) AliITSclusterV2(lab,lp);
       }
       cTree->Fill(); clusters->Delete();
       points->Delete();
   }
   cTree->Write();

   cerr<<"Number of clusters: "<<nclusters<<endl;

   delete [] lp;
   delete [] lab;

   delete cTree; delete clusters; delete points;

   delete gAlice; gAlice=0;

   in->Close();
   out->Close();

   return 0;

}

<|endoftext|>


<commit_before>#ifndef SERVER_HPP
#define SERVER_HPP

#include <map>
#include <memory>
#include <thread>
#include <mutex>
#include "alias_for_boost.hpp"
#include "users.hpp"

namespace fs{

class Server
{
public:
    using SharedUserTable = std::shared_ptr<fs::Users>;
    using SocketsMap = std::map<Tcp::endpoint, Tcp::socket>;
    using SharedSocketsMap = std::shared_ptr<SocketsMap>;
    using ThreadVector = std::vector<std::thread>;

    Server():
        Server(1234,5678)
    {}

    Server(unsigned short ctrl_port, unsigned short data_port):
        user_table_{std::make_shared<fs::Users>("users")},
        io_service_{},
        ctrl_acceptor_{io_service_, Tcp::endpoint{Tcp::v4(), ctrl_port}},
        data_acceptor_{io_service_, Tcp::endpoint{Tcp::v4(), data_port}},
        data_sockets_{std::make_shared<SocketsMap>()},
        threads_vector_{}
    {
        add_thread(make_thread_for_data_acceptor());
    }

    ~Server()
    {
        wait_for_all_done();
    }
private:

    static std::mutex m;
    SharedUserTable user_table_;
    Io_service  io_service_;

    Acceptor ctrl_acceptor_;
    Acceptor data_acceptor_;
    SharedSocketsMap data_sockets_;
    ThreadVector threads_vector_;

    void add_thread(std::thread&& t)
    {
        threads_vector_.push_back(std::move(t));
    }

    void wait_for_all_done()
    {
        for(auto& t : threads_vector_)  t.join();
    }

    std::thread make_thread_for_data_acceptor()
    {
        std::thread t
        {
            [this]{
                std::cout << ">accepting data connections" << std::endl;
                while(true)
                {
                    Tcp::socket soc(io_service_);
                    data_acceptor_.accept(soc);
                    std::cout << ">new data socket generated" << std::endl;

                    using Element = std::pair<Tcp::endpoint, Tcp::socket>;
                    data_sockets_->insert(std::move(Element({soc.remote_endpoint(), std::move(soc)})));
                }
            }
        };

        return t;
    }
};

std::mutex Server::m;

}//namespace
#endif // SERVER_HPP
<commit_msg>	modified:   ftp/server.hpp<commit_after>#ifndef SERVER_HPP
#define SERVER_HPP

#include <map>
#include <memory>
#include <thread>
#include <mutex>
#include "alias_for_boost.hpp"
#include "users.hpp"

namespace fs{

class Server
{
public:
    using SharedUserTable = std::shared_ptr<fs::Users>;
    using SocketsMap = std::map<Tcp::endpoint, Tcp::socket>;
    using SharedSocketsMap = std::shared_ptr<SocketsMap>;
    using ThreadVector = std::vector<std::thread>;

    Server():
        Server(1234,5678)
    {}

    Server(unsigned short ctrl_port, unsigned short data_port):
        user_table_{std::make_shared<fs::Users>("users")},
        io_service_{},
        ctrl_acceptor_{io_service_, Tcp::endpoint{Tcp::v4(), ctrl_port}},
        data_acceptor_{io_service_, Tcp::endpoint{Tcp::v4(), data_port}},
        data_sockets_{std::make_shared<SocketsMap>()},
        threads_vector_{}
    {
        add_thread(make_thread_for_data_acceptor());
    }

    ~Server()
    {
        wait_for_all_done();
    }
private:

    static std::mutex m_;
    SharedUserTable user_table_;
    Io_service  io_service_;

    Acceptor ctrl_acceptor_;
    Acceptor data_acceptor_;
    SharedSocketsMap data_sockets_;
    ThreadVector threads_vector_;

    void add_thread(std::thread&& t)
    {
        threads_vector_.push_back(std::move(t));
    }

    void wait_for_all_done()
    {
        for(auto& t : threads_vector_)  t.join();
    }

    std::thread make_thread_for_data_acceptor()
    {
        std::thread t
        {
            [this]{
                std::cout << ">accepting data connections" << std::endl;
                while(true)
                {
                    Tcp::socket soc(io_service_);
                    data_acceptor_.accept(soc);
                    std::cout << ">new data socket generated" << std::endl;

                    using Element = std::pair<Tcp::endpoint, Tcp::socket>;
                    data_sockets_->insert(std::move(Element({soc.remote_endpoint(), std::move(soc)})));
                }
            }
        };

        return t;
    }
};

std::mutex Server::m_;

}//namespace
#endif // SERVER_HPP
<|endoftext|>


<commit_before><commit_msg>compilation fix<commit_after><|endoftext|>


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

#include "chrome/browser/dom_ui/dom_ui_contents.h"

#include "chrome/browser/dom_ui/dom_ui.h"
#include "chrome/browser/dom_ui/history_ui.h"
#include "chrome/browser/navigation_entry.h"
#include "chrome/browser/render_view_host.h"
#include "chrome/common/resource_bundle.h"

// The scheme used for DOMUIContentses
// TODO(glen): Merge this with the scheme in chrome_url_data_manager
static const char kURLScheme[] = "chrome";

// The path used in internal URLs to thumbnail data.
static const char kThumbnailPath[] = "thumb";

// The path used in internal URLs to favicon data.
static const char kFavIconPath[] = "favicon";

///////////////////////////////////////////////////////////////////////////////
// FavIconSource

FavIconSource::FavIconSource(Profile* profile)
    : DataSource(kFavIconPath, MessageLoop::current()), profile_(profile) {}

void FavIconSource::StartDataRequest(const std::string& path, int request_id) {
  HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
  if (hs) {
    HistoryService::Handle handle;
    if (path.size() > 8 && path.substr(0, 8) == "iconurl/") {
      handle = hs->GetFavIcon(
          GURL(path.substr(8)),
          &cancelable_consumer_,
          NewCallback(this, &FavIconSource::OnFavIconDataAvailable));
    } else {
      handle = hs->GetFavIconForURL(
          GURL(path),
          &cancelable_consumer_,
          NewCallback(this, &FavIconSource::OnFavIconDataAvailable));
    }
    // Attach the ChromeURLDataManager request ID to the history request.
    cancelable_consumer_.SetClientData(hs, handle, request_id);
  } else {
    SendResponse(request_id, NULL);
  }
}

void FavIconSource::OnFavIconDataAvailable(
    HistoryService::Handle request_handle,
    bool know_favicon,
    scoped_refptr<RefCountedBytes> data,
    bool expired,
    GURL icon_url) {
  HistoryService* hs =
      profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
  int request_id = cancelable_consumer_.GetClientData(hs, request_handle);

  if (know_favicon && data.get() && !data->data.empty()) {
    // Forward the data along to the networking system.
    SendResponse(request_id, data);
  } else {
    if (!default_favicon_.get()) {
      default_favicon_ = new RefCountedBytes;
      ResourceBundle::GetSharedInstance().LoadImageResourceBytes(
          IDR_DEFAULT_FAVICON, &default_favicon_->data);
    }

    SendResponse(request_id, default_favicon_);
  }
}

///////////////////////////////////////////////////////////////////////////////
// ThumbnailSource

ThumbnailSource::ThumbnailSource(Profile* profile)
    : DataSource(kThumbnailPath, MessageLoop::current()), profile_(profile) {}

void ThumbnailSource::StartDataRequest(const std::string& path,
                                       int request_id) {
  HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
  if (hs) {
    HistoryService::Handle handle = hs->GetPageThumbnail(
        GURL(path),
        &cancelable_consumer_,
        NewCallback(this, &ThumbnailSource::OnThumbnailDataAvailable));
    // Attach the ChromeURLDataManager request ID to the history request.
    cancelable_consumer_.SetClientData(hs, handle, request_id);
  } else {
    // Tell the caller that no thumbnail is available.
    SendResponse(request_id, NULL);
  }
}

void ThumbnailSource::OnThumbnailDataAvailable(
    HistoryService::Handle request_handle,
    scoped_refptr<RefCountedBytes> data) {
  HistoryService* hs =
    profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
  int request_id = cancelable_consumer_.GetClientData(hs, request_handle);
  // Forward the data along to the networking system.
  if (data.get() && !data->data.empty()) {
    SendResponse(request_id, data);
  } else {
    if (!default_thumbnail_.get()) {
      default_thumbnail_ = new RefCountedBytes;
      ResourceBundle::GetSharedInstance().LoadImageResourceBytes(
          IDR_DEFAULT_THUMBNAIL, &default_thumbnail_->data);
    }

    SendResponse(request_id, default_thumbnail_);
  }
}

///////////////////////////////////////////////////////////////////////////////
// DOMUIContents

// This is the top-level URL handler for chrome: URLs, and exposed in
// our header file. The individual DOMUIs provide a chrome:
// HTML source at the same host/path.
bool DOMUIContentsCanHandleURL(GURL* url,
                               TabContentsType* result_type) {
  if (!url->SchemeIs(kURLScheme))
    return false;

  // TODO: remove once the debugger is using DOMContentsUI
  if (url->host().compare("debugger") == 0)
    return false;

  *result_type = TAB_CONTENTS_DOM_UI;
  return true;
}

DOMUIContents::DOMUIContents(Profile* profile,
                             SiteInstance* instance,
                             RenderViewHostFactory* render_view_factory)
    : WebContents(profile,
                  instance,
                  render_view_factory,
                  MSG_ROUTING_NONE,
                  NULL),
      current_ui_(NULL) {
  set_type(TAB_CONTENTS_DOM_UI);
}

DOMUIContents::~DOMUIContents() {
  if (current_ui_)
    delete current_ui_;
}

bool DOMUIContents::CreateRenderViewForRenderManager(
    RenderViewHost* render_view_host) {
  // Be sure to enable DOM UI bindings on the RenderViewHost before
  // CreateRenderView is called.  Since a cross-site transition may be
  // involved, this may or may not be the same RenderViewHost that we had when
  // we were created.
  render_view_host->AllowDOMUIBindings();
  return WebContents::CreateRenderViewForRenderManager(render_view_host);
}

WebPreferences DOMUIContents::GetWebkitPrefs() {
  // Get the users preferences then force image loading to always be on.
  WebPreferences web_prefs = WebContents::GetWebkitPrefs();
  web_prefs.loads_images_automatically = true;
  web_prefs.javascript_enabled = true;

  return web_prefs;
}

bool DOMUIContents::NavigateToPendingEntry(bool reload) {
  if (current_ui_) {
    // Shut down our existing DOMUI.
    delete current_ui_;
    current_ui_ = NULL;
  }

  // Set up a new DOMUI.
  NavigationEntry* pending_entry = controller()->GetPendingEntry();
  current_ui_ = GetDOMUIForURL(pending_entry->url());
  if (current_ui_)
    current_ui_->Init();
  else
    return false;

  // Let WebContents do whatever it's meant to do.
  return WebContents::NavigateToPendingEntry(reload);
}

DOMUI* DOMUIContents::GetDOMUIForURL(const GURL &url) {
  if (url.host() == HistoryUI::GetBaseURL().host())
    return new HistoryUI(this);

  return NULL;
}

void DOMUIContents::ProcessDOMUIMessage(const std::string& message,
                                        const std::string& content) {
  DCHECK(current_ui_);
  current_ui_->ProcessDOMUIMessage(message, content);
}

// static
const std::string DOMUIContents::GetScheme() {
  return kURLScheme;
}<commit_msg>Let the debugger work again. Error was due to me not noticing the change in debugger URL.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/dom_ui/dom_ui_contents.h"

#include "chrome/browser/dom_ui/dom_ui.h"
#include "chrome/browser/dom_ui/history_ui.h"
#include "chrome/browser/navigation_entry.h"
#include "chrome/browser/render_view_host.h"
#include "chrome/common/resource_bundle.h"

// The scheme used for DOMUIContentses
// TODO(glen): Merge this with the scheme in chrome_url_data_manager
static const char kURLScheme[] = "chrome";

// The path used in internal URLs to thumbnail data.
static const char kThumbnailPath[] = "thumb";

// The path used in internal URLs to favicon data.
static const char kFavIconPath[] = "favicon";

///////////////////////////////////////////////////////////////////////////////
// FavIconSource

FavIconSource::FavIconSource(Profile* profile)
    : DataSource(kFavIconPath, MessageLoop::current()), profile_(profile) {}

void FavIconSource::StartDataRequest(const std::string& path, int request_id) {
  HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
  if (hs) {
    HistoryService::Handle handle;
    if (path.size() > 8 && path.substr(0, 8) == "iconurl/") {
      handle = hs->GetFavIcon(
          GURL(path.substr(8)),
          &cancelable_consumer_,
          NewCallback(this, &FavIconSource::OnFavIconDataAvailable));
    } else {
      handle = hs->GetFavIconForURL(
          GURL(path),
          &cancelable_consumer_,
          NewCallback(this, &FavIconSource::OnFavIconDataAvailable));
    }
    // Attach the ChromeURLDataManager request ID to the history request.
    cancelable_consumer_.SetClientData(hs, handle, request_id);
  } else {
    SendResponse(request_id, NULL);
  }
}

void FavIconSource::OnFavIconDataAvailable(
    HistoryService::Handle request_handle,
    bool know_favicon,
    scoped_refptr<RefCountedBytes> data,
    bool expired,
    GURL icon_url) {
  HistoryService* hs =
      profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
  int request_id = cancelable_consumer_.GetClientData(hs, request_handle);

  if (know_favicon && data.get() && !data->data.empty()) {
    // Forward the data along to the networking system.
    SendResponse(request_id, data);
  } else {
    if (!default_favicon_.get()) {
      default_favicon_ = new RefCountedBytes;
      ResourceBundle::GetSharedInstance().LoadImageResourceBytes(
          IDR_DEFAULT_FAVICON, &default_favicon_->data);
    }

    SendResponse(request_id, default_favicon_);
  }
}

///////////////////////////////////////////////////////////////////////////////
// ThumbnailSource

ThumbnailSource::ThumbnailSource(Profile* profile)
    : DataSource(kThumbnailPath, MessageLoop::current()), profile_(profile) {}

void ThumbnailSource::StartDataRequest(const std::string& path,
                                       int request_id) {
  HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
  if (hs) {
    HistoryService::Handle handle = hs->GetPageThumbnail(
        GURL(path),
        &cancelable_consumer_,
        NewCallback(this, &ThumbnailSource::OnThumbnailDataAvailable));
    // Attach the ChromeURLDataManager request ID to the history request.
    cancelable_consumer_.SetClientData(hs, handle, request_id);
  } else {
    // Tell the caller that no thumbnail is available.
    SendResponse(request_id, NULL);
  }
}

void ThumbnailSource::OnThumbnailDataAvailable(
    HistoryService::Handle request_handle,
    scoped_refptr<RefCountedBytes> data) {
  HistoryService* hs =
    profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
  int request_id = cancelable_consumer_.GetClientData(hs, request_handle);
  // Forward the data along to the networking system.
  if (data.get() && !data->data.empty()) {
    SendResponse(request_id, data);
  } else {
    if (!default_thumbnail_.get()) {
      default_thumbnail_ = new RefCountedBytes;
      ResourceBundle::GetSharedInstance().LoadImageResourceBytes(
          IDR_DEFAULT_THUMBNAIL, &default_thumbnail_->data);
    }

    SendResponse(request_id, default_thumbnail_);
  }
}

///////////////////////////////////////////////////////////////////////////////
// DOMUIContents

// This is the top-level URL handler for chrome: URLs, and exposed in
// our header file. The individual DOMUIs provide a chrome:
// HTML source at the same host/path.
bool DOMUIContentsCanHandleURL(GURL* url,
                               TabContentsType* result_type) {
  if (!url->SchemeIs(kURLScheme))
    return false;

  // TODO: remove once the debugger is using DOMContentsUI
  if (url->host().compare("inspector") == 0 &&
      url->path().compare("/debugger.html") == 0)
    return false;

  *result_type = TAB_CONTENTS_DOM_UI;
  return true;
}

DOMUIContents::DOMUIContents(Profile* profile,
                             SiteInstance* instance,
                             RenderViewHostFactory* render_view_factory)
    : WebContents(profile,
                  instance,
                  render_view_factory,
                  MSG_ROUTING_NONE,
                  NULL),
      current_ui_(NULL) {
  set_type(TAB_CONTENTS_DOM_UI);
}

DOMUIContents::~DOMUIContents() {
  if (current_ui_)
    delete current_ui_;
}

bool DOMUIContents::CreateRenderViewForRenderManager(
    RenderViewHost* render_view_host) {
  // Be sure to enable DOM UI bindings on the RenderViewHost before
  // CreateRenderView is called.  Since a cross-site transition may be
  // involved, this may or may not be the same RenderViewHost that we had when
  // we were created.
  render_view_host->AllowDOMUIBindings();
  return WebContents::CreateRenderViewForRenderManager(render_view_host);
}

WebPreferences DOMUIContents::GetWebkitPrefs() {
  // Get the users preferences then force image loading to always be on.
  WebPreferences web_prefs = WebContents::GetWebkitPrefs();
  web_prefs.loads_images_automatically = true;
  web_prefs.javascript_enabled = true;

  return web_prefs;
}

bool DOMUIContents::NavigateToPendingEntry(bool reload) {
  if (current_ui_) {
    // Shut down our existing DOMUI.
    delete current_ui_;
    current_ui_ = NULL;
  }

  // Set up a new DOMUI.
  NavigationEntry* pending_entry = controller()->GetPendingEntry();
  current_ui_ = GetDOMUIForURL(pending_entry->url());
  if (current_ui_)
    current_ui_->Init();
  else
    return false;

  // Let WebContents do whatever it's meant to do.
  return WebContents::NavigateToPendingEntry(reload);
}

DOMUI* DOMUIContents::GetDOMUIForURL(const GURL &url) {
  if (url.host() == HistoryUI::GetBaseURL().host())
    return new HistoryUI(this);

  return NULL;
}

void DOMUIContents::ProcessDOMUIMessage(const std::string& message,
                                        const std::string& content) {
  DCHECK(current_ui_);
  current_ui_->ProcessDOMUIMessage(message, content);
}

// static
const std::string DOMUIContents::GetScheme() {
  return kURLScheme;
}<|endoftext|>


<commit_before><commit_msg>reindent<commit_after><|endoftext|>


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

#include "chrome/browser/dom_ui/new_tab_ui.h"
#include "chrome/browser/renderer_host/test_render_view_host.h"
#include "chrome/common/url_constants.h"
#include "testing/gtest/include/gtest/gtest.h"

class DOMUITest : public RenderViewHostTestHarness {
 public:
  DOMUITest() {}

  // Tests navigating with a DOM UI from a fresh (nothing pending or committed)
  // state, through pending, committed, then another navigation. The first page
  // ID that we should use is passed as a parameter. We'll use the next two
  // values. This must be increasing for the life of the tests.
  static void DoNavigationTest(WebContents* contents, int page_id) {
    NavigationController* controller = contents->controller();

    // Start a pending load.
    GURL new_tab_url(chrome::kChromeUINewTabURL);
    controller->LoadURL(new_tab_url, GURL(), PageTransition::LINK);

    // The navigation entry should be pending with no committed entry.
    ASSERT_TRUE(controller->GetPendingEntry());
    ASSERT_FALSE(controller->GetLastCommittedEntry());

    // Check the things the pending DOM UI should have set.
    EXPECT_FALSE(contents->ShouldDisplayURL());
    EXPECT_FALSE(contents->ShouldDisplayFavIcon());
    EXPECT_TRUE(contents->IsBookmarkBarAlwaysVisible());
    EXPECT_TRUE(contents->FocusLocationBarByDefault());

    // Now commit the load.
    static_cast<TestRenderViewHost*>(
        contents->render_view_host())->SendNavigate(page_id, new_tab_url);

    // The same flags should be set as before now that the load has committed.
    EXPECT_FALSE(contents->ShouldDisplayURL());
    EXPECT_FALSE(contents->ShouldDisplayFavIcon());
    EXPECT_TRUE(contents->IsBookmarkBarAlwaysVisible());
    EXPECT_TRUE(contents->FocusLocationBarByDefault());

    // Start a pending navigation to a regular page.
    GURL next_url("http://google.com/");
    controller->LoadURL(next_url, GURL(), PageTransition::LINK);

    // Check the flags. Some should reflect the new page (URL, title), some
    // should reflect the old one (bookmark bar) until it has committed.
    EXPECT_TRUE(contents->ShouldDisplayURL());
    EXPECT_TRUE(contents->ShouldDisplayFavIcon());
    EXPECT_TRUE(contents->IsBookmarkBarAlwaysVisible());
    EXPECT_FALSE(contents->FocusLocationBarByDefault());

    // Commit the regular page load. Note that we must send it to the "pending"
    // RenderViewHost, since this transition will also cause a process
    // transition, and our RVH pointer will be the "committed" one.
    static_cast<TestRenderViewHost*>(
        contents->render_manager()->pending_render_view_host())->SendNavigate(
            page_id + 1, next_url);

    // The state should now reflect a regular page.
    EXPECT_TRUE(contents->ShouldDisplayURL());
    EXPECT_TRUE(contents->ShouldDisplayFavIcon());
    EXPECT_FALSE(contents->IsBookmarkBarAlwaysVisible());
    EXPECT_FALSE(contents->FocusLocationBarByDefault());
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(DOMUITest);
};

// Tests that the New Tab Page flags are correctly set and propogated by
// WebContents when we first navigate to a DOM UI page, then to a standard
// non-DOM-UI page.
/* TODO(brettw) uncomment this test when it doesn't crash.
TEST_F(DOMUITest, DOMUIToStandard) {
  DoNavigationTest(contents(), 1);

  // Check for a non-first
  WebContents* contents2 = new TestWebContents(profile_.get(), NULL,
      &rvh_factory_);
  DoNavigationTest(contents2, 101);
  contents2->CloseContents();
}
*/

TEST_F(DOMUITest, DOMUIToDOMUI) {
  // Do a load (this state is tested above).
  GURL new_tab_url(chrome::kChromeUINewTabURL);
  controller()->LoadURL(new_tab_url, GURL(), PageTransition::LINK);
  rvh()->SendNavigate(1, new_tab_url);

  // Start another pending load of the new tab page.
  controller()->LoadURL(new_tab_url, GURL(), PageTransition::LINK);
  rvh()->SendNavigate(2, new_tab_url);

  // The flags should be the same as the non-pending state.
  EXPECT_FALSE(contents()->ShouldDisplayURL());
  EXPECT_FALSE(contents()->ShouldDisplayFavIcon());
  EXPECT_TRUE(contents()->IsBookmarkBarAlwaysVisible());
  EXPECT_TRUE(contents()->FocusLocationBarByDefault());
}

TEST_F(DOMUITest, StandardToDOMUI) {
  // Start a pending navigation to a regular page.
  GURL std_url("http://google.com/");
  controller()->LoadURL(std_url, GURL(), PageTransition::LINK);

  // The state should now reflect the default.
  EXPECT_TRUE(contents()->ShouldDisplayURL());
  EXPECT_TRUE(contents()->ShouldDisplayFavIcon());
  EXPECT_FALSE(contents()->IsBookmarkBarAlwaysVisible());
  EXPECT_FALSE(contents()->FocusLocationBarByDefault());

  // Commit the load, the state should be the same.
  rvh()->SendNavigate(1, std_url);
  EXPECT_TRUE(contents()->ShouldDisplayURL());
  EXPECT_TRUE(contents()->ShouldDisplayFavIcon());
  EXPECT_FALSE(contents()->IsBookmarkBarAlwaysVisible());
  EXPECT_FALSE(contents()->FocusLocationBarByDefault());

  // Start a pending load for a DOMUI.
  GURL new_tab_url(chrome::kChromeUINewTabURL);
  controller()->LoadURL(new_tab_url, GURL(), PageTransition::LINK);
  EXPECT_FALSE(contents()->ShouldDisplayURL());
  EXPECT_FALSE(contents()->ShouldDisplayFavIcon());
  EXPECT_FALSE(contents()->IsBookmarkBarAlwaysVisible());
  EXPECT_TRUE(contents()->FocusLocationBarByDefault());

  // Committing DOM UI is tested above.
}
<commit_msg>Fix the DOMUIToStandard unit test and uncomment it. The NavigationController wasn't getting hooked up properly to the WebContents, and we were getting the wrong RenderViewHost out of it later on in the test. Review URL: http://codereview.chromium.org/55045<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/dom_ui/new_tab_ui.h"
#include "chrome/browser/renderer_host/test_render_view_host.h"
#include "chrome/common/url_constants.h"
#include "testing/gtest/include/gtest/gtest.h"

class DOMUITest : public RenderViewHostTestHarness {
 public:
  DOMUITest() {}

  // Tests navigating with a DOM UI from a fresh (nothing pending or committed)
  // state, through pending, committed, then another navigation. The first page
  // ID that we should use is passed as a parameter. We'll use the next two
  // values. This must be increasing for the life of the tests.
  static void DoNavigationTest(WebContents* contents, int page_id) {
    NavigationController* controller = contents->controller();

    // Start a pending load.
    GURL new_tab_url(chrome::kChromeUINewTabURL);
    controller->LoadURL(new_tab_url, GURL(), PageTransition::LINK);

    // The navigation entry should be pending with no committed entry.
    ASSERT_TRUE(controller->GetPendingEntry());
    ASSERT_FALSE(controller->GetLastCommittedEntry());

    // Check the things the pending DOM UI should have set.
    EXPECT_FALSE(contents->ShouldDisplayURL());
    EXPECT_FALSE(contents->ShouldDisplayFavIcon());
    EXPECT_TRUE(contents->IsBookmarkBarAlwaysVisible());
    EXPECT_TRUE(contents->FocusLocationBarByDefault());

    // Now commit the load.
    static_cast<TestRenderViewHost*>(
        contents->render_view_host())->SendNavigate(page_id, new_tab_url);

    // The same flags should be set as before now that the load has committed.
    EXPECT_FALSE(contents->ShouldDisplayURL());
    EXPECT_FALSE(contents->ShouldDisplayFavIcon());
    EXPECT_TRUE(contents->IsBookmarkBarAlwaysVisible());
    EXPECT_TRUE(contents->FocusLocationBarByDefault());

    // Start a pending navigation to a regular page.
    GURL next_url("http://google.com/");
    controller->LoadURL(next_url, GURL(), PageTransition::LINK);

    // Check the flags. Some should reflect the new page (URL, title), some
    // should reflect the old one (bookmark bar) until it has committed.
    EXPECT_TRUE(contents->ShouldDisplayURL());
    EXPECT_TRUE(contents->ShouldDisplayFavIcon());
    EXPECT_TRUE(contents->IsBookmarkBarAlwaysVisible());
    EXPECT_FALSE(contents->FocusLocationBarByDefault());

    // Commit the regular page load. Note that we must send it to the "pending"
    // RenderViewHost if there is one, since this transition will also cause a
    // process transition, and our RVH pointer will be the "committed" one.
    // In the second call to this function from DOMUIToStandard, it won't
    // actually be pending, which is the point of this test.
    if (contents->render_manager()->pending_render_view_host()) {
      static_cast<TestRenderViewHost*>(
          contents->render_manager()->pending_render_view_host())->SendNavigate(
              page_id + 1, next_url);
    } else {
      static_cast<TestRenderViewHost*>(
          contents->render_view_host())->SendNavigate(page_id + 1, next_url);
    }

    // The state should now reflect a regular page.
    EXPECT_TRUE(contents->ShouldDisplayURL());
    EXPECT_TRUE(contents->ShouldDisplayFavIcon());
    EXPECT_FALSE(contents->IsBookmarkBarAlwaysVisible());
    EXPECT_FALSE(contents->FocusLocationBarByDefault());
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(DOMUITest);
};

// Tests that the New Tab Page flags are correctly set and propogated by
// WebContents when we first navigate to a DOM UI page, then to a standard
// non-DOM-UI page.
TEST_F(DOMUITest, DOMUIToStandard) {
  DoNavigationTest(contents(), 1);

  // Test the case where we're not doing the initial navigation. This is
  // slightly different than the very-first-navigation case since the
  // SiteInstance will be the same (the original WebContents must still be
  // alive), which will trigger different behavior in RenderViewHostManager.
  WebContents* contents2 = new TestWebContents(profile_.get(), NULL,
      &rvh_factory_);
  NavigationController* controller2 =
      new NavigationController(contents2, profile_.get());
  contents2->set_controller(controller2);

  DoNavigationTest(contents2, 101);
  contents2->CloseContents();
}

TEST_F(DOMUITest, DOMUIToDOMUI) {
  // Do a load (this state is tested above).
  GURL new_tab_url(chrome::kChromeUINewTabURL);
  controller()->LoadURL(new_tab_url, GURL(), PageTransition::LINK);
  rvh()->SendNavigate(1, new_tab_url);

  // Start another pending load of the new tab page.
  controller()->LoadURL(new_tab_url, GURL(), PageTransition::LINK);
  rvh()->SendNavigate(2, new_tab_url);

  // The flags should be the same as the non-pending state.
  EXPECT_FALSE(contents()->ShouldDisplayURL());
  EXPECT_FALSE(contents()->ShouldDisplayFavIcon());
  EXPECT_TRUE(contents()->IsBookmarkBarAlwaysVisible());
  EXPECT_TRUE(contents()->FocusLocationBarByDefault());
}

TEST_F(DOMUITest, StandardToDOMUI) {
  // Start a pending navigation to a regular page.
  GURL std_url("http://google.com/");
  controller()->LoadURL(std_url, GURL(), PageTransition::LINK);

  // The state should now reflect the default.
  EXPECT_TRUE(contents()->ShouldDisplayURL());
  EXPECT_TRUE(contents()->ShouldDisplayFavIcon());
  EXPECT_FALSE(contents()->IsBookmarkBarAlwaysVisible());
  EXPECT_FALSE(contents()->FocusLocationBarByDefault());

  // Commit the load, the state should be the same.
  rvh()->SendNavigate(1, std_url);
  EXPECT_TRUE(contents()->ShouldDisplayURL());
  EXPECT_TRUE(contents()->ShouldDisplayFavIcon());
  EXPECT_FALSE(contents()->IsBookmarkBarAlwaysVisible());
  EXPECT_FALSE(contents()->FocusLocationBarByDefault());

  // Start a pending load for a DOMUI.
  GURL new_tab_url(chrome::kChromeUINewTabURL);
  controller()->LoadURL(new_tab_url, GURL(), PageTransition::LINK);
  EXPECT_FALSE(contents()->ShouldDisplayURL());
  EXPECT_FALSE(contents()->ShouldDisplayFavIcon());
  EXPECT_FALSE(contents()->IsBookmarkBarAlwaysVisible());
  EXPECT_TRUE(contents()->FocusLocationBarByDefault());

  // Committing DOM UI is tested above.
}
<|endoftext|>


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

#include "chrome/browser/download/download_util.h"

#include <string>

#include "app/gfx/canvas.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/file_util.h"
#include "base/string_util.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/download/download_item_model.h"
#include "chrome/browser/download/download_manager.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "grit/theme_resources.h"
#include "skia/ext/image_operations.h"
#include "third_party/skia/include/core/SkPath.h"
#include "third_party/skia/include/core/SkShader.h"

#if defined(OS_WIN) || defined(TOOLKIT_VIEWS)
#include "app/os_exchange_data.h"
#endif

#if defined(OS_WIN)
#include "base/base_drag_source.h"
#include "views/drag_utils.h"
#endif

namespace download_util {

// How many times to cycle the complete animation. This should be an odd number
// so that the animation ends faded out.
static const int kCompleteAnimationCycles = 5;

// Download opening ------------------------------------------------------------

bool CanOpenDownload(DownloadItem* download) {
  FilePath file_to_use = download->full_path();
  if (!download->original_name().value().empty())
    file_to_use = download->original_name();

  const FilePath::StringType extension =
      file_util::GetFileExtensionFromPath(file_to_use);
  return !download->manager()->IsExecutable(extension);
}

void OpenDownload(DownloadItem* download) {
  if (download->state() == DownloadItem::IN_PROGRESS) {
    download->set_open_when_complete(!download->open_when_complete());
  } else if (download->state() == DownloadItem::COMPLETE) {
    download->NotifyObserversDownloadOpened();
    download->manager()->OpenDownload(download, NULL);
  }
}

// Download progress painting --------------------------------------------------

// Common bitmaps used for download progress animations. We load them once the
// first time we do a progress paint, then reuse them as they are always the
// same.
SkBitmap* g_foreground_16 = NULL;
SkBitmap* g_background_16 = NULL;
SkBitmap* g_foreground_32 = NULL;
SkBitmap* g_background_32 = NULL;

void PaintDownloadProgress(gfx::Canvas* canvas,
#if defined(OS_WIN) || defined(TOOLKIT_VIEWS)
                           views::View* containing_view,
#endif
                           int origin_x,
                           int origin_y,
                           int start_angle,
                           int percent_done,
                           PaintDownloadProgressSize size) {
  // Load up our common bitmaps
  if (!g_background_16) {
    ResourceBundle& rb = ResourceBundle::GetSharedInstance();
    g_foreground_16 = rb.GetBitmapNamed(IDR_DOWNLOAD_PROGRESS_FOREGROUND_16);
    g_background_16 = rb.GetBitmapNamed(IDR_DOWNLOAD_PROGRESS_BACKGROUND_16);
    g_foreground_32 = rb.GetBitmapNamed(IDR_DOWNLOAD_PROGRESS_FOREGROUND_32);
    g_background_32 = rb.GetBitmapNamed(IDR_DOWNLOAD_PROGRESS_BACKGROUND_32);
  }

  SkBitmap* background = (size == BIG) ? g_background_32 : g_background_16;
  SkBitmap* foreground = (size == BIG) ? g_foreground_32 : g_foreground_16;

  const int kProgressIconSize = (size == BIG) ? kBigProgressIconSize :
                                                kSmallProgressIconSize;

  // We start by storing the bounds of the background and foreground bitmaps
  // so that it is easy to mirror the bounds if the UI layout is RTL.
  gfx::Rect background_bounds(origin_x, origin_y,
                              background->width(), background->height());
  gfx::Rect foreground_bounds(origin_x, origin_y,
                              foreground->width(), foreground->height());

#if defined(OS_WIN) || defined(TOOLKIT_VIEWS)
  // Mirror the positions if necessary.
  int mirrored_x = containing_view->MirroredLeftPointForRect(background_bounds);
  background_bounds.set_x(mirrored_x);
  mirrored_x = containing_view->MirroredLeftPointForRect(foreground_bounds);
  foreground_bounds.set_x(mirrored_x);
#endif

  // Draw the background progress image.
  SkPaint background_paint;
  canvas->DrawBitmapInt(*background,
                        background_bounds.x(),
                        background_bounds.y(),
                        background_paint);

  // Layer the foreground progress image in an arc proportional to the download
  // progress. The arc grows clockwise, starting in the midnight position, as
  // the download progresses. However, if the download does not have known total
  // size (the server didn't give us one), then we just spin an arc around until
  // we're done.
  float sweep_angle = 0.0;
  float start_pos = static_cast<float>(kStartAngleDegrees);
  if (percent_done < 0) {
    sweep_angle = kUnknownAngleDegrees;
    start_pos = static_cast<float>(start_angle);
  } else if (percent_done > 0) {
    sweep_angle = static_cast<float>(kMaxDegrees / 100.0 * percent_done);
  }

  // Set up an arc clipping region for the foreground image. Don't bother using
  // a clipping region if it would round to 360 (really 0) degrees, since that
  // would eliminate the foreground completely and be quite confusing (it would
  // look like 0% complete when it should be almost 100%).
  SkPaint foreground_paint;
  if (sweep_angle < static_cast<float>(kMaxDegrees - 1)) {
    SkRect oval;
    oval.set(SkIntToScalar(foreground_bounds.x()),
             SkIntToScalar(foreground_bounds.y()),
             SkIntToScalar(foreground_bounds.x() + kProgressIconSize),
             SkIntToScalar(foreground_bounds.y() + kProgressIconSize));
    SkPath path;
    path.arcTo(oval,
               SkFloatToScalar(start_pos),
               SkFloatToScalar(sweep_angle), false);
    path.lineTo(SkIntToScalar(foreground_bounds.x() + kProgressIconSize / 2),
                SkIntToScalar(foreground_bounds.y() + kProgressIconSize / 2));

    SkShader* shader =
        SkShader::CreateBitmapShader(*foreground,
                                     SkShader::kClamp_TileMode,
                                     SkShader::kClamp_TileMode);
    SkMatrix shader_scale;
    shader_scale.setTranslate(SkIntToScalar(foreground_bounds.x()),
                              SkIntToScalar(foreground_bounds.y()));
    shader->setLocalMatrix(shader_scale);
    foreground_paint.setShader(shader);
    foreground_paint.setAntiAlias(true);
    shader->unref();
    canvas->drawPath(path, foreground_paint);
    return;
  }

  canvas->DrawBitmapInt(*foreground,
                        foreground_bounds.x(),
                        foreground_bounds.y(),
                        foreground_paint);
}

void PaintDownloadComplete(gfx::Canvas* canvas,
#if defined(OS_WIN) || defined(TOOLKIT_VIEWS)
                           views::View* containing_view,
#endif
                           int origin_x,
                           int origin_y,
                           double animation_progress,
                           PaintDownloadProgressSize size) {
  // Load up our common bitmaps.
  if (!g_foreground_16) {
    ResourceBundle& rb = ResourceBundle::GetSharedInstance();
    g_foreground_16 = rb.GetBitmapNamed(IDR_DOWNLOAD_PROGRESS_FOREGROUND_16);
    g_foreground_32 = rb.GetBitmapNamed(IDR_DOWNLOAD_PROGRESS_FOREGROUND_32);
  }

  SkBitmap* complete = (size == BIG) ? g_foreground_32 : g_foreground_16;

  gfx::Rect complete_bounds(origin_x, origin_y,
                            complete->width(), complete->height());
#if defined(OS_WIN) || defined(TOOLKIT_VIEWS)
  // Mirror the positions if necessary.
  complete_bounds.set_x(
      containing_view->MirroredLeftPointForRect(complete_bounds));
#endif

  // Start at full opacity, then loop back and forth five times before ending
  // at zero opacity.
  static const double PI = 3.141592653589793;
  double opacity = sin(animation_progress * PI * kCompleteAnimationCycles +
                   PI/2) / 2 + 0.5;

  SkRect bounds;
  bounds.set(SkIntToScalar(complete_bounds.x()),
             SkIntToScalar(complete_bounds.y()),
             SkIntToScalar(complete_bounds.x() + complete_bounds.width()),
             SkIntToScalar(complete_bounds.y() + complete_bounds.height()));
  canvas->saveLayerAlpha(&bounds,
                         static_cast<int>(255.0 * opacity),
                         SkCanvas::kARGB_ClipLayer_SaveFlag);
  canvas->drawARGB(0, 255, 255, 255, SkXfermode::kClear_Mode);
  canvas->DrawBitmapInt(*complete, complete_bounds.x(), complete_bounds.y());
  canvas->restore();
}

// Load a language dependent height so that the dangerous download confirmation
// message doesn't overlap with the download link label.
int GetBigProgressIconSize() {
  static int big_progress_icon_size = 0;
  if (big_progress_icon_size == 0) {
    string16 locale_size_str =
        WideToUTF16Hack(
        l10n_util::GetString(IDS_DOWNLOAD_BIG_PROGRESS_SIZE));
    bool rc = StringToInt(locale_size_str, &big_progress_icon_size);
    if (!rc || big_progress_icon_size < kBigProgressIconSize) {
      NOTREACHED();
      big_progress_icon_size = kBigProgressIconSize;
    }
  }

  return big_progress_icon_size;
}

int GetBigProgressIconOffset() {
  return (GetBigProgressIconSize() - kBigIconSize) / 2;
}

#if defined(OS_WIN) || defined(TOOLKIT_VIEWS)
// Download dragging
void DragDownload(const DownloadItem* download, SkBitmap* icon) {
#if defined(OS_WIN)
  DCHECK(download);

  // Set up our OLE machinery
  scoped_refptr<OSExchangeData> data(new OSExchangeData);
  if (icon)
    drag_utils::CreateDragImageForFile(download->file_name().ToWStringHack(),
                                       icon, data);
  data->SetFilename(download->full_path().ToWStringHack());
  scoped_refptr<BaseDragSource> drag_source(new BaseDragSource);

  // Run the drag and drop loop
  DWORD effects;
  DoDragDrop(data.get(), drag_source.get(), DROPEFFECT_COPY | DROPEFFECT_LINK,
             &effects);
#else
  NOTIMPLEMENTED();
#endif
}
#endif

}  // namespace download_util
<commit_msg>Commit patch for Pierre-Antoine LaFayette, original CL: http://codereview.chromium.org/164119<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Download utility implementation

#include "chrome/browser/download/download_util.h"

#include <string>

#include "app/gfx/canvas.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/file_util.h"
#include "base/string_util.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/download/download_item_model.h"
#include "chrome/browser/download/download_manager.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "grit/theme_resources.h"
#include "net/base/mime_util.h"
#include "skia/ext/image_operations.h"
#include "third_party/skia/include/core/SkPath.h"
#include "third_party/skia/include/core/SkShader.h"

#if defined(OS_WIN) || defined(TOOLKIT_VIEWS)
#include "app/os_exchange_data.h"
#endif

#if defined(OS_WIN)
#include "base/base_drag_source.h"
#include "views/drag_utils.h"
#endif

namespace download_util {

// How many times to cycle the complete animation. This should be an odd number
// so that the animation ends faded out.
static const int kCompleteAnimationCycles = 5;

// Download opening ------------------------------------------------------------

bool CanOpenDownload(DownloadItem* download) {
  FilePath file_to_use = download->full_path();
  if (!download->original_name().value().empty())
    file_to_use = download->original_name();

  const FilePath::StringType extension =
      file_util::GetFileExtensionFromPath(file_to_use);
  return !download->manager()->IsExecutable(extension);
}

void OpenDownload(DownloadItem* download) {
  if (download->state() == DownloadItem::IN_PROGRESS) {
    download->set_open_when_complete(!download->open_when_complete());
  } else if (download->state() == DownloadItem::COMPLETE) {
    download->NotifyObserversDownloadOpened();
    download->manager()->OpenDownload(download, NULL);
  }
}

// Download progress painting --------------------------------------------------

// Common bitmaps used for download progress animations. We load them once the
// first time we do a progress paint, then reuse them as they are always the
// same.
SkBitmap* g_foreground_16 = NULL;
SkBitmap* g_background_16 = NULL;
SkBitmap* g_foreground_32 = NULL;
SkBitmap* g_background_32 = NULL;

void PaintDownloadProgress(gfx::Canvas* canvas,
#if defined(OS_WIN) || defined(TOOLKIT_VIEWS)
                           views::View* containing_view,
#endif
                           int origin_x,
                           int origin_y,
                           int start_angle,
                           int percent_done,
                           PaintDownloadProgressSize size) {
  // Load up our common bitmaps
  if (!g_background_16) {
    ResourceBundle& rb = ResourceBundle::GetSharedInstance();
    g_foreground_16 = rb.GetBitmapNamed(IDR_DOWNLOAD_PROGRESS_FOREGROUND_16);
    g_background_16 = rb.GetBitmapNamed(IDR_DOWNLOAD_PROGRESS_BACKGROUND_16);
    g_foreground_32 = rb.GetBitmapNamed(IDR_DOWNLOAD_PROGRESS_FOREGROUND_32);
    g_background_32 = rb.GetBitmapNamed(IDR_DOWNLOAD_PROGRESS_BACKGROUND_32);
  }

  SkBitmap* background = (size == BIG) ? g_background_32 : g_background_16;
  SkBitmap* foreground = (size == BIG) ? g_foreground_32 : g_foreground_16;

  const int kProgressIconSize = (size == BIG) ? kBigProgressIconSize :
                                                kSmallProgressIconSize;

  // We start by storing the bounds of the background and foreground bitmaps
  // so that it is easy to mirror the bounds if the UI layout is RTL.
  gfx::Rect background_bounds(origin_x, origin_y,
                              background->width(), background->height());
  gfx::Rect foreground_bounds(origin_x, origin_y,
                              foreground->width(), foreground->height());

#if defined(OS_WIN) || defined(TOOLKIT_VIEWS)
  // Mirror the positions if necessary.
  int mirrored_x = containing_view->MirroredLeftPointForRect(background_bounds);
  background_bounds.set_x(mirrored_x);
  mirrored_x = containing_view->MirroredLeftPointForRect(foreground_bounds);
  foreground_bounds.set_x(mirrored_x);
#endif

  // Draw the background progress image.
  SkPaint background_paint;
  canvas->DrawBitmapInt(*background,
                        background_bounds.x(),
                        background_bounds.y(),
                        background_paint);

  // Layer the foreground progress image in an arc proportional to the download
  // progress. The arc grows clockwise, starting in the midnight position, as
  // the download progresses. However, if the download does not have known total
  // size (the server didn't give us one), then we just spin an arc around until
  // we're done.
  float sweep_angle = 0.0;
  float start_pos = static_cast<float>(kStartAngleDegrees);
  if (percent_done < 0) {
    sweep_angle = kUnknownAngleDegrees;
    start_pos = static_cast<float>(start_angle);
  } else if (percent_done > 0) {
    sweep_angle = static_cast<float>(kMaxDegrees / 100.0 * percent_done);
  }

  // Set up an arc clipping region for the foreground image. Don't bother using
  // a clipping region if it would round to 360 (really 0) degrees, since that
  // would eliminate the foreground completely and be quite confusing (it would
  // look like 0% complete when it should be almost 100%).
  SkPaint foreground_paint;
  if (sweep_angle < static_cast<float>(kMaxDegrees - 1)) {
    SkRect oval;
    oval.set(SkIntToScalar(foreground_bounds.x()),
             SkIntToScalar(foreground_bounds.y()),
             SkIntToScalar(foreground_bounds.x() + kProgressIconSize),
             SkIntToScalar(foreground_bounds.y() + kProgressIconSize));
    SkPath path;
    path.arcTo(oval,
               SkFloatToScalar(start_pos),
               SkFloatToScalar(sweep_angle), false);
    path.lineTo(SkIntToScalar(foreground_bounds.x() + kProgressIconSize / 2),
                SkIntToScalar(foreground_bounds.y() + kProgressIconSize / 2));

    SkShader* shader =
        SkShader::CreateBitmapShader(*foreground,
                                     SkShader::kClamp_TileMode,
                                     SkShader::kClamp_TileMode);
    SkMatrix shader_scale;
    shader_scale.setTranslate(SkIntToScalar(foreground_bounds.x()),
                              SkIntToScalar(foreground_bounds.y()));
    shader->setLocalMatrix(shader_scale);
    foreground_paint.setShader(shader);
    foreground_paint.setAntiAlias(true);
    shader->unref();
    canvas->drawPath(path, foreground_paint);
    return;
  }

  canvas->DrawBitmapInt(*foreground,
                        foreground_bounds.x(),
                        foreground_bounds.y(),
                        foreground_paint);
}

void PaintDownloadComplete(gfx::Canvas* canvas,
#if defined(OS_WIN) || defined(TOOLKIT_VIEWS)
                           views::View* containing_view,
#endif
                           int origin_x,
                           int origin_y,
                           double animation_progress,
                           PaintDownloadProgressSize size) {
  // Load up our common bitmaps.
  if (!g_foreground_16) {
    ResourceBundle& rb = ResourceBundle::GetSharedInstance();
    g_foreground_16 = rb.GetBitmapNamed(IDR_DOWNLOAD_PROGRESS_FOREGROUND_16);
    g_foreground_32 = rb.GetBitmapNamed(IDR_DOWNLOAD_PROGRESS_FOREGROUND_32);
  }

  SkBitmap* complete = (size == BIG) ? g_foreground_32 : g_foreground_16;

  gfx::Rect complete_bounds(origin_x, origin_y,
                            complete->width(), complete->height());
#if defined(OS_WIN) || defined(TOOLKIT_VIEWS)
  // Mirror the positions if necessary.
  complete_bounds.set_x(
      containing_view->MirroredLeftPointForRect(complete_bounds));
#endif

  // Start at full opacity, then loop back and forth five times before ending
  // at zero opacity.
  static const double PI = 3.141592653589793;
  double opacity = sin(animation_progress * PI * kCompleteAnimationCycles +
                   PI/2) / 2 + 0.5;

  SkRect bounds;
  bounds.set(SkIntToScalar(complete_bounds.x()),
             SkIntToScalar(complete_bounds.y()),
             SkIntToScalar(complete_bounds.x() + complete_bounds.width()),
             SkIntToScalar(complete_bounds.y() + complete_bounds.height()));
  canvas->saveLayerAlpha(&bounds,
                         static_cast<int>(255.0 * opacity),
                         SkCanvas::kARGB_ClipLayer_SaveFlag);
  canvas->drawARGB(0, 255, 255, 255, SkXfermode::kClear_Mode);
  canvas->DrawBitmapInt(*complete, complete_bounds.x(), complete_bounds.y());
  canvas->restore();
}

// Load a language dependent height so that the dangerous download confirmation
// message doesn't overlap with the download link label.
int GetBigProgressIconSize() {
  static int big_progress_icon_size = 0;
  if (big_progress_icon_size == 0) {
    string16 locale_size_str =
        WideToUTF16Hack(
        l10n_util::GetString(IDS_DOWNLOAD_BIG_PROGRESS_SIZE));
    bool rc = StringToInt(locale_size_str, &big_progress_icon_size);
    if (!rc || big_progress_icon_size < kBigProgressIconSize) {
      NOTREACHED();
      big_progress_icon_size = kBigProgressIconSize;
    }
  }

  return big_progress_icon_size;
}

int GetBigProgressIconOffset() {
  return (GetBigProgressIconSize() - kBigIconSize) / 2;
}

#if defined(OS_WIN) || defined(TOOLKIT_VIEWS)
// Download dragging
void DragDownload(const DownloadItem* download, SkBitmap* icon) {
#if defined(OS_WIN)
  DCHECK(download);

  // Set up our OLE machinery
  scoped_refptr<OSExchangeData> data(new OSExchangeData);

  const FilePath::StringType file_name = download->file_name().value();
  if (icon)
    drag_utils::CreateDragImageForFile(file_name, icon, data);

  const FilePath full_path = download->full_path();
  data->SetFilename(full_path.value());

  std::string mime_type = download->mime_type();
  if (mime_type.empty())
    net::GetMimeTypeFromFile(full_path, &mime_type);

  // Add URL so that we can load supported files when dragged to TabContents.
  if (net::IsSupportedMimeType(mime_type))
    data->SetURL(GURL(full_path.value()), file_name);

  scoped_refptr<BaseDragSource> drag_source(new BaseDragSource);

  // Run the drag and drop loop
  DWORD effects;
  DoDragDrop(data.get(), drag_source.get(), DROPEFFECT_COPY | DROPEFFECT_LINK,
             &effects);
#else
  NOTIMPLEMENTED();
#endif
}
#endif

}  // namespace download_util
<|endoftext|>