<commit_before>/** Handling of SQL arrays.
 *
 * Copyright (c) 2018, Jeroen T. Vermeulen.
 *
 * See COPYING for copyright license.  If you did not receive a file called
 * COPYING with this source code, please notify the distributor of this mistake,
 * or contact the author.
 */
#include "pqxx/compiler-internal.hxx"

#include <cassert>
#include <cstring>
#include <utility>

#include "pqxx/array"
#include "pqxx/except"

using namespace pqxx::internal;

namespace
{

/// Find the end of a single-quoted SQL string in an SQL array.
/** Assumes UTF-8 or an ASCII-superset single-byte encoding.
 * This is used for array parsing, where the database may send us strings
 * stored in the array, in a quoted and escaped format.
 *
 * Returns the address of the first character after the closing quote.
 */
const char*scan_single_quoted_string(const char begin[])
{
  const char *here = begin;
  assert(*here == '\'');
  for (here++; *here; here++)
  {
    switch (*here)
    {
    case '\'':
      // Escaped quote, or closing quote.
      here++;
      // If the next character is a quote, we've got a double single quote.
      // That's how SQL escapes embedded quotes in a string.  Terrible idea,
      // but it's what we have.
      if (*here != '\'') return here;
      // Otherwise, we've found the end of the string.  Return the address of
      // the very next byte.
      break;
    case '\\':
      // Backslash escape.  Skip ahead by one more character.
      here++;
      if (!*here)
        throw pqxx::argument_error(
          "SQL string ends in escape: " + std::string(begin));
      break;
    }
  }
  throw pqxx::argument_error(
      "Null byte in SQL string: " + std::string(begin));
}

/// Parse a single-quoted SQL string: un-quote it and un-escape it.
/** Assumes UTF-8 or an ASCII-superset single-byte encoding.
 */
std::string parse_single_quoted_string(const char begin[], const char end[])
{
  // There have to be at least 2 characters: the opening and closing quotes.
  assert(begin + 1 < end);
  assert(*begin == '\'');
  assert(*(end - 1) == '\'');

  std::string output;
  // Maximum output size is same as the input size, minus the opening and
  // closing quotes.  In the worst case, the real number could be half that.
  // Usually it'll be a pretty close estimate.
  output.reserve(end - begin - 2);
  for (const char *here = begin + 1; here < end - 1; here++)
  {
    auto c = *here;
    // Skip escapes.
    if (c == '\'' || c == '\\') here++;
    output.push_back(c);
  }

  return output;
}

/// Find the end of a double-quoted SQL string in an SQL array.
/** Assumes UTF-8 or an ASCII-superset single-byte encoding.
 */
const char *scan_double_quoted_string(const char begin[])
{
  const char *here = begin;
  assert(*here == '"');
  for (here++; *here; here++)
  {
    switch (*here)
    {
    case '\\':
      // Backslash escape.  Skip ahead by one more character.
      here++;
      if (!*here)
        throw pqxx::argument_error(
          "SQL string ends in escape: " + std::string(begin));
      break;
    case '"':
      return here + 1;
    }
  }
  throw pqxx::argument_error(
      "Null byte in SQL string: " + std::string(begin));
}

/// Parse a double-quoted SQL string: un-quote it and un-escape it.
/** Assumes UTF-8 or an ASCII-superset single-byte encoding.
 */
std::string parse_double_quoted_string(const char begin[], const char end[])
{
  // There have to be at least 2 characters: the opening and closing quotes.
  assert(begin + 1 < end);
  assert(*begin == '"');
  assert(*(end - 1) == '"');

  std::string output;
  // Maximum output size is same as the input size, minus the opening and
  // closing quotes.  In the worst case, the real number could be half that.
  // Usually it'll be a pretty close estimate.
  output.reserve(end - begin - 2);
  for (const char *here = begin + 1; here < end - 1; here++)
  {
    auto c = *here;
    // Skip escapes.
    if (c == '\\') here++;
    output.push_back(c);
  }

  return output;
}

/// Find the end of an unquoted string in an SQL array.
/** Assumes UTF-8 or an ASCII-superset single-byte encoding.
 */
const char *scan_unquoted_string(const char begin[])
{
  assert(*begin != '\'');
  assert(*begin != '"');

  const char *p;
  for (
        p = begin;
        *p != ',' && *p != ';' && *p != '}';
        p++);
  return p;
}

/// Parse an unquoted SQL string.
/** Here, the special unquoted value NULL means a null value, not a string
 * that happens to spell "NULL".
 */
std::string parse_unquoted_string(const char begin[], const char end[])
{
  return std::string(begin, end);
}

} // namespace

namespace pqxx
{
array_parser::array_parser(const char input[]) : m_pos(input)
{
}

std::pair<array_parser::juncture, std::string>
array_parser::get_next()
{
  pqxx::array_parser::juncture found;
  std::string value;
  const char *end;

  if (m_pos == nullptr)
  {
    found = juncture::done;
    end = nullptr;
  }
  else switch (*m_pos)
  {
  case '\0':
    found = juncture::done;
    end = m_pos;
    break;
  case '{':
    found = juncture::row_start;
    end = m_pos + 1;
    break;
  case '}':
    found = juncture::row_end;
    end = m_pos + 1;
    break;
  case '\'':
    found = juncture::string_value;
    end = scan_single_quoted_string(m_pos);
    value = parse_single_quoted_string(m_pos, end);
    break;
  case '"':
    found = juncture::string_value;
    end = scan_double_quoted_string(m_pos);
    value = parse_double_quoted_string(m_pos, end);
    break;
  default:
    end = scan_unquoted_string(m_pos);
    value = parse_unquoted_string(m_pos, end);
    if (value == "NULL")
    {
      // In this one situation, as a special case, NULL means a null field,
      // not a string that happens to spell "NULL".
      value.clear();
      found = juncture::null_value;
    }
    else
    {
      // The normal case: we just parsed an unquoted string.  The value is
      // what we need.
      found = juncture::string_value;
    }
    break;
  }

  // Skip a field separator following a string (or null).
  if (end != nullptr && (*end == ',' || *end == ';'))
    end++;

  m_pos = end;
  return std::make_pair(found, value);
}
} // namespace pqxx
<commit_msg>Fix clang signedness warning.<commit_after>/** Handling of SQL arrays.
 *
 * Copyright (c) 2018, Jeroen T. Vermeulen.
 *
 * See COPYING for copyright license.  If you did not receive a file called
 * COPYING with this source code, please notify the distributor of this mistake,
 * or contact the author.
 */
#include "pqxx/compiler-internal.hxx"

#include <cassert>
#include <cstddef>
#include <cstring>
#include <utility>

#include "pqxx/array"
#include "pqxx/except"

using namespace pqxx::internal;

namespace
{

/// Find the end of a single-quoted SQL string in an SQL array.
/** Assumes UTF-8 or an ASCII-superset single-byte encoding.
 * This is used for array parsing, where the database may send us strings
 * stored in the array, in a quoted and escaped format.
 *
 * Returns the address of the first character after the closing quote.
 */
const char*scan_single_quoted_string(const char begin[])
{
  const char *here = begin;
  assert(*here == '\'');
  for (here++; *here; here++)
  {
    switch (*here)
    {
    case '\'':
      // Escaped quote, or closing quote.
      here++;
      // If the next character is a quote, we've got a double single quote.
      // That's how SQL escapes embedded quotes in a string.  Terrible idea,
      // but it's what we have.
      if (*here != '\'') return here;
      // Otherwise, we've found the end of the string.  Return the address of
      // the very next byte.
      break;
    case '\\':
      // Backslash escape.  Skip ahead by one more character.
      here++;
      if (!*here)
        throw pqxx::argument_error(
          "SQL string ends in escape: " + std::string(begin));
      break;
    }
  }
  throw pqxx::argument_error(
      "Null byte in SQL string: " + std::string(begin));
}

/// Parse a single-quoted SQL string: un-quote it and un-escape it.
/** Assumes UTF-8 or an ASCII-superset single-byte encoding.
 */
std::string parse_single_quoted_string(const char begin[], const char end[])
{
  // There have to be at least 2 characters: the opening and closing quotes.
  assert(begin + 1 < end);
  assert(*begin == '\'');
  assert(*(end - 1) == '\'');

  std::string output;
  // Maximum output size is same as the input size, minus the opening and
  // closing quotes.  In the worst case, the real number could be half that.
  // Usually it'll be a pretty close estimate.
  output.reserve(std::size_t(end - begin - 2));
  for (const char *here = begin + 1; here < end - 1; here++)
  {
    auto c = *here;
    // Skip escapes.
    if (c == '\'' || c == '\\') here++;
    output.push_back(c);
  }

  return output;
}

/// Find the end of a double-quoted SQL string in an SQL array.
/** Assumes UTF-8 or an ASCII-superset single-byte encoding.
 */
const char *scan_double_quoted_string(const char begin[])
{
  const char *here = begin;
  assert(*here == '"');
  for (here++; *here; here++)
  {
    switch (*here)
    {
    case '\\':
      // Backslash escape.  Skip ahead by one more character.
      here++;
      if (!*here)
        throw pqxx::argument_error(
          "SQL string ends in escape: " + std::string(begin));
      break;
    case '"':
      return here + 1;
    }
  }
  throw pqxx::argument_error(
      "Null byte in SQL string: " + std::string(begin));
}

/// Parse a double-quoted SQL string: un-quote it and un-escape it.
/** Assumes UTF-8 or an ASCII-superset single-byte encoding.
 */
std::string parse_double_quoted_string(const char begin[], const char end[])
{
  // There have to be at least 2 characters: the opening and closing quotes.
  assert(begin + 1 < end);
  assert(*begin == '"');
  assert(*(end - 1) == '"');

  std::string output;
  // Maximum output size is same as the input size, minus the opening and
  // closing quotes.  In the worst case, the real number could be half that.
  // Usually it'll be a pretty close estimate.
  output.reserve(std::size_t(end - begin - 2));
  for (const char *here = begin + 1; here < end - 1; here++)
  {
    auto c = *here;
    // Skip escapes.
    if (c == '\\') here++;
    output.push_back(c);
  }

  return output;
}

/// Find the end of an unquoted string in an SQL array.
/** Assumes UTF-8 or an ASCII-superset single-byte encoding.
 */
const char *scan_unquoted_string(const char begin[])
{
  assert(*begin != '\'');
  assert(*begin != '"');

  const char *p;
  for (
        p = begin;
        *p != ',' && *p != ';' && *p != '}';
        p++);
  return p;
}

/// Parse an unquoted SQL string.
/** Here, the special unquoted value NULL means a null value, not a string
 * that happens to spell "NULL".
 */
std::string parse_unquoted_string(const char begin[], const char end[])
{
  return std::string(begin, end);
}

} // namespace

namespace pqxx
{
array_parser::array_parser(const char input[]) : m_pos(input)
{
}

std::pair<array_parser::juncture, std::string>
array_parser::get_next()
{
  pqxx::array_parser::juncture found;
  std::string value;
  const char *end;

  if (m_pos == nullptr)
  {
    found = juncture::done;
    end = nullptr;
  }
  else switch (*m_pos)
  {
  case '\0':
    found = juncture::done;
    end = m_pos;
    break;
  case '{':
    found = juncture::row_start;
    end = m_pos + 1;
    break;
  case '}':
    found = juncture::row_end;
    end = m_pos + 1;
    break;
  case '\'':
    found = juncture::string_value;
    end = scan_single_quoted_string(m_pos);
    value = parse_single_quoted_string(m_pos, end);
    break;
  case '"':
    found = juncture::string_value;
    end = scan_double_quoted_string(m_pos);
    value = parse_double_quoted_string(m_pos, end);
    break;
  default:
    end = scan_unquoted_string(m_pos);
    value = parse_unquoted_string(m_pos, end);
    if (value == "NULL")
    {
      // In this one situation, as a special case, NULL means a null field,
      // not a string that happens to spell "NULL".
      value.clear();
      found = juncture::null_value;
    }
    else
    {
      // The normal case: we just parsed an unquoted string.  The value is
      // what we need.
      found = juncture::string_value;
    }
    break;
  }

  // Skip a field separator following a string (or null).
  if (end != nullptr && (*end == ',' || *end == ';'))
    end++;

  m_pos = end;
  return std::make_pair(found, value);
}
} // namespace pqxx
<|endoftext|>


