<commit_before>#include "yaml-cpp/yaml.h"  // IWYU pragma: keep

#include "gtest/gtest.h"

namespace YAML {
namespace {
TEST(LoadNodeTest, Reassign) {
  Node node = Load("foo");
  node = Node();
}

TEST(LoadNodeTest, FallbackValues) {
  Node node = Load("foo: bar\nx: 2");
  EXPECT_EQ("bar", node["foo"].as<std::string>());
  EXPECT_EQ("bar", node["foo"].as<std::string>("hello"));
  EXPECT_EQ("hello", node["baz"].as<std::string>("hello"));
  EXPECT_EQ(2, node["x"].as<int>());
  EXPECT_EQ(2, node["x"].as<int>(5));
  EXPECT_EQ(5, node["y"].as<int>(5));
}

TEST(LoadNodeTest, NumericConversion) {
  Node node = Load("[1.5, 1, .nan, .inf, -.inf, 0x15, 015]");
  EXPECT_EQ(1.5f, node[0].as<float>());
  EXPECT_EQ(1.5, node[0].as<double>());
  EXPECT_THROW(node[0].as<int>(), TypedBadConversion<int>);
  EXPECT_EQ(1, node[1].as<int>());
  EXPECT_EQ(1.0f, node[1].as<float>());
  EXPECT_NE(node[2].as<float>(), node[2].as<float>());
  EXPECT_EQ(std::numeric_limits<float>::infinity(), node[3].as<float>());
  EXPECT_EQ(-std::numeric_limits<float>::infinity(), node[4].as<float>());
  EXPECT_EQ(21, node[5].as<int>());
  EXPECT_EQ(13, node[6].as<int>());
}

TEST(LoadNodeTest, Binary) {
  Node node = Load(
      "[!!binary \"SGVsbG8sIFdvcmxkIQ==\", !!binary "
      "\"TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieS"
      "B0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIG"
      "x1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbi"
      "B0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZG"
      "dlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS"
      "4K\"]");
  EXPECT_EQ(Binary(reinterpret_cast<const unsigned char*>("Hello, World!"), 13),
            node[0].as<Binary>());
  EXPECT_EQ(Binary(reinterpret_cast<const unsigned char*>(
                       "Man is distinguished, not only by his reason, "
                       "but by this singular passion from other "
                       "animals, which is a lust of the mind, that by "
                       "a perseverance of delight in the continued and "
                       "indefatigable generation of knowledge, exceeds "
                       "the short vehemence of any carnal pleasure.\n"),
                   270),
            node[1].as<Binary>());
}

TEST(LoadNodeTest, IterateSequence) {
  Node node = Load("[1, 3, 5, 7]");
  int seq[] = {1, 3, 5, 7};
  int i = 0;
  for (const_iterator it = node.begin(); it != node.end(); ++it) {
    EXPECT_TRUE(i < 4);
    int x = seq[i++];
    EXPECT_EQ(x, it->as<int>());
  }
  EXPECT_EQ(4, i);
}

TEST(LoadNodeTest, IterateMap) {
  Node node = Load("{a: A, b: B, c: C}");
  int i = 0;
  for (const_iterator it = node.begin(); it != node.end(); ++it) {
    EXPECT_TRUE(i < 3);
    i++;
    EXPECT_EQ(it->second.as<char>(), it->first.as<char>() + 'A' - 'a');
  }
  EXPECT_EQ(3, i);
}

#ifdef BOOST_FOREACH
TEST(LoadNodeTest, ForEach) {
  Node node = Load("[1, 3, 5, 7]");
  int seq[] = {1, 3, 5, 7};
  int i = 0;
  BOOST_FOREACH (const Node& item, node) {
    int x = seq[i++];
    EXPECT_EQ(x, item.as<int>());
  }
}

TEST(LoadNodeTest, ForEachMap) {
  Node node = Load("{a: A, b: B, c: C}");
  BOOST_FOREACH (const const_iterator::value_type& p, node) {
    EXPECT_EQ(p.second.as<char>(), p.first.as<char>() + 'A' - 'a');
  }
}
#endif

TEST(LoadNodeTest, CloneScalar) {
  Node node = Load("!foo monkey");
  Node clone = Clone(node);
  EXPECT_FALSE(clone == node);
  EXPECT_EQ(clone.as<std::string>(), node.as<std::string>());
  EXPECT_EQ(clone.Tag(), node.Tag());
}

TEST(LoadNodeTest, CloneSeq) {
  Node node = Load("[1, 3, 5, 7]");
  Node clone = Clone(node);
  EXPECT_FALSE(clone == node);
  EXPECT_EQ(NodeType::Sequence, clone.Type());
  EXPECT_EQ(clone.size(), node.size());
  for (std::size_t i = 0; i < node.size(); i++) {
    EXPECT_EQ(clone[i].as<int>(), node[i].as<int>());
  }
}

TEST(LoadNodeTest, CloneMap) {
  Node node = Load("{foo: bar}");
  Node clone = Clone(node);
  EXPECT_FALSE(clone == node);
  EXPECT_EQ(NodeType::Map, clone.Type());
  EXPECT_EQ(clone.size(), node.size());
  EXPECT_EQ(clone["foo"].as<std::string>(), node["foo"].as<std::string>());
}

TEST(LoadNodeTest, CloneAlias) {
  Node node = Load("&foo [*foo]");
  Node clone = Clone(node);
  EXPECT_FALSE(clone == node);
  EXPECT_EQ(NodeType::Sequence, clone.Type());
  EXPECT_EQ(clone.size(), node.size());
  EXPECT_EQ(clone[0], clone);
}

TEST(LoadNodeTest, ForceInsertIntoMap) {
  Node node;
  node["a"] = "b";
  node.force_insert("x", "y");
  node.force_insert("a", 5);
  EXPECT_EQ(3, node.size());
  EXPECT_EQ(NodeType::Map, node.Type());
  bool ab = false;
  bool a5 = false;
  bool xy = false;
  for (const_iterator it = node.begin(); it != node.end(); ++it) {
    if (it->first.as<std::string>() == "a") {
      if (it->second.as<std::string>() == "b")
        ab = true;
      else if (it->second.as<std::string>() == "5")
        a5 = true;
    } else if (it->first.as<std::string>() == "x" &&
               it->second.as<std::string>() == "y")
      xy = true;
  }
  EXPECT_TRUE(ab);
  EXPECT_TRUE(a5);
  EXPECT_TRUE(xy);
}

TEST(LoadNodeTest, ResetNode) {
  Node node = Load("[1, 2, 3]");
  EXPECT_TRUE(!node.IsNull());
  Node other = node;
  node.reset();
  EXPECT_TRUE(node.IsNull());
  EXPECT_TRUE(!other.IsNull());
  node.reset(other);
  EXPECT_TRUE(!node.IsNull());
  EXPECT_EQ(node, other);
}

TEST(LoadNodeTest, EmptyString) {
  Node node = Load("\"\"");
  EXPECT_TRUE(!node.IsNull());
}

TEST(LoadNodeTest, DereferenceIteratorError) {
  Node node = Load("[{a: b}, 1, 2]");
  EXPECT_THROW(node.begin()->first.as<int>(), InvalidNode);
  EXPECT_EQ(true, (*node.begin()).IsMap());
  EXPECT_EQ(true, node.begin()->IsMap());
  EXPECT_THROW((*node.begin()->begin()).Type(), InvalidNode);
  EXPECT_THROW(node.begin()->begin()->Type(), InvalidNode);
}

TEST(NodeTest, MergeKeyScalarSupport) {
  Node node = Load("{<<: {a: 1}}");
  ASSERT_FALSE(!node["a"]);
  EXPECT_EQ(1, node["a"].as<int>());
}

TEST(NodeTest, MergeKeySequenceSupport) {
  Node node = Load("<<: [{a: 1}, {a: 2, b: 3}]");
  ASSERT_FALSE(!node["a"]);
  ASSERT_FALSE(!node["b"]);
  EXPECT_EQ(1, node["a"].as<int>());
  EXPECT_EQ(3, node["b"].as<int>());
}

TEST(NodeTest, EmitEmptyNode) {
  Node node;
  Emitter emitter;
  emitter << node;
  EXPECT_EQ("", std::string(emitter.c_str()));
}

TEST(NodeTest, ParseNodeStyle) {
  EXPECT_EQ(EmitterStyle::Flow, Load("[1, 2, 3]").Style());
  EXPECT_EQ(EmitterStyle::Flow, Load("{foo: bar}").Style());
  EXPECT_EQ(EmitterStyle::Block, Load("- foo\n- bar").Style());
  EXPECT_EQ(EmitterStyle::Block, Load("foo: bar").Style());
}
}
}
<commit_msg>Added more merge key tests.<commit_after>#include "yaml-cpp/yaml.h"  // IWYU pragma: keep

#include "gtest/gtest.h"

