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

#include "config.h"

#include "base/compiler_specific.h"

MSVC_PUSH_WARNING_LEVEL(0);
#include "ContextMenu.h"
#include "Document.h"
#include "DocumentLoader.h"
#include "Editor.h"
#include "EventHandler.h"
#include "FrameLoader.h"
#include "FrameView.h"
#include "HitTestResult.h"
#include "HTMLMediaElement.h"
#include "HTMLNames.h"
#include "KURL.h"
#include "Widget.h"
MSVC_POP_WARNING();
#undef LOG

#include "webkit/glue/context_menu_client_impl.h"

#include "base/string_util.h"
#include "webkit/api/public/WebURL.h"
#include "webkit/api/public/WebURLResponse.h"
#include "webkit/glue/context_menu.h"
#include "webkit/glue/glue_util.h"
#include "webkit/glue/webdatasource_impl.h"
#include "webkit/glue/webview_impl.h"

#include "base/word_iterator.h"

using WebKit::WebDataSource;

namespace {

// Helper function to determine whether text is a single word or a sentence.
bool IsASingleWord(const std::wstring& text) {
  WordIterator iter(text, WordIterator::BREAK_WORD);
  int word_count = 0;
  if (!iter.Init()) return false;
  while (iter.Advance()) {
    if (iter.IsWord()) {
      word_count++;
      if (word_count > 1) // More than one word.
        return false;
    }
  }

  // Check for 0 words.
  if (!word_count)
    return false;

  // Has a single word.
  return true;
}

// Helper function to get misspelled word on which context menu
// is to be evolked. This function also sets the word on which context menu
// has been evoked to be the selected word, as required. This function changes
// the selection only when there were no selected characters.
std::wstring GetMisspelledWord(const WebCore::ContextMenu* default_menu,
                               WebCore::Frame* selected_frame) {
  std::wstring misspelled_word_string;

  // First select from selectedText to check for multiple word selection.
  misspelled_word_string = CollapseWhitespace(
      webkit_glue::StringToStdWString(selected_frame->selectedText()),
      false);

  // If some texts were already selected, we don't change the selection.
  if (!misspelled_word_string.empty()) {
    // Don't provide suggestions for multiple words.
    if (!IsASingleWord(misspelled_word_string))
      return L"";
    else
      return misspelled_word_string;
  }

  WebCore::HitTestResult hit_test_result = selected_frame->eventHandler()->
      hitTestResultAtPoint(default_menu->hitTestResult().point(), true);
  WebCore::Node* inner_node = hit_test_result.innerNode();
  WebCore::VisiblePosition pos(inner_node->renderer()->positionForPoint(
      hit_test_result.localPoint()));

  WebCore::VisibleSelection selection;
  if (pos.isNotNull()) {
    selection = WebCore::VisibleSelection(pos);
    selection.expandUsingGranularity(WebCore::WordGranularity);
  }

  if (selection.isRange()) {
    selected_frame->setSelectionGranularity(WebCore::WordGranularity);
  }

  if (selected_frame->shouldChangeSelection(selection))
    selected_frame->selection()->setSelection(selection);

  misspelled_word_string = CollapseWhitespace(
      webkit_glue::StringToStdWString(selected_frame->selectedText()),
                                      false);

  // If misspelled word is empty, then that portion should not be selected.
  // Set the selection to that position only, and do not expand.
  if (misspelled_word_string.empty()) {
    selection = WebCore::VisibleSelection(pos);
    selected_frame->selection()->setSelection(selection);
  }

  return misspelled_word_string;
}

}  // namespace

ContextMenuClientImpl::~ContextMenuClientImpl() {
}

void ContextMenuClientImpl::contextMenuDestroyed() {
  delete this;
}

// Figure out the URL of a page or subframe. Returns |page_type| as the type,
// which indicates page or subframe, or ContextNodeType::NONE if the URL could not
// be determined for some reason.
static ContextNodeType GetTypeAndURLFromFrame(
    WebCore::Frame* frame,
    GURL* url,
    ContextNodeType page_node_type) {
  ContextNodeType node_type;
  if (frame) {
    WebCore::DocumentLoader* dl = frame->loader()->documentLoader();
    if (dl) {
      WebDataSource* ds = WebDataSourceImpl::FromLoader(dl);
      if (ds) {
        node_type = page_node_type;
        *url = ds->hasUnreachableURL() ? ds->unreachableURL()
                                       : ds->request().url();
      }
    }
  }
  return node_type;
}

WebCore::PlatformMenuDescription
    ContextMenuClientImpl::getCustomMenuFromDefaultItems(
        WebCore::ContextMenu* default_menu) {
  // Displaying the context menu in this function is a big hack as we don't
  // have context, i.e. whether this is being invoked via a script or in
  // response to user input (Mouse event WM_RBUTTONDOWN,
  // Keyboard events KeyVK_APPS, Shift+F10). Check if this is being invoked
  // in response to the above input events before popping up the context menu.
  if (!webview_->context_menu_allowed())
    return NULL;

  WebCore::HitTestResult r = default_menu->hitTestResult();
  WebCore::Frame* selected_frame = r.innerNonSharedNode()->document()->frame();

  WebCore::IntPoint menu_point =
      selected_frame->view()->contentsToWindow(r.point());

  ContextNodeType node_type;

  // Links, Images, Media tags, and Image/Media-Links take preference over
  // all else.
  WebCore::KURL link_url = r.absoluteLinkURL();
  if (!link_url.isEmpty()) {
    node_type.type |= ContextNodeType::LINK;
  }

  WebCore::KURL src_url;

  ContextMenuMediaParams media_params;

  if (!r.absoluteImageURL().isEmpty()) {
    src_url = r.absoluteImageURL();
    node_type.type |= ContextNodeType::IMAGE;
  } else if (!r.absoluteMediaURL().isEmpty()) {
    src_url = r.absoluteMediaURL();

    // We know that if absoluteMediaURL() is not empty, then this is a media
    // element.
    WebCore::HTMLMediaElement* media_element =
        static_cast<WebCore::HTMLMediaElement*>(r.innerNonSharedNode());
    if (media_element->hasTagName(WebCore::HTMLNames::videoTag)) {
      node_type.type |= ContextNodeType::VIDEO;
    } else if (media_element->hasTagName(WebCore::HTMLNames::audioTag)) {
      node_type.type |= ContextNodeType::AUDIO;
    }

    if (media_element->paused()) {
      media_params.player_state |= ContextMenuMediaParams::PAUSED;
    }
    if (media_element->muted()) {
      media_params.player_state |= ContextMenuMediaParams::MUTED;
    }
    if (media_element->loop()) {
      media_params.player_state |= ContextMenuMediaParams::LOOP;
    }
    if (media_element->supportsSave()) {
      media_params.player_state |= ContextMenuMediaParams::CAN_SAVE;
    }
    // TODO(ajwong): Report error states in the media player.
  }

  // If it's not a link, an image, a media element, or an image/media link,
  // show a selection menu or a more generic page menu.
  std::wstring selection_text_string;
  std::wstring misspelled_word_string;
  GURL frame_url;
  GURL page_url;
  std::string security_info;

  std::string frame_charset = WideToASCII(
      webkit_glue::StringToStdWString(selected_frame->loader()->encoding()));
  // Send the frame and page URLs in any case.
  ContextNodeType frame_node = ContextNodeType(ContextNodeType::NONE);
  ContextNodeType page_node =
      GetTypeAndURLFromFrame(webview_->main_frame()->frame(),
                             &page_url,
                             ContextNodeType(ContextNodeType::PAGE));
  if (selected_frame != webview_->main_frame()->frame()) {
    frame_node =
      GetTypeAndURLFromFrame(selected_frame,
          &frame_url,
          ContextNodeType(ContextNodeType::FRAME));
  }

  if (r.isSelected()) {
    node_type.type |= ContextNodeType::SELECTION;
    selection_text_string = CollapseWhitespace(
      webkit_glue::StringToStdWString(selected_frame->selectedText()),
      false);
  }

  if (r.isContentEditable()) {
    node_type.type |= ContextNodeType::EDITABLE;
    if (webview_->GetFocusedWebCoreFrame()->editor()->
        isContinuousSpellCheckingEnabled()) {
      misspelled_word_string = GetMisspelledWord(default_menu,
                                                 selected_frame);
    }
  }

  if (node_type.type == ContextNodeType::NONE) {
    if (selected_frame != webview_->main_frame()->frame()) {
      node_type = frame_node;
    } else {
      node_type = page_node;
    }
  }

  // Now retrieve the security info.
  WebCore::DocumentLoader* dl = selected_frame->loader()->documentLoader();
  WebDataSource* ds = WebDataSourceImpl::FromLoader(dl);
  if (ds)
    security_info = ds->response().securityInfo();

  int edit_flags = ContextNodeType::CAN_DO_NONE;
  if (webview_->GetFocusedWebCoreFrame()->editor()->canUndo())
    edit_flags |= ContextNodeType::CAN_UNDO;
  if (webview_->GetFocusedWebCoreFrame()->editor()->canRedo())
    edit_flags |= ContextNodeType::CAN_REDO;
  if (webview_->GetFocusedWebCoreFrame()->editor()->canCut())
    edit_flags |= ContextNodeType::CAN_CUT;
  if (webview_->GetFocusedWebCoreFrame()->editor()->canCopy())
    edit_flags |= ContextNodeType::CAN_COPY;
  if (webview_->GetFocusedWebCoreFrame()->editor()->canPaste())
    edit_flags |= ContextNodeType::CAN_PASTE;
  if (webview_->GetFocusedWebCoreFrame()->editor()->canDelete())
    edit_flags |= ContextNodeType::CAN_DELETE;
  // We can always select all...
  edit_flags |= ContextNodeType::CAN_SELECT_ALL;

  WebViewDelegate* d = webview_->delegate();
  if (d) {
    d->ShowContextMenu(webview_,
                       node_type,
                       menu_point.x(),
                       menu_point.y(),
                       webkit_glue::KURLToGURL(link_url),
                       webkit_glue::KURLToGURL(src_url),
                       page_url,
                       frame_url,
                       media_params,
                       selection_text_string,
                       misspelled_word_string,
                       edit_flags,
                       security_info,
                       frame_charset);
  }
  return NULL;
}

void ContextMenuClientImpl::contextMenuItemSelected(
    WebCore::ContextMenuItem*, const WebCore::ContextMenu*) {
}

void ContextMenuClientImpl::downloadURL(const WebCore::KURL&) {
}

void ContextMenuClientImpl::copyImageToClipboard(const WebCore::HitTestResult&) {
}

void ContextMenuClientImpl::searchWithGoogle(const WebCore::Frame*) {
}

void ContextMenuClientImpl::lookUpInDictionary(WebCore::Frame*) {
}

void ContextMenuClientImpl::speak(const WebCore::String&) {
}

bool ContextMenuClientImpl::isSpeaking() {
  return false;
}

void ContextMenuClientImpl::stopSpeaking() {
}

bool ContextMenuClientImpl::shouldIncludeInspectElementItem() {
    return false;  // TODO(jackson): Eventually include the inspector context menu item
}

#if defined(OS_MACOSX)
void ContextMenuClientImpl::searchWithSpotlight() {
  // TODO(pinkerton): write this
}
#endif
<commit_msg>Disable playback controls if audio/video element has errored.<commit_after>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "config.h"

#include "base/compiler_specific.h"

MSVC_PUSH_WARNING_LEVEL(0);
#include "ContextMenu.h"
#include "Document.h"
#include "DocumentLoader.h"
#include "Editor.h"
#include "EventHandler.h"
#include "FrameLoader.h"
#include "FrameView.h"
#include "HitTestResult.h"
#include "HTMLMediaElement.h"
#include "HTMLNames.h"
#include "KURL.h"
#include "MediaError.h"
#include "Widget.h"
MSVC_POP_WARNING();
#undef LOG

#include "webkit/glue/context_menu_client_impl.h"

#include "base/string_util.h"
#include "webkit/api/public/WebURL.h"
#include "webkit/api/public/WebURLResponse.h"
#include "webkit/glue/context_menu.h"
#include "webkit/glue/glue_util.h"
#include "webkit/glue/webdatasource_impl.h"
#include "webkit/glue/webview_impl.h"

#include "base/word_iterator.h"

using WebKit::WebDataSource;

