Commit message: None
CVE: CVE-2011-3964
Vulnerability description: Google Chrome before 17.0.963.46 does not properly implement the drag-and-drop feature, which makes it easier for remote attackers to spoof the URL bar via unspecified vectors.

Project: Chrome

views::View* OmniboxViewWin::AddToView(views::View* parent) {
  native_view_host_ = new OmniboxViewWrapper(this);
  parent->AddChildView(native_view_host_);
  native_view_host_->set_focus_view(parent);
  native_view_host_->Attach(GetNativeView());
  return native_view_host_;
}

Project: Chrome

  AutocompleteEditState(const AutocompleteEditModel::State& model_state,
                        const OmniboxViewWin::State& view_state)
      : model_state(model_state),
        view_state(view_state) {
  }

Project: Chrome

void OmniboxViewWin::BuildContextMenu() {
  if (context_menu_contents_.get())
    return;

  context_menu_contents_.reset(new ui::SimpleMenuModel(this));
  if (popup_window_mode_) {
    context_menu_contents_->AddItemWithStringId(IDC_COPY, IDS_COPY);
  } else {
    context_menu_contents_->AddItemWithStringId(IDS_UNDO, IDS_UNDO);
    context_menu_contents_->AddSeparator();
    context_menu_contents_->AddItemWithStringId(IDC_CUT, IDS_CUT);
    context_menu_contents_->AddItemWithStringId(IDC_COPY, IDS_COPY);
    context_menu_contents_->AddItemWithStringId(IDC_PASTE, IDS_PASTE);
    context_menu_contents_->AddItemWithStringId(IDS_PASTE_AND_GO,
                                                IDS_PASTE_AND_GO);
    context_menu_contents_->AddSeparator();
    context_menu_contents_->AddItemWithStringId(IDS_SELECT_ALL, IDS_SELECT_ALL);
    context_menu_contents_->AddSeparator();
    context_menu_contents_->AddItemWithStringId(IDS_EDIT_SEARCH_ENGINES,
                                                IDS_EDIT_SEARCH_ENGINES);
  }
  context_menu_.reset(new views::Menu2(context_menu_contents_.get()));
}

Project: Chrome

bool OmniboxViewWin::CanPasteAndGo(const string16& text) const {
  return !popup_window_mode_ && model_->CanPasteAndGo(text);
}

Project: Chrome

void OmniboxViewWin::ClosePopup() {
  model_->StopAutocomplete();
}

Project: Chrome

int CopyOrLinkDragOperation(int drag_operation) {
  if (drag_operation & ui::DragDropTypes::DRAG_COPY)
    return ui::DragDropTypes::DRAG_COPY;
  if (drag_operation & ui::DragDropTypes::DRAG_LINK)
    return ui::DragDropTypes::DRAG_LINK;
  return ui::DragDropTypes::DRAG_NONE;
}

Project: Chrome

DWORD CopyOrLinkDropEffect(DWORD effect) {
  if (effect & DROPEFFECT_COPY)
    return DROPEFFECT_COPY;
  if (effect & DROPEFFECT_LINK)
    return DROPEFFECT_LINK;
  return DROPEFFECT_NONE;
}

Project: Chrome

OmniboxView* OmniboxView::CreateOmniboxView(
    AutocompleteEditController* controller,
    ToolbarModel* toolbar_model,
    Profile* profile,
    CommandUpdater* command_updater,
    bool popup_window_mode,
    LocationBarView* location_bar) {
  if (views::Widget::IsPureViews()) {
    OmniboxViewViews* omnibox_view = new OmniboxViewViews(controller,
                                                          toolbar_model,
                                                          profile,
                                                          command_updater,
                                                          popup_window_mode,
                                                          location_bar);
    omnibox_view->Init();
    return omnibox_view;
  }
  return new OmniboxViewWin(controller,
                            toolbar_model,
                            location_bar,
                            command_updater,
                            popup_window_mode,
                            location_bar);
}

Project: Chrome

bool OmniboxViewWin::DeleteAtEndPressed() {
  return delete_at_end_pressed_;
}

Project: Chrome

void PaintPatcher::DerefPatch() {
  DCHECK(begin_paint_.is_patched());
  DCHECK(end_paint_.is_patched());
  --refcount_;
  if (refcount_ == 0) {
    begin_paint_.Unpatch();
    end_paint_.Unpatch();
  }
}

Project: Chrome

void OmniboxViewWin::DrawSlashForInsecureScheme(HDC hdc,
                                                const CRect& client_rect,
                                                const CRect& paint_clip_rect) {
  DCHECK(insecure_scheme_component_.is_nonempty());

  const int font_top = client_rect.top + font_y_adjustment_;
  const SkScalar kStrokeWidthPixels = SkIntToScalar(2);
  const int kAdditionalSpaceOutsideFont =
      static_cast<int>(ceil(kStrokeWidthPixels * 1.5f));
  const CRect scheme_rect(PosFromChar(insecure_scheme_component_.begin).x,
                          font_top + font_.GetBaseline() - font_x_height_ -
                              kAdditionalSpaceOutsideFont,
                          PosFromChar(insecure_scheme_component_.end()).x,
                          font_top + font_.GetBaseline() +
                              kAdditionalSpaceOutsideFont);

  CRect canvas_clip_rect, canvas_paint_clip_rect;
  canvas_clip_rect.IntersectRect(scheme_rect, client_rect);
  canvas_paint_clip_rect.IntersectRect(canvas_clip_rect, paint_clip_rect);
  if (canvas_paint_clip_rect.IsRectNull())
    return;  // We don't need to paint any of this region, so just bail early.
  canvas_clip_rect.OffsetRect(-scheme_rect.left, -scheme_rect.top);
  canvas_paint_clip_rect.OffsetRect(-scheme_rect.left, -scheme_rect.top);

  SkPaint paint;
  paint.setAntiAlias(true);
  paint.setStrokeWidth(kStrokeWidthPixels);
  paint.setStrokeCap(SkPaint::kRound_Cap);

  gfx::CanvasSkia canvas(gfx::Size(scheme_rect.Width(), scheme_rect.Height()),
                         false);
  SkCanvas* sk_canvas = canvas.sk_canvas();
  sk_canvas->getDevice()->accessBitmap(true).eraseARGB(0, 0, 0, 0);

  const SkScalar kEndCapRadiusPixels = kStrokeWidthPixels / SkIntToScalar(2);
  const SkPoint start_point = {
      kEndCapRadiusPixels,
      SkIntToScalar(scheme_rect.Height()) - kEndCapRadiusPixels };
  const SkPoint end_point = {
      SkIntToScalar(scheme_rect.Width()) - kEndCapRadiusPixels,
      kEndCapRadiusPixels };

  CHARRANGE sel;
  GetSel(sel);
  const SkRect selection_rect = {
      SkIntToScalar(PosFromChar(sel.cpMin).x - scheme_rect.left),
      SkIntToScalar(0),
      SkIntToScalar(PosFromChar(sel.cpMax).x - scheme_rect.left),
      SkIntToScalar(scheme_rect.Height()) };

  sk_canvas->save();
  if (selection_rect.isEmpty() ||
      sk_canvas->clipRect(selection_rect, SkRegion::kDifference_Op)) {
    paint.setColor(LocationBarView::GetColor(security_level_,
                                             LocationBarView::SECURITY_TEXT));
    sk_canvas->drawLine(start_point.fX, start_point.fY,
                        end_point.fX, end_point.fY, paint);
  }
  sk_canvas->restore();

  if (!selection_rect.isEmpty() && sk_canvas->clipRect(selection_rect)) {
    paint.setColor(LocationBarView::GetColor(security_level_,
                                             LocationBarView::SELECTED_TEXT));
    sk_canvas->drawLine(start_point.fX, start_point.fY,
                        end_point.fX, end_point.fY, paint);
  }

  skia::DrawToNativeContext(sk_canvas, hdc,
      scheme_rect.left + canvas_paint_clip_rect.left - canvas_clip_rect.left,
      std::max(scheme_rect.top, client_rect.top) + canvas_paint_clip_rect.top -
          canvas_clip_rect.top, &canvas_paint_clip_rect);
}

