<commit_before>/* rbOOmit: An implementation of the Certified Reduced Basis method. */
/* Copyright (C) 2009, 2010 David J. Knezevic */
/*     This file is part of rbOOmit. */

/* rbOOmit is free software; you can redistribute it and/or */
/* modify it under the terms of the GNU Lesser General Public */
/* License as published by the Free Software Foundation; either */
/* version 2.1 of the License, or (at your option) any later version. */

/* rbOOmit is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU */
/* Lesser General Public License for more details. */

/* You should have received a copy of the GNU Lesser General Public */
/* License along with this library; if not, write to the Free Software */
/* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

//
Reduced Basis: Example 5 - Reduced Basis Cantilever

// 3D cantilever beam using the Reduced Basis Method
// David Knezevic, Kyung Hoon Lee
//
// We consider four parameters in this problem:
//  x_scaling: scales the length of the cantilever
//  load_Fx: the traction in the x-direction on the right boundary of the cantilever
//  load_Fy: the traction in the y-direction on the right boundary of the cantilever
//  load_Fz: the traction in the z-direction on the right boundary of the cantilever

// C++ include files that we need
#include <iostream>
#include <algorithm>
#include <cmath>
#include <set>

// Basic include file needed for the mesh functionality.
#include "libmesh.h"
#include "mesh.h"
#include "mesh_generation.h"
#include "exodusII_io.h"
#include "equation_systems.h"
#include "dof_map.h"
#include "getpot.h"
#include "elem.h"

// local includes
#include "rb_classes.h"
#include "assembly.h"

// Bring in everything from the libMesh namespace
using namespace libMesh;

// Define a function to scale the mesh according to the parameter.
void scale_mesh_and_plot(EquationSystems& es, const RBParameters& mu, const std::string& filename);

// The main program.
int main(int argc, char** argv) {
	// Initialize libMesh.
	LibMeshInit init (argc, argv);

#if !defined(LIBMESH_HAVE_XDR)
  // We need XDR support to write out reduced bases
  libmesh_example_assert(false, "--enable-xdr");
#elif defined(LIBMESH_DEFAULT_SINGLE_PRECISION)
  // XDR binary support requires double precision
  libmesh_example_assert(false, "--disable-singleprecision");
#endif

  // This example only works if libMesh was compiled for 3D
  const unsigned int dim = 3;
  libmesh_example_assert(dim == LIBMESH_DIM, "3D support");

	std::string parameters_filename = "reduced_basis_ex5.in";
	GetPot infile(parameters_filename);

  unsigned int n_elem_x  = infile("n_elem_x",0);
  unsigned int n_elem_y  = infile("n_elem_y",0);
  unsigned int n_elem_z  = infile("n_elem_z",0);
  Real x_size            = infile("x_size", 0.);
  Real y_size            = infile("y_size", 0.);
  Real z_size            = infile("z_size", 0.);

	bool store_basis_functions = infile("store_basis_functions", true);

	// Read the "online_mode" flag from the command line
	GetPot command_line(argc, argv);
	int online_mode = 0;
	if ( command_line.search(1, "-online_mode") ) {
		online_mode = command_line.next(online_mode);
	}

  Mesh mesh (dim);
  MeshTools::Generation::build_cube (mesh,
                                     n_elem_x,
                                     n_elem_y,
                                     n_elem_z,
                                     0., x_size,
                                     0., y_size,
                                     0., z_size,
                                     HEX8);
	 mesh.print_info();

	// Create an equation systems object.
	EquationSystems equation_systems(mesh);

	// We override RBConstruction with ElasticityRBConstruction in order to
	// specialize a few functions for this particular problem.
	ElasticityRBConstruction& rb_con =
		equation_systems.add_system<ElasticityRBConstruction>("RBElasticity");

	// Initialize the data structures for the equation system.
	equation_systems.init ();
  equation_systems.print_info();

	// Build a new RBEvaluation object which will be used to perform
	// Reduced Basis calculations. This is required in both the
	// "Offline" and "Online" stages.
	ElasticityRBEvaluation rb_eval;

	// We need to give the RBConstruction object a pointer to
	// our RBEvaluation object
	rb_con.set_rb_evaluation(rb_eval);

	if(!online_mode) // Perform the Offline stage of the RB method
	{
		// Read in the data that defines this problem from the specified text file
		rb_con.process_parameters_file(parameters_filename);

		// Print out info that describes the current setup of rb_con
		rb_con.print_info();

		// Prepare rb_con for the Construction stage of the RB method.
		// This sets up the necessary data structures and performs
		// initial assembly of the "truth" affine expansion of the PDE.
		rb_con.initialize_rb_construction();

		// Compute the reduced basis space by computing "snapshots", i.e.
		// "truth" solves, at well-chosen parameter values and employing
		// these snapshots as basis functions.
		rb_con.train_reduced_basis();

		// Write out the data that will subsequently be required for the Evaluation stage
		rb_con.get_rb_evaluation().write_offline_data_to_files();

		// If requested, write out the RB basis functions for visualization purposes
		if(store_basis_functions)
		{
			// Write out the basis functions
			rb_con.get_rb_evaluation().write_out_basis_functions(rb_con);
		}
	}
	else // Perform the Online stage of the RB method
	{
		// Read in the reduced basis data
		rb_eval.read_offline_data_from_files();

		// Iinitialize online parameters
		Real online_x_scaling = infile("online_x_scaling", 0.);
		Real online_load_Fx   = infile("online_load_Fx",   0.);
		Real online_load_Fy   = infile("online_load_Fy",   0.);
		Real online_load_Fz   = infile("online_load_Fz",   0.);
		RBParameters online_mu;
		online_mu.set_value("x_scaling", online_x_scaling);
		online_mu.set_value("load_Fx",   online_load_Fx);
		online_mu.set_value("load_Fy",   online_load_Fy);
		online_mu.set_value("load_Fz",   online_load_Fz);
		rb_eval.set_parameters(online_mu);
		rb_eval.print_parameters();

		// Now do the Online solve using the precomputed reduced basis
		rb_eval.rb_solve( rb_eval.get_n_basis_functions() );

		if(store_basis_functions)
		{
			// Read in the basis functions
			rb_eval.read_in_basis_functions(rb_con);

			// Plot the solution
			rb_con.load_rb_solution();

			const RBParameters& rb_eval_params = rb_eval.get_parameters();
			scale_mesh_and_plot(equation_systems, rb_eval_params, "RB_sol.e");
		}
	}

	return 0;
}

void scale_mesh_and_plot(EquationSystems& es, const RBParameters& mu, const std::string& filename)
{
  const Real x_scaling = mu.get_value("x_scaling");

  // Loop over the mesh nodes and move them!
  MeshBase& mesh = es.get_mesh();

  MeshBase::node_iterator       node_it  = mesh.nodes_begin();
  const MeshBase::node_iterator node_end = mesh.nodes_end();

  for( ; node_it != node_end; node_it++)
  {
    Node* node = *node_it;

    (*node)(0) *= mu.get_value("x_scaling");
  }

#ifdef LIBMESH_HAVE_EXODUS_API
  ExodusII_IO (mesh).write_equation_systems (filename, es);
#endif

  // Loop over the mesh nodes and move them!
  node_it = mesh.nodes_begin();

  for( ; node_it != node_end; node_it++)
  {
    Node* node = *node_it;

    (*node)(0) /= mu.get_value("x_scaling");
  }
}
<commit_msg>corrected K's name in the example<commit_after>/* rbOOmit: An implementation of the Certified Reduced Basis method. */
/* Copyright (C) 2009, 2010 David J. Knezevic */
/*     This file is part of rbOOmit. */

/* rbOOmit is free software; you can redistribute it and/or */
/* modify it under the terms of the GNU Lesser General Public */
/* License as published by the Free Software Foundation; either */
/* version 2.1 of the License, or (at your option) any later version. */

/* rbOOmit is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU */
/* Lesser General Public License for more details. */

/* You should have received a copy of the GNU Lesser General Public */
/* License along with this library; if not, write to the Free Software */
/* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

//
Reduced Basis: Example 5 - Reduced Basis Cantilever

// 3D cantilever beam using the Reduced Basis Method
// David Knezevic, Kyunghoon "K" Lee
//
// We consider four parameters in this problem:
//  x_scaling: scales the length of the cantilever
//  load_Fx: the traction in the x-direction on the right boundary of the cantilever
//  load_Fy: the traction in the y-direction on the right boundary of the cantilever
//  load_Fz: the traction in the z-direction on the right boundary of the cantilever

// C++ include files that we need
#include <iostream>
#include <algorithm>
#include <cmath>
#include <set>

// Basic include file needed for the mesh functionality.
#include "libmesh.h"
#include "mesh.h"
#include "mesh_generation.h"
#include "exodusII_io.h"
#include "equation_systems.h"
#include "dof_map.h"
#include "getpot.h"
#include "elem.h"

// local includes
#include "rb_classes.h"
#include "assembly.h"

// Bring in everything from the libMesh namespace
using namespace libMesh;

// Define a function to scale the mesh according to the parameter.
void scale_mesh_and_plot(EquationSystems& es, const RBParameters& mu, const std::string& filename);

// The main program.
int main(int argc, char** argv) {
	// Initialize libMesh.
	LibMeshInit init (argc, argv);

#if !defined(LIBMESH_HAVE_XDR)
  // We need XDR support to write out reduced bases
  libmesh_example_assert(false, "--enable-xdr");
#elif defined(LIBMESH_DEFAULT_SINGLE_PRECISION)
  // XDR binary support requires double precision
  libmesh_example_assert(false, "--disable-singleprecision");
#endif

  // This example only works if libMesh was compiled for 3D
  const unsigned int dim = 3;
  libmesh_example_assert(dim == LIBMESH_DIM, "3D support");

	std::string parameters_filename = "reduced_basis_ex5.in";
	GetPot infile(parameters_filename);

  unsigned int n_elem_x  = infile("n_elem_x",0);
  unsigned int n_elem_y  = infile("n_elem_y",0);
  unsigned int n_elem_z  = infile("n_elem_z",0);
  Real x_size            = infile("x_size", 0.);
  Real y_size            = infile("y_size", 0.);
  Real z_size            = infile("z_size", 0.);

	bool store_basis_functions = infile("store_basis_functions", true);

	// Read the "online_mode" flag from the command line
	GetPot command_line(argc, argv);
	int online_mode = 0;
	if ( command_line.search(1, "-online_mode") ) {
		online_mode = command_line.next(online_mode);
	}

  Mesh mesh (dim);
  MeshTools::Generation::build_cube (mesh,
                                     n_elem_x,
                                     n_elem_y,
                                     n_elem_z,
                                     0., x_size,
                                     0., y_size,
                                     0., z_size,
                                     HEX8);
	 mesh.print_info();

	// Create an equation systems object.
	EquationSystems equation_systems(mesh);

	// We override RBConstruction with ElasticityRBConstruction in order to
	// specialize a few functions for this particular problem.
	ElasticityRBConstruction& rb_con =
		equation_systems.add_system<ElasticityRBConstruction>("RBElasticity");

	// Initialize the data structures for the equation system.
	equation_systems.init ();
  equation_systems.print_info();

	// Build a new RBEvaluation object which will be used to perform
	// Reduced Basis calculations. This is required in both the
	// "Offline" and "Online" stages.
	ElasticityRBEvaluation rb_eval;

	// We need to give the RBConstruction object a pointer to
	// our RBEvaluation object
	rb_con.set_rb_evaluation(rb_eval);

	if(!online_mode) // Perform the Offline stage of the RB method
	{
		// Read in the data that defines this problem from the specified text file
		rb_con.process_parameters_file(parameters_filename);

		// Print out info that describes the current setup of rb_con
		rb_con.print_info();

		// Prepare rb_con for the Construction stage of the RB method.
		// This sets up the necessary data structures and performs
		// initial assembly of the "truth" affine expansion of the PDE.
		rb_con.initialize_rb_construction();

		// Compute the reduced basis space by computing "snapshots", i.e.
		// "truth" solves, at well-chosen parameter values and employing
		// these snapshots as basis functions.
		rb_con.train_reduced_basis();

		// Write out the data that will subsequently be required for the Evaluation stage
		rb_con.get_rb_evaluation().write_offline_data_to_files();

		// If requested, write out the RB basis functions for visualization purposes
		if(store_basis_functions)
		{
			// Write out the basis functions
			rb_con.get_rb_evaluation().write_out_basis_functions(rb_con);
		}
	}
	else // Perform the Online stage of the RB method
	{
		// Read in the reduced basis data
		rb_eval.read_offline_data_from_files();

		// Iinitialize online parameters
		Real online_x_scaling = infile("online_x_scaling", 0.);
		Real online_load_Fx   = infile("online_load_Fx",   0.);
		Real online_load_Fy   = infile("online_load_Fy",   0.);
		Real online_load_Fz   = infile("online_load_Fz",   0.);
		RBParameters online_mu;
		online_mu.set_value("x_scaling", online_x_scaling);
		online_mu.set_value("load_Fx",   online_load_Fx);
		online_mu.set_value("load_Fy",   online_load_Fy);
		online_mu.set_value("load_Fz",   online_load_Fz);
		rb_eval.set_parameters(online_mu);
		rb_eval.print_parameters();

		// Now do the Online solve using the precomputed reduced basis
		rb_eval.rb_solve( rb_eval.get_n_basis_functions() );

		if(store_basis_functions)
		{
			// Read in the basis functions
			rb_eval.read_in_basis_functions(rb_con);

			// Plot the solution
			rb_con.load_rb_solution();

			const RBParameters& rb_eval_params = rb_eval.get_parameters();
			scale_mesh_and_plot(equation_systems, rb_eval_params, "RB_sol.e");
		}
	}

	return 0;
}

void scale_mesh_and_plot(EquationSystems& es, const RBParameters& mu, const std::string& filename)
{
  const Real x_scaling = mu.get_value("x_scaling");

  // Loop over the mesh nodes and move them!
  MeshBase& mesh = es.get_mesh();

  MeshBase::node_iterator       node_it  = mesh.nodes_begin();
  const MeshBase::node_iterator node_end = mesh.nodes_end();

  for( ; node_it != node_end; node_it++)
  {
    Node* node = *node_it;

    (*node)(0) *= mu.get_value("x_scaling");
  }

#ifdef LIBMESH_HAVE_EXODUS_API
  ExodusII_IO (mesh).write_equation_systems (filename, es);
#endif

  // Loop over the mesh nodes and move them!
  node_it = mesh.nodes_begin();

  for( ; node_it != node_end; node_it++)
  {
    Node* node = *node_it;

    (*node)(0) /= mu.get_value("x_scaling");
  }
}
<|endoftext|>


<commit_before>#ifndef H_EXTENSIONS_CUTEHMI_2_INCLUDE_CUTEHMI_INTERNATIONALIZER_HPP
#define H_EXTENSIONS_CUTEHMI_2_INCLUDE_CUTEHMI_INTERNATIONALIZER_HPP

#include "internal/common.hpp"
#include "Singleton.hpp"

#include <QObject>
#include <QMap>
#include <QTranslator>

namespace cutehmi {

/**
 * Internationalization singleton.
 */