namespace YAML {
namespace {
TEST(LoadNodeTest, Reassign) {
  Node node = Load("foo");
  node = Node();
}

TEST(LoadNodeTest, FallbackValues) {
  Node node = Load("foo: bar\nx: 2");
  EXPECT_EQ("bar", node["foo"].as<std::string>());
  EXPECT_EQ("bar", node["foo"].as<std::string>("hello"));
  EXPECT_EQ("hello", node["baz"].as<std::string>("hello"));
  EXPECT_EQ(2, node["x"].as<int>());
  EXPECT_EQ(2, node["x"].as<int>(5));
  EXPECT_EQ(5, node["y"].as<int>(5));
}

TEST(LoadNodeTest, NumericConversion) {
  Node node = Load("[1.5, 1, .nan, .inf, -.inf, 0x15, 015]");
  EXPECT_EQ(1.5f, node[0].as<float>());
  EXPECT_EQ(1.5, node[0].as<double>());
  EXPECT_THROW(node[0].as<int>(), TypedBadConversion<int>);
  EXPECT_EQ(1, node[1].as<int>());
  EXPECT_EQ(1.0f, node[1].as<float>());
  EXPECT_NE(node[2].as<float>(), node[2].as<float>());
  EXPECT_EQ(std::numeric_limits<float>::infinity(), node[3].as<float>());
  EXPECT_EQ(-std::numeric_limits<float>::infinity(), node[4].as<float>());
  EXPECT_EQ(21, node[5].as<int>());
  EXPECT_EQ(13, node[6].as<int>());
}

TEST(LoadNodeTest, Binary) {
  Node node = Load(
      "[!!binary \"SGVsbG8sIFdvcmxkIQ==\", !!binary "
      "\"TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieS"
      "B0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIG"
      "x1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbi"
      "B0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZG"
      "dlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS"
      "4K\"]");
  EXPECT_EQ(Binary(reinterpret_cast<const unsigned char*>("Hello, World!"), 13),
            node[0].as<Binary>());
  EXPECT_EQ(Binary(reinterpret_cast<const unsigned char*>(
                       "Man is distinguished, not only by his reason, "
                       "but by this singular passion from other "
                       "animals, which is a lust of the mind, that by "
                       "a perseverance of delight in the continued and "
                       "indefatigable generation of knowledge, exceeds "
                       "the short vehemence of any carnal pleasure.\n"),
                   270),
            node[1].as<Binary>());
}

TEST(LoadNodeTest, IterateSequence) {
  Node node = Load("[1, 3, 5, 7]");
  int seq[] = {1, 3, 5, 7};
  int i = 0;
  for (const_iterator it = node.begin(); it != node.end(); ++it) {
    EXPECT_TRUE(i < 4);
    int x = seq[i++];
    EXPECT_EQ(x, it->as<int>());
  }
  EXPECT_EQ(4, i);
}

TEST(LoadNodeTest, IterateMap) {
  Node node = Load("{a: A, b: B, c: C}");
  int i = 0;
  for (const_iterator it = node.begin(); it != node.end(); ++it) {
    EXPECT_TRUE(i < 3);
    i++;
    EXPECT_EQ(it->second.as<char>(), it->first.as<char>() + 'A' - 'a');
  }
  EXPECT_EQ(3, i);
}

#ifdef BOOST_FOREACH
TEST(LoadNodeTest, ForEach) {
  Node node = Load("[1, 3, 5, 7]");
  int seq[] = {1, 3, 5, 7};
  int i = 0;
  BOOST_FOREACH (const Node& item, node) {
    int x = seq[i++];
    EXPECT_EQ(x, item.as<int>());
  }
}

TEST(LoadNodeTest, ForEachMap) {
  Node node = Load("{a: A, b: B, c: C}");
  BOOST_FOREACH (const const_iterator::value_type& p, node) {
    EXPECT_EQ(p.second.as<char>(), p.first.as<char>() + 'A' - 'a');
  }
}
#endif

TEST(LoadNodeTest, CloneScalar) {
  Node node = Load("!foo monkey");
  Node clone = Clone(node);
  EXPECT_FALSE(clone == node);
  EXPECT_EQ(clone.as<std::string>(), node.as<std::string>());
  EXPECT_EQ(clone.Tag(), node.Tag());
}

TEST(LoadNodeTest, CloneSeq) {
  Node node = Load("[1, 3, 5, 7]");
  Node clone = Clone(node);
  EXPECT_FALSE(clone == node);
  EXPECT_EQ(NodeType::Sequence, clone.Type());
  EXPECT_EQ(clone.size(), node.size());
  for (std::size_t i = 0; i < node.size(); i++) {
    EXPECT_EQ(clone[i].as<int>(), node[i].as<int>());
  }
}

TEST(LoadNodeTest, CloneMap) {
  Node node = Load("{foo: bar}");
  Node clone = Clone(node);
  EXPECT_FALSE(clone == node);
  EXPECT_EQ(NodeType::Map, clone.Type());
  EXPECT_EQ(clone.size(), node.size());
  EXPECT_EQ(clone["foo"].as<std::string>(), node["foo"].as<std::string>());
}

TEST(LoadNodeTest, CloneAlias) {
  Node node = Load("&foo [*foo]");
  Node clone = Clone(node);
  EXPECT_FALSE(clone == node);
  EXPECT_EQ(NodeType::Sequence, clone.Type());
  EXPECT_EQ(clone.size(), node.size());
  EXPECT_EQ(clone[0], clone);
}

TEST(LoadNodeTest, ForceInsertIntoMap) {
  Node node;
  node["a"] = "b";
  node.force_insert("x", "y");
  node.force_insert("a", 5);
  EXPECT_EQ(3, node.size());
  EXPECT_EQ(NodeType::Map, node.Type());
  bool ab = false;
  bool a5 = false;
  bool xy = false;
  for (const_iterator it = node.begin(); it != node.end(); ++it) {
    if (it->first.as<std::string>() == "a") {
      if (it->second.as<std::string>() == "b")
        ab = true;
      else if (it->second.as<std::string>() == "5")
        a5 = true;
    } else if (it->first.as<std::string>() == "x" &&
               it->second.as<std::string>() == "y")
      xy = true;
  }
  EXPECT_TRUE(ab);
  EXPECT_TRUE(a5);
  EXPECT_TRUE(xy);
}

TEST(LoadNodeTest, ResetNode) {
  Node node = Load("[1, 2, 3]");
  EXPECT_TRUE(!node.IsNull());
  Node other = node;
  node.reset();
  EXPECT_TRUE(node.IsNull());
  EXPECT_TRUE(!other.IsNull());
  node.reset(other);
  EXPECT_TRUE(!node.IsNull());
  EXPECT_EQ(node, other);
}

TEST(LoadNodeTest, EmptyString) {
  Node node = Load("\"\"");
  EXPECT_TRUE(!node.IsNull());
}

TEST(LoadNodeTest, DereferenceIteratorError) {
  Node node = Load("[{a: b}, 1, 2]");
  EXPECT_THROW(node.begin()->first.as<int>(), InvalidNode);
  EXPECT_EQ(true, (*node.begin()).IsMap());
  EXPECT_EQ(true, node.begin()->IsMap());
  EXPECT_THROW((*node.begin()->begin()).Type(), InvalidNode);
  EXPECT_THROW(node.begin()->begin()->Type(), InvalidNode);
}

TEST(NodeTest, MergeKeyScalarSupport) {
  Node node = Load("{<<: {a: 1}}");
  ASSERT_FALSE(!node["a"]);
  EXPECT_EQ(1, node["a"].as<int>());
}

TEST(NodeTest, MergeKeyExistingKey) {
  Node node = Load("{a: 1, <<: {a: 2}}");
  ASSERT_FALSE(!node["a"]);
  EXPECT_EQ(1, node["a"].as<int>());
}

TEST(NodeTest, MergeKeySequenceSupport) {
  Node node = Load("<<: [{a: 1}, {a: 2, b: 3}]");
  ASSERT_FALSE(!node["a"]);
  ASSERT_FALSE(!node["b"]);
  EXPECT_EQ(1, node["a"].as<int>());
  EXPECT_EQ(3, node["b"].as<int>());
}

TEST(NodeTest, NestedMergeKeys) {
  Node node = Load("{<<: {<<: {a: 1}}}");
  ASSERT_FALSE(!node["a"]);
  EXPECT_EQ(1, node["a"].as<int>());
}

TEST(NodeTest, EmitEmptyNode) {
  Node node;
  Emitter emitter;
  emitter << node;
  EXPECT_EQ("", std::string(emitter.c_str()));
}

TEST(NodeTest, ParseNodeStyle) {
  EXPECT_EQ(EmitterStyle::Flow, Load("[1, 2, 3]").Style());
  EXPECT_EQ(EmitterStyle::Flow, Load("{foo: bar}").Style());
  EXPECT_EQ(EmitterStyle::Block, Load("- foo\n- bar").Style());
  EXPECT_EQ(EmitterStyle::Block, Load("foo: bar").Style());
}
}
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: seriesmodel.hxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef OOX_DRAWINGML_CHART_SERIESMODEL_HXX
#define OOX_DRAWINGML_CHART_SERIESMODEL_HXX

#include "oox/drawingml/chart/datasourcemodel.hxx"
#include "oox/drawingml/chart/titlemodel.hxx"

namespace oox {
namespace drawingml {
namespace chart {

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

struct DataLabelModelBase
{
    typedef ModelRef< Shape >       ShapeRef;
    typedef ModelRef< TextBody >    TextBodyRef;

    ShapeRef            mxShapeProp;            /// Data label frame formatting.
    TextBodyRef         mxTextProp;             /// Data label text formatting.
    OptValue< ::rtl::OUString > moaFormatCode;  /// Number format for numeric labels.
    OptValue< ::rtl::OUString > moaSeparator;   /// Separator between label components.
    OptValue< sal_Int32 > monLabelPos;          /// Data label position.
    OptValue< bool >    mobShowBubbleSize;      /// True = show size of bubbles in bubble charts.
    OptValue< bool >    mobShowCatName;         /// True = show category name of data points.
    OptValue< bool >    mobShowLegendKey;       /// True = show legend key of data series.
    OptValue< bool >    mobShowPercent;         /// True = show percentual value in pie/doughnut charts.
    OptValue< bool >    mobShowSerName;         /// True = show series name.
    OptValue< bool >    mobShowVal;             /// True = show data point value.
    OptValue< bool >    mobSourceLinked;        /// True = number format linked to source data.
    bool                mbDeleted;              /// True = data label(s) deleted.

    explicit            DataLabelModelBase();
                        ~DataLabelModelBase();
};

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

struct DataLabelModel : public DataLabelModelBase
{
    typedef ModelRef< LayoutModel > LayoutRef;
    typedef ModelRef< TextModel >   TextRef;

    LayoutRef           mxLayout;           /// Layout/position of the data point label frame.
    TextRef             mxText;             /// Manual or linked text for this data point label.
    sal_Int32           mnIndex;            /// Data point index for this data label.

    explicit            DataLabelModel();
                        ~DataLabelModel();
};

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

struct DataLabelsModel : public DataLabelModelBase
{
    typedef ModelVector< DataLabelModel >   DataLabelVector;
    typedef ModelRef< Shape >               ShapeRef;

    DataLabelVector     maPointLabels;      /// Settings for individual data point labels.
    ShapeRef            mxLeaderLines;      /// Formatting of connector lines between data points and labels.
    OptValue< bool >    mobShowLeaderLines; /// True = show connector lines between data points and labels.

    explicit            DataLabelsModel();
                        ~DataLabelsModel();
};

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

struct ErrorBarModel
{
    enum SourceType
    {
        PLUS,               /// Plus error bar values.
        MINUS               /// Minus error bar values.
    };

    typedef ModelMap< SourceType, DataSourceModel > DataSourceMap;
    typedef ModelRef< Shape >                       ShapeRef;

    DataSourceMap       maSources;          /// Source ranges for manual error bar values.
    ShapeRef            mxShapeProp;        /// Error line formatting.
    double              mfValue;            /// Fixed value for several error bar types.
    sal_Int32           mnDirection;        /// Direction of the error bars (x/y).
    sal_Int32           mnTypeId;           /// Type of the error bars (plus/minus/both).
    sal_Int32           mnValueType;        /// Type of the values.
    bool                mbNoEndCap;         /// True = no end cap at error bar lines.

    explicit            ErrorBarModel();
                        ~ErrorBarModel();
};

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

struct TrendlineModel
{
    typedef ModelRef< Shape > ShapeRef;

