<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/views/options/content_page_view.h"

#include <windows.h>
#include <shlobj.h>
#include <vsstyle.h>
#include <vssym32.h>

#include "app/gfx/canvas.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/command_line.h"
#include "base/gfx/native_theme.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/views/clear_browsing_data.h"
#include "chrome/browser/views/importer_view.h"
#include "chrome/browser/views/options/options_group_view.h"
#include "chrome/browser/views/options/passwords_exceptions_window_view.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "grit/generated_resources.h"
#include "views/controls/button/radio_button.h"
#include "views/grid_layout.h"
#include "views/standard_layout.h"
#include "views/widget/widget.h"

namespace {

const int kPopupBlockingRadioGroup = 1;
const int kPasswordSavingRadioGroup = 2;
}  // namespace

ContentPageView::ContentPageView(Profile* profile)
    : passwords_exceptions_button_(NULL),
      passwords_group_(NULL),
      passwords_asktosave_radio_(NULL),
      passwords_neversave_radio_(NULL),
      themes_group_(NULL),
      themes_reset_button_(NULL),
      import_group_(NULL),
      import_label_(NULL),
      import_button_(NULL),
      clear_data_group_(NULL),
      clear_data_label_(NULL),
      clear_data_button_(NULL),
      OptionsPageView(profile) {
}

ContentPageView::~ContentPageView() {
}

///////////////////////////////////////////////////////////////////////////////
// ContentPageView, views::ButtonListener implementation:

void ContentPageView::ButtonPressed(views::Button* sender) {
  if (sender == passwords_asktosave_radio_ ||
      sender == passwords_neversave_radio_) {
    bool enabled = passwords_asktosave_radio_->checked();
    if (enabled) {
      UserMetricsRecordAction(L"Options_PasswordManager_Enable",
                              profile()->GetPrefs());
    } else {
      UserMetricsRecordAction(L"Options_PasswordManager_Disable",
                              profile()->GetPrefs());
    }
    ask_to_save_passwords_.SetValue(enabled);
  } else if (sender == passwords_exceptions_button_) {
    UserMetricsRecordAction(L"Options_ShowPasswordsExceptions", NULL);
    PasswordsExceptionsWindowView::Show(profile());
  } else if (sender == form_autofill_checkbox_) {
    bool enabled = form_autofill_checkbox_->checked();
    if (enabled) {
      UserMetricsRecordAction(L"Options_FormAutofill_Enable",
                              profile()->GetPrefs());
    } else {
      UserMetricsRecordAction(L"Options_FormAutofill_Disable",
                              profile()->GetPrefs());
    }
    form_autofill_.SetValue(enabled);
  } else if (sender == themes_reset_button_) {
    UserMetricsRecordAction(L"Options_ThemesReset", profile()->GetPrefs());
    profile()->ClearTheme();
  } else if (sender == import_button_) {
    views::Window::CreateChromeWindow(
      GetWindow()->GetNativeWindow(),
      gfx::Rect(),
      new ImporterView(profile()))->Show();
  } else if (sender == clear_data_button_) {
    views::Window::CreateChromeWindow(
      GetWindow()->GetNativeWindow(),
      gfx::Rect(),
      new ClearBrowsingDataView(profile()))->Show();
  }
}

////////////////////////////////////////////////////////////////////////////////
// ContentPageView, OptionsPageView implementation:

void ContentPageView::InitControlLayout() {
  using views::GridLayout;
  using views::ColumnSet;

  GridLayout* layout = new GridLayout(this);
  layout->SetInsets(5, 5, 5, 5);
  SetLayoutManager(layout);

  const int single_column_view_set_id = 0;
  ColumnSet* column_set = layout->AddColumnSet(single_column_view_set_id);
  column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1,
                        GridLayout::USE_PREF, 0, 0);
  layout->StartRow(0, single_column_view_set_id);
  InitPasswordSavingGroup();
  layout->AddView(passwords_group_);
  layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);

  layout->StartRow(0, single_column_view_set_id);
  InitFormAutofillGroup();
  layout->AddView(form_autofill_group_);
  layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);

  layout->StartRow(0, single_column_view_set_id);
  InitImportGroup();
  layout->AddView(import_group_);
  layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);

  layout->StartRow(0, single_column_view_set_id);
  InitClearDataGroup();
  layout->AddView(clear_data_group_);
  layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);

  if (CommandLine::ForCurrentProcess()->
      HasSwitch(switches::kEnableExtensions)) {
    layout->StartRow(0, single_column_view_set_id);
    InitThemesGroup();
    layout->AddView(themes_group_);
    layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
  }

  // Init member prefs so we can update the controls if prefs change.
  ask_to_save_passwords_.Init(prefs::kPasswordManagerEnabled,
                              profile()->GetPrefs(), this);
  form_autofill_.Init(prefs::kFormAutofillEnabled, profile()->GetPrefs(), this);
}

void ContentPageView::NotifyPrefChanged(const std::wstring* pref_name) {
  if (!pref_name || *pref_name == prefs::kPasswordManagerEnabled) {
    if (ask_to_save_passwords_.GetValue()) {
      passwords_asktosave_radio_->SetChecked(true);
    } else {
      passwords_neversave_radio_->SetChecked(true);
    }
  }
  if (!pref_name || *pref_name == prefs::kFormAutofillEnabled) {
    form_autofill_checkbox_->SetChecked(form_autofill_.GetValue());
  }
}

///////////////////////////////////////////////////////////////////////////////
// ContentsPageView, views::View overrides:

void ContentPageView::Layout() {
  // We need to Layout twice - once to get the width of the contents box...
  View::Layout();
  passwords_asktosave_radio_->SetBounds(
      0, 0, passwords_group_->GetContentsWidth(), 0);
  passwords_neversave_radio_->SetBounds(
      0, 0, passwords_group_->GetContentsWidth(), 0);
  import_label_->SetBounds(0, 0, import_group_->GetContentsWidth(), 0);
  clear_data_label_->SetBounds(0, 0, clear_data_group_->GetContentsWidth(), 0);
  // ... and twice to get the height of multi-line items correct.
  View::Layout();
}

///////////////////////////////////////////////////////////////////////////////
// ContentPageView, private:

void ContentPageView::InitPasswordSavingGroup() {
  passwords_asktosave_radio_ = new views::RadioButton(
      l10n_util::GetString(IDS_OPTIONS_PASSWORDS_ASKTOSAVE),
      kPasswordSavingRadioGroup);
  passwords_asktosave_radio_->set_listener(this);
  passwords_asktosave_radio_->SetMultiLine(true);
  passwords_neversave_radio_ = new views::RadioButton(
      l10n_util::GetString(IDS_OPTIONS_PASSWORDS_NEVERSAVE),
      kPasswordSavingRadioGroup);
  passwords_neversave_radio_->set_listener(this);
  passwords_neversave_radio_->SetMultiLine(true);
  passwords_exceptions_button_ = new views::NativeButton(
      this, l10n_util::GetString(IDS_OPTIONS_PASSWORDS_EXCEPTIONS));

  using views::GridLayout;
  using views::ColumnSet;

  views::View* contents = new views::View;
  GridLayout* layout = new GridLayout(contents);
  contents->SetLayoutManager(layout);

  const int single_column_view_set_id = 1;
  ColumnSet* column_set = layout->AddColumnSet(single_column_view_set_id);
  column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 1,
                        GridLayout::USE_PREF, 0, 0);

  const int double_column_view_set_id = 0;
  column_set = layout->AddColumnSet(double_column_view_set_id);
  column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 0,
                        GridLayout::USE_PREF, 0, 0);
  column_set->AddPaddingColumn(0, kRelatedControlHorizontalSpacing);
  column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 0,
                        GridLayout::USE_PREF, 0, 0);

  layout->StartRow(0, single_column_view_set_id);
  layout->AddView(passwords_asktosave_radio_);
  layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
  layout->StartRow(0, single_column_view_set_id);
  layout->AddView(passwords_neversave_radio_);
  layout->AddPaddingRow(0, kUnrelatedControlVerticalSpacing);
  layout->StartRow(0, single_column_view_set_id);
  layout->AddView(passwords_exceptions_button_);

  passwords_group_ = new OptionsGroupView(
      contents, l10n_util::GetString(IDS_OPTIONS_PASSWORDS_GROUP_NAME), L"",
      true);
}

void ContentPageView::InitFormAutofillGroup() {
  form_autofill_checkbox_ = new views::Checkbox(
      l10n_util::GetString(IDS_AUTOFILL_SAVEFORMS));
  form_autofill_checkbox_->set_listener(this);
  form_autofill_checkbox_->SetMultiLine(true);

  using views::GridLayout;
  using views::ColumnSet;

  views::View* contents = new views::View;
  GridLayout* layout = new GridLayout(contents);
  contents->SetLayoutManager(layout);

  const int single_column_view_set_id = 1;
  ColumnSet* column_set = layout->AddColumnSet(single_column_view_set_id);
  column_set->AddColumn(GridLayout::FILL, GridLayout::CENTER, 1,
                        GridLayout::USE_PREF, 0, 0);

  layout->StartRow(0, single_column_view_set_id);
  layout->AddView(form_autofill_checkbox_);

  form_autofill_group_ = new OptionsGroupView(
      contents, l10n_util::GetString(IDS_AUTOFILL_SETTING_WINDOWS_GROUP_NAME),
      L"", true);
}

void ContentPageView::InitThemesGroup() {
  themes_reset_button_ = new views::NativeButton(this,
      l10n_util::GetString(IDS_THEMES_RESET_BUTTON));

  using views::GridLayout;
  using views::ColumnSet;

  views::View* contents = new views::View;
  GridLayout* layout = new GridLayout(contents);
  contents->SetLayoutManager(layout);

  const int single_column_view_set_id = 1;
  ColumnSet* column_set = layout->AddColumnSet(single_column_view_set_id);
  column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 1,
      GridLayout::USE_PREF, 0, 0);

  layout->StartRow(0, single_column_view_set_id);
  layout->AddView(themes_reset_button_);

  themes_group_ = new OptionsGroupView(
      contents, l10n_util::GetString(IDS_THEMES_GROUP_NAME),
      L"", false);
}

void ContentPageView::InitClearDataGroup() {
  clear_data_button_ = new views::NativeButton(this,
      l10n_util::GetString(IDS_OPTIONS_CLEAR_DATA_BUTTON));
  clear_data_label_ = new views::Label(
      l10n_util::GetString(IDS_OPTIONS_CLEAR_DATA_INFO));
  clear_data_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
  clear_data_label_->SetMultiLine(true);

  using views::GridLayout;
  using views::ColumnSet;

  views::View* contents = new views::View;
  GridLayout* layout = new GridLayout(contents);
  contents->SetLayoutManager(layout);

  const int single_column_view_set_id = 1;
  ColumnSet* column_set = layout->AddColumnSet(single_column_view_set_id);
  column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 1,
      GridLayout::USE_PREF, 0, 0);

  layout->StartRow(0, single_column_view_set_id);
  layout->AddView(clear_data_label_);
  layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
  layout->StartRow(0, single_column_view_set_id);
  layout->AddView(clear_data_button_);

  clear_data_group_ = new OptionsGroupView(
      contents, l10n_util::GetString(IDS_OPTIONS_CLEAR_DATA_GROUP_NAME),
      L"", true);
}

void ContentPageView::InitImportGroup() {
  import_button_ = new views::NativeButton(this,
      l10n_util::GetString(IDS_OPTIONS_IMPORT_DATA_BUTTON));
  import_label_ = new views::Label(
      l10n_util::GetString(IDS_OPTIONS_IMPORT_DATA_INFO));
  import_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
  import_label_->SetMultiLine(true);

  using views::GridLayout;
  using views::ColumnSet;

  views::View* contents = new views::View;
  GridLayout* layout = new GridLayout(contents);
  contents->SetLayoutManager(layout);

  const int single_column_view_set_id = 1;
  ColumnSet* column_set = layout->AddColumnSet(single_column_view_set_id);
  column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 1,
      GridLayout::USE_PREF, 0, 0);

  layout->StartRow(0, single_column_view_set_id);
  layout->AddView(import_label_);
  layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
  layout->StartRow(0, single_column_view_set_id);
  layout->AddView(import_button_);

  import_group_ = new OptionsGroupView(
      contents, l10n_util::GetString(IDS_OPTIONS_IMPORT_DATA_GROUP_NAME),
      L"", true);
}
<commit_msg>Now that themes are enabled by default, the option should be visible by default.<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/views/options/content_page_view.h"