class CUTEHMI_API Internationalizer:
	public QObject,
	public Singleton<Internationalizer>
{
		Q_OBJECT

		friend class Singleton<Internationalizer>;
		friend class test_Internationalizer;

	public:
		/**
		  User interface language.
		  */
		Q_PROPERTY(QString uiLanguage READ uiLanguage WRITE setUILanguage NOTIFY uiLanguageChanged)

		/**
		 * Get user interface language.
		 * @return currently used user interface language.
		 */
		QString uiLanguage() const;

		/**
		 * Set user interface language.
		 * @param uiLanguage language to be currently used.
		 */
		void setUILanguage(const QString & uiLanguage);

		/**
		 * Load Qt translation.
		 */
		Q_INVOKABLE void loadQtTranslation();

		/**
		 * Unload Qt translation.
		 */
		Q_INVOKABLE void unloadQtTranslation();

		/**
		 * Load translation of %CuteHMI product. Typically product is an extension, but the function can be also used to load
		 * translation of a tool or even a test.
		 *
		 * In order to load a translation function looks at various directories as returned by standardTranslationDirectories()
		 * function. The directories are searched in the same order as they appear in the list. Additional directories can be
		 * specified by setAdditionalTranslationDirectories() function. Additional directories take precedence over standard ones.
		 *
		 * To obtain the stem of the translation file, product name is lowercased and all the dots are replaced with hyphens, thus
		 * for example @p CuteHMI.2 becomes @p cutehmi-2. After that several file suffixes are tested in each of the translation
		 * directories as specified by QTranslator::load() function and "_qt.qm" suffix is used to satisfy KDE internationalization
		 * framework convention. For example, for @p CuteHMI.2 product any of the following translation files will match @p en-US
		 * translation: @p cutehmi-2.qm, @p cutehmi-2_en.qm, @p cutehmi-2_en_US.qm, @p cutehmi-2.en.qm, @p cutehmi-2.en_US.qm,
		 * @p cutehmi-2_qt.qm, @p cutehmi-2_en_qt.qm, @p cutehmi-2_en_US_qt.qm, @p cutehmi-2.en_qt.qm, @p cutehmi-2.en_US_qt.qm.
		 *
		 * @param product product name.
		 * @param dependencies denotes if translations of product dependencies should be loaded as well. Dependency information is
		 * retrieved from metadata, so it is important to specify appropriate dependencies in Qbs file.
		 */
		Q_INVOKABLE void loadTranslation(const QString & product, bool dependencies = true);

		/**
		 * Unload translations of a specific product.
		 * @param product product name.
		 */
		Q_INVOKABLE void unloadTranslation(const QString & product);

		/**
		 * Unload loaded translations. Function unloads any previously loaded translation of a product and optionally Qt
		 * translation.
		 * @param qt whether to unload Qt translation. If set to @p true, Qt translation will be unloaded.
		 */
		Q_INVOKABLE void unloadTranslations(bool qt = true);

		/**
		 * Get standard translation directories. The list is composed of following entries:
		 * - CuteHMI-specific "translations" subdirectory.
		 * - In an attempt to satisfy gettext convention, path specified by LOCPATH environmental variable followed by
		 * <tt>{langdir}/LC_MESSAGES</tt> is used. The @p {langdir} subdirectory is obtained from \ref uiLanguage passed through
		 * QLocale::uiLanguages() function. Hyphens are replaced by underscores, so that <tt>en-US</tt> becomes <tt>en_US</tt>.
		 * - In an attempt to satisfy gettext convention, directories specified by XDG_DATA_HOME environmental variable followed by
		 * <tt>/locale/{langdir}/LC_MESSAGES</tt> are used. If XDG_DATA_HOME has not been set,
		 * <tt>HOME/.local/share</tt> is being used. The @p {langdir} subdirectory is obtained in the same way as above.
		 * - In an attempt to satisfy gettext convention, directories specified by XDG_DATA_DIRS environmental variable followed by
		 * <tt>/locale/{langdir}/LC_MESSAGES</tt> are used. If XDG_DATA_DIRS has not been set, <tt>usr/local/share/</tt> and
		 * <tt>/usr/share/</tt> are used. The @p {langdir} subdirectory is obtained in the same way as above.
		 * @return list of standard translation directories.
		 * - Directories returned by QLibraryInfo::location(QLibraryInfo::TranslationsPath) are ued.
		 *
		 * @see additionalTranslationDirectories().
		 */
		Q_INVOKABLE QStringList standardTranslationDirectories() const;

		/**
		 * Get additional translation directories.
		 * @return list of additional translation directories. By default this list is empty.
		 *
		 * @see setAdditionalTranslationDirectories().
		 */
		Q_INVOKABLE QStringList additionalTranslationDirectories() const;

		/**
		 * Set additional translation directories.
		 * @param additionalDirectories additional directories, where translation files may reside.
		 *
		 * @see additionalTranslationDirectories(), standardTranslationDirectories().
		 */
		Q_INVOKABLE void setAdditionalTranslationDirectories(const QStringList & additionalDirectories);

	signals:
		/**
		 * User interface language has changed.
		 */
		void uiLanguageChanged();

	private:
		typedef QMap<QString, QTranslator *> TranslatorsContainer;

		/**
		 * Default constructor.
		 * @param parent parent object.
		 */
		explicit Internationalizer(QObject * parent = nullptr);

		void updateTranslation(QTranslator & translator, const QString & product, const QStringList & directories);

		void updateQtTranslation(QTranslator & translator);

		QString translationFileStem(const QString & product);

		QStringList translationDirectories() const;

		struct Members
		{
			QLocale uiLanguage;
			TranslatorsContainer translators;
			QTranslator * qtTranslator = nullptr;
			QStringList additionalTranslationDirectories;
		};

		MPtr<Members> m;
};

}

#endif

//(c)C: Copyright © 2020, Michał Policht <michal@policht.pl>. All rights reserved.
//(c)C: SPDX-License-Identifier: LGPL-3.0-or-later OR MIT
//(c)C: This file is a part of CuteHMI.
//(c)C: CuteHMI is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
//(c)C: CuteHMI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
//(c)C: You should have received a copy of the GNU Lesser General Public License along with CuteHMI.  If not, see <https://www.gnu.org/licenses/>.
//(c)C: Additionally, this file is licensed under terms of MIT license as expressed below.
//(c)C: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//(c)C: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//(c)C: THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
<commit_msg>Fix a typo<commit_after>#ifndef H_EXTENSIONS_CUTEHMI_2_INCLUDE_CUTEHMI_INTERNATIONALIZER_HPP
#define H_EXTENSIONS_CUTEHMI_2_INCLUDE_CUTEHMI_INTERNATIONALIZER_HPP

#include "internal/common.hpp"
#include "Singleton.hpp"

#include <QObject>
#include <QMap>
#include <QTranslator>

namespace cutehmi {

/**
 * Internationalization singleton.
 */
class CUTEHMI_API Internationalizer:
	public QObject,
	public Singleton<Internationalizer>
{
		Q_OBJECT

		friend class Singleton<Internationalizer>;
		friend class test_Internationalizer;

	public:
		/**
		  User interface language.
		  */
		Q_PROPERTY(QString uiLanguage READ uiLanguage WRITE setUILanguage NOTIFY uiLanguageChanged)

		/**
		 * Get user interface language.
		 * @return currently used user interface language.
		 */
		QString uiLanguage() const;

		/**
		 * Set user interface language.
		 * @param uiLanguage language to be currently used.
		 */
		void setUILanguage(const QString & uiLanguage);

		/**
		 * Load Qt translation.
		 */
		Q_INVOKABLE void loadQtTranslation();

		/**
		 * Unload Qt translation.
		 */
		Q_INVOKABLE void unloadQtTranslation();

		/**
		 * Load translation of %CuteHMI product. Typically product is an extension, but the function can be also used to load
		 * translation of a tool or even a test.
		 *
		 * In order to load a translation function looks at various directories as returned by standardTranslationDirectories()
		 * function. The directories are searched in the same order as they appear in the list. Additional directories can be
		 * specified by setAdditionalTranslationDirectories() function. Additional directories take precedence over standard ones.
		 *
		 * To obtain the stem of the translation file, product name is lowercased and all the dots are replaced with hyphens, thus
		 * for example @p CuteHMI.2 becomes @p cutehmi-2. After that several file suffixes are tested in each of the translation
		 * directories as specified by QTranslator::load() function and "_qt.qm" suffix is used to satisfy KDE internationalization
		 * framework convention. For example, for @p CuteHMI.2 product any of the following translation files will match @p en-US
		 * translation: @p cutehmi-2.qm, @p cutehmi-2_en.qm, @p cutehmi-2_en_US.qm, @p cutehmi-2.en.qm, @p cutehmi-2.en_US.qm,
		 * @p cutehmi-2_qt.qm, @p cutehmi-2_en_qt.qm, @p cutehmi-2_en_US_qt.qm, @p cutehmi-2.en_qt.qm, @p cutehmi-2.en_US_qt.qm.
		 *
		 * @param product product name.
		 * @param dependencies denotes if translations of product dependencies should be loaded as well. Dependency information is
		 * retrieved from metadata, so it is important to specify appropriate dependencies in Qbs file.
		 */
		Q_INVOKABLE void loadTranslation(const QString & product, bool dependencies = true);

		/**
		 * Unload translations of a specific product.
		 * @param product product name.
		 */
		Q_INVOKABLE void unloadTranslation(const QString & product);

		/**
		 * Unload loaded translations. Function unloads any previously loaded translation of a product and optionally Qt
		 * translation.
		 * @param qt whether to unload Qt translation. If set to @p true, Qt translation will be unloaded.
		 */
		Q_INVOKABLE void unloadTranslations(bool qt = true);

		/**
		 * Get standard translation directories. The list is composed of following entries:
		 * - CuteHMI-specific "translations" subdirectory.
		 * - In an attempt to satisfy gettext convention, path specified by LOCPATH environmental variable followed by
		 * <tt>{langdir}/LC_MESSAGES</tt> is used. The @p {langdir} subdirectory is obtained from \ref uiLanguage passed through
		 * QLocale::uiLanguages() function. Hyphens are replaced by underscores, so that <tt>en-US</tt> becomes <tt>en_US</tt>.
		 * - In an attempt to satisfy gettext convention, directories specified by XDG_DATA_HOME environmental variable followed by
		 * <tt>/locale/{langdir}/LC_MESSAGES</tt> are used. If XDG_DATA_HOME has not been set,
		 * <tt>HOME/.local/share</tt> is being used. The @p {langdir} subdirectory is obtained in the same way as above.
		 * - In an attempt to satisfy gettext convention, directories specified by XDG_DATA_DIRS environmental variable followed by
		 * <tt>/locale/{langdir}/LC_MESSAGES</tt> are used. If XDG_DATA_DIRS has not been set, <tt>usr/local/share/</tt> and
		 * <tt>/usr/share/</tt> are used. The @p {langdir} subdirectory is obtained in the same way as above.
		 * @return list of standard translation directories.
		 * - Directories returned by QLibraryInfo::location(QLibraryInfo::TranslationsPath) are used.
		 *
		 * @see additionalTranslationDirectories().
		 */
		Q_INVOKABLE QStringList standardTranslationDirectories() const;

		/**
		 * Get additional translation directories.
		 * @return list of additional translation directories. By default this list is empty.
		 *
		 * @see setAdditionalTranslationDirectories().
		 */
		Q_INVOKABLE QStringList additionalTranslationDirectories() const;

		/**
		 * Set additional translation directories.
		 * @param additionalDirectories additional directories, where translation files may reside.
		 *
		 * @see additionalTranslationDirectories(), standardTranslationDirectories().
		 */
		Q_INVOKABLE void setAdditionalTranslationDirectories(const QStringList & additionalDirectories);

	signals:
		/**
		 * User interface language has changed.
		 */
		void uiLanguageChanged();

	private:
		typedef QMap<QString, QTranslator *> TranslatorsContainer;

		/**
		 * Default constructor.
		 * @param parent parent object.
		 */
		explicit Internationalizer(QObject * parent = nullptr);

		void updateTranslation(QTranslator & translator, const QString & product, const QStringList & directories);

		void updateQtTranslation(QTranslator & translator);

		QString translationFileStem(const QString & product);

		QStringList translationDirectories() const;

		struct Members
		{
			QLocale uiLanguage;
			TranslatorsContainer translators;
			QTranslator * qtTranslator = nullptr;
			QStringList additionalTranslationDirectories;
		};

		MPtr<Members> m;
};

}

