<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Justin Madsen
// =============================================================================
//
// model a single track chain system, as part of a tracked vehicle. Uses JSON input files
//
// =============================================================================

#include <cstdio>

#include "subsys/trackSystem/TrackSystem.h"

namespace chrono {

// -----------------------------------------------------------------------------
// Static variables

// idler, right side
const ChVector<> TrackSystem::m_idlerPos(-2.1904, -0.1443, 0); // relative to local csys
const ChQuaternion<> TrackSystem::m_idlerRot(QUNIT);

// drive gear, right side
const ChVector<> TrackSystem::m_gearPos(1.7741, -0.0099, 0);  // relative to local csys
const ChQuaternion<> TrackSystem::m_gearRot(QUNIT);

// Support rollers
const int TrackSystem::m_numRollers = 0;
const double TrackSystem::m_roller_mass = 100.0;
const ChVector<> TrackSystem::m_roller_inertia(19.82, 19.82, 26.06);  // rotates about z-axis initially
const double TrackSystem::m_roller_radius = 0.2;
const double TrackSystem::m_roller_width = 0.2;

// suspension
const int TrackSystem::m_numSuspensions = 5;

TrackSystem::TrackSystem(const std::string& name, int track_idx)
  : m_track_idx(track_idx), m_name(name)
{
  // FILE* fp = fopen(filename.c_str(), "r");
  // char readBuffer[65536];
  // fclose(fp);

  Create(track_idx);

}

// Create: 1) load/set the subsystem data, resize vectors 2) BuildSubsystems()
// TODO: replace hard-coded junk with JSON input files for each subsystem
void TrackSystem::Create(int track_idx)
{

  /*

  // read idler info
  assert(d.HasMember("Idler"));
  m_idlerMass = d["Idler"]["Mass"].GetDouble();
  m_idlerPos = loadVector(d["Idler"]["Location"]);
  m_idlerInertia = loadVector(d["Idler"]["Inertia"]);
  m_idlerRadius = d["Spindle"]["Radius"].GetDouble();
  m_idlerWidth = d["Spindle"]["Width"].GetDouble();
  m_idler_K = d["Idler"]["SpringK"].GetDouble();
  m_idler_C = d["Idler"]["SpringC"].GetDouble();

  // Read Drive Gear data
  assert(d.HasMember("Drive Gear"));
  assert(d["Drive Gear"].IsObject());

  m_gearMass = d["Drive Gear"]["Mass"].GetDouble();
  m_gearPos = loadVector(d["Drive Gear"]["Location"]);
  m_gearInertia = loadVector(d["Drive Gear"]["Inertia"]);
  m_gearRadius = d["Drive Gear"]["Radius"].GetDouble();
  m_gearWidth = d["Drive Gear"]["Width"].GetDouble();

  // Read Support Roller info
  assert(d.HasMember("Support Roller"));
  assert(d["Support Roller"].IsObject());

  m_rollerMass = d["Support Roller"]["Mass"].GetDouble();
  m_rollerInertia = loadVector(d["Support Roller"]["Inertia"]);
  m_rollerRadius = d["Support Roller"]["Radius"].GetDouble();
  m_rollerWidth = d["Support Roller"]["Width"].GetDouble();

  assert(d["Support Roller"]["Location"].IsArray());
  m_NumRollers = d["Support Roller"]["Location"].Size();

  */

  // no support rollers, for this model
  m_supportRollers.resize(m_numRollers);
  m_supportRollers_rev.resize(m_numRollers);

  /*

  m_rollerLocs.resize(m_NumRollers);
  for(int i = 0; i < m_NumRollers; i++ )
  {
	m_rollerLocs[i] = loadVector(d["Support Roller"]["Location"][i]);
  }

  // Read Suspension data
  assert(d.HasMember("Suspension"));
  assert(d["Suspension"].IsObject());
  assert(d["Suspension"]["Location"].IsArray() );

  m_suspensionFilename = d["Suspension"]["Input File"].GetString();
  m_NumSuspensions = d["Suspension"]["Location"].Size();

  m_suspensions.resize(m_numSuspensions);
  m_suspensionLocs.resize(m_numSuspensions);
  for(int j = 0; j < m_numSuspensions; j++)
  {
    // m_suspensionLocs[j] = loadVector(d["Suspension"]["Locaiton"][j]);
  }
  */

  m_suspensions.resize(m_numSuspensions);
  m_suspensionLocs.resize(m_numSuspensions);
  // hard-code positions relative to trackSystem csys. Start w/ one nearest sprocket
  m_suspensionLocs[0] = ChVector<>(1.3336, 0, 0);
  m_suspensionLocs[1] = ChVector<>(0.6668, 0, 0);
  // trackSystem c-sys aligned with middle suspension subsystem arm/chassis revolute constraint position
  m_suspensionLocs[2] = ChVector<>(0,0,0);
  m_suspensionLocs[3] = ChVector<>(-0.6682, 0, 0);
  m_suspensionLocs[4] = ChVector<>(-1.3368, 0, 0);

  /*

  // Read Track Chain data
  assert(d.HasMember("Track Chain"));
  assert(d["Track Chain"].IsObject());
  m_trackChainFilename = d["Track Chain"]["Input File"].GetString()

  */

  // create the various subsystems, from the hardcoded static variables in each subsystem class
  BuildSubsystems();

}

void TrackSystem::BuildSubsystems()
{
  // build one of each of the following subsystems. VisualizationType and CollisionType defaults are PRIMITIVES
  m_driveGear = ChSharedPtr<DriveGear>(new DriveGear("drive gear "+std::to_string(m_track_idx)) );
  m_idler = ChSharedPtr<IdlerSimple>(new IdlerSimple("idler "+std::to_string(m_track_idx)) );
  m_chain = ChSharedPtr<TrackChain>(new TrackChain("chain "+std::to_string(m_track_idx)) );

  // build suspension/road wheel subsystems
  for(int i = 0; i < m_numSuspensions; i++)
  {
    m_suspensions[i] = ChSharedPtr<TorsionArmSuspension>(new TorsionArmSuspension("suspension "+std::to_string(i) +", chain "+std::to_string(m_track_idx)) );
  }

  // build support rollers manually (if any)
  for(int j = 0; j < m_numRollers; j++)
  {
    m_supportRollers[j] = ChSharedPtr<ChBody>(new ChBody);
    m_supportRollers[j]->SetNameString("support roller"+std::to_string(j)+", chain "+std::to_string(m_track_idx) );
    m_supportRollers[j]->SetMass(m_roller_mass);
    m_supportRollers[j]->SetInertiaXX(m_roller_inertia);
  }

}

void TrackSystem::Initialize(ChSharedPtr<ChBodyAuxRef> chassis,
			 const ChVector<>&  local_pos)
{
  m_Pos_local = local_pos;  // same rotation as chassis
  // Need a list of the center location of the rolling elements and their clearance for TrackChain.
  // Clearance is a sphere shaped envelope at each center location, where it can
  //  be guaranteed that the track chain geometry will not penetrate the sphere.
  std::vector<ChVector<>> rolling_elem_locs; // w.r.t. chassis ref. frame
  std::vector<double> clearance;  // 1 per rolling elem

  // initialize 1 of each of the following subsystems.
  // will use the chassis ref frame to do the transforms, since the TrackSystem
  // local ref. frame has same rot (just difference in position)
  m_driveGear->Initialize(chassis, ChCoordsys<>(m_gearPos + local_pos, QUNIT) );
  // drive sprocket is First added to the lists passed into TrackChain Init()
  rolling_elem_locs.push_back(m_gearPos + local_pos );
  clearance.push_back(m_driveGear->GetRadius() );

  // initialize the road wheels & torsion arm suspension subsystems
  for(int i = 0; i < m_suspensionLocs.size(); i++)
  {
    m_suspensions[i]->Initialize(chassis, ChCoordsys<>(m_suspensionLocs[i] + local_pos, QUNIT) );
    // add to the lists passed into the track chain
    rolling_elem_locs.push_back(m_suspensionLocs[i] + local_pos );
    clearance.push_back(m_suspensions[i]->GetWheelRadius() );
  }

  // initialize the support rollers.
  // NOTE: None for the M113
  for(int j = 0; j < m_rollerLocs.size(); j++)
  {
    initialize_roller(m_supportRollers[j], chassis, m_rollerLocs[j], QUNIT, j);
    // add to the points passed into the track chain
    rolling_elem_locs.push_back(m_rollerLocs[j] + local_pos );
    clearance.push_back(m_roller_radius);
  }

  // last control point: the idler body
  m_idler->Initialize(chassis, ChCoordsys<>(m_idlerPos + local_pos, QUNIT) );
  rolling_elem_locs.push_back(m_idlerPos + local_pos );
  clearance.push_back(m_idler->GetRadius() );

  // After all rolling elements have been initialized, now able to setup the TrackChain.
  // Assumed that start_pos is between idler and gear control points, e.g., on the top
  //   of the track chain.
  ChVector<> start_pos = (rolling_elem_locs[0] + rolling_elem_locs.back())/2.0;
  start_pos.y += (clearance[0] + clearance.back() )/2.0;

  // Assumption: start_pos should lie close to where the actual track chain would
  //             pass between the idler and driveGears.
  // MUST be on the top part of the chain so the chain wrap rotation direction can be assumed.
  // rolling_elem_locs, start_pos w.r.t. chassis c-sys
  m_chain->Initialize(chassis, rolling_elem_locs, clearance, start_pos );
}

// initialize a roller at the specified location and orientation, w.r.t. TrackSystem c-sys
void TrackSystem::initialize_roller(ChSharedPtr<ChBody> body, ChSharedPtr<ChBodyAuxRef>  chassis,
                                    const ChVector<>& loc, const ChQuaternion<>& rot, int idx)
{
  // express loc and rot in the global c-sys
  ChFrame<> frame_to_abs(loc, rot);

  body->SetPos(loc);
  body->SetRot(rot);

  // transform point to absolute frame and initialize

  // add the revolute joint at the location and w/ orientation specified

  // Add a visual asset
}

} // end namespace chrono
<commit_msg>specify armWheel distance. fixed control point error, not including above distance.<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Justin Madsen
// =============================================================================
//
// model a single track chain system, as part of a tracked vehicle. Uses JSON input files
//
// =============================================================================

#include <cstdio>

#include "subsys/trackSystem/TrackSystem.h"

