@Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
    // Galaxy Note sends key events for the stylus that are outside of the
    // valid keyCode range (see bug 758427)
    if (keyCode > KeyEvent.getMaxKeyCode()) return true;

    // This method is called only if the key event was not handled
    // by any of the views, which usually means the edit box lost focus
    if (keyCode == KeyEvent.KEYCODE_BACK
        || keyCode == KeyEvent.KEYCODE_MENU
        || keyCode == KeyEvent.KEYCODE_DPAD_UP
        || keyCode == KeyEvent.KEYCODE_DPAD_DOWN
        || keyCode == KeyEvent.KEYCODE_DPAD_LEFT
        || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT
        || keyCode == KeyEvent.KEYCODE_DPAD_CENTER
        || keyCode == KeyEvent.KEYCODE_DEL
        || keyCode == KeyEvent.KEYCODE_VOLUME_UP
        || keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
      return super.onKeyDown(keyCode, event);
    } else if (keyCode == KeyEvent.KEYCODE_SEARCH) {
      mText.setText("");
      mText.requestFocus();
      InputMethodManager imm =
          (InputMethodManager) mText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
      imm.showSoftInput(mText, InputMethodManager.SHOW_IMPLICIT);
      return true;
    } else {
      int selStart = -1;
      int selEnd = -1;
      if (mText.hasSelection()) {
        selStart = mText.getSelectionStart();
        selEnd = mText.getSelectionEnd();
      }

      if (selStart >= 0) {
        // Restore the selection, which gets lost due to the focus switch
        mText.setSelection(selStart, selEnd);
      }

      // Manually dispatch the key event to the AwesomeBar before restoring (default) input
      // focus. dispatchKeyEvent() will update AwesomeBar's cursor position.
      mText.dispatchKeyEvent(event);
      int newCursorPos = mText.getSelectionEnd();

      // requestFocusFromTouch() will select all AwesomeBar text, so we must restore cursor
      // position so subsequent typing does not overwrite all text.
      mText.requestFocusFromTouch();
      mText.setSelection(newCursorPos);

      return true;
    }
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Log.d(LOGTAG, "creating awesomebar");

    mResolver = Tabs.getInstance().getContentResolver();
    LayoutInflater.from(this).setFactory(GeckoViewsFactory.getInstance());

    setContentView(R.layout.awesomebar);

    mGoButton = (ImageButton) findViewById(R.id.awesomebar_button);
    mText = (CustomEditText) findViewById(R.id.awesomebar_text);

    TabWidget tabWidget = (TabWidget) findViewById(android.R.id.tabs);
    tabWidget.setDividerDrawable(null);

    mAwesomeTabs = (AwesomeBarTabs) findViewById(R.id.awesomebar_tabs);
    mAwesomeTabs.setOnUrlOpenListener(
        new AwesomeBarTabs.OnUrlOpenListener() {
          public void onUrlOpen(String url) {
            openUrlAndFinish(url);
          }

          public void onSearch(String engine, String text) {
            openSearchAndFinish(text, engine);
          }

          public void onEditSuggestion(final String text) {
            GeckoApp.mAppContext.mMainHandler.post(
                new Runnable() {
                  public void run() {
                    mText.setText(text);
                    mText.setSelection(mText.getText().length());
                    mText.requestFocus();
                    InputMethodManager imm =
                        (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.showSoftInput(mText, InputMethodManager.SHOW_IMPLICIT);
                  }
                });
          }
        });

    mGoButton.setOnClickListener(
        new Button.OnClickListener() {
          public void onClick(View v) {
            openUserEnteredAndFinish(mText.getText().toString());
          }
        });

    Intent intent = getIntent();
    String currentUrl = intent.getStringExtra(CURRENT_URL_KEY);
    mTarget = intent.getStringExtra(TARGET_KEY);
    if (currentUrl != null) {
      mText.setText(currentUrl);
      mText.selectAll();
    }

    mText.setOnKeyPreImeListener(
        new CustomEditText.OnKeyPreImeListener() {
          public boolean onKeyPreIme(View v, int keyCode, KeyEvent event) {
            // We only want to process one event per tap
            if (event.getAction() != KeyEvent.ACTION_DOWN) return false;

            if (keyCode == KeyEvent.KEYCODE_ENTER) {
              // If the AwesomeBar has a composition string, don't submit the text yet.
              // ENTER is needed to commit the composition string.
              Editable content = mText.getText();
              if (!hasCompositionString(content)) {
                openUserEnteredAndFinish(content.toString());
                return true;
              }
            }

            // If input method is in fullscreen mode, we want to dismiss
            // it instead of closing awesomebar straight away.
            InputMethodManager imm =
                (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (keyCode == KeyEvent.KEYCODE_BACK && !imm.isFullscreenMode()) {
              // Let mAwesomeTabs try to handle the back press, since we may be in a
              // bookmarks sub-folder.
              if (mAwesomeTabs.onBackPressed()) return true;

              // If mAwesomeTabs.onBackPressed() returned false, we didn't move up
              // a folder level, so just exit the activity.
              cancelAndFinish();
              return true;
            }

            return false;
          }
        });

    mText.addTextChangedListener(
        new TextWatcher() {
          public void afterTextChanged(Editable s) {
            String text = s.toString();
            mAwesomeTabs.filter(text);

            // If the AwesomeBar has a composition string, don't call updateGoButton().
            // That method resets IME and composition state will be broken.
            if (!hasCompositionString(s)) {
              updateGoButton(text);
            }

            if (Build.VERSION.SDK_INT >= 11) {
              getActionBar().hide();
            }
          }

          public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            // do nothing
          }

          public void onTextChanged(CharSequence s, int start, int before, int count) {
            // do nothing
          }
        });

    mText.setOnKeyListener(
        new View.OnKeyListener() {
          public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_ENTER) {
              if (event.getAction() != KeyEvent.ACTION_DOWN) return true;

              openUserEnteredAndFinish(mText.getText().toString());
              return true;
            } else {
              return false;
            }
          }
        });

    mText.setOnFocusChangeListener(
        new View.OnFocusChangeListener() {
          public void onFocusChange(View v, boolean hasFocus) {
            if (v == null || hasFocus) {
              return;
            }

            InputMethodManager imm =
                (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            try {
              imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            } catch (NullPointerException e) {
              Log.e(
                  LOGTAG,
                  "InputMethodManagerService, why are you throwing"
                      + " a NullPointerException? See bug 782096",
                  e);
            }
          }
        });

    mText.setOnLongClickListener(
        new View.OnLongClickListener() {
          @Override
          public boolean onLongClick(View v) {
            if (Build.VERSION.SDK_INT >= 11) {
              CustomEditText text = (CustomEditText) v;

              if (text.getSelectionStart() == text.getSelectionEnd()) return false;

              getActionBar().show();
              return false;
            }

            return false;
          }
        });

    mText.setOnSelectionChangedListener(
        new CustomEditText.OnSelectionChangedListener() {
          @Override
          public void onSelectionChanged(int selStart, int selEnd) {
            if (Build.VERSION.SDK_INT >= 11 && selStart == selEnd) {
              getActionBar().hide();
            }
          }
        });

    boolean showReadingList = intent.getBooleanExtra(READING_LIST_KEY, false);
    if (showReadingList) {
      BookmarksTab bookmarksTab = mAwesomeTabs.getBookmarksTab();
      bookmarksTab.setShowReadingList(true);
      mAwesomeTabs.setCurrentTabByTag(bookmarksTab.getTag());
    }
  }