    ShapeRef            mxShapeProp;        /// Trendline formatting.
    ::rtl::OUString     maName;             /// User-defined name of the trendline.
    OptValue< double >  mfBackward;         /// Size of trendline before first data point.
    OptValue< double >  mfForward;          /// Size of trendline behind last data point.
    OptValue< double >  mfIntercept;        /// Crossing point with Y axis.
    sal_Int32           mnOrder;            /// Polynomial order in range [2, 6].
    sal_Int32           mnPeriod;           /// Moving average period in range [2, 255].
    sal_Int32           mnTypeId;           /// Type of the trendline.
    bool                mbDispEquation;     /// True = show equation of the trendline.
    bool                mbDispRSquared;     /// True = show R-squared of the trendline.

    explicit            TrendlineModel();
                        ~TrendlineModel();
};

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

struct DataPointModel
{
    typedef ModelRef< Shape > ShapeRef;

    ShapeRef            mxShapeProp;        /// Data point formatting.
    ShapeRef            mxMarkerProp;       /// Data point marker formatting.
    OptValue< sal_Int32 > monExplosion;     /// Pie slice moved from pie center.
    OptValue< sal_Int32 > monMarkerSize;    /// Size of the series line marker (2...72).
    OptValue< sal_Int32 > monMarkerSymbol;  /// Series line marker symbol.
    OptValue< bool >    mobBubble3d;        /// True = show bubbles with 3D shade.
    sal_Int32           mnIndex;            /// Unique data point index.
    bool                mbInvertNeg;        /// True = invert negative data points (not derived from series!).

    explicit            DataPointModel();
                        ~DataPointModel();
};

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

struct SeriesModel
{
    enum SourceType
    {
        CATEGORIES,         /// Data point categories.
        VALUES,             /// Data point values.
        POINTS              /// Data point size (e.g. bubble size in bubble charts).
    };

    typedef ModelMap< SourceType, DataSourceModel > DataSourceMap;
    typedef ModelVector< ErrorBarModel >            ErrorBarVector;
    typedef ModelVector< TrendlineModel >           TrendlineVector;
    typedef ModelVector< DataPointModel >           DataPointVector;
    typedef ModelRef< Shape >                       ShapeRef;
    typedef ModelRef< TextModel >                   TextRef;
    typedef ModelRef< DataLabelsModel >             DataLabelsRef;

    DataSourceMap       maSources;          /// Series source ranges.
    ErrorBarVector      maErrorBars;        /// All error bars of this series.
    TrendlineVector     maTrendlines;       /// All trendlines of this series.
    DataPointVector     maPoints;           /// Explicit formatted data points.
    ShapeRef            mxShapeProp;        /// Series formatting.
    ShapeRef            mxMarkerProp;       /// Data point marker formatting.
    TextRef             mxText;             /// Series title source.
    DataLabelsRef       mxLabels;           /// Data point label settings for all points.
    OptValue< sal_Int32 > monShape;         /// 3D bar shape type.
    sal_Int32           mnExplosion;        /// Pie slice moved from pie center.
    sal_Int32           mnIndex;            /// Series index used for automatic formatting.
    sal_Int32           mnMarkerSize;       /// Size of the series line marker (2...72).
    sal_Int32           mnMarkerSymbol;     /// Series line marker symbol.
    sal_Int32           mnOrder;            /// Series order.
    bool                mbBubble3d;         /// True = show bubbles with 3D shade.
    bool                mbInvertNeg;        /// True = invert negative data points.
    bool                mbSmooth;           /// True = smooth series line.

    explicit            SeriesModel();
                        ~SeriesModel();
};

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

} // namespace chart
} // namespace drawingml
} // namespace oox

#endif

<commit_msg>INTEGRATION: CWS xmlfilter06 (1.4.6); FILE MERGED 2008/06/25 14:58:38 dr 1.4.6.2: import chart data point labels and trendline label 2008/05/27 10:40:29 dr 1.4.6.1: joined changes from CWS xmlfilter05<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: seriesmodel.hxx,v $
 * $Revision: 1.6 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef OOX_DRAWINGML_CHART_SERIESMODEL_HXX
#define OOX_DRAWINGML_CHART_SERIESMODEL_HXX

#include "oox/drawingml/chart/datasourcemodel.hxx"
#include "oox/drawingml/chart/titlemodel.hxx"

namespace oox {
namespace drawingml {
namespace chart {

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

struct DataLabelModelBase
{
    typedef ModelRef< Shape >       ShapeRef;
    typedef ModelRef< TextBody >    TextBodyRef;

    ShapeRef            mxShapeProp;        /// Data label frame formatting.
    TextBodyRef         mxTextProp;         /// Data label text formatting.
    NumberFormat        maNumberFormat;     /// Number format for numeric data labels.
    OptValue< ::rtl::OUString > moaSeparator;/// Separator between label components.
    OptValue< sal_Int32 > monLabelPos;      /// Data label position.
    OptValue< bool >    mobShowBubbleSize;  /// True = show size of bubbles in bubble charts.
    OptValue< bool >    mobShowCatName;     /// True = show category name of data points.
    OptValue< bool >    mobShowLegendKey;   /// True = show legend key of data series.
    OptValue< bool >    mobShowPercent;     /// True = show percentual value in pie/doughnut charts.
    OptValue< bool >    mobShowSerName;     /// True = show series name.
    OptValue< bool >    mobShowVal;         /// True = show data point value.
    bool                mbDeleted;          /// True = data label(s) deleted.

    explicit            DataLabelModelBase();
                        ~DataLabelModelBase();
};

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

struct DataLabelModel : public DataLabelModelBase
{
    typedef ModelRef< LayoutModel > LayoutRef;
    typedef ModelRef< TextModel >   TextRef;

    LayoutRef           mxLayout;           /// Layout/position of the data point label frame.
    TextRef             mxText;             /// Manual or linked text for this data point label.
    sal_Int32           mnIndex;            /// Data point index for this data label.

    explicit            DataLabelModel();
                        ~DataLabelModel();
};

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

struct DataLabelsModel : public DataLabelModelBase
{
    typedef ModelVector< DataLabelModel >   DataLabelVector;
    typedef ModelRef< Shape >               ShapeRef;

    DataLabelVector     maPointLabels;      /// Settings for individual data point labels.
    ShapeRef            mxLeaderLines;      /// Formatting of connector lines between data points and labels.
    bool                mbShowLeaderLines;  /// True = show connector lines between data points and labels.

    explicit            DataLabelsModel();
                        ~DataLabelsModel();
};

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

struct ErrorBarModel
{
    enum SourceType
    {
        PLUS,               /// Plus error bar values.
        MINUS               /// Minus error bar values.
    };

    typedef ModelMap< SourceType, DataSourceModel > DataSourceMap;
    typedef ModelRef< Shape >                       ShapeRef;

    DataSourceMap       maSources;          /// Source ranges for manual error bar values.
    ShapeRef            mxShapeProp;        /// Error line formatting.
    double              mfValue;            /// Fixed value for several error bar types.
    sal_Int32           mnDirection;        /// Direction of the error bars (x/y).
    sal_Int32           mnTypeId;           /// Type of the error bars (plus/minus/both).
    sal_Int32           mnValueType;        /// Type of the values.
    bool                mbNoEndCap;         /// True = no end cap at error bar lines.

    explicit            ErrorBarModel();
                        ~ErrorBarModel();
};

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

struct TrendlineLabelModel
{
    typedef ModelRef< Shape >       ShapeRef;
    typedef ModelRef< TextBody >    TextBodyRef;
    typedef ModelRef< LayoutModel > LayoutRef;
    typedef ModelRef< TextModel >   TextRef;

    ShapeRef            mxShapeProp;        /// Label frame formatting.
    TextBodyRef         mxTextProp;         /// Label text formatting.
    LayoutRef           mxLayout;           /// Layout/position of the frame.
    TextRef             mxText;             /// Text source of the label.
    NumberFormat        maNumberFormat;     /// Number format for coefficients.

    explicit            TrendlineLabelModel();
                        ~TrendlineLabelModel();
};

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

struct TrendlineModel
{
    typedef ModelRef< Shape >               ShapeRef;
    typedef ModelRef< TrendlineLabelModel > TrendlineLabelRef;

    ShapeRef            mxShapeProp;        /// Trendline formatting.
    TrendlineLabelRef   mxLabel;            /// Trendline label text object.
    ::rtl::OUString     maName;             /// User-defined name of the trendline.
    OptValue< double >  mfBackward;         /// Size of trendline before first data point.
    OptValue< double >  mfForward;          /// Size of trendline behind last data point.
    OptValue< double >  mfIntercept;        /// Crossing point with Y axis.
    sal_Int32           mnOrder;            /// Polynomial order in range [2, 6].
    sal_Int32           mnPeriod;           /// Moving average period in range [2, 255].
    sal_Int32           mnTypeId;           /// Type of the trendline.
    bool                mbDispEquation;     /// True = show equation of the trendline.
    bool                mbDispRSquared;     /// True = show R-squared of the trendline.

    explicit            TrendlineModel();
                        ~TrendlineModel();
};

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

struct DataPointModel
{
    typedef ModelRef< Shape > ShapeRef;

    ShapeRef            mxShapeProp;        /// Data point formatting.
    ShapeRef            mxMarkerProp;       /// Data point marker formatting.
    OptValue< sal_Int32 > monExplosion;     /// Pie slice moved from pie center.
    OptValue< sal_Int32 > monMarkerSize;    /// Size of the series line marker (2...72).
    OptValue< sal_Int32 > monMarkerSymbol;  /// Series line marker symbol.
    OptValue< bool >    mobBubble3d;        /// True = show bubbles with 3D shade.
    sal_Int32           mnIndex;            /// Unique data point index.
    bool                mbInvertNeg;        /// True = invert negative data points (not derived from series!).

    explicit            DataPointModel();
                        ~DataPointModel();
};

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

struct SeriesModel
{
    enum SourceType
    {
        CATEGORIES,         /// Data point categories.
        VALUES,             /// Data point values.
        POINTS              /// Data point size (e.g. bubble size in bubble charts).
    };

    typedef ModelMap< SourceType, DataSourceModel > DataSourceMap;
    typedef ModelVector< ErrorBarModel >            ErrorBarVector;
    typedef ModelVector< TrendlineModel >           TrendlineVector;
    typedef ModelVector< DataPointModel >           DataPointVector;
    typedef ModelRef< Shape >                       ShapeRef;
    typedef ModelRef< TextModel >                   TextRef;
    typedef ModelRef< DataLabelsModel >             DataLabelsRef;

