<commit_before>// This file is part of the dune-gdt project:
//   https://github.com/dune-community/dune-gdt
// Copyright 2010-2017 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//      or  GPL-2.0+ (http://opensource.org/licenses/gpl-license)
//          with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
//   Felix Schindler (2016 - 2017)
//   Rene Milk       (2016 - 2017)
//   Tobias Leibner  (2016)

#ifndef DUNE_GDT_TIMESTEPPER_FRACTIONAL_STEP_HH
#define DUNE_GDT_TIMESTEPPER_FRACTIONAL_STEP_HH

#include <utility>

#include <dune/gdt/operators/interfaces.hh>

#include <dune/xt/common/memory.hh>
#include <dune/xt/common/string.hh>
#include <dune/xt/la/container.hh>

#include "interface.hh"

namespace Dune {
namespace GDT {

/**
 * Takes two time steppers and performs a simple fractional step scheme (see e.g. LeVeque, "Finite Volume Methods for
 * Hyperbolic Problems", 2002, Section 17.1. In each time step t, the first stepper is applied up to time t+dt and the
 * result is taken as input for the second time stepper, which is also applied up to time t+dt. Initial values and time
 * are taken from the first time stepper.
 */
template <class FirstStepperImp, class SecondStepperImp>
class FractionalTimeStepper : public TimeStepperInterface<typename FirstStepperImp::DiscreteFunctionType,
                                                          typename FirstStepperImp::TimeFieldType>
{
  typedef TimeStepperInterface<typename FirstStepperImp::DiscreteFunctionType, typename FirstStepperImp::TimeFieldType>
      BaseType;

public:
  using typename BaseType::DiscreteFunctionType;
  using typename BaseType::TimeFieldType;
  using typename BaseType::DomainFieldType;
  using typename BaseType::RangeFieldType;
  using typename BaseType::SolutionType;

  typedef FirstStepperImp FirstStepperType;
  typedef SecondStepperImp SecondStepperType;

  using BaseType::current_solution;
  using BaseType::current_time;
  using BaseType::solution;

  FractionalTimeStepper(FirstStepperType& first_stepper, SecondStepperType& second_stepper)
    : BaseType(first_stepper.current_time(), first_stepper.current_solution())
    , first_stepper_(first_stepper)
    , second_stepper_(second_stepper)
  {
    first_stepper_.set_current_solution_pointer(current_solution());
    first_stepper_.set_solution_pointer(solution());
    second_stepper_.set_current_solution_pointer(current_solution());
    second_stepper_.set_solution_pointer(solution());
  } // constructor

  TimeFieldType step(const TimeFieldType dt, const TimeFieldType max_dt) override final
  {
    auto& t = current_time();
    const TimeFieldType actual_dt = std::min(dt, max_dt);
    const auto dt_1 = first_stepper_.solve(t + actual_dt, dt, -1, false);
    const auto dt_2 = second_stepper_.solve(t + actual_dt, dt_1, -1, false);
    t += actual_dt;
    return dt_2;
  } // ... step(...)

private:
  FirstStepperType& first_stepper_;
  SecondStepperType& second_stepper_;
}; // class FractionalTimeStepper

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_TIMESTEPPER_FRACTIONAL_STEP_HH
<commit_msg>[timestepper] add strang splitting<commit_after>// This file is part of the dune-gdt project:
//   https://github.com/dune-community/dune-gdt
// Copyright 2010-2017 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//      or  GPL-2.0+ (http://opensource.org/licenses/gpl-license)
//          with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
//   Felix Schindler (2016 - 2017)
//   Rene Milk       (2016 - 2017)
//   Tobias Leibner  (2016)

#ifndef DUNE_GDT_TIMESTEPPER_FRACTIONAL_STEP_HH
#define DUNE_GDT_TIMESTEPPER_FRACTIONAL_STEP_HH

#include <utility>

#include <dune/gdt/operators/interfaces.hh>

#include <dune/xt/common/memory.hh>
#include <dune/xt/common/string.hh>
#include <dune/xt/la/container.hh>

#include "interface.hh"

namespace Dune {
namespace GDT {

/**
 * Takes two time steppers and performs a simple fractional step scheme (see e.g. LeVeque, "Finite Volume Methods for
 * Hyperbolic Problems", 2002, Section 17.1). In each time step t, the first stepper is applied up to time t+dt and the
 * result is taken as input for the second time stepper, which is also applied up to time t+dt. Initial values and time
 * are taken from the first time stepper.
 */
template <class FirstStepperImp, class SecondStepperImp>
class FractionalTimeStepper : public TimeStepperInterface<typename FirstStepperImp::DiscreteFunctionType,
                                                          typename FirstStepperImp::TimeFieldType>
{
  typedef TimeStepperInterface<typename FirstStepperImp::DiscreteFunctionType, typename FirstStepperImp::TimeFieldType>
      BaseType;

public:
  using typename BaseType::DiscreteFunctionType;
  using typename BaseType::TimeFieldType;
  using typename BaseType::DomainFieldType;
  using typename BaseType::RangeFieldType;
  using typename BaseType::SolutionType;

  typedef FirstStepperImp FirstStepperType;
  typedef SecondStepperImp SecondStepperType;

  using BaseType::current_solution;
  using BaseType::current_time;
  using BaseType::solution;

  FractionalTimeStepper(FirstStepperType& first_stepper, SecondStepperType& second_stepper)
    : BaseType(first_stepper.current_time(), first_stepper.current_solution())
    , first_stepper_(first_stepper)
    , second_stepper_(second_stepper)
  {
    first_stepper_.set_current_solution_pointer(current_solution());
    first_stepper_.set_solution_pointer(solution());
    second_stepper_.set_current_solution_pointer(current_solution());
    second_stepper_.set_solution_pointer(solution());
  } // constructor

  TimeFieldType step(const TimeFieldType dt, const TimeFieldType max_dt) override final
  {
    auto& t = current_time();
    const TimeFieldType actual_dt = std::min(dt, max_dt);
    const auto dt_1 = first_stepper_.solve(t + actual_dt, dt, -1, false);
    const auto dt_2 = second_stepper_.solve(t + actual_dt, dt_1, -1, false);
    t += actual_dt;
    return dt_2;
  } // ... step(...)

private:
  FirstStepperType& first_stepper_;
  SecondStepperType& second_stepper_;
}; // class FractionalTimeStepper

/**
 * Takes two time steppers and performs a strang splitting fractional step scheme (see e.g. LeVeque, "Finite Volume
 * Methods for
 * Hyperbolic Problems", 2002, Section 17.1). In each time step t, the first stepper is applied up to time t+dt/2, then
 * the
 * second time stepper is applied up to time t+dt, then the first stepper is applied again up to time t+dt. Initial
 * values and time
 * are taken from the first time stepper.
 */
template <class FirstStepperImp, class SecondStepperImp>
class StrangSplittingTimeStepper : public TimeStepperInterface<typename FirstStepperImp::DiscreteFunctionType,
                                                               typename FirstStepperImp::TimeFieldType>
{
  typedef TimeStepperInterface<typename FirstStepperImp::DiscreteFunctionType, typename FirstStepperImp::TimeFieldType>
      BaseType;

public:
  using typename BaseType::DiscreteFunctionType;
  using typename BaseType::TimeFieldType;
  using typename BaseType::DomainFieldType;
  using typename BaseType::RangeFieldType;
  using typename BaseType::SolutionType;

  typedef FirstStepperImp FirstStepperType;
  typedef SecondStepperImp SecondStepperType;

  using BaseType::current_solution;
  using BaseType::current_time;
  using BaseType::solution;

  StrangSplittingTimeStepper(FirstStepperType& first_stepper, SecondStepperType& second_stepper)
    : BaseType(first_stepper.current_time(), first_stepper.current_solution())
    , first_stepper_(first_stepper)
    , second_stepper_(second_stepper)
  {
    first_stepper_.set_current_solution_pointer(current_solution());
    first_stepper_.set_solution_pointer(solution());
    second_stepper_.set_current_solution_pointer(current_solution());
    second_stepper_.set_solution_pointer(solution());
  } // constructor

  TimeFieldType step(const TimeFieldType dt, const TimeFieldType max_dt) override final
  {
    auto& t = current_time();
    const TimeFieldType actual_dt = std::min(dt, max_dt);
    const auto dt_1 = first_stepper_.solve(t + actual_dt / 2, actual_dt / 2, -1, false);
    const auto dt_2 = second_stepper_.solve(t + actual_dt, actual_dt, -1, false);
    const auto dt_3 = first_stepper_.solve(t + actual_dt, actual_dt / 2, -1, false);
    t += actual_dt;
    return dt;
  } // ... step(...)

private:
  FirstStepperType& first_stepper_;
  SecondStepperType& second_stepper_;
}; // class FractionalTimeStepper

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_TIMESTEPPER_FRACTIONAL_STEP_HH
<|endoftext|>


<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//

#include <BALL/STRUCTURE/assignBondOrderProcessor.h>
#include <BALL/FORMAT/MOL2File.h>
#include <BALL/KERNEL/system.h>

#include <BALL/FORMAT/commandlineParser.h>
#include <iostream>
#include "version.h"

using namespace std;
using namespace BALL;

int main (int argc, char **argv)
{
	// instantiate CommandlineParser object supplying
	// - tool name
	// - short description
	// - version string
	// - build date
	// - category
	CommandlineParser parpars("BondOrderAssigner", "computes bond order assignments for a ligand ", VERSION, String(__DATE__), "Preparation");

	// we register an input file parameter
	// - CLI switch
	// - description
	// - Inputfile
	// - required
	parpars.registerParameter("i", "input mol2-file", INFILE, true);

	// we register an output file parameter
	// - description
	// - Outputfile
	// - required
	parpars.registerParameter("o", "output mol2-file name for first solution", STRING, true, "", true);

	parpars.registerParameter("o_id", "output id", STRING, true, "", true);

	parpars.registerParameter("o_dir", "output directory for 2nd to last solution", STRING, true, "", true);

	// register String parameter for supplying max number of solutions
	parpars.registerParameter("max_sol", "maximal number of assignments solutions to compute", INT, false, 25);
	parpars.setParameterRestrictions("max_sol", 0, 100);

	// parameter for computing sub-optimal solutions
	parpars.registerFlag("non_opt", "compute sub-optimal assignments as well", false);

	// option for hydrogen addition
	// TODO: test and then release :-)
	//parpars.registerFlag("add_hyd", "add hydrogens as well", false);

	// choice of penalty table
	parpars.registerParameter("scr_pen", "penalty table", STRING, false, "Antechamber");
	list<String> ini_files;
	ini_files.push_back("Antechamber");
	ini_files.push_back("BALL");
	parpars.setParameterRestrictions("scr_pen", ini_files);

  // the manual
	String man = "This tool computes optimal and sub-optimal bond order assignments based on an atomic penalty function for a given ligand in mol2 file format.\n\nOptional parameters are the maximal number of solutions to be computed ('-max_sol'), the penalty table specifiying the atomic penalty rules ('-scr_pen'), a flag indicating if sub-optimal solutions should be computed as well ('-non_opt') and a flag indicating if hydrogens should be computed as well ('-add_hyd').\n\nOutput of this tool is a number of mol2 files each containing one bond order assignment.\n\nTo upload an input file please use the upload tool (Get Data -> Upload File).\n\n**Further information and help** can be found in our wiki http://ball-trac.bioinf.uni-sb.de/wiki/ballaxy/BOAConstructor_Help.\n\nPlease cite the following: Dehof, A.K., Rurainski, A., Bui, Q.B.A., Boecker, S., Lenhof, H.-P. & Hildebrandt, A. (2011). Automated Bond Order Assignment as an Optimization Problem. Bioinformatics, 2011";

	parpars.setToolManual(man);

	// here we set the types of I/O files, for example sdf is also allowed
	parpars.setSupportedFormats("i","mol2");
	parpars.setSupportedFormats("o","mol2");

	parpars.parse(argc, argv);

	// read the input
	MOL2File f0;
	f0.open(parpars.get("i"));
	System system;
	f0 >> system;

	AssignBondOrderProcessor abop;

	// the combination of the following two options causes the computation of all optimal solutions
	abop.options.setInteger(AssignBondOrderProcessor::Option::MAX_NUMBER_OF_SOLUTIONS, 0);
	abop.options.setBool(AssignBondOrderProcessor::Option::COMPUTE_ALSO_NON_OPTIMAL_SOLUTIONS, false);

	if (parpars.has("max_sol"))
	{
		int max_sol = parpars.get("max_sol").toInt();
		//cout << "   limit number of solutions to " << max_sol << endl;
		abop.options.setInteger(AssignBondOrderProcessor::Option::MAX_NUMBER_OF_SOLUTIONS, String(max_sol).toInt());
	}

	bool non_opt = false;
	if (parpars.has("non_opt"))
	{
		non_opt = parpars.get("non_opt").toBool();
		//if (non_opt)
		//	cout << "   Compute also non-optimal solutions." << endl;
		abop.options.setBool(AssignBondOrderProcessor::Option::COMPUTE_ALSO_NON_OPTIMAL_SOLUTIONS, non_opt);
	}

	if (parpars.has("add_hyd"))
	{
		bool add_hyd = parpars.get("add_hyd").toBool();
		//if (add_hyd)
		//	cout << "   Add hydrogens as well." << endl;
		abop.options.setBool(AssignBondOrderProcessor::Option::ADD_HYDROGENS, add_hyd);
	}

	if (parpars.has("scr_pen"))
	{
		String penalty_table = parpars.get("scr_pen");
		//cout << "   Use penalty table " << penalty_table << endl;
		if (penalty_table == "Antechamber")
			abop.options[AssignBondOrderProcessor::Option::INIFile] = "/bond_lengths/BondOrderGAFF.xml";
		else
			abop.options[AssignBondOrderProcessor::Option::INIFile] = "/bond_lengths/BondOrder.xml";
	}

	// set the solver
	//abop.options.set(AssignBondOrderProcessor::Option::ALGORITHM, AssignBondOrderProcessor::Algorithm::A_STAR);
	abop.options.set(AssignBondOrderProcessor::Option::ALGORITHM, AssignBondOrderProcessor::Algorithm::FPT);
	abop.options.dump();
	system.apply(abop);
	Size num_of_sols = abop.getNumberOfComputedSolutions();

	if (num_of_sols == 0)
	{
		Log << "No valid bond order assignment found!" << endl;
		return 1;
	}
	else
	{
		//Log << "Found " << num_of_sols << " solutions:" << endl;
		for (Size i=0; (i<num_of_sols) && (non_opt || (abop.getTotalPenalty(0)==abop.getTotalPenalty(i))); i++)
		{
			Log << "   Solution " << i << " has penalty " << abop.getTotalPenalty(i) << endl;

			// apply the solution
			if (abop.apply(i))
			{
				String outfile_name = (i == 0) ? String(parpars.get("o"))
				                               :   String(parpars.get("o_dir")) + "/primary_"
				                                 + String(parpars.get("o_id"))  + "_solution" + String(i)
				                                 + "_visible_mol2";
				//Log << "   Writing solution " << String(i) << " as " << outfile_name << endl;
				//	GenericMolFile* outfile = MolFileFactory::open(outfile_name, ios::out);
				MOL2File outfile(outfile_name, ios::out);

				if (outfile.bad())
				{
					Log.error() << endl << "cannot write file " << outfile_name << endl;
					return 2;
				}

				system.beginMolecule()->setProperty("BOA_Constructor_penalty", abop.getTotalPenalty(i));

				outfile << system;
				outfile.close();
			}
		}
	}
	Log << "done." << endl;

	return 0;
}

<commit_msg>work on galaxy specific multi outfile parameters<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//

#include <BALL/STRUCTURE/assignBondOrderProcessor.h>
#include <BALL/FORMAT/MOL2File.h>
#include <BALL/KERNEL/system.h>

#include <BALL/FORMAT/commandlineParser.h>
#include <iostream>
#include "version.h"

using namespace std;
using namespace BALL;

int main (int argc, char **argv)
{
	// instantiate CommandlineParser object supplying
	// - tool name
	// - short description
	// - version string
	// - build date
	// - category
	CommandlineParser parpars("BondOrderAssigner", "computes bond order assignments for a ligand ", VERSION, String(__DATE__), "Preparation");

	// we register an input file parameter
	// - CLI switch
	// - description
	// - Inputfile
	// - required
	parpars.registerParameter("i", "input mol2-file", INFILE, true);

	// we register an output file parameter
	// - description
	// - Outputfile
	// - required
	parpars.registerParameter("o", "output mol2-file name for first solution", STRING, true, "", true);

	// parameters for galaxy for handling multiple output files
	parpars.registerParameter("o_id", "output id", STRING, false, "", true);
	// need to be hidden in command line mode
	parpars.setParameterAsAdvanced("o_id");

	// parameters for galaxy for handling multiple output files
	parpars.registerParameter("o_dir", "output directory for 2nd to last solution", STRING, false, "", true);
	// need to be hidden in command line mode
	parpars.setParameterAsAdvanced("o_dir");

	// register String parameter for supplying max number of solutions
	parpars.registerParameter("max_sol", "maximal number of assignments solutions to compute", INT, false, 25);
	parpars.setParameterRestrictions("max_sol", 0, 100);

	// parameter for computing sub-optimal solutions
	parpars.registerFlag("non_opt", "compute sub-optimal assignments as well", false);

	// option for hydrogen addition
	// TODO: test and then release :-)
	//parpars.registerFlag("add_hyd", "add hydrogens as well", false);

	// choice of penalty table
	parpars.registerParameter("scr_pen", "penalty table", STRING, false, "Antechamber");
	list<String> ini_files;
	ini_files.push_back("Antechamber");
	ini_files.push_back("BALL");
	parpars.setParameterRestrictions("scr_pen", ini_files);

  // the manual
	String man = "This tool computes optimal and sub-optimal bond order assignments based on an atomic penalty function for a given ligand in mol2 file format.\n\nOptional parameters are the maximal number of solutions to be computed ('-max_sol'), the penalty table specifiying the atomic penalty rules ('-scr_pen'), a flag indicating if sub-optimal solutions should be computed as well ('-non_opt') and a flag indicating if hydrogens should be computed as well ('-add_hyd').\n\nOutput of this tool is a number of mol2 files each containing one bond order assignment.\n\nTo upload an input file please use the upload tool (Get Data -> Upload File).\n\n**Further information and help** can be found in our wiki http://ball-trac.bioinf.uni-sb.de/wiki/ballaxy/BOAConstructor_Help.\n\nPlease cite the following: Dehof, A.K., Rurainski, A., Bui, Q.B.A., Boecker, S., Lenhof, H.-P. & Hildebrandt, A. (2011). Automated Bond Order Assignment as an Optimization Problem. Bioinformatics, 2011";

	parpars.setToolManual(man);

	// here we set the types of I/O files, for example sdf is also allowed
	parpars.setSupportedFormats("i","mol2");
	parpars.setSupportedFormats("o","mol2");

	parpars.parse(argc, argv);

	// read the input
	MOL2File f0;
	f0.open(parpars.get("i"));
	System system;
	f0 >> system;

	AssignBondOrderProcessor abop;

	// the combination of the following two options causes the computation of all optimal solutions
	abop.options.setInteger(AssignBondOrderProcessor::Option::MAX_NUMBER_OF_SOLUTIONS, 0);
	abop.options.setBool(AssignBondOrderProcessor::Option::COMPUTE_ALSO_NON_OPTIMAL_SOLUTIONS, false);

	if (parpars.has("max_sol"))
	{
		int max_sol = parpars.get("max_sol").toInt();
		//cout << "   limit number of solutions to " << max_sol << endl;
		abop.options.setInteger(AssignBondOrderProcessor::Option::MAX_NUMBER_OF_SOLUTIONS, String(max_sol).toInt());
	}

	bool non_opt = false;
	if (parpars.has("non_opt"))
	{
		non_opt = parpars.get("non_opt").toBool();
		//if (non_opt)
		//	cout << "   Compute also non-optimal solutions." << endl;
		abop.options.setBool(AssignBondOrderProcessor::Option::COMPUTE_ALSO_NON_OPTIMAL_SOLUTIONS, non_opt);
	}

	if (parpars.has("add_hyd"))
	{
		bool add_hyd = parpars.get("add_hyd").toBool();
		//if (add_hyd)
		//	cout << "   Add hydrogens as well." << endl;
		abop.options.setBool(AssignBondOrderProcessor::Option::ADD_HYDROGENS, add_hyd);
	}

	if (parpars.has("scr_pen"))
	{
		String penalty_table = parpars.get("scr_pen");
		//cout << "   Use penalty table " << penalty_table << endl;
		if (penalty_table == "Antechamber")
			abop.options[AssignBondOrderProcessor::Option::INIFile] = "/bond_lengths/BondOrderGAFF.xml";
		else
			abop.options[AssignBondOrderProcessor::Option::INIFile] = "/bond_lengths/BondOrder.xml";
	}

	// set the solver
	//abop.options.set(AssignBondOrderProcessor::Option::ALGORITHM, AssignBondOrderProcessor::Algorithm::A_STAR);
	abop.options.set(AssignBondOrderProcessor::Option::ALGORITHM, AssignBondOrderProcessor::Algorithm::FPT);
	abop.options.dump();
	system.apply(abop);
	Size num_of_sols = abop.getNumberOfComputedSolutions();

	if (num_of_sols == 0)
	{
		Log << "No valid bond order assignment found!" << endl;
		return 1;
	}
	else
	{
		// called as command line or e.g. via galaxy?
		bool is_cmd =    !parpars.has("env")
			            || ((parpars.has("env") && parpars.get("env")=="cmdline"));

		//Log << "Found " << num_of_sols << " solutions:" << endl;
		for (Size i=0; (i<num_of_sols) && (non_opt || (abop.getTotalPenalty(0)==abop.getTotalPenalty(i))); i++)
		{
			Log << "   Solution " << i << " has penalty " << abop.getTotalPenalty(i) << " ... ";

			// apply the solution
			if (abop.apply(i))
			{
				// create the output name
				String outfile_name = String(parpars.get("o")) + "solution_"
															+ String(i) + ".mol2";
				if (parpars.has("o_dir"))
				{
					outfile_name =  String(parpars.get("o_dir")) + "/" + outfile_name;
				}

				// NOTE: Galaxy requires this strange naming convention
				//       including the fact, that zero-th element has a different name
				if (!is_cmd)
				{
					outfile_name = (i == 0) ? String(parpars.get("o"))
				                               :   String(parpars.get("o_dir")) + "/primary_"
				                                 + String(parpars.get("o_id"))  + "_solution_" + String(i)
				                                 + "_visible_mol2";
				}
				//Log << "   Writing solution " << String(i) << " as " << outfile_name << endl;
				//	GenericMolFile* outfile = MolFileFactory::open(outfile_name, ios::out);
				MOL2File outfile(outfile_name, ios::out);

				if (outfile.bad())
				{
					Log.error() << endl << "cannot write file " << outfile_name << endl;
					return 2;
				}

				system.beginMolecule()->setProperty("BOA_Constructor_penalty", abop.getTotalPenalty(i));

				outfile << system;
				outfile.close();
			}
		}
	}
	Log << "done." << endl;

	return 0;
}

<|endoftext|>


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

#include "chrome/browser/chromeos/login/webui_login_view.h"

#include "base/bind.h"
#include "base/callback.h"
#include "base/i18n/rtl.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/chromeos/accessibility_util.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/login_library.h"
#include "chrome/browser/chromeos/login/proxy_settings_dialog.h"
#include "chrome/browser/chromeos/login/webui_login_display.h"
#include "chrome/browser/chromeos/status/clock_menu_button.h"
#include "chrome/browser/chromeos/status/input_method_menu_button.h"
#include "chrome/browser/chromeos/status/network_menu_button.h"
#include "chrome/browser/chromeos/status/status_area_view.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/views/dom_view.h"
#include "chrome/common/render_messages.h"
#include "content/browser/renderer_host/render_view_host_observer.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "ui/gfx/rect.h"
#include "ui/gfx/size.h"
#include "views/desktop/desktop_window_view.h"
#include "views/widget/widget.h"

#if defined(TOOLKIT_USES_GTK)
#include "chrome/browser/chromeos/wm_ipc.h"
#include "views/widget/native_widget_gtk.h"
#endif

#if defined(USE_VIRTUAL_KEYBOARD)
#include "chrome/browser/ui/virtual_keyboard/virtual_keyboard_manager.h"
#endif

namespace {

const char kViewClassName[] = "browser/chromeos/login/WebUILoginView";

// These strings must be kept in sync with handleAccelerator() in oobe.js.
const char kAccelNameAccessibility[] = "accessibility";
const char kAccelNameCancel[] = "cancel";
const char kAccelNameEnrollment[] = "enrollment";

// Observes IPC messages from the FrameSniffer and notifies JS if error
// appears.
class SnifferObserver : public RenderViewHostObserver {
 public:
  SnifferObserver(RenderViewHost* host, WebUI* webui)
      : RenderViewHostObserver(host), webui_(webui) {
    DCHECK(webui_);
    Send(new ChromeViewMsg_StartFrameSniffer(routing_id(),
                                             UTF8ToUTF16("gaia-frame")));
  }

