<commit_before>/*
 * Copyright 2016 The Cartographer Authors
 *
 * 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 "cartographer/mapping_3d/pose_graph/constraint_builder.h"

#include <cmath>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <memory>
#include <sstream>
#include <string>

#include "Eigen/Eigenvalues"
#include "cartographer/common/make_unique.h"
#include "cartographer/common/math.h"
#include "cartographer/common/thread_pool.h"
#include "cartographer/mapping_3d/scan_matching/proto/ceres_scan_matcher_options.pb.h"
#include "cartographer/mapping_3d/scan_matching/proto/fast_correlative_scan_matcher_options.pb.h"
#include "cartographer/transform/transform.h"
#include "glog/logging.h"

namespace cartographer {
namespace mapping_3d {
namespace pose_graph {

ConstraintBuilder::ConstraintBuilder(
    const mapping::pose_graph::proto::ConstraintBuilderOptions& options,
    common::ThreadPool* const thread_pool)
    : options_(options),
      thread_pool_(thread_pool),
      sampler_(options.sampling_ratio()),
      ceres_scan_matcher_(options.ceres_scan_matcher_options_3d()) {}

ConstraintBuilder::~ConstraintBuilder() {
  common::MutexLocker locker(&mutex_);
  CHECK_EQ(constraints_.size(), 0) << "WhenDone() was not called";
  CHECK_EQ(pending_computations_.size(), 0);
  CHECK_EQ(submap_queued_work_items_.size(), 0);
  CHECK(when_done_ == nullptr);
}

void ConstraintBuilder::MaybeAddConstraint(
    const mapping::SubmapId& submap_id, const Submap* const submap,
    const mapping::NodeId& node_id,
    const mapping::TrajectoryNode::Data* const constant_data,
    const std::vector<mapping::TrajectoryNode>& submap_nodes,
    const transform::Rigid3d& global_node_pose,
    const transform::Rigid3d& global_submap_pose) {
  if ((global_node_pose.translation() - global_submap_pose.translation())
          .norm() > options_.max_constraint_distance()) {
    return;
  }
  if (sampler_.Pulse()) {
    common::MutexLocker locker(&mutex_);
    constraints_.emplace_back();
    auto* const constraint = &constraints_.back();
    ++pending_computations_[current_computation_];
    const int current_computation = current_computation_;
    ScheduleSubmapScanMatcherConstructionAndQueueWorkItem(
        submap_id, submap_nodes, submap, [=]() EXCLUDES(mutex_) {
          ComputeConstraint(submap_id, node_id, false, /* match_full_submap */
                            constant_data, global_node_pose, global_submap_pose,
                            constraint);
          FinishComputation(current_computation);
        });
  }
}

void ConstraintBuilder::MaybeAddGlobalConstraint(
    const mapping::SubmapId& submap_id, const Submap* const submap,
    const mapping::NodeId& node_id,
    const mapping::TrajectoryNode::Data* const constant_data,
    const std::vector<mapping::TrajectoryNode>& submap_nodes,
    const Eigen::Quaterniond& global_node_rotation,
    const Eigen::Quaterniond& global_submap_rotation) {
  common::MutexLocker locker(&mutex_);
  constraints_.emplace_back();
  auto* const constraint = &constraints_.back();
  ++pending_computations_[current_computation_];
  const int current_computation = current_computation_;
  ScheduleSubmapScanMatcherConstructionAndQueueWorkItem(
      submap_id, submap_nodes, submap, [=]() EXCLUDES(mutex_) {
        ComputeConstraint(
            submap_id, node_id, true, /* match_full_submap */
            constant_data, transform::Rigid3d::Rotation(global_node_rotation),
            transform::Rigid3d::Rotation(global_submap_rotation), constraint);
        FinishComputation(current_computation);
      });
}

void ConstraintBuilder::NotifyEndOfNode() {
  common::MutexLocker locker(&mutex_);
  ++current_computation_;
}

void ConstraintBuilder::WhenDone(
    const std::function<void(const ConstraintBuilder::Result&)>& callback) {
  common::MutexLocker locker(&mutex_);
  CHECK(when_done_ == nullptr);
  when_done_ =
      common::make_unique<std::function<void(const Result&)>>(callback);
  ++pending_computations_[current_computation_];
  const int current_computation = current_computation_;
  thread_pool_->Schedule(
      [this, current_computation] { FinishComputation(current_computation); });
}

void ConstraintBuilder::ScheduleSubmapScanMatcherConstructionAndQueueWorkItem(
    const mapping::SubmapId& submap_id,
    const std::vector<mapping::TrajectoryNode>& submap_nodes,
    const Submap* const submap, const std::function<void()>& work_item) {
  if (submap_scan_matchers_[submap_id].fast_correlative_scan_matcher !=
      nullptr) {
    thread_pool_->Schedule(work_item);
  } else {
    submap_queued_work_items_[submap_id].push_back(work_item);
    if (submap_queued_work_items_[submap_id].size() == 1) {
      thread_pool_->Schedule([=]() {
        ConstructSubmapScanMatcher(submap_id, submap_nodes, submap);
      });
    }
  }
}

void ConstraintBuilder::ConstructSubmapScanMatcher(
    const mapping::SubmapId& submap_id,
    const std::vector<mapping::TrajectoryNode>& submap_nodes,
    const Submap* const submap) {
  auto submap_scan_matcher =
      common::make_unique<scan_matching::FastCorrelativeScanMatcher>(
          submap->high_resolution_hybrid_grid(),
          &submap->low_resolution_hybrid_grid(), submap_nodes,
          options_.fast_correlative_scan_matcher_options_3d());
  common::MutexLocker locker(&mutex_);
  submap_scan_matchers_[submap_id] = {&submap->high_resolution_hybrid_grid(),
                                      &submap->low_resolution_hybrid_grid(),
                                      std::move(submap_scan_matcher)};
  for (const std::function<void()>& work_item :
       submap_queued_work_items_[submap_id]) {
    thread_pool_->Schedule(work_item);
  }
  submap_queued_work_items_.erase(submap_id);
}

const ConstraintBuilder::SubmapScanMatcher*
ConstraintBuilder::GetSubmapScanMatcher(const mapping::SubmapId& submap_id) {
  common::MutexLocker locker(&mutex_);
  const SubmapScanMatcher* submap_scan_matcher =
      &submap_scan_matchers_[submap_id];
  CHECK(submap_scan_matcher->fast_correlative_scan_matcher != nullptr);
  return submap_scan_matcher;
}

void ConstraintBuilder::ComputeConstraint(
    const mapping::SubmapId& submap_id, const mapping::NodeId& node_id,
    bool match_full_submap,
    const mapping::TrajectoryNode::Data* const constant_data,
    const transform::Rigid3d& global_node_pose,
    const transform::Rigid3d& global_submap_pose,
    std::unique_ptr<OptimizationProblem::Constraint>* constraint) {
  const SubmapScanMatcher* const submap_scan_matcher =
      GetSubmapScanMatcher(submap_id);

  // The 'constraint_transform' (submap i <- node j) is computed from:
  // - a 'high_resolution_point_cloud' in node j and
  // - the initial guess 'initial_pose' (submap i <- node j).
  std::unique_ptr<scan_matching::FastCorrelativeScanMatcher::Result>
      match_result;

  // Compute 'pose_estimate' in three stages:
  // 1. Fast estimate using the fast correlative scan matcher.
  // 2. Prune if the score is too low.
  // 3. Refine.
  if (match_full_submap) {
    match_result =
        submap_scan_matcher->fast_correlative_scan_matcher->MatchFullSubmap(
            global_node_pose.rotation(), global_submap_pose.rotation(),
            *constant_data, options_.global_localization_min_score());
    if (match_result != nullptr) {
      CHECK_GT(match_result->score, options_.global_localization_min_score());
      CHECK_GE(node_id.trajectory_id, 0);
      CHECK_GE(submap_id.trajectory_id, 0);
    } else {
      return;
    }
  } else {
    match_result = submap_scan_matcher->fast_correlative_scan_matcher->Match(
        global_node_pose, global_submap_pose, *constant_data,
        options_.min_score());
    if (match_result != nullptr) {
      // We've reported a successful local match.
      CHECK_GT(match_result->score, options_.min_score());
    } else {
      return;
    }
  }
  {
    common::MutexLocker locker(&mutex_);
    score_histogram_.Add(match_result->score);
    rotational_score_histogram_.Add(match_result->rotational_score);
    low_resolution_score_histogram_.Add(match_result->low_resolution_score);
  }

  // Use the CSM estimate as both the initial and previous pose. This has the
  // effect that, in the absence of better information, we prefer the original
  // CSM estimate.
  ceres::Solver::Summary unused_summary;
  transform::Rigid3d constraint_transform;
  ceres_scan_matcher_.Match(match_result->pose_estimate.translation(),
                            match_result->pose_estimate,
                            {{&constant_data->high_resolution_point_cloud,
                              submap_scan_matcher->high_resolution_hybrid_grid},
                             {&constant_data->low_resolution_point_cloud,
                              submap_scan_matcher->low_resolution_hybrid_grid}},
                            &constraint_transform, &unused_summary);

  constraint->reset(new OptimizationProblem::Constraint{
      submap_id,
      node_id,
      {constraint_transform, options_.loop_closure_translation_weight(),
       options_.loop_closure_rotation_weight()},
      OptimizationProblem::Constraint::INTER_SUBMAP});

  if (options_.log_matches()) {
    std::ostringstream info;
    info << "Node " << node_id << " with "
         << constant_data->high_resolution_point_cloud.size()
         << " points on submap " << submap_id << std::fixed;
    if (match_full_submap) {
      info << " matches";
    } else {
      const transform::Rigid3d difference = global_submap_pose.inverse() *
                                            global_node_pose *
                                            constraint_transform;
      info << " differs by translation " << std::setprecision(2)
           << difference.translation().norm() << " rotation "
           << std::setprecision(3) << transform::GetAngle(difference);
    }
    info << " with score " << std::setprecision(1) << 100. * match_result->score
         << "%.";
    LOG(INFO) << info.str();
  }
}

void ConstraintBuilder::FinishComputation(const int computation_index) {
  Result result;
  std::unique_ptr<std::function<void(const Result&)>> callback;
  {
    common::MutexLocker locker(&mutex_);
    if (--pending_computations_[computation_index] == 0) {
      pending_computations_.erase(computation_index);
    }
    if (pending_computations_.empty()) {
      CHECK_EQ(submap_queued_work_items_.size(), 0);
      if (when_done_ != nullptr) {
        for (const std::unique_ptr<OptimizationProblem::Constraint>&
                 constraint : constraints_) {
          if (constraint != nullptr) {
            result.push_back(*constraint);
          }
        }
        if (options_.log_matches()) {
          LOG(INFO) << constraints_.size() << " computations resulted in "
                    << result.size() << " additional constraints.";
          LOG(INFO) << "Score histogram:\n" << score_histogram_.ToString(10);
          LOG(INFO) << "Rotational score histogram:\n"
                    << rotational_score_histogram_.ToString(10);
          LOG(INFO) << "Low resolution score histogram:\n"
                    << low_resolution_score_histogram_.ToString(10);
        }
        constraints_.clear();
        callback = std::move(when_done_);
        when_done_.reset();
      }
    }
  }
  if (callback != nullptr) {
    (*callback)(result);
  }
}

