<commit_before>#include "args.hpp"
#include <iostream>

namespace {
    using doc_t = const char* const;
    doc_t inputDoc = "<path> Path to an input video file. Can be used multiple times. Must not be "
                     "used with --camera.";
    doc_t gtDoc = "<path> Text file containing ground truth data. Using this option enables "
                  "quality evaluation. If used at all, this option must be used as many times as "
                  "--file. Use --out to save evaluation results.";
    doc_t cameraDoc = "<int> Input camera device ID. When this option is used, stream from the "
                      "specified camera will be used as input. Using ID 0 selects the default "
                      "camera, if available. Must not be used with --input, --wait, --fast, "
                      "--frame, --pause.";
    doc_t recordDirDoc = "<dir> Output directory to save video to. A new video file will be "
                         "created, storing the unmodified input video. The name of the video file "
                         "will be determined by system time. The directory must exist.";
    doc_t pauseFpDoc = "Playback will pause whenever a detection is deemed a false positive. Must "
                       "be used with --gt.";
    doc_t pauseFnDoc = "Playback will pause whenever a detection is deemed a false negative. Must "
                       "be used with --gt.";
    doc_t pauseRgDoc = "Playback will pause whenever a regression is detected, i.e. whenever a "
                       "frame is evaluated as false and baseline is true. Must be used with "
                       "--baseline.";
    doc_t pauseImDoc = "Playback will pause whenever an improvement is detected, i.e. whenever a "
                       "frame is evaluated as true and baseline is false. Must be used with "
                       "--baseline.";
    doc_t evalDirDoc = "<dir> Output directory to save evaluation results to. Must be used with "
                       "--gt.";
    doc_t scoreFileDoc = "<file> File to write a numeric evaluation score to.";
    doc_t baselineDoc = "<path> File with previously saved results (via --out) for comparison. "
                        "When used, the playback will pause to demonstrate where the results "
                        "differ. Must be used with --gt.";
    doc_t includeDoc = "<path> File with additional command-line arguments. The format is the same "
                       "as when specifying parameters on the command line. Whitespace such as tabs "
                       "and endlines is allowed.";
    doc_t pausedDoc = "Playback will be paused on the first frame. Shorthand for --frame 1. Must "
                      "not be used with --camera.";
    doc_t frameDoc = "<frame> Playback will be paused on the specified frame number. If there are "
                     "multiple input files, playback will be paused in each file that contains a "
                     "frame with the specified frame number. Must not be used with --camera.";
    doc_t fastDoc = "Sets the maximum playback speed. Shorthand for --wait 0. Must not be used "
                    "with --camera, --headless.";
    doc_t waitDoc = "<ms> Specifies the frame time in milliseconds, allowing for slow playback. "
                    "Must not be used with --camera, --headless.";
    doc_t headlessDoc = "Don't draw any GUI unless the playback is paused. Must be used with --gt. "
                        "Must not be used with --wait, --fast.";
    doc_t demoDoc = "Force demo visualization method. This visualization method is preferred when "
                    "--camera is used.";
    doc_t debugDoc = "Force debug visualization method. This visualization method is preferred "
                     "when --input is used.";
    doc_t helpDoc = "Display help.";
    doc_t defaultsDoc = "Display default values for all parameters.";
    doc_t algorithmDoc = "<name> Specifies the name of the algorithm variant. Use --list to list "
                         "available algorithm names.";
    doc_t listDoc = "Display available algorithm names. Use --algorithm to select an algorithm.";
    doc_t paramDocI = "<int> Algorithm parameter.";
    doc_t paramDocF = "<float> Algorithm parameter.";
    doc_t paramDocUint8 = "<uint8> Algorithm parameter.";
}

Args::Args(int argc, char** argv)
    : inputs(),
      gts(),
      camera(-1),
      recordDir("."),
      pauseFn(false),
      pauseFp(false),
      pauseRg(false),
      pauseIm(false),
      evalDir(),
      baseline(),
      frame(-1),
      wait(-1),
      headless(false),
      demo(false),
      debug(false),
      params(),
      mParser(),
      mHelp(false),
      mDefaults(false),
      mList(false) {

    // add commands
    mParser.add("--input", inputDoc, inputs);
    mParser.add("--gt", gtDoc, gts);
    mParser.add("--camera", cameraDoc, camera);
    mParser.add("--record-dir", recordDirDoc, recordDir);
    mParser.add("--pause-fp", pauseFpDoc, pauseFp);
    mParser.add("--pause-fn", pauseFnDoc, pauseFn);
    mParser.add("--pause-rg", pauseRgDoc, pauseRg);
    mParser.add("--pause-im", pauseImDoc, pauseIm);
    mParser.add("--eval-dir", evalDirDoc, evalDir);
    mParser.add("--score-file", scoreFileDoc, scoreFile);
    mParser.add("--baseline", baselineDoc, baseline);
    mParser.add("--include", includeDoc, [this](const std::string& path) { mParser.parse(path); });
    mParser.add("--paused", pausedDoc, [this]() { frame = 1; });
    mParser.add("--frame", frameDoc, frame);
    mParser.add("--fast", fastDoc, [this]() { wait = 0; });
    mParser.add("--wait", waitDoc, wait);
    mParser.add("--headless", headlessDoc, headless);
    mParser.add("--demo", demoDoc, demo);
    mParser.add("--debug", debugDoc, debug);
    mParser.add("--help", helpDoc, mHelp);
    mParser.add("--defaults", defaultsDoc, mDefaults);

    // add algorithm params
    mParser.add("--algorithm", algorithmDoc, params.name);
    mParser.add("--list", listDoc, mList);

    mParser.add("--p-thresh", paramDocUint8, params.diff.thresh);
    mParser.add("--p-min-gap-x", paramDocF, params.maxGapX);
    mParser.add("--p-min-gap-y", paramDocF, params.minGapY);
    mParser.add("--p-max-image-height", paramDocI, params.maxImageHeight);
    mParser.add("--p-min-strip-height", paramDocI, params.minStripHeight);
    mParser.add("--p-min-strips-in-object", paramDocI, params.minStripsInObject);
    mParser.add("--p-min-strip-area", paramDocF, params.minStripArea);
    mParser.add("--p-min-aspect", paramDocF, params.minAspect);
    mParser.add("--p-match-aspect-max", paramDocF, params.matchAspectMax);
    mParser.add("--p-match-area-max", paramDocF, params.matchAreaMax);
    mParser.add("--p-match-distance-max", paramDocF, params.matchDistanceMax);
    mParser.add("--p-match-angle-max", paramDocF, params.matchAngleMax);
    mParser.add("--p-match-aspect-weight", paramDocF, params.matchAspectWeight);
    mParser.add("--p-match-area-weight", paramDocF, params.matchAreaWeight);
    mParser.add("--p-match-distance-weight", paramDocF, params.matchDistanceWeight);
    mParser.add("--p-match-angle-weight", paramDocF, params.matchAngleWeight);
    mParser.add("--p-select-max-distance", paramDocF, params.selectMaxDistance);

    mParser.add("--p-min-strips-in-component", paramDocI, params.minStripsInComponent);
    mParser.add("--p-min-strips-in-cluster", paramDocI, params.minStripsInCluster);
    mParser.add("--p-min-cluster-length", paramDocF, params.minClusterLength);
    mParser.add("--p-weight-height-ratio", paramDocF, params.heightRatioWeight);
    mParser.add("--p-weight-distance", paramDocF, params.distanceWeight);
    mParser.add("--p-weight-gaps", paramDocF, params.gapsWeight);
    mParser.add("--p-max-height-ratio-internal", paramDocF, params.maxHeightRatioInternal);
    mParser.add("--p-max-height-ratio-external", paramDocF, params.maxHeightRatioExternal);
    mParser.add("--p-max-distance", paramDocF, params.maxDistance);
    mParser.add("--p-max-gaps-length", paramDocF, params.maxGapsLength);
    mParser.add("--p-min-motion", paramDocF, params.minMotion);

    // parse command-line
    mParser.parse(argc, argv);

    // if requested, display help and exit
    if (mHelp) {
        mParser.printHelp(std::cerr);
        std::exit(-1);
    }

    // if requested, display defaults and exit
    if (mDefaults) {
        mDefaults = false;
        mParser.printValues(std::cerr, '\n');
        std::exit(-1);
    }

    // if requested, display list and exit
    if (mList) {
        auto names = fmo::Algorithm::listFactories();
        for (auto& name : names) { std::cerr << name << '\n'; }
        std::exit(-1);
    }

    // validate parameters, throw if there is trouble
    validate();
}

void Args::validate() const {
    if (inputs.empty() && camera == -1) {
        throw std::runtime_error("one of --input, --camera must be specified");
    }
    if (camera != -1) {
        if (!inputs.empty()) { throw std::runtime_error("--camera cannot be used with --input"); }
        if (wait != -1) {
            throw std::runtime_error("--camera cannot be used with --wait or --fast");
        }
        if (frame != -1) {
            throw std::runtime_error("--camera canot be used with --frame or --pause");
        }
    }
    if (!gts.empty()) {
        if (gts.size() != inputs.size()) {
            std::cerr << "have " << inputs.size() << " inputs and " << gts.size() << " gts\n";
            throw std::runtime_error("there must be one --gt for each --input");
        }
    }
    if (gts.empty()) {
        if (pauseFn || pauseFp) {
            throw std::runtime_error("--pause-fn|fp must be used with --gt");
        }
        if (!evalDir.empty()) { throw std::runtime_error("--eval-dir must be used with --gt"); }
        if (!baseline.empty()) { throw std::runtime_error("--baseline must be used with --gt"); }
        if (headless) { throw std::runtime_error("--headless must be used with --gt"); }
    }
    if (baseline.empty()) {
        if (pauseRg || pauseIm) {
            throw std::runtime_error("--pause-rg|im must be used with --baseline");
        }
    }
    if (demo && debug) { throw std::runtime_error("--demo must not be used with --debug"); }
    if (headless && wait != -1) {
        throw std::runtime_error("--headless cannot be used with --wait or --fast");
    }
}
<commit_msg>Fix typo in parameter name<commit_after>#include "args.hpp"
#include <iostream>