#include <windows.h>
#include <shlobj.h>
#include <vsstyle.h>
#include <vssym32.h>

#include "app/gfx/canvas.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/gfx/native_theme.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/views/clear_browsing_data.h"
#include "chrome/browser/views/importer_view.h"
#include "chrome/browser/views/options/options_group_view.h"
#include "chrome/browser/views/options/passwords_exceptions_window_view.h"
#include "chrome/common/pref_names.h"
#include "grit/generated_resources.h"
#include "views/controls/button/radio_button.h"
#include "views/grid_layout.h"
#include "views/standard_layout.h"
#include "views/widget/widget.h"

namespace {

const int kPopupBlockingRadioGroup = 1;
const int kPasswordSavingRadioGroup = 2;
}  // namespace

ContentPageView::ContentPageView(Profile* profile)
    : passwords_exceptions_button_(NULL),
      passwords_group_(NULL),
      passwords_asktosave_radio_(NULL),
      passwords_neversave_radio_(NULL),
      themes_group_(NULL),
      themes_reset_button_(NULL),
      import_group_(NULL),
      import_label_(NULL),
      import_button_(NULL),
      clear_data_group_(NULL),
      clear_data_label_(NULL),
      clear_data_button_(NULL),
      OptionsPageView(profile) {
}

ContentPageView::~ContentPageView() {
}

///////////////////////////////////////////////////////////////////////////////
// ContentPageView, views::ButtonListener implementation:

void ContentPageView::ButtonPressed(views::Button* sender) {
  if (sender == passwords_asktosave_radio_ ||
      sender == passwords_neversave_radio_) {
    bool enabled = passwords_asktosave_radio_->checked();
    if (enabled) {
      UserMetricsRecordAction(L"Options_PasswordManager_Enable",
                              profile()->GetPrefs());
    } else {
      UserMetricsRecordAction(L"Options_PasswordManager_Disable",
                              profile()->GetPrefs());
    }
    ask_to_save_passwords_.SetValue(enabled);
  } else if (sender == passwords_exceptions_button_) {
    UserMetricsRecordAction(L"Options_ShowPasswordsExceptions", NULL);
    PasswordsExceptionsWindowView::Show(profile());
  } else if (sender == form_autofill_checkbox_) {
    bool enabled = form_autofill_checkbox_->checked();
    if (enabled) {
      UserMetricsRecordAction(L"Options_FormAutofill_Enable",
                              profile()->GetPrefs());
    } else {
      UserMetricsRecordAction(L"Options_FormAutofill_Disable",
                              profile()->GetPrefs());
    }
    form_autofill_.SetValue(enabled);
  } else if (sender == themes_reset_button_) {
    UserMetricsRecordAction(L"Options_ThemesReset", profile()->GetPrefs());
    profile()->ClearTheme();
  } else if (sender == import_button_) {
    views::Window::CreateChromeWindow(
      GetWindow()->GetNativeWindow(),
      gfx::Rect(),
      new ImporterView(profile()))->Show();
  } else if (sender == clear_data_button_) {
    views::Window::CreateChromeWindow(
      GetWindow()->GetNativeWindow(),
      gfx::Rect(),
      new ClearBrowsingDataView(profile()))->Show();
  }
}

////////////////////////////////////////////////////////////////////////////////
// ContentPageView, OptionsPageView implementation:

void ContentPageView::InitControlLayout() {
  using views::GridLayout;
  using views::ColumnSet;

  GridLayout* layout = new GridLayout(this);
  layout->SetInsets(5, 5, 5, 5);
  SetLayoutManager(layout);

  const int single_column_view_set_id = 0;
  ColumnSet* column_set = layout->AddColumnSet(single_column_view_set_id);
  column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1,
                        GridLayout::USE_PREF, 0, 0);
  layout->StartRow(0, single_column_view_set_id);
  InitPasswordSavingGroup();
  layout->AddView(passwords_group_);
  layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);

  layout->StartRow(0, single_column_view_set_id);
  InitFormAutofillGroup();
  layout->AddView(form_autofill_group_);
  layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);

  layout->StartRow(0, single_column_view_set_id);
  InitImportGroup();
  layout->AddView(import_group_);
  layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);

  layout->StartRow(0, single_column_view_set_id);
  InitClearDataGroup();
  layout->AddView(clear_data_group_);
  layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);

  layout->StartRow(0, single_column_view_set_id);
  InitThemesGroup();
  layout->AddView(themes_group_);
  layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);

  // Init member prefs so we can update the controls if prefs change.
  ask_to_save_passwords_.Init(prefs::kPasswordManagerEnabled,
                              profile()->GetPrefs(), this);
  form_autofill_.Init(prefs::kFormAutofillEnabled, profile()->GetPrefs(), this);
}

void ContentPageView::NotifyPrefChanged(const std::wstring* pref_name) {
  if (!pref_name || *pref_name == prefs::kPasswordManagerEnabled) {
    if (ask_to_save_passwords_.GetValue()) {
      passwords_asktosave_radio_->SetChecked(true);
    } else {
      passwords_neversave_radio_->SetChecked(true);
    }
  }
  if (!pref_name || *pref_name == prefs::kFormAutofillEnabled) {
    form_autofill_checkbox_->SetChecked(form_autofill_.GetValue());
  }
}

///////////////////////////////////////////////////////////////////////////////
// ContentsPageView, views::View overrides:

void ContentPageView::Layout() {
  // We need to Layout twice - once to get the width of the contents box...
  View::Layout();
  passwords_asktosave_radio_->SetBounds(
      0, 0, passwords_group_->GetContentsWidth(), 0);
  passwords_neversave_radio_->SetBounds(
      0, 0, passwords_group_->GetContentsWidth(), 0);
  import_label_->SetBounds(0, 0, import_group_->GetContentsWidth(), 0);
  clear_data_label_->SetBounds(0, 0, clear_data_group_->GetContentsWidth(), 0);
  // ... and twice to get the height of multi-line items correct.
  View::Layout();
}

///////////////////////////////////////////////////////////////////////////////
// ContentPageView, private:

void ContentPageView::InitPasswordSavingGroup() {
  passwords_asktosave_radio_ = new views::RadioButton(
      l10n_util::GetString(IDS_OPTIONS_PASSWORDS_ASKTOSAVE),
      kPasswordSavingRadioGroup);
  passwords_asktosave_radio_->set_listener(this);
  passwords_asktosave_radio_->SetMultiLine(true);
  passwords_neversave_radio_ = new views::RadioButton(
      l10n_util::GetString(IDS_OPTIONS_PASSWORDS_NEVERSAVE),
      kPasswordSavingRadioGroup);
  passwords_neversave_radio_->set_listener(this);
  passwords_neversave_radio_->SetMultiLine(true);
  passwords_exceptions_button_ = new views::NativeButton(
      this, l10n_util::GetString(IDS_OPTIONS_PASSWORDS_EXCEPTIONS));

  using views::GridLayout;
  using views::ColumnSet;

  views::View* contents = new views::View;
  GridLayout* layout = new GridLayout(contents);
  contents->SetLayoutManager(layout);

  const int single_column_view_set_id = 1;
  ColumnSet* column_set = layout->AddColumnSet(single_column_view_set_id);
  column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 1,
                        GridLayout::USE_PREF, 0, 0);

  const int double_column_view_set_id = 0;
  column_set = layout->AddColumnSet(double_column_view_set_id);
  column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 0,
                        GridLayout::USE_PREF, 0, 0);
  column_set->AddPaddingColumn(0, kRelatedControlHorizontalSpacing);
  column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 0,
                        GridLayout::USE_PREF, 0, 0);

  layout->StartRow(0, single_column_view_set_id);
  layout->AddView(passwords_asktosave_radio_);
  layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
  layout->StartRow(0, single_column_view_set_id);
  layout->AddView(passwords_neversave_radio_);
  layout->AddPaddingRow(0, kUnrelatedControlVerticalSpacing);
  layout->StartRow(0, single_column_view_set_id);
  layout->AddView(passwords_exceptions_button_);

  passwords_group_ = new OptionsGroupView(
      contents, l10n_util::GetString(IDS_OPTIONS_PASSWORDS_GROUP_NAME), L"",
      true);
}

void ContentPageView::InitFormAutofillGroup() {
  form_autofill_checkbox_ = new views::Checkbox(
      l10n_util::GetString(IDS_AUTOFILL_SAVEFORMS));
  form_autofill_checkbox_->set_listener(this);
  form_autofill_checkbox_->SetMultiLine(true);

  using views::GridLayout;
  using views::ColumnSet;

  views::View* contents = new views::View;
  GridLayout* layout = new GridLayout(contents);
  contents->SetLayoutManager(layout);

  const int single_column_view_set_id = 1;
  ColumnSet* column_set = layout->AddColumnSet(single_column_view_set_id);
  column_set->AddColumn(GridLayout::FILL, GridLayout::CENTER, 1,
                        GridLayout::USE_PREF, 0, 0);

  layout->StartRow(0, single_column_view_set_id);
  layout->AddView(form_autofill_checkbox_);

  form_autofill_group_ = new OptionsGroupView(
      contents, l10n_util::GetString(IDS_AUTOFILL_SETTING_WINDOWS_GROUP_NAME),
      L"", true);
}

void ContentPageView::InitThemesGroup() {
  themes_reset_button_ = new views::NativeButton(this,
      l10n_util::GetString(IDS_THEMES_RESET_BUTTON));

  using views::GridLayout;
  using views::ColumnSet;

  views::View* contents = new views::View;
  GridLayout* layout = new GridLayout(contents);
  contents->SetLayoutManager(layout);

  const int single_column_view_set_id = 1;
  ColumnSet* column_set = layout->AddColumnSet(single_column_view_set_id);
  column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 1,
      GridLayout::USE_PREF, 0, 0);

  layout->StartRow(0, single_column_view_set_id);
  layout->AddView(themes_reset_button_);

  themes_group_ = new OptionsGroupView(
      contents, l10n_util::GetString(IDS_THEMES_GROUP_NAME),
      L"", false);
}

void ContentPageView::InitClearDataGroup() {
  clear_data_button_ = new views::NativeButton(this,
      l10n_util::GetString(IDS_OPTIONS_CLEAR_DATA_BUTTON));
  clear_data_label_ = new views::Label(
      l10n_util::GetString(IDS_OPTIONS_CLEAR_DATA_INFO));
  clear_data_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
  clear_data_label_->SetMultiLine(true);

  using views::GridLayout;
  using views::ColumnSet;

  views::View* contents = new views::View;
  GridLayout* layout = new GridLayout(contents);
  contents->SetLayoutManager(layout);

  const int single_column_view_set_id = 1;
  ColumnSet* column_set = layout->AddColumnSet(single_column_view_set_id);
  column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 1,
      GridLayout::USE_PREF, 0, 0);

  layout->StartRow(0, single_column_view_set_id);
  layout->AddView(clear_data_label_);
  layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
  layout->StartRow(0, single_column_view_set_id);
  layout->AddView(clear_data_button_);

  clear_data_group_ = new OptionsGroupView(
      contents, l10n_util::GetString(IDS_OPTIONS_CLEAR_DATA_GROUP_NAME),
      L"", true);
}

void ContentPageView::InitImportGroup() {
  import_button_ = new views::NativeButton(this,
      l10n_util::GetString(IDS_OPTIONS_IMPORT_DATA_BUTTON));
  import_label_ = new views::Label(
      l10n_util::GetString(IDS_OPTIONS_IMPORT_DATA_INFO));
  import_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
  import_label_->SetMultiLine(true);

  using views::GridLayout;
  using views::ColumnSet;

  views::View* contents = new views::View;
  GridLayout* layout = new GridLayout(contents);
  contents->SetLayoutManager(layout);

  const int single_column_view_set_id = 1;
  ColumnSet* column_set = layout->AddColumnSet(single_column_view_set_id);
  column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 1,
      GridLayout::USE_PREF, 0, 0);

  layout->StartRow(0, single_column_view_set_id);
  layout->AddView(import_label_);
  layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
  layout->StartRow(0, single_column_view_set_id);
  layout->AddView(import_button_);

  import_group_ = new OptionsGroupView(
      contents, l10n_util::GetString(IDS_OPTIONS_IMPORT_DATA_GROUP_NAME),
      L"", true);
}
<|endoftext|>


