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

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

#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "chrome/browser/browsing_data_remover.h"
#include "chrome/browser/profile.h"
#include "chrome/common/gtk_util.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"
#include "grit/generated_resources.h"

// 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.
  GtkWidget* dialog = gtk_dialog_new_with_buttons(
      l10n_util::GetStringUTF8(IDS_CLEAR_BROWSING_DATA_TITLE).c_str(),
      parent,
      (GtkDialogFlags) (GTK_DIALOG_MODAL | GTK_DIALOG_NO_SEPARATOR),
      GTK_STOCK_CANCEL,
      GTK_RESPONSE_REJECT,
      l10n_util::GetStringUTF8(IDS_CLEAR_BROWSING_DATA_COMMIT).c_str(),
      GTK_RESPONSE_ACCEPT,
      NULL);

  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(HandleOnClickedWidget), 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(HandleOnClickedWidget), 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(HandleOnClickedWidget), 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(HandleOnClickedWidget), 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(HandleOnClickedWidget), 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(HandleOnClickedWidget), 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_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(HandleOnClickedWidget), this);

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

  g_signal_connect(dialog, "response",
                   G_CALLBACK(HandleOnResponseDialog), this);
  gtk_window_set_resizable(GTK_WINDOW(dialog), FALSE);
  gtk_widget_show_all(dialog);
}

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_));

    int items = 0;
    if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(del_history_checkbox_)))
      items |= BrowsingDataRemover::REMOVE_HISTORY;
    if (gtk_toggle_button_get_active(
        GTK_TOGGLE_BUTTON(del_downloads_checkbox_))) {
      items |= BrowsingDataRemover::REMOVE_DOWNLOADS;
    }
    if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(del_cookies_checkbox_)))
      items |= BrowsingDataRemover::REMOVE_COOKIES;
    if (gtk_toggle_button_get_active(
        GTK_TOGGLE_BUTTON(del_passwords_checkbox_))) {
      items |= BrowsingDataRemover::REMOVE_PASSWORDS;
    }
    if (gtk_toggle_button_get_active(
        GTK_TOGGLE_BUTTON(del_form_data_checkbox_))) {
      items |= BrowsingDataRemover::REMOVE_FORM_DATA;
    }
    if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(del_cache_checkbox_)))
      items |= BrowsingDataRemover::REMOVE_CACHE;

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

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

void ClearBrowsingDataDialogGtk::OnDialogWidgetClicked(GtkWidget* widget) {
  if (widget == del_history_checkbox_) {
    profile_->GetPrefs()->SetBoolean(prefs::kDeleteBrowsingHistory,
        gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget)) ?
        true : false);
  } else if (widget == del_downloads_checkbox_) {
    profile_->GetPrefs()->SetBoolean(prefs::kDeleteDownloadHistory,
        gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget)) ?
        true : false);
  } else if (widget == del_cache_checkbox_) {
    profile_->GetPrefs()->SetBoolean(prefs::kDeleteCache,
        gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget)) ?
        true : false);
  } else if (widget == del_cookies_checkbox_) {
    profile_->GetPrefs()->SetBoolean(prefs::kDeleteCookies,
        gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget)) ?
        true : false);
  } else if (widget == del_passwords_checkbox_) {
    profile_->GetPrefs()->SetBoolean(prefs::kDeletePasswords,
        gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget)) ?
        true : false);
  } else if (widget == del_form_data_checkbox_) {
    profile_->GetPrefs()->SetBoolean(prefs::kDeleteFormData,
        gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget)) ?
        true : false);
  } else if (widget == time_period_combobox_) {
    profile_->GetPrefs()->SetInteger(prefs::kDeleteTimePeriod,
        gtk_combo_box_get_active(GTK_COMBO_BOX(widget)));
  }
}
<commit_msg>Rename the Cancel button to Close in gtk Clear Browsing Data.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

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

#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "chrome/browser/browsing_data_remover.h"
#include "chrome/browser/profile.h"
#include "chrome/common/gtk_util.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"
#include "grit/generated_resources.h"

// 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.
  GtkWidget* dialog = gtk_dialog_new_with_buttons(
      l10n_util::GetStringUTF8(IDS_CLEAR_BROWSING_DATA_TITLE).c_str(),
      parent,
      (GtkDialogFlags) (GTK_DIALOG_MODAL | GTK_DIALOG_NO_SEPARATOR),
      GTK_STOCK_CLOSE,
      GTK_RESPONSE_REJECT,
      l10n_util::GetStringUTF8(IDS_CLEAR_BROWSING_DATA_COMMIT).c_str(),
      GTK_RESPONSE_ACCEPT,
      NULL);

  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(HandleOnClickedWidget), 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(HandleOnClickedWidget), 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(HandleOnClickedWidget), 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(HandleOnClickedWidget), 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(HandleOnClickedWidget), 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(HandleOnClickedWidget), 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_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(HandleOnClickedWidget), this);

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

  g_signal_connect(dialog, "response",
                   G_CALLBACK(HandleOnResponseDialog), this);
  gtk_window_set_resizable(GTK_WINDOW(dialog), FALSE);
  gtk_widget_show_all(dialog);
}

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_));

    int items = 0;
    if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(del_history_checkbox_)))
      items |= BrowsingDataRemover::REMOVE_HISTORY;
    if (gtk_toggle_button_get_active(
        GTK_TOGGLE_BUTTON(del_downloads_checkbox_))) {
      items |= BrowsingDataRemover::REMOVE_DOWNLOADS;
    }
    if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(del_cookies_checkbox_)))
      items |= BrowsingDataRemover::REMOVE_COOKIES;
    if (gtk_toggle_button_get_active(
        GTK_TOGGLE_BUTTON(del_passwords_checkbox_))) {
      items |= BrowsingDataRemover::REMOVE_PASSWORDS;
    }
    if (gtk_toggle_button_get_active(
        GTK_TOGGLE_BUTTON(del_form_data_checkbox_))) {
      items |= BrowsingDataRemover::REMOVE_FORM_DATA;
    }
    if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(del_cache_checkbox_)))
      items |= BrowsingDataRemover::REMOVE_CACHE;

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

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

void ClearBrowsingDataDialogGtk::OnDialogWidgetClicked(GtkWidget* widget) {
  if (widget == del_history_checkbox_) {
    profile_->GetPrefs()->SetBoolean(prefs::kDeleteBrowsingHistory,
        gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget)) ?
        true : false);
  } else if (widget == del_downloads_checkbox_) {
    profile_->GetPrefs()->SetBoolean(prefs::kDeleteDownloadHistory,
        gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget)) ?
        true : false);
  } else if (widget == del_cache_checkbox_) {
    profile_->GetPrefs()->SetBoolean(prefs::kDeleteCache,
        gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget)) ?
        true : false);
  } else if (widget == del_cookies_checkbox_) {
    profile_->GetPrefs()->SetBoolean(prefs::kDeleteCookies,
        gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget)) ?
        true : false);
  } else if (widget == del_passwords_checkbox_) {
    profile_->GetPrefs()->SetBoolean(prefs::kDeletePasswords,
        gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget)) ?
        true : false);
  } else if (widget == del_form_data_checkbox_) {
    profile_->GetPrefs()->SetBoolean(prefs::kDeleteFormData,
        gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget)) ?
        true : false);
  } else if (widget == time_period_combobox_) {
    profile_->GetPrefs()->SetInteger(prefs::kDeleteTimePeriod,
        gtk_combo_box_get_active(GTK_COMBO_BOX(widget)));
  }
}
<|endoftext|>


<commit_before>// Copyright 2014 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/apps/chrome_app_window_delegate.h"

#include "base/strings/stringprintf.h"
#include "chrome/browser/favicon/favicon_tab_helper.h"
#include "chrome/browser/file_select_helper.h"
#include "chrome/browser/media/media_capture_devices_dispatcher.h"
#include "chrome/browser/platform_util.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_tabstrip.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/scoped_tabbed_browser_displayer.h"
#include "chrome/common/render_messages.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_view.h"

#if defined(USE_ASH)
#include "ash/shelf/shelf_constants.h"
#endif

#if defined(ENABLE_PRINTING)
#if defined(ENABLE_FULL_PRINTING)
#include "chrome/browser/printing/print_preview_message_handler.h"
#include "chrome/browser/printing/print_view_manager.h"
#else
#include "chrome/browser/printing/print_view_manager_basic.h"
#endif  // defined(ENABLE_FULL_PRINTING)
#endif  // defined(ENABLE_PRINTING)

namespace {

bool disable_external_open_for_testing_ = false;

// Opens a URL with Chromium (not external browser) with the right profile.
content::WebContents* OpenURLFromTabInternal(
    content::BrowserContext* context,
    content::WebContents* source,
    const content::OpenURLParams& params) {
  // Force all links to open in a new tab, even if they were trying to open a
  // window.
  chrome::NavigateParams new_tab_params(
      static_cast<Browser*>(NULL), params.url, params.transition);
  new_tab_params.disposition = params.disposition == NEW_BACKGROUND_TAB
                                   ? params.disposition
                                   : NEW_FOREGROUND_TAB;
  new_tab_params.initiating_profile = Profile::FromBrowserContext(context);
  chrome::Navigate(&new_tab_params);

  return new_tab_params.target_contents;
}

// Helper class that opens a URL based on if this browser instance is the
// default system browser. If it is the default, open the URL directly instead
// of asking the system to open it.
class OpenURLFromTabBasedOnBrowserDefault
    : public ShellIntegration::DefaultWebClientObserver {
 public:
  OpenURLFromTabBasedOnBrowserDefault(content::WebContents* source,
                                      const content::OpenURLParams& params)
      : source_(source), params_(params) {}

  // Opens a URL when called with the result of if this is the default system
  // browser or not.
  virtual void SetDefaultWebClientUIState(
      ShellIntegration::DefaultWebClientUIState state) OVERRIDE {
    Profile* profile =
        Profile::FromBrowserContext(source_->GetBrowserContext());
    DCHECK(profile);
    if (!profile)
      return;
    switch (state) {
      case ShellIntegration::STATE_PROCESSING:
        break;
      case ShellIntegration::STATE_IS_DEFAULT:
        OpenURLFromTabInternal(profile, source_, params_);
        break;
      case ShellIntegration::STATE_NOT_DEFAULT:
      case ShellIntegration::STATE_UNKNOWN:
        platform_util::OpenExternal(profile, params_.url);
        break;
    }
  }

  virtual bool IsOwnedByWorker() OVERRIDE { return true; }

 private:
  content::WebContents* source_;
  const content::OpenURLParams params_;
};

}  // namespace