int ConstraintBuilder::GetNumFinishedNodes() {
  common::MutexLocker locker(&mutex_);
  if (pending_computations_.empty()) {
    return current_computation_;
  }
  return pending_computations_.begin()->first;
}

void ConstraintBuilder::DeleteScanMatcher(const mapping::SubmapId& submap_id) {
  common::MutexLocker locker(&mutex_);
  CHECK(pending_computations_.empty());
  submap_scan_matchers_.erase(submap_id);
}

}  // namespace pose_graph
}  // namespace mapping_3d
}  // namespace cartographer
<commit_msg>Fix debug output for 3D loop closure error. (#826)<commit_after>/*
 * Copyright 2016 The Cartographer Authors
 *
 * 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 "cartographer/mapping_3d/pose_graph/constraint_builder.h"

#include <cmath>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <memory>
#include <sstream>
#include <string>

#include "Eigen/Eigenvalues"
#include "cartographer/common/make_unique.h"
#include "cartographer/common/math.h"
#include "cartographer/common/thread_pool.h"
#include "cartographer/mapping_3d/scan_matching/proto/ceres_scan_matcher_options.pb.h"
#include "cartographer/mapping_3d/scan_matching/proto/fast_correlative_scan_matcher_options.pb.h"
#include "cartographer/transform/transform.h"
#include "glog/logging.h"

namespace cartographer {
namespace mapping_3d {
namespace pose_graph {

ConstraintBuilder::ConstraintBuilder(
    const mapping::pose_graph::proto::ConstraintBuilderOptions& options,
    common::ThreadPool* const thread_pool)
    : options_(options),
      thread_pool_(thread_pool),
      sampler_(options.sampling_ratio()),
      ceres_scan_matcher_(options.ceres_scan_matcher_options_3d()) {}

ConstraintBuilder::~ConstraintBuilder() {
  common::MutexLocker locker(&mutex_);
  CHECK_EQ(constraints_.size(), 0) << "WhenDone() was not called";
  CHECK_EQ(pending_computations_.size(), 0);
  CHECK_EQ(submap_queued_work_items_.size(), 0);
  CHECK(when_done_ == nullptr);
}

void ConstraintBuilder::MaybeAddConstraint(
    const mapping::SubmapId& submap_id, const Submap* const submap,
    const mapping::NodeId& node_id,
    const mapping::TrajectoryNode::Data* const constant_data,
    const std::vector<mapping::TrajectoryNode>& submap_nodes,
    const transform::Rigid3d& global_node_pose,
    const transform::Rigid3d& global_submap_pose) {
  if ((global_node_pose.translation() - global_submap_pose.translation())
          .norm() > options_.max_constraint_distance()) {
    return;
  }
  if (sampler_.Pulse()) {
    common::MutexLocker locker(&mutex_);
    constraints_.emplace_back();
    auto* const constraint = &constraints_.back();
    ++pending_computations_[current_computation_];
    const int current_computation = current_computation_;
    ScheduleSubmapScanMatcherConstructionAndQueueWorkItem(
        submap_id, submap_nodes, submap, [=]() EXCLUDES(mutex_) {
          ComputeConstraint(submap_id, node_id, false, /* match_full_submap */
                            constant_data, global_node_pose, global_submap_pose,
                            constraint);
          FinishComputation(current_computation);
        });
  }
}

void ConstraintBuilder::MaybeAddGlobalConstraint(
    const mapping::SubmapId& submap_id, const Submap* const submap,
    const mapping::NodeId& node_id,
    const mapping::TrajectoryNode::Data* const constant_data,
    const std::vector<mapping::TrajectoryNode>& submap_nodes,
    const Eigen::Quaterniond& global_node_rotation,
    const Eigen::Quaterniond& global_submap_rotation) {
  common::MutexLocker locker(&mutex_);
  constraints_.emplace_back();
  auto* const constraint = &constraints_.back();
  ++pending_computations_[current_computation_];
  const int current_computation = current_computation_;
  ScheduleSubmapScanMatcherConstructionAndQueueWorkItem(
      submap_id, submap_nodes, submap, [=]() EXCLUDES(mutex_) {
        ComputeConstraint(
            submap_id, node_id, true, /* match_full_submap */
            constant_data, transform::Rigid3d::Rotation(global_node_rotation),
            transform::Rigid3d::Rotation(global_submap_rotation), constraint);
        FinishComputation(current_computation);
      });
}

void ConstraintBuilder::NotifyEndOfNode() {
  common::MutexLocker locker(&mutex_);
  ++current_computation_;
}

void ConstraintBuilder::WhenDone(
    const std::function<void(const ConstraintBuilder::Result&)>& callback) {
  common::MutexLocker locker(&mutex_);
  CHECK(when_done_ == nullptr);
  when_done_ =
      common::make_unique<std::function<void(const Result&)>>(callback);
  ++pending_computations_[current_computation_];
  const int current_computation = current_computation_;
  thread_pool_->Schedule(
      [this, current_computation] { FinishComputation(current_computation); });
}

void ConstraintBuilder::ScheduleSubmapScanMatcherConstructionAndQueueWorkItem(
    const mapping::SubmapId& submap_id,
    const std::vector<mapping::TrajectoryNode>& submap_nodes,
    const Submap* const submap, const std::function<void()>& work_item) {
  if (submap_scan_matchers_[submap_id].fast_correlative_scan_matcher !=
      nullptr) {
    thread_pool_->Schedule(work_item);
  } else {
    submap_queued_work_items_[submap_id].push_back(work_item);
    if (submap_queued_work_items_[submap_id].size() == 1) {
      thread_pool_->Schedule([=]() {
        ConstructSubmapScanMatcher(submap_id, submap_nodes, submap);
      });
    }
  }
}

void ConstraintBuilder::ConstructSubmapScanMatcher(
    const mapping::SubmapId& submap_id,
    const std::vector<mapping::TrajectoryNode>& submap_nodes,
    const Submap* const submap) {
  auto submap_scan_matcher =
      common::make_unique<scan_matching::FastCorrelativeScanMatcher>(
          submap->high_resolution_hybrid_grid(),
          &submap->low_resolution_hybrid_grid(), submap_nodes,
          options_.fast_correlative_scan_matcher_options_3d());
  common::MutexLocker locker(&mutex_);
  submap_scan_matchers_[submap_id] = {&submap->high_resolution_hybrid_grid(),
                                      &submap->low_resolution_hybrid_grid(),
                                      std::move(submap_scan_matcher)};
  for (const std::function<void()>& work_item :
       submap_queued_work_items_[submap_id]) {
    thread_pool_->Schedule(work_item);
  }
  submap_queued_work_items_.erase(submap_id);
}

const ConstraintBuilder::SubmapScanMatcher*
ConstraintBuilder::GetSubmapScanMatcher(const mapping::SubmapId& submap_id) {
  common::MutexLocker locker(&mutex_);
  const SubmapScanMatcher* submap_scan_matcher =
      &submap_scan_matchers_[submap_id];
  CHECK(submap_scan_matcher->fast_correlative_scan_matcher != nullptr);
  return submap_scan_matcher;
}

void ConstraintBuilder::ComputeConstraint(
    const mapping::SubmapId& submap_id, const mapping::NodeId& node_id,
    bool match_full_submap,
    const mapping::TrajectoryNode::Data* const constant_data,
    const transform::Rigid3d& global_node_pose,
    const transform::Rigid3d& global_submap_pose,
    std::unique_ptr<OptimizationProblem::Constraint>* constraint) {
  const SubmapScanMatcher* const submap_scan_matcher =
      GetSubmapScanMatcher(submap_id);

  // The 'constraint_transform' (submap i <- node j) is computed from:
  // - a 'high_resolution_point_cloud' in node j and
  // - the initial guess 'initial_pose' (submap i <- node j).
  std::unique_ptr<scan_matching::FastCorrelativeScanMatcher::Result>
      match_result;

  // Compute 'pose_estimate' in three stages:
  // 1. Fast estimate using the fast correlative scan matcher.
  // 2. Prune if the score is too low.
  // 3. Refine.
  if (match_full_submap) {
    match_result =
        submap_scan_matcher->fast_correlative_scan_matcher->MatchFullSubmap(
            global_node_pose.rotation(), global_submap_pose.rotation(),
            *constant_data, options_.global_localization_min_score());
    if (match_result != nullptr) {
      CHECK_GT(match_result->score, options_.global_localization_min_score());
      CHECK_GE(node_id.trajectory_id, 0);
      CHECK_GE(submap_id.trajectory_id, 0);
    } else {
      return;
    }
  } else {
    match_result = submap_scan_matcher->fast_correlative_scan_matcher->Match(
        global_node_pose, global_submap_pose, *constant_data,
        options_.min_score());
    if (match_result != nullptr) {
      // We've reported a successful local match.
      CHECK_GT(match_result->score, options_.min_score());
    } else {
      return;
    }
  }
  {
    common::MutexLocker locker(&mutex_);
    score_histogram_.Add(match_result->score);
    rotational_score_histogram_.Add(match_result->rotational_score);
    low_resolution_score_histogram_.Add(match_result->low_resolution_score);
  }

  // Use the CSM estimate as both the initial and previous pose. This has the
  // effect that, in the absence of better information, we prefer the original
  // CSM estimate.
  ceres::Solver::Summary unused_summary;
  transform::Rigid3d constraint_transform;
  ceres_scan_matcher_.Match(match_result->pose_estimate.translation(),
                            match_result->pose_estimate,
                            {{&constant_data->high_resolution_point_cloud,
                              submap_scan_matcher->high_resolution_hybrid_grid},
                             {&constant_data->low_resolution_point_cloud,
                              submap_scan_matcher->low_resolution_hybrid_grid}},
                            &constraint_transform, &unused_summary);

  constraint->reset(new OptimizationProblem::Constraint{
      submap_id,
      node_id,
      {constraint_transform, options_.loop_closure_translation_weight(),
       options_.loop_closure_rotation_weight()},
      OptimizationProblem::Constraint::INTER_SUBMAP});

  if (options_.log_matches()) {
    std::ostringstream info;
    info << "Node " << node_id << " with "
         << constant_data->high_resolution_point_cloud.size()
         << " points on submap " << submap_id << std::fixed;
    if (match_full_submap) {
      info << " matches";
    } else {
      // Compute the difference between (submap i <- node j) according to loop
      // closure ('constraint_transform') and according to global SLAM state.
      const transform::Rigid3d difference = global_node_pose.inverse() *
                                            global_submap_pose *
                                            constraint_transform;
      info << " differs by translation " << std::setprecision(2)
           << difference.translation().norm() << " rotation "
           << std::setprecision(3) << transform::GetAngle(difference);
    }
    info << " with score " << std::setprecision(1) << 100. * match_result->score
         << "%.";
    LOG(INFO) << info.str();
  }
}

void ConstraintBuilder::FinishComputation(const int computation_index) {
  Result result;
  std::unique_ptr<std::function<void(const Result&)>> callback;
  {
    common::MutexLocker locker(&mutex_);
    if (--pending_computations_[computation_index] == 0) {
      pending_computations_.erase(computation_index);
    }
    if (pending_computations_.empty()) {
      CHECK_EQ(submap_queued_work_items_.size(), 0);
      if (when_done_ != nullptr) {
        for (const std::unique_ptr<OptimizationProblem::Constraint>&
                 constraint : constraints_) {
          if (constraint != nullptr) {
            result.push_back(*constraint);
          }
        }
        if (options_.log_matches()) {
          LOG(INFO) << constraints_.size() << " computations resulted in "
                    << result.size() << " additional constraints.";
          LOG(INFO) << "Score histogram:\n" << score_histogram_.ToString(10);
          LOG(INFO) << "Rotational score histogram:\n"
                    << rotational_score_histogram_.ToString(10);
          LOG(INFO) << "Low resolution score histogram:\n"
                    << low_resolution_score_histogram_.ToString(10);
        }
        constraints_.clear();
        callback = std::move(when_done_);
        when_done_.reset();
      }
    }
  }
  if (callback != nullptr) {
    (*callback)(result);
  }
}

int ConstraintBuilder::GetNumFinishedNodes() {
  common::MutexLocker locker(&mutex_);
  if (pending_computations_.empty()) {
    return current_computation_;
  }
  return pending_computations_.begin()->first;
}

void ConstraintBuilder::DeleteScanMatcher(const mapping::SubmapId& submap_id) {
  common::MutexLocker locker(&mutex_);
  CHECK(pending_computations_.empty());
  submap_scan_matchers_.erase(submap_id);
}

}  // namespace pose_graph
}  // namespace mapping_3d
}  // namespace cartographer
<|endoftext|>


<commit_before>// Copyright (c) 2006-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/renderer_host/resource_message_filter.h"

#include "base/gfx/gtk_native_view_id_manager.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/x11_util.h"

#include "third_party/WebKit/WebKit/chromium/public/WebScreenInfo.h"
#include "third_party/WebKit/WebKit/chromium/public/x11/WebScreenInfoFactory.h"

using WebKit::WebScreenInfo;
using WebKit::WebScreenInfoFactory;

// We get null window_ids passed into the two functions below; please see
// http://crbug.com/9060 for more details.

// Called on the IO thread.
void ResourceMessageFilter::SendBackgroundX11Reply(IPC::Message* reply_msg) {
  Send(reply_msg);
}

// Called on the BACKGROUND_X11 thread.
void ResourceMessageFilter::DoOnGetScreenInfo(gfx::NativeViewId view,
                                              IPC::Message* reply_msg) {
  Display* display = x11_util::GetSecondaryDisplay();
  int screen = x11_util::GetDefaultScreen(display);
  WebScreenInfo results = WebScreenInfoFactory::screenInfo(display, screen);
  ViewHostMsg_GetScreenInfo::WriteReplyParams(reply_msg, results);

  ChromeThread::GetMessageLoop(ChromeThread::IO)->PostTask(
      FROM_HERE, NewRunnableMethod(
        this, &ResourceMessageFilter::SendBackgroundX11Reply, reply_msg));
}

// Called on the BACKGROUND_X11 thread.
void ResourceMessageFilter::DoOnGetWindowRect(gfx::NativeViewId view,
                                              IPC::Message* reply_msg) {
  // This is called to get the x, y offset (in screen coordinates) of the given
  // view and its width and height.
  gfx::Rect rect;
  XID window;

  if (Singleton<GtkNativeViewManager>()->GetXIDForId(&window, view)) {
    if (window) {
      int x, y;
      unsigned width, height;
      if (x11_util::GetWindowGeometry(&x, &y, &width, &height, window))
        rect = gfx::Rect(x, y, width, height);
    }
  }

  ViewHostMsg_GetWindowRect::WriteReplyParams(reply_msg, rect);

  ChromeThread::GetMessageLoop(ChromeThread::IO)->PostTask(
      FROM_HERE, NewRunnableMethod(
        this, &ResourceMessageFilter::SendBackgroundX11Reply, reply_msg));
}

// Return the top-level parent of the given window. Called on the
// BACKGROUND_X11 thread.
static XID GetTopLevelWindow(XID window) {
  bool parent_is_root;
  XID parent_window;

  if (!x11_util::GetWindowParent(&parent_window, &parent_is_root, window))
    return 0;
  if (parent_is_root)
    return window;

  return GetTopLevelWindow(parent_window);
}

// Called on the BACKGROUND_X11 thread.
void ResourceMessageFilter::DoOnGetRootWindowRect(gfx::NativeViewId view,
                                                  IPC::Message* reply_msg) {
  // This is called to get the screen coordinates and size of the browser
  // window itself.
  gfx::Rect rect;
  XID window;

  if (Singleton<GtkNativeViewManager>()->GetXIDForId(&window, view)) {
    if (window) {
      const XID toplevel = GetTopLevelWindow(toplevel);
      int x, y;
      unsigned width, height;
      if (x11_util::GetWindowGeometry(&x, &y, &width, &height, window))
        rect = gfx::Rect(x, y, width, height);
    }
  }

  ViewHostMsg_GetRootWindowRect::WriteReplyParams(reply_msg, rect);

  ChromeThread::GetMessageLoop(ChromeThread::IO)->PostTask(
      FROM_HERE, NewRunnableMethod(
        this, &ResourceMessageFilter::SendBackgroundX11Reply, reply_msg));
}

// Called on the IO thread.
void ResourceMessageFilter::OnGetScreenInfo(gfx::NativeViewId view,
                                            IPC::Message* reply_msg) {
  ChromeThread::GetMessageLoop(ChromeThread::BACKGROUND_X11)->PostTask(
      FROM_HERE, NewRunnableMethod(
        this, &ResourceMessageFilter::DoOnGetScreenInfo, view, reply_msg));
}

// Called on the IO thread.
void ResourceMessageFilter::OnGetWindowRect(gfx::NativeViewId view,
                                            IPC::Message* reply_msg) {
  ChromeThread::GetMessageLoop(ChromeThread::BACKGROUND_X11)->PostTask(
      FROM_HERE, NewRunnableMethod(
        this, &ResourceMessageFilter::DoOnGetWindowRect, view, reply_msg));
}

// Called on the IO thread.
void ResourceMessageFilter::OnGetRootWindowRect(gfx::NativeViewId view,
                                                IPC::Message* reply_msg) {
  ChromeThread::GetMessageLoop(ChromeThread::BACKGROUND_X11)->PostTask(
      FROM_HERE, NewRunnableMethod(
        this, &ResourceMessageFilter::DoOnGetRootWindowRect, view, reply_msg));
}
<commit_msg>Linux: fix root window co-ordinates.<commit_after>// Copyright (c) 2006-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/renderer_host/resource_message_filter.h"

#include "base/gfx/gtk_native_view_id_manager.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/x11_util.h"

#include "third_party/WebKit/WebKit/chromium/public/WebScreenInfo.h"
#include "third_party/WebKit/WebKit/chromium/public/x11/WebScreenInfoFactory.h"

using WebKit::WebScreenInfo;
using WebKit::WebScreenInfoFactory;

// We get null window_ids passed into the two functions below; please see
// http://crbug.com/9060 for more details.

// Called on the IO thread.
void ResourceMessageFilter::SendBackgroundX11Reply(IPC::Message* reply_msg) {
  Send(reply_msg);
}

// Called on the BACKGROUND_X11 thread.
void ResourceMessageFilter::DoOnGetScreenInfo(gfx::NativeViewId view,
                                              IPC::Message* reply_msg) {
  Display* display = x11_util::GetSecondaryDisplay();
  int screen = x11_util::GetDefaultScreen(display);
  WebScreenInfo results = WebScreenInfoFactory::screenInfo(display, screen);
  ViewHostMsg_GetScreenInfo::WriteReplyParams(reply_msg, results);

  ChromeThread::GetMessageLoop(ChromeThread::IO)->PostTask(
      FROM_HERE, NewRunnableMethod(
        this, &ResourceMessageFilter::SendBackgroundX11Reply, reply_msg));
}

// Called on the BACKGROUND_X11 thread.
void ResourceMessageFilter::DoOnGetWindowRect(gfx::NativeViewId view,
                                              IPC::Message* reply_msg) {
  // This is called to get the x, y offset (in screen coordinates) of the given
  // view and its width and height.
  gfx::Rect rect;
  XID window;

  if (Singleton<GtkNativeViewManager>()->GetXIDForId(&window, view)) {
    if (window) {
      int x, y;
      unsigned width, height;
      if (x11_util::GetWindowGeometry(&x, &y, &width, &height, window))
        rect = gfx::Rect(x, y, width, height);
    }
  }

  ViewHostMsg_GetWindowRect::WriteReplyParams(reply_msg, rect);

  ChromeThread::GetMessageLoop(ChromeThread::IO)->PostTask(
      FROM_HERE, NewRunnableMethod(
        this, &ResourceMessageFilter::SendBackgroundX11Reply, reply_msg));
}

// Return the top-level parent of the given window. Called on the
// BACKGROUND_X11 thread.
static XID GetTopLevelWindow(XID window) {
  bool parent_is_root;
  XID parent_window;

  if (!x11_util::GetWindowParent(&parent_window, &parent_is_root, window))
    return 0;
  if (parent_is_root)
    return window;

  return GetTopLevelWindow(parent_window);
}

// Called on the BACKGROUND_X11 thread.
void ResourceMessageFilter::DoOnGetRootWindowRect(gfx::NativeViewId view,
                                                  IPC::Message* reply_msg) {
  // This is called to get the screen coordinates and size of the browser
  // window itself.
  gfx::Rect rect;
  XID window;

  if (Singleton<GtkNativeViewManager>()->GetXIDForId(&window, view)) {
    if (window) {
      const XID toplevel = GetTopLevelWindow(window);
      int x, y;
      unsigned width, height;
      if (x11_util::GetWindowGeometry(&x, &y, &width, &height, toplevel))
        rect = gfx::Rect(x, y, width, height);
    }
  }

  ViewHostMsg_GetRootWindowRect::WriteReplyParams(reply_msg, rect);

  ChromeThread::GetMessageLoop(ChromeThread::IO)->PostTask(
      FROM_HERE, NewRunnableMethod(
        this, &ResourceMessageFilter::SendBackgroundX11Reply, reply_msg));
}

// Called on the IO thread.
void ResourceMessageFilter::OnGetScreenInfo(gfx::NativeViewId view,
                                            IPC::Message* reply_msg) {
  ChromeThread::GetMessageLoop(ChromeThread::BACKGROUND_X11)->PostTask(
      FROM_HERE, NewRunnableMethod(
        this, &ResourceMessageFilter::DoOnGetScreenInfo, view, reply_msg));
}

// Called on the IO thread.
void ResourceMessageFilter::OnGetWindowRect(gfx::NativeViewId view,
                                            IPC::Message* reply_msg) {
  ChromeThread::GetMessageLoop(ChromeThread::BACKGROUND_X11)->PostTask(
      FROM_HERE, NewRunnableMethod(
        this, &ResourceMessageFilter::DoOnGetWindowRect, view, reply_msg));
}

// Called on the IO thread.
void ResourceMessageFilter::OnGetRootWindowRect(gfx::NativeViewId view,
                                                IPC::Message* reply_msg) {
  ChromeThread::GetMessageLoop(ChromeThread::BACKGROUND_X11)->PostTask(
      FROM_HERE, NewRunnableMethod(
        this, &ResourceMessageFilter::DoOnGetRootWindowRect, view, reply_msg));
}
<|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/gtk/translate/translate_infobar_base_gtk.h"

#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "app/slide_animation.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/translate/options_menu_model.h"
#include "chrome/browser/translate/translate_infobar_delegate.h"
#include "chrome/browser/gtk/translate/after_translate_infobar_gtk.h"
#include "chrome/browser/gtk/translate/before_translate_infobar_gtk.h"
#include "chrome/browser/gtk/translate/translate_message_infobar_gtk.h"
#include "chrome/browser/gtk/gtk_util.h"
#include "chrome/browser/gtk/menu_gtk.h"
#include "gfx/canvas.h"
#include "gfx/gtk_util.h"
#include "grit/generated_resources.h"

namespace {

// To be able to map from language id <-> entry in the combo box, we
// store the language id in the combo box data model in addition to the
// displayed name.
enum {
  LANGUAGE_COMBO_COLUMN_ID,
  LANGUAGE_COMBO_COLUMN_NAME,
  LANGUAGE_COMBO_COLUMN_COUNT
};

}  // namespace

TranslateInfoBarBase::TranslateInfoBarBase(TranslateInfoBarDelegate* delegate)
    : InfoBar(delegate) {
  TranslateInfoBarDelegate::BackgroundAnimationType animation =
      delegate->background_animation_type();
  if (animation != TranslateInfoBarDelegate::kNone) {
    background_color_animation_.reset(new SlideAnimation(this));
    background_color_animation_->SetTweenType(Tween::LINEAR);
    background_color_animation_->SetSlideDuration(500);
    if (animation == TranslateInfoBarDelegate::kNormalToError) {
      background_color_animation_->Show();
    } else {
      DCHECK_EQ(TranslateInfoBarDelegate::kErrorToNormal, animation);
      // Hide() runs the animation in reverse.
      background_color_animation_->Reset(1.0);
      background_color_animation_->Hide();
    }
  }
}

TranslateInfoBarBase::~TranslateInfoBarBase() {
}

void TranslateInfoBarBase::Init() {
  if (!ShowOptionsMenuButton())
    return;

  // The options button sits outside the translate_box so that it can be end
  // packed in hbox_.
  GtkWidget* options_menu_button = BuildOptionsMenuButton();
  g_signal_connect(options_menu_button, "clicked",
                   G_CALLBACK(&OnOptionsClickedThunk), this);
  gtk_widget_show_all(options_menu_button);
  gtk_util::CenterWidgetInHBox(hbox_, options_menu_button, true, 0);
}

void TranslateInfoBarBase::GetTopColor(InfoBarDelegate::Type type,
                                       double* r, double* g, double *b) {
  if (background_error_percent_ <= 0) {
    InfoBar::GetTopColor(InfoBarDelegate::PAGE_ACTION_TYPE, r, g, b);
  } else if (background_error_percent_ >= 1) {
    InfoBar::GetTopColor(InfoBarDelegate::ERROR_TYPE, r, g, b);
  } else {
    double normal_r, normal_g, normal_b;
    InfoBar::GetTopColor(InfoBarDelegate::PAGE_ACTION_TYPE,
                         &normal_r, &normal_g, &normal_b);

    double error_r, error_g, error_b;
    InfoBar::GetTopColor(InfoBarDelegate::ERROR_TYPE,
                         &error_r, &error_g, &error_b);

    double offset_r = error_r - normal_r;
    double offset_g = error_g - normal_g;
    double offset_b = error_b - normal_b;

    *r = normal_r + (background_error_percent_ * offset_r);
    *g = normal_g + (background_error_percent_ * offset_g);
    *b = normal_b + (background_error_percent_ * offset_b);
  }
}

void TranslateInfoBarBase::GetBottomColor(InfoBarDelegate::Type type,
                                          double* r, double* g, double *b) {
  if (background_error_percent_ <= 0) {
    InfoBar::GetBottomColor(InfoBarDelegate::PAGE_ACTION_TYPE, r, g, b);
  } else if (background_error_percent_ >= 1) {
    InfoBar::GetBottomColor(InfoBarDelegate::ERROR_TYPE, r, g, b);
  } else {
    double normal_r, normal_g, normal_b;
    InfoBar::GetBottomColor(InfoBarDelegate::PAGE_ACTION_TYPE,
                            &normal_r, &normal_g, &normal_b);

    double error_r, error_g, error_b;
    InfoBar::GetBottomColor(InfoBarDelegate::ERROR_TYPE,
                            &error_r, &error_g, &error_b);

    double offset_r = error_r - normal_r;
    double offset_g = error_g - normal_g;
    double offset_b = error_b - normal_b;

    *r = normal_r + (background_error_percent_ * offset_r);
    *g = normal_g + (background_error_percent_ * offset_g);
    *b = normal_b + (background_error_percent_ * offset_b);
  }
}

void TranslateInfoBarBase::AnimationProgressed(const Animation* animation) {
  DCHECK(animation == background_color_animation_.get());
  background_error_percent_ = animation->GetCurrentValue();
  // Queue the info bar widget for redisplay so it repaints its background.
  gtk_widget_queue_draw(widget());
}

GtkWidget* TranslateInfoBarBase::CreateLabel(const std::string& text) {
  GtkWidget* label = gtk_label_new(text.c_str());
  gtk_widget_modify_fg(label, GTK_STATE_NORMAL, &gfx::kGdkBlack);
  return label;
}

GtkWidget* TranslateInfoBarBase::CreateLanguageCombobox(int selected_language,
                                                        int exclude_language) {
  GtkListStore* model = gtk_list_store_new(LANGUAGE_COMBO_COLUMN_COUNT,
                                           G_TYPE_INT, G_TYPE_STRING);
  bool set_selection = false;
  GtkTreeIter selected_iter;
  TranslateInfoBarDelegate* delegate = GetDelegate();
  for (int i = 0; i < delegate->GetLanguageCount(); ++i) {
    if (i == exclude_language)
      continue;
    GtkTreeIter tree_iter;
    const string16& name = delegate->GetLanguageDisplayableNameAt(i);

    gtk_list_store_append(model, &tree_iter);
    gtk_list_store_set(model, &tree_iter,
                       LANGUAGE_COMBO_COLUMN_ID, i,
                       LANGUAGE_COMBO_COLUMN_NAME, UTF16ToUTF8(name).c_str(),
                       -1);
    if (i == selected_language) {
      selected_iter = tree_iter;
      set_selection = true;
    }
  }

  GtkWidget* combobox = gtk_combo_box_new_with_model(GTK_TREE_MODEL(model));
  if (set_selection)
    gtk_combo_box_set_active_iter(GTK_COMBO_BOX(combobox), &selected_iter);
  g_object_unref(model);
  GtkCellRenderer* renderer = gtk_cell_renderer_text_new();
  gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(combobox), renderer, TRUE);
  gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(combobox), renderer,
                                 "text", LANGUAGE_COMBO_COLUMN_NAME,
                                 NULL);
  return combobox;
}

