<commit_before>#pragma once
//=====================================================================//
/*!	@file
	@brief	シーン共通関係
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2018 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "graphics/font8x16.hpp"
#include "graphics/kfont.hpp"
#include "graphics/graphics.hpp"
#include "graphics/picojpeg_in.hpp"
#include "graphics/scaling.hpp"
#include "graphics/img_in.hpp"
#include "graphics/menu.hpp"
#include "chip/FT5206.hpp"

// #define SOFT_I2C

#ifdef SOFT_I2C
#include "common/si2c_io.hpp"
#else
#include "common/sci_i2c_io.hpp"
#endif

#include "common/cmt_io.hpp"

#include "resource.hpp"

namespace app {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief	シーン ID
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	enum class scenes_id {
		title,
		root_menu,

		laptime,
		recall,
		setup
	};

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief	シーン・ベース
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	class scenes_base {

		typedef device::PORT<device::PORT0, device::bitpos::B5> SW2;

	public:
		/// GLCDC
		static const int16_t LCD_X = 480;
		static const int16_t LCD_Y = 272;
		static const auto PIX = graphics::pixel::TYPE::RGB565;
		typedef device::glcdc_io<device::GLCDC, LCD_X, LCD_Y, PIX> GLCDC_IO;

		typedef graphics::font8x16 AFONT;
		typedef graphics::kfont<16, 16, 64> KFONT;

		typedef device::drw2d_mgr<GLCDC_IO, AFONT, KFONT> DRW2D_MGR;
		typedef graphics::render<GLCDC_IO, AFONT, KFONT> RENDER;

		// FT5206, SCI6 簡易 I2C 定義
		typedef device::PORT<device::PORT0, device::bitpos::B7> FT5206_RESET;
#ifdef SOFT_I2C
		typedef device::PORT<device::PORT0, device::bitpos::B0> FT5206_SDA;
		typedef device::PORT<device::PORT0, device::bitpos::B1> FT5206_SCL;
		typedef device::si2c_io<FT5206_SDA, FT5206_SCL> FT5206_I2C;
#else
		typedef utils::fixed_fifo<uint8_t, 64> RECV6_BUFF;
		typedef utils::fixed_fifo<uint8_t, 64> SEND6_BUFF;
		typedef device::sci_i2c_io<device::SCI6, RECV6_BUFF, SEND6_BUFF,
				device::port_map::option::FIRST_I2C> FT5206_I2C;
#endif
		// FT5206 touch device
		typedef chip::FT5206<FT5206_I2C> FT5206;

		typedef resource<RENDER> RESOURCE;

	private:
		GLCDC_IO	glcdc_io_;
		KFONT		kfont_;
		DRW2D_MGR	drw2d_mgr_;
		RENDER		render_;

	public:
		// 最大８個のメニュー
		class BACK {
			RENDER&	render_;
		public:
			BACK(RENDER& render) : render_(render) { }

			void operator () (const vtx::srect& rect)
			{
				render_.round_box(rect, 8);
//				render_.fill_box_r(x + 3, y + 3, w - 6, h - 6, c);
			}
		};
		typedef graphics::menu<RENDER, BACK, 8> MENU;

		typedef img::scaling<RENDER> PLOT;
		typedef img::img_in<PLOT> IMG_IN;

		// CMT 1/100 秒計測
		class watch_task {
		public:
			static const uint32_t LAP_LIMIT = 500;

		private:
			uint32_t	count_;
			bool		enable_;
			bool		lvl_;

			uint32_t	lap_pos_;
			uint32_t	lap_pad_[LAP_LIMIT];

		public:
			watch_task() : count_(0), enable_(false), lvl_(false),
				lap_pos_(0), lap_pad_{ 0 } { }

			void operator() () noexcept
			{
				bool lvl = !SW2::P();
				if(enable_) {
					if(!lvl_ && lvl) {
						if(lap_pos_ < LAP_LIMIT) {
							lap_pad_[lap_pos_] = count_;
							++lap_pos_;
						}
					}
					++count_;
				}
				lvl_ = lvl;
			}

			void enable(bool ena = true) noexcept { enable_ = ena; }

			void set(uint32_t count) noexcept { count_ = count; }

			uint32_t get() const noexcept { return count_; }

			void reset() noexcept
			{
				count_ = 0;
				lap_pos_ = 0;
			}

			uint32_t get_lap_pos() const noexcept { return lap_pos_; }

			uint32_t get_lap(uint32_t pos) const noexcept {
				if(pos >= LAP_LIMIT) return 0;
				return lap_pad_[pos];
			}
		};
		typedef device::cmt_io<device::CMT0, watch_task> CMT;

	private:
		typedef device::PORT<device::PORT6, device::bitpos::B3> LCD_DISP;
		typedef device::PORT<device::PORT6, device::bitpos::B6> LCD_LIGHT;

		FT5206_I2C	ft5206_i2c_;
		FT5206		ft5206_;

		MENU		menu_;
		BACK		back_;

		CMT			cmt_;

		RESOURCE	resource_;

		PLOT		plot_;
		IMG_IN		img_in_;

	public:
		//-------------------------------------------------------------//
		/*!
			@brief	コンストラクタ
			@param[in]	lcdorg	LCD フレームバッファの先頭アドレス
		*/
		//-------------------------------------------------------------//
		scenes_base(void* lcdorg = reinterpret_cast<void*>(0x00000100)) noexcept :
			glcdc_io_(nullptr, lcdorg),
			kfont_(),
			drw2d_mgr_(glcdc_io_, kfont_),
			render_(glcdc_io_, kfont_),
			ft5206_(ft5206_i2c_), menu_(render_, back_), back_(render_), resource_(render_),
			plot_(render_), img_in_(plot_) { }

		//-------------------------------------------------------------//
		/*!
			@brief	ベースの初期化
		*/
		//-------------------------------------------------------------//
		void init() noexcept
		{
			{  // GLCDC の初期化
				LCD_DISP::DIR  = 1;
				LCD_LIGHT::DIR = 1;
				LCD_DISP::P  = 0;  // DISP Disable
				LCD_LIGHT::P = 0;  // BackLight Disable (No PWM)
				if(glcdc_io_.start()) {
					utils::format("Start GLCDC\n");
					LCD_DISP::P  = 1;  // DISP Enable
					LCD_LIGHT::P = 1;  // BackLight Enable (No PWM)
					if(!glcdc_io_.control(GLCDC_IO::CONTROL_CMD::START_DISPLAY)) {
						utils::format("GLCDC ctrl fail...\n");
					}
				} else {
					utils::format("GLCDC Fail\n");
				}
			}

			{  // DRW2D 初期化
				auto ver = drw2d_mgr_.get_version();
				utils::format("DRW2D Version: %04X\n") % ver;

				if(drw2d_mgr_.start()) {
					utils:: format("Start DRW2D\n");
				} else {
					utils:: format("DRW2D Fail\n");
				}
			}
			{  // FT5206 touch screen controller
				FT5206::reset<FT5206_RESET>();
				uint8_t intr_lvl = 1;
				if(!ft5206_i2c_.start(FT5206_I2C::SPEED::STANDARD, intr_lvl)) {
					utils::format("FT5206 I2C Start Fail...\n");
				}
				if(!ft5206_.start()) {
					utils::format("FT5206 Start Fail...\n");
				}
			}

			{  // CMT 100Hz タイマー
				uint8_t intr_level = 5;
				cmt_.start(100, intr_level);
			}

			// スイッチ入力
			SW2::DIR = 0;
		}

		//-------------------------------------------------------------//
		/*!
			@brief	同期と、タッチパネルデータ更新
		*/
		//-------------------------------------------------------------//
		void sync() noexcept
		{
			glcdc_io_.sync_vpos();
			ft5206_.update();
		}

		//-------------------------------------------------------------//
		/*!
			@brief	GLCDC_IO の参照
			@return GLCDC_IO
		*/
		//-------------------------------------------------------------//
		GLCDC_IO& at_glcdc_io() noexcept { return glcdc_io_; }

		//-------------------------------------------------------------//
		/*!
			@brief	タッチデバイスの参照
			@return タッチデバイス
		*/
		//-------------------------------------------------------------//
		FT5206& at_touch() noexcept { return ft5206_; }

		//-------------------------------------------------------------//
		/*!
			@brief	RENDER の参照
			@return RENDER
		*/
		//-------------------------------------------------------------//
		RENDER& at_render() noexcept { return render_; }

		//-------------------------------------------------------------//
		/*!
			@brief	MENU の参照
			@return MENU
		*/
		//-------------------------------------------------------------//
		MENU& at_menu() noexcept { return menu_; }

		//-------------------------------------------------------------//
		/*!
			@brief	CMT の参照
			@return CMT
		*/
		//-------------------------------------------------------------//
		CMT& at_cmt() noexcept { return cmt_; }

		//-------------------------------------------------------------//
		/*!
			@brief	RESOURCE の参照
			@return RESOURCE
		*/
		//-------------------------------------------------------------//
		RESOURCE& at_resource() noexcept { return resource_; }

		//-------------------------------------------------------------//
		/*!
			@brief	PLOT の参照
			@return PLOT
		*/
		//-------------------------------------------------------------//
		PLOT& at_plot() noexcept { return plot_; }

		//-------------------------------------------------------------//
		/*!
			@brief	IMG_IN の参照
			@return IMG_IN
		*/
		//-------------------------------------------------------------//
		IMG_IN& at_img() noexcept { return img_in_; }
	};
}