Project: Chrome

OmniboxViewWin::EditDropTarget::EditDropTarget(OmniboxViewWin* edit)
    : ui::DropTarget(edit->m_hWnd),
      edit_(edit),
      drag_has_url_(false),
      drag_has_string_(false) {
}

Project: Chrome

void OmniboxViewWin::EmphasizeURLComponents() {
  ITextDocument* const text_object_model = GetTextObjectModel();
  ScopedFreeze freeze(this, text_object_model);
  ScopedSuspendUndo suspend_undo(text_object_model);

  CHARRANGE saved_sel;
  GetSelection(saved_sel);

  url_parse::Component scheme, host;
  AutocompleteInput::ParseForEmphasizeComponents(
      GetText(), model_->GetDesiredTLD(), &scheme, &host);
  const bool emphasize = model_->CurrentTextIsURL() && (host.len > 0);

  CHARFORMAT cf = {0};
  cf.dwMask = CFM_COLOR;
  cf.crTextColor = skia::SkColorToCOLORREF(LocationBarView::GetColor(
      security_level_,
      emphasize ? LocationBarView::DEEMPHASIZED_TEXT : LocationBarView::TEXT));
  SelectAll(false);
  SetSelectionCharFormat(cf);

  if (emphasize) {
    cf.crTextColor = skia::SkColorToCOLORREF(LocationBarView::GetColor(
        security_level_, LocationBarView::TEXT));
    SetSelection(host.begin, host.end());
    SetSelectionCharFormat(cf);
  }

  insecure_scheme_component_.reset();
  if (!model_->user_input_in_progress() && scheme.is_nonempty() &&
      (security_level_ != ToolbarModel::NONE)) {
    if (security_level_ == ToolbarModel::SECURITY_ERROR) {
      insecure_scheme_component_.begin = scheme.begin;
      insecure_scheme_component_.len = scheme.len;
    }
    cf.crTextColor = skia::SkColorToCOLORREF(LocationBarView::GetColor(
        security_level_, LocationBarView::SECURITY_TEXT));
    SetSelection(scheme.begin, scheme.end());
    SetSelectionCharFormat(cf);
  }

  SetSelectionRange(saved_sel);
}

Project: Chrome

BOOL WINAPI EndPaintIntercept(HWND hWnd, const PAINTSTRUCT* lpPaint) {
  return (edit_hwnd && (hWnd == edit_hwnd)) || ::EndPaint(hWnd, lpPaint);
}

Project: Chrome

void OmniboxViewWin::EraseTopOfSelection(CDC* dc,
                                         const CRect& client_rect,
                                         const CRect& paint_clip_rect) {
  CRect erase_rect(client_rect.left, client_rect.top, client_rect.right,
                   client_rect.top + font_y_adjustment_);
  erase_rect.IntersectRect(erase_rect, paint_clip_rect);

  if (!erase_rect.IsRectNull())
    dc->FillSolidRect(&erase_rect, background_color_);
}

Project: Chrome

void OmniboxViewWin::ExecuteCommand(int command_id) {
  ScopedFreeze freeze(this, GetTextObjectModel());
  if (command_id == IDS_PASTE_AND_GO) {
    model_->PasteAndGo();
    return;
  }

  OnBeforePossibleChange();
  switch (command_id) {
    case IDS_UNDO:
      Undo();
      break;

    case IDC_CUT:
      Cut();
      break;

    case IDC_COPY:
      Copy();
      break;

    case IDC_PASTE:
      Paste();
      break;

    case IDS_SELECT_ALL:
      SelectAll(false);
      break;

    case IDS_EDIT_SEARCH_ENGINES:
      command_updater_->ExecuteCommand(IDC_EDIT_SEARCH_ENGINES);
      break;

    default:
      NOTREACHED();
      break;
  }
  OnAfterPossibleChange();
}

Project: Chrome

bool OmniboxViewWin::GetAcceleratorForCommandId(
    int command_id,
    ui::Accelerator* accelerator) {
  return parent_view_->GetWidget()->GetAccelerator(command_id, accelerator);
}

Project: Chrome

  virtual void GetAccessibleState(ui::AccessibleViewState* state) {
    views::NativeViewHost::GetAccessibleState(state);
    state->name = l10n_util::GetStringUTF16(IDS_ACCNAME_LOCATION);
    state->role = ui::AccessibilityTypes::ROLE_TEXT;
    state->value = omnibox_view_win_->GetText();
    state->state = ui::AccessibilityTypes::STATE_EDITABLE;
    size_t sel_start;
    size_t sel_end;
    omnibox_view_win_->GetSelectionBounds(&sel_start, &sel_end);
    state->selection_start = sel_start;
    state->selection_end = sel_end;
  }

Project: Chrome

string16 OmniboxViewWin::GetClipboardText() const {
  ui::Clipboard* clipboard = g_browser_process->clipboard();
  if (clipboard->IsFormatAvailable(ui::Clipboard::GetPlainTextWFormatType(),
                                   ui::Clipboard::BUFFER_STANDARD)) {
    string16 text;
    clipboard->ReadText(ui::Clipboard::BUFFER_STANDARD, &text);
    return StripJavascriptSchemas(CollapseWhitespace(text, true));
  }

  if (clipboard->IsFormatAvailable(ui::Clipboard::GetUrlWFormatType(),
                                   ui::Clipboard::BUFFER_STANDARD)) {
    std::string url_str;
    clipboard->ReadBookmark(NULL, &url_str);
    GURL url(url_str);
    if (url.is_valid())
      return StripJavascriptSchemas(UTF8ToUTF16(url.spec()));
  }

  return string16();
}

Project: Chrome

CommandUpdater* OmniboxViewWin::GetCommandUpdater() {
  return command_updater_;
}

Project: Chrome

gfx::Font OmniboxViewWin::GetFont() {
  return font_;
}

Project: Chrome

int OmniboxViewWin::GetHorizontalMargin() const {
  RECT rect;
  GetRect(&rect);
  RECT client_rect;
  GetClientRect(&client_rect);
  return (rect.left - client_rect.left) + (client_rect.right - rect.right);
}

Project: Chrome

int OmniboxViewWin::GetIcon() const {
  return IsEditingOrEmpty() ?
      AutocompleteMatch::TypeToIcon(model_->CurrentTextType()) :
      toolbar_model_->GetIcon();
}

Project: Chrome

string16 OmniboxViewWin::GetInstantSuggestion() const {
  return parent_view_->GetInstantSuggestion();
}

Project: Chrome

string16 OmniboxViewWin::GetLabelForCommandId(int command_id) const {
  DCHECK_EQ(IDS_PASTE_AND_GO, command_id);
  return l10n_util::GetStringUTF16(model_->is_paste_and_search() ?
      IDS_PASTE_AND_SEARCH : IDS_PASTE_AND_GO);
}