#endif

//(c)C: Copyright © 2020, Michał Policht <michal@policht.pl>. All rights reserved.
//(c)C: SPDX-License-Identifier: LGPL-3.0-or-later OR MIT
//(c)C: This file is a part of CuteHMI.
//(c)C: CuteHMI is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
//(c)C: CuteHMI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
//(c)C: You should have received a copy of the GNU Lesser General Public License along with CuteHMI.  If not, see <https://www.gnu.org/licenses/>.
//(c)C: Additionally, this file is licensed under terms of MIT license as expressed below.
//(c)C: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//(c)C: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//(c)C: THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
<|endoftext|>


<commit_before>#include <iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define lli long long int

using namespace std;

int main()
{
    int a,b;
    cin >> a >> b;
    cout << a+a+b+b << endl;
	return 0;
}
<commit_msg>Update A_Accepted.cpp<commit_after>#include <iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

using namespace std;

int main()
{
    int a,b;
    cin >> a >> b;
    cout << a+a+b+b << endl;
	return 0;
}
<|endoftext|>


<commit_before>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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 "stdlib/strided_binary.h"
#include "stdlib/ndarray/base/bytes_per_element.h"
#include "stdlib/ndarray/dtypes.h"
#include <node_api.h>
#include <stdint.h>
#include <stdbool.h>
#include <assert.h>

/**
* Add-on namespace.
*/
namespace addon_strided_add {

	/**
	* Adds two doubles.
	*
	* @private
	* @param x  first double
	* @param y  second double
	* @return   sum
	*/
	double add( double x, double y ) {
		return x + y;
	}

	/**
	* Returns a typed array data type.
	*
	* @private
	* @param vtype  typed array type
	* @return       data type
	*/
	enum STDLIB_NDARRAY_DTYPE typed_array_data_type( napi_typedarray_type vtype ) {
		if ( vtype == napi_float64_array ) {
			return STDLIB_NDARRAY_FLOAT64;
		}
		if ( vtype == napi_float32_array ) {
			return STDLIB_NDARRAY_FLOAT32;
		}
		if ( vtype == napi_int32_array ) {
			return STDLIB_NDARRAY_INT32;
		}
		if ( vtype == napi_uint32_array ) {
			return STDLIB_NDARRAY_UINT32;
		}
		if ( vtype == napi_int16_array ) {
			return STDLIB_NDARRAY_INT16;
		}
		if ( vtype == napi_uint16_array ) {
			return STDLIB_NDARRAY_UINT16;
		}
		if ( vtype == napi_int8_array ) {
			return STDLIB_NDARRAY_INT8;
		}
		if ( vtype == napi_uint8_array ) {
			return STDLIB_NDARRAY_UINT8;
		}
		if ( vtype == napi_uint8_clamped_array ) {
			return STDLIB_NDARRAY_UINT8;
		}
		// FIXME: handle BigInt64Array and BigUint64Array
	}

	/**
	* Validates, extracts, and transforms arguments provided to the main entry point for a Node.js add-on to native C types.
	*
	* ## Notes
	*
	* -   The function assumes the following argument order:
	*
	*     ```text
	*     [ N, ia1, is1, ia2, is2, ..., oa1, os1, oa2, os2, ... ]
	*     ```
	*
	*     where
	*
	*     -   `N` is the number of elements over which to iterate
	*     -   `ia#` is an input strided array
	*     -   `is#` is a corresponding input strided array stride (in units of elements)
	*     -   `oa#` is an output strided array
	*     -   `os#` is a corresponding output strided array stride (in units of elements)
	*
	* -   We **assume** no more than `64` input strided array arguments, which seems a reasonable assumption, as strided array functions which operate over `65` or more input strided arrays are **exceedingly** unlikely (most strided array functions operate on 3 or fewer input strided arrays).
	*
	* @private
	* @param env      environment
	* @param info     arguments
	* @param nargs    total number of expected arguments
	* @param nin      number of input strided array arguments
	* @param nout     number of output strided array arguments
	* @param arrays   destination array containing pointers to both input and output strided byte arrays
	* @param shape    destination array containing the array shape (dimensions)
	* @param strides  destination array containing array strides (in bytes) for each strided array
	* @param types    destination array containing strided array argument data types
	* @throws         must provide expected number of input arguments
	* @throws         stride arguments must be numbers
	* @throws         input strided array arguments must be either typed arrays or scalars
	* @throws         output strided array arguments must be typed arrays
	* @throws         must provide at least one input strided array
	* @return         number of scalar strided "array" arguments
	*/
	int64_t stdlib_napi_addon_strided_array_function_arguments( const napi_env env, const napi_callback_info info, const int64_t nargs, const int64_t nin, const int64_t nout, uint8_t *arrays[], int64_t *shape, int64_t *strides, enum STDLIB_NDARRAY_DTYPE *types ) {
		napi_status status;
		int64_t i;
		int64_t j;

		// Compute the index of the first output strided array argument:
		int64_t iout = ( nin*2 ) + 1;

		// Initialize variables used to track scalar input arguments:
		int64_t nsargs = 0;
		int64_t sargs = 0;

		// Get callback arguments:
		size_t argc = 7;
		napi_value argv[ 7 ];
		status = napi_get_cb_info( env, info, &argc, argv, nullptr, nullptr );
		assert( status == napi_ok );

		if ( (int64_t)argc != nargs ) {
			napi_throw_error( env, nullptr, "invalid invocation. Incorrect number of arguments." );
			return -1;
		}

		// The first argument is always the number of elements over which to iterate...
		napi_valuetype vtype0;
		status = napi_typeof( env, argv[ 0 ], &vtype0 );
		assert( status == napi_ok );
		if ( vtype0 != napi_number ) {
			napi_throw_type_error( env, nullptr, "invalid argument. First argument must be a number." );
			return -1;
		}

		// Retrieve the number of elements:
		int64_t N;
		status = napi_get_value_int64( env, argv[ 0 ], &N );
		assert( status == napi_ok );

		shape[ 0 ] = N;

		// Stride arguments for both input and output strided arrays are every other argument beginning from the third argument...
		for ( i = 2; i < nargs; i += 2 ) {
			napi_valuetype vtype;
			status = napi_typeof( env, argv[ i ], &vtype );
			assert( status == napi_ok );
			if ( vtype != napi_number ) {
				napi_throw_type_error( env, nullptr, "invalid argument. Stride argument must be a number." );
				return -1;
			}

			int64_t stride;
			status = napi_get_value_int64( env, argv[ i ], &stride );
			assert( status == napi_ok );

			j = ( i-2 ) / 2;
			strides[ j ] = stride;
		}

		// Input strided array arguments are every other argument beginning from the second argument...
		for ( i = 1; i < iout; i += 2 ) {
			j = ( i-1 ) / 2;

			bool res;
			status = napi_is_typedarray( env, argv[ i ], &res );
			assert( status == napi_ok );
			if ( res == true ) {
				napi_typedarray_type vtype;
				size_t len;
				void *TypedArray;
				status = napi_get_typedarray_info( env, argv[ i ], &vtype, &len, &TypedArray, nullptr, nullptr );
				assert( status == napi_ok );
				if ( (N-1)*llabs(strides[j]) > (int64_t)len ) {
					napi_throw_range_error( env, nullptr, "invalid argument. Input array argument has insufficient elements based on the associated stride and the number of indexed elements." );
					return -1;
				}

				arrays[ j ] = (uint8_t *)TypedArray;
				types[ j ] = typed_array_data_type( vtype );
				strides[ j ] *= stdlib_ndarray_bytes_per_element( types[ j ] );
			} else {
				double v;
				status = napi_get_value_double( env, argv[ i ], &v );
				if ( status != napi_ok ) {
					napi_throw_type_error( env, nullptr, "invalid argument. Input strided array argument must be a typed array or scalar." );
					return -1;
				}
				sargs |= (1<<j);
				nsargs += 1;
			}
		}

		// Output strided array arguments are every other argument beginning from the argument following the last input strided array stride argument...
		for ( i = iout; i < nargs; i += 2 ) {
			j = ( i-1 ) / 2;

			bool res;
			status = napi_is_typedarray( env, argv[ i ], &res );
			assert( status == napi_ok );
			if ( res == true ) {
				napi_typedarray_type vtype;
				size_t len;
				void *TypedArray;
				status = napi_get_typedarray_info( env, argv[ i ], &vtype, &len, &TypedArray, nullptr, nullptr );
				assert( status == napi_ok );
				if ( (N-1)*llabs(strides[j]) > (int64_t)len ) {
					napi_throw_range_error( env, nullptr, "invalid argument. Output array argument has insufficient elements based on the associated stride and the number of indexed elements." );
					return -1;
				}

				arrays[ j ] = (uint8_t *)TypedArray;
				types[ j ] = typed_array_data_type( vtype );
				strides[ j ] *= stdlib_ndarray_bytes_per_element( types[ j ] );
			} else {
				napi_throw_type_error( env, nullptr, "invalid argument. Output strided array arguments must be typed arrays." );
				return -1;
			}
		}

		// Check if we have been provided only scalar input arguments...
		if ( nin > 0 && nsargs == nin ) {
			napi_throw_type_error( env, nullptr, "invalid arguments. Must provide at least one input strided array argument." );
			return -1;
		}
		return nsargs;
	}

	/**
	* Adds each element in `X` to a corresponding element in `Y` and assigns the result to an element in `Z`.
	*
	* ## Notes
	*
	* -   When called from JavaScript, the function expects the following arguments:
	*
	*     -   `N`: number of indexed elements
	*     -   `X`: input array (or scalar constant)
	*     -   `strideX`: `X` stride length
	*     -   `Y`: input array (or scalar constant)
	*     -   `strideY`: `Y` stride length
	*     -   `Z`: destination array
	*     -   `strideZ`: `Z` stride length
	*/
	napi_value node_add( napi_env env, napi_callback_info info ) {
		enum STDLIB_NDARRAY_DTYPE types[ 3 ];
		uint8_t *arrays[ 3 ];
		int64_t strides[ 3 ];
		int64_t shape[ 1 ];
		int64_t nsargs;
		int64_t nargs;
		int64_t nout;
		int64_t nin;

		// Total number of input arguments:
		nargs = 7;

		// Number of input and output strided array arguments:
		nin = 2;
		nout = 1;

		// Process the provided arguments:
		nsargs = stdlib_napi_addon_strided_array_function_arguments( env, info, nargs, nin, nout, arrays, shape, strides, types );
		if ( nsargs < 0 ) {
			return nullptr;
		}

		// Broadcasting of scalar arguments...
		if ( nsargs > 0 ) {
			// Create an array having the closest "compatible" type...
			// arrays[ 0 ] = broadcast( static_cast<double>( info[ 1 ]->NumberValue() ), types[ 0 ] );
		}

		// Perform addition:
		stdlib_strided_dd_d( arrays, shape, strides, (void *)add );

		return nullptr;
	}

	napi_value Init( napi_env env, napi_value exports ) {
		napi_status status;
		napi_value fcn;
		status = napi_create_function( env, "exports", NAPI_AUTO_LENGTH, node_add, NULL, &fcn );
		assert( status == napi_ok );
		return fcn;
	}

	NAPI_MODULE( NODE_GYP_MODULE_NAME, Init )
} // end namespace addon_strided_add
<commit_msg>Add FIXMEs<commit_after>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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 "stdlib/strided_binary.h"
#include "stdlib/ndarray/base/bytes_per_element.h"
#include "stdlib/ndarray/dtypes.h"
#include <node_api.h>
#include <stdint.h>
#include <stdbool.h>
#include <assert.h>

/**
* Add-on namespace.
*/
namespace addon_strided_add {

