<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
 *
 * This application is open source and may be redistributed and/or modified
 * freely and without restriction, both in commericial and non commericial applications,
 * as long as this copyright notice is maintained.
 *
 * This application 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.
*/

#include <osgDB/ReadFile>
#include <osgUtil/Optimizer>
#include <osg/CoordinateSystemNode>

#include <osg/Switch>
#include <osgText/Text>

#include <osgViewer/Viewer>
#include <osgViewer/StatsHandler>

#include <osgGA/TrackballManipulator>
#include <osgGA/FlightManipulator>
#include <osgGA/DriveManipulator>
#include <osgGA/KeySwitchMatrixManipulator>
#include <osgGA/StateSetManipulator>
#include <osgGA/AnimationPathManipulator>
#include <osgGA/TerrainManipulator>

#include <iostream>

class ThreadingHandler : public osgGA::GUIEventHandler
{
public:

    ThreadingHandler() {}

    bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
    {
        osgViewer::Viewer* viewer = dynamic_cast<osgViewer::Viewer*>(&aa);
        if (!viewer) return false;

        switch(ea.getEventType())
        {
            case(osgGA::GUIEventAdapter::KEYUP):
            {
                if (ea.getKey()=='m')
                {
                    switch(viewer->getThreadingModel())
                    {
                        case(osgViewer::Viewer::SingleThreaded):
                            viewer->setThreadingModel(osgViewer::Viewer::CullDrawThreadPerContext);
                            osg::notify(osg::NOTICE)<<"Threading model 'CullDrawThreadPerContext' selected."<<std::endl;
                            break;
                        case(osgViewer::Viewer::CullDrawThreadPerContext):
                            viewer->setThreadingModel(osgViewer::Viewer::DrawThreadPerContext);
                            osg::notify(osg::NOTICE)<<"Threading model 'DrawThreadPerContext' selected."<<std::endl;
                            break;
                        case(osgViewer::Viewer::DrawThreadPerContext):
                            viewer->setThreadingModel(osgViewer::Viewer::CullThreadPerCameraDrawThreadPerContext);
                            osg::notify(osg::NOTICE)<<"Threading model 'CullThreadPerCameraDrawThreadPerContext' selected."<<std::endl;
                            break;
                        case(osgViewer::Viewer::CullThreadPerCameraDrawThreadPerContext):
                            viewer->setThreadingModel(osgViewer::Viewer::SingleThreaded);
                            osg::notify(osg::NOTICE)<<"Threading model 'SingleThreaded' selected."<<std::endl;
                            break;
                        case(osgViewer::Viewer::AutomaticSelection):
                            viewer->setThreadingModel(viewer->suggestBestThreadingModel());
                            osg::notify(osg::NOTICE)<<"Threading model 'AutomaticSelection' selected."<<std::endl;
                            break;
                    }
                    return true;
                }
                if (ea.getKey()=='e')
                {
                    switch(viewer->getEndBarrierPosition())
                    {
                        case(osgViewer::Viewer::BeforeSwapBuffers):
                            viewer->setEndBarrierPosition(osgViewer::Viewer::AfterSwapBuffers);
                            osg::notify(osg::NOTICE)<<"Threading model 'AfterSwapBuffers' selected."<<std::endl;
                            break;
                        case(osgViewer::Viewer::AfterSwapBuffers):
                            viewer->setEndBarrierPosition(osgViewer::Viewer::BeforeSwapBuffers);
                            osg::notify(osg::NOTICE)<<"Threading model 'BeforeSwapBuffers' selected."<<std::endl;
                            break;
                    }
                    return true;
                }
            }
            default: break;
        }

        return false;
    }

    bool _done;
};

int main(int argc, char** argv)
{
    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the standard OpenSceneGraph example which loads and visualises 3d models.");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
    arguments.getApplicationUsage()->addCommandLineOption("--image <filename>","Load an image and render it on a quad");
    arguments.getApplicationUsage()->addCommandLineOption("--dem <filename>","Load an image/DEM and render it on a HeightField");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display command line parameters");
    arguments.getApplicationUsage()->addCommandLineOption("--help-env","Display environmental variables available");
    arguments.getApplicationUsage()->addCommandLineOption("--help-keys","Display keyboard & mouse bindings available");
    arguments.getApplicationUsage()->addCommandLineOption("--help-all","Display all command line, env vars and keyboard & mouse bindings.");

    // if user request help write it out to cout.
    bool helpAll = arguments.read("--help-all");
    unsigned int helpType = ((helpAll || arguments.read("-h") || arguments.read("--help"))? osg::ApplicationUsage::COMMAND_LINE_OPTION : 0 ) |
                            ((helpAll ||  arguments.read("--help-env"))? osg::ApplicationUsage::ENVIRONMENTAL_VARIABLE : 0 ) |
                            ((helpAll ||  arguments.read("--help-keys"))? osg::ApplicationUsage::KEYBOARD_MOUSE_BINDING : 0 );
    if (helpType)
    {
        arguments.getApplicationUsage()->write(std::cout, helpType);
        return 1;
    }

    // report any errors if they have occurred when parsing the program arguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

    if (arguments.argc()<=1)
    {
        arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
        return 1;
    }

    osgViewer::Viewer viewer;

    // set up the camera manipulators.
    {
        osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator;

        keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() );
        keyswitchManipulator->addMatrixManipulator( '2', "Flight", new osgGA::FlightManipulator() );
        keyswitchManipulator->addMatrixManipulator( '3', "Drive", new osgGA::DriveManipulator() );
        keyswitchManipulator->addMatrixManipulator( '4', "Terrain", new osgGA::TerrainManipulator() );

        std::string pathfile;
        char keyForAnimationPath = '5';
        while (arguments.read("-p",pathfile))
        {
            osgGA::AnimationPathManipulator* apm = new osgGA::AnimationPathManipulator(pathfile);
            if (apm || !apm->valid())
            {
                unsigned int num = keyswitchManipulator->getNumMatrixManipulators();
                keyswitchManipulator->addMatrixManipulator( keyForAnimationPath, "Path", apm );
                keyswitchManipulator->selectMatrixManipulator(num);
                ++keyForAnimationPath;
            }
        }

        viewer.setCameraManipulator( keyswitchManipulator.get() );
    }

    // add the state manipulator
    viewer.addEventHandler( new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()) );

    // add the thread model handler
    viewer.addEventHandler(new ThreadingHandler);

    // add the stats handler
    viewer.addEventHandler(new osgViewer::StatsHandler);

    unsigned int screenNum;
    while (arguments.read("--screen",screenNum))
    {
        viewer.setUpViewOnSingleScreen(screenNum);
    }

    // load the data
    osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments);
    if (!loadedModel)
    {
        std::cout << arguments.getApplicationName() <<": No data loaded" << std::endl;
        return 1;
    }

    // any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized();

    // report any errors if they have occurred when parsing the program arguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

    // optimize the scene graph, remove redundant nodes and state etc.
    osgUtil::Optimizer optimizer;
    optimizer.optimize(loadedModel.get());

    viewer.setSceneData( loadedModel.get() );

    return viewer.run();
}
<commit_msg>Disabled the toggling to ThreadModel CullThreadPerCameraDrawThreadPerContext<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
 *
 * This application is open source and may be redistributed and/or modified
 * freely and without restriction, both in commericial and non commericial applications,
 * as long as this copyright notice is maintained.
 *
 * This application 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.
*/

#include <osgDB/ReadFile>
#include <osgUtil/Optimizer>
#include <osg/CoordinateSystemNode>

#include <osg/Switch>
#include <osgText/Text>

#include <osgViewer/Viewer>
#include <osgViewer/StatsHandler>

#include <osgGA/TrackballManipulator>
#include <osgGA/FlightManipulator>
#include <osgGA/DriveManipulator>
#include <osgGA/KeySwitchMatrixManipulator>
#include <osgGA/StateSetManipulator>
#include <osgGA/AnimationPathManipulator>
#include <osgGA/TerrainManipulator>

#include <iostream>

class ThreadingHandler : public osgGA::GUIEventHandler
{
public:

    ThreadingHandler() {}

    bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
    {
        osgViewer::Viewer* viewer = dynamic_cast<osgViewer::Viewer*>(&aa);
        if (!viewer) return false;

        switch(ea.getEventType())
        {
            case(osgGA::GUIEventAdapter::KEYUP):
            {
                if (ea.getKey()=='m')
                {
#if 1
                    switch(viewer->getThreadingModel())
                    {
                        case(osgViewer::Viewer::SingleThreaded):
                            viewer->setThreadingModel(osgViewer::Viewer::CullDrawThreadPerContext);
                            osg::notify(osg::NOTICE)<<"Threading model 'CullDrawThreadPerContext' selected."<<std::endl;
                            break;
                        case(osgViewer::Viewer::CullDrawThreadPerContext):
                            viewer->setThreadingModel(osgViewer::Viewer::DrawThreadPerContext);
                            osg::notify(osg::NOTICE)<<"Threading model 'DrawThreadPerContext' selected."<<std::endl;
                            break;
                        case(osgViewer::Viewer::DrawThreadPerContext):
                            viewer->setThreadingModel(osgViewer::Viewer::SingleThreaded);
                            osg::notify(osg::NOTICE)<<"Threading model 'SingleThreaded' selected."<<std::endl;
                            break;
                        default:
                            break;
                    }
#else
                    switch(viewer->getThreadingModel())
                    {
                        case(osgViewer::Viewer::SingleThreaded):
                            viewer->setThreadingModel(osgViewer::Viewer::CullDrawThreadPerContext);
                            osg::notify(osg::NOTICE)<<"Threading model 'CullDrawThreadPerContext' selected."<<std::endl;
                            break;
                        case(osgViewer::Viewer::CullDrawThreadPerContext):
                            viewer->setThreadingModel(osgViewer::Viewer::DrawThreadPerContext);
                            osg::notify(osg::NOTICE)<<"Threading model 'DrawThreadPerContext' selected."<<std::endl;
                            break;
                        case(osgViewer::Viewer::DrawThreadPerContext):
                            viewer->setThreadingModel(osgViewer::Viewer::CullThreadPerCameraDrawThreadPerContext);
                            osg::notify(osg::NOTICE)<<"Threading model 'CullThreadPerCameraDrawThreadPerContext' selected."<<std::endl;
                            break;
                        case(osgViewer::Viewer::CullThreadPerCameraDrawThreadPerContext):
                            viewer->setThreadingModel(osgViewer::Viewer::SingleThreaded);
                            osg::notify(osg::NOTICE)<<"Threading model 'SingleThreaded' selected."<<std::endl;
                            break;
                        case(osgViewer::Viewer::AutomaticSelection):
                            viewer->setThreadingModel(viewer->suggestBestThreadingModel());
                            osg::notify(osg::NOTICE)<<"Threading model 'AutomaticSelection' selected."<<std::endl;
                            break;
                    }
#endif
                    return true;
                }
                if (ea.getKey()=='e')
                {
                    switch(viewer->getEndBarrierPosition())
                    {
                        case(osgViewer::Viewer::BeforeSwapBuffers):
                            viewer->setEndBarrierPosition(osgViewer::Viewer::AfterSwapBuffers);
                            osg::notify(osg::NOTICE)<<"Threading model 'AfterSwapBuffers' selected."<<std::endl;
                            break;
                        case(osgViewer::Viewer::AfterSwapBuffers):
                            viewer->setEndBarrierPosition(osgViewer::Viewer::BeforeSwapBuffers);
                            osg::notify(osg::NOTICE)<<"Threading model 'BeforeSwapBuffers' selected."<<std::endl;
                            break;
                    }
                    return true;
                }
            }
            default: break;
        }

        return false;
    }

