<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon, Dane Springmeyer
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id: mapnik_layer.cc 17 2005-03-08 23:58:43Z pavlenko $

// boost
#include <boost/python.hpp>
#include <boost/python/detail/api_placeholder.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>

// mapnik
#include <mapnik/layer.hpp>
#include <mapnik/datasource.hpp>

using mapnik::Layer;
using mapnik::parameters;
using mapnik::datasource;

struct layer_pickle_suite : boost::python::pickle_suite
{
   static boost::python::tuple
   getinitargs(const Layer& l)
   {
      return boost::python::make_tuple(l.name(),l.srs());
   }

   static  boost::python::tuple
   getstate(const Layer& l)
   {
        boost::python::list s;
        std::vector<std::string> const& style_names = l.styles();
        for (unsigned i = 0; i < style_names.size(); ++i)
        {
            s.append(style_names[i]);
        }
        return boost::python::make_tuple(l.abstract(),l.title(),l.clear_label_cache(),l.getMinZoom(),l.getMaxZoom(),l.isQueryable(),l.datasource(),s);
   }

   static void
   setstate (Layer& l, boost::python::tuple state)
   {
        using namespace boost::python;
        if (len(state) != 8)
        {
         PyErr_SetObject(PyExc_ValueError,
                         ("expected 8-item tuple in call to __setstate__; got %s"
                          % state).ptr()
            );
         throw_error_already_set();
        }

        if (state[0])
        {
            l.set_abstract(extract<std::string>(state[0]));
        }

        if (state[1])
        {
            l.set_title(extract<std::string>(state[1]));
        }

        if (state[2])
        {
            l.set_clear_label_cache(extract<bool>(state[2]));
        }

        if (state[3])
        {
            l.setMinZoom(extract<double>(state[3]));
        }

        if (state[4])
        {
            l.setMaxZoom(extract<double>(state[4]));
        }

        if (state[5])
        {
            l.setQueryable(extract<bool>(state[5]));
        }

        if (state[6])
        {
            boost::shared_ptr<datasource> ds = extract<boost::shared_ptr<datasource> >(state[6]);
            l.set_datasource(ds);
        }

        boost::python::list s = extract<boost::python::list>(state[7]);
        for (int i=0;i<len(s);++i)
        {
           l.add_style(extract<std::string>(s[i]));
        }
   }
};

std::vector<std::string> & (mapnik::Layer::*_styles_)() = &mapnik::Layer::styles;

void export_layer()
{
    using namespace boost::python;
    class_<std::vector<std::string> >("Names")
    	.def(vector_indexing_suite<std::vector<std::string>,true >())
    	;

    class_<Layer>("Layer", "A Mapnik map layer.", init<std::string const&,optional<std::string const&> >(
                "Create a Layer with a named string and, optionally, an srs string either with\n"
                "a Proj.4 epsg code ('+init=epsg:<code>') or with a Proj.4 literal ('+proj=<literal>').\n"
                "If no srs is specified it will default to '+proj=latlong +datum=WGS84'\n"
                "\n"
                "Usage:\n"
                ">>> from mapnik import Layer\n"
                ">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
                ">>> lyr\n"
                "<mapnik._mapnik.Layer object at 0x6a270>"
                ))

        .def_pickle(layer_pickle_suite()
                )

        .def("envelope",&Layer::envelope,
                "Return the geographic envelope/bounding box "
                "of the data in the layer.\n"
                "\n"
                "Usage:\n"
                ">>> from mapnik import Layer\n"
                ">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
                ">>> lyr.envelope()\n"
                "Envelope(-1.0,-1.0,0.0,0.0) # default until a datasource is loaded\n"
                )

        .def("visible", &Layer::isVisible,
                "Return True if this layer's data is active and visible at a given scale.\n"
                "Otherwise returns False.\n"
                "Accepts a scale value as an integer or float input.\n"
                "Will return False if:\n"
                "\tscale >= minzoom - 1e-6\n"
                "\tor:\n"
                "\tscale < maxzoom + 1e-6\n"
                "\n"
                "Usage:\n"
                ">>> from mapnik import Layer\n"
                ">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
                ">>> lyr.visible(1.0/1000000)\n"
                "True\n"
                ">>> lyr.active = False\n"
                ">>> lyr.visible(1.0/1000000)\n"
                "False\n"
                )

        .add_property("abstract",
                make_function(&Layer::abstract,return_value_policy<copy_const_reference>()),
                &Layer::set_abstract,
                "Get/Set the abstract of the layer.\n"
                "\n"
                "Usage:\n"
                ">>> from mapnik import Layer\n"
                ">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
                ">>> lyr.abstract\n"
                "'' # default is en empty string\n"
                ">>> lyr.abstract = 'My Shapefile rendered with Mapnik'\n"
                ">>> lyr.abstract\n"
                "'My Shapefile rendered with Mapnik'\n"
                )

        .add_property("active",
                &Layer::isActive,
                &Layer::setActive,
                "Get/Set whether this layer is active and will be rendered.\n"
                "\n"
                "Usage:\n"
                ">>> from mapnik import Layer\n"
                ">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
                ">>> lyr.active\n"
                "True # Active by default\n"
                ">>> lyr.active = False # set False to disable layer rendering\n"
                ">>> lyr.active\n"
                "False\n"
                )

        .add_property("clear_label_cache",
                &Layer::clear_label_cache,
                &Layer::set_clear_label_cache,
                "Get/Set whether this layer's labels are cached."
                "\n"
                "Usage:\n"
                "TODO"
                )

        .add_property("datasource",
                &Layer::datasource,
                &Layer::set_datasource,
                "The datasource attached to this layer.\n"
                "\n"
                "Usage:\n"
                ">>> from mapnik import Layer, Datasource\n"
                ">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
                ">>> lyr.datasource = Datasource(type='shape',file='world_borders')\n"
                ">>> lyr.datasource\n"
                "<mapnik.Datasource object at 0x65470>\n"
                )

        .add_property("maxzoom",
                &Layer::getMaxZoom,
                &Layer::setMaxZoom,
                "Get/Set the maximum zoom lever of the layer.\n"
                "\n"
                "Usage:\n"
                ">>> from mapnik import Layer\n"
                ">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
                ">>> lyr.maxzoom\n"
                "1.7976931348623157e+308 # default is the numerical maximum\n"
                ">>> lyr.maxzoom = 1.0/1000000\n"
                ">>> lyr.maxzoom\n"
                "9.9999999999999995e-07\n"
                )

        .add_property("minzoom",
                &Layer::getMinZoom,
                &Layer::setMinZoom,
                "Get/Set the minimum zoom lever of the layer.\n"
                "\n"
                "Usage:\n"
                ">>> from mapnik import Layer\n"
                ">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
                ">>> lyr.minzoom # default is 0\n"
                "0.0\n"
                ">>> lyr.minzoom = 1.0/1000000\n"
                ">>> lyr.minzoom\n"
                "9.9999999999999995e-07\n"
                )

        .add_property("name",
                make_function(&Layer::name, return_value_policy<copy_const_reference>()),
                &Layer::set_name,
                "Get/Set the name of the layer.\n"
                "\n"
                "Usage:\n"
                ">>> from mapnik import Layer\n"
                ">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
                ">>> lyr.name\n"
                "'My Layer'\n"
                ">>> lyr.name = 'New Name'\n"
                ">>> lyr.name\n"
                "'New Name'\n"
                )

        .add_property("queryable",
                &Layer::isQueryable,
                &Layer::setQueryable,
                "Get/Set whether this layer is queryable.\n"
                "\n"
                "Usage:\n"
                ">>> from mapnik import Layer\n"
                ">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
                ">>> lyr.queryable\n"
                "False # Not queryable by default\n"
                ">>> lyr.queryable = True\n"
                ">>> lyr.queryable\n"
                "True\n"
                )

        .add_property("srs",
                make_function(&Layer::srs,return_value_policy<copy_const_reference>()),
                &Layer::set_srs,
                "Get/Set the SRS of the layer."
                "\n"
                "Usage:\n"
                ">>> from mapnik import Layer\n"
                ">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
                ">>> lyr.srs\n"
                "'+proj=latlong +datum=WGS84' # The default srs if not initialized with custom srs\n"
                ">>> # set to google mercator with Proj.4 literal\n"
                "... \n"
                ">>> lyr.srs = '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs +over'\n"
                )

        .add_property("styles",
                make_function(_styles_,return_value_policy<reference_existing_object>()),
                "The styles list attached to this layer.\n"
                "\n"
                "Usage:\n"
                ">>> from mapnik import Layer\n"
                ">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
                ">>> lyr.styles\n"
                "<mapnik._mapnik.Names object at 0x6d3e8>\n"
                ">>> len(lyr.styles)\n"
                "0\n # no styles until you append them"
                "lyr.styles.append('My Style') # mapnik uses named styles for flexibility\n"
                ">>> len(lyr.styles)\n"
                "1\n"
                ">>> lyr.styles[0]\n"
                "'My Style'\n"
                )

        .add_property("title",
                make_function(&Layer::title, return_value_policy<copy_const_reference>()),
                &Layer::set_title,
                "Get/Set the title of the layer.\n"
                "\n"
                "Usage:\n"
                ">>> from mapnik import Layer\n"
                ">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
                ">>> lyr.title\n"
                "''\n"
                ">>> lyr.title = 'My first layer'\n"
                ">>> lyr.title\n"
                "'My first layer'\n"
                )

        ;
}
<commit_msg>slight formatting fixes to docstrings in layer class<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon, Dane Springmeyer
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id: mapnik_layer.cc 17 2005-03-08 23:58:43Z pavlenko $

// boost
#include <boost/python.hpp>
#include <boost/python/detail/api_placeholder.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>

// mapnik
#include <mapnik/layer.hpp>
#include <mapnik/datasource.hpp>

using mapnik::Layer;
using mapnik::parameters;
using mapnik::datasource;

struct layer_pickle_suite : boost::python::pickle_suite
{
   static boost::python::tuple
   getinitargs(const Layer& l)
   {
      return boost::python::make_tuple(l.name(),l.srs());
   }

   static  boost::python::tuple
   getstate(const Layer& l)
   {
        boost::python::list s;
        std::vector<std::string> const& style_names = l.styles();
        for (unsigned i = 0; i < style_names.size(); ++i)
        {
            s.append(style_names[i]);
        }
        return boost::python::make_tuple(l.abstract(),l.title(),l.clear_label_cache(),l.getMinZoom(),l.getMaxZoom(),l.isQueryable(),l.datasource(),s);
   }

   static void
   setstate (Layer& l, boost::python::tuple state)
   {
        using namespace boost::python;
        if (len(state) != 8)
        {
         PyErr_SetObject(PyExc_ValueError,
                         ("expected 8-item tuple in call to __setstate__; got %s"
                          % state).ptr()
            );
         throw_error_already_set();
        }

        if (state[0])
        {
            l.set_abstract(extract<std::string>(state[0]));
        }

        if (state[1])
        {
            l.set_title(extract<std::string>(state[1]));
        }

        if (state[2])
        {
            l.set_clear_label_cache(extract<bool>(state[2]));
        }

        if (state[3])
        {
            l.setMinZoom(extract<double>(state[3]));
        }

        if (state[4])
        {
            l.setMaxZoom(extract<double>(state[4]));
        }

        if (state[5])
        {
            l.setQueryable(extract<bool>(state[5]));
        }

        if (state[6])
        {
            boost::shared_ptr<datasource> ds = extract<boost::shared_ptr<datasource> >(state[6]);
            l.set_datasource(ds);
        }

        boost::python::list s = extract<boost::python::list>(state[7]);
        for (int i=0;i<len(s);++i)
        {
           l.add_style(extract<std::string>(s[i]));
        }
   }
};

std::vector<std::string> & (mapnik::Layer::*_styles_)() = &mapnik::Layer::styles;

