<commit_before>#include "medGroupBox.h"

class medGroupBoxPrivate
{
public:
    bool collapsible;
    bool collapsed;
};

medGroupBox::medGroupBox(QWidget *parent) :
    QGroupBox(parent),d(new medGroupBoxPrivate)
{
    d->collapsible = false;
    d->collapsed = false;

    connect(this, SIGNAL(toggled(bool)), this, SLOT(setExpanded(bool)));

}

medGroupBox::~medGroupBox()
{
}

bool medGroupBox::isCollapsible()
{
    return d->collapsible;
}

void medGroupBox::setCollapsible(bool collapsible)
{
    d->collapsible = collapsible;
    //change appearance if necessary:
    if (!collapsible)
        setCollapsed(false);
    else if (!isChecked())//hide content
        setCollapsed(true);
}

bool medGroupBox::isCollapsed()
{
    return d->collapsed;
}

void medGroupBox::setCollapsed(bool collapse)
{
    d->collapsed = collapse;
    //only collapse if collapsible,
    //and show whenever it is asked.
    if (d->collapsible || !collapse)
    {
        // show/hide children
        foreach(QObject* child, children())
        {
            if (child->isWidgetType())
                qobject_cast<QWidget*>(child)->setVisible(!collapse);
        }
    }
}

void medGroupBox::setExpanded(bool expand)
{
    setCollapsed(!expand);
}

void medGroupBox::childEvent(QChildEvent *event)
{
    //any added children must be hidden if we are collapsed!
    QObject* child = event->child();
    if (event->added() && child->isWidgetType())
    {
        QWidget* widget = qobject_cast<QWidget*>(child);
        if (d->collapsible && !isChecked())
            widget->hide();
    }
}

<commit_msg>Fixes memory leak on medGroupBox<commit_after>#include "medGroupBox.h"

class medGroupBoxPrivate
{
public:
    bool collapsible;
    bool collapsed;
};

medGroupBox::medGroupBox(QWidget *parent) :
    QGroupBox(parent),d(new medGroupBoxPrivate)
{
    d->collapsible = false;
    d->collapsed = false;

    connect(this, SIGNAL(toggled(bool)), this, SLOT(setExpanded(bool)));

}

medGroupBox::~medGroupBox()
{
    delete d;
    d = NULL;
}

bool medGroupBox::isCollapsible()
{
    return d->collapsible;
}

void medGroupBox::setCollapsible(bool collapsible)
{
    d->collapsible = collapsible;
    //change appearance if necessary:
    if (!collapsible)
        setCollapsed(false);
    else if (!isChecked())//hide content
        setCollapsed(true);
}

bool medGroupBox::isCollapsed()
{
    return d->collapsed;
}

void medGroupBox::setCollapsed(bool collapse)
{
    d->collapsed = collapse;
    //only collapse if collapsible,
    //and show whenever it is asked.
    if (d->collapsible || !collapse)
    {
        // show/hide children
        foreach(QObject* child, children())
        {
            if (child->isWidgetType())
                qobject_cast<QWidget*>(child)->setVisible(!collapse);
        }
    }
}

void medGroupBox::setExpanded(bool expand)
{
    setCollapsed(!expand);
}

void medGroupBox::childEvent(QChildEvent *event)
{
    //any added children must be hidden if we are collapsed!
    QObject* child = event->child();
    if (event->added() && child->isWidgetType())
    {
        QWidget* widget = qobject_cast<QWidget*>(child);
        if (d->collapsible && !isChecked())
            widget->hide();
    }
}

<|endoftext|>


<commit_before>// Copyright 2009 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Log viewer window implementation.
#include "sawbuck/viewer/log_viewer.h"

#include <atlbase.h>
#include <atlframe.h>
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "pcrecpp.h"  // NOLINT
#include "sawbuck/viewer/filtered_log_view.h"
#include "sawbuck/viewer/filter_dialog.h"
#include "sawbuck/viewer/const_config.h"
#include "sawbuck/viewer/preferences.h"

LogViewer::LogViewer(CUpdateUIBase* update_ui)
    : log_list_view_(update_ui),
      stack_trace_list_view_(update_ui),
      log_view_(NULL),
      update_ui_(update_ui) {
  Preferences prefs;
  prefs.ReadStringValue(config::kIncludeReValue, &include_re_, ".*");
  prefs.ReadStringValue(config::kExcludeReValue, &exclude_re_, "");
}

LogViewer::~LogViewer() {
}

int LogViewer::OnCreate(LPCREATESTRUCT create_struct) {
  BOOL bHandled = TRUE;
  Super::OnCreate(WM_CREATE,
                  NULL,
                  reinterpret_cast<LPARAM>(create_struct),
                  bHandled);

  // Create the log list view.
  log_list_view_.Create(m_hWnd);

  // Create the stack trace list view.
  stack_trace_list_view_.Create(m_hWnd);

  log_list_view_.set_stack_trace_view(&stack_trace_list_view_);

  SetDefaultActivePane(SPLIT_PANE_TOP);
  SetSplitterPanes(log_list_view_.m_hWnd, stack_trace_list_view_.m_hWnd);
  SetSplitterExtendedStyle(SPLIT_BOTTOMALIGNED);

  // This is enabled so long as we live.
  update_ui_->UIEnable(ID_LOG_FILTER, true);

  SetMsgHandled(FALSE);
  return 1;
}

LRESULT LogViewer::OnCommand(UINT msg,
                             WPARAM wparam,
                             LPARAM lparam,
                             BOOL& handled) {
  HWND window = GetSplitterPane(GetActivePane());
  return ::SendMessage(window, msg, wparam, lparam);
}

void LogViewer::OnLogFilter(UINT code, int id, CWindow window) {
  FilterDialog dialog;

  if (dialog.DoModal(m_hWnd) == IDOK) {
    std::vector<Filter> filters = dialog.get_filters();
    Preferences pref;
    pref.WriteStringValue(config::kFilterValues,
                          Filter::SerializeFilters(filters));

    // TODO(robertshield): If dialog.get_filters() is empty, we should set it
    // back to the non filtered log view.
    scoped_ptr<FilteredLogView> new_view(new FilteredLogView(log_view_,
                                                             filters));
    log_list_view_.SetLogView(new_view.get());

    filtered_log_view_.reset(new_view.release());
  }
}
<commit_msg>Fix a merge problem that occurred when r94 got checked in.+<commit_after>// Copyright 2009 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Log viewer window implementation.
#include "sawbuck/viewer/log_viewer.h"

#include <atlbase.h>
#include <atlframe.h>
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "pcrecpp.h"  // NOLINT
#include "sawbuck/viewer/filtered_log_view.h"
#include "sawbuck/viewer/filter_dialog.h"
#include "sawbuck/viewer/const_config.h"
#include "sawbuck/viewer/preferences.h"

LogViewer::LogViewer(CUpdateUIBase* update_ui)
    : log_list_view_(update_ui),
      stack_trace_list_view_(update_ui),
      log_view_(NULL),
      update_ui_(update_ui) {
  Preferences prefs;
  prefs.ReadStringValue(config::kIncludeReValue, &include_re_, ".*");
  prefs.ReadStringValue(config::kExcludeReValue, &exclude_re_, "");
}

LogViewer::~LogViewer() {
}

void LogViewer::SetLogView(ILogView* log_view) {
  DCHECK(log_view_ == NULL);
  log_view_ = log_view;
}

int LogViewer::OnCreate(LPCREATESTRUCT create_struct) {
  BOOL bHandled = TRUE;
  Super::OnCreate(WM_CREATE,
                  NULL,
                  reinterpret_cast<LPARAM>(create_struct),
                  bHandled);

  // Create the log list view.
  log_list_view_.Create(m_hWnd);

  // Create the stack trace list view.
  stack_trace_list_view_.Create(m_hWnd);

  log_list_view_.set_stack_trace_view(&stack_trace_list_view_);

  SetDefaultActivePane(SPLIT_PANE_TOP);
  SetSplitterPanes(log_list_view_.m_hWnd, stack_trace_list_view_.m_hWnd);
  SetSplitterExtendedStyle(SPLIT_BOTTOMALIGNED);

  // This is enabled so long as we live.
  update_ui_->UIEnable(ID_LOG_FILTER, true);

  SetMsgHandled(FALSE);
  return 1;
}

LRESULT LogViewer::OnCommand(UINT msg,
                             WPARAM wparam,
                             LPARAM lparam,
                             BOOL& handled) {
  HWND window = GetSplitterPane(GetActivePane());
  return ::SendMessage(window, msg, wparam, lparam);
}

void LogViewer::OnLogFilter(UINT code, int id, CWindow window) {
  FilterDialog dialog;

  if (dialog.DoModal(m_hWnd) == IDOK) {
    std::vector<Filter> filters = dialog.get_filters();
    Preferences pref;
    pref.WriteStringValue(config::kFilterValues,
                          Filter::SerializeFilters(filters));

    // TODO(robertshield): If dialog.get_filters() is empty, we should set it
    // back to the non filtered log view.
    scoped_ptr<FilteredLogView> new_view(new FilteredLogView(log_view_,
                                                             filters));
    log_list_view_.SetLogView(new_view.get());

    filtered_log_view_.reset(new_view.release());
  }
}
<|endoftext|>


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

#include <string>

#include "base/files/file_path.h"
#include "chrome/browser/search/suggestions/proto/suggestions.pb.h"
#include "chrome/browser/search/suggestions/thumbnail_manager.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/testing_profile.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "content/public/test/test_utils.h"
#include "net/test/spawned_test_server/spawned_test_server.h"
#include "net/url_request/url_request_test_util.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gfx/image/image_skia.h"
#include "url/gurl.h"

namespace {

const char kTestUrl1[] = "http://go.com/";
const char kTestUrl2[] = "http://goal.com/";
const char kTestImagePath[] = "files/image_decoding/droids.png";
const char kInvalidImagePath[] = "files/DOESNOTEXIST";

const base::FilePath::CharType kDocRoot[] =
    FILE_PATH_LITERAL("chrome/test/data");

using content::BrowserThread;

class ThumbnailManagerBrowserTest : public InProcessBrowserTest {
 public:
  ThumbnailManagerBrowserTest()
    : num_callback_null_called_(0),
      num_callback_valid_called_(0),
      thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP),
      test_server_(net::SpawnedTestServer::TYPE_HTTP,
                   net::SpawnedTestServer::kLocalhost,
                   base::FilePath(kDocRoot)) {}

  virtual void SetUp() OVERRIDE {
    ASSERT_TRUE(test_server_.Start());

    context_ = new net::TestURLRequestContextGetter(
        BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
    context_->AddRef();
  }

  virtual void TearDown() OVERRIDE {
    BrowserThread::ReleaseSoon(BrowserThread::IO, FROM_HERE, context_);
  }

  void OnThumbnailAvailable(const GURL& url, const SkBitmap* bitmap) {
    if (bitmap) {
      num_callback_valid_called_++;
    } else {
      num_callback_null_called_++;
    }
  }
  int num_callback_null_called_;
  int num_callback_valid_called_;
  content::TestBrowserThreadBundle thread_bundle_;
  net::SpawnedTestServer test_server_;
  net::TestURLRequestContextGetter* context_;
};

}  // namespace

