<commit_before>
#include "ksp_plugin/planetarium.hpp"

#include <vector>

#include "geometry/point.hpp"
#include "quantities/elementary_functions.hpp"

namespace principia {
namespace ksp_plugin {
namespace internal_planetarium {

using geometry::Position;
using geometry::RP2Line;
using geometry::Velocity;
using quantities::Pow;
using quantities::Sin;
using quantities::Sqrt;
using quantities::Tan;
using quantities::Time;

Planetarium::Parameters::Parameters(double const sphere_radius_multiplier,
                                    Angle const& angular_resolution,
                                    Angle const& field_of_view)
    : sphere_radius_multiplier_(sphere_radius_multiplier),
      sin²_angular_resolution_(Pow<2>(Sin(angular_resolution))),
      tan_angular_resolution_(Tan(angular_resolution)),
      tan_field_of_view_(Tan(field_of_view)) {}

Planetarium::Planetarium(
    Parameters const& parameters,
    Perspective<Navigation, Camera, Length, OrthogonalMap> const& perspective,
    not_null<Ephemeris<Barycentric> const*> const ephemeris,
    not_null<NavigationFrame const*> const plotting_frame)
    : parameters_(parameters),
      perspective_(perspective),
      ephemeris_(ephemeris),
      plotting_frame_(plotting_frame) {}

RP2Lines<Length, Camera> Planetarium::PlotMethod0(
    DiscreteTrajectory<Barycentric>::Iterator const& begin,
    DiscreteTrajectory<Barycentric>::Iterator const& end,
    Instant const& now) const {
  auto const plottable_spheres = ComputePlottableSpheres(now);
  auto const plottable_segments = ComputePlottableSegments(plottable_spheres,
                                                           begin, end);

  auto const field_of_view_radius² =
      perspective_.focal() * perspective_.focal() *
      parameters_.tan_field_of_view_ * parameters_.tan_field_of_view_;
  std::experimental::optional<Position<Navigation>> previous_position;
  RP2Lines<Length, Camera> rp2_lines;
  for (auto const& plottable_segment : plottable_segments) {
    // Apply the projection to the current plottable segment.
    auto const rp2_first = perspective_(plottable_segment.first);
    auto const rp2_second = perspective_(plottable_segment.second);

    // If the segment is entirely outside the field of view, ignore it.
    Length const x1 = rp2_first.x();
    Length const y1 = rp2_first.y();
    Length const x2 = rp2_second.x();
    Length const y2 = rp2_second.y();
    if (x1 * x1 + y1 * y1 > field_of_view_radius² &&
        x2 * x2 + y2 * y2 > field_of_view_radius²) {
      continue;
    }

    // Create a new ℝP² line when two segments are not consecutive.  Don't
    // compare ℝP² points for equality, that's expensive.
    bool const are_consecutive =
        previous_position == plottable_segment.first;
    previous_position = plottable_segment.second;

    if (are_consecutive) {
      rp2_lines.back().push_back(rp2_second);
    } else {
      RP2Line<Length, Camera> const rp2_line = {rp2_first, rp2_second};
      rp2_lines.push_back(rp2_line);
    }
  }
  return rp2_lines;
}

RP2Lines<Length, Camera> Planetarium::PlotMethod1(
    DiscreteTrajectory<Barycentric>::Iterator const& begin,
    DiscreteTrajectory<Barycentric>::Iterator const& end,
    Instant const& now) const {
  Length const focal_plane_tolerance =
      perspective_.focal() * parameters_.tan_angular_resolution_;
  auto const focal_plane_tolerance² =
      focal_plane_tolerance * focal_plane_tolerance;

  auto const rp2_lines = PlotMethod0(begin, end, now);

  int skipped = 0;
  int total = 0;
  RP2Lines<Length, Camera> new_rp2_lines;
  for (auto const& rp2_line : rp2_lines) {
    RP2Line<Length, Camera> new_rp2_line;
    std::experimental::optional<RP2Point<Length, Camera>> start_rp2_point;
    for (int i = 0; i < rp2_line.size(); ++i) {
      RP2Point<Length, Camera> const& rp2_point = rp2_line[i];
      if (i == 0) {
        new_rp2_line.push_back(rp2_point);
        start_rp2_point = rp2_point;
      } else if (Pow<2>(rp2_point.x() - start_rp2_point->x()) +
                 Pow<2>(rp2_point.y() - start_rp2_point->y()) >
                     focal_plane_tolerance²) {
        // TODO(phl): This creates a segment if the tolerance is exceeded.  It
        // should probably create a segment that stays just below the tolerance.
        new_rp2_line.push_back(rp2_point);
        start_rp2_point = rp2_point;
      } else if (i == rp2_line.size() - 1) {
        new_rp2_line.push_back(rp2_point);
      } else {
        ++skipped;
      }
      ++total;
    }
    new_rp2_lines.push_back(std::move(new_rp2_line));
  }
  LOG(INFO) << "PlotMethod1 skipped " << skipped << " points out of " << total
            << ".";
  return new_rp2_lines;
}

RP2Lines<Length, Camera> Planetarium::PlotMethod2(
    DiscreteTrajectory<Barycentric>::Iterator const& begin,
    DiscreteTrajectory<Barycentric>::Iterator const& end,
    Instant const& now) const {
  RP2Lines<Length, Camera> lines;
  if (begin == end) {
    return lines;
  }
  auto last = end;
  --last;
  if (begin == last) {
    return lines;
  }

  auto const plottable_spheres = ComputePlottableSpheres(now);

  auto const final_time = last.time();
  auto const& trajectory = *begin.trajectory();

  double const tan²_angular_resolution =
      Pow<2>(parameters_.tan_angular_resolution_);

  auto previous_time = begin.time();
  auto previous_degrees_of_freedom = begin.degrees_of_freedom();

  Position<Navigation> previous_position;
  Velocity<Navigation> previous_velocity;
  Time Δt;

  previous_position =
      plotting_frame_->ToThisFrameAtTime(previous_time)
          .rigid_transformation()(previous_degrees_of_freedom.position());
  previous_velocity =
      plotting_frame_->ToThisFrameAtTime(previous_time)
          .orthogonal_map()(previous_degrees_of_freedom.velocity());

  Δt = final_time - previous_time;

  Instant t;
  double estimated_tan²_error;
  Position<Navigation> position_in_navigation;
  Displacement<Camera> displacement_from_camera;

  std::experimental::optional<Position<Navigation>> last_endpoint;

  int steps_accepted = 0;
  int steps_attempted = 0;

  goto estimate_tan²_error;

  while (previous_time < final_time) {
    do {
      Δt *= 0.9 * Sqrt(Sqrt(tan²_angular_resolution / estimated_tan²_error));
    estimate_tan²_error:
      t = previous_time + Δt;
      if (t > final_time) {
        t = final_time;
        Δt = t - previous_time;
      }
      Position<Navigation> const estimated_position =
          previous_position + previous_velocity * Δt;

      position_in_navigation =
          plotting_frame_->ToThisFrameAtTime(t).rigid_transformation()(
              trajectory.EvaluatePosition(t));

      estimated_tan²_error =
          perspective_.Tan²AngularDistance(estimated_position,
                                           position_in_navigation);
      ++steps_attempted;
    } while (estimated_tan²_error > tan²_angular_resolution);
    ++steps_accepted;
    auto const segments =
        perspective_.VisibleSegments(
            Segment<Displacement<Navigation>>(previous_position,
                                              position_in_navigation),
            plottable_spheres);
    for (auto const& full_segment : segments) {
      // TODO(egg): also limit to field of view.
      auto const segment = perspective_.SegmentBehindFocalPlane(full_segment);
      if (!segment) {
        continue;
      }
      if (last_endpoint != segment->first) {
        lines.emplace_back();
        lines.back().push_back(perspective_(segment->first));
      }
      lines.back().push_back(perspective_(segment->second));
      last_endpoint = segment->second;
    }

    previous_time = t;
    previous_position = position_in_navigation;
    previous_velocity =
        plotting_frame_->ToThisFrameAtTime(t).orthogonal_map()(
            trajectory.EvaluateVelocity(t));
  }
  LOG(INFO) << "PlotMethod2 took " << steps_accepted << " steps, attempted "
            << steps_attempted << " steps.";
  return lines;
}

std::vector<Sphere<Length, Navigation>> Planetarium::ComputePlottableSpheres(
    Instant const& now) const {
  RigidMotion<Barycentric, Navigation> const rigid_motion_at_now =
      plotting_frame_->ToThisFrameAtTime(now);
  std::vector<Sphere<Length, Navigation>> plottable_spheres;

  auto const& bodies = ephemeris_->bodies();
  for (auto const body : bodies) {
    auto const trajectory = ephemeris_->trajectory(body);
    Length const mean_radius = body->mean_radius();
    Position<Barycentric> const centre_in_barycentric =
        trajectory->EvaluatePosition(now);
    Sphere<Length, Navigation> plottable_sphere(
        rigid_motion_at_now.rigid_transformation()(centre_in_barycentric),
        parameters_.sphere_radius_multiplier_ * mean_radius);
    // If the sphere is seen under an angle that is very small it doesn't
    // participate in hiding.
    if (perspective_.SphereSin²HalfAngle(plottable_sphere) >
        parameters_.sin²_angular_resolution_) {
      plottable_spheres.emplace_back(std::move(plottable_sphere));
    }
  }
  return plottable_spheres;
}

Segments<Displacement<Navigation>> Planetarium::ComputePlottableSegments(
    const std::vector<Sphere<Length, Navigation>>& plottable_spheres,
    DiscreteTrajectory<Barycentric>::Iterator const& begin,
    DiscreteTrajectory<Barycentric>::Iterator const& end) const {
  std::vector<Segment<Displacement<Navigation>>> all_segments;
  if (begin == end) {
    return all_segments;
  }
  auto it1 = begin;
  Instant t1 = it1.time();
  RigidMotion<Barycentric, Navigation> rigid_motion_at_t1 =
      plotting_frame_->ToThisFrameAtTime(t1);
  Position<Navigation> p1 =
      rigid_motion_at_t1(it1.degrees_of_freedom()).position();

  auto it2 = it1;
  while (++it2 != end) {
    // Processing one segment of the trajectory.
    Instant const t2 = it2.time();

    // Transform the degrees of freedom to the plotting frame.
    RigidMotion<Barycentric, Navigation> const rigid_motion_at_t2 =
        plotting_frame_->ToThisFrameAtTime(t2);
    Position<Navigation> const p2 =
        rigid_motion_at_t2(it2.degrees_of_freedom()).position();

    // Find the part of the segment that is behind the focal plane.  We don't
    // care about things that are in front of the focal plane.
    const Segment<Displacement<Navigation>> segment = {p1, p2};
    auto const segment_behind_focal_plane =
        perspective_.SegmentBehindFocalPlane(segment);
    if (segment_behind_focal_plane) {
      // Find the part(s) of the segment that are not hidden by spheres.  These
      // are the ones we want to plot.
      auto segments = perspective_.VisibleSegments(*segment_behind_focal_plane,
                                                   plottable_spheres);
      std::move(segments.begin(),
                segments.end(),
                std::back_inserter(all_segments));
    }

    it1 = it2;
    t1 = t2;
    rigid_motion_at_t1 = rigid_motion_at_t2;
    p1 = p2;
  }

  return all_segments;
}

}  // namespace internal_planetarium
}  // namespace ksp_plugin
}  // namespace principia
<commit_msg>yet more cleanup<commit_after>
#include "ksp_plugin/planetarium.hpp"