    bool _done;
};

int main(int argc, char** argv)
{
    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the standard OpenSceneGraph example which loads and visualises 3d models.");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
    arguments.getApplicationUsage()->addCommandLineOption("--image <filename>","Load an image and render it on a quad");
    arguments.getApplicationUsage()->addCommandLineOption("--dem <filename>","Load an image/DEM and render it on a HeightField");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display command line parameters");
    arguments.getApplicationUsage()->addCommandLineOption("--help-env","Display environmental variables available");
    arguments.getApplicationUsage()->addCommandLineOption("--help-keys","Display keyboard & mouse bindings available");
    arguments.getApplicationUsage()->addCommandLineOption("--help-all","Display all command line, env vars and keyboard & mouse bindings.");

    // if user request help write it out to cout.
    bool helpAll = arguments.read("--help-all");
    unsigned int helpType = ((helpAll || arguments.read("-h") || arguments.read("--help"))? osg::ApplicationUsage::COMMAND_LINE_OPTION : 0 ) |
                            ((helpAll ||  arguments.read("--help-env"))? osg::ApplicationUsage::ENVIRONMENTAL_VARIABLE : 0 ) |
                            ((helpAll ||  arguments.read("--help-keys"))? osg::ApplicationUsage::KEYBOARD_MOUSE_BINDING : 0 );
    if (helpType)
    {
        arguments.getApplicationUsage()->write(std::cout, helpType);
        return 1;
    }

    // report any errors if they have occurred when parsing the program arguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

    if (arguments.argc()<=1)
    {
        arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);
        return 1;
    }

    osgViewer::Viewer viewer;

    // set up the camera manipulators.
    {
        osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator;

        keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() );
        keyswitchManipulator->addMatrixManipulator( '2', "Flight", new osgGA::FlightManipulator() );
        keyswitchManipulator->addMatrixManipulator( '3', "Drive", new osgGA::DriveManipulator() );
        keyswitchManipulator->addMatrixManipulator( '4', "Terrain", new osgGA::TerrainManipulator() );

        std::string pathfile;
        char keyForAnimationPath = '5';
        while (arguments.read("-p",pathfile))
        {
            osgGA::AnimationPathManipulator* apm = new osgGA::AnimationPathManipulator(pathfile);
            if (apm || !apm->valid())
            {
                unsigned int num = keyswitchManipulator->getNumMatrixManipulators();
                keyswitchManipulator->addMatrixManipulator( keyForAnimationPath, "Path", apm );
                keyswitchManipulator->selectMatrixManipulator(num);
                ++keyForAnimationPath;
            }
        }

        viewer.setCameraManipulator( keyswitchManipulator.get() );
    }

    // add the state manipulator
    viewer.addEventHandler( new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()) );

    // add the thread model handler
    viewer.addEventHandler(new ThreadingHandler);

    // add the stats handler
    viewer.addEventHandler(new osgViewer::StatsHandler);

    unsigned int screenNum;
    while (arguments.read("--screen",screenNum))
    {
        viewer.setUpViewOnSingleScreen(screenNum);
    }

    // load the data
    osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments);
    if (!loadedModel)
    {
        std::cout << arguments.getApplicationName() <<": No data loaded" << std::endl;
        return 1;
    }

    // any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized();

    // report any errors if they have occurred when parsing the program arguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

    // optimize the scene graph, remove redundant nodes and state etc.
    osgUtil::Optimizer optimizer;
    optimizer.optimize(loadedModel.get());

    viewer.setSceneData( loadedModel.get() );

    return viewer.run();
}
<|endoftext|>


<commit_before>#include "sm/logging.hpp"

#include <string>
#include <boost/algorithm/string.hpp> // for case-insensitive string comparison

/**
 * \brief Returns a Level enum from string
 */
sm::logging::Level sm::logging::levels::fromString(const std::string& l) {

//   enum Level
//   {
//       All,
//       Finest,
//       Verbose,
//       Finer,
//       Trace,
//       Fine,
//       Debug,
//       Info,
//       Warn,
//       Error,
//       Fatal,
//
//       Count
//   };

  if (boost::iequals(l, "All")) {
    return Level::All;
  } else if (boost::iequals(l, "Finest")) {
    return Level::Finest;
  } else if (boost::iequals(l, "Verbose")) {
    return Level::Verbose;
  } else if (boost::iequals(l, "Finer")) {
    return Level::Finer;
  } else if (boost::iequals(l, "Trace")) {
    return Level::Trace;
  } else if (boost::iequals(l, "Fine")) {
    return Level::Fine;
  } else if (boost::iequals(l, "Debug")) {
    return Level::Debug;
  } else if (boost::iequals(l, "Info")) {
    return Level::Info;
  } else if (boost::iequals(l, "Warn")) {
    return Level::Warn;
  } else if (boost::iequals(l, "Error")) {
    return Level::Error;
  } else if (boost::iequals(l, "Fatal")) {
    return Level::Fatal;
  } else {
    SM_ERROR_STREAM("Invalid logging level " << l << ", setting to Level::Info");
    return Level::Info;
  }

}<commit_msg>Update Levels.cpp<commit_after>#include "sm/logging.hpp"

#include <string>
#include <boost/algorithm/string.hpp> // for case-insensitive string comparison

/**
 * \brief Returns a Level enum from string
 */
sm::logging::Level sm::logging::levels::fromString(const std::string& level) {

  if (boost::iequals(level, "All")) {
    return Level::All;
  } else if (boost::iequals(level, "Finest")) {
    return Level::Finest;
  } else if (boost::iequals(level, "Verbose")) {
    return Level::Verbose;
  } else if (boost::iequals(level, "Finer")) {
    return Level::Finer;
  } else if (boost::iequals(level, "Trace")) {
    return Level::Trace;
  } else if (boost::iequals(level, "Fine")) {
    return Level::Fine;
  } else if (boost::iequals(level, "Debug")) {
    return Level::Debug;
  } else if (boost::iequals(level, "Info")) {
    return Level::Info;
  } else if (boost::iequals(level, "Warn")) {
    return Level::Warn;
  } else if (boost::iequals(level, "Error")) {
    return Level::Error;
  } else if (boost::iequals(level, "Fatal")) {
    return Level::Fatal;
  } else {
    SM_ERROR_STREAM("Invalid logging level " << level << ", setting to Level::Info");
    return Level::Info;
  }

}
<|endoftext|>


<commit_before>#include "Halide.h"

using namespace Halide;

void blur_float(std::string suffix, ImageParam input8, const int channels) {
    Var x, y, c;
    Func input;
    input(x, y, c) = input8(clamp(x, input8.left(), input8.right()),
                            clamp(y, input8.top(), input8.bottom()), c);

    Func blur_x("blur_x");
    blur_x(x, y, c) = (input(x, y, c) +
        input(x + 1, y, c) +
        input(x + 2, y, c)) / 3;

    Func result("result");
    result(x, y, c) = (blur_x(x, y, c) +
        blur_x(x, y + 1, c) +
        blur_x(x, y + 2, c)) / 3;

    // Unset default constraints so that specialization works.
    result.output_buffer().set_stride(0, Expr());

    result.bound(c, 0, channels);

    Expr interleaved =
        (result.output_buffer().stride(0) == channels &&
         result.output_buffer().stride(2) == 1);
    Expr planar = result.output_buffer().stride(0) == 1;

    if (suffix == "_rs") {
        result.shader(x, y, c, DeviceAPI::Renderscript);
        result.specialize(interleaved).vectorize(c);
        // non-specialized version is planar
    } else {
        Var yi;
        result
            .reorder(c, x, y)
            .unroll(c)
            .split(y, y, yi, 32)
            .parallel(y)
            .vectorize(x, 2);
        result.specialize(interleaved);
        result.specialize(planar);
        // blur_x is compute at result, so it's included in result's
        // specializations.
        blur_x.store_at(result, y)
            .compute_at(result, yi)
            .reorder(c, x, y)
            .unroll(c)
            .vectorize(x, 2);
    }

    std::vector<Argument> args;
    args.push_back(input8);
    std::string filename("generated_blur");
    result.compile_to_file(filename + suffix + "_float", args);
}

void copy_float(std::string suffix, ImageParam input8, const int channels) {
    Var x, y, c;
    Func input;
    input(x, y, c) = input8(clamp(x, input8.left(), input8.right()),
                            clamp(y, input8.top(), input8.bottom()), c);

    Func result("result");
    result(x, y, c) = input(x, y, c);
    result.bound(c, 0, channels);

    // Unset default constraints so that specialization works.
    result.output_buffer().set_stride(0, Expr());

    Expr interleaved =
        (result.output_buffer().stride(0) == channels &&
         result.output_buffer().stride(2) == 1);

    if (suffix == "_rs") {
        result.shader(x, y, c, DeviceAPI::Renderscript);
        result.specialize(interleaved).vectorize(c);
    } else {
        result.reorder(c, x, y)
            .parallel(y)
            .unroll(c)
            .vectorize(x, 2)
            .specialize(interleaved);
    }
    // non-specialized version is planar

    std::vector<Argument> args;
    args.push_back(input8);
    std::string filename("generated_copy");
    result.compile_to_file(filename + suffix + "_float", args);
}