extern void change_scene(app::scenes_id id);
extern app::scenes_base& at_scenes_base();
<commit_msg>update: AFONT, KFONT, FONT cleanup<commit_after>#pragma once
//=====================================================================//
/*!	@file
	@brief	シーン共通関係
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2018 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "graphics/font8x16.hpp"
#include "graphics/kfont.hpp"
#include "graphics/font.hpp"
#include "graphics/graphics.hpp"
#include "graphics/picojpeg_in.hpp"
#include "graphics/scaling.hpp"
#include "graphics/img_in.hpp"
#include "graphics/menu.hpp"
#include "chip/FT5206.hpp"

// #define SOFT_I2C

#ifdef SOFT_I2C
#include "common/si2c_io.hpp"
#else
#include "common/sci_i2c_io.hpp"
#endif

#include "common/cmt_io.hpp"

#include "resource.hpp"

namespace app {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief	シーン ID
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	enum class scenes_id {
		title,
		root_menu,

		laptime,
		recall,
		setup
	};

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief	シーン・ベース
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	class scenes_base {

		typedef device::PORT<device::PORT0, device::bitpos::B5> SW2;

	public:
		/// GLCDC
		static const int16_t LCD_X = 480;
		static const int16_t LCD_Y = 272;
		static const auto PIX = graphics::pixel::TYPE::RGB565;
		typedef device::glcdc_io<device::GLCDC, LCD_X, LCD_Y, PIX> GLCDC_IO;

		typedef graphics::font8x16 AFONT;
		typedef graphics::kfont<16, 16, 64> KFONT;
		typedef graphics::font<AFONT, KFONT> FONT;

		typedef device::drw2d_mgr<GLCDC_IO, FONT> DRW2D_MGR;
		typedef graphics::render<GLCDC_IO, FONT> RENDER;

		// FT5206, SCI6 簡易 I2C 定義
		typedef device::PORT<device::PORT0, device::bitpos::B7> FT5206_RESET;
#ifdef SOFT_I2C
		typedef device::PORT<device::PORT0, device::bitpos::B0> FT5206_SDA;
		typedef device::PORT<device::PORT0, device::bitpos::B1> FT5206_SCL;
		typedef device::si2c_io<FT5206_SDA, FT5206_SCL> FT5206_I2C;
#else
		typedef utils::fixed_fifo<uint8_t, 64> RECV6_BUFF;
		typedef utils::fixed_fifo<uint8_t, 64> SEND6_BUFF;
		typedef device::sci_i2c_io<device::SCI6, RECV6_BUFF, SEND6_BUFF,
				device::port_map::option::FIRST_I2C> FT5206_I2C;
#endif
		// FT5206 touch device
		typedef chip::FT5206<FT5206_I2C> FT5206;

		typedef resource<RENDER> RESOURCE;

	private:
		GLCDC_IO	glcdc_io_;
		AFONT		afont_;
		KFONT		kfont_;
		FONT		font_;
		DRW2D_MGR	drw2d_mgr_;
		RENDER		render_;

	public:
		// 最大８個のメニュー
		class BACK {
			RENDER&	render_;
		public:
			BACK(RENDER& render) : render_(render) { }

			void operator () (const vtx::srect& rect)
			{
				render_.round_box(rect, 8);
//				render_.fill_box_r(x + 3, y + 3, w - 6, h - 6, c);
			}
		};
		typedef graphics::menu<RENDER, BACK, 8> MENU;

		typedef img::scaling<RENDER> PLOT;
		typedef img::img_in<PLOT> IMG_IN;

		// CMT 1/100 秒計測
		class watch_task {
		public:
			static const uint32_t LAP_LIMIT = 500;

		private:
			uint32_t	count_;
			bool		enable_;
			bool		lvl_;

			uint32_t	lap_pos_;
			uint32_t	lap_pad_[LAP_LIMIT];

		public:
			watch_task() : count_(0), enable_(false), lvl_(false),
				lap_pos_(0), lap_pad_{ 0 } { }

			void operator() () noexcept
			{
				bool lvl = !SW2::P();
				if(enable_) {
					if(!lvl_ && lvl) {
						if(lap_pos_ < LAP_LIMIT) {
							lap_pad_[lap_pos_] = count_;
							++lap_pos_;
						}
					}
					++count_;
				}
				lvl_ = lvl;
			}

			void enable(bool ena = true) noexcept { enable_ = ena; }

			void set(uint32_t count) noexcept { count_ = count; }

			uint32_t get() const noexcept { return count_; }

			void reset() noexcept
			{
				count_ = 0;
				lap_pos_ = 0;
			}

			uint32_t get_lap_pos() const noexcept { return lap_pos_; }

			uint32_t get_lap(uint32_t pos) const noexcept {
				if(pos >= LAP_LIMIT) return 0;
				return lap_pad_[pos];
			}
		};
		typedef device::cmt_io<device::CMT0, watch_task> CMT;

	private:
		typedef device::PORT<device::PORT6, device::bitpos::B3> LCD_DISP;
		typedef device::PORT<device::PORT6, device::bitpos::B6> LCD_LIGHT;

		FT5206_I2C	ft5206_i2c_;
		FT5206		ft5206_;

		MENU		menu_;
		BACK		back_;

		CMT			cmt_;

		RESOURCE	resource_;

		PLOT		plot_;
		IMG_IN		img_in_;

	public:
		//-------------------------------------------------------------//
		/*!
			@brief	コンストラクタ
			@param[in]	lcdorg	LCD フレームバッファの先頭アドレス
		*/
		//-------------------------------------------------------------//
		scenes_base(void* lcdorg = reinterpret_cast<void*>(0x00000100)) noexcept :
			glcdc_io_(nullptr, lcdorg),
			afont_(), kfont_(), font_(afont_, kfont_),
			drw2d_mgr_(glcdc_io_, font_),
			render_(glcdc_io_, font_),
			ft5206_(ft5206_i2c_), menu_(render_, back_), back_(render_), resource_(render_),
			plot_(render_), img_in_(plot_) { }

		//-------------------------------------------------------------//
		/*!
			@brief	ベースの初期化
		*/
		//-------------------------------------------------------------//
		void init() noexcept
		{
			{  // GLCDC の初期化
				LCD_DISP::DIR  = 1;
				LCD_LIGHT::DIR = 1;
				LCD_DISP::P  = 0;  // DISP Disable
				LCD_LIGHT::P = 0;  // BackLight Disable (No PWM)
				if(glcdc_io_.start()) {
					utils::format("Start GLCDC\n");
					LCD_DISP::P  = 1;  // DISP Enable
					LCD_LIGHT::P = 1;  // BackLight Enable (No PWM)
					if(!glcdc_io_.control(GLCDC_IO::CONTROL_CMD::START_DISPLAY)) {
						utils::format("GLCDC ctrl fail...\n");
					}
				} else {
					utils::format("GLCDC Fail\n");
				}
			}

			{  // DRW2D 初期化
				auto ver = drw2d_mgr_.get_version();
				utils::format("DRW2D Version: %04X\n") % ver;

				if(drw2d_mgr_.start()) {
					utils:: format("Start DRW2D\n");
				} else {
					utils:: format("DRW2D Fail\n");
				}
			}
			{  // FT5206 touch screen controller
				FT5206::reset<FT5206_RESET>();
				uint8_t intr_lvl = 1;
				if(!ft5206_i2c_.start(FT5206_I2C::SPEED::STANDARD, intr_lvl)) {
					utils::format("FT5206 I2C Start Fail...\n");
				}
				if(!ft5206_.start()) {
					utils::format("FT5206 Start Fail...\n");
				}
			}

			{  // CMT 100Hz タイマー
				uint8_t intr_level = 5;
				cmt_.start(100, intr_level);
			}

			// スイッチ入力
			SW2::DIR = 0;
		}

		//-------------------------------------------------------------//
		/*!
			@brief	同期と、タッチパネルデータ更新
		*/
		//-------------------------------------------------------------//
		void sync() noexcept
		{
			glcdc_io_.sync_vpos();
			ft5206_.update();
		}

		//-------------------------------------------------------------//
		/*!
			@brief	GLCDC_IO の参照
			@return GLCDC_IO
		*/
		//-------------------------------------------------------------//
		GLCDC_IO& at_glcdc_io() noexcept { return glcdc_io_; }

		//-------------------------------------------------------------//
		/*!
			@brief	タッチデバイスの参照
			@return タッチデバイス
		*/
		//-------------------------------------------------------------//
		FT5206& at_touch() noexcept { return ft5206_; }

		//-------------------------------------------------------------//
		/*!
			@brief	RENDER の参照
			@return RENDER
		*/
		//-------------------------------------------------------------//
		RENDER& at_render() noexcept { return render_; }

		//-------------------------------------------------------------//
		/*!
			@brief	MENU の参照
			@return MENU
		*/
		//-------------------------------------------------------------//
		MENU& at_menu() noexcept { return menu_; }

		//-------------------------------------------------------------//
		/*!
			@brief	CMT の参照
			@return CMT
		*/
		//-------------------------------------------------------------//
		CMT& at_cmt() noexcept { return cmt_; }

		//-------------------------------------------------------------//
		/*!
			@brief	RESOURCE の参照
			@return RESOURCE
		*/
		//-------------------------------------------------------------//
		RESOURCE& at_resource() noexcept { return resource_; }

		//-------------------------------------------------------------//
		/*!
			@brief	PLOT の参照
			@return PLOT
		*/
		//-------------------------------------------------------------//
		PLOT& at_plot() noexcept { return plot_; }

		//-------------------------------------------------------------//
		/*!
			@brief	IMG_IN の参照
			@return IMG_IN
		*/
		//-------------------------------------------------------------//
		IMG_IN& at_img() noexcept { return img_in_; }
	};
}

