<commit_before>/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * 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 <array>
#include <cstdio>
#include <limits>

#include <folly/init/Init.h>

#include <thrift/lib/cpp/Thrift.h>
#include <thrift/lib/cpp/protocol/TBinaryProtocol.h>
#include <thrift/lib/cpp/protocol/TCompactProtocol.h>
#include <thrift/lib/cpp/protocol/THeaderProtocol.h>
#include <thrift/lib/cpp/protocol/TJSONProtocol.h>
#include <thrift/lib/cpp/transport/TBufferTransports.h>

#include <thrift/test/GenericHelpers.h>

using namespace apache::thrift;
using namespace apache::thrift::protocol;

namespace {

#define ERR_LEN 512
extern char errorMessage[ERR_LEN];

template <typename TProto, typename Val>
void testNaked(Val val) {
  auto protocol =
      std::make_shared<TProto>(std::make_shared<transport::TMemoryBuffer>());

  GenericIO::write(protocol, val);
  protocol->getTransport()->flush();
  Val out;
  GenericIO::read(protocol, out);
  if (out != val) {
    snprintf(
        errorMessage,
        ERR_LEN,
        "Invalid naked test (type: %s)",
        ClassNames::getName<Val>());
    throw TLibraryException(errorMessage);
  }
}

template <typename TProto, protocol::TType type, typename Val>
void testField(const Val& val) {
  auto protocol =
      std::make_shared<TProto>(std::make_shared<transport::TMemoryBuffer>());

  protocol->writeStructBegin("test_struct");
  protocol->writeFieldBegin("test_field", type, (int16_t)15);

  GenericIO::write(protocol, val);

  protocol->writeFieldEnd();
  protocol->writeStructEnd();
  protocol->getTransport()->flush();

  std::string name;
  protocol::TType fieldType;
  int16_t fieldId;

  protocol->readStructBegin(name);
  protocol->readFieldBegin(name, fieldType, fieldId);

  if (fieldId != 15) {
    snprintf(
        errorMessage, ERR_LEN, "Invalid ID (type: %s)", typeid(val).name());
    throw TLibraryException(errorMessage);
  }
  if (fieldType != type) {
    snprintf(
        errorMessage,
        ERR_LEN,
        "Invalid Field Type (type: %s)",
        typeid(val).name());
    throw TLibraryException(errorMessage);
  }

  Val out;
  GenericIO::read(protocol, out);

  if (out != val) {
    snprintf(
        errorMessage,
        ERR_LEN,
        "Invalid value read (type: %s)",
        typeid(val).name());
    throw TLibraryException(errorMessage);
  }

  protocol->readFieldEnd();
  protocol->readStructEnd();
}

template <typename TProto>
void testMessage() {
  struct TMessage {
    const char* name;
    protocol::TMessageType type;
    int32_t seqid;
  };
  std::array<TMessage, 4> messages{{
      {"short message name", protocol::T_CALL, 0},
      {"1", protocol::T_REPLY, 12345},
      {"loooooooooooooooooooooooooooooooooong", protocol::T_EXCEPTION, 1 << 16},
      {"Janky", protocol::T_CALL, 0},
  }};

  for (int i = 0; i < 4; i++) {
    auto protocol =
        std::make_shared<TProto>(std::make_shared<transport::TMemoryBuffer>());

    protocol->writeMessageBegin(
        messages[i].name, messages[i].type, messages[i].seqid);
    protocol->writeMessageEnd();
    protocol->getTransport()->flush();

    std::string name;
    protocol::TMessageType type;
    int32_t seqid;

    protocol->readMessageBegin(name, type, seqid);
    if (name != messages[i].name || type != messages[i].type ||
        seqid != messages[i].seqid) {
      throw TLibraryException("readMessageBegin failed.");
    }
  }
}

template <typename TProto>
void testProtocol(const char* protoname) {
  try {
    testNaked<TProto, int8_t>((int8_t)123);

    for (int32_t i = 0; i < 128; i++) {
      testField<TProto, T_BYTE, int8_t>((int8_t)i);
      testField<TProto, T_BYTE, int8_t>((int8_t)-i);
    }

    testNaked<TProto, int16_t>((int16_t)0);
    testNaked<TProto, int16_t>((int16_t)1);
    testNaked<TProto, int16_t>((int16_t)15000);
    testNaked<TProto, int16_t>((int16_t)0x7fff);
    testNaked<TProto, int16_t>((int16_t)-1);
    testNaked<TProto, int16_t>((int16_t)-15000);
    testNaked<TProto, int16_t>((int16_t)-0x7fff);
    testNaked<TProto, int16_t>(std::numeric_limits<int16_t>::min());
    testNaked<TProto, int16_t>(std::numeric_limits<int16_t>::max());

    testField<TProto, T_I16, int16_t>((int16_t)0);
    testField<TProto, T_I16, int16_t>((int16_t)1);
    testField<TProto, T_I16, int16_t>((int16_t)7);
    testField<TProto, T_I16, int16_t>((int16_t)150);
    testField<TProto, T_I16, int16_t>((int16_t)15000);
    testField<TProto, T_I16, int16_t>((int16_t)0x7fff);
    testField<TProto, T_I16, int16_t>((int16_t)-1);
    testField<TProto, T_I16, int16_t>((int16_t)-7);
    testField<TProto, T_I16, int16_t>((int16_t)-150);
    testField<TProto, T_I16, int16_t>((int16_t)-15000);
    testField<TProto, T_I16, int16_t>((int16_t)-0x7fff);

    testNaked<TProto, int32_t>(0);
    testNaked<TProto, int32_t>(1);
    testNaked<TProto, int32_t>(15000);
    testNaked<TProto, int32_t>(0xffff);
    testNaked<TProto, int32_t>(-1);
    testNaked<TProto, int32_t>(-15000);
    testNaked<TProto, int32_t>(-0xffff);
    testNaked<TProto, int32_t>(std::numeric_limits<int32_t>::min());
    testNaked<TProto, int32_t>(std::numeric_limits<int32_t>::max());

    testField<TProto, T_I32, int32_t>(0);
    testField<TProto, T_I32, int32_t>(1);
    testField<TProto, T_I32, int32_t>(7);
    testField<TProto, T_I32, int32_t>(150);
    testField<TProto, T_I32, int32_t>(15000);
    testField<TProto, T_I32, int32_t>(31337);
    testField<TProto, T_I32, int32_t>(0xffff);
    testField<TProto, T_I32, int32_t>(0xffffff);
    testField<TProto, T_I32, int32_t>(-1);
    testField<TProto, T_I32, int32_t>(-7);
    testField<TProto, T_I32, int32_t>(-150);
    testField<TProto, T_I32, int32_t>(-15000);
    testField<TProto, T_I32, int32_t>(-0xffff);
    testField<TProto, T_I32, int32_t>(-0xffffff);
    testNaked<TProto, int64_t>(std::numeric_limits<int32_t>::min());
    testNaked<TProto, int64_t>(std::numeric_limits<int32_t>::max());
    testNaked<TProto, int64_t>(std::numeric_limits<int32_t>::min() + 10);
    testNaked<TProto, int64_t>(std::numeric_limits<int32_t>::max() - 16);
    testNaked<TProto, int64_t>(std::numeric_limits<int64_t>::min());
    testNaked<TProto, int64_t>(std::numeric_limits<int64_t>::max());

    testNaked<TProto, int64_t>(0);
    for (int64_t i = 0; i < 62; i++) {
      testNaked<TProto, int64_t>(1L << i);
      testNaked<TProto, int64_t>(-(1L << i));
    }

    testField<TProto, T_I64, int64_t>(0);
    for (int i = 0; i < 62; i++) {
      testField<TProto, T_I64, int64_t>(1L << i);
      testField<TProto, T_I64, int64_t>(-(1L << i));
    }

    testNaked<TProto, double>(123.456);

    testNaked<TProto, std::string>("");
    testNaked<TProto, std::string>("short");
    testNaked<TProto, std::string>("borderlinetiny");
    testNaked<TProto, std::string>("a bit longer than the smallest possible");
    testNaked<TProto, std::string>(
        "\x1\x2\x3\x4\x5\x6\x7\x8\x9\xA"); // kinda binary test

    testField<TProto, T_STRING, std::string>("");
    testField<TProto, T_STRING, std::string>("short");
    testField<TProto, T_STRING, std::string>("borderlinetiny");
    testField<TProto, T_STRING, std::string>(
        "a bit longer than the smallest possible");

    testMessage<TProto>();

    printf("%s => OK\n", protoname);
  } catch (const TException& e) {
    snprintf(
        errorMessage, ERR_LEN, "%s => Test FAILED: %s", protoname, e.what());
    throw TLibraryException(errorMessage);
  }
}

char errorMessage[ERR_LEN];

} // namespace

int main(int argc, char** argv) {
  folly::init(&argc, &argv);

  try {
    testProtocol<TBinaryProtocol>("TBinaryProtocol");
    testProtocol<TCompactProtocol>("TCompactProtocol");
    testProtocol<THeaderProtocol>("THeaderProtocol");
    testProtocol<TJSONProtocol>("TJSONProtocol");
  } catch (const TException& e) {
    printf("%s\n", e.what());
    return 1;
  }
  return 0;
}
<commit_msg>Kill AllProtocolTests<commit_after><|endoftext|>


<commit_before>#ifndef DUNE_STUFF_FUNCTION_EXPRESSION_HH
#define DUNE_STUFF_FUNCTION_EXPRESSION_HH

#ifdef HAVE_CMAKE_CONFIG
  #include "cmake_config.h"
#else
  #include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG

#include <sstream>
#include <vector>

#include <dune/common/fvector.hh>
#include <dune/common/dynvector.hh>
#include <dune/common/exceptions.hh>
#include <dune/common/static_assert.hh>

#include <dune/stuff/common/parameter/tree.hh>
#include <dune/stuff/common/string.hh>
#include <dune/stuff/common/color.hh>

#include "expression/base.hh"
#include "interface.hh"