namespace {

// Helper function to determine whether text is a single word or a sentence.
bool IsASingleWord(const std::wstring& text) {
  WordIterator iter(text, WordIterator::BREAK_WORD);
  int word_count = 0;
  if (!iter.Init()) return false;
  while (iter.Advance()) {
    if (iter.IsWord()) {
      word_count++;
      if (word_count > 1) // More than one word.
        return false;
    }
  }

  // Check for 0 words.
  if (!word_count)
    return false;

  // Has a single word.
  return true;
}

// Helper function to get misspelled word on which context menu
// is to be evolked. This function also sets the word on which context menu
// has been evoked to be the selected word, as required. This function changes
// the selection only when there were no selected characters.
std::wstring GetMisspelledWord(const WebCore::ContextMenu* default_menu,
                               WebCore::Frame* selected_frame) {
  std::wstring misspelled_word_string;

  // First select from selectedText to check for multiple word selection.
  misspelled_word_string = CollapseWhitespace(
      webkit_glue::StringToStdWString(selected_frame->selectedText()),
      false);

  // If some texts were already selected, we don't change the selection.
  if (!misspelled_word_string.empty()) {
    // Don't provide suggestions for multiple words.
    if (!IsASingleWord(misspelled_word_string))
      return L"";
    else
      return misspelled_word_string;
  }

  WebCore::HitTestResult hit_test_result = selected_frame->eventHandler()->
      hitTestResultAtPoint(default_menu->hitTestResult().point(), true);
  WebCore::Node* inner_node = hit_test_result.innerNode();
  WebCore::VisiblePosition pos(inner_node->renderer()->positionForPoint(
      hit_test_result.localPoint()));

  WebCore::VisibleSelection selection;
  if (pos.isNotNull()) {
    selection = WebCore::VisibleSelection(pos);
    selection.expandUsingGranularity(WebCore::WordGranularity);
  }

  if (selection.isRange()) {
    selected_frame->setSelectionGranularity(WebCore::WordGranularity);
  }

  if (selected_frame->shouldChangeSelection(selection))
    selected_frame->selection()->setSelection(selection);

  misspelled_word_string = CollapseWhitespace(
      webkit_glue::StringToStdWString(selected_frame->selectedText()),
                                      false);

  // If misspelled word is empty, then that portion should not be selected.
  // Set the selection to that position only, and do not expand.
  if (misspelled_word_string.empty()) {
    selection = WebCore::VisibleSelection(pos);
    selected_frame->selection()->setSelection(selection);
  }

  return misspelled_word_string;
}

}  // namespace

ContextMenuClientImpl::~ContextMenuClientImpl() {
}

void ContextMenuClientImpl::contextMenuDestroyed() {
  delete this;
}

// Figure out the URL of a page or subframe. Returns |page_type| as the type,
// which indicates page or subframe, or ContextNodeType::NONE if the URL could not
// be determined for some reason.
static ContextNodeType GetTypeAndURLFromFrame(
    WebCore::Frame* frame,
    GURL* url,
    ContextNodeType page_node_type) {
  ContextNodeType node_type;
  if (frame) {
    WebCore::DocumentLoader* dl = frame->loader()->documentLoader();
    if (dl) {
      WebDataSource* ds = WebDataSourceImpl::FromLoader(dl);
      if (ds) {
        node_type = page_node_type;
        *url = ds->hasUnreachableURL() ? ds->unreachableURL()
                                       : ds->request().url();
      }
    }
  }
  return node_type;
}

WebCore::PlatformMenuDescription
    ContextMenuClientImpl::getCustomMenuFromDefaultItems(
        WebCore::ContextMenu* default_menu) {
  // Displaying the context menu in this function is a big hack as we don't
  // have context, i.e. whether this is being invoked via a script or in
  // response to user input (Mouse event WM_RBUTTONDOWN,
  // Keyboard events KeyVK_APPS, Shift+F10). Check if this is being invoked
  // in response to the above input events before popping up the context menu.
  if (!webview_->context_menu_allowed())
    return NULL;

  WebCore::HitTestResult r = default_menu->hitTestResult();
  WebCore::Frame* selected_frame = r.innerNonSharedNode()->document()->frame();

  WebCore::IntPoint menu_point =
      selected_frame->view()->contentsToWindow(r.point());

  ContextNodeType node_type;

  // Links, Images, Media tags, and Image/Media-Links take preference over
  // all else.
  WebCore::KURL link_url = r.absoluteLinkURL();
  if (!link_url.isEmpty()) {
    node_type.type |= ContextNodeType::LINK;
  }

  WebCore::KURL src_url;

  ContextMenuMediaParams media_params;

  if (!r.absoluteImageURL().isEmpty()) {
    src_url = r.absoluteImageURL();
    node_type.type |= ContextNodeType::IMAGE;
  } else if (!r.absoluteMediaURL().isEmpty()) {
    src_url = r.absoluteMediaURL();

    // We know that if absoluteMediaURL() is not empty, then this is a media
    // element.
    WebCore::HTMLMediaElement* media_element =
        static_cast<WebCore::HTMLMediaElement*>(r.innerNonSharedNode());
    if (media_element->hasTagName(WebCore::HTMLNames::videoTag)) {
      node_type.type |= ContextNodeType::VIDEO;
    } else if (media_element->hasTagName(WebCore::HTMLNames::audioTag)) {
      node_type.type |= ContextNodeType::AUDIO;
    }

    if (media_element->error()) {
      media_params.player_state |= ContextMenuMediaParams::IN_ERROR;
    }
    if (media_element->paused()) {
      media_params.player_state |= ContextMenuMediaParams::PAUSED;
    }
    if (media_element->muted()) {
      media_params.player_state |= ContextMenuMediaParams::MUTED;
    }
    if (media_element->loop()) {
      media_params.player_state |= ContextMenuMediaParams::LOOP;
    }
    if (media_element->supportsSave()) {
      media_params.player_state |= ContextMenuMediaParams::CAN_SAVE;
    }
  }

  // If it's not a link, an image, a media element, or an image/media link,
  // show a selection menu or a more generic page menu.
  std::wstring selection_text_string;
  std::wstring misspelled_word_string;
  GURL frame_url;
  GURL page_url;
  std::string security_info;

  std::string frame_charset = WideToASCII(
      webkit_glue::StringToStdWString(selected_frame->loader()->encoding()));
  // Send the frame and page URLs in any case.
  ContextNodeType frame_node = ContextNodeType(ContextNodeType::NONE);
  ContextNodeType page_node =
      GetTypeAndURLFromFrame(webview_->main_frame()->frame(),
                             &page_url,
                             ContextNodeType(ContextNodeType::PAGE));
  if (selected_frame != webview_->main_frame()->frame()) {
    frame_node =
      GetTypeAndURLFromFrame(selected_frame,
          &frame_url,
          ContextNodeType(ContextNodeType::FRAME));
  }

  if (r.isSelected()) {
    node_type.type |= ContextNodeType::SELECTION;
    selection_text_string = CollapseWhitespace(
      webkit_glue::StringToStdWString(selected_frame->selectedText()),
      false);
  }

  if (r.isContentEditable()) {
    node_type.type |= ContextNodeType::EDITABLE;
    if (webview_->GetFocusedWebCoreFrame()->editor()->
        isContinuousSpellCheckingEnabled()) {
      misspelled_word_string = GetMisspelledWord(default_menu,
                                                 selected_frame);
    }
  }

  if (node_type.type == ContextNodeType::NONE) {
    if (selected_frame != webview_->main_frame()->frame()) {
      node_type = frame_node;
    } else {
      node_type = page_node;
    }
  }

  // Now retrieve the security info.
  WebCore::DocumentLoader* dl = selected_frame->loader()->documentLoader();
  WebDataSource* ds = WebDataSourceImpl::FromLoader(dl);
  if (ds)
    security_info = ds->response().securityInfo();

  int edit_flags = ContextNodeType::CAN_DO_NONE;
  if (webview_->GetFocusedWebCoreFrame()->editor()->canUndo())
    edit_flags |= ContextNodeType::CAN_UNDO;
  if (webview_->GetFocusedWebCoreFrame()->editor()->canRedo())
    edit_flags |= ContextNodeType::CAN_REDO;
  if (webview_->GetFocusedWebCoreFrame()->editor()->canCut())
    edit_flags |= ContextNodeType::CAN_CUT;
  if (webview_->GetFocusedWebCoreFrame()->editor()->canCopy())
    edit_flags |= ContextNodeType::CAN_COPY;
  if (webview_->GetFocusedWebCoreFrame()->editor()->canPaste())
    edit_flags |= ContextNodeType::CAN_PASTE;
  if (webview_->GetFocusedWebCoreFrame()->editor()->canDelete())
    edit_flags |= ContextNodeType::CAN_DELETE;
  // We can always select all...
  edit_flags |= ContextNodeType::CAN_SELECT_ALL;

  WebViewDelegate* d = webview_->delegate();
  if (d) {
    d->ShowContextMenu(webview_,
                       node_type,
                       menu_point.x(),
                       menu_point.y(),
                       webkit_glue::KURLToGURL(link_url),
                       webkit_glue::KURLToGURL(src_url),
                       page_url,
                       frame_url,
                       media_params,
                       selection_text_string,
                       misspelled_word_string,
                       edit_flags,
                       security_info,
                       frame_charset);
  }
  return NULL;
}

void ContextMenuClientImpl::contextMenuItemSelected(
    WebCore::ContextMenuItem*, const WebCore::ContextMenu*) {
}

void ContextMenuClientImpl::downloadURL(const WebCore::KURL&) {
}

void ContextMenuClientImpl::copyImageToClipboard(const WebCore::HitTestResult&) {
}

void ContextMenuClientImpl::searchWithGoogle(const WebCore::Frame*) {
}

void ContextMenuClientImpl::lookUpInDictionary(WebCore::Frame*) {
}

void ContextMenuClientImpl::speak(const WebCore::String&) {
}

bool ContextMenuClientImpl::isSpeaking() {
  return false;
}

void ContextMenuClientImpl::stopSpeaking() {
}

bool ContextMenuClientImpl::shouldIncludeInspectElementItem() {
    return false;  // TODO(jackson): Eventually include the inspector context menu item
}

#if defined(OS_MACOSX)
void ContextMenuClientImpl::searchWithSpotlight() {
  // TODO(pinkerton): write this
}
#endif
<|endoftext|>


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

#include <string>

#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "net/base/escape.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/WebKit/WebKit/chromium/public/WebData.h"
#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/WebKit/chromium/public/WebInputEvent.h"
#include "third_party/WebKit/WebKit/chromium/public/WebScriptSource.h"
#include "third_party/WebKit/WebKit/chromium/public/WebView.h"
#include "webkit/tools/test_shell/test_shell.h"
#include "webkit/tools/test_shell/test_shell_test.h"

using WebKit::WebFrame;
using WebKit::WebScriptSource;
using WebKit::WebString;

#if defined(OS_WIN)
#define TEST_PLUGIN_NAME "npapi_test_plugin.dll"
#elif defined(OS_MACOSX)
#define TEST_PLUGIN_NAME "npapi_test_plugin.plugin"
#elif defined(OS_POSIX)
#define TEST_PLUGIN_NAME "libnpapi_test_plugin.so"
#endif

#if defined(OS_MACOSX)
#define TEST_PLUGIN_DIRECTORY "PlugIns"
#else
#define TEST_PLUGIN_DIRECTORY "plugins"
#endif

// Ignore these until 64-bit plugin build is fixed. http://crbug.com/18337
#if !defined(ARCH_CPU_64_BITS)
// Provides functionality for creating plugin tests.
class PluginTest : public TestShellTest {
 public:
  PluginTest() {
    FilePath executable_directory;
    PathService::Get(base::DIR_EXE, &executable_directory);
    plugin_src_ = executable_directory.AppendASCII(TEST_PLUGIN_NAME);
    CHECK(file_util::PathExists(plugin_src_));

    plugin_file_path_ = executable_directory.AppendASCII(TEST_PLUGIN_DIRECTORY);
    file_util::CreateDirectory(plugin_file_path_);

    plugin_file_path_ = plugin_file_path_.AppendASCII(TEST_PLUGIN_NAME);
  }

  void CopyTestPlugin() {
    // On Linux, we need to delete before copying because if the plugin is a
    // hard link, the copy will fail.
    DeleteTestPlugin();
    ASSERT_TRUE(file_util::CopyDirectory(plugin_src_, plugin_file_path_, true));
  }

  void DeleteTestPlugin() {
    file_util::Delete(plugin_file_path_, true);
  }

  virtual void SetUp() {
    CopyTestPlugin();
    TestShellTest::SetUp();
  }