	/**
	* Adds two doubles.
	*
	* @private
	* @param x  first double
	* @param y  second double
	* @return   sum
	*/
	double add( double x, double y ) {
		return x + y;
	}

	/**
	* Returns a typed array data type.
	*
	* @private
	* @param vtype  typed array type
	* @return       data type
	*/
	enum STDLIB_NDARRAY_DTYPE typed_array_data_type( napi_typedarray_type vtype ) {
		if ( vtype == napi_float64_array ) {
			return STDLIB_NDARRAY_FLOAT64;
		}
		if ( vtype == napi_float32_array ) {
			return STDLIB_NDARRAY_FLOAT32;
		}
		if ( vtype == napi_int32_array ) {
			return STDLIB_NDARRAY_INT32;
		}
		if ( vtype == napi_uint32_array ) {
			return STDLIB_NDARRAY_UINT32;
		}
		if ( vtype == napi_int16_array ) {
			return STDLIB_NDARRAY_INT16;
		}
		if ( vtype == napi_uint16_array ) {
			return STDLIB_NDARRAY_UINT16;
		}
		if ( vtype == napi_int8_array ) {
			return STDLIB_NDARRAY_INT8;
		}
		if ( vtype == napi_uint8_array ) {
			return STDLIB_NDARRAY_UINT8;
		}
		if ( vtype == napi_uint8_clamped_array ) {
			return STDLIB_NDARRAY_UINT8;
		}
		// FIXME: handle BigInt64Array and BigUint64Array
	}

	/**
	* Validates, extracts, and transforms arguments provided to the main entry point for a Node.js add-on to native C types.
	*
	* ## Notes
	*
	* -   The function assumes the following argument order:
	*
	*     ```text
	*     [ N, ia1, is1, ia2, is2, ..., oa1, os1, oa2, os2, ... ]
	*     ```
	*
	*     where
	*
	*     -   `N` is the number of elements over which to iterate
	*     -   `ia#` is an input strided array
	*     -   `is#` is a corresponding input strided array stride (in units of elements)
	*     -   `oa#` is an output strided array
	*     -   `os#` is a corresponding output strided array stride (in units of elements)
	*
	* -   We **assume** (due to use of bit flags for keeping track of scalar arguments) no more than `64` input strided array arguments, which seems a reasonable assumption, as strided array functions which operate over `65` or more input strided arrays are **exceedingly** unlikely (most strided array functions operate on 3 or fewer input strided arrays).
	*
	* @private
	* @param env      environment
	* @param info     arguments
	* @param nargs    total number of expected arguments
	* @param nin      number of input strided array arguments
	* @param nout     number of output strided array arguments
	* @param arrays   destination array containing pointers to both input and output strided byte arrays
	* @param shape    destination array containing the array shape (dimensions)
	* @param strides  destination array containing array strides (in bytes) for each strided array
	* @param types    destination array containing strided array argument data types
	* @throws         must provide expected number of input arguments
	* @throws         stride arguments must be numbers
	* @throws         input strided array arguments must be either typed arrays or scalars
	* @throws         output strided array arguments must be typed arrays
	* @throws         must provide at least one input strided array
	* @return         number of scalar strided "array" arguments
	*/
	int64_t stdlib_napi_addon_strided_array_function_arguments( const napi_env env, const napi_callback_info info, const int64_t nargs, const int64_t nin, const int64_t nout, uint8_t *arrays[], int64_t *shape, int64_t *strides, enum STDLIB_NDARRAY_DTYPE *types ) {
		napi_status status;
		int64_t i;
		int64_t j;

		// Compute the index of the first output strided array argument:
		int64_t iout = ( nin*2 ) + 1;

		// Initialize variables used to track scalar input arguments:
		int64_t nsargs = 0;
		int64_t sargs = 0;

		// Get callback arguments:
		size_t argc = 7;
		napi_value argv[ 7 ];
		status = napi_get_cb_info( env, info, &argc, argv, nullptr, nullptr );
		assert( status == napi_ok );

		if ( (int64_t)argc != nargs ) {
			napi_throw_error( env, nullptr, "invalid invocation. Incorrect number of arguments." );
			return -1;
		}

		// The first argument is always the number of elements over which to iterate...
		napi_valuetype vtype0;
		status = napi_typeof( env, argv[ 0 ], &vtype0 );
		assert( status == napi_ok );
		if ( vtype0 != napi_number ) {
			napi_throw_type_error( env, nullptr, "invalid argument. First argument must be a number." );
			return -1;
		}

		// Retrieve the number of elements:
		int64_t N;
		status = napi_get_value_int64( env, argv[ 0 ], &N );
		assert( status == napi_ok );

		shape[ 0 ] = N;

		// Stride arguments for both input and output strided arrays are every other argument beginning from the third argument...
		for ( i = 2; i < nargs; i += 2 ) {
			napi_valuetype vtype;
			status = napi_typeof( env, argv[ i ], &vtype );
			assert( status == napi_ok );
			if ( vtype != napi_number ) {
				napi_throw_type_error( env, nullptr, "invalid argument. Stride argument must be a number." );
				return -1;
			}

			int64_t stride;
			status = napi_get_value_int64( env, argv[ i ], &stride );
			assert( status == napi_ok );

			j = ( i-2 ) / 2;
			strides[ j ] = stride;
		}

		// Input strided array arguments are every other argument beginning from the second argument...
		for ( i = 1; i < iout; i += 2 ) {
			j = ( i-1 ) / 2;

			bool res;
			status = napi_is_typedarray( env, argv[ i ], &res );
			assert( status == napi_ok );
			if ( res == true ) {
				napi_typedarray_type vtype;
				size_t len;
				void *TypedArray;
				status = napi_get_typedarray_info( env, argv[ i ], &vtype, &len, &TypedArray, nullptr, nullptr );
				assert( status == napi_ok );
				if ( (N-1)*llabs(strides[j]) > (int64_t)len ) {
					napi_throw_range_error( env, nullptr, "invalid argument. Input array argument has insufficient elements based on the associated stride and the number of indexed elements." );
					return -1;
				}

				arrays[ j ] = (uint8_t *)TypedArray;
				types[ j ] = typed_array_data_type( vtype );
				strides[ j ] *= stdlib_ndarray_bytes_per_element( types[ j ] );
			} else {
				double v;
				status = napi_get_value_double( env, argv[ i ], &v );
				if ( status != napi_ok ) {
					napi_throw_type_error( env, nullptr, "invalid argument. Input strided array argument must be a typed array or scalar." );
					return -1;
				}
				sargs |= (1<<j);
				nsargs += 1;
			}
		}

		// Output strided array arguments are every other argument beginning from the argument following the last input strided array stride argument...
		for ( i = iout; i < nargs; i += 2 ) {
			j = ( i-1 ) / 2;

			bool res;
			status = napi_is_typedarray( env, argv[ i ], &res );
			assert( status == napi_ok );
			if ( res == true ) {
				napi_typedarray_type vtype;
				size_t len;
				void *TypedArray;
				status = napi_get_typedarray_info( env, argv[ i ], &vtype, &len, &TypedArray, nullptr, nullptr );
				assert( status == napi_ok );
				if ( (N-1)*llabs(strides[j]) > (int64_t)len ) {
					napi_throw_range_error( env, nullptr, "invalid argument. Output array argument has insufficient elements based on the associated stride and the number of indexed elements." );
					return -1;
				}

				arrays[ j ] = (uint8_t *)TypedArray;
				types[ j ] = typed_array_data_type( vtype );
				strides[ j ] *= stdlib_ndarray_bytes_per_element( types[ j ] );
			} else {
				napi_throw_type_error( env, nullptr, "invalid argument. Output strided array arguments must be typed arrays." );
				return -1;
			}
		}

		// Check if we have been provided only scalar input arguments...
		if ( nin > 0 && nsargs == nin ) {
			napi_throw_type_error( env, nullptr, "invalid arguments. Must provide at least one input strided array argument." );
			return -1;
		}
		return nsargs;
	}

	/**
	* Adds each element in `X` to a corresponding element in `Y` and assigns the result to an element in `Z`.
	*
	* ## Notes
	*
	* -   When called from JavaScript, the function expects the following arguments:
	*
	*     -   `N`: number of indexed elements
	*     -   `X`: input array (or scalar constant)
	*     -   `strideX`: `X` stride length
	*     -   `Y`: input array (or scalar constant)
	*     -   `strideY`: `Y` stride length
	*     -   `Z`: destination array
	*     -   `strideZ`: `Z` stride length
	*/
	napi_value node_add( napi_env env, napi_callback_info info ) {
		enum STDLIB_NDARRAY_DTYPE types[ 3 ];
		uint8_t *arrays[ 3 ];
		int64_t strides[ 3 ];
		int64_t shape[ 1 ];
		int64_t nsargs;
		int64_t nargs;
		int64_t nout;
		int64_t nin;

		// Total number of input arguments:
		nargs = 7;

		// Number of input and output strided array arguments:
		nin = 2;
		nout = 1;

		// Process the provided arguments:
		nsargs = stdlib_napi_addon_strided_array_function_arguments( env, info, nargs, nin, nout, arrays, shape, strides, types );
		if ( nsargs < 0 ) {
			return nullptr;
		}

		// Broadcasting of scalar arguments...
		if ( nsargs > 0 ) {
			// FIXME
			// Create an array having the closest "compatible" type...
			// arrays[ 0 ] = broadcast( static_cast<double>( info[ 1 ]->NumberValue() ), types[ 0 ] );
		}

		// Perform addition (NOTE: this currently assumes Float64Array input and output strided array arguments!!!):
		stdlib_strided_dd_d( arrays, shape, strides, (void *)add );

		return nullptr;
	}

	napi_value Init( napi_env env, napi_value exports ) {
		napi_status status;
		napi_value fcn;
		status = napi_create_function( env, "exports", NAPI_AUTO_LENGTH, node_add, NULL, &fcn );
		assert( status == napi_ok );
		return fcn;
	}

	NAPI_MODULE( NODE_GYP_MODULE_NAME, Init )
} // end namespace addon_strided_add
<|endoftext|>


<commit_before>// For conditions of distribution and use, see copyright notice in license.txt

#include <boost/test/unit_test.hpp>

#include <OISKeyboard.h>

#include "CoreStdIncludes.h"
#include "Core.h"
#include "Foundation.h"
#include "ServiceInterfaces.h"
#include "StaticModuleDefinitions.h"

#include "ConsoleModuleApi.h"
#include "ConsoleModule.h"
#include "ConsoleManager.h"
#include "OgreOverlay.h"

#include "InputEvents.h"

//! Unit test for framework
BOOST_AUTO_TEST_SUITE(test_suite_support_modules)

Foundation::Framework &CreateFramework()
{
    static Foundation::Framework fw;
    return fw;
}

struct TestA
{
    Console::CommandResult TestCallbackSuccess(const Core::StringVector &params)
    {
        BOOST_CHECK_EQUAL(params[0], "paramA");
        BOOST_CHECK_EQUAL(params[1], "paramB");

        return Console::ResultSuccess("Success");
    }
    Console::CommandResult TestCallbackFailure(const Core::StringVector &params)
    {
        BOOST_CHECK_EQUAL(params.size(), 0);

        return Console::ResultFailure();
    }
};

struct TestB
{
    Console::CommandResult TestCallbackThreaded(const Core::StringVector &params)
    {
        test_var_ = 1;
        return Console::ResultSuccess();
    }

    void operator()()
    {
        test_var_ = 0;
        Console::CommandService *console = fw_->GetService<Console::CommandService>
            (Foundation::Service::ST_ConsoleCommand);

        console->RegisterCommand(Console::CreateCommand("Test CommandC", "Test command threaded", Console::Bind(this, &TestB::TestCallbackThreaded), true));

        console->Update();
        boost::optional<Console::CommandResult> result;
        while ( !(result = console->Poll("Test CommandC")) )
            console->Update();

        BOOST_CHECK_EQUAL (result->success_, true);
    }
    Foundation::Framework *fw_;
    int test_var_;
};

BOOST_AUTO_TEST_CASE( support_modules_console_commands )
{
    Foundation::Framework &fw = CreateFramework();

    fw.GetModuleManager()->ExcludeModule("StaticModuleTest");

    //! \todo Gtk seems to cause problems with unit tests, so excluded for now
    //! \bug Re-creating Gtk::Main when running unit tests in debug mode causes a crash.
    //!      It should have been destroyed properly though, and unloading/loading GtkmmUI
    //!      module at runtime works just fine.
    fw.GetModuleManager()->ExcludeModule("GtkmmUI");

    Test::StaticModuleDefinitions static_test;
    static_test(&fw);
    fw.GetModuleManager()->PreInitializeModule(fw.GetModuleManager()->GetModule(Foundation::Module::MT_Scene).lock().get());
    fw.GetModuleManager()->InitializeModule(fw.GetModuleManager()->GetModule(Foundation::Module::MT_Scene).lock().get());
    fw.GetModuleManager()->PostInitializeModule(fw.GetModuleManager()->GetModule(Foundation::Module::MT_Scene).lock().get());

    fw.GetModuleManager()->LoadModuleByName("SupportModules", "ConsoleModule");
    BOOST_CHECK (fw.GetModuleManager()->HasModule(Foundation::Module::MT_Console));

    Console::CommandService *console = fw.GetService<Console::CommandService>
        (Foundation::Service::ST_ConsoleCommand);

    TestA test_class;
    console->RegisterCommand(Console::CreateCommand("Test_CommandA", "Test command Success", Console::Bind(&test_class, &TestA::TestCallbackSuccess)));
    console->RegisterCommand(Console::CreateCommand("Test_CommandB", "Test command Failure", Console::Bind(&test_class, &TestA::TestCallbackFailure)));

    Console::CommandResult result = console->ExecuteCommand("Test_CommandA (paramA, paramB )");
    BOOST_CHECK_EQUAL (result.success_, true);
    BOOST_CHECK_EQUAL (result.why_, "Success");

    result = console->ExecuteCommand("Test_CommandB");
    BOOST_CHECK_EQUAL (result.success_, false);
    BOOST_CHECK_EQUAL (result.why_.size(), 0);

    TestB testb;
    testb.fw_ = &fw;

    Core::Thread thread(boost::ref(testb));
    console->QueueCommand("Test CommandC");
    thread.join();

    BOOST_CHECK_EQUAL (testb.test_var_, 1);
}