AppWindowLinkDelegate::AppWindowLinkDelegate() {}

AppWindowLinkDelegate::~AppWindowLinkDelegate() {}

// TODO(rockot): Add a test that exercises this code. See
// http://crbug.com/254260.
content::WebContents* AppWindowLinkDelegate::OpenURLFromTab(
    content::WebContents* source,
    const content::OpenURLParams& params) {
  if (source) {
    scoped_refptr<ShellIntegration::DefaultWebClientWorker>
        check_if_default_browser_worker =
            new ShellIntegration::DefaultBrowserWorker(
                new OpenURLFromTabBasedOnBrowserDefault(source, params));
    // Object lifetime notes: The OpenURLFromTabBasedOnBrowserDefault is owned
    // by check_if_default_browser_worker. StartCheckIsDefault() takes lifetime
    // ownership of check_if_default_browser_worker and will clean up after
    // the asynchronous tasks.
    check_if_default_browser_worker->StartCheckIsDefault();
  }
  return NULL;
}

ChromeAppWindowDelegate::ChromeAppWindowDelegate() {}

ChromeAppWindowDelegate::~ChromeAppWindowDelegate() {}

void ChromeAppWindowDelegate::DisableExternalOpenForTesting() {
  disable_external_open_for_testing_ = true;
}

void ChromeAppWindowDelegate::InitWebContents(
    content::WebContents* web_contents) {
  FaviconTabHelper::CreateForWebContents(web_contents);

#if defined(ENABLE_PRINTING)
#if defined(ENABLE_FULL_PRINTING)
  printing::PrintViewManager::CreateForWebContents(web_contents);
  printing::PrintPreviewMessageHandler::CreateForWebContents(web_contents);
#else
  printing::PrintViewManagerBasic::CreateForWebContents(web_contents);
#endif  // defined(ENABLE_FULL_PRINTING)
#endif  // defined(ENABLE_PRINTING)
}

apps::NativeAppWindow* ChromeAppWindowDelegate::CreateNativeAppWindow(
    apps::AppWindow* window,
    const apps::AppWindow::CreateParams& params) {
  return CreateNativeAppWindowImpl(window, params);
}

content::WebContents* ChromeAppWindowDelegate::OpenURLFromTab(
    content::BrowserContext* context,
    content::WebContents* source,
    const content::OpenURLParams& params) {
  return OpenURLFromTabInternal(context, source, params);
}

void ChromeAppWindowDelegate::AddNewContents(content::BrowserContext* context,
                                             content::WebContents* new_contents,
                                             WindowOpenDisposition disposition,
                                             const gfx::Rect& initial_pos,
                                             bool user_gesture,
                                             bool* was_blocked) {
  if (!disable_external_open_for_testing_) {
    if (!app_window_link_delegate_.get())
      app_window_link_delegate_.reset(new AppWindowLinkDelegate());
    new_contents->SetDelegate(app_window_link_delegate_.get());
    return;
  }
  chrome::ScopedTabbedBrowserDisplayer displayer(
      Profile::FromBrowserContext(context), chrome::GetActiveDesktop());
  // Force all links to open in a new tab, even if they were trying to open a
  // new window.
  disposition =
      disposition == NEW_BACKGROUND_TAB ? disposition : NEW_FOREGROUND_TAB;
  chrome::AddWebContents(displayer.browser(), NULL, new_contents, disposition,
                         initial_pos, user_gesture, was_blocked);
}

content::ColorChooser* ChromeAppWindowDelegate::ShowColorChooser(
    content::WebContents* web_contents,
    SkColor initial_color) {
  return chrome::ShowColorChooser(web_contents, initial_color);
}

void ChromeAppWindowDelegate::RunFileChooser(
    content::WebContents* tab,
    const content::FileChooserParams& params) {
  FileSelectHelper::RunFileChooser(tab, params);
}

void ChromeAppWindowDelegate::RequestMediaAccessPermission(
    content::WebContents* web_contents,
    const content::MediaStreamRequest& request,
    const content::MediaResponseCallback& callback,
    const extensions::Extension* extension) {
  MediaCaptureDevicesDispatcher::GetInstance()->ProcessMediaAccessRequest(
      web_contents, request, callback, extension);
}

int ChromeAppWindowDelegate::PreferredIconSize() {
#if defined(USE_ASH)
  return ash::kShelfPreferredSize;
#else
  return extension_misc::EXTENSION_ICON_SMALL;
#endif
}

void ChromeAppWindowDelegate::SetWebContentsBlocked(
    content::WebContents* web_contents,
    bool blocked) {
  // RenderViewHost may be NULL during shutdown.
  content::RenderViewHost* host = web_contents->GetRenderViewHost();
  if (host) {
    host->Send(new ChromeViewMsg_SetVisuallyDeemphasized(
        host->GetRoutingID(), blocked));
  }
}

bool ChromeAppWindowDelegate::IsWebContentsVisible(
    content::WebContents* web_contents) {
  return platform_util::IsVisible(web_contents->GetView()->GetNativeView());
}
<commit_msg>Activate browser window when opening new tab from a packaged app window.<commit_after>// Copyright 2014 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/apps/chrome_app_window_delegate.h"

#include "base/strings/stringprintf.h"
#include "chrome/browser/favicon/favicon_tab_helper.h"
#include "chrome/browser/file_select_helper.h"
#include "chrome/browser/media/media_capture_devices_dispatcher.h"
#include "chrome/browser/platform_util.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_tabstrip.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/scoped_tabbed_browser_displayer.h"
#include "chrome/common/render_messages.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_view.h"

#if defined(USE_ASH)
#include "ash/shelf/shelf_constants.h"
#endif

#if defined(ENABLE_PRINTING)
#if defined(ENABLE_FULL_PRINTING)
#include "chrome/browser/printing/print_preview_message_handler.h"
#include "chrome/browser/printing/print_view_manager.h"
#else
#include "chrome/browser/printing/print_view_manager_basic.h"
#endif  // defined(ENABLE_FULL_PRINTING)
#endif  // defined(ENABLE_PRINTING)

namespace {

bool disable_external_open_for_testing_ = false;

// Opens a URL with Chromium (not external browser) with the right profile.
content::WebContents* OpenURLFromTabInternal(
    content::BrowserContext* context,
    content::WebContents* source,
    const content::OpenURLParams& params) {
  // Force all links to open in a new tab, even if they were trying to open a
  // window.
  chrome::NavigateParams new_tab_params(
      static_cast<Browser*>(NULL), params.url, params.transition);
  if (params.disposition == NEW_BACKGROUND_TAB) {
    new_tab_params.disposition = NEW_BACKGROUND_TAB;
  } else {
    new_tab_params.disposition = NEW_FOREGROUND_TAB;
    new_tab_params.window_action = chrome::NavigateParams::SHOW_WINDOW;
  }

  new_tab_params.initiating_profile = Profile::FromBrowserContext(context);
  chrome::Navigate(&new_tab_params);

  return new_tab_params.target_contents;
}

// Helper class that opens a URL based on if this browser instance is the
// default system browser. If it is the default, open the URL directly instead
// of asking the system to open it.
class OpenURLFromTabBasedOnBrowserDefault
    : public ShellIntegration::DefaultWebClientObserver {
 public:
  OpenURLFromTabBasedOnBrowserDefault(content::WebContents* source,
                                      const content::OpenURLParams& params)
      : source_(source), params_(params) {}

  // Opens a URL when called with the result of if this is the default system
  // browser or not.
  virtual void SetDefaultWebClientUIState(
      ShellIntegration::DefaultWebClientUIState state) OVERRIDE {
    Profile* profile =
        Profile::FromBrowserContext(source_->GetBrowserContext());
    DCHECK(profile);
    if (!profile)
      return;
    switch (state) {
      case ShellIntegration::STATE_PROCESSING:
        break;
      case ShellIntegration::STATE_IS_DEFAULT:
        OpenURLFromTabInternal(profile, source_, params_);
        break;
      case ShellIntegration::STATE_NOT_DEFAULT:
      case ShellIntegration::STATE_UNKNOWN:
        platform_util::OpenExternal(profile, params_.url);
        break;
    }
  }

  virtual bool IsOwnedByWorker() OVERRIDE { return true; }

 private:
  content::WebContents* source_;
  const content::OpenURLParams params_;
};

}  // namespace

AppWindowLinkDelegate::AppWindowLinkDelegate() {}

AppWindowLinkDelegate::~AppWindowLinkDelegate() {}

// TODO(rockot): Add a test that exercises this code. See
// http://crbug.com/254260.
content::WebContents* AppWindowLinkDelegate::OpenURLFromTab(
    content::WebContents* source,
    const content::OpenURLParams& params) {
  if (source) {
    scoped_refptr<ShellIntegration::DefaultWebClientWorker>
        check_if_default_browser_worker =
            new ShellIntegration::DefaultBrowserWorker(
                new OpenURLFromTabBasedOnBrowserDefault(source, params));
    // Object lifetime notes: The OpenURLFromTabBasedOnBrowserDefault is owned
    // by check_if_default_browser_worker. StartCheckIsDefault() takes lifetime
    // ownership of check_if_default_browser_worker and will clean up after
    // the asynchronous tasks.
    check_if_default_browser_worker->StartCheckIsDefault();
  }
  return NULL;
}

ChromeAppWindowDelegate::ChromeAppWindowDelegate() {}

ChromeAppWindowDelegate::~ChromeAppWindowDelegate() {}

void ChromeAppWindowDelegate::DisableExternalOpenForTesting() {
  disable_external_open_for_testing_ = true;
}

void ChromeAppWindowDelegate::InitWebContents(
    content::WebContents* web_contents) {
  FaviconTabHelper::CreateForWebContents(web_contents);

#if defined(ENABLE_PRINTING)
#if defined(ENABLE_FULL_PRINTING)
  printing::PrintViewManager::CreateForWebContents(web_contents);
  printing::PrintPreviewMessageHandler::CreateForWebContents(web_contents);
#else
  printing::PrintViewManagerBasic::CreateForWebContents(web_contents);
#endif  // defined(ENABLE_FULL_PRINTING)
#endif  // defined(ENABLE_PRINTING)
}

apps::NativeAppWindow* ChromeAppWindowDelegate::CreateNativeAppWindow(
    apps::AppWindow* window,
    const apps::AppWindow::CreateParams& params) {
  return CreateNativeAppWindowImpl(window, params);
}

content::WebContents* ChromeAppWindowDelegate::OpenURLFromTab(
    content::BrowserContext* context,
    content::WebContents* source,
    const content::OpenURLParams& params) {
  return OpenURLFromTabInternal(context, source, params);
}