    DataSourceMap       maSources;          /// Series source ranges.
    ErrorBarVector      maErrorBars;        /// All error bars of this series.
    TrendlineVector     maTrendlines;       /// All trendlines of this series.
    DataPointVector     maPoints;           /// Explicit formatted data points.
    ShapeRef            mxShapeProp;        /// Series formatting.
    ShapeRef            mxMarkerProp;       /// Data point marker formatting.
    TextRef             mxText;             /// Series title source.
    DataLabelsRef       mxLabels;           /// Data point label settings for all points.
    OptValue< sal_Int32 > monShape;         /// 3D bar shape type.
    sal_Int32           mnExplosion;        /// Pie slice moved from pie center.
    sal_Int32           mnIndex;            /// Series index used for automatic formatting.
    sal_Int32           mnMarkerSize;       /// Size of the series line marker (2...72).
    sal_Int32           mnMarkerSymbol;     /// Series line marker symbol.
    sal_Int32           mnOrder;            /// Series order.
    bool                mbBubble3d;         /// True = show bubbles with 3D shade.
    bool                mbInvertNeg;        /// True = invert negative data points.
    bool                mbSmooth;           /// True = smooth series line.

    explicit            SeriesModel();
                        ~SeriesModel();
};

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

} // namespace chart
} // namespace drawingml
} // namespace oox

#endif

<|endoftext|>


<commit_before>#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

namespace Bor{

class EndianReader{
public:
    EndianReader(ifstream & stream):
    stream(stream){
    }

    virtual int8_t readByte1(){
        return convert(readBytes(sizeof(int8_t)));
    }

    virtual int16_t readByte2(){
        return convert(readBytes(sizeof(int16_t)));
    }

    virtual int32_t readByte4(){
        return convert(readBytes(sizeof(int32_t)));
    }

    virtual string readString(int length){
        ostringstream out;
        vector<uint8_t> bytes = readBytes(length);
        for (vector<uint8_t>::iterator it = bytes.begin(); it != bytes.end(); it++){
            char byte = *it;
            if (byte == 0){
                break;
            }
            out << *it;
        }
        return out.str();
    }

    virtual void seekEnd(int where){
        stream.seekg(where, ios::end);
    }

    virtual void seek(int where){
        stream.seekg(where);
    }

    virtual int position(){
        return stream.tellg();
    }

protected:
    virtual int32_t convert(const vector<uint8_t> & bytes) = 0;

    vector<uint8_t> readBytes(int length){
        vector<uint8_t> bytes;
        for (int i = 0; i < length; i++){
            uint8_t byte;
            stream >> byte;
            bytes.push_back(byte);
        }
        return bytes;
    }

    ifstream & stream;
};

class LittleEndianReader: public EndianReader {
public:
    LittleEndianReader(ifstream & stream):
    EndianReader(stream){
    }
protected:
    virtual int32_t convert(const vector<uint8_t> & bytes){
        int32_t out = 0;
        for (vector<uint8_t>::const_reverse_iterator it = bytes.rbegin(); it != bytes.rend(); it++){
            out = (out << 8) + *it;
        }
        return out;
    }
};

class BigEndianReader: public EndianReader {
public:
    BigEndianReader(ifstream & stream):
    EndianReader(stream){
    }
protected:
    virtual int32_t convert(const vector<uint8_t> & bytes){
        int32_t out = 0;
        for (vector<uint8_t>::const_iterator it = bytes.begin(); it != bytes.end(); it++){
            out = (out << 8) + *it;
        }
        return out;
    }
};

/* Reads Bor/Openbor packfiles */
class PackReader{
public:
    PackReader(const string & filename){
        ifstream stream;
        stream.open(filename.c_str(), std::ios::in | std::ios::binary);
        LittleEndianReader reader(stream);
        uint32_t magic = reader.readByte4();
        if (magic != MAGIC){
            cout << "Not a packfile! " << std::hex << magic << endl;
        } else {
            cout << "Ok got a packfile" << endl;
        }
        uint32_t version = reader.readByte4();
        reader.seekEnd(-4);
        uint32_t headerPosition = reader.readByte4();
        reader.seek(headerPosition);

        cout << "Header at " << headerPosition << endl;

        bool done = false;
        while (!done){
            uint32_t current = reader.position();
            uint32_t length = reader.readByte4();
            uint32_t start = reader.readByte4();
            uint32_t size = reader.readByte4();
            string name = reader.readString(80);
            done = name.size() == 0;
            cout << name << " at " << start << " size " << size << endl;
            cout << " seek to " << (current + length) << endl;
            reader.seek(current + length);
            done |= stream.eof();
        }
    }

private:
    static const uint32_t MAGIC = 0x4B434150;
};

}

int main(int argc, char ** argv){
    Bor::PackReader reader(argv[1]);
}
<commit_msg>some trivial fixes. use ifstream.read() instead of >><commit_after>#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

namespace Bor{

class EndianReader{
public:
    EndianReader(ifstream & stream):
    stream(stream){
    }

    virtual int8_t readByte1(){
        return convert(readBytes(sizeof(int8_t)));
    }

    virtual int16_t readByte2(){
        return convert(readBytes(sizeof(int16_t)));
    }

    virtual int32_t readByte4(){
        return convert(readBytes(sizeof(int32_t)));
    }

    virtual string readString(int length){
        ostringstream out;
        uint8_t letter = readByte1();
        while (letter != 0 && length > 0){
            out << letter;
            letter = readByte1();
        }
        return out.str();
    }

    virtual string readString2(int length){
        ostringstream out;
        vector<uint8_t> bytes = readBytes(length);
        for (vector<uint8_t>::iterator it = bytes.begin(); it != bytes.end(); it++){
            char byte = *it;
            if (byte == 0){
                break;
            }
            out << *it;
        }
        return out.str();
    }

    virtual void seekEnd(streamoff where){
        stream.seekg(where, ios::end);
    }

    virtual void seek(streampos where){
        stream.seekg(where);
    }

    virtual int position(){
        return stream.tellg();
    }

protected:
    virtual int32_t convert(const vector<uint8_t> & bytes) = 0;

    vector<uint8_t> readBytes(int length){
        vector<uint8_t> bytes;
        for (int i = 0; i < length; i++){
            uint8_t byte = 0;
            stream.read((char*) &byte, 1);
            if (stream.eof()){
                cout << "Stream eof!" << endl;
            } else {
            }
            bytes.push_back(byte);
        }
        return bytes;
    }