  virtual void TearDown() {
    DeleteTestPlugin();
    TestShellTest::TearDown();
  }

  FilePath plugin_src_;
  FilePath plugin_file_path_;
};

// Tests navigator.plugins.refresh() works.
TEST_F(PluginTest, Refresh) {
  std::string html = "\

Test running....
\
      \
      ";

  WebScriptSource call_check(
      WebString::fromUTF8("check();"));
  WebScriptSource refresh(
      WebString::fromUTF8("navigator.plugins.refresh(false)"));

  // Remove any leftover from previous tests if they exist.  We must also
  // refresh WebKit's plugin cache since it might have had an entry for the
  // test plugin from a previous test.
  DeleteTestPlugin();
  ASSERT_FALSE(file_util::PathExists(plugin_file_path_));
  test_shell_->webView()->mainFrame()->executeScript(refresh);

  test_shell_->webView()->mainFrame()->loadHTMLString(
      html, GURL("about:blank"));
  test_shell_->WaitTestFinished();

  std::string text;
  test_shell_->webView()->mainFrame()->executeScript(call_check);
  text = test_shell_->webView()->mainFrame()->contentAsText(10000).utf8();
  ASSERT_EQ(text, "FAIL");

  CopyTestPlugin();

  test_shell_->webView()->mainFrame()->executeScript(refresh);
  test_shell_->webView()->mainFrame()->executeScript(call_check);
  text = test_shell_->webView()->mainFrame()->contentAsText(10000).utf8();
  ASSERT_EQ(text, "DONE");
}

// Tests that if a frame is deleted as a result of calling NPP_HandleEvent, we
// don't crash.
TEST_F(PluginTest, DeleteFrameDuringEvent) {
  FilePath test_html = data_dir_;
  test_html = test_html.AppendASCII("plugins");
  test_html = test_html.AppendASCII("delete_frame.html");
  test_shell_->LoadFile(test_html);
  test_shell_->WaitTestFinished();

  WebKit::WebMouseEvent input;
  input.button = WebKit::WebMouseEvent::ButtonLeft;
  input.x = 50;
  input.y = 50;
  input.type = WebKit::WebInputEvent::MouseUp;
  test_shell_->webView()->handleInputEvent(input);

  // No crash means we passed.
}

#if defined(OS_WIN)
BOOL CALLBACK EnumChildProc(HWND hwnd, LPARAM lparam) {
  HWND* plugin_hwnd = reinterpret_cast<HWND*>(lparam);
  if (*plugin_hwnd) {
    // More than one child window found, unexpected.
    plugin_hwnd = NULL;
    return FALSE;
  }
  *plugin_hwnd = hwnd;
  return TRUE;
}

// Tests that hiding/showing the parent frame hides/shows the plugin.
TEST_F(PluginTest, PluginVisibilty) {
  FilePath test_html = data_dir_;
  test_html = test_html.AppendASCII("plugins");
  test_html = test_html.AppendASCII("plugin_visibility.html");
  test_shell_->LoadFile(test_html);
  test_shell_->WaitTestFinished();

  WebFrame* main_frame = test_shell_->webView()->mainFrame();
  HWND frame_hwnd = test_shell_->webViewWnd();
  HWND plugin_hwnd = NULL;
  EnumChildWindows(frame_hwnd, EnumChildProc,
      reinterpret_cast<LPARAM>(&plugin_hwnd));
  ASSERT_TRUE(plugin_hwnd != NULL);
  ASSERT_FALSE(IsWindowVisible(plugin_hwnd));

  main_frame->executeScript(WebString::fromUTF8("showPlugin(true)"));
  ASSERT_TRUE(IsWindowVisible(plugin_hwnd));

  main_frame->executeScript(WebString::fromUTF8("showFrame(false)"));
  ASSERT_FALSE(IsWindowVisible(plugin_hwnd));

  main_frame->executeScript(WebString::fromUTF8("showFrame(true)"));
  ASSERT_TRUE(IsWindowVisible(plugin_hwnd));
}
#endif
#endif //!ARCH_CPU_64_BITS
<commit_msg>Disable failing test on Linux.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <string>

#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "net/base/escape.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/WebKit/WebKit/chromium/public/WebData.h"
#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/WebKit/chromium/public/WebInputEvent.h"
#include "third_party/WebKit/WebKit/chromium/public/WebScriptSource.h"
#include "third_party/WebKit/WebKit/chromium/public/WebView.h"
#include "webkit/tools/test_shell/test_shell.h"
#include "webkit/tools/test_shell/test_shell_test.h"

using WebKit::WebFrame;
using WebKit::WebScriptSource;
using WebKit::WebString;

#if defined(OS_WIN)
#define TEST_PLUGIN_NAME "npapi_test_plugin.dll"
#elif defined(OS_MACOSX)
#define TEST_PLUGIN_NAME "npapi_test_plugin.plugin"
#elif defined(OS_POSIX)
#define TEST_PLUGIN_NAME "libnpapi_test_plugin.so"
#endif

#if defined(OS_MACOSX)
#define TEST_PLUGIN_DIRECTORY "PlugIns"
#else
#define TEST_PLUGIN_DIRECTORY "plugins"
#endif

// Ignore these until 64-bit plugin build is fixed. http://crbug.com/18337
#if !defined(ARCH_CPU_64_BITS)
// Provides functionality for creating plugin tests.
class PluginTest : public TestShellTest {
 public:
  PluginTest() {
    FilePath executable_directory;
    PathService::Get(base::DIR_EXE, &executable_directory);
    plugin_src_ = executable_directory.AppendASCII(TEST_PLUGIN_NAME);
    CHECK(file_util::PathExists(plugin_src_));

    plugin_file_path_ = executable_directory.AppendASCII(TEST_PLUGIN_DIRECTORY);
    file_util::CreateDirectory(plugin_file_path_);

    plugin_file_path_ = plugin_file_path_.AppendASCII(TEST_PLUGIN_NAME);
  }

  void CopyTestPlugin() {
    // On Linux, we need to delete before copying because if the plugin is a
    // hard link, the copy will fail.
    DeleteTestPlugin();
    ASSERT_TRUE(file_util::CopyDirectory(plugin_src_, plugin_file_path_, true));
  }

  void DeleteTestPlugin() {
    file_util::Delete(plugin_file_path_, true);
  }

  virtual void SetUp() {
    CopyTestPlugin();
    TestShellTest::SetUp();
  }

  virtual void TearDown() {
    DeleteTestPlugin();
    TestShellTest::TearDown();
  }

  FilePath plugin_src_;
  FilePath plugin_file_path_;
};

#if !defined(OS_LINUX)
// TODO(tony): http://code.google.com/p/chromium/issues/detail?id=51402
// Tests navigator.plugins.refresh() works.
TEST_F(PluginTest, Refresh) {
  std::string html = "\

Test running....
\
      \
      ";

  WebScriptSource call_check(
      WebString::fromUTF8("check();"));
  WebScriptSource refresh(
      WebString::fromUTF8("navigator.plugins.refresh(false)"));

  // Remove any leftover from previous tests if they exist.  We must also
  // refresh WebKit's plugin cache since it might have had an entry for the
  // test plugin from a previous test.
  DeleteTestPlugin();
  ASSERT_FALSE(file_util::PathExists(plugin_file_path_));
  test_shell_->webView()->mainFrame()->executeScript(refresh);

  test_shell_->webView()->mainFrame()->loadHTMLString(
      html, GURL("about:blank"));
  test_shell_->WaitTestFinished();

  std::string text;
  test_shell_->webView()->mainFrame()->executeScript(call_check);
  text = test_shell_->webView()->mainFrame()->contentAsText(10000).utf8();
  ASSERT_EQ(text, "FAIL");

  CopyTestPlugin();

  test_shell_->webView()->mainFrame()->executeScript(refresh);
  test_shell_->webView()->mainFrame()->executeScript(call_check);
  text = test_shell_->webView()->mainFrame()->contentAsText(10000).utf8();
  ASSERT_EQ(text, "DONE");
}
#endif

// Tests that if a frame is deleted as a result of calling NPP_HandleEvent, we
// don't crash.
TEST_F(PluginTest, DeleteFrameDuringEvent) {
  FilePath test_html = data_dir_;
  test_html = test_html.AppendASCII("plugins");
  test_html = test_html.AppendASCII("delete_frame.html");
  test_shell_->LoadFile(test_html);
  test_shell_->WaitTestFinished();

  WebKit::WebMouseEvent input;
  input.button = WebKit::WebMouseEvent::ButtonLeft;
  input.x = 50;
  input.y = 50;
  input.type = WebKit::WebInputEvent::MouseUp;
  test_shell_->webView()->handleInputEvent(input);

  // No crash means we passed.
}

#if defined(OS_WIN)
BOOL CALLBACK EnumChildProc(HWND hwnd, LPARAM lparam) {
  HWND* plugin_hwnd = reinterpret_cast<HWND*>(lparam);
  if (*plugin_hwnd) {
    // More than one child window found, unexpected.
    plugin_hwnd = NULL;
    return FALSE;
  }
  *plugin_hwnd = hwnd;
  return TRUE;
}

// Tests that hiding/showing the parent frame hides/shows the plugin.
TEST_F(PluginTest, PluginVisibilty) {
  FilePath test_html = data_dir_;
  test_html = test_html.AppendASCII("plugins");
  test_html = test_html.AppendASCII("plugin_visibility.html");
  test_shell_->LoadFile(test_html);
  test_shell_->WaitTestFinished();

  WebFrame* main_frame = test_shell_->webView()->mainFrame();
  HWND frame_hwnd = test_shell_->webViewWnd();
  HWND plugin_hwnd = NULL;
  EnumChildWindows(frame_hwnd, EnumChildProc,
      reinterpret_cast<LPARAM>(&plugin_hwnd));
  ASSERT_TRUE(plugin_hwnd != NULL);
  ASSERT_FALSE(IsWindowVisible(plugin_hwnd));

  main_frame->executeScript(WebString::fromUTF8("showPlugin(true)"));
  ASSERT_TRUE(IsWindowVisible(plugin_hwnd));

  main_frame->executeScript(WebString::fromUTF8("showFrame(false)"));
  ASSERT_FALSE(IsWindowVisible(plugin_hwnd));

  main_frame->executeScript(WebString::fromUTF8("showFrame(true)"));
  ASSERT_TRUE(IsWindowVisible(plugin_hwnd));
}
#endif
#endif //!ARCH_CPU_64_BITS
<|endoftext|>


<commit_before>#include "testbase.h"

#include <QDebug>
#include <QCoreApplication>

/*!
    \page example.html
    \title Generic QDoc Guide
    There are three essential materials for generating documentation with qdoc:

    \list
        \li \c qdoc binary
        \li \c qdocconf configuration files
        \li \c Documentation in \c C++, \c QML, and \c .qdoc files
    \endlist
*/

int main(int argc, char **argv)
{
  QCoreApplication app(argc, argv);

  TestBase test;
  test.setValue(123);
  qDebug() << "main: " << test.getValue();

  return 0;
}
<commit_msg>Added map test<commit_after>#include "testbase.h"

#include <QMap>
#include <QDebug>
#include <QCoreApplication>

/*!
    \page example.html
    \title Generic QDoc Guide
    There are three essential materials for generating documentation with qdoc:

    \list
        \li \c qdoc binary
        \li \c qdocconf configuration files
        \li \c Documentation in \c C++, \c QML, and \c .qdoc files
    \endlist
*/

QMap<int, QString> TheMap;

int main(int argc, char **argv)
{
  QCoreApplication app(argc, argv);

  TestBase test;
  test.setValue(123);
  qDebug() << "main: " << test.getValue();

  TheMap.insert(0, "This is the first element");
  TheMap.insert(1, "This one is to be updated");
  TheMap.insert(9, "Some more information is here, 9th element");
  TheMap.insert(5, "Some element in the middle");
  TheMap.insert(4, "The 4th element");
  TheMap.insert(1, "Here is the 1st updated element");
  qDebug() << "Here is the map:" << TheMap;

  return 0;
}
<|endoftext|>


<commit_before>#include "polylineStyle.h"

#include "tangram.h"
#include "gl/shaderProgram.h"
#include "scene/stops.h"
#include "tile/tile.h"
#include "util/mapProjection.h"