// static
int TranslateInfoBarBase::GetLanguageComboboxActiveId(GtkComboBox* combo) {
  GtkTreeIter iter;
  if (!gtk_combo_box_get_active_iter(combo, &iter))
    return 0;

  gint id = 0;
  gtk_tree_model_get(gtk_combo_box_get_model(combo), &iter,
                     LANGUAGE_COMBO_COLUMN_ID, &id,
                     -1);
  return id;
}

TranslateInfoBarDelegate* TranslateInfoBarBase::GetDelegate() const {
  return static_cast<TranslateInfoBarDelegate*>(delegate());
}

// static
GtkWidget* TranslateInfoBarBase::BuildOptionsMenuButton() {
  GtkWidget* button = gtk_button_new();
  GtkWidget* former_child = gtk_bin_get_child(GTK_BIN(button));
  if (former_child)
    gtk_container_remove(GTK_CONTAINER(button), former_child);

  GtkWidget* hbox = gtk_hbox_new(FALSE, 0);

  GtkWidget* label = gtk_label_new(
      l10n_util::GetStringUTF8(IDS_TRANSLATE_INFOBAR_OPTIONS).c_str());
  gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 0);

  GtkWidget* arrow = gtk_arrow_new(GTK_ARROW_DOWN, GTK_SHADOW_NONE);
  gtk_box_pack_start(GTK_BOX(hbox), arrow, FALSE, FALSE, 0);

  gtk_container_add(GTK_CONTAINER(button), hbox);

  return button;
}

