<commit_before>#ifndef STAN_MATH_OPENCL_KERNEL_GENERATOR_LOAD_HPP
#define STAN_MATH_OPENCL_KERNEL_GENERATOR_LOAD_HPP
#ifdef STAN_OPENCL

#include <stan/math/opencl/matrix_cl.hpp>
#include <stan/math/opencl/matrix_cl_view.hpp>
#include <stan/math/opencl/kernel_generator/type_str.hpp>
#include <stan/math/opencl/kernel_generator/name_generator.hpp>
#include <stan/math/opencl/kernel_generator/operation_cl.hpp>
#include <stan/math/opencl/kernel_generator/operation_cl_lhs.hpp>
#include <type_traits>
#include <string>
#include <utility>
#include <set>

namespace stan {
namespace math {

/**
 * Represents an access to a \c matrix_cl in kernel generator expressions
 * @tparam T \c matrix_cl
 */
template <typename T>
class load_
    : public operation_cl_lhs<load_<T>,
                              typename std::remove_reference_t<T>::type> {
 protected:
  T a_;

 public:
  using Scalar = typename std::remove_reference_t<T>::type;
  using base = operation_cl<load_<T>, Scalar>;
  using base::var_name;
  static_assert(std::is_base_of<matrix_cl<Scalar>,
                                typename std::remove_reference_t<T>>::value,
                "load_: argument a must be a matrix_cl<T>!");
  static_assert(
      std::is_arithmetic<Scalar>::value,
      "load_: T in \"matrix_cl<T> a\" argument must be an arithmetic type!");

  /**
   * Constructor
   * @param a \c matrix_cl
   */
  explicit load_(T&& a) : a_(std::forward<T>(a)) {}

  /**
   * Creates a deep copy of this expression.
   * @return copy of \c *this
   */
  inline load_<T&> deep_copy() const & { return load_<T&>(a_); }
  inline load_<T> deep_copy() && { return load_<T>(std::forward<T>(a_)); }

  /**
   * generates kernel code for this expression.
   * @param i row index variable name
   * @param j column index variable name
   * @return part of kernel with code for this expression
   */
  inline kernel_parts generate(const std::string& i,
                               const std::string& j) const {
    kernel_parts res{};
    std::string type = type_str<Scalar>();
    res.body = type + " " + var_name + " = 0;"
               " if (!((!contains_nonzero(" + var_name + "_view, LOWER) && "
               + j + " < " + i + ") || (!contains_nonzero(" + var_name +
               "_view, UPPER) && " + j + " > " + i + "))) {"
               + var_name + " = " + var_name + "_global[" + i + " + " +
               var_name + "_rows * " + j + "];}\n";
    res.args = "__global " + type + "* " + var_name + "_global, int " + var_name
               + "_rows, int " + var_name + "_view, ";
    return res;
  }

  /**
   * generates kernel code for this expression if it appears on the left hand
   * side of an assignment.
   * @param i row index variable name
   * @param j column index variable name
   * @return part of kernel with code for this expressions
   */
  inline kernel_parts generate_lhs(const std::string& i,
                                   const std::string& j) const {
    kernel_parts res;
    std::string type = type_str<Scalar>();
    res.args = "__global " + type + "* " + var_name + "_global, int " + var_name
               + "_rows, int " + var_name + "_view, ";
    res.body
        = var_name + "_global[" + i + " + " + var_name + "_rows * " + j + "]";
    return res;
  }

  /**
   * Sets kernel arguments for this expression.
   * @param[in,out] generated set of expressions that already set their kernel
   * arguments
   * @param kernel kernel to set arguments on
   * @param[in,out] arg_num consecutive number of the first argument to set.
   * This is incremented for each argument set by this function.
   */
  inline void set_args(std::set<const operation_cl_base*>& generated,
                       cl::Kernel& kernel, int& arg_num) const {
    if (generated.count(this) == 0) {
      generated.insert(this);
      kernel.setArg(arg_num++, a_.buffer());
      kernel.setArg(arg_num++, a_.rows());
      kernel.setArg(arg_num++, a_.view());
    }
  }

  /**
   * Adds read event to the matrix used in this expression.
   * @param e the event to add
   */
  inline void add_read_event(cl::Event& e) const { a_.add_read_event(e); }

  /**
   * Adds write event to the matrix used in this expression.
   * @param e the event to add
   */
  inline void add_write_event(cl::Event& e) const { a_.add_write_event(e); }

  /**
   * Number of rows of a matrix that would be the result of evaluating this
   * expression.
   * @return number of rows
   */
  inline int rows() const { return a_.rows(); }

  /**
   * Number of columns of a matrix that would be the result of evaluating this
   * expression.
   * @return number of columns
   */
  inline int cols() const { return a_.cols(); }

  /**
   * View of a matrix that would be the result of evaluating this expression.
   * @return view
   */
  inline matrix_cl_view view() const { return a_.view(); }

  /**
   * Sets view of the matrix depending on which part is written.
   * @param bottom_diagonal Index of the top sub- or super- diagonal written
   * with nonzero elements.
   * @param top_diagonal Index of the top sub- or super- diagonal written with
   * nonzero elements.
   * @param bottom_zero_diagonal Index of the top sub- or super- diagonal
   * written with zeros if it ie more extreme than \c bottom_diagonal. Otherwise
   * it should be set to equal value as \c bottom_diagonal.
   * @param top_zero_diagonal Index of the top sub- or super- diagonal written
   * with zeros if it ie more extreme than \c top_diagonal. Otherwise it should
   * be set to equal value as \c top_diagonal.
   */
  inline void set_view(int bottom_diagonal, int top_diagonal,
                       int bottom_zero_diagonal, int top_zero_diagonal) const {
    if (bottom_diagonal < 0) {
      a_.view(either(a_.view(), matrix_cl_view::Lower));
    } else if (bottom_zero_diagonal <= 1 - a_.rows()) {
      a_.view(both(a_.view(), matrix_cl_view::Upper));
    }
    if (top_diagonal > 0) {
      a_.view(either(a_.view(), matrix_cl_view::Upper));
    } else if (top_zero_diagonal >= a_.cols() - 1) {
      a_.view(both(a_.view(), matrix_cl_view::Lower));
    }
  }

  /**
   * Determine index of bottom diagonal written.
   * @return number of columns
   */
  inline int bottom_diagonal() const {
    return contains_nonzero(a_.view(), matrix_cl_view::Lower) ? -a_.rows() + 1
                                                              : 0;
  }

  /**
   * Determine index of top diagonal written.
   * @return number of columns
   */
  inline int top_diagonal() const {
    return contains_nonzero(a_.view(), matrix_cl_view::Upper) ? a_.cols() - 1
                                                              : 0;
  }

  /**
   * Evaluates the expression. \c load_ returns a const reference to stored
   * matrix_cl.
   * @return Result of the expression.
   */
  const T& eval() const { return a_; }

  /**
   * If needed resizes underlying matrix to desired number of rows and cols.
   * @param rows desired number of rows
   * @param cols desired number of columns
   */
  inline void check_assign_dimensions(int rows, int cols) const {
    if (a_.rows() != rows || a_.cols() != cols) {
      a_ = matrix_cl<Scalar>(rows, cols);
    }
  }
};

}  // namespace math
}  // namespace stan

#endif
#endif
<commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0 (tags/google/stable/2017-11-14)<commit_after>#ifndef STAN_MATH_OPENCL_KERNEL_GENERATOR_LOAD_HPP
#define STAN_MATH_OPENCL_KERNEL_GENERATOR_LOAD_HPP
#ifdef STAN_OPENCL

#include <stan/math/opencl/matrix_cl.hpp>
#include <stan/math/opencl/matrix_cl_view.hpp>
#include <stan/math/opencl/kernel_generator/type_str.hpp>
#include <stan/math/opencl/kernel_generator/name_generator.hpp>
#include <stan/math/opencl/kernel_generator/operation_cl.hpp>
#include <stan/math/opencl/kernel_generator/operation_cl_lhs.hpp>
#include <type_traits>
#include <string>
#include <utility>
#include <set>