<commit_before>/* dlvhex -- Answer-Set Programming with external interfaces.
 * Copyright (C) 2005, 2006, 2007 Roman Schindlauer
 * Copyright (C) 2006, 2007, 2008, 2009, 2010 Thomas Krennwallner
 * Copyright (C) 2009, 2010 Peter Schüller
 * Copyright (C) 2009 Peter Schüller
 *
 * This file is part of dlvhex.
 *
 * dlvhex is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * dlvhex is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with dlvhex; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 */

/**
 * @file   DLVResultParser.cpp
 * @author Roman Schindlauer, Peter Schüller
 * @date   Wed Mar 22 14:38:53 CET 2006
 *
 * @brief  DLV result parser using boost::spirit
 *
 *
 */

// use this for developing the parser
#undef CWDEBUG
#ifdef CWDEBUG
# ifndef _GNU_SOURCE
#  define _GNU_SOURCE
# endif
# include <libcwd/sys.h>
# include <libcwd/debug.h>
#endif

//#include "dlvhex/DLVResultParser.hpp"
#include "dlvhex/DLVresultParserDriver.h"

// use this for debugging parser progress (XML style)
#undef BOOST_SPIRIT_DEBUG

// activate benchmarking if activated by configure option --enable-debug
#ifdef HAVE_CONFIG_H
#  include "config.h"
#  ifdef DLVHEX_DEBUG
#    define DLVHEX_BENCHMARK
#  endif
#endif

#include "dlvhex/Benchmarking.h"
#include "dlvhex/globals.h"
#include "dlvhex/ID.hpp"
#include "dlvhex/Term.hpp"
#include "dlvhex/Atoms.hpp"
#include "dlvhex/ProgramCtx.h"

#include <boost/optional.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_object.hpp>
#include <boost/spirit/include/phoenix_fusion.hpp>
#include <boost/spirit/include/support_multi_pass.hpp>
#include <boost/algorithm/string/trim.hpp>

#include <sstream>
#include <iostream>

namespace spirit = boost::spirit;
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
namespace fusion = boost::fusion;
namespace phoenix = boost::phoenix;

DLVHEX_NAMESPACE_BEGIN

DLVResultParser::DLVResultParser(RegistryPtr reg):
  reg(reg),
  pMode(FirstOrder)
{
}

DLVResultParser::DLVResultParser(RegistryPtr reg, ParseMode mode):
  reg(reg),
  pMode(mode)
{
}

DLVResultParser::~DLVResultParser()
{
}

void
DLVResultParser::setParseMode(ParseMode mode)
{
	pMode = mode;
}

struct ParserState
{
  RegistryPtr registry;
  AnswerSet::Ptr current;
  DLVResultParser::AnswerSetAdder adder;
	bool dropPredicates;

  ParserState(
      RegistryPtr registry,
      DLVResultParser::AnswerSetAdder adder,
      bool dropPredicates):
    registry(registry),
    current(new AnswerSet(registry)),
		adder(adder),
    dropPredicates(dropPredicates) {}
};

#if 1
//
// useful phoenix operator debugging stuff:
// -> just add [ handle_dbg("message") ] to any rule/parser to get information
//
template<typename Attrib>
void houtput(Attrib const& a)
{
#ifdef CWDEBUG
  std::cerr << "XXX handling attribute " << libcwd::type_info_of(a).demangled_name() << std::endl;
#endif
};

template<>
void houtput(std::vector<char> const& a)
{
  std::cerr << "XXX got string  attribute '" << std::string(a.begin(), a.end()) << "'" << std::endl;
}

template<typename Content>
void houtput(boost::optional<Content> const& a)
{
  if( !a )
  {
    std::cerr << "XXX optional (unset):" << std::endl;
  }
  else
  {
    std::cerr << "XXX optional:" << std::endl;
  }
  houtput(a.get());
}

struct handle_dbg
{
  handle_dbg(std::string s): s(s) {}
  std::string s;
  template<typename Attrib>
  void operator()(Attrib& a, qi::unused_type, qi::unused_type) const
  {
    std::cerr << "DBG=" << s << std::endl;
    houtput(a);
  }
};
#endif

struct handle_int
{
  template <typename Context>
  void operator()(int i, Context& ctx, qi::unused_type) const
  {
    ID& ruleAttr = fusion::at_c<0>(ctx.attributes);

    ruleAttr = ID::termFromInteger(i);
    //std::cerr << "created int " << i << std::endl;
  }
};

namespace
{
  inline ID getOrRegisterTerm(RegistryPtr registry, const std::string& s)
  {
    ID id = registry->terms.getIDByString(s);
    if( id == ID_FAIL )
    {
      Term term(ID::MAINKIND_TERM, s);
      // we can only get strings or constants
      assert(s[0] == '"' || islower(s[0]));
      id = registry->terms.storeAndGetID(term);
    }
    return id;
  }
}

struct handle_ident
{
  handle_ident(ParserState& state): state(state) {}

  template <typename Context>
  void operator()(const std::string& s, Context& ctx, qi::unused_type) const
  {
    ID& ruleAttr = fusion::at_c<0>(ctx.attributes);

    ID id = getOrRegisterTerm(state.registry, s);
    ruleAttr = id;
    //std::cerr << "created ident '" << s << "'" << std::endl;
  }

  ParserState& state;
};

struct handle_finished_answerset
{
  handle_finished_answerset(ParserState& state): state(state) {}

  void operator()(qi::unused_type, qi::unused_type, qi::unused_type) const
  {
    state.adder(state.current);
		state.current.reset(new AnswerSet(state.registry));
  }

  ParserState& state;
};

struct handle_fact
{
  handle_fact(ParserState& state): state(state) {}

  void operator()(
			boost::fusion::vector3<
				boost::optional<char>,
				std::string,
				boost::optional<Tuple> >& attr,
			qi::unused_type, qi::unused_type) const
  {
		// alias for fusion input
		bool strong_neg = !!fusion::at_c<0>(attr);
    assert(!strong_neg);
		const std::string& predicate = fusion::at_c<1>(attr);
    ID predid = getOrRegisterTerm(state.registry, predicate);
    OrdinaryAtom atom(ID::MAINKIND_ATOM);
    atom.tuple.push_back(predid);
    boost::optional<Tuple>& tup = fusion::at_c<2>(attr);
    if( !!tup )
      atom.tuple.insert(atom.tuple.end(), tup.get().begin(), tup.get().end());

    // TODO lookup by string in registry, then by tuple
    ID id = state.registry->ogatoms.getIDByTuple(atom.tuple);
    if( id == ID_FAIL )
    {
      {
        #warning parsing efficiency problem see HexGrammarPTToASTConverter
        std::stringstream ss;
        RawPrinter printer(ss, state.registry);
        Tuple::const_iterator it = atom.tuple.begin();
        printer.print(*it);
        it++;
        if( it != atom.tuple.end() )
        {
          ss << "(";
          printer.print(*it);
          it++;
          while(it != atom.tuple.end())
          {
            ss << ",";
            printer.print(*it);
            it++;
          }
          ss << ")";
        }
        atom.text = ss.str();
      }
      LOG("storing atom " << atom);
      id = state.registry->ogatoms.storeAndGetID(atom);
    }
    //TODO make more efficient (cache pointer to interpretation or even function object)
    LOG("setting fact " << id);
    state.current->interpretation->setFact(id.address);
  }

  ParserState& state;
};

// "The Grammar"
template<typename Iterator>
struct DLVResultGrammar:
  public qi::grammar<Iterator, ascii::space_type>
{
	DLVResultGrammar(ParserState& state):
		DLVResultGrammar::base_type(answersets), state(state)
	{
    using spirit::int_;
    using spirit::_val;
    using spirit::_1;
    using qi::lexeme;
    using qi::char_;
    using qi::omit;
    using qi::lit;

		ident
			= lexeme[char_('"') > *(char_ - '"') > char_('"')]
      // @todo test performance
			//| lexeme[char_("a-z") >> *char_("a-zA-Z0-9_")];
			| lexeme[ascii::lower > *(ascii::alnum|char_('_'))];
		groundterm
			= int_ [ handle_int() ]
			| ident [ handle_ident(state) ]
      ;
		fact
			// char_ synthesizes a char attribute!
			= ( -char_('-') > ident > -params ) [ handle_fact(state) ] ;
		params
			%= '(' > groundterm > *(',' > groundterm) > ')';
		answerset
			= (lit('{') >> '}') [ handle_finished_answerset(state) ]
			| (lit('{') > fact > *(',' > fact) > lit('}') [ handle_finished_answerset(state) ]);
    /// @todo: do not throw away weak answer set information but store it
    costline
      = lit("Cost") > +(ascii::alnum|char_("[]<>():"));
		answersets
			// end_p enforces a "full" match (in case of success) even with trailing newlines
			= *(
            (-lit("Best model:") >> answerset)
            |
            costline
         ) > (qi::eol | qi::eoi);

    #ifdef BOOST_SPIRIT_DEBUG
		BOOST_SPIRIT_DEBUG_NODE(answersets);
		BOOST_SPIRIT_DEBUG_NODE(answerset);
		BOOST_SPIRIT_DEBUG_NODE(costline);
		BOOST_SPIRIT_DEBUG_NODE(fact);
		BOOST_SPIRIT_DEBUG_NODE(groundterm);
		BOOST_SPIRIT_DEBUG_NODE(ident);
    #endif
	}

	qi::rule<Iterator, ascii::space_type>                  answersets,
                                                         answerset,
                                                         fact,
                                                         costline;
	qi::rule<Iterator, ID(), ascii::space_type>            groundterm;
	qi::rule<Iterator, std::string(), ascii::space_type>   ident;
	qi::rule<Iterator, Tuple(), ascii::space_type>         params;

	ParserState& state;
};

void
DLVResultParser::parse(
    std::istream& is,
    AnswerSetAdder adder) throw (SyntaxError)
{
	DLVHEX_BENCHMARK_REGISTER_AND_SCOPE(sid,"DLVResultParser::parse");

  // @todo: read each line to the next endl, then parse, then get exactly one answer set per parse, maybe reuse the grammar (state can be avoided by using attributes, AtomSetPtr and AtomPtr or just use a new AST with integers instead)

	std::ostringstream buf;
	buf << is.rdbuf();
	const std::string& input = buf.str();
  LOG("parsing input '" << input << "'");

	typedef std::string::const_iterator forward_iterator_type;
	// convert input iterator to forward iterator, usable by spirit parser
	forward_iterator_type fwd_begin = input.begin();
	forward_iterator_type fwd_end = input.end();

	// @todo dump linewise before each line parse (see above todo)
  #ifndef NDEBUG
  if( true || Globals::Instance()->doVerbose(Globals::DUMP_OUTPUT) )
  {
    Globals::Instance()->getVerboseStream() <<
      "Got Result:\n===\n" << input << "\n===" << std::endl;
  }
  #endif

	bool dropPredicates =
		(pMode == DLVResultParser::HO);
	ParserState state(reg, adder, dropPredicates);

  DLVResultGrammar<forward_iterator_type> grammar(state);
  try
  {
    bool r = qi::phrase_parse(fwd_begin, fwd_end, grammar, ascii::space);

    // @todo: add better error message with position iterator
    if (!r || fwd_begin != fwd_end)
      throw SyntaxError("Could not parse complete DLV output!");
  } catch(const qi::expectation_failure<forward_iterator_type>& e)
  {
    throw SyntaxError("Could not parse DLV output! (expectation failure)");
  }
}

DLVHEX_NAMESPACE_END

// Local Variables:
// mode: C++
// End:
<commit_msg>printing dlv output if it is not parseable<commit_after>/* dlvhex -- Answer-Set Programming with external interfaces.
 * Copyright (C) 2005, 2006, 2007 Roman Schindlauer
 * Copyright (C) 2006, 2007, 2008, 2009, 2010 Thomas Krennwallner
 * Copyright (C) 2009, 2010 Peter Schüller
 * Copyright (C) 2009 Peter Schüller
 *
 * This file is part of dlvhex.
 *
 * dlvhex is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * dlvhex is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with dlvhex; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 */

/**
 * @file   DLVResultParser.cpp
 * @author Roman Schindlauer, Peter Schüller
 * @date   Wed Mar 22 14:38:53 CET 2006
 *
 * @brief  DLV result parser using boost::spirit
 *
 *
 */