<commit_before>/* Copyright (c) 2015, Daniel C. Dillon
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * 3. Neither the name of the copyright holder 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 HOLDER 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.
 */

#pragma once

#include "config.hpp"

#include "cpu_spec.hpp"
#include "impl/basic_cpu.hpp"
#include "impl/basic_cpu_set.hpp"
#include "impl/basic_affinity_manager.hpp"
#include "impl/basic_native_cpu_mapper.hpp"
#include "impl/basic_affinity_stack.hpp"
#include "impl/basic_round_robin_allocator.hpp"

#if defined(CPUAFF_PCI_SUPPORTED)

#include "impl/basic_pci_device.hpp"
#include "impl/basic_pci_device_set.hpp"
#include "impl/basic_pci_device_manager.hpp"
#include "pci_device_description.hpp"
#include "pci_device_spec.hpp"
#include "pci_name_resolver.hpp"

#endif

/*!
 * Namespace for all cpuaff functionality
 */
namespace cpuaff
{
/*!
 * affinity_stack is used to keep track of affinities as you get and set
 * them.  It is basically a wrapper for an affinity_manager that gives you the
 * ability to keep track of what affinities have been and reset them later.
 */
typedef impl::basic_affinity_stack< traits > affinity_stack;

/*!
 * cpu is a representation of a cpu on the system.  It contains all the
 * data needed to get and set thread affinity as well data specifying the
 * hardware layout of the cpu.
 */
typedef impl::basic_cpu< traits > cpu;

/*!
 * affinity_manager is a collection of all the valid cpus.  It provides
 * interfaces to get and set cpu affinity as well as ways to classify cpus
 * on the system so that intelligent choices can be made about what affinity a
 * thread should have.
 */
typedef impl::basic_affinity_manager< traits > affinity_manager;

/*!
 * native_cpu_mapper is a utility class that maps native cpu
 * representations to cpus from a basic_cpu_manager.  It may not be available
 * for every platform.
 */
typedef impl::basic_native_cpu_mapper< traits > native_cpu_mapper;

/*!
 * native_cpu_wrapper is a wrapper for the native representation of cpus.
 * It is comparable with < so that it can be used as a key in maps.
 */
typedef traits::native_cpu_mapper_type native_cpu_mapper;

/*!
 * A set that can hold unique cpus.
 */
typedef impl::basic_cpu_set< traits > cpu_set;

/*!
 * round_robin_allocator is a utility class that takes a set of cpus
 * and returns them as requested in a round-robin fashion.  It organizes the
 * cpus such that it returns consecutive cpus from different cores if it can.
 */
typedef impl::basic_round_robin_allocator< traits > round_robin_allocator;

#if defined(CPUAFF_PCI_SUPPORTED)
/*!
 * basic_pci_device_manager is a collection of all the pci devices on the
 * system.
 */
typedef impl::basic_pci_device_manager< traits > pci_device_manager;

/*!
 * basic_pci_device is a representation of a pci_device on the system.  It
 * contains identification, address, and numa information.  The device can
 * then be used to determine what cpus are local to it.
 */
typedef impl::basic_pci_device< traits > pci_device;

/*!
 * A set that can hold unique pci devices
 */
typedef impl::basic_pci_device_set< traits > pci_device_set;

#endif
}
<commit_msg>fixed a typo in cpuaff.hpp<commit_after>/* Copyright (c) 2015, Daniel C. Dillon
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * 3. Neither the name of the copyright holder 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 HOLDER 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.
 */

#pragma once

#include "config.hpp"

#include "cpu_spec.hpp"
#include "impl/basic_cpu.hpp"
#include "impl/basic_cpu_set.hpp"
#include "impl/basic_affinity_manager.hpp"
#include "impl/basic_native_cpu_mapper.hpp"
#include "impl/basic_affinity_stack.hpp"
#include "impl/basic_round_robin_allocator.hpp"

#if defined(CPUAFF_PCI_SUPPORTED)

#include "impl/basic_pci_device.hpp"
#include "impl/basic_pci_device_set.hpp"
#include "impl/basic_pci_device_manager.hpp"
#include "pci_device_description.hpp"
#include "pci_device_spec.hpp"
#include "pci_name_resolver.hpp"

#endif

/*!
 * Namespace for all cpuaff functionality
 */
namespace cpuaff
{
/*!
 * affinity_stack is used to keep track of affinities as you get and set
 * them.  It is basically a wrapper for an affinity_manager that gives you the
 * ability to keep track of what affinities have been and reset them later.
 */
typedef impl::basic_affinity_stack< traits > affinity_stack;

/*!
 * cpu is a representation of a cpu on the system.  It contains all the
 * data needed to get and set thread affinity as well data specifying the
 * hardware layout of the cpu.
 */
typedef impl::basic_cpu< traits > cpu;

/*!
 * affinity_manager is a collection of all the valid cpus.  It provides
 * interfaces to get and set cpu affinity as well as ways to classify cpus
 * on the system so that intelligent choices can be made about what affinity a
 * thread should have.
 */
typedef impl::basic_affinity_manager< traits > affinity_manager;

/*!
 * native_cpu_mapper is a utility class that maps native cpu
 * representations to cpus from a basic_cpu_manager.  It may not be available
 * for every platform.
 */
typedef impl::basic_native_cpu_mapper< traits > native_cpu_mapper;

/*!
 * native_cpu_wrapper is a wrapper for the native representation of cpus.
 * It is comparable with < so that it can be used as a key in maps.
 */
typedef traits::native_cpu_wrapper_type native_cpu_wrapper;

/*!
 * A set that can hold unique cpus.
 */
typedef impl::basic_cpu_set< traits > cpu_set;

/*!
 * round_robin_allocator is a utility class that takes a set of cpus
 * and returns them as requested in a round-robin fashion.  It organizes the
 * cpus such that it returns consecutive cpus from different cores if it can.
 */
typedef impl::basic_round_robin_allocator< traits > round_robin_allocator;

#if defined(CPUAFF_PCI_SUPPORTED)
/*!
 * basic_pci_device_manager is a collection of all the pci devices on the
 * system.
 */
typedef impl::basic_pci_device_manager< traits > pci_device_manager;

/*!
 * basic_pci_device is a representation of a pci_device on the system.  It
 * contains identification, address, and numa information.  The device can
 * then be used to determine what cpus are local to it.
 */
typedef impl::basic_pci_device< traits > pci_device;

/*!
 * A set that can hold unique pci devices
 */
typedef impl::basic_pci_device_set< traits > pci_device_set;

#endif
}
<|endoftext|>


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

#include "chrome/browser/chromeos/status/power_menu_button.h"

#include <algorithm>

#include "base/auto_reset.h"
#include "base/string_number_conversions.h"
#include "base/stringprintf.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chromeos/dbus/dbus_thread_manager.h"
#include "chrome/browser/chromeos/status/status_area_bubble.h"
#include "chrome/browser/chromeos/view_ids.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/canvas_skia.h"
#include "ui/gfx/font.h"
#include "ui/gfx/image/image.h"
#include "views/controls/menu/menu_item_view.h"
#include "views/controls/menu/menu_runner.h"
#include "views/controls/menu/submenu_view.h"
#include "views/widget/widget.h"

namespace {

// Menu item ids.
enum {
  POWER_BATTERY_PERCENTAGE_ITEM = 1000,
  POWER_BATTERY_IS_CHARGED_ITEM,
  POWER_NO_BATTERY,
};

enum ImageType {
  DISCHARGING,
  CHARGING,
  BOLT
};

enum ImageSize {
  SMALL,
  LARGE
};

// Initialize time deltas to large values so they will be replaced when set
// to small values.
const int64 kInitialMS = 0x7fffffff;
// Width and height of small images.
const int kSmallImageWidth = 26, kSmallImageHeight = 24;
// Width and height of large images.
const int kLargeImageWidth = 57, kLargeImageHeight = 35;
// Number of different power states.
const int kNumPowerImages = 20;

// Color of text embedded within battery.
const SkColor kPercentageColor = 0xFF333333;
// Used for embossing text.
const SkColor kPercentageShadowColor = 0x80ffffff;
// Size of percentage w/in battery.
const int kBatteryFontSizeDelta = 3;

// Battery images come from two collections (small and large). In each there
// are |kNumPowerImages| battery states for both on and off charge, followed
// by the missing battery image and the unknown image.
// They are layed out like this:
// Discharging Charging Bolt
// |           |        +
// ||          ||        +
// ...
// |||||       |||||        +
// ||X||       ||?||
SkBitmap GetImage(ImageSize size, ImageType type, int index) {
  int image_width, image_height, image_index;

  if (size == SMALL) {
    image_index = IDR_STATUSBAR_BATTERY_SMALL_ALL;
    image_width = kSmallImageWidth;
    image_height = kSmallImageHeight;
  } else {
    image_index = IDR_STATUSBAR_BATTERY_LARGE_ALL;
    image_width = kLargeImageWidth;
    image_height = kLargeImageHeight;
  }
  const SkBitmap* all_images = ResourceBundle::GetSharedInstance().
      GetImageNamed(image_index).ToSkBitmap();
  SkIRect subset =
      SkIRect::MakeXYWH(
          static_cast<int>(type) * image_width,
          index * image_height,
          image_width,
          image_height);

  SkBitmap image;
  all_images->extractSubset(&image, subset);
  return image;
}

SkBitmap GetImageWithPercentage(ImageSize size, ImageType type,
                                double battery_percentage) {
  // Preserve the fully charged icon for 100% only.
  int battery_index = 0;
  if (battery_percentage >= 100) {
    battery_index = kNumPowerImages - 1;
  } else {
    battery_index = static_cast<int> (
        battery_percentage / 100.0 *
        nextafter(static_cast<double>(kNumPowerImages - 1), 0));
    battery_index =
        std::max(std::min(battery_index, kNumPowerImages - 2), 0);
  }
  return GetImage(size, type, battery_index);
}

SkBitmap GetMissingImage(ImageSize size) {
  return GetImage(size, DISCHARGING, kNumPowerImages);
}

SkBitmap GetUnknownImage(ImageSize size) {
  return GetImage(size, CHARGING, kNumPowerImages);
}

class BatteryIconView : public views::View {
 public:
  BatteryIconView()
      : battery_percentage_(0),
        battery_is_present_(false),
        line_power_on_(false),
        percentage_font_(ResourceBundle::GetSharedInstance().
                         GetFont(ResourceBundle::BaseFont).
                         DeriveFont(kBatteryFontSizeDelta, gfx::Font::BOLD)) {
  }

  virtual gfx::Size GetPreferredSize() OVERRIDE {
    return gfx::Size(kLargeImageWidth, kLargeImageHeight);
  }

  void set_battery_percentage(double battery_percentage) {
    battery_percentage_ = battery_percentage;
    SchedulePaint();
  }

  void set_battery_is_present(bool battery_is_present) {
    battery_is_present_ = battery_is_present;
    SchedulePaint();
  }

  void set_line_power_on(bool line_power_on) {
    line_power_on_ = line_power_on;
    SchedulePaint();
  }