void blur_uint8(std::string suffix, ImageParam input8, const int channels) {
    Var x, y, c;
    Func input;
    input(x, y, c) = input8(clamp(x, input8.left(), input8.right()),
                            clamp(y, input8.top(), input8.bottom()), c);

    Func blur_x("blur_x");

    blur_x(x, y, c) = cast<uint8_t>(
        (cast<uint16_t>(input(x, y, c)) +
        input(x + 1, y, c) +
        input(x + 2, y, c)) / 3);

    Func result("result");
    result(x, y, c) = cast<uint8_t>(
        (cast<uint16_t>(blur_x(x, y, c)) +
        blur_x(x, y + 1, c) +
        blur_x(x, y + 2, c)) / 3);

    // Unset default constraints so that specialization works.
    result.output_buffer().set_stride(0, Expr());

    result.bound(c, 0, channels);

    Expr interleaved =
        (result.output_buffer().stride(0) == channels &&
         result.output_buffer().stride(2) == 1);
    Expr planar = result.output_buffer().stride(0) == 1;

    if (suffix == "_rs") {
        result.shader(x, y, c, DeviceAPI::Renderscript);
        result.specialize(interleaved).vectorize(c);
        // non-specialized version is planar
    } else {
        Var yi;
        result
            .reorder(c, x, y)
            .unroll(c)
            .split(y, y, yi, 32)
            .parallel(y)
            .vectorize(x, 8);
        result.specialize(interleaved);
        result.specialize(planar);
        // blur_x is compute at result, so it's included in result's
        // specializations.
        blur_x.store_at(result, y)
            .compute_at(result, yi)
            .reorder(c, x, y)
            .unroll(c)
            .vectorize(x, 8);
    }

    std::vector<Argument> args;
    args.push_back(input8);
    std::string filename("generated_blur");
    result.compile_to_file(filename + suffix + "_uint8", args);
}

void copy_uint8(std::string suffix, ImageParam input8, const int channels) {
    Var x, y, c;
    Func input;
    input(x, y, c) = input8(clamp(x, input8.left(), input8.right()),
                            clamp(y, input8.top(), input8.bottom()), c);

    Func result("result");
    result(x, y, c) = input(x, y, c);
    result.bound(c, 0, channels);

    // Unset default constraints so that specialization works.
    result.output_buffer().set_stride(0, Expr());

    Expr interleaved =
        (result.output_buffer().stride(0) == channels &&
         result.output_buffer().stride(2) == 1);

    if (suffix == "_rs") {
        result.shader(x, y, c, DeviceAPI::Renderscript);
        result.specialize(interleaved).vectorize(c);
    } else {
        result.reorder(c, x, y)
            .parallel(y)
            .unroll(c)
            .vectorize(x, 16)
            .specialize(interleaved);
    }
    // non-specialized version is planar

    std::vector<Argument> args;
    args.push_back(input8);
    std::string filename("generated_copy");
    result.compile_to_file(filename + suffix + "_uint8", args);
}

int main(int argc, char **argv) {
    const int channels = 4;

    ImageParam input_float(Float(32), 3, "input");
    input_float.set_stride(0, Expr());
    blur_float(argc > 1 ? argv[1] : "", input_float, channels);
    copy_float(argc > 1 ? argv[1]: "", input_float, channels);

    ImageParam input_uint8(UInt(8), 3, "input");
    input_uint8.set_stride(0, Expr());
    blur_uint8(argc > 1 ? argv[1] : "", input_uint8, channels);
    copy_uint8(argc > 1 ? argv[1]: "", input_uint8, channels);

    std::cout << "Done!" << std::endl;
}
<commit_msg>Adjust vectorization to match natural vector size for ARM NEON<commit_after>#include "Halide.h"

using namespace Halide;

void blur_float(std::string suffix, ImageParam input8, const int channels) {
    Var x, y, c;
    Func input;
    input(x, y, c) = input8(clamp(x, input8.left(), input8.right()),
                            clamp(y, input8.top(), input8.bottom()), c);

    Func blur_x("blur_x");
    blur_x(x, y, c) = (input(x, y, c) +
        input(x + 1, y, c) +
        input(x + 2, y, c)) / 3;

    Func result("result");
    result(x, y, c) = (blur_x(x, y, c) +
        blur_x(x, y + 1, c) +
        blur_x(x, y + 2, c)) / 3;

    // Unset default constraints so that specialization works.
    result.output_buffer().set_stride(0, Expr());

    result.bound(c, 0, channels);

    Expr interleaved =
        (result.output_buffer().stride(0) == channels &&
         result.output_buffer().stride(2) == 1);
    Expr planar = result.output_buffer().stride(0) == 1;

    if (suffix == "_rs") {
        result.shader(x, y, c, DeviceAPI::Renderscript);
        result.specialize(interleaved).vectorize(c);
        // non-specialized version is planar
    } else {
        Var yi;
        result
            .reorder(c, x, y)
            .unroll(c)
            .split(y, y, yi, 32)
            .parallel(y)
            .vectorize(x, 4);
        result.specialize(interleaved);
        result.specialize(planar);
        // blur_x is compute at result, so it's included in result's
        // specializations.
        blur_x.store_at(result, y)
            .compute_at(result, yi)
            .reorder(c, x, y)
            .unroll(c)
            .vectorize(x, 4);
    }

    std::vector<Argument> args;
    args.push_back(input8);
    std::string filename("generated_blur");
    result.compile_to_file(filename + suffix + "_float", args);
}

void copy_float(std::string suffix, ImageParam input8, const int channels) {
    Var x, y, c;
    Func input;
    input(x, y, c) = input8(clamp(x, input8.left(), input8.right()),
                            clamp(y, input8.top(), input8.bottom()), c);

    Func result("result");
    result(x, y, c) = input(x, y, c);
    result.bound(c, 0, channels);

    // Unset default constraints so that specialization works.
    result.output_buffer().set_stride(0, Expr());

    Expr interleaved =
        (result.output_buffer().stride(0) == channels &&
         result.output_buffer().stride(2) == 1);

    if (suffix == "_rs") {
        result.shader(x, y, c, DeviceAPI::Renderscript);
        result.specialize(interleaved).vectorize(c);
    } else {
        result.reorder(c, x, y)
            .parallel(y)
            .unroll(c)
            .vectorize(x, 4)
            .specialize(interleaved);
    }
    // non-specialized version is planar

    std::vector<Argument> args;
    args.push_back(input8);
    std::string filename("generated_copy");
    result.compile_to_file(filename + suffix + "_float", args);
}

void blur_uint8(std::string suffix, ImageParam input8, const int channels) {
    Var x, y, c;
    Func input;
    input(x, y, c) = input8(clamp(x, input8.left(), input8.right()),
                            clamp(y, input8.top(), input8.bottom()), c);

    Func blur_x("blur_x");

    blur_x(x, y, c) = cast<uint8_t>(
        (cast<uint16_t>(input(x, y, c)) +
        input(x + 1, y, c) +
        input(x + 2, y, c)) / 3);

    Func result("result");
    result(x, y, c) = cast<uint8_t>(
        (cast<uint16_t>(blur_x(x, y, c)) +
        blur_x(x, y + 1, c) +
        blur_x(x, y + 2, c)) / 3);

    // Unset default constraints so that specialization works.
    result.output_buffer().set_stride(0, Expr());

    result.bound(c, 0, channels);

    Expr interleaved =
        (result.output_buffer().stride(0) == channels &&
         result.output_buffer().stride(2) == 1);
    Expr planar = result.output_buffer().stride(0) == 1;

    if (suffix == "_rs") {
        result.shader(x, y, c, DeviceAPI::Renderscript);
        result.specialize(interleaved).vectorize(c);
        // non-specialized version is planar
    } else {
        Var yi;
        result
            .reorder(c, x, y)
            .unroll(c)
            .split(y, y, yi, 32)
            .parallel(y)
            .vectorize(x, 8);
        result.specialize(interleaved);
        result.specialize(planar);
        // blur_x is compute at result, so it's included in result's
        // specializations.
        blur_x.store_at(result, y)
            .compute_at(result, yi)
            .reorder(c, x, y)
            .unroll(c)
            .vectorize(x, 8);
    }

    std::vector<Argument> args;
    args.push_back(input8);
    std::string filename("generated_blur");
    result.compile_to_file(filename + suffix + "_uint8", args);
}

void copy_uint8(std::string suffix, ImageParam input8, const int channels) {
    Var x, y, c;
    Func input;
    input(x, y, c) = input8(clamp(x, input8.left(), input8.right()),
                            clamp(y, input8.top(), input8.bottom()), c);

    Func result("result");
    result(x, y, c) = input(x, y, c);
    result.bound(c, 0, channels);

    // Unset default constraints so that specialization works.
    result.output_buffer().set_stride(0, Expr());

    Expr interleaved =
        (result.output_buffer().stride(0) == channels &&
         result.output_buffer().stride(2) == 1);

    if (suffix == "_rs") {
        result.shader(x, y, c, DeviceAPI::Renderscript);
        result.specialize(interleaved).vectorize(c);
    } else {
        result.reorder(c, x, y)
            .parallel(y)
            .unroll(c)
            .vectorize(x, 16)
            .specialize(interleaved);
    }
    // non-specialized version is planar

    std::vector<Argument> args;
    args.push_back(input8);
    std::string filename("generated_copy");
    result.compile_to_file(filename + suffix + "_uint8", args);
}

int main(int argc, char **argv) {
    const int channels = 4;

    ImageParam input_float(Float(32), 3, "input");
    input_float.set_stride(0, Expr());
    blur_float(argc > 1 ? argv[1] : "", input_float, channels);
    copy_float(argc > 1 ? argv[1]: "", input_float, channels);

    ImageParam input_uint8(UInt(8), 3, "input");
    input_uint8.set_stride(0, Expr());
    blur_uint8(argc > 1 ? argv[1] : "", input_uint8, channels);
    copy_uint8(argc > 1 ? argv[1]: "", input_uint8, channels);

    std::cout << "Done!" << std::endl;
}
<|endoftext|>