Project: Chrome

int OmniboxViewWin::GetMaxEditWidth(int entry_width) const {
  RECT formatting_rect;
  GetRect(&formatting_rect);
  RECT edit_bounds;
  GetClientRect(&edit_bounds);
  return entry_width - formatting_rect.left -
      (edit_bounds.right - formatting_rect.right);
}

Project: Chrome

gfx::NativeView OmniboxViewWin::GetRelativeWindowForNativeView(
    gfx::NativeView edit_native_view) {
  HWND ime_window = ImmGetDefaultIMEWnd(edit_native_view);
  return ime_window ? ime_window : HWND_NOTOPMOST;
}

Project: Chrome

gfx::NativeView OmniboxViewWin::GetRelativeWindowForPopup() const {
  return GetRelativeWindowForNativeView(GetNativeView());
}

Project: Chrome

string16 OmniboxViewWin::GetSelectedText() const {
  CHARRANGE sel;
  GetSel(sel);
  string16 str;
  if (sel.cpMin != sel.cpMax)
    GetSelText(WriteInto(&str, sel.cpMax - sel.cpMin + 1));
  return str;
}

Project: Chrome

void OmniboxViewWin::GetSelection(CHARRANGE& sel) const {
  GetSel(sel);

  ITextDocument* const text_object_model = GetTextObjectModel();
  if (!text_object_model)
    return;
  base::win::ScopedComPtr<ITextSelection> selection;
  const HRESULT hr = text_object_model->GetSelection(selection.Receive());
  DCHECK_EQ(S_OK, hr);
  long flags;
  selection->GetFlags(&flags);
  if (flags & tomSelStartActive)
    std::swap(sel.cpMin, sel.cpMax);
}

Project: Chrome

void OmniboxViewWin::GetSelectionBounds(string16::size_type* start,
                                        string16::size_type* end) const {
  CHARRANGE selection;
  GetSel(selection);
  *start = static_cast<size_t>(selection.cpMin);
  *end = static_cast<size_t>(selection.cpMax);
}

Project: Chrome

base::PropertyAccessor<AutocompleteEditState>* GetStateAccessor() {
  static base::PropertyAccessor<AutocompleteEditState> state;
  return &state;
}

Project: Chrome

string16 OmniboxViewWin::GetText() const {
  const int len = GetTextLength() + 1;
  string16 str;
  if (len > 1)
    GetWindowText(WriteInto(&str, len), len);
  return str;
}

Project: Chrome

ITextDocument* OmniboxViewWin::GetTextObjectModel() const {
  if (!text_object_model_) {
    base::win::ScopedComPtr<IRichEditOle, NULL> ole_interface;
    ole_interface.Attach(GetOleInterface());
    if (ole_interface) {
      ole_interface.QueryInterface(
          __uuidof(ITextDocument),
          reinterpret_cast<void**>(&text_object_model_));
    }
  }
  return text_object_model_;
}

Project: Chrome

void OmniboxViewWin::HandleExternalMsg(UINT msg,
                                       UINT flags,
                                       const CPoint& screen_point) {
  if (msg == WM_CAPTURECHANGED) {
    SendMessage(msg, 0, NULL);
    return;
  }

  CPoint client_point(screen_point);
  ::MapWindowPoints(NULL, m_hWnd, &client_point, 1);
  SendMessage(msg, flags, MAKELPARAM(client_point.x, client_point.y));
}

Project: Chrome

void OmniboxViewWin::HandleKeystroke(UINT message,
                                     TCHAR key,
                                     UINT repeat_count,
                                     UINT flags) {
  ScopedFreeze freeze(this, GetTextObjectModel());
  OnBeforePossibleChange();

  if (key == ui::VKEY_HOME || key == ui::VKEY_END) {
    HKL layout = GetKeyboardLayout(0);
    DefWindowProc(message, key, MAKELPARAM(repeat_count, flags));
    ActivateKeyboardLayout(layout, KLF_REORDER);
  } else {
    DefWindowProc(message, key, MAKELPARAM(repeat_count, flags));
  }

  const int lang_options = SendMessage(EM_GETLANGOPTIONS, 0, 0);
  if (lang_options & IMF_AUTOKEYBOARD)
    SendMessage(EM_SETLANGOPTIONS, 0, lang_options & ~IMF_AUTOKEYBOARD);

  OnAfterPossibleChange();
}

Project: Chrome

void OmniboxViewWin::InsertText(int position, const string16& text) {
  DCHECK((position >= 0) && (position <= GetTextLength()));
  ScopedFreeze freeze(this, GetTextObjectModel());
  OnBeforePossibleChange();
  SetSelection(position, position);
  ReplaceSel(text.c_str());
  OnAfterPossibleChange();
}

Project: Chrome

bool OmniboxViewWin::IsCaretAtEnd() const {
  long length = GetTextLength();
  CHARRANGE sel;
  GetSelection(sel);
  return sel.cpMin == sel.cpMax && sel.cpMin == length;
}

Project: Chrome

bool OmniboxViewWin::IsCommandIdChecked(int command_id) const {
  return false;
}

Project: Chrome

bool OmniboxViewWin::IsCommandIdEnabled(int command_id) const {
  switch (command_id) {
    case IDS_UNDO:         return !!CanUndo();
    case IDC_CUT:          return !!CanCut();
    case IDC_COPY:         return !!CanCopy();
    case IDC_PASTE:        return !!CanPaste();
    case IDS_PASTE_AND_GO: return CanPasteAndGo(GetClipboardText());
    case IDS_SELECT_ALL:   return !!CanSelectAll();
    case IDS_EDIT_SEARCH_ENGINES:
      return command_updater_->IsCommandEnabled(IDC_EDIT_SEARCH_ENGINES);
    default:
      NOTREACHED();
      return false;
  }
}

Project: Chrome

bool IsDrag(const POINT& origin, const POINT& current) {
  return views::View::ExceededDragThreshold(current.x - origin.x,
                                            current.y - origin.y);
}

Project: Chrome

bool OmniboxViewWin::IsImeComposing() const {
  bool ime_composing = false;
  HIMC context = ImmGetContext(m_hWnd);
  if (context) {
    ime_composing = !!ImmGetCompositionString(context, GCS_COMPSTR, NULL, 0);
    ImmReleaseContext(m_hWnd, context);
  }
  return ime_composing;
}

Project: Chrome

bool OmniboxViewWin::IsSelectAll() {
  CHARRANGE selection;
  GetSel(selection);
  return IsSelectAllForRange(selection);
}

Project: Chrome

bool OmniboxViewWin::IsSelectAllForRange(const CHARRANGE& sel) const {
  const int text_length = GetTextLength();
  return ((sel.cpMin == 0) && (sel.cpMax >= text_length)) ||
      ((sel.cpMax == 0) && (sel.cpMin >= text_length));
}

Project: Chrome

void OmniboxViewWin::MoveSelectedText(int new_position) {
  const string16 selected_text(GetSelectedText());
  CHARRANGE sel;
  GetSel(sel);
  DCHECK((sel.cpMax != sel.cpMin) && (new_position >= 0) &&
         (new_position <= GetTextLength()));

  ScopedFreeze freeze(this, GetTextObjectModel());
  OnBeforePossibleChange();

  ReplaceSel(L"", TRUE);

  if (new_position >= sel.cpMin)
    new_position -= (sel.cpMax - sel.cpMin);
  PlaceCaretAt(new_position);
  ReplaceSel(selected_text.c_str(), TRUE);

  OnAfterPossibleChange();
}