namespace suggestions {

IN_PROC_BROWSER_TEST_F(ThumbnailManagerBrowserTest, FetchThumbnails) {
  SuggestionsProfile suggestions_profile;
  ChromeSuggestion* suggestion = suggestions_profile.add_suggestions();
  suggestion->set_url(kTestUrl1);
  suggestion->set_thumbnail(test_server_.GetURL(kTestImagePath).spec());

  TestingProfile profile;
  ThumbnailManager thumbnail_manager(profile.GetRequestContext());
  thumbnail_manager.InitializeThumbnailMap(suggestions_profile);

  // Fetch existing URL.
  thumbnail_manager.GetPageThumbnail(
      GURL(kTestUrl1),
      base::Bind(&ThumbnailManagerBrowserTest::OnThumbnailAvailable,
                 base::Unretained(this)));

  content::RunMessageLoop();

  EXPECT_EQ(0, num_callback_null_called_);
  EXPECT_EQ(1, num_callback_valid_called_);

  // Fetch non-existing URL.
  thumbnail_manager.GetPageThumbnail(
      GURL(kTestUrl2),
      base::Bind(&ThumbnailManagerBrowserTest::OnThumbnailAvailable,
                 base::Unretained(this)));

  content::RunMessageLoop();

  EXPECT_EQ(1, num_callback_null_called_);
  EXPECT_EQ(1, num_callback_valid_called_);
}

IN_PROC_BROWSER_TEST_F(ThumbnailManagerBrowserTest, FetchThumbnailsMultiple) {
  SuggestionsProfile suggestions_profile;
  ChromeSuggestion* suggestion = suggestions_profile.add_suggestions();
  suggestion->set_url(kTestUrl1);
  suggestion->set_thumbnail(test_server_.GetURL(kTestImagePath).spec());

  TestingProfile profile;
  ThumbnailManager thumbnail_manager(profile.GetRequestContext());
  thumbnail_manager.InitializeThumbnailMap(suggestions_profile);

  // Fetch non-existing URL, and add more while request is in flight.
  for (int i = 0 ; i < 5; i++) {
    thumbnail_manager.GetPageThumbnail(
      GURL(kTestUrl1),
      base::Bind(&ThumbnailManagerBrowserTest::OnThumbnailAvailable,
                 base::Unretained(this)));
  }

  content::RunMessageLoop();

  EXPECT_EQ(0, num_callback_null_called_);
  EXPECT_EQ(5, num_callback_valid_called_);
}

IN_PROC_BROWSER_TEST_F(ThumbnailManagerBrowserTest, FetchThumbnailsInvalid) {
  SuggestionsProfile suggestions_profile;
  ChromeSuggestion* suggestion = suggestions_profile.add_suggestions();
  suggestion->set_url(kTestUrl1);
  suggestion->set_thumbnail(test_server_.GetURL(kInvalidImagePath).spec());

  TestingProfile profile;
  ThumbnailManager thumbnail_manager(profile.GetRequestContext());
  thumbnail_manager.InitializeThumbnailMap(suggestions_profile);

  // Fetch existing URL that has invalid thumbnail.
  thumbnail_manager.GetPageThumbnail(
      GURL(kTestUrl1),
      base::Bind(&ThumbnailManagerBrowserTest::OnThumbnailAvailable,
                 base::Unretained(this)));

  content::RunMessageLoop();

  EXPECT_EQ(1, num_callback_null_called_);
  EXPECT_EQ(0, num_callback_valid_called_);
}

}  // namespace suggestions
<commit_msg>[SuggestionsService] Fix ThumbnailManagerBrowserTest, which were not running<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <string>

#include "base/files/file_path.h"
#include "base/run_loop.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/search/suggestions/proto/suggestions.pb.h"
#include "chrome/browser/search/suggestions/thumbnail_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "net/test/spawned_test_server/spawned_test_server.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gfx/image/image_skia.h"
#include "url/gurl.h"

namespace {

const char kTestUrl1[] = "http://go.com/";
const char kTestUrl2[] = "http://goal.com/";
const char kTestImagePath[] = "files/image_decoding/droids.png";
const char kInvalidImagePath[] = "files/DOESNOTEXIST";

const base::FilePath::CharType kDocRoot[] =
    FILE_PATH_LITERAL("chrome/test/data");

class ThumbnailManagerBrowserTest : public InProcessBrowserTest {
 public:
  ThumbnailManagerBrowserTest()
      : num_callback_null_called_(0),
        num_callback_valid_called_(0),
        test_server_(net::SpawnedTestServer::TYPE_HTTP,
                     net::SpawnedTestServer::kLocalhost,
                     base::FilePath(kDocRoot)) {}

  virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
    ASSERT_TRUE(test_server_.Start());
    InProcessBrowserTest::SetUpInProcessBrowserTestFixture();
  }

  void OnThumbnailAvailable(base::RunLoop* loop, const GURL& url,
                            const SkBitmap* bitmap) {
    if (bitmap) {
      num_callback_valid_called_++;
    } else {
      num_callback_null_called_++;
    }
    loop->Quit();
  }

  int num_callback_null_called_;
  int num_callback_valid_called_;
  net::SpawnedTestServer test_server_;
};

}  // namespace

namespace suggestions {

IN_PROC_BROWSER_TEST_F(ThumbnailManagerBrowserTest, FetchThumbnails) {
  SuggestionsProfile suggestions_profile;
  ChromeSuggestion* suggestion = suggestions_profile.add_suggestions();
  suggestion->set_url(kTestUrl1);
  suggestion->set_thumbnail(test_server_.GetURL(kTestImagePath).spec());

  ThumbnailManager thumbnail_manager(browser()->profile()->GetRequestContext());
  thumbnail_manager.InitializeThumbnailMap(suggestions_profile);

  base::RunLoop run_loop;
  // Fetch existing URL.
  thumbnail_manager.GetPageThumbnail(
      GURL(kTestUrl1),
      base::Bind(&ThumbnailManagerBrowserTest::OnThumbnailAvailable,
                 base::Unretained(this), &run_loop));
  run_loop.Run();

  EXPECT_EQ(0, num_callback_null_called_);
  EXPECT_EQ(1, num_callback_valid_called_);

  base::RunLoop run_loop2;
  thumbnail_manager.GetPageThumbnail(
      GURL(kTestUrl2),
      base::Bind(&ThumbnailManagerBrowserTest::OnThumbnailAvailable,
                 base::Unretained(this), &run_loop2));
  run_loop2.Run();

  EXPECT_EQ(1, num_callback_null_called_);
  EXPECT_EQ(1, num_callback_valid_called_);
}

IN_PROC_BROWSER_TEST_F(ThumbnailManagerBrowserTest, FetchThumbnailsMultiple) {
  SuggestionsProfile suggestions_profile;
  ChromeSuggestion* suggestion = suggestions_profile.add_suggestions();
  suggestion->set_url(kTestUrl1);
  suggestion->set_thumbnail(test_server_.GetURL(kTestImagePath).spec());

  ThumbnailManager thumbnail_manager(browser()->profile()->GetRequestContext());
  thumbnail_manager.InitializeThumbnailMap(suggestions_profile);

  base::RunLoop run_loop;
  // Fetch non-existing URL, and add more while request is in flight.
  for (int i = 0; i < 5; i++) {
    thumbnail_manager.GetPageThumbnail(
        GURL(kTestUrl1),
        base::Bind(&ThumbnailManagerBrowserTest::OnThumbnailAvailable,
                   base::Unretained(this), &run_loop));
  }
  run_loop.Run();

  EXPECT_EQ(0, num_callback_null_called_);
  EXPECT_EQ(5, num_callback_valid_called_);
}

IN_PROC_BROWSER_TEST_F(ThumbnailManagerBrowserTest, FetchThumbnailsInvalid) {
  SuggestionsProfile suggestions_profile;
  ChromeSuggestion* suggestion = suggestions_profile.add_suggestions();
  suggestion->set_url(kTestUrl1);
  suggestion->set_thumbnail(test_server_.GetURL(kInvalidImagePath).spec());

  ThumbnailManager thumbnail_manager(browser()->profile()->GetRequestContext());
  thumbnail_manager.InitializeThumbnailMap(suggestions_profile);

  base::RunLoop run_loop;
  // Fetch existing URL that has invalid thumbnail.
  thumbnail_manager.GetPageThumbnail(
      GURL(kTestUrl1),
      base::Bind(&ThumbnailManagerBrowserTest::OnThumbnailAvailable,
                 base::Unretained(this), &run_loop));
  run_loop.Run();

  EXPECT_EQ(1, num_callback_null_called_);
  EXPECT_EQ(0, num_callback_valid_called_);
}

}  // namespace suggestions
<|endoftext|>


<commit_before><commit_msg>Translate message to English<commit_after><|endoftext|>


<commit_before>// Copyright 2013 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/common/extensions/manifest_handlers/ui_overrides_handler.h"

#include "base/memory/scoped_ptr.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "extensions/common/error_utils.h"
#include "extensions/common/extension_messages.h"
#include "extensions/common/feature_switch.h"
#include "extensions/common/manifest_constants.h"
#include "extensions/common/permissions/manifest_permission.h"
#include "extensions/common/permissions/permissions_data.h"
#include "extensions/common/permissions/permissions_info.h"
#include "grit/generated_resources.h"
#include "ipc/ipc_message.h"
#include "ui/base/l10n/l10n_util.h"

using extensions::api::manifest_types::ChromeUIOverrides;

namespace extensions {

// The manifest permission implementation supports a permission for overriding
// the bookmark UI.
class UIOverridesHandler::ManifestPermissionImpl : public ManifestPermission {
 public:
  explicit ManifestPermissionImpl(bool override_bookmarks_ui_permission)
      : override_bookmarks_ui_permission_(override_bookmarks_ui_permission) {}

  // extensions::ManifestPermission overrides.
  virtual std::string name() const OVERRIDE {
    return manifest_keys::kUIOverride;
  }

  virtual std::string id() const OVERRIDE {
    return name();
  }

  virtual bool HasMessages() const OVERRIDE {
    return override_bookmarks_ui_permission_;
  }

  virtual PermissionMessages GetMessages() const OVERRIDE {
    PermissionMessages result;
    if (override_bookmarks_ui_permission_) {
      result.push_back(PermissionMessage(
          PermissionMessage::kOverrideBookmarksUI,
          l10n_util::GetStringUTF16(
              IDS_EXTENSION_PROMPT_WARNING_OVERRIDE_BOOKMARKS_UI)));
    }
    return result;
  }

  virtual bool FromValue(const base::Value* value) OVERRIDE {
    return value && value->GetAsBoolean(&override_bookmarks_ui_permission_);
  }

  virtual scoped_ptr<base::Value> ToValue() const OVERRIDE {
    return scoped_ptr<base::Value>(
        new base::FundamentalValue(override_bookmarks_ui_permission_)).Pass();
  }

  virtual ManifestPermission* Clone() const OVERRIDE {
    return scoped_ptr<ManifestPermissionImpl>(
        new ManifestPermissionImpl(
            override_bookmarks_ui_permission_)).release();
  }

  virtual ManifestPermission* Diff(const ManifestPermission* rhs) const
      OVERRIDE {
    const ManifestPermissionImpl* other =
        static_cast<const ManifestPermissionImpl*>(rhs);

    return scoped_ptr<ManifestPermissionImpl>(new ManifestPermissionImpl(
        override_bookmarks_ui_permission_ &&
        !other->override_bookmarks_ui_permission_)).release();
  }

  virtual ManifestPermission* Union(const ManifestPermission* rhs) const
      OVERRIDE {
    const ManifestPermissionImpl* other =
        static_cast<const ManifestPermissionImpl*>(rhs);

    return scoped_ptr<ManifestPermissionImpl>(new ManifestPermissionImpl(
        override_bookmarks_ui_permission_ ||
        other->override_bookmarks_ui_permission_)).release();
  }