// use this for developing the parser
#undef CWDEBUG
#ifdef CWDEBUG
# ifndef _GNU_SOURCE
#  define _GNU_SOURCE
# endif
# include <libcwd/sys.h>
# include <libcwd/debug.h>
#endif

//#include "dlvhex/DLVResultParser.hpp"
#include "dlvhex/DLVresultParserDriver.h"

// use this for debugging parser progress (XML style)
#undef BOOST_SPIRIT_DEBUG

// activate benchmarking if activated by configure option --enable-debug
#ifdef HAVE_CONFIG_H
#  include "config.h"
#  ifdef DLVHEX_DEBUG
#    define DLVHEX_BENCHMARK
#  endif
#endif

#include "dlvhex/Benchmarking.h"
#include "dlvhex/globals.h"
#include "dlvhex/ID.hpp"
#include "dlvhex/Term.hpp"
#include "dlvhex/Atoms.hpp"
#include "dlvhex/ProgramCtx.h"

#include <boost/optional.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_object.hpp>
#include <boost/spirit/include/phoenix_fusion.hpp>
#include <boost/spirit/include/support_multi_pass.hpp>
#include <boost/algorithm/string/trim.hpp>

#include <sstream>
#include <iostream>

namespace spirit = boost::spirit;
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
namespace fusion = boost::fusion;
namespace phoenix = boost::phoenix;

DLVHEX_NAMESPACE_BEGIN

DLVResultParser::DLVResultParser(RegistryPtr reg):
  reg(reg),
  pMode(FirstOrder)
{
}

DLVResultParser::DLVResultParser(RegistryPtr reg, ParseMode mode):
  reg(reg),
  pMode(mode)
{
}

DLVResultParser::~DLVResultParser()
{
}

void
DLVResultParser::setParseMode(ParseMode mode)
{
	pMode = mode;
}

struct ParserState
{
  RegistryPtr registry;
  AnswerSet::Ptr current;
  DLVResultParser::AnswerSetAdder adder;
	bool dropPredicates;

  ParserState(
      RegistryPtr registry,
      DLVResultParser::AnswerSetAdder adder,
      bool dropPredicates):
    registry(registry),
    current(new AnswerSet(registry)),
		adder(adder),
    dropPredicates(dropPredicates) {}
};

#if 1
//
// useful phoenix operator debugging stuff:
// -> just add [ handle_dbg("message") ] to any rule/parser to get information
//
template<typename Attrib>
void houtput(Attrib const& a)
{
#ifdef CWDEBUG
  std::cerr << "XXX handling attribute " << libcwd::type_info_of(a).demangled_name() << std::endl;
#endif
};

template<>
void houtput(std::vector<char> const& a)
{
  std::cerr << "XXX got string  attribute '" << std::string(a.begin(), a.end()) << "'" << std::endl;
}

template<typename Content>
void houtput(boost::optional<Content> const& a)
{
  if( !a )
  {
    std::cerr << "XXX optional (unset):" << std::endl;
  }
  else
  {
    std::cerr << "XXX optional:" << std::endl;
  }
  houtput(a.get());
}

struct handle_dbg
{
  handle_dbg(std::string s): s(s) {}
  std::string s;
  template<typename Attrib>
  void operator()(Attrib& a, qi::unused_type, qi::unused_type) const
  {
    std::cerr << "DBG=" << s << std::endl;
    houtput(a);
  }
};
#endif

struct handle_int
{
  template <typename Context>
  void operator()(int i, Context& ctx, qi::unused_type) const
  {
    ID& ruleAttr = fusion::at_c<0>(ctx.attributes);

    ruleAttr = ID::termFromInteger(i);
    //std::cerr << "created int " << i << std::endl;
  }
};

namespace
{
  inline ID getOrRegisterTerm(RegistryPtr registry, const std::string& s)
  {
    ID id = registry->terms.getIDByString(s);
    if( id == ID_FAIL )
    {
      Term term(ID::MAINKIND_TERM, s);
      // we can only get strings or constants
      assert(s[0] == '"' || islower(s[0]));
      id = registry->terms.storeAndGetID(term);
    }
    return id;
  }
}

struct handle_ident
{
  handle_ident(ParserState& state): state(state) {}

  template <typename Context>
  void operator()(const std::string& s, Context& ctx, qi::unused_type) const
  {
    ID& ruleAttr = fusion::at_c<0>(ctx.attributes);

    ID id = getOrRegisterTerm(state.registry, s);
    ruleAttr = id;
    //std::cerr << "created ident '" << s << "'" << std::endl;
  }

  ParserState& state;
};

struct handle_finished_answerset
{
  handle_finished_answerset(ParserState& state): state(state) {}

  void operator()(qi::unused_type, qi::unused_type, qi::unused_type) const
  {
    state.adder(state.current);
		state.current.reset(new AnswerSet(state.registry));
  }

  ParserState& state;
};

struct handle_fact
{
  handle_fact(ParserState& state): state(state) {}

  void operator()(
			boost::fusion::vector3<
				boost::optional<char>,
				std::string,
				boost::optional<Tuple> >& attr,
			qi::unused_type, qi::unused_type) const
  {
		// alias for fusion input
		bool strong_neg = !!fusion::at_c<0>(attr);
    assert(!strong_neg);
		const std::string& predicate = fusion::at_c<1>(attr);
    ID predid = getOrRegisterTerm(state.registry, predicate);
    OrdinaryAtom atom(ID::MAINKIND_ATOM);
    atom.tuple.push_back(predid);
    boost::optional<Tuple>& tup = fusion::at_c<2>(attr);
    if( !!tup )
      atom.tuple.insert(atom.tuple.end(), tup.get().begin(), tup.get().end());

    // TODO lookup by string in registry, then by tuple
    ID id = state.registry->ogatoms.getIDByTuple(atom.tuple);
    if( id == ID_FAIL )
    {
      {
        #warning parsing efficiency problem see HexGrammarPTToASTConverter
        std::stringstream ss;
        RawPrinter printer(ss, state.registry);
        Tuple::const_iterator it = atom.tuple.begin();
        printer.print(*it);
        it++;
        if( it != atom.tuple.end() )
        {
          ss << "(";
          printer.print(*it);
          it++;
          while(it != atom.tuple.end())
          {
            ss << ",";
            printer.print(*it);
            it++;
          }
          ss << ")";
        }
        atom.text = ss.str();
      }
      LOG("storing atom " << atom);
      id = state.registry->ogatoms.storeAndGetID(atom);
    }
    //TODO make more efficient (cache pointer to interpretation or even function object)
    LOG("setting fact " << id);
    state.current->interpretation->setFact(id.address);
  }

  ParserState& state;
};

// "The Grammar"
template<typename Iterator>
struct DLVResultGrammar:
  public qi::grammar<Iterator, ascii::space_type>
{
	DLVResultGrammar(ParserState& state):
		DLVResultGrammar::base_type(answersets), state(state)
	{
    using spirit::int_;
    using spirit::_val;
    using spirit::_1;
    using qi::lexeme;
    using qi::char_;
    using qi::omit;
    using qi::lit;

		ident
			= lexeme[char_('"') > *(char_ - '"') > char_('"')]
      // @todo test performance
			//| lexeme[char_("a-z") >> *char_("a-zA-Z0-9_")];
			| lexeme[ascii::lower > *(ascii::alnum|char_('_'))];
		groundterm
			= int_ [ handle_int() ]
			| ident [ handle_ident(state) ]
      ;
		fact
			// char_ synthesizes a char attribute!
			= ( -char_('-') > ident > -params ) [ handle_fact(state) ] ;
		params
			%= '(' > groundterm > *(',' > groundterm) > ')';
		answerset
			= (lit('{') >> '}') [ handle_finished_answerset(state) ]
			| (lit('{') > fact > *(',' > fact) > lit('}') [ handle_finished_answerset(state) ]);
    /// @todo: do not throw away weak answer set information but store it
    costline
      = lit("Cost") > +(ascii::alnum|char_("[]<>():"));
		answersets
			// end_p enforces a "full" match (in case of success) even with trailing newlines
			= *(
            (-lit("Best model:") >> answerset)
            |
            costline
         ) > (qi::eol | qi::eoi);

    #ifdef BOOST_SPIRIT_DEBUG
		BOOST_SPIRIT_DEBUG_NODE(answersets);
		BOOST_SPIRIT_DEBUG_NODE(answerset);
		BOOST_SPIRIT_DEBUG_NODE(costline);
		BOOST_SPIRIT_DEBUG_NODE(fact);
		BOOST_SPIRIT_DEBUG_NODE(groundterm);
		BOOST_SPIRIT_DEBUG_NODE(ident);
    #endif
	}

	qi::rule<Iterator, ascii::space_type>                  answersets,
                                                         answerset,
                                                         fact,
                                                         costline;
	qi::rule<Iterator, ID(), ascii::space_type>            groundterm;
	qi::rule<Iterator, std::string(), ascii::space_type>   ident;
	qi::rule<Iterator, Tuple(), ascii::space_type>         params;

	ParserState& state;
};

void
DLVResultParser::parse(
    std::istream& is,
    AnswerSetAdder adder) throw (SyntaxError)
{
	DLVHEX_BENCHMARK_REGISTER_AND_SCOPE(sid,"DLVResultParser::parse");

  // @todo: read each line to the next endl, then parse, then get exactly one answer set per parse, maybe reuse the grammar (state can be avoided by using attributes, AtomSetPtr and AtomPtr or just use a new AST with integers instead)

	std::ostringstream buf;
	buf << is.rdbuf();
	const std::string& input = buf.str();
  LOG("parsing input '" << input << "'");

	typedef std::string::const_iterator forward_iterator_type;
	// convert input iterator to forward iterator, usable by spirit parser
	forward_iterator_type fwd_begin = input.begin();
	forward_iterator_type fwd_end = input.end();

	// @todo dump linewise before each line parse (see above todo)
  #ifndef NDEBUG
  if( true || Globals::Instance()->doVerbose(Globals::DUMP_OUTPUT) )
  {
    Globals::Instance()->getVerboseStream() <<
      "Got Result:\n===\n" << input << "\n===" << std::endl;
  }
  #endif

	bool dropPredicates =
		(pMode == DLVResultParser::HO);
	ParserState state(reg, adder, dropPredicates);

  DLVResultGrammar<forward_iterator_type> grammar(state);
  try
  {
    bool r = qi::phrase_parse(fwd_begin, fwd_end, grammar, ascii::space);

    // @todo: add better error message with position iterator
    if (!r || fwd_begin != fwd_end)
      throw SyntaxError("Could not parse complete DLV output!");
  } catch(const qi::expectation_failure<forward_iterator_type>& e)
  {
    throw SyntaxError("Could not parse DLV output! (expectation failure): \n===\n" + input + "===\n");
  }
}

DLVHEX_NAMESPACE_END

// Local Variables:
// mode: C++
// End:
<|endoftext|>


<commit_before><commit_msg>Fix light debug draw<commit_after><|endoftext|>


<commit_before>void AliPHOSCalibHistoProducer(const char* file="2006run2211.root")
{
  // Script is to be run at DAQ computers (LDC, GDC, HLT or MOOD);
  // it fills the histograms with amplitudes per channel.
  // These histograms will be processed in the Shuttle preprocessor
  // e.g., to extract mean amplitudes needed for relative channel calibration
  //
  // This example assumes that the input data is supplied from the
  // raw data file in the ROOT format.
  //
  // Author: Boris Polichtchouk, 4 October 2006

  AliRawReaderRoot* rf = new AliRawReaderRoot(file);
  AliPHOSCalibHistoProducer hp(rf);
  hp.Run();
}
<commit_msg>Close histo file in destructor. Load libPHOSshuttle in macro.<commit_after>void AliPHOSCalibHistoProducer(const char* file="2006run2211.root")
{
  // Script is to be run at DAQ computers (LDC, GDC, HLT or MOOD);
  // it fills the histograms with amplitudes per channel.
  // These histograms will be processed in the Shuttle preprocessor
  // e.g., to extract mean amplitudes needed for relative channel calibration
  //
  // This example assumes that the input data is supplied from the
  // raw data file in the ROOT format.
  //
  // Author: Boris Polichtchouk, 4 October 2006

  // Load PHOS shuttle library as it is not linked to aliroot
  gSystem->Load("libPHOSshuttle");

  AliRawReaderRoot* rf = new AliRawReaderRoot(file);
  AliPHOSCalibHistoProducer hp(rf);
  hp.Run();
}
<|endoftext|>