extern void change_scene(app::scenes_id id);
extern app::scenes_base& at_scenes_base();
<|endoftext|>


<commit_before>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/common/native_mate_converters/gfx_converter.h"

#include "native_mate/dictionary.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"

namespace mate {

v8::Local<v8::Value> Converter<gfx::Point>::ToV8(v8::Isolate* isolate,
                                                 const gfx::Point& val) {
  mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
  dict.SetHidden("simple", true);
  dict.Set("x", val.x());
  dict.Set("y", val.y());
  return dict.GetHandle();
}

bool Converter<gfx::Point>::FromV8(v8::Isolate* isolate,
                                   v8::Local<v8::Value> val,
                                   gfx::Point* out) {
  mate::Dictionary dict;
  if (!ConvertFromV8(isolate, val, &dict))
    return false;
  int x, y;
  if (!dict.Get("x", &x) || !dict.Get("y", &y))
    return false;
  *out = gfx::Point(x, y);
  return true;
}

v8::Local<v8::Value> Converter<gfx::Size>::ToV8(v8::Isolate* isolate,
                                                const gfx::Size& val) {
  mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
  dict.SetHidden("simple", true);
  dict.Set("width", val.width());
  dict.Set("height", val.height());
  return dict.GetHandle();
}

bool Converter<gfx::Size>::FromV8(v8::Isolate* isolate,
                                  v8::Local<v8::Value> val,
                                  gfx::Size* out) {
  mate::Dictionary dict;
  if (!ConvertFromV8(isolate, val, &dict))
    return false;
  int width, height;
  if (!dict.Get("width", &width) || !dict.Get("height", &height))
    return false;
  *out = gfx::Size(width, height);
  return true;
}

v8::Local<v8::Value> Converter<gfx::Rect>::ToV8(v8::Isolate* isolate,
                                                const gfx::Rect& val) {
  mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
  dict.SetHidden("simple", true);
  dict.Set("x", val.x());
  dict.Set("y", val.y());
  dict.Set("width", val.width());
  dict.Set("height", val.height());
  return dict.GetHandle();
}

bool Converter<gfx::Rect>::FromV8(v8::Isolate* isolate,
                                  v8::Local<v8::Value> val,
                                  gfx::Rect* out) {
  mate::Dictionary dict;
  if (!ConvertFromV8(isolate, val, &dict))
    return false;
  int x, y, width, height;
  if (!dict.Get("x", &x) || !dict.Get("y", &y) || !dict.Get("width", &width) ||
      !dict.Get("height", &height))
    return false;
  *out = gfx::Rect(x, y, width, height);
  return true;
}

template <>
struct Converter<display::Display::TouchSupport> {
  static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
                                   const display::Display::TouchSupport& val) {
    switch (val) {
      case display::Display::TOUCH_SUPPORT_AVAILABLE:
        return StringToV8(isolate, "available");
      case display::Display::TOUCH_SUPPORT_UNAVAILABLE:
        return StringToV8(isolate, "unavailable");
      default:
        return StringToV8(isolate, "unknown");
    }
  }
};

v8::Local<v8::Value> Converter<display::Display>::ToV8(
    v8::Isolate* isolate,
    const display::Display& val) {
  mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
  dict.SetHidden("simple", true);
  dict.Set("id", val.id());
  dict.Set("bounds", val.bounds());
  dict.Set("workArea", val.work_area());
  dict.Set("size", val.size());
  dict.Set("workAreaSize", val.work_area_size());
  dict.Set("scaleFactor", val.device_scale_factor());
  dict.Set("rotation", val.RotationAsDegree());
  dict.Set("touchSupport", val.touch_support());
  return dict.GetHandle();
}

}  // namespace mate
<commit_msg>ui::Display cleanup: some enums --> enum classes<commit_after>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/common/native_mate_converters/gfx_converter.h"

#include "native_mate/dictionary.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"

namespace mate {

v8::Local<v8::Value> Converter<gfx::Point>::ToV8(v8::Isolate* isolate,
                                                 const gfx::Point& val) {
  mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
  dict.SetHidden("simple", true);
  dict.Set("x", val.x());
  dict.Set("y", val.y());
  return dict.GetHandle();
}

bool Converter<gfx::Point>::FromV8(v8::Isolate* isolate,
                                   v8::Local<v8::Value> val,
                                   gfx::Point* out) {
  mate::Dictionary dict;
  if (!ConvertFromV8(isolate, val, &dict))
    return false;
  int x, y;
  if (!dict.Get("x", &x) || !dict.Get("y", &y))
    return false;
  *out = gfx::Point(x, y);
  return true;
}

v8::Local<v8::Value> Converter<gfx::Size>::ToV8(v8::Isolate* isolate,
                                                const gfx::Size& val) {
  mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
  dict.SetHidden("simple", true);
  dict.Set("width", val.width());
  dict.Set("height", val.height());
  return dict.GetHandle();
}

bool Converter<gfx::Size>::FromV8(v8::Isolate* isolate,
                                  v8::Local<v8::Value> val,
                                  gfx::Size* out) {
  mate::Dictionary dict;
  if (!ConvertFromV8(isolate, val, &dict))
    return false;
  int width, height;
  if (!dict.Get("width", &width) || !dict.Get("height", &height))
    return false;
  *out = gfx::Size(width, height);
  return true;
}

v8::Local<v8::Value> Converter<gfx::Rect>::ToV8(v8::Isolate* isolate,
                                                const gfx::Rect& val) {
  mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
  dict.SetHidden("simple", true);
  dict.Set("x", val.x());
  dict.Set("y", val.y());
  dict.Set("width", val.width());
  dict.Set("height", val.height());
  return dict.GetHandle();
}

bool Converter<gfx::Rect>::FromV8(v8::Isolate* isolate,
                                  v8::Local<v8::Value> val,
                                  gfx::Rect* out) {
  mate::Dictionary dict;
  if (!ConvertFromV8(isolate, val, &dict))
    return false;
  int x, y, width, height;
  if (!dict.Get("x", &x) || !dict.Get("y", &y) || !dict.Get("width", &width) ||
      !dict.Get("height", &height))
    return false;
  *out = gfx::Rect(x, y, width, height);
  return true;
}

template <>
struct Converter<display::Display::TouchSupport> {
  static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
                                   const display::Display::TouchSupport& val) {
    switch (val) {
      case display::Display::TouchSupport::AVAILABLE:
        return StringToV8(isolate, "available");
      case display::Display::TouchSupport::UNAVAILABLE:
        return StringToV8(isolate, "unavailable");
      default:
        return StringToV8(isolate, "unknown");
    }
  }
};

v8::Local<v8::Value> Converter<display::Display>::ToV8(
    v8::Isolate* isolate,
    const display::Display& val) {
  mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
  dict.SetHidden("simple", true);
  dict.Set("id", val.id());
  dict.Set("bounds", val.bounds());
  dict.Set("workArea", val.work_area());
  dict.Set("size", val.size());
  dict.Set("workAreaSize", val.work_area_size());
  dict.Set("scaleFactor", val.device_scale_factor());
  dict.Set("rotation", val.RotationAsDegree());
  dict.Set("touchSupport", val.touch_support());
  return dict.GetHandle();
}

}  // namespace mate
<|endoftext|>