  virtual ManifestPermission* Intersect(const ManifestPermission* rhs) const
      OVERRIDE {
    const ManifestPermissionImpl* other =
        static_cast<const ManifestPermissionImpl*>(rhs);

    return scoped_ptr<ManifestPermissionImpl>(new ManifestPermissionImpl(
        override_bookmarks_ui_permission_ &&
        other->override_bookmarks_ui_permission_)).release();
  }

  virtual bool Contains(const ManifestPermission* rhs) const OVERRIDE {
    const ManifestPermissionImpl* other =
        static_cast<const ManifestPermissionImpl*>(rhs);

    return !other->override_bookmarks_ui_permission_ ||
        override_bookmarks_ui_permission_;
  }

  virtual bool Equal(const ManifestPermission* rhs) const OVERRIDE {
    const ManifestPermissionImpl* other =
        static_cast<const ManifestPermissionImpl*>(rhs);

    return override_bookmarks_ui_permission_ ==
        other->override_bookmarks_ui_permission_;
  }

  virtual void Write(IPC::Message* m) const OVERRIDE {
    IPC::WriteParam(m, override_bookmarks_ui_permission_);
  }

  virtual bool Read(const IPC::Message* m, PickleIterator* iter) OVERRIDE {
    return IPC::ReadParam(m, iter, &override_bookmarks_ui_permission_);
  }

  virtual void Log(std::string* log) const OVERRIDE {
    IPC::LogParam(override_bookmarks_ui_permission_, log);
  }

 private:
  bool override_bookmarks_ui_permission_;
};

UIOverrides::UIOverrides() {}

UIOverrides::~UIOverrides() {}

const UIOverrides* UIOverrides::Get(const Extension* extension) {
  return static_cast<UIOverrides*>(
      extension->GetManifestData(manifest_keys::kUIOverride));
}

bool UIOverrides::RemovesBookmarkButton(const Extension* extension) {
  const UIOverrides* ui_overrides = Get(extension);
  return ui_overrides && ui_overrides->bookmarks_ui &&
      ui_overrides->bookmarks_ui->remove_button &&
      *ui_overrides->bookmarks_ui->remove_button;
}

bool UIOverrides::RemovesBookmarkShortcut(const Extension* extension) {
  const UIOverrides* ui_overrides = Get(extension);
  return ui_overrides && ui_overrides->bookmarks_ui &&
      ui_overrides->bookmarks_ui->remove_bookmark_shortcut &&
      *ui_overrides->bookmarks_ui->remove_bookmark_shortcut;
}

bool UIOverrides::RemovesBookmarkOpenPagesShortcut(const Extension* extension) {
  const UIOverrides* ui_overrides = Get(extension);
  return ui_overrides && ui_overrides->bookmarks_ui &&
      ui_overrides->bookmarks_ui->remove_bookmark_open_pages_shortcut &&
      *ui_overrides->bookmarks_ui->remove_bookmark_open_pages_shortcut;
}

UIOverridesHandler::UIOverridesHandler() {}

UIOverridesHandler::~UIOverridesHandler() {}

bool UIOverridesHandler::Parse(Extension* extension, base::string16* error) {
  const base::Value* dict = NULL;
  CHECK(extension->manifest()->Get(manifest_keys::kUIOverride, &dict));
  scoped_ptr<ChromeUIOverrides> overrides(
      ChromeUIOverrides::FromValue(*dict, error));
  if (!overrides)
    return false;

  scoped_ptr<UIOverrides> info(new UIOverrides);
  info->bookmarks_ui.swap(overrides->bookmarks_ui);
  if (!info->bookmarks_ui) {
    *error = ErrorUtils::FormatErrorMessageUTF16(
        manifest_errors::kInvalidEmptyDictionary,
        manifest_keys::kUIOverride);
    return false;
  }
  UIOverrides* assigned_ui_overrides = info.get();
  extension->SetManifestData(manifest_keys::kUIOverride, info.release());
  assigned_ui_overrides->manifest_permission.reset(new ManifestPermissionImpl(
      UIOverrides::RemovesBookmarkButton(extension)));
  return true;
}

bool UIOverridesHandler::Validate(const Extension* extension,
                                  std::string* error,
                                  std::vector<InstallWarning>* warnings) const {
  const UIOverrides* ui_overrides = UIOverrides::Get(extension);

  if (ui_overrides && ui_overrides->bookmarks_ui) {
    if (!FeatureSwitch::enable_override_bookmarks_ui()->IsEnabled()) {
      warnings->push_back(InstallWarning(
          ErrorUtils::FormatErrorMessage(
              manifest_errors::kUnrecognizedManifestProperty,
              manifest_keys::kBookmarkUI,
              manifest_keys::kUIOverride)));
    }
  }

  return true;
}

ManifestPermission* UIOverridesHandler::CreatePermission() {
  return new ManifestPermissionImpl(false);
}

ManifestPermission* UIOverridesHandler::CreateInitialRequiredPermission(
    const Extension* extension) {
  const UIOverrides* data = UIOverrides::Get(extension);
  if (data)
    return data->manifest_permission->Clone();
  return NULL;
}
const std::vector<std::string> UIOverridesHandler::Keys() const {
  return SingleKey(manifest_keys::kUIOverride);
}

}  // namespace extensions
<commit_msg>Enforce "override bookmarks UI" manifest permissions for bookmark shortcut overrides<commit_after>// Copyright 2013 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/common/extensions/manifest_handlers/ui_overrides_handler.h"

#include "base/memory/scoped_ptr.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "extensions/common/error_utils.h"
#include "extensions/common/extension_messages.h"
#include "extensions/common/feature_switch.h"
#include "extensions/common/manifest_constants.h"
#include "extensions/common/permissions/manifest_permission.h"
#include "extensions/common/permissions/permissions_data.h"
#include "extensions/common/permissions/permissions_info.h"
#include "grit/generated_resources.h"
#include "ipc/ipc_message.h"
#include "ui/base/l10n/l10n_util.h"

using extensions::api::manifest_types::ChromeUIOverrides;

namespace extensions {

// The manifest permission implementation supports a permission for overriding
// the bookmark UI.
class UIOverridesHandler::ManifestPermissionImpl : public ManifestPermission {
 public:
  explicit ManifestPermissionImpl(bool override_bookmarks_ui_permission)
      : override_bookmarks_ui_permission_(override_bookmarks_ui_permission) {}

  // extensions::ManifestPermission overrides.
  virtual std::string name() const OVERRIDE {
    return manifest_keys::kUIOverride;
  }

  virtual std::string id() const OVERRIDE {
    return name();
  }

  virtual bool HasMessages() const OVERRIDE {
    return override_bookmarks_ui_permission_;
  }

  virtual PermissionMessages GetMessages() const OVERRIDE {
    PermissionMessages result;
    if (override_bookmarks_ui_permission_) {
      result.push_back(PermissionMessage(
          PermissionMessage::kOverrideBookmarksUI,
          l10n_util::GetStringUTF16(
              IDS_EXTENSION_PROMPT_WARNING_OVERRIDE_BOOKMARKS_UI)));
    }
    return result;
  }

  virtual bool FromValue(const base::Value* value) OVERRIDE {
    return value && value->GetAsBoolean(&override_bookmarks_ui_permission_);
  }

  virtual scoped_ptr<base::Value> ToValue() const OVERRIDE {
    return scoped_ptr<base::Value>(
        new base::FundamentalValue(override_bookmarks_ui_permission_)).Pass();
  }

  virtual ManifestPermission* Clone() const OVERRIDE {
    return scoped_ptr<ManifestPermissionImpl>(
        new ManifestPermissionImpl(
            override_bookmarks_ui_permission_)).release();
  }

  virtual ManifestPermission* Diff(const ManifestPermission* rhs) const
      OVERRIDE {
    const ManifestPermissionImpl* other =
        static_cast<const ManifestPermissionImpl*>(rhs);

    return scoped_ptr<ManifestPermissionImpl>(new ManifestPermissionImpl(
        override_bookmarks_ui_permission_ &&
        !other->override_bookmarks_ui_permission_)).release();
  }

  virtual ManifestPermission* Union(const ManifestPermission* rhs) const
      OVERRIDE {
    const ManifestPermissionImpl* other =
        static_cast<const ManifestPermissionImpl*>(rhs);

    return scoped_ptr<ManifestPermissionImpl>(new ManifestPermissionImpl(
        override_bookmarks_ui_permission_ ||
        other->override_bookmarks_ui_permission_)).release();
  }

  virtual ManifestPermission* Intersect(const ManifestPermission* rhs) const
      OVERRIDE {
    const ManifestPermissionImpl* other =
        static_cast<const ManifestPermissionImpl*>(rhs);

    return scoped_ptr<ManifestPermissionImpl>(new ManifestPermissionImpl(
        override_bookmarks_ui_permission_ &&
        other->override_bookmarks_ui_permission_)).release();
  }

  virtual bool Contains(const ManifestPermission* rhs) const OVERRIDE {
    const ManifestPermissionImpl* other =
        static_cast<const ManifestPermissionImpl*>(rhs);

    return !other->override_bookmarks_ui_permission_ ||
        override_bookmarks_ui_permission_;
  }

  virtual bool Equal(const ManifestPermission* rhs) const OVERRIDE {
    const ManifestPermissionImpl* other =
        static_cast<const ManifestPermissionImpl*>(rhs);

    return override_bookmarks_ui_permission_ ==
        other->override_bookmarks_ui_permission_;
  }

  virtual void Write(IPC::Message* m) const OVERRIDE {
    IPC::WriteParam(m, override_bookmarks_ui_permission_);
  }

  virtual bool Read(const IPC::Message* m, PickleIterator* iter) OVERRIDE {
    return IPC::ReadParam(m, iter, &override_bookmarks_ui_permission_);
  }

  virtual void Log(std::string* log) const OVERRIDE {
    IPC::LogParam(override_bookmarks_ui_permission_, log);
  }

 private:
  bool override_bookmarks_ui_permission_;
};

UIOverrides::UIOverrides() {}

UIOverrides::~UIOverrides() {}

const UIOverrides* UIOverrides::Get(const Extension* extension) {
  return static_cast<UIOverrides*>(
      extension->GetManifestData(manifest_keys::kUIOverride));
}

bool UIOverrides::RemovesBookmarkButton(const Extension* extension) {
  const UIOverrides* ui_overrides = Get(extension);
  return ui_overrides && ui_overrides->bookmarks_ui &&
      ui_overrides->bookmarks_ui->remove_button &&
      *ui_overrides->bookmarks_ui->remove_button;
}

bool UIOverrides::RemovesBookmarkShortcut(const Extension* extension) {
  const UIOverrides* ui_overrides = Get(extension);
  return ui_overrides && ui_overrides->bookmarks_ui &&
      ui_overrides->bookmarks_ui->remove_bookmark_shortcut &&
      *ui_overrides->bookmarks_ui->remove_bookmark_shortcut;
}

bool UIOverrides::RemovesBookmarkOpenPagesShortcut(const Extension* extension) {
  const UIOverrides* ui_overrides = Get(extension);
  return ui_overrides && ui_overrides->bookmarks_ui &&
      ui_overrides->bookmarks_ui->remove_bookmark_open_pages_shortcut &&
      *ui_overrides->bookmarks_ui->remove_bookmark_open_pages_shortcut;
}

UIOverridesHandler::UIOverridesHandler() {}

UIOverridesHandler::~UIOverridesHandler() {}

bool UIOverridesHandler::Parse(Extension* extension, base::string16* error) {
  const base::Value* dict = NULL;
  CHECK(extension->manifest()->Get(manifest_keys::kUIOverride, &dict));
  scoped_ptr<ChromeUIOverrides> overrides(
      ChromeUIOverrides::FromValue(*dict, error));
  if (!overrides)
    return false;

  scoped_ptr<UIOverrides> info(new UIOverrides);
  info->bookmarks_ui.swap(overrides->bookmarks_ui);
  if (!info->bookmarks_ui) {
    *error = ErrorUtils::FormatErrorMessageUTF16(
        manifest_errors::kInvalidEmptyDictionary,
        manifest_keys::kUIOverride);
    return false;
  }
  info->manifest_permission.reset(new ManifestPermissionImpl(
      info->bookmarks_ui.get() != NULL));
  extension->SetManifestData(manifest_keys::kUIOverride, info.release());
  return true;
}

bool UIOverridesHandler::Validate(const Extension* extension,
                                  std::string* error,
                                  std::vector<InstallWarning>* warnings) const {
  const UIOverrides* ui_overrides = UIOverrides::Get(extension);

  if (ui_overrides && ui_overrides->bookmarks_ui) {
    if (!FeatureSwitch::enable_override_bookmarks_ui()->IsEnabled()) {
      warnings->push_back(InstallWarning(
          ErrorUtils::FormatErrorMessage(
              manifest_errors::kUnrecognizedManifestProperty,
              manifest_keys::kBookmarkUI,
              manifest_keys::kUIOverride)));
    }
  }

  return true;
}

ManifestPermission* UIOverridesHandler::CreatePermission() {
  return new ManifestPermissionImpl(false);
}

ManifestPermission* UIOverridesHandler::CreateInitialRequiredPermission(
    const Extension* extension) {
  const UIOverrides* data = UIOverrides::Get(extension);
  if (data)
    return data->manifest_permission->Clone();
  return NULL;
}
const std::vector<std::string> UIOverridesHandler::Keys() const {
  return SingleKey(manifest_keys::kUIOverride);
}

}  // namespace extensions
<|endoftext|>