#include <vector>

#include "geometry/point.hpp"
#include "quantities/elementary_functions.hpp"

namespace principia {
namespace ksp_plugin {
namespace internal_planetarium {

using geometry::Position;
using geometry::RP2Line;
using geometry::Velocity;
using quantities::Pow;
using quantities::Sin;
using quantities::Sqrt;
using quantities::Tan;
using quantities::Time;

Planetarium::Parameters::Parameters(double const sphere_radius_multiplier,
                                    Angle const& angular_resolution,
                                    Angle const& field_of_view)
    : sphere_radius_multiplier_(sphere_radius_multiplier),
      sin²_angular_resolution_(Pow<2>(Sin(angular_resolution))),
      tan_angular_resolution_(Tan(angular_resolution)),
      tan_field_of_view_(Tan(field_of_view)) {}

Planetarium::Planetarium(
    Parameters const& parameters,
    Perspective<Navigation, Camera, Length, OrthogonalMap> const& perspective,
    not_null<Ephemeris<Barycentric> const*> const ephemeris,
    not_null<NavigationFrame const*> const plotting_frame)
    : parameters_(parameters),
      perspective_(perspective),
      ephemeris_(ephemeris),
      plotting_frame_(plotting_frame) {}

RP2Lines<Length, Camera> Planetarium::PlotMethod0(
    DiscreteTrajectory<Barycentric>::Iterator const& begin,
    DiscreteTrajectory<Barycentric>::Iterator const& end,
    Instant const& now) const {
  auto const plottable_spheres = ComputePlottableSpheres(now);
  auto const plottable_segments = ComputePlottableSegments(plottable_spheres,
                                                           begin, end);

  auto const field_of_view_radius² =
      perspective_.focal() * perspective_.focal() *
      parameters_.tan_field_of_view_ * parameters_.tan_field_of_view_;
  std::experimental::optional<Position<Navigation>> previous_position;
  RP2Lines<Length, Camera> rp2_lines;
  for (auto const& plottable_segment : plottable_segments) {
    // Apply the projection to the current plottable segment.
    auto const rp2_first = perspective_(plottable_segment.first);
    auto const rp2_second = perspective_(plottable_segment.second);

    // If the segment is entirely outside the field of view, ignore it.
    Length const x1 = rp2_first.x();
    Length const y1 = rp2_first.y();
    Length const x2 = rp2_second.x();
    Length const y2 = rp2_second.y();
    if (x1 * x1 + y1 * y1 > field_of_view_radius² &&
        x2 * x2 + y2 * y2 > field_of_view_radius²) {
      continue;
    }

    // Create a new ℝP² line when two segments are not consecutive.  Don't
    // compare ℝP² points for equality, that's expensive.
    bool const are_consecutive =
        previous_position == plottable_segment.first;
    previous_position = plottable_segment.second;

    if (are_consecutive) {
      rp2_lines.back().push_back(rp2_second);
    } else {
      RP2Line<Length, Camera> const rp2_line = {rp2_first, rp2_second};
      rp2_lines.push_back(rp2_line);
    }
  }
  return rp2_lines;
}

RP2Lines<Length, Camera> Planetarium::PlotMethod1(
    DiscreteTrajectory<Barycentric>::Iterator const& begin,
    DiscreteTrajectory<Barycentric>::Iterator const& end,
    Instant const& now) const {
  Length const focal_plane_tolerance =
      perspective_.focal() * parameters_.tan_angular_resolution_;
  auto const focal_plane_tolerance² =
      focal_plane_tolerance * focal_plane_tolerance;

  auto const rp2_lines = PlotMethod0(begin, end, now);

  int skipped = 0;
  int total = 0;
  RP2Lines<Length, Camera> new_rp2_lines;
  for (auto const& rp2_line : rp2_lines) {
    RP2Line<Length, Camera> new_rp2_line;
    std::experimental::optional<RP2Point<Length, Camera>> start_rp2_point;
    for (int i = 0; i < rp2_line.size(); ++i) {
      RP2Point<Length, Camera> const& rp2_point = rp2_line[i];
      if (i == 0) {
        new_rp2_line.push_back(rp2_point);
        start_rp2_point = rp2_point;
      } else if (Pow<2>(rp2_point.x() - start_rp2_point->x()) +
                 Pow<2>(rp2_point.y() - start_rp2_point->y()) >
                     focal_plane_tolerance²) {
        // TODO(phl): This creates a segment if the tolerance is exceeded.  It
        // should probably create a segment that stays just below the tolerance.
        new_rp2_line.push_back(rp2_point);
        start_rp2_point = rp2_point;
      } else if (i == rp2_line.size() - 1) {
        new_rp2_line.push_back(rp2_point);
      } else {
        ++skipped;
      }
      ++total;
    }
    new_rp2_lines.push_back(std::move(new_rp2_line));
  }
  LOG(INFO) << "PlotMethod1 skipped " << skipped << " points out of " << total
            << ".";
  return new_rp2_lines;
}

RP2Lines<Length, Camera> Planetarium::PlotMethod2(
    DiscreteTrajectory<Barycentric>::Iterator const& begin,
    DiscreteTrajectory<Barycentric>::Iterator const& end,
    Instant const& now) const {
  RP2Lines<Length, Camera> lines;
  if (begin == end) {
    return lines;
  }
  auto last = end;
  --last;
  if (begin == last) {
    return lines;
  }

  auto const plottable_spheres = ComputePlottableSpheres(now);

  auto const final_time = last.time();
  auto const& trajectory = *begin.trajectory();

  double const tan²_angular_resolution =
      Pow<2>(parameters_.tan_angular_resolution_);

  auto previous_time = begin.time();
  auto previous_degrees_of_freedom = begin.degrees_of_freedom();

  Position<Navigation> previous_position;
  Velocity<Navigation> previous_velocity;
  Time Δt;

  previous_position =
      plotting_frame_->ToThisFrameAtTime(previous_time)
          .rigid_transformation()(previous_degrees_of_freedom.position());
  previous_velocity =
      plotting_frame_->ToThisFrameAtTime(previous_time)
          .orthogonal_map()(previous_degrees_of_freedom.velocity());

  Δt = final_time - previous_time;

  Instant t;
  double estimated_tan²_error;
  Position<Navigation> position;

  std::experimental::optional<Position<Navigation>> last_endpoint;

  int steps_accepted = 0;
  int steps_attempted = 0;

  goto estimate_tan²_error;

  while (previous_time < final_time) {
    do {
      Δt *= 0.9 * Sqrt(Sqrt(tan²_angular_resolution / estimated_tan²_error));
    estimate_tan²_error:
      t = previous_time + Δt;
      if (t > final_time) {
        t = final_time;
        Δt = t - previous_time;
      }
      Position<Navigation> const estimated_position =
          previous_position + previous_velocity * Δt;

      position = plotting_frame_->ToThisFrameAtTime(t).rigid_transformation()(
                     trajectory.EvaluatePosition(t));

      estimated_tan²_error =
          perspective_.Tan²AngularDistance(estimated_position,
                                           position);
      ++steps_attempted;
    } while (estimated_tan²_error > tan²_angular_resolution);
    ++steps_accepted;
    auto const segments =
        perspective_.VisibleSegments(
            Segment<Displacement<Navigation>>(previous_position,
                                              position),
            plottable_spheres);
    for (auto const& full_segment : segments) {
      // TODO(egg): also limit to field of view.
      auto const segment = perspective_.SegmentBehindFocalPlane(full_segment);
      if (!segment) {
        continue;
      }
      if (last_endpoint != segment->first) {
        lines.emplace_back();
        lines.back().push_back(perspective_(segment->first));
      }
      lines.back().push_back(perspective_(segment->second));
      last_endpoint = segment->second;
    }

    previous_position = position;
    previous_velocity = plotting_frame_->ToThisFrameAtTime(t).orthogonal_map()(
                            trajectory.EvaluateVelocity(t));
    previous_time = t;
  }
  LOG(INFO) << "PlotMethod2 took " << steps_accepted << " steps, attempted "
            << steps_attempted << " steps.";
  return lines;
}

std::vector<Sphere<Length, Navigation>> Planetarium::ComputePlottableSpheres(
    Instant const& now) const {
  RigidMotion<Barycentric, Navigation> const rigid_motion_at_now =
      plotting_frame_->ToThisFrameAtTime(now);
  std::vector<Sphere<Length, Navigation>> plottable_spheres;

  auto const& bodies = ephemeris_->bodies();
  for (auto const body : bodies) {
    auto const trajectory = ephemeris_->trajectory(body);
    Length const mean_radius = body->mean_radius();
    Position<Barycentric> const centre_in_barycentric =
        trajectory->EvaluatePosition(now);
    Sphere<Length, Navigation> plottable_sphere(
        rigid_motion_at_now.rigid_transformation()(centre_in_barycentric),
        parameters_.sphere_radius_multiplier_ * mean_radius);
    // If the sphere is seen under an angle that is very small it doesn't
    // participate in hiding.
    if (perspective_.SphereSin²HalfAngle(plottable_sphere) >
        parameters_.sin²_angular_resolution_) {
      plottable_spheres.emplace_back(std::move(plottable_sphere));
    }
  }
  return plottable_spheres;
}

Segments<Displacement<Navigation>> Planetarium::ComputePlottableSegments(
    const std::vector<Sphere<Length, Navigation>>& plottable_spheres,
    DiscreteTrajectory<Barycentric>::Iterator const& begin,
    DiscreteTrajectory<Barycentric>::Iterator const& end) const {
  std::vector<Segment<Displacement<Navigation>>> all_segments;
  if (begin == end) {
    return all_segments;
  }
  auto it1 = begin;
  Instant t1 = it1.time();
  RigidMotion<Barycentric, Navigation> rigid_motion_at_t1 =
      plotting_frame_->ToThisFrameAtTime(t1);
  Position<Navigation> p1 =
      rigid_motion_at_t1(it1.degrees_of_freedom()).position();

  auto it2 = it1;
  while (++it2 != end) {
    // Processing one segment of the trajectory.
    Instant const t2 = it2.time();

    // Transform the degrees of freedom to the plotting frame.
    RigidMotion<Barycentric, Navigation> const rigid_motion_at_t2 =
        plotting_frame_->ToThisFrameAtTime(t2);
    Position<Navigation> const p2 =
        rigid_motion_at_t2(it2.degrees_of_freedom()).position();

    // Find the part of the segment that is behind the focal plane.  We don't
    // care about things that are in front of the focal plane.
    const Segment<Displacement<Navigation>> segment = {p1, p2};
    auto const segment_behind_focal_plane =
        perspective_.SegmentBehindFocalPlane(segment);
    if (segment_behind_focal_plane) {
      // Find the part(s) of the segment that are not hidden by spheres.  These
      // are the ones we want to plot.
      auto segments = perspective_.VisibleSegments(*segment_behind_focal_plane,
                                                   plottable_spheres);
      std::move(segments.begin(),
                segments.end(),
                std::back_inserter(all_segments));
    }

    it1 = it2;
    t1 = t2;
    rigid_motion_at_t1 = rigid_motion_at_t2;
    p1 = p2;
  }

  return all_segments;
}

}  // namespace internal_planetarium
}  // namespace ksp_plugin
}  // namespace principia
<|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 "base/process_util.h"
#include "base/test/test_timeouts.h"
#include "chrome/browser/service/service_process_control.h"
#include "chrome/browser/service/service_process_control_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/common/service_process_util.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"

