<commit_before>/**
 *  File name: CEigen.cpp
 *
 *  Programmer: Yongqun He
 *  Contact email: yohe@vt.edu
 *  Purpose: This is the .cpp file for the class CEigen.
 *           It is to calculate eigenvalues and eigenvectors of a matrix.
 *
 */

#include "CEigen.h"

/**
 * Defaulut constructor
 */
CEigen::CEigen()
{   }

/**
 * User defined constructor
 * @param rows is the max row number of Matrix
 * @param cols is the max column number of Matrix
 */
CEigen::CEigen(int rows, int cols)
{

  mMatrix.newsize(rows, cols);
}

/**
 * Deconstructor
 */
CEigen::~CEigen()
{
}

/**
 * return the matrix
 */
TNT::Matrix < C_FLOAT64 > CEigen::getMatrix()
{
  return mMatrix;
}

/**
 * Set the Matrix
 */
void CEigen::setMatrix(int rows, int cols)
{
  mMatrix.newsize(rows, cols);
}

/**
 * Set the Work
 */
void CEigen::setWork(C_FLOAT64 * aWork)
{
  mWork = aWork;
}

/**
 * Get the Work
 */
C_FLOAT64 * CEigen::getWork() const
{
  return mWork;
}

// eigenvalue calculations
void CEigen::CalcEigenvalues( void )
{

  /*
 int res;
 char jobvs = 'N';
 char sort = 'N';

 long int lda;
 long int sdim;
 int n, pz, mx, mn;        // YH: don't use "long" any more
 long int ldvs = 1;
 double *work;
 long int lwork = 4096;
 long int info;
 int i, j;
 double distt, maxt, tott;

 // the dimension of the matrix
 n = Model.IndMetab;
 lda = n>1 ? n : 1;

 // create the matrices
 work = new double[lwork];

 // copy the jacobian into J
 for( i=0; i<n; i++ )
  for( j=0; j<n; j++ )
   eigen_jacob[i*n+j] = ss_jacob[i+1][j+1];

 // calculate the eigenvalues
 res = dgees_( &jobvs,                     //ok
              &sort,                       //ok
                          NULL,            //ok
                          &n,              //ok
                  eigen_jacob,             //ok
                          &lda,            //ok
                          &sdim,           //ok
                          eigen_r,         //????? 8
                  eigen_i,                 //????? 9
                          NULL,            //ok
                          &ldvs,           //ok
                          work,            //ok
                  &lwork,                  //ok
                          NULL,            //ok
                          &info);          //ok

 // release the work array
 delete [] work;
 // initialise variables
 eigen_nreal = eigen_nimag = eigen_nposreal = eigen_nnegreal =
 eigen_nzero = eigen_ncplxconj = 0.0;

 // sort the eigenvalues
 qsort( eigen_r, eigen_i, 0, n-1 );
 // search for the number of positive real parts
 for( pz=0; pz<n; pz++ )
  if( eigen_r[pz] < 0.0 ) break;
 // calculate various eigenvalue statistics
 eigen_maxrealpart = eigen_r[0];
 eigen_maximagpart = fabs(eigen_i[0]);
 for( i=0; i<n; i++ )
 {
  // for the largest real part
  if( eigen_r[i] > eigen_maxrealpart ) eigen_maxrealpart = eigen_r[i];
  // for the largest imaginary part
  if( fabs(eigen_i[i]) > eigen_maximagpart ) eigen_maximagpart = fabs(eigen_i[i]);
  if( fabs(eigen_r[i]) > SSRes )
  {
   // positive real part
   if( eigen_r[i]>=SSRes ) eigen_nposreal += 1.0;
   // negative real part
   if( eigen_r[i]<=-SSRes ) eigen_nnegreal += 1.0;
   if( fabs(eigen_i[i]) > SSRes )
   {
    // complex
    eigen_ncplxconj += 1.0;
   }
   else
   {
    // pure real
        eigen_nreal += 1.0;
   }
  }
  else
  {
   if( fabs(eigen_i[i]) > SSRes )
   {
    // pure imaginary
    eigen_nimag += 1.0;
   }
   else
   {
    // zero
        eigen_nzero += 1.0;
   }
  }
 }
 if( pz > 0 )
 {
  if( eigen_r[0] > fabs( eigen_r[n] ) ) mx = 0; else mx = n-1;
  if( eigen_r[pz-1] < fabs( eigen_r[pz] ) ) mn = 0; else mn = pz;
 }
 else
 {
  mx = n-1; // index of the largest absolute real part
  mn = 0; // index of the smallest absolute real part
 }
 eigen_stiffness = fabs( eigen_r[mx] ) / fabs( eigen_r[mn] );
 maxt = tott = fabs( 1/eigen_r[mn] );
 distt = 0.0;
 for( i=1; i<n; i++ )
  if( i!=mn )
  {
   distt += maxt - fabs( 1/eigen_r[i] );
   tott += fabs( 1/eigen_r[i] );
  }
 eigen_hierarchy = distt / tott / (n-1);

  */

}

<commit_msg>update<commit_after>/**
 *  File name: CEigen.cpp
 *
 *  Programmer: Yongqun He
 *  Contact email: yohe@vt.edu
 *  Purpose: This is the .cpp file for the class CEigen.
 *           It is to calculate eigenvalues and eigenvectors of a matrix.
 *
 */

#include "CEigen.h"

/**
 * Defaulut constructor
 */
CEigen::CEigen()
{
  initialize();
}

/**
 * User defined constructor
 * @param rows is the max row number of Matrix
 * @param cols is the max column number of Matrix
 */
CEigen::CEigen(int rows, int cols)
{

  mMatrix.newsize(rows, cols);
  initialize();
}

/**
 * Deconstructor
 */
CEigen::~CEigen()
{
}

/**
 * return the matrix
 */
TNT::Matrix < C_FLOAT64 > CEigen::getMatrix()
{
  return mMatrix;
}

/**
 * Set the Matrix
 */
void CEigen::setMatrix(int rows, int cols)
{
  mMatrix.newsize(rows, cols);
}

/**
 * Set the Work
 */
void CEigen::setWork(C_FLOAT64 * aWork)
{
  mWork = aWork;
}

/**
 * Get the Work
 */
C_FLOAT64 * CEigen::getWork() const
{
  return mWork;
}

//initialize variables for eigenvalue calculations
//
void CEigen::initialize()
{

  // * #1: (input) characer*1
  mJobvs = 'N';
  // * #2: (input) characer*1
  mSort = 'N';
  // * #3: (input) Logical function of two double precision arguments
  mSelect = NULL;
  // * #4: (input) The order of the matrix A
  mN = 0;
  // * #5: (input/output) The double precision array, dimension (LDA,N)
  //C_FLOAT64 * mA;
  // * #6: (input) The leading dimension of the array A. LDA >= max(1,N)
  //C_INT32 mLDA;
  // * #7: (output) an integer
  //C_INT32 mSdim;
  // * #8: array with dimension (mN)
  //C_FLOAT64 * mWR;
  // * #9: array with dimension (mN)
  //C_FLOAT64 * mWI;
  // * #10: (output) array with dimension (mLdvs, mN)
  //C_FLOAT64 * mVS;
  // * #11: an integer, the leading dimension of the array VS. mLdvs >= 1;
  //C_INT32 mLdvs;
  // * #12: (workspace/output) double precision array, dimension (mLWork)
  //C_FLOAT64 * mWork;
  // * #13: (input) Dimension of array Work, its value >= max(1,3*mN).
  //C_INT32 mLWork;
  // * #14: (workspace) Logical array, dimension (N)
  //C_INT32 * mBWork;
  // * #15: (output) an integer
  //C_INT32 mInfo;

}

// eigenvalue calculations
void CEigen::CalcEigenvalues( void )
{

  /*

 int res;
 //char jobvs = 'N';      //#1
 //char sort = 'N';       //#2

 long int lda;
 long int sdim;
 // int n, pz, mx, mn;        // YH: don't use "long" any more
 int pz, mx, mn;        // YH: don't use "long" any more
 long int ldvs = 1;
 double *work;
 long int lwork = 4096;
 long int info;
 int i, j;
 double distt, maxt, tott;

 // the dimension of the matrix
 //n = Model.IndMetab;
 //lda = n>1 ? n : 1;
 mN = Model.IndMetab;
 lda = mN>1 ? mN : 1;

 // create the matrices
 work = new double[lwork];

 // copy the jacobian into J
 // for( i=0; i<n; i++ )
 // for( j=0; j<n; j++ )
 //  eigen_jacob[i*n+j] = ss_jacob[i+1][j+1];
 for( i=0; i<mN; i++ )
   for( j=0; j<mN; j++ )
     eigen_jacob[i*mN+j] = ss_jacob[i+1][j+1];

 // calculate the eigenvalues
 res = dgees_( &mJobvs,                     //ok, done
              &mSort,                       //ok, done
	       mSelect,          //NULL,    //ok
	       &mN,              //&n,      //ok
                  eigen_jacob,             //ok
                          &lda,            //ok
                          &sdim,           //ok
                          eigen_r,         //????? 8
                  eigen_i,                 //????? 9
                          NULL,            //ok
                          &ldvs,           //ok
                          work,            //ok
                  &lwork,                  //ok
                          NULL,            //ok
                          &info);          //ok

 // release the work array
 delete [] work;
 // initialise variables
 eigen_nreal = eigen_nimag = eigen_nposreal = eigen_nnegreal =
 eigen_nzero = eigen_ncplxconj = 0.0;

 // sort the eigenvalues
 qsort( eigen_r, eigen_i, 0, n-1 );
 // search for the number of positive real parts
 for( pz=0; pz<n; pz++ )
  if( eigen_r[pz] < 0.0 ) break;
 // calculate various eigenvalue statistics
 eigen_maxrealpart = eigen_r[0];
 eigen_maximagpart = fabs(eigen_i[0]);
 for( i=0; i<n; i++ )
 {
  // for the largest real part
  if( eigen_r[i] > eigen_maxrealpart ) eigen_maxrealpart = eigen_r[i];
  // for the largest imaginary part
  if( fabs(eigen_i[i]) > eigen_maximagpart ) eigen_maximagpart = fabs(eigen_i[i]);
  if( fabs(eigen_r[i]) > SSRes )
  {
   // positive real part
   if( eigen_r[i]>=SSRes ) eigen_nposreal += 1.0;
   // negative real part
   if( eigen_r[i]<=-SSRes ) eigen_nnegreal += 1.0;
   if( fabs(eigen_i[i]) > SSRes )
   {
    // complex
    eigen_ncplxconj += 1.0;
   }
   else
   {
    // pure real
        eigen_nreal += 1.0;
   }
  }
  else
  {
   if( fabs(eigen_i[i]) > SSRes )
   {
    // pure imaginary
    eigen_nimag += 1.0;
   }
   else
   {
    // zero
        eigen_nzero += 1.0;
   }
  }
 }
 if( pz > 0 )
 {
  if( eigen_r[0] > fabs( eigen_r[n] ) ) mx = 0; else mx = n-1;
  if( eigen_r[pz-1] < fabs( eigen_r[pz] ) ) mn = 0; else mn = pz;
 }
 else
 {
  mx = n-1; // index of the largest absolute real part
  mn = 0; // index of the smallest absolute real part
 }
 eigen_stiffness = fabs( eigen_r[mx] ) / fabs( eigen_r[mn] );
 maxt = tott = fabs( 1/eigen_r[mn] );
 distt = 0.0;
 for( i=1; i<n; i++ )
  if( i!=mn )
  {
   distt += maxt - fabs( 1/eigen_r[i] );
   tott += fabs( 1/eigen_r[i] );
  }
 eigen_hierarchy = distt / tott / (n-1);

  */

}