Project: Chrome

OmniboxViewWin::OmniboxViewWin(AutocompleteEditController* controller,
                               ToolbarModel* toolbar_model,
                               LocationBarView* parent_view,
                               CommandUpdater* command_updater,
                               bool popup_window_mode,
                               views::View* location_bar)
    : model_(new AutocompleteEditModel(this, controller,
                                       parent_view->browser()->profile())),
      popup_view_(new AutocompletePopupContentsView(parent_view->font(), this,
                                                    model_.get(),
                                                    location_bar)),
      controller_(controller),
      parent_view_(parent_view),
      toolbar_model_(toolbar_model),
      command_updater_(command_updater),
      popup_window_mode_(popup_window_mode),
      force_hidden_(false),
      tracking_click_(),
      tracking_double_click_(false),
      double_click_time_(0),
      can_discard_mousemove_(false),
      ignore_ime_messages_(false),
      delete_at_end_pressed_(false),
      font_(parent_view->font()),
      possible_drag_(false),
      in_drag_(false),
      initiated_drag_(false),
      drop_highlight_position_(-1),
      ime_candidate_window_open_(false),
      background_color_(skia::SkColorToCOLORREF(LocationBarView::GetColor(
          ToolbarModel::NONE, LocationBarView::BACKGROUND))),
      security_level_(ToolbarModel::NONE),
      text_object_model_(NULL) {
  CreateTextServices(NULL, NULL, NULL);

  saved_selection_for_focus_change_.cpMin = -1;

  g_paint_patcher.Pointer()->RefPatch();

  Create(location_bar->GetWidget()->GetNativeView(), 0, 0, 0,
         l10n_util::GetExtendedStyles());
  SetReadOnly(popup_window_mode_);
  SetFont(font_.GetNativeFont());

  SendMessage(m_hWnd, EM_SETWORDBREAKPROC, 0,
              reinterpret_cast<LPARAM>(&WordBreakProc));

  HDC dc = ::GetDC(NULL);
  SelectObject(dc, font_.GetNativeFont());
  TEXTMETRIC tm = {0};
  GetTextMetrics(dc, &tm);
  const float kXHeightRatio = 0.7f;  // The ratio of a font's x-height to its
  font_x_height_ = static_cast<int>((static_cast<float>(font_.GetBaseline() -
      tm.tmInternalLeading) * kXHeightRatio) + 0.5);
  const int kTextBaseline = popup_window_mode_ ? 15 : 18;
  font_y_adjustment_ = kTextBaseline - font_.GetBaseline();

  const long kTwipsPerPixel = kTwipsPerInch / GetDeviceCaps(dc, LOGPIXELSY);
  ::ReleaseDC(NULL, dc);

  CHARFORMAT cf = {0};
  cf.dwMask = CFM_OFFSET;
  cf.yOffset = -font_y_adjustment_ * kTwipsPerPixel;
  SetDefaultCharFormat(cf);

  SetBackgroundColor(background_color_);

  RevokeDragDrop(m_hWnd);

  if (!popup_window_mode_) {
    scoped_refptr<EditDropTarget> drop_target = new EditDropTarget(this);
    RegisterDragDrop(m_hWnd, drop_target.get());
  }
}

Project: Chrome

  explicit OmniboxViewWrapper(OmniboxViewWin* omnibox_view_win)
      : omnibox_view_win_(omnibox_view_win) {}

Project: Chrome

bool OmniboxViewWin::OnAfterPossibleChange() {
  return OnAfterPossibleChangeInternal(false);
}

Project: Chrome

bool OmniboxViewWin::OnAfterPossibleChangeInternal(bool force_text_changed) {
  CHARRANGE new_sel;
  GetSelection(new_sel);
  const int length = GetTextLength();
  if ((new_sel.cpMin > length) || (new_sel.cpMax > length)) {
    if (new_sel.cpMin > length)
      new_sel.cpMin = length;
    if (new_sel.cpMax > length)
      new_sel.cpMax = length;
    SetSelectionRange(new_sel);
  }
  const bool selection_differs =
      ((new_sel.cpMin != new_sel.cpMax) ||
       (sel_before_change_.cpMin != sel_before_change_.cpMax)) &&
      ((new_sel.cpMin != sel_before_change_.cpMin) ||
       (new_sel.cpMax != sel_before_change_.cpMax));

  const string16 new_text(GetText());
  const bool text_differs = (new_text != text_before_change_) ||
      force_text_changed;

  const bool just_deleted_text =
      (text_before_change_.length() > new_text.length()) &&
      (new_sel.cpMin <= std::min(sel_before_change_.cpMin,
                                 sel_before_change_.cpMax));

  const bool something_changed = model_->OnAfterPossibleChange(
      new_text, new_sel.cpMin, new_sel.cpMax, selection_differs,
      text_differs, just_deleted_text, !IsImeComposing());

  if (selection_differs)
    controller_->OnSelectionBoundsChanged();

  if (something_changed && text_differs)
    TextChanged();

  if (text_differs) {
    native_view_host_->GetWidget()->NotifyAccessibilityEvent(
        native_view_host_, ui::AccessibilityTypes::EVENT_TEXT_CHANGED, true);
  } else if (selection_differs) {
    native_view_host_->GetWidget()->NotifyAccessibilityEvent(
        native_view_host_,
        ui::AccessibilityTypes::EVENT_SELECTION_CHANGED,
        true);
  } else if (delete_at_end_pressed_) {
    model_->OnChanged();
  }

  return something_changed;
}

Project: Chrome

void OmniboxViewWin::OnBeforePossibleChange() {
  text_before_change_ = GetText();
  GetSelection(sel_before_change_);
}

Project: Chrome

void OmniboxViewWin::OnChar(TCHAR ch, UINT repeat_count, UINT flags) {
  if (ch == VK_RETURN && (flags & KF_ALTDOWN))
    return;

  if (ch == VK_ESCAPE && !(flags & KF_ALTDOWN))
    return;

  if (ch == VK_TAB) {
    return;
  }

  HandleKeystroke(GetCurrentMessage()->message, ch, repeat_count, flags);
}

Project: Chrome

void OmniboxViewWin::OnContextMenu(HWND window, const CPoint& point) {
  BuildContextMenu();
  if (point.x == -1 || point.y == -1) {
    POINT p;
    GetCaretPos(&p);
    MapWindowPoints(HWND_DESKTOP, &p, 1);
    context_menu_->RunContextMenuAt(gfx::Point(p));
  } else {
    context_menu_->RunContextMenuAt(gfx::Point(point));
  }
}

Project: Chrome

void OmniboxViewWin::OnCopy() {
  string16 text(GetSelectedText());
  if (text.empty())
    return;

  CHARRANGE sel;
  GURL url;
  bool write_url = false;
  GetSel(sel);
  model_->AdjustTextForCopy(sel.cpMin, IsSelectAll(), &text, &url, &write_url);
  ui::ScopedClipboardWriter scw(g_browser_process->clipboard());
  scw.WriteText(text);
  if (write_url) {
    scw.WriteBookmark(text, url.spec());
    scw.WriteHyperlink(net::EscapeForHTML(text), url.spec());
  }
}

Project: Chrome

void OmniboxViewWin::OnCut() {
  OnCopy();

  ReplaceSel(L"", true);
}

Project: Chrome