namespace {
    using doc_t = const char* const;
    doc_t inputDoc = "<path> Path to an input video file. Can be used multiple times. Must not be "
                     "used with --camera.";
    doc_t gtDoc = "<path> Text file containing ground truth data. Using this option enables "
                  "quality evaluation. If used at all, this option must be used as many times as "
                  "--file. Use --out to save evaluation results.";
    doc_t cameraDoc = "<int> Input camera device ID. When this option is used, stream from the "
                      "specified camera will be used as input. Using ID 0 selects the default "
                      "camera, if available. Must not be used with --input, --wait, --fast, "
                      "--frame, --pause.";
    doc_t recordDirDoc = "<dir> Output directory to save video to. A new video file will be "
                         "created, storing the unmodified input video. The name of the video file "
                         "will be determined by system time. The directory must exist.";
    doc_t pauseFpDoc = "Playback will pause whenever a detection is deemed a false positive. Must "
                       "be used with --gt.";
    doc_t pauseFnDoc = "Playback will pause whenever a detection is deemed a false negative. Must "
                       "be used with --gt.";
    doc_t pauseRgDoc = "Playback will pause whenever a regression is detected, i.e. whenever a "
                       "frame is evaluated as false and baseline is true. Must be used with "
                       "--baseline.";
    doc_t pauseImDoc = "Playback will pause whenever an improvement is detected, i.e. whenever a "
                       "frame is evaluated as true and baseline is false. Must be used with "
                       "--baseline.";
    doc_t evalDirDoc = "<dir> Output directory to save evaluation results to. Must be used with "
                       "--gt.";
    doc_t scoreFileDoc = "<file> File to write a numeric evaluation score to.";
    doc_t baselineDoc = "<path> File with previously saved results (via --out) for comparison. "
                        "When used, the playback will pause to demonstrate where the results "
                        "differ. Must be used with --gt.";
    doc_t includeDoc = "<path> File with additional command-line arguments. The format is the same "
                       "as when specifying parameters on the command line. Whitespace such as tabs "
                       "and endlines is allowed.";
    doc_t pausedDoc = "Playback will be paused on the first frame. Shorthand for --frame 1. Must "
                      "not be used with --camera.";
    doc_t frameDoc = "<frame> Playback will be paused on the specified frame number. If there are "
                     "multiple input files, playback will be paused in each file that contains a "
                     "frame with the specified frame number. Must not be used with --camera.";
    doc_t fastDoc = "Sets the maximum playback speed. Shorthand for --wait 0. Must not be used "
                    "with --camera, --headless.";
    doc_t waitDoc = "<ms> Specifies the frame time in milliseconds, allowing for slow playback. "
                    "Must not be used with --camera, --headless.";
    doc_t headlessDoc = "Don't draw any GUI unless the playback is paused. Must be used with --gt. "
                        "Must not be used with --wait, --fast.";
    doc_t demoDoc = "Force demo visualization method. This visualization method is preferred when "
                    "--camera is used.";
    doc_t debugDoc = "Force debug visualization method. This visualization method is preferred "
                     "when --input is used.";
    doc_t helpDoc = "Display help.";
    doc_t defaultsDoc = "Display default values for all parameters.";
    doc_t algorithmDoc = "<name> Specifies the name of the algorithm variant. Use --list to list "
                         "available algorithm names.";
    doc_t listDoc = "Display available algorithm names. Use --algorithm to select an algorithm.";
    doc_t paramDocI = "<int> Algorithm parameter.";
    doc_t paramDocF = "<float> Algorithm parameter.";
    doc_t paramDocUint8 = "<uint8> Algorithm parameter.";
}

Args::Args(int argc, char** argv)
    : inputs(),
      gts(),
      camera(-1),
      recordDir("."),
      pauseFn(false),
      pauseFp(false),
      pauseRg(false),
      pauseIm(false),
      evalDir(),
      baseline(),
      frame(-1),
      wait(-1),
      headless(false),
      demo(false),
      debug(false),
      params(),
      mParser(),
      mHelp(false),
      mDefaults(false),
      mList(false) {

    // add commands
    mParser.add("--input", inputDoc, inputs);
    mParser.add("--gt", gtDoc, gts);
    mParser.add("--camera", cameraDoc, camera);
    mParser.add("--record-dir", recordDirDoc, recordDir);
    mParser.add("--pause-fp", pauseFpDoc, pauseFp);
    mParser.add("--pause-fn", pauseFnDoc, pauseFn);
    mParser.add("--pause-rg", pauseRgDoc, pauseRg);
    mParser.add("--pause-im", pauseImDoc, pauseIm);
    mParser.add("--eval-dir", evalDirDoc, evalDir);
    mParser.add("--score-file", scoreFileDoc, scoreFile);
    mParser.add("--baseline", baselineDoc, baseline);
    mParser.add("--include", includeDoc, [this](const std::string& path) { mParser.parse(path); });
    mParser.add("--paused", pausedDoc, [this]() { frame = 1; });
    mParser.add("--frame", frameDoc, frame);
    mParser.add("--fast", fastDoc, [this]() { wait = 0; });
    mParser.add("--wait", waitDoc, wait);
    mParser.add("--headless", headlessDoc, headless);
    mParser.add("--demo", demoDoc, demo);
    mParser.add("--debug", debugDoc, debug);
    mParser.add("--help", helpDoc, mHelp);
    mParser.add("--defaults", defaultsDoc, mDefaults);

    // add algorithm params
    mParser.add("--algorithm", algorithmDoc, params.name);
    mParser.add("--list", listDoc, mList);

    mParser.add("--p-thresh", paramDocUint8, params.diff.thresh);
    mParser.add("--p-max-gap-x", paramDocF, params.maxGapX);
    mParser.add("--p-min-gap-y", paramDocF, params.minGapY);
    mParser.add("--p-max-image-height", paramDocI, params.maxImageHeight);
    mParser.add("--p-min-strip-height", paramDocI, params.minStripHeight);
    mParser.add("--p-min-strips-in-object", paramDocI, params.minStripsInObject);
    mParser.add("--p-min-strip-area", paramDocF, params.minStripArea);
    mParser.add("--p-min-aspect", paramDocF, params.minAspect);
    mParser.add("--p-match-aspect-max", paramDocF, params.matchAspectMax);
    mParser.add("--p-match-area-max", paramDocF, params.matchAreaMax);
    mParser.add("--p-match-distance-max", paramDocF, params.matchDistanceMax);
    mParser.add("--p-match-angle-max", paramDocF, params.matchAngleMax);
    mParser.add("--p-match-aspect-weight", paramDocF, params.matchAspectWeight);
    mParser.add("--p-match-area-weight", paramDocF, params.matchAreaWeight);
    mParser.add("--p-match-distance-weight", paramDocF, params.matchDistanceWeight);
    mParser.add("--p-match-angle-weight", paramDocF, params.matchAngleWeight);
    mParser.add("--p-select-max-distance", paramDocF, params.selectMaxDistance);

    mParser.add("--p-min-strips-in-component", paramDocI, params.minStripsInComponent);
    mParser.add("--p-min-strips-in-cluster", paramDocI, params.minStripsInCluster);
    mParser.add("--p-min-cluster-length", paramDocF, params.minClusterLength);
    mParser.add("--p-weight-height-ratio", paramDocF, params.heightRatioWeight);
    mParser.add("--p-weight-distance", paramDocF, params.distanceWeight);
    mParser.add("--p-weight-gaps", paramDocF, params.gapsWeight);
    mParser.add("--p-max-height-ratio-internal", paramDocF, params.maxHeightRatioInternal);
    mParser.add("--p-max-height-ratio-external", paramDocF, params.maxHeightRatioExternal);
    mParser.add("--p-max-distance", paramDocF, params.maxDistance);
    mParser.add("--p-max-gaps-length", paramDocF, params.maxGapsLength);
    mParser.add("--p-min-motion", paramDocF, params.minMotion);

    // parse command-line
    mParser.parse(argc, argv);

    // if requested, display help and exit
    if (mHelp) {
        mParser.printHelp(std::cerr);
        std::exit(-1);
    }

    // if requested, display defaults and exit
    if (mDefaults) {
        mDefaults = false;
        mParser.printValues(std::cerr, '\n');
        std::exit(-1);
    }

    // if requested, display list and exit
    if (mList) {
        auto names = fmo::Algorithm::listFactories();
        for (auto& name : names) { std::cerr << name << '\n'; }
        std::exit(-1);
    }

    // validate parameters, throw if there is trouble
    validate();
}

void Args::validate() const {
    if (inputs.empty() && camera == -1) {
        throw std::runtime_error("one of --input, --camera must be specified");
    }
    if (camera != -1) {
        if (!inputs.empty()) { throw std::runtime_error("--camera cannot be used with --input"); }
        if (wait != -1) {
            throw std::runtime_error("--camera cannot be used with --wait or --fast");
        }
        if (frame != -1) {
            throw std::runtime_error("--camera canot be used with --frame or --pause");
        }
    }
    if (!gts.empty()) {
        if (gts.size() != inputs.size()) {
            std::cerr << "have " << inputs.size() << " inputs and " << gts.size() << " gts\n";
            throw std::runtime_error("there must be one --gt for each --input");
        }
    }
    if (gts.empty()) {
        if (pauseFn || pauseFp) {
            throw std::runtime_error("--pause-fn|fp must be used with --gt");
        }
        if (!evalDir.empty()) { throw std::runtime_error("--eval-dir must be used with --gt"); }
        if (!baseline.empty()) { throw std::runtime_error("--baseline must be used with --gt"); }
        if (headless) { throw std::runtime_error("--headless must be used with --gt"); }
    }
    if (baseline.empty()) {
        if (pauseRg || pauseIm) {
            throw std::runtime_error("--pause-rg|im must be used with --baseline");
        }
    }
    if (demo && debug) { throw std::runtime_error("--demo must not be used with --debug"); }
    if (headless && wait != -1) {
        throw std::runtime_error("--headless cannot be used with --wait or --fast");
    }
}
<|endoftext|>


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

#ifndef _COM_SUN_STAR_CHART2_SYMBOLSTYLE_HPP_
#include <com/sun/star/chart2/SymbolStyle.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_SYMBOL_HPP_
#include <com/sun/star/chart2/Symbol.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_LINESTYLE_HPP_
#include <com/sun/star/drawing/LineStyle.hpp>
#endif

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

using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::rtl::OUString;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Any;
using ::osl::MutexGuard;