class ServiceProcessControlBrowserTest
    : public InProcessBrowserTest {
 public:
  ServiceProcessControlBrowserTest()
      : service_process_handle_(base::kNullProcessHandle) {
  }
  ~ServiceProcessControlBrowserTest() {
    base::CloseProcessHandle(service_process_handle_);
    service_process_handle_ = base::kNullProcessHandle;
    // Delete all instances of ServiceProcessControl.
    ServiceProcessControlManager::GetInstance()->Shutdown();
  }

 protected:
  void LaunchServiceProcessControl() {
    ServiceProcessControl* process =
        ServiceProcessControlManager::GetInstance()->GetProcessControl(
            browser()->profile());
    process_ = process;

    // Launch the process asynchronously.
    process->Launch(
        NewRunnableMethod(
            this,
            &ServiceProcessControlBrowserTest::ProcessControlLaunched),
        NewRunnableMethod(
            this,
            &ServiceProcessControlBrowserTest::ProcessControlLaunchFailed));

    // Then run the message loop to keep things running.
    ui_test_utils::RunMessageLoop();
  }

  // Send a remoting host status request and wait reply from the service.
  void SendRequestAndWait() {
    process()->GetCloudPrintProxyStatus(NewCallback(
        this, &ServiceProcessControlBrowserTest::CloudPrintStatusCallback));
    ui_test_utils::RunMessageLoop();
  }

  void CloudPrintStatusCallback(
      bool enabled, std::string email) {
    MessageLoop::current()->Quit();
  }

  void Disconnect() {
    // This will delete all instances of ServiceProcessControl and close the IPC
    // connections.
    ServiceProcessControlManager::GetInstance()->Shutdown();
    process_ = NULL;
  }

  void WaitForShutdown() {
    EXPECT_TRUE(base::WaitForSingleProcess(
        service_process_handle_,
        TestTimeouts::wait_for_terminate_timeout_ms()));
  }

  void ProcessControlLaunched() {
    base::ProcessId service_pid = GetServiceProcessPid();
    EXPECT_NE(static_cast<base::ProcessId>(0), service_pid);
    EXPECT_TRUE(base::OpenProcessHandleWithAccess(
        service_pid,
        base::kProcessAccessWaitForTermination,
        &service_process_handle_));
    // Quit the current message. Post a QuitTask instead of just calling Quit()
    // because this can get invoked in the context of a Launch() call and we
    // may not be in Run() yet.
    MessageLoop::current()->PostTask(FROM_HERE, new MessageLoop::QuitTask());
  }

  void ProcessControlLaunchFailed() {
    ADD_FAILURE();
    // Quit the current message.
    MessageLoop::current()->PostTask(FROM_HERE, new MessageLoop::QuitTask());
  }

  ServiceProcessControl* process() { return process_; }

 private:
  ServiceProcessControl* process_;
  base::ProcessHandle service_process_handle_;
};

#if defined(OS_WIN)
// They way that the IPC is implemented only works on windows. This has to
// change when we implement a different scheme for IPC.
// Times out flakily, http://crbug.com/70076.
IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest,
                       DISABLED_LaunchAndIPC) {
  LaunchServiceProcessControl();

  // Make sure we are connected to the service process.
  EXPECT_TRUE(process()->is_connected());
  SendRequestAndWait();

  // And then shutdown the service process.
  EXPECT_TRUE(process()->Shutdown());
}

// This tests the case when a service process is launched when browser
// starts but we try to launch it again in the remoting setup dialog.
IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest, LaunchTwice) {
  // Launch the service process the first time.
  LaunchServiceProcessControl();

  // Make sure we are connected to the service process.
  EXPECT_TRUE(process()->is_connected());
  SendRequestAndWait();

  // Launch the service process again.
  LaunchServiceProcessControl();
  EXPECT_TRUE(process()->is_connected());
  SendRequestAndWait();

  // And then shutdown the service process.
  EXPECT_TRUE(process()->Shutdown());
}

static void DecrementUntilZero(int* count) {
  (*count)--;
  if (!(*count))
    MessageLoop::current()->PostTask(FROM_HERE, new MessageLoop::QuitTask());
}

// Invoke multiple Launch calls in succession and ensure that all the tasks
// get invoked.
IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest, MultipleLaunchTasks) {
  ServiceProcessControl* process =
      ServiceProcessControlManager::GetInstance()->GetProcessControl(
          browser()->profile());
  int launch_count = 5;
  for (int i = 0; i < launch_count; i++) {
    // Launch the process asynchronously.
    process->Launch(
        NewRunnableFunction(&DecrementUntilZero, &launch_count),
        new MessageLoop::QuitTask());
  }
  // Then run the message loop to keep things running.
  ui_test_utils::RunMessageLoop();
  EXPECT_EQ(0, launch_count);
  // And then shutdown the service process.
  EXPECT_TRUE(process->Shutdown());
}

// Make sure using the same task for success and failure tasks works.
IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest, SameLaunchTask) {
  ServiceProcessControl* process =
      ServiceProcessControlManager::GetInstance()->GetProcessControl(
          browser()->profile());
  int launch_count = 5;
  for (int i = 0; i < launch_count; i++) {
    // Launch the process asynchronously.
    Task * task = NewRunnableFunction(&DecrementUntilZero, &launch_count);
    process->Launch(task, task);
  }
  // Then run the message loop to keep things running.
  ui_test_utils::RunMessageLoop();
  EXPECT_EQ(0, launch_count);
  // And then shutdown the service process.
  EXPECT_TRUE(process->Shutdown());
}

// Tests whether disconnecting from the service IPC causes the service process
// to die.
IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest, DieOnDisconnect) {
  // Launch the service process.
  LaunchServiceProcessControl();
  // Make sure we are connected to the service process.
  EXPECT_TRUE(process()->is_connected());
  Disconnect();
  WaitForShutdown();
}

IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest, ForceShutdown) {
  // Launch the service process.
  LaunchServiceProcessControl();
  // Make sure we are connected to the service process.
  EXPECT_TRUE(process()->is_connected());
  chrome::VersionInfo version_info;
  ForceServiceProcessShutdown(version_info.Version());
  WaitForShutdown();
}

IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest, CheckPid) {
  EXPECT_EQ(0, GetServiceProcessPid());
  // Launch the service process.
  LaunchServiceProcessControl();
  EXPECT_NE(static_cast<base::ProcessId>(0), GetServiceProcessPid());
}

#endif

DISABLE_RUNNABLE_METHOD_REFCOUNT(ServiceProcessControlBrowserTest);
<commit_msg>Disable forceshutdown. TEST=none BUG=70793 Review URL: http://codereview.chromium.org/6293019<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 "base/process_util.h"
#include "base/test/test_timeouts.h"
#include "chrome/browser/service/service_process_control.h"
#include "chrome/browser/service/service_process_control_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/common/service_process_util.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"

class ServiceProcessControlBrowserTest
    : public InProcessBrowserTest {
 public:
  ServiceProcessControlBrowserTest()
      : service_process_handle_(base::kNullProcessHandle) {
  }
  ~ServiceProcessControlBrowserTest() {
    base::CloseProcessHandle(service_process_handle_);
    service_process_handle_ = base::kNullProcessHandle;
    // Delete all instances of ServiceProcessControl.
    ServiceProcessControlManager::GetInstance()->Shutdown();
  }

 protected:
  void LaunchServiceProcessControl() {
    ServiceProcessControl* process =
        ServiceProcessControlManager::GetInstance()->GetProcessControl(
            browser()->profile());
    process_ = process;

    // Launch the process asynchronously.
    process->Launch(
        NewRunnableMethod(
            this,
            &ServiceProcessControlBrowserTest::ProcessControlLaunched),
        NewRunnableMethod(
            this,
            &ServiceProcessControlBrowserTest::ProcessControlLaunchFailed));

    // Then run the message loop to keep things running.
    ui_test_utils::RunMessageLoop();
  }

  // Send a remoting host status request and wait reply from the service.
  void SendRequestAndWait() {
    process()->GetCloudPrintProxyStatus(NewCallback(
        this, &ServiceProcessControlBrowserTest::CloudPrintStatusCallback));
    ui_test_utils::RunMessageLoop();
  }

  void CloudPrintStatusCallback(
      bool enabled, std::string email) {
    MessageLoop::current()->Quit();
  }

  void Disconnect() {
    // This will delete all instances of ServiceProcessControl and close the IPC
    // connections.
    ServiceProcessControlManager::GetInstance()->Shutdown();
    process_ = NULL;
  }

  void WaitForShutdown() {
    EXPECT_TRUE(base::WaitForSingleProcess(
        service_process_handle_,
        TestTimeouts::wait_for_terminate_timeout_ms()));
  }

  void ProcessControlLaunched() {
    base::ProcessId service_pid = GetServiceProcessPid();
    EXPECT_NE(static_cast<base::ProcessId>(0), service_pid);
    EXPECT_TRUE(base::OpenProcessHandleWithAccess(
        service_pid,
        base::kProcessAccessWaitForTermination,
        &service_process_handle_));
    // Quit the current message. Post a QuitTask instead of just calling Quit()
    // because this can get invoked in the context of a Launch() call and we
    // may not be in Run() yet.
    MessageLoop::current()->PostTask(FROM_HERE, new MessageLoop::QuitTask());
  }

  void ProcessControlLaunchFailed() {
    ADD_FAILURE();
    // Quit the current message.
    MessageLoop::current()->PostTask(FROM_HERE, new MessageLoop::QuitTask());
  }

  ServiceProcessControl* process() { return process_; }

 private:
  ServiceProcessControl* process_;
  base::ProcessHandle service_process_handle_;
};