  virtual ~SnifferObserver() {}

  // IPC::Channel::Listener implementation.
  virtual bool OnMessageReceived(const IPC::Message& message) {
    bool handled = true;
    IPC_BEGIN_MESSAGE_MAP(SnifferObserver, message)
      IPC_MESSAGE_HANDLER(ChromeViewHostMsg_FrameLoadingError, OnError)
      IPC_MESSAGE_UNHANDLED(handled = false)
    IPC_END_MESSAGE_MAP()
    return handled;
  }

 private:
  void OnError(int error) {
    base::FundamentalValue error_value(error);
    webui_->CallJavascriptFunction("login.OfflineMessageScreen.onFrameError",
                                   error_value);
  }

  WebUI* webui_;
};

// A View class which places its first child at the right most position.
class RightAlignedView : public views::View {
 public:
  virtual void Layout() OVERRIDE;
  virtual void ChildPreferredSizeChanged(View* child) OVERRIDE;
};

void RightAlignedView::Layout() {
  if (has_children()) {
    views::View* child = child_at(0);
    gfx::Size preferred_size = child->GetPreferredSize();
    child->SetBounds(width() - preferred_size.width(),
                     0, preferred_size.width(), preferred_size.height());
  }
}

void RightAlignedView::ChildPreferredSizeChanged(View* child) {
  Layout();
}

}  // namespace

namespace chromeos {

// static
const int WebUILoginView::kStatusAreaCornerPadding = 5;

// WebUILoginView public: ------------------------------------------------------

WebUILoginView::WebUILoginView()
    : status_area_(NULL),
      webui_login_(NULL),
      status_window_(NULL),
      host_window_frozen_(false),
      status_area_visibility_on_init_(true) {
#if defined(USE_VIRTUAL_KEYBOARD)
  // Make sure the singleton VirtualKeyboardManager object is created.
  VirtualKeyboardManager::GetInstance();
#endif
  accel_map_[views::Accelerator(ui::VKEY_Z, false, true, true)] =
      kAccelNameAccessibility;
  accel_map_[views::Accelerator(ui::VKEY_ESCAPE, false, false, false)] =
      kAccelNameCancel;
  accel_map_[views::Accelerator(ui::VKEY_E, false, true, true)] =
      kAccelNameEnrollment;

  for (AccelMap::iterator i(accel_map_.begin()); i != accel_map_.end(); ++i)
    AddAccelerator(i->first);
}

WebUILoginView::~WebUILoginView() {
  if (status_window_)
    status_window_->CloseNow();
  status_window_ = NULL;
}

void WebUILoginView::Init() {

  webui_login_ = new DOMView();
  AddChildView(webui_login_);
  webui_login_->Init(ProfileManager::GetDefaultProfile(), NULL);
  webui_login_->SetVisible(true);

  TabContents* tab_contents = webui_login_->dom_contents()->tab_contents();
  tab_contents->set_delegate(this);

  tab_watcher_.reset(new TabFirstRenderWatcher(tab_contents, this));
}

std::string WebUILoginView::GetClassName() const {
  return kViewClassName;
}

bool WebUILoginView::AcceleratorPressed(
    const views::Accelerator& accelerator) {
  AccelMap::const_iterator entry = accel_map_.find(accelerator);
  if (entry == accel_map_.end())
    return false;

  if (!webui_login_)
    return true;

  WebUI* web_ui = webui_login_->dom_contents()->tab_contents()->web_ui();
  if (web_ui) {
    base::StringValue accel_name(entry->second);
    web_ui->CallJavascriptFunction("cr.ui.Oobe.handleAccelerator",
                                   accel_name);
  }

  return true;
}

gfx::NativeWindow WebUILoginView::GetNativeWindow() const {
  return GetWidget()->GetNativeWindow();
}

void WebUILoginView::OnWindowCreated() {
#if defined(TOOLKIT_USES_GTK)
  // Freezes host window update until the tab is rendered.
  host_window_frozen_ = static_cast<views::NativeWidgetGtk*>(
      GetWidget()->native_widget())->SuppressFreezeUpdates();
#else
  // TODO(saintlou): Unclear if we need this for the !gtk case.
#endif
}

void WebUILoginView::UpdateWindowType() {
#if defined(TOOLKIT_USES_GTK)
  std::vector<int> params;
  WmIpc::instance()->SetWindowType(
      GTK_WIDGET(GetNativeWindow()),
      WM_IPC_WINDOW_LOGIN_WEBUI,
      &params);
#endif
}

void WebUILoginView::LoadURL(const GURL & url) {
  webui_login_->LoadURL(url);
  webui_login_->RequestFocus();
}

WebUI* WebUILoginView::GetWebUI() {
  return webui_login_->dom_contents()->tab_contents()->web_ui();
}

void WebUILoginView::SetStatusAreaEnabled(bool enable) {
  if (status_area_)
    status_area_->MakeButtonsActive(enable);
}

void WebUILoginView::SetStatusAreaVisible(bool visible) {
  if (status_area_)
    status_area_->SetVisible(visible);
  else
    status_area_visibility_on_init_ = visible;
}

// WebUILoginView protected: ---------------------------------------------------

void WebUILoginView::Layout() {
  DCHECK(webui_login_);
  webui_login_->SetBoundsRect(bounds());
}

void WebUILoginView::ChildPreferredSizeChanged(View* child) {
  Layout();
  SchedulePaint();
}

Profile* WebUILoginView::GetProfile() const {
  return NULL;
}

void WebUILoginView::ExecuteBrowserCommand(int id) const {
}

bool WebUILoginView::ShouldOpenButtonOptions(
    const views::View* button_view) const {
  if (button_view == status_area_->network_view())
    return true;

  if (button_view == status_area_->clock_view() ||
      button_view == status_area_->input_method_view())
    return false;

  return true;
}

void WebUILoginView::OpenButtonOptions(const views::View* button_view) {
  if (button_view == status_area_->network_view()) {
    if (proxy_settings_dialog_.get() == NULL) {
      proxy_settings_dialog_.reset(new ProxySettingsDialog(
          this, GetNativeWindow()));
    }
    proxy_settings_dialog_->Show();
  }
}

StatusAreaHost::ScreenMode WebUILoginView::GetScreenMode() const {
  return kWebUILoginMode;
}

StatusAreaHost::TextStyle WebUILoginView::GetTextStyle() const {
  return kGrayPlain;
}

void WebUILoginView::ButtonVisibilityChanged(views::View* button_view) {
  status_area_->ButtonVisibilityChanged(button_view);
}

void WebUILoginView::OnDialogClosed() {
}

void WebUILoginView::OnLocaleChanged() {
  // Proxy settings dialog contains localized strings.
  proxy_settings_dialog_.reset();
  SchedulePaint();
}

void WebUILoginView::OnRenderHostCreated(RenderViewHost* host) {
  new SnifferObserver(host, GetWebUI());
}

void WebUILoginView::OnTabMainFrameLoaded() {
  VLOG(1) << "WebUI login main frame loaded.";
}

void WebUILoginView::OnTabMainFrameFirstRender() {
  VLOG(1) << "WebUI login main frame rendered.";
  InitStatusArea();

#if defined(TOOLKIT_USES_GTK)
  if (host_window_frozen_) {
    host_window_frozen_ = false;

    // Unfreezes the host window since tab is rendereed now.
    views::NativeWidgetGtk::UpdateFreezeUpdatesProperty(
        GetNativeWindow(), false);
  }
#endif

  bool emit_login_visible = false;

  // In aura or views-desktop environment, there will be no window-manager. So
  // chrome needs to emit the 'login-prompt-visible' signal. This needs to
  // happen here, after the page has completed rendering itself.
#if defined(USE_AURA)
  emit_login_visible = true;
#else
  if (views::desktop::DesktopWindowView::desktop_window_view)
    emit_login_visible = true;
#endif
  if (emit_login_visible && chromeos::CrosLibrary::Get()->EnsureLoaded())
    chromeos::CrosLibrary::Get()->GetLoginLibrary()->EmitLoginPromptVisible();

}

void WebUILoginView::InitStatusArea() {
  DCHECK(status_area_ == NULL);
  DCHECK(status_window_ == NULL);
  status_area_ = new StatusAreaView(this);
  status_area_->Init();
  status_area_->SetVisible(status_area_visibility_on_init_);

  views::Widget* login_window = WebUILoginDisplay::GetLoginWindow();
  // Width of |status_window| is meant to be large enough.
  // The current value of status_area_->GetPreferredSize().width()
  // will be too small when button status is changed.
  // (e.g. when CapsLock indicator appears)
  gfx::Size widget_size(width()/2,
                        status_area_->GetPreferredSize().height());
  const int widget_x = base::i18n::IsRTL() ?
      kStatusAreaCornerPadding :
      width() - widget_size.width() - kStatusAreaCornerPadding;
  gfx::Rect widget_bounds(widget_x, kStatusAreaCornerPadding,
                          widget_size.width(), widget_size.height());
#if defined(TOUCH_UI)
  views::Widget::InitParams widget_params(
      views::Widget::InitParams::TYPE_CONTROL);
#else
  // TODO(nkostylev|oshima): Make status area in the same window as
  // |webui_login_| once RenderWidgetHostViewViews and compositor are
  // ready.
  views::Widget::InitParams widget_params(
      views::Widget::InitParams::TYPE_WINDOW_FRAMELESS);
#endif
  widget_params.bounds = widget_bounds;
  widget_params.transparent = true;
  widget_params.parent_widget = login_window;
  status_window_ = new views::Widget;
  status_window_->Init(widget_params);

#if defined(TOOLKIT_USES_GTK)
  chromeos::WmIpc::instance()->SetWindowType(
      status_window_->GetNativeView(),
      chromeos::WM_IPC_WINDOW_CHROME_INFO_BUBBLE,
      NULL);
#endif

  views::View* contents_view = new RightAlignedView;
  contents_view->AddChildView(status_area_);
  status_window_->SetContentsView(contents_view);
  status_window_->Show();
}

// WebUILoginView private: -----------------------------------------------------

bool WebUILoginView::HandleContextMenu(const ContextMenuParams& params) {
  // Do not show the context menu.
#ifndef NDEBUG
  return false;
#else
  return true;
#endif
}

bool WebUILoginView::IsPopupOrPanel(const TabContents* source) const {
  return true;
}

bool WebUILoginView::TakeFocus(bool reverse) {
  if (status_area_ && status_area_->IsVisible()) {
    // Forward the focus to the status area.
    base::Callback<void(bool)> return_focus_cb =
        base::Bind(&WebUILoginView::ReturnFocus, base::Unretained(this));
    status_area_->TakeFocus(reverse, return_focus_cb);
    status_area_->GetWidget()->Activate();
  }
  return true;
}

void WebUILoginView::ReturnFocus(bool reverse) {
  // Return the focus to the web contents.
  webui_login_->dom_contents()->tab_contents()->
      FocusThroughTabTraversal(reverse);
  GetWidget()->Activate();
}

void WebUILoginView::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
  unhandled_keyboard_event_handler_.HandleKeyboardEvent(event,
                                                        GetFocusManager());