void TranslateInfoBarBase::OnOptionsClicked(GtkWidget* sender) {
  if (!options_menu_model_.get()) {
    options_menu_model_.reset(new OptionsMenuModel(GetDelegate()));
    options_menu_menu_.reset(new MenuGtk(NULL, options_menu_model_.get()));
  }
  options_menu_menu_->Popup(sender, 1, gtk_get_current_event_time());
}

// TranslateInfoBarDelegate specific method:
InfoBar* TranslateInfoBarDelegate::CreateInfoBar() {
  TranslateInfoBarBase* infobar = NULL;
  switch (type_) {
    case kBeforeTranslate:
      infobar = new BeforeTranslateInfoBar(this);
      break;
    case kAfterTranslate:
      infobar = new AfterTranslateInfoBar(this);
      break;
    case kTranslating:
    case kTranslationError:
      infobar = new TranslateMessageInfoBar(this);
      break;
    default:
      NOTREACHED();
  }
  infobar->Init();
  // Set |infobar_view_| so that the model can notify the infobar when it
  // changes.
  infobar_view_ = infobar;
  return infobar;
}
<commit_msg>Fixing translate infobar background. In some cases the infobar background was not the right color.<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/gtk/translate/translate_infobar_base_gtk.h"

#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "app/slide_animation.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/translate/options_menu_model.h"
#include "chrome/browser/translate/translate_infobar_delegate.h"
#include "chrome/browser/gtk/translate/after_translate_infobar_gtk.h"
#include "chrome/browser/gtk/translate/before_translate_infobar_gtk.h"
#include "chrome/browser/gtk/translate/translate_message_infobar_gtk.h"
#include "chrome/browser/gtk/gtk_util.h"
#include "chrome/browser/gtk/menu_gtk.h"
#include "gfx/canvas.h"
#include "gfx/gtk_util.h"
#include "grit/generated_resources.h"

namespace {

// To be able to map from language id <-> entry in the combo box, we
// store the language id in the combo box data model in addition to the
// displayed name.
enum {
  LANGUAGE_COMBO_COLUMN_ID,
  LANGUAGE_COMBO_COLUMN_NAME,
  LANGUAGE_COMBO_COLUMN_COUNT
};

}  // namespace

TranslateInfoBarBase::TranslateInfoBarBase(TranslateInfoBarDelegate* delegate)
    : InfoBar(delegate) {
  TranslateInfoBarDelegate::BackgroundAnimationType animation =
      delegate->background_animation_type();
  if (animation != TranslateInfoBarDelegate::kNone) {
    background_color_animation_.reset(new SlideAnimation(this));
    background_color_animation_->SetTweenType(Tween::LINEAR);
    background_color_animation_->SetSlideDuration(500);
    if (animation == TranslateInfoBarDelegate::kNormalToError) {
      background_color_animation_->Show();
    } else {
      DCHECK_EQ(TranslateInfoBarDelegate::kErrorToNormal, animation);
      // Hide() runs the animation in reverse.
      background_color_animation_->Reset(1.0);
      background_color_animation_->Hide();
    }
  } else {
    background_error_percent_ = delegate->IsError() ? 1 : 0;
  }
}

TranslateInfoBarBase::~TranslateInfoBarBase() {
}

void TranslateInfoBarBase::Init() {
  if (!ShowOptionsMenuButton())
    return;

  // The options button sits outside the translate_box so that it can be end
  // packed in hbox_.
  GtkWidget* options_menu_button = BuildOptionsMenuButton();
  g_signal_connect(options_menu_button, "clicked",
                   G_CALLBACK(&OnOptionsClickedThunk), this);
  gtk_widget_show_all(options_menu_button);
  gtk_util::CenterWidgetInHBox(hbox_, options_menu_button, true, 0);
}