namespace
{
static const ::rtl::OUString lcl_aServiceName(
    RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.chart2.NetChartTypeTemplate" ));
} // anonymous namespace

namespace chart
{

NetChartTypeTemplate::NetChartTypeTemplate(
    Reference< uno::XComponentContext > const & xContext,
    const ::rtl::OUString & rServiceName,
    chart2::StackMode eStackMode,
    bool bSymbols ) :
        ChartTypeTemplate( xContext, rServiceName ),
        m_eStackMode( eStackMode ),
        m_bHasSymbols( bSymbols )
{}

NetChartTypeTemplate::~NetChartTypeTemplate()
{}

chart2::StackMode NetChartTypeTemplate::getYStackMode() const
{
    return m_eStackMode;
}

Reference< chart2::XBoundedCoordinateSystem > NetChartTypeTemplate::createCoordinateSystem(
    const Reference< chart2::XBoundedCoordinateSystemContainer > & xCoordSysCnt )
{
    Reference< chart2::XCoordinateSystem > xCoordSys(
        new PolarCoordinateSystem( getDimension() ));
    Reference< chart2::XBoundedCoordinateSystem > xResult(
        new BoundedCoordinateSystem( xCoordSys ));

    chart2::ScaleData aScale;
    aScale.Scaling = new LinearScaling( 1.0, 0.0 );

    aScale.Orientation = chart2::AxisOrientation_REVERSE;
    xResult->setScaleByDimension(
        0, Reference< chart2::XScale >( new Scale( GetComponentContext(), aScale ) ));
    aScale.Orientation = chart2::AxisOrientation_MATHEMATICAL;
    xResult->setScaleByDimension(
        1, Reference< chart2::XScale >( new Scale( GetComponentContext(), aScale ) ));

    try
    {
        if( xCoordSys.is())
            xCoordSysCnt->addCoordinateSystem( xResult );
    }
    catch( lang::IllegalArgumentException ex )
    {
        ASSERT_EXCEPTION( ex );
    }

    return xResult;
}

Reference< chart2::XChartType > NetChartTypeTemplate::getDefaultChartType()
    throw (uno::RuntimeException)
{
    return new NetChartType();
}

// ____ XChartTypeTemplate ____
Reference< chart2::XDiagram > SAL_CALL
    NetChartTypeTemplate::createDiagram(
        const uno::Sequence< Reference< chart2::XDataSeries > >& aSeriesSeq )
    throw (uno::RuntimeException)
{
    // set symbol type at data series
    chart2::SymbolStyle eStyle = m_bHasSymbols
        ? chart2::SymbolStyle_STANDARD
        : chart2::SymbolStyle_NONE;

    for( sal_Int32 i = 0; i < aSeriesSeq.getLength(); ++i )
    {
        try
        {
            chart2::Symbol aSymbProp;
            Reference< beans::XPropertySet > xProp( aSeriesSeq[i], uno::UNO_QUERY_THROW );
            if( (xProp->getPropertyValue( C2U( "Symbol" )) >>= aSymbProp ) )
            {
                aSymbProp.aStyle = eStyle;
                if( m_bHasSymbols )
                    aSymbProp.nStandardSymbol = i;
                xProp->setPropertyValue( C2U( "Symbol" ), uno::makeAny( aSymbProp ));
            }
        }
        catch( uno::Exception & ex )
        {
            ASSERT_EXCEPTION( ex );
        }
    }

    // todo: set symbol type at data points

    return ChartTypeTemplate::createDiagram( aSeriesSeq );
}

sal_Bool SAL_CALL NetChartTypeTemplate::matchesTemplate(
    const Reference< chart2::XDiagram >& xDiagram )
    throw (uno::RuntimeException)
{
    sal_Bool bResult = ChartTypeTemplate::matchesTemplate( xDiagram );

    // check symbol-style
    if( bResult )
    {
        uno::Sequence< Reference< chart2::XDataSeries > > aSeriesSeq(
            helper::DataSeriesTreeHelper::getDataSeriesFromDiagram( xDiagram ));
        chart2::SymbolStyle eStyle = m_bHasSymbols
            ? chart2::SymbolStyle_STANDARD
            : chart2::SymbolStyle_NONE;

        for( sal_Int32 i = 0; i < aSeriesSeq.getLength(); ++i )
        {
            try
            {
                chart2::Symbol aSymbProp;
                Reference< beans::XPropertySet > xProp( aSeriesSeq[i], uno::UNO_QUERY_THROW );
                if( (xProp->getPropertyValue( C2U( "Symbol" )) >>= aSymbProp ) )
                {
                    if( aSymbProp.aStyle != eStyle )
                    {
                        bResult = false;
                        break;
                    }
                }
            }
            catch( uno::Exception & ex )
            {
                ASSERT_EXCEPTION( ex );
            }
        }
    }

    return bResult;
}

// ----------------------------------------

Sequence< OUString > NetChartTypeTemplate::getSupportedServiceNames_Static()
{
    Sequence< OUString > aServices( 2 );
    aServices[ 0 ] = lcl_aServiceName;
    aServices[ 1 ] = C2U( "com.sun.star.chart2.ChartTypeTemplate" );
    return aServices;
}

// implement XServiceInfo methods basing upon getSupportedServiceNames_Static
APPHELPER_XSERVICEINFO_IMPL( NetChartTypeTemplate, lcl_aServiceName );

} //  namespace chart
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.110); FILE MERGED 2005/09/05 18:43:23 rt 1.3.110.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: NetChartTypeTemplate.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 01:22:28 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#include "NetChartTypeTemplate.hxx"
#include "NetChartType.hxx"
#include "macros.hxx"
#include "algohelper.hxx"
#include "DataSeriesTreeHelper.hxx"
#include "PolarCoordinateSystem.hxx"
#include "BoundedCoordinateSystem.hxx"
#include "Scaling.hxx"
#include "Scale.hxx"

#ifndef _COM_SUN_STAR_CHART2_SYMBOLSTYLE_HPP_
#include <com/sun/star/chart2/SymbolStyle.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_SYMBOL_HPP_
#include <com/sun/star/chart2/Symbol.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_LINESTYLE_HPP_
#include <com/sun/star/drawing/LineStyle.hpp>
#endif

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

using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::rtl::OUString;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Any;
using ::osl::MutexGuard;