namespace chrono {

// -----------------------------------------------------------------------------
// Static variables

// idler, right side
const ChVector<> TrackSystem::m_idlerPos(-2.1904, -0.1443, 0.2447); // relative to local csys
const ChQuaternion<> TrackSystem::m_idlerRot(QUNIT);

// drive gear, right side
const ChVector<> TrackSystem::m_gearPos(1.7741, -0.0099, 0.2447);  // relative to local csys
const ChQuaternion<> TrackSystem::m_gearRot(QUNIT);

// Support rollers
const int TrackSystem::m_numRollers = 0;
const double TrackSystem::m_roller_mass = 100.0;
const ChVector<> TrackSystem::m_roller_inertia(19.82, 19.82, 26.06);  // rotates about z-axis initially
const double TrackSystem::m_roller_radius = 0.2;
const double TrackSystem::m_roller_width = 0.2;

// suspension
const int TrackSystem::m_numSuspensions = 5;
const ChVector<> TrackSystem::m_armWheel(-0.203, -0.2271, 0.2447);  // relative arm distance to right wheel

TrackSystem::TrackSystem(const std::string& name, int track_idx)
  : m_track_idx(track_idx), m_name(name)
{
  // FILE* fp = fopen(filename.c_str(), "r");
  // char readBuffer[65536];
  // fclose(fp);

  Create(track_idx);

}

// Create: 1) load/set the subsystem data, resize vectors 2) BuildSubsystems()
// TODO: replace hard-coded junk with JSON input files for each subsystem
void TrackSystem::Create(int track_idx)
{

  /*

  // read idler info
  assert(d.HasMember("Idler"));
  m_idlerMass = d["Idler"]["Mass"].GetDouble();
  m_idlerPos = loadVector(d["Idler"]["Location"]);
  m_idlerInertia = loadVector(d["Idler"]["Inertia"]);
  m_idlerRadius = d["Spindle"]["Radius"].GetDouble();
  m_idlerWidth = d["Spindle"]["Width"].GetDouble();
  m_idler_K = d["Idler"]["SpringK"].GetDouble();
  m_idler_C = d["Idler"]["SpringC"].GetDouble();

  // Read Drive Gear data
  assert(d.HasMember("Drive Gear"));
  assert(d["Drive Gear"].IsObject());

  m_gearMass = d["Drive Gear"]["Mass"].GetDouble();
  m_gearPos = loadVector(d["Drive Gear"]["Location"]);
  m_gearInertia = loadVector(d["Drive Gear"]["Inertia"]);
  m_gearRadius = d["Drive Gear"]["Radius"].GetDouble();
  m_gearWidth = d["Drive Gear"]["Width"].GetDouble();

  // Read Support Roller info
  assert(d.HasMember("Support Roller"));
  assert(d["Support Roller"].IsObject());

  m_rollerMass = d["Support Roller"]["Mass"].GetDouble();
  m_rollerInertia = loadVector(d["Support Roller"]["Inertia"]);
  m_rollerRadius = d["Support Roller"]["Radius"].GetDouble();
  m_rollerWidth = d["Support Roller"]["Width"].GetDouble();

  assert(d["Support Roller"]["Location"].IsArray());
  m_NumRollers = d["Support Roller"]["Location"].Size();

  */

  // no support rollers, for this model
  m_supportRollers.resize(m_numRollers);
  m_supportRollers_rev.resize(m_numRollers);

  /*

  m_rollerLocs.resize(m_NumRollers);
  for(int i = 0; i < m_NumRollers; i++ )
  {
	m_rollerLocs[i] = loadVector(d["Support Roller"]["Location"][i]);
  }

  // Read Suspension data
  assert(d.HasMember("Suspension"));
  assert(d["Suspension"].IsObject());
  assert(d["Suspension"]["Location"].IsArray() );

  m_suspensionFilename = d["Suspension"]["Input File"].GetString();
  m_NumSuspensions = d["Suspension"]["Location"].Size();

  m_suspensions.resize(m_numSuspensions);
  m_suspensionLocs.resize(m_numSuspensions);
  for(int j = 0; j < m_numSuspensions; j++)
  {
    // m_suspensionLocs[j] = loadVector(d["Suspension"]["Locaiton"][j]);
  }
  */

  m_suspensions.resize(m_numSuspensions);
  m_suspensionLocs.resize(m_numSuspensions);
  // hard-code positions relative to trackSystem csys. Start w/ one nearest sprocket
  m_suspensionLocs[0] = ChVector<>(1.3336, 0, 0);
  m_suspensionLocs[1] = ChVector<>(0.6668, 0, 0);
  // trackSystem c-sys aligned with middle suspension subsystem arm/chassis revolute constraint position
  m_suspensionLocs[2] = ChVector<>(0,0,0);
  m_suspensionLocs[3] = ChVector<>(-0.6682, 0, 0);
  m_suspensionLocs[4] = ChVector<>(-1.3368, 0, 0);

  /*

  // Read Track Chain data
  assert(d.HasMember("Track Chain"));
  assert(d["Track Chain"].IsObject());
  m_trackChainFilename = d["Track Chain"]["Input File"].GetString()

  */

  // create the various subsystems, from the hardcoded static variables in each subsystem class
  BuildSubsystems();

}

void TrackSystem::BuildSubsystems()
{
  // build one of each of the following subsystems. VisualizationType and CollisionType defaults are PRIMITIVES
  m_driveGear = ChSharedPtr<DriveGear>(new DriveGear("drive gear "+std::to_string(m_track_idx)) );
  m_idler = ChSharedPtr<IdlerSimple>(new IdlerSimple("idler "+std::to_string(m_track_idx)) );
  m_chain = ChSharedPtr<TrackChain>(new TrackChain("chain "+std::to_string(m_track_idx)) );

  // build suspension/road wheel subsystems
  for(int i = 0; i < m_numSuspensions; i++)
  {
    m_suspensions[i] = ChSharedPtr<TorsionArmSuspension>(new TorsionArmSuspension("suspension "+std::to_string(i) +", chain "+std::to_string(m_track_idx)) );
  }

  // build support rollers manually (if any)
  for(int j = 0; j < m_numRollers; j++)
  {
    m_supportRollers[j] = ChSharedPtr<ChBody>(new ChBody);
    m_supportRollers[j]->SetNameString("support roller"+std::to_string(j)+", chain "+std::to_string(m_track_idx) );
    m_supportRollers[j]->SetMass(m_roller_mass);
    m_supportRollers[j]->SetInertiaXX(m_roller_inertia);
  }

}

void TrackSystem::Initialize(ChSharedPtr<ChBodyAuxRef> chassis,
			 const ChVector<>&  local_pos)
{
  m_Pos_local = local_pos;  // same rotation as chassis
  // Need a list of the center location of the rolling elements and their clearance for TrackChain.
  // Clearance is a sphere shaped envelope at each center location, where it can
  //  be guaranteed that the track chain geometry will not penetrate the sphere.
  std::vector<ChVector<>> rolling_elem_locs; // w.r.t. chassis ref. frame
  std::vector<double> clearance;  // 1 per rolling elem

  // initialize 1 of each of the following subsystems.
  // will use the chassis ref frame to do the transforms, since the TrackSystem
  // local ref. frame has same rot (just difference in position)
  m_driveGear->Initialize(chassis, ChCoordsys<>(m_gearPos + local_pos, QUNIT) );
  // drive sprocket is First added to the lists passed into TrackChain Init()
  rolling_elem_locs.push_back(m_gearPos + local_pos );
  clearance.push_back(m_driveGear->GetRadius() );

  // initialize the road wheels & torsion arm suspension subsystems
  for(int i = 0; i < m_suspensionLocs.size(); i++)
  {
    m_suspensions[i]->Initialize(chassis, ChCoordsys<>(m_suspensionLocs[i] + local_pos, QUNIT) );
    // add to the lists passed into the track chain
    ChVector<> armWheel = m_armWheel;
    // if it's the left side, switch the lateral direction
    if( local_pos.z < 0 )
      armWheel.z = armWheel.z * -1.0;
    rolling_elem_locs.push_back(m_suspensionLocs[i] + local_pos + armWheel);
    clearance.push_back(m_suspensions[i]->GetWheelRadius() );
  }

  // initialize the support rollers.
  // NOTE: None for the M113
  for(int j = 0; j < m_rollerLocs.size(); j++)
  {
    initialize_roller(m_supportRollers[j], chassis, m_rollerLocs[j], QUNIT, j);
    // add to the points passed into the track chain
    rolling_elem_locs.push_back(m_rollerLocs[j] + local_pos );
    clearance.push_back(m_roller_radius);
  }

  // last control point: the idler body
  m_idler->Initialize(chassis, ChCoordsys<>(m_idlerPos + local_pos, QUNIT) );
  rolling_elem_locs.push_back(m_idlerPos + local_pos );
  clearance.push_back(m_idler->GetRadius() );

  // After all rolling elements have been initialized, now able to setup the TrackChain.
  // Assumed that start_pos is between idler and gear control points, e.g., on the top
  //   of the track chain.
  ChVector<> start_pos = (rolling_elem_locs[0] + rolling_elem_locs.back())/2.0;
  start_pos.y += (clearance[0] + clearance.back() )/2.0;

  // Assumption: start_pos should lie close to where the actual track chain would
  //             pass between the idler and driveGears.
  // MUST be on the top part of the chain so the chain wrap rotation direction can be assumed.
  // rolling_elem_locs, start_pos w.r.t. chassis c-sys
  m_chain->Initialize(chassis, rolling_elem_locs, clearance, start_pos );
}

// initialize a roller at the specified location and orientation, w.r.t. TrackSystem c-sys
void TrackSystem::initialize_roller(ChSharedPtr<ChBody> body, ChSharedPtr<ChBodyAuxRef>  chassis,
                                    const ChVector<>& loc, const ChQuaternion<>& rot, int idx)
{
  // express loc and rot in the global c-sys
  ChFrame<> frame_to_abs(loc, rot);

  body->SetPos(loc);
  body->SetRot(rot);

  // transform point to absolute frame and initialize

  // add the revolute joint at the location and w/ orientation specified

  // Add a visual asset
}

} // end namespace chrono
<|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/chromeos/options/language_chewing_config_view.h"

#include "app/combobox_model.h"
#include "app/l10n_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/language_library.h"
#include "chrome/browser/chromeos/options/language_config_util.h"
#include "chrome/browser/chromeos/preferences.h"
#include "chrome/browser/profile.h"
#include "chrome/common/notification_type.h"
#include "chrome/common/pref_names.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "views/controls/button/checkbox.h"
#include "views/controls/label.h"
#include "views/grid_layout.h"
#include "views/standard_layout.h"
#include "views/window/window.h"