  // Make sure error bubble is cleared on keyboard event. This is needed
  // when the focus is inside an iframe.
  WebUI* web_ui = GetWebUI();
  if (web_ui)
    web_ui->CallJavascriptFunction("cr.ui.Oobe.clearErrors");
}

}  // namespace chromeos
<commit_msg>Improved comment with input from nkostylev.<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/chromeos/login/webui_login_view.h"

#include "base/bind.h"
#include "base/callback.h"
#include "base/i18n/rtl.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/chromeos/accessibility_util.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/login_library.h"
#include "chrome/browser/chromeos/login/proxy_settings_dialog.h"
#include "chrome/browser/chromeos/login/webui_login_display.h"
#include "chrome/browser/chromeos/status/clock_menu_button.h"
#include "chrome/browser/chromeos/status/input_method_menu_button.h"
#include "chrome/browser/chromeos/status/network_menu_button.h"
#include "chrome/browser/chromeos/status/status_area_view.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/views/dom_view.h"
#include "chrome/common/render_messages.h"
#include "content/browser/renderer_host/render_view_host_observer.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "ui/gfx/rect.h"
#include "ui/gfx/size.h"
#include "views/desktop/desktop_window_view.h"
#include "views/widget/widget.h"

#if defined(TOOLKIT_USES_GTK)
#include "chrome/browser/chromeos/wm_ipc.h"
#include "views/widget/native_widget_gtk.h"
#endif

#if defined(USE_VIRTUAL_KEYBOARD)
#include "chrome/browser/ui/virtual_keyboard/virtual_keyboard_manager.h"
#endif

namespace {

const char kViewClassName[] = "browser/chromeos/login/WebUILoginView";

// These strings must be kept in sync with handleAccelerator() in oobe.js.
const char kAccelNameAccessibility[] = "accessibility";
const char kAccelNameCancel[] = "cancel";
const char kAccelNameEnrollment[] = "enrollment";

// Observes IPC messages from the FrameSniffer and notifies JS if error
// appears.
class SnifferObserver : public RenderViewHostObserver {
 public:
  SnifferObserver(RenderViewHost* host, WebUI* webui)
      : RenderViewHostObserver(host), webui_(webui) {
    DCHECK(webui_);
    Send(new ChromeViewMsg_StartFrameSniffer(routing_id(),
                                             UTF8ToUTF16("gaia-frame")));
  }