namespace
{
static const ::rtl::OUString lcl_aServiceName(
    RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.chart2.NetChartTypeTemplate" ));
} // anonymous namespace

namespace chart
{

NetChartTypeTemplate::NetChartTypeTemplate(
    Reference< uno::XComponentContext > const & xContext,
    const ::rtl::OUString & rServiceName,
    chart2::StackMode eStackMode,
    bool bSymbols ) :
        ChartTypeTemplate( xContext, rServiceName ),
        m_eStackMode( eStackMode ),
        m_bHasSymbols( bSymbols )
{}

NetChartTypeTemplate::~NetChartTypeTemplate()
{}

chart2::StackMode NetChartTypeTemplate::getYStackMode() const
{
    return m_eStackMode;
}

Reference< chart2::XBoundedCoordinateSystem > NetChartTypeTemplate::createCoordinateSystem(
    const Reference< chart2::XBoundedCoordinateSystemContainer > & xCoordSysCnt )
{
    Reference< chart2::XCoordinateSystem > xCoordSys(
        new PolarCoordinateSystem( getDimension() ));
    Reference< chart2::XBoundedCoordinateSystem > xResult(
        new BoundedCoordinateSystem( xCoordSys ));

    chart2::ScaleData aScale;
    aScale.Scaling = new LinearScaling( 1.0, 0.0 );

    aScale.Orientation = chart2::AxisOrientation_REVERSE;
    xResult->setScaleByDimension(
        0, Reference< chart2::XScale >( new Scale( GetComponentContext(), aScale ) ));
    aScale.Orientation = chart2::AxisOrientation_MATHEMATICAL;
    xResult->setScaleByDimension(
        1, Reference< chart2::XScale >( new Scale( GetComponentContext(), aScale ) ));

    try
    {
        if( xCoordSys.is())
            xCoordSysCnt->addCoordinateSystem( xResult );
    }
    catch( lang::IllegalArgumentException ex )
    {
        ASSERT_EXCEPTION( ex );
    }

    return xResult;
}

Reference< chart2::XChartType > NetChartTypeTemplate::getDefaultChartType()
    throw (uno::RuntimeException)
{
    return new NetChartType();
}

// ____ XChartTypeTemplate ____
Reference< chart2::XDiagram > SAL_CALL
    NetChartTypeTemplate::createDiagram(
        const uno::Sequence< Reference< chart2::XDataSeries > >& aSeriesSeq )
    throw (uno::RuntimeException)
{
    // set symbol type at data series
    chart2::SymbolStyle eStyle = m_bHasSymbols
        ? chart2::SymbolStyle_STANDARD
        : chart2::SymbolStyle_NONE;

    for( sal_Int32 i = 0; i < aSeriesSeq.getLength(); ++i )
    {
        try
        {
            chart2::Symbol aSymbProp;
            Reference< beans::XPropertySet > xProp( aSeriesSeq[i], uno::UNO_QUERY_THROW );
            if( (xProp->getPropertyValue( C2U( "Symbol" )) >>= aSymbProp ) )
            {
                aSymbProp.aStyle = eStyle;
                if( m_bHasSymbols )
                    aSymbProp.nStandardSymbol = i;
                xProp->setPropertyValue( C2U( "Symbol" ), uno::makeAny( aSymbProp ));
            }
        }
        catch( uno::Exception & ex )
        {
            ASSERT_EXCEPTION( ex );
        }
    }

    // todo: set symbol type at data points

    return ChartTypeTemplate::createDiagram( aSeriesSeq );
}

sal_Bool SAL_CALL NetChartTypeTemplate::matchesTemplate(
    const Reference< chart2::XDiagram >& xDiagram )
    throw (uno::RuntimeException)
{
    sal_Bool bResult = ChartTypeTemplate::matchesTemplate( xDiagram );

    // check symbol-style
    if( bResult )
    {
        uno::Sequence< Reference< chart2::XDataSeries > > aSeriesSeq(
            helper::DataSeriesTreeHelper::getDataSeriesFromDiagram( xDiagram ));
        chart2::SymbolStyle eStyle = m_bHasSymbols
            ? chart2::SymbolStyle_STANDARD
            : chart2::SymbolStyle_NONE;

        for( sal_Int32 i = 0; i < aSeriesSeq.getLength(); ++i )
        {
            try
            {
                chart2::Symbol aSymbProp;
                Reference< beans::XPropertySet > xProp( aSeriesSeq[i], uno::UNO_QUERY_THROW );
                if( (xProp->getPropertyValue( C2U( "Symbol" )) >>= aSymbProp ) )
                {
                    if( aSymbProp.aStyle != eStyle )
                    {
                        bResult = false;
                        break;
                    }
                }
            }
            catch( uno::Exception & ex )
            {
                ASSERT_EXCEPTION( ex );
            }
        }
    }

    return bResult;
}

// ----------------------------------------

Sequence< OUString > NetChartTypeTemplate::getSupportedServiceNames_Static()
{
    Sequence< OUString > aServices( 2 );
    aServices[ 0 ] = lcl_aServiceName;
    aServices[ 1 ] = C2U( "com.sun.star.chart2.ChartTypeTemplate" );
    return aServices;
}

// implement XServiceInfo methods basing upon getSupportedServiceNames_Static
APPHELPER_XSERVICEINFO_IMPL( NetChartTypeTemplate, lcl_aServiceName );

} //  namespace chart
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2011-2014 Intel Corporation. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "decodehelp.h"

#include "common/utils.h"

#include <ctype.h>
#include <limits.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <Yami.h>
#include <getopt.h>

using namespace YamiMediaCodec;

static void printHelp(const char* app)
{
    printf("%s <options>\n", app);
    printf("   -i media file to decode\n");
    printf("   -w wait before quit: 0:no-wait, 1:auto(jpeg wait), 2:wait\n");
    printf("   -f dumped fourcc [*]\n");
    printf("   -o dumped output dir\n");
    printf("   -n specifiy how many frames to be decoded\n");
    printf("   -m <render mode>\n");
    printf("     -2: print MD5 by per frame and the whole decoded file MD5\n");
    printf("     -1: skip video rendering [*]\n");
    printf("      0: dump video frame to file\n");
    printf("      1: render to X window [*]\n");
    printf("      2: texture: render to Pixmap + texture from Pixmap [*]\n");
    printf("      3: texture: export video frame as drm name (RGBX) + texture from drm name\n");
    printf("      4: texture: export video frame as dma_buf(RGBX) + texutre from dma_buf\n");
    printf("      5: texture: export video frame as dma_buf(NV12) + texture from dma_buf. not implement yet\n");
    printf(" [*] v4l2decode doesn't support the option\n");
    printf("  --capi: use the codec capi to encode or decode, default(false)\n");
}

bool processCmdLine(int argc, char** argv, DecodeParameter* parameters)
{
    int32_t option_index;
    bool isSetFourcc = false;
    std::string outputFile;
    parameters->renderFrames = UINT_MAX;
    parameters->waitBeforeQuit = 1;
    parameters->renderMode = 1;
    parameters->inputFile = NULL;
    parameters->useCAPI = false;

    const struct option long_opts[] = {
        {"help", no_argument, NULL, 'h'},
        {"capi", no_argument, NULL, 0},
        {NULL, no_argument, NULL, 0}};

    char opt;
    while ((opt = getopt_long_only(argc, argv, "h:m:n:i:f:o:w:?", long_opts,&option_index)) != -1){
        switch (opt) {
        case 'h':
        case '?':
            printHelp(argv[0]);
            return false;
        case 'i':
            parameters->inputFile = optarg;
            break;
        case 'w':
            parameters->waitBeforeQuit = atoi(optarg);
            break;
        case 'm':
            parameters->renderMode = atoi(optarg);
            break;
        case 'n':
            parameters->renderFrames = atoi(optarg);
            break;
        case 'f':
            if (strlen(optarg) == 4) {
                parameters->renderFourcc = YAMI_FOURCC(toupper(optarg[0]), toupper(optarg[1]), toupper(optarg[2]), toupper(optarg[3]));
                isSetFourcc = true;
            }
            else {
                fprintf(stderr, "invalid fourcc: %s\n", optarg);
                return false;
            }
            break;
        case 'o':
            outputFile = optarg;
            break;
        case 0:
            switch (option_index) {
            case 1:
                parameters->useCAPI = true;
                break;
            default:
                printHelp(argv[0]);
                break;
            }
            break;
        default:
            printHelp(argv[0]);
            break;
        }
    }
    if (optind < argc) {
        int indexOpt = optind;
        printf("unrecognized option: ");
        while (indexOpt < argc)
            printf("%s ", argv[indexOpt++]);
        printf("\n");
        printHelp(argv[0]);
        return false;
    }

    if (!parameters->inputFile) {
        fprintf(stderr, "no input media file specified.\n");
        return false;
    }
    if (outputFile.empty())
        outputFile = "./";
    parameters->outputFile = outputFile;
    if (!isSetFourcc)
        parameters->renderFourcc = guessFourcc(parameters->outputFile.c_str());
    int width, height;
    if (guessResolution(parameters->inputFile, width, height)) {
        parameters->width = width;
        parameters->height = height;
    }
    return true;
}

bool possibleWait(const char* mimeType, const DecodeParameter* parameters)
{
    // waitBeforeQuit 0:nowait, 1:auto(jpeg wait), 2:wait
    switch (parameters->waitBeforeQuit) {
    case 0:
        break;
    case 1:
        if (parameters->renderMode == 0 || strcmp(mimeType, YAMI_MIME_JPEG))
            break;
    case 2:
        fprintf(stdout, "press any key to continue ...");
        getchar();
        break;
    default:
        break;
    }

    return true;
}
<commit_msg>Fix spelling of 'specify'<commit_after>/*
 * Copyright (C) 2011-2014 Intel Corporation. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "decodehelp.h"

#include "common/utils.h"

#include <ctype.h>
#include <limits.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <Yami.h>
#include <getopt.h>

using namespace YamiMediaCodec;

static void printHelp(const char* app)
{
    printf("%s <options>\n", app);
    printf("   -i media file to decode\n");
    printf("   -w wait before quit: 0:no-wait, 1:auto(jpeg wait), 2:wait\n");
    printf("   -f dumped fourcc [*]\n");
    printf("   -o dumped output dir\n");
    printf("   -n specify how many frames to be decoded\n");
    printf("   -m <render mode>\n");
    printf("     -2: print MD5 by per frame and the whole decoded file MD5\n");
    printf("     -1: skip video rendering [*]\n");
    printf("      0: dump video frame to file\n");
    printf("      1: render to X window [*]\n");
    printf("      2: texture: render to Pixmap + texture from Pixmap [*]\n");
    printf("      3: texture: export video frame as drm name (RGBX) + texture from drm name\n");
    printf("      4: texture: export video frame as dma_buf(RGBX) + texutre from dma_buf\n");
    printf("      5: texture: export video frame as dma_buf(NV12) + texture from dma_buf. not implement yet\n");
    printf(" [*] v4l2decode doesn't support the option\n");
    printf("  --capi: use the codec capi to encode or decode, default(false)\n");
}

bool processCmdLine(int argc, char** argv, DecodeParameter* parameters)
{
    int32_t option_index;
    bool isSetFourcc = false;
    std::string outputFile;
    parameters->renderFrames = UINT_MAX;
    parameters->waitBeforeQuit = 1;
    parameters->renderMode = 1;
    parameters->inputFile = NULL;
    parameters->useCAPI = false;

    const struct option long_opts[] = {
        {"help", no_argument, NULL, 'h'},
        {"capi", no_argument, NULL, 0},
        {NULL, no_argument, NULL, 0}};

    char opt;
    while ((opt = getopt_long_only(argc, argv, "h:m:n:i:f:o:w:?", long_opts,&option_index)) != -1){
        switch (opt) {
        case 'h':
        case '?':
            printHelp(argv[0]);
            return false;
        case 'i':
            parameters->inputFile = optarg;
            break;
        case 'w':
            parameters->waitBeforeQuit = atoi(optarg);
            break;
        case 'm':
            parameters->renderMode = atoi(optarg);
            break;
        case 'n':
            parameters->renderFrames = atoi(optarg);
            break;
        case 'f':
            if (strlen(optarg) == 4) {
                parameters->renderFourcc = YAMI_FOURCC(toupper(optarg[0]), toupper(optarg[1]), toupper(optarg[2]), toupper(optarg[3]));
                isSetFourcc = true;
            }
            else {
                fprintf(stderr, "invalid fourcc: %s\n", optarg);
                return false;
            }
            break;
        case 'o':
            outputFile = optarg;
            break;
        case 0:
            switch (option_index) {
            case 1:
                parameters->useCAPI = true;
                break;
            default:
                printHelp(argv[0]);
                break;
            }
            break;
        default:
            printHelp(argv[0]);
            break;
        }
    }
    if (optind < argc) {
        int indexOpt = optind;
        printf("unrecognized option: ");
        while (indexOpt < argc)
            printf("%s ", argv[indexOpt++]);
        printf("\n");
        printHelp(argv[0]);
        return false;
    }

    if (!parameters->inputFile) {
        fprintf(stderr, "no input media file specified.\n");
        return false;
    }
    if (outputFile.empty())
        outputFile = "./";
    parameters->outputFile = outputFile;
    if (!isSetFourcc)
        parameters->renderFourcc = guessFourcc(parameters->outputFile.c_str());
    int width, height;
    if (guessResolution(parameters->inputFile, width, height)) {
        parameters->width = width;
        parameters->height = height;
    }
    return true;
}

bool possibleWait(const char* mimeType, const DecodeParameter* parameters)
{
    // waitBeforeQuit 0:nowait, 1:auto(jpeg wait), 2:wait
    switch (parameters->waitBeforeQuit) {
    case 0:
        break;
    case 1:
        if (parameters->renderMode == 0 || strcmp(mimeType, YAMI_MIME_JPEG))
            break;
    case 2:
        fprintf(stdout, "press any key to continue ...");
        getchar();
        break;
    default:
        break;
    }

    return true;
}
<|endoftext|>


<commit_before>#include "error.hh"

#include <optional>
#include <iostream>

using std::optional;
using std::nullopt;
using std::cout;
using std::endl;

int main()
{
  using namespace nix;

  // In each program where errors occur, this has to be set.
  ErrorInfo::programName = optional("error-test");

  // There are currently four error types -
  // 			ProgramError, ProgramWarning, NixLangError, NixLangWarning.
  // Each error type is created with a specific sequence of builder functions.
  // Unlike with a constructor, each parameter is clearly named.
  // If the sequence of function calls isn't followed, then there's a type error.
  // This should make for a consistent look in the code when errors are created.

  // ProgramError takes name, description, and an optional hint.
  printErrorInfo(
    ProgramError()
      .name("name")
      .description("error description")
      .nohint()
      );

  // ProgramWarning takes name, description, and an optional hint.
  // The hint is in the form of a hintfmt class, which wraps boost::format(), and
  // makes all the substituted text yellow.
  printErrorInfo(
    ProgramWarning()
      .name("warning name")
      .description("warning description")
      .hint(hintfmt("there was a %1%") % "warning") // 'warning' will be yellow.
      );

  // NixLangWarning adds nix file, line number, column range, and the lines of code
  // where a warning occurred.
  printErrorInfo(
    NixLangWarning()
      .name("warning name")
      .description("warning description")
      .nixFile("myfile.nix")
      .lineNumber(40)
      .columnRange(13,7)
      .linesOfCode(nullopt
                  ,"this is the problem line of code"
                  ,nullopt)
      .hint(hintfmt("this hint has %1% templated %2%!!") % "yellow" % "values")
      );

  // NixLangError is just the same as NixLangWarning, except for the Error flag.
  printErrorInfo(
    NixLangError()
      .name("error name")
      .description("error description")
      .nixFile("myfile.nix")
      .lineNumber(40)
      .columnRange(13,7)
      .linesOfCode(optional("previous line of code")
                  ,"this is the problem line of code"
                  ,optional("next line of code"))
      .hint(hintfmt("this hint has %1% templated %2%!!") % "yellow" % "values")
      );

  return 0;
}
<commit_msg>examples of invalid errors<commit_after>#include "error.hh"

#include <optional>
#include <iostream>

using std::optional;
using std::nullopt;
using std::cout;
using std::endl;

int main()
{
  using namespace nix;

  // In each program where errors occur, this has to be set.
  ErrorInfo::programName = optional("error-test");

  // There are currently four error types:
  //
  // 			ProgramError, ProgramWarning, NixLangError, NixLangWarning.
  //
  // Each error type is created with a specific sequence of builder functions.
  // Unlike with a constructor, each parameter is clearly named.
  // If the sequence of function calls isn't followed, then there's a type error.
  // This should make for a consistent look in the code when errors are created.

  // ProgramError takes name, description, and an optional hint.
  printErrorInfo(
    ProgramError()
      .name("name")
      .description("error description")
      .nohint()
      );

  // ProgramWarning takes name, description, and an optional hint.
  // The hint is in the form of a hintfmt class, which wraps boost::format(), and
  // makes all the substituted text yellow.
  printErrorInfo(
    ProgramWarning()
      .name("warning name")
      .description("warning description")
      .hint(hintfmt("there was a %1%") % "warning") // 'warning' will be yellow.
      );

  /*
    // some invalid errors:

    // type error: no hint function.
    ProgramError()
      .name("name")
      .description("error description");

    // type error:  description before name.
    ProgramError()
      .description("error description")
      .name("name")
      .nohint();

    // type error: hint function with regular boost format, not special hintfmt.
    ProgramError()
      .description("error description")
      .name("name")
      .hint(format("there was a %1%") % "warning");
  */