namespace stan {
namespace math {

/**
 * Represents an access to a \c matrix_cl in kernel generator expressions
 * @tparam T \c matrix_cl
 */
template <typename T>
class load_
    : public operation_cl_lhs<load_<T>,
                              typename std::remove_reference_t<T>::type> {
 protected:
  T a_;

 public:
  using Scalar = typename std::remove_reference_t<T>::type;
  using base = operation_cl<load_<T>, Scalar>;
  using base::var_name;
  static_assert(std::is_base_of<matrix_cl<Scalar>,
                                typename std::remove_reference_t<T>>::value,
                "load_: argument a must be a matrix_cl<T>!");
  static_assert(
      std::is_arithmetic<Scalar>::value,
      "load_: T in \"matrix_cl<T> a\" argument must be an arithmetic type!");

  /**
   * Constructor
   * @param a \c matrix_cl
   */
  explicit load_(T&& a) : a_(std::forward<T>(a)) {}

  /**
   * Creates a deep copy of this expression.
   * @return copy of \c *this
   */
  inline load_<T&> deep_copy() const& { return load_<T&>(a_); }
  inline load_<T> deep_copy() && { return load_<T>(std::forward<T>(a_)); }

  /**
   * generates kernel code for this expression.
   * @param i row index variable name
   * @param j column index variable name
   * @return part of kernel with code for this expression
   */
  inline kernel_parts generate(const std::string& i,
                               const std::string& j) const {
    kernel_parts res{};
    std::string type = type_str<Scalar>();
    res.body = type + " " + var_name + " = 0;"
               " if (!((!contains_nonzero(" + var_name + "_view, LOWER) && "
               + j + " < " + i + ") || (!contains_nonzero(" + var_name +
               "_view, UPPER) && " + j + " > " + i + "))) {"
               + var_name + " = " + var_name + "_global[" + i + " + " +
               var_name + "_rows * " + j + "];}\n";
    res.args = "__global " + type + "* " + var_name + "_global, int " + var_name
               + "_rows, int " + var_name + "_view, ";
    return res;
  }

  /**
   * generates kernel code for this expression if it appears on the left hand
   * side of an assignment.
   * @param i row index variable name
   * @param j column index variable name
   * @return part of kernel with code for this expressions
   */
  inline kernel_parts generate_lhs(const std::string& i,
                                   const std::string& j) const {
    kernel_parts res;
    std::string type = type_str<Scalar>();
    res.args = "__global " + type + "* " + var_name + "_global, int " + var_name
               + "_rows, int " + var_name + "_view, ";
    res.body
        = var_name + "_global[" + i + " + " + var_name + "_rows * " + j + "]";
    return res;
  }

  /**
   * Sets kernel arguments for this expression.
   * @param[in,out] generated set of expressions that already set their kernel
   * arguments
   * @param kernel kernel to set arguments on
   * @param[in,out] arg_num consecutive number of the first argument to set.
   * This is incremented for each argument set by this function.
   */
  inline void set_args(std::set<const operation_cl_base*>& generated,
                       cl::Kernel& kernel, int& arg_num) const {
    if (generated.count(this) == 0) {
      generated.insert(this);
      kernel.setArg(arg_num++, a_.buffer());
      kernel.setArg(arg_num++, a_.rows());
      kernel.setArg(arg_num++, a_.view());
    }
  }

  /**
   * Adds read event to the matrix used in this expression.
   * @param e the event to add
   */
  inline void add_read_event(cl::Event& e) const { a_.add_read_event(e); }

  /**
   * Adds write event to the matrix used in this expression.
   * @param e the event to add
   */
  inline void add_write_event(cl::Event& e) const { a_.add_write_event(e); }

  /**
   * Number of rows of a matrix that would be the result of evaluating this
   * expression.
   * @return number of rows
   */
  inline int rows() const { return a_.rows(); }

  /**
   * Number of columns of a matrix that would be the result of evaluating this
   * expression.
   * @return number of columns
   */
  inline int cols() const { return a_.cols(); }

  /**
   * View of a matrix that would be the result of evaluating this expression.
   * @return view
   */
  inline matrix_cl_view view() const { return a_.view(); }

  /**
   * Sets view of the matrix depending on which part is written.
   * @param bottom_diagonal Index of the top sub- or super- diagonal written
   * with nonzero elements.
   * @param top_diagonal Index of the top sub- or super- diagonal written with
   * nonzero elements.
   * @param bottom_zero_diagonal Index of the top sub- or super- diagonal
   * written with zeros if it ie more extreme than \c bottom_diagonal. Otherwise
   * it should be set to equal value as \c bottom_diagonal.
   * @param top_zero_diagonal Index of the top sub- or super- diagonal written
   * with zeros if it ie more extreme than \c top_diagonal. Otherwise it should
   * be set to equal value as \c top_diagonal.
   */
  inline void set_view(int bottom_diagonal, int top_diagonal,
                       int bottom_zero_diagonal, int top_zero_diagonal) const {
    if (bottom_diagonal < 0) {
      a_.view(either(a_.view(), matrix_cl_view::Lower));
    } else if (bottom_zero_diagonal <= 1 - a_.rows()) {
      a_.view(both(a_.view(), matrix_cl_view::Upper));
    }
    if (top_diagonal > 0) {
      a_.view(either(a_.view(), matrix_cl_view::Upper));
    } else if (top_zero_diagonal >= a_.cols() - 1) {
      a_.view(both(a_.view(), matrix_cl_view::Lower));
    }
  }

  /**
   * Determine index of bottom diagonal written.
   * @return number of columns
   */
  inline int bottom_diagonal() const {
    return contains_nonzero(a_.view(), matrix_cl_view::Lower) ? -a_.rows() + 1
                                                              : 0;
  }

  /**
   * Determine index of top diagonal written.
   * @return number of columns
   */
  inline int top_diagonal() const {
    return contains_nonzero(a_.view(), matrix_cl_view::Upper) ? a_.cols() - 1
                                                              : 0;
  }

  /**
   * Evaluates the expression. \c load_ returns a const reference to stored
   * matrix_cl.
   * @return Result of the expression.
   */
  const T& eval() const { return a_; }

  /**
   * If needed resizes underlying matrix to desired number of rows and cols.
   * @param rows desired number of rows
   * @param cols desired number of columns
   */
  inline void check_assign_dimensions(int rows, int cols) const {
    if (a_.rows() != rows || a_.cols() != cols) {
      a_ = matrix_cl<Scalar>(rows, cols);
    }
  }
};

}  // namespace math
}  // namespace stan

#endif
#endif
<|endoftext|>


<commit_before>#ifndef STAN_MATH_PRIM_META_AS_ARRAY_OR_SCALAR_HPP
#define STAN_MATH_PRIM_META_AS_ARRAY_OR_SCALAR_HPP

#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <vector>

namespace stan {
namespace math {

/** \ingroup type_trait
 * Returns specified input value.
 *
 * @tparam T Type of element.
 * @param v Specified value.
 * @return Same value.
 */
template <typename T>
inline const T& as_array_or_scalar(const T& v) {
  return v;
}

/** \ingroup type_trait
 * Converts a matrix type to an array.
 *
 * @tparam T Type of \c Eigen \c Matrix or expression
 * @param v Specified \c Eigen \c Matrix or expression.
 * @return Matrix converted to an array.
 */
template <typename T, typename = require_eigen_t<T>>
inline auto as_array_or_scalar(const T& v) {
  return v.array();
}

/** \ingroup type_trait
 * Converts a std::vector type to an array.
 *
 * @tparam T Type of scalar element.
 * @param v Specified vector.
 * @return Matrix converted to an array.
 */
template <typename T>
inline Eigen::Map<const Eigen::Array<T, Eigen::Dynamic, 1>> as_array_or_scalar(
    const std::vector<T>& v) {
  return Eigen::Map<const Eigen::Array<T, Eigen::Dynamic, 1>>(v.data(),
                                                              v.size());
}

}  // namespace math
}  // namespace stan

#endif
<commit_msg>add other missing include<commit_after>#ifndef STAN_MATH_PRIM_META_AS_ARRAY_OR_SCALAR_HPP
#define STAN_MATH_PRIM_META_AS_ARRAY_OR_SCALAR_HPP

#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/math/prim/meta/require_generics.hpp>
#include <vector>

namespace stan {
namespace math {

/** \ingroup type_trait
 * Returns specified input value.
 *
 * @tparam T Type of element.
 * @param v Specified value.
 * @return Same value.
 */
template <typename T>
inline const T& as_array_or_scalar(const T& v) {
  return v;
}

/** \ingroup type_trait
 * Converts a matrix type to an array.
 *
 * @tparam T Type of \c Eigen \c Matrix or expression
 * @param v Specified \c Eigen \c Matrix or expression.
 * @return Matrix converted to an array.
 */
template <typename T, typename = require_eigen_t<T>>
inline auto as_array_or_scalar(const T& v) {
  return v.array();
}

/** \ingroup type_trait
 * Converts a std::vector type to an array.
 *
 * @tparam T Type of scalar element.
 * @param v Specified vector.
 * @return Matrix converted to an array.
 */
template <typename T>
inline Eigen::Map<const Eigen::Array<T, Eigen::Dynamic, 1>> as_array_or_scalar(
    const std::vector<T>& v) {
  return Eigen::Map<const Eigen::Array<T, Eigen::Dynamic, 1>>(v.data(),
                                                              v.size());
}

}  // namespace math
}  // namespace stan

#endif
<|endoftext|>


<commit_before>#include "MirandaContact.h"

#include <exception>
#include <sstream>

#include <m_contacts.h>
#include <m_core.h>

std::wstring MirandaContact::GetUID(HANDLE contactHandle)
{
	auto contactInfo = CONTACTINFO();
	contactInfo.hContact = contactHandle;
	contactInfo.dwFlag = CNF_UNIQUEID | CNF_UNICODE;

	if (CallService(MS_CONTACT_GETCONTACTINFO, 0, reinterpret_cast<LPARAM>(&contactInfo)))
	{
		throw std::exception("Contact not found");
	}

	// There are unique identifiers of different types, so:
	auto stream = std::wostringstream();
	switch (contactInfo.type)
	{
	case CNFT_BYTE:
		stream << contactInfo.bVal;
		break;
	case CNFT_WORD:
		stream << contactInfo.wVal;
		break;
	case CNFT_DWORD:
		stream << contactInfo.dVal;
		break;
	case CNFT_ASCIIZ:
		stream << contactInfo.pszVal;
	default:
		throw std::exception("Unknown contact info value type");
	}

	return stream.str();
}<commit_msg>Fix bug with string user identifiers.<commit_after>#include "MirandaContact.h"

#include <exception>
#include <sstream>

#include <m_contacts.h>
#include <m_core.h>

std::wstring MirandaContact::GetUID(HANDLE contactHandle)
{
	auto contactInfo = CONTACTINFO();
	contactInfo.hContact = contactHandle;
	contactInfo.dwFlag = CNF_UNIQUEID | CNF_UNICODE;

	if (CallService(MS_CONTACT_GETCONTACTINFO, 0, reinterpret_cast<LPARAM>(&contactInfo)))
	{
		throw std::exception("Contact not found");
	}

	// There are unique identifiers of different types, so:
	auto stream = std::wostringstream();
	switch (contactInfo.type)
	{
	case CNFT_BYTE:
		stream << contactInfo.bVal;
		break;
	case CNFT_WORD:
		stream << contactInfo.wVal;
		break;
	case CNFT_DWORD:
		stream << contactInfo.dVal;
		break;
	case CNFT_ASCIIZ:
		stream << contactInfo.pszVal;
		break;
	default:
		throw std::exception("Unknown contact info value type");
	}

	return stream.str();
}<|endoftext|>


<commit_before>//==============================================================================
// Single cell view information graphs widget
//==============================================================================

#include "cellmlfileruntime.h"
#include "propertyeditorwidget.h"
#include "singlecellviewgraphpanelplotwidget.h"
#include "singlecellviewinformationgraphswidget.h"

//==============================================================================

#include <QFileInfo>
#include <QHeaderView>
#include <QLabel>
#include <QSettings>

//==============================================================================