<commit_before>/******************************************************************************\
* File:          process.cpp
* Purpose:       Implementation of class 'wxExProcessWithListView'
* Author:        Anton van Wezenbeek
* RCS-ID:        $Id$
*
* Copyright (c) 1998-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/

#include <wx/tokenzr.h>
#include <wx/txtstrm.h> // for wxTextInputStream
#include <wx/extension/app.h>
#include <wx/extension/configdialog.h>
#include <wx/extension/report/report.h>

BEGIN_EVENT_TABLE(wxExProcessWithListView, wxProcess)
  EVT_TIMER(-1, wxExProcessWithListView::OnTimer)
END_EVENT_TABLE()

wxString wxExProcessWithListView::m_Command = "";

wxExProcessWithListView::wxExProcessWithListView(
  wxExFrameWithHistory* frame,
  wxExListViewFile* listview,
  const wxString& command)
  : wxProcess(NULL, -1)
  , m_Frame(frame)
  , m_Owner(listview)
  , m_Timer(this)
{
  if (!command.empty())
  {
    m_Command = command;
  }

  Redirect();
}

bool wxExProcessWithListView::CheckInput()
{
  bool hasInput = false;

  // This assumes that the output is always line buffered.
  wxString line;

  if (IsInputAvailable())
  {
    wxTextInputStream tis(*GetInputStream());
    line << tis.ReadLine();
    hasInput = true;
  }
  else if (IsErrorAvailable())
  {
    wxTextInputStream tis(*GetErrorStream());
    line << tis.ReadLine();
    hasInput = true;
  }

  if (hasInput && !line.empty())
  {
    wxString lineno;
    wxString path;

    // Check on error in php script output.
    wxRegEx regex(".*in \\(.*\\) on line \\(.*\\)");

    if (regex.Matches(line))
    {
      size_t start, len;

      if (regex.GetMatch(&start, &len, 1))
      {
        path = line.substr(start, len);
      }

      if (regex.GetMatch(&start, &len, 2))
      {
        lineno = line.substr(start, len);
      }
    }
    else
    {
      // Check on error in gcc output (and some others).
      wxStringTokenizer tkz(line, ':');
      path = tkz.GetNextToken();

      if (tkz.HasMoreTokens())
      {
        const wxString number = tkz.GetNextToken();
        long val;
        if (number.ToLong(&val)) lineno = number;
      }
    }

    wxFileName fn(path);
    fn.Normalize();

    if (fn.FileExists())
    {
      wxExListItemWithFileName item(m_Owner, fn.GetFullPath());
      item.Insert();
      item.SetColumnText(_("Line"), line);
      item.SetColumnText(_("Line No"), lineno);
    }
    else
    {
      // wxExListItem gives incorrect image
      wxExListItemWithFileName item(m_Owner, wxEmptyString);
      item.Insert();
      item.SetColumnText(_("Line"), line);
    }

    // If nothing selected, then ensure last line is visible.
    // Otherwise you are busy inspecting some line, and
    // it would be irritating to get it out of view.
    if (m_Owner->GetSelectedItemCount() == 0)
    {
      m_Owner->EnsureVisible(m_Owner->GetItemCount() - 1);
    }

    m_Owner->UpdateStatusBar();
  }

  return hasInput;
}

int wxExProcessWithListView::ConfigDialog(
  wxWindow* parent,
  const wxString& title)
{
  std::vector<wxExConfigItem> v;
  v.push_back(wxExConfigItem(_("Process"), CONFIG_COMBOBOX, wxEmptyString, true));
  v.push_back(wxExConfigItem(_("Process folder"), CONFIG_COMBOBOXDIR, wxEmptyString, true));

  const int result = wxExConfigDialog(parent,
    wxExApp::GetConfig(),
    v,
    title).ShowModal();

  if (result == wxID_OK)
  {
    m_Command = wxExApp::GetConfig(_("Process"));
  }

  return result;
}

long wxExProcessWithListView::Execute()
{
  if (m_Command.empty())
  {
    return 0;
  }

  const wxString cwd = wxGetCwd();

  wxSetWorkingDirectory(wxExApp::GetConfig(_("Process folder")));

  long pid = 0;

  if ((pid = wxExecute(m_Command, wxEXEC_ASYNC, this)) > 0)
  {
    SetPid(pid);

    wxExFrame::StatusText(m_Command);
    wxExApp::Log(_("Running process") + ": " + m_Command);

    m_Timer.Start(100); // each 100 milliseconds
  }
  else
  {
    wxLogError(_("Cannot run process") + ": " + m_Command);
  }

  wxSetWorkingDirectory(cwd);

  return pid;
}

void wxExProcessWithListView::InitCommandFromConfig()
{
  // The process is a combobox, we want only the first from the list,
  // so use the default separator, causing only first field to be returned.
  m_Command = wxExApp::GetConfig(_("Process"));
}

wxKillError wxExProcessWithListView::Kill(wxSignal sig)
{
  if (!Exists(GetPid()))
  {
    return wxKILL_NO_PROCESS;
  }

  m_Timer.Stop();

  wxExFrame::StatusText(_("Stopped"));

  DeletePendingEvents();

  delete this;

  return wxProcess::Kill(GetPid(), sig);
}

void wxExProcessWithListView::OnTerminate(
  int WXUNUSED(pid),
  int WXUNUSED(status))
{
  m_Timer.Stop();

  // Collect remaining input.
  while (CheckInput())
  {
    // Do nothing.
  }

  wxExFrame::StatusText(_("Ready"));

  wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_TERMINATED_PROCESS);
  wxPostEvent(m_Frame, event);
}

void wxExProcessWithListView::OnTimer(wxTimerEvent& event)
{
  while (CheckInput())
  {
    // Do nothing.
  }
}
<commit_msg>outcommented delete this infor wxGTK in Kill<commit_after>/******************************************************************************\
* File:          process.cpp
* Purpose:       Implementation of class 'wxExProcessWithListView'
* Author:        Anton van Wezenbeek
* RCS-ID:        $Id$
*
* Copyright (c) 1998-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/

#include <wx/tokenzr.h>
#include <wx/txtstrm.h> // for wxTextInputStream
#include <wx/extension/app.h>
#include <wx/extension/configdialog.h>
#include <wx/extension/report/report.h>

BEGIN_EVENT_TABLE(wxExProcessWithListView, wxProcess)
  EVT_TIMER(-1, wxExProcessWithListView::OnTimer)
END_EVENT_TABLE()

wxString wxExProcessWithListView::m_Command = "";

wxExProcessWithListView::wxExProcessWithListView(
  wxExFrameWithHistory* frame,
  wxExListViewFile* listview,
  const wxString& command)
  : wxProcess(NULL, -1)
  , m_Frame(frame)
  , m_Owner(listview)
  , m_Timer(this)
{
  if (!command.empty())
  {
    m_Command = command;
  }

  Redirect();
}

bool wxExProcessWithListView::CheckInput()
{
  bool hasInput = false;

  // This assumes that the output is always line buffered.
  wxString line;

  if (IsInputAvailable())
  {
    wxTextInputStream tis(*GetInputStream());
    line << tis.ReadLine();
    hasInput = true;
  }
  else if (IsErrorAvailable())
  {
    wxTextInputStream tis(*GetErrorStream());
    line << tis.ReadLine();
    hasInput = true;
  }

  if (hasInput && !line.empty())
  {
    wxString lineno;
    wxString path;

    // Check on error in php script output.
    wxRegEx regex(".*in \\(.*\\) on line \\(.*\\)");

    if (regex.Matches(line))
    {
      size_t start, len;

      if (regex.GetMatch(&start, &len, 1))
      {
        path = line.substr(start, len);
      }

      if (regex.GetMatch(&start, &len, 2))
      {
        lineno = line.substr(start, len);
      }
    }
    else
    {
      // Check on error in gcc output (and some others).
      wxStringTokenizer tkz(line, ':');
      path = tkz.GetNextToken();

      if (tkz.HasMoreTokens())
      {
        const wxString number = tkz.GetNextToken();
        long val;
        if (number.ToLong(&val)) lineno = number;
      }
    }

    wxFileName fn(path);
    fn.Normalize();

    if (fn.FileExists())
    {
      wxExListItemWithFileName item(m_Owner, fn.GetFullPath());
      item.Insert();
      item.SetColumnText(_("Line"), line);
      item.SetColumnText(_("Line No"), lineno);
    }
    else
    {
      // wxExListItem gives incorrect image
      wxExListItemWithFileName item(m_Owner, wxEmptyString);
      item.Insert();
      item.SetColumnText(_("Line"), line);
    }

    // If nothing selected, then ensure last line is visible.
    // Otherwise you are busy inspecting some line, and
    // it would be irritating to get it out of view.
    if (m_Owner->GetSelectedItemCount() == 0)
    {
      m_Owner->EnsureVisible(m_Owner->GetItemCount() - 1);
    }

    m_Owner->UpdateStatusBar();
  }

  return hasInput;
}

int wxExProcessWithListView::ConfigDialog(
  wxWindow* parent,
  const wxString& title)
{
  std::vector<wxExConfigItem> v;
  v.push_back(wxExConfigItem(_("Process"), CONFIG_COMBOBOX, wxEmptyString, true));
  v.push_back(wxExConfigItem(_("Process folder"), CONFIG_COMBOBOXDIR, wxEmptyString, true));

  const int result = wxExConfigDialog(parent,
    wxExApp::GetConfig(),
    v,
    title).ShowModal();

  if (result == wxID_OK)
  {
    m_Command = wxExApp::GetConfig(_("Process"));
  }

  return result;
}

long wxExProcessWithListView::Execute()
{
  if (m_Command.empty())
  {
    return 0;
  }

  const wxString cwd = wxGetCwd();

  wxSetWorkingDirectory(wxExApp::GetConfig(_("Process folder")));

  long pid = 0;

  if ((pid = wxExecute(m_Command, wxEXEC_ASYNC, this)) > 0)
  {
    SetPid(pid);

    wxExFrame::StatusText(m_Command);
    wxExApp::Log(_("Running process") + ": " + m_Command);

    m_Timer.Start(100); // each 100 milliseconds
  }
  else
  {
    wxLogError(_("Cannot run process") + ": " + m_Command);
  }

  wxSetWorkingDirectory(cwd);

  return pid;
}

void wxExProcessWithListView::InitCommandFromConfig()
{
  // The process is a combobox, we want only the first from the list,
  // so use the default separator, causing only first field to be returned.
  m_Command = wxExApp::GetConfig(_("Process"));
}

wxKillError wxExProcessWithListView::Kill(wxSignal sig)
{
  if (!Exists(GetPid()))
  {
    return wxKILL_NO_PROCESS;
  }

  m_Timer.Stop();

  wxExFrame::StatusText(_("Stopped"));

  DeletePendingEvents();

  // Next statement causes wxGTK to crash, so outcommented.
#ifndef __WXGTK__
  delete this;
#endif

  return wxProcess::Kill(GetPid(), sig);
}

void wxExProcessWithListView::OnTerminate(
  int WXUNUSED(pid),
  int WXUNUSED(status))
{
  m_Timer.Stop();

  // Collect remaining input.
  while (CheckInput())
  {
    // Do nothing.
  }

  wxExFrame::StatusText(_("Ready"));

  wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_TERMINATED_PROCESS);
  wxPostEvent(m_Frame, event);
}

void wxExProcessWithListView::OnTimer(wxTimerEvent& event)
{
  while (CheckInput())
  {
    // Do nothing.
  }
}
<|endoftext|>


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

#include "chrome/browser/history/in_memory_url_index_types.h"

#include <algorithm>

#include "base/i18n/break_iterator.h"
#include "base/i18n/case_conversion.h"
#include "base/string_util.h"

namespace history {

// Matches within URL and Title Strings ----------------------------------------

TermMatches MatchTermInString(const string16& term,
                              const string16& string,
                              int term_num) {
  const size_t kMaxCompareLength = 2048;
  const string16& short_string = (string.length() > kMaxCompareLength) ?
      string.substr(0, kMaxCompareLength) : string;
  TermMatches matches;
  for (size_t location = short_string.find(term); location != string16::npos;
       location = short_string.find(term, location + 1))
    matches.push_back(TermMatch(term_num, location, term.length()));
  return matches;
}

// Comparison function for sorting TermMatches by their offsets.
bool MatchOffsetLess(const TermMatch& m1, const TermMatch& m2) {
  return m1.offset < m2.offset;
}

TermMatches SortAndDeoverlapMatches(const TermMatches& matches) {
  if (matches.empty())
    return matches;
  TermMatches sorted_matches = matches;
  std::sort(sorted_matches.begin(), sorted_matches.end(), MatchOffsetLess);
  TermMatches clean_matches;
  TermMatch last_match;
  for (TermMatches::const_iterator iter = sorted_matches.begin();
       iter != sorted_matches.end(); ++iter) {
    if (iter->offset >= last_match.offset + last_match.length) {
      last_match = *iter;
      clean_matches.push_back(last_match);
    }
  }
  return clean_matches;
}

std::vector<size_t> OffsetsFromTermMatches(const TermMatches& matches) {
  std::vector<size_t> offsets;
  for (TermMatches::const_iterator i = matches.begin(); i != matches.end(); ++i)
    offsets.push_back(i->offset);
  return offsets;
}

TermMatches ReplaceOffsetsInTermMatches(const TermMatches& matches,
                                        const std::vector<size_t>& offsets) {
  DCHECK_EQ(matches.size(), offsets.size());
  TermMatches new_matches;
  std::vector<size_t>::const_iterator offset_iter = offsets.begin();
  for (TermMatches::const_iterator term_iter = matches.begin();
       term_iter != matches.end(); ++term_iter, ++offset_iter) {
    if (*offset_iter != string16::npos) {
      TermMatch new_match(*term_iter);
      new_match.offset = *offset_iter;
      new_matches.push_back(new_match);
    }
  }
  return new_matches;
}

// ScoredHistoryMatch ----------------------------------------------------------

ScoredHistoryMatch::ScoredHistoryMatch()
    : raw_score(0),
      can_inline(false) {}

ScoredHistoryMatch::ScoredHistoryMatch(const URLRow& url_info)
    : HistoryMatch(url_info, 0, false, false),
      raw_score(0),
      can_inline(false) {}

ScoredHistoryMatch::~ScoredHistoryMatch() {}

// Comparison function for sorting ScoredMatches by their scores.
bool ScoredHistoryMatch::MatchScoreGreater(const ScoredHistoryMatch& m1,
                                           const ScoredHistoryMatch& m2) {
  return m1.raw_score >= m2.raw_score;
}

// InMemoryURLIndex's Private Data ---------------------------------------------

URLIndexPrivateData::URLIndexPrivateData() {}

URLIndexPrivateData::~URLIndexPrivateData() {}

void URLIndexPrivateData::Clear() {
  word_list_.clear();
  available_words_.clear();
  word_map_.clear();
  char_word_map_.clear();
  word_id_history_map_.clear();
  history_id_word_map_.clear();
  history_info_map_.clear();
}

void URLIndexPrivateData::AddToHistoryIDWordMap(HistoryID history_id,
                                               WordID word_id) {
  HistoryIDWordMap::iterator iter = history_id_word_map_.find(history_id);
  if (iter != history_id_word_map_.end()) {
    WordIDSet& word_id_set(iter->second);
    word_id_set.insert(word_id);
  } else {
    WordIDSet word_id_set;
    word_id_set.insert(word_id);
    history_id_word_map_[history_id] = word_id_set;
  }
}

WordIDSet URLIndexPrivateData::WordIDSetForTermChars(
    const Char16Set& term_chars) {
  WordIDSet word_id_set;
  for (Char16Set::const_iterator c_iter = term_chars.begin();
       c_iter != term_chars.end(); ++c_iter) {
    CharWordIDMap::iterator char_iter = char_word_map_.find(*c_iter);
    if (char_iter == char_word_map_.end()) {
      // A character was not found so there are no matching results: bail.
      word_id_set.clear();
      break;
    }
    WordIDSet& char_word_id_set(char_iter->second);
    // It is possible for there to no longer be any words associated with
    // a particular character. Give up in that case.
    if (char_word_id_set.empty()) {
      word_id_set.clear();
      break;
    }

    if (c_iter == term_chars.begin()) {
      // First character results becomes base set of results.
      word_id_set = char_word_id_set;
    } else {
      // Subsequent character results get intersected in.
      WordIDSet new_word_id_set;
      std::set_intersection(word_id_set.begin(), word_id_set.end(),
                            char_word_id_set.begin(), char_word_id_set.end(),
                            std::inserter(new_word_id_set,
                                          new_word_id_set.begin()));
      word_id_set.swap(new_word_id_set);
    }
  }
  return word_id_set;
}

// Utility Functions -----------------------------------------------------------

String16Set String16SetFromString16(const string16& uni_string) {
  const size_t kMaxWordLength = 64;
  String16Vector words = String16VectorFromString16(uni_string, false);
  String16Set word_set;
  for (String16Vector::const_iterator iter = words.begin(); iter != words.end();
       ++iter)
    word_set.insert(base::i18n::ToLower(*iter).substr(0, kMaxWordLength));
  return word_set;
}

String16Vector String16VectorFromString16(const string16& uni_string,
                                          bool break_on_space) {
  base::i18n::BreakIterator iter(uni_string,
      break_on_space ? base::i18n::BreakIterator::BREAK_SPACE :
          base::i18n::BreakIterator::BREAK_WORD);
  String16Vector words;
  if (!iter.Init())
    return words;
  while (iter.Advance()) {
    if (break_on_space || iter.IsWord()) {
      string16 word = iter.GetString();
      if (break_on_space)
        TrimWhitespace(word, TRIM_ALL, &word);
      if (!word.empty())
        words.push_back(word);
    }
  }
  return words;
}

Char16Set Char16SetFromString16(const string16& term) {
  Char16Set characters;
  for (string16::const_iterator iter = term.begin(); iter != term.end(); ++iter)
    characters.insert(*iter);
  return characters;
}

}  // namespace history
<commit_msg>Winbots didn't pick up on a missing include.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/history/in_memory_url_index_types.h"

#include <algorithm>
#include <functional>
#include <iterator>

#include "base/i18n/break_iterator.h"
#include "base/i18n/case_conversion.h"
#include "base/string_util.h"

namespace history {

// Matches within URL and Title Strings ----------------------------------------

TermMatches MatchTermInString(const string16& term,
                              const string16& string,
                              int term_num) {
  const size_t kMaxCompareLength = 2048;
  const string16& short_string = (string.length() > kMaxCompareLength) ?
      string.substr(0, kMaxCompareLength) : string;
  TermMatches matches;
  for (size_t location = short_string.find(term); location != string16::npos;
       location = short_string.find(term, location + 1))
    matches.push_back(TermMatch(term_num, location, term.length()));
  return matches;
}

// Comparison function for sorting TermMatches by their offsets.
bool MatchOffsetLess(const TermMatch& m1, const TermMatch& m2) {
  return m1.offset < m2.offset;
}

TermMatches SortAndDeoverlapMatches(const TermMatches& matches) {
  if (matches.empty())
    return matches;
  TermMatches sorted_matches = matches;
  std::sort(sorted_matches.begin(), sorted_matches.end(), MatchOffsetLess);
  TermMatches clean_matches;
  TermMatch last_match;
  for (TermMatches::const_iterator iter = sorted_matches.begin();
       iter != sorted_matches.end(); ++iter) {
    if (iter->offset >= last_match.offset + last_match.length) {
      last_match = *iter;
      clean_matches.push_back(last_match);
    }
  }
  return clean_matches;
}

std::vector<size_t> OffsetsFromTermMatches(const TermMatches& matches) {
  std::vector<size_t> offsets;
  for (TermMatches::const_iterator i = matches.begin(); i != matches.end(); ++i)
    offsets.push_back(i->offset);
  return offsets;
}

TermMatches ReplaceOffsetsInTermMatches(const TermMatches& matches,
                                        const std::vector<size_t>& offsets) {
  DCHECK_EQ(matches.size(), offsets.size());
  TermMatches new_matches;
  std::vector<size_t>::const_iterator offset_iter = offsets.begin();
  for (TermMatches::const_iterator term_iter = matches.begin();
       term_iter != matches.end(); ++term_iter, ++offset_iter) {
    if (*offset_iter != string16::npos) {
      TermMatch new_match(*term_iter);
      new_match.offset = *offset_iter;
      new_matches.push_back(new_match);
    }
  }
  return new_matches;
}

// ScoredHistoryMatch ----------------------------------------------------------

ScoredHistoryMatch::ScoredHistoryMatch()
    : raw_score(0),
      can_inline(false) {}

ScoredHistoryMatch::ScoredHistoryMatch(const URLRow& url_info)
    : HistoryMatch(url_info, 0, false, false),
      raw_score(0),
      can_inline(false) {}

ScoredHistoryMatch::~ScoredHistoryMatch() {}

// Comparison function for sorting ScoredMatches by their scores.
bool ScoredHistoryMatch::MatchScoreGreater(const ScoredHistoryMatch& m1,
                                           const ScoredHistoryMatch& m2) {
  return m1.raw_score >= m2.raw_score;
}

// InMemoryURLIndex's Private Data ---------------------------------------------

URLIndexPrivateData::URLIndexPrivateData() {}

URLIndexPrivateData::~URLIndexPrivateData() {}

void URLIndexPrivateData::Clear() {
  word_list_.clear();
  available_words_.clear();
  word_map_.clear();
  char_word_map_.clear();
  word_id_history_map_.clear();
  history_id_word_map_.clear();
  history_info_map_.clear();
}

void URLIndexPrivateData::AddToHistoryIDWordMap(HistoryID history_id,
                                               WordID word_id) {
  HistoryIDWordMap::iterator iter = history_id_word_map_.find(history_id);
  if (iter != history_id_word_map_.end()) {
    WordIDSet& word_id_set(iter->second);
    word_id_set.insert(word_id);
  } else {
    WordIDSet word_id_set;
    word_id_set.insert(word_id);
    history_id_word_map_[history_id] = word_id_set;
  }
}

WordIDSet URLIndexPrivateData::WordIDSetForTermChars(
    const Char16Set& term_chars) {
  WordIDSet word_id_set;
  for (Char16Set::const_iterator c_iter = term_chars.begin();
       c_iter != term_chars.end(); ++c_iter) {
    CharWordIDMap::iterator char_iter = char_word_map_.find(*c_iter);
    if (char_iter == char_word_map_.end()) {
      // A character was not found so there are no matching results: bail.
      word_id_set.clear();
      break;
    }
    WordIDSet& char_word_id_set(char_iter->second);
    // It is possible for there to no longer be any words associated with
    // a particular character. Give up in that case.
    if (char_word_id_set.empty()) {
      word_id_set.clear();
      break;
    }

    if (c_iter == term_chars.begin()) {
      // First character results becomes base set of results.
      word_id_set = char_word_id_set;
    } else {
      // Subsequent character results get intersected in.
      WordIDSet new_word_id_set;
      std::set_intersection(word_id_set.begin(), word_id_set.end(),
                            char_word_id_set.begin(), char_word_id_set.end(),
                            std::inserter(new_word_id_set,
                                          new_word_id_set.begin()));
      word_id_set.swap(new_word_id_set);
    }
  }
  return word_id_set;
}

// Utility Functions -----------------------------------------------------------

String16Set String16SetFromString16(const string16& uni_string) {
  const size_t kMaxWordLength = 64;
  String16Vector words = String16VectorFromString16(uni_string, false);
  String16Set word_set;
  for (String16Vector::const_iterator iter = words.begin(); iter != words.end();
       ++iter)
    word_set.insert(base::i18n::ToLower(*iter).substr(0, kMaxWordLength));
  return word_set;
}

String16Vector String16VectorFromString16(const string16& uni_string,
                                          bool break_on_space) {
  base::i18n::BreakIterator iter(uni_string,
      break_on_space ? base::i18n::BreakIterator::BREAK_SPACE :
          base::i18n::BreakIterator::BREAK_WORD);
  String16Vector words;
  if (!iter.Init())
    return words;
  while (iter.Advance()) {
    if (break_on_space || iter.IsWord()) {
      string16 word = iter.GetString();
      if (break_on_space)
        TrimWhitespace(word, TRIM_ALL, &word);
      if (!word.empty())
        words.push_back(word);
    }
  }
  return words;
}

Char16Set Char16SetFromString16(const string16& term) {
  Char16Set characters;
  for (string16::const_iterator iter = term.begin(); iter != term.end(); ++iter)
    characters.insert(*iter);
  return characters;
}

}  // namespace history
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ftpdynresultset.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 15:35:28 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _FTP_FTPDYNRESULTSET_HXX_
#include "ftpdynresultset.hxx"
#endif
#ifndef _FTP_FTPRESULTSETFACTORY_HXX_
#include "ftpresultsetfactory.hxx"
#endif

using namespace com::sun::star::lang;
using namespace com::sun::star::sdbc;
using namespace com::sun::star::ucb;
using namespace com::sun::star::uno;

using namespace ftp;

//=========================================================================
//=========================================================================
//
// DynamicResultSet Implementation.
//
//=========================================================================
//=========================================================================

DynamicResultSet::DynamicResultSet(
    const Reference< XMultiServiceFactory >& rxSMgr,
    const vos::ORef< FTPContent >& rxContent,
    const OpenCommandArgument2& rCommand,
    const Reference< XCommandEnvironment >& rxEnv,
    ResultSetFactory* pFactory )
    : ResultSetImplHelper( rxSMgr, rCommand ),
      m_xContent( rxContent ),
      m_xEnv( rxEnv ),
      m_pFactory( pFactory )
{
}

DynamicResultSet::~DynamicResultSet()
{
    delete m_pFactory;
}

//=========================================================================
//
// Non-interface methods.
//
//=========================================================================

void DynamicResultSet::initStatic()
{
    m_xResultSet1 = Reference< XResultSet >( m_pFactory->createResultSet() );
}

//=========================================================================
void DynamicResultSet::initDynamic()
{
    m_xResultSet1 = Reference< XResultSet >( m_pFactory->createResultSet() );

    m_xResultSet2 = m_xResultSet1;
}

<commit_msg>INTEGRATION: CWS pchfix02 (1.3.70); FILE MERGED 2006/09/01 17:55:44 kaib 1.3.70.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ftpdynresultset.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 13:51:00 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _FTP_FTPDYNRESULTSET_HXX_
#include "ftpdynresultset.hxx"
#endif
#ifndef _FTP_FTPRESULTSETFACTORY_HXX_
#include "ftpresultsetfactory.hxx"
#endif

using namespace com::sun::star::lang;
using namespace com::sun::star::sdbc;
using namespace com::sun::star::ucb;
using namespace com::sun::star::uno;

using namespace ftp;

//=========================================================================
//=========================================================================
//
// DynamicResultSet Implementation.
//
//=========================================================================
//=========================================================================

DynamicResultSet::DynamicResultSet(
    const Reference< XMultiServiceFactory >& rxSMgr,
    const vos::ORef< FTPContent >& rxContent,
    const OpenCommandArgument2& rCommand,
    const Reference< XCommandEnvironment >& rxEnv,
    ResultSetFactory* pFactory )
    : ResultSetImplHelper( rxSMgr, rCommand ),
      m_xContent( rxContent ),
      m_xEnv( rxEnv ),
      m_pFactory( pFactory )
{
}

DynamicResultSet::~DynamicResultSet()
{
    delete m_pFactory;
}

//=========================================================================
//
// Non-interface methods.
//
//=========================================================================

void DynamicResultSet::initStatic()
{
    m_xResultSet1 = Reference< XResultSet >( m_pFactory->createResultSet() );
}

//=========================================================================
void DynamicResultSet::initDynamic()
{
    m_xResultSet1 = Reference< XResultSet >( m_pFactory->createResultSet() );

    m_xResultSet2 = m_xResultSet1;
}

<|endoftext|>


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

#include "ui/base/clipboard/clipboard.h"

#include "base/logging.h"
#include "base/utf_string_conversions.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/linux_util.h"
#include "ui/gfx/size.h"

namespace ui {

namespace {
const char kMimeTypeBitmap[] = "image/bmp";
const char kMimeTypeWebkitSmartPaste[] = "chromium/x-webkit-paste";

// ClipboardData contains data copied to the Clipboard for a variety of formats.
// It mostly just provides APIs to cleanly access and manipulate this data.
class ClipboardData {
 public:
  ClipboardData()
      : bitmap_data_(),
        custom_data_data_(),
        custom_data_len_(0),
        web_smart_paste_(false) {}

  virtual ~ClipboardData() {}

  const std::string& text() const { return text_; }
  void set_text(const std::string& text) { text_ = text; }

  const std::string& markup_data() const { return markup_data_; }
  void set_markup_data(const std::string& markup_data) {
    markup_data_ = markup_data;
  }

  const std::string& url() const { return url_; }
  void set_url(const std::string& url) { url_ = url; }

  const std::string& bookmark_title() const { return bookmark_title_; }
  void set_bookmark_title(const std::string& bookmark_title) {
    bookmark_title_ = bookmark_title;
  }

  const std::string& bookmark_url() const { return bookmark_url_; }
  void set_bookmark_url(const std::string& bookmark_url) {
    bookmark_url_ = bookmark_url;
  }

  uint8_t* bitmap_data() const { return bitmap_data_.get(); }
  const gfx::Size& bitmap_size() const { return bitmap_size_; }
  void SetBitmapData(const char* pixel_data, const char* size_data) {
    bitmap_size_ = *reinterpret_cast<const gfx::Size*>(size_data);

    // We assume 4-byte pixel data.
    size_t bitmap_data_len = 4 * bitmap_size_.width() * bitmap_size_.height();
    bitmap_data_.reset(new uint8_t[bitmap_data_len]);
    memcpy(bitmap_data_.get(), pixel_data, bitmap_data_len);
  }

  const std::string& custom_data_format() const { return custom_data_format_; }
  char* custom_data_data() const { return custom_data_data_.get(); }
  size_t custom_data_len() const { return custom_data_len_; }

  void SetCustomData(const std::string& data_format,
                     const char* data_data,
                     size_t data_len) {
    custom_data_len_ = data_len;
    if (custom_data_len_ == 0) {
      custom_data_data_.reset();
      custom_data_format_.clear();
      return;
    }
    custom_data_data_.reset(new char[custom_data_len_]);
    memcpy(custom_data_data_.get(), data_data, custom_data_len_);
    custom_data_format_ = data_format;
  }

  bool web_smart_paste() const { return web_smart_paste_; }
  void set_web_smart_paste(bool web_smart_paste) {
    web_smart_paste_ = web_smart_paste;
  }

 private:
  // Plain text in UTF8 format.
  std::string text_;

  // HTML markup data in UTF8 format.
  std::string markup_data_;
  std::string url_;

  // Bookmark title in UTF8 format.
  std::string bookmark_title_;
  std::string bookmark_url_;

  // Bitmap images.
  scoped_array<uint8_t> bitmap_data_;
  gfx::Size bitmap_size_;

  // Data with custom format.
  std::string custom_data_format_;
  scoped_array<char> custom_data_data_;
  size_t custom_data_len_;

  // WebKit smart paste data.
  bool web_smart_paste_;

  DISALLOW_COPY_AND_ASSIGN(ClipboardData);
};

ClipboardData* clipboard_data = NULL;

ClipboardData* GetClipboardData() {
  if (!clipboard_data)
    clipboard_data = new ClipboardData();
  return clipboard_data;
}

void DeleteClipboardData() {
  if (clipboard_data)
    delete clipboard_data;
  clipboard_data = NULL;
}

}  // namespace

// TODO(varunjain): Complete implementation:
// 1. Handle different types of BUFFERs.
// 2. Do we need to care about concurrency here? Can there be multiple instances
//    of ui::Clipboard? Ask oshima.
// 3. Implement File types.
// 4. Handle conversion between types.

Clipboard::Clipboard() {
  // Make sure clipboard is created.
  GetClipboardData();
}

Clipboard::~Clipboard() {
}

void Clipboard::WriteObjects(const ObjectMap& objects) {
  // We need to overwrite previous data. Probably best to just delete
  // everything and start fresh.
  DeleteClipboardData();
  for (ObjectMap::const_iterator iter = objects.begin();
       iter != objects.end(); ++iter) {
    DispatchObject(static_cast<ObjectType>(iter->first), iter->second);
  }
}

void Clipboard::WriteObjects(const ObjectMap& objects,
                             base::ProcessHandle process) {
  NOTIMPLEMENTED();
}

bool Clipboard::IsFormatAvailable(const FormatType& format,
                                  Buffer buffer) const {
  ClipboardData* data = GetClipboardData();
  if (GetPlainTextFormatType() == format)
    return !data->text().empty();
  else if (GetHtmlFormatType() == format)
    return !data->markup_data().empty() || !data->url().empty();
  else if (GetBitmapFormatType() == format)
    return !!data->bitmap_data();
  else if (GetWebKitSmartPasteFormatType() == format)
    return data->web_smart_paste();
  else if (data->custom_data_format() == format)
    return true;
  return false;
}

bool Clipboard::IsFormatAvailableByString(const std::string& format,
                                          Buffer buffer) const {
  return IsFormatAvailable(format, buffer);
}

void Clipboard::ReadAvailableTypes(Buffer buffer, std::vector<string16>* types,
    bool* contains_filenames) const {
  if (!types || !contains_filenames) {
    NOTREACHED();
    return;
  }

  types->clear();
  if (IsFormatAvailable(GetPlainTextFormatType(), buffer))
    types->push_back(UTF8ToUTF16(GetPlainTextFormatType()));
  if (IsFormatAvailable(GetHtmlFormatType(), buffer))
    types->push_back(UTF8ToUTF16(GetHtmlFormatType()));
  if (IsFormatAvailable(GetBitmapFormatType(), buffer))
    types->push_back(UTF8ToUTF16(GetBitmapFormatType()));
  if (IsFormatAvailable(GetWebKitSmartPasteFormatType(), buffer))
    types->push_back(UTF8ToUTF16(GetWebKitSmartPasteFormatType()));
  *contains_filenames = false;
}

void Clipboard::ReadText(Buffer buffer, string16* result) const {
  *result = UTF8ToUTF16(GetClipboardData()->text());
}

void Clipboard::ReadAsciiText(Buffer buffer, std::string* result) const {
  *result = GetClipboardData()->text();
}

void Clipboard::ReadHTML(Buffer buffer,
                         string16* markup,
                         std::string* src_url,
                         uint32* fragment_start,
                         uint32* fragment_end) const {
  markup->clear();
  if (src_url)
    src_url->clear();
  *fragment_start = 0;
  *fragment_end = 0;

  *markup = UTF8ToUTF16(GetClipboardData()->markup_data());
  *src_url = GetClipboardData()->url();

  *fragment_start = 0;
  DCHECK(markup->length() <= kuint32max);
  *fragment_end = static_cast<uint32>(markup->length());

}

SkBitmap Clipboard::ReadImage(Buffer buffer) const {
  const gfx::Size size = GetClipboardData()->bitmap_size();
  uint8_t* bitmap = GetClipboardData()->bitmap_data();
  SkBitmap image;
  image.setConfig(SkBitmap::kARGB_8888_Config, size.width(), size.height(), 0);
  image.allocPixels();
  image.eraseARGB(0, 0, 0, 0);
  int byte_counter = 0;
  for (int i = 0; i < size.height(); ++i) {
    for (int j = 0; j < size.width(); ++j) {
      uint32* pixel = image.getAddr32(j, i);
      *pixel = (bitmap[byte_counter] << 0) +      /* R */
               (bitmap[byte_counter + 1] << 8) +  /* G */
               (bitmap[byte_counter + 2] << 16) + /* B */
               (bitmap[byte_counter + 3] << 24);  /* A */
      byte_counter += 4;
    }
  }
  return image;
}

