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

#include <oleacc.h>

#include "app/l10n_util.h"
#include "base/scoped_comptr_win.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/view_ids.h"
#include "chrome/browser/views/bookmark_bar_view.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/views/toolbar_view.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "views/accessibility/view_accessibility_wrapper.h"
#include "views/widget/root_view.h"
#include "views/widget/widget_win.h"
#include "views/window/window.h"

namespace {

VARIANT id_self = {VT_I4, CHILDID_SELF};

// Dummy class to force creation of ATL module, needed by COM to instantiate
// ViewAccessibility.
class TestAtlModule : public CAtlDllModuleT< TestAtlModule > {};
TestAtlModule test_atl_module_;

class BrowserViewsAccessibilityTest : public InProcessBrowserTest {
 public:
  BrowserViewsAccessibilityTest() {
    ::CoInitialize(NULL);
  }

  ~BrowserViewsAccessibilityTest() {
    ::CoUninitialize();
  }

  // Retrieves an instance of BrowserWindowTesting
  BrowserWindowTesting* GetBrowserWindowTesting() {
    BrowserWindow* browser_window = browser()->window();

    if (!browser_window)
      return NULL;

    return browser_window->GetBrowserWindowTesting();
  }

  // Retrieve an instance of BrowserView
  BrowserView* GetBrowserView() {
    return BrowserView::GetBrowserViewForNativeWindow(
               browser()->window()->GetNativeHandle());
  }

  // Retrieves and initializes an instance of LocationBarView.
  LocationBarView* GetLocationBarView() {
    BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();

    if (!browser_window_testing)
      return NULL;

    return GetBrowserWindowTesting()->GetLocationBarView();
  }

  // Retrieves and initializes an instance of ToolbarView.
  ToolbarView* GetToolbarView() {
    BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();

    if (!browser_window_testing)
      return NULL;

    return browser_window_testing->GetToolbarView();
  }

  // Retrieves and initializes an instance of BookmarkBarView.
  BookmarkBarView* GetBookmarkBarView() {
    BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();

    if (!browser_window_testing)
      return NULL;

    return browser_window_testing->GetBookmarkBarView();
  }

  // Retrieves and verifies the accessibility object for the given View.
  void TestViewAccessibilityObject(views::View* view, std::wstring name,
                                   int32 role) {
    ASSERT_TRUE(NULL != view);

    ScopedComPtr<IAccessible> acc_obj;
    HRESULT hr = view->GetViewAccessibilityWrapper()->GetInstance(
        IID_IAccessible, reinterpret_cast<void**>(&acc_obj));
    ASSERT_EQ(S_OK, hr);
    ASSERT_TRUE(NULL != acc_obj);

    TestAccessibilityInfo(acc_obj, name, role);
  }

  // Verifies MSAA Name and Role properties of the given IAccessible.
  void TestAccessibilityInfo(IAccessible* acc_obj, std::wstring name,
                             int32 role) {
    // Verify MSAA Name property.
    BSTR acc_name;

    HRESULT hr = acc_obj->get_accName(id_self, &acc_name);
    ASSERT_EQ(S_OK, hr);
    EXPECT_STREQ(acc_name, name.c_str());

    // Verify MSAA Role property.
    VARIANT acc_role;
    ::VariantInit(&acc_role);

    hr = acc_obj->get_accRole(id_self, &acc_role);
    ASSERT_EQ(S_OK, hr);
    EXPECT_EQ(VT_I4, acc_role.vt);
    EXPECT_EQ(role, acc_role.lVal);

    ::VariantClear(&acc_role);
    ::SysFreeString(acc_name);
  }
};

// Retrieve accessibility object for main window and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestChromeWindowAccObj) {
  BrowserWindow* browser_window = browser()->window();
  ASSERT_TRUE(NULL != browser_window);
  HWND hwnd = browser_window->GetNativeHandle();
  ASSERT_TRUE(NULL != hwnd);

  // Get accessibility object.
  ScopedComPtr<IAccessible> acc_obj;
  HRESULT hr = ::AccessibleObjectFromWindow(hwnd, OBJID_WINDOW, IID_IAccessible,
                                            reinterpret_cast<void**>(&acc_obj));
  ASSERT_EQ(S_OK, hr);
  ASSERT_TRUE(NULL != acc_obj);

  ui_test_utils::NavigateToURL(browser(), GURL(chrome::kAboutBlankURL));
  std::wstring title =
      l10n_util::GetStringF(IDS_BROWSER_WINDOW_TITLE_FORMAT,
                            ASCIIToWide(chrome::kAboutBlankURL));
  TestAccessibilityInfo(acc_obj, title, ROLE_SYSTEM_WINDOW);
}

// Retrieve accessibility object for non client view and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestNonClientViewAccObj) {
  views::View* non_client_view =
  GetBrowserView()->GetWindow()->GetNonClientView();

  TestViewAccessibilityObject(non_client_view,
      l10n_util::GetString(IDS_PRODUCT_NAME),
      ROLE_SYSTEM_WINDOW);
}

// Retrieve accessibility object for browser root view and verify
// accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestBrowserRootViewAccObj) {
  views::View* browser_root_view =
      GetBrowserView()->frame()->GetFrameView()->GetRootView();

  TestViewAccessibilityObject(browser_root_view,
                              l10n_util::GetString(IDS_PRODUCT_NAME),
                              ROLE_SYSTEM_APPLICATION);
}

// Retrieve accessibility object for browser view and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBrowserViewAccObj) {
  // Verify root view MSAA name and role.
  TestViewAccessibilityObject(GetBrowserView(),
                              l10n_util::GetString(IDS_PRODUCT_NAME),
                              ROLE_SYSTEM_CLIENT);
}

// Retrieve accessibility object for toolbar view and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestToolbarViewAccObj) {
  // Verify toolbar MSAA name and role.
  TestViewAccessibilityObject(GetToolbarView(),
                              l10n_util::GetString(IDS_ACCNAME_TOOLBAR),
                              ROLE_SYSTEM_TOOLBAR);
}

// Retrieve accessibility object for Back button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBackButtonAccObj) {
  // Verify Back button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_BACK_BUTTON),
      l10n_util::GetString(IDS_ACCNAME_BACK), ROLE_SYSTEM_BUTTONDROPDOWN);
}

// Retrieve accessibility object for Forward button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestForwardButtonAccObj) {
  // Verify Forward button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_FORWARD_BUTTON),
      l10n_util::GetString(IDS_ACCNAME_FORWARD), ROLE_SYSTEM_BUTTONDROPDOWN);
}

// Retrieve accessibility object for Reload button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestReloadButtonAccObj) {
  // Verify Reload button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_RELOAD_BUTTON),
      l10n_util::GetString(IDS_ACCNAME_RELOAD), ROLE_SYSTEM_PUSHBUTTON);
}

// Retrieve accessibility object for Home button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestHomeButtonAccObj) {
  // Verify Home button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_HOME_BUTTON),
      l10n_util::GetString(IDS_ACCNAME_HOME), ROLE_SYSTEM_PUSHBUTTON);
}

// Retrieve accessibility object for Star button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestStarButtonAccObj) {
  // Verify Star button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_STAR_BUTTON),
      l10n_util::GetString(IDS_ACCNAME_STAR), ROLE_SYSTEM_PUSHBUTTON);
}

// Retrieve accessibility object for location bar view and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestLocationBarViewAccObj) {
  // Verify location bar MSAA name and role.
  TestViewAccessibilityObject(GetLocationBarView(),
                              l10n_util::GetString(IDS_ACCNAME_LOCATION),
                              ROLE_SYSTEM_GROUPING);
}

// Retrieve accessibility object for Go button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestGoButtonAccObj) {
  // Verify Go button MSAA name and role.
  TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_GO_BUTTON),
                              l10n_util::GetString(IDS_ACCNAME_GO),
                              ROLE_SYSTEM_PUSHBUTTON);
}

// Retrieve accessibility object for Page menu button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestPageMenuAccObj) {
  // Verify Page menu button MSAA name and role.
  TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_PAGE_MENU),
                              l10n_util::GetString(IDS_ACCNAME_PAGE),
                              ROLE_SYSTEM_BUTTONMENU);
}

// Retrieve accessibility object for App menu button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestAppMenuAccObj) {
  // Verify App menu button MSAA name and role.
  TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_APP_MENU),
                              l10n_util::GetString(IDS_ACCNAME_APP),
                              ROLE_SYSTEM_BUTTONMENU);
}

IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestBookmarkBarViewAccObj) {
  TestViewAccessibilityObject(GetBookmarkBarView(),
                              l10n_util::GetString(IDS_ACCNAME_BOOKMARKS),
                              ROLE_SYSTEM_TOOLBAR);
}

IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestAboutChromeViewAccObj) {
  //  Firstly, test that the WindowDelegate got updated.
  views::Window* aboutChromeWindow = GetBrowserView()->ShowAboutChromeDialog();
  EXPECT_STREQ(aboutChromeWindow->GetDelegate()->GetWindowTitle().c_str(),
               l10n_util::GetString(IDS_ABOUT_CHROME_TITLE).c_str());
  EXPECT_EQ(aboutChromeWindow->GetDelegate()->accessible_role(),
            AccessibilityTypes::ROLE_DIALOG);

  // Also test the accessibility object directly.
  ScopedComPtr<IAccessible> acc_obj;
  HRESULT hr =
    ::AccessibleObjectFromWindow(aboutChromeWindow->GetNativeWindow(),
                                 OBJID_CLIENT,
                                 IID_IAccessible,
                                 reinterpret_cast<void**>(&acc_obj));
  ASSERT_EQ(S_OK, hr);
  ASSERT_TRUE(NULL != acc_obj);

  TestAccessibilityInfo(acc_obj, l10n_util::GetString(IDS_ABOUT_CHROME_TITLE),
                        ROLE_SYSTEM_DIALOG);
}
}  // Namespace.

<commit_msg>Revert 47582 - Fix flakyness of browser_tests:BrowserViewsAccessibilityTest.TestChromeWindowAccObj<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <oleacc.h>

#include "app/l10n_util.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/view_ids.h"
#include "chrome/browser/views/bookmark_bar_view.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/views/toolbar_view.h"
#include "chrome/test/in_process_browser_test.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "views/accessibility/view_accessibility_wrapper.h"
#include "views/widget/root_view.h"
#include "views/widget/widget_win.h"
#include "views/window/window.h"

namespace {

VARIANT id_self = {VT_I4, CHILDID_SELF};

// Dummy class to force creation of ATL module, needed by COM to instantiate
// ViewAccessibility.
class TestAtlModule : public CAtlDllModuleT< TestAtlModule > {};
TestAtlModule test_atl_module_;

class BrowserViewsAccessibilityTest : public InProcessBrowserTest {
 public:
  BrowserViewsAccessibilityTest() {
    ::CoInitialize(NULL);
  }

  ~BrowserViewsAccessibilityTest() {
    ::CoUninitialize();
  }

  // Retrieves an instance of BrowserWindowTesting
  BrowserWindowTesting* GetBrowserWindowTesting() {
    BrowserWindow* browser_window = browser()->window();

    if (!browser_window)
      return NULL;

    return browser_window->GetBrowserWindowTesting();
  }