void ChromeAppWindowDelegate::AddNewContents(content::BrowserContext* context,
                                             content::WebContents* new_contents,
                                             WindowOpenDisposition disposition,
                                             const gfx::Rect& initial_pos,
                                             bool user_gesture,
                                             bool* was_blocked) {
  if (!disable_external_open_for_testing_) {
    if (!app_window_link_delegate_.get())
      app_window_link_delegate_.reset(new AppWindowLinkDelegate());
    new_contents->SetDelegate(app_window_link_delegate_.get());
    return;
  }
  chrome::ScopedTabbedBrowserDisplayer displayer(
      Profile::FromBrowserContext(context), chrome::GetActiveDesktop());
  // Force all links to open in a new tab, even if they were trying to open a
  // new window.
  disposition =
      disposition == NEW_BACKGROUND_TAB ? disposition : NEW_FOREGROUND_TAB;
  chrome::AddWebContents(displayer.browser(), NULL, new_contents, disposition,
                         initial_pos, user_gesture, was_blocked);
}

content::ColorChooser* ChromeAppWindowDelegate::ShowColorChooser(
    content::WebContents* web_contents,
    SkColor initial_color) {
  return chrome::ShowColorChooser(web_contents, initial_color);
}

void ChromeAppWindowDelegate::RunFileChooser(
    content::WebContents* tab,
    const content::FileChooserParams& params) {
  FileSelectHelper::RunFileChooser(tab, params);
}

void ChromeAppWindowDelegate::RequestMediaAccessPermission(
    content::WebContents* web_contents,
    const content::MediaStreamRequest& request,
    const content::MediaResponseCallback& callback,
    const extensions::Extension* extension) {
  MediaCaptureDevicesDispatcher::GetInstance()->ProcessMediaAccessRequest(
      web_contents, request, callback, extension);
}

int ChromeAppWindowDelegate::PreferredIconSize() {
#if defined(USE_ASH)
  return ash::kShelfPreferredSize;
#else
  return extension_misc::EXTENSION_ICON_SMALL;
#endif
}

void ChromeAppWindowDelegate::SetWebContentsBlocked(
    content::WebContents* web_contents,
    bool blocked) {
  // RenderViewHost may be NULL during shutdown.
  content::RenderViewHost* host = web_contents->GetRenderViewHost();
  if (host) {
    host->Send(new ChromeViewMsg_SetVisuallyDeemphasized(
        host->GetRoutingID(), blocked));
  }
}

bool ChromeAppWindowDelegate::IsWebContentsVisible(
    content::WebContents* web_contents) {
  return platform_util::IsVisible(web_contents->GetView()->GetNativeView());
}
<|endoftext|>


<commit_before>#ifndef MINIDBG_BREAKPOINT_HPP
#define MINIDBG_BREAKPOINT_HPP

#include <cstdint>
#include <sys/ptrace.h>

namespace minidbg {
    class breakpoint {
    public:
        breakpoint() = default;
        breakpoint(pid_t pid, std::intptr_t addr) : m_pid{pid}, m_addr{addr}, m_enabled{false}, m_saved_data{} {}

        void enable() {
            m_saved_data = ptrace(PTRACE_PEEKDATA, m_pid, m_addr, nullptr);
            uint64_t int3 = 0xcc;
            uint64_t data_with_int3 = ((m_saved_data & ~0xff) | int3); //set bottom two bytes to 0xcc
            ptrace(PTRACE_POKEDATA, m_pid, m_addr, data_with_int3);

            m_enabled = true;
        }

        void disable() {
            ptrace(PTRACE_POKEDATA, m_pid, m_addr, m_saved_data);
            m_enabled = false;
        }

        bool is_enabled() { return m_enabled; }

        auto get_address() -> std::intptr_t { return m_addr; }
    private:
        pid_t m_pid;
        std::intptr_t m_addr;
        bool m_enabled;
        uint64_t m_saved_data; //data which used to be at the breakpoint address
    };
}

#endif
<commit_msg>Const correctness and fix comment<commit_after>#ifndef MINIDBG_BREAKPOINT_HPP
#define MINIDBG_BREAKPOINT_HPP

#include <cstdint>
#include <sys/ptrace.h>

namespace minidbg {
    class breakpoint {
    public:
        breakpoint() = default;
        breakpoint(pid_t pid, std::intptr_t addr) : m_pid{pid}, m_addr{addr}, m_enabled{false}, m_saved_data{} {}

        void enable() {
            m_saved_data = ptrace(PTRACE_PEEKDATA, m_pid, m_addr, nullptr);
            uint64_t int3 = 0xcc;
            uint64_t data_with_int3 = ((m_saved_data & ~0xff) | int3); //set bottom byte to 0xcc
            ptrace(PTRACE_POKEDATA, m_pid, m_addr, data_with_int3);

            m_enabled = true;
        }

        void disable() {
            ptrace(PTRACE_POKEDATA, m_pid, m_addr, m_saved_data);
            m_enabled = false;
        }

        bool is_enabled() const { return m_enabled; }

        auto get_address() const -> std::intptr_t { return m_addr; }
    private:
        pid_t m_pid;
        std::intptr_t m_addr;
        bool m_enabled;
        uint64_t m_saved_data; //data which used to be at the breakpoint address
    };
}

#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/views/edit_search_engine_dialog.h"

#include "base/i18n/rtl.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/search_engines/template_url.h"
#include "chrome/browser/ui/search_engines/edit_search_engine_controller.h"
#include "googleurl/src/gurl.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "grit/ui_resources.h"
#include "ui/base/events/event.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/views/controls/image_view.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/layout/grid_layout.h"
#include "ui/views/layout/layout_constants.h"
#include "ui/views/widget/widget.h"
#include "ui/views/window/dialog_client_view.h"

using views::GridLayout;
using views::Textfield;

namespace chrome {

void EditSearchEngine(gfx::NativeWindow parent,
                      TemplateURL* template_url,
                      EditSearchEngineControllerDelegate* delegate,
                      Profile* profile) {
  EditSearchEngineDialog::Show(parent, template_url, delegate, profile);
}

}  // namespace chrome

EditSearchEngineDialog::EditSearchEngineDialog(
    TemplateURL* template_url,
    EditSearchEngineControllerDelegate* delegate,
    Profile* profile)
    : controller_(new EditSearchEngineController(template_url,
                                                 delegate,
                                                 profile)) {
  Init();
}

EditSearchEngineDialog::~EditSearchEngineDialog() {
}

// static
void EditSearchEngineDialog::Show(gfx::NativeWindow parent,
                                  TemplateURL* template_url,
                                  EditSearchEngineControllerDelegate* delegate,
                                  Profile* profile) {
  EditSearchEngineDialog* contents =
      new EditSearchEngineDialog(template_url, delegate, profile);
  // Window interprets an empty rectangle as needing to query the content for
  // the size as well as centering relative to the parent.
  views::Widget::CreateWindowWithParent(contents, parent);
  contents->GetWidget()->Show();
  contents->GetDialogClientView()->UpdateDialogButtons();
  contents->title_tf_->SelectAll(true);
  contents->title_tf_->RequestFocus();
}

ui::ModalType EditSearchEngineDialog::GetModalType() const {
  return ui::MODAL_TYPE_WINDOW;
}

string16 EditSearchEngineDialog::GetWindowTitle() const {
  return l10n_util::GetStringUTF16(controller_->template_url() ?
      IDS_SEARCH_ENGINES_EDITOR_EDIT_WINDOW_TITLE :
      IDS_SEARCH_ENGINES_EDITOR_NEW_WINDOW_TITLE);
}

bool EditSearchEngineDialog::IsDialogButtonEnabled(
    ui::DialogButton button) const {
  if (button == ui::DIALOG_BUTTON_OK) {
    return (controller_->IsKeywordValid(keyword_tf_->text()) &&
            controller_->IsTitleValid(title_tf_->text()) &&
            controller_->IsURLValid(UTF16ToUTF8(url_tf_->text())));
  }
  return true;
}

bool EditSearchEngineDialog::Cancel() {
  controller_->CleanUpCancelledAdd();
  return true;
}

bool EditSearchEngineDialog::Accept() {
  controller_->AcceptAddOrEdit(title_tf_->text(), keyword_tf_->text(),
                               UTF16ToUTF8(url_tf_->text()));
  return true;
}

void EditSearchEngineDialog::ContentsChanged(Textfield* sender,
                                             const string16& new_contents) {
  GetDialogClientView()->UpdateDialogButtons();
  UpdateImageViews();
}

bool EditSearchEngineDialog::HandleKeyEvent(
    Textfield* sender,
    const ui::KeyEvent& key_event) {
  return false;
}