<|endoftext|>


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

#include "chrome/browser/gtk/clear_browsing_data_dialog_gtk.h"

#include <string>

#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browsing_data_remover.h"
#include "chrome/browser/gtk/accessible_widget_helper_gtk.h"
#include "chrome/browser/gtk/browser_window_gtk.h"
#include "chrome/browser/gtk/gtk_chrome_link_button.h"
#include "chrome/browser/gtk/gtk_util.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"

namespace {

// Returns true if the checkbox is checked.
gboolean IsChecked(GtkWidget* widget) {
  return gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget));
}

}  // namespace

// static
void ClearBrowsingDataDialogGtk::Show(GtkWindow* parent, Profile* profile) {
  new ClearBrowsingDataDialogGtk(parent, profile);
}

ClearBrowsingDataDialogGtk::ClearBrowsingDataDialogGtk(GtkWindow* parent,
                                                       Profile* profile) :
    profile_(profile), remover_(NULL) {
  // Build the dialog.
  std::string dialog_name = l10n_util::GetStringUTF8(
      IDS_CLEAR_BROWSING_DATA_TITLE);
  dialog_ = gtk_dialog_new_with_buttons(
      dialog_name.c_str(),
      parent,
      (GtkDialogFlags) (GTK_DIALOG_MODAL | GTK_DIALOG_NO_SEPARATOR),
      GTK_STOCK_CLOSE,
      GTK_RESPONSE_REJECT,
      NULL);

  accessible_widget_helper_.reset(new AccessibleWidgetHelper(dialog_, profile));
  accessible_widget_helper_->SendOpenWindowNotification(dialog_name);

  gtk_util::AddButtonToDialog(dialog_,
      l10n_util::GetStringUTF8(IDS_CLEAR_BROWSING_DATA_COMMIT).c_str(),
      GTK_STOCK_APPLY, GTK_RESPONSE_ACCEPT);

  GtkWidget* content_area = GTK_DIALOG(dialog_)->vbox;
  gtk_box_set_spacing(GTK_BOX(content_area), gtk_util::kContentAreaSpacing);

  GtkWidget* vbox = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);
  gtk_container_add(GTK_CONTAINER(content_area), vbox);

  // Label on top of the checkboxes.
  GtkWidget* description = gtk_label_new(
      l10n_util::GetStringUTF8(IDS_CLEAR_BROWSING_DATA_LABEL).c_str());
  gtk_misc_set_alignment(GTK_MISC(description), 0, 0);
  gtk_box_pack_start(GTK_BOX(vbox), description, FALSE, FALSE, 0);

  // History checkbox.
  del_history_checkbox_ = gtk_check_button_new_with_label(
      l10n_util::GetStringUTF8(IDS_DEL_BROWSING_HISTORY_CHKBOX).c_str());
  gtk_box_pack_start(GTK_BOX(vbox), del_history_checkbox_, FALSE, FALSE, 0);
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(del_history_checkbox_),
      profile_->GetPrefs()->GetBoolean(prefs::kDeleteBrowsingHistory));
  g_signal_connect(del_history_checkbox_, "toggled",
                   G_CALLBACK(OnDialogWidgetClickedThunk), this);

  // Downloads checkbox.
  del_downloads_checkbox_ = gtk_check_button_new_with_label(
      l10n_util::GetStringUTF8(IDS_DEL_DOWNLOAD_HISTORY_CHKBOX).c_str());
  gtk_box_pack_start(GTK_BOX(vbox), del_downloads_checkbox_, FALSE, FALSE, 0);
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(del_downloads_checkbox_),
      profile_->GetPrefs()->GetBoolean(prefs::kDeleteDownloadHistory));
  g_signal_connect(del_downloads_checkbox_, "toggled",
                   G_CALLBACK(OnDialogWidgetClickedThunk), this);

  // Cache checkbox.
  del_cache_checkbox_ = gtk_check_button_new_with_label(
      l10n_util::GetStringUTF8(IDS_DEL_CACHE_CHKBOX).c_str());
  gtk_box_pack_start(GTK_BOX(vbox), del_cache_checkbox_, FALSE, FALSE, 0);
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(del_cache_checkbox_),
      profile_->GetPrefs()->GetBoolean(prefs::kDeleteCache));
  g_signal_connect(del_cache_checkbox_, "toggled",
                   G_CALLBACK(OnDialogWidgetClickedThunk), this);

  // Cookies checkbox.
  del_cookies_checkbox_ = gtk_check_button_new_with_label(
      l10n_util::GetStringUTF8(IDS_DEL_COOKIES_CHKBOX).c_str());
  gtk_box_pack_start(GTK_BOX(vbox), del_cookies_checkbox_, FALSE, FALSE, 0);
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(del_cookies_checkbox_),
      profile_->GetPrefs()->GetBoolean(prefs::kDeleteCookies));
  g_signal_connect(del_cookies_checkbox_, "toggled",
                   G_CALLBACK(OnDialogWidgetClickedThunk), this);

  // Passwords checkbox.
  del_passwords_checkbox_ = gtk_check_button_new_with_label(
      l10n_util::GetStringUTF8(IDS_DEL_PASSWORDS_CHKBOX).c_str());
  gtk_box_pack_start(GTK_BOX(vbox), del_passwords_checkbox_, FALSE, FALSE, 0);
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(del_passwords_checkbox_),
      profile_->GetPrefs()->GetBoolean(prefs::kDeletePasswords));
  g_signal_connect(del_passwords_checkbox_, "toggled",
                   G_CALLBACK(OnDialogWidgetClickedThunk), this);

  // Form data checkbox.
  del_form_data_checkbox_ = gtk_check_button_new_with_label(
      l10n_util::GetStringUTF8(IDS_DEL_FORM_DATA_CHKBOX).c_str());
  gtk_box_pack_start(GTK_BOX(vbox), del_form_data_checkbox_, FALSE, FALSE, 0);
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(del_form_data_checkbox_),
      profile_->GetPrefs()->GetBoolean(prefs::kDeleteFormData));
  g_signal_connect(del_form_data_checkbox_, "toggled",
                   G_CALLBACK(OnDialogWidgetClickedThunk), this);

  // Create a horizontal layout for the combo box and label.
  GtkWidget* combo_hbox = gtk_hbox_new(FALSE, gtk_util::kLabelSpacing);
  GtkWidget* time_period_label_ = gtk_label_new(
      l10n_util::GetStringUTF8(IDS_CLEAR_BROWSING_DATA_TIME_LABEL).c_str());
  gtk_box_pack_start(GTK_BOX(combo_hbox), time_period_label_, FALSE, FALSE, 0);

  // Time period combo box items.
  time_period_combobox_ = gtk_combo_box_new_text();
  gtk_combo_box_append_text(GTK_COMBO_BOX(time_period_combobox_),
      l10n_util::GetStringUTF8(IDS_CLEAR_DATA_HOUR).c_str());
  gtk_combo_box_append_text(GTK_COMBO_BOX(time_period_combobox_),
      l10n_util::GetStringUTF8(IDS_CLEAR_DATA_DAY).c_str());
  gtk_combo_box_append_text(GTK_COMBO_BOX(time_period_combobox_),
      l10n_util::GetStringUTF8(IDS_CLEAR_DATA_WEEK).c_str());
  gtk_combo_box_append_text(GTK_COMBO_BOX(time_period_combobox_),
      l10n_util::GetStringUTF8(IDS_CLEAR_DATA_4WEEKS).c_str());
  gtk_combo_box_append_text(GTK_COMBO_BOX(time_period_combobox_),
      l10n_util::GetStringUTF8(IDS_CLEAR_DATA_EVERYTHING).c_str());
  gtk_combo_box_set_active(GTK_COMBO_BOX(time_period_combobox_),
      profile_->GetPrefs()->GetInteger(prefs::kDeleteTimePeriod));
  gtk_box_pack_start(GTK_BOX(combo_hbox),
                     time_period_combobox_, FALSE, FALSE, 0);
  g_signal_connect(time_period_combobox_, "changed",
                   G_CALLBACK(OnDialogWidgetClickedThunk), this);

  // Add the combo/label time period box to the vertical layout.
  gtk_box_pack_start(GTK_BOX(vbox), combo_hbox, FALSE, FALSE, 0);

  // Add widgets for the area below the accept buttons.
  GtkWidget* flash_link = gtk_chrome_link_button_new(
      l10n_util::GetStringUTF8(IDS_FLASH_STORAGE_SETTINGS).c_str());
  g_signal_connect(G_OBJECT(flash_link), "clicked",
                   G_CALLBACK(OnFlashLinkClickedThunk), this);
  GtkWidget* flash_link_hbox = gtk_hbox_new(FALSE, 0);
  gtk_box_pack_start(GTK_BOX(flash_link_hbox), flash_link, FALSE, FALSE, 0);
  gtk_box_pack_end(GTK_BOX(content_area), flash_link_hbox, FALSE, FALSE, 0);

  GtkWidget* separator = gtk_hseparator_new();
  gtk_box_pack_end(GTK_BOX(content_area), separator, FALSE, FALSE, 0);

  // Make sure we can move things around.
  DCHECK_EQ(GTK_DIALOG(dialog_)->action_area->parent, content_area);

  // Now rearrange those because they're *above* the accept buttons...there's
  // no way to place them in the correct position with gtk_box_pack_end() so
  // manually move things into the correct order.
  gtk_box_reorder_child(GTK_BOX(content_area), flash_link_hbox, -1);
  gtk_box_reorder_child(GTK_BOX(content_area), separator, -1);
  gtk_box_reorder_child(GTK_BOX(content_area), GTK_DIALOG(dialog_)->action_area,
                        -1);

  g_signal_connect(dialog_, "response",
                   G_CALLBACK(OnDialogResponseThunk), this);

  UpdateDialogButtons();

  gtk_util::ShowDialogWithLocalizedSize(dialog_,
                                        IDS_CLEARDATA_DIALOG_WIDTH_CHARS,
                                        -1,
                                        false);
}

ClearBrowsingDataDialogGtk::~ClearBrowsingDataDialogGtk() {
}

void ClearBrowsingDataDialogGtk::OnDialogResponse(GtkWidget* widget,
                                                  int response) {
  if (response == GTK_RESPONSE_ACCEPT) {
    int period_selected = gtk_combo_box_get_active(
        GTK_COMBO_BOX(time_period_combobox_));

    // BrowsingDataRemover deletes itself when done.
    remover_ = new BrowsingDataRemover(profile_,
        static_cast<BrowsingDataRemover::TimePeriod>(period_selected),
        base::Time());
    remover_->Remove(GetCheckedItems());
  }

  delete this;
  gtk_widget_destroy(GTK_WIDGET(widget));
}

void ClearBrowsingDataDialogGtk::OnDialogWidgetClicked(GtkWidget* widget) {
  if (widget == del_history_checkbox_) {
    profile_->GetPrefs()->SetBoolean(prefs::kDeleteBrowsingHistory,
                                     IsChecked(widget));
  } else if (widget == del_downloads_checkbox_) {
    profile_->GetPrefs()->SetBoolean(prefs::kDeleteDownloadHistory,
                                     IsChecked(widget));
  } else if (widget == del_cache_checkbox_) {
    profile_->GetPrefs()->SetBoolean(prefs::kDeleteCache,
                                     IsChecked(widget));
  } else if (widget == del_cookies_checkbox_) {
    profile_->GetPrefs()->SetBoolean(prefs::kDeleteCookies,
                                     IsChecked(widget));
  } else if (widget == del_passwords_checkbox_) {
    profile_->GetPrefs()->SetBoolean(prefs::kDeletePasswords,
                                     IsChecked(widget));
  } else if (widget == del_form_data_checkbox_) {
    profile_->GetPrefs()->SetBoolean(prefs::kDeleteFormData,
                                     IsChecked(widget));
  } else if (widget == time_period_combobox_) {
    profile_->GetPrefs()->SetInteger(prefs::kDeleteTimePeriod,
        gtk_combo_box_get_active(GTK_COMBO_BOX(widget)));
  }
  UpdateDialogButtons();
}