void TranslateInfoBarBase::GetTopColor(InfoBarDelegate::Type type,
                                       double* r, double* g, double *b) {
  if (background_error_percent_ <= 0) {
    InfoBar::GetTopColor(InfoBarDelegate::PAGE_ACTION_TYPE, r, g, b);
  } else if (background_error_percent_ >= 1) {
    InfoBar::GetTopColor(InfoBarDelegate::ERROR_TYPE, r, g, b);
  } else {
    double normal_r, normal_g, normal_b;
    InfoBar::GetTopColor(InfoBarDelegate::PAGE_ACTION_TYPE,
                         &normal_r, &normal_g, &normal_b);

    double error_r, error_g, error_b;
    InfoBar::GetTopColor(InfoBarDelegate::ERROR_TYPE,
                         &error_r, &error_g, &error_b);

    double offset_r = error_r - normal_r;
    double offset_g = error_g - normal_g;
    double offset_b = error_b - normal_b;

    *r = normal_r + (background_error_percent_ * offset_r);
    *g = normal_g + (background_error_percent_ * offset_g);
    *b = normal_b + (background_error_percent_ * offset_b);
  }
}

void TranslateInfoBarBase::GetBottomColor(InfoBarDelegate::Type type,
                                          double* r, double* g, double *b) {
  if (background_error_percent_ <= 0) {
    InfoBar::GetBottomColor(InfoBarDelegate::PAGE_ACTION_TYPE, r, g, b);
  } else if (background_error_percent_ >= 1) {
    InfoBar::GetBottomColor(InfoBarDelegate::ERROR_TYPE, r, g, b);
  } else {
    double normal_r, normal_g, normal_b;
    InfoBar::GetBottomColor(InfoBarDelegate::PAGE_ACTION_TYPE,
                            &normal_r, &normal_g, &normal_b);

    double error_r, error_g, error_b;
    InfoBar::GetBottomColor(InfoBarDelegate::ERROR_TYPE,
                            &error_r, &error_g, &error_b);

    double offset_r = error_r - normal_r;
    double offset_g = error_g - normal_g;
    double offset_b = error_b - normal_b;

    *r = normal_r + (background_error_percent_ * offset_r);
    *g = normal_g + (background_error_percent_ * offset_g);
    *b = normal_b + (background_error_percent_ * offset_b);
  }
}

void TranslateInfoBarBase::AnimationProgressed(const Animation* animation) {
  DCHECK(animation == background_color_animation_.get());
  background_error_percent_ = animation->GetCurrentValue();
  // Queue the info bar widget for redisplay so it repaints its background.
  gtk_widget_queue_draw(widget());
}

GtkWidget* TranslateInfoBarBase::CreateLabel(const std::string& text) {
  GtkWidget* label = gtk_label_new(text.c_str());
  gtk_widget_modify_fg(label, GTK_STATE_NORMAL, &gfx::kGdkBlack);
  return label;
}

GtkWidget* TranslateInfoBarBase::CreateLanguageCombobox(int selected_language,
                                                        int exclude_language) {
  GtkListStore* model = gtk_list_store_new(LANGUAGE_COMBO_COLUMN_COUNT,
                                           G_TYPE_INT, G_TYPE_STRING);
  bool set_selection = false;
  GtkTreeIter selected_iter;
  TranslateInfoBarDelegate* delegate = GetDelegate();
  for (int i = 0; i < delegate->GetLanguageCount(); ++i) {
    if (i == exclude_language)
      continue;
    GtkTreeIter tree_iter;
    const string16& name = delegate->GetLanguageDisplayableNameAt(i);

    gtk_list_store_append(model, &tree_iter);
    gtk_list_store_set(model, &tree_iter,
                       LANGUAGE_COMBO_COLUMN_ID, i,
                       LANGUAGE_COMBO_COLUMN_NAME, UTF16ToUTF8(name).c_str(),
                       -1);
    if (i == selected_language) {
      selected_iter = tree_iter;
      set_selection = true;
    }
  }

  GtkWidget* combobox = gtk_combo_box_new_with_model(GTK_TREE_MODEL(model));
  if (set_selection)
    gtk_combo_box_set_active_iter(GTK_COMBO_BOX(combobox), &selected_iter);
  g_object_unref(model);
  GtkCellRenderer* renderer = gtk_cell_renderer_text_new();
  gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(combobox), renderer, TRUE);
  gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(combobox), renderer,
                                 "text", LANGUAGE_COMBO_COLUMN_NAME,
                                 NULL);
  return combobox;
}

// static
int TranslateInfoBarBase::GetLanguageComboboxActiveId(GtkComboBox* combo) {
  GtkTreeIter iter;
  if (!gtk_combo_box_get_active_iter(combo, &iter))
    return 0;

  gint id = 0;
  gtk_tree_model_get(gtk_combo_box_get_model(combo), &iter,
                     LANGUAGE_COMBO_COLUMN_ID, &id,
                     -1);
  return id;
}

TranslateInfoBarDelegate* TranslateInfoBarBase::GetDelegate() const {
  return static_cast<TranslateInfoBarDelegate*>(delegate());
}

// static
GtkWidget* TranslateInfoBarBase::BuildOptionsMenuButton() {
  GtkWidget* button = gtk_button_new();
  GtkWidget* former_child = gtk_bin_get_child(GTK_BIN(button));
  if (former_child)
    gtk_container_remove(GTK_CONTAINER(button), former_child);

  GtkWidget* hbox = gtk_hbox_new(FALSE, 0);

  GtkWidget* label = gtk_label_new(
      l10n_util::GetStringUTF8(IDS_TRANSLATE_INFOBAR_OPTIONS).c_str());
  gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 0);

  GtkWidget* arrow = gtk_arrow_new(GTK_ARROW_DOWN, GTK_SHADOW_NONE);
  gtk_box_pack_start(GTK_BOX(hbox), arrow, FALSE, FALSE, 0);

  gtk_container_add(GTK_CONTAINER(button), hbox);

  return button;
}

void TranslateInfoBarBase::OnOptionsClicked(GtkWidget* sender) {
  if (!options_menu_model_.get()) {
    options_menu_model_.reset(new OptionsMenuModel(GetDelegate()));
    options_menu_menu_.reset(new MenuGtk(NULL, options_menu_model_.get()));
  }
  options_menu_menu_->Popup(sender, 1, gtk_get_current_event_time());
}

// TranslateInfoBarDelegate specific method:
InfoBar* TranslateInfoBarDelegate::CreateInfoBar() {
  TranslateInfoBarBase* infobar = NULL;
  switch (type_) {
    case kBeforeTranslate:
      infobar = new BeforeTranslateInfoBar(this);
      break;
    case kAfterTranslate:
      infobar = new AfterTranslateInfoBar(this);
      break;
    case kTranslating:
    case kTranslationError:
      infobar = new TranslateMessageInfoBar(this);
      break;
    default:
      NOTREACHED();
  }
  infobar->Init();
  // Set |infobar_view_| so that the model can notify the infobar when it
  // changes.
  infobar_view_ = infobar;
  return infobar;
}
<|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 "base/process_util.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/find_bar/find_bar_controller.h"
#include "chrome/browser/ui/find_bar/find_notification_details.h"
#include "chrome/browser/ui/view_ids.h"
#include "chrome/browser/ui/views/find_bar_host.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "net/test/test_server.h"
#include "ui/base/clipboard/clipboard.h"
#include "ui/base/keycodes/keyboard_codes.h"
#include "views/focus/focus_manager.h"
#include "views/view.h"
#include "views/views_delegate.h"

namespace {

// The delay waited after sending an OS simulated event.
static const int kActionDelayMs = 500;
static const char kSimplePage[] = "files/find_in_page/simple.html";

void Checkpoint(const char* message, const base::TimeTicks& start_time) {
  LOG(INFO) << message << " : "
    << (base::TimeTicks::Now() - start_time).InMilliseconds()
    << " ms" << std::flush;
}

class FindInPageTest : public InProcessBrowserTest {
 public:
  FindInPageTest() {
    set_show_window(true);
    FindBarHost::disable_animations_during_testing_ = true;
  }

  string16 GetFindBarText() {
    FindBarTesting* find_bar =
        browser()->GetFindBarController()->find_bar()->GetFindBarTesting();
    return find_bar->GetFindText();
  }

  string16 GetFindBarSelectedText() {
    FindBarTesting* find_bar =
        browser()->GetFindBarController()->find_bar()->GetFindBarTesting();
    return find_bar->GetFindSelectedText();
  }
};

}  // namespace

#if defined(TOOLKIT_USES_GTK)
#define MAYBE_CrashEscHandlers FLAKY_CrashEscHandlers
#else
#define MAYBE_CrashEscHandlers CrashEscHandlers
#endif

IN_PROC_BROWSER_TEST_F(FindInPageTest, MAYBE_CrashEscHandlers) {
  ASSERT_TRUE(test_server()->Start());

  // First we navigate to our test page (tab A).
  GURL url = test_server()->GetURL(kSimplePage);
  ui_test_utils::NavigateToURL(browser(), url);

  browser()->Find();

  // Open another tab (tab B).
  browser()->AddSelectedTabWithURL(url, PageTransition::TYPED);

  browser()->Find();
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
                                           VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));

  // Select tab A.
  browser()->ActivateTabAt(0, true);

  // Close tab B.
  browser()->CloseTabContents(browser()->GetTabContentsAt(1));

  // Click on the location bar so that Find box loses focus.
  ASSERT_NO_FATAL_FAILURE(ui_test_utils::ClickOnView(browser(),
                                                     VIEW_ID_LOCATION_BAR));
#if defined(TOOLKIT_VIEWS) || defined(OS_WIN)
  // Check the location bar is focused.
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));
#endif

  // This used to crash until bug 1303709 was fixed.
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_ESCAPE, false, false, false, false));
}

IN_PROC_BROWSER_TEST_F(FindInPageTest, FocusRestore) {
  ASSERT_TRUE(test_server()->Start());

  GURL url = test_server()->GetURL("title1.html");
  ui_test_utils::NavigateToURL(browser(), url);

  // Focus the location bar, open and close the find-in-page, focus should
  // return to the location bar.
  browser()->FocusLocationBar();
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));
  // Ensure the creation of the find bar controller.
  browser()->GetFindBarController()->Show();
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
                                           VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
  browser()->GetFindBarController()->EndFindSession(
      FindBarController::kKeepSelection);
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));

  // Focus the location bar, find something on the page, close the find box,
  // focus should go to the page.
  browser()->FocusLocationBar();
  browser()->Find();
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
                                           VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
  ui_test_utils::FindInPage(browser()->GetSelectedTabContentsWrapper(),
                            ASCIIToUTF16("a"), true, false, NULL);
  browser()->GetFindBarController()->EndFindSession(
      FindBarController::kKeepSelection);
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
                                           VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));

  // Focus the location bar, open and close the find box, focus should return to
  // the location bar (same as before, just checking that http://crbug.com/23599
  // is fixed).
  browser()->FocusLocationBar();
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));
  browser()->GetFindBarController()->Show();
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
                                           VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
  browser()->GetFindBarController()->EndFindSession(
      FindBarController::kKeepSelection);
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));
}