 protected:
  virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE {
    SkBitmap image;
    if (!battery_is_present_) {
      image = GetMissingImage(LARGE);
    } else {
      image = GetImageWithPercentage(LARGE,
                                     line_power_on_ ? CHARGING : DISCHARGING,
                                     battery_percentage_);
    }
    const int image_x = 0;
    const int image_y = (height() - image.height()) / 2;
    canvas->DrawBitmapInt(image, image_x, image_y);

    if (battery_is_present_ && (battery_percentage_ < 100 || !line_power_on_)) {
      const string16 text = UTF8ToUTF16(base::StringPrintf(
          "%d%%", static_cast<int>(battery_percentage_)));
      const int text_h = percentage_font_.GetHeight();
      const int text_y = ((height() - text_h) / 2);
      canvas->DrawStringInt(
          text, percentage_font_, kPercentageShadowColor,
          image_x, text_y + 1, image.width(), text_h,
          gfx::Canvas::TEXT_ALIGN_CENTER | gfx::Canvas::NO_ELLIPSIS);
      canvas->DrawStringInt(
          text, percentage_font_, kPercentageColor,
          image_x, text_y, image.width(), text_h,
          gfx::Canvas::TEXT_ALIGN_CENTER | gfx::Canvas::NO_ELLIPSIS);
      if (line_power_on_)
        canvas->DrawBitmapInt(
            GetImageWithPercentage(LARGE, BOLT, battery_percentage_),
            image_x, image_y);
    }
  }

 private:
  double battery_percentage_;
  bool battery_is_present_;
  bool line_power_on_;
  gfx::Font percentage_font_;

  DISALLOW_COPY_AND_ASSIGN(BatteryIconView);
};

}  // namespace

namespace chromeos {

using base::TimeDelta;

////////////////////////////////////////////////////////////////////////////////
// PowerMenuButton

PowerMenuButton::PowerMenuButton(StatusAreaButton::Delegate* delegate)
    : StatusAreaButton(delegate, this),
      battery_is_present_(false),
      line_power_on_(false),
      battery_percentage_(0.0),
      battery_time_to_full_(TimeDelta::FromMicroseconds(kInitialMS)),
      battery_time_to_empty_(TimeDelta::FromMicroseconds(kInitialMS)),
      status_(NULL) {
  set_id(VIEW_ID_STATUS_BUTTON_POWER);
  UpdateIconAndLabelInfo();
  DBusThreadManager::Get()->GetPowerManagerClient()->AddObserver(this);
}

PowerMenuButton::~PowerMenuButton() {
  DBusThreadManager::Get()->GetPowerManagerClient()->RemoveObserver(this);
}

// PowerMenuButton, views::MenuDelegate implementation:

string16 PowerMenuButton::GetLabel(int id) const {
  return string16();
}

string16 PowerMenuButton::GetBatteryIsChargedText() const {
  // The second item shows the battery is charged if it is.
  if (battery_percentage_ >= 100 && line_power_on_)
    return l10n_util::GetStringUTF16(IDS_STATUSBAR_BATTERY_IS_CHARGED);

  // If battery is in an intermediate charge state, show how much time left.
  TimeDelta time = line_power_on_ ? battery_time_to_full_ :
      battery_time_to_empty_;
  if (time.InSeconds() == 0) {
    // If time is 0, then that means we are still calculating how much time.
    // Depending if line power is on, we either show a message saying that we
    // are calculating time until full or calculating remaining time.
    int msg = line_power_on_ ?
        IDS_STATUSBAR_BATTERY_CALCULATING_TIME_UNTIL_FULL :
        IDS_STATUSBAR_BATTERY_CALCULATING_TIME_UNTIL_EMPTY;
    return l10n_util::GetStringUTF16(msg);
  } else {
    // Depending if line power is on, we either show a message saying XX:YY
    // until full or XX:YY remaining where XX is number of hours and YY is
    // number of minutes.
    int msg = line_power_on_ ? IDS_STATUSBAR_BATTERY_TIME_UNTIL_FULL :
        IDS_STATUSBAR_BATTERY_TIME_UNTIL_EMPTY;
    int hour = time.InHours();
    int min = (time - TimeDelta::FromHours(hour)).InMinutes();
    string16 hour_str = base::IntToString16(hour);
    string16 min_str = base::IntToString16(min);
    // Append a "0" before the minute if it's only a single digit.
    if (min < 10)
      min_str = ASCIIToUTF16("0") + min_str;
    return l10n_util::GetStringFUTF16(msg, hour_str, min_str);
  }
}

int PowerMenuButton::icon_width() {
  return 26;
}

////////////////////////////////////////////////////////////////////////////////
// PowerMenuButton, views::View implementation:
void PowerMenuButton::OnLocaleChanged() {
  UpdateIconAndLabelInfo();
}

////////////////////////////////////////////////////////////////////////////////
// PowerMenuButton, views::ViewMenuDelegate implementation:

void PowerMenuButton::RunMenu(views::View* source, const gfx::Point& pt) {
  // Explicitly query the power status.
  DBusThreadManager::Get()->GetPowerManagerClient()->RequestStatusUpdate();

  views::MenuItemView* menu = new views::MenuItemView(this);
  // MenuRunner takes ownership of |menu|.
  menu_runner_.reset(new views::MenuRunner(menu));
  views::MenuItemView* submenu = menu->AppendMenuItem(
      POWER_BATTERY_PERCENTAGE_ITEM,
      string16(),
      views::MenuItemView::NORMAL);
  status_ = new StatusAreaBubbleContentView(new BatteryIconView, string16());
  UpdateStatusView();
  submenu->AddChildView(status_);
  menu->CreateSubmenu()->set_resize_open_menu(true);
  menu->SetMargins(0, 0);
  submenu->SetMargins(0, 0);
  menu->ChildrenChanged();

  gfx::Point screen_location;
  views::View::ConvertPointToScreen(source, &screen_location);
  gfx::Rect bounds(screen_location, source->size());
  if (menu_runner_->RunMenuAt(
          source->GetWidget()->GetTopLevelWidget(), this, bounds,
          views::MenuItemView::TOPRIGHT, views::MenuRunner::HAS_MNEMONICS) ==
      views::MenuRunner::MENU_DELETED)
    return;
  status_ = NULL;
  menu_runner_.reset(NULL);
}

////////////////////////////////////////////////////////////////////////////////
// PowerMenuButton, PowerManagerClient::Observer implementation:

void PowerMenuButton::PowerChanged(const PowerSupplyStatus& power_status) {
  power_status_ = power_status;
  UpdateIconAndLabelInfo();
}

////////////////////////////////////////////////////////////////////////////////
// PowerMenuButton, StatusAreaButton implementation:

void PowerMenuButton::UpdateIconAndLabelInfo() {
  battery_is_present_ = power_status_.battery_is_present;
  line_power_on_ = power_status_.line_power_on;

  // If fully charged, always show 100% even if internal number is a bit less.
  if (power_status_.battery_is_full)
    battery_percentage_ = 100.0;
  else
    battery_percentage_ = power_status_.battery_percentage;

  UpdateBatteryTime(&battery_time_to_full_,
                    TimeDelta::FromSeconds(
                        power_status_.battery_seconds_to_full));
  UpdateBatteryTime(&battery_time_to_empty_,
                    TimeDelta::FromSeconds(
                        power_status_.battery_seconds_to_empty));

  string16 tooltip_text;
  if (!battery_is_present_) {
    SetIcon(GetMissingImage(SMALL));
    tooltip_text = l10n_util::GetStringUTF16(IDS_STATUSBAR_NO_BATTERY);
  } else {
    SetIcon(GetImageWithPercentage(
        SMALL, line_power_on_ ? CHARGING : DISCHARGING, battery_percentage_));
    const int message_id = line_power_on_ ?
        IDS_STATUSBAR_BATTERY_CHARGING_PERCENTAGE :
        IDS_STATUSBAR_BATTERY_USING_PERCENTAGE;
    tooltip_text =  l10n_util::GetStringFUTF16(
        message_id, base::IntToString16(static_cast<int>(battery_percentage_)));
  }
  SetTooltipText(tooltip_text);
  SetAccessibleName(tooltip_text);
  SchedulePaint();
  UpdateStatusView();
}

void PowerMenuButton::UpdateStatusView() {
  if (status_) {
    string16 charging_text;
    if (battery_is_present_) {
      charging_text = GetBatteryIsChargedText();
    } else {
      charging_text = l10n_util::GetStringUTF16(IDS_STATUSBAR_NO_BATTERY);
    }
    status_->SetMessage(charging_text);
    BatteryIconView* battery_icon_view =
        static_cast<BatteryIconView*>(status_->icon_view());
    battery_icon_view->set_battery_percentage(battery_percentage_);
    battery_icon_view->set_battery_is_present(battery_is_present_);
    battery_icon_view->set_line_power_on(line_power_on_);
  }
}

void PowerMenuButton::UpdateBatteryTime(TimeDelta* previous,
                                        const TimeDelta& current) {
  static const TimeDelta kMaxDiff(TimeDelta::FromMinutes(10));
  static const TimeDelta kMinDiff(TimeDelta::FromMinutes(0));
  const TimeDelta diff = current - *previous;
  // If the diff is small and positive, ignore it in favor of
  // keeping time monotonically decreasing.
  // If previous is 0, then it either was never set (initial condition)
  // or got down to 0.
  if (*previous == TimeDelta::FromMicroseconds(kInitialMS) ||
      diff < kMinDiff ||
      diff > kMaxDiff) {
    *previous = current;
  }
}

}  // namespace chromeos
<commit_msg>Revert 109813 - Revert 109777 - Request power status update from power manager when power button view gets created.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/status/power_menu_button.h"

#include <algorithm>

#include "base/auto_reset.h"
#include "base/string_number_conversions.h"
#include "base/stringprintf.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chromeos/dbus/dbus_thread_manager.h"
#include "chrome/browser/chromeos/status/status_area_bubble.h"
#include "chrome/browser/chromeos/view_ids.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/canvas_skia.h"
#include "ui/gfx/font.h"
#include "ui/gfx/image/image.h"
#include "views/controls/menu/menu_item_view.h"
#include "views/controls/menu/menu_runner.h"
#include "views/controls/menu/submenu_view.h"
#include "views/widget/widget.h"

namespace {

// Menu item ids.
enum {
  POWER_BATTERY_PERCENTAGE_ITEM = 1000,
  POWER_BATTERY_IS_CHARGED_ITEM,
  POWER_NO_BATTERY,
};

enum ImageType {
  DISCHARGING,
  CHARGING,
  BOLT
};

enum ImageSize {
  SMALL,
  LARGE
};

// Initialize time deltas to large values so they will be replaced when set
// to small values.
const int64 kInitialMS = 0x7fffffff;
// Width and height of small images.
const int kSmallImageWidth = 26, kSmallImageHeight = 24;
// Width and height of large images.
const int kLargeImageWidth = 57, kLargeImageHeight = 35;
// Number of different power states.
const int kNumPowerImages = 20;

// Color of text embedded within battery.
const SkColor kPercentageColor = 0xFF333333;
// Used for embossing text.
const SkColor kPercentageShadowColor = 0x80ffffff;
// Size of percentage w/in battery.
const int kBatteryFontSizeDelta = 3;

// Battery images come from two collections (small and large). In each there
// are |kNumPowerImages| battery states for both on and off charge, followed
// by the missing battery image and the unknown image.
// They are layed out like this:
// Discharging Charging Bolt
// |           |        +
// ||          ||        +
// ...
// |||||       |||||        +
// ||X||       ||?||
SkBitmap GetImage(ImageSize size, ImageType type, int index) {
  int image_width, image_height, image_index;

  if (size == SMALL) {
    image_index = IDR_STATUSBAR_BATTERY_SMALL_ALL;
    image_width = kSmallImageWidth;
    image_height = kSmallImageHeight;
  } else {
    image_index = IDR_STATUSBAR_BATTERY_LARGE_ALL;
    image_width = kLargeImageWidth;
    image_height = kLargeImageHeight;
  }
  const SkBitmap* all_images = ResourceBundle::GetSharedInstance().
      GetImageNamed(image_index).ToSkBitmap();
  SkIRect subset =
      SkIRect::MakeXYWH(
          static_cast<int>(type) * image_width,
          index * image_height,
          image_width,
          image_height);

  SkBitmap image;
  all_images->extractSubset(&image, subset);
  return image;
}

SkBitmap GetImageWithPercentage(ImageSize size, ImageType type,
                                double battery_percentage) {
  // Preserve the fully charged icon for 100% only.
  int battery_index = 0;
  if (battery_percentage >= 100) {
    battery_index = kNumPowerImages - 1;
  } else {
    battery_index = static_cast<int> (
        battery_percentage / 100.0 *
        nextafter(static_cast<double>(kNumPowerImages - 1), 0));
    battery_index =
        std::max(std::min(battery_index, kNumPowerImages - 2), 0);
  }
  return GetImage(size, type, battery_index);
}

SkBitmap GetMissingImage(ImageSize size) {
  return GetImage(size, DISCHARGING, kNumPowerImages);
}

SkBitmap GetUnknownImage(ImageSize size) {
  return GetImage(size, CHARGING, kNumPowerImages);
}

class BatteryIconView : public views::View {
 public:
  BatteryIconView()
      : battery_percentage_(0),
        battery_is_present_(false),
        line_power_on_(false),
        percentage_font_(ResourceBundle::GetSharedInstance().
                         GetFont(ResourceBundle::BaseFont).
                         DeriveFont(kBatteryFontSizeDelta, gfx::Font::BOLD)) {
  }