  // Retrieve an instance of BrowserView
  BrowserView* GetBrowserView() {
    return BrowserView::GetBrowserViewForNativeWindow(
               browser()->window()->GetNativeHandle());
  }

  // Retrieves and initializes an instance of LocationBarView.
  LocationBarView* GetLocationBarView() {
    BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();

    if (!browser_window_testing)
      return NULL;

    return GetBrowserWindowTesting()->GetLocationBarView();
  }

  // Retrieves and initializes an instance of ToolbarView.
  ToolbarView* GetToolbarView() {
    BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();

    if (!browser_window_testing)
      return NULL;

    return browser_window_testing->GetToolbarView();
  }

  // Retrieves and initializes an instance of BookmarkBarView.
  BookmarkBarView* GetBookmarkBarView() {
    BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();

    if (!browser_window_testing)
      return NULL;

    return browser_window_testing->GetBookmarkBarView();
  }

  // Retrieves and verifies the accessibility object for the given View.
  void TestViewAccessibilityObject(views::View* view, std::wstring name,
                                   int32 role) {
    ASSERT_TRUE(NULL != view);

    IAccessible* acc_obj = NULL;
    HRESULT hr = view->GetViewAccessibilityWrapper()->GetInstance(
        IID_IAccessible, reinterpret_cast<void**>(&acc_obj));
    ASSERT_EQ(S_OK, hr);
    ASSERT_TRUE(NULL != acc_obj);

    TestAccessibilityInfo(acc_obj, name, role);
  }

  // Verifies MSAA Name and Role properties of the given IAccessible.
  void TestAccessibilityInfo(IAccessible* acc_obj, std::wstring name,
                             int32 role) {
    // Verify MSAA Name property.
    BSTR acc_name;

    HRESULT hr = acc_obj->get_accName(id_self, &acc_name);
    ASSERT_EQ(S_OK, hr);
    EXPECT_STREQ(acc_name, name.c_str());

    // Verify MSAA Role property.
    VARIANT acc_role;
    ::VariantInit(&acc_role);

    hr = acc_obj->get_accRole(id_self, &acc_role);
    ASSERT_EQ(S_OK, hr);
    EXPECT_EQ(VT_I4, acc_role.vt);
    EXPECT_EQ(role, acc_role.lVal);

    ::VariantClear(&acc_role);
    ::SysFreeString(acc_name);
  }
};

// Retrieve accessibility object for main window and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       FLAKY_TestChromeWindowAccObj) {
  BrowserWindow* browser_window = browser()->window();
  ASSERT_TRUE(NULL != browser_window);

  HWND hwnd = browser_window->GetNativeHandle();
  ASSERT_TRUE(NULL != hwnd);

  // Get accessibility object.
  IAccessible* acc_obj = NULL;
  HRESULT hr = ::AccessibleObjectFromWindow(hwnd, OBJID_WINDOW, IID_IAccessible,
                                            reinterpret_cast<void**>(&acc_obj));
  ASSERT_EQ(S_OK, hr);
  ASSERT_TRUE(NULL != acc_obj);

  // TODO(ctguil): Fix. The window title could be "New Tab - Chromium" or
  // "about:blank - Chromium"
  TestAccessibilityInfo(acc_obj, l10n_util::GetString(IDS_PRODUCT_NAME),
                        ROLE_SYSTEM_WINDOW);

  acc_obj->Release();
}

// Retrieve accessibility object for non client view and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestNonClientViewAccObj) {
  views::View* non_client_view =
  GetBrowserView()->GetWindow()->GetNonClientView();

  TestViewAccessibilityObject(non_client_view,
      l10n_util::GetString(IDS_PRODUCT_NAME),
      ROLE_SYSTEM_WINDOW);
}

// Retrieve accessibility object for browser root view and verify
// accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestBrowserRootViewAccObj) {
  views::View* browser_root_view =
      GetBrowserView()->frame()->GetFrameView()->GetRootView();

  TestViewAccessibilityObject(browser_root_view,
                              l10n_util::GetString(IDS_PRODUCT_NAME),
                              ROLE_SYSTEM_APPLICATION);
}

// Retrieve accessibility object for browser view and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBrowserViewAccObj) {
  // Verify root view MSAA name and role.
  TestViewAccessibilityObject(GetBrowserView(),
                              l10n_util::GetString(IDS_PRODUCT_NAME),
                              ROLE_SYSTEM_CLIENT);
}

// Retrieve accessibility object for toolbar view and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestToolbarViewAccObj) {
  // Verify toolbar MSAA name and role.
  TestViewAccessibilityObject(GetToolbarView(),
                              l10n_util::GetString(IDS_ACCNAME_TOOLBAR),
                              ROLE_SYSTEM_TOOLBAR);
}

// Retrieve accessibility object for Back button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBackButtonAccObj) {
  // Verify Back button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_BACK_BUTTON),
      l10n_util::GetString(IDS_ACCNAME_BACK), ROLE_SYSTEM_BUTTONDROPDOWN);
}

// Retrieve accessibility object for Forward button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestForwardButtonAccObj) {
  // Verify Forward button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_FORWARD_BUTTON),
      l10n_util::GetString(IDS_ACCNAME_FORWARD), ROLE_SYSTEM_BUTTONDROPDOWN);
}

// Retrieve accessibility object for Reload button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestReloadButtonAccObj) {
  // Verify Reload button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_RELOAD_BUTTON),
      l10n_util::GetString(IDS_ACCNAME_RELOAD), ROLE_SYSTEM_PUSHBUTTON);
}

// Retrieve accessibility object for Home button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestHomeButtonAccObj) {
  // Verify Home button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_HOME_BUTTON),
      l10n_util::GetString(IDS_ACCNAME_HOME), ROLE_SYSTEM_PUSHBUTTON);
}

// Retrieve accessibility object for Star button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestStarButtonAccObj) {
  // Verify Star button MSAA name and role.
  TestViewAccessibilityObject(
      GetToolbarView()->GetViewByID(VIEW_ID_STAR_BUTTON),
      l10n_util::GetString(IDS_ACCNAME_STAR), ROLE_SYSTEM_PUSHBUTTON);
}

// Retrieve accessibility object for location bar view and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestLocationBarViewAccObj) {
  // Verify location bar MSAA name and role.
  TestViewAccessibilityObject(GetLocationBarView(),
                              l10n_util::GetString(IDS_ACCNAME_LOCATION),
                              ROLE_SYSTEM_GROUPING);
}

// Retrieve accessibility object for Go button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestGoButtonAccObj) {
  // Verify Go button MSAA name and role.
  TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_GO_BUTTON),
                              l10n_util::GetString(IDS_ACCNAME_GO),
                              ROLE_SYSTEM_PUSHBUTTON);
}

// Retrieve accessibility object for Page menu button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestPageMenuAccObj) {
  // Verify Page menu button MSAA name and role.
  TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_PAGE_MENU),
                              l10n_util::GetString(IDS_ACCNAME_PAGE),
                              ROLE_SYSTEM_BUTTONMENU);
}

// Retrieve accessibility object for App menu button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestAppMenuAccObj) {
  // Verify App menu button MSAA name and role.
  TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_APP_MENU),
                              l10n_util::GetString(IDS_ACCNAME_APP),
                              ROLE_SYSTEM_BUTTONMENU);
}

IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestBookmarkBarViewAccObj) {
  TestViewAccessibilityObject(GetBookmarkBarView(),
                              l10n_util::GetString(IDS_ACCNAME_BOOKMARKS),
                              ROLE_SYSTEM_TOOLBAR);
}

IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
                       TestAboutChromeViewAccObj) {
  //  Firstly, test that the WindowDelegate got updated.
  views::Window* aboutChromeWindow = GetBrowserView()->ShowAboutChromeDialog();
  EXPECT_STREQ(aboutChromeWindow->GetDelegate()->GetWindowTitle().c_str(),
               l10n_util::GetString(IDS_ABOUT_CHROME_TITLE).c_str());
  EXPECT_EQ(aboutChromeWindow->GetDelegate()->accessible_role(),
            AccessibilityTypes::ROLE_DIALOG);

  // Also test the accessibility object directly.
  IAccessible* acc_obj = NULL;
  HRESULT hr =
    ::AccessibleObjectFromWindow(aboutChromeWindow->GetNativeWindow(),
                                 OBJID_CLIENT,
                                 IID_IAccessible,
                                 reinterpret_cast<void**>(&acc_obj));
  ASSERT_EQ(S_OK, hr);
  ASSERT_TRUE(NULL != acc_obj);

  TestAccessibilityInfo(acc_obj, l10n_util::GetString(IDS_ABOUT_CHROME_TITLE),
                        ROLE_SYSTEM_DIALOG);

  acc_obj->Release();
}
}  // Namespace.

<|endoftext|>


<commit_before>
#include <nstd/Process.h>
#include <nstd/Console.h>
#include <nstd/Directory.h>
#include <nstd/Error.h>
#include <nstd/File.h>

#include "InputData.h"
#include "OutputData.h"
#include "Reader.h"
#include "Parser.h"
#include "Generator.h"

static bool latex2pdf(const String& texFile, const String& engine, const String& auxDirectory)
{
  String tocFile;
  String auxFile;
  {
    const char* end = texFile.findLastOf("\\/.");
    if(end)
    {
      tocFile = texFile.substr(0, end - (const char*)texFile) + ".toc";
      auxFile = texFile.substr(0, end - (const char*)texFile) + ".aux";
    }
    else
    {
      tocFile = texFile + ".toc";
      auxFile = texFile + ".aux";
    }
  }

  for(int run = 0; run < 5; ++run)
  {
    bool tocFileExists = File::exists(tocFile);
    bool auxFileExists = File::exists(auxFile);
    bool rerun = false;

    Process process;
    if(process.open(engine + " --interaction=scrollmode --halt-on-error --file-line-error --aux-directory=\"" + auxDirectory + "\" --output-directory=\"" + auxDirectory + "\" \"" + texFile + "\"") == 0)
      return false;

    // Well I tried to set textinfo.max_print_line in an lua init script. This does not work since it is overwritten from kpathsea when it is reading its config file (texmf.cnf).
    // I tried to create a texmf.cnf file to overwrite max_print_line just for this build, but this does not seem to work with MiKTeX. After inspecting some MiKTeX I came to the
    // conclusion that there is currently no way to set max_print_line without editing the global texmfapp.ini or hacking into MiKTeX's file IO operations.

    // Why the fuck are TeX engines still wrapping log messages after 79 characters? We have terminal emulators and text editors that will do this for you.

    // Now, lets try to unfuck lualatex's output:

    char buffer[32 * 1024];
    String unhandledData;
    String bufferedLine;
    for(ssize i;;)
      switch((i = process.read(buffer, sizeof(buffer))))
      {
      case -1:
        return false;
      case 0:
        if(!bufferedLine.isEmpty() || !unhandledData.isEmpty())
          Console::print(bufferedLine + unhandledData + "\n");
        goto done;
      default:
        unhandledData.append(buffer, i);

        for(;;)
        {
          const char* lineEnd = unhandledData.findOneOf("\r\n");
          if(lineEnd)
          {
            usize lineLen = lineEnd - (const char*)unhandledData;
#ifdef _WIN32
            if(lineLen == 79)
#else
            if(lineLen == 80)
#endif
              bufferedLine.append(unhandledData.substr(0, lineLen));
            else
            {
              String line = bufferedLine + unhandledData.substr(0, lineLen);
              if(line.find("Rerun to get") || line.find("run LaTeX again"))
                rerun = true;

              Console::print(line + "\n");
              bufferedLine.clear();
            }
            if(*lineEnd == '\r' && lineEnd[1] == '\n')
              ++lineLen;
            unhandledData = unhandledData.substr(lineLen + 1);
          }
          else
            break;
        }
        break;
      }

  done: ;

    uint32 exitCode;
    if(!process.join(exitCode))
      return false;
    if(exitCode != 0)
      return false;

    if((!tocFileExists && File::exists(tocFile)) ||
       (!auxFileExists && File::exists(auxFile)))
       rerun = true;

    if(!rerun)
       break;

  }

  return true;
}