<commit_before>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include <memory>

#include "atom/browser/api/atom_api_cookies.h"

#include "atom/browser/atom_browser_context.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/gurl_converter.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "base/time/time.h"
#include "base/values.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "native_mate/dictionary.h"
#include "native_mate/object_template_builder.h"
#include "net/cookies/cookie_monster.h"
#include "net/cookies/cookie_store.h"
#include "net/cookies/cookie_util.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"

using content::BrowserThread;

namespace mate {

template<>
struct Converter<atom::api::Cookies::Error> {
  static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
                                   atom::api::Cookies::Error val) {
    if (val == atom::api::Cookies::SUCCESS)
      return v8::Null(isolate);
    else
      return v8::Exception::Error(StringToV8(isolate, "Setting cookie failed"));
  }
};

template<>
struct Converter<net::CanonicalCookie> {
  static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
                                   const net::CanonicalCookie& val) {
    mate::Dictionary dict(isolate, v8::Object::New(isolate));
    dict.Set("name", val.Name());
    dict.Set("value", val.Value());
    dict.Set("domain", val.Domain());
    dict.Set("hostOnly", net::cookie_util::DomainIsHostOnly(val.Domain()));
    dict.Set("path", val.Path());
    dict.Set("secure", val.IsSecure());
    dict.Set("httpOnly", val.IsHttpOnly());
    dict.Set("session", !val.IsPersistent());
    if (val.IsPersistent())
      dict.Set("expirationDate", val.ExpiryDate().ToDoubleT());
    return dict.GetHandle();
  }
};

}  // namespace mate

namespace atom {

namespace api {

namespace {

// Returns whether |domain| matches |filter|.
bool MatchesDomain(std::string filter, const std::string& domain) {
  // Add a leading '.' character to the filter domain if it doesn't exist.
  if (net::cookie_util::DomainIsHostOnly(filter))
    filter.insert(0, ".");

  std::string sub_domain(domain);
  // Strip any leading '.' character from the input cookie domain.
  if (!net::cookie_util::DomainIsHostOnly(sub_domain))
    sub_domain = sub_domain.substr(1);

  // Now check whether the domain argument is a subdomain of the filter domain.
  for (sub_domain.insert(0, "."); sub_domain.length() >= filter.length();) {
    if (sub_domain == filter)
      return true;
    const size_t next_dot = sub_domain.find('.', 1);  // Skip over leading dot.
    sub_domain.erase(0, next_dot);
  }
  return false;
}

// Returns whether |cookie| matches |filter|.
bool MatchesCookie(const base::DictionaryValue* filter,
                   const net::CanonicalCookie& cookie) {
  std::string str;
  bool b;
  if (filter->GetString("name", &str) && str != cookie.Name())
    return false;
  if (filter->GetString("path", &str) && str != cookie.Path())
    return false;
  if (filter->GetString("domain", &str) && !MatchesDomain(str, cookie.Domain()))
    return false;
  if (filter->GetBoolean("secure", &b) && b != cookie.IsSecure())
    return false;
  if (filter->GetBoolean("session", &b) && b != !cookie.IsPersistent())
    return false;
  return true;
}

// Helper to returns the CookieStore.
inline net::CookieStore* GetCookieStore(
    scoped_refptr<net::URLRequestContextGetter> getter) {
  return getter->GetURLRequestContext()->cookie_store();
}

// Run |callback| on UI thread.
void RunCallbackInUI(const base::Closure& callback) {
  BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, callback);
}

// Remove cookies from |list| not matching |filter|, and pass it to |callback|.
void FilterCookies(std::unique_ptr<base::DictionaryValue> filter,
                   const Cookies::GetCallback& callback,
                   const net::CookieList& list) {
  net::CookieList result;
  for (const auto& cookie : list) {
    if (MatchesCookie(filter.get(), cookie))
      result.push_back(cookie);
  }
  RunCallbackInUI(base::Bind(callback, Cookies::SUCCESS, result));
}

// Receives cookies matching |filter| in IO thread.
void GetCookiesOnIO(scoped_refptr<net::URLRequestContextGetter> getter,
                    std::unique_ptr<base::DictionaryValue> filter,
                    const Cookies::GetCallback& callback) {
  std::string url;
  filter->GetString("url", &url);

  auto filtered_callback =
      base::Bind(FilterCookies, base::Passed(&filter), callback);

  // Empty url will match all url cookies.
  if (url.empty())
    GetCookieStore(getter)->GetAllCookiesAsync(filtered_callback);
  else
    GetCookieStore(getter)->GetAllCookiesForURLAsync(GURL(url),
        filtered_callback);
}

// Removes cookie with |url| and |name| in IO thread.
void RemoveCookieOnIOThread(scoped_refptr<net::URLRequestContextGetter> getter,
                            const GURL& url, const std::string& name,
                            const base::Closure& callback) {
  GetCookieStore(getter)->DeleteCookieAsync(
      url, name, base::Bind(RunCallbackInUI, callback));
}

// Callback of SetCookie.
void OnSetCookie(const Cookies::SetCallback& callback, bool success) {
  RunCallbackInUI(
      base::Bind(callback, success ? Cookies::SUCCESS : Cookies::FAILED));
}

// Sets cookie with |details| in IO thread.
void SetCookieOnIO(scoped_refptr<net::URLRequestContextGetter> getter,
                   std::unique_ptr<base::DictionaryValue> details,
                   const Cookies::SetCallback& callback) {
  std::string url, name, value, domain, path;
  bool secure = false;
  bool http_only = false;
  double creation_date;
  double expiration_date;
  double last_access_date;
  details->GetString("url", &url);
  details->GetString("name", &name);
  details->GetString("value", &value);
  details->GetString("domain", &domain);
  details->GetString("path", &path);
  details->GetBoolean("secure", &secure);
  details->GetBoolean("httpOnly", &http_only);

  base::Time creation_time;
  if (details->GetDouble("creationDate", &creation_date)) {
    creation_time = (creation_date == 0) ?
        base::Time::UnixEpoch() :
        base::Time::FromDoubleT(creation_date);
  }

  base::Time expiration_time;
  if (details->GetDouble("expirationDate", &expiration_date)) {
    expiration_time = (expiration_date == 0) ?
        base::Time::UnixEpoch() :
        base::Time::FromDoubleT(expiration_date);
  }

  base::Time last_access_time;
  if (details->GetDouble("lastAccessDate", &last_access_date)) {
    last_access_time = (last_access_date == 0) ?
        base::Time::UnixEpoch() :
        base::Time::FromDoubleT(last_access_date);
  }

  GetCookieStore(getter)->SetCookieWithDetailsAsync(
      GURL(url), name, value, domain, path, creation_time,
      expiration_time, last_access_time, secure, http_only,
      net::CookieSameSite::DEFAULT_MODE, false,
      net::COOKIE_PRIORITY_DEFAULT, base::Bind(OnSetCookie, callback));
}

}  // namespace

Cookies::Cookies(v8::Isolate* isolate,
                 AtomBrowserContext* browser_context)
      : request_context_getter_(browser_context->url_request_context_getter()) {
  Init(isolate);
}

Cookies::~Cookies() {
}

void Cookies::Get(const base::DictionaryValue& filter,
                  const GetCallback& callback) {
  std::unique_ptr<base::DictionaryValue> copied(filter.CreateDeepCopy());
  auto getter = base::RetainedRef(request_context_getter_);
  content::BrowserThread::PostTask(
      BrowserThread::IO, FROM_HERE,
      base::Bind(GetCookiesOnIO, getter, Passed(&copied), callback));
}

void Cookies::Remove(const GURL& url, const std::string& name,
                     const base::Closure& callback) {
  auto getter = base::RetainedRef(request_context_getter_);
  content::BrowserThread::PostTask(
      BrowserThread::IO, FROM_HERE,
      base::Bind(RemoveCookieOnIOThread, getter, url, name, callback));
}

void Cookies::Set(const base::DictionaryValue& details,
                  const SetCallback& callback) {
  std::unique_ptr<base::DictionaryValue> copied(details.CreateDeepCopy());
  auto getter = base::RetainedRef(request_context_getter_);
  content::BrowserThread::PostTask(
      BrowserThread::IO, FROM_HERE,
      base::Bind(SetCookieOnIO, getter, Passed(&copied), callback));
}

// static
mate::Handle<Cookies> Cookies::Create(
    v8::Isolate* isolate,
    AtomBrowserContext* browser_context) {
  return mate::CreateHandle(isolate, new Cookies(isolate, browser_context));
}

// static
void Cookies::BuildPrototype(v8::Isolate* isolate,
                             v8::Local<v8::FunctionTemplate> prototype) {
  prototype->SetClassName(mate::StringToV8(isolate, "Cookies"));
  mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
      .SetMethod("get", &Cookies::Get)
      .SetMethod("remove", &Cookies::Remove)
      .SetMethod("set", &Cookies::Set);
}

}  // namespace api

}  // namespace atom
<commit_msg>Update SetCookieWithDetailsAsync call to match interface<commit_after>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include <memory>

#include "atom/browser/api/atom_api_cookies.h"

#include "atom/browser/atom_browser_context.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/gurl_converter.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "base/time/time.h"
#include "base/values.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "native_mate/dictionary.h"
#include "native_mate/object_template_builder.h"
#include "net/cookies/cookie_monster.h"
#include "net/cookies/cookie_store.h"
#include "net/cookies/cookie_util.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"

using content::BrowserThread;

namespace mate {

template<>
struct Converter<atom::api::Cookies::Error> {
  static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
                                   atom::api::Cookies::Error val) {
    if (val == atom::api::Cookies::SUCCESS)
      return v8::Null(isolate);
    else
      return v8::Exception::Error(StringToV8(isolate, "Setting cookie failed"));
  }
};