void Clipboard::ReadBookmark(string16* title, std::string* url) const {
  *title = UTF8ToUTF16(GetClipboardData()->bookmark_title());
  *url = GetClipboardData()->bookmark_url();
}

void Clipboard::ReadFile(FilePath* file) const {
  NOTIMPLEMENTED();
}

void Clipboard::ReadFiles(std::vector<FilePath>* files) const {
  NOTIMPLEMENTED();
}

void Clipboard::ReadData(const std::string& format, std::string* result) {
  result->clear();
  ClipboardData* data = GetClipboardData();
  if (data->custom_data_format() == format)
    *result = std::string(data->custom_data_data(), data->custom_data_len());
}

uint64 Clipboard::GetSequenceNumber() {
  NOTIMPLEMENTED();
  return 0;
}

void Clipboard::WriteText(const char* text_data, size_t text_len) {
  GetClipboardData()->set_text(std::string(text_data, text_len));
}

void Clipboard::WriteHTML(const char* markup_data,
                          size_t markup_len,
                          const char* url_data,
                          size_t url_len) {
  GetClipboardData()->set_markup_data(std::string(markup_data, markup_len));
  GetClipboardData()->set_url(std::string(url_data, url_len));
}

void Clipboard::WriteBookmark(const char* title_data,
                              size_t title_len,
                              const char* url_data,
                              size_t url_len) {
  GetClipboardData()->set_bookmark_title(std::string(title_data, title_len));
  GetClipboardData()->set_bookmark_url(std::string(url_data, url_len));
}