  // NixLangWarning adds nix file, line number, column range, and the lines of code
  // where a warning occurred.
  printErrorInfo(
    NixLangWarning()
      .name("warning name")
      .description("warning description")
      .nixFile("myfile.nix")
      .lineNumber(40)
      .columnRange(13,7)
      .linesOfCode(nullopt
                  ,"this is the problem line of code"
                  ,nullopt)
      .hint(hintfmt("this hint has %1% templated %2%!!") % "yellow" % "values")
      );

  // NixLangError is just the same as NixLangWarning, except for the Error flag.
  printErrorInfo(
    NixLangError()
      .name("error name")
      .description("error description")
      .nixFile("myfile.nix")
      .lineNumber(40)
      .columnRange(13,7)
      .linesOfCode(optional("previous line of code")
                  ,"this is the problem line of code"
                  ,optional("next line of code"))
      .hint(hintfmt("this hint has %1% templated %2%!!") % "yellow" % "values")
      );

  return 0;
}
<|endoftext|>


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

#include <vector>

#include "base/file_path.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/autofill/autofill_manager.h"
#include "chrome/browser/autofill/data_driven_test.h"
#include "chrome/browser/autofill/form_structure.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "googleurl/src/gurl.h"

namespace {

const FilePath::CharType kTestName[] = FILE_PATH_LITERAL("heuristics");
const FilePath::CharType kFileNamePattern[] = FILE_PATH_LITERAL("*.html");

// Convert the |html| snippet to a data URI.
GURL HTMLToDataURI(const std::string& html) {
  return GURL(std::string("data:text/html;charset=utf-8,") + html);
}

}  // namespace

// A data-driven test for verifying AutoFill heuristics. Each input is an HTML
// file that contains one or more forms. The corresponding output file lists the
// heuristically detected type for eachfield.
class FormStructureBrowserTest : public InProcessBrowserTest,
                                 public DataDrivenTest {
 protected:
  FormStructureBrowserTest();
  virtual ~FormStructureBrowserTest();

  // DataDrivenTest:
  virtual void GenerateResults(const std::string& input,
                               std::string* output);

  // Serializes the given |forms| into a string.
  std::string FormStructuresToString(const std::vector<FormStructure*>& forms);

 private:
  DISALLOW_COPY_AND_ASSIGN(FormStructureBrowserTest);
};

FormStructureBrowserTest::FormStructureBrowserTest() {
}

FormStructureBrowserTest::~FormStructureBrowserTest() {
}

void FormStructureBrowserTest::GenerateResults(const std::string& input,
                                               std::string* output) {
  ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(),
                                                       HTMLToDataURI(input)));
  ASSERT_NO_FATAL_FAILURE(ui_test_utils::ClickOnView(browser(),
                                                     VIEW_ID_TAB_CONTAINER));
  ASSERT_TRUE(ui_test_utils::IsViewFocused(browser(),
                                           VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));

  AutoFillManager* autofill_manager =
      browser()->GetSelectedTabContents()->autofill_manager();
  ASSERT_NE(static_cast<AutoFillManager*>(NULL), autofill_manager);
  std::vector<FormStructure*> forms = autofill_manager->form_structures_.get();
  *output = FormStructureBrowserTest::FormStructuresToString(forms);
}

std::string FormStructureBrowserTest::FormStructuresToString(
    const std::vector<FormStructure*>& forms) {
  std::string forms_string;
  for (std::vector<FormStructure*>::const_iterator iter = forms.begin();
       iter != forms.end();
       ++iter) {

    for (std::vector<AutoFillField*>::const_iterator field_iter =
            (*iter)->begin();
         field_iter != (*iter)->end();
         ++field_iter) {
      // The field list is NULL-terminated.  Exit loop when at the end.
      if (!*field_iter)
        break;
      forms_string += AutoFillType::FieldTypeToString((*field_iter)->type());
      forms_string += "\n";
    }
  }
  return forms_string;
}

IN_PROC_BROWSER_TEST_F(FormStructureBrowserTest, DataDrivenHeuristics) {
  ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));
  RunDataDrivenTest(GetInputDirectory(kTestName),
                    GetOutputDirectory(kTestName),
                    kFileNamePattern);
}
<commit_msg>Disable FormStructureBrowserTest.DataDrivenHeuristics on Windows<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <vector>

#include "base/file_path.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/autofill/autofill_manager.h"
#include "chrome/browser/autofill/data_driven_test.h"
#include "chrome/browser/autofill/form_structure.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "googleurl/src/gurl.h"

namespace {

const FilePath::CharType kTestName[] = FILE_PATH_LITERAL("heuristics");
const FilePath::CharType kFileNamePattern[] = FILE_PATH_LITERAL("*.html");

// Convert the |html| snippet to a data URI.
GURL HTMLToDataURI(const std::string& html) {
  return GURL(std::string("data:text/html;charset=utf-8,") + html);
}

}  // namespace

// A data-driven test for verifying AutoFill heuristics. Each input is an HTML
// file that contains one or more forms. The corresponding output file lists the
// heuristically detected type for eachfield.
class FormStructureBrowserTest : public InProcessBrowserTest,
                                 public DataDrivenTest {
 protected:
  FormStructureBrowserTest();
  virtual ~FormStructureBrowserTest();

  // DataDrivenTest:
  virtual void GenerateResults(const std::string& input,
                               std::string* output);

  // Serializes the given |forms| into a string.
  std::string FormStructuresToString(const std::vector<FormStructure*>& forms);

 private:
  DISALLOW_COPY_AND_ASSIGN(FormStructureBrowserTest);
};

FormStructureBrowserTest::FormStructureBrowserTest() {
}

FormStructureBrowserTest::~FormStructureBrowserTest() {
}

void FormStructureBrowserTest::GenerateResults(const std::string& input,
                                               std::string* output) {
  ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(),
                                                       HTMLToDataURI(input)));
  ASSERT_NO_FATAL_FAILURE(ui_test_utils::ClickOnView(browser(),
                                                     VIEW_ID_TAB_CONTAINER));
  ASSERT_TRUE(ui_test_utils::IsViewFocused(browser(),
                                           VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));

  AutoFillManager* autofill_manager =
      browser()->GetSelectedTabContents()->autofill_manager();
  ASSERT_NE(static_cast<AutoFillManager*>(NULL), autofill_manager);
  std::vector<FormStructure*> forms = autofill_manager->form_structures_.get();
  *output = FormStructureBrowserTest::FormStructuresToString(forms);
}

std::string FormStructureBrowserTest::FormStructuresToString(
    const std::vector<FormStructure*>& forms) {
  std::string forms_string;
  for (std::vector<FormStructure*>::const_iterator iter = forms.begin();
       iter != forms.end();
       ++iter) {

    for (std::vector<AutoFillField*>::const_iterator field_iter =
            (*iter)->begin();
         field_iter != (*iter)->end();
         ++field_iter) {
      // The field list is NULL-terminated.  Exit loop when at the end.
      if (!*field_iter)
        break;
      forms_string += AutoFillType::FieldTypeToString((*field_iter)->type());
      forms_string += "\n";
    }
  }
  return forms_string;
}

#if defined(OS_WIN)
// This test fails on the 'Win' full builder: http://crbug.com/72401
#define MAYBE_DataDrivenHeuristics DISABLED_DataDrivenHeuristics
#else
#define MAYBE_DataDrivenHeuristics DataDrivenHeuristics
#endif
IN_PROC_BROWSER_TEST_F(FormStructureBrowserTest, MAYBE_DataDrivenHeuristics) {
  ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));
  RunDataDrivenTest(GetInputDirectory(kTestName),
                    GetOutputDirectory(kTestName),
                    kFileNamePattern);
}
<|endoftext|>


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