namespace Dune {
namespace Stuff {
namespace Function {

template< class DomainFieldImp, int domainDim,
          class RangeFieldImp, int rangeDim >
class Expression
  : public ExpressionBase< DomainFieldImp, domainDim, RangeFieldImp, rangeDim >
  , public Interface< DomainFieldImp, domainDim, RangeFieldImp, rangeDim >
{
public:
  typedef Expression<  DomainFieldImp, domainDim, RangeFieldImp, rangeDim >     ThisType;
  typedef ExpressionBase<  DomainFieldImp, domainDim, RangeFieldImp, rangeDim > BaseType;
  typedef Interface<  DomainFieldImp, domainDim, RangeFieldImp, rangeDim >      InterfaceType;

  using typename InterfaceType::DomainFieldType;
  using InterfaceType::dimDomain;
  typedef typename InterfaceType::DomainType  DomainType;
  using typename InterfaceType::RangeFieldType;
  using InterfaceType::dimRange;
  typedef typename InterfaceType::RangeType   RangeType;

  Expression(const std::string _variable,
             const std::string _expression,
             const int _order = -1,
             const std::string _name = "function.expression")
    : BaseType(_variable, _expression)
    , order_(_order)
    , name_(_name)
  {}

  Expression(const std::string _variable,
             const std::vector< std::string > _expressions,
             const int _order = -1,
             const std::string _name = "function.expression")
    : BaseType(_variable, _expressions)
    , order_(_order)
    , name_(_name)
  {}

  Expression(const ThisType& other)
    : BaseType(other)
    , order_(other.order())
    , name_(other.name())
  {}

  ThisType& operator=(const ThisType& other)
  {
    if (this != &other) {
      BaseType::operator=(other);
      order_ = other.order();
      name_ = other.name();
    }
    return this;
  } // ThisType& operator=(const ThisType& other)

  static Dune::ParameterTree createSampleDescription(const std::string prefix = "")
  {
    Dune::ParameterTree description;
    description[prefix + "variable"] = "x";
    description[prefix + "expression"] = "x[0]";
    description[prefix + "order"] = "1";
    description[prefix + "name"] = "function.expression";
    return description;
  }

  static ThisType createFromDescription(const Dune::ParameterTree& _description)
  {
    const Dune::Stuff::Common::ExtendedParameterTree description(_description);
    // get necessary
    const std::string _variable = description.get< std::string >("variable");
    const std::vector< std::string > _expressions = description.getVector< std::string >("expression",
                                                                                InterfaceType::dimRange);
    // get optional
    const int _order = description.get< int >("order", -1);
    const std::string _name = description.get< std::string >("name", "function.expression");
    // create and return
    return ThisType(_variable, _expressions, _order, _name);
  } // static ThisType createFromDescription(const Dune::ParameterTree& _description)

  virtual int order() const
  {
    return order_;
  }

  virtual std::string name() const
  {
    return name_;
  }

  virtual void evaluate(const DomainType& _x, RangeType& _ret) const
  {
    BaseType::evaluate(_x, _ret);
  }

private:
  int order_;
  std::string name_;
}; // class Expression

} // namespace Function
} // namespace Stuff
} // namespace Dune

#endif // DUNE_STUFF_FUNCTION_EXPRESSION_HH
<commit_msg>[function.expression] fixed createSampleDescription() and createFromDescription()<commit_after>#ifndef DUNE_STUFF_FUNCTION_EXPRESSION_HH
#define DUNE_STUFF_FUNCTION_EXPRESSION_HH

#ifdef HAVE_CMAKE_CONFIG
  #include "cmake_config.h"
#else
  #include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG

#include <sstream>
#include <vector>

#include <dune/common/fvector.hh>
#include <dune/common/dynvector.hh>
#include <dune/common/exceptions.hh>
#include <dune/common/static_assert.hh>

#include <dune/stuff/common/parameter/tree.hh>
#include <dune/stuff/common/string.hh>
#include <dune/stuff/common/color.hh>

#include "expression/base.hh"
#include "interface.hh"

namespace Dune {
namespace Stuff {
namespace Function {

template< class DomainFieldImp, int domainDim,
          class RangeFieldImp, int rangeDim >
class Expression
  : public ExpressionBase< DomainFieldImp, domainDim, RangeFieldImp, rangeDim >
  , public Interface< DomainFieldImp, domainDim, RangeFieldImp, rangeDim >
{
public:
  typedef Expression<  DomainFieldImp, domainDim, RangeFieldImp, rangeDim >     ThisType;
  typedef ExpressionBase<  DomainFieldImp, domainDim, RangeFieldImp, rangeDim > BaseType;
  typedef Interface<  DomainFieldImp, domainDim, RangeFieldImp, rangeDim >      InterfaceType;

  using typename InterfaceType::DomainFieldType;
  using InterfaceType::dimDomain;
  typedef typename InterfaceType::DomainType  DomainType;
  using typename InterfaceType::RangeFieldType;
  using InterfaceType::dimRange;
  typedef typename InterfaceType::RangeType   RangeType;

  Expression(const std::string _variable,
             const std::string _expression,
             const int _order = -1,
             const std::string _name = "function.expression")
    : BaseType(_variable, _expression)
    , order_(_order)
    , name_(_name)
  {}

  Expression(const std::string _variable,
             const std::vector< std::string > _expressions,
             const int _order = -1,
             const std::string _name = "function.expression")
    : BaseType(_variable, _expressions)
    , order_(_order)
    , name_(_name)
  {}

  Expression(const ThisType& other)
    : BaseType(other)
    , order_(other.order())
    , name_(other.name())
  {}

  ThisType& operator=(const ThisType& other)
  {
    if (this != &other) {
      BaseType::operator=(other);
      order_ = other.order();
      name_ = other.name();
    }
    return this;
  } // ThisType& operator=(const ThisType& other)

  static Dune::ParameterTree createSampleDescription(const std::string subName = "")
  {
    Dune::ParameterTree description;
    description["variable"] = "x";
    description["expression"] = "[x[0]; sin(x[0])]";
    description["order"] = "1";
    description["name"] = "function.expression";
    if (subName.empty())
      return description;
    else {
      Dune::Stuff::Common::ExtendedParameterTree extendedDescription;
      extendedDescription.add(description, subName);
      return extendedDescription;
    }
  }

  static ThisType createFromDescription(const Dune::ParameterTree& _description)
  {
    const Dune::Stuff::Common::ExtendedParameterTree description(_description);
    // get necessary
    const std::string _variable = description.get< std::string >("variable", "x");
    std::vector< std::string > _expressions;
    // lets see, if there is a key or vector
    if (description.hasVector("expression")) {
      const std::vector< std::string > expr = description.getVector< std::string >("expression", 1);
      for (size_t ii = 0; ii < expr.size(); ++ii)
        _expressions.push_back(expr[ii]);
    } else if (description.hasKey("expression")) {
      const std::string expr = description.get< std::string >("expression");
      _expressions.push_back(expr);
    } else
      DUNE_THROW(Dune::IOError,
                 "\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
                 << " neither key nor vector 'expression' found in the following description:\n"
                 << description.reportString("  "));
    // get optional
    const int _order = description.get< int >("order", -1);
    const std::string _name = description.get< std::string >("name", "function.expression");
    // create and return
    return ThisType(_variable, _expressions, _order, _name);
  } // static ThisType createFromDescription(const Dune::ParameterTree& _description)

  virtual int order() const
  {
    return order_;
  }

  virtual std::string name() const
  {
    return name_;
  }

  virtual void evaluate(const DomainType& _x, RangeType& _ret) const
  {
    BaseType::evaluate(_x, _ret);
  }

private:
  int order_;
  std::string name_;
}; // class Expression

} // namespace Function
} // namespace Stuff
} // namespace Dune

#endif // DUNE_STUFF_FUNCTION_EXPRESSION_HH
<|endoftext|>


<commit_before>/*************************************************************************/
/*  import_defaults_editor.cpp                                           */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* 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:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* 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.                */
/*************************************************************************/

#include "import_defaults_editor.h"

class ImportDefaultsEditorSettings : public Object {
	GDCLASS(ImportDefaultsEditorSettings, Object)
	friend class ImportDefaultsEditor;
	List<PropertyInfo> properties;
	Map<StringName, Variant> values;
	Map<StringName, Variant> default_values;

	Ref<ResourceImporter> importer;

protected:
	bool _set(const StringName &p_name, const Variant &p_value) {
		if (values.has(p_name)) {
			values[p_name] = p_value;
			return true;
		} else {
			return false;
		}
	}
	bool _get(const StringName &p_name, Variant &r_ret) const {
		if (values.has(p_name)) {
			r_ret = values[p_name];
			return true;
		} else {
			r_ret = Variant();
			return false;
		}
	}
	void _get_property_list(List<PropertyInfo> *p_list) const {
		if (importer.is_null()) {
			return;
		}
		for (const List<PropertyInfo>::Element *E = properties.front(); E; E = E->next()) {
			if (importer->get_option_visibility(E->get().name, values)) {
				p_list->push_back(E->get());
			}
		}
	}
};

void ImportDefaultsEditor::_reset() {
	if (settings->importer.is_valid()) {
		settings->values = settings->default_values;
		settings->notify_property_list_changed();
	}
}
void ImportDefaultsEditor::_save() {
	if (settings->importer.is_valid()) {
		Dictionary modified;

		for (Map<StringName, Variant>::Element *E = settings->values.front(); E; E = E->next()) {
			if (E->get() != settings->default_values[E->key()]) {
				modified[E->key()] = E->get();
			}
		}

		if (modified.size()) {
			ProjectSettings::get_singleton()->set("importer_defaults/" + settings->importer->get_importer_name(), modified);
		} else {
			ProjectSettings::get_singleton()->set("importer_defaults/" + settings->importer->get_importer_name(), Variant());
		}

		emit_signal("project_settings_changed");
	}
}