void EditSearchEngineDialog::Init() {
  // Create the views we'll need.
  if (controller_->template_url()) {
    title_tf_ = CreateTextfield(controller_->template_url()->short_name(),
                                false);
    keyword_tf_ = CreateTextfield(controller_->template_url()->keyword(), true);
    url_tf_ = CreateTextfield(
        controller_->template_url()->url_ref().DisplayURL(), false);
    // We don't allow users to edit prepopulate URLs. This is done as
    // occasionally we need to update the URL of prepopulated TemplateURLs.
    url_tf_->SetReadOnly(controller_->template_url()->prepopulate_id() != 0);
  } else {
    title_tf_ = CreateTextfield(string16(), false);
    keyword_tf_ = CreateTextfield(string16(), true);
    url_tf_ = CreateTextfield(string16(), false);
  }
  title_iv_ = new views::ImageView();
  keyword_iv_ = new views::ImageView();
  url_iv_ = new views::ImageView();

  UpdateImageViews();

  const int related_x = views::kRelatedControlHorizontalSpacing;
  const int related_y = views::kRelatedControlVerticalSpacing;
  const int unrelated_y = views::kUnrelatedControlVerticalSpacing;

  // View and GridLayout take care of deleting GridLayout for us.
  GridLayout* layout = GridLayout::CreatePanel(this);
  SetLayoutManager(layout);

  // Define the structure of the layout.

  // For the buttons.
  views::ColumnSet* column_set = layout->AddColumnSet(0);
  column_set->AddPaddingColumn(1, 0);
  column_set->AddColumn(GridLayout::FILL, GridLayout::CENTER, 0,
                        GridLayout::USE_PREF, 0, 0);
  column_set->AddPaddingColumn(0, related_x);
  column_set->AddColumn(GridLayout::FILL, GridLayout::CENTER, 0,
                        GridLayout::USE_PREF, 0, 0);
  column_set->LinkColumnSizes(1, 3, -1);

  // For the Textfields.
  column_set = layout->AddColumnSet(1);
  column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 0,
                        GridLayout::USE_PREF, 0, 0);
  column_set->AddPaddingColumn(0, related_x);
  column_set->AddColumn(GridLayout::FILL, GridLayout::CENTER, 1,
                        GridLayout::USE_PREF, 0, 0);
  column_set->AddPaddingColumn(0, related_x);
  column_set->AddColumn(GridLayout::CENTER, GridLayout::CENTER, 0,
                        GridLayout::USE_PREF, 0, 0);

  // For the description.
  column_set = layout->AddColumnSet(2);
  column_set->AddColumn(GridLayout::FILL, GridLayout::CENTER, 0,
                        GridLayout::USE_PREF, 0, 0);

  // Add the contents.
  layout->StartRow(0, 1);
  layout->AddView(CreateLabel(IDS_SEARCH_ENGINES_EDITOR_DESCRIPTION_LABEL));
  layout->AddView(title_tf_);
  layout->AddView(title_iv_);

  layout->StartRowWithPadding(0, 1, 0, related_y);
  layout->AddView(CreateLabel(IDS_SEARCH_ENGINES_EDITOR_KEYWORD_LABEL));
  layout->AddView(keyword_tf_);
  layout->AddView(keyword_iv_);

  layout->StartRowWithPadding(0, 1, 0, related_y);
  layout->AddView(CreateLabel(IDS_SEARCH_ENGINES_EDITOR_URL_LABEL));
  layout->AddView(url_tf_);
  layout->AddView(url_iv_);

  // On RTL UIs (such as Arabic and Hebrew) the description text is not
  // displayed correctly since it contains the substring "%s". This substring
  // is not interpreted by the Unicode BiDi algorithm as an LTR string and
  // therefore the end result is that the following right to left text is
  // displayed: ".three two s% one" (where 'one', 'two', etc. are words in
  // Hebrew).
  //
  // In order to fix this problem we transform the substring "%s" so that it
  // is displayed correctly when rendered in an RTL context.
  layout->StartRowWithPadding(0, 2, 0, unrelated_y);
  string16 description = l10n_util::GetStringUTF16(
      IDS_SEARCH_ENGINES_EDITOR_URL_DESCRIPTION_LABEL);
  if (base::i18n::IsRTL()) {
    const string16 reversed_percent(ASCIIToUTF16("s%"));
    string16::size_type percent_index =
        description.find(ASCIIToUTF16("%s"),
                         static_cast<string16::size_type>(0));
    if (percent_index != string16::npos)
      description.replace(percent_index,
                          reversed_percent.length(),
                          reversed_percent);
  }

  views::Label* description_label = new views::Label(description);
  description_label->SetHorizontalAlignment(gfx::ALIGN_LEFT);
  layout->AddView(description_label);

  layout->AddPaddingRow(0, related_y);
}

views::Label* EditSearchEngineDialog::CreateLabel(int message_id) {
  views::Label* label =
      new views::Label(l10n_util::GetStringUTF16(message_id));
  label->SetHorizontalAlignment(gfx::ALIGN_LEFT);
  return label;
}

Textfield* EditSearchEngineDialog::CreateTextfield(const string16& text,
                                                   bool lowercase) {
  Textfield* text_field = new Textfield(
      lowercase ? Textfield::STYLE_LOWERCASE : Textfield::STYLE_DEFAULT);
  text_field->SetText(text);
  text_field->SetController(this);
  return text_field;
}

void EditSearchEngineDialog::UpdateImageViews() {
  UpdateImageView(keyword_iv_, controller_->IsKeywordValid(keyword_tf_->text()),
                  IDS_SEARCH_ENGINES_INVALID_KEYWORD_TT);
  UpdateImageView(url_iv_,
                  controller_->IsURLValid(UTF16ToUTF8(url_tf_->text())),
                  IDS_SEARCH_ENGINES_INVALID_URL_TT);
  UpdateImageView(title_iv_, controller_->IsTitleValid(title_tf_->text()),
                  IDS_SEARCH_ENGINES_INVALID_TITLE_TT);
}

void EditSearchEngineDialog::UpdateImageView(views::ImageView* image_view,
                                             bool is_valid,
                                             int invalid_message_id) {
  ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
  if (is_valid) {
    image_view->SetTooltipText(string16());
    image_view->SetImage(rb.GetImageSkiaNamed(IDR_INPUT_GOOD));
  } else {
    image_view->SetTooltipText(l10n_util::GetStringUTF16(invalid_message_id));
    image_view->SetImage(rb.GetImageSkiaNamed(IDR_INPUT_ALERT));
  }
}
<commit_msg>Remove the edit search engine dialog black border.<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/edit_search_engine_dialog.h"

#include "base/i18n/rtl.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/search_engines/template_url.h"
#include "chrome/browser/ui/search_engines/edit_search_engine_controller.h"
#include "googleurl/src/gurl.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "grit/ui_resources.h"
#include "ui/base/events/event.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/views/controls/image_view.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/layout/grid_layout.h"
#include "ui/views/layout/layout_constants.h"
#include "ui/views/widget/widget.h"
#include "ui/views/window/dialog_client_view.h"

using views::GridLayout;
using views::Textfield;

namespace chrome {

void EditSearchEngine(gfx::NativeWindow parent,
                      TemplateURL* template_url,
                      EditSearchEngineControllerDelegate* delegate,
                      Profile* profile) {
  EditSearchEngineDialog::Show(parent, template_url, delegate, profile);
}

}  // namespace chrome

EditSearchEngineDialog::EditSearchEngineDialog(
    TemplateURL* template_url,
    EditSearchEngineControllerDelegate* delegate,
    Profile* profile)
    : controller_(new EditSearchEngineController(template_url,
                                                 delegate,
                                                 profile)) {
  Init();
}

EditSearchEngineDialog::~EditSearchEngineDialog() {
}

// static
void EditSearchEngineDialog::Show(gfx::NativeWindow parent,
                                  TemplateURL* template_url,
                                  EditSearchEngineControllerDelegate* delegate,
                                  Profile* profile) {
  EditSearchEngineDialog* contents =
      new EditSearchEngineDialog(template_url, delegate, profile);
  // Window interprets an empty rectangle as needing to query the content for
  // the size as well as centering relative to the parent.
  views::DialogDelegate::CreateDialogWidget(contents, NULL, parent);
  contents->GetWidget()->Show();
  contents->GetDialogClientView()->UpdateDialogButtons();
  contents->title_tf_->SelectAll(true);
  contents->title_tf_->RequestFocus();
}

ui::ModalType EditSearchEngineDialog::GetModalType() const {
  return ui::MODAL_TYPE_WINDOW;
}

string16 EditSearchEngineDialog::GetWindowTitle() const {
  return l10n_util::GetStringUTF16(controller_->template_url() ?
      IDS_SEARCH_ENGINES_EDITOR_EDIT_WINDOW_TITLE :
      IDS_SEARCH_ENGINES_EDITOR_NEW_WINDOW_TITLE);
}

bool EditSearchEngineDialog::IsDialogButtonEnabled(
    ui::DialogButton button) const {
  if (button == ui::DIALOG_BUTTON_OK) {
    return (controller_->IsKeywordValid(keyword_tf_->text()) &&
            controller_->IsTitleValid(title_tf_->text()) &&
            controller_->IsURLValid(UTF16ToUTF8(url_tf_->text())));
  }
  return true;
}

bool EditSearchEngineDialog::Cancel() {
  controller_->CleanUpCancelledAdd();
  return true;
}

bool EditSearchEngineDialog::Accept() {
  controller_->AcceptAddOrEdit(title_tf_->text(), keyword_tf_->text(),
                               UTF16ToUTF8(url_tf_->text()));
  return true;
}

void EditSearchEngineDialog::ContentsChanged(Textfield* sender,
                                             const string16& new_contents) {
  GetDialogClientView()->UpdateDialogButtons();
  UpdateImageViews();
}

bool EditSearchEngineDialog::HandleKeyEvent(
    Textfield* sender,
    const ui::KeyEvent& key_event) {
  return false;
}

void EditSearchEngineDialog::Init() {
  // Create the views we'll need.
  if (controller_->template_url()) {
    title_tf_ = CreateTextfield(controller_->template_url()->short_name(),
                                false);
    keyword_tf_ = CreateTextfield(controller_->template_url()->keyword(), true);
    url_tf_ = CreateTextfield(
        controller_->template_url()->url_ref().DisplayURL(), false);
    // We don't allow users to edit prepopulate URLs. This is done as
    // occasionally we need to update the URL of prepopulated TemplateURLs.
    url_tf_->SetReadOnly(controller_->template_url()->prepopulate_id() != 0);
  } else {
    title_tf_ = CreateTextfield(string16(), false);
    keyword_tf_ = CreateTextfield(string16(), true);
    url_tf_ = CreateTextfield(string16(), false);
  }
  title_iv_ = new views::ImageView();
  keyword_iv_ = new views::ImageView();
  url_iv_ = new views::ImageView();

  UpdateImageViews();

  const int related_x = views::kRelatedControlHorizontalSpacing;
  const int related_y = views::kRelatedControlVerticalSpacing;
  const int unrelated_y = views::kUnrelatedControlVerticalSpacing;

  // View and GridLayout take care of deleting GridLayout for us.
  GridLayout* layout = GridLayout::CreatePanel(this);
  SetLayoutManager(layout);

  // Define the structure of the layout.

  // For the buttons.
  views::ColumnSet* column_set = layout->AddColumnSet(0);
  column_set->AddPaddingColumn(1, 0);
  column_set->AddColumn(GridLayout::FILL, GridLayout::CENTER, 0,
                        GridLayout::USE_PREF, 0, 0);
  column_set->AddPaddingColumn(0, related_x);
  column_set->AddColumn(GridLayout::FILL, GridLayout::CENTER, 0,
                        GridLayout::USE_PREF, 0, 0);
  column_set->LinkColumnSizes(1, 3, -1);

  // For the Textfields.
  column_set = layout->AddColumnSet(1);
  column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 0,
                        GridLayout::USE_PREF, 0, 0);
  column_set->AddPaddingColumn(0, related_x);
  column_set->AddColumn(GridLayout::FILL, GridLayout::CENTER, 1,
                        GridLayout::USE_PREF, 0, 0);
  column_set->AddPaddingColumn(0, related_x);
  column_set->AddColumn(GridLayout::CENTER, GridLayout::CENTER, 0,
                        GridLayout::USE_PREF, 0, 0);

  // For the description.
  column_set = layout->AddColumnSet(2);
  column_set->AddColumn(GridLayout::FILL, GridLayout::CENTER, 0,
                        GridLayout::USE_PREF, 0, 0);

  // Add the contents.
  layout->StartRow(0, 1);
  layout->AddView(CreateLabel(IDS_SEARCH_ENGINES_EDITOR_DESCRIPTION_LABEL));
  layout->AddView(title_tf_);
  layout->AddView(title_iv_);

  layout->StartRowWithPadding(0, 1, 0, related_y);
  layout->AddView(CreateLabel(IDS_SEARCH_ENGINES_EDITOR_KEYWORD_LABEL));
  layout->AddView(keyword_tf_);
  layout->AddView(keyword_iv_);

  layout->StartRowWithPadding(0, 1, 0, related_y);
  layout->AddView(CreateLabel(IDS_SEARCH_ENGINES_EDITOR_URL_LABEL));
  layout->AddView(url_tf_);
  layout->AddView(url_iv_);

  // On RTL UIs (such as Arabic and Hebrew) the description text is not
  // displayed correctly since it contains the substring "%s". This substring
  // is not interpreted by the Unicode BiDi algorithm as an LTR string and
  // therefore the end result is that the following right to left text is
  // displayed: ".three two s% one" (where 'one', 'two', etc. are words in
  // Hebrew).
  //
  // In order to fix this problem we transform the substring "%s" so that it
  // is displayed correctly when rendered in an RTL context.
  layout->StartRowWithPadding(0, 2, 0, unrelated_y);
  string16 description = l10n_util::GetStringUTF16(
      IDS_SEARCH_ENGINES_EDITOR_URL_DESCRIPTION_LABEL);
  if (base::i18n::IsRTL()) {
    const string16 reversed_percent(ASCIIToUTF16("s%"));
    string16::size_type percent_index =
        description.find(ASCIIToUTF16("%s"),
                         static_cast<string16::size_type>(0));
    if (percent_index != string16::npos)
      description.replace(percent_index,
                          reversed_percent.length(),
                          reversed_percent);
  }

  views::Label* description_label = new views::Label(description);
  description_label->SetHorizontalAlignment(gfx::ALIGN_LEFT);
  layout->AddView(description_label);

  layout->AddPaddingRow(0, related_y);
}