template<>
struct Converter<net::CanonicalCookie> {
  static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
                                   const net::CanonicalCookie& val) {
    mate::Dictionary dict(isolate, v8::Object::New(isolate));
    dict.Set("name", val.Name());
    dict.Set("value", val.Value());
    dict.Set("domain", val.Domain());
    dict.Set("hostOnly", net::cookie_util::DomainIsHostOnly(val.Domain()));
    dict.Set("path", val.Path());
    dict.Set("secure", val.IsSecure());
    dict.Set("httpOnly", val.IsHttpOnly());
    dict.Set("session", !val.IsPersistent());
    if (val.IsPersistent())
      dict.Set("expirationDate", val.ExpiryDate().ToDoubleT());
    return dict.GetHandle();
  }
};

}  // namespace mate

namespace atom {

namespace api {

namespace {

// Returns whether |domain| matches |filter|.
bool MatchesDomain(std::string filter, const std::string& domain) {
  // Add a leading '.' character to the filter domain if it doesn't exist.
  if (net::cookie_util::DomainIsHostOnly(filter))
    filter.insert(0, ".");

  std::string sub_domain(domain);
  // Strip any leading '.' character from the input cookie domain.
  if (!net::cookie_util::DomainIsHostOnly(sub_domain))
    sub_domain = sub_domain.substr(1);

  // Now check whether the domain argument is a subdomain of the filter domain.
  for (sub_domain.insert(0, "."); sub_domain.length() >= filter.length();) {
    if (sub_domain == filter)
      return true;
    const size_t next_dot = sub_domain.find('.', 1);  // Skip over leading dot.
    sub_domain.erase(0, next_dot);
  }
  return false;
}

// Returns whether |cookie| matches |filter|.
bool MatchesCookie(const base::DictionaryValue* filter,
                   const net::CanonicalCookie& cookie) {
  std::string str;
  bool b;
  if (filter->GetString("name", &str) && str != cookie.Name())
    return false;
  if (filter->GetString("path", &str) && str != cookie.Path())
    return false;
  if (filter->GetString("domain", &str) && !MatchesDomain(str, cookie.Domain()))
    return false;
  if (filter->GetBoolean("secure", &b) && b != cookie.IsSecure())
    return false;
  if (filter->GetBoolean("session", &b) && b != !cookie.IsPersistent())
    return false;
  return true;
}

// Helper to returns the CookieStore.
inline net::CookieStore* GetCookieStore(
    scoped_refptr<net::URLRequestContextGetter> getter) {
  return getter->GetURLRequestContext()->cookie_store();
}

// Run |callback| on UI thread.
void RunCallbackInUI(const base::Closure& callback) {
  BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, callback);
}

// Remove cookies from |list| not matching |filter|, and pass it to |callback|.
void FilterCookies(std::unique_ptr<base::DictionaryValue> filter,
                   const Cookies::GetCallback& callback,
                   const net::CookieList& list) {
  net::CookieList result;
  for (const auto& cookie : list) {
    if (MatchesCookie(filter.get(), cookie))
      result.push_back(cookie);
  }
  RunCallbackInUI(base::Bind(callback, Cookies::SUCCESS, result));
}

// Receives cookies matching |filter| in IO thread.
void GetCookiesOnIO(scoped_refptr<net::URLRequestContextGetter> getter,
                    std::unique_ptr<base::DictionaryValue> filter,
                    const Cookies::GetCallback& callback) {
  std::string url;
  filter->GetString("url", &url);

  auto filtered_callback =
      base::Bind(FilterCookies, base::Passed(&filter), callback);

  // Empty url will match all url cookies.
  if (url.empty())
    GetCookieStore(getter)->GetAllCookiesAsync(filtered_callback);
  else
    GetCookieStore(getter)->GetAllCookiesForURLAsync(GURL(url),
        filtered_callback);
}

// Removes cookie with |url| and |name| in IO thread.
void RemoveCookieOnIOThread(scoped_refptr<net::URLRequestContextGetter> getter,
                            const GURL& url, const std::string& name,
                            const base::Closure& callback) {
  GetCookieStore(getter)->DeleteCookieAsync(
      url, name, base::Bind(RunCallbackInUI, callback));
}

// Callback of SetCookie.
void OnSetCookie(const Cookies::SetCallback& callback, bool success) {
  RunCallbackInUI(
      base::Bind(callback, success ? Cookies::SUCCESS : Cookies::FAILED));
}

// Sets cookie with |details| in IO thread.
void SetCookieOnIO(scoped_refptr<net::URLRequestContextGetter> getter,
                   std::unique_ptr<base::DictionaryValue> details,
                   const Cookies::SetCallback& callback) {
  std::string url, name, value, domain, path;
  bool secure = false;
  bool http_only = false;
  double creation_date;
  double expiration_date;
  double last_access_date;
  details->GetString("url", &url);
  details->GetString("name", &name);
  details->GetString("value", &value);
  details->GetString("domain", &domain);
  details->GetString("path", &path);
  details->GetBoolean("secure", &secure);
  details->GetBoolean("httpOnly", &http_only);

  base::Time creation_time;
  if (details->GetDouble("creationDate", &creation_date)) {
    creation_time = (creation_date == 0) ?
        base::Time::UnixEpoch() :
        base::Time::FromDoubleT(creation_date);
  }

  base::Time expiration_time;
  if (details->GetDouble("expirationDate", &expiration_date)) {
    expiration_time = (expiration_date == 0) ?
        base::Time::UnixEpoch() :
        base::Time::FromDoubleT(expiration_date);
  }

  base::Time last_access_time;
  if (details->GetDouble("lastAccessDate", &last_access_date)) {
    last_access_time = (last_access_date == 0) ?
        base::Time::UnixEpoch() :
        base::Time::FromDoubleT(last_access_date);
  }

  GetCookieStore(getter)->SetCookieWithDetailsAsync(
      GURL(url), name, value, domain, path, creation_time,
      expiration_time, last_access_time, secure, http_only,
      net::CookieSameSite::DEFAULT_MODE,
      net::COOKIE_PRIORITY_DEFAULT, base::Bind(OnSetCookie, callback));
}

}  // namespace

Cookies::Cookies(v8::Isolate* isolate,
                 AtomBrowserContext* browser_context)
      : request_context_getter_(browser_context->url_request_context_getter()) {
  Init(isolate);
}

Cookies::~Cookies() {
}

void Cookies::Get(const base::DictionaryValue& filter,
                  const GetCallback& callback) {
  std::unique_ptr<base::DictionaryValue> copied(filter.CreateDeepCopy());
  auto getter = base::RetainedRef(request_context_getter_);
  content::BrowserThread::PostTask(
      BrowserThread::IO, FROM_HERE,
      base::Bind(GetCookiesOnIO, getter, Passed(&copied), callback));
}

void Cookies::Remove(const GURL& url, const std::string& name,
                     const base::Closure& callback) {
  auto getter = base::RetainedRef(request_context_getter_);
  content::BrowserThread::PostTask(
      BrowserThread::IO, FROM_HERE,
      base::Bind(RemoveCookieOnIOThread, getter, url, name, callback));
}

void Cookies::Set(const base::DictionaryValue& details,
                  const SetCallback& callback) {
  std::unique_ptr<base::DictionaryValue> copied(details.CreateDeepCopy());
  auto getter = base::RetainedRef(request_context_getter_);
  content::BrowserThread::PostTask(
      BrowserThread::IO, FROM_HERE,
      base::Bind(SetCookieOnIO, getter, Passed(&copied), callback));
}

// static
mate::Handle<Cookies> Cookies::Create(
    v8::Isolate* isolate,
    AtomBrowserContext* browser_context) {
  return mate::CreateHandle(isolate, new Cookies(isolate, browser_context));
}

// static
void Cookies::BuildPrototype(v8::Isolate* isolate,
                             v8::Local<v8::FunctionTemplate> prototype) {
  prototype->SetClassName(mate::StringToV8(isolate, "Cookies"));
  mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
      .SetMethod("get", &Cookies::Get)
      .SetMethod("remove", &Cookies::Remove)
      .SetMethod("set", &Cookies::Set);
}

}  // namespace api

}  // namespace atom
<|endoftext|>


<commit_before>// copy of avx512bw.cpp, but use masked writes instead of explicit bit-or operations

#include <cstdint>
#include <immintrin.h>

void jpeg_zigzag_avx512bw_masks(const uint8_t* in, uint8_t* out) {

    const __m512i v = _mm512_loadu_si512((const __m512i*)in);

    // populate lanes -- each lane represents pair of output rows
    const __m512i A = _mm512_permutexvar_epi32(
                      _mm512_setr_epi32(0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3), v);
    const __m512i B = _mm512_permutexvar_epi32(
                      _mm512_setr_epi32(4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7), v);
    const __m512i C = _mm512_permutexvar_epi32(
                      _mm512_setr_epi32(8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11), v);
    const __m512i D = _mm512_permutexvar_epi32(
                      _mm512_setr_epi32(12, 13, 14, 15, 12, 13, 14, 15, 12, 13, 14, 15, 12, 13, 14, 15), v);

    // perform shuffling within lanes
    static const int8_t shuffle_A[64] __attribute__((aligned(64))) = {
         0,  1,  8, -1,  9,  2,  3, 10, -1, -1, -1, -1, -1, 11,  4,  5,
        12, -1, -1, -1, -1, -1, -1, -1, -1, -1, 13,  6,  7, 14, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 15, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
    };

    static const int8_t shuffle_B[64] __attribute__((aligned(64))) = {
        -1, -1, -1,  0, -1, -1, -1, -1,  1,  8, -1,  9,  2, -1, -1, -1,
        -1,  3, 10, -1, -1, -1, -1, -1, 11,  4, -1, -1, -1, -1,  5, 12,
        -1, -1, -1, -1, -1, -1, -1, -1, 13,  6, -1,  7, 14, -1, -1, -1,
        -1, -1, -1, -1, -1, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
    };

    static const int8_t shuffle_C[64] __attribute__((aligned(64))) = {
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,  0, -1, -1, -1, -1, -1,
        -1, -1, -1,  1,  8, -1,  9,  2, -1, -1, -1, -1, -1, -1, -1, -1,
         3, 10, -1, -1, -1, -1, 11,  4, -1, -1, -1, -1, -1,  5, 12, -1,
        -1, -1, -1, 13,  6, -1,  7, 14, -1, -1, -1, -1, 15, -1, -1, -1
    };

    static const int8_t shuffle_D[64] __attribute__((aligned(64))) = {
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1,  0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1,  1,  8,  9,  2, -1, -1, -1, -1, -1, -1, -1, -1, -1,  3,
        10, 11,  4, -1, -1, -1, -1, -1,  5, 12, 13,  6, -1,  7, 14, 15
    };

    __m512i result = _mm512_shuffle_epi8(A, _mm512_load_si512((const __m512i*)shuffle_A));
    result = _mm512_mask_shuffle_epi8(result, 0x00201b00c3061b08lu,
                                      B, _mm512_load_si512((const __m512i*)shuffle_B));
    result = _mm512_mask_shuffle_epi8(result, 0x10d860c300d80400lu,
                                      C, _mm512_load_si512((const __m512i*)shuffle_C));
    result = _mm512_mask_shuffle_epi8(result, 0xef07803c00200000lu,
                                      D, _mm512_load_si512((const __m512i*)shuffle_D));

    _mm512_storeu_si512((__m512i*)out, result);
}
<commit_msg>AVX512 masked: use the same broadcasting code<commit_after>// copy of avx512bw.cpp, but use masked writes instead of explicit bit-or operations