void export_layer()
{
    using namespace boost::python;
    class_<std::vector<std::string> >("Names")
    	.def(vector_indexing_suite<std::vector<std::string>,true >())
    	;

    class_<Layer>("Layer", "A Mapnik map layer.", init<std::string const&,optional<std::string const&> >(
                "Create a Layer with a named string and, optionally, an srs string.\n"
                "\n"
                "The srs can be either a Proj.4 epsg code ('+init=epsg:<code>') or\n"
                "of a Proj.4 literal ('+proj=<literal>').\n"
                "If no srs is specified it will default to '+proj=latlong +datum=WGS84'\n"
                "\n"
                "Usage:\n"
                ">>> from mapnik import Layer\n"
                ">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
                ">>> lyr\n"
                "<mapnik._mapnik.Layer object at 0x6a270>\n"
                ))

        .def_pickle(layer_pickle_suite())

        .def("envelope",&Layer::envelope,
                "Return the geographic envelope/bounding box."
                "\n"
                "Determined based on the layer datasource.\n"
                "\n"
                "Usage:\n"
                ">>> from mapnik import Layer\n"
                ">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
                ">>> lyr.envelope()\n"
                "Envelope(-1.0,-1.0,0.0,0.0) # default until a datasource is loaded\n"
                )

        .def("visible", &Layer::isVisible,
                "Return True if this layer's data is active and visible at a given scale.\n"
                "\n"
                "Otherwise returns False.\n"
                "Accepts a scale value as an integer or float input.\n"
                "Will return False if:\n"
                "\tscale >= minzoom - 1e-6\n"
                "\tor:\n"
                "\tscale < maxzoom + 1e-6\n"
                "\n"
                "Usage:\n"
                ">>> from mapnik import Layer\n"
                ">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
                ">>> lyr.visible(1.0/1000000)\n"
                "True\n"
                ">>> lyr.active = False\n"
                ">>> lyr.visible(1.0/1000000)\n"
                "False\n"
                )

        .add_property("abstract",
                make_function(&Layer::abstract,return_value_policy<copy_const_reference>()),
                &Layer::set_abstract,
                "Get/Set the abstract of the layer.\n"
                "\n"
                "Usage:\n"
                ">>> from mapnik import Layer\n"
                ">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
                ">>> lyr.abstract\n"
                "'' # default is en empty string\n"
                ">>> lyr.abstract = 'My Shapefile rendered with Mapnik'\n"
                ">>> lyr.abstract\n"
                "'My Shapefile rendered with Mapnik'\n"
                )

        .add_property("active",
                &Layer::isActive,
                &Layer::setActive,
                "Get/Set whether this layer is active and will be rendered.\n"
                "\n"
                "Usage:\n"
                ">>> from mapnik import Layer\n"
                ">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
                ">>> lyr.active\n"
                "True # Active by default\n"
                ">>> lyr.active = False # set False to disable layer rendering\n"
                ">>> lyr.active\n"
                "False\n"
                )

        .add_property("clear_label_cache",
                &Layer::clear_label_cache,
                &Layer::set_clear_label_cache,
                "Get/Set whether this layer's labels are cached.\n"
                "\n"
                "Usage:\n"
                "TODO\n"
                )

        .add_property("datasource",
                &Layer::datasource,
                &Layer::set_datasource,
                "The datasource attached to this layer.\n"
                "\n"
                "Usage:\n"
                ">>> from mapnik import Layer, Datasource\n"
                ">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
                ">>> lyr.datasource = Datasource(type='shape',file='world_borders')\n"
                ">>> lyr.datasource\n"
                "<mapnik.Datasource object at 0x65470>\n"
                )

        .add_property("maxzoom",
                &Layer::getMaxZoom,
                &Layer::setMaxZoom,
                "Get/Set the maximum zoom lever of the layer.\n"
                "\n"
                "Usage:\n"
                ">>> from mapnik import Layer\n"
                ">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
                ">>> lyr.maxzoom\n"
                "1.7976931348623157e+308 # default is the numerical maximum\n"
                ">>> lyr.maxzoom = 1.0/1000000\n"
                ">>> lyr.maxzoom\n"
                "9.9999999999999995e-07\n"
                )

        .add_property("minzoom",
                &Layer::getMinZoom,
                &Layer::setMinZoom,
                "Get/Set the minimum zoom lever of the layer.\n"
                "\n"
                "Usage:\n"
                ">>> from mapnik import Layer\n"
                ">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
                ">>> lyr.minzoom # default is 0\n"
                "0.0\n"
                ">>> lyr.minzoom = 1.0/1000000\n"
                ">>> lyr.minzoom\n"
                "9.9999999999999995e-07\n"
                )

        .add_property("name",
                make_function(&Layer::name, return_value_policy<copy_const_reference>()),
                &Layer::set_name,
                "Get/Set the name of the layer.\n"
                "\n"
                "Usage:\n"
                ">>> from mapnik import Layer\n"
                ">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
                ">>> lyr.name\n"
                "'My Layer'\n"
                ">>> lyr.name = 'New Name'\n"
                ">>> lyr.name\n"
                "'New Name'\n"
                )

        .add_property("queryable",
                &Layer::isQueryable,
                &Layer::setQueryable,
                "Get/Set whether this layer is queryable.\n"
                "\n"
                "Usage:\n"
                ">>> from mapnik import Layer\n"
                ">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
                ">>> lyr.queryable\n"
                "False # Not queryable by default\n"
                ">>> lyr.queryable = True\n"
                ">>> lyr.queryable\n"
                "True\n"
                )

        .add_property("srs",
                make_function(&Layer::srs,return_value_policy<copy_const_reference>()),
                &Layer::set_srs,
                "Get/Set the SRS of the layer.\n"
                "\n"
                "Usage:\n"
                ">>> from mapnik import Layer\n"
                ">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
                ">>> lyr.srs\n"
                "'+proj=latlong +datum=WGS84' # The default srs if not initialized with custom srs\n"
                ">>> # set to google mercator with Proj.4 literal\n"
                "... \n"
                ">>> lyr.srs = '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs +over'\n"
                )

        .add_property("styles",
                make_function(_styles_,return_value_policy<reference_existing_object>()),
                "The styles list attached to this layer.\n"
                "\n"
                "Usage:\n"
                ">>> from mapnik import Layer\n"
                ">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
                ">>> lyr.styles\n"
                "<mapnik._mapnik.Names object at 0x6d3e8>\n"
                ">>> len(lyr.styles)\n"
                "0\n # no styles until you append them\n"
                "lyr.styles.append('My Style') # mapnik uses named styles for flexibility\n"
                ">>> len(lyr.styles)\n"
                "1\n"
                ">>> lyr.styles[0]\n"
                "'My Style'\n"
                )

        .add_property("title",
                make_function(&Layer::title, return_value_policy<copy_const_reference>()),
                &Layer::set_title,
                "Get/Set the title of the layer.\n"
                "\n"
                "Usage:\n"
                ">>> from mapnik import Layer\n"
                ">>> lyr = Layer('My Layer','+proj=latlong +datum=WGS84')\n"
                ">>> lyr.title\n"
                "''\n"
                ">>> lyr.title = 'My first layer'\n"
                ">>> lyr.title\n"
                "'My first layer'\n"
                )

        ;
}
<|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 "chrome/browser/ui/webui/constrained_html_ui.h"

#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/gtk/constrained_window_gtk.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/browser/ui/views/tab_contents/tab_contents_container.h"
#include "chrome/browser/ui/webui/html_dialog_tab_contents_delegate.h"
#include "chrome/browser/ui/webui/html_dialog_ui.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "ui/base/gtk/gtk_hig_constants.h"
#include "ui/gfx/rect.h"
#include "views/widget/native_widget_gtk.h"

// ConstrainedHtmlDelegateGtk works with ConstrainedWindowGtk to present
// a TabContents in a ContraintedHtmlUI.
class ConstrainedHtmlDelegateGtk : public views::NativeWidgetGtk,
                                   public ConstrainedHtmlUIDelegate,
                                   public ConstrainedWindowGtkDelegate,
                                   public HtmlDialogTabContentsDelegate {
 public:
  ConstrainedHtmlDelegateGtk(Profile* profile,
                             HtmlDialogUIDelegate* delegate);
  ~ConstrainedHtmlDelegateGtk();

  // ConstrainedHtmlUIDelegate interface.
  virtual HtmlDialogUIDelegate* GetHtmlDialogUIDelegate() OVERRIDE;
  virtual void OnDialogCloseFromWebUI() OVERRIDE;
  virtual void ReleaseTabContentsOnDialogClose() OVERRIDE {
    release_tab_on_close_ = true;
  }
  virtual ConstrainedWindow* window() OVERRIDE {
    return window_;
  }
  virtual TabContentsWrapper* tab() OVERRIDE {
    return html_tab_contents_.get();
  }

  // ConstrainedWindowGtkDelegate implementation.
  virtual GtkWidget* GetWidgetRoot() OVERRIDE {
    return GetNativeView();
  }
  virtual GtkWidget* GetFocusWidget() OVERRIDE {
    return html_tab_contents_->tab_contents()->GetContentNativeView();
  }
  virtual void DeleteDelegate() OVERRIDE {
    if (!closed_via_webui_)
      html_delegate_->OnDialogClosed("");
    tab_container_->ChangeTabContents(NULL);
  }
  virtual bool GetBackgroundColor(GdkColor* color) OVERRIDE {
    *color = ui::kGdkWhite;
    return true;
  }
  virtual bool ShouldHaveBorderPadding() const OVERRIDE {
    return false;
  }

  // HtmlDialogTabContentsDelegate interface.
  void HandleKeyboardEvent(const NativeWebKeyboardEvent& event) OVERRIDE {}

  void set_window(ConstrainedWindow* window) {
    window_ = window;
  }

 private:
  scoped_ptr<TabContentsWrapper> html_tab_contents_;
  TabContentsContainer* tab_container_;

  HtmlDialogUIDelegate* html_delegate_;

  // The constrained window that owns |this|.  Saved so we can close it later.
  ConstrainedWindow* window_;

  // Was the dialog closed from WebUI (in which case |html_delegate_|'s
  // OnDialogClosed() method has already been called)?
  bool closed_via_webui_;

  // If true, release |tab_| on close instead of destroying it.
  bool release_tab_on_close_;
};

ConstrainedHtmlDelegateGtk::ConstrainedHtmlDelegateGtk(
    Profile* profile,
    HtmlDialogUIDelegate* delegate)
    : views::NativeWidgetGtk(new views::Widget),
      HtmlDialogTabContentsDelegate(profile),
      tab_container_(NULL),
      html_delegate_(delegate),
      window_(NULL),
      closed_via_webui_(false) {
  CHECK(delegate);
  TabContents* tab_contents =
      new TabContents(profile, NULL, MSG_ROUTING_NONE, NULL, NULL);
  html_tab_contents_.reset(new TabContentsWrapper(tab_contents));
  tab_contents->set_delegate(this);

  // Set |this| as a property so the ConstrainedHtmlUI can retrieve it.
  ConstrainedHtmlUI::GetPropertyAccessor().SetProperty(
      tab_contents->property_bag(), this);
  tab_contents->controller().LoadURL(delegate->GetDialogContentURL(), GURL(),
                                     content::PAGE_TRANSITION_START_PAGE,
                                     std::string());

  views::Widget::InitParams params(views::Widget::InitParams::TYPE_CONTROL);
  params.native_widget = this;
  GetWidget()->Init(params);

  tab_container_ = new TabContentsContainer;
  GetWidget()->SetContentsView(tab_container_);
  tab_container_->ChangeTabContents(html_tab_contents_->tab_contents());

  gfx::Size dialog_size;
  html_delegate_->GetDialogSize(&dialog_size);
  gtk_widget_set_size_request(GetWidgetRoot(),
                              dialog_size.width(),
                              dialog_size.height());
}

ConstrainedHtmlDelegateGtk::~ConstrainedHtmlDelegateGtk() {
  if (release_tab_on_close_)
    ignore_result(html_tab_contents_.release());
}

HtmlDialogUIDelegate* ConstrainedHtmlDelegateGtk::GetHtmlDialogUIDelegate() {
  return html_delegate_;
}

void ConstrainedHtmlDelegateGtk::OnDialogCloseFromWebUI() {
  closed_via_webui_ = true;
  window_->CloseConstrainedWindow();
}