views::Label* EditSearchEngineDialog::CreateLabel(int message_id) {
  views::Label* label =
      new views::Label(l10n_util::GetStringUTF16(message_id));
  label->SetHorizontalAlignment(gfx::ALIGN_LEFT);
  return label;
}

Textfield* EditSearchEngineDialog::CreateTextfield(const string16& text,
                                                   bool lowercase) {
  Textfield* text_field = new Textfield(
      lowercase ? Textfield::STYLE_LOWERCASE : Textfield::STYLE_DEFAULT);
  text_field->SetText(text);
  text_field->SetController(this);
  return text_field;
}

void EditSearchEngineDialog::UpdateImageViews() {
  UpdateImageView(keyword_iv_, controller_->IsKeywordValid(keyword_tf_->text()),
                  IDS_SEARCH_ENGINES_INVALID_KEYWORD_TT);
  UpdateImageView(url_iv_,
                  controller_->IsURLValid(UTF16ToUTF8(url_tf_->text())),
                  IDS_SEARCH_ENGINES_INVALID_URL_TT);
  UpdateImageView(title_iv_, controller_->IsTitleValid(title_tf_->text()),
                  IDS_SEARCH_ENGINES_INVALID_TITLE_TT);
}

void EditSearchEngineDialog::UpdateImageView(views::ImageView* image_view,
                                             bool is_valid,
                                             int invalid_message_id) {
  ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
  if (is_valid) {
    image_view->SetTooltipText(string16());
    image_view->SetImage(rb.GetImageSkiaNamed(IDR_INPUT_GOOD));
  } else {
    image_view->SetTooltipText(l10n_util::GetStringUTF16(invalid_message_id));
    image_view->SetImage(rb.GetImageSkiaNamed(IDR_INPUT_ALERT));
  }
}
<|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include <config_category.h>
#include <string.h>
#include <string>
#include <rapidjson/document.h>

using namespace std;
using namespace rapidjson;

const char *categories = "{\"categories\": ["
	"{\"key\": \"cat1\", \"description\":\"First category\"},"
	"{\"key\": \"cat2\", \"description\":\"Second\"}]}";

const char *myCategory = "{\"description\": {"
		"\"value\": \"The FogLAMP administrative API\","
		"\"type\": \"string\","
		"\"default\": \"The FogLAMP administrative API\","
		"\"description\": \"The description of this FogLAMP service\"},"
	"\"name\": {"
		"\"value\": \"FogLAMP\","
		"\"type\": \"string\","
		"\"default\": \"FogLAMP\","
		"\"description\": \"The name of this FogLAMP service\"},"
        "\"complex\": {" \
		"\"value\": { \"first\" : \"FogLAMP\", \"second\" : \"json\" },"
		"\"type\": \"json\","
		"\"default\": {\"first\" : \"FogLAMP\", \"second\" : \"json\" },"
		"\"description\": \"A JSON configuration parameter\"}}";

const char *json = "{ \"key\" : \"test\", \"description\" : \"Test description\", "
	"\"description\" : { "
		"\"description\" : \"The description of this FogLAMP service\", "
		"\"type\" : \"string\", "
		"\"value\" : \"The FogLAMP administrative API\", "
		"\"default\" : \"The FogLAMP administrative API\" }, "
	"\"name\" : { "
		"\"description\" : \"The name of this FogLAMP service\", "
		"\"type\" : \"string\", "
		"\"value\" : \"FogLAMP\", "
		"\"default\" : \"FogLAMP\" }, "
	"\"complex\" : { "
		"\"description\" : \"A JSON configuration parameter\", "
		"\"type\" : \"json\", "
		"\"value\" : {\"first\":\"FogLAMP\",\"second\":\"json\"}, "
		"\"default\" : {\"first\":\"FogLAMP\",\"second\":\"json\"} }}";

TEST(CategoriesTest, Count)
{
	ConfigCategories confCategories(categories);
	ASSERT_EQ(2, confCategories.length());
}

TEST(CategoriesTest, Index)
{
	ConfigCategories confCategories(categories);
	const ConfigCategoryDescription *item = confCategories[0];
	ASSERT_EQ(0, item->getName().compare("cat1"));
	ASSERT_EQ(0, item->getDescription().compare("First category"));
}

TEST(CategoryTest, Construct)
{
	ConfigCategory confCategory("test", myCategory);
	ASSERT_EQ(3, confCategory.getCount());
}

TEST(CategoryTest, ExistsTest)
{
	ConfigCategory confCategory("test", myCategory);
	ASSERT_EQ(true, confCategory.itemExists("name"));
	ASSERT_EQ(false, confCategory.itemExists("non-existance"));
}

TEST(CategoryTest, getValue)
{
	ConfigCategory confCategory("test", myCategory);
	ASSERT_EQ(0, confCategory.getValue("name").compare("FogLAMP"));
}

TEST(CategoryTest, getType)
{
	ConfigCategory confCategory("test", myCategory);
	ASSERT_EQ(0, confCategory.getType("name").compare("string"));
}

TEST(CategoryTest, getDefault)
{
	ConfigCategory confCategory("test", myCategory);
	ASSERT_EQ(0, confCategory.getDefault("name").compare("FogLAMP"));
}

TEST(CategoryTest, getDescription)
{
	ConfigCategory confCategory("test", myCategory);
	ASSERT_EQ(0, confCategory.getDescription("name").compare("The name of this FogLAMP service"));
}

TEST(CategoryTest, isString)
{
	ConfigCategory confCategory("test", myCategory);
	ASSERT_EQ(true, confCategory.isString("name"));
	ASSERT_EQ(false, confCategory.isString("complex"));
}

TEST(CategoryTest, isJSON)
{
	ConfigCategory confCategory("test", myCategory);
	ASSERT_EQ(false, confCategory.isJSON("name"));
	ASSERT_EQ(true, confCategory.isJSON("complex"));
}

TEST(CategoryTest, toJSON)
{
	ConfigCategory confCategory("test", myCategory);
	confCategory.setDescription("Test description");
	ASSERT_EQ(0, confCategory.toJSON().compare(json));
}
<commit_msg>Fix unit test broken by merginf previous checkin<commit_after>#include <gtest/gtest.h>
#include <config_category.h>
#include <string.h>
#include <string>
#include <rapidjson/document.h>

using namespace std;
using namespace rapidjson;

const char *categories = "{\"categories\": ["
	"{\"key\": \"cat1\", \"description\":\"First category\"},"
	"{\"key\": \"cat2\", \"description\":\"Second\"}]}";

const char *myCategory = "{\"description\": {"
		"\"value\": \"The FogLAMP administrative API\","
		"\"type\": \"string\","
		"\"default\": \"The FogLAMP administrative API\","
		"\"description\": \"The description of this FogLAMP service\"},"
	"\"name\": {"
		"\"value\": \"FogLAMP\","
		"\"type\": \"string\","
		"\"default\": \"FogLAMP\","
		"\"description\": \"The name of this FogLAMP service\"},"
        "\"complex\": {" \
		"\"value\": { \"first\" : \"FogLAMP\", \"second\" : \"json\" },"
		"\"type\": \"json\","
		"\"default\": {\"first\" : \"FogLAMP\", \"second\" : \"json\" },"
		"\"description\": \"A JSON configuration parameter\"}}";

const char *json = "{ \"key\" : \"test\", \"description\" : \"Test description\", "
    "\"value\" : {"
	"\"description\" : { "
		"\"description\" : \"The description of this FogLAMP service\", "
		"\"type\" : \"string\", "
		"\"value\" : \"The FogLAMP administrative API\", "
		"\"default\" : \"The FogLAMP administrative API\" }, "
	"\"name\" : { "
		"\"description\" : \"The name of this FogLAMP service\", "
		"\"type\" : \"string\", "
		"\"value\" : \"FogLAMP\", "
		"\"default\" : \"FogLAMP\" }, "
	"\"complex\" : { "
		"\"description\" : \"A JSON configuration parameter\", "
		"\"type\" : \"json\", "
		"\"value\" : {\"first\":\"FogLAMP\",\"second\":\"json\"}, "
		"\"default\" : {\"first\":\"FogLAMP\",\"second\":\"json\"} }} }";

TEST(CategoriesTest, Count)
{
	ConfigCategories confCategories(categories);
	ASSERT_EQ(2, confCategories.length());
}