BOOST_AUTO_TEST_CASE( support_modules_console_ogre )
{
    Foundation::Framework &fw = CreateFramework();

    Console::ConsoleManager *console_manager = checked_static_cast<Console::ConsoleManager*>(fw.GetService<Console::ConsoleServiceInterface>
        (Foundation::Service::ST_Console));

    Console::ConsolePtr ogre_console = console_manager->GetOgre();
    Console::OgreOverlay *overlay = checked_static_cast<Console::OgreOverlay*>(ogre_console.get());

    overlay->SetVisible(true);
    BOOST_CHECK_EQUAL(overlay->IsVisible(), true);
    overlay->Update(60); // fast-forward one minute
    BOOST_CHECK_EQUAL(overlay->IsVisible(), true);
    BOOST_CHECK_EQUAL(overlay->IsActive(), true);

    overlay->Scroll(30000);
    overlay->Scroll(-30000);
    overlay->Scroll(300000);
    overlay->Scroll(-2);
    overlay->Scroll(1);
    overlay->Clear();
    overlay->Scroll(5);
    overlay->Scroll(-5);
    overlay->Print("Test message A");
    overlay->Print("Test message B");
    overlay->Print("Test message C");
    BOOST_CHECK_EQUAL(overlay->GetLine(0), std::string("Test message C"));
    BOOST_CHECK_EQUAL(overlay->GetLine(1), std::string("Test message B"));
    BOOST_CHECK_EQUAL(overlay->GetLine(2), std::string("Test message A"));

    BOOST_CHECK_EQUAL(overlay->GetCommandLine(), std::string(""));

    overlay->HandleKeyDown(OIS::KC_A, 65);
    BOOST_CHECK_EQUAL(overlay->GetCommandLine(), std::string("A"));
    overlay->HandleKeyDown(OIS::KC_B, 66);
    BOOST_CHECK_EQUAL(overlay->GetCommandLine(), std::string("AB"));
    overlay->HandleKeyDown(OIS::KC_BACK, 0);
    BOOST_CHECK_EQUAL(overlay->GetCommandLine(), std::string("A"));
    overlay->HandleKeyDown(OIS::KC_C, 67);
    overlay->HandleKeyDown(OIS::KC_RIGHT, 0);
    overlay->HandleKeyDown(OIS::KC_LEFT, 0);
    overlay->HandleKeyDown(OIS::KC_BACK, 0);
    overlay->HandleKeyDown(OIS::KC_DELETE, 0);
    BOOST_CHECK_EQUAL(overlay->GetCommandLine(), std::string(""));

    overlay->HandleKeyDown(OIS::KC_A, 65);
    overlay->HandleKeyDown(OIS::KC_RETURN, 0);
    overlay->HandleKeyDown(OIS::KC_B, 66);
    overlay->HandleKeyDown(OIS::KC_RETURN, 0);
    overlay->HandleKeyDown(OIS::KC_C, 67);
    overlay->HandleKeyDown(OIS::KC_RETURN, 0);
    BOOST_CHECK_EQUAL(overlay->GetCommandLine(), std::string(""));

    overlay->HandleKeyDown(OIS::KC_DOWN, 0);
    overlay->HandleKeyDown(OIS::KC_UP, 0);
    BOOST_CHECK_EQUAL(overlay->GetCommandLine(), std::string("C"));
    overlay->HandleKeyDown(OIS::KC_UP, 0);
    overlay->HandleKeyDown(OIS::KC_UP, 0);
    overlay->HandleKeyDown(OIS::KC_UP, 0);
    BOOST_CHECK_EQUAL(overlay->GetCommandLine(), std::string("A"));
    overlay->HandleKeyDown(OIS::KC_DOWN, 0);
    BOOST_CHECK_EQUAL(overlay->GetCommandLine(), std::string("B"));

    overlay->SetVisible(false);
    BOOST_CHECK_EQUAL(overlay->IsActive(), false);

    ogre_console.reset();
    fw.GetModuleManager()->UninitializeModules();
    fw.GetModuleManager()->UnloadModules();
}

BOOST_AUTO_TEST_SUITE_END()

<commit_msg>Fixed comment.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt

#include <boost/test/unit_test.hpp>

#include <OISKeyboard.h>

#include "CoreStdIncludes.h"
#include "Core.h"
#include "Foundation.h"
#include "ServiceInterfaces.h"
#include "StaticModuleDefinitions.h"

#include "ConsoleModuleApi.h"
#include "ConsoleModule.h"
#include "ConsoleManager.h"
#include "OgreOverlay.h"

#include "InputEvents.h"

//! Unit test for framework
BOOST_AUTO_TEST_SUITE(test_suite_support_modules)

Foundation::Framework &CreateFramework()
{
    static Foundation::Framework fw;
    return fw;
}

struct TestA
{
    Console::CommandResult TestCallbackSuccess(const Core::StringVector &params)
    {
        BOOST_CHECK_EQUAL(params[0], "paramA");
        BOOST_CHECK_EQUAL(params[1], "paramB");

        return Console::ResultSuccess("Success");
    }
    Console::CommandResult TestCallbackFailure(const Core::StringVector &params)
    {
        BOOST_CHECK_EQUAL(params.size(), 0);

        return Console::ResultFailure();
    }
};

struct TestB
{
    Console::CommandResult TestCallbackThreaded(const Core::StringVector &params)
    {
        test_var_ = 1;
        return Console::ResultSuccess();
    }

    void operator()()
    {
        test_var_ = 0;
        Console::CommandService *console = fw_->GetService<Console::CommandService>
            (Foundation::Service::ST_ConsoleCommand);

        console->RegisterCommand(Console::CreateCommand("Test CommandC", "Test command threaded", Console::Bind(this, &TestB::TestCallbackThreaded), true));

        console->Update();
        boost::optional<Console::CommandResult> result;
        while ( !(result = console->Poll("Test CommandC")) )
            console->Update();

        BOOST_CHECK_EQUAL (result->success_, true);
    }
    Foundation::Framework *fw_;
    int test_var_;
};

BOOST_AUTO_TEST_CASE( support_modules_console_commands )
{
    Foundation::Framework &fw = CreateFramework();

    fw.GetModuleManager()->ExcludeModule("StaticModuleTest");

    //! \todo Gtk seems to cause problems with unit tests, so excluded for now
    //! \bug Re-creating Gtk::Main when running unit tests in debug mode causes a crash.
    //!      It should have been destroyed properly though, and unloading/loading GtkmmUI
    //!      module at runtime works just fine. The problem seems to be confined to
    //!      unit tests in debug mode (run outside of the debugger).
    fw.GetModuleManager()->ExcludeModule("GtkmmUI");

    Test::StaticModuleDefinitions static_test;
    static_test(&fw);
    fw.GetModuleManager()->PreInitializeModule(fw.GetModuleManager()->GetModule(Foundation::Module::MT_Scene).lock().get());
    fw.GetModuleManager()->InitializeModule(fw.GetModuleManager()->GetModule(Foundation::Module::MT_Scene).lock().get());
    fw.GetModuleManager()->PostInitializeModule(fw.GetModuleManager()->GetModule(Foundation::Module::MT_Scene).lock().get());

    fw.GetModuleManager()->LoadModuleByName("SupportModules", "ConsoleModule");
    BOOST_CHECK (fw.GetModuleManager()->HasModule(Foundation::Module::MT_Console));

    Console::CommandService *console = fw.GetService<Console::CommandService>
        (Foundation::Service::ST_ConsoleCommand);

    TestA test_class;
    console->RegisterCommand(Console::CreateCommand("Test_CommandA", "Test command Success", Console::Bind(&test_class, &TestA::TestCallbackSuccess)));
    console->RegisterCommand(Console::CreateCommand("Test_CommandB", "Test command Failure", Console::Bind(&test_class, &TestA::TestCallbackFailure)));

    Console::CommandResult result = console->ExecuteCommand("Test_CommandA (paramA, paramB )");
    BOOST_CHECK_EQUAL (result.success_, true);
    BOOST_CHECK_EQUAL (result.why_, "Success");

    result = console->ExecuteCommand("Test_CommandB");
    BOOST_CHECK_EQUAL (result.success_, false);
    BOOST_CHECK_EQUAL (result.why_.size(), 0);

    TestB testb;
    testb.fw_ = &fw;

    Core::Thread thread(boost::ref(testb));
    console->QueueCommand("Test CommandC");
    thread.join();

    BOOST_CHECK_EQUAL (testb.test_var_, 1);
}

BOOST_AUTO_TEST_CASE( support_modules_console_ogre )
{
    Foundation::Framework &fw = CreateFramework();

    Console::ConsoleManager *console_manager = checked_static_cast<Console::ConsoleManager*>(fw.GetService<Console::ConsoleServiceInterface>
        (Foundation::Service::ST_Console));

    Console::ConsolePtr ogre_console = console_manager->GetOgre();
    Console::OgreOverlay *overlay = checked_static_cast<Console::OgreOverlay*>(ogre_console.get());

    overlay->SetVisible(true);
    BOOST_CHECK_EQUAL(overlay->IsVisible(), true);
    overlay->Update(60); // fast-forward one minute
    BOOST_CHECK_EQUAL(overlay->IsVisible(), true);
    BOOST_CHECK_EQUAL(overlay->IsActive(), true);

    overlay->Scroll(30000);
    overlay->Scroll(-30000);
    overlay->Scroll(300000);
    overlay->Scroll(-2);
    overlay->Scroll(1);
    overlay->Clear();
    overlay->Scroll(5);
    overlay->Scroll(-5);
    overlay->Print("Test message A");
    overlay->Print("Test message B");
    overlay->Print("Test message C");
    BOOST_CHECK_EQUAL(overlay->GetLine(0), std::string("Test message C"));
    BOOST_CHECK_EQUAL(overlay->GetLine(1), std::string("Test message B"));
    BOOST_CHECK_EQUAL(overlay->GetLine(2), std::string("Test message A"));

    BOOST_CHECK_EQUAL(overlay->GetCommandLine(), std::string(""));

    overlay->HandleKeyDown(OIS::KC_A, 65);
    BOOST_CHECK_EQUAL(overlay->GetCommandLine(), std::string("A"));
    overlay->HandleKeyDown(OIS::KC_B, 66);
    BOOST_CHECK_EQUAL(overlay->GetCommandLine(), std::string("AB"));
    overlay->HandleKeyDown(OIS::KC_BACK, 0);
    BOOST_CHECK_EQUAL(overlay->GetCommandLine(), std::string("A"));
    overlay->HandleKeyDown(OIS::KC_C, 67);
    overlay->HandleKeyDown(OIS::KC_RIGHT, 0);
    overlay->HandleKeyDown(OIS::KC_LEFT, 0);
    overlay->HandleKeyDown(OIS::KC_BACK, 0);
    overlay->HandleKeyDown(OIS::KC_DELETE, 0);
    BOOST_CHECK_EQUAL(overlay->GetCommandLine(), std::string(""));

    overlay->HandleKeyDown(OIS::KC_A, 65);
    overlay->HandleKeyDown(OIS::KC_RETURN, 0);
    overlay->HandleKeyDown(OIS::KC_B, 66);
    overlay->HandleKeyDown(OIS::KC_RETURN, 0);
    overlay->HandleKeyDown(OIS::KC_C, 67);
    overlay->HandleKeyDown(OIS::KC_RETURN, 0);
    BOOST_CHECK_EQUAL(overlay->GetCommandLine(), std::string(""));

    overlay->HandleKeyDown(OIS::KC_DOWN, 0);
    overlay->HandleKeyDown(OIS::KC_UP, 0);
    BOOST_CHECK_EQUAL(overlay->GetCommandLine(), std::string("C"));
    overlay->HandleKeyDown(OIS::KC_UP, 0);
    overlay->HandleKeyDown(OIS::KC_UP, 0);
    overlay->HandleKeyDown(OIS::KC_UP, 0);
    BOOST_CHECK_EQUAL(overlay->GetCommandLine(), std::string("A"));
    overlay->HandleKeyDown(OIS::KC_DOWN, 0);
    BOOST_CHECK_EQUAL(overlay->GetCommandLine(), std::string("B"));

    overlay->SetVisible(false);
    BOOST_CHECK_EQUAL(overlay->IsActive(), false);

    ogre_console.reset();
    fw.GetModuleManager()->UninitializeModules();
    fw.GetModuleManager()->UnloadModules();
}