  virtual gfx::Size GetPreferredSize() OVERRIDE {
    return gfx::Size(kLargeImageWidth, kLargeImageHeight);
  }

  void set_battery_percentage(double battery_percentage) {
    battery_percentage_ = battery_percentage;
    SchedulePaint();
  }

  void set_battery_is_present(bool battery_is_present) {
    battery_is_present_ = battery_is_present;
    SchedulePaint();
  }

  void set_line_power_on(bool line_power_on) {
    line_power_on_ = line_power_on;
    SchedulePaint();
  }

 protected:
  virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE {
    SkBitmap image;
    if (!battery_is_present_) {
      image = GetMissingImage(LARGE);
    } else {
      image = GetImageWithPercentage(LARGE,
                                     line_power_on_ ? CHARGING : DISCHARGING,
                                     battery_percentage_);
    }
    const int image_x = 0;
    const int image_y = (height() - image.height()) / 2;
    canvas->DrawBitmapInt(image, image_x, image_y);

    if (battery_is_present_ && (battery_percentage_ < 100 || !line_power_on_)) {
      const string16 text = UTF8ToUTF16(base::StringPrintf(
          "%d%%", static_cast<int>(battery_percentage_)));
      const int text_h = percentage_font_.GetHeight();
      const int text_y = ((height() - text_h) / 2);
      canvas->DrawStringInt(
          text, percentage_font_, kPercentageShadowColor,
          image_x, text_y + 1, image.width(), text_h,
          gfx::Canvas::TEXT_ALIGN_CENTER | gfx::Canvas::NO_ELLIPSIS);
      canvas->DrawStringInt(
          text, percentage_font_, kPercentageColor,
          image_x, text_y, image.width(), text_h,
          gfx::Canvas::TEXT_ALIGN_CENTER | gfx::Canvas::NO_ELLIPSIS);
      if (line_power_on_)
        canvas->DrawBitmapInt(
            GetImageWithPercentage(LARGE, BOLT, battery_percentage_),
            image_x, image_y);
    }
  }

 private:
  double battery_percentage_;
  bool battery_is_present_;
  bool line_power_on_;
  gfx::Font percentage_font_;

  DISALLOW_COPY_AND_ASSIGN(BatteryIconView);
};

}  // namespace

namespace chromeos {

using base::TimeDelta;

////////////////////////////////////////////////////////////////////////////////
// PowerMenuButton

PowerMenuButton::PowerMenuButton(StatusAreaButton::Delegate* delegate)
    : StatusAreaButton(delegate, this),
      battery_is_present_(false),
      line_power_on_(false),
      battery_percentage_(0.0),
      battery_time_to_full_(TimeDelta::FromMicroseconds(kInitialMS)),
      battery_time_to_empty_(TimeDelta::FromMicroseconds(kInitialMS)),
      status_(NULL) {
  set_id(VIEW_ID_STATUS_BUTTON_POWER);
  UpdateIconAndLabelInfo();
  DBusThreadManager::Get()->GetPowerManagerClient()->AddObserver(this);
  DBusThreadManager::Get()->GetPowerManagerClient()->RequestStatusUpdate();
}

PowerMenuButton::~PowerMenuButton() {
  DBusThreadManager::Get()->GetPowerManagerClient()->RemoveObserver(this);
}

// PowerMenuButton, views::MenuDelegate implementation:

string16 PowerMenuButton::GetLabel(int id) const {
  return string16();
}

string16 PowerMenuButton::GetBatteryIsChargedText() const {
  // The second item shows the battery is charged if it is.
  if (battery_percentage_ >= 100 && line_power_on_)
    return l10n_util::GetStringUTF16(IDS_STATUSBAR_BATTERY_IS_CHARGED);

  // If battery is in an intermediate charge state, show how much time left.
  TimeDelta time = line_power_on_ ? battery_time_to_full_ :
      battery_time_to_empty_;
  if (time.InSeconds() == 0) {
    // If time is 0, then that means we are still calculating how much time.
    // Depending if line power is on, we either show a message saying that we
    // are calculating time until full or calculating remaining time.
    int msg = line_power_on_ ?
        IDS_STATUSBAR_BATTERY_CALCULATING_TIME_UNTIL_FULL :
        IDS_STATUSBAR_BATTERY_CALCULATING_TIME_UNTIL_EMPTY;
    return l10n_util::GetStringUTF16(msg);
  } else {
    // Depending if line power is on, we either show a message saying XX:YY
    // until full or XX:YY remaining where XX is number of hours and YY is
    // number of minutes.
    int msg = line_power_on_ ? IDS_STATUSBAR_BATTERY_TIME_UNTIL_FULL :
        IDS_STATUSBAR_BATTERY_TIME_UNTIL_EMPTY;
    int hour = time.InHours();
    int min = (time - TimeDelta::FromHours(hour)).InMinutes();
    string16 hour_str = base::IntToString16(hour);
    string16 min_str = base::IntToString16(min);
    // Append a "0" before the minute if it's only a single digit.
    if (min < 10)
      min_str = ASCIIToUTF16("0") + min_str;
    return l10n_util::GetStringFUTF16(msg, hour_str, min_str);
  }
}

int PowerMenuButton::icon_width() {
  return 26;
}

////////////////////////////////////////////////////////////////////////////////
// PowerMenuButton, views::View implementation:
void PowerMenuButton::OnLocaleChanged() {
  UpdateIconAndLabelInfo();
}

////////////////////////////////////////////////////////////////////////////////
// PowerMenuButton, views::ViewMenuDelegate implementation:

void PowerMenuButton::RunMenu(views::View* source, const gfx::Point& pt) {
  // Explicitly query the power status.
  DBusThreadManager::Get()->GetPowerManagerClient()->RequestStatusUpdate();

  views::MenuItemView* menu = new views::MenuItemView(this);
  // MenuRunner takes ownership of |menu|.
  menu_runner_.reset(new views::MenuRunner(menu));
  views::MenuItemView* submenu = menu->AppendMenuItem(
      POWER_BATTERY_PERCENTAGE_ITEM,
      string16(),
      views::MenuItemView::NORMAL);
  status_ = new StatusAreaBubbleContentView(new BatteryIconView, string16());
  UpdateStatusView();
  submenu->AddChildView(status_);
  menu->CreateSubmenu()->set_resize_open_menu(true);
  menu->SetMargins(0, 0);
  submenu->SetMargins(0, 0);
  menu->ChildrenChanged();

  gfx::Point screen_location;
  views::View::ConvertPointToScreen(source, &screen_location);
  gfx::Rect bounds(screen_location, source->size());
  if (menu_runner_->RunMenuAt(
          source->GetWidget()->GetTopLevelWidget(), this, bounds,
          views::MenuItemView::TOPRIGHT, views::MenuRunner::HAS_MNEMONICS) ==
      views::MenuRunner::MENU_DELETED)
    return;
  status_ = NULL;
  menu_runner_.reset(NULL);
}

////////////////////////////////////////////////////////////////////////////////
// PowerMenuButton, PowerManagerClient::Observer implementation:

void PowerMenuButton::PowerChanged(const PowerSupplyStatus& power_status) {
  power_status_ = power_status;
  UpdateIconAndLabelInfo();
}

////////////////////////////////////////////////////////////////////////////////
// PowerMenuButton, StatusAreaButton implementation:

void PowerMenuButton::UpdateIconAndLabelInfo() {
  battery_is_present_ = power_status_.battery_is_present;
  line_power_on_ = power_status_.line_power_on;

  // If fully charged, always show 100% even if internal number is a bit less.
  if (power_status_.battery_is_full)
    battery_percentage_ = 100.0;
  else
    battery_percentage_ = power_status_.battery_percentage;

  UpdateBatteryTime(&battery_time_to_full_,
                    TimeDelta::FromSeconds(
                        power_status_.battery_seconds_to_full));
  UpdateBatteryTime(&battery_time_to_empty_,
                    TimeDelta::FromSeconds(
                        power_status_.battery_seconds_to_empty));

  string16 tooltip_text;
  if (!battery_is_present_) {
    SetIcon(GetMissingImage(SMALL));
    tooltip_text = l10n_util::GetStringUTF16(IDS_STATUSBAR_NO_BATTERY);
  } else {
    SetIcon(GetImageWithPercentage(
        SMALL, line_power_on_ ? CHARGING : DISCHARGING, battery_percentage_));
    const int message_id = line_power_on_ ?
        IDS_STATUSBAR_BATTERY_CHARGING_PERCENTAGE :
        IDS_STATUSBAR_BATTERY_USING_PERCENTAGE;
    tooltip_text =  l10n_util::GetStringFUTF16(
        message_id, base::IntToString16(static_cast<int>(battery_percentage_)));
  }
  SetTooltipText(tooltip_text);
  SetAccessibleName(tooltip_text);
  SchedulePaint();
  UpdateStatusView();
}

void PowerMenuButton::UpdateStatusView() {
  if (status_) {
    string16 charging_text;
    if (battery_is_present_) {
      charging_text = GetBatteryIsChargedText();
    } else {
      charging_text = l10n_util::GetStringUTF16(IDS_STATUSBAR_NO_BATTERY);
    }
    status_->SetMessage(charging_text);
    BatteryIconView* battery_icon_view =
        static_cast<BatteryIconView*>(status_->icon_view());
    battery_icon_view->set_battery_percentage(battery_percentage_);
    battery_icon_view->set_battery_is_present(battery_is_present_);
    battery_icon_view->set_line_power_on(line_power_on_);
  }
}

void PowerMenuButton::UpdateBatteryTime(TimeDelta* previous,
                                        const TimeDelta& current) {
  static const TimeDelta kMaxDiff(TimeDelta::FromMinutes(10));
  static const TimeDelta kMinDiff(TimeDelta::FromMinutes(0));
  const TimeDelta diff = current - *previous;
  // If the diff is small and positive, ignore it in favor of
  // keeping time monotonically decreasing.
  // If previous is 0, then it either was never set (initial condition)
  // or got down to 0.
  if (*previous == TimeDelta::FromMicroseconds(kInitialMS) ||
      diff < kMinDiff ||
      diff > kMaxDiff) {
    *previous = current;
  }
}

}  // namespace chromeos
<|endoftext|>


<commit_before>//===--- Compilation.cpp - Compilation Task Implementation --------------*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "clang/Driver/Compilation.h"

#include "clang/Driver/Action.h"
#include "clang/Driver/ArgList.h"
#include "clang/Driver/ToolChain.h"

using namespace clang::driver;

Compilation::Compilation(ToolChain &_DefaultToolChain,
                         ArgList *_Args)
  : DefaultToolChain(_DefaultToolChain), Args(_Args) {
}

Compilation::~Compilation() {
  delete Args;

  // Free any derived arg lists.
  for (llvm::DenseMap<const ToolChain*, ArgList*>::iterator
         it = TCArgs.begin(), ie = TCArgs.end(); it != ie; ++it) {
    ArgList *A = it->second;
    if (A != Args)
      delete Args;
  }

  // Free the actions, if built.
  for (ActionList::iterator it = Actions.begin(), ie = Actions.end();
       it != ie; ++it)
    delete *it;
}