namespace Tangram {

PolylineStyle::PolylineStyle(std::string _name, Blending _blendMode, GLenum _drawMode)
    : Style(_name, _blendMode, _drawMode) {
}

void PolylineStyle::constructVertexLayout() {

    // TODO: Ideally this would be in the same location as the struct that it basically describes
    m_vertexLayout = std::shared_ptr<VertexLayout>(new VertexLayout({
        {"a_position", 3, GL_FLOAT, false, 0},
        {"a_texcoord", 2, GL_FLOAT, false, 0},
        {"a_extrude", 4, GL_FLOAT, false, 0},
        {"a_color", 4, GL_UNSIGNED_BYTE, true, 0},
        {"a_layer", 1, GL_FLOAT, false, 0}
    }));

}

void PolylineStyle::constructShaderProgram() {

    std::string vertShaderSrcStr = stringFromFile("shaders/polyline.vs", PathType::internal);
    std::string fragShaderSrcStr = stringFromFile("shaders/polyline.fs", PathType::internal);

    m_shaderProgram->setSourceStrings(fragShaderSrcStr, vertShaderSrcStr);
}

PolylineStyle::Parameters PolylineStyle::parseRule(const DrawRule& _rule) const {
    Parameters p;

    uint32_t cap = 0, join = 0;

    _rule.get(StyleParamKey::extrude, p.extrude);
    _rule.get(StyleParamKey::color, p.color);
    _rule.get(StyleParamKey::cap, cap);
    _rule.get(StyleParamKey::join, join);
    if (!_rule.get(StyleParamKey::order, p.order)) {
        LOGW("No 'order' specified for feature, ordering cannot be guaranteed :(");
    }

    p.cap = static_cast<CapTypes>(cap);
    p.join = static_cast<JoinTypes>(join);

    if (_rule.get(StyleParamKey::outline_color, p.outlineColor) |
        _rule.contains(StyleParamKey::outline_width) |
        _rule.get(StyleParamKey::outline_cap, cap) |
        _rule.get(StyleParamKey::outline_join, join)) {
        p.outlineOn = true;
        p.outlineCap = static_cast<CapTypes>(cap);
        p.outlineJoin = static_cast<JoinTypes>(join);
    }

    return p;
}

void PolylineStyle::buildPolygon(const Polygon& _poly, const DrawRule& _rule, const Properties& _props,
                                 VboMesh& _mesh, Tile& _tile) const {

    for (const auto& line : _poly) {
        buildLine(line, _rule, _props, _mesh, _tile);
    }
}

double widthMeterToPixel(int _zoom, double _tileSize, double _width) {
    // pixel per meter at z == 0
    double meterRes = _tileSize / (2.0 * MapProjection::HALF_CIRCUMFERENCE);
    // pixel per meter at zoom
    meterRes *= exp2(_zoom);

    return _width * meterRes;
}

bool evalStyleParamWidth(StyleParamKey _key, const DrawRule& _rule, const Tile& _tile,
                         float& width, float& dWdZ){

    int zoom  = _tile.getID().z;
    double tileSize = _tile.getProjection()->TileSize();

    // NB: Tile vertex coordinates are in the range -1..1 => 2,
    // * 0.5 for half-width == 1.0 => 1.0 / tileSize
    //double tileRes = 1.0 / _tile.getProjection()->TileSize();
    double tileRes = 1.0 / tileSize;

    auto& styleParam = _rule.findParameter(_key);
    if (styleParam.stops) {

        width = styleParam.stops->evalWidth(zoom);
        width *= tileRes;

        dWdZ = styleParam.stops->evalWidth(zoom + 1);
        dWdZ *= tileRes;
        // NB: Multiply by 2 for the outline to get the expected stroke pixel width.
        if (_key == StyleParamKey::outline_width) {
            width *= 2;
            dWdZ *= 2;
        }

        dWdZ -= width;

        return true;
    }

    if (styleParam.value.is<StyleParam::Width>()) {
        auto& widthParam = styleParam.value.get<StyleParam::Width>();

        width = widthParam.value;

        if (widthParam.isMeter()) {
            width = widthMeterToPixel(zoom, tileSize, width);
            width *= tileRes;
            dWdZ = width * 2;
        } else {
            width *= tileRes;
            dWdZ = width;
        }

        if (_key == StyleParamKey::outline_width) {
            width *= 2;
            dWdZ *= 2;
        }

        dWdZ -= width;

        return true;
    }

    logMsg("Error: Invalid type for Width '%d'\n", styleParam.value.which());
    return false;
}

void PolylineStyle::buildLine(const Line& _line, const DrawRule& _rule, const Properties& _props,
                              VboMesh& _mesh, Tile& _tile) const {

    if (!_rule.contains(StyleParamKey::color)) {
        const auto& blocks = m_shaderProgram->getSourceBlocks();
        if (blocks.find("color") == blocks.end() && blocks.find("filter") == blocks.end()) {
            return; // No color parameter or color block? NO SOUP FOR YOU
        }
    }

    std::vector<PolylineVertex> vertices;

    Parameters params = parseRule(_rule);
    GLuint abgr = params.color;

    float dWdZ = 0.f;
    float width = 0.f;

    if (!evalStyleParamWidth(StyleParamKey::width, _rule, _tile, width, dWdZ)) {
        return;
    }

    if (Tangram::getDebugFlag(Tangram::DebugFlags::proxy_colors)) {
        abgr = abgr << (_tile.getID().z % 6);
    }

    float height = 0.0f;
    auto& extrude = params.extrude;

    if (extrude[0] != 0.0f || extrude[1] != 0.0f) {
        const static std::string key_height("height");

        height = _props.getNumeric(key_height) * _tile.getInverseScale();
        if (std::isnan(extrude[1])) {
            if (!std::isnan(extrude[0])) {
                height = extrude[0];
            }
        } else { height = extrude[1]; }
    }

    GLfloat layer = _props.getNumeric("sort_key") + params.order;

    PolyLineBuilder builder {
        [&](const glm::vec3& coord, const glm::vec2& normal, const glm::vec2& uv) {
            glm::vec4 extrude = { normal.x, normal.y, width, dWdZ };
            vertices.push_back({ {coord.x, coord.y, height}, uv, extrude, abgr, layer });
        },
        [&](size_t sizeHint){ vertices.reserve(sizeHint); },
        params.cap,
        params.join
    };

    Builders::buildPolyLine(_line, builder);

    if (params.outlineOn) {

        GLuint abgrOutline = params.outlineColor;

        float widthOutline = 0.f;
        float dWdZOutline = 0.f;

        if (!evalStyleParamWidth(StyleParamKey::outline_width, _rule, _tile,
                                 widthOutline, dWdZOutline)) {
            return;
        }

        widthOutline += width;
        dWdZOutline += dWdZ;

        if (params.outlineCap != params.cap || params.outlineJoin != params.join) {
            // need to re-triangulate with different cap and/or join
            builder.cap = params.outlineCap;
            builder.join = params.outlineJoin;
            Builders::buildPolyLine(_line, builder);
        } else {
            // re-use indices from original line
            size_t oldSize = builder.indices.size();
            size_t offset = vertices.size();
            builder.indices.reserve(2 * oldSize);

            for(size_t i = 0; i < oldSize; i++) {
                 builder.indices.push_back(offset + builder.indices[i]);
            }
            for (size_t i = 0; i < offset; i++) {
                const auto& v = vertices[i];
                glm::vec4 extrudeOutline = { v.extrude.x, v.extrude.y, widthOutline, dWdZOutline };
                vertices.push_back({ v.pos, v.texcoord, extrudeOutline, abgrOutline, params.order - 1.f });
            }
        }
    }

    auto& mesh = static_cast<PolylineStyle::Mesh&>(_mesh);
    mesh.addVertices(std::move(vertices), std::move(builder.indices));
}

}
<commit_msg>Fix lines being drawn with double width<commit_after>#include "polylineStyle.h"

#include "tangram.h"
#include "gl/shaderProgram.h"
#include "scene/stops.h"
#include "tile/tile.h"
#include "util/mapProjection.h"

namespace Tangram {

PolylineStyle::PolylineStyle(std::string _name, Blending _blendMode, GLenum _drawMode)
    : Style(_name, _blendMode, _drawMode) {
}

void PolylineStyle::constructVertexLayout() {

    // TODO: Ideally this would be in the same location as the struct that it basically describes
    m_vertexLayout = std::shared_ptr<VertexLayout>(new VertexLayout({
        {"a_position", 3, GL_FLOAT, false, 0},
        {"a_texcoord", 2, GL_FLOAT, false, 0},
        {"a_extrude", 4, GL_FLOAT, false, 0},
        {"a_color", 4, GL_UNSIGNED_BYTE, true, 0},
        {"a_layer", 1, GL_FLOAT, false, 0}
    }));

}

void PolylineStyle::constructShaderProgram() {

    std::string vertShaderSrcStr = stringFromFile("shaders/polyline.vs", PathType::internal);
    std::string fragShaderSrcStr = stringFromFile("shaders/polyline.fs", PathType::internal);

    m_shaderProgram->setSourceStrings(fragShaderSrcStr, vertShaderSrcStr);
}

PolylineStyle::Parameters PolylineStyle::parseRule(const DrawRule& _rule) const {
    Parameters p;

    uint32_t cap = 0, join = 0;

    _rule.get(StyleParamKey::extrude, p.extrude);
    _rule.get(StyleParamKey::color, p.color);
    _rule.get(StyleParamKey::cap, cap);
    _rule.get(StyleParamKey::join, join);
    if (!_rule.get(StyleParamKey::order, p.order)) {
        LOGW("No 'order' specified for feature, ordering cannot be guaranteed :(");
    }

    p.cap = static_cast<CapTypes>(cap);
    p.join = static_cast<JoinTypes>(join);

    if (_rule.get(StyleParamKey::outline_color, p.outlineColor) |
        _rule.contains(StyleParamKey::outline_width) |
        _rule.get(StyleParamKey::outline_cap, cap) |
        _rule.get(StyleParamKey::outline_join, join)) {
        p.outlineOn = true;
        p.outlineCap = static_cast<CapTypes>(cap);
        p.outlineJoin = static_cast<JoinTypes>(join);
    }

    return p;
}

void PolylineStyle::buildPolygon(const Polygon& _poly, const DrawRule& _rule, const Properties& _props,
                                 VboMesh& _mesh, Tile& _tile) const {

    for (const auto& line : _poly) {
        buildLine(line, _rule, _props, _mesh, _tile);
    }
}

double widthMeterToPixel(int _zoom, double _tileSize, double _width) {
    // pixel per meter at z == 0
    double meterRes = _tileSize / (2.0 * MapProjection::HALF_CIRCUMFERENCE);
    // pixel per meter at zoom
    meterRes *= exp2(_zoom);

    return _width * meterRes;
}

bool evalStyleParamWidth(StyleParamKey _key, const DrawRule& _rule, const Tile& _tile,
                         float& width, float& dWdZ){

    int zoom  = _tile.getID().z;
    double tileSize = _tile.getProjection()->TileSize();

    // NB: 0.5 because 'width' will be extruded in both directions
    double tileRes = 0.5 / _tile.getProjection()->TileSize();

    auto& styleParam = _rule.findParameter(_key);
    if (styleParam.stops) {

        width = styleParam.stops->evalWidth(zoom);
        width *= tileRes;

        dWdZ = styleParam.stops->evalWidth(zoom + 1);
        dWdZ *= tileRes;
        // NB: Multiply by 2 for the outline to get the expected stroke pixel width.
        if (_key == StyleParamKey::outline_width) {
            width *= 2;
            dWdZ *= 2;
        }

        dWdZ -= width;

        return true;
    }

    if (styleParam.value.is<StyleParam::Width>()) {
        auto& widthParam = styleParam.value.get<StyleParam::Width>();

        width = widthParam.value;

        if (widthParam.isMeter()) {
            width = widthMeterToPixel(zoom, tileSize, width);
            width *= tileRes;
            dWdZ = width * 2;
        } else {
            width *= tileRes;
            dWdZ = width;
        }

        if (_key == StyleParamKey::outline_width) {
            width *= 2;
            dWdZ *= 2;
        }

        dWdZ -= width;

        return true;
    }

    logMsg("Error: Invalid type for Width '%d'\n", styleParam.value.which());
    return false;
}

void PolylineStyle::buildLine(const Line& _line, const DrawRule& _rule, const Properties& _props,
                              VboMesh& _mesh, Tile& _tile) const {

    if (!_rule.contains(StyleParamKey::color)) {
        const auto& blocks = m_shaderProgram->getSourceBlocks();
        if (blocks.find("color") == blocks.end() && blocks.find("filter") == blocks.end()) {
            return; // No color parameter or color block? NO SOUP FOR YOU
        }
    }

    std::vector<PolylineVertex> vertices;

    Parameters params = parseRule(_rule);
    GLuint abgr = params.color;

    float dWdZ = 0.f;
    float width = 0.f;

    if (!evalStyleParamWidth(StyleParamKey::width, _rule, _tile, width, dWdZ)) {
        return;
    }

    if (Tangram::getDebugFlag(Tangram::DebugFlags::proxy_colors)) {
        abgr = abgr << (_tile.getID().z % 6);
    }

    float height = 0.0f;
    auto& extrude = params.extrude;

    if (extrude[0] != 0.0f || extrude[1] != 0.0f) {
        const static std::string key_height("height");

        height = _props.getNumeric(key_height) * _tile.getInverseScale();
        if (std::isnan(extrude[1])) {
            if (!std::isnan(extrude[0])) {
                height = extrude[0];
            }
        } else { height = extrude[1]; }
    }

    GLfloat layer = _props.getNumeric("sort_key") + params.order;

    PolyLineBuilder builder {
        [&](const glm::vec3& coord, const glm::vec2& normal, const glm::vec2& uv) {
            glm::vec4 extrude = { normal.x, normal.y, width, dWdZ };
            vertices.push_back({ {coord.x, coord.y, height}, uv, extrude, abgr, layer });
        },
        [&](size_t sizeHint){ vertices.reserve(sizeHint); },
        params.cap,
        params.join
    };

    Builders::buildPolyLine(_line, builder);

    if (params.outlineOn) {

        GLuint abgrOutline = params.outlineColor;

        float widthOutline = 0.f;
        float dWdZOutline = 0.f;

        if (!evalStyleParamWidth(StyleParamKey::outline_width, _rule, _tile,
                                 widthOutline, dWdZOutline)) {
            return;
        }

        widthOutline += width;
        dWdZOutline += dWdZ;

        if (params.outlineCap != params.cap || params.outlineJoin != params.join) {
            // need to re-triangulate with different cap and/or join
            builder.cap = params.outlineCap;
            builder.join = params.outlineJoin;
            Builders::buildPolyLine(_line, builder);
        } else {
            // re-use indices from original line
            size_t oldSize = builder.indices.size();
            size_t offset = vertices.size();
            builder.indices.reserve(2 * oldSize);

            for(size_t i = 0; i < oldSize; i++) {
                 builder.indices.push_back(offset + builder.indices[i]);
            }
            for (size_t i = 0; i < offset; i++) {
                const auto& v = vertices[i];
                glm::vec4 extrudeOutline = { v.extrude.x, v.extrude.y, widthOutline, dWdZOutline };
                vertices.push_back({ v.pos, v.texcoord, extrudeOutline, abgrOutline, params.order - 1.f });
            }
        }
    }

    auto& mesh = static_cast<PolylineStyle::Mesh&>(_mesh);
    mesh.addVertices(std::move(vertices), std::move(builder.indices));
}

}
<|endoftext|>