    ifstream & stream;
};

class LittleEndianReader: public EndianReader {
public:
    LittleEndianReader(ifstream & stream):
    EndianReader(stream){
    }
protected:
    virtual int32_t convert(const vector<uint8_t> & bytes){
        uint32_t out = 0;
        for (vector<uint8_t>::const_reverse_iterator it = bytes.rbegin(); it != bytes.rend(); it++){
            out = (out << 8) + *it;
        }
        return out;
    }
};

class BigEndianReader: public EndianReader {
public:
    BigEndianReader(ifstream & stream):
    EndianReader(stream){
    }
protected:
    virtual int32_t convert(const vector<uint8_t> & bytes){
        uint32_t out = 0;
        for (vector<uint8_t>::const_iterator it = bytes.begin(); it != bytes.end(); it++){
            out = (out << 8) + *it;
        }
        return out;
    }
};

/* Reads Bor/Openbor packfiles */
class PackReader{
public:
    PackReader(const string & filename){
        ifstream stream;
        // stream.rdbuf()->pubsetbuf(0, 0);
        stream.open(filename.c_str(), std::ios::in | std::ios::binary);
        LittleEndianReader reader(stream);
        uint32_t magic = reader.readByte4();
        if (magic != MAGIC){
            cout << "Not a packfile! " << std::hex << magic << endl;
            return;
        } else {
            cout << "Ok got a packfile" << endl;
        }
        cout << "Stream position is " << stream.tellg() << endl;
        uint32_t version = reader.readByte4();
        cout << "Version is " << version << endl;
        reader.seekEnd(-4);
        uint32_t headerPosition = reader.readByte4();
        reader.seek(headerPosition);

        cout << "Header at 0x" << std::hex << headerPosition << std::dec << endl;

        bool done = false;
        while (!done){
            uint32_t current = reader.position();
            uint32_t length = reader.readByte4();
            uint32_t start = reader.readByte4();
            uint32_t size = reader.readByte4();
            string name = reader.readString(80);
            done = name.size() == 0;
            cout << name << " at " << start << " size " << size << " length " << length << endl;
            // cout << " seek to " << (current + length) << endl;
            // reader.seek(current + length);
            done |= stream.eof();
        }
    }

private:
    static const uint32_t MAGIC = 0x4B434150;
};

}

int main(int argc, char ** argv){
    Bor::PackReader reader(argv[1]);
}
<|endoftext|>


<commit_before>//
//  main.cpp
//  C-Server
//
//  Created by Zackery leman & Chris Lu on 1/28/15.
//  Copyright (c) 2015 Zleman-Clu. All rights reserved.
//
#include <fcntl.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <iostream>
//using namespace std;
#define NUM_THREADS     5
#define MAX_BACKLOG     10
void *handeRequest(void *threadid)
{
    long tid;
    tid = (long)threadid;
    std::cout << "Handeling Request! Socket Descriptor, " << tid <<    std::endl;
    pthread_exit(NULL);
}

int main(int argc, const char * argv[]) {
    //Prints the comamnd line arguments
    std::cout << "argc = " << argc << std::endl;
    for(int i = 0; i < argc; i++)
        std::cout << "argv[" << i << "] = " << argv[i] << std::endl;

    // Create socket
    int sock_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (sock_fd < 0) {
        printf("error opening socket\n");
        return -1;
    }

    struct sockaddr_in myaddr;
    /*if (argv[i]){
     myaddr.sin_port = htons(argv[i]);
     }else{*/
    myaddr.sin_port = htons(8888); // use port default of 8888
    // }
    myaddr.sin_family = AF_INET;
    myaddr.sin_addr.s_addr = htonl(INADDR_ANY);

    //Bind Socket
    if(bind(sock_fd, (struct sockaddr*) &myaddr, sizeof(myaddr)) < 0) {
        // error opening socket
        return -1;
    }

    if(int listen_begin = listen(sock_fd, MAX_BACKLOG) < 0)
    {
        std::cout << "Error while establishing listening socket" << std::endl;
        return -1;
    }

    while(true)
    {
        int newSocketfd = accept(sock_fd, (struct sockaddr*) &myaddr, (socklen_t *) sizeof(myaddr));

        if( newSocketfd < 0)
        {
            std::cout << "Error while accepting" << std::endl;
            return -1;
        } else{

            pthread_t newThread;
            std::cout << "Creating  new thread " <<    std::endl;
            int rc = pthread_create(&newThread, NULL, handeRequest, (void *)newSocketfd);
            if (rc){
                std::cout << "Error:unable to create thread," << rc <<  std::endl;
                exit(-1);
            }

            int getMsg = recv(sock_fd, buf, buflen, 0);
            if (getMsg < 0)
            {
                cout << "Error while recieving HTTP request" << endl;
                exit(-1); //or break?
            }

        }

    }

    //close();

    std::cout <<"End!\n";

    return 0;

}

/*

 Forever loop:
 Listen for connections
 Accept new connection from incoming client
 Parse HTTP request
 Ensure well-formed request (return error otherwise)
 Determine if target file exists and if permissions are set properly (return error otherwise)
 Transmit contents of file to connect (by performing reads on the file and writes on the socket)
 Close the connection (if HTTP/1.0)

 */

<commit_msg>added to handle request<commit_after>//
//  main.cpp
//  C-Server
//
//  Created by Zackery leman & Chris Lu on 1/28/15.
//  Copyright (c) 2015 Zleman-Clu. All rights reserved.
//
#include <fcntl.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <iostream>
//using namespace std;
#define NUM_THREADS     5
#define MAX_BACKLOG     10
void *handeRequest(void *threadid)
{
    long tid;
    tid = (long)threadid;
    std::cout << "Handeling Request! Socket Descriptor, " << tid <<    std::endl;
    int getMsg = recv(sock_fd, buf, buflen, 0);
    if (getMsg < 0)
    {
        cout << "Error while recieving HTTP request" << endl;
        exit(-1); //or break?
    }
    pthread_exit(NULL);
}

int main(int argc, const char * argv[]) {
    //Prints the comamnd line arguments
    std::cout << "argc = " << argc << std::endl;
    for(int i = 0; i < argc; i++)
        std::cout << "argv[" << i << "] = " << argv[i] << std::endl;

    // Create socket
    int sock_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (sock_fd < 0) {
        printf("error opening socket\n");
        return -1;
    }

    struct sockaddr_in myaddr;
    /*if (argv[i]){
     myaddr.sin_port = htons(argv[i]);
     }else{*/
    myaddr.sin_port = htons(8888); // use port default of 8888
    // }
    myaddr.sin_family = AF_INET;
    myaddr.sin_addr.s_addr = htonl(INADDR_ANY);

    //Bind Socket
    if(bind(sock_fd, (struct sockaddr*) &myaddr, sizeof(myaddr)) < 0) {
        // error opening socket
        return -1;
    }

    if(int listen_begin = listen(sock_fd, MAX_BACKLOG) < 0)
    {
        std::cout << "Error while establishing listening socket" << std::endl;
        return -1;
    }

    while(true)
    {
        int newSocketfd = accept(sock_fd, (struct sockaddr*) &myaddr, (socklen_t *) sizeof(myaddr));

        if( newSocketfd < 0)
        {
            std::cout << "Error while accepting" << std::endl;
            return -1;
        } else{

            pthread_t newThread;
            std::cout << "Creating  new thread " <<    std::endl;
            int rc = pthread_create(&newThread, NULL, handeRequest, (void *)newSocketfd);
            if (rc){
                std::cout << "Error:unable to create thread," << rc <<  std::endl;
                exit(-1);
            }
        }

    }

    //close();

    std::cout <<"End!\n";

    return 0;

}

/*

 Forever loop:
 Listen for connections
 Accept new connection from incoming client
 Parse HTTP request
 Ensure well-formed request (return error otherwise)
 Determine if target file exists and if permissions are set properly (return error otherwise)
 Transmit contents of file to connect (by performing reads on the file and writes on the socket)
 Close the connection (if HTTP/1.0)

 */

<|endoftext|>


<commit_before>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4      *
*                (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS                    *
*                                                                             *
* This library is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this library; if not, write to the Free Software Foundation,     *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *
*******************************************************************************
*                              SOFA :: Framework                              *
*                                                                             *
* Authors: M. Adam, J. Allard, B. Andre, P-J. Bensoussan, S. Cotin, C. Duriez,*
* H. Delingette, F. Falipou, F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza,  *
* M. Nesme, P. Neumann, J-P. de la Plata Alcade, F. Poyer and F. Roy          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#include <sofa/core/behavior/BaseMechanicalState.h>

namespace sofa
{

namespace core
{

namespace behavior
{

BaseMechanicalState::BaseMechanicalState()
    : useMask(initData(&useMask, true, "useMask", "Usage of a mask to optimize the computation of the system, highly reducing the passage through the mappings")), forceMask(helper::ParticleMask(useMask.beginEdit()))
{
    useMask.endEdit();
}

BaseMechanicalState::~BaseMechanicalState()
{
}

/// Perform a sequence of linear vector accumulation operation $r_i = sum_j (v_j*f_{ij})$
///
/// This is used to compute in on steps operations such as $v = v + a*dt, x = x + v*dt$.
/// Note that if the result vector appears inside the expression, it must be the first operand.
/// By default this method decompose the computation into multiple vOp calls.
void BaseMechanicalState::vMultiOp(const VMultiOp& ops)
{
    for(VMultiOp::const_iterator it = ops.begin(), itend = ops.end(); it != itend; ++it)
    {
        VecId r = it->first;
        const helper::vector< std::pair< ConstVecId, double > >& operands = it->second;
        int nop = operands.size();
        if (nop==0)
        {
            vOp(r);
        }
        else if (nop==1)
        {
            if (operands[0].second == 1.0)
                vOp(r, operands[0].first);
            else
                vOp(r, ConstVecId::null(), operands[0].first, operands[0].second);
        }
        else
        {
            int i;
            if (operands[0].second == 1.0)
            {
                vOp(r, operands[0].first, operands[1].first, operands[1].second);
                i = 2;
            }
            else
            {
                vOp(r, ConstVecId::null(), operands[0].first, operands[0].second);
                i = 1;
            }
            for (; i<nop; ++i)
                vOp(r, r, operands[i].first, operands[i].second);
        }
    }
}

} // namespace behavior

} // namespace core

} // namespace sofa
<commit_msg>r8278/sofa-dev : FIX : Warning.<commit_after>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4      *
*                (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS                    *
*                                                                             *
* This library is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this library; if not, write to the Free Software Foundation,     *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *
*******************************************************************************
*                              SOFA :: Framework                              *
*                                                                             *
* Authors: M. Adam, J. Allard, B. Andre, P-J. Bensoussan, S. Cotin, C. Duriez,*
* H. Delingette, F. Falipou, F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza,  *
* M. Nesme, P. Neumann, J-P. de la Plata Alcade, F. Poyer and F. Roy          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#include <sofa/core/behavior/BaseMechanicalState.h>

namespace sofa
{

namespace core
{

namespace behavior
{

BaseMechanicalState::BaseMechanicalState()
    : useMask(initData(&useMask, true, "useMask", "Usage of a mask to optimize the computation of the system, highly reducing the passage through the mappings"))
    , forceMask(helper::ParticleMask(useMask.getValue()))
{
}

BaseMechanicalState::~BaseMechanicalState()
{
}

/// Perform a sequence of linear vector accumulation operation $r_i = sum_j (v_j*f_{ij})$
///
/// This is used to compute in on steps operations such as $v = v + a*dt, x = x + v*dt$.
/// Note that if the result vector appears inside the expression, it must be the first operand.
/// By default this method decompose the computation into multiple vOp calls.
void BaseMechanicalState::vMultiOp(const VMultiOp& ops)
{
    for(VMultiOp::const_iterator it = ops.begin(), itend = ops.end(); it != itend; ++it)
    {
        VecId r = it->first;
        const helper::vector< std::pair< ConstVecId, double > >& operands = it->second;
        int nop = operands.size();
        if (nop==0)
        {
            vOp(r);
        }
        else if (nop==1)
        {
            if (operands[0].second == 1.0)
                vOp(r, operands[0].first);
            else
                vOp(r, ConstVecId::null(), operands[0].first, operands[0].second);
        }
        else
        {
            int i;
            if (operands[0].second == 1.0)
            {
                vOp(r, operands[0].first, operands[1].first, operands[1].second);
                i = 2;
            }
            else
            {
                vOp(r, ConstVecId::null(), operands[0].first, operands[0].second);
                i = 1;
            }
            for (; i<nop; ++i)
                vOp(r, r, operands[i].first, operands[i].second);
        }
    }
}

} // namespace behavior

} // namespace core

} // namespace sofa
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: edittoolbarcontroller.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: ihi $ $Date: 2006-08-01 09:38:44 $
 *
 *  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 __FRAMEWORK_UIELEMENT_EDITTOOLBARCONTROLLER_HXX
#include "uielement/edittoolbarcontroller.hxx"
#endif

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_TOOLBAR_HXX_
#include "uielement/toolbar.hxx"
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_
#include <com/sun/star/util/XURLTransformer.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_
#include <com/sun/star/frame/XDispatchProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_STATUS_ITEMSTATUS_HPP_
#include <com/sun/star/frame/status/ItemStatus.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_STATUS_ITEMSTATE_HPP_
#include <com/sun/star/frame/status/ItemState.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_STATUS_VISIBILITY_HPP_
#include <com/sun/star/frame/status/Visibility.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCONTROLNOTIFICATIONLISTENER_HPP_
#include <com/sun/star/frame/XControlNotificationListener.hpp>
#endif

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

#ifndef _SVTOOLS_TOOLBOXCONTROLLER_HXX
#include <svtools/toolboxcontroller.hxx>
#endif
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _VCL_MNEMONIC_HXX_
#include <vcl/mnemonic.hxx>
#endif
#include <tools/urlobj.hxx>

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;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::frame::status;
using namespace ::com::sun::star::util;

namespace framework
{

// ------------------------------------------------------------------

// Wrapper class to notify controller about events from edit.
// Unfortunaltly the events are notifed through virtual methods instead
// of Listeners.

class EditControl : public Edit
{
    public:
        EditControl( Window* pParent, WinBits nStyle, IEditListener* pEditListener );
        virtual ~EditControl();

        virtual void Modify();
        virtual void KeyInput( const ::KeyEvent& rKEvt );
        virtual void GetFocus();
        virtual void LoseFocus();
        virtual long PreNotify( NotifyEvent& rNEvt );

    private:
        IEditListener* m_pEditListener;
};

EditControl::EditControl( Window* pParent, WinBits nStyle, IEditListener* pEditListener ) :
    Edit( pParent, nStyle )
    , m_pEditListener( pEditListener )
{
}

EditControl::~EditControl()
{
    m_pEditListener = 0;
}

void EditControl::Modify()
{
    Edit::Modify();
    if ( m_pEditListener )
        m_pEditListener->Modify();
}

void EditControl::KeyInput( const ::KeyEvent& rKEvt )
{
    Edit::KeyInput( rKEvt );
    if ( m_pEditListener )
        m_pEditListener->KeyInput( rKEvt );
}

void EditControl::GetFocus()
{
    Edit::GetFocus();
    if ( m_pEditListener )
        m_pEditListener->GetFocus();
}

void EditControl::LoseFocus()
{
    Edit::LoseFocus();
    if ( m_pEditListener )
        m_pEditListener->LoseFocus();
}

long EditControl::PreNotify( NotifyEvent& rNEvt )
{
    long nRet( 0 );
    if ( m_pEditListener )
        nRet = m_pEditListener->PreNotify( rNEvt );
    if ( nRet == 0 )
        nRet = Edit::PreNotify( rNEvt );

    return nRet;
}

// ------------------------------------------------------------------

EditToolbarController::EditToolbarController(
    const Reference< XMultiServiceFactory >& rServiceManager,
    const Reference< XFrame >&               rFrame,
    ToolBar*                                 pToolbar,
    USHORT                                   nID,
    sal_Int32                                nWidth,
    const OUString&                          aCommand ) :
    ComplexToolbarController( rServiceManager, rFrame, pToolbar, nID, aCommand )
    ,   m_pEditControl( 0 )
{
    m_pEditControl = new EditControl( m_pToolbar, WB_BORDER, this );
    if ( nWidth == 0 )
        nWidth = 100;

    // Calculate height of the edit field according to the application font height
    sal_Int32 nHeight = getFontSizePixel( m_pEditControl ) + 6 + 1;

    m_pEditControl->SetSizePixel( ::Size( nWidth, nHeight ));
    m_pToolbar->SetItemWindow( m_nID, m_pEditControl );
}

// ------------------------------------------------------------------

EditToolbarController::~EditToolbarController()
{
}

// ------------------------------------------------------------------

void SAL_CALL EditToolbarController::dispose()
throw ( RuntimeException )
{
    vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );

    m_pToolbar->SetItemWindow( m_nID, 0 );
    delete m_pEditControl;

    ComplexToolbarController::dispose();

    m_pEditControl = 0;
}

// ------------------------------------------------------------------

void SAL_CALL EditToolbarController::execute( sal_Int16 KeyModifier )
throw ( RuntimeException )
{
    Reference< XDispatch >       xDispatch;
    Reference< XURLTransformer > xURLTransformer;
    OUString                     aCommandURL;
    OUString                     aSelectedText;
    ::com::sun::star::util::URL  aTargetURL;

    {
        vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );

        if ( m_bDisposed )
            throw DisposedException();

        if ( m_bInitialized &&
             m_xFrame.is() &&
             m_xServiceManager.is() &&
             m_aCommandURL.getLength() )
        {
            xURLTransformer = m_xURLTransformer;
            xDispatch = getDispatchFromCommand( m_aCommandURL );
            aCommandURL = m_aCommandURL;
            aTargetURL = getInitializedURL();
            aSelectedText = m_pEditControl->GetText();
        }
    }

    if ( xDispatch.is() && aTargetURL.Complete.getLength() > 0 )
    {
        Sequence<PropertyValue>   aArgs( 2 );

        // Add key modifier to argument list
        aArgs[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "KeyModifier" ));
        aArgs[0].Value <<= KeyModifier;
        aArgs[1].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Text" ));
        aArgs[1].Value <<= aSelectedText;

        // Execute dispatch asynchronously
        ExecuteInfo* pExecuteInfo = new ExecuteInfo;
        pExecuteInfo->xDispatch     = xDispatch;
        pExecuteInfo->aTargetURL    = aTargetURL;
        pExecuteInfo->aArgs         = aArgs;
        Application::PostUserEvent( STATIC_LINK(0, ComplexToolbarController , ExecuteHdl_Impl), pExecuteInfo );
    }
}

// ------------------------------------------------------------------

void EditToolbarController::Modify()
{
    notifyTextChanged( m_pEditControl->GetText() );
}

void EditToolbarController::KeyInput( const ::KeyEvent& /*rKEvt*/ )
{
}

void EditToolbarController::GetFocus()
{
    notifyFocusGet();
}

void EditToolbarController::LoseFocus()
{
    notifyFocusLost();
}

long EditToolbarController::PreNotify( NotifyEvent& rNEvt )
{
    if( rNEvt.GetType() == EVENT_KEYINPUT )
    {
        const ::KeyEvent* pKeyEvent = rNEvt.GetKeyEvent();
        const KeyCode& rKeyCode = pKeyEvent->GetKeyCode();
        if(( rKeyCode.GetModifier() | rKeyCode.GetCode()) == KEY_RETURN )
        {
            // Call execute only with non-empty text
            if ( m_pEditControl->GetText().Len() > 0 )
                execute( rKeyCode.GetModifier() );
            return 1;
        }
    }

    return 0;
}

// --------------------------------------------------------

void EditToolbarController::executeControlCommand( const ::com::sun::star::frame::ControlCommand& rControlCommand )
{
    if ( rControlCommand.Command.equalsAsciiL( "SetText", 7 ))
    {
        for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
        {
            if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Text", 4 ))
            {
                rtl::OUString aText;
                rControlCommand.Arguments[i].Value >>= aText;
                m_pEditControl->SetText( aText );

                // send notification
                notifyTextChanged( aText );
                break;
            }
        }
    }
}

} // namespace
<commit_msg>INTEGRATION: CWS pchfix02 (1.2.16); FILE MERGED 2006/09/01 17:29:26 kaib 1.2.16.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: edittoolbarcontroller.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 14:19:19 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_framework.hxx"