#include <cstdint>
#include <immintrin.h>

void jpeg_zigzag_avx512bw_masks(const uint8_t* in, uint8_t* out) {

    // populate lanes -- each lane represents pair of output rows
    const __m512i A = _mm512_broadcast_i32x4(_mm_loadu_si128((const __m128i*)(in + 0 * 16)));
    const __m512i B = _mm512_broadcast_i32x4(_mm_loadu_si128((const __m128i*)(in + 1 * 16)));
    const __m512i C = _mm512_broadcast_i32x4(_mm_loadu_si128((const __m128i*)(in + 2 * 16)));
    const __m512i D = _mm512_broadcast_i32x4(_mm_loadu_si128((const __m128i*)(in + 3 * 16)));

    // perform shuffling within lanes
    static const int8_t shuffle_A[64] __attribute__((aligned(64))) = {
         0,  1,  8, -1,  9,  2,  3, 10, -1, -1, -1, -1, -1, 11,  4,  5,
        12, -1, -1, -1, -1, -1, -1, -1, -1, -1, 13,  6,  7, 14, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 15, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
    };

    static const int8_t shuffle_B[64] __attribute__((aligned(64))) = {
        -1, -1, -1,  0, -1, -1, -1, -1,  1,  8, -1,  9,  2, -1, -1, -1,
        -1,  3, 10, -1, -1, -1, -1, -1, 11,  4, -1, -1, -1, -1,  5, 12,
        -1, -1, -1, -1, -1, -1, -1, -1, 13,  6, -1,  7, 14, -1, -1, -1,
        -1, -1, -1, -1, -1, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
    };

    static const int8_t shuffle_C[64] __attribute__((aligned(64))) = {
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,  0, -1, -1, -1, -1, -1,
        -1, -1, -1,  1,  8, -1,  9,  2, -1, -1, -1, -1, -1, -1, -1, -1,
         3, 10, -1, -1, -1, -1, 11,  4, -1, -1, -1, -1, -1,  5, 12, -1,
        -1, -1, -1, 13,  6, -1,  7, 14, -1, -1, -1, -1, 15, -1, -1, -1
    };

    static const int8_t shuffle_D[64] __attribute__((aligned(64))) = {
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1,  0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1,  1,  8,  9,  2, -1, -1, -1, -1, -1, -1, -1, -1, -1,  3,
        10, 11,  4, -1, -1, -1, -1, -1,  5, 12, 13,  6, -1,  7, 14, 15
    };

    __m512i result = _mm512_shuffle_epi8(A, _mm512_load_si512((const __m512i*)shuffle_A));
    result = _mm512_mask_shuffle_epi8(result, 0x00201b00c3061b08lu,
                                      B, _mm512_load_si512((const __m512i*)shuffle_B));
    result = _mm512_mask_shuffle_epi8(result, 0x10d860c300d80400lu,
                                      C, _mm512_load_si512((const __m512i*)shuffle_C));
    result = _mm512_mask_shuffle_epi8(result, 0xef07803c00200000lu,
                                      D, _mm512_load_si512((const __m512i*)shuffle_D));

    _mm512_storeu_si512((__m512i*)out, result);
}
<|endoftext|>


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

#include <windows.h>

#include "base/gfx/platform_canvas_win.h"
#include "base/gfx/platform_device_win.h"
#include "testing/gtest/include/gtest/gtest.h"

#include "SkColor.h"

namespace gfx {

namespace {

// Return true if the canvas is filled to canvas_color,
// and contains a single rectangle filled to rect_color.
bool VerifyRect(const PlatformCanvasWin& canvas,
                uint32_t canvas_color, uint32_t rect_color,
                int x, int y, int w, int h) {
  PlatformDeviceWin& device = canvas.getTopPlatformDevice();
  const SkBitmap& bitmap = device.accessBitmap(false);
  SkAutoLockPixels lock(bitmap);

  for (int cur_y = 0; cur_y < bitmap.height(); cur_y++) {
    for (int cur_x = 0; cur_x < bitmap.width(); cur_x++) {
      if (cur_x >= x && cur_x < x + w &&
          cur_y >= y && cur_y < y + h) {
        // Inside the square should be rect_color
        if (*bitmap.getAddr32(cur_x, cur_y) != rect_color)
          return false;
      } else {
        // Outside the square should be canvas_color
        if (*bitmap.getAddr32(cur_x, cur_y) != canvas_color)
          return false;
      }
    }
  }
  return true;
}

// Checks whether there is a white canvas with a black square at the given
// location in pixels (not in the canvas coordinate system).
// TODO(ericroman): rename Square to Rect
bool VerifyBlackSquare(const PlatformCanvasWin& canvas, int x, int y, int w, int h) {
  return VerifyRect(canvas, SK_ColorWHITE, SK_ColorBLACK, x, y, w, h);
}

// Check that every pixel in the canvas is a single color.
bool VerifyCanvasColor(const PlatformCanvasWin& canvas, uint32_t canvas_color) {
  return VerifyRect(canvas, canvas_color, 0, 0, 0, 0, 0);
}

void DrawGDIRect(PlatformCanvasWin& canvas, int x, int y, int w, int h) {
  HDC dc = canvas.beginPlatformPaint();

  RECT inner_rc;
  inner_rc.left = x;
  inner_rc.top = y;
  inner_rc.right = x + w;
  inner_rc.bottom = y + h;
  FillRect(dc, &inner_rc, reinterpret_cast<HBRUSH>(GetStockObject(BLACK_BRUSH)));

  canvas.endPlatformPaint();
}

// Clips the contents of the canvas to the given rectangle. This will be
// intersected with any existing clip.
void AddClip(PlatformCanvasWin& canvas, int x, int y, int w, int h) {
  SkRect rect;
  rect.set(SkIntToScalar(x), SkIntToScalar(y),
           SkIntToScalar(x + w), SkIntToScalar(y + h));
  canvas.clipRect(rect);
}

class LayerSaver {
 public:
  LayerSaver(PlatformCanvasWin& canvas, int x, int y, int w, int h)
      : canvas_(canvas),
        x_(x),
        y_(y),
        w_(w),
        h_(h) {
    SkRect bounds;
    bounds.set(SkIntToScalar(x_), SkIntToScalar(y_),
               SkIntToScalar(right()), SkIntToScalar(bottom()));
    canvas_.saveLayer(&bounds, NULL);
  }

  ~LayerSaver() {
    canvas_.getTopPlatformDevice().fixupAlphaBeforeCompositing();
    canvas_.restore();
  }

  int x() const { return x_; }
  int y() const { return y_; }
  int w() const { return w_; }
  int h() const { return h_; }

  // Returns the EXCLUSIVE far bounds of the layer.
  int right() const { return x_ + w_; }
  int bottom() const { return y_ + h_; }