TEST(CategoriesTest, Index)
{
	ConfigCategories confCategories(categories);
	const ConfigCategoryDescription *item = confCategories[0];
	ASSERT_EQ(0, item->getName().compare("cat1"));
	ASSERT_EQ(0, item->getDescription().compare("First category"));
}

TEST(CategoryTest, Construct)
{
	ConfigCategory confCategory("test", myCategory);
	ASSERT_EQ(3, confCategory.getCount());
}

TEST(CategoryTest, ExistsTest)
{
	ConfigCategory confCategory("test", myCategory);
	ASSERT_EQ(true, confCategory.itemExists("name"));
	ASSERT_EQ(false, confCategory.itemExists("non-existance"));
}

TEST(CategoryTest, getValue)
{
	ConfigCategory confCategory("test", myCategory);
	ASSERT_EQ(0, confCategory.getValue("name").compare("FogLAMP"));
}

TEST(CategoryTest, getType)
{
	ConfigCategory confCategory("test", myCategory);
	ASSERT_EQ(0, confCategory.getType("name").compare("string"));
}

TEST(CategoryTest, getDefault)
{
	ConfigCategory confCategory("test", myCategory);
	ASSERT_EQ(0, confCategory.getDefault("name").compare("FogLAMP"));
}

TEST(CategoryTest, getDescription)
{
	ConfigCategory confCategory("test", myCategory);
	ASSERT_EQ(0, confCategory.getDescription("name").compare("The name of this FogLAMP service"));
}

TEST(CategoryTest, isString)
{
	ConfigCategory confCategory("test", myCategory);
	ASSERT_EQ(true, confCategory.isString("name"));
	ASSERT_EQ(false, confCategory.isString("complex"));
}

TEST(CategoryTest, isJSON)
{
	ConfigCategory confCategory("test", myCategory);
	ASSERT_EQ(false, confCategory.isJSON("name"));
	ASSERT_EQ(true, confCategory.isJSON("complex"));
}

TEST(CategoryTest, toJSON)
{
	ConfigCategory confCategory("test", myCategory);
	confCategory.setDescription("Test description");
	ASSERT_EQ(0, confCategory.toJSON().compare(json));
}
<|endoftext|>


<commit_before>#include <MutilaDebug.h>
#include <stdint.h>
#include <string.h>
#include "PowerMode.h"
#include "Matrix.h"
#include "Config.h"
#include "Settings.h"

PowerMode_ PowerMode;

PowerMode_::PowerMode_() :
    lastPlot(0),
    graphPos(0),
    maxSincePlot(0)
{
    clearGraph();
}

void PowerMode_::start(const char* data)
{
    DB(F("PowerMode::start "));
    DBLN(data);
    String s = data;
    // strip trailing '-' characters
    s.replace("-", "");
    Matrix.clear();
    // TODO: determine if we need to clear the graph - if we have had no value for some number of seconds

    // Update maxSincePlot
    if (s.toInt() > maxSincePlot) {
        maxSincePlot = s.toInt();
    }

    // Plot the graph if we need to
    if (millis() >= lastPlot + GRAPH_PLOT_MS) {
        lastPlot = millis();
        plotGraph();
    }

    writeValue(s.toInt());
    Matrix.paint();
}

void PowerMode_::writeValue(uint32_t tenthsWatt)
{
    // Work out width in pixels of whole part text
    uint16_t wholePart = tenthsWatt/10;
    uint8_t wholePartWidth = wholePart == 0 ? otherWidth+1 : 0;
    for (uint16_t i=wholePart; i>0; i/=10) {
        wholePartWidth += (i%10==1) ? oneWidth : otherWidth;
        wholePartWidth++;
    }

    Matrix.setFont(fontSize);
    // Write the whole part
    Matrix.text(MATRIX_GREEN, xpos - wholePartWidth, ypos, String(wholePart));
    // Draw the decimal point
    Matrix.rectangle(MATRIX_GREEN, xpos, ypos, 2, 2);
    // Write the fractional part (1 d.p.)
    Matrix.text(MATRIX_GREEN, xpos+3, ypos, String(tenthsWatt%10));
    // Write the units symbol (Watts)
    Matrix.text(MATRIX_GREEN, xpos+otherWidth+4, ypos, "W");
}

void PowerMode_::update()
{
}

void PowerMode_::clearGraph()
{
    DBLN(F("PowerMode::clearGraph"));
    memset((void*)graphData, 0, sizeof(uint32_t)*GRAPH_DATA_ITEMS);
}

void PowerMode_::plotGraph()
{
    DB(F("PowerMode::plotGraph 10ths="));
    DBLN(maxSincePlot);
    // Add a value to the graph data & change the pointer
    graphData[graphPos] = maxSincePlot;
    // Incremement the pointer
    graphPos = (graphPos+1)%GRAPH_DATA_ITEMS;

    // Plot up to the pointer
    int8_t idx = graphPos;
    for (uint8_t i=0; i<GRAPH_DATA_ITEMS; i++) {
        idx = idx == 0 ? GRAPH_DATA_ITEMS-1 : idx-1;
        // get the index in the graph in reverse chronological order (most recent first)
        uint8_t height = (graphData[idx]*MATRIX_SIZE_Y)/(10*MaxPowerWatts.get());
        DB(F("PLOT idx="));
        DB(idx);
        DB(F(" 10ths="));
        DB(graphData[idx]);
        DB(F(" max="));
        DB(MaxPowerWatts.get());
        DB(F(" height="));
        DBLN(height);
        if (graphData[idx]>0) {
            Matrix.line(MATRIX_RED, MATRIX_SIZE_X-i-1, MATRIX_SIZE_Y-1, MATRIX_SIZE_X-i-1, MATRIX_SIZE_Y-1-height);
        }
    }
    maxSincePlot = 0;
}

<commit_msg>prevent wrap with high graphs<commit_after>#include <MutilaDebug.h>
#include <stdint.h>
#include <string.h>
#include "PowerMode.h"
#include "Matrix.h"
#include "Config.h"
#include "Settings.h"

PowerMode_ PowerMode;

PowerMode_::PowerMode_() :
    lastPlot(0),
    graphPos(0),
    maxSincePlot(0)
{
    clearGraph();
}

void PowerMode_::start(const char* data)
{
    DB(F("PowerMode::start "));
    DBLN(data);
    String s = data;
    // strip trailing '-' characters
    s.replace("-", "");
    Matrix.clear();
    // TODO: determine if we need to clear the graph - if we have had no value for some number of seconds

    // Update maxSincePlot
    if (s.toInt() > maxSincePlot) {
        maxSincePlot = s.toInt();
    }

    // Plot the graph if we need to
    if (millis() >= lastPlot + GRAPH_PLOT_MS) {
        lastPlot = millis();
        plotGraph();
    }

    writeValue(s.toInt());
    Matrix.paint();
}

void PowerMode_::writeValue(uint32_t tenthsWatt)
{
    // Work out width in pixels of whole part text
    uint16_t wholePart = tenthsWatt/10;
    uint8_t wholePartWidth = wholePart == 0 ? otherWidth+1 : 0;
    for (uint16_t i=wholePart; i>0; i/=10) {
        wholePartWidth += (i%10==1) ? oneWidth : otherWidth;
        wholePartWidth++;
    }

    Matrix.setFont(fontSize);
    // Write the whole part
    Matrix.text(MATRIX_GREEN, xpos - wholePartWidth, ypos, String(wholePart));
    // Draw the decimal point
    Matrix.rectangle(MATRIX_GREEN, xpos, ypos, 2, 2);
    // Write the fractional part (1 d.p.)
    Matrix.text(MATRIX_GREEN, xpos+3, ypos, String(tenthsWatt%10));
    // Write the units symbol (Watts)
    Matrix.text(MATRIX_GREEN, xpos+otherWidth+4, ypos, "W");
}

void PowerMode_::update()
{
}

void PowerMode_::clearGraph()
{
    DBLN(F("PowerMode::clearGraph"));
    memset((void*)graphData, 0, sizeof(uint32_t)*GRAPH_DATA_ITEMS);
}

void PowerMode_::plotGraph()
{
    DB(F("PowerMode::plotGraph 10ths="));
    DBLN(maxSincePlot);
    // Add a value to the graph data & change the pointer
    graphData[graphPos] = maxSincePlot;
    // Incremement the pointer
    graphPos = (graphPos+1)%GRAPH_DATA_ITEMS;

    // Plot up to the pointer
    int8_t idx = graphPos;
    for (uint8_t i=0; i<GRAPH_DATA_ITEMS; i++) {
        idx = idx == 0 ? GRAPH_DATA_ITEMS-1 : idx-1;
        // get the index in the graph in reverse chronological order (most recent first)
        uint8_t height = (graphData[idx]*MATRIX_SIZE_Y)/(10*MaxPowerWatts.get());
        DB(F("PLOT idx="));
        DB(idx);
        DB(F(" 10ths="));
        DB(graphData[idx]);
        DB(F(" max="));
        DB(MaxPowerWatts.get());
        DB(F(" height="));
        DBLN(height);
        if (graphData[idx]>0) {
            Matrix.line(MATRIX_RED, MATRIX_SIZE_X-i-1, MATRIX_SIZE_Y-1, MATRIX_SIZE_X-i-1, height < MATRIX_SIZE_Y ? MATRIX_SIZE_Y-1-height : 0);
        }
    }
    maxSincePlot = 0;
}

<|endoftext|>


<commit_before>/*
 * @file node.hpp
 *
 * @brief Ellis node public C++ header.
 *
 */

#pragma once
#ifndef ELLIS_NODE_HPP_
#define ELLIS_NODE_HPP_

#include <ellis/type.hpp>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include <vector>

namespace ellis {

/* Forward declaration. */
class array_node;
class binary_node;
class map_node;
struct prize_blk;

/* TODO: steal/adapt doxygen documentation from the C headers */
/* TODO: name the variables in the function prototypes */

/** node is an in-memory generic hierarchical node that can represent a
 * map, array, integer, or string, etc, corresponding to a hierarchical object
 * expressed in a variety of formats, such as XML, JSON, BSON, or msgpack.
 *
 * It is intended as a convenient interoperable in-memory object (representing
 * unpacked data received from network or disk in some serialized form), and
 * for general purpose conveyance between functions in a program after having
 * been received.  For example, a server might receive an node using one
 * serialization format, modify the node, store it into a queue, and
 * then send it elsewhere in a completely different format.
 *
 * This object has ref-counted copy-on-write semantics--if you make a copy,
 * then the reference count of the source will be incremented, but if you
 * then modify the copy, then an actual copy will occur at the given node,
 * with new reference count equal to one, and the original reference count
 * will decrease.
 */
class node {