<commit_before>#include <QApplication>
#include <QPushButton>
#include <QGridLayout>
#include <QStackedLayout>
#include <QLabel>
#include <QMenuBar>
#include <QAction>
#include <QPainter>
#include <QPicture>
#include <QMessageBox>

/* TESTING CLASSESS */
class Game;

/* FUNCTIONS */
void markDisabledAll(QPushButton button[3][3])
{
	for(int x = 0; x < 3; x++) for(int y = 0; y < 3; y++)
		button[x][y].setDisabled(true);
}

void paintCross(QIcon &icon, QSize &size, const int &thickness)
{
	QPixmap pic(size);
	pic.fill(Qt::transparent);

	QPainter painter(&pic);
	painter.setPen(QPen(Qt::black, thickness));
	painter.setRenderHint(QPainter::Antialiasing);

	QLineF angleline;
	angleline.setLine(7, 7, 93, 93);
	painter.drawLine(angleline);
	angleline.setLine(7, 93, 93, 7);
	painter.drawLine(angleline);

	painter.end();
	icon.addPixmap(pic);
}

void paintCircle(QIcon &icon, QSize &size, const int &thickness)
{
	QPixmap pic(size);
	pic.fill(Qt::transparent);

	QPainter painter(&pic);
	painter.setPen(QPen(Qt::black, thickness));
	painter.setRenderHint(QPainter::Antialiasing);

	painter.drawEllipse(QPointF(50, 50), 45, 45);

	painter.end();
	icon.addPixmap(pic);
}

void paintLine(QLabel &label, int angle, int len, QPointF point, const int &thickness)
{
	QPicture pic;
	QLineF angleline;
	QPainter painter(&pic);

	painter.setPen(QPen(Qt::black, thickness));
	painter.setRenderHint(QPainter::Antialiasing);

	angleline.setP1(point);
	angleline.setAngle(angle);
	angleline.setLength(len);

	painter.drawLine(angleline);
	painter.end();

	label.setPicture(pic);
}

/* MAIN */
int main(int argc, char *argv[])
{
	/* VARIABLES */
	QApplication a(argc, argv);
	QWidget window;
	QStackedLayout layout;
	QMenuBar menubar;
	QMenu help("Help");
	QAction about("About", &help);

	/* GRID_GAME */
	QWidget widget_game;
	QGridLayout grid_game;

	/* BOX_MENU */
	QWidget widget_menu;
	QVBoxLayout box_menu;

	QPushButton restart("Restart");
	QPushButton play_single("Play Singleplayer");
	QPushButton play_2v2("Play 2v2");
	QPushButton play_multi("Play Multiplayer");
	QPushButton return_to_menu("Return");
	QPushButton button[3][3];
	QSize size_current(30, 30);

	int thickness = 8;
	int rows = 0;
	int columns = 0;
	char button_str[3][3];
	bool xnow = true;
	char win = 'n';

	QIcon icon_x;
	QIcon icon_o;

	QSize size_x(100, 100);
	QSize size_o(100, 100);

	QFrame line[4];

	QLabel left_line;
	QLabel right_line;
	QLabel horizon_line;
	QLabel vertical_line;
	QLabel turn("Whose turn:");
	QLabel icon_current;

	/* PAINT STUFF */
	paintCross(icon_x, size_x, thickness);
	paintCircle(icon_o, size_o, thickness);
	paintLine(vertical_line, 90, 298, QPointF(112, 0), thickness);
	paintLine(horizon_line, 0, 298, QPointF(0, 100), thickness);
	paintLine(left_line, 45, 420, QPointF(0, 100), thickness);
	paintLine(right_line, -45, 420, QPointF(0, 100), thickness);

	/* INITS */
	icon_current.setPixmap(icon_x.pixmap(size_current));
	restart.setFocusPolicy(Qt::NoFocus);
	play_2v2.setFixedSize(305, 40);
	play_single.setFixedSize(305, 40);
	play_multi.setFixedSize(305, 40);
	window.setWindowTitle("QTicTacToe");
	window.setWindowFlags(Qt::Window);
	window.setFixedSize(0, 0);
	window.setLayout(&layout);
	layout.setMenuBar(&menubar);

	widget_game.setLayout(&grid_game);
	widget_menu.setLayout(&box_menu);

	box_menu.setAlignment(Qt::AlignTop);
	box_menu.setSpacing(50);

	layout.addWidget(&widget_game);
	layout.addWidget(&widget_menu);

	grid_game.setSpacing(0);
	grid_game.setRowMinimumHeight(5, 20);
	grid_game.setRowMinimumHeight(6, 40);
	menubar.addMenu(&help);
	help.addAction(&about);
	line[0].setFrameShape(QFrame::HLine);
	line[1].setFrameShape(QFrame::HLine);
	line[2].setFrameShape(QFrame::VLine);
	line[3].setFrameShape(QFrame::VLine);
	line[0].setLineWidth(2);
	line[1].setLineWidth(2);
	line[2].setLineWidth(2);
	line[3].setLineWidth(2);
	for(int x = 0; x < 3; x++) for(int y = 0; y < 3; y++)
	{
		button[x][y].setFixedSize(100, 100);
		button[x][y].setFlat(true);
		button[x][y].setFocusPolicy(Qt::NoFocus);
	}

	/* CONNECTS */
	QObject::connect(&about, &QAction::triggered, [&]
	{
		qDebug("action");
		QMessageBox::about(&window, "About", "QTicTacToe");
	});

	QObject::connect(&restart, &QPushButton::clicked, [&]
	{
		xnow = true;
		win = 'n';
		icon_current.setPixmap(icon_x.pixmap(size_current));
		for(int x = 0; x < 3; x++) for(int y = 0; y < 3; y++)
		{
			button_str[x][y] = '0';
			button[x][y].setEnabled(true);
			button[x][y].setIcon(QIcon());
		}
		grid_game.removeWidget(&left_line);
		grid_game.removeWidget(&right_line);
		grid_game.removeWidget(&horizon_line);
		grid_game.removeWidget(&vertical_line);
		left_line.hide();
		right_line.hide();
		horizon_line.hide();
		vertical_line.hide();

	});

	QObject::connect(&play_2v2, &QPushButton::clicked, [&]
	{
		widget_game.show();
		widget_menu.hide();

	});

	QObject::connect(&play_single, &QPushButton::clicked, [&]
	{
		widget_game.show();
		widget_menu.hide();
	});

	QObject::connect(&play_multi, &QPushButton::clicked, [&]
	{
		widget_game.show();
		widget_menu.hide();
	});

	QObject::connect(&return_to_menu, &QPushButton::clicked, [&]
	{
		widget_game.hide();
		widget_menu.show();
	});

	for(int x = 0; x < 3; x++) for(int y = 0; y < 3; y++)
	{
		QObject::connect(&button[x][y], &QPushButton::clicked, [&, x, y]
		{
			if(xnow)
			{
				button[x][y].setIcon(icon_x);
				button[x][y].setIconSize(size_x);
				button_str[x][y] = 'x';
				icon_current.setPixmap(icon_o.pixmap(size_current));
				xnow = false;
			}
			else
			{
				button[x][y].setIcon(icon_o);
				button[x][y].setIconSize(size_o);
				button_str[x][y] = 'o';
				icon_current.setPixmap(icon_x.pixmap(size_current));
				xnow = true;
			}
			button[x][y].setDisabled(true);

			//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
			if(button_str[0][0] == 'x' && button_str[0][1] == 'x' && button_str[0][2] == 'x')
			{
				grid_game.addWidget(&horizon_line, 0, 0, 1, 5, Qt::AlignJustify);
				horizon_line.show();
				markDisabledAll(button);
			}
			else if(button_str[1][0] == 'x' && button_str[1][1] == 'x' && button_str[1][2] == 'x')
			{
				grid_game.addWidget(&horizon_line, 2, 0, 1, 5, Qt::AlignJustify);
				horizon_line.show();
				markDisabledAll(button);
			}
			else if(button_str[2][0] == 'x' && button_str[2][1] == 'x' && button_str[2][2] == 'x')
			{
				grid_game.addWidget(&horizon_line, 4, 0, 1, 5, Qt::AlignJustify);
				horizon_line.show();
				markDisabledAll(button);
			}
			/*else if(button_str[0] == 'x' && button_str[3] == 'x' && button_str[6] == 'x')
			{
				grid_game.addWidget(&vertical_line, 0, 0, 5, 1, Qt::AlignJustify);
				vertical_line.show();
				markDisabledAll();
			}
			else if(button_str[1] == 'x' && button_str[4] == 'x' && button_str[7] == 'x')
			{
				grid_game.addWidget(&vertical_line, 0, 2, 5, 1, Qt::AlignJustify);
				vertical_line.show();
				markDisabledAll();
			}
			else if(button_str[2] == 'x' && button_str[5] == 'x' && button_str[8] == 'x')
			{
				grid_game.addWidget(&vertical_line, 0, 4, 5, 1, Qt::AlignJustify);
				vertical_line.show();
				markDisabledAll();
			}
			else if(button_str[0] == 'x' && button_str[4] == 'x' && button_str[8] == 'x')
			{
				grid_game.addWidget(&right_line, 0, 0, 5, 5, Qt::AlignJustify);
				right_line.show();
				markDisabledAll();
			}
			else if(button_str[2] == 'x' && button_str[4] == 'x' && button_str[6] == 'x')
			{
				grid_game.addWidget(&left_line, 0, 0, 5, 5, Qt::AlignJustify);
				left_line.show();
				markDisabledAll();
			}
			// OOOOOOOOOOOOOOOOOOOOOOOOOOO
			if(button_str[0] == 'o' && button_str[1] == 'o' && button_str[2] == 'o')
			{
				grid_game.addWidget(&horizon_line, 0, 0, 1, 5, Qt::AlignJustify);
				horizon_line.show();
				markDisabledAll();
			}
			else if(button_str[3] == 'o' && button_str[4] == 'o' && button_str[5] == 'o')
			{
				grid_game.addWidget(&horizon_line, 2, 0, 1, 5, Qt::AlignJustify);
				horizon_line.show();
				markDisabledAll();
			}
			else if(button_str[6] == 'o' && button_str[7] == 'o' && button_str[8] == 'o')
			{
				grid_game.addWidget(&horizon_line, 4, 0, 1, 5, Qt::AlignJustify);
				horizon_line.show();
				markDisabledAll();
			}
			else if(button_str[0] == 'o' && button_str[3] == 'o' && button_str[6] == 'o')
			{
				grid_game.addWidget(&vertical_line, 0, 0, 5, 1, Qt::AlignJustify);
				vertical_line.show();
				markDisabledAll();
			}
			else if(button_str[1] == 'o' && button_str[4] == 'o' && button_str[7] == 'o')
			{
				grid_game.addWidget(&vertical_line, 0, 2, 5, 1, Qt::AlignJustify);
				vertical_line.show();
				markDisabledAll();
			}
			else if(button_str[2] == 'o' && button_str[5] == 'o' && button_str[8] == 'o')
			{
				grid_game.addWidget(&vertical_line, 0, 4, 5, 1, Qt::AlignJustify);
				vertical_line.show();
				markDisabledAll();
			}
			else if(button_str[0] == 'o' && button_str[4] == 'o' && button_str[8] == 'o')
			{
				grid_game.addWidget(&right_line, 0, 0, 5, 5, Qt::AlignJustify);
				right_line.show();
				markDisabledAll();
			}
			else if(button_str[2] == 'o' && button_str[4] == 'o' && button_str[6] == 'o')
			{
				grid_game.addWidget(&left_line, 0, 0, 5, 5, Qt::AlignJustify);
				left_line.show();
				markDisabledAll();
			}*/

		});
	}

	/* GRID ADDONS */
	box_menu.addWidget(&play_single);
	box_menu.addWidget(&play_2v2);
	box_menu.addWidget(&play_multi);
	grid_game.addWidget(&turn, 6, 0);
	grid_game.addWidget(&icon_current, 6, 2);
	grid_game.addWidget(&restart, 6, 4, Qt::AlignRight);
	grid_game.addWidget(&return_to_menu, 7, 4, Qt::AlignRight);
	for(int x = 0; x < 3; x++) for(int y = 0; y < 3; y++)
	{
		if(columns == 5)
		{
			rows++;
			columns = 0;
		}
		if(columns == 1 || columns == 3)
		{
			grid_game.addWidget(&line[2], 0, 1, 5, 1);
			grid_game.addWidget(&line[3], 0, 3, 5, 1);
			columns++;
		}
		if(rows == 1 || rows == 3)
		{
			grid_game.addWidget(&line[0], 1, 0, 1, 5);
			grid_game.addWidget(&line[1], 3, 0, 1, 5);
			rows++;
		}
		grid_game.addWidget(&button[x][y], rows, columns);
		columns++;
	}

	/* SHOW AND RUN */
	window.show();
	widget_menu.show();
	widget_game.hide();
	return a.exec();
}
<commit_msg>10th source drop<commit_after>#include <QApplication>
#include <QPushButton>
#include <QGridLayout>
#include <QStackedLayout>
#include <QLabel>
#include <QMenuBar>
#include <QAction>
#include <QPainter>
#include <QPicture>
#include <QMessageBox>