BOOST_AUTO_TEST_SUITE_END()

<|endoftext|>


<commit_before>/*
 * Copyright 2012 TennenColl
 *
 * 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 "application_database.h"
#include "application_gamemode_manager_dialog.h"
#include "application_gamemode_manager_team.h"
#include "application_gamemode_dialogdefinitions.h"
#include "application_data_waypoint.h"
#include "application_gamemode_colordefinitions.h"
#include "application_gamemode_role_classes.h"

#define DIALOG(x) void Dlg##x(Profile& player, bool response, int listitem, const char* inputtext)

DIALOG(SelectTeam) {
	if(player.GetTeamFixed() != TeamManager::GetInstance()[inputtext].GetIngameID()) {
		if(player.GetTeamFixed() != NO_TEAM)
			TeamManager::GetInstance()[TeamManager::GetInstance().GetNameByID(player.GetTeamFixed())].Quit(player);
		TeamManager::GetInstance()[inputtext].Join(player);
	}
	ShowPlayerDialog(player.GetId(), DIALOG_ROLE_SELECT, DIALOG_STYLE_LIST, "ѡְҵ",
		"Assault\nMedic\nMechanic\nEngineer", "ȷ", "");
}

DIALOG(SelectRole) {
	switch(listitem) {
	case 0:
		player.SetRole(Profile::RolePtr(new Assault(player)));
		break;

	case 1:
		player.SetRole(Profile::RolePtr(new Medic(player)));
		break;

	case 2:
		player.SetRole(Profile::RolePtr(new Mechanic(player)));
		break;

	case 3:
		player.SetRole(Profile::RolePtr(new Engineer(player)));
		break;
	}
	player.Spawn();
}

DIALOG(Register) {
	if(inputtext[0] == 0) throw std::runtime_error("벻Ϊ");
	try {
		player.Create(player.GetName(), inputtext);
		player.SendChatMessage(COLOR_SUCC, "עɹ");
		player.SetSignedIn(true);
	} catch(std::runtime_error) {
		throw;
	} catch(...) {
		throw std::runtime_error("עʧ");
	}
}

DIALOG(Login) {
	if(!player.AuthPassword(inputtext)) throw std::runtime_error("");
	player.SetSignedIn(true);
	player.ApplyDataToPlayer();
	player.SendChatMessage(COLOR_SUCC, "¼ɹ");
}

#define REGDLG(x, y) DlgMgr.Add(x, y)

bool RegisterPlayerDlgs() {
	DialogManager& DlgMgr = DialogManager::GetInstance();
	REGDLG(DIALOG_TEAM_SELECT,			DlgSelectTeam);
	REGDLG(DIALOG_ROLE_SELECT,			DlgSelectRole);
	REGDLG(DIALOG_PROFILE_REGISTER,		DlgRegister);
	REGDLG(DIALOG_PROFILE_LOGIN,		DlgLogin);
	return true;
}

#undef REGDLG

void* PlayerDlgInit((void*)RegisterPlayerDlgs());
<commit_msg>修正注册登录若失败不会重新ShowDialog的问题<commit_after>/*
 * Copyright 2012 TennenColl
 *
 * 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 "application_database.h"
#include "application_gamemode_manager_dialog.h"
#include "application_gamemode_manager_team.h"
#include "application_gamemode_dialogdefinitions.h"
#include "application_data_waypoint.h"
#include "application_gamemode_colordefinitions.h"
#include "application_gamemode_role_classes.h"

#define DIALOG(x) void Dlg##x(Profile& player, bool response, int listitem, const char* inputtext)

DIALOG(SelectTeam) {
	if(player.GetTeamFixed() != TeamManager::GetInstance()[inputtext].GetIngameID()) {
		if(player.GetTeamFixed() != NO_TEAM)
			TeamManager::GetInstance()[TeamManager::GetInstance().GetNameByID(player.GetTeamFixed())].Quit(player);
		TeamManager::GetInstance()[inputtext].Join(player);
	}
	ShowPlayerDialog(player.GetId(), DIALOG_ROLE_SELECT, DIALOG_STYLE_LIST, "ѡְҵ",
		"Assault\nMedic\nMechanic\nEngineer", "ȷ", "");
}

DIALOG(SelectRole) {
	switch(listitem) {
	case 0:
		player.SetRole(Profile::RolePtr(new Assault(player)));
		break;

	case 1:
		player.SetRole(Profile::RolePtr(new Medic(player)));
		break;

	case 2:
		player.SetRole(Profile::RolePtr(new Mechanic(player)));
		break;

	case 3:
		player.SetRole(Profile::RolePtr(new Engineer(player)));
		break;
	}
	player.Spawn();
}

DIALOG(Register) {
	if(inputtext[0] == 0) {
		player.SendChatMessage(COLOR_ERROR, "벻Ϊ");
	} else {
		try {
			player.Create(player.GetName(), inputtext);
			player.SendChatMessage(COLOR_SUCC, "עɹ");
			player.SetSignedIn(true);
			return;
		} catch(std::runtime_error& e) {
			player.SendChatMessage(COLOR_ERROR, e.what());
		} catch(...) {
			player.SendChatMessage(COLOR_ERROR, "δ֪ԭעʧ, ϵԱ");
		}
	}
	ShowPlayerDialog(player.GetId(), DIALOG_PROFILE_REGISTER, DIALOG_STYLE_INPUT, "ע", ":", "ע", "");
}

DIALOG(Login) {
	if(!player.AuthPassword(inputtext)) {
		ShowPlayerDialog(player.GetId(), DIALOG_PROFILE_LOGIN, DIALOG_STYLE_INPUT, "¼", "Ե¼:", "¼", "");
		throw std::runtime_error("");
	}
	player.SetSignedIn(true);
	player.ApplyDataToPlayer();
	player.SendChatMessage(COLOR_SUCC, "¼ɹ");
}

#define REGDLG(x, y) DlgMgr.Add(x, y)

bool RegisterPlayerDlgs() {
	DialogManager& DlgMgr = DialogManager::GetInstance();
	REGDLG(DIALOG_TEAM_SELECT,			DlgSelectTeam);
	REGDLG(DIALOG_ROLE_SELECT,			DlgSelectRole);
	REGDLG(DIALOG_PROFILE_REGISTER,		DlgRegister);
	REGDLG(DIALOG_PROFILE_LOGIN,		DlgLogin);
	return true;
}

#undef REGDLG

void* PlayerDlgInit((void*)RegisterPlayerDlgs());
<|endoftext|>


<commit_before>/*!
 * \file dcxdivider.cpp
 * \brief blah
 *
 * blah
 *
 * \author David Legault ( clickhere at scriptsdb dot org )
 * \version 1.0
 *
 * \b Revisions
 *
 *  ScriptsDB.org - 2006
 */

#include "dcxdivider.h"
#include "dcxdialog.h"

/*!
 * \brief Constructor
 *
 * \param ID Control ID
 * \param p_Dialog Parent DcxDialog Object
 * \param mParentHwnd Parent Window Handle
 * \param rc Window Rectangle
 * \param styles Window Style Tokenized List
 */

DcxDivider::DcxDivider( UINT ID, DcxDialog * p_Dialog, HWND mParentHwnd, RECT * rc, TString & styles )
: DcxControl( ID, p_Dialog )
{
	LONG Styles = 0, ExStyles = 0;
	BOOL bNoTheme = FALSE;
	this->parseControlStyles( styles, &Styles, &ExStyles, &bNoTheme );

	this->m_Hwnd = CreateWindowEx(
		ExStyles | WS_EX_CONTROLPARENT,
		DCX_DIVIDERCLASS,
		NULL,
		WS_CHILD | Styles,
		rc->left, rc->top, rc->right - rc->left, rc->bottom - rc->top,
		mParentHwnd,
		(HMENU) ID,
		GetModuleHandle(NULL),
		NULL);

	if (!IsWindow(this->m_Hwnd))
		throw "Unable To Create Window";

	if ( bNoTheme )
		dcxSetWindowTheme( this->m_Hwnd , L" ", L" " );

	this->registreDefaultWindowProc( );
	SetProp( this->m_Hwnd, "dcx_cthis", (HANDLE) this );
}

/*!
 * \brief blah
 *
 * blah
 */

DcxDivider::~DcxDivider( ) {

  this->unregistreDefaultWindowProc( );
}

/*!
 * \brief blah
 *
 * blah
 */

TString DcxDivider::getStyles(void) {
	TString styles;
	LONG Styles;
	Styles = GetWindowLong(this->m_Hwnd, GWL_STYLE);
	styles = __super::getStyles();
	if (Styles & DVS_VERT)
		styles.addtok("vertical", " ");
	return styles;
}

void DcxDivider::parseControlStyles( TString & styles, LONG * Styles, LONG * ExStyles, BOOL * bNoTheme ) {

	unsigned int i = 1, numtok = styles.numtok( );
	*Styles |= DVS_HORZ;

	while ( i <= numtok ) {

		if ( styles.gettok( i ) == "vertical" )
			*Styles |= DVS_VERT;

		i++;
	}
	this->parseGeneralControlStyles( styles, Styles, ExStyles, bNoTheme );
}

/*!
 * \brief $xdid Parsing Function
 *
 * \param input [NAME] [ID] [PROP] (OPTIONS)
 * \param szReturnValue mIRC Data Container
 *
 * \return > void
 */

void DcxDivider::parseInfoRequest( TString & input, char * szReturnValue ) {

  //int numtok = input.numtok( );
  TString prop = input.gettok(3);

  // [NAME] [ID] [PROP]
  if (prop == "position") {
    int iDivPos = 0;

    SendMessage(this->m_Hwnd, DV_GETDIVPOS, (WPARAM) NULL, (LPARAM) &iDivPos);
    wsprintf(szReturnValue, "%d", iDivPos);
    return;
  }
  else if (prop == "isvertical") {
    wsprintf(szReturnValue, "%d", (GetWindowLong(this->m_Hwnd, GWL_STYLE) & DVS_VERT));
    return;
  }

  if ( this->parseGlobalInfoRequest( input, szReturnValue ) )
    return;

  szReturnValue[0] = 0;
}

/*!
 * \brief blah
 *
 * blah
 */

void DcxDivider::parseCommandRequest( TString & input ) {
  XSwitchFlags flags(input.gettok(3));

  int numtok = input.numtok( );

  // xdid -l|r [NAME] [ID] [SWITCH] [MIN] [IDEAL][TAB][ID] [CONTROL] [X] [Y] [W] [H] (OPTIONS)
  if ( ( flags['l'] || flags['r'] )&& numtok > 9 ) {

    DVPANEINFO dvpi;
    ZeroMemory( &dvpi, sizeof( DVPANEINFO ) );
    dvpi.cbSize = sizeof( DVPANEINFO );

    TString data(input.gettok(1, TSTAB).trim());
    TString control_data;

    if ( input.numtok( TSTAB ) > 1 )
      control_data = input.gettok(2, TSTAB).trim();

    dvpi.fMask = DVPIM_CHILD | DVPIM_MIN | DVPIM_IDEAL;
    dvpi.cxMin = data.gettok( 4 ).to_int( );
    dvpi.cxIdeal = data.gettok( 5 ).to_int( );

    if ( control_data.numtok( ) > 5 ) {

      UINT ID = mIRC_ID_OFFSET + control_data.gettok( 1 ).to_int( );

      if ( ID > mIRC_ID_OFFSET - 1 &&
        !IsWindow( GetDlgItem( this->m_pParentDialog->getHwnd( ), ID ) ) &&
        this->m_pParentDialog->getControlByID( ID ) == NULL )
      {
				try {
					DcxControl * p_Control = DcxControl::controlFactory(this->m_pParentDialog,ID,control_data,2,
										 CTLF_ALLOW_PBAR|CTLF_ALLOW_TRACKBAR|CTLF_ALLOW_COMBOEX|
										 CTLF_ALLOW_COLORCOMBO|CTLF_ALLOW_STATUSBAR|CTLF_ALLOW_TOOLBAR|
										 CTLF_ALLOW_TREEVIEW|CTLF_ALLOW_LISTVIEW|CTLF_ALLOW_REBAR|
										 CTLF_ALLOW_BUTTON|CTLF_ALLOW_RICHEDIT|CTLF_ALLOW_EDIT|
										 CTLF_ALLOW_UPDOWN| CTLF_ALLOW_IPADDRESS|CTLF_ALLOW_WEBCTRL|
										 CTLF_ALLOW_CALANDER|CTLF_ALLOW_DIVIDER|CTLF_ALLOW_PANEL|
										 CTLF_ALLOW_TAB|CTLF_ALLOW_LINE|CTLF_ALLOW_BOX|CTLF_ALLOW_RADIO|
										 CTLF_ALLOW_CHECK|CTLF_ALLOW_TEXT|CTLF_ALLOW_SCROLL|CTLF_ALLOW_LIST|
										 CTLF_ALLOW_LINK|CTLF_ALLOW_IMAGE|CTLF_ALLOW_PAGER|CTLF_ALLOW_DATETIME|
										 CTLF_ALLOW_STACKER|CTLF_ALLOW_DIRECTSHOW
						,this->m_Hwnd);

					if ( p_Control != NULL ) {

						this->m_pParentDialog->addControl( p_Control );

						dvpi.hChild = p_Control->getHwnd( );

						if ( flags['l'] )
							this->setPane( DVF_PANELEFT, &dvpi );
						else if ( flags['r'] )
							this->setPane( DVF_PANERIGHT, &dvpi );

						this->redrawWindow( );
					}
				}
				catch ( char *err ) {
					this->showErrorEx(NULL, "-l|r", "Unable To Create Control %d (%s)", ID - mIRC_ID_OFFSET, err);
				}
      }
      else
				this->showErrorEx(NULL, "-l|r", "Control with ID \"%d\" already exists", ID - mIRC_ID_OFFSET );
    }
  }
  // xdid -v [NAME] [ID] [SWITCH] [POS]
  else if (flags['v'] && numtok > 3) {
    if (!this->setDivPos(input.gettok(4).to_int())) {
      this->showError(NULL, "-v", "Divider position must be between bounds.");
    }
  }
  else
    this->parseGlobalCommandRequest( input, flags );
}