#ifndef __FRAMEWORK_UIELEMENT_EDITTOOLBARCONTROLLER_HXX
#include "uielement/edittoolbarcontroller.hxx"
#endif

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_TOOLBAR_HXX_
#include "uielement/toolbar.hxx"
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_
#include <com/sun/star/util/XURLTransformer.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_
#include <com/sun/star/frame/XDispatchProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_STATUS_ITEMSTATUS_HPP_
#include <com/sun/star/frame/status/ItemStatus.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_STATUS_ITEMSTATE_HPP_
#include <com/sun/star/frame/status/ItemState.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_STATUS_VISIBILITY_HPP_
#include <com/sun/star/frame/status/Visibility.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCONTROLNOTIFICATIONLISTENER_HPP_
#include <com/sun/star/frame/XControlNotificationListener.hpp>
#endif

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

#ifndef _SVTOOLS_TOOLBOXCONTROLLER_HXX
#include <svtools/toolboxcontroller.hxx>
#endif
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _VCL_MNEMONIC_HXX_
#include <vcl/mnemonic.hxx>
#endif
#include <tools/urlobj.hxx>

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;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::frame::status;
using namespace ::com::sun::star::util;

namespace framework
{

// ------------------------------------------------------------------

// Wrapper class to notify controller about events from edit.
// Unfortunaltly the events are notifed through virtual methods instead
// of Listeners.

class EditControl : public Edit
{
    public:
        EditControl( Window* pParent, WinBits nStyle, IEditListener* pEditListener );
        virtual ~EditControl();

        virtual void Modify();
        virtual void KeyInput( const ::KeyEvent& rKEvt );
        virtual void GetFocus();
        virtual void LoseFocus();
        virtual long PreNotify( NotifyEvent& rNEvt );

    private:
        IEditListener* m_pEditListener;
};

EditControl::EditControl( Window* pParent, WinBits nStyle, IEditListener* pEditListener ) :
    Edit( pParent, nStyle )
    , m_pEditListener( pEditListener )
{
}

EditControl::~EditControl()
{
    m_pEditListener = 0;
}

void EditControl::Modify()
{
    Edit::Modify();
    if ( m_pEditListener )
        m_pEditListener->Modify();
}

void EditControl::KeyInput( const ::KeyEvent& rKEvt )
{
    Edit::KeyInput( rKEvt );
    if ( m_pEditListener )
        m_pEditListener->KeyInput( rKEvt );
}

void EditControl::GetFocus()
{
    Edit::GetFocus();
    if ( m_pEditListener )
        m_pEditListener->GetFocus();
}

void EditControl::LoseFocus()
{
    Edit::LoseFocus();
    if ( m_pEditListener )
        m_pEditListener->LoseFocus();
}

long EditControl::PreNotify( NotifyEvent& rNEvt )
{
    long nRet( 0 );
    if ( m_pEditListener )
        nRet = m_pEditListener->PreNotify( rNEvt );
    if ( nRet == 0 )
        nRet = Edit::PreNotify( rNEvt );

    return nRet;
}

// ------------------------------------------------------------------

EditToolbarController::EditToolbarController(
    const Reference< XMultiServiceFactory >& rServiceManager,
    const Reference< XFrame >&               rFrame,
    ToolBar*                                 pToolbar,
    USHORT                                   nID,
    sal_Int32                                nWidth,
    const OUString&                          aCommand ) :
    ComplexToolbarController( rServiceManager, rFrame, pToolbar, nID, aCommand )
    ,   m_pEditControl( 0 )
{
    m_pEditControl = new EditControl( m_pToolbar, WB_BORDER, this );
    if ( nWidth == 0 )
        nWidth = 100;

    // Calculate height of the edit field according to the application font height
    sal_Int32 nHeight = getFontSizePixel( m_pEditControl ) + 6 + 1;

    m_pEditControl->SetSizePixel( ::Size( nWidth, nHeight ));
    m_pToolbar->SetItemWindow( m_nID, m_pEditControl );
}

// ------------------------------------------------------------------

EditToolbarController::~EditToolbarController()
{
}

// ------------------------------------------------------------------

void SAL_CALL EditToolbarController::dispose()
throw ( RuntimeException )
{
    vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );

    m_pToolbar->SetItemWindow( m_nID, 0 );
    delete m_pEditControl;

    ComplexToolbarController::dispose();

    m_pEditControl = 0;
}

// ------------------------------------------------------------------