namespace chromeos {

LanguageChewingConfigView::LanguageChewingConfigView(Profile* profile)
    : OptionsPageView(profile), contents_(NULL) {
  for (size_t i = 0; i < kNumChewingBooleanPrefs; ++i) {
    chewing_boolean_prefs_[i].Init(
        kChewingBooleanPrefs[i].pref_name, profile->GetPrefs(), this);
    chewing_boolean_checkboxes_[i] = NULL;
  }
  for (size_t i = 0; i < kNumChewingMultipleChoicePrefs; ++i) {
    ChewingPrefAndAssociatedCombobox& current = prefs_and_comboboxes_[i];
    current.multiple_choice_pref.Init(
        kChewingMultipleChoicePrefs[i].pref_name, profile->GetPrefs(), this);
    current.combobox_model =
        new LanguageComboboxModel<const char*>(&kChewingMultipleChoicePrefs[i]);
    current.combobox = NULL;
  }

  hsu_sel_key_type_.multiple_choice_pref.Init(
      kChewingHsuSelKeyType.pref_name, profile->GetPrefs(), this);
  hsu_sel_key_type_.combobox_model =
      new LanguageComboboxModel<int>(&kChewingHsuSelKeyType);
  hsu_sel_key_type_.combobox = NULL;

  for (size_t i = 0; i < kNumChewingIntegerPrefs; ++i) {
    chewing_integer_prefs_[i].Init(
        kChewingIntegerPrefs[i].pref_name, profile->GetPrefs(), this);
    chewing_integer_sliders_[i] = NULL;
  }
}

LanguageChewingConfigView::~LanguageChewingConfigView() {
}

void LanguageChewingConfigView::ButtonPressed(
    views::Button* sender, const views::Event& event) {
  views::Checkbox* checkbox = static_cast<views::Checkbox*>(sender);
  const int pref_id = checkbox->tag();
  DCHECK(pref_id >= 0 && pref_id < static_cast<int>(kNumChewingBooleanPrefs));
  chewing_boolean_prefs_[pref_id].SetValue(checkbox->checked());
}

void LanguageChewingConfigView::ItemChanged(
    views::Combobox* sender, int prev_index, int new_index) {
  for (size_t i = 0; i < kNumChewingMultipleChoicePrefs; ++i) {
    ChewingPrefAndAssociatedCombobox& current = prefs_and_comboboxes_[i];
    if (current.combobox == sender) {
      const std::wstring config_value =
          UTF8ToWide(current.combobox_model->GetConfigValueAt(new_index));
      LOG(INFO) << "Changing Chewing pref to " << config_value;
      // Update the Chrome pref.
      current.multiple_choice_pref.SetValue(config_value);
      break;
    }
  }
  if (hsu_sel_key_type_.combobox == sender) {
    const int config_value =
        hsu_sel_key_type_.combobox_model->GetConfigValueAt(new_index);
    LOG(INFO) << "Changing Chewing pref to " << config_value;
    // Update the Chrome pref.
    hsu_sel_key_type_.multiple_choice_pref.SetValue(config_value);
  }
}

void LanguageChewingConfigView::SliderValueChanged(views::Slider* sender) {
  size_t pref_id;
  for (pref_id = 0; pref_id < kNumChewingIntegerPrefs; ++pref_id) {
    if (chewing_integer_sliders_[pref_id] == sender)
      break;
  }
  DCHECK(pref_id < kNumChewingIntegerPrefs);
  chewing_integer_prefs_[pref_id].SetValue(sender->value());
}

void LanguageChewingConfigView::Layout() {
  // Not sure why but this is needed to show contents in the dialog.
  contents_->SetBounds(0, 0, width(), height());
}

std::wstring LanguageChewingConfigView::GetWindowTitle() const {
  return l10n_util::GetString(
      IDS_OPTIONS_SETTINGS_LANGUAGES_CHEWING_SETTINGS_TITLE);
}

gfx::Size LanguageChewingConfigView::GetPreferredSize() {
  return gfx::Size(views::Window::GetLocalizedContentsSize(
      IDS_LANGUAGES_INPUT_DIALOG_WIDTH_CHARS,
      IDS_LANGUAGES_INPUT_DIALOG_HEIGHT_LINES));
}

void LanguageChewingConfigView::InitControlLayout() {
  using views::ColumnSet;
  using views::GridLayout;

  contents_ = new views::View;
  AddChildView(contents_);

  GridLayout* layout = new GridLayout(contents_);
  layout->SetInsets(kPanelVertMargin, kPanelHorizMargin,
                    kPanelVertMargin, kPanelHorizMargin);
  contents_->SetLayoutManager(layout);

  const int kColumnSetId = 0;
  ColumnSet* column_set = layout->AddColumnSet(kColumnSetId);
  column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 0,
                        GridLayout::USE_PREF, 0, 0);
  column_set->AddPaddingColumn(0, kRelatedControlHorizontalSpacing);
  column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 0,
                        GridLayout::USE_PREF, 0, 0);

  for (size_t i = 0; i < kNumChewingBooleanPrefs; ++i) {
    chewing_boolean_checkboxes_[i] = new views::Checkbox(
        l10n_util::GetString(kChewingBooleanPrefs[i].message_id));
    chewing_boolean_checkboxes_[i]->set_listener(this);
    chewing_boolean_checkboxes_[i]->set_tag(i);
  }
  for (size_t i = 0; i < kNumChewingMultipleChoicePrefs; ++i) {
    ChewingPrefAndAssociatedCombobox& current = prefs_and_comboboxes_[i];
    current.combobox = new LanguageCombobox(current.combobox_model);
    current.combobox->set_listener(this);
  }
  hsu_sel_key_type_.combobox =
      new LanguageCombobox(hsu_sel_key_type_.combobox_model);
  hsu_sel_key_type_.combobox->set_listener(this);

  for (size_t i = 0; i < kNumChewingIntegerPrefs; ++i) {
    chewing_integer_sliders_[i] = new views::Slider(
        kChewingIntegerPrefs[i].min_pref_value,
        kChewingIntegerPrefs[i].max_pref_value,
        1,
        static_cast<views::Slider::StyleFlags>(
            views::Slider::STYLE_DRAW_VALUE |
            views::Slider::STYLE_UPDATE_ON_RELEASE),
        this);
  }
  for (size_t i = 0; i < kNumChewingBooleanPrefs; ++i) {
    layout->StartRow(0, kColumnSetId);
    layout->AddView(chewing_boolean_checkboxes_[i]);
  }

  for (size_t i = 0; i < kNumChewingIntegerPrefs; ++i) {
    layout->StartRow(0, kColumnSetId);
    layout->AddView(new views::Label(
        l10n_util::GetString(kChewingIntegerPrefs[i].message_id)));
    layout->AddView(chewing_integer_sliders_[i]);
  }
  NotifyPrefChanged();

  // Show the comboboxes.
  for (size_t i = 0; i < kNumChewingMultipleChoicePrefs; ++i) {
    const ChewingPrefAndAssociatedCombobox& current = prefs_and_comboboxes_[i];
    layout->StartRow(0, kColumnSetId);
    layout->AddView(new views::Label(current.combobox_model->GetLabel()));
    layout->AddView(current.combobox);
  }
  layout->StartRow(0, kColumnSetId);
  layout->AddView(
      new views::Label(hsu_sel_key_type_.combobox_model->GetLabel()));
  layout->AddView(hsu_sel_key_type_.combobox);
}

void LanguageChewingConfigView::Observe(NotificationType type,
                                        const NotificationSource& source,
                                        const NotificationDetails& details) {
  if (type == NotificationType::PREF_CHANGED) {
    NotifyPrefChanged();
  }
}

void LanguageChewingConfigView::NotifyPrefChanged() {
  for (size_t i = 0; i < kNumChewingBooleanPrefs; ++i) {
    const bool checked = chewing_boolean_prefs_[i].GetValue();
    chewing_boolean_checkboxes_[i]->SetChecked(checked);
  }
  for (size_t i = 0; i < kNumChewingIntegerPrefs; ++i) {
    const int value = chewing_integer_prefs_[i].GetValue();
    chewing_integer_sliders_[i]->SetValue(value);
  }
  for (size_t i = 0; i < kNumChewingMultipleChoicePrefs; ++i) {
    ChewingPrefAndAssociatedCombobox& current = prefs_and_comboboxes_[i];
    const std::wstring value = current.multiple_choice_pref.GetValue();
    for (int i = 0; i < current.combobox_model->num_items(); ++i) {
      if (UTF8ToWide(current.combobox_model->GetConfigValueAt(i)) == value) {
        current.combobox->SetSelectedItem(i);
        break;
      }
    }
  }
  const int value = hsu_sel_key_type_.multiple_choice_pref.GetValue();
  for (int i = 0; i < hsu_sel_key_type_.combobox_model->num_items(); ++i) {
    if (hsu_sel_key_type_.combobox_model->GetConfigValueAt(i) == value) {
      hsu_sel_key_type_.combobox->SetSelectedItem(i);
      break;
    }
  }
}

}  // namespace chromeos
<commit_msg>Fix chewing layout<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/chromeos/options/language_chewing_config_view.h"

#include "app/combobox_model.h"
#include "app/l10n_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/language_library.h"
#include "chrome/browser/chromeos/options/language_config_util.h"
#include "chrome/browser/chromeos/preferences.h"
#include "chrome/browser/profile.h"
#include "chrome/common/notification_type.h"
#include "chrome/common/pref_names.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "views/controls/button/checkbox.h"
#include "views/controls/label.h"
#include "views/grid_layout.h"
#include "views/standard_layout.h"
#include "views/window/window.h"

namespace chromeos {

LanguageChewingConfigView::LanguageChewingConfigView(Profile* profile)
    : OptionsPageView(profile), contents_(NULL) {
  for (size_t i = 0; i < kNumChewingBooleanPrefs; ++i) {
    chewing_boolean_prefs_[i].Init(
        kChewingBooleanPrefs[i].pref_name, profile->GetPrefs(), this);
    chewing_boolean_checkboxes_[i] = NULL;
  }
  for (size_t i = 0; i < kNumChewingMultipleChoicePrefs; ++i) {
    ChewingPrefAndAssociatedCombobox& current = prefs_and_comboboxes_[i];
    current.multiple_choice_pref.Init(
        kChewingMultipleChoicePrefs[i].pref_name, profile->GetPrefs(), this);
    current.combobox_model =
        new LanguageComboboxModel<const char*>(&kChewingMultipleChoicePrefs[i]);
    current.combobox = NULL;
  }

  hsu_sel_key_type_.multiple_choice_pref.Init(
      kChewingHsuSelKeyType.pref_name, profile->GetPrefs(), this);
  hsu_sel_key_type_.combobox_model =
      new LanguageComboboxModel<int>(&kChewingHsuSelKeyType);
  hsu_sel_key_type_.combobox = NULL;

  for (size_t i = 0; i < kNumChewingIntegerPrefs; ++i) {
    chewing_integer_prefs_[i].Init(
        kChewingIntegerPrefs[i].pref_name, profile->GetPrefs(), this);
    chewing_integer_sliders_[i] = NULL;
  }
}

LanguageChewingConfigView::~LanguageChewingConfigView() {
}

void LanguageChewingConfigView::ButtonPressed(
    views::Button* sender, const views::Event& event) {
  views::Checkbox* checkbox = static_cast<views::Checkbox*>(sender);
  const int pref_id = checkbox->tag();
  DCHECK(pref_id >= 0 && pref_id < static_cast<int>(kNumChewingBooleanPrefs));
  chewing_boolean_prefs_[pref_id].SetValue(checkbox->checked());
}

void LanguageChewingConfigView::ItemChanged(
    views::Combobox* sender, int prev_index, int new_index) {
  for (size_t i = 0; i < kNumChewingMultipleChoicePrefs; ++i) {
    ChewingPrefAndAssociatedCombobox& current = prefs_and_comboboxes_[i];
    if (current.combobox == sender) {
      const std::wstring config_value =
          UTF8ToWide(current.combobox_model->GetConfigValueAt(new_index));
      LOG(INFO) << "Changing Chewing pref to " << config_value;
      // Update the Chrome pref.
      current.multiple_choice_pref.SetValue(config_value);
      break;
    }
  }
  if (hsu_sel_key_type_.combobox == sender) {
    const int config_value =
        hsu_sel_key_type_.combobox_model->GetConfigValueAt(new_index);
    LOG(INFO) << "Changing Chewing pref to " << config_value;
    // Update the Chrome pref.
    hsu_sel_key_type_.multiple_choice_pref.SetValue(config_value);
  }
}

void LanguageChewingConfigView::SliderValueChanged(views::Slider* sender) {
  size_t pref_id;
  for (pref_id = 0; pref_id < kNumChewingIntegerPrefs; ++pref_id) {
    if (chewing_integer_sliders_[pref_id] == sender)
      break;
  }
  DCHECK(pref_id < kNumChewingIntegerPrefs);
  chewing_integer_prefs_[pref_id].SetValue(sender->value());
}

void LanguageChewingConfigView::Layout() {
  // Not sure why but this is needed to show contents in the dialog.
  contents_->SetBounds(0, 0, width(), height());
}

std::wstring LanguageChewingConfigView::GetWindowTitle() const {
  return l10n_util::GetString(
      IDS_OPTIONS_SETTINGS_LANGUAGES_CHEWING_SETTINGS_TITLE);
}

gfx::Size LanguageChewingConfigView::GetPreferredSize() {
  return gfx::Size(views::Window::GetLocalizedContentsSize(
      IDS_LANGUAGES_INPUT_DIALOG_WIDTH_CHARS,
      IDS_LANGUAGES_INPUT_DIALOG_HEIGHT_LINES));
}

void LanguageChewingConfigView::InitControlLayout() {
  using views::ColumnSet;
  using views::GridLayout;

  contents_ = new views::View;
  AddChildView(contents_);

  GridLayout* layout = new GridLayout(contents_);
  layout->SetInsets(kPanelVertMargin, kPanelHorizMargin,
                    kPanelVertMargin, kPanelHorizMargin);
  contents_->SetLayoutManager(layout);

  const int kColumnSetId = 0;
  ColumnSet* column_set = layout->AddColumnSet(kColumnSetId);
  column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 0,
                        GridLayout::USE_PREF, 0, 0);
  column_set->AddPaddingColumn(0, kRelatedControlHorizontalSpacing);
  column_set->AddColumn(GridLayout::FILL, GridLayout::LEADING, 1,
                        GridLayout::USE_PREF, 0, 0);