namespace OpenCOR {
namespace SingleCellView {

//==============================================================================

SingleCellViewInformationGraphsWidget::SingleCellViewInformationGraphsWidget(QWidget *pParent) :
    QStackedWidget(pParent),
    mPropertyEditors(QMap<SingleCellViewGraphPanelWidget *, Core::PropertyEditorWidget *>()),
    mColumnWidths(QList<int>()),
    mPropertyEditor(0),
    mFileName(QString()),
    mFileNames(QStringList()),
    mRuntimes(QMap<QString, CellMLSupport::CellmlFileRuntime *>()),
    mSimulations(QMap<QString, SingleCellViewSimulation *>())
{
    // Create a widget that will be shown whenever there are no graphs
    // associated with the current plotting area

    mNoGraphsMessageWidget = new QLabel(pParent);

    mNoGraphsMessageWidget->setAlignment(Qt::AlignCenter);
    mNoGraphsMessageWidget->setAutoFillBackground(true);
    mNoGraphsMessageWidget->setBackgroundRole(QPalette::Base);
    mNoGraphsMessageWidget->setWordWrap(true);

    addWidget(mNoGraphsMessageWidget);

    // Determine the default width of each column of our property editors

    Core::PropertyEditorWidget *tempPropertyEditor = new Core::PropertyEditorWidget(this);

    for (int i = 0, iMax = tempPropertyEditor->header()->count(); i < iMax; ++i)
        mColumnWidths.append(tempPropertyEditor->columnWidth(i));

    delete tempPropertyEditor;
}

//==============================================================================

void SingleCellViewInformationGraphsWidget::retranslateUi()
{
    // Retranslate our no graphs message widget

    mNoGraphsMessageWidget->setText(tr("There are no graphs..."));

    // Retranslate all our property editors

    foreach (Core::PropertyEditorWidget *propertyEditor, mPropertyEditors)
        propertyEditor->retranslateUi();

    // Retranslate the information about our graphs properties

    updateGraphsInfo();
}

//==============================================================================

static const QString SettingsColumnWidth = "ColumnWidth%1";

//==============================================================================

void SingleCellViewInformationGraphsWidget::loadSettings(QSettings *pSettings)
{
    // Retrieve the width of each column of our property editors

    for (int i = 0, iMax = mColumnWidths.size(); i < iMax; ++i)
        mColumnWidths[i] = pSettings->value(SettingsColumnWidth.arg(i),
                                            mColumnWidths.at(i)).toInt();

}

//==============================================================================

void SingleCellViewInformationGraphsWidget::saveSettings(QSettings *pSettings) const
{
    // Keep track of the width of each column of our current property editor

    for (int i = 0, iMax = mColumnWidths.size(); i < iMax; ++i)
        pSettings->setValue(SettingsColumnWidth.arg(i), mColumnWidths.at(i));
}

//==============================================================================

void SingleCellViewInformationGraphsWidget::initialize(const QString &pFileName,
                                                       CellMLSupport::CellmlFileRuntime *pRuntime,
                                                       SingleCellViewSimulation *pSimulation)
{
    // Keep track of the file name, runtime and simulation

    mFileName = pFileName;

    mRuntimes.insert(pFileName, pRuntime);
    mSimulations.insert(pFileName, pSimulation);

    // Update the information about our graphs properties

    updateGraphsInfo();
}

//==============================================================================

void SingleCellViewInformationGraphsWidget::finalize(const QString &pFileName)
{
    // Remove track of the file name, runtime and simulation

    mFileNames.removeOne(pFileName);

    mRuntimes.remove(pFileName);
    mSimulations.remove(pFileName);

    // Update the information about our graphs properties

    updateGraphsInfo();
}

//==============================================================================

void SingleCellViewInformationGraphsWidget::fileOpened(const QString &pFileName)
{
    // Keep track of the file name

    if (!mFileNames.contains(pFileName))
        mFileNames << pFileName;

    mFileNames.sort();

    // Update the information about our graphs properties

    updateGraphsInfo();
}

//==============================================================================

void SingleCellViewInformationGraphsWidget::fileRenamed(const QString &pOldFileName,
                                                        const QString &pNewFileName)
{
    // Replace the old file name with the new one in our various trackers

    mFileName = pNewFileName;

    mFileNames << pNewFileName;

    mRuntimes.insert(pNewFileName, mRuntimes.value(pOldFileName));
    mSimulations.insert(pNewFileName, mSimulations.value(pOldFileName));

    finalize(pOldFileName);
}

//==============================================================================

void SingleCellViewInformationGraphsWidget::initialize(SingleCellViewGraphPanelWidget *pGraphPanel)
{
    // Retrieve the property editor for the given file name or create one, if
    // none exists

    mPropertyEditor = mPropertyEditors.value(pGraphPanel);

    if (!mPropertyEditor) {
        // No property editor exists for the given graph panel, so create one

        mPropertyEditor = new Core::PropertyEditorWidget(false, false, this);

        // Initialise our property editor's columns' width

        for (int i = 0, iMax = mColumnWidths.size(); i < iMax; ++i)
            mPropertyEditor->setColumnWidth(i, mColumnWidths.at(i));

        // Keep track of changes to columns' width

        connect(mPropertyEditor->header(), SIGNAL(sectionResized(int, int, int)),
                this, SLOT(propertyEditorSectionResized(const int &, const int &, const int &)));

        // Keep track of changes to list properties

        connect(mPropertyEditor, SIGNAL(listPropertyChanged(Core::Property *, const QString &)),
                this, SLOT(modelChanged(Core::Property *, const QString &)));

        // Keep track of when the user changes a property value

        connect(mPropertyEditor, SIGNAL(propertyChanged(Core::Property *)),
                this, SLOT(propertyChanged(Core::Property *)));

        // Add our new property editor to ourselves

        addWidget(mPropertyEditor);

        // Keep track of our new property editor

        mPropertyEditors.insert(pGraphPanel, mPropertyEditor);
    }

    // Set our retrieved property editor as our current widget, but only if it
    // isn't empty

    if (mPropertyEditor->properties().count())
        setCurrentWidget(mPropertyEditor);
    else
        setCurrentWidget(mNoGraphsMessageWidget);

    // Update the information about our graphs properties
    // Note: this is in case the user changed the locale and then switched to a
    //       different graph panel...

    updateGraphsInfo();
}

//==============================================================================

void SingleCellViewInformationGraphsWidget::finalize(SingleCellViewGraphPanelWidget *pGraphPanel)
{
    // Remove track of our property editor

    mPropertyEditors.remove(pGraphPanel);
}

//==============================================================================

void SingleCellViewInformationGraphsWidget::addGraph(SingleCellViewGraphPanelPlotGraph *pGraph)
{
    // Make sure that we have a property editor

    if (!mPropertyEditor)
        return;

    // Prevent ourselves from being updated (to avoid any flickering)

    mPropertyEditor->setUpdatesEnabled(false);

    // Create a section for our newly added graph

    Core::Property *sectionProperty = mPropertyEditor->addSectionProperty();

    sectionProperty->setCheckable(true);
    sectionProperty->setChecked(true);

    // Create some properties for our graph

    mPropertyEditor->addListProperty(sectionProperty);
    Core::Property *xProperty = mPropertyEditor->addStringProperty(pGraph->parameterX()->fullyFormattedName(), sectionProperty);
    Core::Property *yProperty = mPropertyEditor->addStringProperty(pGraph->parameterY()->fullyFormattedName(), sectionProperty);

    xProperty->setEditable(true);
    yProperty->setEditable(true);

    // Update the information about our new graph

    updateGraphsInfo(sectionProperty);

    // Allow ourselves to be updated again

    mPropertyEditor->setUpdatesEnabled(true);

    // Make sure that our property editor is our current widget

    setCurrentWidget(mPropertyEditor);
}

//==============================================================================

void SingleCellViewInformationGraphsWidget::removeGraph(SingleCellViewGraphPanelPlotGraph *pGraph)
{
//---GRY--- TO BE DONE...
Q_UNUSED(pGraph);
    // Make sure that we have a property editor

    if (!mPropertyEditor)
        return;

    // Prevent ourselves from being updated (to avoid any flickering)

    mPropertyEditor->setUpdatesEnabled(false);

    // Allow ourselves to be updated again

    mPropertyEditor->setUpdatesEnabled(true);

    // Hide our property editor if it doesn't contain any graph anymore

    if (!mPropertyEditor->properties().count())
        setCurrentWidget(mNoGraphsMessageWidget);
}

//==============================================================================

void SingleCellViewInformationGraphsWidget::finishPropertyEditing()
{
    // Make sure that we have a property editor

    if (!mPropertyEditor)
        return;

    // Finish the editing of our property editor

    mPropertyEditor->finishPropertyEditing();
}

//==============================================================================

void SingleCellViewInformationGraphsWidget::propertyEditorSectionResized(const int &pLogicalIndex,
                                                                             const int &pOldSize,
                                                                             const int &pNewSize)
{
    Q_UNUSED(pOldSize);

    // Prevent all our property editors from responding to an updating of their
    // columns' width

    foreach (Core::PropertyEditorWidget *propertyEditor, mPropertyEditors)
        disconnect(propertyEditor->header(), SIGNAL(sectionResized(int, int, int)),
                   this, SLOT(propertyEditorSectionResized(const int &, const int &, const int &)));

    // Update the column width of all our property editors

    foreach (Core::PropertyEditorWidget *propertyEditor, mPropertyEditors)
        propertyEditor->header()->resizeSection(pLogicalIndex, pNewSize);

    // Keep track of the new column width

    mColumnWidths[pLogicalIndex] = pNewSize;

    // Re-allow all our property editors to respond to an updating of their
    // columns' width

    foreach (Core::PropertyEditorWidget *propertyEditor, mPropertyEditors)
        connect(propertyEditor->header(), SIGNAL(sectionResized(int, int, int)),
                this, SLOT(propertyEditorSectionResized(const int &, const int &, const int &)));
}

//==============================================================================

bool SingleCellViewInformationGraphsWidget::checkParameter(const QString &pFileName,
                                                           Core::Property *pProperty) const
{
    bool res = false;

    // Retrieve the runtime associated with the given file name

    CellMLSupport::CellmlFileRuntime *runtime = mRuntimes.value(pFileName);

    // Check that the information held by the given property corresponds to
    // an existing parameter in our runtime

    if (runtime) {
        QStringList info = pProperty->value().split(".");
        QString componentName = info.first();
        QString parameterName = info.last();

        foreach (CellMLSupport::CellmlFileRuntimeParameter *parameter, runtime->parameters())
            if (   !parameter->component().compare(componentName)
                && !parameter->name().compare(parameterName)) {
                res = true;

                break;
            }
    }

    pProperty->setIcon(res?
                           QIcon(":Core_blankIcon"):
                           QIcon(":/oxygen/status/task-attention.png"));
    pProperty->setExtraInfo(res?
                                QString():
                                runtime?
                                    tr("does not exist"):
                                    tr("no runtime"));

    return res;
}

//==============================================================================

void SingleCellViewInformationGraphsWidget::updateGraphInfo(Core::Property *pProperty,
                                                            const QString &pFileName) const
{
    // Update the graph information by checking the new value of the given
    // section property

    // Update the model property's icon based on its value and determine the
    // file name from which we will have to check our X and Y properties

    QString oldFileName = pProperty->properties()[0]->value();
    QString fileName = mFileName;

    if (!pFileName.compare(tr("Current"))) {
        pProperty->properties()[0]->setIcon(QIcon(":/oxygen/status/object-unlocked.png"));
    } else {
        pProperty->properties()[0]->setIcon(QIcon(":/oxygen/status/object-locked.png"));

        fileName = pFileName.split(" | ").last();
    }

    // Check that the parameters represented by the value of the X and Y
    // properties exist for the current/selected model
    // Note: we absolutely want to check the parameter (so that an icon can be
    //       assigned to its corresponding property) , hence the order of our &&
    //       assignment...

    bool graphOk = true;

    if (pProperty->properties().count() >= 2)
        graphOk = checkParameter(fileName, pProperty->properties()[1]) && graphOk;

    if (pProperty->properties().count() == 3)
        graphOk = checkParameter(fileName, pProperty->properties()[2]) && graphOk;

    // Update our section's name, if possible
    // Note: indeed, when populating ourselves, updateGraphInfo() gets called
    //       (through propertyChanged()), yet we don't want to (and can't) do
    //       what follows if not all the properties are available...

    if (pProperty->properties().count() == 3)
        pProperty->setName(QString("%1 | %2").arg(pProperty->properties()[1]->value(),
                                                  pProperty->properties()[2]->value()));

    // Update the status (i.e. icon) of our (section) property

    pProperty->setIcon(graphOk?
                           QIcon(":Core_blankIcon"):
                           QIcon(":/oxygen/status/task-attention.png"));
}

//==============================================================================

void SingleCellViewInformationGraphsWidget::modelChanged(Core::Property *pProperty,
                                                         const QString &pValue)
{
    // Update the graph information associated with the given property's
    // corresponding section property and the given value

    updateGraphInfo(pProperty->parentProperty(), pValue);
}

//==============================================================================

void SingleCellViewInformationGraphsWidget::propertyChanged(Core::Property *pProperty)
{
    // Update the graph information associated with the given property's
    // corresponding section property, but only if the property is not the model
    // one (since we will have been updating the graph information in
    // modelChanged()) above)

    if (pProperty != pProperty->parentProperty()->properties()[0])
        updateGraphInfo(pProperty->parentProperty(),
                        pProperty->parentProperty()->properties()[0]->value());
}

//==============================================================================

void SingleCellViewInformationGraphsWidget::updateGraphsInfo(Core::Property *pSectionProperty)
{
    // Make sure that we have a property editor

    if (!mPropertyEditor)
        return;

    // Make sure that no editing is in progress

    finishPropertyEditing();

    // Use the given section property or retrieve the ones for our current
    // property editor

    QList<Core::Property *> sectionProperties = QList<Core::Property *>();

    if (pSectionProperty)
        sectionProperties << pSectionProperty;
    else
        foreach (Core::Property *property, mPropertyEditor->properties())
            if (property->type() == Core::Property::Section)
                sectionProperties << property;

    // Determine the model list value

    QStringList modelListValue = QStringList();

    foreach (const QString &fileName, mFileNames)
        modelListValue << QString("%1 | %2").arg(QFileInfo(fileName).fileName(), fileName);

    modelListValue.sort();

    modelListValue.prepend(QString());
    modelListValue.prepend(tr("Current"));

    // Go through our section properties and update (incl. retranslate) their
    // information

    foreach (Core::Property *sectionProperty, sectionProperties) {
        sectionProperty->properties()[0]->setName(tr("Model"));
        sectionProperty->properties()[1]->setName(tr("X"));
        sectionProperty->properties()[2]->setName(tr("Y"));

        sectionProperty->properties()[0]->setListValue(modelListValue);

        updateGraphInfo(sectionProperty, sectionProperty->properties()[0]->value());
    }
}

//==============================================================================

}   // namespace SingleCellView
}   // namespace OpenCOR