void ImportDefaultsEditor::_update_importer() {
	List<Ref<ResourceImporter>> importer_list;
	ResourceFormatImporter::get_singleton()->get_importers(&importer_list);
	Ref<ResourceImporter> importer;
	for (List<Ref<ResourceImporter>>::Element *E = importer_list.front(); E; E = E->next()) {
		if (E->get()->get_visible_name() == importers->get_item_text(importers->get_selected())) {
			importer = E->get();
			break;
		}
	}

	settings->properties.clear();
	settings->values.clear();
	settings->importer = importer;

	if (importer.is_valid()) {
		List<ResourceImporter::ImportOption> options;
		importer->get_import_options(&options);
		Dictionary d;
		if (ProjectSettings::get_singleton()->has_setting("importer_defaults/" + importer->get_importer_name())) {
			d = ProjectSettings::get_singleton()->get("importer_defaults/" + importer->get_importer_name());
		}

		for (List<ResourceImporter::ImportOption>::Element *E = options.front(); E; E = E->next()) {
			settings->properties.push_back(E->get().option);
			if (d.has(E->get().option.name)) {
				settings->values[E->get().option.name] = d[E->get().option.name];
			} else {
				settings->values[E->get().option.name] = E->get().default_value;
			}
			settings->default_values[E->get().option.name] = E->get().default_value;
		}

		save_defaults->set_disabled(false);
		reset_defaults->set_disabled(false);

	} else {
		save_defaults->set_disabled(true);
		reset_defaults->set_disabled(true);
	}

	settings->notify_property_list_changed();

	inspector->edit(settings);
}
void ImportDefaultsEditor::_importer_selected(int p_index) {
	_update_importer();
}
void ImportDefaultsEditor::clear() {
	importers->clear();
	importers->add_item("<" + TTR("Select Importer") + ">");
	List<Ref<ResourceImporter>> importer_list;
	ResourceFormatImporter::get_singleton()->get_importers(&importer_list);
	Vector<String> names;
	for (List<Ref<ResourceImporter>>::Element *E = importer_list.front(); E; E = E->next()) {
		String vn = E->get()->get_visible_name();
		names.push_back(vn);
	}
	names.sort();

	for (int i = 0; i < names.size(); i++) {
		importers->add_item(names[i]);
	}
}
void ImportDefaultsEditor::_bind_methods() {
	ADD_SIGNAL(MethodInfo("project_settings_changed"));
}
ImportDefaultsEditor::ImportDefaultsEditor() {
	HBoxContainer *hb = memnew(HBoxContainer);
	hb->add_child(memnew(Label(TTR("Importer:"))));
	importers = memnew(OptionButton);
	hb->add_child(importers);
	hb->add_spacer();
	importers->connect("item_selected", callable_mp(this, &ImportDefaultsEditor::_importer_selected));
	reset_defaults = memnew(Button);
	reset_defaults->set_text(TTR("Reset to Defaults"));
	reset_defaults->set_disabled(true);
	reset_defaults->connect("pressed", callable_mp(this, &ImportDefaultsEditor::_reset));
	hb->add_child(reset_defaults);
	add_child(hb);
	inspector = memnew(EditorInspector);
	add_child(inspector);
	inspector->set_v_size_flags(SIZE_EXPAND_FILL);
	CenterContainer *cc = memnew(CenterContainer);
	save_defaults = memnew(Button);
	save_defaults->set_text(TTR("Save"));
	save_defaults->connect("pressed", callable_mp(this, &ImportDefaultsEditor::_save));
	cc->add_child(save_defaults);
	add_child(cc);

	settings = memnew(ImportDefaultsEditorSettings);
}

ImportDefaultsEditor::~ImportDefaultsEditor() {
	inspector->edit(nullptr);
	memdelete(settings);
}
<commit_msg>Fix import selector resetting in Import Defaults Editor<commit_after>/*************************************************************************/
/*  import_defaults_editor.cpp                                           */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* 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:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* 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.                */
/*************************************************************************/

#include "import_defaults_editor.h"

class ImportDefaultsEditorSettings : public Object {
	GDCLASS(ImportDefaultsEditorSettings, Object)
	friend class ImportDefaultsEditor;
	List<PropertyInfo> properties;
	Map<StringName, Variant> values;
	Map<StringName, Variant> default_values;

	Ref<ResourceImporter> importer;

protected:
	bool _set(const StringName &p_name, const Variant &p_value) {
		if (values.has(p_name)) {
			values[p_name] = p_value;
			return true;
		} else {
			return false;
		}
	}
	bool _get(const StringName &p_name, Variant &r_ret) const {
		if (values.has(p_name)) {
			r_ret = values[p_name];
			return true;
		} else {
			r_ret = Variant();
			return false;
		}
	}
	void _get_property_list(List<PropertyInfo> *p_list) const {
		if (importer.is_null()) {
			return;
		}
		for (const List<PropertyInfo>::Element *E = properties.front(); E; E = E->next()) {
			if (importer->get_option_visibility(E->get().name, values)) {
				p_list->push_back(E->get());
			}
		}
	}
};

void ImportDefaultsEditor::_reset() {
	if (settings->importer.is_valid()) {
		settings->values = settings->default_values;
		settings->notify_property_list_changed();
	}
}

void ImportDefaultsEditor::_save() {
	if (settings->importer.is_valid()) {
		Dictionary modified;

		for (Map<StringName, Variant>::Element *E = settings->values.front(); E; E = E->next()) {
			if (E->get() != settings->default_values[E->key()]) {
				modified[E->key()] = E->get();
			}
		}

		if (modified.size()) {
			ProjectSettings::get_singleton()->set("importer_defaults/" + settings->importer->get_importer_name(), modified);
		} else {
			ProjectSettings::get_singleton()->set("importer_defaults/" + settings->importer->get_importer_name(), Variant());
		}

		emit_signal("project_settings_changed");
	}
}

void ImportDefaultsEditor::_update_importer() {
	List<Ref<ResourceImporter>> importer_list;
	ResourceFormatImporter::get_singleton()->get_importers(&importer_list);
	Ref<ResourceImporter> importer;
	for (List<Ref<ResourceImporter>>::Element *E = importer_list.front(); E; E = E->next()) {
		if (E->get()->get_visible_name() == importers->get_item_text(importers->get_selected())) {
			importer = E->get();
			break;
		}
	}

	settings->properties.clear();
	settings->values.clear();
	settings->importer = importer;

	if (importer.is_valid()) {
		List<ResourceImporter::ImportOption> options;
		importer->get_import_options(&options);
		Dictionary d;
		if (ProjectSettings::get_singleton()->has_setting("importer_defaults/" + importer->get_importer_name())) {
			d = ProjectSettings::get_singleton()->get("importer_defaults/" + importer->get_importer_name());
		}

		for (List<ResourceImporter::ImportOption>::Element *E = options.front(); E; E = E->next()) {
			settings->properties.push_back(E->get().option);
			if (d.has(E->get().option.name)) {
				settings->values[E->get().option.name] = d[E->get().option.name];
			} else {
				settings->values[E->get().option.name] = E->get().default_value;
			}
			settings->default_values[E->get().option.name] = E->get().default_value;
		}

		save_defaults->set_disabled(false);
		reset_defaults->set_disabled(false);

	} else {
		save_defaults->set_disabled(true);
		reset_defaults->set_disabled(true);
	}

	settings->notify_property_list_changed();

	inspector->edit(settings);
}

void ImportDefaultsEditor::_importer_selected(int p_index) {
	_update_importer();
}

void ImportDefaultsEditor::clear() {
	String last_selected;
	if (importers->get_selected() > 0) {
		last_selected = importers->get_item_text(importers->get_selected());
	}

	importers->clear();

	importers->add_item("<" + TTR("Select Importer") + ">");
	importers->set_item_disabled(0, true);

	List<Ref<ResourceImporter>> importer_list;
	ResourceFormatImporter::get_singleton()->get_importers(&importer_list);
	Vector<String> names;
	for (List<Ref<ResourceImporter>>::Element *E = importer_list.front(); E; E = E->next()) {
		String vn = E->get()->get_visible_name();
		names.push_back(vn);
	}
	names.sort();

	for (int i = 0; i < names.size(); i++) {
		importers->add_item(names[i]);

		if (names[i] == last_selected) {
			importers->select(i + 1);
		}
	}
}

void ImportDefaultsEditor::_bind_methods() {
	ADD_SIGNAL(MethodInfo("project_settings_changed"));
}

ImportDefaultsEditor::ImportDefaultsEditor() {
	HBoxContainer *hb = memnew(HBoxContainer);
	hb->add_child(memnew(Label(TTR("Importer:"))));
	importers = memnew(OptionButton);
	hb->add_child(importers);
	hb->add_spacer();
	importers->connect("item_selected", callable_mp(this, &ImportDefaultsEditor::_importer_selected));
	reset_defaults = memnew(Button);
	reset_defaults->set_text(TTR("Reset to Defaults"));
	reset_defaults->set_disabled(true);
	reset_defaults->connect("pressed", callable_mp(this, &ImportDefaultsEditor::_reset));
	hb->add_child(reset_defaults);
	add_child(hb);
	inspector = memnew(EditorInspector);
	add_child(inspector);
	inspector->set_v_size_flags(SIZE_EXPAND_FILL);
	CenterContainer *cc = memnew(CenterContainer);
	save_defaults = memnew(Button);
	save_defaults->set_text(TTR("Save"));
	save_defaults->connect("pressed", callable_mp(this, &ImportDefaultsEditor::_save));
	cc->add_child(save_defaults);
	add_child(cc);

	settings = memnew(ImportDefaultsEditorSettings);
}

ImportDefaultsEditor::~ImportDefaultsEditor() {
	inspector->edit(nullptr);
	memdelete(settings);
}
<|endoftext|>


<commit_before>/*******************************************************************************
*    ALMA - Atacama Large Millimiter Array
*    (c) European Southern Observatory, 2002
*    Copyright by ESO (in the framework of the ALMA collaboration)
*    and Cosylab 2002, All rights reserved
*
*    This library is free software; you can redistribute it and/or
*    modify it under the terms of the GNU Lesser General Public
*    License as published by the Free Software Foundation; either
*    version 2.1 of the License, or (at your option) any later version.
*
*    This library is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
*    Lesser General Public License for more details.
*
*    You should have received a copy of the GNU Lesser General Public
*    License along with this library; if not, write to the Free Software
*    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
*
*
*
* "@(#) $Id: acstestcompErrorExplorerImpl.cpp,v 1.2 2008/10/01 05:33:43 cparedes Exp $"
*
*/

#include <acstestcompErrorExplorerImpl.h>

ACE_RCSID(acstestcomp, acstestcompErrorExplorerImpl, "$Id: acstestcompErrorExplorerImpl.cpp,v 1.2 2008/10/01 05:33:43 cparedes Exp $")

using namespace baci;

/////////////////////////////////////////////////
// ErrorExplorerImpl
/////////////////////////////////////////////////

ErrorExplorerImpl::ErrorExplorerImpl(
			 const ACE_CString &name,
			 maci::ContainerServices * containerServices) :
    CharacteristicComponentImpl(name,containerServices),
    m_explorerDoubleProperty_sp(new RWdouble(name+":explorerDoubleProperty", getComponent()),this)
{
    ACS_TRACE("::ErrorExplorerImpl::ErrorExplorerImpl");
}