  using pad_t = char[8];  /* pad covers union--checked via static_assert */
  union {
    bool m_boo;
    double m_dbl;
    int64_t m_int;
    std::string m_str;
    prize_blk *m_blk;
    pad_t m_pad;
  };
  unsigned int m_type;

  /* Private methods--see implementation for description. */
  void _zap_contents(type t);
  void _grab_contents(const node &other);
  void _release_contents();
  void _prep_for_write();
  bool & _as_mutable_bool();
  const bool & _as_bool() const;
  int64_t & _as_mutable_int64();
  const int64_t & _as_int64() const;
  double & _as_mutable_double();
  // TODO: remove this const as well? no! but still, rename for _const_as.
  const double & _as_double() const;
  std::string & _as_mutable_u8str();
  const std::string & _as_u8str() const;
  array_node & _as_mutable_array();
  const array_node & _as_array() const;
  map_node & _as_mutable_map();
  const map_node & _as_map() const;
  binary_node & _as_mutable_binary();
  const binary_node & _as_binary() const;

 public:

  /*   ____                _                   _
   *  / ___|___  _ __  ___| |_ _ __ _   _  ___| |_ ___  _ __ ___
   * | |   / _ \| '_ \/ __| __| '__| | | |/ __| __/ _ \| '__/ __|
   * | |__| (_) | | | \__ \ |_| |  | |_| | (__| || (_) | |  \__ \
   *  \____\___/|_| |_|___/\__|_|   \__,_|\___|\__\___/|_|  |___/
   *
   */

  // TODO: experiment re safety w/o explicit constructors

  /** Construct an ARRAY, MAP, or NIL node. */
  node(type);

  /** Construct a BINARY node. */
  node(const uint8_t *mem, size_t bytes);

  /** Construct a BOOL node. */
  node(bool);

  /** Construct an INT64 node. */
  node(int);

  /** Construct an INT64 node. */
  node(int64_t);

  /** Construct an INT64 node. */
  node(unsigned int);

  /** Construct an INT64 node. */
  node(uint64_t);

  /** Construct a DOUBLE node. */
  node(double);

  /** Construct a U8STR node. */
  node(const std::string&);

  /** Construct a U8STR node. */
  node(const char *);

  /** Copy constructor.
   *
   * Shares contents by incrementing ref count.  Contents are subject to
   * copy on write, until refcount goes down to 1 again. */
  node(const node& other);

  /** Move constructor.
   *
   * Steals contents, without changing ref count.  Other no longer has a
   * reference count, and will not affect the contents when deleted. */
  node(node&& other);

  /*  ____            _                   _
   * |  _ \  ___  ___| |_ _ __ _   _  ___| |_ ___  _ __
   * | | | |/ _ \/ __| __| '__| | | |/ __| __/ _ \| '__|
   * | |_| |  __/\__ \ |_| |  | |_| | (__| || (_) | |
   * |____/ \___||___/\__|_|   \__,_|\___|\__\___/|_|
   *
   */

  void release();
  ~node();

  void swap(node &other);

  /** Do a deep copy of the other node--new objects, new reference counter,
   * no sharing.
   *
   * The "other" node is allowed to be this very node; copy-on-write does this.
   */
  void deep_copy(const node &other);

  /*   ___                       _
   *  / _ \ _ __   ___ _ __ __ _| |_ ___  _ __ ___
   * | | | | '_ \ / _ \ '__/ _` | __/ _ \| '__/ __|
   * | |_| | |_) |  __/ | | (_| | || (_) | |  \__ \
   *  \___/| .__/ \___|_|  \__,_|\__\___/|_|  |___/
   *       |_|
   */

  /** Copy assignment operator.
   *
   * Shares the RHS's contents via COW, as in copy constructor.
   *
   * Any prior contents of this node are lost (refcount decremented).
   */
  node& operator=(const node& rhs);
  node& operator=(bool o);
  node& operator=(double o);
  node& operator=(int o);
  node& operator=(unsigned int o);
  node& operator=(int64_t o);
  node& operator=(const char *o);
  node& operator=(const std::string &o);

  /** Move assignment operator.
   *
   * Steals the RHS's contents, as in move constructor.
   *
   * Any prior contents of this node are lost (refcount decremented).
   */
  node& operator=(node&& rhs);

  /** Equality operator.
   *
   * Equality is defined as one might expect--types same, simple values same,
   * array sizes and elements same, map keys and values same.
   *
   * Note that we also define not equal operator, but we do not define
   * lesser/greater operators since there is not a clear scheme for ordering
   * at this time.
   */
  bool operator==(const node &) const;
  bool operator==(bool o) const;
  bool operator==(double o) const;
  bool operator==(int o) const;
  bool operator==(unsigned int o) const;
  bool operator==(int64_t o) const;
  bool operator==(const char *o) const;
  bool operator==(const std::string &o) const;

  /** Inequality operator.
   *
   * Same as (not (a==b)).
   */
  bool operator!=(const node &o) const;
  bool operator!=(bool o) const;
  bool operator!=(double o) const;
  bool operator!=(int o) const;
  bool operator!=(unsigned int o) const;
  bool operator!=(int64_t o) const;
  bool operator!=(const char *o) const;
  bool operator!=(const std::string &o) const;

  /*  _____
   * |_   _|   _ _ __   ___
   *   | || | | | '_ \ / _ \
   *   | || |_| | |_) |  __/
   *   |_| \__, | .__/ \___|
   *       |___/|_|
   */

  /** Check whether this node is of type t. */
  bool is_type(type t) const;

  /** Return the type of this node. */
  type get_type() const;

  /*   ____            _             _
   *  / ___|___  _ __ | |_ ___ _ __ | |_ ___
   * | |   / _ \| '_ \| __/ _ \ '_ \| __/ __|
   * | |__| (_) | | | | ||  __/ | | | |_\__ \
   *  \____\___/|_| |_|\__\___|_| |_|\__|___/
   *
   */

  /** Get contents as an bool.
   *
   * Will throw WRONG_TYPE error if type is not convertible.
   */
  explicit operator bool() const;
  bool & as_mutable_bool();
  const bool & as_bool() const;

  /** Get contents as an int64_t.
   *
   * Will throw WRONG_TYPE error if type is not convertible.
   */
  explicit operator int() const;
  explicit operator unsigned int() const;
  explicit operator int64_t() const;
  explicit operator uint64_t() const;
  int64_t & as_mutable_int64();
  const int64_t & as_int64() const;

  /** Get contents as a double.
   *
   * Will throw WRONG_TYPE error if type is not convertible.
   */
  explicit operator double() const;
  double & as_mutable_double();
  const double & as_double() const;

  /** Provide access to UTF-8 string contents.
   *
   * Will throw WRONG_TYPE error if type is not U8STR.
   */
  std::string & as_mutable_u8str();
  const std::string & as_u8str() const;

  /** Provide access to array functionality.
   *
   * See array_node.hpp for more information.
   *
   * Will throw WRONG_TYPE error if type is not ARRAY.
   */
  array_node & as_mutable_array();
  const array_node & as_array() const;

  /** Provide access to map functionality.
   *
   * See map_node.hpp for more information.
   *
   * Will throw WRONG_TYPE error if type is not MAP.
   */
  map_node & as_mutable_map();
  const map_node & as_map() const;

  /** Provide access to binary blob contents.
   *
   * See binary_node.hpp for more information.
   *
   * Will throw WRONG_TYPE error if type is not BINARY.
   */
  binary_node & as_mutable_binary();
  const binary_node & as_binary() const;

  /** Get value from tree at given path (e.g. "{log}{handlers}[0]{sync}").
   */
  node & at_path_mutable(const std::string &path);
  const node & at_path(const std::string &path) const;

  friend class array_node;
  friend class binary_node;
  friend class map_node;
};

namespace prize_types {
  using arr_t = std::vector<node>;
  using map_t = std::unordered_map<std::string, node>;
  using bin_t = std::vector<uint8_t>;
  using refcount_t = unsigned;
}

struct prize_blk {
  prize_types::refcount_t m_refcount;
  union {
    prize_types::arr_t m_arr;
    prize_types::map_t m_map;
    prize_types::bin_t m_bin;
  };
};

/*  ___          _
 * |_ _|___  ___| |_ _ __ ___  __ _ _ __ ___
 *  | |/ _ \/ __| __| '__/ _ \/ _` | '_ ` _ \
 *  | | (_) \__ \ |_| | |  __/ (_| | | | | | |
 * |___\___/|___/\__|_|  \___|\__,_|_| |_| |_|
 *
 *   ___                       _
 *  / _ \ _ __   ___ _ __ __ _| |_ ___  _ __ ___
 * | | | | '_ \ / _ \ '__/ _` | __/ _ \| '__/ __|
 * | |_| | |_) |  __/ | | (_| | || (_) | |  \__ \
 *  \___/| .__/ \___|_|  \__,_|\__\___/|_|  |___/
 *       |_|
 */

std::ostream & operator<<(std::ostream & os, const node & v);
std::istream & operator>>(std::istream & is, node & v);

}  /* namespace ellis */

#endif  /* ELLIS_NODE_HPP_ */
<commit_msg>refactorizin<commit_after>/*
 * @file node.hpp
 *
 * @brief Ellis node public C++ header.
 *
 */

#pragma once
#ifndef ELLIS_NODE_HPP_
#define ELLIS_NODE_HPP_

#include <ellis/type.hpp>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include <vector>

namespace ellis {

/* Forward declaration. */
class array_node;
class binary_node;
class map_node;
struct prize_blk;

/* TODO: steal/adapt doxygen documentation from the C headers */
/* TODO: name the variables in the function prototypes */

/** node is an in-memory generic hierarchical node that can represent a
 * map, array, integer, or string, etc, corresponding to a hierarchical object
 * expressed in a variety of formats, such as XML, JSON, BSON, or msgpack.
 *
 * It is intended as a convenient interoperable in-memory object (representing
 * unpacked data received from network or disk in some serialized form), and
 * for general purpose conveyance between functions in a program after having
 * been received.  For example, a server might receive an node using one
 * serialization format, modify the node, store it into a queue, and
 * then send it elsewhere in a completely different format.
 *
 * This object has ref-counted copy-on-write semantics--if you make a copy,
 * then the reference count of the source will be incremented, but if you
 * then modify the copy, then an actual copy will occur at the given node,
 * with new reference count equal to one, and the original reference count
 * will decrease.
 */
class node {