const ArgList &Compilation::getArgsForToolChain(const ToolChain *TC) {
  if (!TC)
    TC = &DefaultToolChain;

  ArgList *&Args = TCArgs[TC];
  if (!Args)
    Args = TC->TranslateArgs(*Args);

  return *Args;
}

int Compilation::Execute() const {
  return 0;
}
<commit_msg>Driver: Fix Compilation::getArgsForToolChain, local variable was shadowing member.<commit_after>//===--- Compilation.cpp - Compilation Task Implementation --------------*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "clang/Driver/Compilation.h"

#include "clang/Driver/Action.h"
#include "clang/Driver/ArgList.h"
#include "clang/Driver/ToolChain.h"

using namespace clang::driver;

Compilation::Compilation(ToolChain &_DefaultToolChain,
                         ArgList *_Args)
  : DefaultToolChain(_DefaultToolChain), Args(_Args) {
}

Compilation::~Compilation() {
  delete Args;

  // Free any derived arg lists.
  for (llvm::DenseMap<const ToolChain*, ArgList*>::iterator
         it = TCArgs.begin(), ie = TCArgs.end(); it != ie; ++it) {
    ArgList *A = it->second;
    if (A != Args)
      delete Args;
  }

  // Free the actions, if built.
  for (ActionList::iterator it = Actions.begin(), ie = Actions.end();
       it != ie; ++it)
    delete *it;
}

const ArgList &Compilation::getArgsForToolChain(const ToolChain *TC) {
  if (!TC)
    TC = &DefaultToolChain;

  ArgList *&Entry = TCArgs[TC];
  if (!Entry)
    Entry = TC->TranslateArgs(*Args);

  return *Entry;
}

int Compilation::Execute() const {
  return 0;
}
<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2018 The Apollo Authors. All Rights Reserved.
 *
 * 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 "modules/prediction/scenario/feature_extractor/feature_extractor.h"

#include <string>

#include "modules/common/adapters/proto/adapter_config.pb.h"
#include "modules/common/math/vec2d.h"
#include "modules/map/hdmap/hdmap_util.h"

using apollo::common::adapter::AdapterConfig;
using apollo::common::math::Vec2d;
using apollo::planning::ADCTrajectory;
using apollo::hdmap::HDMapUtil;
using apollo::hdmap::LaneInfo;
using apollo::hdmap::JunctionInfo;
using apollo::perception::PerceptionObstacle;
using JunctionInfoPtr = std::shared_ptr<const JunctionInfo>;
using LaneInfoPtr = std::shared_ptr<const LaneInfo>;