#if defined(OS_WIN)
// They way that the IPC is implemented only works on windows. This has to
// change when we implement a different scheme for IPC.
// Times out flakily, http://crbug.com/70076.
IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest,
                       DISABLED_LaunchAndIPC) {
  LaunchServiceProcessControl();

  // Make sure we are connected to the service process.
  EXPECT_TRUE(process()->is_connected());
  SendRequestAndWait();

  // And then shutdown the service process.
  EXPECT_TRUE(process()->Shutdown());
}

// This tests the case when a service process is launched when browser
// starts but we try to launch it again in the remoting setup dialog.
IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest, LaunchTwice) {
  // Launch the service process the first time.
  LaunchServiceProcessControl();

  // Make sure we are connected to the service process.
  EXPECT_TRUE(process()->is_connected());
  SendRequestAndWait();

  // Launch the service process again.
  LaunchServiceProcessControl();
  EXPECT_TRUE(process()->is_connected());
  SendRequestAndWait();

  // And then shutdown the service process.
  EXPECT_TRUE(process()->Shutdown());
}

static void DecrementUntilZero(int* count) {
  (*count)--;
  if (!(*count))
    MessageLoop::current()->PostTask(FROM_HERE, new MessageLoop::QuitTask());
}

// Invoke multiple Launch calls in succession and ensure that all the tasks
// get invoked.
IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest, MultipleLaunchTasks) {
  ServiceProcessControl* process =
      ServiceProcessControlManager::GetInstance()->GetProcessControl(
          browser()->profile());
  int launch_count = 5;
  for (int i = 0; i < launch_count; i++) {
    // Launch the process asynchronously.
    process->Launch(
        NewRunnableFunction(&DecrementUntilZero, &launch_count),
        new MessageLoop::QuitTask());
  }
  // Then run the message loop to keep things running.
  ui_test_utils::RunMessageLoop();
  EXPECT_EQ(0, launch_count);
  // And then shutdown the service process.
  EXPECT_TRUE(process->Shutdown());
}

// Make sure using the same task for success and failure tasks works.
IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest, SameLaunchTask) {
  ServiceProcessControl* process =
      ServiceProcessControlManager::GetInstance()->GetProcessControl(
          browser()->profile());
  int launch_count = 5;
  for (int i = 0; i < launch_count; i++) {
    // Launch the process asynchronously.
    Task * task = NewRunnableFunction(&DecrementUntilZero, &launch_count);
    process->Launch(task, task);
  }
  // Then run the message loop to keep things running.
  ui_test_utils::RunMessageLoop();
  EXPECT_EQ(0, launch_count);
  // And then shutdown the service process.
  EXPECT_TRUE(process->Shutdown());
}

// Tests whether disconnecting from the service IPC causes the service process
// to die.
IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest, DieOnDisconnect) {
  // Launch the service process.
  LaunchServiceProcessControl();
  // Make sure we are connected to the service process.
  EXPECT_TRUE(process()->is_connected());
  Disconnect();
  WaitForShutdown();
}

//http://code.google.com/p/chromium/issues/detail?id=70793
IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest,
                       DISABLED_ForceShutdown) {
  // Launch the service process.
  LaunchServiceProcessControl();
  // Make sure we are connected to the service process.
  EXPECT_TRUE(process()->is_connected());
  chrome::VersionInfo version_info;
  ForceServiceProcessShutdown(version_info.Version());
  WaitForShutdown();
}

IN_PROC_BROWSER_TEST_F(ServiceProcessControlBrowserTest, CheckPid) {
  EXPECT_EQ(0, GetServiceProcessPid());
  // Launch the service process.
  LaunchServiceProcessControl();
  EXPECT_NE(static_cast<base::ProcessId>(0), GetServiceProcessPid());
}

#endif

DISABLE_RUNNABLE_METHOD_REFCOUNT(ServiceProcessControlBrowserTest);
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2009 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "WebURLRequest.h"

#include "WebHTTPBody.h"
#include "WebHTTPHeaderVisitor.h"
#include "WebURL.h"
#include "WebURLRequestPrivate.h"

#include "ResourceRequest.h"

using namespace WebCore;

namespace WebKit {

// The standard implementation of WebURLRequestPrivate, which maintains
// ownership of a ResourceRequest instance.
class WebURLRequestPrivateImpl : public WebURLRequestPrivate {
public:
    WebURLRequestPrivateImpl()
    {
        m_resourceRequest = &m_resourceRequestAllocation;
    }

    WebURLRequestPrivateImpl(const WebURLRequestPrivate* p)
        : m_resourceRequestAllocation(*p->m_resourceRequest)
    {
        m_resourceRequest = &m_resourceRequestAllocation;
    }

    virtual void dispose() { delete this; }

    ResourceRequest m_resourceRequestAllocation;
};

void WebURLRequest::initialize()
{
    assign(new WebURLRequestPrivateImpl());
}

void WebURLRequest::reset()
{
    assign(0);
}

void WebURLRequest::assign(const WebURLRequest& r)
{
    assign(r.m_private ? new WebURLRequestPrivateImpl(r.m_private) : 0);
}

WebURL WebURLRequest::url() const
{
    return m_private->m_resourceRequest->url();
}

void WebURLRequest::setURL(const WebURL& url)
{
    m_private->m_resourceRequest->setURL(url);
}

WebURL WebURLRequest::firstPartyForCookies() const
{
    return m_private->m_resourceRequest->firstPartyForCookies();
}

void WebURLRequest::setFirstPartyForCookies(const WebURL& firstPartyForCookies)
{
    m_private->m_resourceRequest->setFirstPartyForCookies(firstPartyForCookies);
}

WebURLRequest::CachePolicy WebURLRequest::cachePolicy() const
{
    return static_cast<WebURLRequest::CachePolicy>(
        m_private->m_resourceRequest->cachePolicy());
}

void WebURLRequest::setCachePolicy(CachePolicy cachePolicy)
{
    m_private->m_resourceRequest->setCachePolicy(
        static_cast<ResourceRequestCachePolicy>(cachePolicy));
}

WebString WebURLRequest::httpMethod() const
{
    return m_private->m_resourceRequest->httpMethod();
}

void WebURLRequest::setHTTPMethod(const WebString& httpMethod)
{
    m_private->m_resourceRequest->setHTTPMethod(httpMethod);
}

WebString WebURLRequest::httpHeaderField(const WebString& name) const
{
    return m_private->m_resourceRequest->httpHeaderField(String(name));
}

void WebURLRequest::setHTTPHeaderField(const WebString& name, const WebString& value)
{
    m_private->m_resourceRequest->setHTTPHeaderField(String(name), value);
}

void WebURLRequest::addHTTPHeaderField(const WebString& name, const WebString& value)
{
    m_private->m_resourceRequest->addHTTPHeaderField(String(name), value);
}

void WebURLRequest::clearHTTPHeaderField(const WebString& name)
{
    // FIXME: Add a clearHTTPHeaderField method to ResourceRequest.
    const HTTPHeaderMap& map = m_private->m_resourceRequest->httpHeaderFields();
    const_cast<HTTPHeaderMap*>(&map)->remove(String(name));
}

void WebURLRequest::visitHTTPHeaderFields(WebHTTPHeaderVisitor* visitor) const
{
    const HTTPHeaderMap& map = m_private->m_resourceRequest->httpHeaderFields();
    for (HTTPHeaderMap::const_iterator it = map.begin(); it != map.end(); ++it)
        visitor->visitHeader(String(it->first), it->second);
}

WebHTTPBody WebURLRequest::httpBody() const
{
    return m_private->m_resourceRequest->httpBody();
}

void WebURLRequest::setHTTPBody(const WebHTTPBody& httpBody)
{
    m_private->m_resourceRequest->setHTTPBody(httpBody);
}

bool WebURLRequest::reportUploadProgress() const
{
    return m_private->m_resourceRequest->reportUploadProgress();
}

void WebURLRequest::setReportUploadProgress(bool reportUploadProgress)
{
    m_private->m_resourceRequest->setReportUploadProgress(reportUploadProgress);
}

WebURLRequest::TargetType WebURLRequest::targetType() const
{
    return static_cast<TargetType>(m_private->m_resourceRequest->targetType());
}

void WebURLRequest::setTargetType(TargetType targetType)
{
    m_private->m_resourceRequest->setTargetType(
        static_cast<ResourceRequest::TargetType>(targetType));
}

int WebURLRequest::requestorID() const
{
    return m_private->m_resourceRequest->requestorID();
}

void WebURLRequest::setRequestorID(int requestorID)
{
    m_private->m_resourceRequest->setRequestorID(requestorID);
}

int WebURLRequest::requestorProcessID() const
{
    return m_private->m_resourceRequest->requestorProcessID();
}

void WebURLRequest::setRequestorProcessID(int requestorProcessID)
{
    m_private->m_resourceRequest->setRequestorProcessID(requestorProcessID);
}

int WebURLRequest::appCacheContextID() const
{
    return m_private->m_resourceRequest->appCacheContextID();
}

void WebURLRequest::setAppCacheContextID(int appCacheContextID)
{
    m_private->m_resourceRequest->setAppCacheContextID(appCacheContextID);
}

WebCString WebURLRequest::securityInfo() const
{
    return m_private->m_resourceRequest->securityInfo();
}

void WebURLRequest::setSecurityInfo(const WebCString& securityInfo)
{
    m_private->m_resourceRequest->setSecurityInfo(securityInfo);
}

ResourceRequest& WebURLRequest::toMutableResourceRequest()
{
    ASSERT(m_private);
    ASSERT(m_private->m_resourceRequest);

    return *m_private->m_resourceRequest;
}

const ResourceRequest& WebURLRequest::toResourceRequest() const
{
    ASSERT(m_private);
    ASSERT(m_private->m_resourceRequest);

    return *m_private->m_resourceRequest;
}

void WebURLRequest::assign(WebURLRequestPrivate* p)
{
    if (m_private == p)
        return;
    if (m_private)
        m_private->dispose();
    m_private = p;
}

} // namespace WebKit
<commit_msg>Fix GCC bustage.  Part 2.<commit_after>/*
 * Copyright (C) 2009 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "WebURLRequest.h"

#include "WebHTTPBody.h"
#include "WebHTTPHeaderVisitor.h"
#include "WebURL.h"
#include "WebURLRequestPrivate.h"

#include "ResourceRequest.h"

using namespace WebCore;

namespace WebKit {

// The standard implementation of WebURLRequestPrivate, which maintains
// ownership of a ResourceRequest instance.
class WebURLRequestPrivateImpl : public WebURLRequestPrivate {
public:
    WebURLRequestPrivateImpl()
    {
        m_resourceRequest = &m_resourceRequestAllocation;
    }

    WebURLRequestPrivateImpl(const WebURLRequestPrivate* p)
        : m_resourceRequestAllocation(*p->m_resourceRequest)
    {
        m_resourceRequest = &m_resourceRequestAllocation;
    }

    virtual void dispose() { delete this; }

    ResourceRequest m_resourceRequestAllocation;
};

void WebURLRequest::initialize()
{
    assign(new WebURLRequestPrivateImpl());
}

void WebURLRequest::reset()
{
    assign(0);
}

void WebURLRequest::assign(const WebURLRequest& r)
{
    assign(r.m_private ? new WebURLRequestPrivateImpl(r.m_private) : 0);
}

WebURL WebURLRequest::url() const
{
    return m_private->m_resourceRequest->url();
}

void WebURLRequest::setURL(const WebURL& url)
{
    m_private->m_resourceRequest->setURL(url);
}

WebURL WebURLRequest::firstPartyForCookies() const
{
    return m_private->m_resourceRequest->firstPartyForCookies();
}

void WebURLRequest::setFirstPartyForCookies(const WebURL& firstPartyForCookies)
{
    m_private->m_resourceRequest->setFirstPartyForCookies(firstPartyForCookies);
}

WebURLRequest::CachePolicy WebURLRequest::cachePolicy() const
{
    return static_cast<WebURLRequest::CachePolicy>(
        m_private->m_resourceRequest->cachePolicy());
}

void WebURLRequest::setCachePolicy(CachePolicy cachePolicy)
{
    m_private->m_resourceRequest->setCachePolicy(
        static_cast<ResourceRequestCachePolicy>(cachePolicy));
}

WebString WebURLRequest::httpMethod() const
{
    return m_private->m_resourceRequest->httpMethod();
}

void WebURLRequest::setHTTPMethod(const WebString& httpMethod)
{
    m_private->m_resourceRequest->setHTTPMethod(httpMethod);
}

WebString WebURLRequest::httpHeaderField(const WebString& name) const
{
    return m_private->m_resourceRequest->httpHeaderField(String(name));
}

void WebURLRequest::setHTTPHeaderField(const WebString& name, const WebString& value)
{
    m_private->m_resourceRequest->setHTTPHeaderField(String(name), value);
}

void WebURLRequest::addHTTPHeaderField(const WebString& name, const WebString& value)
{
    m_private->m_resourceRequest->addHTTPHeaderField(String(name), value);
}

void WebURLRequest::clearHTTPHeaderField(const WebString& name)
{
    // FIXME: Add a clearHTTPHeaderField method to ResourceRequest.
    const HTTPHeaderMap& map = m_private->m_resourceRequest->httpHeaderFields();
    const_cast<HTTPHeaderMap*>(&map)->remove(String(name));
}

void WebURLRequest::visitHTTPHeaderFields(WebHTTPHeaderVisitor* visitor) const
{
    const HTTPHeaderMap& map = m_private->m_resourceRequest->httpHeaderFields();
    for (HTTPHeaderMap::const_iterator it = map.begin(); it != map.end(); ++it)
        visitor->visitHeader(String(it->first), it->second);
}

WebHTTPBody WebURLRequest::httpBody() const
{
    return WebHTTPBody(m_private->m_resourceRequest->httpBody());
}

void WebURLRequest::setHTTPBody(const WebHTTPBody& httpBody)
{
    m_private->m_resourceRequest->setHTTPBody(httpBody);
}

bool WebURLRequest::reportUploadProgress() const
{
    return m_private->m_resourceRequest->reportUploadProgress();
}

void WebURLRequest::setReportUploadProgress(bool reportUploadProgress)
{
    m_private->m_resourceRequest->setReportUploadProgress(reportUploadProgress);
}

WebURLRequest::TargetType WebURLRequest::targetType() const
{
    return static_cast<TargetType>(m_private->m_resourceRequest->targetType());
}

void WebURLRequest::setTargetType(TargetType targetType)
{
    m_private->m_resourceRequest->setTargetType(
        static_cast<ResourceRequest::TargetType>(targetType));
}

int WebURLRequest::requestorID() const
{
    return m_private->m_resourceRequest->requestorID();
}

void WebURLRequest::setRequestorID(int requestorID)
{
    m_private->m_resourceRequest->setRequestorID(requestorID);
}

int WebURLRequest::requestorProcessID() const
{
    return m_private->m_resourceRequest->requestorProcessID();
}

void WebURLRequest::setRequestorProcessID(int requestorProcessID)
{
    m_private->m_resourceRequest->setRequestorProcessID(requestorProcessID);
}

int WebURLRequest::appCacheContextID() const
{
    return m_private->m_resourceRequest->appCacheContextID();
}

void WebURLRequest::setAppCacheContextID(int appCacheContextID)
{
    m_private->m_resourceRequest->setAppCacheContextID(appCacheContextID);
}

WebCString WebURLRequest::securityInfo() const
{
    return m_private->m_resourceRequest->securityInfo();
}

void WebURLRequest::setSecurityInfo(const WebCString& securityInfo)
{
    m_private->m_resourceRequest->setSecurityInfo(securityInfo);
}

ResourceRequest& WebURLRequest::toMutableResourceRequest()
{
    ASSERT(m_private);
    ASSERT(m_private->m_resourceRequest);

    return *m_private->m_resourceRequest;
}

const ResourceRequest& WebURLRequest::toResourceRequest() const
{
    ASSERT(m_private);
    ASSERT(m_private->m_resourceRequest);

    return *m_private->m_resourceRequest;
}

void WebURLRequest::assign(WebURLRequestPrivate* p)
{
    if (m_private == p)
        return;
    if (m_private)
        m_private->dispose();
    m_private = p;
}

} // namespace WebKit
<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#pragma once

namespace etl {

/*!
 * \brief Wrapper used in the context to force an implementation to be used
 */