// static
ConstrainedHtmlUIDelegate* ConstrainedHtmlUI::CreateConstrainedHtmlDialog(
    Profile* profile,
    HtmlDialogUIDelegate* delegate,
    TabContentsWrapper* wrapper) {
  ConstrainedHtmlDelegateGtk* constrained_delegate =
      new ConstrainedHtmlDelegateGtk(profile, delegate);
  ConstrainedWindow* constrained_window =
      new ConstrainedWindowGtk(wrapper, constrained_delegate);
  constrained_delegate->set_window(constrained_window);
  return constrained_delegate;
}
<commit_msg>Views: Add missing initializer in the views version of ConstrainedHtmlDelegateGtk.<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 "chrome/browser/ui/webui/constrained_html_ui.h"

#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/gtk/constrained_window_gtk.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/browser/ui/views/tab_contents/tab_contents_container.h"
#include "chrome/browser/ui/webui/html_dialog_tab_contents_delegate.h"
#include "chrome/browser/ui/webui/html_dialog_ui.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "ui/base/gtk/gtk_hig_constants.h"
#include "ui/gfx/rect.h"
#include "views/widget/native_widget_gtk.h"

// ConstrainedHtmlDelegateGtk works with ConstrainedWindowGtk to present
// a TabContents in a ContraintedHtmlUI.
class ConstrainedHtmlDelegateGtk : public views::NativeWidgetGtk,
                                   public ConstrainedHtmlUIDelegate,
                                   public ConstrainedWindowGtkDelegate,
                                   public HtmlDialogTabContentsDelegate {
 public:
  ConstrainedHtmlDelegateGtk(Profile* profile,
                             HtmlDialogUIDelegate* delegate);
  ~ConstrainedHtmlDelegateGtk();

  // ConstrainedHtmlUIDelegate interface.
  virtual HtmlDialogUIDelegate* GetHtmlDialogUIDelegate() OVERRIDE;
  virtual void OnDialogCloseFromWebUI() OVERRIDE;
  virtual void ReleaseTabContentsOnDialogClose() OVERRIDE {
    release_tab_on_close_ = true;
  }
  virtual ConstrainedWindow* window() OVERRIDE {
    return window_;
  }
  virtual TabContentsWrapper* tab() OVERRIDE {
    return html_tab_contents_.get();
  }

  // ConstrainedWindowGtkDelegate implementation.
  virtual GtkWidget* GetWidgetRoot() OVERRIDE {
    return GetNativeView();
  }
  virtual GtkWidget* GetFocusWidget() OVERRIDE {
    return html_tab_contents_->tab_contents()->GetContentNativeView();
  }
  virtual void DeleteDelegate() OVERRIDE {
    if (!closed_via_webui_)
      html_delegate_->OnDialogClosed("");
    tab_container_->ChangeTabContents(NULL);
  }
  virtual bool GetBackgroundColor(GdkColor* color) OVERRIDE {
    *color = ui::kGdkWhite;
    return true;
  }
  virtual bool ShouldHaveBorderPadding() const OVERRIDE {
    return false;
  }

  // HtmlDialogTabContentsDelegate interface.
  void HandleKeyboardEvent(const NativeWebKeyboardEvent& event) OVERRIDE {}

  void set_window(ConstrainedWindow* window) {
    window_ = window;
  }

 private:
  scoped_ptr<TabContentsWrapper> html_tab_contents_;
  TabContentsContainer* tab_container_;

  HtmlDialogUIDelegate* html_delegate_;

  // The constrained window that owns |this|.  Saved so we can close it later.
  ConstrainedWindow* window_;

  // Was the dialog closed from WebUI (in which case |html_delegate_|'s
  // OnDialogClosed() method has already been called)?
  bool closed_via_webui_;

  // If true, release |tab_| on close instead of destroying it.
  bool release_tab_on_close_;
};

ConstrainedHtmlDelegateGtk::ConstrainedHtmlDelegateGtk(
    Profile* profile,
    HtmlDialogUIDelegate* delegate)
    : views::NativeWidgetGtk(new views::Widget),
      HtmlDialogTabContentsDelegate(profile),
      tab_container_(NULL),
      html_delegate_(delegate),
      window_(NULL),
      closed_via_webui_(false),
      release_tab_on_close_(false) {
  CHECK(delegate);
  TabContents* tab_contents =
      new TabContents(profile, NULL, MSG_ROUTING_NONE, NULL, NULL);
  html_tab_contents_.reset(new TabContentsWrapper(tab_contents));
  tab_contents->set_delegate(this);

  // Set |this| as a property so the ConstrainedHtmlUI can retrieve it.
  ConstrainedHtmlUI::GetPropertyAccessor().SetProperty(
      tab_contents->property_bag(), this);
  tab_contents->controller().LoadURL(delegate->GetDialogContentURL(), GURL(),
                                     content::PAGE_TRANSITION_START_PAGE,
                                     std::string());

  views::Widget::InitParams params(views::Widget::InitParams::TYPE_CONTROL);
  params.native_widget = this;
  GetWidget()->Init(params);

  tab_container_ = new TabContentsContainer;
  GetWidget()->SetContentsView(tab_container_);
  tab_container_->ChangeTabContents(html_tab_contents_->tab_contents());

  gfx::Size dialog_size;
  html_delegate_->GetDialogSize(&dialog_size);
  gtk_widget_set_size_request(GetWidgetRoot(),
                              dialog_size.width(),
                              dialog_size.height());
}

ConstrainedHtmlDelegateGtk::~ConstrainedHtmlDelegateGtk() {
  if (release_tab_on_close_)
    ignore_result(html_tab_contents_.release());
}

HtmlDialogUIDelegate* ConstrainedHtmlDelegateGtk::GetHtmlDialogUIDelegate() {
  return html_delegate_;
}

void ConstrainedHtmlDelegateGtk::OnDialogCloseFromWebUI() {
  closed_via_webui_ = true;
  window_->CloseConstrainedWindow();
}

// static
ConstrainedHtmlUIDelegate* ConstrainedHtmlUI::CreateConstrainedHtmlDialog(
    Profile* profile,
    HtmlDialogUIDelegate* delegate,
    TabContentsWrapper* wrapper) {
  ConstrainedHtmlDelegateGtk* constrained_delegate =
      new ConstrainedHtmlDelegateGtk(profile, delegate);
  ConstrainedWindow* constrained_window =
      new ConstrainedWindowGtk(wrapper, constrained_delegate);
  constrained_delegate->set_window(constrained_window);
  return constrained_delegate;
}
<|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/printing/print_job.h"

#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/message_loop/message_loop.h"
#include "base/threading/thread_restrictions.h"
#include "base/threading/worker_pool.h"
#include "base/timer/timer.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/printing/print_job_worker.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_service.h"
#include "printing/printed_document.h"
#include "printing/printed_page.h"

#if defined(OS_WIN)
#include "chrome/browser/printing/pdf_to_emf_converter.h"
#include "printing/pdf_render_settings.h"
#endif

using base::TimeDelta;

namespace {

// Helper function to ensure |owner| is valid until at least |callback| returns.
void HoldRefCallback(const scoped_refptr<printing::PrintJobWorkerOwner>& owner,
                     const base::Closure& callback) {
  callback.Run();
}

}  // namespace

namespace printing {

PrintJob::PrintJob()
    : source_(NULL),
      worker_(),
      settings_(),
      is_job_pending_(false),
      is_canceling_(false),
      quit_factory_(this) {
  // This is normally a UI message loop, but in unit tests, the message loop is
  // of the 'default' type.
  DCHECK(base::MessageLoopForUI::IsCurrent() ||
         base::MessageLoop::current()->type() ==
             base::MessageLoop::TYPE_DEFAULT);
}

PrintJob::~PrintJob() {
  // The job should be finished (or at least canceled) when it is destroyed.
  DCHECK(!is_job_pending_);
  DCHECK(!is_canceling_);
  DCHECK(!worker_ || !worker_->IsRunning());
  DCHECK(RunsTasksOnCurrentThread());
}

void PrintJob::Initialize(PrintJobWorkerOwner* job,
                          PrintedPagesSource* source,
                          int page_count) {
  DCHECK(!source_);
  DCHECK(!worker_.get());
  DCHECK(!is_job_pending_);
  DCHECK(!is_canceling_);
  DCHECK(!document_.get());
  source_ = source;
  worker_.reset(job->DetachWorker(this));
  settings_ = job->settings();

  PrintedDocument* new_doc =
      new PrintedDocument(settings_,
                          source_,
                          job->cookie(),
                          content::BrowserThread::GetBlockingPool());
  new_doc->set_page_count(page_count);
  UpdatePrintedDocument(new_doc);

  // Don't forget to register to our own messages.
  registrar_.Add(this, chrome::NOTIFICATION_PRINT_JOB_EVENT,
                 content::Source<PrintJob>(this));
}

void PrintJob::Observe(int type,
                       const content::NotificationSource& source,
                       const content::NotificationDetails& details) {
  DCHECK(RunsTasksOnCurrentThread());
  switch (type) {
    case chrome::NOTIFICATION_PRINT_JOB_EVENT: {
      OnNotifyPrintJobEvent(*content::Details<JobEventDetails>(details).ptr());
      break;
    }
    default: {
      break;
    }
  }
}

void PrintJob::GetSettingsDone(const PrintSettings& new_settings,
                               PrintingContext::Result result) {
  NOTREACHED();
}

PrintJobWorker* PrintJob::DetachWorker(PrintJobWorkerOwner* new_owner) {
  NOTREACHED();
  return NULL;
}

const PrintSettings& PrintJob::settings() const {
  return settings_;
}

int PrintJob::cookie() const {
  if (!document_.get())
    // Always use an invalid cookie in this case.
    return 0;
  return document_->cookie();
}

void PrintJob::StartPrinting() {
  DCHECK(RunsTasksOnCurrentThread());
  DCHECK(worker_->IsRunning());
  DCHECK(!is_job_pending_);
  if (!worker_->IsRunning() || is_job_pending_)
    return;

  // Real work is done in PrintJobWorker::StartPrinting().
  worker_->PostTask(FROM_HERE,
                    base::Bind(&HoldRefCallback,
                               make_scoped_refptr(this),
                               base::Bind(&PrintJobWorker::StartPrinting,
                                          base::Unretained(worker_.get()),
                                          document_)));
  // Set the flag right now.
  is_job_pending_ = true;

  // Tell everyone!
  scoped_refptr<JobEventDetails> details(
      new JobEventDetails(JobEventDetails::NEW_DOC, document_.get(), NULL));
  content::NotificationService::current()->Notify(
      chrome::NOTIFICATION_PRINT_JOB_EVENT,
      content::Source<PrintJob>(this),
      content::Details<JobEventDetails>(details.get()));
}

void PrintJob::Stop() {
  DCHECK(RunsTasksOnCurrentThread());

  if (quit_factory_.HasWeakPtrs()) {
    // In case we're running a nested message loop to wait for a job to finish,
    // and we finished before the timeout, quit the nested loop right away.
    Quit();
    quit_factory_.InvalidateWeakPtrs();
  }

  // Be sure to live long enough.
  scoped_refptr<PrintJob> handle(this);

  if (worker_->IsRunning()) {
    ControlledWorkerShutdown();
  } else {
    // Flush the cached document.
    UpdatePrintedDocument(NULL);
  }
}

void PrintJob::Cancel() {
  if (is_canceling_)
    return;
  is_canceling_ = true;

  // Be sure to live long enough.
  scoped_refptr<PrintJob> handle(this);

  DCHECK(RunsTasksOnCurrentThread());
  if (worker_ && worker_->IsRunning()) {
    // Call this right now so it renders the context invalid. Do not use
    // InvokeLater since it would take too much time.
    worker_->Cancel();
  }
  // Make sure a Cancel() is broadcast.
  scoped_refptr<JobEventDetails> details(
      new JobEventDetails(JobEventDetails::FAILED, NULL, NULL));
  content::NotificationService::current()->Notify(
      chrome::NOTIFICATION_PRINT_JOB_EVENT,
      content::Source<PrintJob>(this),
      content::Details<JobEventDetails>(details.get()));
  Stop();
  is_canceling_ = false;
}

bool PrintJob::FlushJob(base::TimeDelta timeout) {
  // Make sure the object outlive this message loop.
  scoped_refptr<PrintJob> handle(this);

  base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
      base::Bind(&PrintJob::Quit, quit_factory_.GetWeakPtr()), timeout);