//==============================================================================
// End of file
//==============================================================================
<commit_msg>Can now lock a graph to a particular model and everything will be fine if the file gets renamed or the locale gets changed (#31).<commit_after>//==============================================================================
// Single cell view information graphs widget
//==============================================================================

#include "cellmlfileruntime.h"
#include "propertyeditorwidget.h"
#include "singlecellviewgraphpanelplotwidget.h"
#include "singlecellviewinformationgraphswidget.h"

//==============================================================================

#include <QFileInfo>
#include <QHeaderView>
#include <QLabel>
#include <QSettings>

//==============================================================================

namespace OpenCOR {
namespace SingleCellView {

//==============================================================================

SingleCellViewInformationGraphsWidget::SingleCellViewInformationGraphsWidget(QWidget *pParent) :
    QStackedWidget(pParent),
    mPropertyEditors(QMap<SingleCellViewGraphPanelWidget *, Core::PropertyEditorWidget *>()),
    mColumnWidths(QList<int>()),
    mPropertyEditor(0),
    mFileName(QString()),
    mFileNames(QStringList()),
    mRuntimes(QMap<QString, CellMLSupport::CellmlFileRuntime *>()),
    mSimulations(QMap<QString, SingleCellViewSimulation *>())
{
    // Create a widget that will be shown whenever there are no graphs
    // associated with the current plotting area

    mNoGraphsMessageWidget = new QLabel(pParent);

    mNoGraphsMessageWidget->setAlignment(Qt::AlignCenter);
    mNoGraphsMessageWidget->setAutoFillBackground(true);
    mNoGraphsMessageWidget->setBackgroundRole(QPalette::Base);
    mNoGraphsMessageWidget->setWordWrap(true);

    addWidget(mNoGraphsMessageWidget);

    // Determine the default width of each column of our property editors

    Core::PropertyEditorWidget *tempPropertyEditor = new Core::PropertyEditorWidget(this);

    for (int i = 0, iMax = tempPropertyEditor->header()->count(); i < iMax; ++i)
        mColumnWidths.append(tempPropertyEditor->columnWidth(i));

    delete tempPropertyEditor;
}

//==============================================================================

void SingleCellViewInformationGraphsWidget::retranslateUi()
{
    // Retranslate our no graphs message widget

    mNoGraphsMessageWidget->setText(tr("There are no graphs..."));

    // Retranslate all our property editors

    foreach (Core::PropertyEditorWidget *propertyEditor, mPropertyEditors)
        propertyEditor->retranslateUi();

    // Retranslate the information about our graphs properties

    updateGraphsInfo();
}

//==============================================================================

static const QString SettingsColumnWidth = "ColumnWidth%1";

//==============================================================================

void SingleCellViewInformationGraphsWidget::loadSettings(QSettings *pSettings)
{
    // Retrieve the width of each column of our property editors

    for (int i = 0, iMax = mColumnWidths.size(); i < iMax; ++i)
        mColumnWidths[i] = pSettings->value(SettingsColumnWidth.arg(i),
                                            mColumnWidths.at(i)).toInt();

}

//==============================================================================

void SingleCellViewInformationGraphsWidget::saveSettings(QSettings *pSettings) const
{
    // Keep track of the width of each column of our current property editor

    for (int i = 0, iMax = mColumnWidths.size(); i < iMax; ++i)
        pSettings->setValue(SettingsColumnWidth.arg(i), mColumnWidths.at(i));
}

//==============================================================================

void SingleCellViewInformationGraphsWidget::initialize(const QString &pFileName,
                                                       CellMLSupport::CellmlFileRuntime *pRuntime,
                                                       SingleCellViewSimulation *pSimulation)
{
    // Keep track of the file name, runtime and simulation

    mFileName = pFileName;

    mRuntimes.insert(pFileName, pRuntime);
    mSimulations.insert(pFileName, pSimulation);

    // Update the information about our graphs properties

    updateGraphsInfo();
}

//==============================================================================

void SingleCellViewInformationGraphsWidget::finalize(const QString &pFileName)
{
    // Remove track of the file name, runtime and simulation

    mFileNames.removeOne(pFileName);

    mRuntimes.remove(pFileName);
    mSimulations.remove(pFileName);

    // Update the information about our graphs properties

    updateGraphsInfo();
}

//==============================================================================

void SingleCellViewInformationGraphsWidget::fileOpened(const QString &pFileName)
{
    // Keep track of the file name

    if (!mFileNames.contains(pFileName))
        mFileNames << pFileName;

    mFileNames.sort();

    // Update the information about our graphs properties

    updateGraphsInfo();
}

//==============================================================================

void SingleCellViewInformationGraphsWidget::fileRenamed(const QString &pOldFileName,
                                                        const QString &pNewFileName)
{
    // Replace the old file name with the new one in our various trackers

    mFileName = pNewFileName;

    mFileNames << pNewFileName;

    mRuntimes.insert(pNewFileName, mRuntimes.value(pOldFileName));
    mSimulations.insert(pNewFileName, mSimulations.value(pOldFileName));

    finalize(pOldFileName);
}

//==============================================================================

void SingleCellViewInformationGraphsWidget::initialize(SingleCellViewGraphPanelWidget *pGraphPanel)
{
    // Retrieve the property editor for the given file name or create one, if
    // none exists

    mPropertyEditor = mPropertyEditors.value(pGraphPanel);

    if (!mPropertyEditor) {
        // No property editor exists for the given graph panel, so create one

        mPropertyEditor = new Core::PropertyEditorWidget(false, false, this);

        // Initialise our property editor's columns' width

        for (int i = 0, iMax = mColumnWidths.size(); i < iMax; ++i)
            mPropertyEditor->setColumnWidth(i, mColumnWidths.at(i));

        // Keep track of changes to columns' width

        connect(mPropertyEditor->header(), SIGNAL(sectionResized(int, int, int)),
                this, SLOT(propertyEditorSectionResized(const int &, const int &, const int &)));

        // Keep track of changes to list properties

        connect(mPropertyEditor, SIGNAL(listPropertyChanged(Core::Property *, const QString &)),
                this, SLOT(modelChanged(Core::Property *, const QString &)));

        // Keep track of when the user changes a property value

        connect(mPropertyEditor, SIGNAL(propertyChanged(Core::Property *)),
                this, SLOT(propertyChanged(Core::Property *)));

        // Add our new property editor to ourselves

        addWidget(mPropertyEditor);

        // Keep track of our new property editor

        mPropertyEditors.insert(pGraphPanel, mPropertyEditor);
    }

    // Set our retrieved property editor as our current widget, but only if it
    // isn't empty

    if (mPropertyEditor->properties().count())
        setCurrentWidget(mPropertyEditor);
    else
        setCurrentWidget(mNoGraphsMessageWidget);

    // Update the information about our graphs properties
    // Note: this is in case the user changed the locale and then switched to a
    //       different graph panel...

    updateGraphsInfo();
}

//==============================================================================

void SingleCellViewInformationGraphsWidget::finalize(SingleCellViewGraphPanelWidget *pGraphPanel)
{
    // Remove track of our property editor

    mPropertyEditors.remove(pGraphPanel);
}

//==============================================================================

void SingleCellViewInformationGraphsWidget::addGraph(SingleCellViewGraphPanelPlotGraph *pGraph)
{
    // Make sure that we have a property editor

    if (!mPropertyEditor)
        return;

    // Prevent ourselves from being updated (to avoid any flickering)

    mPropertyEditor->setUpdatesEnabled(false);

    // Create a section for our newly added graph

    Core::Property *sectionProperty = mPropertyEditor->addSectionProperty();

    sectionProperty->setCheckable(true);
    sectionProperty->setChecked(true);

    // Create some properties for our graph

    mPropertyEditor->addListProperty(sectionProperty);
    Core::Property *xProperty = mPropertyEditor->addStringProperty(pGraph->parameterX()->fullyFormattedName(), sectionProperty);
    Core::Property *yProperty = mPropertyEditor->addStringProperty(pGraph->parameterY()->fullyFormattedName(), sectionProperty);

    xProperty->setEditable(true);
    yProperty->setEditable(true);

    // Update the information about our new graph

    updateGraphsInfo(sectionProperty);

    // Allow ourselves to be updated again

    mPropertyEditor->setUpdatesEnabled(true);

    // Make sure that our property editor is our current widget

    setCurrentWidget(mPropertyEditor);
}

//==============================================================================

void SingleCellViewInformationGraphsWidget::removeGraph(SingleCellViewGraphPanelPlotGraph *pGraph)
{
//---GRY--- TO BE DONE...
Q_UNUSED(pGraph);
    // Make sure that we have a property editor

    if (!mPropertyEditor)
        return;

    // Prevent ourselves from being updated (to avoid any flickering)

    mPropertyEditor->setUpdatesEnabled(false);

    // Allow ourselves to be updated again

    mPropertyEditor->setUpdatesEnabled(true);

    // Hide our property editor if it doesn't contain any graph anymore

    if (!mPropertyEditor->properties().count())
        setCurrentWidget(mNoGraphsMessageWidget);
}

//==============================================================================

void SingleCellViewInformationGraphsWidget::finishPropertyEditing()
{
    // Make sure that we have a property editor

    if (!mPropertyEditor)
        return;

    // Finish the editing of our property editor

    mPropertyEditor->finishPropertyEditing();
}

//==============================================================================

void SingleCellViewInformationGraphsWidget::propertyEditorSectionResized(const int &pLogicalIndex,
                                                                             const int &pOldSize,
                                                                             const int &pNewSize)
{
    Q_UNUSED(pOldSize);

    // Prevent all our property editors from responding to an updating of their
    // columns' width

    foreach (Core::PropertyEditorWidget *propertyEditor, mPropertyEditors)
        disconnect(propertyEditor->header(), SIGNAL(sectionResized(int, int, int)),
                   this, SLOT(propertyEditorSectionResized(const int &, const int &, const int &)));

    // Update the column width of all our property editors

    foreach (Core::PropertyEditorWidget *propertyEditor, mPropertyEditors)
        propertyEditor->header()->resizeSection(pLogicalIndex, pNewSize);

    // Keep track of the new column width

    mColumnWidths[pLogicalIndex] = pNewSize;

    // Re-allow all our property editors to respond to an updating of their
    // columns' width

    foreach (Core::PropertyEditorWidget *propertyEditor, mPropertyEditors)
        connect(propertyEditor->header(), SIGNAL(sectionResized(int, int, int)),
                this, SLOT(propertyEditorSectionResized(const int &, const int &, const int &)));
}

//==============================================================================

bool SingleCellViewInformationGraphsWidget::checkParameter(const QString &pFileName,
                                                           Core::Property *pProperty) const
{
    bool res = false;

    // Retrieve the runtime associated with the given file name

    CellMLSupport::CellmlFileRuntime *runtime = mRuntimes.value(pFileName);

    // Check that the information held by the given property corresponds to
    // an existing parameter in our runtime

    if (runtime) {
        QStringList info = pProperty->value().split(".");
        QString componentName = info.first();
        QString parameterName = info.last();

        foreach (CellMLSupport::CellmlFileRuntimeParameter *parameter, runtime->parameters())
            if (   !parameter->component().compare(componentName)
                && !parameter->name().compare(parameterName)) {
                res = true;

                break;
            }
    }

    pProperty->setIcon(res?
                           QIcon(":Core_blankIcon"):
                           QIcon(":/oxygen/status/task-attention.png"));
    pProperty->setExtraInfo(res?
                                QString():
                                runtime?
                                    tr("does not exist"):
                                    tr("no runtime"));

    return res;
}

//==============================================================================

static const QString PropertySeparator = " | ";

void SingleCellViewInformationGraphsWidget::updateGraphInfo(Core::Property *pProperty,
                                                            const QString &pFileName) const
{
    // Update the graph information by checking the new value of the given
    // section property

    // Update the model property's icon based on its value and determine the
    // file name from which we will have to check our X and Y properties

    QString fileName = mFileName;

    if (!pFileName.compare(tr("Current"))) {
        pProperty->properties()[0]->setIcon(QIcon(":/oxygen/status/object-unlocked.png"));
    } else {
        pProperty->properties()[0]->setIcon(QIcon(":/oxygen/status/object-locked.png"));

        fileName = pFileName.split(PropertySeparator).last();
    }

    // Check that the parameters represented by the value of the X and Y
    // properties exist for the current/selected model
    // Note: we absolutely want to check the parameter (so that an icon can be
    //       assigned to its corresponding property) , hence the order of our &&
    //       assignment...

    bool graphOk = true;

    if (pProperty->properties().count() >= 2)
        graphOk = checkParameter(fileName, pProperty->properties()[1]) && graphOk;

    if (pProperty->properties().count() == 3)
        graphOk = checkParameter(fileName, pProperty->properties()[2]) && graphOk;

    // Update our section's name, if possible
    // Note: indeed, when populating ourselves, updateGraphInfo() gets called
    //       (through propertyChanged()), yet we don't want to (and can't) do
    //       what follows if not all the properties are available...

    if (pProperty->properties().count() == 3)
        pProperty->setName( pProperty->properties()[1]->value()
                           +PropertySeparator
                           +pProperty->properties()[2]->value());

    // Update the status (i.e. icon) of our (section) property

    pProperty->setIcon(graphOk?
                           QIcon(":Core_blankIcon"):
                           QIcon(":/oxygen/status/task-attention.png"));
}

//==============================================================================

void SingleCellViewInformationGraphsWidget::modelChanged(Core::Property *pProperty,
                                                         const QString &pValue)
{
    // Update the graph information associated with the given property's
    // corresponding section property and the given value

    updateGraphInfo(pProperty->parentProperty(), pValue);
}

//==============================================================================

void SingleCellViewInformationGraphsWidget::propertyChanged(Core::Property *pProperty)
{
    // Update the graph information associated with the given property's
    // corresponding section property, but only if the property is not the model
    // one (since we will have been updating the graph information in
    // modelChanged()) above)

    if (pProperty != pProperty->parentProperty()->properties()[0])
        updateGraphInfo(pProperty->parentProperty(),
                        pProperty->parentProperty()->properties()[0]->value());
}

//==============================================================================

void SingleCellViewInformationGraphsWidget::updateGraphsInfo(Core::Property *pSectionProperty)
{
    // Make sure that we have a property editor

    if (!mPropertyEditor)
        return;

    // Make sure that no editing is in progress

    finishPropertyEditing();

    // Use the given section property or retrieve the ones for our current
    // property editor

    QList<Core::Property *> sectionProperties = QList<Core::Property *>();

    if (pSectionProperty)
        sectionProperties << pSectionProperty;
    else
        foreach (Core::Property *property, mPropertyEditor->properties())
            if (property->type() == Core::Property::Section)
                sectionProperties << property;

    // Determine the model list value

    QStringList modelListValue = QStringList();

    foreach (const QString &fileName, mFileNames)
        modelListValue << QFileInfo(fileName).fileName()+PropertySeparator+fileName;

    modelListValue.sort();

    modelListValue.prepend(QString());
    modelListValue.prepend(tr("Current"));

    // Go through our section properties and update (incl. retranslate) their
    // information

    foreach (Core::Property *sectionProperty, sectionProperties) {
        sectionProperty->properties()[0]->setName(tr("Model"));
        sectionProperty->properties()[1]->setName(tr("X"));
        sectionProperty->properties()[2]->setName(tr("Y"));

        // Keep track of the current model value, so that we can safely update
        // its list value and then select the correct model value back

        QString oldModelValue = sectionProperty->properties()[0]->value();
        QString newModelValue = oldModelValue;

        sectionProperty->properties()[0]->setListValue(modelListValue);

        if (!modelListValue.contains(oldModelValue))
            // Our old model value is not in our new model list value, which
            // means that the current file got renamed, so we use that instead

            newModelValue = QFileInfo(mFileName).fileName()+PropertySeparator+mFileName;

        // Check whether newModelValue is empty and, if so, update our graph
        // info using the current value of our model property, otherwise set the
        // value of our model property to newModelValue
        // Note: the latter will result in updateGraphInfo() being called, so we
        //       are all fine...

        if (newModelValue.isEmpty())
            updateGraphInfo(sectionProperty, sectionProperty->properties()[0]->value());
        else
            sectionProperty->properties()[0]->setValue(newModelValue);
    }
}

//==============================================================================

}   // namespace SingleCellView
}   // namespace OpenCOR

//==============================================================================
// End of file
//==============================================================================
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: SwXTextDefaults.cxx,v $
 *
 *  $Revision: 1.16 $
 *
 *  last change: $Author: obo $ $Date: 2004-08-11 15:41:27 $
 *
 *  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): Martin Gallwey (gallwey@sun.com)
 *
 *
 ************************************************************************/