/*!
 * \brief blah
 *
 * blah
 */

LRESULT DcxDivider::setPane( const UINT iPaneId, LPDVPANEINFO lpdvpi ) {
  return SendMessage( this->m_Hwnd, DV_SETPANE, (WPARAM) iPaneId, (LPARAM) lpdvpi );
}

/*!
 * \brief blah
 *
 * blah
 */

LRESULT DcxDivider::setDivPos( const UINT iDivPos ) {
  return SendMessage( this->m_Hwnd, DV_SETDIVPOS, (WPARAM) 0, (LPARAM) iDivPos );
}

void DcxDivider::toXml(TiXmlElement * xml) {
	__super::toXml(xml);
	DVPANEINFO left;
	DVPANEINFO right;
	DcxControl * dcxcleft = NULL;
	DcxControl * dcxcright = NULL;
	Divider_GetChildControl(this->m_Hwnd, DVF_PANELEFT, &left);
	Divider_GetChildControl(this->m_Hwnd, DVF_PANELEFT, &right);
	if (left.hChild != NULL) {
		dcxcleft = this->m_pParentDialog->getControlByHWND(left.hChild);
		if (dcxcleft != NULL)
			xml->LinkEndChild(dcxcleft->toXml());
		else
			xml->LinkEndChild(new TiXmlElement("control"));
	}
	else {
		xml->LinkEndChild(new TiXmlElement("control"));
	}
	if (right.hChild != NULL) {
		dcxcright = this->m_pParentDialog->getControlByHWND(right.hChild);
		if (dcxcright != NULL)
			xml->LinkEndChild(dcxcright->toXml());
		else
			xml->LinkEndChild(new TiXmlElement("control"));
	}
	else {
		xml->LinkEndChild(new TiXmlElement("control"));
	}
}

/*!
 * \brief blah
 *
 * blah
 */
LRESULT DcxDivider::ParentMessage( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL & bParsed ) {
	return 0L;
}

LRESULT DcxDivider::PostMessage( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL & bParsed ) {

	LRESULT lRes = 0L;
  switch( uMsg ) {

    case WM_NOTIFY :
      {
        LPNMHDR hdr = (LPNMHDR) lParam;

        if (!hdr)
          break;

				if (IsWindow(hdr->hwndFrom)) {
					DcxControl *c_this = (DcxControl *) GetProp(hdr->hwndFrom,"dcx_cthis");
					if (c_this != NULL) {
						lRes = c_this->ParentMessage(uMsg, wParam, lParam, bParsed);
					}
				}
      }
      break;

    case WM_HSCROLL:
    case WM_VSCROLL:
    case WM_COMMAND:
      {
				if (IsWindow((HWND) lParam)) {
					DcxControl *c_this = (DcxControl *) GetProp((HWND) lParam,"dcx_cthis");
					if (c_this != NULL) {
						lRes = c_this->ParentMessage(uMsg, wParam, lParam, bParsed);
					}
				}
      }
      break;

    case WM_DELETEITEM:
      {
				DELETEITEMSTRUCT *idata = (DELETEITEMSTRUCT *)lParam;
				if ((idata != NULL) && (IsWindow(idata->hwndItem))) {
					DcxControl *c_this = (DcxControl *) GetProp(idata->hwndItem,"dcx_cthis");
					if (c_this != NULL) {
						lRes = c_this->ParentMessage(uMsg, wParam, lParam, bParsed);
					}
				}
      }
      break;

    case WM_MEASUREITEM:
      {
				HWND cHwnd = GetDlgItem(this->m_Hwnd, wParam);
				if (IsWindow(cHwnd)) {
					DcxControl *c_this = (DcxControl *) GetProp(cHwnd,"dcx_cthis");
					if (c_this != NULL) {
						lRes = c_this->ParentMessage(uMsg, wParam, lParam, bParsed);
					}
				}
      }
      break;

    case WM_DRAWITEM:
      {
				DRAWITEMSTRUCT *idata = (DRAWITEMSTRUCT *)lParam;
				if ((idata != NULL) && (IsWindow(idata->hwndItem))) {
					DcxControl *c_this = (DcxControl *) GetProp(idata->hwndItem,"dcx_cthis");
					if (c_this != NULL) {
						lRes = c_this->ParentMessage(uMsg, wParam, lParam, bParsed);
					}
				}
      }
     break;

  case WM_DESTROY:
    {
      delete this;
      bParsed = TRUE;
    }
    break;

  case DV_CHANGEPOS:
  {
    int phase = (int) wParam;
    LPPOINT pt = (LPPOINT) lParam;
    TString tsPhase = (phase == DVNM_DRAG_START ? "dragbegin" : (phase == DVNM_DRAG_END ? "dragfinish" : "drag"));

    this->execAliasEx("%s,%d,%d,%d", tsPhase.to_chr(), this->getUserID(), pt->x, pt->y);
    break;
  }

  default:
    return this->CommonMessage( uMsg, wParam, lParam, bParsed);
    break;
  }

  return lRes;
}
<commit_msg>[divider] - changed some error msgs to use this->getUserID()<commit_after>/*!
 * \file dcxdivider.cpp
 * \brief blah
 *
 * blah
 *
 * \author David Legault ( clickhere at scriptsdb dot org )
 * \version 1.0
 *
 * \b Revisions
 *
 *  ScriptsDB.org - 2006
 */

#include "dcxdivider.h"
#include "dcxdialog.h"

/*!
 * \brief Constructor
 *
 * \param ID Control ID
 * \param p_Dialog Parent DcxDialog Object
 * \param mParentHwnd Parent Window Handle
 * \param rc Window Rectangle
 * \param styles Window Style Tokenized List
 */

DcxDivider::DcxDivider( UINT ID, DcxDialog * p_Dialog, HWND mParentHwnd, RECT * rc, TString & styles )
: DcxControl( ID, p_Dialog )
{
	LONG Styles = 0, ExStyles = 0;
	BOOL bNoTheme = FALSE;
	this->parseControlStyles( styles, &Styles, &ExStyles, &bNoTheme );

	this->m_Hwnd = CreateWindowEx(
		ExStyles | WS_EX_CONTROLPARENT,
		DCX_DIVIDERCLASS,
		NULL,
		WS_CHILD | Styles,
		rc->left, rc->top, rc->right - rc->left, rc->bottom - rc->top,
		mParentHwnd,
		(HMENU) ID,
		GetModuleHandle(NULL),
		NULL);

	if (!IsWindow(this->m_Hwnd))
		throw "Unable To Create Window";

	if ( bNoTheme )
		dcxSetWindowTheme( this->m_Hwnd , L" ", L" " );

	this->registreDefaultWindowProc( );
	SetProp( this->m_Hwnd, "dcx_cthis", (HANDLE) this );
}

/*!
 * \brief blah
 *
 * blah
 */

DcxDivider::~DcxDivider( ) {

  this->unregistreDefaultWindowProc( );
}

/*!
 * \brief blah
 *
 * blah
 */

TString DcxDivider::getStyles(void) {
	TString styles;
	LONG Styles;
	Styles = GetWindowLong(this->m_Hwnd, GWL_STYLE);
	styles = __super::getStyles();
	if (Styles & DVS_VERT)
		styles.addtok("vertical", " ");
	return styles;
}

void DcxDivider::parseControlStyles( TString & styles, LONG * Styles, LONG * ExStyles, BOOL * bNoTheme ) {

	unsigned int i = 1, numtok = styles.numtok( );
	*Styles |= DVS_HORZ;

	while ( i <= numtok ) {

		if ( styles.gettok( i ) == "vertical" )
			*Styles |= DVS_VERT;

		i++;
	}
	this->parseGeneralControlStyles( styles, Styles, ExStyles, bNoTheme );
}

/*!
 * \brief $xdid Parsing Function
 *
 * \param input [NAME] [ID] [PROP] (OPTIONS)
 * \param szReturnValue mIRC Data Container
 *
 * \return > void
 */

void DcxDivider::parseInfoRequest( TString & input, char * szReturnValue ) {

  //int numtok = input.numtok( );
  TString prop = input.gettok(3);

  // [NAME] [ID] [PROP]
  if (prop == "position") {
    int iDivPos = 0;

    SendMessage(this->m_Hwnd, DV_GETDIVPOS, (WPARAM) NULL, (LPARAM) &iDivPos);
    wsprintf(szReturnValue, "%d", iDivPos);
    return;
  }
  else if (prop == "isvertical") {
    wsprintf(szReturnValue, "%d", (GetWindowLong(this->m_Hwnd, GWL_STYLE) & DVS_VERT));
    return;
  }

  if ( this->parseGlobalInfoRequest( input, szReturnValue ) )
    return;

  szReturnValue[0] = 0;
}

/*!
 * \brief blah
 *
 * blah
 */

void DcxDivider::parseCommandRequest( TString & input ) {
  XSwitchFlags flags(input.gettok(3));

  int numtok = input.numtok( );

  // xdid -l|r [NAME] [ID] [SWITCH] [MIN] [IDEAL][TAB][ID] [CONTROL] [X] [Y] [W] [H] (OPTIONS)
  if ( ( flags['l'] || flags['r'] )&& numtok > 9 ) {

    DVPANEINFO dvpi;
    ZeroMemory( &dvpi, sizeof( DVPANEINFO ) );
    dvpi.cbSize = sizeof( DVPANEINFO );

    TString data(input.gettok(1, TSTAB).trim());
    TString control_data;

    if ( input.numtok( TSTAB ) > 1 )
      control_data = input.gettok(2, TSTAB).trim();

    dvpi.fMask = DVPIM_CHILD | DVPIM_MIN | DVPIM_IDEAL;
    dvpi.cxMin = data.gettok( 4 ).to_int( );
    dvpi.cxIdeal = data.gettok( 5 ).to_int( );

    if ( control_data.numtok( ) > 5 ) {

      UINT ID = mIRC_ID_OFFSET + control_data.gettok( 1 ).to_int( );

      if ( ID > mIRC_ID_OFFSET - 1 &&
        !IsWindow( GetDlgItem( this->m_pParentDialog->getHwnd( ), ID ) ) &&
        this->m_pParentDialog->getControlByID( ID ) == NULL )
      {
				try {
					DcxControl * p_Control = DcxControl::controlFactory(this->m_pParentDialog,ID,control_data,2,
										 CTLF_ALLOW_PBAR|CTLF_ALLOW_TRACKBAR|CTLF_ALLOW_COMBOEX|
										 CTLF_ALLOW_COLORCOMBO|CTLF_ALLOW_STATUSBAR|CTLF_ALLOW_TOOLBAR|
										 CTLF_ALLOW_TREEVIEW|CTLF_ALLOW_LISTVIEW|CTLF_ALLOW_REBAR|
										 CTLF_ALLOW_BUTTON|CTLF_ALLOW_RICHEDIT|CTLF_ALLOW_EDIT|
										 CTLF_ALLOW_UPDOWN| CTLF_ALLOW_IPADDRESS|CTLF_ALLOW_WEBCTRL|
										 CTLF_ALLOW_CALANDER|CTLF_ALLOW_DIVIDER|CTLF_ALLOW_PANEL|
										 CTLF_ALLOW_TAB|CTLF_ALLOW_LINE|CTLF_ALLOW_BOX|CTLF_ALLOW_RADIO|
										 CTLF_ALLOW_CHECK|CTLF_ALLOW_TEXT|CTLF_ALLOW_SCROLL|CTLF_ALLOW_LIST|
										 CTLF_ALLOW_LINK|CTLF_ALLOW_IMAGE|CTLF_ALLOW_PAGER|CTLF_ALLOW_DATETIME|
										 CTLF_ALLOW_STACKER|CTLF_ALLOW_DIRECTSHOW
						,this->m_Hwnd);

					if ( p_Control != NULL ) {

						this->m_pParentDialog->addControl( p_Control );

						dvpi.hChild = p_Control->getHwnd( );

						if ( flags['l'] )
							this->setPane( DVF_PANELEFT, &dvpi );
						else if ( flags['r'] )
							this->setPane( DVF_PANERIGHT, &dvpi );

						this->redrawWindow( );
					}
				}
				catch ( char *err ) {
					this->showErrorEx(NULL, "-l|r", "Unable To Create Control %d (%s)", this->getUserID(), err);
				}
      }
      else
				this->showErrorEx(NULL, "-l|r", "Control with ID \"%d\" already exists", this->getUserID());
    }
  }
  // xdid -v [NAME] [ID] [SWITCH] [POS]
  else if (flags['v'] && numtok > 3) {
    if (!this->setDivPos(input.gettok(4).to_int())) {
      this->showError(NULL, "-v", "Divider position must be between bounds.");
    }
  }
  else
    this->parseGlobalCommandRequest( input, flags );
}