  base::MessageLoop::ScopedNestableTaskAllower allow(
      base::MessageLoop::current());
  base::MessageLoop::current()->Run();

  return true;
}

void PrintJob::DisconnectSource() {
  source_ = NULL;
  if (document_.get())
    document_->DisconnectSource();
}

bool PrintJob::is_job_pending() const {
  return is_job_pending_;
}

PrintedDocument* PrintJob::document() const {
  return document_.get();
}

void PrintJob::UpdatePrintedDocument(PrintedDocument* new_document) {
  if (document_.get() == new_document)
    return;

  document_ = new_document;

  if (document_.get()) {
    settings_ = document_->settings();
  }

  if (worker_) {
    DCHECK(!is_job_pending_);
    // Sync the document with the worker.
    worker_->PostTask(FROM_HERE,
                      base::Bind(&HoldRefCallback,
                                 make_scoped_refptr(this),
                                 base::Bind(&PrintJobWorker::OnDocumentChanged,
                                            base::Unretained(worker_.get()),
                                            document_)));
  }
}

void PrintJob::OnNotifyPrintJobEvent(const JobEventDetails& event_details) {
  switch (event_details.type()) {
    case JobEventDetails::FAILED: {
      settings_.Clear();
      // No need to cancel since the worker already canceled itself.
      Stop();
      break;
    }
    case JobEventDetails::USER_INIT_DONE:
    case JobEventDetails::DEFAULT_INIT_DONE:
    case JobEventDetails::USER_INIT_CANCELED: {
      DCHECK_EQ(event_details.document(), document_.get());
      break;
    }
    case JobEventDetails::NEW_DOC:
    case JobEventDetails::NEW_PAGE:
    case JobEventDetails::JOB_DONE:
    case JobEventDetails::ALL_PAGES_REQUESTED: {
      // Don't care.
      break;
    }
    case JobEventDetails::DOC_DONE: {
      // This will call Stop() and broadcast a JOB_DONE message.
      base::MessageLoop::current()->PostTask(
          FROM_HERE, base::Bind(&PrintJob::OnDocumentDone, this));
      break;
    }
    case JobEventDetails::PAGE_DONE:
      break;
    default: {
      NOTREACHED();
      break;
    }
  }
}

#if defined(OS_WIN)

class PrintJob::PdfToEmfState {
 public:
  PdfToEmfState(const gfx::Size& page_size, const gfx::Rect& content_area)
      : page_count_(0),
        current_page_(0),
        pages_in_progress_(0),
        page_size_(page_size),
        content_area_(content_area),
        converter_(PdfToEmfConverter::CreateDefault()) {}

  void Start(const scoped_refptr<base::RefCountedMemory>& data,
             const PdfRenderSettings& conversion_settings,
             const PdfToEmfConverter::StartCallback& start_callback) {
    converter_->Start(data, conversion_settings, start_callback);
  }

  void GetMorePages(
      const PdfToEmfConverter::GetPageCallback& get_page_callback) {
    const int kMaxNumberOfTempFilesPerDocument = 3;
    while (pages_in_progress_ < kMaxNumberOfTempFilesPerDocument &&
           current_page_ < page_count_) {
      ++pages_in_progress_;
      converter_->GetPage(current_page_++, get_page_callback);
    }
  }

  void OnPageProcessed(
      const PdfToEmfConverter::GetPageCallback& get_page_callback) {
    --pages_in_progress_;
    GetMorePages(get_page_callback);
    // Release converter if we don't need this any more.
    if (!pages_in_progress_ && current_page_ >= page_count_)
      converter_.reset();
  }

  void set_page_count(int page_count) { page_count_ = page_count; }
  gfx::Size page_size() const { return page_size_; }
  gfx::Rect content_area() const { return content_area_; }

 private:
  int page_count_;
  int current_page_;
  int pages_in_progress_;
  gfx::Size page_size_;
  gfx::Rect content_area_;
  scoped_ptr<PdfToEmfConverter> converter_;
};

void PrintJob::StartPdfToEmfConversion(
    const scoped_refptr<base::RefCountedMemory>& bytes,
    const gfx::Size& page_size,
    const gfx::Rect& content_area) {
  DCHECK(!ptd_to_emf_state_.get());
  ptd_to_emf_state_.reset(new PdfToEmfState(page_size, content_area));
  const int kPrinterDpi = settings().dpi();
  ptd_to_emf_state_->Start(
      bytes,
      printing::PdfRenderSettings(content_area, kPrinterDpi, true),
      base::Bind(&PrintJob::OnPdfToEmfStarted, this));
}

void PrintJob::OnPdfToEmfStarted(int page_count) {
  if (page_count <= 0) {
    ptd_to_emf_state_.reset();
    Cancel();
    return;
  }
  ptd_to_emf_state_->set_page_count(page_count);
  ptd_to_emf_state_->GetMorePages(
      base::Bind(&PrintJob::OnPdfToEmfPageConverted, this));
}

void PrintJob::OnPdfToEmfPageConverted(int page_number,
                                       float scale_factor,
                                       scoped_ptr<MetafilePlayer> emf) {
  DCHECK(ptd_to_emf_state_);
  if (!document_.get() || !emf) {
    ptd_to_emf_state_.reset();
    Cancel();
    return;
  }

  // Update the rendered document. It will send notifications to the listener.
  document_->SetPage(page_number,
                     emf.Pass(),
                     scale_factor,
                     ptd_to_emf_state_->page_size(),
                     ptd_to_emf_state_->content_area());

  ptd_to_emf_state_->GetMorePages(
      base::Bind(&PrintJob::OnPdfToEmfPageConverted, this));
}

#endif  // OS_WIN

void PrintJob::OnDocumentDone() {
  // Be sure to live long enough. The instance could be destroyed by the
  // JOB_DONE broadcast.
  scoped_refptr<PrintJob> handle(this);

  // Stop the worker thread.
  Stop();

  scoped_refptr<JobEventDetails> details(
      new JobEventDetails(JobEventDetails::JOB_DONE, document_.get(), NULL));
  content::NotificationService::current()->Notify(
      chrome::NOTIFICATION_PRINT_JOB_EVENT,
      content::Source<PrintJob>(this),
      content::Details<JobEventDetails>(details.get()));
}

void PrintJob::ControlledWorkerShutdown() {
  DCHECK(RunsTasksOnCurrentThread());

  // The deadlock this code works around is specific to window messaging on
  // Windows, so we aren't likely to need it on any other platforms.
#if defined(OS_WIN)
  // We could easily get into a deadlock case if worker_->Stop() is used; the
  // printer driver created a window as a child of the browser window. By
  // canceling the job, the printer driver initiated dialog box is destroyed,
  // which sends a blocking message to its parent window. If the browser window
  // thread is not processing messages, a deadlock occurs.
  //
  // This function ensures that the dialog box will be destroyed in a timely
  // manner by the mere fact that the thread will terminate. So the potential
  // deadlock is eliminated.
  worker_->StopSoon();

  // Delay shutdown until the worker terminates.  We want this code path
  // to wait on the thread to quit before continuing.
  if (worker_->IsRunning()) {
    base::MessageLoop::current()->PostDelayedTask(
        FROM_HERE,
        base::Bind(&PrintJob::ControlledWorkerShutdown, this),
        base::TimeDelta::FromMilliseconds(100));
    return;
  }
#endif

  // Now make sure the thread object is cleaned up. Do this on a worker
  // thread because it may block.
  base::WorkerPool::PostTaskAndReply(
      FROM_HERE,
      base::Bind(&PrintJobWorker::Stop, base::Unretained(worker_.get())),
      base::Bind(&PrintJob::HoldUntilStopIsCalled, this),
      false);

  is_job_pending_ = false;
  registrar_.RemoveAll();
  UpdatePrintedDocument(NULL);
}

void PrintJob::HoldUntilStopIsCalled() {
}

void PrintJob::Quit() {
  base::MessageLoop::current()->Quit();
}

// Takes settings_ ownership and will be deleted in the receiving thread.
JobEventDetails::JobEventDetails(Type type,
                                 PrintedDocument* document,
                                 PrintedPage* page)
    : document_(document),
      page_(page),
      type_(type) {
}

JobEventDetails::~JobEventDetails() {
}

PrintedDocument* JobEventDetails::document() const { return document_.get(); }

PrintedPage* JobEventDetails::page() const { return page_.get(); }

}  // namespace printing
<commit_msg>Fix print spooler hangs when printing more than 3 pages on Windows.<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/printing/print_job.h"

#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/message_loop/message_loop.h"
#include "base/threading/thread_restrictions.h"
#include "base/threading/worker_pool.h"
#include "base/timer/timer.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/printing/print_job_worker.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_service.h"
#include "printing/printed_document.h"
#include "printing/printed_page.h"

#if defined(OS_WIN)
#include "chrome/browser/printing/pdf_to_emf_converter.h"
#include "printing/pdf_render_settings.h"
#endif

using base::TimeDelta;

namespace {

// Helper function to ensure |owner| is valid until at least |callback| returns.
void HoldRefCallback(const scoped_refptr<printing::PrintJobWorkerOwner>& owner,
                     const base::Closure& callback) {
  callback.Run();
}

}  // namespace