void ClearBrowsingDataDialogGtk::OnFlashLinkClicked(GtkWidget* button) {
  // We open a new browser window so the Options dialog doesn't get lost
  // behind other windows.
  Browser* browser = Browser::Create(profile_);
  browser->OpenURL(GURL(l10n_util::GetStringUTF8(IDS_FLASH_STORAGE_URL)),
                   GURL(), NEW_FOREGROUND_TAB, PageTransition::LINK);
  browser->window()->Show();
}

void ClearBrowsingDataDialogGtk::UpdateDialogButtons() {
  gtk_dialog_set_response_sensitive(GTK_DIALOG(dialog_), GTK_RESPONSE_ACCEPT,
                                    GetCheckedItems() != 0);
}

int ClearBrowsingDataDialogGtk::GetCheckedItems() {
  int items = 0;
  if (IsChecked(del_history_checkbox_))
    items |= BrowsingDataRemover::REMOVE_HISTORY;
  if (IsChecked(del_downloads_checkbox_))
    items |= BrowsingDataRemover::REMOVE_DOWNLOADS;
  if (IsChecked(del_cookies_checkbox_))
    items |= BrowsingDataRemover::REMOVE_COOKIES;
  if (IsChecked(del_passwords_checkbox_))
    items |= BrowsingDataRemover::REMOVE_PASSWORDS;
  if (IsChecked(del_form_data_checkbox_))
    items |= BrowsingDataRemover::REMOVE_FORM_DATA;
  if (IsChecked(del_cache_checkbox_))
    items |= BrowsingDataRemover::REMOVE_CACHE;
  return items;
}
<commit_msg>Make "Clear Browser Data" dialog wider for ja.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/gtk/clear_browsing_data_dialog_gtk.h"

#include <string>

#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browsing_data_remover.h"
#include "chrome/browser/gtk/accessible_widget_helper_gtk.h"
#include "chrome/browser/gtk/browser_window_gtk.h"
#include "chrome/browser/gtk/gtk_chrome_link_button.h"
#include "chrome/browser/gtk/gtk_util.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"

namespace {

// Returns true if the checkbox is checked.
gboolean IsChecked(GtkWidget* widget) {
  return gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget));
}

}  // namespace

// static
void ClearBrowsingDataDialogGtk::Show(GtkWindow* parent, Profile* profile) {
  new ClearBrowsingDataDialogGtk(parent, profile);
}

ClearBrowsingDataDialogGtk::ClearBrowsingDataDialogGtk(GtkWindow* parent,
                                                       Profile* profile) :
    profile_(profile), remover_(NULL) {
  // Build the dialog.
  std::string dialog_name = l10n_util::GetStringUTF8(
      IDS_CLEAR_BROWSING_DATA_TITLE);
  dialog_ = gtk_dialog_new_with_buttons(
      dialog_name.c_str(),
      parent,
      (GtkDialogFlags) (GTK_DIALOG_MODAL | GTK_DIALOG_NO_SEPARATOR),
      GTK_STOCK_CLOSE,
      GTK_RESPONSE_REJECT,
      NULL);

  accessible_widget_helper_.reset(new AccessibleWidgetHelper(dialog_, profile));
  accessible_widget_helper_->SendOpenWindowNotification(dialog_name);

  gtk_util::AddButtonToDialog(dialog_,
      l10n_util::GetStringUTF8(IDS_CLEAR_BROWSING_DATA_COMMIT).c_str(),
      GTK_STOCK_APPLY, GTK_RESPONSE_ACCEPT);

  GtkWidget* content_area = GTK_DIALOG(dialog_)->vbox;
  gtk_box_set_spacing(GTK_BOX(content_area), gtk_util::kContentAreaSpacing);

  GtkWidget* vbox = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);
  gtk_container_add(GTK_CONTAINER(content_area), vbox);

  // Label on top of the checkboxes.
  GtkWidget* description = gtk_label_new(
      l10n_util::GetStringUTF8(IDS_CLEAR_BROWSING_DATA_LABEL).c_str());
  gtk_misc_set_alignment(GTK_MISC(description), 0, 0);
  gtk_box_pack_start(GTK_BOX(vbox), description, FALSE, FALSE, 0);

  // History checkbox.
  del_history_checkbox_ = gtk_check_button_new_with_label(
      l10n_util::GetStringUTF8(IDS_DEL_BROWSING_HISTORY_CHKBOX).c_str());
  gtk_box_pack_start(GTK_BOX(vbox), del_history_checkbox_, FALSE, FALSE, 0);
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(del_history_checkbox_),
      profile_->GetPrefs()->GetBoolean(prefs::kDeleteBrowsingHistory));
  g_signal_connect(del_history_checkbox_, "toggled",
                   G_CALLBACK(OnDialogWidgetClickedThunk), this);

  // Downloads checkbox.
  del_downloads_checkbox_ = gtk_check_button_new_with_label(
      l10n_util::GetStringUTF8(IDS_DEL_DOWNLOAD_HISTORY_CHKBOX).c_str());
  gtk_box_pack_start(GTK_BOX(vbox), del_downloads_checkbox_, FALSE, FALSE, 0);
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(del_downloads_checkbox_),
      profile_->GetPrefs()->GetBoolean(prefs::kDeleteDownloadHistory));
  g_signal_connect(del_downloads_checkbox_, "toggled",
                   G_CALLBACK(OnDialogWidgetClickedThunk), this);

  // Cache checkbox.
  del_cache_checkbox_ = gtk_check_button_new_with_label(
      l10n_util::GetStringUTF8(IDS_DEL_CACHE_CHKBOX).c_str());
  gtk_box_pack_start(GTK_BOX(vbox), del_cache_checkbox_, FALSE, FALSE, 0);
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(del_cache_checkbox_),
      profile_->GetPrefs()->GetBoolean(prefs::kDeleteCache));
  g_signal_connect(del_cache_checkbox_, "toggled",
                   G_CALLBACK(OnDialogWidgetClickedThunk), this);

  // Cookies checkbox.
  del_cookies_checkbox_ = gtk_check_button_new_with_label(
      l10n_util::GetStringUTF8(IDS_DEL_COOKIES_CHKBOX).c_str());
  gtk_box_pack_start(GTK_BOX(vbox), del_cookies_checkbox_, FALSE, FALSE, 0);
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(del_cookies_checkbox_),
      profile_->GetPrefs()->GetBoolean(prefs::kDeleteCookies));
  g_signal_connect(del_cookies_checkbox_, "toggled",
                   G_CALLBACK(OnDialogWidgetClickedThunk), this);

  // Passwords checkbox.
  del_passwords_checkbox_ = gtk_check_button_new_with_label(
      l10n_util::GetStringUTF8(IDS_DEL_PASSWORDS_CHKBOX).c_str());
  gtk_box_pack_start(GTK_BOX(vbox), del_passwords_checkbox_, FALSE, FALSE, 0);
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(del_passwords_checkbox_),
      profile_->GetPrefs()->GetBoolean(prefs::kDeletePasswords));
  g_signal_connect(del_passwords_checkbox_, "toggled",
                   G_CALLBACK(OnDialogWidgetClickedThunk), this);

  // Form data checkbox.
  del_form_data_checkbox_ = gtk_check_button_new_with_label(
      l10n_util::GetStringUTF8(IDS_DEL_FORM_DATA_CHKBOX).c_str());
  gtk_box_pack_start(GTK_BOX(vbox), del_form_data_checkbox_, FALSE, FALSE, 0);
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(del_form_data_checkbox_),
      profile_->GetPrefs()->GetBoolean(prefs::kDeleteFormData));
  g_signal_connect(del_form_data_checkbox_, "toggled",
                   G_CALLBACK(OnDialogWidgetClickedThunk), this);

  // Create a horizontal layout for the combo box and label.
  GtkWidget* combo_hbox = gtk_hbox_new(FALSE, gtk_util::kLabelSpacing);
  GtkWidget* time_period_label_ = gtk_label_new(
      l10n_util::GetStringUTF8(IDS_CLEAR_BROWSING_DATA_TIME_LABEL).c_str());
  gtk_box_pack_start(GTK_BOX(combo_hbox), time_period_label_, FALSE, FALSE, 0);

  // Time period combo box items.
  time_period_combobox_ = gtk_combo_box_new_text();
  gtk_combo_box_append_text(GTK_COMBO_BOX(time_period_combobox_),
      l10n_util::GetStringUTF8(IDS_CLEAR_DATA_HOUR).c_str());
  gtk_combo_box_append_text(GTK_COMBO_BOX(time_period_combobox_),
      l10n_util::GetStringUTF8(IDS_CLEAR_DATA_DAY).c_str());
  gtk_combo_box_append_text(GTK_COMBO_BOX(time_period_combobox_),
      l10n_util::GetStringUTF8(IDS_CLEAR_DATA_WEEK).c_str());
  gtk_combo_box_append_text(GTK_COMBO_BOX(time_period_combobox_),
      l10n_util::GetStringUTF8(IDS_CLEAR_DATA_4WEEKS).c_str());
  gtk_combo_box_append_text(GTK_COMBO_BOX(time_period_combobox_),
      l10n_util::GetStringUTF8(IDS_CLEAR_DATA_EVERYTHING).c_str());
  gtk_combo_box_set_active(GTK_COMBO_BOX(time_period_combobox_),
      profile_->GetPrefs()->GetInteger(prefs::kDeleteTimePeriod));
  gtk_box_pack_start(GTK_BOX(combo_hbox),
                     time_period_combobox_, FALSE, FALSE, 0);
  g_signal_connect(time_period_combobox_, "changed",
                   G_CALLBACK(OnDialogWidgetClickedThunk), this);

  // Add the combo/label time period box to the vertical layout.
  gtk_box_pack_start(GTK_BOX(vbox), combo_hbox, FALSE, FALSE, 0);

  // Add widgets for the area below the accept buttons.
  GtkWidget* flash_link = gtk_chrome_link_button_new(
      l10n_util::GetStringUTF8(IDS_FLASH_STORAGE_SETTINGS).c_str());
  g_signal_connect(G_OBJECT(flash_link), "clicked",
                   G_CALLBACK(OnFlashLinkClickedThunk), this);
  GtkWidget* flash_link_hbox = gtk_hbox_new(FALSE, 0);
  gtk_box_pack_start(GTK_BOX(flash_link_hbox), flash_link, FALSE, FALSE, 0);
  gtk_box_pack_end(GTK_BOX(content_area), flash_link_hbox, FALSE, FALSE, 0);

  GtkWidget* separator = gtk_hseparator_new();
  gtk_box_pack_end(GTK_BOX(content_area), separator, FALSE, FALSE, 0);

  // Make sure we can move things around.
  DCHECK_EQ(GTK_DIALOG(dialog_)->action_area->parent, content_area);

  // Now rearrange those because they're *above* the accept buttons...there's
  // no way to place them in the correct position with gtk_box_pack_end() so
  // manually move things into the correct order.
  gtk_box_reorder_child(GTK_BOX(content_area), flash_link_hbox, -1);
  gtk_box_reorder_child(GTK_BOX(content_area), separator, -1);
  gtk_box_reorder_child(GTK_BOX(content_area), GTK_DIALOG(dialog_)->action_area,
                        -1);

  g_signal_connect(dialog_, "response",
                   G_CALLBACK(OnDialogResponseThunk), this);

  UpdateDialogButtons();

  gtk_util::ShowModalDialogWithMinLocalizedWidth(dialog_,
      IDS_CLEARDATA_DIALOG_WIDTH_CHARS);
}