ErrorExplorerImpl::~ErrorExplorerImpl()
{
    ACS_TRACE("::ErrorExplorerImpl::~ErrorExplorerImpl");
}

ACS::RWdouble_ptr
ErrorExplorerImpl::explorerDoubleProperty()
{
    if (m_explorerDoubleProperty_sp == 0)
	{
	return ACS::RWdouble::_nil();
	}

    ACS::RWdouble_var prop = ACS::RWdouble::_narrow(m_explorerDoubleProperty_sp->getCORBAReference());
    return prop._retn();
}

/* --------------- [ MACI DLL support functions ] -----------------*/

#include <maciACSComponentDefines.h>
MACI_DLL_SUPPORT_FUNCTIONS(ErrorExplorerImpl)

<commit_msg>upgraded to aCE+TAO 6.3.0 ICT-4152 - removed ACE_RCSID<commit_after>/*******************************************************************************
*    ALMA - Atacama Large Millimiter Array
*    (c) European Southern Observatory, 2002
*    Copyright by ESO (in the framework of the ALMA collaboration)
*    and Cosylab 2002, All rights reserved
*
*    This library is free software; you can redistribute it and/or
*    modify it under the terms of the GNU Lesser General Public
*    License as published by the Free Software Foundation; either
*    version 2.1 of the License, or (at your option) any later version.
*
*    This library is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
*    Lesser General Public License for more details.
*
*    You should have received a copy of the GNU Lesser General Public
*    License along with this library; if not, write to the Free Software
*    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
*
*
*
* "@(#) $Id: acstestcompErrorExplorerImpl.cpp,v 1.2 2008/10/01 05:33:43 cparedes Exp $"
*
*/

#include <acstestcompErrorExplorerImpl.h>

using namespace baci;

/////////////////////////////////////////////////
// ErrorExplorerImpl
/////////////////////////////////////////////////

ErrorExplorerImpl::ErrorExplorerImpl(
			 const ACE_CString &name,
			 maci::ContainerServices * containerServices) :
    CharacteristicComponentImpl(name,containerServices),
    m_explorerDoubleProperty_sp(new RWdouble(name+":explorerDoubleProperty", getComponent()),this)
{
    ACS_TRACE("::ErrorExplorerImpl::ErrorExplorerImpl");
}

ErrorExplorerImpl::~ErrorExplorerImpl()
{
    ACS_TRACE("::ErrorExplorerImpl::~ErrorExplorerImpl");
}

ACS::RWdouble_ptr
ErrorExplorerImpl::explorerDoubleProperty()
{
    if (m_explorerDoubleProperty_sp == 0)
	{
	return ACS::RWdouble::_nil();
	}

    ACS::RWdouble_var prop = ACS::RWdouble::_narrow(m_explorerDoubleProperty_sp->getCORBAReference());
    return prop._retn();
}

/* --------------- [ MACI DLL support functions ] -----------------*/

#include <maciACSComponentDefines.h>
MACI_DLL_SUPPORT_FUNCTIONS(ErrorExplorerImpl)

<|endoftext|>


<commit_before>//
//  VideoPlayer.cpp
//  Chilli Source
//  Created by Ian Copland on 10/08/2012.
//
//  The MIT License (MIT)
//
//  Copyright (c) 2012 Tag Games Limited
//
//  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:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  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.
//

#include <ChilliSource/Backend/Platform/Android/Video/Base/VideoPlayer.h>

#include <ChilliSource/Backend/Platform/Android/Core/JNI/JavaInterfaceManager.h>
#include <ChilliSource/Backend/Platform/Android/Video/Base/VideoPlayerJavaInterface.h>
#include <ChilliSource/Core/Base/Application.h>
#include <ChilliSource/Core/Base/MakeDelegate.h>
#include <ChilliSource/Core/Base/Screen.h>
#include <ChilliSource/Core/Math/MathUtils.h>
#include <ChilliSource/Core/Localisation/LocalisedText.h>
#include <ChilliSource/Core/String/StringUtils.h>
#include <ChilliSource/Core/Threading/TaskScheduler.h>
#include <ChilliSource/Video/Base/Subtitles.h>

namespace ChilliSource
{
    namespace Android
    {
    	CS_DEFINE_NAMEDTYPE(VideoPlayer);
        //--------------------------------------------------------------
        //--------------------------------------------------------------
        VideoPlayer::VideoPlayer()
        	: m_currentSubtitleTimeMS(0), m_isPlaying(false)
        {
        }
		//--------------------------------------------------------------
		//--------------------------------------------------------------
		bool VideoPlayer::IsA(Core::InterfaceIDType in_interfaceId) const
		{
			return (in_interfaceId == Video::VideoPlayer::InterfaceID || in_interfaceId == VideoPlayer::InterfaceID);
		}
        //--------------------------------------------------------------
        //--------------------------------------------------------------
        void VideoPlayer::Present(Core::StorageLocation in_storageLocation, const std::string& in_fileName, const VideoCompleteDelegate& in_delegate, bool in_dismissWithTap,
        		const Core::Colour& in_backgroundColour)
        {
        	CS_ASSERT(m_isPlaying == false, "Cannot present a video while one is already playing.");
        	m_isPlaying = true;
        	m_completionDelegate = in_delegate;

        	//calculate the storage location and full filename.
        	bool isPackage = false;
        	std::string fileName;
        	if (in_storageLocation == Core::StorageLocation::k_package)
        	{
        		isPackage = true;
        		fileName = Core::Application::Get()->GetFileSystem()->GetAbsolutePathToFile(Core::StorageLocation::k_package, in_fileName);
        	}
        	else if (in_storageLocation == Core::StorageLocation::k_DLC)
			{
        		if (Core::Application::Get()->GetFileSystem()->DoesFileExistInCachedDLC(in_fileName) == true)
        		{
        			isPackage = false;
        			fileName = Core::Application::Get()->GetFileSystem()->GetAbsolutePathToStorageLocation(Core::StorageLocation::k_DLC) + in_fileName;
        		}
        		else
        		{
        			isPackage = true;
        			fileName = Core::Application::Get()->GetFileSystem()->GetAbsolutePathToFile(Core::StorageLocation::k_package, Core::Application::Get()->GetFileSystem()->GetPackageDLCPath() + in_fileName);
        		}
			}
        	else
        	{
        		isPackage = false;
        		fileName = Core::Application::Get()->GetFileSystem()->GetAbsolutePathToStorageLocation(in_storageLocation) + in_fileName;
        	}

        	//start the video
        	m_javaInterface->Present(isPackage, fileName, in_dismissWithTap, in_backgroundColour, Core::MakeDelegate(this, &VideoPlayer::OnVideoComplete));
        }
        //--------------------------------------------------------------
		//--------------------------------------------------------------
		void VideoPlayer::PresentWithSubtitles(Core::StorageLocation in_storageLocation, const std::string& in_fileName, const Video::SubtitlesCSPtr& in_subtitles, const VideoCompleteDelegate& in_delegate,
                bool in_dismissWithTap, const Core::Colour& in_backgroundColour)
		{
			m_subtitles = in_subtitles;
			m_javaInterface->SetUpdateSubtitlesDelegate(Core::MakeDelegate(this, &VideoPlayer::OnUpdateSubtitles));
			Present(in_storageLocation, in_fileName, in_delegate, in_dismissWithTap, in_backgroundColour);
		}
        //-------------------------------------------------------
        //-------------------------------------------------------
        void VideoPlayer::OnInit()
        {
        	//get the media player java interface or create it if it doesn't yet exist.
			m_javaInterface = JavaInterfaceManager::GetSingletonPtr()->GetJavaInterface<VideoPlayerJavaInterface>();
			if (m_javaInterface == nullptr)
			{
				m_javaInterface = VideoPlayerJavaInterfaceSPtr(new VideoPlayerJavaInterface());
				JavaInterfaceManager::GetSingletonPtr()->AddJavaInterface(m_javaInterface);
			}
        }
        //---------------------------------------------------------------
        //---------------------------------------------------------------
        void VideoPlayer::OnVideoComplete()
        {
        	m_javaInterface->SetUpdateSubtitlesDelegate(nullptr);
        	m_subtitles.reset();
        	m_isPlaying = false;

        	if (m_completionDelegate != nullptr)
        	{
        		m_completionDelegate();
        	}
        }
		//---------------------------------------------------------------
		//---------------------------------------------------------------
		void VideoPlayer::OnUpdateSubtitles()
		{
			//only update if the position in the video has changed.
			f32 position = m_javaInterface->GetTime();
			TimeIntervalMs currentTimeMS = (TimeIntervalMs)(position * 1000.0f);
			if (m_currentSubtitleTimeMS != currentTimeMS)
			{
				m_currentSubtitleTimeMS = currentTimeMS;

				//get the current subtitles
				auto subtitleArray = m_subtitles->GetSubtitlesAtTime(m_currentSubtitleTimeMS);

				//add any new subtitles
				for (auto it = subtitleArray.begin(); it != subtitleArray.end(); ++it)
				{
					auto mapEntry = m_subtitleMap.find(*it);
					if (mapEntry == m_subtitleMap.end())
					{
						Core::UTF8String text = Core::LocalisedText::GetText((*it)->m_textId);
						const Video::Subtitles::Style* style = m_subtitles->GetStyleWithName((*it)->m_styleName);
						s64 subtitleID = m_javaInterface->CreateSubtitle(text, style->m_fontName, style->m_fontSize, Rendering::StringFromAlignmentAnchor(style->m_alignment), style->m_bounds.vOrigin.x, style->m_bounds.vOrigin.y, style->m_bounds.vSize.x, style->m_bounds.vSize.y);
						m_javaInterface->SetSubtitleColour(subtitleID, 0.0f, 0.0f, 0.0f, 0.0f);
						m_subtitleMap.insert(std::make_pair(*it, subtitleID));
					}
				}

				//update the current text views
				for (auto it = m_subtitleMap.begin(); it != m_subtitleMap.end(); ++it)
				{
					UpdateSubtitle(it->first, it->second, m_currentSubtitleTimeMS);
				}

				//removes any text views that are no longer needed.
				for (auto it = m_subtitlesToRemove.begin(); it != m_subtitlesToRemove.end(); ++it)
				{
					auto mapEntry = m_subtitleMap.find(*it);
					if (mapEntry != m_subtitleMap.end())
					{
						m_javaInterface->RemoveSubtitle(mapEntry->second);
						m_subtitleMap.erase(mapEntry);
					}
				}
				m_subtitlesToRemove.clear();
			}
		}
		//---------------------------------------------------------------
		//---------------------------------------------------------------
		void VideoPlayer::UpdateSubtitle(const Video::Subtitles::Subtitle* in_subtitle, s64 in_subtitleID, TimeIntervalMs in_timeMS)
		{
			const Video::Subtitles::Style* style = m_subtitles->GetStyleWithName(in_subtitle->m_styleName);

			f32 fade = 0.0f;
			s64 relativeTime = ((s64)in_timeMS) - ((s64)in_subtitle->m_startTimeMS);
			s64 displayTime = ((s64)in_subtitle->m_endTimeMS) - ((s64)in_subtitle->m_startTimeMS);

			//subtitle should not be displayed yet so remove
			if (relativeTime < 0)
			{
				m_subtitlesToRemove.push_back(in_subtitle);
			}

			//fading in
			else if (relativeTime < style->m_fadeTimeMS)
			{
				fade = ((f32)relativeTime) / ((f32)style->m_fadeTimeMS);
			}

			//active
			else if (relativeTime < displayTime - style->m_fadeTimeMS)
			{
				fade = 1.0f;
			}

			//fading out
			else if (relativeTime < displayTime)
			{
				fade = 1.0f - (((f32)relativeTime - (displayTime - style->m_fadeTimeMS)) / ((f32)style->m_fadeTimeMS));
			}

			//should no longer be displayed so remove
			else if (relativeTime >= displayTime)
			{
				m_subtitlesToRemove.push_back(in_subtitle);
			}

			m_javaInterface->SetSubtitleColour(in_subtitleID, style->m_colour.r, style->m_colour.g, style->m_colour.b, fade * style->m_colour.a);
		}
        //-------------------------------------------------------
        //-------------------------------------------------------
        void VideoPlayer::OnDestroy()
        {
        	m_javaInterface.reset();
        }
    }
}
<commit_msg>Apply localised text changed to Android<commit_after>//
//  VideoPlayer.cpp
//  Chilli Source
//  Created by Ian Copland on 10/08/2012.
//
//  The MIT License (MIT)
//
//  Copyright (c) 2012 Tag Games Limited
//
//  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:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  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.
//