#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif

#pragma hdrstop
#ifndef _SW_XTEXT_DEFAULTS_HXX
#include <SwXTextDefaults.hxx>
#endif
#ifndef _SWSTYLENAMEMAPPER_HXX
#include <SwStyleNameMapper.hxx>
#endif
#ifndef _FCHRFMT_HXX
#include <fchrfmt.hxx>
#endif
#ifndef _CHARFMT_HXX
#include <charfmt.hxx>
#endif
#ifndef _DOCSTYLE_HXX
#include <docstyle.hxx>
#endif
#ifndef _SWDOCSH_HXX
#include <docsh.hxx>
#endif
#ifndef _UNOMAP_HXX
#include <unomap.hxx>
#endif
#ifndef SW_UNOMID_HXX
#include <unomid.h>
#endif
#ifndef _PARATR_HXX
#include <paratr.hxx>
#endif
#ifndef _UNOPRNMS_HXX
#include <unoprnms.hxx>
#endif
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif

using namespace rtl;
using namespace com::sun::star;
using namespace com::sun::star::uno;
using namespace com::sun::star::beans;
using namespace com::sun::star::lang;

// declarations
void lcl_setPageDesc(SwDoc*, const uno::Any&, SfxItemSet& ); // from unoobj.cxx

#define C2U(cChar) OUString::createFromAscii(cChar)

SwXTextDefaults::SwXTextDefaults ( SwDoc * pNewDoc )
: pDoc (pNewDoc)
, aPropSet (aSwMapProvider.GetPropertyMap ( PROPERTY_MAP_TEXT_DEFAULT ) )
{
}

SwXTextDefaults::~SwXTextDefaults ()
{
}

Reference< XPropertySetInfo > SAL_CALL SwXTextDefaults::getPropertySetInfo(  )
        throw(RuntimeException)
{
    static uno::Reference < XPropertySetInfo > xRef = aPropSet.getPropertySetInfo();
    return xRef;
}