  for (size_t i = 0; i < kNumChewingBooleanPrefs; ++i) {
    chewing_boolean_checkboxes_[i] = new views::Checkbox(
        l10n_util::GetString(kChewingBooleanPrefs[i].message_id));
    chewing_boolean_checkboxes_[i]->set_listener(this);
    chewing_boolean_checkboxes_[i]->set_tag(i);
  }
  for (size_t i = 0; i < kNumChewingMultipleChoicePrefs; ++i) {
    ChewingPrefAndAssociatedCombobox& current = prefs_and_comboboxes_[i];
    current.combobox = new LanguageCombobox(current.combobox_model);
    current.combobox->set_listener(this);
  }
  hsu_sel_key_type_.combobox =
      new LanguageCombobox(hsu_sel_key_type_.combobox_model);
  hsu_sel_key_type_.combobox->set_listener(this);

  for (size_t i = 0; i < kNumChewingIntegerPrefs; ++i) {
    chewing_integer_sliders_[i] = new views::Slider(
        kChewingIntegerPrefs[i].min_pref_value,
        kChewingIntegerPrefs[i].max_pref_value,
        1,
        static_cast<views::Slider::StyleFlags>(
            views::Slider::STYLE_DRAW_VALUE |
            views::Slider::STYLE_UPDATE_ON_RELEASE),
        this);
  }
  for (size_t i = 0; i < kNumChewingBooleanPrefs; ++i) {
    layout->StartRow(0, kColumnSetId);
    layout->AddView(chewing_boolean_checkboxes_[i]);
  }

  for (size_t i = 0; i < kNumChewingIntegerPrefs; ++i) {
    layout->StartRow(0, kColumnSetId);
    layout->AddView(new views::Label(
        l10n_util::GetString(kChewingIntegerPrefs[i].message_id)));
    layout->AddView(chewing_integer_sliders_[i]);
  }
  NotifyPrefChanged();

  // Show the comboboxes.
  for (size_t i = 0; i < kNumChewingMultipleChoicePrefs; ++i) {
    const ChewingPrefAndAssociatedCombobox& current = prefs_and_comboboxes_[i];
    layout->StartRow(0, kColumnSetId);
    layout->AddView(new views::Label(current.combobox_model->GetLabel()));
    layout->AddView(current.combobox);
  }
  layout->StartRow(0, kColumnSetId);
  layout->AddView(
      new views::Label(hsu_sel_key_type_.combobox_model->GetLabel()));
  layout->AddView(hsu_sel_key_type_.combobox);
}

void LanguageChewingConfigView::Observe(NotificationType type,
                                        const NotificationSource& source,
                                        const NotificationDetails& details) {
  if (type == NotificationType::PREF_CHANGED) {
    NotifyPrefChanged();
  }
}

void LanguageChewingConfigView::NotifyPrefChanged() {
  for (size_t i = 0; i < kNumChewingBooleanPrefs; ++i) {
    const bool checked = chewing_boolean_prefs_[i].GetValue();
    chewing_boolean_checkboxes_[i]->SetChecked(checked);
  }
  for (size_t i = 0; i < kNumChewingIntegerPrefs; ++i) {
    const int value = chewing_integer_prefs_[i].GetValue();
    chewing_integer_sliders_[i]->SetValue(value);
  }
  for (size_t i = 0; i < kNumChewingMultipleChoicePrefs; ++i) {
    ChewingPrefAndAssociatedCombobox& current = prefs_and_comboboxes_[i];
    const std::wstring value = current.multiple_choice_pref.GetValue();
    for (int i = 0; i < current.combobox_model->num_items(); ++i) {
      if (UTF8ToWide(current.combobox_model->GetConfigValueAt(i)) == value) {
        current.combobox->SetSelectedItem(i);
        break;
      }
    }
  }
  const int value = hsu_sel_key_type_.multiple_choice_pref.GetValue();
  for (int i = 0; i < hsu_sel_key_type_.combobox_model->num_items(); ++i) {
    if (hsu_sel_key_type_.combobox_model->GetConfigValueAt(i) == value) {
      hsu_sel_key_type_.combobox->SetSelectedItem(i);
      break;
    }
  }
}

}  // namespace chromeos
<|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/extensions/extension_apitest.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, ContentSettings) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  PrefService* pref_service = browser()->profile()->GetPrefs();
  pref_service->SetBoolean(prefs::kBlockThirdPartyCookies, true);

  EXPECT_TRUE(RunExtensionTest("content_settings/standard")) << message_;

  const PrefService::Preference* pref = pref_service->FindPreference(
      prefs::kBlockThirdPartyCookies);
  ASSERT_TRUE(pref);
  EXPECT_TRUE(pref->IsExtensionControlled());
  EXPECT_EQ(false, pref_service->GetBoolean(prefs::kBlockThirdPartyCookies));
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoContentSettings) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  PrefService* prefs = browser()->profile()->GetPrefs();
  prefs->SetBoolean(prefs::kBlockThirdPartyCookies, false);

  EXPECT_TRUE(RunExtensionTest("content_settings/incognito")) << message_;

  // Setting an incognito preference should not create an incognito profile.
  EXPECT_FALSE(browser()->profile()->HasOffTheRecordProfile());

  PrefService* otr_prefs =
      browser()->profile()->GetOffTheRecordProfile()->GetPrefs();
  const PrefService::Preference* pref =
      otr_prefs->FindPreference(prefs::kBlockThirdPartyCookies);
  ASSERT_TRUE(pref);
  EXPECT_TRUE(pref->IsExtensionControlled());
  EXPECT_EQ(true, otr_prefs->GetBoolean(prefs::kBlockThirdPartyCookies));

  pref = prefs->FindPreference(prefs::kBlockThirdPartyCookies);
  ASSERT_TRUE(pref);
  EXPECT_FALSE(pref->IsExtensionControlled());
  EXPECT_EQ(false, prefs->GetBoolean(prefs::kBlockThirdPartyCookies));
}
<commit_msg>Fix clang build.<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/extensions/extension_apitest.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, ContentSettings) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  PrefService* pref_service = browser()->profile()->GetPrefs();
  pref_service->SetBoolean(prefs::kBlockThirdPartyCookies, true);

  EXPECT_TRUE(RunExtensionTest("content_settings/standard")) << message_;

  const PrefService::Preference* pref = pref_service->FindPreference(
      prefs::kBlockThirdPartyCookies);
  ASSERT_TRUE(pref);
  EXPECT_TRUE(pref->IsExtensionControlled());
  EXPECT_FALSE(pref_service->GetBoolean(prefs::kBlockThirdPartyCookies));
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoContentSettings) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  PrefService* prefs = browser()->profile()->GetPrefs();
  prefs->SetBoolean(prefs::kBlockThirdPartyCookies, false);

  EXPECT_TRUE(RunExtensionTest("content_settings/incognito")) << message_;

  // Setting an incognito preference should not create an incognito profile.
  EXPECT_FALSE(browser()->profile()->HasOffTheRecordProfile());

  PrefService* otr_prefs =
      browser()->profile()->GetOffTheRecordProfile()->GetPrefs();
  const PrefService::Preference* pref =
      otr_prefs->FindPreference(prefs::kBlockThirdPartyCookies);
  ASSERT_TRUE(pref);
  EXPECT_TRUE(pref->IsExtensionControlled());
  EXPECT_TRUE(otr_prefs->GetBoolean(prefs::kBlockThirdPartyCookies));

  pref = prefs->FindPreference(prefs::kBlockThirdPartyCookies);
  ASSERT_TRUE(pref);
  EXPECT_FALSE(pref->IsExtensionControlled());
  EXPECT_FALSE(prefs->GetBoolean(prefs::kBlockThirdPartyCookies));
}
<|endoftext|>


<commit_before>// Copyright (c) 2009 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/sync/notifier/communicator/ssl_socket_adapter.h"

#include "base/compiler_specific.h"
#include "chrome/browser/net/url_request_context_getter.h"
#include "chrome/browser/profile.h"
#include "net/base/ssl_config_service.h"
#include "net/socket/client_socket_factory.h"
#include "net/url_request/url_request_context.h"