void Clipboard::WriteWebSmartPaste() {
  GetClipboardData()->set_web_smart_paste(true);
}

void Clipboard::WriteBitmap(const char* pixel_data, const char* size_data) {
  GetClipboardData()->SetBitmapData(pixel_data, size_data);
}

void Clipboard::WriteData(const char* format_name, size_t format_len,
                          const char* data_data, size_t data_len) {
  GetClipboardData()->SetCustomData(std::string(format_name, format_len),
      data_data, data_len);
}

// static
Clipboard::FormatType Clipboard::GetPlainTextFormatType() {
  return std::string(kMimeTypeText);
}

// static
Clipboard::FormatType Clipboard::GetPlainTextWFormatType() {
  return GetPlainTextFormatType();
}

// static
Clipboard::FormatType Clipboard::GetHtmlFormatType() {
  return std::string(kMimeTypeHTML);
}

// static
Clipboard::FormatType Clipboard::GetBitmapFormatType() {
  return std::string(kMimeTypeBitmap);
}

// static
Clipboard::FormatType Clipboard::GetWebKitSmartPasteFormatType() {
  return std::string(kMimeTypeWebkitSmartPaste);
}

}  // namespace ui
<commit_msg>aura: Fix compile after change in clipboard api (in r109476).<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/base/clipboard/clipboard.h"

