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

#include "base/command_line.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"

namespace {

// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
 public:
  BrowserClosedObserver(Browser* browser) {
    registrar_.Add(this, NotificationType::BROWSER_CLOSED,
                   Source<Browser>(browser));
    ui_test_utils::RunMessageLoop();
  }

  virtual void Observe(NotificationType type,
                       const NotificationSource& source,
                       const NotificationDetails& details) {
    MessageLoopForUI::current()->Quit();
  }

 private:
  NotificationRegistrar registrar_;
  DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};

// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;

const wchar_t kConsoleTestPage[] = L"files/devtools/console_test_page.html";
const wchar_t kDebuggerTestPage[] = L"files/devtools/debugger_test_page.html";
const wchar_t kEvalTestPage[] = L"files/devtools/eval_test_page.html";
const wchar_t kJsPage[] = L"files/devtools/js_page.html";
const wchar_t kResourceTestPage[] = L"files/devtools/resource_test_page.html";
const wchar_t kSimplePage[] = L"files/devtools/simple_page.html";

class DevToolsSanityTest : public InProcessBrowserTest {
 public:
  DevToolsSanityTest() {
    set_show_window(true);
    EnableDOMAutomation();
  }

 protected:
  void RunTest(const std::string& test_name, const std::wstring& test_page) {
    OpenDevToolsWindow(test_page);
    std::string result;

    // At first check that JavaScript part of the front-end is loaded by
    // checking that global variable uiTests exists(it's created after all js
    // files have been loaded) and has runTest method.
    ASSERT_TRUE(
        ui_test_utils::ExecuteJavaScriptAndExtractString(
            client_contents_->render_view_host(),
            L"",
            L"window.domAutomationController.send("
            L"'' + (window.uiTests && (typeof uiTests.runTest)));",
            &result));

    if (result == "function") {
      ASSERT_TRUE(
          ui_test_utils::ExecuteJavaScriptAndExtractString(
              client_contents_->render_view_host(),
              L"",
              UTF8ToWide(StringPrintf("uiTests.runTest('%s')",
                                      test_name.c_str())),
              &result));
      EXPECT_EQ("[OK]", result);
    } else {
      FAIL() << "DevTools front-end is broken.";
    }
    CloseDevToolsWindow();
  }

  void OpenDevToolsWindow(const std::wstring& test_page) {
    HTTPTestServer* server = StartHTTPServer();
    GURL url = server->TestServerPageW(test_page);
    ui_test_utils::NavigateToURL(browser(), url);

    TabContents* tab = browser()->GetTabContentsAt(0);
    inspected_rvh_ = tab->render_view_host();
    DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
    devtools_manager->OpenDevToolsWindow(inspected_rvh_);

    DevToolsClientHost* client_host =
        devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
    window_ = client_host->AsDevToolsWindow();
    RenderViewHost* client_rvh = window_->GetRenderViewHost();
    client_contents_ = client_rvh->delegate()->GetAsTabContents();
    ui_test_utils::WaitForNavigation(&client_contents_->controller());
  }

  void CloseDevToolsWindow() {
    DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
    // UnregisterDevToolsClientHostFor may destroy window_ so store the browser
    // first.
    Browser* browser = window_->browser();
    devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);
    BrowserClosedObserver close_observer(browser);
  }

  TabContents* client_contents_;
  DevToolsWindow* window_;
  RenderViewHost* inspected_rvh_;
};

// WebInspector opens.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHostIsPresent) {
  RunTest("testHostIsPresent", kSimplePage);
}

// Tests elements panel basics.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestElementsTreeRoot) {
  RunTest("testElementsTreeRoot", kSimplePage);
}

// Tests main resource load.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestMainResource) {
  RunTest("testMainResource", kSimplePage);
}

// Tests resources panel enabling.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) {
  RunTest("testEnableResourcesTab", kSimplePage);
}

// Tests resource headers.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceHeaders) {
  RunTest("testResourceHeaders", kResourceTestPage);
}

// Tests profiler panel.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) {
  RunTest("testProfilerTab", kJsPage);
}

// Tests scripts panel showing.
// http://crbug.com/16767
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {
  RunTest("testShowScriptsTab", kDebuggerTestPage);
}

// Tests set breakpoint.
// http://crbug.com/16767
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestSetBreakpoint) {
  RunTest("testSetBreakpoint", kDebuggerTestPage);
}

// Tests that 'Pause' button works for eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) {
  RunTest("testPauseInEval", kDebuggerTestPage);
}

// Tests console eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleEval) {
  RunTest("testConsoleEval", kConsoleTestPage);
}

// Tests console log.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleLog) {
  RunTest("testConsoleLog", kConsoleTestPage);
}

// Tests eval global values.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalGlobal) {
  RunTest("testEvalGlobal", kEvalTestPage);
}

// Tests eval on call frame.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalCallFrame) {
  RunTest("testEvalCallFrame", kEvalTestPage);
}

}  // namespace
<commit_msg>DevTools: temporary disable TestConsoleLog and TestEvalGlobal that would fail with next WebKit roll. Review URL: http://codereview.chromium.org/208009<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"

namespace {

// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
 public:
  BrowserClosedObserver(Browser* browser) {
    registrar_.Add(this, NotificationType::BROWSER_CLOSED,
                   Source<Browser>(browser));
    ui_test_utils::RunMessageLoop();
  }

  virtual void Observe(NotificationType type,
                       const NotificationSource& source,
                       const NotificationDetails& details) {
    MessageLoopForUI::current()->Quit();
  }

 private:
  NotificationRegistrar registrar_;
  DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};

// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;

const wchar_t kConsoleTestPage[] = L"files/devtools/console_test_page.html";
const wchar_t kDebuggerTestPage[] = L"files/devtools/debugger_test_page.html";
const wchar_t kEvalTestPage[] = L"files/devtools/eval_test_page.html";
const wchar_t kJsPage[] = L"files/devtools/js_page.html";
const wchar_t kResourceTestPage[] = L"files/devtools/resource_test_page.html";
const wchar_t kSimplePage[] = L"files/devtools/simple_page.html";

class DevToolsSanityTest : public InProcessBrowserTest {
 public:
  DevToolsSanityTest() {
    set_show_window(true);
    EnableDOMAutomation();
  }

 protected:
  void RunTest(const std::string& test_name, const std::wstring& test_page) {
    OpenDevToolsWindow(test_page);
    std::string result;

    // At first check that JavaScript part of the front-end is loaded by
    // checking that global variable uiTests exists(it's created after all js
    // files have been loaded) and has runTest method.
    ASSERT_TRUE(
        ui_test_utils::ExecuteJavaScriptAndExtractString(
            client_contents_->render_view_host(),
            L"",
            L"window.domAutomationController.send("
            L"'' + (window.uiTests && (typeof uiTests.runTest)));",
            &result));

    if (result == "function") {
      ASSERT_TRUE(
          ui_test_utils::ExecuteJavaScriptAndExtractString(
              client_contents_->render_view_host(),
              L"",
              UTF8ToWide(StringPrintf("uiTests.runTest('%s')",
                                      test_name.c_str())),
              &result));
      EXPECT_EQ("[OK]", result);
    } else {
      FAIL() << "DevTools front-end is broken.";
    }
    CloseDevToolsWindow();
  }

  void OpenDevToolsWindow(const std::wstring& test_page) {
    HTTPTestServer* server = StartHTTPServer();
    GURL url = server->TestServerPageW(test_page);
    ui_test_utils::NavigateToURL(browser(), url);

    TabContents* tab = browser()->GetTabContentsAt(0);
    inspected_rvh_ = tab->render_view_host();
    DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
    devtools_manager->OpenDevToolsWindow(inspected_rvh_);

    DevToolsClientHost* client_host =
        devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
    window_ = client_host->AsDevToolsWindow();
    RenderViewHost* client_rvh = window_->GetRenderViewHost();
    client_contents_ = client_rvh->delegate()->GetAsTabContents();
    ui_test_utils::WaitForNavigation(&client_contents_->controller());
  }

  void CloseDevToolsWindow() {
    DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
    // UnregisterDevToolsClientHostFor may destroy window_ so store the browser
    // first.
    Browser* browser = window_->browser();
    devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);
    BrowserClosedObserver close_observer(browser);
  }

  TabContents* client_contents_;
  DevToolsWindow* window_;
  RenderViewHost* inspected_rvh_;
};

// WebInspector opens.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHostIsPresent) {
  RunTest("testHostIsPresent", kSimplePage);
}

// Tests elements panel basics.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestElementsTreeRoot) {
  RunTest("testElementsTreeRoot", kSimplePage);
}

// Tests main resource load.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestMainResource) {
  RunTest("testMainResource", kSimplePage);
}

// Tests resources panel enabling.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) {
  RunTest("testEnableResourcesTab", kSimplePage);
}

// Tests resource headers.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceHeaders) {
  RunTest("testResourceHeaders", kResourceTestPage);
}

// Tests profiler panel.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) {
  RunTest("testProfilerTab", kJsPage);
}

// Tests scripts panel showing.
// http://crbug.com/16767
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {
  RunTest("testShowScriptsTab", kDebuggerTestPage);
}

// Tests set breakpoint.
// http://crbug.com/16767
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestSetBreakpoint) {
  RunTest("testSetBreakpoint", kDebuggerTestPage);
}

// Tests that 'Pause' button works for eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) {
  RunTest("testPauseInEval", kDebuggerTestPage);
}

// Tests console eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleEval) {
  RunTest("testConsoleEval", kConsoleTestPage);
}

// Tests console log.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestConsoleLog) {
  RunTest("testConsoleLog", kConsoleTestPage);
}

// Tests eval global values.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestEvalGlobal) {
  RunTest("testEvalGlobal", kEvalTestPage);
}

// Tests eval on call frame.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalCallFrame) {
  RunTest("testEvalCallFrame", kEvalTestPage);
}

}  // namespace
<|endoftext|>


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

#include "chrome/browser/extensions/extension_apitest.h"
#include "net/base/mock_host_resolver.h"

class ExecuteScriptApiTest : public ExtensionApiTest {
 protected:
  void SetupDelayedHostResolver() {
    // We need a.com to be a little bit slow to trigger a race condition.
    host_resolver()->AddRuleWithLatency("a.com", "127.0.0.1", 500);
    host_resolver()->AddRule("b.com", "127.0.0.1");
    host_resolver()->AddRule("c.com", "127.0.0.1");
  }
};

IN_PROC_BROWSER_TEST_F(ExecuteScriptApiTest, ExecuteScriptBasic) {
  SetupDelayedHostResolver();
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionTest("executescript/basic")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExecuteScriptApiTest, ExecuteScriptInFrame) {
  SetupDelayedHostResolver();
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionTest("executescript/in_frame")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExecuteScriptApiTest, ExecuteScriptPermissions) {
  SetupDelayedHostResolver();
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionTest("executescript/permissions")) << message_;
}

// http://crbug.com/84760
#if defined(OS_CHROMEOS)
#define MAYBE_ExecuteScriptFileAfterClose DISABLED_ExecuteScriptFileAfterClose
#else
#define MAYBE_ExecuteScriptFileAfterClose ExecuteScriptFileAfterClose
#endif  // defined(OS_CHROMEOS)

IN_PROC_BROWSER_TEST_F(ExecuteScriptApiTest,
                       MAYBE_ExecuteScriptFileAfterClose) {
  host_resolver()->AddRule("b.com", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionTest("executescript/file_after_close")) << message_;
}

// Crashy, http://crbug.com/67774.
IN_PROC_BROWSER_TEST_F(ExecuteScriptApiTest,
                       DISABLED_ExecuteScriptFragmentNavigation) {
  ASSERT_TRUE(StartTestServer());
  const char* extension_name = "executescript/fragment";
  ASSERT_TRUE(RunExtensionTest(extension_name)) << message_;
}