namespace printing {

PrintJob::PrintJob()
    : source_(NULL),
      worker_(),
      settings_(),
      is_job_pending_(false),
      is_canceling_(false),
      quit_factory_(this) {
  // This is normally a UI message loop, but in unit tests, the message loop is
  // of the 'default' type.
  DCHECK(base::MessageLoopForUI::IsCurrent() ||
         base::MessageLoop::current()->type() ==
             base::MessageLoop::TYPE_DEFAULT);
}

PrintJob::~PrintJob() {
  // The job should be finished (or at least canceled) when it is destroyed.
  DCHECK(!is_job_pending_);
  DCHECK(!is_canceling_);
  DCHECK(!worker_ || !worker_->IsRunning());
  DCHECK(RunsTasksOnCurrentThread());
}

void PrintJob::Initialize(PrintJobWorkerOwner* job,
                          PrintedPagesSource* source,
                          int page_count) {
  DCHECK(!source_);
  DCHECK(!worker_.get());
  DCHECK(!is_job_pending_);
  DCHECK(!is_canceling_);
  DCHECK(!document_.get());
  source_ = source;
  worker_.reset(job->DetachWorker(this));
  settings_ = job->settings();

  PrintedDocument* new_doc =
      new PrintedDocument(settings_,
                          source_,
                          job->cookie(),
                          content::BrowserThread::GetBlockingPool());
  new_doc->set_page_count(page_count);
  UpdatePrintedDocument(new_doc);

  // Don't forget to register to our own messages.
  registrar_.Add(this, chrome::NOTIFICATION_PRINT_JOB_EVENT,
                 content::Source<PrintJob>(this));
}

void PrintJob::Observe(int type,
                       const content::NotificationSource& source,
                       const content::NotificationDetails& details) {
  DCHECK(RunsTasksOnCurrentThread());
  switch (type) {
    case chrome::NOTIFICATION_PRINT_JOB_EVENT: {
      OnNotifyPrintJobEvent(*content::Details<JobEventDetails>(details).ptr());
      break;
    }
    default: {
      break;
    }
  }
}

void PrintJob::GetSettingsDone(const PrintSettings& new_settings,
                               PrintingContext::Result result) {
  NOTREACHED();
}

PrintJobWorker* PrintJob::DetachWorker(PrintJobWorkerOwner* new_owner) {
  NOTREACHED();
  return NULL;
}

const PrintSettings& PrintJob::settings() const {
  return settings_;
}

int PrintJob::cookie() const {
  if (!document_.get())
    // Always use an invalid cookie in this case.
    return 0;
  return document_->cookie();
}

void PrintJob::StartPrinting() {
  DCHECK(RunsTasksOnCurrentThread());
  DCHECK(worker_->IsRunning());
  DCHECK(!is_job_pending_);
  if (!worker_->IsRunning() || is_job_pending_)
    return;

  // Real work is done in PrintJobWorker::StartPrinting().
  worker_->PostTask(FROM_HERE,
                    base::Bind(&HoldRefCallback,
                               make_scoped_refptr(this),
                               base::Bind(&PrintJobWorker::StartPrinting,
                                          base::Unretained(worker_.get()),
                                          document_)));
  // Set the flag right now.
  is_job_pending_ = true;

  // Tell everyone!
  scoped_refptr<JobEventDetails> details(
      new JobEventDetails(JobEventDetails::NEW_DOC, document_.get(), NULL));
  content::NotificationService::current()->Notify(
      chrome::NOTIFICATION_PRINT_JOB_EVENT,
      content::Source<PrintJob>(this),
      content::Details<JobEventDetails>(details.get()));
}

void PrintJob::Stop() {
  DCHECK(RunsTasksOnCurrentThread());

  if (quit_factory_.HasWeakPtrs()) {
    // In case we're running a nested message loop to wait for a job to finish,
    // and we finished before the timeout, quit the nested loop right away.
    Quit();
    quit_factory_.InvalidateWeakPtrs();
  }

  // Be sure to live long enough.
  scoped_refptr<PrintJob> handle(this);

  if (worker_->IsRunning()) {
    ControlledWorkerShutdown();
  } else {
    // Flush the cached document.
    UpdatePrintedDocument(NULL);
  }
}

void PrintJob::Cancel() {
  if (is_canceling_)
    return;
  is_canceling_ = true;

  // Be sure to live long enough.
  scoped_refptr<PrintJob> handle(this);

  DCHECK(RunsTasksOnCurrentThread());
  if (worker_ && worker_->IsRunning()) {
    // Call this right now so it renders the context invalid. Do not use
    // InvokeLater since it would take too much time.
    worker_->Cancel();
  }
  // Make sure a Cancel() is broadcast.
  scoped_refptr<JobEventDetails> details(
      new JobEventDetails(JobEventDetails::FAILED, NULL, NULL));
  content::NotificationService::current()->Notify(
      chrome::NOTIFICATION_PRINT_JOB_EVENT,
      content::Source<PrintJob>(this),
      content::Details<JobEventDetails>(details.get()));
  Stop();
  is_canceling_ = false;
}

bool PrintJob::FlushJob(base::TimeDelta timeout) {
  // Make sure the object outlive this message loop.
  scoped_refptr<PrintJob> handle(this);

  base::MessageLoop::current()->PostDelayedTask(FROM_HERE,
      base::Bind(&PrintJob::Quit, quit_factory_.GetWeakPtr()), timeout);

  base::MessageLoop::ScopedNestableTaskAllower allow(
      base::MessageLoop::current());
  base::MessageLoop::current()->Run();

  return true;
}

void PrintJob::DisconnectSource() {
  source_ = NULL;
  if (document_.get())
    document_->DisconnectSource();
}

bool PrintJob::is_job_pending() const {
  return is_job_pending_;
}

PrintedDocument* PrintJob::document() const {
  return document_.get();
}

#if defined(OS_WIN)

class PrintJob::PdfToEmfState {
 public:
  PdfToEmfState(const gfx::Size& page_size, const gfx::Rect& content_area)
      : page_count_(0),
        current_page_(0),
        pages_in_progress_(0),
        page_size_(page_size),
        content_area_(content_area),
        converter_(PdfToEmfConverter::CreateDefault()) {}

  void Start(const scoped_refptr<base::RefCountedMemory>& data,
             const PdfRenderSettings& conversion_settings,
             const PdfToEmfConverter::StartCallback& start_callback) {
    converter_->Start(data, conversion_settings, start_callback);
  }

  void GetMorePages(
      const PdfToEmfConverter::GetPageCallback& get_page_callback) {
    const int kMaxNumberOfTempFilesPerDocument = 3;
    while (pages_in_progress_ < kMaxNumberOfTempFilesPerDocument &&
           current_page_ < page_count_) {
      ++pages_in_progress_;
      converter_->GetPage(current_page_++, get_page_callback);
    }
  }

  void OnPageProcessed(
      const PdfToEmfConverter::GetPageCallback& get_page_callback) {
    --pages_in_progress_;
    GetMorePages(get_page_callback);
    // Release converter if we don't need this any more.
    if (!pages_in_progress_ && current_page_ >= page_count_)
      converter_.reset();
  }

  void set_page_count(int page_count) { page_count_ = page_count; }
  gfx::Size page_size() const { return page_size_; }
  gfx::Rect content_area() const { return content_area_; }

 private:
  int page_count_;
  int current_page_;
  int pages_in_progress_;
  gfx::Size page_size_;
  gfx::Rect content_area_;
  scoped_ptr<PdfToEmfConverter> converter_;
};

void PrintJob::StartPdfToEmfConversion(
    const scoped_refptr<base::RefCountedMemory>& bytes,
    const gfx::Size& page_size,
    const gfx::Rect& content_area) {
  DCHECK(!ptd_to_emf_state_.get());
  ptd_to_emf_state_.reset(new PdfToEmfState(page_size, content_area));
  const int kPrinterDpi = settings().dpi();
  ptd_to_emf_state_->Start(
      bytes,
      printing::PdfRenderSettings(content_area, kPrinterDpi, true),
      base::Bind(&PrintJob::OnPdfToEmfStarted, this));
}

void PrintJob::OnPdfToEmfStarted(int page_count) {
  if (page_count <= 0) {
    ptd_to_emf_state_.reset();
    Cancel();
    return;
  }
  ptd_to_emf_state_->set_page_count(page_count);
  ptd_to_emf_state_->GetMorePages(
      base::Bind(&PrintJob::OnPdfToEmfPageConverted, this));
}

void PrintJob::OnPdfToEmfPageConverted(int page_number,
                                       float scale_factor,
                                       scoped_ptr<MetafilePlayer> emf) {
  DCHECK(ptd_to_emf_state_);
  if (!document_.get() || !emf) {
    ptd_to_emf_state_.reset();
    Cancel();
    return;
  }

  // Update the rendered document. It will send notifications to the listener.
  document_->SetPage(page_number,
                     emf.Pass(),
                     scale_factor,
                     ptd_to_emf_state_->page_size(),
                     ptd_to_emf_state_->content_area());

  ptd_to_emf_state_->GetMorePages(
      base::Bind(&PrintJob::OnPdfToEmfPageConverted, this));
}

#endif  // OS_WIN

void PrintJob::UpdatePrintedDocument(PrintedDocument* new_document) {
  if (document_.get() == new_document)
    return;

  document_ = new_document;

  if (document_.get()) {
    settings_ = document_->settings();
  }

  if (worker_) {
    DCHECK(!is_job_pending_);
    // Sync the document with the worker.
    worker_->PostTask(FROM_HERE,
                      base::Bind(&HoldRefCallback,
                                 make_scoped_refptr(this),
                                 base::Bind(&PrintJobWorker::OnDocumentChanged,
                                            base::Unretained(worker_.get()),
                                            document_)));
  }
}

void PrintJob::OnNotifyPrintJobEvent(const JobEventDetails& event_details) {
  switch (event_details.type()) {
    case JobEventDetails::FAILED: {
      settings_.Clear();
      // No need to cancel since the worker already canceled itself.
      Stop();
      break;
    }
    case JobEventDetails::USER_INIT_DONE:
    case JobEventDetails::DEFAULT_INIT_DONE:
    case JobEventDetails::USER_INIT_CANCELED: {
      DCHECK_EQ(event_details.document(), document_.get());
      break;
    }
    case JobEventDetails::NEW_DOC:
    case JobEventDetails::NEW_PAGE:
    case JobEventDetails::JOB_DONE:
    case JobEventDetails::ALL_PAGES_REQUESTED: {
      // Don't care.
      break;
    }
    case JobEventDetails::DOC_DONE: {
      // This will call Stop() and broadcast a JOB_DONE message.
      base::MessageLoop::current()->PostTask(
          FROM_HERE, base::Bind(&PrintJob::OnDocumentDone, this));
      break;
    }
    case JobEventDetails::PAGE_DONE:
#if defined(OS_WIN)
      ptd_to_emf_state_->OnPageProcessed(
          base::Bind(&PrintJob::OnPdfToEmfPageConverted, this));
#endif  // OS_WIN
      break;
    default: {
      NOTREACHED();
      break;
    }
  }
}

void PrintJob::OnDocumentDone() {
  // Be sure to live long enough. The instance could be destroyed by the
  // JOB_DONE broadcast.
  scoped_refptr<PrintJob> handle(this);

  // Stop the worker thread.
  Stop();

  scoped_refptr<JobEventDetails> details(
      new JobEventDetails(JobEventDetails::JOB_DONE, document_.get(), NULL));
  content::NotificationService::current()->Notify(
      chrome::NOTIFICATION_PRINT_JOB_EVENT,
      content::Source<PrintJob>(this),
      content::Details<JobEventDetails>(details.get()));
}

void PrintJob::ControlledWorkerShutdown() {
  DCHECK(RunsTasksOnCurrentThread());

  // The deadlock this code works around is specific to window messaging on
  // Windows, so we aren't likely to need it on any other platforms.
#if defined(OS_WIN)
  // We could easily get into a deadlock case if worker_->Stop() is used; the
  // printer driver created a window as a child of the browser window. By
  // canceling the job, the printer driver initiated dialog box is destroyed,
  // which sends a blocking message to its parent window. If the browser window
  // thread is not processing messages, a deadlock occurs.
  //
  // This function ensures that the dialog box will be destroyed in a timely
  // manner by the mere fact that the thread will terminate. So the potential
  // deadlock is eliminated.
  worker_->StopSoon();

  // Delay shutdown until the worker terminates.  We want this code path
  // to wait on the thread to quit before continuing.
  if (worker_->IsRunning()) {
    base::MessageLoop::current()->PostDelayedTask(
        FROM_HERE,
        base::Bind(&PrintJob::ControlledWorkerShutdown, this),
        base::TimeDelta::FromMilliseconds(100));
    return;
  }
#endif

  // Now make sure the thread object is cleaned up. Do this on a worker
  // thread because it may block.
  base::WorkerPool::PostTaskAndReply(
      FROM_HERE,
      base::Bind(&PrintJobWorker::Stop, base::Unretained(worker_.get())),
      base::Bind(&PrintJob::HoldUntilStopIsCalled, this),
      false);

  is_job_pending_ = false;
  registrar_.RemoveAll();
  UpdatePrintedDocument(NULL);
}

void PrintJob::HoldUntilStopIsCalled() {
}

void PrintJob::Quit() {
  base::MessageLoop::current()->Quit();
}

// Takes settings_ ownership and will be deleted in the receiving thread.
JobEventDetails::JobEventDetails(Type type,
                                 PrintedDocument* document,
                                 PrintedPage* page)
    : document_(document),
      page_(page),
      type_(type) {
}

JobEventDetails::~JobEventDetails() {
}

PrintedDocument* JobEventDetails::document() const { return document_.get(); }

PrintedPage* JobEventDetails::page() const { return page_.get(); }

}  // namespace printing
<|endoftext|>


<commit_before>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE client
#include <boost/test/unit_test.hpp>

#include "client.hpp"
#include "request.hpp"
#include "reply.hpp"

BOOST_AUTO_TEST_CASE(check_readrequest)
{
	request r;

	BOOST_CHECK (read_request ("b", r) == invalid_request);
	BOOST_CHECK (read_request ("open bla", r) == no_error);
}
<commit_msg>improve test case<commit_after>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE client
#include <boost/test/unit_test.hpp>

#include "client.hpp"
#include "request.hpp"
#include "reply.hpp"

BOOST_AUTO_TEST_CASE(check_readrequest)
{
	request r;

	BOOST_CHECK (read_request ("aaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbb", r) == invalid_request);

	BOOST_CHECK (read_request ("b", r) == invalid_request);

	BOOST_CHECK (read_request ("open bla", r) == no_error);
	BOOST_CHECK (r.getType() == openfile);

	BOOST_CHECK (read_request ("close 0", r) == no_error);
	BOOST_CHECK (r.getType() == closefile);

	BOOST_CHECK (read_request ("read 0 100", r) == no_error);
	BOOST_CHECK (r.getType() == readfile);
}
<|endoftext|>