 private:
  PlatformCanvasWin& canvas_;
  int x_, y_, w_, h_;
};

// Size used for making layers in many of the below tests.
const int kLayerX = 2;
const int kLayerY = 3;
const int kLayerW = 9;
const int kLayerH = 7;

// Size used by some tests to draw a rectangle inside the layer.
const int kInnerX = 4;
const int kInnerY = 5;
const int kInnerW = 2;
const int kInnerH = 3;

}

// This just checks that our checking code is working properly, it just uses
// regular skia primitives.
TEST(PlatformCanvasWin, SkLayer) {
  // Create the canvas initialized to opaque white.
  PlatformCanvasWin canvas(16, 16, true);
  canvas.drawColor(SK_ColorWHITE);

  // Make a layer and fill it completely to make sure that the bounds are
  // correct.
  {
    LayerSaver layer(canvas, kLayerX, kLayerY, kLayerW, kLayerH);
    canvas.drawColor(SK_ColorBLACK);
  }
  EXPECT_TRUE(VerifyBlackSquare(canvas, kLayerX, kLayerY, kLayerW, kLayerH));
}

// Test the GDI clipping.
TEST(PlatformCanvasWin, GDIClipRegion) {
  // Initialize a white canvas
  PlatformCanvasWin canvas(16, 16, true);
  canvas.drawColor(SK_ColorWHITE);
  EXPECT_TRUE(VerifyCanvasColor(canvas, SK_ColorWHITE));

  // Test that initially the canvas has no clip region, by filling it
  // with a black rectangle.
  // Note: Don't use LayerSaver, since internally it sets a clip region.
  DrawGDIRect(canvas, 0, 0, 16, 16);
  canvas.getTopPlatformDevice().fixupAlphaBeforeCompositing();
  EXPECT_TRUE(VerifyCanvasColor(canvas, SK_ColorBLACK));

  // Test that intersecting disjoint clip rectangles sets an empty clip region
  canvas.drawColor(SK_ColorWHITE);
  EXPECT_TRUE(VerifyCanvasColor(canvas, SK_ColorWHITE));
  {
    LayerSaver layer(canvas, 0, 0, 16, 16);
    AddClip(canvas, 2, 3, 4, 5);
    AddClip(canvas, 4, 9, 10, 10);
    DrawGDIRect(canvas, 0, 0, 16, 16);
  }
  EXPECT_TRUE(VerifyCanvasColor(canvas, SK_ColorWHITE));
}

// Test the layers get filled properly by GDI.
TEST(PlatformCanvasWin, GDILayer) {
  // Create the canvas initialized to opaque white.
  PlatformCanvasWin canvas(16, 16, true);

  // Make a layer and fill it completely to make sure that the bounds are
  // correct.
  canvas.drawColor(SK_ColorWHITE);
  {
    LayerSaver layer(canvas, kLayerX, kLayerY, kLayerW, kLayerH);
    DrawGDIRect(canvas, 0, 0, 100, 100);
  }
  EXPECT_TRUE(VerifyBlackSquare(canvas, kLayerX, kLayerY, kLayerW, kLayerH));

  // Make a layer and fill it partially to make sure the translation is correct.
  canvas.drawColor(SK_ColorWHITE);
  {
    LayerSaver layer(canvas, kLayerX, kLayerY, kLayerW, kLayerH);
    DrawGDIRect(canvas, kInnerX, kInnerY, kInnerW, kInnerH);
  }
  EXPECT_TRUE(VerifyBlackSquare(canvas, kInnerX, kInnerY, kInnerW, kInnerH));

  // Add a clip on the layer and fill to make sure clip is correct.
  canvas.drawColor(SK_ColorWHITE);
  {
    LayerSaver layer(canvas, kLayerX, kLayerY, kLayerW, kLayerH);
    canvas.save();
    AddClip(canvas, kInnerX, kInnerY, kInnerW, kInnerH);
    DrawGDIRect(canvas, 0, 0, 100, 100);
    canvas.restore();
  }
  EXPECT_TRUE(VerifyBlackSquare(canvas, kInnerX, kInnerY, kInnerW, kInnerH));

  // Add a clip and then make the layer to make sure the clip is correct.
  canvas.drawColor(SK_ColorWHITE);
  canvas.save();
  AddClip(canvas, kInnerX, kInnerY, kInnerW, kInnerH);
  {
    LayerSaver layer(canvas, kLayerX, kLayerY, kLayerW, kLayerH);
    DrawGDIRect(canvas, 0, 0, 100, 100);
  }
  canvas.restore();
  EXPECT_TRUE(VerifyBlackSquare(canvas, kInnerX, kInnerY, kInnerW, kInnerH));
}

// Test that translation + make layer works properly.
TEST(PlatformCanvasWin, GDITranslateLayer) {
  // Create the canvas initialized to opaque white.
  PlatformCanvasWin canvas(16, 16, true);

  // Make a layer and fill it completely to make sure that the bounds are
  // correct.
  canvas.drawColor(SK_ColorWHITE);
  canvas.save();
  canvas.translate(1, 1);
  {
    LayerSaver layer(canvas, kLayerX, kLayerY, kLayerW, kLayerH);
    DrawGDIRect(canvas, 0, 0, 100, 100);
  }
  canvas.restore();
  EXPECT_TRUE(VerifyBlackSquare(canvas, kLayerX + 1, kLayerY + 1,
                                kLayerW, kLayerH));

  // Translate then make the layer.
  canvas.drawColor(SK_ColorWHITE);
  canvas.save();
  canvas.translate(1, 1);
  {
    LayerSaver layer(canvas, kLayerX, kLayerY, kLayerW, kLayerH);
    DrawGDIRect(canvas, kInnerX, kInnerY, kInnerW, kInnerH);
  }
  canvas.restore();
  EXPECT_TRUE(VerifyBlackSquare(canvas, kInnerX + 1, kInnerY + 1,
                                kInnerW, kInnerH));

  // Make the layer then translate.
  canvas.drawColor(SK_ColorWHITE);
  canvas.save();
  {
    LayerSaver layer(canvas, kLayerX, kLayerY, kLayerW, kLayerH);
    canvas.translate(1, 1);
    DrawGDIRect(canvas, kInnerX, kInnerY, kInnerW, kInnerH);
  }
  canvas.restore();
  EXPECT_TRUE(VerifyBlackSquare(canvas, kInnerX + 1, kInnerY + 1,
                                kInnerW, kInnerH));

  // Translate both before and after, and have a clip.
  canvas.drawColor(SK_ColorWHITE);
  canvas.save();
  canvas.translate(1, 1);
  {
    LayerSaver layer(canvas, kLayerX, kLayerY, kLayerW, kLayerH);
    canvas.translate(1, 1);
    AddClip(canvas, kInnerX, kInnerY, kInnerW, kInnerH);
    DrawGDIRect(canvas, 0, 0, 100, 100);
  }
  canvas.restore();
  EXPECT_TRUE(VerifyBlackSquare(canvas, kInnerX + 2, kInnerY + 2,
                                kInnerW, kInnerH));
}

}  // namespace

<commit_msg>Update file that got committed under the wrong name, causing the change to get missed. Review URL: http://codereview.chromium.org/1862<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "build/build_config.h"

#if defined(OS_WIN)
#include <windows.h>
#else
#include <unistd.h>
#endif

#include "base/gfx/platform_canvas.h"
#include "base/gfx/platform_device.h"
#include "testing/gtest/include/gtest/gtest.h"

#include "SkColor.h"

namespace gfx {

namespace {

// Return true if the canvas is filled to canvas_color,
// and contains a single rectangle filled to rect_color.
bool VerifyRect(const PlatformCanvas& canvas,
                uint32_t canvas_color, uint32_t rect_color,
                int x, int y, int w, int h) {
  PlatformDevice& device = canvas.getTopPlatformDevice();
  const SkBitmap& bitmap = device.accessBitmap(false);
  SkAutoLockPixels lock(bitmap);

  for (int cur_y = 0; cur_y < bitmap.height(); cur_y++) {
    for (int cur_x = 0; cur_x < bitmap.width(); cur_x++) {
      if (cur_x >= x && cur_x < x + w &&
          cur_y >= y && cur_y < y + h) {
        // Inside the square should be rect_color
        if (*bitmap.getAddr32(cur_x, cur_y) != rect_color)
          return false;
      } else {
        // Outside the square should be canvas_color
        if (*bitmap.getAddr32(cur_x, cur_y) != canvas_color)
          return false;
      }
    }
  }
  return true;
}

// Checks whether there is a white canvas with a black square at the given
// location in pixels (not in the canvas coordinate system).
// TODO(ericroman): rename Square to Rect
bool VerifyBlackSquare(const PlatformCanvas& canvas, int x, int y, int w, int h) {
  return VerifyRect(canvas, SK_ColorWHITE, SK_ColorBLACK, x, y, w, h);
}

// Check that every pixel in the canvas is a single color.
bool VerifyCanvasColor(const PlatformCanvas& canvas, uint32_t canvas_color) {
  return VerifyRect(canvas, canvas_color, 0, 0, 0, 0, 0);
}

#if defined(OS_WIN)
void DrawNativeRect(const PlatformCanvas& canvas, int x, int y, int w, int h) {
  HDC dc = canvas.beginPlatformPaint();

  RECT inner_rc;
  inner_rc.left = x;
  inner_rc.top = y;
  inner_rc.right = x + w;
  inner_rc.bottom = y + h;
  FillRect(dc, &inner_rc, reinterpret_cast<HBRUSH>(GetStockObject(BLACK_BRUSH)));

  canvas.endPlatformPaint();
}
#elif defined(OS_MACOSX)
void DrawNativeRect(const PlatformCanvas& canvas, int x, int y, int w, int h) {
  CGContextRef context = canvas.beginPlatformPaint();

  CGRect inner_rc = CGRectMake(x, y, w, h);
  CGFloat black[] = { 0.0, 0.0, 0.0, 1.0 };  // RGBA opaque black
  CGContextSetFillColor(context, black);
  CGContextFillRect(context, inner_rc);

  canvas.endPlatformPaint();
}
#else
void DrawNativeRect(const PlatformCanvas& canvas, int x, int y, int w, int h) {
  NOTIMPLEMENTED();
}
#endif

// Clips the contents of the canvas to the given rectangle. This will be
// intersected with any existing clip.
void AddClip(const PlatformCanvas& canvas, int x, int y, int w, int h) {
  SkRect rect;
  rect.set(SkIntToScalar(x), SkIntToScalar(y),
           SkIntToScalar(x + w), SkIntToScalar(y + h));
  canvas.clipRect(rect);
}

class LayerSaver {
 public:
  LayerSaver(const PlatformCanvas& canvas, int x, int y, int w, int h)
      : canvas_(canvas),
        x_(x),
        y_(y),
        w_(w),
        h_(h) {
    SkRect bounds;
    bounds.set(SkIntToScalar(x_), SkIntToScalar(y_),
               SkIntToScalar(right()), SkIntToScalar(bottom()));
    canvas_.saveLayer(&bounds, NULL);
  }

  ~LayerSaver() {
    canvas_.getTopPlatformDevice().fixupAlphaBeforeCompositing();
    canvas_.restore();
  }

  int x() const { return x_; }
  int y() const { return y_; }
  int w() const { return w_; }
  int h() const { return h_; }

  // Returns the EXCLUSIVE far bounds of the layer.
  int right() const { return x_ + w_; }
  int bottom() const { return y_ + h_; }