DWORD OmniboxViewWin::EditDropTarget::OnDragEnter(IDataObject* data_object,
                                                  DWORD key_state,
                                                  POINT cursor_position,
                                                  DWORD effect) {
  ui::OSExchangeData os_data(new ui::OSExchangeDataProviderWin(data_object));
  drag_has_url_ = os_data.HasURL();
  drag_has_string_ = !drag_has_url_ && os_data.HasString();
  if (drag_has_url_) {
    if (edit_->in_drag()) {
      drag_has_url_ = false;
    }
  }
  return OnDragOver(data_object, key_state, cursor_position, effect);
}

Project: Chrome

void OmniboxViewWin::EditDropTarget::OnDragLeave(IDataObject* data_object) {
  ResetDropHighlights();
}

Project: Chrome

DWORD OmniboxViewWin::EditDropTarget::OnDragOver(IDataObject* data_object,
                                                 DWORD key_state,
                                                 POINT cursor_position,
                                                 DWORD effect) {
  if (drag_has_url_)
    return CopyOrLinkDropEffect(effect);

  if (drag_has_string_) {
    UpdateDropHighlightPosition(cursor_position);
    if (edit_->drop_highlight_position() == -1 && edit_->in_drag())
      return DROPEFFECT_NONE;
    if (edit_->in_drag()) {
      DCHECK((effect & DROPEFFECT_COPY) && (effect & DROPEFFECT_MOVE));
      return (key_state & MK_CONTROL) ? DROPEFFECT_COPY : DROPEFFECT_MOVE;
    }
    return CopyOrLinkDropEffect(effect);
  }

  return DROPEFFECT_NONE;
}

Project: Chrome

DWORD OmniboxViewWin::EditDropTarget::OnDrop(IDataObject* data_object,
                                             DWORD key_state,
                                             POINT cursor_position,
                                             DWORD effect) {
  effect = OnDragOver(data_object, key_state, cursor_position, effect);

  ui::OSExchangeData os_data(new ui::OSExchangeDataProviderWin(data_object));
  views::DropTargetEvent event(os_data, cursor_position.x, cursor_position.y,
      ui::DragDropTypes::DropEffectToDragOperation(effect));

  int drag_operation = edit_->OnPerformDropImpl(event, edit_->in_drag());

  if (!drag_has_url_)
    ResetDropHighlights();

  return ui::DragDropTypes::DragOperationToDropEffect(drag_operation);
}

Project: Chrome

LRESULT OmniboxViewWin::OnGetObject(UINT message,
                                    WPARAM wparam,
                                    LPARAM lparam) {
  if (lparam == OBJID_CLIENT) {
    return LresultFromObject(IID_IAccessible, wparam,
                             native_view_host_->GetNativeViewAccessible());
  }
  return 0;
}

Project: Chrome

LRESULT OmniboxViewWin::OnImeComposition(UINT message,
                                         WPARAM wparam,
                                         LPARAM lparam) {
  if (ignore_ime_messages_) {
    return DefWindowProc(message, wparam, lparam);
  }

  ScopedFreeze freeze(this, GetTextObjectModel());
  OnBeforePossibleChange();
  LRESULT result = DefWindowProc(message, wparam, lparam);
  OnAfterPossibleChangeInternal((lparam & GCS_RESULTSTR) != 0);
  return result;
}

Project: Chrome

LRESULT OmniboxViewWin::OnImeNotify(UINT message,
                                    WPARAM wparam,
                                    LPARAM lparam) {
  switch (wparam) {
    case IMN_OPENCANDIDATE:
      ime_candidate_window_open_ = true;
      ClosePopup();
      break;
    case IMN_CLOSECANDIDATE:
      ime_candidate_window_open_ = false;
      UpdatePopup();
      break;
    default:
      break;
  }
  return DefWindowProc(message, wparam, lparam);
}

Project: Chrome

bool OmniboxViewWin::OnInlineAutocompleteTextMaybeChanged(
    const string16& display_text,
    size_t user_text_length) {
  if (display_text == GetText())
    return false;

  ScopedFreeze freeze(this, GetTextObjectModel());
  SetWindowText(display_text.c_str());
  SetSelection(static_cast<LONG>(display_text.length()),
               static_cast<LONG>(user_text_length));
  TextChanged();
  return true;
}

Project: Chrome

void OmniboxViewWin::OnKeyDown(TCHAR key,
                               UINT repeat_count,
                               UINT flags) {
  delete_at_end_pressed_ = false;

  if (OnKeyDownAllModes(key, repeat_count, flags))
    return;

  if (popup_window_mode_) {
    DefWindowProc(GetCurrentMessage()->message, key, MAKELPARAM(repeat_count,
                                                                flags));
    return;
  }

  if (OnKeyDownOnlyWritable(key, repeat_count, flags))
    return;

  HandleKeystroke(GetCurrentMessage()->message, key, repeat_count, flags);
}

Project: Chrome

bool OmniboxViewWin::OnKeyDownOnlyWritable(TCHAR key,
                                           UINT repeat_count,
                                           UINT flags) {

  int count = repeat_count;
  switch (key) {
    case VK_RIGHT:
      if (base::i18n::IsRTL())
        return false;
      {
        CHARRANGE selection;
        GetSel(selection);
        return (selection.cpMin == selection.cpMax) &&
            (selection.cpMin == GetTextLength()) &&
            model_->CommitSuggestedText(true);
      }

    case VK_RETURN:
      model_->AcceptInput((flags & KF_ALTDOWN) ?
          NEW_FOREGROUND_TAB : CURRENT_TAB, false);
      return true;

    case VK_PRIOR:
    case VK_NEXT:
      count = model_->result().size();
    case VK_UP:
    case VK_DOWN:
      if ((flags & KF_ALTDOWN) && !(flags & KF_EXTENDED))
        return false;

      model_->OnUpOrDownKeyPressed(((key == VK_PRIOR) || (key == VK_UP)) ?
          -count : count);
      return true;


    case VK_DELETE:
      if (flags & KF_ALTDOWN)
        return false;
      if (GetKeyState(VK_SHIFT) >= 0) {
        if (GetKeyState(VK_CONTROL) >= 0) {
          CHARRANGE selection;
          GetSel(selection);
          delete_at_end_pressed_ = ((selection.cpMin == selection.cpMax) &&
                                    (selection.cpMin == GetTextLength()));
        }
        return false;
      }
      if (GetKeyState(VK_CONTROL) >= 0) {
        CHARRANGE selection;
        GetSel(selection);
        if (selection.cpMin != selection.cpMax) {
          ScopedFreeze freeze(this, GetTextObjectModel());
          OnBeforePossibleChange();
          Cut();
          OnAfterPossibleChange();
        } else {
          if (model_->popup_model()->IsOpen()) {
            model_->popup_model()->TryDeletingCurrentItem();
          }
        }
      }
      return true;

    case 'X':
      if ((flags & KF_ALTDOWN) || (GetKeyState(VK_CONTROL) >= 0))
        return false;
      if (GetKeyState(VK_SHIFT) >= 0) {
        ScopedFreeze freeze(this, GetTextObjectModel());
        OnBeforePossibleChange();
        Cut();
        OnAfterPossibleChange();
      }
      return true;

    case VK_INSERT:
      if (!(flags & KF_ALTDOWN) && (GetKeyState(VK_SHIFT) >= 0) &&
          (GetKeyState(VK_CONTROL) >= 0))
        return true;
    case 'V':
      if ((flags & KF_ALTDOWN) ||
          (GetKeyState((key == 'V') ? VK_CONTROL : VK_SHIFT) >= 0))
        return false;
      if (GetKeyState((key == 'V') ? VK_SHIFT : VK_CONTROL) >= 0) {
        ScopedFreeze freeze(this, GetTextObjectModel());
        OnBeforePossibleChange();
        Paste();
        OnAfterPossibleChange();
      }
      return true;

    case VK_BACK: {
      if ((flags & KF_ALTDOWN) || model_->is_keyword_hint() ||
          model_->keyword().empty())
        return false;

      {
        CHARRANGE selection;
        GetSel(selection);
        if ((selection.cpMin != selection.cpMax) || (selection.cpMin != 0))
          return false;
      }

      ScopedFreeze freeze(this, GetTextObjectModel());
      model_->ClearKeyword(GetText());
      return true;
    }

    case VK_TAB: {
      if (model_->is_keyword_hint()) {
        ScopedFreeze freeze(this, GetTextObjectModel());
        model_->AcceptKeyword();
      } else if (!IsCaretAtEnd()) {
        ScopedFreeze freeze(this, GetTextObjectModel());
        OnBeforePossibleChange();
        PlaceCaretAt(GetTextLength());
        OnAfterPossibleChange();
      } else {
        model_->CommitSuggestedText(true);
      }
      return true;
    }

    case 0xbb:  // Ctrl-'='.  Triggers subscripting (even in plain text mode).
      return true;

    default:
      return false;
  }
}