<commit_before>// USE INF = 1e9!

// w: weight or cost, c : capacity
struct edge {int v, f, w, c; };

int node_count, flw_lmt=INF, src, snk, flw, cst, p[N], d[N], et[N];
vector<edge> e;
vector<int> g[N];

void add_edge(int u, int v, int w, int c) {
  int k = e.size();
  node_count = max(node_count, u+1);
  node_count = max(node_count, v+1);
  g[u].push_back(k);
  g[v].push_back(k+1);
  e.push_back({ v, 0,  w, c });
  e.push_back({ u, 0, -w, 0 });
}

void clear() {
  flw_lmt = INF;
  for(int i=0; i<node_count; ++i) g[i].clear();
  e.clear();
  node_count = 0;
}

void min_cost_max_flow() {
  flw = 0, cst = 0;
  while (flw < flw_lmt) {
    memset(et, 0, sizeof et);
    memset(d, 63, sizeof d);
    deque<int> q;
    q.push_back(src), d[src] = 0;

    while (!q.empty()) {
      int u = q.front(); q.pop_front();
      et[u] = 2;

      for(int i : g[u]) {
        edge &dir = e[i];
        int v = dir.v;
        if (dir.f < dir.c and d[u] + dir.w < d[v]) {
          d[v] = d[u] + dir.w;
          if (et[v] == 0) q.push_back(v);
          else if (et[v] == 2) q.push_front(v);
          et[v] = 1;
          p[v] = i;
        }
      }
    }

    if (d[snk] > INF) break;

    int inc = flw_lmt - flw;
    for (int u=snk; u != src; u = e[p[u]^1].v) {
      edge &dir = e[p[u]];
      inc = min(inc, dir.c - dir.f);
    }

    for (int u=snk; u != src; u = e[p[u]^1].v) {
      edge &dir = e[p[u]], &rev = e[p[u]^1];
      dir.f += inc;
      rev.f -= inc;
      cst += inc * dir.w;
    }

    if (!inc) break;
    flw += inc;
  }
}
<commit_msg>Fix for when graph has |E| = 0<commit_after>// USE INF = 1e9!

// w: weight or cost, c : capacity
struct edge {int v, f, w, c; };

int n, flw_lmt=INF, src, snk, flw, cst, p[N], d[N], et[N];
vector<edge> e;
vector<int> g[N];

void add_edge(int u, int v, int w, int c) {
  int k = e.size();
  g[u].push_back(k);
  g[v].push_back(k+1);
  e.push_back({ v, 0,  w, c });
  e.push_back({ u, 0, -w, 0 });
}

void clear() {
  flw_lmt = INF;
  for(int i=0; i<=n; ++i) g[i].clear();
  e.clear();
}

void min_cost_max_flow() {
  flw = 0, cst = 0;
  while (flw < flw_lmt) {
    memset(et, 0, (n+1) * sizeof(int));
    memset(d, 63, (n+1) * sizeof(int));
    deque<int> q;
    q.push_back(src), d[src] = 0;

    while (!q.empty()) {
      int u = q.front(); q.pop_front();
      et[u] = 2;

      for(int i : g[u]) {
        edge &dir = e[i];
        int v = dir.v;
        if (dir.f < dir.c and d[u] + dir.w < d[v]) {
          d[v] = d[u] + dir.w;
          if (et[v] == 0) q.push_back(v);
          else if (et[v] == 2) q.push_front(v);
          et[v] = 1;
          p[v] = i;
        }
      }
    }

    if (d[snk] > INF) break;

    int inc = flw_lmt - flw;
    for (int u=snk; u != src; u = e[p[u]^1].v) {
      edge &dir = e[p[u]];
      inc = min(inc, dir.c - dir.f);
    }

    for (int u=snk; u != src; u = e[p[u]^1].v) {
      edge &dir = e[p[u]], &rev = e[p[u]^1];
      dir.f += inc;
      rev.f -= inc;
      cst += inc * dir.w;
    }

    if (!inc) break;
    flw += inc;
  }
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    qtITK.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include <qapplication.h>
#include <qpushbutton.h>
#include <qvbox.h>

#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkDiscreteGaussianImageFilter.h"

#include "itkQtAdaptor.h"
#include "itkQtProgressBar.h"

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

  typedef itk::Image< float, 2 > ImageType;

  typedef itk::DiscreteGaussianImageFilter<
                    ImageType,
                    ImageType >  FilterType;

  typedef itk::ImageFileReader< ImageType > ReaderType;

  ReaderType::Pointer reader = ReaderType::New();

  FilterType::Pointer filter = FilterType::New();

  filter->SetInput( reader->GetOutput() );

  // Create Qt Application to let Qt get its
  // parameters from the command line
  QApplication app( argc, argv );

  reader->SetFileName( argv[1] );

  QVBox qb;
  qb.resize(120,200);

  QPushButton  bb( "Start", &qb );
  bb.resize( 100, 30 );

  QPushButton  cc( "State", &qb );
  cc.resize( 100, 30 );

  QPushButton  qt( "Quit", &qb );
  qt.resize( 100, 30 );

  itk::QtProgressBar qs( Qt::Horizontal, &qb, "Progress");
  qs.resize( 100, 30 );
  qs.setRange(0,100);
  qs.setValue(0);

  // Connect the progress bar to the ITK processObject
  qs.Observe( filter.GetPointer() );
  qs.Observe( reader.GetPointer() );

  typedef itk::QtSlotAdaptor<FilterType> SlotAdaptorType;
  SlotAdaptorType slotAdaptor;

  // Connect the adaptor to a method of the ITK filter
  slotAdaptor.SetCallbackFunction( filter, & FilterType::Update );

  // Connect the adaptor's Slot to the Qt Widget Signal
  QObject::connect( &bb, SIGNAL(clicked()), &slotAdaptor, SLOT(Slot()) );

  typedef itk::QtSignalAdaptor SignalAdaptorType;
  SignalAdaptorType signalAdaptor;

  // Connect the adaptor as an observer of a Filter's event
  filter->AddObserver( itk::StartEvent(),  signalAdaptor.GetCommand() );

  // Connect the adaptor's Signal to the Qt Widget Slot
  QObject::connect( &signalAdaptor, SIGNAL(Signal()), &cc, SLOT(toggle()) );

  // Connect the Quit button signal to the quit slot of the application
  QObject::connect( &qt, SIGNAL(clicked()), &app, SLOT(quit()) );

  app.setMainWidget( &qb );
  qb.show();

  return app.exec();

}

<commit_msg>ENH: AddImageFilter used to illustrate the progress bar.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    qtITK.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include <qapplication.h>
#include <qpushbutton.h>
#include <qvbox.h>

#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkAddImageFilter.h"

#include "itkQtAdaptor.h"
#include "itkQtProgressBar.h"

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

  typedef itk::Image< float, 2 > ImageType;

  typedef itk::AddImageFilter<
                    ImageType,
                    ImageType,
                    ImageType >  FilterType;

  typedef itk::ImageFileReader< ImageType > ReaderType;

  ReaderType::Pointer reader = ReaderType::New();

  FilterType::Pointer filter = FilterType::New();

  filter->SetInput1( reader->GetOutput() );
  filter->SetInput2( reader->GetOutput() );

  // Create Qt Application to let Qt get its
  // parameters from the command line
  QApplication app( argc, argv );

  reader->SetFileName( argv[1] );

  QVBox qb;
  qb.resize(620,200);

  QPushButton  bb( "Start", &qb );
  bb.resize( 100, 30 );

  QPushButton  cc( "State", &qb );
  cc.resize( 100, 30 );

  QPushButton  qt( "Quit", &qb );
  qt.resize( 100, 30 );

  itk::QtProgressBar qs( Qt::Horizontal, &qb, "Progress");
  qs.resize( 100, 30 );
  qs.setRange(0,100);
  qs.setValue(0);

  // Connect the progress bar to the ITK processObject
  qs.Observe( filter.GetPointer() );
  qs.Observe( reader.GetPointer() );

  typedef itk::QtSlotAdaptor<FilterType> SlotAdaptorType;
  SlotAdaptorType slotAdaptor;

  // Connect the adaptor to a method of the ITK filter
  slotAdaptor.SetCallbackFunction( filter, & FilterType::Update );

  // Connect the adaptor's Slot to the Qt Widget Signal
  QObject::connect( &bb, SIGNAL(clicked()), &slotAdaptor, SLOT(Slot()) );

  typedef itk::QtSignalAdaptor SignalAdaptorType;
  SignalAdaptorType signalAdaptor;

  // Connect the adaptor as an observer of a Filter's event
  filter->AddObserver( itk::StartEvent(),  signalAdaptor.GetCommand() );

  // Connect the adaptor's Signal to the Qt Widget Slot
  QObject::connect( &signalAdaptor, SIGNAL(Signal()), &cc, SLOT(toggle()) );

  // Connect the Quit button signal to the quit slot of the application
  QObject::connect( &qt, SIGNAL(clicked()), &app, SLOT(quit()) );

  app.setMainWidget( &qb );
  qb.show();

  return app.exec();

}

<|endoftext|>


<commit_before>AliAnalysisTask *AddTaskHFEnpePbPb5TeV(Bool_t MCthere,
                                   Bool_t isAOD = kTRUE,
				   Bool_t kNPERef = kTRUE,
				   Bool_t kNPEkAny = kFALSE,
                                   Bool_t newCentralitySelection = kTRUE, // kTRUE: new framework used; kFALSE: old framework used
				   Bool_t kNPERefTPConly = kFALSE,
				   Bool_t kNPETOFITS = kTRUE,
				   Bool_t kNPETOFlast = kFALSE,
				   Bool_t kNPEw      = kFALSE,
				   Bool_t kNPEkf  = kFALSE)