#include "chrome/browser/chromeos/drive/drive_system_service.h"

#include "base/bind.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/drive/drive_api_service.h"
#include "chrome/browser/chromeos/drive/drive_download_observer.h"
#include "chrome/browser/chromeos/drive/drive_file_system.h"
#include "chrome/browser/chromeos/drive/drive_file_system_proxy.h"
#include "chrome/browser/chromeos/drive/drive_file_system_util.h"
#include "chrome/browser/chromeos/drive/drive_prefetcher.h"
#include "chrome/browser/chromeos/drive/drive_sync_client.h"
#include "chrome/browser/chromeos/drive/drive_webapps_registry.h"
#include "chrome/browser/chromeos/drive/event_logger.h"
#include "chrome/browser/chromeos/drive/file_write_helper.h"
#include "chrome/browser/chromeos/drive/stale_cache_files_remover.h"
#include "chrome/browser/download/download_service.h"
#include "chrome/browser/download/download_service_factory.h"
#include "chrome/browser/download/download_util.h"
#include "chrome/browser/google_apis/drive_api_util.h"
#include "chrome/browser/google_apis/drive_uploader.h"
#include "chrome/browser/google_apis/gdata_wapi_service.h"
#include "chrome/browser/google_apis/gdata_wapi_url_generator.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_dependency_manager.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/sync/profile_sync_service_factory.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/common/pref_names.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/storage_partition.h"
#include "google/cacheinvalidation/types.pb.h"
#include "webkit/fileapi/file_system_context.h"
#include "webkit/fileapi/file_system_mount_point_provider.h"
#include "webkit/user_agent/user_agent_util.h"

using content::BrowserContext;
using content::BrowserThread;

namespace drive {
namespace {

static const size_t kEventLogHistorySize = 100;

// Used in test to setup system service.
google_apis::DriveServiceInterface* g_test_drive_service = NULL;
const std::string* g_test_cache_root = NULL;

// The sync invalidation object ID for Google Drive.
const char kDriveInvalidationObjectId[] = "CHANGELOG";

// Returns true if Drive is enabled for the given Profile.
bool IsDriveEnabledForProfile(Profile* profile) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  if (!google_apis::AuthService::CanAuthenticate(profile))
    return false;

  // Disable Drive if preference is set.  This can happen with commandline flag
  // --disable-gdata or enterprise policy, or probably with user settings too
  // in the future.
  if (profile->GetPrefs()->GetBoolean(prefs::kDisableDrive))
    return false;

  return true;
}

// Returns a user agent string used for communicating with the Drive backend,
// both WAPI and Drive API.  The user agent looks like:
//
// chromedrive-<VERSION> chrome-cc/none (<OS_CPU_INFO>)
// chromedrive-24.0.1274.0 chrome-cc/none (CrOS x86_64 0.4.0)
//
// TODO(satorux): Move this function to somewhere else: crbug.com/151605
std::string GetDriveUserAgent() {
  const char kDriveClientName[] = "chromedrive";

  chrome::VersionInfo version_info;
  const std::string version = (version_info.is_valid() ?
                               version_info.Version() :
                               std::string("unknown"));

  // This part is <client_name>/<version>.
  const char kLibraryInfo[] = "chrome-cc/none";

  const std::string os_cpu_info = webkit_glue::BuildOSCpuInfo();

  return base::StringPrintf("%s-%s %s (%s)",
                            kDriveClientName,
                            version.c_str(),
                            kLibraryInfo,
                            os_cpu_info.c_str());
}

}  // namespace

DriveSystemService::DriveSystemService(Profile* profile)
    : profile_(profile),
      drive_disabled_(false),
      push_notification_registered_(false),
      cache_(NULL),
      ALLOW_THIS_IN_INITIALIZER_LIST(weak_ptr_factory_(this)) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  base::SequencedWorkerPool* blocking_pool = BrowserThread::GetBlockingPool();
  blocking_task_runner_ = blocking_pool->GetSequencedTaskRunner(
      blocking_pool->GetSequenceToken());
}

DriveSystemService::~DriveSystemService() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  cache_->Destroy();
}

void DriveSystemService::Initialize(
    google_apis::DriveServiceInterface* drive_service,
    const FilePath& cache_root) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  event_logger_.reset(new EventLogger(kEventLogHistorySize));
  drive_service_.reset(drive_service);
  cache_ = DriveCache::CreateDriveCache(cache_root, blocking_task_runner_);
  uploader_.reset(new google_apis::DriveUploader(drive_service_.get()));
  webapps_registry_.reset(new DriveWebAppsRegistry);
  file_system_.reset(new DriveFileSystem(profile_,
                                         cache(),
                                         drive_service_.get(),
                                         uploader(),
                                         webapps_registry(),
                                         blocking_task_runner_));
  file_write_helper_.reset(new FileWriteHelper(file_system()));
  download_observer_.reset(new DriveDownloadObserver(file_write_helper(),
                                                     file_system()));
  sync_client_.reset(new DriveSyncClient(profile_, file_system(), cache()));
  prefetcher_.reset(new DrivePrefetcher(file_system(),
                                        event_logger(),
                                        DrivePrefetcherOptions()));
  sync_client_->AddObserver(prefetcher_.get());
  stale_cache_files_remover_.reset(new StaleCacheFilesRemover(file_system(),
                                                              cache()));

  sync_client_->Initialize();
  file_system_->Initialize();
  cache_->RequestInitialize(base::Bind(&DriveSystemService::OnCacheInitialized,
                                       weak_ptr_factory_.GetWeakPtr()));
}

void DriveSystemService::Shutdown() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  ProfileSyncService* profile_sync_service =
      profile_ ? ProfileSyncServiceFactory::GetForProfile(profile_) : NULL;
  if (profile_sync_service && push_notification_registered_) {
    // TODO(kochi): Once DriveSystemService gets started / stopped at runtime,
    // this ID needs to be unregistered *before* the handler is unregistered
    // as ID persists across browser restarts.
    if (!IsDriveEnabledForProfile(profile_)) {
      profile_sync_service->UpdateRegisteredInvalidationIds(
          this, syncer::ObjectIdSet());
    }
    profile_sync_service->UnregisterInvalidationHandler(this);
    push_notification_registered_ = false;
  }

  RemoveDriveMountPoint();

  // Shut down the member objects in the reverse order of creation.
  stale_cache_files_remover_.reset();
  sync_client_->RemoveObserver(prefetcher_.get());
  prefetcher_.reset();
  sync_client_.reset();
  download_observer_.reset();
  file_write_helper_.reset();
  file_system_.reset();
  webapps_registry_.reset();
  uploader_.reset();
  drive_service_.reset();
}

bool DriveSystemService::IsDriveEnabled() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  if (!IsDriveEnabledForProfile(profile_))
    return false;

  // Drive may be disabled for cache initialization failure, etc.
  if (drive_disabled_)
    return false;

  return true;
}

void DriveSystemService::OnInvalidatorStateChange(
    syncer::InvalidatorState state) {
  file_system_->SetPushNotificationEnabled(
      state == syncer::INVALIDATIONS_ENABLED);
}

void DriveSystemService::OnIncomingInvalidation(
    const syncer::ObjectIdInvalidationMap& invalidation_map,
    syncer::IncomingInvalidationSource source) {
  DCHECK_EQ(1U, invalidation_map.size());
  const invalidation::ObjectId object_id(
      ipc::invalidation::ObjectSource::COSMO_CHANGELOG,
      kDriveInvalidationObjectId);
  DCHECK_EQ(1U, invalidation_map.count(object_id));

  file_system_->CheckForUpdates();
}

void DriveSystemService::ClearCacheAndRemountFileSystem(
    const base::Callback<void(bool)>& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  RemoveDriveMountPoint();
  drive_service()->CancelAll();
  cache_->ClearAll(base::Bind(&DriveSystemService::AddBackDriveMountPoint,
                              weak_ptr_factory_.GetWeakPtr(),
                              callback));
}

void DriveSystemService::AddBackDriveMountPoint(
    const base::Callback<void(bool)>& callback,
    bool success) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  file_system_->Initialize();
  AddDriveMountPoint();

  if (!callback.is_null())
    callback.Run(success);
}

void DriveSystemService::ReloadAndRemountFileSystem() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  RemoveDriveMountPoint();
  drive_service()->CancelAll();
  file_system_->Reload();

  // Reload() is asynchronous. But we can add back the mount point right away
  // because every operation waits until loading is complete.
  AddDriveMountPoint();
}

void DriveSystemService::AddDriveMountPoint() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  const FilePath mount_point = util::GetDriveMountPointPath();
  fileapi::ExternalFileSystemMountPointProvider* provider =
      BrowserContext::GetDefaultStoragePartition(profile_)->
          GetFileSystemContext()->external_provider();
  if (provider && !provider->HasMountPoint(mount_point)) {
    event_logger_->Log("AddDriveMountPoint");
    provider->AddRemoteMountPoint(
        mount_point,
        new DriveFileSystemProxy(file_system_.get()));
  }

  file_system_->NotifyFileSystemMounted();
}

void DriveSystemService::RemoveDriveMountPoint() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  file_system_->NotifyFileSystemToBeUnmounted();
  file_system_->StopPolling();

  const FilePath mount_point = util::GetDriveMountPointPath();
  fileapi::ExternalFileSystemMountPointProvider* provider =
      BrowserContext::GetDefaultStoragePartition(profile_)->
          GetFileSystemContext()->external_provider();
  if (provider && provider->HasMountPoint(mount_point)) {
    provider->RemoveMountPoint(mount_point);
    event_logger_->Log("RemoveDriveMountPoint");
  }
}

void DriveSystemService::OnCacheInitialized(bool success) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  if (!success) {
    LOG(WARNING) << "Failed to initialize the cache. Disabling Drive";
    DisableDrive();
    return;
  }

  content::DownloadManager* download_manager =
    g_browser_process->download_status_updater() ?
        BrowserContext::GetDownloadManager(profile_) : NULL;
  download_observer_->Initialize(
      download_manager,
      cache_->GetCacheDirectoryPath(
          DriveCache::CACHE_TYPE_TMP_DOWNLOADS));

  // Register for Google Drive invalidation notifications.
  ProfileSyncService* profile_sync_service =
      profile_ ? ProfileSyncServiceFactory::GetForProfile(profile_) : NULL;
  if (profile_sync_service) {
    DCHECK(!push_notification_registered_);
    profile_sync_service->RegisterInvalidationHandler(this);
    syncer::ObjectIdSet ids;
    ids.insert(invalidation::ObjectId(
        ipc::invalidation::ObjectSource::COSMO_CHANGELOG,
        kDriveInvalidationObjectId));
    profile_sync_service->UpdateRegisteredInvalidationIds(this, ids);
    push_notification_registered_ = true;
    file_system_->SetPushNotificationEnabled(
        profile_sync_service->GetInvalidatorState() ==
        syncer::INVALIDATIONS_ENABLED);
  }

  AddDriveMountPoint();

  // Start prefetching of Drive metadata.
  file_system_->StartInitialFeedFetch();
}