#include <ChilliSource/Backend/Platform/Android/Video/Base/VideoPlayer.h>

#include <ChilliSource/Backend/Platform/Android/Core/JNI/JavaInterfaceManager.h>
#include <ChilliSource/Backend/Platform/Android/Video/Base/VideoPlayerJavaInterface.h>
#include <ChilliSource/Core/Base/Application.h>
#include <ChilliSource/Core/Base/MakeDelegate.h>
#include <ChilliSource/Core/Base/Screen.h>
#include <ChilliSource/Core/Math/MathUtils.h>
#include <ChilliSource/Core/Localisation/LocalisedText.h>
#include <ChilliSource/Core/String/StringUtils.h>
#include <ChilliSource/Core/Threading/TaskScheduler.h>
#include <ChilliSource/Video/Base/Subtitles.h>

namespace ChilliSource
{
    namespace Android
    {
    	CS_DEFINE_NAMEDTYPE(VideoPlayer);
        //--------------------------------------------------------------
        //--------------------------------------------------------------
        VideoPlayer::VideoPlayer()
        	: m_currentSubtitleTimeMS(0), m_isPlaying(false)
        {
        }
		//--------------------------------------------------------------
		//--------------------------------------------------------------
		bool VideoPlayer::IsA(Core::InterfaceIDType in_interfaceId) const
		{
			return (in_interfaceId == Video::VideoPlayer::InterfaceID || in_interfaceId == VideoPlayer::InterfaceID);
		}
        //--------------------------------------------------------------
        //--------------------------------------------------------------
        void VideoPlayer::Present(Core::StorageLocation in_storageLocation, const std::string& in_fileName, const VideoCompleteDelegate& in_delegate, bool in_dismissWithTap,
        		const Core::Colour& in_backgroundColour)
        {
        	CS_ASSERT(m_isPlaying == false, "Cannot present a video while one is already playing.");
        	m_isPlaying = true;
        	m_completionDelegate = in_delegate;

        	//calculate the storage location and full filename.
        	bool isPackage = false;
        	std::string fileName;
        	if (in_storageLocation == Core::StorageLocation::k_package)
        	{
        		isPackage = true;
        		fileName = Core::Application::Get()->GetFileSystem()->GetAbsolutePathToFile(Core::StorageLocation::k_package, in_fileName);
        	}
        	else if (in_storageLocation == Core::StorageLocation::k_DLC)
			{
        		if (Core::Application::Get()->GetFileSystem()->DoesFileExistInCachedDLC(in_fileName) == true)
        		{
        			isPackage = false;
        			fileName = Core::Application::Get()->GetFileSystem()->GetAbsolutePathToStorageLocation(Core::StorageLocation::k_DLC) + in_fileName;
        		}
        		else
        		{
        			isPackage = true;
        			fileName = Core::Application::Get()->GetFileSystem()->GetAbsolutePathToFile(Core::StorageLocation::k_package, Core::Application::Get()->GetFileSystem()->GetPackageDLCPath() + in_fileName);
        		}
			}
        	else
        	{
        		isPackage = false;
        		fileName = Core::Application::Get()->GetFileSystem()->GetAbsolutePathToStorageLocation(in_storageLocation) + in_fileName;
        	}

        	//start the video
        	m_javaInterface->Present(isPackage, fileName, in_dismissWithTap, in_backgroundColour, Core::MakeDelegate(this, &VideoPlayer::OnVideoComplete));
        }
        //--------------------------------------------------------------
		//--------------------------------------------------------------
		void VideoPlayer::PresentWithSubtitles(Core::StorageLocation in_storageLocation, const std::string& in_fileName, const Video::SubtitlesCSPtr& in_subtitles, const VideoCompleteDelegate& in_delegate,
                bool in_dismissWithTap, const Core::Colour& in_backgroundColour)
		{
			m_subtitles = in_subtitles;
			m_javaInterface->SetUpdateSubtitlesDelegate(Core::MakeDelegate(this, &VideoPlayer::OnUpdateSubtitles));
			Present(in_storageLocation, in_fileName, in_delegate, in_dismissWithTap, in_backgroundColour);
		}
        //-------------------------------------------------------
        //-------------------------------------------------------
        void VideoPlayer::OnInit()
        {
        	//get the media player java interface or create it if it doesn't yet exist.
			m_javaInterface = JavaInterfaceManager::GetSingletonPtr()->GetJavaInterface<VideoPlayerJavaInterface>();
			if (m_javaInterface == nullptr)
			{
				m_javaInterface = VideoPlayerJavaInterfaceSPtr(new VideoPlayerJavaInterface());
				JavaInterfaceManager::GetSingletonPtr()->AddJavaInterface(m_javaInterface);
			}
        }
        //---------------------------------------------------------------
        //---------------------------------------------------------------
        void VideoPlayer::OnVideoComplete()
        {
        	m_javaInterface->SetUpdateSubtitlesDelegate(nullptr);
        	m_subtitles.reset();
        	m_isPlaying = false;

        	if (m_completionDelegate != nullptr)
        	{
        		m_completionDelegate();
        	}
        }
		//---------------------------------------------------------------
		//---------------------------------------------------------------
		void VideoPlayer::OnUpdateSubtitles()
		{
			//only update if the position in the video has changed.
			f32 position = m_javaInterface->GetTime();
			TimeIntervalMs currentTimeMS = (TimeIntervalMs)(position * 1000.0f);
			if (m_currentSubtitleTimeMS != currentTimeMS)
			{
				m_currentSubtitleTimeMS = currentTimeMS;

				//get the current subtitles
				auto subtitleArray = m_subtitles->GetSubtitlesAtTime(m_currentSubtitleTimeMS);

				//add any new subtitles
				for (auto it = subtitleArray.begin(); it != subtitleArray.end(); ++it)
				{
					auto mapEntry = m_subtitleMap.find(*it);
					if (mapEntry == m_subtitleMap.end())
					{
						const Core::UTF8String& text = (*it)->m_localisedText->GetText((*it)->m_localisedTextId);
						const Video::Subtitles::Style* style = m_subtitles->GetStyleWithName((*it)->m_styleName);
						s64 subtitleID = m_javaInterface->CreateSubtitle(text, style->m_fontName, style->m_fontSize, Rendering::StringFromAlignmentAnchor(style->m_alignment), style->m_bounds.vOrigin.x, style->m_bounds.vOrigin.y, style->m_bounds.vSize.x, style->m_bounds.vSize.y);
						m_javaInterface->SetSubtitleColour(subtitleID, 0.0f, 0.0f, 0.0f, 0.0f);
						m_subtitleMap.insert(std::make_pair(*it, subtitleID));
					}
				}

				//update the current text views
				for (auto it = m_subtitleMap.begin(); it != m_subtitleMap.end(); ++it)
				{
					UpdateSubtitle(it->first, it->second, m_currentSubtitleTimeMS);
				}

				//removes any text views that are no longer needed.
				for (auto it = m_subtitlesToRemove.begin(); it != m_subtitlesToRemove.end(); ++it)
				{
					auto mapEntry = m_subtitleMap.find(*it);
					if (mapEntry != m_subtitleMap.end())
					{
						m_javaInterface->RemoveSubtitle(mapEntry->second);
						m_subtitleMap.erase(mapEntry);
					}
				}
				m_subtitlesToRemove.clear();
			}
		}
		//---------------------------------------------------------------
		//---------------------------------------------------------------
		void VideoPlayer::UpdateSubtitle(const Video::Subtitles::Subtitle* in_subtitle, s64 in_subtitleID, TimeIntervalMs in_timeMS)
		{
			const Video::Subtitles::Style* style = m_subtitles->GetStyleWithName(in_subtitle->m_styleName);

			f32 fade = 0.0f;
			s64 relativeTime = ((s64)in_timeMS) - ((s64)in_subtitle->m_startTimeMS);
			s64 displayTime = ((s64)in_subtitle->m_endTimeMS) - ((s64)in_subtitle->m_startTimeMS);

			//subtitle should not be displayed yet so remove
			if (relativeTime < 0)
			{
				m_subtitlesToRemove.push_back(in_subtitle);
			}

			//fading in
			else if (relativeTime < style->m_fadeTimeMS)
			{
				fade = ((f32)relativeTime) / ((f32)style->m_fadeTimeMS);
			}

			//active
			else if (relativeTime < displayTime - style->m_fadeTimeMS)
			{
				fade = 1.0f;
			}

			//fading out
			else if (relativeTime < displayTime)
			{
				fade = 1.0f - (((f32)relativeTime - (displayTime - style->m_fadeTimeMS)) / ((f32)style->m_fadeTimeMS));
			}

			//should no longer be displayed so remove
			else if (relativeTime >= displayTime)
			{
				m_subtitlesToRemove.push_back(in_subtitle);
			}

			m_javaInterface->SetSubtitleColour(in_subtitleID, style->m_colour.r, style->m_colour.g, style->m_colour.b, fade * style->m_colour.a);
		}
        //-------------------------------------------------------
        //-------------------------------------------------------
        void VideoPlayer::OnDestroy()
        {
        	m_javaInterface.reset();
        }
    }
}
<|endoftext|>


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