void SAL_CALL SwXTextDefaults::setPropertyValue( const OUString& rPropertyName, const Any& aValue )
        throw(UnknownPropertyException, PropertyVetoException, IllegalArgumentException, WrappedTargetException, RuntimeException)
{
    vos::OGuard aGuard( Application::GetSolarMutex());
    if (!pDoc)
        throw RuntimeException();
    const SfxItemPropertyMap *pMap = SfxItemPropertyMap::GetByName( aPropSet.getPropertyMap(), rPropertyName);
    if (!pMap)
        throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );
    if ( pMap->nFlags & PropertyAttribute::READONLY)
        throw PropertyVetoException ( OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Property is read-only: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );

    const SfxPoolItem& rItem = pDoc->GetDefault(pMap->nWID);
    if (RES_PAGEDESC == pMap->nWID && MID_PAGEDESC_PAGEDESCNAME == pMap->nMemberId)
    {
        SfxItemSet aSet( pDoc->GetAttrPool(), RES_PAGEDESC, RES_PAGEDESC );
        aSet.Put(rItem);
        lcl_setPageDesc( pDoc, aValue, aSet );
        pDoc->SetDefault(aSet.Get(RES_PAGEDESC));
    }
    else if ((RES_PARATR_DROP == pMap->nWID && MID_DROPCAP_CHAR_STYLE_NAME == pMap->nMemberId) ||
             (RES_TXTATR_CHARFMT == pMap->nWID))
    {
        OUString uStyle;
        if(aValue >>= uStyle)
        {
            String sStyle;
            SwStyleNameMapper::FillUIName(uStyle, sStyle, GET_POOLID_CHRFMT, sal_True );
            SwDocStyleSheet* pStyle =
                (SwDocStyleSheet*)pDoc->GetDocShell()->GetStyleSheetPool()->Find(sStyle, SFX_STYLE_FAMILY_CHAR);
            SwFmtDrop* pDrop = 0;
            SwFmtCharFmt *pCharFmt = 0;
            if(pStyle)
            {
                SwDocStyleSheet aStyle( *(SwDocStyleSheet*)pStyle );
                if (RES_PARATR_DROP == pMap->nWID)
                {
                    pDrop = (SwFmtDrop*)rItem.Clone();   // because rItem ist const...
                    pDrop->SetCharFmt(aStyle.GetCharFmt());
                    pDoc->SetDefault(*pDrop);
                }
                else // RES_TXTATR_CHARFMT == pMap->nWID
                {
                    pCharFmt = (SwFmtCharFmt*)rItem.Clone();   // because rItem ist const...
                    pCharFmt->SetCharFmt(aStyle.GetCharFmt());
                    pDoc->SetDefault(*pCharFmt);
                }
            }
            else
                throw lang::IllegalArgumentException();
            delete pDrop;
            delete pCharFmt;
        }
        else
            throw lang::IllegalArgumentException();
    }
    else
    {
        SfxPoolItem * pNewItem = rItem.Clone();
        pNewItem->PutValue( aValue, pMap->nMemberId);
        pDoc->SetDefault(*pNewItem);
        delete pNewItem;
    }
}

Any SAL_CALL SwXTextDefaults::getPropertyValue( const OUString& rPropertyName )
        throw(UnknownPropertyException, WrappedTargetException, RuntimeException)
{
    vos::OGuard aGuard( Application::GetSolarMutex());
    if (!pDoc)
        throw RuntimeException();
    const SfxItemPropertyMap *pMap = SfxItemPropertyMap::GetByName( aPropSet.getPropertyMap(), rPropertyName);
    if (!pMap)
        throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );
    Any aRet;
    const SfxPoolItem& rItem = pDoc->GetDefault(pMap->nWID);
    rItem.QueryValue( aRet, pMap->nMemberId );
    return aRet;
}

void SAL_CALL SwXTextDefaults::addPropertyChangeListener( const OUString& rPropertyName, const Reference< XPropertyChangeListener >& xListener )
        throw(UnknownPropertyException, WrappedTargetException, RuntimeException)
{
    DBG_WARNING ( "not implemented" );
}

void SAL_CALL SwXTextDefaults::removePropertyChangeListener( const OUString& rPropertyName, const Reference< XPropertyChangeListener >& aListener )
        throw(UnknownPropertyException, WrappedTargetException, RuntimeException)
{
    DBG_WARNING ( "not implemented" );
}

void SAL_CALL SwXTextDefaults::addVetoableChangeListener( const OUString& rPropertyName, const Reference< XVetoableChangeListener >& aListener )
        throw(UnknownPropertyException, WrappedTargetException, RuntimeException)
{
    DBG_WARNING ( "not implemented" );
}

void SAL_CALL SwXTextDefaults::removeVetoableChangeListener( const OUString& rPropertyName, const Reference< XVetoableChangeListener >& aListener )
        throw(UnknownPropertyException, WrappedTargetException, RuntimeException)
{
    DBG_WARNING ( "not implemented" );
}

// XPropertyState
PropertyState SAL_CALL SwXTextDefaults::getPropertyState( const OUString& rPropertyName )
        throw(UnknownPropertyException, RuntimeException)
{
    vos::OGuard aGuard( Application::GetSolarMutex());
    PropertyState eRet = PropertyState_DIRECT_VALUE;
    if (!pDoc)
        throw RuntimeException();
    const SfxItemPropertyMap *pMap = SfxItemPropertyMap::GetByName( aPropSet.getPropertyMap(), rPropertyName);
    if (!pMap)
        throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );

    const SfxPoolItem& rItem = pDoc->GetDefault(pMap->nWID);
    if (IsStaticDefaultItem ( &rItem ) )
        eRet = PropertyState_DEFAULT_VALUE;
    return eRet;
}

Sequence< PropertyState > SAL_CALL SwXTextDefaults::getPropertyStates( const Sequence< OUString >& rPropertyNames )
        throw(UnknownPropertyException, RuntimeException)
{
    const sal_Int32 nCount = rPropertyNames.getLength();
    const OUString * pNames = rPropertyNames.getConstArray();
    Sequence < PropertyState > aRet ( nCount );
    PropertyState *pState = aRet.getArray();

    for ( sal_Int32 nIndex = 0; nIndex < nCount; nIndex++)
        pState[nIndex] = getPropertyState( pNames[nIndex] );

    return aRet;
}

void SAL_CALL SwXTextDefaults::setPropertyToDefault( const OUString& rPropertyName )
        throw(UnknownPropertyException, RuntimeException)
{
    if (!pDoc)
        throw RuntimeException();
    const SfxItemPropertyMap *pMap = SfxItemPropertyMap::GetByName( aPropSet.getPropertyMap(), rPropertyName);
    if (!pMap)
        throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );
    if ( pMap->nFlags & PropertyAttribute::READONLY)
        throw RuntimeException( OUString ( RTL_CONSTASCII_USTRINGPARAM ( "setPropertyToDefault: property is read-only: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );
    SfxItemPool rSet (pDoc->GetAttrPool());
    rSet.ResetPoolDefaultItem ( pMap->nWID );
}

Any SAL_CALL SwXTextDefaults::getPropertyDefault( const OUString& rPropertyName )
        throw(UnknownPropertyException, WrappedTargetException, RuntimeException)
{
    if (!pDoc)
        throw RuntimeException();
    const SfxItemPropertyMap *pMap = SfxItemPropertyMap::GetByName( aPropSet.getPropertyMap(), rPropertyName);
    if (!pMap)
        throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );
    Any aRet;
    SfxItemPool rSet (pDoc->GetAttrPool());
    const SfxPoolItem *pItem = rSet.GetPoolDefaultItem ( pMap->nWID );
    pItem->QueryValue( aRet, pMap->nMemberId );
    return aRet;
}

rtl::OUString SAL_CALL SwXTextDefaults::getImplementationName(  )
    throw (RuntimeException)
{
    return C2U("SwXTextDefaults");
}

sal_Bool SAL_CALL SwXTextDefaults::supportsService( const ::rtl::OUString& rServiceName )
    throw (RuntimeException)
{
    return  rServiceName == C2U("com.sun.star.text.Defaults") ||
            rServiceName == C2U("com.sun.star.style.CharacterProperties") ||
            rServiceName == C2U("com.sun.star.style.CharacterPropertiesAsian") ||
            rServiceName == C2U("com.sun.star.style.CharacterPropertiesComplex") ||
            rServiceName == C2U("com.sun.star.style.ParagraphProperties") ||
            rServiceName == C2U("com.sun.star.style.ParagraphPropertiesAsian") ||
            rServiceName == C2U("com.sun.star.style.ParagraphPropertiesComplex");
}

uno::Sequence< ::rtl::OUString > SAL_CALL SwXTextDefaults::getSupportedServiceNames(  )
    throw (RuntimeException)
{
    uno::Sequence< OUString > aRet(7);
    OUString* pArr = aRet.getArray();
    *pArr++ = C2U("com.sun.star.text.Defaults");
    *pArr++ = C2U("com.sun.star.style.CharacterProperties");
    *pArr++ = C2U("com.sun.star.style.CharacterPropertiesAsian");
    *pArr++ = C2U("com.sun.star.style.CharacterPropertiesComplex");
    *pArr++ = C2U("com.sun.star.style.ParagraphProperties");
    *pArr++ = C2U("com.sun.star.style.ParagraphPropertiesAsian");
    *pArr++ = C2U("com.sun.star.style.ParagraphPropertiesComplex");
    return aRet;
}

<commit_msg>INTEGRATION: CWS ooo19126 (1.16.600); FILE MERGED 2005/09/05 13:41:35 rt 1.16.600.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: SwXTextDefaults.cxx,v $
 *
 *  $Revision: 1.17 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 05:23:27 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/

#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif

#pragma hdrstop
#ifndef _SW_XTEXT_DEFAULTS_HXX
#include <SwXTextDefaults.hxx>
#endif
#ifndef _SWSTYLENAMEMAPPER_HXX
#include <SwStyleNameMapper.hxx>
#endif
#ifndef _FCHRFMT_HXX
#include <fchrfmt.hxx>
#endif
#ifndef _CHARFMT_HXX
#include <charfmt.hxx>
#endif
#ifndef _DOCSTYLE_HXX
#include <docstyle.hxx>
#endif
#ifndef _SWDOCSH_HXX
#include <docsh.hxx>
#endif
#ifndef _UNOMAP_HXX
#include <unomap.hxx>
#endif
#ifndef SW_UNOMID_HXX
#include <unomid.h>
#endif
#ifndef _PARATR_HXX
#include <paratr.hxx>
#endif
#ifndef _UNOPRNMS_HXX
#include <unoprnms.hxx>
#endif
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif

using namespace rtl;
using namespace com::sun::star;
using namespace com::sun::star::uno;
using namespace com::sun::star::beans;
using namespace com::sun::star::lang;

// declarations
void lcl_setPageDesc(SwDoc*, const uno::Any&, SfxItemSet& ); // from unoobj.cxx

#define C2U(cChar) OUString::createFromAscii(cChar)

SwXTextDefaults::SwXTextDefaults ( SwDoc * pNewDoc )
: pDoc (pNewDoc)
, aPropSet (aSwMapProvider.GetPropertyMap ( PROPERTY_MAP_TEXT_DEFAULT ) )
{
}

SwXTextDefaults::~SwXTextDefaults ()
{
}

Reference< XPropertySetInfo > SAL_CALL SwXTextDefaults::getPropertySetInfo(  )
        throw(RuntimeException)
{
    static uno::Reference < XPropertySetInfo > xRef = aPropSet.getPropertySetInfo();
    return xRef;
}

void SAL_CALL SwXTextDefaults::setPropertyValue( const OUString& rPropertyName, const Any& aValue )
        throw(UnknownPropertyException, PropertyVetoException, IllegalArgumentException, WrappedTargetException, RuntimeException)
{
    vos::OGuard aGuard( Application::GetSolarMutex());
    if (!pDoc)
        throw RuntimeException();
    const SfxItemPropertyMap *pMap = SfxItemPropertyMap::GetByName( aPropSet.getPropertyMap(), rPropertyName);
    if (!pMap)
        throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );
    if ( pMap->nFlags & PropertyAttribute::READONLY)
        throw PropertyVetoException ( OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Property is read-only: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );

    const SfxPoolItem& rItem = pDoc->GetDefault(pMap->nWID);
    if (RES_PAGEDESC == pMap->nWID && MID_PAGEDESC_PAGEDESCNAME == pMap->nMemberId)
    {
        SfxItemSet aSet( pDoc->GetAttrPool(), RES_PAGEDESC, RES_PAGEDESC );
        aSet.Put(rItem);
        lcl_setPageDesc( pDoc, aValue, aSet );
        pDoc->SetDefault(aSet.Get(RES_PAGEDESC));
    }
    else if ((RES_PARATR_DROP == pMap->nWID && MID_DROPCAP_CHAR_STYLE_NAME == pMap->nMemberId) ||
             (RES_TXTATR_CHARFMT == pMap->nWID))
    {
        OUString uStyle;
        if(aValue >>= uStyle)
        {
            String sStyle;
            SwStyleNameMapper::FillUIName(uStyle, sStyle, GET_POOLID_CHRFMT, sal_True );
            SwDocStyleSheet* pStyle =
                (SwDocStyleSheet*)pDoc->GetDocShell()->GetStyleSheetPool()->Find(sStyle, SFX_STYLE_FAMILY_CHAR);
            SwFmtDrop* pDrop = 0;
            SwFmtCharFmt *pCharFmt = 0;
            if(pStyle)
            {
                SwDocStyleSheet aStyle( *(SwDocStyleSheet*)pStyle );
                if (RES_PARATR_DROP == pMap->nWID)
                {
                    pDrop = (SwFmtDrop*)rItem.Clone();   // because rItem ist const...
                    pDrop->SetCharFmt(aStyle.GetCharFmt());
                    pDoc->SetDefault(*pDrop);
                }
                else // RES_TXTATR_CHARFMT == pMap->nWID
                {
                    pCharFmt = (SwFmtCharFmt*)rItem.Clone();   // because rItem ist const...
                    pCharFmt->SetCharFmt(aStyle.GetCharFmt());
                    pDoc->SetDefault(*pCharFmt);
                }
            }
            else
                throw lang::IllegalArgumentException();
            delete pDrop;
            delete pCharFmt;
        }
        else
            throw lang::IllegalArgumentException();
    }
    else
    {
        SfxPoolItem * pNewItem = rItem.Clone();
        pNewItem->PutValue( aValue, pMap->nMemberId);
        pDoc->SetDefault(*pNewItem);
        delete pNewItem;
    }
}