namespace apollo {
namespace prediction {

EnvironmentFeatures FeatureExtractor::ExtractEnvironmentFeatures() {
  EnvironmentFeatures environment_features;

  PoseContainer* pose_container = dynamic_cast<PoseContainer*>(
      ContainerManager::Instance()->GetContainer(
          AdapterConfig::LOCALIZATION));

  if (pose_container == nullptr) {
    AERROR << "Null pose container found.";
    return environment_features;
  }
  ExtractEgoVehicleFeatures(&environment_features);

  const PerceptionObstacle* pose_ptr = pose_container->ToPerceptionObstacle();
  if (pose_ptr == nullptr) {
    AERROR << "Null pose pointer, skip extracting environment features.";
    return environment_features;
  }

  auto ego_trajectory_point = pose_ptr->position();
  if (!ego_trajectory_point.has_x() ||
      !ego_trajectory_point.has_y()) {
    AERROR << "Fail to get ego vehicle position";
    return environment_features;
  }
  Vec2d ego_position(ego_trajectory_point.x(), ego_trajectory_point.y());

  auto ptr_ego_lane = GetEgoLane(ego_position);

  ExtractEgoLaneFeatures(&environment_features,
      ptr_ego_lane, ego_position);

  ExtractNeighborLaneFeatures(
      &environment_features, ptr_ego_lane, ego_position);

  ExtractFrontJunctionFeatures(&environment_features);

  ExtractObstacleFeatures(&environment_features);

  // TODO(all): add other features

  return environment_features;
}

void FeatureExtractor::ExtractEgoVehicleFeatures(
    EnvironmentFeatures* ptr_environment_features) {
  PoseContainer* pose_container = dynamic_cast<PoseContainer*>(
      ContainerManager::Instance()->GetContainer(
          AdapterConfig::LOCALIZATION));
  const PerceptionObstacle* pose_ptr = pose_container->ToPerceptionObstacle();
  if (pose_ptr == nullptr) {
    AERROR << "Null pose pointer";
    return;
  }
  // TODO(all): change this to ego_speed and ego_heading
  double pose_speed = std::hypot(pose_ptr->velocity().x(),
                                 pose_ptr->velocity().y());
  ptr_environment_features->set_ego_speed(pose_speed);
  ptr_environment_features->set_ego_heading(pose_ptr->theta());
  // TODO(all): add acceleration if needed
}

void FeatureExtractor::ExtractEgoLaneFeatures(
    EnvironmentFeatures* ptr_environment_features,
    const LaneInfoPtr& ptr_ego_lane,
    const common::math::Vec2d& ego_position) {

  if (ptr_ego_lane == nullptr) {
    AERROR << "Ego vehicle is not on any lane.";
    return;
  }
  ADEBUG << "Ego vehicle is on lane [" << ptr_ego_lane->id().id() << "]";
  double curr_lane_s = 0.0;
  double curr_lane_l = 0.0;
  ptr_ego_lane->GetProjection(ego_position, &curr_lane_s, &curr_lane_l);
  ptr_environment_features->SetEgoLane(ptr_ego_lane->id().id(), curr_lane_s);

  double threshold = 1.0;
  auto ptr_left_neighbor_lane = PredictionMap::GetLeftNeighborLane(
      ptr_ego_lane, {ego_position.x(), ego_position.y()}, threshold);

  if (ptr_left_neighbor_lane == nullptr &&
      ptr_ego_lane->lane().has_left_boundary() &&
      ptr_ego_lane->lane().left_boundary().boundary_type_size() != 0 &&
      ptr_ego_lane->lane().left_boundary().boundary_type(0).types_size() != 0 &&
      ptr_ego_lane->lane().left_boundary().boundary_type(0).types(0) !=
      hdmap::LaneBoundaryType::CURB) {
    const auto& reverse_lanes =
        ptr_ego_lane->lane().left_neighbor_reverse_lane_id();
    std::for_each(reverse_lanes.begin(), reverse_lanes.end(),
        [&ptr_environment_features](decltype(*reverse_lanes.begin())& t) {
      ptr_environment_features->AddNonneglectableReverseLanes(t.id());
    });
  }
}

void FeatureExtractor::ExtractNeighborLaneFeatures(
    EnvironmentFeatures* ptr_environment_features,
    const LaneInfoPtr& ptr_ego_lane, const Vec2d& ego_position) {

  if (ptr_ego_lane == nullptr) {
    AERROR << "Ego vehicle is not on any lane.";
    return;
  }

  // TODO(all): make this a gflag
  double threshold = 3.0;

  auto ptr_left_neighbor_lane = PredictionMap::GetLeftNeighborLane(
      ptr_ego_lane, {ego_position.x(), ego_position.y()}, threshold);

  if (ptr_left_neighbor_lane != nullptr) {
    double left_neighbor_lane_s = 0.0;
    double left_neighbor_lane_l = 0.0;
    ptr_left_neighbor_lane->GetProjection(ego_position,
        &left_neighbor_lane_s, &left_neighbor_lane_l);
    ptr_environment_features->SetLeftNeighborLane(
        ptr_left_neighbor_lane->id().id(), left_neighbor_lane_s);
  }

  auto ptr_right_neighbor_lane = PredictionMap::GetRightNeighborLane(
      ptr_ego_lane, {ego_position.x(), ego_position.y()}, threshold);
  if (ptr_right_neighbor_lane != nullptr) {
    double right_neighbor_lane_s = 0.0;
    double right_neighbor_lane_l = 0.0;
    ptr_right_neighbor_lane->GetProjection(ego_position,
        &right_neighbor_lane_s, &right_neighbor_lane_l);
    ptr_environment_features->SetRightNeighborLane(
        ptr_right_neighbor_lane->id().id(), right_neighbor_lane_s);
  }
}

void FeatureExtractor::ExtractFrontJunctionFeatures(
    EnvironmentFeatures* ptr_environment_features) {
  ADCTrajectoryContainer* ego_trajectory_container =
      dynamic_cast<ADCTrajectoryContainer*>(
          ContainerManager::Instance()->GetContainer(
              AdapterConfig::PLANNING_TRAJECTORY));
  if (ego_trajectory_container == nullptr) {
    AERROR << "Null ego trajectory container";
    return;
  }
  JunctionInfoPtr junction = ego_trajectory_container->ADCJunction();
  if (junction != nullptr) {
    ptr_environment_features->SetFrontJunction(junction->id().id(),
        ego_trajectory_container->ADCDistanceToJunction());
  }
}

void FeatureExtractor::ExtractObstacleFeatures(
    EnvironmentFeatures* ptr_environment_features) {
}

LaneInfoPtr FeatureExtractor::GetEgoLane(const Vec2d& ego_position) {
  ADCTrajectoryContainer* ego_trajectory_container =
      dynamic_cast<ADCTrajectoryContainer*>(
          ContainerManager::Instance()->GetContainer(
              AdapterConfig::PLANNING_TRAJECTORY));
  const auto& trajectory =
      ego_trajectory_container->adc_trajectory();
  for (const auto& lane_id : trajectory.lane_id()) {
    LaneInfoPtr lane_info =
        HDMapUtil::BaseMap().GetLaneById(hdmap::MakeMapId(lane_id.id()));
    if (lane_info->IsOnLane(ego_position)) {
      return lane_info;
    }
  }
  return nullptr;
}

}  // namespace prediction
}  // namespace apollo
<commit_msg>prediction: bug fix for null pointer issue in FeatureExtractor<commit_after>/******************************************************************************
 * Copyright 2018 The Apollo Authors. All Rights Reserved.
 *
 * 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 "modules/prediction/scenario/feature_extractor/feature_extractor.h"

#include <string>

#include "modules/common/adapters/proto/adapter_config.pb.h"
#include "modules/common/math/vec2d.h"
#include "modules/map/hdmap/hdmap_util.h"

using apollo::common::adapter::AdapterConfig;
using apollo::common::math::Vec2d;
using apollo::planning::ADCTrajectory;
using apollo::hdmap::HDMapUtil;
using apollo::hdmap::LaneInfo;
using apollo::hdmap::JunctionInfo;
using apollo::perception::PerceptionObstacle;
using JunctionInfoPtr = std::shared_ptr<const JunctionInfo>;
using LaneInfoPtr = std::shared_ptr<const LaneInfo>;

namespace apollo {
namespace prediction {

EnvironmentFeatures FeatureExtractor::ExtractEnvironmentFeatures() {
  EnvironmentFeatures environment_features;

  PoseContainer* pose_container = dynamic_cast<PoseContainer*>(
      ContainerManager::Instance()->GetContainer(
          AdapterConfig::LOCALIZATION));

  if (pose_container == nullptr) {
    AERROR << "Null pose container found.";
    return environment_features;
  }
  ExtractEgoVehicleFeatures(&environment_features);

  const PerceptionObstacle* pose_ptr = pose_container->ToPerceptionObstacle();
  if (pose_ptr == nullptr) {
    AERROR << "Null pose pointer, skip extracting environment features.";
    return environment_features;
  }

  auto ego_trajectory_point = pose_ptr->position();
  if (!ego_trajectory_point.has_x() ||
      !ego_trajectory_point.has_y()) {
    AERROR << "Fail to get ego vehicle position";
    return environment_features;
  }
  Vec2d ego_position(ego_trajectory_point.x(), ego_trajectory_point.y());

  auto ptr_ego_lane = GetEgoLane(ego_position);

  ExtractEgoLaneFeatures(&environment_features,
      ptr_ego_lane, ego_position);

  ExtractNeighborLaneFeatures(
      &environment_features, ptr_ego_lane, ego_position);

  ExtractFrontJunctionFeatures(&environment_features);

  ExtractObstacleFeatures(&environment_features);

  // TODO(all): add other features

  return environment_features;
}

void FeatureExtractor::ExtractEgoVehicleFeatures(
    EnvironmentFeatures* ptr_environment_features) {
  PoseContainer* pose_container = dynamic_cast<PoseContainer*>(
      ContainerManager::Instance()->GetContainer(
          AdapterConfig::LOCALIZATION));
  const PerceptionObstacle* pose_ptr = pose_container->ToPerceptionObstacle();
  if (pose_ptr == nullptr) {
    AERROR << "Null pose pointer";
    return;
  }
  // TODO(all): change this to ego_speed and ego_heading
  double pose_speed = std::hypot(pose_ptr->velocity().x(),
                                 pose_ptr->velocity().y());
  ptr_environment_features->set_ego_speed(pose_speed);
  ptr_environment_features->set_ego_heading(pose_ptr->theta());
  // TODO(all): add acceleration if needed
}

void FeatureExtractor::ExtractEgoLaneFeatures(
    EnvironmentFeatures* ptr_environment_features,
    const LaneInfoPtr& ptr_ego_lane,
    const common::math::Vec2d& ego_position) {

  if (ptr_ego_lane == nullptr) {
    AERROR << "Ego vehicle is not on any lane.";
    return;
  }
  ADEBUG << "Ego vehicle is on lane [" << ptr_ego_lane->id().id() << "]";
  double curr_lane_s = 0.0;
  double curr_lane_l = 0.0;
  ptr_ego_lane->GetProjection(ego_position, &curr_lane_s, &curr_lane_l);
  ptr_environment_features->SetEgoLane(ptr_ego_lane->id().id(), curr_lane_s);

  double threshold = 1.0;
  auto ptr_left_neighbor_lane = PredictionMap::GetLeftNeighborLane(
      ptr_ego_lane, {ego_position.x(), ego_position.y()}, threshold);

  if (ptr_left_neighbor_lane == nullptr &&
      ptr_ego_lane->lane().has_left_boundary() &&
      ptr_ego_lane->lane().left_boundary().boundary_type_size() != 0 &&
      ptr_ego_lane->lane().left_boundary().boundary_type(0).types_size() != 0 &&
      ptr_ego_lane->lane().left_boundary().boundary_type(0).types(0) !=
      hdmap::LaneBoundaryType::CURB) {
    const auto& reverse_lanes =
        ptr_ego_lane->lane().left_neighbor_reverse_lane_id();
    std::for_each(reverse_lanes.begin(), reverse_lanes.end(),
        [&ptr_environment_features](decltype(*reverse_lanes.begin())& t) {
      ptr_environment_features->AddNonneglectableReverseLanes(t.id());
    });
  }
}

void FeatureExtractor::ExtractNeighborLaneFeatures(
    EnvironmentFeatures* ptr_environment_features,
    const LaneInfoPtr& ptr_ego_lane, const Vec2d& ego_position) {

  if (ptr_ego_lane == nullptr) {
    AERROR << "Ego vehicle is not on any lane.";
    return;
  }

  // TODO(all): make this a gflag
  double threshold = 3.0;

  auto ptr_left_neighbor_lane = PredictionMap::GetLeftNeighborLane(
      ptr_ego_lane, {ego_position.x(), ego_position.y()}, threshold);

  if (ptr_left_neighbor_lane != nullptr) {
    double left_neighbor_lane_s = 0.0;
    double left_neighbor_lane_l = 0.0;
    ptr_left_neighbor_lane->GetProjection(ego_position,
        &left_neighbor_lane_s, &left_neighbor_lane_l);
    ptr_environment_features->SetLeftNeighborLane(
        ptr_left_neighbor_lane->id().id(), left_neighbor_lane_s);
  }

  auto ptr_right_neighbor_lane = PredictionMap::GetRightNeighborLane(
      ptr_ego_lane, {ego_position.x(), ego_position.y()}, threshold);
  if (ptr_right_neighbor_lane != nullptr) {
    double right_neighbor_lane_s = 0.0;
    double right_neighbor_lane_l = 0.0;
    ptr_right_neighbor_lane->GetProjection(ego_position,
        &right_neighbor_lane_s, &right_neighbor_lane_l);
    ptr_environment_features->SetRightNeighborLane(
        ptr_right_neighbor_lane->id().id(), right_neighbor_lane_s);
  }
}

void FeatureExtractor::ExtractFrontJunctionFeatures(
    EnvironmentFeatures* ptr_environment_features) {
  ADCTrajectoryContainer* ego_trajectory_container =
      dynamic_cast<ADCTrajectoryContainer*>(
          ContainerManager::Instance()->GetContainer(
              AdapterConfig::PLANNING_TRAJECTORY));
  if (ego_trajectory_container == nullptr) {
    AERROR << "Null ego trajectory container";
    return;
  }
  JunctionInfoPtr junction = ego_trajectory_container->ADCJunction();
  if (junction != nullptr) {
    ptr_environment_features->SetFrontJunction(junction->id().id(),
        ego_trajectory_container->ADCDistanceToJunction());
  }
}

void FeatureExtractor::ExtractObstacleFeatures(
    EnvironmentFeatures* ptr_environment_features) {
}

LaneInfoPtr FeatureExtractor::GetEgoLane(const Vec2d& ego_position) {
  ADCTrajectoryContainer* ego_trajectory_container =
      dynamic_cast<ADCTrajectoryContainer*>(
          ContainerManager::Instance()->GetContainer(
              AdapterConfig::PLANNING_TRAJECTORY));
  const auto& trajectory =
      ego_trajectory_container->adc_trajectory();
  for (const auto& lane_id : trajectory.lane_id()) {
    LaneInfoPtr lane_info =
        HDMapUtil::BaseMap().GetLaneById(hdmap::MakeMapId(lane_id.id()));

    if (lane_info == nullptr) {
      continue;
    }

    if (lane_info->IsOnLane(ego_position)) {
      return lane_info;
    }
  }
  return nullptr;
}

}  // namespace prediction
}  // namespace apollo
<|endoftext|>


<commit_before>#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"

// Mix
#include "VDMix.h"

using namespace ci;
using namespace ci::app;
using namespace std;
using namespace VideoDromm;

class _TBOX_PREFIX_App : public App {

public:

	void setup() override;
	void mouseDown( MouseEvent event ) override;
	void mouseMove( MouseEvent event ) override;
	void fileDrop(FileDropEvent event) override;
	void update() override;
	void draw() override;
	void cleanup() override;
private:
	VDMixList					mMixes;
	fs::path					mMixesFilepath;
};

void _TBOX_PREFIX_App::setup()
{
		// initialize
	mMixesFilepath = getAssetPath("") / "mixes.xml";
	if (fs::exists(mMixesFilepath)) {
		// load textures from file if one exists
		mMixes = VDMix::readSettings(loadFile(mMixesFilepath));
	}
	else {
		// otherwise create a texture from scratch
		mMixes.push_back(VDMix::create());
	}
}
void _TBOX_PREFIX_App::fileDrop(FileDropEvent event)
{
	int index = 1;
	bool right = true;
	string ext = "";
	// use the last of the dropped files
	fs::path mPath = event.getFile(event.getNumFiles() - 1);
	string mFile = mPath.string();
	int dotIndex = mFile.find_last_of(".");
	int slashIndex = mFile.find_last_of("\\");
	// determine right or left from x position
	right = ((float)event.getX() / getWindowWidth() > 0.5);

	if (dotIndex != std::string::npos && dotIndex > slashIndex) ext = mFile.substr(mFile.find_last_of(".") + 1);

	if (ext == "png" || ext == "jpg")
	{
		mMixes[0]->loadImageFile(mFile, index, 0, right);
	}
	else if (ext == "glsl")
	{
		int rtn = mMixes[0]->loadFboFragmentShader(mFile, right);//right = true
	}
}
void _TBOX_PREFIX_App::update()
{

}
void _TBOX_PREFIX_App::cleanup()
{

	// save mix settings
	VDMix::writeSettings(mMixes, writeFile(mMixesFilepath));

	quit();
}
void _TBOX_PREFIX_App::mouseDown(MouseEvent event)
{
	mMixes[0]->setZoom((float)event.getX() / 640.0f);
	mMixes[0]->setCrossfade((float)event.getY() / 480.0f);

}
void _TBOX_PREFIX_App::mouseMove(MouseEvent event)
{
	mMixes[0]->setPosition(event.getX(), event.getY());

}

void _TBOX_PREFIX_App::draw()
{
	gl::clear( Color( 0, 0, 0 ) );
	gl::draw(mMixes[0]->getRightFboTexture(), Rectf(0, 0, 128, 128));
	gl::draw(mMixes[0]->getLeftFboTexture(), Rectf(128, 0, 256, 128));
	gl::draw(mMixes[0]->getFboTexture(0), Rectf(256, 0, 384, 128));
	gl::draw(mMixes[0]->getFboTexture(1), Rectf(384, 0, 512, 128));
	gl::draw(mMixes[0]->getFboInputTexture(0,0), Rectf(0, 128, 128, 256));
	gl::draw(mMixes[0]->getTexture(), Rectf(128, 128, 256, 256));
}

CINDER_APP(_TBOX_PREFIX_App, RendererGl)
<commit_msg>broken...<commit_after>#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"

// Mix
#include "VDMix.h"

using namespace ci;
using namespace ci::app;
using namespace std;
using namespace VideoDromm;

class _TBOX_PREFIX_App : public App {

public:

	void setup() override;
	void mouseDown( MouseEvent event ) override;
	void mouseMove( MouseEvent event ) override;
	void fileDrop(FileDropEvent event) override;
	void update() override;
	void draw() override;
	void cleanup() override;
private:
	VDMixList					mMixes;
	fs::path					mMixesFilepath;
};

void _TBOX_PREFIX_App::setup()
{
		// initialize
	mMixesFilepath = getAssetPath("") / "mixes.xml";
	if (fs::exists(mMixesFilepath)) {
		// load textures from file if one exists
		mMixes = VDMix::readSettings(loadFile(mMixesFilepath));
	}
	else {
		// otherwise create a texture from scratch
		mMixes.push_back(VDMix::create());
	}
}
void _TBOX_PREFIX_App::fileDrop(FileDropEvent event)
{
	int index = 1;
	bool right = true;
	string ext = "";
	// use the last of the dropped files
	fs::path mPath = event.getFile(event.getNumFiles() - 1);
	string mFile = mPath.string();
	int dotIndex = mFile.find_last_of(".");
	int slashIndex = mFile.find_last_of("\\");
	// determine right or left from x position
	right = ((float)event.getX() / getWindowWidth() > 0.5);

	if (dotIndex != std::string::npos && dotIndex > slashIndex) ext = mFile.substr(mFile.find_last_of(".") + 1);

	if (ext == "png" || ext == "jpg")
	{
		mMixes[0]->loadImageFile(mFile, index, 0, right);
	}
	else if (ext == "glsl")
	{
		int rtn = mMixes[0]->loadFboFragmentShader(mFile, right);//right = true
	}
}
void _TBOX_PREFIX_App::update()
{

}
void _TBOX_PREFIX_App::cleanup()
{

	// save mix settings
	VDMix::writeSettings(mMixes, writeFile(mMixesFilepath));

	quit();
}
void _TBOX_PREFIX_App::mouseDown(MouseEvent event)
{
	mMixes[0]->setZoom((float)event.getX() / 640.0f);
	mMixes[0]->setCrossfade((float)event.getY() / 480.0f);

}
void _TBOX_PREFIX_App::mouseMove(MouseEvent event)
{
	mMixes[0]->setPosition(event.getX(), event.getY());

}

void _TBOX_PREFIX_App::draw()
{
	gl::clear( Color( 0, 0, 0 ) );
	gl::draw(mMixes[0]->getRightFboTexture(), Rectf(0, 0, 128, 128));
	gl::draw(mMixes[0]->getLeftFboTexture(), Rectf(128, 0, 256, 128));
	gl::draw(mMixes[0]->getFboTexture(0), Rectf(256, 0, 384, 128));
	gl::draw(mMixes[0]->getFboTexture(1), Rectf(384, 0, 512, 128));
	gl::draw(mMixes[0]->getTexture(), Rectf(512, 0, 640, 128));

	gl::draw(mMixes[0]->getFboInputTexture(0, 0), Rectf(0, 128, 128, 256));
	gl::draw(mMixes[0]->getFboInputTexture(0, 1), Rectf(128, 128, 256, 256));
	gl::draw(mMixes[0]->getFboInputTexture(0, 2), Rectf(256, 128, 384, 256));
	gl::draw(mMixes[0]->getFboInputTexture(0, 3), Rectf(384, 128, 512, 256));
	gl::draw(mMixes[0]->getFboInputTexture(0, 4), Rectf(512, 128, 640, 256));

	gl::draw(mMixes[0]->getFboInputTexture(1, 0), Rectf(0, 256, 128, 384));
	gl::draw(mMixes[0]->getFboInputTexture(1, 1), Rectf(128, 256, 256, 384));
	gl::draw(mMixes[0]->getFboInputTexture(1, 2), Rectf(256, 256, 384, 384));
	gl::draw(mMixes[0]->getFboInputTexture(1, 3), Rectf(384, 256, 512, 384));
	gl::draw(mMixes[0]->getFboInputTexture(1, 4), Rectf(512, 256, 640, 384));
}

CINDER_APP(_TBOX_PREFIX_App, RendererGl)
<|endoftext|>


<commit_before>#pragma once
/**
	@file
	@brief atomic operation

	Copyright (C) 2007 Cybozu Labs, Inc., all rights reserved.
	@author MITSUNARI Shigeo
*/
#include <cybozu/inttype.hpp>
#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <intrin.h>
#else
#include <emmintrin.h>
#endif