// Time-outy linux. http://crbug.com/89076
#if defined(OS_LINUX)
#define MAYBE_NavigationRaceExecuteScript DISABLED_NavigationRaceExecuteScript
#else
#define MAYBE_NavigationRaceExecuteScript NavigationRaceExecuteScript
#endif
IN_PROC_BROWSER_TEST_F(ExecuteScriptApiTest,
                       MAYBE_NavigationRaceExecuteScript) {
  host_resolver()->AddRule("a.com", "127.0.0.1");
  host_resolver()->AddRule("b.com", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionSubtest("executescript/navigation_race",
                                  "execute_script.html")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExecuteScriptApiTest, NavigationRaceJavaScriptUrl) {
  host_resolver()->AddRule("a.com", "127.0.0.1");
  host_resolver()->AddRule("b.com", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionSubtest("executescript/navigation_race",
                                  "javascript_url.html")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExecuteScriptApiTest, ExecuteScriptFrameAfterLoad) {
  SetupDelayedHostResolver();
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionTest("executescript/frame_after_load")) << message_;
}
<commit_msg>Forgot to actually re-enable the test in r92388.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/extension_apitest.h"
#include "net/base/mock_host_resolver.h"

class ExecuteScriptApiTest : public ExtensionApiTest {
 protected:
  void SetupDelayedHostResolver() {
    // We need a.com to be a little bit slow to trigger a race condition.
    host_resolver()->AddRuleWithLatency("a.com", "127.0.0.1", 500);
    host_resolver()->AddRule("b.com", "127.0.0.1");
    host_resolver()->AddRule("c.com", "127.0.0.1");
  }
};

IN_PROC_BROWSER_TEST_F(ExecuteScriptApiTest, ExecuteScriptBasic) {
  SetupDelayedHostResolver();
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionTest("executescript/basic")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExecuteScriptApiTest, ExecuteScriptInFrame) {
  SetupDelayedHostResolver();
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionTest("executescript/in_frame")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExecuteScriptApiTest, ExecuteScriptPermissions) {
  SetupDelayedHostResolver();
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionTest("executescript/permissions")) << message_;
}

// http://crbug.com/84760
#if defined(OS_CHROMEOS)
#define MAYBE_ExecuteScriptFileAfterClose DISABLED_ExecuteScriptFileAfterClose
#else
#define MAYBE_ExecuteScriptFileAfterClose ExecuteScriptFileAfterClose
#endif  // defined(OS_CHROMEOS)

IN_PROC_BROWSER_TEST_F(ExecuteScriptApiTest,
                       MAYBE_ExecuteScriptFileAfterClose) {
  host_resolver()->AddRule("b.com", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionTest("executescript/file_after_close")) << message_;
}

// Crashy, http://crbug.com/67774.
IN_PROC_BROWSER_TEST_F(ExecuteScriptApiTest,
                       DISABLED_ExecuteScriptFragmentNavigation) {
  ASSERT_TRUE(StartTestServer());
  const char* extension_name = "executescript/fragment";
  ASSERT_TRUE(RunExtensionTest(extension_name)) << message_;
}

IN_PROC_BROWSER_TEST_F(ExecuteScriptApiTest, NavigationRaceExecuteScript) {
  host_resolver()->AddRule("a.com", "127.0.0.1");
  host_resolver()->AddRule("b.com", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionSubtest("executescript/navigation_race",
                                  "execute_script.html")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExecuteScriptApiTest, NavigationRaceJavaScriptUrl) {
  host_resolver()->AddRule("a.com", "127.0.0.1");
  host_resolver()->AddRule("b.com", "127.0.0.1");
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionSubtest("executescript/navigation_race",
                                  "javascript_url.html")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExecuteScriptApiTest, ExecuteScriptFrameAfterLoad) {
  SetupDelayedHostResolver();
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionTest("executescript/frame_after_load")) << message_;
}
<|endoftext|>