<commit_before>// Copyright (c) 2018 ASMlover. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
//  * Redistributions of source code must retain the above copyright
//    notice, this list ofconditions and the following disclaimer.
//
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in
//    the documentation and/or other materialsprovided with the
//    distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include "nyx_filter_manager.h"

namespace nyx { namespace filter {

void filter_manager::delete_filter_randomly(void) {
}

filter_ptr filter_manager::from_object(PyObject* v) {
  filter_ptr filter;
  return filter;
}

filter_ptr filter_manager::from_tuple(PyObject* v) {
  filter_ptr filter;
  return filter;
}

filter_ptr filter_manager::from_list(PyObject* v) {
  filter_ptr filter;
  return filter;
}

int filter_manager::add_filter(const py::object& args) {
  return 0;
}

int filter_manager::add_str_filter(
    const std::string& s, const py::object& args) {
  return 0;
}

void filter_manager::del_filter(int filter) {
  filters_.erase(filter);
  auto it = int_filters_.find(filter);
  if (it != int_filters_.end()) {
    str_filters_.erase(it->second);
    int_filters_.erase(it);
  }
}

filter_ptr filter_manager::get_filter(int index) const {
  filter_ptr filter;
  auto it = filters_.find(index);
  if (it != filters_.end())
    filter = it->second;
  return filter;
}

int filter_manager::get_filter_index(const std::string& s) const {
  auto it = str_filters_.find(s);
  if (it != str_filters_.end())
    return it->second;
  return -1;
}

void filter_manager::print_filter(int index) {
  auto it = filters_.find(index);
  if (it != filters_.end())
    it->second->print();
}

}}
<commit_msg>:construction: chore(filter): updated the implementation of filter manager<commit_after>// Copyright (c) 2018 ASMlover. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
//  * Redistributions of source code must retain the above copyright
//    notice, this list ofconditions and the following disclaimer.
//
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in
//    the documentation and/or other materialsprovided with the
//    distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <cstdlib>
#include <ctime>
#include "nyx_int_filter.h"
#include "nyx_float_filter.h"
#include "nyx_str_filter.h"
#include "nyx_filter_manager.h"

namespace nyx { namespace filter {

static const char* kUsageError = "Usage Error";

void filter_manager::delete_filter_randomly(void) {
  if (str_filters_.empty())
    return;

  std::srand(std::time(0));
  int bucket;
  int bucket_size;
  do {
    bucket = std::rand() % str_filters_.bucket_count();
  } while ((bucket_size = str_filters_.bucket_size(bucket)) == 0);
  auto it = str_filters_.begin(bucket);
  std::advance(it, std::rand() % bucket_size);
  del_filter(it->second);
}

filter_ptr filter_manager::from_object(PyObject* v) {
  filter_ptr filter;
  if (!PyTuple_Check(v) || (Py_SIZE(v) != 3)) {
    PyErr_SetString(PyExc_TypeError, kUsageError);
    return filter;
  }
  auto* type = PyTuple_GET_ITEM(v, 0);
  auto* key = PyTuple_GET_ITEM(v, 1);
  auto* val = PyTuple_GET_ITEM(v, 2);
  if (!PyInt_Check(type) || !PyString_Check(key)) {
    PyErr_SetString(PyExc_TypeError, kUsageError);
    return filter;
  }

  auto raw_type = PyInt_AsSsize_t(type);
  if (raw_type == -1)
    return filter;
  const char* raw_key = PyString_AsString(key);
  if (raw_key == nullptr)
    return filter;

  if (PyInt_Check(val)) {
    auto raw_val = PyInt_AsSsize_t(val);
    if (raw_val == -1 && PyErr_Occurred())
      return filter;
    filter = std::make_shared<int_filter>(
        static_cast<filter::filter_type>(raw_type), raw_key, raw_val);
    return filter;
  }
  else if (PyFloat_Check(val)) {
    auto raw_val = PyFloat_AsDouble(val);
    if (raw_val == -1.f && PyErr_Occurred())
      return filter;
    filter = std::make_shared<float_filter>(
        static_cast<filter::filter_type>(raw_type), raw_key, raw_val);
    return filter;
  }
  else if (PyString_Check(val)) {
    auto raw_val = PyString_AsString(val);
    if (raw_val == nullptr)
      return filter;
    filter = std::make_shared<str_filter>(
        static_cast<filter::filter_type>(raw_type), raw_key, raw_val);
    return filter;
  }
  else {
    PyErr_SetString(PyExc_TypeError, kUsageError);
    return filter;
  }

  return filter;
}

filter_ptr filter_manager::from_tuple(PyObject* v) {
  filter_ptr filter;
  return filter;
}

filter_ptr filter_manager::from_list(PyObject* v) {
  filter_ptr filter;
  return filter;
}

int filter_manager::add_filter(const py::object& args) {
  return 0;
}

int filter_manager::add_str_filter(
    const std::string& s, const py::object& args) {
  return 0;
}

void filter_manager::del_filter(int filter) {
  filters_.erase(filter);
  auto it = int_filters_.find(filter);
  if (it != int_filters_.end()) {
    str_filters_.erase(it->second);
    int_filters_.erase(it);
  }
}

filter_ptr filter_manager::get_filter(int index) const {
  filter_ptr filter;
  auto it = filters_.find(index);
  if (it != filters_.end())
    filter = it->second;
  return filter;
}

int filter_manager::get_filter_index(const std::string& s) const {
  auto it = str_filters_.find(s);
  if (it != str_filters_.end())
    return it->second;
  return -1;
}

void filter_manager::print_filter(int index) {
  auto it = filters_.find(index);
  if (it != filters_.end())
    it->second->print();
}

}}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: autofmt.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2004-08-23 09:33:03 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library 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 this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef SC_AUTOFMT_HXX
#define SC_AUTOFMT_HXX

#ifndef _VIRDEV_HXX //autogen
#include <vcl/virdev.hxx>
#endif
#ifndef SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#ifndef SV_LSTBOX_HXX
#include <vcl/lstbox.hxx>
#endif
#ifndef SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
#ifndef SV_MOREBTN_HXX
#include <vcl/morebtn.hxx>
#endif
#ifndef _DIALOG_HXX //autogen
#include <vcl/dialog.hxx>
#endif
#ifndef _SVTOOLS_SCRIPTEDTEXT_HXX
#include <svtools/scriptedtext.hxx>
#endif
#ifndef SVX_FRAMELINKARRAY_HXX
#include <svx/framelinkarray.hxx>
#endif

#ifndef INCLUDED_SCDLLAPI_H
#include "scdllapi.h"
#endif

//------------------------------------------------------------------------

class ScAutoFormat;
class ScAutoFormatData;
class SvxBoxItem;
class SvxLineItem;
class AutoFmtPreview; // s.u.
class SvNumberFormatter;
class ScDocument;

//------------------------------------------------------------------------

enum AutoFmtLine { TOP_LINE, BOTTOM_LINE, LEFT_LINE, RIGHT_LINE };

//========================================================================

//CHINA001 class ScAutoFormatDlg : public ModalDialog
//CHINA001 {
//CHINA001 public:
//CHINA001 ScAutoFormatDlg( Window*                 pParent,
//CHINA001 ScAutoFormat*                pAutoFormat,
//CHINA001 const ScAutoFormatData*    pSelFormatData,
//CHINA001 ScDocument*                pDoc );
//CHINA001 ~ScAutoFormatDlg();
//CHINA001
//CHINA001 USHORT GetIndex() const { return nIndex; }
//CHINA001 String GetCurrFormatName();
//CHINA001
//CHINA001 private:
//CHINA001 FixedLine       aFlFormat;
//CHINA001 ListBox          aLbFormat;
//CHINA001 AutoFmtPreview*  pWndPreview;
//CHINA001 OKButton     aBtnOk;
//CHINA001 CancelButton aBtnCancel;
//CHINA001 HelpButton       aBtnHelp;
//CHINA001 PushButton       aBtnAdd;
//CHINA001 PushButton       aBtnRemove;
//CHINA001 MoreButton       aBtnMore;
//CHINA001 FixedLine       aFlFormatting;
//CHINA001 CheckBox     aBtnNumFormat;
//CHINA001 CheckBox     aBtnBorder;
//CHINA001 CheckBox     aBtnFont;
//CHINA001 CheckBox     aBtnPattern;
//CHINA001 CheckBox     aBtnAlignment;
//CHINA001 CheckBox     aBtnAdjust;
//CHINA001 PushButton       aBtnRename;
//CHINA001 String           aStrTitle;
//CHINA001 String           aStrLabel;
//CHINA001 String           aStrClose;
//CHINA001 String           aStrDelTitle;
//CHINA001 String           aStrDelMsg;
//CHINA001 String           aStrRename;
//CHINA001
//CHINA001 //------------------------
//CHINA001 ScAutoFormat*            pFormat;
//CHINA001 const ScAutoFormatData*  pSelFmtData;
//CHINA001 USHORT                   nIndex;
//CHINA001 BOOL                 bCoreDataChanged;
//CHINA001 BOOL                 bFmtInserted;
//CHINA001
//CHINA001 void Init            ();
//CHINA001 void UpdateChecks    ();
//CHINA001 //------------------------
//CHINA001 DECL_LINK( CheckHdl, Button * );
//CHINA001 DECL_LINK( AddHdl, void * );
//CHINA001 DECL_LINK( RemoveHdl, void * );
//CHINA001 DECL_LINK( SelFmtHdl, void * );
//CHINA001 DECL_LINK( CloseHdl, PushButton * );
//CHINA001 DECL_LINK( DblClkHdl, void * );
//CHINA001 DECL_LINK( RenameHdl, void *);
//CHINA001
//CHINA001 };
//CHINA001
//========================================================================

class SC_DLLPUBLIC AutoFmtPreview : public Window
{
public:
            AutoFmtPreview( Window* pParent, const ResId& rRes, ScDocument* pDoc );
            ~AutoFmtPreview();