<commit_before>#include "Camera.h"
#include "Object.h"
#include "Director.h"
#include "TransformPipelineParam.h"

using namespace Math;
using namespace std;
using namespace Rendering::Light;
using namespace Device;
using namespace Core;
using namespace Rendering::Camera;
using namespace Rendering::Manager;

Camera::Camera() : Component(),
	_frustum(nullptr), _renderTarget(nullptr), _depthBuffer(nullptr)
{

}

Camera::~Camera(void)
{

}

void Camera::Initialize()
{
	_FOV = 60.0f;
	_clippingNear = 0.01f;
	_clippingFar = 50.0f;

	Size<unsigned int> windowSize = Director::GetInstance()->GetWindowSize();
	_aspect = (float)windowSize.w / (float)windowSize.h;

	_camType    = Type::Perspective;
	_clearColor = Color(0.5f, 0.5f, 1.0f);

	_frustum = new Frustum(0.0f);

	_renderTarget = new Texture::RenderTexture;
	_renderTarget->Create(windowSize);

	_depthBuffer =  new Texture::RenderTexture;
	_depthBuffer->Create(windowSize);

	_constBuffer = new Buffer::ConstBuffer;
	if(_constBuffer->Create(sizeof(CameraConstBuffer)) == false)
		ASSERT("Error, cam->constbuffer->Create");

	//_clearFlag = ClearFlag::FlagSolidColor;
}

void Camera::Destroy()
{
	SAFE_DELETE(_frustum);
	SAFE_DELETE(_renderTarget);
	SAFE_DELETE(_depthBuffer);
}

void Camera::CalcAspect()
{
	Size<unsigned int> windowSize =  Device::Director::GetInstance()->GetWindowSize();
	_aspect = (float)windowSize.w / (float)windowSize.h;
}

void Camera::ProjectionMatrix(Math::Matrix& outMatrix)
{
	if(_camType == Type::Perspective)
	{
		float radian = _FOV * PI / 180.0f;
		Matrix::PerspectiveFovLH(outMatrix, _aspect, radian, _clippingNear, _clippingFar);
	}
	else if(_camType == Type::Orthographic)
	{
		Size<unsigned int> windowSize = Device::Director::GetInstance()->GetWindowSize();
		Matrix::OrthoLH(outMatrix, (float)(windowSize.w), (float)(windowSize.h), _clippingNear, _clippingFar);
	}
}

void Camera::ViewMatrix(Math::Matrix& outMatrix)
{
	Transform* ownerTransform = _owner->GetTransform();
	ownerTransform->WorldMatrix(outMatrix);

	Vector3 worldPos;
	worldPos.x = outMatrix._41;
	worldPos.y = outMatrix._42;
	worldPos.z = outMatrix._43;

	Vector3 p;
	p.x = -Vector3::Dot(ownerTransform->GetRight(), worldPos);
	p.y = -Vector3::Dot(ownerTransform->GetUp(), worldPos);
	p.z = -Vector3::Dot(ownerTransform->GetForward(), worldPos);

	outMatrix._41 = p.x;
	outMatrix._42 = p.y;
	outMatrix._43 = p.z;
	outMatrix._44 = 1.0f;
}

void Camera::UpdateTransformCBAndCheckRender(const Structure::Vector<std::string, Core::Object>& objects)
{
	TransformPipelineParam tfParam;
	ProjectionMatrix(tfParam.projMat);
	ViewMatrix(tfParam.viewMat);

	Matrix viewProj = tfParam.viewMat * tfParam.projMat;
	_frustum->Make(viewProj);

	CameraConstBuffer camCB;
	{
		const Math::Matrix& viewMat = tfParam.viewMat;
		camCB.viewPos = Vector4(viewMat._41, viewMat._42, viewMat._43, 1.0f);
		camCB.clippingNear = _clippingNear;
		camCB.clippingFar = _clippingFar;
		const auto& size = Device::Director::GetInstance()->GetWindowSize();
		camCB.screenSize.w = static_cast<float>(size.w);
		camCB.screenSize.h = static_cast<float>(size.h);
	}

	ID3D11DeviceContext* context = Device::Director::GetInstance()->GetDirectX()->GetContext();
	_constBuffer->Update(context, &camCB);

	auto& dataInobjects = objects.GetVector();
	for(auto iter = dataInobjects.begin(); iter != dataInobjects.end(); ++iter)
	{
		GET_CONTENT_FROM_ITERATOR(iter)->Culling(_frustum);
		GET_CONTENT_FROM_ITERATOR(iter)->UpdateTransformCBAndCheckRender(tfParam);
	}
}

void Camera::RenderObjects(const Device::DirectX* dx, const Rendering::Manager::RenderManager* renderMgr)
{
	enum MeshRenderOption
	{
		DepthWriteWithTest,
		AlphaTest,
		Common,
	};
	auto MeshRender = [&](ID3D11DeviceContext* context, Material* customMaterial, Manager::RenderManager::MeshType type, MeshRenderOption option)
	{
		Material* currentUseMaterial = nullptr;
		if(customMaterial &&
			(option == MeshRenderOption::DepthWriteWithTest ||
			 option == MeshRenderOption::AlphaTest) )
			ASSERT("Invalid Arg");

		auto RenderIter = [&](Material* material, Mesh::Mesh* mesh)
		{
			if(customMaterial)
				material = customMaterial;
			else if(option == MeshRenderOption::DepthWriteWithTest)
			{
				material = mesh->GetMeshRenderer()->GetDepthWriteMaterial();
				customMaterial = material;
			}
			else if(option == MeshRenderOption::AlphaTest)
			{
				material =  mesh->GetMeshRenderer()->GetAlphaTestMaterial();
				customMaterial = material;
			}

			if(currentUseMaterial != material)
			{
				currentUseMaterial = material;
				currentUseMaterial->UpdateShader(context);
			}

			mesh->Render(customMaterial, _constBuffer);
		};

		renderMgr->Iterate(RenderIter, type);
	};

	//graphics part
	{
		ID3D11DeviceContext* context = dx->GetContext();

		//Test
		{
			ID3D11RenderTargetView* rtv = dx->GetBackBuffer();
			context->OMSetRenderTargets(1, &rtv, dx->GetDepthBuffer()->GetDepthStencilView());
			context->ClearRenderTargetView(dx->GetBackBuffer(), _clearColor.color);
			dx->GetDepthBuffer()->Clear(1.0f, 0);
			MeshRender(context, nullptr, Manager::RenderManager::MeshType::nonAlpha, MeshRenderOption::Common);
		}

		////clear backbuffer, depthbuffer
		//{
		//	context->ClearRenderTargetView(dx->GetBackBuffer(), _clearColor.color);
		//	dx->GetDepthBuffer()->Clear(0.0f, 0);
		//	_depthBuffer->Clear(Rendering::Color::white(), dx);
		//}

		////off alpha blending
		//{
		//	float blendFactor[1] = { 0.0f };
		//	context->OMSetBlendState(dx->GetOpaqueBlendState(), blendFactor, 0xffffffff);
		//}

		////Render
		//{
		//	//Early-Z
		//	{
		//		ID3D11RenderTargetView* rtv = _depthBuffer->GetRenderTargetView();
		//		context->OMSetRenderTargets(1, &rtv, dx->GetDepthBuffer()->GetDepthStencilView());
		//		context->OMSetDepthStencilState(dx->GetDepthLessEqualState(), 0);
		//		MeshRender(context, nullptr, RenderManager::MeshType::nonAlpha, MeshRenderOption::DepthWriteWithTest);

		//		context->RSSetState(dx->GetDisableCullingRasterizerState());
		//		MeshRender(context, nullptr, RenderManager::MeshType::hasAlpha, MeshRenderOption::AlphaTest);
		//		context->RSSetState(nullptr);
		//	}

		//	//Light Culling
		//	{

		//	}

		//	//Forward Rendering
		//	{
		//		//MeshRender(context, nullptr, Manager::RenderManager::MeshType::nonAlpha);
		//	}
		//}

		IDXGISwapChain* swapChain = dx->GetSwapChain();
		swapChain->Present(0, 0);
	}
}
<commit_msg>Camera - 임시 렌더링 #37<commit_after>#include "Camera.h"
#include "Object.h"
#include "Director.h"
#include "TransformPipelineParam.h"

using namespace Math;
using namespace std;
using namespace Rendering::Light;
using namespace Device;
using namespace Core;
using namespace Rendering::Camera;
using namespace Rendering::Manager;

Camera::Camera() : Component(),
	_frustum(nullptr), _renderTarget(nullptr), _depthBuffer(nullptr)
{

}

Camera::~Camera(void)
{

}

void Camera::Initialize()
{
	_FOV = 60.0f;
	_clippingNear = 0.01f;
	_clippingFar = 50.0f;

	Size<unsigned int> windowSize = Director::GetInstance()->GetWindowSize();
	_aspect = (float)windowSize.w / (float)windowSize.h;

	_camType    = Type::Perspective;
	_clearColor = Color(0.5f, 0.5f, 1.0f);

	_frustum = new Frustum(0.0f);

	_renderTarget = new Texture::RenderTexture;
	_renderTarget->Create(windowSize);

	_depthBuffer =  new Texture::RenderTexture;
	_depthBuffer->Create(windowSize);

	_constBuffer = new Buffer::ConstBuffer;
	if(_constBuffer->Create(sizeof(CameraConstBuffer)) == false)
		ASSERT("Error, cam->constbuffer->Create");

	//_clearFlag = ClearFlag::FlagSolidColor;
}

void Camera::Destroy()
{
	SAFE_DELETE(_frustum);
	SAFE_DELETE(_renderTarget);
	SAFE_DELETE(_depthBuffer);
}

void Camera::CalcAspect()
{
	Size<unsigned int> windowSize =  Device::Director::GetInstance()->GetWindowSize();
	_aspect = (float)windowSize.w / (float)windowSize.h;
}

void Camera::ProjectionMatrix(Math::Matrix& outMatrix)
{
	if(_camType == Type::Perspective)
	{
		float radian = _FOV * PI / 180.0f;
		Matrix::PerspectiveFovLH(outMatrix, _aspect, radian, _clippingNear, _clippingFar);
	}
	else if(_camType == Type::Orthographic)
	{
		Size<unsigned int> windowSize = Device::Director::GetInstance()->GetWindowSize();
		Matrix::OrthoLH(outMatrix, (float)(windowSize.w), (float)(windowSize.h), _clippingNear, _clippingFar);
	}
}

void Camera::ViewMatrix(Math::Matrix& outMatrix)
{
	Transform* ownerTransform = _owner->GetTransform();
	ownerTransform->WorldMatrix(outMatrix);

	Vector3 worldPos;
	worldPos.x = outMatrix._41;
	worldPos.y = outMatrix._42;
	worldPos.z = outMatrix._43;

	Vector3 p;
	p.x = -Vector3::Dot(ownerTransform->GetRight(), worldPos);
	p.y = -Vector3::Dot(ownerTransform->GetUp(), worldPos);
	p.z = -Vector3::Dot(ownerTransform->GetForward(), worldPos);

	outMatrix._41 = p.x;
	outMatrix._42 = p.y;
	outMatrix._43 = p.z;
	outMatrix._44 = 1.0f;
}

void Camera::UpdateTransformCBAndCheckRender(const Structure::Vector<std::string, Core::Object>& objects)
{
	TransformPipelineParam tfParam;
	ProjectionMatrix(tfParam.projMat);
	ViewMatrix(tfParam.viewMat);

	Matrix viewProj = tfParam.viewMat * tfParam.projMat;
	_frustum->Make(viewProj);

	CameraConstBuffer camCB;
	{
		const Math::Matrix& viewMat = tfParam.viewMat;
		camCB.viewPos = Vector4(viewMat._41, viewMat._42, viewMat._43, 1.0f);
		camCB.clippingNear = _clippingNear;
		camCB.clippingFar = _clippingFar;
		const auto& size = Device::Director::GetInstance()->GetWindowSize();
		camCB.screenSize.w = static_cast<float>(size.w);
		camCB.screenSize.h = static_cast<float>(size.h);
	}

	ID3D11DeviceContext* context = Device::Director::GetInstance()->GetDirectX()->GetContext();
	_constBuffer->Update(context, &camCB);

	auto& dataInobjects = objects.GetVector();
	for(auto iter = dataInobjects.begin(); iter != dataInobjects.end(); ++iter)
	{
		GET_CONTENT_FROM_ITERATOR(iter)->Culling(_frustum);
		GET_CONTENT_FROM_ITERATOR(iter)->UpdateTransformCBAndCheckRender(tfParam);
	}
}