  virtual ~SnifferObserver() {}

  // IPC::Channel::Listener implementation.
  virtual bool OnMessageReceived(const IPC::Message& message) {
    bool handled = true;
    IPC_BEGIN_MESSAGE_MAP(SnifferObserver, message)
      IPC_MESSAGE_HANDLER(ChromeViewHostMsg_FrameLoadingError, OnError)
      IPC_MESSAGE_UNHANDLED(handled = false)
    IPC_END_MESSAGE_MAP()
    return handled;
  }

 private:
  void OnError(int error) {
    base::FundamentalValue error_value(error);
    webui_->CallJavascriptFunction("login.OfflineMessageScreen.onFrameError",
                                   error_value);
  }

  WebUI* webui_;
};

// A View class which places its first child at the right most position.
class RightAlignedView : public views::View {
 public:
  virtual void Layout() OVERRIDE;
  virtual void ChildPreferredSizeChanged(View* child) OVERRIDE;
};

void RightAlignedView::Layout() {
  if (has_children()) {
    views::View* child = child_at(0);
    gfx::Size preferred_size = child->GetPreferredSize();
    child->SetBounds(width() - preferred_size.width(),
                     0, preferred_size.width(), preferred_size.height());
  }
}

void RightAlignedView::ChildPreferredSizeChanged(View* child) {
  Layout();
}

}  // namespace

namespace chromeos {

// static
const int WebUILoginView::kStatusAreaCornerPadding = 5;

// WebUILoginView public: ------------------------------------------------------

WebUILoginView::WebUILoginView()
    : status_area_(NULL),
      webui_login_(NULL),
      status_window_(NULL),
      host_window_frozen_(false),
      status_area_visibility_on_init_(true) {
#if defined(USE_VIRTUAL_KEYBOARD)
  // Make sure the singleton VirtualKeyboardManager object is created.
  VirtualKeyboardManager::GetInstance();
#endif
  accel_map_[views::Accelerator(ui::VKEY_Z, false, true, true)] =
      kAccelNameAccessibility;
  accel_map_[views::Accelerator(ui::VKEY_ESCAPE, false, false, false)] =
      kAccelNameCancel;
  accel_map_[views::Accelerator(ui::VKEY_E, false, true, true)] =
      kAccelNameEnrollment;

  for (AccelMap::iterator i(accel_map_.begin()); i != accel_map_.end(); ++i)
    AddAccelerator(i->first);
}

WebUILoginView::~WebUILoginView() {
  if (status_window_)
    status_window_->CloseNow();
  status_window_ = NULL;
}

void WebUILoginView::Init() {

  webui_login_ = new DOMView();
  AddChildView(webui_login_);
  webui_login_->Init(ProfileManager::GetDefaultProfile(), NULL);
  webui_login_->SetVisible(true);

  TabContents* tab_contents = webui_login_->dom_contents()->tab_contents();
  tab_contents->set_delegate(this);

  tab_watcher_.reset(new TabFirstRenderWatcher(tab_contents, this));
}

std::string WebUILoginView::GetClassName() const {
  return kViewClassName;
}

bool WebUILoginView::AcceleratorPressed(
    const views::Accelerator& accelerator) {
  AccelMap::const_iterator entry = accel_map_.find(accelerator);
  if (entry == accel_map_.end())
    return false;

  if (!webui_login_)
    return true;

  WebUI* web_ui = webui_login_->dom_contents()->tab_contents()->web_ui();
  if (web_ui) {
    base::StringValue accel_name(entry->second);
    web_ui->CallJavascriptFunction("cr.ui.Oobe.handleAccelerator",
                                   accel_name);
  }

  return true;
}

gfx::NativeWindow WebUILoginView::GetNativeWindow() const {
  return GetWidget()->GetNativeWindow();
}

void WebUILoginView::OnWindowCreated() {
#if defined(TOOLKIT_USES_GTK)
  // Freezes host window update until the tab is rendered.
  host_window_frozen_ = static_cast<views::NativeWidgetGtk*>(
      GetWidget()->native_widget())->SuppressFreezeUpdates();
#else
  // TODO(saintlou): Unclear if we need this for the !gtk case.
  // According to nkostylev it prevents the renderer from flashing with a
  // white solid background until the content is fully rendered.
#endif
}

void WebUILoginView::UpdateWindowType() {
#if defined(TOOLKIT_USES_GTK)
  std::vector<int> params;
  WmIpc::instance()->SetWindowType(
      GTK_WIDGET(GetNativeWindow()),
      WM_IPC_WINDOW_LOGIN_WEBUI,
      &params);
#endif
}

void WebUILoginView::LoadURL(const GURL & url) {
  webui_login_->LoadURL(url);
  webui_login_->RequestFocus();
}

WebUI* WebUILoginView::GetWebUI() {
  return webui_login_->dom_contents()->tab_contents()->web_ui();
}

void WebUILoginView::SetStatusAreaEnabled(bool enable) {
  if (status_area_)
    status_area_->MakeButtonsActive(enable);
}

void WebUILoginView::SetStatusAreaVisible(bool visible) {
  if (status_area_)
    status_area_->SetVisible(visible);
  else
    status_area_visibility_on_init_ = visible;
}

// WebUILoginView protected: ---------------------------------------------------

void WebUILoginView::Layout() {
  DCHECK(webui_login_);
  webui_login_->SetBoundsRect(bounds());
}

void WebUILoginView::ChildPreferredSizeChanged(View* child) {
  Layout();
  SchedulePaint();
}

Profile* WebUILoginView::GetProfile() const {
  return NULL;
}

void WebUILoginView::ExecuteBrowserCommand(int id) const {
}

bool WebUILoginView::ShouldOpenButtonOptions(
    const views::View* button_view) const {
  if (button_view == status_area_->network_view())
    return true;

  if (button_view == status_area_->clock_view() ||
      button_view == status_area_->input_method_view())
    return false;

  return true;
}

void WebUILoginView::OpenButtonOptions(const views::View* button_view) {
  if (button_view == status_area_->network_view()) {
    if (proxy_settings_dialog_.get() == NULL) {
      proxy_settings_dialog_.reset(new ProxySettingsDialog(
          this, GetNativeWindow()));
    }
    proxy_settings_dialog_->Show();
  }
}

StatusAreaHost::ScreenMode WebUILoginView::GetScreenMode() const {
  return kWebUILoginMode;
}

StatusAreaHost::TextStyle WebUILoginView::GetTextStyle() const {
  return kGrayPlain;
}

void WebUILoginView::ButtonVisibilityChanged(views::View* button_view) {
  status_area_->ButtonVisibilityChanged(button_view);
}

void WebUILoginView::OnDialogClosed() {
}

void WebUILoginView::OnLocaleChanged() {
  // Proxy settings dialog contains localized strings.
  proxy_settings_dialog_.reset();
  SchedulePaint();
}

void WebUILoginView::OnRenderHostCreated(RenderViewHost* host) {
  new SnifferObserver(host, GetWebUI());
}

void WebUILoginView::OnTabMainFrameLoaded() {
  VLOG(1) << "WebUI login main frame loaded.";
}

void WebUILoginView::OnTabMainFrameFirstRender() {
  VLOG(1) << "WebUI login main frame rendered.";
  InitStatusArea();

#if defined(TOOLKIT_USES_GTK)
  if (host_window_frozen_) {
    host_window_frozen_ = false;

    // Unfreezes the host window since tab is rendereed now.
    views::NativeWidgetGtk::UpdateFreezeUpdatesProperty(
        GetNativeWindow(), false);
  }
#endif

  bool emit_login_visible = false;

  // In aura or views-desktop environment, there will be no window-manager. So
  // chrome needs to emit the 'login-prompt-visible' signal. This needs to
  // happen here, after the page has completed rendering itself.
#if defined(USE_AURA)
  emit_login_visible = true;
#else
  if (views::desktop::DesktopWindowView::desktop_window_view)
    emit_login_visible = true;
#endif
  if (emit_login_visible && chromeos::CrosLibrary::Get()->EnsureLoaded())
    chromeos::CrosLibrary::Get()->GetLoginLibrary()->EmitLoginPromptVisible();

}

void WebUILoginView::InitStatusArea() {
  DCHECK(status_area_ == NULL);
  DCHECK(status_window_ == NULL);
  status_area_ = new StatusAreaView(this);
  status_area_->Init();
  status_area_->SetVisible(status_area_visibility_on_init_);

  views::Widget* login_window = WebUILoginDisplay::GetLoginWindow();
  // Width of |status_window| is meant to be large enough.
  // The current value of status_area_->GetPreferredSize().width()
  // will be too small when button status is changed.
  // (e.g. when CapsLock indicator appears)
  gfx::Size widget_size(width()/2,
                        status_area_->GetPreferredSize().height());
  const int widget_x = base::i18n::IsRTL() ?
      kStatusAreaCornerPadding :
      width() - widget_size.width() - kStatusAreaCornerPadding;
  gfx::Rect widget_bounds(widget_x, kStatusAreaCornerPadding,
                          widget_size.width(), widget_size.height());
#if defined(TOUCH_UI)
  views::Widget::InitParams widget_params(
      views::Widget::InitParams::TYPE_CONTROL);
#else
  // TODO(nkostylev|oshima): Make status area in the same window as
  // |webui_login_| once RenderWidgetHostViewViews and compositor are
  // ready.
  views::Widget::InitParams widget_params(
      views::Widget::InitParams::TYPE_WINDOW_FRAMELESS);
#endif
  widget_params.bounds = widget_bounds;
  widget_params.transparent = true;
  widget_params.parent_widget = login_window;
  status_window_ = new views::Widget;
  status_window_->Init(widget_params);

#if defined(TOOLKIT_USES_GTK)
  chromeos::WmIpc::instance()->SetWindowType(
      status_window_->GetNativeView(),
      chromeos::WM_IPC_WINDOW_CHROME_INFO_BUBBLE,
      NULL);
#endif

  views::View* contents_view = new RightAlignedView;
  contents_view->AddChildView(status_area_);
  status_window_->SetContentsView(contents_view);
  status_window_->Show();
}

// WebUILoginView private: -----------------------------------------------------

bool WebUILoginView::HandleContextMenu(const ContextMenuParams& params) {
  // Do not show the context menu.
#ifndef NDEBUG
  return false;
#else
  return true;
#endif
}

bool WebUILoginView::IsPopupOrPanel(const TabContents* source) const {
  return true;
}

bool WebUILoginView::TakeFocus(bool reverse) {
  if (status_area_ && status_area_->IsVisible()) {
    // Forward the focus to the status area.
    base::Callback<void(bool)> return_focus_cb =
        base::Bind(&WebUILoginView::ReturnFocus, base::Unretained(this));
    status_area_->TakeFocus(reverse, return_focus_cb);
    status_area_->GetWidget()->Activate();
  }
  return true;
}

void WebUILoginView::ReturnFocus(bool reverse) {
  // Return the focus to the web contents.
  webui_login_->dom_contents()->tab_contents()->
      FocusThroughTabTraversal(reverse);
  GetWidget()->Activate();
}

void WebUILoginView::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
  unhandled_keyboard_event_handler_.HandleKeyboardEvent(event,
                                                        GetFocusManager());