template<typename T>
struct forced_impl {
    T impl;              ///< The impl to be used (if forced == true)
    bool forced = false; ///< Indicate if forced or default
};

/*!
 * \brief The contextual configuration of ETL
 */
struct context {
    bool serial = false;   ///< Force serial execution
    bool parallel = false; ///< Force parallel execution

    forced_impl<scalar_impl> scalar_selector;       ///< Force selector for scalar operations
    forced_impl<sum_impl> sum_selector;             ///< Forced selector for sum
    forced_impl<transpose_impl> transpose_selector; ///< Forced selector for transpose
    forced_impl<dot_impl> dot_selector;             ///< Forced selector for dot
    forced_impl<conv_impl> conv_selector;           ///< Forced selector for conv
    forced_impl<gemm_impl> gemm_selector;           ///< Forced selector for gemm
    forced_impl<outer_impl> outer_selector;         ///< Forced selector for outer product
    forced_impl<fft_impl> fft_selector;             ///< Forced selector for fft
};

/*!
 * \brief Return the configuration context of the current thread.
 * \return the configuration context of the current thread
 */
inline context& local_context(){
    static thread_local context local_context;
    return local_context;
}

namespace detail {

template<typename T>
forced_impl<T>& get_forced_impl();

template<>
inline forced_impl<scalar_impl>& get_forced_impl(){
    return local_context().scalar_selector;
}

template<>
inline forced_impl<sum_impl>& get_forced_impl(){
    return local_context().sum_selector;
}

template<>
inline forced_impl<transpose_impl>& get_forced_impl(){
    return local_context().transpose_selector;
}

template<>
inline forced_impl<dot_impl>& get_forced_impl(){
    return local_context().dot_selector;
}

template<>
inline forced_impl<conv_impl>& get_forced_impl(){
    return local_context().conv_selector;
}

template<>
inline forced_impl<gemm_impl>& get_forced_impl(){
    return local_context().gemm_selector;
}

template<>
inline forced_impl<outer_impl>& get_forced_impl(){
    return local_context().outer_selector;
}

template<>
inline forced_impl<fft_impl>& get_forced_impl(){
    return local_context().fft_selector;
}

/*!
 * \brief RAII helper for setting the context to serial
 */
struct serial_context {
    bool old_serial;

    serial_context(){
        old_serial = etl::local_context().serial;
        etl::local_context().serial = true;
    }

    ~serial_context(){
        etl::local_context().serial = old_serial;
    }

    operator bool(){
        return true;
    }
};

/*!
 * \brief RAII helper for setting the context to parallel
 */
struct parallel_context {
    bool old_parallel;

    parallel_context(){
        old_parallel = etl::local_context().parallel;
        etl::local_context().parallel = true;
    }

    ~parallel_context(){
        etl::local_context().parallel = old_parallel;
    }

    operator bool(){
        return true;
    }
};

/*!
 * \brief RAII helper for setting the context to a selected
 * implementation
 */
template<typename Selector, Selector V>
struct selected_context {
    forced_impl<Selector> old_selector;

    selected_context(){
        decltype(auto) selector = get_forced_impl<Selector>();

        old_selector = selector;

        selector.impl = V;
        selector.forced = true;
    }

    ~selected_context(){
        get_forced_impl<Selector>() = old_selector;
    }

    operator bool(){
        return true;
    }
};

} //end of namespace detail

/*!
 * \brief Define the start of an ETL serial section
 */
#define SERIAL_SECTION if(auto etl_serial_context__ = etl::detail::serial_context())

/*!
 * \brief Define the start of an ETL parallel section
 */
#define PARALLEL_SECTION if(auto etl_parallel_context__ = etl::detail::parallel_context())

/*!
 * \brief Define the start of an ETL selected section
 */
#define SELECTED_SECTION(v) if(auto etl_selected_context__ = etl::detail::selected_context<decltype(v), v>())

} //end of namespace etl
<commit_msg>Complete the doc<commit_after>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#pragma once

namespace etl {

/*!
 * \brief Wrapper used in the context to force an implementation to be used
 */
template<typename T>
struct forced_impl {
    T impl;              ///< The impl to be used (if forced == true)
    bool forced = false; ///< Indicate if forced or default
};

/*!
 * \brief The contextual configuration of ETL
 */
struct context {
    bool serial = false;   ///< Force serial execution
    bool parallel = false; ///< Force parallel execution

