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

#include "chrome/browser/extensions/extension_message_service.h"
#include "chrome/common/render_messages.h"
#include "chrome/renderer/extensions/event_bindings.h"
#include "chrome/renderer/extensions/renderer_extension_bindings.h"
#include "chrome/test/render_view_test.h"
#include "testing/gtest/include/gtest/gtest.h"

static void DispatchOnConnect(int source_port_id, const std::string& name,
                              const std::string& tab_json) {
  ListValue args;
  args.Set(0, Value::CreateIntegerValue(source_port_id));
  args.Set(1, Value::CreateStringValue(name));
  args.Set(2, Value::CreateStringValue(tab_json));
  args.Set(3, Value::CreateStringValue(""));  // extension ID is empty for tests
  args.Set(4, Value::CreateStringValue(""));  // extension ID is empty for tests
  RendererExtensionBindings::Invoke(
      ExtensionMessageService::kDispatchOnConnect, args, NULL, false, GURL());
}

static void DispatchOnDisconnect(int source_port_id) {
  ListValue args;
  args.Set(0, Value::CreateIntegerValue(source_port_id));
  RendererExtensionBindings::Invoke(
      ExtensionMessageService::kDispatchOnDisconnect, args, NULL, false,
      GURL());
}

static void DispatchOnMessage(const std::string& message, int source_port_id) {
  ListValue args;
  args.Set(0, Value::CreateStringValue(message));
  args.Set(1, Value::CreateIntegerValue(source_port_id));
  RendererExtensionBindings::Invoke(
      ExtensionMessageService::kDispatchOnMessage, args, NULL, false, GURL());
}

// Tests that the bindings for opening a channel to an extension and sending
// and receiving messages through that channel all works.
TEST_F(RenderViewTest, DISABLED_ExtensionMessagesOpenChannel) {
  render_thread_.sink().ClearMessages();
  LoadHTML("");
  ExecuteJavaScript(
    "var port = chrome.extension.connect({name:'testName'});"
    "port.onMessage.addListener(doOnMessage);"
    "port.postMessage({message: 'content ready'});"
    "function doOnMessage(msg, port) {"
    "  alert('content got: ' + msg.val);"
    "}");

  // Verify that we opened a channel and sent a message through it.
  const IPC::Message* open_channel_msg =
      render_thread_.sink().GetUniqueMessageMatching(
          ViewHostMsg_OpenChannelToExtension::ID);
  ASSERT_TRUE(open_channel_msg);
  void* iter = IPC::SyncMessage::GetDataIterator(open_channel_msg);
  ViewHostMsg_OpenChannelToExtension::SendParam open_params;
  ASSERT_TRUE(IPC::ReadParam(open_channel_msg, &iter, &open_params));
  EXPECT_EQ("testName", open_params.d);

  const IPC::Message* post_msg =
      render_thread_.sink().GetUniqueMessageMatching(
          ViewHostMsg_ExtensionPostMessage::ID);
  ASSERT_TRUE(post_msg);
  ViewHostMsg_ExtensionPostMessage::Param post_params;
  ViewHostMsg_ExtensionPostMessage::Read(post_msg, &post_params);
  EXPECT_EQ("{\"message\":\"content ready\"}", post_params.b);

  // Now simulate getting a message back from the other side.
  render_thread_.sink().ClearMessages();
  const int kPortId = 0;
  DispatchOnMessage("{\"val\": 42}", kPortId);

  // Verify that we got it.
  const IPC::Message* alert_msg =
      render_thread_.sink().GetUniqueMessageMatching(
          ViewHostMsg_RunJavaScriptMessage::ID);
  ASSERT_TRUE(alert_msg);
  iter = IPC::SyncMessage::GetDataIterator(alert_msg);
  ViewHostMsg_RunJavaScriptMessage::SendParam alert_param;
  ASSERT_TRUE(IPC::ReadParam(alert_msg, &iter, &alert_param));
  EXPECT_EQ(L"content got: 42", alert_param.a);
}

// Tests that the bindings for handling a new channel connection and channel
// closing all works.
TEST_F(RenderViewTest, DISABLED_ExtensionMessagesOnConnect) {
  LoadHTML("");
  ExecuteJavaScript(
    "chrome.extension.onConnect.addListener(function (port) {"
    "  port.test = 24;"
    "  port.onMessage.addListener(doOnMessage);"
    "  port.onDisconnect.addListener(doOnDisconnect);"
    "  port.postMessage({message: 'onconnect from ' + port.tab.url + "
    "                   ' name ' + port.name});"
    "});"
    "function doOnMessage(msg, port) {"
    "  alert('got: ' + msg.val);"
    "}"
    "function doOnDisconnect(port) {"
    "  alert('disconnected: ' + port.test);"
    "}");

  render_thread_.sink().ClearMessages();

  // Simulate a new connection being opened.
  const int kPortId = 0;
  const std::string kPortName = "testName";
  DispatchOnConnect(kPortId, kPortName, "{\"url\":\"foo://bar\"}");

  // Verify that we handled the new connection by posting a message.
  const IPC::Message* post_msg =
      render_thread_.sink().GetUniqueMessageMatching(
          ViewHostMsg_ExtensionPostMessage::ID);
  ASSERT_TRUE(post_msg);
  ViewHostMsg_ExtensionPostMessage::Param post_params;
  ViewHostMsg_ExtensionPostMessage::Read(post_msg, &post_params);
  std::string expected_msg =
      "{\"message\":\"onconnect from foo://bar name " + kPortName + "\"}";
  EXPECT_EQ(expected_msg, post_params.b);

  // Now simulate getting a message back from the channel opener.
  render_thread_.sink().ClearMessages();
  DispatchOnMessage("{\"val\": 42}", kPortId);

  // Verify that we got it.
  const IPC::Message* alert_msg =
      render_thread_.sink().GetUniqueMessageMatching(
          ViewHostMsg_RunJavaScriptMessage::ID);
  ASSERT_TRUE(alert_msg);
  void* iter = IPC::SyncMessage::GetDataIterator(alert_msg);
  ViewHostMsg_RunJavaScriptMessage::SendParam alert_param;
  ASSERT_TRUE(IPC::ReadParam(alert_msg, &iter, &alert_param));
  EXPECT_EQ(L"got: 42", alert_param.a);

  // Now simulate the channel closing.
  render_thread_.sink().ClearMessages();
  DispatchOnDisconnect(kPortId);

  // Verify that we got it.
  alert_msg =
      render_thread_.sink().GetUniqueMessageMatching(
          ViewHostMsg_RunJavaScriptMessage::ID);
  ASSERT_TRUE(alert_msg);
  iter = IPC::SyncMessage::GetDataIterator(alert_msg);
  ASSERT_TRUE(IPC::ReadParam(alert_msg, &iter, &alert_param));
  EXPECT_EQ(L"disconnected: 24", alert_param.a);
}
<commit_msg>It seems all RenderView tests have issues. I'll try reverting last significant RenderView change and see if that helps.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/extension_message_service.h"
#include "chrome/common/render_messages.h"
#include "chrome/renderer/extensions/event_bindings.h"
#include "chrome/renderer/extensions/renderer_extension_bindings.h"
#include "chrome/test/render_view_test.h"
#include "testing/gtest/include/gtest/gtest.h"

static void DispatchOnConnect(int source_port_id, const std::string& name,
                              const std::string& tab_json) {
  ListValue args;
  args.Set(0, Value::CreateIntegerValue(source_port_id));
  args.Set(1, Value::CreateStringValue(name));
  args.Set(2, Value::CreateStringValue(tab_json));
  args.Set(3, Value::CreateStringValue(""));  // extension ID is empty for tests
  args.Set(4, Value::CreateStringValue(""));  // extension ID is empty for tests
  RendererExtensionBindings::Invoke(
      ExtensionMessageService::kDispatchOnConnect, args, NULL, false, GURL());
}

static void DispatchOnDisconnect(int source_port_id) {
  ListValue args;
  args.Set(0, Value::CreateIntegerValue(source_port_id));
  RendererExtensionBindings::Invoke(
      ExtensionMessageService::kDispatchOnDisconnect, args, NULL, false,
      GURL());
}

static void DispatchOnMessage(const std::string& message, int source_port_id) {
  ListValue args;
  args.Set(0, Value::CreateStringValue(message));
  args.Set(1, Value::CreateIntegerValue(source_port_id));
  RendererExtensionBindings::Invoke(
      ExtensionMessageService::kDispatchOnMessage, args, NULL, false, GURL());
}

// Tests that the bindings for opening a channel to an extension and sending
// and receiving messages through that channel all works.
TEST_F(RenderViewTest, ExtensionMessagesOpenChannel) {
  render_thread_.sink().ClearMessages();
  LoadHTML("");
  ExecuteJavaScript(
    "var port = chrome.extension.connect({name:'testName'});"
    "port.onMessage.addListener(doOnMessage);"
    "port.postMessage({message: 'content ready'});"
    "function doOnMessage(msg, port) {"
    "  alert('content got: ' + msg.val);"
    "}");

  // Verify that we opened a channel and sent a message through it.
  const IPC::Message* open_channel_msg =
      render_thread_.sink().GetUniqueMessageMatching(
          ViewHostMsg_OpenChannelToExtension::ID);
  ASSERT_TRUE(open_channel_msg);
  void* iter = IPC::SyncMessage::GetDataIterator(open_channel_msg);
  ViewHostMsg_OpenChannelToExtension::SendParam open_params;
  ASSERT_TRUE(IPC::ReadParam(open_channel_msg, &iter, &open_params));
  EXPECT_EQ("testName", open_params.d);

  const IPC::Message* post_msg =
      render_thread_.sink().GetUniqueMessageMatching(
          ViewHostMsg_ExtensionPostMessage::ID);
  ASSERT_TRUE(post_msg);
  ViewHostMsg_ExtensionPostMessage::Param post_params;
  ViewHostMsg_ExtensionPostMessage::Read(post_msg, &post_params);
  EXPECT_EQ("{\"message\":\"content ready\"}", post_params.b);

  // Now simulate getting a message back from the other side.
  render_thread_.sink().ClearMessages();
  const int kPortId = 0;
  DispatchOnMessage("{\"val\": 42}", kPortId);

  // Verify that we got it.
  const IPC::Message* alert_msg =
      render_thread_.sink().GetUniqueMessageMatching(
          ViewHostMsg_RunJavaScriptMessage::ID);
  ASSERT_TRUE(alert_msg);
  iter = IPC::SyncMessage::GetDataIterator(alert_msg);
  ViewHostMsg_RunJavaScriptMessage::SendParam alert_param;
  ASSERT_TRUE(IPC::ReadParam(alert_msg, &iter, &alert_param));
  EXPECT_EQ(L"content got: 42", alert_param.a);
}