ClearBrowsingDataDialogGtk::~ClearBrowsingDataDialogGtk() {
}

void ClearBrowsingDataDialogGtk::OnDialogResponse(GtkWidget* widget,
                                                  int response) {
  if (response == GTK_RESPONSE_ACCEPT) {
    int period_selected = gtk_combo_box_get_active(
        GTK_COMBO_BOX(time_period_combobox_));

    // BrowsingDataRemover deletes itself when done.
    remover_ = new BrowsingDataRemover(profile_,
        static_cast<BrowsingDataRemover::TimePeriod>(period_selected),
        base::Time());
    remover_->Remove(GetCheckedItems());
  }

  delete this;
  gtk_widget_destroy(GTK_WIDGET(widget));
}

void ClearBrowsingDataDialogGtk::OnDialogWidgetClicked(GtkWidget* widget) {
  if (widget == del_history_checkbox_) {
    profile_->GetPrefs()->SetBoolean(prefs::kDeleteBrowsingHistory,
                                     IsChecked(widget));
  } else if (widget == del_downloads_checkbox_) {
    profile_->GetPrefs()->SetBoolean(prefs::kDeleteDownloadHistory,
                                     IsChecked(widget));
  } else if (widget == del_cache_checkbox_) {
    profile_->GetPrefs()->SetBoolean(prefs::kDeleteCache,
                                     IsChecked(widget));
  } else if (widget == del_cookies_checkbox_) {
    profile_->GetPrefs()->SetBoolean(prefs::kDeleteCookies,
                                     IsChecked(widget));
  } else if (widget == del_passwords_checkbox_) {
    profile_->GetPrefs()->SetBoolean(prefs::kDeletePasswords,
                                     IsChecked(widget));
  } else if (widget == del_form_data_checkbox_) {
    profile_->GetPrefs()->SetBoolean(prefs::kDeleteFormData,
                                     IsChecked(widget));
  } else if (widget == time_period_combobox_) {
    profile_->GetPrefs()->SetInteger(prefs::kDeleteTimePeriod,
        gtk_combo_box_get_active(GTK_COMBO_BOX(widget)));
  }
  UpdateDialogButtons();
}

void ClearBrowsingDataDialogGtk::OnFlashLinkClicked(GtkWidget* button) {
  // We open a new browser window so the Options dialog doesn't get lost
  // behind other windows.
  Browser* browser = Browser::Create(profile_);
  browser->OpenURL(GURL(l10n_util::GetStringUTF8(IDS_FLASH_STORAGE_URL)),
                   GURL(), NEW_FOREGROUND_TAB, PageTransition::LINK);
  browser->window()->Show();
}

void ClearBrowsingDataDialogGtk::UpdateDialogButtons() {
  gtk_dialog_set_response_sensitive(GTK_DIALOG(dialog_), GTK_RESPONSE_ACCEPT,
                                    GetCheckedItems() != 0);
}

int ClearBrowsingDataDialogGtk::GetCheckedItems() {
  int items = 0;
  if (IsChecked(del_history_checkbox_))
    items |= BrowsingDataRemover::REMOVE_HISTORY;
  if (IsChecked(del_downloads_checkbox_))
    items |= BrowsingDataRemover::REMOVE_DOWNLOADS;
  if (IsChecked(del_cookies_checkbox_))
    items |= BrowsingDataRemover::REMOVE_COOKIES;
  if (IsChecked(del_passwords_checkbox_))
    items |= BrowsingDataRemover::REMOVE_PASSWORDS;
  if (IsChecked(del_form_data_checkbox_))
    items |= BrowsingDataRemover::REMOVE_FORM_DATA;
  if (IsChecked(del_cache_checkbox_))
    items |= BrowsingDataRemover::REMOVE_CACHE;
  return items;
}
<|endoftext|>


<commit_before><commit_msg>Add unit test for the "aborted by shutdown" case. This unit test would crash the code that is on the current dev branch, however with the addition of the DataTypeManager this is no longer a problem on trunk.  In the dev version, the PSS would try to try to stop a data type in mid startp causing it to abort, which then rasies and error and tries to stop the same data type again.  With the DTM, it knows how to handle aborting a data type startup at shutdown by not letting an aborted stop raise an error.<commit_after><|endoftext|>


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

#include "chrome/browser/ui/views/ash/chrome_shell_delegate.h"

#include "ash/launcher/launcher_types.h"
#include "ash/system/tray/system_tray_delegate.h"
#include "ash/wm/partial_screenshot_view.h"
#include "ash/wm/window_util.h"
#include "base/command_line.h"
#include "chrome/browser/chromeos/login/screen_locker.h"
#include "chrome/browser/extensions/api/terminal/terminal_extension_helper.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/views/ash/app_list/app_list_view_delegate.h"
#include "chrome/browser/ui/views/ash/launcher/chrome_launcher_delegate.h"
#include "chrome/browser/ui/views/ash/window_positioner.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/user_metrics.h"
#include "content/public/browser/web_contents.h"
#include "grit/generated_resources.h"
#include "ui/aura/window.h"

#if defined(OS_CHROMEOS)
#include "base/chromeos/chromeos_version.h"
#include "chrome/browser/chromeos/accessibility/accessibility_util.h"
#include "chrome/browser/chromeos/background/desktop_background_observer.h"
#include "chrome/browser/chromeos/extensions/file_manager_util.h"
#include "chrome/browser/chromeos/kiosk_mode/kiosk_mode_settings.h"
#include "chrome/browser/chromeos/login/webui_login_display_host.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/chromeos/system/ash_system_tray_delegate.h"
#include "chrome/browser/ui/webui/chromeos/login/oobe_ui.h"
#include "chrome/browser/ui/webui/chromeos/mobile_setup_dialog.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/dbus/power_manager_client.h"
#endif

// static
ChromeShellDelegate* ChromeShellDelegate::instance_ = NULL;

ChromeShellDelegate::ChromeShellDelegate()
    : window_positioner_(new WindowPositioner()),
      ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) {
  instance_ = this;
#if defined(OS_CHROMEOS)
  registrar_.Add(
      this,
      chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED,
      content::NotificationService::AllSources());
#endif
}

ChromeShellDelegate::~ChromeShellDelegate() {
  if (instance_ == this)
    instance_ = NULL;
}

bool ChromeShellDelegate::IsUserLoggedIn() {
#if defined(OS_CHROMEOS)
  // When running a Chrome OS build outside of a device (i.e. on a developer's
  // workstation), pretend like we're always logged in.
  if (!base::chromeos::IsRunningOnChromeOS())
    return true;

  return chromeos::UserManager::Get()->IsUserLoggedIn();
#else
  return true;
#endif
}

void ChromeShellDelegate::LockScreen() {
#if defined(OS_CHROMEOS)
  if (!CommandLine::ForCurrentProcess()->HasSwitch(switches::kGuestSession) &&
      !chromeos::KioskModeSettings::Get()->IsKioskModeEnabled()) {
    chromeos::DBusThreadManager::Get()->GetPowerManagerClient()->
        NotifyScreenLockRequested();
  }
#endif
}

void ChromeShellDelegate::UnlockScreen() {
  // This is used only for testing thus far.
  NOTIMPLEMENTED();
}

bool ChromeShellDelegate::IsScreenLocked() const {
#if defined(OS_CHROMEOS)
  if (!chromeos::ScreenLocker::default_screen_locker())
    return false;
  return chromeos::ScreenLocker::default_screen_locker()->locked();
#else
  return false;
#endif
}

void ChromeShellDelegate::Shutdown() {
#if defined(OS_CHROMEOS)
  content::RecordAction(content::UserMetricsAction("Shutdown"));
  chromeos::DBusThreadManager::Get()->GetPowerManagerClient()->
      RequestShutdown();
#endif
}

void ChromeShellDelegate::Exit() {
  BrowserList::AttemptUserExit();
}

void ChromeShellDelegate::NewWindow(bool is_incognito) {
  Profile* profile = ProfileManager::GetDefaultProfileOrOffTheRecord();
  Browser::NewEmptyWindow(
      is_incognito ? profile->GetOffTheRecordProfile() : profile);
}

void ChromeShellDelegate::Search() {
  // Exit fullscreen to show omnibox.
  Browser* last_active = BrowserList::GetLastActive();
  if (last_active) {
    if (last_active->window()->IsFullscreen()) {
      last_active->ToggleFullscreenMode();
      // ToggleFullscreenMode is asynchronous, so we don't have omnibox
      // visible at this point. Wait for next event cycle which toggles
      // the visibility of omnibox before creating new tab.
      MessageLoop::current()->PostTask(
          FROM_HERE, base::Bind(&ChromeShellDelegate::Search,
                                weak_factory_.GetWeakPtr()));
      return;
    }
  }

  Browser* target_browser = Browser::GetOrCreateTabbedBrowser(
      last_active ? last_active->profile() :
                    ProfileManager::GetDefaultProfileOrOffTheRecord());
  const GURL& url = target_browser->GetSelectedWebContents()->GetURL();
  if (url.SchemeIs(chrome::kChromeUIScheme) &&
      url.host() == chrome::kChromeUINewTabHost) {
    // If the NTP is showing, focus the omnibox.
    target_browser->window()->SetFocusToLocationBar(true);
  } else {
    target_browser->NewTab();
  }
}

void ChromeShellDelegate::OpenFileManager() {
#if defined(OS_CHROMEOS)
  file_manager_util::OpenApplication();
#endif
}

void ChromeShellDelegate::OpenCrosh() {
#if defined(OS_CHROMEOS)
  Browser* browser = Browser::GetOrCreateTabbedBrowser(
      ProfileManager::GetDefaultProfileOrOffTheRecord());
  GURL crosh_url = TerminalExtensionHelper::GetCroshExtensionURL(
      browser->profile());
  if (!crosh_url.is_valid())
    return;
  browser->OpenURL(
      content::OpenURLParams(crosh_url,
                             content::Referrer(),
                             NEW_FOREGROUND_TAB,
                             content::PAGE_TRANSITION_GENERATED,
                             false));
#endif
}

void ChromeShellDelegate::OpenMobileSetup() {
#if defined(OS_CHROMEOS)
  Browser* browser = Browser::GetOrCreateTabbedBrowser(
      ProfileManager::GetDefaultProfileOrOffTheRecord());
  if (CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kEnableMobileSetupDialog)) {
    MobileSetupDialog::Show();
  } else {
    browser->OpenURL(
        content::OpenURLParams(GURL(chrome::kChromeUIMobileSetupURL),
                               content::Referrer(),
                               NEW_FOREGROUND_TAB,
                               content::PAGE_TRANSITION_LINK,
                               false));
    browser->window()->Activate();
  }
#endif
}