  // Make sure error bubble is cleared on keyboard event. This is needed
  // when the focus is inside an iframe.
  WebUI* web_ui = GetWebUI();
  if (web_ui)
    web_ui->CallJavascriptFunction("cr.ui.Oobe.clearErrors");
}

}  // namespace chromeos
<|endoftext|>


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

#include <gtest/gtest.h>
#include <thrift/lib/cpp2/async/RequestChannel.h>
#include <thrift/lib/cpp2/async/FutureRequest.h>
#include <thrift/lib/cpp2/test/gen-cpp2/FutureService.h>
#include <thrift/lib/cpp2/server/ThriftServer.h>
#include <thrift/lib/cpp2/async/HeaderClientChannel.h>

#include <thrift/lib/cpp/util/ScopedServerThread.h>
#include <folly/io/async/EventBase.h>
#include <thrift/lib/cpp/async/TAsyncSocket.h>

#include <thrift/lib/cpp2/async/StubSaslClient.h>
#include <thrift/lib/cpp2/async/StubSaslServer.h>
#include <thrift/lib/cpp2/TestServer.h>

#include <boost/cast.hpp>
#include <boost/lexical_cast.hpp>
#include <memory>
#include <atomic>

#include <folly/Executor.h>
#include <folly/futures/ManualExecutor.h>

using namespace apache::thrift;
using namespace apache::thrift::concurrency;
using namespace apache::thrift::test::cpp2;
using namespace apache::thrift::util;
using namespace apache::thrift::async;
using namespace folly;

class TestInterface : public FutureServiceSvIf {
  Future<std::unique_ptr<std::string>> future_sendResponse(
      int64_t size) override {
    EXPECT_NE("", getConnectionContext()->getPeerAddress()->describe());

    MoveWrapper<Promise<std::unique_ptr<std::string> > > p;
    auto f = p->getFuture();

    auto func = std::function<void()>([=]() mutable {
      std::unique_ptr<std::string> _return(
        new std::string("test" + boost::lexical_cast<std::string>(size)));
      p->setValue(std::move(_return));
    });

    RequestEventBase::get()->runInEventBaseThread([this, func, size](){
      RequestEventBase::get()->tryRunAfterDelay(func, size);
    });

    return f;
  }

  Future<Unit> future_noResponse(int64_t size) override {
    MoveWrapper<Promise<Unit>> p;
    auto f = p->getFuture();

    auto func = std::function<void()>([=]() mutable {
      p->setValue();
    });
    RequestEventBase::get()->runInEventBaseThread([this, func, size](){
      RequestEventBase::get()->tryRunAfterDelay(func, size);
    });
    return f;
  }

  Future<std::unique_ptr<std::string>> future_echoRequest(
      std::unique_ptr<std::string> req) override {
    *req += "ccccccccccccccccccccccccccccccccccccccccccccc";

    return makeFuture<std::unique_ptr<std::string>>(std::move(req));
  }

  Future<int> future_throwing() override {
    Promise<int> p;
    auto f = p.getFuture();

    Xception x;
    x.errorCode = 32;
    x.message = "test";

    p.setException(x);

    return f;
  }