// Tests that the bindings for handling a new channel connection and channel
// closing all works.
TEST_F(RenderViewTest, ExtensionMessagesOnConnect) {
  LoadHTML("");
  ExecuteJavaScript(
    "chrome.extension.onConnect.addListener(function (port) {"
    "  port.test = 24;"
    "  port.onMessage.addListener(doOnMessage);"
    "  port.onDisconnect.addListener(doOnDisconnect);"
    "  port.postMessage({message: 'onconnect from ' + port.tab.url + "
    "                   ' name ' + port.name});"
    "});"
    "function doOnMessage(msg, port) {"
    "  alert('got: ' + msg.val);"
    "}"
    "function doOnDisconnect(port) {"
    "  alert('disconnected: ' + port.test);"
    "}");

  render_thread_.sink().ClearMessages();

  // Simulate a new connection being opened.
  const int kPortId = 0;
  const std::string kPortName = "testName";
  DispatchOnConnect(kPortId, kPortName, "{\"url\":\"foo://bar\"}");

  // Verify that we handled the new connection by posting a message.
  const IPC::Message* post_msg =
      render_thread_.sink().GetUniqueMessageMatching(
          ViewHostMsg_ExtensionPostMessage::ID);
  ASSERT_TRUE(post_msg);
  ViewHostMsg_ExtensionPostMessage::Param post_params;
  ViewHostMsg_ExtensionPostMessage::Read(post_msg, &post_params);
  std::string expected_msg =
      "{\"message\":\"onconnect from foo://bar name " + kPortName + "\"}";
  EXPECT_EQ(expected_msg, post_params.b);

  // Now simulate getting a message back from the channel opener.
  render_thread_.sink().ClearMessages();
  DispatchOnMessage("{\"val\": 42}", kPortId);

  // Verify that we got it.
  const IPC::Message* alert_msg =
      render_thread_.sink().GetUniqueMessageMatching(
          ViewHostMsg_RunJavaScriptMessage::ID);
  ASSERT_TRUE(alert_msg);
  void* iter = IPC::SyncMessage::GetDataIterator(alert_msg);
  ViewHostMsg_RunJavaScriptMessage::SendParam alert_param;
  ASSERT_TRUE(IPC::ReadParam(alert_msg, &iter, &alert_param));
  EXPECT_EQ(L"got: 42", alert_param.a);

  // Now simulate the channel closing.
  render_thread_.sink().ClearMessages();
  DispatchOnDisconnect(kPortId);

  // Verify that we got it.
  alert_msg =
      render_thread_.sink().GetUniqueMessageMatching(
          ViewHostMsg_RunJavaScriptMessage::ID);
  ASSERT_TRUE(alert_msg);
  iter = IPC::SyncMessage::GetDataIterator(alert_msg);
  ASSERT_TRUE(IPC::ReadParam(alert_msg, &iter, &alert_param));
  EXPECT_EQ(L"disconnected: 24", alert_param.a);
}
<|endoftext|>


<commit_before>// Copyright 2020 The Google Research Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     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 "test_util.h"

#include <functional>
#include <iostream>

#include "definitions.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"

namespace automl_zero {

using ::std::function;  // NOLINT;
using ::std::pair;  // NOLINT;
using ::std::unordered_set;  // NOLINT;
using ::testing::Pair;
using ::testing::UnorderedElementsAre;

IntegerT cycle_up_to_five() {
  static IntegerT x = 0;
  return x++ % 5;
}

TEST(IsEventuallyTest, CorrectAnswer) {
  EXPECT_TRUE(IsEventually(
      function<IntegerT()>(cycle_up_to_five),
      {0, 1, 2, 3, 4}, {0, 1, 2, 3, 4}));
}

TEST(IsEventuallyTest, DisallowedNumber) {
  EXPECT_FALSE(IsEventually(
      function<IntegerT()>(cycle_up_to_five),
      {0, 1, 2, 4}, {0, 1, 2, 3, 4}));
}

TEST(IsEventuallyTest, MissingRequiredNumber) {
  EXPECT_FALSE(IsEventually(
      function<IntegerT()>(cycle_up_to_five),
      {0, 1, 2, 3, 4}, {0, 1, 2, 3, 4, 5}));
}

TEST(IsEventuallyTest, NotRequiredNumber) {
  EXPECT_TRUE(IsEventually(
      function<IntegerT()>(cycle_up_to_five),
      {0, 1, 2, 3, 4}, {0, 1, 2, 4}));
}

TEST(IsEventuallyTest, MissingAllowedNumber) {
  EXPECT_TRUE(IsEventually(
      function<IntegerT()>(cycle_up_to_five),
      {0, 1, 2, 3, 4, 5}, {0, 1, 2, 3, 4}));
}

TEST(IsNeverTest, ExcludedValue) {
  EXPECT_FALSE(IsNever(
      function<IntegerT()>(cycle_up_to_five),
      {3}, 3.0));
}

TEST(IsNeverTest, NotExcludedValue) {
  EXPECT_TRUE(IsNever(
      function<IntegerT()>(cycle_up_to_five),
      {6}, 3.0));
}

TEST(RangeTest, WorksCorrectly) {
  EXPECT_THAT(Range<IntegerT>(0, 5), UnorderedElementsAre(0, 1, 2, 3, 4));
}

TEST(CartesianProductTest, WorksCorrectly) {
  EXPECT_THAT(CartesianProduct(Range<IntegerT>(0, 3),
                               Range<IntegerT>(3, 5)),
              UnorderedElementsAre(Pair(0, 3), Pair(0, 4),
                                   Pair(1, 3), Pair(1, 4),
                                   Pair(2, 3), Pair(2, 4)));
}

}  // namespace automl_zero
<commit_msg>Internal change<commit_after>// Copyright 2020 The Google Research Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     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 "test_util.h"

#include <functional>
#include <iostream>

#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/container/node_hash_set.h"
#include "definitions.h"

namespace automl_zero {

using ::std::function;  // NOLINT;
using ::std::pair;  // NOLINT;
// NOLINT;
using ::testing::Pair;
using ::testing::UnorderedElementsAre;

IntegerT cycle_up_to_five() {
  static IntegerT x = 0;
  return x++ % 5;
}

TEST(IsEventuallyTest, CorrectAnswer) {
  EXPECT_TRUE(IsEventually(
      function<IntegerT()>(cycle_up_to_five),
      {0, 1, 2, 3, 4}, {0, 1, 2, 3, 4}));
}

TEST(IsEventuallyTest, DisallowedNumber) {
  EXPECT_FALSE(IsEventually(
      function<IntegerT()>(cycle_up_to_five),
      {0, 1, 2, 4}, {0, 1, 2, 3, 4}));
}

TEST(IsEventuallyTest, MissingRequiredNumber) {
  EXPECT_FALSE(IsEventually(
      function<IntegerT()>(cycle_up_to_five),
      {0, 1, 2, 3, 4}, {0, 1, 2, 3, 4, 5}));
}

TEST(IsEventuallyTest, NotRequiredNumber) {
  EXPECT_TRUE(IsEventually(
      function<IntegerT()>(cycle_up_to_five),
      {0, 1, 2, 3, 4}, {0, 1, 2, 4}));
}

TEST(IsEventuallyTest, MissingAllowedNumber) {
  EXPECT_TRUE(IsEventually(
      function<IntegerT()>(cycle_up_to_five),
      {0, 1, 2, 3, 4, 5}, {0, 1, 2, 3, 4}));
}

TEST(IsNeverTest, ExcludedValue) {
  EXPECT_FALSE(IsNever(
      function<IntegerT()>(cycle_up_to_five),
      {3}, 3.0));
}

TEST(IsNeverTest, NotExcludedValue) {
  EXPECT_TRUE(IsNever(
      function<IntegerT()>(cycle_up_to_five),
      {6}, 3.0));
}

TEST(RangeTest, WorksCorrectly) {
  EXPECT_THAT(Range<IntegerT>(0, 5), UnorderedElementsAre(0, 1, 2, 3, 4));
}

TEST(CartesianProductTest, WorksCorrectly) {
  EXPECT_THAT(CartesianProduct(Range<IntegerT>(0, 3),
                               Range<IntegerT>(3, 5)),
              UnorderedElementsAre(Pair(0, 3), Pair(0, 4),
                                   Pair(1, 3), Pair(1, 4),
                                   Pair(2, 3), Pair(2, 4)));
}

}  // namespace automl_zero
<|endoftext|>


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

#include "chrome/browser/extensions/extension_apitest.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Toolstrip) {
  ASSERT_TRUE(RunExtensionTest("toolstrip")) << message_;
}
<commit_msg>TBR: rafaelw,leiz disable a ExtensionApiTest.Toolstrip which is flaky on linux<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/extension_apitest.h"

// TODO(rafaelw,erikkay) disabled due to flakiness
// BUG=22668 (probably the same bug)
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Toolstrip) {
  ASSERT_TRUE(RunExtensionTest("toolstrip")) << message_;
}
<|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 "base/command_line.h"
#include "base/path_service.h"
#include "base/process/launch.h"
#include "base/rand_util.h"
#include "base/strings/stringprintf.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/media/webrtc_browsertest_base.h"
#include "chrome/browser/media/webrtc_browsertest_common.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/ui_test_utils.h"
#include "chrome/test/ui/ui_test.h"
#include "content/public/test/browser_test_utils.h"
#include "net/test/python_utils.h"

// You need this solution to run this test. The solution will download appengine
// and the apprtc code for you.
const char kAdviseOnGclientSolution[] =
    "You need to add this solution to your .gclient to run this test:\n"
    "{\n"
    "  \"name\"        : \"webrtc.DEPS\",\n"
    "  \"url\"         : \"svn://svn.chromium.org/chrome/trunk/deps/"
    "third_party/webrtc/webrtc.DEPS\",\n"
    "}";
const char kTitlePageOfAppEngineAdminPage[] = "Instances";

// WebRTC-AppRTC integration test. Requires a real webcam and microphone
// on the running system. This test is not meant to run in the main browser
// test suite since normal tester machines do not have webcams.
//
// This test will bring up a AppRTC instance on localhost and verify that the
// call gets up when connecting to the same room from two tabs in a browser.
class WebrtcApprtcBrowserTest : public WebRtcTestBase {
 public:
  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    EXPECT_FALSE(command_line->HasSwitch(
        switches::kUseFakeDeviceForMediaStream));
    EXPECT_FALSE(command_line->HasSwitch(
        switches::kUseFakeUIForMediaStream));

    // The video playback will not work without a GPU, so force its use here.
    command_line->AppendSwitch(switches::kUseGpuInTests);
  }

 protected:
  bool LaunchApprtcInstanceOnLocalhost() {
    base::FilePath appengine_dev_appserver =
        GetSourceDir().Append(
            FILE_PATH_LITERAL("../google_appengine/dev_appserver.py"));
    if (!base::PathExists(appengine_dev_appserver)) {
      LOG(ERROR) << "Missing appengine sdk at " <<
          appengine_dev_appserver.value() << ". " << kAdviseOnGclientSolution;
      return false;
    }

    base::FilePath apprtc_dir =
        GetSourceDir().Append(
            FILE_PATH_LITERAL("third_party/webrtc_apprtc/apprtc"));
    if (!base::PathExists(apprtc_dir)) {
      LOG(ERROR) << "Missing AppRTC code at " <<
          apprtc_dir.value() << ". " << kAdviseOnGclientSolution;
      return false;
    }

    CommandLine command_line(CommandLine::NO_PROGRAM);
    EXPECT_TRUE(GetPythonCommand(&command_line));

    command_line.AppendArgPath(appengine_dev_appserver);
    command_line.AppendArgPath(apprtc_dir);
    command_line.AppendArg("--port=9999");
    command_line.AppendArg("--admin_port=9998");
    command_line.AppendArg("--skip_sdk_update_check");

    LOG(INFO) << "Running " << command_line.GetCommandLineString();
    return base::LaunchProcess(command_line, base::LaunchOptions(),
                               &dev_appserver_);
  }

  bool LocalApprtcInstanceIsUp() {
    // Load the admin page and see if we manage to load it right.
    ui_test_utils::NavigateToURL(browser(), GURL("localhost:9998"));
    content::WebContents* tab_contents =
        browser()->tab_strip_model()->GetActiveWebContents();
    std::string javascript =
        "window.domAutomationController.send(document.title)";
    std::string result;
    if (!content::ExecuteScriptAndExtractString(tab_contents, javascript,
                                                &result))
      return false;

    return result == kTitlePageOfAppEngineAdminPage;
  }

  bool StopApprtcInstance() {
    return base::KillProcess(dev_appserver_, 0, false);
  }

  bool WaitForCallToComeUp(content::WebContents* tab_contents) {
    // Apprtc will set remoteVideo.style.opacity to 1 when the call comes up.
    std::string javascript =
        "window.domAutomationController.send(remoteVideo.style.opacity)";
    return PollingWaitUntil(javascript, "1", tab_contents);
  }

  base::FilePath GetSourceDir() {
    base::FilePath source_dir;
    PathService::Get(base::DIR_SOURCE_ROOT, &source_dir);
    return source_dir;
  }

 private:
  base::ProcessHandle dev_appserver_;
};