IN_PROC_BROWSER_TEST_F(FindInPageTest, FocusRestoreOnTabSwitch) {
  ASSERT_TRUE(test_server()->Start());

  // First we navigate to our test page (tab A).
  GURL url = test_server()->GetURL(kSimplePage);
  ui_test_utils::NavigateToURL(browser(), url);

  browser()->Find();
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
                                           VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));

  FindBarTesting* find_bar =
      browser()->GetFindBarController()->find_bar()->GetFindBarTesting();

  // Search for 'a'.
  ui_test_utils::FindInPage(browser()->GetSelectedTabContentsWrapper(),
                            ASCIIToUTF16("a"), true, false, NULL);
  EXPECT_TRUE(ASCIIToUTF16("a") == find_bar->GetFindSelectedText());

  // Open another tab (tab B).
  browser()->AddSelectedTabWithURL(url, PageTransition::TYPED);
  ASSERT_TRUE(ui_test_utils::WaitForNavigationInCurrentTab(browser()));

  // Make sure Find box is open.
  browser()->Find();
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
                                           VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));

  // Search for 'b'.
  ui_test_utils::FindInPage(browser()->GetSelectedTabContentsWrapper(),
                            ASCIIToUTF16("b"), true, false, NULL);
  EXPECT_TRUE(ASCIIToUTF16("b") == find_bar->GetFindSelectedText());

  // Set focus away from the Find bar (to the Location bar).
  browser()->FocusLocationBar();
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));

  // Select tab A. Find bar should get focus.
  browser()->ActivateTabAt(0, true);
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
                                           VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
  EXPECT_TRUE(ASCIIToUTF16("a") == find_bar->GetFindSelectedText());

  // Select tab B. Location bar should get focus.
  browser()->ActivateTabAt(1, true);
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));
}

// This tests that whenever you clear values from the Find box and close it that
// it respects that and doesn't show you the last search, as reported in bug:
// http://crbug.com/40121.
IN_PROC_BROWSER_TEST_F(FindInPageTest, PrepopulateRespectBlank) {
#if defined(OS_MACOSX)
  // FindInPage on Mac doesn't use prepopulated values. Search there is global.
  return;
#endif
  base::TimeTicks start_time = base::TimeTicks::Now();
  Checkpoint("Test starting", start_time);

  ASSERT_TRUE(test_server()->Start());

  // Make sure Chrome is in the foreground, otherwise sending input
  // won't do anything and the test will hang.
  ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));

  Checkpoint("Navigate", start_time);

  // First we navigate to any page.
  GURL url = test_server()->GetURL(kSimplePage);
  ui_test_utils::NavigateToURL(browser(), url);

  Checkpoint("Show Find bar", start_time);

  // Show the Find bar.
  browser()->GetFindBarController()->Show();

  Checkpoint("Search for 'a'", start_time);

  // Search for "a".
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_A, false, false, false, false));

  // We should find "a" here.
  EXPECT_EQ(ASCIIToUTF16("a"), GetFindBarText());

  Checkpoint("Delete 'a'", start_time);

  // Delete "a".
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_BACK, false, false, false, false));

  // Validate we have cleared the text.
  EXPECT_EQ(string16(), GetFindBarText());

  Checkpoint("Close find bar", start_time);

  // Close the Find box.
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_ESCAPE, false, false, false, false));

  Checkpoint("Show Find bar", start_time);

  // Show the Find bar.
  browser()->GetFindBarController()->Show();

  Checkpoint("Validate text", start_time);

  // After the Find box has been reopened, it should not have been prepopulated
  // with "a" again.
  EXPECT_EQ(string16(), GetFindBarText());

  Checkpoint("Close Find bar", start_time);

  // Close the Find box.
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_ESCAPE, false, false, false, false));

  Checkpoint("FindNext", start_time);

  // Press F3 to trigger FindNext.
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_F3, false, false, false, false));

  Checkpoint("Validate", start_time);

  // After the Find box has been reopened, it should still have no prepopulate
  // value.
  EXPECT_EQ(string16(), GetFindBarText());

  Checkpoint("Test done", start_time);
}

IN_PROC_BROWSER_TEST_F(FindInPageTest, PasteWithoutTextChange) {
  ASSERT_TRUE(test_server()->Start());

  // Make sure Chrome is in the foreground, otherwise sending input
  // won't do anything and the test will hang.
  ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));

  // First we navigate to any page.
  GURL url = test_server()->GetURL(kSimplePage);
  ui_test_utils::NavigateToURL(browser(), url);

  // Show the Find bar.
  browser()->GetFindBarController()->Show();

  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
                                           VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));

  // Search for "a".
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_A, false, false, false, false));

  // We should find "a" here.
  EXPECT_EQ(ASCIIToUTF16("a"), GetFindBarText());

  // Reload the page to clear the matching result.
  browser()->Reload(CURRENT_TAB);

  // Focus the Find bar again to make sure the text is selected.
  browser()->GetFindBarController()->Show();

  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
                                           VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));

  // "a" should be selected.
  EXPECT_EQ(ASCIIToUTF16("a"), GetFindBarSelectedText());

  // Press Ctrl-C to copy the content.
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_C, true, false, false, false));

  string16 str;
  views::ViewsDelegate::views_delegate->GetClipboard()->
      ReadText(ui::Clipboard::BUFFER_STANDARD, &str);

  // Make sure the text is copied successfully.
  EXPECT_EQ(ASCIIToUTF16("a"), str);

  // Press Ctrl-V to paste the content back, it should start finding even if the
  // content is not changed.
  Source<TabContents> notification_source(browser()->GetSelectedTabContents());
  ui_test_utils::WindowedNotificationObserverWithDetails
      <FindNotificationDetails> observer(
          chrome::NOTIFICATION_FIND_RESULT_AVAILABLE, notification_source);

  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_V, true, false, false, false));

  ASSERT_NO_FATAL_FAILURE(observer.Wait());
  FindNotificationDetails details;
  ASSERT_TRUE(observer.GetDetailsFor(notification_source.map_key(), &details));
  EXPECT_TRUE(details.number_of_matches() > 0);
}
<commit_msg>Mark FindInPageTest.PasteWithoutTextChange flaky on Win.<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 "base/process_util.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/find_bar/find_bar_controller.h"
#include "chrome/browser/ui/find_bar/find_notification_details.h"
#include "chrome/browser/ui/view_ids.h"
#include "chrome/browser/ui/views/find_bar_host.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "net/test/test_server.h"
#include "ui/base/clipboard/clipboard.h"
#include "ui/base/keycodes/keyboard_codes.h"
#include "views/focus/focus_manager.h"
#include "views/view.h"
#include "views/views_delegate.h"

namespace {

// The delay waited after sending an OS simulated event.
static const int kActionDelayMs = 500;
static const char kSimplePage[] = "files/find_in_page/simple.html";

void Checkpoint(const char* message, const base::TimeTicks& start_time) {
  LOG(INFO) << message << " : "
    << (base::TimeTicks::Now() - start_time).InMilliseconds()
    << " ms" << std::flush;
}

class FindInPageTest : public InProcessBrowserTest {
 public:
  FindInPageTest() {
    set_show_window(true);
    FindBarHost::disable_animations_during_testing_ = true;
  }

  string16 GetFindBarText() {
    FindBarTesting* find_bar =
        browser()->GetFindBarController()->find_bar()->GetFindBarTesting();
    return find_bar->GetFindText();
  }

  string16 GetFindBarSelectedText() {
    FindBarTesting* find_bar =
        browser()->GetFindBarController()->find_bar()->GetFindBarTesting();
    return find_bar->GetFindSelectedText();
  }
};

}  // namespace

#if defined(TOOLKIT_USES_GTK)
#define MAYBE_CrashEscHandlers FLAKY_CrashEscHandlers
#else
#define MAYBE_CrashEscHandlers CrashEscHandlers
#endif

IN_PROC_BROWSER_TEST_F(FindInPageTest, MAYBE_CrashEscHandlers) {
  ASSERT_TRUE(test_server()->Start());

  // First we navigate to our test page (tab A).
  GURL url = test_server()->GetURL(kSimplePage);
  ui_test_utils::NavigateToURL(browser(), url);

  browser()->Find();

  // Open another tab (tab B).
  browser()->AddSelectedTabWithURL(url, PageTransition::TYPED);

  browser()->Find();
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
                                           VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));

  // Select tab A.
  browser()->ActivateTabAt(0, true);

  // Close tab B.
  browser()->CloseTabContents(browser()->GetTabContentsAt(1));

  // Click on the location bar so that Find box loses focus.
  ASSERT_NO_FATAL_FAILURE(ui_test_utils::ClickOnView(browser(),
                                                     VIEW_ID_LOCATION_BAR));
#if defined(TOOLKIT_VIEWS) || defined(OS_WIN)
  // Check the location bar is focused.
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));
#endif

  // This used to crash until bug 1303709 was fixed.
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_ESCAPE, false, false, false, false));
}

IN_PROC_BROWSER_TEST_F(FindInPageTest, FocusRestore) {
  ASSERT_TRUE(test_server()->Start());

  GURL url = test_server()->GetURL("title1.html");
  ui_test_utils::NavigateToURL(browser(), url);

  // Focus the location bar, open and close the find-in-page, focus should
  // return to the location bar.
  browser()->FocusLocationBar();
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));
  // Ensure the creation of the find bar controller.
  browser()->GetFindBarController()->Show();
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
                                           VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
  browser()->GetFindBarController()->EndFindSession(
      FindBarController::kKeepSelection);
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));

  // Focus the location bar, find something on the page, close the find box,
  // focus should go to the page.
  browser()->FocusLocationBar();
  browser()->Find();
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
                                           VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
  ui_test_utils::FindInPage(browser()->GetSelectedTabContentsWrapper(),
                            ASCIIToUTF16("a"), true, false, NULL);
  browser()->GetFindBarController()->EndFindSession(
      FindBarController::kKeepSelection);
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
                                           VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));

  // Focus the location bar, open and close the find box, focus should return to
  // the location bar (same as before, just checking that http://crbug.com/23599
  // is fixed).
  browser()->FocusLocationBar();
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));
  browser()->GetFindBarController()->Show();
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
                                           VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
  browser()->GetFindBarController()->EndFindSession(
      FindBarController::kKeepSelection);
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));
}

IN_PROC_BROWSER_TEST_F(FindInPageTest, FocusRestoreOnTabSwitch) {
  ASSERT_TRUE(test_server()->Start());

  // First we navigate to our test page (tab A).
  GURL url = test_server()->GetURL(kSimplePage);
  ui_test_utils::NavigateToURL(browser(), url);

  browser()->Find();
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
                                           VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));

  FindBarTesting* find_bar =
      browser()->GetFindBarController()->find_bar()->GetFindBarTesting();

  // Search for 'a'.
  ui_test_utils::FindInPage(browser()->GetSelectedTabContentsWrapper(),
                            ASCIIToUTF16("a"), true, false, NULL);
  EXPECT_TRUE(ASCIIToUTF16("a") == find_bar->GetFindSelectedText());

  // Open another tab (tab B).
  browser()->AddSelectedTabWithURL(url, PageTransition::TYPED);
  ASSERT_TRUE(ui_test_utils::WaitForNavigationInCurrentTab(browser()));

  // Make sure Find box is open.
  browser()->Find();
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
                                           VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));

  // Search for 'b'.
  ui_test_utils::FindInPage(browser()->GetSelectedTabContentsWrapper(),
                            ASCIIToUTF16("b"), true, false, NULL);
  EXPECT_TRUE(ASCIIToUTF16("b") == find_bar->GetFindSelectedText());

  // Set focus away from the Find bar (to the Location bar).
  browser()->FocusLocationBar();
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));

  // Select tab A. Find bar should get focus.
  browser()->ActivateTabAt(0, true);
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
                                           VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
  EXPECT_TRUE(ASCIIToUTF16("a") == find_bar->GetFindSelectedText());

  // Select tab B. Location bar should get focus.
  browser()->ActivateTabAt(1, true);
  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));
}