void DriveSystemService::DisableDrive() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  drive_disabled_ = true;
  // Change the download directory to the default value if the download
  // destination is set to under Drive mount point.
  PrefService* pref_service = profile_->GetPrefs();
  if (util::IsUnderDriveMountPoint(
          pref_service->GetFilePath(prefs::kDownloadDefaultDirectory))) {
    pref_service->SetFilePath(prefs::kDownloadDefaultDirectory,
                              download_util::GetDefaultDownloadDirectory());
  }
}

//===================== DriveSystemServiceFactory =============================

// static
DriveSystemService* DriveSystemServiceFactory::GetForProfile(
    Profile* profile) {
  DriveSystemService* service = static_cast<DriveSystemService*>(
      GetInstance()->GetServiceForProfile(profile, true));
  if (service && !service->IsDriveEnabled())
    return NULL;

  return service;
}

// static
DriveSystemService* DriveSystemServiceFactory::FindForProfile(
    Profile* profile) {
  DriveSystemService* service = static_cast<DriveSystemService*>(
      GetInstance()->GetServiceForProfile(profile, false));
  if (service && !service->IsDriveEnabled())
    return NULL;

  return service;
}

// static
DriveSystemServiceFactory* DriveSystemServiceFactory::GetInstance() {
  return Singleton<DriveSystemServiceFactory>::get();
}

DriveSystemServiceFactory::DriveSystemServiceFactory()
    : ProfileKeyedServiceFactory("DriveSystemService",
                                 ProfileDependencyManager::GetInstance()) {
  DependsOn(ProfileSyncServiceFactory::GetInstance());
  DependsOn(DownloadServiceFactory::GetInstance());
}

DriveSystemServiceFactory::~DriveSystemServiceFactory() {
}

// static
void DriveSystemServiceFactory::set_drive_service_for_test(
    google_apis::DriveServiceInterface* drive_service) {
  if (g_test_drive_service)
    delete g_test_drive_service;
  g_test_drive_service = drive_service;
}

// static
void DriveSystemServiceFactory::set_cache_root_for_test(
    const std::string& cache_root) {
  if (g_test_cache_root)
    delete g_test_cache_root;
  g_test_cache_root = !cache_root.empty() ? new std::string(cache_root) : NULL;
}

ProfileKeyedService* DriveSystemServiceFactory::BuildServiceInstanceFor(
    Profile* profile) const {
  DriveSystemService* service = new DriveSystemService(profile);

  google_apis::DriveServiceInterface* drive_service = g_test_drive_service;
  g_test_drive_service = NULL;
  if (!drive_service) {
    if (google_apis::util::IsDriveV2ApiEnabled()) {
      drive_service = new DriveAPIService(
          g_browser_process->system_request_context(),
          GetDriveUserAgent());
    } else {
      drive_service = new google_apis::GDataWapiService(
          g_browser_process->system_request_context(),
          GURL(google_apis::GDataWapiUrlGenerator::kBaseUrlForProduction),
          GetDriveUserAgent());
    }
  }

  FilePath cache_root =
      g_test_cache_root ? FilePath(*g_test_cache_root) :
                          DriveCache::GetCacheRootPath(profile);
  delete g_test_cache_root;
  g_test_cache_root = NULL;

  service->Initialize(drive_service, cache_root);
  return service;
}

}  // namespace drive
<commit_msg>drive: Remove the one last instance of if (!callback.is_null())<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/drive/drive_system_service.h"

#include "base/bind.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/drive/drive_api_service.h"
#include "chrome/browser/chromeos/drive/drive_download_observer.h"
#include "chrome/browser/chromeos/drive/drive_file_system.h"
#include "chrome/browser/chromeos/drive/drive_file_system_proxy.h"
#include "chrome/browser/chromeos/drive/drive_file_system_util.h"
#include "chrome/browser/chromeos/drive/drive_prefetcher.h"
#include "chrome/browser/chromeos/drive/drive_sync_client.h"
#include "chrome/browser/chromeos/drive/drive_webapps_registry.h"
#include "chrome/browser/chromeos/drive/event_logger.h"
#include "chrome/browser/chromeos/drive/file_write_helper.h"
#include "chrome/browser/chromeos/drive/stale_cache_files_remover.h"
#include "chrome/browser/download/download_service.h"
#include "chrome/browser/download/download_service_factory.h"
#include "chrome/browser/download/download_util.h"
#include "chrome/browser/google_apis/drive_api_util.h"
#include "chrome/browser/google_apis/drive_uploader.h"
#include "chrome/browser/google_apis/gdata_wapi_service.h"
#include "chrome/browser/google_apis/gdata_wapi_url_generator.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_dependency_manager.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/sync/profile_sync_service_factory.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/common/pref_names.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/storage_partition.h"
#include "google/cacheinvalidation/types.pb.h"
#include "webkit/fileapi/file_system_context.h"
#include "webkit/fileapi/file_system_mount_point_provider.h"
#include "webkit/user_agent/user_agent_util.h"

using content::BrowserContext;
using content::BrowserThread;

namespace drive {
namespace {

static const size_t kEventLogHistorySize = 100;

// Used in test to setup system service.
google_apis::DriveServiceInterface* g_test_drive_service = NULL;
const std::string* g_test_cache_root = NULL;

// The sync invalidation object ID for Google Drive.
const char kDriveInvalidationObjectId[] = "CHANGELOG";

// Returns true if Drive is enabled for the given Profile.
bool IsDriveEnabledForProfile(Profile* profile) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  if (!google_apis::AuthService::CanAuthenticate(profile))
    return false;

  // Disable Drive if preference is set.  This can happen with commandline flag
  // --disable-gdata or enterprise policy, or probably with user settings too
  // in the future.
  if (profile->GetPrefs()->GetBoolean(prefs::kDisableDrive))
    return false;

  return true;
}

// Returns a user agent string used for communicating with the Drive backend,
// both WAPI and Drive API.  The user agent looks like:
//
// chromedrive-<VERSION> chrome-cc/none (<OS_CPU_INFO>)
// chromedrive-24.0.1274.0 chrome-cc/none (CrOS x86_64 0.4.0)
//
// TODO(satorux): Move this function to somewhere else: crbug.com/151605
std::string GetDriveUserAgent() {
  const char kDriveClientName[] = "chromedrive";

  chrome::VersionInfo version_info;
  const std::string version = (version_info.is_valid() ?
                               version_info.Version() :
                               std::string("unknown"));

  // This part is <client_name>/<version>.
  const char kLibraryInfo[] = "chrome-cc/none";

  const std::string os_cpu_info = webkit_glue::BuildOSCpuInfo();

  return base::StringPrintf("%s-%s %s (%s)",
                            kDriveClientName,
                            version.c_str(),
                            kLibraryInfo,
                            os_cpu_info.c_str());
}

}  // namespace

DriveSystemService::DriveSystemService(Profile* profile)
    : profile_(profile),
      drive_disabled_(false),
      push_notification_registered_(false),
      cache_(NULL),
      ALLOW_THIS_IN_INITIALIZER_LIST(weak_ptr_factory_(this)) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  base::SequencedWorkerPool* blocking_pool = BrowserThread::GetBlockingPool();
  blocking_task_runner_ = blocking_pool->GetSequencedTaskRunner(
      blocking_pool->GetSequenceToken());
}

DriveSystemService::~DriveSystemService() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  cache_->Destroy();
}

void DriveSystemService::Initialize(
    google_apis::DriveServiceInterface* drive_service,
    const FilePath& cache_root) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  event_logger_.reset(new EventLogger(kEventLogHistorySize));
  drive_service_.reset(drive_service);
  cache_ = DriveCache::CreateDriveCache(cache_root, blocking_task_runner_);
  uploader_.reset(new google_apis::DriveUploader(drive_service_.get()));
  webapps_registry_.reset(new DriveWebAppsRegistry);
  file_system_.reset(new DriveFileSystem(profile_,
                                         cache(),
                                         drive_service_.get(),
                                         uploader(),
                                         webapps_registry(),
                                         blocking_task_runner_));
  file_write_helper_.reset(new FileWriteHelper(file_system()));
  download_observer_.reset(new DriveDownloadObserver(file_write_helper(),
                                                     file_system()));
  sync_client_.reset(new DriveSyncClient(profile_, file_system(), cache()));
  prefetcher_.reset(new DrivePrefetcher(file_system(),
                                        event_logger(),
                                        DrivePrefetcherOptions()));
  sync_client_->AddObserver(prefetcher_.get());
  stale_cache_files_remover_.reset(new StaleCacheFilesRemover(file_system(),
                                                              cache()));

  sync_client_->Initialize();
  file_system_->Initialize();
  cache_->RequestInitialize(base::Bind(&DriveSystemService::OnCacheInitialized,
                                       weak_ptr_factory_.GetWeakPtr()));
}

void DriveSystemService::Shutdown() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  ProfileSyncService* profile_sync_service =
      profile_ ? ProfileSyncServiceFactory::GetForProfile(profile_) : NULL;
  if (profile_sync_service && push_notification_registered_) {
    // TODO(kochi): Once DriveSystemService gets started / stopped at runtime,
    // this ID needs to be unregistered *before* the handler is unregistered
    // as ID persists across browser restarts.
    if (!IsDriveEnabledForProfile(profile_)) {
      profile_sync_service->UpdateRegisteredInvalidationIds(
          this, syncer::ObjectIdSet());
    }
    profile_sync_service->UnregisterInvalidationHandler(this);
    push_notification_registered_ = false;
  }

  RemoveDriveMountPoint();

  // Shut down the member objects in the reverse order of creation.
  stale_cache_files_remover_.reset();
  sync_client_->RemoveObserver(prefetcher_.get());
  prefetcher_.reset();
  sync_client_.reset();
  download_observer_.reset();
  file_write_helper_.reset();
  file_system_.reset();
  webapps_registry_.reset();
  uploader_.reset();
  drive_service_.reset();
}