namespace cybozu {

namespace atomic_util {

template<size_t S>
struct Tag {};

template<>
struct Tag<4> {
	typedef int type;

	template<class T>
	static inline T AtomicAddSub(T *p, T y)
	{
#ifdef _WIN32
		return (T)_InterlockedExchangeAdd((long*)p, (long)y);
#else
		return (T)__sync_fetch_and_add(p, y);
#endif
	}

	template<class T>
	static inline T AtomicCompareExchangeSub(T *p, T newValue, T oldValue)
	{
#ifdef _WIN32
		return (T)InterlockedCompareExchange((long*)p, (long)newValue, (long)oldValue);
#else
		return (T)__sync_val_compare_and_swap(p, oldValue, newValue);
#endif
	}

	template<class T>
	static inline T AtomicExchangeSub(T *p, T newValue)
	{
#ifdef _WIN32
		return (T)InterlockedExchange((long*)p, (long)newValue);
#else
		return (T)__sync_lock_test_and_set(p, newValue);
#endif
	}
};

template<>
struct Tag<8> {
	typedef int64_t type;

#if (CYBOZU_OS_BIT == 64)
	template<class T>
	static inline T AtomicAddSub(T *p, T y)
	{
#ifdef _WIN32
		return (T)_InterlockedExchangeAdd64((int64_t*)p, (int64_t)y);
#else
		return (T)__sync_fetch_and_add(p, y);
#endif
	}
#endif

	template<class T>
	static inline T AtomicCompareExchangeSub(T *p, T newValue, T oldValue)
	{
#ifdef _WIN32
		return (T)_InterlockedCompareExchange64((int64_t*)p, (int64_t)newValue, (int64_t)oldValue);
#else
		return (T)__sync_val_compare_and_swap(p, oldValue, newValue);
#endif
	}

#if (CYBOZU_OS_BIT == 64)
	template<class T>
	static inline T AtomicExchangeSub(T *p, T newValue)
	{
#ifdef _WIN32
		return (T)_InterlockedExchange64((int64_t*)p, (int64_t)newValue);
#else
		return (T)__sync_lock_test_and_set(p, newValue);
#endif
	}
#endif
};

} // atomic_util

/**
	atomic operation
	see http://gcc.gnu.org/onlinedocs/gcc-4.4.0/gcc/Atomic-Builtins.html
	http://msdn.microsoft.com/en-us/library/ms683504(VS.85).aspx
*/
/**
	tmp = *p;
	*p += y;
	return tmp;
*/
template<class T>
T AtomicAdd(T *p, T y)
{
	return atomic_util::Tag<sizeof(T)>::AtomicAddSub(p, y);
}

/**
	tmp = *p;
	if (*p == oldValue) *p = newValue;
	return tmp;
*/
template<class T>
T AtomicCompareExchange(T *p, T newValue, T oldValue)
{
	return atomic_util::Tag<sizeof(T)>::AtomicCompareExchangeSub(p, newValue, oldValue);
}

/**
	tmp *p;
	*p = newValue;
	return tmp;
*/
template<class T>
T AtomicExchange(T *p, T newValue)
{
	return atomic_util::Tag<sizeof(T)>::AtomicExchangeSub(p, newValue);
}

inline void mfence()
{
#ifdef _MSC_VER
	MemoryBarrier();
#else
	_mm_mfence();
#endif
}

} // cybozu
<commit_msg>remove unused typedef<commit_after>#pragma once
/**
	@file
	@brief atomic operation

	Copyright (C) 2007 Cybozu Labs, Inc., all rights reserved.
	@author MITSUNARI Shigeo
*/
#include <cybozu/inttype.hpp>
#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <intrin.h>
#else
#include <emmintrin.h>
#endif

namespace cybozu {

namespace atomic_util {

template<size_t S>
struct Tag {};

template<>
struct Tag<4> {
	template<class T>
	static inline T AtomicAddSub(T *p, T y)
	{
#ifdef _WIN32
		return (T)_InterlockedExchangeAdd((long*)p, (long)y);
#else
		return (T)__sync_fetch_and_add(p, y);
#endif
	}

	template<class T>
	static inline T AtomicCompareExchangeSub(T *p, T newValue, T oldValue)
	{
#ifdef _WIN32
		return (T)InterlockedCompareExchange((long*)p, (long)newValue, (long)oldValue);
#else
		return (T)__sync_val_compare_and_swap(p, oldValue, newValue);
#endif
	}

	template<class T>
	static inline T AtomicExchangeSub(T *p, T newValue)
	{
#ifdef _WIN32
		return (T)InterlockedExchange((long*)p, (long)newValue);
#else
		return (T)__sync_lock_test_and_set(p, newValue);
#endif
	}
};

template<>
struct Tag<8> {
#if (CYBOZU_OS_BIT == 64)
	template<class T>
	static inline T AtomicAddSub(T *p, T y)
	{
#ifdef _WIN32
		return (T)_InterlockedExchangeAdd64((int64_t*)p, (int64_t)y);
#else
		return (T)__sync_fetch_and_add(p, y);
#endif
	}
#endif

	template<class T>
	static inline T AtomicCompareExchangeSub(T *p, T newValue, T oldValue)
	{
#ifdef _WIN32
		return (T)_InterlockedCompareExchange64((int64_t*)p, (int64_t)newValue, (int64_t)oldValue);
#else
		return (T)__sync_val_compare_and_swap(p, oldValue, newValue);
#endif
	}

#if (CYBOZU_OS_BIT == 64)
	template<class T>
	static inline T AtomicExchangeSub(T *p, T newValue)
	{
#ifdef _WIN32
		return (T)_InterlockedExchange64((int64_t*)p, (int64_t)newValue);
#else
		return (T)__sync_lock_test_and_set(p, newValue);
#endif
	}
#endif
};

} // atomic_util

/**
	atomic operation
	see http://gcc.gnu.org/onlinedocs/gcc-4.4.0/gcc/Atomic-Builtins.html
	http://msdn.microsoft.com/en-us/library/ms683504(VS.85).aspx
*/
/**
	tmp = *p;
	*p += y;
	return tmp;
*/
template<class T>
T AtomicAdd(T *p, T y)
{
	return atomic_util::Tag<sizeof(T)>::AtomicAddSub(p, y);
}

/**
	tmp = *p;
	if (*p == oldValue) *p = newValue;
	return tmp;
*/
template<class T>
T AtomicCompareExchange(T *p, T newValue, T oldValue)
{
	return atomic_util::Tag<sizeof(T)>::AtomicCompareExchangeSub(p, newValue, oldValue);
}

/**
	tmp *p;
	*p = newValue;
	return tmp;
*/
template<class T>
T AtomicExchange(T *p, T newValue)
{
	return atomic_util::Tag<sizeof(T)>::AtomicExchangeSub(p, newValue);
}

inline void mfence()
{
#ifdef _MSC_VER
	MemoryBarrier();
#else
	_mm_mfence();
#endif
}

} // cybozu
<|endoftext|>


<commit_before>#include "color.hpp"
#include "converter.hpp"

#include <iostream>
#include <string>

using namespace std;

int main(int argc, char *argv[])
{
	if (argc != 3) {
		return -1;
	}

	if (argv[1] == "rgba"s) {
		convert<color_rgba>(argv[2]);
	}
	else if (argv[1] == "ha"s) {
		convert<color_ha>(argv[2]);
	}
	else {
		return -1;
	}

	return 0;
}<commit_msg>Add help<commit_after>#include "color.hpp"
#include "converter.hpp"

#include <iostream>
#include <string>

using namespace std;

int main(int argc, char *argv[])
{
	if (argc != 3) {
		cout << "Should be only 2 arguments: [rgba|ha] path" << endl;
	}

	if (argv[1] == "rgba"s) {
		convert<color_rgba>(argv[2]);
	}
	else if (argv[1] == "ha"s) {
		convert<color_ha>(argv[2]);
	}
	else {
		cout << "Unknown color format" << endl;
	}

	return 0;
}<|endoftext|>


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

#include "chrome/browser/debugger/devtools_netlog_observer.h"

#include "base/string_util.h"
#include "chrome/browser/io_thread.h"
#include "chrome/common/resource_response.h"
#include "net/base/load_flags.h"
#include "net/http/http_net_log_params.h"
#include "net/http/http_response_headers.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_netlog_params.h"
#include "webkit/glue/resource_loader_bridge.h"

const size_t kMaxNumEntries = 1000;

DevToolsNetLogObserver* DevToolsNetLogObserver::instance_ = NULL;

DevToolsNetLogObserver::DevToolsNetLogObserver(ChromeNetLog* chrome_net_log)
    : ChromeNetLog::Observer(net::NetLog::LOG_ALL_BUT_BYTES),
      chrome_net_log_(chrome_net_log) {
  chrome_net_log_->AddObserver(this);
}

DevToolsNetLogObserver::~DevToolsNetLogObserver() {
  chrome_net_log_->RemoveObserver(this);
}

DevToolsNetLogObserver::ResourceInfo*
DevToolsNetLogObserver::GetResourceInfo(uint32 id) {
  RequestToInfoMap::iterator it = request_to_info_.find(id);
  if (it != request_to_info_.end())
    return it->second;
  return NULL;
}