#if defined (OS_WIN) || defined(OS_MACOSX)
#define MAYBE_MANUAL_WorksOnApprtc DISABLED_MANUAL_WorksOnApprtc
#else
#define MAYBE_MANUAL_WorksOnApprtc MANUAL_WorksOnApprtc
#endif

IN_PROC_BROWSER_TEST_F(WebrtcApprtcBrowserTest, MAYBE_MANUAL_WorksOnApprtc) {
  if (!LaunchApprtcInstanceOnLocalhost()) {
    // TODO(phoglund): assert on this once everything is in place on the bots.
    return;
  }
  while (!LocalApprtcInstanceIsUp())
    LOG(INFO) << "Waiting for AppRTC to come up...";

  GURL room_url = GURL(base::StringPrintf("localhost:9999?r=room_%d",
                                          base::RandInt(0, 65536)));

  chrome::AddBlankTabAt(browser(), -1, true);
  content::WebContents* left_tab = OpenPageAndAcceptUserMedia(room_url);
  chrome::AddBlankTabAt(browser(), -1, true);
  content::WebContents* right_tab = OpenPageAndAcceptUserMedia(room_url);

  ASSERT_TRUE(WaitForCallToComeUp(left_tab));
  ASSERT_TRUE(WaitForCallToComeUp(right_tab));

  ASSERT_TRUE(StopApprtcInstance());
}
<commit_msg>Now looking at AppRTC from the out/ directory.<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 "base/command_line.h"
#include "base/path_service.h"
#include "base/process/launch.h"
#include "base/rand_util.h"
#include "base/strings/stringprintf.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/media/webrtc_browsertest_base.h"
#include "chrome/browser/media/webrtc_browsertest_common.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/ui_test_utils.h"
#include "chrome/test/ui/ui_test.h"
#include "content/public/test/browser_test_utils.h"
#include "net/test/python_utils.h"

// You need this solution to run this test. The solution will download appengine
// and the apprtc code for you.
const char kAdviseOnGclientSolution[] =
    "You need to add this solution to your .gclient to run this test:\n"
    "{\n"
    "  \"name\"        : \"webrtc.DEPS\",\n"
    "  \"url\"         : \"svn://svn.chromium.org/chrome/trunk/deps/"
    "third_party/webrtc/webrtc.DEPS\",\n"
    "}";
const char kTitlePageOfAppEngineAdminPage[] = "Instances";

// WebRTC-AppRTC integration test. Requires a real webcam and microphone
// on the running system. This test is not meant to run in the main browser
// test suite since normal tester machines do not have webcams.
//
// This test will bring up a AppRTC instance on localhost and verify that the
// call gets up when connecting to the same room from two tabs in a browser.
class WebrtcApprtcBrowserTest : public WebRtcTestBase {
 public:
  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    EXPECT_FALSE(command_line->HasSwitch(
        switches::kUseFakeDeviceForMediaStream));
    EXPECT_FALSE(command_line->HasSwitch(
        switches::kUseFakeUIForMediaStream));

    // The video playback will not work without a GPU, so force its use here.
    command_line->AppendSwitch(switches::kUseGpuInTests);
  }

 protected:
  bool LaunchApprtcInstanceOnLocalhost() {
    base::FilePath appengine_dev_appserver =
        GetSourceDir().Append(
            FILE_PATH_LITERAL("../google_appengine/dev_appserver.py"));
    if (!base::PathExists(appengine_dev_appserver)) {
      LOG(ERROR) << "Missing appengine sdk at " <<
          appengine_dev_appserver.value() << ". " << kAdviseOnGclientSolution;
      return false;
    }

    base::FilePath apprtc_dir =
        GetSourceDir().Append(FILE_PATH_LITERAL("out/apprtc"));
    if (!base::PathExists(apprtc_dir)) {
      LOG(ERROR) << "Missing AppRTC code at " <<
          apprtc_dir.value() << ". " << kAdviseOnGclientSolution;
      return false;
    }

    CommandLine command_line(CommandLine::NO_PROGRAM);
    EXPECT_TRUE(GetPythonCommand(&command_line));

    command_line.AppendArgPath(appengine_dev_appserver);
    command_line.AppendArgPath(apprtc_dir);
    command_line.AppendArg("--port=9999");
    command_line.AppendArg("--admin_port=9998");
    command_line.AppendArg("--skip_sdk_update_check");

    LOG(INFO) << "Running " << command_line.GetCommandLineString();
    return base::LaunchProcess(command_line, base::LaunchOptions(),
                               &dev_appserver_);
  }

  bool LocalApprtcInstanceIsUp() {
    // Load the admin page and see if we manage to load it right.
    ui_test_utils::NavigateToURL(browser(), GURL("localhost:9998"));
    content::WebContents* tab_contents =
        browser()->tab_strip_model()->GetActiveWebContents();
    std::string javascript =
        "window.domAutomationController.send(document.title)";
    std::string result;
    if (!content::ExecuteScriptAndExtractString(tab_contents, javascript,
                                                &result))
      return false;

    return result == kTitlePageOfAppEngineAdminPage;
  }

  bool StopApprtcInstance() {
    return base::KillProcess(dev_appserver_, 0, false);
  }

  bool WaitForCallToComeUp(content::WebContents* tab_contents) {
    // Apprtc will set remoteVideo.style.opacity to 1 when the call comes up.
    std::string javascript =
        "window.domAutomationController.send(remoteVideo.style.opacity)";
    return PollingWaitUntil(javascript, "1", tab_contents);
  }

  base::FilePath GetSourceDir() {
    base::FilePath source_dir;
    PathService::Get(base::DIR_SOURCE_ROOT, &source_dir);
    return source_dir;
  }

 private:
  base::ProcessHandle dev_appserver_;
};

#if defined (OS_WIN) || defined(OS_MACOSX)
#define MAYBE_MANUAL_WorksOnApprtc DISABLED_MANUAL_WorksOnApprtc
#else
#define MAYBE_MANUAL_WorksOnApprtc MANUAL_WorksOnApprtc
#endif