void ChromeShellDelegate::ToggleSpokenFeedback() {
#if defined(OS_CHROMEOS)
  content::WebUI* login_screen_web_ui = NULL;
  chromeos::WebUILoginDisplayHost* host =
      static_cast<chromeos::WebUILoginDisplayHost*>(
          chromeos::BaseLoginDisplayHost::default_host());
  if (host && host->GetOobeUI())
    login_screen_web_ui = host->GetOobeUI()->web_ui();
  chromeos::accessibility::ToggleSpokenFeedback(login_screen_web_ui);
#endif
}

ash::AppListViewDelegate*
    ChromeShellDelegate::CreateAppListViewDelegate() {
  // Shell will own the created delegate.
  return new AppListViewDelegate;
}

void ChromeShellDelegate::StartPartialScreenshot(
    ash::ScreenshotDelegate* screenshot_delegate) {
  ash::PartialScreenshotView::StartPartialScreenshot(screenshot_delegate);
}

ash::LauncherDelegate* ChromeShellDelegate::CreateLauncherDelegate(
    ash::LauncherModel* model) {
  ChromeLauncherDelegate* delegate = new ChromeLauncherDelegate(NULL, model);
  delegate->Init();
  return delegate;
}

ash::SystemTrayDelegate* ChromeShellDelegate::CreateSystemTrayDelegate(
    ash::SystemTray* tray) {
#if defined(OS_CHROMEOS)
  return chromeos::CreateSystemTrayDelegate(tray);
#else
  return NULL;
#endif
}

ash::UserWallpaperDelegate* ChromeShellDelegate::CreateUserWallpaperDelegate() {
#if defined(OS_CHROMEOS)
  return chromeos::CreateUserWallpaperDelegate();
#else
  return NULL;
#endif
}

void ChromeShellDelegate::Observe(int type,
                                  const content::NotificationSource& source,
                                  const content::NotificationDetails& details) {
#if defined(OS_CHROMEOS)
  switch (type) {
    case chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED:
      ash::Shell::GetInstance()->CreateLauncher();
      break;
    default:
      NOTREACHED() << "Unexpected notification " << type;
  }
#else
  // MSVC++ warns about switch statements without any cases.
  NOTREACHED() << "Unexpected notification " << type;
#endif
}
<commit_msg>ash: Fix a couple issues in ChromeShellDelegate::Search<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/views/ash/chrome_shell_delegate.h"

#include "ash/launcher/launcher_types.h"
#include "ash/system/tray/system_tray_delegate.h"
#include "ash/wm/partial_screenshot_view.h"
#include "ash/wm/window_util.h"
#include "base/command_line.h"
#include "chrome/browser/chromeos/login/screen_locker.h"
#include "chrome/browser/extensions/api/terminal/terminal_extension_helper.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/views/ash/app_list/app_list_view_delegate.h"
#include "chrome/browser/ui/views/ash/launcher/chrome_launcher_delegate.h"
#include "chrome/browser/ui/views/ash/window_positioner.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/user_metrics.h"
#include "content/public/browser/web_contents.h"
#include "grit/generated_resources.h"
#include "ui/aura/window.h"

#if defined(OS_CHROMEOS)
#include "base/chromeos/chromeos_version.h"
#include "chrome/browser/chromeos/accessibility/accessibility_util.h"
#include "chrome/browser/chromeos/background/desktop_background_observer.h"
#include "chrome/browser/chromeos/extensions/file_manager_util.h"
#include "chrome/browser/chromeos/kiosk_mode/kiosk_mode_settings.h"
#include "chrome/browser/chromeos/login/webui_login_display_host.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/chromeos/system/ash_system_tray_delegate.h"
#include "chrome/browser/ui/webui/chromeos/login/oobe_ui.h"
#include "chrome/browser/ui/webui/chromeos/mobile_setup_dialog.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/dbus/power_manager_client.h"
#endif

// static
ChromeShellDelegate* ChromeShellDelegate::instance_ = NULL;

ChromeShellDelegate::ChromeShellDelegate()
    : window_positioner_(new WindowPositioner()),
      ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) {
  instance_ = this;
#if defined(OS_CHROMEOS)
  registrar_.Add(
      this,
      chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED,
      content::NotificationService::AllSources());
#endif
}

ChromeShellDelegate::~ChromeShellDelegate() {
  if (instance_ == this)
    instance_ = NULL;
}

bool ChromeShellDelegate::IsUserLoggedIn() {
#if defined(OS_CHROMEOS)
  // When running a Chrome OS build outside of a device (i.e. on a developer's
  // workstation), pretend like we're always logged in.
  if (!base::chromeos::IsRunningOnChromeOS())
    return true;

  return chromeos::UserManager::Get()->IsUserLoggedIn();
#else
  return true;
#endif
}

void ChromeShellDelegate::LockScreen() {
#if defined(OS_CHROMEOS)
  if (!CommandLine::ForCurrentProcess()->HasSwitch(switches::kGuestSession) &&
      !chromeos::KioskModeSettings::Get()->IsKioskModeEnabled()) {
    chromeos::DBusThreadManager::Get()->GetPowerManagerClient()->
        NotifyScreenLockRequested();
  }
#endif
}

void ChromeShellDelegate::UnlockScreen() {
  // This is used only for testing thus far.
  NOTIMPLEMENTED();
}

bool ChromeShellDelegate::IsScreenLocked() const {
#if defined(OS_CHROMEOS)
  if (!chromeos::ScreenLocker::default_screen_locker())
    return false;
  return chromeos::ScreenLocker::default_screen_locker()->locked();
#else
  return false;
#endif
}

void ChromeShellDelegate::Shutdown() {
#if defined(OS_CHROMEOS)
  content::RecordAction(content::UserMetricsAction("Shutdown"));
  chromeos::DBusThreadManager::Get()->GetPowerManagerClient()->
      RequestShutdown();
#endif
}

void ChromeShellDelegate::Exit() {
  BrowserList::AttemptUserExit();
}

void ChromeShellDelegate::NewWindow(bool is_incognito) {
  Profile* profile = ProfileManager::GetDefaultProfileOrOffTheRecord();
  Browser::NewEmptyWindow(
      is_incognito ? profile->GetOffTheRecordProfile() : profile);
}

void ChromeShellDelegate::Search() {
  // Exit fullscreen to show omnibox.
  Browser* last_active = BrowserList::GetLastActive();
  if (last_active) {
    if (last_active->window()->IsFullscreen()) {
      last_active->ToggleFullscreenMode();
      // ToggleFullscreenMode is asynchronous, so we don't have omnibox
      // visible at this point. Wait for next event cycle which toggles
      // the visibility of omnibox before creating new tab.
      MessageLoop::current()->PostTask(
          FROM_HERE, base::Bind(&ChromeShellDelegate::Search,
                                weak_factory_.GetWeakPtr()));
      return;
    }
  }

  Browser* target_browser = Browser::GetOrCreateTabbedBrowser(
      last_active ? last_active->profile() :
                    ProfileManager::GetDefaultProfileOrOffTheRecord());
  const GURL& url = target_browser->GetSelectedWebContents() ?
      target_browser->GetSelectedWebContents()->GetURL() : GURL();
  if (url.SchemeIs(chrome::kChromeUIScheme) &&
      url.host() == chrome::kChromeUINewTabHost) {
    // If the NTP is showing, focus the omnibox.
    target_browser->window()->SetFocusToLocationBar(true);
  } else {
    target_browser->NewTab();
  }
  target_browser->window()->Show();
}

void ChromeShellDelegate::OpenFileManager() {
#if defined(OS_CHROMEOS)
  file_manager_util::OpenApplication();
#endif
}

void ChromeShellDelegate::OpenCrosh() {
#if defined(OS_CHROMEOS)
  Browser* browser = Browser::GetOrCreateTabbedBrowser(
      ProfileManager::GetDefaultProfileOrOffTheRecord());
  GURL crosh_url = TerminalExtensionHelper::GetCroshExtensionURL(
      browser->profile());
  if (!crosh_url.is_valid())
    return;
  browser->OpenURL(
      content::OpenURLParams(crosh_url,
                             content::Referrer(),
                             NEW_FOREGROUND_TAB,
                             content::PAGE_TRANSITION_GENERATED,
                             false));
#endif
}

void ChromeShellDelegate::OpenMobileSetup() {
#if defined(OS_CHROMEOS)
  Browser* browser = Browser::GetOrCreateTabbedBrowser(
      ProfileManager::GetDefaultProfileOrOffTheRecord());
  if (CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kEnableMobileSetupDialog)) {
    MobileSetupDialog::Show();
  } else {
    browser->OpenURL(
        content::OpenURLParams(GURL(chrome::kChromeUIMobileSetupURL),
                               content::Referrer(),
                               NEW_FOREGROUND_TAB,
                               content::PAGE_TRANSITION_LINK,
                               false));
    browser->window()->Activate();
  }
#endif
}

void ChromeShellDelegate::ToggleSpokenFeedback() {
#if defined(OS_CHROMEOS)
  content::WebUI* login_screen_web_ui = NULL;
  chromeos::WebUILoginDisplayHost* host =
      static_cast<chromeos::WebUILoginDisplayHost*>(
          chromeos::BaseLoginDisplayHost::default_host());
  if (host && host->GetOobeUI())
    login_screen_web_ui = host->GetOobeUI()->web_ui();
  chromeos::accessibility::ToggleSpokenFeedback(login_screen_web_ui);
#endif
}

ash::AppListViewDelegate*
    ChromeShellDelegate::CreateAppListViewDelegate() {
  // Shell will own the created delegate.
  return new AppListViewDelegate;
}

void ChromeShellDelegate::StartPartialScreenshot(
    ash::ScreenshotDelegate* screenshot_delegate) {
  ash::PartialScreenshotView::StartPartialScreenshot(screenshot_delegate);
}

ash::LauncherDelegate* ChromeShellDelegate::CreateLauncherDelegate(
    ash::LauncherModel* model) {
  ChromeLauncherDelegate* delegate = new ChromeLauncherDelegate(NULL, model);
  delegate->Init();
  return delegate;
}

ash::SystemTrayDelegate* ChromeShellDelegate::CreateSystemTrayDelegate(
    ash::SystemTray* tray) {
#if defined(OS_CHROMEOS)
  return chromeos::CreateSystemTrayDelegate(tray);
#else
  return NULL;
#endif
}

ash::UserWallpaperDelegate* ChromeShellDelegate::CreateUserWallpaperDelegate() {
#if defined(OS_CHROMEOS)
  return chromeos::CreateUserWallpaperDelegate();
#else
  return NULL;
#endif
}

void ChromeShellDelegate::Observe(int type,
                                  const content::NotificationSource& source,
                                  const content::NotificationDetails& details) {
#if defined(OS_CHROMEOS)
  switch (type) {
    case chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED:
      ash::Shell::GetInstance()->CreateLauncher();
      break;
    default:
      NOTREACHED() << "Unexpected notification " << type;
  }
#else
  // MSVC++ warns about switch statements without any cases.
  NOTREACHED() << "Unexpected notification " << type;
#endif
}
<|endoftext|>


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

#include "chrome/browser/ui/webui/set_as_default_browser_ui.h"

#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/metrics/histogram.h"
#include "base/path_service.h"
#include "chrome/browser/first_run/first_run.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/shell_integration.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_dialogs.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/chrome_pages.h"
#include "chrome/browser/ui/singleton_tabs.h"
#include "chrome/browser/ui/webui/chrome_web_ui_data_source.h"
#include "chrome/browser/ui/webui/sync_promo/sync_promo_ui.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "chrome/installer/util/install_util.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_delegate.h"
#include "content/public/browser/web_contents_view.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_message_handler.h"
#include "grit/browser_resources.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "ui/base/l10n/l10n_font_util.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/gfx/font.h"
#include "ui/web_dialogs/web_dialog_delegate.h"