#include "base/logging.h"
#include "base/utf_string_conversions.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/linux_util.h"
#include "ui/gfx/size.h"

namespace ui {

namespace {
const char kMimeTypeBitmap[] = "image/bmp";
const char kMimeTypeWebkitSmartPaste[] = "chromium/x-webkit-paste";

// ClipboardData contains data copied to the Clipboard for a variety of formats.
// It mostly just provides APIs to cleanly access and manipulate this data.
class ClipboardData {
 public:
  ClipboardData()
      : bitmap_data_(),
        custom_data_data_(),
        custom_data_len_(0),
        web_smart_paste_(false) {}

  virtual ~ClipboardData() {}

  const std::string& text() const { return text_; }
  void set_text(const std::string& text) { text_ = text; }

  const std::string& markup_data() const { return markup_data_; }
  void set_markup_data(const std::string& markup_data) {
    markup_data_ = markup_data;
  }

  const std::string& url() const { return url_; }
  void set_url(const std::string& url) { url_ = url; }

  const std::string& bookmark_title() const { return bookmark_title_; }
  void set_bookmark_title(const std::string& bookmark_title) {
    bookmark_title_ = bookmark_title;
  }

  const std::string& bookmark_url() const { return bookmark_url_; }
  void set_bookmark_url(const std::string& bookmark_url) {
    bookmark_url_ = bookmark_url;
  }