Project: Chrome

void OmniboxViewWin::OnKeyUp(TCHAR key,
                             UINT repeat_count,
                             UINT flags) {
  if (key == VK_CONTROL)
    model_->OnControlKeyChanged(false);

  if (!(flags & KF_ALTDOWN) &&
      (((key == VK_CONTROL) && (GetKeyState(VK_SHIFT) < 0)) ||
       ((key == VK_SHIFT) && (GetKeyState(VK_CONTROL) < 0)))) {
    ScopedFreeze freeze(this, GetTextObjectModel());

    string16 saved_text(GetText());
    CHARRANGE saved_sel;
    GetSelection(saved_sel);

    SetWindowText(L"");

    DefWindowProc(WM_KEYUP, key, MAKELPARAM(repeat_count, flags));

    SetWindowText(saved_text.c_str());
    SetSelectionRange(saved_sel);
    return;
  }

  SetMsgHandled(false);
}

Project: Chrome

void OmniboxViewWin::OnKillFocus(HWND focus_wnd) {
  if (m_hWnd == focus_wnd) {
    SetMsgHandled(false);
    return;
  }

  model_->OnWillKillFocus(focus_wnd);

  ClosePopup();

  GetSelection(saved_selection_for_focus_change_);

  model_->OnKillFocus();

  ScopedFreeze freeze(this, GetTextObjectModel());
  DefWindowProc(WM_KILLFOCUS, reinterpret_cast<WPARAM>(focus_wnd), 0);

  SelectAll(true);
  PlaceCaretAt(0);
}

Project: Chrome

void OmniboxViewWin::OnLButtonDblClk(UINT keys, const CPoint& point) {
  tracking_double_click_ = true;
  double_click_point_ = point;
  double_click_time_ = GetCurrentMessage()->time;
  possible_drag_ = false;

  ScopedFreeze freeze(this, GetTextObjectModel());
  OnBeforePossibleChange();
  DefWindowProc(WM_LBUTTONDBLCLK, keys,
                MAKELPARAM(ClipXCoordToVisibleText(point.x, false), point.y));
  OnAfterPossibleChange();

  gaining_focus_.reset();  // See NOTE in OnMouseActivate().
}

Project: Chrome

void OmniboxViewWin::OnLButtonDown(UINT keys, const CPoint& point) {
  TrackMousePosition(kLeft, point);
  if (gaining_focus_.get()) {
    saved_selection_for_focus_change_.cpMin = -1;

    DefWindowProc(WM_LBUTTONDOWN, keys, MAKELPARAM(point.x, point.y));
    DefWindowProc(WM_LBUTTONUP, keys, MAKELPARAM(point.x, point.y));
  }

  const bool is_triple_click = tracking_double_click_ &&
      views::NativeTextfieldWin::IsDoubleClick(double_click_point_, point,
          GetCurrentMessage()->time - double_click_time_);
  tracking_double_click_ = false;

  if (!gaining_focus_.get() && !is_triple_click)
    OnPossibleDrag(point);


  ScopedFreeze freeze(this, GetTextObjectModel());
  OnBeforePossibleChange();
  DefWindowProc(WM_LBUTTONDOWN, keys,
                MAKELPARAM(ClipXCoordToVisibleText(point.x, is_triple_click),
                           point.y));
  OnAfterPossibleChange();

  gaining_focus_.reset();
}

Project: Chrome

void OmniboxViewWin::OnLButtonUp(UINT keys, const CPoint& point) {
  ScopedFreeze freeze(this, GetTextObjectModel());
  DefWindowProc(WM_LBUTTONUP, keys,
                MAKELPARAM(ClipXCoordToVisibleText(point.x, false), point.y));

  SelectAllIfNecessary(kLeft, point);

  tracking_click_[kLeft] = false;

  possible_drag_ = false;
}

Project: Chrome

void OmniboxViewWin::OnMButtonDblClk(UINT /*keys*/, const CPoint& /*point*/) {
  gaining_focus_.reset();  // See NOTE in OnMouseActivate().

}

Project: Chrome

void OmniboxViewWin::OnMButtonUp(UINT /*keys*/, const CPoint& /*point*/) {
  possible_drag_ = false;

}

Project: Chrome

LRESULT OmniboxViewWin::OnMouseActivate(HWND window,
                                        UINT hit_test,
                                        UINT mouse_message) {
  LRESULT result = DefWindowProc(WM_MOUSEACTIVATE,
                                 reinterpret_cast<WPARAM>(window),
                                 MAKELPARAM(hit_test, mouse_message));
  if (!model_->has_focus() &&
      ((mouse_message == WM_LBUTTONDOWN || mouse_message == WM_RBUTTONDOWN)) &&
      (result == MA_ACTIVATE)) {
    DCHECK(!gaining_focus_.get());
    gaining_focus_.reset(new ScopedFreeze(this, GetTextObjectModel()));

    saved_selection_for_focus_change_.cpMin = -1;
  }
  return result;
}

Project: Chrome

BOOL OmniboxViewWin::OnMouseWheel(UINT flags, short delta, CPoint point) {
  if (!ui::RerouteMouseWheel(m_hWnd, MAKEWPARAM(flags, delta),
                             MAKELPARAM(point.x, point.y)))
    SetMsgHandled(false);
  return 0;
}

Project: Chrome

void OmniboxViewWin::OnPaste() {
  const string16 text(GetClipboardText());
  if (!text.empty()) {
    model_->on_paste();
    text_before_change_.clear();
    ReplaceSel(text.c_str(), true);
  }
}

Project: Chrome

int OmniboxViewWin::OnPerformDrop(const views::DropTargetEvent& event) {
  return OnPerformDropImpl(event, false);
}

Project: Chrome

void OmniboxViewWin::OnPossibleDrag(const CPoint& point) {
  if (possible_drag_)
    return;

  click_point_[kLeft] = point;
  initiated_drag_ = false;

  CHARRANGE selection;
  GetSel(selection);
  if (selection.cpMin != selection.cpMax) {
    const POINT min_sel_location(PosFromChar(selection.cpMin));
    const POINT max_sel_location(PosFromChar(selection.cpMax));
    possible_drag_ = (point.x >= min_sel_location.x) &&
                     (point.x < max_sel_location.x);
  }
}