{
  // Default settings (TOF-TPC PbPb)
  const int	kDefTPCcl	= 120;  // 100 (Andrea)
  const int	kDefTPCclPID	=  80;  // 90 (Andrea)
  const int kDefTPCclshared = 1.1;
  const int	kDefITScl	=   4;  // 5 (Andrea)
  const int kDefITSchi2percluster = -1; // cleanup removes badly matching tracks - effects high pt  (cut value = 36) ---> 36 default value for AOD
  const double	kDefDCAr	=   1.; // 2.4 (Andrea)
  const double	kDefDCAz	=   2.; // 3.2 (Andrea)
  const double	kDefTOFs	=   3.;
  const double	kDefITSs	=   2.; // -1,1 up to 1.5, -2,2 up to 3 (Andrea)
  const double  kDefEtaIncMin = -0.8;
  const double  kDefEtaIncMax = 0.8;
  const Bool_t   etacorrection   = kFALSE;
  const Bool_t   multicorrection = kFALSE;

  // --- TPC nsigma max and min cut ---
  Double_t dEdxhm[12] = {3.11,3.11,3.0,3.0,3.0,3.0,3.0,3.0,3.0,3.0,3.0,3.0};
  Double_t tpcl1[12]  = {0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0};                              // my 46% (mfaggin)
  Double_t tpcl2[12]  = {-0.1,-0.1,-0.1,-0.1,-0.1,-0.1,-0.1,-0.1,-0.1,-0.1,-0.1,-0.1};                  // my 50% (mfaggin)
  Double_t tpcl3[12]  = {0.18,0.18,0.18,0.18,0.18,0.18,0.18,0.18,0.18,0.18,0.18,0.18};                  // my 40% (mfaggin)
  Double_t tpcl4[12]  = {-0.38,-0.38,-0.38,-0.38,-0.38,-0.38,-0.38,-0.38,-0.38,-0.38,-0.38,-0.38};      // my 60% (mfaggin)

  // Default setting for the associated electron for the NonPhotonic Analysis
  const double	kassETAm = -0.8;                // -0.9 (Andrea)
  const double	kassETAp = 0.8;                 // 0.9 (Andrea)
  const int	kassITS		=   2;          // # cluster
  const int	kassTPCcl	= 60;           // 80 (Andrea)
  const int	kassTPCPIDcl	=  60;          // not used (Andrea) ---> directly in the filterbit
  const double	kassDCAr	=   1.0;        // not used (Andrea) ---> directly in the filterbit 2.4
  const double	kassDCAz	=   2.0;        // not used (Andrea) ---> directly in the filterbit 3.2
  const double	kassTPCSminus	=  -3.0;
  const double	kassTPCSplus	=   3.0;
  // --- Centrality selection ---
  const int     centrMin        = 0;
  const int     centrMax        = 10;

  Int_t kWei = -1;
  /*
  if (MCthere) kWei = 9;    // default Pb-Pb
  enum {

    k11a10abisweiData = 6,  // LHC11a10abis weights
    k11a10bplusweiData = 7,     // LHC11a10b_plus weights
    k11a10bpluswei11a10abis   = 8,  // LHC11a10b_plus weights for LHC11a10abis
    k11a10bbisweiData = 9,  // LHC11a10bbis weights
  };
  */

  //get the current analysis manager
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTask_hfe_HFE", "No analysis manager found.");
    return 0;
  }

  //mgr->AddClassDebug("AliAnalysisTaskHFE",12);

  AliAnalysisDataContainer *cinput  = mgr->GetCommonInputContainer();

  //@@ 0 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

  Double_t dEdxaclm[12], dEdxachm[12];
  for(int icent = 0; icent < 12; icent++){
    dEdxaclm[icent] = kassTPCSminus;
    dEdxachm[icent] = kassTPCSplus;
  }

  const Bool_t isBeauty = kFALSE; // should be false to prevent inclusive analysis

  if(kNPERef){
    // **************************************************************
    //
    // Reference task
    //
    // **************************************************************

    // TPC low cut = 0 (tpcl1)
    RegisterTaskNPEPbPb( centrMin,centrMax,newCentralitySelection,MCthere, isAOD, isBeauty, kDefTPCcl, kDefTPCclPID, kDefITScl, kDefDCAr, kDefDCAz, tpcl1, dEdxhm, kDefTOFs,0., AliHFEextraCuts::kBoth, kDefITSchi2percluster, kDefTPCclshared, etacorrection, multicorrection, kFALSE, kDefEtaIncMin, kDefEtaIncMax,
			 kassETAm, kassETAp, kassITS, kassTPCcl, kassTPCPIDcl, kassDCAr, kassDCAz, dEdxaclm, dEdxachm, kTRUE, kFALSE,-1);

    // Additional tasks

    // (sma, 6.6.2017) Vary the TOF cut to +-2 sigma)
    RegisterTaskNPEPbPb( centrMin,centrMax,newCentralitySelection,MCthere, isAOD, isBeauty, kDefTPCcl, kDefTPCclPID, kDefITScl, kDefDCAr, kDefDCAz, tpcl2, dEdxhm, 2., 0., AliHFEextraCuts::kBoth, kDefITSchi2percluster, kDefTPCclshared, etacorrection, multicorrection, kFALSE, kDefEtaIncMin, kDefEtaIncMax,
			 kassETAm, kassETAp, kassITS, kassTPCcl, kassTPCPIDcl, kassDCAr, kassDCAz, dEdxaclm, dEdxachm, kTRUE, kFALSE,-1);

    // TPC low cut = -0.1 (tpcl2)
    RegisterTaskNPEPbPb( centrMin,centrMax,newCentralitySelection,MCthere, isAOD, isBeauty, kDefTPCcl, kDefTPCclPID, kDefITScl, kDefDCAr, kDefDCAz, tpcl2, dEdxhm, kDefTOFs,0., AliHFEextraCuts::kBoth, kDefITSchi2percluster, kDefTPCclshared, etacorrection, multicorrection, kFALSE, kDefEtaIncMin, kDefEtaIncMax,
			 kassETAm, kassETAp, kassITS, kassTPCcl, kassTPCPIDcl, kassDCAr, kassDCAz, dEdxaclm, dEdxachm, kTRUE, kFALSE,-1);
    // TPC low cut = 0.16 (tpcl3)
    RegisterTaskNPEPbPb( centrMin,centrMax,newCentralitySelection,MCthere, isAOD, isBeauty, kDefTPCcl, kDefTPCclPID, kDefITScl, kDefDCAr, kDefDCAz, tpcl3, dEdxhm, kDefTOFs,0., AliHFEextraCuts::kBoth, kDefITSchi2percluster, kDefTPCclshared, etacorrection, multicorrection, kFALSE, kDefEtaIncMin, kDefEtaIncMax,
			 kassETAm, kassETAp, kassITS, kassTPCcl, kassTPCPIDcl, kassDCAr, kassDCAz, dEdxaclm, dEdxachm, kTRUE, kFALSE,-1);
    // TPC low cut = -0.38 (tpcl4)
    RegisterTaskNPEPbPb( centrMin,centrMax,newCentralitySelection,MCthere, isAOD, isBeauty, kDefTPCcl, kDefTPCclPID, kDefITScl, kDefDCAr, kDefDCAz, tpcl4, dEdxhm, kDefTOFs,0., AliHFEextraCuts::kBoth, kDefITSchi2percluster, kDefTPCclshared, etacorrection, multicorrection, kFALSE, kDefEtaIncMin, kDefEtaIncMax,
			 kassETAm, kassETAp, kassITS, kassTPCcl, kassTPCPIDcl, kassDCAr, kassDCAz, dEdxaclm, dEdxachm, kTRUE, kFALSE,-1);
  }

  if(kNPETOFlast){
    // **************************************************************
    //
    // Apply TOF after TPC for mismatch background studies
    //
    // **************************************************************
    RegisterTaskNPEPbPb( centrMin,centrMax,newCentralitySelection,MCthere, isAOD, isBeauty, kDefTPCcl, kDefTPCclPID, kDefITScl, kDefDCAr, kDefDCAz, tpcl1, dEdxhm, kDefTOFs,0., AliHFEextraCuts::kBoth, kDefITSchi2percluster, kDefTPCclshared, etacorrection, multicorrection, kTRUE, kDefEtaIncMin, kDefEtaIncMax,
			 kassETAm, kassETAp, kassITS, kassTPCcl, kassTPCPIDcl, kassDCAr, kassDCAz, dEdxaclm, dEdxachm, kTRUE, kFALSE,-1);
  }

  if(kNPEkAny){
    // **************************************************************
    //
    // task for kAny instead of kBoth
    //
    // **************************************************************
    RegisterTaskNPEPbPb( centrMin,centrMax,newCentralitySelection,MCthere, isAOD, isBeauty, kDefTPCcl, kDefTPCclPID, kDefITScl, kDefDCAr, kDefDCAz, tpcl1, dEdxhm, kDefTOFs,0., AliHFEextraCuts::kAny, kDefITSchi2percluster, kDefTPCclshared, etacorrection, multicorrection, kFALSE, kDefEtaIncMin, kDefEtaIncMax,
			 kassETAm, kassETAp, kassITS, kassTPCcl, kassTPCPIDcl, kassDCAr, kassDCAz, dEdxaclm, dEdxachm, kTRUE, kFALSE,-1);
  }

  if(kNPEw && MCthere){
    // **************************************************************
    //
    // Reference task
    //
    // **************************************************************
    RegisterTaskNPEPbPb( centrMin,centrMax,newCentralitySelection,MCthere, isAOD, isBeauty, kDefTPCcl, kDefTPCclPID, kDefITScl, kDefDCAr, kDefDCAz, tpcl1, dEdxhm, kDefTOFs,0., AliHFEextraCuts::kBoth, kDefITSchi2percluster, kDefTPCclshared, etacorrection, multicorrection, kFALSE, kDefEtaIncMin, kDefEtaIncMax,
			 kassETAm, kassETAp, kassITS, kassTPCcl, kassTPCPIDcl, kassDCAr, kassDCAz, dEdxaclm, dEdxachm, kTRUE, kFALSE, 0,kWei);
  }

  if(kNPERefTPConly){
    // **************************************************************
    //
    // Reference task
    //
    // **************************************************************
    RegisterTaskNPEPbPb( centrMin,centrMax,newCentralitySelection,MCthere, isAOD, isBeauty, kDefTPCcl, kDefTPCclPID, kDefITScl, kDefDCAr, kDefDCAz, tpcl1, dEdxhm, 0.,0., AliHFEextraCuts::kBoth, kDefITSchi2percluster, kDefTPCclshared, etacorrection, multicorrection, kFALSE, kDefEtaIncMin, kDefEtaIncMax,
			 kassETAm, kassETAp, kassITS, kassTPCcl, kassTPCPIDcl, kassDCAr, kassDCAz, dEdxaclm, dEdxachm, kTRUE, kFALSE,-1);
  }

 if(kNPETOFITS){
   // **************************************************************
   //
   // Reference task
   //
   // **************************************************************

   // TPC low cut = 0 (tpcl1)
   RegisterTaskNPEPbPb( centrMin,centrMax,newCentralitySelection,MCthere, isAOD, isBeauty, kDefTPCcl, kDefTPCclPID, kDefITScl, kDefDCAr, kDefDCAz, tpcl1, dEdxhm,  kDefTOFs,  kDefITSs, AliHFEextraCuts::kBoth, kDefITSchi2percluster, kDefTPCclshared, etacorrection, multicorrection, kFALSE, kDefEtaIncMin, kDefEtaIncMax,
			kassETAm, kassETAp, kassITS, kassTPCcl, kassTPCPIDcl, kassDCAr, kassDCAz, dEdxaclm, dEdxachm, kTRUE, kFALSE,-1);

   // Additional tasks

   // (sma, 6.6.2017) Vary the ITS cut to +-1
   RegisterTaskNPEPbPb( centrMin,centrMax,newCentralitySelection,MCthere, isAOD, isBeauty, kDefTPCcl, kDefTPCclPID, kDefITScl, kDefDCAr, kDefDCAz, tpcl2, dEdxhm,  kDefTOFs, 1., AliHFEextraCuts::kBoth, kDefITSchi2percluster, kDefTPCclshared, etacorrection, multicorrection, kFALSE, kDefEtaIncMin, kDefEtaIncMax,
			kassETAm, kassETAp, kassITS, kassTPCcl, kassTPCPIDcl, kassDCAr, kassDCAz, dEdxaclm, dEdxachm, kTRUE, kFALSE,-1);

   // (sma, 6.6.2017) Vary the ITS cut to +-3
   RegisterTaskNPEPbPb( centrMin,centrMax,newCentralitySelection,MCthere, isAOD, isBeauty, kDefTPCcl, kDefTPCclPID, kDefITScl, kDefDCAr, kDefDCAz, tpcl2, dEdxhm,  kDefTOFs, 3., AliHFEextraCuts::kBoth, kDefITSchi2percluster, kDefTPCclshared, etacorrection, multicorrection, kFALSE, kDefEtaIncMin, kDefEtaIncMax,
			kassETAm, kassETAp, kassITS, kassTPCcl, kassTPCPIDcl, kassDCAr, kassDCAz, dEdxaclm, dEdxachm, kTRUE, kFALSE,-1);

   // TPC low cut = -0.1 (tpcl2)
   RegisterTaskNPEPbPb( centrMin,centrMax,newCentralitySelection,MCthere, isAOD, isBeauty, kDefTPCcl, kDefTPCclPID, kDefITScl, kDefDCAr, kDefDCAz, tpcl2, dEdxhm,  kDefTOFs,  kDefITSs, AliHFEextraCuts::kBoth, kDefITSchi2percluster, kDefTPCclshared, etacorrection, multicorrection, kFALSE, kDefEtaIncMin, kDefEtaIncMax,
			kassETAm, kassETAp, kassITS, kassTPCcl, kassTPCPIDcl, kassDCAr, kassDCAz, dEdxaclm, dEdxachm, kTRUE, kFALSE,-1);
   // TPC low cut = 0.16 (tpcl3)
   RegisterTaskNPEPbPb( centrMin,centrMax,newCentralitySelection,MCthere, isAOD, isBeauty, kDefTPCcl, kDefTPCclPID, kDefITScl, kDefDCAr, kDefDCAz, tpcl3, dEdxhm,  kDefTOFs,  kDefITSs, AliHFEextraCuts::kBoth, kDefITSchi2percluster, kDefTPCclshared, etacorrection, multicorrection, kFALSE, kDefEtaIncMin, kDefEtaIncMax,
			kassETAm, kassETAp, kassITS, kassTPCcl, kassTPCPIDcl, kassDCAr, kassDCAz, dEdxaclm, dEdxachm, kTRUE, kFALSE,-1);
   // TPC low cut = -0.38 (tpcl4)
   RegisterTaskNPEPbPb( centrMin,centrMax,newCentralitySelection,MCthere, isAOD, isBeauty, kDefTPCcl, kDefTPCclPID, kDefITScl, kDefDCAr, kDefDCAz, tpcl4, dEdxhm,  kDefTOFs,  kDefITSs, AliHFEextraCuts::kBoth, kDefITSchi2percluster, kDefTPCclshared, etacorrection, multicorrection, kFALSE, kDefEtaIncMin, kDefEtaIncMax,
			kassETAm, kassETAp, kassITS, kassTPCcl, kassTPCPIDcl, kassDCAr, kassDCAz, dEdxaclm, dEdxachm, kTRUE, kFALSE,-1);
 }

  if(kNPEkf){
    // **************************************************************
    //
    // Use KF particle
    //
    // **************************************************************
    RegisterTaskNPEPbPb( centrMin,centrMax,newCentralitySelection,MCthere, isAOD, isBeauty, kDefTPCcl, kDefTPCclPID, kDefITScl, kDefDCAr, kDefDCAz, tpcl1, dEdxhm, kDefTOFs,0., AliHFEextraCuts::kBoth, kDefITSchi2percluster, kDefTPCclshared, etacorrection, multicorrection, kFALSE, kDefEtaIncMin, kDefEtaIncMax,
			 kassETAm, kassETAp, kassITS, kassTPCcl, kassTPCPIDcl, kassDCAr, kassDCAz, dEdxaclm, dEdxachm, kTRUE, kFALSE,-1,2,kFALSE,kFALSE,kFALSE,kTRUE);
  }

  return NULL;

}