#ifndef _RTL_STRING_HXX_
#include <rtl/string.hxx>
#endif
#include <typeinfo>

typedef struct _uno_Any uno_Any;
typedef struct _uno_Mapping uno_Mapping;

// private C50 structures and functions
namespace __Crun
{
    struct static_type_info
    {
        char*       m_pClassName;
        int         m_nSkip1; // must be 0
        void*       m_pMagic; // points to some magic data
        int         m_nMagic[ 4 ];
        int         m_nSkip2[2]; // must be 0
    };
    void* ex_alloc(unsigned);
    void ex_throw( void*, const static_type_info*, void(*)(void*));
    void* ex_get();
    void ex_rethrow_q();
}

namespace __Cimpl
{
    const char* ex_name();
}

extern "C" void _ex_register( void*, int );

namespace CPPU_CURRENT_NAMESPACE
{

//##################################################################################################
//#### exceptions ##################################################################################
//##################################################################################################

void cc50_solaris_intel_raiseException(
    uno_Any * pUnoExc, uno_Mapping * pUno2Cpp );

void cc50_solaris_intel_fillUnoException(
    void*, const char*,
    typelib_TypeDescription * pExcTypeDescr,
    uno_Any*, uno_Mapping * pCpp2Uno );
}

<commit_msg>INTEGRATION: CWS sb34 (1.2.70); FILE MERGED 2005/06/28 15:23:47 sb 1.2.70.1: #b6280765# Adapted Solaris C++--UNO bridge code to be compliant with libCrun (problems with ex_alloc/ex_throw usage, and pointers within RTTI structures).<commit_after>/*************************************************************************
 *
 *  $RCSfile: cc50_solaris_intel.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: kz $ $Date: 2005-07-01 12:15:35 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <cstddef>

#ifndef _RTL_STRING_HXX_
#include <rtl/string.hxx>
#endif
#include <typeinfo>

typedef struct _uno_Any uno_Any;
typedef struct _uno_Mapping uno_Mapping;

// private C50 structures and functions
namespace __Crun
{
    struct static_type_info
    {
        std::ptrdiff_t m_pClassName;
        int         m_nSkip1; // must be 0
        void*       m_pMagic; // points to some magic data
        int         m_nMagic[ 4 ];
        int         m_nSkip2[2]; // must be 0
    };
    void* ex_alloc(unsigned);
    void ex_throw( void*, const static_type_info*, void(*)(void*));
    void* ex_get();
    void ex_rethrow_q();
}

namespace __Cimpl
{
    const char* ex_name();
}

extern "C" void _ex_register( void*, int );

namespace CPPU_CURRENT_NAMESPACE
{

//##################################################################################################
//#### exceptions ##################################################################################
//##################################################################################################

void cc50_solaris_intel_raiseException(
    uno_Any * pUnoExc, uno_Mapping * pUno2Cpp );

void cc50_solaris_intel_fillUnoException(
    void*, const char*,
    uno_Any*, uno_Mapping * pCpp2Uno );
}

<|endoftext|>


<commit_before>/* medViewContainerMulti.cpp ---
 *
 * Author: Julien Wintz
 * Copyright (C) 2008 - Julien Wintz, Inria.
 * Created: Wed Mar 17 11:01:46 2010 (+0100)
 * Version: $Id$
 * Last-Updated: Mon Dec 20 11:26:25 2010 (+0100)
 *           By: Julien Wintz
 *     Update #: 56
 */

/* Commentary:
 *
 */

/* Change log:
 *
 */

#include "medViewContainer_p.h"
#include "medViewContainerMulti.h"
#include "medViewPool.h"

#include <dtkCore/dtkAbstractView.h>

#include <medCore/medAbstractView.h>
#include <medCore/medViewManager.h>

medViewContainerSingle2::~medViewContainerSingle2()
{
}

void medViewContainerSingle2::setView (dtkAbstractView *view)
{
    d->layout->setContentsMargins(0, 0, 0, 0);
    d->layout->addWidget(view->widget(), 0, 0);
    d->view = view;

    // d->pool->appendView (view); // only difference with medViewContainerSingle: do not add the view to the pool
    connect (view, SIGNAL (closing()), this, SLOT (onViewClosing()));
}

bool medViewContainerSingle2::isLeaf(void) const
{
    return true;
}

void medViewContainerSingle2::onViewClosing (void)
{
    if (d->view) {
        d->layout->removeWidget(d->view->widget());
        d->view->widget()->hide();
        disconnect (d->view, SIGNAL (closing()), this, SLOT (onViewClosing()));
        // d->pool->removeView (d->view); // do not remove it from the pool
        d->view = NULL;
    }

    // qDebug() << this << __func__;
    // qDebug() << "isRoot:    " << this->isRoot();
    // qDebug() << "isLeaf:    " << this->isLeaf();
    // qDebug() << "isEmpty:   " << this->isEmpty();
    // qDebug() << "isCurrent: " << this->isCurrent();
}

class medViewContainerMultiPrivate
{
public:
    QList<dtkAbstractView *> views;
};

medViewContainerMulti::medViewContainerMulti (QWidget *parent) : medViewContainer (parent), d2 (new medViewContainerMultiPrivate)
{
}

medViewContainerMulti::~medViewContainerMulti()
{
    medViewContainer::setView(0);

    delete d2;
    d2 = NULL;
}

void medViewContainerMulti::split(int rows, int cols)
{
    Q_UNUSED(rows);
    Q_UNUSED(cols);

    // Don't split a multi view container

    return;
}

dtkAbstractView *medViewContainerMulti::view(void) const
{
    return NULL;
}

QList<dtkAbstractView*> medViewContainerMulti::views (void) const
{
    return d2->views;
}

void medViewContainerMulti::setView(dtkAbstractView *view)
{
    if (!view)
        return;

    if (d2->views.contains (view))
        return;

    QList<QWidget *> content;
    for(int i = 0; i < d->layout->rowCount() ; i++) {
        for(int j = 0; j < d->layout->columnCount() ; j++) {
            if(QLayoutItem *item = d->layout->itemAtPosition(i, j)) {
                content << item->widget();
                d->layout->removeItem(item);
            }
        }
    }

    medViewContainer *container = new medViewContainerSingle2(this);
    container->setAcceptDrops(false);
    container->setView(view);
    content << container;
    this->layout(content);

    medViewContainer::setView (view);

    d2->views << view;

    // d->view = view; // set in medViewContainer::setView(view)

    // d->view->reset();

    if (medAbstractView *medView = dynamic_cast<medAbstractView*> (view))
        d->pool->appendView (medView);

    connect (view, SIGNAL (closing()),         this, SLOT (onViewClosing()));
    connect (view, SIGNAL (fullScreen(bool)),  this, SLOT (onViewFullScreen(bool)));
    connect (view, SIGNAL (changeDaddy(bool)),
             this, SLOT (onDaddyChanged(bool)));

    this->setCurrent( container );
    emit viewAdded (view);
}

void medViewContainerMulti::layout(QList<QWidget *> content)
{
    int row = 0;
    int col = 0, colmax = 0;

    for(int i = 0; i < content.count()-1; i++) {

        if(((col+1)*(row+1)) <= content.count()-1) {

            qreal rratio = qMin(((qreal)this->height()/(qreal)(row+2)), ((qreal)this->width()/(qreal)(col+1)));
            qreal cratio = qMin(((qreal)this->height()/(qreal)(row+1)), ((qreal)this->width()/(qreal)(col+2)));

            if(rratio > cratio) {
                row++;
                col = 0;
            } else {
                col++;
            }

            colmax = qMax(col, colmax);
        }
    }

    int layout_row = 0;
    int layout_col = 0;

    for(int i = 0; i < content.size(); i++) {

        d->layout->addWidget(content.at(i), layout_row, layout_col);

        if(layout_col == colmax) {
            layout_row++;
            layout_col = 0;
        } else {
            layout_col++;
        }
    }
}

void medViewContainerMulti::onViewClosing (void)
{
    if (dtkAbstractView *view =
        dynamic_cast<dtkAbstractView *>(this->sender())) {

        // needed for selecting another container as current afterwards
        QWidget * predContainer   = NULL;
        QWidget * succContainer   = NULL;
        bool      closedItemFound = false;

        QWidget * closedContainer =
            dynamic_cast< QWidget * >( view->widget()->parent() );
        QList<QWidget *> content;
        for (int i = 0; i < d->layout->rowCount(); i++) {
            for (int j = 0; j < d->layout->columnCount(); j++) {
                QLayoutItem * item = d->layout->itemAtPosition(i, j);
                if ( item != NULL ) {
                    QWidget * container = item->widget();
                    if ( container == closedContainer ) {
                        container->hide();
                        closedItemFound = true;
                    }
                    else {
                        content << container; // keep the container in layout
                        container->show(); // in case view was hidden

                        // remember the predecessor resp. successor of
                        // the closed container
                        if ( closedItemFound ) {
                            if ( succContainer == NULL )
                                succContainer = container;
                        }
                        else
                            predContainer = container;
                    }

                    d->layout->removeItem(item);
                }
            }
        }

        disconnect (view, SIGNAL (closing()),
                    this, SLOT (onViewClosing()));
        disconnect (view, SIGNAL (fullScreen(bool)),
                    this, SLOT (onViewFullScreen(bool)));
        disconnect (view, SIGNAL (changeDaddy(bool)),
                    this, SLOT (onDaddyChanged(bool)));

        if (medAbstractView *medView = dynamic_cast<medAbstractView*> (view))
            d->pool->removeView (medView);

        d2->views.removeOne (view);

        emit viewRemoved (view);

        view->close();

        delete closedContainer;

        this->layout (content);

        medViewContainer * current =
            dynamic_cast< medViewContainer * >( succContainer );
        if ( current == NULL )
            current = dynamic_cast< medViewContainer * >( predContainer );
        if ( current == NULL )
            current = this;

        this->setCurrent(current);

        current->onViewFocused( true );

        this->update();

        // qDebug() << this << __func__;
        // qDebug() << "isRoot:    " << this->isRoot();
        // qDebug() << "isLeaf:    " << this->isLeaf();
        // qDebug() << "isEmpty:   " << this->isEmpty();
        // qDebug() << "isCurrent: " << this->isCurrent();
    }
}