 private:
  const PlatformCanvas& canvas_;
  int x_, y_, w_, h_;
};

// Size used for making layers in many of the below tests.
const int kLayerX = 2;
const int kLayerY = 3;
const int kLayerW = 9;
const int kLayerH = 7;

// Size used by some tests to draw a rectangle inside the layer.
const int kInnerX = 4;
const int kInnerY = 5;
const int kInnerW = 2;
const int kInnerH = 3;

}

// This just checks that our checking code is working properly, it just uses
// regular skia primitives.
TEST(PlatformCanvas, SkLayer) {
  // Create the canvas initialized to opaque white.
  PlatformCanvas canvas(16, 16, true);
  canvas.drawColor(SK_ColorWHITE);

  // Make a layer and fill it completely to make sure that the bounds are
  // correct.
  {
    LayerSaver layer(canvas, kLayerX, kLayerY, kLayerW, kLayerH);
    canvas.drawColor(SK_ColorBLACK);
  }
  EXPECT_TRUE(VerifyBlackSquare(canvas, kLayerX, kLayerY, kLayerW, kLayerH));
}

// Test native clipping.
TEST(PlatformCanvas, ClipRegion) {
  // Initialize a white canvas
  PlatformCanvas canvas(16, 16, true);
  canvas.drawColor(SK_ColorWHITE);
  EXPECT_TRUE(VerifyCanvasColor(canvas, SK_ColorWHITE));

  // Test that initially the canvas has no clip region, by filling it
  // with a black rectangle.
  // Note: Don't use LayerSaver, since internally it sets a clip region.
  DrawNativeRect(canvas, 0, 0, 16, 16);
  canvas.getTopPlatformDevice().fixupAlphaBeforeCompositing();
  EXPECT_TRUE(VerifyCanvasColor(canvas, SK_ColorBLACK));

  // Test that intersecting disjoint clip rectangles sets an empty clip region
  canvas.drawColor(SK_ColorWHITE);
  EXPECT_TRUE(VerifyCanvasColor(canvas, SK_ColorWHITE));
  {
    LayerSaver layer(canvas, 0, 0, 16, 16);
    AddClip(canvas, 2, 3, 4, 5);
    AddClip(canvas, 4, 9, 10, 10);
    DrawNativeRect(canvas, 0, 0, 16, 16);
  }
  EXPECT_TRUE(VerifyCanvasColor(canvas, SK_ColorWHITE));
}

// Test the layers get filled properly by native rendering.
TEST(PlatformCanvas, FillLayer) {
  // Create the canvas initialized to opaque white.
  PlatformCanvas canvas(16, 16, true);

  // Make a layer and fill it completely to make sure that the bounds are
  // correct.
  canvas.drawColor(SK_ColorWHITE);
  {
    LayerSaver layer(canvas, kLayerX, kLayerY, kLayerW, kLayerH);
    DrawNativeRect(canvas, 0, 0, 100, 100);
  }
  EXPECT_TRUE(VerifyBlackSquare(canvas, kLayerX, kLayerY, kLayerW, kLayerH));

  // Make a layer and fill it partially to make sure the translation is correct.
  canvas.drawColor(SK_ColorWHITE);
  {
    LayerSaver layer(canvas, kLayerX, kLayerY, kLayerW, kLayerH);
    DrawNativeRect(canvas, kInnerX, kInnerY, kInnerW, kInnerH);
  }
  EXPECT_TRUE(VerifyBlackSquare(canvas, kInnerX, kInnerY, kInnerW, kInnerH));

  // Add a clip on the layer and fill to make sure clip is correct.
  canvas.drawColor(SK_ColorWHITE);
  {
    LayerSaver layer(canvas, kLayerX, kLayerY, kLayerW, kLayerH);
    canvas.save();
    AddClip(canvas, kInnerX, kInnerY, kInnerW, kInnerH);
    DrawNativeRect(canvas, 0, 0, 100, 100);
    canvas.restore();
  }
  EXPECT_TRUE(VerifyBlackSquare(canvas, kInnerX, kInnerY, kInnerW, kInnerH));

  // Add a clip and then make the layer to make sure the clip is correct.
  canvas.drawColor(SK_ColorWHITE);
  canvas.save();
  AddClip(canvas, kInnerX, kInnerY, kInnerW, kInnerH);
  {
    LayerSaver layer(canvas, kLayerX, kLayerY, kLayerW, kLayerH);
    DrawNativeRect(canvas, 0, 0, 100, 100);
  }
  canvas.restore();
  EXPECT_TRUE(VerifyBlackSquare(canvas, kInnerX, kInnerY, kInnerW, kInnerH));
}

// Test that translation + make layer works properly.
TEST(PlatformCanvas, TranslateLayer) {
  // Create the canvas initialized to opaque white.
  PlatformCanvas canvas(16, 16, true);

  // Make a layer and fill it completely to make sure that the bounds are
  // correct.
  canvas.drawColor(SK_ColorWHITE);
  canvas.save();
  canvas.translate(1, 1);
  {
    LayerSaver layer(canvas, kLayerX, kLayerY, kLayerW, kLayerH);
    DrawNativeRect(canvas, 0, 0, 100, 100);
  }
  canvas.restore();
  EXPECT_TRUE(VerifyBlackSquare(canvas, kLayerX + 1, kLayerY + 1,
                                kLayerW, kLayerH));

  // Translate then make the layer.
  canvas.drawColor(SK_ColorWHITE);
  canvas.save();
  canvas.translate(1, 1);
  {
    LayerSaver layer(canvas, kLayerX, kLayerY, kLayerW, kLayerH);
    DrawNativeRect(canvas, kInnerX, kInnerY, kInnerW, kInnerH);
  }
  canvas.restore();
  EXPECT_TRUE(VerifyBlackSquare(canvas, kInnerX + 1, kInnerY + 1,
                                kInnerW, kInnerH));

  // Make the layer then translate.
  canvas.drawColor(SK_ColorWHITE);
  canvas.save();
  {
    LayerSaver layer(canvas, kLayerX, kLayerY, kLayerW, kLayerH);
    canvas.translate(1, 1);
    DrawNativeRect(canvas, kInnerX, kInnerY, kInnerW, kInnerH);
  }
  canvas.restore();
  EXPECT_TRUE(VerifyBlackSquare(canvas, kInnerX + 1, kInnerY + 1,
                                kInnerW, kInnerH));

  // Translate both before and after, and have a clip.
  canvas.drawColor(SK_ColorWHITE);
  canvas.save();
  canvas.translate(1, 1);
  {
    LayerSaver layer(canvas, kLayerX, kLayerY, kLayerW, kLayerH);
    canvas.translate(1, 1);
    AddClip(canvas, kInnerX, kInnerY, kInnerW, kInnerH);
    DrawNativeRect(canvas, 0, 0, 100, 100);
  }
  canvas.restore();
  EXPECT_TRUE(VerifyBlackSquare(canvas, kInnerX + 2, kInnerY + 2,
                                kInnerW, kInnerH));
}

}  // namespace

<|endoftext|>


<commit_before>/*******************************************************************************
 * benchmarks/word_count/word_count.cpp
 *
 * Runner program for WordCount example. See thrill/examples/word_count.hpp for
 * the source to the example.
 *
 * Part of Project Thrill.
 *
 * Copyright (C) 2015 Timo Bingmann <tb@panthema.net>
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#include <thrill/api/dia.hpp>
#include <thrill/thrill.hpp>
#include <thrill/common/cmdline_parser.hpp>
#include <thrill/common/logger.hpp>

using WordCountPair = std::pair<std::string, size_t>;
using namespace thrill; // NOLINT

int main(int argc, char* argv[]) {

    common::CmdlineParser clp;

    clp.SetVerboseProcess(false);

    std::string input;
    clp.AddParamString("input", input,
                       "input file pattern");

    std::string output;
    clp.AddParamString("output", output,
                       "output file pattern");

    if (!clp.Process(argc, argv)) {
        return -1;
    }

    clp.PrintResult();

    auto start_func =
        [&input, &output](api::Context& ctx) {
		auto input_dia = ReadLines(ctx, input);

		std::string word;
		word.reserve(1024);
		auto word_pairs = input_dia.template FlatMap<WordCountPair>(
        [&word](const std::string& line, auto emit) -> void {
            /* map lambda: emit each word */
			word.clear();
			for (auto it = line.begin(); it != line.end(); it++) {
				if(*it == ' ') {
					emit(WordCountPair(word, 1));
					word.clear();
				} else {
					if(*it != ',' && *it != '.') {
						word.push_back(*it);
					}
				}
			}
			emit(WordCountPair(word, 1));
        }).ReduceBy(
        [](const WordCountPair& in) -> std::string {
            /* reduction key: the word string */
            return in.first;
        },
        [](const WordCountPair& a, const WordCountPair& b) -> WordCountPair {
            /* associative reduction operator: add counters */
            return WordCountPair(a.first, a.second + b.second);
        });

		word_pairs.Sort([](const WordCountPair& wc1, const WordCountPair& wc2) {
				return wc1 < wc2;
			}).Map(
        [](const WordCountPair& wc) {
			return wc.first + ": " + std::to_string(wc.second);
        }).WriteLinesMany(output);
        };

    return api::Run(start_func);
}

/******************************************************************************/
<commit_msg>sort by word count and not by lexicographical order<commit_after>/*******************************************************************************
 * benchmarks/word_count/word_count.cpp
 *
 * Runner program for WordCount example. See thrill/examples/word_count.hpp for
 * the source to the example.
 *
 * Part of Project Thrill.
 *
 * Copyright (C) 2015 Timo Bingmann <tb@panthema.net>
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#include <thrill/api/dia.hpp>
#include <thrill/thrill.hpp>
#include <thrill/common/cmdline_parser.hpp>
#include <thrill/common/logger.hpp>

using WordCountPair = std::pair<std::string, size_t>;
using namespace thrill; // NOLINT

int main(int argc, char* argv[]) {

    common::CmdlineParser clp;

    clp.SetVerboseProcess(false);

    std::string input;
    clp.AddParamString("input", input,
                       "input file pattern");

    std::string output;
    clp.AddParamString("output", output,
                       "output file pattern");

    if (!clp.Process(argc, argv)) {
        return -1;
    }

    clp.PrintResult();

    auto start_func =
        [&input, &output](api::Context& ctx) {
		auto input_dia = ReadLines(ctx, input);

		std::string word;
		word.reserve(1024);
		auto word_pairs = input_dia.template FlatMap<WordCountPair>(
        [&word](const std::string& line, auto emit) -> void {
            /* map lambda: emit each word */
			word.clear();
			for (auto it = line.begin(); it != line.end(); it++) {
				if(*it == ' ') {
					emit(WordCountPair(word, 1));
					word.clear();
				} else {
					if(*it != ',' && *it != '.') {
						word.push_back(*it);
					}
				}
			}
			emit(WordCountPair(word, 1));
        }).ReduceBy(
        [](const WordCountPair& in) -> std::string {
            /* reduction key: the word string */
            return in.first;
        },
        [](const WordCountPair& a, const WordCountPair& b) -> WordCountPair {
            /* associative reduction operator: add counters */
            return WordCountPair(a.first, a.second + b.second);
        });

		word_pairs.Sort([](const WordCountPair& wc1, const WordCountPair& wc2) {
				return wc1.second < wc2.second;
			}).Map(
        [](const WordCountPair& wc) {
			return wc.first + ": " + std::to_string(wc.second);
        }).WriteLinesMany(output);
        };

    return api::Run(start_func);
}

/******************************************************************************/
<|endoftext|>