namespace notifier {

namespace {

// Convert values from <errno.h> to values from "net/base/net_errors.h"
int MapPosixError(int err) {
  // There are numerous posix error codes, but these are the ones we thus far
  // find interesting.
  switch (err) {
    case EAGAIN:
#if EWOULDBLOCK != EAGAIN
    case EWOULDBLOCK:
#endif
      return net::ERR_IO_PENDING;
    case ENETDOWN:
      return net::ERR_INTERNET_DISCONNECTED;
    case ETIMEDOUT:
      return net::ERR_TIMED_OUT;
    case ECONNRESET:
    case ENETRESET:  // Related to keep-alive
      return net::ERR_CONNECTION_RESET;
    case ECONNABORTED:
      return net::ERR_CONNECTION_ABORTED;
    case ECONNREFUSED:
      return net::ERR_CONNECTION_REFUSED;
    case EHOSTUNREACH:
    case ENETUNREACH:
      return net::ERR_ADDRESS_UNREACHABLE;
    case EADDRNOTAVAIL:
      return net::ERR_ADDRESS_INVALID;
    case 0:
      return net::OK;
    default:
      LOG(WARNING) << "Unknown error " << err << " mapped to net::ERR_FAILED";
      return net::ERR_FAILED;
  }
}

}  // namespace

SSLSocketAdapter* SSLSocketAdapter::Create(AsyncSocket* socket) {
  return new SSLSocketAdapter(socket);
}

SSLSocketAdapter::SSLSocketAdapter(AsyncSocket* socket)
    : AsyncSocketAdapter(socket),
      ignore_bad_cert_(false),
      ALLOW_THIS_IN_INITIALIZER_LIST(
        connected_callback_(this, &SSLSocketAdapter::OnConnected)),
      ALLOW_THIS_IN_INITIALIZER_LIST(
        io_callback_(this, &SSLSocketAdapter::OnIO)),
      ssl_connected_(false),
      state_(STATE_NONE) {
  transport_socket_ = new TransportSocket(socket, this);
}

int SSLSocketAdapter::StartSSL(const char* hostname, bool restartable) {
  DCHECK(!restartable);
  hostname_ = hostname;

  if (socket_->GetState() != Socket::CS_CONNECTED) {
    state_ = STATE_SSL_WAIT;
    return 0;
  } else {
    return BeginSSL();
  }
}

int SSLSocketAdapter::BeginSSL() {
  // SSLConfigService is not thread-safe, and the default values for SSLConfig
  // are correct for us, so we don't use the config service to initialize this
  // object.
  net::SSLConfig ssl_config;
  transport_socket_->set_addr(talk_base::SocketAddress(hostname_.c_str()));
  ssl_socket_.reset(
      net::ClientSocketFactory::GetDefaultFactory()->CreateSSLClientSocket(
          transport_socket_, hostname_.c_str(), ssl_config));

  int result = ssl_socket_->Connect(&connected_callback_, NULL);

  if (result == net::ERR_IO_PENDING || result == net::OK) {
    return 0;
  } else {
    return result;
  }
}

int SSLSocketAdapter::Send(const void* buf, size_t len) {
  if (!ssl_connected_) {
    return AsyncSocketAdapter::Send(buf, len);
  } else {
    scoped_refptr<net::IOBuffer> transport_buf = new net::IOBuffer(len);
    memcpy(transport_buf->data(), buf, len);

    int result = ssl_socket_->Write(transport_buf, len, NULL);
    if (result == net::ERR_IO_PENDING) {
      SetError(EWOULDBLOCK);
    }
    transport_buf = NULL;
    return result;
  }
}

int SSLSocketAdapter::Recv(void* buf, size_t len) {
  if (!ssl_connected_) {
    return AsyncSocketAdapter::Recv(buf, len);
  }

  switch (state_) {
    case STATE_NONE: {
      transport_buf_ = new net::IOBuffer(len);
      int result = ssl_socket_->Read(transport_buf_, len, &io_callback_);
      if (result >= 0) {
        memcpy(buf, transport_buf_->data(), len);
      }

      if (result == net::ERR_IO_PENDING) {
        state_ = STATE_READ;
        SetError(EWOULDBLOCK);
      } else {
        if (result < 0) {
          SetError(result);
          LOG(INFO) << "Socket error " << result;
        }
        transport_buf_ = NULL;
      }
      return result;
    }
    case STATE_READ_COMPLETE:
      memcpy(buf, transport_buf_->data(), len);
      transport_buf_ = NULL;
      state_ = STATE_NONE;
      return data_transferred_;

    case STATE_READ:
    case STATE_WRITE:
    case STATE_WRITE_COMPLETE:
    case STATE_SSL_WAIT:
      SetError(EWOULDBLOCK);
      return -1;

    default:
      NOTREACHED();
      break;
  }
  return -1;
}

void SSLSocketAdapter::OnConnected(int result) {
  if (result == net::OK) {
    ssl_connected_ = true;
    OnConnectEvent(this);
  }
}

void SSLSocketAdapter::OnIO(int result) {
  switch (state_) {
    case STATE_READ:
      state_ = STATE_READ_COMPLETE;
      data_transferred_ = result;
      AsyncSocketAdapter::OnReadEvent(this);
      break;
    case STATE_WRITE:
      state_ = STATE_WRITE_COMPLETE;
      data_transferred_ = result;
      AsyncSocketAdapter::OnWriteEvent(this);
      break;
    case STATE_NONE:
    case STATE_READ_COMPLETE:
    case STATE_WRITE_COMPLETE:
    case STATE_SSL_WAIT:
    default:
      NOTREACHED();
      break;
  }
}

void SSLSocketAdapter::OnReadEvent(talk_base::AsyncSocket* socket) {
  if (!transport_socket_->OnReadEvent(socket))
    AsyncSocketAdapter::OnReadEvent(socket);
}

void SSLSocketAdapter::OnWriteEvent(talk_base::AsyncSocket* socket) {
  if (!transport_socket_->OnWriteEvent(socket))
    AsyncSocketAdapter::OnWriteEvent(socket);
}

void SSLSocketAdapter::OnConnectEvent(talk_base::AsyncSocket* socket) {
  if (state_ != STATE_SSL_WAIT) {
    AsyncSocketAdapter::OnConnectEvent(socket);
  } else {
    state_ = STATE_NONE;
    int result = BeginSSL();
    if (0 != result) {
      // TODO(zork): Handle this case gracefully.
      LOG(WARNING) << "BeginSSL() failed with " << result;
    }
  }
}

TransportSocket::TransportSocket(talk_base::AsyncSocket* socket,
                                 SSLSocketAdapter *ssl_adapter)
    : connect_callback_(NULL),
      read_callback_(NULL),
      write_callback_(NULL),
      read_buffer_len_(0),
      write_buffer_len_(0),
      socket_(socket) {
    socket_->SignalConnectEvent.connect(this, &TransportSocket::OnConnectEvent);
}

int TransportSocket::Connect(net::CompletionCallback* callback,
                             net::LoadLog* /* load_log */) {
  connect_callback_ = callback;
  return socket_->Connect(addr_);
}

void TransportSocket::Disconnect() {
  socket_->Close();
}

bool TransportSocket::IsConnected() const {
  return (socket_->GetState() == talk_base::Socket::CS_CONNECTED);
}

bool TransportSocket::IsConnectedAndIdle() const {
  // Not implemented.
  NOTREACHED();
  return false;
}

int TransportSocket::GetPeerName(struct sockaddr* name, socklen_t* namelen) {
  talk_base::SocketAddress address = socket_->GetRemoteAddress();
  address.ToSockAddr(reinterpret_cast<sockaddr_in *>(name));
  return 0;
}

int TransportSocket::Read(net::IOBuffer* buf, int buf_len,
                          net::CompletionCallback* callback) {
  DCHECK(buf);
  DCHECK(!read_callback_);
  DCHECK(!read_buffer_.get());
  int result = socket_->Recv(buf->data(), buf_len);
  if (result < 0) {
    result = MapPosixError(socket_->GetError());
    if (result == net::ERR_IO_PENDING) {
      read_callback_ = callback;
      read_buffer_ = buf;
      read_buffer_len_ = buf_len;
    }
  }
  return result;
}

int TransportSocket::Write(net::IOBuffer* buf, int buf_len,
                           net::CompletionCallback* callback) {
  DCHECK(buf);
  DCHECK(!write_callback_);
  DCHECK(!write_buffer_.get());
  int result = socket_->Send(buf->data(), buf_len);
  if (result < 0) {
    result = MapPosixError(socket_->GetError());
    if (result == net::ERR_IO_PENDING) {
      write_callback_ = callback;
      write_buffer_ = buf;
      write_buffer_len_ = buf_len;
    }
  }
  return result;
}

bool TransportSocket::SetReceiveBufferSize(int32 size) {
  // Not implemented.
  return false;
}

bool TransportSocket::SetSendBufferSize(int32 size) {
  // Not implemented.
  return false;
}

void TransportSocket::OnConnectEvent(talk_base::AsyncSocket * socket) {
  if (connect_callback_) {
    net::CompletionCallback *callback = connect_callback_;
    connect_callback_ = NULL;
    callback->RunWithParams(Tuple1<int>(MapPosixError(socket_->GetError())));
  }
}

bool TransportSocket::OnReadEvent(talk_base::AsyncSocket* socket) {
  if (read_callback_) {
    DCHECK(read_buffer_.get());
    net::CompletionCallback* callback = read_callback_;
    scoped_refptr<net::IOBuffer> buffer = read_buffer_;
    int buffer_len = read_buffer_len_;

    read_callback_ = NULL;
    read_buffer_ = NULL;
    read_buffer_len_ = 0;

    int result = socket_->Recv(buffer->data(), buffer_len);
    if (result < 0) {
      result = MapPosixError(socket_->GetError());
      if (result == net::ERR_IO_PENDING) {
        read_callback_ = callback;
        read_buffer_ = buffer;
        read_buffer_len_ = buffer_len;
        return true;
      }
    }
    callback->RunWithParams(Tuple1<int>(result));
    return true;
  } else {
    return false;
  }
}

bool TransportSocket::OnWriteEvent(talk_base::AsyncSocket* socket) {
  if (write_callback_) {
    DCHECK(write_buffer_.get());
    net::CompletionCallback* callback = write_callback_;
    scoped_refptr<net::IOBuffer> buffer = write_buffer_;
    int buffer_len = write_buffer_len_;

    write_callback_ = NULL;
    write_buffer_ = NULL;
    write_buffer_len_ = 0;

    int result = socket_->Send(buffer->data(), buffer_len);
    if (result < 0) {
      result = MapPosixError(socket_->GetError());
      if (result == net::ERR_IO_PENDING) {
        write_callback_ = callback;
        write_buffer_ = buffer;
        write_buffer_len_ = buffer_len;
        return true;
      }
    }
    callback->RunWithParams(Tuple1<int>(result));
    return true;
  } else {
    return false;
  }
}

}  // namespace notifier
<commit_msg>Added check for Chrome message loop in SSLSocketAdapter::BeginSSL().<commit_after>// Copyright (c) 2009 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/sync/notifier/communicator/ssl_socket_adapter.h"

#include "base/compiler_specific.h"
#include "base/message_loop.h"
#include "chrome/browser/net/url_request_context_getter.h"
#include "chrome/browser/profile.h"
#include "net/base/ssl_config_service.h"
#include "net/socket/client_socket_factory.h"
#include "net/url_request/url_request_context.h"