void SAL_CALL EditToolbarController::execute( sal_Int16 KeyModifier )
throw ( RuntimeException )
{
    Reference< XDispatch >       xDispatch;
    Reference< XURLTransformer > xURLTransformer;
    OUString                     aCommandURL;
    OUString                     aSelectedText;
    ::com::sun::star::util::URL  aTargetURL;

    {
        vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );

        if ( m_bDisposed )
            throw DisposedException();

        if ( m_bInitialized &&
             m_xFrame.is() &&
             m_xServiceManager.is() &&
             m_aCommandURL.getLength() )
        {
            xURLTransformer = m_xURLTransformer;
            xDispatch = getDispatchFromCommand( m_aCommandURL );
            aCommandURL = m_aCommandURL;
            aTargetURL = getInitializedURL();
            aSelectedText = m_pEditControl->GetText();
        }
    }

    if ( xDispatch.is() && aTargetURL.Complete.getLength() > 0 )
    {
        Sequence<PropertyValue>   aArgs( 2 );

        // Add key modifier to argument list
        aArgs[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "KeyModifier" ));
        aArgs[0].Value <<= KeyModifier;
        aArgs[1].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Text" ));
        aArgs[1].Value <<= aSelectedText;

        // Execute dispatch asynchronously
        ExecuteInfo* pExecuteInfo = new ExecuteInfo;
        pExecuteInfo->xDispatch     = xDispatch;
        pExecuteInfo->aTargetURL    = aTargetURL;
        pExecuteInfo->aArgs         = aArgs;
        Application::PostUserEvent( STATIC_LINK(0, ComplexToolbarController , ExecuteHdl_Impl), pExecuteInfo );
    }
}

// ------------------------------------------------------------------

void EditToolbarController::Modify()
{
    notifyTextChanged( m_pEditControl->GetText() );
}

void EditToolbarController::KeyInput( const ::KeyEvent& /*rKEvt*/ )
{
}

void EditToolbarController::GetFocus()
{
    notifyFocusGet();
}

void EditToolbarController::LoseFocus()
{
    notifyFocusLost();
}

long EditToolbarController::PreNotify( NotifyEvent& rNEvt )
{
    if( rNEvt.GetType() == EVENT_KEYINPUT )
    {
        const ::KeyEvent* pKeyEvent = rNEvt.GetKeyEvent();
        const KeyCode& rKeyCode = pKeyEvent->GetKeyCode();
        if(( rKeyCode.GetModifier() | rKeyCode.GetCode()) == KEY_RETURN )
        {
            // Call execute only with non-empty text
            if ( m_pEditControl->GetText().Len() > 0 )
                execute( rKeyCode.GetModifier() );
            return 1;
        }
    }

    return 0;
}

// --------------------------------------------------------

void EditToolbarController::executeControlCommand( const ::com::sun::star::frame::ControlCommand& rControlCommand )
{
    if ( rControlCommand.Command.equalsAsciiL( "SetText", 7 ))
    {
        for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
        {
            if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Text", 4 ))
            {
                rtl::OUString aText;
                rControlCommand.Arguments[i].Value >>= aText;
                m_pEditControl->SetText( aText );

                // send notification
                notifyTextChanged( aText );
                break;
            }
        }
    }
}

} // namespace
<|endoftext|>


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

#include <gtest/gtest.h>
#include "include/restclienttest.hpp"
#include "../../../src/rest/client/include/restclient.hpp"

void RestClientTest::SetUp()
{
	get_url = "http://echo.jsontest.com/value/get";
	put_url = "http://httpbin.org/put";
	content_type = "application/json";
	client = new RestClient;
}

//---------------------------------------------
// GET
//---------------------------------------------

TEST_F(RestClientTest, GetReturns200WhenOk)
{
	// when
	rest_response response = client->get(get_url);
	// then
	EXPECT_EQ(200, response.code);
}

TEST_F(RestClientTest, GetReturnsValidResponseBody)
{
	// when
	rest_response response = client->get(get_url);
	// then
	EXPECT_EQ("{\"value\": \"get\"}\n", response.body);
}

TEST_F(RestClientTest, ShouldReturnValidResponseCodeWhenFails)
{
	rest_response response = client->get("http://nonexisting.org");
	EXPECT_EQ(-1, response.code);
}

//---------------------------------------------
// PUT
//---------------------------------------------

TEST_F(RestClientTest, ShouldReturn200WhenPUTSucceed)
{
	// given
	std::string data = "testdata";
	// when
	rest_response response = client->put(put_url, content_type, data);
	// then
	EXPECT_EQ(200, response.code);
}

TEST_F(RestClientTest, ShouldReturnValidResponseBody)
{
	// given
	std::string data = "testdata";
	// when
	rest_response response = client->put(put_url, content_type, data);
	size_t data_content_position = response.body.find(data);
	// then
 	ASSERT_TRUE(data_content_position != std::string::npos);
}