IN_PROC_BROWSER_TEST_F(WebrtcApprtcBrowserTest, MAYBE_MANUAL_WorksOnApprtc) {
  ASSERT_TRUE(LaunchApprtcInstanceOnLocalhost());
  while (!LocalApprtcInstanceIsUp())
    LOG(INFO) << "Waiting for AppRTC to come up...";

  GURL room_url = GURL(base::StringPrintf("localhost:9999?r=room_%d",
                                          base::RandInt(0, 65536)));

  chrome::AddBlankTabAt(browser(), -1, true);
  content::WebContents* left_tab = OpenPageAndAcceptUserMedia(room_url);
  chrome::AddBlankTabAt(browser(), -1, true);
  content::WebContents* right_tab = OpenPageAndAcceptUserMedia(room_url);

  ASSERT_TRUE(WaitForCallToComeUp(left_tab));
  ASSERT_TRUE(WaitForCallToComeUp(right_tab));

  ASSERT_TRUE(StopApprtcInstance());
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: toolbar.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: os $ $Date: 2002-05-07 13:49:06 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _BIB_TOOLBAR_HXX
#define _BIB_TOOLBAR_HXX

#ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_
#include <com/sun/star/frame/XController.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_
#include <com/sun/star/frame/XStatusListener.hpp>
#endif

#ifndef _SV_TOOLBOX_HXX //autogen wg. ToolBox
#include <vcl/toolbox.hxx>
#endif

#ifndef _SV_LSTBOX_HXX //autogen wg. ::com::sun::star::form
#include <vcl/lstbox.hxx>
#endif

#ifndef _SV_EDIT_HXX //autogen wg. Edit
#include <vcl/edit.hxx>
#endif

#ifndef _SV_FIXED_HXX //autogen wg. FixedText
#include <vcl/fixed.hxx>
#endif

#ifndef _SVARRAY_HXX
#include <svtools/svarray.hxx>
#endif

#ifndef _SV_TIMER_HXX //autogen wg. Timer
#include <vcl/timer.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx> // helper for implementations
#endif

class BibDataManager;
class BibToolBar;

class BibToolBarListener: public cppu::WeakImplHelper1 < ::com::sun::star::frame::XStatusListener>
{
private:

    sal_uInt16      nIndex;
    rtl::OUString           aCommand;

protected:

    BibToolBar      *pToolBar;

public:

    BibToolBarListener(BibToolBar *pTB,rtl::OUString aStr,sal_uInt16 nId);
    ~BibToolBarListener();

    rtl::OUString           GetCommand();
    void            SetCommand(const rtl::OUString& aStr);

    sal_uInt16          GetIndex();
    void            SetIndex(sal_uInt16 nIndex);

    // ::com::sun::star::lang::XEventListener
    // we do not hold References to dispatches, so there is nothing to do on disposal
    virtual void    SAL_CALL disposing(const ::com::sun::star::lang::EventObject& Source)
                                            throw( ::com::sun::star::uno::RuntimeException ){};

    // ::com::sun::star::frame::XStatusListener
    virtual void    SAL_CALL statusChanged(const ::com::sun::star::frame::FeatureStateEvent& Event)
                                            throw( ::com::sun::star::uno::RuntimeException );

};

class BibTBListBoxListener: public BibToolBarListener
{
public:

    BibTBListBoxListener(BibToolBar *pTB,rtl::OUString aStr,sal_uInt16 nId);
    ~BibTBListBoxListener();

    virtual void    SAL_CALL statusChanged(const ::com::sun::star::frame::FeatureStateEvent& Event)
                                            throw( ::com::sun::star::uno::RuntimeException );

};

class BibTBEditListener: public BibToolBarListener
{
public:

    BibTBEditListener(BibToolBar *pTB,rtl::OUString aStr,sal_uInt16 nId);
    ~BibTBEditListener();

    virtual void    SAL_CALL statusChanged(const ::com::sun::star::frame::FeatureStateEvent& Event)
                                            throw( ::com::sun::star::uno::RuntimeException );

};

class BibTBQueryMenuListener:   public BibToolBarListener
{
public:

    BibTBQueryMenuListener(BibToolBar *pTB,rtl::OUString aStr,sal_uInt16 nId);
    ~BibTBQueryMenuListener();

    virtual void    SAL_CALL statusChanged(const ::com::sun::star::frame::FeatureStateEvent& Event)
                                            throw( ::com::sun::star::uno::RuntimeException );

};

typedef ::com::sun::star::uno::Reference< ::com::sun::star::frame::XStatusListener>* BibToolBarListenerPtr;
SV_DECL_PTRARR_DEL( BibToolBarListenerArr, BibToolBarListenerPtr, 4, 4 );

class BibToolBar:   public ToolBox
{
    private:

        BibToolBarListenerArr   aListenerArr;
        ::com::sun::star::uno::Reference< ::com::sun::star::frame::XController >            xController;
        Timer                   aTimer;
        Timer                   aMenuTimer;
        ImageList               aImgLst;
        ImageList               aImgLstHC;
        FixedText               aFtSource;
        ListBox                 aLBSource;
        FixedText               aFtQuery;
        Edit                    aEdQuery;
        PopupMenu               aPopupMenu;
        sal_uInt16              nMenuId;
        sal_uInt16              nSelMenuItem;
        rtl::OUString           aQueryField;

        BibDataManager*         pDatMan;
        DECL_LINK( SelHdl, ListBox* );
        DECL_LINK( SendSelHdl, Timer* );
        DECL_LINK( MenuHdl, Timer* );

        void                    ApplyImageList();
    protected:

        void                    DataChanged( const DataChangedEvent& rDCEvt );
        void                    InitListener();
        virtual void            Select();
        virtual void            Click();
        void                    SendDispatch(sal_uInt16 nId, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& rArgs);
        long                    PreNotify( NotifyEvent& rNEvt );

    public:

        BibToolBar(Window* pParent, WinBits nStyle = WB_3DLOOK );
        ~BibToolBar();

        void    SetXController(const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XController > &);

        void    ClearSourceList();
        void    UpdateSourceList(sal_Bool bFlag=sal_True);
        void    EnableSourceList(sal_Bool bFlag=sal_True);
        void    InsertSourceEntry(const XubString&,sal_uInt16 nPos=LISTBOX_APPEND );
        void    SelectSourceEntry(const XubString& );

        void    EnableQuery(sal_Bool bFlag=sal_True);
        void    SetQueryString(const XubString& );

        void    ClearFilterMenu();
        sal_uInt16  InsertFilterItem(const XubString& );
        void    SelectFilterItem(sal_uInt16 nId);

        void    statusChanged(const ::com::sun::star::frame::FeatureStateEvent& Event)
                                            throw( ::com::sun::star::uno::RuntimeException );

        void    SetDatMan(BibDataManager& rDatMan) {pDatMan = &rDatMan;}
};

#endif
<commit_msg>INTEGRATION: CWS os8 (1.5.70); FILE MERGED 2003/04/03 06:39:23 cd 1.5.70.1: #108520# Support automatic toolbar button size depending on menu text height<commit_after>/*************************************************************************
 *
 *  $RCSfile: toolbar.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: vg $ $Date: 2003-04-17 16:13:03 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _BIB_TOOLBAR_HXX
#define _BIB_TOOLBAR_HXX

#ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_
#include <com/sun/star/frame/XController.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_
#include <com/sun/star/frame/XStatusListener.hpp>
#endif

#ifndef _SV_TOOLBOX_HXX //autogen wg. ToolBox
#include <vcl/toolbox.hxx>
#endif

#ifndef _SV_LSTBOX_HXX //autogen wg. ::com::sun::star::form
#include <vcl/lstbox.hxx>
#endif

#ifndef _SV_EDIT_HXX //autogen wg. Edit
#include <vcl/edit.hxx>
#endif

#ifndef _SV_FIXED_HXX //autogen wg. FixedText
#include <vcl/fixed.hxx>
#endif

#ifndef _SVARRAY_HXX
#include <svtools/svarray.hxx>
#endif

#ifndef _SV_TIMER_HXX //autogen wg. Timer
#include <vcl/timer.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx> // helper for implementations
#endif

class BibDataManager;
class BibToolBar;

class BibToolBarListener: public cppu::WeakImplHelper1 < ::com::sun::star::frame::XStatusListener>
{
private:

    sal_uInt16      nIndex;
    rtl::OUString           aCommand;

protected:

    BibToolBar      *pToolBar;

public:

    BibToolBarListener(BibToolBar *pTB,rtl::OUString aStr,sal_uInt16 nId);
    ~BibToolBarListener();

    rtl::OUString           GetCommand();
    void            SetCommand(const rtl::OUString& aStr);

    sal_uInt16          GetIndex();
    void            SetIndex(sal_uInt16 nIndex);

    // ::com::sun::star::lang::XEventListener
    // we do not hold References to dispatches, so there is nothing to do on disposal
    virtual void    SAL_CALL disposing(const ::com::sun::star::lang::EventObject& Source)
                                            throw( ::com::sun::star::uno::RuntimeException ){};

    // ::com::sun::star::frame::XStatusListener
    virtual void    SAL_CALL statusChanged(const ::com::sun::star::frame::FeatureStateEvent& Event)
                                            throw( ::com::sun::star::uno::RuntimeException );

};

class BibTBListBoxListener: public BibToolBarListener
{
public:

    BibTBListBoxListener(BibToolBar *pTB,rtl::OUString aStr,sal_uInt16 nId);
    ~BibTBListBoxListener();

    virtual void    SAL_CALL statusChanged(const ::com::sun::star::frame::FeatureStateEvent& Event)
                                            throw( ::com::sun::star::uno::RuntimeException );

};

class BibTBEditListener: public BibToolBarListener
{
public:

    BibTBEditListener(BibToolBar *pTB,rtl::OUString aStr,sal_uInt16 nId);
    ~BibTBEditListener();

    virtual void    SAL_CALL statusChanged(const ::com::sun::star::frame::FeatureStateEvent& Event)
                                            throw( ::com::sun::star::uno::RuntimeException );

};

class BibTBQueryMenuListener:   public BibToolBarListener
{
public:

    BibTBQueryMenuListener(BibToolBar *pTB,rtl::OUString aStr,sal_uInt16 nId);
    ~BibTBQueryMenuListener();

    virtual void    SAL_CALL statusChanged(const ::com::sun::star::frame::FeatureStateEvent& Event)
                                            throw( ::com::sun::star::uno::RuntimeException );

};

typedef ::com::sun::star::uno::Reference< ::com::sun::star::frame::XStatusListener>* BibToolBarListenerPtr;
SV_DECL_PTRARR_DEL( BibToolBarListenerArr, BibToolBarListenerPtr, 4, 4 );

class BibToolBar:   public ToolBox
{
    private:

        BibToolBarListenerArr   aListenerArr;
        ::com::sun::star::uno::Reference< ::com::sun::star::frame::XController >            xController;
        Timer                   aTimer;
        Timer                   aMenuTimer;
        ImageList               aImgLst;
        ImageList               aImgLstHC;
        ImageList               aBigImgLst;
        ImageList               aBigImgLstHC;
        FixedText               aFtSource;
        ListBox                 aLBSource;
        FixedText               aFtQuery;
        Edit                    aEdQuery;
        PopupMenu               aPopupMenu;
        sal_uInt16              nMenuId;
        sal_uInt16              nSelMenuItem;
        rtl::OUString           aQueryField;
        Link                    aLayoutManager;
        sal_Int16               nSymbolSet;
        sal_Int16               nOutStyle;

        BibDataManager*         pDatMan;
        DECL_LINK( SelHdl, ListBox* );
        DECL_LINK( SendSelHdl, Timer* );
        DECL_LINK( MenuHdl, Timer* );
        DECL_LINK( OptionsChanged_Impl, void* );
        DECL_LINK( SettingsChanged_Impl, void* );

        void                    ApplyImageList();
        void                    RebuildToolbar();

    protected:

        void                    DataChanged( const DataChangedEvent& rDCEvt );
        void                    InitListener();
        virtual void            Select();
        virtual void            Click();
        void                    SendDispatch(sal_uInt16 nId, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& rArgs);
        long                    PreNotify( NotifyEvent& rNEvt );
        sal_Int16               GetCurrentSymbolSet();

    public:

        BibToolBar(Window* pParent, Link aLink, WinBits nStyle = WB_3DLOOK );
        ~BibToolBar();

        void    SetXController(const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XController > &);

        void    ClearSourceList();
        void    UpdateSourceList(sal_Bool bFlag=sal_True);
        void    EnableSourceList(sal_Bool bFlag=sal_True);
        void    InsertSourceEntry(const XubString&,sal_uInt16 nPos=LISTBOX_APPEND );
        void    SelectSourceEntry(const XubString& );

        void    EnableQuery(sal_Bool bFlag=sal_True);
        void    SetQueryString(const XubString& );
        void    AdjustToolBox();

        void    ClearFilterMenu();
        sal_uInt16  InsertFilterItem(const XubString& );
        void    SelectFilterItem(sal_uInt16 nId);

        void    statusChanged(const ::com::sun::star::frame::FeatureStateEvent& Event)
                                            throw( ::com::sun::star::uno::RuntimeException );

        void    SetDatMan(BibDataManager& rDatMan) {pDatMan = &rDatMan;}
};

#endif
<|endoftext|>


<commit_before>/*******************************************************************************
 * This file is part of "Patrick's Programming Library", Version 7 (PPL7).
 * Web: http://www.pfp.de/ppl/
 *
 * $Author$
 * $Revision$
 * $Date$
 * $Id$
 *
 *******************************************************************************
 * Copyright (c) 2013, Patrick Fedick <patrick@pfp.de>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *    1. Redistributions of source code must retain the above copyright notice, this
 *       list of conditions and the following disclaimer.
 *    2. Redistributions in binary form must reproduce the above copyright notice,
 *       this list of conditions and the following disclaimer in the documentation
 *       and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER AND CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 *******************************************************************************/

#include "prolog.h"
#ifdef HAVE_STDIO_H
#include <stdio.h>
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#ifdef HAVE_MATH_H
#include <math.h>
#endif

#include "ppl7.h"
#include "ppl7-grafix.h"

#ifdef HAVE_FREETYPE2
#include <ft2build.h>
#include FT_FREETYPE_H
#endif

//#undef HAVE_X86_ASSEMBLER

// Font-Blitter
typedef struct tagGLYPH {
	const char *data;
	char *target;
	ppluint32 pitch;
	pplint32 color;
} GLYPH;

extern "C" {
	int BltGlyph_M8_32 (GLYPH *g);
	int BltGlyph_M1_32 (GLYPH *g);
	int BltGlyph_AA8_32 (GLYPH *g);
	int BltGlyph_AA2_32 (GLYPH *g);
	int BltGlyph_AA4_32 (GLYPH *g);
}

namespace ppl7 {
namespace grafix {

/*!\class FontEngineFreeType
 * \ingroup PPLGroupGrafik
 * \brief Font-Engine für von FreeType unterstützte Fonts
 *
 * Diese Engine unterstützt TrueType, OpenType, Type1 und weitere von der Freetype-Library
 * unterstützte Formate.
 *
 * \see
 * http://www.freetype.org/
 */

#ifdef HAVE_FREETYPE2
typedef struct tagFreeTypeEngineData {
	FT_Library	ftlib;
} FREETYPE_ENGINE_DATA;

typedef struct tagFreeTypeFaceData {
	FT_Byte *buffer;
	FT_Face	face;
	int		kerning;
} FREETYPE_FACE_DATA;
#endif

FontEngineFreeType::FontEngineFreeType()
{
	ft=NULL;
#ifdef HAVE_FREETYPE2
#endif
}

FontEngineFreeType::~FontEngineFreeType()
{
#ifdef HAVE_FREETYPE2
	FREETYPE_ENGINE_DATA *f=(FREETYPE_ENGINE_DATA*)ft;
	if (f) {
		FT_Done_FreeType(f->ftlib);
		free(f);
	}
#endif
}

String FontEngineFreeType::name() const
{
	return "FontEngineFreeType";
}

String FontEngineFreeType::description() const
{
	return "Rendering of TrueType and OpenType fonts";
}

void FontEngineFreeType::init()
{
#ifndef HAVE_FREETYPE2
	throw UnsupportedFeatureException("Freetype2");
#else
	if (ft) return;
	FREETYPE_ENGINE_DATA *f=(FREETYPE_ENGINE_DATA *)malloc(sizeof(FREETYPE_ENGINE_DATA));
	if (!f) throw OutOfMemoryException();
	int error=FT_Init_FreeType(&f->ftlib );
	if (error) {
		free(f);
		throw FontEngineInitializationException();
	}
	ft=f;
#endif
}

int FontEngineFreeType::ident(FileObject &file) throw()
{
#ifndef HAVE_FREETYPE2
	return 0;
#else
	FREETYPE_ENGINE_DATA *f=(FREETYPE_ENGINE_DATA*)ft;
	if (!f) return 0;
	const FT_Byte *buffer=(const FT_Byte *)file.map();
	size_t size=file.size();
	FT_Face face;
	int error = FT_New_Memory_Face(f->ftlib, buffer, (FT_Long)size, 0, &face );
	if (error!=0) return 0;
	FT_Done_Face(face);
	return 1;
#endif
}

FontFile *FontEngineFreeType::loadFont(FileObject &file, const String &fontname)
{
#ifndef HAVE_FREETYPE2
	throw UnsupportedFeatureException("Freetype2");
#else
	FREETYPE_ENGINE_DATA *f=(FREETYPE_ENGINE_DATA*)ft;
	if (!f) throw FontEngineUninitializedException();
	FREETYPE_FACE_DATA *face=(FREETYPE_FACE_DATA*)malloc(sizeof(FREETYPE_FACE_DATA));
	if (!face) throw OutOfMemoryException();
	face->buffer=(FT_Byte *)file.load();
	size_t size=file.size();
	int error = FT_New_Memory_Face(f->ftlib, face->buffer, (FT_Long)size, 0, &face->face );
	if (error!=0) {
		free(face->buffer);
		free(face);
		if (error!=0) throw InvalidFontException();
	}
	String name=fontname;
	if (name.isEmpty()) name.set(face->face->family_name);
	face->kerning=(int)FT_HAS_KERNING(face->face);		// Kerning unterstützt?
	FontFile *ff=new FontFile;
	ff->Name=fontname;
	ff->engine=this;
	ff->priv=face;
	return ff;
#endif
}

void FontEngineFreeType::deleteFont(FontFile *file)
{
#ifndef HAVE_FREETYPE2
	throw UnsupportedFeatureException("Freetype2");
#else
	if (!file) throw NullPointerException();
	if (file->engine!=this) throw InvalidFontEngineException();
	FREETYPE_FACE_DATA *face=(FREETYPE_FACE_DATA*)file->priv;
	if (face) {
		FT_Done_Face(face->face);
		free(face->buffer);
		free(face);
		file->priv=NULL;
	}
	file->engine=NULL;
#endif
}

#ifdef HAVE_FREETYPE2
static void renderGlyphAA(Drawable &draw, FT_Bitmap *bitmap, int x, int y, const Color &color)
{
	ppluint8 v=0;
	ppluint8 *glyph=(ppluint8 *)bitmap->buffer;
	for (unsigned int gy=0;gy<bitmap->rows;gy++) {
		for (unsigned int gx=0;gx<bitmap->width;gx++) {
			v=glyph[gx];
			if (v>0) {
				draw.blendPixel(x+gx,y+gy,color,v);
			}
		}
		glyph+=bitmap->pitch;
	}
}

static void renderGlyphMono(Drawable &draw, FT_Bitmap *bitmap, int x, int y, const Color &color)
{
	ppluint8 v=0;
	ppluint8 *glyph=(ppluint8 *)bitmap->buffer;
	for (unsigned int gy=0;gy<bitmap->rows;gy++) {
		ppluint8 bitcount=0;
		ppluint8 bytecount=0;
		for (unsigned int gx=0;gx<bitmap->width;gx++) {
			if (!bitcount) {
				v=glyph[bytecount];
				bitcount=8;
				bytecount++;
			}
			if(v&128) {
				draw.putPixel(x+gx,y+gy,color);
			}
			v=v<<1;
			bitcount--;
		}
		glyph+=bitmap->pitch;
	}
}

#endif

void FontEngineFreeType::render(const FontFile &file, const Font &font, Drawable &draw, int x, int y, const WideString &text, const Color &color)
{
#ifndef HAVE_FREETYPE2
	throw UnsupportedFeatureException("Freetype2");
#else
	if (file.priv==NULL) throw InvalidFontException();
	FREETYPE_FACE_DATA *face=(FREETYPE_FACE_DATA*)file.priv;
	int error=FT_Set_Pixel_Sizes(face->face,0,font.size()+2);
	if (error!=0) throw InvalidFontException();

	int orgx=x<<6;
	int orgy=y<<6;
	int lastx=orgx;
	bool rotate=false;
	FT_Matrix matrix; /* transformation matrix */
	if (font.rotation()!=0.0) {
		rotate=true;
		double angle=font.rotation()*3.14159265359/180.0;
		/* set up matrix */
		matrix.xx = (FT_Fixed)( cos( angle ) * 0x10000L );
		matrix.xy = (FT_Fixed)( sin( angle ) * 0x10000L );
		matrix.yx = (FT_Fixed)( -sin( angle ) * 0x10000L );
		matrix.yy = (FT_Fixed)( cos( angle ) * 0x10000L );
		FT_Set_Transform( face->face, &matrix, NULL );
	} else {
		FT_Set_Transform( face->face, NULL, NULL );
	}

	FT_GlyphSlot slot=face->face->glyph;
	FT_UInt			glyph_index, last_glyph=0;
	FT_Vector		kerning;
	kerning.x=0;
	kerning.y=0;

	size_t p=0;
	size_t textlen=text.len();

	while (p<textlen) {
		int code=text[p];
		p++;
		if (code==10) {											// Newline
			lastx=orgx;
			orgy+=(font.size()+2)<<6;
			last_glyph=0;
		} else {
			y=orgy;
			x=lastx;
			glyph_index=FT_Get_Char_Index(face->face,code);
			if (!glyph_index) continue;
			// Antialiasing
			if (font.antialias()) {
				error=FT_Load_Glyph(face->face,glyph_index,FT_LOAD_DEFAULT|FT_LOAD_RENDER|FT_LOAD_TARGET_NORMAL);
			} else {
				error=FT_Load_Glyph(face->face,glyph_index,FT_LOAD_DEFAULT|FT_LOAD_TARGET_MONO|FT_LOAD_RENDER);
			}
			if (error!=0) continue;
			//x=x+(slot->bitmap_left<<6);
			//y=y-(slot->bitmap_top<<6);
			if (face->kerning>0 && last_glyph>0 && rotate==false) {
				FT_Get_Kerning(face->face,last_glyph,glyph_index,FT_KERNING_DEFAULT,&kerning);
				x+=kerning.x;
				y+=kerning.y;
			}

			if (font.antialias()) {
				renderGlyphAA(draw,&slot->bitmap,(x>>6)+slot->bitmap_left,
						(y>>6)-slot->bitmap_top,color);
			} else {
				renderGlyphMono(draw,&slot->bitmap,(x>>6)+slot->bitmap_left,
						(y>>6)-slot->bitmap_top,color);
			}
			if (font.drawUnderline()) {

			}
			lastx=x+slot->advance.x;
			orgy-=slot->advance.y;
			last_glyph=glyph_index;
		}
	}
#endif
}

Size FontEngineFreeType::measure(const FontFile &file, const Font &font, const WideString &text)
{
	Size s;
#ifndef HAVE_FREETYPE2
	throw UnsupportedFeatureException("Freetype2");
#else
	if (file.priv==NULL) throw InvalidFontException();
	FREETYPE_FACE_DATA *face=(FREETYPE_FACE_DATA*)file.priv;
	int error=FT_Set_Pixel_Sizes(face->face,0,font.size()+2);
	if (error!=0) throw InvalidFontException();

	FT_Set_Transform( face->face, NULL, NULL );

	int width=0,height=0;

	FT_GlyphSlot slot=face->face->glyph;
	FT_UInt			glyph_index, last_glyph=0;
	FT_Vector		kerning;
	kerning.x=0;
	kerning.y=0;
	size_t p=0;
	size_t textlen=text.len();
	while (p<textlen) {
		int code=text[p];
		p++;
		if (code==10) {											// Newline
			width=0;
			height+=(font.size()+2);
			last_glyph=0;
		} else {
			glyph_index=FT_Get_Char_Index(face->face,code);
			if (!glyph_index) continue;
			// Antialiasing
			if (font.antialias()) {
				error=FT_Load_Glyph(face->face,glyph_index,FT_LOAD_DEFAULT|FT_LOAD_RENDER|FT_LOAD_TARGET_NORMAL);
			} else {
				error=FT_Load_Glyph(face->face,glyph_index,FT_LOAD_DEFAULT|FT_LOAD_TARGET_MONO|FT_LOAD_RENDER);
			}
			if (error!=0) continue;
			//x=x+slot->bitmap_left;
			//y=y-slot->bitmap_top;
			if (face->kerning>0 && last_glyph>0) {
				error=FT_Get_Kerning(face->face,last_glyph,glyph_index,FT_KERNING_DEFAULT,&kerning);
				width+=kerning.x;
			}
			width+=(slot->advance.x);
			if (width>s.width) s.width=width;
			last_glyph=glyph_index;
		}
	}
	s.setHeight(height+font.size()+2);
	s.width=s.width>>6;
	return s;
#endif
}

} // EOF namespace grafix
} // EOF namespace ppl7

<commit_msg>putPixel überarbeitet<commit_after>/*******************************************************************************
 * This file is part of "Patrick's Programming Library", Version 7 (PPL7).
 * Web: http://www.pfp.de/ppl/
 *
 * $Author$
 * $Revision$
 * $Date$
 * $Id$
 *
 *******************************************************************************
 * Copyright (c) 2013, Patrick Fedick <patrick@pfp.de>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *    1. Redistributions of source code must retain the above copyright notice, this
 *       list of conditions and the following disclaimer.
 *    2. Redistributions in binary form must reproduce the above copyright notice,
 *       this list of conditions and the following disclaimer in the documentation
 *       and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER AND CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 *******************************************************************************/

#include "prolog.h"
#ifdef HAVE_STDIO_H
#include <stdio.h>
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#ifdef HAVE_MATH_H
#include <math.h>
#endif

#include "ppl7.h"
#include "ppl7-grafix.h"

#ifdef HAVE_FREETYPE2
#include <ft2build.h>
#include FT_FREETYPE_H
#endif

//#undef HAVE_X86_ASSEMBLER

// Font-Blitter
typedef struct tagGLYPH {
	const char *data;
	char *target;
	ppluint32 pitch;
	pplint32 color;
} GLYPH;

extern "C" {
	int BltGlyph_M8_32 (GLYPH *g);
	int BltGlyph_M1_32 (GLYPH *g);
	int BltGlyph_AA8_32 (GLYPH *g);
	int BltGlyph_AA2_32 (GLYPH *g);
	int BltGlyph_AA4_32 (GLYPH *g);
}

namespace ppl7 {
namespace grafix {

/*!\class FontEngineFreeType
 * \ingroup PPLGroupGrafik
 * \brief Font-Engine für von FreeType unterstützte Fonts
 *
 * Diese Engine unterstützt TrueType, OpenType, Type1 und weitere von der Freetype-Library
 * unterstützte Formate.
 *
 * \see
 * http://www.freetype.org/
 */

#ifdef HAVE_FREETYPE2
typedef struct tagFreeTypeEngineData {
	FT_Library	ftlib;
} FREETYPE_ENGINE_DATA;

typedef struct tagFreeTypeFaceData {
	FT_Byte *buffer;
	FT_Face	face;
	int		kerning;
} FREETYPE_FACE_DATA;
#endif

FontEngineFreeType::FontEngineFreeType()
{
	ft=NULL;
#ifdef HAVE_FREETYPE2
#endif
}

FontEngineFreeType::~FontEngineFreeType()
{
#ifdef HAVE_FREETYPE2
	FREETYPE_ENGINE_DATA *f=(FREETYPE_ENGINE_DATA*)ft;
	if (f) {
		FT_Done_FreeType(f->ftlib);
		free(f);
	}
#endif
}

String FontEngineFreeType::name() const
{
	return "FontEngineFreeType";
}

String FontEngineFreeType::description() const
{
	return "Rendering of TrueType and OpenType fonts";
}

void FontEngineFreeType::init()
{
#ifndef HAVE_FREETYPE2
	throw UnsupportedFeatureException("Freetype2");
#else
	if (ft) return;
	FREETYPE_ENGINE_DATA *f=(FREETYPE_ENGINE_DATA *)malloc(sizeof(FREETYPE_ENGINE_DATA));
	if (!f) throw OutOfMemoryException();
	int error=FT_Init_FreeType(&f->ftlib );
	if (error) {
		free(f);
		throw FontEngineInitializationException();
	}
	ft=f;
#endif
}

int FontEngineFreeType::ident(FileObject &file) throw()
{
#ifndef HAVE_FREETYPE2
	return 0;
#else
	FREETYPE_ENGINE_DATA *f=(FREETYPE_ENGINE_DATA*)ft;
	if (!f) return 0;
	const FT_Byte *buffer=(const FT_Byte *)file.map();
	size_t size=file.size();
	FT_Face face;
	int error = FT_New_Memory_Face(f->ftlib, buffer, (FT_Long)size, 0, &face );
	if (error!=0) return 0;
	FT_Done_Face(face);
	return 1;
#endif
}

FontFile *FontEngineFreeType::loadFont(FileObject &file, const String &fontname)
{
#ifndef HAVE_FREETYPE2
	throw UnsupportedFeatureException("Freetype2");
#else
	FREETYPE_ENGINE_DATA *f=(FREETYPE_ENGINE_DATA*)ft;
	if (!f) throw FontEngineUninitializedException();
	FREETYPE_FACE_DATA *face=(FREETYPE_FACE_DATA*)malloc(sizeof(FREETYPE_FACE_DATA));
	if (!face) throw OutOfMemoryException();
	face->buffer=(FT_Byte *)file.load();
	size_t size=file.size();
	int error = FT_New_Memory_Face(f->ftlib, face->buffer, (FT_Long)size, 0, &face->face );
	if (error!=0) {
		free(face->buffer);
		free(face);
		if (error!=0) throw InvalidFontException();
	}
	String name=fontname;
	if (name.isEmpty()) name.set(face->face->family_name);
	face->kerning=(int)FT_HAS_KERNING(face->face);		// Kerning unterstützt?
	FontFile *ff=new FontFile;
	ff->Name=fontname;
	ff->engine=this;
	ff->priv=face;
	return ff;
#endif
}

void FontEngineFreeType::deleteFont(FontFile *file)
{
#ifndef HAVE_FREETYPE2
	throw UnsupportedFeatureException("Freetype2");
#else
	if (!file) throw NullPointerException();
	if (file->engine!=this) throw InvalidFontEngineException();
	FREETYPE_FACE_DATA *face=(FREETYPE_FACE_DATA*)file->priv;
	if (face) {
		FT_Done_Face(face->face);
		free(face->buffer);
		free(face);
		file->priv=NULL;
	}
	file->engine=NULL;
#endif
}

static void putPixel(Drawable &draw, int x, int y, const Color &color, int intensity)
{
	Color vg=color;
	int a=vg.alpha()*intensity/255;
	if (a==0) return;
	if (a==255) {
		vg.setAlpha(a);
		draw.putPixel(x,y,vg);
	}
	Color &bg=draw.getPixel(x,y);
	int reva=255-a;
	int red=bg.red()*reva+vg.red()*a;
	int green=bg.green()*reva+vg.green()*a;
	int blue=bg.blue()*reva+vg.blue()*a;
	int alpha=bg.alpha()*reva+vg.alpha()*a;
	draw.putPixel(x,y,Color(red,green,blue,alpha));
}

#ifdef HAVE_FREETYPE2
static void renderGlyphAA(Drawable &draw, FT_Bitmap *bitmap, int x, int y, const Color &color)
{
	ppluint8 v=0;
	ppluint8 *glyph=(ppluint8 *)bitmap->buffer;
	for (unsigned int gy=0;gy<bitmap->rows;gy++) {
		for (unsigned int gx=0;gx<bitmap->width;gx++) {
			v=glyph[gx];
			if (v>0) {
				putPixel(x+gx,y+gy,color,v);
				//draw.blendPixel(x+gx,y+gy,color,v);
			}
		}
		glyph+=bitmap->pitch;
	}
}

static void renderGlyphMono(Drawable &draw, FT_Bitmap *bitmap, int x, int y, const Color &color)
{
	ppluint8 v=0;
	ppluint8 *glyph=(ppluint8 *)bitmap->buffer;
	for (unsigned int gy=0;gy<bitmap->rows;gy++) {
		ppluint8 bitcount=0;
		ppluint8 bytecount=0;
		for (unsigned int gx=0;gx<bitmap->width;gx++) {
			if (!bitcount) {
				v=glyph[bytecount];
				bitcount=8;
				bytecount++;
			}
			if(v&128) {
				putPixel(x+gx,y+gy,color,255);
				//draw.alphaPixel(x+gx,y+gy,color);
			}
			v=v<<1;
			bitcount--;
		}
		glyph+=bitmap->pitch;
	}
}

#endif

void FontEngineFreeType::render(const FontFile &file, const Font &font, Drawable &draw, int x, int y, const WideString &text, const Color &color)
{
#ifndef HAVE_FREETYPE2
	throw UnsupportedFeatureException("Freetype2");
#else
	if (file.priv==NULL) throw InvalidFontException();
	FREETYPE_FACE_DATA *face=(FREETYPE_FACE_DATA*)file.priv;
	int error=FT_Set_Pixel_Sizes(face->face,0,font.size()+2);
	if (error!=0) throw InvalidFontException();

	int orgx=x<<6;
	int orgy=y<<6;
	int lastx=orgx;
	bool rotate=false;
	FT_Matrix matrix; /* transformation matrix */
	if (font.rotation()!=0.0) {
		rotate=true;
		double angle=font.rotation()*3.14159265359/180.0;
		/* set up matrix */
		matrix.xx = (FT_Fixed)( cos( angle ) * 0x10000L );
		matrix.xy = (FT_Fixed)( sin( angle ) * 0x10000L );
		matrix.yx = (FT_Fixed)( -sin( angle ) * 0x10000L );
		matrix.yy = (FT_Fixed)( cos( angle ) * 0x10000L );
		FT_Set_Transform( face->face, &matrix, NULL );
	} else {
		FT_Set_Transform( face->face, NULL, NULL );
	}

	FT_GlyphSlot slot=face->face->glyph;
	FT_UInt			glyph_index, last_glyph=0;
	FT_Vector		kerning;
	kerning.x=0;
	kerning.y=0;

	size_t p=0;
	size_t textlen=text.len();

	while (p<textlen) {
		int code=text[p];
		p++;
		if (code==10) {											// Newline
			lastx=orgx;
			orgy+=(font.size()+2)<<6;
			last_glyph=0;
		} else {
			y=orgy;
			x=lastx;
			glyph_index=FT_Get_Char_Index(face->face,code);
			if (!glyph_index) continue;
			// Antialiasing
			if (font.antialias()) {
				error=FT_Load_Glyph(face->face,glyph_index,FT_LOAD_DEFAULT|FT_LOAD_RENDER|FT_LOAD_TARGET_NORMAL);
			} else {
				error=FT_Load_Glyph(face->face,glyph_index,FT_LOAD_DEFAULT|FT_LOAD_TARGET_MONO|FT_LOAD_RENDER);
			}
			if (error!=0) continue;
			//x=x+(slot->bitmap_left<<6);
			//y=y-(slot->bitmap_top<<6);
			if (face->kerning>0 && last_glyph>0 && rotate==false) {
				FT_Get_Kerning(face->face,last_glyph,glyph_index,FT_KERNING_DEFAULT,&kerning);
				x+=kerning.x;
				y+=kerning.y;
			}

			if (font.antialias()) {
				renderGlyphAA(draw,&slot->bitmap,(x>>6)+slot->bitmap_left,
						(y>>6)-slot->bitmap_top,color);
			} else {
				renderGlyphMono(draw,&slot->bitmap,(x>>6)+slot->bitmap_left,
						(y>>6)-slot->bitmap_top,color);
			}
			if (font.drawUnderline()) {

			}
			lastx=x+slot->advance.x;
			orgy-=slot->advance.y;
			last_glyph=glyph_index;
		}
	}
#endif
}

Size FontEngineFreeType::measure(const FontFile &file, const Font &font, const WideString &text)
{
	Size s;
#ifndef HAVE_FREETYPE2
	throw UnsupportedFeatureException("Freetype2");
#else
	if (file.priv==NULL) throw InvalidFontException();
	FREETYPE_FACE_DATA *face=(FREETYPE_FACE_DATA*)file.priv;
	int error=FT_Set_Pixel_Sizes(face->face,0,font.size()+2);
	if (error!=0) throw InvalidFontException();

	FT_Set_Transform( face->face, NULL, NULL );

	int width=0,height=0;

	FT_GlyphSlot slot=face->face->glyph;
	FT_UInt			glyph_index, last_glyph=0;
	FT_Vector		kerning;
	kerning.x=0;
	kerning.y=0;
	size_t p=0;
	size_t textlen=text.len();
	while (p<textlen) {
		int code=text[p];
		p++;
		if (code==10) {											// Newline
			width=0;
			height+=(font.size()+2);
			last_glyph=0;
		} else {
			glyph_index=FT_Get_Char_Index(face->face,code);
			if (!glyph_index) continue;
			// Antialiasing
			if (font.antialias()) {
				error=FT_Load_Glyph(face->face,glyph_index,FT_LOAD_DEFAULT|FT_LOAD_RENDER|FT_LOAD_TARGET_NORMAL);
			} else {
				error=FT_Load_Glyph(face->face,glyph_index,FT_LOAD_DEFAULT|FT_LOAD_TARGET_MONO|FT_LOAD_RENDER);
			}
			if (error!=0) continue;
			//x=x+slot->bitmap_left;
			//y=y-slot->bitmap_top;
			if (face->kerning>0 && last_glyph>0) {
				error=FT_Get_Kerning(face->face,last_glyph,glyph_index,FT_KERNING_DEFAULT,&kerning);
				width+=kerning.x;
			}
			width+=(slot->advance.x);
			if (width>s.width) s.width=width;
			last_glyph=glyph_index;
		}
	}
	s.setHeight(height+font.size()+2);
	s.width=s.width>>6;
	return s;
#endif
}

} // EOF namespace grafix
} // EOF namespace ppl7

<|endoftext|>


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

#include "chrome/renderer/extensions/app_window_custom_bindings.h"

#include <string>

#include "base/string_util.h"
#include "chrome/common/extensions/extension_action.h"
#include "chrome/common/extensions/extension_messages.h"
#include "chrome/common/url_constants.h"
#include "chrome/renderer/extensions/extension_dispatcher.h"
#include "chrome/renderer/extensions/extension_helper.h"
#include "content/public/renderer/render_view.h"
#include "grit/renderer_resources.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURLRequest.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebWindowFeatures.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebNavigationPolicy.h"
#include "webkit/glue/webkit_glue.h"
#include "v8/include/v8.h"

#include "content/public/renderer/render_view.h"
#include "content/public/renderer/render_view_visitor.h"

namespace extensions {

AppWindowCustomBindings::AppWindowCustomBindings(
    ExtensionDispatcher* extension_dispatcher)
    : ChromeV8Extension(extension_dispatcher) {
  RouteStaticFunction("GetView", &GetView);
}

namespace {
class FindViewByID : public content::RenderViewVisitor {
 public:
  explicit FindViewByID(int route_id) : route_id_(route_id), view_(NULL) {
  }

  content::RenderView* view() { return view_; }

  // Returns false to terminate the iteration.
  virtual bool Visit(content::RenderView* render_view) {
    if (render_view->GetRoutingID() == route_id_) {
      view_ = render_view;
      return false;
    }
    return true;
  }

 private:
  int route_id_;
  content::RenderView* view_;
};
}  // namespace

v8::Handle<v8::Value> AppWindowCustomBindings::GetView(
    const v8::Arguments& args) {
  // TODO(jeremya): convert this to IDL nocompile to get validation, and turn
  // these argument checks into CHECK().
  if (args.Length() != 1)
    return v8::Undefined();

  if (!args[0]->IsInt32())
    return v8::Undefined();

  int view_id = args[0]->Int32Value();

  if (view_id == MSG_ROUTING_NONE)
    return v8::Undefined();

  // TODO(jeremya): there exists a direct map of routing_id -> RenderView as
  // ChildThread::current()->ResolveRoute(), but ResolveRoute returns an
  // IPC::Channel::Listener*, which RenderView doesn't inherit from
  // (RenderViewImpl does, indirectly, via RenderWidget, but the link isn't
  // exposed outside of content/.)
  FindViewByID view_finder(view_id);
  content::RenderView::ForEach(&view_finder);
  content::RenderView* view = view_finder.view();
  if (!view)
    return v8::Undefined();

  // TODO(jeremya): it doesn't really make sense to set the opener here, but we
  // need to make sure the security origin is set up before returning the DOM
  // reference. A better way to do this would be to have the browser pass the
  // opener through so opener_id is set in RenderViewImpl's constructor.
  WebKit::WebFrame* opener = GetCurrentRenderView()->GetWebView()->mainFrame();
  WebKit::WebFrame* frame = view->GetWebView()->mainFrame();
  frame->setOpener(opener);

  v8::Local<v8::Value> window = frame->mainWorldScriptContext()->Global();
  return window;
}

}  // namespace extensions
<commit_msg>Coverity NULL_RETURNS issue.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/renderer/extensions/app_window_custom_bindings.h"

#include <string>

#include "base/string_util.h"
#include "chrome/common/extensions/extension_action.h"
#include "chrome/common/extensions/extension_messages.h"
#include "chrome/common/url_constants.h"
#include "chrome/renderer/extensions/extension_dispatcher.h"
#include "chrome/renderer/extensions/extension_helper.h"
#include "content/public/renderer/render_view.h"
#include "grit/renderer_resources.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURLRequest.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebWindowFeatures.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebNavigationPolicy.h"
#include "webkit/glue/webkit_glue.h"
#include "v8/include/v8.h"

#include "content/public/renderer/render_view.h"
#include "content/public/renderer/render_view_visitor.h"

namespace extensions {

AppWindowCustomBindings::AppWindowCustomBindings(
    ExtensionDispatcher* extension_dispatcher)
    : ChromeV8Extension(extension_dispatcher) {
  RouteStaticFunction("GetView", &GetView);
}

namespace {
class FindViewByID : public content::RenderViewVisitor {
 public:
  explicit FindViewByID(int route_id) : route_id_(route_id), view_(NULL) {
  }

  content::RenderView* view() { return view_; }

  // Returns false to terminate the iteration.
  virtual bool Visit(content::RenderView* render_view) {
    if (render_view->GetRoutingID() == route_id_) {
      view_ = render_view;
      return false;
    }
    return true;
  }

 private:
  int route_id_;
  content::RenderView* view_;
};
}  // namespace

v8::Handle<v8::Value> AppWindowCustomBindings::GetView(
    const v8::Arguments& args) {
  // TODO(jeremya): convert this to IDL nocompile to get validation, and turn
  // these argument checks into CHECK().
  if (args.Length() != 1)
    return v8::Undefined();

  if (!args[0]->IsInt32())
    return v8::Undefined();

  int view_id = args[0]->Int32Value();

  if (view_id == MSG_ROUTING_NONE)
    return v8::Undefined();

  // TODO(jeremya): there exists a direct map of routing_id -> RenderView as
  // ChildThread::current()->ResolveRoute(), but ResolveRoute returns an
  // IPC::Channel::Listener*, which RenderView doesn't inherit from
  // (RenderViewImpl does, indirectly, via RenderWidget, but the link isn't
  // exposed outside of content/.)
  FindViewByID view_finder(view_id);
  content::RenderView::ForEach(&view_finder);
  content::RenderView* view = view_finder.view();
  if (!view)
    return v8::Undefined();

  // TODO(jeremya): it doesn't really make sense to set the opener here, but we
  // need to make sure the security origin is set up before returning the DOM
  // reference. A better way to do this would be to have the browser pass the
  // opener through so opener_id is set in RenderViewImpl's constructor.
  content::RenderView* render_view = GetCurrentRenderView();
  if (!render_view)
    return v8::Undefined();
  WebKit::WebFrame* opener = render_view->GetWebView()->mainFrame();
  WebKit::WebFrame* frame = view->GetWebView()->mainFrame();
  frame->setOpener(opener);

  v8::Local<v8::Value> window = frame->mainWorldScriptContext()->Global();
  return window;
}

}  // namespace extensions
<|endoftext|>


<commit_before>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2011 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  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
//
//  Current versions can be found at www.libavg.de
//

#include "VertexData.h"

#include "GLContext.h"

#include "../base/Exception.h"
#include "../base/WideLine.h"
#include "../base/ObjectCounter.h"

#include <iostream>
#include <stddef.h>
#include <string.h>

using namespace std;
using namespace boost;

namespace avg {

const int MIN_VERTEXES = 100;
const int MIN_INDEXES = 100;

VertexData::VertexData(int reserveVerts, int reserveIndexes)
    : m_NumVerts(0),
      m_NumIndexes(0),
      m_ReserveVerts(reserveVerts),
      m_ReserveIndexes(reserveIndexes),
      m_bDataChanged(true)
{
    ObjectCounter::get()->incRef(&typeid(*this));
    if (m_ReserveVerts < MIN_VERTEXES) {
        m_ReserveVerts = MIN_VERTEXES;
    }
    if (m_ReserveIndexes < MIN_INDEXES) {
        m_ReserveIndexes = MIN_INDEXES;
    }
    m_pVertexData = new T2V3C4Vertex[m_ReserveVerts];
    m_pIndexData = new unsigned int[m_ReserveIndexes];

}

VertexData::~VertexData()
{
    delete[] m_pVertexData;
    delete[] m_pIndexData;
    ObjectCounter::get()->decRef(&typeid(*this));
}

void VertexData::appendPos(const glm::vec2& pos, const glm::vec2& texPos,
        const Pixel32& color)
{
    if (m_NumVerts >= m_ReserveVerts-1) {
        grow();
    }
    T2V3C4Vertex* pVertex = &(m_pVertexData[m_NumVerts]);
    pVertex->m_Pos[0] = (GLfloat)pos.x;
    pVertex->m_Pos[1] = (GLfloat)pos.y;
    pVertex->m_Pos[2] = 0.0;
    pVertex->m_Tex[0] = (GLfloat)texPos.x;
    pVertex->m_Tex[1] = (GLfloat)texPos.y;
    pVertex->m_Color = color;
    m_bDataChanged = true;
    m_NumVerts++;
}

void VertexData::appendTriIndexes(int v0, int v1, int v2)
{
    if (m_NumIndexes >= m_ReserveIndexes-3) {
        grow();
    }
    m_pIndexData[m_NumIndexes] = v0;
    m_pIndexData[m_NumIndexes+1] = v1;
    m_pIndexData[m_NumIndexes+2] = v2;
    m_NumIndexes += 3;
}

void VertexData::appendQuadIndexes(int v0, int v1, int v2, int v3)
{
    if (m_NumIndexes >= m_ReserveIndexes-6) {
        grow();
    }
    m_pIndexData[m_NumIndexes] = v0;
    m_pIndexData[m_NumIndexes+1] = v1;
    m_pIndexData[m_NumIndexes+2] = v2;
    m_pIndexData[m_NumIndexes+3] = v1;
    m_pIndexData[m_NumIndexes+4] = v2;
    m_pIndexData[m_NumIndexes+5] = v3;
    m_NumIndexes += 6;
}

void VertexData::addLineData(Pixel32 color, const glm::vec2& p1, const glm::vec2& p2,
        float width, float tc1, float tc2)
{
    WideLine wl(p1, p2, width);
    int curVertex = getCurVert();
    appendPos(wl.pl0, glm::vec2(tc1, 1), color);
    appendPos(wl.pr0, glm::vec2(tc1, 0), color);
    appendPos(wl.pl1, glm::vec2(tc2, 1), color);
    appendPos(wl.pr1, glm::vec2(tc2, 0), color);
    appendQuadIndexes(curVertex+1, curVertex, curVertex+3, curVertex+2);
}

void VertexData::appendVertexData(VertexDataPtr pVertexes)
{
    int oldNumVerts = m_NumVerts;
    int oldNumIndexes = m_NumIndexes;
    m_NumVerts += pVertexes->getNumVerts();
    m_NumIndexes += pVertexes->getNumIndexes();
    if (m_NumVerts > m_ReserveVerts || m_NumIndexes > m_ReserveIndexes) {
        grow();
    }

    for (int i=0; i<pVertexes->getNumVerts(); ++i) {
        m_pVertexData[oldNumVerts+i] = pVertexes->m_pVertexData[i];
    }
    for (int i=0; i<pVertexes->getNumIndexes(); ++i) {
        m_pIndexData[oldNumIndexes+i] = pVertexes->m_pIndexData[i]+oldNumVerts;
    }
    m_bDataChanged = true;
}

bool VertexData::hasDataChanged() const
{
    return m_bDataChanged;
}

void VertexData::resetDataChanged()
{
    m_bDataChanged = false;
}

void VertexData::reset()
{
    m_NumVerts = 0;
    m_NumIndexes = 0;
}

int VertexData::getCurVert() const
{
    return m_NumVerts;
}

int VertexData::getCurIndex() const
{
    return m_NumIndexes;
}

void VertexData::dump() const
{
    cerr << m_NumVerts << " vertexes: ";
    for (int i=0; i<m_NumVerts; ++i) {
        cerr << m_pVertexData[i] << ", ";
    }
    cerr << endl;
    cerr << m_NumIndexes << " indexes: ";
    for (int i=0; i<m_NumIndexes; ++i) {
        cerr << m_pIndexData[i] << " ";
    }
    cerr << endl;
}

void VertexData::grow()
{
    bool bChanged = false;
    if (m_NumVerts >= m_ReserveVerts-1) {
        bChanged = true;
        int oldReserveVerts = m_ReserveVerts;
        m_ReserveVerts = int(m_ReserveVerts*1.5);
        if (m_ReserveVerts < m_NumVerts) {
            m_ReserveVerts = m_NumVerts;
        }
        T2V3C4Vertex* pVertexData = m_pVertexData;
        m_pVertexData = new T2V3C4Vertex[m_ReserveVerts];
        memcpy(m_pVertexData, pVertexData, sizeof(T2V3C4Vertex)*oldReserveVerts);
        delete[] pVertexData;
    }
    if (m_NumIndexes >= m_ReserveIndexes-6) {
        bChanged = true;
        int oldReserveIndexes = m_ReserveIndexes;
        m_ReserveIndexes = int(m_ReserveIndexes*1.5);
        if (m_ReserveIndexes < m_NumIndexes) {
            m_ReserveIndexes = m_NumIndexes;
        }
        unsigned int * pIndexData = m_pIndexData;
        m_pIndexData = new unsigned int[m_ReserveIndexes];
        memcpy(m_pIndexData, pIndexData, sizeof(unsigned int)*oldReserveIndexes);
        delete[] pIndexData;
    }
    if (bChanged) {
        m_bDataChanged = true;
    }
}

int VertexData::getNumVerts() const
{
    return m_NumVerts;
}

int VertexData::getNumIndexes() const
{
    return m_NumIndexes;
}

int VertexData::getReserveVerts() const
{
    return m_ReserveVerts;
}

int VertexData::getReserveIndexes() const
{
    return m_ReserveIndexes;
}

const T2V3C4Vertex * VertexData::getVertexPointer() const
{
    return m_pVertexData;
}

const unsigned int * VertexData::getIndexPointer() const
{
    return m_pIndexData;
}

std::ostream& operator<<(std::ostream& os, const T2V3C4Vertex& v)
{
    os << "(" << v.m_Pos[0] << ", " << v.m_Pos[1] << ", " << v.m_Pos[2] << ")";
    return os;
}

}

<commit_msg>Minor optimization.<commit_after>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2011 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  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
//
//  Current versions can be found at www.libavg.de
//

#include "VertexData.h"

#include "GLContext.h"

#include "../base/Exception.h"
#include "../base/WideLine.h"
#include "../base/ObjectCounter.h"

#include <iostream>
#include <stddef.h>
#include <string.h>

using namespace std;
using namespace boost;

namespace avg {

const int MIN_VERTEXES = 100;
const int MIN_INDEXES = 100;

VertexData::VertexData(int reserveVerts, int reserveIndexes)
    : m_NumVerts(0),
      m_NumIndexes(0),
      m_ReserveVerts(reserveVerts),
      m_ReserveIndexes(reserveIndexes),
      m_bDataChanged(true)
{
    ObjectCounter::get()->incRef(&typeid(*this));
    if (m_ReserveVerts < MIN_VERTEXES) {
        m_ReserveVerts = MIN_VERTEXES;
    }
    if (m_ReserveIndexes < MIN_INDEXES) {
        m_ReserveIndexes = MIN_INDEXES;
    }
    m_pVertexData = new T2V3C4Vertex[m_ReserveVerts];
    m_pIndexData = new unsigned int[m_ReserveIndexes];

}

VertexData::~VertexData()
{
    delete[] m_pVertexData;
    delete[] m_pIndexData;
    ObjectCounter::get()->decRef(&typeid(*this));
}

void VertexData::appendPos(const glm::vec2& pos, const glm::vec2& texPos,
        const Pixel32& color)
{
    if (m_NumVerts >= m_ReserveVerts-1) {
        grow();
    }
    T2V3C4Vertex* pVertex = &(m_pVertexData[m_NumVerts]);
    pVertex->m_Pos[0] = (GLfloat)pos.x;
    pVertex->m_Pos[1] = (GLfloat)pos.y;
    pVertex->m_Pos[2] = 0.0;
    pVertex->m_Tex[0] = (GLfloat)texPos.x;
    pVertex->m_Tex[1] = (GLfloat)texPos.y;
    pVertex->m_Color = color;
    m_bDataChanged = true;
    m_NumVerts++;
}

void VertexData::appendTriIndexes(int v0, int v1, int v2)
{
    if (m_NumIndexes >= m_ReserveIndexes-3) {
        grow();
    }
    m_pIndexData[m_NumIndexes] = v0;
    m_pIndexData[m_NumIndexes+1] = v1;
    m_pIndexData[m_NumIndexes+2] = v2;
    m_NumIndexes += 3;
}

void VertexData::appendQuadIndexes(int v0, int v1, int v2, int v3)
{
    if (m_NumIndexes >= m_ReserveIndexes-6) {
        grow();
    }
    m_pIndexData[m_NumIndexes] = v0;
    m_pIndexData[m_NumIndexes+1] = v1;
    m_pIndexData[m_NumIndexes+2] = v2;
    m_pIndexData[m_NumIndexes+3] = v1;
    m_pIndexData[m_NumIndexes+4] = v2;
    m_pIndexData[m_NumIndexes+5] = v3;
    m_NumIndexes += 6;
}

void VertexData::addLineData(Pixel32 color, const glm::vec2& p1, const glm::vec2& p2,
        float width, float tc1, float tc2)
{
    WideLine wl(p1, p2, width);
    int curVertex = getCurVert();
    appendPos(wl.pl0, glm::vec2(tc1, 1), color);
    appendPos(wl.pr0, glm::vec2(tc1, 0), color);
    appendPos(wl.pl1, glm::vec2(tc2, 1), color);
    appendPos(wl.pr1, glm::vec2(tc2, 0), color);
    appendQuadIndexes(curVertex+1, curVertex, curVertex+3, curVertex+2);
}

void VertexData::appendVertexData(VertexDataPtr pVertexes)
{
    int oldNumVerts = m_NumVerts;
    int oldNumIndexes = m_NumIndexes;
    m_NumVerts += pVertexes->getNumVerts();
    m_NumIndexes += pVertexes->getNumIndexes();
    if (m_NumVerts > m_ReserveVerts || m_NumIndexes > m_ReserveIndexes) {
        grow();
    }

    memcpy(&(m_pVertexData[oldNumVerts]), pVertexes->m_pVertexData,
            pVertexes->getNumVerts()*sizeof(T2V3C4Vertex));

    for (int i=0; i<pVertexes->getNumIndexes(); ++i) {
        m_pIndexData[oldNumIndexes+i] = pVertexes->m_pIndexData[i]+oldNumVerts;
    }
    m_bDataChanged = true;
}

bool VertexData::hasDataChanged() const
{
    return m_bDataChanged;
}

void VertexData::resetDataChanged()
{
    m_bDataChanged = false;
}

void VertexData::reset()
{
    m_NumVerts = 0;
    m_NumIndexes = 0;
}

int VertexData::getCurVert() const
{
    return m_NumVerts;
}

int VertexData::getCurIndex() const
{
    return m_NumIndexes;
}

void VertexData::dump() const
{
    cerr << m_NumVerts << " vertexes: ";
    for (int i=0; i<m_NumVerts; ++i) {
        cerr << m_pVertexData[i] << ", ";
    }
    cerr << endl;
    cerr << m_NumIndexes << " indexes: ";
    for (int i=0; i<m_NumIndexes; ++i) {
        cerr << m_pIndexData[i] << " ";
    }
    cerr << endl;
}

void VertexData::grow()
{
    bool bChanged = false;
    if (m_NumVerts >= m_ReserveVerts-1) {
        bChanged = true;
        int oldReserveVerts = m_ReserveVerts;
        m_ReserveVerts = int(m_ReserveVerts*1.5);
        if (m_ReserveVerts < m_NumVerts) {
            m_ReserveVerts = m_NumVerts;
        }
        T2V3C4Vertex* pVertexData = m_pVertexData;
        m_pVertexData = new T2V3C4Vertex[m_ReserveVerts];
        memcpy(m_pVertexData, pVertexData, sizeof(T2V3C4Vertex)*oldReserveVerts);
        delete[] pVertexData;
    }
    if (m_NumIndexes >= m_ReserveIndexes-6) {
        bChanged = true;
        int oldReserveIndexes = m_ReserveIndexes;
        m_ReserveIndexes = int(m_ReserveIndexes*1.5);
        if (m_ReserveIndexes < m_NumIndexes) {
            m_ReserveIndexes = m_NumIndexes;
        }
        unsigned int * pIndexData = m_pIndexData;
        m_pIndexData = new unsigned int[m_ReserveIndexes];
        memcpy(m_pIndexData, pIndexData, sizeof(unsigned int)*oldReserveIndexes);
        delete[] pIndexData;
    }
    if (bChanged) {
        m_bDataChanged = true;
    }
}

int VertexData::getNumVerts() const
{
    return m_NumVerts;
}

int VertexData::getNumIndexes() const
{
    return m_NumIndexes;
}

int VertexData::getReserveVerts() const
{
    return m_ReserveVerts;
}

int VertexData::getReserveIndexes() const
{
    return m_ReserveIndexes;
}

const T2V3C4Vertex * VertexData::getVertexPointer() const
{
    return m_pVertexData;
}

const unsigned int * VertexData::getIndexPointer() const
{
    return m_pIndexData;
}

std::ostream& operator<<(std::ostream& os, const T2V3C4Vertex& v)
{
    os << "(" << v.m_Pos[0] << ", " << v.m_Pos[1] << ", " << v.m_Pos[2] << ")";
    return os;
}

}

<|endoftext|>


<commit_before>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// GRINS - General Reacting Incompressible Navier-Stokes
//
// Copyright (C) 2014 Paul T. Bauman, Roy H. Stogner
// Copyright (C) 2010-2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License 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 Street, Fifth Floor,
// Boston, MA  02110-1301  USA
//
//-----------------------------------------------------------------------el-

// This class
#include "grins/solver_factory.h"

// GRINS
#include "grins/grins_steady_solver.h"
#include "grins/grins_unsteady_solver.h"
#include "grins/steady_mesh_adaptive_solver.h"

// libMesh
#include "libmesh/getpot.h"

namespace GRINS
{
  SolverFactory::SolverFactory()
  {
    return;
  }

  SolverFactory::~SolverFactory()
  {
    return;
  }

  std::tr1::shared_ptr<Solver> SolverFactory::build(const GetPot& input)
  {
    bool mesh_adaptive = input("MeshAdaptivity/mesh_adaptive", false );

    bool transient = input("unsteady-solver/transient", false );

    std::tr1::shared_ptr<Solver> solver;  // Effectively NULL

    if(transient && !mesh_adaptive)
      {
        solver.reset( new UnsteadySolver(input) );
      }
    else if( !transient && !mesh_adaptive )
      {
        solver.reset( new SteadySolver(input) );
      }
    else if( !transient && mesh_adaptive )
      {
        solver.reset( new SteadyMeshAdaptiveSolver(input) );
      }
    else if( transient && mesh_adaptive )
      {
        libmesh_not_implemented();
      }
    else
      {
        std::cerr << "Invalid solver options!" << std::endl;
      }

    return solver;
  }

} // namespace GRINS
<commit_msg>Add displacement solver to solver factory<commit_after>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// GRINS - General Reacting Incompressible Navier-Stokes
//
// Copyright (C) 2014 Paul T. Bauman, Roy H. Stogner
// Copyright (C) 2010-2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License 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 Street, Fifth Floor,
// Boston, MA  02110-1301  USA
//
//-----------------------------------------------------------------------el-

// This class
#include "grins/solver_factory.h"

// GRINS
#include "grins/grins_steady_solver.h"
#include "grins/grins_unsteady_solver.h"
#include "grins/steady_mesh_adaptive_solver.h"
#include "grins/displacement_continuation_solver.h"

// libMesh
#include "libmesh/getpot.h"

namespace GRINS
{
  SolverFactory::SolverFactory()
  {
    return;
  }

  SolverFactory::~SolverFactory()
  {
    return;
  }

  std::tr1::shared_ptr<Solver> SolverFactory::build(const GetPot& input)
  {
    bool mesh_adaptive = input("MeshAdaptivity/mesh_adaptive", false );

    bool transient = input("unsteady-solver/transient", false );

    std::tr1::shared_ptr<Solver> solver;  // Effectively NULL

    std::string solver_type = input("SolverOptions/solver_type", "DIE!");

    if( solver_type == std::string("displacement_continuation") )
      {
        solver.reset( new DisplacementContinuationSolver(input) );
      }
    else if(transient && !mesh_adaptive)
      {
        solver.reset( new UnsteadySolver(input) );
      }
    else if( !transient && !mesh_adaptive )
      {
        solver.reset( new SteadySolver(input) );
      }
    else if( !transient && mesh_adaptive )
      {
        solver.reset( new SteadyMeshAdaptiveSolver(input) );
      }
    else if( transient && mesh_adaptive )
      {
        libmesh_not_implemented();
      }
    else
      {
        std::cerr << "Invalid solver options!" << std::endl;
      }

    return solver;
  }

} // namespace GRINS
<|endoftext|>