/* TESTING CLASSESS */
class Board
{

};

/* FUNCTIONS */
void markDisabledAll(QPushButton button[3][3])
{
	for(int x = 0; x < 3; x++) for(int y = 0; y < 3; y++)
		button[x][y].setDisabled(true);
}

void drawLineOnGrid(QGridLayout &grid, QLabel &line, int fromrow, int fromcolumn, int rowspan, int columnspan, QPushButton button[3][3])
{
	grid.addWidget(&line, fromrow, fromcolumn, rowspan, columnspan, Qt::AlignJustify);
	line.show();
	markDisabledAll(button);
}

void markButtonIcon(QPushButton button[3][3], const int &x, const int &y, char button_str[3][3], const char symbol, QIcon &icon, QSize &size, bool &xnow, bool n, QLabel &label_current, QSize &size_current)
{
	button[x][y].setIcon(icon);
	button[x][y].setIconSize(size);
	button_str[x][y] = symbol;
	label_current.setPixmap(icon.pixmap(size_current));
	xnow = n;
}

void paintCross(QIcon &icon, QSize &size, const int &thickness)
{
	QPixmap pic(size);
	pic.fill(Qt::transparent);

	QPainter painter(&pic);
	painter.setPen(QPen(Qt::black, thickness));
	painter.setRenderHint(QPainter::Antialiasing);

	QLineF angleline;
	angleline.setLine(7, 7, 93, 93);
	painter.drawLine(angleline);
	angleline.setLine(7, 93, 93, 7);
	painter.drawLine(angleline);

	painter.end();
	icon.addPixmap(pic);
}

void paintCircle(QIcon &icon, QSize &size, const int &thickness)
{
	QPixmap pic(size);
	pic.fill(Qt::transparent);

	QPainter painter(&pic);
	painter.setPen(QPen(Qt::black, thickness));
	painter.setRenderHint(QPainter::Antialiasing);

	painter.drawEllipse(QPointF(50, 50), 45, 45);

	painter.end();
	icon.addPixmap(pic);
}

void paintLine(QLabel &label, int angle, int len, QPointF point, const int &thickness)
{
	QPicture pic;
	QLineF angleline;
	QPainter painter(&pic);

	painter.setPen(QPen(Qt::black, thickness));
	painter.setRenderHint(QPainter::Antialiasing);

	angleline.setP1(point);
	angleline.setAngle(angle);
	angleline.setLength(len);

	painter.drawLine(angleline);
	painter.end();

	label.setPicture(pic);
}

/* MAIN */
int main(int argc, char *argv[])
{
	/* VARIABLES */
	QApplication a(argc, argv);
	QWidget window;
	QStackedLayout layout;
	QMenuBar menubar;
	QMenu help("Help");
	QAction about("About", &help);

	/* GRID_GAME */
	QWidget widget_game;
QGridLayout grid_game;

	/* BOX_MENU */
	QWidget widget_menu;
	QVBoxLayout box_menu;

	QPushButton restart("Restart");
	QPushButton play_single("Play Singleplayer");
	QPushButton play_2v2("Play 2v2");
	QPushButton play_multi("Play Multiplayer");
	QPushButton return_to_menu("Return");
	QPushButton button[3][3];
	QSize size_current(30, 30);

	int thickness = 8;
	int rows = 0;
	int columns = 0;
	char button_str[3][3];
	bool xnow = true;
	char win = 'n';

	QIcon icon_x;
	QIcon icon_o;

	QSize size_x(100, 100);
	QSize size_o(100, 100);

	QFrame line[4];

	QLabel left_line;
	QLabel right_line;
	QLabel horizon_line;
	QLabel vertical_line;
	QLabel turn("Whose turn:");
	QLabel label_current;

	/* PAINT STUFF */
	paintCross(icon_x, size_x, thickness);
	paintCircle(icon_o, size_o, thickness);
	paintLine(vertical_line, 90, 298, QPointF(112, 0), thickness);
	paintLine(horizon_line, 0, 298, QPointF(0, 100), thickness);
	paintLine(left_line, 45, 420, QPointF(0, 100), thickness);
	paintLine(right_line, -45, 420, QPointF(0, 100), thickness);

	/* INITS */
	label_current.setPixmap(icon_x.pixmap(size_current));
	restart.setFocusPolicy(Qt::NoFocus);
	play_2v2.setFixedSize(305, 40);
	play_single.setFixedSize(305, 40);
	play_multi.setFixedSize(305, 40);
	window.setWindowTitle("QTicTacToe");
	window.setWindowFlags(Qt::Window);
	window.setFixedSize(0, 0);
	window.setLayout(&layout);
	layout.setMenuBar(&menubar);

	widget_game.setLayout(&grid_game);
	widget_menu.setLayout(&box_menu);

	box_menu.setAlignment(Qt::AlignTop);
	box_menu.setSpacing(50);

	layout.addWidget(&widget_game);
	layout.addWidget(&widget_menu);

	grid_game.setSpacing(0);
	grid_game.setRowMinimumHeight(5, 20);
	grid_game.setRowMinimumHeight(6, 40);
	menubar.addMenu(&help);
	help.addAction(&about);
	line[0].setFrameShape(QFrame::HLine);
	line[1].setFrameShape(QFrame::HLine);
	line[2].setFrameShape(QFrame::VLine);
	line[3].setFrameShape(QFrame::VLine);
	line[0].setLineWidth(2);
	line[1].setLineWidth(2);
	line[2].setLineWidth(2);
	line[3].setLineWidth(2);

	for(int x = 0; x < 3; x++) for(int y = 0; y < 3; y++)
	{
		button[x][y].setFixedSize(100, 100);
		button[x][y].setFlat(true);
		button[x][y].setFocusPolicy(Qt::NoFocus);
	}

	/* CONNECTS */
	QObject::connect(&about, &QAction::triggered, [&]
	{
		qDebug("action");
		QMessageBox::about(&window, "About", "QTicTacToe");
	});

	QObject::connect(&restart, &QPushButton::clicked, [&]
	{
		xnow = true;
		win = 'n';
		label_current.setPixmap(icon_x.pixmap(size_current));
		for(int x = 0; x < 3; x++) for(int y = 0; y < 3; y++)
		{
			button_str[x][y] = '0';
			button[x][y].setEnabled(true);
			button[x][y].setIcon(QIcon());
		}
		grid_game.removeWidget(&left_line);
		grid_game.removeWidget(&right_line);
		grid_game.removeWidget(&horizon_line);
		grid_game.removeWidget(&vertical_line);
		left_line.hide();
		right_line.hide();
		horizon_line.hide();
		vertical_line.hide();

	});

	QObject::connect(&play_2v2, &QPushButton::clicked, [&]
	{
		widget_game.show();
		widget_menu.hide();

	});

	QObject::connect(&play_single, &QPushButton::clicked, [&]
	{
		widget_game.show();
		widget_menu.hide();
	});

	QObject::connect(&play_multi, &QPushButton::clicked, [&]
	{
		widget_game.show();
		widget_menu.hide();
	});

	QObject::connect(&return_to_menu, &QPushButton::clicked, [&]
	{
		widget_game.hide();
		widget_menu.show();
	});

	for(int x = 0; x < 3; x++) for(int y = 0; y < 3; y++)
	{
		QObject::connect(&button[x][y], &QPushButton::clicked, [&, x, y]
		{
			button[x][y].setDisabled(true);

			if(xnow)
				markButtonIcon(button, x, y, button_str, 'x', icon_x, size_x, xnow, false, label_current, size_current);
			else
				markButtonIcon(button, x, y, button_str, 'o', icon_o, size_o, xnow, true, label_current, size_current);

			if(button_str[0][0] == 'x' && button_str[0][1] == 'x' && button_str[0][2] == 'x')
				drawLineOnGrid(grid_game, horizon_line, 0, 0, 1, 5, button);
			else if(button_str[1][0] == 'x' && button_str[1][1] == 'x' && button_str[1][2] == 'x')
				drawLineOnGrid(grid_game, horizon_line, 2, 0, 1, 5, button);
			else if(button_str[2][0] == 'x' && button_str[2][1] == 'x' && button_str[2][2] == 'x')
				drawLineOnGrid(grid_game, horizon_line, 4, 0, 1, 5, button);
			else if(button_str[0][0] == 'x' && button_str[1][0] == 'x' && button_str[2][0] == 'x')
				drawLineOnGrid(grid_game, vertical_line, 0, 0, 5, 1, button);
			else if(button_str[0][1] == 'x' && button_str[1][1] == 'x' && button_str[2][1] == 'x')
				drawLineOnGrid(grid_game, vertical_line, 0, 2, 5, 1, button);
			else if(button_str[0][2] == 'x' && button_str[1][2] == 'x' && button_str[2][2] == 'x')
				drawLineOnGrid(grid_game, vertical_line, 0, 4, 5, 1, button);
			else if(button_str[0][0] == 'x' && button_str[1][1] == 'x' && button_str[2][2] == 'x')
				drawLineOnGrid(grid_game, right_line, 0, 0, 5, 5, button);
			else if(button_str[0][2] == 'x' && button_str[1][1] == 'x' && button_str[2][0] == 'x')
				drawLineOnGrid(grid_game, left_line, 0, 0, 5, 5, button);
			if(button_str[0][0] == 'o' && button_str[0][1] == 'o' && button_str[0][2] == 'o')
				drawLineOnGrid(grid_game, horizon_line, 0, 0, 1, 5, button);
			else if(button_str[1][0] == 'o' && button_str[1][1] == 'o' && button_str[1][2] == 'o')
				drawLineOnGrid(grid_game, horizon_line, 2, 0, 1, 5, button);
			else if(button_str[2][0] == 'o' && button_str[2][1] == 'o' && button_str[2][2] == 'o')
				drawLineOnGrid(grid_game, horizon_line, 4, 0, 1, 5, button);
			else if(button_str[0][0] == 'o' && button_str[1][0] == 'o' && button_str[2][0] == 'o')
				drawLineOnGrid(grid_game, vertical_line, 0, 0, 5, 1, button);
			else if(button_str[0][1] == 'o' && button_str[1][1] == 'o' && button_str[2][1] == 'o')
				drawLineOnGrid(grid_game, vertical_line, 0, 2, 5, 1, button);
			else if(button_str[0][2] == 'o' && button_str[1][2] == 'o' && button_str[2][2] == 'o')
				drawLineOnGrid(grid_game, vertical_line, 0, 4, 5, 1, button);
			else if(button_str[0][0] == 'o' && button_str[1][1] == 'o' && button_str[2][2] == 'o')
				drawLineOnGrid(grid_game, right_line, 0, 0, 5, 5, button);
			else if(button_str[0][2] == 'o' && button_str[1][1] == 'o' && button_str[2][0] == 'o')
				drawLineOnGrid(grid_game, left_line, 0, 0, 5, 5, button);

		});
	}

	/* GRID ADDONS */
	box_menu.addWidget(&play_single);
	box_menu.addWidget(&play_2v2);
	box_menu.addWidget(&play_multi);
	grid_game.addWidget(&turn, 6, 0);
	grid_game.addWidget(&label_current, 6, 2);
	grid_game.addWidget(&restart, 6, 4, Qt::AlignRight);
	grid_game.addWidget(&return_to_menu, 7, 4, Qt::AlignRight);
	for(int x = 0; x < 3; x++) for(int y = 0; y < 3; y++)
	{
		if(columns == 5)
		{
			rows++;
			columns = 0;
		}
		if(columns == 1 || columns == 3)
		{
			grid_game.addWidget(&line[2], 0, 1, 5, 1);
			grid_game.addWidget(&line[3], 0, 3, 5, 1);
			columns++;
		}
		if(rows == 1 || rows == 3)
		{
			grid_game.addWidget(&line[0], 1, 0, 1, 5);
			grid_game.addWidget(&line[1], 3, 0, 1, 5);
			rows++;
		}
		grid_game.addWidget(&button[x][y], rows, columns);
		columns++;
	}

	/* SHOW AND RUN */
	window.show();
	widget_menu.show();
	widget_game.hide();
	return a.exec();
}
<|endoftext|>