//===============================================================================
//===============================================================================
AliAnalysisTask *RegisterTaskNPEPbPb(
                                     Int_t centrMin = 0, Int_t centrMax = 100,
                                     Bool_t newCentralitySelection = kTRUE, // kTRUE: new framework used; kFALSE: old framework used
                                     Bool_t useMC, Bool_t isAOD, Bool_t beauty,
				     Int_t tpcCls=120, Int_t tpcClsPID=80,
				     Int_t itsCls=4, Double_t dcaxy=1.0, Double_t dcaz=2.0,
				     Double_t *tpcdEdxcutlow=NULL, Double_t *tpcdEdxcuthigh=NULL,
				     Double_t tofs=3., Double_t itss=0., Int_t itshitpixel =AliHFEextraCuts::kBoth,
				     Double_t itschi2percluster = -1, Double_t tpcsharedcluster = 1.1,
				     Bool_t etacorr=kFALSE, Bool_t multicorr = kFALSE, Bool_t toflast = kFALSE,
				     Double_t etaIncMin = -0.8, Double_t etaIncMax = 0.8,
				     Double_t assETAm=-0.8, Double_t assETAp=0.8, Int_t assITS=2, Int_t assTPCcl=100,
				     Int_t assTPCPIDcl=80, Double_t assDCAr=1.0, Double_t assDCAz=2.0,
				     Double_t *assTPCSminus = NULL, Double_t *assTPCSplus=NULL,
				     Bool_t useCat1Tracks = kTRUE, Bool_t useCat2Tracks = kTRUE,
				     Int_t weightlevelback = -1,Int_t wei = 2,
				     Bool_t releasemcvx = kFALSE,
				     Bool_t ipCharge = kFALSE,
				     Bool_t ipOpp = kFALSE,
				     Bool_t usekfparticle = kFALSE)
{

  //
  // Cuts on the inclusive leg
  //
  Int_t idcaxy = (Int_t)(dcaxy*10.);
  Int_t idcaz = (Int_t)(dcaz*10.);
  Int_t tpclow = 0;
  // ------- to manage containers name with negative TPC low cut --------
  bool IsTPClowcutNegative = kFALSE;
  if(tpcdEdxcutlow)
  {
        tpclow = (Int_t) (tpcdEdxcutlow[0]*1000.);
        if(tpclow<0)
        {
                IsTPClowcutNegative = kTRUE;
                tpclow = 0 - tpclow;            // switched signed (ready to be used in the container name)
        }
  }
  // --------------------------------------------------------------------
  Int_t itofs = (Int_t)(tofs*10.);
  Int_t iitss = (Int_t)(itss*10.);
  Int_t ipixelany = itshitpixel;
  Int_t imult = multicorr ? 1 : 0;
  Int_t itofpos = toflast ? 1 : 0;

  //
  // Cuts on the associated leg
  //
  Int_t iassDCAr = (Int_t)(assDCAr*10);
  Int_t iassDCAz = (Int_t)(assDCAz*10);
  Int_t iassTPCSplus  = assTPCSplus ? (Int_t)(assTPCSplus[0]*1000) : 0;
  Int_t icat1 = useCat1Tracks ? 1 : 0;
  Int_t icat2 = useCat2Tracks ? 1 : 0;

  Bool_t nondefaultcentr = kFALSE;

  TString cweightsback("");
  if(weightlevelback>=0) {
    cweightsback += "Wa";
    cweightsback += weightlevelback;
  }

  TString cmvx("");
  if(releasemcvx) {
    cmvx += "MCVR";
  }

  TString kfp("");
  if(usekfparticle) {
    kfp += "kf";
  }

  if(beauty) {
    if(ipCharge && ipOpp) TString cbeauty("BeautyIPopp");
    else if(ipCharge) TString cbeauty("BeautyIPcrg");
    else if(!ipCharge) TString cbeauty("Beauty");
    else TString cbeauty("BeautyWrong");
  }
  else TString cbeauty("");

  // ------- to manage containers name with negative TPC low cut --------
  TString appendix = "";                                                                   // letter 'm' added in this point (after TPCs)
  if(IsTPClowcutNegative)      appendix+=TString::Format("SPD%d_incTPCc%dTPCp%dITS%dDCAr%dz%dTPCsm%dTOFs%dITSs%dm%dt%d_photTPCc%dTPCp%dITS%dDCAr%dDCAz%dTPCs%d%s%s%s%s",ipixelany,tpcCls,tpcClsPID,itsCls,idcaxy,idcaz,tpclow,itofs,iitss,imult,itofpos,assTPCcl,assTPCPIDcl,assITS,iassDCAr,iassDCAz,iassTPCSplus,cweightsback.Data(),cmvx.Data(),cbeauty.Data(),kfp.Data());
  else                         appendix+=TString::Format("SPD%d_incTPCc%dTPCp%dITS%dDCAr%dz%dTPCs%dTOFs%dITSs%dm%dt%d_photTPCc%dTPCp%dITS%dDCAr%dDCAz%dTPCs%d%s%s%s%s",ipixelany,tpcCls,tpcClsPID,itsCls,idcaxy,idcaz,tpclow,itofs,iitss,imult,itofpos,assTPCcl,assTPCPIDcl,assITS,iassDCAr,iassDCAz,iassTPCSplus,cweightsback.Data(),cmvx.Data(),cbeauty.Data(),kfp.Data());
  //TString appendix(TString::Format("SPD%d_incTPCc%dTPCp%dITS%dDCAr%dz%dTPCs%dTOFs%dITSs%dm%dt%d_photTPCc%dTPCp%dITS%dDCAr%dDCAz%dTPCs%d%s%s%s%s",ipixelany,tpcCls,tpcClsPID,itsCls,idcaxy,idcaz,tpclow,itofs,iitss,imult,itofpos,assTPCcl,assTPCPIDcl,assITS,iassDCAr,iassDCAz,iassTPCSplus,cweightsback.Data(),cmvx.Data(),cbeauty.Data(),kfp.Data()));      // old version
  // --------------------------------------------------------------------

  printf("Add macro appendix %s\n", appendix.Data());

  // --------------------------------------------------------------------
  // GRID version
  if(useMC&&!gROOT->GetListOfGlobalFunctions()->FindObject("ConfigWeightFactors")) gROOT->LoadMacro("$ALICE_PHYSICS/PWGHF/hfe/macros/configs/ConfigWeightFactors.C");
  if(!gROOT->GetListOfGlobalFunctions()->FindObject("ConfigHFEnpePbPb5TeV"))gROOT->LoadMacro("$ALICE_PHYSICS/PWGHF/hfe/macros/configs/PbPb/ConfigHFEnpePbPb5TeV.C");
  // GSI version
  //if(useMC&&!gROOT->GetListOfGlobalFunctions()->FindObject("ConfigWeightFactors")) gROOT->LoadMacro("$TRAIN_ROOT/util/hfe/configs/ConfigWeightFactors.C");
  //if(!gROOT->GetListOfGlobalFunctions()->FindObject("ConfigHFEnpePbPb5TeV")) gROOT->LoadMacro("$TRAIN_ROOT/util/hfe/configs/ConfigHFEnpePbPb5TeV.C");
  // --------------------------------------------------------------------

  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  AliAnalysisDataContainer *cinput  = mgr->GetCommonInputContainer();

    AliAnalysisTaskHFE *task = ConfigHFEnpePbPb5TeV(useMC, isAOD, appendix, tpcCls, tpcClsPID, itsCls, dcaxy, dcaz, tpcdEdxcutlow, tpcdEdxcuthigh, tofs, 0, itss, itshitpixel, itschi2percluster, tpcsharedcluster, etacorr, multicorr, toflast, etaIncMin, etaIncMax,
					      assETAm, assETAp, assITS, assTPCcl, assTPCPIDcl,
					      assDCAr, assDCAz, assTPCSminus, assTPCSplus,
					      useCat1Tracks, useCat2Tracks, weightlevelback,usekfparticle);
  // old config file
  //AliAnalysisTaskHFE *task = ConfigHFEnpePbPb(useMC, isAOD, appendix, tpcCls, tpcClsPID, itsCls, dcaxy, dcaz, tpcdEdxcutlow, tpcdEdxcuthigh, tofs, 0, itss, itshitpixel, itschi2percluster, tpcsharedcluster, etacorr, multicorr, toflast, etaIncMin, etaIncMax,
  //					      assETAm, assETAp, assITS, assTPCcl, assTPCPIDcl,
  //					      assDCAr, assDCAz, assTPCSminus, assTPCSplus,
  //					      useCat1Tracks, useCat2Tracks, weightlevelback,usekfparticle);

  if(isAOD)
    task->SetAODAnalysis();
  else
    task->SetESDAnalysis();

  if (useMC)	task->SetHasMCData(kTRUE);
  else		task->SetHasMCData(kFALSE);

  if(useMC&&(beauty || (weightlevelback>=0))) ConfigWeightFactors(task,kFALSE,wei);//2;For default PbPb

  // ----- centrality selection -----
  task->SetCentralityCheck(newCentralitySelection,"V0M");
  task->SetCentralityInterval(centrMin,centrMax);               // all events outside the desired centrality interval are rejected
  // --------------------------------
  // ----- trigger selecton ---------
  if(!newCentralitySelection)   task->SelectCollisionCandidates(AliVEvent::kMB | AliVEvent::kCentral | AliVEvent::kSemiCentral); // old framework
  if(newCentralitySelection)    task->SelectCollisionCandidates(AliVEvent::kINT7);                                               // new framework
  // --------------------------------

  TString containerName = mgr->GetCommonFileName();
  containerName += ":HFEtask";
  containerName += appendix.Data();
  printf("container name: %s\n", containerName.Data());

  //create data containers
  task->ConnectOutput(1, mgr->CreateContainer(Form("HFE_Results_%s", appendix.Data()), TList::Class(), AliAnalysisManager::kOutputContainer, containerName.Data()));
  task->ConnectOutput(2, mgr->CreateContainer(Form("HFE_QA_%s", appendix.Data()), TList::Class(), AliAnalysisManager::kOutputContainer, containerName.Data()));
  mgr->ConnectInput(task,  0, cinput );

  mgr->AddTask(task);

  return NULL;
}

<commit_msg>remove addtask HFE run2 PbPb<commit_after><|endoftext|>