int main(int argc, char* argv[])
{
  String inputFile("umdoc.xml");
  String outputFile;
  String engine("lualatex");
  String auxDirectory;
  HashMap<String, String> variables;
  bool stopAfterTex = false;

  {
    Process::Option options[] = {
        {'o', "output", Process::argumentFlag},
        {'e', "engine", Process::argumentFlag},
        {'a', "aux-directory", Process::argumentFlag},
        {'h', "help", Process::optionFlag},
        {'t', "tex", Process::optionFlag},
        {1000, "version", Process::optionFlag},
    };
    Process::Arguments arguments(argc, argv, options);
    int character;
    String argument;
    while(arguments.read(character, argument))
      switch(character)
      {
      case 'o':
        outputFile = argument;
        break;
       case 'e':
        engine = argument;
        break;
       case 'a':
        auxDirectory = argument;
        break;
      case 't':
        stopAfterTex = true;
        break;
      case '?':
        if(argument.startsWith("--"))
        {
          const char* i = argument.find('=');
          if(i)
          {
            variables.append(argument.substr(2, i - (const char*)argument - 2), argument.substr(i  - (const char*)argument + 1));
            continue;
          }
        }
        Console::errorf("Unknown option: %s.\n", (const char*)argument);
        return 1;
      case ':':
        Console::errorf("Option %s required an argument.\n", (const char*)argument);
        return 1;
      case 1000:
        Console::errorf("umdoc %s\n", VERSION);
        return 0;
      case '\0':
        inputFile = argument;
        break;
      default:
        Console::errorf("Usage: %s [<input-file>] [-a <aux-directory>] [-e <latex-engine>]\n             [-o <output-file>] [-t] [--<variable>=<value>]\n", argv[0]);
        return 1;
      }
  }

  if(outputFile.isEmpty())
  {
    const char* end = inputFile.findLastOf("\\/.");
    if(end && *end == '.')
      outputFile = inputFile.substr(0, end - (const char*)inputFile) + (stopAfterTex ? String(".tex") : String(".pdf"));
    else
      outputFile = inputFile + (stopAfterTex ? String(".tex") : String(".pdf"));
  }

  if(auxDirectory.isEmpty())
  {
    const char* end = outputFile.findLastOf("\\/.");
    if(end && *end == '.')
      auxDirectory = outputFile.substr(0, end - (const char*)outputFile);
    else
      auxDirectory = outputFile;
  }

  String tmpTexFile;
  String tmpPdfFile;
  {
    String inputFileBasename = File::basename(inputFile);
    const char* end = inputFileBasename.findLast('.');
    if(end)
      inputFileBasename = inputFileBasename.substr(0, end - (const char*)inputFileBasename);
    tmpTexFile = auxDirectory + "/" + inputFileBasename + ".tex";
    tmpPdfFile = auxDirectory + "/" + inputFileBasename + ".pdf";
  }

  // change working directory to the directory of the input fle
  String inputFileDir = File::dirname(inputFile);
  if(inputFileDir != "." || auxDirectory != ".")
  {
    // convert input and output files to absolute paths
    inputFile = File::getAbsolutePath(inputFile);
    outputFile = File::getAbsolutePath(outputFile);
    auxDirectory = File::getAbsolutePath(auxDirectory);
    tmpTexFile = File::getAbsolutePath(tmpTexFile);
    tmpPdfFile = File::getAbsolutePath(tmpPdfFile);
  }
  if(inputFileDir != ".")
  {
    if(!Directory::change(inputFileDir))
    {
      Console::errorf("%s: error: %s\n", (const char*)inputFile, (const char*)Error::getErrorString());
      return 1;
    }
  }

  //
  InputData inputData;
  OutputData outputData;

  // read input file
  {
    Reader reader;
    if(!reader.read(inputFile, inputData))
    {
      Console::errorf("%s:%d:%d: error: %s\n", (const char*)inputFile, reader.getErrorLine(), reader.getErrorColumn(), (const char*)reader.getErrorString());
      return 1;
    }
  }

  // set variables
  for(HashMap<String, String>::Iterator i = variables.begin(), end = variables.end(); i != end; ++i)
  {
    if(inputData.variables.find(i.key()) == inputData.variables.end())
    {
      Console::errorf("Unknown option: %s.\n", (const char*)i.key());
      return 1;
    }
    inputData.variables.append(i.key(), *i);
  }

  // parse input data
  {
    Parser parser;
    if(!parser.parse(inputData, tmpTexFile, outputData))
    {
      Console::errorf("%s:%d: error: %s\n", (const char*)parser.getErrorFile(), parser.getErrorLine(), (const char*)parser.getErrorString());
      return 1;
    }
  }

  // generate tmp tex file
  if(!Directory::exists(auxDirectory) && !Directory::create(auxDirectory))
  {
    Console::errorf("%s: error: %s\n", (const char*)auxDirectory, (const char*)Error::getErrorString());
    return 1;
  }
  {
    Generator generator;
    if(!generator.generate(engine, outputData, stopAfterTex ? outputFile : tmpTexFile))
    {
      Console::errorf("%s: error: %s\n", (const char*)tmpTexFile, (const char*)generator.getErrorString());
      return 1;
    }
  }
  if(stopAfterTex)
    return 0;

  // change working directory to aux dir
  if(auxDirectory != ".")
  {
    if(!Directory::change(auxDirectory))
    {
      Console::errorf("%s: error: %s\n", (const char*)inputFile, (const char*)Error::getErrorString());
      return 1;
    }
  }

  // covnert tmp tex file to tmp pdf
  if(!latex2pdf(tmpTexFile, engine, auxDirectory))
    return 1;

  // copy tmp pdf to output file
  if(tmpPdfFile != outputFile)
  {
    String pdfData;
    File pdfFile;
    if(!pdfFile.open(tmpPdfFile) ||
       !pdfFile.readAll(pdfData))
    {
      Console::errorf("%s: error: %s\n", (const char*)tmpPdfFile, (const char*)Error::getErrorString());
      return 1;
    }
    File file;
    if(!file.open(outputFile, File::writeFlag) ||
       !file.write(pdfData))
    {
      Console::errorf("%s: error: %s\n", (const char*)outputFile, (const char*)Error::getErrorString());
      return 1;
    }
  }

  return 0;
}
<commit_msg>Revert "Change working directory to aux dir when converting the generated tex file"<commit_after>
#include <nstd/Process.h>
#include <nstd/Console.h>
#include <nstd/Directory.h>
#include <nstd/Error.h>
#include <nstd/File.h>

#include "InputData.h"
#include "OutputData.h"
#include "Reader.h"
#include "Parser.h"
#include "Generator.h"

static bool latex2pdf(const String& texFile, const String& engine, const String& auxDirectory)
{
  String tocFile;
  String auxFile;
  {
    const char* end = texFile.findLastOf("\\/.");
    if(end)
    {
      tocFile = texFile.substr(0, end - (const char*)texFile) + ".toc";
      auxFile = texFile.substr(0, end - (const char*)texFile) + ".aux";
    }
    else
    {
      tocFile = texFile + ".toc";
      auxFile = texFile + ".aux";
    }
  }

  for(int run = 0; run < 5; ++run)
  {
    bool tocFileExists = File::exists(tocFile);
    bool auxFileExists = File::exists(auxFile);
    bool rerun = false;

    Process process;
    if(process.open(engine + " --interaction=scrollmode --halt-on-error --file-line-error --aux-directory=\"" + auxDirectory + "\" --output-directory=\"" + auxDirectory + "\" \"" + texFile + "\"") == 0)
      return false;

    // Well I tried to set textinfo.max_print_line in an lua init script. This does not work since it is overwritten from kpathsea when it is reading its config file (texmf.cnf).
    // I tried to create a texmf.cnf file to overwrite max_print_line just for this build, but this does not seem to work with MiKTeX. After inspecting some MiKTeX I came to the
    // conclusion that there is currently no way to set max_print_line without editing the global texmfapp.ini or hacking into MiKTeX's file IO operations.

    // Why the fuck are TeX engines still wrapping log messages after 79 characters? We have terminal emulators and text editors that will do this for you.

    // Now, lets try to unfuck lualatex's output:

    char buffer[32 * 1024];
    String unhandledData;
    String bufferedLine;
    for(ssize i;;)
      switch((i = process.read(buffer, sizeof(buffer))))
      {
      case -1:
        return false;
      case 0:
        if(!bufferedLine.isEmpty() || !unhandledData.isEmpty())
          Console::print(bufferedLine + unhandledData + "\n");
        goto done;
      default:
        unhandledData.append(buffer, i);

        for(;;)
        {
          const char* lineEnd = unhandledData.findOneOf("\r\n");
          if(lineEnd)
          {
            usize lineLen = lineEnd - (const char*)unhandledData;
#ifdef _WIN32
            if(lineLen == 79)
#else
            if(lineLen == 80)
#endif
              bufferedLine.append(unhandledData.substr(0, lineLen));
            else
            {
              String line = bufferedLine + unhandledData.substr(0, lineLen);
              if(line.find("Rerun to get") || line.find("run LaTeX again"))
                rerun = true;

              Console::print(line + "\n");
              bufferedLine.clear();
            }
            if(*lineEnd == '\r' && lineEnd[1] == '\n')
              ++lineLen;
            unhandledData = unhandledData.substr(lineLen + 1);
          }
          else
            break;
        }
        break;
      }

  done: ;

    uint32 exitCode;
    if(!process.join(exitCode))
      return false;
    if(exitCode != 0)
      return false;

    if((!tocFileExists && File::exists(tocFile)) ||
       (!auxFileExists && File::exists(auxFile)))
       rerun = true;

    if(!rerun)
       break;

  }

  return true;
}