void medViewContainerMulti::onViewFullScreen (bool value)
{
  if (dtkAbstractView *view = dynamic_cast<dtkAbstractView *>(this->sender())) {
      if (value) {
          QList<QWidget *> content;
	  for(int i = 0; i < d->layout->rowCount() ; i++) {
            for(int j = 0; j < d->layout->columnCount() ; j++) {
	      if(QLayoutItem *item = d->layout->itemAtPosition(i, j)) {
		if(item->widget()!=view->widget()->parent())
		  item->widget()->hide();
	      }
            }
	  }
      }
      else {
	QList<QWidget *> content;
	for(int i = 0; i < d->layout->rowCount() ; i++) {
	  for(int j = 0; j < d->layout->columnCount() ; j++) {
	    if(QLayoutItem *item = d->layout->itemAtPosition(i, j)) {
	      if(item->widget()!=view->widget()->parent())
		item->widget()->show();
	  }
	  }
	}
      }
  }
}

void medViewContainerMulti::dragEnterEvent(QDragEnterEvent *event)
{
    medViewContainer::dragEnterEvent(event);
}

void medViewContainerMulti::dragMoveEvent(QDragMoveEvent *event)
{
    medViewContainer::dragMoveEvent(event);
}

void medViewContainerMulti::dragLeaveEvent(QDragLeaveEvent *event)
{
    medViewContainer::dragLeaveEvent(event);
}

void medViewContainerMulti::dropEvent(QDropEvent *event)
{
    if(medViewContainerMulti *container = dynamic_cast<medViewContainerMulti *>(this->parentWidget())) {
        this->setCurrent(container);
    }
    else {
        this->setCurrent(this);
    }

    medViewContainer::dropEvent(event);
}

void medViewContainerMulti::focusInEvent(QFocusEvent *event)
{
    Q_UNUSED(event);
}

void medViewContainerMulti::focusOutEvent(QFocusEvent *event)
{
    Q_UNUSED(event);
}
<commit_msg>Correct setCurrent that was going too deep<commit_after>/* medViewContainerMulti.cpp ---
 *
 * Author: Julien Wintz
 * Copyright (C) 2008 - Julien Wintz, Inria.
 * Created: Wed Mar 17 11:01:46 2010 (+0100)
 * Version: $Id$
 * Last-Updated: Mon Dec 20 11:26:25 2010 (+0100)
 *           By: Julien Wintz
 *     Update #: 56
 */

/* Commentary:
 *
 */

/* Change log:
 *
 */

#include "medViewContainer_p.h"
#include "medViewContainerMulti.h"
#include "medViewPool.h"

#include <dtkCore/dtkAbstractView.h>

#include <medCore/medAbstractView.h>
#include <medCore/medViewManager.h>

medViewContainerSingle2::~medViewContainerSingle2()
{
}

void medViewContainerSingle2::setView (dtkAbstractView *view)
{
    d->layout->setContentsMargins(0, 0, 0, 0);
    d->layout->addWidget(view->widget(), 0, 0);
    d->view = view;

    // d->pool->appendView (view); // only difference with medViewContainerSingle: do not add the view to the pool
    connect (view, SIGNAL (closing()), this, SLOT (onViewClosing()));
}

bool medViewContainerSingle2::isLeaf(void) const
{
    return true;
}

void medViewContainerSingle2::onViewClosing (void)
{
    if (d->view) {
        d->layout->removeWidget(d->view->widget());
        d->view->widget()->hide();
        disconnect (d->view, SIGNAL (closing()), this, SLOT (onViewClosing()));
        // d->pool->removeView (d->view); // do not remove it from the pool
        d->view = NULL;
    }

    // qDebug() << this << __func__;
    // qDebug() << "isRoot:    " << this->isRoot();
    // qDebug() << "isLeaf:    " << this->isLeaf();
    // qDebug() << "isEmpty:   " << this->isEmpty();
    // qDebug() << "isCurrent: " << this->isCurrent();
}

class medViewContainerMultiPrivate
{
public:
    QList<dtkAbstractView *> views;
};

medViewContainerMulti::medViewContainerMulti (QWidget *parent) : medViewContainer (parent), d2 (new medViewContainerMultiPrivate)
{
}

medViewContainerMulti::~medViewContainerMulti()
{
    medViewContainer::setView(0);

    delete d2;
    d2 = NULL;
}

void medViewContainerMulti::split(int rows, int cols)
{
    Q_UNUSED(rows);
    Q_UNUSED(cols);

    // Don't split a multi view container

    return;
}

dtkAbstractView *medViewContainerMulti::view(void) const
{
    return NULL;
}

QList<dtkAbstractView*> medViewContainerMulti::views (void) const
{
    return d2->views;
}

void medViewContainerMulti::setView(dtkAbstractView *view)
{
    if (!view)
        return;

    if (d2->views.contains (view))
        return;

    QList<QWidget *> content;
    for(int i = 0; i < d->layout->rowCount() ; i++) {
        for(int j = 0; j < d->layout->columnCount() ; j++) {
            if(QLayoutItem *item = d->layout->itemAtPosition(i, j)) {
                content << item->widget();
                d->layout->removeItem(item);
            }
        }
    }

    medViewContainer *container = new medViewContainerSingle2(this);
    container->setAcceptDrops(false);
    container->setView(view);
    content << container;
    this->layout(content);

    medViewContainer::setView (view);

    d2->views << view;

    // d->view = view; // set in medViewContainer::setView(view)

    // d->view->reset();

    if (medAbstractView *medView = dynamic_cast<medAbstractView*> (view))
        d->pool->appendView (medView);

    connect (view, SIGNAL (closing()),         this, SLOT (onViewClosing()));
    connect (view, SIGNAL (fullScreen(bool)),  this, SLOT (onViewFullScreen(bool)));
    connect (view, SIGNAL (changeDaddy(bool)),
             this, SLOT (onDaddyChanged(bool)));

    this->setCurrent( container );
    emit viewAdded (view);
}

void medViewContainerMulti::layout(QList<QWidget *> content)
{
    int row = 0;
    int col = 0, colmax = 0;

    for(int i = 0; i < content.count()-1; i++) {

        if(((col+1)*(row+1)) <= content.count()-1) {

            qreal rratio = qMin(((qreal)this->height()/(qreal)(row+2)), ((qreal)this->width()/(qreal)(col+1)));
            qreal cratio = qMin(((qreal)this->height()/(qreal)(row+1)), ((qreal)this->width()/(qreal)(col+2)));

            if(rratio > cratio) {
                row++;
                col = 0;
            } else {
                col++;
            }

            colmax = qMax(col, colmax);
        }
    }

    int layout_row = 0;
    int layout_col = 0;

    for(int i = 0; i < content.size(); i++) {

        d->layout->addWidget(content.at(i), layout_row, layout_col);

        if(layout_col == colmax) {
            layout_row++;
            layout_col = 0;
        } else {
            layout_col++;
        }
    }
}

void medViewContainerMulti::onViewClosing (void)
{
    if (dtkAbstractView *view =
        dynamic_cast<dtkAbstractView *>(this->sender())) {

        // needed for selecting another container as current afterwards
        QWidget * predContainer   = NULL;
        QWidget * succContainer   = NULL;
        bool      closedItemFound = false;

        QWidget * closedContainer =
            dynamic_cast< QWidget * >( view->widget()->parent() );
        QList<QWidget *> content;
        for (int i = 0; i < d->layout->rowCount(); i++) {
            for (int j = 0; j < d->layout->columnCount(); j++) {
                QLayoutItem * item = d->layout->itemAtPosition(i, j);
                if ( item != NULL ) {
                    QWidget * container = item->widget();
                    if ( container == closedContainer ) {
                        container->hide();
                        closedItemFound = true;
                    }
                    else {
                        content << container; // keep the container in layout
                        container->show(); // in case view was hidden

                        // remember the predecessor resp. successor of
                        // the closed container
                        if ( closedItemFound ) {
                            if ( succContainer == NULL )
                                succContainer = container;
                        }
                        else
                            predContainer = container;
                    }

                    d->layout->removeItem(item);
                }
            }
        }

        disconnect (view, SIGNAL (closing()),
                    this, SLOT (onViewClosing()));
        disconnect (view, SIGNAL (fullScreen(bool)),
                    this, SLOT (onViewFullScreen(bool)));
        disconnect (view, SIGNAL (changeDaddy(bool)),
                    this, SLOT (onDaddyChanged(bool)));

        if (medAbstractView *medView = dynamic_cast<medAbstractView*> (view))
            d->pool->removeView (medView);

        d2->views.removeOne (view);

        emit viewRemoved (view);

        view->close();

        delete closedContainer;

        this->layout (content);

        medViewContainer * current =
            dynamic_cast< medViewContainer * >( succContainer );
        if ( current == NULL )
            current = dynamic_cast< medViewContainer * >( predContainer );
        if ( current == NULL )
            current = this;

        this->setCurrent(this);

        current->onViewFocused( true );

        this->update();

        // qDebug() << this << __func__;
        // qDebug() << "isRoot:    " << this->isRoot();
        // qDebug() << "isLeaf:    " << this->isLeaf();
        // qDebug() << "isEmpty:   " << this->isEmpty();
        // qDebug() << "isCurrent: " << this->isCurrent();
    }
}