namespace notifier {

namespace {

// Convert values from <errno.h> to values from "net/base/net_errors.h"
int MapPosixError(int err) {
  // There are numerous posix error codes, but these are the ones we thus far
  // find interesting.
  switch (err) {
    case EAGAIN:
#if EWOULDBLOCK != EAGAIN
    case EWOULDBLOCK:
#endif
      return net::ERR_IO_PENDING;
    case ENETDOWN:
      return net::ERR_INTERNET_DISCONNECTED;
    case ETIMEDOUT:
      return net::ERR_TIMED_OUT;
    case ECONNRESET:
    case ENETRESET:  // Related to keep-alive
      return net::ERR_CONNECTION_RESET;
    case ECONNABORTED:
      return net::ERR_CONNECTION_ABORTED;
    case ECONNREFUSED:
      return net::ERR_CONNECTION_REFUSED;
    case EHOSTUNREACH:
    case ENETUNREACH:
      return net::ERR_ADDRESS_UNREACHABLE;
    case EADDRNOTAVAIL:
      return net::ERR_ADDRESS_INVALID;
    case 0:
      return net::OK;
    default:
      LOG(WARNING) << "Unknown error " << err << " mapped to net::ERR_FAILED";
      return net::ERR_FAILED;
  }
}

}  // namespace

SSLSocketAdapter* SSLSocketAdapter::Create(AsyncSocket* socket) {
  return new SSLSocketAdapter(socket);
}

SSLSocketAdapter::SSLSocketAdapter(AsyncSocket* socket)
    : AsyncSocketAdapter(socket),
      ignore_bad_cert_(false),
      ALLOW_THIS_IN_INITIALIZER_LIST(
        connected_callback_(this, &SSLSocketAdapter::OnConnected)),
      ALLOW_THIS_IN_INITIALIZER_LIST(
        io_callback_(this, &SSLSocketAdapter::OnIO)),
      ssl_connected_(false),
      state_(STATE_NONE) {
  transport_socket_ = new TransportSocket(socket, this);
}

int SSLSocketAdapter::StartSSL(const char* hostname, bool restartable) {
  DCHECK(!restartable);
  hostname_ = hostname;

  if (socket_->GetState() != Socket::CS_CONNECTED) {
    state_ = STATE_SSL_WAIT;
    return 0;
  } else {
    return BeginSSL();
  }
}

int SSLSocketAdapter::BeginSSL() {
  if (!MessageLoop::current()) {
    // Certificate verification is done via the Chrome message loop.
    // Without this check, if we don't have a chrome message loop the
    // SSL connection just hangs silently.
    LOG(DFATAL) << "Chrome message loop (needed by SSL certificate "
                << "verification) does not exist";
    return net::ERR_UNEXPECTED;
  }

  // SSLConfigService is not thread-safe, and the default values for SSLConfig
  // are correct for us, so we don't use the config service to initialize this
  // object.
  net::SSLConfig ssl_config;
  transport_socket_->set_addr(talk_base::SocketAddress(hostname_.c_str()));
  ssl_socket_.reset(
      net::ClientSocketFactory::GetDefaultFactory()->CreateSSLClientSocket(
          transport_socket_, hostname_.c_str(), ssl_config));

  int result = ssl_socket_->Connect(&connected_callback_, NULL);

  if (result == net::ERR_IO_PENDING || result == net::OK) {
    return 0;
  } else {
    return result;
  }
}

int SSLSocketAdapter::Send(const void* buf, size_t len) {
  if (!ssl_connected_) {
    return AsyncSocketAdapter::Send(buf, len);
  } else {
    scoped_refptr<net::IOBuffer> transport_buf = new net::IOBuffer(len);
    memcpy(transport_buf->data(), buf, len);

    int result = ssl_socket_->Write(transport_buf, len, NULL);
    if (result == net::ERR_IO_PENDING) {
      SetError(EWOULDBLOCK);
    }
    transport_buf = NULL;
    return result;
  }
}

int SSLSocketAdapter::Recv(void* buf, size_t len) {
  if (!ssl_connected_) {
    return AsyncSocketAdapter::Recv(buf, len);
  }

  switch (state_) {
    case STATE_NONE: {
      transport_buf_ = new net::IOBuffer(len);
      int result = ssl_socket_->Read(transport_buf_, len, &io_callback_);
      if (result >= 0) {
        memcpy(buf, transport_buf_->data(), len);
      }

      if (result == net::ERR_IO_PENDING) {
        state_ = STATE_READ;
        SetError(EWOULDBLOCK);
      } else {
        if (result < 0) {
          SetError(result);
          LOG(INFO) << "Socket error " << result;
        }
        transport_buf_ = NULL;
      }
      return result;
    }
    case STATE_READ_COMPLETE:
      memcpy(buf, transport_buf_->data(), len);
      transport_buf_ = NULL;
      state_ = STATE_NONE;
      return data_transferred_;

    case STATE_READ:
    case STATE_WRITE:
    case STATE_WRITE_COMPLETE:
    case STATE_SSL_WAIT:
      SetError(EWOULDBLOCK);
      return -1;

    default:
      NOTREACHED();
      break;
  }
  return -1;
}

void SSLSocketAdapter::OnConnected(int result) {
  if (result == net::OK) {
    ssl_connected_ = true;
    OnConnectEvent(this);
  }
}

void SSLSocketAdapter::OnIO(int result) {
  switch (state_) {
    case STATE_READ:
      state_ = STATE_READ_COMPLETE;
      data_transferred_ = result;
      AsyncSocketAdapter::OnReadEvent(this);
      break;
    case STATE_WRITE:
      state_ = STATE_WRITE_COMPLETE;
      data_transferred_ = result;
      AsyncSocketAdapter::OnWriteEvent(this);
      break;
    case STATE_NONE:
    case STATE_READ_COMPLETE:
    case STATE_WRITE_COMPLETE:
    case STATE_SSL_WAIT:
    default:
      NOTREACHED();
      break;
  }
}

void SSLSocketAdapter::OnReadEvent(talk_base::AsyncSocket* socket) {
  if (!transport_socket_->OnReadEvent(socket))
    AsyncSocketAdapter::OnReadEvent(socket);
}

void SSLSocketAdapter::OnWriteEvent(talk_base::AsyncSocket* socket) {
  if (!transport_socket_->OnWriteEvent(socket))
    AsyncSocketAdapter::OnWriteEvent(socket);
}

void SSLSocketAdapter::OnConnectEvent(talk_base::AsyncSocket* socket) {
  if (state_ != STATE_SSL_WAIT) {
    AsyncSocketAdapter::OnConnectEvent(socket);
  } else {
    state_ = STATE_NONE;
    int result = BeginSSL();
    if (0 != result) {
      // TODO(zork): Handle this case gracefully.
      LOG(WARNING) << "BeginSSL() failed with " << result;
    }
  }
}

TransportSocket::TransportSocket(talk_base::AsyncSocket* socket,
                                 SSLSocketAdapter *ssl_adapter)
    : connect_callback_(NULL),
      read_callback_(NULL),
      write_callback_(NULL),
      read_buffer_len_(0),
      write_buffer_len_(0),
      socket_(socket) {
    socket_->SignalConnectEvent.connect(this, &TransportSocket::OnConnectEvent);
}

int TransportSocket::Connect(net::CompletionCallback* callback,
                             net::LoadLog* /* load_log */) {
  connect_callback_ = callback;
  return socket_->Connect(addr_);
}

void TransportSocket::Disconnect() {
  socket_->Close();
}

bool TransportSocket::IsConnected() const {
  return (socket_->GetState() == talk_base::Socket::CS_CONNECTED);
}

bool TransportSocket::IsConnectedAndIdle() const {
  // Not implemented.
  NOTREACHED();
  return false;
}

int TransportSocket::GetPeerName(struct sockaddr* name, socklen_t* namelen) {
  talk_base::SocketAddress address = socket_->GetRemoteAddress();
  address.ToSockAddr(reinterpret_cast<sockaddr_in *>(name));
  return 0;
}

int TransportSocket::Read(net::IOBuffer* buf, int buf_len,
                          net::CompletionCallback* callback) {
  DCHECK(buf);
  DCHECK(!read_callback_);
  DCHECK(!read_buffer_.get());
  int result = socket_->Recv(buf->data(), buf_len);
  if (result < 0) {
    result = MapPosixError(socket_->GetError());
    if (result == net::ERR_IO_PENDING) {
      read_callback_ = callback;
      read_buffer_ = buf;
      read_buffer_len_ = buf_len;
    }
  }
  return result;
}

int TransportSocket::Write(net::IOBuffer* buf, int buf_len,
                           net::CompletionCallback* callback) {
  DCHECK(buf);
  DCHECK(!write_callback_);
  DCHECK(!write_buffer_.get());
  int result = socket_->Send(buf->data(), buf_len);
  if (result < 0) {
    result = MapPosixError(socket_->GetError());
    if (result == net::ERR_IO_PENDING) {
      write_callback_ = callback;
      write_buffer_ = buf;
      write_buffer_len_ = buf_len;
    }
  }
  return result;
}

bool TransportSocket::SetReceiveBufferSize(int32 size) {
  // Not implemented.
  return false;
}

bool TransportSocket::SetSendBufferSize(int32 size) {
  // Not implemented.
  return false;
}

void TransportSocket::OnConnectEvent(talk_base::AsyncSocket * socket) {
  if (connect_callback_) {
    net::CompletionCallback *callback = connect_callback_;
    connect_callback_ = NULL;
    callback->RunWithParams(Tuple1<int>(MapPosixError(socket_->GetError())));
  }
}

bool TransportSocket::OnReadEvent(talk_base::AsyncSocket* socket) {
  if (read_callback_) {
    DCHECK(read_buffer_.get());
    net::CompletionCallback* callback = read_callback_;
    scoped_refptr<net::IOBuffer> buffer = read_buffer_;
    int buffer_len = read_buffer_len_;

    read_callback_ = NULL;
    read_buffer_ = NULL;
    read_buffer_len_ = 0;

    int result = socket_->Recv(buffer->data(), buffer_len);
    if (result < 0) {
      result = MapPosixError(socket_->GetError());
      if (result == net::ERR_IO_PENDING) {
        read_callback_ = callback;
        read_buffer_ = buffer;
        read_buffer_len_ = buffer_len;
        return true;
      }
    }
    callback->RunWithParams(Tuple1<int>(result));
    return true;
  } else {
    return false;
  }
}

bool TransportSocket::OnWriteEvent(talk_base::AsyncSocket* socket) {
  if (write_callback_) {
    DCHECK(write_buffer_.get());
    net::CompletionCallback* callback = write_callback_;
    scoped_refptr<net::IOBuffer> buffer = write_buffer_;
    int buffer_len = write_buffer_len_;

    write_callback_ = NULL;
    write_buffer_ = NULL;
    write_buffer_len_ = 0;

    int result = socket_->Send(buffer->data(), buffer_len);
    if (result < 0) {
      result = MapPosixError(socket_->GetError());
      if (result == net::ERR_IO_PENDING) {
        write_callback_ = callback;
        write_buffer_ = buffer;
        write_buffer_len_ = buffer_len;
        return true;
      }
    }
    callback->RunWithParams(Tuple1<int>(result));
    return true;
  } else {
    return false;
  }
}

}  // namespace notifier
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include <MNSInclude.hxx>
#include "MTypeConverter.hxx"
#include <ucbhelper/content.hxx>

using namespace connectivity::mozab;

// -------------------------------------------------------------------------
void MTypeConverter::ouStringToNsString(::rtl::OUString const &ous, nsString &nss)
{
    // Convert to ::rtl::OString (utf-8 encoding).
    ::rtl::OString os(ous,ous.getLength(), RTL_TEXTENCODING_UTF8);

    const char *cs = os.getStr();
    PRUint32 csLen = os.getLength();

    NS_ConvertUTF8toUCS2 mozString(cs, csLen);
    //const PRUnichar* uniMozString = (const PRUnichar*) mozString;
    nss = mozString; // temp.
}
// -------------------------------------------------------------------------
::rtl::OUString MTypeConverter::nsACStringToOUString( const nsACString& _source )
{
    const char* buffer = _source.BeginReading();
    const char* bufferEnd = _source.EndReading();
    return ::rtl::OUString( buffer, static_cast<sal_Int32>(bufferEnd - buffer), RTL_TEXTENCODING_ASCII_US );
}
// -------------------------------------------------------------------------
::rtl::OString MTypeConverter::nsACStringToOString( const nsACString& _source )
{
    const char* buffer = _source.BeginReading();
    const char* bufferEnd = _source.EndReading();
    return ::rtl::OString( buffer, static_cast<sal_Int32>(bufferEnd - buffer) );
}
// -------------------------------------------------------------------------
void MTypeConverter::asciiOUStringToNsACString( const ::rtl::OUString& _asciiString, nsACString& _dest )
{
    ::rtl::OString sAsciiVersion( _asciiString.getStr(), _asciiString.getLength(), RTL_TEXTENCODING_ASCII_US );
    asciiToNsACString( sAsciiVersion.getStr(), _dest );
}
// -------------------------------------------------------------------------
void MTypeConverter::asciiToNsACString( const sal_Char* _asciiString, nsACString& _dest )
{
    _dest.Truncate();
    _dest.AppendASCII( _asciiString );
}
// -------------------------------------------------------------------------
void MTypeConverter::nsStringToOUString(nsString const &nss, ::rtl::OUString &ous)
{
    // Get clone of buffer.
    PRUnichar *uc = ToNewUnicode(nss);
    sal_Int32 nssLen = nss.Length();

    // TODO check if this is ok.
    // PRUnichar != sal_Unicode in mingw
    ::rtl::OUString _ous(reinterpret_cast_mingw_only<sal_Unicode *>(uc), nssLen);
    ous = _ous;

    nsMemory::Free(uc);
}
// -------------------------------------------------------------------------
void MTypeConverter::prUnicharToOUString(PRUnichar const *pru, ::rtl::OUString &ous)
{
    // TODO, specify length.
    // PRUnichar != sal_Unicode in mingw
    ::rtl::OUString _ous(reinterpret_cast_mingw_only<const sal_Unicode *>(pru));
    ous = _ous;
}
// -------------------------------------------------------------------------
char *MTypeConverter::ouStringToCCharStringUtf8(::rtl::OUString const &ous)
{
    // Convert to ::rtl::OString,
    ::rtl::OString os(ous,ous.getLength(), RTL_TEXTENCODING_UTF8);

    const char *cs = os.getStr();

    return(strdup(cs));
}
// -------------------------------------------------------------------------
char *MTypeConverter::ouStringToCCharStringAscii(::rtl::OUString const &ous)
{
    // Convert ::rtl::OUString to ::rtl::OString,
    ::rtl::OString os(ous,ous.getLength(), RTL_TEXTENCODING_ASCII_US);

    return(strdup(os.getStr()));
}
// -------------------------------------------------------------------------
char *MTypeConverter::nsStringToCCharStringAscii(nsString const &nss)
{
    char cs[1024];
    nss.ToCString(cs, 1024);

    return(strdup(cs));
}
// -------------------------------------------------------------------------
::std::string MTypeConverter::ouStringToStlString(::rtl::OUString const &ous)
{
    // Convert ::rtl::OUString to ::rtl::OString.
    ::rtl::OString os(ous,ous.getLength(),RTL_TEXTENCODING_ASCII_US);
    return( ::std::string(os.getStr()));
}
// -------------------------------------------------------------------------

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>avoid implicit casting<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include <MNSInclude.hxx>
#include "MTypeConverter.hxx"
#include <ucbhelper/content.hxx>

using namespace connectivity::mozab;