using content::BrowserThread;
using content::WebContents;
using content::WebUIMessageHandler;

namespace {

const char kSetAsDefaultBrowserHistogram[] = "DefaultBrowser.InteractionResult";

// The enum permits registering in UMA the three possible outcomes.
// ACCEPTED: user pressed Next and made Chrome default.
// DECLINED: user simply closed the dialog without making Chrome default.
// REGRETTED: user pressed Next but then elected a different default browser.
enum MakeChromeDefaultResult {
  MAKE_CHROME_DEFAULT_ACCEPTED,
  MAKE_CHROME_DEFAULT_DECLINED,
  MAKE_CHROME_DEFAULT_REGRETTED,
  MAKE_CHROME_DEFAULT_MAX
};

ChromeWebUIDataSource* CreateSetAsDefaultBrowserUIHTMLSource() {
  ChromeWebUIDataSource* data_source = new ChromeWebUIDataSource(
      chrome::kChromeUIMetroFlowHost);
  data_source->AddLocalizedString("page-title", IDS_METRO_FLOW_TAB_TITLE);
  data_source->AddLocalizedString("flowTitle", IDS_METRO_FLOW_TITLE_SHORT);
  data_source->AddLocalizedString("flowDescription",
                                  IDS_METRO_FLOW_DESCRIPTION);
  data_source->AddLocalizedString("flowNext",
                                  IDS_METRO_FLOW_SET_DEFAULT);
  data_source->AddLocalizedString("chromeLogoString",
                                  IDS_METRO_FLOW_LOGO_STRING_ALT);
  data_source->set_json_path("strings.js");
  data_source->add_resource_path("set_as_default_browser.js",
      IDR_SET_AS_DEFAULT_BROWSER_JS);
  data_source->set_default_resource(IDR_SET_AS_DEFAULT_BROWSER_HTML);
  return data_source;
}

// A simple class serving as a delegate for passing down the result of the
// interaction.
class ResponseDelegate {
 public:
  virtual void SetDialogInteractionResult(MakeChromeDefaultResult result) = 0;

 protected:
  virtual ~ResponseDelegate() { }
};

// Event handler for SetAsDefaultBrowserUI. Capable of setting Chrome as the
// default browser on button click, closing itself and triggering Chrome
// restart.
class SetAsDefaultBrowserHandler
    : public WebUIMessageHandler,
      public base::SupportsWeakPtr<SetAsDefaultBrowserHandler>,
      public ShellIntegration::DefaultWebClientObserver {
 public:
  explicit SetAsDefaultBrowserHandler(ResponseDelegate* response_delegate);
  virtual ~SetAsDefaultBrowserHandler();

  // WebUIMessageHandler implementation.
  virtual void RegisterMessages() OVERRIDE;

  // ShellIntegration::DefaultWebClientObserver implementation.
  virtual void SetDefaultWebClientUIState(
      ShellIntegration::DefaultWebClientUIState state) OVERRIDE;
  virtual void OnSetAsDefaultConcluded(bool close_chrome)  OVERRIDE;
  virtual bool IsInteractiveSetDefaultPermitted() OVERRIDE;

 private:
  // Handler for the 'Next' (or 'make Chrome the Metro browser') button.
  void HandleLaunchSetDefaultBrowserFlow(const ListValue* args);

  // Close this web ui.
  void ConcludeInteraction(MakeChromeDefaultResult interaction_result);

  scoped_refptr<ShellIntegration::DefaultBrowserWorker> default_browser_worker_;
  bool set_default_returned_;
  bool set_default_result_;
  ResponseDelegate* response_delegate_;

  DISALLOW_COPY_AND_ASSIGN(SetAsDefaultBrowserHandler);
};

SetAsDefaultBrowserHandler::SetAsDefaultBrowserHandler(
    ResponseDelegate* response_delegate)
    : ALLOW_THIS_IN_INITIALIZER_LIST(default_browser_worker_(
          new ShellIntegration::DefaultBrowserWorker(this))),
      set_default_returned_(false), set_default_result_(false),
      response_delegate_(response_delegate) {
}

SetAsDefaultBrowserHandler::~SetAsDefaultBrowserHandler() {
  default_browser_worker_->ObserverDestroyed();
}

void SetAsDefaultBrowserHandler::RegisterMessages() {
  web_ui()->RegisterMessageCallback(
      "SetAsDefaultBrowser:LaunchSetDefaultBrowserFlow",
      base::Bind(&SetAsDefaultBrowserHandler::HandleLaunchSetDefaultBrowserFlow,
                 base::Unretained(this)));
}

void SetAsDefaultBrowserHandler::SetDefaultWebClientUIState(
    ShellIntegration::DefaultWebClientUIState state) {
  // The callback is expected to be invoked once the procedure has completed.
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  if (!set_default_returned_)
    return;

  if (state == ShellIntegration::STATE_NOT_DEFAULT && set_default_result_) {
    // The operation concluded, but Chrome is still not the default.
    // If the call has succeeded, this suggests user has decided not to make
    // chrome the default.
    ConcludeInteraction(MAKE_CHROME_DEFAULT_REGRETTED);
  } else if (state == ShellIntegration::STATE_IS_DEFAULT) {
    ConcludeInteraction(MAKE_CHROME_DEFAULT_ACCEPTED);
  }

  // Otherwise, keep the dialog open since the user probably didn't make a
  // choice.
}

void SetAsDefaultBrowserHandler::OnSetAsDefaultConcluded(bool call_result) {
  set_default_returned_ = true;
  set_default_result_ = call_result;
}

bool SetAsDefaultBrowserHandler::IsInteractiveSetDefaultPermitted() {
  return true;
}

void SetAsDefaultBrowserHandler::HandleLaunchSetDefaultBrowserFlow(
    const ListValue* args) {
  set_default_returned_ = false;
  set_default_result_ = false;
  default_browser_worker_->StartSetAsDefault();
}

void SetAsDefaultBrowserHandler::ConcludeInteraction(
    MakeChromeDefaultResult interaction_result) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  if (response_delegate_)
    response_delegate_->SetDialogInteractionResult(interaction_result);

  WebContents* contents = web_ui()->GetWebContents();

  if (contents) {
    content::WebContentsDelegate* delegate = contents->GetDelegate();
    if (delegate)
      delegate->CloseContents(contents);
  }
}

// A web dialog delegate implementation for when 'Make Chrome Metro' UI
// is displayed on a dialog.
class SetAsDefaultBrowserDialogImpl : public ui::WebDialogDelegate,
                                      public ResponseDelegate {
 public:
  SetAsDefaultBrowserDialogImpl(Profile* profile, Browser* browser);
  virtual ~SetAsDefaultBrowserDialogImpl();
  // Show a modal web dialog with kChromeUIMetroFlowURL page.
  void ShowDialog();

 protected:
  // Overridden from WebDialogDelegate:
  virtual ui::ModalType GetDialogModalType() const OVERRIDE;
  virtual string16 GetDialogTitle() const OVERRIDE;
  virtual GURL GetDialogContentURL() const OVERRIDE;
  virtual void GetWebUIMessageHandlers(
      std::vector<WebUIMessageHandler*>* handlers) const OVERRIDE;
  virtual void GetDialogSize(gfx::Size* size) const OVERRIDE;
  virtual std::string GetDialogArgs() const OVERRIDE;
  virtual void OnDialogClosed(const std::string& json_retval) OVERRIDE;
  virtual void OnCloseContents(WebContents* source,
                               bool* out_close_dialog) OVERRIDE;
  virtual bool ShouldShowDialogTitle() const OVERRIDE;
  virtual bool HandleContextMenu(
      const content::ContextMenuParams& params) OVERRIDE;

  // Overridden from ResponseDelegate:
  virtual void SetDialogInteractionResult(MakeChromeDefaultResult result);

 private:
  Profile* profile_;
  Browser* browser_;
  mutable bool owns_handler_;
  SetAsDefaultBrowserHandler* handler_;
  MakeChromeDefaultResult dialog_interation_result_;

  DISALLOW_COPY_AND_ASSIGN(SetAsDefaultBrowserDialogImpl);
};

SetAsDefaultBrowserDialogImpl::SetAsDefaultBrowserDialogImpl(Profile* profile,
                                                             Browser* browser)
    : profile_(profile),
      browser_(browser),
      owns_handler_(true),
      handler_(new SetAsDefaultBrowserHandler(this)),
      dialog_interation_result_(MAKE_CHROME_DEFAULT_DECLINED) {
}

SetAsDefaultBrowserDialogImpl::~SetAsDefaultBrowserDialogImpl() {
  if (owns_handler_)
    delete handler_;
}

void SetAsDefaultBrowserDialogImpl::ShowDialog() {
  chrome::ShowWebDialog(browser_->window()->GetNativeWindow(),
                        browser_->profile(), this);
}

ui::ModalType SetAsDefaultBrowserDialogImpl::GetDialogModalType() const {
  return ui::MODAL_TYPE_SYSTEM;
}

string16 SetAsDefaultBrowserDialogImpl::GetDialogTitle() const {
  return l10n_util::GetStringUTF16(IDS_METRO_FLOW_TAB_TITLE);
}

GURL SetAsDefaultBrowserDialogImpl::GetDialogContentURL() const {
  std::string url_string(chrome::kChromeUIMetroFlowURL);
  return GURL(url_string);
}

void SetAsDefaultBrowserDialogImpl::GetWebUIMessageHandlers(
    std::vector<WebUIMessageHandler*>* handlers) const {
  handlers->push_back(handler_);
  owns_handler_ = false;
}

void SetAsDefaultBrowserDialogImpl::GetDialogSize(gfx::Size* size) const {
  PrefService* prefs = profile_->GetPrefs();
  gfx::Font approximate_web_font(
      prefs->GetString(prefs::kWebKitSansSerifFontFamily),
      prefs->GetInteger(prefs::kWebKitDefaultFontSize));

  *size = ui::GetLocalizedContentsSizeForFont(
      IDS_METRO_FLOW_WIDTH_CHARS, IDS_METRO_FLOW_HEIGHT_LINES,
      approximate_web_font);
}

std::string SetAsDefaultBrowserDialogImpl::GetDialogArgs() const {
  return "[]";
}

void SetAsDefaultBrowserDialogImpl::OnDialogClosed(
    const std::string& json_retval) {
  // Register the user's response in UMA.
  UMA_HISTOGRAM_ENUMERATION(kSetAsDefaultBrowserHistogram,
                            dialog_interation_result_,
                            MAKE_CHROME_DEFAULT_MAX);

  // Carry on with a normal chrome session. For the purpose of surfacing this
  // dialog the actual browser window had to remain hidden. Now it's time to
  // show it.
  BrowserWindow* window = browser_->window();
  WebContents* contents = chrome::GetActiveWebContents(browser_);
  window->Show();
  if (contents)
    contents->GetView()->SetInitialFocus();

  delete this;
}

void SetAsDefaultBrowserDialogImpl::OnCloseContents(WebContents* source,
                                                    bool* out_close_dialog) {
  *out_close_dialog = true;
}

bool SetAsDefaultBrowserDialogImpl::ShouldShowDialogTitle() const {
  return true;
}

bool SetAsDefaultBrowserDialogImpl::HandleContextMenu(
    const content::ContextMenuParams& params) {
  return true;
}

void SetAsDefaultBrowserDialogImpl::SetDialogInteractionResult(
    MakeChromeDefaultResult result) {
  dialog_interation_result_ = result;
}

}  // namespace