// This tests that whenever you clear values from the Find box and close it that
// it respects that and doesn't show you the last search, as reported in bug:
// http://crbug.com/40121.
IN_PROC_BROWSER_TEST_F(FindInPageTest, PrepopulateRespectBlank) {
#if defined(OS_MACOSX)
  // FindInPage on Mac doesn't use prepopulated values. Search there is global.
  return;
#endif
  base::TimeTicks start_time = base::TimeTicks::Now();
  Checkpoint("Test starting", start_time);

  ASSERT_TRUE(test_server()->Start());

  // Make sure Chrome is in the foreground, otherwise sending input
  // won't do anything and the test will hang.
  ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));

  Checkpoint("Navigate", start_time);

  // First we navigate to any page.
  GURL url = test_server()->GetURL(kSimplePage);
  ui_test_utils::NavigateToURL(browser(), url);

  Checkpoint("Show Find bar", start_time);

  // Show the Find bar.
  browser()->GetFindBarController()->Show();

  Checkpoint("Search for 'a'", start_time);

  // Search for "a".
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_A, false, false, false, false));

  // We should find "a" here.
  EXPECT_EQ(ASCIIToUTF16("a"), GetFindBarText());

  Checkpoint("Delete 'a'", start_time);

  // Delete "a".
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_BACK, false, false, false, false));

  // Validate we have cleared the text.
  EXPECT_EQ(string16(), GetFindBarText());

  Checkpoint("Close find bar", start_time);

  // Close the Find box.
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_ESCAPE, false, false, false, false));

  Checkpoint("Show Find bar", start_time);

  // Show the Find bar.
  browser()->GetFindBarController()->Show();

  Checkpoint("Validate text", start_time);

  // After the Find box has been reopened, it should not have been prepopulated
  // with "a" again.
  EXPECT_EQ(string16(), GetFindBarText());

  Checkpoint("Close Find bar", start_time);

  // Close the Find box.
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_ESCAPE, false, false, false, false));

  Checkpoint("FindNext", start_time);

  // Press F3 to trigger FindNext.
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_F3, false, false, false, false));

  Checkpoint("Validate", start_time);

  // After the Find box has been reopened, it should still have no prepopulate
  // value.
  EXPECT_EQ(string16(), GetFindBarText());

  Checkpoint("Test done", start_time);
}

// Flaky on Win. http://crbug.com/92467
#if defined(OS_WIN)
#define MAYBE_PasteWithoutTextChange FLAKY_PasteWithoutTextChange
#else
#define MAYBE_PasteWithoutTextChange PasteWithoutTextChange
#endif

IN_PROC_BROWSER_TEST_F(FindInPageTest, MAYBE_PasteWithoutTextChange) {
  ASSERT_TRUE(test_server()->Start());

  // Make sure Chrome is in the foreground, otherwise sending input
  // won't do anything and the test will hang.
  ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));

  // First we navigate to any page.
  GURL url = test_server()->GetURL(kSimplePage);
  ui_test_utils::NavigateToURL(browser(), url);

  // Show the Find bar.
  browser()->GetFindBarController()->Show();

  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
                                           VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));

  // Search for "a".
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_A, false, false, false, false));

  // We should find "a" here.
  EXPECT_EQ(ASCIIToUTF16("a"), GetFindBarText());

  // Reload the page to clear the matching result.
  browser()->Reload(CURRENT_TAB);

  // Focus the Find bar again to make sure the text is selected.
  browser()->GetFindBarController()->Show();

  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
                                           VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));

  // "a" should be selected.
  EXPECT_EQ(ASCIIToUTF16("a"), GetFindBarSelectedText());

  // Press Ctrl-C to copy the content.
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_C, true, false, false, false));

  string16 str;
  views::ViewsDelegate::views_delegate->GetClipboard()->
      ReadText(ui::Clipboard::BUFFER_STANDARD, &str);

  // Make sure the text is copied successfully.
  EXPECT_EQ(ASCIIToUTF16("a"), str);

  // Press Ctrl-V to paste the content back, it should start finding even if the
  // content is not changed.
  Source<TabContents> notification_source(browser()->GetSelectedTabContents());
  ui_test_utils::WindowedNotificationObserverWithDetails
      <FindNotificationDetails> observer(
          chrome::NOTIFICATION_FIND_RESULT_AVAILABLE, notification_source);

  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_V, true, false, false, false));

  ASSERT_NO_FATAL_FAILURE(observer.Wait());
  FindNotificationDetails details;
  ASSERT_TRUE(observer.GetDetailsFor(notification_source.map_key(), &details));
  EXPECT_TRUE(details.number_of_matches() > 0);
}
<|endoftext|>


<commit_before>// Copyright (c) 2012 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/ui/views/constrained_window_frame_simple.h"

#include "chrome/browser/ui/constrained_window.h"
#include "chrome/browser/ui/views/constrained_window_views.h"
#include "grit/ui_resources.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/google_chrome_strings.h"
#include "grit/shared_resources.h"
#include "grit/theme_resources.h"
#include "ui/base/hit_test.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/rect.h"
#include "ui/gfx/path.h"
#include "ui/views/background.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/button/image_button.h"
#include "ui/views/layout/grid_layout.h"
#include "ui/views/layout/layout_manager.h"
#include "ui/views/layout/layout_constants.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"

namespace {

typedef ConstrainedWindowFrameSimple::HeaderViews HeaderViews;

// A layout manager that lays out the header view with proper padding,
// and sized to the widget's client view.
class HeaderLayout : public views::LayoutManager {
 public:
  explicit HeaderLayout(views::Widget* container) : container_(container) {}
  virtual ~HeaderLayout() {}

  // Overridden from LayoutManager
  virtual void Layout(views::View* host);
  virtual gfx::Size GetPreferredSize(views::View* host);

 private:
  views::Widget* container_;

  DISALLOW_COPY_AND_ASSIGN(HeaderLayout);
};

void HeaderLayout::Layout(views::View* host) {
  if (!host->has_children())
    return;

  int horizontal_padding = ConstrainedWindow::kHorizontalPadding;
  int vertical_padding = ConstrainedWindow::kVerticalPadding;
  int row_padding = ConstrainedWindow::kRowPadding;

  views::View* header = host->child_at(0);
  gfx::Size preferred_size = GetPreferredSize(host);
  int width = preferred_size.width() - 2 * horizontal_padding;
  int height = preferred_size.height() - vertical_padding - row_padding;

  header->SetBounds(horizontal_padding, vertical_padding, width, height);
}

gfx::Size HeaderLayout::GetPreferredSize(views::View* host) {
  int horizontal_padding = ConstrainedWindow::kHorizontalPadding;
  int vertical_padding = ConstrainedWindow::kVerticalPadding;
  int row_padding = ConstrainedWindow::kRowPadding;

  views::View* header = host->child_at(0);
  views::View* client_view = container_->client_view();

  gfx::Size header_size = header ? header->GetPreferredSize() : gfx::Size();
  gfx::Size client_size =
      client_view ? client_view->GetPreferredSize() : gfx::Size();
  int width = std::max(client_size.width(), header_size.width()) +
      2 * horizontal_padding;
  int height = vertical_padding + header_size.height() + row_padding;
  return gfx::Size(width, height);
}

}  // namespace

ConstrainedWindowFrameSimple::HeaderViews::HeaderViews(
    views::View* header,
    views::Label* title_label,
    views::Button* close_button)
    : header(header),
      title_label(title_label),
      close_button(close_button) {
  DCHECK(header);
}

ConstrainedWindowFrameSimple::ConstrainedWindowFrameSimple(
    ConstrainedWindowViews* container)
    : container_(container) {
  container_->set_frame_type(views::Widget::FRAME_TYPE_FORCE_CUSTOM);

  layout_ = new HeaderLayout(container_);
  SetLayoutManager(layout_);

  SetHeaderView(CreateDefaultHeaderView());

  set_background(views::Background::CreateSolidBackground(
      ConstrainedWindow::GetBackgroundColor()));
}

ConstrainedWindowFrameSimple::~ConstrainedWindowFrameSimple() {
}

void ConstrainedWindowFrameSimple::SetHeaderView(HeaderViews* header_views)
{
  RemoveAllChildViews(true);

  header_views_.reset(header_views);

  AddChildView(header_views_->header);
}

HeaderViews* ConstrainedWindowFrameSimple::CreateDefaultHeaderView() {
  views::View* header_view = new views::View;

  views::GridLayout* grid_layout = new views::GridLayout(header_view);
  header_view->SetLayoutManager(grid_layout);

  views::ColumnSet* header_cs = grid_layout->AddColumnSet(0);
  header_cs->AddColumn(views::GridLayout::CENTER, views::GridLayout::CENTER, 0,
                       views::GridLayout::USE_PREF, 0, 0);  // Title.
  header_cs->AddPaddingColumn(1, views::kUnrelatedControlHorizontalSpacing);
  header_cs->AddColumn(views::GridLayout::CENTER, views::GridLayout::CENTER, 0,
                       views::GridLayout::USE_PREF, 0, 0);  // Close Button.

  // Header row.
  ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
  grid_layout->StartRow(0, 0);
  views::Label* title_label = new views::Label();
  title_label->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
  title_label->SetFont(rb.GetFont(ConstrainedWindow::kTitleFontStyle));
  title_label->SetEnabledColor(ConstrainedWindow::GetTextColor());
  title_label->SetText(container_->widget_delegate()->GetWindowTitle());
  grid_layout->AddView(title_label);

  views::Button* close_button = CreateCloseButton();
  grid_layout->AddView(close_button);

  return new HeaderViews(header_view, title_label, close_button);
}

gfx::Rect ConstrainedWindowFrameSimple::GetBoundsForClientView() const {
  int horizontal_padding = ConstrainedWindow::kHorizontalPadding;
  int vertical_padding = ConstrainedWindow::kVerticalPadding;
  int row_padding = ConstrainedWindow::kRowPadding;
  gfx::Size header_size =
      header_views_->header ?
      header_views_->header->GetPreferredSize() : gfx::Size();

  return gfx::Rect(horizontal_padding,
                   vertical_padding + header_size.height() + row_padding,
                   std::max(0, width() - 2 * horizontal_padding),
                   std::max(0, (height() - 2 * vertical_padding -
                                header_size.height() - row_padding)));
}

gfx::Rect ConstrainedWindowFrameSimple::GetWindowBoundsForClientBounds(
    const gfx::Rect& client_bounds) const {
  int horizontal_padding = ConstrainedWindow::kHorizontalPadding;
  int vertical_padding = ConstrainedWindow::kVerticalPadding;
  int row_padding = ConstrainedWindow::kRowPadding;
  gfx::Size header_size =
      header_views_->header ?
      header_views_->header->GetPreferredSize() : gfx::Size();

  int x = client_bounds.x() - horizontal_padding;
  int y = client_bounds.y() - vertical_padding - header_size.height() -
      row_padding;
  int width = client_bounds.width() + 2 * horizontal_padding;
  int height = client_bounds.height() + 2 * vertical_padding +
      header_size.height() + row_padding;

  return gfx::Rect(x, y, width, height);
}