  uint8_t* bitmap_data() const { return bitmap_data_.get(); }
  const gfx::Size& bitmap_size() const { return bitmap_size_; }
  void SetBitmapData(const char* pixel_data, const char* size_data) {
    bitmap_size_ = *reinterpret_cast<const gfx::Size*>(size_data);

    // We assume 4-byte pixel data.
    size_t bitmap_data_len = 4 * bitmap_size_.width() * bitmap_size_.height();
    bitmap_data_.reset(new uint8_t[bitmap_data_len]);
    memcpy(bitmap_data_.get(), pixel_data, bitmap_data_len);
  }

  const std::string& custom_data_format() const { return custom_data_format_; }
  char* custom_data_data() const { return custom_data_data_.get(); }
  size_t custom_data_len() const { return custom_data_len_; }

  void SetCustomData(const std::string& data_format,
                     const char* data_data,
                     size_t data_len) {
    custom_data_len_ = data_len;
    if (custom_data_len_ == 0) {
      custom_data_data_.reset();
      custom_data_format_.clear();
      return;
    }
    custom_data_data_.reset(new char[custom_data_len_]);
    memcpy(custom_data_data_.get(), data_data, custom_data_len_);
    custom_data_format_ = data_format;
  }

  bool web_smart_paste() const { return web_smart_paste_; }
  void set_web_smart_paste(bool web_smart_paste) {
    web_smart_paste_ = web_smart_paste;
  }

 private:
  // Plain text in UTF8 format.
  std::string text_;

  // HTML markup data in UTF8 format.
  std::string markup_data_;
  std::string url_;

  // Bookmark title in UTF8 format.
  std::string bookmark_title_;
  std::string bookmark_url_;

  // Bitmap images.
  scoped_array<uint8_t> bitmap_data_;
  gfx::Size bitmap_size_;

  // Data with custom format.
  std::string custom_data_format_;
  scoped_array<char> custom_data_data_;
  size_t custom_data_len_;

  // WebKit smart paste data.
  bool web_smart_paste_;

  DISALLOW_COPY_AND_ASSIGN(ClipboardData);
};

ClipboardData* clipboard_data = NULL;

ClipboardData* GetClipboardData() {
  if (!clipboard_data)
    clipboard_data = new ClipboardData();
  return clipboard_data;
}

void DeleteClipboardData() {
  if (clipboard_data)
    delete clipboard_data;
  clipboard_data = NULL;
}

}  // namespace

// TODO(varunjain): Complete implementation:
// 1. Handle different types of BUFFERs.
// 2. Do we need to care about concurrency here? Can there be multiple instances
//    of ui::Clipboard? Ask oshima.
// 3. Implement File types.
// 4. Handle conversion between types.

Clipboard::Clipboard() {
  // Make sure clipboard is created.
  GetClipboardData();
}

Clipboard::~Clipboard() {
}

void Clipboard::WriteObjects(const ObjectMap& objects) {
  // We need to overwrite previous data. Probably best to just delete
  // everything and start fresh.
  DeleteClipboardData();
  for (ObjectMap::const_iterator iter = objects.begin();
       iter != objects.end(); ++iter) {
    DispatchObject(static_cast<ObjectType>(iter->first), iter->second);
  }
}

void Clipboard::WriteObjects(const ObjectMap& objects,
                             base::ProcessHandle process) {
  NOTIMPLEMENTED();
}

bool Clipboard::IsFormatAvailable(const FormatType& format,
                                  Buffer buffer) const {
  ClipboardData* data = GetClipboardData();
  if (GetPlainTextFormatType() == format)
    return !data->text().empty();
  else if (GetHtmlFormatType() == format)
    return !data->markup_data().empty() || !data->url().empty();
  else if (GetBitmapFormatType() == format)
    return !!data->bitmap_data();
  else if (GetWebKitSmartPasteFormatType() == format)
    return data->web_smart_paste();
  else if (data->custom_data_format() == format)
    return true;
  return false;
}

bool Clipboard::IsFormatAvailableByString(const std::string& format,
                                          Buffer buffer) const {
  return IsFormatAvailable(format, buffer);
}

void Clipboard::ReadAvailableTypes(Buffer buffer, std::vector<string16>* types,
    bool* contains_filenames) const {
  if (!types || !contains_filenames) {
    NOTREACHED();
    return;
  }

  types->clear();
  if (IsFormatAvailable(GetPlainTextFormatType(), buffer))
    types->push_back(UTF8ToUTF16(GetPlainTextFormatType()));
  if (IsFormatAvailable(GetHtmlFormatType(), buffer))
    types->push_back(UTF8ToUTF16(GetHtmlFormatType()));
  if (IsFormatAvailable(GetBitmapFormatType(), buffer))
    types->push_back(UTF8ToUTF16(GetBitmapFormatType()));
  if (IsFormatAvailable(GetWebKitSmartPasteFormatType(), buffer))
    types->push_back(UTF8ToUTF16(GetWebKitSmartPasteFormatType()));
  *contains_filenames = false;
}

void Clipboard::ReadText(Buffer buffer, string16* result) const {
  *result = UTF8ToUTF16(GetClipboardData()->text());
}

void Clipboard::ReadAsciiText(Buffer buffer, std::string* result) const {
  *result = GetClipboardData()->text();
}

void Clipboard::ReadHTML(Buffer buffer,
                         string16* markup,
                         std::string* src_url,
                         uint32* fragment_start,
                         uint32* fragment_end) const {
  markup->clear();
  if (src_url)
    src_url->clear();
  *fragment_start = 0;
  *fragment_end = 0;

  *markup = UTF8ToUTF16(GetClipboardData()->markup_data());
  *src_url = GetClipboardData()->url();

  *fragment_start = 0;
  DCHECK(markup->length() <= kuint32max);
  *fragment_end = static_cast<uint32>(markup->length());

}

SkBitmap Clipboard::ReadImage(Buffer buffer) const {
  const gfx::Size size = GetClipboardData()->bitmap_size();
  uint8_t* bitmap = GetClipboardData()->bitmap_data();
  SkBitmap image;
  image.setConfig(SkBitmap::kARGB_8888_Config, size.width(), size.height(), 0);
  image.allocPixels();
  image.eraseARGB(0, 0, 0, 0);
  int byte_counter = 0;
  for (int i = 0; i < size.height(); ++i) {
    for (int j = 0; j < size.width(); ++j) {
      uint32* pixel = image.getAddr32(j, i);
      *pixel = (bitmap[byte_counter] << 0) +      /* R */
               (bitmap[byte_counter + 1] << 8) +  /* G */
               (bitmap[byte_counter + 2] << 16) + /* B */
               (bitmap[byte_counter + 3] << 24);  /* A */
      byte_counter += 4;
    }
  }
  return image;
}

void Clipboard::ReadBookmark(string16* title, std::string* url) const {
  *title = UTF8ToUTF16(GetClipboardData()->bookmark_title());
  *url = GetClipboardData()->bookmark_url();
}

void Clipboard::ReadFile(FilePath* file) const {
  NOTIMPLEMENTED();
}

void Clipboard::ReadFiles(std::vector<FilePath>* files) const {
  NOTIMPLEMENTED();
}

void Clipboard::ReadData(const std::string& format, std::string* result) {
  result->clear();
  ClipboardData* data = GetClipboardData();
  if (data->custom_data_format() == format)
    *result = std::string(data->custom_data_data(), data->custom_data_len());
}

uint64 Clipboard::GetSequenceNumber(Buffer buffer) {
  NOTIMPLEMENTED();
  return 0;
}

void Clipboard::WriteText(const char* text_data, size_t text_len) {
  GetClipboardData()->set_text(std::string(text_data, text_len));
}

void Clipboard::WriteHTML(const char* markup_data,
                          size_t markup_len,
                          const char* url_data,
                          size_t url_len) {
  GetClipboardData()->set_markup_data(std::string(markup_data, markup_len));
  GetClipboardData()->set_url(std::string(url_data, url_len));
}

void Clipboard::WriteBookmark(const char* title_data,
                              size_t title_len,
                              const char* url_data,
                              size_t url_len) {
  GetClipboardData()->set_bookmark_title(std::string(title_data, title_len));
  GetClipboardData()->set_bookmark_url(std::string(url_data, url_len));
}

void Clipboard::WriteWebSmartPaste() {
  GetClipboardData()->set_web_smart_paste(true);
}

void Clipboard::WriteBitmap(const char* pixel_data, const char* size_data) {
  GetClipboardData()->SetBitmapData(pixel_data, size_data);
}

void Clipboard::WriteData(const char* format_name, size_t format_len,
                          const char* data_data, size_t data_len) {
  GetClipboardData()->SetCustomData(std::string(format_name, format_len),
      data_data, data_len);
}

// static
Clipboard::FormatType Clipboard::GetPlainTextFormatType() {
  return std::string(kMimeTypeText);
}

// static
Clipboard::FormatType Clipboard::GetPlainTextWFormatType() {
  return GetPlainTextFormatType();
}

// static
Clipboard::FormatType Clipboard::GetHtmlFormatType() {
  return std::string(kMimeTypeHTML);
}

// static
Clipboard::FormatType Clipboard::GetBitmapFormatType() {
  return std::string(kMimeTypeBitmap);
}

// static
Clipboard::FormatType Clipboard::GetWebKitSmartPasteFormatType() {
  return std::string(kMimeTypeWebkitSmartPaste);
}

}  // namespace ui
<|endoftext|>