SetAsDefaultBrowserUI::SetAsDefaultBrowserUI(content::WebUI* web_ui)
    : ui::WebDialogUI(web_ui) {
  ChromeURLDataManager::AddDataSource(Profile::FromWebUI(web_ui),
                                      CreateSetAsDefaultBrowserUIHTMLSource());
}

// static
void SetAsDefaultBrowserUI::Show(Profile* profile, Browser* browser) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  SetAsDefaultBrowserDialogImpl* dialog =
      new SetAsDefaultBrowserDialogImpl(profile, browser);
  dialog->ShowDialog();
}
<commit_msg>Make sure the SetAsDefault dialog is highly visible on Windows.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/webui/set_as_default_browser_ui.h"

#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/metrics/histogram.h"
#include "base/path_service.h"
#include "chrome/browser/first_run/first_run.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/shell_integration.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_dialogs.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/chrome_pages.h"
#include "chrome/browser/ui/singleton_tabs.h"
#include "chrome/browser/ui/webui/chrome_web_ui_data_source.h"
#include "chrome/browser/ui/webui/sync_promo/sync_promo_ui.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "chrome/installer/util/install_util.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_delegate.h"
#include "content/public/browser/web_contents_view.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_message_handler.h"
#include "grit/browser_resources.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "ui/base/l10n/l10n_font_util.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/gfx/font.h"
#include "ui/views/widget/widget.h"
#include "ui/web_dialogs/web_dialog_delegate.h"

using content::BrowserThread;
using content::WebContents;
using content::WebUIMessageHandler;

namespace {

const char kSetAsDefaultBrowserHistogram[] = "DefaultBrowser.InteractionResult";

// The enum permits registering in UMA the three possible outcomes.
// ACCEPTED: user pressed Next and made Chrome default.
// DECLINED: user simply closed the dialog without making Chrome default.
// REGRETTED: user pressed Next but then elected a different default browser.
enum MakeChromeDefaultResult {
  MAKE_CHROME_DEFAULT_ACCEPTED,
  MAKE_CHROME_DEFAULT_DECLINED,
  MAKE_CHROME_DEFAULT_REGRETTED,
  MAKE_CHROME_DEFAULT_MAX
};

ChromeWebUIDataSource* CreateSetAsDefaultBrowserUIHTMLSource() {
  ChromeWebUIDataSource* data_source = new ChromeWebUIDataSource(
      chrome::kChromeUIMetroFlowHost);
  data_source->AddLocalizedString("page-title", IDS_METRO_FLOW_TAB_TITLE);
  data_source->AddLocalizedString("flowTitle", IDS_METRO_FLOW_TITLE_SHORT);
  data_source->AddLocalizedString("flowDescription",
                                  IDS_METRO_FLOW_DESCRIPTION);
  data_source->AddLocalizedString("flowNext",
                                  IDS_METRO_FLOW_SET_DEFAULT);
  data_source->AddLocalizedString("chromeLogoString",
                                  IDS_METRO_FLOW_LOGO_STRING_ALT);
  data_source->set_json_path("strings.js");
  data_source->add_resource_path("set_as_default_browser.js",
      IDR_SET_AS_DEFAULT_BROWSER_JS);
  data_source->set_default_resource(IDR_SET_AS_DEFAULT_BROWSER_HTML);
  return data_source;
}

// A simple class serving as a delegate for passing down the result of the
// interaction.
class ResponseDelegate {
 public:
  virtual void SetDialogInteractionResult(MakeChromeDefaultResult result) = 0;

 protected:
  virtual ~ResponseDelegate() { }
};

// Event handler for SetAsDefaultBrowserUI. Capable of setting Chrome as the
// default browser on button click, closing itself and triggering Chrome
// restart.
class SetAsDefaultBrowserHandler
    : public WebUIMessageHandler,
      public base::SupportsWeakPtr<SetAsDefaultBrowserHandler>,
      public ShellIntegration::DefaultWebClientObserver {
 public:
  explicit SetAsDefaultBrowserHandler(ResponseDelegate* response_delegate);
  virtual ~SetAsDefaultBrowserHandler();

  // WebUIMessageHandler implementation.
  virtual void RegisterMessages() OVERRIDE;

  // ShellIntegration::DefaultWebClientObserver implementation.
  virtual void SetDefaultWebClientUIState(
      ShellIntegration::DefaultWebClientUIState state) OVERRIDE;
  virtual void OnSetAsDefaultConcluded(bool close_chrome)  OVERRIDE;
  virtual bool IsInteractiveSetDefaultPermitted() OVERRIDE;

 private:
  // Handler for the 'Next' (or 'make Chrome the Metro browser') button.
  void HandleLaunchSetDefaultBrowserFlow(const ListValue* args);

  // Close this web ui.
  void ConcludeInteraction(MakeChromeDefaultResult interaction_result);

  scoped_refptr<ShellIntegration::DefaultBrowserWorker> default_browser_worker_;
  bool set_default_returned_;
  bool set_default_result_;
  ResponseDelegate* response_delegate_;

  DISALLOW_COPY_AND_ASSIGN(SetAsDefaultBrowserHandler);
};

SetAsDefaultBrowserHandler::SetAsDefaultBrowserHandler(
    ResponseDelegate* response_delegate)
    : ALLOW_THIS_IN_INITIALIZER_LIST(default_browser_worker_(
          new ShellIntegration::DefaultBrowserWorker(this))),
      set_default_returned_(false), set_default_result_(false),
      response_delegate_(response_delegate) {
}

SetAsDefaultBrowserHandler::~SetAsDefaultBrowserHandler() {
  default_browser_worker_->ObserverDestroyed();
}

void SetAsDefaultBrowserHandler::RegisterMessages() {
  web_ui()->RegisterMessageCallback(
      "SetAsDefaultBrowser:LaunchSetDefaultBrowserFlow",
      base::Bind(&SetAsDefaultBrowserHandler::HandleLaunchSetDefaultBrowserFlow,
                 base::Unretained(this)));
}

void SetAsDefaultBrowserHandler::SetDefaultWebClientUIState(
    ShellIntegration::DefaultWebClientUIState state) {
  // The callback is expected to be invoked once the procedure has completed.
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  if (!set_default_returned_)
    return;

  if (state == ShellIntegration::STATE_NOT_DEFAULT && set_default_result_) {
    // The operation concluded, but Chrome is still not the default.
    // If the call has succeeded, this suggests user has decided not to make
    // chrome the default.
    ConcludeInteraction(MAKE_CHROME_DEFAULT_REGRETTED);
  } else if (state == ShellIntegration::STATE_IS_DEFAULT) {
    ConcludeInteraction(MAKE_CHROME_DEFAULT_ACCEPTED);
  }

  // Otherwise, keep the dialog open since the user probably didn't make a
  // choice.
}

void SetAsDefaultBrowserHandler::OnSetAsDefaultConcluded(bool call_result) {
  set_default_returned_ = true;
  set_default_result_ = call_result;
}

bool SetAsDefaultBrowserHandler::IsInteractiveSetDefaultPermitted() {
  return true;
}

void SetAsDefaultBrowserHandler::HandleLaunchSetDefaultBrowserFlow(
    const ListValue* args) {
  set_default_returned_ = false;
  set_default_result_ = false;
  default_browser_worker_->StartSetAsDefault();
}

void SetAsDefaultBrowserHandler::ConcludeInteraction(
    MakeChromeDefaultResult interaction_result) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  if (response_delegate_)
    response_delegate_->SetDialogInteractionResult(interaction_result);

  WebContents* contents = web_ui()->GetWebContents();

  if (contents) {
    content::WebContentsDelegate* delegate = contents->GetDelegate();
    if (delegate)
      delegate->CloseContents(contents);
  }
}

// A web dialog delegate implementation for when 'Make Chrome Metro' UI
// is displayed on a dialog.
class SetAsDefaultBrowserDialogImpl : public ui::WebDialogDelegate,
                                      public ResponseDelegate {
 public:
  SetAsDefaultBrowserDialogImpl(Profile* profile, Browser* browser);
  virtual ~SetAsDefaultBrowserDialogImpl();
  // Show a modal web dialog with kChromeUIMetroFlowURL page.
  void ShowDialog();

 protected:
  // Overridden from WebDialogDelegate:
  virtual ui::ModalType GetDialogModalType() const OVERRIDE;
  virtual string16 GetDialogTitle() const OVERRIDE;
  virtual GURL GetDialogContentURL() const OVERRIDE;
  virtual void GetWebUIMessageHandlers(
      std::vector<WebUIMessageHandler*>* handlers) const OVERRIDE;
  virtual void GetDialogSize(gfx::Size* size) const OVERRIDE;
  virtual std::string GetDialogArgs() const OVERRIDE;
  virtual void OnDialogClosed(const std::string& json_retval) OVERRIDE;
  virtual void OnCloseContents(WebContents* source,
                               bool* out_close_dialog) OVERRIDE;
  virtual bool ShouldShowDialogTitle() const OVERRIDE;
  virtual bool HandleContextMenu(
      const content::ContextMenuParams& params) OVERRIDE;

  // Overridden from ResponseDelegate:
  virtual void SetDialogInteractionResult(MakeChromeDefaultResult result);

 private:
  Profile* profile_;
  Browser* browser_;
  mutable bool owns_handler_;
  SetAsDefaultBrowserHandler* handler_;
  MakeChromeDefaultResult dialog_interation_result_;

  DISALLOW_COPY_AND_ASSIGN(SetAsDefaultBrowserDialogImpl);
};

SetAsDefaultBrowserDialogImpl::SetAsDefaultBrowserDialogImpl(Profile* profile,
                                                             Browser* browser)
    : profile_(profile),
      browser_(browser),
      owns_handler_(true),
      handler_(new SetAsDefaultBrowserHandler(this)),
      dialog_interation_result_(MAKE_CHROME_DEFAULT_DECLINED) {
}

SetAsDefaultBrowserDialogImpl::~SetAsDefaultBrowserDialogImpl() {
  if (owns_handler_)
    delete handler_;
}

void SetAsDefaultBrowserDialogImpl::ShowDialog() {
  // Use a NULL parent window to make sure that the dialog will have an item
  // in the Windows task bar. The code below will make it highlight if the
  // dialog is not in the foreground.
  gfx::NativeWindow native_window = chrome::ShowWebDialog(NULL,
                                                          browser_->profile(),
                                                          this);
  views::Widget* widget = views::Widget::GetWidgetForNativeWindow(
      native_window);
  widget->FlashFrame(true);
}

ui::ModalType SetAsDefaultBrowserDialogImpl::GetDialogModalType() const {
  return ui::MODAL_TYPE_SYSTEM;
}

string16 SetAsDefaultBrowserDialogImpl::GetDialogTitle() const {
  return l10n_util::GetStringUTF16(IDS_METRO_FLOW_TAB_TITLE);
}

GURL SetAsDefaultBrowserDialogImpl::GetDialogContentURL() const {
  std::string url_string(chrome::kChromeUIMetroFlowURL);
  return GURL(url_string);
}

void SetAsDefaultBrowserDialogImpl::GetWebUIMessageHandlers(
    std::vector<WebUIMessageHandler*>* handlers) const {
  handlers->push_back(handler_);
  owns_handler_ = false;
}

void SetAsDefaultBrowserDialogImpl::GetDialogSize(gfx::Size* size) const {
  PrefService* prefs = profile_->GetPrefs();
  gfx::Font approximate_web_font(
      prefs->GetString(prefs::kWebKitSansSerifFontFamily),
      prefs->GetInteger(prefs::kWebKitDefaultFontSize));

  *size = ui::GetLocalizedContentsSizeForFont(
      IDS_METRO_FLOW_WIDTH_CHARS, IDS_METRO_FLOW_HEIGHT_LINES,
      approximate_web_font);
}