void Camera::RenderObjects(const Device::DirectX* dx, const Rendering::Manager::RenderManager* renderMgr)
{
	enum MeshRenderOption
	{
		DepthWriteWithTest,
		AlphaTest,
		Common,
	};
	auto MeshRender = [&](ID3D11DeviceContext* context, Material* customMaterial, Manager::RenderManager::MeshType type, MeshRenderOption option)
	{
		Material* currentUseMaterial = nullptr;
		if(customMaterial &&
			(option == MeshRenderOption::DepthWriteWithTest ||
			 option == MeshRenderOption::AlphaTest) )
			ASSERT("Invalid Arg");

		auto RenderIter = [&](Material* material, Mesh::Mesh* mesh)
		{
			if(customMaterial)
				material = customMaterial;
			else if(option == MeshRenderOption::DepthWriteWithTest)
			{
				material = mesh->GetMeshRenderer()->GetDepthWriteMaterial();
				customMaterial = material;
			}
			else if(option == MeshRenderOption::AlphaTest)
			{
				material =  mesh->GetMeshRenderer()->GetAlphaTestMaterial();
				customMaterial = material;
			}

			if(currentUseMaterial != material)
			{
				currentUseMaterial = material;
				currentUseMaterial->UpdateShader(context);
			}

			mesh->Render(customMaterial, _constBuffer);
		};

		renderMgr->Iterate(RenderIter, type);
	};

	//graphics part
	{
		ID3D11DeviceContext* context = dx->GetContext();

		//Test
		{
			ID3D11RenderTargetView* rtv = dx->GetBackBuffer();
			context->OMSetRenderTargets(1, &rtv, dx->GetDepthBuffer()->GetDepthStencilView());
			context->ClearRenderTargetView(dx->GetBackBuffer(), _clearColor.color);
			dx->GetDepthBuffer()->Clear(1.0f, 0);
			MeshRender(context, nullptr, Manager::RenderManager::MeshType::nonAlpha, MeshRenderOption::Common);
		}

		//clear backbuffer, depthbuffer
		{
			//context->ClearRenderTargetView(dx->GetBackBuffer(), _clearColor.color);
			//dx->GetDepthBuffer()->Clear(0.0f, 0);
			//_depthBuffer->Clear(Rendering::Color::white(), dx);
		}

		//off alpha blending
		{
			//float blendFactor[1] = { 0.0f };
			//context->OMSetBlendState(dx->GetOpaqueBlendState(), blendFactor, 0xffffffff);
		}

		//Render
		{
		/*	ID3D11RenderTargetView*		nullRTV		= nullptr;
			ID3D11DepthStencilView*		nullDSV		= nullptr;
			ID3D11ShaderResourceView*	nullSRV		= nullptr;
			ID3D11UnorderedAccessView*	nullUAV		= nullptr;
			ID3D11SamplerState*			nullSampler = nullptr;*/

			//Early-Z
			{
				//ID3D11RenderTargetView* rtv = _depthBuffer->GetRenderTargetView();
				//context->OMSetRenderTargets(1, &rtv, dx->GetDepthBuffer()->GetDepthStencilView());
				//context->OMSetDepthStencilState(dx->GetDepthLessEqualState(), 0);
				//MeshRender(context, nullptr, RenderManager::MeshType::nonAlpha, MeshRenderOption::DepthWriteWithTest);

				//rtv = nullptr;
				//context->OMSetRenderTargets(1, &rtv, dx->GetDepthBuffer()->GetDepthStencilView());
				//context->RSSetState(dx->GetDisableCullingRasterizerState());
				//MeshRender(context, nullptr, RenderManager::MeshType::hasAlpha, MeshRenderOption::AlphaTest);
				//context->RSSetState(nullptr);
			}

			//Light Culling
			{
				//context->OMSetRenderTargets(1, &nullRTV, nullDSV);
				//context->VSSetShader(nullptr, nullptr, 0);
				//context->PSSetShader(nullptr, nullptr, 0);
				//context->CSSetShader(
			}

			//Forward Rendering
			{
			}
		}

		IDXGISwapChain* swapChain = dx->GetSwapChain();
		swapChain->Present(0, 0);
	}
}
<|endoftext|>


<commit_before>#include <stdio.h>      /* printf */
#include <math.h>       /* fmod */
using namespace std;

/**
 * Created by Marcus Therkildsen on 27-10-2015.
 * Using http://www.tutorialspoint.com/compile_cpp_online.php
 * to check if working
 */

int main()
{
    // Creating some start variables
    float num_sailors = 5;
    int search_to = 3500;
	float perc = (1 - 1/num_sailors);

    // Go through the number of sailors
    for (int i=0;i<search_to;i++){
        float num_coc = i;

        // Go through the number of sailors
        for (int j=0; j<num_sailors;j++){

            /* Removing 1 coconut (for the monkey) and the amount that the
            certain sailor takes for himself */
            num_coc = (num_coc - 1)*perc;

		}

		/*
        Now each sailor has his own pile.
        The monkey has 5 and there's a pile left.
        Checking if there is an amount divisible by num_sailors left in the pile
        and if the number of remaining is positive (of course)
         */

		if ((fmod(num_coc, num_sailors) == 0) & (num_coc >= 0)){
            /* If the remaining (positive) number of coconuts is divisible
            between the sailors, then we found the solution.*/
	        printf ( "Solution: %i coconuts to begin with\n",i);
		}
    }
    return 0;
}<commit_msg>Removed C++ solution since it is identical to C<commit_after><|endoftext|>


<commit_before>//
//  customCircle.cpp
//  01_simpleClass
//
//  Created by Bernardo Santos Schorr on 1/31/15.
//
//

#include "customCircle.h"

customCircle::customCircle() {

}

void customCircle::setup(ofVec2f _initPos) {
    initPos = _initPos;
    currentPos = initPos;
}

void customCircle::update() {

    if(currentIter < totalIter) {

        pct = easeOut(currentIter, 0.0, 1.0, totalIter);
        currentPos.x = initPos.x * (1 - pct) + finalPos.x * pct;

        pct = easeIn(currentIter, 0.0, 1.0, totalIter);
        currentPos.y = initPos.y * (1 - pct) + finalPos.y * pct;

        currentIter++;

    }

}

void customCircle::draw() {

    //ofLine (initPos, finalPos);
    ofCircle(currentPos, 10);

    ofDrawBitmapString("Click anywhere!", 30, 30);
    ofDrawBitmapString("Init Pos", initPos);
    ofDrawBitmapString("Final Pos", finalPos);

}

void customCircle::setPenner(ofVec2f _newPos, int _totalIter){
    currentIter = 0;
    totalIter = _totalIter;
    initPos = currentPos;
    finalPos = _newPos;
}

float customCircle::easeIn (float t,float b , float c, float d) {
    float s = 1.70158f;
    float postFix = t/=d;
    return c*(postFix)*t*((s+1)*t - s) + b;
}
float customCircle::easeOut(float t,float b , float c, float d) {
    float s = 1.70158f;
    return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
}

float customCircle::easeInOut(float t,float b , float c, float d) {
    float s = 1.70158f;
    if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525f))+1)*t - s)) + b;
    float postFix = t-=2;
    return c/2*((postFix)*t*(((s*=(1.525f))+1)*t + s) + 2) + b;
}<commit_msg>added week 1 examples<commit_after>//
//  customCircle.cpp
//  01_simpleClass
//
//  Created by Bernardo Santos Schorr on 1/31/15.
//
//

#include "customCircle.h"

customCircle::customCircle() {

}

void customCircle::setup(ofVec2f _initPos) {
    initPos = _initPos;
    currentPos = initPos;
}

void customCircle::update() {

    if(currentIter < totalIter) {

        pct = easeOut(currentIter, 0.0, 1.0, totalIter);
        currentPos.x = initPos.x * (1 - pct) + finalPos.x * pct;

        pct = easeIn(currentIter, 0.0, 1.0, totalIter);
        currentPos.y = initPos.y * (1 - pct) + finalPos.y * pct;

        currentIter++;

    }

}

void customCircle::draw() {

    //ofLine (initPos, finalPos);
    ofCircle(currentPos, 10);

    ofDrawBitmapString("Click anywhere!", 30, 30);
    ofDrawBitmapString("Init Pos", initPos);
    ofDrawBitmapString("Final Pos", finalPos);

}

void customCircle::setPenner(ofVec2f _newPos, int _totalIter){
    currentIter = 0;
    totalIter = _totalIter;
    initPos = currentPos;
    finalPos = _newPos;
}

//this code is using Penner's BACK functions for easing. Check out the other ones he made!

float customCircle::easeIn (float t,float b , float c, float d) {
    float s = 1.70158f;
    float postFix = t/=d;
    return c*(postFix)*t*((s+1)*t - s) + b;
}
float customCircle::easeOut(float t,float b , float c, float d) {
    float s = 1.70158f;
    return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
}

float customCircle::easeInOut(float t,float b , float c, float d) {
    float s = 1.70158f;
    if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525f))+1)*t - s)) + b;
    float postFix = t-=2;
    return c/2*((postFix)*t*(((s*=(1.525f))+1)*t + s) + 2) + b;
}<|endoftext|>


<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2013 Bernhard Beschow <bbeschow@cs.tu-berlin.de>
// Copyright 2013 Dennis Nienhüser <earthwings@gentoo.org>
//

#include "MapThemeDownloadDialog.h"
#include "ui_MapThemeDownloadDialog.h"

#include "MarbleDirs.h"
#include "NewstuffModel.h"
#include "MarbleWidget.h"

#include <QtGui/QPainter>
#include <QtGui/QTextDocument>
#include <QtGui/QAbstractTextDocumentLayout>
#include <QtGui/QStyledItemDelegate>

namespace Marble
{

class MapItemDelegate : public QStyledItemDelegate
{
public:
    MapItemDelegate( QListView* view, NewstuffModel* newstuffModel, MarbleWidget* marbleWidget );
    void paint( QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const;
    QSize sizeHint( const QStyleOptionViewItem &option, const QModelIndex &index ) const;

protected:
    bool editorEvent( QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index );

private:
    enum Element {
        Icon,
        Text,
        InstallButton,
        UpgradeButton,
        OpenButton,
        CancelButton,
        RemoveButton,
        ProgressReport
    };

    int buttonWidth( const QStyleOptionViewItem &option ) const;
    QStyleOptionButton button( Element element, const QStyleOptionViewItem &option ) const;
    QRect position( Element element, const QStyleOptionViewItem &option ) const;
    QString text( const QModelIndex &index ) const;
    QListView* m_view;
    NewstuffModel* m_newstuffModel;
    mutable int m_buttonWidth;
    int const m_margin;
    int const m_iconSize;
    MarbleWidget* m_marbleWidget;
};

class MapThemeDownloadDialog::Private : public Ui::MapThemeDownloadDialog
{
public:
    Private() :
        m_model()
    {}