  Future<Unit> future_voidThrowing() override {
    Promise<Unit> p;
    auto f = p.getFuture();

    Xception x;
    x.errorCode = 42;
    x.message = "test2";

    p.setException(x);

    return f;
  }
};

void AsyncCpp2Test(bool enable_security) {
  apache::thrift::TestThriftServerFactory<TestInterface> factory;
  ScopedServerThread sst(factory.create());
  EventBase base;
  std::shared_ptr<TAsyncSocket> socket(
    TAsyncSocket::newSocket(&base, *sst.getAddress()));

  auto client_channel = HeaderClientChannel::newChannel(socket);
  if (enable_security) {
    client_channel->setSecurityPolicy(THRIFT_SECURITY_PERMITTED);
    client_channel->setSaslClient(std::unique_ptr<SaslClient>(
      new StubSaslClient(socket->getEventBase())
    ));
  }
  FutureServiceAsyncClient client(std::move(client_channel));

  boost::polymorphic_downcast<HeaderClientChannel*>(
    client.getChannel())->setTimeout(10000);
  client.sendResponse([](ClientReceiveState&& state) {
                        std::string response;
                        try {
                          FutureServiceAsyncClient::recv_sendResponse(
                              response, state);
                        } catch(const std::exception& ex) {
                        }
                        EXPECT_EQ(response, "test64");
                      },
                      64);
  base.loop();
}

TEST(ThriftServer, FutureExceptions) {
  apache::thrift::TestThriftServerFactory<TestInterface> factory;
  ScopedServerThread sst(factory.create());
  EventBase base;
  std::shared_ptr<TAsyncSocket> socket(
    TAsyncSocket::newSocket(&base, *sst.getAddress()));

  FutureServiceAsyncClient client(
    std::unique_ptr<HeaderClientChannel,
                    DelayedDestruction::Destructor>(
                      new HeaderClientChannel(socket)));
  auto f = client.future_throwing().waitVia(&base);

  EXPECT_THROW(f.value(), Xception);

  auto vf = client.future_voidThrowing().waitVia(&base);

  EXPECT_THROW(vf.value(), Xception);
}

TEST(ThriftServer, FutureClientTest) {
  using std::chrono::steady_clock;

  apache::thrift::TestThriftServerFactory<TestInterface> factory;
  ScopedServerThread sst(factory.create());
  EventBase base;
  std::shared_ptr<TAsyncSocket> socket(
    TAsyncSocket::newSocket(&base, *sst.getAddress()));

  FutureServiceAsyncClient client(
    std::unique_ptr<HeaderClientChannel,
                    DelayedDestruction::Destructor>(
                      new HeaderClientChannel(socket)));

  boost::polymorphic_downcast<HeaderClientChannel*>(
    client.getChannel())->setTimeout(10000);

  // only once you call wait() should you start looping,
  // so the wait time in value() (which calls wait()) should
  // be much higher than the time for future_sendResponse(0)
  steady_clock::time_point start = steady_clock::now();

  auto future = client.future_sendResponse(1000);
  steady_clock::time_point sent = steady_clock::now();

  auto value = future.getVia(&base);
  steady_clock::time_point got = steady_clock::now();

  EXPECT_EQ(value, "test1000");

  steady_clock::duration sentTime = sent - start;
  steady_clock::duration waitTime = got - sent;

  int factor = 2;
  EXPECT_GE(waitTime, factor * sentTime);

  auto len = client.future_sendResponse(64).then(
    [](folly::Try<std::string>&& response) {
      EXPECT_TRUE(response.hasValue());
      EXPECT_EQ(response.value(), "test64");
      return response.value().size();
    }
  );

  EXPECT_EQ(len.getVia(&base), 6);

  RpcOptions options;
  options.setTimeout(std::chrono::milliseconds(1));
  try {
    // should timeout
    auto f = client.future_sendResponse(options, 10000);

    // Wait for future to finish
    f.getVia(&base);
    EXPECT_EQ(true, false);
  } catch (...) {
    return;
  }
}

// Needs wait()
TEST(ThriftServer, FutureGetOrderTest) {
  using std::chrono::steady_clock;

  auto thf = std::make_shared<PosixThreadFactory>();
  auto thm = ThreadManager::newSimpleThreadManager(1, 5, false, 5);
  thm->threadFactory(thf);
  thm->start();
  apache::thrift::TestThriftServerFactory<TestInterface> factory;
  factory.useSimpleThreadManager(false);
  factory.useThreadManager(thm);
  ScopedServerThread sst(factory.create());
  EventBase base;
  std::shared_ptr<TAsyncSocket> socket(
    TAsyncSocket::newSocket(&base, *sst.getAddress()));

  FutureServiceAsyncClient client(
    std::unique_ptr<HeaderClientChannel,
                    DelayedDestruction::Destructor>(
                      new HeaderClientChannel(socket)));

  boost::polymorphic_downcast<HeaderClientChannel*>(
    client.getChannel())->setTimeout(10000);

  auto future0 = client.future_sendResponse(0);
  auto future1 = client.future_sendResponse(10);
  auto future2 = client.future_sendResponse(20);
  auto future3 = client.future_sendResponse(30);
  auto future4 = client.future_sendResponse(40);

  steady_clock::time_point start = steady_clock::now();

  EXPECT_EQ(future3.getVia(&base), "test30");
  steady_clock::time_point sent = steady_clock::now();
  EXPECT_EQ(future4.getVia(&base), "test40");
  EXPECT_EQ(future0.getVia(&base), "test0");
  EXPECT_EQ(future2.getVia(&base), "test20");
  EXPECT_EQ(future1.getVia(&base), "test10");
  steady_clock::time_point gets = steady_clock::now();

  steady_clock::duration sentTime = sent - start;
  steady_clock::duration getsTime = gets - sent;

  int factor = 2;
  EXPECT_GE(sentTime, factor * getsTime);
}

TEST(ThriftServer, OnewayFutureClientTest) {
  using std::chrono::steady_clock;

  apache::thrift::TestThriftServerFactory<TestInterface> factory;
  ScopedServerThread sst(factory.create());
  EventBase base;
  std::shared_ptr<TAsyncSocket> socket(
    TAsyncSocket::newSocket(&base, *sst.getAddress()));

  FutureServiceAsyncClient client(
    std::unique_ptr<HeaderClientChannel,
                    DelayedDestruction::Destructor>(
                      new HeaderClientChannel(socket)));

  auto future = client.future_noResponse(1000);
  steady_clock::time_point sent = steady_clock::now();

  // wait for future to finish.
  base.loop();
  steady_clock::time_point waited = steady_clock::now();

  future.value();
  steady_clock::time_point got = steady_clock::now();

  steady_clock::duration waitTime = waited - sent;
  steady_clock::duration gotTime = got - waited;

  int factor = 1;
  EXPECT_GE(waitTime, factor * gotTime);
}

int main(int argc, char** argv) {
  testing::InitGoogleTest(&argc, argv);
  google::InitGoogleLogging(argv[0]);
  google::ParseCommandLineFlags(&argc, &argv, true);

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

#include <gtest/gtest.h>
#include <thrift/lib/cpp2/async/RequestChannel.h>
#include <thrift/lib/cpp2/async/FutureRequest.h>
#include <thrift/lib/cpp2/test/gen-cpp2/FutureService.h>
#include <thrift/lib/cpp2/server/ThriftServer.h>
#include <thrift/lib/cpp2/async/HeaderClientChannel.h>

#include <thrift/lib/cpp/util/ScopedServerThread.h>
#include <folly/io/async/EventBase.h>
#include <thrift/lib/cpp/async/TAsyncSocket.h>

#include <thrift/lib/cpp2/async/StubSaslClient.h>
#include <thrift/lib/cpp2/async/StubSaslServer.h>
#include <thrift/lib/cpp2/TestServer.h>
#include <thrift/lib/cpp2/util/ScopedServerInterfaceThread.h>

#include <boost/cast.hpp>
#include <boost/lexical_cast.hpp>
#include <memory>
#include <atomic>

#include <folly/Executor.h>
#include <folly/MapUtil.h>
#include <folly/futures/ManualExecutor.h>

using namespace apache::thrift;
using namespace apache::thrift::concurrency;
using namespace apache::thrift::test::cpp2;
using namespace apache::thrift::util;
using namespace apache::thrift::async;
using namespace folly;

class TestInterface : public FutureServiceSvIf {
  Future<std::unique_ptr<std::string>> future_sendResponse(
      int64_t size) override {
    EXPECT_NE("", getConnectionContext()->getPeerAddress()->describe());

    MoveWrapper<Promise<std::unique_ptr<std::string> > > p;
    auto f = p->getFuture();

    auto func = std::function<void()>([=]() mutable {
      std::unique_ptr<std::string> _return(
        new std::string("test" + boost::lexical_cast<std::string>(size)));
      p->setValue(std::move(_return));
    });

    RequestEventBase::get()->runInEventBaseThread([this, func, size](){
      RequestEventBase::get()->tryRunAfterDelay(func, size);
    });

    return f;
  }

  Future<Unit> future_noResponse(int64_t size) override {
    MoveWrapper<Promise<Unit>> p;
    auto f = p->getFuture();

    auto func = std::function<void()>([=]() mutable {
      p->setValue();
    });
    RequestEventBase::get()->runInEventBaseThread([this, func, size](){
      RequestEventBase::get()->tryRunAfterDelay(func, size);
    });
    return f;
  }

  Future<std::unique_ptr<std::string>> future_echoRequest(
      std::unique_ptr<std::string> req) override {
    *req += "ccccccccccccccccccccccccccccccccccccccccccccc";

    auto header = getConnectionContext()->getHeader();

    if (header->getHeaders().count("foo")) {
      header->setHeader("header_from_server", "1");
    }

    return makeFuture<std::unique_ptr<std::string>>(std::move(req));
  }

  Future<int> future_throwing() override {
    Promise<int> p;
    auto f = p.getFuture();

    Xception x;
    x.errorCode = 32;
    x.message = "test";

    p.setException(x);

    return f;
  }

  Future<Unit> future_voidThrowing() override {
    Promise<Unit> p;
    auto f = p.getFuture();

    Xception x;
    x.errorCode = 42;
    x.message = "test2";

    p.setException(x);

    return f;
  }
};

void AsyncCpp2Test(bool enable_security) {
  apache::thrift::TestThriftServerFactory<TestInterface> factory;
  ScopedServerThread sst(factory.create());
  EventBase base;
  std::shared_ptr<TAsyncSocket> socket(
    TAsyncSocket::newSocket(&base, *sst.getAddress()));

  auto client_channel = HeaderClientChannel::newChannel(socket);
  if (enable_security) {
    client_channel->setSecurityPolicy(THRIFT_SECURITY_PERMITTED);
    client_channel->setSaslClient(std::unique_ptr<SaslClient>(
      new StubSaslClient(socket->getEventBase())
    ));
  }
  FutureServiceAsyncClient client(std::move(client_channel));

  boost::polymorphic_downcast<HeaderClientChannel*>(
    client.getChannel())->setTimeout(10000);
  client.sendResponse([](ClientReceiveState&& state) {
                        std::string response;
                        try {
                          FutureServiceAsyncClient::recv_sendResponse(
                              response, state);
                        } catch(const std::exception& ex) {
                        }
                        EXPECT_EQ(response, "test64");
                      },
                      64);
  base.loop();
}

TEST(ThriftServer, FutureExceptions) {
  apache::thrift::TestThriftServerFactory<TestInterface> factory;
  ScopedServerThread sst(factory.create());
  EventBase base;
  std::shared_ptr<TAsyncSocket> socket(
    TAsyncSocket::newSocket(&base, *sst.getAddress()));

  FutureServiceAsyncClient client(
    std::unique_ptr<HeaderClientChannel,
                    DelayedDestruction::Destructor>(
                      new HeaderClientChannel(socket)));
  auto f = client.future_throwing().waitVia(&base);

  EXPECT_THROW(f.value(), Xception);

  auto vf = client.future_voidThrowing().waitVia(&base);

  EXPECT_THROW(vf.value(), Xception);
}

TEST(ThriftServer, FutureClientTest) {
  using std::chrono::steady_clock;

  apache::thrift::TestThriftServerFactory<TestInterface> factory;
  ScopedServerThread sst(factory.create());
  EventBase base;
  std::shared_ptr<TAsyncSocket> socket(
    TAsyncSocket::newSocket(&base, *sst.getAddress()));

  FutureServiceAsyncClient client(
    std::unique_ptr<HeaderClientChannel,
                    DelayedDestruction::Destructor>(
                      new HeaderClientChannel(socket)));

  boost::polymorphic_downcast<HeaderClientChannel*>(
    client.getChannel())->setTimeout(10000);

  // only once you call wait() should you start looping,
  // so the wait time in value() (which calls wait()) should
  // be much higher than the time for future_sendResponse(0)
  steady_clock::time_point start = steady_clock::now();

  auto future = client.future_sendResponse(1000);
  steady_clock::time_point sent = steady_clock::now();

  auto value = future.getVia(&base);
  steady_clock::time_point got = steady_clock::now();

  EXPECT_EQ(value, "test1000");

  steady_clock::duration sentTime = sent - start;
  steady_clock::duration waitTime = got - sent;

  int factor = 2;
  EXPECT_GE(waitTime, factor * sentTime);

  auto len = client.future_sendResponse(64).then(
    [](folly::Try<std::string>&& response) {
      EXPECT_TRUE(response.hasValue());
      EXPECT_EQ(response.value(), "test64");
      return response.value().size();
    }
  );

  EXPECT_EQ(len.getVia(&base), 6);

  RpcOptions options;
  options.setTimeout(std::chrono::milliseconds(1));
  try {
    // should timeout
    auto f = client.future_sendResponse(options, 10000);

    // Wait for future to finish
    f.getVia(&base);
    EXPECT_EQ(true, false);
  } catch (...) {
    return;
  }
}

// Needs wait()
TEST(ThriftServer, FutureGetOrderTest) {
  using std::chrono::steady_clock;

  auto thf = std::make_shared<PosixThreadFactory>();
  auto thm = ThreadManager::newSimpleThreadManager(1, 5, false, 5);
  thm->threadFactory(thf);
  thm->start();
  apache::thrift::TestThriftServerFactory<TestInterface> factory;
  factory.useSimpleThreadManager(false);
  factory.useThreadManager(thm);
  ScopedServerThread sst(factory.create());
  EventBase base;
  std::shared_ptr<TAsyncSocket> socket(
    TAsyncSocket::newSocket(&base, *sst.getAddress()));

  FutureServiceAsyncClient client(
    std::unique_ptr<HeaderClientChannel,
                    DelayedDestruction::Destructor>(
                      new HeaderClientChannel(socket)));

  boost::polymorphic_downcast<HeaderClientChannel*>(
    client.getChannel())->setTimeout(10000);

  auto future0 = client.future_sendResponse(0);
  auto future1 = client.future_sendResponse(10);
  auto future2 = client.future_sendResponse(20);
  auto future3 = client.future_sendResponse(30);
  auto future4 = client.future_sendResponse(40);

  steady_clock::time_point start = steady_clock::now();

  EXPECT_EQ(future3.getVia(&base), "test30");
  steady_clock::time_point sent = steady_clock::now();
  EXPECT_EQ(future4.getVia(&base), "test40");
  EXPECT_EQ(future0.getVia(&base), "test0");
  EXPECT_EQ(future2.getVia(&base), "test20");
  EXPECT_EQ(future1.getVia(&base), "test10");
  steady_clock::time_point gets = steady_clock::now();

  steady_clock::duration sentTime = sent - start;
  steady_clock::duration getsTime = gets - sent;

  int factor = 2;
  EXPECT_GE(sentTime, factor * getsTime);
}

TEST(ThriftServer, OnewayFutureClientTest) {
  using std::chrono::steady_clock;

  apache::thrift::TestThriftServerFactory<TestInterface> factory;
  ScopedServerThread sst(factory.create());
  EventBase base;
  std::shared_ptr<TAsyncSocket> socket(
    TAsyncSocket::newSocket(&base, *sst.getAddress()));

  FutureServiceAsyncClient client(
    std::unique_ptr<HeaderClientChannel,
                    DelayedDestruction::Destructor>(
                      new HeaderClientChannel(socket)));

  auto future = client.future_noResponse(1000);
  steady_clock::time_point sent = steady_clock::now();

  // wait for future to finish.
  base.loop();
  steady_clock::time_point waited = steady_clock::now();

  future.value();
  steady_clock::time_point got = steady_clock::now();

  steady_clock::duration waitTime = waited - sent;
  steady_clock::duration gotTime = got - waited;

  int factor = 1;
  EXPECT_GE(waitTime, factor * gotTime);
}

TEST(ThriftServer, FutureHeaderClientTest) {
  ScopedServerInterfaceThread runner(make_shared<TestInterface>());
  EventBase eb;
  auto client = runner.newClient<FutureServiceAsyncClient>(&eb);

  RpcOptions rpcOptions;
  rpcOptions.setWriteHeader("foo", "bar");
  auto future = client->header_future_echoRequest(rpcOptions, "hi")
    .waitVia(&eb);

  const auto& headers = future.value().second->getHeaders();
  EXPECT_EQ(get_default(headers, "header_from_server"), "1");
}

int main(int argc, char** argv) {
  testing::InitGoogleTest(&argc, argv);
  google::InitGoogleLogging(argv[0]);
  google::ParseCommandLineFlags(&argc, &argv, true);

  return RUN_ALL_TESTS();
}
<|endoftext|>


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

#include "qquickitemsmodule_p.h"

#include "qquickitem.h"
#include "qquickitem_p.h"
#include "qquickevents_p_p.h"
#include "qquickrectangle_p.h"
#include "qquickfocusscope_p.h"
#include "qquicktext_p.h"
#include "qquicktextinput_p.h"
#include "qquicktextedit_p.h"
#include "qquicktextdocument.h"
#include "qquickimage_p.h"
#include "qquickborderimage_p.h"
#include "qquickscalegrid_p_p.h"
#include "qquickmousearea_p.h"
#include "qquickpincharea_p.h"
#include "qquickflickable_p.h"
#include "qquickflickable_p_p.h"
#include "qquicklistview_p.h"
#include "qquickgridview_p.h"
#include "qquickpathview_p.h"
#include "qquickitemviewtransition_p.h"
#include <private/qquickpath_p.h>
#include <private/qquickpathinterpolator_p.h>
#include "qquickpositioners_p.h"
#include "qquickrepeater_p.h"
#include "qquickloader_p.h"
#include "qquickanimatedimage_p.h"
#include "qquickflipable_p.h"
#include "qquicktranslate_p.h"
#include "qquickstateoperations_p.h"
#include "qquickitemanimation_p.h"
#include <private/qquickshadereffect_p.h>
#include <QtQuick/private/qquickshadereffectsource_p.h>
//#include <private/qquickpincharea_p.h>
#include <QtQuick/private/qquickcanvasitem_p.h>
#include <QtQuick/private/qquickcontext2d_p.h>
#include "qquicksprite_p.h"
#include "qquickspritesequence_p.h"
#include "qquickanimatedsprite_p.h"
#include "qquickdrag_p.h"
#include "qquickdroparea_p.h"
#include "qquickmultipointtoucharea_p.h"
#include <private/qqmlmetatype_p.h>
#include <QtQuick/private/qquickaccessibleattached_p.h>

static QQmlPrivate::AutoParentResult qquickitem_autoParent(QObject *obj, QObject *parent)
{
    // When setting a parent (especially during dynamic object creation) in QML,
    // also try to set up the analogous item/window relationship.
    QQuickItem *parentItem = qmlobject_cast<QQuickItem *>(parent);
    if (parentItem) {
        QQuickItem *item = qmlobject_cast<QQuickItem *>(obj);
        if (item) {
            // An Item has another Item
            item->setParentItem(parentItem);
            return QQmlPrivate::Parented;
        } else if (parentItem->window()) {
            QQuickWindow *win = qmlobject_cast<QQuickWindow *>(obj);
            if (win) {
                // A Window inside an Item should be transient for that item's window
                win->setTransientParent(parentItem->window());
                return QQmlPrivate::Parented;
            }
        }
        return QQmlPrivate::IncompatibleObject;
    } else {
        QQuickWindow *parentWindow = qmlobject_cast<QQuickWindow *>(parent);
        if (parentWindow) {
            QQuickWindow *win = qmlobject_cast<QQuickWindow *>(obj);
            if (win) {
                // A Window inside a Window should be transient for it
                win->setTransientParent(parentWindow);
                return QQmlPrivate::Parented;
            } else {
                QQuickItem *item = qmlobject_cast<QQuickItem *>(obj);
                if (item) {
                    // The parent of an Item inside a Window is actually the implicit content Item
                    item->setParentItem(parentWindow->contentItem());
                    return QQmlPrivate::Parented;
                }
            }
            return QQmlPrivate::IncompatibleObject;
        }
    }
    return QQmlPrivate::IncompatibleParent;
}

static bool compareQQuickAnchorLines(const void *p1, const void *p2)
{
    const QQuickAnchorLine &l1 = *static_cast<const QQuickAnchorLine*>(p1);
    const QQuickAnchorLine &l2 = *static_cast<const QQuickAnchorLine*>(p2);
    return l1 == l2;
}

static void qt_quickitems_defineModule(const char *uri, int major, int minor)
{
    QQmlPrivate::RegisterAutoParent autoparent = { 0, &qquickitem_autoParent };
    QQmlPrivate::qmlregister(QQmlPrivate::AutoParentRegistration, &autoparent);
    QQuickItemPrivate::registerAccessorProperties();

#ifdef QT_NO_MOVIE
    qmlRegisterTypeNotAvailable(uri,major,minor,"AnimatedImage", qApp->translate("QQuickAnimatedImage","Qt was built without support for QMovie"));
#else
    qmlRegisterType<QQuickAnimatedImage>(uri,major,minor,"AnimatedImage");
#endif
    qmlRegisterType<QQuickBorderImage>(uri,major,minor,"BorderImage");
    qmlRegisterType<QQuickColumn>(uri,major,minor,"Column");
    qmlRegisterType<QQuickFlickable>(uri,major,minor,"Flickable");
    qmlRegisterType<QQuickFlipable>(uri,major,minor,"Flipable");
    qmlRegisterType<QQuickFlow>(uri,major,minor,"Flow");
//    qmlRegisterType<QQuickFocusPanel>(uri,major,minor,"FocusPanel");
    qmlRegisterType<QQuickFocusScope>(uri,major,minor,"FocusScope");
    qmlRegisterType<QQuickGradient>(uri,major,minor,"Gradient");
    qmlRegisterType<QQuickGradientStop>(uri,major,minor,"GradientStop");
    qmlRegisterType<QQuickGrid>(uri,major,minor,"Grid");
    qmlRegisterType<QQuickGridView>(uri,major,minor,"GridView");
    qmlRegisterType<QQuickImage>(uri,major,minor,"Image");
    qmlRegisterType<QQuickItem>(uri,major,minor,"Item");
    qmlRegisterType<QQuickListView>(uri,major,minor,"ListView");
    qmlRegisterType<QQuickLoader>(uri,major,minor,"Loader");
    qmlRegisterType<QQuickMouseArea>(uri,major,minor,"MouseArea");
    qmlRegisterType<QQuickPath>(uri,major,minor,"Path");
    qmlRegisterType<QQuickPathAttribute>(uri,major,minor,"PathAttribute");
    qmlRegisterType<QQuickPathCubic>(uri,major,minor,"PathCubic");
    qmlRegisterType<QQuickPathLine>(uri,major,minor,"PathLine");
    qmlRegisterType<QQuickPathPercent>(uri,major,minor,"PathPercent");
    qmlRegisterType<QQuickPathQuad>(uri,major,minor,"PathQuad");
    qmlRegisterType<QQuickPathCatmullRomCurve>("QtQuick",2,0,"PathCurve");
    qmlRegisterType<QQuickPathArc>("QtQuick",2,0,"PathArc");
    qmlRegisterType<QQuickPathSvg>("QtQuick",2,0,"PathSvg");
    qmlRegisterType<QQuickPathView>(uri,major,minor,"PathView");
    qmlRegisterUncreatableType<QQuickBasePositioner>(uri,major,minor,"Positioner",
                                                  QStringLiteral("Positioner is an abstract type that is only available as an attached property."));
#ifndef QT_NO_VALIDATOR
    qmlRegisterType<QQuickIntValidator>(uri,major,minor,"IntValidator");
    qmlRegisterType<QQuickDoubleValidator>(uri,major,minor,"DoubleValidator");
    qmlRegisterType<QRegExpValidator>(uri,major,minor,"RegExpValidator");
#endif
    qmlRegisterType<QQuickRectangle>(uri,major,minor,"Rectangle");
    qmlRegisterType<QQuickRepeater>(uri,major,minor,"Repeater");
    qmlRegisterType<QQuickRow>(uri,major,minor,"Row");
    qmlRegisterType<QQuickTranslate>(uri,major,minor,"Translate");
    qmlRegisterType<QQuickRotation>(uri,major,minor,"Rotation");
    qmlRegisterType<QQuickScale>(uri,major,minor,"Scale");
    qmlRegisterType<QQuickText>(uri,major,minor,"Text");
    qmlRegisterType<QQuickTextEdit>(uri,major,minor,"TextEdit");
    qmlRegisterType<QQuickTextEdit,1>(uri,2,1,"TextEdit");
    qmlRegisterType<QQuickTextInput>(uri,major,minor,"TextInput");
    qmlRegisterType<QQuickViewSection>(uri,major,minor,"ViewSection");

    qmlRegisterType<QQuickItemLayer>();
    qmlRegisterType<QQuickAnchors>();
    qmlRegisterType<QQuickKeyEvent>();
    qmlRegisterType<QQuickMouseEvent>();
    qmlRegisterType<QQuickWheelEvent>();
    qmlRegisterType<QQuickCloseEvent>();
    qmlRegisterType<QQuickTransform>();
    qmlRegisterType<QQuickPathElement>();
    qmlRegisterType<QQuickCurve>();
    qmlRegisterType<QQuickScaleGrid>();
    qmlRegisterType<QQuickTextLine>();
#ifndef QT_NO_VALIDATOR
    qmlRegisterType<QValidator>();
#endif
    qmlRegisterType<QQuickPen>();
    qmlRegisterType<QQuickFlickableVisibleArea>();
    qRegisterMetaType<QQuickAnchorLine>("QQuickAnchorLine");
    QQmlMetaType::setQQuickAnchorLineCompareFunction(compareQQuickAnchorLines);

    qmlRegisterType<QQuickTextDocument>();

    qmlRegisterUncreatableType<QQuickKeyNavigationAttached>(uri,major,minor,"KeyNavigation",QQuickKeyNavigationAttached::tr("KeyNavigation is only available via attached properties"));
    qmlRegisterUncreatableType<QQuickKeysAttached>(uri,major,minor,"Keys",QQuickKeysAttached::tr("Keys is only available via attached properties"));
    qmlRegisterUncreatableType<QQuickLayoutMirroringAttached>(uri,major,minor,"LayoutMirroring", QQuickLayoutMirroringAttached::tr("LayoutMirroring is only available via attached properties"));
    qmlRegisterUncreatableType<QQuickViewTransitionAttached>(uri,major,minor,"ViewTransition",QQuickViewTransitionAttached::tr("ViewTransition is only available via attached properties"));

    qmlRegisterType<QQuickPinchArea>(uri,major,minor,"PinchArea");
    qmlRegisterType<QQuickPinch>(uri,major,minor,"Pinch");
    qmlRegisterType<QQuickPinchEvent>();

    qmlRegisterType<QQuickShaderEffect>("QtQuick", 2, 0, "ShaderEffect");
    qmlRegisterType<QQuickShaderEffectSource>("QtQuick", 2, 0, "ShaderEffectSource");
    qmlRegisterUncreatableType<QQuickShaderEffectMesh>("QtQuick", 2, 0, "ShaderEffectMesh", QQuickShaderEffectMesh::tr("Cannot create instance of abstract class ShaderEffectMesh."));
    qmlRegisterType<QQuickGridMesh>("QtQuick", 2, 0, "GridMesh");

    qmlRegisterUncreatableType<QQuickPaintedItem>("QtQuick", 2, 0, "PaintedItem", QQuickPaintedItem::tr("Cannot create instance of abstract class PaintedItem"));

    qmlRegisterType<QQuickCanvasItem>("QtQuick", 2, 0, "Canvas");

    qmlRegisterType<QQuickSprite>("QtQuick", 2, 0, "Sprite");
    qmlRegisterType<QQuickAnimatedSprite>("QtQuick", 2, 0, "AnimatedSprite");
    qmlRegisterType<QQuickSpriteSequence>("QtQuick", 2, 0, "SpriteSequence");

    qmlRegisterType<QQuickParentChange>(uri, major, minor,"ParentChange");
    qmlRegisterType<QQuickAnchorChanges>(uri, major, minor,"AnchorChanges");
    qmlRegisterType<QQuickAnchorSet>();
    qmlRegisterType<QQuickAnchorAnimation>(uri, major, minor,"AnchorAnimation");
    qmlRegisterType<QQuickParentAnimation>(uri, major, minor,"ParentAnimation");
    qmlRegisterType<QQuickPathAnimation>("QtQuick",2,0,"PathAnimation");
    qmlRegisterType<QQuickPathInterpolator>("QtQuick",2,0,"PathInterpolator");

#ifndef QT_NO_DRAGANDDROP
    qmlRegisterType<QQuickDropArea>("QtQuick", 2, 0, "DropArea");
    qmlRegisterType<QQuickDropEvent>();
    qmlRegisterType<QQuickDropAreaDrag>();
    qmlRegisterUncreatableType<QQuickDrag>("QtQuick", 2, 0, "Drag", QQuickDragAttached::tr("Drag is only available via attached properties"));
#endif

    qmlRegisterType<QQuickMultiPointTouchArea>("QtQuick", 2, 0, "MultiPointTouchArea");
    qmlRegisterType<QQuickTouchPoint>("QtQuick", 2, 0, "TouchPoint");
    qmlRegisterType<QQuickGrabGestureEvent>();

#ifndef QT_NO_ACCESSIBILITY
    qmlRegisterUncreatableType<QQuickAccessibleAttached>("QtQuick", 2, 0, "Accessible",QQuickAccessibleAttached::tr("Accessible is only available via attached properties"));
#endif

    qmlRegisterType<QQuickItem, 1>(uri, 2, 1,"Item");
    qmlRegisterType<QQuickGrid, 1>(uri, 2, 1, "Grid");
    qmlRegisterUncreatableType<QQuickItemView, 1>(uri, 2, 1, "ItemView", QQuickItemView::tr("ItemView is an abstract base class"));
    qmlRegisterType<QQuickListView, 1>(uri, 2, 1, "ListView");
    qmlRegisterType<QQuickGridView, 1>(uri, 2, 1, "GridView");
    qmlRegisterType<QQuickTextEdit, 1>(uri, 2, 1, "TextEdit");

    qmlRegisterType<QQuickText, 2>(uri, 2, 2, "Text");
    qmlRegisterType<QQuickTextEdit, 2>(uri, 2, 2, "TextEdit");
}

void QQuickItemsModule::defineModule()
{
    QByteArray name = "QtQuick";
    int majorVersion = 2;
    int minorVersion = 0;

    qt_quickitems_defineModule(name, majorVersion, minorVersion);
}

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

#include "qquickitemsmodule_p.h"

#include "qquickitem.h"
#include "qquickitem_p.h"
#include "qquickevents_p_p.h"
#include "qquickrectangle_p.h"
#include "qquickfocusscope_p.h"
#include "qquicktext_p.h"
#include "qquicktextinput_p.h"
#include "qquicktextedit_p.h"
#include "qquicktextdocument.h"
#include "qquickimage_p.h"
#include "qquickborderimage_p.h"
#include "qquickscalegrid_p_p.h"
#include "qquickmousearea_p.h"
#include "qquickpincharea_p.h"
#include "qquickflickable_p.h"
#include "qquickflickable_p_p.h"
#include "qquicklistview_p.h"
#include "qquickgridview_p.h"
#include "qquickpathview_p.h"
#include "qquickitemviewtransition_p.h"
#include <private/qquickpath_p.h>
#include <private/qquickpathinterpolator_p.h>
#include "qquickpositioners_p.h"
#include "qquickrepeater_p.h"
#include "qquickloader_p.h"
#include "qquickanimatedimage_p.h"
#include "qquickflipable_p.h"
#include "qquicktranslate_p.h"
#include "qquickstateoperations_p.h"
#include "qquickitemanimation_p.h"
#include <private/qquickshadereffect_p.h>
#include <QtQuick/private/qquickshadereffectsource_p.h>
//#include <private/qquickpincharea_p.h>
#include <QtQuick/private/qquickcanvasitem_p.h>
#include <QtQuick/private/qquickcontext2d_p.h>
#include "qquicksprite_p.h"
#include "qquickspritesequence_p.h"
#include "qquickanimatedsprite_p.h"
#include "qquickdrag_p.h"
#include "qquickdroparea_p.h"
#include "qquickmultipointtoucharea_p.h"
#include <private/qqmlmetatype_p.h>
#include <QtQuick/private/qquickaccessibleattached_p.h>

static QQmlPrivate::AutoParentResult qquickitem_autoParent(QObject *obj, QObject *parent)
{
    // When setting a parent (especially during dynamic object creation) in QML,
    // also try to set up the analogous item/window relationship.
    QQuickItem *parentItem = qmlobject_cast<QQuickItem *>(parent);
    if (parentItem) {
        QQuickItem *item = qmlobject_cast<QQuickItem *>(obj);
        if (item) {
            // An Item has another Item
            item->setParentItem(parentItem);
            return QQmlPrivate::Parented;
        } else if (parentItem->window()) {
            QQuickWindow *win = qmlobject_cast<QQuickWindow *>(obj);
            if (win) {
                // A Window inside an Item should be transient for that item's window
                win->setTransientParent(parentItem->window());
                return QQmlPrivate::Parented;
            }
        }
        return QQmlPrivate::IncompatibleObject;
    } else {
        QQuickWindow *parentWindow = qmlobject_cast<QQuickWindow *>(parent);
        if (parentWindow) {
            QQuickWindow *win = qmlobject_cast<QQuickWindow *>(obj);
            if (win) {
                // A Window inside a Window should be transient for it
                win->setTransientParent(parentWindow);
                return QQmlPrivate::Parented;
            } else {
                QQuickItem *item = qmlobject_cast<QQuickItem *>(obj);
                if (item) {
                    // The parent of an Item inside a Window is actually the implicit content Item
                    item->setParentItem(parentWindow->contentItem());
                    return QQmlPrivate::Parented;
                }
            }
            return QQmlPrivate::IncompatibleObject;
        }
    }
    return QQmlPrivate::IncompatibleParent;
}

static bool compareQQuickAnchorLines(const void *p1, const void *p2)
{
    const QQuickAnchorLine &l1 = *static_cast<const QQuickAnchorLine*>(p1);
    const QQuickAnchorLine &l2 = *static_cast<const QQuickAnchorLine*>(p2);
    return l1 == l2;
}

static void qt_quickitems_defineModule(const char *uri, int major, int minor)
{
    QQmlPrivate::RegisterAutoParent autoparent = { 0, &qquickitem_autoParent };
    QQmlPrivate::qmlregister(QQmlPrivate::AutoParentRegistration, &autoparent);
    QQuickItemPrivate::registerAccessorProperties();

#ifdef QT_NO_MOVIE
    qmlRegisterTypeNotAvailable(uri,major,minor,"AnimatedImage", qApp->translate("QQuickAnimatedImage","Qt was built without support for QMovie"));
#else
    qmlRegisterType<QQuickAnimatedImage>(uri,major,minor,"AnimatedImage");
#endif
    qmlRegisterType<QQuickBorderImage>(uri,major,minor,"BorderImage");
    qmlRegisterType<QQuickColumn>(uri,major,minor,"Column");
    qmlRegisterType<QQuickFlickable>(uri,major,minor,"Flickable");
    qmlRegisterType<QQuickFlipable>(uri,major,minor,"Flipable");
    qmlRegisterType<QQuickFlow>(uri,major,minor,"Flow");
//    qmlRegisterType<QQuickFocusPanel>(uri,major,minor,"FocusPanel");
    qmlRegisterType<QQuickFocusScope>(uri,major,minor,"FocusScope");
    qmlRegisterType<QQuickGradient>(uri,major,minor,"Gradient");
    qmlRegisterType<QQuickGradientStop>(uri,major,minor,"GradientStop");
    qmlRegisterType<QQuickGrid>(uri,major,minor,"Grid");
    qmlRegisterType<QQuickGridView>(uri,major,minor,"GridView");
    qmlRegisterType<QQuickImage>(uri,major,minor,"Image");
    qmlRegisterType<QQuickItem>(uri,major,minor,"Item");
    qmlRegisterType<QQuickListView>(uri,major,minor,"ListView");
    qmlRegisterType<QQuickLoader>(uri,major,minor,"Loader");
    qmlRegisterType<QQuickMouseArea>(uri,major,minor,"MouseArea");
    qmlRegisterType<QQuickPath>(uri,major,minor,"Path");
    qmlRegisterType<QQuickPathAttribute>(uri,major,minor,"PathAttribute");
    qmlRegisterType<QQuickPathCubic>(uri,major,minor,"PathCubic");
    qmlRegisterType<QQuickPathLine>(uri,major,minor,"PathLine");
    qmlRegisterType<QQuickPathPercent>(uri,major,minor,"PathPercent");
    qmlRegisterType<QQuickPathQuad>(uri,major,minor,"PathQuad");
    qmlRegisterType<QQuickPathCatmullRomCurve>("QtQuick",2,0,"PathCurve");
    qmlRegisterType<QQuickPathArc>("QtQuick",2,0,"PathArc");
    qmlRegisterType<QQuickPathSvg>("QtQuick",2,0,"PathSvg");
    qmlRegisterType<QQuickPathView>(uri,major,minor,"PathView");
    qmlRegisterUncreatableType<QQuickBasePositioner>(uri,major,minor,"Positioner",
                                                  QStringLiteral("Positioner is an abstract type that is only available as an attached property."));
#ifndef QT_NO_VALIDATOR
    qmlRegisterType<QQuickIntValidator>(uri,major,minor,"IntValidator");
    qmlRegisterType<QQuickDoubleValidator>(uri,major,minor,"DoubleValidator");
    qmlRegisterType<QRegExpValidator>(uri,major,minor,"RegExpValidator");
#endif
    qmlRegisterType<QQuickRectangle>(uri,major,minor,"Rectangle");
    qmlRegisterType<QQuickRepeater>(uri,major,minor,"Repeater");
    qmlRegisterType<QQuickRow>(uri,major,minor,"Row");
    qmlRegisterType<QQuickTranslate>(uri,major,minor,"Translate");
    qmlRegisterType<QQuickRotation>(uri,major,minor,"Rotation");
    qmlRegisterType<QQuickScale>(uri,major,minor,"Scale");
    qmlRegisterType<QQuickText>(uri,major,minor,"Text");
    qmlRegisterType<QQuickTextEdit>(uri,major,minor,"TextEdit");
    qmlRegisterType<QQuickTextEdit,1>(uri,2,1,"TextEdit");
    qmlRegisterType<QQuickTextInput>(uri,major,minor,"TextInput");
    qmlRegisterType<QQuickViewSection>(uri,major,minor,"ViewSection");

    qmlRegisterType<QQuickItemLayer>();
    qmlRegisterType<QQuickAnchors>();
    qmlRegisterType<QQuickKeyEvent>();
    qmlRegisterType<QQuickMouseEvent>();
    qmlRegisterType<QQuickWheelEvent>();
    qmlRegisterType<QQuickCloseEvent>();
    qmlRegisterType<QQuickTransform>();
    qmlRegisterType<QQuickPathElement>();
    qmlRegisterType<QQuickCurve>();
    qmlRegisterType<QQuickScaleGrid>();
    qmlRegisterType<QQuickTextLine>();
#ifndef QT_NO_VALIDATOR
    qmlRegisterType<QValidator>();
#endif
    qmlRegisterType<QQuickPen>();
    qmlRegisterType<QQuickFlickableVisibleArea>();
    qRegisterMetaType<QQuickAnchorLine>("QQuickAnchorLine");
    QQmlMetaType::setQQuickAnchorLineCompareFunction(compareQQuickAnchorLines);

    qmlRegisterType<QQuickTextDocument>();

    qmlRegisterUncreatableType<QQuickKeyNavigationAttached>(uri,major,minor,"KeyNavigation",QQuickKeyNavigationAttached::tr("KeyNavigation is only available via attached properties"));
    qmlRegisterUncreatableType<QQuickKeysAttached>(uri,major,minor,"Keys",QQuickKeysAttached::tr("Keys is only available via attached properties"));
    qmlRegisterUncreatableType<QQuickLayoutMirroringAttached>(uri,major,minor,"LayoutMirroring", QQuickLayoutMirroringAttached::tr("LayoutMirroring is only available via attached properties"));
    qmlRegisterUncreatableType<QQuickViewTransitionAttached>(uri,major,minor,"ViewTransition",QQuickViewTransitionAttached::tr("ViewTransition is only available via attached properties"));

    qmlRegisterType<QQuickPinchArea>(uri,major,minor,"PinchArea");
    qmlRegisterType<QQuickPinch>(uri,major,minor,"Pinch");
    qmlRegisterType<QQuickPinchEvent>();

    qmlRegisterType<QQuickShaderEffect>("QtQuick", 2, 0, "ShaderEffect");
    qmlRegisterType<QQuickShaderEffectSource>("QtQuick", 2, 0, "ShaderEffectSource");
    qmlRegisterUncreatableType<QQuickShaderEffectMesh>("QtQuick", 2, 0, "ShaderEffectMesh", QQuickShaderEffectMesh::tr("Cannot create instance of abstract class ShaderEffectMesh."));
    qmlRegisterType<QQuickGridMesh>("QtQuick", 2, 0, "GridMesh");

    qmlRegisterUncreatableType<QQuickPaintedItem>("QtQuick", 2, 0, "PaintedItem", QQuickPaintedItem::tr("Cannot create instance of abstract class PaintedItem"));

    qmlRegisterType<QQuickCanvasItem>("QtQuick", 2, 0, "Canvas");

    qmlRegisterType<QQuickSprite>("QtQuick", 2, 0, "Sprite");
    qmlRegisterType<QQuickAnimatedSprite>("QtQuick", 2, 0, "AnimatedSprite");
    qmlRegisterType<QQuickSpriteSequence>("QtQuick", 2, 0, "SpriteSequence");

    qmlRegisterType<QQuickParentChange>(uri, major, minor,"ParentChange");
    qmlRegisterType<QQuickAnchorChanges>(uri, major, minor,"AnchorChanges");
    qmlRegisterType<QQuickAnchorSet>();
    qmlRegisterType<QQuickAnchorAnimation>(uri, major, minor,"AnchorAnimation");
    qmlRegisterType<QQuickParentAnimation>(uri, major, minor,"ParentAnimation");
    qmlRegisterType<QQuickPathAnimation>("QtQuick",2,0,"PathAnimation");
    qmlRegisterType<QQuickPathInterpolator>("QtQuick",2,0,"PathInterpolator");

#ifndef QT_NO_DRAGANDDROP
    qmlRegisterType<QQuickDropArea>("QtQuick", 2, 0, "DropArea");
    qmlRegisterType<QQuickDropEvent>();
    qmlRegisterType<QQuickDropAreaDrag>();
    qmlRegisterUncreatableType<QQuickDrag>("QtQuick", 2, 0, "Drag", QQuickDragAttached::tr("Drag is only available via attached properties"));
#endif

    qmlRegisterType<QQuickMultiPointTouchArea>("QtQuick", 2, 0, "MultiPointTouchArea");
    qmlRegisterType<QQuickTouchPoint>("QtQuick", 2, 0, "TouchPoint");
    qmlRegisterType<QQuickGrabGestureEvent>();

#ifndef QT_NO_ACCESSIBILITY
    qmlRegisterUncreatableType<QQuickAccessibleAttached>("QtQuick", 2, 0, "Accessible",QQuickAccessibleAttached::tr("Accessible is only available via attached properties"));
#endif

    qmlRegisterType<QQuickItem, 1>(uri, 2, 1,"Item");
    qmlRegisterType<QQuickGrid, 1>(uri, 2, 1, "Grid");
    qmlRegisterUncreatableType<QQuickItemView, 1>(uri, 2, 1, "ItemView", QQuickItemView::tr("ItemView is an abstract base class"));
    qmlRegisterType<QQuickListView, 1>(uri, 2, 1, "ListView");
    qmlRegisterType<QQuickGridView, 1>(uri, 2, 1, "GridView");
    qmlRegisterType<QQuickTextEdit, 1>(uri, 2, 1, "TextEdit");

    qmlRegisterType<QQuickText, 2>(uri, 2, 2, "Text");
    qmlRegisterType<QQuickTextEdit, 2>(uri, 2, 2, "TextEdit");
}

QT_BEGIN_NAMESPACE

void QQuickItemsModule::defineModule()
{
    QByteArray name = "QtQuick";
    int majorVersion = 2;
    int minorVersion = 0;

    qt_quickitems_defineModule(name, majorVersion, minorVersion);
}

QT_END_NAMESPACE
<|endoftext|>