std::string SetAsDefaultBrowserDialogImpl::GetDialogArgs() const {
  return "[]";
}

void SetAsDefaultBrowserDialogImpl::OnDialogClosed(
    const std::string& json_retval) {
  // Register the user's response in UMA.
  UMA_HISTOGRAM_ENUMERATION(kSetAsDefaultBrowserHistogram,
                            dialog_interation_result_,
                            MAKE_CHROME_DEFAULT_MAX);

  // Carry on with a normal chrome session. For the purpose of surfacing this
  // dialog the actual browser window had to remain hidden. Now it's time to
  // show it.
  BrowserWindow* window = browser_->window();
  WebContents* contents = chrome::GetActiveWebContents(browser_);
  window->Show();
  if (contents)
    contents->GetView()->SetInitialFocus();

  delete this;
}

void SetAsDefaultBrowserDialogImpl::OnCloseContents(WebContents* source,
                                                    bool* out_close_dialog) {
  *out_close_dialog = true;
}

bool SetAsDefaultBrowserDialogImpl::ShouldShowDialogTitle() const {
  return true;
}

bool SetAsDefaultBrowserDialogImpl::HandleContextMenu(
    const content::ContextMenuParams& params) {
  return true;
}

void SetAsDefaultBrowserDialogImpl::SetDialogInteractionResult(
    MakeChromeDefaultResult result) {
  dialog_interation_result_ = result;
}

}  // namespace

SetAsDefaultBrowserUI::SetAsDefaultBrowserUI(content::WebUI* web_ui)
    : ui::WebDialogUI(web_ui) {
  ChromeURLDataManager::AddDataSource(Profile::FromWebUI(web_ui),
                                      CreateSetAsDefaultBrowserUIHTMLSource());
}

// static
void SetAsDefaultBrowserUI::Show(Profile* profile, Browser* browser) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  SetAsDefaultBrowserDialogImpl* dialog =
      new SetAsDefaultBrowserDialogImpl(profile, browser);
  dialog->ShowDialog();
}
<|endoftext|>


<commit_before>/*=========================================================================

 Program:   ORFEO Toolbox
 Language:  C++
 Date:      $Date$
 Version:   $Revision$

 Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
 See OTBCopyright.txt for details.

 This software is distributed WITHOUT ANY WARRANTY; without even
 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 PURPOSE.  See the above copyright notices for more information.

 =========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"

#include <fstream>

#include "otbChangeLabelImageFilter.h"

namespace otb
{
namespace Wrapper
{

class LabeledImageColorMapping: public Application
{
public:
/** Standard class typedefs. */
 typedef LabeledImageColorMapping      Self;
 typedef Application                   Superclass;
 typedef itk::SmartPointer<Self>       Pointer;
 typedef itk::SmartPointer<const Self> ConstPointer;

 /** Standard macro */
 itkNewMacro(Self);

 itkTypeMacro(LabeledImageColorMapping, otb::Application);

 typedef FloatImageType::PixelType   PixelType;
 typedef UInt16ImageType             LabelImageType;
 typedef LabelImageType::PixelType   LabelType;
 typedef UInt8VectorImageType        VectorImageType;
 typedef VectorImageType::PixelType  VectorPixelType;

 typedef otb::ChangeLabelImageFilter<LabelImageType, VectorImageType> ChangeLabelFilterType;

private:
 LabeledImageColorMapping()
  {
    SetName("LabeledImageColorMapping");
    SetDescription("Replace labels of a classification map with user defined 8-bits RGB colors. Unknown label are mapped to black by default.");
  }

  virtual ~LabeledImageColorMapping()
  {
  }

  void DoCreateParameters()
  {
    AddParameter(ParameterType_InputImage, "in", "Input Image.");
    AddParameter(ParameterType_OutputImage, "out", "Output Image.");
    AddParameter(ParameterType_Filename, "ct", "Color table");
    SetParameterDescription("ct",  "An ASCII file containing the color table\n"
                                   "with one color per line\n"
                                   "(for instance the line '1 255 0 0' means that all pixels with label 1 will be replaced by RGB color 255 0 0)\n"
                                   "Lines beginning with a # are ignored");
  }

  void DoUpdateParameters()
  {
    // Nothing to do here : all parameters are independent
  }

  void DoExecute()
  {

    m_LabeledImage = GetParameterUInt16Image("in");

    m_Mapper = ChangeLabelFilterType::New();
    m_Mapper->SetInput(m_LabeledImage);
    m_Mapper->SetNumberOfComponentsPerPixel(3);

    std::ifstream ifs;

    ifs.open(GetParameterString("ct").c_str());

    if (!ifs)
      {
      itkExceptionMacro("Can not read file " << GetParameterString("ct") << std::endl);
      }

    otbAppLogINFO("Parsing color map file " << GetParameterString("ct") << "." << std::endl);

    while (!ifs.eof())
      {
      std::string line;
      std::getline(ifs, line);

      // Avoid commented lines or too short ones
      if (!line.empty() && line[0] != '#')
        {
        // retrieve the label
        std::string::size_type pos = line.find_first_of(" ", 0);
        LabelType clabel = atoi(line.substr(0, pos).c_str());
        ++pos;
        // Retrieve the color
        VectorPixelType color(3);
        color.Fill(0);
        for (unsigned int i = 0; i < 3; ++i)
          {
          std::string::size_type nextpos = line.find_first_of(" ", pos);
          int value = atoi(line.substr(pos, nextpos).c_str());
          if (value < 0 || value > 255)
          otbAppLogWARNING("WARNING: color value outside 8-bits range (<0 or >255). Value will be clamped." << std::endl);
          color[i] = static_cast<PixelType> (value);
          pos = nextpos + 1;
          nextpos = line.find_first_of(" ", pos);
          }
        otbAppLogINFO("Adding color mapping " << clabel << " -> [" << (int) color[0] << " " << (int) color[1] << " "<< (int) color[2] << " ]" << std::endl);
        m_Mapper->SetChange(clabel, color);
        }
      }
    ifs.close();

    /***/
    SetParameterOutputImage<VectorImageType> ("out", m_Mapper->GetOutput());

  }

  ChangeLabelFilterType::Pointer m_Mapper;
  LabelImageType::Pointer m_LabeledImage;

};
}
}

OTB_APPLICATION_EXPORT(otb::Wrapper::LabeledImageColorMapping)

<commit_msg>DOC : Labeled Image color mapping Qt application doc update.<commit_after>/*=========================================================================

 Program:   ORFEO Toolbox
 Language:  C++
 Date:      $Date$
 Version:   $Revision$

 Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
 See OTBCopyright.txt for details.

 This software is distributed WITHOUT ANY WARRANTY; without even
 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 PURPOSE.  See the above copyright notices for more information.

 =========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"

#include <fstream>

#include "otbChangeLabelImageFilter.h"

namespace otb
{
namespace Wrapper
{

class LabeledImageColorMapping: public Application
{
public:
/** Standard class typedefs. */
 typedef LabeledImageColorMapping      Self;
 typedef Application                   Superclass;
 typedef itk::SmartPointer<Self>       Pointer;
 typedef itk::SmartPointer<const Self> ConstPointer;

 /** Standard macro */
 itkNewMacro(Self);

 itkTypeMacro(LabeledImageColorMapping, otb::Application);

 typedef FloatImageType::PixelType   PixelType;
 typedef UInt16ImageType             LabelImageType;
 typedef LabelImageType::PixelType   LabelType;
 typedef UInt8VectorImageType        VectorImageType;
 typedef VectorImageType::PixelType  VectorPixelType;

 typedef otb::ChangeLabelImageFilter<LabelImageType, VectorImageType> ChangeLabelFilterType;

private:
 LabeledImageColorMapping()
  {
    SetName("LabeledImageColorMapping");
    SetDescription("Replace labels of a classification map with user defined 8-bits RGB colors.");

    SetDocName("Labeled Image Color Mapping Application");
    SetDocLongDescription("Create and save a classification map label image (given by ImageSVMClassifier Application for example) with user defined 8-bits RGB colors LUT. Unknown labels are mapped to black by default.");
    SetDocLimitations("None");
    SetDocAuthors("OTB-Team");
    SetDocSeeAlso(" ");
    SetDocCLExample("otbApplicationLauncherCommandLine LabeledImageColorMapping   --in ${OTBAPP_BASELINE}/clLabeledImageQB123_1.tif --ct ${OTB-Data}/Input/Classification/ColorTable.txt --out clLabeledFancyImageQB123_1.tif");
    AddDocTag("Classification");

  }

  virtual ~LabeledImageColorMapping()
  {
  }

  void DoCreateParameters()
  {
    AddParameter(ParameterType_InputImage, "in", "Input Image");
    SetParameterDescription("in", "Input image filename.");
    AddParameter(ParameterType_OutputImage, "out", "Output Image");
    SetParameterDescription("out","Output image filename.");
    AddParameter(ParameterType_Filename, "ct", "Color table");
    SetParameterDescription("ct",  "An ASCII file containing the color table\n"
                                   "with one color per line\n"
                                   "(for instance the line '1 255 0 0' means that all pixels with label 1 will be replaced by RGB color 255 0 0)\n"
                                   "Lines beginning with a # are ignored");
  }

  void DoUpdateParameters()
  {
    // Nothing to do here : all parameters are independent
  }

  void DoExecute()
  {

    m_LabeledImage = GetParameterUInt16Image("in");

    m_Mapper = ChangeLabelFilterType::New();
    m_Mapper->SetInput(m_LabeledImage);
    m_Mapper->SetNumberOfComponentsPerPixel(3);

    std::ifstream ifs;

    ifs.open(GetParameterString("ct").c_str());

    if (!ifs)
      {
      itkExceptionMacro("Can not read file " << GetParameterString("ct") << std::endl);
      }

    otbAppLogINFO("Parsing color map file " << GetParameterString("ct") << "." << std::endl);

    while (!ifs.eof())
      {
      std::string line;
      std::getline(ifs, line);

      // Avoid commented lines or too short ones
      if (!line.empty() && line[0] != '#')
        {
        // retrieve the label
        std::string::size_type pos = line.find_first_of(" ", 0);
        LabelType clabel = atoi(line.substr(0, pos).c_str());
        ++pos;
        // Retrieve the color
        VectorPixelType color(3);
        color.Fill(0);
        for (unsigned int i = 0; i < 3; ++i)
          {
          std::string::size_type nextpos = line.find_first_of(" ", pos);
          int value = atoi(line.substr(pos, nextpos).c_str());
          if (value < 0 || value > 255)
          otbAppLogWARNING("WARNING: color value outside 8-bits range (<0 or >255). Value will be clamped." << std::endl);
          color[i] = static_cast<PixelType> (value);
          pos = nextpos + 1;
          nextpos = line.find_first_of(" ", pos);
          }
        otbAppLogINFO("Adding color mapping " << clabel << " -> [" << (int) color[0] << " " << (int) color[1] << " "<< (int) color[2] << " ]" << std::endl);
        m_Mapper->SetChange(clabel, color);
        }
      }
    ifs.close();

    /***/
    SetParameterOutputImage<VectorImageType> ("out", m_Mapper->GetOutput());

  }

  ChangeLabelFilterType::Pointer m_Mapper;
  LabelImageType::Pointer m_LabeledImage;

};
}
}

OTB_APPLICATION_EXPORT(otb::Wrapper::LabeledImageColorMapping)

<|endoftext|>