    NewstuffModel m_model;
};

MapThemeDownloadDialog::MapThemeDownloadDialog( MarbleWidget* marbleWidget ) :
    QDialog( marbleWidget ),
    d( new Private )
{
    d->setupUi( this );

    d->m_model.setTargetDirectory( MarbleDirs::localPath() + "/maps" );
    d->m_model.setProvider( "http://edu.kde.org/marble/newstuff/maps-4.5.xml" );
    d->m_model.setRegistryFile( MarbleDirs::localPath() + "/newstuff/marble-map-themes.knsregistry", Marble::NewstuffModel::NameTag );

    d->listView->setIconSize( QSize( 130, 130 ) );
    d->listView->setAlternatingRowColors( true );
    d->listView->setUniformItemSizes( false );
    d->listView->setResizeMode( QListView::Adjust );
    d->listView->setItemDelegate( new MapItemDelegate( d->listView, &d->m_model, marbleWidget ) );
    d->listView->setModel( &d->m_model );
}

MapThemeDownloadDialog::~MapThemeDownloadDialog()
{
    delete d;
}

MapItemDelegate::MapItemDelegate( QListView *view , NewstuffModel *newstuffModel, MarbleWidget* marbleWidget ) :
    m_view( view ),
    m_newstuffModel( newstuffModel ),
    m_buttonWidth( 0 ),
    m_margin( 5 ),
    m_iconSize( 16 ),
    m_marbleWidget( marbleWidget )
{
    // nothing to do
}

void MapItemDelegate::paint( QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const
{
    QStyleOptionViewItemV4 styleOption = option;
    styleOption.text = QString();
    QApplication::style()->drawControl(QStyle::CE_ItemViewItem, &styleOption, painter);

    QAbstractTextDocumentLayout::PaintContext paintContext;
    if (styleOption.state & QStyle::State_Selected) {
        paintContext.palette.setColor(QPalette::Text,
            styleOption.palette.color(QPalette::Active, QPalette::HighlightedText));
    }

    // Draw the map preview icon
    QRect const iconRect = position( Icon, option );
    QIcon const icon = qVariantValue<QIcon>( index.data( Qt::DecorationRole ) );
    painter->drawPixmap( iconRect, icon.pixmap( iconRect.size() ) );

    // Draw summary, author, and similar information
    QTextDocument document;
    QRect const textRect = position( Text, option );
    document.setTextWidth( textRect.width() );
    document.setDefaultFont( option.font );
    document.setHtml( text( index ) );

    painter->save();
    painter->translate( textRect.topLeft() );
    painter->setClipRect( 0, 0, textRect.width(), textRect.height() );
    document.documentLayout()->draw( painter, paintContext );
    painter->restore();

    // Draw buttons and installation progress
    if ( index.data( NewstuffModel::IsTransitioning ).toBool() ) {
        qint64 total = qMax( qint64( 1 ), qVariantValue<qint64>( index.data( NewstuffModel::PayloadSize ) ) );
        qint64 progress = qVariantValue<qint64>( index.data( NewstuffModel::DownloadedSize ) );

        QStyleOptionProgressBar progressBarOption;
        progressBarOption.rect = position( ProgressReport, option );
        progressBarOption.minimum = 0;
        progressBarOption.maximum = 100;
        progressBarOption.progress = ( 100.0 * progress / total );
        progressBarOption.text = QString::number( progressBarOption.progress ) + "%";
        progressBarOption.textVisible = true;
        QApplication::style()->drawControl(QStyle::CE_ProgressBar, &progressBarOption, painter);

        QStyleOptionButton cancelButton = button( CancelButton, option );
        QRect installRect = position( CancelButton, option );
        cancelButton.rect = installRect;
        QApplication::style()->drawControl( QStyle::CE_PushButton, &cancelButton, painter );
    } else {
        bool const installed = index.data( NewstuffModel::IsInstalled ).toBool();
        bool const upgradable = index.data( NewstuffModel::IsUpgradable ).toBool();
        Element element = InstallButton;
        if ( installed ) {
            element = upgradable ? UpgradeButton : OpenButton;
        }
        QStyleOptionButton actionButton = button( element, option );
        QRect installRect = position( element, option );
        actionButton.rect = installRect;
        QApplication::style()->drawControl( QStyle::CE_PushButton, &actionButton, painter );

        if ( installed ) {
            QStyleOptionButton removeButton = button( RemoveButton, option );
            QRect removeRect = position( RemoveButton, option );
            removeButton.rect = removeRect;
            QApplication::style()->drawControl( QStyle::CE_PushButton, &removeButton, painter );
        }
    }
}

QSize MapItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    if ( index.column() == 0 ) {
        QSize const iconSize = option.decorationSize;
        QTextDocument doc;
        doc.setDefaultFont( option.font );
        doc.setTextWidth( qMax( 200, m_view->contentsRect().width() - iconSize.width() - buttonWidth( option ) - 3 * m_margin ) );
        doc.setHtml( text( index ) );
        return QSize( iconSize.width() + doc.size().width() + buttonWidth( option ) + 3 * m_margin,
                      2 + qMax( iconSize.height(), qRound( doc.size().height() ) ) );
    }

    return QSize();
}

bool MapItemDelegate::editorEvent(QEvent *event, QAbstractItemModel *, const QStyleOptionViewItem &option, const QModelIndex &index)
{
    if ( ( event->type() == QEvent::MouseButtonRelease ) ) {
        QMouseEvent *mouseEvent = static_cast<QMouseEvent*>( event );
        if ( index.data( NewstuffModel::IsTransitioning ).toBool() ) {
            QRect cancelRect = position( CancelButton, option );
            if ( cancelRect.contains( mouseEvent->pos() ) ) {
                m_newstuffModel->cancel( index.row() );
                return true;
            }
        } else {
            bool const installed = index.data( NewstuffModel::IsInstalled ).toBool();
            bool const upgradable = index.data( NewstuffModel::IsUpgradable ).toBool();

            if ( !installed || upgradable ) {
                QRect installRect = position( InstallButton, option );
                QRect upgradeRect = position( UpgradeButton, option );
                if ( installRect.contains( mouseEvent->pos() ) || upgradeRect.contains( mouseEvent->pos() ) ) {
                    m_newstuffModel->install( index.row() );
                    return true;
                }
            } else if ( installed && !upgradable && m_marbleWidget ) {
                QStringList const files = index.data( NewstuffModel::InstalledFiles ).toStringList();
                foreach( const QString &file, files ) {
                    if ( file.endsWith( ".dgml" ) ) {
                        QFileInfo dgmlFile( file );
                        QDir baseDir = dgmlFile.dir();
                        baseDir.cdUp();
                        baseDir.cdUp();
                        int const index = baseDir.absolutePath().size();
                        QString const mapTheme = dgmlFile.absoluteFilePath().mid( index+1 );
                        m_marbleWidget->setMapThemeId( mapTheme );
                        return true;
                    }
                }
            } else if ( installed ) {
                QRect removeRect = position( RemoveButton, option );
                if ( removeRect.contains( mouseEvent->pos() ) ) {
                    m_newstuffModel->uninstall( index.row() );
                    return true;
                }
            }
        }
    }

    return false;
}

int MapItemDelegate::buttonWidth(const QStyleOptionViewItem &option) const
{
    if ( m_buttonWidth <= 0 ) {
        int const installWidth = option.fontMetrics.size( 0, tr( "Install" ) ).width();
        int const removeWidth = option.fontMetrics.size( 0, tr( "Remove" ) ).width();
        int const cancelWidth = option.fontMetrics.size( 0, tr( "Cancel" ) ).width();
        int const upgradeWidth = option.fontMetrics.size( 0, tr( "Upgrade" ) ).width();
        m_buttonWidth = 2 * m_iconSize + qMax( qMax( installWidth, removeWidth ),
                                           qMax( cancelWidth, upgradeWidth ) );
    }

    return m_buttonWidth;
}

QStyleOptionButton MapItemDelegate::button( Element element, const QStyleOptionViewItem &option ) const
{
    QStyleOptionButton result;
    result.state = option.state;
    result.state &= ~QStyle::State_HasFocus;

    result.palette = option.palette;
    result.features = QStyleOptionButton::None;

    switch (element) {
    case InstallButton:
        result.text = tr( "Install" );
        result.icon = QIcon( ":/marble/dialog-ok.png" );
        result.iconSize = QSize( m_iconSize, m_iconSize );
        break;
    case UpgradeButton:
        result.text = tr( "Update" );
        result.icon = QIcon( ":/marble/system-software-update.png" );
        result.iconSize = QSize( m_iconSize, m_iconSize );
        break;
    case OpenButton:
        result.text = tr( "Open" );
        result.icon = QIcon( ":/marble/document-open.png" );
        result.iconSize = QSize( m_iconSize, m_iconSize );
        break;
    case CancelButton:
        result.text = tr( "Cancel" );
        break;
    case RemoveButton:
        result.text = tr( "Remove" );
        result.icon = QIcon( ":/marble/edit-delete.png" );
        result.iconSize = QSize( m_iconSize, m_iconSize );
        break;
    default:
        // ignored
        break;
    }

    return result;
}

QRect MapItemDelegate::position(Element element, const QStyleOptionViewItem &option ) const
{
    int const width = buttonWidth( option );
    QPoint const topLeftCol1 = option.rect.topLeft() + QPoint( 0, 2 );
    QPoint const topLeftCol2 = topLeftCol1 + QPoint( option.decorationSize.width(), 0 );
    QPoint const topLeftCol3 = topLeftCol2 + QPoint( option.rect.width() - 3 * m_margin - width - option.decorationSize.width(), 0 );
    switch (element) {
    case Icon:
        return QRect( topLeftCol1, option.decorationSize );
    case Text:
        return QRect( topLeftCol2, QSize( topLeftCol3.x()-topLeftCol2.x(), option.rect.height() ) );
    case InstallButton:
    case UpgradeButton:
    case OpenButton:
    {
        QStyleOptionButton optionButton = button( element, option );
        QSize size = option.fontMetrics.size( 0, optionButton.text ) + QSize( 4, 4 );
        QSize buttonSize = QApplication::style()->sizeFromContents( QStyle::CT_PushButton, &optionButton, size );
        buttonSize.setWidth( width );
        return QRect( topLeftCol3, buttonSize );
    }
    case RemoveButton:
    case CancelButton:
    {
        QStyleOptionButton optionButton = button( element, option );
        QSize size = option.fontMetrics.size( 0, optionButton.text ) + QSize( 4, 4 );
        QSize buttonSize = QApplication::style()->sizeFromContents( QStyle::CT_PushButton, &optionButton, size );
        buttonSize.setWidth( width );
        return QRect( topLeftCol3 + QPoint( 0, option.fontMetrics.height() + 8 + m_margin ), buttonSize );
    }
    case ProgressReport:
    {
        QSize const progressSize = QSize( width, option.fontMetrics.height() + 4 );
        return QRect( topLeftCol3 + QPoint( 0, m_margin ), progressSize );
    }
    }

    Q_ASSERT(false);
    return QRect();
}

QString MapItemDelegate::text( const QModelIndex &index ) const
{
    qreal const size = index.data( NewstuffModel::PayloadSize ).toLongLong() / 1024.0 / 1024.0;
    // Fields are typically not longer than 200 characters. Prevent excessive long text here anyway
    // due to bug 319542
    int const maxEntrySize = 4096;
    return QString("
%1
%2

Author: %3
License: %4
Version %5 (%6) %7
")
            .arg( index.data().toString() )
            .arg( index.data( NewstuffModel::Summary ).toString().left( maxEntrySize ) )
            .arg( index.data( NewstuffModel::Author ).toString().left( maxEntrySize ) )
            .arg( index.data( NewstuffModel::License ).toString().left( maxEntrySize ) )
            .arg( index.data( NewstuffModel::Version ).toString().left( maxEntrySize ) )
            .arg( index.data( NewstuffModel::ReleaseDate ).toString().left( maxEntrySize ) )
            .arg( size > 0 ? QString( "%1 MB" ).arg( size, 0, 'f', 1 ) : QString() );
}

}

#include "MapThemeDownloadDialog.moc"
<commit_msg>Fix mouse scope.<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2013 Bernhard Beschow <bbeschow@cs.tu-berlin.de>
// Copyright 2013 Dennis Nienhüser <earthwings@gentoo.org>
//

#include "MapThemeDownloadDialog.h"
#include "ui_MapThemeDownloadDialog.h"

#include "MarbleDirs.h"
#include "NewstuffModel.h"
#include "MarbleWidget.h"

#include <QtGui/QPainter>
#include <QtGui/QTextDocument>
#include <QtGui/QAbstractTextDocumentLayout>
#include <QtGui/QStyledItemDelegate>

namespace Marble
{

class MapItemDelegate : public QStyledItemDelegate
{
public:
    MapItemDelegate( QListView* view, NewstuffModel* newstuffModel, MarbleWidget* marbleWidget );
    void paint( QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const;
    QSize sizeHint( const QStyleOptionViewItem &option, const QModelIndex &index ) const;

protected:
    bool editorEvent( QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index );

private:
    enum Element {
        Icon,
        Text,
        InstallButton,
        UpgradeButton,
        OpenButton,
        CancelButton,
        RemoveButton,
        ProgressReport
    };

    int buttonWidth( const QStyleOptionViewItem &option ) const;
    QStyleOptionButton button( Element element, const QStyleOptionViewItem &option ) const;
    QRect position( Element element, const QStyleOptionViewItem &option ) const;
    QString text( const QModelIndex &index ) const;
    QListView* m_view;
    NewstuffModel* m_newstuffModel;
    mutable int m_buttonWidth;
    int const m_margin;
    int const m_iconSize;
    MarbleWidget* m_marbleWidget;
};

class MapThemeDownloadDialog::Private : public Ui::MapThemeDownloadDialog
{
public:
    Private() :
        m_model()
    {}