Project: Chrome

void OmniboxViewWin::OnRButtonDblClk(UINT /*keys*/, const CPoint& /*point*/) {
  gaining_focus_.reset();  // See NOTE in OnMouseActivate().
  SetMsgHandled(false);
}

Project: Chrome

void OmniboxViewWin::OnRButtonDown(UINT /*keys*/, const CPoint& point) {
  TrackMousePosition(kRight, point);
  tracking_double_click_ = false;
  possible_drag_ = false;
  gaining_focus_.reset();
  SetMsgHandled(false);
}

Project: Chrome

void OmniboxViewWin::OnRevertTemporaryText() {
  SetSelectionRange(original_selection_);
  TextChanged();
}

Project: Chrome

void OmniboxViewWin::OnSetFocus(HWND focus_wnd) {
  views::FocusManager* focus_manager = parent_view_->GetFocusManager();
  if (focus_manager) {
    focus_manager->SetFocusedView(parent_view_);
  } else {
    NOTREACHED();
  }

  model_->OnSetFocus(GetKeyState(VK_CONTROL) < 0);

  if (saved_selection_for_focus_change_.cpMin != -1) {
    SetSelectionRange(saved_selection_for_focus_change_);
    saved_selection_for_focus_change_.cpMin = -1;
  }

  SetMsgHandled(false);
}

Project: Chrome

LRESULT OmniboxViewWin::OnSetText(const wchar_t* text) {
  AutoReset<bool> auto_reset_ignore_ime_messages(&ignore_ime_messages_, true);
  return DefWindowProc(WM_SETTEXT, 0, reinterpret_cast<LPARAM>(text));
}

Project: Chrome

void OmniboxViewWin::OnSysChar(TCHAR ch,
                               UINT repeat_count,
                               UINT flags) {
  if (ch == VK_SPACE)
    SetMsgHandled(false);
}

Project: Chrome

void OmniboxViewWin::OnTemporaryTextMaybeChanged(const string16& display_text,
                                                 bool save_original_selection) {
  if (save_original_selection)
    GetSelection(original_selection_);

  ScopedFreeze freeze(this, GetTextObjectModel());
  SetWindowTextAndCaretPos(display_text, display_text.length());
  TextChanged();
}

Project: Chrome

void OmniboxViewWin::OnWindowPosChanging(WINDOWPOS* window_pos) {
  if (force_hidden_)
    window_pos->flags &= ~SWP_SHOWWINDOW;
  SetMsgHandled(true);
}

Project: Chrome

void OmniboxViewWin::OpenMatch(const AutocompleteMatch& match,
                               WindowOpenDisposition disposition,
                               const GURL& alternate_nav_url,
                               size_t selected_line,
                               const string16& keyword) {
  if (!match.destination_url.is_valid())
    return;

  ScopedFreeze freeze(this, GetTextObjectModel());
  model_->OpenMatch(match, disposition, alternate_nav_url,
                    selected_line, keyword);
}

Project: Chrome

PaintPatcher::PaintPatcher() : refcount_(0) {
}

Project: Chrome

void OmniboxViewWin::PasteAndGo(const string16& text) {
  if (CanPasteAndGo(text))
    model_->PasteAndGo();
}

Project: Chrome

void OmniboxViewWin::PlaceCaretAt(string16::size_type pos) {
  SetSelection(static_cast<LONG>(pos), static_cast<LONG>(pos));
}

Project: Chrome

void PaintPatcher::RefPatch() {
  if (refcount_ == 0) {
    DCHECK(!begin_paint_.is_patched());
    DCHECK(!end_paint_.is_patched());
    begin_paint_.Patch(L"riched20.dll", "user32.dll", "BeginPaint",
                       &BeginPaintIntercept);
    end_paint_.Patch(L"riched20.dll", "user32.dll", "EndPaint",
                     &EndPaintIntercept);
  }
  ++refcount_;
}

Project: Chrome

void OmniboxViewWin::RepaintDropHighlight(int position) {
  if ((position != -1) && (position <= GetTextLength())) {
    const POINT min_loc(PosFromChar(position));
    const RECT highlight_bounds = {min_loc.x - 1, font_y_adjustment_,
        min_loc.x + 2, font_.GetHeight() + font_y_adjustment_};
    InvalidateRect(&highlight_bounds, false);
  }
}

Project: Chrome

void OmniboxViewWin::EditDropTarget::ResetDropHighlights() {
  if (drag_has_string_)
    edit_->SetDropHighlightPosition(-1);
}

Project: Chrome

void OmniboxViewWin::RevertAll() {
  ScopedFreeze freeze(this, GetTextObjectModel());
  ClosePopup();
  model_->Revert();
  saved_selection_for_focus_change_.cpMin = -1;
  TextChanged();
}

Project: Chrome

void OmniboxViewWin::SaveStateToTab(WebContents* tab) {
  DCHECK(tab);

  const AutocompleteEditModel::State model_state(
      model_->GetStateForTabSwitch());

  CHARRANGE selection;
  GetSelection(selection);
  GetStateAccessor()->SetProperty(tab->GetPropertyBag(),
      AutocompleteEditState(
          model_state,
          State(selection, saved_selection_for_focus_change_)));
}

Project: Chrome

bool OmniboxViewWin::SchemeEnd(LPTSTR edit_text,
                               int current_pos,
                               int length) {
  return (current_pos >= 0) &&
         ((length - current_pos) > 2) &&
         (edit_text[current_pos] == ':') &&
         (edit_text[current_pos + 1] == '/') &&
         (edit_text[current_pos + 2] == '/');
}

Project: Chrome

OmniboxViewWin::ScopedSuspendUndo::ScopedSuspendUndo(
    ITextDocument* text_object_model)
    : text_object_model_(text_object_model) {
  if (text_object_model_)
    text_object_model_->Undo(tomSuspend, NULL);
}

Project: Chrome

void OmniboxViewWin::SelectAll(bool reversed) {
  if (reversed)
    SetSelection(GetTextLength(), 0);
  else
    SetSelection(0, GetTextLength());
}

Project: Chrome

void OmniboxViewWin::SelectAllIfNecessary(MouseButton button,
                                          const CPoint& point) {
  if (tracking_click_[button] &&
      !IsDrag(click_point_[button], point)) {
    SelectAll(true);
    possible_drag_ = false;
  }
}

Project: Chrome

void OmniboxViewWin::SetFocus() {
  ::SetFocus(m_hWnd);
}

Project: Chrome

void OmniboxViewWin::SetForcedQuery() {
  const string16 current_text(GetText());
  const size_t start = current_text.find_first_not_of(kWhitespaceWide);
  if (start == string16::npos || (current_text[start] != '?'))
    SetUserText(L"?");
  else
    SetSelection(current_text.length(), start + 1);
}

Project: Chrome

void OmniboxViewWin::SetInstantSuggestion(const string16& suggestion,
                                          bool animate_to_complete) {
  parent_view_->SetInstantSuggestion(suggestion, animate_to_complete);
}

Project: Chrome

void OmniboxViewWin::SetSelection(LONG start, LONG end) {
  SetSel(start, end);

  if (start <= end)
    return;

  ITextDocument* const text_object_model = GetTextObjectModel();
  if (!text_object_model)
    return;
  base::win::ScopedComPtr<ITextSelection> selection;
  const HRESULT hr = text_object_model->GetSelection(selection.Receive());
  DCHECK_EQ(S_OK, hr);
  selection->SetFlags(tomSelStartActive);
}