  using pad_t = char[8];  /* pad covers union--checked via static_assert */
  union {
    bool m_boo;
    double m_dbl;
    int64_t m_int;
    std::string m_str;
    prize_blk *m_blk;
    pad_t m_pad;
  };
  unsigned int m_type;

  /* Private methods--see implementation for description. */
  void _zap_contents(type t);
  void _grab_contents(const node &other);
  void _release_contents();
  void _prep_for_write();
  const bool        & _as_bool() const;
  const int64_t     & _as_int64() const;
  const double      & _as_double() const;
  const std::string & _as_u8str() const;
  const array_node  & _as_array() const;
  const map_node    & _as_map() const;
  const binary_node & _as_binary() const;
  bool        & _as_mutable_bool();
  int64_t     & _as_mutable_int64();
  double      & _as_mutable_double();
  std::string & _as_mutable_u8str();
  array_node  & _as_mutable_array();
  map_node    & _as_mutable_map();
  binary_node & _as_mutable_binary();

 public:

  /*   ____                _                   _
   *  / ___|___  _ __  ___| |_ _ __ _   _  ___| |_ ___  _ __ ___
   * | |   / _ \| '_ \/ __| __| '__| | | |/ __| __/ _ \| '__/ __|
   * | |__| (_) | | | \__ \ |_| |  | |_| | (__| || (_) | |  \__ \
   *  \____\___/|_| |_|___/\__|_|   \__,_|\___|\__\___/|_|  |___/
   *
   */

  // TODO: experiment re safety w/o explicit constructors

  /** Construct an ARRAY, MAP, or NIL node. */
  node(type);

  /** Construct a BINARY node. */
  node(const uint8_t *mem, size_t bytes);

  /** Construct a BOOL node. */
  node(bool);

  /** Construct an INT64 node. */
  node(int);

  /** Construct an INT64 node. */
  node(int64_t);

  /** Construct an INT64 node. */
  node(unsigned int);

  /** Construct an INT64 node. */
  node(uint64_t);

  /** Construct a DOUBLE node. */
  node(double);

  /** Construct a U8STR node. */
  node(const std::string&);

  /** Construct a U8STR node. */
  node(const char *);

  /** Copy constructor.
   *
   * Shares contents by incrementing ref count.  Contents are subject to
   * copy on write, until refcount goes down to 1 again. */
  node(const node& other);

  /** Move constructor.
   *
   * Steals contents, without changing ref count.  Other no longer has a
   * reference count, and will not affect the contents when deleted. */
  node(node&& other);

  /*  ____            _                   _
   * |  _ \  ___  ___| |_ _ __ _   _  ___| |_ ___  _ __
   * | | | |/ _ \/ __| __| '__| | | |/ __| __/ _ \| '__|
   * | |_| |  __/\__ \ |_| |  | |_| | (__| || (_) | |
   * |____/ \___||___/\__|_|   \__,_|\___|\__\___/|_|
   *
   */

  /** TODO: is this supposed to be related to _release_contents() and if
   * so why public?  Unimplemented.  Remove unless there is a purpose. */
  void release();

  ~node();

  /** Swap the contents of this node and the other. */
  void swap(node &other);

  /** Do a deep copy of the other node--new objects, new reference counter,
   * no sharing.
   *
   * The "other" node is allowed to be this very node; copy-on-write uses
   * this scenario to move self away from the original copy.
   */
  void deep_copy(const node &other);

  /*   ___                       _
   *  / _ \ _ __   ___ _ __ __ _| |_ ___  _ __ ___
   * | | | | '_ \ / _ \ '__/ _` | __/ _ \| '__/ __|
   * | |_| | |_) |  __/ | | (_| | || (_) | |  \__ \
   *  \___/| .__/ \___|_|  \__,_|\__\___/|_|  |___/
   *       |_|
   */

  /** Copy assignment operator.
   *
   * Shares the RHS's contents via COW, as in copy constructor.
   *
   * Any prior contents of this node are lost (refcount decremented).
   */
  node& operator=(const node& rhs);

  /** Move assignment operator.
   *
   * Steals the RHS's contents, as in move constructor.
   *
   * Any prior contents of this node are lost (refcount decremented).
   */
  node& operator=(node&& rhs);

  /** Assignment operators from primitive types.
   *
   * Any prior contents of this node are lost (refcount decremented).
   */
  node& operator=(bool o);
  node& operator=(double o);
  node& operator=(int o);
  node& operator=(unsigned int o);
  node& operator=(int64_t o);
  node& operator=(const char *o);
  node& operator=(const std::string &o);

  /** Comparison operators for another node.
   *
   * Equality is defined as one might expect--types same, simple values same,
   * array sizes and elements same, map keys and values same.
   *
   * Note that we define the not equal operator, but we do not define
   * lesser/greater operators since there is not a clear scheme for ordering
   * at this time.
   */
  bool operator==(const node &) const;
  bool operator!=(const node &o) const;

  /** Comparison operators for primitive types.
   *
   * This implicitly verifies the type, e.g.:
   *
   *   mynode == 4.5
   *
   * Is equivalent to:
   *
   *   mynode.as_double() == 4.5
   *
   * This means that an exception can be thrown if the type is incorrect,
   * as is the case with the as_xxx() converter functions.
   */
  bool operator==(bool o) const;
  bool operator==(double o) const;
  bool operator==(int o) const;
  bool operator==(unsigned int o) const;
  bool operator==(int64_t o) const;
  bool operator==(const char *o) const;
  bool operator==(const std::string &o) const;

  /** Inequality operators for primitive types.
   *
   * Same as (not (a==b)).
   */
  bool operator!=(bool o) const;
  bool operator!=(double o) const;
  bool operator!=(int o) const;
  bool operator!=(unsigned int o) const;
  bool operator!=(int64_t o) const;
  bool operator!=(const char *o) const;
  bool operator!=(const std::string &o) const;

  /** Typecasting operators for primitive types.
   *
   * These are convenience wrappers.  For example:
   *
   *   (bool)mynode
   *
   * is equivalent to:
   *
   *   mynode.as_bool()
   *
   * This means that an exception can be thrown if the type is incorrect,
   * as is the case with the as_xxx() converter functions.
   */
  explicit operator bool() const;
  explicit operator int() const;
  explicit operator unsigned int() const;
  explicit operator int64_t() const;
  explicit operator uint64_t() const;
  explicit operator double() const;
  explicit operator std::string() const;
  explicit operator const char *() const;

  /*  _____
   * |_   _|   _ _ __   ___
   *   | || | | | '_ \ / _ \
   *   | || |_| | |_) |  __/
   *   |_| \__, | .__/ \___|
   *       |___/|_|
   */

  /** Check whether this node is of type t. */
  bool is_type(type t) const;

  /** Return the type of this node. */
  type get_type() const;

  /*   ____            _             _
   *  / ___|___  _ __ | |_ ___ _ __ | |_ ___
   * | |   / _ \| '_ \| __/ _ \ '_ \| __/ __|
   * | |__| (_) | | | | ||  __/ | | | |_\__ \
   *  \____\___/|_| |_|\__\___|_| |_|\__|___/
   *
   */

  /** Get contents as an bool.
   *
   * Will throw WRONG_TYPE error if type is not convertible.
   */
  const bool & as_bool() const;

  /** Get contents as an int64_t.
   *
   * Will throw WRONG_TYPE error if type is not convertible.
   */
  const int64_t & as_int64() const;

  /** Get contents as a double.
   *
   * Will throw WRONG_TYPE error if type is not convertible.
   */
  const double & as_double() const;

  /** Provide access to UTF-8 string contents.
   *
   * Will throw WRONG_TYPE error if type is not U8STR.
   */
  const std::string & as_u8str() const;
  const char * as_u8cstr() const;

  /** Provide access to array functionality.
   *
   * See array_node.hpp for more information.
   *
   * Will throw WRONG_TYPE error if type is not ARRAY.
   */
  const array_node & as_array() const;

  /** Provide access to map functionality.
   *
   * See map_node.hpp for more information.
   *
   * Will throw WRONG_TYPE error if type is not MAP.
   */
  const map_node & as_map() const;

  /** Provide access to binary blob contents.
   *
   * See binary_node.hpp for more information.
   *
   * Will throw WRONG_TYPE error if type is not BINARY.
   */
  const binary_node & as_binary() const;

  /** Get value from tree at given path (e.g. "{log}{handlers}[0]{sync}").
   */
  const node & at_path(const std::string &path) const;

  /** Mutable access to contents.
   *
   * Similar to immutable versions above, including type exceptions,
   * but the return value can be modified and the node will be updated.
   *
   * NOTE: since we don't have an easy hook for when you change the given
   * double pointer/reference, the copy-on-write logic is initiated as soon
   * as you request mutable access, even if you don't actually change it.
   */
  bool        & as_mutable_bool();
  int64_t     & as_mutable_int64();
  double      & as_mutable_double();
  std::string & as_mutable_u8str();
  array_node  & as_mutable_array();
  map_node    & as_mutable_map();
  binary_node & as_mutable_binary();
  node & at_path_mutable(const std::string &path);

  friend class array_node;
  friend class binary_node;
  friend class map_node;
};

namespace prize_types {
  using arr_t = std::vector<node>;
  using map_t = std::unordered_map<std::string, node>;
  using bin_t = std::vector<uint8_t>;
  using refcount_t = unsigned;
}

struct prize_blk {
  prize_types::refcount_t m_refcount;
  union {
    prize_types::arr_t m_arr;
    prize_types::map_t m_map;
    prize_types::bin_t m_bin;
  };
};

/*  ___          _
 * |_ _|___  ___| |_ _ __ ___  __ _ _ __ ___
 *  | |/ _ \/ __| __| '__/ _ \/ _` | '_ ` _ \
 *  | | (_) \__ \ |_| | |  __/ (_| | | | | | |
 * |___\___/|___/\__|_|  \___|\__,_|_| |_| |_|
 *
 *   ___                       _
 *  / _ \ _ __   ___ _ __ __ _| |_ ___  _ __ ___
 * | | | | '_ \ / _ \ '__/ _` | __/ _ \| '__/ __|
 * | |_| | |_) |  __/ | | (_| | || (_) | |  \__ \
 *  \___/| .__/ \___|_|  \__,_|\__\___/|_|  |___/
 *       |_|
 */

std::ostream & operator<<(std::ostream & os, const node & v);
std::istream & operator>>(std::istream & is, node & v);

}  /* namespace ellis */

#endif  /* ELLIS_NODE_HPP_ */
<|endoftext|>