    void NotifyChange( ScAutoFormatData* pNewData );

protected:
    virtual void Paint( const Rectangle& rRect );

private:
    ScAutoFormatData*       pCurData;
    VirtualDevice           aVD;
    SvtScriptedTextHelper   aScriptedText;
    ::com::sun::star::uno::Reference< ::com::sun::star::i18n::XBreakIterator > xBreakIter;
    BOOL                    bFitWidth;
    svx::frame::Array       maArray;            /// Implementation to draw the frame borders.
    Size                    aPrvSize;
    long                    mnLabelColWidth;
    long                    mnDataColWidth1;
    long                    mnDataColWidth2;
    long                    mnRowHeight;
    const String            aStrJan;
    const String            aStrFeb;
    const String            aStrMar;
    const String            aStrNorth;
    const String            aStrMid;
    const String            aStrSouth;
    const String            aStrSum;
    SvNumberFormatter*      pNumFmt;
    //-------------------------------------------
    SC_DLLPRIVATE void  Init            ();
    SC_DLLPRIVATE void  DoPaint         ( const Rectangle& rRect );
    SC_DLLPRIVATE void  CalcCellArray   ( BOOL bFitWidth );
    SC_DLLPRIVATE void  CalcLineMap     ();
    SC_DLLPRIVATE void  PaintCells      ();

/*  Usage of type size_t instead of SCCOL/SCROW is correct here - used in
    conjunction with class svx::frame::Array (svx/framelinkarray.hxx), which
    expects size_t coordinates. */

    SC_DLLPRIVATE USHORT              GetFormatIndex( size_t nCol, size_t nRow ) const;
    SC_DLLPRIVATE const SvxBoxItem&   GetBoxItem( size_t nCol, size_t nRow ) const;
    SC_DLLPRIVATE const SvxLineItem&  GetDiagItem( size_t nCol, size_t nRow, bool bTLBR ) const;

    SC_DLLPRIVATE void                DrawString( size_t nCol, size_t nRow );
    SC_DLLPRIVATE void                DrawStrings();
    SC_DLLPRIVATE void                DrawBackground();

    SC_DLLPRIVATE void    MakeFonts       ( USHORT nIndex,
                              Font& rFont,
                              Font& rCJKFont,
                              Font& rCTLFont );

    SC_DLLPRIVATE String    MakeNumberString( String cellString, BOOL bAddDec );
    SC_DLLPRIVATE void  DrawFrameLine   ( const SvxBorderLine&  rLineD,
                              Point                 from,
                              Point                 to,
                              BOOL                  bHorizontal,
                              const SvxBorderLine&  rLineLT,
                              const SvxBorderLine&  rLineL,
                              const SvxBorderLine&  rLineLB,
                              const SvxBorderLine&  rLineRT,
                              const SvxBorderLine&  rLineR,
                              const SvxBorderLine&  rLineRB );
    SC_DLLPRIVATE void CheckPriority    ( USHORT            nCurLine,
                              AutoFmtLine       eLine,
                              SvxBorderLine&    rLine );
    SC_DLLPRIVATE void  GetLines        ( USHORT nIndex, AutoFmtLine eLine,
                              SvxBorderLine&    rLineD,
                              SvxBorderLine&    rLineLT,
                              SvxBorderLine&    rLineL,
                              SvxBorderLine&    rLineLB,
                              SvxBorderLine&    rLineRT,
                              SvxBorderLine&    rLineR,
                              SvxBorderLine&    rLineRB );
};

#endif // SC_AUTOFMT_HXX

<commit_msg>INTEGRATION: CWS ooo19126 (1.7.346); FILE MERGED 2005/09/05 15:05:07 rt 1.7.346.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: autofmt.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 21:13:27 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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 this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SC_AUTOFMT_HXX
#define SC_AUTOFMT_HXX

#ifndef _VIRDEV_HXX //autogen
#include <vcl/virdev.hxx>
#endif
#ifndef SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#ifndef SV_LSTBOX_HXX
#include <vcl/lstbox.hxx>
#endif
#ifndef SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
#ifndef SV_MOREBTN_HXX
#include <vcl/morebtn.hxx>
#endif
#ifndef _DIALOG_HXX //autogen
#include <vcl/dialog.hxx>
#endif
#ifndef _SVTOOLS_SCRIPTEDTEXT_HXX
#include <svtools/scriptedtext.hxx>
#endif
#ifndef SVX_FRAMELINKARRAY_HXX
#include <svx/framelinkarray.hxx>
#endif

#ifndef INCLUDED_SCDLLAPI_H
#include "scdllapi.h"
#endif

//------------------------------------------------------------------------

class ScAutoFormat;
class ScAutoFormatData;
class SvxBoxItem;
class SvxLineItem;
class AutoFmtPreview; // s.u.
class SvNumberFormatter;
class ScDocument;

//------------------------------------------------------------------------

enum AutoFmtLine { TOP_LINE, BOTTOM_LINE, LEFT_LINE, RIGHT_LINE };

//========================================================================

//CHINA001 class ScAutoFormatDlg : public ModalDialog
//CHINA001 {
//CHINA001 public:
//CHINA001 ScAutoFormatDlg( Window*                 pParent,
//CHINA001 ScAutoFormat*                pAutoFormat,
//CHINA001 const ScAutoFormatData*    pSelFormatData,
//CHINA001 ScDocument*                pDoc );
//CHINA001 ~ScAutoFormatDlg();
//CHINA001
//CHINA001 USHORT GetIndex() const { return nIndex; }
//CHINA001 String GetCurrFormatName();
//CHINA001
//CHINA001 private:
//CHINA001 FixedLine       aFlFormat;
//CHINA001 ListBox          aLbFormat;
//CHINA001 AutoFmtPreview*  pWndPreview;
//CHINA001 OKButton     aBtnOk;
//CHINA001 CancelButton aBtnCancel;
//CHINA001 HelpButton       aBtnHelp;
//CHINA001 PushButton       aBtnAdd;
//CHINA001 PushButton       aBtnRemove;
//CHINA001 MoreButton       aBtnMore;
//CHINA001 FixedLine       aFlFormatting;
//CHINA001 CheckBox     aBtnNumFormat;
//CHINA001 CheckBox     aBtnBorder;
//CHINA001 CheckBox     aBtnFont;
//CHINA001 CheckBox     aBtnPattern;
//CHINA001 CheckBox     aBtnAlignment;
//CHINA001 CheckBox     aBtnAdjust;
//CHINA001 PushButton       aBtnRename;
//CHINA001 String           aStrTitle;
//CHINA001 String           aStrLabel;
//CHINA001 String           aStrClose;
//CHINA001 String           aStrDelTitle;
//CHINA001 String           aStrDelMsg;
//CHINA001 String           aStrRename;
//CHINA001
//CHINA001 //------------------------
//CHINA001 ScAutoFormat*            pFormat;
//CHINA001 const ScAutoFormatData*  pSelFmtData;
//CHINA001 USHORT                   nIndex;
//CHINA001 BOOL                 bCoreDataChanged;
//CHINA001 BOOL                 bFmtInserted;
//CHINA001
//CHINA001 void Init            ();
//CHINA001 void UpdateChecks    ();
//CHINA001 //------------------------
//CHINA001 DECL_LINK( CheckHdl, Button * );
//CHINA001 DECL_LINK( AddHdl, void * );
//CHINA001 DECL_LINK( RemoveHdl, void * );
//CHINA001 DECL_LINK( SelFmtHdl, void * );
//CHINA001 DECL_LINK( CloseHdl, PushButton * );
//CHINA001 DECL_LINK( DblClkHdl, void * );
//CHINA001 DECL_LINK( RenameHdl, void *);
//CHINA001
//CHINA001 };
//CHINA001
//========================================================================

class SC_DLLPUBLIC AutoFmtPreview : public Window
{
public:
            AutoFmtPreview( Window* pParent, const ResId& rRes, ScDocument* pDoc );
            ~AutoFmtPreview();

    void NotifyChange( ScAutoFormatData* pNewData );

protected:
    virtual void Paint( const Rectangle& rRect );

private:
    ScAutoFormatData*       pCurData;
    VirtualDevice           aVD;
    SvtScriptedTextHelper   aScriptedText;
    ::com::sun::star::uno::Reference< ::com::sun::star::i18n::XBreakIterator > xBreakIter;
    BOOL                    bFitWidth;
    svx::frame::Array       maArray;            /// Implementation to draw the frame borders.
    Size                    aPrvSize;
    long                    mnLabelColWidth;
    long                    mnDataColWidth1;
    long                    mnDataColWidth2;
    long                    mnRowHeight;
    const String            aStrJan;
    const String            aStrFeb;
    const String            aStrMar;
    const String            aStrNorth;
    const String            aStrMid;
    const String            aStrSouth;
    const String            aStrSum;
    SvNumberFormatter*      pNumFmt;
    //-------------------------------------------
    SC_DLLPRIVATE void  Init            ();
    SC_DLLPRIVATE void  DoPaint         ( const Rectangle& rRect );
    SC_DLLPRIVATE void  CalcCellArray   ( BOOL bFitWidth );
    SC_DLLPRIVATE void  CalcLineMap     ();
    SC_DLLPRIVATE void  PaintCells      ();

/*  Usage of type size_t instead of SCCOL/SCROW is correct here - used in
    conjunction with class svx::frame::Array (svx/framelinkarray.hxx), which
    expects size_t coordinates. */

    SC_DLLPRIVATE USHORT              GetFormatIndex( size_t nCol, size_t nRow ) const;
    SC_DLLPRIVATE const SvxBoxItem&   GetBoxItem( size_t nCol, size_t nRow ) const;
    SC_DLLPRIVATE const SvxLineItem&  GetDiagItem( size_t nCol, size_t nRow, bool bTLBR ) const;

    SC_DLLPRIVATE void                DrawString( size_t nCol, size_t nRow );
    SC_DLLPRIVATE void                DrawStrings();
    SC_DLLPRIVATE void                DrawBackground();

    SC_DLLPRIVATE void    MakeFonts       ( USHORT nIndex,
                              Font& rFont,
                              Font& rCJKFont,
                              Font& rCTLFont );

    SC_DLLPRIVATE String    MakeNumberString( String cellString, BOOL bAddDec );
    SC_DLLPRIVATE void  DrawFrameLine   ( const SvxBorderLine&  rLineD,
                              Point                 from,
                              Point                 to,
                              BOOL                  bHorizontal,
                              const SvxBorderLine&  rLineLT,
                              const SvxBorderLine&  rLineL,
                              const SvxBorderLine&  rLineLB,
                              const SvxBorderLine&  rLineRT,
                              const SvxBorderLine&  rLineR,
                              const SvxBorderLine&  rLineRB );
    SC_DLLPRIVATE void CheckPriority    ( USHORT            nCurLine,
                              AutoFmtLine       eLine,
                              SvxBorderLine&    rLine );
    SC_DLLPRIVATE void  GetLines        ( USHORT nIndex, AutoFmtLine eLine,
                              SvxBorderLine&    rLineD,
                              SvxBorderLine&    rLineLT,
                              SvxBorderLine&    rLineL,
                              SvxBorderLine&    rLineLB,
                              SvxBorderLine&    rLineRT,
                              SvxBorderLine&    rLineR,
                              SvxBorderLine&    rLineRB );
};

#endif // SC_AUTOFMT_HXX

<|endoftext|>


<commit_before>/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#include <fstream>
#include <iostream>
#include "paddle/fluid/inference/tests/api/tester_helper.h"