Project: Chrome

void OmniboxViewWin::SetUserText(const string16& text) {
  SetUserText(text, text, true);
}

Project: Chrome

void OmniboxViewWin::SetUserText(const string16& text,
                                 const string16& display_text,
                                 bool update_popup) {
  ScopedFreeze freeze(this, GetTextObjectModel());
  model_->SetUserText(text);
  saved_selection_for_focus_change_.cpMin = -1;
  SetWindowTextAndCaretPos(display_text, display_text.length());
  if (update_popup)
    UpdatePopup();
  TextChanged();
}

Project: Chrome

void OmniboxViewWin::SetWindowTextAndCaretPos(const string16& text,
                                              size_t caret_pos) {
  SetWindowText(text.c_str());
  PlaceCaretAt(caret_pos);
}

Project: Chrome

bool OmniboxViewWin::SkipDefaultKeyEventProcessing(
    const views::KeyEvent& event) {
  ui::KeyboardCode key = event.key_code();
  if (event.IsAltDown() && (key != ui::VKEY_HOME) &&
      views::NativeTextfieldWin::IsNumPadDigit(key,
          (event.flags() & ui::EF_EXTENDED) != 0))
    return true;

  switch (key) {
    case ui::VKEY_ESCAPE: {
      ScopedFreeze freeze(this, GetTextObjectModel());
      return model_->OnEscapeKeyPressed();
    }

    case ui::VKEY_RETURN:
      return true;

    case ui::VKEY_UP:
    case ui::VKEY_DOWN:
      return !event.IsAltDown();

    case ui::VKEY_DELETE:
    case ui::VKEY_INSERT:
      return !event.IsAltDown() && event.IsShiftDown() &&
          !event.IsControlDown();

    case ui::VKEY_X:
    case ui::VKEY_V:
      return !event.IsAltDown() && event.IsControlDown();

    case ui::VKEY_BACK:
    case ui::VKEY_OEM_PLUS:
      return true;

    default:
      return false;
  }
}

Project: Chrome

void OmniboxViewWin::TrackMousePosition(MouseButton button,
                                        const CPoint& point) {
  if (gaining_focus_.get()) {
    tracking_click_[button] = true;
    click_point_[button] = point;
  }
}

Project: Chrome

void OmniboxViewWin::Update(const WebContents* tab_for_state_restoring) {
  const bool visibly_changed_permanent_text =
      model_->UpdatePermanentText(toolbar_model_->GetText());

  const ToolbarModel::SecurityLevel security_level =
      toolbar_model_->GetSecurityLevel();
  const bool changed_security_level = (security_level != security_level_);

  if (!changed_security_level && !visibly_changed_permanent_text &&
      !tab_for_state_restoring)
    return;

  security_level_ = security_level;

  ScopedFreeze freeze(this, GetTextObjectModel());
  if (tab_for_state_restoring) {
    RevertAll();

    const AutocompleteEditState* state = GetStateAccessor()->GetProperty(
        tab_for_state_restoring->GetPropertyBag());
    if (state) {
      model_->RestoreState(state->model_state);

      SetSelectionRange(state->view_state.selection);
      saved_selection_for_focus_change_ =
          state->view_state.saved_selection_for_focus_change;
    }
  } else if (visibly_changed_permanent_text) {

    CHARRANGE sel;
    GetSelection(sel);
    const bool was_reversed = (sel.cpMin > sel.cpMax);
    const bool was_sel_all = (sel.cpMin != sel.cpMax) &&
      IsSelectAllForRange(sel);

    RevertAll();

    if (was_sel_all)
      SelectAll(was_reversed);
  } else if (changed_security_level) {
    EmphasizeURLComponents();
  }
}

Project: Chrome

int OmniboxViewWin::WidthNeededToDisplay(const string16& text) const {
  return font_.GetStringWidth(text) + GetHorizontalMargin();
}

Project: Chrome

int OmniboxViewWin::WidthOfTextAfterCursor() {
  CHARRANGE selection;
  GetSelection(selection);
  const int start = std::max(0, static_cast<int>(selection.cpMax - 1));
  return WidthNeededToDisplay(GetText().substr(start));
}

Project: Chrome

int CALLBACK OmniboxViewWin::WordBreakProc(LPTSTR edit_text,
                                           int current_pos,
                                           int num_bytes,
                                           int action) {

  const int length = num_bytes / sizeof(wchar_t);

  switch (action) {
    case WB_LEFT:
    case WB_MOVEWORDLEFT: {
      if (current_pos < 2) {
        return 0;
      }

      const int prev_delim =
          WordBreakProc(edit_text, current_pos - 1, num_bytes, WB_LEFTBREAK);

      if ((prev_delim == 0) &&
          !WordBreakProc(edit_text, 0, num_bytes, WB_ISDELIMITER)) {
        return 0;
      }

      return prev_delim + 1;
    }

    case WB_RIGHT:
    case WB_MOVEWORDRIGHT: {
      if (WordBreakProc(edit_text, current_pos, num_bytes, WB_ISDELIMITER)) {
        return current_pos + 1;
      }

      const int next_delim =
          WordBreakProc(edit_text, current_pos, num_bytes, WB_RIGHTBREAK);
      if (next_delim == length) {
        return length;
      }

      return next_delim + 1;
    }

    case WB_ISDELIMITER:
      return !!(WordBreakProc(edit_text, current_pos, num_bytes, WB_CLASSIFY) &
                WBF_BREAKLINE);

    case WB_CLASSIFY:
      if (IsWhitespace(edit_text[current_pos])) {
        while ((current_pos < (length - 1)) &&
               (edit_text[current_pos] == 0x13)) {
          if (edit_text[++current_pos] == 0x10)
            return WBF_ISWHITE;
        }
        return WBF_BREAKLINE | WBF_ISWHITE;
      }

      if (ispunct(edit_text[current_pos], std::locale()) &&
          !SchemeEnd(edit_text, current_pos, length) &&
          !SchemeEnd(edit_text, current_pos - 1, length))
        return WBF_BREAKLINE;

      return 0;

    case WB_LEFTBREAK:
      for (int i = current_pos - 1; i >= 0; --i) {
        if (WordBreakProc(edit_text, i, num_bytes, WB_ISDELIMITER))
          return i;
      }
      return 0;

    case WB_RIGHTBREAK:
      for (int i = current_pos + 1; i < length; ++i) {
        if (WordBreakProc(edit_text, i, num_bytes, WB_ISDELIMITER))
          return i;
      }
      return length;
  }

  NOTREACHED();
  return 0;
}

Project: Chrome

views::View* OmniboxViewWin::parent_view() const {
  return parent_view_;
}

Project: Chrome

OmniboxViewWin::~OmniboxViewWin() {
  text_object_model_->Release();

  g_paint_patcher.Pointer()->DerefPatch();
}

Project: Chrome

PaintPatcher::~PaintPatcher() {
  DCHECK_EQ(0U, refcount_);
}

Project: Chrome

OmniboxViewWin::ScopedFreeze::~ScopedFreeze() {
  if (edit_->IsWindow() && text_object_model_) {
    long count;
    text_object_model_->Unfreeze(&count);
    if (count == 0) {
      edit_->InvalidateRect(NULL, false);
      edit_->UpdateWindow();
    }
  }
}

Project: Chrome

OmniboxViewWin::ScopedSuspendUndo::~ScopedSuspendUndo() {
  if (text_object_model_)
    text_object_model_->Undo(tomResume, NULL);
}