Any SAL_CALL SwXTextDefaults::getPropertyValue( const OUString& rPropertyName )
        throw(UnknownPropertyException, WrappedTargetException, RuntimeException)
{
    vos::OGuard aGuard( Application::GetSolarMutex());
    if (!pDoc)
        throw RuntimeException();
    const SfxItemPropertyMap *pMap = SfxItemPropertyMap::GetByName( aPropSet.getPropertyMap(), rPropertyName);
    if (!pMap)
        throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );
    Any aRet;
    const SfxPoolItem& rItem = pDoc->GetDefault(pMap->nWID);
    rItem.QueryValue( aRet, pMap->nMemberId );
    return aRet;
}

void SAL_CALL SwXTextDefaults::addPropertyChangeListener( const OUString& rPropertyName, const Reference< XPropertyChangeListener >& xListener )
        throw(UnknownPropertyException, WrappedTargetException, RuntimeException)
{
    DBG_WARNING ( "not implemented" );
}

void SAL_CALL SwXTextDefaults::removePropertyChangeListener( const OUString& rPropertyName, const Reference< XPropertyChangeListener >& aListener )
        throw(UnknownPropertyException, WrappedTargetException, RuntimeException)
{
    DBG_WARNING ( "not implemented" );
}

void SAL_CALL SwXTextDefaults::addVetoableChangeListener( const OUString& rPropertyName, const Reference< XVetoableChangeListener >& aListener )
        throw(UnknownPropertyException, WrappedTargetException, RuntimeException)
{
    DBG_WARNING ( "not implemented" );
}

void SAL_CALL SwXTextDefaults::removeVetoableChangeListener( const OUString& rPropertyName, const Reference< XVetoableChangeListener >& aListener )
        throw(UnknownPropertyException, WrappedTargetException, RuntimeException)
{
    DBG_WARNING ( "not implemented" );
}

// XPropertyState
PropertyState SAL_CALL SwXTextDefaults::getPropertyState( const OUString& rPropertyName )
        throw(UnknownPropertyException, RuntimeException)
{
    vos::OGuard aGuard( Application::GetSolarMutex());
    PropertyState eRet = PropertyState_DIRECT_VALUE;
    if (!pDoc)
        throw RuntimeException();
    const SfxItemPropertyMap *pMap = SfxItemPropertyMap::GetByName( aPropSet.getPropertyMap(), rPropertyName);
    if (!pMap)
        throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );

    const SfxPoolItem& rItem = pDoc->GetDefault(pMap->nWID);
    if (IsStaticDefaultItem ( &rItem ) )
        eRet = PropertyState_DEFAULT_VALUE;
    return eRet;
}

Sequence< PropertyState > SAL_CALL SwXTextDefaults::getPropertyStates( const Sequence< OUString >& rPropertyNames )
        throw(UnknownPropertyException, RuntimeException)
{
    const sal_Int32 nCount = rPropertyNames.getLength();
    const OUString * pNames = rPropertyNames.getConstArray();
    Sequence < PropertyState > aRet ( nCount );
    PropertyState *pState = aRet.getArray();

    for ( sal_Int32 nIndex = 0; nIndex < nCount; nIndex++)
        pState[nIndex] = getPropertyState( pNames[nIndex] );

    return aRet;
}