bool DriveSystemService::IsDriveEnabled() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  if (!IsDriveEnabledForProfile(profile_))
    return false;

  // Drive may be disabled for cache initialization failure, etc.
  if (drive_disabled_)
    return false;

  return true;
}

void DriveSystemService::OnInvalidatorStateChange(
    syncer::InvalidatorState state) {
  file_system_->SetPushNotificationEnabled(
      state == syncer::INVALIDATIONS_ENABLED);
}

void DriveSystemService::OnIncomingInvalidation(
    const syncer::ObjectIdInvalidationMap& invalidation_map,
    syncer::IncomingInvalidationSource source) {
  DCHECK_EQ(1U, invalidation_map.size());
  const invalidation::ObjectId object_id(
      ipc::invalidation::ObjectSource::COSMO_CHANGELOG,
      kDriveInvalidationObjectId);
  DCHECK_EQ(1U, invalidation_map.count(object_id));

  file_system_->CheckForUpdates();
}

void DriveSystemService::ClearCacheAndRemountFileSystem(
    const base::Callback<void(bool)>& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  RemoveDriveMountPoint();
  drive_service()->CancelAll();
  cache_->ClearAll(base::Bind(&DriveSystemService::AddBackDriveMountPoint,
                              weak_ptr_factory_.GetWeakPtr(),
                              callback));
}

void DriveSystemService::AddBackDriveMountPoint(
    const base::Callback<void(bool)>& callback,
    bool success) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(!callback.is_null());

  file_system_->Initialize();
  AddDriveMountPoint();

  callback.Run(success);
}

void DriveSystemService::ReloadAndRemountFileSystem() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  RemoveDriveMountPoint();
  drive_service()->CancelAll();
  file_system_->Reload();

  // Reload() is asynchronous. But we can add back the mount point right away
  // because every operation waits until loading is complete.
  AddDriveMountPoint();
}

void DriveSystemService::AddDriveMountPoint() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  const FilePath mount_point = util::GetDriveMountPointPath();
  fileapi::ExternalFileSystemMountPointProvider* provider =
      BrowserContext::GetDefaultStoragePartition(profile_)->
          GetFileSystemContext()->external_provider();
  if (provider && !provider->HasMountPoint(mount_point)) {
    event_logger_->Log("AddDriveMountPoint");
    provider->AddRemoteMountPoint(
        mount_point,
        new DriveFileSystemProxy(file_system_.get()));
  }

  file_system_->NotifyFileSystemMounted();
}

void DriveSystemService::RemoveDriveMountPoint() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  file_system_->NotifyFileSystemToBeUnmounted();
  file_system_->StopPolling();

  const FilePath mount_point = util::GetDriveMountPointPath();
  fileapi::ExternalFileSystemMountPointProvider* provider =
      BrowserContext::GetDefaultStoragePartition(profile_)->
          GetFileSystemContext()->external_provider();
  if (provider && provider->HasMountPoint(mount_point)) {
    provider->RemoveMountPoint(mount_point);
    event_logger_->Log("RemoveDriveMountPoint");
  }
}

void DriveSystemService::OnCacheInitialized(bool success) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  if (!success) {
    LOG(WARNING) << "Failed to initialize the cache. Disabling Drive";
    DisableDrive();
    return;
  }

  content::DownloadManager* download_manager =
    g_browser_process->download_status_updater() ?
        BrowserContext::GetDownloadManager(profile_) : NULL;
  download_observer_->Initialize(
      download_manager,
      cache_->GetCacheDirectoryPath(
          DriveCache::CACHE_TYPE_TMP_DOWNLOADS));

  // Register for Google Drive invalidation notifications.
  ProfileSyncService* profile_sync_service =
      profile_ ? ProfileSyncServiceFactory::GetForProfile(profile_) : NULL;
  if (profile_sync_service) {
    DCHECK(!push_notification_registered_);
    profile_sync_service->RegisterInvalidationHandler(this);
    syncer::ObjectIdSet ids;
    ids.insert(invalidation::ObjectId(
        ipc::invalidation::ObjectSource::COSMO_CHANGELOG,
        kDriveInvalidationObjectId));
    profile_sync_service->UpdateRegisteredInvalidationIds(this, ids);
    push_notification_registered_ = true;
    file_system_->SetPushNotificationEnabled(
        profile_sync_service->GetInvalidatorState() ==
        syncer::INVALIDATIONS_ENABLED);
  }

  AddDriveMountPoint();

  // Start prefetching of Drive metadata.
  file_system_->StartInitialFeedFetch();
}

void DriveSystemService::DisableDrive() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  drive_disabled_ = true;
  // Change the download directory to the default value if the download
  // destination is set to under Drive mount point.
  PrefService* pref_service = profile_->GetPrefs();
  if (util::IsUnderDriveMountPoint(
          pref_service->GetFilePath(prefs::kDownloadDefaultDirectory))) {
    pref_service->SetFilePath(prefs::kDownloadDefaultDirectory,
                              download_util::GetDefaultDownloadDirectory());
  }
}

//===================== DriveSystemServiceFactory =============================

// static
DriveSystemService* DriveSystemServiceFactory::GetForProfile(
    Profile* profile) {
  DriveSystemService* service = static_cast<DriveSystemService*>(
      GetInstance()->GetServiceForProfile(profile, true));
  if (service && !service->IsDriveEnabled())
    return NULL;

  return service;
}

// static
DriveSystemService* DriveSystemServiceFactory::FindForProfile(
    Profile* profile) {
  DriveSystemService* service = static_cast<DriveSystemService*>(
      GetInstance()->GetServiceForProfile(profile, false));
  if (service && !service->IsDriveEnabled())
    return NULL;

  return service;
}

// static
DriveSystemServiceFactory* DriveSystemServiceFactory::GetInstance() {
  return Singleton<DriveSystemServiceFactory>::get();
}

DriveSystemServiceFactory::DriveSystemServiceFactory()
    : ProfileKeyedServiceFactory("DriveSystemService",
                                 ProfileDependencyManager::GetInstance()) {
  DependsOn(ProfileSyncServiceFactory::GetInstance());
  DependsOn(DownloadServiceFactory::GetInstance());
}

DriveSystemServiceFactory::~DriveSystemServiceFactory() {
}

// static
void DriveSystemServiceFactory::set_drive_service_for_test(
    google_apis::DriveServiceInterface* drive_service) {
  if (g_test_drive_service)
    delete g_test_drive_service;
  g_test_drive_service = drive_service;
}

// static
void DriveSystemServiceFactory::set_cache_root_for_test(
    const std::string& cache_root) {
  if (g_test_cache_root)
    delete g_test_cache_root;
  g_test_cache_root = !cache_root.empty() ? new std::string(cache_root) : NULL;
}

ProfileKeyedService* DriveSystemServiceFactory::BuildServiceInstanceFor(
    Profile* profile) const {
  DriveSystemService* service = new DriveSystemService(profile);

  google_apis::DriveServiceInterface* drive_service = g_test_drive_service;
  g_test_drive_service = NULL;
  if (!drive_service) {
    if (google_apis::util::IsDriveV2ApiEnabled()) {
      drive_service = new DriveAPIService(
          g_browser_process->system_request_context(),
          GetDriveUserAgent());
    } else {
      drive_service = new google_apis::GDataWapiService(
          g_browser_process->system_request_context(),
          GURL(google_apis::GDataWapiUrlGenerator::kBaseUrlForProduction),
          GetDriveUserAgent());
    }
  }

  FilePath cache_root =
      g_test_cache_root ? FilePath(*g_test_cache_root) :
                          DriveCache::GetCacheRootPath(profile);
  delete g_test_cache_root;
  g_test_cache_root = NULL;

  service->Initialize(drive_service, cache_root);
  return service;
}

}  // namespace drive
<|endoftext|>


<commit_before>#include<iostream>
#include"PlayState.h"
#include"Game.h"
#include"TextureManager.h"
#include"Player.h"

const std::string PlayState::playId = "PLAY";

void PlayState::update()
{
	for (int x = 0; x < gameObjects.size(); x++) {
		gameObjects[x]->update();
	}
}

void PlayState::render()
{
	for (int x = 0; x < gameObjects.size(); x++) {
		gameObjects[x]->draw();
	}
}

bool PlayState::onEnter()
{
    std::cout << "entering PlayState" << std::endl;

	if (!TheTextureManager::getInstance()->load("assets/helicopter.png", "helicopter", TheGame::getInstance()->getRenderer())) {
		return false;
	}

	GameObject* player = new Player(new LoaderParams(100, 100, 128, 55, "helicopter"));

	gameObjects.push_back(player);

	return true;
}

bool PlayState::onExit()
{
    std::cout << "exiting PLayState" << std::endl;

	for (int x = 0; x < gameObjects.size(); x++) {
		gameObjects[x]->clean();
	}

	gameObjects.clear();
	TheTextureManager::getInstance()->clearFromTextureMap("helicopter");

	return true;
}
<commit_msg>Included pause to the game.<commit_after>#include<iostream>
#include"PlayState.h"
#include"Game.h"
#include"TextureManager.h"
#include"InputHandler.h"
#include"PauseState.h"
#include"Player.h"

const std::string PlayState::playId = "PLAY";

void PlayState::update()
{
	if (TheInputHandler::getInstance()->isKeyDown(SDL_SCANCODE_ESCAPE)) {
		TheGame::getInstance()->getStateMachine()->pushState(new PauseState());
	}

	for (int x = 0; x < gameObjects.size(); x++) {
		gameObjects[x]->update();
	}
}

void PlayState::render()
{
	for (int x = 0; x < gameObjects.size(); x++) {
		gameObjects[x]->draw();
	}
}

bool PlayState::onEnter()
{
    std::cout << "entering PlayState" << std::endl;

	if (!TheTextureManager::getInstance()->load("assets/helicopter.png", "helicopter", TheGame::getInstance()->getRenderer())) {
		return false;
	}

	GameObject* player = new Player(new LoaderParams(100, 100, 128, 55, "helicopter"));

	gameObjects.push_back(player);

	return true;
}

bool PlayState::onExit()
{
    std::cout << "exiting PLayState" << std::endl;

	for (int x = 0; x < gameObjects.size(); x++) {
		gameObjects[x]->clean();
	}

	gameObjects.clear();
	TheTextureManager::getInstance()->clearFromTextureMap("helicopter");

	return true;
}
<|endoftext|>