int main(int argc, char* argv[])
{
  String inputFile("umdoc.xml");
  String outputFile;
  String engine("lualatex");
  String auxDirectory;
  HashMap<String, String> variables;
  bool stopAfterTex = false;

  {
    Process::Option options[] = {
        {'o', "output", Process::argumentFlag},
        {'e', "engine", Process::argumentFlag},
        {'a', "aux-directory", Process::argumentFlag},
        {'h', "help", Process::optionFlag},
        {'t', "tex", Process::optionFlag},
        {1000, "version", Process::optionFlag},
    };
    Process::Arguments arguments(argc, argv, options);
    int character;
    String argument;
    while(arguments.read(character, argument))
      switch(character)
      {
      case 'o':
        outputFile = argument;
        break;
       case 'e':
        engine = argument;
        break;
       case 'a':
        auxDirectory = argument;
        break;
      case 't':
        stopAfterTex = true;
        break;
      case '?':
        if(argument.startsWith("--"))
        {
          const char* i = argument.find('=');
          if(i)
          {
            variables.append(argument.substr(2, i - (const char*)argument - 2), argument.substr(i  - (const char*)argument + 1));
            continue;
          }
        }
        Console::errorf("Unknown option: %s.\n", (const char*)argument);
        return 1;
      case ':':
        Console::errorf("Option %s required an argument.\n", (const char*)argument);
        return 1;
      case 1000:
        Console::errorf("umdoc %s\n", VERSION);
        return 0;
      case '\0':
        inputFile = argument;
        break;
      default:
        Console::errorf("Usage: %s [<input-file>] [-a <aux-directory>] [-e <latex-engine>]\n             [-o <output-file>] [-t] [--<variable>=<value>]\n", argv[0]);
        return 1;
      }
  }

  if(outputFile.isEmpty())
  {
    const char* end = inputFile.findLastOf("\\/.");
    if(end && *end == '.')
      outputFile = inputFile.substr(0, end - (const char*)inputFile) + (stopAfterTex ? String(".tex") : String(".pdf"));
    else
      outputFile = inputFile + (stopAfterTex ? String(".tex") : String(".pdf"));
  }

  if(auxDirectory.isEmpty())
  {
    const char* end = outputFile.findLastOf("\\/.");
    if(end && *end == '.')
      auxDirectory = outputFile.substr(0, end - (const char*)outputFile);
    else
      auxDirectory = outputFile;
  }

  String tmpTexFile;
  String tmpPdfFile;
  {
    String inputFileBasename = File::basename(inputFile);
    const char* end = inputFileBasename.findLast('.');
    if(end)
      inputFileBasename = inputFileBasename.substr(0, end - (const char*)inputFileBasename);
    tmpTexFile = auxDirectory + "/" + inputFileBasename + ".tex";
    tmpPdfFile = auxDirectory + "/" + inputFileBasename + ".pdf";
  }

  // change working directory to the directory of the input fle
  String inputFileDir = File::dirname(inputFile);
  if(inputFileDir != "." || auxDirectory != ".")
  {
    // convert input and output files to absolute paths:wq:wq
    inputFile = File::getAbsolutePath(inputFile);
    outputFile = File::getAbsolutePath(outputFile);
    auxDirectory = File::getAbsolutePath(auxDirectory);
    tmpTexFile = File::getAbsolutePath(tmpTexFile);
    tmpPdfFile = File::getAbsolutePath(tmpPdfFile);
  }
  if(inputFileDir != ".")
  {
    if(!Directory::change(inputFileDir))
    {
      Console::errorf("%s: error: %s\n", (const char*)inputFile, (const char*)Error::getErrorString());
      return 1;
    }
  }

  //
  InputData inputData;
  OutputData outputData;

  // read input file
  {
    Reader reader;
    if(!reader.read(inputFile, inputData))
    {
      Console::errorf("%s:%d:%d: error: %s\n", (const char*)inputFile, reader.getErrorLine(), reader.getErrorColumn(), (const char*)reader.getErrorString());
      return 1;
    }
  }

  // set variables
  for(HashMap<String, String>::Iterator i = variables.begin(), end = variables.end(); i != end; ++i)
  {
    if(inputData.variables.find(i.key()) == inputData.variables.end())
    {
      Console::errorf("Unknown option: %s.\n", (const char*)i.key());
      return 1;
    }
    inputData.variables.append(i.key(), *i);
  }

  // parse input data
  {
    Parser parser;
    if(!parser.parse(inputData, tmpTexFile, outputData))
    {
      Console::errorf("%s:%d: error: %s\n", (const char*)parser.getErrorFile(), parser.getErrorLine(), (const char*)parser.getErrorString());
      return 1;
    }
  }

  // generate tmp tex file
  if(!Directory::exists(auxDirectory) && !Directory::create(auxDirectory))
  {
    Console::errorf("%s: error: %s\n", (const char*)auxDirectory, (const char*)Error::getErrorString());
    return 1;
  }
  {
    Generator generator;
    if(!generator.generate(engine, outputData, stopAfterTex ? outputFile : tmpTexFile))
    {
      Console::errorf("%s: error: %s\n", (const char*)tmpTexFile, (const char*)generator.getErrorString());
      return 1;
    }
  }
  if(stopAfterTex)
    return 0;

  // covnert tmp tex file to tmp pdf
  if(!latex2pdf(tmpTexFile, engine, auxDirectory))
    return 1;

  // copy tmp pdf to output file
  if(tmpPdfFile != outputFile)
  {
    String pdfData;
    File pdfFile;
    if(!pdfFile.open(tmpPdfFile) ||
       !pdfFile.readAll(pdfData))
    {
      Console::errorf("%s: error: %s\n", (const char*)tmpPdfFile, (const char*)Error::getErrorString());
      return 1;
    }
    File file;
    if(!file.open(outputFile, File::writeFlag) ||
       !file.write(pdfData))
    {
      Console::errorf("%s: error: %s\n", (const char*)outputFile, (const char*)Error::getErrorString());
      return 1;
    }
  }

  return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <set>
#include <map>
#include <list>
#include <queue>
#include <stack>
#include <memory>
#include <iomanip>
#include <numeric>
#include <functional>
#include <new>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <climits>
#include <cctype>
#include <ctime>

#define REP(i, n) for(int (i) = 0; i < n; i++)
#define FOR(i, a, n) for(int (i) = a; i < n; i++)
#define FORR(i, a, n) for(int (i) = a; i <= n; i++)
#define for_each(q, s) for(typeof(s.begin()) q=s.begin(); q!=s.end(); q++)
#define sz(n) n.size()
#define pb(n) push_back(n)
#define all(n) n.begin(), n.end()

template<typename T> T gcd(T a, T b) {
    if(!b) return a;
    return gcd(b, a % b);
}
template<typename T> T lcm(T a, T b) {
    return a * b / gcd(a, b);
}

template<typename T> void chmin(T& a, T b) { a = (a > b) ? b : a; }
template<typename T> void chmax(T& a, T b) { a = (a < b) ? b : a; }

using namespace std;

typedef long long ll;
typedef unsigned uint;

int main(void) {

    return 0;
}
<commit_msg>updating standard file<commit_after>#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <set>
#include <map>
#include <list>
#include <queue>
#include <stack>
#include <memory>
#include <iomanip>
#include <numeric>
#include <functional>
#include <new>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <climits>
#include <cctype>
#include <ctime>

#define REP(i, n) for(int (i) = 0; i < n; i++)
#define FOR(i, a, n) for(int (i) = a; i < n; i++)
#define FORR(i, a, n) for(int (i) = a; i <= n; i++)
#define for_each(q, s) for(typeof(s.begin()) q=s.begin(); q!=s.end(); q++)
#define sz(n) n.size()
#define pb(n) push_back(n)
#define all(n) n.begin(), n.end()

template<typename T> T gcd(T a, T b) {
    if(!b) return a;
    return gcd(b, a % b);
}
template<typename T> T lcm(T a, T b) {
    return a * b / gcd(a, b);
}

template<typename T> void chmin(T& a, T b) { a = (a > b) ? b : a; }
template<typename T> void chmax(T& a, T b) { a = (a < b) ? b : a; }
int in() { int x; scanf("%d", &x); return x; }

using namespace std;

typedef long long Int;
typedef unsigned uint;

int main(void) {

    return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2008, 2009 Nokia Corporation.
 *
 * Contact: Marius Vollmer <marius.vollmer@nokia.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * version 2.1 as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
 */

#include <QtTest/QtTest>
#include <QtCore>
#include "boolsysfspooler.h"

class BoolSysFsPoolerUnitTest : public QObject
{
    Q_OBJECT

private slots:
    void basic();
    void fileMissing();
    void incorrectData();
};

void BoolSysFsPoolerUnitTest::basic()
{
    BoolSysFsPooler pooler("input1.txt");
    QCOMPARE(pooler.getState(), BoolSysFsPooler::TriStateTrue);
}

void BoolSysFsPoolerUnitTest::fileMissing()
{
    BoolSysFsPooler pooler("does-not-exist.txt");
    QCOMPARE(pooler.getState(), BoolSysFsPooler::TriStateUnknown);
}

void BoolSysFsPoolerUnitTest::incorrectData()
{
    BoolSysFsPooler pooler("input2.txt");
    QCOMPARE(pooler.getState(), BoolSysFsPooler::TriStateUnknown);
}

#include "boolsysfspoolerunittest.moc"
QTEST_MAIN(BoolSysFsPoolerUnitTest);
<commit_msg>Ensure no emissions.<commit_after>/*
 * Copyright (C) 2008, 2009 Nokia Corporation.
 *
 * Contact: Marius Vollmer <marius.vollmer@nokia.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * version 2.1 as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
 */

#include <QtTest/QtTest>
#include <QtCore>
#include "boolsysfspooler.h"

class BoolSysFsPoolerUnitTest : public QObject
{
    Q_OBJECT

private slots:
    void basic();
    void fileMissing();
    void incorrectData();
};

void BoolSysFsPoolerUnitTest::basic()
{
    BoolSysFsPooler pooler("input1.txt");
    QSignalSpy spy(&pooler, SIGNAL(stateChanged(TriState)));
    QCOMPARE(pooler.getState(), BoolSysFsPooler::TriStateTrue);
    QCOMPARE(spy.count(), 0);
}

void BoolSysFsPoolerUnitTest::fileMissing()
{
    BoolSysFsPooler pooler("does-not-exist.txt");
    QSignalSpy spy(&pooler, SIGNAL(stateChanged(TriState)));
    QCOMPARE(pooler.getState(), BoolSysFsPooler::TriStateUnknown);
    QCOMPARE(spy.count(), 0);
}

void BoolSysFsPoolerUnitTest::incorrectData()
{
    BoolSysFsPooler pooler("input2.txt");
    QSignalSpy spy(&pooler, SIGNAL(stateChanged(TriState)));
    QCOMPARE(pooler.getState(), BoolSysFsPooler::TriStateUnknown);
    QCOMPARE(spy.count(), 0);
}

#include "boolsysfspoolerunittest.moc"
QTEST_MAIN(BoolSysFsPoolerUnitTest);
<|endoftext|>


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

#include "ui/views/corewm/tooltip_win.h"

#include <winuser.h>

#include "base/debug/stack_trace.h"
#include "base/i18n/rtl.h"
#include "base/logging.h"
#include "ui/base/l10n/l10n_util_win.h"
#include "ui/gfx/rect.h"
#include "ui/gfx/screen.h"

namespace views {
namespace corewm {

TooltipWin::TooltipWin(HWND parent)
    : parent_hwnd_(parent),
      tooltip_hwnd_(NULL),
      showing_(false) {
  memset(&toolinfo_, 0, sizeof(toolinfo_));
  toolinfo_.cbSize = sizeof(toolinfo_);
  toolinfo_.uFlags = TTF_IDISHWND | TTF_TRACK | TTF_ABSOLUTE;
  toolinfo_.uId = reinterpret_cast<UINT_PTR>(parent_hwnd_);
  toolinfo_.hwnd = parent_hwnd_;
  toolinfo_.lpszText = NULL;
  toolinfo_.lpReserved = NULL;
  SetRectEmpty(&toolinfo_.rect);
}

TooltipWin::~TooltipWin() {
  if (tooltip_hwnd_)
    DestroyWindow(tooltip_hwnd_);
}

bool TooltipWin::HandleNotify(int w_param, NMHDR* l_param, LRESULT* l_result) {
  if (tooltip_hwnd_ == NULL)
    return false;

  switch (l_param->code) {
    case TTN_POP:
      showing_ = false;
      return true;
    case TTN_SHOW:
      *l_result = TRUE;
      PositionTooltip();
      showing_ = true;
      return true;
    default:
      break;
  }
  return false;
}

bool TooltipWin::EnsureTooltipWindow() {
  if (tooltip_hwnd_)
    return true;

  tooltip_hwnd_ = CreateWindowEx(
      WS_EX_TRANSPARENT | l10n_util::GetExtendedTooltipStyles(),
      TOOLTIPS_CLASS, NULL, TTS_NOPREFIX | WS_POPUP, 0, 0, 0, 0,
      parent_hwnd_, NULL, NULL, NULL);
  if (!tooltip_hwnd_) {
    LOG_GETLASTERROR(WARNING) << "tooltip creation failed, disabling tooltips";
    return false;
  }

  l10n_util::AdjustUIFontForWindow(tooltip_hwnd_);

  SendMessage(tooltip_hwnd_, TTM_ADDTOOL, 0,
              reinterpret_cast<LPARAM>(&toolinfo_));
  return true;
}

void TooltipWin::PositionTooltip() {
  // This code only runs for non-metro, so GetNativeScreen() is fine.
  gfx::Display display(
      gfx::Screen::GetNativeScreen()->GetDisplayNearestPoint(location_));

  DWORD tooltip_size = SendMessage(tooltip_hwnd_, TTM_GETBUBBLESIZE, 0,
                                   reinterpret_cast<LPARAM>(&toolinfo_));
  // 20 accounts for visible cursor size. I tried using SM_CYCURSOR but that's
  // way too big (32 on win7 default).
  // TODO(sky): figure out the right way to determine offset.
  const int initial_y = location_.y();
  gfx::Rect tooltip_bounds(location_.x(), initial_y + 20,
                           LOWORD(tooltip_size), HIWORD(tooltip_size));
  tooltip_bounds.AdjustToFit(display.work_area());
  if (tooltip_bounds.y() < initial_y)
    tooltip_bounds.set_y(initial_y - tooltip_bounds.height() - 2);
  SetWindowPos(tooltip_hwnd_, NULL, tooltip_bounds.x(), tooltip_bounds.y(), 0,
               0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
}

void TooltipWin::SetText(aura::Window* window,
                         const base::string16& tooltip_text,
                         const gfx::Point& location) {
  if (!EnsureTooltipWindow())
    return;

  // See comment in header for details on why |location_| is needed.
  location_ = location;

  // Without this we get a flicker of the tooltip appearing at 0x0. Not sure
  // why.
  SetWindowPos(tooltip_hwnd_, NULL, 0, 0, 0, 0,
               SWP_HIDEWINDOW | SWP_NOACTIVATE | SWP_NOMOVE |
               SWP_NOREPOSITION | SWP_NOSIZE | SWP_NOZORDER);

  base::string16 adjusted_text(tooltip_text);
  base::i18n::AdjustStringForLocaleDirection(&adjusted_text);
  toolinfo_.lpszText = const_cast<WCHAR*>(adjusted_text.c_str());
  SendMessage(tooltip_hwnd_, TTM_SETTOOLINFO, 0,
              reinterpret_cast<LPARAM>(&toolinfo_));

  // This code only runs for non-metro, so GetNativeScreen() is fine.
  gfx::Display display(
      gfx::Screen::GetNativeScreen()->GetDisplayNearestPoint(location_));
  const gfx::Rect monitor_bounds = display.bounds();
  int max_width = (monitor_bounds.width() + 1) / 2;
  SendMessage(tooltip_hwnd_, TTM_SETMAXTIPWIDTH, 0, max_width);
}

void TooltipWin::Show() {
  if (!EnsureTooltipWindow())
    return;

  SendMessage(tooltip_hwnd_, TTM_TRACKACTIVATE,
              TRUE, reinterpret_cast<LPARAM>(&toolinfo_));
}

void TooltipWin::Hide() {
  if (!EnsureTooltipWindow())
    return;

  SendMessage(tooltip_hwnd_, TTM_TRACKACTIVATE, FALSE,
              reinterpret_cast<LPARAM>(&toolinfo_));
}

bool TooltipWin::IsVisible() {
  return showing_;
}

}  // namespace corewm
}  // namespace views
<commit_msg>Makes tooltip always on top<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/views/corewm/tooltip_win.h"

#include <winuser.h>

#include "base/debug/stack_trace.h"
#include "base/i18n/rtl.h"
#include "base/logging.h"
#include "ui/base/l10n/l10n_util_win.h"
#include "ui/gfx/rect.h"
#include "ui/gfx/screen.h"

namespace views {
namespace corewm {

TooltipWin::TooltipWin(HWND parent)
    : parent_hwnd_(parent),
      tooltip_hwnd_(NULL),
      showing_(false) {
  memset(&toolinfo_, 0, sizeof(toolinfo_));
  toolinfo_.cbSize = sizeof(toolinfo_);
  toolinfo_.uFlags = TTF_IDISHWND | TTF_TRACK | TTF_ABSOLUTE;
  toolinfo_.uId = reinterpret_cast<UINT_PTR>(parent_hwnd_);
  toolinfo_.hwnd = parent_hwnd_;
  toolinfo_.lpszText = NULL;
  toolinfo_.lpReserved = NULL;
  SetRectEmpty(&toolinfo_.rect);
}

TooltipWin::~TooltipWin() {
  if (tooltip_hwnd_)
    DestroyWindow(tooltip_hwnd_);
}

bool TooltipWin::HandleNotify(int w_param, NMHDR* l_param, LRESULT* l_result) {
  if (tooltip_hwnd_ == NULL)
    return false;

  switch (l_param->code) {
    case TTN_POP:
      showing_ = false;
      return true;
    case TTN_SHOW:
      *l_result = TRUE;
      PositionTooltip();
      showing_ = true;
      return true;
    default:
      break;
  }
  return false;
}

bool TooltipWin::EnsureTooltipWindow() {
  if (tooltip_hwnd_)
    return true;

  tooltip_hwnd_ = CreateWindowEx(
      WS_EX_TRANSPARENT | l10n_util::GetExtendedTooltipStyles(),
      TOOLTIPS_CLASS, NULL, TTS_NOPREFIX | WS_POPUP, 0, 0, 0, 0,
      parent_hwnd_, NULL, NULL, NULL);
  if (!tooltip_hwnd_) {
    LOG_GETLASTERROR(WARNING) << "tooltip creation failed, disabling tooltips";
    return false;
  }

  l10n_util::AdjustUIFontForWindow(tooltip_hwnd_);

  SendMessage(tooltip_hwnd_, TTM_ADDTOOL, 0,
              reinterpret_cast<LPARAM>(&toolinfo_));
  return true;
}

void TooltipWin::PositionTooltip() {
  // This code only runs for non-metro, so GetNativeScreen() is fine.
  gfx::Display display(
      gfx::Screen::GetNativeScreen()->GetDisplayNearestPoint(location_));

  DWORD tooltip_size = SendMessage(tooltip_hwnd_, TTM_GETBUBBLESIZE, 0,
                                   reinterpret_cast<LPARAM>(&toolinfo_));
  // 20 accounts for visible cursor size. I tried using SM_CYCURSOR but that's
  // way too big (32 on win7 default).
  // TODO(sky): figure out the right way to determine offset.
  const int initial_y = location_.y();
  gfx::Rect tooltip_bounds(location_.x(), initial_y + 20,
                           LOWORD(tooltip_size), HIWORD(tooltip_size));
  tooltip_bounds.AdjustToFit(display.work_area());
  if (tooltip_bounds.y() < initial_y)
    tooltip_bounds.set_y(initial_y - tooltip_bounds.height() - 2);
  SetWindowPos(tooltip_hwnd_, NULL, tooltip_bounds.x(), tooltip_bounds.y(), 0,
               0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
}

void TooltipWin::SetText(aura::Window* window,
                         const base::string16& tooltip_text,
                         const gfx::Point& location) {
  if (!EnsureTooltipWindow())
    return;

  // See comment in header for details on why |location_| is needed.
  location_ = location;

  // Without this we get a flicker of the tooltip appearing at 0x0. Not sure
  // why.
  SetWindowPos(tooltip_hwnd_, NULL, 0, 0, 0, 0,
               SWP_HIDEWINDOW | SWP_NOACTIVATE | SWP_NOMOVE |
               SWP_NOREPOSITION | SWP_NOSIZE | SWP_NOZORDER);

  base::string16 adjusted_text(tooltip_text);
  base::i18n::AdjustStringForLocaleDirection(&adjusted_text);
  toolinfo_.lpszText = const_cast<WCHAR*>(adjusted_text.c_str());
  SendMessage(tooltip_hwnd_, TTM_SETTOOLINFO, 0,
              reinterpret_cast<LPARAM>(&toolinfo_));

  // This code only runs for non-metro, so GetNativeScreen() is fine.
  gfx::Display display(
      gfx::Screen::GetNativeScreen()->GetDisplayNearestPoint(location_));
  const gfx::Rect monitor_bounds = display.bounds();
  int max_width = (monitor_bounds.width() + 1) / 2;
  SendMessage(tooltip_hwnd_, TTM_SETMAXTIPWIDTH, 0, max_width);
}

void TooltipWin::Show() {
  if (!EnsureTooltipWindow())
    return;

  SendMessage(tooltip_hwnd_, TTM_TRACKACTIVATE,
              TRUE, reinterpret_cast<LPARAM>(&toolinfo_));
  SetWindowPos(tooltip_hwnd_, HWND_TOPMOST, 0, 0, 0, 0,
               SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOSIZE);
}

void TooltipWin::Hide() {
  if (!EnsureTooltipWindow())
    return;

  SendMessage(tooltip_hwnd_, TTM_TRACKACTIVATE, FALSE,
              reinterpret_cast<LPARAM>(&toolinfo_));
}

bool TooltipWin::IsVisible() {
  return showing_;
}

}  // namespace corewm
}  // namespace views
<|endoftext|>


<commit_before>/*
 * Copyright 2016 Cloudius Systems
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#define BOOST_TEST_DYN_LINK

#include <boost/range/irange.hpp>
#include <boost/range/adaptors.hpp>
#include <boost/range/algorithm.hpp>
#include <boost/test/unit_test.hpp>
#include <stdint.h>

#include <seastar/core/future-util.hh>
#include <seastar/core/shared_ptr.hh>
#include <seastar/core/thread.hh>

#include "tests/test-utils.hh"
#include "tests/cql_test_env.hh"
#include "tests/cql_assertions.hh"

#include "auth/auth.hh"
#include "auth/data_resource.hh"
#include "auth/authenticator.hh"
#include "auth/password_authenticator.hh"
#include "auth/authenticated_user.hh"

#include "db/config.hh"
#include "cql3/query_processor.hh"

SEASTAR_TEST_CASE(test_data_resource) {
    auth::data_resource root, keyspace("fisk"), column_family("fisk", "notter");

    BOOST_REQUIRE_EQUAL(root.is_root_level(), true);
    BOOST_REQUIRE_EQUAL(keyspace.is_keyspace_level(), true);
    BOOST_REQUIRE_EQUAL(column_family.is_column_family_level(), true);

    BOOST_REQUIRE_EQUAL(root.has_parent(), false);
    BOOST_REQUIRE_EQUAL(keyspace.has_parent(), true);
    BOOST_REQUIRE_EQUAL(column_family.has_parent(), true);

    try {
        root.get_parent();
        BOOST_FAIL("Should not reach");
    } catch (...) {
        //  ok
    }

    BOOST_REQUIRE_EQUAL(keyspace.get_parent(), root);
    BOOST_REQUIRE_EQUAL(column_family.get_parent(), keyspace);

    return make_ready_future();
}

SEASTAR_TEST_CASE(test_default_authenticator) {
    return do_with_cql_env([](cql_test_env&) {
        BOOST_REQUIRE_EQUAL(auth::authenticator::get().require_authentication(), false);
        BOOST_REQUIRE_EQUAL(auth::authenticator::get().class_name(), auth::authenticator::ALLOW_ALL_AUTHENTICATOR_NAME);
        return make_ready_future();
    });
}

SEASTAR_TEST_CASE(test_password_authenticator_attributes) {
    db::config cfg;
    cfg.authenticator = auth::password_authenticator::PASSWORD_AUTHENTICATOR_NAME;

    return do_with_cql_env([](cql_test_env&) {
        BOOST_REQUIRE_EQUAL(auth::authenticator::get().require_authentication(), true);
        BOOST_REQUIRE_EQUAL(auth::authenticator::get().class_name(), auth::password_authenticator::PASSWORD_AUTHENTICATOR_NAME);
        return make_ready_future();
    }, cfg);
}

SEASTAR_TEST_CASE(test_auth_users) {
    db::config cfg;
    cfg.authenticator = auth::password_authenticator::PASSWORD_AUTHENTICATOR_NAME;

    return do_with_cql_env([](cql_test_env&) {
        return seastar::async([] {
            sstring username("fisk");
            auth::auth::insert_user(username, false).get();
            BOOST_REQUIRE_EQUAL(auth::auth::is_existing_user(username).get0(), true);
            BOOST_REQUIRE_EQUAL(auth::auth::is_super_user(username).get0(), false);

            auth::auth::insert_user(username, true).get();
            BOOST_REQUIRE_EQUAL(auth::auth::is_existing_user(username).get0(), true);
            BOOST_REQUIRE_EQUAL(auth::auth::is_super_user(username).get0(), true);

            auth::auth::delete_user(username).get();
            BOOST_REQUIRE_EQUAL(auth::auth::is_existing_user(username).get0(), false);
            BOOST_REQUIRE_EQUAL(auth::auth::is_super_user(username).get0(), false);
        });
    }, cfg);
}

SEASTAR_TEST_CASE(test_password_authenticator_operations) {
    db::config cfg;
    cfg.authenticator = auth::password_authenticator::PASSWORD_AUTHENTICATOR_NAME;

    /**
     * Not using seastar::async due to apparent ASan bug.
     * Enjoy the slightly less readable code.
     */
    return do_with_cql_env([](cql_test_env&) {
        sstring username("fisk");
        sstring password("notter");

        using namespace auth;
        using option = authenticator::option;
        using user_ptr = ::shared_ptr<authenticated_user>;

        auto USERNAME_KEY = authenticator::USERNAME_KEY;
        auto PASSWORD_KEY = authenticator::PASSWORD_KEY;

        // check non-existing user
        return authenticator::get().authenticate({ { USERNAME_KEY, username }, { PASSWORD_KEY, password } }).then_wrapped([](future<user_ptr>&& f) {
            try {
                f.get();
                BOOST_FAIL("should not reach");
            } catch (exceptions::authentication_exception&) {
                // ok
            }
        }).then([=] {
            return authenticator::get().create(username, { { option::PASSWORD, password} }).then([=] {
                return authenticator::get().authenticate({ { USERNAME_KEY, username }, { PASSWORD_KEY, password } }).then([=](user_ptr user) {
                    BOOST_REQUIRE_EQUAL(user->name(), username);
                    BOOST_REQUIRE_EQUAL(user->is_anonymous(), false);
                });
            });
        }).then([=] {
            // check wrong password
            return authenticator::get().authenticate( { {USERNAME_KEY, username}, {PASSWORD_KEY, "hejkotte"}}).then_wrapped([](future<user_ptr>&& f) {
                try {
                    f.get();
                    BOOST_FAIL("should not reach");
                } catch (exceptions::authentication_exception&) {
                    // ok
                }
            });
        }).then([=] {
            // sasl
            auto sasl = authenticator::get().new_sasl_challenge();

            BOOST_REQUIRE_EQUAL(sasl->is_complete(), false);

            bytes b;
            int8_t i = 0;
            b.append(&i, 1);
            b.insert(b.end(), username.begin(), username.end());
            b.append(&i, 1);
            b.insert(b.end(), password.begin(), password.end());

            sasl->evaluate_response(b);
            BOOST_REQUIRE_EQUAL(sasl->is_complete(), true);

            return sasl->get_authenticated_user().then([=](user_ptr user) {
                BOOST_REQUIRE_EQUAL(user->name(), username);
                BOOST_REQUIRE_EQUAL(user->is_anonymous(), false);
            });
        }).then([=] {
            // check deleted user
            return authenticator::get().drop(username).then([=] {
                return authenticator::get().authenticate({ { USERNAME_KEY, username }, { PASSWORD_KEY, password } }).then_wrapped([](future<user_ptr>&& f) {
                    try {
                        f.get();
                        BOOST_FAIL("should not reach");
                    } catch (exceptions::authentication_exception&) {
                        // ok
                    }
                });
            });
        });
    }, cfg);
}

SEASTAR_TEST_CASE(test_cassandra_hash) {
    db::config cfg;
    cfg.authenticator = auth::password_authenticator::PASSWORD_AUTHENTICATOR_NAME;

    return do_with_cql_env([](cql_test_env& env) {
        return seastar::async([&env] {

            /**
             * Try to check password against hash from origin.
             * Allow for specific failure if glibc cannot handle the
             * hash algo (i.e. blowfish).
             */

            sstring username("fisk");
            sstring password("cassandra");
            sstring salted_hash("$2a$10$8cz4EZ5v8f/aTZFkNEQafe.z66ZvjOonOpHCApwx0ksWp3aKf.Roq");

            // This is extremely whitebox. We'll just go right ahead and know
            // what the tables etc are called. Oy wei...
            env.local_qp().process("INSERT into system_auth.credentials (username, salted_hash) values (?, ?)", db::consistency_level::ONE,
                            {username, salted_hash}).get();

            auto& a = auth::authenticator::get();

            auto USERNAME_KEY = auth::authenticator::USERNAME_KEY;
            auto PASSWORD_KEY = auth::authenticator::PASSWORD_KEY;

            // try to verify our user with a cassandra-originated salted_hash
            try {
                a.authenticate({ { USERNAME_KEY, username }, { PASSWORD_KEY, password } }).get0();
            } catch (exceptions::authentication_exception& e) {
                try {
                    std::rethrow_if_nested(e);
                    BOOST_FAIL(std::string("Unexcepted exception ") + e.what());
                } catch (std::system_error & e) {
                    bool is_einval = e.code().category() == std::system_category() && e.code().value() == EINVAL;
                    BOOST_WARN_MESSAGE(is_einval, "Could not verify cassandra password hash due to glibc limitation");
                    if (!is_einval) {
                        BOOST_FAIL(std::string("Unexcepted system error ") + e.what());
                    }
                }
            }
        });
    }, cfg);
}

<commit_msg>auth_test: Modify yet another case to use "normal" continuation.<commit_after>/*
 * Copyright 2016 Cloudius Systems
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#define BOOST_TEST_DYN_LINK

#include <boost/range/irange.hpp>
#include <boost/range/adaptors.hpp>
#include <boost/range/algorithm.hpp>
#include <boost/test/unit_test.hpp>
#include <stdint.h>

#include <seastar/core/future-util.hh>
#include <seastar/core/shared_ptr.hh>
#include <seastar/core/thread.hh>

#include "tests/test-utils.hh"
#include "tests/cql_test_env.hh"
#include "tests/cql_assertions.hh"

#include "auth/auth.hh"
#include "auth/data_resource.hh"
#include "auth/authenticator.hh"
#include "auth/password_authenticator.hh"
#include "auth/authenticated_user.hh"

#include "db/config.hh"
#include "cql3/query_processor.hh"

SEASTAR_TEST_CASE(test_data_resource) {
    auth::data_resource root, keyspace("fisk"), column_family("fisk", "notter");

    BOOST_REQUIRE_EQUAL(root.is_root_level(), true);
    BOOST_REQUIRE_EQUAL(keyspace.is_keyspace_level(), true);
    BOOST_REQUIRE_EQUAL(column_family.is_column_family_level(), true);

    BOOST_REQUIRE_EQUAL(root.has_parent(), false);
    BOOST_REQUIRE_EQUAL(keyspace.has_parent(), true);
    BOOST_REQUIRE_EQUAL(column_family.has_parent(), true);

    try {
        root.get_parent();
        BOOST_FAIL("Should not reach");
    } catch (...) {
        //  ok
    }

    BOOST_REQUIRE_EQUAL(keyspace.get_parent(), root);
    BOOST_REQUIRE_EQUAL(column_family.get_parent(), keyspace);

    return make_ready_future();
}

SEASTAR_TEST_CASE(test_default_authenticator) {
    return do_with_cql_env([](cql_test_env&) {
        BOOST_REQUIRE_EQUAL(auth::authenticator::get().require_authentication(), false);
        BOOST_REQUIRE_EQUAL(auth::authenticator::get().class_name(), auth::authenticator::ALLOW_ALL_AUTHENTICATOR_NAME);
        return make_ready_future();
    });
}

SEASTAR_TEST_CASE(test_password_authenticator_attributes) {
    db::config cfg;
    cfg.authenticator = auth::password_authenticator::PASSWORD_AUTHENTICATOR_NAME;

    return do_with_cql_env([](cql_test_env&) {
        BOOST_REQUIRE_EQUAL(auth::authenticator::get().require_authentication(), true);
        BOOST_REQUIRE_EQUAL(auth::authenticator::get().class_name(), auth::password_authenticator::PASSWORD_AUTHENTICATOR_NAME);
        return make_ready_future();
    }, cfg);
}

SEASTAR_TEST_CASE(test_auth_users) {
    db::config cfg;
    cfg.authenticator = auth::password_authenticator::PASSWORD_AUTHENTICATOR_NAME;

    return do_with_cql_env([](cql_test_env&) {
        return seastar::async([] {
            sstring username("fisk");
            auth::auth::insert_user(username, false).get();
            BOOST_REQUIRE_EQUAL(auth::auth::is_existing_user(username).get0(), true);
            BOOST_REQUIRE_EQUAL(auth::auth::is_super_user(username).get0(), false);

            auth::auth::insert_user(username, true).get();
            BOOST_REQUIRE_EQUAL(auth::auth::is_existing_user(username).get0(), true);
            BOOST_REQUIRE_EQUAL(auth::auth::is_super_user(username).get0(), true);

            auth::auth::delete_user(username).get();
            BOOST_REQUIRE_EQUAL(auth::auth::is_existing_user(username).get0(), false);
            BOOST_REQUIRE_EQUAL(auth::auth::is_super_user(username).get0(), false);
        });
    }, cfg);
}

SEASTAR_TEST_CASE(test_password_authenticator_operations) {
    db::config cfg;
    cfg.authenticator = auth::password_authenticator::PASSWORD_AUTHENTICATOR_NAME;

    /**
     * Not using seastar::async due to apparent ASan bug.
     * Enjoy the slightly less readable code.
     */
    return do_with_cql_env([](cql_test_env&) {
        sstring username("fisk");
        sstring password("notter");

        using namespace auth;
        using option = authenticator::option;
        using user_ptr = ::shared_ptr<authenticated_user>;

        auto USERNAME_KEY = authenticator::USERNAME_KEY;
        auto PASSWORD_KEY = authenticator::PASSWORD_KEY;

        // check non-existing user
        return authenticator::get().authenticate({ { USERNAME_KEY, username }, { PASSWORD_KEY, password } }).then_wrapped([](future<user_ptr>&& f) {
            try {
                f.get();
                BOOST_FAIL("should not reach");
            } catch (exceptions::authentication_exception&) {
                // ok
            }
        }).then([=] {
            return authenticator::get().create(username, { { option::PASSWORD, password} }).then([=] {
                return authenticator::get().authenticate({ { USERNAME_KEY, username }, { PASSWORD_KEY, password } }).then([=](user_ptr user) {
                    BOOST_REQUIRE_EQUAL(user->name(), username);
                    BOOST_REQUIRE_EQUAL(user->is_anonymous(), false);
                });
            });
        }).then([=] {
            // check wrong password
            return authenticator::get().authenticate( { {USERNAME_KEY, username}, {PASSWORD_KEY, "hejkotte"}}).then_wrapped([](future<user_ptr>&& f) {
                try {
                    f.get();
                    BOOST_FAIL("should not reach");
                } catch (exceptions::authentication_exception&) {
                    // ok
                }
            });
        }).then([=] {
            // sasl
            auto sasl = authenticator::get().new_sasl_challenge();

            BOOST_REQUIRE_EQUAL(sasl->is_complete(), false);

            bytes b;
            int8_t i = 0;
            b.append(&i, 1);
            b.insert(b.end(), username.begin(), username.end());
            b.append(&i, 1);
            b.insert(b.end(), password.begin(), password.end());

            sasl->evaluate_response(b);
            BOOST_REQUIRE_EQUAL(sasl->is_complete(), true);

            return sasl->get_authenticated_user().then([=](user_ptr user) {
                BOOST_REQUIRE_EQUAL(user->name(), username);
                BOOST_REQUIRE_EQUAL(user->is_anonymous(), false);
            });
        }).then([=] {
            // check deleted user
            return authenticator::get().drop(username).then([=] {
                return authenticator::get().authenticate({ { USERNAME_KEY, username }, { PASSWORD_KEY, password } }).then_wrapped([](future<user_ptr>&& f) {
                    try {
                        f.get();
                        BOOST_FAIL("should not reach");
                    } catch (exceptions::authentication_exception&) {
                        // ok
                    }
                });
            });
        });
    }, cfg);
}

SEASTAR_TEST_CASE(test_cassandra_hash) {
    db::config cfg;
    cfg.authenticator = auth::password_authenticator::PASSWORD_AUTHENTICATOR_NAME;

    return do_with_cql_env([](cql_test_env& env) {
        /**
         * Try to check password against hash from origin.
         * Allow for specific failure if glibc cannot handle the
         * hash algo (i.e. blowfish).
         */

        sstring username("fisk");
        sstring password("cassandra");
        sstring salted_hash("$2a$10$8cz4EZ5v8f/aTZFkNEQafe.z66ZvjOonOpHCApwx0ksWp3aKf.Roq");

        // This is extremely whitebox. We'll just go right ahead and know
        // what the tables etc are called. Oy wei...
        auto f = env.local_qp().process("INSERT into system_auth.credentials (username, salted_hash) values (?, ?)", db::consistency_level::ONE,
                        { username, salted_hash }).discard_result();

        return f.then([=] {
            auto& a = auth::authenticator::get();

            auto USERNAME_KEY = auth::authenticator::USERNAME_KEY;
            auto PASSWORD_KEY = auth::authenticator::PASSWORD_KEY;
            using user_ptr = ::shared_ptr<auth::authenticated_user>;

            // try to verify our user with a cassandra-originated salted_hash
            return a.authenticate({ { USERNAME_KEY, username }, { PASSWORD_KEY, password } }).then_wrapped([](future<user_ptr> f) {
                try {
                    f.get();
                } catch (exceptions::authentication_exception& e) {
                    try {
                        std::rethrow_if_nested(e);
                        BOOST_FAIL(std::string("Unexcepted exception ") + e.what());
                    } catch (std::system_error & e) {
                        bool is_einval = e.code().category() == std::system_category() && e.code().value() == EINVAL;
                        BOOST_WARN_MESSAGE(is_einval, "Could not verify cassandra password hash due to glibc limitation");
                        if (!is_einval) {
                            BOOST_FAIL(std::string("Unexcepted system error ") + e.what());
                        }
                    }
                }
            });
        });
    }, cfg);
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: morebtn.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 11:48:57 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SV_MOREBTN_HXX
#include <morebtn.hxx>
#endif

#ifndef _SV_RD_H
#include <tools/rc.h>
#endif

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

DECLARE_LIST( ImplMoreWindowList, Window* );

struct ImplMoreButtonData
{
    ImplMoreWindowList *mpItemList;
    XubString           maMoreText;
    XubString           maLessText;
};

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

void MoreButton::ImplInit( Window* pParent, WinBits nStyle )
{
    mpMBData     = new ImplMoreButtonData;
    mnDelta      = 0;
    meUnit       = MAP_PIXEL;
    mbState      = FALSE;

    mpMBData->mpItemList = NULL;

    PushButton::ImplInit( pParent, nStyle );

    mpMBData->maMoreText = Button::GetStandardText( BUTTON_MORE );
    mpMBData->maLessText = Button::GetStandardText( BUTTON_LESS );

    SetHelpText( Button::GetStandardHelpText( BUTTON_MORE ) );

    ShowState();

    SetSymbolAlign( SYMBOLALIGN_RIGHT );
    ImplSetSmallSymbol( TRUE );

    if ( ! ( nStyle & ( WB_RIGHT | WB_LEFT ) ) )
    {
        nStyle |= WB_CENTER;
        SetStyle( nStyle );
    }
}

// -----------------------------------------------------------------------
void MoreButton::ShowState()
{
    if ( mbState )
    {
        SetSymbol( SYMBOL_PAGEUP );
        SetText( mpMBData->maLessText );
    }
    else
    {
        SetSymbol( SYMBOL_PAGEDOWN );
        SetText( mpMBData->maMoreText );
    }
}

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

MoreButton::MoreButton( Window* pParent, WinBits nStyle ) :
    PushButton( WINDOW_MOREBUTTON )
{
    ImplInit( pParent, nStyle );
}

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

MoreButton::MoreButton( Window* pParent, const ResId& rResId ) :
    PushButton( WINDOW_MOREBUTTON )
{
    rResId.SetRT( RSC_MOREBUTTON );
    WinBits nStyle = ImplInitRes( rResId );
    ImplInit( pParent, nStyle );
    ImplLoadRes( rResId );

    if ( !(nStyle & WB_HIDE) )
        Show();
}

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

void MoreButton::ImplLoadRes( const ResId& rResId )
{
    PushButton::ImplLoadRes( rResId );

    ULONG nObjMask = ReadLongRes();

    if ( nObjMask & RSC_MOREBUTTON_STATE )
    {
        // Nicht Methode rufen, da Dialog nicht umgeschaltet werden soll
        mbState = (BOOL)ReadShortRes();
        // SetText( GetText() );
        ShowState();
    }
    if ( nObjMask & RSC_MOREBUTTON_MAPUNIT )
        meUnit = (MapUnit)ReadLongRes();
    if ( nObjMask & RSC_MOREBUTTON_DELTA )
        // Groesse fuer Erweitern des Dialogs
        mnDelta = ReadShortRes();
}

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

MoreButton::~MoreButton()
{
    if ( mpMBData->mpItemList )
        delete mpMBData->mpItemList;
    delete mpMBData;
}

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

void MoreButton::Click()
{
    Window*     pParent = GetParent();
    Size        aSize( pParent->GetSizePixel() );
    Window*     pWindow = (mpMBData->mpItemList) ? mpMBData->mpItemList->First() : NULL;
    long        nDeltaPixel = LogicToPixel( Size( 0, mnDelta ), meUnit ).Height();

    // Status aendern
    mbState = !mbState;
    ShowState();

    // Hier den Click-Handler rufen, damit vorher die Controls initialisiert
    // werden koennen
    PushButton::Click();

    // Je nach Status die Fenster updaten
    if ( mbState )
    {
        // Fenster anzeigen
        while ( pWindow )
        {
            pWindow->Show();
            pWindow = mpMBData->mpItemList->Next();
        }

        // Dialogbox anpassen
        Point aPos( pParent->GetPosPixel() );
        Rectangle aDeskRect( pParent->ImplGetFrameWindow()->GetDesktopRectPixel() );

        aSize.Height() += nDeltaPixel;
        if ( (aPos.Y()+aSize.Height()) > aDeskRect.Bottom() )
        {
            aPos.Y() = aDeskRect.Bottom()-aSize.Height();

            if ( aPos.Y() < aDeskRect.Top() )
                aPos.Y() = aDeskRect.Top();

            pParent->SetPosSizePixel( aPos, aSize );
        }
        else
            pParent->SetSizePixel( aSize );
    }
    else
    {
        // Dialogbox anpassen
        aSize.Height() -= nDeltaPixel;
        pParent->SetSizePixel( aSize );

        // Fenster nicht mehr anzeigen
        while ( pWindow )
        {
            pWindow->Hide();
            pWindow = mpMBData->mpItemList->Next();
        }
    }
}

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

void MoreButton::AddWindow( Window* pWindow )
{
    if ( !mpMBData->mpItemList )
        mpMBData->mpItemList = new ImplMoreWindowList( 1024, 16, 16 );

    mpMBData->mpItemList->Insert( pWindow, LIST_APPEND );

    if ( mbState )
        pWindow->Show();
    else
        pWindow->Hide();
}

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

void MoreButton::RemoveWindow( Window* pWindow )
{
    if ( mpMBData->mpItemList )
        mpMBData->mpItemList->Remove( pWindow );
}

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

void MoreButton::SetText( const XubString& rText )
{
    PushButton::SetText( rText );
}

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

XubString MoreButton::GetText() const
{
    return PushButton::GetText();
}

// -----------------------------------------------------------------------
void MoreButton::SetMoreText( const XubString& rText )
{
    if ( mpMBData )
        mpMBData->maMoreText = rText;

    if ( !mbState )
        SetText( rText );
}

// -----------------------------------------------------------------------
XubString MoreButton::GetMoreText() const
{
    if ( mpMBData )
        return mpMBData->maMoreText;
    else
        return PushButton::GetText();
}

// -----------------------------------------------------------------------
void MoreButton::SetLessText( const XubString& rText )
{
    if ( mpMBData )
        mpMBData->maLessText = rText;

    if ( mbState )
        SetText( rText );
}

// -----------------------------------------------------------------------
XubString MoreButton::GetLessText() const
{
    if ( mpMBData )
        return mpMBData->maLessText;
    else
        return PushButton::GetText();
}

<commit_msg>INTEGRATION: CWS warnings01 (1.6.70); FILE MERGED 2005/11/04 16:49:36 pl 1.6.70.1: #i55991# removed warnings for linux/solaris<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: morebtn.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 19:18:29 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SV_MOREBTN_HXX
#include <morebtn.hxx>
#endif

#ifndef _SV_RD_H
#include <tools/rc.h>
#endif

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

DECLARE_LIST( ImplMoreWindowList, Window* )

struct ImplMoreButtonData
{
    ImplMoreWindowList *mpItemList;
    XubString           maMoreText;
    XubString           maLessText;
};

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

void MoreButton::ImplInit( Window* pParent, WinBits nStyle )
{
    mpMBData     = new ImplMoreButtonData;
    mnDelta      = 0;
    meUnit       = MAP_PIXEL;
    mbState      = FALSE;

    mpMBData->mpItemList = NULL;

    PushButton::ImplInit( pParent, nStyle );

    mpMBData->maMoreText = Button::GetStandardText( BUTTON_MORE );
    mpMBData->maLessText = Button::GetStandardText( BUTTON_LESS );

    SetHelpText( Button::GetStandardHelpText( BUTTON_MORE ) );

    ShowState();

    SetSymbolAlign( SYMBOLALIGN_RIGHT );
    ImplSetSmallSymbol( TRUE );

    if ( ! ( nStyle & ( WB_RIGHT | WB_LEFT ) ) )
    {
        nStyle |= WB_CENTER;
        SetStyle( nStyle );
    }
}

// -----------------------------------------------------------------------
void MoreButton::ShowState()
{
    if ( mbState )
    {
        SetSymbol( SYMBOL_PAGEUP );
        SetText( mpMBData->maLessText );
    }
    else
    {
        SetSymbol( SYMBOL_PAGEDOWN );
        SetText( mpMBData->maMoreText );
    }
}

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

MoreButton::MoreButton( Window* pParent, WinBits nStyle ) :
    PushButton( WINDOW_MOREBUTTON )
{
    ImplInit( pParent, nStyle );
}

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

MoreButton::MoreButton( Window* pParent, const ResId& rResId ) :
    PushButton( WINDOW_MOREBUTTON )
{
    rResId.SetRT( RSC_MOREBUTTON );
    WinBits nStyle = ImplInitRes( rResId );
    ImplInit( pParent, nStyle );
    ImplLoadRes( rResId );

    if ( !(nStyle & WB_HIDE) )
        Show();
}

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

void MoreButton::ImplLoadRes( const ResId& rResId )
{
    PushButton::ImplLoadRes( rResId );

    ULONG nObjMask = ReadLongRes();

    if ( nObjMask & RSC_MOREBUTTON_STATE )
    {
        // Nicht Methode rufen, da Dialog nicht umgeschaltet werden soll
        mbState = (BOOL)ReadShortRes();
        // SetText( GetText() );
        ShowState();
    }
    if ( nObjMask & RSC_MOREBUTTON_MAPUNIT )
        meUnit = (MapUnit)ReadLongRes();
    if ( nObjMask & RSC_MOREBUTTON_DELTA )
        // Groesse fuer Erweitern des Dialogs
        mnDelta = ReadShortRes();
}

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

MoreButton::~MoreButton()
{
    if ( mpMBData->mpItemList )
        delete mpMBData->mpItemList;
    delete mpMBData;
}

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

void MoreButton::Click()
{
    Window*     pParent = GetParent();
    Size        aSize( pParent->GetSizePixel() );
    Window*     pWindow = (mpMBData->mpItemList) ? mpMBData->mpItemList->First() : NULL;
    long        nDeltaPixel = LogicToPixel( Size( 0, mnDelta ), meUnit ).Height();

    // Status aendern
    mbState = !mbState;
    ShowState();

    // Hier den Click-Handler rufen, damit vorher die Controls initialisiert
    // werden koennen
    PushButton::Click();

    // Je nach Status die Fenster updaten
    if ( mbState )
    {
        // Fenster anzeigen
        while ( pWindow )
        {
            pWindow->Show();
            pWindow = mpMBData->mpItemList->Next();
        }

        // Dialogbox anpassen
        Point aPos( pParent->GetPosPixel() );
        Rectangle aDeskRect( pParent->ImplGetFrameWindow()->GetDesktopRectPixel() );

        aSize.Height() += nDeltaPixel;
        if ( (aPos.Y()+aSize.Height()) > aDeskRect.Bottom() )
        {
            aPos.Y() = aDeskRect.Bottom()-aSize.Height();

            if ( aPos.Y() < aDeskRect.Top() )
                aPos.Y() = aDeskRect.Top();

            pParent->SetPosSizePixel( aPos, aSize );
        }
        else
            pParent->SetSizePixel( aSize );
    }
    else
    {
        // Dialogbox anpassen
        aSize.Height() -= nDeltaPixel;
        pParent->SetSizePixel( aSize );

        // Fenster nicht mehr anzeigen
        while ( pWindow )
        {
            pWindow->Hide();
            pWindow = mpMBData->mpItemList->Next();
        }
    }
}

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

void MoreButton::AddWindow( Window* pWindow )
{
    if ( !mpMBData->mpItemList )
        mpMBData->mpItemList = new ImplMoreWindowList( 1024, 16, 16 );

    mpMBData->mpItemList->Insert( pWindow, LIST_APPEND );

    if ( mbState )
        pWindow->Show();
    else
        pWindow->Hide();
}

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

void MoreButton::RemoveWindow( Window* pWindow )
{
    if ( mpMBData->mpItemList )
        mpMBData->mpItemList->Remove( pWindow );
}

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

void MoreButton::SetText( const XubString& rText )
{
    PushButton::SetText( rText );
}

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

XubString MoreButton::GetText() const
{
    return PushButton::GetText();
}

// -----------------------------------------------------------------------
void MoreButton::SetMoreText( const XubString& rText )
{
    if ( mpMBData )
        mpMBData->maMoreText = rText;

    if ( !mbState )
        SetText( rText );
}

// -----------------------------------------------------------------------
XubString MoreButton::GetMoreText() const
{
    if ( mpMBData )
        return mpMBData->maMoreText;
    else
        return PushButton::GetText();
}

// -----------------------------------------------------------------------
void MoreButton::SetLessText( const XubString& rText )
{
    if ( mpMBData )
        mpMBData->maLessText = rText;

    if ( mbState )
        SetText( rText );
}

// -----------------------------------------------------------------------
XubString MoreButton::GetLessText() const
{
    if ( mpMBData )
        return mpMBData->maLessText;
    else
        return PushButton::GetText();
}

<|endoftext|>


<commit_before>/*
 * https://github.com/parcon/arl_ardrone_examples
 */

#include "ros/ros.h"
#include "std_msgs/String.h"
#include "std_msgs/Empty.h"

#define LOOP_RATE (50)
double current_time() {
    return ros::Time::now().toSec();
}

int main(int argc, char **argv) {

    int takeoff_time = 3;
    double fly_time = 1.0;
    double land_time = 3.0;

    ros::init(argc, argv, "controller");

    ros::NodeHandle n;

    ros::Publisher pub_takeoff = n.advertise<std_msgs::Empty>("/ardrone/takeoff", 1);
    ros::Publisher pub_land = n.advertise<std_msgs::Empty>("/ardrone/land", 1);
    ros::Rate loop_rate(LOOP_RATE);

    int i = 0;
    int j = 0;
    printf("Enter a key to start: ");
    getchar();
    while (ros::ok()) {

        ROS_INFO("takeoff %d", (int)takeoff_time*LOOP_RATE);
        for(; i < takeoff_time*LOOP_RATE; i++){

            std_msgs::Empty empty_msg;
            pub_takeoff.publish(empty_msg);

            ros::spinOnce();
            loop_rate.sleep();
        }

        for(; j < (takeoff_time+fly_time+land_time)*LOOP_RATE; j++){

            std_msgs::Empty empty_msg;
            pub_land.publish(empty_msg);

            ros::spinOnce();
            loop_rate.sleep();
        }
    }

    return 0;
}<commit_msg>navdata<commit_after>/*
 * https://github.com/parcon/arl_ardrone_examples
 */

#include "ros/ros.h"
#include "std_msgs/String.h"
#include "std_msgs/Empty.h"
#include "ardrone_autonomy/Navdata.h"

#define LOOP_RATE (50)
unsigned int state;

int altitude;

double current_time() {
    return ros::Time::now().toSec();
}

void navdataCallback(const ardrone_autonomy::Navdata::ConstPtr& msg)
{
    state = msg->state;
    altitude = msg->altd;
}

int main(int argc, char **argv) {

    int takeoff_time = 3;
    double fly_time = 1.0;
    double land_time = 3.0;

    ros::init(argc, argv, "controller");

    ros::NodeHandle n;

    ros::Publisher pub_takeoff = n.advertise<std_msgs::Empty>("/ardrone/takeoff", 1);
    ros::Publisher pub_land = n.advertise<std_msgs::Empty>("/ardrone/land", 1);

    ros::Subscriber sub = n.subscribe("ardrone/navdata", 1000, navdataCallback);

    ros::Rate loop_rate(LOOP_RATE);

    int i = 0;
    int j = 0;
    printf("Enter any key to start: ");
    getchar();

    ROS_INFO("takeoff %d", (int)takeoff_time*LOOP_RATE);
    for(; i < takeoff_time*LOOP_RATE; i++){

        std_msgs::Empty empty_msg;
        pub_takeoff.publish(empty_msg);

        ros::spinOnce();
        loop_rate.sleep();
    }

    sub.shutdown();

    for(; j < (takeoff_time+fly_time+land_time)*LOOP_RATE; j++){

        std_msgs::Empty empty_msg;
        pub_land.publish(empty_msg);

        ros::spinOnce();
        loop_rate.sleep();
    }
    printf("Tap to exit: ");
    getchar();

    return 0;
}<|endoftext|>