void SAL_CALL SwXTextDefaults::setPropertyToDefault( const OUString& rPropertyName )
        throw(UnknownPropertyException, RuntimeException)
{
    if (!pDoc)
        throw RuntimeException();
    const SfxItemPropertyMap *pMap = SfxItemPropertyMap::GetByName( aPropSet.getPropertyMap(), rPropertyName);
    if (!pMap)
        throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );
    if ( pMap->nFlags & PropertyAttribute::READONLY)
        throw RuntimeException( OUString ( RTL_CONSTASCII_USTRINGPARAM ( "setPropertyToDefault: property is read-only: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );
    SfxItemPool rSet (pDoc->GetAttrPool());
    rSet.ResetPoolDefaultItem ( pMap->nWID );
}

Any SAL_CALL SwXTextDefaults::getPropertyDefault( const OUString& rPropertyName )
        throw(UnknownPropertyException, WrappedTargetException, RuntimeException)
{
    if (!pDoc)
        throw RuntimeException();
    const SfxItemPropertyMap *pMap = SfxItemPropertyMap::GetByName( aPropSet.getPropertyMap(), rPropertyName);
    if (!pMap)
        throw UnknownPropertyException(OUString ( RTL_CONSTASCII_USTRINGPARAM ( "Unknown property: " ) ) + rPropertyName, static_cast < cppu::OWeakObject * > ( this ) );
    Any aRet;
    SfxItemPool rSet (pDoc->GetAttrPool());
    const SfxPoolItem *pItem = rSet.GetPoolDefaultItem ( pMap->nWID );
    pItem->QueryValue( aRet, pMap->nMemberId );
    return aRet;
}

rtl::OUString SAL_CALL SwXTextDefaults::getImplementationName(  )
    throw (RuntimeException)
{
    return C2U("SwXTextDefaults");
}

sal_Bool SAL_CALL SwXTextDefaults::supportsService( const ::rtl::OUString& rServiceName )
    throw (RuntimeException)
{
    return  rServiceName == C2U("com.sun.star.text.Defaults") ||
            rServiceName == C2U("com.sun.star.style.CharacterProperties") ||
            rServiceName == C2U("com.sun.star.style.CharacterPropertiesAsian") ||
            rServiceName == C2U("com.sun.star.style.CharacterPropertiesComplex") ||
            rServiceName == C2U("com.sun.star.style.ParagraphProperties") ||
            rServiceName == C2U("com.sun.star.style.ParagraphPropertiesAsian") ||
            rServiceName == C2U("com.sun.star.style.ParagraphPropertiesComplex");
}

uno::Sequence< ::rtl::OUString > SAL_CALL SwXTextDefaults::getSupportedServiceNames(  )
    throw (RuntimeException)
{
    uno::Sequence< OUString > aRet(7);
    OUString* pArr = aRet.getArray();
    *pArr++ = C2U("com.sun.star.text.Defaults");
    *pArr++ = C2U("com.sun.star.style.CharacterProperties");
    *pArr++ = C2U("com.sun.star.style.CharacterPropertiesAsian");
    *pArr++ = C2U("com.sun.star.style.CharacterPropertiesComplex");
    *pArr++ = C2U("com.sun.star.style.ParagraphProperties");
    *pArr++ = C2U("com.sun.star.style.ParagraphPropertiesAsian");
    *pArr++ = C2U("com.sun.star.style.ParagraphPropertiesComplex");
    return aRet;
}

<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    TestSimple3DCirclesStrategy.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

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

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

#include "vtkActor.h"
#include "vtkEdgeLayout.h"
#include "vtkGraphLayout.h"
#include "vtkGraphToPolyData.h"
#include "vtkMutableDirectedGraph.h"
#include "vtkPassThroughEdgeStrategy.h"
#include "vtkPolyDataMapper.h"
#include "vtkProperty.h"
#include "vtkRandomGraphSource.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkSimple3DCirclesStrategy.h"
#include "vtkSmartPointer.h"
#include "vtkVertexGlyphFilter.h"

int TestSimple3DCirclesStrategy(int argc, char **argv)
  {
  // graph
  vtkSmartPointer<vtkMutableDirectedGraph> graph = vtkSmartPointer<vtkMutableDirectedGraph>::New();
  // mapper
  vtkSmartPointer<vtkPolyDataMapper> edgeMapper = vtkSmartPointer<vtkPolyDataMapper>::New();
  vtkSmartPointer<vtkPolyDataMapper> vertMapper = vtkSmartPointer<vtkPolyDataMapper>::New();
  vtkSmartPointer<vtkPassThroughEdgeStrategy> edgeStrategy = vtkSmartPointer<vtkPassThroughEdgeStrategy>::New();
  vtkSmartPointer<vtkSimple3DCirclesStrategy> strategy = vtkSmartPointer<vtkSimple3DCirclesStrategy>::New();
  vtkSmartPointer<vtkGraphLayout> layout = vtkSmartPointer<vtkGraphLayout>::New();
  vtkSmartPointer<vtkEdgeLayout> edgeLayout = vtkSmartPointer<vtkEdgeLayout>::New();
  vtkSmartPointer<vtkGraphToPolyData> graphToPoly = vtkSmartPointer<vtkGraphToPolyData>::New();
  vtkSmartPointer<vtkVertexGlyphFilter> vertGlyph = vtkSmartPointer<vtkVertexGlyphFilter>::New();
  vtkSmartPointer<vtkActor> edgeActor = vtkSmartPointer<vtkActor>::New();
  vtkSmartPointer<vtkActor> vertActor = vtkSmartPointer<vtkActor>::New();
  vtkSmartPointer<vtkRenderer> ren = vtkSmartPointer<vtkRenderer>::New();
  vtkSmartPointer<vtkRenderWindow> renwin = vtkSmartPointer<vtkRenderWindow>::New();
  vtkSmartPointer<vtkRenderWindowInteractor> iren = vtkSmartPointer<vtkRenderWindowInteractor>::New();
  iren->SetRenderWindow(renwin);
  renwin->SetMultiSamples(0);

// Vertices:
// layer 0: 0,1,2
// layer 1: 3,4,5,6
// layer 2: 7,8,9
// standalone: 10,11
  for ( int i = 0; i < 12; ++i )
    graph->AddVertex();

// Edges:
// layer 0 -> 1
  graph->AddEdge( 0, 4 );
  graph->AddEdge( 0, 6 );
  graph->AddEdge( 1, 5 );
  graph->AddEdge( 1, 6 );
  graph->AddEdge( 2, 3 );
  graph->AddEdge( 2, 4 );
  graph->AddEdge( 2, 5 );
// layer 1 -> 2
  graph->AddEdge( 3, 8 );
  graph->AddEdge( 3, 7 );
  graph->AddEdge( 4, 9 );
  graph->AddEdge( 4, 8 );
  graph->AddEdge( 5, 7 );
// layer 0 -> 2
  graph->AddEdge( 0, 9 );

  strategy->SetMethod( vtkSimple3DCirclesStrategy::FixedDistanceMethod );
  strategy->AutoHeightOn();
  strategy->SetDirection(0.0,-1.0,0.0);
  strategy->SetMinimumDegree( 45.0 );
  layout->SetInput( graph );
  layout->SetLayoutStrategy( strategy );

  // Uncomment the following for a more interesting result!
#if 0
  vtkSmartPointer<vtkRandomGraphSource> src = vtkSmartPointer<vtkRandomGraphSource>::New();
  src->SetNumberOfVertices(1000);
  src->SetNumberOfEdges(0);
  src->SetDirected(true);
  src->SetStartWithTree(true);
  layout->SetInputConnection( src->GetOutputPort() );
#endif

  edgeLayout->SetInputConnection( layout->GetOutputPort() );
  edgeLayout->SetLayoutStrategy( edgeStrategy );
  edgeLayout->Update();

  graphToPoly->EdgeGlyphOutputOn();
  graphToPoly->SetInput( edgeLayout->GetOutput() );
  vertGlyph->SetInput( edgeLayout->GetOutput() );

  edgeMapper->ScalarVisibilityOff();
  edgeMapper->ImmediateModeRenderingOn();
  edgeMapper->SetInputConnection( graphToPoly->GetOutputPort() );
  edgeActor->GetProperty()->SetColor( 0.75, 0.75, 0.75 );
  edgeActor->GetProperty()->SetOpacity(1.0);
  edgeActor->GetProperty()->SetLineWidth(2);
  edgeActor->PickableOff();
  edgeActor->SetMapper( edgeMapper );
  ren->AddActor( edgeActor );

  vertMapper->ScalarVisibilityOff();
  vertMapper->ImmediateModeRenderingOn();
  vertMapper->SetInputConnection( vertGlyph->GetOutputPort() );
  vertActor->GetProperty()->SetColor( 0.5, 0.5, 0.5 );
  vertActor->GetProperty()->SetOpacity(1.0);
  vertActor->GetProperty()->SetPointSize(7);
  vertActor->PickableOff();
  vertActor->SetMapper( vertMapper );
  ren->AddActor( vertActor );

  renwin->SetSize(800,600);

  renwin->AddRenderer(ren);
  renwin->Render();

  int retVal = vtkRegressionTestImage( renwin );
  if ( retVal == vtkRegressionTester::DO_INTERACTOR )
    {
    iren->Start();
    }

  return !retVal;
  }

<commit_msg>COMP: Use correct argv type.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    TestSimple3DCirclesStrategy.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

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

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

#include "vtkActor.h"
#include "vtkEdgeLayout.h"
#include "vtkGraphLayout.h"
#include "vtkGraphToPolyData.h"
#include "vtkMutableDirectedGraph.h"
#include "vtkPassThroughEdgeStrategy.h"
#include "vtkPolyDataMapper.h"
#include "vtkProperty.h"
#include "vtkRandomGraphSource.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkSimple3DCirclesStrategy.h"
#include "vtkSmartPointer.h"
#include "vtkVertexGlyphFilter.h"

int TestSimple3DCirclesStrategy(int argc, char *argv[])
  {
  // graph
  vtkSmartPointer<vtkMutableDirectedGraph> graph = vtkSmartPointer<vtkMutableDirectedGraph>::New();
  // mapper
  vtkSmartPointer<vtkPolyDataMapper> edgeMapper = vtkSmartPointer<vtkPolyDataMapper>::New();
  vtkSmartPointer<vtkPolyDataMapper> vertMapper = vtkSmartPointer<vtkPolyDataMapper>::New();
  vtkSmartPointer<vtkPassThroughEdgeStrategy> edgeStrategy = vtkSmartPointer<vtkPassThroughEdgeStrategy>::New();
  vtkSmartPointer<vtkSimple3DCirclesStrategy> strategy = vtkSmartPointer<vtkSimple3DCirclesStrategy>::New();
  vtkSmartPointer<vtkGraphLayout> layout = vtkSmartPointer<vtkGraphLayout>::New();
  vtkSmartPointer<vtkEdgeLayout> edgeLayout = vtkSmartPointer<vtkEdgeLayout>::New();
  vtkSmartPointer<vtkGraphToPolyData> graphToPoly = vtkSmartPointer<vtkGraphToPolyData>::New();
  vtkSmartPointer<vtkVertexGlyphFilter> vertGlyph = vtkSmartPointer<vtkVertexGlyphFilter>::New();
  vtkSmartPointer<vtkActor> edgeActor = vtkSmartPointer<vtkActor>::New();
  vtkSmartPointer<vtkActor> vertActor = vtkSmartPointer<vtkActor>::New();
  vtkSmartPointer<vtkRenderer> ren = vtkSmartPointer<vtkRenderer>::New();
  vtkSmartPointer<vtkRenderWindow> renwin = vtkSmartPointer<vtkRenderWindow>::New();
  vtkSmartPointer<vtkRenderWindowInteractor> iren = vtkSmartPointer<vtkRenderWindowInteractor>::New();
  iren->SetRenderWindow(renwin);
  renwin->SetMultiSamples(0);

// Vertices:
// layer 0: 0,1,2
// layer 1: 3,4,5,6
// layer 2: 7,8,9
// standalone: 10,11
  for ( int i = 0; i < 12; ++i )
    graph->AddVertex();

// Edges:
// layer 0 -> 1
  graph->AddEdge( 0, 4 );
  graph->AddEdge( 0, 6 );
  graph->AddEdge( 1, 5 );
  graph->AddEdge( 1, 6 );
  graph->AddEdge( 2, 3 );
  graph->AddEdge( 2, 4 );
  graph->AddEdge( 2, 5 );
// layer 1 -> 2
  graph->AddEdge( 3, 8 );
  graph->AddEdge( 3, 7 );
  graph->AddEdge( 4, 9 );
  graph->AddEdge( 4, 8 );
  graph->AddEdge( 5, 7 );
// layer 0 -> 2
  graph->AddEdge( 0, 9 );

  strategy->SetMethod( vtkSimple3DCirclesStrategy::FixedDistanceMethod );
  strategy->AutoHeightOn();
  strategy->SetDirection(0.0,-1.0,0.0);
  strategy->SetMinimumDegree( 45.0 );
  layout->SetInput( graph );
  layout->SetLayoutStrategy( strategy );

  // Uncomment the following for a more interesting result!
#if 0
  vtkSmartPointer<vtkRandomGraphSource> src = vtkSmartPointer<vtkRandomGraphSource>::New();
  src->SetNumberOfVertices(1000);
  src->SetNumberOfEdges(0);
  src->SetDirected(true);
  src->SetStartWithTree(true);
  layout->SetInputConnection( src->GetOutputPort() );
#endif

  edgeLayout->SetInputConnection( layout->GetOutputPort() );
  edgeLayout->SetLayoutStrategy( edgeStrategy );
  edgeLayout->Update();

  graphToPoly->EdgeGlyphOutputOn();
  graphToPoly->SetInput( edgeLayout->GetOutput() );
  vertGlyph->SetInput( edgeLayout->GetOutput() );

  edgeMapper->ScalarVisibilityOff();
  edgeMapper->ImmediateModeRenderingOn();
  edgeMapper->SetInputConnection( graphToPoly->GetOutputPort() );
  edgeActor->GetProperty()->SetColor( 0.75, 0.75, 0.75 );
  edgeActor->GetProperty()->SetOpacity(1.0);
  edgeActor->GetProperty()->SetLineWidth(2);
  edgeActor->PickableOff();
  edgeActor->SetMapper( edgeMapper );
  ren->AddActor( edgeActor );

  vertMapper->ScalarVisibilityOff();
  vertMapper->ImmediateModeRenderingOn();
  vertMapper->SetInputConnection( vertGlyph->GetOutputPort() );
  vertActor->GetProperty()->SetColor( 0.5, 0.5, 0.5 );
  vertActor->GetProperty()->SetOpacity(1.0);
  vertActor->GetProperty()->SetPointSize(7);
  vertActor->PickableOff();
  vertActor->SetMapper( vertMapper );
  ren->AddActor( vertActor );

  renwin->SetSize(800,600);

  renwin->AddRenderer(ren);
  renwin->Render();

  int retVal = vtkRegressionTestImage( renwin );
  if ( retVal == vtkRegressionTester::DO_INTERACTOR )
    {
    iren->Start();
    }

  return !retVal;
  }

<|endoftext|>