    NewstuffModel m_model;
};

MapThemeDownloadDialog::MapThemeDownloadDialog( MarbleWidget* marbleWidget ) :
    QDialog( marbleWidget ),
    d( new Private )
{
    d->setupUi( this );

    d->m_model.setTargetDirectory( MarbleDirs::localPath() + "/maps" );
    d->m_model.setProvider( "http://edu.kde.org/marble/newstuff/maps-4.5.xml" );
    d->m_model.setRegistryFile( MarbleDirs::localPath() + "/newstuff/marble-map-themes.knsregistry", Marble::NewstuffModel::NameTag );

    d->listView->setIconSize( QSize( 130, 130 ) );
    d->listView->setAlternatingRowColors( true );
    d->listView->setUniformItemSizes( false );
    d->listView->setResizeMode( QListView::Adjust );
    d->listView->setItemDelegate( new MapItemDelegate( d->listView, &d->m_model, marbleWidget ) );
    d->listView->setModel( &d->m_model );
}

MapThemeDownloadDialog::~MapThemeDownloadDialog()
{
    delete d;
}

MapItemDelegate::MapItemDelegate( QListView *view , NewstuffModel *newstuffModel, MarbleWidget* marbleWidget ) :
    m_view( view ),
    m_newstuffModel( newstuffModel ),
    m_buttonWidth( 0 ),
    m_margin( 5 ),
    m_iconSize( 16 ),
    m_marbleWidget( marbleWidget )
{
    // nothing to do
}

void MapItemDelegate::paint( QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const
{
    QStyleOptionViewItemV4 styleOption = option;
    styleOption.text = QString();
    QApplication::style()->drawControl(QStyle::CE_ItemViewItem, &styleOption, painter);

    QAbstractTextDocumentLayout::PaintContext paintContext;
    if (styleOption.state & QStyle::State_Selected) {
        paintContext.palette.setColor(QPalette::Text,
            styleOption.palette.color(QPalette::Active, QPalette::HighlightedText));
    }

    // Draw the map preview icon
    QRect const iconRect = position( Icon, option );
    QIcon const icon = qVariantValue<QIcon>( index.data( Qt::DecorationRole ) );
    painter->drawPixmap( iconRect, icon.pixmap( iconRect.size() ) );

    // Draw summary, author, and similar information
    QTextDocument document;
    QRect const textRect = position( Text, option );
    document.setTextWidth( textRect.width() );
    document.setDefaultFont( option.font );
    document.setHtml( text( index ) );

    painter->save();
    painter->translate( textRect.topLeft() );
    painter->setClipRect( 0, 0, textRect.width(), textRect.height() );
    document.documentLayout()->draw( painter, paintContext );
    painter->restore();

    // Draw buttons and installation progress
    if ( index.data( NewstuffModel::IsTransitioning ).toBool() ) {
        qint64 total = qMax( qint64( 1 ), qVariantValue<qint64>( index.data( NewstuffModel::PayloadSize ) ) );
        qint64 progress = qVariantValue<qint64>( index.data( NewstuffModel::DownloadedSize ) );

        QStyleOptionProgressBar progressBarOption;
        progressBarOption.rect = position( ProgressReport, option );
        progressBarOption.minimum = 0;
        progressBarOption.maximum = 100;
        progressBarOption.progress = ( 100.0 * progress / total );
        progressBarOption.text = QString::number( progressBarOption.progress ) + "%";
        progressBarOption.textVisible = true;
        QApplication::style()->drawControl(QStyle::CE_ProgressBar, &progressBarOption, painter);

        QStyleOptionButton cancelButton = button( CancelButton, option );
        QRect installRect = position( CancelButton, option );
        cancelButton.rect = installRect;
        QApplication::style()->drawControl( QStyle::CE_PushButton, &cancelButton, painter );
    } else {
        bool const installed = index.data( NewstuffModel::IsInstalled ).toBool();
        bool const upgradable = index.data( NewstuffModel::IsUpgradable ).toBool();
        Element element = InstallButton;
        if ( installed ) {
            element = upgradable ? UpgradeButton : OpenButton;
        }
        QStyleOptionButton actionButton = button( element, option );
        QRect installRect = position( element, option );
        actionButton.rect = installRect;
        QApplication::style()->drawControl( QStyle::CE_PushButton, &actionButton, painter );

        if ( installed ) {
            QStyleOptionButton removeButton = button( RemoveButton, option );
            QRect removeRect = position( RemoveButton, option );
            removeButton.rect = removeRect;
            QApplication::style()->drawControl( QStyle::CE_PushButton, &removeButton, painter );
        }
    }
}

QSize MapItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    if ( index.column() == 0 ) {
        QSize const iconSize = option.decorationSize;
        QTextDocument doc;
        doc.setDefaultFont( option.font );
        doc.setTextWidth( qMax( 200, m_view->contentsRect().width() - iconSize.width() - buttonWidth( option ) - 3 * m_margin ) );
        doc.setHtml( text( index ) );
        return QSize( iconSize.width() + doc.size().width() + buttonWidth( option ) + 3 * m_margin,
                      2 + qMax( iconSize.height(), qRound( doc.size().height() ) ) );
    }

    return QSize();
}

bool MapItemDelegate::editorEvent(QEvent *event, QAbstractItemModel *, const QStyleOptionViewItem &option, const QModelIndex &index)
{
    if ( ( event->type() == QEvent::MouseButtonRelease ) ) {
        QMouseEvent *mouseEvent = static_cast<QMouseEvent*>( event );
        if ( index.data( NewstuffModel::IsTransitioning ).toBool() ) {
            QRect cancelRect = position( CancelButton, option );
            if ( cancelRect.contains( mouseEvent->pos() ) ) {
                m_newstuffModel->cancel( index.row() );
                return true;
            }
        } else {
            bool const installed = index.data( NewstuffModel::IsInstalled ).toBool();
            bool const upgradable = index.data( NewstuffModel::IsUpgradable ).toBool();

            if ( !installed || upgradable ) {
                QRect installRect = position( InstallButton, option );
                if ( installRect.contains( mouseEvent->pos() ) ) {
                    m_newstuffModel->install( index.row() );
                    return true;
                }
            }

            if ( installed && !upgradable && m_marbleWidget ) {
                QRect openRect = position( OpenButton, option );
                if ( openRect.contains( mouseEvent->pos() ) ) {
                    QStringList const files = index.data( NewstuffModel::InstalledFiles ).toStringList();
                    foreach( const QString &file, files ) {
                        if ( file.endsWith( ".dgml" ) ) {
                            QFileInfo dgmlFile( file );
                            QDir baseDir = dgmlFile.dir();
                            baseDir.cdUp();
                            baseDir.cdUp();
                            int const index = baseDir.absolutePath().size();
                            QString const mapTheme = dgmlFile.absoluteFilePath().mid( index+1 );
                            m_marbleWidget->setMapThemeId( mapTheme );
                            return true;
                        }
                    }
                }
            }

            if ( installed ) {
                QRect removeRect = position( RemoveButton, option );
                if ( removeRect.contains( mouseEvent->pos() ) ) {
                    m_newstuffModel->uninstall( index.row() );
                    return true;
                }
            }
        }
    }

    return false;
}

int MapItemDelegate::buttonWidth(const QStyleOptionViewItem &option) const
{
    if ( m_buttonWidth <= 0 ) {
        int const installWidth = option.fontMetrics.size( 0, tr( "Install" ) ).width();
        int const removeWidth = option.fontMetrics.size( 0, tr( "Remove" ) ).width();
        int const cancelWidth = option.fontMetrics.size( 0, tr( "Cancel" ) ).width();
        int const upgradeWidth = option.fontMetrics.size( 0, tr( "Upgrade" ) ).width();
        m_buttonWidth = 2 * m_iconSize + qMax( qMax( installWidth, removeWidth ),
                                           qMax( cancelWidth, upgradeWidth ) );
    }

    return m_buttonWidth;
}

QStyleOptionButton MapItemDelegate::button( Element element, const QStyleOptionViewItem &option ) const
{
    QStyleOptionButton result;
    result.state = option.state;
    result.state &= ~QStyle::State_HasFocus;

    result.palette = option.palette;
    result.features = QStyleOptionButton::None;

    switch (element) {
    case InstallButton:
        result.text = tr( "Install" );
        result.icon = QIcon( ":/marble/dialog-ok.png" );
        result.iconSize = QSize( m_iconSize, m_iconSize );
        break;
    case UpgradeButton:
        result.text = tr( "Update" );
        result.icon = QIcon( ":/marble/system-software-update.png" );
        result.iconSize = QSize( m_iconSize, m_iconSize );
        break;
    case OpenButton:
        result.text = tr( "Open" );
        result.icon = QIcon( ":/marble/document-open.png" );
        result.iconSize = QSize( m_iconSize, m_iconSize );
        break;
    case CancelButton:
        result.text = tr( "Cancel" );
        break;
    case RemoveButton:
        result.text = tr( "Remove" );
        result.icon = QIcon( ":/marble/edit-delete.png" );
        result.iconSize = QSize( m_iconSize, m_iconSize );
        break;
    default:
        // ignored
        break;
    }

    return result;
}

QRect MapItemDelegate::position(Element element, const QStyleOptionViewItem &option ) const
{
    int const width = buttonWidth( option );
    QPoint const topLeftCol1 = option.rect.topLeft() + QPoint( 0, 2 );
    QPoint const topLeftCol2 = topLeftCol1 + QPoint( option.decorationSize.width(), 0 );
    QPoint const topLeftCol3 = topLeftCol2 + QPoint( option.rect.width() - 3 * m_margin - width - option.decorationSize.width(), 0 );
    switch (element) {
    case Icon:
        return QRect( topLeftCol1, option.decorationSize );
    case Text:
        return QRect( topLeftCol2, QSize( topLeftCol3.x()-topLeftCol2.x(), option.rect.height() ) );
    case InstallButton:
    case UpgradeButton:
    case OpenButton:
    {
        QStyleOptionButton optionButton = button( element, option );
        QSize size = option.fontMetrics.size( 0, optionButton.text ) + QSize( 4, 4 );
        QSize buttonSize = QApplication::style()->sizeFromContents( QStyle::CT_PushButton, &optionButton, size );
        buttonSize.setWidth( width );
        return QRect( topLeftCol3, buttonSize );
    }
    case RemoveButton:
    case CancelButton:
    {
        QStyleOptionButton optionButton = button( element, option );
        QSize size = option.fontMetrics.size( 0, optionButton.text ) + QSize( 4, 4 );
        QSize buttonSize = QApplication::style()->sizeFromContents( QStyle::CT_PushButton, &optionButton, size );
        buttonSize.setWidth( width );
        return QRect( topLeftCol3 + QPoint( 0, option.fontMetrics.height() + 8 + m_margin ), buttonSize );
    }
    case ProgressReport:
    {
        QSize const progressSize = QSize( width, option.fontMetrics.height() + 4 );
        return QRect( topLeftCol3 + QPoint( 0, m_margin ), progressSize );
    }
    }

    Q_ASSERT(false);
    return QRect();
}

QString MapItemDelegate::text( const QModelIndex &index ) const
{
    qreal const size = index.data( NewstuffModel::PayloadSize ).toLongLong() / 1024.0 / 1024.0;
    // Fields are typically not longer than 200 characters. Prevent excessive long text here anyway
    // due to bug 319542
    int const maxEntrySize = 4096;
    return QString("
%1
%2

Author: %3
License: %4
Version %5 (%6) %7
")
            .arg( index.data().toString() )
            .arg( index.data( NewstuffModel::Summary ).toString().left( maxEntrySize ) )
            .arg( index.data( NewstuffModel::Author ).toString().left( maxEntrySize ) )
            .arg( index.data( NewstuffModel::License ).toString().left( maxEntrySize ) )
            .arg( index.data( NewstuffModel::Version ).toString().left( maxEntrySize ) )
            .arg( index.data( NewstuffModel::ReleaseDate ).toString().left( maxEntrySize ) )
            .arg( size > 0 ? QString( "%1 MB" ).arg( size, 0, 'f', 1 ) : QString() );
}

}

#include "MapThemeDownloadDialog.moc"
<|endoftext|>