/*!
 * \brief blah
 *
 * blah
 */

LRESULT DcxDivider::setPane( const UINT iPaneId, LPDVPANEINFO lpdvpi ) {
  return SendMessage( this->m_Hwnd, DV_SETPANE, (WPARAM) iPaneId, (LPARAM) lpdvpi );
}

/*!
 * \brief blah
 *
 * blah
 */

LRESULT DcxDivider::setDivPos( const UINT iDivPos ) {
  return SendMessage( this->m_Hwnd, DV_SETDIVPOS, (WPARAM) 0, (LPARAM) iDivPos );
}

void DcxDivider::toXml(TiXmlElement * xml) {
	__super::toXml(xml);
	DVPANEINFO left;
	DVPANEINFO right;
	DcxControl * dcxcleft = NULL;
	DcxControl * dcxcright = NULL;
	Divider_GetChildControl(this->m_Hwnd, DVF_PANELEFT, &left);
	Divider_GetChildControl(this->m_Hwnd, DVF_PANELEFT, &right);
	if (left.hChild != NULL) {
		dcxcleft = this->m_pParentDialog->getControlByHWND(left.hChild);
		if (dcxcleft != NULL)
			xml->LinkEndChild(dcxcleft->toXml());
		else
			xml->LinkEndChild(new TiXmlElement("control"));
	}
	else {
		xml->LinkEndChild(new TiXmlElement("control"));
	}
	if (right.hChild != NULL) {
		dcxcright = this->m_pParentDialog->getControlByHWND(right.hChild);
		if (dcxcright != NULL)
			xml->LinkEndChild(dcxcright->toXml());
		else
			xml->LinkEndChild(new TiXmlElement("control"));
	}
	else {
		xml->LinkEndChild(new TiXmlElement("control"));
	}
}

/*!
 * \brief blah
 *
 * blah
 */
LRESULT DcxDivider::ParentMessage( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL & bParsed ) {
	return 0L;
}

LRESULT DcxDivider::PostMessage( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL & bParsed ) {

	LRESULT lRes = 0L;
  switch( uMsg ) {

    case WM_NOTIFY :
      {
        LPNMHDR hdr = (LPNMHDR) lParam;

        if (!hdr)
          break;

				if (IsWindow(hdr->hwndFrom)) {
					DcxControl *c_this = (DcxControl *) GetProp(hdr->hwndFrom,"dcx_cthis");
					if (c_this != NULL) {
						lRes = c_this->ParentMessage(uMsg, wParam, lParam, bParsed);
					}
				}
      }
      break;

    case WM_HSCROLL:
    case WM_VSCROLL:
    case WM_COMMAND:
      {
				if (IsWindow((HWND) lParam)) {
					DcxControl *c_this = (DcxControl *) GetProp((HWND) lParam,"dcx_cthis");
					if (c_this != NULL) {
						lRes = c_this->ParentMessage(uMsg, wParam, lParam, bParsed);
					}
				}
      }
      break;

    case WM_DELETEITEM:
      {
				DELETEITEMSTRUCT *idata = (DELETEITEMSTRUCT *)lParam;
				if ((idata != NULL) && (IsWindow(idata->hwndItem))) {
					DcxControl *c_this = (DcxControl *) GetProp(idata->hwndItem,"dcx_cthis");
					if (c_this != NULL) {
						lRes = c_this->ParentMessage(uMsg, wParam, lParam, bParsed);
					}
				}
      }
      break;

    case WM_MEASUREITEM:
      {
				HWND cHwnd = GetDlgItem(this->m_Hwnd, wParam);
				if (IsWindow(cHwnd)) {
					DcxControl *c_this = (DcxControl *) GetProp(cHwnd,"dcx_cthis");
					if (c_this != NULL) {
						lRes = c_this->ParentMessage(uMsg, wParam, lParam, bParsed);
					}
				}
      }
      break;

    case WM_DRAWITEM:
      {
				DRAWITEMSTRUCT *idata = (DRAWITEMSTRUCT *)lParam;
				if ((idata != NULL) && (IsWindow(idata->hwndItem))) {
					DcxControl *c_this = (DcxControl *) GetProp(idata->hwndItem,"dcx_cthis");
					if (c_this != NULL) {
						lRes = c_this->ParentMessage(uMsg, wParam, lParam, bParsed);
					}
				}
      }
     break;

  case WM_DESTROY:
    {
      delete this;
      bParsed = TRUE;
    }
    break;

  case DV_CHANGEPOS:
  {
    int phase = (int) wParam;
    LPPOINT pt = (LPPOINT) lParam;
    TString tsPhase = (phase == DVNM_DRAG_START ? "dragbegin" : (phase == DVNM_DRAG_END ? "dragfinish" : "drag"));

    this->execAliasEx("%s,%d,%d,%d", tsPhase.to_chr(), this->getUserID(), pt->x, pt->y);
    break;
  }

  default:
    return this->CommonMessage( uMsg, wParam, lParam, bParsed);
    break;
  }

  return lRes;
}
<|endoftext|>


<commit_before>#include "LinearImage.h"

LinearImage::LinearImage( const size_t width, const size_t height, const bool hasAlpha, const unsigned char* data, const float gamma )
    : mWidth( width ), mHeight( height )
{
    InitTables( gamma );

    // allocate channels
    mChannels.resize( hasAlpha ? 4 : 3 );
    for( Channel& channel : mChannels )
    {
        channel.resize( mWidth * mHeight );
    }

    if( NULL == data )
    {
        return;
    }

    // convert to linear color
    const size_t srcPitch = mWidth * 3;
    const unsigned char* srcBytes = data;
    for( size_t y = 0; y < (size_t)mHeight; ++y )
    {
        const size_t dstRow = y * mWidth;
        const unsigned char* srcRow = &srcBytes[ y * srcPitch ];
        for( size_t x = 0; x < (size_t)mWidth; ++x )
        {
            for( size_t c = 0; c < 3; ++c )
            {
                mChannels[ c ][ dstRow + x ] = mSrgbToLinear[ srcRow[ x * 3 + c ] ];
            }
            if( hasAlpha )
            {
                mChannels[ 3 ][ dstRow + x ] = srcRow[ x * 3 + 3 ] * ( 1.0f / 255.0f );
            }
        }
    }
}

void LinearImage::GetSrgb( std::vector< unsigned char >& color, std::vector< unsigned char >& alpha ) const
{
    color.resize( mWidth * mHeight * 3 );
    for( size_t i = 0; i < mWidth * mHeight; ++i )
    {
        for( size_t c = 0; c < 3; ++c )
        {
            int j = static_cast< int >( mLinearToSrgb.size() * mChannels[ c ][ i ] + 0.5f );
            if( j < 0 )                             j = 0;
            // TODO: figure out signed issues
            if( j >= (int)mLinearToSrgb.size() )    j = (int)( mLinearToSrgb.size() - 1 );
            color[ i * 3 + c ] = mLinearToSrgb[ j ];
        }
    }

    alpha.resize( 0 );
    if( mChannels.size() == 4 )
    {
        alpha.resize( mWidth * mHeight );
        for( size_t i = 0; i < mWidth * mHeight; ++i )
        {
            int j = static_cast< int >( 255.0f * mChannels[ 3 ][ i ] + 0.5f );
            if( j < 0 )     j = 0;
            if( j >= 255 )  j = 255;
            alpha[ i ] = static_cast< unsigned char >( j );
        }
    }
}

const float* LinearImage::GetRow( const size_t channel, const size_t row ) const
{
    if( channel > mChannels.size() || row >= mHeight )
        return NULL;
    return &mChannels[ channel ][ mWidth * row ];
}

float* LinearImage::GetRow( const size_t channel, const size_t row )
{
    return const_cast< float* >( static_cast< const LinearImage& >( *this ).GetRow( channel, row ) );
}

void LinearImage::InitTables( const float gamma )
{
    mSrgbToLinear.resize( 256 );
    for( size_t i = 0; i < mSrgbToLinear.size(); ++i )
    {
        mSrgbToLinear[ i ] = pow( i / 255.0f, gamma );
    }

    mLinearToSrgb.resize( 4096 );
    const float invSize = 1.0f / mLinearToSrgb.size();
    const float invGamma = 1.0f / gamma;
    for( size_t i = 0; i < mLinearToSrgb.size(); ++i )
    {
        int k = static_cast< int >( 255.0f * pow( i * invSize, invGamma ) + 0.5f );
        if( k < 0 )     k = 0;
        if( k > 255 )   k = 255;
        mLinearToSrgb[ i ] = static_cast< unsigned char >( k );
    }
}<commit_msg>Add <cmath><commit_after>#include "LinearImage.h"
#include <cmath>

LinearImage::LinearImage( const size_t width, const size_t height, const bool hasAlpha, const unsigned char* data, const float gamma )
    : mWidth( width ), mHeight( height )
{
    InitTables( gamma );

    // allocate channels
    mChannels.resize( hasAlpha ? 4 : 3 );
    for( Channel& channel : mChannels )
    {
        channel.resize( mWidth * mHeight );
    }

    if( NULL == data )
    {
        return;
    }

    // convert to linear color
    const size_t srcPitch = mWidth * 3;
    const unsigned char* srcBytes = data;
    for( size_t y = 0; y < (size_t)mHeight; ++y )
    {
        const size_t dstRow = y * mWidth;
        const unsigned char* srcRow = &srcBytes[ y * srcPitch ];
        for( size_t x = 0; x < (size_t)mWidth; ++x )
        {
            for( size_t c = 0; c < 3; ++c )
            {
                mChannels[ c ][ dstRow + x ] = mSrgbToLinear[ srcRow[ x * 3 + c ] ];
            }
            if( hasAlpha )
            {
                mChannels[ 3 ][ dstRow + x ] = srcRow[ x * 3 + 3 ] * ( 1.0f / 255.0f );
            }
        }
    }
}

void LinearImage::GetSrgb( std::vector< unsigned char >& color, std::vector< unsigned char >& alpha ) const
{
    color.resize( mWidth * mHeight * 3 );
    for( size_t i = 0; i < mWidth * mHeight; ++i )
    {
        for( size_t c = 0; c < 3; ++c )
        {
            int j = static_cast< int >( mLinearToSrgb.size() * mChannels[ c ][ i ] + 0.5f );
            if( j < 0 )                             j = 0;
            // TODO: figure out signed issues
            if( j >= (int)mLinearToSrgb.size() )    j = (int)( mLinearToSrgb.size() - 1 );
            color[ i * 3 + c ] = mLinearToSrgb[ j ];
        }
    }

    alpha.resize( 0 );
    if( mChannels.size() == 4 )
    {
        alpha.resize( mWidth * mHeight );
        for( size_t i = 0; i < mWidth * mHeight; ++i )
        {
            int j = static_cast< int >( 255.0f * mChannels[ 3 ][ i ] + 0.5f );
            if( j < 0 )     j = 0;
            if( j >= 255 )  j = 255;
            alpha[ i ] = static_cast< unsigned char >( j );
        }
    }
}

const float* LinearImage::GetRow( const size_t channel, const size_t row ) const
{
    if( channel > mChannels.size() || row >= mHeight )
        return NULL;
    return &mChannels[ channel ][ mWidth * row ];
}

float* LinearImage::GetRow( const size_t channel, const size_t row )
{
    return const_cast< float* >( static_cast< const LinearImage& >( *this ).GetRow( channel, row ) );
}

void LinearImage::InitTables( const float gamma )
{
    mSrgbToLinear.resize( 256 );
    for( size_t i = 0; i < mSrgbToLinear.size(); ++i )
    {
        mSrgbToLinear[ i ] = pow( i / 255.0f, gamma );
    }

    mLinearToSrgb.resize( 4096 );
    const float invSize = 1.0f / mLinearToSrgb.size();
    const float invGamma = 1.0f / gamma;
    for( size_t i = 0; i < mLinearToSrgb.size(); ++i )
    {
        int k = static_cast< int >( 255.0f * pow( i * invSize, invGamma ) + 0.5f );
        if( k < 0 )     k = 0;
        if( k > 255 )   k = 255;
        mLinearToSrgb[ i ] = static_cast< unsigned char >( k );
    }
}
<|endoftext|>