void medViewContainerMulti::onViewFullScreen (bool value)
{
  if (dtkAbstractView *view = dynamic_cast<dtkAbstractView *>(this->sender())) {
      if (value) {
          QList<QWidget *> content;
	  for(int i = 0; i < d->layout->rowCount() ; i++) {
            for(int j = 0; j < d->layout->columnCount() ; j++) {
	      if(QLayoutItem *item = d->layout->itemAtPosition(i, j)) {
		if(item->widget()!=view->widget()->parent())
		  item->widget()->hide();
	      }
            }
	  }
      }
      else {
	QList<QWidget *> content;
	for(int i = 0; i < d->layout->rowCount() ; i++) {
	  for(int j = 0; j < d->layout->columnCount() ; j++) {
	    if(QLayoutItem *item = d->layout->itemAtPosition(i, j)) {
	      if(item->widget()!=view->widget()->parent())
		item->widget()->show();
	  }
	  }
	}
      }
  }
}

void medViewContainerMulti::dragEnterEvent(QDragEnterEvent *event)
{
    medViewContainer::dragEnterEvent(event);
}

void medViewContainerMulti::dragMoveEvent(QDragMoveEvent *event)
{
    medViewContainer::dragMoveEvent(event);
}

void medViewContainerMulti::dragLeaveEvent(QDragLeaveEvent *event)
{
    medViewContainer::dragLeaveEvent(event);
}

void medViewContainerMulti::dropEvent(QDropEvent *event)
{
    if(medViewContainerMulti *container = dynamic_cast<medViewContainerMulti *>(this->parentWidget())) {
        this->setCurrent(container);
    }
    else {
        this->setCurrent(this);
    }

    medViewContainer::dropEvent(event);
}

void medViewContainerMulti::focusInEvent(QFocusEvent *event)
{
    Q_UNUSED(event);
}

void medViewContainerMulti::focusOutEvent(QFocusEvent *event)
{
    Q_UNUSED(event);
}
<|endoftext|>


<commit_before>/****************************************************************************
 *
 *   Copyright (c) 2013-2014 PX4 Development Team. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/
/**
 * @file gpsfailure.cpp
 * Helper class for gpsfailure mode according to the OBC rules
 *
 * @author Thomas Gubler <thomasgubler@gmail.com>
 */

#include "gpsfailure.h"
#include "navigator.h"

#include <systemlib/mavlink_log.h>
#include <lib/ecl/geo/geo.h>
#include <navigator/navigation.h>
#include <uORB/uORB.h>
#include <uORB/topics/mission.h>
#include <uORB/topics/home_position.h>
#include <uORB/topics/vehicle_attitude_setpoint.h>
#include <mathlib/mathlib.h>

using matrix::Eulerf;
using matrix::Quatf;

GpsFailure::GpsFailure(Navigator *navigator) :
	MissionBlock(navigator),
	ModuleParams(navigator)
{
}

void
GpsFailure::on_inactive()
{
	/* reset GPSF state only if setpoint moved */
	if (!_navigator->get_can_loiter_at_sp()) {
		_gpsf_state = GPSF_STATE_NONE;
	}
}

void
GpsFailure::on_activation()
{
	_gpsf_state = GPSF_STATE_NONE;
	_timestamp_activation = hrt_absolute_time();
	advance_gpsf();
	set_gpsf_item();
}

void
GpsFailure::on_active()
{
	switch (_gpsf_state) {
	case GPSF_STATE_LOITER: {
			/* Position controller does not run in this mode:
			 * navigator has to publish an attitude setpoint */
			vehicle_attitude_setpoint_s att_sp = {};
			att_sp.timestamp = hrt_absolute_time();
			att_sp.roll_body = math::radians(_param_nav_gpsf_r.get());
			att_sp.pitch_body = math::radians(_param_nav_gpsf_p.get());
			att_sp.thrust_body[0] = _param_nav_gpsf_tr.get();

			Quatf q(Eulerf(att_sp.roll_body, att_sp.pitch_body, 0.0f));
			q.copyTo(att_sp.q_d);

			if (_navigator->get_vstatus()->is_vtol) {
				_fw_virtual_att_sp_pub.publish(att_sp);

			} else {
				_att_sp_pub.publish(att_sp);

			}

			/* Measure time */
			if ((_param_nav_gpsf_lt.get() > FLT_EPSILON) &&
			    (hrt_elapsed_time(&_timestamp_activation) > _param_nav_gpsf_lt.get() * 1e6f)) {
				/* no recovery, advance the state machine */
				PX4_WARN("GPS not recovered, switching to next failure state");
				advance_gpsf();
			}

			break;
		}

	case GPSF_STATE_TERMINATE:
		set_gpsf_item();
		advance_gpsf();
		break;

	default:
		break;
	}
}

void
GpsFailure::set_gpsf_item()
{
	struct position_setpoint_triplet_s *pos_sp_triplet = _navigator->get_position_setpoint_triplet();

	/* Set pos sp triplet to invalid to stop pos controller */
	pos_sp_triplet->previous.valid = false;
	pos_sp_triplet->current.valid = false;
	pos_sp_triplet->next.valid = false;

	switch (_gpsf_state) {
	case GPSF_STATE_TERMINATE: {
			/* Request flight termination from commander */
			_navigator->get_mission_result()->flight_termination = true;
			_navigator->set_mission_result_updated();
			PX4_WARN("GPS failure: request flight termination");
		}
		break;

	default:
		break;
	}

	_navigator->set_position_setpoint_triplet_updated();
}

void
GpsFailure::advance_gpsf()
{
	switch (_gpsf_state) {
	case GPSF_STATE_NONE:
		_gpsf_state = GPSF_STATE_LOITER;
		mavlink_log_critical(_navigator->get_mavlink_log_pub(), "Global position failure: fixed bank loiter");
		break;

	case GPSF_STATE_LOITER:
		_gpsf_state = GPSF_STATE_TERMINATE;
		mavlink_log_emergency(_navigator->get_mavlink_log_pub(), "no GPS recovery, terminating flight");
		break;

	case GPSF_STATE_TERMINATE:
		PX4_WARN("terminate");
		_gpsf_state = GPSF_STATE_END;
		break;

	default:
		break;
	}
}
<commit_msg>Change wording in GPS failure handling This matches better the different platforms that are using this functionality.<commit_after>/****************************************************************************
 *
 *   Copyright (c) 2013-2014 PX4 Development Team. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/
/**
 * @file gpsfailure.cpp
 * Helper class for gpsfailure mode according to the OBC rules
 *
 * @author Thomas Gubler <thomasgubler@gmail.com>
 */

#include "gpsfailure.h"
#include "navigator.h"

#include <systemlib/mavlink_log.h>
#include <lib/ecl/geo/geo.h>
#include <navigator/navigation.h>
#include <uORB/uORB.h>
#include <uORB/topics/mission.h>
#include <uORB/topics/home_position.h>
#include <uORB/topics/vehicle_attitude_setpoint.h>
#include <mathlib/mathlib.h>

using matrix::Eulerf;
using matrix::Quatf;

GpsFailure::GpsFailure(Navigator *navigator) :
	MissionBlock(navigator),
	ModuleParams(navigator)
{
}

void
GpsFailure::on_inactive()
{
	/* reset GPSF state only if setpoint moved */
	if (!_navigator->get_can_loiter_at_sp()) {
		_gpsf_state = GPSF_STATE_NONE;
	}
}

void
GpsFailure::on_activation()
{
	_gpsf_state = GPSF_STATE_NONE;
	_timestamp_activation = hrt_absolute_time();
	advance_gpsf();
	set_gpsf_item();
}

void
GpsFailure::on_active()
{
	switch (_gpsf_state) {
	case GPSF_STATE_LOITER: {
			/* Position controller does not run in this mode:
			 * navigator has to publish an attitude setpoint */
			vehicle_attitude_setpoint_s att_sp = {};
			att_sp.timestamp = hrt_absolute_time();
			att_sp.roll_body = math::radians(_param_nav_gpsf_r.get());
			att_sp.pitch_body = math::radians(_param_nav_gpsf_p.get());
			att_sp.thrust_body[0] = _param_nav_gpsf_tr.get();

			Quatf q(Eulerf(att_sp.roll_body, att_sp.pitch_body, 0.0f));
			q.copyTo(att_sp.q_d);

			if (_navigator->get_vstatus()->is_vtol) {
				_fw_virtual_att_sp_pub.publish(att_sp);

			} else {
				_att_sp_pub.publish(att_sp);

			}

			/* Measure time */
			if ((_param_nav_gpsf_lt.get() > FLT_EPSILON) &&
			    (hrt_elapsed_time(&_timestamp_activation) > _param_nav_gpsf_lt.get() * 1e6f)) {
				/* no recovery, advance the state machine */
				PX4_WARN("GPS not recovered, switching to next failure state");
				advance_gpsf();
			}

			break;
		}

	case GPSF_STATE_TERMINATE:
		set_gpsf_item();
		advance_gpsf();
		break;

	default:
		break;
	}
}

void
GpsFailure::set_gpsf_item()
{
	struct position_setpoint_triplet_s *pos_sp_triplet = _navigator->get_position_setpoint_triplet();

	/* Set pos sp triplet to invalid to stop pos controller */
	pos_sp_triplet->previous.valid = false;
	pos_sp_triplet->current.valid = false;
	pos_sp_triplet->next.valid = false;

	switch (_gpsf_state) {
	case GPSF_STATE_TERMINATE: {
			/* Request flight termination from commander */
			_navigator->get_mission_result()->flight_termination = true;
			_navigator->set_mission_result_updated();
			PX4_WARN("GPS failure: request flight termination");
		}
		break;

	default:
		break;
	}

	_navigator->set_position_setpoint_triplet_updated();
}

void
GpsFailure::advance_gpsf()
{
	switch (_gpsf_state) {
	case GPSF_STATE_NONE:
		_gpsf_state = GPSF_STATE_LOITER;
		mavlink_log_critical(_navigator->get_mavlink_log_pub(), "Global position failure: loitering");
		break;

	case GPSF_STATE_LOITER:
		_gpsf_state = GPSF_STATE_TERMINATE;
		mavlink_log_emergency(_navigator->get_mavlink_log_pub(), "no GPS recovery, terminating flight");
		break;

	case GPSF_STATE_TERMINATE:
		PX4_WARN("terminate");
		_gpsf_state = GPSF_STATE_END;
		break;

	default:
		break;
	}
}
<|endoftext|>