<commit_before>
#include <iostream>

#include <proxc/proxc.hpp>

int main()
{
    std::cout << get_name() << std::endl;
    return 0;
}
<commit_msg>Boost Coroutine example<commit_after>
#include <iostream>
#include <vector>

#include <boost/coroutine/coroutine.hpp>

#include <proxc/proxc.hpp>

using proc = boost::coroutines::symmetric_coroutine<void>;

std::vector<int>
merge(const std::vector<int>& a, const std::vector<int>& b)
{
    std::vector<int> c;
    std::size_t idx_a = 0, idx_b = 0;
    proc::call_type *other_a = 0, *other_b = 0;

    proc::call_type coro_a(
        [&](proc::yield_type& yield) {
            while (idx_a < a.size()) {
                if (b[idx_b] < a[idx_a]) {
                    yield(*other_b);
                }
                c.push_back(a[idx_a++]);
            }
            while (idx_b < b.size()) {
                c.push_back(b[idx_b++]);
            }
        });

    proc::call_type coro_b(
        [&](proc::yield_type& yield) {
            while (idx_b < b.size()) {
                if (a[idx_a] < b[idx_b]) {
                    yield(*other_a);
                }
                c.push_back(b[idx_b++]);
            }
            while (idx_a < a.size()) {
                c.push_back(a[idx_a++]);
            }
        });

    other_a = &coro_a;
    other_b = &coro_b;

    coro_a();

    return c;
}

void
print(std::vector<int>& v) {
    for (const auto i : v) {
        std::cout << i << " ";
    }
    std::cout << std::endl;
}

int main()
{
    std::cout << get_name() << std::endl;
    std::vector<int> a = { 1, 5, 6, 10 };
    std::vector<int> b = { 2, 4, 7, 8, 9, 13 };
    std::vector<int> c = merge(a, b);

    print(a);
    print(b);
    print(c);

    return 0;
}
<|endoftext|>


<commit_before>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

#ifdef _MSC_VER
#include <intrin.h>
#else
#include <immintrin.h>
#endif

#include <iostream>

#include "arrow/api.h"
#include "arrow/io/memory.h"
#include "arrow/testing/gtest_util.h"
#include "arrow/testing/util.h"
#include "arrow/util/cpu-info.h"

#include "benchmark/benchmark.h"

namespace arrow {

using internal::CpuInfo;
static CpuInfo* cpu_info = CpuInfo::GetInstance();

static const int kNumCores = cpu_info->num_cores();
static const int64_t kL1Size = cpu_info->CacheSize(CpuInfo::L1_CACHE);
static const int64_t kL2Size = cpu_info->CacheSize(CpuInfo::L2_CACHE);
static const int64_t kL3Size = cpu_info->CacheSize(CpuInfo::L3_CACHE);

constexpr size_t kMemoryPerCore = 32 * 1024 * 1024;
using BufferPtr = std::shared_ptr<Buffer>;

#ifdef ARROW_WITH_BENCHMARKS_REFERENCE
#ifndef _MSC_VER

#ifdef ARROW_AVX512

using VectorType = __m512i;
#define VectorSet _mm512_set1_epi32
#define VectorLoad _mm512_stream_load_si512
#define VectorLoadAsm(SRC, DST) \
  asm volatile("vmovaps %[src], %[dst]" : [dst] "=v"(DST) : [src] "m"(SRC) :)
#define VectorStreamLoad _mm512_stream_load_si512
#define VectorStreamLoadAsm(SRC, DST) \
  asm volatile("vmovntdqa %[src], %[dst]" : [dst] "=v"(DST) : [src] "m"(SRC) :)
#define VectorStreamWrite _mm512_stream_si512

#else

#ifdef ARROW_AVX2

using VectorType = __m256i;
#define VectorSet _mm256_set1_epi32
#define VectorLoad _mm256_stream_load_si256
#define VectorLoadAsm(SRC, DST) \
  asm volatile("vmovaps %[src], %[dst]" : [dst] "=v"(DST) : [src] "m"(SRC) :)
#define VectorStreamLoad _mm256_stream_load_si256
#define VectorStreamLoadAsm(SRC, DST) \
  asm volatile("vmovntdqa %[src], %[dst]" : [dst] "=v"(DST) : [src] "m"(SRC) :)
#define VectorStreamWrite _mm256_stream_si256

#else  // ARROW_AVX2 not set

using VectorType = __m128i;
#define VectorSet _mm_set1_epi32
#define VectorLoad _mm_stream_load_si128
#define VectorLoadAsm(SRC, DST) \
  asm volatile("movaps %[src], %[dst]" : [dst] "=x"(DST) : [src] "m"(SRC) :)
#define VectorStreamLoad _mm_stream_load_si128
#define VectorStreamLoadAsm(SRC, DST) \
  asm volatile("movntdqa %[src], %[dst]" : [dst] "=x"(DST) : [src] "m"(SRC) :)
#define VectorStreamWrite _mm_stream_si128

#endif  // ARROW_AVX2
#endif  // ARROW_AVX512

static void Read(void* src, void* dst, size_t size) {
  const auto simd = static_cast<VectorType*>(src);
  VectorType a, b, c, d;
  (void)dst;

  for (size_t i = 0; i < size / sizeof(VectorType); i += 4) {
    VectorLoadAsm(simd[i], a);
    VectorLoadAsm(simd[i + 1], b);
    VectorLoadAsm(simd[i + 2], c);
    VectorLoadAsm(simd[i + 3], d);
  }

  memset(&a, 0, sizeof(a));
  memset(&b, 0, sizeof(b));
  memset(&c, 0, sizeof(c));
  memset(&d, 0, sizeof(d));

  benchmark::DoNotOptimize(a + b + c + d);
}

// See http://codearcana.com/posts/2013/05/18/achieving-maximum-memory-bandwidth.html
// for the usage of stream loads/writes. Or section 6.1, page 47 of
// https://akkadia.org/drepper/cpumemory.pdf .
static void StreamRead(void* src, void* dst, size_t size) {
  auto simd = static_cast<VectorType*>(src);
  VectorType a, b, c, d;
  (void)dst;

  memset(&a, 0, sizeof(a));
  memset(&b, 0, sizeof(b));
  memset(&c, 0, sizeof(c));
  memset(&d, 0, sizeof(d));

  for (size_t i = 0; i < size / sizeof(VectorType); i += 4) {
    VectorStreamLoadAsm(simd[i], a);
    VectorStreamLoadAsm(simd[i + 1], b);
    VectorStreamLoadAsm(simd[i + 2], c);
    VectorStreamLoadAsm(simd[i + 3], d);
  }

  benchmark::DoNotOptimize(a + b + c + d);
}

static void StreamWrite(void* src, void* dst, size_t size) {
  auto simd = static_cast<VectorType*>(dst);
  const VectorType ones = VectorSet(1);
  (void)src;

  for (size_t i = 0; i < size / sizeof(VectorType); i += 4) {
    VectorStreamWrite(&simd[i], ones);
    VectorStreamWrite(&simd[i + 1], ones);
    VectorStreamWrite(&simd[i + 2], ones);
    VectorStreamWrite(&simd[i + 3], ones);
  }
}

static void StreamReadWrite(void* src, void* dst, size_t size) {
  auto src_simd = static_cast<VectorType*>(src);
  auto dst_simd = static_cast<VectorType*>(dst);

  for (size_t i = 0; i < size / sizeof(VectorType); i += 4) {
    VectorStreamWrite(&dst_simd[i], VectorStreamLoad(&src_simd[i]));
    VectorStreamWrite(&dst_simd[i + 1], VectorStreamLoad(&src_simd[i + 1]));
    VectorStreamWrite(&dst_simd[i + 2], VectorStreamLoad(&src_simd[i + 2]));
    VectorStreamWrite(&dst_simd[i + 3], VectorStreamLoad(&src_simd[i + 3]));
  }
}

static void PlatformMemcpy(void* src, void* dst, size_t size) { memcpy(src, dst, size); }

using ApplyFn = decltype(Read);

template <ApplyFn Apply>
static void MemoryBandwidth(benchmark::State& state) {  // NOLINT non-const reference
  const size_t buffer_size = state.range(0);
  BufferPtr src, dst;

  ABORT_NOT_OK(AllocateBuffer(buffer_size, &dst));
  ABORT_NOT_OK(AllocateBuffer(buffer_size, &src));
  random_bytes(buffer_size, 0, src->mutable_data());

  while (state.KeepRunning()) {
    Apply(src->mutable_data(), dst->mutable_data(), buffer_size);
  }

  state.SetBytesProcessed(state.iterations() * buffer_size);
}

static void SetCacheBandwidthArgs(benchmark::internal::Benchmark* bench) {
  auto cache_sizes = {kL1Size, kL2Size, kL3Size};
  for (auto size : cache_sizes) {
    bench->Arg(size / 2);
    bench->Arg(size);
    bench->Arg(size * 2);
  }

  bench->ArgName("size");
}

BENCHMARK_TEMPLATE(MemoryBandwidth, Read)->Apply(SetCacheBandwidthArgs);

static void SetMemoryBandwidthArgs(benchmark::internal::Benchmark* bench) {
  // `UseRealTime` is required due to threads, otherwise the cumulative CPU time
  // is used which will skew the results by the number of threads.
  bench->Arg(kMemoryPerCore)->ThreadRange(1, kNumCores)->UseRealTime();
}

BENCHMARK_TEMPLATE(MemoryBandwidth, StreamRead)->Apply(SetMemoryBandwidthArgs);
BENCHMARK_TEMPLATE(MemoryBandwidth, StreamWrite)->Apply(SetMemoryBandwidthArgs);
BENCHMARK_TEMPLATE(MemoryBandwidth, StreamReadWrite)->Apply(SetMemoryBandwidthArgs);
BENCHMARK_TEMPLATE(MemoryBandwidth, PlatformMemcpy)->Apply(SetMemoryBandwidthArgs);

#endif  // _MSC_VER
#endif  // ARROW_WITH_BENCHMARKS_REFERENCE

static void ParallelMemoryCopy(benchmark::State& state) {  // NOLINT non-const reference
  const int64_t n_threads = state.range(0);
  const int64_t buffer_size = kMemoryPerCore;

  std::shared_ptr<Buffer> src, dst;
  ABORT_NOT_OK(AllocateBuffer(buffer_size, &src));
  ABORT_NOT_OK(AllocateBuffer(buffer_size, &dst));

  random_bytes(buffer_size, 0, src->mutable_data());

  while (state.KeepRunning()) {
    io::FixedSizeBufferWriter writer(dst);
    writer.set_memcopy_threads(static_cast<int>(n_threads));
    ABORT_NOT_OK(writer.Write(src->data(), src->size()));
  }

  state.SetBytesProcessed(int64_t(state.iterations()) * buffer_size);
}

BENCHMARK(ParallelMemoryCopy)
    ->RangeMultiplier(2)
    ->Range(1, kNumCores)
    ->ArgName("threads")
    ->UseRealTime();

}  // namespace arrow
<commit_msg>ARROW-5567: [C++] Fix build error of memory-benchmark<commit_after>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