    forced_impl<scalar_impl> scalar_selector;       ///< Force selector for scalar operations
    forced_impl<sum_impl> sum_selector;             ///< Forced selector for sum
    forced_impl<transpose_impl> transpose_selector; ///< Forced selector for transpose
    forced_impl<dot_impl> dot_selector;             ///< Forced selector for dot
    forced_impl<conv_impl> conv_selector;           ///< Forced selector for conv
    forced_impl<gemm_impl> gemm_selector;           ///< Forced selector for gemm
    forced_impl<outer_impl> outer_selector;         ///< Forced selector for outer product
    forced_impl<fft_impl> fft_selector;             ///< Forced selector for fft
};

/*!
 * \brief Return the configuration context of the current thread.
 * \return the configuration context of the current thread
 */
inline context& local_context(){
    static thread_local context local_context;
    return local_context;
}

namespace detail {

/*!
 * \brief Return the forced_impl of the local context for the given enumeration type
 * \tparam T The type of enumeration of implmentation
 * \return the forced_impl of the given type for the local context
 */
template<typename T>
forced_impl<T>& get_forced_impl();

/*!
 * \copydoc get_forced_impl
 */
template<>
inline forced_impl<scalar_impl>& get_forced_impl(){
    return local_context().scalar_selector;
}

/*!
 * \copydoc get_forced_impl
 */
template<>
inline forced_impl<sum_impl>& get_forced_impl(){
    return local_context().sum_selector;
}

/*!
 * \copydoc get_forced_impl
 */
template<>
inline forced_impl<transpose_impl>& get_forced_impl(){
    return local_context().transpose_selector;
}

/*!
 * \copydoc get_forced_impl
 */
template<>
inline forced_impl<dot_impl>& get_forced_impl(){
    return local_context().dot_selector;
}

/*!
 * \copydoc get_forced_impl
 */
template<>
inline forced_impl<conv_impl>& get_forced_impl(){
    return local_context().conv_selector;
}

/*!
 * \copydoc get_forced_impl
 */
template<>
inline forced_impl<gemm_impl>& get_forced_impl(){
    return local_context().gemm_selector;
}

/*!
 * \copydoc get_forced_impl
 */
template<>
inline forced_impl<outer_impl>& get_forced_impl(){
    return local_context().outer_selector;
}

/*!
 * \copydoc get_forced_impl
 */
template<>
inline forced_impl<fft_impl>& get_forced_impl(){
    return local_context().fft_selector;
}

/*!
 * \brief RAII helper for setting the context to serial
 */
struct serial_context {
    bool old_serial; ///< The previous value of serial

    /*!
     * \brief Default construct a serial context
     *
     * This saves the previous serial value and sets serial to true
     */
    serial_context(){
        old_serial = etl::local_context().serial;
        etl::local_context().serial = true;
    }

    /*!
     * \brief Destruct a serial context
     *
     * This restores the serial state
     */
    ~serial_context(){
        etl::local_context().serial = old_serial;
    }

    /*!
     * \brief Does nothing, simple trick for section to be nice
     */
    operator bool(){
        return true;
    }
};

/*!
 * \brief RAII helper for setting the context to parallel
 */
struct parallel_context {
    bool old_parallel; ///< The previous value of parallel

    /*!
     * \brief Default construct a parallel context
     *
     * This saves the previous parallel value and sets parallel to true
     */
    parallel_context(){
        old_parallel = etl::local_context().parallel;
        etl::local_context().parallel = true;
    }

    /*!
     * \brief Destruct a parallel context
     *
     * This restores the parallel state
     */
    ~parallel_context(){
        etl::local_context().parallel = old_parallel;
    }

    /*!
     * \brief Does nothing, simple trick for section to be nice
     */
    operator bool(){
        return true;
    }
};

/*!
 * \brief RAII helper for setting the context to a selected
 * implementation
 */
template<typename Selector, Selector V>
struct selected_context {
    forced_impl<Selector> old_selector; ///< The previous value of selector

    /*!
     * \brief Default construct a selected context
     *
     * This saves the previous selector value and sets selector to
     * the specified implementation.
     */
    selected_context(){
        decltype(auto) selector = get_forced_impl<Selector>();

        old_selector = selector;

        selector.impl = V;
        selector.forced = true;
    }

    /*!
     * \brief Destruct a selected context
     *
     * This restores the selector state
     */
    ~selected_context(){
        get_forced_impl<Selector>() = old_selector;
    }

    /*!
     * \brief Does nothing, simple trick for section to be nice
     */
    operator bool(){
        return true;
    }
};

} //end of namespace detail

/*!
 * \brief Define the start of an ETL serial section
 */
#define SERIAL_SECTION if(auto etl_serial_context__ = etl::detail::serial_context())

/*!
 * \brief Define the start of an ETL parallel section
 */
#define PARALLEL_SECTION if(auto etl_parallel_context__ = etl::detail::parallel_context())

/*!
 * \brief Define the start of an ETL selected section
 */
#define SELECTED_SECTION(v) if(auto etl_selected_context__ = etl::detail::selected_context<decltype(v), v>())

} //end of namespace etl
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2007 Apple Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "LocalizedStrings.h"
#include "PlatformString.h"
#include "IntSize.h"

#undef LOG
#include "webkit/glue/glue_util.h"
#include "webkit/glue/webkit_glue.h"
#include "base/logging.h"
#include "base/file_util.h"
#include "base/string_util.h"
#include "build/build_config.h"
#include "webkit/glue/glue_util.h"

#if defined(OS_WIN)
#include "webkit_strings.h"
#else
// TODO:(pinkerton): only windows has the GRIT machinery, so we've created a
// temporary generated header until we can figure out the l10n strategy.
#include "bogus_webkit_strings.h"
#endif

using namespace WebCore;

inline String GetLocalizedString(int message_id) {
  const std::wstring& str(webkit_glue::GetLocalizedString(message_id));
  return webkit_glue::StdWStringToString(str);
}

#if defined(OS_WIN)
String WebCore::searchableIndexIntroduction() {
  return GetLocalizedString(IDS_SEARCHABLE_INDEX_INTRO);
}
String WebCore::submitButtonDefaultLabel() {
  return GetLocalizedString(IDS_FORM_SUBMIT_LABEL);
}
String WebCore::inputElementAltText() {
  return GetLocalizedString(IDS_FORM_INPUT_ALT);
}
String WebCore::resetButtonDefaultLabel() {
  return GetLocalizedString(IDS_FORM_RESET_LABEL);
}
String WebCore::fileButtonChooseFileLabel() {
  return GetLocalizedString(IDS_FORM_FILE_BUTTON_LABEL);
}
String WebCore::fileButtonNoFileSelectedLabel() {
  return GetLocalizedString(IDS_FORM_FILE_NO_FILE_LABEL);
}

String WebCore::searchMenuNoRecentSearchesText() {
  return GetLocalizedString(IDS_RECENT_SEARCHES_NONE);
}
String WebCore::searchMenuRecentSearchesText() {
  return GetLocalizedString(IDS_RECENT_SEARCHES);
}
String WebCore::searchMenuClearRecentSearchesText() {
  return GetLocalizedString(IDS_RECENT_SEARCHES_CLEAR);
}

// A11y strings.
String WebCore::AXWebAreaText() {
  return GetLocalizedString(IDS_AX_ROLE_WEB_AREA);
}
String WebCore::AXLinkText() {
  return GetLocalizedString(IDS_AX_ROLE_LINK);
}
String WebCore::AXListMarkerText() {
  return GetLocalizedString(IDS_AX_ROLE_LIST_MARKER);
}
String WebCore::AXImageMapText() {
  return GetLocalizedString(IDS_AX_ROLE_IMAGE_MAP);
}
String WebCore::AXHeadingText() {
  return GetLocalizedString(IDS_AX_ROLE_HEADING);
}
#endif  // OS_WIN
String WebCore::AXButtonActionVerb() {
  return GetLocalizedString(IDS_AX_BUTTON_ACTION_VERB);
}
String WebCore::AXRadioButtonActionVerb() {
  return GetLocalizedString(IDS_AX_RADIO_BUTTON_ACTION_VERB);
}
String WebCore::AXTextFieldActionVerb() {
  return GetLocalizedString(IDS_AX_TEXT_FIELD_ACTION_VERB);
}
String WebCore::AXCheckedCheckBoxActionVerb() {
  return GetLocalizedString(IDS_AX_CHECKED_CHECK_BOX_ACTION_VERB);
}
String WebCore::AXUncheckedCheckBoxActionVerb() {
  return GetLocalizedString(IDS_AX_UNCHECKED_CHECK_BOX_ACTION_VERB);
}
String WebCore::AXLinkActionVerb() {
  return GetLocalizedString(IDS_AX_LINK_ACTION_VERB);
}

// Used in FTPDirectoryDocument.cpp
String WebCore::unknownFileSizeText() {
  return String();
}

// These two are used in FileChooserWin.cpp.
String WebCore::uploadFileText() {
  return String();
}
String WebCore::allFilesText() {
  return String();
}

// The following two functions are not declared in LocalizedStrings.h.
// They are used by the menu for the HTML keygen tag.
namespace WebCore {
String keygenMenuHighGradeKeySize() {
  return GetLocalizedString(IDS_KEYGEN_HIGH_GRADE_KEY);
}
String keygenMenuMediumGradeKeySize() {
  return GetLocalizedString(IDS_KEYGEN_MED_GRADE_KEY);
}

// Used in ImageDocument.cpp as the title for pages when that page is an image.
String WebCore::imageTitle(const String& filename, const IntSize& size) {
  // C3 97 is UTF-8 for U+00D7 (multiplication sign).
  std::string size_str = StringPrintf(" (%d\xC3\x97%d)",
                                      size.width(), size.height());
  return filename + webkit_glue::StdStringToString(size_str);
}

} //namespace WebCore

#if defined(OS_WIN)
// We don't use these strings, so they return an empty String. We can't just
// make them asserts because webcore still calls them.
String WebCore::contextMenuItemTagOpenLinkInNewWindow() { return String(); }
String WebCore::contextMenuItemTagDownloadLinkToDisk() { return String(); }
String WebCore::contextMenuItemTagCopyLinkToClipboard() { return String(); }
String WebCore::contextMenuItemTagOpenImageInNewWindow() { return String(); }
String WebCore::contextMenuItemTagDownloadImageToDisk() { return String(); }
String WebCore::contextMenuItemTagCopyImageToClipboard() { return String(); }
String WebCore::contextMenuItemTagOpenFrameInNewWindow() { return String(); }
String WebCore::contextMenuItemTagCopy() { return String(); }
String WebCore::contextMenuItemTagGoBack() { return String(); }
String WebCore::contextMenuItemTagGoForward() { return String(); }
String WebCore::contextMenuItemTagStop() { return String(); }
String WebCore::contextMenuItemTagReload() { return String(); }
String WebCore::contextMenuItemTagCut() { return String(); }
String WebCore::contextMenuItemTagPaste() { return String(); }
String WebCore::contextMenuItemTagNoGuessesFound() { return String(); }
String WebCore::contextMenuItemTagIgnoreSpelling() { return String(); }
String WebCore::contextMenuItemTagLearnSpelling() { return String(); }
String WebCore::contextMenuItemTagSearchWeb() { return String(); }
String WebCore::contextMenuItemTagLookUpInDictionary() { return String(); }
String WebCore::contextMenuItemTagOpenLink() { return String(); }
String WebCore::contextMenuItemTagIgnoreGrammar() { return String(); }
String WebCore::contextMenuItemTagSpellingMenu() { return String(); }
String WebCore::contextMenuItemTagCheckSpelling() { return String(); }
String WebCore::contextMenuItemTagCheckSpellingWhileTyping() { return String(); }
String WebCore::contextMenuItemTagCheckGrammarWithSpelling() { return String(); }
String WebCore::contextMenuItemTagFontMenu() { return String(); }
String WebCore::contextMenuItemTagBold() { return String(); }
String WebCore::contextMenuItemTagItalic() { return String(); }
String WebCore::contextMenuItemTagUnderline() { return String(); }
String WebCore::contextMenuItemTagOutline() { return String(); }
String WebCore::contextMenuItemTagWritingDirectionMenu() { return String(); }
String WebCore::contextMenuItemTagDefaultDirection() { return String(); }
String WebCore::contextMenuItemTagLeftToRight() { return String(); }
String WebCore::contextMenuItemTagRightToLeft() { return String(); }
String WebCore::contextMenuItemTagInspectElement() { return String(); }
String WebCore::contextMenuItemTagShowSpellingPanel(bool show) { return String(); }
#endif  // OS_WIN
<commit_msg>Update localized_strings.cc post-merge Review URL: http://codereview.chromium.org/6497<commit_after>/*
 * Copyright (C) 2007 Apple Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "LocalizedStrings.h"