TEST_F(RestClientTest, ShouldReturnValidResponseCodeWhenPUTFails)
{
	// given
	std::string data = "testdata";
	// when
	rest_response response = client->put("http://nonexisting.org", content_type, data);
	// then
	EXPECT_EQ(-1, response.code);
}<commit_msg>Add short comments to the RestClient_ShouldReturnValidResponseCodeWhenFails<commit_after>/*
 * Copyright 2013 Kamil Michalak <kmichalak8@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include <gtest/gtest.h>
#include "include/restclienttest.hpp"
#include "../../../src/rest/client/include/restclient.hpp"

void RestClientTest::SetUp()
{
	get_url = "http://echo.jsontest.com/value/get";
	put_url = "http://httpbin.org/put";
	content_type = "application/json";
	client = new RestClient;
}

//---------------------------------------------
// GET
//---------------------------------------------

TEST_F(RestClientTest, GetReturns200WhenOk)
{
	// when
	rest_response response = client->get(get_url);
	// then
	EXPECT_EQ(200, response.code);
}

TEST_F(RestClientTest, GetReturnsValidResponseBody)
{
	// when
	rest_response response = client->get(get_url);
	// then
	EXPECT_EQ("{\"value\": \"get\"}\n", response.body);
}

TEST_F(RestClientTest, ShouldReturnValidResponseCodeWhenFails)
{
	// when
	rest_response response = client->get("http://nonexisting.org");
	// then
	EXPECT_EQ(-1, response.code);
}

//---------------------------------------------
// PUT
//---------------------------------------------

TEST_F(RestClientTest, ShouldReturn200WhenPUTSucceed)
{
	// given
	std::string data = "testdata";
	// when
	rest_response response = client->put(put_url, content_type, data);
	// then
	EXPECT_EQ(200, response.code);
}

TEST_F(RestClientTest, ShouldReturnValidResponseBody)
{
	// given
	std::string data = "testdata";
	// when
	rest_response response = client->put(put_url, content_type, data);
	size_t data_content_position = response.body.find(data);
	// then
 	ASSERT_TRUE(data_content_position != std::string::npos);
}

TEST_F(RestClientTest, ShouldReturnValidResponseCodeWhenPUTFails)
{
	// given
	std::string data = "testdata";
	// when
	rest_response response = client->put("http://nonexisting.org", content_type, data);
	// then
	EXPECT_EQ(-1, response.code);
}<|endoftext|>


<commit_before>// Copyright 2010 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * 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.
//     * Neither the name of Google Inc. 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.

#include <stdlib.h>
#include <stdarg.h>
#include "../include/v8stdint.h"
#include "../include/v8-preparser.h"
#include "unicode-inl.h"

enum ResultCode { kSuccess = 0, kErrorReading = 1, kErrorWriting = 2 };

namespace v8 {
namespace internal {

// THIS FILE IS PROOF-OF-CONCEPT ONLY.
// The final goal is a stand-alone preparser library.

class UTF8InputStream : public v8::UnicodeInputStream {
 public:
  UTF8InputStream(uint8_t* buffer, size_t length)
      : buffer_(buffer),
        offset_(0),
        pos_(0),
        end_offset_(static_cast<int>(length)) { }

  virtual ~UTF8InputStream() { }

  virtual void PushBack(int32_t ch) {
    // Pushback assumes that the character pushed back is the
    // one that was most recently read, and jumps back in the
    // UTF-8 stream by the length of that character's encoding.
    offset_ -= unibrow::Utf8::Length(ch);
    pos_--;
#ifdef DEBUG
    if (static_cast<unsigned>(ch) <= unibrow::Utf8::kMaxOneByteChar) {
      if (ch != buffer_[offset_]) {
        fprintf(stderr, "Invalid pushback: '%c'.", ch);
        exit(1);
      }
    } else {
      unsigned tmp = 0;
      if (static_cast<unibrow::uchar>(ch) !=
          unibrow::Utf8::CalculateValue(buffer_ + offset_,
                                        end_offset_ - offset_,
                                        &tmp)) {
        fprintf(stderr, "Invalid pushback: 0x%x.", ch);
        exit(1);
      }
    }
#endif
  }

  virtual int32_t Next() {
    if (offset_ == end_offset_) return -1;
    uint8_t first_char = buffer_[offset_];
    if (first_char <= unibrow::Utf8::kMaxOneByteChar) {
      pos_++;
      offset_++;
      return static_cast<int32_t>(first_char);
    }
    unibrow::uchar codepoint =
        unibrow::Utf8::CalculateValue(buffer_ + offset_,
                                      end_offset_ - offset_,
                                      &offset_);
    pos_++;
    return static_cast<int32_t>(codepoint);
  }

 private:
  const uint8_t* buffer_;
  unsigned offset_;
  unsigned pos_;
  unsigned end_offset_;
};

// Write a number to dest in network byte order.
void WriteUInt32(FILE* dest, uint32_t value, bool* ok) {
  for (int i = 3; i >= 0; i--) {
    uint8_t byte = static_cast<uint8_t>(value >> (i << 3));
    int result = fputc(byte, dest);
    if (result == EOF) {
      *ok = false;
      return;
    }
  }
}

// Read number from FILE* in network byte order.
uint32_t ReadUInt32(FILE* source, bool* ok) {
  uint32_t n = 0;
  for (int i = 0; i < 4; i++) {
    int c = fgetc(source);
    if (c == EOF) {
      *ok = false;
      return 0;
    }
    n = (n << 8) + static_cast<uint32_t>(c);
  }
  return n;
}

bool ReadBuffer(FILE* source, void* buffer, size_t length) {
  size_t actually_read = fread(buffer, 1, length, source);
  return (actually_read == length);
}

bool WriteBuffer(FILE* dest, const void* buffer, size_t length) {
  size_t actually_written = fwrite(buffer, 1, length, dest);
  return (actually_written == length);
}

template <typename T>
class ScopedPointer {
 public:
  explicit ScopedPointer(T* pointer) : pointer_(pointer) {}
  ~ScopedPointer() { delete[] pointer_; }
  T& operator[](int index) { return pointer_[index]; }
  T* operator*() { return pointer_ ;}
 private:
  T* pointer_;
};

// Preparse input and output result on stdout.
int PreParseIO(FILE* input) {
  fprintf(stderr, "LOG: Enter parsing loop\n");
  bool ok = true;
  uint32_t length = ReadUInt32(input, &ok);
  fprintf(stderr, "LOG: Input length: %d\n", length);
  if (!ok) return kErrorReading;
  ScopedPointer<uint8_t> buffer(new uint8_t[length]);

  if (!ReadBuffer(input, *buffer, length)) {
    return kErrorReading;
  }
  UTF8InputStream input_buffer(*buffer, static_cast<size_t>(length));

  v8::PreParserData data =
      v8::Preparse(&input_buffer, 64 * 1024 * sizeof(void*));  // NOLINT
  if (data.stack_overflow()) {
    fprintf(stderr, "LOG: Stack overflow\n");
    fflush(stderr);
    // Report stack overflow error/no-preparser-data.
    WriteUInt32(stdout, 0, &ok);
    if (!ok) return kErrorWriting;
    return 0;
  }

  uint32_t size = data.size();
  fprintf(stderr, "LOG: Success, data size: %u\n", size);
  fflush(stderr);
  WriteUInt32(stdout, size, &ok);
  if (!ok) return kErrorWriting;
  if (!WriteBuffer(stdout, data.data(), size)) {
    return kErrorWriting;
  }
  return 0;
}

} }  // namespace v8::internal

int main(int argc, char* argv[]) {
  FILE* input = stdin;
  if (argc > 1) {
    char* arg = argv[1];
    FILE* file = fopen(arg, "rb");
    if (!file) return EXIT_FAILURE;
  }
  int status = 0;
  do {
    status = v8::internal::PreParseIO(input);
  } while (status == 0);
  fprintf(stderr, "EXIT: Failure %d\n", status);
  fflush(stderr);
  return EXIT_FAILURE;
}
<commit_msg>Use the file opened from argv[1] in preparser-process.cc<commit_after>// Copyright 2010 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * 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.
//     * Neither the name of Google Inc. 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.

#include <stdlib.h>
#include <stdarg.h>
#include "../include/v8stdint.h"
#include "../include/v8-preparser.h"
#include "unicode-inl.h"

enum ResultCode { kSuccess = 0, kErrorReading = 1, kErrorWriting = 2 };

namespace v8 {
namespace internal {

// THIS FILE IS PROOF-OF-CONCEPT ONLY.
// The final goal is a stand-alone preparser library.

class UTF8InputStream : public v8::UnicodeInputStream {
 public:
  UTF8InputStream(uint8_t* buffer, size_t length)
      : buffer_(buffer),
        offset_(0),
        pos_(0),
        end_offset_(static_cast<int>(length)) { }

  virtual ~UTF8InputStream() { }

  virtual void PushBack(int32_t ch) {
    // Pushback assumes that the character pushed back is the
    // one that was most recently read, and jumps back in the
    // UTF-8 stream by the length of that character's encoding.
    offset_ -= unibrow::Utf8::Length(ch);
    pos_--;
#ifdef DEBUG
    if (static_cast<unsigned>(ch) <= unibrow::Utf8::kMaxOneByteChar) {
      if (ch != buffer_[offset_]) {
        fprintf(stderr, "Invalid pushback: '%c'.", ch);
        exit(1);
      }
    } else {
      unsigned tmp = 0;
      if (static_cast<unibrow::uchar>(ch) !=
          unibrow::Utf8::CalculateValue(buffer_ + offset_,
                                        end_offset_ - offset_,
                                        &tmp)) {
        fprintf(stderr, "Invalid pushback: 0x%x.", ch);
        exit(1);
      }
    }
#endif
  }

  virtual int32_t Next() {
    if (offset_ == end_offset_) return -1;
    uint8_t first_char = buffer_[offset_];
    if (first_char <= unibrow::Utf8::kMaxOneByteChar) {
      pos_++;
      offset_++;
      return static_cast<int32_t>(first_char);
    }
    unibrow::uchar codepoint =
        unibrow::Utf8::CalculateValue(buffer_ + offset_,
                                      end_offset_ - offset_,
                                      &offset_);
    pos_++;
    return static_cast<int32_t>(codepoint);
  }

 private:
  const uint8_t* buffer_;
  unsigned offset_;
  unsigned pos_;
  unsigned end_offset_;
};

// Write a number to dest in network byte order.
void WriteUInt32(FILE* dest, uint32_t value, bool* ok) {
  for (int i = 3; i >= 0; i--) {
    uint8_t byte = static_cast<uint8_t>(value >> (i << 3));
    int result = fputc(byte, dest);
    if (result == EOF) {
      *ok = false;
      return;
    }
  }
}

// Read number from FILE* in network byte order.
uint32_t ReadUInt32(FILE* source, bool* ok) {
  uint32_t n = 0;
  for (int i = 0; i < 4; i++) {
    int c = fgetc(source);
    if (c == EOF) {
      *ok = false;
      return 0;
    }
    n = (n << 8) + static_cast<uint32_t>(c);
  }
  return n;
}

bool ReadBuffer(FILE* source, void* buffer, size_t length) {
  size_t actually_read = fread(buffer, 1, length, source);
  return (actually_read == length);
}

bool WriteBuffer(FILE* dest, const void* buffer, size_t length) {
  size_t actually_written = fwrite(buffer, 1, length, dest);
  return (actually_written == length);
}

template <typename T>
class ScopedPointer {
 public:
  explicit ScopedPointer(T* pointer) : pointer_(pointer) {}
  ~ScopedPointer() { delete[] pointer_; }
  T& operator[](int index) { return pointer_[index]; }
  T* operator*() { return pointer_ ;}
 private:
  T* pointer_;
};

// Preparse input and output result on stdout.
int PreParseIO(FILE* input) {
  fprintf(stderr, "LOG: Enter parsing loop\n");
  bool ok = true;
  uint32_t length = ReadUInt32(input, &ok);
  fprintf(stderr, "LOG: Input length: %d\n", length);
  if (!ok) return kErrorReading;
  ScopedPointer<uint8_t> buffer(new uint8_t[length]);

  if (!ReadBuffer(input, *buffer, length)) {
    return kErrorReading;
  }
  UTF8InputStream input_buffer(*buffer, static_cast<size_t>(length));

  v8::PreParserData data =
      v8::Preparse(&input_buffer, 64 * 1024 * sizeof(void*));  // NOLINT
  if (data.stack_overflow()) {
    fprintf(stderr, "LOG: Stack overflow\n");
    fflush(stderr);
    // Report stack overflow error/no-preparser-data.
    WriteUInt32(stdout, 0, &ok);
    if (!ok) return kErrorWriting;
    return 0;
  }

  uint32_t size = data.size();
  fprintf(stderr, "LOG: Success, data size: %u\n", size);
  fflush(stderr);
  WriteUInt32(stdout, size, &ok);
  if (!ok) return kErrorWriting;
  if (!WriteBuffer(stdout, data.data(), size)) {
    return kErrorWriting;
  }
  return 0;
}

} }  // namespace v8::internal

int main(int argc, char* argv[]) {
  FILE* input = stdin;
  if (argc > 1) {
    char* arg = argv[1];
    input = fopen(arg, "rb");
    if (input == NULL) return EXIT_FAILURE;
  }
  int status = 0;
  do {
    status = v8::internal::PreParseIO(input);
  } while (status == 0);
  fprintf(stderr, "EXIT: Failure %d\n", status);
  fflush(stderr);
  return EXIT_FAILURE;
}
<|endoftext|>


<commit_before>/*
    Copyright (C) 2012 Othmane Moustaouda <othmane.moustaouda@gmail.com>

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

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

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "nowplaying-lineedit.h"

#include <QtGui>

NowPlayingLineEdit::NowPlayingLineEdit(QWidget *parent)
: QLineEdit(parent)
{

}

NowPlayingLineEdit::~NowPlayingLineEdit()
{

}

void NowPlayingLineEdit::setLocalizedTagNames(QStringList tagNames)
{
    m_localizedTagNames = tagNames;
}

void NowPlayingLineEdit::dropEvent(QDropEvent *event)
{
    const QMimeData *content = event->mimeData();

    //adapt the dropped text and insert it at current cursor position
    if (content->hasText()) {
        QString text = content->text();
        text = text.toLower();
        text = text.insert(0, QLatin1Char('%'));
        insert(text);

        setFocus();
        event->accept();
    } else
        event->ignore();
}

void NowPlayingLineEdit::mousePressEvent(QMouseEvent *event)
{
    //small usability improvement:
    //if we detect that the click is inside a tag name then that tag will be auto selected
    if (event->button() == Qt::LeftButton) {
        int currentCursorPosition = cursorPositionAt(event->pos());

        Q_FOREACH (const QString &tag, m_localizedTagNames) {
            if(text().contains(tag)
            && currentCursorPosition >= text().indexOf(tag) //cursor must be inside tag's bounds
            && currentCursorPosition <= text().indexOf(tag) + tag.size()) {

                setSelection(text().indexOf(tag), tag.size());
                break;
            }
            else {
                //since we are intercepting mouse events, setting manually the cursor's position is needed
                setCursorPosition(currentCursorPosition);
            }
        }
    }
}
<commit_msg>Fix includes<commit_after>/*
    Copyright (C) 2012 Othmane Moustaouda <othmane.moustaouda@gmail.com>

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

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

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "nowplaying-lineedit.h"

#include <QLineEdit>
#include <QMimeData>
#include <QMouseEvent>
#include <QDropEvent>

NowPlayingLineEdit::NowPlayingLineEdit(QWidget *parent)
: QLineEdit(parent)
{

}

NowPlayingLineEdit::~NowPlayingLineEdit()
{

}

void NowPlayingLineEdit::setLocalizedTagNames(QStringList tagNames)
{
    m_localizedTagNames = tagNames;
}

void NowPlayingLineEdit::dropEvent(QDropEvent *event)
{
    const QMimeData *content = event->mimeData();

    //adapt the dropped text and insert it at current cursor position
    if (content->hasText()) {
        QString text = content->text();
        text = text.toLower();
        text = text.insert(0, QLatin1Char('%'));
        insert(text);

        setFocus();
        event->accept();
    } else
        event->ignore();
}

void NowPlayingLineEdit::mousePressEvent(QMouseEvent *event)
{
    //small usability improvement:
    //if we detect that the click is inside a tag name then that tag will be auto selected
    if (event->button() == Qt::LeftButton) {
        int currentCursorPosition = cursorPositionAt(event->pos());

        Q_FOREACH (const QString &tag, m_localizedTagNames) {
            if(text().contains(tag)
            && currentCursorPosition >= text().indexOf(tag) //cursor must be inside tag's bounds
            && currentCursorPosition <= text().indexOf(tag) + tag.size()) {

                setSelection(text().indexOf(tag), tag.size());
                break;
            }
            else {
                //since we are intercepting mouse events, setting manually the cursor's position is needed
                setCursorPosition(currentCursorPosition);
            }
        }
    }
}
<|endoftext|>