#include <iostream>

#include "arrow/api.h"
#include "arrow/io/memory.h"
#include "arrow/testing/gtest_util.h"
#include "arrow/testing/util.h"
#include "arrow/util/cpu-info.h"
#include "arrow/util/sse-util.h"

#include "benchmark/benchmark.h"

#ifdef ARROW_HAVE_SSE4_2
namespace arrow {

using internal::CpuInfo;
static CpuInfo* cpu_info = CpuInfo::GetInstance();

static const int kNumCores = cpu_info->num_cores();
static const int64_t kL1Size = cpu_info->CacheSize(CpuInfo::L1_CACHE);
static const int64_t kL2Size = cpu_info->CacheSize(CpuInfo::L2_CACHE);
static const int64_t kL3Size = cpu_info->CacheSize(CpuInfo::L3_CACHE);

constexpr size_t kMemoryPerCore = 32 * 1024 * 1024;
using BufferPtr = std::shared_ptr<Buffer>;

#ifdef ARROW_WITH_BENCHMARKS_REFERENCE
#ifndef _MSC_VER

#ifdef ARROW_AVX512

using VectorType = __m512i;
#define VectorSet _mm512_set1_epi32
#define VectorLoad _mm512_stream_load_si512
#define VectorLoadAsm(SRC, DST) \
  asm volatile("vmovaps %[src], %[dst]" : [dst] "=v"(DST) : [src] "m"(SRC) :)
#define VectorStreamLoad _mm512_stream_load_si512
#define VectorStreamLoadAsm(SRC, DST) \
  asm volatile("vmovntdqa %[src], %[dst]" : [dst] "=v"(DST) : [src] "m"(SRC) :)
#define VectorStreamWrite _mm512_stream_si512

#else

#ifdef ARROW_AVX2

using VectorType = __m256i;
#define VectorSet _mm256_set1_epi32
#define VectorLoad _mm256_stream_load_si256
#define VectorLoadAsm(SRC, DST) \
  asm volatile("vmovaps %[src], %[dst]" : [dst] "=v"(DST) : [src] "m"(SRC) :)
#define VectorStreamLoad _mm256_stream_load_si256
#define VectorStreamLoadAsm(SRC, DST) \
  asm volatile("vmovntdqa %[src], %[dst]" : [dst] "=v"(DST) : [src] "m"(SRC) :)
#define VectorStreamWrite _mm256_stream_si256

#else  // ARROW_AVX2 not set

using VectorType = __m128i;
#define VectorSet _mm_set1_epi32
#define VectorLoad _mm_stream_load_si128
#define VectorLoadAsm(SRC, DST) \
  asm volatile("movaps %[src], %[dst]" : [dst] "=x"(DST) : [src] "m"(SRC) :)
#define VectorStreamLoad _mm_stream_load_si128
#define VectorStreamLoadAsm(SRC, DST) \
  asm volatile("movntdqa %[src], %[dst]" : [dst] "=x"(DST) : [src] "m"(SRC) :)
#define VectorStreamWrite _mm_stream_si128

#endif  // ARROW_AVX2
#endif  // ARROW_AVX512

static void Read(void* src, void* dst, size_t size) {
  const auto simd = static_cast<VectorType*>(src);
  VectorType a, b, c, d;
  (void)dst;

  for (size_t i = 0; i < size / sizeof(VectorType); i += 4) {
    VectorLoadAsm(simd[i], a);
    VectorLoadAsm(simd[i + 1], b);
    VectorLoadAsm(simd[i + 2], c);
    VectorLoadAsm(simd[i + 3], d);
  }

  memset(&a, 0, sizeof(a));
  memset(&b, 0, sizeof(b));
  memset(&c, 0, sizeof(c));
  memset(&d, 0, sizeof(d));

  benchmark::DoNotOptimize(a + b + c + d);
}

// See http://codearcana.com/posts/2013/05/18/achieving-maximum-memory-bandwidth.html
// for the usage of stream loads/writes. Or section 6.1, page 47 of
// https://akkadia.org/drepper/cpumemory.pdf .
static void StreamRead(void* src, void* dst, size_t size) {
  auto simd = static_cast<VectorType*>(src);
  VectorType a, b, c, d;
  (void)dst;

  memset(&a, 0, sizeof(a));
  memset(&b, 0, sizeof(b));
  memset(&c, 0, sizeof(c));
  memset(&d, 0, sizeof(d));

  for (size_t i = 0; i < size / sizeof(VectorType); i += 4) {
    VectorStreamLoadAsm(simd[i], a);
    VectorStreamLoadAsm(simd[i + 1], b);
    VectorStreamLoadAsm(simd[i + 2], c);
    VectorStreamLoadAsm(simd[i + 3], d);
  }

  benchmark::DoNotOptimize(a + b + c + d);
}

static void StreamWrite(void* src, void* dst, size_t size) {
  auto simd = static_cast<VectorType*>(dst);
  const VectorType ones = VectorSet(1);
  (void)src;

  for (size_t i = 0; i < size / sizeof(VectorType); i += 4) {
    VectorStreamWrite(&simd[i], ones);
    VectorStreamWrite(&simd[i + 1], ones);
    VectorStreamWrite(&simd[i + 2], ones);
    VectorStreamWrite(&simd[i + 3], ones);
  }
}

static void StreamReadWrite(void* src, void* dst, size_t size) {
  auto src_simd = static_cast<VectorType*>(src);
  auto dst_simd = static_cast<VectorType*>(dst);

  for (size_t i = 0; i < size / sizeof(VectorType); i += 4) {
    VectorStreamWrite(&dst_simd[i], VectorStreamLoad(&src_simd[i]));
    VectorStreamWrite(&dst_simd[i + 1], VectorStreamLoad(&src_simd[i + 1]));
    VectorStreamWrite(&dst_simd[i + 2], VectorStreamLoad(&src_simd[i + 2]));
    VectorStreamWrite(&dst_simd[i + 3], VectorStreamLoad(&src_simd[i + 3]));
  }
}

static void PlatformMemcpy(void* src, void* dst, size_t size) { memcpy(src, dst, size); }

using ApplyFn = decltype(Read);

template <ApplyFn Apply>
static void MemoryBandwidth(benchmark::State& state) {  // NOLINT non-const reference
  const size_t buffer_size = state.range(0);
  BufferPtr src, dst;

  ABORT_NOT_OK(AllocateBuffer(buffer_size, &dst));
  ABORT_NOT_OK(AllocateBuffer(buffer_size, &src));
  random_bytes(buffer_size, 0, src->mutable_data());

  while (state.KeepRunning()) {
    Apply(src->mutable_data(), dst->mutable_data(), buffer_size);
  }

  state.SetBytesProcessed(state.iterations() * buffer_size);
}

static void SetCacheBandwidthArgs(benchmark::internal::Benchmark* bench) {
  auto cache_sizes = {kL1Size, kL2Size, kL3Size};
  for (auto size : cache_sizes) {
    bench->Arg(size / 2);
    bench->Arg(size);
    bench->Arg(size * 2);
  }

  bench->ArgName("size");
}

BENCHMARK_TEMPLATE(MemoryBandwidth, Read)->Apply(SetCacheBandwidthArgs);

static void SetMemoryBandwidthArgs(benchmark::internal::Benchmark* bench) {
  // `UseRealTime` is required due to threads, otherwise the cumulative CPU time
  // is used which will skew the results by the number of threads.
  bench->Arg(kMemoryPerCore)->ThreadRange(1, kNumCores)->UseRealTime();
}

BENCHMARK_TEMPLATE(MemoryBandwidth, StreamRead)->Apply(SetMemoryBandwidthArgs);
BENCHMARK_TEMPLATE(MemoryBandwidth, StreamWrite)->Apply(SetMemoryBandwidthArgs);
BENCHMARK_TEMPLATE(MemoryBandwidth, StreamReadWrite)->Apply(SetMemoryBandwidthArgs);
BENCHMARK_TEMPLATE(MemoryBandwidth, PlatformMemcpy)->Apply(SetMemoryBandwidthArgs);

#endif  // _MSC_VER
#endif  // ARROW_WITH_BENCHMARKS_REFERENCE

static void ParallelMemoryCopy(benchmark::State& state) {  // NOLINT non-const reference
  const int64_t n_threads = state.range(0);
  const int64_t buffer_size = kMemoryPerCore;

  std::shared_ptr<Buffer> src, dst;
  ABORT_NOT_OK(AllocateBuffer(buffer_size, &src));
  ABORT_NOT_OK(AllocateBuffer(buffer_size, &dst));

  random_bytes(buffer_size, 0, src->mutable_data());

  while (state.KeepRunning()) {
    io::FixedSizeBufferWriter writer(dst);
    writer.set_memcopy_threads(static_cast<int>(n_threads));
    ABORT_NOT_OK(writer.Write(src->data(), src->size()));
  }

  state.SetBytesProcessed(int64_t(state.iterations()) * buffer_size);
}

BENCHMARK(ParallelMemoryCopy)
    ->RangeMultiplier(2)
    ->Range(1, kNumCores)
    ->ArgName("threads")
    ->UseRealTime();

}  // namespace arrow
#endif  // ARROW_HAVE_SSE4_2
<|endoftext|>


<commit_before>#include <cstdlib>
#include <iostream>
#include <ios>

#include "hext/parser.h"

int main(int argc, char ** argv)
{
  // todo: boost::program_options
  if( argc < 2 )
  {
    std::cout << "Usage: " << argv[0] << " [rules.hext]" << std::endl;
    return EXIT_SUCCESS;
  }

  try
  {
    auto rules = hext::parser::parse_file(argv[1]);
    for( const auto& rule : rules )
    {
      std::cout << "root-rule with tag_name: " << rule.get_tag_name() << std::endl;
    }
  }
  catch( std::ios_base::failure& e )
  {
    std::cerr << e.what() << '\n';
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}

<commit_msg>print rule tree after parsing<commit_after>#include <cstdlib>
#include <iostream>
#include <ios>

#include "hext/parser.h"
#include "hext/print.h"

int main(int argc, char ** argv)
{
  // todo: boost::program_options
  if( argc < 2 )
  {
    std::cout << "Usage: " << argv[0] << " [rules.hext]" << std::endl;
    return EXIT_SUCCESS;
  }

  try
  {
    auto rules = hext::parser::parse_file(argv[1]);
    for(const auto& r : rules)
    {
      print_rule(r);
    }
  }
  catch( std::ios_base::failure& e )
  {
    std::cerr << e.what() << '\n';
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}

<|endoftext|>