<commit_before>/*
    This file is part of the kolab resource - the implementation of the
    Kolab storage format. See www.kolab.org for documentation on this.

    Copyright (c) 2004 Bo Thorsen <bo@sonofthor.dk>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include "task.h"

#include <libkcal/todo.h>
#include <kdebug.h>

using namespace Kolab;

KCal::Todo* Task::xmlToTask( const QString& xml, const QString& tz )
{
  Task task( tz );
  task.load( xml );
  KCal::Todo* todo = new KCal::Todo();
  task.saveTo( todo );
  return todo;
}

QString Task::taskToXML( KCal::Todo* todo, const QString& tz )
{
  Task task( tz, todo );
  return task.saveXML();
}

Task::Task( const QString& tz, KCal::Todo* task )
  : Incidence( tz ), mPriority( 3 ), mPercentCompleted( 100 ),
    mStatus( KCal::Incidence::StatusNone ),
    mHasStartDate( false ), mHasDueDate( false ),
    mHasCompletedDate( false )
{
  if ( task )
    setFields( task );
}

Task::~Task()
{
}

void Task::setPriority( int priority )
{
  mPriority = priority;
}

int Task::priority() const
{
  return mPriority;
}

void Task::setPercentCompleted( int percent )
{
  mPercentCompleted = percent;
}

int Task::percentCompleted() const
{
  return mPercentCompleted;
}

void Task::setStatus( KCal::Incidence::Status status )
{
  mStatus = status;
}

KCal::Incidence::Status Task::status() const
{
  return mStatus;
}

void Task::setParent( const QString& parentUid )
{
  mParent = parentUid;
}

QString Task::parent() const
{
  return mParent;
}

void Task::setDueDate( const QDateTime& date )
{
  mDueDate = date;
  mHasDueDate = true;
}

QDateTime Task::dueDate() const
{
  return mDueDate;
}

void Task::setHasStartDate( bool v )
{
  mHasStartDate = v;
}

bool Task::hasStartDate() const
{
  return mHasStartDate;
}

bool Task::hasDueDate() const
{
  return mHasDueDate;
}

void Task::setCompletedDate( const QDateTime& date )
{
  mCompletedDate = date;
  mHasCompletedDate = true;
}

QDateTime Task::completedDate() const
{
  return mCompletedDate;
}

bool Task::hasCompletedDate() const
{
  return mHasCompletedDate;
}

bool Task::loadAttribute( QDomElement& element )
{
  QString tagName = element.tagName();

  if ( tagName == "priority" ) {
    bool ok;
    int priority = element.text().toInt( &ok );
    if ( !ok || priority < 0 || priority > 5 )
      priority = 3;
    setPriority( priority );
  } else if ( tagName == "completed" ) {
    bool ok;
    int percent = element.text().toInt( &ok );
    if ( !ok || percent < 0 || percent > 100 )
      percent = 0;
    setPercentCompleted( percent );
  } else if ( tagName == "status" ) {
    if ( element.text() == "in-progress" )
      setStatus( KCal::Incidence::StatusInProcess );
    else if ( element.text() == "completed" )
      setStatus( KCal::Incidence::StatusCompleted );
    else if ( element.text() == "waiting-on-someone-else" )
      setStatus( KCal::Incidence::StatusNeedsAction );
    else if ( element.text() == "deferred" )
      // Guessing a status here
      setStatus( KCal::Incidence::StatusCanceled );
    else
      // Default
      setStatus( KCal::Incidence::StatusNone );
  } else if ( tagName == "due-date" )
    setDueDate( stringToDateTime( element.text() ) );
  else if ( tagName == "parent" )
    setParent( element.text() );
  else if ( tagName == "x-completed-date" )
    setCompletedDate( stringToDateTime( element.text() ) );
  else if ( tagName == "start-date" ) {
    setHasStartDate( true );
    setStartDate( element.text() );
  } else
    return Incidence::loadAttribute( element );

  // We handled this
  return true;
}

bool Task::saveAttributes( QDomElement& element ) const
{
  // Save the base class elements
  Incidence::saveAttributes( element );

  writeString( element, "priority", QString::number( priority() ) );
  writeString( element, "completed", QString::number( percentCompleted() ) );

  switch( status() ) {
  case KCal::Incidence::StatusInProcess:
    writeString( element, "status", "in-progress" );
    break;
  case KCal::Incidence::StatusCompleted:
    writeString( element, "status", "completed" );
    break;
  case KCal::Incidence::StatusNeedsAction:
    writeString( element, "status", "waiting-on-someone-else" );
    break;
  case KCal::Incidence::StatusCanceled:
    writeString( element, "status", "deferred" );
    break;
  case KCal::Incidence::StatusNone:
    writeString( element, "status", "not-started" );
    break;
  case KCal::Incidence::StatusTentative:
  case KCal::Incidence::StatusConfirmed:
  case KCal::Incidence::StatusDraft:
  case KCal::Incidence::StatusFinal:
  case KCal::Incidence::StatusX:
    // All of these are saved as StatusNone.
    writeString( element, "status", "not-started" );
    break;
  }

  if ( hasDueDate() )
    writeString( element, "due-date", dateTimeToString( dueDate() ) );

  if ( !parent().isNull() )
    writeString( element, "parent", parent() );

  if ( hasCompletedDate() )
    writeString( element, "x-completed-date", dateTimeToString( completedDate() ) );

  return true;
}

bool Task::loadXML( const QDomDocument& document )
{
  QDomElement top = document.documentElement();

  if ( top.tagName() != "task" ) {
    qWarning( "XML error: Top tag was %s instead of the expected task",
              top.tagName().ascii() );
    return false;
  }
  setHasStartDate( false ); // todo's don't necessarily have one

  for ( QDomNode n = top.firstChild(); !n.isNull(); n = n.nextSibling() ) {
    if ( n.isComment() )
      continue;
    if ( n.isElement() ) {
      QDomElement e = n.toElement();
      if ( !loadAttribute( e ) )
        // TODO: Unhandled tag - save for later storage
        kdDebug() << "Warning: Unhandled tag " << e.tagName() << endl;
    } else
      kdDebug() << "Node is not a comment or an element???" << endl;
  }

  return true;
}

QString Task::saveXML() const
{
  QDomDocument document = domTree();
  QDomElement element = document.createElement( "task" );
  element.setAttribute( "version", "1.0" );
  saveAttributes( element );
  if ( !hasStartDate() ) {
    // events and journals always have a start date, but tasks don't.
    // Remove the entry done by the inherited save above, because we
    // don't have one.
    QDomNodeList l = element.elementsByTagName( "start-date" );
    Q_ASSERT( l.count() == 1 );
    element.removeChild( l.item( 0 ) );
  }
  document.appendChild( element );
  return document.toString();
}

void Task::setFields( const KCal::Todo* task )
{
  Incidence::setFields( task );

  setPriority( task->priority() );
  setPercentCompleted( task->percentComplete() );
  setStatus( task->status() );
  setHasStartDate( task->hasStartDate() );

  if ( task->hasDueDate() )
    setDueDate( localToUTC( task->dtDue() ) );
  else
    mHasDueDate = false;
  if ( task->relatedTo() )
    setParent( task->relatedTo()->uid() );
  else
    setParent( QString::null );

  if ( task->hasCompletedDate() )
    setCompletedDate( localToUTC( task->completed() ) );
  else
    mHasCompletedDate = false;
}

void Task::saveTo( KCal::Todo* task )
{
  Incidence::saveTo( task );

  task->setPriority( priority() );
  task->setPercentComplete( percentCompleted() );
  task->setStatus( status() );
  task->setHasStartDate( hasStartDate() );
  task->setHasDueDate( hasDueDate() );
  if ( hasDueDate() )
    task->setDtDue( utcToLocal( dueDate() ) );

  if ( parent() != QString::null )
    task->setRelatedToUid( parent() );

  if ( hasCompletedDate() )
    task->setCompleted( utcToLocal( mCompletedDate ) );
}
<commit_msg>Default to 0% completed, not 100%, as per spec.<commit_after>/*
    This file is part of the kolab resource - the implementation of the
    Kolab storage format. See www.kolab.org for documentation on this.

    Copyright (c) 2004 Bo Thorsen <bo@sonofthor.dk>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include "task.h"

#include <libkcal/todo.h>
#include <kdebug.h>

using namespace Kolab;

KCal::Todo* Task::xmlToTask( const QString& xml, const QString& tz )
{
  Task task( tz );
  task.load( xml );
  KCal::Todo* todo = new KCal::Todo();
  task.saveTo( todo );
  return todo;
}

QString Task::taskToXML( KCal::Todo* todo, const QString& tz )
{
  Task task( tz, todo );
  return task.saveXML();
}

Task::Task( const QString& tz, KCal::Todo* task )
  : Incidence( tz ), mPriority( 3 ), mPercentCompleted( 0 ),
    mStatus( KCal::Incidence::StatusNone ),
    mHasStartDate( false ), mHasDueDate( false ),
    mHasCompletedDate( false )
{
  if ( task )
    setFields( task );
}

Task::~Task()
{
}

void Task::setPriority( int priority )
{
  mPriority = priority;
}

int Task::priority() const
{
  return mPriority;
}

void Task::setPercentCompleted( int percent )
{
  mPercentCompleted = percent;
}

int Task::percentCompleted() const
{
  return mPercentCompleted;
}

void Task::setStatus( KCal::Incidence::Status status )
{
  mStatus = status;
}

KCal::Incidence::Status Task::status() const
{
  return mStatus;
}

void Task::setParent( const QString& parentUid )
{
  mParent = parentUid;
}

QString Task::parent() const
{
  return mParent;
}

void Task::setDueDate( const QDateTime& date )
{
  mDueDate = date;
  mHasDueDate = true;
}

QDateTime Task::dueDate() const
{
  return mDueDate;
}

void Task::setHasStartDate( bool v )
{
  mHasStartDate = v;
}

bool Task::hasStartDate() const
{
  return mHasStartDate;
}

bool Task::hasDueDate() const
{
  return mHasDueDate;
}

void Task::setCompletedDate( const QDateTime& date )
{
  mCompletedDate = date;
  mHasCompletedDate = true;
}

QDateTime Task::completedDate() const
{
  return mCompletedDate;
}

bool Task::hasCompletedDate() const
{
  return mHasCompletedDate;
}

bool Task::loadAttribute( QDomElement& element )
{
  QString tagName = element.tagName();

  if ( tagName == "priority" ) {
    bool ok;
    int priority = element.text().toInt( &ok );
    if ( !ok || priority < 0 || priority > 5 )
      priority = 3;
    setPriority( priority );
  } else if ( tagName == "completed" ) {
    bool ok;
    int percent = element.text().toInt( &ok );
    if ( !ok || percent < 0 || percent > 100 )
      percent = 0;
    setPercentCompleted( percent );
  } else if ( tagName == "status" ) {
    if ( element.text() == "in-progress" )
      setStatus( KCal::Incidence::StatusInProcess );
    else if ( element.text() == "completed" )
      setStatus( KCal::Incidence::StatusCompleted );
    else if ( element.text() == "waiting-on-someone-else" )
      setStatus( KCal::Incidence::StatusNeedsAction );
    else if ( element.text() == "deferred" )
      // Guessing a status here
      setStatus( KCal::Incidence::StatusCanceled );
    else
      // Default
      setStatus( KCal::Incidence::StatusNone );
  } else if ( tagName == "due-date" )
    setDueDate( stringToDateTime( element.text() ) );
  else if ( tagName == "parent" )
    setParent( element.text() );
  else if ( tagName == "x-completed-date" )
    setCompletedDate( stringToDateTime( element.text() ) );
  else if ( tagName == "start-date" ) {
    setHasStartDate( true );
    setStartDate( element.text() );
  } else
    return Incidence::loadAttribute( element );

  // We handled this
  return true;
}

bool Task::saveAttributes( QDomElement& element ) const
{
  // Save the base class elements
  Incidence::saveAttributes( element );

  writeString( element, "priority", QString::number( priority() ) );
  writeString( element, "completed", QString::number( percentCompleted() ) );

  switch( status() ) {
  case KCal::Incidence::StatusInProcess:
    writeString( element, "status", "in-progress" );
    break;
  case KCal::Incidence::StatusCompleted:
    writeString( element, "status", "completed" );
    break;
  case KCal::Incidence::StatusNeedsAction:
    writeString( element, "status", "waiting-on-someone-else" );
    break;
  case KCal::Incidence::StatusCanceled:
    writeString( element, "status", "deferred" );
    break;
  case KCal::Incidence::StatusNone:
    writeString( element, "status", "not-started" );
    break;
  case KCal::Incidence::StatusTentative:
  case KCal::Incidence::StatusConfirmed:
  case KCal::Incidence::StatusDraft:
  case KCal::Incidence::StatusFinal:
  case KCal::Incidence::StatusX:
    // All of these are saved as StatusNone.
    writeString( element, "status", "not-started" );
    break;
  }

  if ( hasDueDate() )
    writeString( element, "due-date", dateTimeToString( dueDate() ) );

  if ( !parent().isNull() )
    writeString( element, "parent", parent() );

  if ( hasCompletedDate() )
    writeString( element, "x-completed-date", dateTimeToString( completedDate() ) );

  return true;
}

bool Task::loadXML( const QDomDocument& document )
{
  QDomElement top = document.documentElement();

  if ( top.tagName() != "task" ) {
    qWarning( "XML error: Top tag was %s instead of the expected task",
              top.tagName().ascii() );
    return false;
  }
  setHasStartDate( false ); // todo's don't necessarily have one

  for ( QDomNode n = top.firstChild(); !n.isNull(); n = n.nextSibling() ) {
    if ( n.isComment() )
      continue;
    if ( n.isElement() ) {
      QDomElement e = n.toElement();
      if ( !loadAttribute( e ) )
        // TODO: Unhandled tag - save for later storage
        kdDebug() << "Warning: Unhandled tag " << e.tagName() << endl;
    } else
      kdDebug() << "Node is not a comment or an element???" << endl;
  }

  return true;
}

QString Task::saveXML() const
{
  QDomDocument document = domTree();
  QDomElement element = document.createElement( "task" );
  element.setAttribute( "version", "1.0" );
  saveAttributes( element );
  if ( !hasStartDate() ) {
    // events and journals always have a start date, but tasks don't.
    // Remove the entry done by the inherited save above, because we
    // don't have one.
    QDomNodeList l = element.elementsByTagName( "start-date" );
    Q_ASSERT( l.count() == 1 );
    element.removeChild( l.item( 0 ) );
  }
  document.appendChild( element );
  return document.toString();
}

void Task::setFields( const KCal::Todo* task )
{
  Incidence::setFields( task );

  setPriority( task->priority() );
  setPercentCompleted( task->percentComplete() );
  setStatus( task->status() );
  setHasStartDate( task->hasStartDate() );

  if ( task->hasDueDate() )
    setDueDate( localToUTC( task->dtDue() ) );
  else
    mHasDueDate = false;
  if ( task->relatedTo() )
    setParent( task->relatedTo()->uid() );
  else
    setParent( QString::null );

  if ( task->hasCompletedDate() )
    setCompletedDate( localToUTC( task->completed() ) );
  else
    mHasCompletedDate = false;
}

void Task::saveTo( KCal::Todo* task )
{
  Incidence::saveTo( task );

  task->setPriority( priority() );
  task->setPercentComplete( percentCompleted() );
  task->setStatus( status() );
  task->setHasStartDate( hasStartDate() );
  task->setHasDueDate( hasDueDate() );
  if ( hasDueDate() )
    task->setDtDue( utcToLocal( dueDate() ) );

  if ( parent() != QString::null )
    task->setRelatedToUid( parent() );

  if ( hasCompletedDate() )
    task->setCompleted( utcToLocal( mCompletedDate ) );
}
<|endoftext|>


<commit_before>// Copyright (c) 2011 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 <algorithm>
#include <list>
#include <map>

#include "chrome/browser/browser_thread.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/login/login_prompt.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/auth.h"

namespace {

class LoginPromptBrowserTest : public InProcessBrowserTest {
 public:
  LoginPromptBrowserTest()
      : bad_password_(L"incorrect"), bad_username_(L"nouser") {
    set_show_window(true);

    auth_map_[L"foo"] = AuthInfo(L"testuser", L"foopassword");
    auth_map_[L"bar"] = AuthInfo(L"testuser", L"barpassword");
  }

 protected:
  void SetAuthFor(LoginHandler* handler);

  struct AuthInfo {
    std::wstring username_;
    std::wstring password_;

    AuthInfo() {}

    AuthInfo(const std::wstring username,
             const std::wstring password)
        : username_(username), password_(password) {}
  };

  std::map<std::wstring, AuthInfo> auth_map_;
  std::wstring bad_password_;
  std::wstring bad_username_;
};

void LoginPromptBrowserTest::SetAuthFor(LoginHandler* handler) {
  const net::AuthChallengeInfo* challenge = handler->auth_info();

  ASSERT_TRUE(challenge);
  std::map<std::wstring, AuthInfo>::iterator i =
      auth_map_.find(challenge->realm);
  EXPECT_TRUE(auth_map_.end() != i);
  if (i != auth_map_.end()) {
    const AuthInfo& info = i->second;
    handler->SetAuth(info.username_, info.password_);
  }
}

// Maintains a set of LoginHandlers that are currently active and
// keeps a count of the notifications that were observed.
class LoginPromptBrowserTestObserver : public NotificationObserver {
 public:
  LoginPromptBrowserTestObserver()
      : auth_needed_count_(0),
        auth_supplied_count_(0),
        auth_cancelled_count_(0) {}

  virtual void Observe(NotificationType type,
                       const NotificationSource& source,
                       const NotificationDetails& details);

  void AddHandler(LoginHandler* handler);

  void RemoveHandler(LoginHandler* handler);

  void Register(const NotificationSource& source);

  std::list<LoginHandler*> handlers_;

  // The exact number of notifications we receive is depedent on the
  // number of requests that were dispatched and is subject to a
  // number of factors that we don't directly control here.  The
  // values below should only be used qualitatively.
  int auth_needed_count_;
  int auth_supplied_count_;
  int auth_cancelled_count_;

 private:
  NotificationRegistrar registrar_;

  DISALLOW_COPY_AND_ASSIGN(LoginPromptBrowserTestObserver);
};

void LoginPromptBrowserTestObserver::Observe(
    NotificationType type,
    const NotificationSource& source,
    const NotificationDetails& details) {
  if (type == NotificationType::AUTH_NEEDED) {
    LoginNotificationDetails* login_details =
        Details<LoginNotificationDetails>(details).ptr();
    AddHandler(login_details->handler());
    auth_needed_count_++;
  } else if (type == NotificationType::AUTH_SUPPLIED) {
    AuthSuppliedLoginNotificationDetails* login_details =
        Details<AuthSuppliedLoginNotificationDetails>(details).ptr();
    RemoveHandler(login_details->handler());
    auth_supplied_count_++;
  } else if (type == NotificationType::AUTH_CANCELLED) {
    LoginNotificationDetails* login_details =
        Details<LoginNotificationDetails>(details).ptr();
    RemoveHandler(login_details->handler());
    auth_cancelled_count_++;
  }
}

void LoginPromptBrowserTestObserver::AddHandler(LoginHandler* handler) {
  std::list<LoginHandler*>::iterator i = std::find(handlers_.begin(),
                                                   handlers_.end(),
                                                   handler);
  EXPECT_TRUE(i == handlers_.end());
  if (i == handlers_.end())
    handlers_.push_back(handler);
}

void LoginPromptBrowserTestObserver::RemoveHandler(LoginHandler* handler) {
  std::list<LoginHandler*>::iterator i = std::find(handlers_.begin(),
                                                   handlers_.end(),
                                                   handler);
  EXPECT_TRUE(i != handlers_.end());
  if (i != handlers_.end())
    handlers_.erase(i);
}

void LoginPromptBrowserTestObserver::Register(
    const NotificationSource& source) {
  registrar_.Add(this, NotificationType::AUTH_NEEDED, source);
  registrar_.Add(this, NotificationType::AUTH_SUPPLIED, source);
  registrar_.Add(this, NotificationType::AUTH_CANCELLED, source);
}

template <NotificationType::Type T>
class WindowedNavigationObserver
    : public ui_test_utils::WindowedNotificationObserver {
 public:
  explicit WindowedNavigationObserver(NavigationController* controller)
      : ui_test_utils::WindowedNotificationObserver(
          T, Source<NavigationController>(controller)) {}
};

typedef WindowedNavigationObserver<NotificationType::LOAD_STOP>
    WindowedLoadStopObserver;

typedef WindowedNavigationObserver<NotificationType::AUTH_NEEDED>
    WindowedAuthNeededObserver;

typedef WindowedNavigationObserver<NotificationType::AUTH_CANCELLED>
    WindowedAuthCancelledObserver;

typedef WindowedNavigationObserver<NotificationType::AUTH_SUPPLIED>
    WindowedAuthSuppliedObserver;

const char* kMultiRealmTestPage = "files/login/multi_realm.html";
const int   kMultiRealmTestRealmCount = 2;
const int   kMultiRealmTestResourceCount = 4;

const char* kSingleRealmTestPage = "files/login/single_realm.html";
const int   kSingleRealmTestResourceCount = 6;

// Test handling of resources that require authentication even though
// the page they are included on doesn't.  In this case we should only
// present the minimal number of prompts necessary for successfully
// displaying the page.  First we check whether cancelling works as
// expected.
IN_PROC_BROWSER_TEST_F(LoginPromptBrowserTest, MultipleRealmCancellation) {
  ASSERT_TRUE(test_server()->Start());
  GURL test_page = test_server()->GetURL(kMultiRealmTestPage);

  TabContentsWrapper* contents =
      browser()->GetSelectedTabContentsWrapper();
  ASSERT_TRUE(contents);

  NavigationController* controller = &contents->controller();
  LoginPromptBrowserTestObserver observer;

  observer.Register(Source<NavigationController>(controller));

  WindowedLoadStopObserver load_stop_waiter(controller);

  {
    WindowedAuthNeededObserver auth_needed_waiter(controller);
    browser()->OpenURL(test_page, GURL(), CURRENT_TAB, PageTransition::TYPED);
    auth_needed_waiter.Wait();
  }

  int n_handlers = 0;

  while (n_handlers < kMultiRealmTestRealmCount) {
    WindowedAuthNeededObserver auth_needed_waiter(controller);

    while (!observer.handlers_.empty()) {
      WindowedAuthCancelledObserver auth_cancelled_waiter(controller);
      LoginHandler* handler = *observer.handlers_.begin();

      ASSERT_TRUE(handler);
      n_handlers++;
      handler->CancelAuth();
      auth_cancelled_waiter.Wait();
    }

    if (n_handlers < kMultiRealmTestRealmCount)
      auth_needed_waiter.Wait();
  }

  load_stop_waiter.Wait();

  EXPECT_EQ(kMultiRealmTestRealmCount, n_handlers);
  EXPECT_EQ(0, observer.auth_supplied_count_);
  EXPECT_LT(0, observer.auth_needed_count_);
  EXPECT_LT(0, observer.auth_cancelled_count_);
  EXPECT_TRUE(test_server()->Stop());
}

// Similar to the MultipleRealmCancellation test above, but tests
// whether supplying credentials work as exepcted.
IN_PROC_BROWSER_TEST_F(LoginPromptBrowserTest, MultipleRealmConfirmation) {
  ASSERT_TRUE(test_server()->Start());
  GURL test_page = test_server()->GetURL(kMultiRealmTestPage);

  TabContentsWrapper* contents =
      browser()->GetSelectedTabContentsWrapper();
  ASSERT_TRUE(contents);

  NavigationController* controller = &contents->controller();
  LoginPromptBrowserTestObserver observer;

  observer.Register(Source<NavigationController>(controller));

  WindowedLoadStopObserver load_stop_waiter(controller);
  int n_handlers = 0;

  {
    WindowedAuthNeededObserver auth_needed_waiter(controller);

    browser()->OpenURL(test_page, GURL(), CURRENT_TAB, PageTransition::TYPED);
    auth_needed_waiter.Wait();
  }

  while (n_handlers < kMultiRealmTestRealmCount) {
    WindowedAuthNeededObserver auth_needed_waiter(controller);

    while (!observer.handlers_.empty()) {
      WindowedAuthSuppliedObserver auth_supplied_waiter(controller);
      LoginHandler* handler = *observer.handlers_.begin();

      ASSERT_TRUE(handler);
      n_handlers++;
      SetAuthFor(handler);
      auth_supplied_waiter.Wait();
    }

    if (n_handlers < kMultiRealmTestRealmCount)
      auth_needed_waiter.Wait();
  }

  load_stop_waiter.Wait();

  EXPECT_EQ(kMultiRealmTestRealmCount, n_handlers);
  EXPECT_LT(0, observer.auth_needed_count_);
  EXPECT_LT(0, observer.auth_supplied_count_);
  EXPECT_EQ(0, observer.auth_cancelled_count_);
  EXPECT_TRUE(test_server()->Stop());
}

// Testing for recovery from an incorrect password for the case where
// there are multiple authenticated resources.
IN_PROC_BROWSER_TEST_F(LoginPromptBrowserTest, IncorrectConfirmation) {
  ASSERT_TRUE(test_server()->Start());
  GURL test_page = test_server()->GetURL(kSingleRealmTestPage);

  TabContentsWrapper* contents =
      browser()->GetSelectedTabContentsWrapper();
  ASSERT_TRUE(contents);

  NavigationController* controller = &contents->controller();
  LoginPromptBrowserTestObserver observer;

  observer.Register(Source<NavigationController>(controller));

  WindowedLoadStopObserver load_stop_waiter(controller);

  {
    WindowedAuthNeededObserver auth_needed_waiter(controller);
    browser()->OpenURL(test_page, GURL(), CURRENT_TAB, PageTransition::TYPED);
    auth_needed_waiter.Wait();
  }

  EXPECT_FALSE(observer.handlers_.empty());

  if (!observer.handlers_.empty()) {
    WindowedAuthNeededObserver auth_needed_waiter(controller);
    WindowedAuthSuppliedObserver auth_supplied_waiter(controller);
    LoginHandler* handler = *observer.handlers_.begin();

    ASSERT_TRUE(handler);
    handler->SetAuth(bad_username_, bad_password_);
    auth_supplied_waiter.Wait();

    // The request should be retried after the incorrect password is
    // supplied.  This should result in a new AUTH_NEEDED notification
    // for the same realm.
    auth_needed_waiter.Wait();
  }

  int n_handlers = 0;

  while (n_handlers < 1) {
    WindowedAuthNeededObserver auth_needed_waiter(controller);

    while (!observer.handlers_.empty()) {
      WindowedAuthSuppliedObserver auth_supplied_waiter(controller);
      LoginHandler* handler = *observer.handlers_.begin();

      ASSERT_TRUE(handler);
      n_handlers++;
      SetAuthFor(handler);
      auth_supplied_waiter.Wait();
    }

    if (n_handlers < 1)
      auth_needed_waiter.Wait();
  }

  load_stop_waiter.Wait();

  // The single realm test has only one realm, and thus only one login
  // prompt.
  EXPECT_EQ(1, n_handlers);
  EXPECT_LT(0, observer.auth_needed_count_);
  EXPECT_LT(0, observer.auth_supplied_count_);
  EXPECT_EQ(0, observer.auth_cancelled_count_);
  EXPECT_TRUE(test_server()->Stop());
}
} // namespace
<commit_msg>Marking test LoginPromptBrowserTest.IncorrectConfirmation as flaky.  See here for evidence: http://test-results.appspot.com/dashboards/flakiness_dashboard.html#testType=browser_tests&tests=LoginPromptBrowserTest.IncorrectConfirmation<commit_after>// Copyright (c) 2011 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 <algorithm>
#include <list>
#include <map>

#include "chrome/browser/browser_thread.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/login/login_prompt.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/auth.h"

namespace {

class LoginPromptBrowserTest : public InProcessBrowserTest {
 public:
  LoginPromptBrowserTest()
      : bad_password_(L"incorrect"), bad_username_(L"nouser") {
    set_show_window(true);

    auth_map_[L"foo"] = AuthInfo(L"testuser", L"foopassword");
    auth_map_[L"bar"] = AuthInfo(L"testuser", L"barpassword");
  }

 protected:
  void SetAuthFor(LoginHandler* handler);

  struct AuthInfo {
    std::wstring username_;
    std::wstring password_;

    AuthInfo() {}

    AuthInfo(const std::wstring username,
             const std::wstring password)
        : username_(username), password_(password) {}
  };

  std::map<std::wstring, AuthInfo> auth_map_;
  std::wstring bad_password_;
  std::wstring bad_username_;
};

void LoginPromptBrowserTest::SetAuthFor(LoginHandler* handler) {
  const net::AuthChallengeInfo* challenge = handler->auth_info();

  ASSERT_TRUE(challenge);
  std::map<std::wstring, AuthInfo>::iterator i =
      auth_map_.find(challenge->realm);
  EXPECT_TRUE(auth_map_.end() != i);
  if (i != auth_map_.end()) {
    const AuthInfo& info = i->second;
    handler->SetAuth(info.username_, info.password_);
  }
}

// Maintains a set of LoginHandlers that are currently active and
// keeps a count of the notifications that were observed.
class LoginPromptBrowserTestObserver : public NotificationObserver {
 public:
  LoginPromptBrowserTestObserver()
      : auth_needed_count_(0),
        auth_supplied_count_(0),
        auth_cancelled_count_(0) {}

  virtual void Observe(NotificationType type,
                       const NotificationSource& source,
                       const NotificationDetails& details);

  void AddHandler(LoginHandler* handler);

  void RemoveHandler(LoginHandler* handler);

  void Register(const NotificationSource& source);

  std::list<LoginHandler*> handlers_;

  // The exact number of notifications we receive is depedent on the
  // number of requests that were dispatched and is subject to a
  // number of factors that we don't directly control here.  The
  // values below should only be used qualitatively.
  int auth_needed_count_;
  int auth_supplied_count_;
  int auth_cancelled_count_;

 private:
  NotificationRegistrar registrar_;

  DISALLOW_COPY_AND_ASSIGN(LoginPromptBrowserTestObserver);
};

void LoginPromptBrowserTestObserver::Observe(
    NotificationType type,
    const NotificationSource& source,
    const NotificationDetails& details) {
  if (type == NotificationType::AUTH_NEEDED) {
    LoginNotificationDetails* login_details =
        Details<LoginNotificationDetails>(details).ptr();
    AddHandler(login_details->handler());
    auth_needed_count_++;
  } else if (type == NotificationType::AUTH_SUPPLIED) {
    AuthSuppliedLoginNotificationDetails* login_details =
        Details<AuthSuppliedLoginNotificationDetails>(details).ptr();
    RemoveHandler(login_details->handler());
    auth_supplied_count_++;
  } else if (type == NotificationType::AUTH_CANCELLED) {
    LoginNotificationDetails* login_details =
        Details<LoginNotificationDetails>(details).ptr();
    RemoveHandler(login_details->handler());
    auth_cancelled_count_++;
  }
}

void LoginPromptBrowserTestObserver::AddHandler(LoginHandler* handler) {
  std::list<LoginHandler*>::iterator i = std::find(handlers_.begin(),
                                                   handlers_.end(),
                                                   handler);
  EXPECT_TRUE(i == handlers_.end());
  if (i == handlers_.end())
    handlers_.push_back(handler);
}

void LoginPromptBrowserTestObserver::RemoveHandler(LoginHandler* handler) {
  std::list<LoginHandler*>::iterator i = std::find(handlers_.begin(),
                                                   handlers_.end(),
                                                   handler);
  EXPECT_TRUE(i != handlers_.end());
  if (i != handlers_.end())
    handlers_.erase(i);
}

void LoginPromptBrowserTestObserver::Register(
    const NotificationSource& source) {
  registrar_.Add(this, NotificationType::AUTH_NEEDED, source);
  registrar_.Add(this, NotificationType::AUTH_SUPPLIED, source);
  registrar_.Add(this, NotificationType::AUTH_CANCELLED, source);
}

template <NotificationType::Type T>
class WindowedNavigationObserver
    : public ui_test_utils::WindowedNotificationObserver {
 public:
  explicit WindowedNavigationObserver(NavigationController* controller)
      : ui_test_utils::WindowedNotificationObserver(
          T, Source<NavigationController>(controller)) {}
};

typedef WindowedNavigationObserver<NotificationType::LOAD_STOP>
    WindowedLoadStopObserver;

typedef WindowedNavigationObserver<NotificationType::AUTH_NEEDED>
    WindowedAuthNeededObserver;

typedef WindowedNavigationObserver<NotificationType::AUTH_CANCELLED>
    WindowedAuthCancelledObserver;

typedef WindowedNavigationObserver<NotificationType::AUTH_SUPPLIED>
    WindowedAuthSuppliedObserver;

const char* kMultiRealmTestPage = "files/login/multi_realm.html";
const int   kMultiRealmTestRealmCount = 2;
const int   kMultiRealmTestResourceCount = 4;

const char* kSingleRealmTestPage = "files/login/single_realm.html";
const int   kSingleRealmTestResourceCount = 6;

// Test handling of resources that require authentication even though
// the page they are included on doesn't.  In this case we should only
// present the minimal number of prompts necessary for successfully
// displaying the page.  First we check whether cancelling works as
// expected.
IN_PROC_BROWSER_TEST_F(LoginPromptBrowserTest, MultipleRealmCancellation) {
  ASSERT_TRUE(test_server()->Start());
  GURL test_page = test_server()->GetURL(kMultiRealmTestPage);

  TabContentsWrapper* contents =
      browser()->GetSelectedTabContentsWrapper();
  ASSERT_TRUE(contents);

  NavigationController* controller = &contents->controller();
  LoginPromptBrowserTestObserver observer;

  observer.Register(Source<NavigationController>(controller));

  WindowedLoadStopObserver load_stop_waiter(controller);

  {
    WindowedAuthNeededObserver auth_needed_waiter(controller);
    browser()->OpenURL(test_page, GURL(), CURRENT_TAB, PageTransition::TYPED);
    auth_needed_waiter.Wait();
  }

  int n_handlers = 0;

  while (n_handlers < kMultiRealmTestRealmCount) {
    WindowedAuthNeededObserver auth_needed_waiter(controller);

    while (!observer.handlers_.empty()) {
      WindowedAuthCancelledObserver auth_cancelled_waiter(controller);
      LoginHandler* handler = *observer.handlers_.begin();

      ASSERT_TRUE(handler);
      n_handlers++;
      handler->CancelAuth();
      auth_cancelled_waiter.Wait();
    }

    if (n_handlers < kMultiRealmTestRealmCount)
      auth_needed_waiter.Wait();
  }

  load_stop_waiter.Wait();

  EXPECT_EQ(kMultiRealmTestRealmCount, n_handlers);
  EXPECT_EQ(0, observer.auth_supplied_count_);
  EXPECT_LT(0, observer.auth_needed_count_);
  EXPECT_LT(0, observer.auth_cancelled_count_);
  EXPECT_TRUE(test_server()->Stop());
}

// Similar to the MultipleRealmCancellation test above, but tests
// whether supplying credentials work as exepcted.
IN_PROC_BROWSER_TEST_F(LoginPromptBrowserTest, MultipleRealmConfirmation) {
  ASSERT_TRUE(test_server()->Start());
  GURL test_page = test_server()->GetURL(kMultiRealmTestPage);

  TabContentsWrapper* contents =
      browser()->GetSelectedTabContentsWrapper();
  ASSERT_TRUE(contents);

  NavigationController* controller = &contents->controller();
  LoginPromptBrowserTestObserver observer;

  observer.Register(Source<NavigationController>(controller));

  WindowedLoadStopObserver load_stop_waiter(controller);
  int n_handlers = 0;

  {
    WindowedAuthNeededObserver auth_needed_waiter(controller);

    browser()->OpenURL(test_page, GURL(), CURRENT_TAB, PageTransition::TYPED);
    auth_needed_waiter.Wait();
  }

  while (n_handlers < kMultiRealmTestRealmCount) {
    WindowedAuthNeededObserver auth_needed_waiter(controller);

    while (!observer.handlers_.empty()) {
      WindowedAuthSuppliedObserver auth_supplied_waiter(controller);
      LoginHandler* handler = *observer.handlers_.begin();

      ASSERT_TRUE(handler);
      n_handlers++;
      SetAuthFor(handler);
      auth_supplied_waiter.Wait();
    }

    if (n_handlers < kMultiRealmTestRealmCount)
      auth_needed_waiter.Wait();
  }

  load_stop_waiter.Wait();

  EXPECT_EQ(kMultiRealmTestRealmCount, n_handlers);
  EXPECT_LT(0, observer.auth_needed_count_);
  EXPECT_LT(0, observer.auth_supplied_count_);
  EXPECT_EQ(0, observer.auth_cancelled_count_);
  EXPECT_TRUE(test_server()->Stop());
}

// Testing for recovery from an incorrect password for the case where
// there are multiple authenticated resources.
// Marked as flaky.  See crbug.com/68860
IN_PROC_BROWSER_TEST_F(LoginPromptBrowserTest, FLAKY_IncorrectConfirmation) {
  ASSERT_TRUE(test_server()->Start());
  GURL test_page = test_server()->GetURL(kSingleRealmTestPage);

  TabContentsWrapper* contents =
      browser()->GetSelectedTabContentsWrapper();
  ASSERT_TRUE(contents);

  NavigationController* controller = &contents->controller();
  LoginPromptBrowserTestObserver observer;

  observer.Register(Source<NavigationController>(controller));

  WindowedLoadStopObserver load_stop_waiter(controller);

  {
    WindowedAuthNeededObserver auth_needed_waiter(controller);
    browser()->OpenURL(test_page, GURL(), CURRENT_TAB, PageTransition::TYPED);
    auth_needed_waiter.Wait();
  }

  EXPECT_FALSE(observer.handlers_.empty());

  if (!observer.handlers_.empty()) {
    WindowedAuthNeededObserver auth_needed_waiter(controller);
    WindowedAuthSuppliedObserver auth_supplied_waiter(controller);
    LoginHandler* handler = *observer.handlers_.begin();

    ASSERT_TRUE(handler);
    handler->SetAuth(bad_username_, bad_password_);
    auth_supplied_waiter.Wait();

    // The request should be retried after the incorrect password is
    // supplied.  This should result in a new AUTH_NEEDED notification
    // for the same realm.
    auth_needed_waiter.Wait();
  }

  int n_handlers = 0;

  while (n_handlers < 1) {
    WindowedAuthNeededObserver auth_needed_waiter(controller);

    while (!observer.handlers_.empty()) {
      WindowedAuthSuppliedObserver auth_supplied_waiter(controller);
      LoginHandler* handler = *observer.handlers_.begin();

      ASSERT_TRUE(handler);
      n_handlers++;
      SetAuthFor(handler);
      auth_supplied_waiter.Wait();
    }

    if (n_handlers < 1)
      auth_needed_waiter.Wait();
  }

  load_stop_waiter.Wait();

  // The single realm test has only one realm, and thus only one login
  // prompt.
  EXPECT_EQ(1, n_handlers);
  EXPECT_LT(0, observer.auth_needed_count_);
  EXPECT_LT(0, observer.auth_supplied_count_);
  EXPECT_EQ(0, observer.auth_cancelled_count_);
  EXPECT_TRUE(test_server()->Stop());
}
} // namespace
<|endoftext|>


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

#include "chrome/browser/views/options/passwords_page_view.h"

#include "app/l10n_util.h"
#include "base/string_util.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"
#include "grit/generated_resources.h"
#include "views/background.h"
#include "views/controls/button/native_button.h"
#include "views/grid_layout.h"
#include "views/standard_layout.h"

using views::ColumnSet;
using views::GridLayout;
using webkit_glue::PasswordForm;

///////////////////////////////////////////////////////////////////////////////
// MultiLabelButtons
MultiLabelButtons::MultiLabelButtons(views::ButtonListener* listener,
                                     const std::wstring& label,
                                     const std::wstring& alt_label)
    : NativeButton(listener, label),
      label_(label),
      alt_label_(alt_label) {
}

gfx::Size MultiLabelButtons::GetPreferredSize() {
  if (pref_size_.IsEmpty()) {
    // Let's compute our preferred size.
    std::wstring current_label = label();
    SetLabel(label_);
    pref_size_ = NativeButton::GetPreferredSize();
    SetLabel(alt_label_);
    gfx::Size alt_pref_size = NativeButton::GetPreferredSize();
    // Revert to the original label.
    SetLabel(current_label);
    pref_size_.SetSize(std::max(pref_size_.width(), alt_pref_size.width()),
                       std::max(pref_size_.height(), alt_pref_size.height()));
  }
  return gfx::Size(pref_size_.width(), pref_size_.height());
}

///////////////////////////////////////////////////////////////////////////////
// PasswordsTableModel, public
PasswordsTableModel::PasswordsTableModel(Profile* profile)
    : observer_(NULL),
      row_count_observer_(NULL),
      pending_login_query_(NULL),
      saved_signons_cleanup_(&saved_signons_),
      profile_(profile) {
  DCHECK(profile && profile->GetWebDataService(Profile::EXPLICIT_ACCESS));
}

PasswordsTableModel::~PasswordsTableModel() {
  CancelLoginsQuery();
}

int PasswordsTableModel::RowCount() {
  return static_cast<int>(saved_signons_.size());
}

std::wstring PasswordsTableModel::GetText(int row,
                                          int col_id) {
  switch (col_id) {
    case IDS_PASSWORDS_PAGE_VIEW_SITE_COLUMN: {  // Site.
      const std::wstring& url = saved_signons_[row]->display_url.display_url();
      // Force URL to have LTR directionality.
      if (l10n_util::GetTextDirection() == l10n_util::RIGHT_TO_LEFT) {
        std::wstring localized_url = url;
        l10n_util::WrapStringWithLTRFormatting(&localized_url);
        return localized_url;
      }
      return url;
    }
    case IDS_PASSWORDS_PAGE_VIEW_USERNAME_COLUMN: {  // Username.
      std::wstring username = GetPasswordFormAt(row)->username_value;
      l10n_util::AdjustStringForLocaleDirection(username, &username);
      return username;
    }
    default:
      NOTREACHED() << "Invalid column.";
      return std::wstring();
  }
}

int PasswordsTableModel::CompareValues(int row1, int row2,
                                       int column_id) {
  if (column_id == IDS_PASSWORDS_PAGE_VIEW_SITE_COLUMN) {
    return saved_signons_[row1]->display_url.Compare(
        saved_signons_[row2]->display_url, GetCollator());
  }
  return TableModel::CompareValues(row1, row2, column_id);
}

void PasswordsTableModel::SetObserver(TableModelObserver* observer) {
  observer_ = observer;
}

void PasswordsTableModel::GetAllSavedLoginsForProfile() {
  DCHECK(!pending_login_query_);
  pending_login_query_ = web_data_service()->GetAllAutofillableLogins(this);
}

void PasswordsTableModel::OnWebDataServiceRequestDone(
    WebDataService::Handle h,
    const WDTypedResult* result) {
  DCHECK_EQ(pending_login_query_, h);
  pending_login_query_ = NULL;

  if (!result)
    return;

  DCHECK(result->GetType() == PASSWORD_RESULT);

  // Get the result from the database into a useable form.
  const WDResult<std::vector<PasswordForm*> >* r =
      static_cast<const WDResult<std::vector<PasswordForm*> >*>(result);
  std::vector<PasswordForm*> rows = r->GetValue();
  STLDeleteElements<PasswordRows>(&saved_signons_);
  saved_signons_.resize(rows.size(), NULL);
  std::wstring languages =
      profile_->GetPrefs()->GetString(prefs::kAcceptLanguages);
  for (size_t i = 0; i < rows.size(); ++i) {
    saved_signons_[i] = new PasswordRow(
        gfx::SortedDisplayURL(rows[i]->origin, languages), rows[i]);
  }
  if (observer_)
    observer_->OnModelChanged();
  if (row_count_observer_)
    row_count_observer_->OnRowCountChanged(RowCount());
}

PasswordForm* PasswordsTableModel::GetPasswordFormAt(int row) {
  DCHECK(row >= 0 && row < RowCount());
  return saved_signons_[row]->form.get();
}

void PasswordsTableModel::ForgetAndRemoveSignon(int row) {
  DCHECK(row >= 0 && row < RowCount());
  PasswordRows::iterator target_iter = saved_signons_.begin() + row;
  // Remove from DB, memory, and vector.
  PasswordRow* password_row = *target_iter;
  web_data_service()->RemoveLogin(*(password_row->form.get()));
  delete password_row;
  saved_signons_.erase(target_iter);
  if (observer_)
    observer_->OnItemsRemoved(row, 1);
  if (row_count_observer_)
    row_count_observer_->OnRowCountChanged(RowCount());
}

void PasswordsTableModel::ForgetAndRemoveAllSignons() {
  PasswordRows::iterator iter = saved_signons_.begin();
  while (iter != saved_signons_.end()) {
    // Remove from DB, memory, and vector.
    PasswordRow* row = *iter;
    web_data_service()->RemoveLogin(*(row->form.get()));
    delete row;
    iter = saved_signons_.erase(iter);
  }
  if (observer_)
    observer_->OnModelChanged();
  if (row_count_observer_)
    row_count_observer_->OnRowCountChanged(RowCount());
}

///////////////////////////////////////////////////////////////////////////////
// PasswordsTableModel, private
void PasswordsTableModel::CancelLoginsQuery() {
  if (pending_login_query_) {
    web_data_service()->CancelRequest(pending_login_query_);
    pending_login_query_ = NULL;
  }
}

///////////////////////////////////////////////////////////////////////////////
// PasswordsPageView, public
PasswordsPageView::PasswordsPageView(Profile* profile)
    : OptionsPageView(profile),
      ALLOW_THIS_IN_INITIALIZER_LIST(show_button_(
          this,
          l10n_util::GetString(IDS_PASSWORDS_PAGE_VIEW_SHOW_BUTTON),
          l10n_util::GetString(IDS_PASSWORDS_PAGE_VIEW_HIDE_BUTTON))),
      ALLOW_THIS_IN_INITIALIZER_LIST(remove_button_(
          this,
          l10n_util::GetString(IDS_PASSWORDS_PAGE_VIEW_REMOVE_BUTTON))),
      ALLOW_THIS_IN_INITIALIZER_LIST(remove_all_button_(
          this,
          l10n_util::GetString(IDS_PASSWORDS_PAGE_VIEW_REMOVE_ALL_BUTTON))),
      table_model_(profile),
      table_view_(NULL),
      current_selected_password_(NULL) {
}

void PasswordsPageView::OnSelectionChanged() {
  bool has_selection = table_view_->SelectedRowCount() > 0;
  remove_button_.SetEnabled(has_selection);

  views::TableSelectionIterator iter = table_view_->SelectionBegin();
  int row = *iter;
  PasswordForm* selected = table_model_.GetPasswordFormAt(row);
  DCHECK(++iter == table_view_->SelectionEnd());

  if (selected != current_selected_password_) {
    // Reset the password related views.
    show_button_.SetLabel(
        l10n_util::GetString(IDS_PASSWORDS_PAGE_VIEW_SHOW_BUTTON));
    show_button_.SetEnabled(has_selection);
    password_label_.SetText(std::wstring());

    current_selected_password_ = selected;
  }
}

void PasswordsPageView::ButtonPressed(views::Button* sender) {
  // Close will result in our destruction.
  if (sender == &remove_all_button_) {
    table_model_.ForgetAndRemoveAllSignons();
    return;
  }

  // The following require a selection (and only one, since table is single-
  // select only).
  views::TableSelectionIterator iter = table_view_->SelectionBegin();
  int row = *iter;
  PasswordForm* selected = table_model_.GetPasswordFormAt(row);
  DCHECK(++iter == table_view_->SelectionEnd());

  if (sender == &remove_button_) {
    table_model_.ForgetAndRemoveSignon(row);
  } else if (sender == &show_button_) {
    if (password_label_.GetText().length() == 0) {
      password_label_.SetText(selected->password_value);
      show_button_.SetLabel(
          l10n_util::GetString(IDS_PASSWORDS_PAGE_VIEW_HIDE_BUTTON));
    } else {
      password_label_.SetText(L"");
      show_button_.SetLabel(
          l10n_util::GetString(IDS_PASSWORDS_PAGE_VIEW_SHOW_BUTTON));
    }
  } else {
    NOTREACHED() << "Invalid button.";
  }
}

void PasswordsPageView::OnRowCountChanged(size_t rows) {
  remove_all_button_.SetEnabled(rows > 0);
}

///////////////////////////////////////////////////////////////////////////////
// PasswordsPageView, protected
void PasswordsPageView::InitControlLayout() {
  SetupButtonsAndLabels();
  SetupTable();

  // Do the layout thing.
  const int top_column_set_id = 0;
  GridLayout* layout = CreatePanelGridLayout(this);
  SetLayoutManager(layout);

  // Design the grid.
  ColumnSet* column_set = layout->AddColumnSet(top_column_set_id);
  column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1,
                        GridLayout::USE_PREF, 0, 0);
  column_set->AddPaddingColumn(0, kRelatedControlHorizontalSpacing);
  column_set->AddColumn(GridLayout::FILL, GridLayout::CENTER, 0,
                        GridLayout::USE_PREF, 0, 0);

  // Fill the grid.
  layout->StartRow(0, top_column_set_id);
  layout->AddView(table_view_, 1, 8, GridLayout::FILL,
                  GridLayout::FILL);
  layout->AddView(&remove_button_);
  layout->StartRowWithPadding(0, top_column_set_id, 0,
                              kRelatedControlVerticalSpacing);
  layout->SkipColumns(1);
  layout->AddView(&remove_all_button_);
  layout->StartRowWithPadding(0, top_column_set_id, 0,
                              kRelatedControlVerticalSpacing);
  layout->SkipColumns(1);
  layout->AddView(&show_button_);
  layout->StartRowWithPadding(0, top_column_set_id, 0,
                              kRelatedControlVerticalSpacing);
  layout->SkipColumns(1);
  layout->AddView(&password_label_);
  layout->AddPaddingRow(1, 0);

  // Ask the database for saved password data.
  table_model_.GetAllSavedLoginsForProfile();
}

///////////////////////////////////////////////////////////////////////////////
// PasswordsPageView, private
void PasswordsPageView::SetupButtonsAndLabels() {
  // Disable all buttons in the first place.
  show_button_.SetParentOwned(false);
  show_button_.SetEnabled(false);

  remove_button_.SetParentOwned(false);
  remove_button_.SetEnabled(false);

  remove_all_button_.SetParentOwned(false);
  remove_all_button_.SetEnabled(false);

  password_label_.SetParentOwned(false);
}

void PasswordsPageView::SetupTable() {
  // Tell the table model we are concern about how many rows it has.
  table_model_.set_row_count_observer(this);

  // Creates the different columns for the table.
  // The float resize values are the result of much tinkering.
  std::vector<TableColumn> columns;
  columns.push_back(TableColumn(IDS_PASSWORDS_PAGE_VIEW_SITE_COLUMN,
                                       TableColumn::LEFT, -1, 0.55f));
  columns.back().sortable = true;
  columns.push_back(TableColumn(
      IDS_PASSWORDS_PAGE_VIEW_USERNAME_COLUMN, TableColumn::LEFT,
      -1, 0.37f));
  columns.back().sortable = true;
  table_view_ = new views::TableView(&table_model_, columns, views::TEXT_ONLY,
                                     true, true, true);
  // Make the table initially sorted by host.
  views::TableView::SortDescriptors sort;
  sort.push_back(views::TableView::SortDescriptor(
      IDS_PASSWORDS_PAGE_VIEW_SITE_COLUMN, true));
  table_view_->SetSortDescriptors(sort);
  table_view_->SetObserver(this);
}
<commit_msg>We were hitting a DCHECK when removing a password in the password option panel. This is a regression introduced by a recent change that fixed another bug. The problem was that we were not dealing with the empty selection case in the password table.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/views/options/passwords_page_view.h"

#include "app/l10n_util.h"
#include "base/string_util.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"
#include "grit/generated_resources.h"
#include "views/background.h"
#include "views/controls/button/native_button.h"
#include "views/grid_layout.h"
#include "views/standard_layout.h"

using views::ColumnSet;
using views::GridLayout;
using webkit_glue::PasswordForm;

///////////////////////////////////////////////////////////////////////////////
// MultiLabelButtons
MultiLabelButtons::MultiLabelButtons(views::ButtonListener* listener,
                                     const std::wstring& label,
                                     const std::wstring& alt_label)
    : NativeButton(listener, label),
      label_(label),
      alt_label_(alt_label) {
}

gfx::Size MultiLabelButtons::GetPreferredSize() {
  if (pref_size_.IsEmpty()) {
    // Let's compute our preferred size.
    std::wstring current_label = label();
    SetLabel(label_);
    pref_size_ = NativeButton::GetPreferredSize();
    SetLabel(alt_label_);
    gfx::Size alt_pref_size = NativeButton::GetPreferredSize();
    // Revert to the original label.
    SetLabel(current_label);
    pref_size_.SetSize(std::max(pref_size_.width(), alt_pref_size.width()),
                       std::max(pref_size_.height(), alt_pref_size.height()));
  }
  return gfx::Size(pref_size_.width(), pref_size_.height());
}

///////////////////////////////////////////////////////////////////////////////
// PasswordsTableModel, public
PasswordsTableModel::PasswordsTableModel(Profile* profile)
    : observer_(NULL),
      row_count_observer_(NULL),
      pending_login_query_(NULL),
      saved_signons_cleanup_(&saved_signons_),
      profile_(profile) {
  DCHECK(profile && profile->GetWebDataService(Profile::EXPLICIT_ACCESS));
}

PasswordsTableModel::~PasswordsTableModel() {
  CancelLoginsQuery();
}

int PasswordsTableModel::RowCount() {
  return static_cast<int>(saved_signons_.size());
}

std::wstring PasswordsTableModel::GetText(int row,
                                          int col_id) {
  switch (col_id) {
    case IDS_PASSWORDS_PAGE_VIEW_SITE_COLUMN: {  // Site.
      const std::wstring& url = saved_signons_[row]->display_url.display_url();
      // Force URL to have LTR directionality.
      if (l10n_util::GetTextDirection() == l10n_util::RIGHT_TO_LEFT) {
        std::wstring localized_url = url;
        l10n_util::WrapStringWithLTRFormatting(&localized_url);
        return localized_url;
      }
      return url;
    }
    case IDS_PASSWORDS_PAGE_VIEW_USERNAME_COLUMN: {  // Username.
      std::wstring username = GetPasswordFormAt(row)->username_value;
      l10n_util::AdjustStringForLocaleDirection(username, &username);
      return username;
    }
    default:
      NOTREACHED() << "Invalid column.";
      return std::wstring();
  }
}

int PasswordsTableModel::CompareValues(int row1, int row2,
                                       int column_id) {
  if (column_id == IDS_PASSWORDS_PAGE_VIEW_SITE_COLUMN) {
    return saved_signons_[row1]->display_url.Compare(
        saved_signons_[row2]->display_url, GetCollator());
  }
  return TableModel::CompareValues(row1, row2, column_id);
}

void PasswordsTableModel::SetObserver(TableModelObserver* observer) {
  observer_ = observer;
}

void PasswordsTableModel::GetAllSavedLoginsForProfile() {
  DCHECK(!pending_login_query_);
  pending_login_query_ = web_data_service()->GetAllAutofillableLogins(this);
}

void PasswordsTableModel::OnWebDataServiceRequestDone(
    WebDataService::Handle h,
    const WDTypedResult* result) {
  DCHECK_EQ(pending_login_query_, h);
  pending_login_query_ = NULL;

  if (!result)
    return;

  DCHECK(result->GetType() == PASSWORD_RESULT);

  // Get the result from the database into a useable form.
  const WDResult<std::vector<PasswordForm*> >* r =
      static_cast<const WDResult<std::vector<PasswordForm*> >*>(result);
  std::vector<PasswordForm*> rows = r->GetValue();
  STLDeleteElements<PasswordRows>(&saved_signons_);
  saved_signons_.resize(rows.size(), NULL);
  std::wstring languages =
      profile_->GetPrefs()->GetString(prefs::kAcceptLanguages);
  for (size_t i = 0; i < rows.size(); ++i) {
    saved_signons_[i] = new PasswordRow(
        gfx::SortedDisplayURL(rows[i]->origin, languages), rows[i]);
  }
  if (observer_)
    observer_->OnModelChanged();
  if (row_count_observer_)
    row_count_observer_->OnRowCountChanged(RowCount());
}

PasswordForm* PasswordsTableModel::GetPasswordFormAt(int row) {
  DCHECK(row >= 0 && row < RowCount());
  return saved_signons_[row]->form.get();
}

void PasswordsTableModel::ForgetAndRemoveSignon(int row) {
  DCHECK(row >= 0 && row < RowCount());
  PasswordRows::iterator target_iter = saved_signons_.begin() + row;
  // Remove from DB, memory, and vector.
  PasswordRow* password_row = *target_iter;
  web_data_service()->RemoveLogin(*(password_row->form.get()));
  delete password_row;
  saved_signons_.erase(target_iter);
  if (observer_)
    observer_->OnItemsRemoved(row, 1);
  if (row_count_observer_)
    row_count_observer_->OnRowCountChanged(RowCount());
}

void PasswordsTableModel::ForgetAndRemoveAllSignons() {
  PasswordRows::iterator iter = saved_signons_.begin();
  while (iter != saved_signons_.end()) {
    // Remove from DB, memory, and vector.
    PasswordRow* row = *iter;
    web_data_service()->RemoveLogin(*(row->form.get()));
    delete row;
    iter = saved_signons_.erase(iter);
  }
  if (observer_)
    observer_->OnModelChanged();
  if (row_count_observer_)
    row_count_observer_->OnRowCountChanged(RowCount());
}

///////////////////////////////////////////////////////////////////////////////
// PasswordsTableModel, private
void PasswordsTableModel::CancelLoginsQuery() {
  if (pending_login_query_) {
    web_data_service()->CancelRequest(pending_login_query_);
    pending_login_query_ = NULL;
  }
}

///////////////////////////////////////////////////////////////////////////////
// PasswordsPageView, public
PasswordsPageView::PasswordsPageView(Profile* profile)
    : OptionsPageView(profile),
      ALLOW_THIS_IN_INITIALIZER_LIST(show_button_(
          this,
          l10n_util::GetString(IDS_PASSWORDS_PAGE_VIEW_SHOW_BUTTON),
          l10n_util::GetString(IDS_PASSWORDS_PAGE_VIEW_HIDE_BUTTON))),
      ALLOW_THIS_IN_INITIALIZER_LIST(remove_button_(
          this,
          l10n_util::GetString(IDS_PASSWORDS_PAGE_VIEW_REMOVE_BUTTON))),
      ALLOW_THIS_IN_INITIALIZER_LIST(remove_all_button_(
          this,
          l10n_util::GetString(IDS_PASSWORDS_PAGE_VIEW_REMOVE_ALL_BUTTON))),
      table_model_(profile),
      table_view_(NULL),
      current_selected_password_(NULL) {
}

void PasswordsPageView::OnSelectionChanged() {
  bool has_selection = table_view_->SelectedRowCount() > 0;
  remove_button_.SetEnabled(has_selection);

  PasswordForm* selected = NULL;
  if (has_selection) {
    views::TableSelectionIterator iter = table_view_->SelectionBegin();
    selected = table_model_.GetPasswordFormAt(*iter);
    DCHECK(++iter == table_view_->SelectionEnd());
  }

  if (selected != current_selected_password_) {
    // Reset the password related views.
    show_button_.SetLabel(
        l10n_util::GetString(IDS_PASSWORDS_PAGE_VIEW_SHOW_BUTTON));
    show_button_.SetEnabled(has_selection);
    password_label_.SetText(std::wstring());

    current_selected_password_ = selected;
  }
}

void PasswordsPageView::ButtonPressed(views::Button* sender) {
  // Close will result in our destruction.
  if (sender == &remove_all_button_) {
    table_model_.ForgetAndRemoveAllSignons();
    return;
  }

  // The following require a selection (and only one, since table is single-
  // select only).
  views::TableSelectionIterator iter = table_view_->SelectionBegin();
  int row = *iter;
  PasswordForm* selected = table_model_.GetPasswordFormAt(row);
  DCHECK(++iter == table_view_->SelectionEnd());

  if (sender == &remove_button_) {
    table_model_.ForgetAndRemoveSignon(row);
  } else if (sender == &show_button_) {
    if (password_label_.GetText().length() == 0) {
      password_label_.SetText(selected->password_value);
      show_button_.SetLabel(
          l10n_util::GetString(IDS_PASSWORDS_PAGE_VIEW_HIDE_BUTTON));
    } else {
      password_label_.SetText(L"");
      show_button_.SetLabel(
          l10n_util::GetString(IDS_PASSWORDS_PAGE_VIEW_SHOW_BUTTON));
    }
  } else {
    NOTREACHED() << "Invalid button.";
  }
}

void PasswordsPageView::OnRowCountChanged(size_t rows) {
  remove_all_button_.SetEnabled(rows > 0);
}

///////////////////////////////////////////////////////////////////////////////
// PasswordsPageView, protected
void PasswordsPageView::InitControlLayout() {
  SetupButtonsAndLabels();
  SetupTable();

  // Do the layout thing.
  const int top_column_set_id = 0;
  GridLayout* layout = CreatePanelGridLayout(this);
  SetLayoutManager(layout);

  // Design the grid.
  ColumnSet* column_set = layout->AddColumnSet(top_column_set_id);
  column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1,
                        GridLayout::USE_PREF, 0, 0);
  column_set->AddPaddingColumn(0, kRelatedControlHorizontalSpacing);
  column_set->AddColumn(GridLayout::FILL, GridLayout::CENTER, 0,
                        GridLayout::USE_PREF, 0, 0);

  // Fill the grid.
  layout->StartRow(0, top_column_set_id);
  layout->AddView(table_view_, 1, 8, GridLayout::FILL,
                  GridLayout::FILL);
  layout->AddView(&remove_button_);
  layout->StartRowWithPadding(0, top_column_set_id, 0,
                              kRelatedControlVerticalSpacing);
  layout->SkipColumns(1);
  layout->AddView(&remove_all_button_);
  layout->StartRowWithPadding(0, top_column_set_id, 0,
                              kRelatedControlVerticalSpacing);
  layout->SkipColumns(1);
  layout->AddView(&show_button_);
  layout->StartRowWithPadding(0, top_column_set_id, 0,
                              kRelatedControlVerticalSpacing);
  layout->SkipColumns(1);
  layout->AddView(&password_label_);
  layout->AddPaddingRow(1, 0);

  // Ask the database for saved password data.
  table_model_.GetAllSavedLoginsForProfile();
}

///////////////////////////////////////////////////////////////////////////////
// PasswordsPageView, private
void PasswordsPageView::SetupButtonsAndLabels() {
  // Disable all buttons in the first place.
  show_button_.SetParentOwned(false);
  show_button_.SetEnabled(false);

  remove_button_.SetParentOwned(false);
  remove_button_.SetEnabled(false);

  remove_all_button_.SetParentOwned(false);
  remove_all_button_.SetEnabled(false);

  password_label_.SetParentOwned(false);
}

void PasswordsPageView::SetupTable() {
  // Tell the table model we are concern about how many rows it has.
  table_model_.set_row_count_observer(this);

  // Creates the different columns for the table.
  // The float resize values are the result of much tinkering.
  std::vector<TableColumn> columns;
  columns.push_back(TableColumn(IDS_PASSWORDS_PAGE_VIEW_SITE_COLUMN,
                                       TableColumn::LEFT, -1, 0.55f));
  columns.back().sortable = true;
  columns.push_back(TableColumn(
      IDS_PASSWORDS_PAGE_VIEW_USERNAME_COLUMN, TableColumn::LEFT,
      -1, 0.37f));
  columns.back().sortable = true;
  table_view_ = new views::TableView(&table_model_, columns, views::TEXT_ONLY,
                                     true, true, true);
  // Make the table initially sorted by host.
  views::TableView::SortDescriptors sort;
  sort.push_back(views::TableView::SortDescriptor(
      IDS_PASSWORDS_PAGE_VIEW_SITE_COLUMN, true));
  table_view_->SetSortDescriptors(sort);
  table_view_->SetObserver(this);
}
<|endoftext|>


<commit_before>

int main(int argc, const char **argv)
{
  return 0;
}
<commit_msg>connected device proxy and indication<commit_after>/* Copyright (c) 2014 Quanta Research Cambridge, Inc
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

#include "Ov7670ControllerRequest.h"
#include "Ov7670ControllerIndication.h"

class Ov7670ControllerIndication : public Ov7670ControllerIndicationWrapper {
public:
  Ov7670ControllerIndication(unsigned int id) : Ov7670ControllerIndicationWrapper(id){}
  virtual void probeResponse(uint8_t data) {
    fprintf(stderr, "i2c response %02x\n", data);
  }
  virtual void vsync() {
    fprintf(stderr, "vsync\n");
  }
};

int main(int argc, const char **argv)
{
  Ov7670ControllerRequestProxy device(IfcNames_Ov7670ControllerRequestS2H);
  Ov7670ControllerIndication deviceResponse(IfcNames_Ov7670ControllerIndicationH2S);
  return 0;
}
<|endoftext|>


<commit_before>#include <sstream>
#include <cereal/archives/binary.hpp>
#include <nfl.hpp>
#include "tools.h"

template <size_t degree, size_t modulus, class T>
bool run() {
  using poly_t = nfl::poly_from_modulus<T, degree, modulus>;

  // Stream
  std::stringstream ss;

  // Archives
  cereal::BinaryOutputArchive oarchive(ss); // output archive
  cereal::BinaryInputArchive iarchive(ss); // input archive

  // define a random polynomial
  poly_t& p0 = *alloc_aligned<poly_t, 32>(1, nfl::uniform());

  // serialize the polynomial
  oarchive(p0);

  // copy p0 into p1
  poly_t& p1 = *alloc_aligned<poly_t, 32>(1, p0);

  // free p0
  free_aligned(1, &p0);

  // define a new polynomial p2
  poly_t& p2 = *alloc_aligned<poly_t, 32>(1);

  // deserialize the stream into p2
  iarchive(p2);

  // Verify that p1 == p2
  bool ret_value = (p1 == p2);

  // Cleaning
  free_aligned(1, &p1);
  free_aligned(1, &p2);

  return ret_value;
}

template <size_t degree, size_t modulus, class T>
bool run_p() {
  using poly_p = nfl::poly_p_from_modulus<T, degree, modulus>;

  // Stream
  std::stringstream ss;

  // Archives
  cereal::BinaryOutputArchive oarchive(ss); // output archive
  cereal::BinaryInputArchive iarchive(ss); // input archive

  // define a random polynomial
  poly_p* p0 = new poly_p(nfl::uniform());

  // serialize the polynomial
  oarchive(*p0);

  // copy p0 into p1
  poly_p p1 = *p0;

  // delete p0
  delete p0;

  // define a new polynomial p2
  poly_p p2;

  // deserialize the stream into p2
  iarchive(p2);

  // Verify that p1 == p2
  return (p1 == p2);
}

int main(int argc, char const* argv[]) {
  return not(run<CONFIG>() and run_p<CONFIG>());
}
<commit_msg>Serializer perfs<commit_after>#include <cereal/archives/binary.hpp>
#include <chrono>
#include <iostream>
#include <iterator>
#include <nfl.hpp>
#include <sstream>
#include "tools.h"

#define REPETITIONS 500

template <class T>
double get_time_us(T const& start, T const& end, uint32_t N) {
  auto diff = end - start;
  return (long double)(std::chrono::duration_cast<std::chrono::microseconds>(
                           diff)
                           .count()) /
         N;
}

/// Temporary class to compare manual serialization and serialization using
/// cereal
template <class T, size_t degree, size_t modulus>
class poly_temp {
  using poly_p = nfl::poly_p_from_modulus<T, degree, modulus>;
  static constexpr size_t N = poly_p::degree * poly_p::nmoduli;

 public:
  T _data[N] __attribute__((aligned(32))) = {0};
  poly_temp() {}
  void set(poly_p const& p) {
    for (size_t cm = 0; cm < poly_p::nmoduli; cm++) {
      for (size_t i = 0; i < poly_p::degree; i++) {
        _data[cm * poly_p::degree + i] = p(cm, i);
      }
    }
  }
  T& operator()(size_t cm, size_t i) { return _data[cm * degree + i]; }

  /// cereal serializer
  template <class Archive>
  void serialize(Archive& archive) {
    archive(_data);  // serialize coefficients by passing them to the archive
  }

  /// manual serializers
  inline void oserialize_manually(std::ostream& outputstream) {
    outputstream.write(reinterpret_cast<char*>(_data), N * sizeof(T));
  }
  inline void iserialize_manually(std::istream& inputstream) {
    inputstream.read(reinterpret_cast<char*>(_data), N * sizeof(T));
  }
} __attribute__((aligned(32)));

template <size_t degree, size_t modulus, class T>
bool run() {
  using poly_t = nfl::poly_from_modulus<T, degree, modulus>;

  // Stream
  std::stringstream ss(std::stringstream::in | std::stringstream::out |
                       std::stringstream::binary);

  // Archives
  cereal::BinaryOutputArchive oarchive(ss);  // output archive
  cereal::BinaryInputArchive iarchive(ss);   // input archive

  // define a random polynomial
  poly_t& p0 = *alloc_aligned<poly_t, 32>(1, nfl::uniform());

  // serialize the polynomial
  oarchive(p0);

  // copy p0 into p1
  poly_t& p1 = *alloc_aligned<poly_t, 32>(1, p0);

  // free p0
  free_aligned(1, &p0);

  // define a new polynomial p2
  poly_t& p2 = *alloc_aligned<poly_t, 32>(1);

  // deserialize the stream into p2
  iarchive(p2);

  // Verify that p1 == p2
  bool ret_value = (p1 == p2);

  // Cleaning
  free_aligned(1, &p1);
  free_aligned(1, &p2);

  return ret_value;
}

template <size_t degree, size_t modulus, class T>
bool run_p() {
  using poly_p = nfl::poly_p_from_modulus<T, degree, modulus>;

  // Stream
  std::stringstream ss(std::stringstream::in | std::stringstream::out |
                       std::stringstream::binary);

  // Archives
  cereal::BinaryOutputArchive oarchive(ss);  // output archive
  cereal::BinaryInputArchive iarchive(ss);   // input archive

  // define a random polynomial
  poly_p* p0 = new poly_p(nfl::uniform());

  // serialize the polynomial
  oarchive(*p0);

  // copy p0 into p1
  poly_p p1 = *p0;

  // delete p0
  delete p0;

  // define a new polynomial p2
  poly_p p2;

  // deserialize the stream into p2
  iarchive(p2);

  // Verify that p1 == p2
  return (p1 == p2);
}

template <size_t degree, size_t modulus, class T>
bool run_perf() {
  using poly_p = nfl::poly_p_from_modulus<T, degree, modulus>;
  using poly_tmp = poly_temp<T, degree, modulus>;

  auto start = std::chrono::steady_clock::now();
  auto end = std::chrono::steady_clock::now();

  // Stream
  std::stringstream ss(std::stringstream::in | std::stringstream::out |
                       std::stringstream::binary);

  // Archives
  cereal::BinaryOutputArchive oarchive(ss);  // output archive
  cereal::BinaryInputArchive iarchive(ss);   // input archive

  // array of random polynomials
  std::array<poly_p, REPETITIONS> poly_p_array;
  std::fill(poly_p_array.begin(), poly_p_array.end(), nfl::uniform());

  // array of poly_tmp
  poly_tmp* poly_tmp_array = alloc_aligned<poly_tmp, 32>(REPETITIONS);
  for (size_t i = 0; i < REPETITIONS; i++) {
    poly_tmp_array[i].set(poly_p_array[i]);
  }

  // Benchmark cereal serialization
  start = std::chrono::steady_clock::now();
  for (size_t i = 0; i < REPETITIONS; i++) {
    oarchive(poly_tmp_array[i]);
  }
  end = std::chrono::steady_clock::now();
  std::cout << "Cereal output serialization: "
            << get_time_us(start, end, REPETITIONS) << " us" << std::endl;

  start = std::chrono::steady_clock::now();
  for (size_t i = 0; i < REPETITIONS; i++) {
    iarchive(poly_tmp_array[i]);
  }
  end = std::chrono::steady_clock::now();
  std::cout << "Cereal input serialization: "
            << get_time_us(start, end, REPETITIONS) << " us" << std::endl;

  // reset stringstream
  ss.clear();
  ss.str("");

  // Benchmark cereal serialization
  start = std::chrono::steady_clock::now();
  for (size_t i = 0; i < REPETITIONS; i++) {
    poly_tmp_array[i].oserialize_manually(ss);
  }
  end = std::chrono::steady_clock::now();
  std::cout << "Manual output serialization: "
            << get_time_us(start, end, REPETITIONS) << " us" << std::endl;

  start = std::chrono::steady_clock::now();
  for (size_t i = 0; i < REPETITIONS; i++) {
    poly_tmp_array[i].iserialize_manually(ss);
  }
  end = std::chrono::steady_clock::now();
  std::cout << "Manual input serialization: "
            << get_time_us(start, end, REPETITIONS) << " us" << std::endl;

  // Verify serialization
  bool ret_value = true;
  for (size_t i = 0; i < REPETITIONS; i++) {
    // reset stringstream
    ss.clear();
    ss.str("");

    // poly_p serialized to ss2, and read as a poly_tmp
    oarchive(poly_p_array[i]);
    poly_tmp* p_tmp = alloc_aligned<poly_tmp, 32>(1);
    p_tmp->iserialize_manually(ss);
    for (size_t cm = 0; cm < poly_p::nmoduli; cm++) {
      for (size_t j = 0; j < poly_p::degree; j++) {
        ret_value &= ((*p_tmp)(cm, j) == poly_p_array[i](cm, j));
      }
    }

    // reset stringstream
    ss.clear();
    ss.str("");

    // poly_tmp serialized to ss3, and read as a poly_p
    p_tmp->oserialize_manually(ss);
    poly_p p;
    iarchive(p);
    for (size_t cm = 0; cm < poly_p::nmoduli; cm++) {
      for (size_t j = 0; j < poly_p::degree; j++) {
        ret_value &= ((*p_tmp)(cm, j) == p(cm, j));
      }
    }

    free_aligned(1, p_tmp);
  }

  free_aligned(REPETITIONS, poly_tmp_array);

  return ret_value;
}

int main(int argc, char const* argv[]) {
  return not(run<CONFIG>() and run_p<CONFIG>() and run_perf<CONFIG>());
}
<|endoftext|>


<commit_before>#include <x0/http/HttpRangeDef.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <iostream>
#include <cstdlib>
#include <cctype>
#include <cassert>
#include <strings.h>

class range_def_test :
	public CPPUNIT_NS::TestFixture
{
public:
	CPPUNIT_TEST_SUITE(range_def_test);
		CPPUNIT_TEST(range1);
		CPPUNIT_TEST(range2);
		CPPUNIT_TEST(range3);
		CPPUNIT_TEST(range4);
		CPPUNIT_TEST(range5);
		CPPUNIT_TEST(range6);
	CPPUNIT_TEST_SUITE_END();

private:
	void range1()
	{
		x0::HttpRangeDef r;
		x0::ConstBuffer spec("bytes=0-499");

		r.parse(spec);
		CPPUNIT_ASSERT(r.unitName() == "bytes");
		CPPUNIT_ASSERT(r.size() == 1);
		CPPUNIT_ASSERT(r[0].first == 0);
		CPPUNIT_ASSERT(r[0].second == 499);
	}

	void range2()
	{
		x0::HttpRangeDef r;
		x0::ConstBuffer spec("bytes=500-999");

		r.parse(spec);
		CPPUNIT_ASSERT(r.unitName() == "bytes");
		CPPUNIT_ASSERT(r.size() == 1);
		CPPUNIT_ASSERT(r[0].first == 500);
		CPPUNIT_ASSERT(r[0].second == 999);
	}

	void range3()
	{
		x0::HttpRangeDef r;

		x0::ConstBuffer spec("bytes=-500");
		r.parse(spec);
		CPPUNIT_ASSERT(r.unitName() == "bytes");
		CPPUNIT_ASSERT(r.size() == 1);
		CPPUNIT_ASSERT(r[0].first == x0::HttpRangeDef::npos);
		CPPUNIT_ASSERT(r[0].second == 500);
	}

	void range4()
	{
		x0::HttpRangeDef r;

		x0::ConstBuffer spec("bytes=9500-");
		r.parse(spec);
		CPPUNIT_ASSERT(r.unitName() == "bytes");
		CPPUNIT_ASSERT(r.size() == 1);
		CPPUNIT_ASSERT(r[0].first == 9500);
		CPPUNIT_ASSERT(r[0].second == x0::HttpRangeDef::npos);
	}

	void range5()
	{
		x0::HttpRangeDef r;

		x0::ConstBuffer spec("bytes=0-0,-1");
		r.parse(spec);
		CPPUNIT_ASSERT(r.unitName() == "bytes");
		CPPUNIT_ASSERT(r.size() == 2);

		CPPUNIT_ASSERT(r[0].first == 0);
		CPPUNIT_ASSERT(r[0].second == 0);

		CPPUNIT_ASSERT(r[1].first == x0::HttpRangeDef::npos);
		CPPUNIT_ASSERT(r[1].second == 1);
	}

	void range6()
	{
		x0::HttpRangeDef r;

		x0::ConstBuffer spec("bytes=500-700,601-999");
		r.parse(spec);
		CPPUNIT_ASSERT(r.unitName() == "bytes");
		CPPUNIT_ASSERT(r.size() == 2);

		CPPUNIT_ASSERT(r[0].first == 500);
		CPPUNIT_ASSERT(r[0].second == 700);

		CPPUNIT_ASSERT(r[1].first == 601);
		CPPUNIT_ASSERT(r[1].second == 999);
	}
};

CPPUNIT_TEST_SUITE_REGISTRATION(range_def_test);
<commit_msg>[tests] range_def_test: added missing include (due to recent changes)<commit_after>#include <x0/http/HttpRangeDef.h>
#include <x0/ConstBuffer.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <iostream>
#include <cstdlib>
#include <cctype>
#include <cassert>
#include <strings.h>

class range_def_test :
	public CPPUNIT_NS::TestFixture
{
public:
	CPPUNIT_TEST_SUITE(range_def_test);
		CPPUNIT_TEST(range1);
		CPPUNIT_TEST(range2);
		CPPUNIT_TEST(range3);
		CPPUNIT_TEST(range4);
		CPPUNIT_TEST(range5);
		CPPUNIT_TEST(range6);
	CPPUNIT_TEST_SUITE_END();

private:
	void range1()
	{
		x0::HttpRangeDef r;
		x0::ConstBuffer spec("bytes=0-499");

		r.parse(spec);
		CPPUNIT_ASSERT(r.unitName() == "bytes");
		CPPUNIT_ASSERT(r.size() == 1);
		CPPUNIT_ASSERT(r[0].first == 0);
		CPPUNIT_ASSERT(r[0].second == 499);
	}

	void range2()
	{
		x0::HttpRangeDef r;
		x0::ConstBuffer spec("bytes=500-999");

		r.parse(spec);
		CPPUNIT_ASSERT(r.unitName() == "bytes");
		CPPUNIT_ASSERT(r.size() == 1);
		CPPUNIT_ASSERT(r[0].first == 500);
		CPPUNIT_ASSERT(r[0].second == 999);
	}

	void range3()
	{
		x0::HttpRangeDef r;

		x0::ConstBuffer spec("bytes=-500");
		r.parse(spec);
		CPPUNIT_ASSERT(r.unitName() == "bytes");
		CPPUNIT_ASSERT(r.size() == 1);
		CPPUNIT_ASSERT(r[0].first == x0::HttpRangeDef::npos);
		CPPUNIT_ASSERT(r[0].second == 500);
	}

	void range4()
	{
		x0::HttpRangeDef r;

		x0::ConstBuffer spec("bytes=9500-");
		r.parse(spec);
		CPPUNIT_ASSERT(r.unitName() == "bytes");
		CPPUNIT_ASSERT(r.size() == 1);
		CPPUNIT_ASSERT(r[0].first == 9500);
		CPPUNIT_ASSERT(r[0].second == x0::HttpRangeDef::npos);
	}

	void range5()
	{
		x0::HttpRangeDef r;

		x0::ConstBuffer spec("bytes=0-0,-1");
		r.parse(spec);
		CPPUNIT_ASSERT(r.unitName() == "bytes");
		CPPUNIT_ASSERT(r.size() == 2);

		CPPUNIT_ASSERT(r[0].first == 0);
		CPPUNIT_ASSERT(r[0].second == 0);

		CPPUNIT_ASSERT(r[1].first == x0::HttpRangeDef::npos);
		CPPUNIT_ASSERT(r[1].second == 1);
	}

	void range6()
	{
		x0::HttpRangeDef r;

		x0::ConstBuffer spec("bytes=500-700,601-999");
		r.parse(spec);
		CPPUNIT_ASSERT(r.unitName() == "bytes");
		CPPUNIT_ASSERT(r.size() == 2);

		CPPUNIT_ASSERT(r[0].first == 500);
		CPPUNIT_ASSERT(r[0].second == 700);

		CPPUNIT_ASSERT(r[1].first == 601);
		CPPUNIT_ASSERT(r[1].second == 999);
	}
};

CPPUNIT_TEST_SUITE_REGISTRATION(range_def_test);
<|endoftext|>