namespace paddle {
namespace inference {
namespace analysis {

void SetConfig(AnalysisConfig *cfg) {
  cfg->param_file = FLAGS_infer_model + "/params";
  cfg->prog_file = FLAGS_infer_model + "/model";
  cfg->use_gpu = false;
  cfg->device = 0;
  cfg->enable_ir_optim = true;
  cfg->specify_input_name = true;
#ifdef PADDLE_WITH_MKLDNN
  cfg->_use_mkldnn = true;
#endif
}

void SetInput(std::vector<std::vector<PaddleTensor>> *inputs) {
  PADDLE_ENFORCE_EQ(FLAGS_test_all_data, 0, "Only have single batch of data.");

  PaddleTensor input;
  // channel=3, height/width=318
  std::vector<int> shape({FLAGS_batch_size, 3, 318, 318});
  input.shape = shape;
  input.dtype = PaddleDType::FLOAT32;

  // fill input data, for profile easily, do not use random data here.
  size_t size = FLAGS_batch_size * 3 * 318 * 318;
  input.data.Resize(size * sizeof(float));
  float *input_data = static_cast<float *>(input.data.data());
  for (size_t i = 0; i < size; i++) {
    *(input_data + i) = static_cast<float>(i) / size;
  }

  std::vector<PaddleTensor> input_slots;
  input_slots.assign({input});
  (*inputs).emplace_back(input_slots);
}

// Easy for profiling independently.
void profile(bool use_mkldnn = false) {
  AnalysisConfig cfg;
  SetConfig(&cfg);
  cfg._use_mkldnn = use_mkldnn;
  std::vector<PaddleTensor> outputs;

  std::vector<std::vector<PaddleTensor>> input_slots_all;
  SetInput(&input_slots_all);
  TestPrediction(cfg, input_slots_all, &outputs, FLAGS_num_threads);

  if (FLAGS_num_threads == 1 && !FLAGS_test_all_data) {
    PADDLE_ENFORCE_EQ(outputs.size(), 1UL);
    size_t size = GetSize(outputs[0]);
    // output is a 512-dimension feature
    EXPECT_EQ(size, 512 * FLAGS_batch_size);
  }
}

TEST(Analyzer_resnet50, profile) { profile(); }
#ifndef PADDLE_WITH_MKLDNN
TEST(Analyzer_resnet50, profile_mkldnn) { profile(true /* use_mkldnn */); }
#endif

// Check the fuse status
TEST(Analyzer_resnet50, fuse_statis) {
  AnalysisConfig cfg;
  SetConfig(&cfg);
  int num_ops;
  auto predictor = CreatePaddlePredictor<AnalysisConfig>(cfg);
  auto fuse_statis = GetFuseStatis(
      static_cast<AnalysisPredictor *>(predictor.get()), &num_ops);
  ASSERT_TRUE(fuse_statis.count("fc_fuse"));
  EXPECT_EQ(fuse_statis.at("fc_fuse"), 1);
}

// Compare result of NativeConfig and AnalysisConfig
void compare(bool use_mkldnn = false) {
  AnalysisConfig cfg;
  SetConfig(&cfg);
  cfg._use_mkldnn = use_mkldnn;

  std::vector<std::vector<PaddleTensor>> input_slots_all;
  SetInput(&input_slots_all);
  CompareNativeAndAnalysis(cfg, input_slots_all);
}

TEST(Analyzer_resnet50, compare) { compare(); }
#ifdef PADDLE_WITH_MKLDNN
TEST(Analyzer_resnet50, compare_mkldnn) { compare(true /* use_mkldnn */); }
#endif

}  // namespace analysis
}  // namespace inference
}  // namespace paddle
<commit_msg>Remove use mkldnn from config in resnet50 test<commit_after>/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#include <fstream>
#include <iostream>
#include "paddle/fluid/inference/tests/api/tester_helper.h"

namespace paddle {
namespace inference {
namespace analysis {

void SetConfig(AnalysisConfig *cfg) {
  cfg->param_file = FLAGS_infer_model + "/params";
  cfg->prog_file = FLAGS_infer_model + "/model";
  cfg->use_gpu = false;
  cfg->device = 0;
  cfg->enable_ir_optim = true;
  cfg->specify_input_name = true;
}

void SetInput(std::vector<std::vector<PaddleTensor>> *inputs) {
  PADDLE_ENFORCE_EQ(FLAGS_test_all_data, 0, "Only have single batch of data.");

  PaddleTensor input;
  // channel=3, height/width=318
  std::vector<int> shape({FLAGS_batch_size, 3, 318, 318});
  input.shape = shape;
  input.dtype = PaddleDType::FLOAT32;

  // fill input data, for profile easily, do not use random data here.
  size_t size = FLAGS_batch_size * 3 * 318 * 318;
  input.data.Resize(size * sizeof(float));
  float *input_data = static_cast<float *>(input.data.data());
  for (size_t i = 0; i < size; i++) {
    *(input_data + i) = static_cast<float>(i) / size;
  }

  std::vector<PaddleTensor> input_slots;
  input_slots.assign({input});
  (*inputs).emplace_back(input_slots);
}

// Easy for profiling independently.
void profile(bool use_mkldnn = false) {
  AnalysisConfig cfg;
  SetConfig(&cfg);
  cfg._use_mkldnn = use_mkldnn;
  std::vector<PaddleTensor> outputs;

  std::vector<std::vector<PaddleTensor>> input_slots_all;
  SetInput(&input_slots_all);
  TestPrediction(cfg, input_slots_all, &outputs, FLAGS_num_threads);

  if (FLAGS_num_threads == 1 && !FLAGS_test_all_data) {
    PADDLE_ENFORCE_EQ(outputs.size(), 1UL);
    size_t size = GetSize(outputs[0]);
    // output is a 512-dimension feature
    EXPECT_EQ(size, 512 * FLAGS_batch_size);
  }
}

TEST(Analyzer_resnet50, profile) { profile(); }
#ifndef PADDLE_WITH_MKLDNN
TEST(Analyzer_resnet50, profile_mkldnn) { profile(true /* use_mkldnn */); }
#endif

// Check the fuse status
TEST(Analyzer_resnet50, fuse_statis) {
  AnalysisConfig cfg;
  SetConfig(&cfg);
  int num_ops;
  auto predictor = CreatePaddlePredictor<AnalysisConfig>(cfg);
  auto fuse_statis = GetFuseStatis(
      static_cast<AnalysisPredictor *>(predictor.get()), &num_ops);
  ASSERT_TRUE(fuse_statis.count("fc_fuse"));
  EXPECT_EQ(fuse_statis.at("fc_fuse"), 1);
}

// Compare result of NativeConfig and AnalysisConfig
void compare(bool use_mkldnn = false) {
  AnalysisConfig cfg;
  SetConfig(&cfg);
  cfg._use_mkldnn = use_mkldnn;

  std::vector<std::vector<PaddleTensor>> input_slots_all;
  SetInput(&input_slots_all);
  CompareNativeAndAnalysis(cfg, input_slots_all);
}

TEST(Analyzer_resnet50, compare) { compare(); }
#ifdef PADDLE_WITH_MKLDNN
TEST(Analyzer_resnet50, compare_mkldnn) { compare(true /* use_mkldnn */); }
#endif

}  // namespace analysis
}  // namespace inference
}  // namespace paddle
<|endoftext|>


<commit_before>// Copyright 2019 The Pigweed Authors
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

#include "pw_string/string_builder.h"

#include <cstdio>

#include "pw_string/format.h"
#include "pw_string/util.h"

namespace pw {

void StringBuilder::clear() {
  *size_ = 0;
  NullTerminate();
  status_ = StatusCode(OkStatus());
  last_status_ = StatusCode(OkStatus());
}

StringBuilder& StringBuilder::append(size_t count, char ch) {
  char* const append_destination = buffer_.data() + size();
  std::fill_n(append_destination, ResizeAndTerminate(count), ch);
  return *this;
}

StringBuilder& StringBuilder::append(const char* str, size_t count) {
  char* const append_destination = buffer_.data() + size();
  std::copy_n(str, ResizeAndTerminate(count), append_destination);
  return *this;
}

StringBuilder& StringBuilder::append(const char* str) {
  // Use buffer_.size() - size() as the maximum length so that strings too long
  // to fit in the buffer will request one character too many, which sets the
  // status to RESOURCE_EXHAUSTED.
  return append(string::ClampedCString(str, buffer_.size() - size()));
}

StringBuilder& StringBuilder::append(const std::string_view& str) {
  return append(str.data(), str.size());
}

StringBuilder& StringBuilder::append(const std::string_view& str,
                                     size_t pos,
                                     size_t count) {
  if (pos > str.size()) {
    SetErrorStatus(Status::OutOfRange());
    return *this;
  }

  return append(str.data() + pos, std::min(str.size() - pos, count));
}

size_t StringBuilder::ResizeAndTerminate(size_t chars_to_append) {
  const size_t copied = std::min(chars_to_append, max_size() - size());
  *size_ += copied;
  NullTerminate();

  if (buffer_.empty() || chars_to_append != copied) {
    SetErrorStatus(Status::ResourceExhausted());
  } else {
    last_status_ = StatusCode(OkStatus());
  }
  return copied;
}

void StringBuilder::resize(size_t new_size) {
  if (new_size <= size()) {
    *size_ = new_size;
    NullTerminate();
    last_status_ = StatusCode(OkStatus());
  } else {
    SetErrorStatus(Status::OutOfRange());
  }
}

StringBuilder& StringBuilder::Format(const char* format, ...) {
  va_list args;
  va_start(args, format);
  FormatVaList(format, args);
  va_end(args);

  return *this;
}

StringBuilder& StringBuilder::FormatVaList(const char* format, va_list args) {
  HandleStatusWithSize(
      string::FormatVaList(buffer_.subspan(size()), format, args));
  return *this;
}

void StringBuilder::WriteBytes(span<const std::byte> data) {
  if (size() + data.size() * 2 > max_size()) {
    SetErrorStatus(Status::ResourceExhausted());
  } else {
    for (std::byte val : data) {
      *this << val;
    }
  }
}

void StringBuilder::CopySizeAndStatus(const StringBuilder& other) {
  *size_ = other.size();
  status_ = other.status_;
  last_status_ = other.last_status_;
}

void StringBuilder::HandleStatusWithSize(StatusWithSize written) {
  const Status status = written.status();
  last_status_ = StatusCode(status);
  if (!status.ok()) {
    status_ = StatusCode(status);
  }

  *size_ += written.size();
}

void StringBuilder::SetErrorStatus(Status status) {
  last_status_ = StatusCode(status);
  status_ = StatusCode(status);
}

}  // namespace pw
<commit_msg>pw_string: Make narrowing conversions explicit<commit_after>// Copyright 2019 The Pigweed Authors
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

#include "pw_string/string_builder.h"

#include <cstdio>

#include "pw_string/format.h"
#include "pw_string/util.h"