// -------------------------------------------------------------------------
void MTypeConverter::ouStringToNsString(::rtl::OUString const &ous, nsString &nss)
{
    // Convert to ::rtl::OString (utf-8 encoding).
    ::rtl::OString os(rtl::OUStringToOString(ous, RTL_TEXTENCODING_UTF8));

    const char *cs = os.getStr();
    PRUint32 csLen = os.getLength();

    NS_ConvertUTF8toUCS2 mozString(cs, csLen);
    //const PRUnichar* uniMozString = (const PRUnichar*) mozString;
    nss = mozString; // temp.
}
// -------------------------------------------------------------------------
::rtl::OUString MTypeConverter::nsACStringToOUString( const nsACString& _source )
{
    const char* buffer = _source.BeginReading();
    const char* bufferEnd = _source.EndReading();
    return ::rtl::OUString( buffer, static_cast<sal_Int32>(bufferEnd - buffer), RTL_TEXTENCODING_ASCII_US );
}
// -------------------------------------------------------------------------
::rtl::OString MTypeConverter::nsACStringToOString( const nsACString& _source )
{
    const char* buffer = _source.BeginReading();
    const char* bufferEnd = _source.EndReading();
    return ::rtl::OString( buffer, static_cast<sal_Int32>(bufferEnd - buffer) );
}
// -------------------------------------------------------------------------
void MTypeConverter::asciiOUStringToNsACString( const ::rtl::OUString& _asciiString, nsACString& _dest )
{
    ::rtl::OString sAsciiVersion( _asciiString.getStr(), _asciiString.getLength(), RTL_TEXTENCODING_ASCII_US );
    asciiToNsACString( sAsciiVersion.getStr(), _dest );
}
// -------------------------------------------------------------------------
void MTypeConverter::asciiToNsACString( const sal_Char* _asciiString, nsACString& _dest )
{
    _dest.Truncate();
    _dest.AppendASCII( _asciiString );
}
// -------------------------------------------------------------------------
void MTypeConverter::nsStringToOUString(nsString const &nss, ::rtl::OUString &ous)
{
    // Get clone of buffer.
    PRUnichar *uc = ToNewUnicode(nss);
    sal_Int32 nssLen = nss.Length();

    // TODO check if this is ok.
    // PRUnichar != sal_Unicode in mingw
    ::rtl::OUString _ous(reinterpret_cast_mingw_only<sal_Unicode *>(uc), nssLen);
    ous = _ous;

    nsMemory::Free(uc);
}
// -------------------------------------------------------------------------
void MTypeConverter::prUnicharToOUString(PRUnichar const *pru, ::rtl::OUString &ous)
{
    // TODO, specify length.
    // PRUnichar != sal_Unicode in mingw
    ::rtl::OUString _ous(reinterpret_cast_mingw_only<const sal_Unicode *>(pru));
    ous = _ous;
}
// -------------------------------------------------------------------------
char *MTypeConverter::ouStringToCCharStringUtf8(::rtl::OUString const &ous)
{
    // Convert to ::rtl::OString,
    ::rtl::OString os(rtl::OUStringToOString(ous, RTL_TEXTENCODING_UTF8));

    const char *cs = os.getStr();

    return(strdup(cs));
}
// -------------------------------------------------------------------------
char *MTypeConverter::ouStringToCCharStringAscii(::rtl::OUString const &ous)
{
    // Convert ::rtl::OUString to ::rtl::OString,
    ::rtl::OString os(rtl::OUStringToOString(ous, RTL_TEXTENCODING_ASCII_US));

    return(strdup(os.getStr()));
}
// -------------------------------------------------------------------------
char *MTypeConverter::nsStringToCCharStringAscii(nsString const &nss)
{
    char cs[1024];
    nss.ToCString(cs, 1024);

    return(strdup(cs));
}
// -------------------------------------------------------------------------
::std::string MTypeConverter::ouStringToStlString(::rtl::OUString const &ous)
{
    // Convert ::rtl::OUString to ::rtl::OString.
    ::rtl::OString os(rtl::OUStringToOString(ous,RTL_TEXTENCODING_ASCII_US));
    return( ::std::string(os.getStr()));
}
// -------------------------------------------------------------------------

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>// ========================================================================== //
// This file is part of Sara, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2019 David Ok <david.ok8@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //

//! @example

#include <DO/Sara/Core/PhysicalQuantities.hpp>
#include <DO/Sara/Core/StringFormat.hpp>
#include <DO/Sara/Graphics.hpp>
#include <DO/Sara/ImageProcessing/Interpolation.hpp>
#include <DO/Sara/MultiViewGeometry/Camera/BrownConradyCamera.hpp>
#include <DO/Sara/VideoIO.hpp>

#include <array>
#include <filesystem>

#include <omp.h>

using namespace std;
using namespace std::string_literals;

namespace fs = std::filesystem;

namespace sara = DO::Sara;
using sara::operator""_px;
using sara::operator""_m;

const auto camera_height = 1.30_m;
const auto px_per_meter = 8._px / 1._m;
const auto map_metric_dims = std::array{2.L * 10._m, 100._m};
const auto map_pixel_dims = std::array{map_metric_dims[0] * px_per_meter,
                                       map_metric_dims[1] * px_per_meter};

auto to_map_view(const sara::BrownConradyCamera<float>& C,
                 const sara::ImageView<sara::Rgb8>& image_plane)
    -> sara::Image<sara::Rgb8>
{
  const auto xmin_px = -int(map_pixel_dims[0].value / 2);
  const auto xmax_px = int(map_pixel_dims[0].value / 2);
  const auto ymin_px = 0;
  const auto ymax_px = int(map_pixel_dims[1].value);

  const auto w = image_plane.width();
  const auto h = image_plane.height();

  auto map_view = sara::Image<sara::Rgb8>(map_pixel_dims[0].value,  //
                                          map_pixel_dims[1].value);

  for (auto y = ymin_px; y < ymax_px; ++y)
  {
    for (auto x = xmin_px; x < xmax_px; ++x)
    {
      const auto u = x - xmin_px;
      const auto v = ymax_px - y;

      const auto in_output_domain = 0 <= u && u < map_view.width() &&  //
                                    0 <= v && v < map_view.height();   //
      if (!in_output_domain)
        continue;

      // Convert the corresponding metric coordinates.
      auto xyz = Eigen::Vector3f(x / px_per_meter.value, camera_height.value,
                                 y / px_per_meter.value);

      // Project to the image.
      Eigen::Vector2d p = (C.K * xyz).hnormalized().cast<double>();

      const auto in_image_domain = 0 <= p.x() && p.x() < w - 1 &&  //
                                   0 <= p.y() && p.y() < h - 1;
      if (!in_image_domain)
      {
        map_view(u, v) = sara::Black8;
        continue;
      }

      auto color = sara::interpolate(image_plane, p);
      color /= 255;

      auto color_converted = sara::Rgb8{};
      sara::smart_convert_color(color, color_converted);

      map_view(u, v) = color_converted;
    }
  }

  return map_view;
}

auto difference(const sara::ImageView<sara::Rgb8>& a1,
                const sara::ImageView<sara::Rgb8>& a2,
                sara::ImageView<float>& diff) -> void
{
  for (auto y = 0; y < a1.height(); ++y)
    for (auto x = 0; x < a2.width(); ++x)
      diff(x, y) = (a1(x, y).cast<float>() - a2(x, y).cast<float>()).norm();

  const auto max_val = diff.flat_array().maxCoeff();
  const auto min_val = diff.flat_array().minCoeff();
  diff.flat_array() = (diff.flat_array() - min_val) / (max_val - min_val);
}

auto average(const sara::ImageView<sara::Rgb8>& a1,
             const sara::ImageView<sara::Rgb8>& a2,
             sara::ImageView<sara::Rgb8>& average) -> void
{
  for (auto y = 0; y < a1.height(); ++y)
  {
    for (auto x = 0; x < a1.width(); ++x)
    {
      const auto c1 = a1(x, y);
      if (c1 == sara::Black8)
      {
        average(x, y) = c1;
        continue;
      }

      const auto c2 = a2(x, y);
      const Eigen::Vector3i c = (0.5f *  //
                                 (c1.cast<float>() + c2.cast<float>()))
                                    .cast<int>();
      average(x, y)(0) = c(0);
      average(x, y)(1) = c(1);
      average(x, y)(2) = c(2);
    }
  }
}

int __main(int argc, char**argv)
{
  if (argc < 2)
    return -1;
  const auto video_filepath = argv[1];

  omp_set_num_threads(omp_get_max_threads());

  auto video_stream = sara::VideoStream{video_filepath};
  auto video_writer = sara::VideoWriter{
#ifdef __APPLE__
      "/Users/david/Desktop/test.mp4",
#else
      "/home/david/Desktop/test.mp4",
#endif
      Eigen::Vector2i(map_pixel_dims[0].value, map_pixel_dims[1].value)};

  // one example of distortion correction.
  auto camera_parameters = sara::BrownConradyCamera<float>{};
  {
    const auto f = 946.8984425572634_px;
    const auto u0 = 960._px;
    const auto v0 = 540._px;
    const auto p = Eigen::Vector2f{0, 0};
    const auto k = Eigen::Vector3f{
        -0.22996356451342749,  //
        0.05952465745165465,
        -0.007399008111054717  //
    };
    camera_parameters.K << f, 0, u0,
                           0, f, v0,
                           0, 0,  1;
    camera_parameters.k = k;
    camera_parameters.p = p;
  }
  // // one example of distortion correction.
  // auto camera_parameters = sara::BrownConradyCamera<float>{};
  // {
  //   const auto f = 650._px;
  //   const auto u0 = 640._px;
  //   const auto v0 = 360._px;
  //   camera_parameters.K << f, 0, u0,
  //                          0, f, v0,
  //                          0, 0,  1;
  //   camera_parameters.k.setZero();
  //   camera_parameters.p.setZero();
  // }
  camera_parameters.calculate_K_inverse();
  camera_parameters.calculate_drap_lefevre_inverse_coefficients();

  auto frame_undistorted = sara::Image<sara::Rgb8>{video_stream.sizes()};
  auto frame_redistorted = sara::Image<sara::Rgb8>{video_stream.sizes()};
  auto frame_diff = sara::Image<float>{video_stream.sizes()};
  auto frame_average = sara::Image<sara::Rgb8>{video_stream.sizes()};

  auto wu = sara::create_window(video_stream.frame().sizes(),  //
                                "Undistorted Frame");
  auto wd = sara::create_window(video_stream.frame().sizes(),  //
                                "Redistorted Frame");
  auto wdiff = sara::create_window(video_stream.frame().sizes(),  //
                                   "Absolute frame diff");
  auto wavg = sara::create_window(video_stream.frame().sizes(),  //
                                  "Absolute frame average");
  auto wmap = sara::create_window(                          //
      map_pixel_dims[0].value,                              //
      map_pixel_dims[1].value,                              //
      sara::format("Bird's Eye View [Scale: %d px = 1 m]",  //
                   int(px_per_meter.value)));

  while (video_stream.read())
  {
#ifdef DIRTY
    frame_undistorted = video_stream.frame();
    auto map_view = to_map_view(camera_parameters, video_stream.frame());
#else
    camera_parameters.undistort(video_stream.frame(), frame_undistorted);
    camera_parameters.distort_drap_lefevre(frame_undistorted, frame_redistorted);
    auto map_view = to_map_view(camera_parameters, frame_undistorted);

    difference(frame_redistorted, video_stream.frame(), frame_diff);
    average(frame_redistorted, video_stream.frame(), frame_average);
#endif

    sara::set_active_window(wu);
    sara::display(frame_undistorted);

    sara::set_active_window(wd);
    sara::display(frame_redistorted);

    sara::set_active_window(wdiff);
    sara::display(frame_diff);

    sara::set_active_window(wavg);
    sara::display(frame_average);

    sara::set_active_window(wmap);
    constexpr auto interval = 20;
    for (auto i = 0; i < 5; ++i)
    {
      const auto p1 = Eigen::Vector2i(0, i * interval * px_per_meter.value);
      const auto p2 =
          Eigen::Vector2i(map_view.width(), i * interval * px_per_meter.value);
      sara::draw_line(map_view, p1.x(), p1.y(), p2.x(), p2.y(), sara::Yellow8,
                      2);
    }
    sara::display(map_view);

    video_writer.write(map_view);
  }

  sara::close_window(wu);
  sara::close_window(wd);
  sara::close_window(wdiff);
  sara::close_window(wavg);
  sara::close_window(wmap);

  return 0;
}