int ConstrainedWindowFrameSimple::NonClientHitTest(const gfx::Point& point) {
  if (!bounds().Contains(point))
    return HTNOWHERE;
  return HTCLIENT;
}

void ConstrainedWindowFrameSimple::GetWindowMask(const gfx::Size& size,
                                                 gfx::Path* window_mask) {
  SkRect rect = {0, 0, size.width() - 1, size.height() - 1};
  SkScalar radius = SkIntToScalar(ConstrainedWindow::kBorderRadius);
  SkScalar radii[8] = {radius, radius, radius, radius,
                       radius, radius, radius, radius};

  // NB: We're not using the addRoundRect uniform radius overload as it
  // mishandles the bottom corners on Windows
  window_mask->addRoundRect(rect, radii);
}

void ConstrainedWindowFrameSimple::ResetWindowControls() {
}

void ConstrainedWindowFrameSimple::UpdateWindowIcon() {
}

void ConstrainedWindowFrameSimple::UpdateWindowTitle() {
  if (!header_views_->title_label)
    return;

  string16 text = container_->widget_delegate()->GetWindowTitle();
  header_views_->title_label->SetText(text);
}

gfx::Size ConstrainedWindowFrameSimple::GetPreferredSize() {
  return container_->non_client_view()->GetWindowBoundsForClientBounds(
      gfx::Rect(container_->client_view()->GetPreferredSize())).size();
}

void ConstrainedWindowFrameSimple::ButtonPressed(views::Button* sender,
                                                 const ui::Event& event) {
  if (header_views_->close_button && sender == header_views_->close_button)
    sender->GetWidget()->Close();
}

views::ImageButton* ConstrainedWindowFrameSimple::CreateCloseButton() {
  ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
  views::ImageButton* close_button = new views::ImageButton(this);
  close_button->SetImage(views::CustomButton::BS_NORMAL,
                          rb.GetImageSkiaNamed(IDR_SHARED_IMAGES_X));
  close_button->SetImage(views::CustomButton::BS_HOT,
                          rb.GetImageSkiaNamed(IDR_SHARED_IMAGES_X_HOVER));
  close_button->SetImage(views::CustomButton::BS_PUSHED,
                          rb.GetImageSkiaNamed(IDR_SHARED_IMAGES_X_HOVER));
  return close_button;
}
<commit_msg>Add workaround for window mask off-by-one bug<commit_after>// Copyright (c) 2012 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/ui/views/constrained_window_frame_simple.h"

#include "chrome/browser/ui/constrained_window.h"
#include "chrome/browser/ui/views/constrained_window_views.h"
#include "grit/ui_resources.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/google_chrome_strings.h"
#include "grit/shared_resources.h"
#include "grit/theme_resources.h"
#include "ui/base/hit_test.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/rect.h"
#include "ui/gfx/path.h"
#include "ui/views/background.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/button/image_button.h"
#include "ui/views/layout/grid_layout.h"
#include "ui/views/layout/layout_manager.h"
#include "ui/views/layout/layout_constants.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"

namespace {

typedef ConstrainedWindowFrameSimple::HeaderViews HeaderViews;

// A layout manager that lays out the header view with proper padding,
// and sized to the widget's client view.
class HeaderLayout : public views::LayoutManager {
 public:
  explicit HeaderLayout(views::Widget* container) : container_(container) {}
  virtual ~HeaderLayout() {}

  // Overridden from LayoutManager
  virtual void Layout(views::View* host);
  virtual gfx::Size GetPreferredSize(views::View* host);

 private:
  views::Widget* container_;

  DISALLOW_COPY_AND_ASSIGN(HeaderLayout);
};

void HeaderLayout::Layout(views::View* host) {
  if (!host->has_children())
    return;

  int horizontal_padding = ConstrainedWindow::kHorizontalPadding;
  int vertical_padding = ConstrainedWindow::kVerticalPadding;
  int row_padding = ConstrainedWindow::kRowPadding;

  views::View* header = host->child_at(0);
  gfx::Size preferred_size = GetPreferredSize(host);
  int width = preferred_size.width() - 2 * horizontal_padding;
  int height = preferred_size.height() - vertical_padding - row_padding;

  header->SetBounds(horizontal_padding, vertical_padding, width, height);
}

gfx::Size HeaderLayout::GetPreferredSize(views::View* host) {
  int horizontal_padding = ConstrainedWindow::kHorizontalPadding;
  int vertical_padding = ConstrainedWindow::kVerticalPadding;
  int row_padding = ConstrainedWindow::kRowPadding;

  views::View* header = host->child_at(0);
  views::View* client_view = container_->client_view();

  gfx::Size header_size = header ? header->GetPreferredSize() : gfx::Size();
  gfx::Size client_size =
      client_view ? client_view->GetPreferredSize() : gfx::Size();
  int width = std::max(client_size.width(), header_size.width()) +
      2 * horizontal_padding;
  int height = vertical_padding + header_size.height() + row_padding;
  return gfx::Size(width, height);
}

}  // namespace

ConstrainedWindowFrameSimple::HeaderViews::HeaderViews(
    views::View* header,
    views::Label* title_label,
    views::Button* close_button)
    : header(header),
      title_label(title_label),
      close_button(close_button) {
  DCHECK(header);
}

ConstrainedWindowFrameSimple::ConstrainedWindowFrameSimple(
    ConstrainedWindowViews* container)
    : container_(container) {
  container_->set_frame_type(views::Widget::FRAME_TYPE_FORCE_CUSTOM);

  layout_ = new HeaderLayout(container_);
  SetLayoutManager(layout_);

  SetHeaderView(CreateDefaultHeaderView());

  set_background(views::Background::CreateSolidBackground(
      ConstrainedWindow::GetBackgroundColor()));
}

ConstrainedWindowFrameSimple::~ConstrainedWindowFrameSimple() {
}

void ConstrainedWindowFrameSimple::SetHeaderView(HeaderViews* header_views)
{
  RemoveAllChildViews(true);

  header_views_.reset(header_views);

  AddChildView(header_views_->header);
}

HeaderViews* ConstrainedWindowFrameSimple::CreateDefaultHeaderView() {
  views::View* header_view = new views::View;

  views::GridLayout* grid_layout = new views::GridLayout(header_view);
  header_view->SetLayoutManager(grid_layout);

  views::ColumnSet* header_cs = grid_layout->AddColumnSet(0);
  header_cs->AddColumn(views::GridLayout::CENTER, views::GridLayout::CENTER, 0,
                       views::GridLayout::USE_PREF, 0, 0);  // Title.
  header_cs->AddPaddingColumn(1, views::kUnrelatedControlHorizontalSpacing);
  header_cs->AddColumn(views::GridLayout::CENTER, views::GridLayout::CENTER, 0,
                       views::GridLayout::USE_PREF, 0, 0);  // Close Button.

  // Header row.
  ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
  grid_layout->StartRow(0, 0);
  views::Label* title_label = new views::Label();
  title_label->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
  title_label->SetFont(rb.GetFont(ConstrainedWindow::kTitleFontStyle));
  title_label->SetEnabledColor(ConstrainedWindow::GetTextColor());
  title_label->SetText(container_->widget_delegate()->GetWindowTitle());
  grid_layout->AddView(title_label);

  views::Button* close_button = CreateCloseButton();
  grid_layout->AddView(close_button);

  return new HeaderViews(header_view, title_label, close_button);
}

gfx::Rect ConstrainedWindowFrameSimple::GetBoundsForClientView() const {
  int horizontal_padding = ConstrainedWindow::kHorizontalPadding;
  int vertical_padding = ConstrainedWindow::kVerticalPadding;
  int row_padding = ConstrainedWindow::kRowPadding;
  gfx::Size header_size =
      header_views_->header ?
      header_views_->header->GetPreferredSize() : gfx::Size();

  return gfx::Rect(horizontal_padding,
                   vertical_padding + header_size.height() + row_padding,
                   std::max(0, width() - 2 * horizontal_padding),
                   std::max(0, (height() - 2 * vertical_padding -
                                header_size.height() - row_padding)));
}

gfx::Rect ConstrainedWindowFrameSimple::GetWindowBoundsForClientBounds(
    const gfx::Rect& client_bounds) const {
  int horizontal_padding = ConstrainedWindow::kHorizontalPadding;
  int vertical_padding = ConstrainedWindow::kVerticalPadding;
  int row_padding = ConstrainedWindow::kRowPadding;
  gfx::Size header_size =
      header_views_->header ?
      header_views_->header->GetPreferredSize() : gfx::Size();

  int x = client_bounds.x() - horizontal_padding;
  int y = client_bounds.y() - vertical_padding - header_size.height() -
      row_padding;
  int width = client_bounds.width() + 2 * horizontal_padding;
  int height = client_bounds.height() + 2 * vertical_padding +
      header_size.height() + row_padding;

  return gfx::Rect(x, y, width, height);
}

int ConstrainedWindowFrameSimple::NonClientHitTest(const gfx::Point& point) {
  if (!bounds().Contains(point))
    return HTNOWHERE;
  return HTCLIENT;
}

void ConstrainedWindowFrameSimple::GetWindowMask(const gfx::Size& size,
                                                 gfx::Path* window_mask) {
#if defined(USE_AURA)
  SkRect rect = {0, 0, size.width() - 1, size.height() - 1};
#else
  // There appears to be a bug in the window mask calculation on Windows
  // which causes the width, but not the height, to be off by one.
  SkRect rect = {0, 0, size.width(), size.height() - 1};
#endif
  SkScalar radius = SkIntToScalar(ConstrainedWindow::kBorderRadius);
  SkScalar radii[8] = {radius, radius, radius, radius,
                       radius, radius, radius, radius};

  // NB: We're not using the addRoundRect uniform radius overload as it
  // mishandles the bottom corners on Windows
  window_mask->addRoundRect(rect, radii);
}

void ConstrainedWindowFrameSimple::ResetWindowControls() {
}

void ConstrainedWindowFrameSimple::UpdateWindowIcon() {
}

void ConstrainedWindowFrameSimple::UpdateWindowTitle() {
  if (!header_views_->title_label)
    return;

  string16 text = container_->widget_delegate()->GetWindowTitle();
  header_views_->title_label->SetText(text);
}

gfx::Size ConstrainedWindowFrameSimple::GetPreferredSize() {
  return container_->non_client_view()->GetWindowBoundsForClientBounds(
      gfx::Rect(container_->client_view()->GetPreferredSize())).size();
}

void ConstrainedWindowFrameSimple::ButtonPressed(views::Button* sender,
                                                 const ui::Event& event) {
  if (header_views_->close_button && sender == header_views_->close_button)
    sender->GetWidget()->Close();
}

views::ImageButton* ConstrainedWindowFrameSimple::CreateCloseButton() {
  ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
  views::ImageButton* close_button = new views::ImageButton(this);
  close_button->SetImage(views::CustomButton::BS_NORMAL,
                          rb.GetImageSkiaNamed(IDR_SHARED_IMAGES_X));
  close_button->SetImage(views::CustomButton::BS_HOT,
                          rb.GetImageSkiaNamed(IDR_SHARED_IMAGES_X_HOVER));
  close_button->SetImage(views::CustomButton::BS_PUSHED,
                          rb.GetImageSkiaNamed(IDR_SHARED_IMAGES_X_HOVER));
  return close_button;
}
<|endoftext|>