#include "PlatformString.h"
#include "IntSize.h"

#undef LOG
#include "webkit/glue/glue_util.h"
#include "webkit/glue/webkit_glue.h"
#include "base/logging.h"
#include "base/file_util.h"
#include "base/string_util.h"
#include "build/build_config.h"
#include "webkit/glue/glue_util.h"

#if defined(OS_WIN)
#include "webkit_strings.h"
#else
// TODO:(pinkerton): only windows has the GRIT machinery, so we've created a
// temporary generated header until we can figure out the l10n strategy.
#include "bogus_webkit_strings.h"
#endif

using namespace WebCore;

inline String GetLocalizedString(int message_id) {
  const std::wstring& str(webkit_glue::GetLocalizedString(message_id));
  return webkit_glue::StdWStringToString(str);
}

#if defined(OS_WIN)
String WebCore::searchableIndexIntroduction() {
  return GetLocalizedString(IDS_SEARCHABLE_INDEX_INTRO);
}
String WebCore::submitButtonDefaultLabel() {
  return GetLocalizedString(IDS_FORM_SUBMIT_LABEL);
}
String WebCore::inputElementAltText() {
  return GetLocalizedString(IDS_FORM_INPUT_ALT);
}
String WebCore::resetButtonDefaultLabel() {
  return GetLocalizedString(IDS_FORM_RESET_LABEL);
}
String WebCore::fileButtonChooseFileLabel() {
  return GetLocalizedString(IDS_FORM_FILE_BUTTON_LABEL);
}
String WebCore::fileButtonNoFileSelectedLabel() {
  return GetLocalizedString(IDS_FORM_FILE_NO_FILE_LABEL);
}

String WebCore::searchMenuNoRecentSearchesText() {
  return GetLocalizedString(IDS_RECENT_SEARCHES_NONE);
}
String WebCore::searchMenuRecentSearchesText() {
  return GetLocalizedString(IDS_RECENT_SEARCHES);
}
String WebCore::searchMenuClearRecentSearchesText() {
  return GetLocalizedString(IDS_RECENT_SEARCHES_CLEAR);
}

// A11y strings.
String WebCore::AXWebAreaText() {
  return GetLocalizedString(IDS_AX_ROLE_WEB_AREA);
}
String WebCore::AXLinkText() {
  return GetLocalizedString(IDS_AX_ROLE_LINK);
}
String WebCore::AXListMarkerText() {
  return GetLocalizedString(IDS_AX_ROLE_LIST_MARKER);
}
String WebCore::AXImageMapText() {
  return GetLocalizedString(IDS_AX_ROLE_IMAGE_MAP);
}
String WebCore::AXHeadingText() {
  return GetLocalizedString(IDS_AX_ROLE_HEADING);
}
#endif  // OS_WIN
String WebCore::AXButtonActionVerb() {
  return GetLocalizedString(IDS_AX_BUTTON_ACTION_VERB);
}
String WebCore::AXRadioButtonActionVerb() {
  return GetLocalizedString(IDS_AX_RADIO_BUTTON_ACTION_VERB);
}
String WebCore::AXTextFieldActionVerb() {
  return GetLocalizedString(IDS_AX_TEXT_FIELD_ACTION_VERB);
}
String WebCore::AXCheckedCheckBoxActionVerb() {
  return GetLocalizedString(IDS_AX_CHECKED_CHECK_BOX_ACTION_VERB);
}
String WebCore::AXUncheckedCheckBoxActionVerb() {
  return GetLocalizedString(IDS_AX_UNCHECKED_CHECK_BOX_ACTION_VERB);
}
String WebCore::AXLinkActionVerb() {
  return GetLocalizedString(IDS_AX_LINK_ACTION_VERB);
}

// Used in FTPDirectoryDocument.cpp
String WebCore::unknownFileSizeText() {
  return String();
}

// These two are used in FileChooserWin.cpp.
#if PLATFORM(WIN)
String WebCore::uploadFileText() {
  return String();
}
String WebCore::allFilesText() {
  return String();
}
#endif

// The following two functions are not declared in LocalizedStrings.h.
// They are used by the menu for the HTML keygen tag.
namespace WebCore {
String keygenMenuHighGradeKeySize() {
  return GetLocalizedString(IDS_KEYGEN_HIGH_GRADE_KEY);
}
String keygenMenuMediumGradeKeySize() {
  return GetLocalizedString(IDS_KEYGEN_MED_GRADE_KEY);
}

// Used in ImageDocument.cpp as the title for pages when that page is an image.
String imageTitle(const String& filename, const IntSize& size) {
  // C3 97 is UTF-8 for U+00D7 (multiplication sign).
  std::string size_str = StringPrintf(" (%d\xC3\x97%d)",
                                      size.width(), size.height());
  return filename + webkit_glue::StdStringToString(size_str);
}

} //namespace WebCore

#if defined(OS_WIN)
// We don't use these strings, so they return an empty String. We can't just
// make them asserts because webcore still calls them.
String WebCore::contextMenuItemTagOpenLinkInNewWindow() { return String(); }
String WebCore::contextMenuItemTagDownloadLinkToDisk() { return String(); }
String WebCore::contextMenuItemTagCopyLinkToClipboard() { return String(); }
String WebCore::contextMenuItemTagOpenImageInNewWindow() { return String(); }
String WebCore::contextMenuItemTagDownloadImageToDisk() { return String(); }
String WebCore::contextMenuItemTagCopyImageToClipboard() { return String(); }
String WebCore::contextMenuItemTagOpenFrameInNewWindow() { return String(); }
String WebCore::contextMenuItemTagCopy() { return String(); }
String WebCore::contextMenuItemTagGoBack() { return String(); }
String WebCore::contextMenuItemTagGoForward() { return String(); }
String WebCore::contextMenuItemTagStop() { return String(); }
String WebCore::contextMenuItemTagReload() { return String(); }
String WebCore::contextMenuItemTagCut() { return String(); }
String WebCore::contextMenuItemTagPaste() { return String(); }
String WebCore::contextMenuItemTagNoGuessesFound() { return String(); }
String WebCore::contextMenuItemTagIgnoreSpelling() { return String(); }
String WebCore::contextMenuItemTagLearnSpelling() { return String(); }
String WebCore::contextMenuItemTagSearchWeb() { return String(); }
String WebCore::contextMenuItemTagLookUpInDictionary() { return String(); }
String WebCore::contextMenuItemTagOpenLink() { return String(); }
String WebCore::contextMenuItemTagIgnoreGrammar() { return String(); }
String WebCore::contextMenuItemTagSpellingMenu() { return String(); }
String WebCore::contextMenuItemTagCheckSpelling() { return String(); }
String WebCore::contextMenuItemTagCheckSpellingWhileTyping() { return String(); }
String WebCore::contextMenuItemTagCheckGrammarWithSpelling() { return String(); }
String WebCore::contextMenuItemTagFontMenu() { return String(); }
String WebCore::contextMenuItemTagBold() { return String(); }
String WebCore::contextMenuItemTagItalic() { return String(); }
String WebCore::contextMenuItemTagUnderline() { return String(); }
String WebCore::contextMenuItemTagOutline() { return String(); }
String WebCore::contextMenuItemTagWritingDirectionMenu() { return String(); }
String WebCore::contextMenuItemTagDefaultDirection() { return String(); }
String WebCore::contextMenuItemTagLeftToRight() { return String(); }
String WebCore::contextMenuItemTagRightToLeft() { return String(); }
String WebCore::contextMenuItemTagInspectElement() { return String(); }
String WebCore::contextMenuItemTagShowSpellingPanel(bool show) { return String(); }
#endif  // OS_WIN
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: MABColumns.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: oj $ $Date: 2001-10-12 11:53:28 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_MAB_COLUMNS_HXX_
#define _CONNECTIVITY_MAB_COLUMNS_HXX_

#ifndef _CONNECTIVITY_FILE_COLUMNS_HXX_
#include "file/FColumns.hxx"
#endif

namespace connectivity
{
    namespace mozaddressbook
    {
        class OMozabColumns : public file::OColumns
        {
        protected:
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNamed > createObject(const ::rtl::OUString& _rName);
        public:
            OMozabColumns(file::OFileTable* _pTable,
                            ::osl::Mutex& _rMutex,
                            const ::std::vector< ::rtl::OUString> &_rVector
                         ) : file::OColumns(_pTable,_rMutex,_rVector)
            {}

        };
    }
}

#endif // _CONNECTIVITY_MAB_COLUMNS_HXX_

<commit_msg>INTEGRATION: CWS dba24 (1.4.262); FILE MERGED 2005/02/09 08:07:56 oj 1.4.262.1: #i26950# remove the need for XNamed<commit_after>/*************************************************************************
 *
 *  $RCSfile: MABColumns.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: vg $ $Date: 2005-03-10 15:40:34 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_MAB_COLUMNS_HXX_
#define _CONNECTIVITY_MAB_COLUMNS_HXX_

#ifndef _CONNECTIVITY_FILE_COLUMNS_HXX_
#include "file/FColumns.hxx"
#endif

namespace connectivity
{
    namespace mozaddressbook
    {
        class OMozabColumns : public file::OColumns
        {
        protected:
            virtual sdbcx::ObjectType createObject(const ::rtl::OUString& _rName);
        public:
            OMozabColumns(file::OFileTable* _pTable,
                            ::osl::Mutex& _rMutex,
                            const ::std::vector< ::rtl::OUString> &_rVector
                         ) : file::OColumns(_pTable,_rMutex,_rVector)
            {}

        };
    }
}