namespace pw {

void StringBuilder::clear() {
  *size_ = 0;
  NullTerminate();
  status_ = StatusCode(OkStatus());
  last_status_ = StatusCode(OkStatus());
}

StringBuilder& StringBuilder::append(size_t count, char ch) {
  char* const append_destination = buffer_.data() + size();
  std::fill_n(append_destination, ResizeAndTerminate(count), ch);
  return *this;
}

StringBuilder& StringBuilder::append(const char* str, size_t count) {
  char* const append_destination = buffer_.data() + size();
  std::copy_n(str, ResizeAndTerminate(count), append_destination);
  return *this;
}

StringBuilder& StringBuilder::append(const char* str) {
  // Use buffer_.size() - size() as the maximum length so that strings too long
  // to fit in the buffer will request one character too many, which sets the
  // status to RESOURCE_EXHAUSTED.
  return append(string::ClampedCString(str, buffer_.size() - size()));
}

StringBuilder& StringBuilder::append(const std::string_view& str) {
  return append(str.data(), str.size());
}

StringBuilder& StringBuilder::append(const std::string_view& str,
                                     size_t pos,
                                     size_t count) {
  if (pos > str.size()) {
    SetErrorStatus(Status::OutOfRange());
    return *this;
  }

  return append(str.data() + pos, std::min(str.size() - pos, count));
}

size_t StringBuilder::ResizeAndTerminate(size_t chars_to_append) {
  const size_t copied = std::min(chars_to_append, max_size() - size());
  *size_ += copied;
  NullTerminate();

  if (buffer_.empty() || chars_to_append != copied) {
    SetErrorStatus(Status::ResourceExhausted());
  } else {
    last_status_ = StatusCode(OkStatus());
  }
  return copied;
}

void StringBuilder::resize(size_t new_size) {
  if (new_size <= size()) {
    *size_ = static_cast<InlineString<>::size_type>(new_size);
    NullTerminate();
    last_status_ = StatusCode(OkStatus());
  } else {
    SetErrorStatus(Status::OutOfRange());
  }
}

StringBuilder& StringBuilder::Format(const char* format, ...) {
  va_list args;
  va_start(args, format);
  FormatVaList(format, args);
  va_end(args);

  return *this;
}

StringBuilder& StringBuilder::FormatVaList(const char* format, va_list args) {
  HandleStatusWithSize(
      string::FormatVaList(buffer_.subspan(size()), format, args));
  return *this;
}

void StringBuilder::WriteBytes(span<const std::byte> data) {
  if (size() + data.size() * 2 > max_size()) {
    SetErrorStatus(Status::ResourceExhausted());
  } else {
    for (std::byte val : data) {
      *this << val;
    }
  }
}

void StringBuilder::CopySizeAndStatus(const StringBuilder& other) {
  *size_ = static_cast<InlineString<>::size_type>(other.size());
  status_ = other.status_;
  last_status_ = other.last_status_;
}

void StringBuilder::HandleStatusWithSize(StatusWithSize written) {
  const Status status = written.status();
  last_status_ = StatusCode(status);
  if (!status.ok()) {
    status_ = StatusCode(status);
  }

  *size_ += written.size();
}

void StringBuilder::SetErrorStatus(Status status) {
  last_status_ = StatusCode(status);
  status_ = StatusCode(status);
}

}  // namespace pw
<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact:  Qt Software Information (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
**
**************************************************************************/

#include "qt4buildconfigwidget.h"

#include "makestep.h"
#include "qmakestep.h"
#include "qt4project.h"
#include "qt4projectmanagerconstants.h"
#include "qt4projectmanager.h"
#include "ui_qt4buildconfigwidget.h"

#include <coreplugin/icore.h>
#include <coreplugin/mainwindow.h>

#include <QtGui/QFileDialog>

namespace {
bool debug = false;
}

using namespace Qt4ProjectManager;
using namespace Qt4ProjectManager::Internal;

Qt4BuildConfigWidget::Qt4BuildConfigWidget(Qt4Project *project)
    : BuildStepConfigWidget(),
      m_pro(project)
{
    m_ui = new Ui::Qt4BuildConfigWidget();
    m_ui->setupUi(this);
    m_ui->shadowBuildDirEdit->setPromptDialogTitle(tr("Shadow Build Directory"));
    m_ui->shadowBuildDirEdit->setExpectedKind(Core::Utils::PathChooser::Directory);
    m_ui->invalidQtWarningLabel->setVisible(false);

    connect(m_ui->nameLineEdit, SIGNAL(textEdited(QString)),
            this, SLOT(changeConfigName(QString)));

    connect(m_ui->shadowBuildCheckBox, SIGNAL(clicked(bool)),
            this, SLOT(shadowBuildCheckBoxClicked(bool)));

    connect(m_ui->shadowBuildDirEdit, SIGNAL(beforeBrowsing()),
            this, SLOT(onBeforeBeforeShadowBuildDirBrowsed()));

    connect(m_ui->shadowBuildDirEdit, SIGNAL(changed()),
            this, SLOT(shadowBuildLineEditTextChanged()));

    connect(m_ui->qtVersionComboBox, SIGNAL(currentIndexChanged(QString)),
            this, SLOT(qtVersionComboBoxCurrentIndexChanged(QString)));

    connect(m_ui->importLabel, SIGNAL(linkActivated(QString)),
            this, SLOT(importLabelClicked()));

    connect(m_ui->manageQtVersionPushButtons, SIGNAL(clicked()),
            this, SLOT(manageQtVersions()));

    connect(m_pro->qt4ProjectManager()->versionManager(), SIGNAL(qtVersionsChanged()),
            this, SLOT(setupQtVersionsComboBox()));
}

Qt4BuildConfigWidget::~Qt4BuildConfigWidget()
{
    delete m_ui;
}

void Qt4BuildConfigWidget::manageQtVersions()
{
    Core::ICore *core = Core::ICore::instance();
    core->showOptionsDialog(Constants::QT_CATEGORY, Constants::QTVERSION_PAGE);
}

QString Qt4BuildConfigWidget::displayName() const
{
    return tr("General");
}

void Qt4BuildConfigWidget::init(const QString &buildConfiguration)
{
    if (debug)
        qDebug() << "Qt4BuildConfigWidget::init()";

    m_buildConfiguration = buildConfiguration;

    m_ui->nameLineEdit->setText(m_pro->displayNameFor(m_buildConfiguration));

    setupQtVersionsComboBox();

    bool shadowBuild = m_pro->value(buildConfiguration, "useShadowBuild").toBool();
    m_ui->shadowBuildCheckBox->setChecked(shadowBuild);
    m_ui->shadowBuildDirEdit->setEnabled(shadowBuild);
    m_ui->shadowBuildDirEdit->setPath(m_pro->buildDirectory(buildConfiguration));
    updateImportLabel();
}

void Qt4BuildConfigWidget::changeConfigName(const QString &newName)
{
    m_pro->setDisplayNameFor(m_buildConfiguration, newName);
}

void Qt4BuildConfigWidget::setupQtVersionsComboBox()
{
    if (m_buildConfiguration.isEmpty()) // not yet initialized
        return;

    disconnect(m_ui->qtVersionComboBox, SIGNAL(currentIndexChanged(QString)),
        this, SLOT(qtVersionComboBoxCurrentIndexChanged(QString)));

    m_ui->qtVersionComboBox->clear();
    m_ui->qtVersionComboBox->addItem(tr("Default Qt Version"), 0);

    if (m_pro->qtVersionId(m_buildConfiguration) == 0) {
        m_ui->qtVersionComboBox->setCurrentIndex(0);
        m_ui->invalidQtWarningLabel->setVisible(false);
    }
    // Add Qt Versions to the combo box
    QtVersionManager *vm = m_pro->qt4ProjectManager()->versionManager();
    const QList<QtVersion *> &versions = vm->versions();
    for (int i = 0; i < versions.size(); ++i) {
        m_ui->qtVersionComboBox->addItem(versions.at(i)->name(), versions.at(i)->uniqueId());

        if (versions.at(i)->uniqueId() == m_pro->qtVersionId(m_buildConfiguration)) {
            m_ui->qtVersionComboBox->setCurrentIndex(i + 1);
            m_ui->invalidQtWarningLabel->setVisible(!versions.at(i)->isValid());
        }
    }

    // And connect again
    connect(m_ui->qtVersionComboBox, SIGNAL(currentIndexChanged(QString)),
        this, SLOT(qtVersionComboBoxCurrentIndexChanged(QString)));
}

void Qt4BuildConfigWidget::onBeforeBeforeShadowBuildDirBrowsed()
{
    QString initialDirectory = QFileInfo(m_pro->file()->fileName()).absolutePath();
    if (!initialDirectory.isEmpty())
        m_ui->shadowBuildDirEdit->setInitialBrowsePathBackup(initialDirectory);
}

void Qt4BuildConfigWidget::shadowBuildCheckBoxClicked(bool checked)
{
    m_ui->shadowBuildDirEdit->setEnabled(checked);
    bool b = m_ui->shadowBuildCheckBox->isChecked();
    m_pro->setValue(m_buildConfiguration, "useShadowBuild", b);
    if (b)
        m_pro->setValue(m_buildConfiguration, "buildDirectory", m_ui->shadowBuildDirEdit->path());
    else
        m_pro->setValue(m_buildConfiguration, "buildDirectory", QVariant(QString::null));
}

void Qt4BuildConfigWidget::updateImportLabel()
{
    m_ui->importLabel->setVisible(false);
    if (m_ui->shadowBuildCheckBox->isChecked()) {
        QString qtPath = m_pro->qt4ProjectManager()->versionManager()->findQtVersionFromMakefile(m_ui->shadowBuildDirEdit->path());
        if (!qtPath.isEmpty()) {
            m_ui->importLabel->setVisible(true);
        }
    }
}

void Qt4BuildConfigWidget::shadowBuildLineEditTextChanged()
{
    if (m_pro->value(m_buildConfiguration, "buildDirectory").toString() == m_ui->shadowBuildDirEdit->path())
    m_pro->setValue(m_buildConfiguration, "buildDirectory", m_ui->shadowBuildDirEdit->path());
    // if the directory already exists
    // check if we have a build in there and
    // offer to import it
    updateImportLabel();

    m_pro->invalidateCachedTargetInformation();

//    QFileInfo fi(m_ui->shadowBuildDirEdit->path());
//    if (fi.exists()) {
//        m_ui->shadowBuildLineEdit->setStyleSheet("");
//        m_ui->shadowBuildLineEdit->setToolTip("");
//    } else {
//        m_ui->shadowBuildLineEdit->setStyleSheet("background: red;");
//        m_ui->shadowBuildLineEdit->setToolTip(tr("Directory does not exist."));
//    }
}

void Qt4BuildConfigWidget::importLabelClicked()
{
    if (m_ui->shadowBuildCheckBox->isChecked()) {
        QString directory = m_ui->shadowBuildDirEdit->path();
        if (!directory.isEmpty()) {
            QtVersionManager *vm = m_pro->qt4ProjectManager()->versionManager();
            QString qtPath = vm->findQtVersionFromMakefile(directory);
            if (!qtPath.isEmpty()) {
                QtVersion *version = vm->qtVersionForDirectory(qtPath);
                if (!version) {
                    version = new QtVersion(QFileInfo(qtPath).baseName(), qtPath);
                    vm->addVersion(version);
                }
                QtVersion::QmakeBuildConfig qmakeBuildConfig = version->defaultBuildConfig();
                qmakeBuildConfig = vm->scanMakefileForQmakeConfig(directory, qmakeBuildConfig);

                // So we got all the information now apply it...
                m_pro->setQtVersion(m_buildConfiguration, version->uniqueId());
                // Combo box will be updated at the end

                // Find qmakestep...
                QMakeStep *qmakeStep = m_pro->qmakeStep();
                MakeStep *makeStep = m_pro->makeStep();

                qmakeStep->setValue(m_buildConfiguration, "buildConfiguration", int(qmakeBuildConfig));
                // Adjust command line arguments, this is ugly as hell
                // If we are switching to BuildAll we want "release" in there and no "debug"
                // or "debug" in there and no "release"
                // If we are switching to not BuildAl we want neither "release" nor "debug" in there
                QStringList makeCmdArguments = makeStep->value(m_buildConfiguration, "makeargs").toStringList();
                bool debug = qmakeBuildConfig & QtVersion::DebugBuild;
                if (qmakeBuildConfig & QtVersion::BuildAll) {
                    makeCmdArguments.removeAll(debug ? "release" : "debug");
                    if (!makeCmdArguments.contains(debug ? "debug" : "release"))
                        makeCmdArguments.append(debug ? "debug" : "release");
                } else {
                    makeCmdArguments.removeAll("debug");
                    makeCmdArguments.removeAll("remove");
                }
                makeStep->setValue(m_buildConfiguration, "makeargs", makeCmdArguments);
            }
        }
    }
    setupQtVersionsComboBox();
}

void Qt4BuildConfigWidget::qtVersionComboBoxCurrentIndexChanged(const QString &)
{
    //Qt Version
    int newQtVersion;
    if (m_ui->qtVersionComboBox->currentIndex() == 0) {
        newQtVersion = 0;
    } else {
        newQtVersion = m_ui->qtVersionComboBox->itemData(m_ui->qtVersionComboBox->currentIndex()).toInt();
    }
    bool isValid = m_pro->qt4ProjectManager()->versionManager()->version(newQtVersion)->isValid();
    m_ui->invalidQtWarningLabel->setVisible(!isValid);
    if (newQtVersion != m_pro->qtVersionId(m_buildConfiguration)) {
        m_pro->setQtVersion(m_buildConfiguration, newQtVersion);
        m_pro->update();
    }
}
<commit_msg>Shadow build directory setting not used "right away".<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact:  Qt Software Information (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
**
**************************************************************************/

#include "qt4buildconfigwidget.h"

#include "makestep.h"
#include "qmakestep.h"
#include "qt4project.h"
#include "qt4projectmanagerconstants.h"
#include "qt4projectmanager.h"
#include "ui_qt4buildconfigwidget.h"

#include <coreplugin/icore.h>
#include <coreplugin/mainwindow.h>

#include <QtGui/QFileDialog>

namespace {
bool debug = false;
}

using namespace Qt4ProjectManager;
using namespace Qt4ProjectManager::Internal;

Qt4BuildConfigWidget::Qt4BuildConfigWidget(Qt4Project *project)
    : BuildStepConfigWidget(),
      m_pro(project)
{
    m_ui = new Ui::Qt4BuildConfigWidget();
    m_ui->setupUi(this);
    m_ui->shadowBuildDirEdit->setPromptDialogTitle(tr("Shadow Build Directory"));
    m_ui->shadowBuildDirEdit->setExpectedKind(Core::Utils::PathChooser::Directory);
    m_ui->invalidQtWarningLabel->setVisible(false);

    connect(m_ui->nameLineEdit, SIGNAL(textEdited(QString)),
            this, SLOT(changeConfigName(QString)));

    connect(m_ui->shadowBuildCheckBox, SIGNAL(clicked(bool)),
            this, SLOT(shadowBuildCheckBoxClicked(bool)));

    connect(m_ui->shadowBuildDirEdit, SIGNAL(beforeBrowsing()),
            this, SLOT(onBeforeBeforeShadowBuildDirBrowsed()));

    connect(m_ui->shadowBuildDirEdit, SIGNAL(changed()),
            this, SLOT(shadowBuildLineEditTextChanged()));

    connect(m_ui->qtVersionComboBox, SIGNAL(currentIndexChanged(QString)),
            this, SLOT(qtVersionComboBoxCurrentIndexChanged(QString)));

    connect(m_ui->importLabel, SIGNAL(linkActivated(QString)),
            this, SLOT(importLabelClicked()));

    connect(m_ui->manageQtVersionPushButtons, SIGNAL(clicked()),
            this, SLOT(manageQtVersions()));

    connect(m_pro->qt4ProjectManager()->versionManager(), SIGNAL(qtVersionsChanged()),
            this, SLOT(setupQtVersionsComboBox()));
}

Qt4BuildConfigWidget::~Qt4BuildConfigWidget()
{
    delete m_ui;
}

void Qt4BuildConfigWidget::manageQtVersions()
{
    Core::ICore *core = Core::ICore::instance();
    core->showOptionsDialog(Constants::QT_CATEGORY, Constants::QTVERSION_PAGE);
}

QString Qt4BuildConfigWidget::displayName() const
{
    return tr("General");
}

void Qt4BuildConfigWidget::init(const QString &buildConfiguration)
{
    if (debug)
        qDebug() << "Qt4BuildConfigWidget::init()";

    m_buildConfiguration = buildConfiguration;

    m_ui->nameLineEdit->setText(m_pro->displayNameFor(m_buildConfiguration));

    setupQtVersionsComboBox();

    bool shadowBuild = m_pro->value(buildConfiguration, "useShadowBuild").toBool();
    m_ui->shadowBuildCheckBox->setChecked(shadowBuild);
    m_ui->shadowBuildDirEdit->setEnabled(shadowBuild);
    m_ui->shadowBuildDirEdit->setPath(m_pro->buildDirectory(buildConfiguration));
    updateImportLabel();
}

void Qt4BuildConfigWidget::changeConfigName(const QString &newName)
{
    m_pro->setDisplayNameFor(m_buildConfiguration, newName);
}

void Qt4BuildConfigWidget::setupQtVersionsComboBox()
{
    if (m_buildConfiguration.isEmpty()) // not yet initialized
        return;

    disconnect(m_ui->qtVersionComboBox, SIGNAL(currentIndexChanged(QString)),
        this, SLOT(qtVersionComboBoxCurrentIndexChanged(QString)));

    m_ui->qtVersionComboBox->clear();
    m_ui->qtVersionComboBox->addItem(tr("Default Qt Version"), 0);

    if (m_pro->qtVersionId(m_buildConfiguration) == 0) {
        m_ui->qtVersionComboBox->setCurrentIndex(0);
        m_ui->invalidQtWarningLabel->setVisible(false);
    }
    // Add Qt Versions to the combo box
    QtVersionManager *vm = m_pro->qt4ProjectManager()->versionManager();
    const QList<QtVersion *> &versions = vm->versions();
    for (int i = 0; i < versions.size(); ++i) {
        m_ui->qtVersionComboBox->addItem(versions.at(i)->name(), versions.at(i)->uniqueId());

        if (versions.at(i)->uniqueId() == m_pro->qtVersionId(m_buildConfiguration)) {
            m_ui->qtVersionComboBox->setCurrentIndex(i + 1);
            m_ui->invalidQtWarningLabel->setVisible(!versions.at(i)->isValid());
        }
    }

    // And connect again
    connect(m_ui->qtVersionComboBox, SIGNAL(currentIndexChanged(QString)),
        this, SLOT(qtVersionComboBoxCurrentIndexChanged(QString)));
}

void Qt4BuildConfigWidget::onBeforeBeforeShadowBuildDirBrowsed()
{
    QString initialDirectory = QFileInfo(m_pro->file()->fileName()).absolutePath();
    if (!initialDirectory.isEmpty())
        m_ui->shadowBuildDirEdit->setInitialBrowsePathBackup(initialDirectory);
}

void Qt4BuildConfigWidget::shadowBuildCheckBoxClicked(bool checked)
{
    m_ui->shadowBuildDirEdit->setEnabled(checked);
    bool b = m_ui->shadowBuildCheckBox->isChecked();
    m_pro->setValue(m_buildConfiguration, "useShadowBuild", b);
    if (b)
        m_pro->setValue(m_buildConfiguration, "buildDirectory", m_ui->shadowBuildDirEdit->path());
    else
        m_pro->setValue(m_buildConfiguration, "buildDirectory", QVariant(QString::null));
}

void Qt4BuildConfigWidget::updateImportLabel()
{
    m_ui->importLabel->setVisible(false);
    if (m_ui->shadowBuildCheckBox->isChecked()) {
        QString qtPath = m_pro->qt4ProjectManager()->versionManager()->findQtVersionFromMakefile(m_ui->shadowBuildDirEdit->path());
        if (!qtPath.isEmpty()) {
            m_ui->importLabel->setVisible(true);
        }
    }
}

void Qt4BuildConfigWidget::shadowBuildLineEditTextChanged()
{
    if (m_pro->value(m_buildConfiguration, "buildDirectory").toString() == m_ui->shadowBuildDirEdit->path())
        return;
    m_pro->setValue(m_buildConfiguration, "buildDirectory", m_ui->shadowBuildDirEdit->path());
    // if the directory already exists
    // check if we have a build in there and
    // offer to import it
    updateImportLabel();

    m_pro->invalidateCachedTargetInformation();

//    QFileInfo fi(m_ui->shadowBuildDirEdit->path());
//    if (fi.exists()) {
//        m_ui->shadowBuildLineEdit->setStyleSheet("");
//        m_ui->shadowBuildLineEdit->setToolTip("");
//    } else {
//        m_ui->shadowBuildLineEdit->setStyleSheet("background: red;");
//        m_ui->shadowBuildLineEdit->setToolTip(tr("Directory does not exist."));
//    }
}

void Qt4BuildConfigWidget::importLabelClicked()
{
    if (m_ui->shadowBuildCheckBox->isChecked()) {
        QString directory = m_ui->shadowBuildDirEdit->path();
        if (!directory.isEmpty()) {
            QtVersionManager *vm = m_pro->qt4ProjectManager()->versionManager();
            QString qtPath = vm->findQtVersionFromMakefile(directory);
            if (!qtPath.isEmpty()) {
                QtVersion *version = vm->qtVersionForDirectory(qtPath);
                if (!version) {
                    version = new QtVersion(QFileInfo(qtPath).baseName(), qtPath);
                    vm->addVersion(version);
                }
                QtVersion::QmakeBuildConfig qmakeBuildConfig = version->defaultBuildConfig();
                qmakeBuildConfig = vm->scanMakefileForQmakeConfig(directory, qmakeBuildConfig);

                // So we got all the information now apply it...
                m_pro->setQtVersion(m_buildConfiguration, version->uniqueId());
                // Combo box will be updated at the end

                // Find qmakestep...
                QMakeStep *qmakeStep = m_pro->qmakeStep();
                MakeStep *makeStep = m_pro->makeStep();

                qmakeStep->setValue(m_buildConfiguration, "buildConfiguration", int(qmakeBuildConfig));
                // Adjust command line arguments, this is ugly as hell
                // If we are switching to BuildAll we want "release" in there and no "debug"
                // or "debug" in there and no "release"
                // If we are switching to not BuildAl we want neither "release" nor "debug" in there
                QStringList makeCmdArguments = makeStep->value(m_buildConfiguration, "makeargs").toStringList();
                bool debug = qmakeBuildConfig & QtVersion::DebugBuild;
                if (qmakeBuildConfig & QtVersion::BuildAll) {
                    makeCmdArguments.removeAll(debug ? "release" : "debug");
                    if (!makeCmdArguments.contains(debug ? "debug" : "release"))
                        makeCmdArguments.append(debug ? "debug" : "release");
                } else {
                    makeCmdArguments.removeAll("debug");
                    makeCmdArguments.removeAll("remove");
                }
                makeStep->setValue(m_buildConfiguration, "makeargs", makeCmdArguments);
            }
        }
    }
    setupQtVersionsComboBox();
}

void Qt4BuildConfigWidget::qtVersionComboBoxCurrentIndexChanged(const QString &)
{
    //Qt Version
    int newQtVersion;
    if (m_ui->qtVersionComboBox->currentIndex() == 0) {
        newQtVersion = 0;
    } else {
        newQtVersion = m_ui->qtVersionComboBox->itemData(m_ui->qtVersionComboBox->currentIndex()).toInt();
    }
    bool isValid = m_pro->qt4ProjectManager()->versionManager()->version(newQtVersion)->isValid();
    m_ui->invalidQtWarningLabel->setVisible(!isValid);
    if (newQtVersion != m_pro->qtVersionId(m_buildConfiguration)) {
        m_pro->setQtVersion(m_buildConfiguration, newQtVersion);
        m_pro->update();
    }
}
<|endoftext|>