int main(int argc, char** argv)
{
  DO::Sara::GraphicsApplication app(argc, argv);
  app.register_user_main(__main);
  return app.exec();
}
<commit_msg>MAINT: fix compiler errors.<commit_after>// ========================================================================== //
// This file is part of Sara, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2019 David Ok <david.ok8@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //

//! @example

#include <DO/Sara/Core/PhysicalQuantities.hpp>
#include <DO/Sara/Core/StringFormat.hpp>
#include <DO/Sara/Graphics.hpp>
#include <DO/Sara/ImageProcessing/Interpolation.hpp>
#include <DO/Sara/MultiViewGeometry/Camera/BrownConradyCamera.hpp>
#include <DO/Sara/VideoIO.hpp>

#include <array>

#include <omp.h>

using namespace std;
using namespace std::string_literals;

namespace sara = DO::Sara;
using sara::operator""_px;
using sara::operator""_m;

const auto camera_height = 1.30_m;
const auto px_per_meter = 8._px / 1._m;
const auto map_metric_dims = std::array{2.L * 10._m, 100._m};
const auto map_pixel_dims = std::array{map_metric_dims[0] * px_per_meter,
                                       map_metric_dims[1] * px_per_meter};

auto to_map_view(const sara::BrownConradyCamera<float>& C,
                 const sara::ImageView<sara::Rgb8>& image_plane)
    -> sara::Image<sara::Rgb8>
{
  const auto xmin_px = -int(map_pixel_dims[0].value / 2);
  const auto xmax_px = int(map_pixel_dims[0].value / 2);
  const auto ymin_px = 0;
  const auto ymax_px = int(map_pixel_dims[1].value);

  const auto w = image_plane.width();
  const auto h = image_plane.height();

  auto map_view = sara::Image<sara::Rgb8>(map_pixel_dims[0].value,  //
                                          map_pixel_dims[1].value);

  for (auto y = ymin_px; y < ymax_px; ++y)
  {
    for (auto x = xmin_px; x < xmax_px; ++x)
    {
      const auto u = x - xmin_px;
      const auto v = ymax_px - y;

      const auto in_output_domain = 0 <= u && u < map_view.width() &&  //
                                    0 <= v && v < map_view.height();   //
      if (!in_output_domain)
        continue;

      // Convert the corresponding metric coordinates.
      auto xyz = Eigen::Vector3f(x / px_per_meter.value,  //
                                 camera_height.value,     //
                                 y / px_per_meter.value);

      // Project to the image.
      Eigen::Vector2d p = (C.K * xyz).hnormalized().cast<double>();

      const auto in_image_domain = 0 <= p.x() && p.x() < w - 1 &&  //
                                   0 <= p.y() && p.y() < h - 1;
      if (!in_image_domain)
      {
        map_view(u, v) = sara::Black8;
        continue;
      }

      auto color = sara::interpolate(image_plane, p);
      color /= 255;

      auto color_converted = sara::Rgb8{};
      sara::smart_convert_color(color, color_converted);

      map_view(u, v) = color_converted;
    }
  }

  return map_view;
}

auto difference(const sara::ImageView<sara::Rgb8>& a1,
                const sara::ImageView<sara::Rgb8>& a2,
                sara::ImageView<float>& diff) -> void
{
  for (auto y = 0; y < a1.height(); ++y)
    for (auto x = 0; x < a2.width(); ++x)
      diff(x, y) = (a1(x, y).cast<float>() - a2(x, y).cast<float>()).norm();

  const auto max_val = diff.flat_array().maxCoeff();
  const auto min_val = diff.flat_array().minCoeff();
  diff.flat_array() = (diff.flat_array() - min_val) / (max_val - min_val);
}

auto average(const sara::ImageView<sara::Rgb8>& a1,
             const sara::ImageView<sara::Rgb8>& a2,
             sara::ImageView<sara::Rgb8>& average) -> void
{
  for (auto y = 0; y < a1.height(); ++y)
  {
    for (auto x = 0; x < a1.width(); ++x)
    {
      const auto c1 = a1(x, y);
      if (c1 == sara::Black8)
      {
        average(x, y) = c1;
        continue;
      }

      const auto c2 = a2(x, y);
      const Eigen::Vector3i c = (0.5f *  //
                                 (c1.cast<float>() + c2.cast<float>()))
                                    .cast<int>();
      average(x, y)(0) = c(0);
      average(x, y)(1) = c(1);
      average(x, y)(2) = c(2);
    }
  }
}

int __main(int argc, char**argv)
{
  if (argc < 2)
    return -1;
  const auto video_filepath = argv[1];

  omp_set_num_threads(omp_get_max_threads());

  auto video_stream = sara::VideoStream{video_filepath};
  auto video_writer = sara::VideoWriter{
#ifdef __APPLE__
      "/Users/david/Desktop/test.mp4",
#else
      "/home/david/Desktop/test.mp4",
#endif
      Eigen::Vector2i(map_pixel_dims[0].value, map_pixel_dims[1].value)};

  // one example of distortion correction.
  auto camera_parameters = sara::BrownConradyCamera<float>{};
  {
    const auto f = 946.8984425572634_px;
    const auto u0 = 960._px;
    const auto v0 = 540._px;
    const auto p = Eigen::Vector2f{0, 0};
    const auto k = Eigen::Vector3f{
        -0.22996356451342749,  //
        0.05952465745165465,
        -0.007399008111054717  //
    };
    camera_parameters.K << f, 0, u0,
                           0, f, v0,
                           0, 0,  1;
    camera_parameters.k = k;
    camera_parameters.p = p;
  }
  // // one example of distortion correction.
  // auto camera_parameters = sara::BrownConradyCamera<float>{};
  // {
  //   const auto f = 650._px;
  //   const auto u0 = 640._px;
  //   const auto v0 = 360._px;
  //   camera_parameters.K << f, 0, u0,
  //                          0, f, v0,
  //                          0, 0,  1;
  //   camera_parameters.k.setZero();
  //   camera_parameters.p.setZero();
  // }
  camera_parameters.calculate_K_inverse();
  camera_parameters.calculate_drap_lefevre_inverse_coefficients();

  auto frame_undistorted = sara::Image<sara::Rgb8>{video_stream.sizes()};
  auto frame_redistorted = sara::Image<sara::Rgb8>{video_stream.sizes()};
  auto frame_diff = sara::Image<float>{video_stream.sizes()};
  auto frame_average = sara::Image<sara::Rgb8>{video_stream.sizes()};

  auto wu = sara::create_window(video_stream.frame().sizes(),  //
                                "Undistorted Frame");
  auto wd = sara::create_window(video_stream.frame().sizes(),  //
                                "Redistorted Frame");
  auto wdiff = sara::create_window(video_stream.frame().sizes(),  //
                                   "Absolute frame diff");
  auto wavg = sara::create_window(video_stream.frame().sizes(),  //
                                  "Absolute frame average");
  auto wmap = sara::create_window(                          //
      map_pixel_dims[0].value,                              //
      map_pixel_dims[1].value,                              //
      sara::format("Bird's Eye View [Scale: %d px = 1 m]",  //
                   int(px_per_meter.value)));

  while (video_stream.read())
  {
#ifdef DIRTY
    frame_undistorted = video_stream.frame();
    auto map_view = to_map_view(camera_parameters, video_stream.frame());
#else
    camera_parameters.undistort(video_stream.frame(), frame_undistorted);
    camera_parameters.distort_drap_lefevre(frame_undistorted, frame_redistorted);
    auto map_view = to_map_view(camera_parameters, frame_undistorted);

    difference(frame_redistorted, video_stream.frame(), frame_diff);
    average(frame_redistorted, video_stream.frame(), frame_average);
#endif

    sara::set_active_window(wu);
    sara::display(frame_undistorted);

    sara::set_active_window(wd);
    sara::display(frame_redistorted);

    sara::set_active_window(wdiff);
    sara::display(frame_diff);

    sara::set_active_window(wavg);
    sara::display(frame_average);

    sara::set_active_window(wmap);
    constexpr auto interval = 20;
    for (auto i = 0; i < 5; ++i)
    {
      const auto p1 = Eigen::Vector2i(0, i * interval * px_per_meter.value);
      const auto p2 =
          Eigen::Vector2i(map_view.width(), i * interval * px_per_meter.value);
      sara::draw_line(map_view, p1.x(), p1.y(), p2.x(), p2.y(), sara::Yellow8,
                      2);
    }
    sara::display(map_view);

    video_writer.write(map_view);
  }

  sara::close_window(wu);
  sara::close_window(wd);
  sara::close_window(wdiff);
  sara::close_window(wavg);
  sara::close_window(wmap);

  return 0;
}

int main(int argc, char** argv)
{
  DO::Sara::GraphicsApplication app(argc, argv);
  app.register_user_main(__main);
  return app.exec();
}
<|endoftext|>


<commit_before>
void test1()
{
	int v = 10; // assignment to `v`
	int *ptr_v = &v; // assignment to `ptr_v`
	int &ref_v = v; // assignment to `ref_v`

	v = 11; // assignment to `v`
	*ptr_v = 12;
	ref_v = 13; // assignment to `ref_v`
	v = v + 1; // assignment to `v`
	v += 1;
	v++;
}

class myClass1
{
public:
	myClass1(float _x, float _y = 0.0f) : x(_x), y(_y), z(0.0f) { // assignments to `_y`, `x`, `y`, `z`
		// ...
	}

private:
	float x, y, z;
};

// ---

struct myStruct1
{
	int num;
	const char *str;
};

myStruct1 v1 = {1, "One"}; // assigments to `v1`, `num`, `str`
myStruct1 v2 = {.num = 2, .str = "Two"}; // assigments to `v2`, `num`, `str`

void test2(myStruct1 v = {3, "Three"}) // assignments to `v` (literal `{...}` has no location), `num`, `str`
{
	// ...
}

struct myStruct2
{
	myStruct1 ms2;
};

myStruct2 v3 = {{4, "Four"}}; // assigments to `v3`, `ms2`, `num`, `str`

// ---

int myArray[10] = {1, 2, 3}; // assigment to `myArray`
char chars1[] = "abc"; // assignment to `chars1` (literal "abc" has no location)
char chars2[] = {'a', 'b', 'c'}; // assigment to `chars2`
char *chars3 = "abc"; // assigment to `chars3`
<commit_msg>C++: Remove outdated comment<commit_after>
void test1()
{
	int v = 10; // assignment to `v`
	int *ptr_v = &v; // assignment to `ptr_v`
	int &ref_v = v; // assignment to `ref_v`

	v = 11; // assignment to `v`
	*ptr_v = 12;
	ref_v = 13; // assignment to `ref_v`
	v = v + 1; // assignment to `v`
	v += 1;
	v++;
}

class myClass1
{
public:
	myClass1(float _x, float _y = 0.0f) : x(_x), y(_y), z(0.0f) { // assignments to `_y`, `x`, `y`, `z`
		// ...
	}

private:
	float x, y, z;
};

// ---

struct myStruct1
{
	int num;
	const char *str;
};

myStruct1 v1 = {1, "One"}; // assigments to `v1`, `num`, `str`
myStruct1 v2 = {.num = 2, .str = "Two"}; // assigments to `v2`, `num`, `str`

void test2(myStruct1 v = {3, "Three"}) // assignments to `v` (literal `{...}` has no location), `num`, `str`
{
	// ...
}

struct myStruct2
{
	myStruct1 ms2;
};

myStruct2 v3 = {{4, "Four"}}; // assigments to `v3`, `ms2`, `num`, `str`

// ---

int myArray[10] = {1, 2, 3}; // assigment to `myArray`
char chars1[] = "abc"; // assignment to `chars1`
char chars2[] = {'a', 'b', 'c'}; // assigment to `chars2`
char *chars3 = "abc"; // assigment to `chars3`
<|endoftext|>


<commit_before><commit_msg>cppcheck: reduce scope<commit_after><|endoftext|>