#endif // _CONNECTIVITY_MAB_COLUMNS_HXX_

<|endoftext|>


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

#include "webkit/glue/webclipboard_impl.h"

#include "base/clipboard.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "googleurl/src/gurl.h"
#include "net/base/escape.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "webkit/api/public/WebImage.h"
#include "webkit/api/public/WebSize.h"
#include "webkit/api/public/WebString.h"
#include "webkit/api/public/WebURL.h"
#include "webkit/glue/scoped_clipboard_writer_glue.h"
#include "webkit/glue/webkit_glue.h"

#if WEBKIT_USING_CG
#include "skia/ext/skia_utils_mac.h"
#endif

using WebKit::WebClipboard;
using WebKit::WebImage;
using WebKit::WebString;
using WebKit::WebURL;

namespace webkit_glue {

// Static
std::string WebClipboardImpl::URLToMarkup(const WebURL& url,
    const WebString& title) {
  std::string markup("");
  // TODO(darin): HTML escape this
  markup.append(EscapeForHTML(UTF16ToUTF8(title)));
  markup.append("");
  return markup;
}

// Static
std::string WebClipboardImpl::URLToImageMarkup(const WebURL& url,
    const WebString& title) {
  std::string markup("");
  return markup;
}

bool WebClipboardImpl::isFormatAvailable(Format format, Buffer buffer) {
  Clipboard::FormatType format_type;
  Clipboard::Buffer buffer_type;

  switch (format) {
    case FormatHTML:
      format_type = Clipboard::GetHtmlFormatType();
      break;
    case FormatSmartPaste:
      format_type = Clipboard::GetWebKitSmartPasteFormatType();
      break;
    case FormatBookmark:
#if defined(OS_WIN) || defined(OS_MACOSX)
      format_type = Clipboard::GetUrlWFormatType();
      break;
#endif
    default:
      NOTREACHED();
      return false;
  }

  if (!ConvertBufferType(buffer, &buffer_type))
    return false;

  return ClipboardIsFormatAvailable(format_type, buffer_type);
}

WebString WebClipboardImpl::readPlainText(Buffer buffer) {
  Clipboard::Buffer buffer_type;
  if (!ConvertBufferType(buffer, &buffer_type))
    return WebString();

  if (ClipboardIsFormatAvailable(Clipboard::GetPlainTextWFormatType(),
                                 buffer_type)) {
    string16 text;
    ClipboardReadText(buffer_type, &text);
    if (!text.empty())
      return text;
  }

  if (ClipboardIsFormatAvailable(Clipboard::GetPlainTextFormatType(),
                                 buffer_type)) {
    std::string text;
    ClipboardReadAsciiText(buffer_type, &text);
    if (!text.empty())
      return ASCIIToUTF16(text);
  }

  return WebString();
}

WebString WebClipboardImpl::readHTML(Buffer buffer, WebURL* source_url) {
  Clipboard::Buffer buffer_type;
  if (!ConvertBufferType(buffer, &buffer_type))
    return WebString();

  string16 html_stdstr;
  GURL gurl;
  ClipboardReadHTML(buffer_type, &html_stdstr, &gurl);
  *source_url = gurl;
  return html_stdstr;
}

void WebClipboardImpl::writeHTML(
    const WebString& html_text, const WebURL& source_url,
    const WebString& plain_text, bool write_smart_paste) {
  ScopedClipboardWriterGlue scw(ClipboardGetClipboard());
  scw.WriteHTML(html_text, source_url.spec());
  scw.WriteText(plain_text);

  if (write_smart_paste)
    scw.WriteWebSmartPaste();
}

void WebClipboardImpl::writePlainText(const WebString& plain_text) {
  ScopedClipboardWriterGlue scw(ClipboardGetClipboard());
  scw.WriteText(plain_text);
}

void WebClipboardImpl::writeURL(const WebURL& url, const WebString& title) {
  ScopedClipboardWriterGlue scw(ClipboardGetClipboard());

  scw.WriteBookmark(title, url.spec());
  scw.WriteHTML(UTF8ToUTF16(URLToMarkup(url, title)), "");
  scw.WriteText(UTF8ToUTF16(url.spec()));
}

void WebClipboardImpl::writeImage(
    const WebImage& image, const WebURL& url, const WebString& title) {
  ScopedClipboardWriterGlue scw(ClipboardGetClipboard());

  if (!image.isNull()) {
#if WEBKIT_USING_SKIA
    const SkBitmap& bitmap = image.getSkBitmap();
#elif WEBKIT_USING_CG
    const SkBitmap& bitmap = gfx::CGImageToSkBitmap(image.getCGImageRef());
#endif
    SkAutoLockPixels locked(bitmap);
    scw.WriteBitmapFromPixels(bitmap.getPixels(), image.size());
  }

  if (!url.isEmpty()) {
    scw.WriteBookmark(title, url.spec());
    scw.WriteHTML(UTF8ToUTF16(URLToImageMarkup(url, title)), "");
    scw.WriteText(UTF8ToUTF16(url.spec()));
  }
}

bool WebClipboardImpl::ConvertBufferType(Buffer buffer,
                                         Clipboard::Buffer* result) {
  switch (buffer) {
    case BufferStandard:
      *result = Clipboard::BUFFER_STANDARD;
      break;
    case BufferSelection:
#if defined(OS_LINUX)
      *result = Clipboard::BUFFER_SELECTION;
      break;
#endif
    default:
      NOTREACHED();
      return false;
  }
  return true;
}

}  // namespace webkit_glue
<commit_msg>Only write the image when writeImage is called.  We don't write the other formats because when pasting, we want to make sure the image has priority.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.  Use of this
// source code is governed by a BSD-style license that can be found in the
// LICENSE file.

#include "webkit/glue/webclipboard_impl.h"

#include "base/clipboard.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "googleurl/src/gurl.h"
#include "net/base/escape.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "webkit/api/public/WebImage.h"
#include "webkit/api/public/WebSize.h"
#include "webkit/api/public/WebString.h"
#include "webkit/api/public/WebURL.h"
#include "webkit/glue/scoped_clipboard_writer_glue.h"
#include "webkit/glue/webkit_glue.h"

#if WEBKIT_USING_CG
#include "skia/ext/skia_utils_mac.h"
#endif

using WebKit::WebClipboard;
using WebKit::WebImage;
using WebKit::WebString;
using WebKit::WebURL;

namespace webkit_glue {

// Static
std::string WebClipboardImpl::URLToMarkup(const WebURL& url,
    const WebString& title) {
  std::string markup("");
  // TODO(darin): HTML escape this
  markup.append(EscapeForHTML(UTF16ToUTF8(title)));
  markup.append("");
  return markup;
}

// Static
std::string WebClipboardImpl::URLToImageMarkup(const WebURL& url,
    const WebString& title) {
  std::string markup("");
  return markup;
}

bool WebClipboardImpl::isFormatAvailable(Format format, Buffer buffer) {
  Clipboard::FormatType format_type;
  Clipboard::Buffer buffer_type;

  switch (format) {
    case FormatHTML:
      format_type = Clipboard::GetHtmlFormatType();
      break;
    case FormatSmartPaste:
      format_type = Clipboard::GetWebKitSmartPasteFormatType();
      break;
    case FormatBookmark:
#if defined(OS_WIN) || defined(OS_MACOSX)
      format_type = Clipboard::GetUrlWFormatType();
      break;
#endif
    default:
      NOTREACHED();
      return false;
  }

  if (!ConvertBufferType(buffer, &buffer_type))
    return false;

  return ClipboardIsFormatAvailable(format_type, buffer_type);
}

WebString WebClipboardImpl::readPlainText(Buffer buffer) {
  Clipboard::Buffer buffer_type;
  if (!ConvertBufferType(buffer, &buffer_type))
    return WebString();

  if (ClipboardIsFormatAvailable(Clipboard::GetPlainTextWFormatType(),
                                 buffer_type)) {
    string16 text;
    ClipboardReadText(buffer_type, &text);
    if (!text.empty())
      return text;
  }

  if (ClipboardIsFormatAvailable(Clipboard::GetPlainTextFormatType(),
                                 buffer_type)) {
    std::string text;
    ClipboardReadAsciiText(buffer_type, &text);
    if (!text.empty())
      return ASCIIToUTF16(text);
  }

  return WebString();
}

WebString WebClipboardImpl::readHTML(Buffer buffer, WebURL* source_url) {
  Clipboard::Buffer buffer_type;
  if (!ConvertBufferType(buffer, &buffer_type))
    return WebString();

  string16 html_stdstr;
  GURL gurl;
  ClipboardReadHTML(buffer_type, &html_stdstr, &gurl);
  *source_url = gurl;
  return html_stdstr;
}

void WebClipboardImpl::writeHTML(
    const WebString& html_text, const WebURL& source_url,
    const WebString& plain_text, bool write_smart_paste) {
  ScopedClipboardWriterGlue scw(ClipboardGetClipboard());
  scw.WriteHTML(html_text, source_url.spec());
  scw.WriteText(plain_text);

  if (write_smart_paste)
    scw.WriteWebSmartPaste();
}

void WebClipboardImpl::writePlainText(const WebString& plain_text) {
  ScopedClipboardWriterGlue scw(ClipboardGetClipboard());
  scw.WriteText(plain_text);
}

void WebClipboardImpl::writeURL(const WebURL& url, const WebString& title) {
  ScopedClipboardWriterGlue scw(ClipboardGetClipboard());

  scw.WriteBookmark(title, url.spec());
  scw.WriteHTML(UTF8ToUTF16(URLToMarkup(url, title)), "");
  scw.WriteText(UTF8ToUTF16(url.spec()));
}

void WebClipboardImpl::writeImage(
    const WebImage& image, const WebURL& url, const WebString& title) {
  ScopedClipboardWriterGlue scw(ClipboardGetClipboard());

  if (!image.isNull()) {
#if WEBKIT_USING_SKIA
    const SkBitmap& bitmap = image.getSkBitmap();
#elif WEBKIT_USING_CG
    const SkBitmap& bitmap = gfx::CGImageToSkBitmap(image.getCGImageRef());
#endif
    SkAutoLockPixels locked(bitmap);
    scw.WriteBitmapFromPixels(bitmap.getPixels(), image.size());
  }

  // We intentionally only write the image.  If the user wants the URL, they
  // can get that from the context menu.
}

bool WebClipboardImpl::ConvertBufferType(Buffer buffer,
                                         Clipboard::Buffer* result) {
  switch (buffer) {
    case BufferStandard:
      *result = Clipboard::BUFFER_STANDARD;
      break;
    case BufferSelection:
#if defined(OS_LINUX)
      *result = Clipboard::BUFFER_SELECTION;
      break;
#endif
    default:
      NOTREACHED();
      return false;
  }
  return true;
}

}  // namespace webkit_glue
<|endoftext|>