void DevToolsNetLogObserver::OnAddEntry(net::NetLog::EventType type,
                                        const base::TimeTicks& time,
                                        const net::NetLog::Source& source,
                                        net::NetLog::EventPhase phase,
                                        net::NetLog::EventParameters* params) {
  if (type == net::NetLog::TYPE_URL_REQUEST_START_JOB) {
    if (phase != net::NetLog::PHASE_BEGIN)
      return;
    int load_flags = static_cast<URLRequestStartEventParameters*>(params)->
        load_flags();
    if (!(load_flags & net::LOAD_REPORT_RAW_HEADERS))
      return;
    if (request_to_info_.size() > kMaxNumEntries) {
      LOG(WARNING) << "The raw headers observer url request count has grown "
                      "larger than expected, resetting";
      request_to_info_.clear();
    }
    scoped_refptr<ResourceInfo> new_record(new ResourceInfo());
    request_to_info_.insert(std::make_pair(source.id, new_record));
    return;
  }
  if (type == net::NetLog::TYPE_REQUEST_ALIVE &&
      phase == net::NetLog::PHASE_END) {
    request_to_info_.erase(source.id);
    return;
  }
  if (type != net::NetLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST_HEADERS &&
      type != net::NetLog::TYPE_HTTP_TRANSACTION_READ_RESPONSE_HEADERS)
    return;

  ResourceInfo* info = GetResourceInfo(source.id);
  if (!info)
    return;

  switch (type) {
    case net::NetLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST_HEADERS: {
      const net::HttpRequestHeaders &request_headers =
          static_cast<net::NetLogHttpRequestParameter*>(params)->GetHeaders();
      for (net::HttpRequestHeaders::Iterator it(request_headers);
           it.GetNext();) {
        info->request_headers.push_back(std::make_pair(it.name(),
                                                       it.value()));
      }
      break;
    }
    case net::NetLog::TYPE_HTTP_TRANSACTION_READ_RESPONSE_HEADERS: {
      const net::HttpResponseHeaders& response_headers =
          static_cast<net::NetLogHttpResponseParameter*>(params)->GetHeaders();
      std::string name, value;
      for (void* it = NULL;
           response_headers.EnumerateHeaderLines(&it, &name, &value); ) {
        info->response_headers.push_back(std::make_pair(name, value));
      }
      break;
    }
    default:
      break;
  }
}

void DevToolsNetLogObserver::Attach(IOThread* io_thread) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  DCHECK(!instance_);

  instance_ = new DevToolsNetLogObserver(io_thread->globals()->net_log.get());
}

void DevToolsNetLogObserver::Detach() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  DCHECK(instance_);

  delete instance_;
  instance_ = NULL;
}

DevToolsNetLogObserver* DevToolsNetLogObserver::GetInstance() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));

  return instance_;
}

// static
void DevToolsNetLogObserver::PopulateResponseInfo(URLRequest* request,
                                                  ResourceResponse* response) {
  if (!(request->load_flags() & net::LOAD_REPORT_RAW_HEADERS))
    return;

  uint32 source_id = request->net_log().source().id;
  DevToolsNetLogObserver* dev_tools_net_log_observer =
      DevToolsNetLogObserver::GetInstance();
  if (!dev_tools_net_log_observer)
    return;
  response->response_head.devtools_info =
      dev_tools_net_log_observer->GetResourceInfo(source_id);
}
<commit_msg>Avoid collecting headers from several reqeusts in case of redirect.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/debugger/devtools_netlog_observer.h"

#include "base/string_util.h"
#include "chrome/browser/io_thread.h"
#include "chrome/common/resource_response.h"
#include "net/base/load_flags.h"
#include "net/http/http_net_log_params.h"
#include "net/http/http_response_headers.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_netlog_params.h"
#include "webkit/glue/resource_loader_bridge.h"

const size_t kMaxNumEntries = 1000;

DevToolsNetLogObserver* DevToolsNetLogObserver::instance_ = NULL;

DevToolsNetLogObserver::DevToolsNetLogObserver(ChromeNetLog* chrome_net_log)
    : ChromeNetLog::Observer(net::NetLog::LOG_ALL_BUT_BYTES),
      chrome_net_log_(chrome_net_log) {
  chrome_net_log_->AddObserver(this);
}

DevToolsNetLogObserver::~DevToolsNetLogObserver() {
  chrome_net_log_->RemoveObserver(this);
}

DevToolsNetLogObserver::ResourceInfo*
DevToolsNetLogObserver::GetResourceInfo(uint32 id) {
  RequestToInfoMap::iterator it = request_to_info_.find(id);
  if (it != request_to_info_.end())
    return it->second;
  return NULL;
}

void DevToolsNetLogObserver::OnAddEntry(net::NetLog::EventType type,
                                        const base::TimeTicks& time,
                                        const net::NetLog::Source& source,
                                        net::NetLog::EventPhase phase,
                                        net::NetLog::EventParameters* params) {
  if (type == net::NetLog::TYPE_URL_REQUEST_START_JOB) {
    if (phase != net::NetLog::PHASE_BEGIN)
      return;
    int load_flags = static_cast<URLRequestStartEventParameters*>(params)->
        load_flags();
    if (!(load_flags & net::LOAD_REPORT_RAW_HEADERS))
      return;
    if (request_to_info_.size() > kMaxNumEntries) {
      LOG(WARNING) << "The raw headers observer url request count has grown "
                      "larger than expected, resetting";
      request_to_info_.clear();
    }
    scoped_refptr<ResourceInfo> new_record(new ResourceInfo());
    // We may encounter multiple PHASE_BEGIN for same resource in case of
    // redirect -- if so, replace the old record to avoid keeping headers
    // from different requests.
    std::pair<RequestToInfoMap::iterator, bool> inserted =
        request_to_info_.insert(std::make_pair(source.id, new_record));
    if (!inserted.second)
      inserted.first->second = new_record;
    return;
  }
  if (type == net::NetLog::TYPE_REQUEST_ALIVE &&
      phase == net::NetLog::PHASE_END) {
    request_to_info_.erase(source.id);
    return;
  }
  if (type != net::NetLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST_HEADERS &&
      type != net::NetLog::TYPE_HTTP_TRANSACTION_READ_RESPONSE_HEADERS)
    return;

  ResourceInfo* info = GetResourceInfo(source.id);
  if (!info)
    return;

  switch (type) {
    case net::NetLog::TYPE_HTTP_TRANSACTION_SEND_REQUEST_HEADERS: {
      const net::HttpRequestHeaders &request_headers =
          static_cast<net::NetLogHttpRequestParameter*>(params)->GetHeaders();
      for (net::HttpRequestHeaders::Iterator it(request_headers);
           it.GetNext();) {
        info->request_headers.push_back(std::make_pair(it.name(),
                                                       it.value()));
      }
      break;
    }
    case net::NetLog::TYPE_HTTP_TRANSACTION_READ_RESPONSE_HEADERS: {
      const net::HttpResponseHeaders& response_headers =
          static_cast<net::NetLogHttpResponseParameter*>(params)->GetHeaders();
      std::string name, value;
      for (void* it = NULL;
           response_headers.EnumerateHeaderLines(&it, &name, &value); ) {
        info->response_headers.push_back(std::make_pair(name, value));
      }
      break;
    }
    default:
      break;
  }
}

void DevToolsNetLogObserver::Attach(IOThread* io_thread) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  DCHECK(!instance_);

  instance_ = new DevToolsNetLogObserver(io_thread->globals()->net_log.get());
}

void DevToolsNetLogObserver::Detach() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  DCHECK(instance_);

  delete instance_;
  instance_ = NULL;
}

DevToolsNetLogObserver* DevToolsNetLogObserver::GetInstance() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));

  return instance_;
}

// static
void DevToolsNetLogObserver::PopulateResponseInfo(URLRequest* request,
                                                  ResourceResponse* response) {
  if (!(request->load_flags() & net::LOAD_REPORT_RAW_HEADERS))
    return;

  uint32 source_id = request->net_log().source().id;
  DevToolsNetLogObserver* dev_tools_net_log_observer =
      DevToolsNetLogObserver::GetInstance();
  if (!dev_tools_net_log_observer)
    return;
  response->response_head.devtools_info =
      dev_tools_net_log_observer->GetResourceInfo(source_id);
}
<|endoftext|>


<commit_before>// This is free and unencumbered software released into the public domain.
// For more information, please refer to <http://unlicense.org/>

#include "sagtension/catenary_cable_unloader.h"

CatenaryCableUnloader::CatenaryCableUnloader() {
  is_updated_strainer_ = false;

  strainer_.set_load_finish(0);
}

CatenaryCableUnloader::~CatenaryCableUnloader() {
}

double CatenaryCableUnloader::LengthUnloaded() const {

  // updates class if necessary
  if (IsUpdated() == false) {
    if (Update() == false) {
      return -999999;
    }
  }

  return strainer_.LengthFinish();
}

bool CatenaryCableUnloader::Validate(
    const bool& is_included_warnings,
    std::list<std::string>* messages_error) const {

  bool is_valid = true;

  /// \todo implement this

  return is_valid;
}

CatenaryCable CatenaryCableUnloader::catenary_cable() const {
  return catenary_cable_;
}

void CatenaryCableUnloader::set_catenary_cable(
    const CatenaryCable& catenary_cable) {

  catenary_cable_ = catenary_cable;

  is_updated_strainer_ = false;
}

void CatenaryCableUnloader::set_state_unloaded(
    const CableState& state_unloaded) {

  strainer_.set_state_finish(state_unloaded);
}

CableState CatenaryCableUnloader::state_unloaded() const {
  return strainer_.state_finish();
}

bool CatenaryCableUnloader::IsUpdated() const {

  if (is_updated_strainer_ == true) {
    return true;
  } else {
    return false;
  }
}

bool CatenaryCableUnloader::Update() const {

  // updates strainer
  if (is_updated_strainer_ == false) {

    is_updated_strainer_ = UpdateStrainer();
    if (is_updated_strainer_ == false) {
      return false;
    }
  }

  // if it reaches this point, update was successful
  return true;
}

bool CatenaryCableUnloader::UpdateStrainer() const {

  strainer_.set_cable(catenary_cable_.cable());
  strainer_.set_load_start(catenary_cable_.Length());
  strainer_.set_load_start(catenary_cable_.TensionAverage());
  strainer_.set_state_start(catenary_cable_.state());

  return true;
}
<commit_msg>Fixed UpdateStrainer function.<commit_after>// This is free and unencumbered software released into the public domain.
// For more information, please refer to <http://unlicense.org/>

#include "sagtension/catenary_cable_unloader.h"

CatenaryCableUnloader::CatenaryCableUnloader() {
  is_updated_strainer_ = false;

  strainer_.set_load_finish(0);
}

CatenaryCableUnloader::~CatenaryCableUnloader() {
}

double CatenaryCableUnloader::LengthUnloaded() const {

  // updates class if necessary
  if (IsUpdated() == false) {
    if (Update() == false) {
      return -999999;
    }
  }

  return strainer_.LengthFinish();
}

bool CatenaryCableUnloader::Validate(
    const bool& is_included_warnings,
    std::list<std::string>* messages_error) const {

  bool is_valid = true;

  /// \todo implement this

  return is_valid;
}

CatenaryCable CatenaryCableUnloader::catenary_cable() const {
  return catenary_cable_;
}

void CatenaryCableUnloader::set_catenary_cable(
    const CatenaryCable& catenary_cable) {

  catenary_cable_ = catenary_cable;

  is_updated_strainer_ = false;
}

void CatenaryCableUnloader::set_state_unloaded(
    const CableState& state_unloaded) {

  strainer_.set_state_finish(state_unloaded);
}

CableState CatenaryCableUnloader::state_unloaded() const {
  return strainer_.state_finish();
}

bool CatenaryCableUnloader::IsUpdated() const {

  if (is_updated_strainer_ == true) {
    return true;
  } else {
    return false;
  }
}

bool CatenaryCableUnloader::Update() const {

  // updates strainer
  if (is_updated_strainer_ == false) {

    is_updated_strainer_ = UpdateStrainer();
    if (is_updated_strainer_ == false) {
      return false;
    }
  }

  // if it reaches this point, update was successful
  return true;
}

bool CatenaryCableUnloader::UpdateStrainer() const {

  strainer_.set_cable(catenary_cable_.cable());
  strainer_.set_length_start(catenary_cable_.Length());
  strainer_.set_load_start(catenary_cable_.TensionAverage());
  strainer_.set_state_start(catenary_cable_.state());

  return true;
}
<|endoftext|>